src/commands/verification.rs

1aebd1afe96d6b9a2f26ca598c88d5aae0ba5008
weechat-matrix-rs/src/commands/verification.rs history · blame · raw

250 lines · 8672 bytes

18 symbols in this file
  1use clap::{
  2    App as Argparse, AppSettings as ArgParseSettings, Arg, ArgMatches,
  3    SubCommand,
  4};
  5use matrix_sdk::ruma::{OwnedUserId, UserId};
  6
  7use weechat::{
  8    buffer::Buffer,
  9    hooks::{Command, CommandCallback, CommandSettings},
 10    Args, Weechat,
 11};
 12
 13use super::parse_and_run;
 14use crate::{BufferOwner, Servers};
 15
 16pub struct VerificationCommand {
 17    servers: Servers,
 18}
 19
 20enum CommandType {
 21    Accept,
 22    Confirm,
 23    Cancel,
 24}
 25
 26impl VerificationCommand {
 27    pub const DESCRIPTION: &'static str =
 28        "Control interactive verification flows";
 29
 30    pub const COMPLETION: &'static str =
 31        "start %(matrix-users)|info %(matrix-users)|accept|confirm|cancel";
 32    pub const SETTINGS: &'static [ArgParseSettings] = &[
 33        ArgParseSettings::DisableHelpFlags,
 34        ArgParseSettings::DisableVersion,
 35        ArgParseSettings::VersionlessSubcommands,
 36        ArgParseSettings::SubcommandRequiredElseHelp,
 37    ];
 38
 39    pub fn create(servers: &Servers) -> Result<Command, ()> {
 40        let settings = CommandSettings::new("verification")
 41            .description(Self::DESCRIPTION)
 42            .add_argument("verification start <contact>")
 43            .add_argument("verification info [contact]")
 44            .add_argument("verification accept|confirm|cancel")
 45            .arguments_description(
 46                "  start: start an interactive verification with a contact
 47                  info: show verification state for one or all known contacts
 48                accept: accept the verification request
 49                confirm: confirm that the emojis match on both sides or \
 50                confirm that the other side has scanned our QR code
 51                cancel: cancel the verification flow or request",
 52            )
 53            .add_completion(Self::COMPLETION)
 54            .add_completion("help start|info|accept|confirm|cancel");
 55
 56        Command::new(
 57            settings,
 58            VerificationCommand {
 59                servers: servers.clone(),
 60            },
 61        )
 62    }
 63
 64    fn verification(servers: &Servers, buffer: &Buffer, command: CommandType) {
 65        let buffer_owner = servers.buffer_owner(buffer);
 66
 67        match buffer_owner {
 68            BufferOwner::Room(_, b) => match command {
 69                CommandType::Accept => b.accept_verification(),
 70                CommandType::Confirm => b.confirm_verification(),
 71                CommandType::Cancel => b.cancel_verification(),
 72            },
 73            BufferOwner::Verification(_, b) => match command {
 74                CommandType::Accept => b.accept(),
 75                CommandType::Confirm => b.confirm(),
 76                CommandType::Cancel => b.cancel(),
 77            },
 78            BufferOwner::Server(_) | BufferOwner::None => {
 79                Weechat::print(
 80                    "The verification command needs to be executed in a room or \
 81                    verification buffer",
 82                );
 83            }
 84        }
 85    }
 86
 87    fn start(servers: &Servers, buffer: &Buffer, user_id: OwnedUserId) {
 88        if let Some(server) = servers.find_server(buffer) {
 89            Weechat::spawn(async move {
 90                server.start_verification(user_id).await;
 91            })
 92            .detach();
 93        } else {
 94            Weechat::print("Must be executed on Matrix buffer")
 95        }
 96    }
 97
 98    fn info(servers: &Servers, buffer: &Buffer, user_id: Option<OwnedUserId>) {
 99        if let Some(server) = servers.find_server(buffer) {
100            Weechat::spawn(async move {
101                server.verification_info(user_id).await;
102            })
103            .detach();
104        } else {
105            Weechat::print("Must be executed on Matrix buffer")
106        }
107    }
108
109    pub fn run(buffer: &Buffer, servers: &Servers, args: &ArgMatches) {
110        match args.subcommand() {
111            ("start", Some(args)) => {
112                let user_id =
113                    UserId::parse(args.value_of("contact").expect(
114                        "Contact wasn't provided despite being required",
115                    ))
116                    .expect("Contact wasn't a valid Matrix user ID");
117                Self::start(servers, buffer, user_id);
118            }
119            ("info", Some(args)) => {
120                let user_id = args.value_of("contact").map(|contact| {
121                    UserId::parse(contact)
122                        .expect("Contact wasn't a valid Matrix user ID")
123                });
124                Self::info(servers, buffer, user_id);
125            }
126            ("accept", _) => {
127                Self::verification(servers, buffer, CommandType::Accept)
128            }
129            ("confirm", _) => {
130                Self::verification(servers, buffer, CommandType::Confirm)
131            }
132            ("cancel", _) => {
133                Self::verification(servers, buffer, CommandType::Cancel)
134            }
135            _ => unreachable!(),
136        }
137    }
138
139    pub fn subcommands() -> Vec<Argparse<'static, 'static>> {
140        vec![
141            SubCommand::with_name("start")
142                .about("Start an interactive verification with a contact")
143                .arg(Arg::with_name("contact").required(true).validator(
144                    |contact| {
145                        UserId::parse(contact).map(|_| ()).map_err(|_| {
146                            "The contact isn't a valid Matrix user ID"
147                                .to_owned()
148                        })
149                    },
150                )),
151            SubCommand::with_name("info")
152                .about("Show verification state for one or all known contacts")
153                .arg(Arg::with_name("contact").required(false).validator(
154                    |contact| {
155                        UserId::parse(contact).map(|_| ()).map_err(|_| {
156                            "The contact isn't a valid Matrix user ID"
157                                .to_owned()
158                        })
159                    },
160                )),
161            SubCommand::with_name("accept")
162                .about("Accept a verification request"),
163            SubCommand::with_name("confirm").about(
164                "Confirm that the emoji matches or that the other side has \
165                   scanned our QR code",
166            ),
167            SubCommand::with_name("cancel")
168                .about("Cancel the verification flow"),
169        ]
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    fn parser() -> Argparse<'static, 'static> {
178        Argparse::new("verification")
179            .settings(VerificationCommand::SETTINGS)
180            .subcommands(VerificationCommand::subcommands())
181    }
182
183    #[test]
184    fn parses_verification_start_contact() {
185        let matches = parser()
186            .get_matches_from_safe(vec![
187                "verification",
188                "start",
189                "@alice:example.org",
190            ])
191            .expect("valid verification start command");
192        let args = matches.subcommand_matches("start").expect("start args");
193
194        assert_eq!(args.value_of("contact"), Some("@alice:example.org"));
195    }
196
197    #[test]
198    fn rejects_invalid_verification_start_contact() {
199        assert!(parser()
200            .get_matches_from_safe(vec!["verification", "start", "alice"])
201            .is_err());
202    }
203
204    #[test]
205    fn parses_verification_info_with_optional_contact() {
206        let all = parser()
207            .get_matches_from_safe(vec!["verification", "info"])
208            .expect("valid verification info command");
209        assert_eq!(
210            all.subcommand_matches("info")
211                .expect("info args")
212                .value_of("contact"),
213            None
214        );
215
216        let one = parser()
217            .get_matches_from_safe(vec![
218                "verification",
219                "info",
220                "@alice:example.org",
221            ])
222            .expect("valid verification info contact");
223        assert_eq!(
224            one.subcommand_matches("info")
225                .expect("info args")
226                .value_of("contact"),
227            Some("@alice:example.org")
228        );
229    }
230
231    #[test]
232    fn rejects_invalid_verification_info_contact() {
233        assert!(parser()
234            .get_matches_from_safe(vec!["verification", "info", "alice"])
235            .is_err());
236    }
237}
238
239impl CommandCallback for VerificationCommand {
240    fn callback(&mut self, _: &Weechat, buffer: &Buffer, arguments: Args) {
241        let argparse = Argparse::new("verification")
242            .about(Self::DESCRIPTION)
243            .settings(Self::SETTINGS)
244            .subcommands(Self::subcommands());
245
246        parse_and_run(argparse, arguments, |matches| {
247            Self::run(buffer, &self.servers, &matches)
248        });
249    }
250}