DEVELOPMENT ENVIRONMENT

~liljamo/canwa

ref: 45439cc45439d0050fb8dd130f48993bba82574f canwa/src/service/matrix.rs -rw-r--r-- 1.9 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
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
/*
 * 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 async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::json;

use crate::config::ServiceConfig;

use super::Service;

#[derive(Clone, Deserialize, Serialize)]
pub struct MatrixConfig {
    pub instance: String,
    pub token: String,
    pub room: String,
}

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

pub struct MatrixService {
    client: reqwest::Client,
    config: MatrixConfig,
}

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

    fn gen_txn_id(&self) -> String {
        format!(
            "{}_{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or(std::time::Duration::new(0, 0))
                .as_nanos()
        )
    }
}

#[async_trait]
impl Service for MatrixService {
    async fn send(&self, title: &str, message: &str) -> Result<(), Box<dyn std::error::Error>> {
        let body = json!({
            "msgtype": "m.notice",
            "body": format!("**{}**\n\n{}", title, message),
            "format": "org.matrix.custom.html",
            "formatted_body": format!("<p><strong>{}</strong></p>\n<p>{}</p>\n", title, message),
        });
        let _ = self
            .client
            .put(format!(
                "{}/_matrix/client/v3/rooms/{}/send/m.room.message/{}",
                self.config.instance,
                self.config.room,
                self.gen_txn_id()
            ))
            .query(&[("access_token", &self.config.token)])
            .body(body.to_string())
            .send()
            .await?;
        Ok(())
    }
}