atagen

macltok

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