atagen

macltok

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