atagen

macltok

public
Star0
Watch0
66db1b3cd8955da257726f2f3028b931ba34c3c0
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git
src/model.rsRust2349 lines67.7 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
    },
986
    /// a room that stops being watched says so with an empty `users`
987
    TypingChanged(TypingState),
988
    MediaUploadProgress {
989
        room_id: OwnedRoomId,
990
        transaction_id: OwnedTransactionId,
991
        uploaded_bytes: u64,
992
        total_bytes: u64,
993
        complete: bool,
994
    },
995
    /// not the end of it. `will_retry` means the send queue has another go by itself,
996
    /// otherwise it waits for `retry_send` or `cancel_send`
997
    MediaUploadFailed {
998
        room_id: OwnedRoomId,
999
        transaction_id: OwnedTransactionId,
1000
        kind: crate::ErrorKind,
1001
        will_retry: bool,
1002
    },
1003
    /// an upload that turned up in a progress or failure event gets exactly one of
1004
    /// these while the engine runs, and nothing about it after. stopping ends
1005
    /// nothing, `Stopped` covers whatever is still going and the sdk resumes it next run
1006
    MediaUploadFinished {
1007
        room_id: OwnedRoomId,
1008
        transaction_id: OwnedTransactionId,
1009
        outcome: UploadOutcome,
1010
    },
1011
    EncryptionChanged(EncryptionState),
1012
    VerificationChanged(VerificationState),
1013
    /// logout went through and the engine stops. delete the record and the store
1014
    LoggedOut,
1015
    Failed(EngineFailure),
1016
    /// always the last event. keep the saved record unless `LoggedOut` or a
1017
    /// hard `SessionAccessRejected` came first. commands still in flight answer `Interrupted`
1018
    Stopped,
