src/render.rs

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

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