~nicohman/signal-rs

ref: 58466229374133a351ab1563aa57cc0d78dd5d3f signal-rs/src/signal.rs -rw-r--r-- 9.0 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
use crate::Message;
use enum_variant_type::EnumVariantType;
use futures_util::sink::SinkExt;
use futures_util::stream::*;
use futures_util::{future, StreamExt};
use gio::subclass::BoxedType;
use glib_macros::*;
use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize};
use serde_repr::*;
use std::convert::TryFrom;
use tokio_tungstenite::tungstenite::protocol::Message as TMessage;
use tokio_tungstenite::*;
lazy_static! {
    static ref CONTACT_REG: Regex =
        Regex::new(r"Number: (\+[0-9]+) Name: (\S+)  Blocked:").unwrap();
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
#[serde(tag = "request")]
pub enum SignalRequest {
    SendMessage {
        to: String,
        message: String,
    },
    GetMessageList {
        id: String,
    },
    CreateChat {
        tel: String,
    },
    OpenChat {
        id: String,
    },
    DelChat {
        id: String,
    },
    DelContact {
        id: String,
    },
    GetChatList,
    GetContacts,
    GetDevices,
    GetMoreMessages {
        lastId: String,
    },
    LeaveChat,
    ToggleNotifications {
        chat: String,
    },
    CreateNewGroup {
        name: String,
        members: Vec<String>,
    },
    GetConfig,
    AddContact {
        name: String,
        phone: String,
    },
    SendPassword {
        pw: String,
    },
    EditContact {
        name: String,
        phone: String,
        id: String,
    },
}

#[derive(Serialize, Deserialize, Clone, EnumVariantType, Debug)]
pub enum SignalResponse {
    #[evt(derive(Clone, Serialize, Deserialize, Debug))]
    ContactList(Vec<Contact>),
    #[evt(derive(Clone, Serialize, Deserialize, Debug))]
    ChatList(Vec<Chat>),
    #[evt(derive(Clone, Serialize, Deserialize, Debug))]
    MessageList(SignalMessageList),
    #[evt(derive(Clone, Serialize, Deserialize, Debug))]
    SignalCLIEnvelope(SignalCLIMessage),
    #[evt(derive(Clone, Serialize, Deserialize, Debug))]
    MoreMessageList(SignalMessageList),
    #[evt(derive(Clone, Serialize, Deserialize, Debug))]
    #[serde(rename = "MessageRecieved")]
    MessageReceived(SignalMessage),
    #[evt(derive(Clone, Debug))]
    #[serde(skip)]
    ShowView(crate::View),
    #[evt(derive(Clone, Serialize, Deserialize, Debug))]
    Type(String),
    #[serde(skip)]
    AddHist(String, i64, bool),
    #[serde(skip)]
    ShowTheme(crate::config::Theme),
    IDLessMessage(SignalMessage),
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct SignalMessageList {
    #[serde(rename = "ID")]
    pub ID: String,
    pub messages: Vec<SignalMessage>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Chat {
    #[serde(rename = "ID")]
    pub ID: i32,
    pub name: String,
    pub tel: String,
    pub is_group: bool,
    pub last: String,
    pub timestamp: i64,
    // pub when: String,
    //pub c_type: i32,
    #[serde(deserialize_with = "parse_messages")]
    pub messages: Vec<SignalMessage>,
    /*#[serde(deserialize_with = "parse_messages")]
    pub messages: usize,*/
    /*#[serde(default)]
    pub force_enable: bool,*/
}
fn parse_messages<'de, D>(d: D) -> Result<Vec<SignalMessage>, D::Error>
where
    D: Deserializer<'de>,
{
    Deserialize::deserialize(d).map(|x: Option<_>| x.unwrap_or(vec![]))
}
/*fn parse_messages<'de, D>(d: D) -> Result<usize, D::Error>
where
    D: Deserializer<'de>,
{
    let msgs : Result<Vec<SignalMessage>, D::Error> = Deserialize::deserialize(d).map(|x: Option<_>| x.unwrap_or(vec![]));
    Ok(msgs?.len())
}*/
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct SignalCLIContainer {
    pub envelope: SignalCLIMessage,
}
#[serde(rename_all = "camelCase")]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct SignalCLIMessage {
    pub source: String,
    pub source_device: u8,
    pub timestamp: i64,
    pub message: Option<String>,
    pub is_read: Option<bool>,
    pub is_delivery: Option<bool>,
    pub data_message: Option<DataMessage>,
    pub sync_message: Option<SyncMessage>
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct SignalCLIContactInfo {
    pub number: String,
    pub name: String,
}
impl SignalCLIContactInfo {
    pub fn from_str(sti: impl Into<String>) -> Option<SignalCLIContactInfo> {
        if let Some(cap) = CONTACT_REG.captures(&sti.into()) {
            return Some(SignalCLIContactInfo {
                number: cap[1].to_string(),
                name: cap[2].to_string(),
            });
        }
        None
    }
}
#[serde(rename_all = "camelCase")]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct SyncMessage {
    pub sent_message: Option<SentMessage>,
}
#[serde(rename_all = "camelCase")]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct SentMessage {
    pub timestamp: u64,
    pub message: Option<String>,
    pub expires_in_seconds: u64,
    pub attachments: Option<Vec<SignalCLIAttachment>>,
    //pub group_info: 
    pub destination: String,
}
#[serde(rename_all = "camelCase")]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct DataMessage {
    pub timestamp: u64,
    pub message: Option<String>,
    pub expires_in_seconds: u64,
    pub attachments: Option<Vec<SignalCLIAttachment>>,
    //pub group_info: Option<GroupInfo>,
    pub destination: Option<String>,
}
#[serde(rename_all = "camelCase")]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct SignalCLIAttachment {
    pub content_type: String,
    pub filename: Option<String>,
    pub id: String,
    pub size: u64,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct SignalMessage {
    #[serde(rename = "ID")]
    pub ID: i32,
    /*#[serde(rename = "SID")]
    pub SID: i32,*/
    /*#[serde(rename = "ChatID")]
    pub chat_id: String,*/
    pub source: String,
    pub message: String,
    pub outgoing: bool,
    pub sent_at: i64,
    #[serde(deserialize_with = "parse_attachment")]
    pub attachment: Option<Vec<Attachment>>,
    //pub received_at: i64,
    /*pub h_time: String,
    pub c_type: i32,
    pub is_sent: bool,
    pub is_read: bool,
    pub flags: i32,
    pub expire_timer: i32,
    pub sending_error: bool,
    pub receipt: bool,
    pub status_message: bool,*/
}
fn parse_attachment<'de, D>(d: D) -> Result<Option<Vec<Attachment>>, D::Error>
where
    D: Deserializer<'de>,
{
    let vec: Option<String> = Deserialize::deserialize(d).ok();
    if let Some(vec) = vec {
        if let Some(vec) = serde_json::from_str::<Vec<Attachment>>(&vec).ok() {
            Ok(Some(vec))
        } else {
            Ok(None)
        }
    } else {
        Ok(None)
    }
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Attachment {
    pub file: String,
    pub file_name: String,
    pub c_type: AttachmentType,
}
#[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug, Clone)]
#[repr(u8)]
pub enum AttachmentType {
    Image = 2,
    Audio = 3,
    File = 0,
    Video = 5,
}
impl AttachmentType {
    pub fn from_mime(mime: &str) -> AttachmentType {
        if mime.contains("image") {
            return AttachmentType::Image;
        }
        AttachmentType::File
    }
}
impl PartialEq for SignalMessage {
    fn eq(&self, other: &Self) -> bool {
        self.ID == other.ID && self.message == other.message
    }
}
trait SignalResponseTrait {}
impl SignalResponseTrait for SignalResponse {}
#[serde(rename_all = "PascalCase")]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Contact {
    pub tel: String,
    //pub uuid: String,
    pub name: String,
    //pub color: String,
    //pub avatar: String,
    //pub blocked: bool,
    //pub expire_timer: i32,
}
pub struct SignalSession<'a> {
    pub sink: SplitSink<WebSocketStream<tokio::net::TcpStream>, TMessage>,
    pub stream: BoxStream<'a, SignalResponse>,
}
impl<'a> SignalSession<'a> {
    pub fn from_socket(socket: WebSocketStream<tokio::net::TcpStream>) -> SignalSession<'a> {
        let (write, read) = socket.split();
        let st = read.filter_map(|x| {
            if let Ok(attempt) =
                serde_json::from_str::<SignalResponse>(&x.unwrap().into_text().unwrap())
            {
                return future::ready(Some(attempt));
            }
            future::ready(None)
        });
        SignalSession {
            sink: write,
            stream: st.boxed(),
        }
    }
    pub async fn send(&mut self, req: SignalRequest) -> Result<(), Box<dyn std::error::Error>> {
        Ok(self
            .sink
            .send(TMessage::Text(serde_json::to_string(&req)?))
            .await?)
    }
    pub async fn send_res<T>(&mut self, req: SignalRequest) -> Result<T, Box<dyn std::error::Error>>
    where
        T: TryFrom<SignalResponse>,
    {
        self.send(req).await?;
        Ok(self
            .stream
            .by_ref()
            .filter_map(|x| {
                if let Ok(v) = T::try_from(x) {
                    future::ready(Some(v))
                } else {
                    future::ready(None)
                }
            })
            .next()
            .await
            .unwrap())
    }
}