atagen

macltok

public
Star0
Watch0
0bfa3f46f0be39529f9541bdfbff51255e54ffba
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git
src/model.rsRust1739 lines47.2 KB
1
use std::{fmt, sync::Arc};
2
3
use ruma::{
4
    OwnedDeviceId, OwnedEventId, OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, OwnedRoomOrAliasId,
5
    OwnedServerName, OwnedTransactionId, OwnedUserId,
6
    events::{
7
        AnyGlobalAccountDataEventContent, AnyRoomAccountDataEventContent, AnySyncTimelineEvent,
8
        GlobalAccountDataEventType, RoomAccountDataEventType,
9
        room::member::StrippedRoomMemberEvent,
10
    },
11
    serde::Raw,
12
};
13
#[cfg(feature = "serde")]
14
use serde::{Deserialize, Serialize};
15
16
/// every command answers exactly once through `ClientHandle::send` or `execute`.
17
/// the event stream only ever carries state
18
#[derive(Debug)]
19
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
20
#[non_exhaustive]
21
pub enum Command {
22
    Account(AccountCommand),
23
    Room(RoomCommand),
24
    Timeline(TimelineCommand),
25
    Media(MediaCommand),
26
    Encryption(EncryptionCommand),
27
    Notification(NotificationCommand),
28
    Lifecycle(LifecycleCommand),
29
}
30
31
#[derive(Debug)]
32
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
33
#[non_exhaustive]
34
pub enum AccountCommand {
35
    Logout,
36
    SetAccountData {
37
        event_type: GlobalAccountDataEventType,
38
        content: Raw<AnyGlobalAccountDataEventContent>,
39
    },
40
    SetDisplayName(Option<String>),
41
    SetAvatar(Option<OwnedMxcUri>),
42
    /// uploads the image and points the profile at it, same byte cap as any upload
43
    UploadAvatar {
44
        mimetype: String,
45
        bytes: Vec<u8>,
46
    },
47
    RenameDevice {
48
        device_id: OwnedDeviceId,
49
        display_name: String,
50
    },
51
    DeleteDevices {
52
        device_ids: Vec<OwnedDeviceId>,
53
        auth: Option<crate::InteractiveAuth>,
54
    },
55
}
56
57
#[derive(Clone, Debug)]
58
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
59
#[non_exhaustive]
60
pub enum RoomCommand {
61
    /// the snapshot turns up as `Event::TimelineReset`. opening an open room sends a fresh one
62
    Open(OwnedRoomId),
63
    Close(OwnedRoomId),
64
    Join {
65
        room: OwnedRoomOrAliasId,
66
        via: Vec<OwnedServerName>,
67
    },
68
    Leave(OwnedRoomId),
69
    Forget(OwnedRoomId),
70
    AcceptInvite(OwnedRoomId),
71
    RejectInvite(OwnedRoomId),
72
    InviteUser {
73
        room_id: OwnedRoomId,
74
        user_id: OwnedUserId,
75
    },
76
    KickUser {
77
        room_id: OwnedRoomId,
78
        user_id: OwnedUserId,
79
        reason: Option<String>,
80
    },
81
    BanUser {
82
        room_id: OwnedRoomId,
83
        user_id: OwnedUserId,
84
        reason: Option<String>,
85
    },
86
    UnbanUser {
87
        room_id: OwnedRoomId,
88
        user_id: OwnedUserId,
89
        reason: Option<String>,
90
    },
91
    SetPowerLevels {
92
        room_id: OwnedRoomId,
93
        changes: PowerLevelChanges,
94
    },
95
    SetUserPowerLevel {
96
        room_id: OwnedRoomId,
97
        user_id: OwnedUserId,
98
        level: i64,
99
    },
100
    Create(CreateRoomOptions),
101
    /// hands back the existing dm if there is one
102
    CreateDirect(OwnedUserId),
103
    CancelSend {
104
        room_id: OwnedRoomId,
105
        transaction_id: OwnedTransactionId,
106
    },
107
    RetrySend {
108
        room_id: OwnedRoomId,
109
        transaction_id: OwnedTransactionId,
110
    },
111
    SetTyping {
112
        room_id: OwnedRoomId,
113
        typing: bool,
114
    },
115
    SetAccountData {
116
        room_id: OwnedRoomId,
117
        event_type: RoomAccountDataEventType,
118
        content: Raw<AnyRoomAccountDataEventContent>,
119
    },
120
}
121
122
#[derive(Clone, Debug, Default, Eq, PartialEq)]
123
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
124
#[non_exhaustive]
125
pub struct CreateRoomOptions {
126
    pub name: Option<String>,
127
    pub topic: Option<String>,
128
    pub alias_localpart: Option<String>,
129
    pub invite: Vec<OwnedUserId>,
130
    pub direct: bool,
131
    pub visibility: RoomVisibility,
132
    pub preset: Option<RoomPreset>,
133
}
134
135
impl CreateRoomOptions {
136
    #[must_use]
137
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
138
        self.name = Some(name.into());
139
        self
140
    }
141
142
    #[must_use]
143
    pub fn with_topic(mut self, topic: impl Into<String>) -> Self {
144
        self.topic = Some(topic.into());
145
        self
146
    }
147
148
    #[must_use]
149
    pub fn with_alias_localpart(mut self, localpart: impl Into<String>) -> Self {
150
        self.alias_localpart = Some(localpart.into());
151
        self
152
    }
153
154
    #[must_use]
155
    pub fn with_invite(mut self, invite: impl IntoIterator<Item = OwnedUserId>) -> Self {
156
        self.invite = invite.into_iter().collect();
157
        self
158
    }
159
160
    #[must_use]
161
    pub const fn with_direct(mut self, direct: bool) -> Self {
162
        self.direct = direct;
163
        self
164
    }
165
166
    #[must_use]
167
    pub const fn with_visibility(mut self, visibility: RoomVisibility) -> Self {
168
        self.visibility = visibility;
169
        self
170
    }
171
172
    #[must_use]
173
    pub const fn with_preset(mut self, preset: RoomPreset) -> Self {
174
        self.preset = Some(preset);
175
        self
176
    }
