DEVELOPMENT ENVIRONMENT

~liljamo/canwa

ref: a05128d215529422a7424f1265f53010620ace59 canwa/src/service/gotify.rs -rw-r--r-- 1.8 KiB
a05128d2Jonni Liljamo feat: alertmanager webhook route 10 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
81
82
83
84
85
86
/*
 * 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::{
    config::{ServiceConfig, deserialize_token},
    routes::message::MessageForm,
};

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,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        Ok(Self { client, config })
    }
}

#[async_trait]
impl Service for GotifyService {
    async fn send(
        &self,
        form: &MessageForm,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        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();
    }
}