src/commands/invite.rs
129 lines · 3791 bytes
1use clap::{App as Argparse, AppSettings as ArgParseSettings, Arg};
2use matrix_sdk::ruma::{OwnedUserId, UserId};
3use weechat::{
4 buffer::Buffer,
5 hooks::{Command, CommandCallback, CommandSettings},
6 Args, Prefix, Weechat,
7};
8
9use super::parse_and_run;
10use crate::Servers;
11
12pub struct InviteCommand {
13 servers: Servers,
14}
15
16impl InviteCommand {
17 pub fn create(servers: &Servers) -> Result<Command, ()> {
18 let settings = CommandSettings::new("invite")
19 .description("Invite a Matrix user to the current room.")
20 .add_argument("<user-id>")
21 .arguments_description(
22 "user-id: The Matrix user ID to invite to the current room.",
23 )
24 .add_completion("%(matrix-users)");
25
26 Command::new(
27 settings,
28 InviteCommand {
29 servers: servers.clone(),
30 },
31 )
32 }
33
34 fn print_error(buffer: &Buffer, message: &str) {
35 buffer.print(&format!("{}{}", Weechat::prefix(Prefix::Error), message));
36 }
37
38 fn invite(&self, buffer: &Buffer, input: &str) {
39 let Some(room) = self.servers.find_room(buffer) else {
40 Self::print_error(
41 buffer,
42 "The /invite command needs to be run in a Matrix room buffer.",
43 );
44 return;
45 };
46
47 let domain = room
48 .room_id()
49 .server_name()
50 .map(|server_name| server_name.as_str())
51 .unwrap_or_default();
52
53 let user_id = match normalize_invitee(input, domain) {
54 Ok(user_id) => user_id,
55 Err(error) => {
56 Self::print_error(buffer, &error);
57 return;
58 }
59 };
60
61 Weechat::spawn(async move { room.invite_user(user_id).await }).detach();
62 }
63}
64
65impl CommandCallback for InviteCommand {
66 fn callback(&mut self, _: &Weechat, buffer: &Buffer, arguments: Args) {
67 let parser = Argparse::new("invite")
68 .about("Invite a Matrix user to the current room.")
69 .settings(&[
70 ArgParseSettings::DisableHelpFlags,
71 ArgParseSettings::DisableVersion,
72 ])
73 .arg(Arg::with_name("user-id").required(true));
74
75 parse_and_run(parser, arguments, |matches| {
76 let user_id = matches
77 .value_of("user-id")
78 .expect("User ID not set but was required");
79
80 self.invite(buffer, user_id);
81 });
82 }
83}
84
85fn normalize_invitee(
86 input: &str,
87 default_domain: &str,
88) -> Result<OwnedUserId, String> {
89 let input = input.trim();
90 let candidate = if input.contains(':') {
91 input.to_owned()
92 } else {
93 let localpart = input.strip_prefix('@').unwrap_or(input);
94 format!("@{}:{}", localpart, default_domain)
95 };
96
97 UserId::parse(candidate.as_str()).map_err(|error| {
98 format!("Invalid Matrix user ID `{}`: {}", candidate, error)
99 })
100}
101
102#[cfg(test)]
103mod tests {
104 use super::normalize_invitee;
105
106 #[test]
107 fn keeps_fully_qualified_user_ids() {
108 let user = normalize_invitee("@strk:osgeo.org", "matrix.org").unwrap();
109 assert_eq!("@strk:osgeo.org", user.as_str());
110 }
111
112 #[test]
113 fn appends_room_domain_to_local_user_ids() {
114 let user = normalize_invitee("@strk", "matrix.org").unwrap();
115 assert_eq!("@strk:matrix.org", user.as_str());
116 }
117
118 #[test]
119 fn accepts_localparts_without_at_sign() {
120 let user = normalize_invitee("strk", "matrix.org").unwrap();
121 assert_eq!("@strk:matrix.org", user.as_str());
122 }
123
124 #[test]
125 fn reports_the_candidate_user_id_on_error() {
126 let error = normalize_invitee("@strk", "").unwrap_err();
127 assert!(error.contains("@strk:"));
128 }
129}