atagen

macltok

public
Star0
Watch0
06c73391cbaec25f3bfaacf44d54a9ac657ec4e9
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git
src/model.rsRust2234 lines63.9 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
    SendSticker {
413
        room_id: OwnedRoomId,
414
        pack_id: String,
415
        shortcode: String,
416
    },
417
    /// fails if the state key already holds a pack
418
    CreateRoomPack {
419
        room_id: OwnedRoomId,
420
        state_key: String,
421
        display_name: String,
422
    },
423
    /// empties the content, which is all deleting a pack can mean
424
    Delete(ImagePackSource),
425
    SetMeta {
426
        pack: ImagePackSource,
427
        display_name: Patch<String>,
428
        avatar: Patch<OwnedMxcUri>,
429
        usage: Patch<Vec<PackUsage>>,
430
    },
431
    /// adds or replaces by shortcode. a replaced image keeps its info unless the url changed
432
    PutImage {
433
        pack: ImagePackSource,
434
        shortcode: String,
435
        mxc: OwnedMxcUri,
436
        body: Option<String>,
437
        usage: Option<Vec<PackUsage>>,
438
        info: Option<PackImageInfo>,
439
    },
440
    /// fails if `to` is taken
441
    RenameImage {
442
        pack: ImagePackSource,
443
        from: String,
444
        to: String,
445
    },
446
    RemoveImage {
447
        pack: ImagePackSource,
448
        shortcode: String,
449
    },
450
    SetEnabledEverywhere {
451
        room_id: OwnedRoomId,
452
        state_key: String,
453
        enabled: bool,
454
    },
455
    /// answers with `CommandOutput::Mxc`, the same uri when it already lives on your homeserver
456
    Rehost(OwnedMxcUri),
457
    /// the rest answer with `CommandOutput::Cloned`. clashes get `-2`, `-3` and so on
458
    CloneImage {
459
        from_pack: String,
460
        shortcode: String,
461
        to: ImagePackSource,
462
        usage: Option<Vec<PackUsage>>,
463
    },
464
    CloneSticker {
465
        room_id: OwnedRoomId,
466
        event_id: OwnedEventId,
467
        to: ImagePackSource,
468
        shortcode: String,
469
        usage: Option<Vec<PackUsage>>,
470
    },
471
    /// makes the room pack if its state key is free, else merges. images that can't be
472
    /// fetched are skipped and listed, the rest are written
473
    ClonePack {
474
        from_pack: String,
475
        to: ImagePackSource,
476
        display_name: Option<String>,
477
        usage: Option<Vec<PackUsage>>,
478
    },
479
}
480
481
#[derive(Clone, Debug, Default, Eq, PartialEq)]
482
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
483
pub enum Patch<T> {
484
    #[default]
485
    Keep,
486
    Clear,
487
    Set(T),
488
}
489
490
#[derive(Clone, Debug, Default, Eq, PartialEq)]
491
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
492
#[non_exhaustive]
493
pub struct PackImageInfo {
494
    pub mimetype: Option<String>,
495
    pub size_bytes: Option<u64>,
496
    pub width: Option<u64>,
497
    pub height: Option<u64>,
498
}
499
500
impl PackImageInfo {
501
    #[must_use]
502
    pub fn new(
503
        mimetype: Option<String>,
504
        size_bytes: Option<u64>,
505
        width: Option<u64>,
506
        height: Option<u64>,
507
    ) -> Self {
508
        Self {
509
            mimetype,
510
            size_bytes,
511
            width,
512
            height,
513
        }
514
    }
515
}
516
517
#[derive(Clone, Debug, Eq, PartialEq)]
518
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
519
#[non_exhaustive]
520
pub struct AttachmentUpload {
521
    pub timeline_id: TimelineId,
522
    pub filename: String,
523
    pub mimetype: String,
524
    pub bytes: Vec<u8>,
525
    pub caption: Option<RichText>,
526
    pub mentions: MessageMentions,
527
    pub reply_to: Option<OwnedEventId>,
528
    pub notify_replied_to: bool,
529
    pub details: Option<UploadDetails>,
530
    pub thumbnail: Option<UploadThumbnail>,
531
}
532
533
impl AttachmentUpload {
534
    #[must_use]
535
    pub fn new(
536
        timeline_id: impl Into<TimelineId>,
537
        filename: impl Into<String>,
538
        mimetype: impl Into<String>,
539
        bytes: Vec<u8>,
540
    ) -> Self {
541
        Self {
542
            timeline_id: timeline_id.into(),
543
            filename: filename.into(),
544
            mimetype: mimetype.into(),
545
            bytes,
546
            caption: None,
547
            mentions: MessageMentions::default(),
548
            reply_to: None,
549
            notify_replied_to: true,
550
            details: None,
551
            thumbnail: None,
552
        }
553
    }
554
}
555
556
#[derive(Clone, Debug, Eq, PartialEq)]
557
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
558
#[non_exhaustive]
559
pub enum UploadDetails {
560
    Image {
561
        width: Option<u32>,
562
        height: Option<u32>,
563
        blurhash: Option<String>,
564
    },
565
    Video {
566
        width: Option<u32>,
567
        height: Option<u32>,
568
        duration_ms: Option<u64>,
569
        blurhash: Option<String>,
570
    },
571
    Audio {
572
        duration_ms: Option<u64>,
573
    },
574
    Voice {
575
        duration_ms: u64,
576
        waveform: Vec<u16>,
577
    },
578
    File,
579
}
580
581
#[derive(Clone, Debug, Eq, PartialEq)]
582
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
583
#[non_exhaustive]
584
pub struct UploadThumbnail {
585
    pub bytes: Vec<u8>,
586
    pub mimetype: String,
587
    pub width: u32,
588
    pub height: u32,
589
}
590
591
impl UploadThumbnail {
592
    #[must_use]
593
    pub fn new(bytes: Vec<u8>, mimetype: impl Into<String>, width: u32, height: u32) -> Self {
594
        Self {
595
            bytes,
596
            mimetype: mimetype.into(),
597
            width,
598
            height,
599
        }
600
    }
601
}
602
603
#[derive(Eq, PartialEq)]
604
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
605
#[non_exhaustive]
606
pub enum EncryptionCommand {
607
    Recover(String),
608
    CreateKeyBackup,
609
    EnableKeyBackup,
610
    DisableKeyBackup { delete_from_server: bool },
611
    RecoverKeyBackup(String),
612
    StartVerification(VerificationTarget),
613
    Verify(VerificationAction),
614
}
615
616
impl fmt::Debug for EncryptionCommand {
617
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
618
        match self {
619
            Self::Recover(_) => formatter.debug_tuple("Recover").field(&"...").finish(),
620
            Self::CreateKeyBackup => formatter.write_str("CreateKeyBackup"),
621
            Self::EnableKeyBackup => formatter.write_str("EnableKeyBackup"),
622
            Self::DisableKeyBackup { delete_from_server } => formatter
623
                .debug_struct("DisableKeyBackup")
624
                .field("delete_from_server", delete_from_server)
625
                .finish(),
626
            Self::RecoverKeyBackup(_) => formatter
627
                .debug_tuple("RecoverKeyBackup")
628
                .field(&"...")
629
                .finish(),
630
            Self::StartVerification(target) => formatter
631
                .debug_tuple("StartVerification")
632
                .field(target)
633
                .finish(),
634
            Self::Verify(action) => formatter.debug_tuple("Verify").field(action).finish(),
635
        }
636
    }
