src/render.rs

4fddc50d6d9f3d82220a4e3264d792d54fc940cf
weechat-matrix-rs/src/render.rs history · blame · raw

1091 lines · 36088 bytes

   1use url::Url;
   2
   3use matrix_sdk::{
   4    encryption::verification::{
   5        SasVerification, Verification, VerificationRequest,
   6    },
   7    ruma::{
   8        events::{
   9            key::verification::{
  10                key::{
  11                    KeyVerificationKeyEventContent,
  12                    ToDeviceKeyVerificationKeyEventContent,
  13                },
  14                ready::{
  15                    KeyVerificationReadyEventContent,
  16                    ToDeviceKeyVerificationReadyEventContent,
  17                },
  18                request::ToDeviceKeyVerificationRequestEventContent,
  19                start::{
  20                    KeyVerificationStartEventContent,
  21                    ToDeviceKeyVerificationStartEventContent,
  22                },
  23            },
  24            room::{
  25                encrypted::RoomEncryptedEventContent,
  26                member::{MembershipChange, RoomMemberEventContent},
  27                message::{
  28                    AudioMessageEventContent, EmoteMessageEventContent,
  29                    FileMessageEventContent, ImageMessageEventContent,
  30                    KeyVerificationRequestEventContent,
  31                    LocationMessageEventContent, NoticeMessageEventContent,
  32                    RedactedRoomMessageEventContent,
  33                    ServerNoticeMessageEventContent, TextMessageEventContent,
  34                    VideoMessageEventContent,
  35                },
  36                EncryptedFile, MediaSource,
  37            },
  38            OriginalSyncStateEvent, RedactedSyncMessageLikeEvent,
  39        },
  40        uint, EventId, MilliSecondsSinceUnixEpoch, MxcUri, OwnedUserId,
  41        TransactionId, UserId,
  42    },
  43};
  44
  45use weechat::{Prefix, Weechat};
  46
  47use crate::{room::WeechatRoomMember, utils::ToTag};
  48
  49/// The rendered version of an event.
  50pub struct RenderedEvent {
  51    /// The UNIX timestamp of the event.
  52    pub message_timestamp: isize,
  53    pub prefix: String,
  54    pub content: RenderedContent,
  55}
  56
  57impl RenderedEvent {
  58    const MSG_TAGS: &'static [&'static str] = &["notify_message"];
  59    const SELF_TAGS: &'static [&'static str] =
  60        &["notify_none", "no_highlight", "self_msg"];
  61
  62    pub fn add_self_tags(self) -> Self {
  63        self.add_tags(Self::SELF_TAGS)
  64    }
  65
  66    pub fn add_msg_tags(self) -> Self {
  67        self.add_tags(Self::MSG_TAGS)
  68    }
  69
  70    fn add_tags(mut self, tags: &[&str]) -> Self {
  71        for line in &mut self.content.lines {
  72            line.tags.extend(tags.iter().map(|tag| tag.to_string()))
  73        }
  74
  75        self
  76    }
  77}
  78
  79#[derive(Debug)]
  80pub struct RenderedLine {
  81    /// The tags of the line.
  82    pub tags: Vec<String>,
  83    /// The message of the line.
  84    pub message: String,
  85}
  86
  87#[derive(Debug)]
  88pub struct RenderedContent {
  89    /// The collection of lines that the event has.
  90    pub lines: Vec<RenderedLine>,
  91}
  92
  93/// Trait allowing events to be rendered for Weechat.
  94pub trait Render {
  95    /// The event specific tags that should be attached to the rendered event.
  96    const TAGS: &'static [&'static str];
  97
  98    /// Some events might need additional context to be rendered. For example,
  99    /// instead of displaying the MXID for the sender, we might want to display
 100    /// the disambiguated display name, which isn't available in the event.
 101    ///
 102    /// This allows the render implementation to be passed some additional data
 103    /// when rendering.
 104    type RenderContext;
 105
 106    fn tags(&self) -> Vec<String> {
 107        Self::TAGS.iter().map(|t| t.to_string()).collect()
 108    }
 109
 110    fn event_tags(
 111        &self,
 112        event_id: &EventId,
 113        sender: &UserId,
 114        nick: &str,
 115        color_name: &str,
 116    ) -> Vec<String> {
 117        let mut tags = self.tags();
 118        let event_tag = event_id.to_tag();
 119        let sender_tag = sender.to_tag();
 120        let nick_tag = format!("nick_{}", nick);
 121        let color = format!("prefix_nick_{}", color_name);
 122        tags.push(event_tag);
 123        tags.push(sender_tag);
 124        tags.push(nick_tag);
 125        tags.push(color);
 126
 127        tags
 128    }
 129
 130    fn prefix(&self, sender: &WeechatRoomMember) -> String {
 131        format!("{}\t", sender.nick_colored())
 132    }
 133
 134    /// Render the event.
 135    fn render_with_prefix(
 136        &self,
 137        timestamp: MilliSecondsSinceUnixEpoch,
 138        event_id: &EventId,
 139        sender: &WeechatRoomMember,
 140        context: &Self::RenderContext,
 141    ) -> RenderedEvent {
 142        let prefix = self.prefix(sender);
 143        let mut content = self.render(context);
 144        let timestamp: i64 = (timestamp.0 / uint!(1000)).into();
 145
 146        let tags = self.event_tags(
 147            event_id,
 148            sender.user_id(),
 149            &sender.nick(),
 150            sender.color(),
 151        );
 152
 153        for line in &mut content.lines {
 154            line.tags = tags.clone();
 155        }
 156
 157        RenderedEvent {
 158            prefix,
 159            message_timestamp: timestamp as isize,
 160            content,
 161        }
 162    }
 163
 164    fn render_with_prefix_for_echo(
 165        &self,
 166        sender: &WeechatRoomMember,
 167        uuid: &TransactionId,
 168        context: &Self::RenderContext,
 169    ) -> RenderedEvent {
 170        let content = self.render_for_echo(uuid, context);
 171        let prefix = self.prefix(sender);
 172
 173        RenderedEvent {
 174            prefix,
 175            message_timestamp: 0,
 176            content,
 177        }
 178    }
 179
 180    fn render_for_echo(
 181        &self,
 182        uuid: &TransactionId,
 183        context: &Self::RenderContext,
 184    ) -> RenderedContent {
 185        let mut content = self.render(context);
 186        let uuid_tag = format!("matrix_echo_{}", uuid);
 187
 188        for line in &mut content.lines {
 189            let message = Weechat::remove_color(&line.message);
 190            line.message = format!(
 191                "{}{}{}",
 192                Weechat::color_pair("darkgray", "default"),
 193                message,
 194                Weechat::color("reset")
 195            );
 196            line.tags.push(uuid_tag.clone())
 197        }
 198
 199        content
 200    }
 201
 202    fn render(&self, context: &Self::RenderContext) -> RenderedContent;
 203}
 204
 205impl Render for TextMessageEventContent {
 206    const TAGS: &'static [&'static str] = &["matrix_text"];
 207    type RenderContext = ();
 208
 209    fn render(&self, _: &Self::RenderContext) -> RenderedContent {
 210        let lines = self
 211            .body
 212            .lines()
 213            .map(|l| RenderedLine {
 214                message: l.to_owned(),
 215                tags: self.tags(),
 216            })
 217            .collect();
 218        // TODO: parse and render using the formatted body.
 219        RenderedContent { lines }
 220    }
 221}
 222
 223impl Render for EmoteMessageEventContent {
 224    const TAGS: &'static [&'static str] = &["matrix_emote"];
 225    type RenderContext = WeechatRoomMember;
 226
 227    fn prefix(&self, _: &WeechatRoomMember) -> String {
 228        Weechat::prefix(Prefix::Action)
 229    }
 230
 231    fn render(&self, sender: &Self::RenderContext) -> RenderedContent {
 232        // TODO: parse and render using the formatted body.
 233        // TODO: handle multiple lines in the body.
 234        let message = format!("{} {}", sender.nick(), self.body);
 235
 236        let line = RenderedLine {
 237            message,
 238            tags: self.tags(),
 239        };
 240
 241        RenderedContent { lines: vec![line] }
 242    }
 243}
 244
 245impl Render for LocationMessageEventContent {
 246    const TAGS: &'static [&'static str] = &["matrix_location"];
 247    type RenderContext = WeechatRoomMember;
 248
 249    fn prefix(&self, _: &WeechatRoomMember) -> String {
 250        Weechat::prefix(Prefix::Action)
 251    }
 252
 253    fn render(&self, sender: &Self::RenderContext) -> RenderedContent {
 254        let message = format!(
 255            "{} has shared a location: {color_delimiter}<{color_reset}{}{color_delimiter}>\
 256            [{color_reset}{}{color_delimiter}]{color_reset}",
 257            sender.nick(),
 258            self.body,
 259            self.geo_uri,
 260            color_delimiter = Weechat::color("color_delimiter"),
 261            color_reset = Weechat::color("reset")
 262        );
 263
 264        let line = RenderedLine {
 265            message,
 266            tags: self.tags(),
 267        };
 268
 269        RenderedContent { lines: vec![line] }
 270    }
 271}
 272
 273impl Render for NoticeMessageEventContent {
 274    const TAGS: &'static [&'static str] = &["matrix_notice"];
 275    type RenderContext = WeechatRoomMember;
 276
 277    fn prefix(&self, _: &WeechatRoomMember) -> String {
 278        Weechat::prefix(Prefix::Network)
 279    }
 280
 281    fn render(&self, sender: &Self::RenderContext) -> RenderedContent {
 282        // TODO: parse and render using the formatted body.
 283        let message = format!(
 284            "{color_notice}Notice\
 285            {color_delim}({color_reset}{}{color_delim}){color_reset}: {}",
 286            sender.nick(),
 287            self.body,
 288            color_notice = Weechat::color("irc.color.notice"),
 289            color_delim = Weechat::color("chat_delimiters"),
 290            color_reset = Weechat::color("reset"),
 291        );
 292
 293        let line = RenderedLine {
 294            message,
 295            tags: self.tags(),
 296        };
 297
 298        RenderedContent { lines: vec![line] }
 299    }
 300}
 301
 302impl Render for ServerNoticeMessageEventContent {
 303    const TAGS: &'static [&'static str] = &["matrix_server_notice"];
 304    type RenderContext = WeechatRoomMember;
 305
 306    fn prefix(&self, _: &WeechatRoomMember) -> String {
 307        Weechat::prefix(Prefix::Network)
 308    }
 309
 310    fn render(&self, sender: &Self::RenderContext) -> RenderedContent {
 311        let message = format!(
 312            "{color_notice}Server notice\
 313            {color_delim}({color_reset}{}{color_delim}){color_reset}: {}",
 314            sender.nick(),
 315            self.body,
 316            color_notice = Weechat::color("irc.color.notice"),
 317            color_delim = Weechat::color("chat_delimiters"),
 318            color_reset = Weechat::color("reset"),
 319        );
 320
 321        let line = RenderedLine {
 322            message,
 323            tags: self.tags(),
 324        };
 325
 326        RenderedContent { lines: vec![line] }
 327    }
 328}
 329
 330/// Create an HTTP download path from a matrix content URI
 331fn mxc_to_http_download_path(
 332    mxc_url: Url,
 333) -> Result<String, Box<dyn std::error::Error>> {
 334    Ok(format!(
 335        "/_matrix/media/r0/download/{server_name}{media_id}",
 336        server_name = mxc_url.host_str().ok_or("Missing host")?,
 337        media_id = mxc_url.path(),
 338    ))
 339}
 340
 341/// Convert a matrix content URI to HTTP(s), respecting a user's homeserver
 342fn mxc_to_http(
 343    mxc_url: &MxcUri,
 344    homeserver: &Url,
 345) -> Result<String, Box<dyn std::error::Error>> {
 346    let url = url::Url::parse(mxc_url.as_str())?;
 347
 348    if url.scheme() != "mxc" {
 349        return Err("URL missing MXC scheme".into());
 350    }
 351
 352    if url.path().is_empty() {
 353        return Err("URL missing path".into());
 354    }
 355
 356    Ok(homeserver
 357        .join(&mxc_to_http_download_path(url)?)?
 358        .to_string())
 359}
 360
 361/// Convert a matrix content URI to an encrypted mxc URI, respecting a user's homeserver.
 362///
 363/// The return value of this function will have a URI schema of emxc://. The path of the URI will
 364/// be converted just like the mxc_to_http() function does, but it will also contain query
 365/// parameters that are necessary to decrypt the payload the URI is pointing to.
 366///
 367/// This function is useful to present a clickable URI that can be passed to a plumber program that
 368/// will download and decrypt the content that the matrix content URI is pointing to.
 369///
 370/// The returned URI should never be converted to http and opened directly, as that would expose
 371/// the decryption parameters to any middleman or ISP.
 372fn mxc_to_emxc(
 373    mxc_url: &MxcUri,
 374    homeserver: &Url,
 375    encrypted: &EncryptedFile,
 376) -> Result<String, Box<dyn std::error::Error>> {
 377    let url = url::Url::parse(mxc_url.as_str())?;
 378
 379    if url.scheme() != "mxc" {
 380        return Err("URL missing MXC scheme".into());
 381    }
 382
 383    if url.path().is_empty() {
 384        return Err("URL missing path".into());
 385    }
 386
 387    let host_str = format!(
 388        "emxc://{}",
 389        homeserver
 390            .host_str()
 391            .ok_or("Missing homeserver host string")?
 392    );
 393
 394    let mut emxc_url = url::Url::parse(&host_str)?;
 395    emxc_url
 396        .set_port(homeserver.port_or_known_default())
 397        .map_err(|_| "Can't set port")?;
 398
 399    emxc_url = emxc_url.join(&mxc_to_http_download_path(url)?)?;
 400
 401    // Add query parameters
 402    emxc_url
 403        .query_pairs_mut()
 404        .append_pair("key", &encrypted.key.k.encode())
 405        .append_pair(
 406            "hash",
 407            &encrypted
 408                .hashes
 409                .get("sha256")
 410                .ok_or("Missing sha256 hash")?
 411                .encode(),
 412        )
 413        .append_pair("iv", &encrypted.iv.encode());
 414
 415    Ok(emxc_url.to_string())
 416}
 417
 418fn media_download_command(source: &MediaSource) -> Option<String> {
 419    match source {
 420        MediaSource::Plain(url) => {
 421            Some(format!("/matrix media download {} [file]", url.as_str()))
 422        }
 423        MediaSource::Encrypted(_) => None,
 424    }
 425}
 426
 427impl<C: HasUrlOrFile> Render for C {
 428    type RenderContext = Url;
 429    const TAGS: &'static [&'static str] = &["matrix_media"];
 430
 431    fn render(&self, homeserver: &Self::RenderContext) -> RenderedContent {
 432        // Convert MXC to HTTP(s) or EMXC, but fallback to MXC if unable to.
 433        let mxc_url = match self.encrypted_file() {
 434            Some(encrypted_file) => {
 435                mxc_to_emxc(self.resolve_url(), homeserver, encrypted_file)
 436            }
 437            None => mxc_to_http(self.resolve_url(), homeserver),
 438        }
 439        .unwrap_or_else(|_| self.resolve_url().to_string());
 440
 441        let message = format!(
 442            "{color_delimiter}<{color_reset}{}{color_delimiter}>\
 443                [{color_reset}{}{color_delimiter}]{color_reset}",
 444            self.body(),
 445            mxc_url,
 446            color_delimiter = Weechat::color("color_delimiter"),
 447            color_reset = Weechat::color("reset")
 448        );
 449
 450        let line = RenderedLine {
 451            message,
 452            tags: self.tags(),
 453        };
 454
 455        let mut lines = vec![line];
 456
 457        if let Some(command) = media_download_command(self.source()) {
 458            lines.push(RenderedLine {
 459                message: format!(
 460                    "{}authenticated download: {}",
 461                    Weechat::prefix(Prefix::Network),
 462                    command
 463                ),
 464                tags: self.tags(),
 465            });
 466        }
 467
 468        RenderedContent { lines }
 469    }
 470}
 471
 472impl Render for RoomEncryptedEventContent {
 473    const TAGS: &'static [&'static str] = &["matrix_encrypted"];
 474    type RenderContext = ();
 475
 476    fn render(&self, _: &Self::RenderContext) -> RenderedContent {
 477        let message = format!(
 478            "{}<{}Unable to decrypt message{}>{}",
 479            Weechat::color("chat_delimiters"),
 480            Weechat::color("logger.color.backlog_line"),
 481            Weechat::color("chat_delimiters"),
 482            Weechat::color("reset"),
 483        );
 484
 485        let line = RenderedLine {
 486            message,
 487            // TODO: add tags that allow us decrypt the event at a later point in
 488            // time, sender key, algorithm, session id.
 489            tags: self.tags(),
 490        };
 491
 492        RenderedContent { lines: vec![line] }
 493    }
 494}
 495
 496impl Render for RedactedSyncMessageLikeEvent<RedactedRoomMessageEventContent> {
 497    type RenderContext = WeechatRoomMember;
 498    const TAGS: &'static [&'static str] = &["matrix_redacted"];
 499
 500    fn render(&self, redacter: &Self::RenderContext) -> RenderedContent {
 501        // TODO: add the redaction reason.
 502        let message = format!(
 503            "{}<{}Message redacted by: {}{}>{}",
 504            Weechat::color("chat_delimiters"),
 505            Weechat::color("logger.color.backlog_line"),
 506            redacter.nick(),
 507            Weechat::color("chat_delimiters"),
 508            Weechat::color("reset"),
 509        );
 510
 511        let line = RenderedLine {
 512            message,
 513            tags: self.tags(),
 514        };
 515
 516        RenderedContent { lines: vec![line] }
 517    }
 518}
 519
 520pub enum StartVerificationContext {
 521    Room(OwnedUserId, Verification),
 522    ToDevice(OwnedUserId, Verification),
 523}
 524
 525impl StartVerificationContext {
 526    fn sender(&self) -> &UserId {
 527        match self {
 528            StartVerificationContext::Room(s, _) => &s,
 529            StartVerificationContext::ToDevice(s, _) => &s,
 530        }
 531    }
 532
 533    fn verification(&self) -> &Verification {
 534        match self {
 535            StartVerificationContext::Room(_, v) => &v,
 536            StartVerificationContext::ToDevice(_, v) => &v,
 537        }
 538    }
 539
 540    fn is_self_verification(&self) -> bool {
 541        self.verification().is_self_verification()
 542    }
 543}
 544
 545macro_rules! render_start_content {
 546    ($type: ident) => {
 547        impl Render for $type {
 548            const TAGS: &'static [&'static str] = &[];
 549
 550            type RenderContext = StartVerificationContext;
 551
 552            fn prefix(&self, _: &WeechatRoomMember) -> String {
 553                Weechat::prefix(Prefix::Network)
 554            }
 555
 556            fn render(&self, context: &Self::RenderContext) -> RenderedContent {
 557                let message = match context.verification() {
 558                    Verification::SasV1(sas) => {
 559                        if context.sender() == sas.own_user_id() {
 560                            if context.is_self_verification() {
 561                                if sas.started_from_request() {
 562                                    // We auto accept emoji verifications that start
 563                                    // from a verification request, so don't print
 564                                    // anything.
 565                                    return RenderedContent {
 566                                        lines: vec![],
 567                                    }
 568                                } else {
 569                                    format!(
 570                                        "You have started an interactive emoji \
 571                                            verification, accept on your other device.",
 572                                    )
 573                                }
 574                            } else {
 575                                format!(
 576                                    "You have started an interactive emoji \
 577                                        verification, waiting for {} to accept",
 578                                    sas.other_device().user_id()
 579                                )
 580                            }
 581                        } else {
 582                            if sas.started_from_request() {
 583                                format!(
 584                                    "{} has started an interactive emoji verifiaction \
 585                                        with you, accept with TODO",
 586                                    sas.other_device().user_id()
 587                                )
 588                            } else {
 589                                // We auto accept emoji verifications that start
 590                                // from a verification request, so don't print
 591                                // anything.
 592                                return RenderedContent {
 593                                    lines: vec![],
 594                                }
 595                            }
 596                        }
 597                    }
 598                    Verification::QrV1(_) => {
 599                        // We don't support QR code scanning, so if there's an QR
 600                        // code verification struct it's because someone else
 601                        // scanned our QR code.
 602                        format!(
 603                            "{} has scanned our QR code, confirm that he \
 604                                has done so TODO",
 605                            context.sender(),
 606                        )
 607                    }
 608                    _ => unreachable!(),
 609                };
 610
 611                RenderedContent {
 612                    lines: vec![RenderedLine {
 613                        message,
 614                        tags: self.tags(),
 615                    }],
 616                }
 617            }
 618        }
 619    };
 620}
 621
 622render_start_content!(KeyVerificationStartEventContent);
 623render_start_content!(ToDeviceKeyVerificationStartEventContent);
 624
 625pub enum VerificationContext {
 626    Room(WeechatRoomMember, WeechatRoomMember),
 627    ToDevice(VerificationRequest),
 628}
 629
 630macro_rules! render_request_content {
 631    ($type: ident) => {
 632        impl Render for $type {
 633            const TAGS: &'static [&'static str] = &[];
 634
 635            type RenderContext = VerificationContext;
 636
 637            fn prefix(&self, _: &WeechatRoomMember) -> String {
 638                Weechat::prefix(Prefix::Network)
 639            }
 640
 641            fn render(&self, context: &Self::RenderContext) -> RenderedContent {
 642                let message = match context {
 643                    VerificationContext::Room(own_member, sender) => {
 644                        if own_member == sender {
 645                            "You sent a verification request".to_string()
 646                        } else {
 647                            format!(
 648                                "{} has sent a verification request",
 649                                sender.nick_colored()
 650                            )
 651                        }
 652                    }
 653                    VerificationContext::ToDevice(_) => {
 654                        format!("You have requested this device to be verified")
 655                    }
 656                };
 657
 658                RenderedContent {
 659                    lines: vec![RenderedLine {
 660                        message,
 661                        tags: self.tags(),
 662                    }],
 663                }
 664            }
 665        }
 666    };
 667}
 668
 669render_request_content!(KeyVerificationRequestEventContent);
 670render_request_content!(ToDeviceKeyVerificationRequestEventContent);
 671
 672macro_rules! render_ready_content {
 673    ($type: ident) => {
 674        impl Render for $type {
 675            const TAGS: &'static [&'static str] = &[];
 676
 677            type RenderContext = (WeechatRoomMember, WeechatRoomMember);
 678
 679            fn prefix(&self, _: &WeechatRoomMember) -> String {
 680                Weechat::prefix(Prefix::Network)
 681            }
 682
 683            fn render(&self, context: &Self::RenderContext) -> RenderedContent {
 684                let (own_mebmer, sender) = context;
 685
 686                let message = if own_mebmer == sender {
 687                    "You answered the verification request".to_string()
 688                } else {
 689                    format!(
 690                        "{} has answered the verification request",
 691                        sender.nick_colored()
 692                    )
 693                };
 694
 695                RenderedContent {
 696                    lines: vec![RenderedLine {
 697                        message,
 698                        tags: self.tags(),
 699                    }],
 700                }
 701            }
 702        }
 703    };
 704}
 705
 706render_ready_content!(KeyVerificationReadyEventContent);
 707render_ready_content!(ToDeviceKeyVerificationReadyEventContent);
 708
 709macro_rules! render_key_content {
 710    ($type: ident) => {
 711        impl Render for $type {
 712            const TAGS: &'static [&'static str] = &[];
 713            type RenderContext = SasVerification;
 714
 715            fn prefix(&self, _: &WeechatRoomMember) -> String {
 716                Weechat::prefix(Prefix::Network)
 717            }
 718
 719            fn render(&self, sas: &Self::RenderContext) -> RenderedContent {
 720                let (message, short_auth_string) = if sas.supports_emoji() {
 721                    (
 722                        "Do the emojis match?".to_string(),
 723                        format!("{:?}", sas.emoji()),
 724                    )
 725                } else {
 726                    (
 727                        "Do the decimals match".to_string(),
 728                        format!("{:?}", sas.decimals()),
 729                    )
 730                };
 731
 732                RenderedContent {
 733                    lines: vec![
 734                        RenderedLine {
 735                            message,
 736                            tags: self.tags(),
 737                        },
 738                        RenderedLine {
 739                            message: short_auth_string,
 740                            tags: self.tags(),
 741                        },
 742                    ],
 743                }
 744            }
 745        }
 746    };
 747}
 748
 749render_key_content!(KeyVerificationKeyEventContent);
 750render_key_content!(ToDeviceKeyVerificationKeyEventContent);
 751
 752/// Trait for message event types that contain an optional formatted body.
 753/// `resolve_body` will return the formatted body if present, else fallback to
 754/// the regular body.
 755trait HasFormattedBody {
 756    fn body(&self) -> &str;
 757    fn formatted_body(&self) -> Option<&str>;
 758    #[inline]
 759    fn resolve_body(&self) -> &str {
 760        self.formatted_body().unwrap_or_else(|| self.body())
 761    }
 762}
 763
 764// Repeating this for each event type would get boring fast so lets use a simple
 765// macro to implement the trait for a struct that has a `body` and
 766// `formatted_body` field
 767macro_rules! has_formatted_body {
 768    ($content: ident) => {
 769        impl HasFormattedBody for $content {
 770            #[inline]
 771            fn body(&self) -> &str {
 772                &self.body
 773            }
 774
 775            #[inline]
 776            fn formatted_body(&self) -> Option<&str> {
 777                self.formatted.as_ref().map(|f| f.body.as_ref())
 778            }
 779        }
 780    };
 781}
 782
 783/// This trait is implemented for message types that can contain either an URL
 784/// or an encrypted file. One of these _must_ be present.
 785pub trait HasUrlOrFile {
 786    fn url(&self) -> Option<&MxcUri>;
 787
 788    fn body(&self) -> &str;
 789
 790    #[inline]
 791    fn resolve_url(&self) -> &MxcUri {
 792        match self.source() {
 793            MediaSource::Plain(s) => s,
 794            MediaSource::Encrypted(e) => &e.url,
 795        }
 796    }
 797
 798    fn encrypted_file(&self) -> Option<&EncryptedFile>;
 799
 800    fn source(&self) -> &MediaSource;
 801}
 802
 803// Same as above: a simple macro to implement the trait for structs with `url`
 804// and `file` fields.
 805macro_rules! has_url_or_file {
 806    ($content: ident) => {
 807        impl HasUrlOrFile for $content {
 808            fn body(&self) -> &str {
 809                &self.body
 810            }
 811
 812            #[inline]
 813            fn url(&self) -> Option<&MxcUri> {
 814                match &self.source {
 815                    MediaSource::Plain(url) => Some(url),
 816                    _ => None,
 817                }
 818            }
 819
 820            fn source(&self) -> &MediaSource {
 821                &self.source
 822            }
 823
 824            fn encrypted_file(&self) -> Option<&EncryptedFile> {
 825                match &self.source {
 826                    MediaSource::Encrypted(e) => Some(&e),
 827                    _ => None,
 828                }
 829            }
 830        }
 831    };
 832}
 833
 834// this actually implements the trait for different event types
 835has_formatted_body!(EmoteMessageEventContent);
 836has_formatted_body!(NoticeMessageEventContent);
 837has_formatted_body!(TextMessageEventContent);
 838
 839has_url_or_file!(AudioMessageEventContent);
 840has_url_or_file!(FileMessageEventContent);
 841has_url_or_file!(ImageMessageEventContent);
 842has_url_or_file!(VideoMessageEventContent);
 843
 844/// Rendering implementation for membership events (joins, leaves, bans, profile
 845/// changes, etc).
 846pub fn render_membership(
 847    event: &OriginalSyncStateEvent<RoomMemberEventContent>,
 848    sender: &WeechatRoomMember,
 849    target: &WeechatRoomMember,
 850) -> RenderedLine {
 851    use MembershipChange::*;
 852    let change_op = event.membership_change();
 853
 854    let operation = match change_op {
 855        None => "did nothing",
 856        Error => "caused an error", // must never happen
 857        Joined => "has joined the room",
 858        Left => "has left the room",
 859        Banned => "was banned by",
 860        Unbanned => "was unbanned by",
 861        Kicked => "was kicked from the room by",
 862        Invited => "was invited to the room by",
 863        KickedAndBanned => "was kicked and banned by",
 864        InvitationRejected => "rejected the invitation",
 865        InvitationRevoked => "had the invitation revoked by",
 866        ProfileChanged { .. } => "_",
 867        _ => "performed an unimplemented operation",
 868    };
 869
 870    fn formatted_name(member: &WeechatRoomMember) -> String {
 871        match member.display_name() {
 872            Some(display_name) => {
 873                format!(
 874                    "{name} {color_delim}({color_reset}{user_id}{color_delim}){color_reset}",
 875                    name = display_name,
 876                    user_id = member.user_id(),
 877                    color_delim = Weechat::color("chat_delimiters"),
 878                    color_reset = Weechat::color("reset"))
 879            }
 880
 881            Option::None => member.user_id().to_string(),
 882        }
 883    }
 884
 885    let (prefix, color_action) = match change_op {
 886        Joined => (Prefix::Join, "green"),
 887        Banned | ProfileChanged { .. } | Invited => {
 888            (Prefix::Network, "magenta")
 889        }
 890        _ => (Prefix::Quit, "red"),
 891    };
 892
 893    let color_action = Weechat::color(color_action);
 894    let color_reset = Weechat::color("reset");
 895
 896    let operation = format!(
 897        "{color_action}{op}{color_reset}",
 898        color_action = color_action,
 899        op = operation,
 900        color_reset = color_reset
 901    );
 902
 903    let target_name = format!(
 904        "{color_user}{target_name}{color_reset}",
 905        target_name = formatted_name(target),
 906        color_user = Weechat::color("reset"), // TODO
 907        color_reset = Weechat::color("reset")
 908    );
 909
 910    let sender_name = format!(
 911        "{color_user}{sender_name}{color_reset}",
 912        sender_name = formatted_name(sender),
 913        color_user = Weechat::color("reset"), // TODO
 914        color_reset = Weechat::color("reset")
 915    );
 916
 917    let message = match change_op {
 918        ProfileChanged {
 919            displayname_change,
 920            avatar_url_change,
 921        } => {
 922            let new_display_name = &event.content.displayname;
 923
 924            // TODO: Should we display the new avatar URL?
 925            // let new_avatar = self.content.avatar_url.as_ref();
 926
 927            match (displayname_change.is_some(), avatar_url_change.is_some()) {
 928                (false, true) =>
 929                    format!(
 930                        "{prefix}{target} {color_action}changed their avatar{color_reset}",
 931                        prefix = Weechat::prefix(prefix),
 932                        target = target_name,
 933                        color_action = color_action,
 934                        color_reset = color_reset
 935                        ),
 936                (true, false) => {
 937                    match new_display_name {
 938                        Some(name) => format!(
 939                            "{prefix}{target} {color_action}changed their display name to{color_reset} {new}",
 940                            prefix = Weechat::prefix(prefix),
 941                            target = event.prev_content().as_ref().and_then(|p| p.displayname.clone()).unwrap_or(target_name),
 942                            new = name,
 943                            color_action = color_action,
 944                            color_reset = color_reset
 945                            ),
 946                        Option::None => format!(
 947                            "{prefix}{target} {color_action}removed their display name{color_reset}",
 948                            prefix = Weechat::prefix(prefix),
 949                            target = target_name,
 950                            color_action = color_action,
 951                            color_reset = color_reset
 952                            ),
 953                    }
 954                }
 955                (true, true) =>
 956                    match new_display_name {
 957                        Some(name) => format!(
 958                            "{prefix}{target} {color_action}changed their avatar \
 959                            and changed their display name to{color_reset} {new}",
 960                            prefix = Weechat::prefix(prefix),
 961                            target = target_name,
 962                            new = name,
 963                            color_action = color_action,
 964                            color_reset = color_reset
 965                            ),
 966                        Option::None => format!(
 967                            "{prefix}{target} {color_action}changed their \
 968                            avatar and removed display name{color_reset}",
 969                            prefix = Weechat::prefix(prefix),
 970                            target = target_name,
 971                            color_action = color_action,
 972                            color_reset = color_reset
 973                            ),
 974                    }
 975                (false, false) =>
 976                    "Cannot happen: got profile changed but nothing really changed".to_string()
 977            }
 978        }
 979        Banned | Unbanned | Kicked | Invited | InvitationRevoked
 980        | KickedAndBanned => format!(
 981            "{prefix}{target} {op} {sender}",
 982            prefix = Weechat::prefix(prefix),
 983            target = target_name,
 984            op = operation,
 985            sender = sender_name
 986        ),
 987        _ => format!(
 988            "{prefix}{target} {op}",
 989            prefix = Weechat::prefix(prefix),
 990            target = target_name,
 991            op = operation
 992        ),
 993    };
 994
 995    RenderedLine {
 996        tags: vec!["matrix_membership".to_owned()],
 997        message,
 998    }
 999}
