Torrents through qBittorrent instead of librqbit (#494)

ipx ran a BitTorrent session of its own: it bound 6881, joined the DHT and
seeded, and librqbit brought over a thousand lines of Cargo.lock with it,
ringbuf's advisory (#281) and a second path to chrono (#493) among them.
Tower already runs qBittorrent, so torrents go there through its Web API.

ipx still fetches the .torrent itself, through the guarded client and under
the 10 MB cap (#320, #330), and adds it with the enclosure's own folder as
the save path (#318, #331), the files straight into it (NoSubfolder), the
seed limits, and a tag ipx-<enclosure> to find it by, since a magnet has no
hash until its metadata comes. A torrent already tagged when ipx starts
again is taken up where qBittorrent has it (#410). It is polled to the end
under the stall limit; a qBittorrent not answering counts as no progress
rather than a failure. qBittorrent seeds to the limits; with none, ipx
removes the torrent from it at the end, files kept.

The session cookie is whatever qBittorrent sets with SID in its name:
5.x calls it QBT_SID_<port>. torrents/info by POST with a tag was checked
against Tower's 5.2.3.

The ringbuf ignore leaves deny.toml; chrono's stays, for rss and
atom_syndication alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U
This commit is contained in:
2026-11-22 14:29:20 -05:00
parent 2c8b4d925e
commit c4d7b497fa
13 changed files with 364 additions and 1369 deletions

View File

@@ -30,6 +30,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- Torrents go to qBittorrent through its Web API, set in `[torrent]` (`qbittorrent_url`, `username`, `password`, `save_path`), which downloads and seeds them; ipx no longer runs a BitTorrent client of its own or listens on 6881, and `port_range` is gone. Without a qBittorrent set, torrents are held back as when they are turned off (#494).
- The server's command is `ipxd`, not `ipx`: `ipxd daemon`, `ipxd status`, `ipxd user add` and the rest, in the container as `docker exec iPX ipxd ...`. `ipx` is now the reader in a terminal (#437).
- The log no longer has a line for every request that went well, over half its size: `/metrics` counts each request and its time by route and status as `ipx_http_request_duration_seconds`, a request that failed keeps its warning, and the admin page's log view still shows them all (#364).

View File

@@ -27,7 +27,6 @@ chrono.workspace = true
clap.workspace = true
futures-util.workspace = true
jsonwebtoken.workspace = true
librqbit.workspace = true
opentelemetry.workspace = true
opentelemetry_sdk.workspace = true
opml.workspace = true

View File

@@ -112,10 +112,17 @@ impl Push {
#[serde(default)]
pub struct Torrent {
pub enabled: bool,
/// Stop seeding at this ratio, or after seed_time_mins, whichever comes first.
/// qBittorrent's Web UI, which does the downloading and seeding (#494), e.g.
/// "http://qbittorrent:8080". Empty: torrents are held back, as when not enabled.
pub qbittorrent_url: String,
/// Empty when qBittorrent lets ipx's address in without signing in.
pub username: String,
pub password: String,
/// Where qBittorrent sees `download_dir`, when its mount is not at the same path as ipx's.
pub save_path: String,
/// qBittorrent stops seeding at this ratio, or after seed_time_mins, whichever comes first.
pub seed_ratio: f64,
pub seed_time_mins: u64,
pub port_range: String,
/// Drop a torrent that has made no progress for this long.
pub stall_mins: u64,
}
@@ -265,7 +272,16 @@ impl Default for General {
impl Default for Torrent {
fn default() -> Self {
Self { enabled: true, seed_ratio: 1.0, seed_time_mins: 60, port_range: "6881-6889".into(), stall_mins: 30 }
Self {
enabled: true,
qbittorrent_url: String::new(),
username: String::new(),
password: String::new(),
save_path: String::new(),
seed_ratio: 1.0,
seed_time_mins: 60,
stall_mins: 30,
}
}
}
@@ -313,16 +329,9 @@ pub fn parse_interval(s: &str) -> Option<u64> {
}
impl Torrent {
/// Inclusive listen port range. Falls back to the BitTorrent default on garbage input.
pub fn ports(&self) -> (u16, u16) {
let parse = || -> Option<(u16, u16)> {
let (lo, hi) = self.port_range.split_once('-')?;
Some((lo.trim().parse().ok()?, hi.trim().parse().ok()?))
};
match parse() {
Some((lo, hi)) if lo <= hi => (lo, hi),
_ => (6881, 6889),
}
/// Torrents are fetched only with somewhere to send them.
pub fn on(&self) -> bool {
self.enabled && !self.qbittorrent_url.trim().is_empty()
}
}
@@ -714,15 +723,13 @@ mod tests {
}
#[test]
fn port_range_falls_back_when_malformed() {
fn torrents_are_on_only_with_a_qbittorrent_to_send_them_to() {
let mut t = Torrent::default();
assert_eq!(t.ports(), (6881, 6889));
t.port_range = "51413-51420".into();
assert_eq!(t.ports(), (51413, 51420));
t.port_range = "nonsense".into();
assert_eq!(t.ports(), (6881, 6889));
t.port_range = "900-100".into();
assert_eq!(t.ports(), (6881, 6889), "reversed range is not a range");
assert!(!t.on(), "enabled, but nowhere to send them");
t.qbittorrent_url = "http://qbittorrent:8080".into();
assert!(t.on());
t.enabled = false;
assert!(!t.on());
}
#[test]

View File

@@ -29,15 +29,14 @@ pub struct Ctx {
/// that moved for good from one sent elsewhere for now.
pub feed_client: reqwest::Client,
pub out: Emitter,
/// Started on first use: a BitTorrent session binds ports and starts a DHT, which is
/// rude to do for a config that has never seen a torrent.
/// qBittorrent's client and session cookie, made on first use (#494).
pub torrents: OnceCell<torrent::Torrents>,
/// Caps how many torrents run at once when they are detached.
pub torrent_slots: Arc<Semaphore>,
/// Needed because a subscribed OPML rewrites the feed list as it syncs.
pub config_path: PathBuf,
/// Run torrents off the command worker. A torrent takes minutes to fetch metadata and
/// then seeds for up to an hour, and the worker is sequential -- inline, one torrent
/// more to download, and the worker is sequential -- inline, one torrent
/// stops every feed scan, every HTTP download and every status command behind it.
/// A one-shot CLI run keeps them inline, or the process would exit mid-download.
pub detach_torrents: bool,
@@ -209,8 +208,7 @@ impl Ctx {
}
pub(crate) async fn torrents(&self) -> Result<&torrent::Torrents> {
let cfg = self.cfg();
self.torrents.get_or_try_init(|| torrent::Torrents::new(&cfg)).await
self.torrents.get_or_try_init(|| async { torrent::Torrents::new() }).await
}
}

View File

@@ -3,7 +3,7 @@
use crate::catalogue::Sub;
use crate::ctx::Ctx;
use crate::ipc::Event;
use crate::{catalogue, cli, config, db, download, feed, lists, metrics, signals, torrent};
use crate::{catalogue, cli, config, db, download, feed, lists, metrics, signals};
use anyhow::Result;
use std::collections::HashSet;
use std::path::Path;
@@ -533,7 +533,7 @@ pub(crate) async fn scan_one(
for item in ctx.db.pending(id, budget).await? {
if download::looks_like_torrent(&item.url, item.mime.as_deref()) {
if !ctx.cfg().torrent.enabled {
if !ctx.cfg().torrent.on() {
ctx.db.mark_enclosure(&item.url, "skipped", Some("torrents disabled")).await?;
ctx.out.emit(Event::TorrentDeferred { feed: id.to_string(), url: item.url.clone() });
scan.torrents += 1;
@@ -750,7 +750,7 @@ pub(crate) async fn fetch_one(
// The MIME lied. Hand the URL to the torrent session instead of filing a .torrent
// as if it were an episode.
let _ = tokio::fs::remove_file(&got.tmp).await;
if !ctx.cfg().torrent.enabled {
if !ctx.cfg().torrent.on() {
ctx.db.mark_enclosure(url, "skipped", Some("torrents disabled")).await?;
anyhow::bail!("body is a torrent and torrents are disabled");
}
@@ -831,13 +831,13 @@ pub(crate) async fn download_one(ctx: &Arc<Ctx>, id: i64) -> Result<()> {
ctx.out.emit(Event::FeedStart { feed: enc.feed_id.clone() });
let is_torrent = download::looks_like_torrent(&enc.url, enc.mime.as_deref());
if is_torrent && cfg.torrent.enabled && ctx.detach_torrents {
if is_torrent && cfg.torrent.on() && ctx.detach_torrents {
ctx.db.mark_enclosure(&enc.url, "downloading", None).await?;
spawn_torrent(ctx, enc.feed_id.clone(), enc.id, enc.url.clone(), dest_dir);
return Ok(());
}
let result = if is_torrent {
if !cfg.torrent.enabled {
if !cfg.torrent.on() {
Err(anyhow::anyhow!("torrents are disabled"))
} else {
torrent_one(ctx, &enc.feed_id, enc.id, &enc.url, &dest_dir).await.map(Some)
@@ -889,7 +889,7 @@ pub(crate) async fn torrent_one(
let cfg = ctx.cfg();
ctx.torrents()
.await?
.fetch(&cfg, &ctx.client, url, &torrent::own_folder(dest_dir, enclosure), |done, total| {
.fetch(&cfg, &ctx.client, url, dest_dir, enclosure, |done, total| {
if let Some(pct) = (done * 100).checked_div(total).map(|p| p as i64)
&& pct > last_pct
{
@@ -1089,17 +1089,17 @@ mod tests {
let state = |ctx: Arc<Ctx>| async move { ctx.db.strings_for_test("SELECT state FROM enclosures").await };
// Detached, as the daemon runs them: no slot free, so it waits its turn as 'downloading'.
let mut ctx = test_ctx(config::Config::default()).await;
let mut on = config::Config::default();
on.torrent.qbittorrent_url = "http://127.0.0.1:9".into();
let mut ctx = test_ctx(on).await;
ctx.detach_torrents = true;
ctx.torrent_slots = Arc::new(tokio::sync::Semaphore::new(0));
let ctx = Arc::new(ctx);
assert_eq!(scan(ctx.clone()).await, (0, 1), "counted as a torrent, not a download");
assert_eq!(state(ctx).await, ["downloading"], "so the next scan does not queue it again");
// Turned off, it is skipped and still counted.
let mut cfg = config::Config::default();
cfg.torrent.enabled = false;
let ctx = Arc::new(test_ctx(cfg).await);
// With no qBittorrent to send it to, it is skipped and still counted.
let ctx = Arc::new(test_ctx(config::Config::default()).await);
assert_eq!(scan(ctx.clone()).await, (0, 1));
assert_eq!(state(ctx).await, ["skipped"]);
}

View File

@@ -1,20 +1,39 @@
//! Torrent enclosures via librqbit. Replaces iPXDownloader.getTorrent and the vendored
//! BitTorrent 4.2.1 + khashmir tree.
//! Torrent enclosures through qBittorrent's Web API (#494). ipx fetches the .torrent itself, hands
//! it over with the enclosure's own folder as its save path, and watches it to the end; qBittorrent
//! downloads it and seeds it to the limits set here. Until then ipx ran a BitTorrent session of its
//! own (librqbit), which replaced iPXDownloader.getTorrent and the vendored BitTorrent 4.2.1.
use anyhow::{Context, Result, bail};
use librqbit::{AddTorrent, AddTorrentOptions, AddTorrentResponse, Session, SessionOptions};
use std::net::SocketAddr;
use anyhow::{Context, Result, anyhow, bail};
use reqwest::header::{COOKIE, SET_COOKIE};
use reqwest::multipart::{Form, Part};
use serde::Deserialize;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::config::Config;
use librqbit::{ListenerOptions, ManagedTorrent};
pub struct Torrents {
session: Arc<Session>,
/// Not the guarded client feeds are fetched with: qBittorrent is on the LAN by design, at the
/// address the admin gave, which the guard would refuse (#320).
http: reqwest::Client,
/// The session cookie, `name=value`; qBittorrent 5 names it after its port.
cookie: tokio::sync::Mutex<Option<String>>,
}
/// What `torrents/info` says of one torrent, as much as ipx reads.
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
struct Info {
hash: String,
state: String,
progress: f64,
total_size: i64,
completed: i64,
}
/// How often a running torrent is looked at.
const POLL: Duration = Duration::from_secs(2);
/// How long a torrent may make no progress before we give up on it. The original called
/// this torrentMaxBeatTime and counted display ticks; a wall clock is easier to reason about.
fn stall_limit(cfg: &Config) -> Duration {
@@ -22,132 +41,175 @@ fn stall_limit(cfg: &Config) -> Duration {
}
impl Torrents {
pub async fn new(cfg: &Config) -> Result<Self> {
let (lo, _hi) = cfg.torrent.ports();
let listen_addr: SocketAddr = format!("0.0.0.0:{lo}").parse()?;
let opts = SessionOptions {
listen: Some(ListenerOptions { listen_addr, ..Default::default() }),
client_name_and_version: Some(concat!("ipx ", env!("CARGO_PKG_VERSION")).into()),
// A test's swarm is two sessions and a tracker on 127.0.0.1, not the public DHT or the LAN.
dht: if cfg!(test) { None } else { Some(Default::default()) },
disable_local_service_discovery: cfg!(test),
..Default::default()
};
// The session root is only a fallback; every torrent names its own output folder.
let session = Session::new_with_opts(cfg.general.download_dir.clone(), opts)
.await
.context("starting the torrent session")?;
Ok(Self { session })
pub fn new() -> Result<Self> {
let http = reqwest::Client::builder().timeout(Duration::from_secs(30)).build()?;
Ok(Self { http, cookie: Default::default() })
}
/// Downloads a torrent (a .torrent URL or a magnet link) straight into `dest_dir`,
/// seeds it up to the configured limit, then stops. `dest_dir` is the torrent's own
/// folder (`own_folder`), and it is the path returned: a file of several or one.
///
/// Downloading in place rather than into a staging dir is deliberate: seeding serves
/// the files it downloaded, so moving them first would break it.
/// Downloads a torrent (a .torrent URL or a magnet link) through qBittorrent into the
/// enclosure's own folder inside `feed_dir`, which is the path returned: a file of several or
/// one. Done once qBittorrent has all of it; the seeding is qBittorrent's.
pub async fn fetch(
&self,
cfg: &Config,
client: &reqwest::Client,
url: &str,
dest_dir: &Path,
feed_dir: &Path,
enclosure: i64,
mut on_progress: impl FnMut(u64, u64),
) -> Result<(PathBuf, u64)> {
tokio::fs::create_dir_all(dest_dir).await?;
let dir = own_folder(feed_dir, enclosure);
tokio::fs::create_dir_all(&dir).await?;
let limit = stall_limit(cfg);
let source = if url.starts_with("http://") || url.starts_with("https://") {
// Under the stall budget as well: a body sent a byte a minute stays inside the cap.
let file = tokio::time::timeout(limit, torrent_file(client, url))
.await
.map_err(|_| anyhow::anyhow!("no .torrent after {} minutes, gave up", limit.as_secs() / 60))??;
AddTorrent::from_bytes(file)
} else {
AddTorrent::from_url(url)
};
// How ipx finds it again: qBittorrent names a torrent by its hash, which a magnet does not
// say until its metadata has come.
let tag = format!("ipx-{enclosure}");
// Resolving a magnet's metadata happens inside add_torrent, and against a dead
// swarm it never returns. The stall budget has to cover this phase too, or a
// torrent nobody is seeding wedges the scan forever.
let added = tokio::time::timeout(
limit,
self.session.add_torrent(
source,
Some(AddTorrentOptions {
output_folder: Some(dest_dir.to_string_lossy().into_owned()),
overwrite: true,
..Default::default()
}),
),
)
.await
.map_err(|_| anyhow::anyhow!("no metadata after {} minutes, gave up", limit.as_secs() / 60))?
.context("adding the torrent")?;
let (id, handle) = match added {
AddTorrentResponse::Added(id, h) | AddTorrentResponse::AlreadyManaged(id, h) => (id, h),
AddTorrentResponse::ListOnly(_) => bail!("torrent added in list-only mode"),
};
let mut last_progress = 0u64;
let mut last_move = Instant::now();
loop {
tokio::time::sleep(Duration::from_secs(1)).await;
let stats = handle.stats();
if let Some(err) = &stats.error {
let _ = self.session.delete(id.into(), false).await;
bail!("torrent failed: {err}");
// There already when ipx stopped while it ran (#410): taken up where qBittorrent has it.
if self.info(cfg, &tag).await?.is_none() {
let file = if url.starts_with("http://") || url.starts_with("https://") {
// Under the stall budget as well: a body sent a byte a minute stays inside the cap.
let got = tokio::time::timeout(limit, torrent_file(client, url))
.await
.map_err(|_| anyhow!("no .torrent after {} minutes, gave up", limit.as_secs() / 60))??;
Some(got)
} else {
None
};
let t = &cfg.torrent;
let save = save_path(cfg, &dir);
let said = self
.api(cfg, "torrents/add", |req| {
let form = Form::new()
.text("savepath", save.clone())
.text("tags", tag.clone())
// The files straight into the folder, as the path recorded says (#318).
.text("contentLayout", "NoSubfolder")
.text("ratioLimit", t.seed_ratio.to_string())
.text("seedingTimeLimit", t.seed_time_mins.to_string());
req.multipart(match &file {
Some(b) => form.part("torrents", Part::bytes(b.clone()).file_name("episode.torrent")),
None => form.text("urls", url.to_owned()),
})
})
.await?;
if said.trim() == "Fails." {
bail!("qBittorrent would not take the torrent; it may have it already");
}
on_progress(stats.progress_bytes, stats.total_bytes);
}
if stats.finished {
break;
let mut last = (-1i64, Instant::now());
let done = loop {
tokio::time::sleep(POLL).await;
// A qBittorrent restarting is a pause, not a failure, until the stall limit says so.
let info = match self.info(cfg, &tag).await {
Ok(i) => i,
Err(e) if last.1.elapsed() < limit => {
tracing::debug!(error = %format!("{e:#}"), "qBittorrent did not answer");
continue;
}
Err(e) => return Err(e),
};
let Some(info) = info else { bail!("the torrent is no longer in qBittorrent") };
if matches!(info.state.as_str(), "error" | "missingFiles") {
self.delete(cfg, &info.hash).await;
bail!("qBittorrent says the torrent failed ({})", info.state);
}
if stats.progress_bytes > last_progress {
last_progress = stats.progress_bytes;
last_move = Instant::now();
} else if last_move.elapsed() > limit {
on_progress(info.completed.max(0) as u64, info.total_size.max(0) as u64);
if info.progress >= 1.0 && info.total_size > 0 {
break info;
}
if info.completed > last.0 {
last = (info.completed, Instant::now());
} else if last.1.elapsed() > limit {
// Leave the partial files behind; the row records the failure.
let _ = self.session.delete(id.into(), false).await;
self.delete(cfg, &info.hash).await;
bail!("no progress for {} minutes, gave up", limit.as_secs() / 60);
}
};
// shortcut: a torrent seeding when the reaper deletes its files shows as missing files in
// qBittorrent until someone removes it there; have the reaper delete it too if that bothers.
if cfg.torrent.seed_ratio <= 0.0 || cfg.torrent.seed_time_mins == 0 {
self.delete(cfg, &done.hash).await;
}
// The torrent's own name is the publisher's to choose, and librqbit checks it only when it
// picks the folder itself: joined on, "/config" or ".." pointed Delete, the reaper and
// /media at anything the daemon can reach (#318). The folder is ours, so it is the path.
let path = dest_dir.to_owned();
let size = handle.stats().total_bytes;
self.seed(cfg, &handle).await;
self.session.delete(id.into(), false).await.context("releasing the torrent")?;
Ok((path, size))
Ok((dir, done.total_size as u64))
}
/// Seeds until the ratio or the time limit is reached, whichever comes first.
async fn seed(&self, cfg: &Config, handle: &Arc<ManagedTorrent>) {
if cfg.torrent.seed_ratio <= 0.0 || cfg.torrent.seed_time_mins == 0 {
return;
async fn info(&self, cfg: &Config, tag: &str) -> Result<Option<Info>> {
let body = self.api(cfg, "torrents/info", |req| req.form(&[("tag", tag)])).await?;
let mut all: Vec<Info> = serde_json::from_str(&body).context("reading qBittorrent's torrent list")?;
Ok((!all.is_empty()).then(|| all.swap_remove(0)))
}
/// Takes the torrent out of qBittorrent, keeping its files. A failure is logged, not raised:
/// what called it is already giving up, or done.
async fn delete(&self, cfg: &Config, hash: &str) {
let form = [("hashes", hash), ("deleteFiles", "false")];
if let Err(e) = self.api(cfg, "torrents/delete", |req| req.form(&form)).await {
tracing::warn!(error = %format!("{e:#}"), "could not remove the torrent from qBittorrent");
}
let deadline = Instant::now() + Duration::from_secs(cfg.torrent.seed_time_mins * 60);
loop {
let stats = handle.stats();
if ratio(stats.uploaded_bytes, stats.total_bytes) >= cfg.torrent.seed_ratio {
tracing::info!(ratio = cfg.torrent.seed_ratio, "seed ratio reached");
return;
}
/// One call to the Web API, signing in first when a user is set, and again once if the session
/// has expired (a 403). The answer's body.
async fn api(
&self,
cfg: &Config,
path: &str,
body: impl Fn(reqwest::RequestBuilder) -> reqwest::RequestBuilder,
) -> Result<String> {
let base = cfg.torrent.qbittorrent_url.trim_end_matches('/');
for retry in [false, true] {
let cookie = self.cookie(cfg, retry).await?;
let mut req = body(self.http.post(format!("{base}/api/v2/{path}")));
if let Some(c) = cookie {
req = req.header(COOKIE, c);
}
if Instant::now() >= deadline {
tracing::info!(mins = cfg.torrent.seed_time_mins, "seed time reached");
return;
let resp = req.send().await.with_context(|| format!("asking qBittorrent ({path})"))?;
if resp.status() == reqwest::StatusCode::FORBIDDEN && !retry && !cfg.torrent.username.is_empty() {
continue;
}
tokio::time::sleep(Duration::from_secs(5)).await;
let resp = resp.error_for_status().with_context(|| format!("qBittorrent refused {path}"))?;
return Ok(resp.text().await?);
}
unreachable!("the second try returns")
}
async fn cookie(&self, cfg: &Config, fresh: bool) -> Result<Option<String>> {
let t = &cfg.torrent;
if t.username.is_empty() {
return Ok(None);
}
let mut held = self.cookie.lock().await;
if fresh || held.is_none() {
let resp = self
.http
.post(format!("{}/api/v2/auth/login", t.qbittorrent_url.trim_end_matches('/')))
.form(&[("username", t.username.as_str()), ("password", t.password.as_str())])
.send()
.await
.context("signing in to qBittorrent")?;
let got = resp
.headers()
.get_all(SET_COOKIE)
.iter()
.filter_map(|v| v.to_str().ok()?.split(';').next())
.find(|c| c.split_once('=').is_some_and(|(name, _)| name.contains("SID")))
.map(str::to_owned);
*held = Some(got.ok_or_else(|| anyhow!("qBittorrent refused ipx's username and password"))?);
}
Ok(held.clone())
}
}
/// Where qBittorrent is to write `dir`: the same path, or `save_path` in place of `download_dir`
/// when qBittorrent's mount of it is somewhere else.
fn save_path(cfg: &Config, dir: &Path) -> String {
let theirs = cfg.torrent.save_path.trim();
match dir.strip_prefix(&cfg.general.download_dir) {
Ok(rest) if !theirs.is_empty() => Path::new(theirs).join(rest).display().to_string(),
_ => dir.display().to_string(),
}
}
@@ -175,93 +237,95 @@ pub fn own_folder(feed_dir: &Path, enclosure: i64) -> PathBuf {
feed_dir.join(format!("torrent-{enclosure}"))
}
/// Uploaded over total. A zero-byte torrent counts as fully seeded rather than dividing by zero.
pub fn ratio(uploaded: u64, total: u64) -> f64 {
if total == 0 {
return f64::INFINITY;
}
uploaded as f64 / total as f64
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
fn free_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}
/// A swarm on 127.0.0.1: a seeding session holding `file`, and a web server answering for the
/// .torrent (`/ep.torrent`) and as its tracker, naming the seed as the one peer. The server's
/// address, and the seeding session, which stops seeding when dropped.
async fn swarm(file: &Path) -> (SocketAddr, Arc<Session>) {
/// A qBittorrent that wants a sign-in, and as the feed's server serves the .torrent too. A
/// torrent added is finished at once: the file is written into its save path, as qBittorrent
/// would. Its address, and the hashes deleted.
async fn qbittorrent(episode: Vec<u8>) -> (std::net::SocketAddr, Arc<std::sync::Mutex<Vec<String>>>) {
use axum::http::{HeaderMap, StatusCode};
use axum::response::IntoResponse;
use axum::routing::{get, post};
type Held = Arc<std::sync::Mutex<Vec<serde_json::Value>>>;
let held: Held = Default::default();
let deleted: Arc<std::sync::Mutex<Vec<String>>> = Default::default();
let signed_in = |h: &HeaderMap| h.get("cookie").is_some_and(|c| c == "QBT_SID_8080=abc");
// The multipart body read as text: enough to find a field's value in a test.
let field = |body: &str, name: &str| {
let at = body.find(&format!("name=\"{name}\"\r\n\r\n")).unwrap() + name.len() + 11;
body[at..].split("\r\n").next().unwrap().to_owned()
};
let (h1, h2, d) = (held.clone(), held.clone(), deleted.clone());
let app = axum::Router::new()
.route("/ep.torrent", get(|| async { "d4:infode" }))
.route(
"/api/v2/auth/login",
post(|body: String| async move {
if body == "username=ipx&password=pw" {
([("set-cookie", "QBT_SID_8080=abc; HttpOnly; path=/")], "Ok.").into_response()
} else {
"Fails.".into_response()
}
}),
)
.route(
"/api/v2/torrents/add",
post(move |h: HeaderMap, body: axum::body::Bytes| async move {
if !signed_in(&h) {
return (StatusCode::FORBIDDEN, "Forbidden").into_response();
}
let body = String::from_utf8_lossy(&body);
assert!(body.contains("d4:infode"), "the .torrent ipx fetched");
assert_eq!(field(&body, "contentLayout"), "NoSubfolder");
let save = field(&body, "savepath");
std::fs::write(Path::new(&save).join("episode.mp3"), &episode).unwrap();
let n = episode.len();
h1.lock().unwrap().push(serde_json::json!({"hash": "h1", "tags": field(&body, "tags"),
"state": "uploading", "progress": 1.0, "total_size": n, "completed": n}));
"Ok.".into_response()
}),
)
.route(
"/api/v2/torrents/info",
post(move |h: HeaderMap, body: String| async move {
if !signed_in(&h) {
return (StatusCode::FORBIDDEN, "Forbidden").into_response();
}
let tag = body.strip_prefix("tag=").unwrap().to_owned();
let all = h2.lock().unwrap().iter().filter(|t| t["tags"] == tag).cloned().collect::<Vec<_>>();
axum::Json(all).into_response()
}),
)
.route(
"/api/v2/torrents/delete",
post(move |body: String| async move {
d.lock().unwrap().push(body);
"Ok."
}),
);
let web = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let at = web.local_addr().unwrap();
let seed_port = free_port();
let made = librqbit::create_torrent(
file,
librqbit::CreateTorrentOptions {
name: None,
trackers: vec![format!("http://{at}/announce")],
piece_length: Some(16 * 1024),
},
&librqbit::spawn_utils::BlockingSpawner::new(2),
)
.await
.unwrap();
let torrent = made.as_bytes().unwrap();
// Compact peers: the address's four bytes, then the port's two.
let mut peers = b"d8:intervali60e5:peers6:".to_vec();
peers.extend_from_slice(&[127, 0, 0, 1]);
peers.extend_from_slice(&seed_port.to_be_bytes());
peers.push(b'e');
let app = axum::Router::new()
.route("/ep.torrent", axum::routing::get(move || std::future::ready(torrent.clone())))
.route("/announce", axum::routing::get(move || std::future::ready(peers.clone())));
tokio::spawn(async move { axum::serve(web, app).await });
let seed = Session::new_with_opts(
file.parent().unwrap().to_owned(),
SessionOptions {
dht: None,
disable_local_service_discovery: true,
listen: Some(ListenerOptions {
listen_addr: format!("127.0.0.1:{seed_port}").parse().unwrap(),
..Default::default()
}),
..Default::default()
},
)
.await
.unwrap();
seed.add_torrent(
AddTorrent::from_bytes(made.as_bytes().unwrap()),
Some(AddTorrentOptions {
output_folder: Some(file.parent().unwrap().display().to_string()),
overwrite: true,
..Default::default()
}),
)
.await
.unwrap();
(at, seed)
(at, deleted)
}
#[tokio::test(flavor = "multi_thread")]
async fn a_detached_torrent_lands_in_its_own_folder_is_recorded_and_frees_its_slot() {
let root = std::env::temp_dir().join(format!("ipx-torrent-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let (seeded, downloads) = (root.join("seed"), root.join("downloads"));
std::fs::create_dir_all(&seeded).unwrap();
let downloads = root.join("downloads");
let episode: Vec<u8> = (0..200_000u32).map(|i| (i * 7 % 251) as u8).collect();
std::fs::write(seeded.join("episode.mp3"), &episode).unwrap();
let (at, _seed) = swarm(&seeded.join("episode.mp3")).await;
let (at, deleted) = qbittorrent(episode.clone()).await;
let mut cfg = Config::default();
cfg.general.download_dir = downloads.clone();
cfg.torrent.enabled = true;
let port = free_port();
cfg.torrent.port_range = format!("{port}-{port}");
cfg.general.fetch_internal = vec!["127.0.0.1".into()];
cfg.torrent.qbittorrent_url = format!("http://{at}/");
cfg.torrent.username = "ipx".into();
cfg.torrent.password = "pw".into();
cfg.torrent.seed_ratio = 0.0;
let mut ctx = crate::test_util::test_ctx(cfg.clone()).await;
ctx.detach_torrents = true;
@@ -275,7 +339,7 @@ mod tests {
.unwrap();
crate::scan::spawn_torrent(&ctx, "f".into(), 9, url.clone(), downloads.join("Show"));
let row = tokio::time::timeout(Duration::from_secs(90), async {
let row = tokio::time::timeout(Duration::from_secs(30), async {
loop {
let row = ctx.db.enclosure(9).await.unwrap().unwrap();
if row.state != "downloading" {
@@ -285,17 +349,32 @@ mod tests {
}
})
.await
.expect("the torrent finished within 90 s");
.expect("the torrent finished within 30 s");
let folder = own_folder(&downloads.join("Show"), 9);
assert_eq!((row.state.as_str(), row.last_error.as_deref()), ("done", None));
assert_eq!(row.path.as_deref(), Some(folder.display().to_string().as_str()), "the folder is ours (#318)");
assert_eq!(std::fs::read(folder.join("episode.mp3")).unwrap(), episode);
assert_eq!(
*deleted.lock().unwrap(),
["hashes=h1&deleteFiles=false"],
"no seeding asked for: let go, files kept"
);
// The slot is let go once the row is written; give the task its moment.
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(ctx.torrent_slots.available_permits(), 2, "the slot is free again");
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn the_save_path_is_where_qbittorrent_sees_the_folder() {
let mut cfg = Config::default();
cfg.general.download_dir = "/downloads".into();
let dir = Path::new("/downloads/Show/torrent-9");
assert_eq!(save_path(&cfg, dir), "/downloads/Show/torrent-9", "the same mount");
cfg.torrent.save_path = "/data/ipx".into();
assert_eq!(save_path(&cfg, dir), "/data/ipx/Show/torrent-9");
}
#[tokio::test]
async fn a_torrent_file_from_an_internal_address_is_refused_unless_allowed() {
let app = axum::Router::new().route("/ep.torrent", axum::routing::get(|| async { "d4:infode" }));
@@ -317,14 +396,6 @@ mod tests {
);
}
#[test]
fn ratio_handles_the_empty_torrent() {
assert_eq!(ratio(0, 100), 0.0);
assert_eq!(ratio(50, 100), 0.5);
assert_eq!(ratio(200, 100), 2.0);
assert!(ratio(0, 0).is_infinite(), "must not divide by zero or seed forever");
}
#[tokio::test]
async fn an_endless_torrent_file_stops_at_the_cap() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};