DEVELOPMENT ENVIRONMENT

~liljamo/canwa

ref: 9621cd5d4e6923d4fd326a3bf31ffa1bd457a196 canwa/src/routes/message.rs -rw-r--r-- 1.6 KiB
9621cd5dJonni Liljamo feat: separate routes to module 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
/*
 * 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 std::sync::Arc;

use axum::{Json, http::HeaderMap, response::IntoResponse};
use reqwest::StatusCode;
use serde::Deserialize;
use tracing::{error, info};

use crate::state::State;

#[derive(Deserialize)]
pub struct MessageForm {
    pub title: String,
    pub message: String,
    #[serde(default)]
    pub format_commonmark: bool,
}

pub async fn message(
    state: Arc<State>,
    headers: HeaderMap,
    Json(message): Json<MessageForm>,
) -> impl IntoResponse {
    let token = match headers.get("Authorization") {
        Some(token) => match token.to_str() {
            Ok(token) => token,
            Err(_) => {
                return (StatusCode::UNAUTHORIZED, "unauthorized");
            }
        },
        None => {
            return (StatusCode::UNAUTHORIZED, "unauthorized");
        }
    };

    let notifier = match state.notifiers.iter().find(|(_k, v)| v.token == token) {
        Some(n) => n,
        None => return (StatusCode::UNAUTHORIZED, "unauthorized"),
    };

    info!(msg = "message", notifier = notifier.0);

    for (_k, v) in state
        .services
        .iter()
        .filter(|(k, _v)| notifier.1.services.contains(k))
    {
        match v.send(&message).await {
            Ok(_) => {}
            Err(err) => {
                error!(msg = "message sending failed", ?err);
                return (StatusCode::INTERNAL_SERVER_ERROR, "failed to send message");
            }
        }
    }

    (StatusCode::OK, "")
}