yt_sub/
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
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)]
pub enum Notifier {
    Log(LogConfig),
    Slack(SlackConfig),
    Telegram,
}

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

#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct LogConfig {
    notify: bool,
}

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

impl Notifier {
    pub async fn notify(&self, messages: Vec<String>, cron: bool) -> Result<()> {
        match self {
            Notifier::Log(log_config) => {
                if !log_config.notify {
                    return Ok(());
                }

                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!(),
        }
    }
}

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 _ = client.post(&config.webhook_url).json(&payload).send().await;

    Ok(())
}