~nicohman/signal-rs

ref: ad7bba6ed316afe281e38a8327baf7c1bbf824da signal-rs/src/presage_manager.rs -rw-r--r-- 38.2 KiB
ad7bba6e — nicohman Basic attachments 4 months ago
                                                                                
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
use crate::util::*;
use crate::*;
use anyhow::{Context, Result};
use futures::io::AsyncReadExt;
use futures_util::StreamExt;
use pallet::Document;
use pallet::Store;
use std::fs;
use std::io::Write;
use std::path::Path;
pub struct Presage {
    pub msg_store: Store<SignalMessage>,
    pub contact_store: Store<Contact>,
    pub group_store: Store<Group>,
    pub profile_store: Store<Profile>,
    pub req_sender: UnboundedSender<SignalRequest>,
    pub whoami: Option<Uuid>,
    pub res_sender: UnboundedSender<SignalResponse>,
    pub data_dir: String,
}
impl Presage {
    pub async fn run(
        config_store: SledConfigStore,
        res_sender: UnboundedSender<SignalResponse>,
        mut req_receiver: UnboundedReceiver<SignalRequest>,
        config: Config,
    ) {
        let data_dir = config
            .data_dir
            .replace("~", home::home_dir().unwrap().to_str().unwrap());
        let mut manager = Manager::with_config_store(config_store, ProtocolContext::default())
            .expect("Couldn't create Manager");
        let whoami = manager
            .whoami()
            .await
            .unwrap()
            .uuid
            .to_string()
            .to_uppercase();
        let self_profile = manager
            .retrieve_profile()
            .await
            .expect("Couldn't fetch own profile");
        let name = self_profile.name.map(|x| x.given_name).unwrap_or(
            manager
                .phone_number()
                .map(|x| x.format().mode(phonenumber::Mode::E164).to_string())
                .unwrap_or_default(),
        );
        res_sender
            .send(SignalResponse::Profile(Profile {
                uuid: whoami.clone(),
                name,
                about_emoji: self_profile.about_emoji.unwrap_or_default(),
                about: self_profile.about.unwrap_or_default(),
            }))
            .expect("Couldn't send own profile");
        let incoming_messages = manager
            .receive_messages_stream()
            .await
            .expect("Couldn't create incoming messages stream");
        let mut pinned_fut = Box::pin(incoming_messages);
        loop {
            tokio::select! {
                inc = pinned_fut.next() => {
                    if let Some(response) = inc {
                        println!("{:?}", response);
                        res_sender.send(SignalResponse::Metadata(response.metadata.clone())).expect("Couldn't send Metadata");
                        match response.body.clone() {
                            ContentBody::DataMessage(dm) => {
                                if let Some(profile_key) = dm.profile_key {
                                    if let Some(uuid) = response.metadata.sender.uuid {
                                        if let Ok(profile) = manager.retrieve_profile_by_uuid(uuid.clone(), make_profile_key(profile_key)).await {
                                            let name = profile.name.map(|x| {
                                                x.given_name
                                            }).unwrap_or_default();
                                            res_sender.send(SignalResponse::Profile(Profile {
                                                name,
                                                about: profile.about.unwrap_or_default(),
                                                about_emoji: profile.about_emoji.unwrap_or_default(),
                                                uuid: response.metadata.sender.identifier().to_uppercase()
                                            })).expect("Couldn't send Profile");
                                        }
                                    }

                                }


                                if let Some(react) = dm.reaction {
                                    if react.target_author_uuid.is_some() && react.emoji.is_some() && react.target_sent_timestamp.is_some() {
                                        if let Some(remove) = react.remove {
                                            if remove {
                                                //Remove reaction
                                                continue;
                                            }
                                        res_sender.send(SignalResponse::AddReaction{
                                            target: react.target_author_uuid.unwrap().clone().to_uppercase(),
                                            emoji: react.emoji.unwrap(),
                                            target_timestamp: react.target_sent_timestamp.unwrap() as i64,
                                            timestamp: response.metadata.timestamp as i64,
                                            from: response.metadata.sender.identifier().to_uppercase()
                                        }).expect("Couldn't send AddReaction");
                                        }
                                    }
                                }
                                if dm.body.is_some() || dm.attachments.len() > 0{
                                    let body = dm.body.unwrap_or_default();
                                    let mut chat_id = response
                                        .metadata
                                        .sender
                                        .identifier().to_uppercase();
                                    if let Some(gc) = dm.group {
                                        chat_id = get_gid(gc.id.unwrap());
                                        let g = Group {
                                            name: gc.name.unwrap_or_default(),
                                            members: gc.members_e164,
                                            id: chat_id.clone(),
                                            master_key: None
                                        };
                                        res_sender.send(SignalResponse::SGroup(g)).expect("Couldn't send SGroup");
                                        }
                                    let mut attachments : Vec<Attachment> = vec![];
                                    // TODO: This blocks the select loop until attachment has been downloaded. It shouldn't do that. Fix this.
                                    for attachment in dm.attachments.iter() {
                                        let path = Path::new(&data_dir).join("attachments").join(attachment.file_name());
                                        if !path.exists() {
                                            let mut key : [u8; 64] = [0; 64];
                                            let mut down = manager.fetch_attachment(attachment).await.unwrap();
                                            key.copy_from_slice(attachment.key.as_ref().unwrap().as_slice());
                                            let mut ciphertext : Vec<u8> = vec![];
                                            down.read_to_end(&mut ciphertext).await.unwrap();
                                            libsignal_service::attachment_cipher::decrypt_in_place(key, &mut ciphertext).unwrap();
                                            let mut f = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap();
                                            f.write_all(&ciphertext).expect("Couldn't write to attachment file");
                                            attachments.push(Attachment {
                                                file: path.into_os_string().into_string().unwrap(),
                                                file_name: attachment.file_name().to_string(),
                                                c_type: AttachmentType::from_mime(attachment.content_type())
                                            });
                                        }
                                    }
                                    if let Some(gc2) = dm.group_v2 {
                                        let gid = get_gid_v2(gc2.master_key.clone().unwrap());
                                        chat_id = gid;
                                        res_sender.send(SignalResponse::GroupV2Context(gc2)).expect("Couldn't send GroupV2Context");
                                    }
                                    let msg = SignalMessage {
                                        source: response
                                            .metadata
                                            .sender
                                            .identifier().to_uppercase(),
                                        chat_id: chat_id,
                                        sent_at: dm.timestamp.unwrap() as i64,
                                        ID: 0,
                                        message: body,
                                        reactions: vec![],
                                        attachment: Some(attachments),
                                        outgoing: response.metadata.sender.identifier().to_uppercase() == whoami,
                                    };
                                    res_sender.send(SignalResponse::IDLessMessage(msg)).expect("Couldn't send IDLessMessage");
                                } else {
                                }
                            }
                            ContentBody::SynchronizeMessage(sm) => {
                                if let Some(sent) = sm.sent {
                                    if let Some(dm) = sent.message {
                                        if let Some(react) = dm.reaction {
                                            if react.target_author_uuid.is_some() && react.emoji.is_some() && react.target_sent_timestamp.is_some() {
                                                if let Some(remove) = react.remove {
                                                    if remove {
                                                        //Remove reaction
                                                        continue;
                                                    }
                                                res_sender.send(SignalResponse::AddReaction{
                                                    target: react.target_author_uuid.unwrap().clone().to_uppercase(),
                                                    emoji: react.emoji.unwrap(),
                                                    target_timestamp: react.target_sent_timestamp.unwrap() as i64,
                                                    timestamp: response.metadata.timestamp as i64,
                                                    from: response.metadata.sender.identifier().to_uppercase()
                                                }).expect("Couldn't send AddReaction");
                                                }
                                            }
                                        }
                                        if dm.body.is_some() || dm.attachments.len() > 0 {
                                            let body = dm.body.unwrap_or_default();
                                            let mut chat_id = sent
                                                .destination_uuid.
                                                unwrap_or(sent.destination_e164.unwrap_or_default()).to_uppercase();
                                            if let Some(gc) = dm.group {
                                                chat_id = get_gid(gc.id.unwrap());
                                                let g = Group {
                                                    name: gc.name.unwrap_or_default(),
                                                    members: gc.members_e164,
                                                    id: chat_id.clone(),
                                                    master_key: None
                                                };
                                                res_sender.send(SignalResponse::SGroup(g)).expect("Couldn't send SGroup");
                                            }
                                            let mut attachments : Vec<Attachment> = vec![];
                                            // TODO: This blocks the select loop until attachment has been downloaded. It shouldn't do that. Fix this.
                                            for attachment in dm.attachments.iter() {
                                                let path = Path::new(&data_dir).join("attachments").join(attachment.file_name());
                                                if !path.exists() {
                                                    let mut key : [u8; 64] = [0; 64];
                                                    let mut down = manager.fetch_attachment(attachment).await.unwrap();
                                                    key.copy_from_slice(attachment.key.as_ref().unwrap().as_slice());
                                                    let mut ciphertext : Vec<u8> = vec![];
                                                    down.read_to_end(&mut ciphertext).await.unwrap();
                                                    libsignal_service::attachment_cipher::decrypt_in_place(key, &mut ciphertext).unwrap();
                                                    let mut f = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap();
                                                    f.write_all(&ciphertext).expect("Couldn't write to attachment file");
                                                    attachments.push(Attachment {
                                                        file: path.into_os_string().into_string().unwrap(),
                                                        file_name: attachment.file_name().to_string(),
                                                        c_type: AttachmentType::from_mime(attachment.content_type())
                                                    });
                                                }
                                            }
                                            if let Some(gc2) = dm.group_v2 {
                                                let gid = get_gid_v2(gc2.master_key.clone().unwrap());
                                                chat_id = gid;
                                                res_sender.send(SignalResponse::GroupV2Context(gc2)).expect("Couldn't send GroupV2Context");
                                            }
                                            let msg = SignalMessage {
                                                source: response
                                                    .metadata
                                                    .sender.identifier().to_uppercase(),
                                                chat_id: chat_id,
                                                sent_at: dm.timestamp.unwrap() as i64,
                                                ID: 0,
                                                message: body,
                                                reactions: vec![],
                                                attachment: Some(attachments),
                                                outgoing: response.metadata.sender.identifier().to_uppercase() == whoami,
                                            };
                                            res_sender.send(SignalResponse::IDLessMessage(msg)).expect("Couldn't send IDLessMessage");
                                        }
                                    }
                                }
                            }
                        _ => {}
                        }
                    }
                },
                req = req_receiver.recv() => {
                    println!("{:?}", req);
                    if let Some(req) = req {
                    match req {
                        SignalRequest::SendMessageToGroup { members, message, attachment: _, id, master_key} => {
                            let now = chrono::Utc::now().timestamp_millis() as u64;
                            let msg = DataMessage {
                                body: Some(message.clone()),
                                timestamp:Some(now.clone()),
                                group_v2: Some(GroupContextV2 {
                                    master_key: master_key,
                                    revision: Some(1),
                                    group_change: None
                                }),
                                ..Default::default()
                            };
                            manager.send_message_to_group(members.into_iter().map(|x| {
                                return ServiceAddress::parse(None, Some(&x)).unwrap();
                            }).collect::<Vec<ServiceAddress>>(),  msg, now).await.unwrap();
                            let sm = SignalResponse::IDLessMessage(SignalMessage {
                                message: message,
                                source: whoami.clone().to_uppercase(),
                                chat_id: id,
                                outgoing: true,
                                attachment: None,
                                sent_at: now as i64,
                                ID: 0,
                                reactions: vec![]
                            });
                            res_sender.send(sm).expect("Couldn't send IDLessMessage");
                        },
                        SignalRequest::SendMessage { to, message, attachment: _ } => {
                            let tos = ServiceAddress::parse(None, Some(to.as_str())).unwrap_or_else(|_| {ServiceAddress::parse(Some(to.as_str()), None).unwrap()});
                            let now = chrono::Utc::now().timestamp_millis() as u64;
                            let msg = DataMessage {
                                body: Some(message.clone()),
                                timestamp:Some(now.clone()),
                                ..Default::default()
                            };
                            manager.send_message(tos.clone(), msg, now).await.unwrap();
                            let sm = SignalResponse::IDLessMessage(SignalMessage {
                                message: message,
                                source: to.clone().to_uppercase(),
                                chat_id: to.clone().to_uppercase(),
                                outgoing: true,
                                attachment: None,
                                sent_at: now as i64,
                                ID: 0,
                                reactions: vec![]
                            });
                            res_sender.send(sm).expect("Couldn't send IDLessMessage");
                        },
                        SignalRequest::EditContact{ name, phone, id } => {
                            res_sender.send(SignalResponse::RmContact(id.clone())).expect("Couldn't send RmContact");
                            res_sender.send(SignalResponse::ContactList(vec![Contact {name, tel: phone, uuid: id, state: "real".to_string()}])).expect("Couldn't send ContactList");
                        },
                        SignalRequest::GetGroupCtxV2(ctx) => {
                            let group = manager.get_group_v2(make_gkey(ctx.master_key.clone().unwrap())).await.unwrap();
                            println!("{:?}", group);
                            let gid = get_gid_v2(ctx.master_key.clone().unwrap());
                            res_sender.send(SignalResponse::SGroup(Group {
                                name: group.title,
                                id: gid,
                                master_key: ctx.master_key.clone(),
                                members: group.members.clone().into_iter().map(|x| {
                                    return Uuid::from_slice(&x.uuid).unwrap().to_string().to_uppercase();
                                }).collect()
                            })).expect("Couldn't send SGroup");
                        },
                        _ => {

                        }
                    }
                }
                }
            }
        }
    }

