diff --git a/crates/ipx/CHANGELOG.md b/crates/ipx/CHANGELOG.md index 8b653aa..1daf3fe 100644 --- a/crates/ipx/CHANGELOG.md +++ b/crates/ipx/CHANGELOG.md @@ -30,7 +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). +- 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 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). diff --git a/crates/ipx/src/ctx.rs b/crates/ipx/src/ctx.rs index d495004..6987cf2 100644 --- a/crates/ipx/src/ctx.rs +++ b/crates/ipx/src/ctx.rs @@ -207,6 +207,19 @@ impl Ctx { 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> { self.torrents.get_or_try_init(|| async { torrent::Torrents::new() }).await } diff --git a/crates/ipx/src/retention.rs b/crates/ipx/src/retention.rs index b3b16b1..b2661c5 100644 --- a/crates/ipx/src/retention.rs +++ b/crates/ipx/src/retention.rs @@ -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()); 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 }); } if standalone { diff --git a/crates/ipx/src/torrent.rs b/crates/ipx/src/torrent.rs index 06531da..520f4e6 100644 --- a/crates/ipx/src/torrent.rs +++ b/crates/ipx/src/torrent.rs @@ -61,9 +61,7 @@ impl Torrents { let dir = own_folder(feed_dir, enclosure); tokio::fs::create_dir_all(&dir).await?; let limit = stall_limit(cfg); - // 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}"); + let tag = tag(enclosure); // There already when ipx stopped while it ran (#410): taken up where qBittorrent has it. 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 { self.delete(cfg, &done.hash).await; } 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> { let body = self.api(cfg, "torrents/info", |req| req.form(&[("tag", tag)])).await?; let mut all: Vec = 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` /// when qBittorrent's mount of it is somewhere else. fn save_path(cfg: &Config, dir: &Path) -> String { @@ -359,12 +376,25 @@ mod tests { ["hashes=h1&deleteFiles=false"], "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. 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 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] fn the_save_path_is_where_qbittorrent_sees_the_folder() { let mut cfg = Config::default(); diff --git a/crates/ipx/src/web.rs b/crates/ipx/src/web.rs index 19a8de9..fbec079 100644 --- a/crates/ipx/src/web.rs +++ b/crates/ipx/src/web.rs @@ -2814,6 +2814,9 @@ async fn delete_file( { 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. state.ctx.db.mark_reaped(id).await?; state