177
}
178
179
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
180
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
181
pub enum RoomVisibility {
182
    #[default]
183
    Private,
184
    Public,
185
}
186
187
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
188
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
189
pub enum RoomPreset {
190
    PrivateChat,
191
    TrustedPrivateChat,
192
    PublicChat,
193
}
194
195
#[derive(Clone, Debug, Eq, PartialEq)]
196
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
197
#[non_exhaustive]
198
pub enum TimelineCommand {
199
    OpenThread {
200
        room_id: OwnedRoomId,
201
        root_event_id: OwnedEventId,
202
    },
203
    CloseThread {
204
        room_id: OwnedRoomId,
205
        root_event_id: OwnedEventId,
206
    },
207
    /// Re-emit an authoritative reset for an open room or thread without
208
    /// closing it. The reset arrives before this command's terminal result.
209
    Resync {
210
        timeline_id: TimelineId,
211
    },
212
    Paginate {
213
        timeline_id: TimelineId,
214
        limit: u16,
215
    },
216
    Send {
217
        timeline_id: TimelineId,
218
        content: MessageContent,
219
    },
220
    Edit {
221
        timeline_id: TimelineId,
222
        target: EventRef,
223
        content: MessageEditContent,
224
    },
225
    /// redacting your own unsent message just cancels it
226
    Redact {
227
        timeline_id: TimelineId,
228
        target: EventRef,
229
        reason: Option<String>,
230
    },
231
    ToggleReaction {
232
        timeline_id: TimelineId,
233
        target: EventRef,
234
        key: String,
235
    },
236
    /// works on a closed room too, it just can't refuse to move the marker backwards
237
    MarkRead {
238
        timeline_id: TimelineId,
239
        event_id: OwnedEventId,
240
    },
241
}
242
243
impl TimelineCommand {
244
    #[must_use]
245
    pub const fn room_id(&self) -> &OwnedRoomId {
246
        match self {
247
            Self::OpenThread { room_id, .. } | Self::CloseThread { room_id, .. } => room_id,
248
            Self::Resync { timeline_id }
249
            | Self::Paginate { timeline_id, .. }
250
            | Self::Send { timeline_id, .. }
251
            | Self::Edit { timeline_id, .. }
252
            | Self::Redact { timeline_id, .. }
253
            | Self::ToggleReaction { timeline_id, .. }
254
            | Self::MarkRead { timeline_id, .. } => timeline_id.room_id(),
255
        }
256
    }
257
258
    #[must_use]
259
    pub const fn timeline_id(&self) -> Option<&TimelineId> {
260
        match self {
261
            Self::OpenThread { .. } | Self::CloseThread { .. } => None,
262
            Self::Resync { timeline_id }
263
            | Self::Paginate { timeline_id, .. }
264
            | Self::Send { timeline_id, .. }
265
            | Self::Edit { timeline_id, .. }
266
            | Self::Redact { timeline_id, .. }
267
            | Self::ToggleReaction { timeline_id, .. }
268
            | Self::MarkRead { timeline_id, .. } => Some(timeline_id),
269
        }
270
    }
271
}
272
273
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
274
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
275
#[non_exhaustive]
276
pub enum TimelineId {
277
    Room(OwnedRoomId),
278
    Thread {
279
        room_id: OwnedRoomId,
280
        root_event_id: OwnedEventId,
281
    },
282
}
283
284
impl TimelineId {
285
    #[must_use]
286
    pub const fn room_id(&self) -> &OwnedRoomId {
287
        match self {
288
            Self::Room(room_id) | Self::Thread { room_id, .. } => room_id,
289
        }
290
    }
291
292
    #[must_use]
293
    pub fn thread(room_id: OwnedRoomId, root_event_id: OwnedEventId) -> Self {
294
        Self::Thread {
295
            room_id,
296
            root_event_id,
297
        }
298
    }
299
300
    #[must_use]
301
    pub fn thread_root(&self) -> Option<&OwnedEventId> {
302
        match self {
303
            Self::Room(_) => None,
304
            Self::Thread { root_event_id, .. } => Some(root_event_id),
305
        }
306
    }
307
}
308
309
impl From<OwnedRoomId> for TimelineId {
310
    fn from(room_id: OwnedRoomId) -> Self {
311
        Self::Room(room_id)
312
    }
313
}
314
315
#[derive(Clone, Debug, Eq, PartialEq)]
316
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
317
#[non_exhaustive]
318
pub enum MediaCommand {
319
    /// succeeds once the send queue has it. progress and failure arrive as events
320
    Upload(AttachmentUpload),
321
}
322
323
#[derive(Clone, Debug, Eq, PartialEq)]
324
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
325
#[non_exhaustive]
326
pub struct AttachmentUpload {
327
    pub timeline_id: TimelineId,
328
    pub filename: String,
329
    pub mimetype: String,
330
    pub bytes: Vec<u8>,
331
    pub caption: Option<String>,
332
    pub details: Option<UploadDetails>,
333
    pub thumbnail: Option<UploadThumbnail>,
334
}
335
336
impl AttachmentUpload {
337
    #[must_use]
338
    pub fn new(
339
        timeline_id: impl Into<TimelineId>,
340
        filename: impl Into<String>,
341
        mimetype: impl Into<String>,
342
        bytes: Vec<u8>,
343
    ) -> Self {
344
        Self {
345
            timeline_id: timeline_id.into(),
346
            filename: filename.into(),
347
            mimetype: mimetype.into(),
348
            bytes,
349
            caption: None,
350
            details: None,
351
            thumbnail: None,
352
        }
353
    }
354
}
355
356
#[derive(Clone, Debug, Eq, PartialEq)]
357
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
358
#[non_exhaustive]
359
pub enum UploadDetails {
360
    Image {
361
        width: Option<u32>,
362
        height: Option<u32>,
363
        blurhash: Option<String>,
364
    },
365
    Video {
366
        width: Option<u32>,
367
        height: Option<u32>,
368
        duration_ms: Option<u64>,
369
        blurhash: Option<String>,
370
    },
371
    Audio {
372
        duration_ms: Option<u64>,
373
    },
374
    Voice {
375
        duration_ms: u64,
376
        waveform: Vec<u16>,
377
    },
378
    File,
379
}
380
381
#[derive(Clone, Debug, Eq, PartialEq)]
382
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
383
#[non_exhaustive]
384
pub struct UploadThumbnail {
385
    pub bytes: Vec<u8>,
386
    pub mimetype: String,
387
    pub width: u32,
388
    pub height: u32,
389
}
390
391
impl UploadThumbnail {
392
    #[must_use]
393
    pub fn new(bytes: Vec<u8>, mimetype: impl Into<String>, width: u32, height: u32) -> Self {
394
        Self {
395
            bytes,
396
            mimetype: mimetype.into(),
397
            width,
398
            height,
399
        }
400
    }
401
}
402
403
#[derive(Eq, PartialEq)]
404
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
405
#[non_exhaustive]
406
pub enum EncryptionCommand {
407
    Recover(String),
408
    CreateKeyBackup,
409
    EnableKeyBackup,
410
    DisableKeyBackup { delete_from_server: bool },
411
    RecoverKeyBackup(String),
412
    StartVerification(VerificationTarget),
413
    Verify(VerificationAction),
414
}
415
416
impl fmt::Debug for EncryptionCommand {
417
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
418
        match self {
419
            Self::Recover(_) => formatter.debug_tuple("Recover").field(&"...").finish(),
420
            Self::CreateKeyBackup => formatter.write_str("CreateKeyBackup"),
421
            Self::EnableKeyBackup => formatter.write_str("EnableKeyBackup"),
422
            Self::DisableKeyBackup { delete_from_server } => formatter
423
                .debug_struct("DisableKeyBackup")
424
                .field("delete_from_server", delete_from_server)
425
                .finish(),
426
            Self::RecoverKeyBackup(_) => formatter
427
                .debug_tuple("RecoverKeyBackup")
428
                .field(&"...")
429
                .finish(),
430
            Self::StartVerification(target) => formatter
431
                .debug_tuple("StartVerification")
432
                .field(target)
433
                .finish(),
434
            Self::Verify(action) => formatter.debug_tuple("Verify").field(action).finish(),
435
        }
436
    }
