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:
157157
158158Room buffers accept normal message input after `/matrix connect [server-name]`
159159has 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::{
1212
1313use super::{parse_and_run, verification::VerificationCommand};
1414use crate::{
15 commands::{DevicesCommand, KeysCommand},
15 commands::{DevicesCommand, KeysCommand, MediaCommand},
1616 config::ConfigHandle,
1717 MatrixServer, Servers, PLUGIN_NAME,
1818};
@@ -34,6 +34,7 @@ impl MatrixCommand {
3434 .add_argument("connect <server-name>")
3535 .add_argument("devices delete|list|set-name")
3636 .add_argument("keys import|export <file> <passphrase>")
37 .add_argument("media download <mxc-uri> <file>")
3738 .add_argument("disconnect <server-name>")
3839 .add_argument("reconnect <server-name>")
3940 .add_argument("help <matrix-command> [<matrix-subcommand>]")
@@ -44,16 +45,19 @@ impl MatrixCommand {
4445 reconnect: Reconnect to server(s).
4546 devices: {}
4647 keys: {}
48 media: {}
4749verification: {}
4850 help: Show detailed command help.\n
4951Use /matrix [command] help to find out more.\n",
5052 DevicesCommand::DESCRIPTION,
5153 KeysCommand::DESCRIPTION,
54 MediaCommand::DESCRIPTION,
5255 VerificationCommand::DESCRIPTION,
5356 ))
5457 .add_completion("server add|delete|list|listfull")
5558 .add_completion("devices list|delete|set-name %(matrix-users)")
5659 .add_completion(format!("keys {}", KeysCommand::COMPLETION))
60 .add_completion(format!("media {}", MediaCommand::COMPLETION))
5761 .add_completion(format!(
5862 "verification {}",
5963 VerificationCommand::COMPLETION
@@ -62,7 +66,7 @@ Use /matrix [command] help to find out more.\n",
6266 .add_completion("disconnect %(matrix_servers)")
6367 .add_completion("reconnect %(matrix_servers)")
6468 .add_completion(
65 "help server|connect|disconnect|reconnect|keys|devices",
69 "help server|connect|disconnect|reconnect|keys|devices|media",
6670 );
6771
6872 Command::new(
@@ -230,6 +234,9 @@ Use /matrix [command] help to find out more.\n",
230234 ("keys", Some(subargs)) => {
231235 KeysCommand::run(buffer, &self.servers, subargs)
232236 }
237 ("media", Some(subargs)) => {
238 MediaCommand::run(buffer, &self.servers, subargs)
239 }
233240 ("verification", Some(subargs)) => {
234241 VerificationCommand::run(buffer, &self.servers, subargs)
235242 }
@@ -300,6 +307,12 @@ impl CommandCallback for MatrixCommand {
300307 .settings(KeysCommand::SETTINGS)
301308 .subcommands(KeysCommand::subcommands()),
302309 )
310 .subcommand(
311 SubCommand::with_name("media")
312 .about(MediaCommand::DESCRIPTION)
313 .settings(MediaCommand::SETTINGS)
314 .subcommands(MediaCommand::subcommands()),
315 )
303316 .subcommand(
304317 SubCommand::with_name("verification")
305318 .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;
1212mod keys;
1313mod matrix;
1414mod me;
15mod media;
1516mod page_up;
1617mod verification;
1718
@@ -20,6 +21,7 @@ use devices::DevicesCommand;
2021use keys::KeysCommand;
2122use matrix::MatrixCommand;
2223use me::MeCommand;
24use media::MediaCommand;
2325use page_up::PageUpCommand;
2426
2527pub struct Commands {
src/server.rs +53 −3
@@ -59,6 +59,7 @@ use std::{
5959 cell::{Ref, RefCell, RefMut},
6060 cmp::Reverse,
6161 collections::HashMap,
62 io::Write,
6263 path::PathBuf,
6364 rc::{Rc, Weak},
6465};
@@ -69,15 +70,17 @@ use matrix_sdk::{
6970 self,
7071 deserialized_responses::AmbiguityChange,
7172 encryption::RoomKeyImportResult,
73 media::{MediaFormat, MediaRequestParameters},
7274 room::Room,
7375 ruma::{
7476 api::client::session::login::v3::Response as LoginResponse,
7577 events::{
76 room::member::RoomMemberEventContent, AnySyncStateEvent,
77 AnySyncTimelineEvent, AnyToDeviceEvent, SyncStateEvent,
78 room::{member::RoomMemberEventContent, MediaSource},
79 AnySyncStateEvent, AnySyncTimelineEvent, AnyToDeviceEvent,
80 SyncStateEvent,
7881 },
7982 DeviceId, DeviceKeyAlgorithm, MilliSecondsSinceUnixEpoch,
80 OwnedDeviceId, OwnedRoomId, OwnedUserId, RoomId, UserId,
83 OwnedDeviceId, OwnedMxcUri, OwnedRoomId, OwnedUserId, RoomId, UserId,
8184 },
8285 Client, Error,
8386};
@@ -1017,6 +1020,53 @@ impl InnerServer {
10171020 };
10181021 }
10191022
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
10201070 async fn list_own_devices(
10211071 &self,
10221072 connection: Connection,