src/commands/matrix.rs

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

343 lines · 11981 bytes

  1use clap::{
  2    App as Argparse, AppSettings as ArgParseSettings, Arg, ArgMatches,
  3    SubCommand,
  4};
  5use url::Url;
  6
  7use weechat::{
  8    buffer::Buffer,
  9    hooks::{Command, CommandCallback, CommandSettings},
 10    Args, Prefix, Weechat,
 11};
 12
 13use super::{parse_and_run, verification::VerificationCommand};
 14use crate::{
 15    commands::{DevicesCommand, KeysCommand, MediaCommand},
 16    config::ConfigHandle,
 17    MatrixServer, Servers, PLUGIN_NAME,
 18};
 19
 20pub struct MatrixCommand {
 21    servers: Servers,
 22    config: ConfigHandle,
 23}
 24
 25impl MatrixCommand {
 26    pub fn create(
 27        servers: &Servers,
 28        config: &ConfigHandle,
 29    ) -> Result<Command, ()> {
 30        let matrix_settings = CommandSettings::new("matrix")
 31            .description("Matrix chat protocol command.")
 32            .add_argument("server add <server-name> <hostname>[:<port>]")
 33            .add_argument("server delete|list|listfull <server-name>")
 34            .add_argument("connect <server-name>")
 35            .add_argument("devices delete|list|set-name")
 36            .add_argument("keys import|export <file> <passphrase>")
 37            .add_argument("media download <mxc-uri> [file]")
 38            .add_argument("disconnect <server-name>")
 39            .add_argument("reconnect <server-name>")
 40            .add_argument("help <matrix-command> [<matrix-subcommand>]")
 41            .arguments_description(format!(
 42                "      server: List, add, or remove Matrix servers.
 43     connect: Connect to Matrix servers.
 44  disconnect: Disconnect from one or all Matrix servers.
 45   reconnect: Reconnect to server(s).
 46     devices: {}
 47        keys: {}
 48       media: {}
 49verification: {}
 50        help: Show detailed command help.\n
 51Use /matrix [command] help to find out more.\n",
 52                DevicesCommand::DESCRIPTION,
 53                KeysCommand::DESCRIPTION,
 54                MediaCommand::DESCRIPTION,
 55                VerificationCommand::DESCRIPTION,
 56            ))
 57            .add_completion("server add|delete|list|listfull")
 58            .add_completion("devices list|delete|set-name %(matrix-users)")
 59            .add_completion(format!("keys {}", KeysCommand::COMPLETION))
 60            .add_completion(format!("media {}", MediaCommand::COMPLETION))
 61            .add_completion(format!(
 62                "verification {}",
 63                VerificationCommand::COMPLETION
 64            ))
 65            .add_completion("connect %(matrix_servers)")
 66            .add_completion("disconnect %(matrix_servers)")
 67            .add_completion("reconnect %(matrix_servers)")
 68            .add_completion(
 69                "help server|connect|disconnect|reconnect|keys|devices|media",
 70            );
 71
 72        Command::new(
 73            matrix_settings,
 74            MatrixCommand {
 75                servers: servers.clone(),
 76                config: config.clone(),
 77            },
 78        )
 79    }
 80
 81    fn add_server(&self, args: &ArgMatches) {
 82        let server_name = args
 83            .value_of("name")
 84            .expect("Server name not set but was required");
 85        let homeserver = args
 86            .value_of("homeserver")
 87            .expect("Homeserver not set but was required");
 88        let homeserver = Url::parse(homeserver)
 89            .expect("Can't parse Homeserver even if validation passed");
 90
 91        let mut config_borrow = self.config.borrow_mut();
 92        let mut section = config_borrow
 93            .search_section_mut("server")
 94            .expect("Can't get server section");
 95
 96        let server = MatrixServer::new(
 97            server_name,
 98            &self.config,
 99            &mut section,
100            self.servers.clone(),
101        );
102
103        self.servers.insert(server);
104
105        let homeserver_option = section
106            .search_option(&format!("{}.homeserver", server_name))
107            .expect("Homeserver option wasn't created");
108        homeserver_option.set(homeserver.as_str(), true);
109
110        Weechat::print(&format!(
111            "{}: Server {}{}{} has been added.",
112            PLUGIN_NAME,
113            Weechat::color("chat_server"),
114            server_name,
115            Weechat::color("reset")
116        ));
117    }
118
119    fn delete_server(&self, args: &ArgMatches) {
120        let server_name = args
121            .value_of("name")
122            .expect("Server name not set but was required");
123
124        let connected = {
125            if let Some(s) = self.servers.get(server_name) {
126                s.connected()
127            } else {
128                Weechat::print(&format!(
129                    "{}: No such server {}{}{} found.",
130                    PLUGIN_NAME,
131                    Weechat::color("chat_server"),
132                    server_name,
133                    Weechat::color("reset")
134                ));
135                return;
136            }
137        };
138
139        if connected {
140            Weechat::print(&format!(
141                "{}: Server {}{}{} is still connected.",
142                PLUGIN_NAME,
143                Weechat::color("chat_server"),
144                server_name,
145                Weechat::color("reset")
146            ));
147            return;
148        }
149
150        let server = self.servers.remove(server_name).unwrap();
151
152        drop(server);
153
154        Weechat::print(&format!(
155            "{}: Server {}{}{} has been deleted.",
156            PLUGIN_NAME,
157            Weechat::color("chat_server"),
158            server_name,
159            Weechat::color("reset")
160        ));
161    }
162
163    fn list_servers(&self, details: bool) {
164        if self.servers.borrow().is_empty() {
165            return;
166        }
167
168        Weechat::print("\nAll Matrix servers:");
169
170        // TODO print out some stats if the server is connected.
171        for server in self.servers.borrow().values() {
172            Weechat::print(&format!("    {}", server.get_info_str(details)));
173        }
174    }
175
176    fn server_command(&self, args: &ArgMatches) {
177        match args.subcommand() {
178            ("add", Some(subargs)) => self.add_server(subargs),
179            ("delete", Some(subargs)) => self.delete_server(subargs),
180            ("list", _) => self.list_servers(false),
181            ("listfull", _) => self.list_servers(true),
182            _ => self.list_servers(false),
183        }
184    }
185
186    fn server_not_found(&self, server_name: &str) {
187        Weechat::print(&format!(
188            "{}{}: Server \"{}{}{}\" not found.",
189            Weechat::prefix(Prefix::Error),
190            PLUGIN_NAME,
191            Weechat::color("chat_server"),
192            server_name,
193            Weechat::color("reset")
194        ));
195    }
196
197    fn connect_command(&self, args: &ArgMatches) {
198        let server_names = args
199            .values_of("name")
200            .expect("Server names not set but were required");
201
202        for server_name in server_names {
203            if let Some(s) = self.servers.get(server_name) {
204                match s.connect() {
205                    Ok(_) => (),
206                    Err(e) => Weechat::print(&format!("{:?}", e)),
207                }
208            } else {
209                self.server_not_found(server_name)
210            }
211        }
212    }
213
214    fn disconnect_command(&self, args: &ArgMatches) {
215        let server_name = args
216            .value_of("name")
217            .expect("Server name not set but was required");
218
219        if let Some(s) = self.servers.get(server_name) {
220            s.disconnect();
221        } else {
222            self.server_not_found(server_name)
223        }
224    }
225
226    fn run(&self, buffer: &Buffer, args: &ArgMatches) {
227        match args.subcommand() {
228            ("connect", Some(subargs)) => self.connect_command(subargs),
229            ("disconnect", Some(subargs)) => self.disconnect_command(subargs),
230            ("server", Some(subargs)) => self.server_command(subargs),
231            ("devices", Some(subargs)) => {
232                DevicesCommand::run(buffer, &self.servers, subargs)
233            }
234            ("keys", Some(subargs)) => {
235                KeysCommand::run(buffer, &self.servers, subargs)
236            }
237            ("media", Some(subargs)) => {
238                MediaCommand::run(buffer, &self.servers, subargs)
239            }
240            ("verification", Some(subargs)) => {
241                VerificationCommand::run(buffer, &self.servers, subargs)
242            }
243            _ => unreachable!(),
244        }
245    }
246}
247
248impl CommandCallback for MatrixCommand {
249    fn callback(
250        &mut self,
251        _weechat: &Weechat,
252        buffer: &Buffer,
253        arguments: Args,
254    ) {
255        let server_command = SubCommand::with_name("server")
256            .about("List, add or delete Matrix servers.")
257            .subcommand(
258                SubCommand::with_name("add")
259                    .about("Add a new Matrix server.")
260                    .arg(
261                        Arg::with_name("name")
262                            .value_name("server-name")
263                            .required(true),
264                    )
265                    .arg(
266                        Arg::with_name("homeserver")
267                            .required(true)
268                            .validator(MatrixServer::parse_url),
269                    ),
270            )
271            .subcommand(
272                SubCommand::with_name("delete")
273                    .about("Delete an existing Matrix server.")
274                    .arg(
275                        Arg::with_name("name")
276                            .value_name("server-name")
277                            .required(true),
278                    ),
279            )
280            .subcommand(
281                SubCommand::with_name("list")
282                    .about("List the configured Matrix servers."),
283            )
284            .subcommand(
285                SubCommand::with_name("listfull")
286                    .about("List detailed information about the configured Matrix servers."),
287            );
288
289        let argparse = Argparse::new("matrix")
290            .about("Matrix chat protocol command.")
291            .global_settings(&[
292                ArgParseSettings::DisableHelpFlags,
293                ArgParseSettings::DisableVersion,
294                ArgParseSettings::VersionlessSubcommands,
295            ])
296            .setting(ArgParseSettings::SubcommandRequiredElseHelp)
297            .subcommand(server_command)
298            .subcommand(
299                SubCommand::with_name("devices")
300                    .about(DevicesCommand::DESCRIPTION)
301                    .settings(DevicesCommand::SETTINGS)
302                    .subcommands(DevicesCommand::subcommands()),
303            )
304            .subcommand(
305                SubCommand::with_name("keys")
306                    .about(KeysCommand::DESCRIPTION)
307                    .settings(KeysCommand::SETTINGS)
308                    .subcommands(KeysCommand::subcommands()),
309            )
310            .subcommand(
311                SubCommand::with_name("media")
312                    .about(MediaCommand::DESCRIPTION)
313                    .settings(MediaCommand::SETTINGS)
314                    .subcommands(MediaCommand::subcommands()),
315            )
316            .subcommand(
317                SubCommand::with_name("verification")
318                    .about(VerificationCommand::DESCRIPTION)
319                    .subcommands(VerificationCommand::subcommands()),
320            )
321            .subcommand(
322                SubCommand::with_name("connect")
323                    .about("Connect to Matrix servers.")
324                    .arg(
325                        Arg::with_name("name")
326                            .value_name("server-name")
327                            .required(true)
328                            .multiple(true),
329                    ),
330            )
331            .subcommand(
332                SubCommand::with_name("disconnect")
333                    .about("Disconnect from one or all Matrix servers")
334                    .arg(
335                        Arg::with_name("name")
336                            .value_name("server-name")
337                            .required(true),
338                    ),
339            );
340
341        parse_and_run(argparse, arguments, |args| self.run(buffer, args));
342    }
343}