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