mas_matrix/
lib.rs

1// Copyright 2024 New Vector Ltd.
2// Copyright 2023, 2024 The Matrix.org Foundation C.I.C.
3//
4// SPDX-License-Identifier: AGPL-3.0-only
5// Please see LICENSE in the repository root for full details.
6
7mod mock;
8mod readonly;
9
10use std::{collections::HashSet, sync::Arc};
11
12use ruma_common::UserId;
13
14pub use self::{
15    mock::HomeserverConnection as MockHomeserverConnection, readonly::ReadOnlyHomeserverConnection,
16};
17
18#[derive(Debug)]
19pub struct MatrixUser {
20    pub displayname: Option<String>,
21    pub avatar_url: Option<String>,
22    pub deactivated: bool,
23}
24
25#[derive(Debug, Default)]
26enum FieldAction<T> {
27    #[default]
28    DoNothing,
29    Set(T),
30    Unset,
31}
32
33pub struct ProvisionRequest {
34    mxid: String,
35    sub: String,
36    displayname: FieldAction<String>,
37    avatar_url: FieldAction<String>,
38    emails: FieldAction<Vec<String>>,
39}
40
41impl ProvisionRequest {
42    /// Create a new [`ProvisionRequest`].
43    ///
44    /// # Parameters
45    ///
46    /// * `mxid` - The Matrix ID to provision.
47    /// * `sub` - The `sub` of the user, aka the internal ID.
48    #[must_use]
49    pub fn new(mxid: impl Into<String>, sub: impl Into<String>) -> Self {
50        Self {
51            mxid: mxid.into(),
52            sub: sub.into(),
53            displayname: FieldAction::DoNothing,
54            avatar_url: FieldAction::DoNothing,
55            emails: FieldAction::DoNothing,
56        }
57    }
58
59    /// Get the `sub` of the user to provision, aka the internal ID.
60    #[must_use]
61    pub fn sub(&self) -> &str {
62        &self.sub
63    }
64
65    /// Get the Matrix ID to provision.
66    #[must_use]
67    pub fn mxid(&self) -> &str {
68        &self.mxid
69    }
70
71    /// Ask to set the displayname of the user.
72    ///
73    /// # Parameters
74    ///
75    /// * `displayname` - The displayname to set.
76    #[must_use]
77    pub fn set_displayname(mut self, displayname: String) -> Self {
78        self.displayname = FieldAction::Set(displayname);
79        self
80    }
81
82    /// Ask to unset the displayname of the user.
83    #[must_use]
84    pub fn unset_displayname(mut self) -> Self {
85        self.displayname = FieldAction::Unset;
86        self
87    }
88
89    /// Call the given callback if the displayname should be set or unset.
90    ///
91    /// # Parameters
92    ///
93    /// * `callback` - The callback to call.
94    pub fn on_displayname<F>(&self, callback: F) -> &Self
95    where
96        F: FnOnce(Option<&str>),
97    {
98        match &self.displayname {
99            FieldAction::Unset => callback(None),
100            FieldAction::Set(displayname) => callback(Some(displayname)),
101            FieldAction::DoNothing => {}
102        }
103
104        self
105    }
106
107    /// Ask to set the avatar URL of the user.
108    ///
109    /// # Parameters
110    ///
111    /// * `avatar_url` - The avatar URL to set.
112    #[must_use]
113    pub fn set_avatar_url(mut self, avatar_url: String) -> Self {
114        self.avatar_url = FieldAction::Set(avatar_url);
115        self
116    }
117
118    /// Ask to unset the avatar URL of the user.
119    #[must_use]
120    pub fn unset_avatar_url(mut self) -> Self {
121        self.avatar_url = FieldAction::Unset;
122        self
123    }
124
125    /// Call the given callback if the avatar URL should be set or unset.
126    ///
127    /// # Parameters
128    ///
129    /// * `callback` - The callback to call.
130    pub fn on_avatar_url<F>(&self, callback: F) -> &Self
131    where
132        F: FnOnce(Option<&str>),
133    {
134        match &self.avatar_url {
135            FieldAction::Unset => callback(None),
136            FieldAction::Set(avatar_url) => callback(Some(avatar_url)),
137            FieldAction::DoNothing => {}
138        }
139
140        self
141    }
142
143    /// Ask to set the emails of the user.
144    ///
145    /// # Parameters
146    ///
147    /// * `emails` - The list of emails to set.
148    #[must_use]
149    pub fn set_emails(mut self, emails: Vec<String>) -> Self {
150        self.emails = FieldAction::Set(emails);
151        self
152    }
153
154    /// Ask to unset the emails of the user.
155    #[must_use]
156    pub fn unset_emails(mut self) -> Self {
157        self.emails = FieldAction::Unset;
158        self
159    }
160
161    /// Call the given callback if the emails should be set or unset.
162    ///
163    /// # Parameters
164    ///
165    /// * `callback` - The callback to call.
166    pub fn on_emails<F>(&self, callback: F) -> &Self
167    where
168        F: FnOnce(Option<&[String]>),
169    {
170        match &self.emails {
171            FieldAction::Unset => callback(None),
172            FieldAction::Set(emails) => callback(Some(emails)),
173            FieldAction::DoNothing => {}
174        }
175
176        self
177    }
178}
179
180#[async_trait::async_trait]
181pub trait HomeserverConnection: Send + Sync {
182    /// Get the homeserver URL.
183    fn homeserver(&self) -> &str;
184
185    /// Get the Matrix ID of the user with the given localpart.
186    ///
187    /// # Parameters
188    ///
189    /// * `localpart` - The localpart of the user.
190    fn mxid(&self, localpart: &str) -> String {
191        format!("@{}:{}", localpart, self.homeserver())
192    }
193
194    /// Get the localpart of a Matrix ID if it has the right server name
195    ///
196    /// Returns [`None`] if the input isn't a valid MXID, or if the server name
197    /// doesn't match
198    ///
199    /// # Parameters
200    ///
201    /// * `mxid` - The MXID of the user
202    fn localpart<'a>(&self, mxid: &'a str) -> Option<&'a str> {
203        let mxid = <&UserId>::try_from(mxid).ok()?;
204        if mxid.server_name() != self.homeserver() {
205            return None;
206        }
207        Some(mxid.localpart())
208    }
209
210    /// Query the state of a user on the homeserver.
211    ///
212    /// # Parameters
213    ///
214    /// * `mxid` - The Matrix ID of the user to query.
215    ///
216    /// # Errors
217    ///
218    /// Returns an error if the homeserver is unreachable or the user does not
219    /// exist.
220    async fn query_user(&self, mxid: &str) -> Result<MatrixUser, anyhow::Error>;
221
222    /// Provision a user on the homeserver.
223    ///
224    /// # Parameters
225    ///
226    /// * `request` - a [`ProvisionRequest`] containing the details of the user
227    ///   to provision.
228    ///
229    /// # Errors
230    ///
231    /// Returns an error if the homeserver is unreachable or the user could not
232    /// be provisioned.
233    async fn provision_user(&self, request: &ProvisionRequest) -> Result<bool, anyhow::Error>;
234
235    /// Check whether a given username is available on the homeserver.
236    ///
237    /// # Parameters
238    ///
239    /// * `localpart` - The localpart to check.
240    ///
241    /// # Errors
242    ///
243    /// Returns an error if the homeserver is unreachable.
244    async fn is_localpart_available(&self, localpart: &str) -> Result<bool, anyhow::Error>;
245
246    /// Create a device for a user on the homeserver.
247    ///
248    /// # Parameters
249    ///
250    /// * `mxid` - The Matrix ID of the user to create a device for.
251    /// * `device_id` - The device ID to create.
252    ///
253    /// # Errors
254    ///
255    /// Returns an error if the homeserver is unreachable or the device could
256    /// not be created.
257    async fn create_device(&self, mxid: &str, device_id: &str) -> Result<(), anyhow::Error>;
258
259    /// Delete a device for a user on the homeserver.
260    ///
261    /// # Parameters
262    ///
263    /// * `mxid` - The Matrix ID of the user to delete a device for.
264    /// * `device_id` - The device ID to delete.
265    ///
266    /// # Errors
267    ///
268    /// Returns an error if the homeserver is unreachable or the device could
269    /// not be deleted.
270    async fn delete_device(&self, mxid: &str, device_id: &str) -> Result<(), anyhow::Error>;
271
272    /// Sync the list of devices of a user with the homeserver.
273    ///
274    /// # Parameters
275    ///
276    /// * `mxid` - The Matrix ID of the user to sync the devices for.
277    /// * `devices` - The list of devices to sync.
278    ///
279    /// # Errors
280    ///
281    /// Returns an error if the homeserver is unreachable or the devices could
282    /// not be synced.
283    async fn sync_devices(&self, mxid: &str, devices: HashSet<String>)
284    -> Result<(), anyhow::Error>;
285
286    /// Delete a user on the homeserver.
287    ///
288    /// # Parameters
289    ///
290    /// * `mxid` - The Matrix ID of the user to delete.
291    /// * `erase` - Whether to ask the homeserver to erase the user's data.
292    ///
293    /// # Errors
294    ///
295    /// Returns an error if the homeserver is unreachable or the user could not
296    /// be deleted.
297    async fn delete_user(&self, mxid: &str, erase: bool) -> Result<(), anyhow::Error>;
298
299    /// Reactivate a user on the homeserver.
300    ///
301    /// # Parameters
302    ///
303    /// * `mxid` - The Matrix ID of the user to reactivate.
304    ///
305    /// # Errors
306    ///
307    /// Returns an error if the homeserver is unreachable or the user could not
308    /// be reactivated.
309    async fn reactivate_user(&self, mxid: &str) -> Result<(), anyhow::Error>;
310
311    /// Set the displayname of a user on the homeserver.
312    ///
313    /// # Parameters
314    ///
315    /// * `mxid` - The Matrix ID of the user to set the displayname for.
316    /// * `displayname` - The displayname to set.
317    ///
318    /// # Errors
319    ///
320    /// Returns an error if the homeserver is unreachable or the displayname
321    /// could not be set.
322    async fn set_displayname(&self, mxid: &str, displayname: &str) -> Result<(), anyhow::Error>;
323
324    /// Unset the displayname of a user on the homeserver.
325    ///
326    /// # Parameters
327    ///
328    /// * `mxid` - The Matrix ID of the user to unset the displayname for.
329    ///
330    /// # Errors
331    ///
332    /// Returns an error if the homeserver is unreachable or the displayname
333    /// could not be unset.
334    async fn unset_displayname(&self, mxid: &str) -> Result<(), anyhow::Error>;
335
336    /// Temporarily allow a user to reset their cross-signing keys.
337    ///
338    /// # Parameters
339    ///
340    /// * `mxid` - The Matrix ID of the user to allow cross-signing key reset
341    ///
342    /// # Errors
343    ///
344    /// Returns an error if the homeserver is unreachable or the cross-signing
345    /// reset could not be allowed.
346    async fn allow_cross_signing_reset(&self, mxid: &str) -> Result<(), anyhow::Error>;
347}
348
349#[async_trait::async_trait]
350impl<T: HomeserverConnection + Send + Sync + ?Sized> HomeserverConnection for &T {
351    fn homeserver(&self) -> &str {
352        (**self).homeserver()
353    }
354
355    async fn query_user(&self, mxid: &str) -> Result<MatrixUser, anyhow::Error> {
356        (**self).query_user(mxid).await
357    }
358
359    async fn provision_user(&self, request: &ProvisionRequest) -> Result<bool, anyhow::Error> {
360        (**self).provision_user(request).await
361    }
362
363    async fn is_localpart_available(&self, localpart: &str) -> Result<bool, anyhow::Error> {
364        (**self).is_localpart_available(localpart).await
365    }
366
367    async fn create_device(&self, mxid: &str, device_id: &str) -> Result<(), anyhow::Error> {
368        (**self).create_device(mxid, device_id).await
369    }
370
371    async fn delete_device(&self, mxid: &str, device_id: &str) -> Result<(), anyhow::Error> {
372        (**self).delete_device(mxid, device_id).await
373    }
374
375    async fn sync_devices(
376        &self,
377        mxid: &str,
378        devices: HashSet<String>,
379    ) -> Result<(), anyhow::Error> {
380        (**self).sync_devices(mxid, devices).await
381    }
382
383    async fn delete_user(&self, mxid: &str, erase: bool) -> Result<(), anyhow::Error> {
384        (**self).delete_user(mxid, erase).await
385    }
386
387    async fn reactivate_user(&self, mxid: &str) -> Result<(), anyhow::Error> {
388        (**self).reactivate_user(mxid).await
389    }
390
391    async fn set_displayname(&self, mxid: &str, displayname: &str) -> Result<(), anyhow::Error> {
392        (**self).set_displayname(mxid, displayname).await
393    }
394
395    async fn unset_displayname(&self, mxid: &str) -> Result<(), anyhow::Error> {
396        (**self).unset_displayname(mxid).await
397    }
398
399    async fn allow_cross_signing_reset(&self, mxid: &str) -> Result<(), anyhow::Error> {
400        (**self).allow_cross_signing_reset(mxid).await
401    }
402}
403
404// Implement for Arc<T> where T: HomeserverConnection
405#[async_trait::async_trait]
406impl<T: HomeserverConnection + ?Sized> HomeserverConnection for Arc<T> {
407    fn homeserver(&self) -> &str {
408        (**self).homeserver()
409    }
410
411    async fn query_user(&self, mxid: &str) -> Result<MatrixUser, anyhow::Error> {
412        (**self).query_user(mxid).await
413    }
414
415    async fn provision_user(&self, request: &ProvisionRequest) -> Result<bool, anyhow::Error> {
416        (**self).provision_user(request).await
417    }
418
419    async fn is_localpart_available(&self, localpart: &str) -> Result<bool, anyhow::Error> {
420        (**self).is_localpart_available(localpart).await
421    }
422
423    async fn create_device(&self, mxid: &str, device_id: &str) -> Result<(), anyhow::Error> {
424        (**self).create_device(mxid, device_id).await
425    }
426
427    async fn delete_device(&self, mxid: &str, device_id: &str) -> Result<(), anyhow::Error> {
428        (**self).delete_device(mxid, device_id).await
429    }
430
431    async fn sync_devices(
432        &self,
433        mxid: &str,
434        devices: HashSet<String>,
435    ) -> Result<(), anyhow::Error> {
436        (**self).sync_devices(mxid, devices).await
437    }
438
439    async fn delete_user(&self, mxid: &str, erase: bool) -> Result<(), anyhow::Error> {
440        (**self).delete_user(mxid, erase).await
441    }
442
443    async fn reactivate_user(&self, mxid: &str) -> Result<(), anyhow::Error> {
444        (**self).reactivate_user(mxid).await
445    }
446
447    async fn set_displayname(&self, mxid: &str, displayname: &str) -> Result<(), anyhow::Error> {
448        (**self).set_displayname(mxid, displayname).await
449    }
450
451    async fn unset_displayname(&self, mxid: &str) -> Result<(), anyhow::Error> {
452        (**self).unset_displayname(mxid).await
453    }
454
455    async fn allow_cross_signing_reset(&self, mxid: &str) -> Result<(), anyhow::Error> {
456        (**self).allow_cross_signing_reset(mxid).await
457    }
458}