437
}
438
439
#[derive(Clone, Debug, Eq, PartialEq)]
440
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
441
#[non_exhaustive]
442
pub enum NotificationCommand {
443
    SetRoomMode {
444
        room_id: OwnedRoomId,
445
        mode: RoomNotificationMode,
446
    },
447
    ResetRoomMode(OwnedRoomId),
448
    SetDefaultMode {
449
        encrypted: bool,
450
        one_to_one: bool,
451
        mode: RoomNotificationMode,
452
    },
453
    AddKeyword(String),
454
    RemoveKeyword(String),
455
}
456
457
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
458
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
459
#[non_exhaustive]
460
pub enum LifecycleCommand {
461
    Shutdown,
462
}
463
464
#[derive(Clone, Debug, Eq, PartialEq)]
465
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
466
#[non_exhaustive]
467
pub enum CommandOutput {
468
    Done,
469
    Room(OwnedRoomId),
470
}
471
472
#[derive(Clone, Debug, Eq, PartialEq)]
473
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
474
#[non_exhaustive]
475
pub enum MessageContent {
476
    Text {
477
        content: RichText,
478
        mentions: MessageMentions,
479
    },
480
    Emote {
481
        content: RichText,
482
        mentions: MessageMentions,
483
    },
484
    Reply {
485
        event_id: OwnedEventId,
486
        content: RichText,
487
        mentions: MessageMentions,
488
        notify_replied_to: bool,
489
    },
490
}
491
492
impl MessageContent {
493
    #[must_use]
494
    pub fn text(body: impl Into<String>) -> Self {
495
        Self::Text {
496
            content: RichText::plain(body),
497
            mentions: MessageMentions::default(),
498
        }
499
    }
500
501
    #[must_use]
502
    pub fn html(body: impl Into<String>, formatted_body: impl Into<String>) -> Self {
503
        Self::Text {
504
            content: RichText::html(body, formatted_body),
505
            mentions: MessageMentions::default(),
506
        }
507
    }
508
509
    #[must_use]
510
    pub fn emote(content: RichText, mentions: MessageMentions) -> Self {
511
        Self::Emote { content, mentions }
512
    }
513
514
    #[must_use]
515
    pub fn reply(event_id: OwnedEventId, content: RichText, mentions: MessageMentions) -> Self {
516
        Self::Reply {
517
            event_id,
518
            content,
519
            mentions,
520
            notify_replied_to: true,
521
        }
522
    }
523
524
    #[must_use]
525
    pub fn reply_without_notification(
526
        event_id: OwnedEventId,
527
        content: RichText,
528
        mentions: MessageMentions,
529
    ) -> Self {
530
        Self::Reply {
531
            event_id,
532
            content,
533
            mentions,
534
            notify_replied_to: false,
535
        }
536
    }
537
}
538
539
#[derive(Clone, Debug, Eq, PartialEq)]
540
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
541
#[non_exhaustive]
542
pub enum MessageEditContent {
543
    Text {
544
        content: RichText,
545
        mentions: MessageMentions,
546
    },
547
    Emote {
548
        content: RichText,
549
        mentions: MessageMentions,
550
    },
551
}
552
553
impl MessageEditContent {
554
    #[must_use]
555
    pub fn text(body: impl Into<String>) -> Self {
556
        Self::Text {
557
            content: RichText::plain(body),
558
            mentions: MessageMentions::default(),
559
        }
560
    }
561
562
    #[must_use]
563
    pub fn html(body: impl Into<String>, formatted_body: impl Into<String>) -> Self {
564
        Self::Text {
565
            content: RichText::html(body, formatted_body),
566
            mentions: MessageMentions::default(),
567
        }
568
    }
569
570
    #[must_use]
571
    pub fn emote(content: RichText, mentions: MessageMentions) -> Self {
572
        Self::Emote { content, mentions }
573
    }
574
}
575
576
#[derive(Clone, Debug, Default, Eq, PartialEq)]
577
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
578
#[non_exhaustive]
579
pub struct RichText {
580
    pub body: String,
581
    pub formatted_body: Option<String>,
582
}
583
584
impl RichText {
585
    #[must_use]
586
    pub fn plain(body: impl Into<String>) -> Self {
587
        Self {
588
            body: body.into(),
589
            formatted_body: None,
590
        }
591
    }
592
593
    #[must_use]
594
    pub fn html(body: impl Into<String>, formatted_body: impl Into<String>) -> Self {
595
        Self {
596
            body: body.into(),
597
            formatted_body: Some(formatted_body.into()),
598
        }
599
    }
600
}
601
602
#[derive(Clone, Debug, Default, Eq, PartialEq)]
603
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
604
#[non_exhaustive]
605
pub struct MessageMentions {
606
    pub user_ids: Vec<OwnedUserId>,
607
    pub room: bool,
608
}
609
610
impl MessageMentions {
611
    #[must_use]
612
    pub fn with_user_ids(user_ids: impl IntoIterator<Item = OwnedUserId>) -> Self {
613
        Self {
614
            user_ids: user_ids.into_iter().collect(),
615
            room: false,
616
        }
617
    }
618
619
    #[must_use]
620
    pub fn room() -> Self {
621
        Self {
622
            user_ids: Vec::new(),
623
            room: true,
624
        }
625
    }
626
}
627
628
#[derive(Clone, Debug, Eq, PartialEq)]
629
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
630
#[non_exhaustive]
631
pub enum Event {
632
    ConnectionChanged(ConnectionState),
633
    Authenticated {
634
        user_id: OwnedUserId,
635
    },
636
    /// Refresh tokens changed. Persist a fresh `ClientHandle::session_record()`
637
    /// atomically; a record captured before this event may no longer restore.
638
    SessionTokensChanged,
639
    /// the server stopped honouring our token and the engine stops. on a soft
640
    /// logout keep the store and log in again with the same device, otherwise
641
    /// the record and the store are both dead
642
    SessionAccessRejected {
643
        soft_logout: bool,
644
    },
645
    NotificationSettingsChanged,
646
    VerificationTargetChanged(VerificationTarget),
647
    RoomsChanged,
648
    /// replaces whatever you had for this timeline. every diff after it applies to it
649
    TimelineReset {
650
        timeline_id: TimelineId,
651
        items: Vec<TimelineItem>,
652
    },
653
    TimelineChanged {
654
        timeline_id: TimelineId,
655
        diffs: Vec<TimelineDiff>,
656
    },
657
    HistoryChanged {
658
        timeline_id: TimelineId,
659
        state: HistoryState,
660
    },
661
    /// the timeline was closed, or its room was left, and nothing more comes for it
662
    /// until another `TimelineReset`
663
    TimelineClosed {
664
        timeline_id: TimelineId,
665
    },
666
    /// a room that stops being watched says so with an empty `users`
667
    TypingChanged(TypingState),
668
    MediaUploadProgress {
669
        room_id: OwnedRoomId,
670
        transaction_id: OwnedTransactionId,
671
        uploaded_bytes: u64,
672
        total_bytes: u64,
673
        complete: bool,
674
    },
675
    /// not the end of it. `will_retry` means the send queue has another go by itself,
676
    /// otherwise it waits for `retry_send` or `cancel_send`
677
    MediaUploadFailed {
678
        room_id: OwnedRoomId,
679
        transaction_id: OwnedTransactionId,
680
        kind: crate::ErrorKind,
681
        will_retry: bool,
682
    },
683
    /// every upload ends with exactly one of these
684
    MediaUploadFinished {
685
        room_id: OwnedRoomId,
686
        transaction_id: OwnedTransactionId,
687
        outcome: UploadOutcome,
688
    },
689
    EncryptionChanged(EncryptionState),
690
    VerificationChanged(VerificationState),
691
    /// logout went through and the engine stops. delete the record and the store
692
    LoggedOut,
693
    Failed(EngineFailure),
694
    /// always the last event. keep the saved record unless `LoggedOut` or a
695
    /// hard `SessionAccessRejected` came first. commands still in flight answer `Interrupted`
696
    Stopped,
697
}
698
699
#[derive(Clone, Debug, Eq, PartialEq)]
700
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
701
#[non_exhaustive]
702
pub enum UploadOutcome {
703
    Sent {
704
        event_id: OwnedEventId,
705
    },
706
    Cancelled,
707
    /// its room was forgotten, and the queue with it
708
    RoomForgotten,
709
    /// the sdk's update channel overflowed while it ended, so whether it was sent is unknown
710
    Missed,
711
}
712
713
/// why `Engine::run` came back, when nothing went wrong
714
#[derive(Clone, Debug, Eq, PartialEq)]
715
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
716
#[non_exhaustive]
717
pub enum Termination {
718
    ShutDown,
719
    /// every `ClientHandle` was dropped, so nobody could have asked for anything else
720
    HandlesDropped,
721
    LoggedOut,
722
    /// the server rejected our token for good
723
    AccessRevoked,
724
    /// the server wants this device to log in again, and its e2ee keys live in the store
725
    SoftLoggedOut {
726
        device_id: OwnedDeviceId,
727
    },
728
}
729
730
impl Termination {
731
    #[must_use]
732
    pub const fn retain(&self) -> Retain {
733
        match self {
734
            Self::ShutDown | Self::HandlesDropped => Retain::RecordAndStore,
735
            Self::SoftLoggedOut { .. } => Retain::Store,
736
            Self::LoggedOut | Self::AccessRevoked => Retain::Nothing,
737
        }
738
    }
739
}
740
741
/// what's still worth keeping of the saved record and the store
742
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
743
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
744
pub enum Retain {
745
    RecordAndStore,
746
    Store,
747
    Nothing,
748
}
749
750
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
751
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
752
#[non_exhaustive]
753
pub enum ConnectionState {
754
    Idle,
755
    Connecting,
756
    Online,
757
    Offline,
758
    Stopped,
759
}
760
761
#[derive(Clone, Debug, Eq, PartialEq)]
762
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
763
#[non_exhaustive]
764
pub struct RoomSummary {
765
    pub room_id: OwnedRoomId,
766
    pub name: String,
767
    pub membership: RoomMembership,
768
    pub unread_messages: u64,
769
    pub unread_mentions: u64,
770
    /// unread events the push rules said to notify about, which is neither of the above
771
    pub unread_notifications: u64,
772
    pub encrypted: bool,
773
    pub space: bool,
774
    pub direct: bool,
775
    pub favourite: bool,
776
    pub low_priority: bool,
777
    pub avatar: Option<OwnedMxcUri>,
778
    pub latest_event_timestamp_ms: Option<u64>,
779
    pub latest_event: Option<LatestEvent>,
780
    pub notification_mode: Option<RoomNotificationMode>,
781
    pub notification_mode_custom: bool,
782
    pub topic: Option<String>,
783
    pub canonical_alias: Option<OwnedRoomAliasId>,
784
    pub joined_members: u64,
785
    pub invited_members: u64,
786
    /// who a nameless room gets named after
787
    pub heroes: Vec<RoomHero>,
788
    /// set once the room has been upgraded, this is where everyone went
789
    pub successor: Option<OwnedRoomId>,
790
    pub inviter: Option<OwnedUserId>,
791
    /// joined spaces that list this room as a child
792
    pub parent_spaces: Vec<OwnedRoomId>,
793
    /// for a space, the children it lists, joined or not
794
    pub children: Vec<OwnedRoomId>,
795
}
796
797
#[derive(Clone, Debug, Eq, PartialEq)]
798
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
799
#[non_exhaustive]
800
pub struct RoomHero {
801
    pub user_id: OwnedUserId,
802
    pub display_name: Option<String>,
803
    pub avatar: Option<OwnedMxcUri>,
804
}
805
806
/// enough for a room list preview line. `kind` and `body` are only set for messages,
807
/// and an edit shows its new text
808
#[derive(Clone, Debug, Eq, PartialEq)]
809
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
810
#[non_exhaustive]
811
pub struct LatestEvent {
812
    pub sender: Option<OwnedUserId>,
813
    pub kind: Option<MessageKind>,
814
    pub body: Option<String>,
815
    pub timestamp_ms: Option<u64>,
816
    pub send_state: SendState,
817
}
818
819
#[derive(Clone, Debug, Eq, PartialEq)]
820
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
821
#[non_exhaustive]
822
pub struct Profile {
823
    pub user_id: OwnedUserId,
824
    pub display_name: Option<String>,
825
    pub avatar: Option<OwnedMxcUri>,
826
}
827
828
/// one room in a space's hierarchy, as the server describes it, which may be a room you're not in
829
#[derive(Clone, Debug, Eq, PartialEq)]
830
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
831
#[non_exhaustive]
832
pub struct SpaceChild {
833
    pub room_id: OwnedRoomId,
834
    pub name: String,
835
    pub topic: Option<String>,
836
    pub avatar: Option<OwnedMxcUri>,
837
    pub canonical_alias: Option<OwnedRoomAliasId>,
838
    pub joined_members: u64,
839
    pub space: bool,
840
    pub children_count: u64,
841
    pub membership: Option<RoomMembership>,
842
    pub via: Vec<OwnedServerName>,
843
    pub suggested: bool,
844
    pub world_readable: Option<bool>,
845
    pub guest_can_join: bool,
846
}
847
848
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
849
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
850
#[non_exhaustive]
851
pub enum RoomNotificationMode {
852
    AllMessages,
853
    MentionsAndKeywordsOnly,
854
    Mute,
855
}
856
857
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
858
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
859
#[non_exhaustive]
860
pub struct RoomNotificationSettings {
861
    pub mode: RoomNotificationMode,
862
    pub custom: bool,
863
}
864
865
#[derive(Clone, Debug)]
866
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
867
#[non_exhaustive]
868
pub enum PushNotificationStatus {
869
    Event(Box<PushNotification>),
870
    NotFound,
871
    FilteredOut,
872
    Redacted,
873
}
874
875
#[derive(Clone, Debug)]
876
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
877
#[non_exhaustive]
878
pub struct PushNotification {
879
    pub event_id: OwnedEventId,
880
    pub event: PushNotificationEvent,
881
    pub sender: PushNotificationSender,
882
    pub room: PushNotificationRoom,
883
    pub noisy: Option<bool>,
884
    pub has_mention: Option<bool>,
885
    pub thread_id: Option<OwnedEventId>,
886
}
887
888
#[derive(Clone, Debug, Eq, PartialEq)]
889
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
890
#[non_exhaustive]
891
pub struct PushNotificationSender {
892
    pub user_id: OwnedUserId,
893
    pub display_name: Option<String>,
894
    pub avatar_url: Option<OwnedMxcUri>,
895
    pub name_ambiguous: bool,
896
}
897
898
#[derive(Clone, Debug, Eq, PartialEq)]
899
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
900
#[non_exhaustive]
901
pub struct PushNotificationRoom {
902
    pub room_id: OwnedRoomId,
903
    pub name: String,
904
    pub avatar_url: Option<OwnedMxcUri>,
905
    pub canonical_alias: Option<OwnedRoomAliasId>,
906
    pub topic: Option<String>,
907
    pub encrypted: Option<bool>,
908
    pub direct: bool,
909
    pub joined_members_count: u64,
910
    pub service_members: Vec<OwnedUserId>,
911
    pub active_service_members_count: u64,
912
    pub space: bool,
913
}
914
915
#[derive(Clone, Debug)]
916
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
917
#[non_exhaustive]
918
pub enum PushNotificationEvent {
919
    Timeline(Raw<AnySyncTimelineEvent>),
920
    Invite(Raw<StrippedRoomMemberEvent>),
921
}
922
923
#[derive(Clone, Debug, Eq, PartialEq)]
924
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
925
#[non_exhaustive]
926
pub struct RoomPowerLevels {
927
    pub ban: i64,
928
    pub invite: i64,
929
    pub kick: i64,
930
    pub redact: i64,
931
    pub events_default: i64,
932
    pub state_default: i64,
933
    pub users_default: i64,
934
    pub room_notification: i64,
935
    pub users: Vec<(OwnedUserId, i64)>,
936
    pub events: Vec<(String, i64)>,
937
    /// in rooms from version 12 the creators outrank everyone and aren't listed in `users`
938
    pub creators: Vec<OwnedUserId>,
939
}
940
941
#[derive(Clone, Debug, Default, Eq, PartialEq)]
942
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
943
#[non_exhaustive]
944
pub struct PowerLevelChanges {
945
    pub ban: Option<i64>,
946
    pub invite: Option<i64>,
947
    pub kick: Option<i64>,
948
    pub redact: Option<i64>,
949
    pub events_default: Option<i64>,
950
    pub state_default: Option<i64>,
951
    pub users_default: Option<i64>,
952
    pub room_notification: Option<i64>,
953
    pub room_name: Option<i64>,
954
    pub room_avatar: Option<i64>,
955
    pub room_topic: Option<i64>,
956
    pub space_child: Option<i64>,
957
    pub beacon: Option<i64>,
958
    pub beacon_info: Option<i64>,
959
}
960
961
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
962
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
963
#[non_exhaustive]
964
pub enum RoomMembership {
965
    Joined,
966
    Invited,
967
    Left,
968
    Knocked,
969
    Banned,
970
}
971
972
#[derive(Clone, Debug, Default, Eq, PartialEq)]
973
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
974
#[non_exhaustive]
975
pub struct RoomListFilter {
976
    pub membership: Option<RoomMembership>,
977
    pub category: Option<RoomCategory>,
978
    pub favourite: Option<bool>,
979
    pub unread_only: bool,
980
    pub search: Option<String>,
981
}
982
983
impl RoomListFilter {
984
    #[must_use]
985
    pub fn with_membership(mut self, membership: RoomMembership) -> Self {
986
        self.membership = Some(membership);
987
        self
988
    }
989
990
    #[must_use]
991
    pub fn with_category(mut self, category: RoomCategory) -> Self {
992
        self.category = Some(category);
993
        self
994
    }
995
996
    #[must_use]
997
    pub fn with_favourite(mut self, favourite: bool) -> Self {
998
        self.favourite = Some(favourite);
999
        self
1000
    }
1001
1002
    #[must_use]
1003
    pub const fn with_unread_only(mut self, unread_only: bool) -> Self {
1004
        self.unread_only = unread_only;
1005
        self
1006
    }
1007
1008
    #[must_use]
1009
    pub fn with_search(mut self, search: impl Into<String>) -> Self {
1010
        self.search = Some(search.into());
1011
        self
1012
    }
1013
1014
    #[must_use]
1015
    pub fn matches(&self, room: &RoomSummary) -> bool {
1016
        self.matcher().matches(room)
1017
    }
1018
1019
    /// lowercases the search once, for filtering a whole list
1020
    #[must_use]
1021
    pub fn matcher(&self) -> RoomMatcher<'_> {
1022
        RoomMatcher {
1023
            filter: self,
1024
            search: self.search.as_deref().map(str::to_lowercase),
1025
        }
1026
    }
