Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(sdk): Add day dividers to the experimental timeline #1251

Merged
merged 5 commits into from
Dec 14, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions bindings/matrix-sdk-ffi/src/timeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,8 +193,8 @@ impl EventTimelineItem {
Arc::new(TimelineItemContent(self.0.content().clone()))
}

pub fn origin_server_ts(&self) -> Option<u64> {
self.0.origin_server_ts().map(|ts| ts.0.into())
pub fn timestamp(&self) -> u64 {
self.0.timestamp().0.into()
}

pub fn reactions(&self) -> Vec<Reaction> {
Expand Down
39 changes: 16 additions & 23 deletions crates/matrix-sdk/src/room/timeline/event_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ use crate::events::SyncTimelineEventWithoutContent;
pub(super) enum Flow {
Local {
txn_id: OwnedTransactionId,
timestamp: MilliSecondsSinceUnixEpoch,
},
Remote {
event_id: OwnedEventId,
Expand All @@ -61,14 +62,14 @@ impl Flow {
fn to_key(&self) -> TimelineKey {
match self {
Self::Remote { event_id, .. } => TimelineKey::EventId(event_id.to_owned()),
Self::Local { txn_id } => TimelineKey::TransactionId(txn_id.to_owned()),
Self::Local { txn_id, .. } => TimelineKey::TransactionId(txn_id.to_owned()),
}
}

fn origin_server_ts(&self) -> Option<MilliSecondsSinceUnixEpoch> {
fn timestamp(&self) -> MilliSecondsSinceUnixEpoch {
match self {
Flow::Local { .. } => None,
Flow::Remote { origin_server_ts, .. } => Some(*origin_server_ts),
Flow::Local { timestamp, .. } => *timestamp,
Flow::Remote { origin_server_ts, .. } => *origin_server_ts,
}
}

Expand Down Expand Up @@ -408,38 +409,33 @@ impl<'a, 'i> TimelineEventHandler<'a, 'i> {
sender: self.meta.sender.to_owned(),
content,
reactions,
origin_server_ts: self.flow.origin_server_ts(),
timestamp: self.flow.timestamp(),
is_own: self.meta.is_own_event,
encryption_info: self.meta.encryption_info.clone(),
raw: self.flow.raw_event().cloned(),
};

let item = Arc::new(TimelineItem::Event(item));
match &self.flow {
Flow::Local { .. } => {
// Use the current time for local events.
let new_ts = MilliSecondsSinceUnixEpoch::now();

Flow::Local { timestamp, .. } => {
// Check if the latest event has the same date as this event.
if let Some(latest_event) = self
.timeline_items
.iter()
.rfind(|item| item.as_event().is_some())
.and_then(|item| item.as_event())
{
if let Some(old_ts) = latest_event.origin_server_ts() {
// If there is no origin_server_ts, it's a local event so we can assume
// it has the same date.
if let Some(day_divider_item) =
maybe_create_day_divider_from_timestamps(old_ts, new_ts)
{
self.timeline_items
.push_cloned(Arc::new(TimelineItem::Virtual(day_divider_item)));
}
let old_ts = latest_event.timestamp();

if let Some(day_divider_item) =
maybe_create_day_divider_from_timestamps(old_ts, *timestamp)
{
self.timeline_items
.push_cloned(Arc::new(TimelineItem::Virtual(day_divider_item)));
}
} else {
// If there is not event item, there is no day divider yet.
jplatte marked this conversation as resolved.
Show resolved Hide resolved
let (year, month, day) = timestamp_to_ymd(new_ts);
let (year, month, day) = timestamp_to_ymd(*timestamp);
self.timeline_items.push_cloned(Arc::new(TimelineItem::Virtual(
VirtualTimelineItem::day_divider(year, month, day),
)));
Expand Down Expand Up @@ -521,10 +517,7 @@ impl<'a, 'i> TimelineEventHandler<'a, 'i> {
.rfind(|item| item.as_event().is_some())
.and_then(|item| item.as_event())
{
let old_ts = latest_event
.origin_server_ts()
// Default to now for local events.
.unwrap_or_else(MilliSecondsSinceUnixEpoch::now);
let old_ts = latest_event.timestamp();

if let Some(day_divider_item) =
maybe_create_day_divider_from_timestamps(old_ts, *origin_server_ts)
Expand Down
22 changes: 12 additions & 10 deletions crates/matrix-sdk/src/room/timeline/event_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub struct EventTimelineItem {
pub(super) sender: OwnedUserId,
pub(super) content: TimelineItemContent,
pub(super) reactions: BundledReactions,
pub(super) origin_server_ts: Option<MilliSecondsSinceUnixEpoch>,
pub(super) timestamp: MilliSecondsSinceUnixEpoch,
pub(super) is_own: bool,
pub(super) encryption_info: Option<EncryptionInfo>,
// FIXME: Expose the raw JSON of aggregated events somehow
Expand All @@ -60,7 +60,7 @@ impl fmt::Debug for EventTimelineItem {
.field("sender", &self.sender)
.field("content", &self.content)
.field("reactions", &self.reactions)
.field("origin_server_ts", &self.origin_server_ts)
.field("timestamp", &self.timestamp)
.field("is_own", &self.is_own)
.field("encryption_info", &self.encryption_info)
// skip raw, too noisy
Expand Down Expand Up @@ -121,11 +121,13 @@ impl EventTimelineItem {
&self.reactions.bundled
}

/// Get the origin server timestamp of this item.
/// Get the timestamp of this item.
///
/// Returns `None` if this event hasn't been echoed back by the server yet.
pub fn origin_server_ts(&self) -> Option<MilliSecondsSinceUnixEpoch> {
self.origin_server_ts
/// If this event hasn't been echoed back by the server yet, Returns the
zecakeh marked this conversation as resolved.
Show resolved Hide resolved
/// time the local event was created. Otherwise, returns the origin
/// server timestamp.
pub fn timestamp(&self) -> MilliSecondsSinceUnixEpoch {
self.timestamp
}

/// Whether this timeline item was sent by the logged-in user themselves.
Expand Down Expand Up @@ -157,14 +159,14 @@ impl EventTimelineItem {
// FIXME: Change when we support state events
content: TimelineItemContent::RedactedMessage,
reactions: BundledReactions::default(),
..self(key, event_id, sender, origin_server_ts, is_own, encryption_info, raw)
..self(key, event_id, sender, timestamp, is_own, encryption_info, raw)
})
}

pub(super) fn with_event_id(&self, event_id: Option<OwnedEventId>) -> Self {
build!(Self {
event_id,
..self(key, sender, content, reactions, origin_server_ts, is_own, encryption_info, raw,)
..self(key, sender, content, reactions, timestamp, is_own, encryption_info, raw,)
})
}

Expand All @@ -173,7 +175,7 @@ impl EventTimelineItem {
build!(Self {
content,
..self(
key, event_id, sender, reactions, origin_server_ts, is_own, encryption_info, raw,
key, event_id, sender, reactions, timestamp, is_own, encryption_info, raw,
)
})
}
Expand All @@ -183,7 +185,7 @@ impl EventTimelineItem {
build!(Self {
reactions,
..self(
key, event_id, sender, content, origin_server_ts, is_own, encryption_info, raw,
key, event_id, sender, content, timestamp, is_own, encryption_info, raw,
)
})
}
Expand Down
4 changes: 2 additions & 2 deletions crates/matrix-sdk/src/room/timeline/inner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use matrix_sdk_base::{
use ruma::{
events::{fully_read::FullyReadEvent, AnyMessageLikeEventContent, AnySyncTimelineEvent},
serde::Raw,
OwnedEventId, OwnedTransactionId, RoomId, TransactionId, UserId,
MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedTransactionId, RoomId, TransactionId, UserId,
};
use tracing::{error, info, warn};

Expand Down Expand Up @@ -80,7 +80,7 @@ impl TimelineInner {
encryption_info: None,
};

let flow = Flow::Local { txn_id };
let flow = Flow::Local { txn_id, timestamp: MilliSecondsSinceUnixEpoch::now() };
let kind = TimelineEventKind::Message { content };

let mut timeline_meta = self.metadata.lock().await;
Expand Down
60 changes: 58 additions & 2 deletions crates/matrix-sdk/src/room/timeline/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ async fn invalid_event_content() {
*event_item.key(),
TimelineKey::EventId(event_id!("$eeG0HA0FAZ37wP8kXlNkxx3I").to_owned())
);
assert_eq!(event_item.origin_server_ts(), Some(MilliSecondsSinceUnixEpoch(uint!(10))));
assert_eq!(event_item.timestamp(), MilliSecondsSinceUnixEpoch(uint!(10)));
let event_type = assert_matches!(
event_item.content(),
TimelineItemContent::FailedToParseMessageLike { event_type, .. } => event_type
Expand All @@ -333,7 +333,7 @@ async fn invalid_event_content() {
*event_item.key(),
TimelineKey::EventId(event_id!("$d5G0HA0FAZ37wP8kXlNkxx3I").to_owned())
);
assert_eq!(event_item.origin_server_ts(), Some(MilliSecondsSinceUnixEpoch(uint!(2179))));
assert_eq!(event_item.timestamp(), MilliSecondsSinceUnixEpoch(uint!(2179)));
let (event_type, state_key) = assert_matches!(
event_item.content(),
TimelineItemContent::FailedToParseState {
Expand Down Expand Up @@ -366,6 +366,48 @@ async fn invalid_event() {
assert_eq!(timeline.inner.items.lock_ref().len(), 0);
}

#[async_test]
async fn remote_echo_without_txn_id() {
let timeline = TestTimeline::new(&ALICE);
let mut stream = timeline.stream();

// Given a local event…
let txn_id = timeline
.handle_local_event(AnyMessageLikeEventContent::RoomMessage(
RoomMessageEventContent::text_plain("echo"),
))
.await;

let item = assert_matches!(stream.next().await, Some(VecDiff::Push { value }) => value);
assert_matches!(item.as_event().unwrap().key(), TimelineKey::TransactionId(_));

// That has an event ID assigned already (from the response to sending it)…
let event_id = event_id!("$W6mZSLWMmfuQQ9jhZWeTxFIM");
timeline.inner.add_event_id(&txn_id, event_id.to_owned());

let item =
assert_matches!(stream.next().await, Some(VecDiff::UpdateAt { value, index: 0 }) => value);
assert_matches!(item.as_event().unwrap().key(), TimelineKey::TransactionId(_));

// When an event with the same ID comes in…
timeline
.handle_live_custom_event(json!({
"content": {
"body": "echo",
"msgtype": "m.text",
},
"sender": &*ALICE,
"event_id": event_id,
"origin_server_ts": 5,
"type": "m.room.message",
}))
.await;

let item =
assert_matches!(stream.next().await, Some(VecDiff::UpdateAt { value, index: 0 }) => value);
assert_matches!(item.as_event().unwrap().key(), TimelineKey::EventId(_));
}

#[async_test]
async fn day_divider() {
let timeline = TestTimeline::new(&ALICE);
Expand Down Expand Up @@ -436,6 +478,20 @@ async fn day_divider() {

let item = assert_matches!(stream.next().await, Some(VecDiff::Push { value }) => value);
item.as_event().unwrap();

let _ = timeline
.handle_local_event(AnyMessageLikeEventContent::RoomMessage(
RoomMessageEventContent::text_plain("A message I'm sending just now"),
))
.await;

// The other events are in the past so a local event always creates a new day
// divider.
let day_divider = assert_matches!(stream.next().await, Some(VecDiff::Push { value }) => value);
assert_matches!(day_divider.as_virtual().unwrap(), VirtualTimelineItem::DayDivider { .. });

let item = assert_matches!(stream.next().await, Some(VecDiff::Push { value }) => value);
item.as_event().unwrap();
}

struct TestTimeline {
Expand Down
6 changes: 2 additions & 4 deletions crates/matrix-sdk/tests/integration/room/timeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ async fn edit() {
let second =
assert_matches!(timeline_stream.next().await, Some(VecDiff::Push { value }) => value);
let item = second.as_event().unwrap();
assert_eq!(item.origin_server_ts(), Some(MilliSecondsSinceUnixEpoch(uint!(152038280))));
assert_eq!(item.timestamp(), MilliSecondsSinceUnixEpoch(uint!(152038280)));
assert!(item.event_id().is_some());
assert!(!item.is_own());
assert!(item.raw().is_some());
Expand Down Expand Up @@ -184,7 +184,6 @@ async fn echo() {
assert!(item.event_id().is_none());
assert!(item.is_own());
assert_matches!(item.key(), TimelineKey::TransactionId(_));
assert_eq!(item.origin_server_ts(), None);
assert_matches!(item.raw(), None);

let msg = assert_matches!(item.content(), TimelineItemContent::Message(msg) => msg);
Expand All @@ -202,7 +201,6 @@ async fn echo() {
assert!(item.event_id().is_some());
assert!(item.is_own());
assert_matches!(item.key(), TimelineKey::TransactionId(_));
assert_eq!(item.origin_server_ts(), None);
assert_matches!(item.raw(), None);

ev_builder.add_joined_room(JoinedRoomBuilder::new(room_id).add_timeline_event(
Expand Down Expand Up @@ -230,7 +228,7 @@ async fn echo() {
let item = remote_echo.as_event().unwrap();
assert!(item.event_id().is_some());
assert!(item.is_own());
assert_eq!(item.origin_server_ts(), Some(MilliSecondsSinceUnixEpoch(uint!(152038280))));
assert_eq!(item.timestamp(), MilliSecondsSinceUnixEpoch(uint!(152038280)));
assert_matches!(item.key(), TimelineKey::EventId(_));
assert_matches!(item.raw(), Some(_));
}
Expand Down
20 changes: 10 additions & 10 deletions labs/jack-in/src/components/details.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,43 +78,43 @@ impl Details {
.map(|e| match e.content() {
TimelineItemContent::Message(m) => format!(
"[{}] {}: {}",
e.origin_server_ts()
.and_then(|r| r.to_system_time())
e.timestamp()
.to_system_time()
.map(|s| DateTime::<Local>::from(s).format("%Y-%m-%dT%T").to_string())
.unwrap_or_default(),
e.sender(),
m.body()
),
TimelineItemContent::RedactedMessage => format!(
"[{}] {} - redacted -",
e.origin_server_ts()
.and_then(|r| r.to_system_time())
e.timestamp()
.to_system_time()
.map(|s| DateTime::<Local>::from(s).format("%Y-%m-%dT%T").to_string())
.unwrap_or_default(),
e.sender(),
),
TimelineItemContent::UnableToDecrypt(_) => format!(
"[{}] {} - unable to decrypt -",
e.origin_server_ts()
.and_then(|r| r.to_system_time())
e.timestamp()
.to_system_time()
.map(|s| DateTime::<Local>::from(s).format("%Y-%m-%dT%T").to_string())
.unwrap_or_default(),
e.sender(),
),
TimelineItemContent::FailedToParseState { event_type, state_key, error } => {
format!(
"[{}] {} - failed to parse {event_type}({state_key}): {error}",
e.origin_server_ts()
.and_then(|r| r.to_system_time())
e.timestamp()
.to_system_time()
.map(|s| DateTime::<Local>::from(s).format("%Y-%m-%dT%T").to_string())
.unwrap_or_default(),
e.sender(),
)
}
TimelineItemContent::FailedToParseMessageLike { event_type, error } => format!(
"[{}] {} - failed to parse {event_type}: {error}",
e.origin_server_ts()
.and_then(|r| r.to_system_time())
e.timestamp()
.to_system_time()
.map(|s| DateTime::<Local>::from(s).format("%Y-%m-%dT%T").to_string())
.unwrap_or_default(),
e.sender(),
Expand Down