atagen

macltok

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