Commit cc423cabd1

cc423cabd10e7b03b70c24e26f5b70be1f49711a

parent: bdc4031c08

Unsigned

Darafei Praliaskouski <me@komzpa.net> · 2026-07-31 15:16 UTC
committer: <strk@kbt.io>

feat: upload native Matrix attachments to threads

Layout: unified · split

Cargo.lock +2
@@ -4705,10 +4705,12 @@ dependencies = [
4705 "futures-util", 4705 "futures-util",
4706 "image", 4706 "image",
4707 "matrix-sdk", 4707 "matrix-sdk",
4708 "mime",
4708 "mime_guess", 4709 "mime_guess",
4709 "qrcode", 4710 "qrcode",
4710 "ruma-html", 4711 "ruma-html",
4711 "serde_json", 4712 "serde_json",
4713 "sha2",
4712 "strum", 4714 "strum",
4713 "tokio", 4715 "tokio",
4714 "tracing", 4716 "tracing",
Cargo.toml +3
@@ -50,7 +50,10 @@ ruma-html = { version = "0.5.0", features = ["matrix"] }
50# Auto-select version from matrix-sdk 50# Auto-select version from matrix-sdk
51qrcode = { version = "*", default-features = false } 51qrcode = { version = "*", default-features = false }
52image = { version = "*", default-features = false, features = ["jpeg"] } 52image = { version = "*", default-features = false, features = ["jpeg"] }
53base64 = "0.22"
54mime = "0.3"
53mime_guess = "2.0" 55mime_guess = "2.0"
56sha2 = "0.10"
54 57
55[dependencies.weechat] 58[dependencies.weechat]
56git = "https://github.com/poljar/rust-weechat" 59git = "https://github.com/poljar/rust-weechat"
src/commands/matrix_upload.rs added +605
@@ -0,0 +1,605 @@
1use std::{
2 cell::RefCell,
3 collections::BTreeMap,
4 rc::Rc,
5 time::{Duration, Instant},
6};
7
8use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
9use matrix_sdk::ruma::OwnedRoomId;
10use sha2::{Digest, Sha256};
11use weechat::{
12 buffer::Buffer,
13 hooks::{CommandRun, CommandRunCallback},
14 Prefix, ReturnCode, Weechat,
15};
16
17use crate::{
18 room::{thread_root_from_buffer, RoomHandle},
19 Servers,
20};
21
22const MAX_UPLOAD_BYTES: usize = 10 * 1024 * 1024;
23const MAX_ENCODED_CHUNK_BYTES: usize = 32 * 1024;
24const MAX_ACTIVE_UPLOADS: usize = 4;
25const UPLOAD_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
26const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
27
28struct MediaUpload {
29 filename: String,
30 mime: mime::Mime,
31 declared_size: usize,
32 expected_sha256: [u8; 32],
33 next_chunk: u32,
34 data: Vec<u8>,
35}
36
37impl MediaUpload {
38 fn begin(
39 encoded_filename: &str,
40 mime: &str,
41 declared_size: &str,
42 sha256: &str,
43 ) -> Result<Self, &'static str> {
44 let filename = decode_filename(encoded_filename)?;
45 if !valid_filename(&filename) {
46 return Err("filename must be a single non-empty file name");
47 }
48
49 if mime.len() > 127 || mime.chars().any(char::is_control) {
50 return Err("MIME type is invalid or too long");
51 }
52 let mime: mime::Mime =
53 mime.parse().map_err(|_| "MIME type is invalid")?;
54
55 let declared_size = declared_size
56 .parse::<usize>()
57 .map_err(|_| "declared size must be a decimal byte count")?;
58
59 if declared_size == 0 || declared_size > MAX_UPLOAD_BYTES {
60 return Err("declared size is outside the allowed range");
61 }
62
63 let expected_sha256 = parse_sha256(sha256)?;
64
65 Ok(Self {
66 filename,
67 mime,
68 declared_size,
69 expected_sha256,
70 next_chunk: 0,
71 data: Vec::with_capacity(declared_size),
72 })
73 }
74
75 fn append_chunk(
76 &mut self,
77 chunk_index: &str,
78 encoded: &str,
79 ) -> Result<(), &'static str> {
80 if encoded.len() > MAX_ENCODED_CHUNK_BYTES {
81 return Err("encoded chunk exceeds the allowed size");
82 }
83
84 let chunk_index = chunk_index
85 .parse::<u32>()
86 .map_err(|_| "chunk index must be an unsigned integer")?;
87
88 if chunk_index != self.next_chunk {
89 return Err("chunk index is out of order");
90 }
91
92 let chunk = URL_SAFE_NO_PAD
93 .decode(encoded)
94 .map_err(|_| "chunk is not valid base64")?;
95 let new_len = self
96 .data
97 .len()
98 .checked_add(chunk.len())
99 .ok_or("decoded bytes exceed the declared size")?;
100
101 if new_len > self.declared_size {
102 return Err("decoded bytes exceed the declared size");
103 }
104
105 self.data.extend_from_slice(&chunk);
106 self.next_chunk = self
107 .next_chunk
108 .checked_add(1)
109 .ok_or("too many upload chunks")?;
110 Ok(())
111 }
112
113 fn finish(self) -> Result<(String, mime::Mime, Vec<u8>), &'static str> {
114 if self.data.len() != self.declared_size {
115 return Err("decoded byte count does not match the declared size");
116 }
117
118 if self.mime == mime::IMAGE_PNG && !self.data.starts_with(PNG_SIGNATURE)
119 {
120 return Err("image/png payload does not have a PNG signature");
121 }
122
123 let actual_sha256: [u8; 32] = Sha256::digest(&self.data).into();
124 if actual_sha256 != self.expected_sha256 {
125 return Err("payload hash does not match the declared SHA-256");
126 }
127
128 Ok((self.filename, self.mime, self.data))
129 }
130}
131
132struct PendingMediaUpload {
133 room: RoomHandle,
134 room_id: OwnedRoomId,
135 thread_root: Option<matrix_sdk::ruma::OwnedEventId>,
136 upload: MediaUpload,
137 last_activity: Instant,
138}
139
140#[derive(Default)]
141struct UploadState {
142 pending: BTreeMap<String, PendingMediaUpload>,
143}
144
145impl UploadState {
146 fn prune_expired(&mut self, now: Instant) {
147 self.pending.retain(|_, pending| {
148 !upload_is_expired(pending.last_activity, now)
149 });
150 }
151}
152
153pub struct MatrixUploadCommand {
154 servers: Servers,
155 state: Rc<RefCell<UploadState>>,
156}
157
158impl MatrixUploadCommand {
159 pub fn create(servers: &Servers) -> Result<CommandRun, ()> {
160 CommandRun::new(
161 "/matrix-upload",
162 MatrixUploadCommand {
163 servers: servers.clone(),
164 state: Rc::new(RefCell::new(UploadState::default())),
165 },
166 )
167 }
168
169 fn report_error(buffer: &Buffer, error: &str) {
170 buffer.print(&format!(
171 "{}matrix-upload: {}",
172 Weechat::prefix(Prefix::Error),
173 error
174 ));
175 }
176
177 fn current_context(
178 &self,
179 buffer: &Buffer,
180 ) -> Result<
181 (RoomHandle, Option<matrix_sdk::ruma::OwnedEventId>),
182 &'static str,
183 > {
184 let room = self
185 .servers
186 .find_room(buffer)
187 .ok_or("command must be run in a Matrix room or thread buffer")?;
188 Ok((room, thread_root_from_buffer(buffer)))
189 }
190
191 fn matches_pending(
192 pending: &PendingMediaUpload,
193 room: &RoomHandle,
194 thread_root: &Option<matrix_sdk::ruma::OwnedEventId>,
195 ) -> bool {
196 pending.room_id == room.room_id()
197 && pending.thread_root.as_ref() == thread_root.as_ref()
198 }
199
200 fn begin(&self, buffer: &Buffer, args: &[&str]) {
201 if args.len() != 6 {
202 Self::report_error(buffer, "usage: /matrix-upload begin <id> <filename-base64url> <mime> <bytes> <sha256>");
203 return;
204 }
205
206 if !valid_transfer_id(args[1]) {
207 Self::report_error(
208 buffer,
209 "transfer id must be 1-64 URL-safe characters",
210 );
211 return;
212 }
213
214 let Ok((room, thread_root)) = self.current_context(buffer) else {
215 Self::report_error(
216 buffer,
217 "command must be run in a Matrix room or thread buffer",
218 );
219 return;
220 };
221
222 let upload =
223 match MediaUpload::begin(args[2], args[3], args[4], args[5]) {
224 Ok(upload) => upload,
225 Err(error) => {
226 Self::report_error(buffer, error);
227 return;
228 }
229 };
230
231 let mut state = self.state.borrow_mut();
232 state.prune_expired(Instant::now());
233 if state.pending.contains_key(args[1]) {
234 Self::report_error(buffer, "transfer id is already active");
235 return;
236 }
237 if state.pending.len() >= MAX_ACTIVE_UPLOADS {
238 Self::report_error(buffer, "too many active media uploads");
239 return;
240 }
241
242 state.pending.insert(
243 args[1].to_owned(),
244 PendingMediaUpload {
245 room_id: room.room_id().to_owned(),
246 room,
247 thread_root,
248 upload,
249 last_activity: Instant::now(),
250 },
251 );
252 }
253
254 fn chunk(&self, buffer: &Buffer, args: &[&str]) {
255 if args.len() != 4 {
256 Self::report_error(
257 buffer,
258 "usage: /matrix-upload chunk <id> <index> <base64url>",
259 );
260 return;
261 }
262 if !valid_transfer_id(args[1]) {
263 Self::report_error(
264 buffer,
265 "transfer id must be 1-64 URL-safe characters",
266 );
267 return;
268 }
269
270 let Ok((room, thread_root)) = self.current_context(buffer) else {
271 Self::report_error(buffer, "command must be run in the Matrix buffer that began the upload");
272 return;
273 };
274
275 let mut state = self.state.borrow_mut();
276 state.prune_expired(Instant::now());
277 let error = {
278 let Some(pending) = state.pending.get_mut(args[1]) else {
279 Self::report_error(buffer, "no active upload");
280 return;
281 };
282
283 if !Self::matches_pending(pending, &room, &thread_root) {
284 Self::report_error(
285 buffer,
286 "upload buffer or thread does not match transfer id",
287 );
288 return;
289 } else {
290 let result = pending.upload.append_chunk(args[2], args[3]);
291 if result.is_ok() {
292 pending.last_activity = Instant::now();
293 }
294 result.err()
295 }
296 };
297
298 if let Some(error) = error {
299 state.pending.remove(args[1]);
300 Self::report_error(buffer, error);
301 }
302 }
303
304 fn commit(&self, buffer: &Buffer, args: &[&str]) {
305 if args.len() != 2 {
306 Self::report_error(buffer, "usage: /matrix-upload commit <id>");
307 return;
308 }
309 if !valid_transfer_id(args[1]) {
310 Self::report_error(
311 buffer,
312 "transfer id must be 1-64 URL-safe characters",
313 );
314 return;
315 }
316
317 let Ok((room, thread_root)) = self.current_context(buffer) else {
318 Self::report_error(buffer, "command must be run in the Matrix buffer that began the upload");
319 return;
320 };
321
322 let pending = {
323 let mut state = self.state.borrow_mut();
324 state.prune_expired(Instant::now());
325 let Some(pending) = state.pending.get(args[1]) else {
326 Self::report_error(buffer, "no active upload");
327 return;
328 };
329 if !Self::matches_pending(pending, &room, &thread_root) {
330 Self::report_error(
331 buffer,
332 "upload buffer or thread does not match transfer id",
333 );
334 return;
335 }
336 state.pending.remove(args[1])
337 };
338 let Some(pending) = pending else {
339 Self::report_error(buffer, "no active upload");
340 return;
341 };
342
343 let (filename, mime, data) = match pending.upload.finish() {
344 Ok(upload) => upload,
345 Err(error) => {
346 Self::report_error(buffer, error);
347 return;
348 }
349 };
350
351 let room = pending.room;
352 let thread_root = pending.thread_root;
353 Weechat::spawn(async move {
354 room.send_attachment_bytes(filename, mime, data, thread_root)
355 .await
356 })
357 .detach();
358 }
359
360 fn cancel(&self, buffer: &Buffer, args: &[&str]) {
361 if args.len() != 2 {
362 Self::report_error(buffer, "usage: /matrix-upload cancel <id>");
363 return;
364 }
365 if !valid_transfer_id(args[1]) {
366 Self::report_error(
367 buffer,
368 "transfer id must be 1-64 URL-safe characters",
369 );
370 return;
371 }
372
373 let Ok((room, thread_root)) = self.current_context(buffer) else {
374 Self::report_error(buffer, "command must be run in the Matrix buffer that began the upload");
375 return;
376 };
377
378 let mut state = self.state.borrow_mut();
379 state.prune_expired(Instant::now());
380 let Some(pending) = state.pending.get(args[1]) else {
381 Self::report_error(buffer, "no active upload");
382 return;
383 };
384 if !Self::matches_pending(pending, &room, &thread_root) {
385 Self::report_error(
386 buffer,
387 "upload buffer or thread does not match transfer id",
388 );
389 return;
390 }
391
392 state.pending.remove(args[1]);
393 }
394}
395
396impl CommandRunCallback for MatrixUploadCommand {
397 fn callback(
398 &mut self,
399 _: &Weechat,
400 buffer: &Buffer,
401 cmd: std::borrow::Cow<str>,
402 ) -> ReturnCode {
403 let Some(arguments) = cmd.strip_prefix("/matrix-upload") else {
404 return ReturnCode::Ok;
405 };
406 let args = arguments.split_whitespace().collect::<Vec<_>>();
407
408 match args.first().copied() {
409 Some("begin") => self.begin(buffer, &args),
410 Some("chunk") => self.chunk(buffer, &args),
411 Some("commit") => self.commit(buffer, &args),
412 Some("cancel") => self.cancel(buffer, &args),
413 _ => Self::report_error(
414 buffer,
415 "usage: /matrix-upload <begin|chunk|commit|cancel>",
416 ),
417 }
418
419 ReturnCode::Ok
420 }
421}
422
423fn valid_filename(filename: &str) -> bool {
424 !filename.is_empty()
425 && filename.len() <= 255
426 && !filename.contains(['/', '\\', '\0'])
427 && !filename.chars().any(char::is_control)
428}
429
430fn decode_filename(encoded: &str) -> Result<String, &'static str> {
431 let bytes = URL_SAFE_NO_PAD
432 .decode(encoded)
433 .map_err(|_| "filename must be URL-safe base64 without padding")?;
434 String::from_utf8(bytes).map_err(|_| "filename must be valid UTF-8")
435}
436
437fn valid_transfer_id(id: &str) -> bool {
438 !id.is_empty()
439 && id.len() <= 64
440 && id.bytes().all(|byte| {
441 byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-'
442 })
443}
444
445fn upload_is_expired(last_activity: Instant, now: Instant) -> bool {
446 now.saturating_duration_since(last_activity) >= UPLOAD_IDLE_TIMEOUT
447}
448
449fn parse_sha256(value: &str) -> Result<[u8; 32], &'static str> {
450 if value.len() != 64 || !value.bytes().all(|byte| byte.is_ascii_hexdigit())
451 {
452 return Err("SHA-256 must be 64 hexadecimal characters");
453 }
454
455 let mut hash = [0_u8; 32];
456 for (index, byte) in hash.iter_mut().enumerate() {
457 *byte = u8::from_str_radix(&value[index * 2..index * 2 + 2], 16)
458 .map_err(|_| "SHA-256 must be hexadecimal")?;
459 }
460 Ok(hash)
461}
462
463#[cfg(test)]
464mod tests {
465 use super::*;
466
467 fn png(bytes: &[u8]) -> Vec<u8> {
468 [PNG_SIGNATURE, bytes].concat()
469 }
470
471 fn sha256(bytes: &[u8]) -> String {
472 format!("{:x}", Sha256::digest(bytes))
473 }
474
475 fn upload_for(bytes: &[u8], filename: &str, mime: &str) -> MediaUpload {
476 MediaUpload::begin(
477 &URL_SAFE_NO_PAD.encode(filename),
478 mime,
479 &bytes.len().to_string(),
480 &sha256(bytes),
481 )
482 .unwrap()
483 }
484
485 #[test]
486 fn rejects_out_of_bounds_begin_metadata() {
487 assert!(MediaUpload::begin(
488 &URL_SAFE_NO_PAD.encode("image.png"),
489 "image/png",
490 &(MAX_UPLOAD_BYTES + 1).to_string(),
491 &"0".repeat(64),
492 )
493 .is_err());
494 assert!(MediaUpload::begin(
495 &URL_SAFE_NO_PAD.encode("../image.png"),
496 "image/png",
497 "1",
498 &"0".repeat(64),
499 )
500 .is_err());
501 assert!(MediaUpload::begin(
502 &URL_SAFE_NO_PAD.encode("payload.bin"),
503 "not a mime",
504 "1",
505 &"0".repeat(64),
506 )
507 .is_err());
508 }
509
510 #[test]
511 fn rejects_malformed_or_out_of_order_chunks() {
512 let bytes = png(b"payload");
513 let mut upload = upload_for(&bytes, "image.png", "image/png");
514 assert!(upload.append_chunk("1", "AA==").is_err());
515 assert!(upload.append_chunk("0", "not-base64").is_err());
516 assert!(upload
517 .append_chunk("0", &"A".repeat(MAX_ENCODED_CHUNK_BYTES + 1))
518 .is_err());
519 }
520
521 #[test]
522 fn preserves_exact_bytes_across_chunks() {
523 let bytes = png(b"split pixels");
524 let mut upload = upload_for(&bytes, "image.png", "image/png");
525 let split = 10;
526 upload
527 .append_chunk("0", &URL_SAFE_NO_PAD.encode(&bytes[..split]))
528 .unwrap();
529 upload
530 .append_chunk("1", &URL_SAFE_NO_PAD.encode(&bytes[split..]))
531 .unwrap();
532 let (_, content_type, actual) = upload.finish().unwrap();
533 assert_eq!(content_type, mime::IMAGE_PNG);
534 assert_eq!(actual, bytes);
535 }
536
537 #[test]
538 fn rejects_hash_mismatch_and_wrong_png_signature() {
539 let bytes = png(b"payload");
540 let mut upload = MediaUpload::begin(
541 &URL_SAFE_NO_PAD.encode("image.png"),
542 "image/png",
543 &bytes.len().to_string(),
544 &"0".repeat(64),
545 )
546 .unwrap();
547 upload
548 .append_chunk("0", &URL_SAFE_NO_PAD.encode(&bytes))
549 .unwrap();
550 assert!(upload.finish().is_err());
551
552 let bytes = b"not a png";
553 let mut upload = upload_for(bytes, "image.png", "image/png");
554 upload
555 .append_chunk("0", &URL_SAFE_NO_PAD.encode(bytes))
556 .unwrap();
557 assert!(upload.finish().is_err());
558 }
559
560 #[test]
561 fn accepts_pdf_and_octet_stream_without_png_validation() {
562 for (filename, mime, bytes) in [
563 ("report.pdf", "application/pdf", b"%PDF-1.7\n".as_slice()),
564 (
565 "archive.bin",
566 "application/octet-stream",
567 b"\x00\x01\x02".as_slice(),
568 ),
569 ] {
570 let mut upload = upload_for(bytes, filename, mime);
571 upload
572 .append_chunk("0", &URL_SAFE_NO_PAD.encode(bytes))
573 .unwrap();
574 let (actual_filename, actual_mime, actual_bytes) =
575 upload.finish().unwrap();
576 assert_eq!(actual_filename, filename);
577 assert_eq!(actual_mime.as_ref(), mime);
578 assert_eq!(actual_bytes, bytes);
579 }
580 }
581
582 #[test]
583 fn accepts_only_url_safe_ids_and_filenames() {
584 assert!(valid_transfer_id("upload-01_A"));
585 assert!(!valid_transfer_id(""));
586 assert!(!valid_transfer_id("contains space"));
587 assert!(!valid_transfer_id(&"a".repeat(65)));
588 assert_eq!(
589 decode_filename(&URL_SAFE_NO_PAD.encode("attachment image.png"))
590 .unwrap(),
591 "attachment image.png"
592 );
593 assert!(decode_filename("a==").is_err());
594 }
595
596 #[test]
597 fn expires_abandoned_transfers_after_one_minute() {
598 let started = Instant::now();
599 assert!(!upload_is_expired(
600 started,
601 started + UPLOAD_IDLE_TIMEOUT - Duration::from_millis(1)
602 ));
603 assert!(upload_is_expired(started, started + UPLOAD_IDLE_TIMEOUT));
604 }
605}
src/commands/mod.rs +4
@@ -16,6 +16,7 @@ mod invite;
16mod join; 16mod join;
17mod keys; 17mod keys;
18mod matrix; 18mod matrix;
19mod matrix_upload;
19mod me; 20mod me;
20mod media; 21mod media;
21mod mention_send; 22mod mention_send;
@@ -42,6 +43,7 @@ use invite::InviteCommand;
42use join::JoinCommand; 43use join::JoinCommand;
43use keys::KeysCommand; 44use keys::KeysCommand;
44use matrix::MatrixCommand; 45use matrix::MatrixCommand;
46use matrix_upload::MatrixUploadCommand;
45use me::MeCommand; 47use me::MeCommand;
46use media::MediaCommand; 48use media::MediaCommand;
47use mention_send::MentionSendCommand; 49use mention_send::MentionSendCommand;
@@ -59,6 +61,7 @@ use verify::VerifyCommand;
59pub struct Commands { 61pub struct Commands {
60 _matrix: Command, 62 _matrix: Command,
61 _mention_send: CommandRun, 63 _mention_send: CommandRun,
64 _matrix_upload: CommandRun,
62 _keys: Command, 65 _keys: Command,
63 _devices: Command, 66 _devices: Command,
64 _invite: Command, 67 _invite: Command,
@@ -91,6 +94,7 @@ impl Commands {
91 Ok(Commands { 94 Ok(Commands {
92 _matrix: MatrixCommand::create(servers, config)?, 95 _matrix: MatrixCommand::create(servers, config)?,
93 _mention_send: MentionSendCommand::create(servers)?, 96 _mention_send: MentionSendCommand::create(servers)?,
97 _matrix_upload: MatrixUploadCommand::create(servers)?,
94 _devices: DevicesCommand::create(servers)?, 98 _devices: DevicesCommand::create(servers)?,
95 _invite: InviteCommand::create(servers)?, 99 _invite: InviteCommand::create(servers)?,
96 _ignore: IgnoreCommand::create()?, 100 _ignore: IgnoreCommand::create()?,
src/commands/upload.rs +6 −3
@@ -6,7 +6,7 @@ use weechat::{
6 ReturnCode, Weechat, 6 ReturnCode, Weechat,
7}; 7};
8 8
9use crate::Servers; 9use crate::{room::thread_root_from_buffer, Servers};
10 10
11pub struct UploadCommand { 11pub struct UploadCommand {
12 servers: Servers, 12 servers: Servers,
@@ -47,8 +47,11 @@ impl CommandRunCallback for UploadCommand {
47 } 47 }
48 48
49 let path = PathBuf::from(Weechat::expand_home(path)); 49 let path = PathBuf::from(Weechat::expand_home(path));
50 Weechat::spawn(async move { room.send_attachment(path).await }) 50 let thread_root = thread_root_from_buffer(buffer);
51 .detach(); 51 Weechat::spawn(
52 async move { room.send_attachment(path, thread_root).await },
53 )
54 .detach();
52 55
53 ReturnCode::Ok 56 ReturnCode::Ok
54 } 57 }
src/room/mod.rs +109 −8
@@ -52,9 +52,14 @@ use url::Url;
52 52
53use matrix_sdk::{ 53use matrix_sdk::{
54 async_trait, 54 async_trait,
55 attachment::{AttachmentConfig, AttachmentInfo, BaseFileInfo}, 55 attachment::{
56 AttachmentConfig, AttachmentInfo, BaseFileInfo, BaseImageInfo,
57 },
56 deserialized_responses::AmbiguityChange, 58 deserialized_responses::AmbiguityChange,
57 room::Room, 59 room::{
60 reply::{EnforceThread, Reply},
61 Room,
62 },
58 ruma::{ 63 ruma::{
59 events::{ 64 events::{
60 relation::Thread, 65 relation::Thread,
@@ -65,8 +70,8 @@ use matrix_sdk::{
65 }, 70 },
66 member::RoomMemberEventContent, 71 member::RoomMemberEventContent,
67 message::{ 72 message::{
68 MessageType, Relation, RoomMessageEventContent, 73 MessageType, Relation, ReplyWithinThread,
69 TextMessageEventContent, 74 RoomMessageEventContent, TextMessageEventContent,
70 }, 75 },
71 redaction::SyncRoomRedactionEvent, 76 redaction::SyncRoomRedactionEvent,
72 }, 77 },
@@ -420,12 +425,28 @@ fn with_mentions(
420 content 425 content
421} 426}
422 427
423fn thread_root_from_buffer(buffer: &Buffer) -> Option<OwnedEventId> { 428pub(crate) fn thread_root_from_buffer(buffer: &Buffer) -> Option<OwnedEventId> {
424 buffer 429 buffer
425 .get_localvar("thread_root") 430 .get_localvar("thread_root")
426 .and_then(|thread_root| EventId::parse(thread_root.as_ref()).ok()) 431 .and_then(|thread_root| EventId::parse(thread_root.as_ref()).ok())
427} 432}
428 433
434fn attachment_config(
435 info: AttachmentInfo,
436 thread_root: Option<OwnedEventId>,
437) -> AttachmentConfig {
438 let config = AttachmentConfig::new().info(info);
439
440 if let Some(event_id) = thread_root {
441 config.reply(Some(Reply {
442 event_id,
443 enforce_thread: EnforceThread::Threaded(ReplyWithinThread::No),
444 }))
445 } else {
446 config
447 }
448}
449
429fn thread_root_from_content( 450fn thread_root_from_content(
430 content: &RoomMessageEventContent, 451 content: &RoomMessageEventContent,
431) -> Option<&EventId> { 452) -> Option<&EventId> {
@@ -1766,7 +1787,11 @@ impl MatrixRoom {
1766 } 1787 }
1767 } 1788 }
1768 1789
1769 pub async fn send_attachment(&self, path: PathBuf) { 1790 pub async fn send_attachment(
1791 &self,
1792 path: PathBuf,
1793 thread_root: Option<OwnedEventId>,
1794 ) {
1770 let Some(filename) = path 1795 let Some(filename) = path
1771 .file_name() 1796 .file_name()
1772 .and_then(|f| f.to_str()) 1797 .and_then(|f| f.to_str())
@@ -1790,8 +1815,10 @@ impl MatrixRoom {
1790 1815
1791 let content_type = mime_guess::from_path(&path).first_or_octet_stream(); 1816 let content_type = mime_guess::from_path(&path).first_or_octet_stream();
1792 let size = UInt::new(data.len() as u64); 1817 let size = UInt::new(data.len() as u64);
1793 let config = AttachmentConfig::new() 1818 let config = attachment_config(
1794 .info(AttachmentInfo::File(BaseFileInfo { size })); 1819 AttachmentInfo::File(BaseFileInfo { size }),
1820 thread_root,
1821 );
1795 1822
1796 let Some(connection) = self.connection.borrow().clone() else { 1823 let Some(connection) = self.connection.borrow().clone() else {
1797 self.print_error("Not connected. Please connect first."); 1824 self.print_error("Not connected. Please connect first.");
@@ -1819,6 +1846,47 @@ impl MatrixRoom {
1819 } 1846 }
1820 } 1847 }
1821 1848
1849 pub async fn send_attachment_bytes(
1850 &self,
1851 filename: String,
1852 content_type: mime::Mime,
1853 data: Vec<u8>,
1854 thread_root: Option<OwnedEventId>,
1855 ) {
1856 let size = UInt::new(data.len() as u64);
1857 let info = if content_type.type_() == mime::IMAGE {
1858 AttachmentInfo::Image(BaseImageInfo {
1859 size,
1860 ..Default::default()
1861 })
1862 } else {
1863 AttachmentInfo::File(BaseFileInfo { size })
1864 };
1865 let config = attachment_config(info, thread_root);
1866
1867 let Some(connection) = self.connection.borrow().clone() else {
1868 self.print_error("Not connected. Please connect first.");
1869 return;
1870 };
1871
1872 match connection
1873 .spawn({
1874 let room = self.room();
1875 async move {
1876 room.send_attachment(filename, &content_type, data, config)
1877 .await
1878 }
1879 })
1880 .await
1881 {
1882 Ok(_) => (),
1883 Err(e) => self.print_error(&format!(
1884 "Failed to upload Matrix attachment: {}",
1885 e
1886 )),
1887 }
1888 }
1889
1822 /// Send out a typing notice. 1890 /// Send out a typing notice.
1823 /// 1891 ///
1824 /// This will send out a typing notice or reset the one in progress, if 1892 /// This will send out a typing notice or reset the one in progress, if
@@ -2531,6 +2599,39 @@ mod tests {
2531 assert_eq!(ReplyContext::Full, reply_context_for_distance(2, None)); 2599 assert_eq!(ReplyContext::Full, reply_context_for_distance(2, None));
2532 } 2600 }
2533 2601
2602 #[test]
2603 fn room_image_attachment_has_native_image_metadata_without_reply() {
2604 let config = attachment_config(
2605 AttachmentInfo::Image(BaseImageInfo {
2606 size: UInt::new(42),
2607 ..Default::default()
2608 }),
2609 None,
2610 );
2611
2612 assert!(matches!(config.info, Some(AttachmentInfo::Image(_))));
2613 assert!(config.reply.is_none());
2614 }
2615
2616 #[test]
2617 fn thread_image_attachment_targets_the_thread_root() {
2618 let thread_root = EventId::parse("$thread-root:example.org").unwrap();
2619 let config = attachment_config(
2620 AttachmentInfo::Image(BaseImageInfo {
2621 size: UInt::new(42),
2622 ..Default::default()
2623 }),
2624 Some(thread_root.to_owned()),
2625 );
2626
2627 let reply = config.reply.expect("thread image must carry a reply");
2628 assert_eq!(reply.event_id, thread_root);
2629 assert_eq!(
2630 reply.enforce_thread,
2631 EnforceThread::Threaded(ReplyWithinThread::No)
2632 );
2633 }
2634
2534 #[test] 2635 #[test]
2535 fn thread_buffer_input_sends_thread_relation() { 2636 fn thread_buffer_input_sends_thread_relation() {
2536 let content = make_text_message_content( 2637 let content = make_text_message_content(