atagen

macltok

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