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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
// Copyright (c) 2021 Open Community Project Association https://ocpa.ch
// This software is published under the AGPLv3 license.

//! # Group 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.group.rs");
}

/// include chat protobuf RPC file
mod proto_chat {
    include!("../../../libqaul/src/rpc/protobuf_generated/rust/qaul.rpc.chat.rs");
}

/// Group module function handling
pub struct Group {}

impl Group {
    /// CLI command interpretation
    ///
    /// The CLI commands of group module are processed here
    pub fn cli(command: &str) {
        match command {
            // create group
            cmd if cmd.starts_with("create ") => {
                let command_string = cmd.strip_prefix("create ").unwrap().to_string();
                let group_name = command_string.trim().to_string();

                if group_name.len() > 0 {
                    Self::create_group(group_name.clone());
                } else {
                    log::error!("group create command incorrectly formatted");
                }
            }
            // rename group
            cmd if cmd.starts_with("rename ") => {
                let command_string = cmd.strip_prefix("rename ").unwrap().to_string();
                let mut iter = command_string.split_whitespace();

                if let Some(group_id_str) = iter.next() {
                    match Self::uuid_string_to_bin(group_id_str.to_string()) {
                        Ok(group_id) => {
                            let group_name = command_string
                                .strip_prefix(group_id_str.clone())
                                .unwrap()
                                .to_string()
                                .trim()
                                .to_string();

                            if group_name.len() > 0 {
                                Self::rename_group(group_id, group_name.to_string());
                            } else {
                                log::error!("group name is missing");
                            }
                        }
                        Err(e) => {
                            log::error!("{}", e);
                            return;
                        }
                    }
                } else {
                    log::error!("group create command incorrectly formatted");
                }
            }
            // group info
            cmd if cmd.starts_with("info ") => {
                let command_string = cmd.strip_prefix("info ").unwrap().to_string();
                let mut iter = command_string.split_whitespace();

                if let Some(group_id_str) = iter.next() {
                    match Self::uuid_string_to_bin(group_id_str.to_string()) {
                        Ok(group_id) => {
                            Self::group_info(group_id);
                        }
                        Err(e) => {
                            log::error!("{}", e);
                            return;
                        }
                    }
                } else {
                    log::error!("group create command incorrectly formatted");
                }
            }
            // group list
            cmd if cmd.starts_with("list") => {
                //let command_string = cmd.strip_prefix("list ").unwrap().to_string();
                Self::group_list();
            }
            // group list
            cmd if cmd.starts_with("invited") => {
                Self::group_invited();
            }
            // group invite
            cmd if cmd.starts_with("invite ") => {
                let command_string = cmd.strip_prefix("invite ").unwrap().to_string();
                let mut iter = command_string.split_whitespace();

                if let Some(group_id_str) = iter.next() {
                    match Self::uuid_string_to_bin(group_id_str.to_string()) {
                        Ok(group_id) => {
                            if let Some(user_id_str) = iter.next() {
                                match Self::id_string_to_bin(user_id_str.to_string()) {
                                    Ok(user_id) => {
                                        Self::invite(group_id, user_id);
                                    }
                                    Err(e) => {
                                        log::error!("{}", e);
                                        return;
                                    }
                                }
                            } else {
                                log::error!("user id is not given");
                            }
                        }
                        Err(e) => {
                            log::error!("{}", e);
                            return;
                        }
                    }
                } else {
                    log::error!("group create command incorrectly formatted");
                }
            }
            // accept invite
            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::uuid_string_to_bin(group_id_str.to_string()) {
                        Ok(group_id) => {
                            Self::reply_invite(group_id, true);
                        }
                        Err(e) => {
                            log::error!("{}", e);
                            return;
                        }
                    }
                } else {
                    log::error!("group accept command incorrectly formatted");
                }
            }
            // decline invite
            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::uuid_string_to_bin(group_id_str.to_string()) {
                        Ok(group_id) => {
                            Self::reply_invite(group_id, false);
                        }
                        Err(e) => {
                            log::error!("{}", e);
                            return;
                        }
                    }
                } else {
                    log::error!("group accept command incorrectly formatted");
                }
            }
            // remove member
            cmd if cmd.starts_with("remove ") => {
                let command_string = cmd.strip_prefix("remove ").unwrap().to_string();
                let mut iter = command_string.split_whitespace();

                if let Some(group_id_str) = iter.next() {
                    match Self::uuid_string_to_bin(group_id_str.to_string()) {
                        Ok(group_id) => {
                            if let Some(user_id_str) = iter.next() {
                                match Self::id_string_to_bin(user_id_str.to_string()) {
                                    Ok(user_id) => {
                                        Self::remove_member(group_id, user_id);
                                    }
                                    Err(e) => {
                                        log::error!("{}", e);
                                        return;
                                    }
                                }
                            } else {
                                log::error!("user id is not given");
                            }
                        }
                        Err(e) => {
                            log::error!("{}", e);
                            return;
                        }
                    }
                } else {
                    log::error!("group remove command incorrectly formatted");
                }
            }
            // 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)
            }
        }
    }

    /// Convert Group ID from String to Binary
    fn uuid_string_to_bin(id_str: String) -> Result<Vec<u8>, String> {
        match uuid::Uuid::parse_str(id_str.as_str()) {
            Ok(id) => Ok(id.as_bytes().to_vec()),
            _ => Err("invalid group id".to_string()),
        }
    }

    /// create group
    fn create_group(group_name: String) {
        // create group send message
        let proto_message = proto::Group {
            message: Some(proto::group::Message::GroupCreateRequest(
                proto::GroupCreateRequest {
                    group_name: group_name.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::Group.into(),
            "".to_string(),
        );
    }

    /// rename group
    fn rename_group(group_id: Vec<u8>, group_name: String) {
        // rename group send message
        let proto_message = proto::Group {
            message: Some(proto::group::Message::GroupRenameRequest(
                proto::GroupRenameRequest {
                    group_name: group_name.clone(),
                    group_id: group_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::Group.into(),
            "".to_string(),
        );
    }

    /// group info
    fn group_info(group_id: Vec<u8>) {
        // group info send message
        let proto_message = proto::Group {
            message: Some(proto::group::Message::GroupInfoRequest(
                proto::GroupInfoRequest {
                    group_id: group_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::Group.into(),
            "".to_string(),
        );
    }

    /// group list
    fn group_list() {
        // group list send message
        let proto_message = proto::Group {
            message: Some(proto::group::Message::GroupListRequest(
                proto::GroupListRequest {},
            )),
        };

        // 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::Group.into(),
            "".to_string(),
        );
    }

    /// group invited
    fn group_invited() {
        // group list send message
        let proto_message = proto::Group {
            message: Some(proto::group::Message::GroupInvitedRequest(
                proto::GroupInvitedRequest {},
            )),
        };

        // send message
        Rpc::send_message(
            proto_message.encode_to_vec(),
            super::rpc::proto::Modules::Group.into(),
            "".to_string(),
        );
    }

    /// group invite
    fn invite(group_id: Vec<u8>, user_id: Vec<u8>) {
        // group invite send message
        let proto_message = proto::Group {
            message: Some(proto::group::Message::GroupInviteMemberRequest(
                proto::GroupInviteMemberRequest {
                    group_id: group_id.clone(),
                    user_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::Group.into(),
            "".to_string(),
        );
    }

    /// reply invite
    fn reply_invite(group_id: Vec<u8>, accept: bool) {
        // group invite send message
        let proto_message = proto::Group {
            message: Some(proto::group::Message::GroupReplyInviteRequest(
                proto::GroupReplyInviteRequest {
                    group_id: group_id.clone(),
                    accept,
                },
            )),
        };

        // 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::Group.into(),
            "".to_string(),
        );
    }

    /// remove member
    fn remove_member(group_id: Vec<u8>, user_id: Vec<u8>) {
        // group invite send message
        let proto_message = proto::Group {
            message: Some(proto::group::Message::GroupRemoveMemberRequest(
                proto::GroupRemoveMemberRequest {
                    group_id: group_id.clone(),
                    user_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::Group.into(),
            "".to_string(),
        );
    }

    /// Process the last message & print it's content
    fn print_last_message(data: Vec<u8>) {
        if let Ok(content_message) = proto_chat::ChatContentMessage::decode(&data[..]) {
            match content_message.message {
                Some(proto_chat::chat_content_message::Message::ChatContent(chat_content)) => {
                    println!("\t\t{}", chat_content.text);
                }
                Some(proto_chat::chat_content_message::Message::FileContent(file_content)) => {
                    println!(
                        "\t\tfile {} [{}] ID {}",
                        file_content.file_name,
                        file_content.file_size.to_string(),
                        file_content.file_id.to_string()
                    );
                    println!("\t\t{}", file_content.file_description);
                }
                Some(proto_chat::chat_content_message::Message::GroupEvent(group_event)) => {
                    match proto_chat::GroupEventType::from_i32(group_event.event_type).unwrap() {
                        proto_chat::GroupEventType::Joined => {
                            println!(
                                "\t\tNew user joined group, user id: {}",
                                bs58::encode(group_event.user_id).into_string()
                            );
                        }
                        proto_chat::GroupEventType::Left => {
                            println!(
                                "\t\tUser left group, user id: {}",
                                bs58::encode(group_event.user_id).into_string()
                            );
                        }
                        proto_chat::GroupEventType::Removed => {
                            println!("\t\tYou have been removed from this group.");
                        }
                        proto_chat::GroupEventType::Created => {
                            println!("\t\tYou created this group");
                        }
                        proto_chat::GroupEventType::InviteAccepted => {
                            println!("\t\tYou accepted the invitation");
                        }
                        _ => {}
                    }
                }
                None => {}
            }
        }
    }

    /// Process received RPC message
    ///
    /// Decodes received protobuf encoded binary RPC message
    /// of the group chat module.
    pub fn rpc(data: Vec<u8>) {
        match proto::Group::decode(&data[..]) {
            Ok(group_chat) => {
                match group_chat.message {
                    Some(proto::group::Message::GroupCreateResponse(create_group_response)) => {
                        println!("====================================");
                        println!("Group was created or updated");
                        let group_id = uuid::Uuid::from_bytes(
                            create_group_response.group_id.try_into().unwrap(),
                        );
                        println!("\tid: {}", group_id.to_string());
                    }
                    Some(proto::group::Message::GroupRenameResponse(rename_group_response)) => {
                        let result = rename_group_response.result.unwrap();
                        println!("====================================");
                        println!("Group Rename status: {}", result.status);
                        let group_id = uuid::Uuid::from_bytes(
                            rename_group_response.group_id.try_into().unwrap(),
                        );
                        println!("\tid: {}", group_id.to_string());
                        if !result.status {
                            println!("\terror: {}", result.message);
                        }
                    }
                    Some(proto::group::Message::GroupInviteMemberResponse(
                        invite_group_response,
                    )) => {
                        let result = invite_group_response.result.unwrap();
                        println!("====================================");
                        println!("Group Invite status: {}", result.status);
                        let group_id = uuid::Uuid::from_bytes(
                            invite_group_response.group_id.try_into().unwrap(),
                        );
                        println!("\tid: {}", group_id.to_string());
                        if !result.status {
                            println!("\terror: {}", result.message);
                        }
                    }
                    Some(proto::group::Message::GroupReplyInviteResponse(reply_group_response)) => {
                        let result = reply_group_response.result.unwrap();
                        println!("====================================");
                        println!("Reply Group Invite status: {}", result.status);
                        let group_id = uuid::Uuid::from_bytes(
                            reply_group_response.group_id.try_into().unwrap(),
                        );
                        println!("\tid: {}", group_id.to_string());
                        if !result.status {
                            println!("\terror: {}", result.message);
                        }
                    }
                    Some(proto::group::Message::GroupRemoveMemberResponse(
                        remove_member_response,
                    )) => {
                        let result = remove_member_response.result.unwrap();
                        println!("====================================");
                        println!("Group Remove Member status: {}", result.status);
                        let group_id = uuid::Uuid::from_bytes(
                            remove_member_response.group_id.try_into().unwrap(),
                        );
                        println!("\tid: {}", group_id.to_string());
                        if !result.status {
                            println!("\terror: {}", result.message);
                        }
                    }
                    Some(proto::group::Message::GroupInfoResponse(group_info_response)) => {
                        // group
                        println!("====================================");
                        println!("Group Information");
                        let group_id = uuid::Uuid::from_bytes(
                            group_info_response.group_id.try_into().unwrap(),
                        );
                        println!("\tid: {}", group_id.to_string());
                        println!("\tname: {}", group_info_response.group_name.clone());
                        println!("\tcreated_at: {}", group_info_response.created_at);
                        println!("\tmembers: {}", group_info_response.members.len());
                    }
                    Some(proto::group::Message::GroupListResponse(group_list_response)) => {
                        // List groups
                        println!("=============List Of Groups=================");
                        for group in group_list_response.groups {
                            let group_id =
                                uuid::Uuid::from_bytes(group.group_id.try_into().unwrap());
                            let group_type: String;
                            match group.is_direct_chat {
                                true => group_type = "Direct".to_string(),
                                false => group_type = "Group".to_string(),
                            }
                            println!(
                                "{} {} {}",
                                group_type,
                                group_id.to_string(),
                                group.group_name.clone()
                            );
                            print!("\tstatus: ");
                            match proto::GroupStatus::from_i32(group.status) {
                                Some(proto::GroupStatus::Active) => println!("Active"),
                                Some(proto::GroupStatus::InviteAccepted) => {
                                    println!("Invite Accepted")
                                }
                                Some(proto::GroupStatus::Deactivated) => println!("Deactivated"),
                                None => println!("NOT SET"),
                            }

                            println!(
                                "\tcreated_at: {}, members: {}",
                                group.created_at,
                                group.members.len()
                            );
                            for member in group.members {
                                print!(
                                    "\t\t id: {} , state: ",
                                    bs58::encode(member.user_id.clone()).into_string()
                                );
                                match proto::GroupMemberState::from_i32(member.state).unwrap() {
                                    proto::GroupMemberState::Invited => {
                                        print!("invited , role: ");
                                    }
                                    proto::GroupMemberState::Activated => {
                                        print!("activated , role: ");
                                    }
                                }

                                match proto::GroupMemberRole::from_i32(member.role).unwrap() {
                                    proto::GroupMemberRole::User => {
                                        println!("user , sent: {}", member.last_message_index);
                                    }
                                    proto::GroupMemberRole::Admin => {
                                        println!("admin , sent: {}", member.last_message_index);
                                    }
                                }
                            }
                            println!("\trevision: {}", group.revision);
                            println!("\tunread messages: {}", group.unread_messages);
                            println!("\tlast message:");
                            println!(
                                "\t\tsent_at: {} from: {}",
                                group.last_message_at,
                                bs58::encode(group.last_message_sender_id).into_string()
                            );
                            Self::print_last_message(group.last_message);
                        }
                    }
                    Some(proto::group::Message::GroupInvitedResponse(group_invited_response)) => {
                        // List of pending invites
                        println!("=============List Of Invited=================");
                        for invite in group_invited_response.invited {
                            if let Some(group) = invite.group {
                                let group_id =
                                    uuid::Uuid::from_bytes(group.group_id.try_into().unwrap());
                                println!("id: {}", group_id.to_string());
                                println!("\tname: {}", group.group_name.clone());
                                println!(
                                    "\tsender: {}",
                                    bs58::encode(invite.sender_id).into_string()
                                );
                                println!("\treceived at: {}", invite.received_at);
                                println!(
                                    "\tcreated_at: {}, members: {}",
                                    invite.received_at,
                                    group.members.len()
                                );
                            }
                        }
                    }
                    _ => {
                        log::error!("unprocessable RPC group chat message");
                    }
                }
            }
            Err(error) => {
                log::error!("{:?}", error);
            }
        }
    }
}