src/message/mod.rs

975 lines · 31646 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 content(&self) -> Option<&RoomMessageEventContent> {
346        match self {
347            MessageEvent::EncryptedOriginal(_) => None,
348            MessageEvent::Original(ev) => Some(&ev.content),
349            MessageEvent::EncryptedRedacted(_) => None,
350            MessageEvent::Redacted(_) => None,
351            MessageEvent::Local(_, content) => Some(content),
352        }
353    }
354
355    pub fn is_emote(&self) -> bool {
356        matches!(
357            self.content(),
358            Some(RoomMessageEventContent { msgtype: MessageType::Emote(_), .. })
359        )
360    }
361
362    pub fn body(&self) -> Cow<'_, str> {
363        match self {
364            MessageEvent::EncryptedOriginal(_) => "[Unable to decrypt message]".into(),
365            MessageEvent::Original(ev) => body_cow_content(&ev.content),
366            MessageEvent::EncryptedRedacted(ev) => body_cow_reason(&ev.unsigned),
367            MessageEvent::Redacted(ev) => body_cow_reason(&ev.unsigned),
368            MessageEvent::Local(_, content) => body_cow_content(content),
369        }
370    }
371
372    pub fn html(&self) -> Option<StyleTree> {
373        let content = match self {
374            MessageEvent::EncryptedOriginal(_) => return None,
375            MessageEvent::EncryptedRedacted(_) => return None,
376            MessageEvent::Original(ev) => &ev.content,
377            MessageEvent::Redacted(_) => return None,
378            MessageEvent::Local(_, content) => content,
379        };
380
381        if let MessageType::Text(content) = &content.msgtype {
382            if let Some(FormattedBody { format: MessageFormat::Html, body }) = &content.formatted {
383                Some(parse_matrix_html(body.as_str()))
384            } else {
385                None
386            }
387        } else {
388            None
389        }
390    }
391
392    fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
393        match self {
394            MessageEvent::EncryptedOriginal(_) => return,
395            MessageEvent::EncryptedRedacted(_) => return,
396            MessageEvent::Redacted(_) => return,
397            MessageEvent::Local(_, _) => return,
398            MessageEvent::Original(ev) => {
399                let redacted = ev.clone().redact(redaction, version);
400                *self = MessageEvent::Redacted(Box::new(redacted));
401            },
402        }
403    }
404}
405
406fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
407    let s = match &content.msgtype {
408        MessageType::Text(content) => content.body.as_str(),
409        MessageType::VerificationRequest(_) => "[Verification Request]",
410        MessageType::Emote(content) => content.body.as_ref(),
411        MessageType::Notice(content) => content.body.as_str(),
412        MessageType::ServerNotice(content) => content.body.as_str(),
413
414        MessageType::Audio(content) => {
415            return Cow::Owned(format!("[Attached Audio: {}]", content.body));
416        },
417        MessageType::File(content) => {
418            return Cow::Owned(format!("[Attached File: {}]", content.body));
419        },
420        MessageType::Image(content) => {
421            return Cow::Owned(format!("[Attached Image: {}]", content.body));
422        },
423        MessageType::Video(content) => {
424            return Cow::Owned(format!("[Attached Video: {}]", content.body));
425        },
426        _ => {
427            return Cow::Owned(format!("[Unknown message type: {:?}]", content.msgtype()));
428        },
429    };
430
431    Cow::Borrowed(s)
432}
433
434fn body_cow_reason(unsigned: &RedactedUnsigned) -> Cow<'_, str> {
435    let reason = unsigned
436        .redacted_because
437        .as_ref()
438        .and_then(|e| e.as_original())
439        .and_then(|r| r.content.reason.as_ref());
440
441    if let Some(r) = reason {
442        Cow::Owned(format!("[Redacted: {r:?}]"))
443    } else {
444        Cow::Borrowed("[Redacted]")
445    }
446}
447
448enum MessageColumns {
449    /// Four columns: sender, message, timestamp, read receipts.
450    Four,
451
452    /// Three columns: sender, message, timestamp.
453    Three,
454
455    /// Two columns: sender, message.
456    Two,
457
458    /// One column: message with sender on line before the message.
459    One,
460}
461
462struct MessageFormatter<'a> {
463    settings: &'a ApplicationSettings,
464
465    /// How many columns to print.
466    cols: MessageColumns,
467
468    /// The full, original width.
469    orig: usize,
470
471    /// The width that the message contents need to fill.
472    fill: usize,
473
474    /// The formatted Span for the message sender.
475    user: Option<Span<'a>>,
476
477    /// The time the message was sent.
478    time: Option<Span<'a>>,
479
480    /// The date the message was sent.
481    date: Option<Span<'a>>,
482
483    /// Iterator over the users who have read up to this message.
484    read: Iter<'a, OwnedUserId>,
485}
486
487impl<'a> MessageFormatter<'a> {
488    fn width(&self) -> usize {
489        self.fill
490    }
491
492    #[inline]
493    fn push_spans(&mut self, spans: Spans<'a>, style: Style, text: &mut Text<'a>) {
494        if let Some(date) = self.date.take() {
495            let len = date.content.as_ref().len();
496            let padding = self.orig.saturating_sub(len);
497            let leading = space_span(padding / 2, Style::default());
498            let trailing = space_span(padding.saturating_sub(padding / 2), Style::default());
499
500            text.lines.push(Spans(vec![leading, date, trailing]));
501        }
502
503        match self.cols {
504            MessageColumns::Four => {
505                let settings = self.settings;
506                let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
507                let time = self.time.take().unwrap_or(TIME_GUTTER_EMPTY_SPAN);
508
509                let mut line = vec![user];
510                line.extend(spans.0);
511                line.push(time);
512
513                // Show read receipts.
514                let user_char =
515                    |user: &'a OwnedUserId| -> Span<'a> { settings.get_user_char_span(user) };
516
517                let a = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
518                let b = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
519                let c = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
520
521                line.push(Span::raw(" "));
522                line.push(c);
523                line.push(b);
524                line.push(a);
525                line.push(Span::raw(" "));
526
527                text.lines.push(Spans(line))
528            },
529            MessageColumns::Three => {
530                let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
531                let time = self.time.take().unwrap_or_else(|| Span::from(""));
532
533                let mut line = vec![user];
534                line.extend(spans.0);
535                line.push(time);
536
537                text.lines.push(Spans(line))
538            },
539            MessageColumns::Two => {
540                let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
541                let mut line = vec![user];
542                line.extend(spans.0);
543
544                text.lines.push(Spans(line));
545            },
546            MessageColumns::One => {
547                if let Some(user) = self.user.take() {
548                    text.lines.push(Spans(vec![user]));
549                }
550
551                let leading = space_span(2, style);
552                let mut line = vec![leading];
553                line.extend(spans.0);
554
555                text.lines.push(Spans(line));
556            },
557        }
558    }
559
560    fn push_text(&mut self, append: Text<'a>, style: Style, text: &mut Text<'a>) {
561        for line in append.lines.into_iter() {
562            self.push_spans(line, style, text);
563        }
564    }
565}
566
567pub struct Message {
568    pub event: MessageEvent,
569    pub sender: OwnedUserId,
570    pub timestamp: MessageTimeStamp,
571    pub downloaded: bool,
572    pub html: Option<StyleTree>,
573}
574
575impl Message {
576    pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
577        let html = event.html();
578        let downloaded = false;
579
580        Message { event, sender, timestamp, downloaded, html }
581    }
582
583    pub fn reply_to(&self) -> Option<OwnedEventId> {
584        let content = match &self.event {
585            MessageEvent::EncryptedOriginal(_) => return None,
586            MessageEvent::EncryptedRedacted(_) => return None,
587            MessageEvent::Local(_, content) => content,
588            MessageEvent::Original(ev) => &ev.content,
589            MessageEvent::Redacted(_) => return None,
590        };
591
592        if let Some(Relation::Reply { in_reply_to }) = &content.relates_to {
593            Some(in_reply_to.event_id.clone())
594        } else {
595            None
596        }
597    }
598
599    fn get_render_style(&self, selected: bool) -> Style {
600        let mut style = Style::default();
601
602        if selected {
603            style = style.add_modifier(StyleModifier::REVERSED)
604        }
605
606        if self.timestamp.is_local_echo() {
607            style = style.add_modifier(StyleModifier::ITALIC);
608        }
609
610        return style;
611    }
612
613    fn get_render_format<'a>(
614        &'a self,
615        prev: Option<&Message>,
616        width: usize,
617        info: &'a RoomInfo,
618        settings: &'a ApplicationSettings,
619    ) -> MessageFormatter<'a> {
620        let orig = width;
621        let date = match &prev {
622            Some(prev) if prev.timestamp.same_day(&self.timestamp) => None,
623            _ => self.timestamp.show_date(),
624        };
625
626        if USER_GUTTER + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
627            settings.tunables.read_receipt_display
628        {
629            let cols = MessageColumns::Four;
630            let fill = width - USER_GUTTER - TIME_GUTTER - READ_GUTTER;
631            let user = self.show_sender(prev, true, settings);
632            let time = self.timestamp.show_time();
633            let read = match info.receipts.get(self.event.event_id()) {
634                Some(read) => read.iter(),
635                None => [].iter(),
636            };
637
638            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
639        } else if USER_GUTTER + TIME_GUTTER + MIN_MSG_LEN <= width {
640            let cols = MessageColumns::Three;
641            let fill = width - USER_GUTTER - TIME_GUTTER;
642            let user = self.show_sender(prev, true, settings);
643            let time = self.timestamp.show_time();
644            let read = [].iter();
645
646            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
647        } else if USER_GUTTER + MIN_MSG_LEN <= width {
648            let cols = MessageColumns::Two;
649            let fill = width - USER_GUTTER;
650            let user = self.show_sender(prev, true, settings);
651            let time = None;
652            let read = [].iter();
653
654            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
655        } else {
656            let cols = MessageColumns::One;
657            let fill = width.saturating_sub(2);
658            let user = self.show_sender(prev, false, settings);
659            let time = None;
660            let read = [].iter();
661
662            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
663        }
664    }
665
666    pub fn show<'a>(
667        &'a self,
668        prev: Option<&Message>,
669        selected: bool,
670        vwctx: &ViewportContext<MessageCursor>,
671        info: &'a RoomInfo,
672        settings: &'a ApplicationSettings,
673    ) -> Text<'a> {
674        let width = vwctx.get_width();
675
676        let style = self.get_render_style(selected);
677        let mut fmt = self.get_render_format(prev, width, info, settings);
678        let mut text = Text { lines: vec![] };
679        let width = fmt.width();
680
681        // Show the message that this one replied to, if any.
682        let reply = self.reply_to().and_then(|e| info.get_event(&e));
683
684        if let Some(r) = &reply {
685            let w = width.saturating_sub(2);
686            let mut replied = r.show_msg(w, style, true);
687            let mut sender = r.sender_span(settings);
688            let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
689            let trailing = w.saturating_sub(sender_width + 1);
690
691            sender.style = sender.style.patch(style);
692
693            fmt.push_spans(
694                Spans(vec![
695                    Span::styled(" ", style),
696                    Span::styled(THICK_VERTICAL, style),
697                    sender,
698                    Span::styled(":", style),
699                    space_span(trailing, style),
700                ]),
701                style,
702                &mut text,
703            );
704
705            for line in replied.lines.iter_mut() {
706                line.0.insert(0, Span::styled(THICK_VERTICAL, style));
707                line.0.insert(0, Span::styled(" ", style));
708            }
709
710            fmt.push_text(replied, style, &mut text);
711        }
712
713        // Now show the message contents, and the inlined reply if we couldn't find it above.
714        let msg = self.show_msg(width, style, reply.is_some());
715        fmt.push_text(msg, style, &mut text);
716
717        if text.lines.is_empty() {
718            // If there was nothing in the body, just show an empty message.
719            fmt.push_spans(space_span(width, style).into(), style, &mut text);
720        }
721
722        if settings.tunables.reaction_display {
723            let mut emojis = printer::TextPrinter::new(width, style, false);
724            let mut reactions = 0;
725
726            for (key, count) in info.get_reactions(self.event.event_id()).into_iter() {
727                if reactions != 0 {
728                    emojis.push_str(" ", style);
729                }
730
731                let name = if settings.tunables.reaction_shortcode_display {
732                    if let Some(emoji) = emojis::get(key) {
733                        if let Some(short) = emoji.shortcode() {
734                            short
735                        } else {
736                            // No ASCII shortcode name to show.
737                            continue;
738                        }
739                    } else if key.chars().all(|c| c.is_ascii_alphanumeric()) {
740                        key
741                    } else {
742                        // Not an Emoji or a printable ASCII string.
743                        continue;
744                    }
745                } else {
746                    key
747                };
748
749                emojis.push_str("[", style);
750                emojis.push_str(name, style);
751                emojis.push_str(" ", style);
752                emojis.push_span_nobreak(Span::styled(count.to_string(), style));
753                emojis.push_str("]", style);
754
755                reactions += 1;
756            }
757
758            if reactions > 0 {
759                fmt.push_text(emojis.finish(), style, &mut text);
760            }
761        }
762
763        return text;
764    }
765
766    pub fn show_msg(&self, width: usize, style: Style, hide_reply: bool) -> Text {
767        if let Some(html) = &self.html {
768            html.to_text(width, style, hide_reply)
769        } else {
770            let mut msg = self.event.body();
771
772            if self.downloaded {
773                msg.to_mut().push_str(" \u{2705}");
774            }
775
776            wrapped_text(msg, width, style)
777        }
778    }
779
780    fn sender_span(&self, settings: &ApplicationSettings) -> Span {
781        settings.get_user_span(self.sender.as_ref())
782    }
783
784    fn show_sender(
785        &self,
786        prev: Option<&Message>,
787        align_right: bool,
788        settings: &ApplicationSettings,
789    ) -> Option<Span> {
790        if let Some(prev) = prev {
791            if self.sender == prev.sender &&
792                self.timestamp.same_day(&prev.timestamp) &&
793                !self.event.is_emote()
794            {
795                return None;
796            }
797        }
798
799        let Span { content, style } = self.sender_span(settings);
800        let stop = content.len().min(28);
801        let s = &content[..stop];
802
803        let sender = if align_right {
804            format!("{: >width$}  ", s, width = 28)
805        } else {
806            format!("{: <width$}  ", s, width = 28)
807        };
808
809        Span::styled(sender, style).into()
810    }
811
812    pub fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
813        self.event.redact(redaction, version);
814        self.html = None;
815    }
816}
817
818impl From<RoomEncryptedEvent> for Message {
819    fn from(event: RoomEncryptedEvent) -> Self {
820        let timestamp = event.origin_server_ts().into();
821        let user_id = event.sender().to_owned();
822        let content = match event {
823            RoomEncryptedEvent::Original(ev) => MessageEvent::EncryptedOriginal(ev.into()),
824            RoomEncryptedEvent::Redacted(ev) => MessageEvent::EncryptedRedacted(ev.into()),
825        };
826
827        Message::new(content, user_id, timestamp)
828    }
829}
830
831impl From<OriginalRoomMessageEvent> for Message {
832    fn from(event: OriginalRoomMessageEvent) -> Self {
833        let timestamp = event.origin_server_ts.into();
834        let user_id = event.sender.clone();
835        let content = MessageEvent::Original(event.into());
836
837        Message::new(content, user_id, timestamp)
838    }
839}
840
841impl From<RedactedRoomMessageEvent> for Message {
842    fn from(event: RedactedRoomMessageEvent) -> Self {
843        let timestamp = event.origin_server_ts.into();
844        let user_id = event.sender.clone();
845        let content = MessageEvent::Redacted(event.into());
846
847        Message::new(content, user_id, timestamp)
848    }
849}
850
851impl From<RoomMessageEvent> for Message {
852    fn from(event: RoomMessageEvent) -> Self {
853        match event {
854            RoomMessageEvent::Original(ev) => ev.into(),
855            RoomMessageEvent::Redacted(ev) => ev.into(),
856        }
857    }
858}
859
860impl ToString for Message {
861    fn to_string(&self) -> String {
862        self.event.body().into_owned()
863    }
864}
865
866#[cfg(test)]
867pub mod tests {
868    use super::*;
869    use crate::tests::*;
870
871    #[test]
872    fn test_mc_cmp() {
873        let mc1 = MessageCursor::from(MSG1_KEY.clone());
874        let mc2 = MessageCursor::from(MSG2_KEY.clone());
875        let mc3 = MessageCursor::from(MSG3_KEY.clone());
876        let mc4 = MessageCursor::from(MSG4_KEY.clone());
877        let mc5 = MessageCursor::from(MSG5_KEY.clone());
878
879        // Everything is equal to itself.
880        assert_eq!(mc1.cmp(&mc1), Ordering::Equal);
881        assert_eq!(mc2.cmp(&mc2), Ordering::Equal);
882        assert_eq!(mc3.cmp(&mc3), Ordering::Equal);
883        assert_eq!(mc4.cmp(&mc4), Ordering::Equal);
884        assert_eq!(mc5.cmp(&mc5), Ordering::Equal);
885
886        // Local echo is always greater than an origin server timestamp.
887        assert_eq!(mc1.cmp(&mc2), Ordering::Greater);
888        assert_eq!(mc1.cmp(&mc3), Ordering::Greater);
889        assert_eq!(mc1.cmp(&mc4), Ordering::Greater);
890        assert_eq!(mc1.cmp(&mc5), Ordering::Greater);
891
892        // mc2 is the smallest timestamp.
893        assert_eq!(mc2.cmp(&mc1), Ordering::Less);
894        assert_eq!(mc2.cmp(&mc3), Ordering::Less);
895        assert_eq!(mc2.cmp(&mc4), Ordering::Less);
896        assert_eq!(mc2.cmp(&mc5), Ordering::Less);
897
898        // mc3 should be less than mc4 because of its event ID.
899        assert_eq!(mc3.cmp(&mc1), Ordering::Less);
900        assert_eq!(mc3.cmp(&mc2), Ordering::Greater);
901        assert_eq!(mc3.cmp(&mc4), Ordering::Less);
902        assert_eq!(mc3.cmp(&mc5), Ordering::Less);
903
904        // mc4 should be greater than mc3 because of its event ID.
905        assert_eq!(mc4.cmp(&mc1), Ordering::Less);
906        assert_eq!(mc4.cmp(&mc2), Ordering::Greater);
907        assert_eq!(mc4.cmp(&mc3), Ordering::Greater);
908        assert_eq!(mc4.cmp(&mc5), Ordering::Less);
909
910        // mc5 is the greatest OriginServer timestamp.
911        assert_eq!(mc5.cmp(&mc1), Ordering::Less);
912        assert_eq!(mc5.cmp(&mc2), Ordering::Greater);
913        assert_eq!(mc5.cmp(&mc3), Ordering::Greater);
914        assert_eq!(mc5.cmp(&mc4), Ordering::Greater);
915    }
916
917    #[test]
918    fn test_mc_to_key() {
919        let info = mock_room();
920        let mc1 = MessageCursor::from(MSG1_KEY.clone());
921        let mc2 = MessageCursor::from(MSG2_KEY.clone());
922        let mc3 = MessageCursor::from(MSG3_KEY.clone());
923        let mc4 = MessageCursor::from(MSG4_KEY.clone());
924        let mc5 = MessageCursor::from(MSG5_KEY.clone());
925        let mc6 = MessageCursor::latest();
926
927        let k1 = mc1.to_key(&info).unwrap();
928        let k2 = mc2.to_key(&info).unwrap();
929        let k3 = mc3.to_key(&info).unwrap();
930        let k4 = mc4.to_key(&info).unwrap();
931        let k5 = mc5.to_key(&info).unwrap();
932        let k6 = mc6.to_key(&info).unwrap();
933
934        // These should all be equal to their MSGN_KEYs.
935        assert_eq!(k1, &MSG1_KEY.clone());
936        assert_eq!(k2, &MSG2_KEY.clone());
937        assert_eq!(k3, &MSG3_KEY.clone());
938        assert_eq!(k4, &MSG4_KEY.clone());
939        assert_eq!(k5, &MSG5_KEY.clone());
940
941        // MessageCursor::latest() turns into the largest key (our local echo message).
942        assert_eq!(k6, &MSG1_KEY.clone());
943
944        // MessageCursor::latest() fails to convert for a room w/o messages.
945        let info_empty = RoomInfo::default();
946        assert_eq!(mc6.to_key(&info_empty), None);
947    }
948
949    #[test]
950    fn test_mc_to_from_cursor() {
951        let info = mock_room();
952        let mc1 = MessageCursor::from(MSG1_KEY.clone());
953        let mc2 = MessageCursor::from(MSG2_KEY.clone());
954        let mc3 = MessageCursor::from(MSG3_KEY.clone());
955        let mc4 = MessageCursor::from(MSG4_KEY.clone());
956        let mc5 = MessageCursor::from(MSG5_KEY.clone());
957        let mc6 = MessageCursor::latest();
958
959        let identity = |mc: &MessageCursor| {
960            let c = mc.to_cursor(&info).unwrap();
961
962            MessageCursor::from_cursor(&c, &info).unwrap()
963        };
964
965        // These should all convert to a Cursor and back to the original value.
966        assert_eq!(identity(&mc1), mc1);
967        assert_eq!(identity(&mc2), mc2);
968        assert_eq!(identity(&mc3), mc3);
969        assert_eq!(identity(&mc4), mc4);
970        assert_eq!(identity(&mc5), mc5);
971
972        // MessageCursor::latest() should point at the most recent message after conversion.
973        assert_eq!(identity(&mc6), mc1);
974    }
975}