src/commands.rs

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

64 lines · 2008 bytes

 1use clap::App as Argparse;
 2use clap::AppSettings as ArgParseSettings;
 3use clap::SubCommand;
 4
 5use crate::{Servers, ServersHandle};
 6use weechat::Weechat;
 7use weechat::{ArgsWeechat, Buffer, CommandDescription, CommandHook};
 8
 9pub struct Commands {
10    _matrix: CommandHook<ServersHandle>,
11}
12
13impl Commands {
14    pub fn hook_all(weechat: &Weechat, servers: &Servers) -> Commands {
15        let matrix_desc = CommandDescription {
16            name: "matrix",
17            ..Default::default()
18        };
19
20        let matrix = weechat.hook_command(
21            matrix_desc,
22            Commands::matrix_command_cb,
23            Some(servers.clone_weak()),
24        );
25
26        Commands { _matrix: matrix }
27    }
28
29    fn matrix_command_cb(
30        servers: &ServersHandle,
31        buffer: Buffer,
32        args: ArgsWeechat,
33    ) {
34        let weechat = unsafe { Weechat::weechat() };
35        let argparse = Argparse::new("matrix")
36            .setting(ArgParseSettings::ColorNever)
37            .subcommand(SubCommand::with_name("connect"))
38            .subcommand(SubCommand::with_name("disconnect"));
39
40        let matches = match argparse.get_matches_from_safe(args) {
41            Ok(m) => m,
42            Err(e) => {
43                weechat
44                    .print(&format!("Error parsing command arguments {}", e));
45                return;
46            }
47        };
48        if let Some(matches) = matches.subcommand_matches("connect") {
49            let servers = servers.upgrade();
50            for server in servers.borrow().values() {
51                weechat.print(&format!("Connecting {}", server.name()));
52                server.connect();
53            }
54        } else if let Some(matches) = matches.subcommand_matches("disconnect") {
55            let servers = servers.upgrade();
56            weechat.print("Disconnecting");
57            for server in servers.borrow().values() {
58                server.disconnect();
59            }
60        } else {
61            weechat.print("Unknown subcommand");
62        }
63    }
64}