637
}
638
639
#[derive(Clone, Debug, Eq, PartialEq)]
640
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
641
#[non_exhaustive]
642
pub enum NotificationCommand {
643
    SetRoomMode {
644
        room_id: OwnedRoomId,
645
        mode: RoomNotificationMode,
646
    },
647
    ResetRoomMode(OwnedRoomId),
648
    SetDefaultMode {
649
        encrypted: bool,
650
        one_to_one: bool,
651
        mode: RoomNotificationMode,
652
    },
653
    AddKeyword(String),
654
    RemoveKeyword(String),
655
}
656
657
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
658
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
659
#[non_exhaustive]
660
pub enum LifecycleCommand {
661
    Shutdown,
662
}
663
664
#[derive(Clone, Debug, PartialEq)]
665
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
666
pub enum CommandOutput {
667
    Done,
668
    Room(OwnedRoomId),
669
    Mxc(OwnedMxcUri),
670
    /// the shortcodes the copies ended up under, and the ones that couldn't be fetched
671
    Cloned {
672
        shortcodes: Vec<String>,
673
        skipped: Vec<String>,
674
    },
675
    EventContext(EventContextSession),
676
    EventContextPage(EventContextPage),
677
    MentionsPage(crate::MentionsPage),
678
    MentionContext(crate::SavedMentionContext),
679
}
680
681
#[derive(Clone, Debug, Eq, PartialEq)]
682
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
683
#[non_exhaustive]
684
pub struct EventContext {
685
    pub events_before: Vec<TimelineItem>,
686
    pub event: TimelineItem,
687
    pub events_after: Vec<TimelineItem>,
688
    pub start_token: Option<String>,
689
    pub end_token: Option<String>,
690
}
691
692
/// a session's media stay resolvable until it closes, and past `EngineConfig::max_context_media`
693
/// its least recently used are dropped
694
#[derive(Clone, Debug, Eq, PartialEq)]
695
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
696
#[non_exhaustive]
697
pub struct EventContextSession {
698
    pub context_id: String,
699
    pub context: EventContext,
700
}
701
702
#[derive(Clone, Debug, Eq, PartialEq)]
703
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
704
#[non_exhaustive]
705
pub struct EventContextPage {
706
    pub events: Vec<TimelineItem>,
707
    /// `None` once that end of the room is reached
708
    pub next_token: Option<String>,
709
}
710
711
#[derive(Clone, Debug, Eq, PartialEq)]
712
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
713
#[non_exhaustive]
714
pub enum MessageContent {
715
    Text {
716
        content: RichText,
717
        mentions: MessageMentions,
718
    },
719
    Emote {
720
        content: RichText,
721
        mentions: MessageMentions,
722
    },
723
    /// m.notice, for bots. clients render it muted and never answer it automatically
724
    Notice {
725
        content: RichText,
726
        mentions: MessageMentions,
727
    },
728
    Reply {
729
        event_id: OwnedEventId,
730
        content: RichText,
731
        mentions: MessageMentions,
732
        notify_replied_to: bool,
733
    },
734
}
735
736
impl MessageContent {
737
    #[must_use]
738
    pub fn text(body: impl Into<String>) -> Self {
739
        Self::Text {
740
            content: RichText::plain(body),
741
            mentions: MessageMentions::default(),
742
        }
743
    }
744
745
    #[must_use]
746
    pub fn html(body: impl Into<String>, formatted_body: impl Into<String>) -> Self {
747
        Self::Text {
748
            content: RichText::html(body, formatted_body),
749
            mentions: MessageMentions::default(),
750
        }
751
    }
752
753
    #[must_use]
754
    pub fn emote(content: RichText, mentions: MessageMentions) -> Self {
755
        Self::Emote { content, mentions }
756
    }
757
758
    #[must_use]
759
    pub fn notice(content: RichText, mentions: MessageMentions) -> Self {
760
        Self::Notice { content, mentions }
761
    }
762
763
    #[must_use]
764
    pub fn reply(event_id: OwnedEventId, content: RichText, mentions: MessageMentions) -> Self {
765
        Self::Reply {
766
            event_id,
767
            content,
768
            mentions,
769
            notify_replied_to: true,
770
        }
771
    }
772
773
    #[must_use]
774
    pub fn reply_without_notification(
775
        event_id: OwnedEventId,
776
        content: RichText,
777
        mentions: MessageMentions,
778
    ) -> Self {
779
        Self::Reply {
780
            event_id,
781
            content,
782
            mentions,
783
            notify_replied_to: false,
784
        }
785
    }
786
}
787
788
#[derive(Clone, Debug, Eq, PartialEq)]
789
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
790
#[non_exhaustive]
791
pub enum MessageEditContent {
792
    Text {
793
        content: RichText,
794
        mentions: MessageMentions,
795
    },
796
    Emote {
797
        content: RichText,
798
        mentions: MessageMentions,
799
    },
800
}
801
802
impl MessageEditContent {
803
    #[must_use]
804
    pub fn text(body: impl Into<String>) -> Self {
805
        Self::Text {
806
            content: RichText::plain(body),
807
            mentions: MessageMentions::default(),
808
        }
809
    }
810
811
    #[must_use]
812
    pub fn html(body: impl Into<String>, formatted_body: impl Into<String>) -> Self {
813
        Self::Text {
814
            content: RichText::html(body, formatted_body),
815
            mentions: MessageMentions::default(),
816
        }
817
    }
818
819
    #[must_use]
820
    pub fn emote(content: RichText, mentions: MessageMentions) -> Self {
821
        Self::Emote { content, mentions }
822
    }
823
}
824
825
#[derive(Clone, Debug, Default, Eq, PartialEq)]
826
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
827
#[non_exhaustive]
828
pub struct RichText {
829
    pub body: String,
830
    pub formatted_body: Option<String>,
831
}
832
833
impl RichText {
834
    #[must_use]
835
    pub fn plain(body: impl Into<String>) -> Self {
836
        Self {
837
            body: body.into(),
838
            formatted_body: None,
839
        }
840
    }
841
842
    #[must_use]
843
    pub fn html(body: impl Into<String>, formatted_body: impl Into<String>) -> Self {
844
        Self {
845
            body: body.into(),
846
            formatted_body: Some(formatted_body.into()),
847
        }
848
    }
849
}
850
851
#[derive(Clone, Debug, Default, Eq, PartialEq)]
852
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
853
#[non_exhaustive]
854
pub struct MessageMentions {
855
    pub user_ids: Vec<OwnedUserId>,
856
    pub room: bool,
857
}
858
859
impl MessageMentions {
860
    #[must_use]
861
    pub fn with_user_ids(user_ids: impl IntoIterator<Item = OwnedUserId>) -> Self {
862
        Self {
863
            user_ids: user_ids.into_iter().collect(),
864
            room: false,
865
        }
866
    }
867
868
    #[must_use]
869
    pub fn room() -> Self {
870
        Self {
871
            user_ids: Vec::new(),
872
            room: true,
873
        }
874
    }
875
}
876
877
#[derive(Clone, Debug, PartialEq)]
878
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
879
pub enum Event {
880
    ConnectionChanged(ConnectionState),
881
    Authenticated {
882
        user_id: OwnedUserId,
883
    },
884
    /// the tokens rotated. with a `SessionStore` the record is already saved by now,
885
    /// without one persist a fresh `ClientHandle::session_record()` atomically
886
    SessionTokensChanged,
887
    /// the rotated tokens didn't reach the `SessionStore`, so the saved record may not
888
    /// restore. the engine tries again on the next rotation
889
    SessionSaveFailed {
890
        message: String,
891
    },
892
    /// the server stopped honouring our token and the engine stops. a soft logout
893
    /// names the device to log in again as, keeping the store. otherwise the record
894
    /// and the store are both dead
895
    SessionAccessRejected {
896
        soft_logout: Option<OwnedDeviceId>,
897
    },
898
    NotificationSettingsChanged,
899
    VerificationTargetChanged(VerificationTarget),
900
    RoomsChanged,
901
    MentionsChanged(crate::MentionsUpdate),
902
    /// an image pack came, went or changed somewhere. ask `image_packs` again
903
    ImagePacksChanged,
904
    /// replaces whatever you had for this timeline. every diff after it applies to it
905
    TimelineReset {
906
        timeline_id: TimelineId,
907
        items: Vector<TimelineItem>,
908
    },
909
    TimelineChanged {
910
        timeline_id: TimelineId,
911
        diffs: Vec<TimelineDiff>,
912
    },
913
    HistoryChanged {
914
        timeline_id: TimelineId,
915
        state: HistoryState,
916
    },
917
    RecentHistoryChanged {
918
        room_id: OwnedRoomId,
919
        state: RecentHistoryState,
920
    },
921
    HistoryRepairChanged(crate::HistoryRepairReport),
922
    #[doc(hidden)]
923
    PublicationBarrier {
924
        #[cfg_attr(feature = "serde", serde(skip))]
925
        acknowledgement: Option<crate::PublicationAck>,
926
    },
927
    /// the timeline was closed, or its room was left, and nothing more comes for it
928
    /// until another `TimelineReset`
929
    TimelineClosed {
930
        timeline_id: TimelineId,
931
    },
932
    /// a room that stops being watched says so with an empty `users`
933
    TypingChanged(TypingState),
934
    MediaUploadProgress {
935
        room_id: OwnedRoomId,
936
        transaction_id: OwnedTransactionId,
937
        uploaded_bytes: u64,
938
        total_bytes: u64,
939
        complete: bool,
940
    },
941
    /// not the end of it. `will_retry` means the send queue has another go by itself,
942
    /// otherwise it waits for `retry_send` or `cancel_send`
943
    MediaUploadFailed {
944
        room_id: OwnedRoomId,
945
        transaction_id: OwnedTransactionId,
946
        kind: crate::ErrorKind,
947
        will_retry: bool,
948
    },
949
    /// an upload that turned up in a progress or failure event gets exactly one of
950
    /// these while the engine runs, and nothing about it after. stopping ends
951
    /// nothing, `Stopped` covers whatever is still going and the sdk resumes it next run
952
    MediaUploadFinished {
953
        room_id: OwnedRoomId,
954
        transaction_id: OwnedTransactionId,
955
        outcome: UploadOutcome,
956
    },
957
    EncryptionChanged(EncryptionState),
958
    VerificationChanged(VerificationState),
959
    /// logout went through and the engine stops. delete the record and the store
960
    LoggedOut,
961
    Failed(EngineFailure),
962
    /// always the last event. keep the saved record unless `LoggedOut` or a
963
    /// hard `SessionAccessRejected` came first. commands still in flight answer `Interrupted`
964
    Stopped,
965
}
966
967
#[derive(Clone, Debug, Eq, PartialEq)]
968
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
969
pub enum UploadOutcome {
970
    Sent {
971
        event_id: OwnedEventId,
972
    },
973
    Cancelled,
974
    /// its room was forgotten, and the queue with it
975
    RoomForgotten,
976
    /// the sdk's update channel overflowed while it ended, so whether it was sent is unknown
977
    Missed,
978
}
979
980
/// why `Engine::run` came back, when nothing went wrong
981
#[derive(Clone, Debug, Eq, PartialEq)]
982
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
983
pub enum Termination {
984
    ShutDown,
985
    /// every `ClientHandle` was dropped, so nobody could have asked for anything else
986
    HandlesDropped,
987
    LoggedOut,
988
    /// the server rejected our token for good
989
    AccessRevoked,
990
    /// the server wants this device to log in again, and its e2ee keys live in the store
991
    SoftLoggedOut {
992
        device_id: OwnedDeviceId,
993
    },
994
}
995
996
impl Termination {
997
    #[must_use]
998
    pub const fn retain(&self) -> Retain {
999
        match self {
1000
            Self::ShutDown | Self::HandlesDropped => Retain::RecordAndStore,
1001
            Self::SoftLoggedOut { .. } => Retain::Store,
1002
            Self::LoggedOut | Self::AccessRevoked => Retain::Nothing,
1003
        }
1004
    }
1005
}
1006
1007
/// what's still worth keeping of the saved record and the store
1008
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1009
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1010
pub enum Retain {
1011
    RecordAndStore,
1012
    /// keep the store and a record naming the device to log in again as
1013
    Store,
1014
    Nothing,
1015
}
1016
1017
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1018
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1019
pub enum ConnectionState {
1020
    Idle,
1021
    Connecting,
1022
    Online,
1023
    Offline,
1024
    Stopped,
1025
}
1026
1027
#[derive(Clone, Debug, Eq, PartialEq)]
1028
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1029
#[non_exhaustive]
1030
pub struct RoomSummary {
1031
    pub room_id: OwnedRoomId,
1032
    pub name: String,
1033
    pub membership: RoomMembership,
1034
    pub unread_messages: u64,
1035
    pub unread_mentions: u64,
1036
    /// unread events the push rules said to notify about, which is neither of the above
1037
    pub unread_notifications: u64,
1038
    pub encrypted: bool,
1039
    pub space: bool,
1040
    pub direct: bool,
1041
    pub favourite: bool,
1042
    pub low_priority: bool,
1043
    pub avatar: Option<MediaId>,
1044
    pub latest_event_timestamp_ms: Option<u64>,
1045
    pub latest_event: Option<LatestEvent>,
1046
    pub notification_mode: Option<RoomNotificationMode>,
1047
    pub notification_mode_custom: bool,
1048
    pub topic: Option<String>,
1049
    pub canonical_alias: Option<OwnedRoomAliasId>,
1050
    pub joined_members: u64,
1051
    pub invited_members: u64,
1052
    /// who a nameless room gets named after
1053
    pub heroes: Vec<RoomHero>,
1054
    /// set once the room has been upgraded, this is where everyone went
1055
    pub successor: Option<OwnedRoomId>,
1056
    pub inviter: Option<OwnedUserId>,
1057
    /// joined spaces that list this room as a child
1058
    pub parent_spaces: Vec<OwnedRoomId>,
1059
    /// for a space, the children it lists, joined or not
1060
    pub children: Vec<OwnedRoomId>,
1061
    /// a space's msc3230 order. ordered spaces sort first by (order, room id), the rest by room id
1062
    pub space_order: Option<String>,
1063
    /// you can send im.ponies.room_emotes here, so you can make and edit its packs
1064
    pub can_edit_packs: bool,
1065
    /// m.room.pinned_events in order, the newest pin last
1066
    pub pinned_events: Vec<OwnedEventId>,
1067
    pub can_pin: bool,
1068
}
1069
1070
#[derive(Clone, Debug, Eq, PartialEq)]
1071
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1072
#[non_exhaustive]
1073
pub struct RoomHero {
1074
    pub user_id: OwnedUserId,
1075
    pub display_name: Option<String>,
1076
    pub avatar: Option<MediaId>,
1077
}
1078
1079
/// enough for a room list preview line. `kind` and `body` are only set for messages,
1080
/// and an edit shows its new text
1081
#[derive(Clone, Debug, Eq, PartialEq)]
1082
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1083
#[non_exhaustive]
1084
pub struct LatestEvent {
1085
    pub sender: Option<OwnedUserId>,
1086
    pub kind: Option<MessageKind>,
1087
    pub body: Option<String>,
1088
    pub timestamp_ms: Option<u64>,
1089
    pub send_state: SendState,
1090
}
1091
1092
#[derive(Clone, Debug, Eq, PartialEq)]
1093
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1094
#[non_exhaustive]
1095
pub struct Profile {
1096
    pub user_id: OwnedUserId,
1097
    pub display_name: Option<String>,
1098
    pub avatar: Option<MediaId>,
1099
}
1100
1101
/// one room in a space's hierarchy, as the server describes it, which may be a room you're not in
1102
#[derive(Clone, Debug, Eq, PartialEq)]
1103
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1104
#[non_exhaustive]
1105
pub struct SpaceChild {
1106
    pub room_id: OwnedRoomId,
1107
    pub name: String,
1108
    pub topic: Option<String>,
1109
    pub avatar: Option<MediaId>,
1110
    pub canonical_alias: Option<OwnedRoomAliasId>,
1111
    pub joined_members: u64,
1112
    pub space: bool,
1113
    pub children_count: u64,
1114
    pub membership: Option<RoomMembership>,
1115
    pub via: Vec<OwnedServerName>,
1116
    pub suggested: bool,
1117
    pub world_readable: Option<bool>,
1118
    pub guest_can_join: bool,
1119
}
1120
1121
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1122
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1123
pub enum RoomNotificationMode {
1124
    AllMessages,
1125
    MentionsAndKeywordsOnly,
1126
    Mute,
1127
}
1128
1129
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1130
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1131
#[non_exhaustive]
1132
pub struct RoomNotificationSettings {
1133
    pub mode: RoomNotificationMode,
1134
    pub custom: bool,
1135
}
1136
1137
#[derive(Clone, Debug)]
1138
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1139
pub enum PushNotificationStatus {
1140
    Event(Box<PushNotification>),
1141
    NotFound,
1142
    FilteredOut,
1143
    Redacted,
1144
}
1145
1146
#[derive(Clone, Debug)]
1147
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1148
#[non_exhaustive]
1149
pub struct PushNotification {
1150
    pub event_id: OwnedEventId,
1151
    pub event: PushNotificationEvent,
1152
    pub sender: PushNotificationSender,
1153
    pub room: PushNotificationRoom,
1154
    pub noisy: Option<bool>,
1155
    pub has_mention: Option<bool>,
1156
    pub thread_id: Option<OwnedEventId>,
1157
}
1158
1159
#[derive(Clone, Debug, Eq, PartialEq)]
1160
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1161
#[non_exhaustive]
1162
pub struct PushNotificationSender {
1163
    pub user_id: OwnedUserId,
1164
    pub display_name: Option<String>,
1165
    pub avatar_url: Option<MediaId>,
1166
    pub name_ambiguous: bool,
1167
}
1168
1169
#[derive(Clone, Debug, Eq, PartialEq)]
1170
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1171
#[non_exhaustive]
1172
pub struct PushNotificationRoom {
1173
    pub room_id: OwnedRoomId,
1174
    pub name: String,
1175
    pub avatar_url: Option<MediaId>,
1176
    pub canonical_alias: Option<OwnedRoomAliasId>,
1177
    pub topic: Option<String>,
1178
    pub encrypted: Option<bool>,
1179
    pub direct: bool,
1180
    pub joined_members_count: u64,
1181
    pub service_members: Vec<OwnedUserId>,
1182
    pub active_service_members_count: u64,
1183
    pub space: bool,
1184
}
1185
1186
#[derive(Clone, Debug)]
1187
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1188
pub enum PushNotificationEvent {
1189
    Timeline(Raw<AnySyncTimelineEvent>),
1190
    Invite(Raw<StrippedRoomMemberEvent>),
1191
}
1192
1193
#[derive(Clone, Debug, Eq, PartialEq)]
1194
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1195
#[non_exhaustive]
1196
pub struct RoomPowerLevels {
1197
    pub ban: i64,
1198
    pub invite: i64,
1199
    pub kick: i64,
1200
    pub redact: i64,
1201
    pub events_default: i64,
1202
    pub state_default: i64,
1203
    pub users_default: i64,
1204
    pub room_notification: i64,
1205
    pub users: Vec<(OwnedUserId, i64)>,
1206
    pub events: Vec<(String, i64)>,
1207
    /// in rooms from version 12 the creators outrank everyone and aren't listed in `users`
1208
    pub creators: Vec<OwnedUserId>,
1209
}
1210
1211
#[derive(Clone, Debug, Default, Eq, PartialEq)]
1212
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1213
#[non_exhaustive]
1214
pub struct PowerLevelChanges {
1215
    pub ban: Option<i64>,
1216
    pub invite: Option<i64>,
1217
    pub kick: Option<i64>,
1218
    pub redact: Option<i64>,
1219
    pub events_default: Option<i64>,
1220
    pub state_default: Option<i64>,
1221
    pub users_default: Option<i64>,
1222
    pub room_notification: Option<i64>,
1223
    pub room_name: Option<i64>,
1224
    pub room_avatar: Option<i64>,
1225
    pub room_topic: Option<i64>,
1226
    pub space_child: Option<i64>,
1227
    pub beacon: Option<i64>,
1228
    pub beacon_info: Option<i64>,
1229
}
1230
1231
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1232
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1233
pub enum RoomMembership {
1234
    Joined,
1235
    Invited,
1236
    Left,
1237
    Knocked,
1238
    Banned,
1239
}
1240
1241
#[derive(Clone, Debug, Default, Eq, PartialEq)]
1242
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1243
#[non_exhaustive]
1244
pub struct RoomListFilter {
1245
    pub membership: Option<RoomMembership>,
1246
    pub category: Option<RoomCategory>,
1247
    pub favourite: Option<bool>,
1248
    pub unread_only: bool,
1249
    pub search: Option<String>,
1250
}
1251
1252
impl RoomListFilter {
1253
    #[must_use]
1254
    pub fn with_membership(mut self, membership: RoomMembership) -> Self {
1255
        self.membership = Some(membership);
1256
        self
1257
    }
1258
1259
    #[must_use]
1260
    pub fn with_category(mut self, category: RoomCategory) -> Self {
1261
        self.category = Some(category);
1262
        self
1263
    }
1264
1265
    #[must_use]
1266
    pub fn with_favourite(mut self, favourite: bool) -> Self {
1267
        self.favourite = Some(favourite);
1268
        self
1269
    }
1270
1271
    #[must_use]
1272
    pub const fn with_unread_only(mut self, unread_only: bool) -> Self {
1273
        self.unread_only = unread_only;
1274
        self
1275
    }
1276
1277
    #[must_use]
1278
    pub fn with_search(mut self, search: impl Into<String>) -> Self {
1279
        self.search = Some(search.into());
1280
        self
1281
    }
1282
1283
    #[must_use]
1284
    pub fn matches(&self, room: &RoomSummary) -> bool {
1285
        self.matcher().matches(room)
1286
    }
1287
1288
    /// lowercases the search once, for filtering a whole list
1289
    #[must_use]
1290
    pub fn matcher(&self) -> RoomMatcher<'_> {
1291
        RoomMatcher {
1292
            filter: self,
1293
            search: self.search.as_deref().map(str::to_lowercase),
1294
        }
1295
    }
