~nicohman/signal-rs

ref: c9f649c299bf94f7d76a8a152b7785a9b04149d8 signal-rs/src/main.rs -rw-r--r-- 16.4 KiB
c9f649c2 — nicohman Use Dbus for scli 11 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
#![feature(type_alias_impl_trait)]
extern crate confy;
extern crate crossbeam_channel;
extern crate enum_variant_type;
extern crate futures_util;
extern crate gdk_pixbuf;
extern crate gio;
extern crate glib;
extern crate gtk;
extern crate libhandy;
extern crate mio;
extern crate reqwest;
extern  crate dbus;
extern crate serde;
extern crate serde_json;
extern crate tokio;
extern crate tokio_tungstenite;
extern crate tungstenite;
extern crate url;
extern crate dbus_tokio;
#[macro_use]
extern crate lazy_static;
use futures_util::StreamExt;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::mpsc::*;
use tokio_tungstenite::connect_async;
const CONNECTION: &str = "ws://localhost:9080/ws";
#[allow(non_snake_case)]
mod signal;
use gio::prelude::*;
use glib::clone;
use gtk::prelude::*;
use gtk::*;
use signal::*;
use std::collections::*;
use std::env::args;
use std::io::BufRead;
use tungstenite::*;
use url::Url;
mod config;
mod util;
/// Contains the custom widgets
mod widgets;
use config::*;
use std::cell::*;
use std::process::Command;
use std::rc::*;
use widgets::ChatList;
use widgets::Settings;
use widgets::*;
mod axolotl;
use axolotl::*;
mod scli;
const BASE_CSS: &'static str = include_str!("base.css");
const SIGNAL_CSS: &'static str = include_str!("signal.css");
const STYLE_CSS: &'static str = include_str!("style.css");
pub trait SignalBackend {
    fn messages<'a>(&'a self) -> &'a HashMap<String, BTreeMap<i64, Message>>;
    fn contacts<'a>(&'a self) -> &'a HashMap<String, Contact>;
    fn process_response(&mut self, response: SignalResponse);
    fn new(res_sender: glib::Sender<SignalResponse>, config: Config) -> Self;
}
/// The main state manager/UI controller
pub struct SignalState<T: SignalBackend> {
    pub message_box: Box,
    pub app_box: Box,
    pub current: Option<String>,
    pub history: Option<ChatHistory>,
    pub scroll: ScrolledWindow,
    pub req_sender: UnboundedSender<SignalRequest>,
    pub last_id: Rc<RefCell<Option<String>>>,
    pub chat_list: ChatList,
    pub stack: Stack,
    pub res_sender: glib::Sender<SignalResponse>,
    pub current_chat: Rc<RefCell<Option<String>>>,
    pub button: Button,
    pub input: Entry,
    pub pw: PasswordDialog,
    pub cc: CreateChat,
    pub ccontact: CreateContact,
    pub edit_contact: EditContact,
    pub user_tel: Option<String>,
    pub backend: Backend,
    pub sbackend: T,
    pub headerbar: Header,
    pub config: Rc<RefCell<Config>>,
    pub settings: Settings,
    pub providers: HashMap<Theme, CssProvider>,
}
/// 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> {
        let message_box = Box::new(Orientation::Vertical, 6);
        let scroll = ScrolledWindow::new::<Adjustment, Adjustment>(None, None);
        scroll.set_min_content_height(300);
        add_class(&message_box, "msg-box");
        add_class(&scroll, "msg-scroll");
        let app_box = Box::new(Orientation::Vertical, 0);
        let stack = Stack::new();
        let chat_list = ChatList::new();
        let input = EntryBuilder::new().build();
        let button = Button::with_label("Send message");
        let headerbar = Header::new(&res_sender);
        app_box.add(&headerbar.headerbar);
        let msg_box = Box::new(Orientation::Vertical, 8);
        msg_box.pack_start(&scroll, true, true, 0);
        scroll.set_vexpand(true);
        scroll.set_policy(PolicyType::Never, PolicyType::Always);
        msg_box.pack_start(&input, false, false, 0);
        msg_box.pack_start(&button, false, false, 0);
        let pw = PasswordDialog::new();
        let cc = CreateChat::new();
        let create_contact = CreateContact::new();
        let edit_contact = EditContact::new();
        let settings = widgets::Settings::new(config.clone());
        stack.add_named(&settings.cbox, "settings");
        stack.add_named(&msg_box, "messages");
        stack.add_named(&chat_list.listbox, "chats");
        stack.add_named(&pw.container, "password");
        stack.add_named(&cc.container, "create-chat");
        stack.add_named(&create_contact.container, "create-contact");
        stack.add_named(&edit_contact.container, "edit-contact");
        add_class(&app_box, "app-box");
        scroll.add(&message_box);
        app_box.add(&stack);
        let mut providers = HashMap::new();
        let style_prov = CssProvider::new();
        style_prov.load_from_data(&STYLE_CSS.as_bytes()).unwrap();
        let signal_prov = CssProvider::new();
        signal_prov.load_from_data(&SIGNAL_CSS.as_bytes()).unwrap();
        providers.insert(Theme::Base, style_prov);
        providers.insert(Theme::Signal, signal_prov);
        SignalState {
            message_box,
            app_box,
            stack,
            current: None,
            history: None,
            scroll,
            req_sender,
            last_id: Rc::new(RefCell::new(None)),
            chat_list,
            res_sender: res_sender.clone(),
            current_chat: Rc::new(RefCell::new(None)),
            button,
            input,
            headerbar,
            pw,
            cc,
            ccontact: create_contact,
            edit_contact,
            user_tel: None,
            backend: config.backend,
            config: Rc::new(RefCell::new(config.clone())),
            sbackend: T::new(res_sender, config),
            settings,
            providers,
        }
    }
    /// Connects the gtk event signals to the relevant callbacks
    pub fn connect_signals(&mut self) {
        self.chat_list.connect(&self);
        self.connect_scroll();
        self.connect_send_button();
        self.cc.connect(&self);
        self.pw.connect(&self);
        self.edit_contact.connect(&self);
        self.ccontact.connect(&self);
        self.settings.connect(&self);
    }
    pub fn connect_send_button(&mut self) {
        self.button.connect_clicked(clone!( @weak self.input as input, @strong self.req_sender as req_sender, @weak self.scroll as scroll, @weak self.current_chat as chat => move |_| {
            let msg = input.get_buffer().get_text();
            input.set_buffer(&EntryBuffer::new(None));
            let to = chat.borrow().clone().unwrap();
            req_sender.send(SignalRequest::SendMessage {
                to: to.clone(),
                message: msg
            }).expect("Couldn't send SendMessage");
            req_sender.send(SignalRequest::GetMessageList{id: to}).expect("Couldn't send GetMessageList");
            scroll.emit_scroll_child(ScrollType::End, false);
        }));
    }
    /// Shows the given view in the app_box
    pub fn show_view(&mut self, view: View) {
        match view.clone() {
            View::Chats => {
                self.req_sender
                    .send(SignalRequest::GetChatList)
                    .expect("Couldn't send GetChatList");
                self.hide_history();
                self.update_chats();
                self.chat_list.update_chats();
                self.chat_list.set_enabled(true);
                self.chat_list.listbox.unselect_all();
                self.stack.set_visible_child_name("chats");
            }
            View::Messages(tel) => {
                self.chat_list.set_enabled(false);
                self.show_chat(tel);
                self.stack.set_visible_child_name("messages");
            }
            View::Password => {
                self.stack.set_visible_child_name("password");
            }
            View::CreateContact => {
                self.stack.set_visible_child_name("create-contact");
            }
            View::EditContact(id) => {
                self.edit_contact
                    .edit(self.sbackend.contacts().get(&id).unwrap().clone());
                self.stack.set_visible_child_name("edit-contact");
            }
            View::CreateChat => {
                self.cc
                    .set_choices(self.sbackend.contacts().values().cloned().collect());
                self.stack.set_visible_child_name("create-chat");
            }
            View::Settings => {
                self.stack.set_visible_child_name("settings");
            }
        };
        self.headerbar
            .set_view(view, &self.req_sender, &self.res_sender);
    }
    pub fn update_chats(&mut self) {
        self.chat_list.chats = HashMap::new();
        for (i, contact) in self.sbackend.contacts().values().enumerate() {
            if let Some(msgs) = self.sbackend.messages().get(&contact.tel) {
                let latest = msgs.values().max_by_key(|x| x.msg.sent_at).unwrap();
                self.chat_list.add_chat(Chat {
                    ID: i as i32,
                    name: contact.name.clone(),
                    tel: contact.tel.clone(),
                    is_group: false,
                    last: latest.msg.message.clone(),
                    timestamp: latest.msg.sent_at,
                    messages: vec![latest.msg.clone()],
                });
            }
        }
    }
    /// Hides message history
    pub fn hide_history(&mut self) {
        if self.history.is_some() {
            for child in self.message_box.get_children().iter() {
                self.message_box.remove(child);
            }
            let mut h = self.history.take().unwrap();
            h.wipe();
            self.current_chat.replace(None);
        }
        self.scroll.hide();
    }
    pub fn connect_scroll(&mut self) {
        self.scroll.connect_edge_overshot(clone!( @strong self.req_sender as req_sender, @weak self.last_id as last_id => @default-panic, move |_, pos_type| {
            match pos_type {
                PositionType::Top => {
                    req_sender.send(SignalRequest::GetMoreMessages{ lastId: last_id.borrow().clone().unwrap() }).expect("Couldn't send GetMoreMessages");
                },
                _ => {
                    // Do nothing for any other position
                }
            };
        }));
    }
    /// Shows a given chat by tel
    pub fn show_chat(&mut self, tel: String) {
        self.hide_history();
        let mut history = ChatHistory::new(tel.clone());
        if let Some(map) = self.sbackend.messages().get(&tel) {
            for m in map.values() {
                history.insert_bottom(Element::Message(m.clone()));
            }
        }
        self.current_chat.replace(Some(tel.clone()));
        self.last_id.replace(history.get_last_id());
        self.message_box.add(&history.listbox);
        self.message_box.show_all();
        self.scroll.show_all();
        history.listbox.show_all();
        self.history = Some(history);
    }
    /// 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::ShowTheme(theme) => {
                self.change_theme(theme);
            }
            SignalResponse::ShowView(to_show) => {
                self.show_view(to_show);
            }
            SignalResponse::ContactList(_) => {
                self.update_chats();
            }
            SignalResponse::Type(typ) => match typ.as_ref() {
                "getEncryptionPw" => {
                    self.show_view(View::Password);
                }
                "registrationDone" => {
                    self.show_view(View::Chats);
                }
                _ => {
                    println!("Type: {}", typ);
                }
            },
            SignalResponse::AddHist(tel, id, new) => {
                let msg = self
                    .sbackend
                    .messages()
                    .get(&tel)
                    .unwrap()
                    .get(&id)
                    .unwrap();
                if let Some(hist) = self.history.as_mut() {
                    if hist.tel == msg.msg.source {
                        if new {
                            hist.insert_bottom(Element::Message(msg.clone()));
                        } else {
                            hist.insert_top(Element::Message(msg.clone()));
                        }
                        self.last_id.replace(hist.get_last_id());
                    }
                }
            }
            _ => {}
        }
    }
    /// Fetches a chat by tel, if it exists
    pub fn chat_by_tel<'a>(&'a self, tel: String) -> Option<&'a Chat> {
        self.chat_list
            .chats
            .values()
            .filter(|x| x.tel == tel)
            .next()
    }
    pub fn change_theme(&self, theme: Theme) {
        let screen = gdk::Screen::get_default().expect("Error initializing gtk css provider.");
        for prov in &self.providers {
            StyleContext::remove_provider_for_screen(&screen, prov.1);
        }
        StyleContext::add_provider_for_screen(
            &screen,
            self.providers.get(&theme).unwrap(),
            STYLE_PROVIDER_PRIORITY_APPLICATION,
        );
        StyleContext::reset_widgets(&screen);
    }
}
/// A container struct with a Signal Message and a built UI
#[derive(Clone, Debug)]
pub struct Message {
    pub msg: SignalMessage,
    pub ui: MessageUi,
}
impl Message {
    pub fn new(msg: SignalMessage) -> Message {
        Message {
            ui: MessageUi::new(&msg),
            msg,
        }
    }
}
#[tokio::main]
async fn main() -> Result<()> {
    let config: Config = confy::load("signal-rs").expect("Couldn't handle config file");
    let _total: Vec<SignalResponse> = vec![];
    let application = Application::new(Some("com.nicohman"), Default::default()).unwrap();
    application.connect_activate(move |app| {
        let icon = gdk_pixbuf::Pixbuf::from_file("src/icon.png").unwrap();
        let provider = CssProvider::new();
        provider.load_from_data(BASE_CSS.as_bytes()).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 window = ApplicationWindow::new(app);
        let mut state: SignalState<scli::SCLISession> =
            SignalState::new(req_sender.clone(), l_res_sender.clone(), config.clone());
        StyleContext::add_provider_for_screen(
            &gdk::Screen::get_default().expect("Error initializing gtk css provider."),
            &provider,
            STYLE_PROVIDER_PRIORITY_APPLICATION,
        );
        state.change_theme(config.theme);
        state.user_tel = config.number.clone();
        window.set_title("Signal");
        window.set_icon(Some(&icon));
        window.set_border_width(10);
        window.set_position(WindowPosition::Center);
        window.set_default_size(400, 800);
        state.connect_signals();
        window.add(&state.app_box);
        state.show_view(View::Chats);
        res_receiver.attach(None, move |value| {
            state.process_response(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");
        }
        tokio::spawn(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;
                }
            }
        });
        std::thread::sleep_ms(1000);
        window.show_all();
        l_res_sender
            .send(SignalResponse::ShowView(View::Chats))
            .expect("Couldn't send ShowChats");
    });
    application.run(&args().collect::<Vec<_>>());
    Ok(())
}
pub fn add_class(widget: &impl WidgetExt, class: impl Into<String>) {
    let ctx = widget.get_style_context();
    ctx.add_class(class.into().as_str());
}