1027
}
1028
1029
#[derive(Debug)]
1030
pub struct RoomMatcher<'a> {
1031
    filter: &'a RoomListFilter,
1032
    search: Option<String>,
1033
}
1034
1035
impl RoomMatcher<'_> {
1036
    #[must_use]
1037
    pub fn matches(&self, room: &RoomSummary) -> bool {
1038
        let filter = self.filter;
1039
        filter
1040
            .membership
1041
            .is_none_or(|membership| room.membership == membership)
1042
            && filter.category.is_none_or(|category| match category {
1043
                RoomCategory::People => room.direct && !room.space,
1044
                RoomCategory::Rooms => !room.direct && !room.space,
1045
                RoomCategory::Spaces => room.space,
1046
            })
1047
            && filter
1048
                .favourite
1049
                .is_none_or(|favourite| room.favourite == favourite)
1050
            && (!filter.unread_only || room.unread_messages > 0 || room.unread_mentions > 0)
1051
            && self.search.as_ref().is_none_or(|search| {
1052
                room.name.to_lowercase().contains(search)
1053
                    || room.room_id.as_str().to_lowercase().contains(search)
1054
            })
1055
    }
1056
}
1057
1058
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1059
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1060
#[non_exhaustive]
1061
pub enum RoomCategory {
1062
    People,
1063
    Rooms,
1064
    Spaces,
1065
}
1066
1067
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1068
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1069
#[non_exhaustive]
1070
pub enum MemberFilter {
1071
    Active,
1072
    Joined,
1073
    Invited,
1074
    Banned,
1075
    Left,
1076
    All,
1077
}
1078
1079
#[derive(Clone, Debug, Eq, PartialEq)]
1080
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1081
#[non_exhaustive]
1082
pub enum MemberMembership {
1083
    Joined,
1084
    Invited,
1085
    Left,
1086
    Knocked,
1087
    Banned,
1088
    Custom(String),
1089
}
1090
1091
#[derive(Clone, Debug, Eq, PartialEq)]
1092
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1093
#[non_exhaustive]
1094
pub struct MemberSummary {
1095
    pub user_id: OwnedUserId,
1096
    pub name: String,
1097
    pub display_name: Option<String>,
1098
    pub avatar: Option<OwnedMxcUri>,
1099
    pub membership: MemberMembership,
1100
    pub own: bool,
1101
    pub name_ambiguous: bool,
1102
    pub ignored: bool,
1103
    pub service: bool,
1104
}
1105
1106
#[derive(Clone, Debug, Eq, PartialEq)]
1107
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1108
#[non_exhaustive]
1109
pub struct OwnDevice {
1110
    pub device_id: OwnedDeviceId,
1111
    pub display_name: Option<String>,
1112
    pub last_seen_ip: Option<String>,
1113
    pub last_seen_timestamp_ms: Option<u64>,
1114
    pub current: bool,
1115
}
1116
1117
#[derive(Clone, Debug, Eq, PartialEq)]
1118
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1119
#[non_exhaustive]
1120
pub enum TimelineItem {
1121
    Event(Box<TimelineEvent>),
1122
    DayDivider { timestamp_ms: u64 },
1123
    ReadMarker,
1124
    TimelineStart,
1125
}
1126
1127
#[derive(Clone, Debug, Eq, PartialEq)]
1128
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1129
#[non_exhaustive]
1130
pub enum TimelineDiff {
1131
    Append { values: Vec<TimelineItem> },
1132
    Clear,
1133
    PushFront { value: TimelineItem },
1134
    PushBack { value: TimelineItem },
1135
    PopFront,
1136
    PopBack,
1137
    Insert { index: usize, value: TimelineItem },
1138
    Set { index: usize, value: TimelineItem },
1139
    Remove { index: usize },
1140
    Truncate { length: usize },
1141
    Reset { values: Vec<TimelineItem> },
1142
}
1143
1144
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
1145
#[error("timeline diff is incompatible with the current {length}-item snapshot")]
1146
pub struct TimelineDiffError {
1147
    pub length: usize,
1148
}
1149
1150
impl TimelineDiff {
1151
    /// Apply a diff only when its indices match the current snapshot.
1152
    /// On error the snapshot is unchanged; request `TimelineCommand::Resync`
1153
    /// and ignore further diffs until the corresponding `TimelineReset`.
1154
    pub fn try_apply(self, items: &mut Vec<TimelineItem>) -> Result<(), TimelineDiffError> {
1155
        let length = items.len();
1156
        match self {
1157
            Self::Append { values } => items.extend(values),
1158
            Self::Clear => items.clear(),
1159
            Self::PushFront { value } => items.insert(0, value),
1160
            Self::PushBack { value } => items.push(value),
1161
            Self::PopFront if length == 0 => return Err(TimelineDiffError { length }),
1162
            Self::PopFront => {
1163
                items.remove(0);
1164
            }
1165
            Self::PopBack if length == 0 => return Err(TimelineDiffError { length }),
1166
            Self::PopBack => {
1167
                items.pop();
1168
            }
1169
            Self::Insert { index, .. } if index > length => {
1170
                return Err(TimelineDiffError { length });
1171
            }
1172
            Self::Insert { index, value } => items.insert(index, value),
1173
            Self::Set { index, .. } if index >= length => return Err(TimelineDiffError { length }),
1174
            Self::Set { index, value } => items[index] = value,
1175
            Self::Remove { index } if index >= length => return Err(TimelineDiffError { length }),
1176
            Self::Remove { index } => {
1177
                items.remove(index);
1178
            }
1179
            Self::Truncate { length: target } if target > length => {
1180
                return Err(TimelineDiffError { length });
1181
            }
1182
            Self::Truncate { length } => items.truncate(length),
1183
            Self::Reset { values } => *items = values,
1184
        }
1185
        Ok(())
1186
    }
1187
}
1188
1189
#[cfg(test)]
1190
mod tests {
1191
    use super::{TimelineDiff, TimelineItem};
1192
1193
    fn item(timestamp_ms: u64) -> TimelineItem {
1194
        TimelineItem::DayDivider { timestamp_ms }
1195
    }
1196
1197
    #[test]
1198
    fn timeline_diff_try_apply_handles_every_variant() {
1199
        let mut items = vec![item(1), item(2)];
1200
1201
        TimelineDiff::Append {
1202
            values: vec![item(3)],
1203
        }
1204
        .try_apply(&mut items)
1205
        .unwrap();
1206
        assert_eq!(items, vec![item(1), item(2), item(3)]);
1207
1208
        TimelineDiff::Clear.try_apply(&mut items).unwrap();
1209
        assert!(items.is_empty());
1210
1211
        TimelineDiff::PushFront { value: item(2) }
1212
            .try_apply(&mut items)
1213
            .unwrap();
1214
        TimelineDiff::PushBack { value: item(3) }
1215
            .try_apply(&mut items)
1216
            .unwrap();
1217
        assert_eq!(items, vec![item(2), item(3)]);
1218
1219
        TimelineDiff::PopFront.try_apply(&mut items).unwrap();
1220
        TimelineDiff::PopBack.try_apply(&mut items).unwrap();
1221
        assert!(items.is_empty());
1222
1223
        TimelineDiff::Reset {
1224
            values: vec![item(1), item(3)],
1225
        }
1226
        .try_apply(&mut items)
1227
        .unwrap();
1228
        TimelineDiff::Insert {
1229
            index: 1,
1230
            value: item(2),
1231
        }
1232
        .try_apply(&mut items)
1233
        .unwrap();
1234
        assert_eq!(items, vec![item(1), item(2), item(3)]);
1235
1236
        TimelineDiff::Set {
1237
            index: 1,
1238
            value: item(4),
1239
        }
1240
        .try_apply(&mut items)
1241
        .unwrap();
1242
        assert_eq!(items, vec![item(1), item(4), item(3)]);
1243
1244
        TimelineDiff::Remove { index: 1 }
1245
            .try_apply(&mut items)
1246
            .unwrap();
1247
        assert_eq!(items, vec![item(1), item(3)]);
1248
1249
        TimelineDiff::Truncate { length: 1 }
1250
            .try_apply(&mut items)
1251
            .unwrap();
1252
        assert_eq!(items, vec![item(1)]);
1253
    }
1254
1255
    #[test]
1256
    fn invalid_timeline_diff_leaves_snapshot_unchanged() {
1257
        let invalid = [
1258
            TimelineDiff::Insert {
1259
                index: 3,
1260
                value: item(3),
1261
            },
1262
            TimelineDiff::Set {
1263
                index: 2,
1264
                value: item(3),
1265
            },
1266
            TimelineDiff::Remove { index: 2 },
1267
            TimelineDiff::Truncate { length: 3 },
1268
        ];
1269
        for diff in invalid {
1270
            let mut items = vec![item(1), item(2)];
1271
            assert_eq!(diff.try_apply(&mut items).unwrap_err().length, 2);
1272
            assert_eq!(items, vec![item(1), item(2)]);
1273
        }
1274
        for diff in [TimelineDiff::PopFront, TimelineDiff::PopBack] {
1275
            let mut items = Vec::new();
1276
            assert_eq!(diff.try_apply(&mut items).unwrap_err().length, 0);
1277
            assert!(items.is_empty());
1278
        }
1279
    }
1280
}
1281
1282
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1283
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1284
pub struct TimelineItemId(String);
1285
1286
impl TimelineItemId {
1287
    pub(crate) fn new(value: String) -> Self {
1288
        Self(value)
1289
    }
1290
1291
    #[must_use]
1292
    pub fn as_str(&self) -> &str {
1293
        &self.0
1294
    }
1295
}
1296
1297
#[derive(Clone, Debug, Eq, PartialEq)]
1298
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1299
#[non_exhaustive]
1300
pub struct TimelineEvent {
1301
    pub item_id: TimelineItemId,
1302
    pub event_id: Option<OwnedEventId>,
1303
    pub transaction_id: Option<OwnedTransactionId>,
1304
    pub sender: Sender,
1305
    pub timestamp_ms: u64,
1306
    pub own: bool,
1307
    pub send_state: SendState,
1308
    pub content: TimelineContent,
1309
    pub reply_to: Option<ReplyReference>,
1310
    pub thread_root: Option<OwnedEventId>,
1311
    pub thread_summary: Option<ThreadSummary>,
1312
    pub reactions: Vec<Reaction>,
1313
    pub read_by: Vec<OwnedUserId>,
1314
    pub editable: bool,
1315
}
1316
1317
impl TimelineEvent {
1318
    /// what to hand edit, redact and react. works before the server has echoed it back
1319
    #[must_use]
1320
    pub fn target(&self) -> Option<EventRef> {
1321
        self.event_id
1322
            .clone()
1323
            .map(EventRef::Remote)
1324
            .or_else(|| self.transaction_id.clone().map(EventRef::Local))
1325
    }
1326
}
1327
1328
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1329
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1330
#[non_exhaustive]
1331
pub enum EventRef {
1332
    Remote(OwnedEventId),
1333
    /// a local echo, by the transaction id it was queued under
1334
    Local(OwnedTransactionId),
1335
}
1336
1337
impl From<OwnedEventId> for EventRef {
1338
    fn from(event_id: OwnedEventId) -> Self {
1339
        Self::Remote(event_id)
1340
    }
1341
}
1342
1343
#[derive(Clone, Debug, Eq, PartialEq)]
1344
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1345
#[non_exhaustive]
1346
pub struct Sender {
1347
    pub user_id: OwnedUserId,
1348
    pub display_name: Option<String>,
1349
    pub avatar: Option<OwnedMxcUri>,
1350
    /// someone else in the room goes by the same name, so show the user id too
1351
    pub name_ambiguous: bool,
1352
}
1353
1354
impl Sender {
1355
    #[must_use]
1356
    pub fn name(&self) -> &str {
1357
        self.display_name
1358
            .as_deref()
1359
            .unwrap_or_else(|| self.user_id.as_str())
1360
    }
1361
}
1362
1363
#[derive(Clone, Debug, Eq, PartialEq)]
1364
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1365
#[non_exhaustive]
1366
pub enum TimelineContent {
1367
    Message(Message),
1368
    Sticker {
1369
        body: String,
1370
        media: MediaDescriptor,
1371
    },
1372
    Poll {
1373
        question: String,
1374
    },
1375
    Redacted,
1376
    UnableToDecrypt(UtdCause),
1377
    Membership {
1378
        user_id: OwnedUserId,
1379
        display_name: Option<String>,
1380
        change: MembershipChange,
1381
    },
1382
    Profile {
1383
        user_id: OwnedUserId,
1384
        display_name: Option<Change<Option<String>>>,
1385
        avatar: Option<Change<Option<OwnedMxcUri>>>,
1386
    },
1387
    /// `None` means it was cleared, or the event was redacted
1388
    RoomName(Option<String>),
1389
    RoomTopic(Option<String>),
1390
    RoomAvatar(Option<OwnedMxcUri>),
1391
    EncryptionEnabled,
1392
    RoomCreated,
1393
    RoomUpgraded {
1394
        successor: OwnedRoomId,
1395
    },
1396
    OtherState {
1397
        event_type: String,
1398
        state_key: String,
1399
    },
1400
    Other {
1401
        event_type: String,
1402
    },
1403
}
1404
1405
#[derive(Clone, Debug, Eq, PartialEq)]
1406
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1407
#[non_exhaustive]
1408
pub struct Message {
1409
    pub kind: MessageKind,
1410
    pub body: String,
1411
    /// only for `MessageKind::Location`
1412
    pub geo_uri: Option<String>,
1413
    pub formatted_body: Option<String>,
1414
    pub mentions: Option<MessageMentions>,
1415
    pub edited: bool,
1416
    pub media: Option<MediaDescriptor>,
1417
}
1418
1419
#[derive(Clone, Debug, Eq, PartialEq)]
1420
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1421
#[non_exhaustive]
1422
pub enum MessageKind {
1423
    Text,
1424
    Emote,
1425
    Notice,
1426
    ServerNotice,
1427
    Image,
1428
    Video,
1429
    Audio,
1430
    File,
1431
    Location,
1432
    VerificationRequest,
1433
    Other(String),
1434
}
1435
1436
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1437
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1438
#[non_exhaustive]
1439
pub enum MembershipChange {
1440
    Joined,
1441
    Left,
1442
    Banned,
1443
    Unbanned,
1444
    Kicked,
1445
    KickedAndBanned,
1446
    Invited,
1447
    InvitationAccepted,
1448
    InvitationRejected,
1449
    InvitationRevoked,
1450
    Knocked,
1451
    KnockAccepted,
1452
    KnockRetracted,
1453
    KnockDenied,
1454
    /// nothing a person would call a change, or something the sdk couldn't make sense of
1455
    Other,
1456
}
1457
1458
#[derive(Clone, Debug, Eq, PartialEq)]
1459
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1460
pub struct Change<T> {
1461
    pub old: T,
1462
    pub new: T,
1463
}
1464
1465
/// why a message couldn't be read, worth telling the user since some of these they can fix
1466
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1467
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1468
#[non_exhaustive]
1469
pub enum UtdCause {
1470
    Unknown,
1471
    SentBeforeWeJoined,
1472
    VerificationViolation,
1473
    UnsignedDevice,
1474
    UnknownDevice,
1475
    HistoricalMessageAndBackupIsDisabled,
1476
    WithheldForUnverifiedOrInsecureDevice,
1477
    WithheldBySender,
1478
    HistoricalMessageAndDeviceIsUnverified,
1479
}
1480
1481
#[derive(Clone, Debug, Eq, PartialEq)]
1482
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1483
#[non_exhaustive]
1484
pub struct ThreadSummary {
1485
    pub reply_count: u32,
1486
    pub latest_event_id: Option<OwnedEventId>,
1487
    pub latest_event_timestamp_ms: Option<u64>,
1488
}
1489
1490
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1491
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1492
#[non_exhaustive]
1493
pub enum SendState {
1494
    Sent,
1495
    Sending,
1496
    /// `will_retry` means macltok has it in hand. otherwise it's wedged until you
1497
    /// `retry_send` or `cancel_send`, so that's when to show a retry button
1498
    Failed {
1499
        will_retry: bool,
1500
    },
1501
}
1502
1503
#[derive(Clone, Debug, Eq, PartialEq)]
1504
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1505
#[non_exhaustive]
1506
pub struct ReplyReference {
1507
    pub event_id: OwnedEventId,
1508
    pub details: ReplyDetails,
1509
}
1510
1511
/// the replied-to event. macltok asks for it when it isn't loaded, `Pending` then turns into one of the others
1512
#[derive(Clone, Debug, Eq, PartialEq)]
1513
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1514
#[non_exhaustive]
1515
pub enum ReplyDetails {
1516
    Pending,
1517
    Ready {
1518
        sender: Sender,
1519
        content: Box<TimelineContent>,
1520
        timestamp_ms: u64,
1521
    },
1522
    Unavailable,
1523
}
1524
1525
#[derive(Clone, Debug, Eq, PartialEq)]
1526
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1527
#[non_exhaustive]
1528
pub struct Reaction {
1529
    pub key: String,
1530
    pub count: usize,
1531
    pub own: bool,
1532
    pub senders: Vec<OwnedUserId>,
1533
}
1534
1535
#[derive(Clone, Debug, Eq, PartialEq)]
1536
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1537
#[non_exhaustive]
1538
pub struct MediaDescriptor {
1539
    pub id: MediaId,
1540
    pub kind: MediaKind,
1541
    pub filename: String,
1542
    pub caption: Option<String>,
1543
    pub mimetype: Option<String>,
1544
    pub size_bytes: Option<u64>,
1545
    pub width: Option<u64>,
1546
    pub height: Option<u64>,
1547
    pub duration_ms: Option<u64>,
1548
    pub blurhash: Option<String>,
1549
    /// the uploader sent a thumbnail, so `MediaSize::Thumbnail` won't need the server to resize
1550
    pub has_thumbnail: bool,
1551
}
1552
1553
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1554
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1555
pub struct MediaId(String);
1556
1557
impl MediaId {
1558
    pub(crate) fn new(value: String) -> Self {
1559
        Self(value)
1560
    }
1561
1562
    #[must_use]
1563
    pub fn as_str(&self) -> &str {
1564
        &self.0
1565
    }
1566
}
1567
1568
/// media ids are opaque but they do have to survive a trip through a browser. a made up one just fails `MediaUnknown`
1569
impl std::str::FromStr for MediaId {
1570
    type Err = std::convert::Infallible;
1571
1572
    fn from_str(value: &str) -> Result<Self, Self::Err> {
1573
        Ok(Self(value.to_owned()))
1574
    }
1575
}
1576
1577
impl From<String> for MediaId {
1578
    fn from(value: String) -> Self {
1579
        Self(value)
1580
    }
1581
}
1582
1583
impl std::fmt::Display for MediaId {
1584
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1585
        self.0.fmt(formatter)
1586
    }
