~nicohman/signal-rs

ref: 21d519db83d3c672c89259ac11661434f0dbdc34 signal-rs/src/main.rs -rw-r--r-- 20.2 KiB
21d519db — nicohman Save to try kirigami 7 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
/*
 * 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-ut 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(type_alias_impl_trait)]
#![feature(async_closure)]
#[macro_use]
extern crate cstr;
#[macro_use]
extern crate cpp;
#[macro_use]
extern crate qmetaobject;
extern crate confy;
extern crate crossbeam_channel;
extern crate dbus;
extern crate enum_variant_type;
extern crate futures_util;
extern crate glib;
extern crate mio;
extern crate notify_rust;
extern crate reqwest;
extern crate serde;
#[macro_use]
extern crate pallet;
extern crate dbus_tokio;
extern crate home;
extern crate serde_json;

extern crate tempfile;
use std::io::Read;
use std::sync::Arc;
extern crate tokio;
use std::ffi::CStr;
extern crate tungstenite;
#[macro_use]
extern crate lazy_static;
use dbus::*;
use dbus_tokio::connection;
use qmetaobject::QAbstractListModel;
use qmetaobject::*;
use tokio::sync::mpsc::*;

#[allow(non_snake_case)]
mod signal;
use signal::*;
use std::collections::*;

mod config;
use config::*;
use gettextrs::{bindtextdomain, textdomain};
use notify_rust::Notification;
use signal::signal_cli::*;
use std::cell::*;
use std::env;
use std::path::PathBuf;
use std::process::Command;
use std::rc::*;
use std::result::Result;
mod scli;
#[derive(QObject, Default)]
pub struct SignalUI {
    base: qt_base_class!(trait QObject),
    state: Option<SignalState>,
    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!(),
    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)),
}
impl SignalUI {
    fn send_res(&self, resp: SignalResponse) {
        self.state
            .as_ref()
            .unwrap()
            .sbackend
            .res_sender
            .send(resp)
            .expect("Couldn't send SignalResponse");
    }
    fn send_req(&self, reqp: SignalRequest) {
        self.state
            .as_ref()
            .unwrap()
            .sbackend
            .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 });
        /*self.state
        .as_ref()
        .unwrap()
        .sbackend
        .res_sender
        .send()
        .expect("Couldn't send RmMessage");*/
    }
    fn avatar(&self, id: String) -> QString {
        QString::from(
            self.state
                .as_ref()
                .unwrap()
                .sbackend
                .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().sbackend.set_avatar(id, &data)
    }
    fn contact(&self, tel: String) -> String {
        let fetched = self
            .state
            .as_ref()
            .unwrap()
            .sbackend
            .contact(&tel)
            .unwrap_or_default();
        serde_json::to_string(&fetched).unwrap()
    }
    fn edit_contact(&self, name: String, tel: String, id: String) {
        self.send_req(SignalRequest::EditContact {
            name,
            phone: tel,
            id,
        });
        /*self.state
        .as_ref()
        .unwrap()
        .req_sender
        .send()
        .expect("Couldn't send EditContact");*/
    }
    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,
        });
        /*        self.state
        .as_ref()
        .unwrap()
        .req_sender
        .send()
        .expect("Couldn't send SendMessage");*/
    }
    fn resolve_name(&mut self, source: String) -> String {
        self.state.as_mut().unwrap().resolve_name(source)
    }
    fn send_group_message(&self, chat_id: String, message: String, attachment: String) {
        let attachment = match attachment.len() {
            0 => None,
            _ => Some(vec![attachment]),
        };
        self.send_req(SignalRequest::SendGroupMessage {
            chat_id,
            message,
            attachment,
        });
        /*self.state
        .as_ref()
        .unwrap()
        .req_sender
        .send()
        .expect("Couldn't send SendGroupMessage");*/
    }
    fn add_contact(&self, name: String, tel: String) {
        self.send_req(SignalRequest::AddContact { name, phone: tel });
        /*self.state
        .as_ref()
        .unwrap()
        .req_sender
        .send()
        .expect("Couldn't send AddContact");*/
    }
    fn show_view(&mut self, view: String) {
        self.state.as_mut().unwrap().show_view(view);
    }
    fn show_chat(&mut self, view: String) {
        self.messages.replace(
            self.state
                .as_ref()
                .unwrap()
                .sbackend
                .messages_id(view.as_str())
                .unwrap()
                .values()
                .cloned()
                .map(|x| QMLSignalMessage::from_msg(x))
                .collect(),
        );
        self.msgs_changed();
        self.current_messages = view.clone();
        self.state.as_ref().unwrap().show_chat(view);
    }
    fn init_state(&mut self) {
        //let config: Config = confy::load("signal-rs").expect("Couldn't handle config file");
        let config = Config {
            number: Some("+14254920949".to_string()),
            theme: Theme::System,
            scli: Some(SignalCLIConfig {
                username: "+14254920949".to_string(),
                data_dir: "data".to_string(),
            }),
            notifications: NotificationPolicy::Enabled,
        };
        let qptr = QPointer::from(&*self);
        let cfg = config.clone();
        let process_res = queued_callback(move |res: SignalResponse| {
            let cfg = cfg.clone();
            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) => {
                        slf.chats.borrow_mut().reset_data(chats.clone());
                        slf.chats_changed();
                    }
                    SignalResponse::ContactList(ref contacts) => {
                        slf.contacts.borrow_mut().reset_data(contacts.clone());
                        slf.contacts_changed();
                    }
                    SignalResponse::AddHist(ref msg, new) => {
                        if new {
                            if msg.chat_id == slf.current_messages {
                                slf.messages
                                    .get_mut()
                                    .push(QMLSignalMessage::from_msg(msg.clone()));
                            }
                            let cfg = cfg;
                            if cfg.notifications == NotificationPolicy::Enabled {
                                Notification::new()
                                    .summary(&slf.resolve_name(msg.source.clone()))
                                    .body(msg.message.as_str())
                                    .show()
                                    .unwrap();
                            }
                        }
                    }
                    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()
                            .sbackend
                            .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()
                                    .sbackend
                                    .resolve_name(&id)
                                    .unwrap();
                            }
                        }
                        println!("Finished initialization");
                        slf.show_view("chats".to_string());
                        slf.ready();
                        slf.signalResponse(serde_json::to_string(&res).unwrap());
                    }
                    _ => {}
                };
            });
        });
        let (res_sender, res_receiver) =
            glib::MainContext::channel::<SignalResponse>(glib::PRIORITY_DEFAULT);
        let l_res_sender = res_sender.clone();
        let (req_sender, req_receiver) = unbounded_channel::<SignalRequest>();
        let clconf = config.clone();
        let (resource, conn) = connection::new_session_sync().expect("Couldn't connect to DBus");
        qmetaobject::future::execute_async(async {
            let err = resource.await;
            println!("Lost connection to DBus: {}", err);
        });
        let mut state: SignalState = SignalState::new(
            req_sender.clone(),
            l_res_sender.clone(),
            config.clone(),
            conn.clone(),
        );
        state.user_tel = config.number.clone();
        self.state = Some(state);
        res_receiver.attach(None, move |value| {
            process_res(value);
            glib::Continue(true)
        });
        req_sender
            .send(SignalRequest::GetChatList)
            .expect("Couldn't send GetChatList");
        req_sender
            .send(SignalRequest::GetGroups)
            .expect("Couldn't send GetGroups");
        qmetaobject::future::execute_async(async move {
            scli::SCLISession::run(res_sender, req_receiver, clconf.scli.unwrap(), conn).await;
        });
    }
}
/// The main state manager/UI controller
pub struct SignalState {
    pub current: Option<String>,
    pub req_sender: UnboundedSender<SignalRequest>,
    pub last_id: Rc<RefCell<Option<String>>>,
    pub res_sender: glib::Sender<SignalResponse>,
    pub current_chat: Rc<RefCell<Option<String>>>,
    pub user_tel: Option<String>,
    pub sbackend: std::boxed::Box<scli::SCLISession>,
    pub config: Rc<RefCell<Config>>,
}
/// 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,
}
impl SignalState {
    /// Build a new signal state using a websocket connection
    pub fn new(
        req_sender: UnboundedSender<SignalRequest>,
        res_sender: glib::Sender<SignalResponse>,
        config: Config,
        conn: Arc<nonblock::SyncConnection>,
    ) -> SignalState {
        SignalState {
            current: None,
            req_sender: req_sender.clone(),
            last_id: Rc::new(RefCell::new(None)),
            res_sender: res_sender.clone(),
            current_chat: Rc::new(RefCell::new(None)),
            user_tel: None,
            config: Rc::new(RefCell::new(config.clone())),
            sbackend: std::boxed::Box::new(scli::SCLISession::new(
                res_sender, config, conn, req_sender,
            )),
        }
    }
    /// 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
            .sbackend
            .contacts()
            .values()
            .enumerate()
            .filter_map(|(i, contact)| {
                if let Some(msgs) = self.sbackend.messages_id(&contact.tel).ok() {
                    if msgs.len() > 0 {
                        let latest = msgs.values().max_by_key(|x| x.sent_at).unwrap();
                        constructed.push(contact.tel.clone());
                        return Some(Chat {
                            ID: i as i32,
                            name: contact.name.clone(),
                            tel: contact.tel.clone(),
                            is_group: false,
                            last: latest.message.clone(),
                            timestamp: latest.sent_at,
                            messages: vec![latest.clone()],
                        });
                    }
                }
                None
            })
            .collect();
        for (i, (gid, group)) in self.sbackend.groups().into_iter().enumerate() {
            if let Some(msgs) = self.sbackend.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
            .sbackend
            .messages()
            .unwrap()
            .into_iter()
            .filter(|(id, _msgs)| !constructed.contains(&id))
            .enumerate()
        {
            if msgs.len() > 0 {
                let latest = msgs.values().max_by_key(|x| x.sent_at).unwrap();
                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.res_sender
            .send(SignalResponse::ChatList(chats))
            .expect("Couldn't send ChatList");
    }
    pub fn resolve_name(&mut self, source: String) -> String {
        return self.sbackend.resolve_name(source.as_str()).unwrap();
    }
    pub fn update_contacts(&self) {
        let mut contacts: Vec<Contact> = self.sbackend.contacts().values().cloned().collect();
        contacts.sort_by_key(|x| x.name.clone());
        self.res_sender
            .send(SignalResponse::ContactList(contacts))
            .expect("Couldn't send ContactList");
    }
    /// Shows a given chat by tel
    pub fn show_chat(&self, chat_id: String) {
        if let Some(map) = self.sbackend.messages_id(&chat_id).ok() {
            self.res_sender
                .send(SignalResponse::HistoryMessage {
                    phone: chat_id,
                    messages: map.values().cloned().collect(),
                })
                .expect("Couldn't send HistoryMessage");
        }
    }
    /// Processes an incoming SignalResponse and modifies state/UI accordingly
    pub fn process_response(&mut self, response: SignalResponse) {
        self.sbackend.process_response(response.clone());
        match response {
            SignalResponse::Quit => {}
            SignalResponse::ShowTheme(_theme) => {}
            SignalResponse::ShowView(to_show) => {
                self.show_view(to_show);
            }
            SignalResponse::ContactList(_) => {
                self.update_chats();
            }
            SignalResponse::Type(typ) => match typ.as_ref() {
                "getEncryptionPw" => {}
                "registrationDone" => {}
                _ => {
                    println!("Type: {}", typ);
                }
            },
            _ => {}
        }
    }
}
mod qrc;

#[tokio::main]
async fn main() -> Result<(), std::boxed::Box<dyn std::error::Error>> {
    init_gettext();
    unsafe {
        cpp! { {
            #include <QtCore/QCoreApplication>
            #include <QtCore/QString>
        }}
        cpp! ([] {
            QCoreApplication::setApplicationName(QStringLiteral("signal-rs-ut.nicohman"));
            QCoreApplication::setOrganizationDomain(QStringLiteral("nicohman.com"));
            QCoreApplication::setOrganizationName(QStringLiteral("signal-rs-ut.nicohman"));
        });
    }
    //QQuickStyle::set_style("Suru");
    qrc::load();
    qml_register_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();
    println!("Shutting down");
    std::process::Command::new("pkill")
        .arg("-f")
        .arg("-SIGKILL")
        .arg("signal-cli")
        .spawn()
        .unwrap()
        .wait()
        .unwrap();
    Ok(())
}

fn init_gettext() {
    let domain = "signal-rs-ut.nicohman";
    textdomain(domain);

    let app_dir = env::var("APP_DIR").expect("Failed to read the APP_DIR environment variable");

    let mut app_dir_path = PathBuf::from(app_dir);
    if !app_dir_path.is_absolute() {
        app_dir_path = PathBuf::from("/usr");
    }

    let path = app_dir_path.join("share/locale");

    bindtextdomain(domain, path.to_str().unwrap());
}