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