src/render.rs

8454dcd1674dfb48ab4ee615134e2d4d5fc04fa7
weechat-matrix-rs/src/render.rs history · blame · raw

1812 lines · 57709 bytes

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