src/message/mod.rs

1417 lines · 45701 bytes

   1//! # Room Messages
   2use std::borrow::Cow;
   3use std::cmp::{Ord, Ordering, PartialOrd};
   4use std::collections::hash_map::DefaultHasher;
   5use std::collections::hash_set;
   6use std::collections::BTreeMap;
   7use std::convert::TryFrom;
   8use std::fmt::{self, Display};
   9use std::hash::{Hash, Hasher};
  10use std::ops::{Deref, DerefMut};
  11
  12use chrono::{DateTime, Local as LocalTz, NaiveDateTime, TimeZone};
  13use humansize::{format_size, DECIMAL};
  14use serde_json::json;
  15use unicode_width::UnicodeWidthStr;
  16
  17use matrix_sdk::ruma::{
  18    events::{
  19        relation::Thread,
  20        room::{
  21            encrypted::{
  22                OriginalRoomEncryptedEvent,
  23                RedactedRoomEncryptedEvent,
  24                RoomEncryptedEvent,
  25            },
  26            message::{
  27                FormattedBody,
  28                MessageFormat,
  29                MessageType,
  30                OriginalRoomMessageEvent,
  31                RedactedRoomMessageEvent,
  32                Relation,
  33                RoomMessageEvent,
  34                RoomMessageEventContent,
  35            },
  36            redaction::SyncRoomRedactionEvent,
  37        },
  38        RedactContent,
  39        RedactedUnsigned,
  40    },
  41    EventId,
  42    MilliSecondsSinceUnixEpoch,
  43    OwnedEventId,
  44    OwnedUserId,
  45    RoomVersionId,
  46    UInt,
  47};
  48
  49use ratatui::{
  50    style::{Modifier as StyleModifier, Style},
  51    symbols::line::THICK_VERTICAL,
  52    text::{Line, Span, Text},
  53};
  54
  55use modalkit::editing::cursor::Cursor;
  56use modalkit::prelude::*;
  57use ratatui_image::protocol::Protocol;
  58
  59use crate::config::ImagePreviewSize;
  60use crate::{
  61    base::RoomInfo,
  62    config::ApplicationSettings,
  63    message::html::{parse_matrix_html, StyleTree},
  64    util::{replace_emojis_in_str, space, space_span, take_width, wrapped_text},
  65};
  66
  67mod compose;
  68mod html;
  69mod printer;
  70
  71pub use self::compose::text_to_message;
  72
  73pub type MessageKey = (MessageTimeStamp, OwnedEventId);
  74
  75#[derive(Default)]
  76pub struct Messages(BTreeMap<MessageKey, Message>);
  77
  78impl Deref for Messages {
  79    type Target = BTreeMap<MessageKey, Message>;
  80
  81    fn deref(&self) -> &Self::Target {
  82        &self.0
  83    }
  84}
  85
  86impl DerefMut for Messages {
  87    fn deref_mut(&mut self) -> &mut Self::Target {
  88        &mut self.0
  89    }
  90}
  91
  92impl Messages {
  93    pub fn insert_message(&mut self, key: MessageKey, msg: impl Into<Message>) {
  94        let event_id = key.1.clone();
  95        let msg = msg.into();
  96
  97        self.0.insert(key, msg);
  98
  99        // Remove any echo.
 100        let key = (MessageTimeStamp::LocalEcho, event_id);
 101        let _ = self.0.remove(&key);
 102    }
 103}
 104
 105const fn span_static(s: &'static str) -> Span<'static> {
 106    Span {
 107        content: Cow::Borrowed(s),
 108        style: Style {
 109            fg: None,
 110            bg: None,
 111            add_modifier: StyleModifier::empty(),
 112            sub_modifier: StyleModifier::empty(),
 113            underline_color: None,
 114        },
 115    }
 116}
 117
 118const BOLD_STYLE: Style = Style {
 119    fg: None,
 120    bg: None,
 121    add_modifier: StyleModifier::BOLD,
 122    sub_modifier: StyleModifier::empty(),
 123    underline_color: None,
 124};
 125
 126const TIME_GUTTER: usize = 12;
 127const READ_GUTTER: usize = 5;
 128const MIN_MSG_LEN: usize = 30;
 129
 130const TIME_GUTTER_EMPTY: &str = "            ";
 131const TIME_GUTTER_EMPTY_SPAN: Span<'static> = span_static(TIME_GUTTER_EMPTY);
 132
 133/// Before the image is loaded, already display a placeholder frame of the image size.
 134fn placeholder_frame(
 135    text: Option<&str>,
 136    outer_width: usize,
 137    image_preview_size: &ImagePreviewSize,
 138) -> Option<String> {
 139    let ImagePreviewSize { width, height } = image_preview_size;
 140    if outer_width < *width || (*width < 2 || *height < 2) {
 141        return None;
 142    }
 143    let mut placeholder = "\u{230c}".to_string();
 144    placeholder.push_str(&" ".repeat(width - 2));
 145    placeholder.push_str("\u{230d}\n");
 146    if *height > 2 {
 147        if let Some(text) = text {
 148            if text.width() <= width - 2 {
 149                placeholder.push(' ');
 150                placeholder.push_str(text);
 151            }
 152        }
 153    }
 154
 155    placeholder.push_str(&"\n".repeat(height - 2));
 156    placeholder.push('\u{230e}');
 157    placeholder.push_str(&" ".repeat(width - 2));
 158    placeholder.push_str("\u{230f}\n");
 159    Some(placeholder)
 160}
 161
 162#[inline]
 163fn millis_to_datetime(ms: UInt) -> DateTime<LocalTz> {
 164    let time = i64::from(ms) / 1000;
 165    let time = NaiveDateTime::from_timestamp_opt(time, 0).unwrap_or_default();
 166
 167    LocalTz.from_utc_datetime(&time)
 168}
 169
 170#[derive(thiserror::Error, Debug)]
 171pub enum TimeStampIntError {
 172    #[error("Integer conversion error: {0}")]
 173    IntError(#[from] std::num::TryFromIntError),
 174
 175    #[error("UInt conversion error: {0}")]
 176    UIntError(<UInt as TryFrom<u64>>::Error),
 177}
 178
 179#[derive(Clone, Copy, Debug, Eq, PartialEq)]
 180pub enum MessageTimeStamp {
 181    OriginServer(UInt),
 182    LocalEcho,
 183}
 184
 185impl MessageTimeStamp {
 186    fn as_datetime(&self) -> DateTime<LocalTz> {
 187        match self {
 188            MessageTimeStamp::OriginServer(ms) => millis_to_datetime(*ms),
 189            MessageTimeStamp::LocalEcho => LocalTz::now(),
 190        }
 191    }
 192
 193    fn same_day(&self, other: &Self) -> bool {
 194        let dt1 = self.as_datetime();
 195        let dt2 = other.as_datetime();
 196
 197        dt1.date_naive() == dt2.date_naive()
 198    }
 199
 200    fn show_date(&self) -> Option<Span> {
 201        let time = self.as_datetime().format("%A, %B %d %Y").to_string();
 202
 203        Span::styled(time, BOLD_STYLE).into()
 204    }
 205
 206    fn show_time(&self) -> Option<Span> {
 207        match self {
 208            MessageTimeStamp::OriginServer(ms) => {
 209                let time = millis_to_datetime(*ms).format("%T");
 210                let time = format!("  [{time}]");
 211
 212                Span::raw(time).into()
 213            },
 214            MessageTimeStamp::LocalEcho => None,
 215        }
 216    }
 217
 218    fn is_local_echo(&self) -> bool {
 219        matches!(self, MessageTimeStamp::LocalEcho)
 220    }
 221
 222    pub fn as_millis(&self) -> Option<MilliSecondsSinceUnixEpoch> {
 223        match self {
 224            MessageTimeStamp::OriginServer(ms) => MilliSecondsSinceUnixEpoch(*ms).into(),
 225            MessageTimeStamp::LocalEcho => None,
 226        }
 227    }
 228}
 229
 230impl Ord for MessageTimeStamp {
 231    fn cmp(&self, other: &Self) -> Ordering {
 232        match (self, other) {
 233            (MessageTimeStamp::OriginServer(_), MessageTimeStamp::LocalEcho) => Ordering::Less,
 234            (MessageTimeStamp::OriginServer(a), MessageTimeStamp::OriginServer(b)) => a.cmp(b),
 235            (MessageTimeStamp::LocalEcho, MessageTimeStamp::OriginServer(_)) => Ordering::Greater,
 236            (MessageTimeStamp::LocalEcho, MessageTimeStamp::LocalEcho) => Ordering::Equal,
 237        }
 238    }
 239}
 240
 241impl PartialOrd for MessageTimeStamp {
 242    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 243        Some(self.cmp(other))
 244    }
 245}
 246
 247impl From<UInt> for MessageTimeStamp {
 248    fn from(millis: UInt) -> Self {
 249        MessageTimeStamp::OriginServer(millis)
 250    }
 251}
 252
 253impl From<MilliSecondsSinceUnixEpoch> for MessageTimeStamp {
 254    fn from(millis: MilliSecondsSinceUnixEpoch) -> Self {
 255        MessageTimeStamp::OriginServer(millis.0)
 256    }
 257}
 258
 259impl TryFrom<&MessageTimeStamp> for usize {
 260    type Error = TimeStampIntError;
 261
 262    fn try_from(ts: &MessageTimeStamp) -> Result<Self, Self::Error> {
 263        let n = match ts {
 264            MessageTimeStamp::LocalEcho => 0,
 265            MessageTimeStamp::OriginServer(u) => usize::try_from(u64::from(*u))?,
 266        };
 267
 268        Ok(n)
 269    }
 270}
 271
 272impl TryFrom<usize> for MessageTimeStamp {
 273    type Error = TimeStampIntError;
 274
 275    fn try_from(u: usize) -> Result<Self, Self::Error> {
 276        if u == 0 {
 277            Ok(MessageTimeStamp::LocalEcho)
 278        } else {
 279            let n = u64::try_from(u)?;
 280            let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?;
 281
 282            Ok(MessageTimeStamp::from(n))
 283        }
 284    }
 285}
 286
 287#[derive(Clone, Debug, Default, Eq, PartialEq)]
 288pub struct MessageCursor {
 289    /// When timestamp is None, the corner is determined by moving backwards from
 290    /// the most recently received message.
 291    pub timestamp: Option<MessageKey>,
 292
 293    /// A row within the [Text] representation of a [Message].
 294    pub text_row: usize,
 295}
 296
 297impl MessageCursor {
 298    pub fn new(timestamp: MessageKey, text_row: usize) -> Self {
 299        MessageCursor { timestamp: Some(timestamp), text_row }
 300    }
 301
 302    /// Get a cursor that refers to the most recent message.
 303    pub fn latest() -> Self {
 304        MessageCursor::default()
 305    }
 306
 307    pub fn to_key<'a>(&'a self, thread: &'a Messages) -> Option<&'a MessageKey> {
 308        if let Some(ref key) = self.timestamp {
 309            Some(key)
 310        } else {
 311            Some(thread.last_key_value()?.0)
 312        }
 313    }
 314
 315    pub fn from_cursor(cursor: &Cursor, thread: &Messages) -> Option<Self> {
 316        let ev_hash = u64::try_from(cursor.get_x()).ok()?;
 317        let ev_term = OwnedEventId::try_from("$").ok()?;
 318
 319        let ts_start = MessageTimeStamp::try_from(cursor.get_y()).ok()?;
 320        let start = (ts_start, ev_term);
 321
 322        for ((ts, event_id), _) in thread.range(&start..) {
 323            let mut hasher = DefaultHasher::new();
 324            event_id.hash(&mut hasher);
 325
 326            if hasher.finish() == ev_hash {
 327                return Self::from((*ts, event_id.clone())).into();
 328            }
 329
 330            if ts > &ts_start {
 331                break;
 332            }
 333        }
 334
 335        // If we can't find the cursor, then go to the nearest timestamp.
 336        thread
 337            .range(start..)
 338            .next()
 339            .map(|((ts, ev), _)| Self::from((*ts, ev.clone())))
 340    }
 341
 342    pub fn to_cursor(&self, thread: &Messages) -> Option<Cursor> {
 343        let (ts, event_id) = self.to_key(thread)?;
 344
 345        let y: usize = usize::try_from(ts).ok()?;
 346
 347        let mut hasher = DefaultHasher::new();
 348        event_id.hash(&mut hasher);
 349        let x = usize::try_from(hasher.finish()).ok()?;
 350
 351        Cursor::new(y, x).into()
 352    }
 353}
 354
 355impl From<Option<MessageKey>> for MessageCursor {
 356    fn from(key: Option<MessageKey>) -> Self {
 357        MessageCursor { timestamp: key, text_row: 0 }
 358    }
 359}
 360
 361impl From<MessageKey> for MessageCursor {
 362    fn from(key: MessageKey) -> Self {
 363        MessageCursor { timestamp: Some(key), text_row: 0 }
 364    }
 365}
 366
 367impl Ord for MessageCursor {
 368    fn cmp(&self, other: &Self) -> Ordering {
 369        match (&self.timestamp, &other.timestamp) {
 370            (None, None) => self.text_row.cmp(&other.text_row),
 371            (None, Some(_)) => Ordering::Greater,
 372            (Some(_), None) => Ordering::Less,
 373            (Some(st), Some(ot)) => {
 374                let pcmp = st.cmp(ot);
 375                let tcmp = self.text_row.cmp(&other.text_row);
 376
 377                pcmp.then(tcmp)
 378            },
 379        }
 380    }
 381}
 382
 383impl PartialOrd for MessageCursor {
 384    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 385        Some(self.cmp(other))
 386    }
 387}
 388
 389fn redaction_reason(ev: &SyncRoomRedactionEvent) -> Option<&str> {
 390    let SyncRoomRedactionEvent::Original(ev) = ev else {
 391        return None;
 392    };
 393
 394    return ev.content.reason.as_deref();
 395}
 396
 397fn redaction_unsigned(ev: SyncRoomRedactionEvent) -> RedactedUnsigned {
 398    let reason = redaction_reason(&ev);
 399    let redacted_because = json!({
 400        "content": {
 401            "reason": reason
 402        },
 403        "event_id": ev.event_id(),
 404        "sender": ev.sender(),
 405        "origin_server_ts": ev.origin_server_ts(),
 406        "unsigned": {},
 407    });
 408    RedactedUnsigned::new(serde_json::from_value(redacted_because).unwrap())
 409}
 410
 411#[derive(Clone)]
 412pub enum MessageEvent {
 413    EncryptedOriginal(Box<OriginalRoomEncryptedEvent>),
 414    EncryptedRedacted(Box<RedactedRoomEncryptedEvent>),
 415    Original(Box<OriginalRoomMessageEvent>),
 416    Redacted(Box<RedactedRoomMessageEvent>),
 417    Local(OwnedEventId, Box<RoomMessageEventContent>),
 418}
 419
 420impl MessageEvent {
 421    pub fn event_id(&self) -> &EventId {
 422        match self {
 423            MessageEvent::EncryptedOriginal(ev) => ev.event_id.as_ref(),
 424            MessageEvent::EncryptedRedacted(ev) => ev.event_id.as_ref(),
 425            MessageEvent::Original(ev) => ev.event_id.as_ref(),
 426            MessageEvent::Redacted(ev) => ev.event_id.as_ref(),
 427            MessageEvent::Local(event_id, _) => event_id.as_ref(),
 428        }
 429    }
 430
 431    pub fn content(&self) -> Option<&RoomMessageEventContent> {
 432        match self {
 433            MessageEvent::EncryptedOriginal(_) => None,
 434            MessageEvent::Original(ev) => Some(&ev.content),
 435            MessageEvent::EncryptedRedacted(_) => None,
 436            MessageEvent::Redacted(_) => None,
 437            MessageEvent::Local(_, content) => Some(content),
 438        }
 439    }
 440
 441    pub fn is_emote(&self) -> bool {
 442        matches!(
 443            self.content(),
 444            Some(RoomMessageEventContent { msgtype: MessageType::Emote(_), .. })
 445        )
 446    }
 447
 448    pub fn body(&self) -> Cow<'_, str> {
 449        match self {
 450            MessageEvent::EncryptedOriginal(_) => "[Unable to decrypt message]".into(),
 451            MessageEvent::Original(ev) => body_cow_content(&ev.content),
 452            MessageEvent::EncryptedRedacted(ev) => body_cow_reason(&ev.unsigned),
 453            MessageEvent::Redacted(ev) => body_cow_reason(&ev.unsigned),
 454            MessageEvent::Local(_, content) => body_cow_content(content),
 455        }
 456    }
 457
 458    pub fn html(&self) -> Option<StyleTree> {
 459        let content = match self {
 460            MessageEvent::EncryptedOriginal(_) => return None,
 461            MessageEvent::EncryptedRedacted(_) => return None,
 462            MessageEvent::Original(ev) => &ev.content,
 463            MessageEvent::Redacted(_) => return None,
 464            MessageEvent::Local(_, content) => content,
 465        };
 466
 467        if let MessageType::Text(content) = &content.msgtype {
 468            if let Some(FormattedBody { format: MessageFormat::Html, body }) = &content.formatted {
 469                Some(parse_matrix_html(body.as_str()))
 470            } else {
 471                None
 472            }
 473        } else {
 474            None
 475        }
 476    }
 477
 478    fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
 479        match self {
 480            MessageEvent::EncryptedOriginal(_) => return,
 481            MessageEvent::EncryptedRedacted(_) => return,
 482            MessageEvent::Redacted(_) => return,
 483            MessageEvent::Local(_, _) => return,
 484            MessageEvent::Original(ev) => {
 485                let redacted = RedactedRoomMessageEvent {
 486                    content: ev.content.clone().redact(version),
 487                    event_id: ev.event_id.clone(),
 488                    sender: ev.sender.clone(),
 489                    origin_server_ts: ev.origin_server_ts,
 490                    room_id: ev.room_id.clone(),
 491                    unsigned: redaction_unsigned(redaction),
 492                };
 493                *self = MessageEvent::Redacted(Box::new(redacted));
 494            },
 495        }
 496    }
 497}
 498
 499/// Macro rule converting a File / Image / Audio / Video to its text content with the shape:
 500/// `[Attached <type>: <content>[ (<human readable file size>)]]`
 501macro_rules! display_file_to_text {
 502    ( $msgtype:ident, $content:expr ) => {
 503        return Cow::Owned(format!(
 504            "[Attached {}: {}{}]",
 505            stringify!($msgtype),
 506            $content.body,
 507            $content
 508                .info
 509                .as_ref()
 510                .map(|info| {
 511                    info.size
 512                        .map(|s| format!(" ({})", format_size(u64::from(s), DECIMAL)))
 513                        .unwrap_or_else(String::new)
 514                })
 515                .unwrap_or_else(String::new)
 516        ))
 517    };
 518}
 519
 520fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
 521    let s = match &content.msgtype {
 522        MessageType::Text(content) => content.body.as_str(),
 523        MessageType::VerificationRequest(_) => "[Verification Request]",
 524        MessageType::Emote(content) => content.body.as_ref(),
 525        MessageType::Notice(content) => content.body.as_str(),
 526        MessageType::ServerNotice(content) => content.body.as_str(),
 527
 528        MessageType::Audio(content) => {
 529            display_file_to_text!(Audio, content);
 530        },
 531        MessageType::File(content) => {
 532            display_file_to_text!(File, content);
 533        },
 534        MessageType::Image(content) => {
 535            display_file_to_text!(Image, content);
 536        },
 537        MessageType::Video(content) => {
 538            display_file_to_text!(Video, content);
 539        },
 540        _ => {
 541            match content.msgtype() {
 542                // Just show the body text for the special Element messages.
 543                "nic.custom.confetti" |
 544                "nic.custom.fireworks" |
 545                "io.element.effect.hearts" |
 546                "io.element.effect.rainfall" |
 547                "io.element.effect.snowfall" |
 548                "io.element.effects.space_invaders" => content.body(),
 549                other => {
 550                    return Cow::Owned(format!("[Unknown message type: {other:?}]"));
 551                },
 552            }
 553        },
 554    };
 555
 556    Cow::Borrowed(s)
 557}
 558
 559fn body_cow_reason(unsigned: &RedactedUnsigned) -> Cow<'_, str> {
 560    let reason = unsigned.redacted_because.content.reason.as_ref();
 561
 562    if let Some(r) = reason {
 563        Cow::Owned(format!("[Redacted: {r:?}]"))
 564    } else {
 565        Cow::Borrowed("[Redacted]")
 566    }
 567}
 568
 569enum MessageColumns {
 570    /// Four columns: sender, message, timestamp, read receipts.
 571    Four,
 572
 573    /// Three columns: sender, message, timestamp.
 574    Three,
 575
 576    /// Two columns: sender, message.
 577    Two,
 578
 579    /// One column: message with sender on line before the message.
 580    One,
 581}
 582
 583impl MessageColumns {
 584    fn user_gutter_width(&self, settings: &ApplicationSettings) -> u16 {
 585        if let MessageColumns::One = self {
 586            0
 587        } else {
 588            settings.tunables.user_gutter_width as u16
 589        }
 590    }
 591}
 592
 593struct MessageFormatter<'a> {
 594    settings: &'a ApplicationSettings,
 595
 596    /// How many columns to print.
 597    cols: MessageColumns,
 598
 599    /// The full, original width.
 600    orig: usize,
 601
 602    /// The width that the message contents need to fill.
 603    fill: usize,
 604
 605    /// The formatted Span for the message sender.
 606    user: Option<Span<'a>>,
 607
 608    /// The time the message was sent.
 609    time: Option<Span<'a>>,
 610
 611    /// The date the message was sent.
 612    date: Option<Span<'a>>,
 613
 614    /// Iterator over the users who have read up to this message.
 615    read: Option<hash_set::Iter<'a, OwnedUserId>>,
 616}
 617
 618impl<'a> MessageFormatter<'a> {
 619    fn width(&self) -> usize {
 620        self.fill
 621    }
 622
 623    #[inline]
 624    fn push_spans(&mut self, prev_line: Line<'a>, style: Style, text: &mut Text<'a>) {
 625        if let Some(date) = self.date.take() {
 626            let len = date.content.as_ref().len();
 627            let padding = self.orig.saturating_sub(len);
 628            let leading = space_span(padding / 2, Style::default());
 629            let trailing = space_span(padding.saturating_sub(padding / 2), Style::default());
 630
 631            text.lines.push(Line::from(vec![leading, date, trailing]));
 632        }
 633
 634        let user_gutter_empty_span =
 635            space_span(self.settings.tunables.user_gutter_width, Style::default());
 636
 637        match self.cols {
 638            MessageColumns::Four => {
 639                let settings = self.settings;
 640                let user = self.user.take().unwrap_or(user_gutter_empty_span);
 641                let time = self.time.take().unwrap_or(TIME_GUTTER_EMPTY_SPAN);
 642
 643                let mut line = vec![user];
 644                line.extend(prev_line.spans);
 645                line.push(time);
 646
 647                // Show read receipts.
 648                let user_char =
 649                    |user: &'a OwnedUserId| -> Span<'a> { settings.get_user_char_span(user) };
 650                let mut read = self.read.iter_mut().flatten();
 651
 652                let a = read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
 653                let b = read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
 654                let c = read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
 655
 656                line.push(Span::raw(" "));
 657                line.push(c);
 658                line.push(b);
 659                line.push(a);
 660                line.push(Span::raw(" "));
 661
 662                text.lines.push(Line::from(line))
 663            },
 664            MessageColumns::Three => {
 665                let user = self.user.take().unwrap_or(user_gutter_empty_span);
 666                let time = self.time.take().unwrap_or_else(|| Span::from(""));
 667
 668                let mut line = vec![user];
 669                line.extend(prev_line.spans);
 670                line.push(time);
 671
 672                text.lines.push(Line::from(line))
 673            },
 674            MessageColumns::Two => {
 675                let user = self.user.take().unwrap_or(user_gutter_empty_span);
 676                let mut line = vec![user];
 677                line.extend(prev_line.spans);
 678
 679                text.lines.push(Line::from(line));
 680            },
 681            MessageColumns::One => {
 682                if let Some(user) = self.user.take() {
 683                    text.lines.push(Line::from(vec![user]));
 684                }
 685
 686                let leading = space_span(2, style);
 687                let mut line = vec![leading];
 688                line.extend(prev_line.spans);
 689
 690                text.lines.push(Line::from(line));
 691            },
 692        }
 693    }
 694
 695    fn push_text(&mut self, append: Text<'a>, style: Style, text: &mut Text<'a>) {
 696        for line in append.lines.into_iter() {
 697            self.push_spans(line, style, text);
 698        }
 699    }
 700
 701    fn push_in_reply(
 702        &mut self,
 703        msg: &'a Message,
 704        style: Style,
 705        text: &mut Text<'a>,
 706        info: &'a RoomInfo,
 707    ) {
 708        let width = self.width();
 709        let w = width.saturating_sub(2);
 710        let shortcodes = self.settings.tunables.message_shortcode_display;
 711        let (mut replied, _) = msg.show_msg(w, style, true, shortcodes);
 712        let mut sender = msg.sender_span(info, self.settings);
 713        let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
 714        let trailing = w.saturating_sub(sender_width + 1);
 715
 716        sender.style = sender.style.patch(style);
 717
 718        self.push_spans(
 719            Line::from(vec![
 720                Span::styled(" ", style),
 721                Span::styled(THICK_VERTICAL, style),
 722                sender,
 723                Span::styled(":", style),
 724                space_span(trailing, style),
 725            ]),
 726            style,
 727            text,
 728        );
 729
 730        for line in replied.lines.iter_mut() {
 731            line.spans.insert(0, Span::styled(THICK_VERTICAL, style));
 732            line.spans.insert(0, Span::styled(" ", style));
 733        }
 734
 735        self.push_text(replied, style, text);
 736    }
 737
 738    fn push_reactions(&mut self, counts: Vec<(&'a str, usize)>, style: Style, text: &mut Text<'a>) {
 739        let mut emojis = printer::TextPrinter::new(self.width(), style, false, false);
 740        let mut reactions = 0;
 741
 742        for (key, count) in counts {
 743            if reactions != 0 {
 744                emojis.push_str(" ", style);
 745            }
 746
 747            let name = if self.settings.tunables.reaction_shortcode_display {
 748                if let Some(emoji) = emojis::get(key) {
 749                    if let Some(short) = emoji.shortcode() {
 750                        short
 751                    } else {
 752                        // No ASCII shortcode name to show.
 753                        continue;
 754                    }
 755                } else if key.chars().all(|c| c.is_ascii_alphanumeric()) {
 756                    key
 757                } else {
 758                    // Not an Emoji or a printable ASCII string.
 759                    continue;
 760                }
 761            } else {
 762                key
 763            };
 764
 765            emojis.push_str("[", style);
 766            emojis.push_str(name, style);
 767            emojis.push_str(" ", style);
 768            emojis.push_span_nobreak(Span::styled(count.to_string(), style));
 769            emojis.push_str("]", style);
 770
 771            reactions += 1;
 772        }
 773
 774        if reactions > 0 {
 775            self.push_text(emojis.finish(), style, text);
 776        }
 777    }
 778
 779    fn push_thread_reply_count(&mut self, len: usize, text: &mut Text<'a>) {
 780        if len == 0 {
 781            return;
 782        }
 783
 784        // If we have threaded replies to this message, show how many.
 785        let plural = len != 1;
 786        let style = Style::default();
 787        let mut threaded =
 788            printer::TextPrinter::new(self.width(), style, false, false).literal(true);
 789        let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD));
 790        threaded.push_str(" \u{2937} ", style);
 791        threaded.push_span_nobreak(len);
 792        if plural {
 793            threaded.push_str(" replies in thread", style);
 794        } else {
 795            threaded.push_str(" reply in thread", style);
 796        }
 797
 798        self.push_text(threaded.finish(), style, text);
 799    }
 800}
 801
 802pub enum ImageStatus {
 803    None,
 804    Downloading(ImagePreviewSize),
 805    Loaded(Box<dyn Protocol>),
 806    Error(String),
 807}
 808
 809pub struct Message {
 810    pub event: MessageEvent,
 811    pub sender: OwnedUserId,
 812    pub timestamp: MessageTimeStamp,
 813    pub downloaded: bool,
 814    pub html: Option<StyleTree>,
 815    pub image_preview: ImageStatus,
 816}
 817
 818impl Message {
 819    pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
 820        let html = event.html();
 821        let downloaded = false;
 822
 823        Message {
 824            event,
 825            sender,
 826            timestamp,
 827            downloaded,
 828            html,
 829            image_preview: ImageStatus::None,
 830        }
 831    }
 832
 833    pub fn reply_to(&self) -> Option<OwnedEventId> {
 834        let content = match &self.event {
 835            MessageEvent::EncryptedOriginal(_) => return None,
 836            MessageEvent::EncryptedRedacted(_) => return None,
 837            MessageEvent::Local(_, content) => content,
 838            MessageEvent::Original(ev) => &ev.content,
 839            MessageEvent::Redacted(_) => return None,
 840        };
 841
 842        match &content.relates_to {
 843            Some(Relation::Reply { in_reply_to }) => Some(in_reply_to.event_id.clone()),
 844            Some(Relation::Thread(Thread {
 845                in_reply_to: Some(in_reply_to),
 846                is_falling_back: false,
 847                ..
 848            })) => Some(in_reply_to.event_id.clone()),
 849            Some(_) | None => None,
 850        }
 851    }
 852
 853    fn thread_root(&self) -> Option<OwnedEventId> {
 854        let content = match &self.event {
 855            MessageEvent::EncryptedOriginal(_) => return None,
 856            MessageEvent::EncryptedRedacted(_) => return None,
 857            MessageEvent::Local(_, content) => content,
 858            MessageEvent::Original(ev) => &ev.content,
 859            MessageEvent::Redacted(_) => return None,
 860        };
 861
 862        match &content.relates_to {
 863            Some(Relation::Thread(Thread {
 864                event_id,
 865                in_reply_to: Some(in_reply_to),
 866                is_falling_back: true,
 867                ..
 868            })) if event_id == &in_reply_to.event_id => Some(event_id.clone()),
 869            Some(_) | None => None,
 870        }
 871    }
 872
 873    fn get_render_style(&self, selected: bool, settings: &ApplicationSettings) -> Style {
 874        let mut style = Style::default();
 875
 876        if selected {
 877            style = style.add_modifier(StyleModifier::REVERSED)
 878        }
 879
 880        if self.timestamp.is_local_echo() {
 881            style = style.add_modifier(StyleModifier::ITALIC);
 882        }
 883
 884        if settings.tunables.message_user_color {
 885            let color = settings.get_user_color(&self.sender);
 886            style = style.fg(color);
 887        }
 888
 889        return style;
 890    }
 891
 892    fn get_render_format<'a>(
 893        &'a self,
 894        prev: Option<&Message>,
 895        width: usize,
 896        info: &'a RoomInfo,
 897        settings: &'a ApplicationSettings,
 898    ) -> MessageFormatter<'a> {
 899        let orig = width;
 900        let date = match &prev {
 901            Some(prev) if prev.timestamp.same_day(&self.timestamp) => None,
 902            _ => self.timestamp.show_date(),
 903        };
 904        let user_gutter = settings.tunables.user_gutter_width;
 905
 906        if user_gutter + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
 907            settings.tunables.read_receipt_display
 908        {
 909            let cols = MessageColumns::Four;
 910            let fill = width - user_gutter - TIME_GUTTER - READ_GUTTER;
 911            let user = self.show_sender(prev, true, info, settings);
 912            let time = self.timestamp.show_time();
 913            let read = info.event_receipts.get(self.event.event_id()).map(|read| read.iter());
 914
 915            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
 916        } else if user_gutter + TIME_GUTTER + MIN_MSG_LEN <= width {
 917            let cols = MessageColumns::Three;
 918            let fill = width - user_gutter - TIME_GUTTER;
 919            let user = self.show_sender(prev, true, info, settings);
 920            let time = self.timestamp.show_time();
 921            let read = None;
 922
 923            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
 924        } else if user_gutter + MIN_MSG_LEN <= width {
 925            let cols = MessageColumns::Two;
 926            let fill = width - user_gutter;
 927            let user = self.show_sender(prev, true, info, settings);
 928            let time = None;
 929            let read = None;
 930
 931            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
 932        } else {
 933            let cols = MessageColumns::One;
 934            let fill = width.saturating_sub(2);
 935            let user = self.show_sender(prev, false, info, settings);
 936            let time = None;
 937            let read = None;
 938
 939            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
 940        }
 941    }
 942
 943    /// Render the message as a [Text] object for the terminal.
 944    ///
 945    /// This will also get the image preview Protocol with an x/y offset.
 946    pub fn show_with_preview<'a>(
 947        &'a self,
 948        prev: Option<&Message>,
 949        selected: bool,
 950        vwctx: &ViewportContext<MessageCursor>,
 951        info: &'a RoomInfo,
 952        settings: &'a ApplicationSettings,
 953    ) -> (Text<'a>, Option<(&dyn Protocol, u16, u16)>) {
 954        let width = vwctx.get_width();
 955
 956        let style = self.get_render_style(selected, settings);
 957        let mut fmt = self.get_render_format(prev, width, info, settings);
 958        let mut text = Text::default();
 959        let width = fmt.width();
 960
 961        // Show the message that this one replied to, if any.
 962        let reply = self
 963            .reply_to()
 964            .or_else(|| self.thread_root())
 965            .and_then(|e| info.get_event(&e));
 966
 967        if let Some(r) = &reply {
 968            fmt.push_in_reply(r, style, &mut text, info);
 969        }
 970
 971        // Now show the message contents, and the inlined reply if we couldn't find it above.
 972        let (msg, proto) = self.show_msg(
 973            width,
 974            style,
 975            reply.is_some(),
 976            settings.tunables.message_shortcode_display,
 977        );
 978
 979        // Given our text so far, determine the image offset.
 980        let proto = proto.map(|p| {
 981            let y_off = text.lines.len() as u16;
 982            let x_off = fmt.cols.user_gutter_width(settings);
 983            // Adjust y_off by 1 if a date was printed before the message to account for the extra line.
 984            let y_off = if fmt.date.is_some() { y_off + 1 } else { y_off };
 985            (p, x_off, y_off)
 986        });
 987
 988        fmt.push_text(msg, style, &mut text);
 989
 990        if text.lines.is_empty() {
 991            // If there was nothing in the body, just show an empty message.
 992            fmt.push_spans(space_span(width, style).into(), style, &mut text);
 993        }
 994
 995        if settings.tunables.reaction_display {
 996            let reactions = info.get_reactions(self.event.event_id());
 997            fmt.push_reactions(reactions, style, &mut text);
 998        }
 999
1000        if let Some(thread) = info.get_thread(Some(self.event.event_id())) {
1001            fmt.push_thread_reply_count(thread.len(), &mut text);
1002        }
1003
1004        (text, proto)
1005    }
1006
1007    pub fn show<'a>(
1008        &'a self,
1009        prev: Option<&Message>,
1010        selected: bool,
1011        vwctx: &ViewportContext<MessageCursor>,
1012        info: &'a RoomInfo,
1013        settings: &'a ApplicationSettings,
1014    ) -> Text<'a> {
1015        self.show_with_preview(prev, selected, vwctx, info, settings).0
1016    }
1017
1018    fn show_msg(
1019        &self,
1020        width: usize,
1021        style: Style,
1022        hide_reply: bool,
1023        emoji_shortcodes: bool,
1024    ) -> (Text, Option<&dyn Protocol>) {
1025        if let Some(html) = &self.html {
1026            (html.to_text(width, style, hide_reply, emoji_shortcodes), None)
1027        } else {
1028            let mut msg = self.event.body();
1029            if emoji_shortcodes {
1030                msg = Cow::Owned(replace_emojis_in_str(msg.as_ref()));
1031            }
1032
1033            if self.downloaded {
1034                msg.to_mut().push_str(" \u{2705}");
1035            }
1036
1037            let mut proto = None;
1038            let placeholder = match &self.image_preview {
1039                ImageStatus::None => None,
1040                ImageStatus::Downloading(image_preview_size) => {
1041                    placeholder_frame(Some("Downloading..."), width, image_preview_size)
1042                },
1043                ImageStatus::Loaded(backend) => {
1044                    proto = Some(backend.as_ref());
1045                    placeholder_frame(None, width, &backend.rect().into())
1046                },
1047                ImageStatus::Error(err) => Some(format!("[Image error: {err}]\n")),
1048            };
1049
1050            if let Some(placeholder) = placeholder {
1051                msg.to_mut().insert_str(0, &placeholder);
1052            }
1053
1054            (wrapped_text(msg, width, style), proto)
1055        }
1056    }
1057
1058    fn sender_span<'a>(
1059        &'a self,
1060        info: &'a RoomInfo,
1061        settings: &'a ApplicationSettings,
1062    ) -> Span<'a> {
1063        settings.get_user_span(self.sender.as_ref(), info)
1064    }
1065
1066    fn show_sender<'a>(
1067        &'a self,
1068        prev: Option<&Message>,
1069        align_right: bool,
1070        info: &'a RoomInfo,
1071        settings: &'a ApplicationSettings,
1072    ) -> Option<Span<'a>> {
1073        if let Some(prev) = prev {
1074            if self.sender == prev.sender &&
1075                self.timestamp.same_day(&prev.timestamp) &&
1076                !self.event.is_emote()
1077            {
1078                return None;
1079            }
1080        }
1081
1082        let Span { content, style } = self.sender_span(info, settings);
1083        let user_gutter = settings.tunables.user_gutter_width;
1084        let ((truncated, width), _) = take_width(content, user_gutter - 2);
1085        let padding = user_gutter - 2 - width;
1086
1087        let sender = if align_right {
1088            space(padding) + &truncated + "  "
1089        } else {
1090            truncated.into_owned() + &space(padding) + "  "
1091        };
1092
1093        Span::styled(sender, style).into()
1094    }
1095
1096    pub fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
1097        self.event.redact(redaction, version);
1098        self.html = None;
1099    }
1100}
1101
1102impl From<RoomEncryptedEvent> for Message {
1103    fn from(event: RoomEncryptedEvent) -> Self {
1104        let timestamp = event.origin_server_ts().into();
1105        let user_id = event.sender().to_owned();
1106        let content = match event {
1107            RoomEncryptedEvent::Original(ev) => MessageEvent::EncryptedOriginal(ev.into()),
1108            RoomEncryptedEvent::Redacted(ev) => MessageEvent::EncryptedRedacted(ev.into()),
1109        };
1110
1111        Message::new(content, user_id, timestamp)
1112    }
1113}
1114
1115impl From<OriginalRoomMessageEvent> for Message {
1116    fn from(event: OriginalRoomMessageEvent) -> Self {
1117        let timestamp = event.origin_server_ts.into();
1118        let user_id = event.sender.clone();
1119        let content = MessageEvent::Original(event.into());
1120
1121        Message::new(content, user_id, timestamp)
1122    }
1123}
1124
1125impl From<RedactedRoomMessageEvent> for Message {
1126    fn from(event: RedactedRoomMessageEvent) -> Self {
1127        let timestamp = event.origin_server_ts.into();
1128        let user_id = event.sender.clone();
1129        let content = MessageEvent::Redacted(event.into());
1130
1131        Message::new(content, user_id, timestamp)
1132    }
1133}
1134
1135impl From<RoomMessageEvent> for Message {
1136    fn from(event: RoomMessageEvent) -> Self {
1137        match event {
1138            RoomMessageEvent::Original(ev) => ev.into(),
1139            RoomMessageEvent::Redacted(ev) => ev.into(),
1140        }
1141    }
1142}
1143
1144impl Display for Message {
1145    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1146        write!(f, "{}", self.event.body())
1147    }
1148}
1149
1150#[cfg(test)]
1151pub mod tests {
1152    use matrix_sdk::ruma::events::room::{
1153        message::{
1154            AudioInfo,
1155            AudioMessageEventContent,
1156            FileInfo,
1157            FileMessageEventContent,
1158            ImageMessageEventContent,
1159            VideoInfo,
1160            VideoMessageEventContent,
1161        },
1162        ImageInfo,
1163    };
1164
1165    use super::*;
1166    use crate::tests::*;
1167
1168    #[test]
1169    fn test_mc_cmp() {
1170        let mc1 = MessageCursor::from(MSG1_KEY.clone());
1171        let mc2 = MessageCursor::from(MSG2_KEY.clone());
1172        let mc3 = MessageCursor::from(MSG3_KEY.clone());
1173        let mc4 = MessageCursor::from(MSG4_KEY.clone());
1174        let mc5 = MessageCursor::from(MSG5_KEY.clone());
1175
1176        // Everything is equal to itself.
1177        assert_eq!(mc1.cmp(&mc1), Ordering::Equal);
1178        assert_eq!(mc2.cmp(&mc2), Ordering::Equal);
1179        assert_eq!(mc3.cmp(&mc3), Ordering::Equal);
1180        assert_eq!(mc4.cmp(&mc4), Ordering::Equal);
1181        assert_eq!(mc5.cmp(&mc5), Ordering::Equal);
1182
1183        // Local echo is always greater than an origin server timestamp.
1184        assert_eq!(mc1.cmp(&mc2), Ordering::Greater);
1185        assert_eq!(mc1.cmp(&mc3), Ordering::Greater);
1186        assert_eq!(mc1.cmp(&mc4), Ordering::Greater);
1187        assert_eq!(mc1.cmp(&mc5), Ordering::Greater);
1188
1189        // mc2 is the smallest timestamp.
1190        assert_eq!(mc2.cmp(&mc1), Ordering::Less);
1191        assert_eq!(mc2.cmp(&mc3), Ordering::Less);
1192        assert_eq!(mc2.cmp(&mc4), Ordering::Less);
1193        assert_eq!(mc2.cmp(&mc5), Ordering::Less);
1194
1195        // mc3 should be less than mc4 because of its event ID.
1196        assert_eq!(mc3.cmp(&mc1), Ordering::Less);
1197        assert_eq!(mc3.cmp(&mc2), Ordering::Greater);
1198        assert_eq!(mc3.cmp(&mc4), Ordering::Less);
1199        assert_eq!(mc3.cmp(&mc5), Ordering::Less);
1200
1201        // mc4 should be greater than mc3 because of its event ID.
1202        assert_eq!(mc4.cmp(&mc1), Ordering::Less);
1203        assert_eq!(mc4.cmp(&mc2), Ordering::Greater);
1204        assert_eq!(mc4.cmp(&mc3), Ordering::Greater);
1205        assert_eq!(mc4.cmp(&mc5), Ordering::Less);
1206
1207        // mc5 is the greatest OriginServer timestamp.
1208        assert_eq!(mc5.cmp(&mc1), Ordering::Less);
1209        assert_eq!(mc5.cmp(&mc2), Ordering::Greater);
1210        assert_eq!(mc5.cmp(&mc3), Ordering::Greater);
1211        assert_eq!(mc5.cmp(&mc4), Ordering::Greater);
1212    }
1213
1214    #[test]
1215    fn test_mc_to_key() {
1216        let messages = mock_messages();
1217        let mc1 = MessageCursor::from(MSG1_KEY.clone());
1218        let mc2 = MessageCursor::from(MSG2_KEY.clone());
1219        let mc3 = MessageCursor::from(MSG3_KEY.clone());
1220        let mc4 = MessageCursor::from(MSG4_KEY.clone());
1221        let mc5 = MessageCursor::from(MSG5_KEY.clone());
1222        let mc6 = MessageCursor::latest();
1223
1224        let k1 = mc1.to_key(&messages).unwrap();
1225        let k2 = mc2.to_key(&messages).unwrap();
1226        let k3 = mc3.to_key(&messages).unwrap();
1227        let k4 = mc4.to_key(&messages).unwrap();
1228        let k5 = mc5.to_key(&messages).unwrap();
1229        let k6 = mc6.to_key(&messages).unwrap();
1230
1231        // These should all be equal to their MSGN_KEYs.
1232        assert_eq!(k1, &MSG1_KEY.clone());
1233        assert_eq!(k2, &MSG2_KEY.clone());
1234        assert_eq!(k3, &MSG3_KEY.clone());
1235        assert_eq!(k4, &MSG4_KEY.clone());
1236        assert_eq!(k5, &MSG5_KEY.clone());
1237
1238        // MessageCursor::latest() turns into the largest key (our local echo message).
1239        assert_eq!(k6, &MSG1_KEY.clone());
1240
1241        // MessageCursor::latest() fails to convert for a room w/o messages.
1242        let messages_empty = Messages::default();
1243        assert_eq!(mc6.to_key(&messages_empty), None);
1244    }
1245
1246    #[test]
1247    fn test_mc_to_from_cursor() {
1248        let messages = mock_messages();
1249        let mc1 = MessageCursor::from(MSG1_KEY.clone());
1250        let mc2 = MessageCursor::from(MSG2_KEY.clone());
1251        let mc3 = MessageCursor::from(MSG3_KEY.clone());
1252        let mc4 = MessageCursor::from(MSG4_KEY.clone());
1253        let mc5 = MessageCursor::from(MSG5_KEY.clone());
1254        let mc6 = MessageCursor::latest();
1255
1256        let identity = |mc: &MessageCursor| {
1257            let c = mc.to_cursor(&messages).unwrap();
1258
1259            MessageCursor::from_cursor(&c, &messages).unwrap()
1260        };
1261
1262        // These should all convert to a Cursor and back to the original value.
1263        assert_eq!(identity(&mc1), mc1);
1264        assert_eq!(identity(&mc2), mc2);
1265        assert_eq!(identity(&mc3), mc3);
1266        assert_eq!(identity(&mc4), mc4);
1267        assert_eq!(identity(&mc5), mc5);
1268
1269        // MessageCursor::latest() should point at the most recent message after conversion.
1270        assert_eq!(identity(&mc6), mc1);
1271    }
1272
1273    #[test]
1274    fn test_placeholder_frame() {
1275        fn pretty_frame_test(str: &str) -> Option<String> {
1276            Some(str[1..].to_string())
1277        }
1278
1279        assert_eq!(
1280            placeholder_frame(None, 4, &ImagePreviewSize { width: 4, height: 4 }),
1281            pretty_frame_test(
1282                r#"
1283⌌  ⌍
1284
1285
1286⌎  ⌏
1287"#
1288            )
1289        );
1290
1291        assert_eq!(placeholder_frame(None, 2, &ImagePreviewSize { width: 4, height: 4 }), None);
1292        assert_eq!(placeholder_frame(None, 4, &ImagePreviewSize { width: 1, height: 4 }), None);
1293
1294        assert_eq!(placeholder_frame(None, 4, &ImagePreviewSize { width: 4, height: 1 }), None);
1295
1296        assert_eq!(
1297            placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 4, height: 4 }),
1298            pretty_frame_test(
1299                r#"
1300⌌  ⌍
1301 OK
1302
1303⌎  ⌏
1304"#
1305            )
1306        );
1307        assert_eq!(
1308            placeholder_frame(Some("idontfit"), 4, &ImagePreviewSize { width: 4, height: 4 }),
1309            pretty_frame_test(
1310                r#"
1311⌌  ⌍
1312
1313
1314⌎  ⌏
1315"#
1316            )
1317        );
1318        assert_eq!(
1319            placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 4, height: 2 }),
1320            pretty_frame_test(
1321                r#"
1322⌌  ⌍
1323⌎  ⌏
1324"#
1325            )
1326        );
1327        assert_eq!(
1328            placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 2, height: 3 }),
1329            pretty_frame_test(
1330                r#"
1331⌌⌍
1332
1333⌎⌏
1334"#
1335            )
1336        );
1337    }
1338
1339    #[test]
1340    fn test_display_attachment_size() {
1341        assert_eq!(
1342            body_cow_content(&RoomMessageEventContent::new(MessageType::Image(
1343                ImageMessageEventContent::plain(
1344                    "Alt text".to_string(),
1345                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1346                )
1347                .info(Some(Box::default()))
1348            ))),
1349            "[Attached Image: Alt text]".to_string()
1350        );
1351
1352        let mut info = ImageInfo::default();
1353        info.size = Some(442630_u32.into());
1354        assert_eq!(
1355            body_cow_content(&RoomMessageEventContent::new(MessageType::Image(
1356                ImageMessageEventContent::plain(
1357                    "Alt text".to_string(),
1358                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1359                )
1360                .info(Some(Box::new(info)))
1361            ))),
1362            "[Attached Image: Alt text (442.63 kB)]".to_string()
1363        );
1364
1365        let mut info = ImageInfo::default();
1366        info.size = Some(12_u32.into());
1367        assert_eq!(
1368            body_cow_content(&RoomMessageEventContent::new(MessageType::Image(
1369                ImageMessageEventContent::plain(
1370                    "Alt text".to_string(),
1371                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1372                )
1373                .info(Some(Box::new(info)))
1374            ))),
1375            "[Attached Image: Alt text (12 B)]".to_string()
1376        );
1377
1378        let mut info = AudioInfo::default();
1379        info.size = Some(4294967295_u32.into());
1380        assert_eq!(
1381            body_cow_content(&RoomMessageEventContent::new(MessageType::Audio(
1382                AudioMessageEventContent::plain(
1383                    "Alt text".to_string(),
1384                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1385                )
1386                .info(Some(Box::new(info)))
1387            ))),
1388            "[Attached Audio: Alt text (4.29 GB)]".to_string()
1389        );
1390
1391        let mut info = FileInfo::default();
1392        info.size = Some(4426300_u32.into());
1393        assert_eq!(
1394            body_cow_content(&RoomMessageEventContent::new(MessageType::File(
1395                FileMessageEventContent::plain(
1396                    "Alt text".to_string(),
1397                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1398                )
1399                .info(Some(Box::new(info)))
1400            ))),
1401            "[Attached File: Alt text (4.43 MB)]".to_string()
1402        );
1403
1404        let mut info = VideoInfo::default();
1405        info.size = Some(44000_u32.into());
1406        assert_eq!(
1407            body_cow_content(&RoomMessageEventContent::new(MessageType::Video(
1408                VideoMessageEventContent::plain(
1409                    "Alt text".to_string(),
1410                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1411                )
1412                .info(Some(Box::new(info)))
1413            ))),
1414            "[Attached Video: Alt text (44 kB)]".to_string()
1415        );
1416    }
1417}