1019
}
1020
1021
#[derive(Clone, Debug, Eq, PartialEq)]
1022
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1023
pub enum UploadOutcome {
1024
    Sent {
1025
        event_id: OwnedEventId,
1026
    },
1027
    Cancelled,
1028
    /// its room was forgotten, and the queue with it
1029
    RoomForgotten,
1030
    /// the sdk's update channel overflowed while it ended, so whether it was sent is unknown
1031
    Missed,
1032
}
1033
1034
/// why `Engine::run` came back, when nothing went wrong
1035
#[derive(Clone, Debug, Eq, PartialEq)]
1036
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1037
pub enum Termination {
1038
    ShutDown,
1039
    /// every `ClientHandle` was dropped, so nobody could have asked for anything else
1040
    HandlesDropped,
1041
    LoggedOut,
1042
    /// the server rejected our token for good
1043
    AccessRevoked,
1044
    /// the server wants this device to log in again, and its e2ee keys live in the store
1045
    SoftLoggedOut {
1046
        device_id: OwnedDeviceId,
1047
    },
1048
}
1049
1050
impl Termination {
1051
    #[must_use]
1052
    pub const fn retain(&self) -> Retain {
1053
        match self {
1054
            Self::ShutDown | Self::HandlesDropped => Retain::RecordAndStore,
1055
            Self::SoftLoggedOut { .. } => Retain::Store,
1056
            Self::LoggedOut | Self::AccessRevoked => Retain::Nothing,
1057
        }
1058
    }
1059
}
1060
1061
/// what's still worth keeping of the saved record and the store
1062
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1063
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1064
pub enum Retain {
1065
    RecordAndStore,
1066
    /// keep the store and a record naming the device to log in again as
1067
    Store,
1068
    Nothing,
1069
}
1070
1071
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1072
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1073
pub enum ConnectionState {
1074
    Idle,
1075
    Connecting,
1076
    Online,
1077
    Offline,
1078
    Stopped,
1079
}
1080
1081
#[derive(Clone, Debug, Eq, PartialEq)]
1082
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1083
#[non_exhaustive]
1084
pub struct RoomSummary {
1085
    pub room_id: OwnedRoomId,
1086
    pub name: String,
1087
    pub membership: RoomMembership,
1088
    /// the main timeline's, threads have theirs in `thread_unreads`
1089
    pub unread_messages: u64,
1090
    /// thread mentions included
1091
    pub unread_mentions: u64,
1092
    /// unread events the push rules said to notify about, which is neither of the above.
1093
    /// the main timeline's
1094
    pub unread_notifications: u64,
1095
    /// threads with anything unread, by root
1096
    pub thread_unreads: BTreeMap<OwnedEventId, ThreadUnread>,
1097
    pub encrypted: bool,
1098
    pub space: bool,
1099
    pub direct: bool,
1100
    pub favourite: bool,
1101
    pub low_priority: bool,
1102
    pub avatar: Option<MediaId>,
1103
    pub latest_event_timestamp_ms: Option<u64>,
1104
    pub latest_event: Option<LatestEvent>,
1105
    pub notification_mode: Option<RoomNotificationMode>,
1106
    pub notification_mode_custom: bool,
1107
    pub topic: Option<String>,
1108
    pub canonical_alias: Option<OwnedRoomAliasId>,
1109
    pub joined_members: u64,
1110
    pub invited_members: u64,
1111
    /// who a nameless room gets named after
1112
    pub heroes: Vec<RoomHero>,
1113
    /// set once the room has been upgraded, this is where everyone went
1114
    pub successor: Option<OwnedRoomId>,
1115
    pub inviter: Option<OwnedUserId>,
1116
    /// joined spaces that list this room as a child
1117
    pub parent_spaces: Vec<OwnedRoomId>,
1118
    /// for a space, the children it lists, joined or not
1119
    pub children: Vec<OwnedRoomId>,
1120
    /// a space's msc3230 order. ordered spaces sort first by (order, room id), the rest by room id
1121
    pub space_order: Option<String>,
1122
    /// you can send im.ponies.room_emotes here, so you can make and edit its packs
1123
    pub can_edit_packs: bool,
1124
    /// m.room.pinned_events in order, the newest pin last
1125
    pub pinned_events: Vec<OwnedEventId>,
1126
    pub can_pin: bool,
1127
}
1128
1129
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1130
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1131
#[non_exhaustive]
1132
pub struct ThreadUnread {
1133
    pub messages: u64,
1134
    pub mentions: u64,
1135
    pub notifications: u64,
1136
}
1137
1138
#[derive(Clone, Debug, Eq, PartialEq)]
1139
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1140
#[non_exhaustive]
1141
pub struct RoomHero {
1142
    pub user_id: OwnedUserId,
1143
    pub display_name: Option<String>,
1144
    pub avatar: Option<MediaId>,
1145
}
1146
1147
/// enough for a room list preview line. `kind` and `body` are only set for messages,
1148
/// and an edit shows its new text
1149
#[derive(Clone, Debug, Eq, PartialEq)]
1150
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1151
#[non_exhaustive]
1152
pub struct LatestEvent {
1153
    pub sender: Option<OwnedUserId>,
1154
    pub kind: Option<MessageKind>,
1155
    pub body: Option<String>,
1156
    pub timestamp_ms: Option<u64>,
1157
    pub send_state: SendState,
1158
}
1159
1160
#[derive(Clone, Debug, Eq, PartialEq)]
1161
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1162
#[non_exhaustive]
1163
pub struct Profile {
1164
    pub user_id: OwnedUserId,
1165
    pub display_name: Option<String>,
1166
    pub avatar: Option<MediaId>,
1167
}
1168
1169
/// one room in a space's hierarchy, as the server describes it, which may be a room you're not in
1170
#[derive(Clone, Debug, Eq, PartialEq)]
1171
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1172
#[non_exhaustive]
1173
pub struct SpaceChild {
1174
    pub room_id: OwnedRoomId,
1175
    pub name: String,
1176
    pub topic: Option<String>,
1177
    pub avatar: Option<MediaId>,
1178
    pub canonical_alias: Option<OwnedRoomAliasId>,
1179
    pub joined_members: u64,
1180
    pub space: bool,
1181
    pub children_count: u64,
1182
    pub membership: Option<RoomMembership>,
1183
    pub via: Vec<OwnedServerName>,
1184
    pub suggested: bool,
1185
    pub world_readable: Option<bool>,
1186
    pub guest_can_join: bool,
1187
}
1188
1189
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1190
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1191
pub enum RoomNotificationMode {
1192
    AllMessages,
1193
    MentionsAndKeywordsOnly,
1194
    Mute,
1195
}
1196
1197
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1198
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1199
#[non_exhaustive]
1200
pub struct RoomNotificationSettings {
1201
    pub mode: RoomNotificationMode,
1202
    pub custom: bool,
1203
}
1204
1205
#[derive(Clone, Debug)]
1206
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1207
pub enum PushNotificationStatus {
1208
    Event(Box<PushNotification>),
1209
    NotFound,
1210
    FilteredOut,
1211
    Redacted,
1212
}
1213
1214
#[derive(Clone, Debug)]
1215
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1216
#[non_exhaustive]
1217
pub struct PushNotification {
1218
    pub event_id: OwnedEventId,
1219
    pub event: PushNotificationEvent,
1220
    pub sender: PushNotificationSender,
1221
    pub room: PushNotificationRoom,
1222
    pub noisy: Option<bool>,
1223
    pub has_mention: Option<bool>,
1224
    pub thread_id: Option<OwnedEventId>,
1225
}
1226
1227
#[derive(Clone, Debug, Eq, PartialEq)]
1228
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1229
#[non_exhaustive]
1230
pub struct PushNotificationSender {
1231
    pub user_id: OwnedUserId,
1232
    pub display_name: Option<String>,
1233
    pub avatar_url: Option<MediaId>,
1234
    pub name_ambiguous: bool,
1235
}
1236
1237
#[derive(Clone, Debug, Eq, PartialEq)]
1238
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1239
#[non_exhaustive]
1240
pub struct PushNotificationRoom {
1241
    pub room_id: OwnedRoomId,
1242
    pub name: String,
1243
    pub avatar_url: Option<MediaId>,
1244
    pub canonical_alias: Option<OwnedRoomAliasId>,
1245
    pub topic: Option<String>,
1246
    pub encrypted: Option<bool>,
1247
    pub direct: bool,
1248
    pub joined_members_count: u64,
1249
    pub service_members: Vec<OwnedUserId>,
1250
    pub active_service_members_count: u64,
1251
    pub space: bool,
1252
}
1253
1254
#[derive(Clone, Debug)]
1255
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1256
pub enum PushNotificationEvent {
1257
    Timeline(Raw<AnySyncTimelineEvent>),
1258
    Invite(Raw<StrippedRoomMemberEvent>),
1259
}
1260
1261
#[derive(Clone, Debug, Eq, PartialEq)]
1262
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1263
#[non_exhaustive]
1264
pub struct RoomPowerLevels {
1265
    pub ban: i64,
1266
    pub invite: i64,
1267
    pub kick: i64,
1268
    pub redact: i64,
1269
    pub events_default: i64,
1270
    pub state_default: i64,
1271
    pub users_default: i64,
1272
    pub room_notification: i64,
1273
    pub users: Vec<(OwnedUserId, i64)>,
1274
    pub events: Vec<(String, i64)>,
1275
    /// in rooms from version 12 the creators outrank everyone and aren't listed in `users`
1276
    pub creators: Vec<OwnedUserId>,
1277
}
1278
1279
#[derive(Clone, Debug, Default, Eq, PartialEq)]
1280
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1281
#[non_exhaustive]
1282
pub struct PowerLevelChanges {
1283
    pub ban: Option<i64>,
1284
    pub invite: Option<i64>,
1285
    pub kick: Option<i64>,
1286
    pub redact: Option<i64>,
1287
    pub events_default: Option<i64>,
1288
    pub state_default: Option<i64>,
1289
    pub users_default: Option<i64>,
1290
    pub room_notification: Option<i64>,
1291
    pub room_name: Option<i64>,
1292
    pub room_avatar: Option<i64>,
1293
    pub room_topic: Option<i64>,
1294
    pub space_child: Option<i64>,
1295
    pub beacon: Option<i64>,
1296
    pub beacon_info: Option<i64>,
1297
}
1298
1299
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1300
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1301
pub enum RoomMembership {
1302
    Joined,
1303
    Invited,
1304
    Left,
1305
    Knocked,
1306
    Banned,
1307
}
1308
1309
#[derive(Clone, Debug, Default, Eq, PartialEq)]
1310
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1311
#[non_exhaustive]
1312
pub struct RoomListFilter {
1313
    pub membership: Option<RoomMembership>,
1314
    pub category: Option<RoomCategory>,
1315
    pub favourite: Option<bool>,
1316
    pub unread_only: bool,
1317
    pub search: Option<String>,
1318
}
1319
1320
impl RoomListFilter {
1321
    #[must_use]
1322
    pub fn with_membership(mut self, membership: RoomMembership) -> Self {
1323
        self.membership = Some(membership);
1324
        self
1325
    }
1326
1327
    #[must_use]
1328
    pub fn with_category(mut self, category: RoomCategory) -> Self {
1329
        self.category = Some(category);
1330
        self
1331
    }
1332
1333
    #[must_use]
1334
    pub fn with_favourite(mut self, favourite: bool) -> Self {
1335
        self.favourite = Some(favourite);
1336
        self
1337
    }
1338
1339
    #[must_use]
1340
    pub const fn with_unread_only(mut self, unread_only: bool) -> Self {
1341
        self.unread_only = unread_only;
1342
        self
1343
    }
1344
1345
    #[must_use]
1346
    pub fn with_search(mut self, search: impl Into<String>) -> Self {
1347
        self.search = Some(search.into());
1348
        self
1349
    }
1350
1351
    #[must_use]
1352
    pub fn matches(&self, room: &RoomSummary) -> bool {
1353
        self.matcher().matches(room)
1354
    }
1355
1356
    /// lowercases the search once, for filtering a whole list
1357
    #[must_use]
1358
    pub fn matcher(&self) -> RoomMatcher<'_> {
1359
        RoomMatcher {
1360
            filter: self,
1361
            search: self.search.as_deref().map(str::to_lowercase),
1362
        }
1363
    }
