use std::path::{Path, PathBuf};
use tracing::{debug, info, warn};
use crate::error::{Aria2Error, RecoverableError};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FtpFileSize {
Known(u64),
Unknown,
}
#[derive(Debug, Clone, PartialEq)]
pub enum FtpFilePreparationResult {
NormalDownload {
total_length: u64,
local_path: PathBuf,
suffix_path: String,
},
ZeroLengthFile {
local_path: PathBuf,
suffix_path: String,
dry_run: bool,
file_exists_with_matching_length: bool,
checksum_verification_needed: bool,
},
TotalLengthUnknown {
local_path: PathBuf,
suffix_path: String,
},
DryRunFileFound {
total_length: u64,
local_path: PathBuf,
suffix_path: String,
},
DownloadAlreadyCompleted {
local_path: PathBuf,
},
ChecksumVerificationNeeded {
local_path: PathBuf,
},
}
#[derive(Debug, Clone)]
pub struct FtpFilePreparationConfig {
pub dir: String,
pub dry_run: bool,
pub request_file: String,
pub path_already_set: bool,
pub file_exists_with_matching_length: bool,
pub checksum_verification_needed: bool,
pub knows_total_length: bool,
pub piece_storage_initialized: bool,
}
impl Default for FtpFilePreparationConfig {
fn default() -> Self {
Self {
dir: ".".to_string(),
dry_run: false,
request_file: String::new(),
path_already_set: false,
file_exists_with_matching_length: false,
checksum_verification_needed: false,
knows_total_length: true,
piece_storage_initialized: false,
}
}
}
pub fn derive_local_path(dir: &str, request_file: &str) -> (PathBuf, String) {
let decoded = percent_decode(request_file);
let suffix_path = create_safe_path(&decoded);
let local_path = apply_dir(dir, &suffix_path);
(local_path, suffix_path)
}
pub fn percent_decode(s: &str) -> String {
let mut bytes = Vec::with_capacity(s.len());
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if c == '%' {
let hex: String = chars.by_ref().take(2).collect();
if let Ok(byte) = u8::from_str_radix(&hex, 16) {
bytes.push(byte);
} else {
bytes.push(b'%');
bytes.extend_from_slice(hex.as_bytes());
}
} else {
let mut buf = [0u8; 4];
let str_slice = c.encode_utf8(&mut buf);
bytes.extend_from_slice(str_slice.as_bytes());
}
}
String::from_utf8_lossy(&bytes).into_owned()
}
pub fn create_safe_path(name: &str) -> String {
let mut result = String::with_capacity(name.len());
for ch in name.chars() {
match ch {
'/' | '\\' => result.push('_'),
'\0' => { }
_ => result.push(ch),
}
}
if result.is_empty() {
"index.html".to_string()
} else {
result
}
}
pub fn apply_dir(dir: &str, suffix_path: &str) -> PathBuf {
if dir.is_empty() || dir == "." {
PathBuf::from(suffix_path)
} else {
Path::new(dir).join(suffix_path)
}
}
pub fn prepare_ftp_file(
file_size: &FtpFileSize,
config: &FtpFilePreparationConfig,
) -> Result<FtpFilePreparationResult, Aria2Error> {
match file_size {
FtpFileSize::Known(size) => {
if *size > i64::MAX as u64 {
warn!("File size {} exceeds maximum representable size", size);
return Err(Aria2Error::Recoverable(
RecoverableError::FtpProtocolError {
message: format!("File too large: {} bytes exceeds i64::MAX", size),
},
));
}
if config.piece_storage_initialized {
debug!(
"PieceStorage already initialized, validating total length: {}",
size
);
}
let (local_path, suffix_path) = if config.path_already_set {
(
PathBuf::from(&config.request_file),
config.request_file.clone(),
)
} else {
derive_local_path(&config.dir, &config.request_file)
};
let size = *size;
if size == 0 {
handle_zero_length_file(config, local_path, suffix_path)
} else if config.dry_run {
info!(
"Dry-run: file found, size={} path={}",
size,
local_path.display()
);
Ok(FtpFilePreparationResult::DryRunFileFound {
total_length: size,
local_path,
suffix_path,
})
} else {
info!(
"File preparation complete: size={} path={}",
size,
local_path.display()
);
Ok(FtpFilePreparationResult::NormalDownload {
total_length: size,
local_path,
suffix_path,
})
}
}
FtpFileSize::Unknown => {
debug!("SIZE not supported by server, total length unknown");
let (local_path, suffix_path) = if config.path_already_set {
(
PathBuf::from(&config.request_file),
config.request_file.clone(),
)
} else {
derive_local_path(&config.dir, &config.request_file)
};
if config.dry_run {
info!(
"Dry-run: file found (unknown size), path={}",
local_path.display()
);
return Ok(FtpFilePreparationResult::DryRunFileFound {
total_length: 0,
local_path,
suffix_path,
});
}
Ok(FtpFilePreparationResult::TotalLengthUnknown {
local_path,
suffix_path,
})
}
}
}
fn handle_zero_length_file(
config: &FtpFilePreparationConfig,
local_path: PathBuf,
suffix_path: String,
) -> Result<FtpFilePreparationResult, Aria2Error> {
if config.dry_run {
info!(
"Dry-run: zero-length file found, path={}",
local_path.display()
);
return Ok(FtpFilePreparationResult::DryRunFileFound {
total_length: 0,
local_path,
suffix_path,
});
}
if config.knows_total_length && config.file_exists_with_matching_length {
if config.checksum_verification_needed {
info!(
"Zero-length file exists, checksum verification needed: {}",
local_path.display()
);
return Ok(FtpFilePreparationResult::ChecksumVerificationNeeded { local_path });
}
info!(
"Zero-length file already exists, download complete: {}",
local_path.display()
);
return Ok(FtpFilePreparationResult::DownloadAlreadyCompleted { local_path });
}
info!(
"Zero-length file, preparing for download: {}",
local_path.display()
);
Ok(FtpFilePreparationResult::ZeroLengthFile {
local_path,
suffix_path,
dry_run: config.dry_run,
file_exists_with_matching_length: config.file_exists_with_matching_length,
checksum_verification_needed: config.checksum_verification_needed,
})
}
#[cfg(test)]
mod tests;