Commit c2566233c3

c2566233c3a341105beaea422409ab13152a9b08

parent: 2ec691eff4

Unsigned

Darafei Praliaskouski <me@komzpa.net> · 2026-06-23 21:11 UTC
committer: <strk@kbt.io>

feat: add authenticated media download command

Layout: unified · split

README.md +2
@@ -157,3 +157,5 @@ The inactivity delay defaults to five minutes and can be changed with:
157 157
158Room buffers accept normal message input after `/matrix connect [server-name]` 158Room buffers accept normal message input after `/matrix connect [server-name]`
159has completed. 159has completed.
160
161`/matrix media download <mxc-uri> <file>` downloads Matrix media through the logged-in client, including homeservers that require authenticated media. It refuses to overwrite an existing file.
src/commands/matrix.rs +15 −2
@@ -12,7 +12,7 @@ use weechat::{
12 12
13use super::{parse_and_run, verification::VerificationCommand}; 13use super::{parse_and_run, verification::VerificationCommand};
14use crate::{ 14use crate::{
15 commands::{DevicesCommand, KeysCommand}, 15 commands::{DevicesCommand, KeysCommand, MediaCommand},
16 config::ConfigHandle, 16 config::ConfigHandle,
17 MatrixServer, Servers, PLUGIN_NAME, 17 MatrixServer, Servers, PLUGIN_NAME,
18}; 18};
@@ -34,6 +34,7 @@ impl MatrixCommand {
34 .add_argument("connect <server-name>") 34 .add_argument("connect <server-name>")
35 .add_argument("devices delete|list|set-name") 35 .add_argument("devices delete|list|set-name")
36 .add_argument("keys import|export <file> <passphrase>") 36 .add_argument("keys import|export <file> <passphrase>")
37 .add_argument("media download <mxc-uri> <file>")
37 .add_argument("disconnect <server-name>") 38 .add_argument("disconnect <server-name>")
38 .add_argument("reconnect <server-name>") 39 .add_argument("reconnect <server-name>")
39 .add_argument("help <matrix-command> [<matrix-subcommand>]") 40 .add_argument("help <matrix-command> [<matrix-subcommand>]")
@@ -44,16 +45,19 @@ impl MatrixCommand {
44 reconnect: Reconnect to server(s). 45 reconnect: Reconnect to server(s).
45 devices: {} 46 devices: {}
46 keys: {} 47 keys: {}
48 media: {}
47verification: {} 49verification: {}
48 help: Show detailed command help.\n 50 help: Show detailed command help.\n
49Use /matrix [command] help to find out more.\n", 51Use /matrix [command] help to find out more.\n",
50 DevicesCommand::DESCRIPTION, 52 DevicesCommand::DESCRIPTION,
51 KeysCommand::DESCRIPTION, 53 KeysCommand::DESCRIPTION,
54 MediaCommand::DESCRIPTION,
52 VerificationCommand::DESCRIPTION, 55 VerificationCommand::DESCRIPTION,
53 )) 56 ))
54 .add_completion("server add|delete|list|listfull") 57 .add_completion("server add|delete|list|listfull")
55 .add_completion("devices list|delete|set-name %(matrix-users)") 58 .add_completion("devices list|delete|set-name %(matrix-users)")
56 .add_completion(format!("keys {}", KeysCommand::COMPLETION)) 59 .add_completion(format!("keys {}", KeysCommand::COMPLETION))
60 .add_completion(format!("media {}", MediaCommand::COMPLETION))
57 .add_completion(format!( 61 .add_completion(format!(
58 "verification {}", 62 "verification {}",
59 VerificationCommand::COMPLETION 63 VerificationCommand::COMPLETION
@@ -62,7 +66,7 @@ Use /matrix [command] help to find out more.\n",
62 .add_completion("disconnect %(matrix_servers)") 66 .add_completion("disconnect %(matrix_servers)")
63 .add_completion("reconnect %(matrix_servers)") 67 .add_completion("reconnect %(matrix_servers)")
64 .add_completion( 68 .add_completion(
65 "help server|connect|disconnect|reconnect|keys|devices", 69 "help server|connect|disconnect|reconnect|keys|devices|media",
66 ); 70 );
67 71
68 Command::new( 72 Command::new(
@@ -230,6 +234,9 @@ Use /matrix [command] help to find out more.\n",
230 ("keys", Some(subargs)) => { 234 ("keys", Some(subargs)) => {
231 KeysCommand::run(buffer, &self.servers, subargs) 235 KeysCommand::run(buffer, &self.servers, subargs)
232 } 236 }
237 ("media", Some(subargs)) => {
238 MediaCommand::run(buffer, &self.servers, subargs)
239 }
233 ("verification", Some(subargs)) => { 240 ("verification", Some(subargs)) => {
234 VerificationCommand::run(buffer, &self.servers, subargs) 241 VerificationCommand::run(buffer, &self.servers, subargs)
235 } 242 }
@@ -300,6 +307,12 @@ impl CommandCallback for MatrixCommand {
300 .settings(KeysCommand::SETTINGS) 307 .settings(KeysCommand::SETTINGS)
301 .subcommands(KeysCommand::subcommands()), 308 .subcommands(KeysCommand::subcommands()),
302 ) 309 )
310 .subcommand(
311 SubCommand::with_name("media")
312 .about(MediaCommand::DESCRIPTION)
313 .settings(MediaCommand::SETTINGS)
314 .subcommands(MediaCommand::subcommands()),
315 )
303 .subcommand( 316 .subcommand(
304 SubCommand::with_name("verification") 317 SubCommand::with_name("verification")
305 .about(VerificationCommand::DESCRIPTION) 318 .about(VerificationCommand::DESCRIPTION)
src/commands/media.rs added +74
@@ -0,0 +1,74 @@
1use std::path::PathBuf;
2
3use clap::{
4 App as Argparse, AppSettings as ArgParseSettings, Arg, ArgMatches,
5 SubCommand,
6};
7use matrix_sdk::ruma::MxcUri;
8use weechat::{buffer::Buffer, Weechat};
9
10use crate::Servers;
11
12pub struct MediaCommand;
13
14impl MediaCommand {
15 pub const DESCRIPTION: &'static str = "Download Matrix media.";
16 pub const COMPLETION: &'static str = "download";
17
18 pub fn run(buffer: &Buffer, servers: &Servers, args: &ArgMatches) {
19 let server = match servers.find_server(buffer) {
20 Some(server) => server,
21 None => {
22 Weechat::print("Must be executed on Matrix buffer");
23 return;
24 }
25 };
26
27 match args.subcommand() {
28 ("download", Some(args)) => {
29 let uri = args
30 .value_of("mxc-uri")
31 .expect("MXC URI not set but was required");
32 let uri = Box::<MxcUri>::from(uri);
33
34 if !uri.is_valid() {
35 Weechat::print("Invalid MXC URI");
36 return;
37 }
38
39 let file = args
40 .value_of("file")
41 .expect("File not set but was required");
42 let file = PathBuf::from(Weechat::expand_home(file));
43
44 Weechat::spawn(async move {
45 server.download_media(uri.into(), file).await;
46 })
47 .detach();
48 }
49 _ => unreachable!(),
50 }
51 }
52
53 pub fn subcommands() -> Vec<Argparse<'static, 'static>> {
54 vec![SubCommand::with_name("download")
55 .about("Download the MXC URI through the logged-in Matrix client")
56 .arg(Arg::with_name("mxc-uri").required(true).validator(|uri| {
57 let uri = Box::<MxcUri>::from(uri.as_str());
58
59 if uri.is_valid() {
60 Ok(())
61 } else {
62 Err("The given URI is not a valid MXC URI".to_owned())
63 }
64 }))
65 .arg(Arg::with_name("file").required(true))]
66 }
67
68 pub const SETTINGS: &'static [ArgParseSettings] = &[
69 ArgParseSettings::DisableHelpFlags,
70 ArgParseSettings::DisableVersion,
71 ArgParseSettings::VersionlessSubcommands,
72 ArgParseSettings::SubcommandRequiredElseHelp,
73 ];
74}
src/commands/mod.rs +2
@@ -12,6 +12,7 @@ mod devices;
12mod keys; 12mod keys;
13mod matrix; 13mod matrix;
14mod me; 14mod me;
15mod media;
15mod page_up; 16mod page_up;
16mod verification; 17mod verification;
17 18
@@ -20,6 +21,7 @@ use devices::DevicesCommand;
20use keys::KeysCommand; 21use keys::KeysCommand;
21use matrix::MatrixCommand; 22use matrix::MatrixCommand;
22use me::MeCommand; 23use me::MeCommand;
24use media::MediaCommand;
23use page_up::PageUpCommand; 25use page_up::PageUpCommand;
24 26
25pub struct Commands { 27pub struct Commands {
src/server.rs +53 −3
@@ -59,6 +59,7 @@ use std::{
59 cell::{Ref, RefCell, RefMut}, 59 cell::{Ref, RefCell, RefMut},
60 cmp::Reverse, 60 cmp::Reverse,
61 collections::HashMap, 61 collections::HashMap,
62 io::Write,
62 path::PathBuf, 63 path::PathBuf,
63 rc::{Rc, Weak}, 64 rc::{Rc, Weak},
64}; 65};
@@ -69,15 +70,17 @@ use matrix_sdk::{
69 self, 70 self,
70 deserialized_responses::AmbiguityChange, 71 deserialized_responses::AmbiguityChange,
71 encryption::RoomKeyImportResult, 72 encryption::RoomKeyImportResult,
73 media::{MediaFormat, MediaRequestParameters},
72 room::Room, 74 room::Room,
73 ruma::{ 75 ruma::{
74 api::client::session::login::v3::Response as LoginResponse, 76 api::client::session::login::v3::Response as LoginResponse,
75 events::{ 77 events::{
76 room::member::RoomMemberEventContent, AnySyncStateEvent, 78 room::{member::RoomMemberEventContent, MediaSource},
77 AnySyncTimelineEvent, AnyToDeviceEvent, SyncStateEvent, 79 AnySyncStateEvent, AnySyncTimelineEvent, AnyToDeviceEvent,
80 SyncStateEvent,
78 }, 81 },
79 DeviceId, DeviceKeyAlgorithm, MilliSecondsSinceUnixEpoch, 82 DeviceId, DeviceKeyAlgorithm, MilliSecondsSinceUnixEpoch,
80 OwnedDeviceId, OwnedRoomId, OwnedUserId, RoomId, UserId, 83 OwnedDeviceId, OwnedMxcUri, OwnedRoomId, OwnedUserId, RoomId, UserId,
81 }, 84 },
82 Client, Error, 85 Client, Error,
83}; 86};
@@ -1017,6 +1020,53 @@ impl InnerServer {
1017 }; 1020 };
1018 } 1021 }
1019 1022
1023 pub async fn download_media(&self, uri: OwnedMxcUri, file: PathBuf) {
1024 let connection = if let Some(c) = self.connection() {
1025 c
1026 } else {
1027 self.print_error("You must be connected to execute this command");
1028 return;
1029 };
1030
1031 let client = connection.client().clone();
1032 let request = MediaRequestParameters {
1033 source: MediaSource::Plain(uri),
1034 format: MediaFormat::File,
1035 };
1036 let display_file = file.display().to_string();
1037
1038 self.print_network(&format!("Downloading media to {}", display_file));
1039
1040 match connection
1041 .spawn(async move {
1042 client.media().get_media_content(&request, true).await
1043 })
1044 .await
1045 {
1046 Ok(content) => {
1047 if let Err(e) = std::fs::OpenOptions::new()
1048 .write(true)
1049 .create_new(true)
1050 .open(&file)
1051 .and_then(|mut file| file.write_all(&content))
1052 {
1053 self.print_error(&format!(
1054 "Error writing media to {}: {:#?}",
1055 display_file, e
1056 ));
1057 } else {
1058 self.print_network(&format!(
1059 "Successfully downloaded media to {}",
1060 display_file
1061 ));
1062 }
1063 }
1064 Err(e) => {
1065 self.print_error(&format!("Error downloading media {:#?}", e));
1066 }
1067 }
1068 }
1069
1020 async fn list_own_devices( 1070 async fn list_own_devices(
1021 &self, 1071 &self,
1022 connection: Connection, 1072 connection: Connection,