src/render.rs

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

596 lines · 19611 bytes

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