atagen

macltok

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