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