Commit 04480eda1b

04480eda1b715070ba2f257a2fde7f68ba91fd66

parent: 653287478e

Unregistered key

Ulyssa <git@ulyssa.dev> · 2024-08-08 05:49 UTC
committer: <noreply@github.com>

Add message slash commands (#317)

Layout: unified · split

Cargo.lock +2
@@ -2093,6 +2093,7 @@ dependencies = [
20932093name = "iamb"
20942094version = "0.0.10-alpha.1"
20952095dependencies = [
2096 "anyhow",
20962097 "bitflags 2.5.0",
20972098 "chrono",
20982099 "clap",
@@ -2114,6 +2115,7 @@ dependencies = [
21142115 "mime_guess",
21152116 "modalkit",
21162117 "modalkit-ratatui",
2118 "nom",
21172119 "notify-rust",
21182120 "open",
21192121 "pretty_assertions",
Cargo.toml +2
@@ -26,6 +26,7 @@ default-features = false
2626features = ["build", "git", "gitcl",]
2727
2828[dependencies]
29anyhow = "1.0"
2930bitflags = "^2.3"
3031chrono = "0.4"
3132clap = {version = "~4.3", features = ["derive"]}
@@ -41,6 +42,7 @@ libc = "0.2"
4142markup5ever_rcdom = "0.2.0"
4243mime = "^0.3.16"
4344mime_guess = "^2.0.4"
45nom = "7.0.0"
4446notify-rust = { version = "4.10.0", default-features = false, features = ["zbus", "serde"] }
4547open = "3.2.0"
4648rand = "0.8.5"
docs/iamb.1 +37
@@ -188,6 +188,43 @@ Close all but one tab.
188188Go to the preview tab.
189189.El
190190
191.Sh "SLASH COMMANDS"
192.Bl -tag -width Ds
193.It Sy "/markdown" , Sy "/md"
194Interpret the message body as Markdown markup.
195This is the default behaviour.
196.It Sy "/html" , Sy "/h"
197Send the message body as literal HTML.
198.It Sy "/plaintext" , Sy "/plain" , Sy "/p"
199Do not interpret any markup in the message body and send it as it is.
200.It Sy "/me"
201Send an emote message.
202.It Sy "/confetti"
203Produces no effect in
204.Nm ,
205but will display confetti in Matrix clients that support doing so.
206.It Sy "/fireworks"
207Produces no effect in
208.Nm ,
209but will display fireworks in Matrix clients that support doing so.
210.It Sy "/hearts"
211Produces no effect in
212.Nm ,
213but will display floating hearts in Matrix clients that support doing so.
214.It Sy "/rainfall"
215Produces no effect in
216.Nm ,
217but will display rainfall in Matrix clients that support doing so.
218.It Sy "/snowfall"
219Produces no effect in
220.Nm ,
221but will display snowfall in Matrix clients that support doing so.
222.It Sy "/spaceinvaders"
223Produces no effect in
224.Nm ,
225but will display aliens from Space Invaders in Matrix clients that support doing so.
226.El
227
191228.Sh EXAMPLES
192229.Ss Example 1: Starting with a specific profile
193230To start with a profile named
src/message/compose.rs added +290
@@ -0,0 +1,290 @@
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 html = text_to_html(input);
57 let msg = EmoteMessageEventContent::html(input, html);
58 MessageType::Emote(msg)
59 },
60 SlashCommand::Html => {
61 let msg = TextMessageEventContent::html(input, input);
62 MessageType::Text(msg)
63 },
64 SlashCommand::Plaintext => {
65 let msg = TextMessageEventContent::plain(input);
66 MessageType::Text(msg)
67 },
68 SlashCommand::Markdown => {
69 let html = text_to_html(input);
70 let msg = TextMessageEventContent::html(input, html);
71 MessageType::Text(msg)
72 },
73 SlashCommand::Confetti => {
74 MessageType::new("nic.custom.confetti", input.into(), Default::default())?
75 },
76 SlashCommand::Fireworks => {
77 MessageType::new("nic.custom.fireworks", input.into(), Default::default())?
78 },
79 SlashCommand::Hearts => {
80 MessageType::new("io.element.effect.hearts", input.into(), Default::default())?
81 },
82 SlashCommand::Rainfall => {
83 MessageType::new("io.element.effect.rainfall", input.into(), Default::default())?
84 },
85 SlashCommand::Snowfall => {
86 MessageType::new("io.element.effect.snowfall", input.into(), Default::default())?
87 },
88 SlashCommand::SpaceInvaders => {
89 MessageType::new(
90 "io.element.effects.space_invaders",
91 input.into(),
92 Default::default(),
93 )?
94 },
95 };
96
97 Ok(msgtype)
98 }
99}
100
101fn parse_slash_command_inner(input: &str) -> IResult<&str, SlashCommand> {
102 let (input, _) = space0(input)?;
103 let (input, slash) = alt((
104 value(SlashCommand::Emote, tag("/me ")),
105 value(SlashCommand::Html, tag("/h ")),
106 value(SlashCommand::Html, tag("/html ")),
107 value(SlashCommand::Plaintext, tag("/p ")),
108 value(SlashCommand::Plaintext, tag("/plain ")),
109 value(SlashCommand::Plaintext, tag("/plaintext ")),
110 value(SlashCommand::Markdown, tag("/md ")),
111 value(SlashCommand::Markdown, tag("/markdown ")),
112 value(SlashCommand::Confetti, tag("/confetti ")),
113 value(SlashCommand::Fireworks, tag("/fireworks ")),
114 value(SlashCommand::Hearts, tag("/hearts ")),
115 value(SlashCommand::Rainfall, tag("/rainfall ")),
116 value(SlashCommand::Snowfall, tag("/snowfall ")),
117 value(SlashCommand::SpaceInvaders, tag("/spaceinvaders ")),
118 ))(input)?;
119 let (input, _) = space0(input)?;
120
121 Ok((input, slash))
122}
123
124fn parse_slash_command(input: &str) -> anyhow::Result<(&str, SlashCommand)> {
125 match parse_slash_command_inner(input) {
126 Ok(input) => Ok(input),
127 Err(e) => Err(anyhow::anyhow!("Failed to parse slash command: {e}")),
128 }
129}
130
131fn text_to_html(input: &str) -> String {
132 let mut options = ComrakOptions::default();
133 options.extension.autolink = true;
134 options.extension.shortcodes = true;
135 options.extension.strikethrough = true;
136 options.render.hardbreaks = true;
137 markdown_to_html(input, &options)
138}
139
140fn text_to_message_content(input: String) -> TextMessageEventContent {
141 let html = text_to_html(input.as_str());
142 TextMessageEventContent::html(input, html)
143}
144
145pub fn text_to_message(input: String) -> RoomMessageEventContent {
146 let msg = parse_slash_command(input.as_str())
147 .and_then(|(input, slash)| slash.to_message(input))
148 .unwrap_or_else(|_| MessageType::Text(text_to_message_content(input)));
149
150 RoomMessageEventContent::new(msg)
151}
152
153#[cfg(test)]
154pub mod tests {
155 use super::*;
156
157 #[test]
158 fn test_markdown_autolink() {
159 let input = "http://example.com\n";
160 let content = text_to_message_content(input.into());
161 assert_eq!(content.body, input);
162 assert_eq!(
163 content.formatted.unwrap().body,
164 "<p><a href=\"http://example.com\">http://example.com</a></p>\n"
165 );
166
167 let input = "www.example.com\n";
168 let content = text_to_message_content(input.into());
169 assert_eq!(content.body, input);
170 assert_eq!(
171 content.formatted.unwrap().body,
172 "<p><a href=\"http://www.example.com\">www.example.com</a></p>\n"
173 );
174
175 let input = "See docs (they're at https://iamb.chat)\n";
176 let content = text_to_message_content(input.into());
177 assert_eq!(content.body, input);
178 assert_eq!(
179 content.formatted.unwrap().body,
180 "<p>See docs (they're at <a href=\"https://iamb.chat\">https://iamb.chat</a>)</p>\n"
181 );
182 }
183
184 #[test]
185 fn test_markdown_message() {
186 let input = "**bold**\n";
187 let content = text_to_message_content(input.into());
188 assert_eq!(content.body, input);
189 assert_eq!(content.formatted.unwrap().body, "<p><strong>bold</strong></p>\n");
190
191 let input = "*emphasis*\n";
192 let content = text_to_message_content(input.into());
193 assert_eq!(content.body, input);
194 assert_eq!(content.formatted.unwrap().body, "<p><em>emphasis</em></p>\n");
195
196 let input = "`code`\n";
197 let content = text_to_message_content(input.into());
198 assert_eq!(content.body, input);
199 assert_eq!(content.formatted.unwrap().body, "<p><code>code</code></p>\n");
200
201 let input = "```rust\nconst A: usize = 1;\n```\n";
202 let content = text_to_message_content(input.into());
203 assert_eq!(content.body, input);
204 assert_eq!(
205 content.formatted.unwrap().body,
206 "<pre><code class=\"language-rust\">const A: usize = 1;\n</code></pre>\n"
207 );
208
209 let input = ":heart:\n";
210 let content = text_to_message_content(input.into());
211 assert_eq!(content.body, input);
212 assert_eq!(content.formatted.unwrap().body, "<p>\u{2764}\u{FE0F}</p>\n");
213
214 let input = "para 1\n\npara 2\n";
215 let content = text_to_message_content(input.into());
216 assert_eq!(content.body, input);
217 assert_eq!(content.formatted.unwrap().body, "<p>para 1</p>\n<p>para 2</p>\n");
218
219 let input = "line 1\nline 2\n";
220 let content = text_to_message_content(input.into());
221 assert_eq!(content.body, input);
222 assert_eq!(content.formatted.unwrap().body, "<p>line 1<br />\nline 2</p>\n");
223
224 let input = "# Heading\n## Subheading\n\ntext\n";
225 let content = text_to_message_content(input.into());
226 assert_eq!(content.body, input);
227 assert_eq!(
228 content.formatted.unwrap().body,
229 "<h1>Heading</h1>\n<h2>Subheading</h2>\n<p>text</p>\n"
230 );
231 }
232
233 #[test]
234 fn text_to_message_slash_commands() {
235 let MessageType::Text(content) = text_to_message("/html <b>bold</b>".into()).msgtype else {
236 panic!("Expected MessageType::Text");
237 };
238 assert_eq!(content.body, "<b>bold</b>");
239 assert_eq!(content.formatted.unwrap().body, "<b>bold</b>");
240
241 let MessageType::Text(content) = text_to_message("/h <b>bold</b>".into()).msgtype else {
242 panic!("Expected MessageType::Text");
243 };
244 assert_eq!(content.body, "<b>bold</b>");
245 assert_eq!(content.formatted.unwrap().body, "<b>bold</b>");
246
247 let MessageType::Text(content) = text_to_message("/plain <b>bold</b>".into()).msgtype
248 else {
249 panic!("Expected MessageType::Text");
250 };
251 assert_eq!(content.body, "<b>bold</b>");
252 assert!(content.formatted.is_none(), "{:?}", content.formatted);
253
254 let MessageType::Text(content) = text_to_message("/p <b>bold</b>".into()).msgtype else {
255 panic!("Expected MessageType::Text");
256 };
257 assert_eq!(content.body, "<b>bold</b>");
258 assert!(content.formatted.is_none(), "{:?}", content.formatted);
259
260 let MessageType::Emote(content) = text_to_message("/me *bold*".into()).msgtype else {
261 panic!("Expected MessageType::Emote");
262 };
263 assert_eq!(content.body, "*bold*");
264 assert_eq!(content.formatted.unwrap().body, "<p><em>bold</em></p>\n");
265
266 let content = text_to_message("/confetti hello".into()).msgtype;
267 assert_eq!(content.msgtype(), "nic.custom.confetti");
268 assert_eq!(content.body(), "hello");
269
270 let content = text_to_message("/fireworks hello".into()).msgtype;
271 assert_eq!(content.msgtype(), "nic.custom.fireworks");
272 assert_eq!(content.body(), "hello");
273
274 let content = text_to_message("/hearts hello".into()).msgtype;
275 assert_eq!(content.msgtype(), "io.element.effect.hearts");
276 assert_eq!(content.body(), "hello");
277
278 let content = text_to_message("/rainfall hello".into()).msgtype;
279 assert_eq!(content.msgtype(), "io.element.effect.rainfall");
280 assert_eq!(content.body(), "hello");
281
282 let content = text_to_message("/snowfall hello".into()).msgtype;
283 assert_eq!(content.msgtype(), "io.element.effect.snowfall");
284 assert_eq!(content.body(), "hello");
285
286 let content = text_to_message("/spaceinvaders hello".into()).msgtype;
287 assert_eq!(content.msgtype(), "io.element.effects.space_invaders");
288 assert_eq!(content.body(), "hello");
289 }
290}
src/message/mod.rs +15 −95
@@ -10,7 +10,6 @@ use std::hash::{Hash, Hasher};
1010use std::ops::{Deref, DerefMut};
1111
1212use chrono::{DateTime, Local as LocalTz, NaiveDateTime, TimeZone};
13use comrak::{markdown_to_html, ComrakOptions};
1413use humansize::{format_size, DECIMAL};
1514use serde_json::json;
1615use unicode_width::UnicodeWidthStr;
@@ -33,7 +32,6 @@ use matrix_sdk::ruma::{
3332 Relation,
3433 RoomMessageEvent,
3534 RoomMessageEventContent,
36 TextMessageEventContent,
3735 },
3836 redaction::SyncRoomRedactionEvent,
3937 },
@@ -66,9 +64,12 @@ use crate::{
6664 util::{replace_emojis_in_str, space, space_span, take_width, wrapped_text},
6765};
6866
67mod compose;
6968mod html;
7069mod printer;
7170
71pub use self::compose::text_to_message;
72
7273pub type MessageKey = (MessageTimeStamp, OwnedEventId);
7374
7475#[derive(Default)]
@@ -129,22 +130,6 @@ const MIN_MSG_LEN: usize = 30;
129130const TIME_GUTTER_EMPTY: &str = " ";
130131const TIME_GUTTER_EMPTY_SPAN: Span<'static> = span_static(TIME_GUTTER_EMPTY);
131132
132fn text_to_message_content(input: String) -> TextMessageEventContent {
133 let mut options = ComrakOptions::default();
134 options.extension.autolink = true;
135 options.extension.shortcodes = true;
136 options.extension.strikethrough = true;
137 options.render.hardbreaks = true;
138 let html = markdown_to_html(input.as_str(), &options);
139
140 TextMessageEventContent::html(input, html)
141}
142
143pub fn text_to_message(input: String) -> RoomMessageEventContent {
144 let msg = MessageType::Text(text_to_message_content(input));
145 RoomMessageEventContent::new(msg)
146}
147
148133/// Before the image is loaded, already display a placeholder frame of the image size.
149134fn placeholder_frame(
150135 text: Option<&str>,
@@ -553,7 +538,18 @@ fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
553538 display_file_to_text!(Video, content);
554539 },
555540 _ => {
556 return Cow::Owned(format!("[Unknown message type: {:?}]", content.msgtype()));
541 match content.msgtype() {
542 // Just show the body text for the special Element messages.
543 "nic.custom.confetti" |
544 "nic.custom.fireworks" |
545 "io.element.effect.hearts" |
546 "io.element.effect.rainfall" |
547 "io.element.effect.snowfall" |
548 "io.element.effects.space_invaders" => content.body(),
549 other => {
550 return Cow::Owned(format!("[Unknown message type: {other:?}]"));
551 },
552 }
557553 },
558554 };
559555
@@ -1274,82 +1270,6 @@ pub mod tests {
12741270 assert_eq!(identity(&mc6), mc1);
12751271 }
12761272
1277 #[test]
1278 fn test_markdown_autolink() {
1279 let input = "http://example.com\n";
1280 let content = text_to_message_content(input.into());
1281 assert_eq!(content.body, input);
1282 assert_eq!(
1283 content.formatted.unwrap().body,
1284 "<p><a href=\"http://example.com\">http://example.com</a></p>\n"
1285 );
1286
1287 let input = "www.example.com\n";
1288 let content = text_to_message_content(input.into());
1289 assert_eq!(content.body, input);
1290 assert_eq!(
1291 content.formatted.unwrap().body,
1292 "<p><a href=\"http://www.example.com\">www.example.com</a></p>\n"
1293 );
1294
1295 let input = "See docs (they're at https://iamb.chat)\n";
1296 let content = text_to_message_content(input.into());
1297 assert_eq!(content.body, input);
1298 assert_eq!(
1299 content.formatted.unwrap().body,
1300 "<p>See docs (they're at <a href=\"https://iamb.chat\">https://iamb.chat</a>)</p>\n"
1301 );
1302 }
1303
1304 #[test]
1305 fn test_markdown_message() {
1306 let input = "**bold**\n";
1307 let content = text_to_message_content(input.into());
1308 assert_eq!(content.body, input);
1309 assert_eq!(content.formatted.unwrap().body, "<p><strong>bold</strong></p>\n");
1310
1311 let input = "*emphasis*\n";
1312 let content = text_to_message_content(input.into());
1313 assert_eq!(content.body, input);
1314 assert_eq!(content.formatted.unwrap().body, "<p><em>emphasis</em></p>\n");
1315
1316 let input = "`code`\n";
1317 let content = text_to_message_content(input.into());
1318 assert_eq!(content.body, input);
1319 assert_eq!(content.formatted.unwrap().body, "<p><code>code</code></p>\n");
1320
1321 let input = "```rust\nconst A: usize = 1;\n```\n";
1322 let content = text_to_message_content(input.into());
1323 assert_eq!(content.body, input);
1324 assert_eq!(
1325 content.formatted.unwrap().body,
1326 "<pre><code class=\"language-rust\">const A: usize = 1;\n</code></pre>\n"
1327 );
1328
1329 let input = ":heart:\n";
1330 let content = text_to_message_content(input.into());
1331 assert_eq!(content.body, input);
1332 assert_eq!(content.formatted.unwrap().body, "<p>\u{2764}\u{FE0F}</p>\n");
1333
1334 let input = "para 1\n\npara 2\n";
1335 let content = text_to_message_content(input.into());
1336 assert_eq!(content.body, input);
1337 assert_eq!(content.formatted.unwrap().body, "<p>para 1</p>\n<p>para 2</p>\n");
1338
1339 let input = "line 1\nline 2\n";
1340 let content = text_to_message_content(input.into());
1341 assert_eq!(content.body, input);
1342 assert_eq!(content.formatted.unwrap().body, "<p>line 1<br />\nline 2</p>\n");
1343
1344 let input = "# Heading\n## Subheading\n\ntext\n";
1345 let content = text_to_message_content(input.into());
1346 assert_eq!(content.body, input);
1347 assert_eq!(
1348 content.formatted.unwrap().body,
1349 "<h1>Heading</h1>\n<h2>Subheading</h2>\n<p>text</p>\n"
1350 );
1351 }
1352
13531273 #[test]
13541274 fn test_placeholder_frame() {
13551275 fn pretty_frame_test(str: &str) -> Option<String> {
src/notifications.rs +3 −1
@@ -228,7 +228,9 @@ pub fn event_notification_body(
228228 MessageType::VerificationRequest(_) => {
229229 format!("{sender_name} sent a verification request.")
230230 },
231 _ => unimplemented!(),
231 _ => {
232 format!("[Unknown message type: {:?}]", &message.msgtype)
233 },
232234 };
233235 Some(body)
234236 },
src/windows/room/mod.rs +3 −5
@@ -401,7 +401,7 @@ impl RoomState {
401401 },
402402 RoomField::CanonicalAlias => {
403403 let Some(alias_to_destroy) = room.canonical_alias() else {
404 let msg = format!("This room has no canonical alias to unset");
404 let msg = "This room has no canonical alias to unset";
405405
406406 return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
407407 };
@@ -500,11 +500,9 @@ impl RoomState {
500500 Some(can) => format!("Canonical alias: {can}"),
501501 }
502502 },
503 RoomField::Tag(_) => {
504 format!("Cannot currently show value for a tag")
505 },
503 RoomField::Tag(_) => "Cannot currently show value for a tag".into(),
506504 RoomField::Alias(_) => {
507 format!("Cannot show a single alias; use `:room aliases show` instead.")
505 "Cannot show a single alias; use `:room aliases show` instead.".into()
508506 },
509507 };
510508