Commit 3fa8fbdee5

3fa8fbdee503b70993ef6bc5e9010d530089ed71

parent: 6cdec76e2a

Unsigned

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

feat: improve media download UX

Layout: unified · split

src/commands/matrix.rs +1 −1
@@ -34,7 +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>")
37 .add_argument("media download <mxc-uri> [file]")
3838 .add_argument("disconnect <server-name>")
3939 .add_argument("reconnect <server-name>")
4040 .add_argument("help <matrix-command> [<matrix-subcommand>]")
src/commands/media.rs +37 −4
@@ -13,7 +13,7 @@ pub struct MediaCommand;
1313
1414impl MediaCommand {
1515 pub const DESCRIPTION: &'static str = "Download Matrix media.";
16 pub const COMPLETION: &'static str = "download";
16 pub const COMPLETION: &'static str = "download %(matrix-media)";
1717
1818 pub fn run(buffer: &Buffer, servers: &Servers, args: &ArgMatches) {
1919 let server = match servers.find_server(buffer) {
@@ -38,8 +38,17 @@ impl MediaCommand {
3838
3939 let file = args
4040 .value_of("file")
41 .expect("File not set but was required");
42 let file = PathBuf::from(Weechat::expand_home(file));
41 .map(|file| PathBuf::from(Weechat::expand_home(file)))
42 .or_else(|| default_download_file(&uri));
43 let file = match file {
44 Some(file) => file,
45 None => {
46 Weechat::print(
47 "Could not derive a filename from MXC URI",
48 );
49 return;
50 }
51 };
4352
4453 Weechat::spawn(async move {
4554 server.download_media(uri.into(), file).await;
@@ -62,7 +71,7 @@ impl MediaCommand {
6271 Err("The given URI is not a valid MXC URI".to_owned())
6372 }
6473 }))
65 .arg(Arg::with_name("file").required(true))]
74 .arg(Arg::with_name("file").required(false))]
6675 }
6776
6877 pub const SETTINGS: &'static [ArgParseSettings] = &[
@@ -72,3 +81,27 @@ impl MediaCommand {
7281 ArgParseSettings::SubcommandRequiredElseHelp,
7382 ];
7483}
84
85fn default_download_file(uri: &MxcUri) -> Option<PathBuf> {
86 uri.as_str()
87 .trim_end_matches('/')
88 .rsplit('/')
89 .next()
90 .filter(|name| !name.is_empty())
91 .map(PathBuf::from)
92}
93
94#[cfg(test)]
95mod tests {
96 use super::*;
97
98 #[test]
99 fn defaults_download_file_to_media_id() {
100 let uri = Box::<MxcUri>::from("mxc://matrix.org/some-media-id");
101
102 assert_eq!(
103 Some(PathBuf::from("some-media-id")),
104 default_download_file(&uri)
105 );
106 }
107}
src/completions.rs +99 −2
@@ -1,4 +1,6 @@
1use std::borrow::Cow;
1use std::{borrow::Cow, collections::BTreeSet};
2
3use matrix_sdk::ruma::MxcUri;
24
35use weechat::{
46 buffer::Buffer,
@@ -14,13 +16,15 @@ use crate::Servers;
1416pub struct Completions {
1517 servers: CompletionHook,
1618 users: CompletionHook,
19 media: CompletionHook,
1720}
1821
1922impl Completions {
2023 pub fn hook_all(servers: Servers) -> Result<Self, ()> {
2124 Ok(Self {
2225 servers: ServersCompletion::create(servers.clone())?,
23 users: UsersCompletion::create(servers)?,
26 users: UsersCompletion::create(servers.clone())?,
27 media: MediaCompletion::create(servers)?,
2428 })
2529 }
2630}
@@ -108,3 +112,96 @@ impl CompletionCallback for UsersCompletion {
108112 Ok(())
109113 }
110114}
115
116struct MediaCompletion {
117 servers: Servers,
118}
119
120impl MediaCompletion {
121 fn create(servers: Servers) -> Result<CompletionHook, ()> {
122 let comp = MediaCompletion { servers };
123
124 CompletionHook::new(
125 "matrix-media",
126 "Completion for Matrix media URIs in the current buffer",
127 comp,
128 )
129 }
130}
131
132impl CompletionCallback for MediaCompletion {
133 fn callback(
134 &mut self,
135 _: &Weechat,
136 buffer: &Buffer,
137 _: Cow<str>,
138 completion: &Completion,
139 ) -> Result<(), ()> {
140 if self.servers.find_server(buffer).is_none() {
141 return Ok(());
142 }
143
144 let mut media = BTreeSet::new();
145
146 for line in buffer.lines().rev().take(200) {
147 let message = Weechat::remove_color(&line.message());
148 media.extend(extract_mxc_uris(&message));
149 }
150
151 for uri in media {
152 completion.add_with_options(
153 &uri,
154 false,
155 CompletionPosition::Sorted,
156 );
157 }
158
159 Ok(())
160 }
161}
162
163fn extract_mxc_uris(message: &str) -> Vec<String> {
164 message
165 .match_indices("mxc://")
166 .filter_map(|(start, _)| {
167 let uri = message[start..]
168 .split(|c: char| {
169 c.is_whitespace()
170 || matches!(
171 c,
172 '<' | '>' | '[' | ']' | '(' | ')' | '"' | '\''
173 )
174 })
175 .next()
176 .unwrap_or_default();
177 let uri = Box::<MxcUri>::from(uri);
178
179 if uri.is_valid() {
180 Some(uri.as_str().to_owned())
181 } else {
182 None
183 }
184 })
185 .collect()
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191
192 #[test]
193 fn extracts_valid_mxc_uris() {
194 assert_eq!(
195 vec!["mxc://matrix.org/some-media-id".to_owned()],
196 extract_mxc_uris(
197 "authenticated download: /matrix media download \
198 mxc://matrix.org/some-media-id [file]"
199 )
200 );
201 }
202
203 #[test]
204 fn ignores_invalid_mxc_uris() {
205 assert!(extract_mxc_uris("download mxc://").is_empty());
206 }
207}
src/render.rs +7 −3
@@ -418,7 +418,7 @@ fn mxc_to_emxc(
418418fn media_download_command(source: &MediaSource) -> Option<String> {
419419 match source {
420420 MediaSource::Plain(url) => {
421 Some(format!("/matrix media download {} <file>", url.as_str()))
421 Some(format!("/matrix media download {} [file]", url.as_str()))
422422 }
423423 MediaSource::Encrypted(_) => None,
424424 }
@@ -456,7 +456,11 @@ impl<C: HasUrlOrFile> Render for C {
456456
457457 if let Some(command) = media_download_command(self.source()) {
458458 lines.push(RenderedLine {
459 message: format!("authenticated download: {}", command),
459 message: format!(
460 "{}authenticated download: {}",
461 Weechat::prefix(Prefix::Network),
462 command
463 ),
460464 tags: self.tags(),
461465 });
462466 }
@@ -1052,7 +1056,7 @@ mod tests {
10521056
10531057 assert_eq!(
10541058 Some(
1055 "/matrix media download mxc://matrix.org/some-media-id <file>"
1059 "/matrix media download mxc://matrix.org/some-media-id [file]"
10561060 .to_owned()
10571061 ),
10581062 media_download_command(&source)