~nicohman/signal-rs

ref: 65a31f5a1c4562d1f216e9fef2048f50bddb4fe3 signal-rs/src/scli.rs -rw-r--r-- 27.4 KiB
65a31f5a — nicohman More Krigami conversion and image overlay 6 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
use crate::*;
use anyhow::{Context, Result};
use dbus::message::MatchRule;
use dbus::nonblock;
use futures_util::StreamExt;
use pallet::Document;
use pallet::Store;
use std::fs;
use std::io::BufRead;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
lazy_static! {
    static ref SCLI_ATTACHMENT_DIRECTORY: String = home::home_dir()
        .unwrap()
        .join(".local/share/signal-cli/attachments/")
        .into_os_string()
        .into_string()
        .unwrap();
    static ref SCLI_AVATAR_DIRECTORY: String = home::home_dir()
        .unwrap()
        .join(".local/share/signal-cli/avatars/")
        .into_os_string()
        .into_string()
        .unwrap();
}
pub struct SCLISession {
    pub msg_store: Store<SignalMessage>,
    pub contact_store: Store<Contact>,
    pub config: SignalCLIConfig,
    pub res_sender: glib::Sender<SignalResponse>,
    pub groups: HashMap<String, Group>,
    pub proxy: nonblock::Proxy<'static, Arc<nonblock::SyncConnection>>,
    pub resolved_names: HashMap<String, Option<String>>,
    pub req_sender: UnboundedSender<SignalRequest>,
}
impl SCLISession {
    pub fn merge_ids(&self, from: String, to: String) {
        self.msg_store
            .update_multi(
                self.msg_store
                    .search(format!("chat_id:{}", from).as_str())
                    .unwrap()
                    .hits
                    .into_iter()
                    .map(|hit| {
                        let mut doc = hit.doc;
                        doc.inner.chat_id = to.clone();
                        doc
                    })
                    .collect::<Vec<Document<SignalMessage>>>()
                    .as_slice(),
            )
            .expect("Couldn't merge chatids");
    }
    pub fn fetch_contacts_scli(username: &str) -> Vec<Contact> {
        let output = Command::new("signal-cli")
            .arg("--username")
            .arg(username)
            .arg("listContacts")
            .output()
            .expect("Couldn't start listContacts");
        let res = BufRead::lines(output.stdout.as_slice())
            .into_iter()
            .filter_map(|s| SignalCLIContactInfo::from_str(s.unwrap()))
            .map(|ci| Contact {
                tel: ci.number,
                name: ci.name,
            })
            .collect();
        res
    }
    pub async fn run(
        res_sender: glib::Sender<SignalResponse>,
        mut req_receiver: UnboundedReceiver<SignalRequest>,
        config: SignalCLIConfig,
        conn: Arc<nonblock::SyncConnection>,
    ) {
        let (line_sender, mut line_receiver) =
            tokio::sync::mpsc::unbounded_channel::<SignalCLIContainer>();
        let clconf = config.clone();
        std::thread::spawn(move || {
            let mut cmd = std::process::Command::new("signal-cli");
            cmd.arg("-u")
                .arg(&clconf.username)
                .arg("daemon")
                .arg("--json")
                .stdout(Stdio::piped());
            let mut child = cmd.spawn().expect("Couldn't run signal-cli");
            let stdout = child.stdout.take().unwrap();
            let mut reader = std::io::BufReader::new(stdout).lines();
            loop {
                let msg_line = reader.next().unwrap().unwrap();
                println!("{}", msg_line);
                if let Some(parsed) = serde_json::from_str::<SignalCLIContainer>(&msg_line).ok() {
                    line_sender
                        .send(parsed)
                        .expect("Couldn't send parsed line from scli daemon");
                } else {
                    println!("Could not parsed SCLI message {}", msg_line);
                }
            }
        });
        let proxy = nonblock::Proxy::new(
            "org.asamk.Signal",
            "/org/asamk/Signal",
            Duration::from_secs(10),
            conn.clone(),
        );
        let mr_mr = MatchRule::new_signal("org.asamk.Signal", "MessageReceived");
        let sy_mr = MatchRule::new_signal("org.asamk.Signal", "SyncMessageReceived");
        let _inc = conn.add_match(mr_mr).await.unwrap().msg_stream();
        let _inc_sync = conn.add_match(sy_mr).await.unwrap().msg_stream();
        // Wait to start main select loop until signal-cli's dbus service is up and working
        loop {
            let opts: Result<(Vec<Vec<u8>>,), dbus::Error> = proxy
                .method_call("org.asamk.Signal", "getGroupIds", ())
                .await;
            if opts.is_ok() {
                break;
            }
            std::thread::sleep(Duration::from_millis(500));
        }
        // NOTE: HOLY SHIT GO DBUS
        loop {
            tokio::select! {
                parsed = line_receiver.next() => {
                    let parsed = parsed.unwrap();
                    if let Some(ref data_msg) = parsed.envelope.data_message {
                        if let Some(react) = &data_msg.reaction {
                            res_sender.send(SignalResponse::AddReaction {
                                emoji: react.emoji.clone(),
                                target: react.target_author.clone(),
                                from: parsed.envelope.source.clone(),
                                target_timestamp: react.target_sent_timestamp,
                                timestamp: parsed.envelope.timestamp
                            }).expect("Couldn't send AddReaction");
                        } else {
                            let mut attachment = vec![];
                            if let Some(ats) = &data_msg.attachments {
                                attachment = parse_attachments(ats);
                            }
                            let mut chat_id = parsed.envelope.source.clone();
                            if let Some(group_info) = &data_msg.group_info {
                                chat_id = group_info.group_id.clone();
                            }
                            let outgoing = config.username == parsed.envelope.source;
                            let con_msg = SignalMessage {
                                message: data_msg.message.clone().unwrap_or_default(),
                                ID: 0,
                                outgoing,
                                attachment: Some(attachment),
                                source: parsed.envelope.source.clone(),
                                sent_at: parsed.envelope.timestamp,
                                chat_id,
                                reactions: vec![]
                            };
                            res_sender.send(SignalResponse::IDLessMessage(con_msg)).expect("Couldn't send IDLessMessage");
                        }
                    } else if let Some(ref sync_msg) = parsed.envelope.sync_message {
                        if let Some(sm) = &sync_msg.sent_message {
                            if let Some(react) = &sm.reaction {
                                res_sender.send(SignalResponse::AddReaction {
                                    emoji: react.emoji.clone(),
                                    target: react.target_author.clone(),
                                    from: parsed.envelope.source.clone(),
                                    target_timestamp: react.target_sent_timestamp,
                                    timestamp: parsed.envelope.timestamp
                                }).expect("Couldn't send AddReaction");
                            } else {
                            let mut outgoing = false;
                            let mut source = parsed.envelope.source.clone();
                            if parsed.envelope.source == config.username {
                                outgoing = true;
                                if let Some(ref _group_info) = sm.group_info {
                                    //source = group_info.group_id.clone();
                                } else {
                                    source = sm.destination.clone().unwrap();
                                }
                            }
                            let mut attachment = vec![];
                            if let Some(ats) = &sm.attachments {
                                attachment = parse_attachments(ats);
                            }
                            let mut chat_id = source.clone();
                            if let Some(group_info) = &sm.group_info {
                                chat_id = group_info.group_id.clone();
                            }
                            let con_msg = SignalMessage {
                                message: sm.message.clone().unwrap_or_default(),
                                ID: 0,
                                outgoing,
                                attachment: Some(attachment),
                                source,
                                sent_at: parsed.envelope.timestamp,
                                chat_id,
                                reactions: vec![]
                            };
                            res_sender.send(SignalResponse::IDLessMessage(con_msg)).expect("Couldn't send IDLessMessage");
                        }
                    }
                    }
                }
                inc = req_receiver.recv() => {
                    if let Some(v) = inc {
                        match v {
                            SignalRequest::GetContacts => {
                                println!("Getting contacts");
                                //let contacts = Self::fetch_contacts_scli(config.username.as_str());
                                //res_sender.send(SignalResponse::ContactList(contacts)).expect("Can't send ContactList");
                            }
                            SignalRequest::GetGroups => {
                                let (ids, ) : (Vec<Vec<u8>>, ) = proxy.method_call("org.asamk.Signal", "getGroupIds", ()).await.unwrap();
                                let mut groups: Vec<Group> = vec![];
                                for id in ids.into_iter() {
                                    let parsed_id = base64::encode(&id);
                                    let (group_members, ) : (Vec<String>, ) = proxy.method_call("org.asamk.Signal", "getGroupMembers", (id.clone(),)).await.unwrap();
                                    let (group_name, ) : (String, ) =  proxy.method_call("org.asamk.Signal", "getGroupName", (id,)).await.unwrap();
                                    groups.push(Group {
                                        name: group_name,
                                        members: group_members,
                                        id: parsed_id
                                    });
                                }
                                res_sender.send(SignalResponse::Groups(groups)).expect("Couldn't send Groups");
                            }
                            SignalRequest::SendGroupMessage {chat_id, message, attachment} => {
                                let (timestamp, ) : (i64,) = proxy.method_call("org.asamk.Signal", "sendGroupMessage", (&message, attachment.clone().unwrap_or_default(), base64::decode(&chat_id).expect("Couldn't decode group id"))).await.unwrap();
                                res_sender.send(SignalResponse::IDLessMessage(SignalMessage {
                                    message: message,
                                    source: config.username.clone(),
                                    outgoing: true,
                                    attachment: attachment.map(|x| {
                                        x.into_iter().map(|x| {
                                        let path = PathBuf::from(x.clone());
                                        let mut ctype = AttachmentType::File;
                                        if x.contains("png") || x.contains("jpg") || x.contains("jpeg") {
                                            ctype = AttachmentType::Image;
                                        }

                                         Attachment {
                                            file_name: path.file_name().unwrap().to_str().unwrap().to_string(),
                                            file: x,
                                            c_type: ctype
                                        }
                                        }).collect()
                                    }),
                                    sent_at: timestamp,
                                    chat_id: chat_id,
                                    ID: 0,
                                    reactions: vec![]
                                })).expect("Couldnt send IDLessMessage");
                            }
                            SignalRequest::SendMessage { to, message, attachment } => {
                                let (timestamp,) : (i64,) = proxy.method_call("org.asamk.Signal", "sendMessage", (&message,attachment.clone().unwrap_or_default(), vec![&to] )).await.unwrap();
                                res_sender.send(SignalResponse::IDLessMessage(SignalMessage {
                                    message: message,
                                    source: to.clone(),
                                    outgoing: true,
                                    attachment: attachment.map(|x| {
                                        x.into_iter().map(|x| {


                                        let path = PathBuf::from(x.clone());
                                        let mut ctype = AttachmentType::File;
                                        if x.contains("png") || x.contains("jpg") || x.contains("jpeg") {
                                            ctype = AttachmentType::Image;
                                        }

                                         Attachment {
                                            file_name: path.file_name().unwrap().to_str().unwrap().to_string(),
                                            file: x,
                                            c_type: ctype
                                        }
                                        }).collect()
                                    }),
                                    sent_at: timestamp,
                                    chat_id: to,
                                    ID: 0,
                                    reactions: vec![]
                                })).expect("Couldnt send IDLessMessage");
                            },
                            SignalRequest::GetContactName { chat_id } => {
                                let (name,): (String,) = proxy.method_call("org.asamk.Signal", "getContactName", (chat_id.clone(), )).await.unwrap();
                                res_sender.send(SignalResponse::ContactList(vec![Contact {name, tel: chat_id}])).expect("Couldn't send ContactList");
                            },
                            SignalRequest::AddContact{ name, phone} => {
                                res_sender.send(SignalResponse::ContactList(vec![Contact {name, tel: phone}])).expect("Couldn't send ContactList");
                            },
                            SignalRequest::EditContact{ name, phone, id } => {
                                res_sender.send(SignalResponse::RmContact(id)).expect("Couldn't send RmContact");
                                res_sender.send(SignalResponse::ContactList(vec![Contact {name, tel: phone}])).expect("Couldn't send ContactList");
                            },
                            _ => {

                            }
                        }
                    }
                }
            }
        }
        //unreachable!();
        //conn.remove_match(_inc.0.token()).await.unwrap();
    }
    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");
        }
    }

    pub fn process_scli_msg(&mut self, mut msg: SignalCLIMessage) {
        let message: Option<String>;
        let mut outgoing = false;
        let chat_id = msg.source.clone();
        if let Some(m) = msg.message {
            println!("text");
            message = Some(m);
        } else if let Some(data) = msg.data_message {
            message = data.message;
            if let Some(dest) = data.destination {
                if msg.source == self.config.username {
                    outgoing = true;
                    msg.source = dest;
                }
            }
        } else {
            println!("Return early");
            return;
        }
        if let Some(v) = self.messages_id(&chat_id).ok() {
            let last_id = v.values().map(|msg| msg.ID).max().unwrap();
            let made_msg = SignalMessage {
                ID: last_id + 1,
                source: msg.source,
                message: message.unwrap(),
                outgoing,
                sent_at: msg.timestamp,
                attachment: None,
                chat_id,
                reactions: vec![],
            };
            self.add_message(made_msg, true);
        } else {
            let made_msg = SignalMessage {
                ID: 0,
                source: msg.source,
                message: message.unwrap(),
                outgoing,
                sent_at: msg.timestamp,
                attachment: None,
                chat_id,
                reactions: vec![],
            };
            self.add_message(made_msg, true);
        }
    }
    fn message_doc<'a>(
        &'a 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())
    }
    fn contact_doc<'a>(&'a self, tel: &str) -> Result<Document<Contact>, anyhow::Error> {
        Ok(self
            .contact_store
            .search(format!("tel:{}", tel).as_str())?
            .hits
            .into_iter()
            .next()
            .context("none")?
            .doc
            .clone())
    }
    pub fn avatar(&self, id: &str) -> Option<String> {
        let opts = vec![
            "profile".to_string(),
            "contact".to_string(),
            "group".to_string(),
        ];
        let av_dir = PathBuf::from(SCLI_AVATAR_DIRECTORY.to_owned());
        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 = PathBuf::from(SCLI_AVATAR_DIRECTORY.to_owned()).join(format!("contact-{}", id));
        let mut fd = fs::File::create(&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();
    }
    pub fn new(
        res_sender: glib::Sender<SignalResponse>,
        config: Config,
        conn: Arc<nonblock::SyncConnection>,
        req_sender: UnboundedSender<SignalRequest>,
    ) -> SCLISession {
        let scli_config = config.scli.expect("No configured SCLI settings");
        let data_dir = scli_config.data_dir.clone().replace(
            "~",
            home::home_dir()
                .expect("Couldn't get home dir")
                .to_str()
                .unwrap(),
        );
        let m_db = pallet::ext::sled::open(Path::new(&data_dir).join("messages").to_str().unwrap())
            .unwrap();
        let c_db = pallet::ext::sled::open(Path::new(&data_dir).join("contacts").to_str().unwrap())
            .unwrap();
        fs::create_dir("/tmp/sclim");
        fs::create_dir("/tmp/sclic");
        let msg_store = pallet::Store::builder()
            .with_db(m_db)
            .with_index_dir("/tmp/sclim")
            .finish()
            .unwrap();
        msg_store.index_all().expect("Couldn't index message store");
        let contact_store = pallet::Store::builder()
            .with_db(c_db)
            .with_index_dir("/tmp/sclic")
            .finish()
            .unwrap();
        contact_store
            .index_all()
            .expect("Couldn't index contact store");
        let proxy = nonblock::Proxy::new(
            "org.asamk.Signal",
            "/org/asamk/Signal",
            Duration::from_secs(10),
            conn.clone(),
        );
        let session = SCLISession {
            res_sender,
            config: scli_config,
            msg_store,
            contact_store,
            groups: HashMap::new(),
            proxy,
            resolved_names: HashMap::new(),
            req_sender,
        };
        session
    }
    pub fn messages_id<'a>(&'a 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())
    }
    pub fn resolve_name(&mut self, chat_id: &str) -> Result<String> {
        if let Some(contact) = self.contact(chat_id.clone()).ok() {
            return Ok(contact.name);
        } else if let Some(group) = self.groups().get(chat_id) {
            return Ok(group.name.clone());
        } else if let Some(name) = self.resolved_names.get(chat_id) {
            if let Some(name) = name {
                return Ok(name.to_string());
            } else {
                return Ok(chat_id.to_string());
            }
        } else {
            self.req_sender
                .send(SignalRequest::GetContactName {
                    chat_id: chat_id.to_string(),
                })
                .expect("Couldn't send GetContactName");
            self.resolved_names.insert(chat_id.to_string(), None);
            return Ok(chat_id.to_string());
        }
    }
    pub fn messages<'a>(
        &'a 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)
    }
    pub fn message<'a>(&'a 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())
    }
    pub fn contact<'a>(&'a self, tel: &str) -> Result<Contact> {
        Ok(self
            .contact_store
            .search(format!("tel:{}", tel).as_str())?
            .hits
            .into_iter()
            .next()
            .context("none")?
            .doc
            .inner
            .clone())
    }
    pub fn groups<'a>(&'a self) -> HashMap<String, Group> {
        self.groups.clone()
    }
    pub fn contacts<'a>(&'a self) -> HashMap<String, Contact> {
        let map = self
            .contact_store
            .all()
            .unwrap()
            .into_iter()
            .map(|x| {
                let x = x.inner;
                (x.tel.clone(), x)
            })
            .collect();
        map
    }
    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::SignalCLIEnvelope(msg) => {
                println!("Processing");
                self.process_scli_msg(msg);
            }
            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;
                    }
                }
                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::Groups(groups) => {
                for group in groups.into_iter() {
                    if let Some(group_p) = self.groups.get_mut(&group.id) {
                        *group_p = group;
                    } else {
                        self.groups.insert(group.id.clone(), 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::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");
                }
            }
            _ => {}
        }
    }
}
/// Turns a vec of SignalCLIAttachments into their Attachment counterparts
pub fn parse_attachments(catt: &Vec<SignalCLIAttachment>) -> Vec<Attachment> {
    catt.into_iter()
        .map(|x| Attachment {
            file: SCLI_ATTACHMENT_DIRECTORY.to_owned() + &x.id,
            file_name: x.filename.clone().unwrap_or(x.id.to_string()),
            c_type: AttachmentType::from_mime(&x.content_type),
        })
        .collect()
}