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