src/message/compose.rs
528 lines · 19310 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.parse.broken_link_callback = Some(Arc::new(broken_link_handler));
188 options.render.hardbreaks = true;
189 markdown_to_html(input, &options).into()
190}
191
192fn text_to_message_content(input: Cow<'_, str>) -> TextMessageEventContent {
193 if let Some(html) = text_to_html(&input) {
194 TextMessageEventContent::html(input, html)
195 } else {
196 TextMessageEventContent::plain(input)
197 }
198}
199
200pub fn text_to_message(
201 input: Cow<'_, str>,
202 default_markup: MarkupFormat,
203) -> RoomMessageEventContent {
204 let (rest, slash) = parse_slash_command(&input)
205 .unwrap_or_else(|_| (&input, SlashCommand::from(default_markup)));
206
207 let msg = slash
208 .to_message(rest)
209 .unwrap_or_else(|_| MessageType::Text(text_to_message_content(input)));
210
211 RoomMessageEventContent::new(msg)
212}
213
214/// Returns `None` if `input` contains a non-text slash command.
215pub fn text_to_text_message_event_content(
216 input: String,
217 default_markup: MarkupFormat,
218) -> Option<TextMessageEventContent> {
219 let (rest, slash) = parse_slash_command(&input)
220 .unwrap_or_else(|_| (&input, SlashCommand::from(default_markup)));
221
222 let content = match slash {
223 SlashCommand::Html => TextMessageEventContent::html(rest, rest),
224 SlashCommand::Plaintext => TextMessageEventContent::plain(rest),
225 SlashCommand::Markdown => text_to_message_content(rest.into()),
226 _ => return None,
227 };
228
229 Some(content)
230}
231
232#[cfg(test)]
233pub mod tests {
234 use super::*;
235
236 #[test]
237 fn test_markdown_autolink() {
238 let input = "http://example.com\n";
239 let content = text_to_message_content(input.into());
240 assert_eq!(content.body, input);
241 assert_eq!(
242 content.formatted.unwrap().body,
243 "<p><a href=\"http://example.com\">http://example.com</a></p>\n"
244 );
245
246 let input = "www.example.com\n";
247 let content = text_to_message_content(input.into());
248 assert_eq!(content.body, input);
249 assert_eq!(
250 content.formatted.unwrap().body,
251 "<p><a href=\"http://www.example.com\">www.example.com</a></p>\n"
252 );
253
254 let input = "See docs (they're at https://iamb.chat)\n";
255 let content = text_to_message_content(input.into());
256 assert_eq!(content.body, input);
257 assert_eq!(
258 content.formatted.unwrap().body,
259 "<p>See docs (they're at <a href=\"https://iamb.chat\">https://iamb.chat</a>)</p>\n"
260 );
261 }
262
263 #[test]
264 fn test_markdown_link_alias() {
265 let input = "[#room1:example.com]\n";
266 let content = text_to_message_content(input.into());
267 assert_eq!(content.body, input);
268 assert_eq!(
269 content.formatted.unwrap().body,
270 "<p><a href=\"https://matrix.to/#/%23room1:example.com\" title=\"#room1:example.com\">#room1:example.com</a></p>\n"
271 );
272
273 let input = "See [other room][#room1:example.com]\n";
274 let content = text_to_message_content(input.into());
275 assert_eq!(content.body, input);
276 assert_eq!(
277 content.formatted.unwrap().body,
278 "<p>See <a href=\"https://matrix.to/#/%23room1:example.com\" title=\"#room1:example.com\">other room</a></p>\n"
279 );
280 }
281
282 #[test]
283 fn test_markdown_link_room() {
284 let input = "[!room1:example.com]\n";
285 let content = text_to_message_content(input.into());
286 assert_eq!(content.body, input);
287 assert_eq!(
288 content.formatted.unwrap().body,
289 "<p><a href=\"https://matrix.to/#/!room1:example.com\" title=\"!room1:example.com\">!room1:example.com</a></p>\n"
290 );
291
292 let input = "See [other room][!room1:example.com]\n";
293 let content = text_to_message_content(input.into());
294 assert_eq!(content.body, input);
295 assert_eq!(
296 content.formatted.unwrap().body,
297 "<p>See <a href=\"https://matrix.to/#/!room1:example.com\" title=\"!room1:example.com\">other room</a></p>\n"
298 );
299 }
300
301 #[test]
302 fn test_markdown_link_user() {
303 let input = "[@user1:example.com]\n";
304 let content = text_to_message_content(input.into());
305 assert_eq!(content.body, input);
306 assert_eq!(
307 content.formatted.unwrap().body,
308 "<p><a href=\"https://matrix.to/#/@user1:example.com\" title=\"@user1:example.com\">@user1:example.com</a></p>\n"
309 );
310
311 let input = "Talk to [Jane][@user1:example.com]\n";
312 let content = text_to_message_content(input.into());
313 assert_eq!(content.body, input);
314 assert_eq!(
315 content.formatted.unwrap().body,
316 "<p>Talk to <a href=\"https://matrix.to/#/@user1:example.com\" title=\"@user1:example.com\">Jane</a></p>\n"
317 );
318 }
319
320 #[test]
321 fn test_markdown_message() {
322 let input = "**bold**\n";
323 let content = text_to_message_content(input.into());
324 assert_eq!(content.body, input);
325 assert_eq!(content.formatted.unwrap().body, "<p><strong>bold</strong></p>\n");
326
327 let input = "*emphasis*\n";
328 let content = text_to_message_content(input.into());
329 assert_eq!(content.body, input);
330 assert_eq!(content.formatted.unwrap().body, "<p><em>emphasis</em></p>\n");
331
332 let input = "`code`\n";
333 let content = text_to_message_content(input.into());
334 assert_eq!(content.body, input);
335 assert_eq!(content.formatted.unwrap().body, "<p><code>code</code></p>\n");
336
337 let input = "```rust\nconst A: usize = 1;\n```\n";
338 let content = text_to_message_content(input.into());
339 assert_eq!(content.body, input);
340 assert_eq!(
341 content.formatted.unwrap().body,
342 "<pre><code class=\"language-rust\">const A: usize = 1;\n</code></pre>\n"
343 );
344
345 let input = ":heart:\n";
346 let content = text_to_message_content(input.into());
347 assert_eq!(content.body, input);
348 assert_eq!(content.formatted.unwrap().body, "<p>\u{2764}\u{FE0F}</p>\n");
349
350 let input = "para *1*\n\npara _2_\n";
351 let content = text_to_message_content(input.into());
352 assert_eq!(content.body, input);
353 assert_eq!(
354 content.formatted.unwrap().body,
355 "<p>para <em>1</em></p>\n<p>para <em>2</em></p>\n"
356 );
357
358 let input = "line 1\nline ~~2~~\n";
359 let content = text_to_message_content(input.into());
360 assert_eq!(content.body, input);
361 assert_eq!(content.formatted.unwrap().body, "<p>line 1<br />\nline <del>2</del></p>\n");
362
363 let input = "# Heading\n## Subheading\n\ntext\n";
364 let content = text_to_message_content(input.into());
365 assert_eq!(content.body, input);
366 assert_eq!(
367 content.formatted.unwrap().body,
368 "<h1>Heading</h1>\n<h2>Subheading</h2>\n<p>text</p>\n"
369 );
370 }
371
372 #[test]
373 fn test_markdown_headers() {
374 let input = "hello\n=====\n";
375 let content = text_to_message_content(input.into());
376 assert_eq!(content.body, input);
377 assert_eq!(content.formatted.unwrap().body, "<h1>hello</h1>\n");
378
379 let input = "hello\n-----\n";
380 let content = text_to_message_content(input.into());
381 assert_eq!(content.body, input);
382 assert_eq!(content.formatted.unwrap().body, "<h2>hello</h2>\n");
383 }
384
385 #[test]
386 fn test_markdown_lists() {
387 let input = "- A\n- B\n- C\n";
388 let content = text_to_message_content(input.into());
389 assert_eq!(content.body, input);
390 assert_eq!(
391 content.formatted.unwrap().body,
392 "<ul>\n<li>A</li>\n<li>B</li>\n<li>C</li>\n</ul>\n"
393 );
394
395 let input = "1) A\n2) B\n3) C\n";
396 let content = text_to_message_content(input.into());
397 assert_eq!(content.body, input);
398 assert_eq!(
399 content.formatted.unwrap().body,
400 "<ol>\n<li>A</li>\n<li>B</li>\n<li>C</li>\n</ol>\n"
401 );
402 }
403
404 #[test]
405 fn test_no_markdown_conversion_on_simple_text() {
406 let input = "para 1\n\npara 2\n";
407 let content = text_to_message_content(input.into());
408 assert_eq!(content.body, input);
409 assert!(content.formatted.is_none());
410
411 let input = "line 1\nline 2\n";
412 let content = text_to_message_content(input.into());
413 assert_eq!(content.body, input);
414 assert!(content.formatted.is_none());
415
416 let input = "isn't markdown\n";
417 let content = text_to_message_content(input.into());
418 assert_eq!(content.body, input);
419 assert!(content.formatted.is_none());
420
421 let input = "\"scare quotes\"\n";
422 let content = text_to_message_content(input.into());
423 assert_eq!(content.body, input);
424 assert!(content.formatted.is_none());
425 }
426
427 #[test]
428 fn text_to_message_slash_commands() {
429 let MessageType::Text(content) =
430 text_to_message("/html <b>bold</b>".into(), Default::default()).msgtype
431 else {
432 panic!("Expected MessageType::Text");
433 };
434 assert_eq!(content.body, "<b>bold</b>");
435 assert_eq!(content.formatted.unwrap().body, "<b>bold</b>");
436
437 let MessageType::Text(content) =
438 text_to_message("/h <b>bold</b>".into(), Default::default()).msgtype
439 else {
440 panic!("Expected MessageType::Text");
441 };
442 assert_eq!(content.body, "<b>bold</b>");
443 assert_eq!(content.formatted.unwrap().body, "<b>bold</b>");
444
445 let MessageType::Text(content) =
446 text_to_message("/plain <b>bold</b>".into(), Default::default()).msgtype
447 else {
448 panic!("Expected MessageType::Text");
449 };
450 assert_eq!(content.body, "<b>bold</b>");
451 assert!(content.formatted.is_none(), "{:?}", content.formatted);
452
453 let MessageType::Text(content) =
454 text_to_message("/p <b>bold</b>".into(), Default::default()).msgtype
455 else {
456 panic!("Expected MessageType::Text");
457 };
458 assert_eq!(content.body, "<b>bold</b>");
459 assert!(content.formatted.is_none(), "{:?}", content.formatted);
460
461 let MessageType::Emote(content) =
462 text_to_message("/me *bold*".into(), Default::default()).msgtype
463 else {
464 panic!("Expected MessageType::Emote");
465 };
466 assert_eq!(content.body, "*bold*");
467 assert_eq!(content.formatted.unwrap().body, "<p><em>bold</em></p>\n");
468
469 let content = text_to_message("/confetti hello".into(), Default::default()).msgtype;
470 assert_eq!(content.msgtype(), "nic.custom.confetti");
471 assert_eq!(content.body(), "hello");
472
473 let content = text_to_message("/fireworks hello".into(), Default::default()).msgtype;
474 assert_eq!(content.msgtype(), "nic.custom.fireworks");
475 assert_eq!(content.body(), "hello");
476
477 let content = text_to_message("/hearts hello".into(), Default::default()).msgtype;
478 assert_eq!(content.msgtype(), "io.element.effect.hearts");
479 assert_eq!(content.body(), "hello");
480
481 let content = text_to_message("/rainfall hello".into(), Default::default()).msgtype;
482 assert_eq!(content.msgtype(), "io.element.effect.rainfall");
483 assert_eq!(content.body(), "hello");
484
485 let content = text_to_message("/snowfall hello".into(), Default::default()).msgtype;
486 assert_eq!(content.msgtype(), "io.element.effect.snowfall");
487 assert_eq!(content.body(), "hello");
488
489 let content = text_to_message("/spaceinvaders hello".into(), Default::default()).msgtype;
490 assert_eq!(content.msgtype(), "io.element.effects.space_invaders");
491 assert_eq!(content.body(), "hello");
492 }
493
494 #[test]
495 fn text_to_message_slash_default() {
496 let MessageType::Text(content) =
497 text_to_message("*hello*".into(), MarkupFormat::Html).msgtype
498 else {
499 panic!("Expected MessageType::Text");
500 };
501 assert_eq!(content.body, "*hello*");
502 assert_eq!(content.formatted.unwrap().body, "*hello*");
503
504 let MessageType::Text(content) =
505 text_to_message("/markdown *hello*".into(), MarkupFormat::Html).msgtype
506 else {
507 panic!("Expected MessageType::Text");
508 };
509 assert_eq!(content.body, "*hello*");
510 assert_eq!(content.formatted.unwrap().body, "<p><em>hello</em></p>\n");
511
512 let MessageType::Text(content) =
513 text_to_message("<b>hello</b>".into(), MarkupFormat::Plaintext).msgtype
514 else {
515 panic!("Expected MessageType::Text");
516 };
517 assert_eq!(content.body, "<b>hello</b>");
518 assert!(content.formatted.is_none(), "{:?}", content.formatted);
519
520 let MessageType::Text(content) =
521 text_to_message("/html <b>hello</b>".into(), MarkupFormat::Plaintext).msgtype
522 else {
523 panic!("Expected MessageType::Text");
524 };
525 assert_eq!(content.body, "<b>hello</b>");
526 assert_eq!(content.formatted.unwrap().body, "<b>hello</b>");
527 }
528}