use crate::bot::command_parser::parse_command; use crate::bot::define::{AttendanceHandler, Bot, InboundMessage, MessageEnum, OutboundMessage}; use crate::bot::filters::support_chinese_command; use crate::db::crud_handler; use anyhow::{Result, anyhow}; use async_trait::async_trait; use std::path::Path; use std::sync::{Arc, Mutex, OnceLock}; use tokio::sync::mpsc; use tokio::task::JoinHandle; type MessageTx = mpsc::Sender; type MessageRx = mpsc::Receiver; static GLOBAL_CHANNEL: OnceLock<(MessageTx, Mutex>)> = OnceLock::new(); fn global_channel() -> &'static (MessageTx, Mutex>) { GLOBAL_CHANNEL.get_or_init(|| { let (tx, rx) = mpsc::channel(100); (tx, Mutex::new(Some(rx))) }) } pub struct ChannelManager { tx: MessageTx, rx: &'static Mutex>, filters: Option InboundMessage + Send + Sync>>>, } //channel的包装,提供过滤功能,后续可以考虑增加更多功能,比如广播等 impl ChannelManager { pub fn new() -> Self { let (tx, rx) = global_channel(); let mut _self = Self { tx: tx.clone(), rx, filters: None, }; _self.reg_filters(); _self } fn filter_message(&self, msg: &InboundMessage) -> InboundMessage { let mut result_msg = msg.clone(); if let Some(filters) = &self.filters { for filter in filters { result_msg = filter(&result_msg); } } result_msg } fn reg_filters(&mut self) { let cn_filter = Box::new(support_chinese_command) as Box InboundMessage + Send + Sync>; self.filters.get_or_insert_with(Vec::new).push(cn_filter); //后续可以考虑增加更多过滤器 } //这里先过滤,在发送,后续可以考虑在接收时过滤 pub async fn send(&self, value: MessageEnum) -> Result<()> { let tx = self.tx.clone(); if let MessageEnum::MatrixMessage(inbound_msg) = value { let filtered_msg = self.filter_message(&inbound_msg); tx.send(MessageEnum::MatrixMessage(filtered_msg)).await?; } else { tx.send(value).await?; } Ok(()) } pub fn get_receiver(&self) -> Option { self.rx.lock().unwrap().take() } } type SharedBot = Arc; pub struct CommandHandler { bot: SharedBot, } impl CommandHandler { pub fn new(bot: SharedBot) -> Self { Self { bot } } pub fn global_sender() -> MessageTx { global_channel().0.clone() } } async fn start_bot_command_processor( bot: &(dyn Bot + Send + Sync), inbound: &InboundMessage, command_text: &str, ) -> Result<()> { let ast = parse_command(command_text)?; let command = ast.command.as_str(); match command { "echo" => { let text = ast.arguments.join(" "); let outbound = OutboundMessage { channel_id: inbound.channel_id.clone(), text, reply_to_event_id: Some(inbound.event_id.clone()), }; bot.send_raw_message(&outbound.channel_id, &outbound) .await?; } "ping" => { let outbound = OutboundMessage { channel_id: inbound.channel_id.clone(), text: "pong".to_string(), reply_to_event_id: Some(inbound.event_id.clone()), }; bot.send_raw_message(&outbound.channel_id, &outbound) .await?; } "checkin" => { let crud_handler = crud_handler::CrudHandler::new(crate::db::sled_db::SledDB::new( Path::new("daily_state.sled.db"), )?); crud_handler.checkin(&inbound.user_id).await?; let outbound = OutboundMessage { channel_id: inbound.channel_id.clone(), text: format!(" {} 已签到成功", inbound.user_id), reply_to_event_id: Some(inbound.event_id.clone()), }; bot.send_raw_message(&outbound.channel_id, &outbound) .await?; } "test_report" => {} _ => { return Err(anyhow!("unknown command: {}", command)); } } let arguments = ast.arguments; let options = ast.options; for argument in arguments { log::trace!("Argument: {}", argument); } for (k, v) in options { log::trace!("Option: {}={}", k, v); } Ok(()) } #[async_trait] impl AttendanceHandler for CommandHandler { async fn handle_commands(&self) -> Result> { let rx = { let (_tx, rx_slot) = global_channel(); rx_slot .lock() .map_err(|_| anyhow!("global receiver lock poisoned"))? .take() .ok_or_else(|| anyhow!("global receiver has already been taken"))? }; let mut rx = rx; let bot = Arc::clone(&self.bot); let handle: JoinHandle<()> = tokio::spawn(async move { while let Some(msg) = rx.recv().await { match msg { MessageEnum::StopMessage => break, MessageEnum::MatrixMessage(msg) => { let text: &str = msg.text.trim(); log::info!( "Received Matrix message (event_id={}, channel_id={}, user_id={}): {}", msg.event_id, msg.channel_id, msg.user_id, msg.text ); let Some(command_text) = text.strip_prefix('!') else { continue; }; if let Err(err) = start_bot_command_processor(bot.as_ref(), &msg, command_text).await { log::warn!( "failed to process matrix command (event_id={}, channel_id={}): {}", msg.event_id, msg.channel_id, err ); } } MessageEnum::TelegramMessage(msg) => { let text = msg.text.trim(); let Some(command_text) = text.strip_prefix('/') else { continue; }; if let Err(err) = start_bot_command_processor(bot.as_ref(), &msg, command_text).await { log::warn!( "failed to process telegram command (event_id={}, channel_id={}): {}", msg.event_id, msg.channel_id, err ); } } } } }); Ok(handle) } } #[cfg(test)] mod tests { use super::start_bot_command_processor; use crate::bot::define::{Bot, InboundMessage, OutboundMessage}; use anyhow::{Ok, Result}; use async_trait::async_trait; use std::sync::Mutex; #[derive(Default)] struct MockBot { sent: Mutex>, } impl MockBot { fn sent_messages(&self) -> Vec<(String, OutboundMessage)> { self.sent.lock().expect("mock sent lock poisoned").clone() } } #[async_trait] impl Bot for MockBot { async fn start(&self) -> Result<()> { Ok(()) } async fn get_users_who_unchecked_for_long_time( &self, ) -> Result)>> { Ok(vec![("@user1:example.org".to_string(), Some(100))]) } async fn join_rooms(&self) -> Result<()> { Ok(()) } async fn get_users_count(&self, _room_id: &str) -> Result { return Ok(100); } async fn send_raw_message( &self, room_id: &str, message: &OutboundMessage, ) -> Result { self.sent .lock() .expect("mock sent lock poisoned") .push((room_id.to_string(), message.clone())); Ok("mock_event_id".to_string()) } } fn make_inbound(text: &str) -> InboundMessage { InboundMessage { event_id: "$event_1".to_string(), channel_id: "!room:example.org".to_string(), user_id: "@alice:example.org".to_string(), text: text.to_string(), timestamp_ms: 1, } } #[tokio::test] async fn processor_ping_sends_pong_to_source_channel() { let bot = MockBot::default(); let inbound = make_inbound("!ping"); let result = start_bot_command_processor(&bot, &inbound, "ping").await; assert!(result.is_ok()); let sent = bot.sent_messages(); assert_eq!(sent.len(), 1); assert_eq!(sent[0].0, "!room:example.org"); assert_eq!(sent[0].1.channel_id, "!room:example.org"); assert_eq!(sent[0].1.text, "pong"); assert_eq!(sent[0].1.reply_to_event_id.as_deref(), Some("$event_1")); } #[tokio::test] async fn processor_echo_sends_joined_arguments_to_source_channel() { let bot = MockBot::default(); let inbound = make_inbound("!echo hello world"); let result = start_bot_command_processor(&bot, &inbound, "echo hello world").await; assert!(result.is_ok()); let sent = bot.sent_messages(); assert_eq!(sent.len(), 1); assert_eq!(sent[0].1.text, "hello world"); assert_eq!(sent[0].1.channel_id, "!room:example.org"); assert_eq!(sent[0].1.reply_to_event_id.as_deref(), Some("$event_1")); } #[tokio::test] async fn processor_unknown_command_returns_error_and_sends_nothing() { let bot = MockBot::default(); let inbound = make_inbound("!doesnotexist"); let result = start_bot_command_processor(&bot, &inbound, "doesnotexist").await; assert!(result.is_err()); assert_eq!(bot.sent_messages().len(), 0); } }