atagen

macltok

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