pub mod binary;
pub mod digest;
pub mod text;
pub mod types;
pub use types::{
BtProgress, DownloadStats, InFlightPiece, PeerAddr, hex_to_info_hash, info_hash_to_hex,
};
use std::path::{Path, PathBuf};
use tracing::debug;
use crate::error::{Aria2Error, Result};
#[derive(Debug)]
pub struct BtProgressManager {
save_dir: PathBuf,
last_digest: Option<[u8; 20]>,
write_lock: std::sync::Mutex<()>,
}
impl BtProgressManager {
pub fn new(save_dir: &Path) -> Result<Self> {
std::fs::create_dir_all(save_dir).map_err(|e| {
Aria2Error::InvalidArgument(format!(
"Failed to create progress save directory {:?}: {}",
save_dir, e
))
})?;
Ok(Self {
save_dir: save_dir.to_path_buf(),
last_digest: None,
write_lock: std::sync::Mutex::new(()),
})
}
pub fn save_progress(&self, info_hash: &[u8; 20], progress: &BtProgress) -> Result<()> {
let _write_guard = self
.write_lock
.lock()
.map_err(|_| Aria2Error::Io("BT progress write lock is poisoned".into()))?;
let path = self.get_progress_file_path(info_hash);
let data = binary::serialize_binary(progress)?;
let temp_path = path.with_extension(format!("aria2.tmp{}", rand::random::<u32>()));
std::fs::write(&temp_path, &data)
.map_err(|e| Aria2Error::Io(format!("Failed to write temp progress file: {}", e)))?;
#[cfg(windows)]
let _ = std::fs::remove_file(&path);
if let Err(e) = std::fs::rename(&temp_path, &path) {
let _ = std::fs::remove_file(&temp_path);
return Err(Aria2Error::Io(format!(
"Failed to rename temp progress file: {}",
e
)));
}
debug!(
path = ?path,
bytes = data.len(),
"Saved BT progress (binary format)"
);
Ok(())
}
pub fn save_progress_with_dedup(
&mut self,
info_hash: &[u8; 20],
progress: &BtProgress,
) -> Result<bool> {
let data = binary::serialize_binary(progress)?;
let digest = digest::compute_sha1_digest(&data);
if let Some(ref last) = self.last_digest
&& last == &digest
{
debug!("Progress unchanged, skipping write (dedup)");
return Ok(false);
}
self.save_progress(info_hash, progress)?;
self.last_digest = Some(digest);
Ok(true)
}
pub fn load_progress(&self, info_hash: &[u8; 20]) -> Result<BtProgress> {
let path = self.get_progress_file_path(info_hash);
if !path.exists() {
return Err(Aria2Error::InvalidArgument(format!(
"Progress file not found: {:?}",
path
)));
}
let data = std::fs::read(&path)
.map_err(|e| Aria2Error::Io(format!("Failed to read progress file: {}", e)))?;
if data.is_empty() {
return Err(Aria2Error::InvalidArgument(
"Progress file is empty".to_string(),
));
}
if data.len() >= 2 && data[0] == 0x00 && data[1] == 0x01 {
binary::deserialize_binary(&data, info_hash)
} else if data.starts_with(b"[Download]") {
text::deserialize_text(&data, info_hash)
} else {
Err(Aria2Error::InvalidArgument(
"Unrecognized progress file format".to_string(),
))
}
}
pub fn remove_progress(&self, info_hash: &[u8; 20]) -> Result<()> {
let path = self.get_progress_file_path(info_hash);
if path.exists() {
std::fs::remove_file(&path)
.map_err(|e| Aria2Error::Io(format!("Failed to remove progress file: {}", e)))?;
}
Ok(())
}
pub fn exists(&self, info_hash: &[u8; 20]) -> bool {
self.get_progress_file_path(info_hash).exists()
}
pub fn list_saved_progresses(&self) -> Vec<[u8; 20]> {
let mut result = Vec::new();
if let Ok(entries) = std::fs::read_dir(&self.save_dir) {
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str()
&& let Some(hex_hash) = name.strip_suffix(".aria2")
{
if hex_hash.len() == 40
&& let Ok(hash) = hex_to_info_hash(hex_hash)
{
result.push(hash);
}
}
}
}
result
}
pub fn get_progress_file_path(&self, info_hash: &[u8; 20]) -> PathBuf {
let hex_hash = info_hash_to_hex(info_hash);
self.save_dir.join(format!("{}.aria2", hex_hash))
}
}