src/render.rs

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

615 lines · 19957 bytes

  1use std::{convert::TryInto, time::SystemTime};
  2use url::Url;
  3
  4use matrix_sdk::{
  5    events::{
  6        room::{
  7            encrypted::EncryptedEventContent,
  8            member::{MemberEventContent, MembershipChange},
  9            message::{
 10                AudioMessageEventContent, EmoteMessageEventContent,
 11                FileMessageEventContent, ImageMessageEventContent,
 12                LocationMessageEventContent, NoticeMessageEventContent,
 13                RedactedMessageEventContent, ServerNoticeMessageEventContent,
 14                TextMessageEventContent, VideoMessageEventContent,
 15            },
 16        },
 17        RedactedSyncMessageEvent, SyncStateEvent,
 18    },
 19    identifiers::{EventId, UserId},
 20    uuid::Uuid,
 21};
 22
 23use weechat::{Prefix, Weechat};
 24
 25use crate::room::WeechatRoomMember;
 26
 27/// The rendered version of an event.
 28pub struct RenderedEvent {
 29    /// The UNIX timestamp of the event.
 30    pub message_timestamp: i64,
 31    pub prefix: String,
 32    pub content: RenderedContent,
 33}
 34
 35impl RenderedEvent {
 36    const MSG_TAGS: &'static [&'static str] = &["notify_message"];
 37    const SELF_TAGS: &'static [&'static str] =
 38        &["notify_none", "no_highlight", "self_msg"];
 39
 40    pub fn add_self_tags(self) -> Self {
 41        self.add_tags(Self::SELF_TAGS)
 42    }
 43
 44    pub fn add_msg_tags(self) -> Self {
 45        self.add_tags(Self::MSG_TAGS)
 46    }
 47
 48    fn add_tags(mut self, tags: &[&str]) -> Self {
 49        for line in &mut self.content.lines {
 50            line.tags.extend(tags.iter().map(|tag| tag.to_string()))
 51        }
 52
 53        self
 54    }
 55}
 56
 57#[derive(Debug)]
 58pub struct RenderedLine {
 59    /// The tags of the line.
 60    pub tags: Vec<String>,
 61    /// The message of the line.
 62    pub message: String,
 63}
 64
 65#[derive(Debug)]
 66pub struct RenderedContent {
 67    /// The collection of lines that the event has.
 68    pub lines: Vec<RenderedLine>,
 69}
 70
 71/// Trait allowing events to be rendered for Weechat.
 72pub trait Render {
 73    /// The event specific tags that should be attached to the rendered event.
 74    const TAGS: &'static [&'static str];
 75
 76    /// Some events might need additional context to be rendered. For example,
 77    /// instead of displaying the MXID for the sender, we might want to display
 78    /// the disambiguated display name, which isn't available in the event.
 79    ///
 80    /// This allows the render implementation to be passed some additional data
 81    /// when rendering.
 82    type RenderContext;
 83
 84    fn tags(&self) -> Vec<String> {
 85        Self::TAGS.iter().map(|t| t.to_string()).collect()
 86    }
 87
 88    fn event_tags(
 89        &self,
 90        event_id: &EventId,
 91        sender: &UserId,
 92        nick: &str,
 93        color_name: &str,
 94    ) -> Vec<String> {
 95        let mut tags = self.tags();
 96        let event_tag = format!("matrix_id_{}", event_id.as_str());
 97        let sender_tag = format!("matrix_sender_{}", sender.as_str());
 98        let nick_tag = format!("nick_{}", nick);
 99        let color = format!("prefix_nick_{}", color_name);
100        tags.push(event_tag);
101        tags.push(sender_tag);
102        tags.push(nick_tag);
103        tags.push(color);
104
105        tags
106    }
107
108    fn prefix(&self, sender: &WeechatRoomMember) -> String {
109        format!("{}\t", sender.nick_colored())
110    }
111
112    /// Render the event.
113    fn render_with_prefix(
114        &self,
115        timestamp: &SystemTime,
116        event_id: &EventId,
117        sender: &WeechatRoomMember,
118        context: &Self::RenderContext,
119    ) -> RenderedEvent {
120        let prefix = self.prefix(sender);
121        let mut content = self.render(context);
122        let timestamp: i64 = timestamp
123            .duration_since(std::time::SystemTime::UNIX_EPOCH)
124            .unwrap_or_default()
125            .as_secs()
126            .try_into()
127            .unwrap_or_default();
128
129        let tags = self.event_tags(
130            event_id,
131            &sender.user_id(),
132            &sender.nick(),
133            sender.color(),
134        );
135
136        for line in &mut content.lines {
137            line.tags = tags.clone();
138        }
139
140        RenderedEvent {
141            prefix,
142            message_timestamp: timestamp,
143            content,
144        }
145    }
146
147    fn render_with_prefix_for_echo(
148        &self,
149        sender: &WeechatRoomMember,
150        uuid: Uuid,
151        context: &Self::RenderContext,
152    ) -> RenderedEvent {
153        let content = self.render_for_echo(uuid, context);
154        let prefix = self.prefix(sender);
155
156        RenderedEvent {
157            prefix,
158            message_timestamp: 0,
159            content,
160        }
161    }
162
163    fn render_for_echo(
164        &self,
165        uuid: Uuid,
166        context: &Self::RenderContext,
167    ) -> RenderedContent {
168        let mut content = self.render(context);
169        let uuid_tag = format!("matrix_echo_{}", uuid.to_string());
170
171        for line in &mut content.lines {
172            let message = Weechat::remove_color(&line.message);
173            line.message = format!(
174                "{}{}{}",
175                Weechat::color_pair("darkgray", "default"),
176                message,
177                Weechat::color("reset")
178            );
179            line.tags.push(uuid_tag.clone())
180        }
181
182        content
183    }
184
185    fn render(&self, context: &Self::RenderContext) -> RenderedContent;
186}
187
188impl Render for TextMessageEventContent {
189    const TAGS: &'static [&'static str] = &["matrix_text"];
190    type RenderContext = ();
191
192    fn render(&self, _: &Self::RenderContext) -> RenderedContent {
193        let lines = self
194            .body
195            .lines()
196            .map(|l| RenderedLine {
197                message: l.to_owned(),
198                tags: self.tags(),
199            })
200            .collect();
201        // TODO parse and render using the formattted body.
202        RenderedContent { lines }
203    }
204}
205
206impl Render for EmoteMessageEventContent {
207    const TAGS: &'static [&'static str] = &["matrix_emote"];
208    type RenderContext = WeechatRoomMember;
209
210    fn prefix(&self, _: &WeechatRoomMember) -> String {
211        Weechat::prefix(Prefix::Action)
212    }
213
214    fn render(&self, sender: &Self::RenderContext) -> RenderedContent {
215        // TODO parse and render using the formattted body.
216        // TODO handle multiple lines in the body.
217        let message = format!("{} {}", sender.nick(), self.body);
218
219        let line = RenderedLine {
220            message,
221            tags: self.tags(),
222        };
223
224        RenderedContent { lines: vec![line] }
225    }
226}
227
228impl Render for LocationMessageEventContent {
229    const TAGS: &'static [&'static str] = &["matrix_location"];
230    type RenderContext = WeechatRoomMember;
231
232    fn prefix(&self, _: &WeechatRoomMember) -> String {
233        Weechat::prefix(Prefix::Action)
234    }
235
236    fn render(&self, sender: &Self::RenderContext) -> RenderedContent {
237        let message = format!(
238            "{} has shared a location: {color_delimiter}<{color_reset}{}{color_delimiter}>\
239            [{color_reset}{}{color_delimiter}]{color_reset}",
240            sender.nick(),
241            self.body,
242            self.geo_uri,
243            color_delimiter = Weechat::color("color_delimiter"),
244            color_reset = Weechat::color("reset")
245        );
246
247        let line = RenderedLine {
248            message,
249            tags: self.tags(),
250        };
251
252        RenderedContent { lines: vec![line] }
253    }
254}
255
256impl Render for NoticeMessageEventContent {
257    const TAGS: &'static [&'static str] = &["matrix_notice"];
258    type RenderContext = WeechatRoomMember;
259
260    fn prefix(&self, _: &WeechatRoomMember) -> String {
261        Weechat::prefix(Prefix::Network)
262    }
263
264    fn render(&self, sender: &Self::RenderContext) -> RenderedContent {
265        // TODO parse and render using the formattted body.
266        let message = format!(
267            "{color_notice}Notice\
268            {color_delim}({color_reset}{}{color_delim}){color_reset}: {}",
269            sender.nick(),
270            self.body,
271            color_notice = Weechat::color("irc.color.notice"),
272            color_delim = Weechat::color("chat_delimiters"),
273            color_reset = Weechat::color("reset"),
274        );
275
276        let line = RenderedLine {
277            message,
278            tags: self.tags(),
279        };
280
281        RenderedContent { lines: vec![line] }
282    }
283}
284
285impl Render for ServerNoticeMessageEventContent {
286    const TAGS: &'static [&'static str] = &["matrix_server_notice"];
287    type RenderContext = WeechatRoomMember;
288
289    fn prefix(&self, _: &WeechatRoomMember) -> String {
290        Weechat::prefix(Prefix::Network)
291    }
292
293    fn render(&self, sender: &Self::RenderContext) -> RenderedContent {
294        let message = format!(
295            "{color_notice}Server notice\
296            {color_delim}({color_reset}{}{color_delim}){color_reset}: {}",
297            sender.nick(),
298            self.body,
299            color_notice = Weechat::color("irc.color.notice"),
300            color_delim = Weechat::color("chat_delimiters"),
301            color_reset = Weechat::color("reset"),
302        );
303
304        let line = RenderedLine {
305            message,
306            tags: self.tags(),
307        };
308
309        RenderedContent { lines: vec![line] }
310    }
311}
312
313impl<C: HasUrlOrFile> Render for C {
314    type RenderContext = Url;
315    const TAGS: &'static [&'static str] = &["matrix_media"];
316
317    fn render(&self, _homeserver: &Self::RenderContext) -> RenderedContent {
318        let message = format!(
319            "{color_delimiter}<{color_reset}{}{color_delimiter}>\
320                [{color_reset}{}{color_delimiter}]{color_reset}",
321            self.body(),
322            // FIXME this isn't right, the MXID -> URL transformation depends on
323            // your homeserver URL.
324            self.resolve_url(),
325            color_delimiter = Weechat::color("color_delimiter"),
326            color_reset = Weechat::color("reset")
327        );
328
329        let line = RenderedLine {
330            message,
331            tags: self.tags(),
332        };
333
334        RenderedContent { lines: vec![line] }
335    }
336}
337
338impl Render for EncryptedEventContent {
339    const TAGS: &'static [&'static str] = &["matrix_encrypted"];
340    type RenderContext = ();
341
342    fn render(&self, _: &Self::RenderContext) -> RenderedContent {
343        let message = format!(
344            "{}<{}Unable to decrypt message{}>{}",
345            Weechat::color("chat_delimiters"),
346            Weechat::color("logger.color.backlog_line"),
347            Weechat::color("chat_delimiters"),
348            Weechat::color("reset"),
349        );
350
351        let line = RenderedLine {
352            message,
353            // TODO add tags that allow us decrypt the event at a later point in
354            // time, sender key, algorithm, session id.
355            tags: self.tags(),
356        };
357
358        RenderedContent { lines: vec![line] }
359    }
360}
361
362impl Render for RedactedSyncMessageEvent<RedactedMessageEventContent> {
363    type RenderContext = WeechatRoomMember;
364    const TAGS: &'static [&'static str] = &["matrix_redacted"];
365
366    fn render(&self, redacter: &Self::RenderContext) -> RenderedContent {
367        // TODO add the redaction reason.
368        let message = format!(
369            "{}<{}Message redacted by: {}{}>{}",
370            Weechat::color("chat_delimiters"),
371            Weechat::color("logger.color.backlog_line"),
372            redacter.nick(),
373            Weechat::color("chat_delimiters"),
374            Weechat::color("reset"),
375        );
376
377        let line = RenderedLine {
378            message,
379            tags: self.tags(),
380        };
381
382        RenderedContent { lines: vec![line] }
383    }
384}
385
386/// Trait for message event types that contain an optional formatted body.
387/// `resolve_body` will return the formatted body if present, else fallback to
388/// the regular body.
389trait HasFormattedBody {
390    fn body(&self) -> &str;
391    fn formatted_body(&self) -> Option<&str>;
392    #[inline]
393    fn resolve_body(&self) -> &str {
394        self.formatted_body().unwrap_or_else(|| self.body())
395    }
396}
397
398// Repeating this for each event type would get boring fast so lets use a simple
399// macro to implement the trait for a struct that has a `body` and
400// `formatted_body` field
401macro_rules! has_formatted_body {
402    ($content: ident) => {
403        impl HasFormattedBody for $content {
404            #[inline]
405            fn body(&self) -> &str {
406                &self.body
407            }
408
409            #[inline]
410            fn formatted_body(&self) -> Option<&str> {
411                self.formatted.as_ref().map(|f| f.body.as_ref())
412            }
413        }
414    };
415}
416
417/// This trait is implemented for message types that can contain either an URL
418/// or an encrypted file. One of these _must_ be present.
419pub trait HasUrlOrFile {
420    fn url(&self) -> Option<&str>;
421    fn file(&self) -> Option<&str>;
422    fn body(&self) -> &str;
423    #[inline]
424    fn resolve_url(&self) -> &str {
425        // the file is either encrypted or not encrypted so either `url` or
426        // `file` must exist and unwrapping will never panic
427        self.url().or_else(|| self.file()).unwrap()
428    }
429}
430
431// Same as above: a simple macro to implement the trait for structs with `url`
432// and `file` fields.
433macro_rules! has_url_or_file {
434    ($content: ident) => {
435        impl HasUrlOrFile for $content {
436            fn body(&self) -> &str {
437                &self.body
438            }
439
440            #[inline]
441            fn url(&self) -> Option<&str> {
442                self.url.as_deref()
443            }
444
445            #[inline]
446            fn file(&self) -> Option<&str> {
447                self.file.as_ref().map(|f| f.url.as_str())
448            }
449        }
450    };
451}
452
453// this actually implements the trait for different event types
454has_formatted_body!(EmoteMessageEventContent);
455has_formatted_body!(NoticeMessageEventContent);
456has_formatted_body!(TextMessageEventContent);
457
458has_url_or_file!(AudioMessageEventContent);
459has_url_or_file!(FileMessageEventContent);
460has_url_or_file!(ImageMessageEventContent);
461has_url_or_file!(VideoMessageEventContent);
462
463/// Rendering implementation for membership events (joins, leaves, bans, profile
464/// changes, etc).
465pub fn render_membership(
466    event: &SyncStateEvent<MemberEventContent>,
467    sender: &WeechatRoomMember,
468    target: &WeechatRoomMember,
469) -> String {
470    const _TAGS: &[&str] = &["matrix_membership"];
471    use MembershipChange::*;
472    let change_op = event.membership_change();
473
474    let operation = match change_op {
475        None => "did nothing",
476        Error => "caused an error", // must never happen
477        Joined => "has joined the room",
478        Left => "has left the room",
479        Banned => "was banned by",
480        Unbanned => "was unbanned by",
481        Kicked => "was kicked from the room by",
482        Invited => "was invited to the room by",
483        KickedAndBanned => "was kicked and banned by",
484        InvitationRejected => "rejected the invitation",
485        InvitationRevoked => "had the invitation revoked by",
486        ProfileChanged { .. } => "_",
487        _ => "performed an unimplemented operation",
488    };
489
490    fn formatted_name(member: &WeechatRoomMember) -> String {
491        match member.display_name() {
492            Some(display_name) => {
493                format!(
494                    "{name} {color_delim}({color_reset}{user_id}{color_delim}){color_reset}",
495                    name = display_name,
496                    user_id = member.user_id(),
497                    color_delim = Weechat::color("chat_delimiters"),
498                    color_reset = Weechat::color("reset"))
499            }
500
501            Option::None => member.user_id().to_string(),
502        }
503    }
504
505    let (prefix, color_action) = match change_op {
506        Joined => (Prefix::Join, "green"),
507        Banned | ProfileChanged { .. } | Invited => {
508            (Prefix::Network, "magenta")
509        }
510        _ => (Prefix::Quit, "red"),
511    };
512
513    let color_action = Weechat::color(color_action);
514    let color_reset = Weechat::color("reset");
515
516    let operation = format!(
517        "{color_action}{op}{color_reset}",
518        color_action = color_action,
519        op = operation,
520        color_reset = color_reset
521    );
522
523    let target_name = format!(
524        "{color_user}{target_name}{color_reset}",
525        target_name = formatted_name(target),
526        color_user = Weechat::color("reset"), // TODO
527        color_reset = Weechat::color("reset")
528    );
529
530    let sender_name = format!(
531        "{color_user}{sender_name}{color_reset}",
532        sender_name = formatted_name(sender),
533        color_user = Weechat::color("reset"), // TODO
534        color_reset = Weechat::color("reset")
535    );
536
537    // TODO we should return the tags as well.
538    match change_op {
539        ProfileChanged {
540            displayname_changed,
541            avatar_url_changed,
542        } => {
543            let new_display_name = &event.content.displayname;
544
545            // TODO: Should we display the new avatar URL?
546            // let new_avatar = self.content.avatar_url.as_ref();
547
548            match (displayname_changed, avatar_url_changed) {
549                (false, true) =>
550                    format!(
551                        "{prefix}{target} {color_action}changed their avatar{color_reset}",
552                        prefix = Weechat::prefix(prefix),
553                        target = target_name,
554                        color_action = color_action,
555                        color_reset = color_reset
556                        ),
557                (true, false) => {
558                    match new_display_name {
559                        Some(name) => format!(
560                            "{prefix}{target} {color_action}changed their display name to{color_reset} {new}",
561                            prefix = Weechat::prefix(prefix),
562                            target = event.prev_content.as_ref().map(|p| p.displayname.clone()).flatten().unwrap_or(target_name),
563                            new = name,
564                            color_action = color_action,
565                            color_reset = color_reset
566                            ),
567                        Option::None => format!(
568                            "{prefix}{target} {color_action}removed their display name{color_reset}",
569                            prefix = Weechat::prefix(prefix),
570                            target = target_name,
571                            color_action = color_action,
572                            color_reset = color_reset
573                            ),
574                    }
575                }
576                (true, true) =>
577                    match new_display_name {
578                        Some(name) => format!(
579                            "{prefix}{target} {color_action}changed their avatar \
580                            and changed their display name to{color_reset} {new}",
581                            prefix = Weechat::prefix(prefix),
582                            target = target_name,
583                            new = name,
584                            color_action = color_action,
585                            color_reset = color_reset
586                            ),
587                        Option::None => format!(
588                            "{prefix}{target} {color_action}changed their \
589                            avatar and removed display name{color_reset}",
590                            prefix = Weechat::prefix(prefix),
591                            target = target_name,
592                            color_action = color_action,
593                            color_reset = color_reset
594                            ),
595                    }
596                (false, false) =>
597                    "Cannot happen: got profile changed but nothing really changed".to_string()
598            }
599        }
600        Banned | Unbanned | Kicked | Invited | InvitationRevoked
601        | KickedAndBanned => format!(
602            "{prefix}{target} {op} {sender}",
603            prefix = Weechat::prefix(prefix),
604            target = target_name,
605            op = operation,
606            sender = sender_name
607        ),
608        _ => format!(
609            "{prefix}{target} {op}",
610            prefix = Weechat::prefix(prefix),
611            target = target_name,
612            op = operation
613        ),
614    }
615}