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"
23612361source = "registry+https://github.com/rust-lang/crates.io-index"
23622362checksum = "cbf6f36070878c42c5233846cd3de24cf9016828fd47bc22957a687298bb21fc"
23632363
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
23642374[[package]]
23652375name = "minimal-lexical"
23662376version = "0.2.1"
@@ -4627,6 +4637,7 @@ dependencies = [
46274637 "dashmap",
46284638 "image",
46294639 "matrix-sdk",
4640 "mime_guess",
46304641 "qrcode",
46314642 "serde_json",
46324643 "strum",
Cargo.toml +1
@@ -45,6 +45,7 @@ unicode-segmentation = "1.10.0"
4545# Auto-select version from matrix-sdk
4646qrcode = { version = "*", default-features = false }
4747image = { version = "*", default-features = false, features = ["jpeg"] }
48mime_guess = "2.0"
4849
4950[dependencies.weechat]
5051git = "https://github.com/poljar/rust-weechat"
src/commands/mod.rs +4
@@ -14,6 +14,7 @@ mod matrix;
1414mod me;
1515mod media;
1616mod page_up;
17mod upload;
1718mod verification;
1819
1920use buffer_clear::BufferClearCommand;
@@ -23,6 +24,7 @@ use matrix::MatrixCommand;
2324use me::MeCommand;
2425use media::MediaCommand;
2526use page_up::PageUpCommand;
27use upload::UploadCommand;
2628
2729pub struct Commands {
2830 _matrix: Command,
@@ -32,6 +34,7 @@ pub struct Commands {
3234 _verification: Command,
3335 _buffer_clear: CommandRun,
3436 _me: CommandRun,
37 _upload: CommandRun,
3538}
3639
3740impl Commands {
@@ -47,6 +50,7 @@ impl Commands {
4750 _verification: VerificationCommand::create(servers)?,
4851 _buffer_clear: BufferClearCommand::create(servers)?,
4952 _me: MeCommand::create(servers)?,
53 _upload: UploadCommand::create(servers)?,
5054 })
5155 }
5256}
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::{
3838 cell::RefCell,
3939 collections::HashMap,
4040 ops::Deref,
41 path::PathBuf,
4142 rc::Rc,
4243 sync::{
4344 atomic::{AtomicBool, Ordering},
@@ -50,6 +51,7 @@ use url::Url;
5051
5152use matrix_sdk::{
5253 async_trait,
54 attachment::{AttachmentConfig, AttachmentInfo, BaseFileInfo},
5355 deserialized_responses::AmbiguityChange,
5456 room::Room,
5557 ruma::{
@@ -67,7 +69,7 @@ use matrix_sdk::{
6769 OriginalSyncMessageLikeEvent, SyncMessageLikeEvent, SyncStateEvent,
6870 },
6971 EventId, MilliSecondsSinceUnixEpoch, OwnedRoomAliasId,
70 OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UserId,
72 OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UInt, UserId,
7173 },
7274 StoreError,
7375};
@@ -77,7 +79,7 @@ use weechat::{
7779 Buffer, BufferBuilderAsync, BufferHandle, BufferInputCallbackAsync,
7880 BufferLine,
7981 },
80 Weechat,
82 Prefix, Weechat,
8183};
8284
8385use crate::{
@@ -725,6 +727,69 @@ impl MatrixRoom {
725727 }
726728 }
727729
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
728793 /// Send out a typing notice.
729794 ///
730795 /// This will send out a typing notice or reset the one in progress, if