Skip to main content

rustango_cms/notify/channels/
slack.rs

1//! Slack — incoming webhook.
2
3use crate::notify::{ConfigField, DeliverError, Delivery, Notification, NotificationChannel};
4use serde_json::json;
5
6/// Posts to a Slack incoming webhook using Block Kit, so fields render as
7/// a readable list rather than one run-on line.
8#[derive(Default)]
9pub struct SlackChannel;
10
11#[async_trait::async_trait]
12impl NotificationChannel for SlackChannel {
13    fn kind(&self) -> &'static str {
14        "slack"
15    }
16    fn label(&self) -> &'static str {
17        "Slack"
18    }
19    fn help(&self) -> &'static str {
20        "Create an Incoming Webhook in your Slack app settings and paste its URL."
21    }
22    fn config_fields(&self) -> Vec<ConfigField> {
23        vec![ConfigField {
24            name: "webhook_url",
25            label: "Webhook URL",
26            help: "https://hooks.slack.com/services/…",
27            // The URL *is* the credential — anyone holding it can post to
28            // the channel — so it lives in the encrypted column.
29            secret: true,
30            required: true,
31        }]
32    }
33
34    async fn deliver(&self, d: &Delivery<'_>, msg: &Notification) -> Result<(), DeliverError> {
35        if d.secret.is_empty() {
36            return Err(DeliverError::Permanent("no webhook URL set".to_owned()));
37        }
38        let mut blocks = vec![json!({
39            "type": "header",
40            "text": { "type": "plain_text", "text": truncate(&msg.title, 150), "emoji": true }
41        })];
42        if !msg.summary.is_empty() {
43            blocks.push(json!({
44                "type": "section",
45                "text": { "type": "mrkdwn", "text": truncate(&msg.summary, 2900) }
46            }));
47        }
48        // Slack caps a section at 10 fields; chunk rather than truncate so
49        // a long form still delivers every answer.
50        for chunk in msg.fields.chunks(10) {
51            blocks.push(json!({
52                "type": "section",
53                "fields": chunk.iter().map(|(k, v)| json!({
54                    "type": "mrkdwn",
55                    "text": format!("*{}*\n{}", escape(k), escape(&truncate(v, 1900))),
56                })).collect::<Vec<_>>(),
57            }));
58        }
59        if !msg.url.is_empty() {
60            blocks.push(json!({
61                "type": "actions",
62                "elements": [{
63                    "type": "button",
64                    "text": { "type": "plain_text", "text": "Open" },
65                    "url": msg.url,
66                }],
67            }));
68        }
69        let payload = json!({ "text": msg.title, "blocks": blocks });
70        post_json(d.secret, &payload).await
71    }
72}
73
74/// Slack's mrkdwn needs only these three escaped.
75fn escape(s: &str) -> String {
76    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
77}
78
79pub(crate) fn truncate(s: &str, max: usize) -> String {
80    if s.chars().count() <= max {
81        return s.to_owned();
82    }
83    s.chars().take(max.saturating_sub(1)).collect::<String>() + "…"
84}
85
86/// Shared by Slack + Teams + generic webhook: POST JSON, classify status.
87pub(crate) async fn post_json(
88    url: &str,
89    payload: &serde_json::Value,
90) -> Result<(), DeliverError> {
91    let resp = super::client_for(url).await?
92        .post(url)
93        .json(payload)
94        .map_err(|e| DeliverError::Permanent(format!("encode: {e}")))?
95        .send()
96        .await
97        // A DNS blip or refused connection is exactly what the outbox is
98        // for; never permanent.
99        .map_err(|e| DeliverError::Transient(e.to_string()))?;
100    let status = resp.status().as_u16();
101    if (200..300).contains(&status) {
102        return Ok(());
103    }
104    let body = resp.text().await.unwrap_or_default();
105    Err(super::classify(status, &body))
106}
107
108crate::register_notification_channel!(SlackChannel);