diff --git a/src/bot/bot_handler.rs b/src/bot/bot_handler.rs index bc4801a..5265c61 100644 --- a/src/bot/bot_handler.rs +++ b/src/bot/bot_handler.rs @@ -1,33 +1,57 @@ use crate::bot::define::{AttendanceBot, MessageEnum}; -use anyhow::Ok; -use anyhow::Result; -use matrix_sdk::async_trait; +use anyhow::{Result, anyhow}; +use async_trait::async_trait; +use std::sync::{Mutex, OnceLock}; use tokio::sync::mpsc; use tokio::task::JoinHandle; -pub struct Bot { - pub messages_receiver: mpsc::Receiver, - pub message_sender: mpsc::Sender, + +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 Bot; + impl Bot { - fn new() -> Self { - let (tx, rx) = mpsc::channel(100); - Self { - messages_receiver: rx, - message_sender: tx, - } + pub fn new() -> Self { + Self + } + + pub fn global_sender() -> MessageTx { + global_channel().0.clone() } } #[async_trait] impl AttendanceBot for Bot { async fn handle_commands(&self) -> Result> { - let bot = Bot::new(); - let (_tx, mut rx) = (bot.message_sender, bot.messages_receiver); + 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 handle = tokio::spawn(async move { - while let Some(msg) = rx.blocking_recv() { + while let Some(msg) = rx.recv().await { match msg { - _ => {} + MessageEnum::StopMessage => break, + MessageEnum::MatrixMessage(_msg) => { + // TODO: route matrix message to command processor. + } + MessageEnum::TelegramMessage(_msg) => { + // TODO: route telegram message to command processor. + } } } }); diff --git a/src/bot/define.rs b/src/bot/define.rs index bca9907..4496c50 100644 --- a/src/bot/define.rs +++ b/src/bot/define.rs @@ -10,7 +10,6 @@ pub trait Sender { #[async_trait] pub trait Receiver { - // Pull user inputs from upstream and return a cursor for incremental sync. async fn recv(&self, msg: InboundMessage) -> Result<()>; } @@ -46,4 +45,3 @@ pub enum MessageEnum { TelegramMessage(InboundMessage), StopMessage, } -