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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
// Copyright (c) 2021 Open Community Project Association https://ocpa.ch
// This software is published under the AGPLv3 license.

//! # ChatFile module functions

use super::rpc::Rpc;
use prost::Message;
use std::fmt;

/// include generated protobuf RPC rust definition file
mod proto {
    include!("../../../libqaul/src/rpc/protobuf_generated/rust/qaul.rpc.rtc.rs");
}
mod proto_net {
    include!("../../../libqaul/src/rpc/protobuf_generated/rust/qaul.net.rtc.rs");
}

/// GrouChat module function handling
pub struct Rtc {}

impl Rtc {
    /// CLI command interpretation
    ///
    /// The CLI commands of RTC module are processed here
    pub fn cli(command: &str) {
        match command {
            // rtc session request
            cmd if cmd.starts_with("request ") => {
                let command_string = cmd.strip_prefix("request ").unwrap().to_string();
                let mut iter = command_string.split_whitespace();

                if let Some(user_id_str) = iter.next() {
                    match Self::id_string_to_bin(user_id_str.to_string()) {
                        Ok(user_id) => {
                            Self::request_session(user_id);
                        }
                        Err(e) => {
                            log::error!("{}", e);
                            return;
                        }
                    }
                } else {
                    log::error!("rtc request command incorrectly formatted");
                }
            }

            // rtc session accept
            cmd if cmd.starts_with("accept ") => {
                let command_string = cmd.strip_prefix("accept ").unwrap().to_string();
                let mut iter = command_string.split_whitespace();

                if let Some(group_id_str) = iter.next() {
                    match Self::id_string_to_bin(group_id_str.to_string()) {
                        Ok(group_id) => {
                            Self::accept_session(group_id);
                        }
                        Err(e) => {
                            log::error!("{}", e);
                            return;
                        }
                    }
                } else {
                    log::error!("rtc accept command incorrectly formatted");
                }
            }

            // rtc session accept
            cmd if cmd.starts_with("decline ") => {
                let command_string = cmd.strip_prefix("decline ").unwrap().to_string();
                let mut iter = command_string.split_whitespace();

                if let Some(group_id_str) = iter.next() {
                    match Self::id_string_to_bin(group_id_str.to_string()) {
                        Ok(group_id) => {
                            Self::decline_session(group_id);
                        }
                        Err(e) => {
                            log::error!("{}", e);
                            return;
                        }
                    }
                } else {
                    log::error!("rtc decline command incorrectly formatted");
                }
            }

            // rtc session accept
            cmd if cmd.starts_with("end ") => {
                let command_string = cmd.strip_prefix("end ").unwrap().to_string();
                let mut iter = command_string.split_whitespace();

                if let Some(group_id_str) = iter.next() {
                    match Self::id_string_to_bin(group_id_str.to_string()) {
                        Ok(group_id) => {
                            Self::end_session(group_id);
                        }
                        Err(e) => {
                            log::error!("{}", e);
                            return;
                        }
                    }
                } else {
                    log::error!("rtc end command incorrectly formatted");
                }
            }

            // rtc send message
            cmd if cmd.starts_with("send ") => {
                let command_string = cmd.strip_prefix("send ").unwrap().to_string();
                let mut iter = command_string.split_whitespace();

                if let Some(group_id_str) = iter.next() {
                    match Self::id_string_to_bin(group_id_str.to_string()) {
                        Ok(group_id) => {
                            if let Some(message_str) = iter.next() {
                                Self::send_session(group_id, message_str.to_string());
                            } else {
                                log::error!("rtc send command no contents");
                            }
                        }
                        Err(e) => {
                            log::error!("{}", e);
                            return;
                        }
                    }
                } else {
                    log::error!("rtc send command incorrectly formatted");
                }
            }

            // rtc send message
            cmd if cmd.starts_with("list") => {
                Self::list_session();
            }

            // unknown command
            _ => log::error!("unknown group command"),
        }
    }

    /// Convert Group ID from String to Binary
    fn id_string_to_bin(id: String) -> Result<Vec<u8>, String> {
        // check length
        if id.len() < 52 {
            return Err("Group ID not long enough".to_string());
        }

        // convert input
        match bs58::decode(id).into_vec() {
            Ok(id_bin) => Ok(id_bin),
            Err(e) => {
                let err = fmt::format(format_args!("{}", e));
                Err(err)
            }
        }
    }

    /// session request
    fn request_session(user_id: Vec<u8>) {
        // create group send message
        let proto_message = proto::RtcRpc {
            message: Some(proto::rtc_rpc::Message::RtcSessionRequest(
                proto::RtcSessionRequest {
                    group_id: user_id.clone(),
                },
            )),
        };

        // encode message
        let mut buf = Vec::with_capacity(proto_message.encoded_len());
        proto_message
            .encode(&mut buf)
            .expect("Vec<u8> provides capacity as needed");

        // send message
        Rpc::send_message(buf, super::rpc::proto::Modules::Rtc.into(), "".to_string());
    }

