From cd630bd97bdd987d86b9a7012bcf6f558396144c Mon Sep 17 00:00:00 2001 From: Benjamin Bouvier Date: Tue, 21 Jan 2025 15:28:32 +0100 Subject: [PATCH 1/6] 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 cf27dae0d9c..9156eb576d5 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 5af760e713f..712f543c799 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 7c6b3e5272f..1d7a8b81405 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 09ee071f923..06c715eaf7d 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 23bab244a79..61aa0ca9f82 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 55cae54db5f..912b1fd0bb9 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 9eb3b40e14c..e59f31128eb 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 f4162d42940..ee7a3b3e6dd 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 943d6d5f544..d7c57621e95 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 0ea2fa05b55..ddc29a85b12 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 4df79363e2a..e3bd4630184 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 7c4709feb50..37d2e6b38d4 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 d1317567719..c86b544d39c 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 b78cdc147f0..92e83f58181 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 34d232b544e..44dda8cf1f9 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 a61a4bc76fa..fbe03af1443 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 6aee69b3d46..b2db9fd1484 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 a35fcad9de2..ceb64e419d3 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 48ee5afde8e..444e315fe68 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() } From ad3b922bd261aca0aa182e114337685f8b6b179b Mon Sep 17 00:00:00 2001 From: Benjamin Bouvier Date: Tue, 21 Jan 2025 15:36:57 +0100 Subject: [PATCH 2/6] refactor: have `SyncTimelineEvent::push_actions` be optional --- crates/matrix-sdk-base/src/client.rs | 2 +- .../src/event_cache/store/integration_tests.rs | 4 ++-- crates/matrix-sdk-base/src/read_receipts.rs | 6 +++++- .../src/deserialized_responses.rs | 18 ++++++++++-------- .../matrix-sdk-ui/src/notification_client.rs | 17 ++++++++--------- .../src/timeline/controller/state.rs | 13 ++++++------- crates/matrix-sdk/src/event_handler/mod.rs | 2 +- crates/matrix-sdk/src/room/mod.rs | 7 ++++--- .../tests/integration/room/common.rs | 2 +- 9 files changed, 38 insertions(+), 33 deletions(-) diff --git a/crates/matrix-sdk-base/src/client.rs b/crates/matrix-sdk-base/src/client.rs index 3bc63034091..92b4c7b2d44 100644 --- a/crates/matrix-sdk-base/src/client.rs +++ b/crates/matrix-sdk-base/src/client.rs @@ -535,7 +535,7 @@ impl BaseClient { }, ); } - event.push_actions = actions.to_owned(); + event.push_actions = Some(actions.to_owned()); } } Err(e) => { diff --git a/crates/matrix-sdk-base/src/event_cache/store/integration_tests.rs b/crates/matrix-sdk-base/src/event_cache/store/integration_tests.rs index 83ab9b3eda1..7a5bae43ca0 100644 --- a/crates/matrix-sdk-base/src/event_cache/store/integration_tests.rs +++ b/crates/matrix-sdk-base/src/event_cache/store/integration_tests.rs @@ -66,7 +66,7 @@ pub fn make_test_event(room_id: &RoomId, content: &str) -> SyncTimelineEvent { encryption_info, unsigned_encryption_info: None, }), - push_actions: vec![Action::Notify], + push_actions: Some(vec![Action::Notify]), } } @@ -77,7 +77,7 @@ pub fn make_test_event(room_id: &RoomId, content: &str) -> SyncTimelineEvent { #[track_caller] pub fn check_test_event(event: &SyncTimelineEvent, text: &str) { // Check push actions. - let actions = &event.push_actions; + let actions = event.push_actions.as_ref().unwrap(); assert_eq!(actions.len(), 1); assert_matches!(&actions[0], Action::Notify); diff --git a/crates/matrix-sdk-base/src/read_receipts.rs b/crates/matrix-sdk-base/src/read_receipts.rs index 84046a9ac74..bc4f54364e4 100644 --- a/crates/matrix-sdk-base/src/read_receipts.rs +++ b/crates/matrix-sdk-base/src/read_receipts.rs @@ -210,7 +210,11 @@ impl RoomReadReceipts { let mut has_notify = false; let mut has_mention = false; - for action in &event.push_actions { + let Some(actions) = event.push_actions.as_ref() else { + return; + }; + + for action in actions.iter() { if !has_notify && action.should_notify() { self.num_notifications += 1; has_notify = true; diff --git a/crates/matrix-sdk-common/src/deserialized_responses.rs b/crates/matrix-sdk-common/src/deserialized_responses.rs index 9156eb576d5..72b5ec0911f 100644 --- a/crates/matrix-sdk-common/src/deserialized_responses.rs +++ b/crates/matrix-sdk-common/src/deserialized_responses.rs @@ -330,8 +330,10 @@ pub struct SyncTimelineEvent { pub kind: TimelineEventKind, /// The push actions associated with this event. - #[serde(skip_serializing_if = "Vec::is_empty")] - pub push_actions: Vec, + /// + /// If it's set to `None`, then it means we couldn't compute those actions. + #[serde(skip_serializing_if = "Option::is_none")] + pub push_actions: Option>, } // See https://github.com/matrix-org/matrix-rust-sdk/pull/3749#issuecomment-2312939823. @@ -357,7 +359,7 @@ impl SyncTimelineEvent { /// 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 { kind: TimelineEventKind::PlainText { event }, push_actions: vec![] } + Self { kind: TimelineEventKind::PlainText { event }, push_actions: None } } /// Create a new `SyncTimelineEvent` from the given raw event and push @@ -369,13 +371,13 @@ impl SyncTimelineEvent { event: Raw, push_actions: Vec, ) -> Self { - Self { kind: TimelineEventKind::PlainText { event }, push_actions } + Self { kind: TimelineEventKind::PlainText { event }, push_actions: Some(push_actions) } } /// Create a new `SyncTimelineEvent` 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: vec![] } + Self { kind: TimelineEventKind::UnableToDecrypt { event, utd_info }, push_actions: None } } /// Get the event id of this `SyncTimelineEvent` if the event has any valid @@ -418,7 +420,7 @@ impl SyncTimelineEvent { impl From for SyncTimelineEvent { fn from(decrypted: DecryptedRoomEvent) -> Self { - Self { kind: TimelineEventKind::Decrypted(decrypted), push_actions: Vec::new() } + Self { kind: TimelineEventKind::Decrypted(decrypted), push_actions: None } } } @@ -821,7 +823,7 @@ struct SyncTimelineEventDeserializationHelperV1 { impl From for SyncTimelineEvent { fn from(value: SyncTimelineEventDeserializationHelperV1) -> Self { let SyncTimelineEventDeserializationHelperV1 { kind, push_actions } = value; - SyncTimelineEvent { kind, push_actions } + SyncTimelineEvent { kind, push_actions: Some(push_actions) } } } @@ -873,7 +875,7 @@ impl From for SyncTimelineEvent { None => TimelineEventKind::PlainText { event }, }; - SyncTimelineEvent { kind, push_actions } + SyncTimelineEvent { kind, push_actions: Some(push_actions) } } } diff --git a/crates/matrix-sdk-ui/src/notification_client.rs b/crates/matrix-sdk-ui/src/notification_client.rs index 712f543c799..b896fa64f84 100644 --- a/crates/matrix-sdk-ui/src/notification_client.rs +++ b/crates/matrix-sdk-ui/src/notification_client.rs @@ -507,9 +507,9 @@ impl NotificationClient { if let Some(mut timeline_event) = self.retry_decryption(&room, timeline_event).await? { - let push_actions = std::mem::take(&mut timeline_event.push_actions); + let push_actions = timeline_event.push_actions.take(); raw_event = RawNotificationEvent::Timeline(timeline_event.into_raw()); - Some(push_actions) + push_actions } else { room.event_push_actions(timeline_event).await? } @@ -564,19 +564,18 @@ impl NotificationClient { timeline_event = decrypted_event; } - // TODO: nope - if !timeline_event.push_actions.is_empty() - && !timeline_event.push_actions.iter().any(|a| a.should_notify()) - { - return Ok(None); + if let Some(actions) = timeline_event.push_actions.as_ref() { + if !actions.iter().any(|a| a.should_notify()) { + return Ok(None); + } } - let push_actions = std::mem::take(&mut timeline_event.push_actions); + let push_actions = timeline_event.push_actions.take(); Ok(Some( NotificationItem::new( &room, RawNotificationEvent::Timeline(timeline_event.into_raw()), - Some(&push_actions), + push_actions.as_deref(), 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 1d7a8b81405..5b5d1e59d21 100644 --- a/crates/matrix-sdk-ui/src/timeline/controller/state.rs +++ b/crates/matrix-sdk-ui/src/timeline/controller/state.rs @@ -273,12 +273,9 @@ 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() - }) - .unwrap_or_default(); + event.push_actions = push_rules_context.as_ref().map(|(push_rules, push_context)| { + push_rules.get_actions(event.raw(), push_context).to_owned() + }); let handle_one_res = txn .handle_remote_event( @@ -760,7 +757,9 @@ impl TimelineStateTransaction<'_> { } else { Default::default() }, - is_highlighted: push_actions.iter().any(Action::is_highlight), + is_highlighted: push_actions + .as_ref() + .map_or(false, |actions| actions.iter().any(Action::is_highlight)), flow: Flow::Remote { event_id: event_id.clone(), raw_event: raw, diff --git a/crates/matrix-sdk/src/event_handler/mod.rs b/crates/matrix-sdk/src/event_handler/mod.rs index 5fff2db8baa..4f802210b0c 100644 --- a/crates/matrix-sdk/src/event_handler/mod.rs +++ b/crates/matrix-sdk/src/event_handler/mod.rs @@ -402,7 +402,7 @@ impl Client { let raw_event = item.raw().json(); let encryption_info = item.encryption_info(); - let push_actions = &item.push_actions; + let push_actions = item.push_actions.as_deref().unwrap_or(&[]); // Event handlers for possibly-redacted timeline events self.call_event_handlers( diff --git a/crates/matrix-sdk/src/room/mod.rs b/crates/matrix-sdk/src/room/mod.rs index c86b544d39c..650a8044458 100644 --- a/crates/matrix-sdk/src/room/mod.rs +++ b/crates/matrix-sdk/src/room/mod.rs @@ -353,7 +353,8 @@ impl Room { let push_rules = self.client().account().push_rules().await?; for event in &mut response.chunk { - event.push_actions = push_rules.get_actions(event.raw(), &push_context).to_owned(); + event.push_actions = + Some(push_rules.get_actions(event.raw(), &push_context).to_owned()); } } @@ -458,7 +459,7 @@ impl Room { } let mut event = SyncTimelineEvent::new(event.cast()); - event.push_actions = self.event_push_actions(event.raw()).await?.unwrap_or_default(); + event.push_actions = self.event_push_actions(event.raw()).await?; Ok(event) } @@ -1298,7 +1299,7 @@ impl Room { } }; - event.push_actions = self.event_push_actions(event.raw()).await?.unwrap_or_default(); + event.push_actions = self.event_push_actions(event.raw()).await?; Ok(event) } diff --git a/crates/matrix-sdk/tests/integration/room/common.rs b/crates/matrix-sdk/tests/integration/room/common.rs index fbe03af1443..a61a4bc76fa 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; + let push_actions = timeline_event.push_actions.unwrap(); assert!(push_actions.iter().any(|a| a.is_highlight())); assert!(push_actions.iter().any(|a| a.should_notify())); From cc34341ab049c13f3bad937f03efa56dfec40f5f Mon Sep 17 00:00:00 2001 From: Benjamin Bouvier Date: Tue, 21 Jan 2025 15:44:46 +0100 Subject: [PATCH 3/6] refactor: rename `SyncTimelineEvent` to `TimelineEvent` --- crates/matrix-sdk-base/src/client.rs | 14 ++-- crates/matrix-sdk-base/src/event_cache/mod.rs | 4 +- .../event_cache/store/integration_tests.rs | 8 +-- crates/matrix-sdk-base/src/latest_event.rs | 22 +++--- crates/matrix-sdk-base/src/read_receipts.rs | 34 ++++----- crates/matrix-sdk-base/src/rooms/normal.rs | 6 +- .../matrix-sdk-base/src/sliding_sync/mod.rs | 22 +++--- .../src/store/migration_helpers.rs | 4 +- crates/matrix-sdk-base/src/sync.rs | 4 +- .../src/deserialized_responses.rs | 69 +++++++++---------- .../event_cache_store/003_events.sql | 2 +- .../matrix-sdk-ui/src/notification_client.rs | 4 +- .../src/timeline/controller/mod.rs | 10 +-- .../src/timeline/controller/state.rs | 18 ++--- .../src/timeline/event_handler.rs | 2 +- .../timeline/event_item/content/message.rs | 6 +- .../src/timeline/event_item/mod.rs | 15 ++-- .../src/timeline/pinned_events_loader.rs | 14 ++-- .../matrix-sdk-ui/src/timeline/tests/basic.rs | 4 +- .../matrix-sdk-ui/src/timeline/tests/edit.rs | 6 +- .../src/timeline/tests/encryption.rs | 6 +- .../src/timeline/tests/event_filter.rs | 6 +- .../src/timeline/tests/invalid.rs | 8 +-- .../matrix-sdk-ui/src/timeline/tests/mod.rs | 8 +-- .../src/timeline/tests/reactions.rs | 4 +- .../src/timeline/tests/shields.rs | 4 +- crates/matrix-sdk-ui/src/timeline/traits.rs | 16 ++--- .../matrix-sdk-ui/tests/integration/main.rs | 10 +-- .../integration/timeline/pinned_event.rs | 4 +- .../src/event_cache/deduplicator.rs | 4 +- crates/matrix-sdk/src/event_cache/mod.rs | 18 ++--- .../matrix-sdk/src/event_cache/pagination.rs | 4 +- .../matrix-sdk/src/event_cache/paginator.rs | 14 ++-- crates/matrix-sdk/src/event_cache/room/mod.rs | 34 +++++---- crates/matrix-sdk/src/event_handler/mod.rs | 4 +- crates/matrix-sdk/src/room/edit.rs | 14 ++-- crates/matrix-sdk/src/room/messages.rs | 10 +-- crates/matrix-sdk/src/room/mod.rs | 20 +++--- crates/matrix-sdk/src/sliding_sync/client.rs | 2 +- crates/matrix-sdk/src/sliding_sync/mod.rs | 10 +-- crates/matrix-sdk/src/sliding_sync/room.rs | 24 +++---- crates/matrix-sdk/src/test_utils/mocks.rs | 4 +- crates/matrix-sdk/src/test_utils/mod.rs | 6 +- .../tests/integration/event_cache.rs | 4 +- testing/matrix-sdk-test/src/event_factory.rs | 14 ++-- 45 files changed, 256 insertions(+), 264 deletions(-) diff --git a/crates/matrix-sdk-base/src/client.rs b/crates/matrix-sdk-base/src/client.rs index 92b4c7b2d44..4a910a3ae2c 100644 --- a/crates/matrix-sdk-base/src/client.rs +++ b/crates/matrix-sdk-base/src/client.rs @@ -68,7 +68,7 @@ use crate::latest_event::{is_suitable_for_latest_event, LatestEvent, PossibleLat #[cfg(feature = "e2e-encryption")] use crate::RoomMemberships; use crate::{ - deserialized_responses::{DisplayName, RawAnySyncOrStrippedTimelineEvent, SyncTimelineEvent}, + deserialized_responses::{DisplayName, RawAnySyncOrStrippedTimelineEvent, TimelineEvent}, error::{Error, Result}, event_cache::store::EventCacheStoreLock, response_processors::AccountDataProcessor, @@ -347,9 +347,9 @@ impl BaseClient { Ok(()) } - /// Attempt to decrypt the given raw event into a `SyncTimelineEvent`. + /// Attempt to decrypt the given raw event into a [`TimelineEvent`]. /// - /// In the case of a decryption error, returns a `SyncTimelineEvent` + /// In the case of a decryption error, returns a [`TimelineEvent`] /// representing the decryption error; in the case of problems with our /// application, returns `Err`. /// @@ -359,7 +359,7 @@ impl BaseClient { &self, event: &Raw, room_id: &RoomId, - ) -> Result> { + ) -> Result> { let olm = self.olm_machine().await; let Some(olm) = olm.as_ref() else { return Ok(None) }; @@ -372,7 +372,7 @@ impl BaseClient { .await? { RoomEventDecryptionResult::Decrypted(decrypted) => { - let event: SyncTimelineEvent = decrypted.into(); + let event: TimelineEvent = decrypted.into(); if let Ok(AnySyncTimelineEvent::MessageLike(e)) = event.raw().deserialize() { match &e { @@ -394,7 +394,7 @@ impl BaseClient { event } RoomEventDecryptionResult::UnableToDecrypt(utd_info) => { - SyncTimelineEvent::new_utd_event(event.clone(), utd_info) + TimelineEvent::new_utd_event(event.clone(), utd_info) } }; @@ -423,7 +423,7 @@ impl BaseClient { for raw_event in events { // Start by assuming we have a plaintext event. We'll replace it with a // decrypted or UTD event below if necessary. - let mut event = SyncTimelineEvent::new(raw_event); + let mut event = TimelineEvent::new(raw_event); match event.raw().deserialize() { Ok(e) => { diff --git a/crates/matrix-sdk-base/src/event_cache/mod.rs b/crates/matrix-sdk-base/src/event_cache/mod.rs index 0b4a80a4d95..fb8f2bcf2d5 100644 --- a/crates/matrix-sdk-base/src/event_cache/mod.rs +++ b/crates/matrix-sdk-base/src/event_cache/mod.rs @@ -14,12 +14,12 @@ //! Event cache store and common types shared with `matrix_sdk::event_cache`. -use matrix_sdk_common::deserialized_responses::SyncTimelineEvent; +use matrix_sdk_common::deserialized_responses::TimelineEvent; pub mod store; /// The kind of event the event storage holds. -pub type Event = SyncTimelineEvent; +pub type Event = TimelineEvent; /// The kind of gap the event storage holds. #[derive(Clone, Debug)] diff --git a/crates/matrix-sdk-base/src/event_cache/store/integration_tests.rs b/crates/matrix-sdk-base/src/event_cache/store/integration_tests.rs index 7a5bae43ca0..f36bc662bfb 100644 --- a/crates/matrix-sdk-base/src/event_cache/store/integration_tests.rs +++ b/crates/matrix-sdk-base/src/event_cache/store/integration_tests.rs @@ -18,7 +18,7 @@ use assert_matches::assert_matches; use async_trait::async_trait; use matrix_sdk_common::{ deserialized_responses::{ - AlgorithmInfo, DecryptedRoomEvent, EncryptionInfo, SyncTimelineEvent, TimelineEventKind, + AlgorithmInfo, DecryptedRoomEvent, EncryptionInfo, TimelineEvent, TimelineEventKind, VerificationState, }, linked_chunk::{ @@ -42,7 +42,7 @@ use crate::{ /// correctly stores event data. /// /// Keep in sync with [`check_test_event`]. -pub fn make_test_event(room_id: &RoomId, content: &str) -> SyncTimelineEvent { +pub fn make_test_event(room_id: &RoomId, content: &str) -> TimelineEvent { let encryption_info = EncryptionInfo { sender: (*ALICE).into(), sender_device: None, @@ -60,7 +60,7 @@ pub fn make_test_event(room_id: &RoomId, content: &str) -> SyncTimelineEvent { .into_raw_timeline() .cast(); - SyncTimelineEvent { + TimelineEvent { kind: TimelineEventKind::Decrypted(DecryptedRoomEvent { event, encryption_info, @@ -75,7 +75,7 @@ pub fn make_test_event(room_id: &RoomId, content: &str) -> SyncTimelineEvent { /// /// Keep in sync with [`make_test_event`]. #[track_caller] -pub fn check_test_event(event: &SyncTimelineEvent, text: &str) { +pub fn check_test_event(event: &TimelineEvent, text: &str) { // Check push actions. let actions = event.push_actions.as_ref().unwrap(); assert_eq!(actions.len(), 1); diff --git a/crates/matrix-sdk-base/src/latest_event.rs b/crates/matrix-sdk-base/src/latest_event.rs index d610ec90ff5..92fc77a8263 100644 --- a/crates/matrix-sdk-base/src/latest_event.rs +++ b/crates/matrix-sdk-base/src/latest_event.rs @@ -1,7 +1,7 @@ //! Utilities for working with events to decide whether they are suitable for //! use as a [crate::Room::latest_event]. -use matrix_sdk_common::deserialized_responses::SyncTimelineEvent; +use matrix_sdk_common::deserialized_responses::TimelineEvent; #[cfg(feature = "e2e-encryption")] use ruma::{ events::{ @@ -164,7 +164,7 @@ pub fn is_suitable_for_latest_event<'a>( #[derive(Clone, Debug, Serialize)] pub struct LatestEvent { /// The actual event. - event: SyncTimelineEvent, + event: TimelineEvent, /// The member profile of the event' sender. #[serde(skip_serializing_if = "Option::is_none")] @@ -178,7 +178,7 @@ pub struct LatestEvent { #[derive(Deserialize)] struct SerializedLatestEvent { /// The actual event. - event: SyncTimelineEvent, + event: TimelineEvent, /// The member profile of the event' sender. #[serde(skip_serializing_if = "Option::is_none")] @@ -211,7 +211,7 @@ impl<'de> Deserialize<'de> for LatestEvent { Err(err) => variant_errors.push(err), } - match serde_json::from_str::(raw.get()) { + match serde_json::from_str::(raw.get()) { Ok(value) => { return Ok(LatestEvent { event: value, @@ -230,13 +230,13 @@ impl<'de> Deserialize<'de> for LatestEvent { impl LatestEvent { /// Create a new [`LatestEvent`] without the sender's profile. - pub fn new(event: SyncTimelineEvent) -> Self { + pub fn new(event: TimelineEvent) -> Self { Self { event, sender_profile: None, sender_name_is_ambiguous: None } } /// Create a new [`LatestEvent`] with maybe the sender's profile. pub fn new_with_sender_details( - event: SyncTimelineEvent, + event: TimelineEvent, sender_profile: Option, sender_name_is_ambiguous: Option, ) -> Self { @@ -244,17 +244,17 @@ impl LatestEvent { } /// Transform [`Self`] into an event. - pub fn into_event(self) -> SyncTimelineEvent { + pub fn into_event(self) -> TimelineEvent { self.event } /// Get a reference to the event. - pub fn event(&self) -> &SyncTimelineEvent { + pub fn event(&self) -> &TimelineEvent { &self.event } /// Get a mutable reference to the event. - pub fn event_mut(&mut self) -> &mut SyncTimelineEvent { + pub fn event_mut(&mut self) -> &mut TimelineEvent { &mut self.event } @@ -301,7 +301,7 @@ mod tests { use assert_matches::assert_matches; #[cfg(feature = "e2e-encryption")] use assert_matches2::assert_let; - use matrix_sdk_common::deserialized_responses::SyncTimelineEvent; + use matrix_sdk_common::deserialized_responses::TimelineEvent; use ruma::serde::Raw; #[cfg(feature = "e2e-encryption")] use ruma::{ @@ -596,7 +596,7 @@ mod tests { latest_event: LatestEvent, } - let event = SyncTimelineEvent::new( + let event = TimelineEvent::new( Raw::from_json_string(json!({ "event_id": "$1" }).to_string()).unwrap(), ); diff --git a/crates/matrix-sdk-base/src/read_receipts.rs b/crates/matrix-sdk-base/src/read_receipts.rs index bc4f54364e4..171fd1ad35a 100644 --- a/crates/matrix-sdk-base/src/read_receipts.rs +++ b/crates/matrix-sdk-base/src/read_receipts.rs @@ -123,7 +123,7 @@ use std::{ }; use eyeball_im::Vector; -use matrix_sdk_common::{deserialized_responses::SyncTimelineEvent, ring_buffer::RingBuffer}; +use matrix_sdk_common::{deserialized_responses::TimelineEvent, ring_buffer::RingBuffer}; use ruma::{ events::{ poll::{start::PollStartEventContent, unstable_start::UnstablePollStartEventContent}, @@ -202,7 +202,7 @@ impl RoomReadReceipts { /// /// Returns whether a new event triggered a new unread/notification/mention. #[inline(always)] - fn process_event(&mut self, event: &SyncTimelineEvent, user_id: &UserId) { + fn process_event(&mut self, event: &TimelineEvent, user_id: &UserId) { if marks_as_unread(event.raw(), user_id) { self.num_unread += 1; } @@ -240,7 +240,7 @@ impl RoomReadReceipts { &mut self, receipt_event_id: &EventId, user_id: &UserId, - events: impl IntoIterator, + events: impl IntoIterator, ) -> bool { let mut counting_receipts = false; @@ -273,11 +273,11 @@ impl RoomReadReceipts { pub trait PreviousEventsProvider: Send + Sync { /// Returns the list of known timeline events, in sync order, for the given /// room. - fn for_room(&self, room_id: &RoomId) -> Vector; + fn for_room(&self, room_id: &RoomId) -> Vector; } impl PreviousEventsProvider for () { - fn for_room(&self, _: &RoomId) -> Vector { + fn for_room(&self, _: &RoomId) -> Vector { Vector::new() } } @@ -296,7 +296,7 @@ struct ReceiptSelector { impl ReceiptSelector { fn new( - all_events: &Vector, + all_events: &Vector, latest_active_receipt_event: Option<&EventId>, ) -> Self { let event_id_to_pos = Self::create_sync_index(all_events.iter()); @@ -314,7 +314,7 @@ impl ReceiptSelector { /// Create a mapping of `event_id` -> sync order for all events that have an /// `event_id`. fn create_sync_index<'a>( - events: impl Iterator + 'a, + events: impl Iterator + 'a, ) -> BTreeMap { // TODO: this should be cached and incrementally updated. BTreeMap::from_iter( @@ -409,7 +409,7 @@ impl ReceiptSelector { /// Try to match an implicit receipt, that is, the one we get for events we /// sent ourselves. #[instrument(skip_all)] - fn try_match_implicit(&mut self, user_id: &UserId, new_events: &[SyncTimelineEvent]) { + fn try_match_implicit(&mut self, user_id: &UserId, new_events: &[TimelineEvent]) { for ev in new_events { // Get the `sender` field, if any, or skip this event. let Ok(Some(sender)) = ev.raw().get_field::("sender") else { continue }; @@ -436,8 +436,8 @@ impl ReceiptSelector { /// Returns true if there's an event common to both groups of events, based on /// their event id. fn events_intersects<'a>( - previous_events: impl Iterator, - new_events: &[SyncTimelineEvent], + previous_events: impl Iterator, + new_events: &[TimelineEvent], ) -> bool { let previous_events_ids = BTreeSet::from_iter(previous_events.filter_map(|ev| ev.event_id())); new_events @@ -458,8 +458,8 @@ pub(crate) fn compute_unread_counts( user_id: &UserId, room_id: &RoomId, receipt_event: Option<&ReceiptEventContent>, - previous_events: Vector, - new_events: &[SyncTimelineEvent], + previous_events: Vector, + new_events: &[TimelineEvent], read_receipts: &mut RoomReadReceipts, ) { debug!(?read_receipts, "Starting."); @@ -624,7 +624,7 @@ mod tests { use std::{num::NonZeroUsize, ops::Not as _}; use eyeball_im::Vector; - use matrix_sdk_common::{deserialized_responses::SyncTimelineEvent, ring_buffer::RingBuffer}; + use matrix_sdk_common::{deserialized_responses::TimelineEvent, ring_buffer::RingBuffer}; use matrix_sdk_test::event_factory::EventFactory; use ruma::{ event_id, @@ -724,13 +724,13 @@ mod tests { #[test] fn test_count_unread_and_mentions() { - fn make_event(user_id: &UserId, push_actions: Vec) -> SyncTimelineEvent { + fn make_event(user_id: &UserId, push_actions: Vec) -> TimelineEvent { let mut ev = EventFactory::new() .text_msg("A") .sender(user_id) .event_id(event_id!("$ida")) .into_sync(); - ev.push_actions = push_actions; + ev.push_actions = Some(push_actions); ev } @@ -805,7 +805,7 @@ mod tests { // When provided with one event, that's not the receipt event, we don't count // it. - fn make_event(event_id: &EventId) -> SyncTimelineEvent { + fn make_event(event_id: &EventId) -> TimelineEvent { EventFactory::new() .text_msg("A") .sender(user_id!("@bob:example.org")) @@ -958,7 +958,7 @@ mod tests { assert_eq!(read_receipts.num_unread, 2); } - fn make_test_events(user_id: &UserId) -> Vector { + fn make_test_events(user_id: &UserId) -> Vector { let f = EventFactory::new().sender(user_id); let ev1 = f.text_msg("With the lights out, it's less dangerous").event_id(event_id!("$1")); let ev2 = f.text_msg("Here we are now, entertain us").event_id(event_id!("$2")); diff --git a/crates/matrix-sdk-base/src/rooms/normal.rs b/crates/matrix-sdk-base/src/rooms/normal.rs index f534ad399e8..316d64dcc6f 100644 --- a/crates/matrix-sdk-base/src/rooms/normal.rs +++ b/crates/matrix-sdk-base/src/rooms/normal.rs @@ -2164,7 +2164,7 @@ mod tests { }; use assign::assign; - use matrix_sdk_common::deserialized_responses::SyncTimelineEvent; + use matrix_sdk_common::deserialized_responses::TimelineEvent; use matrix_sdk_test::{ async_test, event_factory::EventFactory, @@ -2241,7 +2241,7 @@ mod tests { last_prev_batch: Some("pb".to_owned()), sync_info: SyncInfo::FullySynced, encryption_state_synced: true, - latest_event: Some(Box::new(LatestEvent::new(SyncTimelineEvent::new( + latest_event: Some(Box::new(LatestEvent::new(TimelineEvent::new( Raw::from_json_string(json!({"sender": "@u:i.uk"}).to_string()).unwrap(), )))), base_info: Box::new( @@ -3324,7 +3324,7 @@ mod tests { #[cfg(feature = "e2e-encryption")] fn make_latest_event(event_id: &str) -> Box { - Box::new(LatestEvent::new(SyncTimelineEvent::new( + Box::new(LatestEvent::new(TimelineEvent::new( Raw::from_json_string(json!({ "event_id": event_id }).to_string()).unwrap(), ))) } diff --git a/crates/matrix-sdk-base/src/sliding_sync/mod.rs b/crates/matrix-sdk-base/src/sliding_sync/mod.rs index 29024555cab..8ae81a41cc4 100644 --- a/crates/matrix-sdk-base/src/sliding_sync/mod.rs +++ b/crates/matrix-sdk-base/src/sliding_sync/mod.rs @@ -21,7 +21,7 @@ use std::ops::Deref; use std::{borrow::Cow, collections::BTreeMap}; #[cfg(feature = "e2e-encryption")] -use matrix_sdk_common::deserialized_responses::SyncTimelineEvent; +use matrix_sdk_common::deserialized_responses::TimelineEvent; use ruma::{ api::client::sync::sync_events::v3::{self, InvitedRoom, KnockedRoom}, events::{ @@ -690,7 +690,7 @@ impl BaseClient { async fn cache_latest_events( room: &Room, room_info: &mut RoomInfo, - events: &[SyncTimelineEvent], + events: &[TimelineEvent], changes: Option<&StateChanges>, store: Option<&Store>, ) { @@ -900,7 +900,7 @@ mod tests { use std::sync::{Arc, RwLock as SyncRwLock}; use assert_matches::assert_matches; - use matrix_sdk_common::deserialized_responses::SyncTimelineEvent; + use matrix_sdk_common::deserialized_responses::TimelineEvent; #[cfg(feature = "e2e-encryption")] use matrix_sdk_common::{ deserialized_responses::{UnableToDecryptInfo, UnableToDecryptReason}, @@ -2606,7 +2606,7 @@ mod tests { } #[cfg(feature = "e2e-encryption")] - async fn choose_event_to_cache(events: &[SyncTimelineEvent]) -> Option { + async fn choose_event_to_cache(events: &[TimelineEvent]) -> Option { let room = make_room(); let mut room_info = room.clone_info(); cache_latest_events(&room, &mut room_info, events, None, None).await; @@ -2615,11 +2615,11 @@ mod tests { } #[cfg(feature = "e2e-encryption")] - fn rawev_id(event: SyncTimelineEvent) -> String { + fn rawev_id(event: TimelineEvent) -> String { event.event_id().unwrap().to_string() } - fn ev_id(event: Option) -> String { + fn ev_id(event: Option) -> String { event.unwrap().event_id().unwrap().to_string() } @@ -2629,7 +2629,7 @@ mod tests { } #[cfg(feature = "e2e-encryption")] - fn evs_ids(events: &[SyncTimelineEvent]) -> Vec { + fn evs_ids(events: &[TimelineEvent]) -> Vec { events.iter().map(|e| e.event_id().unwrap().to_string()).collect() } @@ -2661,13 +2661,13 @@ mod tests { } #[cfg(feature = "e2e-encryption")] - fn make_event(typ: &str, id: &str) -> SyncTimelineEvent { - SyncTimelineEvent::new(make_raw_event(typ, id)) + fn make_event(typ: &str, id: &str) -> TimelineEvent { + TimelineEvent::new(make_raw_event(typ, id)) } #[cfg(feature = "e2e-encryption")] - fn make_encrypted_event(id: &str) -> SyncTimelineEvent { - SyncTimelineEvent::new_utd_event( + fn make_encrypted_event(id: &str) -> TimelineEvent { + TimelineEvent::new_utd_event( Raw::from_json_string( json!({ "type": "m.room.encrypted", diff --git a/crates/matrix-sdk-base/src/store/migration_helpers.rs b/crates/matrix-sdk-base/src/store/migration_helpers.rs index e38be077036..b22456fd1b8 100644 --- a/crates/matrix-sdk-base/src/store/migration_helpers.rs +++ b/crates/matrix-sdk-base/src/store/migration_helpers.rs @@ -19,7 +19,7 @@ use std::{ sync::Arc, }; -use matrix_sdk_common::deserialized_responses::SyncTimelineEvent; +use matrix_sdk_common::deserialized_responses::TimelineEvent; use ruma::{ events::{ direct::OwnedDirectUserIdentifier, @@ -76,7 +76,7 @@ pub struct RoomInfoV1 { sync_info: SyncInfo, #[serde(default = "encryption_state_default")] // see fn docs for why we use this default encryption_state_synced: bool, - latest_event: Option, + latest_event: Option, base_info: BaseRoomInfoV1, } diff --git a/crates/matrix-sdk-base/src/sync.rs b/crates/matrix-sdk-base/src/sync.rs index 824becb54b2..5b01e90103f 100644 --- a/crates/matrix-sdk-base/src/sync.rs +++ b/crates/matrix-sdk-base/src/sync.rs @@ -16,7 +16,7 @@ use std::{collections::BTreeMap, fmt}; -use matrix_sdk_common::{debug::DebugRawEvent, deserialized_responses::SyncTimelineEvent}; +use matrix_sdk_common::{debug::DebugRawEvent, deserialized_responses::TimelineEvent}; use ruma::{ api::client::sync::sync_events::{ v3::{InvitedRoom as InvitedRoomUpdate, KnockedRoom as KnockedRoomUpdate}, @@ -236,7 +236,7 @@ pub struct Timeline { pub prev_batch: Option, /// A list of events. - pub events: Vec, + pub events: Vec, } impl Timeline { diff --git a/crates/matrix-sdk-common/src/deserialized_responses.rs b/crates/matrix-sdk-common/src/deserialized_responses.rs index 72b5ec0911f..54366b475fd 100644 --- a/crates/matrix-sdk-common/src/deserialized_responses.rs +++ b/crates/matrix-sdk-common/src/deserialized_responses.rs @@ -311,13 +311,13 @@ pub struct EncryptionInfo { // // 🚨 Note about this type, please read! 🚨 // -// `SyncTimelineEvent` is heavily used across the SDK crates. In some cases, we +// `TimelineEvent` is heavily used across the SDK crates. In some cases, we // are reaching a [`recursion_limit`] when the compiler is trying to figure out -// if `SyncTimelineEvent` implements `Sync` when it's embedded in other types. +// if `TimelineEvent` implements `Sync` when it's embedded in other types. // // We want to help the compiler so that one doesn't need to increase the // `recursion_limit`. We stop the recursive check by (un)safely implement `Sync` -// and `Send` on `SyncTimelineEvent` directly. +// and `Send` on `TimelineEvent` directly. // // See // https://github.com/matrix-org/matrix-rust-sdk/pull/3749#issuecomment-2312939823 @@ -325,7 +325,7 @@ pub struct EncryptionInfo { // // [`recursion_limit`]: https://doc.rust-lang.org/reference/attributes/limits.html#the-recursion_limit-attribute #[derive(Clone, Debug, Serialize)] -pub struct SyncTimelineEvent { +pub struct TimelineEvent { /// The event itself, together with any information on decryption. pub kind: TimelineEventKind, @@ -338,11 +338,11 @@ pub struct SyncTimelineEvent { // See https://github.com/matrix-org/matrix-rust-sdk/pull/3749#issuecomment-2312939823. #[cfg(not(feature = "test-send-sync"))] -unsafe impl Send for SyncTimelineEvent {} +unsafe impl Send for TimelineEvent {} // See https://github.com/matrix-org/matrix-rust-sdk/pull/3749#issuecomment-2312939823. #[cfg(not(feature = "test-send-sync"))] -unsafe impl Sync for SyncTimelineEvent {} +unsafe impl Sync for TimelineEvent {} #[cfg(feature = "test-send-sync")] #[test] @@ -350,11 +350,11 @@ unsafe impl Sync for SyncTimelineEvent {} fn test_send_sync_for_sync_timeline_event() { fn assert_send_sync() {} - assert_send_sync::(); + assert_send_sync::(); } -impl SyncTimelineEvent { - /// Create a new `SyncTimelineEvent` from the given raw event. +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. @@ -362,7 +362,7 @@ impl SyncTimelineEvent { Self { kind: TimelineEventKind::PlainText { event }, push_actions: None } } - /// Create a new `SyncTimelineEvent` from the given raw event and push + /// Create a new [`TimelineEvent`] from the given raw event and push /// actions. /// /// This is a convenience constructor for a plaintext event, for example @@ -374,20 +374,20 @@ impl SyncTimelineEvent { Self { kind: TimelineEventKind::PlainText { event }, push_actions: Some(push_actions) } } - /// Create a new `SyncTimelineEvent` to represent the given decryption + /// 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 } } - /// Get the event id of this `SyncTimelineEvent` if the event has any valid + /// Get the event id of this [`TimelineEvent`] if the event has any valid /// id. pub fn event_id(&self) -> Option { self.kind.event_id() } /// Returns a reference to the (potentially decrypted) Matrix event inside - /// this `TimelineEvent`. + /// this [`TimelineEvent`]. pub fn raw(&self) -> &Raw { self.kind.raw() } @@ -418,14 +418,14 @@ impl SyncTimelineEvent { } } -impl From for SyncTimelineEvent { +impl From for TimelineEvent { fn from(decrypted: DecryptedRoomEvent) -> Self { Self { kind: TimelineEventKind::Decrypted(decrypted), push_actions: None } } } -impl<'de> Deserialize<'de> for SyncTimelineEvent { - /// Custom deserializer for [`SyncTimelineEvent`], to support older formats. +impl<'de> Deserialize<'de> for TimelineEvent { + /// Custom deserializer for [`TimelineEvent`], to support older formats. /// /// Ideally we might use an untagged enum and then convert from that; /// however, that doesn't work due to a [serde bug](https://github.com/serde-rs/json/issues/497). @@ -446,7 +446,7 @@ impl<'de> Deserialize<'de> for SyncTimelineEvent { let v0: SyncTimelineEventDeserializationHelperV0 = serde_json::from_value(Value::Object(value)).map_err(|e| { serde::de::Error::custom(format!( - "Unable to deserialize V0-format SyncTimelineEvent: {}", + "Unable to deserialize V0-format TimelineEvent: {}", e )) })?; @@ -457,7 +457,7 @@ impl<'de> Deserialize<'de> for SyncTimelineEvent { let v1: SyncTimelineEventDeserializationHelperV1 = serde_json::from_value(Value::Object(value)).map_err(|e| { serde::de::Error::custom(format!( - "Unable to deserialize V1-format SyncTimelineEvent: {}", + "Unable to deserialize V1-format TimelineEvent: {}", e )) })?; @@ -466,8 +466,7 @@ impl<'de> Deserialize<'de> for SyncTimelineEvent { } } -/// The event within a [`TimelineEvent`] or [`SyncTimelineEvent`], together with -/// encryption data. +/// The event within a [`TimelineEvent`], together with encryption data. #[derive(Clone, Serialize, Deserialize)] pub enum TimelineEventKind { /// A successfully-decrypted encrypted event. @@ -806,9 +805,9 @@ impl fmt::Debug for PrivOwnedStr { } } -/// Deserialization helper for [`SyncTimelineEvent`], for the modern format. +/// Deserialization helper for [`TimelineEvent`], for the modern format. /// -/// This has the exact same fields as [`SyncTimelineEvent`] itself, but has a +/// This has the exact same fields as [`TimelineEvent`] itself, but has a /// regular `Deserialize` implementation. #[derive(Debug, Deserialize)] struct SyncTimelineEventDeserializationHelperV1 { @@ -820,14 +819,14 @@ struct SyncTimelineEventDeserializationHelperV1 { push_actions: Vec, } -impl From for SyncTimelineEvent { +impl From for TimelineEvent { fn from(value: SyncTimelineEventDeserializationHelperV1) -> Self { let SyncTimelineEventDeserializationHelperV1 { kind, push_actions } = value; - SyncTimelineEvent { kind, push_actions: Some(push_actions) } + TimelineEvent { kind, push_actions: Some(push_actions) } } } -/// Deserialization helper for [`SyncTimelineEvent`], for an older format. +/// Deserialization helper for [`TimelineEvent`], for an older format. #[derive(Deserialize)] struct SyncTimelineEventDeserializationHelperV0 { /// The actual event. @@ -848,7 +847,7 @@ struct SyncTimelineEventDeserializationHelperV0 { unsigned_encryption_info: Option>, } -impl From for SyncTimelineEvent { +impl From for TimelineEvent { fn from(value: SyncTimelineEventDeserializationHelperV0) -> Self { let SyncTimelineEventDeserializationHelperV0 { event, @@ -875,7 +874,7 @@ impl From for SyncTimelineEvent { None => TimelineEventKind::PlainText { event }, }; - SyncTimelineEvent { kind, push_actions: Some(push_actions) } + TimelineEvent { kind, push_actions: Some(push_actions) } } } @@ -894,7 +893,7 @@ mod tests { use super::{ AlgorithmInfo, DecryptedRoomEvent, DeviceLinkProblem, EncryptionInfo, ShieldState, - ShieldStateCode, SyncTimelineEvent, TimelineEventKind, UnableToDecryptInfo, + ShieldStateCode, TimelineEvent, TimelineEventKind, UnableToDecryptInfo, UnableToDecryptReason, UnsignedDecryptionResult, UnsignedEventLocation, VerificationLevel, VerificationState, WithheldCode, }; @@ -912,7 +911,7 @@ mod tests { #[test] fn sync_timeline_debug_content() { - let room_event = SyncTimelineEvent::new(Raw::new(&example_event()).unwrap().cast()); + let room_event = TimelineEvent::new(Raw::new(&example_event()).unwrap().cast()); let debug_s = format!("{room_event:?}"); assert!( !debug_s.contains("secret"), @@ -1030,7 +1029,7 @@ mod tests { #[test] fn sync_timeline_event_serialisation() { - let room_event = SyncTimelineEvent { + let room_event = TimelineEvent { kind: TimelineEventKind::Decrypted(DecryptedRoomEvent { event: Raw::new(&example_event()).unwrap().cast(), encryption_info: EncryptionInfo { @@ -1092,7 +1091,7 @@ mod tests { ); // And it can be properly deserialized from the new format. - let event: SyncTimelineEvent = serde_json::from_value(serialized).unwrap(); + let event: TimelineEvent = serde_json::from_value(serialized).unwrap(); assert_eq!(event.event_id(), Some(event_id!("$xxxxx:example.org").to_owned())); assert_matches!( event.encryption_info().unwrap().algorithm_info, @@ -1121,7 +1120,7 @@ mod tests { "verification_state": "Verified", }, }); - let event: SyncTimelineEvent = serde_json::from_value(serialized).unwrap(); + let event: TimelineEvent = serde_json::from_value(serialized).unwrap(); assert_eq!(event.event_id(), Some(event_id!("$xxxxx:example.org").to_owned())); assert_matches!( event.encryption_info().unwrap().algorithm_info, @@ -1154,7 +1153,7 @@ mod tests { "RelationsReplace": {"UnableToDecrypt": {"session_id": "xyz"}} } }); - let event: SyncTimelineEvent = serde_json::from_value(serialized).unwrap(); + let event: TimelineEvent = serde_json::from_value(serialized).unwrap(); assert_eq!(event.event_id(), Some(event_id!("$xxxxx:example.org").to_owned())); assert_matches!( event.encryption_info().unwrap().algorithm_info, @@ -1220,7 +1219,7 @@ mod tests { assert!(result.is_ok()); // should have migrated to the new format - let event: SyncTimelineEvent = result.unwrap(); + let event: TimelineEvent = result.unwrap(); assert_matches!( event.kind, TimelineEventKind::UnableToDecrypt { utd_info, .. }=> { @@ -1362,7 +1361,7 @@ mod tests { #[test] fn snapshot_test_sync_timeline_event() { - let room_event = SyncTimelineEvent { + let room_event = TimelineEvent { kind: TimelineEventKind::Decrypted(DecryptedRoomEvent { event: Raw::new(&example_event()).unwrap().cast(), encryption_info: EncryptionInfo { diff --git a/crates/matrix-sdk-sqlite/migrations/event_cache_store/003_events.sql b/crates/matrix-sdk-sqlite/migrations/event_cache_store/003_events.sql index 1de6495cc0d..c3f8e07a098 100644 --- a/crates/matrix-sdk-sqlite/migrations/event_cache_store/003_events.sql +++ b/crates/matrix-sdk-sqlite/migrations/event_cache_store/003_events.sql @@ -36,7 +36,7 @@ CREATE TABLE "events" ( -- `OwnedEventId` for events, can be null if malformed. "event_id" TEXT, - -- JSON serialized `SyncTimelineEvent` (encrypted value). + -- JSON serialized `TimelineEvent` (encrypted value). "content" BLOB NOT NULL, -- Position (index) in the chunk. "position" INTEGER NOT NULL, diff --git a/crates/matrix-sdk-ui/src/notification_client.rs b/crates/matrix-sdk-ui/src/notification_client.rs index b896fa64f84..5af760e713f 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::SyncTimelineEvent, sliding_sync::http, RoomState, StoreError, + deserialized_responses::TimelineEvent, 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)?; diff --git a/crates/matrix-sdk-ui/src/timeline/controller/mod.rs b/crates/matrix-sdk-ui/src/timeline/controller/mod.rs index 75c7f8983fb..e5f963d1524 100644 --- a/crates/matrix-sdk-ui/src/timeline/controller/mod.rs +++ b/crates/matrix-sdk-ui/src/timeline/controller/mod.rs @@ -22,7 +22,7 @@ use imbl::Vector; #[cfg(test)] use matrix_sdk::{crypto::OlmMachine, SendOutsideWasm}; use matrix_sdk::{ - deserialized_responses::{SyncTimelineEvent, TimelineEventKind as SdkTimelineEventKind}, + deserialized_responses::{TimelineEvent, TimelineEventKind as SdkTimelineEventKind}, event_cache::{paginator::Paginator, RoomEventCache}, send_queue::{ LocalEcho, LocalEchoContent, RoomSendQueueUpdate, SendHandle, SendReactionHandle, @@ -396,7 +396,7 @@ impl TimelineController

{ pub(crate) async fn reload_pinned_events( &self, - ) -> Result, PinnedEventsLoaderError> { + ) -> Result, PinnedEventsLoaderError> { let focus_guard = self.focus.read().await; if let TimelineFocusData::PinnedEvents { loader } = &*focus_guard { @@ -663,7 +663,7 @@ impl TimelineController

{ ) -> HandleManyEventsResult where Events: IntoIterator + ExactSizeIterator, - ::Item: Into, + ::Item: Into, { if events.len() == 0 { return Default::default(); @@ -676,7 +676,7 @@ impl TimelineController

{ /// Handle updates on events as [`VectorDiff`]s. pub(super) async fn handle_remote_events_with_diffs( &self, - diffs: Vec>, + diffs: Vec>, origin: RemoteEventOrigin, ) { if diffs.is_empty() { @@ -711,7 +711,7 @@ impl TimelineController

{ origin: RemoteEventOrigin, ) where Events: IntoIterator + ExactSizeIterator, - ::Item: Into, + ::Item: Into, { let mut state = self.state.write().await; diff --git a/crates/matrix-sdk-ui/src/timeline/controller/state.rs b/crates/matrix-sdk-ui/src/timeline/controller/state.rs index 5b5d1e59d21..18fa85cbe05 100644 --- a/crates/matrix-sdk-ui/src/timeline/controller/state.rs +++ b/crates/matrix-sdk-ui/src/timeline/controller/state.rs @@ -22,7 +22,7 @@ use std::{ use eyeball_im::VectorDiff; use itertools::Itertools as _; use matrix_sdk::{ - deserialized_responses::SyncTimelineEvent, ring_buffer::RingBuffer, send_queue::SendHandle, + deserialized_responses::TimelineEvent, ring_buffer::RingBuffer, send_queue::SendHandle, }; #[cfg(test)] use ruma::events::receipt::ReceiptEventContent; @@ -138,7 +138,7 @@ impl TimelineState { ) -> HandleManyEventsResult where Events: IntoIterator + ExactSizeIterator, - ::Item: Into, + ::Item: Into, RoomData: RoomDataProvider, { if events.len() == 0 { @@ -156,7 +156,7 @@ impl TimelineState { /// Handle updates on events as [`VectorDiff`]s. pub(super) async fn handle_remote_events_with_diffs( &mut self, - diffs: Vec>, + diffs: Vec>, origin: RemoteEventOrigin, room_data: &RoomData, settings: &TimelineSettings, @@ -256,7 +256,7 @@ impl TimelineState { room_data_provider: &P, settings: &TimelineSettings, ) where - Fut: Future>, + Fut: Future>, { let mut txn = self.transaction(); @@ -330,7 +330,7 @@ impl TimelineState { ) -> HandleManyEventsResult where Events: IntoIterator, - Events::Item: Into, + Events::Item: Into, RoomData: RoomDataProvider, { let mut txn = self.transaction(); @@ -396,7 +396,7 @@ impl TimelineStateTransaction<'_> { ) -> HandleManyEventsResult where Events: IntoIterator, - Events::Item: Into, + Events::Item: Into, RoomData: RoomDataProvider, { let mut total = HandleManyEventsResult::default(); @@ -438,7 +438,7 @@ impl TimelineStateTransaction<'_> { /// Handle updates on events as [`VectorDiff`]s. pub(super) async fn handle_remote_events_with_diffs( &mut self, - diffs: Vec>, + diffs: Vec>, origin: RemoteEventOrigin, room_data_provider: &RoomData, settings: &TimelineSettings, @@ -558,13 +558,13 @@ impl TimelineStateTransaction<'_> { /// Returns the number of timeline updates that were made. async fn handle_remote_event( &mut self, - event: SyncTimelineEvent, + event: TimelineEvent, position: TimelineItemPosition, room_data_provider: &P, settings: &TimelineSettings, date_divider_adjuster: &mut DateDividerAdjuster, ) -> HandleEventResult { - let SyncTimelineEvent { push_actions, kind } = event; + let TimelineEvent { push_actions, kind } = event; let encryption_info = kind.encryption_info().cloned(); let (raw, utd_info) = match kind { diff --git a/crates/matrix-sdk-ui/src/timeline/event_handler.rs b/crates/matrix-sdk-ui/src/timeline/event_handler.rs index 5a3d362ea52..6759a2e5250 100644 --- a/crates/matrix-sdk-ui/src/timeline/event_handler.rs +++ b/crates/matrix-sdk-ui/src/timeline/event_handler.rs @@ -211,7 +211,7 @@ impl TimelineEventKind { Self::UnableToDecrypt { content, utd_cause } } else { // If we get here, it means that some part of the code has created a - // `SyncTimelineEvent` containing an `m.room.encrypted` event + // `TimelineEvent` containing an `m.room.encrypted` event // without decrypting it. Possibly this means that encryption has not been // configured. // We treat it the same as any other message-like 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 06c715eaf7d..09ee071f923 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::SyncTimelineEvent, Room}; +use matrix_sdk::{deserialized_responses::TimelineEvent, 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: SyncTimelineEvent, + timeline_event: TimelineEvent, 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: SyncTimelineEvent, + timeline_event: TimelineEvent, room_data_provider: &P, ) -> Result { let event = match timeline_event.raw().deserialize() { diff --git a/crates/matrix-sdk-ui/src/timeline/event_item/mod.rs b/crates/matrix-sdk-ui/src/timeline/event_item/mod.rs index 9873c0a0947..a31ac8dbb84 100644 --- a/crates/matrix-sdk-ui/src/timeline/event_item/mod.rs +++ b/crates/matrix-sdk-ui/src/timeline/event_item/mod.rs @@ -127,14 +127,17 @@ impl EventTimelineItem { Self { sender, sender_profile, timestamp, content, reactions, kind, is_room_encrypted } } - /// If the supplied low-level `SyncTimelineEvent` is suitable for use as the - /// `latest_event` in a message preview, wrap it as an `EventTimelineItem`. + /// If the supplied low-level [`TimelineEvent`] is suitable for use as the + /// `latest_event` in a message preview, wrap it as an + /// `EventTimelineItem`. /// /// **Note:** Timeline items created via this constructor do **not** produce /// the correct ShieldState when calling /// [`get_shield`][EventTimelineItem::get_shield]. This is because they are /// intended for display in the room list which a) is unlikely to show /// shields and b) would incur a significant performance overhead. + /// + /// [`TimelineEvent`]: matrix_sdk::deserialized_responses::TimelineEvent pub async fn from_latest_event( client: Client, room_id: &RoomId, @@ -754,7 +757,7 @@ mod tests { use assert_matches2::assert_let; use matrix_sdk::test_utils::logged_in_client; use matrix_sdk_base::{ - deserialized_responses::SyncTimelineEvent, latest_event::LatestEvent, sliding_sync::http, + deserialized_responses::TimelineEvent, latest_event::LatestEvent, sliding_sync::http, MinimalStateEvent, OriginalMinimalStateEvent, }; use matrix_sdk_test::{ @@ -844,7 +847,7 @@ mod tests { client.process_sliding_sync_test_helper(&response).await.unwrap(); // When we construct a timeline event from it - let event = SyncTimelineEvent::new(raw_event.cast()); + let event = TimelineEvent::new(raw_event.cast()); let timeline_item = EventTimelineItem::from_latest_event(client, room_id, LatestEvent::new(event)) .await @@ -1121,8 +1124,8 @@ mod tests { body: &str, formatted_body: &str, ts: u64, - ) -> SyncTimelineEvent { - SyncTimelineEvent::new(sync_timeline_event!({ + ) -> TimelineEvent { + TimelineEvent::new(sync_timeline_event!({ "event_id": "$eventid6", "sender": user_id, "origin_server_ts": ts, diff --git a/crates/matrix-sdk-ui/src/timeline/pinned_events_loader.rs b/crates/matrix-sdk-ui/src/timeline/pinned_events_loader.rs index 2fa07fd6787..53b8444119e 100644 --- a/crates/matrix-sdk-ui/src/timeline/pinned_events_loader.rs +++ b/crates/matrix-sdk-ui/src/timeline/pinned_events_loader.rs @@ -19,7 +19,7 @@ use matrix_sdk::{ config::RequestConfig, event_cache::paginator::PaginatorError, BoxFuture, Room, SendOutsideWasm, SyncOutsideWasm, }; -use matrix_sdk_base::deserialized_responses::SyncTimelineEvent; +use matrix_sdk_base::deserialized_responses::TimelineEvent; use ruma::{events::relation::RelationType, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId}; use thiserror::Error; use tracing::{debug, warn}; @@ -55,9 +55,9 @@ impl PinnedEventsLoader { /// `max_concurrent_requests` allows, to avoid overwhelming the server. /// /// It returns a `Result` with either a - /// chronologically sorted list of retrieved `SyncTimelineEvent`s - /// or a `PinnedEventsLoaderError`. - pub async fn load_events(&self) -> Result, PinnedEventsLoaderError> { + /// chronologically sorted list of retrieved [`TimelineEvent`]s + /// or a [`PinnedEventsLoaderError`]. + pub async fn load_events(&self) -> Result, PinnedEventsLoaderError> { let pinned_event_ids: Vec = self .room .pinned_event_ids() @@ -74,7 +74,7 @@ impl PinnedEventsLoader { let request_config = Some(RequestConfig::default().retry_limit(3)); - let mut loaded_events: Vec = + let mut loaded_events: Vec = stream::iter(pinned_event_ids.into_iter().map(|event_id| { let provider = self.room.clone(); let relations_filter = @@ -132,7 +132,7 @@ pub trait PinnedEventsRoom: SendOutsideWasm + SyncOutsideWasm { event_id: &'a EventId, request_config: Option, related_event_filters: Option>, - ) -> BoxFuture<'a, Result<(SyncTimelineEvent, Vec), PaginatorError>>; + ) -> BoxFuture<'a, Result<(TimelineEvent, Vec), PaginatorError>>; /// Get the pinned event ids for a room. fn pinned_event_ids(&self) -> Option>; @@ -150,7 +150,7 @@ impl PinnedEventsRoom for Room { event_id: &'a EventId, request_config: Option, related_event_filters: Option>, - ) -> BoxFuture<'a, Result<(SyncTimelineEvent, Vec), PaginatorError>> { + ) -> BoxFuture<'a, Result<(TimelineEvent, Vec), PaginatorError>> { Box::pin(async move { if let Ok((cache, _handles)) = self.event_cache().await { if let Some(ret) = cache.event_with_relations(event_id, related_event_filters).await diff --git a/crates/matrix-sdk-ui/src/timeline/tests/basic.rs b/crates/matrix-sdk-ui/src/timeline/tests/basic.rs index a9350283240..43126c02342 100644 --- a/crates/matrix-sdk-ui/src/timeline/tests/basic.rs +++ b/crates/matrix-sdk-ui/src/timeline/tests/basic.rs @@ -16,7 +16,7 @@ use assert_matches::assert_matches; use assert_matches2::assert_let; use eyeball_im::VectorDiff; use futures_util::StreamExt; -use matrix_sdk::deserialized_responses::SyncTimelineEvent; +use matrix_sdk::deserialized_responses::TimelineEvent; use matrix_sdk_test::{ async_test, event_factory::PreviousMembership, sync_timeline_event, ALICE, BOB, CAROL, }; @@ -122,7 +122,7 @@ async fn test_sticker() { let mut stream = timeline.subscribe_events().await; timeline - .handle_live_event(SyncTimelineEvent::new(sync_timeline_event!({ + .handle_live_event(TimelineEvent::new(sync_timeline_event!({ "content": { "body": "Happy sticker", "info": { diff --git a/crates/matrix-sdk-ui/src/timeline/tests/edit.rs b/crates/matrix-sdk-ui/src/timeline/tests/edit.rs index ed90d46c57a..5c00e21861f 100644 --- a/crates/matrix-sdk-ui/src/timeline/tests/edit.rs +++ b/crates/matrix-sdk-ui/src/timeline/tests/edit.rs @@ -19,7 +19,7 @@ use eyeball_im::VectorDiff; use matrix_sdk::deserialized_responses::{ AlgorithmInfo, EncryptionInfo, VerificationLevel, VerificationState, }; -use matrix_sdk_base::deserialized_responses::{DecryptedRoomEvent, SyncTimelineEvent}; +use matrix_sdk_base::deserialized_responses::{DecryptedRoomEvent, TimelineEvent}; use matrix_sdk_test::{async_test, ALICE}; use ruma::{ event_id, @@ -178,7 +178,7 @@ async fn test_edit_updates_encryption_info() { verification_state: VerificationState::Verified, }; - let original_event: SyncTimelineEvent = DecryptedRoomEvent { + let original_event: TimelineEvent = DecryptedRoomEvent { event: original_event.cast(), encryption_info: encryption_info.clone(), unsigned_encryption_info: None, @@ -207,7 +207,7 @@ async fn test_edit_updates_encryption_info() { .into_raw_timeline(); encryption_info.verification_state = VerificationState::Unverified(VerificationLevel::UnverifiedIdentity); - let edit_event: SyncTimelineEvent = DecryptedRoomEvent { + let edit_event: TimelineEvent = DecryptedRoomEvent { event: edit_event.cast(), encryption_info: encryption_info.clone(), unsigned_encryption_info: None, diff --git a/crates/matrix-sdk-ui/src/timeline/tests/encryption.rs b/crates/matrix-sdk-ui/src/timeline/tests/encryption.rs index d50fdb76f3c..40799138d31 100644 --- a/crates/matrix-sdk-ui/src/timeline/tests/encryption.rs +++ b/crates/matrix-sdk-ui/src/timeline/tests/encryption.rs @@ -30,7 +30,7 @@ use matrix_sdk::{ crypto::{decrypt_room_key_export, types::events::UtdCause, OlmMachine}, test_utils::test_client_builder, }; -use matrix_sdk_base::deserialized_responses::{SyncTimelineEvent, UnableToDecryptReason}; +use matrix_sdk_base::deserialized_responses::{TimelineEvent, UnableToDecryptReason}; use matrix_sdk_test::{async_test, ALICE, BOB}; use ruma::{ assign, event_id, @@ -750,7 +750,7 @@ async fn test_retry_decryption_updates_response() { } } -fn utd_event_with_unsigned(unsigned: serde_json::Value) -> SyncTimelineEvent { +fn utd_event_with_unsigned(unsigned: serde_json::Value) -> TimelineEvent { let raw = Raw::from_json( to_raw_value(&json!({ "event_id": "$myevent", @@ -770,7 +770,7 @@ fn utd_event_with_unsigned(unsigned: serde_json::Value) -> SyncTimelineEvent { .unwrap(), ); - SyncTimelineEvent::new_utd_event( + TimelineEvent::new_utd_event( raw, matrix_sdk::deserialized_responses::UnableToDecryptInfo { session_id: Some("SESSION_ID".into()), diff --git a/crates/matrix-sdk-ui/src/timeline/tests/event_filter.rs b/crates/matrix-sdk-ui/src/timeline/tests/event_filter.rs index 5cfd714f66c..da1d7d40062 100644 --- a/crates/matrix-sdk-ui/src/timeline/tests/event_filter.rs +++ b/crates/matrix-sdk-ui/src/timeline/tests/event_filter.rs @@ -17,7 +17,7 @@ use std::sync::Arc; use assert_matches::assert_matches; use assert_matches2::assert_let; use eyeball_im::VectorDiff; -use matrix_sdk::deserialized_responses::SyncTimelineEvent; +use matrix_sdk::deserialized_responses::TimelineEvent; use matrix_sdk_test::{async_test, sync_timeline_event, ALICE, BOB}; use ruma::events::{ room::{ @@ -141,7 +141,7 @@ async fn test_hide_failed_to_parse() { // m.room.message events must have a msgtype and body in content, so this // event with an empty content object should fail to deserialize. timeline - .handle_live_event(SyncTimelineEvent::new(sync_timeline_event!({ + .handle_live_event(TimelineEvent::new(sync_timeline_event!({ "content": {}, "event_id": "$eeG0HA0FAZ37wP8kXlNkxx3I", "origin_server_ts": 10, @@ -153,7 +153,7 @@ async fn test_hide_failed_to_parse() { // Similar to above, the m.room.member state event must also not have an // empty content object. timeline - .handle_live_event(SyncTimelineEvent::new(sync_timeline_event!({ + .handle_live_event(TimelineEvent::new(sync_timeline_event!({ "content": {}, "event_id": "$d5G0HA0FAZ37wP8kXlNkxx3I", "origin_server_ts": 2179, diff --git a/crates/matrix-sdk-ui/src/timeline/tests/invalid.rs b/crates/matrix-sdk-ui/src/timeline/tests/invalid.rs index 8f3a0883029..1340c6a0923 100644 --- a/crates/matrix-sdk-ui/src/timeline/tests/invalid.rs +++ b/crates/matrix-sdk-ui/src/timeline/tests/invalid.rs @@ -14,7 +14,7 @@ use assert_matches2::assert_let; use eyeball_im::VectorDiff; -use matrix_sdk::deserialized_responses::SyncTimelineEvent; +use matrix_sdk::deserialized_responses::TimelineEvent; use matrix_sdk_test::{async_test, sync_timeline_event, ALICE, BOB}; use ruma::{ events::{room::message::MessageType, MessageLikeEventType, StateEventType}, @@ -60,7 +60,7 @@ async fn test_invalid_event_content() { // m.room.message events must have a msgtype and body in content, so this // event with an empty content object should fail to deserialize. timeline - .handle_live_event(SyncTimelineEvent::new(sync_timeline_event!({ + .handle_live_event(TimelineEvent::new(sync_timeline_event!({ "content": {}, "event_id": "$eeG0HA0FAZ37wP8kXlNkxx3I", "origin_server_ts": 10, @@ -79,7 +79,7 @@ async fn test_invalid_event_content() { // Similar to above, the m.room.member state event must also not have an // empty content object. timeline - .handle_live_event(SyncTimelineEvent::new(sync_timeline_event!({ + .handle_live_event(TimelineEvent::new(sync_timeline_event!({ "content": {}, "event_id": "$d5G0HA0FAZ37wP8kXlNkxx3I", "origin_server_ts": 2179, @@ -107,7 +107,7 @@ async fn test_invalid_event() { // This event is missing the sender field which the homeserver must add to // all timeline events. Because the event is malformed, it will be ignored. timeline - .handle_live_event(SyncTimelineEvent::new(sync_timeline_event!({ + .handle_live_event(TimelineEvent::new(sync_timeline_event!({ "content": { "body": "hello world", "msgtype": "m.text" diff --git a/crates/matrix-sdk-ui/src/timeline/tests/mod.rs b/crates/matrix-sdk-ui/src/timeline/tests/mod.rs index 61aa0ca9f82..2c23569b289 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, + deserialized_responses::TimelineEvent, event_cache::paginator::{PaginableRoom, PaginatorError}, room::{EventWithContextResponse, Messages, MessagesOptions}, send_queue::RoomSendQueueUpdate, @@ -173,7 +173,7 @@ impl TestTimeline { self.controller.items().await.len() } - async fn handle_live_event(&self, event: impl Into) { + async fn handle_live_event(&self, event: impl Into) { let event = event.into(); self.controller .add_events_at( @@ -196,7 +196,7 @@ impl TestTimeline { } async fn handle_back_paginated_event(&self, event: Raw) { - let timeline_event = SyncTimelineEvent::new(event.cast()); + let timeline_event = TimelineEvent::new(event.cast()); self.controller .add_events_at( [timeline_event].into_iter(), @@ -297,7 +297,7 @@ impl PinnedEventsRoom for TestRoomDataProvider { _event_id: &'a EventId, _request_config: Option, _related_event_filters: Option>, - ) -> BoxFuture<'a, Result<(SyncTimelineEvent, Vec), PaginatorError>> { + ) -> BoxFuture<'a, Result<(TimelineEvent, Vec), PaginatorError>> { unimplemented!(); } diff --git a/crates/matrix-sdk-ui/src/timeline/tests/reactions.rs b/crates/matrix-sdk-ui/src/timeline/tests/reactions.rs index cea3ffc1804..9f42e1013b5 100644 --- a/crates/matrix-sdk-ui/src/timeline/tests/reactions.rs +++ b/crates/matrix-sdk-ui/src/timeline/tests/reactions.rs @@ -18,7 +18,7 @@ use assert_matches2::{assert_let, assert_matches}; use eyeball_im::VectorDiff; use futures_core::Stream; use futures_util::{FutureExt as _, StreamExt as _}; -use matrix_sdk::deserialized_responses::SyncTimelineEvent; +use matrix_sdk::deserialized_responses::TimelineEvent; use matrix_sdk_test::{async_test, event_factory::EventFactory, sync_timeline_event, ALICE, BOB}; use ruma::{ event_id, events::AnyMessageLikeEventContent, server_name, uint, EventId, @@ -151,7 +151,7 @@ async fn test_redact_reaction_success() { // When that redaction is confirmed by the server, timeline - .handle_live_event(SyncTimelineEvent::new(sync_timeline_event!({ + .handle_live_event(TimelineEvent::new(sync_timeline_event!({ "sender": *ALICE, "type": "m.room.redaction", "event_id": "$idb", diff --git a/crates/matrix-sdk-ui/src/timeline/tests/shields.rs b/crates/matrix-sdk-ui/src/timeline/tests/shields.rs index c7f50c26731..4dd6cb98573 100644 --- a/crates/matrix-sdk-ui/src/timeline/tests/shields.rs +++ b/crates/matrix-sdk-ui/src/timeline/tests/shields.rs @@ -1,6 +1,6 @@ use assert_matches::assert_matches; use eyeball_im::VectorDiff; -use matrix_sdk_base::deserialized_responses::{ShieldState, ShieldStateCode, SyncTimelineEvent}; +use matrix_sdk_base::deserialized_responses::{ShieldState, ShieldStateCode, TimelineEvent}; use matrix_sdk_test::{async_test, sync_timeline_event, ALICE}; use ruma::{ event_id, @@ -97,7 +97,7 @@ async fn test_local_sent_in_clear_shield() { // When the remote echo comes in. timeline - .handle_live_event(SyncTimelineEvent::new(sync_timeline_event!({ + .handle_live_event(TimelineEvent::new(sync_timeline_event!({ "content": { "body": "Local message", "msgtype": "m.text", diff --git a/crates/matrix-sdk-ui/src/timeline/traits.rs b/crates/matrix-sdk-ui/src/timeline/traits.rs index 912b1fd0bb9..55cae54db5f 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::SyncTimelineEvent, + crypto::types::events::CryptoContextInfo, deserialized_responses::TimelineEvent, event_cache::paginator::PaginableRoom, AsyncTraitDeps, Result, Room, SendOutsideWasm, }; use matrix_sdk_base::{latest_event::LatestEvent, RoomInfo}; @@ -281,24 +281,18 @@ 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 }; @@ -308,7 +302,7 @@ impl Decryptor for (matrix_sdk_base::crypto::OlmMachine, ruma::OwnedRoomId) { { RoomEventDecryptionResult::Decrypted(decrypted) => Ok(decrypted.into()), RoomEventDecryptionResult::UnableToDecrypt(utd_info) => { - Ok(SyncTimelineEvent::new_utd_event(raw.clone(), utd_info)) + Ok(TimelineEvent::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 e59f31128eb..2c575ca819c 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::SyncTimelineEvent; +use matrix_sdk::deserialized_responses::TimelineEvent; use ruma::{events::AnyStateEvent, serde::Raw, EventId, RoomId}; use serde::Serialize; use serde_json::json; @@ -62,9 +62,9 @@ async fn mock_context( room_id: &RoomId, event_id: &EventId, prev_batch_token: Option, - events_before: Vec, - event: SyncTimelineEvent, - events_after: Vec, + events_before: Vec, + event: TimelineEvent, + events_after: Vec, next_batch_token: Option, state: Vec>, ) { @@ -92,7 +92,7 @@ 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/pinned_event.rs b/crates/matrix-sdk-ui/tests/integration/timeline/pinned_event.rs index d7c57621e95..943d6d5f544 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::SyncTimelineEvent; +use matrix_sdk_base::deserialized_responses::TimelineEvent; 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(SyncTimelineEvent::new(event.cast())) + .ok(TimelineEvent::new(event.cast())) .mount() .await; } diff --git a/crates/matrix-sdk/src/event_cache/deduplicator.rs b/crates/matrix-sdk/src/event_cache/deduplicator.rs index 7dbd54eeca0..9714ab5169c 100644 --- a/crates/matrix-sdk/src/event_cache/deduplicator.rs +++ b/crates/matrix-sdk/src/event_cache/deduplicator.rs @@ -155,13 +155,13 @@ pub enum Decoration { #[cfg(test)] mod tests { use assert_matches2::{assert_let, assert_matches}; - use matrix_sdk_base::deserialized_responses::SyncTimelineEvent; + use matrix_sdk_base::deserialized_responses::TimelineEvent; use matrix_sdk_test::event_factory::EventFactory; use ruma::{owned_event_id, user_id, EventId}; use super::*; - fn sync_timeline_event(event_id: &EventId) -> SyncTimelineEvent { + fn sync_timeline_event(event_id: &EventId) -> TimelineEvent { EventFactory::new() .text_msg("") .sender(user_id!("@mnt_io:matrix.org")) diff --git a/crates/matrix-sdk/src/event_cache/mod.rs b/crates/matrix-sdk/src/event_cache/mod.rs index ddc29a85b12..4c4622229ef 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}, + deserialized_responses::{AmbiguityChange, TimelineEvent}, event_cache::store::{EventCacheStoreError, EventCacheStoreLock}, store_locks::LockStoreError, sync::RoomUpdates, @@ -214,7 +214,7 @@ impl EventCache { /// Try to find an event by its ID in all the rooms. // Note: replace this with a select-by-id query when this is implemented in a // store. - pub async fn event(&self, event_id: &EventId) -> Option { + pub async fn event(&self, event_id: &EventId) -> Option { self.inner .all_events .read() @@ -323,7 +323,7 @@ impl EventCache { pub async fn add_initial_events( &self, room_id: &RoomId, - events: Vec, + events: Vec, prev_batch: Option, ) -> Result<()> { // If the event cache's storage has been enabled, do nothing. @@ -352,7 +352,7 @@ impl EventCache { } } -type AllEventsMap = BTreeMap; +type AllEventsMap = BTreeMap; type RelationsMap = BTreeMap>; /// Cache wrapper containing both copies of received events and lists of event @@ -374,7 +374,7 @@ impl AllEventsCache { /// If the event is related to another one, its id is added to the relations /// map. - fn append_related_event(&mut self, event: &SyncTimelineEvent) { + fn append_related_event(&mut self, event: &TimelineEvent) { // Handle and cache events and relations. let Ok(AnySyncTimelineEvent::MessageLike(ev)) = event.raw().deserialize() else { return; @@ -452,7 +452,7 @@ impl AllEventsCache { &self, event_id: &EventId, filter: Option<&[RelationType]>, - ) -> Vec { + ) -> Vec { let mut results = Vec::new(); self.collect_related_events_rec(event_id, filter, &mut results); results @@ -462,7 +462,7 @@ impl AllEventsCache { &self, event_id: &EventId, filter: Option<&[RelationType]>, - results: &mut Vec, + results: &mut Vec, ) { let Some(related_event_ids) = self.relations.get(event_id) else { return; @@ -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. @@ -689,7 +689,7 @@ pub enum RoomEventCacheUpdate { /// The room has received updates for the timeline as _diffs_. UpdateTimelineEvents { /// Diffs to apply to the timeline. - diffs: Vec>, + diffs: Vec>, /// Where the diffs are coming from. origin: EventsOrigin, diff --git a/crates/matrix-sdk/src/event_cache/pagination.rs b/crates/matrix-sdk/src/event_cache/pagination.rs index d3ef7fab3c7..a0ae902a59a 100644 --- a/crates/matrix-sdk/src/event_cache/pagination.rs +++ b/crates/matrix-sdk/src/event_cache/pagination.rs @@ -17,7 +17,7 @@ use std::{future::Future, ops::ControlFlow, sync::Arc, time::Duration}; use eyeball::Subscriber; -use matrix_sdk_base::deserialized_responses::SyncTimelineEvent; +use matrix_sdk_base::deserialized_responses::TimelineEvent; use matrix_sdk_common::linked_chunk::ChunkContent; use tokio::time::timeout; use tracing::{debug, instrument, trace}; @@ -181,7 +181,7 @@ impl RoomPagination { // (backward). The `RoomEvents` API expects the first event to be the oldest. .rev() .cloned() - .map(SyncTimelineEvent::from) + .map(TimelineEvent::from) .collect::>(); let first_event_pos = room_events.events().next().map(|(item_pos, _)| item_pos); diff --git a/crates/matrix-sdk/src/event_cache/paginator.rs b/crates/matrix-sdk/src/event_cache/paginator.rs index e3bd4630184..fa445f3cfdb 100644 --- a/crates/matrix-sdk/src/event_cache/paginator.rs +++ b/crates/matrix-sdk/src/event_cache/paginator.rs @@ -20,9 +20,7 @@ use std::{future::Future, sync::Mutex}; use eyeball::{SharedObservable, Subscriber}; -use matrix_sdk_base::{ - deserialized_responses::SyncTimelineEvent, SendOutsideWasm, SyncOutsideWasm, -}; +use matrix_sdk_base::{deserialized_responses::TimelineEvent, SendOutsideWasm, SyncOutsideWasm}; use ruma::{api::Direction, EventId, OwnedEventId, UInt}; use super::pagination::PaginationToken; @@ -118,7 +116,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? /// @@ -134,7 +132,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, @@ -538,7 +536,7 @@ mod tests { use assert_matches2::assert_let; use futures_core::Future; use futures_util::FutureExt as _; - use matrix_sdk_base::deserialized_responses::SyncTimelineEvent; + use matrix_sdk_base::deserialized_responses::TimelineEvent; 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}; @@ -561,8 +559,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>>, diff --git a/crates/matrix-sdk/src/event_cache/room/mod.rs b/crates/matrix-sdk/src/event_cache/room/mod.rs index 93a5f42802f..c48bcbdf6de 100644 --- a/crates/matrix-sdk/src/event_cache/room/mod.rs +++ b/crates/matrix-sdk/src/event_cache/room/mod.rs @@ -18,7 +18,7 @@ use std::{collections::BTreeMap, fmt, sync::Arc}; use events::Gap; use matrix_sdk_base::{ - deserialized_responses::{AmbiguityChange, SyncTimelineEvent}, + deserialized_responses::{AmbiguityChange, TimelineEvent}, linked_chunk::ChunkContent, sync::{JoinedRoomUpdate, LeftRoomUpdate, Timeline}, }; @@ -77,9 +77,7 @@ impl RoomEventCache { /// Subscribe to this room updates, after getting the initial list of /// events. - pub async fn subscribe( - &self, - ) -> Result<(Vec, Receiver)> { + pub async fn subscribe(&self) -> Result<(Vec, Receiver)> { let state = self.inner.state.read().await; let events = state.events().events().map(|(_position, item)| item.clone()).collect(); @@ -93,7 +91,7 @@ impl RoomEventCache { } /// Try to find an event by id in this room. - pub async fn event(&self, event_id: &EventId) -> Option { + pub async fn event(&self, event_id: &EventId) -> Option { if let Some((room_id, event)) = self.inner.all_events.read().await.events.get(event_id).cloned() { @@ -119,7 +117,7 @@ impl RoomEventCache { &self, event_id: &EventId, filter: Option>, - ) -> Option<(SyncTimelineEvent, Vec)> { + ) -> Option<(TimelineEvent, Vec)> { let cache = self.inner.all_events.read().await; if let Some((_, event)) = cache.events.get(event_id) { let related_events = cache.collect_related_events(event_id, filter.as_deref()); @@ -155,7 +153,7 @@ impl RoomEventCache { // TODO: This doesn't insert the event into the linked chunk. In the future // there'll be no distinction between the linked chunk and the separate // cache. There is a discussion in https://github.com/matrix-org/matrix-rust-sdk/issues/3886. - pub(crate) async fn save_event(&self, event: SyncTimelineEvent) { + pub(crate) async fn save_event(&self, event: TimelineEvent) { if let Some(event_id) = event.event_id() { let mut cache = self.inner.all_events.write().await; @@ -172,7 +170,7 @@ impl RoomEventCache { // TODO: This doesn't insert the event into the linked chunk. In the future // there'll be no distinction between the linked chunk and the separate // cache. There is a discussion in https://github.com/matrix-org/matrix-rust-sdk/issues/3886. - pub(crate) async fn save_events(&self, events: impl IntoIterator) { + pub(crate) async fn save_events(&self, events: impl IntoIterator) { let mut cache = self.inner.all_events.write().await; for event in events { if let Some(event_id) = event.event_id() { @@ -370,7 +368,7 @@ impl RoomEventCacheInner { /// storage, notifying observers. pub(super) async fn replace_all_events_by( &self, - sync_timeline_events: Vec, + sync_timeline_events: Vec, prev_batch: Option, ephemeral_events: Vec>, ambiguity_changes: BTreeMap, @@ -407,7 +405,7 @@ impl RoomEventCacheInner { async fn append_events_locked( &self, state: &mut RoomEventCacheState, - sync_timeline_events: Vec, + sync_timeline_events: Vec, prev_batch: Option, ephemeral_events: Vec>, ambiguity_changes: BTreeMap, @@ -506,7 +504,7 @@ impl RoomEventCacheInner { } /// Create a debug string for a [`ChunkContent`] for an event/gap pair. -fn chunk_debug_string(content: &ChunkContent) -> String { +fn chunk_debug_string(content: &ChunkContent) -> String { match content { ChunkContent::Gap(Gap { prev_token }) => { format!("gap['{prev_token}']") @@ -534,7 +532,7 @@ mod private { use eyeball_im::VectorDiff; use matrix_sdk_base::{ - deserialized_responses::{SyncTimelineEvent, TimelineEventKind}, + deserialized_responses::{TimelineEvent, TimelineEventKind}, event_cache::{ store::{ EventCacheStoreError, EventCacheStoreLock, EventCacheStoreLockGuard, @@ -650,7 +648,7 @@ mod private { let _ = closure(); } - fn strip_relations_from_event(ev: &mut SyncTimelineEvent) { + fn strip_relations_from_event(ev: &mut TimelineEvent) { match &mut ev.kind { TimelineEventKind::Decrypted(decrypted) => { // Remove all information about encryption info for @@ -669,7 +667,7 @@ mod private { } /// Strips the bundled relations from a collection of events. - fn strip_relations_from_events(items: &mut [SyncTimelineEvent]) { + fn strip_relations_from_events(items: &mut [TimelineEvent]) { for ev in items.iter_mut() { Self::strip_relations_from_event(ev); } @@ -755,7 +753,7 @@ mod private { pub async fn with_events_mut O>( &mut self, func: F, - ) -> Result<(O, Vec>), EventCacheError> { + ) -> Result<(O, Vec>), EventCacheError> { let output = func(&mut self.events); self.propagate_changes().await?; let updates_as_vector_diffs = self.events.updates_as_vector_diffs(); @@ -847,7 +845,7 @@ mod tests { store::StoreConfig, sync::{JoinedRoomUpdate, Timeline}, }; - use matrix_sdk_common::deserialized_responses::SyncTimelineEvent; + use matrix_sdk_common::deserialized_responses::TimelineEvent; use matrix_sdk_test::{async_test, event_factory::EventFactory, ALICE, BOB}; use ruma::{ event_id, @@ -1617,8 +1615,8 @@ mod tests { async fn assert_relations( room_id: &RoomId, - original_event: SyncTimelineEvent, - related_event: SyncTimelineEvent, + original_event: TimelineEvent, + related_event: TimelineEvent, event_factory: EventFactory, ) { let client = logged_in_client(None).await; diff --git a/crates/matrix-sdk/src/event_handler/mod.rs b/crates/matrix-sdk/src/event_handler/mod.rs index 4f802210b0c..a8b8d2946ac 100644 --- a/crates/matrix-sdk/src/event_handler/mod.rs +++ b/crates/matrix-sdk/src/event_handler/mod.rs @@ -50,7 +50,7 @@ use eyeball::{SharedObservable, Subscriber}; use futures_core::Stream; use futures_util::stream::{FuturesUnordered, StreamExt}; use matrix_sdk_base::{ - deserialized_responses::{EncryptionInfo, SyncTimelineEvent}, + deserialized_responses::{EncryptionInfo, TimelineEvent}, SendOutsideWasm, SyncOutsideWasm, }; use pin_project_lite::pin_project; @@ -380,7 +380,7 @@ impl Client { pub(crate) async fn handle_sync_timeline_events( &self, room: Option<&Room>, - timeline_events: &[SyncTimelineEvent], + timeline_events: &[TimelineEvent], ) -> serde_json::Result<()> { #[derive(Deserialize)] struct TimelineEventDetails<'a> { diff --git a/crates/matrix-sdk/src/room/edit.rs b/crates/matrix-sdk/src/room/edit.rs index 850e70d3884..33fe5dbeb71 100644 --- a/crates/matrix-sdk/src/room/edit.rs +++ b/crates/matrix-sdk/src/room/edit.rs @@ -16,7 +16,7 @@ use std::future::Future; -use matrix_sdk_base::{deserialized_responses::SyncTimelineEvent, SendOutsideWasm}; +use matrix_sdk_base::{deserialized_responses::TimelineEvent, SendOutsideWasm}; use ruma::{ events::{ poll::unstable_start::{ @@ -129,11 +129,11 @@ trait EventSource { fn get_event( &self, event_id: &EventId, - ) -> impl Future> + SendOutsideWasm; + ) -> impl Future> + SendOutsideWasm; } impl EventSource for &Room { - async fn get_event(&self, event_id: &EventId) -> Result { + async fn get_event(&self, event_id: &EventId) -> Result { match self.event_cache().await { Ok((event_cache, _drop_handles)) => { if let Some(event) = event_cache.event(event_id).await { @@ -359,7 +359,7 @@ mod tests { use std::collections::BTreeMap; use assert_matches2::{assert_let, assert_matches}; - use matrix_sdk_base::deserialized_responses::SyncTimelineEvent; + use matrix_sdk_base::deserialized_responses::TimelineEvent; use matrix_sdk_test::{async_test, event_factory::EventFactory}; use ruma::{ event_id, @@ -378,11 +378,11 @@ mod tests { #[derive(Default)] struct TestEventCache { - events: BTreeMap, + events: BTreeMap, } impl EventSource for TestEventCache { - async fn get_event(&self, event_id: &EventId) -> Result { + async fn get_event(&self, event_id: &EventId) -> Result { Ok(self.events.get(event_id).unwrap().clone()) } } @@ -397,7 +397,7 @@ mod tests { cache.events.insert( event_id.to_owned(), // TODO: use the EventFactory for state events too. - SyncTimelineEvent::new( + TimelineEvent::new( Raw::::from_json_string( json!({ "content": { diff --git a/crates/matrix-sdk/src/room/messages.rs b/crates/matrix-sdk/src/room/messages.rs index 37d2e6b38d4..7c4709feb50 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::SyncTimelineEvent}; +use matrix_sdk_common::{debug::DebugStructExt as _, deserialized_responses::TimelineEvent}; 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 650a8044458..078bf86c8b8 100644 --- a/crates/matrix-sdk/src/room/mod.rs +++ b/crates/matrix-sdk/src/room/mod.rs @@ -48,7 +48,7 @@ use matrix_sdk_base::{ #[cfg(all(feature = "e2e-encryption", not(target_arch = "wasm32")))] use matrix_sdk_common::BoxFuture; use matrix_sdk_common::{ - deserialized_responses::SyncTimelineEvent, + deserialized_responses::TimelineEvent, executor::{spawn, JoinHandle}, timeout::timeout, }; @@ -341,10 +341,10 @@ impl Room { if let Ok(event) = self.decrypt_event(event.cast_ref()).await { event } else { - SyncTimelineEvent::new(event.cast()) + TimelineEvent::new(event.cast()) } } else { - SyncTimelineEvent::new(event.cast()) + TimelineEvent::new(event.cast()) }; response.chunk.push(decrypted_event); } @@ -447,7 +447,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,7 +458,7 @@ impl Room { } } - let mut event = SyncTimelineEvent::new(event.cast()); + let mut event = TimelineEvent::new(event.cast()); event.push_actions = self.event_push_actions(event.raw()).await?; Ok(event) @@ -472,7 +472,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()); @@ -525,7 +525,7 @@ impl Room { // Save the loaded events into the event cache, if it's set up. if let Ok((cache, _handles)) = self.event_cache().await { - let mut events_to_save: Vec = Vec::new(); + let mut events_to_save: Vec = Vec::new(); if let Some(event) = &target_event { events_to_save.push(event.clone().into()); } @@ -1278,14 +1278,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: SyncTimelineEvent = match machine + let mut event: TimelineEvent = match machine .try_decrypt_room_event(event.cast_ref(), self.inner.room_id(), &decryption_settings) .await? { @@ -1295,7 +1295,7 @@ impl Room { .encryption() .backups() .maybe_download_room_key(self.room_id().to_owned(), event.clone()); - SyncTimelineEvent::new_utd_event(event.clone().cast(), utd_info) + TimelineEvent::new_utd_event(event.clone().cast(), utd_info) } }; diff --git a/crates/matrix-sdk/src/sliding_sync/client.rs b/crates/matrix-sdk/src/sliding_sync/client.rs index 2cad1347733..9e3ab60767d 100644 --- a/crates/matrix-sdk/src/sliding_sync/client.rs +++ b/crates/matrix-sdk/src/sliding_sync/client.rs @@ -257,7 +257,7 @@ impl PreviousEventsProvider for SlidingSyncPreviousEventsProvider<'_> { fn for_room( &self, room_id: &ruma::RoomId, - ) -> Vector { + ) -> Vector { self.0.get(room_id).map(|room| room.timeline_queue()).unwrap_or_default() } } diff --git a/crates/matrix-sdk/src/sliding_sync/mod.rs b/crates/matrix-sdk/src/sliding_sync/mod.rs index cfdf45105b4..2256e5c43fb 100644 --- a/crates/matrix-sdk/src/sliding_sync/mod.rs +++ b/crates/matrix-sdk/src/sliding_sync/mod.rs @@ -36,7 +36,7 @@ use async_stream::stream; pub use client::{Version, VersionBuilder}; use futures_core::stream::Stream; pub use matrix_sdk_base::sliding_sync::http; -use matrix_sdk_common::{deserialized_responses::SyncTimelineEvent, executor::spawn, timer}; +use matrix_sdk_common::{deserialized_responses::TimelineEvent, executor::spawn, timer}; use ruma::{ api::{client::error::ErrorKind, OutgoingRequest}, assign, OwnedEventId, OwnedRoomId, RoomId, @@ -345,7 +345,7 @@ impl SlidingSync { if let Some(joined_room) = sync_response.rooms.join.remove(&room_id) { joined_room.timeline.events } else { - room_data.timeline.drain(..).map(SyncTimelineEvent::new).collect() + room_data.timeline.drain(..).map(TimelineEvent::new).collect() }; match rooms_map.get_mut(&room_id) { @@ -1103,7 +1103,7 @@ mod tests { use assert_matches::assert_matches; use event_listener::Listener; use futures_util::{future::join_all, pin_mut, StreamExt}; - use matrix_sdk_common::deserialized_responses::SyncTimelineEvent; + use matrix_sdk_common::deserialized_responses::TimelineEvent; use matrix_sdk_test::async_test; use ruma::{ api::client::error::ErrorKind, assign, owned_room_id, room_id, serde::Raw, uint, @@ -2268,8 +2268,8 @@ mod tests { #[async_test] async fn test_limited_flag_computation() { - let make_event = |event_id: &str| -> SyncTimelineEvent { - SyncTimelineEvent::new( + let make_event = |event_id: &str| -> TimelineEvent { + TimelineEvent::new( Raw::from_json_string( json!({ "event_id": event_id, diff --git a/crates/matrix-sdk/src/sliding_sync/room.rs b/crates/matrix-sdk/src/sliding_sync/room.rs index 92e83f58181..4615fb1d715 100644 --- a/crates/matrix-sdk/src/sliding_sync/room.rs +++ b/crates/matrix-sdk/src/sliding_sync/room.rs @@ -4,7 +4,7 @@ use std::{ }; use eyeball_im::Vector; -use matrix_sdk_base::{deserialized_responses::SyncTimelineEvent, sliding_sync::http}; +use matrix_sdk_base::{deserialized_responses::TimelineEvent, sliding_sync::http}; use ruma::{OwnedRoomId, RoomId}; use serde::{Deserialize, Serialize}; @@ -40,7 +40,7 @@ impl SlidingSyncRoom { pub fn new( room_id: OwnedRoomId, prev_batch: Option, - timeline: Vec, + timeline: Vec, ) -> Self { Self { inner: Arc::new(SlidingSyncRoomInner { @@ -66,14 +66,14 @@ impl SlidingSyncRoom { /// /// Note: This API only exists temporarily, it *will* be removed in the /// future. - pub fn timeline_queue(&self) -> Vector { + pub fn timeline_queue(&self) -> Vector { self.inner.timeline_queue.read().unwrap().clone() } pub(super) fn update( &mut self, room_data: http::response::Room, - timeline_updates: Vec, + timeline_updates: Vec, ) { let http::response::Room { prev_batch, limited, .. } = room_data; @@ -165,7 +165,7 @@ struct SlidingSyncRoomInner { /// /// When persisting the room, this queue is truncated to keep only the last /// N events. - timeline_queue: RwLock>, + timeline_queue: RwLock>, } /// A “frozen” [`SlidingSyncRoom`], i.e. that can be written into, or read from @@ -176,7 +176,7 @@ pub(super) struct FrozenSlidingSyncRoom { #[serde(skip_serializing_if = "Option::is_none")] pub(super) prev_batch: Option, #[serde(rename = "timeline")] - pub(super) timeline_queue: Vector, + pub(super) timeline_queue: Vector, } /// Number of timeline events to keep when [`SlidingSyncRoom`] is saved in the @@ -214,7 +214,7 @@ impl From<&SlidingSyncRoom> for FrozenSlidingSyncRoom { #[cfg(test)] mod tests { use imbl::vector; - use matrix_sdk_common::deserialized_responses::SyncTimelineEvent; + use matrix_sdk_common::deserialized_responses::TimelineEvent; use matrix_sdk_test::async_test; use ruma::{events::room::message::RoomMessageEventContent, room_id, serde::Raw, RoomId}; use serde_json::json; @@ -237,7 +237,7 @@ mod tests { fn new_room_with_timeline( room_id: &RoomId, inner: http::response::Room, - timeline: Vec, + timeline: Vec, ) -> SlidingSyncRoom { SlidingSyncRoom::new(room_id.to_owned(), inner.prev_batch, timeline) } @@ -314,7 +314,7 @@ mod tests { macro_rules! timeline_event { (from $sender:literal with id $event_id:literal at $ts:literal: $message:literal) => { - SyncTimelineEvent::new( + TimelineEvent::new( Raw::new(&json!({ "content": RoomMessageEventContent::text_plain($message), "type": "m.room.message", @@ -605,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![SyncTimelineEvent::new( + timeline_queue: vector![TimelineEvent::new( Raw::new(&json!({ "content": RoomMessageEventContent::text_plain("let it gooo!"), "type": "m.room.message", @@ -657,7 +657,7 @@ mod tests { let max = NUMBER_OF_TIMELINE_EVENTS_TO_KEEP_FOR_THE_CACHE - 1; let timeline_events = (0..=max) .map(|nth| { - SyncTimelineEvent::new( + TimelineEvent::new( Raw::new(&json!({ "content": RoomMessageEventContent::text_plain(format!("message {nth}")), "type": "m.room.message", @@ -694,7 +694,7 @@ mod tests { let max = NUMBER_OF_TIMELINE_EVENTS_TO_KEEP_FOR_THE_CACHE + 2; let timeline_events = (0..=max) .map(|nth| { - SyncTimelineEvent::new( + TimelineEvent::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 44dda8cf1f9..34d232b544e 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::SyncTimelineEvent; +use matrix_sdk_base::deserialized_responses::TimelineEvent; 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: SyncTimelineEvent) -> MatrixMock<'a> { + pub fn ok(self, event: TimelineEvent) -> 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/src/test_utils/mod.rs b/crates/matrix-sdk/src/test_utils/mod.rs index 80865ad2a8d..0b5f28eb2b2 100644 --- a/crates/matrix-sdk/src/test_utils/mod.rs +++ b/crates/matrix-sdk/src/test_utils/mod.rs @@ -3,7 +3,7 @@ #![allow(dead_code)] use assert_matches2::assert_let; -use matrix_sdk_base::{deserialized_responses::SyncTimelineEvent, SessionMeta}; +use matrix_sdk_base::{deserialized_responses::TimelineEvent, SessionMeta}; use ruma::{ api::MatrixVersion, device_id, @@ -24,8 +24,8 @@ use crate::{ /// Checks that an event is a message-like text event with the given text. #[track_caller] -pub fn assert_event_matches_msg>(event: &E, expected: &str) { - let event: SyncTimelineEvent = event.clone().into(); +pub fn assert_event_matches_msg>(event: &E, expected: &str) { + let event: TimelineEvent = event.clone().into(); let event = event.raw().deserialize().unwrap(); assert_let!( AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomMessage(message)) = event diff --git a/crates/matrix-sdk/tests/integration/event_cache.rs b/crates/matrix-sdk/tests/integration/event_cache.rs index a2e2aaf7d44..700c61da77e 100644 --- a/crates/matrix-sdk/tests/integration/event_cache.rs +++ b/crates/matrix-sdk/tests/integration/event_cache.rs @@ -9,7 +9,7 @@ use assert_matches2::assert_let; use eyeball_im::VectorDiff; use matrix_sdk::{ assert_let_timeout, assert_next_matches_with_timeout, - deserialized_responses::SyncTimelineEvent, + deserialized_responses::TimelineEvent, event_cache::{ paginator::PaginatorState, BackPaginationOutcome, EventCacheError, PaginationToken, RoomEventCacheUpdate, TimelineHasBeenResetWhilePaginating, @@ -204,7 +204,7 @@ async fn test_ignored_unignored() { /// Small helper for backpagination tests, to wait for things to stabilize. async fn wait_for_initial_events( - events: Vec, + events: Vec, room_stream: &mut broadcast::Receiver, ) { if events.is_empty() { diff --git a/testing/matrix-sdk-test/src/event_factory.rs b/testing/matrix-sdk-test/src/event_factory.rs index 444e315fe68..9b6f3e59a07 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, UnableToDecryptInfo, UnableToDecryptReason, + TimelineEvent, UnableToDecryptInfo, UnableToDecryptReason, }; use ruma::{ events::{ @@ -254,19 +254,19 @@ where Raw::new(&self.construct_json(false)).unwrap().cast() } - pub fn into_sync(self) -> SyncTimelineEvent { - SyncTimelineEvent::new(self.into_raw_sync()) + pub fn into_sync(self) -> TimelineEvent { + TimelineEvent::new(self.into_raw_sync()) } } impl EventBuilder { - /// Turn this event into a SyncTimelineEvent representing a decryption + /// Turn this event into a [`TimelineEvent`] representing a decryption /// failure - pub fn into_utd_sync_timeline_event(self) -> SyncTimelineEvent { + pub fn into_utd_sync_timeline_event(self) -> TimelineEvent { let session_id = as_variant!(&self.content.scheme, EncryptedEventScheme::MegolmV1AesSha2) .map(|content| content.session_id.clone()); - SyncTimelineEvent::new_utd_event( + TimelineEvent::new_utd_event( self.into(), UnableToDecryptInfo { session_id, @@ -354,7 +354,7 @@ where } } -impl From> for SyncTimelineEvent +impl From> for TimelineEvent where E::EventType: Serialize, { From d2f1fa2c61397304230761e9ec416e605655e214 Mon Sep 17 00:00:00 2001 From: Benjamin Bouvier Date: Tue, 21 Jan 2025 15:48:45 +0100 Subject: [PATCH 4/6] docs: add changelog entries --- crates/matrix-sdk-base/CHANGELOG.md | 4 ++++ crates/matrix-sdk-common/CHANGELOG.md | 5 +++++ crates/matrix-sdk/CHANGELOG.md | 5 +++++ 3 files changed, 14 insertions(+) diff --git a/crates/matrix-sdk-base/CHANGELOG.md b/crates/matrix-sdk-base/CHANGELOG.md index 6716adf5e44..bb72c478e5a 100644 --- a/crates/matrix-sdk-base/CHANGELOG.md +++ b/crates/matrix-sdk-base/CHANGELOG.md @@ -11,6 +11,10 @@ All notable changes to this project will be documented in this file. - Replaced `Room::compute_display_name` with the reintroduced `Room::display_name()`. The new method computes a display name, or return a cached value from the previous successful computation. If you need a sync variant, consider using `Room::cached_display_name()`. +- [**breaking**]: The reexported types `SyncTimelineEvent` and `TimelineEvent` have been fused into a single type + `TimelineEvent`, and its field `push_actions` has been made `Option`al (it is set to `None` when + we couldn't compute the push actions, because we lacked some information). + ([#4568](https://github.com/matrix-org/matrix-rust-sdk/pull/4568)) ### Features diff --git a/crates/matrix-sdk-common/CHANGELOG.md b/crates/matrix-sdk-common/CHANGELOG.md index 7eedc0ab0b7..0af184d859d 100644 --- a/crates/matrix-sdk-common/CHANGELOG.md +++ b/crates/matrix-sdk-common/CHANGELOG.md @@ -6,6 +6,11 @@ All notable changes to this project will be documented in this file. ## [Unreleased] - ReleaseDate +- [**breaking**]: `SyncTimelineEvent` and `TimelineEvent` have been fused into a single type + `TimelineEvent`, and its field `push_actions` has been made `Option`al (it is set to `None` when + we couldn't compute the push actions, because we lacked some information). + ([#4568](https://github.com/matrix-org/matrix-rust-sdk/pull/4568)) + ## [0.9.0] - 2024-12-18 ### Bug Fixes diff --git a/crates/matrix-sdk/CHANGELOG.md b/crates/matrix-sdk/CHANGELOG.md index 84257ac97e4..c4d9cad781a 100644 --- a/crates/matrix-sdk/CHANGELOG.md +++ b/crates/matrix-sdk/CHANGELOG.md @@ -28,6 +28,11 @@ All notable changes to this project will be documented in this file. ### Refactor +- [**breaking**]: The reexported types `SyncTimelineEvent` and `TimelineEvent` have been fused into a single type + `TimelineEvent`, and its field `push_actions` has been made `Option`al (it is set to `None` when + we couldn't compute the push actions, because we lacked some information). + ([#4568](https://github.com/matrix-org/matrix-rust-sdk/pull/4568)) + - [**breaking**] Move the optional `RequestConfig` argument of the `Client::send()` method to the `with_request_config()` builder method. You should call `Client::send(request).with_request_config(request_config).await` From 6377e25780937c493ad511dbd20b7c57720be6a0 Mon Sep 17 00:00:00 2001 From: Benjamin Bouvier Date: Tue, 21 Jan 2025 15:56:04 +0100 Subject: [PATCH 5/6] test: rename `EventFactory::into_sync` to `into_event` --- crates/matrix-sdk-base/src/read_receipts.rs | 37 ++++++++++--------- .../src/timeline/event_item/mod.rs | 4 +- .../matrix-sdk-ui/src/timeline/tests/basic.rs | 14 +++---- .../matrix-sdk-ui/src/timeline/tests/echo.rs | 2 +- .../src/timeline/tests/reactions.rs | 4 +- .../tests/integration/timeline/focus_event.rs | 24 ++++++------ .../src/event_cache/deduplicator.rs | 2 +- .../matrix-sdk/src/event_cache/pagination.rs | 9 +++-- .../matrix-sdk/src/event_cache/paginator.rs | 18 ++++----- .../matrix-sdk/src/event_cache/room/events.rs | 2 +- crates/matrix-sdk/src/event_cache/room/mod.rs | 20 +++++----- crates/matrix-sdk/src/room/edit.rs | 4 +- .../tests/integration/room/joined.rs | 2 +- .../tests/integration/send_queue.rs | 6 +-- testing/matrix-sdk-test/src/event_factory.rs | 4 +- 15 files changed, 77 insertions(+), 75 deletions(-) diff --git a/crates/matrix-sdk-base/src/read_receipts.rs b/crates/matrix-sdk-base/src/read_receipts.rs index 171fd1ad35a..ee4282e9db1 100644 --- a/crates/matrix-sdk-base/src/read_receipts.rs +++ b/crates/matrix-sdk-base/src/read_receipts.rs @@ -729,7 +729,7 @@ mod tests { .text_msg("A") .sender(user_id) .event_id(event_id!("$ida")) - .into_sync(); + .into_event(); ev.push_actions = Some(push_actions); ev } @@ -919,8 +919,8 @@ mod tests { let mut previous_events = Vector::new(); let f = EventFactory::new(); - let ev1 = f.text_msg("A").sender(other_user_id).event_id(receipt_event_id).into_sync(); - let ev2 = f.text_msg("A").sender(other_user_id).event_id(event_id!("$2")).into_sync(); + let ev1 = f.text_msg("A").sender(other_user_id).event_id(receipt_event_id).into_event(); + let ev2 = f.text_msg("A").sender(other_user_id).event_id(event_id!("$2")).into_event(); let receipt_event = f .read_receipts() @@ -944,7 +944,8 @@ mod tests { previous_events.push_back(ev1); previous_events.push_back(ev2); - let new_event = f.text_msg("A").sender(other_user_id).event_id(event_id!("$3")).into_sync(); + let new_event = + f.text_msg("A").sender(other_user_id).event_id(event_id!("$3")).into_event(); compute_unread_counts( user_id, room_id, @@ -1134,7 +1135,7 @@ mod tests { let events = make_test_events(uid); // An event with no id. - let ev6 = EventFactory::new().text_msg("yolo").sender(uid).no_event_id().into_sync(); + let ev6 = EventFactory::new().text_msg("yolo").sender(uid).no_event_id().into_event(); let index = ReceiptSelector::create_sync_index(events.iter().chain(&[ev6])); @@ -1201,8 +1202,8 @@ mod tests { fn test_receipt_selector_handle_pending_receipts_noop() { let sender = user_id!("@bob:example.org"); let f = EventFactory::new().sender(sender); - let ev1 = f.text_msg("yo").event_id(event_id!("$1")).into_sync(); - let ev2 = f.text_msg("well?").event_id(event_id!("$2")).into_sync(); + let ev1 = f.text_msg("yo").event_id(event_id!("$1")).into_event(); + let ev2 = f.text_msg("well?").event_id(event_id!("$2")).into_event(); let events: Vector<_> = vec![ev1, ev2].into(); { @@ -1237,8 +1238,8 @@ mod tests { fn test_receipt_selector_handle_pending_receipts_doesnt_match_known_events() { let sender = user_id!("@bob:example.org"); let f = EventFactory::new().sender(sender); - let ev1 = f.text_msg("yo").event_id(event_id!("$1")).into_sync(); - let ev2 = f.text_msg("well?").event_id(event_id!("$2")).into_sync(); + let ev1 = f.text_msg("yo").event_id(event_id!("$1")).into_event(); + let ev2 = f.text_msg("well?").event_id(event_id!("$2")).into_event(); let events: Vector<_> = vec![ev1, ev2].into(); { @@ -1274,8 +1275,8 @@ mod tests { fn test_receipt_selector_handle_pending_receipts_matches_known_events_no_initial() { let sender = user_id!("@bob:example.org"); let f = EventFactory::new().sender(sender); - let ev1 = f.text_msg("yo").event_id(event_id!("$1")).into_sync(); - let ev2 = f.text_msg("well?").event_id(event_id!("$2")).into_sync(); + let ev1 = f.text_msg("yo").event_id(event_id!("$1")).into_event(); + let ev2 = f.text_msg("well?").event_id(event_id!("$2")).into_event(); let events: Vector<_> = vec![ev1, ev2].into(); { @@ -1316,8 +1317,8 @@ mod tests { fn test_receipt_selector_handle_pending_receipts_matches_known_events_with_initial() { let sender = user_id!("@bob:example.org"); let f = EventFactory::new().sender(sender); - let ev1 = f.text_msg("yo").event_id(event_id!("$1")).into_sync(); - let ev2 = f.text_msg("well?").event_id(event_id!("$2")).into_sync(); + let ev1 = f.text_msg("yo").event_id(event_id!("$1")).into_event(); + let ev2 = f.text_msg("well?").event_id(event_id!("$2")).into_event(); let events: Vector<_> = vec![ev1, ev2].into(); { @@ -1495,10 +1496,10 @@ mod tests { f.text_msg("A mulatto, an albino") .sender(&myself) .event_id(event_id!("$6")) - .into_sync(), + .into_event(), ); events.push_back( - f.text_msg("A mosquito, my libido").sender(bob).event_id(event_id!("$7")).into_sync(), + f.text_msg("A mosquito, my libido").sender(bob).event_id(event_id!("$7")).into_event(), ); let mut selector = ReceiptSelector::new(&events, None); @@ -1524,15 +1525,15 @@ mod tests { f.text_msg("A mulatto, an albino") .sender(user_id) .event_id(event_id!("$6")) - .into_sync(), + .into_event(), ); // And others by Bob, events.push_back( - f.text_msg("A mosquito, my libido").sender(bob).event_id(event_id!("$7")).into_sync(), + f.text_msg("A mosquito, my libido").sender(bob).event_id(event_id!("$7")).into_event(), ); events.push_back( - f.text_msg("A denial, a denial").sender(bob).event_id(event_id!("$8")).into_sync(), + f.text_msg("A denial, a denial").sender(bob).event_id(event_id!("$8")).into_event(), ); let events: Vec<_> = events.into_iter().collect(); diff --git a/crates/matrix-sdk-ui/src/timeline/event_item/mod.rs b/crates/matrix-sdk-ui/src/timeline/event_item/mod.rs index a31ac8dbb84..1284fdf2b90 100644 --- a/crates/matrix-sdk-ui/src/timeline/event_item/mod.rs +++ b/crates/matrix-sdk-ui/src/timeline/event_item/mod.rs @@ -894,7 +894,7 @@ mod tests { .event_id(original_event_id) .bundled_relations(relations) .server_ts(42) - .into_sync(); + .into_event(); let client = logged_in_client(None).await; @@ -950,7 +950,7 @@ mod tests { .event_id(original_event_id) .bundled_relations(relations) .sender(user_id) - .into_sync(); + .into_event(); let client = logged_in_client(None).await; diff --git a/crates/matrix-sdk-ui/src/timeline/tests/basic.rs b/crates/matrix-sdk-ui/src/timeline/tests/basic.rs index 43126c02342..523835056c8 100644 --- a/crates/matrix-sdk-ui/src/timeline/tests/basic.rs +++ b/crates/matrix-sdk-ui/src/timeline/tests/basic.rs @@ -89,7 +89,7 @@ async fn test_replace_with_initial_events_and_read_marker() { .with_settings(TimelineSettings { track_read_receipts: true, ..Default::default() }); let f = &timeline.factory; - let ev = f.text_msg("hey").sender(*ALICE).into_sync(); + let ev = f.text_msg("hey").sender(*ALICE).into_event(); timeline .controller @@ -104,7 +104,7 @@ async fn test_replace_with_initial_events_and_read_marker() { assert!(items[0].is_date_divider()); assert_eq!(items[1].as_event().unwrap().content().as_message().unwrap().body(), "hey"); - let ev = f.text_msg("yo").sender(*BOB).into_sync(); + let ev = f.text_msg("yo").sender(*BOB).into_event(); timeline .controller .replace_with_initial_remote_events([ev].into_iter(), RemoteEventOrigin::Sync) @@ -276,9 +276,9 @@ async fn test_internal_id_prefix() { let timeline = TestTimeline::with_internal_id_prefix("le_prefix_".to_owned()); let f = &timeline.factory; - let ev_a = f.text_msg("A").sender(*ALICE).into_sync(); - let ev_b = f.text_msg("B").sender(*BOB).into_sync(); - let ev_c = f.text_msg("C").sender(*CAROL).into_sync(); + let ev_a = f.text_msg("A").sender(*ALICE).into_event(); + let ev_b = f.text_msg("B").sender(*BOB).into_event(); + let ev_c = f.text_msg("C").sender(*CAROL).into_event(); timeline .controller @@ -445,7 +445,7 @@ async fn test_replace_with_initial_events_when_batched() { .with_settings(TimelineSettings::default()); let f = &timeline.factory; - let ev = f.text_msg("hey").sender(*ALICE).into_sync(); + let ev = f.text_msg("hey").sender(*ALICE).into_event(); timeline .controller @@ -460,7 +460,7 @@ async fn test_replace_with_initial_events_when_batched() { assert!(items[0].is_date_divider()); assert_eq!(items[1].as_event().unwrap().content().as_message().unwrap().body(), "hey"); - let ev = f.text_msg("yo").sender(*BOB).into_sync(); + let ev = f.text_msg("yo").sender(*BOB).into_event(); timeline .controller .replace_with_initial_remote_events([ev].into_iter(), RemoteEventOrigin::Sync) diff --git a/crates/matrix-sdk-ui/src/timeline/tests/echo.rs b/crates/matrix-sdk-ui/src/timeline/tests/echo.rs index f5a85de4495..8d097f7d856 100644 --- a/crates/matrix-sdk-ui/src/timeline/tests/echo.rs +++ b/crates/matrix-sdk-ui/src/timeline/tests/echo.rs @@ -251,7 +251,7 @@ async fn test_no_read_marker_with_local_echo() { .sender(user_id!("@a:b.c")) .event_id(event_id) .server_ts(MilliSecondsSinceUnixEpoch::now()) - .into_sync()] + .into_event()] .into_iter(), RemoteEventOrigin::Sync, ) diff --git a/crates/matrix-sdk-ui/src/timeline/tests/reactions.rs b/crates/matrix-sdk-ui/src/timeline/tests/reactions.rs index 9f42e1013b5..78ca0d69b5f 100644 --- a/crates/matrix-sdk-ui/src/timeline/tests/reactions.rs +++ b/crates/matrix-sdk-ui/src/timeline/tests/reactions.rs @@ -198,9 +198,9 @@ async fn test_initial_reaction_timestamp_is_stored() { // Reaction comes first. f.reaction(&message_event_id, REACTION_KEY) .server_ts(reaction_timestamp) - .into_sync(), + .into_event(), // Event comes next. - f.text_msg("A").event_id(&message_event_id).into_sync(), + f.text_msg("A").event_id(&message_event_id).into_event(), ] .into_iter(), TimelineNewItemPosition::End { origin: RemoteEventOrigin::Sync }, 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 ee7a3b3e6dd..47569fa5c62 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_sync(), - f.text_msg("and got so far").sender(*ALICE).into_sync(), + f.text_msg("i tried so hard").sender(*ALICE).into_event(), + f.text_msg("and got so far").sender(*ALICE).into_event(), ], - f.text_msg("in the end").event_id(target_event).sender(*BOB).into_sync(), + f.text_msg("in the end").event_id(target_event).sender(*BOB).into_event(), vec![ - f.text_msg("it doesn't even").sender(*ALICE).into_sync(), - f.text_msg("matter").sender(*ALICE).into_sync(), + f.text_msg("it doesn't even").sender(*ALICE).into_event(), + f.text_msg("matter").sender(*ALICE).into_event(), ], 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_sync(), - f.text_msg("I kept everything inside").sender(*BOB).into_sync(), + f.text_msg("And even though I tried, it all fell apart").sender(*BOB).into_event(), + f.text_msg("I kept everything inside").sender(*BOB).into_event(), ], 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_sync(), - f.text_msg("But in the end, it doesn't event matter").sender(*BOB).into_sync(), + f.text_msg("I had to fall, to lose it all").sender(*BOB).into_event(), + f.text_msg("But in the end, it doesn't event matter").sender(*BOB).into_event(), ], 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_sync(), + f.text_msg("yolo").event_id(target_event).sender(*BOB).into_event(), 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_sync(), + f.text_msg("yolo").event_id(target_event).sender(*BOB).into_event(), 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_sync(), + f.text_msg("yolo").event_id(target_event).sender(*BOB).into_event(), vec![], None, vec![], diff --git a/crates/matrix-sdk/src/event_cache/deduplicator.rs b/crates/matrix-sdk/src/event_cache/deduplicator.rs index 9714ab5169c..d84807f37da 100644 --- a/crates/matrix-sdk/src/event_cache/deduplicator.rs +++ b/crates/matrix-sdk/src/event_cache/deduplicator.rs @@ -166,7 +166,7 @@ mod tests { .text_msg("") .sender(user_id!("@mnt_io:matrix.org")) .event_id(event_id) - .into_sync() + .into_event() } #[test] diff --git a/crates/matrix-sdk/src/event_cache/pagination.rs b/crates/matrix-sdk/src/event_cache/pagination.rs index a0ae902a59a..325e1e7ff2b 100644 --- a/crates/matrix-sdk/src/event_cache/pagination.rs +++ b/crates/matrix-sdk/src/event_cache/pagination.rs @@ -453,8 +453,9 @@ mod tests { .write() .await .with_events_mut(|events| { - events - .push_events([f.text_msg("this is the start of the timeline").into_sync()]); + events.push_events([f + .text_msg("this is the start of the timeline") + .into_event()]); }) .await .unwrap(); @@ -498,7 +499,7 @@ mod tests { .with_events_mut(|events| { events.push_events([f .text_msg("this is the start of the timeline") - .into_sync()]); + .into_event()]); }) .await .unwrap(); @@ -542,7 +543,7 @@ mod tests { .text_msg("yolo") .sender(user_id!("@b:z.h")) .event_id(event_id!("$ida")) - .into_sync()]); + .into_event()]); }) .await .unwrap(); diff --git a/crates/matrix-sdk/src/event_cache/paginator.rs b/crates/matrix-sdk/src/event_cache/paginator.rs index fa445f3cfdb..599faf19c3c 100644 --- a/crates/matrix-sdk/src/event_cache/paginator.rs +++ b/crates/matrix-sdk/src/event_cache/paginator.rs @@ -609,7 +609,7 @@ mod tests { .event_factory .text_msg(self.target_event_text.lock().await.clone()) .event_id(event_id) - .into_sync(); + .into_event(); // 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,10 +707,10 @@ mod tests { *room.target_event_text.lock().await = "fetch_from".to_owned(); *room.prev_events.lock().await = (0..10) .rev() - .map(|i| event_factory.text_msg(format!("before-{i}")).into_sync()) + .map(|i| event_factory.text_msg(format!("before-{i}")).into_event()) .collect(); *room.next_events.lock().await = - (0..10).map(|i| event_factory.text_msg(format!("after-{i}")).into_sync()).collect(); + (0..10).map(|i| event_factory.text_msg(format!("after-{i}")).into_event()).collect(); // When I call `Paginator::start_from`, it works, let paginator = Arc::new(Paginator::new(room.clone())); @@ -747,7 +747,7 @@ mod tests { *room.target_event_text.lock().await = "fetch_from".to_owned(); *room.prev_events.lock().await = - (0..100).rev().map(|i| event_factory.text_msg(format!("ev{i}")).into_sync()).collect(); + (0..100).rev().map(|i| event_factory.text_msg(format!("ev{i}")).into_event()).collect(); // When I call `Paginator::start_from`, it works, let paginator = Arc::new(Paginator::new(room.clone())); @@ -800,7 +800,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_sync()]; + *room.prev_events.lock().await = vec![event_factory.text_msg("previous").into_event()]; *room.prev_batch_token.lock().await = Some("prev2".to_owned()); // When I backpaginate, I get the events I expect. @@ -813,7 +813,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_sync()]; + *room.prev_events.lock().await = vec![event_factory.text_msg("oldest").into_event()]; *room.prev_batch_token.lock().await = None; let prev = paginator @@ -864,7 +864,7 @@ mod tests { // Preparing data for the next back-pagination. *room.prev_events.lock().await = (0..100) .rev() - .map(|i| event_factory.text_msg(format!("prev{i}")).into_sync()) + .map(|i| event_factory.text_msg(format!("prev{i}")).into_event()) .collect(); *room.prev_batch_token.lock().await = None; @@ -914,7 +914,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_sync()]; + *room.next_events.lock().await = vec![event_factory.text_msg("next").into_event()]; *room.next_batch_token.lock().await = Some("next2".to_owned()); // When I forward-paginate, I get the events I expect. @@ -927,7 +927,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_sync()]; + *room.next_events.lock().await = vec![event_factory.text_msg("latest").into_event()]; *room.next_batch_token.lock().await = None; let next = paginator diff --git a/crates/matrix-sdk/src/event_cache/room/events.rs b/crates/matrix-sdk/src/event_cache/room/events.rs index 142594ecb7a..1b3a6cec50b 100644 --- a/crates/matrix-sdk/src/event_cache/room/events.rs +++ b/crates/matrix-sdk/src/event_cache/room/events.rs @@ -557,7 +557,7 @@ mod tests { .text_msg("") .sender(user_id!("@mnt_io:matrix.org")) .event_id(&event_id) - .into_sync(); + .into_event(); (event_id, event) } diff --git a/crates/matrix-sdk/src/event_cache/room/mod.rs b/crates/matrix-sdk/src/event_cache/room/mod.rs index c48bcbdf6de..3471f4a57d9 100644 --- a/crates/matrix-sdk/src/event_cache/room/mod.rs +++ b/crates/matrix-sdk/src/event_cache/room/mod.rs @@ -805,8 +805,8 @@ mod private { content: ChunkContent::Items(vec![ f.text_msg("hey") .event_id(event_id!("$123456789101112131415617181920")) - .into_sync(), - f.text_msg("you").event_id(event_id!("$2")).into_sync(), + .into_event(), + f.text_msg("you").event_id(event_id!("$2")).into_event(), ]), identifier: CId::new(1), previous: Some(CId::new(0)), @@ -1125,7 +1125,7 @@ mod tests { let timeline = Timeline { limited: true, prev_batch: Some("raclette".to_owned()), - events: vec![f.text_msg("hey yo").sender(*ALICE).into_sync()], + events: vec![f.text_msg("hey yo").sender(*ALICE).into_event()], }; room_event_cache @@ -1197,7 +1197,7 @@ mod tests { let mut relations = BundledMessageLikeRelations::new(); relations.replace = Some(Box::new(f.text_msg("Hello, Kind Sir").sender(*ALICE).into_raw_sync())); - let ev = f.text_msg("hey yo").sender(*ALICE).bundled_relations(relations).into_sync(); + let ev = f.text_msg("hey yo").sender(*ALICE).bundled_relations(relations).into_event(); let timeline = Timeline { limited: false, prev_batch: None, events: vec![ev] }; @@ -1261,8 +1261,8 @@ mod tests { let event_id1 = event_id!("$1"); let event_id2 = event_id!("$2"); - let ev1 = f.text_msg("hello world").sender(*ALICE).event_id(event_id1).into_sync(); - let ev2 = f.text_msg("how's it going").sender(*BOB).event_id(event_id2).into_sync(); + let ev1 = f.text_msg("hello world").sender(*ALICE).event_id(event_id1).into_event(); + let ev2 = f.text_msg("how's it going").sender(*BOB).event_id(event_id2).into_event(); // Prefill the store with some data. event_cache_store @@ -1372,8 +1372,8 @@ mod tests { let event_id1 = event_id!("$1"); let event_id2 = event_id!("$2"); - let ev1 = f.text_msg("hello world").sender(*ALICE).event_id(event_id1).into_sync(); - let ev2 = f.text_msg("how's it going").sender(*BOB).event_id(event_id2).into_sync(); + let ev1 = f.text_msg("hello world").sender(*ALICE).event_id(event_id1).into_event(); + let ev2 = f.text_msg("how's it going").sender(*BOB).event_id(event_id2).into_event(); // Prefill the store with some data. event_cache_store @@ -1547,7 +1547,7 @@ mod tests { timeline: Timeline { limited: true, prev_batch: Some("raclette".to_owned()), - events: vec![f.text_msg("hey yo").into_sync()], + events: vec![f.text_msg("hey yo").into_event()], }, ..Default::default() }, @@ -1583,7 +1583,7 @@ mod tests { timeline: Timeline { limited: false, prev_batch: Some("fondue".to_owned()), - events: vec![f.text_msg("sup").into_sync()], + events: vec![f.text_msg("sup").into_event()], }, ..Default::default() }, diff --git a/crates/matrix-sdk/src/room/edit.rs b/crates/matrix-sdk/src/room/edit.rs index 33fe5dbeb71..0b3844afee8 100644 --- a/crates/matrix-sdk/src/room/edit.rs +++ b/crates/matrix-sdk/src/room/edit.rs @@ -589,7 +589,7 @@ mod tests { .caption(Some("caption".to_owned()), None) .event_id(event_id) .sender(own_user_id) - .into_sync(); + .into_event(); { // Sanity checks. @@ -648,7 +648,7 @@ mod tests { .image(filename.to_owned(), owned_mxc_uri!("mxc://sdk.rs/rickroll")) .event_id(event_id) .sender(own_user_id) - .into_sync(); + .into_event(); { // Sanity checks. diff --git a/crates/matrix-sdk/tests/integration/room/joined.rs b/crates/matrix-sdk/tests/integration/room/joined.rs index b2db9fd1484..a5511446421 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_sync()) + .ok(f.text_msg("hi").event_id(event_id).sender(&user_id).room(room_id).into_event()) .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 ceb64e419d3..39244873691 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_sync()) + .into_event()) .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_sync()) + .into_event()) .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_sync()) + .into_event()) .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 9b6f3e59a07..61ea252e059 100644 --- a/testing/matrix-sdk-test/src/event_factory.rs +++ b/testing/matrix-sdk-test/src/event_factory.rs @@ -254,7 +254,7 @@ where Raw::new(&self.construct_json(false)).unwrap().cast() } - pub fn into_sync(self) -> TimelineEvent { + pub fn into_event(self) -> TimelineEvent { TimelineEvent::new(self.into_raw_sync()) } } @@ -359,7 +359,7 @@ where E::EventType: Serialize, { fn from(val: EventBuilder) -> Self { - val.into_sync() + val.into_event() } } From a66fa241da2449295910a55e24bcb077515ea076 Mon Sep 17 00:00:00 2001 From: Benjamin Bouvier Date: Tue, 21 Jan 2025 16:09:34 +0100 Subject: [PATCH 6/6] refactor: send respects to multiple automated lints and checks --- .../src/deserialized_responses.rs | 2 ++ .../matrix-sdk-ui/src/timeline/controller/state.rs | 4 ++-- .../src/timeline/pinned_events_loader.rs | 2 +- crates/matrix-sdk/src/room/mod.rs | 14 +++++++++----- crates/matrix-sdk/src/sliding_sync/room.rs | 7 ++----- 5 files changed, 16 insertions(+), 13 deletions(-) diff --git a/crates/matrix-sdk-common/src/deserialized_responses.rs b/crates/matrix-sdk-common/src/deserialized_responses.rs index 54366b475fd..0a25b539374 100644 --- a/crates/matrix-sdk-common/src/deserialized_responses.rs +++ b/crates/matrix-sdk-common/src/deserialized_responses.rs @@ -14,6 +14,8 @@ use std::{collections::BTreeMap, fmt}; +#[cfg(doc)] +use ruma::events::AnyTimelineEvent; use ruma::{ events::{AnyMessageLikeEvent, AnySyncTimelineEvent}, push::Action, diff --git a/crates/matrix-sdk-ui/src/timeline/controller/state.rs b/crates/matrix-sdk-ui/src/timeline/controller/state.rs index 18fa85cbe05..75bd8512f81 100644 --- a/crates/matrix-sdk-ui/src/timeline/controller/state.rs +++ b/crates/matrix-sdk-ui/src/timeline/controller/state.rs @@ -279,7 +279,7 @@ impl TimelineState { let handle_one_res = txn .handle_remote_event( - event.into(), + event, TimelineItemPosition::UpdateAt { timeline_item_index: idx }, room_data_provider, settings, @@ -759,7 +759,7 @@ impl TimelineStateTransaction<'_> { }, is_highlighted: push_actions .as_ref() - .map_or(false, |actions| actions.iter().any(Action::is_highlight)), + .is_some_and(|actions| actions.iter().any(Action::is_highlight)), flow: Flow::Remote { event_id: event_id.clone(), raw_event: raw, diff --git a/crates/matrix-sdk-ui/src/timeline/pinned_events_loader.rs b/crates/matrix-sdk-ui/src/timeline/pinned_events_loader.rs index 53b8444119e..28a9ed9a772 100644 --- a/crates/matrix-sdk-ui/src/timeline/pinned_events_loader.rs +++ b/crates/matrix-sdk-ui/src/timeline/pinned_events_loader.rs @@ -163,7 +163,7 @@ impl PinnedEventsRoom for Room { debug!("Loading pinned event {event_id} from HS"); self.event(event_id, request_config) .await - .map(|e| (e.into(), Vec::new())) + .map(|e| (e, Vec::new())) .map_err(|err| PaginatorError::SdkError(Box::new(err))) }) } diff --git a/crates/matrix-sdk/src/room/mod.rs b/crates/matrix-sdk/src/room/mod.rs index 078bf86c8b8..c68d3c5e25e 100644 --- a/crates/matrix-sdk/src/room/mod.rs +++ b/crates/matrix-sdk/src/room/mod.rs @@ -326,7 +326,11 @@ impl Room { start: http_response.start, end: http_response.end, #[cfg(not(feature = "e2e-encryption"))] - chunk: http_response.chunk.into_iter().map(TimelineEvent::new).collect(), + chunk: http_response + .chunk + .into_iter() + .map(|raw| TimelineEvent::new(raw.cast())) + .collect(), #[cfg(feature = "e2e-encryption")] chunk: Vec::with_capacity(http_response.chunk.len()), state: http_response.state, @@ -481,7 +485,7 @@ impl Room { // Save the event into the event cache, if it's set up. if let Ok((cache, _handles)) = self.event_cache().await { - cache.save_event(event.clone().into()).await; + cache.save_event(event.clone()).await; } Ok(event) @@ -527,15 +531,15 @@ impl Room { if let Ok((cache, _handles)) = self.event_cache().await { let mut events_to_save: Vec = Vec::new(); if let Some(event) = &target_event { - events_to_save.push(event.clone().into()); + events_to_save.push(event.clone()); } for event in &events_before { - events_to_save.push(event.clone().into()); + events_to_save.push(event.clone()); } for event in &events_after { - events_to_save.push(event.clone().into()); + events_to_save.push(event.clone()); } cache.save_events(events_to_save).await; diff --git a/crates/matrix-sdk/src/sliding_sync/room.rs b/crates/matrix-sdk/src/sliding_sync/room.rs index 4615fb1d715..49ce04a0fe7 100644 --- a/crates/matrix-sdk/src/sliding_sync/room.rs +++ b/crates/matrix-sdk/src/sliding_sync/room.rs @@ -325,7 +325,7 @@ mod tests { })) .unwrap() .cast() - ).into() + ) }; } @@ -616,8 +616,7 @@ mod tests { })) .unwrap() .cast(), - ) - .into()], + )], }; let serialized = serde_json::to_value(&frozen_room).unwrap(); @@ -669,7 +668,6 @@ mod tests { .unwrap() .cast(), ) - .into() }) .collect::>(); @@ -706,7 +704,6 @@ mod tests { .unwrap() .cast(), ) - .into() }) .collect::>();