pub mod builtin;
pub mod types;
#[cfg(test)]
mod tests;
pub use builtin::{ExecHook, MoveHook, RenameHook, TouchHook};
pub use types::{DownloadStats, DownloadStatus, HookContext, PostDownloadHook};
use tracing::{debug, error, info};
use crate::error::{Aria2Error, Result};
#[derive(Clone, Debug)]
pub struct HookConfig {
pub stop_on_error: bool,
pub timeout: std::time::Duration,
}
impl Default for HookConfig {
fn default() -> Self {
Self {
stop_on_error: false,
timeout: std::time::Duration::from_secs(30),
}
}
}
pub struct HookManager {
hooks: Vec<Box<dyn PostDownloadHook>>,
config: HookConfig,
}
impl HookManager {
pub fn new(config: HookConfig) -> Self {
Self {
hooks: Vec::new(),
config,
}
}
pub fn add_hook(&mut self, hook: Box<dyn PostDownloadHook>) {
info!(hook_name = hook.name(), "Adding hook to chain");
self.hooks.push(hook);
}
pub fn remove_hook(&mut self, name: &str) -> Option<Box<dyn PostDownloadHook>> {
let pos = self.hooks.iter().position(|h| h.name() == name)?;
info!(hook_name = name, "Removing hook from chain");
Some(self.hooks.remove(pos))
}
pub async fn fire_complete(&self, context: &HookContext) -> Result<Vec<String>> {
let mut results = Vec::with_capacity(self.hooks.len());
for hook in &self.hooks {
let hook_name = hook.name();
debug!(hook = hook_name, event = "complete", "Executing hook");
match hook.on_complete(context).await {
Ok(()) => {
let msg = format!("[{}] complete succeeded", hook_name);
info!("{}", msg);
results.push(msg);
}
Err(e) => {
let msg = format!("[{}] complete failed: {}", hook_name, e);
error!("{}", msg);
if self.config.stop_on_error {
return Err(Aria2Error::DownloadFailed(format!(
"Hook '{}' execution aborted due to stop_on_error setting: {}",
hook_name, e
)));
}
results.push(msg);
}
}
}
Ok(results)
}
pub async fn fire_error(&self, context: &HookContext, error: &str) -> Result<Vec<String>> {
let mut results = Vec::with_capacity(self.hooks.len());
let error_owned = error.to_string();
for hook in &self.hooks {
let hook_name = hook.name();
debug!(hook = hook_name, event = "error", "Executing hook");
match hook.on_error(context, &error_owned).await {
Ok(()) => {
let msg = format!("[{}] error handled successfully", hook_name);
info!("{}", msg);
results.push(msg);
}
Err(e) => {
let msg = format!("[{}] error handling failed: {}", hook_name, e);
error!("{}", msg);
if self.config.stop_on_error {
return Err(Aria2Error::DownloadFailed(format!(
"Hook '{}' error handler aborted due to stop_on_error setting: {}",
hook_name, e
)));
}
results.push(msg);
}
}
}
Ok(results)
}
pub fn hook_count(&self) -> usize {
self.hooks.len()
}
pub fn clear_hooks(&mut self) {
info!("Clearing all hooks");
self.hooks.clear();
}
}