atagen

macltok

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