1use async_trait::async_trait;
20use darkfi::{net::P2pPtr, system::StoppableTaskPtr};
21use log::debug;
22use smol::lock::MutexGuard;
23use std::collections::HashSet;
24
25use darkfi::rpc::{
26 jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
27 p2p_method::HandlerP2p,
28 server::RequestHandler,
29 util::JsonValue,
30};
31
32use crate::{dchatmsg::DchatMsg, Dchat};
33
34#[async_trait]
35impl RequestHandler<()> for Dchat {
36 async fn handle_request(&self, req: JsonRequest) -> JsonResult {
37 debug!(target: "dchat::rpc", "--> {}", req.stringify().unwrap());
38
39 match req.method.as_str() {
41 "send" => self.send(req.id, req.params).await,
42 "recv" => self.recv(req.id).await,
43 "ping" => self.pong(req.id, req.params).await,
44 "p2p.get_info" => self.p2p_get_info(req.id, req.params).await,
45 "dnet.switch" => self.dnet_switch(req.id, req.params).await,
46 "dnet.subscribe_events" => self.dnet_subscribe_events(req.id, req.params).await,
47 _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
48 }
49 }
51
52 async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
53 self.rpc_connections.lock().await
54 }
55}
56
57impl Dchat {
58 async fn send(&self, id: u16, params: JsonValue) -> JsonResult {
63 let msg = params[0].get::<String>().unwrap().to_string();
64 let dchatmsg = DchatMsg { msg };
65 self.p2p.broadcast(&dchatmsg).await;
66 JsonResponse::new(JsonValue::Boolean(true), id).into()
67 }
68
69 async fn recv(&self, id: u16) -> JsonResult {
74 let buffer = self.recv_msgs.lock().await;
75 let msgs: Vec<JsonValue> =
76 buffer.iter().map(|x| JsonValue::String(x.msg.clone())).collect();
77 JsonResponse::new(JsonValue::Array(msgs), id).into()
78 }
79
80 async fn dnet_switch(&self, id: u16, params: JsonValue) -> JsonResult {
88 let params = params.get::<Vec<JsonValue>>().unwrap();
89 if params.len() != 1 || !params[0].is_bool() {
90 return JsonError::new(ErrorCode::InvalidParams, None, id).into()
91 }
92
93 let switch = params[0].get::<bool>().unwrap();
94
95 if *switch {
96 self.p2p.dnet_enable();
97 } else {
98 self.p2p.dnet_disable();
99 }
100
101 JsonResponse::new(JsonValue::Boolean(true), id).into()
102 }
103 pub async fn dnet_subscribe_events(&self, id: u16, params: JsonValue) -> JsonResult {
112 let params = params.get::<Vec<JsonValue>>().unwrap();
113 if !params.is_empty() {
114 return JsonError::new(ErrorCode::InvalidParams, None, id).into()
115 }
116
117 self.dnet_sub.clone().into()
118 }
119}
120
121impl HandlerP2p for Dchat {
122 fn p2p(&self) -> P2pPtr {
123 self.p2p.clone()
124 }
125}