Skip to content

Commit

Permalink
feat: add command for opening file attachments (#356)
Browse files Browse the repository at this point in the history
  • Loading branch information
BradLewis authored Jan 22, 2025
1 parent d5304b8 commit 5c2a150
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ end_of_line
delete_character previous
edit_message
open_url
open_file
```

### Example configuration
Expand Down
31 changes: 31 additions & 0 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,9 @@ impl App {
Command::OpenUrl => {
self.try_open_url();
}
Command::OpenFile => {
self.try_open_file();
}
Command::DeleteCharacter(MoveDirection::Previous) => {
self.get_input().on_backspace();
}
Expand Down Expand Up @@ -406,6 +409,25 @@ impl App {
Some(())
}

/// Tries to open the first file attachment in the selected message.
///
/// Does nothing if no message is selected and the message contains no attachments.
fn try_open_file(&mut self) -> Option<()> {
// Note: to make the borrow checker happy, we have to use distinct fields here, and no
// methods that borrow self mutably.
let channel_id = self.channels.selected_item()?;
let messages = self.messages.get(channel_id)?;
let idx = messages.state.selected()?;
let idx = messages.items.len().checked_sub(idx + 1)?;
let arrived_at = messages.items.get(idx)?;
let message = self
.storage
.message(MessageId::new(*channel_id, *arrived_at))?;
open_file(&message)?;
self.reset_message_selection();
Some(())
}

fn selected_message_id(&self) -> Option<MessageId> {
// Messages are shown in reversed order => selected is reversed
let channel_id = self.channels.selected_item()?;
Expand Down Expand Up @@ -1650,6 +1672,15 @@ fn open_url(message: &Message, url_regex: &Regex) -> Option<()> {
Some(())
}

fn open_file(message: &Message) -> Option<()> {
let attachment = message.attachments.first()?;
let file: &Path = attachment.filename.as_ref();
if let Err(error) = opener::open(file) {
let path = file.display().to_string();
error!(path, %error, "failed to open");
}
Some(())
}
fn notification_text_for_attachments(attachments: &[Attachment]) -> Option<String> {
match attachments.len() {
0 => None,
Expand Down
2 changes: 2 additions & 0 deletions src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,8 @@ pub enum Command {
EditMessage,
#[strum(props(desc = "Try to open the first url in the selected message"))]
OpenUrl,
#[strum(props(desc = "Try to open the first file attachment of the selected message"))]
OpenFile,
// ReplyMessage,
// DeleteMessage,
}
Expand Down

0 comments on commit 5c2a150

Please sign in to comment.