src/message/compose.rs
529 lines · 19346 bytes
1//! Code for converting composed messages into content to send to the homeserver.
2use std::sync::Arc;
3
4use comrak::options::{BrokenLinkReference, Options};
5use comrak::{ResolvedReference, markdown_to_html};
6use matrix_sdk::ruma::events::room::message::{EmoteMessageEventContent, TextMessageEventContent};
7use nom::branch::alt;
8use nom::bytes::complete::tag;
9use nom::character::complete::space0;
10use nom::combinator::value;
11use nom::{IResult, Parser as _};
12
13use crate::config::MarkupFormat;
14use crate::prelude::*;
15
16fn broken_link_handler(link: BrokenLinkReference<'_>) -> Option<ResolvedReference> {
17 let uri = if let Ok(user_id) = OwnedUserId::from_str(link.normalized) {
18 user_id.matrix_to_uri()
19 } else if let Ok(room_id) = OwnedRoomAliasId::from_str(link.normalized) {
20 room_id.matrix_to_uri()
21 } else if let Ok(room_id) = OwnedRoomId::from_str(link.normalized) {
22 room_id.matrix_to_uri()
23 } else {
24 return None;
25 };
26
27 Some(ResolvedReference {
28 url: uri.to_string(),
29 title: link.normalized.to_string(),
30 })
31}
32
33#[derive(Clone, Debug, Default)]
34enum SlashCommand {
35 /// Send an emote message.
36 Emote,
37
38 /// Send a message as literal HTML.
39 Html,
40
41 /// Send a message without parsing any markup.
42 Plaintext,
43
44 /// Send a Markdown message (the default message markup).
45 #[default]
46 Markdown,
47
48 /// Send a message with confetti effects in clients that show them.
49 Confetti,
50
51 /// Send a message with fireworks effects in clients that show them.
52 Fireworks,
53
54 /// Send a message with heart effects in clients that show them.
55 Hearts,
56
57 /// Send a message with rainfall effects in clients that show them.
58 Rainfall,
59
60 /// Send a message with snowfall effects in clients that show them.
61 Snowfall,
62
63 /// Send a message with heart effects in clients that show them.
64 SpaceInvaders,
65}
66
67impl SlashCommand {
68 fn to_message(&self, input: &str) -> anyhow::Result<MessageType> {
69 let msgtype = match self {
70 SlashCommand::Emote => {
71 let msg = if let Some(html) = text_to_html(input) {
72 EmoteMessageEventContent::html(input, html)
73 } else {
74 EmoteMessageEventContent::plain(input)
75 };
76
77 MessageType::Emote(msg)
78 },
79 SlashCommand::Html => {
80 let msg = TextMessageEventContent::html(input, input);
81 MessageType::Text(msg)
82 },
83 SlashCommand::Plaintext => {
84 let msg = TextMessageEventContent::plain(input);
85 MessageType::Text(msg)
86 },
87 SlashCommand::Markdown => {
88 let msg = text_to_message_content(input.into());
89 MessageType::Text(msg)
90 },
91 SlashCommand::Confetti => {
92 MessageType::new("nic.custom.confetti", input.into(), Default::default())?
93 },
94 SlashCommand::Fireworks => {
95 MessageType::new("nic.custom.fireworks", input.into(), Default::default())?
96 },
97 SlashCommand::Hearts => {
98 MessageType::new("io.element.effect.hearts", input.into(), Default::default())?
99 },
100 SlashCommand::Rainfall => {
101 MessageType::new("io.element.effect.rainfall", input.into(), Default::default())?
102 },
103 SlashCommand::Snowfall => {
104 MessageType::new("io.element.effect.snowfall", input.into(), Default::default())?
105 },
106 SlashCommand::SpaceInvaders => {
107 MessageType::new(
108 "io.element.effects.space_invaders",
109 input.into(),
110 Default::default(),
111 )?
112 },
113 };
114
115 Ok(msgtype)
116 }
117}
118
119impl From<MarkupFormat> for SlashCommand {
120 fn from(markup: MarkupFormat) -> Self {
121 match markup {
122 MarkupFormat::Html => Self::Html,
123 MarkupFormat::Markdown => Self::Markdown,
124 MarkupFormat::Plaintext => Self::Plaintext,
125 }
126 }
127}
128
129fn parse_slash_command_inner(input: &str) -> IResult<&str, SlashCommand> {
130 let (input, _) = space0(input)?;
131 let (input, slash) = alt((
132 value(SlashCommand::Emote, tag("/me ")),
133 value(SlashCommand::Html, tag("/h ")),
134 value(SlashCommand::Html, tag("/html ")),
135 value(SlashCommand::Plaintext, tag("/p ")),
136 value(SlashCommand::Plaintext, tag("/plain ")),
137 value(SlashCommand::Plaintext, tag("/plaintext ")),
138 value(SlashCommand::Markdown, tag("/md ")),
139 value(SlashCommand::Markdown, tag("/markdown ")),
140 value(SlashCommand::Confetti, tag("/confetti ")),
141 value(SlashCommand::Fireworks, tag("/fireworks ")),
142 value(SlashCommand::Hearts, tag("/hearts ")),
143 value(SlashCommand::Rainfall, tag("/rainfall ")),
144 value(SlashCommand::Snowfall, tag("/snowfall ")),
145 value(SlashCommand::SpaceInvaders, tag("/spaceinvaders ")),
146 ))
147 .parse(input)?;
148 let (input, _) = space0(input)?;
149
150 Ok((input, slash))
151}
152
153fn parse_slash_command(input: &str) -> anyhow::Result<(&str, SlashCommand)> {
154 match parse_slash_command_inner(input) {
155 Ok(input) => Ok(input),
156 Err(e) => Err(anyhow::anyhow!("Failed to parse slash command: {e}")),
157 }
158}
159
160/// Check whether this character is not used for markup in Markdown.
161///
162/// Markdown uses just about every ASCII punctuation symbol in some way, especially
163/// once autolinking is involved, so we really just check whether it's non-punctuation or
164/// single/double quotations.
165fn not_markdown_char(c: char) -> bool {
166 if !c.is_ascii_punctuation() {
167 return true;
168 }
169
170 matches!(c, '"' | '\'')
171}
172
173/// Check whether the input actually needs to be processed as Markdown.
174fn not_markdown(input: &str) -> bool {
175 input.chars().all(not_markdown_char)
176}
177
178fn text_to_html(input: &str) -> Option<String> {
179 if not_markdown(input) {
180 return None;
181 }
182
183 let mut options = Options::default();
184 options.extension.autolink = true;
185 options.extension.shortcodes = true;
186 options.extension.strikethrough = true;
187 options.extension.table = true;
188 options.parse.broken_link_callback = Some(Arc::new(broken_link_handler));
189 options.render.hardbreaks = true;
190 markdown_to_html(input, &options).into()
191}
192
193fn text_to_message_content(input: Cow<'_, str>) -> TextMessageEventContent {
194 if let Some(html) = text_to_html(&input) {
195 TextMessageEventContent::html(input, html)
196 } else {
197 TextMessageEventContent::plain(input)
198 }
199}
200
201pub fn text_to_message(
202 input: Cow<'_, str>,
203 default_markup: MarkupFormat,
204) -> RoomMessageEventContent {
205 let (rest, slash) = parse_slash_command(&input)
206 .unwrap_or_else(|_| (&input, SlashCommand::from(default_markup)));
207
208 let msg = slash
209 .to_message(rest)
210 .unwrap_or_else(|_| MessageType::Text(text_to_message_content(input)));
211
212 RoomMessageEventContent::new(msg)
213}
214
215/// Returns `None` if `input` contains a non-text slash command.
216pub fn text_to_text_message_event_content(
217 input: String,
218 default_markup: MarkupFormat,
219) -> Option<TextMessageEventContent> {
220 let (rest, slash) = parse_slash_command(&input)
221 .unwrap_or_else(|_| (&input, SlashCommand::from(default_markup)));
222
223 let content = match slash {
224 SlashCommand::Html => TextMessageEventContent::html(rest, rest),
225 SlashCommand::Plaintext => TextMessageEventContent::plain(rest),
226 SlashCommand::Markdown => text_to_message_content(rest.into()),
227 _ => return None,
228 };
229
230 Some(content)
231}
232
233#[cfg(test)]
234pub mod tests {
235 use super::*;
236
237 #[test]
238 fn test_markdown_autolink() {
239 let input = "http://example.com\n";
240 let content = text_to_message_content(input.into());
241 assert_eq!(content.body, input);
242 assert_eq!(
243 content.formatted.unwrap().body,
244 "<p><a href=\"http://example.com\">http://example.com</a></p>\n"
245 );
246
247 let input = "www.example.com\n";
248 let content = text_to_message_content(input.into());
249 assert_eq!(content.body, input);
250 assert_eq!(
251 content.formatted.unwrap().body,
252 "<p><a href=\"http://www.example.com\">www.example.com</a></p>\n"
253 );
254
255 let input = "See docs (they're at https://iamb.chat)\n";
256 let content = text_to_message_content(input.into());
257 assert_eq!(content.body, input);
258 assert_eq!(
259 content.formatted.unwrap().body,
260 "<p>See docs (they're at <a href=\"https://iamb.chat\">https://iamb.chat</a>)</p>\n"
261 );
262 }
263
264 #[test]
265 fn test_markdown_link_alias() {
266 let input = "[#room1:example.com]\n";
267 let content = text_to_message_content(input.into());
268 assert_eq!(content.body, input);
269 assert_eq!(
270 content.formatted.unwrap().body,
271 "<p><a href=\"https://matrix.to/#/%23room1:example.com\" title=\"#room1:example.com\">#room1:example.com</a></p>\n"
272 );
273
274 let input = "See [other room][#room1:example.com]\n";
275 let content = text_to_message_content(input.into());
276 assert_eq!(content.body, input);
277 assert_eq!(
278 content.formatted.unwrap().body,
279 "<p>See <a href=\"https://matrix.to/#/%23room1:example.com\" title=\"#room1:example.com\">other room</a></p>\n"
280 );
281 }
282
283 #[test]
284 fn test_markdown_link_room() {
285 let input = "[!room1:example.com]\n";
286 let content = text_to_message_content(input.into());
287 assert_eq!(content.body, input);
288 assert_eq!(
289 content.formatted.unwrap().body,
290 "<p><a href=\"https://matrix.to/#/!room1:example.com\" title=\"!room1:example.com\">!room1:example.com</a></p>\n"
291 );
292
293 let input = "See [other room][!room1:example.com]\n";
294 let content = text_to_message_content(input.into());
295 assert_eq!(content.body, input);
296 assert_eq!(
297 content.formatted.unwrap().body,
298 "<p>See <a href=\"https://matrix.to/#/!room1:example.com\" title=\"!room1:example.com\">other room</a></p>\n"
299 );
300 }
301
302 #[test]
303 fn test_markdown_link_user() {
304 let input = "[@user1:example.com]\n";
305 let content = text_to_message_content(input.into());
306 assert_eq!(content.body, input);
307 assert_eq!(
308 content.formatted.unwrap().body,
309 "<p><a href=\"https://matrix.to/#/@user1:example.com\" title=\"@user1:example.com\">@user1:example.com</a></p>\n"
310 );
311
312 let input = "Talk to [Jane][@user1:example.com]\n";
313 let content = text_to_message_content(input.into());
314 assert_eq!(content.body, input);
315 assert_eq!(
316 content.formatted.unwrap().body,
317 "<p>Talk to <a href=\"https://matrix.to/#/@user1:example.com\" title=\"@user1:example.com\">Jane</a></p>\n"
318 );
319 }
320
321 #[test]
322 fn test_markdown_message() {
323 let input = "**bold**\n";
324 let content = text_to_message_content(input.into());
325 assert_eq!(content.body, input);
326 assert_eq!(content.formatted.unwrap().body, "<p><strong>bold</strong></p>\n");
327
328 let input = "*emphasis*\n";
329 let content = text_to_message_content(input.into());
330 assert_eq!(content.body, input);
331 assert_eq!(content.formatted.unwrap().body, "<p><em>emphasis</em></p>\n");
332
333 let input = "`code`\n";
334 let content = text_to_message_content(input.into());
335 assert_eq!(content.body, input);
336 assert_eq!(content.formatted.unwrap().body, "<p><code>code</code></p>\n");
337
338 let input = "```rust\nconst A: usize = 1;\n```\n";
339 let content = text_to_message_content(input.into());
340 assert_eq!(content.body, input);
341 assert_eq!(
342 content.formatted.unwrap().body,
343 "<pre><code class=\"language-rust\">const A: usize = 1;\n</code></pre>\n"
344 );
345
346 let input = ":heart:\n";
347 let content = text_to_message_content(input.into());
348 assert_eq!(content.body, input);
349 assert_eq!(content.formatted.unwrap().body, "<p>\u{2764}\u{FE0F}</p>\n");
350
351 let input = "para *1*\n\npara _2_\n";
352 let content = text_to_message_content(input.into());
353 assert_eq!(content.body, input);
354 assert_eq!(
355 content.formatted.unwrap().body,
356 "<p>para <em>1</em></p>\n<p>para <em>2</em></p>\n"
357 );
358
359 let input = "line 1\nline ~~2~~\n";
360 let content = text_to_message_content(input.into());
361 assert_eq!(content.body, input);
362 assert_eq!(content.formatted.unwrap().body, "<p>line 1<br />\nline <del>2</del></p>\n");
363
364 let input = "# Heading\n## Subheading\n\ntext\n";
365 let content = text_to_message_content(input.into());
366 assert_eq!(content.body, input);
367 assert_eq!(
368 content.formatted.unwrap().body,
369 "<h1>Heading</h1>\n<h2>Subheading</h2>\n<p>text</p>\n"
370 );
371 }
372
373 #[test]
374 fn test_markdown_headers() {
375 let input = "hello\n=====\n";
376 let content = text_to_message_content(input.into());
377 assert_eq!(content.body, input);
378 assert_eq!(content.formatted.unwrap().body, "<h1>hello</h1>\n");
379
380 let input = "hello\n-----\n";
381 let content = text_to_message_content(input.into());
382 assert_eq!(content.body, input);
383 assert_eq!(content.formatted.unwrap().body, "<h2>hello</h2>\n");
384 }
385
386 #[test]
387 fn test_markdown_lists() {
388 let input = "- A\n- B\n- C\n";
389 let content = text_to_message_content(input.into());
390 assert_eq!(content.body, input);
391 assert_eq!(
392 content.formatted.unwrap().body,
393 "<ul>\n<li>A</li>\n<li>B</li>\n<li>C</li>\n</ul>\n"
394 );
395
396 let input = "1) A\n2) B\n3) C\n";
397 let content = text_to_message_content(input.into());
398 assert_eq!(content.body, input);
399 assert_eq!(
400 content.formatted.unwrap().body,
401 "<ol>\n<li>A</li>\n<li>B</li>\n<li>C</li>\n</ol>\n"
402 );
403 }
404
405 #[test]
406 fn test_no_markdown_conversion_on_simple_text() {
407 let input = "para 1\n\npara 2\n";
408 let content = text_to_message_content(input.into());
409 assert_eq!(content.body, input);
410 assert!(content.formatted.is_none());
411
412 let input = "line 1\nline 2\n";
413 let content = text_to_message_content(input.into());
414 assert_eq!(content.body, input);
415 assert!(content.formatted.is_none());
416
417 let input = "isn't markdown\n";
418 let content = text_to_message_content(input.into());
419 assert_eq!(content.body, input);
420 assert!(content.formatted.is_none());
421
422 let input = "\"scare quotes\"\n";
423 let content = text_to_message_content(input.into());
424 assert_eq!(content.body, input);
425 assert!(content.formatted.is_none());
426 }
427
428 #[test]
429 fn text_to_message_slash_commands() {
430 let MessageType::Text(content) =
431 text_to_message("/html <b>bold</b>".into(), Default::default()).msgtype
432 else {
433 panic!("Expected MessageType::Text");
434 };
435 assert_eq!(content.body, "<b>bold</b>");
436 assert_eq!(content.formatted.unwrap().body, "<b>bold</b>");
437
438 let MessageType::Text(content) =
439 text_to_message("/h <b>bold</b>".into(), Default::default()).msgtype
440 else {
441 panic!("Expected MessageType::Text");
442 };
443 assert_eq!(content.body, "<b>bold</b>");
444 assert_eq!(content.formatted.unwrap().body, "<b>bold</b>");
445
446 let MessageType::Text(content) =
447 text_to_message("/plain <b>bold</b>".into(), Default::default()).msgtype
448 else {
449 panic!("Expected MessageType::Text");
450 };
451 assert_eq!(content.body, "<b>bold</b>");
452 assert!(content.formatted.is_none(), "{:?}", content.formatted);
453
454 let MessageType::Text(content) =
455 text_to_message("/p <b>bold</b>".into(), Default::default()).msgtype
456 else {
457 panic!("Expected MessageType::Text");
458 };
459 assert_eq!(content.body, "<b>bold</b>");
460 assert!(content.formatted.is_none(), "{:?}", content.formatted);
461
462 let MessageType::Emote(content) =
463 text_to_message("/me *bold*".into(), Default::default()).msgtype
464 else {
465 panic!("Expected MessageType::Emote");
466 };
467 assert_eq!(content.body, "*bold*");
468 assert_eq!(content.formatted.unwrap().body, "<p><em>bold</em></p>\n");
469
470 let content = text_to_message("/confetti hello".into(), Default::default()).msgtype;
471 assert_eq!(content.msgtype(), "nic.custom.confetti");
472 assert_eq!(content.body(), "hello");
473
474 let content = text_to_message("/fireworks hello".into(), Default::default()).msgtype;
475 assert_eq!(content.msgtype(), "nic.custom.fireworks");
476 assert_eq!(content.body(), "hello");
477
478 let content = text_to_message("/hearts hello".into(), Default::default()).msgtype;
479 assert_eq!(content.msgtype(), "io.element.effect.hearts");
480 assert_eq!(content.body(), "hello");
481
482 let content = text_to_message("/rainfall hello".into(), Default::default()).msgtype;
483 assert_eq!(content.msgtype(), "io.element.effect.rainfall");
484 assert_eq!(content.body(), "hello");
485
486 let content = text_to_message("/snowfall hello".into(), Default::default()).msgtype;
487 assert_eq!(content.msgtype(), "io.element.effect.snowfall");
488 assert_eq!(content.body(), "hello");
489
490 let content = text_to_message("/spaceinvaders hello".into(), Default::default()).msgtype;
491 assert_eq!(content.msgtype(), "io.element.effects.space_invaders");
492 assert_eq!(content.body(), "hello");
493 }
494
495 #[test]
496 fn text_to_message_slash_default() {
497 let MessageType::Text(content) =
498 text_to_message("*hello*".into(), MarkupFormat::Html).msgtype
499 else {
500 panic!("Expected MessageType::Text");
501 };
502 assert_eq!(content.body, "*hello*");
503 assert_eq!(content.formatted.unwrap().body, "*hello*");
504
505 let MessageType::Text(content) =
506 text_to_message("/markdown *hello*".into(), MarkupFormat::Html).msgtype
507 else {
508 panic!("Expected MessageType::Text");
509 };
510 assert_eq!(content.body, "*hello*");
511 assert_eq!(content.formatted.unwrap().body, "<p><em>hello</em></p>\n");
512
513 let MessageType::Text(content) =
514 text_to_message("<b>hello</b>".into(), MarkupFormat::Plaintext).msgtype
515 else {
516 panic!("Expected MessageType::Text");
517 };
518 assert_eq!(content.body, "<b>hello</b>");
519 assert!(content.formatted.is_none(), "{:?}", content.formatted);
520
521 let MessageType::Text(content) =
522 text_to_message("/html <b>hello</b>".into(), MarkupFormat::Plaintext).msgtype
523 else {
524 panic!("Expected MessageType::Text");
525 };
526 assert_eq!(content.body, "<b>hello</b>");
527 assert_eq!(content.formatted.unwrap().body, "<b>hello</b>");
528 }
529}