1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
//! rings-rpc client

use rings_core::session::SessionSk;
use serde_json::json;
use serde_json::Value;

use crate::error::Error;
use crate::error::Result;
use crate::jsonrpc_client::SimpleClient;
use crate::method::Method;
use crate::prelude::jsonrpc_core::Params;
use crate::prelude::*;
use crate::response;
use crate::response::Peer;
use crate::types;
use crate::types::Timeout;

/// Wrap json_client send request between nodes or browsers.
pub struct Client {
    client: SimpleClient,
}

impl Client {
    /// Creates a new Client instance with the specified endpoint URL
    pub fn new(endpoint_url: &str, delegated_sk: Option<SessionSk>) -> Self {
        Self {
            client: SimpleClient::new(endpoint_url, delegated_sk),
        }
    }

    /// Establishes a WebRTC connection with a remote peer using HTTP as the signaling channel.
    ///
    /// This function allows two peers to establish a WebRTC connection using HTTP,
    /// which can be useful in scenarios where a direct peer-to-peer connection is not possible due to firewall restrictions or other network issues.
    /// The function sends ICE candidates and Session Description Protocol (SDP) messages over HTTP as a form of signaling to establish the connection.
    ///
    /// Takes a URL for an HTTP server that will be used as the signaling channel to exchange ICE candidates and SDP with the remote peer.
    /// Returns a Did that can be used to refer to this connection in subsequent WebRTC operations.
    pub async fn connect_peer_via_http(&mut self, http_url: &str) -> Result<String> {
        let resp = self
            .client
            .call_method(
                Method::ConnectPeerViaHttp.as_str(),
                Params::Array(vec![Value::String(http_url.to_owned())]),
            )
            .await
            .map_err(Error::RpcError)?;

        let did = resp.as_str().ok_or(Error::DecodeError)?;
        Ok(did.to_string())
    }

    /// Attempts to connect to a peer using a seed file located at the specified source path.
    pub async fn connect_with_seed(&mut self, seeds: &[serde_json::Value]) -> Result<()> {
        self.client
            .call_method(
                Method::ConnectWithSeed.as_str(),
                Params::Array(seeds.to_vec()),
            )
            .await
            .map_err(Error::RpcError)?;
        Ok(())
    }

    /// Attempts to connect to a peer using a DID stored in a Distributed Hash Table (DHT).
    pub async fn connect_with_did(&mut self, did: &str) -> Result<()> {
        self.client
            .call_method(
                Method::ConnectWithDid.as_str(),
                Params::Array(vec![Value::String(did.to_owned())]),
            )
            .await
            .map_err(Error::RpcError)?;
        Ok(())
    }

    /// Lists all connected peers and their status.
    ///
    /// Returns an Output containing a formatted string representation of the list of peers if successful, or an anyhow::Error if an error occurred.
    pub async fn list_peers(&mut self) -> Result<Vec<Peer>> {
        let resp = self
            .client
            .call_method(Method::ListPeers.as_str(), Params::Array(vec![]))
            .await
            .map_err(Error::RpcError)?;

        let peers: Vec<Peer> = serde_json::from_value(resp).map_err(|_| Error::DecodeError)?;
        Ok(peers)
    }

    /// Disconnects from the peer with the specified DID.
    pub async fn disconnect(&mut self, did: &str) -> Result<()> {
        self.client
            .call_method(Method::Disconnect.as_str(), Params::Array(vec![json!(did)]))
            .await
            .map_err(Error::RpcError)?;

        Ok(())
    }

    /// Sends a message to the specified peer.
    pub async fn send_message(
        &self,
        did: &str,
        text: &str,
    ) -> Result<response::SendMessageResponse> {
        let mut params = serde_json::Map::new();
        params.insert("destination".to_owned(), json!(did));
        params.insert("text".to_owned(), json!(text));
        let result = self
            .client
            .call_method(Method::SendTo.as_str(), Params::Map(params))
            .await
            .map_err(Error::RpcError)?;
        serde_json::from_value(result).map_err(|_| Error::DecodeError)
    }

