~nicohman/signal-rs

ref: 470875a3eed683f458bde2434ac9f0480c3fdf16 signal-rs/src/main.rs -rw-r--r-- 18.2 KiB
470875a3nicohman Finish CreateChat, add links 9 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
/*
 * 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)]
#[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;
extern crate tokio;
use std::ffi::CStr;
extern crate tungstenite;
#[macro_use]
extern crate lazy_static;
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;
pub trait SignalBackend {
    fn messages_id(&self, tel: &str) -> Result<BTreeMap<i64, SignalMessage>, anyhow::Error>;
    fn message(&self, tel: &str, id: i64) -> Result<SignalMessage, anyhow::Error>;
    fn messages(&self) -> Result<BTreeMap<String, BTreeMap<i64, SignalMessage>>, anyhow::Error>;
    fn contact(&self, tel: &str) -> Result<Contact, anyhow::Error>;
    fn contacts(&self) -> HashMap<String, Contact>;
    fn process_response(&mut self, response: SignalResponse);
    fn new(res_sender: glib::Sender<SignalResponse>, config: Config) -> Self;
    fn groups(&self) -> HashMap<String, Group>;
    fn avatar(&self, id: &str) -> Option<String>;
}
#[derive(QObject, Default)]
pub struct SignalUI {
    base: qt_base_class!(trait QObject),
    state: Option<SignalState<scli::SCLISession>>,
    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)),
    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),
    send_group_message: qt_method!(fn(&self, chat_id: String, message: String)),
}
impl SignalUI {
    fn del_message(&self, chat_id: String, sent_at: i64) {
        self.state
            .as_ref()
            .unwrap()
            .sbackend
            .res_sender
            .send(SignalResponse::RmMessage { chat_id, sent_at })
            .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 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.state
            .as_ref()
            .unwrap()
            .req_sender
            .send(SignalRequest::EditContact {
                name,
                phone: tel,
                id,
            })
            .expect("Couldn't send EditContact");
    }
    fn send_message(&self, to: String, message: String) {
        self.state
            .as_ref()
            .unwrap()
            .req_sender
            .send(SignalRequest::SendMessage { to, message })
            .expect("Couldn't send SendMessage");
    }
    fn resolve_name(&self, source: String) -> String {
        self.state.as_ref().unwrap().resolve_name(source)
    }
    fn send_group_message(&self, chat_id: String, message: String) {
        self.state
            .as_ref()
            .unwrap()
            .req_sender
            .send(SignalRequest::SendGroupMessage { chat_id, message })
            .expect("Couldn't send SendGroupMessage");
    }
    fn add_contact(&self, name: String, tel: String) {
        self.state
            .as_ref()
            .unwrap()
            .req_sender
            .send(SignalRequest::AddContact { name, phone: tel })
            .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.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 {
            backend: Backend::SignalCLI,
            number: Some("+14254920949".to_string()),
            theme: Theme::Base,
            scli: Some(SignalCLIConfig {
                username: "+14254920949".to_string(),
                data_dir: "data".to_string(),
            }),
        };
        let qptr = QPointer::from(&*self);
        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());
                if let SignalResponse::ChatList(ref chats) = res {
                    slf.chats.borrow_mut().reset_data(chats.clone());
                    slf.chats_changed();
                }
                if let SignalResponse::ContactList(ref contacts) = res {
                    slf.contacts.borrow_mut().reset_data(contacts.clone());
                    slf.contacts_changed();
                }
                if let SignalResponse::AddHist(ref msg, new) = res {
                    if new {
                        if msg.chat_id == slf.current_messages {
                            slf.messages
                                .get_mut()
                                .push(QMLSignalMessage::from_msg(msg.clone()));
                        }
                        /*Notification::new()
                        .summary(&slf.resolve_name(msg.source.clone()))
                        .body(msg.message.as_str())
                        .show()
                        .unwrap();*/
                    }
                }
                if let SignalResponse::RmMessage {
                    ref chat_id,
                    sent_at,
                } = res
                {
                    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;
                            }
                        }
                    }
                }
                if let SignalResponse::Groups(_) = res {
                    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();
        match config.backend {
            Backend::SignalCLI => {
                let mut state: SignalState<scli::SCLISession> =
                    SignalState::new(req_sender.clone(), l_res_sender.clone(), config.clone());
                state.user_tel = config.number.clone();
                state.show_view("chats".to_string());
                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");
        if config.backend == Backend::Axolotl {
            req_sender
                .send(SignalRequest::GetContacts)
                .expect("Couldn't send GetContacts");
        }
        req_sender
            .send(SignalRequest::GetGroups)
            .expect("Couldn't send GetGroups");
        qmetaobject::future::execute_async(async move {
            match clconf.backend {
                Backend::Axolotl => {
                    //AxolotlSession::run(res_sender, req_receiver).await;
                }
                // Inspired in part by https://github.com/boxdot/gurk-rs
                Backend::SignalCLI => {
                    scli::SCLISession::run(res_sender, req_receiver, clconf.scli.unwrap()).await;
                }
            }
        });
    }
}
/// The main state manager/UI controller
pub struct SignalState<T: SignalBackend + ?Sized> {
    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 backend: Backend,
    pub sbackend: std::boxed::Box<T>,
    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<T> SignalState<T>
where
    T: SignalBackend,
{
    /// Build a new signal state using a websocket connection
    pub fn new(
        req_sender: UnboundedSender<SignalRequest>,
        res_sender: glib::Sender<SignalResponse>,
        config: Config,
    ) -> SignalState<T> {
        SignalState {
            current: None,
            req_sender,
            last_id: Rc::new(RefCell::new(None)),
            res_sender: res_sender.clone(),
            current_chat: Rc::new(RefCell::new(None)),
            user_tel: None,
            backend: config.backend,
            config: Rc::new(RefCell::new(config.clone())),
            sbackend: std::boxed::Box::new(T::new(res_sender, config)),
        }
    }
    /// 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: 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(&self, source: String) -> String {
        if let Some(contact) = self.sbackend.contact(source.as_str()).ok() {
            return contact.name;
        } else {
            return source;
        }
    }
    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"));
        }}
    }*/
    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());
}