    // Makes a new Presage struct.
    pub fn new(
        res_sender: UnboundedSender<SignalResponse>,
        config: Config,
        req_sender: UnboundedSender<SignalRequest>,
    ) -> Result<Presage> {
        let data_dir = config
            .data_dir
            .replace("~", home::home_dir().unwrap().to_str().unwrap());
        // Open, index and setup stores for messages/contacts/groups/avatars
        fs::create_dir_all(Path::new(&data_dir).join("avatars"))?;
        fs::create_dir_all(Path::new(&data_dir).join("attachments"))?;
        let m_db =
            pallet::ext::sled::open(Path::new(&data_dir).join("messages").to_str().unwrap())?;
        let c_db =
            pallet::ext::sled::open(Path::new(&data_dir).join("contacts").to_str().unwrap())?;
        let g_db = pallet::ext::sled::open(Path::new(&data_dir).join("groups").to_str().unwrap())?;
        let p_db =
            pallet::ext::sled::open(Path::new(&data_dir).join("profiles").to_str().unwrap())?;
        fs::create_dir_all("/tmp/mdb")?;
        fs::create_dir_all("/tmp/cdb")?;
        fs::create_dir_all("/tmp/gdb")?;
        fs::create_dir_all("/tmp/pdb")?;
        let msg_store = pallet::Store::builder()
            .with_db(m_db)
            .with_index_dir("/tmp/mdb")
            .finish()?;
        msg_store.index_all()?;
        let contact_store = pallet::Store::builder()
            .with_db(c_db)
            .with_index_dir("/tmp/cdb")
            .finish()?;
        contact_store.index_all()?;
        let group_store = pallet::Store::builder()
            .with_db(g_db)
            .with_index_dir("/tmp/gdb")
            .finish()?;
        group_store.index_all()?;
        let profile_store = pallet::Store::builder()
            .with_db(p_db)
            .with_index_dir("/tmp/pdb")
            .finish()?;
        let pre = Presage {
            msg_store,
            contact_store,
            group_store,
            profile_store,
            whoami: None,
            res_sender,
            req_sender,
            data_dir,
        };
        // Converts all old messages stored by phone # into uuid. Probably not necessary anymore
        /*pre.contact_store.all()?.into_iter().for_each(|c| {
            println!("{:?}", c);
            if c.uuid == String::new() || c.tel == String::new() {
                return;
            }
            if let Ok(msgs) = pre.messages_id_doc(c.tel.as_str()) {
                let msgs = msgs
                    .into_iter()
                    .map(|(_i, mut d)| {
                        d.chat_id = c.uuid.clone();
                        return d;
                    })
                    .collect::<Vec<Document<SignalMessage>>>();
                pre.msg_store.update_multi(&msgs).unwrap();
            }
        });
        pre.contact_store
            .all()
            .unwrap()
            .into_iter()
            .for_each(|mut c| {
                c.inner.uuid = c.inner.uuid.to_uppercase();
                pre.contact_store.update(&c).unwrap();
            });
        pre.msg_store
            .all()
            .unwrap()
            .into_iter()
            .for_each(|mut msg| {
                msg.inner.chat_id = msg.inner.chat_id.to_uppercase();
                msg.inner.source = msg.inner.source.to_uppercase();
                pre.msg_store.update(&msg).unwrap();
            });
        pre.group_store
            .all()
            .unwrap()
            .into_iter()
            .for_each(|mut g| {
                g.inner.id = g.inner.id.to_uppercase();
                pre.group_store.update(&g).unwrap();
            });
        pre.profile_store.all().unwrap().into_iter().for_each(|p| {
            println!("{:?}", p);
        });*/
        return Ok(pre);
    }

