From eb31f035e64a77ed8e5c18ea49ffc06fe78fe26a Mon Sep 17 00:00:00 2001 From: Benjamin Bouvier Date: Tue, 21 Jan 2025 15:28:32 +0100 Subject: [PATCH] refactor: turn `TimelineEvent` into `SyncTimelineEvent` As the comment noted, they're essentially doing the same thing. A `TimelineEvent` may not have computed push actions, and in that regard it seemed more correct than `SyncTimelineEvent`, so another commit will make the field optional. --- .../src/deserialized_responses.rs | 97 +------------------ .../matrix-sdk-ui/src/notification_client.rs | 21 ++-- .../src/timeline/controller/state.rs | 12 ++- .../timeline/event_item/content/message.rs | 6 +- .../matrix-sdk-ui/src/timeline/tests/mod.rs | 4 +- crates/matrix-sdk-ui/src/timeline/traits.rs | 16 ++- .../matrix-sdk-ui/tests/integration/main.rs | 12 ++- .../tests/integration/timeline/focus_event.rs | 24 ++--- .../integration/timeline/pinned_event.rs | 4 +- crates/matrix-sdk/src/event_cache/mod.rs | 4 +- .../matrix-sdk/src/event_cache/paginator.rs | 49 ++++------ crates/matrix-sdk/src/room/messages.rs | 10 +- crates/matrix-sdk/src/room/mod.rs | 25 +++-- crates/matrix-sdk/src/sliding_sync/room.rs | 9 +- crates/matrix-sdk/src/test_utils/mocks.rs | 4 +- .../tests/integration/room/common.rs | 2 +- .../tests/integration/room/joined.rs | 2 +- .../tests/integration/send_queue.rs | 6 +- testing/matrix-sdk-test/src/event_factory.rs | 6 +- 19 files changed, 110 insertions(+), 203 deletions(-) diff --git a/crates/matrix-sdk-common/src/deserialized_responses.rs b/crates/matrix-sdk-common/src/deserialized_responses.rs index cf27dae0d..9156eb576 100644 --- a/crates/matrix-sdk-common/src/deserialized_responses.rs +++ b/crates/matrix-sdk-common/src/deserialized_responses.rs @@ -15,7 +15,7 @@ use std::{collections::BTreeMap, fmt}; use ruma::{ - events::{AnyMessageLikeEvent, AnySyncTimelineEvent, AnyTimelineEvent}, + events::{AnyMessageLikeEvent, AnySyncTimelineEvent}, push::Action, serde::{ AsRefStr, AsStrAsRefStr, DebugAsRefStr, DeserializeFromCowStr, FromString, JsonObject, Raw, @@ -416,16 +416,9 @@ impl SyncTimelineEvent { } } -impl From for SyncTimelineEvent { - fn from(o: TimelineEvent) -> Self { - Self { kind: o.kind, push_actions: o.push_actions.unwrap_or_default() } - } -} - impl From for SyncTimelineEvent { fn from(decrypted: DecryptedRoomEvent) -> Self { - let timeline_event: TimelineEvent = decrypted.into(); - timeline_event.into() + Self { kind: TimelineEventKind::Decrypted(decrypted), push_actions: Vec::new() } } } @@ -471,72 +464,6 @@ impl<'de> Deserialize<'de> for SyncTimelineEvent { } } -/// Represents a matrix room event that has been returned from a Matrix -/// client-server API endpoint such as `/messages`, after initial processing. -/// -/// The "initial processing" includes an attempt to decrypt encrypted events, so -/// the main thing this adds over [`AnyTimelineEvent`] is information on -/// encryption. -/// -/// Previously, this differed from [`SyncTimelineEvent`] by wrapping an -/// [`AnyTimelineEvent`] instead of an [`AnySyncTimelineEvent`], but nowadays -/// they are essentially identical, and one of them should probably be removed. -#[derive(Clone, Debug)] -pub struct TimelineEvent { - /// The event itself, together with any information on decryption. - pub kind: TimelineEventKind, - - /// The push actions associated with this event, if we had sufficient - /// context to compute them. - pub push_actions: Option>, -} - -impl TimelineEvent { - /// Create a new `TimelineEvent` from the given raw event. - /// - /// This is a convenience constructor for a plaintext event when you don't - /// need to set `push_action`, for example inside a test. - pub fn new(event: Raw) -> Self { - Self { - // This conversion is unproblematic since a `SyncTimelineEvent` is just a - // `TimelineEvent` without the `room_id`. By converting the raw value in - // this way, we simply cause the `room_id` field in the json to be - // ignored by a subsequent deserialization. - kind: TimelineEventKind::PlainText { event: event.cast() }, - push_actions: None, - } - } - - /// Create a new `TimelineEvent` to represent the given decryption failure. - pub fn new_utd_event(event: Raw, utd_info: UnableToDecryptInfo) -> Self { - Self { kind: TimelineEventKind::UnableToDecrypt { event, utd_info }, push_actions: None } - } - - /// Returns a reference to the (potentially decrypted) Matrix event inside - /// this `TimelineEvent`. - pub fn raw(&self) -> &Raw { - self.kind.raw() - } - - /// If the event was a decrypted event that was successfully decrypted, get - /// its encryption info. Otherwise, `None`. - pub fn encryption_info(&self) -> Option<&EncryptionInfo> { - self.kind.encryption_info() - } - - /// Takes ownership of this `TimelineEvent`, returning the (potentially - /// decrypted) Matrix event within. - pub fn into_raw(self) -> Raw { - self.kind.into_raw() - } -} - -impl From for TimelineEvent { - fn from(decrypted: DecryptedRoomEvent) -> Self { - Self { kind: TimelineEventKind::Decrypted(decrypted), push_actions: None } - } -} - /// The event within a [`TimelineEvent`] or [`SyncTimelineEvent`], together with /// encryption data. #[derive(Clone, Serialize, Deserialize)] @@ -957,17 +884,15 @@ mod tests { use assert_matches::assert_matches; use insta::{assert_json_snapshot, with_settings}; use ruma::{ - device_id, event_id, - events::{room::message::RoomMessageEventContent, AnySyncTimelineEvent}, - serde::Raw, - user_id, DeviceKeyAlgorithm, + device_id, event_id, events::room::message::RoomMessageEventContent, serde::Raw, user_id, + DeviceKeyAlgorithm, }; use serde::Deserialize; use serde_json::json; use super::{ AlgorithmInfo, DecryptedRoomEvent, DeviceLinkProblem, EncryptionInfo, ShieldState, - ShieldStateCode, SyncTimelineEvent, TimelineEvent, TimelineEventKind, UnableToDecryptInfo, + ShieldStateCode, SyncTimelineEvent, TimelineEventKind, UnableToDecryptInfo, UnableToDecryptReason, UnsignedDecryptionResult, UnsignedEventLocation, VerificationLevel, VerificationState, WithheldCode, }; @@ -993,18 +918,6 @@ mod tests { ); } - #[test] - fn room_event_to_sync_room_event() { - let room_event = TimelineEvent::new(Raw::new(&example_event()).unwrap().cast()); - let converted_room_event: SyncTimelineEvent = room_event.into(); - - let converted_event: AnySyncTimelineEvent = - converted_room_event.raw().deserialize().unwrap(); - - assert_eq!(converted_event.event_id(), "$xxxxx:example.org"); - assert_eq!(converted_event.sender(), "@carl:example.com"); - } - #[test] fn old_verification_state_to_new_migration() { #[derive(Deserialize)] diff --git a/crates/matrix-sdk-ui/src/notification_client.rs b/crates/matrix-sdk-ui/src/notification_client.rs index 5af760e71..712f543c7 100644 --- a/crates/matrix-sdk-ui/src/notification_client.rs +++ b/crates/matrix-sdk-ui/src/notification_client.rs @@ -20,7 +20,7 @@ use std::{ use futures_util::{pin_mut, StreamExt as _}; use matrix_sdk::{room::Room, Client, ClientBuildError, SlidingSyncList, SlidingSyncMode}; use matrix_sdk_base::{ - deserialized_responses::TimelineEvent, sliding_sync::http, RoomState, StoreError, + deserialized_responses::SyncTimelineEvent, sliding_sync::http, RoomState, StoreError, }; use ruma::{ assign, @@ -159,7 +159,7 @@ impl NotificationClient { &self, room: &Room, raw_event: &Raw, - ) -> Result, Error> { + ) -> Result, Error> { let event: AnySyncTimelineEvent = raw_event.deserialize().map_err(|_| Error::InvalidRumaEvent)?; @@ -507,9 +507,9 @@ impl NotificationClient { if let Some(mut timeline_event) = self.retry_decryption(&room, timeline_event).await? { - let push_actions = timeline_event.push_actions.take(); + let push_actions = std::mem::take(&mut timeline_event.push_actions); raw_event = RawNotificationEvent::Timeline(timeline_event.into_raw()); - push_actions + Some(push_actions) } else { room.event_push_actions(timeline_event).await? } @@ -564,18 +564,19 @@ impl NotificationClient { timeline_event = decrypted_event; } - if let Some(actions) = timeline_event.push_actions.as_ref() { - if !actions.iter().any(|a| a.should_notify()) { - return Ok(None); - } + // TODO: nope + if !timeline_event.push_actions.is_empty() + && !timeline_event.push_actions.iter().any(|a| a.should_notify()) + { + return Ok(None); } - let push_actions = timeline_event.push_actions.take(); + let push_actions = std::mem::take(&mut timeline_event.push_actions); Ok(Some( NotificationItem::new( &room, RawNotificationEvent::Timeline(timeline_event.into_raw()), - push_actions.as_deref(), + Some(&push_actions), state_events, ) .await?, diff --git a/crates/matrix-sdk-ui/src/timeline/controller/state.rs b/crates/matrix-sdk-ui/src/timeline/controller/state.rs index 7c6b3e527..1d7a8b814 100644 --- a/crates/matrix-sdk-ui/src/timeline/controller/state.rs +++ b/crates/matrix-sdk-ui/src/timeline/controller/state.rs @@ -24,7 +24,6 @@ use itertools::Itertools as _; use matrix_sdk::{ deserialized_responses::SyncTimelineEvent, ring_buffer::RingBuffer, send_queue::SendHandle, }; -use matrix_sdk_base::deserialized_responses::TimelineEvent; #[cfg(test)] use ruma::events::receipt::ReceiptEventContent; use ruma::{ @@ -257,7 +256,7 @@ impl TimelineState { room_data_provider: &P, settings: &TimelineSettings, ) where - Fut: Future>, + Fut: Future>, { let mut txn = self.transaction(); @@ -274,9 +273,12 @@ impl TimelineState { continue; }; - event.push_actions = push_rules_context.as_ref().map(|(push_rules, push_context)| { - push_rules.get_actions(event.raw(), push_context).to_owned() - }); + event.push_actions = push_rules_context + .as_ref() + .map(|(push_rules, push_context)| { + push_rules.get_actions(event.raw(), push_context).to_owned() + }) + .unwrap_or_default(); let handle_one_res = txn .handle_remote_event( diff --git a/crates/matrix-sdk-ui/src/timeline/event_item/content/message.rs b/crates/matrix-sdk-ui/src/timeline/event_item/content/message.rs index 09ee071f9..06c715eaf 100644 --- a/crates/matrix-sdk-ui/src/timeline/event_item/content/message.rs +++ b/crates/matrix-sdk-ui/src/timeline/event_item/content/message.rs @@ -17,7 +17,7 @@ use std::{fmt, sync::Arc}; use imbl::{vector, Vector}; -use matrix_sdk::{deserialized_responses::TimelineEvent, Room}; +use matrix_sdk::{deserialized_responses::SyncTimelineEvent, Room}; use ruma::{ assign, events::{ @@ -340,14 +340,14 @@ impl RepliedToEvent { /// Try to create a `RepliedToEvent` from a `TimelineEvent` by providing the /// room. pub async fn try_from_timeline_event_for_room( - timeline_event: TimelineEvent, + timeline_event: SyncTimelineEvent, room_data_provider: &Room, ) -> Result { Self::try_from_timeline_event(timeline_event, room_data_provider).await } pub(in crate::timeline) async fn try_from_timeline_event( - timeline_event: TimelineEvent, + timeline_event: SyncTimelineEvent, room_data_provider: &P, ) -> Result { let event = match timeline_event.raw().deserialize() { diff --git a/crates/matrix-sdk-ui/src/timeline/tests/mod.rs b/crates/matrix-sdk-ui/src/timeline/tests/mod.rs index 23bab244a..61aa0ca9f 100644 --- a/crates/matrix-sdk-ui/src/timeline/tests/mod.rs +++ b/crates/matrix-sdk-ui/src/timeline/tests/mod.rs @@ -27,7 +27,7 @@ use futures_core::Stream; use indexmap::IndexMap; use matrix_sdk::{ config::RequestConfig, - deserialized_responses::{SyncTimelineEvent, TimelineEvent}, + deserialized_responses::SyncTimelineEvent, event_cache::paginator::{PaginableRoom, PaginatorError}, room::{EventWithContextResponse, Messages, MessagesOptions}, send_queue::RoomSendQueueUpdate, @@ -196,7 +196,7 @@ impl TestTimeline { } async fn handle_back_paginated_event(&self, event: Raw) { - let timeline_event = TimelineEvent::new(event.cast()); + let timeline_event = SyncTimelineEvent::new(event.cast()); self.controller .add_events_at( [timeline_event].into_iter(), diff --git a/crates/matrix-sdk-ui/src/timeline/traits.rs b/crates/matrix-sdk-ui/src/timeline/traits.rs index 55cae54db..912b1fd0b 100644 --- a/crates/matrix-sdk-ui/src/timeline/traits.rs +++ b/crates/matrix-sdk-ui/src/timeline/traits.rs @@ -19,7 +19,7 @@ use indexmap::IndexMap; #[cfg(test)] use matrix_sdk::crypto::{DecryptionSettings, RoomEventDecryptionResult, TrustRequirement}; use matrix_sdk::{ - crypto::types::events::CryptoContextInfo, deserialized_responses::TimelineEvent, + crypto::types::events::CryptoContextInfo, deserialized_responses::SyncTimelineEvent, event_cache::paginator::PaginableRoom, AsyncTraitDeps, Result, Room, SendOutsideWasm, }; use matrix_sdk_base::{latest_event::LatestEvent, RoomInfo}; @@ -281,18 +281,24 @@ pub(super) trait Decryptor: AsyncTraitDeps + Clone + 'static { fn decrypt_event_impl( &self, raw: &Raw, - ) -> impl Future> + SendOutsideWasm; + ) -> impl Future> + SendOutsideWasm; } impl Decryptor for Room { - async fn decrypt_event_impl(&self, raw: &Raw) -> Result { + async fn decrypt_event_impl( + &self, + raw: &Raw, + ) -> Result { self.decrypt_event(raw.cast_ref()).await } } #[cfg(test)] impl Decryptor for (matrix_sdk_base::crypto::OlmMachine, ruma::OwnedRoomId) { - async fn decrypt_event_impl(&self, raw: &Raw) -> Result { + async fn decrypt_event_impl( + &self, + raw: &Raw, + ) -> Result { let (olm_machine, room_id) = self; let decryption_settings = DecryptionSettings { sender_device_trust_requirement: TrustRequirement::Untrusted }; @@ -302,7 +308,7 @@ impl Decryptor for (matrix_sdk_base::crypto::OlmMachine, ruma::OwnedRoomId) { { RoomEventDecryptionResult::Decrypted(decrypted) => Ok(decrypted.into()), RoomEventDecryptionResult::UnableToDecrypt(utd_info) => { - Ok(TimelineEvent::new_utd_event(raw.clone(), utd_info)) + Ok(SyncTimelineEvent::new_utd_event(raw.clone(), utd_info)) } } } diff --git a/crates/matrix-sdk-ui/tests/integration/main.rs b/crates/matrix-sdk-ui/tests/integration/main.rs index 9eb3b40e1..e59f31128 100644 --- a/crates/matrix-sdk-ui/tests/integration/main.rs +++ b/crates/matrix-sdk-ui/tests/integration/main.rs @@ -13,7 +13,7 @@ // limitations under the License. use itertools::Itertools as _; -use matrix_sdk::deserialized_responses::TimelineEvent; +use matrix_sdk::deserialized_responses::SyncTimelineEvent; use ruma::{events::AnyStateEvent, serde::Raw, EventId, RoomId}; use serde::Serialize; use serde_json::json; @@ -55,15 +55,16 @@ async fn mock_sync(server: &MockServer, response_body: impl Serialize, since: Op /// /// Note: pass `events_before` in the normal order, I'll revert the order for /// you. +// TODO: replace with MatrixMockServer #[allow(clippy::too_many_arguments)] // clippy you've got such a fixed mindset async fn mock_context( server: &MockServer, room_id: &RoomId, event_id: &EventId, prev_batch_token: Option, - events_before: Vec, - event: TimelineEvent, - events_after: Vec, + events_before: Vec, + event: SyncTimelineEvent, + events_after: Vec, next_batch_token: Option, state: Vec>, ) { @@ -86,11 +87,12 @@ async fn mock_context( /// /// Note: pass `chunk` in the correct order: topological for forward pagination, /// reverse topological for backwards pagination. +// TODO: replace with MatrixMockServer async fn mock_messages( server: &MockServer, start: String, end: Option, - chunk: Vec, + chunk: Vec, state: Vec>, ) { Mock::given(method("GET")) diff --git a/crates/matrix-sdk-ui/tests/integration/timeline/focus_event.rs b/crates/matrix-sdk-ui/tests/integration/timeline/focus_event.rs index f4162d429..ee7a3b3e6 100644 --- a/crates/matrix-sdk-ui/tests/integration/timeline/focus_event.rs +++ b/crates/matrix-sdk-ui/tests/integration/timeline/focus_event.rs @@ -54,13 +54,13 @@ async fn test_new_focused() { target_event, Some("prev1".to_owned()), vec![ - f.text_msg("i tried so hard").sender(*ALICE).into_timeline(), - f.text_msg("and got so far").sender(*ALICE).into_timeline(), + f.text_msg("i tried so hard").sender(*ALICE).into_sync(), + f.text_msg("and got so far").sender(*ALICE).into_sync(), ], - f.text_msg("in the end").event_id(target_event).sender(*BOB).into_timeline(), + f.text_msg("in the end").event_id(target_event).sender(*BOB).into_sync(), vec![ - f.text_msg("it doesn't even").sender(*ALICE).into_timeline(), - f.text_msg("matter").sender(*ALICE).into_timeline(), + f.text_msg("it doesn't even").sender(*ALICE).into_sync(), + f.text_msg("matter").sender(*ALICE).into_sync(), ], Some("next1".to_owned()), vec![], @@ -114,8 +114,8 @@ async fn test_new_focused() { None, vec![ // reversed manually here - f.text_msg("And even though I tried, it all fell apart").sender(*BOB).into_timeline(), - f.text_msg("I kept everything inside").sender(*BOB).into_timeline(), + f.text_msg("And even though I tried, it all fell apart").sender(*BOB).into_sync(), + f.text_msg("I kept everything inside").sender(*BOB).into_sync(), ], vec![], ) @@ -154,8 +154,8 @@ async fn test_new_focused() { "next1".to_owned(), Some("next2".to_owned()), vec![ - f.text_msg("I had to fall, to lose it all").sender(*BOB).into_timeline(), - f.text_msg("But in the end, it doesn't event matter").sender(*BOB).into_timeline(), + f.text_msg("I had to fall, to lose it all").sender(*BOB).into_sync(), + f.text_msg("But in the end, it doesn't event matter").sender(*BOB).into_sync(), ], vec![], ) @@ -208,7 +208,7 @@ async fn test_focused_timeline_reacts() { target_event, None, vec![], - f.text_msg("yolo").event_id(target_event).sender(*BOB).into_timeline(), + f.text_msg("yolo").event_id(target_event).sender(*BOB).into_sync(), vec![], None, vec![], @@ -293,7 +293,7 @@ async fn test_focused_timeline_local_echoes() { target_event, None, vec![], - f.text_msg("yolo").event_id(target_event).sender(*BOB).into_timeline(), + f.text_msg("yolo").event_id(target_event).sender(*BOB).into_sync(), vec![], None, vec![], @@ -372,7 +372,7 @@ async fn test_focused_timeline_doesnt_show_local_echoes() { target_event, None, vec![], - f.text_msg("yolo").event_id(target_event).sender(*BOB).into_timeline(), + f.text_msg("yolo").event_id(target_event).sender(*BOB).into_sync(), vec![], None, vec![], diff --git a/crates/matrix-sdk-ui/tests/integration/timeline/pinned_event.rs b/crates/matrix-sdk-ui/tests/integration/timeline/pinned_event.rs index 943d6d5f5..d7c57621e 100644 --- a/crates/matrix-sdk-ui/tests/integration/timeline/pinned_event.rs +++ b/crates/matrix-sdk-ui/tests/integration/timeline/pinned_event.rs @@ -13,7 +13,7 @@ use matrix_sdk::{ }, Client, Room, }; -use matrix_sdk_base::deserialized_responses::TimelineEvent; +use matrix_sdk_base::deserialized_responses::SyncTimelineEvent; use matrix_sdk_test::{ async_test, event_factory::EventFactory, JoinedRoomBuilder, StateTestEvent, SyncResponseBuilder, BOB, @@ -880,7 +880,7 @@ async fn mock_events_endpoint( .mock_room_event() .room(room_id.to_owned()) .match_event_id() - .ok(TimelineEvent::new(event.cast())) + .ok(SyncTimelineEvent::new(event.cast())) .mount() .await; } diff --git a/crates/matrix-sdk/src/event_cache/mod.rs b/crates/matrix-sdk/src/event_cache/mod.rs index 0ea2fa05b..ddc29a85b 100644 --- a/crates/matrix-sdk/src/event_cache/mod.rs +++ b/crates/matrix-sdk/src/event_cache/mod.rs @@ -36,7 +36,7 @@ use std::{ use eyeball::Subscriber; use eyeball_im::VectorDiff; use matrix_sdk_base::{ - deserialized_responses::{AmbiguityChange, SyncTimelineEvent, TimelineEvent}, + deserialized_responses::{AmbiguityChange, SyncTimelineEvent}, event_cache::store::{EventCacheStoreError, EventCacheStoreLock}, store_locks::LockStoreError, sync::RoomUpdates, @@ -662,7 +662,7 @@ pub struct BackPaginationOutcome { /// technically, the last one in the topological ordering). /// /// Note: they're not deduplicated (TODO: smart reconciliation). - pub events: Vec, + pub events: Vec, } /// An update related to events happened in a room. diff --git a/crates/matrix-sdk/src/event_cache/paginator.rs b/crates/matrix-sdk/src/event_cache/paginator.rs index 4df79363e..e3bd46301 100644 --- a/crates/matrix-sdk/src/event_cache/paginator.rs +++ b/crates/matrix-sdk/src/event_cache/paginator.rs @@ -20,7 +20,9 @@ use std::{future::Future, sync::Mutex}; use eyeball::{SharedObservable, Subscriber}; -use matrix_sdk_base::{deserialized_responses::TimelineEvent, SendOutsideWasm, SyncOutsideWasm}; +use matrix_sdk_base::{ + deserialized_responses::SyncTimelineEvent, SendOutsideWasm, SyncOutsideWasm, +}; use ruma::{api::Direction, EventId, OwnedEventId, UInt}; use super::pagination::PaginationToken; @@ -116,7 +118,7 @@ pub struct PaginationResult { /// /// If this is the result of a forward pagination, then the events are in /// topological order. - pub events: Vec, + pub events: Vec, /// Did we hit *an* end of the timeline? /// @@ -132,7 +134,7 @@ pub struct PaginationResult { #[derive(Debug)] pub struct StartFromResult { /// All the events returned during this pagination, in topological ordering. - pub events: Vec, + pub events: Vec, /// Whether the /context query returned a previous batch token. pub has_prev: bool, @@ -536,7 +538,7 @@ mod tests { use assert_matches2::assert_let; use futures_core::Future; use futures_util::FutureExt as _; - use matrix_sdk_base::deserialized_responses::TimelineEvent; + use matrix_sdk_base::deserialized_responses::SyncTimelineEvent; use matrix_sdk_test::{async_test, event_factory::EventFactory}; use once_cell::sync::Lazy; use ruma::{api::Direction, event_id, room_id, uint, user_id, EventId, RoomId, UInt, UserId}; @@ -559,8 +561,8 @@ mod tests { wait_for_ready: bool, target_event_text: Arc>, - next_events: Arc>>, - prev_events: Arc>>, + next_events: Arc>>, + prev_events: Arc>>, prev_batch_token: Arc>>, next_batch_token: Arc>>, @@ -609,7 +611,7 @@ mod tests { .event_factory .text_msg(self.target_event_text.lock().await.clone()) .event_id(event_id) - .into_timeline(); + .into_sync(); // Properly simulate `num_events`: take either the closest num_events events // before, or use all of the before events and then consume after events. @@ -707,17 +709,10 @@ mod tests { *room.target_event_text.lock().await = "fetch_from".to_owned(); *room.prev_events.lock().await = (0..10) .rev() - .map(|i| { - TimelineEvent::new( - event_factory.text_msg(format!("before-{i}")).into_raw_timeline(), - ) - }) - .collect(); - *room.next_events.lock().await = (0..10) - .map(|i| { - TimelineEvent::new(event_factory.text_msg(format!("after-{i}")).into_raw_timeline()) - }) + .map(|i| event_factory.text_msg(format!("before-{i}")).into_sync()) .collect(); + *room.next_events.lock().await = + (0..10).map(|i| event_factory.text_msg(format!("after-{i}")).into_sync()).collect(); // When I call `Paginator::start_from`, it works, let paginator = Arc::new(Paginator::new(room.clone())); @@ -753,12 +748,8 @@ mod tests { let event_factory = &room.event_factory; *room.target_event_text.lock().await = "fetch_from".to_owned(); - *room.prev_events.lock().await = (0..100) - .rev() - .map(|i| { - TimelineEvent::new(event_factory.text_msg(format!("ev{i}")).into_raw_timeline()) - }) - .collect(); + *room.prev_events.lock().await = + (0..100).rev().map(|i| event_factory.text_msg(format!("ev{i}")).into_sync()).collect(); // When I call `Paginator::start_from`, it works, let paginator = Arc::new(Paginator::new(room.clone())); @@ -811,7 +802,7 @@ mod tests { assert!(paginator.hit_timeline_end()); // Preparing data for the next back-pagination. - *room.prev_events.lock().await = vec![event_factory.text_msg("previous").into_timeline()]; + *room.prev_events.lock().await = vec![event_factory.text_msg("previous").into_sync()]; *room.prev_batch_token.lock().await = Some("prev2".to_owned()); // When I backpaginate, I get the events I expect. @@ -824,7 +815,7 @@ mod tests { // And I can backpaginate again, because there's a prev batch token // still. - *room.prev_events.lock().await = vec![event_factory.text_msg("oldest").into_timeline()]; + *room.prev_events.lock().await = vec![event_factory.text_msg("oldest").into_sync()]; *room.prev_batch_token.lock().await = None; let prev = paginator @@ -875,9 +866,7 @@ mod tests { // Preparing data for the next back-pagination. *room.prev_events.lock().await = (0..100) .rev() - .map(|i| { - TimelineEvent::new(event_factory.text_msg(format!("prev{i}")).into_raw_timeline()) - }) + .map(|i| event_factory.text_msg(format!("prev{i}")).into_sync()) .collect(); *room.prev_batch_token.lock().await = None; @@ -927,7 +916,7 @@ mod tests { assert!(!paginator.hit_timeline_end()); // Preparing data for the next forward-pagination. - *room.next_events.lock().await = vec![event_factory.text_msg("next").into_timeline()]; + *room.next_events.lock().await = vec![event_factory.text_msg("next").into_sync()]; *room.next_batch_token.lock().await = Some("next2".to_owned()); // When I forward-paginate, I get the events I expect. @@ -940,7 +929,7 @@ mod tests { // And I can forward-paginate again, because there's a prev batch token // still. - *room.next_events.lock().await = vec![event_factory.text_msg("latest").into_timeline()]; + *room.next_events.lock().await = vec![event_factory.text_msg("latest").into_sync()]; *room.next_batch_token.lock().await = None; let next = paginator diff --git a/crates/matrix-sdk/src/room/messages.rs b/crates/matrix-sdk/src/room/messages.rs index 7c4709feb..37d2e6b38 100644 --- a/crates/matrix-sdk/src/room/messages.rs +++ b/crates/matrix-sdk/src/room/messages.rs @@ -14,7 +14,7 @@ use std::fmt; -use matrix_sdk_common::{debug::DebugStructExt as _, deserialized_responses::TimelineEvent}; +use matrix_sdk_common::{debug::DebugStructExt as _, deserialized_responses::SyncTimelineEvent}; use ruma::{ api::{ client::{filter::RoomEventFilter, message::get_message_events}, @@ -134,7 +134,7 @@ pub struct Messages { pub end: Option, /// A list of room events. - pub chunk: Vec, + pub chunk: Vec, /// A list of state events relevant to showing the `chunk`. pub state: Vec>, @@ -148,19 +148,19 @@ pub struct Messages { #[derive(Debug, Default)] pub struct EventWithContextResponse { /// The event targeted by the /context query. - pub event: Option, + pub event: Option, /// Events before the target event, if a non-zero context size was /// requested. /// /// Like the corresponding Ruma response, these are in reverse chronological /// order. - pub events_before: Vec, + pub events_before: Vec, /// Events after the target event, if a non-zero context size was requested. /// /// Like the corresponding Ruma response, these are in chronological order. - pub events_after: Vec, + pub events_after: Vec, /// Token to paginate backwards, aka "start" token. pub prev_batch_token: Option, diff --git a/crates/matrix-sdk/src/room/mod.rs b/crates/matrix-sdk/src/room/mod.rs index fbe5ab16b..aee4f47fd 100644 --- a/crates/matrix-sdk/src/room/mod.rs +++ b/crates/matrix-sdk/src/room/mod.rs @@ -38,7 +38,7 @@ use matrix_sdk_base::crypto::{DecryptionSettings, RoomEventDecryptionResult}; use matrix_sdk_base::crypto::{IdentityStatusChange, RoomIdentityProvider, UserIdentity}; use matrix_sdk_base::{ deserialized_responses::{ - RawAnySyncOrStrippedState, RawSyncOrStrippedState, SyncOrStrippedState, TimelineEvent, + RawAnySyncOrStrippedState, RawSyncOrStrippedState, SyncOrStrippedState, }, media::MediaThumbnailSettings, store::StateStoreExt, @@ -341,10 +341,10 @@ impl Room { if let Ok(event) = self.decrypt_event(event.cast_ref()).await { event } else { - TimelineEvent::new(event) + SyncTimelineEvent::new(event.cast()) } } else { - TimelineEvent::new(event) + SyncTimelineEvent::new(event.cast()) }; response.chunk.push(decrypted_event); } @@ -353,8 +353,7 @@ impl Room { let push_rules = self.client().account().push_rules().await?; for event in &mut response.chunk { - event.push_actions = - Some(push_rules.get_actions(event.raw(), &push_context).to_owned()); + event.push_actions = push_rules.get_actions(event.raw(), &push_context).to_owned(); } } @@ -447,7 +446,7 @@ impl Room { /// /// Doesn't return an error `Result` when decryption failed; only logs from /// the crypto crate will indicate so. - async fn try_decrypt_event(&self, event: Raw) -> Result { + async fn try_decrypt_event(&self, event: Raw) -> Result { #[cfg(feature = "e2e-encryption")] if let Ok(AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomEncrypted( SyncMessageLikeEvent::Original(_), @@ -458,8 +457,8 @@ impl Room { } } - let mut event = TimelineEvent::new(event); - event.push_actions = self.event_push_actions(event.raw()).await?; + let mut event = SyncTimelineEvent::new(event.cast()); + event.push_actions = self.event_push_actions(event.raw()).await?.unwrap_or_default(); Ok(event) } @@ -472,7 +471,7 @@ impl Room { &self, event_id: &EventId, request_config: Option, - ) -> Result { + ) -> Result { let request = get_room_event::v3::Request::new(self.room_id().to_owned(), event_id.to_owned()); @@ -1278,14 +1277,14 @@ impl Room { pub async fn decrypt_event( &self, event: &Raw, - ) -> Result { + ) -> Result { let machine = self.client.olm_machine().await; let machine = machine.as_ref().ok_or(Error::NoOlmMachine)?; let decryption_settings = DecryptionSettings { sender_device_trust_requirement: self.client.base_client().decryption_trust_requirement, }; - let mut event: TimelineEvent = match machine + let mut event: SyncTimelineEvent = match machine .try_decrypt_room_event(event.cast_ref(), self.inner.room_id(), &decryption_settings) .await? { @@ -1295,11 +1294,11 @@ impl Room { .encryption() .backups() .maybe_download_room_key(self.room_id().to_owned(), event.clone()); - TimelineEvent::new_utd_event(event.clone().cast(), utd_info) + SyncTimelineEvent::new_utd_event(event.clone().cast(), utd_info) } }; - event.push_actions = self.event_push_actions(event.raw()).await?; + event.push_actions = self.event_push_actions(event.raw()).await?.unwrap_or_default(); Ok(event) } diff --git a/crates/matrix-sdk/src/sliding_sync/room.rs b/crates/matrix-sdk/src/sliding_sync/room.rs index b78cdc147..92e83f581 100644 --- a/crates/matrix-sdk/src/sliding_sync/room.rs +++ b/crates/matrix-sdk/src/sliding_sync/room.rs @@ -214,7 +214,6 @@ impl From<&SlidingSyncRoom> for FrozenSlidingSyncRoom { #[cfg(test)] mod tests { use imbl::vector; - use matrix_sdk_base::deserialized_responses::TimelineEvent; use matrix_sdk_common::deserialized_responses::SyncTimelineEvent; use matrix_sdk_test::async_test; use ruma::{events::room::message::RoomMessageEventContent, room_id, serde::Raw, RoomId}; @@ -315,7 +314,7 @@ mod tests { macro_rules! timeline_event { (from $sender:literal with id $event_id:literal at $ts:literal: $message:literal) => { - TimelineEvent::new( + SyncTimelineEvent::new( Raw::new(&json!({ "content": RoomMessageEventContent::text_plain($message), "type": "m.room.message", @@ -606,7 +605,7 @@ mod tests { let frozen_room = FrozenSlidingSyncRoom { room_id: room_id!("!29fhd83h92h0:example.com").to_owned(), prev_batch: Some("foo".to_owned()), - timeline_queue: vector![TimelineEvent::new( + timeline_queue: vector![SyncTimelineEvent::new( Raw::new(&json!({ "content": RoomMessageEventContent::text_plain("let it gooo!"), "type": "m.room.message", @@ -658,7 +657,7 @@ mod tests { let max = NUMBER_OF_TIMELINE_EVENTS_TO_KEEP_FOR_THE_CACHE - 1; let timeline_events = (0..=max) .map(|nth| { - TimelineEvent::new( + SyncTimelineEvent::new( Raw::new(&json!({ "content": RoomMessageEventContent::text_plain(format!("message {nth}")), "type": "m.room.message", @@ -695,7 +694,7 @@ mod tests { let max = NUMBER_OF_TIMELINE_EVENTS_TO_KEEP_FOR_THE_CACHE + 2; let timeline_events = (0..=max) .map(|nth| { - TimelineEvent::new( + SyncTimelineEvent::new( Raw::new(&json!({ "content": RoomMessageEventContent::text_plain(format!("message {nth}")), "type": "m.room.message", diff --git a/crates/matrix-sdk/src/test_utils/mocks.rs b/crates/matrix-sdk/src/test_utils/mocks.rs index 34d232b54..44dda8cf1 100644 --- a/crates/matrix-sdk/src/test_utils/mocks.rs +++ b/crates/matrix-sdk/src/test_utils/mocks.rs @@ -22,7 +22,7 @@ use std::{ sync::{Arc, Mutex}, }; -use matrix_sdk_base::deserialized_responses::TimelineEvent; +use matrix_sdk_base::deserialized_responses::SyncTimelineEvent; use matrix_sdk_test::{ test_json, InvitedRoomBuilder, JoinedRoomBuilder, KnockedRoomBuilder, LeftRoomBuilder, SyncResponseBuilder, @@ -1856,7 +1856,7 @@ impl<'a> MockEndpoint<'a, RoomEventEndpoint> { /// Returns a redact endpoint that emulates success, i.e. the redaction /// event has been sent with the given event id. - pub fn ok(self, event: TimelineEvent) -> MatrixMock<'a> { + pub fn ok(self, event: SyncTimelineEvent) -> MatrixMock<'a> { let event_path = if self.endpoint.match_event_id { let event_id = event.kind.event_id().expect("an event id is required"); // The event id should begin with `$`, which would be taken as the end of the diff --git a/crates/matrix-sdk/tests/integration/room/common.rs b/crates/matrix-sdk/tests/integration/room/common.rs index a61a4bc76..fbe03af14 100644 --- a/crates/matrix-sdk/tests/integration/room/common.rs +++ b/crates/matrix-sdk/tests/integration/room/common.rs @@ -667,7 +667,7 @@ async fn test_event() { ); assert_eq!(event.event_id(), event_id); - let push_actions = timeline_event.push_actions.unwrap(); + let push_actions = timeline_event.push_actions; assert!(push_actions.iter().any(|a| a.is_highlight())); assert!(push_actions.iter().any(|a| a.should_notify())); diff --git a/crates/matrix-sdk/tests/integration/room/joined.rs b/crates/matrix-sdk/tests/integration/room/joined.rs index 6aee69b3d..b2db9fd14 100644 --- a/crates/matrix-sdk/tests/integration/room/joined.rs +++ b/crates/matrix-sdk/tests/integration/room/joined.rs @@ -797,7 +797,7 @@ async fn test_make_reply_event_doesnt_require_event_cache() { let event_id = event_id!("$1"); let f = EventFactory::new(); mock.mock_room_event() - .ok(f.text_msg("hi").event_id(event_id).sender(&user_id).room(room_id).into_timeline()) + .ok(f.text_msg("hi").event_id(event_id).sender(&user_id).room(room_id).into_sync()) .expect(1) .named("/event") .mount() diff --git a/crates/matrix-sdk/tests/integration/send_queue.rs b/crates/matrix-sdk/tests/integration/send_queue.rs index a35fcad9d..ceb64e419 100644 --- a/crates/matrix-sdk/tests/integration/send_queue.rs +++ b/crates/matrix-sdk/tests/integration/send_queue.rs @@ -903,7 +903,7 @@ async fn test_edit() { .text_msg("msg1") .sender(client.user_id().unwrap()) .room(room_id) - .into_timeline()) + .into_sync()) .expect(1) .named("room_event") .mount() @@ -1010,7 +1010,7 @@ async fn test_edit_with_poll_start() { .poll_start("poll_start", "question", vec!["Answer A"]) .sender(client.user_id().unwrap()) .room(room_id) - .into_timeline()) + .into_sync()) .expect(1) .named("get_event") .mount() @@ -2944,7 +2944,7 @@ async fn test_update_caption_while_sending_media_event() { .image("surprise.jpeg.exe".to_owned(), owned_mxc_uri!("mxc://sdk.rs/media")) .sender(client.user_id().unwrap()) .room(room_id) - .into_timeline()) + .into_sync()) .expect(1) .named("room_event") .mount() diff --git a/testing/matrix-sdk-test/src/event_factory.rs b/testing/matrix-sdk-test/src/event_factory.rs index 48ee5afde..444e315fe 100644 --- a/testing/matrix-sdk-test/src/event_factory.rs +++ b/testing/matrix-sdk-test/src/event_factory.rs @@ -21,7 +21,7 @@ use std::{ use as_variant::as_variant; use matrix_sdk_common::deserialized_responses::{ - SyncTimelineEvent, TimelineEvent, UnableToDecryptInfo, UnableToDecryptReason, + SyncTimelineEvent, UnableToDecryptInfo, UnableToDecryptReason, }; use ruma::{ events::{ @@ -250,10 +250,6 @@ where Raw::new(&self.construct_json(true)).unwrap().cast() } - pub fn into_timeline(self) -> TimelineEvent { - TimelineEvent::new(self.into_raw_timeline()) - } - pub fn into_raw_sync(self) -> Raw { Raw::new(&self.construct_json(false)).unwrap().cast() }