    /// Sends a custom message to the specified peer.
    pub async fn send_custom_message(
        &self,
        did: &str,
        message_type: u16,
        data: &str,
    ) -> Result<response::SendMessageResponse> {
        let result = self
            .client
            .call_method(
                Method::SendCustomMessage.as_str(),
                Params::Array(vec![json!(did), json!(message_type), json!(data)]),
            )
            .await
            .map_err(Error::RpcError)?;
        serde_json::from_value(result).map_err(|_| Error::DecodeError)
    }

    /// Sends an HTTP request message to the specified peer.
    #[allow(clippy::too_many_arguments)]
    pub async fn send_http_request_message(
        &self,
        did: &str,
        name: &str,
        method: http::Method,
        url: &str,
        timeout: Timeout,
        headers: &[(&str, &str)],
        body: Option<String>,
    ) -> Result<response::SendMessageResponse> {
        let http_request: types::HttpRequest = types::HttpRequest::new(
            name,
            method,
            url,
            timeout,
            headers,
            body.map(|v| v.as_bytes().to_vec()),
        );
        let params2 = serde_json::to_value(http_request).map_err(|_| Error::EncodeError)?;
        let result = self
            .client
            .call_method(
                Method::SendHttpRequestMessage.as_str(),
                Params::Array(vec![json!(did), params2]),
            )
            .await
            .map_err(Error::RpcError)?;
        serde_json::from_value(result).map_err(|_| Error::DecodeError)
    }

    /// Sends a simple text message to the specified peer.
    pub async fn send_simple_text_message(
        &self,
        did: &str,
        text: &str,
    ) -> Result<response::SendMessageResponse> {
        let result = self
            .client
            .call_method(
                Method::SendSimpleText.as_str(),
                Params::Array(vec![json!(did), json!(text)]),
            )
            .await
            .map_err(Error::RpcError)?;
        serde_json::from_value(result).map_err(|_| Error::DecodeError)
    }

    /// Registers a new service with the given name.
    pub async fn register_service(&self, name: &str) -> Result<()> {
        self.client
            .call_method(
                Method::RegisterService.as_str(),
                Params::Array(vec![json!(name)]),
            )
            .await
            .map_err(Error::RpcError)?;
        Ok(())
    }

    /// Looks up the DIDs of services registered with the given name.
    pub async fn lookup_service(&self, name: &str) -> Result<Vec<String>> {
        let resp = self
            .client
            .call_method(
                Method::LookupService.as_str(),
                Params::Array(vec![json!(name)]),
            )
            .await
            .map_err(Error::RpcError)?;

        serde_json::from_value(resp).map_err(|_| Error::DecodeError)
    }

    /// Publishes a message to the specified topic.
    pub async fn publish_message_to_topic(&self, topic: &str, data: &str) -> Result<()> {
        self.client
            .call_method(
                Method::PublishMessageToTopic.as_str(),
                Params::Array(vec![json!(topic), json!(data)]),
            )
            .await
            .map_err(Error::RpcError)?;
        Ok(())
    }

    pub async fn fetch_topic_messages(&self, topic: &str, index: usize) -> Result<Vec<String>> {
        let resp = self
            .client
            .call_method(
                Method::FetchMessagesOfTopic.as_str(),
                Params::Array(vec![json!(topic), json!(index)]),
            )
            .await
            .map_err(Error::RpcError)?;

        serde_json::from_value(resp).map_err(|_| Error::DecodeError)
    }

    /// Query for swarm inspect info.
    pub async fn inspect(&self) -> Result<response::NodeInfo> {
        let resp = self
            .client
            .call_method(Method::NodeInfo.as_str(), Params::None)
            .await
            .map_err(Error::RpcError)?;
        serde_json::from_value(resp).map_err(|_| Error::DecodeError)
    }
}