    pub fn avatar(&self, id: &str) -> Option<String> {
        let opts = vec![
            "profile".to_string(),
            "contact".to_string(),
            "group".to_string(),
        ];
        let av_dir = Path::new(self.data_dir.as_str()).join("avatars");
        for opt in opts {
            let now_path = av_dir.join(format!("{}-{}", opt, id));
            if now_path.exists() {
                return Some(now_path.to_str().unwrap().to_string());
            }
        }
        None
    }

    pub fn set_avatar(&self, id: String, data: &[u8]) -> String {
        let path = Path::new(self.data_dir.as_str())
            .join("avatars")
            .join(format!("contact-{}", id));
        let mut fd = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .open(&path)
            .expect("Couldn't create avatar file");
        fd.write_all(data).expect("Couldn't write to avatar file");
        return path.into_os_string().into_string().unwrap();
    }

    // Adds a message to store and updates GUI
    pub fn add_message(&mut self, message: SignalMessage, new: bool) {
        if self.message(&message.chat_id, message.sent_at).is_err() {
            println!("creating");
            self.msg_store
                .create(&message)
                .expect("Couldn't add message to store");
            self.res_sender
                .send(SignalResponse::AddHist(message.clone(), new))
                .expect("Couldn't send AddHist");
        }
    }

