use super::types::ResumeData;
use std::fs;
use std::path::Path;
use tracing::{debug, info, warn};
impl ResumeData {
pub fn serialize(&self) -> Result<String, String> {
serde_json::to_string_pretty(self)
.map_err(|e| format!("Failed to serialize resume data: {}", e))
}
pub fn deserialize(json_str: &str) -> Result<Self, String> {
serde_json::from_str(json_str).map_err(|e| {
format!(
"Failed to deserialize resume data: {}. JSON preview: {}",
e,
&json_str[..json_str.len().min(100)]
)
})
}
pub fn save_to_file(&self, path: &Path) -> Result<(), String> {
let json = self.serialize()?;
let tmp_path = path.with_extension("aria2.tmp");
debug!(path = %path.display(), "Saving resume data");
fs::write(&tmp_path, json).map_err(|e| {
format!(
"Failed to write temporary resume file {}: {}",
tmp_path.display(),
e
)
})?;
fs::rename(&tmp_path, path).map_err(|e| {
let _ = fs::remove_file(&tmp_path);
format!(
"Failed to atomic-rename resume file {} -> {}: {}",
tmp_path.display(),
path.display(),
e
)
})?;
info!(
gid = %self.gid,
completed = self.completed_length,
total = self.total_length,
path = %path.display(),
"Resume data saved successfully"
);
Ok(())
}
pub fn load_from_file(path: &Path) -> Result<Option<Self>, String> {
if !path.exists() {
return Ok(None);
}
debug!(path = %path.display(), "Loading resume data");
let json = fs::read_to_string(path)
.map_err(|e| format!("Failed to read resume file {}: {}", path.display(), e))?;
let data = Self::deserialize(&json)?;
info!(
gid = %data.gid,
completed = data.completed_length,
path = %path.display(),
"Resume data loaded successfully"
);
Ok(Some(data))
}
pub fn completion_ratio(&self) -> f64 {
if self.total_length == 0 {
return 0.0;
}
self.completed_length as f64 / self.total_length as f64
}
pub fn is_bit_torrent(&self) -> bool {
self.bt_info_hash.is_some() || !self.bitfield.is_empty()
}
pub fn is_metalink(&self) -> bool {
self.uris.len() > 1
}
pub fn get_filename(&self) -> String {
format!("{}.aria2", self.gid)
}
pub fn validate_for_restore(&self) -> Result<(), String> {
if self.gid.is_empty() {
return Err("GID must not be empty".to_string());
}
if self.uris.is_empty() {
return Err("At least one URI is required".to_string());
}
for (i, uri_state) in self.uris.iter().enumerate() {
if uri_state.uri.is_empty() {
return Err(format!("URI at index {} is empty", i));
}
}
if self.total_length > 0 && self.completed_length > self.total_length {
return Err(format!(
"completed_length ({}) exceeds total_length ({})",
self.completed_length, self.total_length
));
}
if self.is_bit_torrent()
&& let Some(num_pieces) = self.num_pieces
{
let expected_bytes = (num_pieces as usize).div_ceil(8);
if !self.bitfield.is_empty() && self.bitfield.len() != expected_bytes {
warn!(
expected = expected_bytes,
actual = self.bitfield.len(),
"Bitfield size mismatch with num_pieces"
);
}
}
match self.status.as_str() {
"active" | "waiting" | "paused" | "error" | "complete" => {}
_ => {
return Err(format!(
"Unknown status '{}': expected one of active/waiting/paused/error/complete",
self.status
));
}
}
Ok(())
}
pub fn detect_protocol(&self) -> &str {
if self.is_bit_torrent() {
"bt"
} else if self.uris.len() > 1 {
"metalink"
} else if let Some(first_uri_state) = self.uris.first() {
if first_uri_state.uri.starts_with("http://")
|| first_uri_state.uri.starts_with("https://")
{
"http"
} else if first_uri_state.uri.starts_with("ftp://")
|| first_uri_state.uri.starts_with("sftp://")
{
"ftp"
} else {
"unknown"
}
} else {
"unknown"
}
}
}
impl ResumeData {
pub(crate) fn extract_info_hash_from_magnet(magnet_uri: &str) -> Option<String> {
let start = magnet_uri.find("xt=urn:btih:")? + "xt=urn:btih:".len();
let end = magnet_uri[start..]
.find('&')
.unwrap_or(magnet_uri[start..].len());
let hash = &magnet_uri[start..start + end];
if hash.len() >= 20 {
Some(hash.to_string())
} else {
None
}
}
}