src/commands/devices.rs
100 lines · 3305 bytes
1use clap::{App as Argparse, AppSettings as ArgParseSettings, Arg, SubCommand};
2
3use weechat::{
4 buffer::Buffer,
5 hooks::{Command, CommandCallback, CommandSettings},
6 Args, Weechat,
7};
8
9use crate::Servers;
10
11pub struct DevicesCommand {
12 servers: Servers,
13}
14
15impl DevicesCommand {
16 pub fn create(servers: &Servers) -> Result<Command, ()> {
17 let settings = CommandSettings::new("devices")
18 .description("List, delete or rename Matrix devices.")
19 .add_argument("list")
20 .add_argument("delete <device-id>")
21 .add_argument("set-name <device-id> <name>")
22 .arguments_description(
23 "device-id: The unique id of the device that should be deleted.
24 name:
25 ",
26 )
27 .add_completion("list")
28 .add_completion("delete %(matrix-own-devices)")
29 .add_completion("set-name %(matrix-own-devices)")
30 .add_completion("help list|delete|set-name");
31
32 Command::new(
33 settings,
34 DevicesCommand {
35 servers: servers.clone(),
36 },
37 )
38 }
39
40 fn list(&self, buffer: &Buffer) {
41 let server = self.servers.find_server(buffer);
42
43 if let Some(s) = server {
44 let devices = || async move {
45 s.devices().await;
46 };
47 Weechat::spawn(devices()).detach();
48 } else {
49 Weechat::print("Must be executed on Matrix buffer")
50 }
51 }
52}
53
54impl CommandCallback for DevicesCommand {
55 fn callback(&mut self, _: &Weechat, buffer: &Buffer, arguments: Args) {
56 let argparse = Argparse::new("devices")
57 .global_setting(ArgParseSettings::DisableHelpFlags)
58 .global_setting(ArgParseSettings::DisableVersion)
59 .global_setting(ArgParseSettings::VersionlessSubcommands)
60 .setting(ArgParseSettings::SubcommandRequiredElseHelp)
61 .subcommand(
62 SubCommand::with_name("list")
63 .about("List your own Matrix devices on the server."),
64 )
65 .subcommand(
66 SubCommand::with_name("delete")
67 .about("Delete the given device")
68 .arg(Arg::with_name("device-id").required(true)),
69 )
70 .subcommand(
71 SubCommand::with_name("set-name")
72 .about("Set the human readable name of the given device")
73 .arg(Arg::with_name("device-id").required(true))
74 .arg(Arg::with_name("name").required(true)),
75 );
76
77 let matches = match argparse.get_matches_from_safe(arguments) {
78 Ok(m) => m,
79 Err(e) => {
80 Weechat::print(
81 &Weechat::execute_modifier(
82 "color_decode_ansi",
83 "1",
84 &e.to_string(),
85 )
86 .unwrap(),
87 );
88 return;
89 }
90 };
91
92 match matches.subcommand() {
93 ("list", _) => self.list(buffer),
94 _ => Weechat::print(&format!(
95 "{}Subcommand isn't implemented",
96 Weechat::prefix("error")
97 )),
98 }
99 }
100}