atagen

macltok

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