yt_sub_core/
user_settings.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
use serde::{Deserialize, Serialize};
use std::{
    fmt::{self, Display, Formatter},
    path::PathBuf,
};

use crate::{channel::Channel, notifier::Notifier};

pub const API_HOST: &str = "https://frog02-20771.wykr.es";

#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct UserSettings {
    pub channels: Vec<Channel>,
    pub notifiers: Vec<Notifier>,
    pub api_key: Option<String>,
    #[serde(skip_serializing, skip_deserializing)]
    pub path: PathBuf,
    pub schedule: Option<Vec<u32>>,
}

impl Display for UserSettings {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let toml_file = toml::to_string(self).expect("Failed to serialize TOML");
        write!(f, "{}\n\n{}", self.path.display(), toml_file)
    }
}

impl UserSettings {
    pub fn default(path: PathBuf) -> Self {
        Self {
            path,
            notifiers: vec![Notifier::default()],
            channels: vec![],
            api_key: None,
            schedule: None,
        }
    }

    pub fn get_channel_by_id(&self, channel_id: &str) -> Option<Channel> {
        self.channels
            .iter()
            .find(|channel| channel.channel_id == channel_id)
            .cloned()
    }

    pub fn get_channel_by_handle(&self, handle: &str) -> Option<Channel> {
        self.channels
            .iter()
            .find(|channel| channel.handle == handle)
            .cloned()
    }

    pub fn get_slack_notifier(&self) -> Option<&Notifier> {
        self.notifiers.iter().find(|n| n.is_slack())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use eyre::Result;
    #[tokio::test]
    async fn test_json_serialize() -> Result<()> {
        let setting = UserSettings::default(PathBuf::from("test.toml"));
        let json = serde_json::to_string(&setting)?;

        let _setting: UserSettings = serde_json::from_str(&json)?;

        Ok(())
    }
}