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