1000
1001#[cfg(test)]
1002mod tests {
1003    use matrix_sdk::ruma::{
1004        events::room::{EncryptedFileInit, JsonWebKeyInit},
1005        serde::Base64,
1006        OwnedMxcUri,
1007    };
1008
1009    use super::*;
1010
1011    #[test]
1012    fn test_mxc_to_http() {
1013        let homeserver = url::Url::parse("https://matrix.org").unwrap();
1014        let mxc_url = OwnedMxcUri::from("mxc://matrix.org/some-media-id");
1015        let expected =
1016            "https://matrix.org/_matrix/media/r0/download/matrix.org/some-media-id";
1017        assert_eq!(expected, mxc_to_http(&mxc_url, &homeserver).unwrap());
1018    }
1019
1020    #[test]
1021    fn test_emxc_to_http() {
1022        use std::collections::BTreeMap;
1023
1024        let homeserver = url::Url::parse("https://matrix.org").unwrap();
1025        let mxc_url = OwnedMxcUri::from("mxc://matrix.org/some-media-id");
1026        let mut hashes: BTreeMap<String, Base64> = BTreeMap::new();
1027        hashes.insert("sha256".to_string(), Base64::parse("aGFzaA").unwrap());
1028        let encrypt_info = EncryptedFileInit {
1029            key: JsonWebKeyInit {
1030                k: Base64::parse("dGVzdA").unwrap(),
1031                kty: "oct".to_string(),
1032                key_ops: vec![],
1033                ext: true,
1034                alg: "A256CTR".to_string(),
1035            }
1036            .into(),
1037            iv: Base64::parse("aXY").unwrap(),
1038            v: "v2".to_string(),
1039            url: OwnedMxcUri::from("mxc://some-url"),
1040            hashes,
1041        }
1042        .into();
1043        let expected =
1044            "emxc://matrix.org:443/_matrix/media/r0/download/matrix.org/some-media-id?key=dGVzdA&hash=aGFzaA&iv=aXY";
1045        assert_eq!(
1046            expected,
1047            mxc_to_emxc(&mxc_url, &homeserver, &encrypt_info).unwrap()
1048        );
1049    }
1050
1051    #[test]
1052    fn test_plain_media_download_command() {
1053        let source = MediaSource::Plain(OwnedMxcUri::from(
1054            "mxc://matrix.org/some-media-id",
1055        ));
1056
1057        assert_eq!(
1058            Some(
1059                "/matrix media download mxc://matrix.org/some-media-id [file]"
1060                    .to_owned()
1061            ),
1062            media_download_command(&source)
1063        );
1064    }
1065
1066    #[test]
1067    fn test_encrypted_media_has_no_plain_download_command() {
1068        use std::collections::BTreeMap;
1069
1070        let mut hashes: BTreeMap<String, Base64> = BTreeMap::new();
1071        hashes.insert("sha256".to_string(), Base64::parse("aGFzaA").unwrap());
1072        let encrypt_info = EncryptedFileInit {
1073            key: JsonWebKeyInit {
1074                k: Base64::parse("dGVzdA").unwrap(),
1075                kty: "oct".to_string(),
1076                key_ops: vec![],
1077                ext: true,
1078                alg: "A256CTR".to_string(),
1079            }
1080            .into(),
1081            iv: Base64::parse("aXY").unwrap(),
1082            v: "v2".to_string(),
1083            url: OwnedMxcUri::from("mxc://some-url"),
1084            hashes,
1085        }
1086        .into();
1087        let source = MediaSource::Encrypted(Box::new(encrypt_info));
1088
1089        assert_eq!(None, media_download_command(&source));
1090    }
1091}