atagen

macltok

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