use std::collections::HashMap;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use async_trait::async_trait;
use tokio::process::Command;
use tracing::{debug, info, warn};
use crate::error::{Aria2Error, Result};
use super::types::{HookContext, PostDownloadHook};
#[derive(Clone, Debug)]
pub struct MoveHook {
target_dir: PathBuf,
create_dirs: bool,
}
impl MoveHook {
pub fn new(target_dir: PathBuf, create_dirs: bool) -> Self {
Self {
target_dir,
create_dirs,
}
}
}
#[async_trait]
impl PostDownloadHook for MoveHook {
async fn on_complete(&self, context: &HookContext) -> Result<()> {
let source = &context.file_path;
if !source.exists() {
return Err(Aria2Error::Fatal(crate::error::FatalError::FileNotFound {
path: source.to_string_lossy().to_string(),
}));
}
if self.create_dirs && !self.target_dir.exists() {
debug!(
hook = "MoveHook",
target_dir = %self.target_dir.display(),
"Creating target directory"
);
tokio::fs::create_dir_all(&self.target_dir)
.await
.map_err(|e| {
Aria2Error::Io(format!(
"Failed to create directory {}: {}",
self.target_dir.display(),
e
))
})?;
}
let filename = context.filename();
let destination = self.target_dir.join(filename);
info!(
hook = "MoveHook",
source = %source.display(),
dest = %destination.display(),
"Moving file"
);
tokio::fs::rename(source, &destination).await.map_err(|e| {
Aria2Error::Io(format!(
"Failed to move file from {} to {}: {}",
source.display(),
destination.display(),
e
))
})?;
Ok(())
}
async fn on_error(&self, _context: &HookContext, _error: &str) -> Result<()> {
Ok(())
}
fn name(&self) -> &'static str {
"MoveHook"
}
}
#[derive(Clone, Debug)]
pub struct RenameHook {
pattern: String,
}
impl RenameHook {
pub fn new(pattern: String) -> Self {
Self { pattern }
}
pub fn expand_pattern(&self, context: &HookContext) -> String {
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
self.pattern
.replace("%d", &context.directory().to_string_lossy())
.replace("%f", context.filename())
.replace("%e", context.extension())
.replace("%i", &context.gid.value().to_string())
.replace("%t", ×tamp.to_string())
}
}
#[async_trait]
impl PostDownloadHook for RenameHook {
async fn on_complete(&self, context: &HookContext) -> Result<()> {
let source = &context.file_path;
if !source.exists() {
return Err(Aria2Error::Fatal(crate::error::FatalError::FileNotFound {
path: source.to_string_lossy().to_string(),
}));
}
let new_name = self.expand_pattern(context);
let destination = if new_name.contains(std::path::MAIN_SEPARATOR)
|| (std::path::MAIN_SEPARATOR == '\\' && new_name.contains('/'))
{
PathBuf::from(&new_name)
} else {
context.directory().join(&new_name)
};
info!(
hook = "RenameHook",
source = %source.display(),
dest = %destination.display(),
pattern = %self.pattern,
"Renaming file"
);
tokio::fs::rename(source, &destination).await.map_err(|e| {
Aria2Error::Io(format!(
"Failed to rename file to {}: {}",
destination.display(),
e
))
})?;
Ok(())
}
async fn on_error(&self, _context: &HookContext, _error: &str) -> Result<()> {
Ok(())
}
fn name(&self) -> &'static str {
"RenameHook"
}
}
#[derive(Clone, Debug)]
pub struct TouchHook;
impl TouchHook {
pub fn new() -> Self {
Self
}
}
impl Default for TouchHook {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl PostDownloadHook for TouchHook {
async fn on_complete(&self, context: &HookContext) -> Result<()> {
let path = &context.file_path;
if !path.exists() {
return Err(Aria2Error::Fatal(crate::error::FatalError::FileNotFound {
path: path.to_string_lossy().to_string(),
}));
}
let now = SystemTime::now();
debug!(
hook = "TouchHook",
path = %path.display(),
"Updating file timestamps"
);
#[cfg(unix)]
{
let _metadata = tokio::fs::metadata(path).await.map_err(|e| {
Aria2Error::Io(format!(
"Failed to get metadata for {}: {}",
path.display(),
e
))
})?;
let duration = now.duration_since(UNIX_EPOCH).unwrap_or_default();
let times: [libc::timespec; 2] = [
libc::timespec {
tv_sec: duration.as_secs() as _,
tv_nsec: duration.subsec_nanos() as _,
},
libc::timespec {
tv_sec: duration.as_secs() as _,
tv_nsec: duration.subsec_nanos() as _,
},
];
let c_path = std::ffi::CString::new(path.to_string_lossy().as_bytes())
.map_err(|e| Aria2Error::Io(format!("Invalid path: {}", e)))?;
unsafe {
if libc::utimensat(0, c_path.as_ptr(), times.as_ptr(), 0) != 0 {
return Err(Aria2Error::Io(format!(
"Failed to update timestamps for {}",
path.display()
)));
}
}
}
#[cfg(windows)]
{
use std::fs;
let file = fs::OpenOptions::new().write(true).open(path).map_err(|e| {
Aria2Error::Io(format!("Failed to open file {}: {}", path.display(), e))
})?;
file.set_modified(now).map_err(|e| {
Aria2Error::Io(format!(
"Failed to set modified time for {}: {}",
path.display(),
e
))
})?;
}
info!(
hook = "TouchHook",
path = %path.display(),
"File timestamps updated"
);
Ok(())
}
async fn on_error(&self, _context: &HookContext, _error: &str) -> Result<()> {
Ok(())
}
fn name(&self) -> &'static str {
"TouchHook"
}
}
#[derive(Clone, Debug)]
pub struct ExecHook {
command: String,
env_vars: HashMap<String, String>,
}
impl ExecHook {
pub fn new(command: String, env_vars: HashMap<String, String>) -> Self {
Self { command, env_vars }
}
pub(crate) fn build_env(
&self,
context: &HookContext,
status_override: Option<&str>,
) -> HashMap<String, String> {
let mut env = HashMap::new();
env.insert("ARIA2_GID".to_string(), context.gid.value().to_string());
env.insert(
"ARIA2_PATH".to_string(),
context.file_path.to_string_lossy().to_string(),
);
env.insert(
"ARIA2_STATUS".to_string(),
status_override
.unwrap_or(&context.status.to_string())
.to_string(),
);
if let Some(ref err) = context.error {
env.insert("ARIA2_ERROR".to_string(), err.clone());
}
env.insert(
"ARIA2_DOWNLOADED_BYTES".to_string(),
context.stats.downloaded_bytes.to_string(),
);
env.insert(
"ARIA2_UPLOADED_BYTES".to_string(),
context.stats.uploaded_bytes.to_string(),
);
env.insert(
"ARIA2_DOWNLOAD_SPEED".to_string(),
context.stats.download_speed.to_string(),
);
env.insert(
"ARIA2_UPLOAD_SPEED".to_string(),
context.stats.upload_speed.to_string(),
);
for (k, v) in &self.env_vars {
env.insert(k.clone(), v.clone());
}
env
}
}
#[async_trait]
impl PostDownloadHook for ExecHook {
async fn on_complete(&self, context: &HookContext) -> Result<()> {
let env = self.build_env(context, None);
info!(
hook = "ExecHook",
command = %self.command,
"Executing command on complete"
);
let output = Command::new("sh")
.arg("-c")
.arg(&self.command)
.envs(&env)
.output()
.await
.map_err(|e| {
Aria2Error::Io(format!(
"Failed to execute command '{}': {}",
self.command, e
))
})?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
warn!(
hook = "ExecHook",
command = %self.command,
exit_code = ?output.status.code(),
stderr = %stderr,
"Command failed with non-zero exit code"
);
return Err(Aria2Error::DownloadFailed(format!(
"Command '{}' failed with exit code {:?}: {}",
self.command,
output.status.code(),
stderr.trim()
)));
}
debug!(
hook = "ExecHook",
stdout = %String::from_utf8_lossy(&output.stdout),
"Command executed successfully"
);
Ok(())
}
async fn on_error(&self, context: &HookContext, error: &str) -> Result<()> {
let mut ctx_with_error = context.clone();
ctx_with_error.error = Some(error.to_string());
let env = self.build_env(&ctx_with_error, Some("error"));
info!(
hook = "ExecHook",
command = %self.command,
"Executing command on error"
);
let output = Command::new("sh")
.arg("-c")
.arg(&self.command)
.envs(&env)
.output()
.await
.map_err(|e| {
Aria2Error::Io(format!(
"Failed to execute command '{}': {}",
self.command, e
))
})?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(Aria2Error::DownloadFailed(format!(
"Command '{}' failed with exit code {:?}: {}",
self.command,
output.status.code(),
stderr.trim()
)));
}
Ok(())
}
fn name(&self) -> &'static str {
"ExecHook"
}
}