    // Processes a SignalResponse enum and makes appropriate changes to manager state/UI state
    pub fn process_response(&mut self, response: SignalResponse) {
        match response {
            SignalResponse::RmMessage { chat_id, sent_at } => {
                if let Some(doc) = self.message_doc(&chat_id, sent_at).ok() {
                    self.msg_store
                        .delete(doc.id)
                        .expect("Couldn't delete message");
                }
            }
            SignalResponse::Metadata(meta) => {
                if let Ok(mut cont) =
                    self.contact_doc(meta.sender.identifier().to_uppercase().as_str())
                {
                    if let Some(uuid) = meta.sender.uuid {
                        if uuid.to_string().to_uppercase() != cont.inner.uuid {
                            cont.inner.uuid = uuid.to_string().to_uppercase();
                            self.contact_store
                                .update(&cont)
                                .expect("Couldn't update contact");
                        }
                    }
                    if let Some(e164) = meta.sender.e164() {
                        if e164.to_string() != cont.inner.tel {
                            cont.inner.tel = e164.to_string();
                            self.contact_store
                                .update(&cont)
                                .expect("Couldn't update contact");
                        }
                    }
                } else {
                    let name = meta
                        .sender
                        .e164()
                        .map(|x| x.to_string())
                        .unwrap_or(meta.sender.uuid.unwrap().to_string().to_uppercase())
                        .to_uppercase();
                    let contact = Contact {
                        state: "fake".into(),
                        name: "".to_string(),
                        tel: meta.sender.e164().unwrap_or_default().to_string(),
                        uuid: meta
                            .sender
                            .uuid
                            .unwrap_or_default()
                            .to_string()
                            .to_uppercase(),
                    };
                    self.contact_store.create(&contact).unwrap();
                }
            }
            SignalResponse::IDLessMessage(mut msg) => {
                let mut id = 0;
                if let Some(v) = self.messages_id(&msg.chat_id).ok() {
                    if v.len() > 0 {
                        id = v.values().map(|msg| msg.ID).max().unwrap() + 1;
                    } else {
                        println!("No previous messages");
                        self.res_sender
                            .send(SignalResponse::ContactList(vec![]))
                            .expect("Couldn't send ContactList");
                    }
                } else {
                    println!("No previous messages");
                    self.res_sender
                        .send(SignalResponse::ContactList(vec![]))
                        .expect("Couldn't send ContactList");
                }
                msg.ID = id;
                self.add_message(msg, true);
            }
            SignalResponse::RmContact(tel) => {
                if let Some(contact) = self.contact_doc(&tel).ok() {
                    self.contact_store
                        .delete(contact.id)
                        .expect("Couldn't delete contact");
                }
            }
            SignalResponse::GroupV2Context(ctx) => {
                let id = get_gid_v2(ctx.master_key.clone().unwrap());
                if ctx.group_change.is_some() || self.group_doc(id.as_str()).is_err() || true {
                    self.req_sender
                        .send(SignalRequest::GetGroupCtxV2(ctx))
                        .expect("Couldn't send GetGroupCtxV2");
                }
            }
            SignalResponse::SGroup(group) => {
                println!("{:?}", group);
                if let Ok(mut g) = self.group_doc(group.id.as_str()) {
                    g.inner = group;
                    self.group_store.update(&g).expect("Couldn't update group");
                } else {
                    self.group_store
                        .create(&group)
                        .expect("Couldn't create group");
                }
            }
            SignalResponse::ContactList(contacts) => {
                for contact in contacts.into_iter() {
                    if let Some(mut contact_p) = self.contact_doc(&contact.tel).ok() {
                        contact_p.inner = contact;
                        self.contact_store
                            .update(&contact_p)
                            .expect("Couldn't update contact");
                    } else {
                        self.contact_store
                            .create(&contact)
                            .expect("Couldn't create contact");
                    }
                }
            }
            SignalResponse::Profile(profile) => {
                println!("{:?}", profile);
                if let Ok(mut fetched) = self.profile_doc(profile.uuid.as_str()) {
                    println!("Found profile");
                    fetched.inner = profile;
                    self.profile_store
                        .update(&fetched)
                        .expect("Couldn't update profile");
                } else {
                    self.profile_store
                        .create(&profile)
                        .expect("Couldn't create profile");
                }
            }
            SignalResponse::AddReaction {
                target,
                target_timestamp,
                timestamp,
                from,
                emoji,
            } => {
                let reaction = Reaction {
                    emoji,
                    source: from,
                    timestamp,
                };
                if let Some(fetched) = self
                    .msg_store
                    .search(format!("source:{} AND sent_at:{}", target, target_timestamp).as_str())
                    .expect("Couldn't search for reaction message")
                    .hits
                    .into_iter()
                    .next()
                {
                    let mut fetched = fetched.doc;
                    fetched.inner.reactions.push(reaction);
                    self.msg_store
                        .update(&fetched)
                        .expect("Couldn't update reaction message");
                }
            }
            _ => {}
        }
    }

