atagen

macltok

public
Star0
Watch0
74befbc72baf5d21a371cff0b839aba9c142afd0
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git
src/transport.rsRust1904 lines58.1 KB
1
use std::{
2
    collections::HashSet,
3
    fmt,
4
    future::Future,
5
    pin::Pin,
6
    sync::{Arc, Mutex, Weak},
7
    task::{Context, Poll},
8
};
9
10
use matrix_sdk::{Client, RoomMemberships};
11
use matrix_sdk_ui::{
12
    notification_client::{
13
        NotificationClient, NotificationProcessSetup, NotificationStatus, RawNotificationEvent,
14
    },
15
    spaces::{SpaceRoomList, SpaceService, room_list::SpaceRoomListPaginationState},
16
    sync_service::SyncService,
17
};
18
use ruma::{
19
    EventId, OwnedDeviceId, OwnedEventId, OwnedMxcUri, OwnedRoomId, OwnedRoomOrAliasId,
20
    OwnedServerName, OwnedTransactionId, OwnedUserId, RoomId, UserId,
21
    events::{
22
        AnyGlobalAccountDataEventContent, AnyRoomAccountDataEvent, AnyRoomAccountDataEventContent,
23
        GlobalAccountDataEventType, RoomAccountDataEventType,
24
    },
25
    serde::Raw,
26
};
27
use tokio::sync::{OnceCell, mpsc, oneshot, watch};
28
29
use crate::{
30
    AccountCommand, AttachmentUpload, Command, CommandOutput, ConnectionState, CreateRoomOptions,
31
    EncryptionCommand, EncryptionState, Error, ErrorKind, Event, EventContextCommand,
32
    EventContextPage, EventContextSession, EventRef, HistoryRepairCommand, ImagePackSource,
33
    ImagePacks, InteractiveAuth, InteractiveAuthOutcome, LifecycleCommand, LinkPreview, Media,
34
    MediaCommand, MediaId, MediaLocation, MediaSize, MemberFilter, MemberSummary, MentionKey,
35
    MentionsBoundary, MentionsCommand, MentionsPage, MessageContent, MessageEditContent,
36
    NotificationCommand, OwnDevice, PackCommand, PackImageInfo, PackUsage, Patch,
37
    PowerLevelChanges, Profile, PushNotification, PushNotificationEvent, PushNotificationStatus,
38
    RoomCommand, RoomListFilter, RoomNotificationMode, RoomNotificationSettings, RoomPowerLevels,
39
    RoomSummary, SavedMentionContext, SearchCommand, SearchCoverage, SearchPage, SearchScope,
40
    SearchSession, SpaceChild, ThreadListCommand, TimelineCommand, TimelineId, VerificationAction,
41
    VerificationTarget,
42
    encryption::encryption_state,
43
    engine::{MediaService, StoreLock},
44
    model::{PushNotificationRoom, PushNotificationSender},
45
    normalise::{image_packs, member_summary, room_summaries, space_child, url_previews_allowed},
46
};
47
48
#[derive(Clone)]
49
pub struct ClientHandle {
50
    requests: mpsc::Sender<Request>,
51
    client: Client,
52
    connection: watch::Receiver<ConnectionState>,
53
    notification_client: Arc<OnceCell<NotificationClient>>,
54
    sync_service: Arc<SyncService>,
55
    media: Arc<MediaService>,
56
    spaces: Arc<OnceCell<SpaceService>>,
57
    members_checked: Arc<Mutex<HashSet<OwnedRoomId>>>,
58
    publication: Arc<PublicationRegistry>,
59
    _store_lock: Option<Arc<StoreLock>>,
60
}
61
62
impl fmt::Debug for ClientHandle {
63
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
64
        formatter
65
            .debug_struct("ClientHandle")
66
            .finish_non_exhaustive()
67
    }
68
}
69
70
/// a command's answer. drop it if you don't care, the command still runs
71
#[derive(Debug)]
72
#[must_use = "dropping it is fine but then you'll never know"]
73
pub struct Pending(oneshot::Receiver<Result<CommandOutput, Error>>);
74
75
impl Future for Pending {
76
    type Output = Result<CommandOutput, Error>;
77
78
    fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
79
        Pin::new(&mut self.0)
80
            .poll(context)
81
            .map(|result| result.unwrap_or_else(|_| Err(Error::interrupted())))
82
    }
