protocol_privmsg.rs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. use async_std::sync::Mutex;
  2. use std::{
  3. sync::Arc,
  4. collections::HashSet,
  5. };
  6. use log::debug;
  7. use async_executor::Executor;
  8. use drk::{
  9. net, Result,
  10. };
  11. use crate::privmsg::{PrivMsgId, PrivMsg};
  12. pub struct ProtocolPrivMsg {
  13. notify_queue_sender: async_channel::Sender<Arc<PrivMsg>>,
  14. privmsg_sub: net::MessageSubscription<PrivMsg>,
  15. jobsman: net::ProtocolJobsManagerPtr,
  16. privmsg_ids: Mutex<HashSet<PrivMsgId>>,
  17. p2p: net::P2pPtr,
  18. }
  19. impl ProtocolPrivMsg {
  20. pub async fn new(
  21. channel: net::ChannelPtr,
  22. notify_queue_sender: async_channel::Sender<Arc<PrivMsg>>,
  23. p2p: net::P2pPtr,
  24. ) -> Arc<Self> {
  25. let message_subsytem = channel.get_message_subsystem();
  26. message_subsytem.add_dispatch::<PrivMsg>().await;
  27. debug!("ADDED DISPATCH");
  28. let privmsg_sub =
  29. channel.subscribe_msg::<PrivMsg>().await.expect("Missing PrivMsg dispatcher!");
  30. Arc::new(Self {
  31. notify_queue_sender,
  32. privmsg_sub,
  33. jobsman: net::ProtocolJobsManager::new("PrivMsgProtocol", channel),
  34. privmsg_ids: Mutex::new(HashSet::new()),
  35. p2p,
  36. })
  37. }
  38. pub async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) {
  39. debug!(target: "ircd", "ProtocolPrivMsg::start() [START]");
  40. self.jobsman.clone().start(executor.clone());
  41. self.jobsman.clone().spawn(self.clone().handle_receive_privmsg(), executor.clone()).await;
  42. debug!(target: "ircd", "ProtocolPrivMsg::start() [END]");
  43. }
  44. async fn handle_receive_privmsg(self: Arc<Self>) -> Result<()> {
  45. debug!(target: "ircd", "ProtocolAddress::handle_receive_privmsg() [START]");
  46. loop {
  47. let privmsg = self.privmsg_sub.receive().await?;
  48. debug!(
  49. target: "ircd",
  50. "ProtocolPrivMsg::handle_receive_privmsg() received {:?}",
  51. privmsg
  52. );
  53. // Do we already have this message?
  54. if self.privmsg_ids.lock().await.contains(&privmsg.id) {
  55. continue
  56. }
  57. // If not then broadcast to everybody else
  58. // First update list of privmsg ids
  59. self.privmsg_ids.lock().await.insert(privmsg.id);
  60. let privmsg_copy = (*privmsg).clone();
  61. self.p2p.broadcast(privmsg_copy).await?;
  62. self.notify_queue_sender.send(privmsg).await.expect("notify_queue_sender send failed!");
  63. }
  64. }
  65. }