atagen

macltok

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