use clap::Parser;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
pub url: String,
#[arg(short, long)]
pub output: Option<PathBuf>,
#[arg(short, long, default_value_t = 4)]
pub threads: usize,
#[arg(long, default_value = "nget/1.0")]
pub user_agent: String,
#[arg(long, default_value_t = 0)]
pub timeout: u64,
#[arg(short, long)]
pub resume: bool,
#[arg(long)]
pub force: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DownloadState {
pub url: String,
pub output_path: PathBuf,
pub total_size: u64,
pub ranges: Vec<DownloadRange>,
pub etag: Option<String>,
pub last_modified: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DownloadRange {
pub start: u64,
pub end: u64,
pub downloaded: u64,
pub completed: bool,
}
impl DownloadRange {
pub fn new(start: u64, end: u64) -> Self {
Self {
start,
end,
downloaded: 0,
completed: false,
}
}
pub fn remaining(&self) -> u64 {
if self.completed {
0
} else {
(self.end - self.start + 1) - self.downloaded
}
}
pub fn is_completed(&self) -> bool {
self.completed || self.downloaded >= (self.end - self.start + 1)
}
}
#[derive(Debug, Clone)]
pub struct DownloadConfig {
pub url: String,
pub output_path: PathBuf,
pub num_threads: usize,
pub user_agent: String,
pub timeout: u64,
pub resume: bool,
pub force: bool,
}
impl From<Cli> for DownloadConfig {
fn from(cli: Cli) -> Self {
let output_path = cli
.output
.unwrap_or_else(|| PathBuf::from(cli.url.split('/').last().unwrap_or("download.bin")));
Self {
url: cli.url,
output_path,
num_threads: cli.threads,
user_agent: cli.user_agent,
timeout: cli.timeout,
resume: cli.resume,
force: cli.force,
}
}
}