Skip to main content

libsimplex_rs/
client.rs

1use std::{
2    sync::{
3        Arc,
4        mpsc::{self, Receiver, Sender},
5    },
6    thread,
7    time::Duration,
8};
9
10use crate::{
11    Config,
12    ffi::{SimplexApi, SimplexPaths},
13    model::{self, ChatRef, ServerProtocol, SimplexEvent},
14};
15
16#[derive(Debug)]
17pub enum SimplexCommand {
18    LoadChat(ChatRef),
19    MarkChatRead(ChatRef),
20    SendMessage {
21        chat_ref: ChatRef,
22        text: String,
23    },
24    SendReaction {
25        chat_ref: ChatRef,
26        item_id: i64,
27        emoji: String,
28    },
29    ReceiveFile {
30        file_id: i64,
31        file_name: String,
32    },
33    CancelFile {
34        file_id: i64,
35    },
36    ActivateProfile(i64),
37    CreateProfile(String),
38    DeleteProfile(i64),
39    SetAutoDelete {
40        user_id: i64,
41        seconds: i64,
42    },
43    LoadChatDeletion {
44        chat_ref: ChatRef,
45    },
46    SetChatDeletion {
47        user_id: i64,
48        chat_ref: ChatRef,
49        seconds: Option<i64>,
50    },
51    LoadConversationFeatures {
52        chat_ref: ChatRef,
53    },
54    SetConversationFeature {
55        chat_ref: ChatRef,
56        feature: ChatFeature,
57        enabled: bool,
58    },
59    DeleteChat {
60        user_id: i64,
61        chat_ref: ChatRef,
62        mode: ChatDeleteMode,
63    },
64    CreateInvitation {
65        user_id: i64,
66    },
67    ConnectInvitation {
68        user_id: i64,
69        link: String,
70    },
71    SetChatFeature {
72        user_id: i64,
73        feature: ChatFeature,
74        enabled: bool,
75    },
76    SetServerEnabled {
77        user_id: i64,
78        protocol: ServerProtocol,
79        address: String,
80        enabled: bool,
81    },
82    AddServer {
83        user_id: i64,
84        protocol: ServerProtocol,
85        address: String,
86    },
87}
88
89#[derive(Clone, Copy, Debug)]
90pub enum ChatFeature {
91    FullDeletion,
92    Reactions,
93    VoiceMessages,
94    FilesAndMedia,
95}
96
97#[derive(Clone, Copy, Debug, Eq, PartialEq)]
98pub enum ChatDeleteMode {
99    Conversation,
100    Contact,
101    BlockContact,
102}
103
104struct DeletedProfileState {
105    profiles: Vec<model::Profile>,
106    active_user: Option<model::User>,
107    chats: Vec<model::ChatSummary>,
108}
109
110pub fn spawn(
111    api: Arc<SimplexApi>,
112    config: Config,
113    sender: Sender<SimplexEvent>,
114) -> Sender<SimplexCommand> {
115    let (command_sender, commands) = mpsc::channel();
116    thread::Builder::new()
117        .name("simplex-core".into())
118        .spawn(move || {
119            if let Err(error) = run(&api, &config, &sender, &commands) {
120                let _ = sender.send(SimplexEvent::Failed(error));
121            }
122        })
123        .expect("failed to spawn SimpleX worker");
124    command_sender
125}
126
127fn run(
128    api: &Arc<SimplexApi>,
129    config: &Config,
130    sender: &Sender<SimplexEvent>,
131    commands: &Receiver<SimplexCommand>,
132) -> Result<(), String> {
133    let paths = SimplexPaths::at(&config.data_directory);
134    paths
135        .create()
136        .map_err(|e| format!("cannot create {}: {e}", paths.root.display()))?;
137    let (controller, migration) = api
138        .open(&paths.database_prefix, "", "yesUp")
139        .map_err(|e| e.to_string())?;
140    if migration.get("error").is_some() {
141        return Err(format!("database migration failed: {migration}"));
142    }
143
144    let profiles = load_profiles(&controller)?;
145    sender
146        .send(SimplexEvent::ProfilesLoaded(profiles))
147        .map_err(|e| e.to_string())?;
148
149    let Some(user) = model::active_user(&controller.command("/u").map_err(|e| e.to_string())?)?
150    else {
151        sender
152            .send(SimplexEvent::NoActiveUser)
153            .map_err(|e| e.to_string())?;
154        return command_loop(controller, &config.download_directory, sender, commands);
155    };
156    controller.command("/_start").map_err(|e| e.to_string())?;
157    send_auto_delete(&controller, sender, user.id)?;
158    send_servers(&controller, sender, user.id)?;
159    load_chat_features(&controller, sender, user.id, true)?;
160    let chats = load_chats(&controller, user.id)?;
161    sender
162        .send(SimplexEvent::Ready { user, chats })
163        .map_err(|e| e.to_string())?;
164
165    command_loop(controller, &config.download_directory, sender, commands)
166}
167
168fn command_loop(
169    controller: crate::ffi::SimplexController,
170    download_directory: &std::path::Path,
171    sender: &Sender<SimplexEvent>,
172    commands: &Receiver<SimplexCommand>,
173) -> Result<(), String> {
174    loop {
175        while let Ok(command) = commands.try_recv() {
176            match command {
177                SimplexCommand::LoadChat(requested_ref) => {
178                    let response =
179                        controller.command(&format!("/_get chat {} count=100", requested_ref.0));
180                    let event = match response
181                        .map_err(|e| e.to_string())
182                        .and_then(|v| model::chat_messages(&v))
183                    {
184                        Ok((chat_ref, messages)) => SimplexEvent::ChatLoaded { chat_ref, messages },
185                        Err(error) => SimplexEvent::ChatLoadFailed {
186                            chat_ref: requested_ref.clone(),
187                            error,
188                        },
189                    };
190                    let loaded = matches!(event, SimplexEvent::ChatLoaded { .. });
191                    sender.send(event).map_err(|e| e.to_string())?;
192                    if loaded {
193                        mark_chat_read(&controller, sender, &requested_ref)?;
194                    }
195                }
196                SimplexCommand::MarkChatRead(chat_ref) => {
197                    mark_chat_read(&controller, sender, &chat_ref)?;
198                }
199                SimplexCommand::SendMessage { chat_ref, text } => {
200                    let command = if let Some(id) = chat_ref.0.strip_prefix('*') {
201                        format!("/_create *{id} text {text}")
202                    } else if chat_ref.0.starts_with('@') || chat_ref.0.starts_with('#') {
203                        format!(
204                            "/_send {} live=off ttl=default sign=off text {text}",
205                            chat_ref.0
206                        )
207                    } else {
208                        sender
209                            .send(SimplexEvent::MessageSendFailed {
210                                chat_ref,
211                                error: "messages cannot be sent to this chat type".into(),
212                            })
213                            .map_err(|e| e.to_string())?;
214                        continue;
215                    };
216                    match controller.command(&command).map_err(|e| e.to_string()) {
217                        Ok(response)
218                            if response
219                                .pointer("/result/type")
220                                .and_then(serde_json::Value::as_str)
221                                == Some("newChatItems") =>
222                        {
223                            for (item_ref, message) in model::new_messages(&response) {
224                                sender
225                                    .send(SimplexEvent::MessageReceived {
226                                        chat_ref: item_ref,
227                                        message,
228                                    })
229                                    .map_err(|e| e.to_string())?;
230                            }
231                            sender
232                                .send(SimplexEvent::MessageSent { chat_ref, text })
233                                .map_err(|e| e.to_string())?;
234                        }
235                        Ok(response) => sender
236                            .send(SimplexEvent::MessageSendFailed {
237                                chat_ref,
238                                error: format!("send failed: {response}"),
239                            })
240                            .map_err(|e| e.to_string())?,
241                        Err(error) => sender
242                            .send(SimplexEvent::MessageSendFailed { chat_ref, error })
243                            .map_err(|e| e.to_string())?,
244                    }
245                }
246                SimplexCommand::SendReaction {
247                    chat_ref,
248                    item_id,
249                    emoji,
250                } => {
251                    let payload = serde_json::json!({"type": "emoji", "emoji": emoji});
252                    let response = controller
253                        .command(&format!("/_reaction {} {item_id} on {payload}", chat_ref.0))
254                        .map_err(|e| e.to_string())?;
255                    send_reaction_change(sender, &response)?;
256                }
257                SimplexCommand::ReceiveFile { file_id, file_name } => {
258                    match receive_file(&controller, download_directory, file_id, &file_name) {
259                        Ok((path, response)) => {
260                            sender
261                                .send(SimplexEvent::FileDownloadStarted {
262                                    file_id,
263                                    path: path.to_string_lossy().into_owned(),
264                                })
265                                .map_err(|e| e.to_string())?;
266                            if let Some((chat_ref, message)) = model::file_update(&response) {
267                                sender
268                                    .send(SimplexEvent::FileUpdated { chat_ref, message })
269                                    .map_err(|e| e.to_string())?;
270                            }
271                        }
272                        Err(error) => sender
273                            .send(SimplexEvent::FileDownloadFailed { file_id, error })
274                            .map_err(|e| e.to_string())?,
275                    }
276                }
277                SimplexCommand::CancelFile { file_id } => match cancel_file(&controller, file_id) {
278                    Ok(response) => {
279                        sender
280                            .send(SimplexEvent::FileDownloadCancelled { file_id })
281                            .map_err(|e| e.to_string())?;
282                        if let Some((chat_ref, message)) = model::file_update(&response) {
283                            sender
284                                .send(SimplexEvent::FileUpdated { chat_ref, message })
285                                .map_err(|e| e.to_string())?;
286                        }
287                    }
288                    Err(error) => sender
289                        .send(SimplexEvent::FileDownloadFailed { file_id, error })
290                        .map_err(|e| e.to_string())?,
291                },
292                SimplexCommand::ActivateProfile(user_id) => {
293                    let result = (|| {
294                        let response = controller
295                            .command(&format!("/_user {user_id}"))
296                            .map_err(|e| e.to_string())?;
297                        let user = model::active_user(&response)?
298                            .ok_or("SimpleX did not activate the selected profile")?;
299                        controller.command("/_start").map_err(|e| e.to_string())?;
300                        send_auto_delete(&controller, sender, user.id)?;
301                        send_servers(&controller, sender, user.id)?;
302                        load_chat_features(&controller, sender, user.id, true)?;
303                        let chats = load_chats(&controller, user.id)?;
304                        Ok::<_, String>(SimplexEvent::ProfileActivated { user, chats })
305                    })();
306                    sender
307                        .send(result.unwrap_or_else(SimplexEvent::Failed))
308                        .map_err(|e| e.to_string())?;
309                }
310                SimplexCommand::CreateProfile(name) => {
311                    let result = (|| {
312                        let escaped = serde_json::to_string(&name).map_err(|e| e.to_string())?;
313                        let payload = format!(
314                            "{{\"profile\":{{\"displayName\":{escaped},\"fullName\":\"\"}},\"pastTimestamp\":false}}"
315                        );
316                        let response = controller
317                            .command(&format!("/_create user {payload}"))
318                            .map_err(|e| e.to_string())?;
319                        let user = model::active_user(&response)?
320                            .ok_or("SimpleX did not create the profile")?;
321                        controller.command("/_start").map_err(|e| e.to_string())?;
322                        send_auto_delete(&controller, sender, user.id)?;
323                        send_servers(&controller, sender, user.id)?;
324                        load_chat_features(&controller, sender, user.id, true)?;
325                        let profiles = load_profiles(&controller)?;
326                        let chats = load_chats(&controller, user.id)?;
327                        Ok::<_, String>(SimplexEvent::ProfileCreated {
328                            user,
329                            profiles,
330                            chats,
331                        })
332                    })();
333                    sender
334                        .send(result.unwrap_or_else(SimplexEvent::Failed))
335                        .map_err(|e| e.to_string())?;
336                }
337                SimplexCommand::DeleteProfile(user_id) => {
338                    let result = delete_profile(&controller, user_id);
339                    sender
340                        .send(match result {
341                            Ok(state) => SimplexEvent::ProfileDeleted {
342                                profiles: state.profiles,
343                                active_user: state.active_user,
344                                chats: state.chats,
345                            },
346                            Err(error) => SimplexEvent::ProfileDeleteFailed(error),
347                        })
348                        .map_err(|e| e.to_string())?;
349                }
350                SimplexCommand::SetAutoDelete { user_id, seconds } => {
351                    let result = update_global_deletion(&controller, user_id, seconds);
352                    sender
353                        .send(match result {
354                            Ok(seconds) => SimplexEvent::AutoDeleteChanged(seconds),
355                            Err(error) => SimplexEvent::AutoDeleteFailed(error),
356                        })
357                        .map_err(|e| e.to_string())?;
358                }
359                SimplexCommand::LoadChatDeletion { chat_ref } => {
360                    let result = load_chat_deletion(&controller, &chat_ref);
361                    sender
362                        .send(match result {
363                            Ok(settings) => SimplexEvent::ChatDeletionLoaded { chat_ref, settings },
364                            Err(error) => SimplexEvent::ChatDeletionFailed(error),
365                        })
366                        .map_err(|e| e.to_string())?;
367                }
368                SimplexCommand::SetChatDeletion {
369                    user_id,
370                    chat_ref,
371                    seconds,
372                } => {
373                    let result = update_chat_deletion(&controller, user_id, &chat_ref, seconds);
374                    sender
375                        .send(match result {
376                            Ok(settings) => {
377                                SimplexEvent::ChatDeletionChanged { chat_ref, settings }
378                            }
379                            Err(error) => SimplexEvent::ChatDeletionFailed(error),
380                        })
381                        .map_err(|e| e.to_string())?;
382                }
383                SimplexCommand::LoadConversationFeatures { chat_ref } => {
384                    let event = load_conversation_features(&controller, &chat_ref)
385                        .map(|features| SimplexEvent::ConversationFeaturesLoaded {
386                            chat_ref,
387                            features,
388                        })
389                        .unwrap_or_else(SimplexEvent::ConversationFeaturesFailed);
390                    sender.send(event).map_err(|e| e.to_string())?;
391                }
392                SimplexCommand::SetConversationFeature {
393                    chat_ref,
394                    feature,
395                    enabled,
396                } => {
397                    let event =
398                        update_conversation_feature(&controller, &chat_ref, feature, enabled)
399                            .map(|features| SimplexEvent::ConversationFeaturesChanged {
400                                chat_ref,
401                                features,
402                            })
403                            .unwrap_or_else(SimplexEvent::ConversationFeaturesFailed);
404                    sender.send(event).map_err(|e| e.to_string())?;
405                }
406                SimplexCommand::DeleteChat {
407                    user_id,
408                    chat_ref,
409                    mode,
410                } => {
411                    let event = delete_chat(&controller, user_id, &chat_ref, mode)
412                        .map(|chats| SimplexEvent::ChatDeleted { chat_ref, chats })
413                        .unwrap_or_else(SimplexEvent::ChatDeleteFailed);
414                    sender.send(event).map_err(|e| e.to_string())?;
415                }
416                SimplexCommand::CreateInvitation { user_id } => {
417                    let event = controller
418                        .command(&format!("/_connect {user_id} incognito=off"))
419                        .map_err(|e| e.to_string())
420                        .and_then(|value| model::invitation_link(&value))
421                        .map(SimplexEvent::InvitationCreated)
422                        .unwrap_or_else(SimplexEvent::InvitationFailed);
423                    sender.send(event).map_err(|e| e.to_string())?;
424                }
425                SimplexCommand::ConnectInvitation { user_id, link } => {
426                    let event = validate_connection_link(&link)
427                        .and_then(|link| {
428                            controller
429                                .command(&format!("/_connect {user_id} incognito=off {link}"))
430                                .map_err(|e| e.to_string())
431                        })
432                        .and_then(|value| model::connection_started(&value))
433                        .map(|()| SimplexEvent::ConnectionStarted)
434                        .unwrap_or_else(SimplexEvent::ConnectionFailed);
435                    sender.send(event).map_err(|e| e.to_string())?;
436                }
437                SimplexCommand::SetChatFeature {
438                    user_id,
439                    feature,
440                    enabled,
441                } => {
442                    let result = update_chat_feature(&controller, user_id, feature, enabled);
443                    match result {
444                        Ok(features) => {
445                            sender
446                                .send(SimplexEvent::ChatFeaturesLoaded(features))
447                                .map_err(|e| e.to_string())?;
448                            sender
449                                .send(SimplexEvent::SettingChanged("Chat feature updated".into()))
450                                .map_err(|e| e.to_string())?;
451                        }
452                        Err(error) => sender
453                            .send(SimplexEvent::SettingChanged(format!(
454                                "Could not update chat feature: {error}"
455                            )))
456                            .map_err(|e| e.to_string())?,
457                    }
458                }
459                SimplexCommand::SetServerEnabled {
460                    user_id,
461                    protocol,
462                    address,
463                    enabled,
464                } => {
465                    let result =
466                        set_server_enabled(&controller, user_id, protocol, &address, enabled)
467                            .and_then(|()| load_servers(&controller, user_id));
468                    sender
469                        .send(match result {
470                            Ok(servers) => SimplexEvent::ServersLoaded(servers),
471                            Err(error) => SimplexEvent::ServersUpdateFailed(error),
472                        })
473                        .map_err(|e| e.to_string())?;
474                }
475                SimplexCommand::AddServer {
476                    user_id,
477                    protocol,
478                    address,
479                } => {
480                    let result = add_server(&controller, user_id, protocol, &address)
481                        .and_then(|()| load_servers(&controller, user_id));
482                    sender
483                        .send(match result {
484                            Ok(servers) => SimplexEvent::ServersLoaded(servers),
485                            Err(error) => SimplexEvent::ServersUpdateFailed(error),
486                        })
487                        .map_err(|e| e.to_string())?;
488                }
489            }
490        }
491        if let Some(value) = controller
492            .recv(Duration::from_millis(200))
493            .map_err(|e| e.to_string())?
494        {
495            send_reaction_change(sender, &value)?;
496            if let Some((chat_ref, message)) = model::file_update(&value) {
497                sender
498                    .send(SimplexEvent::FileUpdated { chat_ref, message })
499                    .map_err(|e| e.to_string())?;
500            }
501            if let Some((user_id, chat_ref)) = model::connected_contact(&value) {
502                let chats = load_chats(&controller, user_id)?;
503                sender
504                    .send(SimplexEvent::ContactConnected { chats, chat_ref })
505                    .map_err(|e| e.to_string())?;
506            }
507            for (chat_ref, message) in model::new_messages(&value) {
508                sender
509                    .send(SimplexEvent::MessageReceived { chat_ref, message })
510                    .map_err(|e| e.to_string())?;
511            }
512        }
513    }
514}
515
516fn validate_connection_link(link: &str) -> Result<&str, String> {
517    let link = link.trim();
518    if link.is_empty() {
519        return Err("invitation link is empty".into());
520    }
521    if link.chars().any(char::is_whitespace) {
522        return Err("invitation link contains whitespace".into());
523    }
524    Ok(link)
525}
526
527fn receive_file(
528    controller: &crate::ffi::SimplexController,
529    directory: &std::path::Path,
530    file_id: i64,
531    file_name: &str,
532) -> Result<(std::path::PathBuf, serde_json::Value), String> {
533    std::fs::create_dir_all(directory)
534        .map_err(|error| format!("could not create {}: {error}", directory.display()))?;
535    let safe_name = std::path::Path::new(file_name)
536        .file_name()
537        .and_then(std::ffi::OsStr::to_str)
538        .filter(|name| !name.is_empty() && *name != "." && *name != "..")
539        .unwrap_or("simplex-file");
540    let path = unused_download_path(directory, safe_name);
541    let response = controller
542        .command(&format!(
543            "/freceive {file_id} approved_relays=on {}",
544            path.display()
545        ))
546        .map_err(|error| error.to_string())?;
547    if response
548        .pointer("/result/type")
549        .and_then(serde_json::Value::as_str)
550        != Some("rcvFileAccepted")
551    {
552        return Err(format!("file download was not accepted: {response}"));
553    }
554    Ok((path, response))
555}
556
557fn cancel_file(
558    controller: &crate::ffi::SimplexController,
559    file_id: i64,
560) -> Result<serde_json::Value, String> {
561    let response = controller
562        .command(&format!("/fcancel {file_id}"))
563        .map_err(|error| error.to_string())?;
564    if response
565        .pointer("/result/type")
566        .and_then(serde_json::Value::as_str)
567        != Some("rcvFileCancelled")
568    {
569        return Err(format!("file download was not cancelled: {response}"));
570    }
571    Ok(response)
572}
573
574fn unused_download_path(directory: &std::path::Path, name: &str) -> std::path::PathBuf {
575    let original = directory.join(name);
576    if !original.exists() {
577        return original;
578    }
579    let path = std::path::Path::new(name);
580    let stem = path
581        .file_stem()
582        .and_then(std::ffi::OsStr::to_str)
583        .unwrap_or("file");
584    let extension = path.extension().and_then(std::ffi::OsStr::to_str);
585    for number in 1.. {
586        let candidate = match extension {
587            Some(extension) => directory.join(format!("{stem} ({number}).{extension}")),
588            None => directory.join(format!("{stem} ({number})")),
589        };
590        if !candidate.exists() {
591            return candidate;
592        }
593    }
594    unreachable!()
595}
596
597fn send_reaction_change(
598    sender: &Sender<SimplexEvent>,
599    value: &serde_json::Value,
600) -> Result<(), String> {
601    if let Some((chat_ref, item_id, emoji, added, user_reacted)) = model::reaction_change(value) {
602        sender
603            .send(SimplexEvent::ReactionChanged {
604                chat_ref,
605                item_id,
606                emoji,
607                added,
608                user_reacted,
609            })
610            .map_err(|e| e.to_string())?;
611    }
612    Ok(())
613}
614
615fn delete_profile(
616    controller: &crate::ffi::SimplexController,
617    user_id: i64,
618) -> Result<DeletedProfileState, String> {
619    let profiles = load_profiles(controller)?;
620    if profiles
621        .iter()
622        .any(|profile| profile.id == user_id && profile.active)
623        && let Some(other) = profiles.iter().find(|profile| profile.id != user_id)
624    {
625        let response = controller
626            .command(&format!("/_user {}", other.id))
627            .map_err(|e| e.to_string())?;
628        model::active_user(&response)?.ok_or("SimpleX did not activate the replacement profile")?;
629    }
630    let response = controller
631        .command(&format!("/_delete user {user_id} del_smp=on"))
632        .map_err(|e| e.to_string())?;
633    ensure_ok(&response, "profile deletion")?;
634    let profiles = load_profiles(controller)?;
635    let active_user = model::active_user(&controller.command("/u").map_err(|e| e.to_string())?)?;
636    let chats = if let Some(user) = &active_user {
637        load_chats(controller, user.id)?
638    } else {
639        Vec::new()
640    };
641    Ok(DeletedProfileState {
642        profiles,
643        active_user,
644        chats,
645    })
646}
647
648fn mark_chat_read(
649    controller: &crate::ffi::SimplexController,
650    sender: &Sender<SimplexEvent>,
651    chat_ref: &ChatRef,
652) -> Result<(), String> {
653    let response = controller
654        .command(&format!("/_read chat {}", chat_ref.0))
655        .map_err(|e| e.to_string())?;
656    ensure_ok(&response, "mark chat as read")?;
657    sender
658        .send(SimplexEvent::ChatMarkedRead(chat_ref.clone()))
659        .map_err(|e| e.to_string())
660}
661
662fn load_chat_features(
663    controller: &crate::ffi::SimplexController,
664    sender: &Sender<SimplexEvent>,
665    user_id: i64,
666    enforce_calls_disabled: bool,
667) -> Result<(), String> {
668    let response = controller.command("/profile").map_err(|e| e.to_string())?;
669    let (mut profile, features) = model::profile_and_features(&response)?;
670    if enforce_calls_disabled && preference_allow(&profile, "calls") != Some("no") {
671        set_profile_preference(&mut profile, "calls", false)?;
672        update_profile(controller, user_id, &profile)?;
673    }
674    sender
675        .send(SimplexEvent::ChatFeaturesLoaded(features))
676        .map_err(|e| e.to_string())
677}
678
679fn update_chat_feature(
680    controller: &crate::ffi::SimplexController,
681    user_id: i64,
682    feature: ChatFeature,
683    enabled: bool,
684) -> Result<model::ChatFeatures, String> {
685    let response = controller.command("/profile").map_err(|e| e.to_string())?;
686    let (mut profile, _) = model::profile_and_features(&response)?;
687    let name = match feature {
688        ChatFeature::FullDeletion => "fullDelete",
689        ChatFeature::Reactions => "reactions",
690        ChatFeature::VoiceMessages => "voice",
691        ChatFeature::FilesAndMedia => "files",
692    };
693    set_profile_preference(&mut profile, name, enabled)?;
694    set_profile_preference(&mut profile, "calls", false)?;
695    update_profile(controller, user_id, &profile)?;
696    let synthetic = serde_json::json!({"result": {"type": "userProfile", "profile": profile}});
697    model::profile_and_features(&synthetic).map(|(_, features)| features)
698}
699
700fn update_global_deletion(
701    controller: &crate::ffi::SimplexController,
702    user_id: i64,
703    seconds: i64,
704) -> Result<i64, String> {
705    let response = controller.command("/profile").map_err(|e| e.to_string())?;
706    let (mut profile, _) = model::profile_and_features(&response)?;
707    set_timed_preference(&mut profile, Some(seconds))?;
708    set_profile_preference(&mut profile, "calls", false)?;
709    update_profile(controller, user_id, &profile)?;
710    let response = controller
711        .command(&format!("/_ttl {user_id} {seconds}"))
712        .map_err(|e| e.to_string())?;
713    ensure_ok(&response, "automatic deletion")?;
714    Ok(seconds)
715}
716
717fn load_chat_deletion(
718    controller: &crate::ffi::SimplexController,
719    chat_ref: &ChatRef,
720) -> Result<model::ChatDeletionSettings, String> {
721    let response = controller
722        .command(&format!("/_get chat {} count=1", chat_ref.0))
723        .map_err(|e| e.to_string())?;
724    let info = response
725        .pointer("/result/chat/chatInfo")
726        .ok_or("chat response has no chatInfo")?;
727    let (entity, timed_pointer) = match info.get("type").and_then(serde_json::Value::as_str) {
728        Some("direct") => (
729            info.get("contact").ok_or("direct chat has no contact")?,
730            "/userPreferences/timedMessages",
731        ),
732        Some("group") => (
733            info.get("groupInfo").ok_or("group chat has no groupInfo")?,
734            "/groupProfile/groupPreferences/timedMessages",
735        ),
736        _ => return Err("chat deletion settings are unsupported for this chat type".into()),
737    };
738    let local_ttl = entity
739        .get("chatItemTTL")
740        .and_then(serde_json::Value::as_i64);
741    let timed = entity.pointer(timed_pointer);
742    let enabled = timed
743        .and_then(|value| value.get("allow").or_else(|| value.get("enable")))
744        .and_then(serde_json::Value::as_str);
745    let disappearing_ttl = match enabled {
746        Some("no" | "off") => Some(0),
747        Some("yes" | "always" | "on") => timed
748            .and_then(|value| value.get("ttl"))
749            .and_then(serde_json::Value::as_i64)
750            .or(Some(0)),
751        _ => None,
752    };
753    Ok(model::ChatDeletionSettings {
754        local_ttl,
755        disappearing_ttl,
756    })
757}
758
759fn update_chat_deletion(
760    controller: &crate::ffi::SimplexController,
761    user_id: i64,
762    chat_ref: &ChatRef,
763    seconds: Option<i64>,
764) -> Result<model::ChatDeletionSettings, String> {
765    let response = controller
766        .command(&format!("/_get chat {} count=1", chat_ref.0))
767        .map_err(|e| e.to_string())?;
768    let info = response
769        .pointer("/result/chat/chatInfo")
770        .ok_or("chat response has no chatInfo")?;
771    match info.get("type").and_then(serde_json::Value::as_str) {
772        Some("direct") => {
773            let mut preferences = info
774                .pointer("/contact/userPreferences")
775                .cloned()
776                .unwrap_or_else(|| serde_json::json!({}));
777            set_timed_preference(&mut preferences, seconds)?;
778            let response = controller
779                .command(&format!("/_set prefs {} {preferences}", chat_ref.0))
780                .map_err(|e| e.to_string())?;
781            ensure_ok(&response, "contact disappearing messages")?;
782        }
783        Some("group") => {
784            let mut profile = info
785                .pointer("/groupInfo/groupProfile")
786                .cloned()
787                .ok_or("group chat has no group profile")?;
788            set_group_timed_preference(&mut profile, seconds)?;
789            let response = controller
790                .command(&format!("/_group_profile {} {profile}", chat_ref.0))
791                .map_err(|e| e.to_string())?;
792            ensure_ok(&response, "group disappearing messages")?;
793        }
794        _ => return Err("chat deletion settings are unsupported for this chat type".into()),
795    }
796    let ttl = seconds.map_or_else(|| "default".to_owned(), |value| value.to_string());
797    let response = controller
798        .command(&format!("/_ttl {user_id} {} {ttl}", chat_ref.0))
799        .map_err(|e| e.to_string())?;
800    ensure_ok(&response, "local chat deletion")?;
801    load_chat_deletion(controller, chat_ref)
802}
803
804fn load_conversation_features(
805    controller: &crate::ffi::SimplexController,
806    chat_ref: &ChatRef,
807) -> Result<model::ChatFeatures, String> {
808    let response = controller
809        .command(&format!("/_get chat {} count=1", chat_ref.0))
810        .map_err(|e| e.to_string())?;
811    let info = response
812        .pointer("/result/chat/chatInfo")
813        .ok_or("chat response has no chatInfo")?;
814    let (_, defaults) =
815        model::profile_and_features(&controller.command("/profile").map_err(|e| e.to_string())?)?;
816    match info.get("type").and_then(serde_json::Value::as_str) {
817        Some("direct") => Ok(features_from_preferences(
818            info.pointer("/contact/userPreferences"),
819            defaults,
820            false,
821        )),
822        Some("group") => Ok(features_from_preferences(
823            info.pointer("/groupInfo/groupProfile/groupPreferences"),
824            defaults,
825            true,
826        )),
827        _ => Err("chat feature settings are unsupported for this chat type".into()),
828    }
829}
830
831fn update_conversation_feature(
832    controller: &crate::ffi::SimplexController,
833    chat_ref: &ChatRef,
834    feature: ChatFeature,
835    enabled: bool,
836) -> Result<model::ChatFeatures, String> {
837    let response = controller
838        .command(&format!("/_get chat {} count=1", chat_ref.0))
839        .map_err(|e| e.to_string())?;
840    let info = response
841        .pointer("/result/chat/chatInfo")
842        .ok_or("chat response has no chatInfo")?;
843    let name = feature_name(feature);
844    match info.get("type").and_then(serde_json::Value::as_str) {
845        Some("direct") => {
846            let mut preferences = info
847                .pointer("/contact/userPreferences")
848                .cloned()
849                .unwrap_or_else(|| serde_json::json!({}));
850            set_contact_feature(&mut preferences, name, enabled)?;
851            set_contact_feature(&mut preferences, "calls", false)?;
852            let response = controller
853                .command(&format!("/_set prefs {} {preferences}", chat_ref.0))
854                .map_err(|e| e.to_string())?;
855            ensure_ok(&response, "contact feature")?;
856        }
857        Some("group") => {
858            let mut profile = info
859                .pointer("/groupInfo/groupProfile")
860                .cloned()
861                .ok_or("group chat has no group profile")?;
862            set_group_feature(&mut profile, name, enabled)?;
863            set_group_feature(&mut profile, "calls", false)?;
864            let response = controller
865                .command(&format!("/_group_profile {} {profile}", chat_ref.0))
866                .map_err(|e| e.to_string())?;
867            ensure_ok(&response, "group feature")?;
868        }
869        _ => return Err("chat feature settings are unsupported for this chat type".into()),
870    }
871    load_conversation_features(controller, chat_ref)
872}
873
874fn delete_chat(
875    controller: &crate::ffi::SimplexController,
876    user_id: i64,
877    chat_ref: &ChatRef,
878    mode: ChatDeleteMode,
879) -> Result<Vec<model::ChatSummary>, String> {
880    let suffix = match mode {
881        ChatDeleteMode::Conversation => "messages",
882        ChatDeleteMode::Contact if chat_ref.0.starts_with('@') => "full notify=on",
883        ChatDeleteMode::BlockContact if chat_ref.0.starts_with('@') => "full notify=off",
884        ChatDeleteMode::Contact | ChatDeleteMode::BlockContact => {
885            return Err("contact actions are only available for direct chats".into());
886        }
887    };
888    let response = controller
889        .command(&format!("/_delete {} {suffix}", chat_ref.0))
890        .map_err(|e| e.to_string())?;
891    ensure_ok(&response, "chat deletion")?;
892    load_chats(controller, user_id)
893}
894
895fn feature_name(feature: ChatFeature) -> &'static str {
896    match feature {
897        ChatFeature::FullDeletion => "fullDelete",
898        ChatFeature::Reactions => "reactions",
899        ChatFeature::VoiceMessages => "voice",
900        ChatFeature::FilesAndMedia => "files",
901    }
902}
903
904fn features_from_preferences(
905    preferences: Option<&serde_json::Value>,
906    defaults: model::ChatFeatures,
907    group: bool,
908) -> model::ChatFeatures {
909    let enabled = |name: &str, default: bool| {
910        let value = preferences
911            .and_then(|prefs| prefs.get(name))
912            .and_then(|pref| pref.get(if group { "enable" } else { "allow" }))
913            .and_then(serde_json::Value::as_str);
914        match value {
915            Some("no" | "off") => false,
916            Some("yes" | "always" | "on") => true,
917            _ => default,
918        }
919    };
920    model::ChatFeatures {
921        disappearing_messages: defaults.disappearing_messages,
922        full_deletion: enabled("fullDelete", defaults.full_deletion),
923        reactions: enabled("reactions", defaults.reactions),
924        voice_messages: enabled("voice", defaults.voice_messages),
925        files_and_media: enabled("files", defaults.files_and_media),
926    }
927}
928
929fn set_contact_feature(
930    preferences: &mut serde_json::Value,
931    name: &str,
932    enabled: bool,
933) -> Result<(), String> {
934    preferences
935        .as_object_mut()
936        .ok_or("contact preferences are not an object")?
937        .insert(
938            name.into(),
939            serde_json::json!({"allow": if enabled { "yes" } else { "no" }}),
940        );
941    Ok(())
942}
943
944fn set_group_feature(
945    profile: &mut serde_json::Value,
946    name: &str,
947    enabled: bool,
948) -> Result<(), String> {
949    profile
950        .as_object_mut()
951        .ok_or("group profile is not an object")?
952        .entry("groupPreferences")
953        .or_insert_with(|| serde_json::json!({}))
954        .as_object_mut()
955        .ok_or("group preferences are not an object")?
956        .insert(
957            name.into(),
958            serde_json::json!({"enable": if enabled { "on" } else { "off" }}),
959        );
960    Ok(())
961}
962
963fn set_timed_preference(
964    object: &mut serde_json::Value,
965    seconds: Option<i64>,
966) -> Result<(), String> {
967    let is_profile = object.get("displayName").is_some();
968    let preferences = if is_profile {
969        object
970            .as_object_mut()
971            .ok_or("profile is not an object")?
972            .entry("preferences")
973            .or_insert_with(|| serde_json::json!({}))
974    } else {
975        object
976    };
977    let preferences = preferences
978        .as_object_mut()
979        .ok_or("preferences are not an object")?;
980    match seconds {
981        None => {
982            preferences.remove("timedMessages");
983        }
984        Some(seconds) => {
985            preferences.insert(
986                "timedMessages".into(),
987                if seconds == 0 {
988                    serde_json::json!({"allow": "no"})
989                } else {
990                    serde_json::json!({"allow": "yes", "ttl": seconds})
991                },
992            );
993        }
994    }
995    Ok(())
996}
997
998fn set_group_timed_preference(
999    profile: &mut serde_json::Value,
1000    seconds: Option<i64>,
1001) -> Result<(), String> {
1002    let profile = profile
1003        .as_object_mut()
1004        .ok_or("group profile is not an object")?;
1005    let preferences = profile
1006        .entry("groupPreferences")
1007        .or_insert_with(|| serde_json::json!({}))
1008        .as_object_mut()
1009        .ok_or("group preferences are not an object")?;
1010    match seconds {
1011        None => {
1012            preferences.remove("timedMessages");
1013        }
1014        Some(seconds) => {
1015            preferences.insert(
1016                "timedMessages".into(),
1017                if seconds == 0 {
1018                    serde_json::json!({"enable": "off"})
1019                } else {
1020                    serde_json::json!({"enable": "on", "ttl": seconds})
1021                },
1022            );
1023        }
1024    }
1025    Ok(())
1026}
1027
1028fn preference_allow<'a>(profile: &'a serde_json::Value, name: &str) -> Option<&'a str> {
1029    profile
1030        .pointer(&format!("/preferences/{name}/allow"))
1031        .and_then(serde_json::Value::as_str)
1032}
1033
1034fn set_profile_preference(
1035    profile: &mut serde_json::Value,
1036    name: &str,
1037    enabled: bool,
1038) -> Result<(), String> {
1039    let profile = profile
1040        .as_object_mut()
1041        .ok_or("profile response is not an object")?;
1042    if !profile
1043        .get("preferences")
1044        .is_some_and(|value| value.is_object())
1045    {
1046        profile.insert("preferences".into(), serde_json::json!({}));
1047    }
1048    let preferences = profile
1049        .get_mut("preferences")
1050        .and_then(serde_json::Value::as_object_mut)
1051        .ok_or("profile preferences are not an object")?;
1052    let mut preference = preferences
1053        .get(name)
1054        .and_then(serde_json::Value::as_object)
1055        .cloned()
1056        .unwrap_or_default();
1057    preference.insert(
1058        "allow".into(),
1059        serde_json::Value::String(if enabled { "yes" } else { "no" }.into()),
1060    );
1061    preferences.insert(name.into(), serde_json::Value::Object(preference));
1062    Ok(())
1063}
1064
1065fn update_profile(
1066    controller: &crate::ffi::SimplexController,
1067    user_id: i64,
1068    profile: &serde_json::Value,
1069) -> Result<(), String> {
1070    let response = controller
1071        .command(&format!("/_profile {user_id} {profile}"))
1072        .map_err(|e| e.to_string())?;
1073    ensure_ok(&response, "chat preferences")
1074}
1075
1076fn send_servers(
1077    controller: &crate::ffi::SimplexController,
1078    sender: &Sender<SimplexEvent>,
1079    user_id: i64,
1080) -> Result<(), String> {
1081    let servers = load_servers(controller, user_id)?;
1082    sender
1083        .send(SimplexEvent::ServersLoaded(servers))
1084        .map_err(|e| e.to_string())
1085}
1086
1087fn load_servers(
1088    controller: &crate::ffi::SimplexController,
1089    user_id: i64,
1090) -> Result<Vec<model::ServerEntry>, String> {
1091    let response = controller
1092        .command(&format!("/_servers {user_id}"))
1093        .map_err(|e| e.to_string())?;
1094    model::server_entries(&response)
1095}
1096
1097fn user_servers_json(
1098    controller: &crate::ffi::SimplexController,
1099    user_id: i64,
1100) -> Result<serde_json::Value, String> {
1101    let response = controller
1102        .command(&format!("/_servers {user_id}"))
1103        .map_err(|e| e.to_string())?;
1104    response
1105        .pointer("/result/userServers")
1106        .cloned()
1107        .ok_or_else(|| format!("user server response is invalid: {response}"))
1108}
1109
1110fn save_user_servers(
1111    controller: &crate::ffi::SimplexController,
1112    user_id: i64,
1113    servers: &serde_json::Value,
1114) -> Result<(), String> {
1115    let response = controller
1116        .command(&format!("/_servers {user_id} {servers}"))
1117        .map_err(|e| e.to_string())?;
1118    ensure_ok(&response, "server configuration")
1119}
1120
1121fn set_server_enabled(
1122    controller: &crate::ffi::SimplexController,
1123    user_id: i64,
1124    protocol: ServerProtocol,
1125    address: &str,
1126    enabled: bool,
1127) -> Result<(), String> {
1128    let mut groups = user_servers_json(controller, user_id)?;
1129    let mut found = false;
1130    for group in groups
1131        .as_array_mut()
1132        .ok_or("user servers are not an array")?
1133    {
1134        for server in group
1135            .get_mut(protocol.json_key())
1136            .and_then(serde_json::Value::as_array_mut)
1137            .into_iter()
1138            .flatten()
1139        {
1140            if server.get("server").and_then(serde_json::Value::as_str) == Some(address) {
1141                server
1142                    .as_object_mut()
1143                    .ok_or("server entry is not an object")?
1144                    .insert("enabled".into(), enabled.into());
1145                found = true;
1146            }
1147        }
1148    }
1149    if !found {
1150        return Err("server is no longer present".into());
1151    }
1152    save_user_servers(controller, user_id, &groups)
1153}
1154
1155fn add_server(
1156    controller: &crate::ffi::SimplexController,
1157    user_id: i64,
1158    protocol: ServerProtocol,
1159    address: &str,
1160) -> Result<(), String> {
1161    if !address.starts_with(match protocol {
1162        ServerProtocol::Smp => "smp://",
1163        ServerProtocol::Xftp => "xftp://",
1164    }) {
1165        return Err(format!(
1166            "expected an {}:// server address",
1167            protocol.label().to_ascii_lowercase()
1168        ));
1169    }
1170    let mut groups_json = user_servers_json(controller, user_id)?;
1171    let groups = groups_json
1172        .as_array_mut()
1173        .ok_or("user servers are not an array")?;
1174    if groups.iter().any(|group| {
1175        group
1176            .get(protocol.json_key())
1177            .and_then(serde_json::Value::as_array)
1178            .is_some_and(|servers| {
1179                servers.iter().any(|server| {
1180                    server.get("server").and_then(serde_json::Value::as_str) == Some(address)
1181                })
1182            })
1183    }) {
1184        return Err("server is already configured".into());
1185    }
1186    let custom_group = groups
1187        .iter_mut()
1188        .find(|group| group.get("operator").is_none_or(serde_json::Value::is_null))
1189        .ok_or("custom server group is missing")?;
1190    custom_group
1191        .get_mut(protocol.json_key())
1192        .and_then(serde_json::Value::as_array_mut)
1193        .ok_or("custom server list is missing")?
1194        .push(serde_json::json!({
1195            "server": address,
1196            "preset": false,
1197            "tested": null,
1198            "enabled": true,
1199            "roles": {"storage": null, "proxy": null, "names": null},
1200            "deleted": false
1201        }));
1202    save_user_servers(controller, user_id, &groups_json)
1203}
1204
1205fn load_profiles(
1206    controller: &crate::ffi::SimplexController,
1207) -> Result<Vec<model::Profile>, String> {
1208    model::profiles(&controller.command("/users").map_err(|e| e.to_string())?)
1209}
1210
1211fn load_chats(
1212    controller: &crate::ffi::SimplexController,
1213    user_id: i64,
1214) -> Result<Vec<model::ChatSummary>, String> {
1215    model::chats(
1216        &controller
1217            .command(&format!("/_get chats {user_id} pcc=on"))
1218            .map_err(|e| e.to_string())?,
1219    )
1220}
1221
1222fn ensure_ok(value: &serde_json::Value, operation: &str) -> Result<(), String> {
1223    if value.get("error").is_some()
1224        || value
1225            .pointer("/result/type")
1226            .and_then(serde_json::Value::as_str)
1227            == Some("chatCmdError")
1228    {
1229        Err(format!("failed to update {operation}: {value}"))
1230    } else {
1231        Ok(())
1232    }
1233}
1234
1235fn send_auto_delete(
1236    controller: &crate::ffi::SimplexController,
1237    sender: &Sender<SimplexEvent>,
1238    user_id: i64,
1239) -> Result<(), String> {
1240    let response = controller
1241        .command(&format!("/_ttl {user_id}"))
1242        .map_err(|e| e.to_string())?;
1243    let seconds = response
1244        .pointer("/result/chatItemTTL")
1245        .and_then(serde_json::Value::as_i64)
1246        .unwrap_or(0);
1247    sender
1248        .send(SimplexEvent::AutoDeleteLoaded(seconds))
1249        .map_err(|e| e.to_string())
1250}
1251
1252#[cfg(test)]
1253mod tests {
1254    use super::*;
1255
1256    #[test]
1257    fn conversation_preferences_override_profile_defaults() {
1258        let defaults = model::ChatFeatures {
1259            full_deletion: false,
1260            reactions: true,
1261            voice_messages: true,
1262            files_and_media: true,
1263            ..model::ChatFeatures::default()
1264        };
1265        let direct = serde_json::json!({
1266            "fullDelete": {"allow": "yes"},
1267            "reactions": {"allow": "no"}
1268        });
1269        let features = features_from_preferences(Some(&direct), defaults.clone(), false);
1270        assert!(features.full_deletion);
1271        assert!(!features.reactions);
1272        assert!(features.voice_messages);
1273
1274        let group = serde_json::json!({
1275            "voice": {"enable": "off"},
1276            "files": {"enable": "on"}
1277        });
1278        let features = features_from_preferences(Some(&group), defaults, true);
1279        assert!(!features.voice_messages);
1280        assert!(features.files_and_media);
1281    }
1282
1283    #[test]
1284    fn connection_links_cannot_inject_another_command() {
1285        assert!(validate_connection_link("simplex:/invitation#example").is_ok());
1286        assert!(validate_connection_link("simplex:/invitation#example\n/_delete @1").is_err());
1287    }
1288}