1use async_trait::async_trait;
21use darkfi::{net, Result};
22use log::debug;
23use smol::Executor;
24use std::sync::Arc;
25
26use crate::dchatmsg::{DchatMsg, DchatMsgsBuffer};
27
28pub struct ProtocolDchat {
29 jobsman: net::ProtocolJobsManagerPtr,
30 msg_sub: net::MessageSubscription<DchatMsg>,
31 msgs: DchatMsgsBuffer,
32}
33impl ProtocolDchat {
37 pub async fn init(channel: net::ChannelPtr, msgs: DchatMsgsBuffer) -> net::ProtocolBasePtr {
38 debug!(target: "dchat", "ProtocolDchat::init() [START]");
39 let message_subsytem = channel.message_subsystem();
40 message_subsytem.add_dispatch::<DchatMsg>().await;
41
42 let msg_sub =
43 channel.subscribe_msg::<DchatMsg>().await.expect("Missing DchatMsg dispatcher!");
44
45 Arc::new(Self {
46 jobsman: net::ProtocolJobsManager::new("ProtocolDchat", channel.clone()),
47 msg_sub,
48 msgs,
49 })
50 }
51 async fn handle_receive_msg(self: Arc<Self>) -> Result<()> {
55 debug!(target: "dchat", "ProtocolDchat::handle_receive_msg() [START]");
56 while let Ok(msg) = self.msg_sub.receive().await {
57 let msg = (*msg).to_owned();
58 self.msgs.lock().await.push(msg);
59 }
60
61 Ok(())
62 }
63 }
65
66#[async_trait]
67impl net::ProtocolBase for ProtocolDchat {
68 async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
70 debug!(target: "dchat", "ProtocolDchat::ProtocolBase::start() [START]");
71 self.jobsman.clone().start(executor.clone());
72 self.jobsman.clone().spawn(self.clone().handle_receive_msg(), executor.clone()).await;
73 debug!(target: "dchat", "ProtocolDchat::ProtocolBase::start() [STOP]");
74 Ok(())
75 }
76 fn name(&self) -> &'static str {
79 "ProtocolDchat"
80 }
81}