yt_sub_core/
notifier.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use eyre::Result;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::json;

use crate::logger::Logger;

#[non_exhaustive]
#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
pub enum Notifier {
    Log(),
    Slack(SlackConfig),
    Telegram,
}

impl Default for Notifier {
    fn default() -> Self {
        Self::Log()
    }
}

#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
pub struct SlackConfig {
    pub webhook_url: String,
    pub channel: String,
}

impl Notifier {
    pub async fn notify(&self, messages: Vec<String>, cron: bool) -> Result<()> {
        match self {
            Notifier::Log() => {
                let logger = Logger::new(cron);
                for message in messages {
                    logger.info(&message);
                }
                Ok(())
            }
            Notifier::Slack(slack_config) => {
                notify_slack(&messages.join("\n\n"), slack_config).await?;
                Ok(())
            }
            Notifier::Telegram => todo!(),
        }
    }

    pub fn is_slack(&self) -> bool {
        matches!(self, Notifier::Slack(_))
    }
}

async fn notify_slack(message: &str, config: &SlackConfig) -> Result<()> {
    let client = Client::new();

    let payload = json!({
        "channel": config.channel,
        "icon_emoji": ":exclamation:",
        "username": "yt-sub-rs",
        "text": message,
        "unfurl_links": false,
    });

    let res = client
        .post(&config.webhook_url)
        .json(&payload)
        .send()
        .await?;

    if res.status() == 200 {
        return Ok(());
    }

    let err_msg = res.text().await?;
    eyre::bail!("Failed to send message to Slack: {err_msg}");
}