    // Given a chat id of any kind, resolve a relevant name. E.g. returns a contact's name/group name/etc. Returns the id if no name can be found
    pub fn resolve_name(&mut self, chat_id: &str) -> Result<String> {
        let searched_for = self
            .contact_store
            .search(format!("uuid:{} AND state:real", chat_id).as_str())
            .expect("Couldn't search for resolve contact")
            .hits
            .into_iter()
            .next();
        let profile_search = self
            .profile_store
            .all()
            .unwrap()
            .into_iter()
            .filter(|p| p.uuid.as_str() == chat_id)
            .next();
        if let Some(contact) = searched_for {
            return Ok(contact.doc.inner.name);
        } else if let Ok(group) = self.group(chat_id) {
            return Ok(group.name.clone());
        } else if let Some(profile) = profile_search {
            return Ok(profile.name.clone());
        } else {
            return Ok(chat_id.to_string());
        }
    }

    // Returns all messages, sorted by chat id and then timestamp
    pub fn messages(
        &self,
    ) -> Result<BTreeMap<String, BTreeMap<i64, SignalMessage>>, anyhow::Error> {
        let mut map: BTreeMap<String, BTreeMap<i64, SignalMessage>> = BTreeMap::new();
        for msg in self.msg_store.all()? {
            let msg = msg.inner;
            if let Some(ind) = map.get_mut(&msg.chat_id) {
                ind.insert(msg.sent_at, msg);
            } else {
                let mut new_map: BTreeMap<i64, SignalMessage> = BTreeMap::new();
                new_map.insert(msg.sent_at, msg.clone());
                map.insert(msg.chat_id.clone(), new_map);
            }
        }
        Ok(map)
    }

