~nicohman/signal-rs

ref: 58466229374133a351ab1563aa57cc0d78dd5d3f signal-rs/src/scli.rs -rw-r--r-- 15.1 KiB
58466229 — nicohman Support basic images with scli 10 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
use crate::Message;
use crate::*;
use config::*;
use dbus::message::MatchRule;
use dbus::nonblock;
use dbus_tokio::connection;
use futures_util::StreamExt;
use serde::{Deserialize, Deserializer, Serialize};
use signal::*;
use signal::*;
use std::fs;
use std::io::BufRead;
use std::path::*;
use std::process::Stdio;
use std::time::Duration;
lazy_static! {
    static ref SCLI_ATTACHMENT_DIRECTORY: String = home::home_dir()
        .unwrap()
        .join(".local/share/signal-cli/attachments/")
        .into_os_string()
        .into_string()
        .unwrap();
}
pub struct SCLISession {
    pub contacts: HashMap<String, Contact>,
    pub messages: HashMap<String, BTreeMap<i64, Message>>,
    pub config: SignalCLIConfig,
    pub res_sender: glib::Sender<SignalResponse>,
}
impl SCLISession {
    pub fn save(&self) {
        let datafile = DataFile::from_data(self.contacts.clone(), self.messages.clone());
        fs::rename(Path::new(&self.config.data_dir).join("data.json"), Path::new(&self.config.data_dir).join("old.data.json")).expect("Couldn't move current data file to backup");
        fs::write(
            Path::new(&self.config.data_dir).join("data.json"),
            serde_json::to_string(&datafile).unwrap().as_bytes(),
        )
        .expect("Couldn't write data");
    }
    pub fn fetch_contacts_scli(username: &str) -> Vec<Contact> {
        let output = Command::new("signal-cli")
            .arg("--username")
            .arg(username)
            .arg("listContacts")
            .output()
            .expect("Couldn't start listContacts");
        let res = BufRead::lines(output.stdout.as_slice())
            .into_iter()
            .filter_map(|s| SignalCLIContactInfo::from_str(s.unwrap()))
            .map(|ci| Contact {
                tel: ci.number,
                name: ci.name,
            })
            .collect();
        res
    }
    pub async fn run(
        res_sender: glib::Sender<SignalResponse>,
        mut req_receiver: UnboundedReceiver<SignalRequest>,
        config: SignalCLIConfig,
    ) {
        let mut cmd = tokio::process::Command::new("signal-cli");
        cmd.arg("-u")
            .arg(&config.username)
            .arg("daemon")
            .arg("--json")
            .stdout(Stdio::piped())
            .kill_on_drop(true);
        let (resource, conn) = connection::new_session_sync().expect("Couldn't connect to DBus");
        tokio::spawn(async {
            let err = resource.await;
            println!("Lost connection to DBus: {}", err);
        });
        let proxy = nonblock::Proxy::new(
            "org.asamk.Signal",
            "/org/asamk/Signal",
            Duration::from_secs(10),
            conn.clone(),
        );
        let mr_mr = MatchRule::new_signal("org.asamk.Signal", "MessageReceived");
        let sy_mr = MatchRule::new_signal("org.asamk.Signal", "SyncMessageReceived");
        let mut inc = conn.add_match(mr_mr).await.unwrap().msg_stream();
        let mut inc_sync = conn.add_match(sy_mr).await.unwrap().msg_stream();
        // NOTE: HOLY SHIT GO DBUS
        let mut child = cmd.spawn().expect("Couldn't run signal-cli");
        let stdout = child.stdout.take().unwrap();
        let mut reader = BufReader::new(stdout).lines();
        let cmd_handle = tokio::spawn(async { child.await });
        loop {
            tokio::select! {
                /*msg  = inc.1.next() => {
                    let (timestamp, source , group_id, message, attachments) : (i64, String, Vec<u8>, String, Vec<String>) = msg.unwrap().read5().unwrap();
                    let con_msg = SignalMessage {
                        message,

                        attachment: None,
                        ID: 0,
                        outgoing: false,
                        source,
                        sent_at: timestamp,
                    };
                    res_sender.send(SignalResponse::IDLessMessage(con_msg)).expect("COuldn't send IDLessMessage");
                },
                msg = inc_sync.1.next() => {
                    let (timestamp, mut source, dest, group_id, message, attachments) : (i64,String,String,Vec<u8>,String,Vec<String>) = msg.unwrap().read_all().unwrap();
                    let mut outgoing = false;
                    if source == config.username {
                        source = dest;
                        outgoing = true;
                    }
                    let con_msg = SignalMessage {
                        message,
                        attachment: None,
                        ID: 0,
                        outgoing,
                        source,
                        sent_at: timestamp,
                    };
                    res_sender.send(SignalResponse::IDLessMessage(con_msg)).expect("COuldn't send IDLessMessage");
                }*/
                msg_line = reader.next_line() => {
                    println!("Incoming!");
                    let parsed : SignalCLIContainer= serde_json::from_str(&msg_line.unwrap().unwrap()).unwrap();
                    if let Some(ref data_msg) = parsed.envelope.data_message {
                                let mut attachment = vec![];
                                if let Some(ats) = &data_msg.attachments {
                                    attachment = parse_attachments(ats);
                                }
                        let con_msg = SignalMessage {
                            message: data_msg.message.clone().unwrap_or_default(),
                            ID: 0,
                            outgoing: false,
                            attachment: Some(attachment),
                            source: parsed.envelope.source.clone(),
                            sent_at: parsed.envelope.timestamp,
                        };
                        res_sender.send(SignalResponse::IDLessMessage(con_msg)).expect("Couldn't send IDLessMessage");
                    } else if let Some(ref sync_msg) = parsed.envelope.sync_message {
                        if let Some(sm) = &sync_msg.sent_message {
                                let mut outgoing = false;
                                let mut source = parsed.envelope.source.clone();
                                if parsed.envelope.source == config.username {
                                    outgoing = true;
                                    source = sm.destination.clone();
                                }
                                let mut attachment = vec![];
                                if let Some(ats) = &sm.attachments {
                                    attachment = parse_attachments(ats);
                                }
                                let con_msg = SignalMessage {
                                    message: sm.message.clone().unwrap_or_default(),
                                    ID: 0,
                                    outgoing,
                                    attachment: Some(attachment),
                                    source,
                                    sent_at: parsed.envelope.timestamp,
                                };
                                res_sender.send(SignalResponse::IDLessMessage(con_msg)).expect("Couldn't send IDLessMessage");

                        }
                    }
                }
                inc = req_receiver.recv() => {
                    if let Some(v) = inc {
                        match v {
                            SignalRequest::GetContacts => {
                                println!("Getting contacts");
                                //let contacts = Self::fetch_contacts_scli(config.username.as_str());
                                //res_sender.send(SignalResponse::ContactList(contacts)).expect("Can't send ContactList");
                            }
                            SignalRequest::SendMessage { to, message } => {
                                let (timestamp,) : (i64,) = proxy.method_call("org.asamk.Signal", "sendMessage", (&message,Vec::<String>::new(), vec![&to] )).await.unwrap();
                                res_sender.send(SignalResponse::IDLessMessage(SignalMessage {
                                    message: message,
                                    source: to,
                                    outgoing: true,
                                    attachment: None,
                                    sent_at: timestamp,
                                    ID: 0,
                                })).expect("Couldnt send IDLessMessage");
                            }
                            SignalRequest::AddContact{ name, phone} => {
                                res_sender.send(SignalResponse::ContactList(vec![Contact {name, tel: phone}])).expect("Couldn't send ContactList");
                            },
                            _ => {

                            }
                        }
                    }
                }
            }
        }
        unreachable!();
        conn.remove_match(inc.0.token()).await.unwrap();
    }
    pub fn add_message(&mut self, message: SignalMessage, new: bool) {
        if !self.messages.contains_key(&message.source) {
            self.messages
                .insert(message.source.clone(), BTreeMap::new());
        }
        let msg_p = self.messages.get_mut(&message.source).unwrap();
        if !msg_p.contains_key(&message.sent_at) {
            let msg = Message::new(message.clone());
            msg_p.insert(message.sent_at, msg);
            self.res_sender
                .send(SignalResponse::AddHist(
                    message.source.clone(),
                    message.sent_at,
                    new,
                ))
                .expect("Couldn't send AddHist");
        }
        self.save();
    }

