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