src/commands/matrix.rs

8454dcd1674dfb48ab4ee615134e2d4d5fc04fa7
weechat-matrix-rs/src/commands/matrix.rs history · blame · raw

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