src/message/compose.rs

376 lines · 13586 bytes

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