Commit 52838922ad
Unsigned
Layout: unified · split
Cargo.lock +1
| @@ -4698,6 +4698,7 @@ dependencies = [ | |||
| 4698 | name = "weechat-matrix" | 4698 | name = "weechat-matrix" |
| 4699 | version = "0.1.0" | 4699 | version = "0.1.0" |
| 4700 | dependencies = [ | 4700 | dependencies = [ |
| 4701 | "base64", | ||
| 4701 | "chrono", | 4702 | "chrono", |
| 4702 | "clap", | 4703 | "clap", |
| 4703 | "dashmap", | 4704 | "dashmap", |
Cargo.toml +1
| @@ -33,6 +33,7 @@ default = [] | |||
| 33 | 33 | ||
| 34 | [dependencies] | 34 | [dependencies] |
| 35 | clap = "2.34.0" | 35 | clap = "2.34.0" |
| 36 | base64 = "0.22" | ||
| 36 | chrono = "0.4.22" | 37 | chrono = "0.4.22" |
| 37 | dashmap = "6.1.0" | 38 | dashmap = "6.1.0" |
| 38 | url = "2.3.1" | 39 | url = "2.3.1" |
src/commands/mention_send.rs added +135
| @@ -0,0 +1,135 @@ | |||
| 1 | use std::{borrow::Cow, convert::TryFrom}; | ||
| 2 | |||
| 3 | use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; | ||
| 4 | use matrix_sdk::ruma::OwnedUserId; | ||
| 5 | use weechat::{ | ||
| 6 | buffer::Buffer, | ||
| 7 | hooks::{CommandRun, CommandRunCallback}, | ||
| 8 | Prefix, ReturnCode, Weechat, | ||
| 9 | }; | ||
| 10 | |||
| 11 | use crate::{Servers, PLUGIN_NAME}; | ||
| 12 | |||
| 13 | pub struct MentionSendCommand { | ||
| 14 | servers: Servers, | ||
| 15 | } | ||
| 16 | |||
| 17 | impl MentionSendCommand { | ||
| 18 | pub fn create(servers: &Servers) -> Result<CommandRun, ()> { | ||
| 19 | CommandRun::new( | ||
| 20 | "/matrix-send *", | ||
| 21 | MentionSendCommand { | ||
| 22 | servers: servers.clone(), | ||
| 23 | }, | ||
| 24 | ) | ||
| 25 | } | ||
| 26 | |||
| 27 | fn parse_payload( | ||
| 28 | encoded: &str, | ||
| 29 | ) -> Result<(String, Vec<OwnedUserId>), String> { | ||
| 30 | let bytes = URL_SAFE_NO_PAD | ||
| 31 | .decode(encoded) | ||
| 32 | .map_err(|_| "invalid encoded mention payload".to_owned())?; | ||
| 33 | let payload: serde_json::Value = serde_json::from_slice(&bytes) | ||
| 34 | .map_err(|_| "invalid mention payload".to_owned())?; | ||
| 35 | let body = payload | ||
| 36 | .get("body") | ||
| 37 | .and_then(|value| value.as_str()) | ||
| 38 | .filter(|body| !body.is_empty()) | ||
| 39 | .ok_or_else(|| "mention message body is empty".to_owned())? | ||
| 40 | .to_owned(); | ||
| 41 | let user_ids = payload | ||
| 42 | .get("user_ids") | ||
| 43 | .and_then(|value| value.as_array()) | ||
| 44 | .ok_or_else(|| "mention payload has no user IDs".to_owned())? | ||
| 45 | .iter() | ||
| 46 | .map(|value| { | ||
| 47 | value | ||
| 48 | .as_str() | ||
| 49 | .ok_or_else(|| "mention user ID is not a string".to_owned()) | ||
| 50 | .and_then(|value| { | ||
| 51 | OwnedUserId::try_from(value).map_err(|_| { | ||
| 52 | format!("invalid Matrix user ID: {}", value) | ||
| 53 | }) | ||
| 54 | }) | ||
| 55 | }) | ||
| 56 | .collect::<Result<Vec<_>, _>>()?; | ||
| 57 | |||
| 58 | if user_ids.is_empty() { | ||
| 59 | return Err("mention payload has no user IDs".to_owned()); | ||
| 60 | } | ||
| 61 | |||
| 62 | Ok((body, user_ids)) | ||
| 63 | } | ||
| 64 | |||
| 65 | fn print_error(buffer: &Buffer, message: &str) { | ||
| 66 | buffer.print(&format!( | ||
| 67 | "{}{}: {}", | ||
| 68 | Weechat::prefix(Prefix::Error), | ||
| 69 | PLUGIN_NAME, | ||
| 70 | message | ||
| 71 | )); | ||
| 72 | } | ||
| 73 | } | ||
| 74 | |||
| 75 | impl CommandRunCallback for MentionSendCommand { | ||
| 76 | fn callback( | ||
| 77 | &mut self, | ||
| 78 | _: &Weechat, | ||
| 79 | buffer: &Buffer, | ||
| 80 | command: Cow<str>, | ||
| 81 | ) -> ReturnCode { | ||
| 82 | let Some(room) = self.servers.find_room(buffer) else { | ||
| 83 | return ReturnCode::Ok; | ||
| 84 | }; | ||
| 85 | let Some(encoded) = command | ||
| 86 | .strip_prefix("/matrix-send ") | ||
| 87 | .map(str::trim) | ||
| 88 | .filter(|value| !value.is_empty()) | ||
| 89 | else { | ||
| 90 | Self::print_error(buffer, "missing mention payload"); | ||
| 91 | return ReturnCode::OkEat; | ||
| 92 | }; | ||
| 93 | let (body, user_ids) = match Self::parse_payload(encoded) { | ||
| 94 | Ok(payload) => payload, | ||
| 95 | Err(error) => { | ||
| 96 | Self::print_error(buffer, &error); | ||
| 97 | return ReturnCode::OkEat; | ||
| 98 | } | ||
| 99 | }; | ||
| 100 | let content = room.mention_message_content(buffer, body, user_ids); | ||
| 101 | |||
| 102 | Weechat::spawn(async move { room.send_message(content).await }) | ||
| 103 | .detach(); | ||
| 104 | |||
| 105 | ReturnCode::OkEat | ||
| 106 | } | ||
| 107 | } | ||
| 108 | |||
| 109 | #[cfg(test)] | ||
| 110 | mod tests { | ||
| 111 | use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; | ||
| 112 | use matrix_sdk::ruma::owned_user_id; | ||
| 113 | |||
| 114 | use super::MentionSendCommand; | ||
| 115 | |||
| 116 | #[test] | ||
| 117 | fn mention_payload_keeps_body_and_matrix_ids() { | ||
| 118 | let encoded = URL_SAFE_NO_PAD.encode( | ||
| 119 | br#"{"body":"hello @Ada","user_ids":["@ada:example.org"]}"#, | ||
| 120 | ); | ||
| 121 | let (body, user_ids) = | ||
| 122 | MentionSendCommand::parse_payload(&encoded).unwrap(); | ||
| 123 | |||
| 124 | assert_eq!(body, "hello @Ada"); | ||
| 125 | assert_eq!(user_ids, vec![owned_user_id!("@ada:example.org")]); | ||
| 126 | } | ||
| 127 | |||
| 128 | #[test] | ||
| 129 | fn mention_payload_rejects_non_matrix_ids() { | ||
| 130 | let encoded = | ||
| 131 | URL_SAFE_NO_PAD.encode(br#"{"body":"hello","user_ids":["Ada"]}"#); | ||
| 132 | |||
| 133 | assert!(MentionSendCommand::parse_payload(&encoded).is_err()); | ||
| 134 | } | ||
| 135 | } | ||
src/commands/mod.rs +4
| @@ -18,6 +18,7 @@ mod keys; | |||
| 18 | mod matrix; | 18 | mod matrix; |
| 19 | mod me; | 19 | mod me; |
| 20 | mod media; | 20 | mod media; |
| 21 | mod mention_send; | ||
| 21 | mod moderation; | 22 | mod moderation; |
| 22 | mod names; | 23 | mod names; |
| 23 | mod nick; | 24 | mod nick; |
| @@ -43,6 +44,7 @@ use keys::KeysCommand; | |||
| 43 | use matrix::MatrixCommand; | 44 | use matrix::MatrixCommand; |
| 44 | use me::MeCommand; | 45 | use me::MeCommand; |
| 45 | use media::MediaCommand; | 46 | use media::MediaCommand; |
| 47 | use mention_send::MentionSendCommand; | ||
| 46 | use moderation::ModerationCommand; | 48 | use moderation::ModerationCommand; |
| 47 | use names::NamesCommand; | 49 | use names::NamesCommand; |
| 48 | use nick::NickCommand; | 50 | use nick::NickCommand; |
| @@ -56,6 +58,7 @@ use verify::VerifyCommand; | |||
| 56 | 58 | ||
| 57 | pub struct Commands { | 59 | pub struct Commands { |
| 58 | _matrix: Command, | 60 | _matrix: Command, |
| 61 | _mention_send: CommandRun, | ||
| 59 | _keys: Command, | 62 | _keys: Command, |
| 60 | _devices: Command, | 63 | _devices: Command, |
| 61 | _invite: Command, | 64 | _invite: Command, |
| @@ -87,6 +90,7 @@ impl Commands { | |||
| 87 | ) -> Result<Commands, ()> { | 90 | ) -> Result<Commands, ()> { |
| 88 | Ok(Commands { | 91 | Ok(Commands { |
| 89 | _matrix: MatrixCommand::create(servers, config)?, | 92 | _matrix: MatrixCommand::create(servers, config)?, |
| 93 | _mention_send: MentionSendCommand::create(servers)?, | ||
| 90 | _devices: DevicesCommand::create(servers)?, | 94 | _devices: DevicesCommand::create(servers)?, |
| 91 | _invite: InviteCommand::create(servers)?, | 95 | _invite: InviteCommand::create(servers)?, |
| 92 | _ignore: IgnoreCommand::create()?, | 96 | _ignore: IgnoreCommand::create()?, |
src/room/members.rs +33
| @@ -99,6 +99,37 @@ impl Members { | |||
| 99 | self.nicks.insert(member.user_id().to_owned(), nick); | 99 | self.nicks.insert(member.user_id().to_owned(), nick); |
| 100 | } | 100 | } |
| 101 | 101 | ||
| 102 | pub(super) fn update_mentions_localvar(&self) { | ||
| 103 | let mut candidates: Vec<_> = self | ||
| 104 | .nicks | ||
| 105 | .iter() | ||
| 106 | .map(|entry| { | ||
| 107 | serde_json::json!({ | ||
| 108 | "display_name": entry.value(), | ||
| 109 | "user_id": entry.key().as_str(), | ||
| 110 | }) | ||
| 111 | }) | ||
| 112 | .collect(); | ||
| 113 | candidates.sort_by(|left, right| { | ||
| 114 | left["display_name"] | ||
| 115 | .as_str() | ||
| 116 | .unwrap_or_default() | ||
| 117 | .to_lowercase() | ||
| 118 | .cmp( | ||
| 119 | &right["display_name"] | ||
| 120 | .as_str() | ||
| 121 | .unwrap_or_default() | ||
| 122 | .to_lowercase(), | ||
| 123 | ) | ||
| 124 | }); | ||
| 125 | |||
| 126 | if let Ok(buffer) = self.buffer.buffer_handle().upgrade() { | ||
| 127 | if let Ok(json) = serde_json::to_string(&candidates) { | ||
| 128 | buffer.set_localvar("matrix_mentions", &json); | ||
| 129 | } | ||
| 130 | } | ||
| 131 | } | ||
| 132 | |||
| 102 | fn weechat_member(&self, member: RoomMember) -> WeechatRoomMember { | 133 | fn weechat_member(&self, member: RoomMember) -> WeechatRoomMember { |
| 103 | let user_id = member.user_id(); | 134 | let user_id = member.user_id(); |
| 104 | let sdk_room = active_room(&self.room); | 135 | let sdk_room = active_room(&self.room); |
| @@ -215,6 +246,7 @@ impl Members { | |||
| 215 | } | 246 | } |
| 216 | 247 | ||
| 217 | self.update_member(user_id).await; | 248 | self.update_member(user_id).await; |
| 249 | self.update_mentions_localvar(); | ||
| 218 | } | 250 | } |
| 219 | 251 | ||
| 220 | /// Remove a Weechat room member by user ID. | 252 | /// Remove a Weechat room member by user ID. |
| @@ -251,6 +283,7 @@ impl Members { | |||
| 251 | if let Some((_, nick)) = self.nicks.remove(user_id) { | 283 | if let Some((_, nick)) = self.nicks.remove(user_id) { |
| 252 | buffer.remove_nick(&nick); | 284 | buffer.remove_nick(&nick); |
| 253 | } | 285 | } |
| 286 | self.update_mentions_localvar(); | ||
| 254 | } | 287 | } |
| 255 | 288 | ||
| 256 | /// Retrieve a reference to a Weechat room member by user ID. | 289 | /// Retrieve a reference to a Weechat room member by user ID. |
src/room/mod.rs +50
| @@ -315,6 +315,16 @@ fn make_emote_message_content( | |||
| 315 | content | 315 | content |
| 316 | } | 316 | } |
| 317 | 317 | ||
| 318 | fn with_mentions( | ||
| 319 | mut content: RoomMessageEventContent, | ||
| 320 | mentioned_user_ids: Vec<OwnedUserId>, | ||
| 321 | ) -> RoomMessageEventContent { | ||
| 322 | content.mentions = Some(matrix_sdk::ruma::events::Mentions::with_user_ids( | ||
| 323 | mentioned_user_ids, | ||
| 324 | )); | ||
| 325 | content | ||
| 326 | } | ||
| 327 | |||
| 318 | fn thread_root_from_buffer(buffer: &Buffer) -> Option<OwnedEventId> { | 328 | fn thread_root_from_buffer(buffer: &Buffer) -> Option<OwnedEventId> { |
| 319 | buffer | 329 | buffer |
| 320 | .get_localvar("thread_root") | 330 | .get_localvar("thread_root") |
| @@ -529,6 +539,7 @@ impl RoomHandle { | |||
| 529 | trace!("Restoring member {}", &user_id); | 539 | trace!("Restoring member {}", &user_id); |
| 530 | room_buffer.members.restore_member(user_id).await; | 540 | room_buffer.members.restore_member(user_id).await; |
| 531 | } | 541 | } |
| 542 | room_buffer.members.update_mentions_localvar(); | ||
| 532 | 543 | ||
| 533 | room_buffer.buffer.update_buffer_name(); | 544 | room_buffer.buffer.update_buffer_name(); |
| 534 | room_buffer.buffer.set_topic(); | 545 | room_buffer.buffer.set_topic(); |
| @@ -560,6 +571,27 @@ impl BufferInputCallbackAsync for MatrixRoom { | |||
| 560 | } | 571 | } |
| 561 | 572 | ||
| 562 | impl MatrixRoom { | 573 | impl MatrixRoom { |
| 574 | pub(crate) fn mention_message_content( | ||
| 575 | &self, | ||
| 576 | buffer: &Buffer, | ||
| 577 | input: String, | ||
| 578 | mentioned_user_ids: Vec<OwnedUserId>, | ||
| 579 | ) -> RoomMessageEventContent { | ||
| 580 | let thread_root = thread_root_from_buffer(buffer); | ||
| 581 | let latest_thread_event = thread_root.as_ref().and_then(|root| { | ||
| 582 | self.latest_thread_event_ids.borrow().get(root).cloned() | ||
| 583 | }); | ||
| 584 | with_mentions( | ||
| 585 | make_text_message_content( | ||
| 586 | input, | ||
| 587 | self.config.borrow().input().markdown_input(), | ||
| 588 | thread_root, | ||
| 589 | latest_thread_event, | ||
| 590 | ), | ||
| 591 | mentioned_user_ids, | ||
| 592 | ) | ||
| 593 | } | ||
| 594 | |||
| 563 | pub fn owns_buffer(&self, buffer: &Buffer) -> bool { | 595 | pub fn owns_buffer(&self, buffer: &Buffer) -> bool { |
| 564 | self.buffer.owns_buffer(buffer) | 596 | self.buffer.owns_buffer(buffer) |
| 565 | } | 597 | } |
| @@ -1834,6 +1866,24 @@ mod tests { | |||
| 1834 | ); | 1866 | ); |
| 1835 | } | 1867 | } |
| 1836 | 1868 | ||
| 1869 | #[test] | ||
| 1870 | fn accepted_mentions_become_matrix_mentions() { | ||
| 1871 | let user_id = UserId::parse("@ada:example.org").unwrap(); | ||
| 1872 | let content = | ||
| 1873 | with_mentions(text_content("hello @Ada"), vec![user_id.clone()]); | ||
| 1874 | |||
| 1875 | let mentions = content.mentions.expect("m.mentions"); | ||
| 1876 | assert!(mentions.user_ids.contains(&user_id)); | ||
| 1877 | assert!(!mentions.room); | ||
| 1878 | |||
| 1879 | let json = serde_json::to_value(with_mentions( | ||
| 1880 | text_content("hello @Ada"), | ||
| 1881 | vec![user_id], | ||
| 1882 | )) | ||
| 1883 | .unwrap(); | ||
| 1884 | assert_eq!(json["m.mentions"]["user_ids"][0], "@ada:example.org"); | ||
| 1885 | } | ||
| 1886 | |||
| 1837 | #[test] | 1887 | #[test] |
| 1838 | fn restored_rooms_without_prev_batch_fetch_history_from_end() { | 1888 | fn restored_rooms_without_prev_batch_fetch_history_from_end() { |
| 1839 | assert_eq!(restored_prev_batch(None), Some(PrevBatch::Backwards(None))); | 1889 | assert_eq!(restored_prev_batch(None), Some(PrevBatch::Backwards(None))); |