src/message/mod.rs

876 lines · 27884 bytes

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