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 {
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("media download <mxc-uri> [file]")
38 .add_argument("disconnect <server-name>") 38 .add_argument("disconnect <server-name>")
39 .add_argument("reconnect <server-name>") 39 .add_argument("reconnect <server-name>")
40 .add_argument("help <matrix-command> [<matrix-subcommand>]") 40 .add_argument("help <matrix-command> [<matrix-subcommand>]")
src/commands/media.rs +37 −4
@@ -13,7 +13,7 @@ pub struct MediaCommand;
13 13
14impl MediaCommand { 14impl MediaCommand {
15 pub const DESCRIPTION: &'static str = "Download Matrix media."; 15 pub const DESCRIPTION: &'static str = "Download Matrix media.";
16 pub const COMPLETION: &'static str = "download"; 16 pub const COMPLETION: &'static str = "download %(matrix-media)";
17 17
18 pub fn run(buffer: &Buffer, servers: &Servers, args: &ArgMatches) { 18 pub fn run(buffer: &Buffer, servers: &Servers, args: &ArgMatches) {
19 let server = match servers.find_server(buffer) { 19 let server = match servers.find_server(buffer) {
@@ -38,8 +38,17 @@ impl MediaCommand {
38 38
39 let file = args 39 let file = args
40 .value_of("file") 40 .value_of("file")
41 .expect("File not set but was required"); 41 .map(|file| PathBuf::from(Weechat::expand_home(file)))
42 let 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 };
43 52
44 Weechat::spawn(async move { 53 Weechat::spawn(async move {
45 server.download_media(uri.into(), file).await; 54 server.download_media(uri.into(), file).await;
@@ -62,7 +71,7 @@ impl MediaCommand {
62 Err("The given URI is not a valid MXC URI".to_owned()) 71 Err("The given URI is not a valid MXC URI".to_owned())
63 } 72 }
64 })) 73 }))
65 .arg(Arg::with_name("file").required(true))] 74 .arg(Arg::with_name("file").required(false))]
66 } 75 }
67 76
68 pub const SETTINGS: &'static [ArgParseSettings] = &[ 77 pub const SETTINGS: &'static [ArgParseSettings] = &[
@@ -72,3 +81,27 @@ impl MediaCommand {
72 ArgParseSettings::SubcommandRequiredElseHelp, 81 ArgParseSettings::SubcommandRequiredElseHelp,
73 ]; 82 ];
74} 83}
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;
2 4
3use weechat::{ 5use weechat::{
4 buffer::Buffer, 6 buffer::Buffer,
@@ -14,13 +16,15 @@ use crate::Servers;
14pub struct Completions { 16pub struct Completions {
15 servers: CompletionHook, 17 servers: CompletionHook,
16 users: CompletionHook, 18 users: CompletionHook,
19 media: CompletionHook,
17} 20}
18 21
19impl Completions { 22impl Completions {
20 pub fn hook_all(servers: Servers) -> Result<Self, ()> { 23 pub fn hook_all(servers: Servers) -> Result<Self, ()> {
21 Ok(Self { 24 Ok(Self {
22 servers: ServersCompletion::create(servers.clone())?, 25 servers: ServersCompletion::create(servers.clone())?,
23 users: UsersCompletion::create(servers)?, 26 users: UsersCompletion::create(servers.clone())?,
27 media: MediaCompletion::create(servers)?,
24 }) 28 })
25 } 29 }
26} 30}
@@ -108,3 +112,96 @@ impl CompletionCallback for UsersCompletion {
108 Ok(()) 112 Ok(())
109 } 113 }
110} 114}
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(
418fn media_download_command(source: &MediaSource) -> Option<String> { 418fn media_download_command(source: &MediaSource) -> Option<String> {
419 match source { 419 match source {
420 MediaSource::Plain(url) => { 420 MediaSource::Plain(url) => {
421 Some(format!("/matrix media download {} <file>", url.as_str())) 421 Some(format!("/matrix media download {} [file]", url.as_str()))
422 } 422 }
423 MediaSource::Encrypted(_) => None, 423 MediaSource::Encrypted(_) => None,
424 } 424 }
@@ -456,7 +456,11 @@ impl<C: HasUrlOrFile> Render for C {
456 456
457 if let Some(command) = media_download_command(self.source()) { 457 if let Some(command) = media_download_command(self.source()) {
458 lines.push(RenderedLine { 458 lines.push(RenderedLine {
459 message: format!("authenticated download: {}", command), 459 message: format!(
460 "{}authenticated download: {}",
461 Weechat::prefix(Prefix::Network),
462 command
463 ),
460 tags: self.tags(), 464 tags: self.tags(),
461 }); 465 });
462 } 466 }
@@ -1052,7 +1056,7 @@ mod tests {
1052 1056
1053 assert_eq!( 1057 assert_eq!(
1054 Some( 1058 Some(
1055 "/matrix media download mxc://matrix.org/some-media-id <file>" 1059 "/matrix media download mxc://matrix.org/some-media-id [file]"
1056 .to_owned() 1060 .to_owned()
1057 ), 1061 ),
1058 media_download_command(&source) 1062 media_download_command(&source)