1587
}
1588
1589
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1590
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1591
#[non_exhaustive]
1592
pub enum MediaSize {
1593
    Full,
1594
    /// a hint. an uploader's own thumbnail wins over the server resizing anything
1595
    Thumbnail {
1596
        width: u32,
1597
        height: u32,
1598
    },
1599
}
1600
1601
#[derive(Clone, Debug, Eq, PartialEq)]
1602
#[non_exhaustive]
1603
pub struct Media {
1604
    pub bytes: Arc<[u8]>,
1605
    pub mimetype: String,
1606
}
1607
1608
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1609
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1610
#[non_exhaustive]
1611
pub enum MediaKind {
1612
    Image,
1613
    Video,
1614
    Audio,
1615
    File,
1616
    Sticker,
1617
}
1618
1619
#[derive(Clone, Debug, Eq, PartialEq)]
1620
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1621
#[non_exhaustive]
1622
pub struct TypingState {
1623
    pub room_id: OwnedRoomId,
1624
    pub users: Vec<OwnedUserId>,
1625
}
1626
1627
#[derive(Clone, Debug, Eq, PartialEq)]
1628
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1629
#[non_exhaustive]
1630
pub enum HistoryState {
1631
    Idle,
1632
    Loading,
1633
    StartReached,
1634
    Failed(String),
1635
}
1636
1637
#[derive(Clone, Debug, Eq, PartialEq)]
1638
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1639
#[non_exhaustive]
1640
pub struct EncryptionState {
1641
    pub device_id: OwnedDeviceId,
1642
    pub device_verified: bool,
1643
    pub recovery: RecoveryState,
1644
    pub key_backup: KeyBackupState,
1645
}
1646
1647
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1648
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1649
#[non_exhaustive]
1650
pub enum KeyBackupState {
1651
    Unknown,
1652
    Creating,
1653
    Enabling,
1654
    Resuming,
1655
    Downloading,
1656
    Enabled,
1657
    Disabling,
1658
}
1659
1660
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1661
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1662
#[non_exhaustive]
1663
pub enum RecoveryState {
1664
    Unknown,
1665
    Disabled,
1666
    Incomplete,
1667
    Enabled,
1668
}
1669
1670
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1671
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1672
#[non_exhaustive]
1673
pub enum VerificationAction {
1674
    /// take up a request another device sent, which arrives as `VerificationState::Incoming`
1675
    Accept,
1676
    Confirm,
1677
    Reject,
1678
    Cancel,
1679
}
1680
1681
#[derive(Clone, Debug, Eq, PartialEq)]
1682
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1683
#[non_exhaustive]
1684
pub enum VerificationTarget {
1685
    OwnIdentity,
1686
    User(OwnedUserId),
1687
    Device {
1688
        user_id: OwnedUserId,
1689
        device_id: OwnedDeviceId,
1690
    },
1691
}
1692
1693
#[derive(Clone, Debug, Eq, PartialEq)]
1694
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1695
#[non_exhaustive]
1696
pub enum VerificationState {
1697
    Waiting,
1698
    /// someone else asked. `Accept` to go ahead, `Cancel` to turn them down
1699
    Incoming {
1700
        user_id: OwnedUserId,
1701
        device_id: Option<OwnedDeviceId>,
1702
    },
1703
    Comparison {
1704
        emojis: Vec<(String, String)>,
1705
        decimals: (u16, u16, u16),
1706
    },
1707
    Confirmed,
1708
    Done,
1709
    Cancelled(String),
1710
    Failed(VerificationFailure),
1711
}
1712
1713
#[derive(Clone, Debug, Eq, PartialEq)]
1714
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1715
#[non_exhaustive]
1716
pub enum VerificationFailure {
1717
    RequestAcceptance(String),
1718
    SasStartup(String),
1719
    SasAcceptance(String),
1720
    RequestStreamEnded,
1721
    SasStreamEnded,
1722
}
1723
1724
#[derive(Clone, Debug, Eq, PartialEq)]
1725
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1726
#[non_exhaustive]
1727
pub struct EngineFailure {
1728
    pub kind: EngineErrorKind,
1729
    pub message: String,
1730
}
1731
1732
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1733
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1734
#[non_exhaustive]
1735
pub enum EngineErrorKind {
1736
    EventReceiverClosed,
1737
    Watcher,
1738
    Other,
1739
}