fractal/utils/matrix/
ext_traits.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
//! Extension traits for Matrix types.

use std::borrow::Cow;

use gtk::{glib, prelude::*};
use matrix_sdk_ui::timeline::{
    AnyOtherFullStateEventContent, EventTimelineItem, Message, TimelineEventItemId,
    TimelineItemContent,
};
use ruma::{
    events::{room::message::MessageType, AnySyncTimelineEvent},
    serde::Raw,
};
use serde::Deserialize;

/// Helper trait for types possibly containing an `@room` mention.
pub(crate) trait AtMentionExt {
    /// Whether this event might contain an `@room` mention.
    ///
    /// This means that either it does not have intentional mentions, or it has
    /// intentional mentions and `room` is set to `true`.
    fn can_contain_at_room(&self) -> bool;
}

impl AtMentionExt for TimelineItemContent {
    fn can_contain_at_room(&self) -> bool {
        match self {
            TimelineItemContent::Message(msg) => msg.can_contain_at_room(),
            _ => false,
        }
    }
}

impl AtMentionExt for Message {
    fn can_contain_at_room(&self) -> bool {
        let Some(mentions) = self.mentions() else {
            return true;
        };

        mentions.room
    }
}

/// Extension trait for [`TimelineEventItemId`].
pub(crate) trait TimelineEventItemIdExt: Sized {
    /// The type used to represent a [`TimelineEventItemId`] as a `GVariant`.
    fn static_variant_type() -> Cow<'static, glib::VariantTy>;

    /// Convert this [`TimelineEventItemId`] to a `GVariant`.
    fn to_variant(&self) -> glib::Variant;

    /// Try to convert a `GVariant` to a [`TimelineEventItemId`].
    fn from_variant(variant: &glib::Variant) -> Option<Self>;
}

impl TimelineEventItemIdExt for TimelineEventItemId {
    fn static_variant_type() -> Cow<'static, glib::VariantTy> {
        Cow::Borrowed(glib::VariantTy::STRING)
    }

    fn to_variant(&self) -> glib::Variant {
        let s = match self {
            Self::TransactionId(txn_id) => format!("transaction_id:{txn_id}"),
            Self::EventId(event_id) => format!("event_id:{event_id}"),
        };

        s.to_variant()
    }

    fn from_variant(variant: &glib::Variant) -> Option<Self> {
        let s = variant.str()?;

        if let Some(s) = s.strip_prefix("transaction_id:") {
            Some(Self::TransactionId(s.into()))
        } else if let Some(s) = s.strip_prefix("event_id:") {
            s.try_into().ok().map(Self::EventId)
        } else {
            None
        }
    }
}

/// Extension trait for [`TimelineItemContent`].
pub(crate) trait TimelineItemContentExt {
    /// Whether this content can count as an unread message.
    ///
    /// This follows the algorithm in [MSC2654], excluding events that we do not
    /// show in the timeline.
    ///
    /// [MSC2654]: https://github.com/matrix-org/matrix-spec-proposals/pull/2654
    fn counts_as_unread(&self) -> bool;

    /// Whether we can show the header for this content.
    fn can_show_header(&self) -> bool;

    /// Whether this content is edited.
    fn is_edited(&self) -> bool;
}

impl TimelineItemContentExt for TimelineItemContent {
    fn counts_as_unread(&self) -> bool {
        match self {
            TimelineItemContent::Message(message) => {
                !matches!(message.msgtype(), MessageType::Notice(_))
            }
            TimelineItemContent::Sticker(_) => true,
            TimelineItemContent::OtherState(state) => matches!(
                state.content(),
                AnyOtherFullStateEventContent::RoomTombstone(_)
            ),
            _ => false,
        }
    }

    fn can_show_header(&self) -> bool {
        match self {
            TimelineItemContent::Message(message) => {
                matches!(
                    message.msgtype(),
                    MessageType::Audio(_)
                        | MessageType::File(_)
                        | MessageType::Image(_)
                        | MessageType::Location(_)
                        | MessageType::Notice(_)
                        | MessageType::Text(_)
                        | MessageType::Video(_)
                )
            }
            TimelineItemContent::Sticker(_) => true,
            _ => false,
        }
    }

    fn is_edited(&self) -> bool {
        match self {
            TimelineItemContent::Message(msg) => msg.is_edited(),
            _ => false,
        }
    }
}

/// Extension trait for [`EventTimelineItem`].
pub(crate) trait EventTimelineItemExt {
    /// The JSON source for the latest edit of this item, if any.
    fn latest_edit_raw(&self) -> Option<Raw<AnySyncTimelineEvent>>;
}

impl EventTimelineItemExt for EventTimelineItem {
    /// The JSON source for the latest edit of this event, if any.
    fn latest_edit_raw(&self) -> Option<Raw<AnySyncTimelineEvent>> {
        if let Some(raw) = self.latest_edit_json() {
            return Some(raw.clone());
        }

        self.original_json()?
            .get_field::<RawUnsigned>("unsigned")
            .ok()
            .flatten()?
            .relations?
            .replace
    }
}

/// Raw unsigned event data.
///
/// Used as a fallback to get the JSON of the latest edit.
#[derive(Debug, Clone, Deserialize)]
struct RawUnsigned {
    #[serde(rename = "m.relations")]
    relations: Option<RawBundledRelations>,
}

/// Raw bundled event relations.
///
/// Used as a fallback to get the JSON of the latest edit.
#[derive(Debug, Clone, Deserialize)]
struct RawBundledRelations {
    #[serde(rename = "m.replace")]
    replace: Option<Raw<AnySyncTimelineEvent>>,
}