    pub fn process_scli_msg(&mut self, msg: SignalCLIMessage) {
        /*if !self.contacts.contains_key(&msg.source) {
            self.req_sender.send(SignalRequest::GetContacts).expect("Couldn't send GetContacts");
        }*/
        let message: Option<String>;
        if let Some(m) = msg.message {
            println!("text");
            message = Some(m);
        } else if let Some(data) = msg.data_message {
            message = data.message;
        } else {
            println!("Return early");
            return;
        }
        // TODO: Fix outgoing
        if let Some(v) = self.messages.get(&msg.source) {
            let last_id = v.values().map(|msg| msg.msg.ID).max().unwrap();
            let made_msg = SignalMessage {
                ID: last_id + 1,
                source: msg.source,
                message: message.unwrap(),
                outgoing: false,
                sent_at: msg.timestamp,
                attachment: None,
            };
            self.add_message(made_msg, true);
        } else {
            let made_msg = SignalMessage {
                ID: 0,
                source: msg.source,
                message: message.unwrap(),
                outgoing: false,
                sent_at: msg.timestamp,
                attachment: None,
            };
            self.add_message(made_msg, true);
        }
    }
}
impl SignalBackend for SCLISession {
    fn new(res_sender: glib::Sender<SignalResponse>, config: Config) -> SCLISession {
        let scli_config = config.scli.expect("No configured SCLI settings");
        let mut messages = HashMap::new();
        let mut contacts = HashMap::new();
        let mut to_save = false;
        if fs::metadata(&scli_config.data_dir).is_err() {
            fs::create_dir_all(&scli_config.data_dir).expect("Couldn't create data directory");
            let base_contacts = Self::fetch_contacts_scli(&scli_config.username);
            for contact in base_contacts {
                contacts.insert(contact.tel.clone(), contact);
            }
            to_save = true;
        } else {
            let data = DataFile::load_data(
                Path::new(&scli_config.data_dir)
                    .join("data.json")
                    .to_str()
                    .unwrap(),
            )
            .expect("Couldn't load data file");
            for contact in data.contacts.values() {
                contacts.insert(contact.tel.clone(), contact.clone());
            }
            messages = data
                .messages
                .into_iter()
                .map(|(k, x)| {
                    (
                        k,
                        x.into_iter()
                            .map(|(k, msg)| (k, Message::new(msg)))
                            .collect(),
                    )
                })
                .collect();
        }
        let session = SCLISession {
            res_sender,
            config: scli_config,
            messages,
            contacts,
        };
        if to_save {
            session.save();
        }
        session
    }
    fn messages<'a>(&'a self) -> &'a HashMap<String, BTreeMap<i64, Message>> {
        &self.messages
    }
    fn contacts<'a>(&'a self) -> &'a HashMap<String, Contact> {
        &self.contacts
    }
    fn process_response(&mut self, response: SignalResponse) {
        match response {
            SignalResponse::SignalCLIEnvelope(msg) => {
                println!("Processing");
                self.process_scli_msg(msg);
            }
            SignalResponse::IDLessMessage(mut msg) => {
                let mut id = 0;
                if let Some(v) = self.messages.get(&msg.source) {
                    id = v.values().map(|msg| msg.msg.ID).max().unwrap() + 1;
                }
                msg.ID = id;
                self.add_message(msg, true);
            }
            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());
                    }
                }
                self.save();
            }
            _ => {}
        }
    }
}
/// The file containing the stored signal messages/contacts
#[derive(Serialize, Deserialize)]
pub struct DataFile {
    pub contacts: HashMap<String, Contact>,
    pub messages: HashMap<String, BTreeMap<i64, SignalMessage>>,
}
impl DataFile {
    pub fn from_data(
        contacts: HashMap<String, Contact>,
        messages: HashMap<String, BTreeMap<i64, Message>>,
    ) -> DataFile {
        DataFile {
            contacts,
            messages: messages
                .into_iter()
                .map(|(k, b)| (k, b.into_iter().map(|(k, v)| (k, v.msg)).collect()))
                .collect(),
        }
    }
    pub fn load_data(
        path: &str,
    ) -> std::result::Result<DataFile, std::boxed::Box<dyn std::error::Error>> {
        let stri = fs::read_to_string(&path)?;
        Ok(serde_json::from_str(&stri)?)
    }
}
/// Turns a vec of SignalCLIAttachments into their Attachment counterparts
pub fn parse_attachments(catt: &Vec<SignalCLIAttachment>) -> Vec<Attachment> {
    catt.into_iter()
        .map(|x| Attachment {
            file: SCLI_ATTACHMENT_DIRECTORY.to_owned() + &x.id,
            file_name: x.filename.clone().unwrap_or(x.id.to_string()),
            c_type: AttachmentType::from_mime(&x.content_type),
        })
        .collect()
}