    // Returns any message with the given chat_id and timestamp
    pub fn message(&self, chat_id: &str, sent_at: i64) -> Result<SignalMessage> {
        Ok(self
            .msg_store
            .search(format!("chat_id:{} AND sent_at:{}", chat_id, sent_at).as_str())?
            .hits
            .into_iter()
            .next()
            .context("none")?
            .doc
            .inner
            .clone())
    }

    // Returns a message with a chat_id and timestamp, as a Document
    fn message_doc(
        &self,
        chat_id: &str,
        sent_at: i64,
    ) -> Result<Document<SignalMessage>, anyhow::Error> {
        Ok(self
            .msg_store
            .search(format!("chat_id:{} AND sent_at:{}", chat_id, sent_at).as_str())?
            .hits
            .into_iter()
            .next()
            .context("none")?
            .doc
            .clone())
    }

    // Returns all messages with a given chat_id in a BTreeMap, keyed by timestamp
    pub fn messages_id(&self, chat_id: &str) -> Result<BTreeMap<i64, SignalMessage>> {
        let messages = self
            .msg_store
            .search(format!("+chat_id:\"{}\"", chat_id).as_str())?
            .hits;
        Ok(messages
            .into_iter()
            .map(|m| {
                let m = m.doc.inner;
                (m.sent_at, m)
            })
            .collect())
    }

