DEVELOPMENT ENVIRONMENT

~liljamo/canwa

ref: 45439cc45439d0050fb8dd130f48993bba82574f canwa/src/state.rs -rw-r--r-- 1.3 KiB
45439cc4Jonni Liljamo feat: initial version 27 days ago
                                                                                
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
/*
 * Copyright (C) 2025 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under GPL-3.0-or-later, see NOTICE and LICENSE for
 * more information.
 */

use std::{collections::HashMap, sync::Arc};

use crate::{
    config::{Config, NotifierConfig},
    service::{self, Service},
};

static USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));

#[derive(Clone)]
pub struct State {
    _client: reqwest::Client,
    pub services: Arc<HashMap<String, Box<dyn Service + Send + Sync>>>,
    pub notifiers: HashMap<String, NotifierConfig>,
}

impl State {
    pub fn from_config(config: &Config) -> Result<Self, Box<dyn std::error::Error>> {
        let client: reqwest::Client = reqwest::ClientBuilder::new()
            .user_agent(USER_AGENT)
            .build()?;
        let mut services: HashMap<String, Box<dyn Service + Send + Sync>> = HashMap::new();

        for (id, service_config) in &config.services {
            let service: Box<dyn Service + Send + Sync> =
                service::build(client.clone(), &*(*service_config));
            services.insert(id.clone(), service);
        }

        Ok(Self {
            _client: client,
            services: Arc::new(services),
            notifiers: config.notifiers.clone(),
        })
    }
}