83
}
84
85
impl ClientHandle {
86
    pub(crate) fn register_publication_mirror(&self) -> PublicationRegistration {
87
        self.publication.register_mirror()
88
    }
89
90
    /// current credentials, it holds secrets. the engine saves it for you unless the
91
    /// session was built `without_persistence`
92
    #[cfg(any(feature = "sqlite", feature = "indexeddb"))]
93
    pub fn session_record(&self) -> Result<crate::SessionRecord, crate::AccountError> {
94
        crate::account::session_record(&self.client)
95
    }
96
97
    /// the bearer token. it rotates on every refresh so ask again after a 401 rather than
98
    /// keeping it, and keep it in memory and away from all but the homeserver's media endpoints
99
    pub fn access_token(&self) -> Option<String> {
100
        self.client.access_token()
101
    }
102
103
    /// queue a command, waiting for room in the queue if there isn't any
104
    pub async fn send(&self, command: Command) -> Result<Pending, Error> {
105
        let (request, pending) = Request::new(command);
106
        self.requests
107
            .send(request)
108
            .await
109
            .map_err(|_| Error::interrupted())?;
110
        Ok(pending)
111
    }
112
113
    /// queue a command or fail with `QueueFull` right now
114
    pub fn try_send(&self, command: Command) -> Result<Pending, Error> {
115
        let (request, pending) = Request::new(command);
116
        self.requests
117
            .try_send(request)
118
            .map_err(|error| match error {
119
                mpsc::error::TrySendError::Full(_) => {
120
                    Error::new(ErrorKind::QueueFull, "the command queue is full")
121
                }
122
                mpsc::error::TrySendError::Closed(_) => Error::interrupted(),
123
            })?;
124
        Ok(pending)
125
    }
126
127
    /// queue a command and wait for its answer. timeline sends answer once the
128
    /// sdk send queue has them, delivery shows up later as the item's send state
129
    pub async fn execute(&self, command: Command) -> Result<CommandOutput, Error> {
130
        self.send(command).await?.await
131
    }
132
133
    async fn run(&self, command: Command) -> Result<(), Error> {
134
        self.execute(command).await.map(drop)
135
    }
136
137
    async fn run_for_room(&self, command: RoomCommand) -> Result<OwnedRoomId, Error> {
138
        match self.execute(Command::Room(command)).await? {
139
            CommandOutput::Room(room_id) => Ok(room_id),
140
            output => Err(Error::new(
141
                ErrorKind::Other,
142
                format!("expected a room but got {output:?}"),
143
            )),
144
        }
145
    }
146
147
    pub async fn shutdown(&self) -> Result<(), Error> {
148
        self.run(Command::Lifecycle(LifecycleCommand::Shutdown))
149
            .await
150
    }
151
152
    pub async fn logout(&self) -> Result<(), Error> {
153
        self.run(Command::Account(AccountCommand::Logout)).await
154
    }
155
156
    pub async fn delete_devices(
157
        &self,
158
        device_ids: Vec<OwnedDeviceId>,
159
        auth: Option<InteractiveAuth>,
160
    ) -> Result<InteractiveAuthOutcome, Error> {
161
        match self
162
            .run(Command::Account(AccountCommand::DeleteDevices {
163
                device_ids,
164
                auth,
165
            }))
166
            .await
167
        {
168
            Ok(()) => Ok(InteractiveAuthOutcome::Completed),
169
            Err(Error {
170
                challenge: Some(challenge),
171
                ..
172
            }) => Ok(InteractiveAuthOutcome::Challenge(*challenge)),
173
            Err(error) => Err(error),
174
        }
175
    }
176
177
    pub async fn rename_device(
178
        &self,
179
        device_id: OwnedDeviceId,
180
        display_name: impl Into<String>,
181
    ) -> Result<(), Error> {
182
        self.run(Command::Account(AccountCommand::RenameDevice {
183
            device_id,
184
            display_name: display_name.into(),
185
        }))
186
        .await
187
    }
188
189
    pub async fn set_global_account_data(
190
        &self,
191
        event_type: GlobalAccountDataEventType,
192
        content: Raw<AnyGlobalAccountDataEventContent>,
193
    ) -> Result<(), Error> {
194
        self.run(Command::Account(AccountCommand::SetAccountData {
195
            event_type,
196
            content,
197
        }))
198
        .await
199
    }
200
201
    pub async fn set_room_account_data(
202
        &self,
203
        room_id: OwnedRoomId,
204
        event_type: RoomAccountDataEventType,
205
        content: Raw<AnyRoomAccountDataEventContent>,
206
    ) -> Result<(), Error> {
207
        self.run(Command::Room(RoomCommand::SetAccountData {
208
            room_id,
209
            event_type,
210
            content,
211
        }))
212
        .await
213
    }
214
215
    pub async fn set_room_notification_mode(
216
        &self,
217
        room_id: OwnedRoomId,
218
        mode: RoomNotificationMode,
219
    ) -> Result<(), Error> {
220
        self.run(Command::Notification(NotificationCommand::SetRoomMode {
221
            room_id,
222
            mode,
223
        }))
224
        .await
225
    }
226
227
    pub async fn reset_room_notification_mode(&self, room_id: OwnedRoomId) -> Result<(), Error> {
228
        self.run(Command::Notification(NotificationCommand::ResetRoomMode(
229
            room_id,
230
        )))
231
        .await
232
    }
233
234
    pub async fn set_default_notification_mode(
235
        &self,
236
        encrypted: bool,
237
        one_to_one: bool,
238
        mode: RoomNotificationMode,
239
    ) -> Result<(), Error> {
240
        self.run(Command::Notification(NotificationCommand::SetDefaultMode {
241
            encrypted,
242
            one_to_one,
243
            mode,
244
        }))
245
        .await
246
    }
247
248
    pub async fn add_notification_keyword(&self, keyword: impl Into<String>) -> Result<(), Error> {
249
        self.run(Command::Notification(NotificationCommand::AddKeyword(
250
            keyword.into(),
251
        )))
252
        .await
253
    }
254
255
    pub async fn remove_notification_keyword(
256
        &self,
257
        keyword: impl Into<String>,
258
    ) -> Result<(), Error> {
259
        self.run(Command::Notification(NotificationCommand::RemoveKeyword(
260
            keyword.into(),
261
        )))
262
        .await
263
    }
264
265
    pub async fn open_room(&self, room_id: OwnedRoomId) -> Result<(), Error> {
266
        self.run(Command::Room(RoomCommand::Open(room_id))).await
267
    }
268
269
    pub async fn close_room(&self, room_id: OwnedRoomId) -> Result<(), Error> {
270
        self.run(Command::Room(RoomCommand::Close(room_id))).await
271
    }
272
273
    pub async fn open_thread(
274
        &self,
275
        room_id: OwnedRoomId,
276
        root_event_id: OwnedEventId,
277
    ) -> Result<(), Error> {
278
        self.run(Command::Timeline(TimelineCommand::OpenThread {
279
            room_id,
280
            root_event_id,
281
        }))
282
        .await
283
    }
284
285
    pub async fn close_thread(
286
        &self,
287
        room_id: OwnedRoomId,
288
        root_event_id: OwnedEventId,
289
    ) -> Result<(), Error> {
290
        self.run(Command::Timeline(TimelineCommand::CloseThread {
291
            room_id,
292
            root_event_id,
293
        }))
294
        .await
295
    }
296
297
    /// the room's pins as `TimelineId::Pinned`, kept current as they change. the room has to be open
298
    pub async fn open_pinned(&self, room_id: OwnedRoomId) -> Result<(), Error> {
299
        self.run(Command::Timeline(TimelineCommand::OpenPinned(room_id)))
300
            .await
301
    }
302
303
    pub async fn close_pinned(&self, room_id: OwnedRoomId) -> Result<(), Error> {
304
        self.run(Command::Timeline(TimelineCommand::ClosePinned(room_id)))
305
            .await
306
    }
307
308
    /// the room's threads, newest activity first, kept current as they gain replies.
309
    /// the room needn't be open. it starts empty, `paginate_thread_list` fills it
310
    pub async fn open_thread_list(&self, room_id: OwnedRoomId) -> Result<(), Error> {
311
        self.run(Command::ThreadList(ThreadListCommand::Open(room_id)))
312
            .await
313
    }
314
315
    pub async fn paginate_thread_list(
316
        &self,
317
        room_id: OwnedRoomId,
318
        limit: u16,
319
    ) -> Result<(), Error> {
320
        self.run(Command::ThreadList(ThreadListCommand::Paginate {
321
            room_id,
322
            limit,
323
        }))
324
        .await
325
    }
326
327
    pub async fn close_thread_list(&self, room_id: OwnedRoomId) -> Result<(), Error> {
328
        self.run(Command::ThreadList(ThreadListCommand::Close(room_id)))
329
            .await
330
    }
331
332
    /// reads the server's list so a pin made elsewhere just before isn't dropped
333
    pub async fn set_pinned(
334
        &self,
335
        room_id: OwnedRoomId,
336
        event_id: OwnedEventId,
337
        pinned: bool,
338
    ) -> Result<(), Error> {
339
        self.run(Command::Room(RoomCommand::SetPinned {
340
            room_id,
341
            event_id,
342
            pinned,
343
        }))
344
        .await
345
    }
346
347
    pub async fn resync(&self, timeline_id: TimelineId) -> Result<(), Error> {
348
        self.run(Command::Timeline(TimelineCommand::Resync { timeline_id }))
349
            .await
350
    }
351
352
    pub async fn paginate(&self, timeline_id: TimelineId, limit: u16) -> Result<(), Error> {
353
        self.run(Command::Timeline(TimelineCommand::Paginate {
354
            timeline_id,
355
            limit,
356
        }))
357
        .await
358
    }
359
360
    pub async fn cancel_history_repair(&self, room_id: OwnedRoomId) -> Result<(), Error> {
361
        self.run(Command::HistoryRepair(HistoryRepairCommand::Cancel {
362
            room_id,
363
        }))
364
        .await
365
    }
366
367
    pub async fn fill_history_gap(
368
        &self,
369
        room_id: OwnedRoomId,
370
        gap_id: ruma::OwnedTransactionId,
371
    ) -> Result<(), Error> {
372
        self.run(Command::HistoryRepair(HistoryRepairCommand::FillGap {
373
            room_id,
374
            gap_id,
375
        }))
376
        .await
377
    }
378
379
    pub async fn retry_recent_history(&self, room_id: OwnedRoomId) -> Result<(), Error> {
380
        self.run(Command::HistoryRepair(HistoryRepairCommand::RetryRecent {
381
            room_id,
382
        }))
383
        .await
384
    }
385
386
    /// close the session when the view goes, or its media stay registered
387
    pub async fn event_context(
388
        &self,
389
        room_id: &RoomId,
390
        event_id: &EventId,
391
        before_limit: u16,
392
        after_limit: u16,
393
    ) -> Result<EventContextSession, Error> {
394
        match self
395
            .execute(Command::EventContext(EventContextCommand::Fetch {
396
                room_id: room_id.to_owned(),
397
                event_id: event_id.to_owned(),
398
                before_limit,
399
                after_limit,
400
            }))
401
            .await?
402
        {
403
            CommandOutput::EventContext(session) => Ok(session),
404
            output => Err(unexpected("event context", &output)),
405
        }
406
    }
407
408
    pub async fn event_context_before(
409
        &self,
410
        context_id: &str,
411
        token: &str,
412
        limit: u16,
413
    ) -> Result<EventContextPage, Error> {
414
        self.event_context_page(EventContextCommand::Before {
415
            context_id: context_id.to_owned(),
416
            limit,
417
            token: token.to_owned(),
418
        })
419
        .await
420
    }
421
422
    pub async fn event_context_after(
423
        &self,
424
        context_id: &str,
425
        token: &str,
426
        limit: u16,
427
    ) -> Result<EventContextPage, Error> {
428
        self.event_context_page(EventContextCommand::After {
429
            context_id: context_id.to_owned(),
430
            limit,
431
            token: token.to_owned(),
432
        })
433
        .await
434
    }
435
436
    pub async fn close_event_context(&self, context_id: &str) -> Result<(), Error> {
437
        self.run(Command::EventContext(EventContextCommand::Close {
438
            context_id: context_id.to_owned(),
439
        }))
440
        .await
441
    }
442
443
    async fn event_context_page(
444
        &self,
445
        command: EventContextCommand,
446
    ) -> Result<EventContextPage, Error> {
447
        match self.execute(Command::EventContext(command)).await? {
448
            CommandOutput::EventContextPage(page) => Ok(page),
449
            output => Err(unexpected("event context page", &output)),
450
        }
451
    }
452
453
    pub async fn mentions_page(
454
        &self,
455
        cursor: Option<String>,
456
        limit: u32,
457
    ) -> Result<MentionsPage, Error> {
458
        match self
459
            .execute(Command::Mentions(MentionsCommand::Page {
460
                cursor,
461
                limit: limit.min(50) as u16,
462
            }))
463
            .await?
464
        {
465
            CommandOutput::MentionsPage(page) => Ok(page),
466
            output => Err(unexpected("mentions page", &output)),
467
        }
468
    }
469
470
    pub async fn mention_context(
471
        &self,
472
        room_id: &RoomId,
473
        event_id: &EventId,
474
    ) -> Result<SavedMentionContext, Error> {
475
        self.mention_context_command(MentionsCommand::Context(MentionKey {
476
            room_id: room_id.to_owned(),
477
            event_id: event_id.to_owned(),
478
        }))
479
        .await
480
    }
481
482
    pub async fn retry_mention_context(
483
        &self,
484
        room_id: &RoomId,
485
        event_id: &EventId,
486
    ) -> Result<SavedMentionContext, Error> {
487
        self.mention_context_command(MentionsCommand::RetryContext(MentionKey {
488
            room_id: room_id.to_owned(),
489
            event_id: event_id.to_owned(),
490
        }))
491
        .await
492
    }
493
494
    async fn mention_context_command(
495
        &self,
496
        command: MentionsCommand,
497
    ) -> Result<SavedMentionContext, Error> {
498
        match self.execute(Command::Mentions(command)).await? {
499
            CommandOutput::MentionContext(context) => Ok(context),
500
            output => Err(unexpected("mention context", &output)),
501
        }
502
    }
503
504
    pub async fn set_mentions_read(&self, keys: Vec<MentionKey>, read: bool) -> Result<(), Error> {
505
        self.run(Command::Mentions(MentionsCommand::SetRead { keys, read }))
506
            .await
507
    }
508
509
    pub async fn mark_mentions_read_through(
510
        &self,
511
        boundary: MentionsBoundary,
512
    ) -> Result<(), Error> {
513
        self.run(Command::Mentions(MentionsCommand::ReadThrough(boundary)))
514
            .await
515
    }
516
517
    pub async fn recover_mentions(&self) -> Result<(), Error> {
518
        self.run(Command::Mentions(MentionsCommand::Recover)).await
519
    }
520
521
    /// newest first, at most 50 a page. close the search when its results go, or its media
522
    /// stay registered
523
    pub async fn search_messages(
524
        &self,
525
        query: &str,
526
        scope: SearchScope,
527
        limit: u16,
528
    ) -> Result<SearchSession, Error> {
529
        match self
530
            .execute(Command::Search(SearchCommand::Search {
531
                query: query.to_owned(),
532
                scope,
533
                limit,
534
            }))
535
            .await?
536
        {
537
            CommandOutput::SearchSession(session) => Ok(session),
538
            output => Err(unexpected("search session", &output)),
539
        }
540
    }
541
542
    pub async fn search_more(
543
        &self,
544
        search_id: &str,
545
        cursor: &str,
546
        limit: u16,
547
    ) -> Result<SearchPage, Error> {
548
        match self
549
            .execute(Command::Search(SearchCommand::More {
550
                search_id: search_id.to_owned(),
551
                cursor: cursor.to_owned(),
552
                limit,
553
            }))
554
            .await?
555
        {
556
            CommandOutput::SearchPage(page) => Ok(page),
557
            output => Err(unexpected("search page", &output)),
558
        }
559
    }
560
561
    pub async fn close_search(&self, search_id: &str) -> Result<(), Error> {
562
        self.run(Command::Search(SearchCommand::Close {
563
            search_id: search_id.to_owned(),
564
        }))
565
        .await
566
    }
567
568
    pub async fn search_coverage(&self, scope: SearchScope) -> Result<SearchCoverage, Error> {
569
        match self
570
            .execute(Command::Search(SearchCommand::Coverage(scope)))
571
            .await?
572
        {
573
            CommandOutput::SearchCoverage(coverage) => Ok(coverage),
574
            output => Err(unexpected("search coverage", &output)),
575
        }
576
    }
577
578
    pub async fn send_message(
579
        &self,
580
        timeline_id: TimelineId,
581
        content: MessageContent,
582
    ) -> Result<(), Error> {
583
        self.run(Command::Timeline(TimelineCommand::Send {
584
            timeline_id,
585
            content,
586
        }))
587
        .await
588
    }
589
590
    pub async fn edit_message(
591
        &self,
592
        timeline_id: TimelineId,
593
        target: impl Into<EventRef>,
594
        content: MessageEditContent,
595
    ) -> Result<(), Error> {
596
        self.run(Command::Timeline(TimelineCommand::Edit {
597
            timeline_id,
598
            target: target.into(),
599
            content,
600
        }))
601
        .await
602
    }
603
604
    pub async fn redact(
605
        &self,
606
        timeline_id: TimelineId,
607
        target: impl Into<EventRef>,
608
        reason: Option<String>,
609
    ) -> Result<(), Error> {
610
        self.run(Command::Timeline(TimelineCommand::Redact {
611
            timeline_id,
612
            target: target.into(),
613
            reason,
614
        }))
615
        .await
616
    }
617
618
    pub async fn toggle_reaction(
619
        &self,
620
        timeline_id: TimelineId,
621
        target: impl Into<EventRef>,
622
        key: impl Into<String>,
623
        shortcode: Option<String>,
624
    ) -> Result<(), Error> {
625
        self.run(Command::Timeline(TimelineCommand::ToggleReaction {
626
            timeline_id,
627
            target: target.into(),
628
            key: key.into(),
629
            shortcode,
630
        }))
631
        .await
632
    }
633
634
    pub async fn mark_read(
635
        &self,
636
        timeline_id: TimelineId,
637
        event_id: OwnedEventId,
638
    ) -> Result<(), Error> {
639
        self.run(Command::Timeline(TimelineCommand::MarkRead {
640
            timeline_id,
641
            event_id,
642
        }))
643
        .await
644
    }
645
646
    pub async fn set_typing(&self, room_id: OwnedRoomId, typing: bool) -> Result<(), Error> {
647
        self.run(Command::Room(RoomCommand::SetTyping { room_id, typing }))
648
            .await
649
    }
650
651
    pub async fn prepare_to_send(&self, room_id: OwnedRoomId) -> Result<(), Error> {
652
        self.run(Command::Room(RoomCommand::PrepareToSend(room_id)))
653
            .await
654
    }
655
656
    pub async fn join_room(
657
        &self,
658
        room: OwnedRoomOrAliasId,
659
        via: Vec<OwnedServerName>,
660
    ) -> Result<OwnedRoomId, Error> {
661
        self.run_for_room(RoomCommand::Join { room, via }).await
662
    }
663
664
    pub async fn leave_room(&self, room_id: OwnedRoomId) -> Result<(), Error> {
665
        self.run(Command::Room(RoomCommand::Leave(room_id))).await
666
    }
667
668
    pub async fn forget_room(&self, room_id: OwnedRoomId) -> Result<(), Error> {
669
        self.run(Command::Room(RoomCommand::Forget(room_id))).await
670
    }
671
672
    pub async fn accept_invite(&self, room_id: OwnedRoomId) -> Result<(), Error> {
673
        self.run(Command::Room(RoomCommand::AcceptInvite(room_id)))
674
            .await
675
    }
676
677
    pub async fn reject_invite(&self, room_id: OwnedRoomId) -> Result<(), Error> {
678
        self.run(Command::Room(RoomCommand::RejectInvite(room_id)))
679
            .await
680
    }
681
682
    pub async fn invite_user(
683
        &self,
684
        room_id: OwnedRoomId,
685
        user_id: OwnedUserId,
686
    ) -> Result<(), Error> {
687
        self.run(Command::Room(RoomCommand::InviteUser { room_id, user_id }))
688
            .await
689
    }
690
691
    pub async fn kick_user(
692
        &self,
693
        room_id: OwnedRoomId,
694
        user_id: OwnedUserId,
695
        reason: Option<String>,
696
    ) -> Result<(), Error> {
697
        self.run(Command::Room(RoomCommand::KickUser {
698
            room_id,
699
            user_id,
700
            reason,
701
        }))
702
        .await
703
    }
704
705
    pub async fn ban_user(
706
        &self,
707
        room_id: OwnedRoomId,
708
        user_id: OwnedUserId,
709
        reason: Option<String>,
710
    ) -> Result<(), Error> {
711
        self.run(Command::Room(RoomCommand::BanUser {
712
            room_id,
713
            user_id,
714
            reason,
715
        }))
716
        .await
717
    }
718
719
    pub async fn unban_user(
720
        &self,
721
        room_id: OwnedRoomId,
722
        user_id: OwnedUserId,
723
        reason: Option<String>,
724
    ) -> Result<(), Error> {
725
        self.run(Command::Room(RoomCommand::UnbanUser {
726
            room_id,
727
            user_id,
728
            reason,
729
        }))
730
        .await
731
    }
732
733
    pub async fn set_power_levels(
734
        &self,
735
        room_id: OwnedRoomId,
736
        changes: PowerLevelChanges,
737
    ) -> Result<(), Error> {
738
        self.run(Command::Room(RoomCommand::SetPowerLevels {
739
            room_id,
740
            changes,
741
        }))
742
        .await
743
    }
744
745
    pub async fn set_user_power_level(
746
        &self,
747
        room_id: OwnedRoomId,
748
        user_id: OwnedUserId,
749
        level: i64,
750
    ) -> Result<(), Error> {
751
        self.run(Command::Room(RoomCommand::SetUserPowerLevel {
752
            room_id,
753
            user_id,
754
            level,
755
        }))
756
        .await
757
    }
758
759
    pub async fn create_room(&self, options: CreateRoomOptions) -> Result<OwnedRoomId, Error> {
760
        self.run_for_room(RoomCommand::Create(options)).await
761
    }
762
763
    /// hands back the existing dm with them if there is one
764
    pub async fn create_direct(&self, user_id: OwnedUserId) -> Result<OwnedRoomId, Error> {
765
        self.run_for_room(RoomCommand::CreateDirect(user_id)).await
766
    }
767
768
    pub async fn cancel_send(
769
        &self,
770
        room_id: OwnedRoomId,
771
        transaction_id: OwnedTransactionId,
772
    ) -> Result<(), Error> {
773
        self.run(Command::Room(RoomCommand::CancelSend {
774
            room_id,
775
            transaction_id,
776
        }))
777
        .await
778
    }
779
780
    pub async fn retry_send(
781
        &self,
782
        room_id: OwnedRoomId,
783
        transaction_id: OwnedTransactionId,
784
    ) -> Result<(), Error> {
785
        self.run(Command::Room(RoomCommand::RetrySend {
786
            room_id,
787
            transaction_id,
788
        }))
789
        .await
790
    }
791
792
    pub async fn upload(&self, upload: AttachmentUpload) -> Result<(), Error> {
793
        self.run(Command::Media(MediaCommand::Upload(upload))).await
794
    }
795
796
    pub async fn recover(&self, recovery_key: impl Into<String>) -> Result<(), Error> {
797
        self.run(Command::Encryption(EncryptionCommand::Recover(
798
            recovery_key.into(),
799
        )))
800
        .await
801
    }
802
803
    pub async fn create_key_backup(&self) -> Result<(), Error> {
804
        self.run(Command::Encryption(EncryptionCommand::CreateKeyBackup))
805
            .await
806
    }
807
808
    pub async fn enable_key_backup(&self) -> Result<(), Error> {
809
        self.run(Command::Encryption(EncryptionCommand::EnableKeyBackup))
810
            .await
811
    }
812
813
    pub async fn disable_key_backup(&self, delete_from_server: bool) -> Result<(), Error> {
814
        self.run(Command::Encryption(EncryptionCommand::DisableKeyBackup {
815
            delete_from_server,
816
        }))
817
        .await
818
    }
819
820
    pub async fn recover_key_backup(&self, recovery_key: impl Into<String>) -> Result<(), Error> {
821
        self.run(Command::Encryption(EncryptionCommand::RecoverKeyBackup(
822
            recovery_key.into(),
823
        )))
824
        .await
825
    }
826
827
    pub async fn start_verification(&self, target: VerificationTarget) -> Result<(), Error> {
828
        self.run(Command::Encryption(EncryptionCommand::StartVerification(
829
            target,
830
        )))
831
        .await
832
    }
833
834
    pub async fn verify(&self, action: VerificationAction) -> Result<(), Error> {
835
        self.run(Command::Encryption(EncryptionCommand::Verify(action)))
836
            .await
837
    }
838
839
    /// bytes for an avatar, or for media a retained timeline showed you. concurrent asks share
840
    /// one download
841
    pub async fn media(&self, media_id: &MediaId, size: MediaSize) -> Result<Media, Error> {
842
        self.media.timeline_media(media_id, size).await
843
    }
844
845
    /// where `media` would fetch from, for a host streaming big files itself. the byte cap
846
    /// doesn't apply since nothing is buffered
847
    pub async fn media_source(
848
        &self,
849
        media_id: &MediaId,
850
        size: MediaSize,
851
    ) -> Result<MediaLocation, Error> {
852
        self.media.media_location(media_id, size).await
853
    }
854
855
    /// the space graph builds on first use and then keeps itself current
856
    async fn spaces(&self) -> &SpaceService {
857
        self.spaces
858
            .get_or_init(|| SpaceService::new(self.client.clone()))
859
            .await
860
    }
861
862
    pub async fn rooms(&self) -> Vec<RoomSummary> {
863
        room_summaries(&self.client, self.spaces().await).await
864
    }
865
866
    pub async fn image_packs(&self) -> Result<ImagePacks, Error> {
867
        image_packs(&self.client).await
868
    }
869
870
    /// the homeserver's preview of a page, `None` when it has none. the homeserver sees every
871
    /// url asked about, so a host decides whether encrypted rooms ask at all
872
    pub async fn url_preview(&self, url: &str) -> Result<Option<LinkPreview>, Error> {
873
        self.media.url_preview(url).await
874
    }
875
876
    /// whether the room and the user's settings let link previews show here
877
    pub async fn url_previews_allowed(&self, room_id: &RoomId) -> Result<bool, Error> {
878
        url_previews_allowed(&self.room(room_id)?).await
879
    }
880
881
    /// browse a space the way the server sees it, rooms you haven't joined included
882
    pub async fn space_hierarchy(&self, space_id: OwnedRoomId) -> SpaceHierarchy {
883
        SpaceHierarchy(SpaceRoomList::new(self.client.clone(), space_id).await)
884
    }
885
886
    pub async fn own_profile(&self) -> Result<Profile, Error> {
887
        let user_id = self
888
            .client
889
            .user_id()
890
            .ok_or_else(|| Error::new(ErrorKind::Unauthenticated, "the client is not logged in"))?
891
            .to_owned();
892
        let response = self
893
            .client
894
            .account()
895
            .fetch_user_profile()
896
            .await
897
            .map_err(|source| Error::from_sdk("fetching the profile failed", source))?;
898
        profile(user_id, &response)
899
    }
900
901
    pub async fn user_profile(&self, user_id: &UserId) -> Result<Profile, Error> {
902
        let response = self
903
            .client
904
            .account()
905
            .fetch_user_profile_of(user_id)
906
            .await
907
            .map_err(|source| Error::from_sdk("fetching the profile failed", source))?;
908
        profile(user_id.to_owned(), &response)
909
    }
910
911
    pub async fn set_display_name(&self, name: Option<String>) -> Result<(), Error> {
912
        self.run(Command::Account(AccountCommand::SetDisplayName(name)))
913
            .await
914
    }
915
916
    pub async fn set_avatar(&self, avatar: Option<OwnedMxcUri>) -> Result<(), Error> {
917
        self.run(Command::Account(AccountCommand::SetAvatar(avatar)))
918
            .await
919
    }
920
921
    pub async fn upload_avatar(
922
        &self,
923
        mimetype: impl Into<String>,
924
        bytes: Vec<u8>,
925
    ) -> Result<(), Error> {
926
        self.run(Command::Account(AccountCommand::UploadAvatar {
927
            mimetype: mimetype.into(),
928
            bytes,
929
        }))
930
        .await
931
    }
932
933
    /// unencrypted, for room avatars and anything else that only needs the uri
934
    pub async fn upload_media(
935
        &self,
936
        mimetype: impl Into<String>,
937
        bytes: Vec<u8>,
938
    ) -> Result<OwnedMxcUri, Error> {
939
        let command = Command::Account(AccountCommand::UploadMedia {
940
            mimetype: mimetype.into(),
941
            bytes,
942
        });
943
        match self.execute(command).await? {
944
            CommandOutput::Mxc(uri) => Ok(uri),
945
            output => Err(Error::new(
946
                ErrorKind::Other,
947
                format!("expected an mxc but got {output:?}"),
948
            )),
949
        }
950
    }
951
952
    pub async fn ignore_user(&self, user_id: OwnedUserId) -> Result<(), Error> {
953
        self.run(Command::Account(AccountCommand::IgnoreUser(user_id)))
954
            .await
955
    }
956
957
    pub async fn unignore_user(&self, user_id: OwnedUserId) -> Result<(), Error> {
958
        self.run(Command::Account(AccountCommand::UnignoreUser(user_id)))
959
            .await
960
    }
961
962
    /// writes msc3230 orders so these spaces sort in exactly this sequence, touching as few as it can
963
    pub async fn reorder_spaces(&self, order: Vec<OwnedRoomId>) -> Result<(), Error> {
964
        self.run(Command::Account(AccountCommand::ReorderSpaces(order)))
965
            .await
966
    }
967
968
    /// adding m.favourite drops m.lowpriority, the way Element does
969
    pub async fn set_favourite(&self, room_id: OwnedRoomId, favourite: bool) -> Result<(), Error> {
970
        self.run(Command::Room(RoomCommand::SetFavourite {
971
            room_id,
972
            favourite,
973
        }))
974
        .await
975
    }
976
977
    /// None goes back to your global name
978
    pub async fn set_room_display_name(
979
        &self,
980
        room_id: OwnedRoomId,
981
        name: Option<String>,
982
    ) -> Result<(), Error> {
983
        self.run(Command::Room(RoomCommand::SetOwnDisplayName {
984
            room_id,
985
            name,
986
        }))
987
        .await
988
    }
989
990
    /// None goes back to your global avatar
991
    pub async fn set_room_avatar(
992
        &self,
993
        room_id: OwnedRoomId,
994
        avatar: Option<OwnedMxcUri>,
995
    ) -> Result<(), Error> {
996
        self.run(Command::Room(RoomCommand::SetOwnAvatar { room_id, avatar }))
997
            .await
998
    }
999
1000
    /// muting drops them below what sending a message takes, unmuting puts a muted user back
1001
    /// at users_default and leaves anyone else alone. `ErrorKind::Forbidden` if you can't
1002
    pub async fn mute_user(
1003
        &self,
1004
        room_id: OwnedRoomId,
1005
        user_id: OwnedUserId,
1006
        muted: bool,
1007
    ) -> Result<(), Error> {
1008
        self.run(Command::Room(RoomCommand::MuteUser {
1009
            room_id,
1010
            user_id,
1011
            muted,
1012
        }))
1013
        .await
1014
    }
1015
1016
    /// body defaults to the shortcode
1017
    pub async fn send_sticker(
1018
        &self,
1019
        timeline_id: TimelineId,
1020
        pack_id: String,
1021
        shortcode: String,
1022
    ) -> Result<(), Error> {
1023
        self.run(Command::Pack(PackCommand::SendSticker {
1024
            timeline_id,
1025
            pack_id,
1026
            shortcode,
1027
        }))
1028
        .await
1029
    }
1030
1031
    /// fails if the state key already holds a pack
1032
    pub async fn create_room_pack(
1033
        &self,
1034
        room_id: OwnedRoomId,
1035
        state_key: String,
1036
        display_name: String,
1037
    ) -> Result<(), Error> {
1038
        self.run(Command::Pack(PackCommand::CreateRoomPack {
1039
            room_id,
1040
            state_key,
1041
            display_name,
1042
        }))
1043
        .await
1044
    }
1045
1046
    pub async fn delete_pack(&self, pack: ImagePackSource) -> Result<(), Error> {
1047
        self.run(Command::Pack(PackCommand::Delete(pack))).await
1048
    }
1049
1050
    pub async fn set_pack_meta(
1051
        &self,
1052
        pack: ImagePackSource,
1053
        display_name: Patch<String>,
1054
        avatar: Patch<OwnedMxcUri>,
1055
        usage: Patch<Vec<PackUsage>>,
1056
    ) -> Result<(), Error> {
1057
        self.run(Command::Pack(PackCommand::SetMeta {
1058
            pack,
1059
            display_name,
1060
            avatar,
1061
            usage,
1062
        }))
1063
        .await
1064
    }
1065
1066
    /// adds or replaces by shortcode. a replaced image keeps its info unless the url changed
1067
    pub async fn put_pack_image(
1068
        &self,
1069
        pack: ImagePackSource,
1070
        shortcode: String,
1071
        mxc: OwnedMxcUri,
1072
        body: Option<String>,
1073
        usage: Option<Vec<PackUsage>>,
1074
        info: Option<PackImageInfo>,
1075
    ) -> Result<(), Error> {
1076
        self.run(Command::Pack(PackCommand::PutImage {
1077
            pack,
1078
            shortcode,
1079
            mxc,
1080
            body,
1081
            usage,
1082
            info,
1083
        }))
1084
        .await
1085
    }
1086
1087
    pub async fn rename_pack_image(
1088
        &self,
1089
        pack: ImagePackSource,
1090
        from: String,
1091
        to: String,
1092
    ) -> Result<(), Error> {
1093
        self.run(Command::Pack(PackCommand::RenameImage { pack, from, to }))
1094
            .await
1095
    }
1096
1097
    pub async fn remove_pack_image(
1098
        &self,
1099
        pack: ImagePackSource,
1100
        shortcode: String,
1101
    ) -> Result<(), Error> {
1102
        self.run(Command::Pack(PackCommand::RemoveImage { pack, shortcode }))
1103
            .await
1104
    }
1105
1106
    pub async fn set_pack_enabled_everywhere(
1107
        &self,
1108
        room_id: OwnedRoomId,
1109
        state_key: String,
1110
        enabled: bool,
1111
    ) -> Result<(), Error> {
1112
        self.run(Command::Pack(PackCommand::SetEnabledEverywhere {
1113
            room_id,
1114
            state_key,
1115
            enabled,
1116
        }))
1117
        .await
1118
    }
1119
1120
    /// the same uri when it already lives on your homeserver
1121
    pub async fn rehost_media(&self, mxc: OwnedMxcUri) -> Result<OwnedMxcUri, Error> {
1122
        match self
1123
            .execute(Command::Pack(PackCommand::Rehost(mxc)))
1124
            .await?
1125
        {
1126
            CommandOutput::Mxc(uri) => Ok(uri),
1127
            output => Err(unexpected("an mxc", &output)),
1128
        }
1129
    }
1130
1131
    /// hands back the shortcode it ended up under. `usage` overrides what the image had
1132
    pub async fn clone_pack_image(
1133
        &self,
1134
        from_pack: String,
1135
        shortcode: String,
1136
        to: ImagePackSource,
1137
        usage: Option<Vec<PackUsage>>,
1138
    ) -> Result<String, Error> {
1139
        let (mut shortcodes, _) = self
1140
            .run_clone(PackCommand::CloneImage {
1141
                from_pack,
1142
                shortcode,
1143
                to,
1144
                usage,
1145
            })
1146
            .await?;
1147
        shortcodes
1148
            .pop()
1149
            .ok_or_else(|| unexpected("a shortcode", &CommandOutput::Done))
1150
    }
1151
1152
    /// hands back the shortcode it ended up under
1153
    pub async fn clone_sticker(
1154
        &self,
1155
        room_id: OwnedRoomId,
1156
        event_id: OwnedEventId,
1157
        to: ImagePackSource,
1158
        shortcode: String,
1159
        usage: Option<Vec<PackUsage>>,
1160
    ) -> Result<String, Error> {
1161
        let (mut shortcodes, _) = self
1162
            .run_clone(PackCommand::CloneSticker {
1163
                room_id,
1164
                event_id,
1165
                to,
1166
                shortcode,
1167
                usage,
1168
            })
1169
            .await?;
1170
        shortcodes
1171
            .pop()
1172
            .ok_or_else(|| unexpected("a shortcode", &CommandOutput::Done))
1173
    }
1174
1175
    /// hands back the shortcodes that couldn't be fetched, everything else is written
1176
    pub async fn clone_pack(
1177
        &self,
1178
        from_pack: String,
1179
        to: ImagePackSource,
1180
        display_name: Option<String>,
1181
        usage: Option<Vec<PackUsage>>,
1182
    ) -> Result<Vec<String>, Error> {
1183
        let (_, skipped) = self
1184
            .run_clone(PackCommand::ClonePack {
1185
                from_pack,
1186
                to,
1187
                display_name,
1188
                usage,
1189
            })
1190
            .await?;
1191
        Ok(skipped)
1192
    }
1193
1194
    async fn run_clone(&self, command: PackCommand) -> Result<(Vec<String>, Vec<String>), Error> {
1195
        match self.execute(Command::Pack(command)).await? {
1196
            CommandOutput::Cloned {
1197
                shortcodes,
1198
                skipped,
1199
            } => Ok((shortcodes, skipped)),
1200
            output => Err(unexpected("a clone", &output)),
1201
        }
1202
    }
1203
1204
    pub async fn rooms_filtered(&self, filter: &RoomListFilter) -> Vec<RoomSummary> {
1205
        let matcher = filter.matcher();
1206
        self.rooms()
1207
            .await
1208
            .into_iter()
1209
            .filter(|room| matcher.matches(room))
1210
            .collect()
1211
    }
1212
1213
    pub async fn devices(&self) -> Result<Vec<OwnDevice>, Error> {
1214
        let current_device_id = self.client.device_id();
1215
        Ok(self
1216
            .client
1217
            .devices()
1218
            .await
1219
            .map_err(|source| Error::from_http("listing devices failed", source))?
1220
            .devices
1221
            .into_iter()
1222
            .map(|device| OwnDevice {
1223
                current: current_device_id == Some(device.device_id.as_ref()),
1224
                device_id: device.device_id,
1225
                display_name: device.display_name,
1226
                last_seen_ip: device.last_seen_ip,
1227
                last_seen_timestamp_ms: device.last_seen_ts.map(|timestamp| timestamp.get().into()),
1228
            })
1229
            .collect())
1230
    }
1231
1232
    fn room(&self, room_id: &RoomId) -> Result<matrix_sdk::Room, Error> {
1233
        self.client
1234
            .get_room(room_id)
1235
            .ok_or_else(Error::room_unknown)
1236
    }
1237
1238
    pub async fn room_notification_settings(
1239
        &self,
1240
        room_id: &RoomId,
1241
    ) -> Result<Option<RoomNotificationSettings>, Error> {
1242
        let room = self.room(room_id)?;
1243
        let custom = room.user_defined_notification_mode().await;
1244
        let mode = match custom {
1245
            Some(mode) => mode,
1246
            None => match room.notification_mode().await {
1247
                Some(mode) => mode,
1248
                None => return Ok(None),
1249
            },
1250
        };
1251
        Ok(Some(RoomNotificationSettings {
1252
            mode: crate::normalise::notification_mode(mode),
1253
            custom: custom.is_some(),
1254
        }))
1255
    }
1256
1257
    pub async fn notification_keywords(&self) -> Vec<String> {
1258
        self.client
1259
            .notification_settings()
1260
            .await
1261
            .enabled_keywords()
1262
            .await
1263
            .into_iter()
1264
            .collect()
1265
    }
1266
1267
    pub async fn resolve_push_notification(
1268
        &self,
1269
        room_id: &RoomId,
1270
        event_id: &EventId,
1271
    ) -> Result<PushNotificationStatus, Error> {
1272
        let notification_failed = |source| {
1273
            Error::with_source(
1274
                ErrorKind::Other,
1275
                "resolving the push notification failed",
1276
                source,
1277
            )
1278
        };
1279
        let client = self
1280
            .notification_client
1281
            .get_or_try_init(|| async {
1282
                NotificationClient::new(
1283
                    self.client.clone(),
1284
                    NotificationProcessSetup::SingleProcess {
1285
                        sync_service: self.sync_service.clone(),
1286
                    },
1287
                )
1288
                .await
1289
            })
1290
            .await
1291
            .map_err(notification_failed)?;
1292
        let status = client
1293
            .get_notification(room_id, event_id)
1294
            .await
1295
            .map_err(notification_failed)?;
1296
        Ok(normalise_push_notification(room_id, event_id, status))
1297
    }
1298
1299
    pub async fn members(
1300
        &self,
1301
        room_id: &RoomId,
1302
        filter: MemberFilter,
1303
    ) -> Result<Vec<MemberSummary>, Error> {
1304
        let room = self.room(room_id)?;
1305
        // stores have been seen with members_synced persisted over a partial
1306
        // roster, and the sdk never asks /members again once it's set
1307
        if self
1308
            .members_checked
1309
            .lock()
1310
            .unwrap()
1311
            .insert(room_id.to_owned())
1312
        {
1313
            room.mark_members_missing();
1314
        }
1315
        list_members(&room, filter).await
1316
    }
1317
1318
    /// drop the cached roster for a room and fetch /members again
1319
    pub async fn refresh_members(
1320
        &self,
1321
        room_id: &RoomId,
1322
        filter: MemberFilter,
1323
    ) -> Result<Vec<MemberSummary>, Error> {
1324
        let room = self.room(room_id)?;
1325
        room.mark_members_missing();
1326
        self.members_checked
1327
            .lock()
1328
            .unwrap()
1329
            .insert(room_id.to_owned());
1330
        list_members(&room, filter).await
1331
    }
1332
1333
    pub async fn room_power_levels(&self, room_id: &RoomId) -> Result<RoomPowerLevels, Error> {
1334
        let levels = self
1335
            .room(room_id)?
1336
            .power_levels()
1337
            .await
1338
            .map_err(|source| Error::from_sdk("reading power levels failed", source.into()))?;
1339
        Ok(RoomPowerLevels {
1340
            ban: levels.ban.into(),
1341
            invite: levels.invite.into(),
1342
            kick: levels.kick.into(),
1343
            redact: levels.redact.into(),
1344
            events_default: levels.events_default.into(),
1345
            state_default: levels.state_default.into(),
1346
            users_default: levels.users_default.into(),
1347
            room_notification: levels.notifications.room.into(),
1348
            users: levels
1349
                .users
1350
                .into_iter()
1351
                .map(|(user_id, level)| (user_id, level.into()))
1352
                .collect(),
1353
            events: levels
1354
                .events
1355
                .into_iter()
1356
                .map(|(event_type, level)| (event_type.to_string(), level.into()))
1357
                .collect(),
1358
            creators: levels
1359
                .rules
1360
                .privileged_creators
1361
                .into_iter()
1362
                .flatten()
1363
                .collect(),
1364
        })
1365
    }
1366
1367
    pub async fn pending_send_ids(
1368
        &self,
1369
        room_id: &RoomId,
1370
    ) -> Result<Vec<OwnedTransactionId>, Error> {
1371
        let (echoes, _) = self
1372
            .room(room_id)?
1373
            .send_queue()
1374
            .subscribe()
1375
            .await
1376
            .map_err(|source| {
1377
                Error::with_source(ErrorKind::Store, "reading the send queue failed", source)
1378
            })?;
1379
        Ok(echoes
1380
            .into_iter()
1381
            .filter(|echo| {
1382
                matches!(
1383
                    echo.content,
1384
                    matrix_sdk::send_queue::LocalEchoContent::Event { .. }
1385
                )
1386
            })
1387
            .map(|echo| echo.transaction_id)
1388
            .collect())
1389
    }
1390
1391
    pub async fn global_account_data(
1392
        &self,
1393
        event_type: GlobalAccountDataEventType,
1394
    ) -> Result<Option<Raw<AnyGlobalAccountDataEventContent>>, Error> {
1395
        self.client
1396
            .account()
1397
            .account_data_raw(event_type)
1398
            .await
1399
            .map_err(|source| Error::from_sdk("reading account data failed", source))
1400
    }
1401
1402
    pub async fn room_account_data(
1403
        &self,
1404
        room_id: &RoomId,
1405
        event_type: RoomAccountDataEventType,
1406
    ) -> Result<Option<Raw<AnyRoomAccountDataEvent>>, Error> {
1407
        self.room(room_id)?
1408
            .account_data(event_type)
1409
            .await
1410
            .map_err(|source| Error::from_sdk("reading room account data failed", source))
1411
    }
1412
1413
    #[must_use]
1414
    pub fn connection_state(&self) -> watch::Receiver<ConnectionState> {
1415
        self.connection.clone()
1416
    }
1417
1418
    #[must_use]
1419
    pub fn encryption_state(&self) -> Option<EncryptionState> {
1420
        let device_id = self.client.device_id()?.to_owned();
1421
        let encryption = self.client.encryption();
1422
        Some(encryption_state(
1423
            device_id,
1424
            encryption.recovery().state(),
1425
            encryption.verification_state().get(),
1426
            encryption.backups().state(),
1427
        ))
1428
    }
1429
}
1430
1431
/// one space's hierarchy, a page at a time. hold on to it while you browse, it remembers where it got to
1432
pub struct SpaceHierarchy(SpaceRoomList);
1433
1434
impl fmt::Debug for SpaceHierarchy {
1435
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1436
        formatter
1437
            .debug_struct("SpaceHierarchy")
1438
            .finish_non_exhaustive()
1439
    }