1364
}
1365
1366
#[derive(Debug)]
1367
pub struct RoomMatcher<'a> {
1368
    filter: &'a RoomListFilter,
1369
    search: Option<String>,
1370
}
1371
1372
impl RoomMatcher<'_> {
1373
    #[must_use]
1374
    pub fn matches(&self, room: &RoomSummary) -> bool {
1375
        let filter = self.filter;
1376
        filter
1377
            .membership
1378
            .is_none_or(|membership| room.membership == membership)
1379
            && filter.category.is_none_or(|category| match category {
1380
                RoomCategory::People => room.direct && !room.space,
1381
                RoomCategory::Rooms => !room.direct && !room.space,
1382
                RoomCategory::Spaces => room.space,
1383
            })
1384
            && filter
1385
                .favourite
1386
                .is_none_or(|favourite| room.favourite == favourite)
1387
            && (!filter.unread_only || room.unread_messages > 0 || room.unread_mentions > 0)
1388
            && self.search.as_ref().is_none_or(|search| {
1389
                room.name.to_lowercase().contains(search)
1390
                    || room.room_id.as_str().to_lowercase().contains(search)
1391
            })
1392
    }
1393
}
1394
1395
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1396
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1397
#[non_exhaustive]
1398
pub enum RoomCategory {
1399
    People,
1400
    Rooms,
1401
    Spaces,
1402
}
1403
1404
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1405
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1406
#[non_exhaustive]
1407
pub enum MemberFilter {
1408
    Active,
1409
    Joined,
1410
    Invited,
1411
    Banned,
1412
    Left,
1413
    All,
1414
}
1415
1416
#[derive(Clone, Debug, Eq, PartialEq)]
1417
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1418
pub enum MemberMembership {
1419
    Joined,
1420
    Invited,
1421
    Left,
1422
    Knocked,
1423
    Banned,
1424
    Custom(String),
1425
}
1426
1427
#[derive(Clone, Debug, Eq, PartialEq)]
1428
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1429
#[non_exhaustive]
1430
pub struct MemberSummary {
1431
    pub user_id: OwnedUserId,
1432
    pub name: String,
1433
    pub display_name: Option<String>,
1434
    pub avatar: Option<MediaId>,
1435
    pub membership: MemberMembership,
1436
    pub own: bool,
1437
    pub name_ambiguous: bool,
1438
    pub ignored: bool,
1439
    pub service: bool,
1440
}
1441
1442
#[derive(Clone, Debug, Eq, PartialEq)]
1443
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1444
#[non_exhaustive]
1445
pub struct OwnDevice {
1446
    pub device_id: OwnedDeviceId,
1447
    pub display_name: Option<String>,
1448
    pub last_seen_ip: Option<String>,
1449
    pub last_seen_timestamp_ms: Option<u64>,
1450
    pub current: bool,
1451
}
1452
1453
#[derive(Clone, Debug, Eq, PartialEq)]
1454
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1455
pub enum TimelineItem {
1456
    Event(Box<TimelineEvent>),
1457
    HistoryGap(crate::HistoryGap),
1458
    DayDivider { timestamp_ms: u64 },
1459
    ReadMarker,
1460
    TimelineStart,
1461
}
1462
1463
#[derive(Clone, Debug, Eq, PartialEq)]
1464
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1465
pub enum TimelineDiff {
1466
    Append { values: Vec<TimelineItem> },
1467
    Clear,
1468
    PushFront { value: TimelineItem },
1469
    PushBack { value: TimelineItem },
1470
    PopFront,
1471
    PopBack,
1472
    Insert { index: usize, value: TimelineItem },
1473
    Set { index: usize, value: TimelineItem },
1474
    Remove { index: usize },
1475
    Truncate { length: usize },
1476
    Reset { values: Vec<TimelineItem> },
1477
}
1478
1479
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
1480
#[error("timeline diff is incompatible with the current {length}-item snapshot")]
1481
pub struct TimelineDiffError {
1482
    pub length: usize,
1483
}
1484
1485
impl TimelineDiff {
1486
    /// Apply a diff only when its indices match the current snapshot.
1487
    /// On error the snapshot is unchanged; request `TimelineCommand::Resync`
1488
    /// and ignore further diffs until the corresponding `TimelineReset`.
1489
    pub fn try_apply(self, items: &mut Vector<TimelineItem>) -> Result<(), TimelineDiffError> {
1490
        let length = items.len();
1491
        if self.length_after(length).is_none() {
1492
            return Err(TimelineDiffError { length });
1493
        }
1494
        self.apply(items);
1495
        Ok(())
1496
    }
1497
1498
    /// a whole `TimelineChanged` or none of it. whether a diff fits depends only on the
1499
    /// length before it, so the batch is checked against lengths alone before anything
1500
    /// moves. the error carries the length the snapshot would have had at the misfit
1501
    pub fn try_apply_all(
1502
        diffs: Vec<Self>,
1503
        items: &mut Vector<TimelineItem>,
1504
    ) -> Result<(), TimelineDiffError> {
1505
        diffs.iter().try_fold(items.len(), |length, diff| {
1506
            diff.length_after(length)
1507
                .ok_or(TimelineDiffError { length })
1508
        })?;
1509
        for diff in diffs {
1510
            diff.apply(items);
1511
        }
1512
        Ok(())
1513
    }
1514
1515
    fn length_after(&self, length: usize) -> Option<usize> {
1516
        match self {
1517
            Self::Append { values } => Some(length + values.len()),
1518
            Self::Clear => Some(0),
1519
            Self::PushFront { .. } | Self::PushBack { .. } => Some(length + 1),
1520
            Self::PopFront | Self::PopBack => length.checked_sub(1),
1521
            Self::Insert { index, .. } => (*index <= length).then_some(length + 1),
1522
            Self::Set { index, .. } => (*index < length).then_some(length),
1523
            Self::Remove { index } => (*index < length).then(|| length - 1),
1524
            Self::Truncate { length: target } => (*target <= length).then_some(*target),
1525
            Self::Reset { values } => Some(values.len()),
1526
        }
1527
    }
1528
1529
    fn apply(self, items: &mut Vector<TimelineItem>) {
1530
        match self {
1531
            Self::Append { values } => items.extend(values),
1532
            Self::Clear => items.clear(),
1533
            Self::PushFront { value } => items.push_front(value),
1534
            Self::PushBack { value } => items.push_back(value),
1535
            Self::PopFront => {
1536
                items.pop_front();
1537
            }
1538
            Self::PopBack => {
1539
                items.pop_back();
1540
            }
1541
            Self::Insert { index, value } => items.insert(index, value),
1542
            Self::Set { index, value } => {
1543
                items.set(index, value);
1544
            }
1545
            Self::Remove { index } => {
1546
                items.remove(index);
1547
            }
1548
            Self::Truncate { length } => items.truncate(length),
1549
            Self::Reset { values } => *items = values.into_iter().collect(),
1550
        }
1551
    }
1552
}
1553
1554
#[cfg(test)]
1555
mod tests {
1556
    use imbl::{Vector, vector};
1557
1558
    use super::{TimelineDiff, TimelineItem};
1559
1560
    fn item(timestamp_ms: u64) -> TimelineItem {
1561
        TimelineItem::DayDivider { timestamp_ms }
1562
    }
1563
1564
    #[test]
1565
    fn timeline_diff_try_apply_handles_every_variant() {
1566
        let mut items = vector![item(1), item(2)];
1567
1568
        TimelineDiff::Append {
1569
            values: vec![item(3)],
1570
        }
1571
        .try_apply(&mut items)
1572
        .unwrap();
1573
        assert_eq!(items, vector![item(1), item(2), item(3)]);
1574
1575
        TimelineDiff::Clear.try_apply(&mut items).unwrap();
1576
        assert!(items.is_empty());
1577
1578
        TimelineDiff::PushFront { value: item(2) }
1579
            .try_apply(&mut items)
1580
            .unwrap();
1581
        TimelineDiff::PushBack { value: item(3) }
1582
            .try_apply(&mut items)
1583
            .unwrap();
1584
        assert_eq!(items, vector![item(2), item(3)]);
1585
1586
        TimelineDiff::PopFront.try_apply(&mut items).unwrap();
1587
        TimelineDiff::PopBack.try_apply(&mut items).unwrap();
1588
        assert!(items.is_empty());
1589
1590
        TimelineDiff::Reset {
1591
            values: vec![item(1), item(3)],
1592
        }
1593
        .try_apply(&mut items)
1594
        .unwrap();
1595
        TimelineDiff::Insert {
1596
            index: 1,
1597
            value: item(2),
1598
        }
1599
        .try_apply(&mut items)
1600
        .unwrap();
1601
        assert_eq!(items, vector![item(1), item(2), item(3)]);
1602
1603
        TimelineDiff::Set {
1604
            index: 1,
1605
            value: item(4),
1606
        }
1607
        .try_apply(&mut items)
1608
        .unwrap();
1609
        assert_eq!(items, vector![item(1), item(4), item(3)]);
1610
1611
        TimelineDiff::Remove { index: 1 }
1612
            .try_apply(&mut items)
1613
            .unwrap();
1614
        assert_eq!(items, vector![item(1), item(3)]);
1615
1616
        TimelineDiff::Truncate { length: 1 }
1617
            .try_apply(&mut items)
1618
            .unwrap();
1619
        assert_eq!(items, vector![item(1)]);
1620
    }
1621
1622
    #[test]
1623
    fn invalid_timeline_diff_leaves_snapshot_unchanged() {
1624
        let invalid = [
1625
            TimelineDiff::Insert {
1626
                index: 3,
1627
                value: item(3),
1628
            },
1629
            TimelineDiff::Set {
1630
                index: 2,
1631
                value: item(3),
1632
            },
1633
            TimelineDiff::Remove { index: 2 },
1634
            TimelineDiff::Truncate { length: 3 },
1635
        ];
1636
        for diff in invalid {
1637
            let mut items = vector![item(1), item(2)];
1638
            assert_eq!(diff.try_apply(&mut items).unwrap_err().length, 2);
1639
            assert_eq!(items, vector![item(1), item(2)]);
1640
        }
1641
        for diff in [TimelineDiff::PopFront, TimelineDiff::PopBack] {
1642
            let mut items = Vector::new();
1643
            assert_eq!(diff.try_apply(&mut items).unwrap_err().length, 0);
1644
            assert!(items.is_empty());
1645
        }
1646
    }
1647
1648
    #[test]
1649
    fn a_batch_that_goes_wrong_halfway_changes_nothing() {
1650
        let mut items = vector![item(1), item(2)];
1651
        let batch = vec![
1652
            TimelineDiff::PushBack { value: item(3) },
1653
            TimelineDiff::PushBack { value: item(4) },
1654
            TimelineDiff::Remove { index: 0 },
1655
            TimelineDiff::Set {
1656
                index: 3,
1657
                value: item(5),
1658
            },
1659
        ];
1660
        assert_eq!(
1661
            TimelineDiff::try_apply_all(batch, &mut items)
1662
                .unwrap_err()
1663
                .length,
1664
            3
1665
        );
1666
        assert_eq!(items, vector![item(1), item(2)]);
1667
1668
        let batch = vec![
1669
            TimelineDiff::PushBack { value: item(3) },
1670
            TimelineDiff::Remove { index: 0 },
1671
            TimelineDiff::Set {
1672
                index: 1,
1673
                value: item(4),
1674
            },
1675
        ];
1676
        TimelineDiff::try_apply_all(batch, &mut items).unwrap();
1677
        assert_eq!(items, vector![item(2), item(4)]);
1678
    }
1679
}
1680
1681
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1682
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1683
pub struct TimelineItemId(String);
1684
1685
impl TimelineItemId {
1686
    pub(crate) fn new(value: String) -> Self {
1687
        Self(value)
1688
    }
1689
1690
    #[must_use]
1691
    pub fn as_str(&self) -> &str {
1692
        &self.0
1693
    }
1694
}
1695
1696
#[derive(Clone, Debug, Eq, PartialEq)]
1697
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1698
#[non_exhaustive]
1699
pub struct TimelineEvent {
1700
    pub item_id: TimelineItemId,
1701
    pub event_id: Option<OwnedEventId>,
1702
    pub transaction_id: Option<OwnedTransactionId>,
1703
    pub sender: Sender,
1704
    pub timestamp_ms: u64,
1705
    pub own: bool,
1706
    pub send_state: SendState,
1707
    pub content: TimelineContent,
1708
    pub reply_to: Option<ReplyReference>,
1709
    pub thread_root: Option<OwnedEventId>,
1710
    pub thread_summary: Option<ThreadSummary>,
1711
    pub reactions: Vec<Reaction>,
1712
    pub read_by: Vec<OwnedUserId>,
1713
    pub editable: bool,
1714
    /// the push rules ask for this one to stand out, always false for a local echo
1715
    pub highlight: bool,
1716
}
1717
1718
impl TimelineEvent {
1719
    /// what to hand edit, redact and react. works before the server has echoed it back
1720
    #[must_use]
1721
    pub fn target(&self) -> Option<EventRef> {
1722
        self.event_id
1723
            .clone()
1724
            .map(EventRef::Remote)
1725
            .or_else(|| self.transaction_id.clone().map(EventRef::Local))
1726
    }
1727
}
1728
1729
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1730
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1731
#[non_exhaustive]
1732
pub enum EventRef {
1733
    Remote(OwnedEventId),
1734
    /// a local echo, by the transaction id it was queued under
1735
    Local(OwnedTransactionId),
1736
}
1737
1738
impl From<OwnedEventId> for EventRef {
1739
    fn from(event_id: OwnedEventId) -> Self {
1740
        Self::Remote(event_id)
1741
    }
1742
}
1743
1744
#[derive(Clone, Debug, Eq, PartialEq)]
1745
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1746
#[non_exhaustive]
1747
pub struct Sender {
1748
    pub user_id: OwnedUserId,
1749
    pub display_name: Option<String>,
1750
    pub avatar: Option<MediaId>,
1751
    /// someone else in the room goes by the same name, so show the user id too
1752
    pub name_ambiguous: bool,
1753
}
1754
1755
impl Sender {
1756
    #[must_use]
1757
    pub fn name(&self) -> &str {
1758
        self.display_name
1759
            .as_deref()
1760
            .unwrap_or_else(|| self.user_id.as_str())
1761
    }
1762
}
1763
1764
#[derive(Clone, Debug, Eq, PartialEq)]
1765
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1766
pub enum TimelineContent {
1767
    Message(Message),
1768
    Sticker {
1769
        body: String,
1770
        media: MediaDescriptor,
1771
    },
1772
    Poll {
1773
        question: String,
1774
    },
1775
    Redacted,
1776
    UnableToDecrypt(UtdCause),
1777
    Membership {
1778
        user_id: OwnedUserId,
1779
        display_name: Option<String>,
1780
        change: MembershipChange,
1781
    },
1782
    Profile {
1783
        user_id: OwnedUserId,
1784
        display_name: Option<Change<Option<String>>>,
1785
        avatar: Option<Change<Option<MediaId>>>,
1786
    },
1787
    /// `None` means it was cleared, or the event was redacted
1788
    RoomName(Option<String>),
1789
    RoomTopic(Option<String>),
1790
    RoomAvatar(Option<MediaId>),
1791
    EncryptionEnabled,
1792
    RoomCreated,
1793
    RoomUpgraded {
1794
        successor: OwnedRoomId,
1795
    },
1796
    OtherState {
1797
        event_type: String,
1798
        state_key: String,
1799
    },
1800
    Other {
1801
        event_type: String,
1802
    },
1803
}
1804
1805
#[derive(Clone, Debug, Eq, PartialEq)]
1806
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1807
#[non_exhaustive]
1808
pub struct Message {
1809
    pub kind: MessageKind,
1810
    pub body: String,
1811
    /// only for `MessageKind::Location`
1812
    pub geo_uri: Option<String>,
1813
    pub formatted_body: Option<String>,
1814
    pub mentions: Option<MessageMentions>,
1815
    pub edited: bool,
1816
    pub media: Option<MediaDescriptor>,
1817
    /// previews the sender attached (msc4095), so showing them asks no one about the url.
1818
    /// one for a url the body doesn't contain is dropped
1819
    pub link_previews: Vec<LinkPreview>,
1820
}
1821
1822
/// a link card, from the sender's own message or from `ClientHandle::url_preview`. page
1823
/// text passes through whoever made it unfiltered, so it arrives trimmed to a sane length
1824
#[derive(Clone, Debug, Eq, PartialEq)]
1825
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1826
#[non_exhaustive]
1827
pub struct LinkPreview {
1828
    /// the url as it appears in the message, or as it was asked about
1829
    pub url: String,
1830
    /// where the page says it lives, when that's somewhere else
1831
    pub canonical_url: Option<String>,
1832
    pub title: Option<String>,
1833
    pub description: Option<String>,
1834
    pub site_name: Option<String>,
1835
    pub image: Option<LinkPreviewImage>,
1836
}
1837
1838
#[derive(Clone, Debug, Eq, PartialEq)]
1839
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1840
#[non_exhaustive]
1841
pub struct LinkPreviewImage {
1842
    pub media_id: MediaId,
1843
    pub mimetype: Option<String>,
1844
    pub size_bytes: Option<u64>,
1845
    pub width: Option<u64>,
1846
    pub height: Option<u64>,
1847
}
1848
1849
#[derive(Clone, Debug, Eq, PartialEq)]
1850
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1851
pub enum MessageKind {
1852
    Text,
1853
    Emote,
1854
    Notice,
1855
    ServerNotice,
1856
    Image,
1857
    Video,
1858
    Audio,
1859
    File,
1860
    Location,
1861
    VerificationRequest,
1862
    Other(String),
1863
}
1864
1865
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1866
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1867
pub enum MembershipChange {
1868
    Joined,
1869
    Left,
1870
    Banned,
1871
    Unbanned,
1872
    Kicked,
1873
    KickedAndBanned,
1874
    Invited,
1875
    InvitationAccepted,
1876
    InvitationRejected,
1877
    InvitationRevoked,
1878
    Knocked,
1879
    KnockAccepted,
1880
    KnockRetracted,
1881
    KnockDenied,
1882
    /// nothing a person would call a change, or something the sdk couldn't make sense of
1883
    Other,
1884
}
1885
1886
#[derive(Clone, Debug, Eq, PartialEq)]
1887
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1888
pub struct Change<T> {
1889
    pub old: T,
1890
    pub new: T,
1891
}
1892
1893
/// why a message couldn't be read, worth telling the user since some of these they can fix
1894
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1895
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1896
pub enum UtdCause {
1897
    Unknown,
1898
    SentBeforeWeJoined,
1899
    VerificationViolation,
1900
    UnsignedDevice,
1901
    UnknownDevice,
1902
    HistoricalMessageAndBackupIsDisabled,
1903
    WithheldForUnverifiedOrInsecureDevice,
1904
    WithheldBySender,
1905
    HistoricalMessageAndDeviceIsUnverified,
1906
}
1907
1908
#[derive(Clone, Debug, Eq, PartialEq)]
1909
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1910
#[non_exhaustive]
1911
pub struct ThreadSummary {
1912
    pub reply_count: u32,
1913
    pub latest_event_id: Option<OwnedEventId>,
1914
    pub latest_event_timestamp_ms: Option<u64>,
1915
}
1916
1917
#[derive(Clone, Debug, Eq, PartialEq)]
1918
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1919
#[non_exhaustive]
1920
pub struct ThreadListEntry {
1921
    pub root_event_id: OwnedEventId,
1922
    /// always an event, carrying `summary` as its own
1923
    pub root: TimelineItem,
1924
    pub summary: ThreadSummary,
1925
    pub latest_reply: Option<TimelineItem>,
1926
    /// the latest reply's timestamp, or the root's before any reply
1927
    pub latest_activity_ms: u64,
1928
}
1929
1930
impl ThreadListEntry {
1931
    /// replaces the entry with the same root, or adds it, where its activity puts it.
1932
    /// ties go by root event id
1933
    pub fn upsert(entries: &mut Vector<Self>, entry: Self) {
1934
        if let Some(index) = entries
1935
            .iter()
1936
            .position(|known| known.root_event_id == entry.root_event_id)
1937
        {
1938
            entries.remove(index);
1939
        }
1940
        let index = entries
1941
            .binary_search_by(|known| {
1942
                if known.sorts_before(&entry) {
1943
                    std::cmp::Ordering::Less
1944
                } else {
1945
                    std::cmp::Ordering::Greater
1946
                }
1947
            })
1948
            .unwrap_or_else(|index| index);
1949
        entries.insert(index, entry);
1950
    }
1951
1952
    #[must_use]
1953
    pub fn sorts_before(&self, other: &Self) -> bool {
1954
        (
1955
            std::cmp::Reverse(self.latest_activity_ms),
1956
            &self.root_event_id,
1957
        ) < (
1958
            std::cmp::Reverse(other.latest_activity_ms),
1959
            &other.root_event_id,
1960
        )
1961
    }
1962
}
1963
1964
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1965
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1966
pub enum SendState {
1967
    Sent,
1968
    Sending,
1969
    /// `will_retry` means macltok has it in hand. otherwise it's wedged until you
1970
    /// `retry_send` or `cancel_send`, so that's when to show a retry button
1971
    Failed {
1972
        will_retry: bool,
1973
    },
1974
}
1975
1976
#[derive(Clone, Debug, Eq, PartialEq)]
1977
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1978
#[non_exhaustive]
1979
pub struct ReplyReference {
1980
    pub event_id: OwnedEventId,
1981
    pub details: ReplyDetails,
1982
}
1983
1984
/// the replied-to event. macltok asks for it when it isn't loaded, `Pending` then turns into one of the others
1985
#[derive(Clone, Debug, Eq, PartialEq)]
1986
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1987
pub enum ReplyDetails {
1988
    Pending,
1989
    Ready {
1990
        sender: Sender,
1991
        content: Box<TimelineContent>,
1992
        timestamp_ms: u64,
1993
    },
1994
    Unavailable,
1995
}
1996
1997
#[derive(Clone, Debug, Eq, PartialEq)]
1998
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1999
#[non_exhaustive]
2000
pub struct Reaction {
2001
    pub key: String,
2002
    /// a custom emote's shortcode, from whichever sender gave one
2003
    pub shortcode: Option<String>,
2004
    /// the custom emote itself, when the key is an image
2005
    pub image: Option<MediaId>,
2006
    pub count: usize,
2007
    pub own: bool,
2008
    pub senders: Vec<OwnedUserId>,
2009
}
2010
2011
/// every custom emote and sticker pack the account can reach, from the user's own
2012
/// pack, each joined room's packs, and the rooms the user enabled everywhere
2013
#[derive(Clone, Debug, Default, Eq, PartialEq)]
2014
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2015
#[non_exhaustive]
2016
pub struct ImagePacks {
2017
    /// the user's own pack, then the packs of rooms enabled everywhere
2018
    pub global: Vec<ImagePack>,
2019
    /// each joined room's own packs, rooms without any left out
2020
    pub rooms: imbl::HashMap<OwnedRoomId, Vec<ImagePack>>,
2021
}
2022
2023
impl ImagePacks {
2024
    /// what a picker in this room offers. the user's pack, the room's own, then the
2025
    /// rest of the enabled ones, each pack once
2026
    #[must_use]
2027
    pub fn for_room(&self, room_id: Option<&RoomId>) -> Vec<&ImagePack> {
2028
        let is_user = |pack: &&ImagePack| pack.source == ImagePackSource::User;
2029
        let own = room_id.and_then(|room_id| self.rooms.get(room_id));
2030
        let mut packs: Vec<&ImagePack> = self.global.iter().filter(is_user).collect();
2031
        packs.extend(own.into_iter().flatten());
2032
        for pack in self.global.iter().filter(|pack| !is_user(pack)) {
2033
            if !packs.iter().any(|seen| seen.id == pack.id) {
2034
                packs.push(pack);
2035
            }
2036
        }
2037
        packs
2038
    }
2039
}
2040
2041
#[derive(Clone, Debug, Eq, PartialEq)]
2042
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2043
#[non_exhaustive]
2044
pub struct ImagePack {
2045
    /// `user`, or `room:<room id>:<state key>`, the same across calls
2046
    pub id: String,
2047
    pub display_name: Option<String>,
2048
    pub avatar: Option<MediaId>,
2049
    pub attribution: Option<String>,
2050
    pub source: ImagePackSource,
2051
    pub images: Vec<PackImage>,
2052
    /// your own pack, or a room pack whose state you're allowed to send
2053
    pub editable: bool,
2054
    /// listed in im.ponies.emote_rooms. always true for your own pack
2055
    pub enabled_everywhere: bool,
2056
}
2057
2058
#[derive(Clone, Debug, Eq, PartialEq)]
2059
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2060
pub enum ImagePackSource {
2061
    User,
2062
    Room {
2063
        room_id: OwnedRoomId,
2064
        state_key: String,
2065
    },
2066
}
2067
2068
#[derive(Clone, Debug, Eq, PartialEq)]
2069
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2070
#[non_exhaustive]
2071
pub struct PackImage {
2072
    pub shortcode: String,
2073
    pub media_id: MediaId,
2074
    /// what `toggle_reaction` takes to react with this image
2075
    pub reaction_key: String,
2076
    pub body: Option<String>,
2077
    pub mimetype: Option<String>,
2078
    pub width: Option<u64>,
2079
    pub height: Option<u64>,
2080
    /// the image's own, else its pack's, else both
2081
    pub usage: Vec<PackUsage>,
2082
}
2083
2084
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
2085
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2086
pub enum PackUsage {
2087
    Emoticon,
2088
    Sticker,
2089
}
2090
2091
#[derive(Clone, Debug, Eq, PartialEq)]
2092
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2093
#[non_exhaustive]
2094
pub struct MediaDescriptor {
2095
    pub id: MediaId,
2096
    pub kind: MediaKind,
2097
    /// only for unencrypted media, an encrypted file's mxc is ciphertext without the keys
2098
    pub mxc: Option<OwnedMxcUri>,
2099
    pub filename: String,
2100
    pub caption: Option<String>,
2101
    pub mimetype: Option<String>,
2102
    pub size_bytes: Option<u64>,
2103
    pub width: Option<u64>,
2104
    pub height: Option<u64>,
2105
    pub duration_ms: Option<u64>,
2106
    pub blurhash: Option<String>,
2107
    /// the uploader sent a thumbnail, so `MediaSize::Thumbnail` won't need the server to resize
2108
    pub has_thumbnail: bool,
2109
}
2110
2111
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2112
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2113
pub struct MediaId(String);
2114
2115
impl MediaId {
2116
    pub(crate) fn new(value: String) -> Self {
2117
        Self(value)
2118
    }
2119
2120
    /// plain media carries no keys, so it needs no registering and never expires
2121
    pub(crate) fn plain<U: AsRef<str> + ?Sized>(uri: &U) -> Self {
2122
        Self(uri.as_ref().to_owned())
2123
    }
2124
2125
    pub(crate) fn as_plain(&self) -> Option<&MxcUri> {
2126
        self.0.starts_with("mxc://").then(|| self.0.as_str().into())
2127
    }
2128
2129
    #[must_use]
2130
    pub fn as_str(&self) -> &str {
2131
        &self.0
2132
    }
2133
}
2134
2135
/// media ids are opaque but they do have to survive a trip through a browser. a made up one just fails `MediaUnknown`
2136
impl std::str::FromStr for MediaId {
2137
    type Err = std::convert::Infallible;
2138
2139
    fn from_str(value: &str) -> Result<Self, Self::Err> {
2140
        Ok(Self(value.to_owned()))
2141
    }
2142
}
2143
2144
impl From<String> for MediaId {
2145
    fn from(value: String) -> Self {
2146
        Self(value)
2147
    }
2148
}
2149
2150
impl std::fmt::Display for MediaId {
2151
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2152
        self.0.fmt(formatter)
2153
    }
