~nicohman/signal-rs

ref: 5084c926fb753fdc6dda5f3cc2c8af2df5f1190b signal-rs/src/main.rs -rw-r--r-- 20.9 KiB
5084c926 — nicohman Make SignalUI a singleton and add application icon 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
/*
 * Copyright (C) 2021  Nico Hickman
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3.
 *
 * signal-rs is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#![feature(async_closure)]
use cpp::cpp;
use presage::prelude::*;
use presage::*;
use qmetaobject::QAbstractListModel;
use qmetaobject::*;
use std::any::Any;
use std::ffi::CStr;
use std::io::Read;
use tokio::sync::mpsc::*;
#[allow(non_snake_case)]
mod signal;
use signal::*;
use std::collections::*;
mod config;
mod util;
use config::*;
use futures::io::AsyncWrite;
use notify_rust::Notification;
use serde_json::json;
use std::cell::*;
use std::path::PathBuf;
use std::result::Result;
mod presage_manager;
mod registration;
use presage_manager::*;
#[derive(QObject, Default)]
pub struct SignalUI {
    base: qt_base_class!(trait QObject),
    state: Option<Presage>,
    name: qt_property!(QString; NOTIFY name_changed),
    name_changed: qt_signal!(),
    init_state: qt_method!(fn(&mut self)),
    show_view: qt_method!(fn(&mut self, view: String)),
    signalResponse: qt_signal!(response: String),
    chats: qt_property!(RefCell<SimpleListModel<Chat>>; NOTIFY chats_changed),
    messages: qt_property!(RefCell<SimpleListModel<QMLSignalMessage>>; NOTIFY msgs_changed),
    current_messages: qt_property!(String),
    contacts: qt_property!(RefCell<SimpleListModel<Contact>>; NOTIFY contacts_changed),
    contacts_changed: qt_signal!(),
    msgs_changed: qt_signal!(),
    chats_changed: qt_signal!(),
    show_chat: qt_method!(fn(&self, tel: String)),
    add_contact: qt_method!(fn(&self, name: String, tel: String)),
    send_message: qt_method!(fn(&self, to: String, message: String, attachment: String)),
    edit_contact: qt_method!(fn(&self, name: String, tel: String, id: String)),
    contact: qt_method!(fn(&self, tel: String) -> String),
    del_message: qt_method!(fn(&self, chat_id: String, sent_at: i64)),
    ready: qt_signal!(),
    message: qt_method!(fn(&self, chat_id: String, sent_at: i64) -> String),
    group: qt_method!(fn(&self, chat_id: String) -> String),
    resolve_name: qt_method!(fn(&self, source: String) -> String),
    avatar: qt_method!(fn(&self, id: String) -> QString),
    set_avatar: qt_method!(fn(&self, id: String, path: String) -> String),
    send_group_message: qt_method!(fn(&self, chat_id: String, message: String, attachment: String)),
    remove_from_group: qt_method!(fn(&self, group_id: String, phone: String)),
    get_cfg: qt_method!(fn(&self, key: String) -> String),
    set_cfg: qt_method!(fn(&mut self, key: String, value: String)),
    config: Option<Config>,
}
impl SignalUI {
    fn remove_from_group(&self, group_id: String, phone: String) {
        self.send_req(SignalRequest::RemoveFromGroup {
            group_id,
            contact: phone,
        });
    }

    fn get_cfg(&self, key: String) -> String {
        match key.as_str() {
            "notifications" => {
                return serde_json::to_string(&self.config.as_ref().unwrap().notifications)
                    .unwrap();
            }
            _ => {
                println!("Unrecognized config key: {}", key);
                return "".into();
            }
        }
    }

    fn set_cfg(&mut self, key: String, value: String) {
        self.config = self.config.clone().map(|mut cfg| {
            match key.as_str() {
                "notifications" => {
                    cfg.notifications = serde_json::from_value(json!(value))
                        .expect("Couldn't parse notifications policy value");
                }
                _ => {
                    println!("Unrecognized config key: {}", key);
                }
            }
            confy::store("signal-rs", cfg.clone()).expect("Couldn't store config");
            return cfg;
        });
    }

    fn group(&self, chat_id: String) -> String {
        serde_json::to_string(&self.state.as_ref().unwrap().group(&chat_id).unwrap()).unwrap()
    }

    fn message(&self, chat_id: String, sent_at: i64) -> String {
        if let Ok(msg) = self
            .state
            .as_ref()
            .unwrap()
            .message(chat_id.as_str(), sent_at)
        {
            serde_json::to_string_pretty(&msg).unwrap()
        } else {
            "".into()
        }
    }

    fn send_res(&self, resp: SignalResponse) {
        self.state
            .as_ref()
            .unwrap()
            .res_sender
            .send(resp)
            .expect("Couldn't send SignalResponse");
    }

    fn send_req(&self, reqp: SignalRequest) {
        self.state
            .as_ref()
            .unwrap()
            .req_sender
            .send(reqp)
            .expect("Couldn't send SignalRequest");
    }

    fn del_message(&self, chat_id: String, sent_at: i64) {
        self.send_res(SignalResponse::RmMessage { chat_id, sent_at });
    }

    fn avatar(&self, id: String) -> QString {
        QString::from(self.state.as_ref().unwrap().avatar(&id).unwrap_or_default())
    }

    fn set_avatar(&self, id: String, path: String) -> String {
        let mut data: Vec<u8> = vec![];
        std::fs::File::open(path)
            .unwrap()
            .read_to_end(&mut data)
            .unwrap();
        self.state.as_ref().unwrap().set_avatar(id, &data)
    }

    fn contact(&self, tel: String) -> String {
        let fetched = self
            .state
            .as_ref()
            .unwrap()
            .contact(&tel)
            .unwrap_or_default();
        serde_json::to_string(&fetched).unwrap()
    }

    fn update_chat(&mut self, chat_id: String) {
        let name = self.resolve_name(chat_id.clone());
        if let Some(msgs) = self.state.as_ref().unwrap().messages_id(&chat_id).ok() {
            if msgs.len() > 0 {
                let latest = msgs.values().max_by_key(|x| x.sent_at).unwrap();
                let mut chats = self.chats.borrow_mut();
                for i in 0..chats.row_count() as usize {
                    let mut chat = chats[i].clone();
                    if chat.tel == chat_id {
                        chat.name = name.clone();
                        chat.last = latest.message.clone();
                        chat.timestamp = latest.sent_at;
                        chat.messages = vec![latest.clone()];
                        chats.remove(i);
                        chats.insert(0, chat);
                        break;
                    }
                }
            }
        }
    }

    fn edit_contact(&self, name: String, tel: String, id: String) {
        self.send_req(SignalRequest::EditContact {
            name,
            phone: tel,
            id,
        });
    }

    fn send_message(&self, to: String, message: String, attachment: String) {
        let attachment = match attachment.len() {
            0 => None,
            _ => Some(vec![attachment]),
        };
        self.send_req(SignalRequest::SendMessage {
            to,
            message,
            attachment,
        });
    }

    fn send_group_message(&self, chat_id: String, message: String, attachment: String) {
        let attachment = match attachment.len() {
            0 => None,
            _ => Some(vec![attachment]),
        };
        let group = self.state.as_ref().unwrap().group(&chat_id).unwrap();
        self.send_req(SignalRequest::SendMessageToGroup {
            members: group.members,
            message,
            attachment,
            id: chat_id,
            master_key: group.master_key,
        });
    }

    fn add_contact(&self, name: String, tel: String) {
        self.send_req(SignalRequest::EditContact {
            name,
            phone: tel,
            id: "".to_string(),
        });
    }

    fn show_chat(&mut self, view: String) {
        self.messages.replace(
            self.state
                .as_ref()
                .unwrap()
                .messages_id(view.as_str())
                .unwrap()
                .values()
                .cloned()
                .rev()
                .map(|x| QMLSignalMessage::from_msg(x))
                .collect(),
        );
        self.msgs_changed();
        self.current_messages = view.clone();
        if let Some(map) = self.state.as_ref().unwrap().messages_id(&view).ok() {
            self.state
                .as_ref()
                .unwrap()
                .res_sender
                .send(SignalResponse::HistoryMessage {
                    phone: view,
                    messages: map.values().cloned().collect(),
                })
                .expect("Couldn't send HistoryMessage");
        }
    }

    fn init_state(&mut self) {
        let qptr = QPointer::from(&*self);

        let config: Config = confy::load("signal-rs").expect("Couldn't handle config file");
        self.config.replace(config.clone());
        let process_res = queued_callback(move |res: SignalResponse| {
            qptr.as_pinned().map(move |self_| {
                let ref mut slf = self_.borrow_mut();
                slf.state.as_mut().unwrap().process_response(res.clone());
                match res {
                    SignalResponse::ChatList(ref chats) => {
                        println!("Updating chats");
                        slf.chats.borrow_mut().reset_data(chats.clone());
                        slf.chats_changed();
                    }
                    SignalResponse::ContactList(_) => {
                        println!("Received ContactList");
                        slf.update_chats();
                    }
                    SignalResponse::ModelContactList(contacts) => {
                        slf.contacts.borrow_mut().reset_data(contacts);
                        slf.contacts_changed();
                    }
                    SignalResponse::AddHist(ref msg, new) => {
                        if new {
                            if msg.chat_id == slf.current_messages {
                                slf.messages
                                    .get_mut()
                                    .insert(0, QMLSignalMessage::from_msg(msg.clone()));
                            }
                            if slf.config.as_ref().unwrap().notifications
                                == NotificationPolicy::Enabled
                            {
                                Notification::new()
                                    .summary(&slf.resolve_name(msg.source.clone()))
                                    .body(msg.message.as_str())
                                    .show()
                                    .unwrap();
                            }
                            slf.update_chat(msg.chat_id.clone());
                        }
                    }
                    SignalResponse::RmMessage {
                        ref chat_id,
                        sent_at,
                    } => {
                        if &slf.current_messages == chat_id {
                            let ref mut msg_model = slf.messages.get_mut();
                            let count = msg_model.row_count() as usize;
                            for i in 0..count {
                                if msg_model[i].sent_at == sent_at {
                                    msg_model.remove(i);
                                    break;
                                }
                            }
                        }
                    }
                    SignalResponse::Groups(_) => {
                        let ids = slf
                            .state
                            .as_mut()
                            .unwrap()
                            .msg_store
                            .all()
                            .unwrap()
                            .into_iter()
                            .map(|x| {
                                return x.inner.source;
                            })
                            .collect::<Vec<String>>();
                        let mut done: HashMap<String, bool> = HashMap::new();
                        for id in ids {
                            if !done.contains_key(id.as_str()) {
                                done.insert(id.clone(), true);
                                slf.state.as_mut().unwrap().resolve_name(&id).unwrap();
                            }
                        }
                        println!("Finished initialization");
                        slf.update_contacts();
                        slf.show_view("chats".to_string());
                        slf.ready();
                        slf.chats_changed();
                        slf.signalResponse(serde_json::to_string(&res).unwrap());
                    }
                    _ => {}
                };
            });
        });
        let (res_sender, mut res_receiver) = unbounded_channel::<SignalResponse>();
        let (req_sender, req_receiver) = unbounded_channel::<SignalRequest>();

        self.state = Some(
            Presage::new(res_sender.clone(), config.clone(), req_sender.clone())
                .expect("Couldn't create Presage"),
        );
        // Spawn a tokio task to receive the SignalResponses and call the Qt callback w/ them
        tokio::task::spawn(async move {
            loop {
                let next = res_receiver
                    .recv()
                    .await
                    .expect("SignalResponse channel dropped");
                process_res(next);
            }
        });
        res_sender
            .send(SignalResponse::Groups(vec![]))
            .expect("Couldn't send Groups");
        let cstore_path = PathBuf::from(
            config
                .clone()
                .data_dir
                .clone()
                .replace("~", home::home_dir().unwrap().to_str().unwrap()),
        );
        // Run the presage thread
        qmetaobject::future::execute_async(async move {
            Presage::run(
                presage::SledConfigStore::new(cstore_path.join(PathBuf::from("cstore"))).unwrap(),
                res_sender,
                req_receiver,
                config,
            )
            .await;
        });
    }

    /// Shows the given view in the app_box
    pub fn show_view(&mut self, view: String) {
        match view.as_ref() {
            "chats" => {
                self.update_chats();
            }
            "createChat" => {
                self.update_contacts();
            }
            _ => {}
        }
    }

    pub fn update_chats(&mut self) {
        let mut constructed: Vec<String> = vec![];
        let mut chats: Vec<Chat> = self
            .state
            .as_ref()
            .unwrap()
            .contacts()
            .values()
            .enumerate()
            .filter_map(|(i, contact)| {
                if let Some(msgs) = self.state.as_ref().unwrap().messages_id(&contact.uuid).ok() {
                    if msgs.len() > 0 {
                        let latest = msgs.values().max_by_key(|x| x.sent_at).unwrap();
                        constructed.push(contact.uuid.clone());
                        return Some(Chat {
                            ID: i as i32,
                            name: self.resolve_name(contact.uuid.clone()),
                            tel: contact.uuid.clone(),
                            is_group: false,
                            last: latest.message.clone(),
                            timestamp: latest.sent_at,
                            messages: vec![latest.clone()],
                        });
                    }
                }
                None
            })
            .collect();
        for (i, (gid, group)) in self
            .state
            .as_ref()
            .unwrap()
            .groups()
            .unwrap()
            .into_iter()
            .enumerate()
        {
            if let Some(msgs) = self.state.as_ref().unwrap().messages_id(&gid).ok() {
                if msgs.len() > 0 {
                    let latest = msgs.values().max_by_key(|x| x.sent_at).unwrap();
                    constructed.push(gid.clone());
                    chats.push(Chat {
                        ID: (chats.len() + i) as i32,
                        name: group.name,
                        tel: gid,
                        is_group: true,
                        last: latest.message.clone(),
                        timestamp: latest.sent_at,
                        messages: vec![latest.clone()],
                    });
                }
            }
        }
        for (i, (id, msgs)) in self
            .state
            .as_ref()
            .unwrap()
            .messages()
            .unwrap()
            .into_iter()
            .filter(|(id, _msgs)| !constructed.contains(&id))
            .enumerate()
        {
            if msgs.len() > 0 {
                println!("not found - {}", id);
                let latest = msgs.values().max_by_key(|x| x.sent_at).unwrap();
                if latest.message.as_str() == "🧝\u{200d}\u{fe0f}" {
                    println!("{:?} - {}", latest, id);
                }
                chats.push(Chat {
                    ID: (chats.len() + i) as i32,
                    name: self.resolve_name(id.clone()),
                    tel: id,
                    is_group: false,
                    last: latest.message.clone(),
                    timestamp: latest.sent_at,
                    messages: msgs.values().cloned().collect(),
                })
            }
        }
        chats.sort_by_key(|c| -1 * c.timestamp);
        self.send_res(SignalResponse::ChatList(chats));
    }

    pub fn resolve_name(&mut self, source: String) -> String {
        return self
            .state
            .as_mut()
            .unwrap()
            .resolve_name(source.as_str())
            .unwrap();
    }

    pub fn update_contacts(&self) {
        let mut contacts: Vec<Contact> = self
            .state
            .as_ref()
            .unwrap()
            .contacts()
            .into_iter()
            .map(|(_k, v)| v)
            .collect();
        contacts.sort_by_key(|x| x.name.clone());
        self.send_res(SignalResponse::ModelContactList(contacts));
    }
}
impl QSingletonInit for SignalUI {
    fn init(&mut self) {
        println!("Initing");
        self.init_state();
    }
}
/// An enum that represents a view that can be displayed.
#[derive(Clone, Debug)]
pub enum View {
    Chats,
    /// Contains the telephone number of the chat to show
    Messages(String),
    Password,
    CreateChat,
    CreateContact,
    /// Contains the ID of the contact to edit
    EditContact(String),
    Settings,
}

mod qrc;

#[tokio::main]
async fn main() -> Result<(), std::boxed::Box<dyn std::error::Error>> {
    let conf: Config = confy::load("signal-rs").unwrap();
    let data_dir = conf
        .data_dir
        .replace("~", home::home_dir().unwrap().to_str().unwrap());
    let config_store =
        presage::SledConfigStore::new(PathBuf::from(data_dir).join(PathBuf::from("cstore")))
            .unwrap();
    // Check if the user is registered or not
    let registered = match config_store.state()? {
        State::Registered { .. } => true,
        _ => false,
    };
    // Manually drop config store so that it doesn't block when starting the actual config store for the RegistrationController/SignalUI
    drop(config_store);
    unsafe {
        cpp! { {
            #include <QtCore/QCoreApplication>
            #include <QtCore/QString>
            #include <QtWidgets/QWidget>
            #include <QtWidgets/QApplication>
            #include <QtGui/QIcon>
        }}
        cpp! ([] {
            QCoreApplication::setApplicationName(QStringLiteral("signal-rs.nicohman"));
            QCoreApplication::setOrganizationDomain(QStringLiteral("nicohman.com"));
            QCoreApplication::setOrganizationName(QStringLiteral("signal-rs.nicohman"));
            QApplication::setWindowIcon(QIcon::fromTheme(QStringLiteral("signal-desktop")));
        });
    }
    qrc::load();
    if registered {
        qml_register_singleton_type::<SignalUI>(
            CStr::from_bytes_with_nul(b"SignalUI\0").unwrap(),
            0,
            1,
            CStr::from_bytes_with_nul(b"SignalUI\0").unwrap(),
        );
        let mut engine = QmlEngine::new();
        engine.load_file("qrc:/qml/main.qml".into());

        engine.exec();
    } else {
        // Init webengine for the captcha page
        webengine::initialize();
        qml_register_type::<registration::RegistrationController>(
            CStr::from_bytes_with_nul(b"RegistrationController\0").unwrap(),
            0,
            1,
            CStr::from_bytes_with_nul(b"RegistrationController\0").unwrap(),
        );
        let mut engine = QmlEngine::new();

        engine.load_file("qrc:/qml/Registration.qml".into());
        engine.exec();
    }
    println!("Shutting down");
    Ok(())
}