1296
}
1297
1298
#[derive(Debug)]
1299
pub struct RoomMatcher<'a> {
1300
    filter: &'a RoomListFilter,
1301
    search: Option<String>,
1302
}
1303
1304
impl RoomMatcher<'_> {
1305
    #[must_use]
1306
    pub fn matches(&self, room: &RoomSummary) -> bool {
1307
        let filter = self.filter;
1308
        filter
1309
            .membership
1310
            .is_none_or(|membership| room.membership == membership)
1311
            && filter.category.is_none_or(|category| match category {
1312
                RoomCategory::People => room.direct && !room.space,
1313
                RoomCategory::Rooms => !room.direct && !room.space,
1314
                RoomCategory::Spaces => room.space,
1315
            })
1316
            && filter
1317
                .favourite
1318
                .is_none_or(|favourite| room.favourite == favourite)
1319
            && (!filter.unread_only || room.unread_messages > 0 || room.unread_mentions > 0)
1320
            && self.search.as_ref().is_none_or(|search| {
1321
                room.name.to_lowercase().contains(search)
1322
                    || room.room_id.as_str().to_lowercase().contains(search)
1323
            })
1324
    }
1325
}
1326
1327
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1328
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1329
#[non_exhaustive]
1330
pub enum RoomCategory {
1331
    People,
1332
    Rooms,
1333
    Spaces,
1334
}
1335
1336
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1337
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1338
#[non_exhaustive]
1339
pub enum MemberFilter {
1340
    Active,
1341
    Joined,
1342
    Invited,
1343
    Banned,
1344
    Left,
1345
    All,
1346
}
1347
1348
#[derive(Clone, Debug, Eq, PartialEq)]
1349
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1350
pub enum MemberMembership {
1351
    Joined,
1352
    Invited,
1353
    Left,
1354
    Knocked,
1355
    Banned,
1356
    Custom(String),
1357
}
1358
1359
#[derive(Clone, Debug, Eq, PartialEq)]
1360
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1361
#[non_exhaustive]
1362
pub struct MemberSummary {
1363
    pub user_id: OwnedUserId,
1364
    pub name: String,
1365
    pub display_name: Option<String>,
1366
    pub avatar: Option<MediaId>,
1367
    pub membership: MemberMembership,
1368
    pub own: bool,
1369
    pub name_ambiguous: bool,
1370
    pub ignored: bool,
1371
    pub service: bool,
1372
}
1373
1374
#[derive(Clone, Debug, Eq, PartialEq)]
1375
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1376
#[non_exhaustive]
1377
pub struct OwnDevice {
1378
    pub device_id: OwnedDeviceId,
1379
    pub display_name: Option<String>,
1380
    pub last_seen_ip: Option<String>,
1381
    pub last_seen_timestamp_ms: Option<u64>,
1382
    pub current: bool,
1383
}
1384
1385
#[derive(Clone, Debug, Eq, PartialEq)]
1386
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1387
pub enum TimelineItem {
1388
    Event(Box<TimelineEvent>),
1389
    HistoryGap(crate::HistoryGap),
1390
    DayDivider { timestamp_ms: u64 },
1391
    ReadMarker,
1392
    TimelineStart,
1393
}
1394
1395
#[derive(Clone, Debug, Eq, PartialEq)]
1396
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1397
pub enum TimelineDiff {
1398
    Append { values: Vec<TimelineItem> },
1399
    Clear,
1400
    PushFront { value: TimelineItem },
1401
    PushBack { value: TimelineItem },
1402
    PopFront,
1403
    PopBack,
1404
    Insert { index: usize, value: TimelineItem },
1405
    Set { index: usize, value: TimelineItem },
1406
    Remove { index: usize },
1407
    Truncate { length: usize },
1408
    Reset { values: Vec<TimelineItem> },
1409
}
1410
1411
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
1412
#[error("timeline diff is incompatible with the current {length}-item snapshot")]
1413
pub struct TimelineDiffError {
1414
    pub length: usize,
1415
}
1416
1417
impl TimelineDiff {
1418
    /// Apply a diff only when its indices match the current snapshot.
1419
    /// On error the snapshot is unchanged; request `TimelineCommand::Resync`
1420
    /// and ignore further diffs until the corresponding `TimelineReset`.
1421
    pub fn try_apply(self, items: &mut Vector<TimelineItem>) -> Result<(), TimelineDiffError> {
1422
        let length = items.len();
1423
        if self.length_after(length).is_none() {
1424
            return Err(TimelineDiffError { length });
1425
        }
1426
        self.apply(items);
1427
        Ok(())
1428
    }
1429
1430
    /// a whole `TimelineChanged` or none of it. whether a diff fits depends only on the
1431
    /// length before it, so the batch is checked against lengths alone before anything
1432
    /// moves. the error carries the length the snapshot would have had at the misfit
1433
    pub fn try_apply_all(
1434
        diffs: Vec<Self>,
1435
        items: &mut Vector<TimelineItem>,
1436
    ) -> Result<(), TimelineDiffError> {
1437
        diffs.iter().try_fold(items.len(), |length, diff| {
1438
            diff.length_after(length)
1439
                .ok_or(TimelineDiffError { length })
1440
        })?;
1441
        for diff in diffs {
1442
            diff.apply(items);
1443
        }
1444
        Ok(())
1445
    }
1446
1447
    fn length_after(&self, length: usize) -> Option<usize> {
1448
        match self {
1449
            Self::Append { values } => Some(length + values.len()),
1450
            Self::Clear => Some(0),
1451
            Self::PushFront { .. } | Self::PushBack { .. } => Some(length + 1),
1452
            Self::PopFront | Self::PopBack => length.checked_sub(1),
1453
            Self::Insert { index, .. } => (*index <= length).then_some(length + 1),
1454
            Self::Set { index, .. } => (*index < length).then_some(length),
1455
            Self::Remove { index } => (*index < length).then(|| length - 1),
1456
            Self::Truncate { length: target } => (*target <= length).then_some(*target),
1457
            Self::Reset { values } => Some(values.len()),
1458
        }
1459
    }
1460
1461
    fn apply(self, items: &mut Vector<TimelineItem>) {
1462
        match self {
1463
            Self::Append { values } => items.extend(values),
1464
            Self::Clear => items.clear(),
1465
            Self::PushFront { value } => items.push_front(value),
1466
            Self::PushBack { value } => items.push_back(value),
1467
            Self::PopFront => {
1468
                items.pop_front();
1469
            }
1470
            Self::PopBack => {
1471
                items.pop_back();
1472
            }
1473
            Self::Insert { index, value } => items.insert(index, value),
1474
            Self::Set { index, value } => {
1475
                items.set(index, value);
1476
            }
1477
            Self::Remove { index } => {
1478
                items.remove(index);
1479
            }
1480
            Self::Truncate { length } => items.truncate(length),
1481
            Self::Reset { values } => *items = values.into_iter().collect(),
1482
        }
1483
    }
1484
}
1485
1486
#[cfg(test)]
1487
mod tests {
1488
    use imbl::{Vector, vector};
1489
1490
    use super::{TimelineDiff, TimelineItem};
1491
1492
    fn item(timestamp_ms: u64) -> TimelineItem {
1493
        TimelineItem::DayDivider { timestamp_ms }
1494
    }
1495
1496
    #[test]
1497
    fn timeline_diff_try_apply_handles_every_variant() {
1498
        let mut items = vector![item(1), item(2)];
1499
1500
        TimelineDiff::Append {
1501
            values: vec![item(3)],
1502
        }
1503
        .try_apply(&mut items)
1504
        .unwrap();
1505
        assert_eq!(items, vector![item(1), item(2), item(3)]);
1506
1507
        TimelineDiff::Clear.try_apply(&mut items).unwrap();
1508
        assert!(items.is_empty());
1509
1510
        TimelineDiff::PushFront { value: item(2) }
1511
            .try_apply(&mut items)
1512
            .unwrap();
1513
        TimelineDiff::PushBack { value: item(3) }
1514
            .try_apply(&mut items)
1515
            .unwrap();
1516
        assert_eq!(items, vector![item(2), item(3)]);
1517
1518
        TimelineDiff::PopFront.try_apply(&mut items).unwrap();
1519
        TimelineDiff::PopBack.try_apply(&mut items).unwrap();
1520
        assert!(items.is_empty());
1521
1522
        TimelineDiff::Reset {
1523
            values: vec![item(1), item(3)],
1524
        }
1525
        .try_apply(&mut items)
1526
        .unwrap();
1527
        TimelineDiff::Insert {
1528
            index: 1,
1529
            value: item(2),
1530
        }
1531
        .try_apply(&mut items)
1532
        .unwrap();
1533
        assert_eq!(items, vector![item(1), item(2), item(3)]);
1534
1535
        TimelineDiff::Set {
1536
            index: 1,
1537
            value: item(4),
1538
        }
1539
        .try_apply(&mut items)
1540
        .unwrap();
1541
        assert_eq!(items, vector![item(1), item(4), item(3)]);
1542
1543
        TimelineDiff::Remove { index: 1 }
1544
            .try_apply(&mut items)
1545
            .unwrap();
1546
        assert_eq!(items, vector![item(1), item(3)]);
1547
1548
        TimelineDiff::Truncate { length: 1 }
1549
            .try_apply(&mut items)
1550
            .unwrap();
1551
        assert_eq!(items, vector![item(1)]);
1552
    }
1553
1554
    #[test]
1555
    fn invalid_timeline_diff_leaves_snapshot_unchanged() {
1556
        let invalid = [
1557
            TimelineDiff::Insert {
1558
                index: 3,
1559
                value: item(3),
1560
            },
1561
            TimelineDiff::Set {
1562
                index: 2,
1563
                value: item(3),
1564
            },
1565
            TimelineDiff::Remove { index: 2 },
1566
            TimelineDiff::Truncate { length: 3 },
1567
        ];
1568
        for diff in invalid {
1569
            let mut items = vector![item(1), item(2)];
1570
            assert_eq!(diff.try_apply(&mut items).unwrap_err().length, 2);
1571
            assert_eq!(items, vector![item(1), item(2)]);
1572
        }
1573
        for diff in [TimelineDiff::PopFront, TimelineDiff::PopBack] {
1574
            let mut items = Vector::new();
1575
            assert_eq!(diff.try_apply(&mut items).unwrap_err().length, 0);
1576
            assert!(items.is_empty());
1577
        }
1578
    }
1579
1580
    #[test]
1581
    fn a_batch_that_goes_wrong_halfway_changes_nothing() {
1582
        let mut items = vector![item(1), item(2)];
1583
        let batch = vec![
1584
            TimelineDiff::PushBack { value: item(3) },
1585
            TimelineDiff::PushBack { value: item(4) },
1586
            TimelineDiff::Remove { index: 0 },
1587
            TimelineDiff::Set {
1588
                index: 3,
1589
                value: item(5),
1590
            },
1591
        ];
1592
        assert_eq!(
1593
            TimelineDiff::try_apply_all(batch, &mut items)
1594
                .unwrap_err()
1595
                .length,
1596
            3
1597
        );
1598
        assert_eq!(items, vector![item(1), item(2)]);
1599
1600
        let batch = vec![
1601
            TimelineDiff::PushBack { value: item(3) },
1602
            TimelineDiff::Remove { index: 0 },
1603
            TimelineDiff::Set {
1604
                index: 1,
1605
                value: item(4),
1606
            },
1607
        ];
1608
        TimelineDiff::try_apply_all(batch, &mut items).unwrap();
1609
        assert_eq!(items, vector![item(2), item(4)]);
1610
    }
1611
}
1612
1613
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1614
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1615
pub struct TimelineItemId(String);
1616
1617
impl TimelineItemId {
1618
    pub(crate) fn new(value: String) -> Self {
1619
        Self(value)
1620
    }
1621
1622
    #[must_use]
1623
    pub fn as_str(&self) -> &str {
1624
        &self.0
1625
    }
1626
}
1627
1628
#[derive(Clone, Debug, Eq, PartialEq)]
1629
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1630
#[non_exhaustive]
1631
pub struct TimelineEvent {
1632
    pub item_id: TimelineItemId,
1633
    pub event_id: Option<OwnedEventId>,
1634
    pub transaction_id: Option<OwnedTransactionId>,
1635
    pub sender: Sender,
1636
    pub timestamp_ms: u64,
1637
    pub own: bool,
1638
    pub send_state: SendState,
1639
    pub content: TimelineContent,
1640
    pub reply_to: Option<ReplyReference>,
1641
    pub thread_root: Option<OwnedEventId>,
1642
    pub thread_summary: Option<ThreadSummary>,
1643
    pub reactions: Vec<Reaction>,
1644
    pub read_by: Vec<OwnedUserId>,
1645
    pub editable: bool,
1646
    /// the push rules ask for this one to stand out, always false for a local echo
1647
    pub highlight: 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
    /// nothing running and nothing to show, which is also what closing the room leaves
2129
    Idle,
2130
    Loading,
2131
    Loaded,
2132
    Cancelled,
2133
    /// stays until a retry or the room is reopened
2134
    Failed(String),
2135
}
2136
2137
#[derive(Clone, Debug, Eq, PartialEq)]
2138
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2139
#[non_exhaustive]
2140
pub struct EncryptionState {
2141
    pub device_id: OwnedDeviceId,
2142
    pub device_verified: bool,
2143
    pub recovery: RecoveryState,
2144
    pub key_backup: KeyBackupState,
2145
}
2146
2147
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2148
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2149
pub enum KeyBackupState {
2150
    Unknown,
2151
    Creating,
2152
    Enabling,
2153
    Resuming,
2154
    Downloading,
2155
    Enabled,
2156
    Disabling,
2157
}
2158
2159
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2160
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2161
pub enum RecoveryState {
2162
    Unknown,
2163
    Disabled,
2164
    Incomplete,
2165
    Enabled,
2166
}
2167
2168
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2169
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2170
#[non_exhaustive]
2171
pub enum VerificationAction {
2172
    /// take up a request another device sent, which arrives as `VerificationState::Incoming`
2173
    Accept,
2174
    Confirm,
2175
    Reject,
2176
    Cancel,
2177
}
2178
2179
#[derive(Clone, Debug, Eq, PartialEq)]
2180
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2181
#[non_exhaustive]
2182
pub enum VerificationTarget {
2183
    OwnIdentity,
2184
    User(OwnedUserId),
2185
    Device {
2186
        user_id: OwnedUserId,
2187
        device_id: OwnedDeviceId,
2188
    },
2189
}
2190
2191
#[derive(Clone, Debug, Eq, PartialEq)]
2192
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2193
pub enum VerificationState {
2194
    Waiting,
2195
    /// someone else asked. `Accept` to go ahead, `Cancel` to turn them down
2196
    Incoming {
2197
        user_id: OwnedUserId,
2198
        device_id: Option<OwnedDeviceId>,
2199
    },
2200
    Comparison {
2201
        emojis: Vec<(String, String)>,
2202
        decimals: (u16, u16, u16),
2203
    },
2204
    Confirmed,
2205
    Done,
2206
    Cancelled(String),
2207
    Failed(VerificationFailure),
2208
}
2209
2210
#[derive(Clone, Debug, Eq, PartialEq)]
2211
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2212
pub enum VerificationFailure {
2213
    RequestAcceptance(String),
2214
    SasStartup(String),
2215
    SasAcceptance(String),
2216
    RequestStreamEnded,
2217
    SasStreamEnded,
2218
}
2219
2220
#[derive(Clone, Debug, Eq, PartialEq)]
2221
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2222
#[non_exhaustive]
2223
pub struct EngineFailure {
2224
    pub kind: EngineErrorKind,
2225
    pub message: String,
2226
}
2227
2228
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2229
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2230
pub enum EngineErrorKind {
2231
    EventReceiverClosed,
2232
    Watcher,
2233
    Other,
2234
}