Skip to main content

simploxide_client/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2//! For first-time users, it's recommended to get hands-on experience by running some example bots
3//! on [GitHub](https://github.com/a1akris/simploxide/tree/main/simploxide-client) before writing
4//! their own.
5//!
6//! This SDK is intended to be used with the `tokio` runtime. Here are the steps to implement any bot:
7//!
8//! ### 1. Choose a backend
9//!
10//! `simploxide` supports both **WebSocket** and **FFI** SimpleX-Chat backends.
11//! All FFI-exclusive methods are reimplemented in native Rust, so in practice the backends differ
12//! only in their runtime characteristics: a single-process app via **FFI** vs. an app that
13//! connects to a running SimpleX-Chat **WebSocket** server.
14//!
15//! Since both backends are equally capable, always start development with the **WebSocket** backend
16//! (enabled by default). Switching to **FFI** later is as simple as replacing `ws` imports with
17//! `ffi` imports, but **FFI** requires configuring the crate build and obliges you to use the
18//! AGPL-3.0 license. You can read more about switching to **FFI** in the `simploxide-sxcrt-sys` crate docs.
19//!
20//! ### 2. Initialise the bot
21//!
22//! `simploxide` provides convenient bot builders to launch and configure your bot.
23//!
24//! ```ignore
25//! let (bot, events, mut cli) = ws::BotBuilder::new("YesMan", 5225)
26//!     .db_prefix("db/bot")
27//!     // Create a public bot address that auto-accepts new users with a welcome message.
28//!     .auto_accept_with(
29//!         "Hello, I'm a bot that always agrees with my users",
30//!     )
31//!     // Launch the CLI, connect the client, and initialise the bot.
32//!     .launch()
33//!     .await?;
34//!
35//! let address = bot.address().await?;
36//! println!("My address: {address}");
37//! ```
38//!
39//! See all available options in [ws::BotBuilder] and [ffi::BotBuilder].
40//!
41//! ### 3. Set up an event dispatcher
42//!
43//! Dispatchers are zero-cost and provide a convenient API for handling events.
44//!
45//! ```ignore
46//! // into_dispatcher accepts any type and creates a dispatcher from the event stream.
47//! // The value provided here is passed into all event handlers as a second argument.
48//! events.into_dispatcher(bot)
49//!     .on(new_messages)
50//!     .dispatch()
51//!     .await?;
52//! ```
53//!
54//! Learn more about dispatchers in the [dispatcher] and [EventStream] docs.
55//!
56//! ### 4. Implement event handlers
57//!
58//! The first handler argument determines which event the handler processes. The [StreamEvents]
59//! type allows interrupting event dispatching via [`StreamEvents::Break`].
60//!
61//! ```ignore
62//! async fn new_msgs(ev: Arc<NewChatItems>, bot: Bot) -> ws::ClientResult<StreamEvents> {
63//!     for (chat, msg, content) in ev.filter_messages() {
64//!         bot.update_msg_reaction(chat, msg, Reaction::Set("👍")).await?;
65//!
66//!         bot.send_msg(chat, "I absolutely agree with this!".bold())
67//!            .reply_to(msg)
68//!            .await?;
69//!     }
70//!
71//!     Ok(StreamEvents::Continue)
72//! }
73//! ```
74//!
75//! Message builders are quite powerful, see [`messages`] for details. In most places where an
76//! ID is expected you can pass a struct directly; see the type-safe conversions available in [id].
77//!
78//! ### 5. Execute cleanup before exiting
79//!
80//! ```ignore
81//! bot.shutdown().await;
82//! cli.kill().await?;
83//! ```
84//!
85//! ## Features
86//!
87//! `simploxide` strives to be a minimal library for simple bots while also coming with batteries
88//! included for all sorts of the advanced use cases. The balance is maintained through feature
89//! gates documented below:
90//!
91//! - **`cli`** *(default)*: WebSocket backend ([`ws`]) with a built-in runner that spawns and
92//!   manages a local `simplex-chat` process. Use [`ws::BotBuilder::launch`] to start everything
93//!   in one call.
94//!
95//! - **`websocket`**: WebSocket backend ([`ws`]) without the CLI runner. Use
96//!   [`ws::BotBuilder::connect`] to attach to an already-running `simplex-chat` server.
97//!
98//! - **`ffi`**: FFI backend ([`ffi`]) that embeds the SimpleX-Chat library in-process.
99//!   Requires AGPL-3.0 and additional build configuration; see `simploxide-sxcrt-sys`.
100//!
101//! - **`native_crypto`**: Native Rust implementation of client-side encryption(XSalsa20 + Poly1305). Enables
102//!   [`ImagePreview::from_crypto_file`](preview::ImagePreview::from_crypto_file) and [crypto::fs]
103//!   module allowing to encrypt decrypt files directly in the Rust code
104//!
105//! - **`multimedia`**: Image transcoding via the `image` crate. Enables
106//!   [`preview::transcoder::Transcoder`] and automatic thumbnail generation for [`messages::Image`].
107//!   [`preview::ImagePreview`] automatically tries to transcode its sources to JPEGs with this
108//!   feature on
109//!
110//! - **`xftp`**: XFTP file transfer support. Enables [`xftp::XftpClient`], which intercepts
111//!   streamlines file downlaods with a `download_file` method.
112//!
113//! - **`cancellation`**: Re-exports [`tokio_util::sync::CancellationToken`] and enables helper
114//!   methods for cooperative shutdown.
115//!
116//! - **`crypto`**: Low-level cryptographic primitives (zeroize, rand). Pulled in automatically by
117//!   `native_crypto`. Useful on its own if you wish to use your own crypto implementation.
118//!
119//! - **`fullcli`**: Convenience bundle: `cli` + `native_crypto` + `multimedia` + `xftp` +
120//!   `cancellation`.
121//!
122//! - **`fullffi`**: Convenience bundle: `ffi` + `native_crypto` + `multimedia` + `xftp` +
123//!   `cancellation`.
124//!
125//! ### How to work with this documentation?
126//!
127//! The [bot] page should be your primary reference and the [events] page your secondary one.
128//! From these two pages you should be able to find everything in a structured manner.
129
130#[cfg(feature = "crypto")]
131pub mod crypto;
132#[cfg(feature = "ffi")]
133pub mod ffi;
134#[cfg(feature = "websocket")]
135pub mod ws;
136#[cfg(feature = "xftp")]
137pub mod xftp;
138
139pub mod bot;
140pub mod dispatcher;
141pub mod ext;
142pub mod id;
143pub mod messages;
144pub mod prelude;
145pub mod preview;
146
147mod util;
148
149pub use simploxide_api_types::{
150    self as types,
151    client_api::{self, BadResponseError, ClientApi, ClientApiError},
152    commands, events,
153    events::{Event, EventKind},
154    responses,
155    utils::CommandSyntax,
156};
157
158#[cfg(feature = "cancellation")]
159pub use tokio_util::{self, sync::CancellationToken};
160
161pub use dispatcher::DispatchChain;
162
163use futures::{Stream, TryStreamExt as _};
164
165use std::{
166    pin::Pin,
167    sync::Arc,
168    task::{Context, Poll},
169};
170
171/// The high level event stream that embeds event filtering.
172///
173/// Parsing SimpleX events may be costly, they are quite large deeply nested structs with a lot of
174/// [`String`] and [`std::collections::BTreeMap`] types. This stream provides filtering APIs
175/// allowing to parse and propagate events the application handles and drop all other events early
176/// without allocating any extra memory.
177///
178/// By default filters are disabled and no events are dropped. Use [`Self::set_filter`] to only
179/// receive events you're interested in.
180///
181/// Use [`Self::into_dispatcher`] to handle events conveniently. Dispatchers are completely
182/// zerocost, manage filters internally, and provide a high-level easy to use API covering the
183/// absolute majority of use cases.
184pub struct EventStream<P> {
185    filter: [bool; EventKind::COUNT],
186    receiver: tokio::sync::mpsc::UnboundedReceiver<P>,
187    hooks: Vec<Box<dyn Hook>>,
188}
189
190impl<P> From<tokio::sync::mpsc::UnboundedReceiver<P>> for EventStream<P> {
191    fn from(receiver: tokio::sync::mpsc::UnboundedReceiver<P>) -> Self {
192        Self {
193            filter: [true; EventKind::COUNT],
194            receiver,
195            hooks: Vec::new(),
196        }
197    }
198}
199
200impl<P> EventStream<P> {
201    pub fn add_hook(&mut self, hook: Box<dyn Hook>) {
202        self.hooks.push(hook);
203    }
204
205    #[cfg(feature = "xftp")]
206    pub fn hook_xftp<C: 'static + Clone + Send + ClientApi>(
207        &mut self,
208        client: C,
209    ) -> xftp::XftpClient<C> {
210        let xftp_client = xftp::XftpClient::from(client);
211        let hook = xftp_client.clone();
212        self.add_hook(Box::new(hook));
213
214        xftp_client
215    }
216
217    pub fn set_filter<I: IntoIterator<Item = EventKind>>(&mut self, f: Filter<I>) -> &mut Self {
218        match f {
219            Filter::Accept(kinds) => {
220                self.reject_all();
221                for kind in kinds {
222                    self.filter[kind.as_usize()] = true;
223                }
224            }
225            Filter::AcceptAllExcept(kinds) => {
226                self.accept_all();
227                for kind in kinds {
228                    self.filter[kind.as_usize()] = false;
229                }
230            }
231            Filter::AcceptAll => self.accept_all(),
232        }
233
234        self
235    }
236
237    pub fn accept(&mut self, kind: EventKind) {
238        self.filter[kind.as_usize()] = true;
239    }
240
241    pub fn reject(&mut self, kind: EventKind) {
242        self.filter[kind.as_usize()] = false;
243    }
244
245    pub fn accept_all(&mut self) {
246        self.set_all(true);
247    }
248
249    pub fn reject_all(&mut self) {
250        self.set_all(false)
251    }
252
253    fn set_all(&mut self, new: bool) {
254        for old in &mut self.filter {
255            *old = new;
256        }
257    }
258}
259
260impl<P: EventParser> EventStream<P> {
261    /// Turns stream into a [`DispatchChain`] builder with the provided `ctx`. The `ctx` is an
262    /// arbitrary type that can be used within event handlers. Use [`dispatcher::Dispatcher::seq`] to add
263    /// sequential handlers: `AsyncFnMut(Arc<Ev>, &mut Ctx)`; or [`dispatcher::Dispatcher::on`] for concurrent
264    /// ones: `AsyncFn(Arc<Ev>, Ctx) where Ctx: 'static + Clone + Send`.
265    pub fn into_dispatcher<C>(self, ctx: C) -> DispatchChain<P, C> {
266        DispatchChain::with_ctx(self, ctx)
267    }
268
269    /// Waits for a particular event `Ev` **dropping** other events in the process. This method is
270    /// mostly useful in bot initialisation scenarios when the bot doesn't have any active users.
271    /// Misusing this method may result in not receiving user messages and other important events.
272    pub async fn wait_for<Ev: events::EventData>(&mut self) -> Result<Option<Arc<Ev>>, P::Error> {
273        self.reject_all();
274        self.accept(Ev::KIND);
275        let result = self.try_next().await;
276        self.accept_all();
277
278        let ev = result?;
279        Ok(ev.map(|ev| Ev::from_event(ev).unwrap()))
280    }
281
282    /// Waits for one one of the events in the `kinds` list **dropping** other events in the
283    /// process. Returns the first encountered event of the specified kind. This method is mostly
284    /// useful in bot initialisation scenarios when the bot doesn't have any active users. Misusing
285    /// this method may result in not receiving user messages and other important events.
286    pub async fn wait_for_any(
287        &mut self,
288        kinds: impl IntoIterator<Item = EventKind>,
289    ) -> Result<Option<Event>, P::Error> {
290        self.set_filter(Filter::Accept(kinds));
291        let result = self.try_next().await;
292        self.accept_all();
293        result
294    }
295
296    pub async fn stream_events<E, F>(mut self, mut f: F) -> Result<Self, E>
297    where
298        F: AsyncFnMut(Event) -> Result<StreamEvents, E>,
299        E: From<P::Error>,
300    {
301        while let Some(event) = self.try_next().await? {
302            if let StreamEvents::Break = f(event).await? {
303                break;
304            }
305        }
306
307        Ok(self)
308    }
309
310    pub async fn stream_events_with_ctx_mut<E, Ctx, F>(
311        mut self,
312        mut f: F,
313        mut ctx: Ctx,
314    ) -> Result<(Self, Ctx), E>
315    where
316        F: AsyncFnMut(Event, &mut Ctx) -> Result<StreamEvents, E>,
317        E: From<P::Error>,
318    {
319        while let Some(event) = self.try_next().await? {
320            if let StreamEvents::Break = f(event, &mut ctx).await? {
321                break;
322            }
323        }
324
325        Ok((self, ctx))
326    }
327
328    pub async fn stream_events_with_ctx_cloned<E, Ctx, F>(
329        mut self,
330        f: F,
331        ctx: Ctx,
332    ) -> Result<(Self, Ctx), E>
333    where
334        Ctx: Clone,
335        F: AsyncFn(Event, Ctx) -> Result<StreamEvents, E>,
336        E: From<P::Error>,
337    {
338        while let Some(event) = self.try_next().await? {
339            if let StreamEvents::Break = f(event, ctx.clone()).await? {
340                break;
341            }
342        }
343
344        Ok((self, ctx))
345    }
346}
347
348pub enum Filter<I: IntoIterator<Item = EventKind>> {
349    Accept(I),
350    AcceptAll,
351    AcceptAllExcept(I),
352}
353
354#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
355pub enum StreamEvents {
356    Break,
357    Continue,
358}
359
360impl<P: EventParser> Stream for EventStream<P> {
361    type Item = Result<Event, P::Error>;
362
363    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
364        loop {
365            match self.receiver.poll_recv(cx) {
366                Poll::Ready(Some(raw_event)) => {
367                    let kind = match raw_event.parse_kind() {
368                        Ok(kind) => kind,
369                        Err(e) => break Poll::Ready(Some(Err(e))),
370                    };
371
372                    if !self.hooks.iter().any(|h| h.should_intercept(kind))
373                        && !self.filter[kind.as_usize()]
374                    {
375                        continue;
376                    }
377
378                    match raw_event.parse_event() {
379                        Ok(event) => {
380                            for hook in self.hooks.iter_mut() {
381                                if hook.should_intercept(kind) {
382                                    hook.intercept_event(event.clone());
383                                }
384                            }
385
386                            if self.filter[kind.as_usize()] {
387                                break Poll::Ready(Some(Ok(event)));
388                            }
389                        }
390                        Err(e) => break Poll::Ready(Some(Err(e))),
391                    }
392                }
393                Poll::Ready(None) => break Poll::Ready(None),
394                Poll::Pending => break Poll::Pending,
395            }
396        }
397    }
398}
399
400/// A helper trait meant to be implemented by raw event types
401pub trait EventParser {
402    type Error;
403
404    /// Should parse kind cheaply without allocations
405    fn parse_kind(&self) -> Result<EventKind, Self::Error>;
406
407    /// Parse the whole events
408    fn parse_event(&self) -> Result<Event, Self::Error>;
409}
410
411impl EventParser for Event {
412    type Error = std::convert::Infallible;
413
414    fn parse_kind(&self) -> Result<EventKind, Self::Error> {
415        Ok(self.kind())
416    }
417
418    fn parse_event(&self) -> Result<Event, Self::Error> {
419        // Cheap Arc Clone
420        Ok(self.clone())
421    }
422}
423
424pub trait Hook: 'static + Send {
425    fn should_intercept(&self, kind: EventKind) -> bool;
426
427    /// Hooks must not block the event stream; this method should be a cheap synchronous call.
428    /// Delegate heavy work to another thread or spawn async tasks internally.
429    fn intercept_event(&mut self, event: Event);
430}
431
432/// Syntactic sugar for constructing [`Preferences`](simploxide_api_types::Preferences) values.
433///
434/// ```ignore
435/// Preferences {
436///     timed_messages: preferences::timed_messages::yes(Duration::from_hours(4)),
437///     full_delete: preferences::YES,
438///     reactions: preferences::ALWAYS,
439///     voice: preferences::NO,
440///     files: preferences::ALWAYS,
441///     calls: preferences::YES,
442///     sessions: preferences::NO,
443///     commands: None,
444///     undocumented: Default::default(),
445/// }
446/// ```
447pub mod preferences {
448    use simploxide_api_types::{FeatureAllowed, SimplePreference};
449
450    pub mod timed_messages {
451        use super::*;
452        use simploxide_api_types::TimedMessagesPreference;
453
454        pub const TTL_MAX: std::time::Duration = std::time::Duration::from_hours(8784);
455
456        pub fn ttl_to_secs(ttl: std::time::Duration) -> i32 {
457            let clamped = std::cmp::min(ttl, TTL_MAX);
458            clamped.as_secs() as i32
459        }
460
461        pub fn always(ttl: std::time::Duration) -> Option<TimedMessagesPreference> {
462            Some(TimedMessagesPreference {
463                allow: FeatureAllowed::Always,
464                ttl: Some(ttl_to_secs(ttl)),
465                undocumented: serde_json::Value::Null,
466            })
467        }
468
469        pub fn yes(ttl: std::time::Duration) -> Option<TimedMessagesPreference> {
470            Some(TimedMessagesPreference {
471                allow: FeatureAllowed::Yes,
472                ttl: Some(ttl_to_secs(ttl)),
473                undocumented: serde_json::Value::Null,
474            })
475        }
476
477        pub const NO: Option<TimedMessagesPreference> = Some(TimedMessagesPreference {
478            allow: FeatureAllowed::No,
479            ttl: None,
480            undocumented: serde_json::Value::Null,
481        });
482    }
483
484    pub const ALWAYS: Option<SimplePreference> = Some(SimplePreference {
485        allow: FeatureAllowed::Always,
486        undocumented: serde_json::Value::Null,
487    });
488
489    pub const YES: Option<SimplePreference> = Some(SimplePreference {
490        allow: FeatureAllowed::Yes,
491        undocumented: serde_json::Value::Null,
492    });
493
494    pub const NO: Option<SimplePreference> = Some(SimplePreference {
495        allow: FeatureAllowed::No,
496        undocumented: serde_json::Value::Null,
497    });
498}