atagen

macltok

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