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

1154
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -26,7 +26,6 @@ chrono = { version = "0.4.45", default-features = false, features = ["std", "clo
clap = { version = "4.6.6", features = ["derive"] } clap = { version = "4.6.6", features = ["derive"] }
futures-util = { version = "0.3.34", default-features = false, features = ["std"] } futures-util = { version = "0.3.34", default-features = false, features = ["std"] }
jsonwebtoken = { version = "11.1.0", default-features = false, features = ["aws_lc_rs"] } jsonwebtoken = { version = "11.1.0", default-features = false, features = ["aws_lc_rs"] }
librqbit = { version = "9.0.1", default-features = false, features = ["rust-tls", "http-api-client"] }
opentelemetry = { version = "0.33", default-features = false, features = ["trace"] } opentelemetry = { version = "0.33", default-features = false, features = ["trace"] }
opentelemetry-otlp = { version = "0.33", default-features = false, features = ["trace", "http-proto", "reqwest-blocking-client", "gzip-http"] } opentelemetry-otlp = { version = "0.33", default-features = false, features = ["trace", "http-proto", "reqwest-blocking-client", "gzip-http"] }
opentelemetry_sdk = { version = "0.33", default-features = false, features = ["trace"] } opentelemetry_sdk = { version = "0.33", default-features = false, features = ["trace"] }
@@ -42,7 +41,7 @@ http = "1.5.0"
hyper-util = { version = "0.1.20", features = ["client-legacy"] } hyper-util = { version = "0.1.20", features = ["client-legacy"] }
percent-encoding = "2.3.2" percent-encoding = "2.3.2"
quick-xml = { version = "0.42.0", features = ["escape-html"] } quick-xml = { version = "0.42.0", features = ["escape-html"] }
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "http2", "gzip", "brotli", "zstd", "stream", "json", "charset", "system-proxy"] } reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "http2", "gzip", "brotli", "zstd", "stream", "json", "form", "multipart", "charset", "system-proxy"] }
rss = "2.1.1" rss = "2.1.1"
sea-orm = { version = "2.0.3", default-features = false, features = ["sqlx-sqlite", "sqlx-postgres", "runtime-tokio-rustls", "macros", "with-json", "sqlite-use-returning-for-3_35"] } sea-orm = { version = "2.0.3", default-features = false, features = ["sqlx-sqlite", "sqlx-postgres", "runtime-tokio-rustls", "macros", "with-json", "sqlite-use-returning-for-3_35"] }
serde = { version = "1.0.229", features = ["derive"] } serde = { version = "1.0.229", features = ["derive"] }

View File

@@ -19,7 +19,7 @@ behind iPodderX (2004-2008, Ray Slakinski & August Trometer).
- **Scanning.** Feeds are checked on a schedule, globally or per feed, and a feed's own TTL is - **Scanning.** Feeds are checked on a schedule, globally or per feed, and a feed's own TTL is
honoured. Keyword, explicit-content and media-type filters decide what is downloaded, with a limit honoured. Keyword, explicit-content and media-type filters decide what is downloaded, with a limit
on how many of a feed's newest episodes are downloaded. on how many of a feed's newest episodes are downloaded.
- **Downloads.** Files come over HTTP or BitTorrent and are filed into a folder per feed. - **Downloads.** Files come over HTTP, or BitTorrent through qBittorrent, and are filed into a folder per feed.
Retention deletes the oldest files to stay under a disk quota or an age limit, and never touches Retention deletes the oldest files to stay under a disk quota or an age limit, and never touches
an item someone has pinned. an item someone has pinned.
- **OPML.** You can import and export your own subscriptions. You can also subscribe to an OPML - **OPML.** You can import and export your own subscriptions. You can also subscribe to an OPML
@@ -37,8 +37,8 @@ docker compose up -d
`docker-compose.yml` is a sample: ipx, with its database in SQLite and its three volumes `docker-compose.yml` is a sample: ipx, with its database in SQLite and its three volumes
(`/config`, `/data` and `/downloads`) in folders beside the file, and ipx-web, the page, served by (`/config`, `/data` and `/downloads`) in folders beside the file, and ipx-web, the page, served by
Caddy in front of it. Change them to suit. The UI is on port 8099. BitTorrent uses 6881 Caddy in front of it. Change them to suit. The UI is on port 8099. Torrents need a qBittorrent
over TCP and UDP. Files are written as `PUID`/`PGID`, 99:100 by default. of your own, set in `[torrent]` (docs/configuration.md). Files are written as `PUID`/`PGID`, 99:100 by default.
From source: From source:

