protocol_privmsg.rs 2.6 KB

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