src/commands/keys.rs

78f0d09198d6950e8d50205bd4ac92ab5a5a0bec
weechat-matrix-rs/src/commands/keys.rs history · blame · raw

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