1440
}
1441
1442
impl SpaceHierarchy {
1443
    /// fetches the next page. a no-op once the end is reached or while a page is in flight
1444
    pub async fn paginate(&self) -> Result<(), Error> {
1445
        self.0.paginate().await.map_err(|source| {
1446
            Error::with_source(
1447
                ErrorKind::Server,
1448
                "fetching the space hierarchy failed",
1449
                source,
1450
            )
1451
        })
1452
    }
1453
1454
    /// everything fetched so far, the space itself excluded
1455
    pub async fn rooms(&self) -> Vec<SpaceChild> {
1456
        self.0.rooms().await.into_iter().map(space_child).collect()
1457
    }
1458
1459
    #[must_use]
1460
    pub fn end_reached(&self) -> bool {
1461
        matches!(
1462
            self.0.pagination_state(),
1463
            SpaceRoomListPaginationState::Idle { end_reached: true }
1464
        )
1465
    }
1466
}
1467
1468
fn profile(
1469
    user_id: OwnedUserId,
1470
    response: &ruma::api::client::profile::get_profile::v3::Response,
1471
) -> Result<Profile, Error> {
1472
    use ruma::api::client::profile::{AvatarUrl, DisplayName};
1473
    let malformed = |source| {
1474
        Error::with_source(
1475
            ErrorKind::Server,
1476
            "the server sent a malformed profile",
1477
            source,
1478
        )
1479
    };
1480
    Ok(Profile {
1481
        user_id,
1482
        display_name: response.get_static::<DisplayName>().map_err(malformed)?,
1483
        avatar: response
1484
            .get_static::<AvatarUrl>()
1485
            .map_err(malformed)?
1486
            .as_deref()
1487
            .map(MediaId::plain),
1488
    })
1489
}
1490
1491
#[derive(Debug)]
1492
pub(crate) struct Request {
1493
    pub(crate) command: Command,
1494
    pub(crate) reply: Responder,
1495
}
1496
1497
impl Request {
1498
    fn new(command: Command) -> (Self, Pending) {
1499
        let (reply, pending) = oneshot::channel();
1500
        (
1501
            Self {
1502
                command,
1503
                reply: Responder(reply),
1504
            },
1505
            Pending(pending),
1506
        )
1507
    }
1508
}
1509
1510
/// whoever holds this owes the caller an answer. dropping it answers `Interrupted`
1511
#[derive(Debug)]
1512
pub(crate) struct Responder(oneshot::Sender<Result<CommandOutput, Error>>);
1513
1514
impl Responder {
1515
    pub(crate) fn channel() -> (Self, Pending) {
1516
        let (reply, pending) = oneshot::channel();
1517
        (Self(reply), Pending(pending))
1518
    }
1519
1520
    pub(crate) fn send(self, result: Result<CommandOutput, Error>) {
1521
        if let Err(error) = &result {
1522
            tracing::debug!(%error, kind = ?error.kind, "command failed");
1523
        }
1524
        let _ = self.0.send(result);
1525
    }
1526
1527
    pub(crate) fn done(self, result: Result<(), Error>) {
1528
        self.send(result.map(|()| CommandOutput::Done));
1529
    }
1530
}
1531
1532
#[derive(Debug)]
1533
pub struct EventStream {
1534
    events: mpsc::Receiver<Event>,
1535
}
1536
1537
impl EventStream {
1538
    pub async fn recv(&mut self) -> Option<Event> {
1539
        self.events.recv().await
1540
    }
1541
1542
    pub fn try_recv(&mut self) -> Result<Event, mpsc::error::TryRecvError> {
1543
        self.events.try_recv()
1544
    }
1545
}
1546
1547
impl futures_util::Stream for EventStream {
1548
    type Item = Event;
1549
1550
    fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1551
        self.events.poll_recv(context)
1552
    }