2154
}
2155
2156
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
2157
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2158
#[non_exhaustive]
2159
pub enum MediaSize {
2160
    Full,
2161
    /// a hint. an uploader's own thumbnail wins over the server resizing anything
2162
    Thumbnail {
2163
        width: u32,
2164
        height: u32,
2165
    },
2166
}
2167
2168
#[derive(Clone, Debug, Eq, PartialEq)]
2169
#[non_exhaustive]
2170
pub struct Media {
2171
    pub bytes: Arc<[u8]>,
2172
    pub mimetype: String,
2173
}
2174
2175
/// where media lives, for a host that fetches and decrypts it itself
2176
#[derive(Clone, Debug, Eq, PartialEq)]
2177
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2178
pub enum MediaLocation {
2179
    File(MediaFile),
2180
    /// a resize of plaintext, so never encrypted. plenty of servers refuse some, and `media`
2181
    /// then fetches `fallback` instead, so should you
2182
    ServerThumbnail {
2183
        url: String,
2184
        fallback: MediaFile,
2185
    },
2186
    /// still in the send queue with no url yet. `media` has the bytes
2187
    Local,
2188
}
2189
2190
#[derive(Clone, Debug, Eq, PartialEq)]
2191
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2192
#[non_exhaustive]
2193
pub struct MediaFile {
2194
    pub url: String,
2195
    pub mimetype: Option<String>,
2196
    pub declared_size: Option<u64>,
2197
    pub encryption: Option<AttachmentEncryption>,
2198
}
2199
2200
/// AES-256-CTR, the only attachment cipher matrix has
2201
#[derive(Clone, Debug, Eq, PartialEq)]
2202
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2203
#[non_exhaustive]
2204
pub struct AttachmentEncryption {
2205
    /// the JWK `k`, unpadded url-safe base64
2206
    pub key: String,
2207
    /// unpadded base64, the initial counter block
2208
    pub iv: String,
2209
    /// unpadded base64 SHA-256 of the whole ciphertext, so a partial read goes unchecked
2210
    pub sha256: String,
2211
}
2212
2213
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2214
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2215
pub enum MediaKind {
2216
    Image,
2217
    Video,
2218
    Audio,
2219
    File,
2220
    Sticker,
2221
}
2222
2223
#[derive(Clone, Debug, Eq, PartialEq)]
2224
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2225
#[non_exhaustive]
2226
pub struct TypingState {
2227
    pub room_id: OwnedRoomId,
2228
    pub users: Vec<OwnedUserId>,
2229
}
2230
2231
#[derive(Clone, Debug, Eq, PartialEq)]
2232
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2233
pub enum HistoryState {
2234
    Idle,
2235
    Loading,
2236
    StartReached,
2237
    Failed(String),
2238
}
2239
2240
#[derive(Clone, Debug, Eq, PartialEq)]
2241
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2242
pub enum RecentHistoryState {
2243
    /// nothing running and nothing to show, which is also what closing the room leaves
2244
    Idle,
2245
    Loading,
2246
    Loaded,
2247
    Cancelled,
2248
    /// stays until a retry, or until closing the room makes it `Idle`
2249
    Failed(String),
2250
}
2251
2252
#[derive(Clone, Debug, Eq, PartialEq)]
2253
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2254
#[non_exhaustive]
2255
pub struct EncryptionState {
2256
    pub device_id: OwnedDeviceId,
2257
    pub device_verified: bool,
2258
    pub recovery: RecoveryState,
2259
    pub key_backup: KeyBackupState,
2260
}
2261
2262
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2263
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2264
pub enum KeyBackupState {
2265
    Unknown,
2266
    Creating,
2267
    Enabling,
2268
    Resuming,
2269
    Downloading,
2270
    Enabled,
2271
    Disabling,
2272
}
2273
2274
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2275
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2276
pub enum RecoveryState {
2277
    Unknown,
2278
    Disabled,
2279
    Incomplete,
2280
    Enabled,
2281
}
2282
2283
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2284
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2285
#[non_exhaustive]
2286
pub enum VerificationAction {
2287
    /// take up a request another device sent, which arrives as `VerificationState::Incoming`
2288
    Accept,
2289
    Confirm,
2290
    Reject,
2291
    Cancel,
2292
}
2293
2294
#[derive(Clone, Debug, Eq, PartialEq)]
2295
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2296
#[non_exhaustive]
2297
pub enum VerificationTarget {
2298
    OwnIdentity,
2299
    User(OwnedUserId),
2300
    Device {
2301
        user_id: OwnedUserId,
2302
        device_id: OwnedDeviceId,
2303
    },
2304
}
2305
2306
#[derive(Clone, Debug, Eq, PartialEq)]
2307
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2308
pub enum VerificationState {
2309
    Waiting,
2310
    /// someone else asked. `Accept` to go ahead, `Cancel` to turn them down
2311
    Incoming {
2312
        user_id: OwnedUserId,
2313
        device_id: Option<OwnedDeviceId>,
2314
    },
2315
    Comparison {
2316
        emojis: Vec<(String, String)>,
2317
        decimals: (u16, u16, u16),
2318
    },
2319
    Confirmed,
2320
    Done,
2321
    Cancelled(String),
2322
    Failed(VerificationFailure),
2323
}
2324
2325
#[derive(Clone, Debug, Eq, PartialEq)]
2326
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2327
pub enum VerificationFailure {
2328
    RequestAcceptance(String),
2329
    SasStartup(String),
2330
    SasAcceptance(String),
2331
    RequestStreamEnded,
2332
    SasStreamEnded,
2333
}
2334
2335
#[derive(Clone, Debug, Eq, PartialEq)]
2336
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2337
#[non_exhaustive]
2338
pub struct EngineFailure {
2339
    pub kind: EngineErrorKind,
2340
    pub message: String,
2341
}
2342
2343
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2344
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2345
pub enum EngineErrorKind {
2346
    EventReceiverClosed,
2347
    Watcher,
2348
    Other,
2349
}