summaryrefslogtreecommitdiff
path: root/src/web.rs
blob: 9ec73fda0e3537fa675e3d5da72290fbf7c11b6f (plain)
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
use std::fmt;
use std::fmt::Formatter;

use serde_derive::{Deserialize, Serialize};
use teloxide::{prelude2::*};
use tracing::{debug, error, info, warn};
use warp::{Rejection, Reply};

use crate::{Bot, database, DbPool};

#[derive(Deserialize, Serialize)]
pub struct SendMessage {
    token: String,
    message: String,
}

impl fmt::Display for SendMessage {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "SendMessage {{ token={}, message={} }}", self.token, self.message)
    }
}

#[derive(Deserialize, Serialize)]
pub struct SendMessageResponse {
    success: bool,
    message: String,
}

impl fmt::Display for SendMessageResponse {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "SendMessageResponse {{ success={}, message={} }}", self.success, self.message)
    }
}

pub async fn handler(req: SendMessage, db: DbPool, bot: Bot)
                     -> std::result::Result<impl Reply, Rejection> {
    info!("Income API request: {}", req);
    let user =
        database::get_user_by_token(&db, req.token.as_str()).await;
    let response = match user {
        Ok(u) => match u {
            Some(user) => {
                info!("Send message to user {}.", user);
                let bot = bot.auto_send();
                match bot.send_message(user.chat_id as i64, req.message).await {
                    Ok(_) => SendMessageResponse {
                        success: true,
                        message: String::new(),
                    },
                    Err(why) => {
                        error!("Failed to send message to telegram: {:?}", why);
                        SendMessageResponse {
                            success: false,
                            message: String::from("Failed to send message to telegram."),
                        }
                    }
                }
            }
            None => {
                warn!("Invalid token: {}.", req);
                SendMessageResponse {
                    success: false,
                    message: String::from("Invalid token."),
                }
            }
        },
        Err(err) => {
            error!("Error when querying the database: {:?}.", err);
            SendMessageResponse {
                success: false,
                message: String::from("Invalid parameter."),
            }
        }
    };
    debug!("Response: {}", response);
    Ok(warp::reply::json(&response))
}