simploxide-client 0.10.0

SimpleX-Chat API client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! WebSocket backend that connects to a `simplex-chat` WebSocket server.
//!
//! Use [`BotBuilder`] to launch or connect to `simplex-chat` and get a ready-to-use [`Bot`].
//! For lower-level access, [`connect`] and [`retry_connect`] return a [`Client`] and an
//! [`EventStream`](crate::EventStream) directly.

use std::sync::Arc;

pub use simploxide_ws_core::{
    self as core, Error as CoreError, Event as CoreEvent, Result as CoreResult, SimplexVersion,
    VersionError, tungstenite::Error as WsError,
};

#[cfg(feature = "cli")]
pub use simploxide_ws_core::cli;

use serde::Deserialize;
use simploxide_api_types::{
    Preferences, Profile,
    client_api::{ExtractResponse, WebSocketResponseShape, WebSocketResponseShapeInner},
    events::{Event, EventKind},
};
use simploxide_core::{MAX_SUPPORTED_VERSION, MIN_SUPPORTED_VERSION};
use simploxide_ws_core::RawClient;

use crate::{
    BadResponseError, ClientApi, ClientApiError, EventParser,
    bot::{BotProfileSettings, BotSettings},
    preview::ImagePreview,
};

#[cfg(not(feature = "xftp"))]
pub type Bot = crate::bot::Bot<Client>;

#[cfg(feature = "xftp")]
pub type Bot = crate::bot::Bot<crate::xftp::XftpClient<Client>>;

pub type EventStream = crate::EventStream<CoreResult<CoreEvent>>;
pub type ClientResult<T = ()> = ::std::result::Result<T, ClientError>;

/// Connects to a `simplex-chat` WebSocket server, returning a [`Client`] and an [`EventStream`]
/// that handle serialization/deserialization of commands and events.
///
/// ```ignore
/// let (client, mut events) = simploxide_client::ws::connect("ws://127.0.0.1:5225").await?;
///
/// let current_user = client.api_show_active_user().await?;
/// println!("{current_user:#?}");
///
/// while let Some(ev) = events.try_next().await? {
///     // Process events...
/// }
/// ```
pub async fn connect<S: AsRef<str>>(uri: S) -> Result<(Client, EventStream), ConnectError> {
    let (raw_client, raw_event_queue) = simploxide_ws_core::connect(uri.as_ref()).await?;

    let version = raw_client
        .version()
        .await
        .map_err(ConnectError::VersionError)?;

    if !version.is_supported() {
        return Err(ConnectError::VersionMismatch(version));
    }

    Ok((
        Client::from(raw_client),
        EventStream::from(raw_event_queue.into_receiver()),
    ))
}

/// Like [`connect`] but retries to connect `retries_count` times before returning an error. This
/// method is needed when you run simplex-cli programmatically and don't know when WebSocket port
/// becomes available.
///
/// ```ignore
/// let port = 5225;
/// let cli = SimplexCli::spawn(port);
/// let uri = format!("ws://127.0.0.1:{port}");
///
/// let (client, mut events) = simploxide_client::retry_connect(&uri, Duration::from_secs(1), 10).await?;
///
/// //...
///
/// ```
pub async fn retry_connect<S: AsRef<str>>(
    uri: S,
    retry_delay: std::time::Duration,
    mut retries_count: usize,
) -> Result<(Client, EventStream), ConnectError> {
    loop {
        match connect(uri.as_ref()).await {
            Ok(connection) => break Ok(connection),
            Err(e) if !e.is_server() || retries_count == 0 => break Err(e),
            Err(_) => {
                retries_count -= 1;
                tokio::time::sleep(retry_delay).await
            }
        }
    }
}

impl EventParser for CoreResult<String> {
    type Error = ClientError;

    fn parse_kind(&self) -> Result<EventKind, Self::Error> {
        #[derive(Deserialize)]
        struct TypeField<'a> {
            #[serde(rename = "type", borrow)]
            typ: &'a str,
        }

