src/message/mod.rs
914 lines · 29235 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(format!("[{name} {count}]"), style);
714
715 reactions += 1;
716 }
717
718 if reactions > 0 {
719 fmt.push_text(emojis.finish(), style, &mut text);
720 }
721 }
722
723 return text;
724 }
725
726 pub fn show_msg(&self, width: usize, style: Style, hide_reply: bool) -> Text {
727 if let Some(html) = &self.html {
728 html.to_text(width, style, hide_reply)
729 } else {
730 let mut msg = self.event.body();
731
732 if self.downloaded {
733 msg.to_mut().push_str(" \u{2705}");
734 }
735
736 wrapped_text(msg, width, style)
737 }
738 }
739
740 fn sender_span(&self, settings: &ApplicationSettings) -> Span {
741 settings.get_user_span(self.sender.as_ref())
742 }
743
744 fn show_sender(
745 &self,
746 prev: Option<&Message>,
747 align_right: bool,
748 settings: &ApplicationSettings,
749 ) -> Option<Span> {
750 if let Some(prev) = prev {
751 if self.sender == prev.sender && self.timestamp.same_day(&prev.timestamp) {
752 return None;
753 }
754 }
755
756 let Span { content, style } = self.sender_span(settings);
757 let stop = content.len().min(28);
758 let s = &content[..stop];
759
760 let sender = if align_right {
761 format!("{: >width$} ", s, width = 28)
762 } else {
763 format!("{: <width$} ", s, width = 28)
764 };
765
766 Span::styled(sender, style).into()
767 }
768}
769
770impl From<OriginalRoomMessageEvent> for Message {
771 fn from(event: OriginalRoomMessageEvent) -> Self {
772 let timestamp = event.origin_server_ts.into();
773 let user_id = event.sender.clone();
774 let content = MessageEvent::Original(event.into());
775
776 Message::new(content, user_id, timestamp)
777 }
778}
779
780impl From<RedactedRoomMessageEvent> for Message {
781 fn from(event: RedactedRoomMessageEvent) -> Self {
782 let timestamp = event.origin_server_ts.into();
783 let user_id = event.sender.clone();
784 let content = MessageEvent::Redacted(event.into());
785
786 Message::new(content, user_id, timestamp)
787 }
788}
789
790impl From<RoomMessageEvent> for Message {
791 fn from(event: RoomMessageEvent) -> Self {
792 match event {
793 RoomMessageEvent::Original(ev) => ev.into(),
794 RoomMessageEvent::Redacted(ev) => ev.into(),
795 }
796 }
797}
798
799impl ToString for Message {
800 fn to_string(&self) -> String {
801 self.event.body().into_owned()
802 }
803}
804
805#[cfg(test)]
806pub mod tests {
807 use super::*;
808 use crate::tests::*;
809
810 #[test]
811 fn test_mc_cmp() {
812 let mc1 = MessageCursor::from(MSG1_KEY.clone());
813 let mc2 = MessageCursor::from(MSG2_KEY.clone());
814 let mc3 = MessageCursor::from(MSG3_KEY.clone());
815 let mc4 = MessageCursor::from(MSG4_KEY.clone());
816 let mc5 = MessageCursor::from(MSG5_KEY.clone());
817
818 // Everything is equal to itself.
819 assert_eq!(mc1.cmp(&mc1), Ordering::Equal);
820 assert_eq!(mc2.cmp(&mc2), Ordering::Equal);
821 assert_eq!(mc3.cmp(&mc3), Ordering::Equal);
822 assert_eq!(mc4.cmp(&mc4), Ordering::Equal);
823 assert_eq!(mc5.cmp(&mc5), Ordering::Equal);
824
825 // Local echo is always greater than an origin server timestamp.
826 assert_eq!(mc1.cmp(&mc2), Ordering::Greater);
827 assert_eq!(mc1.cmp(&mc3), Ordering::Greater);
828 assert_eq!(mc1.cmp(&mc4), Ordering::Greater);
829 assert_eq!(mc1.cmp(&mc5), Ordering::Greater);
830
831 // mc2 is the smallest timestamp.
832 assert_eq!(mc2.cmp(&mc1), Ordering::Less);
833 assert_eq!(mc2.cmp(&mc3), Ordering::Less);
834 assert_eq!(mc2.cmp(&mc4), Ordering::Less);
835 assert_eq!(mc2.cmp(&mc5), Ordering::Less);
836
837 // mc3 should be less than mc4 because of its event ID.
838 assert_eq!(mc3.cmp(&mc1), Ordering::Less);
839 assert_eq!(mc3.cmp(&mc2), Ordering::Greater);
840 assert_eq!(mc3.cmp(&mc4), Ordering::Less);
841 assert_eq!(mc3.cmp(&mc5), Ordering::Less);
842
843 // mc4 should be greater than mc3 because of its event ID.
844 assert_eq!(mc4.cmp(&mc1), Ordering::Less);
845 assert_eq!(mc4.cmp(&mc2), Ordering::Greater);
846 assert_eq!(mc4.cmp(&mc3), Ordering::Greater);
847 assert_eq!(mc4.cmp(&mc5), Ordering::Less);
848
849 // mc5 is the greatest OriginServer timestamp.
850 assert_eq!(mc5.cmp(&mc1), Ordering::Less);
851 assert_eq!(mc5.cmp(&mc2), Ordering::Greater);
852 assert_eq!(mc5.cmp(&mc3), Ordering::Greater);
853 assert_eq!(mc5.cmp(&mc4), Ordering::Greater);
854 }
855
856 #[test]
857 fn test_mc_to_key() {
858 let info = mock_room();
859 let mc1 = MessageCursor::from(MSG1_KEY.clone());
860 let mc2 = MessageCursor::from(MSG2_KEY.clone());
861 let mc3 = MessageCursor::from(MSG3_KEY.clone());
862 let mc4 = MessageCursor::from(MSG4_KEY.clone());
863 let mc5 = MessageCursor::from(MSG5_KEY.clone());
864 let mc6 = MessageCursor::latest();
865
866 let k1 = mc1.to_key(&info).unwrap();
867 let k2 = mc2.to_key(&info).unwrap();
868 let k3 = mc3.to_key(&info).unwrap();
869 let k4 = mc4.to_key(&info).unwrap();
870 let k5 = mc5.to_key(&info).unwrap();
871 let k6 = mc6.to_key(&info).unwrap();
872
873 // These should all be equal to their MSGN_KEYs.
874 assert_eq!(k1, &MSG1_KEY.clone());
875 assert_eq!(k2, &MSG2_KEY.clone());
876 assert_eq!(k3, &MSG3_KEY.clone());
877 assert_eq!(k4, &MSG4_KEY.clone());
878 assert_eq!(k5, &MSG5_KEY.clone());
879
880 // MessageCursor::latest() turns into the largest key (our local echo message).
881 assert_eq!(k6, &MSG1_KEY.clone());
882
883 // MessageCursor::latest() fails to convert for a room w/o messages.
884 let info_empty = RoomInfo::default();
885 assert_eq!(mc6.to_key(&info_empty), None);
886 }
887
888 #[test]
889 fn test_mc_to_from_cursor() {
890 let info = mock_room();
891 let mc1 = MessageCursor::from(MSG1_KEY.clone());
892 let mc2 = MessageCursor::from(MSG2_KEY.clone());
893 let mc3 = MessageCursor::from(MSG3_KEY.clone());
894 let mc4 = MessageCursor::from(MSG4_KEY.clone());
895 let mc5 = MessageCursor::from(MSG5_KEY.clone());
896 let mc6 = MessageCursor::latest();
897
898 let identity = |mc: &MessageCursor| {
899 let c = mc.to_cursor(&info).unwrap();
900
901 MessageCursor::from_cursor(&c, &info).unwrap()
902 };
903
904 // These should all convert to a Cursor and back to the original value.
905 assert_eq!(identity(&mc1), mc1);
906 assert_eq!(identity(&mc2), mc2);
907 assert_eq!(identity(&mc3), mc3);
908 assert_eq!(identity(&mc4), mc4);
909 assert_eq!(identity(&mc5), mc5);
910
911 // MessageCursor::latest() should point at the most recent message after conversion.
912 assert_eq!(identity(&mc6), mc1);
913 }
914}