use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
use indicatif::{ProgressBar, ProgressStyle};
use librqbit::{
AddTorrent, AddTorrentOptions, AddTorrentResponse, ConnectionOptions, DhtSessionConfig,
ListenerMode, ListenerOptions, PeerConnectionOptions, Session, SessionOptions,
};
use crate::config::format_bytes;
use crate::downloader::Summary;
const METADATA_TIMEOUT: Duration = Duration::from_secs(300);
const POLL_INTERVAL: Duration = Duration::from_millis(500);
#[derive(Debug, Clone)]
pub enum TorrentSource {
Magnet(String),
File(PathBuf),
RemoteUrl(String),
}
pub fn detect(input: &str) -> Option<TorrentSource> {
let t = input.trim();
if t.len() > 7 && t[..8].eq_ignore_ascii_case("magnet:?") {
return Some(TorrentSource::Magnet(t.to_string()));
}
if t.len() == 40 && t.chars().all(|c| c.is_ascii_hexdigit()) && !Path::new(t).exists() {
return Some(TorrentSource::Magnet(t.to_string()));
}
let p = Path::new(t);
if p.is_file() {
let lower = t.to_lowercase();
if lower.ends_with(".torrent") {
return Some(TorrentSource::File(p.to_path_buf()));
}
if std::fs::read(p)
.map(|b| is_torrent_bytes(&b))
.unwrap_or(false)
{
return Some(TorrentSource::File(p.to_path_buf()));
}
return None;
}
if let Ok(u) = url::Url::parse(t) {
let scheme = u.scheme().to_ascii_lowercase();
if (scheme == "http" || scheme == "https")
&& u.path().to_ascii_lowercase().ends_with(".torrent")
{
return Some(TorrentSource::RemoteUrl(t.to_string()));
}
}
None
}
fn is_torrent_bytes(b: &[u8]) -> bool {
b.starts_with(b"d") && parse_torrent_bytes(b).is_ok()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MagnetInfo {
pub info_hash: String,
pub name: Option<String>,
pub trackers: Vec<String>,
}
pub fn parse_magnet(uri: &str) -> Result<MagnetInfo> {
let m = librqbit::Magnet::parse(uri.trim()).context("invalid magnet link")?;
let info_hash = if let Some(id) = m.as_id20() {
id.as_string()
} else if let Some(id) = m.as_id32() {
id.as_string()
} else {
bail!("magnet link has no info hash");
};
Ok(MagnetInfo {
info_hash,
name: m.name.clone(),
trackers: m.trackers.clone(),
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TorrentFileEntry {
pub index: usize,
pub path: String,
pub len: u64,
}
#[derive(Debug, Clone)]
pub struct TorrentMeta {
pub info_hash: String,
pub name: String,
pub total_length: u64,
pub piece_length: u32,
pub files: Vec<TorrentFileEntry>,
}
impl TorrentMeta {
pub fn is_single_file(&self) -> bool {
self.files.len() <= 1
}
}
fn lossy(b: &[u8]) -> String {
String::from_utf8_lossy(b).into_owned()
}
pub fn parse_torrent_bytes(data: &[u8]) -> Result<TorrentMeta> {
if data.is_empty() || data.len() > 32 * 1024 * 1024 {
bail!("not a .torrent file (bad size)");
}
let t = librqbit::torrent_from_bytes(data)
.map_err(|e| anyhow::anyhow!("invalid .torrent: {e:?}"))?;
let info = &t.info.data;
let name = info
.name
.as_ref()
.map(|n| lossy(n.as_ref()))
.filter(|n| !n.is_empty())
.unwrap_or_else(|| "torrent".to_string());
let mut files = Vec::new();
if let Some(list) = info.files.as_ref() {
for (i, f) in list.iter().enumerate() {
let rel: Vec<String> = f.path.iter().map(|c| lossy(c.as_ref())).collect();
let mut full = rel.join("/");
if full.is_empty() {
full = name.clone();
} else if !name.is_empty() && name != "torrent" {
full = format!("{name}/{full}");
}
files.push(TorrentFileEntry {
index: i,
path: full,
len: f.length,
});
}
} else if let Some(len) = info.length {
files.push(TorrentFileEntry {
index: 0,
path: name.clone(),
len,
});
} else {
bail!("invalid .torrent: neither multi-file nor single-file length");
}
let total_length: u64 = files.iter().map(|f| f.len).sum();
if total_length == 0 {
bail!("invalid .torrent: zero total length");
}
Ok(TorrentMeta {
info_hash: t.info_hash.as_string(),
name,
total_length,
piece_length: info.piece_length,
files,
})
}
pub fn parse_file_list(spec: &str, nfiles: usize) -> Result<Vec<usize>> {
let mut out: Vec<usize> = Vec::new();
for tok in spec
.split([',', ' ', ';'])
.map(str::trim)
.filter(|s| !s.is_empty())
{
if let Some((a, b)) = tok.split_once('-') {
let lo: usize = a
.trim()
.parse()
.context(format!("bad file range: '{tok}'"))?;
let hi: usize = b
.trim()
.parse()
.context(format!("bad file range: '{tok}'"))?;
if lo > hi {
bail!("bad file range (reversed): '{tok}'");
}
if hi.saturating_sub(lo) > 100_000 {
bail!("file range too wide: '{tok}' (max 100000 entries)");
}
out.extend(lo..=hi);
} else {
out.push(tok.parse().context(format!("bad file index: '{tok}'"))?);
}
}
normalize_selection(out, nfiles)
}
pub fn select_files(nfiles: usize, only: Option<Vec<usize>>) -> Result<Vec<usize>> {
match only {
None => Ok((0..nfiles).collect()),
Some(v) => normalize_selection(v, nfiles),
}
}
fn normalize_selection(mut v: Vec<usize>, nfiles: usize) -> Result<Vec<usize>> {
if nfiles == 0 {
bail!("torrent has no files");
}
v.sort_unstable();
v.dedup();
if v.is_empty() {
bail!("empty file selection");
}
if let Some(&bad) = v.iter().find(|&&i| i >= nfiles) {
bail!(
"file index {bad} out of range (torrent has {nfiles} file(s), 0-{})",
nfiles - 1
);
}
Ok(v)
}
pub fn torrent_sentinel(dir: &Path) -> PathBuf {
dir.join(".xget-torrent.pause")
}
pub fn session_folder_for(output_opt: Option<&Path>, download_dir: &Path) -> PathBuf {
match output_opt {
None => download_dir.to_path_buf(),
Some(o) => {
if o.is_dir() {
return o.to_path_buf();
}
match o.parent() {
Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
_ => PathBuf::from("."),
}
}
}
}
pub fn torrent_meta_file(dir: &Path) -> PathBuf {
dir.join(".xget.torrent.json")
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct TorrentSidecar {
url: String,
total: u64,
name: String,
#[serde(default)]
downloaded: u64,
}
fn source_display(source: &TorrentSource) -> String {
match source {
TorrentSource::Magnet(m) => m.clone(),
TorrentSource::File(p) => p.to_string_lossy().to_string(),
TorrentSource::RemoteUrl(u) => u.clone(),
}
}
fn write_sidecar(dir: &Path, source: &TorrentSource, meta: &TorrentMeta) {
let sc = TorrentSidecar {
url: source_display(source),
total: meta.total_length,
name: meta.name.clone(),
downloaded: 0,
};
if let Ok(raw) = serde_json::to_string_pretty(&sc) {
let _ = std::fs::write(torrent_meta_file(dir), raw);
}
}
fn update_sidecar_progress(dir: &Path, downloaded: u64) {
let p = torrent_meta_file(dir);
let mut sc: TorrentSidecar = std::fs::read_to_string(&p)
.ok()
.and_then(|raw| serde_json::from_str(&raw).ok())
.unwrap_or(TorrentSidecar {
url: String::new(),
total: 0,
name: String::new(),
downloaded: 0,
});
if downloaded > sc.downloaded {
sc.downloaded = downloaded;
if let Ok(raw) = serde_json::to_string_pretty(&sc) {
let _ = std::fs::write(&p, raw);
}
}
}
pub fn read_sidecar_progress(dir: &Path, url: &str) -> Option<(u64, String, u64)> {
let raw = std::fs::read_to_string(torrent_meta_file(dir)).ok()?;
let sc: TorrentSidecar = serde_json::from_str(&raw).ok()?;
if sc.url == url {
Some((sc.total, sc.name, sc.downloaded))
} else {
None
}
}
pub fn read_sidecar(dir: &Path, url: &str) -> Option<(u64, String)> {
let raw = std::fs::read_to_string(torrent_meta_file(dir)).ok()?;
let sc: TorrentSidecar = serde_json::from_str(&raw).ok()?;
if sc.url == url {
Some((sc.total, sc.name))
} else {
None
}
}
pub fn disk_usage(path: &Path) -> u64 {
if let Ok(md) = std::fs::metadata(path) {
if md.is_file() {
return md.len();
}
if md.is_dir() {
return dir_size(path);
}
}
0
}
fn dir_size(dir: &Path) -> u64 {
let mut total = 0u64;
let mut stack = vec![dir.to_path_buf()];
while let Some(d) = stack.pop() {
let Ok(rd) = std::fs::read_dir(&d) else {
continue;
};
for e in rd.flatten() {
let p = e.path();
if let Ok(md) = std::fs::metadata(&p) {
if md.is_dir() {
stack.push(p);
} else if md.is_file() {
total = total.saturating_add(md.len());
}
}
}
}
total
}
pub const PEER_LIMIT: usize = 200;
pub const REQUEST_WINDOW: usize = 256;
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
pub const EXTRA_TRACKERS: &[&str] = &[
"udp://tracker.opentrackr.org:1337/announce",
"udp://open.demonii.com:1337/announce",
"udp://tracker.openbittorrent.com:6969/announce",
"udp://exodus.desync.com:6969/announce",
"udp://tracker.torrent.eu.org:451/announce",
];
pub fn extra_trackers() -> std::collections::HashSet<url::Url> {
EXTRA_TRACKERS
.iter()
.filter_map(|s| url::Url::parse(s).ok())
.collect()
}
pub fn runtime_threads() -> usize {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(8)
.max(8)
}
pub fn perf_session_options() -> SessionOptions {
perf_session_options_with(None)
}
pub fn perf_session_options_with(proxy: Option<&str>) -> SessionOptions {
SessionOptions {
dht: Some(DhtSessionConfig::default()),
listen: Some(ListenerOptions {
mode: ListenerMode::TcpAndUtp,
enable_upnp_port_forwarding: true,
..Default::default()
}),
connect: Some(ConnectionOptions {
enable_tcp: true,
proxy_url: proxy.map(|s| s.to_string()),
peer_opts: Some(PeerConnectionOptions {
connect_timeout: Some(CONNECT_TIMEOUT),
read_write_timeout: None,
keep_alive_interval: None,
max_request_window: Some(REQUEST_WINDOW),
}),
}),
peer_limit: Some(PEER_LIMIT),
runtime_worker_threads: Some(runtime_threads()),
trackers: extra_trackers(),
..Default::default()
}
}
#[derive(Debug, Clone, Default)]
pub struct TorrentOptions {
pub seed_minutes: u64,
pub only_files: Option<Vec<usize>>,
pub proxy: Option<String>,
}
#[derive(Debug, Clone)]
pub struct TorrentDone {
pub summary: Summary,
pub final_path: PathBuf,
pub total_bytes: u64,
pub name: String,
pub files: Vec<TorrentFileEntry>,
}
async fn fetch_remote_torrent(url: &str) -> Result<Vec<u8>> {
let client = reqwest::Client::builder()
.user_agent("xget/0.1 (+https://github.com/JustRoccat/xget)")
.connect_timeout(Duration::from_secs(15))
.timeout(Duration::from_secs(120))
.build()
.context("cannot create HTTP client")?;
let resp = client
.get(url)
.send()
.await
.context("cannot fetch .torrent URL")?;
if !resp.status().is_success() {
bail!("cannot fetch .torrent URL: HTTP {}", resp.status());
}
let bytes = resp.bytes().await.context("cannot read .torrent body")?;
if bytes.is_empty() || bytes.len() > 32 * 1024 * 1024 {
bail!("remote file is not a plausible .torrent");
}
parse_torrent_bytes(&bytes)?;
Ok(bytes.to_vec())
}
fn bar_style() -> ProgressStyle {
crate::engine::total_style()
}
pub async fn run(
source: &TorrentSource,
output_opt: Option<PathBuf>,
download_dir: &Path,
opts: &TorrentOptions,
) -> Result<TorrentDone> {
let started = Instant::now();
let folder = session_folder_for(output_opt.as_deref(), download_dir);
if let Some(parent) = folder.parent()
&& !parent.as_os_str().is_empty()
{
tokio::fs::create_dir_all(parent)
.await
.with_context(|| format!("cannot create directory {}", parent.display()))?;
}
tokio::fs::create_dir_all(&folder)
.await
.with_context(|| format!("cannot create directory {}", folder.display()))?;
let sentinel = torrent_sentinel(&folder);
let _ = std::fs::remove_file(&sentinel);
let only_files = opts.only_files.clone();
if let Some(ref v) = only_files {
if v.is_empty() {
bail!("empty --files selection");
}
}
let (add, expected_hash): (AddTorrent<'_>, Option<String>) = match source {
TorrentSource::Magnet(m) => {
let mi = parse_magnet(m)?;
eprintln!(" infohash: {}", mi.info_hash);
if let Some(n) = mi.name.as_deref().filter(|s| !s.is_empty()) {
eprintln!(" name hint: {n}");
}
(AddTorrent::from_url(m.clone()), Some(mi.info_hash))
}
TorrentSource::File(p) => {
let b = std::fs::read(p).with_context(|| format!("cannot read {}", p.display()))?;
let meta = parse_torrent_bytes(&b)?;
eprintln!(
" metafile: {} [{}], {} file(s), {}, {} piece(s)",
meta.name,
meta.info_hash,
meta.files.len(),
format_bytes(meta.total_length),
meta.total_length.div_ceil(meta.piece_length.max(1) as u64)
);
let h = meta.info_hash.clone();
(AddTorrent::from_bytes(b), Some(h))
}
TorrentSource::RemoteUrl(u) => {
eprintln!(" fetching .torrent metafile...");
let b = fetch_remote_torrent(u).await?;
let meta = parse_torrent_bytes(&b)?;
eprintln!(
" metafile: {} [{}], {} file(s), {}",
meta.name,
meta.info_hash,
meta.files.len(),
format_bytes(meta.total_length)
);
let h = meta.info_hash.clone();
(AddTorrent::from_bytes(b), Some(h))
}
};
let folder_arg = folder.to_string_lossy().to_string();
let session = Session::new_with_opts(folder.clone(), perf_session_options_with(opts.proxy.as_deref()))
.await
.context("cannot start torrent session (DHT/listen sockets)")?;
let resp = session
.add_torrent(
add,
Some(AddTorrentOptions {
overwrite: true,
output_folder: Some(folder_arg),
only_files: only_files.clone(),
peer_limit: Some(PEER_LIMIT),
..Default::default()
}),
)
.await
.context("cannot add torrent to session")?;
let handle = match resp {
AddTorrentResponse::Added(_, h) | AddTorrentResponse::AlreadyManaged(_, h) => h,
AddTorrentResponse::ListOnly(_) => bail!("unexpected list-only torrent response"),
};
tokio::time::timeout(METADATA_TIMEOUT, handle.wait_until_initialized())
.await
.context("timed out waiting for torrent metadata (no peers/trackers/DHT); try a .torrent file instead of magnet")?
.context("torrent failed while resolving metadata")?;
let meta: TorrentMeta = handle
.with_metadata(|md| {
let nm = md
.info
.name()
.map(|c| c.into_owned())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "torrent".to_string());
let files: Vec<TorrentFileEntry> = md
.file_infos
.iter()
.enumerate()
.map(|(i, f)| TorrentFileEntry {
index: i,
path: f.relative_filename.to_string_lossy().to_string(),
len: f.len,
})
.collect();
let total: u64 = files.iter().map(|f| f.len).sum();
TorrentMeta {
info_hash: expected_hash.clone().unwrap_or_default(),
name: nm,
total_length: total,
piece_length: md.info.info().piece_length,
files,
}
})
.context("torrent metadata missing after init")?;
let total = meta.total_length;
select_files(meta.files.len().max(1), only_files.clone())?;
write_sidecar(&folder, source, &meta);
if total == 0 {
bail!("torrent has zero length");
}
eprintln!(
" torrent: {} ({} file(s), {})",
meta.name,
meta.files.len(),
format_bytes(total)
);
for f in meta.files.iter().take(20) {
eprintln!(" [{}] {} ({})", f.index, f.path, format_bytes(f.len));
}
if meta.files.len() > 20 {
eprintln!(
" ... and {} more (use --files i to select)",
meta.files.len() - 20
);
}
let bar = ProgressBar::new(total);
bar.set_style(bar_style());
let short = if meta.name.len() > 48 {
format!("{}...", &meta.name[..48])
} else {
meta.name.clone()
};
bar.set_message(short.clone());
let done = loop {
if sentinel.exists() {
bar.abandon_with_message("paused");
bail!("__XGET_PAUSED__");
}
let st = handle.stats();
if let Some(e) = st.error.as_deref() {
bar.abandon_with_message("error");
bail!("torrent error: {e}");
}
let verified: u64 = st
.live
.as_ref()
.map(|live| {
live.snapshot
.downloaded_and_checked_bytes
.min(st.total_bytes.max(total))
})
.unwrap_or(0);
let shown = verified.min(total);
bar.set_length(total);
bar.set_position(shown);
update_sidecar_progress(&folder, shown);
if let Some(live) = st.live.as_ref() {
let p = &live.snapshot.peer_stats;
bar.set_message(format!(
"{short} | p{}/{} s{} {}",
p.live, p.seen, p.live_seeders, live.download_speed
));
}
if st.finished {
break st;
}
tokio::select! {
_ = tokio::signal::ctrl_c() => {
bar.abandon_with_message("interrupted");
bail!("interrupted (Ctrl-C) - resume re-checks pieces and continues");
}
_ = tokio::time::sleep(POLL_INTERVAL) => {}
}
};
let _ = done;
handle
.wait_until_completed()
.await
.context("torrent failed before completion")?;
bar.set_position(total);
bar.finish_with_message("done");
let wall_dl = started.elapsed().as_secs_f64();
{
let fin = handle.stats();
if let Some(live) = fin.live.as_ref() {
let p = &live.snapshot.peer_stats;
eprintln!(
" peers: live {} (tcp {}/utp {}), seeders {}, seen {}, steals {}",
p.live, p.live_tcp, p.live_utp, p.live_seeders, p.seen, p.steals
);
eprintln!(
" fetched: {} (checked {}), uploaded {}",
format_bytes(live.snapshot.fetched_bytes),
format_bytes(live.snapshot.downloaded_and_checked_bytes),
format_bytes(live.snapshot.uploaded_bytes)
);
}
}
if opts.seed_minutes > 0 {
eprintln!(
" seeding for {} min (Ctrl-C stops seeding, files are complete)...",
opts.seed_minutes
);
let seed_total = Duration::from_secs(opts.seed_minutes.saturating_mul(60));
let t0 = Instant::now();
while t0.elapsed() < seed_total {
if sentinel.exists() {
eprintln!(" seeding stopped (paused).");
break;
}
tokio::select! {
_ = tokio::signal::ctrl_c() => {
eprintln!(" seeding stopped by user; files are complete.");
break;
}
_ = tokio::time::sleep(Duration::from_secs(1)) => {}
}
}
}
let single = meta.is_single_file();
let content_root = folder.join(&meta.name);
let mut final_path = if single {
if content_root.is_file() {
content_root.clone()
} else {
meta.files
.first()
.and_then(|f| {
let c = folder.join(&f.path);
if c.is_file() { Some(c) } else { None }
})
.unwrap_or(content_root.clone())
}
} else {
content_root.clone()
};
if single
&& let Some(want) = output_opt.as_deref()
&& !want.is_dir()
&& want != final_path
{
if let Some(parent) = want.parent()
&& !parent.as_os_str().is_empty()
{
tokio::fs::create_dir_all(parent)
.await
.with_context(|| format!("cannot create directory {}", parent.display()))?;
}
if final_path.is_file() {
tokio::fs::rename(&final_path, want)
.await
.with_context(|| {
format!("cannot move {} -> {}", final_path.display(), want.display())
})?;
final_path = want.to_path_buf();
}
}
let _ = std::fs::remove_file(&sentinel);
let _ = std::fs::remove_file(torrent_meta_file(&folder));
let wall = started.elapsed().as_secs_f64().max(0.001);
eprintln!(
" seeding: {}",
if opts.seed_minutes > 0 {
format!("{} min requested", opts.seed_minutes)
} else {
"off".to_string()
}
);
Ok(TorrentDone {
summary: Summary {
total_bytes: total,
elapsed_secs: wall,
avg_bps: total as f64 / wall.max(wall_dl).max(0.001),
mirrors: Vec::new(),
},
final_path,
total_bytes: total,
name: meta.name,
files: meta.files,
})
}
#[cfg(test)]
mod tests {
use super::*;
const UBUNTU_MAGNET: &str = "magnet:?xt=urn:btih:cab507494d02ebb1178b38f2e9d7be299c86b862&dn=ubuntu&tr=udp%3A%2F%2Ftracker.example%2Fannounce";
#[test]
fn parses_magnet_link() {
let m = parse_magnet(UBUNTU_MAGNET).unwrap();
assert_eq!(m.info_hash, "cab507494d02ebb1178b38f2e9d7be299c86b862");
assert_eq!(m.name.as_deref(), Some("ubuntu"));
assert_eq!(m.trackers, vec!["udp://tracker.example/announce"]);
}
#[test]
fn parses_bare_infohash_as_magnet() {
let src = detect("cab507494d02ebb1178b38f2e9d7be299c86b862").unwrap();
assert!(matches!(src, TorrentSource::Magnet(_)));
let m = parse_magnet("cab507494d02ebb1178b38f2e9d7be299c86b862").unwrap();
assert_eq!(m.info_hash, "cab507494d02ebb1178b38f2e9d7be299c86b862");
assert!(m.trackers.is_empty());
}
#[test]
fn rejects_bad_magnet() {
assert!(parse_magnet("magnet:?xt=urn:btih:zzz").is_err());
assert!(parse_magnet("https://example.com/x").is_err());
}
fn tiny_torrent_bytes() -> Vec<u8> {
let mut v = Vec::new();
v.extend_from_slice(b"d8:announce24:http://tracker.example/a4:infod6:lengthi5e4:name8:tiny.bin12:piece lengthi16384e6:pieces20:");
v.extend_from_slice(&[0u8; 20]);
v.extend_from_slice(b"ee");
v
}
fn tiny_multi_bytes() -> Vec<u8> {
let mut v = Vec::new();
v.extend_from_slice(b"d8:announce24:http://tracker.example/a4:infod4:name4:pack5:filesld6:lengthi3e4:pathl5:a.txteed6:lengthi7e4:pathl3:sub5:b.bineee12:piece lengthi16384e6:pieces20:");
v.extend_from_slice(&[0u8; 20]);
v.extend_from_slice(b"ee");
v
}
#[test]
fn parses_single_file_metainfo() {
let meta = parse_torrent_bytes(&tiny_torrent_bytes()).unwrap();
assert_eq!(meta.name, "tiny.bin");
assert_eq!(meta.total_length, 5);
assert_eq!(meta.piece_length, 16384);
assert_eq!(meta.files.len(), 1);
assert_eq!(meta.files[0].path, "tiny.bin");
assert!(meta.is_single_file());
assert_eq!(meta.info_hash.len(), 40);
}
#[test]
fn parses_multi_file_metainfo() {
let meta = parse_torrent_bytes(&tiny_multi_bytes()).unwrap();
assert_eq!(meta.name, "pack");
assert_eq!(meta.total_length, 10);
assert_eq!(meta.files.len(), 2);
assert_eq!(meta.files[0].path, "pack/a.txt");
assert_eq!(meta.files[1].path, "pack/sub/b.bin");
assert!(!meta.is_single_file());
}
#[test]
fn rejects_garbage_metainfo() {
assert!(parse_torrent_bytes(b"hello world").is_err());
assert!(parse_torrent_bytes(b"").is_err());
assert!(parse_torrent_bytes(b"d4:infoi1ee").is_err());
}
#[test]
fn file_selection_rules() {
assert_eq!(select_files(3, None).unwrap(), vec![0, 1, 2]);
assert_eq!(select_files(5, Some(vec![3, 1, 3])).unwrap(), vec![1, 3]);
assert!(select_files(2, Some(vec![2])).is_err());
assert!(select_files(2, Some(vec![])).is_err());
assert_eq!(parse_file_list("0,2,4-6", 10).unwrap(), vec![0, 2, 4, 5, 6]);
assert_eq!(parse_file_list("3-3", 10).unwrap(), vec![3]);
assert!(parse_file_list("9", 9).is_err());
assert!(parse_file_list("5-2", 10).is_err());
assert!(parse_file_list("abc", 10).is_err());
assert!(parse_file_list("", 10).is_err());
}
#[test]
fn detects_torrent_inputs() {
assert!(matches!(
detect(UBUNTU_MAGNET),
Some(TorrentSource::Magnet(_))
));
assert!(matches!(
detect("https://example.com/debian.iso.torrent?x=1"),
Some(TorrentSource::RemoteUrl(_))
));
assert!(detect("https://example.com/debian.iso").is_none());
assert!(detect("https://example.com/page/").is_none());
}
#[test]
fn session_folder_rules() {
let dl = Path::new("/tmp/dl-xget-test");
assert_eq!(
session_folder_for(None, dl),
PathBuf::from("/tmp/dl-xget-test")
);
assert_eq!(
session_folder_for(Some(Path::new("/tmp")), dl),
PathBuf::from("/tmp")
);
assert_eq!(
session_folder_for(Some(Path::new("/tmp/want.iso")), dl),
PathBuf::from("/tmp")
);
assert_eq!(
session_folder_for(Some(Path::new("want.iso")), dl),
PathBuf::from(".")
);
}
#[test]
fn perf_options_are_high_perf() {
let o = perf_session_options();
let dht = o.dht.as_ref().expect("DHT must stay enabled");
assert!(dht.bootstrap_addrs.is_none());
assert!(dht.persistence.is_some());
let listen = o.listen.as_ref().expect("listener must be set");
assert!(matches!(listen.mode, ListenerMode::TcpAndUtp));
assert!(listen.enable_upnp_port_forwarding);
let conn = o.connect.as_ref().expect("connect opts must be set");
assert!(conn.enable_tcp);
let peer = conn.peer_opts.as_ref().expect("peer opts must be set");
assert_eq!(peer.max_request_window, Some(REQUEST_WINDOW));
const { assert!(REQUEST_WINDOW > 128) };
assert_eq!(peer.connect_timeout, Some(CONNECT_TIMEOUT));
assert_eq!(o.peer_limit, Some(PEER_LIMIT));
const { assert!(PEER_LIMIT >= 128) };
assert!(o.runtime_worker_threads.unwrap_or(0) >= 8);
assert!(o.default_storage_factory.is_none());
assert!(!o.trackers.is_empty());
assert!(!o.disable_trackers);
}
#[test]
fn extra_trackers_all_parse() {
assert!(!EXTRA_TRACKERS.is_empty());
assert_eq!(extra_trackers().len(), EXTRA_TRACKERS.len());
}
#[test]
fn runtime_threads_floor() {
assert!(runtime_threads() >= 8);
}
#[test]
fn sidecar_roundtrip_for_status() {
let dir = std::env::temp_dir().join("xget-torrent-sidecar-test");
std::fs::create_dir_all(&dir).unwrap();
let meta = TorrentMeta {
info_hash: "ab".to_string(),
name: "pack".to_string(),
total_length: 42,
piece_length: 16384,
files: Vec::new(),
};
let src = TorrentSource::Magnet(UBUNTU_MAGNET.to_string());
write_sidecar(&dir, &src, &meta);
assert_eq!(
read_sidecar(&dir, UBUNTU_MAGNET),
Some((42, "pack".to_string()))
);
assert!(read_sidecar(&dir, "magnet:?xt=urn:btih:other").is_none());
let _ = std::fs::remove_dir_all(&dir);
}
}