1553
}
1554
1555
#[derive(Debug)]
1556
pub(crate) struct DriverPort {
1557
    requests: mpsc::Receiver<Request>,
1558
    events: mpsc::Sender<Event>,
1559
    connection: watch::Sender<ConnectionState>,
1560
    publication: Arc<PublicationRegistry>,
1561
}
1562
1563
#[doc(hidden)]
1564
#[derive(Clone, Debug)]
1565
pub struct PublicationAck(Arc<PublicationAckInner>);
1566
1567
#[derive(Debug)]
1568
struct PublicationAckInner {
1569
    sender: Mutex<Option<oneshot::Sender<bool>>>,
1570
}
1571
1572
impl PartialEq for PublicationAck {
1573
    fn eq(&self, other: &Self) -> bool {
1574
        Arc::ptr_eq(&self.0, &other.0)
1575
    }
1576
}
1577
1578
impl Eq for PublicationAck {}
1579
1580
impl PublicationAck {
1581
    pub(crate) fn complete(&self, published: bool) {
1582
        let sender = self
1583
            .0
1584
            .sender
1585
            .lock()
1586
            .unwrap_or_else(|error| error.into_inner())
1587
            .take();
1588
        if let Some(sender) = sender {
1589
            let _ = sender.send(published);
1590
        }
1591
    }
1592
}
1593
1594
#[derive(Debug, Default)]
1595
struct PublicationRegistry {
1596
    state: Mutex<PublicationRegistryState>,
1597
}
1598
1599
#[derive(Debug, Default)]
1600
struct PublicationRegistryState {
1601
    mirrors: usize,
1602
    pending: Vec<Weak<PublicationAckInner>>,
1603
}
1604
1605
impl PublicationRegistry {
1606
    fn register_mirror(self: &Arc<Self>) -> PublicationRegistration {
1607
        self.state
1608
            .lock()
1609
            .unwrap_or_else(|error| error.into_inner())
1610
            .mirrors += 1;
1611
        PublicationRegistration {
1612
            registry: self.clone(),
1613
        }
1614
    }
1615
1616
    fn acknowledgement(&self) -> Option<(PublicationAck, oneshot::Receiver<bool>)> {
1617
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
1618
        if state.mirrors == 0 {
1619
            return None;
1620
        }
1621
        state.pending.retain(|pending| pending.strong_count() > 0);
1622
        let (sender, receiver) = oneshot::channel();
1623
        let acknowledgement = PublicationAck(Arc::new(PublicationAckInner {
1624
            sender: Mutex::new(Some(sender)),
1625
        }));
1626
        state.pending.push(Arc::downgrade(&acknowledgement.0));
1627
        Some((acknowledgement, receiver))
1628
    }
1629
}
1630
1631
pub(crate) struct PublicationRegistration {
1632
    registry: Arc<PublicationRegistry>,
1633
}
1634
1635
impl Drop for PublicationRegistration {
1636
    fn drop(&mut self) {
1637
        let pending = {
1638
            let mut state = self
1639
                .registry
1640
                .state
1641
                .lock()
1642
                .unwrap_or_else(|error| error.into_inner());
1643
            state.mirrors -= 1;
1644
            if state.mirrors == 0 {
1645
                std::mem::take(&mut state.pending)
1646
            } else {
1647
                Vec::new()
1648
            }
1649
        };
1650
        for acknowledgement in pending.into_iter().filter_map(|ack| ack.upgrade()) {
1651
            PublicationAck(acknowledgement).complete(false);
1652
        }
1653
    }
1654
}
1655
1656
#[derive(Clone, Debug)]
1657
pub(crate) struct EventSender {
1658
    events: mpsc::Sender<Event>,
1659
    publication: Arc<PublicationRegistry>,
1660
}
1661
1662
impl EventSender {
1663
    #[cfg(all(test, feature = "sqlite"))]
1664
    pub(crate) fn detached(capacity: usize) -> (Self, mpsc::Receiver<Event>) {
1665
        let (events, receiver) = mpsc::channel(capacity);
1666
        let sender = Self {
1667
            events,
1668
            publication: Arc::new(PublicationRegistry::default()),
1669
        };
1670
        (sender, receiver)
1671
    }
1672
1673
    pub(crate) async fn send(&self, event: Event) -> Result<(), SendEventError> {
1674
        self.events.send(event).await.map_err(|_| SendEventError)
1675
    }
1676
1677
    pub(crate) async fn publish_barrier(&self) -> Result<(), SendEventError> {
1678
        let Some((acknowledgement, published)) = self.publication.acknowledgement() else {
1679
            return Ok(());
1680
        };
1681
        if let Err(error) = self
1682
            .send(Event::PublicationBarrier {
1683
                acknowledgement: Some(acknowledgement.clone()),
1684
            })
1685
            .await
1686
        {
1687
            acknowledgement.complete(false);
1688
            return Err(error);
1689
        }
1690
        drop(acknowledgement);
1691
        match published.await {
1692
            Ok(true) => Ok(()),
1693
            Ok(false) | Err(_) => Err(SendEventError),
1694
        }
1695
    }
1696
1697
    pub(crate) async fn reserve(&self) -> Result<mpsc::Permit<'_, Event>, SendEventError> {
1698
        self.events.reserve().await.map_err(|_| SendEventError)
1699
    }
