src/render.rs

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

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