1use 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 fn timeline(&self)
52 -> impl Future<Output = Result<Timeline, timeline::Error>> + SendOutsideWasm;
53
54 fn timeline_builder(&self) -> TimelineBuilder;
63
64 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 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 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 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 fn send(
126 &self,
127 content: AnyMessageLikeEventContent,
128 ) -> impl Future<Output = Result<(), super::Error>> + SendOutsideWasm + '_;
129
130 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 fn get_encryption_info(
143 &self,
144 session_id: &str,
145 sender: &UserId,
146 ) -> impl Future<Output = Option<Arc<EncryptionInfo>>> + SendOutsideWasm;
147
148 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 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 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
309pub(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}