Commit bff5b632c4

bff5b632c445e1bd932dc071b1b49448d260d4ff

parent: 1a2e2ea0cb

Unsigned

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

feat: add file upload command

Layout: unified · split

Cargo.lock +11
@@ -2361,6 +2361,16 @@ version = "0.1.54"
2361source = "registry+https://github.com/rust-lang/crates.io-index" 2361source = "registry+https://github.com/rust-lang/crates.io-index"
2362checksum = "cbf6f36070878c42c5233846cd3de24cf9016828fd47bc22957a687298bb21fc" 2362checksum = "cbf6f36070878c42c5233846cd3de24cf9016828fd47bc22957a687298bb21fc"
2363 2363
2364[[package]]
2365name = "mime_guess"
2366version = "2.0.5"
2367source = "registry+https://github.com/rust-lang/crates.io-index"
2368checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
2369dependencies = [
2370 "mime",
2371 "unicase",
2372]
2373
2364[[package]] 2374[[package]]
2365name = "minimal-lexical" 2375name = "minimal-lexical"
2366version = "0.2.1" 2376version = "0.2.1"
@@ -4627,6 +4637,7 @@ dependencies = [
4627 "dashmap", 4637 "dashmap",
4628 "image", 4638 "image",
4629 "matrix-sdk", 4639 "matrix-sdk",
4640 "mime_guess",
4630 "qrcode", 4641 "qrcode",
4631 "serde_json", 4642 "serde_json",
4632 "strum", 4643 "strum",
Cargo.toml +1
@@ -45,6 +45,7 @@ unicode-segmentation = "1.10.0"
45# Auto-select version from matrix-sdk 45# Auto-select version from matrix-sdk
46qrcode = { version = "*", default-features = false } 46qrcode = { version = "*", default-features = false }
47image = { version = "*", default-features = false, features = ["jpeg"] } 47image = { version = "*", default-features = false, features = ["jpeg"] }
48mime_guess = "2.0"
48 49
49[dependencies.weechat] 50[dependencies.weechat]
50git = "https://github.com/poljar/rust-weechat" 51git = "https://github.com/poljar/rust-weechat"
src/commands/mod.rs +4
@@ -14,6 +14,7 @@ mod matrix;
14mod me; 14mod me;
15mod media; 15mod media;
16mod page_up; 16mod page_up;
17mod upload;
17mod verification; 18mod verification;
18 19
19use buffer_clear::BufferClearCommand; 20use buffer_clear::BufferClearCommand;
@@ -23,6 +24,7 @@ use matrix::MatrixCommand;
23use me::MeCommand; 24use me::MeCommand;
24use media::MediaCommand; 25use media::MediaCommand;
25use page_up::PageUpCommand; 26use page_up::PageUpCommand;
27use upload::UploadCommand;
26 28
27pub struct Commands { 29pub struct Commands {
28 _matrix: Command, 30 _matrix: Command,
@@ -32,6 +34,7 @@ pub struct Commands {
32 _verification: Command, 34 _verification: Command,
33 _buffer_clear: CommandRun, 35 _buffer_clear: CommandRun,
34 _me: CommandRun, 36 _me: CommandRun,
37 _upload: CommandRun,
35} 38}
36 39
37impl Commands { 40impl Commands {
@@ -47,6 +50,7 @@ impl Commands {
47 _verification: VerificationCommand::create(servers)?, 50 _verification: VerificationCommand::create(servers)?,
48 _buffer_clear: BufferClearCommand::create(servers)?, 51 _buffer_clear: BufferClearCommand::create(servers)?,
49 _me: MeCommand::create(servers)?, 52 _me: MeCommand::create(servers)?,
53 _upload: UploadCommand::create(servers)?,
50 }) 54 })
51 } 55 }
52} 56}
src/commands/upload.rs added +55
@@ -0,0 +1,55 @@
1use std::{borrow::Cow, path::PathBuf};
2
3use weechat::{
4 buffer::Buffer,
5 hooks::{CommandRun, CommandRunCallback},
6 ReturnCode, Weechat,
7};
8
9use crate::Servers;
10
11pub struct UploadCommand {
12 servers: Servers,
13}
14
15impl UploadCommand {
16 pub fn create(servers: &Servers) -> Result<CommandRun, ()> {
17 CommandRun::new(
18 "/upload",
19 UploadCommand {
20 servers: servers.clone(),
21 },
22 )
23 }
24}
25
26impl CommandRunCallback for UploadCommand {
27 fn callback(
28 &mut self,
29 _: &Weechat,
30 buffer: &Buffer,
31 cmd: Cow<str>,
32 ) -> ReturnCode {
33 let Some(room) = self.servers.find_room(buffer) else {
34 Weechat::print(
35 "The upload command needs to be executed in a room buffer",
36 );
37 return ReturnCode::Ok;
38 };
39
40 let Some(path) = cmd.strip_prefix("/upload").map(str::trim) else {
41 return ReturnCode::Ok;
42 };
43
44 if path.is_empty() {
45 Weechat::print("Usage: /upload <file>");
46 return ReturnCode::Ok;
47 }
48
49 let path = PathBuf::from(Weechat::expand_home(path));
50 Weechat::spawn(async move { room.send_attachment(path).await })
51 .detach();
52
53 ReturnCode::Ok
54 }
55}
src/room/mod.rs +67 −2
@@ -38,6 +38,7 @@ use std::{
38 cell::RefCell, 38 cell::RefCell,
39 collections::HashMap, 39 collections::HashMap,
40 ops::Deref, 40 ops::Deref,
41 path::PathBuf,
41 rc::Rc, 42 rc::Rc,
42 sync::{ 43 sync::{
43 atomic::{AtomicBool, Ordering}, 44 atomic::{AtomicBool, Ordering},
@@ -50,6 +51,7 @@ use url::Url;
50 51
51use matrix_sdk::{ 52use matrix_sdk::{
52 async_trait, 53 async_trait,
54 attachment::{AttachmentConfig, AttachmentInfo, BaseFileInfo},
53 deserialized_responses::AmbiguityChange, 55 deserialized_responses::AmbiguityChange,
54 room::Room, 56 room::Room,
55 ruma::{ 57 ruma::{
@@ -67,7 +69,7 @@ use matrix_sdk::{
67 OriginalSyncMessageLikeEvent, SyncMessageLikeEvent, SyncStateEvent, 69 OriginalSyncMessageLikeEvent, SyncMessageLikeEvent, SyncStateEvent,
68 }, 70 },
69 EventId, MilliSecondsSinceUnixEpoch, OwnedRoomAliasId, 71 EventId, MilliSecondsSinceUnixEpoch, OwnedRoomAliasId,
70 OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UserId, 72 OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UInt, UserId,
71 }, 73 },
72 StoreError, 74 StoreError,
73}; 75};
@@ -77,7 +79,7 @@ use weechat::{
77 Buffer, BufferBuilderAsync, BufferHandle, BufferInputCallbackAsync, 79 Buffer, BufferBuilderAsync, BufferHandle, BufferInputCallbackAsync,
78 BufferLine, 80 BufferLine,
79 }, 81 },
80 Weechat, 82 Prefix, Weechat,
81}; 83};
82 84
83use crate::{ 85use crate::{
@@ -725,6 +727,69 @@ impl MatrixRoom {
725 } 727 }
726 } 728 }
727 729
730 fn print_error(&self, message: &str) {
731 if let Ok(buffer) = self.buffer_handle().upgrade() {
732 buffer.print(&format!(
733 "{}{}",
734 Weechat::prefix(Prefix::Error),
735 message
736 ));
737 }
738 }
739
740 pub async fn send_attachment(&self, path: PathBuf) {
741 let Some(filename) = path
742 .file_name()
743 .and_then(|f| f.to_str())
744 .map(ToOwned::to_owned)
745 else {
746 self.print_error("Invalid file name");
747 return;
748 };
749
750 let data = match std::fs::read(&path) {
751 Ok(data) => data,
752 Err(e) => {
753 self.print_error(&format!(
754 "Failed to read attachment {}: {}",
755 path.display(),
756 e
757 ));
758 return;
759 }
760 };
761
762 let content_type = mime_guess::from_path(&path).first_or_octet_stream();
763 let size = UInt::new(data.len() as u64);
764 let config = AttachmentConfig::new()
765 .info(AttachmentInfo::File(BaseFileInfo { size }));
766
767 let Some(connection) = self.connection.borrow().clone() else {
768 self.print_error("Not connected. Please connect first.");
769 return;
770 };
771
772 match connection
773 .spawn({
774 let room = self.room().clone();
775 async move {
776 room.send_attachment(filename, &content_type, data, config)
777 .await
778 }
779 })
780 .await
781 {
782 Ok(_) => (),
783 Err(e) => {
784 self.print_error(&format!(
785 "Failed to upload attachment {}: {}",
786 path.display(),
787 e
788 ));
789 }
790 }
791 }
792
728 /// Send out a typing notice. 793 /// Send out a typing notice.
729 /// 794 ///
730 /// This will send out a typing notice or reset the one in progress, if 795 /// This will send out a typing notice or reset the one in progress, if