matrix_sdk_ui/timeline/
traits.rs

1// Copyright 2025 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{future::Future, sync::Arc};
16
17use eyeball::Subscriber;
18use indexmap::IndexMap;
19#[cfg(test)]
20use matrix_sdk::crypto::{DecryptionSettings, RoomEventDecryptionResult, TrustRequirement};
21use matrix_sdk::{
22    crypto::types::events::CryptoContextInfo,
23    deserialized_responses::{EncryptionInfo, TimelineEvent},
24    paginators::{thread::PaginableThread, PaginableRoom},
25    room::PushContext,
26    AsyncTraitDeps, Result, Room, SendOutsideWasm,
27};
28use matrix_sdk_base::{latest_event::LatestEvent, RoomInfo};
29use ruma::{
30    events::{
31        fully_read::FullyReadEventContent,
32        receipt::{Receipt, ReceiptThread, ReceiptType},
33        AnyMessageLikeEventContent, AnySyncTimelineEvent,
34    },
35    serde::Raw,
36    EventId, OwnedEventId, OwnedTransactionId, OwnedUserId, RoomVersionId, UserId,
37};
38use tracing::error;
39
40use super::{EventTimelineItem, Profile, RedactError, TimelineBuilder};
41use crate::timeline::{self, pinned_events_loader::PinnedEventsRoom, Timeline};
42
43pub trait RoomExt {
44    /// Get a [`Timeline`] for this room.
45    ///
46    /// This offers a higher-level API than event handlers, in treating things
47    /// like edits and reactions as updates of existing items rather than new
48    /// independent events.
49    ///
50    /// This is the same as using `room.timeline_builder().build()`.
51    fn timeline(&self)
52        -> impl Future<Output = Result<Timeline, timeline::Error>> + SendOutsideWasm;
53
54    /// Get a [`TimelineBuilder`] for this room.
55    ///
56    /// [`Timeline`] offers a higher-level API than event handlers, in treating
57    /// things like edits and reactions as updates of existing items rather
58    /// than new independent events.
59    ///
60    /// This allows to customize settings of the [`Timeline`] before
61    /// constructing it.
62    fn timeline_builder(&self) -> TimelineBuilder;
63
64    /// Return an optional [`EventTimelineItem`] corresponding to this room's
65    /// latest event.
66    fn latest_event_item(
67        &self,
68    ) -> impl Future<Output = Option<EventTimelineItem>> + SendOutsideWasm;
69}
70
71impl RoomExt for Room {
72    async fn timeline(&self) -> Result<Timeline, timeline::Error> {
73        self.timeline_builder().build().await
74    }
75
76    fn timeline_builder(&self) -> TimelineBuilder {
77        TimelineBuilder::new(self).track_read_marker_and_receipts()
78    }
79
80    async fn latest_event_item(&self) -> Option<EventTimelineItem> {
81        if let Some(latest_event) = (**self).latest_event() {
82            EventTimelineItem::from_latest_event(self.client(), self.room_id(), latest_event).await
83        } else {
84            None
85        }
86    }
87}
88
89pub(super) trait RoomDataProvider:
90    Clone + PaginableRoom + PaginableThread + PinnedEventsRoom + 'static
91{
92    fn own_user_id(&self) -> &UserId;
93    fn room_version(&self) -> RoomVersionId;
94
95    fn crypto_context_info(&self)
96        -> impl Future<Output = CryptoContextInfo> + SendOutsideWasm + '_;
97
98    fn profile_from_user_id<'a>(
99        &'a self,
100        user_id: &'a UserId,
101    ) -> impl Future<Output = Option<Profile>> + SendOutsideWasm + 'a;
102    fn profile_from_latest_event(&self, latest_event: &LatestEvent) -> Option<Profile>;
103
104    /// Loads a user receipt from the storage backend.
105    fn load_user_receipt<'a>(
106        &'a self,
107        receipt_type: ReceiptType,
108        thread: ReceiptThread,
109        user_id: &'a UserId,
110    ) -> impl Future<Output = Option<(OwnedEventId, Receipt)>> + SendOutsideWasm + 'a;
111
112    /// Loads read receipts for an event from the storage backend.
113    fn load_event_receipts<'a>(
114        &'a self,
115        event_id: &'a EventId,
116        receipt_thread: ReceiptThread,
117    ) -> impl Future<Output = IndexMap<OwnedUserId, Receipt>> + SendOutsideWasm + 'a;
118
119    /// Load the current fully-read event id, from storage.
120    fn load_fully_read_marker(&self) -> impl Future<Output = Option<OwnedEventId>> + '_;
121
122    fn push_context(&self) -> impl Future<Output = Option<PushContext>> + SendOutsideWasm + '_;
123
124    /// Send an event to that room.
125    fn send(
126        &self,
127        content: AnyMessageLikeEventContent,
128    ) -> impl Future<Output = Result<(), super::Error>> + SendOutsideWasm + '_;
129
130    /// Redact an event from that room.
131    fn redact<'a>(
132        &'a self,
133        event_id: &'a EventId,
134        reason: Option<&'a str>,
135        transaction_id: Option<OwnedTransactionId>,
136    ) -> impl Future<Output = Result<(), super::Error>> + SendOutsideWasm + 'a;
137
138    fn room_info(&self) -> Subscriber<RoomInfo>;
139
140    /// Return the encryption info for the Megolm session with the supplied
141    /// session ID.
142    fn get_encryption_info(
143        &self,
144        session_id: &str,
145        sender: &UserId,
146    ) -> impl Future<Output = Option<Arc<EncryptionInfo>>> + SendOutsideWasm;
147
148    /// Loads an event from the cache or network.
149    fn load_event<'a>(
150        &'a self,
151        event_id: &'a EventId,
152    ) -> impl Future<Output = Result<TimelineEvent>> + SendOutsideWasm + 'a;
153}
154
155impl RoomDataProvider for Room {
156    fn own_user_id(&self) -> &UserId {
157        (**self).own_user_id()
158    }
159
160    fn room_version(&self) -> RoomVersionId {
161        (**self).clone_info().room_version_or_default()
162    }
163
164    async fn crypto_context_info(&self) -> CryptoContextInfo {
165        self.crypto_context_info().await
166    }
167
168    async fn profile_from_user_id<'a>(&'a self, user_id: &'a UserId) -> Option<Profile> {
169        match self.get_member_no_sync(user_id).await {
170            Ok(Some(member)) => Some(Profile {
171                display_name: member.display_name().map(ToOwned::to_owned),
172                display_name_ambiguous: member.name_ambiguous(),
173                avatar_url: member.avatar_url().map(ToOwned::to_owned),
174            }),
175            Ok(None) if self.are_members_synced() => Some(Profile::default()),
176            Ok(None) => None,
177            Err(e) => {
178                error!(%user_id, "Failed to fetch room member information: {e}");
179                None
180            }
181        }
182    }
183
184    fn profile_from_latest_event(&self, latest_event: &LatestEvent) -> Option<Profile> {
185        if !latest_event.has_sender_profile() {
186            return None;
187        }
188
189        Some(Profile {
190            display_name: latest_event.sender_display_name().map(ToOwned::to_owned),
191            display_name_ambiguous: latest_event.sender_name_ambiguous().unwrap_or(false),
192            avatar_url: latest_event.sender_avatar_url().map(ToOwned::to_owned),
193        })
194    }
195
196    async fn load_user_receipt<'a>(
197        &'a self,
198        receipt_type: ReceiptType,
199        thread: ReceiptThread,
200        user_id: &'a UserId,
201    ) -> Option<(OwnedEventId, Receipt)> {
202        match self.load_user_receipt(receipt_type.clone(), thread.clone(), user_id).await {
203            Ok(receipt) => receipt,
204            Err(e) => {
205                error!(
206                    ?receipt_type,
207                    ?thread,
208                    ?user_id,
209                    "Failed to get read receipt for user: {e}"
210                );
211                None
212            }
213        }
214    }
215
216    async fn load_event_receipts<'a>(
217        &'a self,
218        event_id: &'a EventId,
219        receipt_thread: ReceiptThread,
220    ) -> IndexMap<OwnedUserId, Receipt> {
221        let mut result = match self
222            .load_event_receipts(ReceiptType::Read, receipt_thread.clone(), event_id)
223            .await
224        {
225            Ok(receipts) => receipts.into_iter().collect(),
226            Err(e) => {
227                error!(?event_id, ?receipt_thread, "Failed to get read receipts for event: {e}");
228                IndexMap::new()
229            }
230        };
231
232        if receipt_thread == ReceiptThread::Unthreaded {
233            // Include the main thread receipts as well, to be maximally compatible with
234            // clients using either the unthreaded or main thread receipt type.
235            let main_thread_receipts = match self
236                .load_event_receipts(ReceiptType::Read, ReceiptThread::Main, event_id)
237                .await
238            {
239                Ok(receipts) => receipts,
240                Err(e) => {
241                    error!(?event_id, "Failed to get main thread read receipts for event: {e}");
242                    Vec::new()
243                }
244            };
245            result.extend(main_thread_receipts);
246        }
247
248        result
249    }
250
251    async fn push_context(&self) -> Option<PushContext> {
252        self.push_context().await.ok().flatten()
253    }
254
255    async fn load_fully_read_marker(&self) -> Option<OwnedEventId> {
256        match self.account_data_static::<FullyReadEventContent>().await {
257            Ok(Some(fully_read)) => match fully_read.deserialize() {
258                Ok(fully_read) => Some(fully_read.content.event_id),
259                Err(e) => {
260                    error!("Failed to deserialize fully-read account data: {e}");
261                    None
262                }
263            },
264            Err(e) => {
265                error!("Failed to get fully-read account data from the store: {e}");
266                None
267            }
268            _ => None,
269        }
270    }
271
272    async fn send(&self, content: AnyMessageLikeEventContent) -> Result<(), super::Error> {
273        let _ = self.send_queue().send(content).await?;
274        Ok(())
275    }
276
277    async fn redact<'a>(
278        &'a self,
279        event_id: &'a EventId,
280        reason: Option<&'a str>,
281        transaction_id: Option<OwnedTransactionId>,
282    ) -> Result<(), super::Error> {
283        let _ = self
284            .redact(event_id, reason, transaction_id)
285            .await
286            .map_err(RedactError::HttpError)
287            .map_err(super::Error::RedactError)?;
288        Ok(())
289    }
290
291    fn room_info(&self) -> Subscriber<RoomInfo> {
292        self.subscribe_info()
293    }
294
295    async fn get_encryption_info(
296        &self,
297        session_id: &str,
298        sender: &UserId,
299    ) -> Option<Arc<EncryptionInfo>> {
300        // Pass directly on to `Room::get_encryption_info`
301        self.get_encryption_info(session_id, sender).await
302    }
303
304    async fn load_event<'a>(&'a self, event_id: &'a EventId) -> Result<TimelineEvent> {
305        self.load_or_fetch_event(event_id, None).await
306    }
307}
308
309// Internal helper to make most of retry_event_decryption independent of a room
310// object, which is annoying to create for testing and not really needed
311pub(super) trait Decryptor: AsyncTraitDeps + Clone + 'static {
312    fn decrypt_event_impl(
313        &self,
314        raw: &Raw<AnySyncTimelineEvent>,
315        push_ctx: Option<&PushContext>,
316    ) -> impl Future<Output = Result<TimelineEvent>> + SendOutsideWasm;
317}
318
319impl Decryptor for Room {
320    async fn decrypt_event_impl(
321        &self,
322        raw: &Raw<AnySyncTimelineEvent>,
323        push_ctx: Option<&PushContext>,
324    ) -> Result<TimelineEvent> {
325        self.decrypt_event(raw.cast_ref(), push_ctx).await
326    }
327}
328
329#[cfg(test)]
330impl Decryptor for (matrix_sdk_base::crypto::OlmMachine, ruma::OwnedRoomId) {
331    async fn decrypt_event_impl(
332        &self,
333        raw: &Raw<AnySyncTimelineEvent>,
334        push_ctx: Option<&PushContext>,
335    ) -> Result<TimelineEvent> {
336        let (olm_machine, room_id) = self;
337        let decryption_settings =
338            DecryptionSettings { sender_device_trust_requirement: TrustRequirement::Untrusted };
339
340        match olm_machine
341            .try_decrypt_room_event(raw.cast_ref(), room_id, &decryption_settings)
342            .await?
343        {
344            RoomEventDecryptionResult::Decrypted(decrypted) => {
345                let push_actions = push_ctx.map(|push_ctx| push_ctx.for_event(&decrypted.event));
346                Ok(TimelineEvent::from_decrypted(decrypted, push_actions))
347            }
348            RoomEventDecryptionResult::UnableToDecrypt(utd_info) => {
349                Ok(TimelineEvent::from_utd(raw.clone(), utd_info))
350            }
351        }
352    }
353}