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