An episode deleted takes its torrent out of qBittorrent (#495)

Since #494 qBittorrent seeds a torrent after ipx has it. When the reaper
or Delete removed the episode's folder first, the torrent stayed in
qBittorrent as missing files until someone removed it there by hand.

Both delete paths now ask qBittorrent for the torrent by its ipx-<id> tag
and remove it, files kept (they are already gone). Only for a path that
is the enclosure's own torrent-<id> folder, only when torrents are on,
and in the reaper only once the folder is really gone, so one that would
not delete keeps seeding. Best effort: a qBittorrent not answering is a
warning, never a failed delete.

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:47:58 -05:00
parent c4d7b497fa
commit 8469db6fa2
5 changed files with 56 additions and 6 deletions

View File

@@ -30,7 +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). - Torrents go to qBittorrent through its Web API, set in `[torrent]` (`qbittorrent_url`, `username`, `password`, `save_path`), which downloads and seeds them until the episode is deleted; 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, #495).
- 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

@@ -207,6 +207,19 @@ impl Ctx {
self.directory_wake.notify_one(); self.directory_wake.notify_one();
} }
/// After an enclosure's files are deleted: its torrent, if it was one, out of qBittorrent too
/// (#495). Best effort; the files are gone whatever qBittorrent says.
pub(crate) async fn forget_torrent(&self, enclosure: i64, path: &str) {
let cfg = self.cfg();
if !cfg.torrent.on() || !torrent::is_own_folder(std::path::Path::new(path), enclosure) {
return;
}
match self.torrents().await {
Ok(t) => t.forget(&cfg, enclosure).await,
Err(e) => tracing::warn!(error = %format!("{e:#}"), "no qBittorrent client"),
}
}
pub(crate) async fn torrents(&self) -> Result<&torrent::Torrents> { pub(crate) async fn torrents(&self) -> Result<&torrent::Torrents> {
self.torrents.get_or_try_init(|| async { torrent::Torrents::new() }).await self.torrents.get_or_try_init(|| async { torrent::Torrents::new() }).await
} }

View File

@@ -142,6 +142,10 @@ pub(crate) async fn reap(ctx: &Ctx, dry_run: bool, standalone: bool) -> Result<(
} }
let removed = r.aged_out.iter().chain(r.over_quota.iter()); let removed = r.aged_out.iter().chain(r.over_quota.iter());
for c in removed { for c in removed {
// Only what is really gone: a folder that would not delete keeps seeding.
if !dry_run && !Path::new(&c.path).exists() {
ctx.forget_torrent(c.id, &c.path).await;
}
ctx.out.emit(Event::Reaped { path: c.path.clone(), bytes: c.bytes.max(0) as u64, dry_run }); ctx.out.emit(Event::Reaped { path: c.path.clone(), bytes: c.bytes.max(0) as u64, dry_run });
} }
if standalone { if standalone {

View File

@@ -61,9 +61,7 @@ impl Torrents {
let dir = own_folder(feed_dir, enclosure); let dir = own_folder(feed_dir, enclosure);
tokio::fs::create_dir_all(&dir).await?; tokio::fs::create_dir_all(&dir).await?;
let limit = stall_limit(cfg); let limit = stall_limit(cfg);
// How ipx finds it again: qBittorrent names a torrent by its hash, which a magnet does not let tag = tag(enclosure);
// say until its metadata has come.
let tag = format!("ipx-{enclosure}");
// There already when ipx stopped while it ran (#410): taken up where qBittorrent has it. // There already when ipx stopped while it ran (#410): taken up where qBittorrent has it.
if self.info(cfg, &tag).await?.is_none() { if self.info(cfg, &tag).await?.is_none() {
@@ -128,14 +126,22 @@ impl Torrents {
} }
}; };
// 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 { if cfg.torrent.seed_ratio <= 0.0 || cfg.torrent.seed_time_mins == 0 {
self.delete(cfg, &done.hash).await; self.delete(cfg, &done.hash).await;
} }
Ok((dir, done.total_size as u64)) Ok((dir, done.total_size as u64))
} }
/// Takes an episode's torrent out of qBittorrent once ipx has deleted its files, so it does not
/// stay there seeding nothing, as missing files (#495). Nothing when it is not there.
pub async fn forget(&self, cfg: &Config, enclosure: i64) {
match self.info(cfg, &tag(enclosure)).await {
Ok(Some(info)) => self.delete(cfg, &info.hash).await,
Ok(None) => {}
Err(e) => tracing::warn!(error = %format!("{e:#}"), enclosure, "could not ask qBittorrent for the torrent"),
}
}
async fn info(&self, cfg: &Config, tag: &str) -> Result<Option<Info>> { 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 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")?; let mut all: Vec<Info> = serde_json::from_str(&body).context("reading qBittorrent's torrent list")?;
@@ -203,6 +209,17 @@ impl Torrents {
} }
} }
/// How ipx finds an enclosure's torrent in qBittorrent: by hash it cannot, since a magnet has none
/// until its metadata has come.
fn tag(enclosure: i64) -> String {
format!("ipx-{enclosure}")
}
/// Whether `path` is the folder `fetch` gave `enclosure`: a torrent of ours, then.
pub fn is_own_folder(path: &Path, enclosure: i64) -> bool {
path.file_name() == own_folder(Path::new(""), enclosure).file_name()
}
/// Where qBittorrent is to write `dir`: the same path, or `save_path` in place of `download_dir` /// 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. /// when qBittorrent's mount of it is somewhere else.
fn save_path(cfg: &Config, dir: &Path) -> String { fn save_path(cfg: &Config, dir: &Path) -> String {
@@ -359,12 +376,25 @@ mod tests {
["hashes=h1&deleteFiles=false"], ["hashes=h1&deleteFiles=false"],
"no seeding asked for: let go, files kept" "no seeding asked for: let go, files kept"
); );
// Its files deleted, by the reaper or Delete: out of qBittorrent too, and only a torrent (#495).
deleted.lock().unwrap().clear();
ctx.forget_torrent(9, &downloads.join("Show/episode.mp3").display().to_string()).await;
assert!(deleted.lock().unwrap().is_empty(), "a file that is not a torrent's folder");
ctx.forget_torrent(9, &folder.display().to_string()).await;
assert_eq!(*deleted.lock().unwrap(), ["hashes=h1&deleteFiles=false"]);
// 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 only_an_enclosures_own_folder_is_its_torrent() {
assert!(is_own_folder(&own_folder(Path::new("/downloads/Show"), 9), 9));
assert!(!is_own_folder(&own_folder(Path::new("/downloads/Show"), 9), 19));
assert!(!is_own_folder(Path::new("/downloads/Show/episode.mp3"), 9));
}
#[test] #[test]
fn the_save_path_is_where_qbittorrent_sees_the_folder() { fn the_save_path_is_where_qbittorrent_sees_the_folder() {
let mut cfg = Config::default(); let mut cfg = Config::default();

View File

@@ -2814,6 +2814,9 @@ async fn delete_file(
{ {
return Err(e.into()); return Err(e.into());
} }
if let Some(path) = &enc.path {
state.ctx.forget_torrent(id, path).await;
}
// The row survives as 'reaped', which is what stops the next scan re-downloading it. // The row survives as 'reaped', which is what stops the next scan re-downloading it.
state.ctx.db.mark_reaped(id).await?; state.ctx.db.mark_reaped(id).await?;
state state