src/message/mod.rs

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