src/commands/keys.rs

4fddc50d6d9f3d82220a4e3264d792d54fc940cf
weechat-matrix-rs/src/commands/keys.rs history · blame · raw

130 lines · 4389 bytes

  1use std::path::PathBuf;
  2
  3use clap::{
  4    App as Argparse, AppSettings as ArgParseSettings, Arg, ArgMatches,
  5    SubCommand,
  6};
  7
  8use weechat::{
  9    buffer::Buffer,
 10    hooks::{Command, CommandCallback, CommandSettings},
 11    Args, Weechat,
 12};
 13
 14use super::parse_and_run;
 15use crate::{MatrixServer, Servers};
 16
 17pub struct KeysCommand {
 18    servers: Servers,
 19}
 20
 21impl KeysCommand {
 22    pub const DESCRIPTION: &'static str = "Import or export E2EE keys.";
 23    pub const COMPLETION: &'static str = "import|export %(filename)";
 24    pub const SETTINGS: &'static [ArgParseSettings] = &[
 25        ArgParseSettings::DisableHelpFlags,
 26        ArgParseSettings::DisableVersion,
 27        ArgParseSettings::VersionlessSubcommands,
 28        ArgParseSettings::SubcommandRequiredElseHelp,
 29    ];
 30
 31    pub fn create(servers: &Servers) -> Result<Command, ()> {
 32        let settings = CommandSettings::new("keys")
 33            .description(Self::DESCRIPTION)
 34            .add_argument("import <file> <passphrase>")
 35            .add_argument("export <file> <passphrase>")
 36            .arguments_description(
 37                "file: Path to a file that is or will contain the E2EE keys export",
 38            )
 39            .add_completion(Self::COMPLETION)
 40            .add_completion("help import|export");
 41
 42        Command::new(
 43            settings,
 44            Self {
 45                servers: servers.clone(),
 46            },
 47        )
 48    }
 49
 50    fn upcast_args(args: &ArgMatches) -> (PathBuf, String) {
 51        let passphrase = args
 52            .args
 53            .get("passphrase")
 54            .and_then(|p| p.vals.first().map(|p| p.clone().into_string().ok()))
 55            .flatten()
 56            .expect("No passphrase found");
 57
 58        let file = args
 59            .args
 60            .get("file")
 61            .and_then(|f| f.vals.first())
 62            .expect("No file found");
 63        let file = Weechat::expand_home(&file.to_string_lossy());
 64        let file = PathBuf::from(file);
 65        (file, passphrase)
 66    }
 67
 68    fn import(server: MatrixServer, file: PathBuf, passphrase: String) {
 69        let import = || async move {
 70            server.import_keys(file, passphrase).await;
 71        };
 72        Weechat::spawn(import()).detach();
 73    }
 74
 75    fn export(server: MatrixServer, file: PathBuf, passphrase: String) {
 76        let export = || async move {
 77            server.export_keys(file, passphrase).await;
 78        };
 79        Weechat::spawn(export()).detach();
 80    }
 81
 82    pub fn run(buffer: &Buffer, servers: &Servers, args: &ArgMatches) {
 83        if let Some(server) = servers.find_server(buffer) {
 84            match args.subcommand() {
 85                ("import", args) => {
 86                    let (file, passphrase) = Self::upcast_args(
 87                        args.expect("No args were provided to the subcommand"),
 88                    );
 89                    Self::import(server, file, passphrase);
 90                }
 91                ("export", args) => {
 92                    let (file, passphrase) = Self::upcast_args(
 93                        args.expect("No args were provided to the subcommand"),
 94                    );
 95                    Self::export(server, file, passphrase);
 96                }
 97                _ => unreachable!(),
 98            }
 99        } else {
100            Weechat::print("Must be executed on Matrix buffer")
101        }
102    }
103
104    pub fn subcommands() -> Vec<Argparse<'static, 'static>> {
105        vec![
106            SubCommand::with_name("import")
107                .about("Import the E2EE keys from the given file.")
108                .arg(Arg::with_name("file").required(true))
109                .arg(Arg::with_name("passphrase").required(true)),
110            SubCommand::with_name("export")
111                // TODO add the ability to export keys only for a given room.
112                .about("Export your E2EE keys to the given file.")
113                .arg(Arg::with_name("file").required(true))
114                .arg(Arg::with_name("passphrase").required(true)),
115        ]
116    }
117}
118
119impl CommandCallback for KeysCommand {
120    fn callback(&mut self, _: &Weechat, buffer: &Buffer, arguments: Args) {
121        let argparse = Argparse::new("keys")
122            .about(Self::DESCRIPTION)
123            .settings(Self::SETTINGS)
124            .subcommands(Self::subcommands());
125
126        parse_and_run(argparse, arguments, |matches| {
127            Self::run(buffer, &self.servers, matches)
128        });
129    }
130}