DEVELOPMENT ENVIRONMENT

~liljamo/canwa

ref: 19620a3f42c717840fd79edda342616159b0f6ff canwa/src/service/gotify.rs -rw-r--r-- 1.7 KiB
19620a3fJonni Liljamo feat: per service config tests 17 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
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
75
76
77
78
79
80
/*
 * Copyright (C) 2025 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under AGPL-3.0-or-later, see NOTICE and LICENSE for
 * more information.
 */

use async_trait::async_trait;
use serde::{Deserialize, Serialize};

use crate::{
    MessageForm,
    config::{ServiceConfig, deserialize_token},
};

use super::Service;

#[derive(Clone, Deserialize, Serialize)]
pub struct GotifyConfig {
    pub instance: String,
    #[serde(deserialize_with = "deserialize_token")]
    pub token: String,
}

#[typetag::serde(name = "gotify")]
impl ServiceConfig for GotifyConfig {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

pub struct GotifyService {
    client: reqwest::Client,
    config: GotifyConfig,
}

impl GotifyService {
    pub fn new(client: reqwest::Client, config: GotifyConfig) -> Self {
        Self { client, config }
    }
}

#[async_trait]
impl Service for GotifyService {
    async fn send(&self, form: &MessageForm) -> Result<(), Box<dyn std::error::Error>> {
        let _ = self
            .client
            .post(format!("{}/message", self.config.instance))
            .query(&[("token", &self.config.token)])
            .form(&[("title", &form.title), ("message", &form.message)])
            .send()
            .await?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::config::Config;

    use super::*;

    #[tokio::test]
    async fn config() {
        Config::from_str(
            r#"
        [services.g]
        type = "gotify"
        instance = "gotify.tld"
        token = "secret"
        "#,
        )
        .await
        .unwrap()
        .services["g"]
            .as_any()
            .downcast_ref::<GotifyConfig>()
            .unwrap();
    }
}