        match parse_data::<TypeField<'_>>(self) {
            Ok(f) => Ok(EventKind::from_type_str(f.typ)),
            Err(ClientError::BadResponse(BadResponseError::Undocumented(_))) => {
                Ok(EventKind::Undocumented)
            }
            Err(e) => Err(e),
        }
    }

    fn parse_event(&self) -> Result<Event, Self::Error> {
        parse_data(self)
    }
}

fn parse_data<'de, 'r: 'de, D: 'de + Deserialize<'de>>(
    res: &'r CoreResult<String>,
) -> ClientResult<D> {
    res.as_ref()
        .map_err(|e| ClientError::WebSocketFailure(e.clone()))
        .and_then(|ev| {
            serde_json::from_str::<EventShape<D>>(ev)
                .map_err(BadResponseError::InvalidJson)
                .and_then(|shape| shape.extract_response())
                .map_err(ClientError::BadResponse)
        })
}

#[derive(Deserialize)]
#[serde(untagged)]
pub enum EventShape<T> {
    ResponseShape(WebSocketResponseShape<T>),
    InlineShape(WebSocketResponseShapeInner<T>),
}

impl<'de, T: 'de + Deserialize<'de>> ExtractResponse<'de, T> for EventShape<T> {
    fn extract_response(self) -> Result<T, BadResponseError> {
        match self {
            Self::ResponseShape(resp) => resp.extract_response(),
            Self::InlineShape(inline) => inline.extract_response(),
        }
    }
}

/// A high level SimpleX-Chat client which provides typed API methods with automatic command
/// serialization and response deserialization.
#[derive(Clone)]
pub struct Client {
    inner: RawClient,
}

impl From<RawClient> for Client {
    fn from(inner: RawClient) -> Self {
        Self { inner }
    }
}

impl Client {
    pub fn version(&self) -> impl Future<Output = Result<SimplexVersion, VersionError>> {
        self.inner.version()
    }

    /// Initiates a graceful shutdown for the underlying web socket connection. See
    /// [`simploxide_ws_core::RawClient::disconnect`] for details.
    pub fn disconnect(self) -> impl Future<Output = ()> {
        self.inner.disconnect()
    }
}

impl ClientApi for Client {
    type ResponseShape<'de, T>
        = WebSocketResponseShape<T>
    where
        T: 'de + Deserialize<'de>;

    type Error = ClientError;

    async fn send_raw(&self, command: String) -> Result<String, Self::Error> {
        self.inner
            .send(command)
            .await
            .map_err(ClientError::WebSocketFailure)
    }
}

/// See [`crate::client_api::AllowUndocumentedResponses`] if you don't want to trigger an error when
/// you receive undocumeted responses(you usually receive undocumented responses when your
/// simplex-chat server version is not compatible with the simploxide-client version. Keep an eye
/// on the
/// [Version compatability table](https://github.com/a1akris/simploxide?tab=readme-ov-file#version-compatability-table)
/// )
#[derive(Debug)]
pub enum ClientError {
    /// Critical error signalling that the web socket connection is dropped for some reason. You
    /// will have to reconnect to the SimpleX server to recover from this one.
    WebSocketFailure(CoreError),
    /// SimpleX command error or unexpected(undocumented) response.
    BadResponse(BadResponseError),
}

impl std::error::Error for ClientError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::WebSocketFailure(error) => Some(error),
            Self::BadResponse(error) => Some(error),
        }
    }
}

impl std::fmt::Display for ClientError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ClientError::WebSocketFailure(err) => writeln!(f, "Web socket failure: {err}"),
            ClientError::BadResponse(err) => err.fmt(f),
        }
    }
}

impl From<BadResponseError> for ClientError {
    fn from(err: BadResponseError) -> Self {
        Self::BadResponse(err)
    }
}

