atagen

macltok

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