acter_core/
models.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
mod attachments;
mod calendar;
mod comments;
mod common;
mod news;
mod pins;
mod reactions;
mod read_receipts;
mod rsvp;
mod stories;
mod tag;
mod tasks;
#[cfg(test)]
mod test;

use async_recursion::async_recursion;
pub use attachments::{Attachment, AttachmentUpdate, AttachmentsManager, AttachmentsStats};
pub use calendar::{CalendarEvent, CalendarEventUpdate};
pub use comments::{Comment, CommentUpdate, CommentsManager, CommentsStats};
pub use common::*;
pub use core::fmt::Debug;
use enum_dispatch::enum_dispatch;
use matrix_sdk::room::Room;
use matrix_sdk_base::ruma::{
    events::{
        reaction::ReactionEventContent,
        room::redaction::{OriginalRoomRedactionEvent, RoomRedactionEventContent},
        MessageLikeEvent, StaticEventContent, UnsignedRoomRedactionEvent,
    },
    EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, UserId,
};
pub use news::{NewsEntry, NewsEntryUpdate};
pub use pins::{Pin, PinUpdate};
pub use reactions::{Reaction, ReactionManager, ReactionStats};
pub use read_receipts::{ReadReceipt, ReadReceiptStats, ReadReceiptsManager};
pub use rsvp::{Rsvp, RsvpManager, RsvpStats};
use serde::{Deserialize, Serialize};
pub use stories::{Story, StoryUpdate};
pub use tag::Tag;
pub use tasks::{
    Task, TaskList, TaskListUpdate, TaskSelfAssign, TaskSelfUnassign, TaskStats, TaskUpdate,
};
use tracing::{error, info, trace, warn};

#[cfg(test)]
pub use test::{TestModel, TestModelBuilder, TestModelBuilderError};

pub use crate::store::Store;
use crate::{
    events::{
        attachments::{AttachmentEventContent, AttachmentUpdateEventContent},
        calendar::{CalendarEventEventContent, CalendarEventUpdateEventContent},
        comments::{CommentEventContent, CommentUpdateEventContent},
        news::{NewsEntryEventContent, NewsEntryUpdateEventContent},
        pins::{PinEventContent, PinUpdateEventContent},
        read_receipt::ReadReceiptEventContent,
        rsvp::RsvpEventContent,
        stories::{StoryEventContent, StoryUpdateEventContent},
        tasks::{
            TaskEventContent, TaskListEventContent, TaskListUpdateEventContent,
            TaskSelfAssignEventContent, TaskSelfUnassignEventContent, TaskUpdateEventContent,
        },
        AnyActerEvent,
    },
    executor::Executor,
};

#[derive(Debug, Eq, PartialEq)]
pub enum Capability {
    // someone can add reaction on this
    Reactable,
    // someone can add comment on this
    Commentable,
    // someone can add attachment on this
    Attachmentable,
    // users reads/views are being tracked
    ReadTracking,
    // another custom capability
    Custom(&'static str),
}

#[async_recursion]
pub async fn transition_tree(
    store: &Store,
    parents: Vec<String>,
    model: &AnyActerModel,
) -> crate::Result<Vec<AnyActerModel>> {
    let mut models = vec![];
    for p in parents {
        let mut parent = store.get(&p).await?;
        if parent.transition(model)? {
            if let Some(grandparents) = parent.belongs_to() {
                let mut parent_models = transition_tree(store, grandparents, &parent).await?;
                if !parent_models.is_empty() {
                    models.append(&mut parent_models);
                }
            }
            models.push(parent);
        }
    }
    Ok(models)
}

pub async fn default_model_execute(
    store: &Store,
    model: AnyActerModel,
) -> crate::Result<Vec<String>> {
    trace!(event_id=?model.event_id(), ?model, "handling");
    let Some(belongs_to) = model.belongs_to() else {
        let event_id = model.event_id().to_string();
        trace!(?event_id, "saving simple model");
        return store.save(model).await;
    };

    trace!(event_id=?model.event_id(), ?belongs_to, "transitioning tree");
    let mut models = transition_tree(store, belongs_to, &model).await?;
    models.push(model);
    store.save_many(models).await
}

#[enum_dispatch(AnyActerModel)]
pub trait ActerModel: Debug {
    fn indizes(&self, user_id: &UserId) -> Vec<String>;
    /// The key to store this model under
    fn event_id(&self) -> &EventId;

