use async_std::sync::Arc; use async_executor::Executor; use async_trait::async_trait; use log::debug; use ringbuffer::{RingBufferExt, RingBufferWrite}; use darkfi::{net, Result}; use crate::{ privmsg::{Privmsg, PrivmsgsBuffer, SeenMsgIds}, MAXIMUM_LENGTH_OF_NICKNAME, }; pub struct ProtocolPrivmsg { jobsman: net::ProtocolJobsManagerPtr, notify_queue_sender: async_channel::Sender, msg_sub: net::MessageSubscription, p2p: net::P2pPtr, msg_ids: SeenMsgIds, msgs: PrivmsgsBuffer, channel: net::ChannelPtr, } impl ProtocolPrivmsg { pub async fn init( channel: net::ChannelPtr, notify_queue_sender: async_channel::Sender, p2p: net::P2pPtr, msg_ids: SeenMsgIds, msgs: PrivmsgsBuffer, ) -> net::ProtocolBasePtr { let message_subsytem = channel.get_message_subsystem(); message_subsytem.add_dispatch::().await; let msg_sub = channel.subscribe_msg::().await.expect("Missing Privmsg dispatcher!"); Arc::new(Self { notify_queue_sender, msg_sub, jobsman: net::ProtocolJobsManager::new("ProtocolPrivmsg", channel.clone()), p2p, msg_ids, msgs, channel, }) } async fn handle_receive_msg(self: Arc) -> Result<()> { debug!(target: "ircd", "ProtocolPrivmsg::handle_receive_msg() [START]"); let exclude_list = vec![self.channel.address()]; // once a channel get started let msgs_buffer = self.msgs.lock().await; let msgs = msgs_buffer.to_vec(); drop(msgs_buffer); for m in msgs { self.channel.send(m.clone()).await?; } loop { let msg = self.msg_sub.receive().await?; let mut msg = (*msg).to_owned(); if msg.nickname.len() > MAXIMUM_LENGTH_OF_NICKNAME { msg.nickname = msg.nickname[..MAXIMUM_LENGTH_OF_NICKNAME].to_string(); } if self.msg_ids.lock().await.contains(&msg.id) { continue } self.msg_ids.lock().await.push(msg.id); // add the msg to the buffer self.msgs.lock().await.push(msg.clone()); self.notify_queue_sender.send(msg.clone()).await?; self.p2p.broadcast_with_exclude(msg, &exclude_list).await?; } } } #[async_trait] impl net::ProtocolBase for ProtocolPrivmsg { /// Starts ping-pong keep-alive messages exchange. Runs ping-pong in the /// protocol task manager, then queues the reply. Sends out a ping and /// waits for pong reply. Waits for ping and replies with a pong. async fn start(self: Arc, executor: Arc>) -> Result<()> { debug!(target: "ircd", "ProtocolPrivmsg::start() [START]"); self.jobsman.clone().start(executor.clone()); self.jobsman.clone().spawn(self.clone().handle_receive_msg(), executor.clone()).await; debug!(target: "ircd", "ProtocolPrivmsg::start() [END]"); Ok(()) } fn name(&self) -> &'static str { "ProtocolPrivmsg" } } impl net::Message for Privmsg { fn name() -> &'static str { "privmsg" } }