src/commands/devices.rs
151 lines · 5192 bytes
9 symbols in this file
1use clap::{
2 App as Argparse, AppSettings as ArgParseSettings, Arg, ArgMatches,
3 SubCommand,
4};
5use matrix_sdk::ruma::{OwnedDeviceId, OwnedUserId, UserId};
6
7use weechat::{
8 buffer::Buffer,
9 hooks::{Command, CommandCallback, CommandSettings},
10 Args, Prefix, Weechat,
11};
12
13use crate::Servers;
14
15use super::parse_and_run;
16
17pub struct DevicesCommand {
18 servers: Servers,
19}
20
21impl DevicesCommand {
22 pub const DESCRIPTION: &'static str =
23 "List, delete or rename Matrix devices";
24
25 pub const SETTINGS: &'static [ArgParseSettings] = &[
26 ArgParseSettings::DisableHelpFlags,
27 ArgParseSettings::DisableVersion,
28 ArgParseSettings::VersionlessSubcommands,
29 ArgParseSettings::SubcommandRequiredElseHelp,
30 ];
31
32 pub fn create(servers: &Servers) -> Result<Command, ()> {
33 let settings = CommandSettings::new("devices")
34 .description(Self::DESCRIPTION)
35 .add_argument("list")
36 .add_argument("delete <device-id>")
37 .add_argument("set-name <device-id> <name>")
38 .arguments_description(
39 "device-id: The unique id of the device that should be deleted.
40 name: The name that the device name should be set to.",
41 )
42 .add_completion("list %(matrix-users)")
43 .add_completion("delete %(matrix-own-devices)")
44 .add_completion("set-name %(matrix-own-devices)")
45 .add_completion("help list|delete|set-name");
46
47 Command::new(
48 settings,
49 DevicesCommand {
50 servers: servers.clone(),
51 },
52 )
53 }
54
55 fn delete(servers: &Servers, buffer: &Buffer, devices: Vec<OwnedDeviceId>) {
56 let server = servers.find_server(buffer);
57
58 if let Some(s) = server {
59 let devices = || async move {
60 s.delete_devices(devices).await;
61 };
62 Weechat::spawn(devices()).detach();
63 } else {
64 Weechat::print("Must be executed on Matrix buffer")
65 }
66 }
67
68 fn list(servers: &Servers, buffer: &Buffer, user_id: Option<OwnedUserId>) {
69 let server = servers.find_server(buffer);
70
71 if let Some(s) = server {
72 let devices = || async move {
73 s.devices(user_id).await;
74 };
75 Weechat::spawn(devices()).detach();
76 } else {
77 Weechat::print("Must be executed on Matrix buffer")
78 }
79 }
80
81 pub fn run(buffer: &Buffer, servers: &Servers, args: &ArgMatches) {
82 match args.subcommand() {
83 ("list", args) => {
84 let user_id = args.and_then(|a| {
85 a.args.get("user-id").and_then(|a| {
86 a.vals.first().map(|u| {
87 UserId::parse(u.to_string_lossy().as_ref())
88 .expect("Argument wasn't a valid user id")
89 })
90 })
91 });
92
93 Self::list(servers, buffer, user_id);
94 }
95 ("delete", args) => {
96 let devices = args
97 .and_then(|a| a.args.get("device-id"))
98 .expect("Args didn't contain any device ids");
99 let devices: Vec<OwnedDeviceId> = devices
100 .vals
101 .iter()
102 .map(|d| d.clone().to_string_lossy().as_ref().into())
103 .collect();
104 Self::delete(servers, buffer, devices);
105 }
106 _ => Weechat::print(&format!(
107 "{}Subcommand isn't implemented",
108 Weechat::prefix(Prefix::Error)
109 )),
110 }
111 }
112
113 pub fn subcommands() -> Vec<Argparse<'static, 'static>> {
114 vec![
115 SubCommand::with_name("list")
116 .arg(Arg::with_name("user-id").required(false).validator(|u| {
117 UserId::parse(u)
118 .map_err(|_| {
119 "The given user isn't a valid user ID".to_owned()
120 })
121 .map(|_| ())
122 }))
123 .about("List your own Matrix devices on the server."),
124 SubCommand::with_name("delete")
125 .about("Delete the given device")
126 .arg(
127 Arg::with_name("device-id")
128 .require_delimiter(true)
129 .multiple(true)
130 .required(true),
131 ),
132 SubCommand::with_name("set-name")
133 .about("Set the human readable name of the given device")
134 .arg(Arg::with_name("device-id").required(true))
135 .arg(Arg::with_name("name").required(true)),
136 ]
137 }
138}
139
140impl CommandCallback for DevicesCommand {
141 fn callback(&mut self, _: &Weechat, buffer: &Buffer, arguments: Args) {
142 let argparse = Argparse::new("devices")
143 .about(Self::DESCRIPTION)
144 .settings(Self::SETTINGS)
145 .subcommands(Self::subcommands());
146
147 parse_and_run(argparse, arguments, |matches| {
148 Self::run(buffer, &self.servers, matches)
149 });
150 }
151}