mod hls;
mod mktorrent;
mod daemon;
mod captcha;
mod cli;
mod config;
mod delta;
mod downloader;
mod engine;
mod fafo;
mod hook;
mod inputs;
mod mirror;
mod refresh;
mod request;
mod serve;
mod split;
mod state;
mod torrent;
mod verify;
use std::path::{Path, PathBuf};
use std::time::Instant;
use anyhow::{Context, Result, bail};
use clap::Parser;
use cli::{Cli, Command};
use config::{Config, format_bytes, format_duration_precise, format_speed, parse_speed_limit};
use downloader::{
DownloadOptions, meta_path, part_path, pause_sentinel, read_progress, resolve_output,
};
use state::{Engine, Record, Status, Store};
async fn via_http(url: &str, out: &Path, o: &DownloadOptions) -> Result<downloader::Summary> {
let input = inputs::HttpInput::new(url.to_owned());
let op = engine::Operation::Download(engine::DownloadParams {
connections: o.connections,
speed_limit_bps: o.speed_limit_bps,
retries: o.retries,
mirrors: o.mirrors.clone(),
allow_h3: o.allow_h3,
auto_mirror: o.auto_mirror,
proxy: o.proxy.clone(),
});
let s = engine::run_input(&input, &op, &engine::Output::File(out.to_path_buf())).await?;
Ok(downloader::Summary {
total_bytes: s.total_bytes,
elapsed_secs: s.elapsed_secs,
avg_bps: s.avg_bps,
mirrors: s.mirrors,
})
}
async fn via_ftp(url: &str, out: &Path, o: &DownloadOptions) -> Result<downloader::Summary> {
let input = inputs::FtpInput::new(url.to_owned());
let op = engine::Operation::Download(engine::DownloadParams {
connections: o.connections,
speed_limit_bps: o.speed_limit_bps,
retries: o.retries,
mirrors: vec![],
allow_h3: false,
auto_mirror: false,
proxy: o.proxy.clone(),
});
let s = engine::run_input(&input, &op, &engine::Output::File(out.to_path_buf())).await?;
Ok(downloader::Summary {
total_bytes: s.total_bytes,
elapsed_secs: s.elapsed_secs,
avg_bps: s.avg_bps,
mirrors: s.mirrors,
})
}
async fn via_sftp(url: &str, out: &Path, o: &DownloadOptions) -> Result<downloader::Summary> {
let input = inputs::SftpInput::new(url.to_owned())?;
let op = engine::Operation::Download(engine::DownloadParams {
connections: o.connections,
speed_limit_bps: o.speed_limit_bps,
retries: o.retries,
mirrors: vec![],
allow_h3: false,
auto_mirror: false,
proxy: o.proxy.clone(),
});
let s = engine::run_input(&input, &op, &engine::Output::File(out.to_path_buf())).await?;
Ok(downloader::Summary {
total_bytes: s.total_bytes,
elapsed_secs: s.elapsed_secs,
avg_bps: s.avg_bps,
mirrors: s.mirrors,
})
}
async fn via_s3(url: &str, out: &Path, o: &DownloadOptions) -> Result<downloader::Summary> {
let input = inputs::S3Input::new(url.to_owned())?;
let op = engine::Operation::Download(engine::DownloadParams {
connections: o.connections,
speed_limit_bps: o.speed_limit_bps,
retries: o.retries,
mirrors: vec![],
allow_h3: false,
auto_mirror: false,
proxy: o.proxy.clone(),
});
let s = engine::run_input(&input, &op, &engine::Output::File(out.to_path_buf())).await?;
Ok(downloader::Summary {
total_bytes: s.total_bytes,
elapsed_secs: s.elapsed_secs,
avg_bps: s.avg_bps,
mirrors: s.mirrors,
})
}
async fn via_ipfs(url: &str, out: &Path, o: &DownloadOptions) -> Result<downloader::Summary> {
let input = inputs::IpfsInput::new(url.to_owned());
inputs::IpfsInput::parse(url)?;
let op = engine::Operation::Download(engine::DownloadParams {
connections: o.connections,
speed_limit_bps: o.speed_limit_bps,
retries: o.retries,
mirrors: o.mirrors.clone(),
allow_h3: o.allow_h3,
auto_mirror: o.auto_mirror,
proxy: o.proxy.clone(),
});
let s = engine::run_input(&input, &op, &engine::Output::File(out.to_path_buf())).await?;
Ok(downloader::Summary {
total_bytes: s.total_bytes,
elapsed_secs: s.elapsed_secs,
avg_bps: s.avg_bps,
mirrors: s.mirrors,
})
}
async fn via_webdav(url: &str, out: &Path, o: &DownloadOptions) -> Result<downloader::Summary> {
let input = inputs::WebdavInput::new(url.to_owned());
let op = engine::Operation::Download(engine::DownloadParams {
connections: o.connections,
speed_limit_bps: o.speed_limit_bps,
retries: o.retries,
mirrors: vec![],
allow_h3: false,
auto_mirror: false,
proxy: o.proxy.clone(),
});
let s = engine::run_input(&input, &op, &engine::Output::File(out.to_path_buf())).await?;
Ok(downloader::Summary {
total_bytes: s.total_bytes,
elapsed_secs: s.elapsed_secs,
avg_bps: s.avg_bps,
mirrors: s.mirrors,
})
}
fn remote_scheme(url: &str) -> Option<&'static str> {
let lower = url.to_lowercase();
if lower.starts_with("ftp://") {
Some("ftp")
} else if lower.starts_with("sftp://") {
Some("sftp")
} else if lower.starts_with("s3://") {
Some("s3")
} else if lower.starts_with("ipfs://") {
Some("ipfs")
} else if lower.starts_with("webdav://") {
Some("webdav")
} else if lower.starts_with("webdavs://") {
Some("webdavs")
} else {
None
}
}
async fn via_remote(url: &str, out: &Path, o: &DownloadOptions) -> Result<downloader::Summary> {
match remote_scheme(url) {
Some("ftp") => via_ftp(url, out, o).await,
Some("sftp") => via_sftp(url, out, o).await,
Some("s3") => via_s3(url, out, o).await,
Some("ipfs") => via_ipfs(url, out, o).await,
Some("webdav") | Some("webdavs") => via_webdav(url, out, o).await,
_ => bail!("not an ftp/sftp/s3/ipfs/webdav URL: {url}"),
}
}
async fn via_torrent(
source: &torrent::TorrentSource,
output: Option<PathBuf>,
dir: &Path,
o: &torrent::TorrentOptions,
) -> Result<torrent::TorrentDone> {
let input = inputs::TorrentInput::new(
source.clone(),
output,
dir.to_path_buf(),
o.seed_minutes,
o.only_files.clone(),
);
let op = engine::Operation::Download(engine::DownloadParams::default());
let out = engine::Output::Dir(dir.to_path_buf());
input.run_full(&op, &out).await
}
async fn via_req(url: &str, o: &request::ReqOptions) -> Result<()> {
let input = inputs::ReqInput::new(url.to_owned(), o.clone());
let op = engine::Operation::Download(engine::DownloadParams::default());
let out = engine::Output::from_req_output(o.output.clone());
engine::run_input(&input, &op, &out).await?;
Ok(())
}
#[tokio::main]
async fn main() {
if let Err(e) = real_main().await {
eprintln!("Error: {e:#}");
std::process::exit(1);
}
}
async fn real_main() -> Result<()> {
let cli = Cli::parse();
match cli.command {
Command::Add {
url,
output,
connections,
speed_limit,
retries,
mirrors,
no_auto_mirror,
http3,
seed,
files,
delta,
referer,
selector,
cookies,
captcha,
proxy,
} => {
cmd_add(
url,
output,
connections,
speed_limit,
retries,
mirrors,
no_auto_mirror,
http3,
seed,
files,
delta,
referer,
selector,
cookies,
captcha,
proxy,
)
.await
}
Command::List {} => cmd_list(),
Command::Pause { id } => cmd_pause(id),
Command::Resume {
id,
connections,
mirrors,
no_auto_mirror,
http3,
seed,
proxy,
} => cmd_resume(id, connections, mirrors, no_auto_mirror, http3, seed, proxy).await,
Command::Remove { id, delete_files } => cmd_remove(id, delete_files),
Command::Status { id } => cmd_status(id),
Command::Queue {
urls,
file,
concurrent,
connections,
output_dir,
speed_limit,
mirrors,
no_auto_mirror,
http3,
seed,
proxy,
} => {
cmd_queue(
urls,
file,
concurrent,
connections,
output_dir,
speed_limit,
mirrors,
no_auto_mirror,
http3,
seed,
proxy,
)
.await
}
Command::Config {
show,
connections,
dir,
speed_limit,
tcp_tuning,
yes,
} => cmd_config(show, connections, dir, speed_limit, tcp_tuning, yes),
Command::Req {
url,
method,
headers,
data,
json,
output,
verbose,
head,
follow,
max_redirs,
silent,
max_time,
basic_auth,
cookie,
cookiejar,
proxy,
insecure,
cert,
key,
user_agent,
referer,
} => {
cmd_req(
url, method, headers, data, json, output, verbose, head, follow, max_redirs,
silent, max_time, basic_auth, cookie, cookiejar, proxy, insecure, cert, key,
user_agent, referer,
)
.await
}
Command::Guide { page } => cmd_guide(page),
Command::Serve { dir, port, host } => cmd_serve(dir, port, host).await,
Command::Hook { browser } => cmd_hook(browser),
Command::Mirror {
url,
recursive,
level,
include,
exclude,
output_dir,
connections,
speed_limit,
retries,
} => {
cmd_mirror(
url,
recursive,
level,
include,
exclude,
output_dir,
connections,
speed_limit,
retries,
)
.await
}
Command::Verify {
file,
sha256,
blake3,
} => cmd_verify(file, sha256, blake3),
Command::Split {
file,
parts,
size,
output_dir,
} => cmd_split(file, parts, size, output_dir),
Command::Join { source, output } => cmd_join(source, output),
Command::Hls {
playlist,
output,
connections,
speed_limit,
retries,
proxy,
} => cmd_hls(playlist, output, connections, speed_limit, retries, proxy).await,
Command::Mktorrent {
path,
trackers,
name,
piece,
} => cmd_mktorrent(path, trackers, name, piece),
Command::Daemon { action } => cmd_daemon(action),
Command::__DaemonRun {} => crate::daemon::run_server().await,
}
}
async fn cmd_serve(dir: PathBuf, port: u16, host: String) -> Result<()> {
serve::run(serve::ServeOptions { dir, host, port }).await
}
fn cmd_hook(browser: String) -> Result<()> {
let path = hook::install_manifest(&browser)?;
println!("xget hook: {browser} -> {}", path.display());
println!("queue endpoint: POST /link {{\"url\": ...}} on `xget serve`");
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn cmd_mirror(
url: String,
recursive: bool,
level: usize,
include: Vec<String>,
exclude: Vec<String>,
output_dir: Option<PathBuf>,
connections: Option<usize>,
speed_limit: Option<String>,
retries: u32,
) -> Result<()> {
if crate::torrent::detect(&url).is_some() || url.to_lowercase().starts_with("s3://") {
bail!("mirror covers http(s) and webdav listings only (torrents and s3:// are not recursed ({url}))");
}
if is_media_url(&url) {
bail!("{}", media_rejection_msg(&url));
}
let u = url::Url::parse(&url).with_context(|| format!("invalid URL: {url}"))?;
if u.scheme() != "http" && u.scheme() != "https" && u.scheme() != "webdav" && u.scheme() != "webdavs" {
bail!("mirror supports http(s) and webdav listings only: {url}");
}
let cfg = Config::load()?;
let dir = output_dir.unwrap_or(cfg.download_dir.clone());
let opts = crate::mirror::MirrorOptions {
recursive,
level,
include,
exclude,
connections: cfg.effective_connections(connections),
speed_limit_bps: match speed_limit {
Some(s) => parse_speed_limit(&s)?,
None => cfg.speed_limit_bps,
},
retries,
};
let started = Instant::now();
println!("xget mirror: {url} -> {}", dir.display());
let rep = crate::mirror::mirror_url(&url, &dir, &opts).await?;
println!(
"xget mirror: {} file(s), {} in {} ({} page(s))",
rep.files.len(),
format_bytes(rep.bytes),
format_duration_precise(started.elapsed().as_secs_f64()),
rep.pages
);
for f in &rep.files {
println!(" got {}", f.display());
}
for s in &rep.skipped {
println!(" skip {s}");
}
Ok(())
}
fn cmd_verify(file: PathBuf, sha256: Option<String>, blake3: Option<String>) -> Result<()> {
let req = crate::verify::VerifyRequest { sha256, blake3 };
let r = crate::verify::verify_file(&file, &req)?;
println!("{} {} ({} bytes)", r.sha256, file.display(), r.size);
println!("blake3: {}", r.blake3);
if r.checked.is_empty() {
println!("(no --sha256/--blake3 given - sums above)");
} else {
println!("{}: ok ({})", file.display(), r.checked.join(" + "));
}
Ok(())
}
fn cmd_split(
file: PathBuf,
parts: Option<usize>,
size: Option<String>,
output_dir: Option<PathBuf>,
) -> Result<()> {
let size = match size {
Some(s) => match parse_speed_limit(&s)? {
Some(n) if n > 0 => Some(n),
_ => bail!("--size must be > 0 (e.g. 100M)"),
},
None => None,
};
let (manifest_path, m) = crate::split::split_file(
&file,
&crate::split::SplitOptions {
parts,
size,
out_dir: output_dir,
},
)?;
println!(
"xget split: {} -> {} chunk(s) of ~{} in {}",
file.display(),
m.chunks.len(),
format_bytes(m.chunk_size),
manifest_path
.parent()
.map(|p| p.display().to_string())
.unwrap_or_default()
);
println!(" manifest: {}", manifest_path.display());
println!(
" total: {} (sha256 {})",
format_bytes(m.total),
m.total_sha256
);
Ok(())
}
fn cmd_join(source: PathBuf, output: Option<PathBuf>) -> Result<()> {
let dest = match output {
Some(p) => p,
None => {
let raw = std::fs::read_to_string(&source)
.with_context(|| format!("cannot read {}", source.display()))?;
let m: crate::split::SplitManifest =
serde_json::from_str(&raw).context("need -o <FILE> unless SOURCE is a manifest")?;
PathBuf::from(&m.file)
}
};
let bytes = crate::split::join_parts(&source, &dest)?;
println!(
"xget join: {} ({} bytes, verified where manifest available)",
dest.display(),
format_bytes(bytes)
);
Ok(())
}
async fn cmd_hls(
playlist: String,
output: Option<PathBuf>,
connections: Option<usize>,
speed_limit: Option<String>,
retries: u32,
proxy: Option<String>,
) -> Result<()> {
let cfg = Config::load()?;
let conns = cfg.effective_connections(connections);
let limit = match speed_limit {
Some(s) => parse_speed_limit(&s)?,
None => cfg.speed_limit_bps,
};
let opts = DownloadOptions {
connections: conns,
speed_limit_bps: limit,
retries,
mirrors: Vec::new(),
allow_h3: false,
auto_mirror: false,
proxy: proxy.clone(),
};
let guess_out = crate::hls::output_for_hls(&playlist, playlist.to_lowercase().contains(".mpd"), output.clone(), &cfg.download_dir);
let (id, via_daemon) = create_record(&playlist, &guess_out, conns, Engine::Direct, Vec::new())?;
println!("xget #{id}: hls {playlist}");
println!(" target: {}", guess_out.display());
match crate::hls::run_hls(&playlist, output, &cfg.download_dir, &opts).await {
Ok((final_path, sum)) => {
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Completed;
r.error = None;
r.output = final_path.to_string_lossy().to_string();
r.total_bytes = Some(sum.total_bytes);
r.downloaded = sum.total_bytes;
}
store.save()?;
if via_daemon {
crate::daemon::daemon_complete(id, sum.total_bytes);
}
println!("xget #{id}: {}", sum.report());
println!(" file: {}", final_path.display());
Ok(())
}
Err(e) => {
let msg = e.to_string();
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Failed;
r.error = Some(msg.clone());
}
store.save()?;
if via_daemon {
crate::daemon::daemon_fail(id, &msg);
}
bail!("xget #{id}: hls failed: {msg}");
}
}
}
fn cmd_mktorrent(
path: PathBuf,
trackers: Option<String>,
name: Option<String>,
piece: Option<String>,
) -> Result<()> {
let dest = crate::mktorrent::create_torrent_file(&path, trackers, name, piece)?;
let bytes = std::fs::read(&dest)
.with_context(|| format!("cannot read {}", dest.display()))?;
let meta = crate::torrent::parse_torrent_bytes(&bytes)?;
println!(
" verify: {} ({} file(s), {}) parses with torrent engine",
meta.name,
meta.files.len(),
format_bytes(meta.total_length)
);
println!(" add: xget add {} -o <DIR>", dest.display());
Ok(())
}
fn cmd_daemon(action: String) -> Result<()> {
match action.to_lowercase().as_str() {
"start" => crate::daemon::cmd_start(),
"stop" => crate::daemon::cmd_stop(),
"status" => crate::daemon::cmd_status(),
_ => bail!("unknown daemon action: {action} (use start|stop|status)"),
}
}
fn cmd_guide(page: Option<String>) -> Result<()> {
const PAGES: &[(&str, &str)] = &[
(
"quickstart",
"QUICKSTART\n\n xget add <URL> -o <PATH> -c <N>\n xget list\n xget pause <ID> / xget resume <ID>\n xget status [ID] / xget remove <ID> [--delete-files]\n\n Exit code 0 = ok, else error text on stderr.",
),
(
"modes",
"MODES (throttle probe)\n\n single-stream: 1 connection, like curl. No per-connection limit.\n segmented xN: up to N Range segments. Per-connection limit detected.\n\n -c <N> (1-32) is the CEILING for segmented mode, not a fixed count.\n Probe (~1.8 MB) prints `mode: ...` before the download starts.",
),
(
"mirrors",
"MIRRORS\n\n --mirror <URL> (repeatable): extra source of THE SAME file.\n Wrong size = dropped silently. Per segment the fastest source wins.\n\n --no-auto-mirror: turns OFF built-in rules (kernel.org, ubuntu,\n hetzner). Use to download ONLY from your URL (+ --mirror).\n\n xget add f --mirror m2 --mirror m3\n xget add f --no-auto-mirror",
),
(
"queue",
"QUEUE\n\n Many files, --concurrent (default 3) at once.\n Per-download segments still capped by -c/--connections.\n\n xget queue URL1 URL2 -o /tmp/q -c 8 --concurrent 2\n xget queue --file urls.txt -o /tmp/q (# = comment)\n\n Clashing names become name.1, name.2, ...",
),
(
"resume",
"RESUME / PAUSE\n\n Ctrl-C keeps .part + sidecar: `xget resume <ID>` continues.\n `pause <ID>` marks for stop (worker halts in ~300 ms).\n `remove <ID>` forgets the record; --delete-files also deletes data.\n\n Resume flags replace saved ones: -c, --mirror, --http3, --no-auto-mirror.",
),
(
"config",
"CONFIG\n\n xget config --show\n xget config --connections 8 --dir ~/Downloads --speed-limit 2M\n xget config --tcp-tuning [--yes] (Linux BBR proposal; --yes needs root)\n\n Used when the matching flag is omitted on add/queue/resume.",
),
(
"torrent",
"TORRENT (magnet / .torrent)\n\n No daemon: DHT + trackers run inside xget, only while downloading.\n\n xget add \"magnet:?xt=urn:btih:...\" -o /tmp/ --seed 60\n xget add pack.torrent -o /tmp/ --files 0,2\n xget add https://example.com/f.iso.torrent -o /tmp/\n\n Single-file torrents land as a file, multi-file as a directory.\n -o <DIR> = shared folder; -o <FILE> renames a single-file torrent.\n\n --files <LIST>: e.g. 0,2,4-6 (indices from the list printed\n after metadata resolves). --seed <MIN>: seed after download (0 = stop).\n HTTP flags (--mirror, --no-auto-mirror, --http3, --speed-limit) are\n ignored for torrents. Pause/resume re-checks pieces and continues.",
),
(
"curl",
"REQUEST (curl parity)\n\n xget req <URL> - one HTTP request, like curl. Body goes to stdout\n unless -o <FILE> is given (-o /dev/null discards it).\n\n xget req https://example.com/f.bin > f.bin\n xget req -d 'a=1&b=2' https://h/echo\n xget req --json '{\"a\":1}' https://h/echo -H 'X-T: 1'\n xget req -I -L https://example.com/f.bin (headers only, follow)\n xget req -v https://h/ (request+response headers on stderr)\n xget req -u me:secret -b 'a=1' -c jar.txt https://h/\n xget req -x http://127.0.0.1:8080 -k https://self-signed/\n xget req --max-time 10 --max-redirs 3 -L https://h/x\n\n Non-http URLs (ftp/smtp/imap) are refused with a readable error.",
),
(
"refresh",
"LINK-REFRESH (expiring links)\n\n Some hosts give links valid ~30 s: the segment then gets\n 403/410 (or a body with `expired`). Save the source page:\n\n xget add <FILE-URL> --referer <PAGE-URL> [--selector STR] [--cookies S]\n\n On expiry xget GETs the source page (with cookies, redirects\n followed), extracts a fresh link with the SAME selector\n (empty = first http URL; `regex:` = plain needle), verifies\n size == total and continues Range from done (max 3 refreshes).\n\n Same flow on resume; records keep referer + selector.",
),
(
"hook",
"BROWSER-HOOK (send links to the queue)\n\n xget hook firefox # ~/.mozilla/native-messaging-hosts/xget.json\n xget hook chrome # ~/.config/google-chrome/NativeMessagingHosts/\n # (+ best-effort copy to chromium/)\n\n The manifest points at the xget binary (stdio). The queue endpoint\n lives on serve:\n\n xget serve /tmp/q -p 8484 # POST /link {\"url\": ...} -> queued\n curl -X POST localhost:8484/link -d '{\"url\": \"https://h/f.bin\"}'\n\n Bad URLs get 400 with a reason; good ones return {queued: id}.",
),
(
"captcha",
"CAPTCHA-HANDOFF (solve in browser, xget continues)\n\n Detection: g-recaptcha/recaptcha, cf-turnstile/turnstile,\n data-sitekey, or generic `captcha` in the source page.\n\n xget add <FILE-URL> --referer <PAGE-URL> --captcha auto\n [--captcha firefox|librewolf|zen|chrome|brave|edge|opera|vivaldi|helium] [--cookies 'a=1']\n\n Flow: source page shows captcha -> xdg-open in browser ->\n wait up to 5 min -> adopt cookies from the profile\n (Firefox cookies.sqlite / Chromium Cookies: Netscape jar first,\n sqlite token-scan fallback) or a pasted final link ->\n continue with segments (Range from done, 8 MiB chunks).\n\n Chromium-family: chrome, chromium, ungoogled, brave, edge,\n opera, vivaldi, helium, arc, yandex.\n Firefox-family: firefox, librewolf, zen, waterfox, tor.\n Profiles are tried most-recently-used first (by Cookies mtime),\n so the browser you used last wins. Explicit --captcha <name>\n narrows to that family only.",
),
(
"hls",
"HLS AND DASH\n\n xget hls <PLAYLIST-URL> -o out.ts [-c N] [-x PROXY]\n\n Parses .m3u8 master and picks the best BANDWIDTH variant,\n then downloads media segments with the Range engine and\n concatenates init + segments into one file.\n Parses .mpd and picks the best Representation, then does\n the same for init + media segments.\n\n Encrypted streams (EXT-X-KEY, ContentProtection) stop with\n a readable error. Use a direct file URL in that case.",
),
(
"daemon",
"DAEMON (background queue owner)\n\n xget daemon start # background process on unix socket\n xget daemon status # pid, socket, record count\n xget daemon stop # shutdown and remove socket\n\n Socket: $XDG_RUNTIME_DIR/xget.sock (JSON-RPC, newline JSON).\n Methods: ping, list, status, add, pause, resume_state,\n complete, fail, remove, shutdown. State stays in the\n shared Store file, so CLI falls back to local when down.\n\n When running, add/pause/resume/list/status use the daemon\n for record updates, else they use the local Store directly.\n No web UI, no browser work.",
),
];
match page {
None => {
println!("xget guide pages:");
for (name, _) in PAGES {
println!(" xget guide {name}");
}
println!("\nFull flags per command: xget <COMMAND> --help");
}
Some(p) => {
let p = p.to_lowercase();
match PAGES.iter().find(|(n, _)| *n == p) {
Some((_, text)) => println!("{text}"),
None => {
println!("unknown help page: {p}");
println!("pages:");
for (name, _) in PAGES {
println!(" {name}");
}
bail!("unknown help page: {p}");
}
}
}
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn cmd_add(
url: String,
output: Option<PathBuf>,
connections: Option<usize>,
speed_limit: Option<String>,
retries: u32,
mirrors: Vec<String>,
no_auto_mirror: bool,
http3: bool,
seed: u64,
files: Option<String>,
delta: bool,
referer: Option<String>,
selector: Option<String>,
cookies: Option<String>,
captcha: Option<String>,
proxy: Option<String>,
) -> Result<()> {
if torrent::detect(&url).is_some() {
if delta {
bail!("--delta works with plain http(s) URLs only (not torrents)");
}
return cmd_add_torrent(
url,
output,
mirrors,
no_auto_mirror,
http3,
speed_limit,
retries,
seed,
files,
proxy.clone(),
)
.await;
}
if metalink_source(&url) {
if delta {
bail!("--delta works with plain http(s) URLs only (metalink verifies its own hash)");
}
return cmd_add_metalink(
url,
output,
connections,
speed_limit,
retries,
mirrors,
no_auto_mirror,
http3,
proxy,
)
.await;
}
if let Some(scheme) = remote_scheme(&url) {
if delta {
bail!("--delta works with plain http(s) URLs only (not {scheme}://)");
}
return cmd_add_remote(url, output, connections, speed_limit, retries, scheme, proxy).await;
}
if delta {
return cmd_add_delta(url, output, connections, speed_limit, retries, proxy).await;
}
validate_url(&url)?;
reject_dir_url(&url)?;
reject_media_page(&url).await?;
let cfg = Config::load()?;
let conns = cfg.effective_connections(connections);
let limit = match speed_limit {
Some(s) => parse_speed_limit(&s)?,
None => cfg.speed_limit_bps,
};
let out = resolve_output(&url, output, &cfg.download_dir)?;
let (id, via_daemon) = create_record(&url, &out, conns, Engine::Direct, mirrors.clone())?;
if let Ok(mut s) = Store::load() {
if let Some(r) = s.get_mut(id) {
r.referer = referer.clone();
r.link_selector = selector.clone();
let _ = s.save();
}
}
println!("xget #{id}: {url}");
if let Some(ref src) = referer {
println!(" source: {src} (link-refresh on 403/410/expired)");
}
println!(" target: {}", out.display());
println!(" connections: {conns} (ceiling; final mode picked by throttle probe)");
if !mirrors.is_empty() {
println!(" mirrors: {} (explicit)", mirrors.len());
for m in &mirrors {
println!(" - {m}");
}
}
if no_auto_mirror {
println!(" auto-mirror: disabled (--no-auto-mirror)");
} else {
let auto = downloader::auto_candidates(&url);
if !auto.is_empty() {
println!(
" auto-mirror: {} candidates (TTFB ranking before start)",
auto.len()
);
} else {
println!(" auto-mirror: no rule for this host");
}
}
if http3 {
println!(" http3: QUIC attempt (fallback to H2/1.1 without error)");
}
println!(
" limit: {}",
limit
.map(|b| format_speed(b as f64))
.unwrap_or_else(|| "none".into())
);
let started = Instant::now();
let opts = DownloadOptions {
connections: conns,
speed_limit_bps: limit,
retries,
mirrors: mirrors.clone(),
allow_h3: http3,
auto_mirror: !no_auto_mirror,
proxy: proxy.clone(),
};
if let Some(ref src) = referer {
let spec = crate::refresh::RefreshSpec {
source_page: src.clone(),
selector: selector.clone().unwrap_or_default(),
cookies: cookies.clone(),
};
if let Ok(html) = crate::refresh::fetch_source_html(&spec).await
&& let Some(kind) = crate::captcha::detect_captcha(&html)
{
println!(" captcha: {} detected on source page", kind.label());
println!(" handoff: opening {src} - solve it, xget waits up to 5 min");
crate::captcha::open_in_browser(src);
let browser = captcha.clone().unwrap_or_else(|| "auto".to_string());
match crate::captcha::wait_for_profile_cookies(
Some(&browser),
crate::captcha::HANDOFF_TIMEOUT,
)
.await
{
Ok(session) => {
println!(" handoff: session adopted, resuming with cookies");
match crate::captcha::download_with_cookies(&url, &out, &session, None).await {
Ok(n) => {
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Completed;
r.error = None;
r.total_bytes = Some(n);
r.downloaded = n;
}
store.save()?;
println!(
"xget #{id}: Completed: {} (captcha handoff, {})",
format_bytes(n),
format_duration_precise(started.elapsed().as_secs_f64())
);
return Ok(());
}
Err(e) => bail!("xget #{id}: captcha handoff download failed: {e:#}"),
}
}
Err(e) => bail!("xget #{id}: captcha not solved: {e:#}"),
}
}
}
let res = via_http(&url, &out, &opts).await;
match res {
Ok(sum) => {
let wall = started.elapsed().as_secs_f64();
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Completed;
r.error = None;
r.total_bytes = Some(sum.total_bytes);
r.downloaded = sum.total_bytes;
let known: std::collections::HashSet<&str> =
mirrors.iter().map(String::as_str).collect();
r.auto_mirrors = sum
.mirrors
.iter()
.filter(|m| !known.contains(m.as_str()))
.cloned()
.collect();
if r.mirrors.is_empty() && !sum.mirrors.is_empty() {
r.auto_mirrors = sum.mirrors.clone();
}
}
store.save()?;
if via_daemon {
crate::daemon::daemon_complete(id, sum.total_bytes);
println!("xget #{id}: {} [daemon]", sum.report());
} else {
println!("xget #{id}: {}", sum.report());
}
println!(" file: {}", out.display());
if !sum.mirrors.is_empty() {
println!(
" sources: {} (+{} auto)",
1 + sum.mirrors.len(),
sum.mirrors.len()
);
for m in &sum.mirrors {
println!(" + {m}");
}
}
println!(
" time: {} (wall: {})",
format_duration_precise(sum.elapsed_secs),
format_duration_precise(wall)
);
println!(" avg speed: {}", format_speed(sum.avg_bps));
Ok(())
}
Err(e) => {
let mut store = Store::load()?;
if e.to_string() == "__XGET_PAUSED__" {
if let Some(r) = store.get_mut(id) {
r.status = Status::Paused;
r.error = None;
}
store.save()?;
println!("xget #{id}: paused - resume with `xget resume {id}`");
return Ok(());
}
let msg = e.to_string();
let paused_like = msg.contains("Ctrl-C");
if !paused_like && referer.is_some() && crate::refresh::is_expired_error(&msg) {
let spec = crate::refresh::RefreshSpec {
source_page: referer.clone().unwrap(),
selector: selector.clone().unwrap_or_default(),
cookies: cookies.clone(),
};
let (tot, done) = read_progress(&out, &url);
if let Some(t) = tot.or_else(|| std::fs::metadata(&out).ok().map(|m| m.len())) {
match crate::refresh::refresh_url_verified(&spec, t).await {
Ok(fresh) if fresh != url => {
eprintln!(" refresh: link expired ({msg}) -> {fresh}");
let res2 = via_http(&fresh, &out, &opts).await;
match res2 {
Ok(sum2) => {
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Completed;
r.error = None;
r.url = fresh.clone();
r.total_bytes = Some(sum2.total_bytes);
r.downloaded = sum2.total_bytes;
}
store.save()?;
println!("xget #{id}: {} (after link-refresh)", sum2.report());
println!(" file: {}", out.display());
return Ok(());
}
Err(e2) => {
let msg2 = format!("{msg}; refresh {fresh} failed: {e2}");
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Failed;
r.error = Some(msg2.clone());
r.downloaded = done;
}
store.save()?;
bail!("xget #{id}: download failed: {msg2}");
}
}
}
Ok(_) => {}
Err(re) => {
eprintln!(" refresh: failed ({re})");
}
}
}
}
let paused_like = msg.contains("Ctrl-C");
if let Some(r) = store.get_mut(id) {
r.status = if paused_like {
Status::Paused
} else {
Status::Failed
};
r.error = Some(msg.clone());
let (tot, done) = read_progress(&out, &url);
if tot.is_some() {
r.total_bytes = tot;
}
r.downloaded = done;
}
store.save()?;
if paused_like {
println!("xget #{id}: {msg}");
return Ok(());
}
bail!("xget #{id}: download failed: {msg}");
}
}
}
fn metalink_source(arg: &str) -> bool {
let lower = arg.to_lowercase();
if !(lower.ends_with(".metalink") || lower.ends_with(".meta4")) {
return false;
}
if Path::new(arg).exists() {
return true;
}
url::Url::parse(arg).is_ok_and(|u| u.scheme() == "http" || u.scheme() == "https")
}
fn sanitize_remote_name(name: &str) -> String {
let n: String = name
.chars()
.map(|c| {
if matches!(c, '/' | '\\' | '\0') {
'_'
} else {
c
}
})
.collect();
let n = n.trim();
if n.is_empty() || n == "." || n == ".." {
"download.bin".into()
} else {
n.into()
}
}
async fn cmd_add_remote(
url: String,
output: Option<PathBuf>,
connections: Option<usize>,
speed_limit: Option<String>,
retries: u32,
scheme: &'static str,
proxy: Option<String>,
) -> Result<()> {
match scheme {
"ftp" => inputs::FtpInput::parse(&url).map(|_| ())?,
"sftp" => inputs::SftpInput::parse(&url).map(|_| ())?,
"s3" => inputs::S3Input::parse(&url).map(|_| ())?,
"ipfs" => inputs::IpfsInput::parse(&url).map(|_| ())?,
"webdav" | "webdavs" => inputs::WebdavInput::parse(&url).map(|_| ())?,
_ => bail!("not an ftp/sftp/s3/ipfs/webdav URL: {url}"),
};
let cfg = Config::load()?;
let conns = cfg.effective_connections(connections);
let limit = match speed_limit {
Some(s) => parse_speed_limit(&s)?,
None => cfg.speed_limit_bps,
};
let out = resolve_output(&url, output, &cfg.download_dir)?;
let (id, via_daemon) = create_record(&url, &out, conns, Engine::Direct, Vec::new())?;
if via_daemon {
println!("xget #{id}: {url} [daemon]");
} else {
println!("xget #{id}: {url}");
}
println!(
" engine: {scheme} ({})",
match scheme {
"ftp" => "PASV, REST resume",
"sftp" => "ssh, key ~/.ssh or password",
"s3" => "SigV4, Range",
"webdav" | "webdavs" => "PROPFIND list, GET Range",
_ => "gateway :8080 albo publiczny",
}
);
println!(" target: {}", out.display());
println!(
" limit: {}",
limit
.map(|b| format_speed(b as f64))
.unwrap_or_else(|| "none".into())
);
let started = Instant::now();
let opts = DownloadOptions {
connections: conns,
speed_limit_bps: limit,
retries,
mirrors: Vec::new(),
allow_h3: false,
auto_mirror: false,
proxy,
};
let res = via_remote(&url, &out, &opts).await;
match res {
Ok(sum) => {
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Completed;
r.error = None;
r.total_bytes = Some(sum.total_bytes);
r.downloaded = sum.total_bytes;
}
store.save()?;
println!("xget #{id}: {}", sum.report());
println!(" file: {}", out.display());
println!(
" time: {} (wall: {})",
format_duration_precise(sum.elapsed_secs),
format_duration_precise(started.elapsed().as_secs_f64())
);
Ok(())
}
Err(e) => {
let mut store = Store::load()?;
if e.to_string() == "__XGET_PAUSED__" {
if let Some(r) = store.get_mut(id) {
r.status = Status::Paused;
r.error = None;
}
store.save()?;
println!("xget #{id}: paused - resume with `xget resume {id}`");
return Ok(());
}
let msg = e.to_string();
let paused_like = msg.contains("Ctrl-C");
if let Some(r) = store.get_mut(id) {
r.status = if paused_like {
Status::Paused
} else {
Status::Failed
};
r.error = Some(msg.clone());
let (tot, done) = read_progress(&out, &url);
if tot.is_some() {
r.total_bytes = tot;
}
r.downloaded = done;
}
store.save()?;
if paused_like {
println!("xget #{id}: {msg}");
return Ok(());
}
bail!("xget #{id}: download failed: {msg}");
}
}
}
#[allow(clippy::too_many_arguments)]
async fn cmd_add_metalink(
url: String,
output: Option<PathBuf>,
connections: Option<usize>,
speed_limit: Option<String>,
retries: u32,
mirrors: Vec<String>,
no_auto_mirror: bool,
http3: bool,
proxy: Option<String>,
) -> Result<()> {
let ml_input = inputs::MetalinkInput::new(url.clone());
let ml = ml_input.load().await?;
if ml.urls.is_empty() {
bail!("metalink has no http(s) URLs: {url}");
}
let cfg = Config::load()?;
let conns = cfg.effective_connections(connections);
let limit = match speed_limit {
Some(s) => parse_speed_limit(&s)?,
None => cfg.speed_limit_bps,
};
let out = match output {
Some(p) if p.is_dir() => p.join(sanitize_remote_name(&ml.name)),
Some(p) => p,
None => cfg.download_dir.join(sanitize_remote_name(&ml.name)),
};
let mut store = Store::load()?;
let id = store.add(
url.clone(),
out.clone(),
conns,
Engine::Direct,
mirrors.clone(),
0,
None,
None,
);
set_status(&mut store, id, Status::Downloading, None);
println!("xget #{id}: {url}");
println!(
" engine: metalink ({} mirror(s){})",
ml.urls.len(),
ml.size.map(|s| format!(", {s} bytes")).unwrap_or_default()
);
println!(" target: {}", out.display());
println!(" file: {} (primary)", ml.urls[0]);
for m in ml.urls.iter().skip(1) {
println!(" + {m}");
}
let started = Instant::now();
let op = engine::Operation::Download(engine::DownloadParams {
connections: conns,
speed_limit_bps: limit,
retries,
mirrors: mirrors.clone(),
allow_h3: http3,
auto_mirror: !no_auto_mirror,
proxy,
});
let res = engine::run_input(&ml_input, &op, &engine::Output::File(out.clone())).await;
match res {
Ok(sum) => {
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Completed;
r.error = None;
r.total_bytes = Some(sum.total_bytes);
r.downloaded = sum.total_bytes;
}
store.save()?;
println!("xget #{id}: {}", sum.report());
println!(" file: {}", out.display());
if ml.sha256.is_some() {
println!(" hash: sha256 ok");
}
println!(
" time (wall): {}",
format_duration_precise(started.elapsed().as_secs_f64())
);
Ok(())
}
Err(e) => {
let mut store = Store::load()?;
if e.to_string() == "__XGET_PAUSED__" {
if let Some(r) = store.get_mut(id) {
r.status = Status::Paused;
r.error = None;
}
store.save()?;
println!("xget #{id}: paused - resume with `xget resume {id}`");
return Ok(());
}
let msg = e.to_string();
let paused_like = msg.contains("Ctrl-C");
if let Some(r) = store.get_mut(id) {
r.status = if paused_like {
Status::Paused
} else {
Status::Failed
};
r.error = Some(msg.clone());
let (tot, done) = read_progress(&out, &ml.urls[0]);
if tot.is_some() {
r.total_bytes = tot;
}
r.downloaded = done;
}
store.save()?;
if paused_like {
println!("xget #{id}: {msg}");
return Ok(());
}
bail!("xget #{id}: download failed: {msg}");
}
}
}
async fn cmd_add_delta(
url: String,
output: Option<PathBuf>,
connections: Option<usize>,
speed_limit: Option<String>,
retries: u32,
proxy: Option<String>,
) -> Result<()> {
validate_url(&url)?;
reject_dir_url(&url)?;
reject_media_page(&url).await?;
let cfg = Config::load()?;
let conns = cfg.effective_connections(connections);
let limit = match speed_limit {
Some(s) => parse_speed_limit(&s)?,
None => cfg.speed_limit_bps,
};
let out = resolve_output(&url, output, &cfg.download_dir)?;
let (id, _via_daemon) = create_record(&url, &out, conns, Engine::Direct, Vec::new())?;
if _via_daemon {
println!("xget #{id}: {url} [daemon]");
} else {
println!("xget #{id}: {url}");
}
println!(" engine: delta (bloki z .xget-zsync, reszta Range)");
println!(" target: {}", out.display());
let started = Instant::now();
let dopts = DownloadOptions {
connections: conns,
speed_limit_bps: limit,
retries,
mirrors: vec![],
allow_h3: false,
auto_mirror: false,
proxy,
};
let res = crate::delta::delta_download(&url, &out, &dopts).await;
match res {
Ok(sum) => {
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Completed;
r.error = None;
r.total_bytes = Some(sum.total_bytes);
r.downloaded = sum.total_bytes;
}
store.save()?;
println!("xget #{id}: {}", sum.report());
println!(" file: {}", out.display());
println!(
" time (wall): {}",
format_duration_precise(started.elapsed().as_secs_f64())
);
Ok(())
}
Err(e) => {
let mut store = Store::load()?;
if e.to_string() == "__XGET_PAUSED__" {
if let Some(r) = store.get_mut(id) {
r.status = Status::Paused;
r.error = None;
}
store.save()?;
println!("xget #{id}: paused - resume with `xget resume {id}`");
return Ok(());
}
let msg = e.to_string();
let paused_like = msg.contains("Ctrl-C");
if let Some(r) = store.get_mut(id) {
r.status = if paused_like {
Status::Paused
} else {
Status::Failed
};
r.error = Some(msg.clone());
let (tot, done) = read_progress(&out, &url);
if tot.is_some() {
r.total_bytes = tot;
}
r.downloaded = done;
}
store.save()?;
if paused_like {
println!("xget #{id}: {msg}");
return Ok(());
}
bail!("xget #{id}: download failed: {msg}");
}
}
}
#[allow(clippy::too_many_arguments)]
async fn cmd_add_torrent(
url: String,
output: Option<PathBuf>,
mirrors: Vec<String>,
no_auto_mirror: bool,
http3: bool,
speed_limit: Option<String>,
_retries: u32,
seed: u64,
files: Option<String>,
proxy: Option<String>,
) -> Result<()> {
let source = torrent::detect(&url)
.context("not a torrent input (need magnet:? or a .torrent file/URL)")?;
let only_files = match files {
Some(spec) => Some(torrent::parse_file_list(&spec, usize::MAX)?),
None => None,
};
if !mirrors.is_empty() || no_auto_mirror || http3 || speed_limit.is_some() {
eprintln!(
" note: HTTP-only flags (--mirror, --no-auto-mirror, --http3, --speed-limit) are ignored for torrents"
);
}
let cfg = Config::load()?;
let conns = cfg.effective_connections(None);
let folder = torrent::session_folder_for(output.as_deref(), &cfg.download_dir);
let mut store = Store::load()?;
let id = store.add(
url.clone(),
folder.clone(),
conns,
Engine::Torrent,
Vec::new(),
seed,
only_files.clone(),
Some(folder.clone()),
);
set_status(&mut store, id, Status::Downloading, None);
println!("xget #{id}: {url}");
println!(" engine: torrent (librqbit: DHT + trackers, no daemon)");
println!(
" target: {} (exact path after metadata)",
folder.display()
);
if only_files.is_some() {
println!(" files: selected subset (validated after metadata)");
}
println!(
" seeding: {}",
if seed > 0 {
format!("{seed} min after download")
} else {
"off (stop right after download)".into()
}
);
let opts = torrent::TorrentOptions {
seed_minutes: seed,
only_files,
proxy: proxy.clone(),
};
let res = via_torrent(&source, output.clone(), &cfg.download_dir, &opts).await;
match res {
Ok(done) => {
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Completed;
r.error = None;
r.output = done.final_path.to_string_lossy().to_string();
r.total_bytes = Some(done.total_bytes);
r.downloaded = done.total_bytes;
}
store.save()?;
println!(
"xget #{id}: Completed: {} in {} (avg. {})",
format_bytes(done.total_bytes),
format_duration_precise(done.summary.elapsed_secs),
format_speed(done.summary.avg_bps)
);
println!(" file: {}", done.final_path.display());
println!(" torrent: {} ({} file(s))", done.name, done.files.len());
Ok(())
}
Err(e) => {
let mut store = Store::load()?;
if e.to_string() == "__XGET_PAUSED__" {
if let Some(r) = store.get_mut(id) {
r.status = Status::Paused;
r.error = None;
}
store.save()?;
println!("xget #{id}: paused - resume with `xget resume {id}`");
return Ok(());
}
let msg = e.to_string();
let paused_like = msg.contains("Ctrl-C");
if let Some(r) = store.get_mut(id) {
r.status = if paused_like {
Status::Paused
} else {
Status::Failed
};
r.error = Some(msg.clone());
let have = torrent::disk_usage(&folder);
r.downloaded = have;
}
store.save()?;
if paused_like {
println!("xget #{id}: {msg}");
return Ok(());
}
bail!("xget #{id}: download failed: {msg}");
}
}
}
fn cmd_list() -> Result<()> {
if crate::daemon::daemon_active() {
if let Some(resp) = crate::daemon::rpc_block("list", serde_json::json!({})) {
if resp.get("error").is_none() {
let records: Vec<Record> = resp
.get("result")
.and_then(|r| r.get("records"))
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_default();
if records.is_empty() {
println!("No downloads. Add the first one: xget add <url>");
return Ok(());
}
println!(
"{:<5} {:<8} {:>12} {:<32} URL",
"ID", "STATUS", "SIZE", "FILE"
);
println!("{}", "-".repeat(100));
for r in &records {
let size = match r.total_bytes {
Some(t) => format_bytes(t),
None => "?".to_string(),
};
let file = Path::new(&r.output)
.file_name()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_else(|| r.output.clone());
let url_short = if r.url.len() > 52 {
format!("{}...", &r.url[..52])
} else {
r.url.clone()
};
let extra = r
.error
.as_ref()
.map(|e| format!(" ({e})"))
.unwrap_or_default();
println!(
"{:<5} {:<8} {:>12} {:<32} {}{} [daemon]",
r.id,
r.status.label(),
size,
truncate(&file, 32),
url_short,
extra
);
}
return Ok(());
}
}
}
let store = Store::load()?;
let all = store.all();
if all.is_empty() {
println!("No downloads. Add the first one: xget add <url>");
return Ok(());
}
println!(
"{:<5} {:<8} {:>12} {:<32} URL",
"ID", "STATUS", "SIZE", "FILE"
);
println!("{}", "-".repeat(100));
for r in all {
let size = match r.total_bytes {
Some(t) => format_bytes(t),
None => "?".to_string(),
};
let file = Path::new(&r.output)
.file_name()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_else(|| r.output.clone());
let url_short = if r.url.len() > 52 {
format!("{}...", &r.url[..52])
} else {
r.url.clone()
};
let extra = r
.error
.as_ref()
.map(|e| format!(" ({e})"))
.unwrap_or_default();
println!(
"{:<5} {:<8} {:>12} {:<32} {}{}",
r.id,
r.status.label(),
size,
truncate(&file, 32),
url_short,
extra
);
}
Ok(())
}
fn truncate(s: &str, max: usize) -> String {
if s.len() <= max {
s.to_string()
} else {
format!("{}...", &s[..max.saturating_sub(3)])
}
}
fn cmd_pause(id: u32) -> Result<()> {
let via_daemon = crate::daemon::daemon_active()
&& crate::daemon::rpc_block("pause", serde_json::json!({"id": id}))
.is_some_and(|v| v.get("error").is_none());
let mut store = Store::load()?;
let rec = store
.get_mut(id)
.with_context(|| format!("no such download with id {id}"))?;
if rec.status == Status::Completed {
println!("xget #{id}: already completed, nothing to pause.");
return Ok(());
}
rec.status = Status::Paused;
rec.error = None;
let out = PathBuf::from(rec.output.clone());
let engine = rec.engine();
let tdir = rec.torrent_dir.clone();
store.save()?;
if engine == Engine::Torrent {
let dir = tdir.map(PathBuf::from).unwrap_or_else(|| {
if out.is_dir() {
out.clone()
} else {
out.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| PathBuf::from("."))
}
});
let _ = std::fs::create_dir_all(&dir);
let _ = std::fs::write(torrent::torrent_sentinel(&dir), b"pause");
}
let _ = std::fs::write(pause_sentinel(&out), b"pause");
if via_daemon {
println!("xget #{id}: paused via daemon. Resume with `xget resume {id}`.");
} else {
println!("xget #{id}: paused. Resume with `xget resume {id}`.");
}
Ok(())
}
async fn cmd_resume(
id: u32,
connections: Option<usize>,
mirrors: Vec<String>,
no_auto_mirror: bool,
http3: bool,
seed: Option<u64>,
proxy: Option<String>,
) -> Result<()> {
let cfg = Config::load()?;
let (url, out, conns, limit, engine, use_mirrors, seed_min, only_files) = {
let mut store = Store::load()?;
let (url, output, prev_conns, prev_engine, prev_mirrors, prev_seed, prev_files) = {
let rec = store
.get_mut(id)
.with_context(|| format!("no such download with id {id}"))?;
if rec.status == Status::Completed {
println!("xget #{id}: already completed.");
return Ok(());
}
(
rec.url.clone(),
rec.output.clone(),
rec.connections,
rec.engine(),
rec.mirrors.clone(),
rec.seed_minutes,
rec.torrent_files.clone(),
)
};
let conns = cfg.effective_connections(connections.or(Some(prev_conns)));
let use_mirrors = if mirrors.is_empty() {
prev_mirrors
} else {
mirrors
};
if let Some(rec) = store.get_mut(id) {
rec.connections = conns;
rec.status = Status::Downloading;
rec.error = None;
rec.mirrors = use_mirrors.clone();
if prev_engine == Engine::Torrent
&& let Some(s) = seed
{
rec.seed_minutes = s;
}
}
store.save()?;
(
url,
PathBuf::from(output),
conns,
cfg.speed_limit_bps,
prev_engine,
use_mirrors,
seed.unwrap_or(prev_seed),
prev_files,
)
};
if metalink_source(&url) {
return cmd_resume_metalink(id, url, out, use_mirrors, proxy).await;
}
if engine == Engine::Torrent {
return cmd_resume_torrent(id, url, out, seed_min, only_files, proxy).await;
}
if remote_scheme(&url).is_some() {
println!(
"xget #{id}: resuming ({conns} connections) -> {}",
out.display()
);
let started = Instant::now();
let opts = DownloadOptions {
connections: conns,
speed_limit_bps: limit,
retries: 5,
mirrors: Vec::new(),
allow_h3: false,
auto_mirror: false,
proxy: proxy.clone(),
};
let res = via_remote(&url, &out, &opts).await;
match res {
Ok(sum) => {
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Completed;
r.error = None;
r.total_bytes = Some(sum.total_bytes);
r.downloaded = sum.total_bytes;
}
store.save()?;
println!("xget #{id}: {}", sum.report());
println!(
" time (wall): {}",
format_duration_precise(started.elapsed().as_secs_f64())
);
return Ok(());
}
Err(e) => {
if e.to_string() == "__XGET_PAUSED__" {
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Paused;
}
store.save()?;
println!("xget #{id}: paused.");
return Ok(());
}
let msg = e.to_string();
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = if msg.contains("Ctrl-C") {
Status::Paused
} else {
Status::Failed
};
r.error = Some(msg.clone());
let (tot, done) = read_progress(&out, &url);
if tot.is_some() {
r.total_bytes = tot;
}
r.downloaded = done;
}
store.save()?;
bail!("xget #{id}: {msg}");
}
}
}
if is_media_url(&url) {
let mut store = Store::load()?;
let msg = media_rejection_msg(&url);
if let Some(r) = store.get_mut(id) {
r.status = Status::Failed;
r.error = Some(msg.clone());
}
let _ = store.save();
bail!("{msg}");
}
reject_dir_url(&url)?;
let use_delta = crate::delta::control_matches(&out, &url);
println!(
"xget #{id}: resuming ({conns} connections{}) -> {}",
if use_delta { ", delta" } else { "" },
out.display()
);
let started = Instant::now();
let opts = DownloadOptions {
connections: conns,
speed_limit_bps: limit,
retries: 5,
mirrors: use_mirrors,
allow_h3: http3,
auto_mirror: !no_auto_mirror,
proxy: proxy.clone(),
};
let res = if use_delta {
let ds = crate::delta::delta_download(&url, &out, &opts)
.await
.map(|s| downloader::Summary {
total_bytes: s.total_bytes,
elapsed_secs: s.elapsed_secs,
avg_bps: s.avg_bps,
mirrors: s.mirrors,
});
match ds {
Ok(s) => Ok(s),
Err(_) => via_http(&url, &out, &opts).await,
}
} else {
via_http(&url, &out, &opts).await
};
match res {
Ok(sum) => {
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Completed;
r.error = None;
r.total_bytes = Some(sum.total_bytes);
r.downloaded = sum.total_bytes;
let known: std::collections::HashSet<&str> =
r.mirrors.iter().map(String::as_str).collect();
r.auto_mirrors = sum
.mirrors
.iter()
.filter(|m| !known.contains(m.as_str()))
.cloned()
.collect();
}
store.save()?;
println!("xget #{id}: {}", sum.report());
println!(
" time (wall): {}",
format_duration_precise(started.elapsed().as_secs_f64())
);
Ok(())
}
Err(e) => {
if e.to_string() == "__XGET_PAUSED__" {
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Paused;
}
store.save()?;
println!("xget #{id}: paused.");
return Ok(());
}
let msg = e.to_string();
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = if msg.contains("Ctrl-C") {
Status::Paused
} else {
Status::Failed
};
r.error = Some(msg.clone());
let (tot, done) = read_progress(&out, &url);
if tot.is_some() {
r.total_bytes = tot;
}
r.downloaded = done;
}
store.save()?;
bail!("xget #{id}: {msg}");
}
}
}
async fn cmd_resume_metalink(
id: u32,
url: String,
out: PathBuf,
mirrors: Vec<String>,
proxy: Option<String>,
) -> Result<()> {
let cfg = Config::load()?;
let ml_input = inputs::MetalinkInput::new(url.clone());
let ml = ml_input.load().await?;
println!("xget #{id}: resuming metalink -> {}", out.display());
let started = Instant::now();
let op = engine::Operation::Download(engine::DownloadParams {
connections: cfg.effective_connections(None),
speed_limit_bps: cfg.speed_limit_bps,
retries: 5,
mirrors,
allow_h3: false,
auto_mirror: true,
proxy,
});
let res = engine::run_input(&ml_input, &op, &engine::Output::File(out.clone())).await;
match res {
Ok(sum) => {
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Completed;
r.error = None;
r.total_bytes = Some(sum.total_bytes);
r.downloaded = sum.total_bytes;
}
store.save()?;
println!("xget #{id}: {}", sum.report());
println!(
" time (wall): {}",
format_duration_precise(started.elapsed().as_secs_f64())
);
if ml.sha256.is_some() {
println!(" hash: sha256 ok");
}
Ok(())
}
Err(e) => {
if e.to_string() == "__XGET_PAUSED__" {
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Paused;
}
store.save()?;
println!("xget #{id}: paused.");
return Ok(());
}
let msg = e.to_string();
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = if msg.contains("Ctrl-C") {
Status::Paused
} else {
Status::Failed
};
r.error = Some(msg.clone());
if let Some(first) = ml.urls.first() {
let (tot, done) = read_progress(&out, first);
if tot.is_some() {
r.total_bytes = tot;
}
r.downloaded = done;
}
}
store.save()?;
bail!("xget #{id}: {msg}");
}
}
}
async fn cmd_resume_torrent(
id: u32,
url: String,
out: PathBuf,
seed: u64,
only_files: Option<Vec<usize>>,
proxy: Option<String>,
) -> Result<()> {
let source = torrent::detect(&url)
.context("stored torrent input no longer recognized (need magnet:? or .torrent)")?;
let cfg = Config::load()?;
println!("xget #{id}: resuming torrent -> {}", out.display());
let res = via_torrent(
&source,
Some(out.clone()),
&cfg.download_dir,
&torrent::TorrentOptions {
seed_minutes: seed,
only_files,
proxy,
},
)
.await;
match res {
Ok(done) => {
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Completed;
r.error = None;
r.output = done.final_path.to_string_lossy().to_string();
r.total_bytes = Some(done.total_bytes);
r.downloaded = done.total_bytes;
}
store.save()?;
println!(
"xget #{id}: Completed: {} (avg. {})",
format_bytes(done.total_bytes),
format_speed(done.summary.avg_bps)
);
println!(" file: {}", done.final_path.display());
println!(" torrent: {} ({} file(s))", done.name, done.files.len());
Ok(())
}
Err(e) => {
if e.to_string() == "__XGET_PAUSED__" {
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = Status::Paused;
}
store.save()?;
println!("xget #{id}: paused.");
return Ok(());
}
let msg = e.to_string();
let mut store = Store::load()?;
if let Some(r) = store.get_mut(id) {
r.status = if msg.contains("Ctrl-C") {
Status::Paused
} else {
Status::Failed
};
r.error = Some(msg.clone());
r.downloaded = torrent::disk_usage(&out);
}
store.save()?;
bail!("xget #{id}: {msg}");
}
}
}
fn cmd_remove(id: u32, delete_files: bool) -> Result<()> {
let via_daemon_rec: Option<Record> = None;
let mut via_daemon_rec = via_daemon_rec;
if crate::daemon::daemon_active() {
if let Some(resp) = crate::daemon::rpc_block("status", serde_json::json!({"id": id})) {
if resp.get("error").is_none() {
if let Some(arr) = resp.get("result").and_then(|r| r.get("records")).and_then(|v| v.as_array()) {
if let Some(first) = arr.first() {
via_daemon_rec = serde_json::from_value(first.clone()).ok();
}
}
}
}
if let Some(rec) = via_daemon_rec.clone() {
let rm = crate::daemon::rpc_block("remove", serde_json::json!({"id": id}));
if rm.is_some_and(|v| v.get("error").is_none()) {
cleanup_record_files(&rec, delete_files);
if delete_files {
println!("xget #{id}: removed record and files via daemon.");
} else {
println!("xget #{id}: removed record via daemon (files left on disk).");
}
return Ok(());
}
}
}
let mut store = Store::load()?;
let rec = store
.remove(id)
.with_context(|| format!("no such download with id {id}"))?;
store.save()?;
cleanup_record_files(&rec, delete_files);
if delete_files {
println!("xget #{id}: removed record and files.");
} else {
println!("xget #{id}: removed record (files left on disk).");
}
Ok(())
}
fn cleanup_record_files(rec: &Record, delete_files: bool) -> bool {
if !delete_files {
return false;
}
let out = PathBuf::from(&rec.output);
if rec.engine() == Engine::Torrent {
let tdir = rec.torrent_dir.clone().map(PathBuf::from);
let shared_root = tdir.as_ref().is_some_and(|d| d == &out);
if shared_root {
if let Some((_, name)) = torrent::read_sidecar(&out, &rec.url) {
let cand = out.join(&name);
if cand != out {
if cand.is_dir() {
let _ = std::fs::remove_dir_all(&cand);
} else {
let _ = std::fs::remove_file(&cand);
}
}
}
} else if out.is_dir() {
let _ = std::fs::remove_dir_all(&out);
} else {
let _ = std::fs::remove_file(&out);
}
if let Some(d) = tdir {
let _ = std::fs::remove_file(torrent::torrent_sentinel(&d));
let _ = std::fs::remove_file(torrent::torrent_meta_file(&d));
}
let _ = std::fs::remove_file(pause_sentinel(&out));
} else {
for p in [
out.clone(),
part_path(&out),
meta_path(&out),
pause_sentinel(&out),
] {
if p.exists() {
if p.is_dir() {
let _ = std::fs::remove_dir_all(&p);
} else {
let _ = std::fs::remove_file(&p);
}
}
}
}
true
}
fn cmd_status(id: Option<u32>) -> Result<()> {
if crate::daemon::daemon_active() {
let params = match id {
Some(i) => serde_json::json!({"id": i}),
None => serde_json::json!({}),
};
if let Some(resp) = crate::daemon::rpc_block("status", params) {
if resp.get("error").is_none() {
let records: Vec<Record> = resp
.get("result")
.and_then(|r| r.get("records"))
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_default();
if records.is_empty() {
println!("No downloads.");
return Ok(());
}
print_status_records(&records, true);
return Ok(());
}
}
}
let store = Store::load()?;
let recs: Vec<&Record> = match id {
Some(i) => vec![
store
.get(i)
.with_context(|| format!("no such download with id {i}"))?,
],
None => store.all().iter().collect(),
};
if recs.is_empty() {
println!("No downloads.");
return Ok(());
}
let owned: Vec<Record> = recs.into_iter().cloned().collect();
print_status_records(&owned, false);
Ok(())
}
fn print_status_records(recs: &[Record], via_daemon: bool) -> bool {
for r in recs {
let out = PathBuf::from(&r.output);
let engine = r.engine();
let (total, live) = if engine == Engine::Torrent {
let dir = r
.torrent_dir
.as_deref()
.map(Path::new)
.unwrap_or(Path::new(&r.output));
match torrent::read_sidecar_progress(dir, &r.url) {
Some((t, _, d)) => (Some(t), d.min(t)),
None => {
let tot = r.total_bytes;
(tot, r.downloaded.min(tot.unwrap_or(u64::MAX)))
}
}
} else {
let (tot, live) = read_progress(&out, &r.url);
(tot.or(r.total_bytes), live)
};
let pct = match (total, live) {
(Some(t), _) if t > 0 => format!("{:.1}%", live as f64 / t as f64 * 100.0),
_ => "?".to_string(),
};
println!("xget #{} [{}]", r.id, r.status.label());
println!(" url: {}", r.url);
println!(" file: {}", r.output);
println!(" engine: {}", engine.label());
if engine == Engine::Torrent {
println!(
" seeding: {}",
if r.seed_minutes > 0 {
format!("{} min after download", r.seed_minutes)
} else {
"off".to_string()
}
);
if let Some(sel) = &r.torrent_files {
println!(" files: selected {:?}", sel);
}
}
println!(
" progress: {} / {} ({})",
format_bytes(live),
total.map(format_bytes).unwrap_or_else(|| "?".into()),
pct
);
println!(" connections: {}", r.connections);
if !r.mirrors.is_empty() || !r.auto_mirrors.is_empty() {
println!(
" sources: primary + {} ({} explicit, {} auto)",
r.mirrors.len() + r.auto_mirrors.len(),
r.mirrors.len(),
r.auto_mirrors.len()
);
println!(" primary: {}", r.url);
for m in r.mirrors.iter().chain(r.auto_mirrors.iter()) {
println!(" + {m}");
}
} else {
println!(" sources: primary only");
}
println!(" created: {}", r.created_at);
if let Some(e) = &r.error {
println!(" error: {e}");
}
let part = part_path(&out);
if part.exists() {
let sz = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
println!(" .part: {} ({})", part.display(), format_bytes(sz));
}
if via_daemon {
println!(" via: daemon socket {}", crate::daemon::socket_path().display());
}
}
true
}
#[allow(clippy::too_many_arguments)]
async fn cmd_queue(
mut urls: Vec<String>,
file: Option<PathBuf>,
concurrent: usize,
connections: Option<usize>,
output_dir: Option<PathBuf>,
speed_limit: Option<String>,
mirrors: Vec<String>,
no_auto_mirror: bool,
http3: bool,
seed: u64,
proxy: Option<String>,
) -> Result<()> {
if let Some(f) = file {
let raw = std::fs::read_to_string(&f)
.with_context(|| format!("could not read {}", f.display()))?;
for line in raw.lines() {
let t = line.trim();
if t.is_empty() || t.starts_with('#') {
continue;
}
urls.push(t.to_string());
}
}
if urls.is_empty() {
bail!("queue is empty - provide URLs or --file with a list");
}
let concurrent = concurrent.clamp(1, 16);
let cfg = Config::load()?;
let conns = cfg.effective_connections(connections);
let limit = match speed_limit {
Some(s) => parse_speed_limit(&s)?,
None => cfg.speed_limit_bps,
};
let dir = output_dir.unwrap_or(cfg.download_dir.clone());
let mut jobs: Vec<(u32, String, PathBuf, Engine)> = Vec::new();
{
let mut store = Store::load()?;
for u in &urls {
if torrent::detect(u).is_some() {
let folder = dir.clone();
let id = store.add(
u.clone(),
folder.clone(),
conns,
Engine::Torrent,
Vec::new(),
seed,
None,
Some(folder.clone()),
);
jobs.push((id, u.clone(), folder, Engine::Torrent));
continue;
}
if metalink_source(u) {
bail!(
"metalink in queue is not supported - use `xget add {u}` (mirrors + hash need a single target)"
);
}
if let Some(scheme) = remote_scheme(u) {
match scheme {
"ftp" => inputs::FtpInput::parse(u).map(|_| ())?,
"sftp" => inputs::SftpInput::parse(u).map(|_| ())?,
"s3" => inputs::S3Input::parse(u).map(|_| ())?,
"ipfs" => inputs::IpfsInput::parse(u).map(|_| ())?,
"webdav" | "webdavs" => inputs::WebdavInput::parse(u).map(|_| ())?,
_ => unreachable!(),
}
} else {
validate_url(u)?;
reject_dir_url(u)?;
if is_media_url(u) {
bail!("{}", media_rejection_msg(u));
}
}
let out = resolve_output(u, None, &dir)?;
let out = dedupe(
&out,
&jobs
.iter()
.map(|(_, _, p, _)| p.clone())
.collect::<Vec<_>>(),
);
let id = store.add(
u.clone(),
out.clone(),
conns,
Engine::Direct,
mirrors.clone(),
0,
None,
None,
);
jobs.push((id, u.clone(), out, Engine::Direct));
}
store.save()?;
}
println!(
"xget: queue of {} files, {} at a time, {} connections each.",
jobs.len(),
concurrent,
conns
);
let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(concurrent));
let mut handles = Vec::new();
for (id, url, out, engine) in jobs {
let sem = sem.clone();
let opts = DownloadOptions {
connections: conns,
speed_limit_bps: limit,
retries: 5,
mirrors: mirrors.clone(),
allow_h3: http3,
auto_mirror: !no_auto_mirror,
proxy: proxy.clone(),
};
let topts = torrent::TorrentOptions {
seed_minutes: seed,
only_files: None,
proxy: proxy.clone(),
};
handles.push(tokio::spawn(async move {
let _permit = sem.acquire_owned().await.unwrap();
{
let mut s = Store::load().unwrap();
set_status(&mut s, id, Status::Downloading, None);
}
if engine == Engine::Torrent {
let Some(src) = torrent::detect(&url) else {
let mut s = Store::load().unwrap();
if let Some(r) = s.get_mut(id) {
r.status = Status::Failed;
r.error = Some("stored torrent input no longer recognized".into());
}
let _ = s.save();
println!("xget #{id}: ERROR: stored torrent input no longer recognized");
return;
};
let res = via_torrent(&src, Some(out.clone()), &out, &topts).await;
match res {
Ok(done) => {
let mut s = Store::load().unwrap();
if let Some(r) = s.get_mut(id) {
r.status = Status::Completed;
r.error = None;
r.output = done.final_path.to_string_lossy().to_string();
r.total_bytes = Some(done.total_bytes);
r.downloaded = done.total_bytes;
}
let _ = s.save();
println!(
"xget #{id}: OK {} ({}, {} file(s))",
format_bytes(done.total_bytes),
done.name,
done.files.len()
);
}
Err(e) => {
let mut s = Store::load().unwrap();
if let Some(r) = s.get_mut(id) {
r.status = Status::Failed;
r.error = Some(e.to_string());
r.downloaded = torrent::disk_usage(&out);
}
let _ = s.save();
println!("xget #{id}: ERROR: {e}");
}
}
return;
}
if is_media_url(&url) {
let msg = media_rejection_msg(&url);
let mut s = Store::load().unwrap();
if let Some(r) = s.get_mut(id) {
r.status = Status::Failed;
r.error = Some(msg.clone());
}
let _ = s.save();
println!("xget #{id}: ERROR: {msg}");
return;
}
let started = Instant::now();
let res = if remote_scheme(&url).is_some() {
via_remote(&url, &out, &opts).await
} else {
via_http(&url, &out, &opts).await
};
match res {
Ok(sum) => {
let mut s = Store::load().unwrap();
if let Some(r) = s.get_mut(id) {
r.status = Status::Completed;
r.error = None;
r.total_bytes = Some(sum.total_bytes);
r.downloaded = sum.total_bytes;
let known: std::collections::HashSet<&str> =
r.mirrors.iter().map(String::as_str).collect();
r.auto_mirrors = sum
.mirrors
.iter()
.filter(|m| !known.contains(m.as_str()))
.cloned()
.collect();
}
let _ = s.save();
println!(
"xget #{id}: OK {} in {} (avg {})",
format_bytes(sum.total_bytes),
format_duration_precise(started.elapsed().as_secs_f64()),
format_speed(sum.avg_bps)
);
}
Err(e) => {
if e.to_string() == "__XGET_PAUSED__" {
let mut s = Store::load().unwrap();
if let Some(r) = s.get_mut(id) {
r.status = Status::Paused;
let (tot, done) = read_progress(&out, &url);
if tot.is_some() {
r.total_bytes = tot;
}
r.downloaded = done;
}
let _ = s.save();
println!("xget #{id}: paused.");
} else {
let mut s = Store::load().unwrap();
if let Some(r) = s.get_mut(id) {
r.status = Status::Failed;
r.error = Some(e.to_string());
let (tot, done) = read_progress(&out, &url);
if tot.is_some() {
r.total_bytes = tot;
}
r.downloaded = done;
}
let _ = s.save();
println!("xget #{id}: ERROR: {e}");
}
}
}
}));
}
for h in handles {
let _ = h.await;
}
println!("xget: queue finished. Check `xget list`.");
Ok(())
}
fn dedupe(out: &Path, taken: &[PathBuf]) -> PathBuf {
if !out.exists() && !taken.contains(&out.to_path_buf()) {
return out.to_path_buf();
}
for i in 1..1000 {
let cand = PathBuf::from(format!("{}.{}", out.display(), i));
if !cand.exists() && !taken.contains(&cand) {
return cand;
}
}
out.to_path_buf()
}
fn cmd_config(
show: bool,
connections: Option<usize>,
dir: Option<PathBuf>,
speed_limit: Option<String>,
tcp_tuning: bool,
yes: bool,
) -> Result<()> {
if tcp_tuning {
println!("{}", fafo::tcp_tuning_report());
if yes {
match fafo::apply_tcp_tuning() {
Ok(applied) => println!("Applied: {applied}"),
Err(e) => bail!("could not apply TCP tuning: {e}"),
}
} else {
println!("(preview - nothing changed; add `--yes` to apply)");
}
return Ok(());
}
if yes {
bail!("`--yes` only works with `--tcp-tuning`");
}
let mut cfg = Config::load()?;
let mut changed = false;
if let Some(c) = connections {
if !(1..=32).contains(&c) {
bail!("connections must be in range 1-32");
}
cfg.connections = c;
changed = true;
}
if let Some(d) = dir {
cfg.download_dir = d;
changed = true;
}
if let Some(s) = speed_limit {
cfg.speed_limit_bps = parse_speed_limit(&s)?;
changed = true;
}
if changed {
cfg.save()?;
println!("Saved configuration.");
}
if show || !changed {
println!("xget configuration:");
println!(" connections: {}", cfg.connections);
println!(" directory: {}", cfg.download_dir.display());
println!(
" speed limit: {}",
cfg.speed_limit_bps
.map(|b| format_speed(b as f64))
.unwrap_or_else(|| "none".into())
);
println!(" (plik: {})", config::config_path().display());
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn cmd_req(
url: String,
method: Option<String>,
headers: Vec<String>,
data: Vec<String>,
json: Option<String>,
output: Option<PathBuf>,
verbose: bool,
head: bool,
follow: bool,
max_redirs: usize,
silent: bool,
max_time: Option<f64>,
basic_auth: Option<String>,
cookie: Option<String>,
cookiejar: Option<PathBuf>,
proxy: Option<String>,
insecure: bool,
cert: Option<PathBuf>,
key: Option<PathBuf>,
user_agent: Option<String>,
referer: Option<String>,
) -> Result<()> {
let opts = request::ReqOptions {
method,
headers,
data,
json,
head,
follow,
max_redirs,
silent,
verbose,
max_time,
basic_auth,
cookie,
cookiejar,
proxy,
insecure,
cert,
key,
user_agent,
referer,
output,
};
via_req(&url, &opts).await
}
fn set_status(store: &mut Store, id: u32, st: Status, err: Option<String>) {
if let Some(r) = store.get_mut(id) {
r.status = st;
r.error = err;
}
let _ = store.save();
}
fn create_record(
url: &str,
out: &Path,
conns: usize,
kind: Engine,
mirrors: Vec<String>,
) -> Result<(u32, bool)> {
if crate::daemon::daemon_active() {
let k = if kind == Engine::Torrent { "torrent" } else { "direct" };
if let Some(id) = crate::daemon::daemon_create_record(url, &out.to_string_lossy(), conns, k) {
if let Ok(mut s) = Store::load() {
if let Some(r) = s.get_mut(id) {
r.mirrors = mirrors;
let _ = s.save();
}
}
return Ok((id, true));
}
}
let mut store = Store::load()?;
let id = store.add(url.to_string(), out.to_path_buf(), conns, kind, mirrors, 0, None, None);
set_status(&mut store, id, Status::Downloading, None);
Ok((id, false))
}
fn validate_url(url: &str) -> Result<()> {
let u = url::Url::parse(url).with_context(|| format!("invalid URL: {url}"))?;
if u.scheme() != "http" && u.scheme() != "https" {
bail!("only http(s) URLs supported: {url}");
}
Ok(())
}
fn is_dir_url(url: &str) -> bool {
url.split(['?', '#'])
.next()
.unwrap_or(url)
.trim_end()
.ends_with('/')
}
fn reject_dir_url(url: &str) -> Result<()> {
if is_dir_url(url) {
bail!(
"xget can't download a directory listing: {url}\nhint: point at a concrete file, or use a recursive fetcher:\n \u{2022} wget -r -np -nH --cut-dirs=N -P <dir> {url}\n \u{2022} lftp / aria2c with a file list"
);
}
Ok(())
}
const MEDIA_HOSTS: &[&str] = &[
"youtube.com",
"youtu.be",
"youtube-nocookie.com",
"instagram.com",
"tiktok.com",
"twitter.com",
"x.com",
"vimeo.com",
"facebook.com",
"fb.watch",
"twitch.tv",
"soundcloud.com",
"dailymotion.com",
"reddit.com",
"rumble.com",
"odysee.com",
];
fn is_media_url(url: &str) -> bool {
let lower = url.to_lowercase();
MEDIA_HOSTS.iter().any(|h| lower.contains(h))
}
fn media_rejection_msg(url: &str) -> String {
format!(
"looks like a page, not a file: {url}\nxget downloads files (direct file URL) and torrents, not pages or media (YouTube and similar).\nhint: paste a direct file link (e.g. .../film.mp4), not a player page address"
)
}
async fn reject_media_page(url: &str) -> Result<()> {
if is_media_url(url) {
bail!("{}", media_rejection_msg(url));
}
if let Ok(client) = reqwest::Client::builder()
.user_agent("xget/0.1 (+https://github.com/JustRoccat/xget)")
.connect_timeout(std::time::Duration::from_secs(10))
.timeout(std::time::Duration::from_secs(10))
.build()
&& let Ok(resp) =
tokio::time::timeout(std::time::Duration::from_secs(10), client.head(url).send()).await
&& let Ok(r) = resp
&& r.status().is_success()
&& let Some(ct) = r
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
{
let ct = ct.to_lowercase();
if ct.contains("text/html") || ct.contains("application/xhtml") {
bail!("{}", media_rejection_msg(url));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn youtube_url_gives_readable_error_instead_of_download() {
let urls = [
"https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"https://youtu.be/dQw4w9WgXcQ",
"https://www.youtube.com/shorts/dQw4w9WgXcQ",
"https://x.com/user/status/123",
"https://www.tiktok.com/@u/video/123",
];
for u in urls {
assert!(is_media_url(u), "expected media page: {u}");
let msg = media_rejection_msg(u);
assert!(
msg.contains("page"),
"readable page error, no download attempt: {msg}"
);
assert!(
msg.contains("not a file"),
"message must say it is not a file: {msg}"
);
assert!(
msg.contains("xget downloads files"),
"message must say what xget is: {msg}"
);
}
}
#[test]
fn direct_file_urls_are_not_media_pages() {
for u in [
"https://example.com/film.mp4",
"https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.9.tar.xz",
"https://example.com/download.bin?x=1",
] {
assert!(!is_media_url(u), "file must not be a page: {u}");
}
}
#[test]
fn dir_url_detection_still_works() {
assert!(is_dir_url("https://example.com/dir/"));
assert!(!is_dir_url("https://example.com/file.iso"));
}
}