atagen

macltok

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