    // Returns all messages with a given chat_id in a BTreeMap, keyed by timestamp. Includes the pallet Document for further operations
    pub fn messages_id_doc(&self, chat_id: &str) -> Result<BTreeMap<i64, Document<SignalMessage>>> {
        let messages = self
            .msg_store
            .search(format!("+chat_id:\"{}\"", chat_id).as_str())?
            .hits;
        Ok(messages
            .into_iter()
            .map(|m| {
                let m = m.doc;
                (m.sent_at, m)
            })
            .collect())
    }

    // Returns all groups in a BTreeMap, keyed by id
    pub fn groups<'a>(&'a self) -> Result<HashMap<String, Group>> {
        Ok(self
            .group_store
            .all()?
            .into_iter()
            .map(|x| {
                let x = x.inner;
                (x.id.clone(), x)
            })
            .collect())
    }

    // Returns a group with the given id
    pub fn group(&self, chat_id: &str) -> Result<Group> {
        Ok(self
            .group_store
            .search(format!("id:{}", chat_id).as_str())?
            .hits
            .into_iter()
            .next()
            .context("none")?
            .doc
            .inner
            .clone())
    }

    // Returns a group with the given chat_id, including Document
    pub fn group_doc(&self, chat_id: &str) -> Result<Document<Group>> {
        Ok(self
            .group_store
            .search(format!("id:{}", chat_id).as_str())?
            .hits
            .into_iter()
            .next()
            .context("none")?
            .doc
            .clone())
    }

    // Returns all contacts, keyed by uuid
    pub fn contacts<'a>(&'a self) -> HashMap<String, Contact> {
        let map: HashMap<String, Contact> = self
            .contact_store
            .all()
            .unwrap()
            .into_iter()
            .map(|x| {
                let x = x.inner;
                (x.uuid.clone(), x)
            })
            .collect();
        map
    }

    // Returns any contact with the given string as either tel or uuid
    pub fn contact(&self, search: &str) -> Result<Contact> {
        Ok(self
            .contact_store
            .search(format!("uuid:{} OR tel:{}", search, search).as_str())?
            .hits
            .into_iter()
            .next()
            .context("none")?
            .doc
            .inner
            .clone())
    }

    // Returns a contact with the given string as either phone # or uuid. Includes Document
    fn contact_doc(&self, search: &str) -> Result<Document<Contact>, anyhow::Error> {
        Ok(self
            .contact_store
            .search(format!("tel:{} OR uuid:{}", search, search).as_str())?
            .hits
            .into_iter()
            .next()
            .context("none")?
            .doc
            .clone())
    }

    pub fn profile(&self, uuid: &str) -> Result<Profile> {
        println!("|{}|", uuid);
        Ok(self
            .profile_store
            .search(format!("uuid:{}", uuid).as_str())?
            .hits
            .into_iter()
            .next()
            .context("none")?
            .doc
            .inner
            .clone())
    }

    fn profile_doc(&self, uuid: &str) -> Result<Document<Profile>> {
        Ok(self
            .profile_store
            .search(format!("uuid:{}", uuid).as_str())?
            .hits
            .into_iter()
            .next()
            .context("none")?
            .doc
            .clone())
    }
}