atagen

macltok

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