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