atagen

macltok

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