Skip to main content

libsimplex_rs/
model.rs

1use serde_json::Value;
2
3#[derive(Clone, Debug, Eq, PartialEq)]
4pub struct User {
5    pub id: i64,
6    pub display_name: String,
7    pub notifications: bool,
8    pub active: bool,
9}
10
11pub type Profile = User;
12
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub enum ServerProtocol {
15    Smp,
16    Xftp,
17}
18
19impl ServerProtocol {
20    pub fn label(self) -> &'static str {
21        match self {
22            Self::Smp => "SMP",
23            Self::Xftp => "XFTP",
24        }
25    }
26
27    pub fn json_key(self) -> &'static str {
28        match self {
29            Self::Smp => "smpServers",
30            Self::Xftp => "xftpServers",
31        }
32    }
33}
34
35#[derive(Clone, Debug, Eq, PartialEq)]
36pub struct ServerEntry {
37    pub protocol: ServerProtocol,
38    pub address: String,
39    pub enabled: bool,
40    pub preset: bool,
41}
42
43#[derive(Clone, Debug, Eq, PartialEq)]
44pub struct ChatSummary {
45    pub chat_ref: ChatRef,
46    pub display_name: String,
47    pub unread_count: u64,
48}
49
50#[derive(Clone, Debug, Eq, Hash, PartialEq)]
51pub struct ChatRef(pub String);
52
53#[derive(Clone, Debug, Eq, PartialEq)]
54pub struct Message {
55    pub id: i64,
56    pub text: String,
57    pub timestamp: String,
58    pub outgoing: bool,
59    pub reactions: Vec<MessageReaction>,
60    pub attachment: Option<Attachment>,
61}
62
63#[derive(Clone, Copy, Debug, Eq, PartialEq)]
64pub enum AttachmentKind {
65    File,
66    Audio,
67    Image,
68    Video,
69}
70
71#[derive(Clone, Debug, Eq, PartialEq)]
72pub struct Attachment {
73    pub id: i64,
74    pub name: String,
75    pub size: i64,
76    pub kind: AttachmentKind,
77    pub status: String,
78    pub progress: Option<u8>,
79    pub path: Option<String>,
80}
81
82#[derive(Clone, Debug, Eq, PartialEq)]
83pub struct MessageReaction {
84    pub emoji: String,
85    pub count: u64,
86    pub user_reacted: bool,
87}
88
89#[derive(Clone, Debug, Default, Eq, PartialEq)]
90pub struct ChatFeatures {
91    pub disappearing_messages: bool,
92    pub full_deletion: bool,
93    pub reactions: bool,
94    pub voice_messages: bool,
95    pub files_and_media: bool,
96}
97
98#[derive(Clone, Debug, Default, Eq, PartialEq)]
99pub struct ChatDeletionSettings {
100    pub local_ttl: Option<i64>,
101    pub disappearing_ttl: Option<i64>,
102}
103
104#[derive(Clone, Debug)]
105pub enum SimplexEvent {
106    Ready {
107        user: User,
108        chats: Vec<ChatSummary>,
109    },
110    ProfilesLoaded(Vec<Profile>),
111    ProfileActivated {
112        user: User,
113        chats: Vec<ChatSummary>,
114    },
115    ProfileCreated {
116        user: User,
117        profiles: Vec<Profile>,
118        chats: Vec<ChatSummary>,
119    },
120    ProfileDeleted {
121        profiles: Vec<Profile>,
122        active_user: Option<User>,
123        chats: Vec<ChatSummary>,
124    },
125    ProfileDeleteFailed(String),
126    SettingChanged(String),
127    AutoDeleteLoaded(i64),
128    AutoDeleteChanged(i64),
129    AutoDeleteFailed(String),
130    ChatDeletionLoaded {
131        chat_ref: ChatRef,
132        settings: ChatDeletionSettings,
133    },
134    ChatDeletionChanged {
135        chat_ref: ChatRef,
136        settings: ChatDeletionSettings,
137    },
138    ChatDeletionFailed(String),
139    ConversationFeaturesLoaded {
140        chat_ref: ChatRef,
141        features: ChatFeatures,
142    },
143    ConversationFeaturesChanged {
144        chat_ref: ChatRef,
145        features: ChatFeatures,
146    },
147    ConversationFeaturesFailed(String),
148    ChatDeleted {
149        chat_ref: ChatRef,
150        chats: Vec<ChatSummary>,
151    },
152    ChatDeleteFailed(String),
153    FileDownloadStarted {
154        file_id: i64,
155        path: String,
156    },
157    FileDownloadFailed {
158        file_id: i64,
159        error: String,
160    },
161    FileDownloadCancelled {
162        file_id: i64,
163    },
164    FileUpdated {
165        chat_ref: ChatRef,
166        message: Message,
167    },
168    ServersLoaded(Vec<ServerEntry>),
169    ServersUpdateFailed(String),
170    ChatFeaturesLoaded(ChatFeatures),
171    InvitationCreated(String),
172    InvitationFailed(String),
173    ConnectionStarted,
174    ConnectionFailed(String),
175    ChatLoaded {
176        chat_ref: ChatRef,
177        messages: Vec<Message>,
178    },
179    ChatMarkedRead(ChatRef),
180    ContactConnected {
181        chats: Vec<ChatSummary>,
182        chat_ref: ChatRef,
183    },
184    MessageReceived {
185        chat_ref: ChatRef,
186        message: Message,
187    },
188    ChatLoadFailed {
189        chat_ref: ChatRef,
190        error: String,
191    },
192    MessageSent {
193        chat_ref: ChatRef,
194        text: String,
195    },
196    MessageSendFailed {
197        chat_ref: ChatRef,
198        error: String,
199    },
200    ReactionChanged {
201        chat_ref: ChatRef,
202        item_id: i64,
203        emoji: String,
204        added: bool,
205        user_reacted: bool,
206    },
207    NoActiveUser,
208    Failed(String),
209}
210
211pub fn invitation_link(value: &Value) -> Result<String, String> {
212    let result = value
213        .get("result")
214        .ok_or_else(|| response_error(value, "invitation"))?;
215    if result.get("type").and_then(Value::as_str) != Some("invitation") {
216        return Err(response_error(value, "invitation"));
217    }
218    let link = result
219        .pointer("/connLinkInvitation/connShortLink")
220        .and_then(Value::as_str)
221        .filter(|link| !link.is_empty())
222        .or_else(|| {
223            result
224                .pointer("/connLinkInvitation/connFullLink")
225                .and_then(Value::as_str)
226        })
227        .ok_or("invitation response has no connection link")?;
228    Ok(link.to_owned())
229}
230
231pub fn connection_started(value: &Value) -> Result<(), String> {
232    let result = value
233        .get("result")
234        .ok_or_else(|| response_error(value, "connection confirmation"))?;
235    match result.get("type").and_then(Value::as_str) {
236        Some(
237            "sentConfirmation"
238            | "sentInvitation"
239            | "startedConnectionToContact"
240            | "startedConnectionToGroup"
241            | "sentInvitationToContact",
242        ) => Ok(()),
243        _ => Err(response_error(value, "connection confirmation")),
244    }
245}
246
247#[cfg(test)]
248pub fn smp_servers(value: &Value) -> Result<Vec<String>, String> {
249    let result = value
250        .get("result")
251        .ok_or_else(|| response_error(value, "SMP servers"))?;
252    if result.get("type").and_then(Value::as_str) != Some("userServers") {
253        return Err(response_error(value, "SMP servers"));
254    }
255    let mut servers = Vec::new();
256    collect_smp_servers(result, &mut servers);
257    servers.sort();
258    servers.dedup();
259    Ok(servers)
260}
261
262pub fn server_entries(value: &Value) -> Result<Vec<ServerEntry>, String> {
263    let groups = value
264        .pointer("/result/userServers")
265        .and_then(Value::as_array)
266        .ok_or_else(|| response_error(value, "user servers"))?;
267    let mut entries = Vec::new();
268    for group in groups {
269        for protocol in [ServerProtocol::Smp, ServerProtocol::Xftp] {
270            for server in group
271                .get(protocol.json_key())
272                .and_then(Value::as_array)
273                .into_iter()
274                .flatten()
275            {
276                let Some(address) = server.get("server").and_then(Value::as_str) else {
277                    continue;
278                };
279                if server
280                    .get("deleted")
281                    .and_then(Value::as_bool)
282                    .unwrap_or(false)
283                {
284                    continue;
285                }
286                entries.push(ServerEntry {
287                    protocol,
288                    address: address.to_owned(),
289                    enabled: server
290                        .get("enabled")
291                        .and_then(Value::as_bool)
292                        .unwrap_or(true),
293                    preset: server
294                        .get("preset")
295                        .and_then(Value::as_bool)
296                        .unwrap_or(false),
297                });
298            }
299        }
300    }
301    Ok(entries)
302}
303
304pub fn profile_and_features(value: &Value) -> Result<(Value, ChatFeatures), String> {
305    let result = value
306        .get("result")
307        .ok_or_else(|| response_error(value, "user profile"))?;
308    if result.get("type").and_then(Value::as_str) != Some("userProfile") {
309        return Err(response_error(value, "user profile"));
310    }
311    let profile = result
312        .get("profile")
313        .cloned()
314        .ok_or("userProfile response has no profile")?;
315    let preferences = profile.get("preferences");
316    let enabled = |name: &str, default: bool| {
317        preferences
318            .and_then(|prefs| prefs.get(name))
319            .and_then(|pref| pref.get("allow"))
320            .and_then(Value::as_str)
321            .map(|allow| allow != "no")
322            .unwrap_or(default)
323    };
324    let features = ChatFeatures {
325        disappearing_messages: enabled("timedMessages", false),
326        full_deletion: enabled("fullDelete", false),
327        reactions: enabled("reactions", true),
328        voice_messages: enabled("voice", true),
329        files_and_media: enabled("files", true),
330    };
331    Ok((profile, features))
332}
333
334pub fn connected_contact(value: &Value) -> Option<(i64, ChatRef)> {
335    let result = value.get("result")?;
336    if result.get("type")?.as_str()? != "contactConnected" {
337        return None;
338    }
339    let user_id = result.pointer("/user/userId")?.as_i64()?;
340    let contact_id = result.pointer("/contact/contactId")?.as_i64()?;
341    Some((user_id, ChatRef(format!("@{contact_id}"))))
342}
343
344pub fn reaction_change(value: &Value) -> Option<(ChatRef, i64, String, bool, bool)> {
345    let result = value.get("result")?;
346    if result.get("type")?.as_str()? != "chatItemReaction" {
347        return None;
348    }
349    let reaction = result.get("reaction")?;
350    let chat_ref = chat_ref(reaction.get("chatInfo")?).ok()?;
351    let chat_reaction = reaction.get("chatReaction")?;
352    let item_id = chat_reaction.pointer("/chatItem/meta/itemId")?.as_i64()?;
353    let emoji = chat_reaction
354        .pointer("/reaction/emoji")?
355        .as_str()?
356        .to_owned();
357    let direction = chat_reaction.pointer("/chatDir/type")?.as_str()?;
358    Some((
359        chat_ref,
360        item_id,
361        emoji,
362        result.get("added")?.as_bool()?,
363        direction.to_ascii_lowercase().contains("snd"),
364    ))
365}
366
367#[cfg(test)]
368fn collect_smp_servers(value: &Value, servers: &mut Vec<String>) {
369    match value {
370        Value::String(server) if server.starts_with("smp://") => servers.push(server.clone()),
371        Value::Array(values) => {
372            for value in values {
373                collect_smp_servers(value, servers);
374            }
375        }
376        Value::Object(values) => {
377            for value in values.values() {
378                collect_smp_servers(value, servers);
379            }
380        }
381        _ => {}
382    }
383}
384
385pub fn active_user(value: &Value) -> Result<Option<User>, String> {
386    if value
387        .pointer("/error/errorType/type")
388        .and_then(Value::as_str)
389        == Some("noActiveUser")
390    {
391        return Ok(None);
392    }
393    let result = value
394        .get("result")
395        .ok_or_else(|| response_error(value, "active user"))?;
396    if result.get("type").and_then(Value::as_str) != Some("activeUser") {
397        return Err(response_error(value, "active user"));
398    }
399    let user = result
400        .get("user")
401        .ok_or("activeUser response has no user")?;
402    Ok(Some(User {
403        id: user
404            .get("userId")
405            .and_then(Value::as_i64)
406            .ok_or("activeUser response has no numeric userId")?,
407        display_name: user
408            .get("localDisplayName")
409            .and_then(Value::as_str)
410            .unwrap_or("SimpleX user")
411            .to_owned(),
412        notifications: user
413            .get("showNtfs")
414            .and_then(Value::as_bool)
415            .unwrap_or(true),
416        active: user
417            .get("activeUser")
418            .and_then(Value::as_bool)
419            .unwrap_or(true),
420    }))
421}
422
423pub fn profiles(value: &Value) -> Result<Vec<Profile>, String> {
424    let result = value
425        .get("result")
426        .ok_or_else(|| response_error(value, "profiles"))?;
427    if result.get("type").and_then(Value::as_str) != Some("usersList") {
428        return Err(response_error(value, "profiles"));
429    }
430    result
431        .get("users")
432        .and_then(Value::as_array)
433        .ok_or("usersList response has no users array")?
434        .iter()
435        .map(|info| {
436            let user = info.get("user").ok_or("profile has no user")?;
437            Ok(Profile {
438                id: user
439                    .get("userId")
440                    .and_then(Value::as_i64)
441                    .ok_or("profile has no numeric userId")?,
442                display_name: user
443                    .get("localDisplayName")
444                    .and_then(Value::as_str)
445                    .unwrap_or("SimpleX user")
446                    .to_owned(),
447                notifications: user
448                    .get("showNtfs")
449                    .and_then(Value::as_bool)
450                    .unwrap_or(true),
451                active: user
452                    .get("activeUser")
453                    .and_then(Value::as_bool)
454                    .unwrap_or(false),
455            })
456        })
457        .collect()
458}
459
460pub fn chats(value: &Value) -> Result<Vec<ChatSummary>, String> {
461    let result = value
462        .get("result")
463        .ok_or_else(|| response_error(value, "chat list"))?;
464    if !matches!(
465        result.get("type").and_then(Value::as_str),
466        Some("apiChats" | "chats")
467    ) {
468        return Err(response_error(value, "chat list"));
469    }
470    result
471        .get("chats")
472        .and_then(Value::as_array)
473        .ok_or("chat-list response has no chats array")?
474        .iter()
475        .filter(|chat| {
476            let Some(info) = chat.get("chatInfo") else {
477                return false;
478            };
479            if info.get("type").and_then(Value::as_str) == Some("local") {
480                return false;
481            }
482            info.pointer("/contact/localDisplayName")
483                .and_then(Value::as_str)
484                != Some("Ask SimpleX Team")
485        })
486        .map(|chat| {
487            let info = chat.get("chatInfo").ok_or("chat has no chatInfo")?;
488            let chat_ref = chat_ref(info)?;
489            let display_name = [
490                "contact",
491                "groupInfo",
492                "noteFolder",
493                "contactRequest",
494                "contactConnection",
495            ]
496            .iter()
497            .find_map(|key| info.get(key))
498            .and_then(|info| info.get("localDisplayName"))
499            .and_then(Value::as_str)
500            .or_else(|| info.get("localDisplayName").and_then(Value::as_str))
501            .unwrap_or("Unknown chat")
502            .to_owned();
503            let unread_count = chat
504                .pointer("/chatStats/unreadCount")
505                .and_then(Value::as_u64)
506                .unwrap_or(0);
507            Ok(ChatSummary {
508                chat_ref,
509                display_name,
510                unread_count,
511            })
512        })
513        .collect()
514}
515
516pub fn chat_messages(value: &Value) -> Result<(ChatRef, Vec<Message>), String> {
517    let result = value
518        .get("result")
519        .ok_or_else(|| response_error(value, "chat"))?;
520    if result.get("type").and_then(Value::as_str) != Some("apiChat") {
521        return Err(response_error(value, "chat"));
522    }
523    let chat = result.get("chat").ok_or("apiChat response has no chat")?;
524    let chat_ref = chat_ref(chat.get("chatInfo").ok_or("chat has no chatInfo")?)?;
525    let messages = chat
526        .get("chatItems")
527        .and_then(Value::as_array)
528        .ok_or("chat has no chatItems array")?
529        .iter()
530        .filter_map(parse_message)
531        .collect();
532    Ok((chat_ref, messages))
533}
534
535pub fn new_messages(value: &Value) -> Vec<(ChatRef, Message)> {
536    let Some(result) = value.get("result") else {
537        return Vec::new();
538    };
539    if result.get("type").and_then(Value::as_str) != Some("newChatItems") {
540        return Vec::new();
541    }
542    result
543        .get("chatItems")
544        .and_then(Value::as_array)
545        .into_iter()
546        .flatten()
547        .filter_map(|item| {
548            let chat_ref = chat_ref(item.get("chatInfo")?).ok()?;
549            let message = parse_message(item.get("chatItem")?)?;
550            Some((chat_ref, message))
551        })
552        .collect()
553}
554
555fn chat_ref(info: &Value) -> Result<ChatRef, String> {
556    let (prefix, object, id_key) = match info.get("type").and_then(Value::as_str) {
557        Some("direct") => ("@", "contact", "contactId"),
558        Some("group") => ("#", "groupInfo", "groupId"),
559        Some("local") => ("*", "noteFolder", "noteFolderId"),
560        Some("contactRequest") => ("<@", "contactRequest", "contactRequestId"),
561        Some("contactConnection") => (":", "contactConnection", "pccConnId"),
562        _ => return Err("unsupported chat type".into()),
563    };
564    let id = info
565        .get(object)
566        .and_then(|v| v.get(id_key))
567        .and_then(Value::as_i64)
568        .ok_or_else(|| format!("chatInfo has no numeric {id_key}"))?;
569    Ok(ChatRef(format!("{prefix}{id}")))
570}
571
572fn parse_message(item: &Value) -> Option<Message> {
573    if !matches!(
574        item.pointer("/content/type").and_then(Value::as_str),
575        Some("sndMsgContent" | "rcvMsgContent")
576    ) {
577        return None;
578    }
579    let meta = item.get("meta")?;
580    let text = meta
581        .get("itemText")
582        .and_then(Value::as_str)
583        .unwrap_or("")
584        .to_owned();
585    let message_kind = item
586        .pointer("/content/msgContent/type")
587        .and_then(Value::as_str);
588    let attachment = item
589        .get("file")
590        .and_then(|file| parse_attachment(file, message_kind));
591    if text.is_empty() && attachment.is_none() {
592        return None;
593    }
594    let direction = item
595        .pointer("/chatDir/type")
596        .and_then(Value::as_str)
597        .unwrap_or("");
598    Some(Message {
599        id: meta.get("itemId")?.as_i64()?,
600        text,
601        timestamp: meta
602            .get("itemTs")
603            .and_then(Value::as_str)
604            .unwrap_or("")
605            .to_owned(),
606        outgoing: direction.to_ascii_lowercase().contains("snd"),
607        reactions: item
608            .get("reactions")
609            .and_then(Value::as_array)
610            .into_iter()
611            .flatten()
612            .filter_map(|reaction| {
613                Some(MessageReaction {
614                    emoji: reaction.pointer("/reaction/emoji")?.as_str()?.to_owned(),
615                    count: reaction.get("totalReacted")?.as_u64()?,
616                    user_reacted: reaction
617                        .get("userReacted")
618                        .and_then(Value::as_bool)
619                        .unwrap_or(false),
620                })
621            })
622            .collect(),
623        attachment,
624    })
625}
626
627fn parse_attachment(file: &Value, content_type: Option<&str>) -> Option<Attachment> {
628    let name = file.get("fileName")?.as_str()?.to_owned();
629    let kind = match content_type {
630        Some("image") => AttachmentKind::Image,
631        Some("video") => AttachmentKind::Video,
632        Some("voice") => AttachmentKind::Audio,
633        _ => attachment_kind_from_name(&name),
634    };
635    Some(Attachment {
636        id: file.get("fileId")?.as_i64()?,
637        name,
638        size: file.get("fileSize").and_then(Value::as_i64).unwrap_or(0),
639        kind,
640        status: file
641            .pointer("/fileStatus/type")
642            .and_then(Value::as_str)
643            .unwrap_or("unknown")
644            .to_owned(),
645        progress: file
646            .pointer("/fileStatus/rcvProgress")
647            .and_then(Value::as_i64)
648            .zip(file.pointer("/fileStatus/rcvTotal").and_then(Value::as_i64))
649            .and_then(|(progress, total)| {
650                (total > 0).then(|| {
651                    u8::try_from(
652                        progress
653                            .saturating_mul(100)
654                            .saturating_div(total)
655                            .clamp(0, 100),
656                    )
657                    .unwrap_or(100)
658                })
659            }),
660        path: file
661            .pointer("/fileSource/filePath")
662            .and_then(Value::as_str)
663            .map(str::to_owned),
664    })
665}
666
667fn attachment_kind_from_name(name: &str) -> AttachmentKind {
668    let extension = name.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
669    match extension.as_str() {
670        "jpg" | "jpeg" | "png" | "gif" | "webp" | "bmp" | "svg" | "heic" => AttachmentKind::Image,
671        "mp3" | "m4a" | "aac" | "wav" | "ogg" | "opus" | "flac" => AttachmentKind::Audio,
672        "mp4" | "m4v" | "mkv" | "mov" | "webm" | "avi" => AttachmentKind::Video,
673        _ => AttachmentKind::File,
674    }
675}
676
677pub fn file_update(value: &Value) -> Option<(ChatRef, Message)> {
678    let result = value.get("result")?;
679    let item = result.get("chatItem").or_else(|| result.get("chatItem_"))?;
680    let mut message = parse_message(item.get("chatItem")?)?;
681    if let Some(attachment) = &mut message.attachment
682        && let Some((received, total)) = result
683            .get("receivedSize")
684            .and_then(Value::as_i64)
685            .zip(result.get("totalSize").and_then(Value::as_i64))
686        && total > 0
687    {
688        attachment.progress = Some(
689            u8::try_from(
690                received
691                    .saturating_mul(100)
692                    .saturating_div(total)
693                    .clamp(0, 100),
694            )
695            .unwrap_or(100),
696        );
697    }
698    Some((chat_ref(item.get("chatInfo")?).ok()?, message))
699}
700
701fn response_error(value: &Value, expected: &str) -> String {
702    let detail = value
703        .pointer("/error/errorType/type")
704        .or_else(|| value.pointer("/error/type"))
705        .or_else(|| value.pointer("/result/type"))
706        .and_then(Value::as_str)
707        .unwrap_or("unknown response");
708    format!("expected {expected}, received {detail}")
709}
710
711#[cfg(test)]
712mod tests {
713    use super::*;
714    use serde_json::json;
715
716    #[test]
717    fn parses_active_user_and_no_user() {
718        let user = active_user(&json!({"result": {"type": "activeUser", "user": {
719            "userId": 7, "localDisplayName": "alice"
720        }}}))
721        .unwrap()
722        .unwrap();
723        assert_eq!(
724            user,
725            User {
726                id: 7,
727                display_name: "alice".into(),
728                notifications: true,
729                active: true,
730            }
731        );
732        assert_eq!(
733            active_user(&json!({"error": {"type": "error", "errorType": {
734                "type": "noActiveUser"
735            }}}))
736            .unwrap(),
737            None
738        );
739    }
740
741    #[test]
742    fn parses_chat_summaries() {
743        let parsed = chats(&json!({"result": {"type": "apiChats", "chats": [{
744            "chatInfo": {"type": "direct", "contact": {"contactId": 9, "localDisplayName": "bob"}},
745            "chatItems": [], "chatStats": {"unreadCount": 3}
746        }]}}))
747        .unwrap();
748        assert_eq!(
749            parsed,
750            vec![ChatSummary {
751                chat_ref: ChatRef("@9".into()),
752                display_name: "bob".into(),
753                unread_count: 3
754            }]
755        );
756    }
757
758    #[test]
759    fn parses_chat_history_and_live_item() {
760        let info =
761            json!({"type": "direct", "contact": {"contactId": 9, "localDisplayName": "bob"}});
762        let item = json!({"chatDir": {"type": "directSnd"},
763            "content": {"type": "sndMsgContent", "msgContent": {"type": "text", "text": "hello"}}, "meta": {
764            "itemId": 12, "itemText": "hello", "itemTs": "2026-08-16T10:00:00Z"
765        }});
766        let (chat_ref, messages) = chat_messages(&json!({"result": {"type": "apiChat", "chat": {
767            "chatInfo": info, "chatItems": [item], "chatStats": {}
768        }}}))
769        .unwrap();
770        assert_eq!(chat_ref, ChatRef("@9".into()));
771        assert!(messages[0].outgoing);
772        assert_eq!(messages[0].text, "hello");
773    }
774
775    #[test]
776    fn protocol_feature_items_are_not_user_messages() {
777        let item = json!({
778            "chatDir": {"type": "directSnd"},
779            "content": {"type": "sndChatFeature", "feature": "calls"},
780            "meta": {"itemId": 13, "itemText": "Audio/video calls: off"}
781        });
782        assert_eq!(parse_message(&item), None);
783    }
784
785    #[test]
786    fn parses_profile_chat_features() {
787        let (_, features) = profile_and_features(&json!({"result": {
788            "type": "userProfile", "profile": {
789                "displayName": "alice", "fullName": "", "preferences": {
790                    "timedMessages": {"allow": "no"},
791                    "fullDelete": {"allow": "yes"},
792                    "reactions": {"allow": "yes"},
793                    "voice": {"allow": "no"},
794                    "files": {"allow": "yes"},
795                    "calls": {"allow": "no"}
796                }
797            }
798        }}))
799        .unwrap();
800        assert!(!features.disappearing_messages);
801        assert!(features.full_deletion);
802        assert!(features.reactions);
803        assert!(!features.voice_messages);
804        assert!(features.files_and_media);
805    }
806
807    #[test]
808    fn prefers_the_short_invitation_link() {
809        let link = invitation_link(&json!({"result": {
810            "type": "invitation",
811            "connLinkInvitation": {
812                "connFullLink": "simplex:/contact#full",
813                "connShortLink": "https://simplex.chat/contact#short"
814            }
815        }}))
816        .unwrap();
817        assert_eq!(link, "https://simplex.chat/contact#short");
818    }
819
820    #[test]
821    fn recognizes_started_invitation_connections() {
822        for response_type in [
823            "sentConfirmation",
824            "sentInvitation",
825            "startedConnectionToContact",
826            "startedConnectionToGroup",
827            "sentInvitationToContact",
828        ] {
829            assert!(
830                connection_started(&json!({"result": {"type": response_type}})).is_ok(),
831                "{response_type} should confirm a started connection"
832            );
833        }
834        assert!(connection_started(&json!({"error": {"type": "chatCmdError"}})).is_err());
835    }
836
837    #[test]
838    fn extracts_and_deduplicates_profile_smp_servers() {
839        let servers = smp_servers(&json!({"result": {
840            "type": "userServers",
841            "userServers": [{"smpServers": [
842                {"server": "smp://fingerprint@smp11.simplex.im,onion"},
843                {"server": "smp://fingerprint@smp11.simplex.im,onion"}
844            ]}]
845        }}))
846        .unwrap();
847        assert_eq!(
848            servers,
849            vec!["smp://fingerprint@smp11.simplex.im,onion".to_owned()]
850        );
851    }
852
853    #[test]
854    fn parses_smp_and_xftp_server_configuration() {
855        let servers = server_entries(&json!({"result": {
856            "type": "userServers",
857            "userServers": [{
858                "operator": {"tradeName": "SimpleX Chat"},
859                "smpServers": [{
860                    "server": "smp://key@smp.example",
861                    "enabled": true,
862                    "preset": true,
863                    "deleted": false
864                }],
865                "xftpServers": [{
866                    "server": "xftp://key@xftp.example",
867                    "enabled": false,
868                    "preset": true,
869                    "deleted": false
870                }]
871            }]
872        }}))
873        .unwrap();
874        assert_eq!(
875            servers,
876            vec![
877                ServerEntry {
878                    protocol: ServerProtocol::Smp,
879                    address: "smp://key@smp.example".into(),
880                    enabled: true,
881                    preset: true,
882                },
883                ServerEntry {
884                    protocol: ServerProtocol::Xftp,
885                    address: "xftp://key@xftp.example".into(),
886                    enabled: false,
887                    preset: true,
888                },
889            ]
890        );
891    }
892
893    #[test]
894    fn recognizes_a_connected_invitation_contact() {
895        let connected = connected_contact(&json!({"result": {
896            "type": "contactConnected",
897            "user": {"userId": 4},
898            "contact": {"contactId": 19, "localDisplayName": "bob"}
899        }}));
900        assert_eq!(connected, Some((4, ChatRef("@19".into()))));
901        assert_eq!(
902            connected_contact(&json!({"result": {"type": "cmdOk"}})),
903            None
904        );
905    }
906
907    #[test]
908    fn parses_message_reactions_and_live_reaction_changes() {
909        let item = json!({
910            "chatDir": {"type": "directRcv"},
911            "content": {"type": "rcvMsgContent", "msgContent": {"type": "text", "text": "hi"}},
912            "meta": {"itemId": 22, "itemText": "hi"},
913            "reactions": [{
914                "reaction": {"type": "emoji", "emoji": "👍"},
915                "userReacted": true,
916                "totalReacted": 3
917            }]
918        });
919        let message = parse_message(&item).unwrap();
920        assert_eq!(
921            message.reactions,
922            vec![MessageReaction {
923                emoji: "👍".into(),
924                count: 3,
925                user_reacted: true,
926            }]
927        );
928
929        let update = reaction_change(&json!({"result": {
930            "type": "chatItemReaction",
931            "added": true,
932            "reaction": {
933                "chatInfo": {"type": "direct", "contact": {"contactId": 7}},
934                "chatReaction": {
935                    "chatDir": {"type": "directRcv"},
936                    "chatItem": {"meta": {"itemId": 22}},
937                    "reaction": {"type": "emoji", "emoji": "😂"}
938                }
939            }
940        }}));
941        assert_eq!(
942            update,
943            Some((ChatRef("@7".into()), 22, "😂".into(), true, false))
944        );
945    }
946
947    #[test]
948    fn parses_file_only_messages_and_file_updates() {
949        let chat_item = json!({
950            "chatDir": {"type": "directRcv"},
951            "content": {
952                "type": "rcvMsgContent",
953                "msgContent": {"type": "image", "text": "", "image": "preview"}
954            },
955            "meta": {"itemId": 33, "itemText": ""},
956            "reactions": [],
957            "file": {
958                "fileId": 44,
959                "fileName": "photo.png",
960                "fileSize": 1234,
961                "fileStatus": {"type": "rcvInvitation"},
962                "fileProtocol": "xftp"
963            }
964        });
965        let message = parse_message(&chat_item).unwrap();
966        let attachment = message.attachment.unwrap();
967        assert_eq!(attachment.kind, AttachmentKind::Image);
968        assert_eq!(attachment.name, "photo.png");
969        assert_eq!(attachment.status, "rcvInvitation");
970
971        let update = json!({"result": {
972            "type": "rcvFileProgressXFTP",
973            "receivedSize": 25,
974            "totalSize": 100,
975            "chatItem_": {
976                "chatInfo": {"type": "direct", "contact": {"contactId": 7}},
977                "chatItem": chat_item
978            }
979        }});
980        let (chat_ref, updated) = file_update(&update).unwrap();
981        assert_eq!(chat_ref, ChatRef("@7".into()));
982        assert_eq!(updated.id, 33);
983        assert_eq!(updated.attachment.unwrap().progress, Some(25));
984    }
985}