1700
1701
    /// resolves once every `EventStream` is gone
1702
    pub(crate) async fn closed(&self) {
1703
        self.events.closed().await;
1704
    }
1705
}
1706
1707
impl DriverPort {
1708
    pub(crate) fn event_sender(&self) -> EventSender {
1709
        EventSender {
1710
            events: self.events.clone(),
1711
            publication: self.publication.clone(),
1712
        }
1713
    }
1714
1715
    pub(crate) fn connection_sender(&self) -> watch::Sender<ConnectionState> {
1716
        self.connection.clone()
1717
    }
1718
1719
    pub(crate) async fn recv(&mut self) -> Option<Request> {
1720
        self.requests.recv().await
1721
    }
1722
1723
    pub(crate) fn try_recv(&mut self) -> Option<Request> {
1724
        self.requests.try_recv().ok()
1725
    }
1726
1727
    pub(crate) fn close(&mut self) {
1728
        self.requests.close();
1729
    }
1730
}
1731
1732
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
1733
#[error("the event receiver has closed")]
1734
pub(crate) struct SendEventError;
1735
1736
#[must_use]
1737
pub(crate) fn transport_pair(
1738
    client: Client,
1739
    sync_service: Arc<SyncService>,
1740
    media: Arc<MediaService>,
1741
    store_lock: Option<Arc<StoreLock>>,
1742
    command_capacity: usize,
1743
    event_capacity: usize,
1744
) -> (ClientHandle, DriverPort, EventStream) {
1745
    let (request_tx, request_rx) = mpsc::channel(command_capacity);
1746
    let (event_tx, event_rx) = mpsc::channel(event_capacity);
1747
    let (connection_tx, connection_rx) = watch::channel(ConnectionState::Idle);
1748
    let publication = Arc::new(PublicationRegistry::default());
1749
    (
1750
        ClientHandle {
1751
            requests: request_tx,
1752
            client,
1753
            connection: connection_rx,
1754
            notification_client: Arc::new(OnceCell::new()),
1755
            sync_service,
1756
            media,
1757
            spaces: Arc::new(OnceCell::new()),
1758
            members_checked: Arc::default(),
1759
            publication: publication.clone(),
1760
            _store_lock: store_lock,
1761
        },
1762
        DriverPort {
1763
            requests: request_rx,
1764
            events: event_tx,
1765
            connection: connection_tx,
1766
            publication,
1767
        },
1768
        EventStream { events: event_rx },
1769
    )
1770
}
1771
1772
async fn list_members(
1773
    room: &matrix_sdk::Room,
1774
    filter: MemberFilter,
1775
) -> Result<Vec<MemberSummary>, Error> {
1776
    let memberships = match filter {
1777
        MemberFilter::Active => RoomMemberships::ACTIVE,
1778
        MemberFilter::Joined => RoomMemberships::JOIN,
1779
        MemberFilter::Invited => RoomMemberships::INVITE,
1780
        MemberFilter::Banned => RoomMemberships::BAN,
1781
        MemberFilter::Left => RoomMemberships::LEAVE,
1782
        // An empty mask is the SDK's unfiltered wildcard: it matches every
1783
        // membership, including custom states that `all()` would exclude.
1784
        MemberFilter::All => RoomMemberships::empty(),
1785
    };
1786
    Ok(room
1787
        .members(memberships)
1788
        .await
1789
        .map_err(|source| Error::from_sdk("listing members failed", source))?
1790
        .into_iter()
1791
        .map(member_summary)
1792
        .collect())
1793
}
1794
1795
fn normalise_push_notification(
1796
    room_id: &RoomId,
1797
    event_id: &EventId,
1798
    status: NotificationStatus,
1799
) -> PushNotificationStatus {
1800
    match status {
1801
        NotificationStatus::Event(item) => {
1802
            let event = match &item.raw_event {
1803
                RawNotificationEvent::Timeline(event) => {
1804
                    PushNotificationEvent::Timeline(event.clone())
1805
                }
1806
                RawNotificationEvent::Invite(event) => PushNotificationEvent::Invite(event.clone()),
1807
            };
1808
            PushNotificationStatus::Event(Box::new(PushNotification {
1809
                event_id: event_id.to_owned(),
1810
                event,
1811
                sender: PushNotificationSender {
1812
                    user_id: item.event.sender().to_owned(),
1813
                    display_name: item.sender_display_name,
1814
                    avatar_url: item.sender_avatar_url.as_deref().map(MediaId::plain),
1815
                    name_ambiguous: item.is_sender_name_ambiguous,
1816
                },
1817
                room: PushNotificationRoom {
1818
                    room_id: room_id.to_owned(),
1819
                    name: item.room_computed_display_name,
1820
                    avatar_url: item.room_avatar_url.as_deref().map(MediaId::plain),
1821
                    canonical_alias: item
1822
                        .room_canonical_alias
1823
                        .as_deref()
1824
                        .and_then(|alias| alias.parse().ok()),
1825
                    topic: item.room_topic,
1826
                    encrypted: item.is_room_encrypted,
1827
                    direct: item.room_is_dm,
1828
                    joined_members_count: item.joined_members_count,
1829
                    service_members: item
1830
                        .service_members
1831
                        .into_iter()
1832
                        .filter_map(|user_id| user_id.parse().ok())
1833
                        .collect(),
1834
                    active_service_members_count: item.active_service_members_count,
1835
                    space: item.is_space,
1836
                },
1837
                noisy: item.is_noisy,
1838
                has_mention: item.has_mention,
1839
                thread_id: item.thread_id,
1840
            }))
1841
        }
1842
        NotificationStatus::EventNotFound => PushNotificationStatus::NotFound,
1843
        NotificationStatus::EventFilteredOut => PushNotificationStatus::FilteredOut,
1844
        NotificationStatus::EventRedacted => PushNotificationStatus::Redacted,
1845
    }
1846
}
1847
1848
fn unexpected(wanted: &str, output: &CommandOutput) -> Error {
1849
    Error::new(
1850
        ErrorKind::Other,
1851
        format!("expected {wanted} but got {output:?}"),
1852
    )
1853
}
1854
1855
#[cfg(test)]
1856
mod tests {
1857
    use super::*;
1858
1859
    #[tokio::test]
1860
    async fn publish_barrier_waits_for_mirror_publication() {
1861
        let publication = Arc::new(PublicationRegistry::default());
1862
        let _registration = publication.register_mirror();
1863
        let (events, mut received) = mpsc::channel(1);
1864
        let sender = EventSender {
1865
            events,
1866
            publication,
1867
        };
1868
        let publisher = tokio::spawn(async move { sender.publish_barrier().await });
1869
1870
        let Some(Event::PublicationBarrier {
1871
            acknowledgement: Some(acknowledgement),
1872
        }) = received.recv().await
1873
        else {
1874
            panic!("barrier was not published");
1875
        };
1876
        tokio::task::yield_now().await;
1877
        assert!(!publisher.is_finished());
1878
1879
        acknowledgement.complete(true);
1880
        assert!(matches!(publisher.await.unwrap(), Ok(())));
1881
    }
1882
1883
    #[tokio::test]
1884
    async fn publish_barrier_fails_when_last_mirror_drops() {
1885
        let publication = Arc::new(PublicationRegistry::default());
1886
        let registration = publication.register_mirror();
1887
        let (events, mut received) = mpsc::channel(1);
1888
        let sender = EventSender {
1889
            events,
1890
            publication,
1891
        };
1892
        let publisher = tokio::spawn(async move { sender.publish_barrier().await });
1893
1894
        assert!(matches!(
1895
            received.recv().await,
1896
            Some(Event::PublicationBarrier {
1897
                acknowledgement: Some(_),
1898
            })
1899
        ));
1900
        drop(registration);
1901
1902
        assert!(matches!(publisher.await.unwrap(), Err(SendEventError)));
1903
    }
1904
}