Skip to content

Commit

Permalink
common: make TimelineEvent 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 a13f018 commit 1b43c88
Show file tree
Hide file tree
Showing 16 changed files with 86 additions and 54 deletions.
48 changes: 38 additions & 10 deletions crates/matrix-sdk-common/src/deserialized_responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -417,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 {
inner_event: o.event.cast(),
inner_encryption_info: o.encryption_info,
inner_event: o.inner_event.cast(),
inner_encryption_info: o.inner_encryption_info,
push_actions: o.push_actions.unwrap_or_default(),
unsigned_encryption_info: o.unsigned_encryption_info,
}
Expand All @@ -445,10 +445,10 @@ impl From<DecryptedRoomEvent> for SyncTimelineEvent {
#[derive(Clone)]
pub struct TimelineEvent {
/// The actual event.
pub event: Raw<AnyTimelineEvent>,
inner_event: Raw<AnyTimelineEvent>,
/// The encryption info about the event. Will be `None` if the event was not
/// encrypted.
pub encryption_info: Option<EncryptionInfo>,
inner_encryption_info: Option<EncryptionInfo>,
/// The push actions associated with this event, if we had sufficient
/// context to compute them.
pub push_actions: Option<Vec<Action>>,
Expand All @@ -464,7 +464,30 @@ impl TimelineEvent {
/// 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<AnyTimelineEvent>) -> Self {
Self { event, encryption_info: None, push_actions: None, unsigned_encryption_info: None }
Self {
inner_event: event,
inner_encryption_info: None,
push_actions: None,
unsigned_encryption_info: None,
}
}

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

Expand All @@ -474,8 +497,8 @@ impl From<DecryptedRoomEvent> for TimelineEvent {
// Casting from the more specific `AnyMessageLikeEvent` (i.e. an event without a
// `state_key`) to a more generic `AnyTimelineEvent` (i.e. one that may contain
// a `state_key`) is safe.
event: decrypted.event.cast(),
encryption_info: Some(decrypted.encryption_info),
inner_event: decrypted.event.cast(),
inner_encryption_info: Some(decrypted.encryption_info),
push_actions: None,
unsigned_encryption_info: decrypted.unsigned_encryption_info,
}
Expand All @@ -485,10 +508,15 @@ impl From<DecryptedRoomEvent> for TimelineEvent {
#[cfg(not(tarpaulin_include))]
impl fmt::Debug for TimelineEvent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let TimelineEvent { event, encryption_info, push_actions, unsigned_encryption_info } = self;
let TimelineEvent {
inner_event,
inner_encryption_info,
push_actions,
unsigned_encryption_info,
} = self;
let mut s = f.debug_struct("TimelineEvent");
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 let Some(push_actions) = &push_actions {
if !push_actions.is_empty() {
s.field("push_actions", push_actions);
Expand Down
16 changes: 10 additions & 6 deletions crates/matrix-sdk-ui/src/notification_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -496,9 +496,12 @@ impl NotificationClient {
let push_actions = match &raw_event {
RawNotificationEvent::Timeline(timeline_event) => {
// Timeline events may be encrypted, so make sure they get decrypted first.
if let Some(timeline_event) = self.retry_decryption(&room, timeline_event).await? {
raw_event = RawNotificationEvent::Timeline(timeline_event.event.cast());
timeline_event.push_actions
if let Some(mut timeline_event) =
self.retry_decryption(&room, timeline_event).await?
{
let push_actions = timeline_event.push_actions.take();
raw_event = RawNotificationEvent::Timeline(timeline_event.into_event().cast());
push_actions
} else {
room.event_push_actions(timeline_event).await?
}
Expand Down Expand Up @@ -550,7 +553,7 @@ impl NotificationClient {
let state_events = response.state;

if let Some(decrypted_event) =
self.retry_decryption(&room, timeline_event.event.cast_ref()).await?
self.retry_decryption(&room, timeline_event.event().cast_ref()).await?
{
timeline_event = decrypted_event;
}
Expand All @@ -561,11 +564,12 @@ impl NotificationClient {
}
}

let push_actions = timeline_event.push_actions.take();
Ok(Some(
NotificationItem::new(
&room,
RawNotificationEvent::Timeline(timeline_event.event.cast()),
timeline_event.push_actions.as_deref(),
RawNotificationEvent::Timeline(timeline_event.into_event().cast()),
push_actions.as_deref(),
state_events,
)
.await?,
Expand Down
2 changes: 1 addition & 1 deletion crates/matrix-sdk-ui/src/timeline/controller/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ impl TimelineState {
};

event.push_actions = push_rules_context.as_ref().map(|(push_rules, push_context)| {
push_rules.get_actions(&event.event, push_context).to_owned()
push_rules.get_actions(event.event(), push_context).to_owned()
});

let handle_one_res = txn
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ impl RepliedToEvent {
timeline_event: TimelineEvent,
room_data_provider: &P,
) -> Result<Self, TimelineError> {
let event = match timeline_event.event.deserialize() {
let event = match timeline_event.event().deserialize() {
Ok(AnyTimelineEvent::MessageLike(event)) => event,
_ => {
return Err(TimelineError::UnsupportedEvent);
Expand Down
2 changes: 1 addition & 1 deletion crates/matrix-sdk-ui/src/timeline/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ impl Timeline {
// `AnySyncTimelineEvent` which is the same as a `AnyTimelineEvent`, but without
// the `room_id` field. The cast is valid because we are just losing
// track of such field.
let raw_sync_event: Raw<AnySyncTimelineEvent> = event.event.cast();
let raw_sync_event: Raw<AnySyncTimelineEvent> = event.into_event().cast();
let sync_event = raw_sync_event.deserialize().map_err(|error| {
error!("Failed to deserialize event with ID {event_id} with error: {error}");
UnsupportedReplyItem::FailedToDeserializeEvent
Expand Down
10 changes: 5 additions & 5 deletions crates/matrix-sdk-ui/tests/integration/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ async fn mock_context(
.and(path(format!("/_matrix/client/r0/rooms/{room_id}/context/{event_id}")))
.and(header("authorization", "Bearer 1234"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"events_before": events_before.into_iter().rev().map(|ev| ev.event).collect_vec(),
"event": event.event,
"events_after": events_after.into_iter().map(|ev| ev.event).collect_vec(),
"events_before": events_before.into_iter().rev().map(|ev| ev.into_event()).collect_vec(),
"event": event.into_event(),
"events_after": events_after.into_iter().map(|ev| ev.into_event()).collect_vec(),
"state": state,
"start": prev_batch_token,
"end": next_batch_token
Expand All @@ -93,7 +93,7 @@ async fn mock_event(
Mock::given(method("GET"))
.and(path(format!("/_matrix/client/r0/rooms/{room_id}/event/{event_id}")))
.and(header("authorization", "Bearer 1234"))
.respond_with(ResponseTemplate::new(200).set_body_json(event.event.json()))
.respond_with(ResponseTemplate::new(200).set_body_json(event.into_event().json()))
.mount(server)
.await;
}
Expand All @@ -116,7 +116,7 @@ async fn mock_messages(
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"start": start,
"end": end,
"chunk": chunk.into_iter().map(|ev| ev.event).collect_vec(),
"chunk": chunk.into_iter().map(|ev| ev.into_event()).collect_vec(),
"state": state,
})))
.expect(1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -720,7 +720,7 @@ impl TestHelper {
) -> Result<SyncResponse, matrix_sdk::Error> {
let mut joined_room_builder = JoinedRoomBuilder::new(&self.room_id);
for (timeline_event, add_to_timeline) in text_messages {
let deserialized_event = timeline_event.event.deserialize()?;
let deserialized_event = timeline_event.event().deserialize()?;
mock_event(
&self.server,
&self.room_id,
Expand All @@ -731,7 +731,7 @@ impl TestHelper {

if add_to_timeline {
joined_room_builder =
joined_room_builder.add_timeline_event(timeline_event.event.cast());
joined_room_builder.add_timeline_event(timeline_event.into_event().cast());
}
}

Expand Down
8 changes: 4 additions & 4 deletions crates/matrix-sdk/src/event_cache/paginator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -736,7 +736,7 @@ mod tests {
}

assert_event_matches_msg(&context.events[10], "fetch_from");
assert_eq!(context.events[10].event.deserialize().unwrap().event_id(), event_id);
assert_eq!(context.events[10].event().deserialize().unwrap().event_id(), event_id);

for i in 0..10 {
assert_event_matches_msg(&context.events[i + 11], &format!("after-{i}"));
Expand Down Expand Up @@ -800,7 +800,7 @@ mod tests {
// And I get the events I expected.
assert_eq!(context.events.len(), 1);
assert_event_matches_msg(&context.events[0], "initial");
assert_eq!(context.events[0].event.deserialize().unwrap().event_id(), event_id);
assert_eq!(context.events[0].event().deserialize().unwrap().event_id(), event_id);

// There's a previous batch, but no next batch.
assert!(context.has_prev);
Expand Down Expand Up @@ -865,7 +865,7 @@ mod tests {
// And I get the events I expected.
assert_eq!(context.events.len(), 1);
assert_event_matches_msg(&context.events[0], "initial");
assert_eq!(context.events[0].event.deserialize().unwrap().event_id(), event_id);
assert_eq!(context.events[0].event().deserialize().unwrap().event_id(), event_id);

// There's a previous batch.
assert!(context.has_prev);
Expand Down Expand Up @@ -915,7 +915,7 @@ mod tests {
// And I get the events I expected.
assert_eq!(context.events.len(), 1);
assert_event_matches_msg(&context.events[0], "initial");
assert_eq!(context.events[0].event.deserialize().unwrap().event_id(), event_id);
assert_eq!(context.events[0].event().deserialize().unwrap().event_id(), event_id);

// There's a next batch, but no previous batch (i.e. we've hit the start of the
// timeline).
Expand Down
6 changes: 3 additions & 3 deletions crates/matrix-sdk/src/room/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ impl Room {

for event in &mut response.chunk {
event.push_actions =
Some(push_rules.get_actions(&event.event, &push_context).to_owned());
Some(push_rules.get_actions(event.event(), &push_context).to_owned());
}
}

Expand Down Expand Up @@ -420,7 +420,7 @@ impl Room {
}

let mut event = TimelineEvent::new(event);
event.push_actions = self.event_push_actions(&event.event).await?;
event.push_actions = self.event_push_actions(event.event()).await?;

Ok(event)
}
Expand Down Expand Up @@ -1238,7 +1238,7 @@ impl Room {
};

let mut event: TimelineEvent = decrypted.into();
event.push_actions = self.event_push_actions(&event.event).await?;
event.push_actions = self.event_push_actions(event.event()).await?;

Ok(event)
}
Expand Down
2 changes: 1 addition & 1 deletion crates/matrix-sdk/src/widget/matrix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ impl MatrixDriver {
});

let messages = self.room.messages(options).await?;
Ok(messages.chunk.into_iter().map(|ev| ev.event.cast()).collect())
Ok(messages.chunk.into_iter().map(|ev| ev.into_event().cast()).collect())
}

pub(crate) async fn read_state_events(
Expand Down
2 changes: 1 addition & 1 deletion crates/matrix-sdk/tests/integration/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -750,7 +750,7 @@ async fn test_encrypt_room_event() {
.expect("We should be able to decrypt an event that we ourselves have encrypted");

let event = timeline_event
.event
.event()
.deserialize()
.expect("We should be able to deserialize the decrypted event");

Expand Down
18 changes: 9 additions & 9 deletions crates/matrix-sdk/tests/integration/encryption/backups.rs
Original file line number Diff line number Diff line change
Expand Up @@ -972,7 +972,7 @@ async fn test_enable_from_secret_storage() {
room.event(event_id, None).await.expect("We should be able to fetch our encrypted event");

assert_matches!(
event.encryption_info,
event.encryption_info(),
None,
"We should not be able to decrypt our encrypted event before we import the room keys from \
the backup"
Expand Down Expand Up @@ -1042,9 +1042,9 @@ async fn test_enable_from_secret_storage() {
let event =
room.event(event_id, None).await.expect("We should be able to fetch our encrypted event");

assert_matches!(event.encryption_info, Some(..), "The event should now be decrypted");
assert_matches!(event.encryption_info(), Some(..), "The event should now be decrypted");
let event: RoomMessageEvent =
event.event.deserialize_as().expect("We should be able to deserialize the event");
event.event().deserialize_as().expect("We should be able to deserialize the event");
let event = event.as_original().unwrap();
assert_eq!(event.content.body(), "tt");

Expand Down Expand Up @@ -1392,7 +1392,7 @@ async fn test_enable_from_secret_storage_and_download_after_utd() {
room.event(event_id, None).await.expect("We should be able to fetch our encrypted event");

assert_matches!(
event.encryption_info,
event.encryption_info(),
None,
"We should not be able to decrypt the event right away"
);
Expand All @@ -1412,9 +1412,9 @@ async fn test_enable_from_secret_storage_and_download_after_utd() {
let event =
room.event(event_id, None).await.expect("We should be able to fetch our encrypted event");

assert_matches!(event.encryption_info, Some(..), "The event should now be decrypted");
assert_matches!(event.encryption_info(), Some(..), "The event should now be decrypted");
let event: RoomMessageEvent =
event.event.deserialize_as().expect("We should be able to deserialize the event");
event.event().deserialize_as().expect("We should be able to deserialize the event");
let event = event.as_original().unwrap();
assert_eq!(event.content.body(), "tt");

Expand Down Expand Up @@ -1522,7 +1522,7 @@ async fn test_enable_from_secret_storage_and_download_after_utd_from_old_message
room.event(event_id, None).await.expect("We should be able to fetch our encrypted event");

assert_matches!(
event.encryption_info,
event.encryption_info(),
None,
"We should not be able to decrypt the event right away"
);
Expand All @@ -1542,9 +1542,9 @@ async fn test_enable_from_secret_storage_and_download_after_utd_from_old_message
let event =
room.event(event_id, None).await.expect("We should be able to fetch our encrypted event");

assert_matches!(event.encryption_info, Some(..), "The event should now be decrypted");
assert_matches!(event.encryption_info(), Some(..), "The event should now be decrypted");
let event: RoomMessageEvent =
event.event.deserialize_as().expect("We should be able to deserialize the event");
event.event().deserialize_as().expect("We should be able to deserialize the event");
let event = event.as_original().unwrap();
assert_eq!(event.content.body(), "tt");

Expand Down
8 changes: 4 additions & 4 deletions crates/matrix-sdk/tests/integration/room/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -672,7 +672,7 @@ async fn test_event() {
let timeline_event = room.event(event_id, None).await.unwrap();
assert_let!(
AnyTimelineEvent::State(AnyStateEvent::RoomTombstone(event)) =
timeline_event.event.deserialize().unwrap()
timeline_event.event().deserialize().unwrap()
);
assert_eq!(event.event_id(), event_id);

Expand Down Expand Up @@ -734,15 +734,15 @@ async fn test_event_with_context() {
let context_ret = room.event_with_context(event_id, false, uint!(1), None).await.unwrap();

assert_let!(Some(timeline_event) = context_ret.event);
assert_let!(Ok(event) = timeline_event.event.deserialize());
assert_let!(Ok(event) = timeline_event.event().deserialize());
assert_eq!(event.event_id(), event_id);

assert_eq!(1, context_ret.events_before.len());
assert_let!(Ok(event) = context_ret.events_before[0].event.deserialize());
assert_let!(Ok(event) = context_ret.events_before[0].event().deserialize());
assert_eq!(event.event_id(), prev_event_id);

assert_eq!(1, context_ret.events_after.len());
assert_let!(Ok(event) = context_ret.events_after[0].event.deserialize());
assert_let!(Ok(event) = context_ret.events_after[0].event().deserialize());
assert_eq!(event.event_id(), next_event_id);

// Requested event and their context ones were saved to the cache
Expand Down
4 changes: 2 additions & 2 deletions testing/matrix-sdk-integration-testing/src/tests/e2ee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -950,11 +950,11 @@ async fn test_secret_gossip_after_interactive_verification() -> Result<()> {

let timeline_event = room.event(&event_id, None).await?;
timeline_event
.encryption_info
.encryption_info()
.expect("The event should have been encrypted and successfully decrypted.");

let event: OriginalSyncMessageLikeEvent<RoomMessageEventContent> =
timeline_event.event.deserialize_as()?;
timeline_event.event().deserialize_as()?;
let message = event.content.msgtype;

assert_let!(MessageType::Text(message) = message);
Expand Down
2 changes: 1 addition & 1 deletion testing/matrix-sdk-integration-testing/src/tests/nse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,7 @@ async fn decrypt_event(
return None;
};

let Ok(deserialized) = decrypted.event.deserialize() else { return None };
let Ok(deserialized) = decrypted.event().deserialize() else { return None };

let AnyTimelineEvent::MessageLike(message) = &deserialized else { return None };

Expand Down
Loading

0 comments on commit 1b43c88

Please sign in to comment.