    /// The room id this model belongs to
    fn room_id(&self) -> &RoomId;

    /// The models to inform about this model as it belongs to that
    fn belongs_to(&self) -> Option<Vec<String>> {
        None
    }

    /// activate to enable commenting support for this type of model
    fn capabilities(&self) -> &[Capability] {
        &[]
    }
    /// The execution to run when this model is found.
    async fn execute(self, store: &Store) -> crate::Result<Vec<String>>;

    /// handle transition from an external Item upon us
    fn transition(&mut self, model: &AnyActerModel) -> crate::Result<bool> {
        warn!(?self, ?model, "Transition has not been implemented");
        Ok(false)
    }
    /// The execution to run when this model is found.
    async fn redact(
        &self,
        store: &Store,
        redaction_model: RedactedActerModel,
    ) -> crate::Result<Vec<String>> {
        trace!(event_id=?redaction_model.event_id(), ?redaction_model, "handling");
        let Some(belongs_to) = self.belongs_to() else {
            let event_id = redaction_model.event_id();
            trace!(?event_id, "saving simple model");
            return store.save(redaction_model.into()).await;
        };
        let model: AnyActerModel = redaction_model.into();
        trace!(event_id=?model.event_id(), ?belongs_to, "transitioning tree");
        let mut models = transition_tree(store, belongs_to, &model).await?;
        models.push(model);
        store.save_many(models).await
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct RedactionContent {
    /// Data specific to the event type.
    pub content: RoomRedactionEventContent,

    /// The globally unique event identifier for the event.
    pub event_id: OwnedEventId,

    /// The fully-qualified ID of the user who sent this event.
    pub sender: OwnedUserId,

    /// Timestamp in milliseconds on originating homeserver when this event was sent.
    pub origin_server_ts: MilliSecondsSinceUnixEpoch,
}

impl From<UnsignedRoomRedactionEvent> for RedactionContent {
    fn from(value: UnsignedRoomRedactionEvent) -> Self {
        let UnsignedRoomRedactionEvent {
            content,
            event_id,
            sender,
            origin_server_ts,
            ..
        } = value;
        RedactionContent {
            content,
            event_id,
            sender,
            origin_server_ts,
        }
    }
}

impl From<OriginalRoomRedactionEvent> for RedactionContent {
    fn from(value: OriginalRoomRedactionEvent) -> Self {
        let OriginalRoomRedactionEvent {
            content,
            event_id,
            sender,
            origin_server_ts,
            ..
        } = value;
        RedactionContent {
            content,
            event_id,
            sender,
            origin_server_ts,
        }
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct RedactedActerModel {
    orig_type: String,
    indizes: Vec<String>,
    meta: EventMeta,
    content: RedactionContent,
}

impl RedactedActerModel {
    pub fn origin_type(&self) -> &str {
        &self.orig_type
    }
}

impl RedactedActerModel {
    pub fn new(
        orig_type: String,
        orig_indizes: Vec<String>,
        meta: EventMeta,
        content: RedactionContent,
    ) -> Self {
        RedactedActerModel {
            meta,
            orig_type,
            content,
            indizes: orig_indizes
                .into_iter()
                .map(|s| format!("{s}::redacted"))
                .collect(),
        }
    }
}

impl ActerModel for RedactedActerModel {
    fn room_id(&self) -> &RoomId {
        &self.meta.room_id
    }
    fn indizes(&self, _user_id: &UserId) -> Vec<String> {
        self.indizes.clone()
    }

    fn event_id(&self) -> &EventId {
        &self.meta.event_id
    }

    async fn execute(self, store: &Store) -> crate::Result<Vec<String>> {
        default_model_execute(store, self.into()).await
    }

    fn transition(&mut self, model: &AnyActerModel) -> crate::Result<bool> {
        // Transitions aren’t possible anymore when the source has been redacted
        // so we eat up the content and just log that we had to do that.
        info!(?self, ?model, "Transition on Redaction Swallowed");
        Ok(false)
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EventMeta {
    /// The globally unique event identifier attached to this event
    pub event_id: OwnedEventId,

    /// The fully-qualified ID of the user who sent created this event
    pub sender: OwnedUserId,

    /// Timestamp in milliseconds on originating homeserver when the event was created
    pub origin_server_ts: MilliSecondsSinceUnixEpoch,

    /// The ID of the room of this event
    pub room_id: OwnedRoomId,

    /// Optional redacted event identifier
    #[serde(default)]
    redacted: Option<OwnedEventId>,
}

impl EventMeta {
    pub fn for_redacted_source(value: &OriginalRoomRedactionEvent) -> Option<Self> {
        let target_event_id = value.redacts.clone()?;

        Some(EventMeta {
            event_id: target_event_id,
            sender: value.sender.clone(),
            room_id: value.room_id.clone(),
            origin_server_ts: value.origin_server_ts,
            redacted: None,
        })
    }
}

pub async fn can_redact(room: &Room, sender_id: &UserId) -> crate::error::Result<bool> {
    let client = room.client();
    let Some(user_id) = client.user_id() else {
        // not logged in means we can’t redact
        return Ok(false);
    };
    Ok(if sender_id == user_id {
        room.can_user_redact_own(user_id).await?
    } else {
        room.can_user_redact_other(user_id).await?
    })
}

#[enum_dispatch]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum AnyActerModel {
    RedactedActerModel,

    // -- Calendar
    CalendarEvent(CalendarEvent),
    CalendarEventUpdate(CalendarEventUpdate),

    // -- Tasks
    TaskList(TaskList),
    TaskListUpdate(TaskListUpdate),
    Task(Task),
    TaskUpdate(TaskUpdate),
    TaskSelfAssign(TaskSelfAssign),
    TaskSelfUnassign(TaskSelfUnassign),

    // -- Pins
    Pin(Pin),
    PinUpdate(PinUpdate),

    // -- News
    NewsEntry(NewsEntry),
    NewsEntryUpdate(NewsEntryUpdate),

    // -- News
    Story(Story),
    StoryUpdate(StoryUpdate),

    // -- more generics
    Comment(Comment),
    CommentUpdate(CommentUpdate),

    Attachment(Attachment),
    AttachmentUpdate(AttachmentUpdate),

    Rsvp(Rsvp),
    Reaction(Reaction),
    ReadReceipt(ReadReceipt),

    #[cfg(test)]
    TestModel(TestModel),
}

impl AnyActerModel {
    pub fn model_type(&self) -> &str {
        match self {
            AnyActerModel::CalendarEvent(_) => CalendarEventEventContent::TYPE,
            AnyActerModel::CalendarEventUpdate(_) => CalendarEventUpdateEventContent::TYPE,
            AnyActerModel::TaskList(_) => TaskListEventContent::TYPE,
            AnyActerModel::TaskListUpdate(_) => TaskListUpdateEventContent::TYPE,
            AnyActerModel::Task(_) => TaskEventContent::TYPE,
            AnyActerModel::TaskUpdate(_) => TaskUpdateEventContent::TYPE,
            AnyActerModel::TaskSelfAssign(_) => TaskSelfAssignEventContent::TYPE,
            AnyActerModel::TaskSelfUnassign(_) => TaskSelfUnassignEventContent::TYPE,
            AnyActerModel::Pin(_) => PinEventContent::TYPE,
            AnyActerModel::PinUpdate(_) => PinUpdateEventContent::TYPE,
            AnyActerModel::NewsEntry(_) => NewsEntryEventContent::TYPE,
            AnyActerModel::NewsEntryUpdate(_) => NewsEntryUpdateEventContent::TYPE,
            AnyActerModel::Story(_) => StoryEventContent::TYPE,
            AnyActerModel::StoryUpdate(_) => StoryUpdateEventContent::TYPE,
            AnyActerModel::Comment(_) => CommentEventContent::TYPE,
            AnyActerModel::CommentUpdate(_) => CommentUpdateEventContent::TYPE,
            AnyActerModel::Attachment(_) => AttachmentEventContent::TYPE,
            AnyActerModel::AttachmentUpdate(_) => AttachmentUpdateEventContent::TYPE,
            AnyActerModel::Rsvp(_) => RsvpEventContent::TYPE,
            AnyActerModel::Reaction(_) => ReactionEventContent::TYPE,
            AnyActerModel::ReadReceipt(_) => ReadReceiptEventContent::TYPE,
            AnyActerModel::RedactedActerModel(..) => "unknown_redacted_model",
            #[cfg(test)]
            AnyActerModel::TestModel(_) => "test_model",
        }
    }

    pub async fn execute(executor: &Executor, event: AnyActerEvent) {
        let room_id = event.room_id().to_owned();
        match AnyActerModel::try_from(event) {
            Ok(model) => {
                trace!(?room_id, ?model, "handling timeline event");
                if let Err(e) = executor.handle(model).await {
                    error!("Failure handling event: {:}", e);
                }
            }
            Err(ParseError::ModelRedacted {
                model_type,
                meta,
                reason,
            }) => {
                trace!(?meta.room_id, model_type, ?meta.event_id, "redacted event");
                if let Err(e) = executor.redact(model_type, meta, reason).await {
                    error!("Failure redacting {:}", e);
                }
            }
            Err(ParseError::UnsupportedEvent(AnyActerEvent::RegularTimelineEvent(_))) => {
                // save to hard ignore
                trace!(?room_id, "ignoring timeline event");
            }
            Err(ParseError::UnsupportedEvent(inner)) => {
                // sae to hard ignore
                error!(?room_id, ?inner, "seems like the dev failed to add parsing");
            }
        };
    }
}

#[derive(thiserror::Error, Debug)]
pub enum ParseError {
    #[error("Model {meta:?} ({model_type}): {reason:?}")]
    ModelRedacted {
        model_type: String,
        meta: EventMeta,
        reason: UnsignedRoomRedactionEvent,
    },
    #[error("Not supported Acter Event")]
    UnsupportedEvent(AnyActerEvent),
}

impl TryFrom<AnyActerEvent> for AnyActerModel {
    type Error = ParseError;
    fn try_from(value: AnyActerEvent) -> Result<Self, Self::Error> {
        match value {
            // Originals
            AnyActerEvent::CalendarEvent(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::CalendarEvent(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: CalendarEventEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::CalendarEventUpdate(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::CalendarEventUpdate(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: CalendarEventUpdateEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::Pin(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::Pin(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: PinEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::PinUpdate(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::PinUpdate(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: PinUpdateEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::NewsEntry(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::NewsEntry(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: NewsEntryEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::NewsEntryUpdate(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::NewsEntryUpdate(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: NewsEntryUpdateEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },

            AnyActerEvent::Story(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::Story(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: StoryEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::StoryUpdate(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::StoryUpdate(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: StoryUpdateEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::TaskList(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::TaskList(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: TaskListEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::TaskListUpdate(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::TaskListUpdate(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: TaskListUpdateEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::Task(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::Task(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: TaskEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::TaskUpdate(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::TaskUpdate(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: TaskUpdateEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::TaskSelfAssign(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::TaskSelfAssign(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: TaskSelfAssignEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::TaskSelfUnassign(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::TaskSelfUnassign(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: TaskSelfUnassignEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::Comment(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::Comment(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: CommentEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::CommentUpdate(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::CommentUpdate(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: CommentUpdateEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::Attachment(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::Attachment(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: AttachmentEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::AttachmentUpdate(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::AttachmentUpdate(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: AttachmentUpdateEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            AnyActerEvent::Rsvp(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::Rsvp(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: RsvpEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },

            AnyActerEvent::Reaction(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::Reaction(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: ReactionEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },

            AnyActerEvent::ReadReceipt(e) => match e {
                MessageLikeEvent::Original(m) => Ok(AnyActerModel::ReadReceipt(m.into())),
                MessageLikeEvent::Redacted(r) => Err(Self::Error::ModelRedacted {
                    model_type: ReadReceiptEventContent::TYPE.to_owned(),
                    meta: EventMeta {
                        room_id: r.room_id,
                        event_id: r.event_id,
                        sender: r.sender,
                        origin_server_ts: r.origin_server_ts,
                        redacted: None,
                    },
                    reason: r.unsigned.redacted_because,
                }),
            },
            // should not really happen
            AnyActerEvent::RegularTimelineEvent(_) => Err(Self::Error::UnsupportedEvent(value)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Result;

    use matrix_sdk_base::ruma::owned_event_id;
    #[test]
    fn ensure_minimal_tasklist_parses() -> Result<()> {
        let json_raw = r#"{"type":"global.acter.dev.tasklist",
            "room_id":"!euhIDqDVvVXulrhWgN:ds9.acter.global","sender":"@odo:ds9.acter.global",
            "content":{"name":"Daily Security Brief"},"origin_server_ts":1672407531453,
            "unsigned":{"age":11523850},
            "event_id":"$KwumA4L3M-duXu0I3UA886LvN-BDCKAyxR1skNfnh3c",
            "user_id":"@odo:ds9.acter.global","age":11523850}"#;
        let event = serde_json::from_str::<AnyActerEvent>(json_raw)?;
        AnyActerModel::try_from(event).unwrap();
        Ok(())
    }
    #[test]
    fn ensure_minimal_pin_parses() -> Result<()> {
        let json_raw = r#"{"type":"global.acter.dev.pin",
            "room_id":"!euhIDqDVvVXulrhWgN:ds9.acter.global","sender":"@odo:ds9.acter.global",
            "content":{"title":"Seat arrangement"},"origin_server_ts":1672407531453,
            "unsigned":{"age":11523850},
            "event_id":"$KwumA4L3M-duXu0I3UA886LvN-BDCKAyxR1skNfnh3c",
            "user_id":"@odo:ds9.acter.global","age":11523850}"#;
        let event = serde_json::from_str::<AnyActerEvent>(json_raw)?;
        AnyActerModel::try_from(event).unwrap();
        // assert!(matches!(event, AnyCreation::TaskList(_)));
        Ok(())
    }

    #[test]
    #[allow(unused_variables)]
    fn ensure_redacted_news_parses() -> Result<()> {
        let json_raw = r#"{
            "content": {},
            "origin_server_ts": 1689158713657,
            "room_id": "!uUufOaBOZwafrtxhoO:effektio.org",
            "sender": "@emilvincentz:effektio.org",
            "type": "global.acter.dev.news",
            "unsigned": {
              "redacted_by": "$2_k7NsG2GOGfyeNOvV55OovysVl7WGKgGEY2hv6VosY",
              "redacted_because": {
                "type": "m.room.redaction",
                "room_id": "!uUufOaBOZwafrtxhoO:effektio.org",
                "sender": "@ben:acter.global",
                "content": {
                  "reason": "",
                  "redacts": "$WAfv0heG198eXRIRPVVuli2Guc9pI2PB_spOcS8NXco"
                },
                "redacts": "$WAfv0heG198eXRIRPVVuli2Guc9pI2PB_spOcS8NXco",
                "origin_server_ts": 1694550003475,
                "unsigned": {
                  "age": 56316493,
                  "transaction_id": "1c85807d10074b17941f84ac02f168ee"
                },
                "event_id": "$2_k7NsG2GOGfyeNOvV55OovysVl7WGKgGEY2hv6VosY",
                "user_id": "@ben:acter.global",
                "age": 56316493
              }
            },
            "event_id": "$WAfv0heG198eXRIRPVVuli2Guc9pI2PB_spOcS8NXco",
            "user_id": "@emilvincentz:effektio.org",
            "redacted_because": {
              "type": "m.room.redaction",
              "room_id": "!uUufOaBOZwafrtxhoO:effektio.org",
              "sender": "@ben:acter.global",
              "content": {
                "reason": "",
                "redacts": "$WAfv0heG198eXRIRPVVuli2Guc9pI2PB_spOcS8NXco"
              },
              "redacts": "$WAfv0heG198eXRIRPVVuli2Guc9pI2PB_spOcS8NXco",
              "origin_server_ts": 1694550003475,
              "unsigned": {
                "age": 56316493,
                "transaction_id": "1c85807d10074b17941f84ac02f168ee"
              },
              "event_id": "$2_k7NsG2GOGfyeNOvV55OovysVl7WGKgGEY2hv6VosY",
              "user_id": "@ben:acter.global",
              "age": 56316493
            }
          }"#;
        let event = serde_json::from_str::<AnyActerEvent>(json_raw)?;
        let acter_ev_result = AnyActerModel::try_from(event.clone());
        let model_type = "global.acter.dev.news".to_owned();
        let event_id = owned_event_id!("$2_k7NsG2GOGfyeNOvV55OovysVl7WGKgGEY2hv6VosY");
        assert!(
            matches!(
                acter_ev_result,
                Err(ParseError::ModelRedacted {
                    ref model_type,
                    meta: EventMeta { ref event_id, .. },
                    ..
                })
            ),
            "Didn’t receive expected error: {acter_ev_result:?}"
        );
        // assert!(matches!(event, AnyCreation::TaskList(_)));
        Ok(())
    }

    #[test]
    #[allow(unused_variables)]
    fn ensure_redacted_pin_parses() -> Result<()> {
        let json_raw = r#"{
            "content": {},
            "origin_server_ts": 1689158713657,
            "room_id": "!uUufOaBOZwafrtxhoO:effektio.org",
            "sender": "@emilvincentz:effektio.org",
            "type": "global.acter.dev.pin",
            "unsigned": {
              "redacted_by": "$2_k7NsG2GOGfyeNOvV55OovysVl7WGKgGEY2hv6VosY",
              "redacted_because": {
                "type": "m.room.redaction",
                "room_id": "!uUufOaBOZwafrtxhoO:effektio.org",
                "sender": "@ben:acter.global",
                "content": {
                  "reason": "",
                  "redacts": "$WAfv0heG198eXRIRPVVuli2Guc9pI2PB_spOcS8NXco"
                },
                "redacts": "$WAfv0heG198eXRIRPVVuli2Guc9pI2PB_spOcS8NXco",
                "origin_server_ts": 1694550003475,
                "unsigned": {
                  "age": 56316493,
                  "transaction_id": "1c85807d10074b17941f84ac02f168ee"
                },
                "event_id": "$2_k7NsG2GOGfyeNOvV55OovysVl7WGKgGEY2hv6VosY",
                "user_id": "@ben:acter.global",
                "age": 56316493
              }
            },
            "event_id": "$WAfv0heG198eXRIRPVVuli2Guc9pI2PB_spOcS8NXco",
            "user_id": "@emilvincentz:effektio.org",
            "redacted_because": {
              "type": "m.room.redaction",
              "room_id": "!uUufOaBOZwafrtxhoO:effektio.org",
              "sender": "@ben:acter.global",
              "content": {
                "reason": "",
                "redacts": "$WAfv0heG198eXRIRPVVuli2Guc9pI2PB_spOcS8NXco"
              },
              "redacts": "$WAfv0heG198eXRIRPVVuli2Guc9pI2PB_spOcS8NXco",
              "origin_server_ts": 1694550003475,
              "unsigned": {
                "age": 56316493,
                "transaction_id": "1c85807d10074b17941f84ac02f168ee"
              },
              "event_id": "$2_k7NsG2GOGfyeNOvV55OovysVl7WGKgGEY2hv6VosY",
              "user_id": "@ben:acter.global",
              "age": 56316493
            }
          }"#;
        let event = serde_json::from_str::<AnyActerEvent>(json_raw)?;
        let acter_ev_result = AnyActerModel::try_from(event);
        let model_type = "global.acter.dev.pin".to_owned();
        let event_id = owned_event_id!("$KwumA4L3M-duXu0I3UA886LvN-BDCKAyxR1skNfnh3c");
        assert!(
            matches!(
                acter_ev_result,
                Err(ParseError::ModelRedacted {
                    ref model_type,
                    meta: EventMeta { ref event_id, .. },
                    ..
                })
            ),
            "Didn’t receive expected error: {acter_ev_result:?}"
        );
        // assert!(matches!(event, AnyCreation::TaskList(_)));
        Ok(())
    }
}