src/message/mod.rs
807 lines · 25922 bytes
1use std::borrow::Cow;
2use std::cmp::{Ord, Ordering, PartialOrd};
3use std::collections::hash_map::DefaultHasher;
4use std::collections::BTreeMap;
5use std::convert::TryFrom;
6use std::hash::{Hash, Hasher};
7use std::slice::Iter;
8
9use chrono::{DateTime, NaiveDateTime, Utc};
10use unicode_width::UnicodeWidthStr;
11
12use matrix_sdk::ruma::{
13 events::{
14 room::{
15 message::{
16 FormattedBody,
17 MessageFormat,
18 MessageType,
19 OriginalRoomMessageEvent,
20 RedactedRoomMessageEvent,
21 Relation,
22 RoomMessageEvent,
23 RoomMessageEventContent,
24 },
25 redaction::SyncRoomRedactionEvent,
26 },
27 Redact,
28 },
29 EventId,
30 MilliSecondsSinceUnixEpoch,
31 OwnedEventId,
32 OwnedUserId,
33 RoomVersionId,
34 UInt,
35};
36
37use modalkit::tui::{
38 style::{Modifier as StyleModifier, Style},
39 symbols::line::THICK_VERTICAL,
40 text::{Span, Spans, Text},
41};
42
43use modalkit::editing::{base::ViewportContext, cursor::Cursor};
44
45use crate::{
46 base::{IambResult, RoomInfo},
47 config::ApplicationSettings,
48 message::html::{parse_matrix_html, StyleTree},
49 util::{space_span, wrapped_text},
50};
51
52mod html;
53mod printer;
54
55pub type MessageFetchResult = IambResult<(Option<String>, Vec<RoomMessageEvent>)>;
56pub type MessageKey = (MessageTimeStamp, OwnedEventId);
57pub type Messages = BTreeMap<MessageKey, Message>;
58
59const fn span_static(s: &'static str) -> Span<'static> {
60 Span {
61 content: Cow::Borrowed(s),
62 style: Style {
63 fg: None,
64 bg: None,
65 add_modifier: StyleModifier::empty(),
66 sub_modifier: StyleModifier::empty(),
67 },
68 }
69}
70
71const USER_GUTTER: usize = 30;
72const TIME_GUTTER: usize = 12;
73const READ_GUTTER: usize = 5;
74const MIN_MSG_LEN: usize = 30;
75
76const USER_GUTTER_EMPTY: &str = " ";
77const USER_GUTTER_EMPTY_SPAN: Span<'static> = span_static(USER_GUTTER_EMPTY);
78
79const TIME_GUTTER_EMPTY: &str = " ";
80const TIME_GUTTER_EMPTY_SPAN: Span<'static> = span_static(TIME_GUTTER_EMPTY);
81
82#[derive(thiserror::Error, Debug)]
83pub enum TimeStampIntError {
84 #[error("Integer conversion error: {0}")]
85 IntError(#[from] std::num::TryFromIntError),
86
87 #[error("UInt conversion error: {0}")]
88 UIntError(<UInt as TryFrom<u64>>::Error),
89}
90
91#[derive(Clone, Copy, Debug, Eq, PartialEq)]
92pub enum MessageTimeStamp {
93 OriginServer(UInt),
94 LocalEcho,
95}
96
97impl MessageTimeStamp {
98 fn show(&self) -> Option<Span> {
99 match self {
100 MessageTimeStamp::OriginServer(ts) => {
101 let time = i64::from(*ts) / 1000;
102 let time = NaiveDateTime::from_timestamp_opt(time, 0)?;
103 let time = DateTime::<Utc>::from_utc(time, Utc);
104 let time = time.format("%T");
105 let time = format!(" [{}]", time);
106
107 Span::raw(time).into()
108 },
109 MessageTimeStamp::LocalEcho => None,
110 }
111 }
112
113 fn is_local_echo(&self) -> bool {
114 matches!(self, MessageTimeStamp::LocalEcho)
115 }
116
117 pub fn as_millis(&self) -> Option<MilliSecondsSinceUnixEpoch> {
118 match self {
119 MessageTimeStamp::OriginServer(ms) => MilliSecondsSinceUnixEpoch(*ms).into(),
120 MessageTimeStamp::LocalEcho => None,
121 }
122 }
123}
124
125impl Ord for MessageTimeStamp {
126 fn cmp(&self, other: &Self) -> Ordering {
127 match (self, other) {
128 (MessageTimeStamp::OriginServer(_), MessageTimeStamp::LocalEcho) => Ordering::Less,
129 (MessageTimeStamp::OriginServer(a), MessageTimeStamp::OriginServer(b)) => a.cmp(b),
130 (MessageTimeStamp::LocalEcho, MessageTimeStamp::OriginServer(_)) => Ordering::Greater,
131 (MessageTimeStamp::LocalEcho, MessageTimeStamp::LocalEcho) => Ordering::Equal,
132 }
133 }
134}
135
136impl PartialOrd for MessageTimeStamp {
137 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
138 self.cmp(other).into()
139 }
140}
141
142impl From<MilliSecondsSinceUnixEpoch> for MessageTimeStamp {
143 fn from(millis: MilliSecondsSinceUnixEpoch) -> Self {
144 MessageTimeStamp::OriginServer(millis.0)
145 }
146}
147
148impl TryFrom<&MessageTimeStamp> for usize {
149 type Error = TimeStampIntError;
150
151 fn try_from(ts: &MessageTimeStamp) -> Result<Self, Self::Error> {
152 let n = match ts {
153 MessageTimeStamp::LocalEcho => 0,
154 MessageTimeStamp::OriginServer(u) => usize::try_from(u64::from(*u))?,
155 };
156
157 Ok(n)
158 }
159}
160
161impl TryFrom<usize> for MessageTimeStamp {
162 type Error = TimeStampIntError;
163
164 fn try_from(u: usize) -> Result<Self, Self::Error> {
165 if u == 0 {
166 Ok(MessageTimeStamp::LocalEcho)
167 } else {
168 let n = u64::try_from(u)?;
169 let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?;
170
171 Ok(MessageTimeStamp::OriginServer(n))
172 }
173 }
174}
175
176#[derive(Clone, Debug, Default, Eq, PartialEq)]
177pub struct MessageCursor {
178 /// When timestamp is None, the corner is determined by moving backwards from
179 /// the most recently received message.
180 pub timestamp: Option<MessageKey>,
181
182 /// A row within the [Text] representation of a [Message].
183 pub text_row: usize,
184}
185
186impl MessageCursor {
187 pub fn new(timestamp: MessageKey, text_row: usize) -> Self {
188 MessageCursor { timestamp: Some(timestamp), text_row }
189 }
190
191 /// Get a cursor that refers to the most recent message.
192 pub fn latest() -> Self {
193 MessageCursor::default()
194 }
195
196 pub fn to_key<'a>(&'a self, info: &'a RoomInfo) -> Option<&'a MessageKey> {
197 if let Some(ref key) = self.timestamp {
198 Some(key)
199 } else {
200 Some(info.messages.last_key_value()?.0)
201 }
202 }
203
204 pub fn from_cursor(cursor: &Cursor, info: &RoomInfo) -> Option<Self> {
205 let ev_hash = u64::try_from(cursor.get_x()).ok()?;
206 let ev_term = OwnedEventId::try_from("$").ok()?;
207
208 let ts_start = MessageTimeStamp::try_from(cursor.get_y()).ok()?;
209 let start = (ts_start, ev_term);
210 let mut mc = None;
211
212 for ((ts, event_id), _) in info.messages.range(start..) {
213 let mut hasher = DefaultHasher::new();
214 event_id.hash(&mut hasher);
215
216 if hasher.finish() == ev_hash {
217 mc = Self::from((*ts, event_id.clone())).into();
218 break;
219 }
220
221 if mc.is_none() {
222 mc = Self::from((*ts, event_id.clone())).into();
223 }
224
225 if ts > &ts_start {
226 break;
227 }
228 }
229
230 return mc;
231 }
232
233 pub fn to_cursor(&self, info: &RoomInfo) -> Option<Cursor> {
234 let (ts, event_id) = self.to_key(info)?;
235
236 let y: usize = usize::try_from(ts).ok()?;
237
238 let mut hasher = DefaultHasher::new();
239 event_id.hash(&mut hasher);
240 let x = usize::try_from(hasher.finish()).ok()?;
241
242 Cursor::new(y, x).into()
243 }
244}
245
246impl From<Option<MessageKey>> for MessageCursor {
247 fn from(key: Option<MessageKey>) -> Self {
248 MessageCursor { timestamp: key, text_row: 0 }
249 }
250}
251
252impl From<MessageKey> for MessageCursor {
253 fn from(key: MessageKey) -> Self {
254 MessageCursor { timestamp: Some(key), text_row: 0 }
255 }
256}
257
258impl Ord for MessageCursor {
259 fn cmp(&self, other: &Self) -> Ordering {
260 match (&self.timestamp, &other.timestamp) {
261 (None, None) => self.text_row.cmp(&other.text_row),
262 (None, Some(_)) => Ordering::Greater,
263 (Some(_), None) => Ordering::Less,
264 (Some(st), Some(ot)) => {
265 let pcmp = st.cmp(ot);
266 let tcmp = self.text_row.cmp(&other.text_row);
267
268 pcmp.then(tcmp)
269 },
270 }
271 }
272}
273
274impl PartialOrd for MessageCursor {
275 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
276 self.cmp(other).into()
277 }
278}
279
280#[derive(Clone)]
281pub enum MessageEvent {
282 Original(Box<OriginalRoomMessageEvent>),
283 Redacted(Box<RedactedRoomMessageEvent>),
284 Local(OwnedEventId, Box<RoomMessageEventContent>),
285}
286
287impl MessageEvent {
288 pub fn event_id(&self) -> &EventId {
289 match self {
290 MessageEvent::Original(ev) => ev.event_id.as_ref(),
291 MessageEvent::Redacted(ev) => ev.event_id.as_ref(),
292 MessageEvent::Local(event_id, _) => event_id.as_ref(),
293 }
294 }
295
296 pub fn body(&self) -> Cow<'_, str> {
297 match self {
298 MessageEvent::Original(ev) => body_cow_content(&ev.content),
299 MessageEvent::Redacted(ev) => {
300 let reason = ev
301 .unsigned
302 .redacted_because
303 .as_ref()
304 .and_then(|e| e.as_original())
305 .and_then(|r| r.content.reason.as_ref());
306
307 if let Some(r) = reason {
308 Cow::Owned(format!("[Redacted: {:?}]", r))
309 } else {
310 Cow::Borrowed("[Redacted]")
311 }
312 },
313 MessageEvent::Local(_, content) => body_cow_content(content),
314 }
315 }
316
317 pub fn html(&self) -> Option<StyleTree> {
318 let content = match self {
319 MessageEvent::Original(ev) => &ev.content,
320 MessageEvent::Redacted(_) => return None,
321 MessageEvent::Local(_, content) => content,
322 };
323
324 if let MessageType::Text(content) = &content.msgtype {
325 if let Some(FormattedBody { format: MessageFormat::Html, body }) = &content.formatted {
326 Some(parse_matrix_html(body.as_str()))
327 } else {
328 None
329 }
330 } else {
331 None
332 }
333 }
334
335 pub fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
336 match self {
337 MessageEvent::Redacted(_) => return,
338 MessageEvent::Local(_, _) => return,
339 MessageEvent::Original(ev) => {
340 let redacted = ev.clone().redact(redaction, version);
341 *self = MessageEvent::Redacted(Box::new(redacted));
342 },
343 }
344 }
345}
346
347fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
348 let s = match &content.msgtype {
349 MessageType::Text(content) => content.body.as_str(),
350 MessageType::VerificationRequest(_) => "[Verification Request]",
351 MessageType::Emote(content) => content.body.as_ref(),
352 MessageType::Notice(content) => content.body.as_str(),
353 MessageType::ServerNotice(content) => content.body.as_str(),
354
355 MessageType::Audio(content) => {
356 return Cow::Owned(format!("[Attached Audio: {}]", content.body));
357 },
358 MessageType::File(content) => {
359 return Cow::Owned(format!("[Attached File: {}]", content.body));
360 },
361 MessageType::Image(content) => {
362 return Cow::Owned(format!("[Attached Image: {}]", content.body));
363 },
364 MessageType::Video(content) => {
365 return Cow::Owned(format!("[Attached Video: {}]", content.body));
366 },
367 _ => {
368 return Cow::Owned(format!("[Unknown message type: {:?}]", content.msgtype()));
369 },
370 };
371
372 Cow::Borrowed(s)
373}
374
375enum MessageColumns {
376 /// Four columns: sender, message, timestamp, read receipts.
377 Four,
378
379 /// Three columns: sender, message, timestamp.
380 Three,
381
382 /// Two columns: sender, message.
383 Two,
384
385 /// One column: message with sender on line before the message.
386 One,
387}
388
389struct MessageFormatter<'a> {
390 settings: &'a ApplicationSettings,
391 cols: MessageColumns,
392 fill: usize,
393 user: Option<Span<'a>>,
394 time: Option<Span<'a>>,
395 read: Iter<'a, OwnedUserId>,
396}
397
398impl<'a> MessageFormatter<'a> {
399 fn width(&self) -> usize {
400 self.fill
401 }
402
403 #[inline]
404 fn push_spans(&mut self, spans: Spans<'a>, style: Style, text: &mut Text<'a>) {
405 match self.cols {
406 MessageColumns::Four => {
407 let settings = self.settings;
408 let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
409 let time = self.time.take().unwrap_or(TIME_GUTTER_EMPTY_SPAN);
410
411 let mut line = vec![user];
412 line.extend(spans.0);
413 line.push(time);
414
415 // Show read receipts.
416 let user_char =
417 |user: &'a OwnedUserId| -> Span<'a> { settings.get_user_char_span(user) };
418
419 let a = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
420 let b = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
421 let c = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
422
423 line.push(Span::raw(" "));
424 line.push(c);
425 line.push(b);
426 line.push(a);
427 line.push(Span::raw(" "));
428
429 text.lines.push(Spans(line))
430 },
431 MessageColumns::Three => {
432 let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
433 let time = self.time.take().unwrap_or_else(|| Span::from(""));
434
435 let mut line = vec![user];
436 line.extend(spans.0);
437 line.push(time);
438
439 text.lines.push(Spans(line))
440 },
441 MessageColumns::Two => {
442 let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
443 let mut line = vec![user];
444 line.extend(spans.0);
445
446 text.lines.push(Spans(line));
447 },
448 MessageColumns::One => {
449 if let Some(user) = self.user.take() {
450 text.lines.push(Spans(vec![user]));
451 }
452
453 let leading = space_span(2, style);
454 let mut line = vec![leading];
455 line.extend(spans.0);
456
457 text.lines.push(Spans(line));
458 },
459 }
460 }
461
462 fn push_text(&mut self, append: Text<'a>, style: Style, text: &mut Text<'a>) {
463 for line in append.lines.into_iter() {
464 self.push_spans(line, style, text);
465 }
466 }
467}
468
469pub struct Message {
470 pub event: MessageEvent,
471 pub sender: OwnedUserId,
472 pub timestamp: MessageTimeStamp,
473 pub downloaded: bool,
474 pub html: Option<StyleTree>,
475}
476
477impl Message {
478 pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
479 let html = event.html();
480 let downloaded = false;
481
482 Message { event, sender, timestamp, downloaded, html }
483 }
484
485 pub fn reply_to(&self) -> Option<OwnedEventId> {
486 let content = match &self.event {
487 MessageEvent::Local(_, content) => content,
488 MessageEvent::Original(ev) => &ev.content,
489 MessageEvent::Redacted(_) => return None,
490 };
491
492 if let Some(Relation::Reply { in_reply_to }) = &content.relates_to {
493 Some(in_reply_to.event_id.clone())
494 } else {
495 None
496 }
497 }
498
499 fn get_render_style(&self, selected: bool) -> Style {
500 let mut style = Style::default();
501
502 if selected {
503 style = style.add_modifier(StyleModifier::REVERSED)
504 }
505
506 if self.timestamp.is_local_echo() {
507 style = style.add_modifier(StyleModifier::ITALIC);
508 }
509
510 return style;
511 }
512
513 fn get_render_format<'a>(
514 &'a self,
515 prev: Option<&Message>,
516 width: usize,
517 info: &'a RoomInfo,
518 settings: &'a ApplicationSettings,
519 ) -> MessageFormatter<'a> {
520 if USER_GUTTER + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
521 settings.tunables.read_receipt_display
522 {
523 let cols = MessageColumns::Four;
524 let fill = width - USER_GUTTER - TIME_GUTTER - READ_GUTTER;
525 let user = self.show_sender(prev, true, settings);
526 let time = self.timestamp.show();
527 let read = match info.receipts.get(self.event.event_id()) {
528 Some(read) => read.iter(),
529 None => [].iter(),
530 };
531
532 MessageFormatter { settings, cols, fill, user, time, read }
533 } else if USER_GUTTER + TIME_GUTTER + MIN_MSG_LEN <= width {
534 let cols = MessageColumns::Three;
535 let fill = width - USER_GUTTER - TIME_GUTTER;
536 let user = self.show_sender(prev, true, settings);
537 let time = self.timestamp.show();
538 let read = [].iter();
539
540 MessageFormatter { settings, cols, fill, user, time, read }
541 } else if USER_GUTTER + MIN_MSG_LEN <= width {
542 let cols = MessageColumns::Two;
543 let fill = width - USER_GUTTER;
544 let user = self.show_sender(prev, true, settings);
545 let time = None;
546 let read = [].iter();
547
548 MessageFormatter { settings, cols, fill, user, time, read }
549 } else {
550 let cols = MessageColumns::One;
551 let fill = width.saturating_sub(2);
552 let user = self.show_sender(prev, false, settings);
553 let time = None;
554 let read = [].iter();
555
556 MessageFormatter { settings, cols, fill, user, time, read }
557 }
558 }
559
560 pub fn show<'a>(
561 &'a self,
562 prev: Option<&Message>,
563 selected: bool,
564 vwctx: &ViewportContext<MessageCursor>,
565 info: &'a RoomInfo,
566 settings: &'a ApplicationSettings,
567 ) -> Text<'a> {
568 let width = vwctx.get_width();
569
570 let style = self.get_render_style(selected);
571 let mut fmt = self.get_render_format(prev, width, info, settings);
572 let mut text = Text { lines: vec![] };
573 let width = fmt.width();
574
575 // Show the message that this one replied to, if any.
576 let reply = self.reply_to().and_then(|e| info.get_event(&e));
577
578 if let Some(r) = &reply {
579 let w = width.saturating_sub(2);
580 let mut replied = r.show_msg(w, style, true);
581 let mut sender = r.sender_span(settings);
582 let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
583 let trailing = w.saturating_sub(sender_width + 1);
584
585 sender.style = sender.style.patch(style);
586
587 fmt.push_spans(
588 Spans(vec![
589 Span::styled(" ", style),
590 Span::styled(THICK_VERTICAL, style),
591 sender,
592 Span::styled(":", style),
593 space_span(trailing, style),
594 ]),
595 style,
596 &mut text,
597 );
598
599 for line in replied.lines.iter_mut() {
600 line.0.insert(0, Span::styled(THICK_VERTICAL, style));
601 line.0.insert(0, Span::styled(" ", style));
602 }
603
604 fmt.push_text(replied, style, &mut text);
605 }
606
607 // Now show the message contents, and the inlined reply if we couldn't find it above.
608 let msg = self.show_msg(width, style, reply.is_some());
609 fmt.push_text(msg, style, &mut text);
610
611 if text.lines.is_empty() {
612 // If there was nothing in the body, just show an empty message.
613 fmt.push_spans(space_span(width, style).into(), style, &mut text);
614 }
615
616 return text;
617 }
618
619 pub fn show_msg(&self, width: usize, style: Style, hide_reply: bool) -> Text {
620 if let Some(html) = &self.html {
621 html.to_text(width, style, hide_reply)
622 } else {
623 let mut msg = self.event.body();
624
625 if self.downloaded {
626 msg.to_mut().push_str(" \u{2705}");
627 }
628
629 wrapped_text(msg, width, style)
630 }
631 }
632
633 fn sender_span(&self, settings: &ApplicationSettings) -> Span {
634 settings.get_user_span(self.sender.as_ref())
635 }
636
637 fn show_sender(
638 &self,
639 prev: Option<&Message>,
640 align_right: bool,
641 settings: &ApplicationSettings,
642 ) -> Option<Span> {
643 let user = if matches!(prev, Some(prev) if self.sender == prev.sender) {
644 return None;
645 } else {
646 self.sender_span(settings)
647 };
648
649 let Span { content, style } = user;
650 let stop = content.len().min(28);
651 let s = &content[..stop];
652
653 let sender = if align_right {
654 format!("{: >width$} ", s, width = 28)
655 } else {
656 format!("{: <width$} ", s, width = 28)
657 };
658
659 Span::styled(sender, style).into()
660 }
661}
662
663impl From<OriginalRoomMessageEvent> for Message {
664 fn from(event: OriginalRoomMessageEvent) -> Self {
665 let timestamp = event.origin_server_ts.into();
666 let user_id = event.sender.clone();
667 let content = MessageEvent::Original(event.into());
668
669 Message::new(content, user_id, timestamp)
670 }
671}
672
673impl From<RedactedRoomMessageEvent> for Message {
674 fn from(event: RedactedRoomMessageEvent) -> Self {
675 let timestamp = event.origin_server_ts.into();
676 let user_id = event.sender.clone();
677 let content = MessageEvent::Redacted(event.into());
678
679 Message::new(content, user_id, timestamp)
680 }
681}
682
683impl From<RoomMessageEvent> for Message {
684 fn from(event: RoomMessageEvent) -> Self {
685 match event {
686 RoomMessageEvent::Original(ev) => ev.into(),
687 RoomMessageEvent::Redacted(ev) => ev.into(),
688 }
689 }
690}
691
692impl ToString for Message {
693 fn to_string(&self) -> String {
694 self.event.body().into_owned()
695 }
696}
697
698#[cfg(test)]
699pub mod tests {
700 use super::*;
701 use crate::tests::*;
702
703 #[test]
704 fn test_mc_cmp() {
705 let mc1 = MessageCursor::from(MSG1_KEY.clone());
706 let mc2 = MessageCursor::from(MSG2_KEY.clone());
707 let mc3 = MessageCursor::from(MSG3_KEY.clone());
708 let mc4 = MessageCursor::from(MSG4_KEY.clone());
709 let mc5 = MessageCursor::from(MSG5_KEY.clone());
710
711 // Everything is equal to itself.
712 assert_eq!(mc1.cmp(&mc1), Ordering::Equal);
713 assert_eq!(mc2.cmp(&mc2), Ordering::Equal);
714 assert_eq!(mc3.cmp(&mc3), Ordering::Equal);
715 assert_eq!(mc4.cmp(&mc4), Ordering::Equal);
716 assert_eq!(mc5.cmp(&mc5), Ordering::Equal);
717
718 // Local echo is always greater than an origin server timestamp.
719 assert_eq!(mc1.cmp(&mc2), Ordering::Greater);
720 assert_eq!(mc1.cmp(&mc3), Ordering::Greater);
721 assert_eq!(mc1.cmp(&mc4), Ordering::Greater);
722 assert_eq!(mc1.cmp(&mc5), Ordering::Greater);
723
724 // mc2 is the smallest timestamp.
725 assert_eq!(mc2.cmp(&mc1), Ordering::Less);
726 assert_eq!(mc2.cmp(&mc3), Ordering::Less);
727 assert_eq!(mc2.cmp(&mc4), Ordering::Less);
728 assert_eq!(mc2.cmp(&mc5), Ordering::Less);
729
730 // mc3 should be less than mc4 because of its event ID.
731 assert_eq!(mc3.cmp(&mc1), Ordering::Less);
732 assert_eq!(mc3.cmp(&mc2), Ordering::Greater);
733 assert_eq!(mc3.cmp(&mc4), Ordering::Less);
734 assert_eq!(mc3.cmp(&mc5), Ordering::Less);
735
736 // mc4 should be greater than mc3 because of its event ID.
737 assert_eq!(mc4.cmp(&mc1), Ordering::Less);
738 assert_eq!(mc4.cmp(&mc2), Ordering::Greater);
739 assert_eq!(mc4.cmp(&mc3), Ordering::Greater);
740 assert_eq!(mc4.cmp(&mc5), Ordering::Less);
741
742 // mc5 is the greatest OriginServer timestamp.
743 assert_eq!(mc5.cmp(&mc1), Ordering::Less);
744 assert_eq!(mc5.cmp(&mc2), Ordering::Greater);
745 assert_eq!(mc5.cmp(&mc3), Ordering::Greater);
746 assert_eq!(mc5.cmp(&mc4), Ordering::Greater);
747 }
748
749 #[test]
750 fn test_mc_to_key() {
751 let info = mock_room();
752 let mc1 = MessageCursor::from(MSG1_KEY.clone());
753 let mc2 = MessageCursor::from(MSG2_KEY.clone());
754 let mc3 = MessageCursor::from(MSG3_KEY.clone());
755 let mc4 = MessageCursor::from(MSG4_KEY.clone());
756 let mc5 = MessageCursor::from(MSG5_KEY.clone());
757 let mc6 = MessageCursor::latest();
758
759 let k1 = mc1.to_key(&info).unwrap();
760 let k2 = mc2.to_key(&info).unwrap();
761 let k3 = mc3.to_key(&info).unwrap();
762 let k4 = mc4.to_key(&info).unwrap();
763 let k5 = mc5.to_key(&info).unwrap();
764 let k6 = mc6.to_key(&info).unwrap();
765
766 // These should all be equal to their MSGN_KEYs.
767 assert_eq!(k1, &MSG1_KEY.clone());
768 assert_eq!(k2, &MSG2_KEY.clone());
769 assert_eq!(k3, &MSG3_KEY.clone());
770 assert_eq!(k4, &MSG4_KEY.clone());
771 assert_eq!(k5, &MSG5_KEY.clone());
772
773 // MessageCursor::latest() turns into the largest key (our local echo message).
774 assert_eq!(k6, &MSG1_KEY.clone());
775
776 // MessageCursor::latest() fails to convert for a room w/o messages.
777 let info_empty = RoomInfo::default();
778 assert_eq!(mc6.to_key(&info_empty), None);
779 }
780
781 #[test]
782 fn test_mc_to_from_cursor() {
783 let info = mock_room();
784 let mc1 = MessageCursor::from(MSG1_KEY.clone());
785 let mc2 = MessageCursor::from(MSG2_KEY.clone());
786 let mc3 = MessageCursor::from(MSG3_KEY.clone());
787 let mc4 = MessageCursor::from(MSG4_KEY.clone());
788 let mc5 = MessageCursor::from(MSG5_KEY.clone());
789 let mc6 = MessageCursor::latest();
790
791 let identity = |mc: &MessageCursor| {
792 let c = mc.to_cursor(&info).unwrap();
793
794 MessageCursor::from_cursor(&c, &info).unwrap()
795 };
796
797 // These should all convert to a Cursor and back to the original value.
798 assert_eq!(identity(&mc1), mc1);
799 assert_eq!(identity(&mc2), mc2);
800 assert_eq!(identity(&mc3), mc3);
801 assert_eq!(identity(&mc4), mc4);
802 assert_eq!(identity(&mc5), mc5);
803
804 // MessageCursor::latest() should point at the most recent message after conversion.
805 assert_eq!(identity(&mc6), mc1);
806 }
807}