~nicohman/signal-rs

ref: notif signal-rs/src/main.rs -rw-r--r-- 8.2 KiB
7e6d9d84 — nicohman Try notifications 1 year, 1 month 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
#[macro_use]
extern crate serde;
extern crate mio;
extern crate tungstenite;
extern crate url;
#[macro_use]
extern crate enum_variant_type;
#[macro_use]
extern crate serde_json;
extern crate crossbeam_channel;
#[macro_use]
extern crate tokio;
extern crate futures_util;
extern crate gio;
extern crate glib;
extern crate gtk;
extern crate tokio_tungstenite;
use futures_util::StreamExt;
use tokio::sync::mpsc::*;
use tokio_tungstenite::connect_async;
const CONNECTION: &str = "ws://localhost:9080/ws";
mod signal;
use gio::prelude::*;
use glib::clone;
use gtk::prelude::*;
use gtk::*;
use signal::*;
use std::collections::*;
use std::env::args;
use std::rc::*;
use tungstenite::*;
use url::Url;
pub struct SignalState {
    pub chats: HashMap<i32, Chat>,
    pub message_box: Rc<Box>,
    pub app_box: Box,
    pub contacts: HashMap<String, Contact>,
    pub messages: HashMap<String, (HashMap<i32, Message>, Box)>,
    pub current: Option<String>,
}
impl SignalState {
    pub fn new(_app: &Box) -> SignalState {
        let message_box = Rc::new(Box::new(Orientation::Vertical, 8));
        let app_box = Box::new(Orientation::Vertical, 8);
        app_box.add(&(*message_box));
        SignalState {
            chats: HashMap::new(),
            contacts: HashMap::new(),
            message_box,
            app_box,
            messages: HashMap::new(),
            current: None,
        }
    }
    pub fn show_messages(&mut self, tel: String) {
        if let Some(cur) = &self.current {
            self.messages.get(cur).unwrap().1.hide();
        }
        self.current = Some(tel.clone());
        if let Some(b) = self.messages.get(&tel) {
            b.1.show();
        } else {
            let b = Box::new(Orientation::Vertical, 8);
            b.show();
            self.message_box.add(&b);
            self.messages.insert(tel.clone(), (HashMap::new(), b));
        }
    }
    pub fn add_message(&mut self, message: SignalMessage) {
        if !self.messages.contains_key(&message.source) {
            let b = Box::new(Orientation::Vertical, 8);
            self.message_box.add(&b);
            self.messages
                .insert(message.source.clone(), (HashMap::new(), b));
        }
        let (msg_p, msg_box) = self.messages.get_mut(&message.source).unwrap();
        if msg_p.contains_key(&message.ID) {
            let msg = msg_p.get_mut(&message.ID).unwrap();
            msg.label.set_text(&message.message);
            msg.msg = message;
        } else {
            let construct = Message::new(message.clone());
            msg_p.insert(message.ID, construct);
            let ui_ref = &msg_p.get(&message.ID).unwrap().ui;
            msg_box.add(ui_ref);
        }
        msg_box.show_all();
    }
    pub fn add_messages(&mut self, messages: Vec<SignalMessage>) {
        for msg in messages.into_iter() {
            self.add_message(msg);
        }
    }
    pub fn process_response(&mut self, response: SignalResponse) {
        match response {
            SignalResponse::ChatList(chats) => {
                let mut new_messages = vec![];
                for chat in chats.into_iter() {
                    if let Some(chat_p) = self.chats.get_mut(&chat.ID) {
                        let mut inter = chat
                            .messages
                            .iter()
                            .filter(|x| !chat_p.messages.contains(x))
                            .cloned()
                            .collect::<Vec<SignalMessage>>();
                        new_messages.append(&mut inter);
                        *chat_p = chat;
                    } else {
                        new_messages.append(&mut chat.messages.clone());
                        self.chats.insert(chat.ID, chat.clone());
                    }
                }
            }
            SignalResponse::ContactList(contacts) => {
                for contact in contacts.into_iter() {
                    if let Some(contact_p) = self.contacts.get_mut(&contact.tel) {
                        *contact_p = contact;
                    } else {
                        self.contacts.insert(contact.tel.clone(), contact.clone());
                    }
                }
            }
            SignalResponse::ShowMessages(to_show) => {
                self.show_messages(to_show);
            }
            SignalResponse::MessageList(message_list) => {
                self.add_messages(message_list.messages);
            }
            _ => {}
        };
    }
    pub fn chat_by_tel<'a>(&'a self, tel: String) -> Option<&'a Chat> {
        self.chats.values().filter(|x| x.tel == tel).next()
    }
}
pub struct Message {
    pub msg: SignalMessage,
    pub ui: Box,
    pub label: Label,
}
impl Message {
    pub fn new(msg: SignalMessage) -> Message {
        let msg_box = Box::new(Orientation::Vertical, 6);
        let label = Label::new(Some(&msg.message));
        msg_box.add(&label);
        let context = msg_box.get_style_context();
        context.add_class("msg");
        if msg.outgoing {
            context.add_class("outgoing");
        }
        Message {
            msg,
            ui: msg_box,
            label,
        }
    }
}
#[tokio::main]
async fn main() -> Result<()> {
    let css = include_str!("style.css");
    let _total: Vec<SignalResponse> = vec![];
    let application = Application::new(Some("com.nicohman"), Default::default()).unwrap();
    application.connect_activate(move |app| {
        let provider = CssProvider::new();
        provider.load_from_data(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, mut req_receiver) = unbounded_channel::<SignalRequest>();
        tokio::spawn(async move {
            let (socket, _response) = connect_async(Url::parse(CONNECTION).unwrap())
                .await
                .unwrap();
            let mut session = SignalSession::from_socket(socket);
            loop {
                tokio::select! {
                    next = session.stream.next() => {
                        res_sender.send(next.unwrap());
                    },
                    inc = req_receiver.recv() => {
                        if let Some(v) = inc {
                            session.send(v).await;
                        }
                    },
                };
            }
        });
        StyleContext::add_provider_for_screen(
            &gdk::Screen::get_default().expect("Error initializing gtk css provider."),
            &provider,
            STYLE_PROVIDER_PRIORITY_APPLICATION,
        );
        let window = ApplicationWindow::new(app);
        let app_box = Box::new(Orientation::Vertical, 6);
        let mut state = SignalState::new(&app_box);
        window.set_title("Signal");
        window.set_border_width(10);
        window.set_position(WindowPosition::Center);
        window.set_default_size(350, 70);
        let input = EntryBuilder::new().build();
        let show_input = Entry::new();
        show_input.set_placeholder_text(Some("Number to show messages from"));
        let show_button = Button::with_label("Show messages");
        let button = Button::with_label("Send debug text");
        show_button.connect_clicked(
            clone!( @strong l_res_sender, @weak show_input, @strong req_sender => move |_| {
                let inp = show_input.get_buffer().get_text();
                req_sender.send(SignalRequest::GetMessageList{ id: inp.clone()});
                l_res_sender.send(SignalResponse::ShowMessages(inp));
            }),
        );
        button.connect_clicked(clone!( @weak input, @weak show_input => move |_| {
            req_sender.send(SignalRequest::SendMessage {
                to: show_input.get_buffer().get_text(),
                message: input.get_buffer().get_text(),
            });
        }));
        state.app_box.add(&show_input);
        state.app_box.add(&show_button);
        state.app_box.add(&input);
        state.app_box.add(&button);
        window.add(&state.app_box);
        res_receiver.attach(None, move |value| {
            state.process_response(value);
            glib::Continue(true)
        });
        window.show_all();
    });
    application.run(&args().collect::<Vec<_>>());
    Ok(())
}