Skip to main content

xmtp_mls/client/
conversations.rs

1//! Client conversations: creating and finding groups and DMs, messages, and the
2//! conversation list.
3
4use super::*;
5
6impl<Context> Client<Context>
7where
8    Context: XmtpSharedContext,
9{
10    /// Create a new group with the default settings
11    /// Applies a custom [`PolicySet`] to the group if one is specified
12    pub fn create_group(
13        &self,
14        permissions_policy_set: Option<PolicySet>,
15        opts: Option<GroupMetadataOptions>,
16    ) -> Result<MlsGroup<Context>, ClientError> {
17        self.ensure_identity_ready::<ClientError>()?;
18
19        let group: MlsGroup<Context> = MlsGroup::create_and_insert(
20            self.context.clone(),
21            ConversationType::Group,
22            permissions_policy_set.unwrap_or_default(),
23            opts.unwrap_or_default(),
24            None,
25        )?;
26
27        log_event!(
28            Event::CreatedGroup,
29            self.context.installation_id(),
30            group_id = group.group_id
31        );
32
33        Ok(group)
34    }
35
36    /// Create a group with an initial set of members added. Every account
37    /// resolves before the group is stored, as do member identities and key
38    /// packages. An account with no inbox fails with [`GroupError::AddressNotFound`].
39    pub async fn create_group_with_identifiers(
40        &self,
41        account_identifiers: &[Identifier],
42        permissions_policy_set: Option<PolicySet>,
43        opts: Option<GroupMetadataOptions>,
44    ) -> Result<MlsGroup<Context>, ClientError> {
45        self.create_group_with_targets(
46            &account_targets(account_identifiers),
47            permissions_policy_set,
48            opts,
49        )
50        .await
51    }
52
53    /// Returns the stored group if its first add is still pending when the wait
54    /// ends. A later sync completes the add.
55    #[tracing::instrument(level = "debug", skip_all, fields(size = inbox_ids.len()))]
56    pub async fn create_group_with_members(
57        &self,
58        inbox_ids: &[impl AsIdRef],
59        permissions_policy_set: Option<PolicySet>,
60        opts: Option<GroupMetadataOptions>,
61    ) -> Result<MlsGroup<Context>, ClientError> {
62        tracing::info!("creating group");
63        self.ensure_identity_ready::<ClientError>()?;
64        let (group, first_add) =
65            MlsGroup::create_with_first_add(&self.context, inbox_ids, permissions_policy_set, opts)
66                .await?;
67        log_event!(
68            Event::CreatedGroup,
69            self.context.installation_id(),
70            group_id = group.group_id
71        );
72        group.sync_first_add(first_add).await?;
73
74        Ok(group)
75    }
76
77    /// Create a new Direct Message with the default settings
78    #[tracing::instrument(level = "debug", skip_all)]
79    pub(super) async fn create_dm_by_inbox_id(
80        &self,
81        target_inbox_id: InboxId,
82        opts: Option<DMMetadataOptions>,
83    ) -> Result<MlsGroup<Context>, ClientError> {
84        let group: MlsGroup<Context> =
85            MlsGroup::create_allowed_dm(&self.context, target_inbox_id.clone(), opts)?;
86
87        log_event!(
88            Event::CreatedDM,
89            self.context.installation_id(),
90            group_id = group.group_id,
91            target_inbox = target_inbox_id
92        );
93        group.add_members(&[target_inbox_id]).await?;
94
95        Ok(group)
96    }
97
98    /// Find or create a Direct Message with the default settings
99    pub async fn find_or_create_dm_by_identity(
100        &self,
101        target_identity: Identifier,
102        opts: Option<DMMetadataOptions>,
103    ) -> Result<MlsGroup<Context>, ClientError> {
104        self.ensure_identity_ready::<ClientError>()?;
105        tracing::info!("finding or creating dm with address: {target_identity}");
106        let inbox_id = match self
107            .find_inbox_id_from_identifier(target_identity.clone())
108            .await?
109        {
110            Some(id) => id,
111            None => {
112                return Err(NotFound::InboxIdForAddress(target_identity.to_string()).into());
113            }
114        };
115
116        self.find_or_create_dm(inbox_id, opts).await
117    }
118
119    /// Find or create a Direct Message by inbox_id with the default settings.
120    /// A stored DM whose creation stopped before the peer was added gets the
121    /// peer first, and any failure of that add is returned, as a new DM's
122    /// creation returns its add's failure.
123    pub async fn find_or_create_dm(
124        &self,
125        inbox_id: impl AsIdRef,
126        opts: Option<DMMetadataOptions>,
127    ) -> Result<MlsGroup<Context>, ClientError> {
128        self.ensure_identity_ready::<ClientError>()?;
129        let inbox_id = inbox_id.as_ref();
130        tracing::info!("finding or creating dm with inbox_id: {}", inbox_id);
131        if let Some(group) =
132            MlsGroup::find_active_dm::<ClientError>(&self.context, inbox_id).await?
133        {
134            return Ok(group);
135        }
136        self.create_dm_by_inbox_id(inbox_id.to_string(), opts).await
137    }
138
139    /// Look up a group by its ID
140    ///
141    /// Returns a [`MlsGroup`] if the group exists, or an error if it does not
142    ///
143    pub fn group(&self, group_id: &GroupId) -> Result<MlsGroup<Context>, ClientError> {
144        MlsGroup::load_by_id(&self.context, group_id).map_err(Into::into)
145    }
146
147    /// Look up a group by its ID while stitching DMs
148    ///
149    /// Returns a [`MlsGroup`] if the group exists, or an error if it does not
150    ///
151    pub fn stitched_group(&self, group_id: &GroupId) -> Result<MlsGroup<Context>, ClientError> {
152        let conn = self.context.db();
153        let stored_group = conn.fetch_stitched(group_id)?;
154        stored_group
155            .map(|g| {
156                MlsGroup::new(
157                    self.context.clone(),
158                    g.id,
159                    g.dm_id,
160                    g.conversation_type,
161                    g.created_at_ns,
162                )
163            })
164            .ok_or(NotFound::GroupById(*group_id))
165            .map_err(Into::into)
166    }
167
168    /// Find all the duplicate dms for this group
169    pub fn find_duplicate_dms_for_group(
170        &self,
171        group_id: &GroupId,
172    ) -> Result<Vec<MlsGroup<Context>>, ClientError> {
173        let (group, _) = MlsGroup::new_cached(self.context.clone(), group_id)?;
174        Ok(group.find_duplicate_dms()?)
175    }
176
177    /// Fetches the message disappearing settings for a given group ID.
178    ///
179    /// Returns `Some(MessageDisappearingSettings)` if the group exists and has valid settings,
180    /// `None` if the group or settings are missing, or `Err(ClientError)` on a database error.
181    pub fn group_disappearing_settings(
182        &self,
183        group_id: &GroupId,
184    ) -> Result<Option<MessageDisappearingSettings>, ClientError> {
185        let (group, _) = MlsGroup::new_cached(self.context.clone(), group_id)?;
186        Ok(group.disappearing_settings()?)
187    }
188
189    /**
190     * Look up a DM group by the target's inbox_id.
191     *
192     * Returns a [`MlsGroup`] if the group exists, or an error if it does not
193     */
194    pub fn dm_group_from_target_inbox(
195        &self,
196        target_inbox_id: String,
197    ) -> Result<MlsGroup<Context>, ClientError> {
198        let conn = self.context.db();
199
200        let group = conn
201            .find_active_dm_group(&DmMembers {
202                member_one_inbox_id: self.inbox_id(),
203                member_two_inbox_id: &target_inbox_id,
204            })?
205            .ok_or(NotFound::DmByInbox(target_inbox_id))?;
206        Ok(MlsGroup::new(
207            self.context.clone(),
208            group.id,
209            group.dm_id,
210            group.conversation_type,
211            group.created_at_ns,
212        ))
213    }
214
215    /// Look up a message by its ID
216    /// Returns a [`StoredGroupMessage`] if the message exists, or an error if it does not
217    pub fn message(&self, message_id: Vec<u8>) -> Result<StoredGroupMessage, ClientError> {
218        let conn = &mut self.context.db();
219        // implements: META-051
220        let message =
221            conn.get_app_visible_group_message(&message_id, xmtp_common::time::now_ns())?;
222        Ok(message.ok_or(NotFound::MessageById(message_id))?)
223    }
224
225    /// Look up a stored message and its current conversation.
226    /// A message in a duplicate DM resolves to the stitched conversation.
227    pub async fn message_with_group(
228        &self,
229        id: &[u8],
230    ) -> Result<Option<(StoredGroupMessage, MlsGroup<Context>)>, ClientError> {
231        let message = match self.message(id.to_vec()) {
232            Ok(message) => message,
233            Err(ClientError::Storage(StorageError::NotFound(NotFound::MessageById(_)))) => {
234                return Ok(None);
235            }
236            Err(error) => return Err(error),
237        };
238        let group = self.stitched_group(&message.group_id)?;
239        Ok(Some((message, group)))
240    }
241
242    /// Look up and enrich a message by its ID, returning a [`DecodedMessage`]
243    /// Returns an error if the message is not found or if it cannot be decoded/enriched
244    #[xmtp_common::mls_span]
245    pub fn message_v2(&self, message_id: Vec<u8>) -> Result<DecodedMessage, ClientError> {
246        let conn = self.context.db();
247        let message = conn
248            .get_app_visible_group_message(&message_id, xmtp_common::time::now_ns())?
249            .ok_or_else(|| NotFound::MessageById(message_id.clone()))?;
250
251        let group_id = message.group_id;
252
253        let enriched = enrich_messages(conn, &group_id, vec![message])?;
254
255        // Since enrich_messages returns a Vec<DecodedMessage>, we can use .into_iter().next().ok_or(...) to take ownership without cloning.
256        enriched
257            .into_iter()
258            .next()
259            // In practice `enrich_messages` should always return an array of the same length as the input
260            .ok_or(ClientError::MessageDecodeFailed)
261    }
262
263    /// Delete a message by its ID
264    /// This method is idempotent and will not error if the message is not found
265    /// Returns the number of messages deleted (0 or 1)
266    pub fn delete_message(&self, message_id: Vec<u8>) -> Result<usize, ClientError> {
267        Ok(crate::state_tx::state_write_with_events(
268            self.context.mls_storage(),
269            self.context.events(),
270            |tx, events| {
271                let storage = tx.storage();
272                let db = storage.db();
273                let message = db.get_group_message(&message_id)?;
274                let deleted = db.delete_message_by_id(&message_id)?;
275                if deleted > 0
276                    && let Some(message) = message
277                {
278                    emit_deleted_messages(
279                        events,
280                        vec![message],
281                        DeletionCause::DeletedLocally,
282                        // A local removal of the row: no inbox sent a delete.
283                        None,
284                        &db,
285                    )?;
286                }
287                Ok::<_, StorageError>(Continue(deleted))
288            },
289        )?
290        .into_continued())
291    }
292
293    /// Query for groups with optional filters
294    ///
295    /// Filters:
296    /// - allowed_states: only return groups with the given membership states
297    /// - created_after_ns: only return groups created after the given timestamp (in nanoseconds)
298    /// - created_before_ns: only return groups created before the given timestamp (in nanoseconds)
299    /// - limit: only return the first `limit` groups
300    pub fn find_groups(&self, args: GroupQueryArgs) -> Result<Vec<MlsGroup<Context>>, ClientError> {
301        MlsGroup::find(&self.context, args).map_err(Into::into)
302    }
303
304    /// List one page of the app's conversations, in activity order unless
305    /// `args` names another order. A page holds at most `args.limit`
306    /// conversations, or [`CONVERSATION_LIST_DEFAULT_LIMIT`] when it names
307    /// none. To read the next page, pass the last row's `listing_time_ns` as
308    /// the order's before time and its group id as `before_id`.
309    ///
310    /// Internal callers that need every group use `find_groups` or
311    /// `fetch_conversation_list`, which apply no default limit.
312    // implements: CONS-046, CONS-049
313    pub fn list_conversations(
314        &self,
315        mut args: GroupQueryArgs,
316    ) -> Result<Vec<ConversationListItem<Context>>, ClientError> {
317        if args.order_by.is_none() {
318            args.order_by = Some(GroupQueryOrderBy::LastActivity);
319        }
320        let limit = args
321            .limit
322            .unwrap_or(i64::from(CONVERSATION_LIST_DEFAULT_LIMIT));
323        if !(1..=i64::from(LOCAL_PAGE_MAX_LIMIT)).contains(&limit) {
324            return Err(ClientError::InvalidListOptions(
325                "limit must be at least 1 and at most the maximum page size",
326            ));
327        }
328        args.limit = Some(limit);
329        if args.before_id.is_some() && args.order_before_ns().is_none() {
330            return Err(ClientError::InvalidListOptions(
331                "before_id needs the before time of the list order",
332            ));
333        }
334        // Requested sync groups bypass the page's limit, order and cursor, and
335        // a sync group is not a conversation.
336        if args.include_sync_groups || args.conversation_type.is_some_and(|kind| kind.is_virtual())
337        {
338            return Err(ClientError::InvalidListOptions(
339                "a conversation listing cannot include sync or one-shot groups",
340            ));
341        }
342        Ok(self
343            .context
344            .db()
345            .fetch_conversation_list(args)?
346            .into_iter()
347            .map(
348                |conversation_item: DbConversationListItem| ConversationListItem {
349                    membership_state: conversation_item.membership_state,
350                    added_by_inbox_id: conversation_item.added_by_inbox_id,
351                    group: MlsGroup::new(
352                        self.context.clone(),
353                        conversation_item.id,
354                        conversation_item.dm_id,
355                        conversation_item.conversation_type,
356                        conversation_item.created_at_ns,
357                    ),
358                    is_commit_log_forked: conversation_item.is_commit_log_forked,
359                    listing_time_ns: conversation_item.listing_time_ns,
360                },
361            )
362            .collect())
363    }
364}
365
366impl<Context: XmtpSharedContext> Client<Context> {
367    /// The active DM with `target`, or `None`. A target that no inbox holds
368    /// has no DM.
369    pub async fn find_dm_by_target(
370        &self,
371        target: &IdentityTarget,
372    ) -> Result<Option<MlsGroup<Context>>, ClientError> {
373        let Some(peer) =
374            inbox_handles::resolve_verified_in(&self.context, std::slice::from_ref(target))
375                .await?
376                .pop()
377                .flatten()
378        else {
379            return Ok(None);
380        };
381        let stored = self.context.db().find_active_dm_group(&DmMembers {
382            member_one_inbox_id: self.inbox_id(),
383            member_two_inbox_id: peer.as_str(),
384        })?;
385        stored.map(|stored| self.group(&stored.id)).transpose()
386    }
387
388    /// Find the DM with `target`, or create it. A handle resolves before the
389    /// existing DM is looked up.
390    pub async fn find_or_create_dm_by_target(
391        &self,
392        target: &IdentityTarget,
393        opts: DMMetadataOptions,
394    ) -> Result<MlsGroup<Context>, ClientError> {
395        match target {
396            IdentityTarget::Account(identifier) => {
397                self.find_or_create_dm_by_identity(identifier.clone(), Some(opts))
398                    .await
399            }
400            IdentityTarget::Handle(handle) => {
401                let peer = self
402                    .resolve_handles(std::slice::from_ref(handle))
403                    .await?
404                    .pop()
405                    .flatten()
406                    .ok_or(HandleError::NotFound)?;
407                self.find_or_create_dm(peer, Some(opts)).await
408            }
409        }
410    }
411
412    /// Create a group with `targets` as its members, in one commit. Targets,
413    /// member identities, and key packages resolve before the group is stored.
414    /// A target with no inbox leaves no group: a handle fails with
415    /// [`HandleError::NotFound`], an account with [`GroupError::AddressNotFound`].
416    pub async fn create_group_with_targets(
417        &self,
418        targets: &[IdentityTarget],
419        permissions_policy_set: Option<PolicySet>,
420        opts: Option<GroupMetadataOptions>,
421    ) -> Result<MlsGroup<Context>, ClientError> {
422        let inbox_ids =
423            crate::groups::targets::target_inboxes::<_, ClientError>(&self.context, targets)
424                .await?;
425        self.create_group_with_members(&inbox_ids, permissions_policy_set, opts)
426            .await
427    }
428}