src/render.rs

2046 lines · 65296 bytes

161 symbols in this file
   1use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
   2use url::Url;
   3
   4use matrix_sdk::{
   5    encryption::verification::{format_emojis, SasVerification, Verification},
   6    ruma::{
   7        events::{
   8            key::verification::{
   9                key::{
  10                    KeyVerificationKeyEventContent,
  11                    ToDeviceKeyVerificationKeyEventContent,
  12                },
  13                ready::{
  14                    KeyVerificationReadyEventContent,
  15                    ToDeviceKeyVerificationReadyEventContent,
  16                },
  17                request::ToDeviceKeyVerificationRequestEventContent,
  18                start::{
  19                    KeyVerificationStartEventContent,
  20                    ToDeviceKeyVerificationStartEventContent,
  21                },
  22            },
  23            room::{
  24                encrypted::RoomEncryptedEventContent,
  25                member::{MembershipChange, RoomMemberEventContent},
  26                message::{
  27                    AudioMessageEventContent, EmoteMessageEventContent,
  28                    FileMessageEventContent, ImageMessageEventContent,
  29                    KeyVerificationRequestEventContent,
  30                    LocationMessageEventContent, MessageFormat,
  31                    NoticeMessageEventContent, RedactedRoomMessageEventContent,
  32                    ServerNoticeMessageEventContent, TextMessageEventContent,
  33                    VideoMessageEventContent,
  34                },
  35                EncryptedFile, EncryptedFileHash, EncryptedFileHashAlgorithm,
  36                EncryptedFileInfo, MediaSource,
  37            },
  38            OriginalSyncStateEvent, RedactedSyncMessageLikeEvent,
  39        },
  40        uint, EventId, MilliSecondsSinceUnixEpoch, MxcUri, OwnedUserId,
  41        TransactionId, UserId,
  42    },
  43};
  44use ruma_html::{
  45    matrix::{AnchorUri, MatrixElement},
  46    Html, NodeData, NodeRef, SanitizerConfig,
  47};
  48
  49use weechat::{Prefix, Weechat};
  50
  51use crate::{room::WeechatRoomMember, utils::ToTag};
  52
  53/// The rendered version of an event.
  54pub struct RenderedEvent {
  55    /// The UNIX timestamp of the event.
  56    pub message_timestamp: isize,
  57    pub prefix: String,
  58    pub content: RenderedContent,
  59}
  60
  61#[derive(Debug, Clone, Copy, Eq, PartialEq)]
  62pub enum ReplyContext {
  63    Inline,
  64    Full,
  65}
  66
  67impl RenderedEvent {
  68    const MSG_TAGS: &'static [&'static str] = &["notify_message"];
  69    const BACKLOG_TAGS: &'static [&'static str] =
  70        &["notify_none", "no_highlight"];
  71    const SELF_TAGS: &'static [&'static str] =
  72        &["notify_none", "no_highlight", "self_msg"];
  73
  74    pub fn add_self_tags(self) -> Self {
  75        self.add_tags(Self::SELF_TAGS)
  76    }
  77
  78    pub fn add_msg_tags(self) -> Self {
  79        self.add_tags(Self::MSG_TAGS)
  80    }
  81
  82    pub fn add_backlog_tags(self) -> Self {
  83        self.add_tags(Self::BACKLOG_TAGS)
  84    }
  85
  86    fn add_tags(mut self, tags: &[&str]) -> Self {
  87        for line in &mut self.content.lines {
  88            line.tags.extend(tags.iter().map(|tag| tag.to_string()))
  89        }
  90
  91        self
  92    }
  93
  94    pub fn add_reply_context(
  95        mut self,
  96        event_id: &EventId,
  97        sender: Option<&str>,
  98        context: ReplyContext,
  99        fetched_body: Option<&str>,
 100    ) -> Self {
 101        let reply_fallback = self.content.reply_fallback.take();
 102        let reply_sender = sender
 103            .map(ToOwned::to_owned)
 104            .or_else(|| {
 105                reply_fallback
 106                    .as_ref()
 107                    .and_then(|fallback| fallback.sender.clone())
 108            })
 109            .unwrap_or_else(|| event_id.as_str().to_owned());
 110        let mut tags = self
 111            .content
 112            .lines
 113            .first()
 114            .map(|line| line.tags.clone())
 115            .unwrap_or_default();
 116        tags.push("matrix_reply".to_owned());
 117        tags.push(format!(
 118            "matrix_reply_sender_hex_{}",
 119            hex_encode(reply_sender.as_bytes())
 120        ));
 121        tags.push(format!("matrix_reply_id_{}", event_id.as_str()));
 122
 123        if context == ReplyContext::Inline {
 124            if let Some(line) = self.content.lines.first_mut() {
 125                line.tags = tags;
 126                line.message = format!("> {}: {}", reply_sender, line.message);
 127            }
 128
 129            return self;
 130        }
 131
 132        let quoted_body = reply_fallback
 133            .as_ref()
 134            .map(|fallback| fallback.body.as_str())
 135            .or(fetched_body);
 136        let mut context_lines = match quoted_body {
 137            Some(body) => {
 138                let mut header_tags = tags.clone();
 139                header_tags.push("matrix_reply_header".to_owned());
 140                let mut lines = vec![RenderedLine {
 141                    tags: header_tags,
 142                    message: format!("Reply to {}:", reply_sender),
 143                }];
 144
 145                lines.extend(reply_quote_lines(body).map(|message| {
 146                    let mut quote_tags = tags.clone();
 147                    quote_tags.push("matrix_reply_quote".to_owned());
 148
 149                    RenderedLine {
 150                        tags: quote_tags,
 151                        message,
 152                    }
 153                }));
 154
 155                lines
 156            }
 157            None => {
 158                tags.push("matrix_reply_header".to_owned());
 159                vec![RenderedLine {
 160                    tags,
 161                    message: format!("Reply to {}", reply_sender),
 162                }]
 163            }
 164        };
 165
 166        self.content.lines.splice(0..0, context_lines.drain(..));
 167
 168        self
 169    }
 170
 171    pub fn has_reply_fallback(&self) -> bool {
 172        self.content.reply_fallback.is_some()
 173    }
 174}
 175
 176fn hex_encode(input: &[u8]) -> String {
 177    const HEX: &[u8; 16] = b"0123456789abcdef";
 178    let mut encoded = String::with_capacity(input.len() * 2);
 179
 180    for byte in input {
 181        encoded.push(HEX[(byte >> 4) as usize] as char);
 182        encoded.push(HEX[(byte & 0x0f) as usize] as char);
 183    }
 184
 185    encoded
 186}
 187
 188#[derive(Debug)]
 189pub struct RenderedLine {
 190    /// The tags of the line.
 191    pub tags: Vec<String>,
 192    /// The message of the line.
 193    pub message: String,
 194}
 195
 196#[derive(Debug)]
 197pub struct RenderedContent {
 198    /// The collection of lines that the event has.
 199    pub lines: Vec<RenderedLine>,
 200    reply_fallback: Option<ReplyFallback>,
 201}
 202
 203impl RenderedContent {
 204    fn new(lines: Vec<RenderedLine>) -> Self {
 205        Self {
 206            lines,
 207            reply_fallback: None,
 208        }
 209    }
 210
 211    fn with_reply_fallback(
 212        mut self,
 213        reply_fallback: Option<ReplyFallback>,
 214    ) -> Self {
 215        self.reply_fallback = reply_fallback;
 216        self
 217    }
 218}
 219
 220#[derive(Clone, Debug)]
 221struct ReplyFallback {
 222    sender: Option<String>,
 223    body: String,
 224}
 225
 226/// Trait allowing events to be rendered for Weechat.
 227pub trait Render {
 228    /// The event specific tags that should be attached to the rendered event.
 229    const TAGS: &'static [&'static str];
 230
 231    /// Some events might need additional context to be rendered. For example,
 232    /// instead of displaying the MXID for the sender, we might want to display
 233    /// the disambiguated display name, which isn't available in the event.
 234    ///
 235    /// This allows the render implementation to be passed some additional data
 236    /// when rendering.
 237    type RenderContext;
 238
 239    fn tags(&self) -> Vec<String> {
 240        Self::TAGS.iter().map(|t| t.to_string()).collect()
 241    }
 242
 243    fn event_tags(
 244        &self,
 245        event_id: &EventId,
 246        sender: &UserId,
 247        nick: &str,
 248        color_name: &str,
 249    ) -> Vec<String> {
 250        let mut tags = self.tags();
 251        let event_tag = event_id.to_tag();
 252        let sender_tag = sender.to_tag();
 253        let nick_tag = format!("nick_{}", nick);
 254        let color = format!("prefix_nick_{}", color_name);
 255        tags.push(event_tag);
 256        tags.push(sender_tag);
 257        tags.push(nick_tag);
 258        tags.push(color);
 259
 260        tags
 261    }
 262
 263    fn prefix(&self, sender: &WeechatRoomMember) -> String {
 264        format!("{}\t", sender.nick_colored())
 265    }
 266
 267    /// Render the event.
 268    fn render_with_prefix(
 269        &self,
 270        timestamp: MilliSecondsSinceUnixEpoch,
 271        event_id: &EventId,
 272        sender: &WeechatRoomMember,
 273        context: &Self::RenderContext,
 274    ) -> RenderedEvent {
 275        let prefix = self.prefix(sender);
 276        let mut content = self.render(context);
 277        let timestamp: i64 = (timestamp.0 / uint!(1000)).into();
 278
 279        let tags = self.event_tags(
 280            event_id,
 281            sender.user_id(),
 282            &sender.nick(),
 283            sender.color(),
 284        );
 285
 286        for line in &mut content.lines {
 287            line.tags = tags.clone();
 288        }
 289
 290        RenderedEvent {
 291            prefix,
 292            message_timestamp: timestamp as isize,
 293            content,
 294        }
 295    }
 296
 297    fn render_with_prefix_for_echo(
 298        &self,
 299        sender: &WeechatRoomMember,
 300        uuid: &TransactionId,
 301        context: &Self::RenderContext,
 302    ) -> RenderedEvent {
 303        let content = self.render_for_echo(uuid, context);
 304        let prefix = self.prefix(sender);
 305
 306        RenderedEvent {
 307            prefix,
 308            message_timestamp: 0,
 309            content,
 310        }
 311    }
 312
 313    fn render_for_echo(
 314        &self,
 315        uuid: &TransactionId,
 316        context: &Self::RenderContext,
 317    ) -> RenderedContent {
 318        let mut content = self.render(context);
 319        let uuid_tag = format!("matrix_echo_{}", uuid);
 320
 321        for line in &mut content.lines {
 322            let message = Weechat::remove_color(&line.message);
 323            line.message = format!(
 324                "{}{}{}",
 325                Weechat::color_pair("darkgray", "default"),
 326                message,
 327                Weechat::color("reset")
 328            );
 329            line.tags.push(uuid_tag.clone())
 330        }
 331
 332        content
 333    }
 334
 335    fn render(&self, context: &Self::RenderContext) -> RenderedContent;
 336}
 337
 338impl Render for TextMessageEventContent {
 339    const TAGS: &'static [&'static str] = &["matrix_text"];
 340    type RenderContext = ();
 341
 342    fn render(&self, _: &Self::RenderContext) -> RenderedContent {
 343        if let Some(body) = self.formatted_body() {
 344            render_formatted_message_body(body, self.tags())
 345        } else {
 346            render_plain_message_body(self.body(), self.tags())
 347        }
 348    }
 349}
 350
 351impl Render for EmoteMessageEventContent {
 352    const TAGS: &'static [&'static str] = &["matrix_emote"];
 353    type RenderContext = WeechatRoomMember;
 354
 355    fn prefix(&self, _: &WeechatRoomMember) -> String {
 356        Weechat::prefix(Prefix::Action)
 357    }
 358
 359    fn render(&self, sender: &Self::RenderContext) -> RenderedContent {
 360        let message = format!(
 361            "{} {}",
 362            sender.nick(),
 363            self.formatted_body()
 364                .map(formatted_body_to_plain_text)
 365                .unwrap_or_else(|| self.body().to_owned())
 366        );
 367
 368        let line = RenderedLine {
 369            message,
 370            tags: self.tags(),
 371        };
 372
 373        RenderedContent::new(vec![line])
 374    }
 375}
 376
 377impl Render for LocationMessageEventContent {
 378    const TAGS: &'static [&'static str] = &["matrix_location"];
 379    type RenderContext = WeechatRoomMember;
 380
 381    fn prefix(&self, _: &WeechatRoomMember) -> String {
 382        Weechat::prefix(Prefix::Action)
 383    }
 384
 385    fn render(&self, sender: &Self::RenderContext) -> RenderedContent {
 386        let message = format!(
 387            "{} has shared a location: {color_delimiter}<{color_reset}{}{color_delimiter}>\
 388            [{color_reset}{}{color_delimiter}]{color_reset}",
 389            sender.nick(),
 390            self.body,
 391            self.geo_uri,
 392            color_delimiter = Weechat::color("color_delimiter"),
 393            color_reset = Weechat::color("reset")
 394        );
 395
 396        let line = RenderedLine {
 397            message,
 398            tags: self.tags(),
 399        };
 400
 401        RenderedContent::new(vec![line])
 402    }
 403}
 404
 405impl Render for NoticeMessageEventContent {
 406    const TAGS: &'static [&'static str] = &["matrix_notice"];
 407    type RenderContext = WeechatRoomMember;
 408
 409    fn prefix(&self, _: &WeechatRoomMember) -> String {
 410        Weechat::prefix(Prefix::Network)
 411    }
 412
 413    fn render(&self, sender: &Self::RenderContext) -> RenderedContent {
 414        let message = format!(
 415            "{color_notice}Notice\
 416            {color_delim}({color_reset}{}{color_delim}){color_reset}: {}",
 417            sender.nick(),
 418            self.formatted_body()
 419                .map(formatted_body_to_plain_text)
 420                .unwrap_or_else(|| self.body().to_owned()),
 421            color_notice = Weechat::color("irc.color.notice"),
 422            color_delim = Weechat::color("chat_delimiters"),
 423            color_reset = Weechat::color("reset"),
 424        );
 425
 426        let line = RenderedLine {
 427            message,
 428            tags: self.tags(),
 429        };
 430
 431        RenderedContent::new(vec![line])
 432    }
 433}
 434
 435impl Render for ServerNoticeMessageEventContent {
 436    const TAGS: &'static [&'static str] = &["matrix_server_notice"];
 437    type RenderContext = WeechatRoomMember;
 438
 439    fn prefix(&self, _: &WeechatRoomMember) -> String {
 440        Weechat::prefix(Prefix::Network)
 441    }
 442
 443    fn render(&self, sender: &Self::RenderContext) -> RenderedContent {
 444        let message = format!(
 445            "{color_notice}Server notice\
 446            {color_delim}({color_reset}{}{color_delim}){color_reset}: {}",
 447            sender.nick(),
 448            self.body,
 449            color_notice = Weechat::color("irc.color.notice"),
 450            color_delim = Weechat::color("chat_delimiters"),
 451            color_reset = Weechat::color("reset"),
 452        );
 453
 454        let line = RenderedLine {
 455            message,
 456            tags: self.tags(),
 457        };
 458
 459        RenderedContent::new(vec![line])
 460    }
 461}
 462
 463/// Create an HTTP download path from a matrix content URI
 464fn mxc_to_http_download_path(
 465    mxc_url: Url,
 466) -> Result<String, Box<dyn std::error::Error>> {
 467    Ok(format!(
 468        "/_matrix/media/r0/download/{server_name}{media_id}",
 469        server_name = mxc_url.host_str().ok_or("Missing host")?,
 470        media_id = mxc_url.path(),
 471    ))
 472}
 473
 474/// Convert a matrix content URI to HTTP(s), respecting a user's homeserver
 475fn mxc_to_http(
 476    mxc_url: &MxcUri,
 477    homeserver: &Url,
 478) -> Result<String, Box<dyn std::error::Error>> {
 479    let url = url::Url::parse(mxc_url.as_str())?;
 480
 481    if url.scheme() != "mxc" {
 482        return Err("URL missing MXC scheme".into());
 483    }
 484
 485    if url.path().is_empty() {
 486        return Err("URL missing path".into());
 487    }
 488
 489    Ok(homeserver
 490        .join(&mxc_to_http_download_path(url)?)?
 491        .to_string())
 492}
 493
 494/// Convert a matrix content URI to an encrypted mxc URI, respecting a user's homeserver.
 495///
 496/// The return value of this function will have a URI schema of emxc://. The path of the URI will
 497/// be converted just like the mxc_to_http() function does, but it will also contain query
 498/// parameters that are necessary to decrypt the payload the URI is pointing to.
 499///
 500/// This function is useful to present a clickable URI that can be passed to a plumber program that
 501/// will download and decrypt the content that the matrix content URI is pointing to.
 502///
 503/// The returned URI should never be converted to http and opened directly, as that would expose
 504/// the decryption parameters to any middleman or ISP.
 505fn mxc_to_emxc(
 506    mxc_url: &MxcUri,
 507    homeserver: &Url,
 508    encrypted: &EncryptedFile,
 509) -> Result<String, Box<dyn std::error::Error>> {
 510    let url = url::Url::parse(mxc_url.as_str())?;
 511
 512    if url.scheme() != "mxc" {
 513        return Err("URL missing MXC scheme".into());
 514    }
 515
 516    if url.path().is_empty() {
 517        return Err("URL missing path".into());
 518    }
 519
 520    let host_str = format!(
 521        "emxc://{}",
 522        homeserver
 523            .host_str()
 524            .ok_or("Missing homeserver host string")?
 525    );
 526
 527    let mut emxc_url = url::Url::parse(&host_str)?;
 528    emxc_url
 529        .set_port(homeserver.port_or_known_default())
 530        .map_err(|_| "Can't set port")?;
 531
 532    emxc_url = emxc_url.join(&mxc_to_http_download_path(url)?)?;
 533
 534    // Add query parameters
 535    let EncryptedFileInfo::V2(info) = &encrypted.info else {
 536        return Err("Unsupported encrypted media info version".into());
 537    };
 538    let Some(EncryptedFileHash::Sha256(hash)) =
 539        encrypted.hashes.get(&EncryptedFileHashAlgorithm::Sha256)
 540    else {
 541        return Err("Missing sha256 hash".into());
 542    };
 543
 544    emxc_url
 545        .query_pairs_mut()
 546        .append_pair("key", &info.k.encode())
 547        .append_pair("hash", &hash.encode())
 548        .append_pair("iv", &info.iv.encode());
 549
 550    Ok(emxc_url.to_string())
 551}
 552
 553fn media_download_command(source: &MediaSource) -> Option<String> {
 554    match source {
 555        MediaSource::Plain(url) => {
 556            Some(format!("/matrix media download {} [file]", url.as_str()))
 557        }
 558        MediaSource::Encrypted(_) => None,
 559    }
 560}
 561
 562fn media_download_message<C: HasUrlOrFile>(content: &C) -> Option<String> {
 563    media_download_command(content.source()).map(|command| {
 564        format!(
 565            "attached `{}`, authenticated download: {}",
 566            content.body(),
 567            command
 568        )
 569    })
 570}
 571
 572fn media_tags<C: HasUrlOrFile>(content: &C) -> Vec<String> {
 573    let mut tags = vec![
 574        "matrix_media".to_owned(),
 575        format!("matrix_media_kind_{}", content.media_kind()),
 576        format!(
 577            "matrix_media_name_{}",
 578            URL_SAFE_NO_PAD.encode(content.body())
 579        ),
 580    ];
 581
 582    if let MediaSource::Plain(uri) = content.source() {
 583        tags.push(format!(
 584            "matrix_media_uri_{}",
 585            URL_SAFE_NO_PAD.encode(uri.as_str())
 586        ));
 587    }
 588
 589    tags
 590}
 591
 592impl<C: HasUrlOrFile> Render for C {
 593    type RenderContext = Url;
 594    const TAGS: &'static [&'static str] = &["matrix_media"];
 595
 596    fn tags(&self) -> Vec<String> {
 597        media_tags(self)
 598    }
 599
 600    fn render(&self, homeserver: &Self::RenderContext) -> RenderedContent {
 601        // Convert MXC to HTTP(s) or EMXC, but fallback to MXC if unable to.
 602        let mxc_url = match self.encrypted_file() {
 603            Some(encrypted_file) => {
 604                mxc_to_emxc(self.resolve_url(), homeserver, encrypted_file)
 605            }
 606            None => mxc_to_http(self.resolve_url(), homeserver),
 607        }
 608        .unwrap_or_else(|_| self.resolve_url().to_string());
 609
 610        let message = media_download_message(self).unwrap_or_else(|| {
 611            format!(
 612                "{color_delimiter}<{color_reset}{}{color_delimiter}>\
 613                    [{color_reset}{}{color_delimiter}]{color_reset}",
 614                self.body(),
 615                mxc_url,
 616                color_delimiter = Weechat::color("color_delimiter"),
 617                color_reset = Weechat::color("reset")
 618            )
 619        });
 620
 621        let line = RenderedLine {
 622            message,
 623            tags: self.tags(),
 624        };
 625
 626        RenderedContent::new(vec![line])
 627    }
 628}
 629
 630impl Render for RoomEncryptedEventContent {
 631    const TAGS: &'static [&'static str] = &["matrix_encrypted"];
 632    type RenderContext = WeechatRoomMember;
 633
 634    fn render(&self, sender: &Self::RenderContext) -> RenderedContent {
 635        let line = RenderedLine {
 636            message: encrypted_placeholder_message(&sender.nick()),
 637            // TODO: add tags that allow us decrypt the event at a later point
 638            // in time, sender key, algorithm, session id.
 639            tags: self.tags(),
 640        };
 641
 642        RenderedContent::new(vec![line])
 643    }
 644}
 645
 646fn encrypted_placeholder_message(sender_nick: &str) -> String {
 647    // The prefix already shows the sender, but naming them in the placeholder
 648    // makes the guidance unambiguous. Keep it one line: decrypted replacement
 649    // rewrites placeholders in place and WeeChat cannot delete surplus lines.
 650    format!(
 651        "{}<{}{}{}>{} {}",
 652        Weechat::color("chat_delimiters"),
 653        Weechat::color("logger.color.backlog_line"),
 654        encrypted_placeholder_body(sender_nick),
 655        Weechat::color("chat_delimiters"),
 656        Weechat::color("reset"),
 657        encrypted_placeholder_guidance(sender_nick),
 658    )
 659}
 660
 661fn encrypted_placeholder_body(sender_nick: &str) -> String {
 662    format!("Unable to decrypt message from {sender_nick}")
 663}
 664
 665fn encrypted_placeholder_guidance(sender_nick: &str) -> String {
 666    format!(
 667        "Waiting for the room key from {}; this message will be decrypted \
 668         automatically once the key arrives.",
 669        sender_nick,
 670    )
 671}
 672
 673impl Render for RedactedSyncMessageLikeEvent<RedactedRoomMessageEventContent> {
 674    type RenderContext = WeechatRoomMember;
 675    const TAGS: &'static [&'static str] = &["matrix_redacted"];
 676
 677    fn render(&self, redacter: &Self::RenderContext) -> RenderedContent {
 678        // TODO: add the redaction reason.
 679        let message = format!(
 680            "{}<{}Message redacted by: {}{}>{}",
 681            Weechat::color("chat_delimiters"),
 682            Weechat::color("logger.color.backlog_line"),
 683            redacter.nick(),
 684            Weechat::color("chat_delimiters"),
 685            Weechat::color("reset"),
 686        );
 687
 688        let line = RenderedLine {
 689            message,
 690            tags: self.tags(),
 691        };
 692
 693        RenderedContent::new(vec![line])
 694    }
 695}
 696
 697pub enum StartVerificationContext {
 698    Room(OwnedUserId, Verification),
 699    ToDevice(OwnedUserId, Verification),
 700}
 701
 702impl StartVerificationContext {
 703    fn sender(&self) -> &UserId {
 704        match self {
 705            StartVerificationContext::Room(s, _) => &s,
 706            StartVerificationContext::ToDevice(s, _) => &s,
 707        }
 708    }
 709
 710    fn verification(&self) -> &Verification {
 711        match self {
 712            StartVerificationContext::Room(_, v) => &v,
 713            StartVerificationContext::ToDevice(_, v) => &v,
 714        }
 715    }
 716
 717    fn is_self_verification(&self) -> bool {
 718        self.verification().is_self_verification()
 719    }
 720}
 721
 722macro_rules! render_start_content {
 723    ($type: ident) => {
 724        impl Render for $type {
 725            const TAGS: &'static [&'static str] = &[];
 726
 727            type RenderContext = StartVerificationContext;
 728
 729            fn prefix(&self, _: &WeechatRoomMember) -> String {
 730                Weechat::prefix(Prefix::Network)
 731            }
 732
 733            fn render(&self, context: &Self::RenderContext) -> RenderedContent {
 734                let message = match context.verification() {
 735                    Verification::SasV1(sas) => {
 736                        if context.sender() == sas.own_user_id() {
 737                            if context.is_self_verification() {
 738                                if sas.started_from_request() {
 739                                    // We auto accept emoji verifications that start
 740                                    // from a verification request, so don't print
 741                                    // anything.
 742                                    return RenderedContent::new(vec![]);
 743                                } else {
 744                                    format!(
 745                                        "You have started an interactive emoji \
 746                                            verification, accept on your other device.",
 747                                    )
 748                                }
 749                            } else {
 750                                format!(
 751                                    "You have started an interactive emoji \
 752                                        verification, waiting for {} to accept",
 753                                    sas.other_device().user_id()
 754                                )
 755                            }
 756                        } else {
 757                            if sas.started_from_request() {
 758                                format!(
 759                                    "{} has started an interactive emoji verification \
 760                                        with you, waiting for emojis",
 761                                    sas.other_device().user_id()
 762                                )
 763                            } else {
 764                                // We auto accept emoji verifications that start
 765                                // from a verification request, so don't print
 766                                // anything.
 767                                return RenderedContent::new(vec![]);
 768                            }
 769                        }
 770                    }
 771                    Verification::QrV1(_) => {
 772                        // We don't support QR code scanning, so if there's an QR
 773                        // code verification struct it's because someone else
 774                        // scanned our QR code.
 775                        format!(
 776                            "{} has scanned our QR code, confirm that he \
 777                                has done so TODO",
 778                            context.sender(),
 779                        )
 780                    }
 781                    _ => unreachable!(),
 782                };
 783
 784                RenderedContent::new(vec![RenderedLine {
 785                        message,
 786                        tags: self.tags(),
 787                    }])
 788            }
 789        }
 790    };
 791}
 792
 793render_start_content!(KeyVerificationStartEventContent);
 794render_start_content!(ToDeviceKeyVerificationStartEventContent);
 795
 796pub enum VerificationContext {
 797    Room {
 798        own_member: WeechatRoomMember,
 799        sender: WeechatRoomMember,
 800    },
 801    ToDevice,
 802}
 803
 804macro_rules! render_request_content {
 805    ($type: ident) => {
 806        impl Render for $type {
 807            const TAGS: &'static [&'static str] = &[];
 808
 809            type RenderContext = VerificationContext;
 810
 811            fn prefix(&self, _: &WeechatRoomMember) -> String {
 812                Weechat::prefix(Prefix::Network)
 813            }
 814
 815            fn render(&self, context: &Self::RenderContext) -> RenderedContent {
 816                let message = match context {
 817                    VerificationContext::Room { own_member, sender } => {
 818                        if own_member == sender {
 819                            "You sent a verification request".to_string()
 820                        } else {
 821                            format!(
 822                                "{} has sent a verification request",
 823                                sender.nick_colored()
 824                            )
 825                        }
 826                    }
 827                    VerificationContext::ToDevice => {
 828                        format!("You have requested this device to be verified")
 829                    }
 830                };
 831
 832                RenderedContent::new(vec![RenderedLine {
 833                    message,
 834                    tags: self.tags(),
 835                }])
 836            }
 837        }
 838    };
 839}
 840
 841render_request_content!(KeyVerificationRequestEventContent);
 842render_request_content!(ToDeviceKeyVerificationRequestEventContent);
 843
 844macro_rules! render_ready_content {
 845    ($type: ident) => {
 846        impl Render for $type {
 847            const TAGS: &'static [&'static str] = &[];
 848
 849            type RenderContext = (WeechatRoomMember, WeechatRoomMember);
 850
 851            fn prefix(&self, _: &WeechatRoomMember) -> String {
 852                Weechat::prefix(Prefix::Network)
 853            }
 854
 855            fn render(&self, context: &Self::RenderContext) -> RenderedContent {
 856                let (own_mebmer, sender) = context;
 857
 858                let message = if own_mebmer == sender {
 859                    "You answered the verification request".to_string()
 860                } else {
 861                    format!(
 862                        "{} has answered the verification request",
 863                        sender.nick_colored()
 864                    )
 865                };
 866
 867                RenderedContent::new(vec![RenderedLine {
 868                    message,
 869                    tags: self.tags(),
 870                }])
 871            }
 872        }
 873    };
 874}
 875
 876render_ready_content!(KeyVerificationReadyEventContent);
 877render_ready_content!(ToDeviceKeyVerificationReadyEventContent);
 878
 879fn render_sas_short_auth_string(sas: &SasVerification) -> Vec<String> {
 880    if sas.supports_emoji() {
 881        if let Some(emojis) = sas.emoji() {
 882            return format_emojis(emojis)
 883                .lines()
 884                .map(ToOwned::to_owned)
 885                .collect();
 886        }
 887    }
 888
 889    if let Some((first, second, third)) = sas.decimals() {
 890        return vec![format!("{first:04} {second:04} {third:04}")];
 891    }
 892
 893    vec!["Short authentication string is not ready yet".to_owned()]
 894}
 895
 896macro_rules! render_key_content {
 897    ($type: ident) => {
 898        impl Render for $type {
 899            const TAGS: &'static [&'static str] = &[];
 900            type RenderContext = SasVerification;
 901
 902            fn prefix(&self, _: &WeechatRoomMember) -> String {
 903                Weechat::prefix(Prefix::Network)
 904            }
 905
 906            fn render(&self, sas: &Self::RenderContext) -> RenderedContent {
 907                let (message, short_auth_string) = if sas.supports_emoji() {
 908                    ("Do the emojis match?", render_sas_short_auth_string(sas))
 909                } else {
 910                    (
 911                        "Do the decimals match?",
 912                        render_sas_short_auth_string(sas),
 913                    )
 914                };
 915
 916                let lines = std::iter::once(message.to_owned())
 917                    .chain(short_auth_string)
 918                    .map(|message| RenderedLine {
 919                        message,
 920                        tags: self.tags(),
 921                    })
 922                    .collect();
 923
 924                RenderedContent::new(lines)
 925            }
 926        }
 927    };
 928}
 929
 930render_key_content!(KeyVerificationKeyEventContent);
 931render_key_content!(ToDeviceKeyVerificationKeyEventContent);
 932
 933fn render_formatted_message_body(
 934    body: &str,
 935    tags: Vec<String>,
 936) -> RenderedContent {
 937    let body = formatted_message_body_to_plain_text(body);
 938
 939    render_plain_message_body(&body.text, tags)
 940        .with_reply_fallback(body.reply_fallback)
 941}
 942
 943fn render_plain_message_body(body: &str, tags: Vec<String>) -> RenderedContent {
 944    let lines = body
 945        .lines()
 946        .map(|l| RenderedLine {
 947            message: l.to_owned(),
 948            tags: tags.clone(),
 949        })
 950        .collect();
 951
 952    RenderedContent::new(lines)
 953}
 954
 955fn formatted_body_to_plain_text(body: &str) -> String {
 956    formatted_message_body_to_plain_text(body).text
 957}
 958
 959struct FormattedMessageBody {
 960    text: String,
 961    reply_fallback: Option<ReplyFallback>,
 962}
 963
 964fn formatted_message_body_to_plain_text(body: &str) -> FormattedMessageBody {
 965    let html = Html::parse(body);
 966    html.sanitize_with(&SanitizerConfig::compat());
 967
 968    let mut reply_fallback = None;
 969
 970    for node in html.children() {
 971        if reply_fallback.is_none() {
 972            reply_fallback = render_reply_fallback(&node);
 973        }
 974    }
 975
 976    html.sanitize();
 977
 978    let mut output = String::new();
 979    let mut context = HtmlRenderContext::default();
 980
 981    for node in html.children() {
 982        render_html_node(&node, &mut output, &mut context);
 983    }
 984
 985    FormattedMessageBody {
 986        text: trim_newlines(output),
 987        reply_fallback,
 988    }
 989}
 990
 991#[derive(Clone, Default)]
 992struct HtmlRenderContext {
 993    lists: Vec<ListContext>,
 994    in_pre: bool,
 995}
 996
 997#[derive(Clone)]
 998enum ListContext {
 999    Unordered,
1000    Ordered { next: i64 },
1001}
1002
1003fn render_html_node(
1004    node: &NodeRef,
1005    output: &mut String,
1006    context: &mut HtmlRenderContext,
1007) {
1008    match node.data() {
1009        NodeData::Text(text) => output.push_str(&text.borrow()),
1010        NodeData::Element(element) => match element.to_matrix().element {
1011            MatrixElement::Br => push_newline(output),
1012            MatrixElement::Hr => {
1013                push_newline(output);
1014                output.push_str("---");
1015                push_newline(output);
1016            }
1017            MatrixElement::P
1018            | MatrixElement::Div(_)
1019            | MatrixElement::Details
1020            | MatrixElement::Summary
1021            | MatrixElement::Table
1022            | MatrixElement::Thead
1023            | MatrixElement::Tbody
1024            | MatrixElement::Tr
1025            | MatrixElement::Caption
1026            | MatrixElement::H(_) => {
1027                push_newline(output);
1028                render_html_children(node, output, context);
1029                push_newline(output);
1030            }
1031            MatrixElement::Blockquote => {
1032                let mut quote = String::new();
1033                let mut quote_context = context.clone();
1034
1035                render_html_children(node, &mut quote, &mut quote_context);
1036
1037                push_newline(output);
1038                output.push_str(&prefix_lines(trim_newlines(quote), "> "));
1039                push_newline(output);
1040            }
1041            MatrixElement::Ul => {
1042                context.lists.push(ListContext::Unordered);
1043                push_newline(output);
1044                render_html_children(node, output, context);
1045                context.lists.pop();
1046                push_newline(output);
1047            }
1048            MatrixElement::Ol(ordered) => {
1049                context.lists.push(ListContext::Ordered {
1050                    next: ordered.start.unwrap_or(1),
1051                });
1052                push_newline(output);
1053                render_html_children(node, output, context);
1054                context.lists.pop();
1055                push_newline(output);
1056            }
1057            MatrixElement::Th | MatrixElement::Td => {
1058                render_html_children(node, output, context);
1059                output.push('\t');
1060            }
1061            MatrixElement::Li => {
1062                push_newline(output);
1063                output.push_str(
1064                    &"  ".repeat(context.lists.len().saturating_sub(1)),
1065                );
1066                output.push_str(&list_marker(context));
1067                render_html_children(node, output, context);
1068            }
1069            MatrixElement::A(anchor) => {
1070                let start = output.len();
1071                render_html_children(node, output, context);
1072                if let Some(href) =
1073                    anchor.href.and_then(|href| anchor_uri_to_string(&href))
1074                {
1075                    if output[start..].trim() != href {
1076                        output.push_str(" <");
1077                        output.push_str(&href);
1078                        output.push('>');
1079                    }
1080                }
1081            }
1082            MatrixElement::B | MatrixElement::Strong => {
1083                render_wrapped_html_children(node, output, context, "*");
1084            }
1085            MatrixElement::I | MatrixElement::Em => {
1086                render_wrapped_html_children(node, output, context, "_");
1087            }
1088            MatrixElement::S | MatrixElement::Del => {
1089                render_wrapped_html_children(node, output, context, "~");
1090            }
1091            MatrixElement::Code(_) if !context.in_pre => {
1092                render_wrapped_html_children(node, output, context, "`");
1093            }
1094            MatrixElement::Pre => {
1095                let was_in_pre = context.in_pre;
1096                context.in_pre = true;
1097
1098                let mut code = String::new();
1099                render_html_children(node, &mut code, context);
1100
1101                context.in_pre = was_in_pre;
1102
1103                push_newline(output);
1104                output.push_str("```");
1105                push_newline(output);
1106                output.push_str(&trim_newlines(code));
1107                push_newline(output);
1108                output.push_str("```");
1109                push_newline(output);
1110            }
1111            MatrixElement::Img(image) => {
1112                if let Some(alt) = image.alt {
1113                    output.push_str(&alt);
1114                } else if let Some(src) = image.src {
1115                    output.push_str(src.as_str());
1116                }
1117            }
1118            MatrixElement::MatrixReply => {}
1119            MatrixElement::Other(_) => {
1120                render_html_children(node, output, context)
1121            }
1122            _ => render_html_children(node, output, context),
1123        },
1124        NodeData::Document | NodeData::Other => {
1125            render_html_children(node, output, context)
1126        }
1127    }
1128}
1129
1130fn render_reply_fallback(node: &NodeRef) -> Option<ReplyFallback> {
1131    let reply_node = find_first_matrix_reply(node)?;
1132    let blockquote = find_first_blockquote(&reply_node)?;
1133    let body = render_reply_fallback_body(&blockquote);
1134
1135    if body.is_empty() {
1136        return None;
1137    }
1138
1139    Some(ReplyFallback {
1140        sender: render_reply_fallback_sender(&blockquote),
1141        body,
1142    })
1143}
1144
1145fn find_first_matrix_reply(node: &NodeRef) -> Option<NodeRef> {
1146    if is_matrix_element(node, |element| {
1147        matches!(element, MatrixElement::MatrixReply)
1148    }) {
1149        return Some(node.clone());
1150    }
1151
1152    node.children()
1153        .find_map(|child| find_first_matrix_reply(&child))
1154}
1155
1156fn find_first_blockquote(node: &NodeRef) -> Option<NodeRef> {
1157    if is_matrix_element(node, |element| {
1158        matches!(element, MatrixElement::Blockquote)
1159    }) {
1160        return Some(node.clone());
1161    }
1162
1163    node.children()
1164        .find_map(|child| find_first_blockquote(&child))
1165}
1166
1167fn is_matrix_element<F>(node: &NodeRef, predicate: F) -> bool
1168where
1169    F: FnOnce(MatrixElement) -> bool,
1170{
1171    match node.data() {
1172        NodeData::Element(element) => predicate(element.to_matrix().element),
1173        _ => false,
1174    }
1175}
1176
1177fn render_reply_fallback_sender(blockquote: &NodeRef) -> Option<String> {
1178    let mut anchors = Vec::new();
1179
1180    collect_anchor_text_before_first_br(blockquote, &mut anchors);
1181
1182    anchors
1183        .into_iter()
1184        .filter_map(|anchor| {
1185            let anchor = collapse_whitespace(&anchor);
1186            (!anchor.is_empty() && !anchor.eq_ignore_ascii_case("in reply to"))
1187                .then_some(anchor)
1188        })
1189        .next_back()
1190}
1191
1192fn collect_anchor_text_before_first_br(
1193    node: &NodeRef,
1194    anchors: &mut Vec<String>,
1195) -> bool {
1196    match node.data() {
1197        NodeData::Element(element)
1198            if matches!(element.to_matrix().element, MatrixElement::Br) =>
1199        {
1200            return true;
1201        }
1202        NodeData::Element(element)
1203            if matches!(element.to_matrix().element, MatrixElement::A(_)) =>
1204        {
1205            let text = plain_text_children(node);
1206            if !text.trim().is_empty() {
1207                anchors.push(text);
1208            }
1209        }
1210        _ => {}
1211    }
1212
1213    for child in node.children() {
1214        if collect_anchor_text_before_first_br(&child, anchors) {
1215            return true;
1216        }
1217    }
1218
1219    false
1220}
1221
1222fn plain_text_children(node: &NodeRef) -> String {
1223    let mut text = String::new();
1224
1225    collect_plain_text(node, &mut text);
1226
1227    text
1228}
1229
1230fn collect_plain_text(node: &NodeRef, output: &mut String) {
1231    match node.data() {
1232        NodeData::Text(text) => output.push_str(&text.borrow()),
1233        _ => {
1234            for child in node.children() {
1235                collect_plain_text(&child, output);
1236            }
1237        }
1238    }
1239}
1240
1241fn render_reply_fallback_body(blockquote: &NodeRef) -> String {
1242    let mut output = String::new();
1243    let mut context = HtmlRenderContext::default();
1244    let mut after_intro = false;
1245
1246    for child in blockquote.children() {
1247        render_after_first_br(
1248            &child,
1249            &mut output,
1250            &mut context,
1251            &mut after_intro,
1252        );
1253    }
1254
1255    trim_newlines(output)
1256}
1257
1258fn render_after_first_br(
1259    node: &NodeRef,
1260    output: &mut String,
1261    context: &mut HtmlRenderContext,
1262    after_intro: &mut bool,
1263) {
1264    if !*after_intro {
1265        if is_matrix_element(node, |element| {
1266            matches!(element, MatrixElement::Br)
1267        }) {
1268            *after_intro = true;
1269            return;
1270        }
1271
1272        for child in node.children() {
1273            render_after_first_br(&child, output, context, after_intro);
1274        }
1275
1276        return;
1277    }
1278
1279    render_html_node(node, output, context);
1280}
1281
1282fn render_html_children(
1283    node: &NodeRef,
1284    output: &mut String,
1285    context: &mut HtmlRenderContext,
1286) {
1287    for child in node.children() {
1288        render_html_node(&child, output, context);
1289    }
1290}
1291
1292fn render_wrapped_html_children(
1293    node: &NodeRef,
1294    output: &mut String,
1295    context: &mut HtmlRenderContext,
1296    wrapper: &str,
1297) {
1298    output.push_str(wrapper);
1299    render_html_children(node, output, context);
1300    output.push_str(wrapper);
1301}
1302
1303fn list_marker(context: &mut HtmlRenderContext) -> String {
1304    match context.lists.last_mut() {
1305        Some(ListContext::Ordered { next }) => {
1306            let marker = format!("{}. ", next);
1307            *next += 1;
1308            marker
1309        }
1310        _ => "- ".to_owned(),
1311    }
1312}
1313
1314fn anchor_uri_to_string(uri: &AnchorUri) -> Option<String> {
1315    match uri {
1316        AnchorUri::Matrix(uri) => Some(uri.to_string()),
1317        AnchorUri::MatrixTo(uri) => Some(uri.to_string()),
1318        AnchorUri::Other(uri) => Some(uri.to_string()),
1319        _ => None,
1320    }
1321}
1322
1323fn reply_quote_lines(body: &str) -> impl Iterator<Item = String> + '_ {
1324    body.lines().map(|line| {
1325        let line = line.trim();
1326
1327        if line.is_empty() {
1328            ">".to_owned()
1329        } else {
1330            format!("> {}", line)
1331        }
1332    })
1333}
1334
1335fn collapse_whitespace(body: &str) -> String {
1336    body.split_whitespace().collect::<Vec<_>>().join(" ")
1337}
1338
1339fn prefix_lines(text: String, prefix: &str) -> String {
1340    text.lines()
1341        .map(|line| {
1342            if line.is_empty() {
1343                prefix.trim_end().to_owned()
1344            } else {
1345                format!("{prefix}{line}")
1346            }
1347        })
1348        .collect::<Vec<_>>()
1349        .join("\n")
1350}
1351
1352fn push_newline(output: &mut String) {
1353    if !output.ends_with('\n') {
1354        output.push('\n');
1355    }
1356}
1357
1358fn trim_newlines(mut output: String) -> String {
1359    while output.starts_with('\n') {
1360        output.remove(0);
1361    }
1362
1363    while output.ends_with('\n') {
1364        output.pop();
1365    }
1366
1367    output
1368}
1369
1370/// Trait for message event types that contain an optional formatted body.
1371trait HasFormattedBody {
1372    fn body(&self) -> &str;
1373    fn formatted_body(&self) -> Option<&str>;
1374}
1375
1376// Repeating this for each event type would get boring fast so lets use a simple
1377// macro to implement the trait for a struct that has a `body` and
1378// `formatted_body` field
1379macro_rules! has_formatted_body {
1380    ($content: ident) => {
1381        impl HasFormattedBody for $content {
1382            #[inline]
1383            fn body(&self) -> &str {
1384                &self.body
1385            }
1386
1387            #[inline]
1388            fn formatted_body(&self) -> Option<&str> {
1389                self.formatted
1390                    .as_ref()
1391                    .filter(|f| f.format == MessageFormat::Html)
1392                    .map(|f| f.body.as_ref())
1393            }
1394        }
1395    };
1396}
1397
1398has_formatted_body!(EmoteMessageEventContent);
1399has_formatted_body!(NoticeMessageEventContent);
1400has_formatted_body!(TextMessageEventContent);
1401
1402/// This trait is implemented for message types that can contain either an URL
1403/// or an encrypted file. One of these _must_ be present.
1404pub trait HasUrlOrFile {
1405    fn body(&self) -> &str;
1406
1407    fn media_kind(&self) -> &'static str;
1408
1409    #[inline]
1410    fn resolve_url(&self) -> &MxcUri {
1411        match self.source() {
1412            MediaSource::Plain(s) => s,
1413            MediaSource::Encrypted(e) => &e.url,
1414        }
1415    }
1416
1417    fn encrypted_file(&self) -> Option<&EncryptedFile>;
1418
1419    fn source(&self) -> &MediaSource;
1420}
1421
1422// Same as above: a simple macro to implement the trait for structs with `url`
1423// and `file` fields.
1424macro_rules! has_url_or_file {
1425    ($content: ident, $kind: literal) => {
1426        impl HasUrlOrFile for $content {
1427            fn body(&self) -> &str {
1428                &self.body
1429            }
1430
1431            fn media_kind(&self) -> &'static str {
1432                $kind
1433            }
1434
1435            fn source(&self) -> &MediaSource {
1436                &self.source
1437            }
1438
1439            fn encrypted_file(&self) -> Option<&EncryptedFile> {
1440                match &self.source {
1441                    MediaSource::Encrypted(e) => Some(&e),
1442                    _ => None,
1443                }
1444            }
1445        }
1446    };
1447}
1448
1449has_url_or_file!(AudioMessageEventContent, "audio");
1450has_url_or_file!(FileMessageEventContent, "file");
1451has_url_or_file!(ImageMessageEventContent, "image");
1452has_url_or_file!(VideoMessageEventContent, "video");
1453
1454/// Rendering implementation for membership events (joins, leaves, bans, profile
1455/// changes, etc).
1456pub fn render_membership(
1457    event: &OriginalSyncStateEvent<RoomMemberEventContent>,
1458    sender: &WeechatRoomMember,
1459    target: &WeechatRoomMember,
1460) -> RenderedLine {
1461    use MembershipChange::*;
1462    let change_op = event.membership_change();
1463
1464    let operation = match change_op {
1465        None => "did nothing",
1466        Error => "caused an error", // must never happen
1467        Joined => "has joined the room",
1468        Left => "has left the room",
1469        Banned => "was banned by",
1470        Unbanned => "was unbanned by",
1471        Kicked => "was kicked from the room by",
1472        Invited => "was invited to the room by",
1473        KickedAndBanned => "was kicked and banned by",
1474        InvitationRejected => "rejected the invitation",
1475        InvitationRevoked => "had the invitation revoked by",
1476        ProfileChanged { .. } => "_",
1477        _ => "performed an unimplemented operation",
1478    };
1479
1480    fn formatted_name(member: &WeechatRoomMember) -> String {
1481        match member.display_name() {
1482            Some(display_name) => {
1483                format!(
1484                    "{name} {color_delim}({color_reset}{user_id}{color_delim}){color_reset}",
1485                    name = display_name,
1486                    user_id = member.user_id(),
1487                    color_delim = Weechat::color("chat_delimiters"),
1488                    color_reset = Weechat::color("reset"))
1489            }
1490
1491            Option::None => member.user_id().to_string(),
1492        }
1493    }
1494
1495    let (prefix, color_action) = match change_op {
1496        Joined => (Prefix::Join, "green"),
1497        Banned | ProfileChanged { .. } | Invited => {
1498            (Prefix::Network, "magenta")
1499        }
1500        _ => (Prefix::Quit, "red"),
1501    };
1502
1503    let color_action = Weechat::color(color_action);
1504    let color_reset = Weechat::color("reset");
1505
1506    let operation = format!(
1507        "{color_action}{op}{color_reset}",
1508        color_action = color_action,
1509        op = operation,
1510        color_reset = color_reset
1511    );
1512
1513    let target_name = format!(
1514        "{color_user}{target_name}{color_reset}",
1515        target_name = formatted_name(target),
1516        color_user = Weechat::color("reset"), // TODO
1517        color_reset = Weechat::color("reset")
1518    );
1519
1520    let sender_name = format!(
1521        "{color_user}{sender_name}{color_reset}",
1522        sender_name = formatted_name(sender),
1523        color_user = Weechat::color("reset"), // TODO
1524        color_reset = Weechat::color("reset")
1525    );
1526
1527    let message = match change_op {
1528        ProfileChanged {
1529            displayname_change,
1530            avatar_url_change,
1531        } => {
1532            let new_display_name = &event.content.displayname;
1533
1534            // TODO: Should we display the new avatar URL?
1535            // let new_avatar = self.content.avatar_url.as_ref();
1536
1537            match (displayname_change.is_some(), avatar_url_change.is_some()) {
1538                (false, true) =>
1539                    format!(
1540                        "{prefix}{target} {color_action}changed their avatar{color_reset}",
1541                        prefix = Weechat::prefix(prefix),
1542                        target = target_name,
1543                        color_action = color_action,
1544                        color_reset = color_reset
1545                        ),
1546                (true, false) => {
1547                    match new_display_name {
1548                        Some(name) => format!(
1549                            "{prefix}{target} {color_action}changed their display name to{color_reset} {new}",
1550                            prefix = Weechat::prefix(prefix),
1551                            target = event.prev_content().as_ref().and_then(|p| p.displayname.clone()).unwrap_or(target_name),
1552                            new = name,
1553                            color_action = color_action,
1554                            color_reset = color_reset
1555                            ),
1556                        Option::None => format!(
1557                            "{prefix}{target} {color_action}removed their display name{color_reset}",
1558                            prefix = Weechat::prefix(prefix),
1559                            target = target_name,
1560                            color_action = color_action,
1561                            color_reset = color_reset
1562                            ),
1563                    }
1564                }
1565                (true, true) =>
1566                    match new_display_name {
1567                        Some(name) => format!(
1568                            "{prefix}{target} {color_action}changed their avatar \
1569                            and changed their display name to{color_reset} {new}",
1570                            prefix = Weechat::prefix(prefix),
1571                            target = target_name,
1572                            new = name,
1573                            color_action = color_action,
1574                            color_reset = color_reset
1575                            ),
1576                        Option::None => format!(
1577                            "{prefix}{target} {color_action}changed their \
1578                            avatar and removed display name{color_reset}",
1579                            prefix = Weechat::prefix(prefix),
1580                            target = target_name,
1581                            color_action = color_action,
1582                            color_reset = color_reset
1583                            ),
1584                    }
1585                (false, false) =>
1586                    "Cannot happen: got profile changed but nothing really changed".to_string()
1587            }
1588        }
1589        Banned | Unbanned | Kicked | Invited | InvitationRevoked
1590        | KickedAndBanned => format!(
1591            "{prefix}{target} {op} {sender}",
1592            prefix = Weechat::prefix(prefix),
1593            target = target_name,
1594            op = operation,
1595            sender = sender_name
1596        ),
1597        _ => format!(
1598            "{prefix}{target} {op}",
1599            prefix = Weechat::prefix(prefix),
1600            target = target_name,
1601            op = operation
1602        ),
1603    };
1604
1605    RenderedLine {
1606        tags: vec!["matrix_membership".to_owned()],
1607        message,
1608    }
1609}
1610
1611#[cfg(test)]
1612mod tests {
1613    use matrix_sdk::ruma::{
1614        events::room::{
1615            EncryptedFile, EncryptedFileHash, EncryptedFileHashAlgorithm,
1616            EncryptedFileHashes, V2EncryptedFileInfo,
1617        },
1618        OwnedMxcUri,
1619    };
1620
1621    use super::*;
1622
1623    fn encrypted_file_fixture() -> (EncryptedFile, String, String, String) {
1624        let info = V2EncryptedFileInfo::encode([1; 32], [2; 16]);
1625        let key = info.k.encode();
1626        let iv = info.iv.encode();
1627        let hashes = EncryptedFileHashes::with_sha256([3; 32]);
1628        let hash = match hashes.get(&EncryptedFileHashAlgorithm::Sha256) {
1629            Some(EncryptedFileHash::Sha256(hash)) => hash.encode(),
1630            _ => unreachable!("fixture always includes a sha256 hash"),
1631        };
1632        let file = EncryptedFile::new(
1633            OwnedMxcUri::from("mxc://some-url"),
1634            info.into(),
1635            hashes,
1636        );
1637
1638        (file, key, hash, iv)
1639    }
1640
1641    #[test]
1642    fn test_mxc_to_http() {
1643        let homeserver = url::Url::parse("https://matrix.org").unwrap();
1644        let mxc_url = OwnedMxcUri::from("mxc://matrix.org/some-media-id");
1645        let expected =
1646            "https://matrix.org/_matrix/media/r0/download/matrix.org/some-media-id";
1647        assert_eq!(expected, mxc_to_http(&mxc_url, &homeserver).unwrap());
1648    }
1649
1650    #[test]
1651    fn test_emxc_to_http() {
1652        let homeserver = url::Url::parse("https://matrix.org").unwrap();
1653        let mxc_url = OwnedMxcUri::from("mxc://matrix.org/some-media-id");
1654        let (encrypt_info, key, hash, iv) = encrypted_file_fixture();
1655        let expected = format!(
1656            "emxc://matrix.org:443/_matrix/media/r0/download/matrix.org/some-media-id?key={key}&hash={hash}&iv={iv}"
1657        );
1658        assert_eq!(
1659            expected,
1660            mxc_to_emxc(&mxc_url, &homeserver, &encrypt_info).unwrap()
1661        );
1662    }
1663
1664    #[test]
1665    fn test_plain_media_download_command() {
1666        let source = MediaSource::Plain(OwnedMxcUri::from(
1667            "mxc://matrix.org/some-media-id",
1668        ));
1669
1670        assert_eq!(
1671            Some(
1672                "/matrix media download mxc://matrix.org/some-media-id [file]"
1673                    .to_owned()
1674            ),
1675            media_download_command(&source)
1676        );
1677    }
1678
1679    #[test]
1680    fn test_plain_media_renders_authenticated_download_message() {
1681        let content = ImageMessageEventContent::plain(
1682            "image.png".to_owned(),
1683            OwnedMxcUri::from("mxc://matrix.org/some-media-id"),
1684        );
1685
1686        assert_eq!(
1687            Some(
1688                "attached `image.png`, authenticated download: /matrix media \
1689                 download mxc://matrix.org/some-media-id [file]"
1690                    .to_owned()
1691            ),
1692            media_download_message(&content)
1693        );
1694    }
1695
1696    #[test]
1697    fn plain_image_exposes_structured_media_tags() {
1698        let content = ImageMessageEventContent::plain(
1699            "image.png".to_owned(),
1700            OwnedMxcUri::from("mxc://matrix.org/some-media-id"),
1701        );
1702
1703        assert_eq!(
1704            vec![
1705                "matrix_media",
1706                "matrix_media_kind_image",
1707                "matrix_media_name_aW1hZ2UucG5n",
1708                "matrix_media_uri_bXhjOi8vbWF0cml4Lm9yZy9zb21lLW1lZGlhLWlk",
1709            ],
1710            content.tags()
1711        );
1712    }
1713
1714    #[test]
1715    fn formatted_body_plain_text_decodes_matrix_html() {
1716        let body = "<p>Hello <b>world</b> &amp; \
1717            <a href=\"https://example.org\">link</a></p>\
1718            <ul><li>one</li><li>two</li></ul>";
1719
1720        assert_eq!(
1721            "Hello *world* & link <https://example.org>\n- one\n- two",
1722            formatted_body_to_plain_text(body)
1723        );
1724    }
1725
1726    #[test]
1727    fn test_encrypted_media_has_no_plain_download_command() {
1728        let (encrypt_info, _, _, _) = encrypted_file_fixture();
1729        let source = MediaSource::Encrypted(Box::new(encrypt_info));
1730
1731        assert_eq!(None, media_download_command(&source));
1732    }
1733
1734    #[test]
1735    fn reply_context_names_known_sender() {
1736        let event_id =
1737            matrix_sdk::ruma::owned_event_id!("$replyevent:example.org");
1738        let rendered = RenderedEvent {
1739            message_timestamp: 0,
1740            prefix: "alice\t".to_owned(),
1741            content: RenderedContent::new(vec![RenderedLine {
1742                tags: vec!["matrix_text".to_owned()],
1743                message: "reply body".to_owned(),
1744            }]),
1745        }
1746        .add_reply_context(
1747            &event_id,
1748            Some("Alice"),
1749            ReplyContext::Inline,
1750            None,
1751        );
1752
1753        assert_eq!(1, rendered.content.lines.len());
1754        assert_eq!("> Alice: reply body", rendered.content.lines[0].message);
1755        assert!(rendered.content.lines[0]
1756            .tags
1757            .contains(&"matrix_reply".to_owned()));
1758        assert!(rendered.content.lines[0]
1759            .tags
1760            .contains(&"matrix_reply_sender_hex_416c696365".to_owned()));
1761        assert!(rendered.content.lines[0]
1762            .tags
1763            .contains(&"matrix_reply_id_$replyevent:example.org".to_owned()));
1764    }
1765
1766    #[test]
1767    fn inline_reply_context_falls_back_to_event_id() {
1768        let event_id =
1769            matrix_sdk::ruma::owned_event_id!("$replyevent:example.org");
1770        let rendered = RenderedEvent {
1771            message_timestamp: 0,
1772            prefix: "alice\t".to_owned(),
1773            content: RenderedContent::new(vec![RenderedLine {
1774                tags: vec!["matrix_text".to_owned()],
1775                message: "reply body".to_owned(),
1776            }]),
1777        }
1778        .add_reply_context(&event_id, None, ReplyContext::Inline, None);
1779
1780        assert_eq!(
1781            "> $replyevent:example.org: reply body",
1782            rendered.content.lines[0].message
1783        );
1784        assert!(rendered.content.lines[0]
1785            .tags
1786            .contains(&"matrix_reply".to_owned()));
1787    }
1788
1789    #[test]
1790    fn reply_context_uses_formatted_reply_fallback_quote() {
1791        let event_id =
1792            matrix_sdk::ruma::owned_event_id!("$replyevent:example.org");
1793        let body = "\
1794            <mx-reply>\
1795                <blockquote>\
1796                    <a href=\"https://matrix.to/#/!room:example.org/$replyevent:example.org\">In reply to</a> \
1797                    <a href=\"https://matrix.to/#/@alice:example.org\">@alice:example.org</a>\
1798                    <br>\
1799                    <p>Previous <strong>message</strong> text</p>\
1800                </blockquote>\
1801            </mx-reply>\
1802            <p>new message</p>";
1803        let content = TextMessageEventContent::html("fallback", body);
1804        let rendered = RenderedEvent {
1805            message_timestamp: 0,
1806            prefix: "bob\t".to_owned(),
1807            content: content.render(&()),
1808        }
1809        .add_reply_context(
1810            &event_id,
1811            Some("Alice"),
1812            ReplyContext::Full,
1813            None,
1814        );
1815
1816        assert_eq!(3, rendered.content.lines.len());
1817        assert_eq!("Reply to Alice:", rendered.content.lines[0].message);
1818        assert_eq!(
1819            "> Previous *message* text",
1820            rendered.content.lines[1].message
1821        );
1822        assert_eq!("new message", rendered.content.lines[2].message);
1823    }
1824
1825    #[test]
1826    fn reply_context_uses_reply_fallback_sender_when_local_sender_is_unknown() {
1827        let event_id =
1828            matrix_sdk::ruma::owned_event_id!("$replyevent:example.org");
1829        let body = "\
1830            <mx-reply>\
1831                <blockquote>\
1832                    <a href=\"https://matrix.to/#/!room:example.org/$replyevent:example.org\">In reply to</a> \
1833                    <a href=\"https://matrix.to/#/@alice:example.org\">@alice:example.org</a>\
1834                    <br>\
1835                    Previous message\
1836                </blockquote>\
1837            </mx-reply>\
1838            <p>new message</p>";
1839        let content = TextMessageEventContent::html("fallback", body);
1840        let rendered = RenderedEvent {
1841            message_timestamp: 0,
1842            prefix: "bob\t".to_owned(),
1843            content: content.render(&()),
1844        }
1845        .add_reply_context(&event_id, None, ReplyContext::Full, None);
1846
1847        assert_eq!(
1848            "Reply to @alice:example.org:",
1849            rendered.content.lines[0].message
1850        );
1851        assert_eq!("> Previous message", rendered.content.lines[1].message);
1852    }
1853
1854    #[test]
1855    fn reply_context_quotes_multiline_reply_fallback() {
1856        let event_id =
1857            matrix_sdk::ruma::owned_event_id!("$replyevent:example.org");
1858        let body = "\
1859            <mx-reply>\
1860                <blockquote>\
1861                    <a href=\"https://matrix.to/#/!room:example.org/$replyevent:example.org\">In reply to</a> \
1862                    <a href=\"https://matrix.to/#/@alice:example.org\">@alice:example.org</a>\
1863                    <br>\
1864                    <p>line one</p><p>line two</p>\
1865                </blockquote>\
1866            </mx-reply>\
1867            <p>new message</p>";
1868        let content = TextMessageEventContent::html("fallback", body);
1869        let rendered = RenderedEvent {
1870            message_timestamp: 0,
1871            prefix: "bob\t".to_owned(),
1872            content: content.render(&()),
1873        }
1874        .add_reply_context(
1875            &event_id,
1876            Some("Alice"),
1877            ReplyContext::Full,
1878            None,
1879        );
1880
1881        let messages = rendered
1882            .content
1883            .lines
1884            .iter()
1885            .map(|line| line.message.as_str())
1886            .collect::<Vec<_>>();
1887
1888        assert_eq!(
1889            vec!["Reply to Alice:", "> line one", "> line two", "new message"],
1890            messages
1891        );
1892        assert!(rendered.content.lines[1]
1893            .tags
1894            .contains(&"matrix_reply_quote".to_owned()));
1895    }
1896
1897    #[test]
1898    fn reply_context_uses_fetched_body_without_matrix_fallback() {
1899        let event_id =
1900            matrix_sdk::ruma::owned_event_id!("$replyevent:example.org");
1901        let rendered = RenderedEvent {
1902            message_timestamp: 0,
1903            prefix: "bob\t".to_owned(),
1904            content: RenderedContent::new(vec![RenderedLine {
1905                tags: vec!["matrix_text".to_owned()],
1906                message: "new message".to_owned(),
1907            }]),
1908        }
1909        .add_reply_context(
1910            &event_id,
1911            Some("Alice"),
1912            ReplyContext::Full,
1913            Some("previous message"),
1914        );
1915
1916        assert_eq!(
1917            vec!["Reply to Alice:", "> previous message", "new message"],
1918            rendered
1919                .content
1920                .lines
1921                .iter()
1922                .map(|line| line.message.as_str())
1923                .collect::<Vec<_>>()
1924        );
1925    }
1926
1927    #[test]
1928    fn inline_reply_context_keeps_reply_on_one_line_with_fallback() {
1929        let event_id =
1930            matrix_sdk::ruma::owned_event_id!("$replyevent:example.org");
1931        let body = "\
1932            <mx-reply>\
1933                <blockquote>\
1934                    <a href=\"https://matrix.to/#/!room:example.org/$replyevent:example.org\">In reply to</a> \
1935                    <a href=\"https://matrix.to/#/@alice:example.org\">@alice:example.org</a>\
1936                    <br>\
1937                    Previous message\
1938                </blockquote>\
1939            </mx-reply>\
1940            <p>new message</p>";
1941        let content = TextMessageEventContent::html("fallback", body);
1942        let rendered = RenderedEvent {
1943            message_timestamp: 0,
1944            prefix: "bob\t".to_owned(),
1945            content: content.render(&()),
1946        }
1947        .add_reply_context(
1948            &event_id,
1949            Some("Alice"),
1950            ReplyContext::Inline,
1951            None,
1952        );
1953
1954        assert_eq!(1, rendered.content.lines.len());
1955        assert_eq!("> Alice: new message", rendered.content.lines[0].message);
1956        assert!(rendered.content.lines[0]
1957            .tags
1958            .contains(&"matrix_reply".to_owned()));
1959    }
1960
1961    #[test]
1962    fn formatted_body_plain_text_keeps_block_structure() {
1963        let body = "<blockquote><p>quoted</p><p>text</p></blockquote>\
1964            <ol start=\"3\"><li>three</li><li>four</li></ol>";
1965
1966        assert_eq!(
1967            "> quoted\n> text\n3. three\n4. four",
1968            formatted_body_to_plain_text(body)
1969        );
1970    }
1971
1972    #[test]
1973    fn formatted_body_plain_text_marks_code_and_emphasis() {
1974        let body = "<p><em>try</em> <code>cargo test</code></p>\
1975            <pre><code class=\"language-rust\">fn main() {}</code></pre>";
1976
1977        assert_eq!(
1978            "_try_ `cargo test`\n```\nfn main() {}\n```",
1979            formatted_body_to_plain_text(body)
1980        );
1981    }
1982
1983    #[test]
1984    fn formatted_body_plain_text_removes_reply_fallback() {
1985        let body = "<mx-reply><blockquote>old reply</blockquote></mx-reply>\
1986            <p>new message</p>";
1987
1988        assert_eq!("new message", formatted_body_to_plain_text(body));
1989    }
1990
1991    #[test]
1992    fn text_render_uses_formatted_body_when_available() {
1993        let content =
1994            TextMessageEventContent::html("fallback", "<p>Hello<br>world</p>");
1995        let rendered = content.render(&());
1996
1997        assert_eq!(rendered.lines.len(), 2);
1998        assert_eq!(rendered.lines[0].message, "Hello");
1999        assert_eq!(rendered.lines[1].message, "world");
2000    }
2001
2002    #[test]
2003    fn text_render_keeps_plain_body_plain() {
2004        let content = TextMessageEventContent::plain("literal <b> text");
2005        let rendered = content.render(&());
2006
2007        assert_eq!(rendered.lines.len(), 1);
2008        assert_eq!(rendered.lines[0].message, "literal <b> text");
2009    }
2010
2011    #[test]
2012    fn encrypted_placeholder_guidance_stays_on_one_line() {
2013        let message = format!(
2014            "{} {}",
2015            encrypted_placeholder_body("Alice"),
2016            encrypted_placeholder_guidance("Alice")
2017        );
2018
2019        assert_eq!(message.lines().count(), 1);
2020        assert!(message.contains("Unable to decrypt message from Alice"));
2021        assert!(message.contains("Waiting for the room key from Alice"));
2022    }
2023
2024    #[test]
2025    fn backlog_tags_suppress_notifications_and_highlights() {
2026        let rendered = RenderedEvent {
2027            message_timestamp: 0,
2028            prefix: "alice\t".to_owned(),
2029            content: RenderedContent::new(vec![RenderedLine {
2030                tags: vec!["matrix_text".to_owned()],
2031                message: "old mention of Darafei".to_owned(),
2032            }]),
2033        }
2034        .add_backlog_tags();
2035
2036        assert!(rendered.content.lines[0]
2037            .tags
2038            .contains(&"notify_none".to_owned()));
2039        assert!(rendered.content.lines[0]
2040            .tags
2041            .contains(&"no_highlight".to_owned()));
2042        assert!(!rendered.content.lines[0]
2043            .tags
2044            .contains(&"notify_message".to_owned()));
2045    }
2046}