impl ClientApiError for ClientError {
    fn bad_response(&self) -> Option<&BadResponseError> {
        if let Self::BadResponse(resp) = self {
            Some(resp)
        } else {
            None
        }
    }

    fn bad_response_mut(&mut self) -> Option<&mut BadResponseError> {
        if let Self::BadResponse(resp) = self {
            Some(resp)
        } else {
            None
        }
    }
}

#[derive(Debug)]
pub enum ConnectError {
    /// Failure to establish the connection to the server
    Server(CoreError),
    /// Failure to get the server version
    VersionError(VersionError),
    /// Unsupported server version
    VersionMismatch(SimplexVersion),
}

impl ConnectError {
    pub fn is_server(&self) -> bool {
        matches!(self, Self::Server(_))
    }

    pub fn is_version_mismatch(&self) -> bool {
        matches!(self, Self::VersionMismatch(_))
    }
}

impl From<WsError> for ConnectError {
    fn from(value: WsError) -> Self {
        Self::Server(Arc::new(value))
    }
}

impl std::fmt::Display for ConnectError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Server(error) => write!(f, "Cannot connect to the server: {error}"),
            Self::VersionError(error) => write!(f, "Cannot get the server version: {error}"),
            Self::VersionMismatch(v) => write!(
                f,
                "Version {v} is unsupported by the current client. Supported versions are {MIN_SUPPORTED_VERSION}..{MAX_SUPPORTED_VERSION}"
            ),
        }
    }
}

impl std::error::Error for ConnectError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Server(error) => Some(error),
            Self::VersionError(error) => Some(error),
            Self::VersionMismatch(_) => None,
        }
    }
}

pub struct BotBuilder {
    name: String,
    port: u16,
    retry_delay: std::time::Duration,
    retries: usize,
    auto_accept: Option<String>,
    profile: Option<Profile>,
    preferences: Option<Preferences>,
    avatar: Option<ImagePreview>,
    #[cfg(feature = "cli")]
    db_prefix: String,
    #[cfg(feature = "cli")]
    db_key: Option<String>,
    #[cfg(feature = "cli")]
    extra_args: Vec<std::ffi::OsString>,
}

impl BotBuilder {
    pub fn new(name: impl Into<String>, port: u16) -> Self {
        Self {
            name: name.into(),
            port,
            db_prefix: "bot".into(),
            db_key: None,
            retry_delay: std::time::Duration::from_secs(1),
            retries: 5,
            auto_accept: None,
            profile: None,
            preferences: None,
            avatar: None,
            #[cfg(feature = "cli")]
            extra_args: Vec::new(),
        }
    }

