src/commands/matrix.rs

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

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