Skip to content

Commit

Permalink
common: make SyncTimelineEvent fields private
Browse files Browse the repository at this point in the history
... and add accessors instead.
  • Loading branch information
richvdh committed Oct 4, 2024
1 parent d9b6ab9 commit a13f018
Show file tree
Hide file tree
Showing 17 changed files with 131 additions and 62 deletions.
18 changes: 9 additions & 9 deletions crates/matrix-sdk-base/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ impl BaseClient {
let event: SyncTimelineEvent =
olm.decrypt_room_event(event.cast_ref(), room_id, &decryption_settings).await?.into();

if let Ok(AnySyncTimelineEvent::MessageLike(e)) = event.event.deserialize() {
if let Ok(AnySyncTimelineEvent::MessageLike(e)) = event.event().deserialize() {
match &e {
AnySyncMessageLikeEvent::RoomMessage(SyncMessageLikeEvent::Original(
original_event,
Expand Down Expand Up @@ -398,7 +398,7 @@ impl BaseClient {
for event in events {
let mut event: SyncTimelineEvent = event.into();

match event.event.deserialize() {
match event.event().deserialize() {
Ok(e) => {
#[allow(clippy::single_match)]
match &e {
Expand Down Expand Up @@ -432,7 +432,7 @@ impl BaseClient {
}
}

let raw_event: Raw<AnySyncStateEvent> = event.event.clone().cast();
let raw_event: Raw<AnySyncStateEvent> = event.event().clone().cast();
changes.add_state_event(room.room_id(), s.clone(), raw_event);
}

Expand All @@ -443,8 +443,8 @@ impl BaseClient {
room_info.room_version().unwrap_or(&RoomVersionId::V1);

if let Some(redacts) = r.redacts(room_version) {
room_info.handle_redaction(r, event.event.cast_ref());
let raw_event = event.event.clone().cast();
room_info.handle_redaction(r, event.event().cast_ref());
let raw_event = event.event().clone().cast();

changes.add_redaction(room.room_id(), redacts, raw_event);
}
Expand All @@ -456,7 +456,7 @@ impl BaseClient {
SyncMessageLikeEvent::Original(_),
) => {
if let Ok(Some(e)) = Box::pin(
self.decrypt_sync_room_event(&event.event, room.room_id()),
self.decrypt_sync_room_event(event.event(), room.room_id()),
)
.await
{
Expand Down Expand Up @@ -494,14 +494,14 @@ impl BaseClient {
}

if let Some(context) = &push_context {
let actions = push_rules.get_actions(&event.event, context);
let actions = push_rules.get_actions(event.event(), context);

if actions.iter().any(Action::should_notify) {
notifications.entry(room.room_id().to_owned()).or_default().push(
Notification {
actions: actions.to_owned(),
event: RawAnySyncOrStrippedTimelineEvent::Sync(
event.event.clone(),
event.event().clone(),
),
},
);
Expand Down Expand Up @@ -773,7 +773,7 @@ impl BaseClient {

if let Ok(Some(decrypted)) = decrypt_sync_room_event.await {
// We found an event we can decrypt
if let Ok(any_sync_event) = decrypted.event.deserialize() {
if let Ok(any_sync_event) = decrypted.event().deserialize() {
// We can deserialize it to find its type
match is_suitable_for_latest_event(&any_sync_event) {
PossibleLatestEvent::YesRoomMessage(_)
Expand Down
4 changes: 2 additions & 2 deletions crates/matrix-sdk-base/src/read_receipts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,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) {
if marks_as_unread(&event.event, user_id) {
if marks_as_unread(event.event(), user_id) {
self.num_unread += 1;
}

Expand Down Expand Up @@ -408,7 +408,7 @@ impl ReceiptSelector {
fn try_match_implicit(&mut self, user_id: &UserId, new_events: &[SyncTimelineEvent]) {
for ev in new_events {
// Get the `sender` field, if any, or skip this event.
let Ok(Some(sender)) = ev.event.get_field::<OwnedUserId>("sender") else { continue };
let Ok(Some(sender)) = ev.event().get_field::<OwnedUserId>("sender") else { continue };
if sender == user_id {
// Get the event id, if any, or skip this event.
let Some(event_id) = ev.event_id() else { continue };
Expand Down
4 changes: 2 additions & 2 deletions crates/matrix-sdk-base/src/rooms/normal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1261,9 +1261,9 @@ impl RoomInfo {
if let Some(latest_event) = &mut self.latest_event {
tracing::trace!("Checking if redaction applies to latest event");
if latest_event.event_id().as_deref() == Some(redacts) {
match apply_redaction(&latest_event.event().event, _raw, room_version) {
match apply_redaction(latest_event.event().event(), _raw, room_version) {
Some(redacted) => {
latest_event.event_mut().event = redacted;
latest_event.event_mut().replace_inner(redacted);
debug!("Redacted latest event");
}
None => {
Expand Down
6 changes: 3 additions & 3 deletions crates/matrix-sdk-base/src/sliding_sync/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -677,7 +677,7 @@ async fn cache_latest_events(
Vec::with_capacity(room.latest_encrypted_events.read().unwrap().capacity());

for event in events.iter().rev() {
if let Ok(timeline_event) = event.event.deserialize() {
if let Ok(timeline_event) = event.event().deserialize() {
match is_suitable_for_latest_event(&timeline_event) {
PossibleLatestEvent::YesRoomMessage(_)
| PossibleLatestEvent::YesPoll(_)
Expand Down Expand Up @@ -757,7 +757,7 @@ async fn cache_latest_events(
// Check how many encrypted events we have seen. Only store another if we
// haven't already stored the maximum number.
if encrypted_events.len() < encrypted_events.capacity() {
encrypted_events.push(event.event.clone());
encrypted_events.push(event.event().clone());
}
}
_ => {
Expand Down Expand Up @@ -1683,7 +1683,7 @@ mod tests {

// But it's now redacted
assert_matches!(
latest_event.event().event.deserialize().unwrap(),
latest_event.event().event().deserialize().unwrap(),
AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomMessage(
SyncRoomMessageEvent::Redacted(_)
))
Expand Down
71 changes: 56 additions & 15 deletions crates/matrix-sdk-common/src/deserialized_responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,10 +305,14 @@ pub struct EncryptionInfo {
#[derive(Clone, Deserialize, Serialize)]
pub struct SyncTimelineEvent {
/// The actual event.
pub event: Raw<AnySyncTimelineEvent>,
#[serde(rename = "event")]
inner_event: Raw<AnySyncTimelineEvent>,

/// The encryption info about the event. Will be `None` if the event was not
/// encrypted.
pub encryption_info: Option<EncryptionInfo>,
#[serde(rename = "encryption_info")]
inner_encryption_info: Option<EncryptionInfo>,

/// The push actions associated with this event.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub push_actions: Vec<Action>,
Expand All @@ -325,7 +329,12 @@ impl SyncTimelineEvent {
/// This is a convenience constructor for when you don't need to set
/// `encryption_info` or `push_action`, for example inside a test.
pub fn new(event: Raw<AnySyncTimelineEvent>) -> Self {
Self { event, encryption_info: None, push_actions: vec![], unsigned_encryption_info: None }
Self {
inner_event: event,
inner_encryption_info: None,
push_actions: vec![],
unsigned_encryption_info: None,
}
}

/// Create a new `SyncTimelineEvent` from the given raw event and push
Expand All @@ -337,24 +346,56 @@ impl SyncTimelineEvent {
event: Raw<AnySyncTimelineEvent>,
push_actions: Vec<Action>,
) -> Self {
Self { event, encryption_info: None, push_actions, unsigned_encryption_info: None }
Self {
inner_event: event,
inner_encryption_info: None,
push_actions,
unsigned_encryption_info: None,
}
}

/// Get the event id of this `SyncTimelineEvent` if the event has any valid
/// id.
pub fn event_id(&self) -> Option<OwnedEventId> {
self.event.get_field::<OwnedEventId>("event_id").ok().flatten()
self.inner_event.get_field::<OwnedEventId>("event_id").ok().flatten()
}

/// Returns a reference to the (potentially decrypted) Matrix event inside
/// this `TimelineEvent`.
pub fn event(&self) -> &Raw<AnySyncTimelineEvent> {
&self.inner_event
}

/// 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.inner_encryption_info.as_ref()
}

/// Takes ownership of this `TimelineEvent`, returning the (potentially
/// decrypted) Matrix event within.
pub fn into_event(self) -> Raw<AnySyncTimelineEvent> {
self.inner_event
}

/// Replace the Matrix event within this event. Used to handle redaction.
pub fn replace_inner(&mut self, event: Raw<AnySyncTimelineEvent>) {
self.inner_event = event;
}
}

#[cfg(not(tarpaulin_include))]
impl fmt::Debug for SyncTimelineEvent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let SyncTimelineEvent { event, encryption_info, push_actions, unsigned_encryption_info } =
self;
let SyncTimelineEvent {
inner_event,
inner_encryption_info,
push_actions,
unsigned_encryption_info,
} = self;
let mut s = f.debug_struct("SyncTimelineEvent");
s.field("event", &DebugRawEvent(event));
s.maybe_field("encryption_info", encryption_info);
s.field("event", &DebugRawEvent(inner_event));
s.maybe_field("encryption_info", inner_encryption_info);
if !push_actions.is_empty() {
s.field("push_actions", push_actions);
}
Expand All @@ -376,8 +417,8 @@ impl From<TimelineEvent> for SyncTimelineEvent {
// this way, we simply cause the `room_id` field in the json to be
// ignored by a subsequent deserialization.
Self {
event: o.event.cast(),
encryption_info: o.encryption_info,
inner_event: o.event.cast(),
inner_encryption_info: o.encryption_info,
push_actions: o.push_actions.unwrap_or_default(),
unsigned_encryption_info: o.unsigned_encryption_info,
}
Expand Down Expand Up @@ -579,7 +620,7 @@ mod tests {
let converted_room_event: SyncTimelineEvent = room_event.into();

let converted_event: AnySyncTimelineEvent =
converted_room_event.event.deserialize().unwrap();
converted_room_event.event().deserialize().unwrap();

assert_eq!(converted_event.event_id(), "$xxxxx:example.org");
assert_eq!(converted_event.sender(), "@carl:example.com");
Expand Down Expand Up @@ -628,8 +669,8 @@ mod tests {
#[test]
fn sync_timeline_event_serialisation() {
let room_event = SyncTimelineEvent {
event: Raw::new(&example_event()).unwrap().cast(),
encryption_info: Some(EncryptionInfo {
inner_event: Raw::new(&example_event()).unwrap().cast(),
inner_encryption_info: Some(EncryptionInfo {
sender: user_id!("@sender:example.com").to_owned(),
sender_device: None,
algorithm_info: AlgorithmInfo::MegolmV1AesSha2 {
Expand Down Expand Up @@ -674,7 +715,7 @@ mod tests {
let event: SyncTimelineEvent = 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,
event.encryption_info().unwrap().algorithm_info,
AlgorithmInfo::MegolmV1AesSha2 { .. }
)
}
Expand Down
4 changes: 2 additions & 2 deletions crates/matrix-sdk-ui/src/timeline/controller/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ impl TimelineStateTransaction<'_> {
settings: &TimelineSettings,
day_divider_adjuster: &mut DayDividerAdjuster,
) -> HandleEventResult {
let raw = event.event;
let raw = event.event();
let (event_id, sender, timestamp, txn_id, event_kind, should_add) = match raw.deserialize()
{
Ok(event) => {
Expand Down Expand Up @@ -584,7 +584,7 @@ impl TimelineStateTransaction<'_> {
flow: Flow::Remote {
event_id: event_id.clone(),
raw_event: raw.clone(),
encryption_info: event.encryption_info,
encryption_info: event.encryption_info().cloned(),
txn_id,
position,
},
Expand Down
6 changes: 3 additions & 3 deletions crates/matrix-sdk-ui/src/timeline/event_item/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use matrix_sdk::{
Client, Error,
};
use matrix_sdk_base::{
deserialized_responses::{ShieldStateCode, SyncTimelineEvent, SENT_IN_CLEAR},
deserialized_responses::{ShieldStateCode, SENT_IN_CLEAR},
latest_event::LatestEvent,
};
use once_cell::sync::Lazy;
Expand Down Expand Up @@ -157,8 +157,8 @@ impl EventTimelineItem {
// potential footgun which could one day turn into a security issue.
use super::traits::RoomDataProvider;

let SyncTimelineEvent { event: raw_sync_event, encryption_info, .. } =
latest_event.event().clone();
let raw_sync_event = latest_event.event().event().clone();
let encryption_info = latest_event.event().encryption_info().cloned();

let Ok(event) = raw_sync_event.deserialize_as::<AnySyncTimelineEvent>() else {
warn!("Unable to deserialize latest_event as an AnySyncTimelineEvent!");
Expand Down
2 changes: 1 addition & 1 deletion crates/matrix-sdk-ui/src/timeline/pinned_events_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ impl PinnedEventsLoader {

// Sort using chronological ordering (oldest -> newest)
loaded_events.sort_by_key(|item| {
item.event
item.event()
.deserialize()
.map(|e| e.origin_server_ts())
.unwrap_or_else(|_| MilliSecondsSinceUnixEpoch::now())
Expand Down
28 changes: 21 additions & 7 deletions crates/matrix-sdk-ui/src/timeline/tests/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@ use eyeball_im::VectorDiff;
use matrix_sdk::deserialized_responses::{
AlgorithmInfo, EncryptionInfo, VerificationLevel, VerificationState,
};
use matrix_sdk_base::deserialized_responses::{DecryptedRoomEvent, SyncTimelineEvent};
use matrix_sdk_test::{async_test, sync_timeline_event, ALICE};
use ruma::{
event_id,
events::room::message::{MessageType, RedactedRoomMessageEventContent},
server_name, EventId,
room_id, server_name, EventId,
};
use stream_assert::assert_next_matches;

Expand Down Expand Up @@ -165,13 +166,15 @@ async fn test_edit_updates_encryption_info() {
let timeline = TestTimeline::new();
let event_factory = &timeline.factory;

let room_id = room_id!("!room:id");
let original_event_id = event_id!("$original_event");

let mut original_event = event_factory
let original_event = event_factory
.text_msg("**original** message")
.sender(*ALICE)
.event_id(original_event_id)
.into_sync();
.room(room_id)
.into_raw_timeline();

let mut encryption_info = EncryptionInfo {
sender: (*ALICE).into(),
Expand All @@ -183,7 +186,12 @@ async fn test_edit_updates_encryption_info() {
verification_state: VerificationState::Verified,
};

original_event.encryption_info = Some(encryption_info.clone());
let original_event: SyncTimelineEvent = DecryptedRoomEvent {
event: original_event.cast(),
encryption_info: encryption_info.clone(),
unsigned_encryption_info: None,
}
.into();

timeline.handle_live_event(original_event).await;

Expand All @@ -199,14 +207,20 @@ async fn test_edit_updates_encryption_info() {
assert_let!(MessageType::Text(text) = message.msgtype());
assert_eq!(text.body, "**original** message");

let mut edit_event = event_factory
let edit_event = event_factory
.text_msg(" * !!edited!! **better** message")
.sender(*ALICE)
.room(room_id)
.edit(original_event_id, MessageType::text_plain("!!edited!! **better** message").into())
.into_sync();
.into_raw_timeline();
encryption_info.verification_state =
VerificationState::Unverified(VerificationLevel::UnverifiedIdentity);
edit_event.encryption_info = Some(encryption_info);
let edit_event: SyncTimelineEvent = DecryptedRoomEvent {
event: edit_event.cast(),
encryption_info: encryption_info.clone(),
unsigned_encryption_info: None,
}
.into();

timeline.handle_live_event(edit_event).await;

Expand Down
2 changes: 1 addition & 1 deletion crates/matrix-sdk/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2110,7 +2110,7 @@ impl Client {
/// while let Some(Ok(response)) = sync_stream.next().await {
/// for room in response.rooms.join.values() {
/// for e in &room.timeline.events {
/// if let Ok(event) = e.event.deserialize() {
/// if let Ok(event) = e.event().deserialize() {
/// println!("Received event {:?}", event);
/// }
/// }
Expand Down
2 changes: 1 addition & 1 deletion crates/matrix-sdk/src/event_cache/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -820,7 +820,7 @@ impl RoomEventCacheInner {
event: &SyncTimelineEvent,
) {
// Handle and cache events and relations.
if let Ok(AnySyncTimelineEvent::MessageLike(ev)) = event.event.deserialize() {
if let Ok(AnySyncTimelineEvent::MessageLike(ev)) = event.event().deserialize() {
// Handle redactions separately, as their logic is slightly different.
if let AnySyncMessageLikeEvent::RoomRedaction(SyncRoomRedactionEvent::Original(ev)) =
&ev
Expand Down
Loading

0 comments on commit a13f018

Please sign in to comment.