    /// accept session
    fn accept_session(group_id: Vec<u8>) {
        // create group send message
        let proto_message = proto::RtcRpc {
            message: Some(proto::rtc_rpc::Message::RtcSessionManagement(
                proto::RtcSessionManagement {
                    group_id: group_id.clone(),
                    option: 1,
                },
            )),
        };

        // encode message
        let mut buf = Vec::with_capacity(proto_message.encoded_len());
        proto_message
            .encode(&mut buf)
            .expect("Vec<u8> provides capacity as needed");

        // send message
        Rpc::send_message(buf, super::rpc::proto::Modules::Rtc.into(), "".to_string());
    }

    /// decline session
    fn decline_session(group_id: Vec<u8>) {
        // decline session message
        let proto_message = proto::RtcRpc {
            message: Some(proto::rtc_rpc::Message::RtcSessionManagement(
                proto::RtcSessionManagement {
                    group_id: group_id.clone(),
                    option: 2,
                },
            )),
        };

        // encode message
        let mut buf = Vec::with_capacity(proto_message.encoded_len());
        proto_message
            .encode(&mut buf)
            .expect("Vec<u8> provides capacity as needed");

        // send message
        Rpc::send_message(buf, super::rpc::proto::Modules::Rtc.into(), "".to_string());
    }

    /// end session
    fn end_session(group_id: Vec<u8>) {
        // end session message
        let proto_message = proto::RtcRpc {
            message: Some(proto::rtc_rpc::Message::RtcSessionManagement(
                proto::RtcSessionManagement {
                    group_id: group_id.clone(),
                    option: 3,
                },
            )),
        };

        // encode message
        let mut buf = Vec::with_capacity(proto_message.encoded_len());
        proto_message
            .encode(&mut buf)
            .expect("Vec<u8> provides capacity as needed");

        // send message
        Rpc::send_message(buf, super::rpc::proto::Modules::Rtc.into(), "".to_string());
    }

    /// send session
    fn send_session(group_id: Vec<u8>, message: String) {
        let rtc_content = proto_net::RtcContent {
            content: Some(proto_net::rtc_content::Content::ChatContent(
                proto_net::RtcChatContent {
                    content: message.clone(),
                },
            )),
        };

        // session message
        let mut buf0 = Vec::with_capacity(rtc_content.encoded_len());
        rtc_content
            .encode(&mut buf0)
            .expect("Vec<u8> provides capacity as needed");

        let proto_message = proto::RtcRpc {
            message: Some(proto::rtc_rpc::Message::RtcOutgoing(proto::RtcOutgoing {
                group_id: group_id.clone(),
                content: buf0,
            })),
        };

        // encode message
        let mut buf = Vec::with_capacity(proto_message.encoded_len());
        proto_message
            .encode(&mut buf)
            .expect("Vec<u8> provides capacity as needed");

        // send message
        Rpc::send_message(buf, super::rpc::proto::Modules::Rtc.into(), "".to_string());
    }

    /// session list
    fn list_session() {
        let proto_message = proto::RtcRpc {
            message: Some(proto::rtc_rpc::Message::RtcSessionListRequest(
                proto::RtcSessionListRequest {},
            )),
        };

        // encode message
        let mut buf = Vec::with_capacity(proto_message.encoded_len());
        proto_message
            .encode(&mut buf)
            .expect("Vec<u8> provides capacity as needed");

        // send message
        Rpc::send_message(buf, super::rpc::proto::Modules::Rtc.into(), "".to_string());
    }

    /// Process received RPC message
    ///
    /// Decodes received protobuf encoded binary RPC message
    /// of the group chat module.
    pub fn rpc(data: Vec<u8>) {
        match proto::RtcRpc::decode(&data[..]) {
            Ok(rtc) => {
                match rtc.message {
                    Some(proto::rtc_rpc::Message::RtcSessionResponse(resp)) => {
                        println!("====================================");
                        println!("Session was created");
                        println!("\tgroup id: {}", bs58::encode(resp.group_id).into_string());
                    }
                    Some(proto::rtc_rpc::Message::RtcIncoming(resp)) => {
                        //
                        println!("====================================");
                        println!("Rtc Incoming");
                        println!("\tgroup id: {}", bs58::encode(resp.group_id).into_string());

                        match proto_net::RtcContent::decode(&resp.content[..])
                            .unwrap()
                            .content
                        {
                            Some(proto_net::rtc_content::Content::ChatContent(chat_content)) => {
                                println!("\tchat content: {}", chat_content.content);
                            }
                            _ => {}
                        }
                    }
                    Some(proto::rtc_rpc::Message::RtcSessionListResponse(resp)) => {
                        // List sessions
                        println!("=============List Of Sessions=================");
                        for session in resp.sessions {
                            println!("group id: {}", bs58::encode(session.group_id).into_string());
                            println!(
                                "\ttype: {} , state: {} , created at: {}",
                                session.session_type, session.state, session.created_at
                            );
                        }
                    }
                    _ => {
                        log::error!("unprocessable RPC RTC message");
                    }
                }
            }
            Err(error) => {
                log::error!("{:?}", error);
            }
        }
    }
}