protocol_privmsg.rs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. use async_executor::Executor;
  2. use async_std::sync::{Arc, Mutex};
  3. use async_trait::async_trait;
  4. use log::debug;
  5. use darkfi::{
  6. net,
  7. serial::{SerialDecodable, SerialEncodable},
  8. Result,
  9. };
  10. use crate::{buffers::SeenIds, Privmsg};
  11. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  12. struct InvObject(String);
  13. pub struct ProtocolPrivmsg {
  14. jobsman: net::ProtocolJobsManagerPtr,
  15. notify: async_channel::Sender<Privmsg>,
  16. msg_sub: net::MessageSubscription<Privmsg>,
  17. p2p: net::P2pPtr,
  18. channel: net::ChannelPtr,
  19. seen: Arc<Mutex<SeenIds>>,
  20. }
  21. impl ProtocolPrivmsg {
  22. pub async fn init(
  23. channel: net::ChannelPtr,
  24. notify: async_channel::Sender<Privmsg>,
  25. p2p: net::P2pPtr,
  26. seen: Arc<Mutex<SeenIds>>,
  27. ) -> net::ProtocolBasePtr {
  28. let message_subsytem = channel.get_message_subsystem();
  29. message_subsytem.add_dispatch::<Privmsg>().await;
  30. let msg_sub =
  31. channel.clone().subscribe_msg::<Privmsg>().await.expect("Missing Privmsg dispatcher!");
  32. Arc::new(Self {
  33. notify,
  34. msg_sub,
  35. jobsman: net::ProtocolJobsManager::new("ProtocolPrivmsg", channel.clone()),
  36. p2p,
  37. channel,
  38. seen,
  39. })
  40. }
  41. async fn handle_receive_msg(self: Arc<Self>) -> Result<()> {
  42. debug!(target: "ircd", "ProtocolPrivmsg::handle_receive_msg() [START]");
  43. let exclude_list = vec![self.channel.address()];
  44. loop {
  45. let msg = self.msg_sub.receive().await?;
  46. let msg = (*msg).to_owned();
  47. {
  48. let ids = &mut self.seen.lock().await;
  49. if !ids.push(msg.id) {
  50. continue
  51. }
  52. }
  53. self.notify.send(msg.clone()).await?;
  54. self.p2p.broadcast_with_exclude(msg, &exclude_list).await?;
  55. }
  56. }
  57. }
  58. #[async_trait]
  59. impl net::ProtocolBase for ProtocolPrivmsg {
  60. /// Starts ping-pong keep-alive messages exchange. Runs ping-pong in the
  61. /// protocol task manager, then queues the reply. Sends out a ping and
  62. /// waits for pong reply. Waits for ping and replies with a pong.
  63. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  64. debug!(target: "ircd", "ProtocolPrivmsg::start() [START]");
  65. self.jobsman.clone().start(executor.clone());
  66. self.jobsman.clone().spawn(self.clone().handle_receive_msg(), executor.clone()).await;
  67. debug!(target: "ircd", "ProtocolPrivmsg::start() [END]");
  68. Ok(())
  69. }
  70. fn name(&self) -> &'static str {
  71. "ProtocolPrivmsg"
  72. }
  73. }
  74. impl net::Message for Privmsg {
  75. fn name() -> &'static str {
  76. "privmsg"
  77. }
  78. }