~nicohman/signal-rs

ref: f0e05ca99d0ee6e29c5ae6b2861065856a0ee523 signal-rs/src/presage_manager.rs -rw-r--r-- 26.2 KiB
f0e05ca9 — nicohman Reorganize QML 8 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
use crate::*;
use anyhow::{Context, Result};
use futures_util::StreamExt;
use pallet::Document;
use pallet::Store;
use std::fs;
use std::path::Path;
use zkgroup::api::groups::group_params::*;
pub struct Presage {
    pub msg_store: Store<SignalMessage>,
    pub contact_store: Store<Contact>,
    pub group_store: Store<Group>,
    pub req_sender: UnboundedSender<SignalRequest>,
    pub whoami: Option<Uuid>,
    pub res_sender: glib::Sender<SignalResponse>,
}
impl Presage {
    pub async fn run(
        config_store: SledConfigStore,
        res_sender: glib::Sender<SignalResponse>,
        mut req_receiver: UnboundedReceiver<SignalRequest>,
    ) {
        let (tx, mut rx) = futures::channel::mpsc::channel::<(Metadata, ContentBody)>(100);
        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();
        let cloned_man = manager.clone();
        let x = cloned_man.receive_messages(tx);
        let mut fut = Box::pin(x);
        loop {
            tokio::select! {
                    inc = rx.next() => {
                        if let Some(response) = inc {
                            println!("{:?}", response);
                            res_sender.send(SignalResponse::Metadata(response.0.clone())).expect("Couldn't send Metadata");

                            match response.1.clone() {
                ContentBody::DataMessage(dm) => {
                    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(),
                                emoji: react.emoji.unwrap(),
                                target_timestamp: react.target_sent_timestamp.unwrap() as i64,
                                timestamp: response.0.timestamp as i64,
                                from: response.0.sender.identifier()
                            }).expect("Couldn't send AddReaction");
                            }
                        }
                    }
                    if let Some(body) = dm.body {
                        let mut chat_id = response
                            .0
                            .sender
                            .identifier();
                        if let Some(gc) = dm.group {
                            chat_id = Presage::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");
                        }
                        if let Some(gc2) = dm.group_v2 {
                            let gid = Presage::get_gid(gc2.master_key.clone().unwrap());
                            chat_id = gid;
                            res_sender.send(SignalResponse::GroupV2Context(gc2)).expect("Couldn't send GroupV2Context");
                        }
                        let msg = SignalMessage {
                            source: response
                                .0
                                .sender
                                .identifier(),
                            chat_id: chat_id,
                            sent_at: dm.timestamp.unwrap() as i64,
                            ID: 0,
                            message: body,
                            reactions: vec![],
                            attachment: Some(vec![]),
                            outgoing: response.0.sender.identifier() == 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(),
                                emoji: react.emoji.unwrap(),
                                target_timestamp: react.target_sent_timestamp.unwrap() as i64,
                                timestamp: response.0.timestamp as i64,
                                from: response.0.sender.identifier()
                            }).expect("Couldn't send AddReaction");
                            }


                        }
                    }
                            if let Some(body) = dm.body {
                                let mut chat_id = sent
                                    .destination_uuid.
                                    unwrap_or(sent.destination_e164.unwrap_or_default());
                                if let Some(gc) = dm.group {
                                    chat_id = Presage::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");
                                }
                                if let Some(gc2) = dm.group_v2 {
                                    let gid = Presage::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
                                        .0
                                        .sender.identifier(),
                                    chat_id: chat_id,
                                    sent_at: dm.timestamp.unwrap() as i64,
                                    ID: 0,
                                    message: body,
                                    reactions: vec![],
                                    attachment: Some(vec![]),
                                    outgoing: response.0.sender.identifier() == 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(),
                                    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(),
                                    chat_id: to.clone(),
                                    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}])).expect("Couldn't send ContactList");
                            },
                            SignalRequest::GetGroupCtxV2(ctx) => {
                                let group = manager.get_group_v2(Presage::make_gkey(ctx.master_key.clone().unwrap())).await.unwrap();
                                println!("{:?}", group);
                                let gid = Presage::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();
                                    }).collect()
                                })).expect("Couldn't send SGroup");
                            },
                            _ => {

                            }
                        }
                    }
                    }
                    _ = &mut fut => {

                    }
                }
        }
    }
    pub fn make_gkey(bytes: Vec<u8>) -> GroupMasterKey {
        let mut slice: [u8; 32] = Default::default();
        slice.copy_from_slice(bytes.as_slice());
        GroupMasterKey::new(slice)
    }
    pub fn new(
        res_sender: glib::Sender<SignalResponse>,
        config: Config,
        req_sender: UnboundedSender<SignalRequest>,
    ) -> Presage {
        let data_dir = config
            .data_dir
            .replace("~", home::home_dir().unwrap().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();
        let g_db =
            pallet::ext::sled::open(Path::new(&data_dir).join("groups").to_str().unwrap()).unwrap();
        fs::create_dir("/tmp/mdb");
        fs::create_dir("/tmp/cdb");
        fs::create_dir("/tmp/gdb");
        let msg_store = pallet::Store::builder()
            .with_db(m_db)
            .with_index_dir("/tmp/mdb")
            .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/cdb")
            .finish()
            .unwrap();
        contact_store
            .index_all()
            .expect("Couldn't index contact store");

        let group_store = pallet::Store::builder()
            .with_db(g_db)
            .with_index_dir("/tmp/gdb")
            .finish()
            .unwrap();
        group_store.index_all().expect("Couldn't index group store");

        //let uuid = manager.whoami().await.unwrap().uuid;
        let pre = Presage {
            msg_store,
            contact_store,
            group_store,
            whoami: None,
            res_sender,
            req_sender,
        };
        pre.contact_store.all().unwrap().into_iter().for_each(|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();
            }
        });
        return pre;
    }
    pub fn avatar(&self, id: &str) -> Option<String> {
        None
    }
    pub fn set_avatar(&self, id: String, data: &[u8]) -> String {
        return String::new();
    }
    pub fn get_gid_v2(master_key: Vec<u8>) -> String {
        let mut ar: [u8; 32] = Default::default();
        ar.copy_from_slice(&master_key);
        let secret_params = GroupSecretParams::derive_from_master_key(GroupMasterKey::new(ar));
        let gid = secret_params.get_group_identifier();
        let dec = base64::encode(gid);
        return dec;
    }
    pub fn get_gid(id: Vec<u8>) -> String {
        return base64::encode(id);
    }
    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_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().as_str()) {
                    if let Some(uuid) = meta.sender.uuid {
                        if uuid.to_string() != cont.inner.uuid {
                            cont.inner.uuid = uuid.to_string();
                            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());
                    let contact = Contact {
                        name,
                        tel: meta.sender.e164().unwrap_or_default().to_string(),
                        uuid: meta.sender.uuid.unwrap_or_default().to_string(),
                    };
                    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;
                    }
                }
                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.group(group.id.as_str()) {
                        *group_p = group;
                    } else {
                        self.groups.insert(group.id.clone(), group);
                    }
                }
            }*/
            SignalResponse::GroupV2Context(ctx) => {
                let id = Presage::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) => {
                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::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");
                }
            }
            _ => {}
        }
    }
    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 messages_id_doc<'a>(
        &'a 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())
    }
    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())
    }
    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())
    }
    fn contact_doc<'a>(&'a self, tel: &str) -> Result<Document<Contact>, anyhow::Error> {
        Ok(self
            .contact_store
            .search(format!("tel:{} OR uuid:{}", tel, tel).as_str())?
            .hits
            .into_iter()
            .next()
            .context("none")?
            .doc
            .clone())
    }
    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 Ok(group) = self.group(chat_id) {
            return Ok(group.name.clone());
        } else {
            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!("uuid:{} OR tel:{}", tel, tel).as_str())?
            .hits
            .into_iter()
            .next()
            .context("none")?
            .doc
            .inner
            .clone())
    }
    pub fn contact_tel<'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) -> Result<HashMap<String, Group>> {
        Ok(self
            .group_store
            .all()?
            .into_iter()
            .map(|x| {
                let x = x.inner;
                (x.id.clone(), x)
            })
            .collect())
    }
    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())
    }
    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.tel.clone(), x)
            })
            .collect();
        println!("{}", map.len());
        map
    }
}