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