src/commands/matrix.rs
616 lines · 22554 bytes
16 symbols in this file
1use clap::{
2 App as Argparse, AppSettings as ArgParseSettings, Arg, ArgMatches,
3 SubCommand,
4};
5use url::Url;
6
7use matrix_sdk::ruma::EventId;
8use weechat::{
9 buffer::Buffer,
10 hooks::{Command, CommandCallback, CommandSettings},
11 Args, Prefix, Weechat,
12};
13
14use super::{
15 join::{print_no_join_server_error, JoinCommand},
16 parse_and_run,
17 verification::VerificationCommand,
18};
19use crate::{
20 commands::{DevicesCommand, KeysCommand, MediaCommand, VerifyCommand},
21 config::ConfigHandle,
22 room::{HistoryPageResult, ThreadFilter},
23 MatrixServer, Servers, PLUGIN_NAME,
24};
25
26pub struct MatrixCommand {
27 servers: Servers,
28 config: ConfigHandle,
29}
30
31/// Validate the `<index>` argument of `/matrix threads open`.
32fn parse_thread_index(value: String) -> Result<(), String> {
33 match value.parse::<usize>() {
34 Ok(index) if index > 0 => Ok(()),
35 _ => Err("index must be a positive number".to_owned()),
36 }
37}
38
39impl MatrixCommand {
40 pub fn create(
41 servers: &Servers,
42 config: &ConfigHandle,
43 ) -> Result<Command, ()> {
44 let matrix_settings = CommandSettings::new("matrix")
45 .description("Matrix chat protocol command.")
46 .add_argument("server add <server-name> <hostname>[:<port>]")
47 .add_argument("server delete|list|listfull <server-name>")
48 .add_argument("connect <server-name>")
49 .add_argument("join <room-id-or-alias>")
50 .add_argument("devices delete|list|set-name")
51 .add_argument("keys import|export <file> <passphrase>")
52 .add_argument("media download <mxc-uri> [file]")
53 .add_argument("verify <contact> <device-id>")
54 .add_argument("verification info [contact]")
55 .add_argument("disconnect <server-name>")
56 .add_argument("reconnect <server-name>")
57 .add_argument("sso-complete <server-name> <login-token>")
58 .add_argument("history")
59 .add_argument("read")
60 .add_argument("thread <event-id>")
61 .add_argument("threads list [all|participated]|more|open <index>")
62 .add_argument("version")
63 .add_argument("help <matrix-command> [<matrix-subcommand>]")
64 .arguments_description(format!(
65 " server: List, add, or remove Matrix servers.
66 connect: Connect to Matrix servers.
67 disconnect: Disconnect from one or all Matrix servers.
68 reconnect: Reconnect to server(s).
69 join: Join a Matrix room by ID or alias.
70sso-complete: Finish SSO login with a copied loginToken.
71 history: Load an older page of messages in the current room.
72 read: Mark the current room as read.
73 thread: Open a thread buffer and load its complete history.
74 threads: List the threads of the current room.
75 version: Show version information about weechat-matrix.
76 devices: {}
77 keys: {}
78 media: {}
79 verify: {}
80verification: {}
81 help: Show detailed command help.\n
82Use /matrix [command] help to find out more.\n",
83 DevicesCommand::DESCRIPTION,
84 KeysCommand::DESCRIPTION,
85 MediaCommand::DESCRIPTION,
86 VerifyCommand::DESCRIPTION,
87 VerificationCommand::DESCRIPTION,
88 ))
89 .add_completion("server add|delete|list|listfull")
90 .add_completion("devices list|delete|set-name %(matrix-users)")
91 .add_completion(format!("keys {}", KeysCommand::COMPLETION))
92 .add_completion(format!("media {}", MediaCommand::COMPLETION))
93 .add_completion("verify %(matrix-users)")
94 .add_completion(format!(
95 "verification {}",
96 VerificationCommand::COMPLETION
97 ))
98 .add_completion("connect %(matrix_servers)")
99 .add_completion("disconnect %(matrix_servers)")
100 .add_completion("reconnect %(matrix_servers)")
101 .add_completion("sso-complete %(matrix_servers)")
102 .add_completion("thread")
103 .add_completion("threads list|more|open")
104 .add_completion(
105 "help server|connect|disconnect|reconnect|join|sso-complete|history|read|thread|threads|version|keys|devices|media|verify|verification",
106 );
107
108 Command::new(
109 matrix_settings,
110 MatrixCommand {
111 servers: servers.clone(),
112 config: config.clone(),
113 },
114 )
115 }
116
117 fn add_server(&self, args: &ArgMatches) {
118 let server_name = args
119 .value_of("name")
120 .expect("Server name not set but was required");
121 let homeserver = args
122 .value_of("homeserver")
123 .expect("Homeserver not set but was required");
124 let homeserver = Url::parse(homeserver)
125 .expect("Can't parse Homeserver even if validation passed");
126
127 let mut config_borrow = self.config.borrow_mut();
128 let mut section = config_borrow
129 .search_section_mut("server")
130 .expect("Can't get server section");
131
132 let server = MatrixServer::new(
133 server_name,
134 &self.config,
135 &mut section,
136 self.servers.clone(),
137 );
138
139 self.servers.insert(server);
140
141 let homeserver_option = section
142 .search_option(&format!("{}.homeserver", server_name))
143 .expect("Homeserver option wasn't created");
144 homeserver_option.set(homeserver.as_str(), true);
145
146 Weechat::print(&format!(
147 "{}: Server {}{}{} has been added.",
148 PLUGIN_NAME,
149 Weechat::color("chat_server"),
150 server_name,
151 Weechat::color("reset")
152 ));
153 }
154
155 fn delete_server(&self, args: &ArgMatches) {
156 let server_name = args
157 .value_of("name")
158 .expect("Server name not set but was required");
159
160 let connected = {
161 if let Some(s) = self.servers.get(server_name) {
162 s.connected()
163 } else {
164 Weechat::print(&format!(
165 "{}: No such server {}{}{} found.",
166 PLUGIN_NAME,
167 Weechat::color("chat_server"),
168 server_name,
169 Weechat::color("reset")
170 ));
171 return;
172 }
173 };
174
175 if connected {
176 Weechat::print(&format!(
177 "{}: Server {}{}{} is still connected.",
178 PLUGIN_NAME,
179 Weechat::color("chat_server"),
180 server_name,
181 Weechat::color("reset")
182 ));
183 return;
184 }
185
186 let server = self.servers.remove(server_name).unwrap();
187
188 drop(server);
189
190 Weechat::print(&format!(
191 "{}: Server {}{}{} has been deleted.",
192 PLUGIN_NAME,
193 Weechat::color("chat_server"),
194 server_name,
195 Weechat::color("reset")
196 ));
197 }
198
199 fn list_servers(&self, details: bool) {
200 if self.servers.borrow().is_empty() {
201 return;
202 }
203
204 Weechat::print("\nAll Matrix servers:");
205
206 // TODO print out some stats if the server is connected.
207 for server in self.servers.borrow().values() {
208 Weechat::print(&format!(" {}", server.get_info_str(details)));
209 }
210 }
211
212 fn server_command(&self, args: &ArgMatches) {
213 match args.subcommand() {
214 ("add", Some(subargs)) => self.add_server(subargs),
215 ("delete", Some(subargs)) => self.delete_server(subargs),
216 ("list", _) => self.list_servers(false),
217 ("listfull", _) => self.list_servers(true),
218 _ => self.list_servers(false),
219 }
220 }
221
222 fn server_not_found(&self, server_name: &str) {
223 Weechat::print(&format!(
224 "{}{}: Server \"{}{}{}\" not found.",
225 Weechat::prefix(Prefix::Error),
226 PLUGIN_NAME,
227 Weechat::color("chat_server"),
228 server_name,
229 Weechat::color("reset")
230 ));
231 }
232
233 fn connect_command(&self, args: &ArgMatches) {
234 let server_names = args
235 .values_of("name")
236 .expect("Server names not set but were required");
237
238 for server_name in server_names {
239 if let Some(s) = self.servers.get(server_name) {
240 match s.connect() {
241 Ok(_) => (),
242 Err(e) => Weechat::print(&format!("{:?}", e)),
243 }
244 } else {
245 self.server_not_found(server_name)
246 }
247 }
248 }
249
250 fn disconnect_command(&self, args: &ArgMatches) {
251 let server_name = args
252 .value_of("name")
253 .expect("Server name not set but was required");
254
255 if let Some(s) = self.servers.get(server_name) {
256 s.disconnect();
257 } else {
258 self.server_not_found(server_name)
259 }
260 }
261
262 fn sso_complete_command(&self, args: &ArgMatches) {
263 let server_name = args
264 .value_of("name")
265 .expect("Server name not set but was required");
266 let login_token = args
267 .value_of("login-token")
268 .expect("Login token not set but was required")
269 .to_owned();
270
271 if let Some(s) = self.servers.get(server_name) {
272 s.complete_sso_login(login_token);
273 } else {
274 self.server_not_found(server_name)
275 }
276 }
277
278 fn join_command(&self, buffer: &Buffer, args: &ArgMatches) {
279 let room_id_or_alias = args
280 .value_of("room")
281 .expect("Room not set but was required")
282 .to_owned();
283
284 if !JoinCommand::join_room(
285 &self.servers,
286 buffer,
287 room_id_or_alias,
288 true,
289 ) {
290 print_no_join_server_error();
291 }
292 }
293
294 fn thread_command(&self, buffer: &Buffer, args: &ArgMatches) {
295 let Some(room) = self.servers.find_room(buffer) else {
296 Weechat::print(&format!(
297 "{}{}: Run /matrix thread from a Matrix room buffer.",
298 Weechat::prefix(Prefix::Error),
299 PLUGIN_NAME,
300 ));
301 return;
302 };
303 let event_id = args
304 .value_of("event-id")
305 .expect("Event ID not set but was required");
306 let Ok(event_id) = EventId::parse(event_id) else {
307 Weechat::print(&format!(
308 "{}{}: Invalid Matrix event ID: {}",
309 Weechat::prefix(Prefix::Error),
310 PLUGIN_NAME,
311 event_id,
312 ));
313 return;
314 };
315
316 if let Some(handle) = room.open_thread_buffer(&event_id) {
317 if let Ok(thread_buffer) = handle.upgrade() {
318 thread_buffer.switch_to();
319 }
320 } else {
321 Weechat::print(&format!(
322 "{}{}: Event {} is not loaded in this room.",
323 Weechat::prefix(Prefix::Error),
324 PLUGIN_NAME,
325 event_id,
326 ));
327 }
328 }
329
330 fn threads_command(&self, buffer: &Buffer, args: &ArgMatches) {
331 let Some(room) = self.servers.find_room(buffer) else {
332 Weechat::print(&format!(
333 "{}{}: Run /matrix threads from a Matrix room buffer.",
334 Weechat::prefix(Prefix::Error),
335 PLUGIN_NAME,
336 ));
337 return;
338 };
339
340 match args.subcommand() {
341 ("list", subargs) => {
342 let filter = ThreadFilter::from_arg(
343 subargs.and_then(|args| args.value_of("include")),
344 );
345 Weechat::spawn(async move {
346 room.list_threads(filter).await
347 })
348 .detach();
349 }
350 ("more", _) => {
351 Weechat::spawn(async move { room.more_threads().await })
352 .detach();
353 }
354 ("open", subargs) => {
355 let index = subargs
356 .and_then(|args| args.value_of("index"))
357 .and_then(|index| index.parse::<usize>().ok())
358 .expect("Index was validated but isn't a number");
359
360 match room.open_listed_thread(index) {
361 Some(handle) => {
362 if let Ok(thread_buffer) = handle.upgrade() {
363 thread_buffer.switch_to();
364 }
365 }
366 None => Weechat::print(&format!(
367 "{}{}: Thread {} is not in the last listing.",
368 Weechat::prefix(Prefix::Error),
369 PLUGIN_NAME,
370 index,
371 )),
372 }
373 }
374 _ => (),
375 }
376 }
377
378 fn run(&self, buffer: &Buffer, args: &ArgMatches) {
379 match args.subcommand() {
380 ("connect", Some(subargs)) => self.connect_command(subargs),
381 ("disconnect", Some(subargs)) => self.disconnect_command(subargs),
382 ("sso-complete", Some(subargs)) => {
383 self.sso_complete_command(subargs)
384 }
385 ("join", Some(subargs)) => self.join_command(buffer, subargs),
386 ("server", Some(subargs)) => self.server_command(subargs),
387 ("devices", Some(subargs)) => {
388 DevicesCommand::run(buffer, &self.servers, subargs)
389 }
390 ("keys", Some(subargs)) => {
391 KeysCommand::run(buffer, &self.servers, subargs)
392 }
393 ("media", Some(subargs)) => {
394 MediaCommand::run(buffer, &self.servers, subargs)
395 }
396 ("verify", Some(subargs)) => {
397 VerifyCommand::run(buffer, &self.servers, subargs)
398 }
399 ("verification", Some(subargs)) => {
400 VerificationCommand::run(buffer, &self.servers, subargs)
401 }
402 ("read", _) => {
403 if let Some(room) = self.servers.find_room(buffer) {
404 room.mark_as_read();
405 }
406 }
407 ("history", _) => {
408 let Some(room) = self.servers.find_room(buffer) else {
409 Weechat::print(&format!(
410 "{}{}: /matrix history needs to be run in a Matrix room buffer.",
411 Weechat::prefix(Prefix::Error),
412 PLUGIN_NAME,
413 ));
414 return;
415 };
416
417 if !room.has_history_page() {
418 room.print_history_page_result(
419 HistoryPageResult::Unavailable,
420 );
421 return;
422 }
423
424 Weechat::spawn(async move {
425 let result = room.get_interactive_history_page().await;
426 room.print_history_page_result(result);
427 })
428 .detach();
429 }
430 ("thread", Some(subargs)) => self.thread_command(buffer, subargs),
431 ("threads", Some(subargs)) => {
432 self.threads_command(buffer, subargs)
433 }
434 ("version", _) => {
435 Weechat::print(&format!(
436 "{}: weechat-matrix version {} ({})",
437 PLUGIN_NAME,
438 env!("CARGO_PKG_VERSION"),
439 option_env!("GIT_DESCRIBE").unwrap_or("unknown"),
440 ));
441 }
442 _ => unreachable!(),
443 }
444 }
445}
446
447impl CommandCallback for MatrixCommand {
448 fn callback(
449 &mut self,
450 _weechat: &Weechat,
451 buffer: &Buffer,
452 arguments: Args,
453 ) {
454 let server_command = SubCommand::with_name("server")
455 .about("List, add or delete Matrix servers.")
456 .subcommand(
457 SubCommand::with_name("add")
458 .about("Add a new Matrix server.")
459 .arg(
460 Arg::with_name("name")
461 .value_name("server-name")
462 .required(true),
463 )
464 .arg(
465 Arg::with_name("homeserver")
466 .required(true)
467 .validator(MatrixServer::parse_url),
468 ),
469 )
470 .subcommand(
471 SubCommand::with_name("delete")
472 .about("Delete an existing Matrix server.")
473 .arg(
474 Arg::with_name("name")
475 .value_name("server-name")
476 .required(true),
477 ),
478 )
479 .subcommand(
480 SubCommand::with_name("list")
481 .about("List the configured Matrix servers."),
482 )
483 .subcommand(
484 SubCommand::with_name("listfull")
485 .about("List detailed information about the configured Matrix servers."),
486 );
487
488 let argparse = Argparse::new("matrix")
489 .about("Matrix chat protocol command.")
490 .global_settings(&[
491 ArgParseSettings::DisableHelpFlags,
492 ArgParseSettings::DisableVersion,
493 ArgParseSettings::VersionlessSubcommands,
494 ])
495 .setting(ArgParseSettings::SubcommandRequiredElseHelp)
496 .subcommand(server_command)
497 .subcommand(
498 SubCommand::with_name("devices")
499 .about(DevicesCommand::DESCRIPTION)
500 .settings(DevicesCommand::SETTINGS)
501 .subcommands(DevicesCommand::subcommands()),
502 )
503 .subcommand(
504 SubCommand::with_name("keys")
505 .about(KeysCommand::DESCRIPTION)
506 .settings(KeysCommand::SETTINGS)
507 .subcommands(KeysCommand::subcommands()),
508 )
509 .subcommand(
510 SubCommand::with_name("media")
511 .about(MediaCommand::DESCRIPTION)
512 .settings(MediaCommand::SETTINGS)
513 .subcommands(MediaCommand::subcommands()),
514 )
515 .subcommand(
516 SubCommand::with_name("verification")
517 .about(VerificationCommand::DESCRIPTION)
518 .settings(VerificationCommand::SETTINGS)
519 .subcommands(VerificationCommand::subcommands()),
520 )
521 .subcommand(VerifyCommand::parser())
522 .subcommand(
523 SubCommand::with_name("connect")
524 .about("Connect to Matrix servers.")
525 .arg(
526 Arg::with_name("name")
527 .value_name("server-name")
528 .required(true)
529 .multiple(true),
530 ),
531 )
532 .subcommand(
533 SubCommand::with_name("disconnect")
534 .about("Disconnect from one or all Matrix servers")
535 .arg(
536 Arg::with_name("name")
537 .value_name("server-name")
538 .required(true),
539 ),
540 )
541 .subcommand(
542 SubCommand::with_name("sso-complete")
543 .about("Finish SSO login with a copied loginToken")
544 .arg(
545 Arg::with_name("name")
546 .value_name("server-name")
547 .required(true),
548 )
549 .arg(
550 Arg::with_name("login-token")
551 .value_name("login-token")
552 .required(true),
553 ),
554 )
555 .subcommand(
556 SubCommand::with_name("join")
557 .about("Join a Matrix room by ID or alias")
558 .arg(
559 Arg::with_name("room")
560 .value_name("room-id-or-alias")
561 .required(true),
562 ),
563 )
564 .subcommand(
565 SubCommand::with_name("read")
566 .about("Mark the current room as read."),
567 )
568 .subcommand(
569 SubCommand::with_name("history").about(
570 "Load an older page of messages in the current room.",
571 ),
572 )
573 .subcommand(
574 SubCommand::with_name("thread")
575 .about("Open a thread buffer and load its history.")
576 .arg(
577 Arg::with_name("event-id")
578 .value_name("event-id")
579 .required(true),
580 ),
581 )
582 .subcommand(
583 SubCommand::with_name("threads")
584 .about("List the threads of the current room.")
585 .setting(ArgParseSettings::SubcommandRequiredElseHelp)
586 .subcommand(
587 SubCommand::with_name("list")
588 .about("List thread roots, newest activity first.")
589 .arg(
590 Arg::with_name("include")
591 .possible_values(&["all", "participated"])
592 .required(false),
593 ),
594 )
595 .subcommand(
596 SubCommand::with_name("more")
597 .about("Fetch the next page of the thread list."),
598 )
599 .subcommand(
600 SubCommand::with_name("open")
601 .about("Open a thread from the last listing.")
602 .arg(
603 Arg::with_name("index")
604 .required(true)
605 .validator(parse_thread_index),
606 ),
607 ),
608 )
609 .subcommand(
610 SubCommand::with_name("version")
611 .about("Show version information about weechat-matrix."),
612 );
613
614 parse_and_run(argparse, arguments, |args| self.run(buffer, args));
615 }
616}