    #[cfg(feature = "cli")]
    /// Path prefix for the SimpleX database
    ///
    /// "{dir}/{prefix}" creates a {dir} with `{prefix}_agent.db` and `{prefix}_chat.db`;
    /// "{prefix}" creates `{prefix}_agent.db` and `{prefix}_chat.db` at the current dir
    pub fn db_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.db_prefix = prefix.into();
        self
    }

    #[cfg(feature = "cli")]
    /// Database encryption key.
    pub fn db_key(mut self, key: impl Into<String>) -> Self {
        self.db_key = Some(key.into());
        self
    }

    /// Delay between connection retry attempt. Default: 1s
    pub fn connect_retry_delay(mut self, delay: std::time::Duration) -> Self {
        self.retry_delay = delay;
        self
    }

    /// Number of connection retry attempts. Default: 5
    pub fn retries(mut self, n: usize) -> Self {
        self.retries = n;
        self
    }

    /// Create public address and auto accept users
    pub fn auto_accept(mut self) -> Self {
        self.auto_accept = Some(String::default());
        self
    }

    /// Set a welcome message. This automatically creates a public address with enabled auto_accept
    pub fn auto_accept_with(mut self, welcome_message: impl Into<String>) -> Self {
        self.auto_accept = Some(welcome_message.into());
        self
    }

    /// Set the bot avatar during initialisation
    pub fn with_avatar(mut self, avatar: ImagePreview) -> Self {
        self.avatar = Some(avatar);
        self
    }

    /// Update/create the whole bot profile on launch
    pub fn with_profile(mut self, profile: Profile) -> Self {
        self.profile = Some(profile);
        self
    }

    /// Apply these preferences to the bot's profile during initialisation.
    pub fn with_preferences(mut self, prefs: Preferences) -> Self {
        self.preferences = Some(prefs);
        self
    }

    /// Pass extra arguments to the `simplex-chat` process.
    #[cfg(feature = "cli")]
    pub fn cli_args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<std::ffi::OsString>,
    {
        self.extra_args.extend(args.into_iter().map(|s| s.into()));
        self
    }

    /// Connect to an already-running `simplex-chat` instance.
    pub async fn connect(self) -> Result<(Bot, EventStream), BotInitError> {
        let url = format!("ws://127.0.0.1:{}", self.port);

        let (client, events) = retry_connect(url, self.retry_delay, self.retries)
            .await
            .map_err(BotInitError::Connect)?;

        #[cfg(feature = "xftp")]
        let (client, events) = {
            let mut events = events;
            let client = events.hook_xftp(client);
            (client, events)
        };

        let settings = BotSettings {
            display_name: self.name,
            auto_accept: self.auto_accept,
            profile_settings: match (self.profile, self.preferences) {
                (Some(mut profile), Some(preferences)) => {
                    profile.preferences = Some(preferences);
                    Some(BotProfileSettings::FullProfile(profile))
                }
                (Some(profile), None) => Some(BotProfileSettings::FullProfile(profile)),
                (None, Some(preferences)) => Some(BotProfileSettings::Preferences(preferences)),
                (None, None) => None,
            },
            avatar: self.avatar,
        };

        let bot = Bot::init(client, settings).await?;
        Ok((bot, events))
    }

    /// Spawn `simplex-chat`, then connect and initialise.
    ///
    /// Returns `(bot, events, cli)`. The caller is responsible for calling
    /// [`cli::SimplexCli::kill`] after the bot finishes.
    #[cfg(feature = "cli")]
    pub async fn launch(mut self) -> Result<(Bot, EventStream, cli::SimplexCli), BotInitError> {
        let mut builder = cli::SimplexCli::builder(&self.name, self.port)
            .db_prefix(std::mem::take(&mut self.db_prefix));

        if let Some(ref mut key) = self.db_key {
            builder = builder.db_key(std::mem::take(key));
        }

        let cli = builder
            .args(std::mem::take(&mut self.extra_args))
            .spawn()
            .await
            .map_err(BotInitError::CliSpawn)?;

        let (bot, events) = self.connect().await?;
        Ok((bot, events, cli))
    }
}

/// Error returned by [`BotBuilder::connect`] and [`BotBuilder::launch`].
#[derive(Debug)]
pub enum BotInitError {
    Connect(ConnectError),
    Api(ClientError),
    #[cfg(feature = "cli")]
    CliSpawn(std::io::Error),
}

impl std::fmt::Display for BotInitError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            #[cfg(feature = "cli")]
            Self::CliSpawn(e) => write!(f, "failed to spawn simplex-chat: {e}"),
            Self::Connect(e) => write!(f, "websocket connection failed: {e}"),
            Self::Api(e) => write!(f, "SimpleX API error during init: {e}"),
        }
    }
}

impl std::error::Error for BotInitError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            #[cfg(feature = "cli")]
            Self::CliSpawn(e) => Some(e),
            Self::Connect(e) => Some(e),
            Self::Api(e) => Some(e),
        }
    }
}

impl From<ClientError> for BotInitError {
    fn from(e: ClientError) -> Self {
        Self::Api(e)
    }
}