View File

@@ -30,6 +30,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed ### 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 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). - 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 clap.workspace = true
futures-util.workspace = true futures-util.workspace = true
jsonwebtoken.workspace = true jsonwebtoken.workspace = true
librqbit.workspace = true
opentelemetry.workspace = true opentelemetry.workspace = true
opentelemetry_sdk.workspace = true opentelemetry_sdk.workspace = true
opml.workspace = true opml.workspace = true

View File

@@ -112,10 +112,17 @@ impl Push {
#[serde(default)] #[serde(default)]
pub struct Torrent { pub struct Torrent {
pub enabled: bool, 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_ratio: f64,
pub seed_time_mins: u64, pub seed_time_mins: u64,
pub port_range: String,
/// Drop a torrent that has made no progress for this long. /// Drop a torrent that has made no progress for this long.
pub stall_mins: u64, pub stall_mins: u64,
} }
@@ -265,7 +272,16 @@ impl Default for General {
impl Default for Torrent { impl Default for Torrent {
fn default() -> Self { 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 { impl Torrent {
/// Inclusive listen port range. Falls back to the BitTorrent default on garbage input. /// Torrents are fetched only with somewhere to send them.
pub fn ports(&self) -> (u16, u16) { pub fn on(&self) -> bool {
let parse = || -> Option<(u16, u16)> { self.enabled && !self.qbittorrent_url.trim().is_empty()
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),
}
} }
} }
@@ -714,15 +723,13 @@ mod tests {
} }
#[test] #[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(); let mut t = Torrent::default();
assert_eq!(t.ports(), (6881, 6889)); assert!(!t.on(), "enabled, but nowhere to send them");
t.port_range = "51413-51420".into(); t.qbittorrent_url = "http://qbittorrent:8080".into();
assert_eq!(t.ports(), (51413, 51420)); assert!(t.on());
t.port_range = "nonsense".into(); t.enabled = false;
assert_eq!(t.ports(), (6881, 6889)); assert!(!t.on());
t.port_range = "900-100".into();
assert_eq!(t.ports(), (6881, 6889), "reversed range is not a range");
} }
#[test] #[test]

View File

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

View File

@@ -3,7 +3,7 @@
use crate::catalogue::Sub; use crate::catalogue::Sub;
use crate::ctx::Ctx; use crate::ctx::Ctx;
use crate::ipc::Event; 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 anyhow::Result;
use std::collections::HashSet; use std::collections::HashSet;
use std::path::Path; use std::path::Path;
@@ -533,7 +533,7 @@ pub(crate) async fn scan_one(
for item in ctx.db.pending(id, budget).await? { for item in ctx.db.pending(id, budget).await? {
if download::looks_like_torrent(&item.url, item.mime.as_deref()) { 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.db.mark_enclosure(&item.url, "skipped", Some("torrents disabled")).await?;
ctx.out.emit(Event::TorrentDeferred { feed: id.to_string(), url: item.url.clone() }); ctx.out.emit(Event::TorrentDeferred { feed: id.to_string(), url: item.url.clone() });
scan.torrents += 1; 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 // The MIME lied. Hand the URL to the torrent session instead of filing a .torrent
// as if it were an episode. // as if it were an episode.
let _ = tokio::fs::remove_file(&got.tmp).await; 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?; ctx.db.mark_enclosure(url, "skipped", Some("torrents disabled")).await?;
anyhow::bail!("body is a torrent and torrents are disabled"); 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() }); ctx.out.emit(Event::FeedStart { feed: enc.feed_id.clone() });
let is_torrent = download::looks_like_torrent(&enc.url, enc.mime.as_deref()); 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?; ctx.db.mark_enclosure(&enc.url, "downloading", None).await?;
spawn_torrent(ctx, enc.feed_id.clone(), enc.id, enc.url.clone(), dest_dir); spawn_torrent(ctx, enc.feed_id.clone(), enc.id, enc.url.clone(), dest_dir);
return Ok(()); return Ok(());
} }
let result = if is_torrent { let result = if is_torrent {
if !cfg.torrent.enabled { if !cfg.torrent.on() {
Err(anyhow::anyhow!("torrents are disabled")) Err(anyhow::anyhow!("torrents are disabled"))
} else { } else {
torrent_one(ctx, &enc.feed_id, enc.id, &enc.url, &dest_dir).await.map(Some) 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(); let cfg = ctx.cfg();
ctx.torrents() ctx.torrents()
.await? .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) if let Some(pct) = (done * 100).checked_div(total).map(|p| p as i64)
&& pct > last_pct && 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 }; 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'. // 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.detach_torrents = true;
ctx.torrent_slots = Arc::new(tokio::sync::Semaphore::new(0)); ctx.torrent_slots = Arc::new(tokio::sync::Semaphore::new(0));
let ctx = Arc::new(ctx); let ctx = Arc::new(ctx);
assert_eq!(scan(ctx.clone()).await, (0, 1), "counted as a torrent, not a download"); 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"); assert_eq!(state(ctx).await, ["downloading"], "so the next scan does not queue it again");
// Turned off, it is skipped and still counted. // With no qBittorrent to send it to, it is skipped and still counted.
let mut cfg = config::Config::default(); let ctx = Arc::new(test_ctx(config::Config::default()).await);
cfg.torrent.enabled = false;
let ctx = Arc::new(test_ctx(cfg).await);
assert_eq!(scan(ctx.clone()).await, (0, 1)); assert_eq!(scan(ctx.clone()).await, (0, 1));
assert_eq!(state(ctx).await, ["skipped"]); assert_eq!(state(ctx).await, ["skipped"]);
} }

View File

@@ -1,20 +1,39 @@
//! Torrent enclosures via librqbit. Replaces iPXDownloader.getTorrent and the vendored //! Torrent enclosures through qBittorrent's Web API (#494). ipx fetches the .torrent itself, hands
//! BitTorrent 4.2.1 + khashmir tree. //! 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 anyhow::{Context, Result, anyhow, bail};
use librqbit::{AddTorrent, AddTorrentOptions, AddTorrentResponse, Session, SessionOptions}; use reqwest::header::{COOKIE, SET_COOKIE};
use std::net::SocketAddr; use reqwest::multipart::{Form, Part};
use serde::Deserialize;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use crate::config::Config; use crate::config::Config;
use librqbit::{ListenerOptions, ManagedTorrent};
pub struct Torrents { 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 /// 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. /// this torrentMaxBeatTime and counted display ticks; a wall clock is easier to reason about.
fn stall_limit(cfg: &Config) -> Duration { fn stall_limit(cfg: &Config) -> Duration {
@@ -22,132 +41,175 @@ fn stall_limit(cfg: &Config) -> Duration {
} }
impl Torrents { impl Torrents {
pub async fn new(cfg: &Config) -> Result<Self> { pub fn new() -> Result<Self> {
let (lo, _hi) = cfg.torrent.ports(); let http = reqwest::Client::builder().timeout(Duration::from_secs(30)).build()?;
let listen_addr: SocketAddr = format!("0.0.0.0:{lo}").parse()?; Ok(Self { http, cookie: Default::default() })
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 })
} }
/// Downloads a torrent (a .torrent URL or a magnet link) straight into `dest_dir`, /// Downloads a torrent (a .torrent URL or a magnet link) through qBittorrent into the
/// seeds it up to the configured limit, then stops. `dest_dir` is the torrent's own /// enclosure's own folder inside `feed_dir`, which is the path returned: a file of several or
/// folder (`own_folder`), and it is the path returned: a file of several or one. /// one. Done once qBittorrent has all of it; the seeding is qBittorrent's.
///
/// Downloading in place rather than into a staging dir is deliberate: seeding serves
/// the files it downloaded, so moving them first would break it.
pub async fn fetch( pub async fn fetch(
&self, &self,
cfg: &Config, cfg: &Config,
client: &reqwest::Client, client: &reqwest::Client,
url: &str, url: &str,
dest_dir: &Path, feed_dir: &Path,
enclosure: i64,
mut on_progress: impl FnMut(u64, u64), mut on_progress: impl FnMut(u64, u64),
) -> Result<(PathBuf, 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 limit = stall_limit(cfg);
let source = if url.starts_with("http://") || url.starts_with("https://") { // How ipx finds it again: qBittorrent names a torrent by its hash, which a magnet does not
// Under the stall budget as well: a body sent a byte a minute stays inside the cap. // say until its metadata has come.
let file = tokio::time::timeout(limit, torrent_file(client, url)) let tag = format!("ipx-{enclosure}");
.await
.map_err(|_| anyhow::anyhow!("no .torrent after {} minutes, gave up", limit.as_secs() / 60))??;
AddTorrent::from_bytes(file)
} else {
AddTorrent::from_url(url)
};
// Resolving a magnet's metadata happens inside add_torrent, and against a dead // There already when ipx stopped while it ran (#410): taken up where qBittorrent has it.
// swarm it never returns. The stall budget has to cover this phase too, or a if self.info(cfg, &tag).await?.is_none() {
// torrent nobody is seeding wedges the scan forever. let file = if url.starts_with("http://") || url.starts_with("https://") {
let added = tokio::time::timeout( // Under the stall budget as well: a body sent a byte a minute stays inside the cap.
limit, let got = tokio::time::timeout(limit, torrent_file(client, url))
self.session.add_torrent( .await
source, .map_err(|_| anyhow!("no .torrent after {} minutes, gave up", limit.as_secs() / 60))??;
Some(AddTorrentOptions { Some(got)
output_folder: Some(dest_dir.to_string_lossy().into_owned()), } else {
overwrite: true, None
..Default::default() };
}), let t = &cfg.torrent;
), let save = save_path(cfg, &dir);
) let said = self
.await .api(cfg, "torrents/add", |req| {
.map_err(|_| anyhow::anyhow!("no metadata after {} minutes, gave up", limit.as_secs() / 60))? let form = Form::new()
.context("adding the torrent")?; .text("savepath", save.clone())
.text("tags", tag.clone())
let (id, handle) = match added { // The files straight into the folder, as the path recorded says (#318).
AddTorrentResponse::Added(id, h) | AddTorrentResponse::AlreadyManaged(id, h) => (id, h), .text("contentLayout", "NoSubfolder")
AddTorrentResponse::ListOnly(_) => bail!("torrent added in list-only mode"), .text("ratioLimit", t.seed_ratio.to_string())
}; .text("seedingTimeLimit", t.seed_time_mins.to_string());
req.multipart(match &file {
let mut last_progress = 0u64; Some(b) => form.part("torrents", Part::bytes(b.clone()).file_name("episode.torrent")),
let mut last_move = Instant::now(); None => form.text("urls", url.to_owned()),
})
loop { })
tokio::time::sleep(Duration::from_secs(1)).await; .await?;
let stats = handle.stats(); if said.trim() == "Fails." {
bail!("qBittorrent would not take the torrent; it may have it already");
if let Some(err) = &stats.error {
let _ = self.session.delete(id.into(), false).await;
bail!("torrent failed: {err}");
} }
on_progress(stats.progress_bytes, stats.total_bytes); }
if stats.finished { let mut last = (-1i64, Instant::now());
break; 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 { on_progress(info.completed.max(0) as u64, info.total_size.max(0) as u64);
last_progress = stats.progress_bytes; if info.progress >= 1.0 && info.total_size > 0 {
last_move = Instant::now(); break info;
} else if last_move.elapsed() > limit { }
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. // 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); 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;
} }
Ok((dir, done.total_size as u64))
// 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))
} }
/// Seeds until the ratio or the time limit is reached, whichever comes first. async fn info(&self, cfg: &Config, tag: &str) -> Result<Option<Info>> {
async fn seed(&self, cfg: &Config, handle: &Arc<ManagedTorrent>) { let body = self.api(cfg, "torrents/info", |req| req.form(&[("tag", tag)])).await?;
if cfg.torrent.seed_ratio <= 0.0 || cfg.torrent.seed_time_mins == 0 { let mut all: Vec<Info> = serde_json::from_str(&body).context("reading qBittorrent's torrent list")?;
return; 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(); /// One call to the Web API, signing in first when a user is set, and again once if the session
if ratio(stats.uploaded_bytes, stats.total_bytes) >= cfg.torrent.seed_ratio { /// has expired (a 403). The answer's body.
tracing::info!(ratio = cfg.torrent.seed_ratio, "seed ratio reached"); async fn api(
return; &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 { let resp = req.send().await.with_context(|| format!("asking qBittorrent ({path})"))?;
tracing::info!(mins = cfg.torrent.seed_time_mins, "seed time reached"); if resp.status() == reqwest::StatusCode::FORBIDDEN && !retry && !cfg.torrent.username.is_empty() {
return; 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}")) 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use std::sync::Arc;
fn free_port() -> u16 { /// A qBittorrent that wants a sign-in, and as the feed's server serves the .torrent too. A
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() /// 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>>>) {
/// A swarm on 127.0.0.1: a seeding session holding `file`, and a web server answering for the use axum::http::{HeaderMap, StatusCode};
/// .torrent (`/ep.torrent`) and as its tracker, naming the seed as the one peer. The server's use axum::response::IntoResponse;
/// address, and the seeding session, which stops seeding when dropped. use axum::routing::{get, post};
async fn swarm(file: &Path) -> (SocketAddr, Arc<Session>) { 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 web = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let at = web.local_addr().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 }); tokio::spawn(async move { axum::serve(web, app).await });
(at, deleted)
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)
} }
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn a_detached_torrent_lands_in_its_own_folder_is_recorded_and_frees_its_slot() { 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 root = std::env::temp_dir().join(format!("ipx-torrent-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root); let _ = std::fs::remove_dir_all(&root);
let (seeded, downloads) = (root.join("seed"), root.join("downloads")); let downloads = root.join("downloads");
std::fs::create_dir_all(&seeded).unwrap();
let episode: Vec<u8> = (0..200_000u32).map(|i| (i * 7 % 251) as u8).collect(); 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, deleted) = qbittorrent(episode.clone()).await;
let (at, _seed) = swarm(&seeded.join("episode.mp3")).await;
let mut cfg = Config::default(); let mut cfg = Config::default();
cfg.general.download_dir = downloads.clone(); cfg.general.download_dir = downloads.clone();
cfg.torrent.enabled = true; cfg.general.fetch_internal = vec!["127.0.0.1".into()];
let port = free_port(); cfg.torrent.qbittorrent_url = format!("http://{at}/");
cfg.torrent.port_range = format!("{port}-{port}"); cfg.torrent.username = "ipx".into();
cfg.torrent.password = "pw".into();
cfg.torrent.seed_ratio = 0.0; cfg.torrent.seed_ratio = 0.0;
let mut ctx = crate::test_util::test_ctx(cfg.clone()).await; let mut ctx = crate::test_util::test_ctx(cfg.clone()).await;
ctx.detach_torrents = true; ctx.detach_torrents = true;
@@ -275,7 +339,7 @@ mod tests {
.unwrap(); .unwrap();
crate::scan::spawn_torrent(&ctx, "f".into(), 9, url.clone(), downloads.join("Show")); 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 { loop {
let row = ctx.db.enclosure(9).await.unwrap().unwrap(); let row = ctx.db.enclosure(9).await.unwrap().unwrap();
if row.state != "downloading" { if row.state != "downloading" {
@@ -285,17 +349,32 @@ mod tests {
} }
}) })
.await .await
.expect("the torrent finished within 90 s"); .expect("the torrent finished within 30 s");
let folder = own_folder(&downloads.join("Show"), 9); let folder = own_folder(&downloads.join("Show"), 9);
assert_eq!((row.state.as_str(), row.last_error.as_deref()), ("done", None)); 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!(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!(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. // The slot is let go once the row is written; give the task its moment.
tokio::time::sleep(Duration::from_millis(200)).await; tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(ctx.torrent_slots.available_permits(), 2, "the slot is free again"); assert_eq!(ctx.torrent_slots.available_permits(), 2, "the slot is free again");
let _ = std::fs::remove_dir_all(&root); 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] #[tokio::test]
async fn a_torrent_file_from_an_internal_address_is_refused_unless_allowed() { 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" })); 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] #[tokio::test]
async fn an_endless_torrent_file_stops_at_the_cap() { async fn an_endless_torrent_file_stops_at_the_cap() {
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};

View File

@@ -7,12 +7,9 @@ targets = ["x86_64-unknown-linux-gnu"]
[advisories] [advisories]
ignore = [ ignore = [
# ringbuf 0.4's double free needs an element whose Drop panics; librqbit-utp's buffer holds # chrono is unmaintained, every version, and no vulnerability is known. rss and atom_syndication
# only u8, which has no Drop. Its fix is ringbuf 0.5, which librqbit 9.0.1 cannot take (#281). # depend on it, so ipx's own code moving off it would not take it out (#493).
{ id = "RUSTSEC-2026-0293", reason = "librqbit-utp's ring buffer holds u8: no Drop to panic" }, { id = "RUSTSEC-2026-0543", reason = "unmaintained, not vulnerable; the feed parsers depend on it (#493)" },
# chrono is unmaintained, every version, and no vulnerability is known. rss, atom_syndication and
# librqbit-dht depend on it, so ipx's own code moving off it would not take it out (#493).
{ id = "RUSTSEC-2026-0543", reason = "unmaintained, not vulnerable; the feed parsers and librqbit depend on it (#493)" },
] ]
[licenses] [licenses]

View File

@@ -16,9 +16,6 @@ services:
# For Postgres instead of SQLite: # For Postgres instead of SQLite:
# IPX_DATABASE_URL: "postgres://ipx:password@db-host:5432/ipx" # IPX_DATABASE_URL: "postgres://ipx:password@db-host:5432/ipx"
# No web port of its own: ipx-web is the way in, and passes the API on to it. # No web port of its own: ipx-web is the way in, and passes the API on to it.
ports:
- "6881:6881/tcp" # BitTorrent peers
- "6881:6881/udp" # DHT
volumes: volumes:
- ./config:/config # config.toml, written on first start - ./config:/config # config.toml, written on first start
- ./data:/data # state.db - ./data:/data # state.db

View File

@@ -53,7 +53,7 @@ id, and Caddy's request lines theirs. ipx also serves Prometheus metrics (`[web]
| `crates/feed/src/jev.rs` | Jev's pick of a category | — | | `crates/feed/src/jev.rs` | Jev's pick of a category | — |
| `crates/feed/src/guard.rs` | The connection guard against internal addresses (#320) | — | | `crates/feed/src/guard.rs` | The connection guard against internal addresses (#320) | — |
| `crates/ipx/src/download.rs` | Streaming download, naming, type sniffing, placement | `iPXDownloader.getFile` | | `crates/ipx/src/download.rs` | Streaming download, naming, type sniffing, placement | `iPXDownloader.getFile` |
| `crates/ipx/src/torrent.rs` | librqbit session, seeding limits, stall abort | vendored BitTorrent 4.2.1 | | `crates/ipx/src/torrent.rs` | Hands torrents to qBittorrent's Web API and watches them to the end, stall abort | vendored BitTorrent 4.2.1 |
| `crates/ipx/src/retention.rs` | Quota and age sweeps | `iPXQuotaManager.py` | | `crates/ipx/src/retention.rs` | Quota and age sweeps | `iPXQuotaManager.py` |
| `crates/ipx/src/ipc.rs` | Event and command types, the socket server | `printMSG` on stdout | | `crates/ipx/src/ipc.rs` | Event and command types, the socket server | `printMSG` on stdout |
| `crates/ipx/src/auth.rs` | Argon2id hashing, session tokens, header names | — | | `crates/ipx/src/auth.rs` | Argon2id hashing, session tokens, header names | — |
@@ -102,7 +102,7 @@ and the files, and no page.
a reason. What a filter skipped is judged again every scan, so a change of settings brings it a reason. What a filter skipped is judged again every scan, so a change of settings brings it
back. A feed in a group takes your settings on the group for anything you have not set on it. back. A feed in a group takes your settings on the group for anything you have not set on it.
7. Download what is still pending, newest first, up to the per-scan cap. A `.torrent` body goes to 7. Download what is still pending, newest first, up to the per-scan cap. A `.torrent` body goes to
the torrent path whatever its advertised type; an HTML body is a failed download — a login wall qBittorrent whatever its advertised type; an HTML body is a failed download — a login wall
or an error page — and is deleted. or an error page — and is deleted.
## Data model ## Data model

View File

@@ -89,15 +89,23 @@ database as described above; `download_dir`, `socket`, `organize` and `fetch_int
```toml ```toml
[torrent] [torrent]
enabled = true enabled = true
seed_ratio = 1.0 # stop seeding at this ratio ... qbittorrent_url = "http://qbittorrent:8080" # its Web UI; empty holds torrents back
seed_time_mins = 60 # ... or after this long, whichever comes first username = "ipx" # empty when qBittorrent lets ipx's address in without one
port_range = "6881-6889" password = ""
stall_mins = 30 # give up on a torrent making no progress save_path = "" # where qBittorrent sees download_dir, if not at the same path
seed_ratio = 1.0 # qBittorrent stops seeding at this ratio ...
seed_time_mins = 60 # ... or after this long, whichever comes first
stall_mins = 30 # give up on a torrent making no progress
``` ```
A `.torrent` body is handed to the torrent path whatever MIME type it was advertised as. Torrents Torrents go to [qBittorrent](https://www.qbittorrent.org/) through its Web API: ipx fetches the
run on their own tasks (two at a time) so a slow swarm never blocks a scan. `.torrent` (or passes on the magnet link), adds it with the episode's own folder as its save path,
and records the episode once qBittorrent has all of it. qBittorrent does the seeding. It has to be
able to write to `download_dir`: mount the same folder into its container, and if the path is not
the same as in ipx's, say where in `save_path`. A `.torrent` body is handed to qBittorrent whatever
MIME type it was advertised as. Torrents are watched on their own tasks (two at a time) so a slow
swarm never blocks a scan.
## `[web]` ## `[web]`