Skip to main content

server_watchdog/application/handler/
general.rs

1use async_trait::async_trait;
2use derive_new::new;
3use log::{debug, trace};
4use crate::application::client::MessageGateway;
5use crate::application::config::{AuthUseCase, EventConfigUseCase, EventSubscribeUseCase};
6use crate::application::handler::command::{Command, Run};
7use crate::application::handler::MessageHandler;
8use crate::application::server::ServerManager;
9use crate::domain::client::Message;
10
11use std::sync::Arc;
12
13#[derive(new)]
14pub struct GeneralHandler {
15    pub message_gateway: Arc<dyn MessageGateway>,
16    pub server_manager: Arc<dyn ServerManager>,
17    pub auth_use_case: Box<dyn AuthUseCase>,
18    pub event_subscribe_use_case: Arc<dyn EventSubscribeUseCase>,
19    pub event_config_use_case: Arc<dyn EventConfigUseCase>,
20}
21
22#[async_trait]
23impl MessageHandler for GeneralHandler {
24    async fn handle(&mut self, message: Message) {
25        match message.data.split_whitespace().collect::<Vec<_>>()[..] {
26            ["/register", password] => {
27                let response = if !self.auth_use_case.password_required() {
28                        String::from("Password is not required")
29                } else if self.auth_use_case.validate_password(password.to_string()).await {
30                    match self.auth_use_case.register(message.client_name.clone(), message.chat_id.clone()).await {
31                        Ok(_) => String::from("Successfully registered."),
32                        Err(e) => format!("Fail to register: {e}")
33                    }
34
35                } else {
36                    String::from("Invalid password. Usage: /register <password>")
37                };
38                self.message_gateway.send_message(
39                    message.client_name.as_str(),
40                    message.chat_id.as_str(),
41                    response.as_str()
42                )
43                    .await
44            },
45            _ => {
46                let auth_id = self.auth_use_case
47                    .authenticate(message.client_name.clone(), message.chat_id.clone())
48                    .await;
49                if let Some(id) = auth_id {
50                    self._handle(String::from(id), message).await
51                } else {
52                    self.message_gateway.send_message(
53                        message.client_name.as_str(),
54                        message.chat_id.as_str(),
55                        "Registration required. Usage: /register <password>"
56                    )
57                        .await
58                }
59            }
60        }
61    }
62}
63impl GeneralHandler {
64
65    async fn _handle(&mut self, id: String, message: Message) {
66        trace!("GeneralHandler::handle");
67        debug!("handling message: {:?}", &message);
68
69        let command = Command::parse(message.data.as_str());
70        debug!("parsed command: {:?}", &command);
71
72        let response = command.run(self, id, &message).await;
73        debug!("response: {:?}", &response);
74
75        let response = response.unwrap_or_else(|e| format!("[Err] {e}"));
76
77        self.message_gateway
78            .send_message(
79                message.client_name.as_str(),
80                message.chat_id.as_str(),
81                response.as_str()
82            )
83            .await;
84    }
85}