NZB enclosures through SABnzbd, as torrents go through qBittorrent (#496)
An episode published as an .nzb was downloaded as if it were the episode: ipx filed the NZB's XML in the feed's folder. NZBs now go to SABnzbd's API the way torrents go to qBittorrent since #494, down the same path in scan (download::Via says which), in the same two slots, counted with torrents. ipx fetches the .nzb itself through the guarded client, under a 20 MB cap, and adds it under the [nzb] category as nzb-<enclosure>, the name it finds the job by again after a restart (#410). Progress is the queue's MB; the stall clock stops while the history says it is verifying or unpacking, since a large repair is slow. SABnzbd takes no folder per job, only per category, so the category's folder has to be inside download_dir: the finished job is renamed into the episode's own folder (save_path maps SABnzbd's view of the mount onto ipx's) and taken out of the history, so nothing is left for a delete to clean up, unlike #495. Every parameter goes in the request body, the key included: reqwest's errors print the URL, and a key in the query would have reached the log and the episode's error. A wrong key comes back as 200 with status false, read as a refusal. Off, or with no SABnzbd or key, NZBs are skipped as "NZBs disabled", which like "torrents disabled" no filter change overturns. An .nzb body behind a lying MIME type is sniffed and handed on too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U
This commit is contained in:
@@ -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
|
||||
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.
|
||||
- **Downloads.** Files come over HTTP, or BitTorrent through qBittorrent, and are filed into a folder per feed.
|
||||
- **Downloads.** Files come over HTTP, BitTorrent through qBittorrent, or Usenet through SABnzbd, 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
|
||||
an item someone has pinned.
|
||||
- **OPML.** You can import and export your own subscriptions. You can also subscribe to an OPML
|
||||
@@ -38,7 +38,7 @@ docker compose up -d
|
||||
`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
|
||||
Caddy in front of it. Change them to suit. The UI is on port 8099. Torrents need a qBittorrent
|
||||
of your own, set in `[torrent]` (docs/configuration.md). Files are written as `PUID`/`PGID`, 99:100 by default.
|
||||
of your own, set in `[torrent]`, and NZBs a SABnzbd, set in `[nzb]` (docs/configuration.md). Files are written as `PUID`/`PGID`, 99:100 by default.
|
||||
|
||||
From source:
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Added
|
||||
|
||||
- Episodes published as NZBs download through SABnzbd, set in `[nzb]`, as torrents do through qBittorrent; with none set they are held back instead of filed as the episode (#496).
|
||||
- An episode's chapters, from the chapters file its feed names (`<podcast:chapters>`) or else from the downloaded file itself, at `GET /api/enclosures/{id}/chapters`, in the clock of DeadAir's shortened copy when that is what plays; episodes already out pick theirs up at the next scan (#477).
|
||||
- `GET /api/feeds/{id}/seasons` gives a podcast's seasons with how many episodes and unread each has, and a podcast's episodes can be asked for one season at a time, or for those naming none (`season=none`), and in its own order (`sort=episode`), season by season and episode by episode. `download-latest` takes a `season` to download all of it, first episode first (#482).
|
||||
- Smart playlists: `GET` and `POST /api/playlists`, `PATCH` and `DELETE /api/playlists/{id}`, and `GET /api/playlists/{id}/entries`, the episodes of the podcasts chosen in the playlist's order, those set to play first ahead of the rest (#476).
|
||||
|
||||
@@ -14,6 +14,8 @@ pub struct Config {
|
||||
#[serde(default)]
|
||||
pub torrent: Torrent,
|
||||
#[serde(default)]
|
||||
pub nzb: Nzb,
|
||||
#[serde(default)]
|
||||
pub web: Web,
|
||||
#[serde(default)]
|
||||
pub push: Push,
|
||||
@@ -127,6 +129,43 @@ pub struct Torrent {
|
||||
pub stall_mins: u64,
|
||||
}
|
||||
|
||||
/// NZB enclosures, sent to SABnzbd (#496) as torrents are to qBittorrent.
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(default)]
|
||||
pub struct Nzb {
|
||||
pub enabled: bool,
|
||||
/// SABnzbd's web address, e.g. "http://sabnzbd:8080". Empty: NZBs are held back.
|
||||
pub sabnzbd_url: String,
|
||||
pub api_key: String,
|
||||
/// The category jobs are added under. Its folder in SABnzbd has to be inside `download_dir`,
|
||||
/// where ipx can move the finished job from.
|
||||
pub category: String,
|
||||
/// Where SABnzbd sees `download_dir`, when its mount is not at the same path as ipx's.
|
||||
pub save_path: String,
|
||||
/// Drop an NZB that has made no progress for this long.
|
||||
pub stall_mins: u64,
|
||||
}
|
||||
|
||||
impl Default for Nzb {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
sabnzbd_url: String::new(),
|
||||
api_key: String::new(),
|
||||
category: "ipx".into(),
|
||||
save_path: String::new(),
|
||||
stall_mins: 30,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Nzb {
|
||||
/// NZBs are fetched only with somewhere to send them.
|
||||
pub fn on(&self) -> bool {
|
||||
self.enabled && !self.sabnzbd_url.trim().is_empty() && !self.api_key.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(default)]
|
||||
pub struct Web {
|
||||
@@ -554,8 +593,8 @@ pub fn wanted_media(mime: Option<&str>, wanted: &[String]) -> bool {
|
||||
return true;
|
||||
};
|
||||
let top = mime.split('/').next().unwrap_or(mime).to_ascii_lowercase();
|
||||
// A .torrent is a container for media, not media itself; judge it once unpacked.
|
||||
if mime.to_ascii_lowercase().contains("torrent") {
|
||||
// A .torrent or an .nzb is a container for media, not media itself; judge it once unpacked.
|
||||
if ["torrent", "nzb"].iter().any(|c| mime.to_ascii_lowercase().contains(c)) {
|
||||
return true;
|
||||
}
|
||||
wanted.iter().any(|w| w.trim().eq_ignore_ascii_case(&top) || w.trim().eq_ignore_ascii_case(mime))
|
||||
@@ -743,6 +782,7 @@ mod tests {
|
||||
|
||||
// A torrent is a container; what is inside is judged after unpacking.
|
||||
assert!(wanted_media(Some("application/x-bittorrent"), &want));
|
||||
assert!(wanted_media(Some("application/x-nzb"), &want));
|
||||
// Unknown type: only discoverable by downloading, so do not refuse it outright.
|
||||
assert!(wanted_media(None, &want));
|
||||
assert!(wanted_media(Some(""), &want));
|
||||
|
||||
@@ -3022,7 +3022,7 @@ impl Db {
|
||||
self.rows(
|
||||
"SELECT url, last_error FROM enclosures
|
||||
WHERE feed_id = $1 AND state = 'skipped' AND last_error IS NOT NULL
|
||||
AND last_error <> 'torrents disabled'",
|
||||
AND last_error NOT IN ('torrents disabled', 'NZBs disabled')",
|
||||
vec![feed_id.into()],
|
||||
)
|
||||
.await?
|
||||
|
||||
@@ -114,8 +114,32 @@ fn disposition_filename(header: &str) -> Option<String> {
|
||||
/// What the download turned out to be, once the bytes were on disk.
|
||||
pub enum Kind {
|
||||
File,
|
||||
/// A .torrent body, whatever the advertised MIME said. Step 7 takes it from here.
|
||||
/// A .torrent or an .nzb body, whatever the advertised MIME said: handed on, not filed.
|
||||
Via(Via),
|
||||
}
|
||||
|
||||
/// Where an enclosure goes instead of being downloaded here: a torrent to qBittorrent (#494), an
|
||||
/// NZB to SABnzbd (#496).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Via {
|
||||
Torrent,
|
||||
Nzb,
|
||||
}
|
||||
|
||||
impl Via {
|
||||
pub fn on(self, cfg: &Config) -> bool {
|
||||
match self {
|
||||
Via::Torrent => cfg.torrent.on(),
|
||||
Via::Nzb => cfg.nzb.on(),
|
||||
}
|
||||
}
|
||||
/// The `last_error` of one held back while its kind is off, which no filter can overturn.
|
||||
pub fn off(self) -> &'static str {
|
||||
match self {
|
||||
Via::Torrent => "torrents disabled",
|
||||
Via::Nzb => "NZBs disabled",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Downloaded {
|
||||
@@ -174,7 +198,8 @@ pub async fn download(
|
||||
let _ = tokio::fs::remove_file(&tmp).await;
|
||||
bail!("server returned an HTML page, not a media file");
|
||||
}
|
||||
Sniffed::Torrent => Kind::Torrent,
|
||||
Sniffed::Torrent => Kind::Via(Via::Torrent),
|
||||
Sniffed::Nzb => Kind::Via(Via::Nzb),
|
||||
Sniffed::Other => Kind::File,
|
||||
};
|
||||
|
||||
@@ -220,15 +245,23 @@ pub fn playable(path: &Path) -> PathBuf {
|
||||
best.map_or_else(|| path.to_owned(), |(_, p)| p)
|
||||
}
|
||||
|
||||
/// Advertised as a torrent, before spending any bandwidth on it.
|
||||
pub fn looks_like_torrent(url: &str, mime: Option<&str>) -> bool {
|
||||
mime.is_some_and(|m| m.to_ascii_lowercase().contains("torrent"))
|
||||
|| url.split('?').next().unwrap_or(url).to_ascii_lowercase().ends_with(".torrent")
|
||||
/// Advertised as a torrent or an NZB, before spending any bandwidth on it.
|
||||
pub fn handed_on(url: &str, mime: Option<&str>) -> Option<Via> {
|
||||
let mime = mime.unwrap_or("").to_ascii_lowercase();
|
||||
let path = url.split('?').next().unwrap_or(url).to_ascii_lowercase();
|
||||
if mime.contains("torrent") || path.ends_with(".torrent") {
|
||||
Some(Via::Torrent)
|
||||
} else if mime.contains("nzb") || path.ends_with(".nzb") {
|
||||
Some(Via::Nzb)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
enum Sniffed {
|
||||
Html,
|
||||
Torrent,
|
||||
Nzb,
|
||||
Other,
|
||||
}
|
||||
|
||||
@@ -244,6 +277,12 @@ async fn sniff(path: &Path) -> Result<Sniffed> {
|
||||
if lead.starts_with("<!doctype html") || lead.starts_with("<html") {
|
||||
return Ok(Sniffed::Html);
|
||||
}
|
||||
if lead.starts_with("<!doctype nzb")
|
||||
|| lead.starts_with("<nzb")
|
||||
|| lead.starts_with("<?xml") && lead.contains("<nzb")
|
||||
{
|
||||
return Ok(Sniffed::Nzb);
|
||||
}
|
||||
Ok(Sniffed::Other)
|
||||
}
|
||||
|
||||
@@ -423,6 +462,15 @@ mod tests {
|
||||
assert_eq!(folder_for(&cfg, "id", &f, None), "etc/Show");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn torrents_and_nzbs_are_told_by_type_or_by_name() {
|
||||
assert_eq!(handed_on("http://x/a.mp3", Some("application/x-bittorrent")), Some(Via::Torrent));
|
||||
assert_eq!(handed_on("http://x/a.TORRENT?k=1", None), Some(Via::Torrent));
|
||||
assert_eq!(handed_on("http://x/a", Some("application/x-nzb")), Some(Via::Nzb));
|
||||
assert_eq!(handed_on("http://x/get.nzb?id=3", Some("")), Some(Via::Nzb));
|
||||
assert_eq!(handed_on("http://x/a.mp3?f=.nzb", Some("audio/mpeg")), None, "the query is not the name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_torrent_folder_plays_its_largest_file_and_deletes_whole() {
|
||||
let d = std::env::temp_dir().join(format!("ipx-torrent-test-{}", std::process::id()));
|
||||
@@ -464,6 +512,7 @@ mod tests {
|
||||
.route("/ep.mp3", get(|| async { "ID3 an episode" }))
|
||||
.route("/wall.mp3", get(|| async { "\n <!DOCTYPE html><html>Sign in</html>" }))
|
||||
.route("/show.torrent", get(|| async { "d8:announce35:udp://tracker.example:80/announcee" }))
|
||||
.route("/show.nzb", get(|| async { "<?xml version=\"1.0\"?>\n<!DOCTYPE nzb><nzb xmlns=\"x\"/>" }))
|
||||
.route("/gone.mp3", get(|| async { axum::http::StatusCode::NOT_FOUND }));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let at = listener.local_addr().unwrap();
|
||||
@@ -500,7 +549,8 @@ mod tests {
|
||||
assert!(format!("{wall:#}").contains("HTML page"), "{wall:#}");
|
||||
assert!(!d.join(".ipx-incomplete/wall.mp3").exists(), "a login page is not kept");
|
||||
|
||||
assert!(matches!(get("/show.torrent").await.unwrap().kind, Kind::Torrent));
|
||||
assert!(matches!(get("/show.torrent").await.unwrap().kind, Kind::Via(Via::Torrent)));
|
||||
assert!(matches!(get("/show.nzb").await.unwrap().kind, Kind::Via(Via::Nzb)), "an NZB is not an episode (#496)");
|
||||
assert!(format!("{:#}", get("/gone.mp3").await.err().unwrap()).contains("404"));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ mod lists;
|
||||
mod logbuf;
|
||||
mod logging;
|
||||
mod metrics;
|
||||
mod nzb;
|
||||
mod play;
|
||||
mod push;
|
||||
mod retention;
|
||||
|
||||
349
crates/ipx/src/nzb.rs
Normal file
349
crates/ipx/src/nzb.rs
Normal file
@@ -0,0 +1,349 @@
|
||||
//! NZB enclosures through SABnzbd's API (#496), the way torrents go through qBittorrent (#494).
|
||||
//! ipx fetches the .nzb itself, adds it under a category of its own with a job name it can find
|
||||
//! again, follows it through the queue and post-processing, and moves the finished folder into
|
||||
//! the enclosure's own. SABnzbd takes no save path for a job, only a category's folder, so that
|
||||
//! folder has to be one ipx can see, inside `download_dir`.
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use reqwest::multipart::{Form, Part};
|
||||
use serde::Deserialize;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::LazyLock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::config::Config;
|
||||
|
||||
/// Not the guarded client feeds are fetched with: SABnzbd is on the LAN by design, at the address
|
||||
/// the admin gave, which the guard would refuse (#320).
|
||||
static HTTP: LazyLock<reqwest::Client> =
|
||||
LazyLock::new(|| reqwest::Client::builder().timeout(Duration::from_secs(30)).build().expect("a client"));
|
||||
|
||||
/// One job in the queue, as much as ipx reads. SABnzbd gives sizes there as strings of MB.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
struct Queued {
|
||||
nzo_id: String,
|
||||
filename: String,
|
||||
mb: String,
|
||||
mbleft: String,
|
||||
}
|
||||
|
||||
/// One job in the history: downloaded, and being or done being post-processed.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
struct Done {
|
||||
nzo_id: String,
|
||||
name: String,
|
||||
status: String,
|
||||
storage: String,
|
||||
bytes: i64,
|
||||
fail_message: String,
|
||||
}
|
||||
|
||||
enum Job {
|
||||
Queued(Queued),
|
||||
Done(Done),
|
||||
}
|
||||
|
||||
const POLL: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Downloads an NZB through SABnzbd into the enclosure's own folder inside `feed_dir`, which is the
|
||||
/// path returned, with its size.
|
||||
pub async fn fetch(
|
||||
cfg: &Config,
|
||||
client: &reqwest::Client,
|
||||
url: &str,
|
||||
feed_dir: &Path,
|
||||
enclosure: i64,
|
||||
mut on_progress: impl FnMut(u64, u64),
|
||||
) -> Result<(PathBuf, u64)> {
|
||||
let limit = Duration::from_secs(cfg.nzb.stall_mins.max(1) * 60);
|
||||
let name = job_name(enclosure);
|
||||
|
||||
// There already when ipx stopped while it ran (#410): taken up where SABnzbd has it.
|
||||
if find(cfg, &name).await?.is_none() {
|
||||
// Under the stall budget as well: a body sent a byte a minute stays inside the cap.
|
||||
let file = tokio::time::timeout(limit, nzb_file(client, url))
|
||||
.await
|
||||
.map_err(|_| anyhow!("no .nzb after {} minutes, gave up", limit.as_secs() / 60))??;
|
||||
let form = Form::new().part("name", Part::bytes(file).file_name(format!("{name}.nzb")));
|
||||
let said: Added =
|
||||
call(cfg, &[("mode", "addfile"), ("nzbname", &name), ("cat", &cfg.nzb.category)], Some(form)).await?;
|
||||
if said.nzo_ids.is_empty() {
|
||||
bail!("SABnzbd would not take the NZB");
|
||||
}
|
||||
}
|
||||
|
||||
let mut last = (-1i64, Instant::now());
|
||||
let done = loop {
|
||||
tokio::time::sleep(POLL).await;
|
||||
// A SABnzbd restarting is a pause, not a failure, until the stall limit says so.
|
||||
let job = match find(cfg, &name).await {
|
||||
Ok(j) => j,
|
||||
Err(e) if last.1.elapsed() < limit => {
|
||||
tracing::debug!(error = %format!("{e:#}"), "SABnzbd did not answer");
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let left = match job {
|
||||
None => bail!("the NZB is no longer in SABnzbd"),
|
||||
Some(Job::Done(d)) if d.status == "Completed" => break d,
|
||||
Some(Job::Done(d)) if d.status == "Failed" => {
|
||||
forget(cfg, "history", &d.nzo_id).await;
|
||||
bail!("SABnzbd says the download failed: {}", d.fail_message);
|
||||
}
|
||||
// Verifying, repairing, unpacking: all of it is here, and a large repair is slow.
|
||||
Some(Job::Done(_)) => {
|
||||
last.1 = Instant::now();
|
||||
continue;
|
||||
}
|
||||
Some(Job::Queued(q)) => {
|
||||
let mb = |s: &str| (s.trim().parse::<f64>().unwrap_or(0.0) * 1_048_576.0) as i64;
|
||||
let (total, left) = (mb(&q.mb), mb(&q.mbleft));
|
||||
on_progress((total - left).max(0) as u64, total.max(0) as u64);
|
||||
(left, q)
|
||||
}
|
||||
};
|
||||
let (left, q) = left;
|
||||
if last.0 < 0 || left < last.0 {
|
||||
last = (left, Instant::now());
|
||||
} else if last.1.elapsed() > limit {
|
||||
forget(cfg, "queue", &q.nzo_id).await;
|
||||
bail!("no progress for {} minutes, gave up", limit.as_secs() / 60);
|
||||
}
|
||||
};
|
||||
|
||||
let dir = feed_dir.join(&name);
|
||||
let from = their_path(cfg, Path::new(&done.storage));
|
||||
tokio::fs::create_dir_all(feed_dir).await?;
|
||||
if tokio::fs::metadata(&from).await.with_context(|| format!("finding {}", from.display()))?.is_dir() {
|
||||
tokio::fs::rename(&from, &dir).await
|
||||
} else {
|
||||
tokio::fs::create_dir_all(&dir).await?;
|
||||
tokio::fs::rename(&from, dir.join(from.file_name().unwrap_or_default())).await
|
||||
}
|
||||
// shortcut: a rename only, so SABnzbd's category folder must be on the same mount as
|
||||
// download_dir; copy across filesystems if one ever is not.
|
||||
.with_context(|| format!("moving {} into {}", from.display(), dir.display()))?;
|
||||
// Out of the history once its files are ipx's, so nothing there points at a folder gone.
|
||||
forget(cfg, "history", &done.nzo_id).await;
|
||||
Ok((dir, done.bytes.max(0) as u64))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Added {
|
||||
#[serde(default)]
|
||||
nzo_ids: Vec<String>,
|
||||
}
|
||||
|
||||
/// The job by its name, in the queue or the history.
|
||||
async fn find(cfg: &Config, name: &str) -> Result<Option<Job>> {
|
||||
#[derive(Deserialize)]
|
||||
struct Slots<T> {
|
||||
slots: Vec<T>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Q {
|
||||
queue: Slots<Queued>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct H {
|
||||
history: Slots<Done>,
|
||||
}
|
||||
// search matches part of a name, so nzb-9 finds nzb-90 too: the exact one is picked out.
|
||||
let q: Q = call(cfg, &[("mode", "queue"), ("search", name)], None).await?;
|
||||
if let Some(j) = q.queue.slots.into_iter().find(|s| s.filename == name) {
|
||||
return Ok(Some(Job::Queued(j)));
|
||||
}
|
||||
let h: H = call(cfg, &[("mode", "history"), ("search", name)], None).await?;
|
||||
Ok(h.history.slots.into_iter().find(|s| s.name == name).map(Job::Done))
|
||||
}
|
||||
|
||||
/// Takes a job out of the queue or the history, its files with it from the queue (they are half
|
||||
/// of a download), not from the history (they are the episode's, or already moved). Logged, not
|
||||
/// raised: what called it is already giving up, or done.
|
||||
async fn forget(cfg: &Config, from: &str, nzo_id: &str) {
|
||||
let files = if from == "queue" { "1" } else { "0" };
|
||||
let query = [("mode", from), ("name", "delete"), ("value", nzo_id), ("del_files", files)];
|
||||
if let Err(e) = call::<serde_json::Value>(cfg, &query, None).await {
|
||||
tracing::warn!(error = %format!("{e:#}"), "could not remove the NZB from SABnzbd");
|
||||
}
|
||||
}
|
||||
|
||||
/// One call to the API. SABnzbd answers a wrong key or a bad call with 200 and `status: false`.
|
||||
/// Everything goes in the body, which SABnzbd reads as it reads a query: reqwest's errors say the
|
||||
/// URL, and the key in it would have gone to the log and the episode's error.
|
||||
async fn call<T: serde::de::DeserializeOwned>(cfg: &Config, query: &[(&str, &str)], form: Option<Form>) -> Result<T> {
|
||||
let n = &cfg.nzb;
|
||||
let url = format!("{}/api", n.sabnzbd_url.trim_end_matches('/'));
|
||||
let mode = query.first().map_or("", |q| q.1);
|
||||
let params = query.iter().copied().chain([("apikey", n.api_key.as_str()), ("output", "json")]);
|
||||
let req = match form {
|
||||
Some(f) => HTTP.post(url).multipart(params.fold(f, |f, (k, v)| f.text(k.to_owned(), v.to_owned()))),
|
||||
None => HTTP.post(url).form(¶ms.collect::<Vec<_>>()),
|
||||
};
|
||||
let body = req
|
||||
.send()
|
||||
.await
|
||||
.with_context(|| format!("asking SABnzbd ({mode})"))?
|
||||
.error_for_status()
|
||||
.with_context(|| format!("SABnzbd refused {mode}"))?
|
||||
.text()
|
||||
.await?;
|
||||
let v: serde_json::Value = serde_json::from_str(&body).with_context(|| format!("reading SABnzbd's {mode}"))?;
|
||||
if v.get("status") == Some(&serde_json::Value::Bool(false)) {
|
||||
bail!("SABnzbd refused {mode}: {}", v.get("error").and_then(|e| e.as_str()).unwrap_or("no reason given"));
|
||||
}
|
||||
serde_json::from_value(v).with_context(|| format!("reading SABnzbd's {mode}"))
|
||||
}
|
||||
|
||||
/// The job's name in SABnzbd, which is also the folder it finishes in.
|
||||
fn job_name(enclosure: i64) -> String {
|
||||
format!("nzb-{enclosure}")
|
||||
}
|
||||
|
||||
/// Where ipx sees a path SABnzbd gave: `download_dir` in place of `save_path` when SABnzbd's mount
|
||||
/// of it is somewhere else.
|
||||
fn their_path(cfg: &Config, path: &Path) -> PathBuf {
|
||||
let theirs = cfg.nzb.save_path.trim();
|
||||
match path.strip_prefix(theirs) {
|
||||
Ok(rest) if !theirs.is_empty() => cfg.general.download_dir.join(rest),
|
||||
_ => path.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// An NZB lists the articles of a release: a few MB even for a large one.
|
||||
const MAX_NZB_FILE: usize = 20 << 20;
|
||||
|
||||
async fn nzb_file(client: &reqwest::Client, url: &str) -> Result<Vec<u8>> {
|
||||
let mut resp = client.get(url).send().await.context("fetching the .nzb")?.error_for_status()?;
|
||||
let mut out = Vec::new();
|
||||
while let Some(c) = resp.chunk().await.context("reading the .nzb")? {
|
||||
out.extend_from_slice(&c);
|
||||
if out.len() > MAX_NZB_FILE {
|
||||
bail!("the .nzb is larger than {} MB, too large to be one", MAX_NZB_FILE >> 20);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// A SABnzbd that, as the feed's server, serves the .nzb too. A job added is finished at once,
|
||||
/// into its category's folder, and is in the history after one look at the queue. Its address,
|
||||
/// and the calls it was asked to delete.
|
||||
async fn sabnzbd(category_dir: PathBuf, episode: Vec<u8>) -> (std::net::SocketAddr, Arc<Mutex<Vec<String>>>) {
|
||||
use axum::routing::{get, post};
|
||||
use std::collections::HashMap;
|
||||
type Jobs = Arc<Mutex<Vec<(String, u8)>>>;
|
||||
let jobs: Jobs = Default::default();
|
||||
let deleted: Arc<Mutex<Vec<String>>> = Default::default();
|
||||
let (j, d) = (jobs.clone(), deleted.clone());
|
||||
let app = axum::Router::new().route("/ep.nzb", get(|| async { "<?xml version=\"1.0\"?><nzb/>" })).route(
|
||||
"/api",
|
||||
post(move |body: axum::body::Bytes| async move {
|
||||
// Either form: a multipart body read as text is enough to find a field's value.
|
||||
let text = String::from_utf8_lossy(&body);
|
||||
let q: HashMap<String, String> = if text.contains("Content-Disposition") {
|
||||
let field = |p: &str| {
|
||||
let (k, rest) = p.split_once('"')?;
|
||||
Some((k.to_owned(), rest.split_once("\r\n\r\n")?.1.split("\r\n").next()?.to_owned()))
|
||||
};
|
||||
text.split("; name=\"").skip(1).filter_map(field).collect()
|
||||
} else {
|
||||
url::form_urlencoded::parse(&body).into_owned().collect()
|
||||
};
|
||||
if q["apikey"] != "key" {
|
||||
return axum::Json(serde_json::json!({"status": false, "error": "API Key Incorrect"}));
|
||||
}
|
||||
let mut jobs = j.lock().unwrap();
|
||||
let name = q.get("search").or(q.get("nzbname")).cloned().unwrap_or_default();
|
||||
match q["mode"].as_str() {
|
||||
"addfile" => {
|
||||
assert_eq!(q["cat"], "ipx");
|
||||
assert!(q["name"].starts_with("<?xml"), "the .nzb ipx fetched");
|
||||
let folder = category_dir.join(&name);
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
std::fs::write(folder.join("episode.mp3"), &episode).unwrap();
|
||||
jobs.push((name, 0));
|
||||
axum::Json(serde_json::json!({"status": true, "nzo_ids": ["SABnzbd_nzo_1"]}))
|
||||
}
|
||||
_ if q.get("name").is_some_and(|n| n == "delete") => {
|
||||
d.lock().unwrap().push(format!("{} {} {}", q["mode"], q["value"], q["del_files"]));
|
||||
jobs.clear();
|
||||
axum::Json(serde_json::json!({"status": true}))
|
||||
}
|
||||
"queue" => {
|
||||
let slots: Vec<_> = jobs.iter_mut().filter(|(n, _)| n.contains(&name)).filter(|(_, s)| *s == 0).map(|(n, s)| {
|
||||
*s = 1;
|
||||
serde_json::json!({"nzo_id": "SABnzbd_nzo_1", "filename": n, "mb": "2.0", "mbleft": "1.0"})
|
||||
}).collect();
|
||||
axum::Json(serde_json::json!({"queue": {"slots": slots}}))
|
||||
}
|
||||
"history" => {
|
||||
let slots: Vec<_> = jobs.iter().filter(|(n, s)| n.contains(&name) && *s == 1).map(|(n, _)| serde_json::json!({
|
||||
"nzo_id": "SABnzbd_nzo_1", "name": n, "status": "Completed", "bytes": episode.len(),
|
||||
"storage": format!("/sab/ipx/{n}"),
|
||||
})).collect();
|
||||
axum::Json(serde_json::json!({"history": {"slots": slots}}))
|
||||
}
|
||||
m => panic!("no mode {m}"),
|
||||
}
|
||||
}),
|
||||
);
|
||||
let web = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let at = web.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(web, app).await });
|
||||
(at, deleted)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_nzb_lands_in_its_own_folder_and_leaves_sabnzbd_s_history() {
|
||||
let root = std::env::temp_dir().join(format!("ipx-nzb-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let downloads = root.join("downloads");
|
||||
let episode: Vec<u8> = (0..50_000u32).map(|i| (i % 251) as u8).collect();
|
||||
let (at, deleted) = sabnzbd(downloads.join("ipx"), episode.clone()).await;
|
||||
|
||||
let mut cfg = Config::default();
|
||||
cfg.general.download_dir = downloads.clone();
|
||||
cfg.nzb.sabnzbd_url = format!("http://{at}/");
|
||||
cfg.nzb.api_key = "key".into();
|
||||
// SABnzbd sees download_dir as /sab, and its category's folder inside it.
|
||||
cfg.nzb.save_path = "/sab".into();
|
||||
|
||||
let mut seen = Vec::new();
|
||||
let (path, bytes) =
|
||||
fetch(&cfg, &reqwest::Client::new(), &format!("http://{at}/ep.nzb"), &downloads.join("Show"), 9, |d, t| {
|
||||
seen.push((d, t))
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(path, downloads.join("Show/nzb-9"));
|
||||
assert_eq!(bytes, episode.len() as u64);
|
||||
assert_eq!(std::fs::read(path.join("episode.mp3")).unwrap(), episode);
|
||||
assert_eq!(seen, [(1 << 20, 2 << 20)], "progress from the queue's MB");
|
||||
assert_eq!(*deleted.lock().unwrap(), ["history SABnzbd_nzo_1 0"], "out of the history, files kept");
|
||||
|
||||
cfg.nzb.api_key = "wrong".into();
|
||||
let err = fetch(&cfg, &reqwest::Client::new(), &format!("http://{at}/ep.nzb"), &downloads, 10, |_, _| {})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(format!("{err:#}").contains("API Key Incorrect"), "{err:#}");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_sabnzbd_gives_is_where_ipx_sees_it() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.general.download_dir = "/downloads".into();
|
||||
let p = Path::new("/ipx-downloads/.sabnzbd/nzb-9");
|
||||
assert_eq!(their_path(&cfg, p), p, "the same mount");
|
||||
cfg.nzb.save_path = "/ipx-downloads".into();
|
||||
assert_eq!(their_path(&cfg, p), Path::new("/downloads/.sabnzbd/nzb-9"));
|
||||
}
|
||||
}
|
||||
@@ -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};
|
||||
use crate::{catalogue, cli, config, db, download, feed, lists, metrics, nzb, signals};
|
||||
use anyhow::Result;
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
@@ -532,9 +532,10 @@ pub(crate) async fn scan_one(
|
||||
let dest_dir = cfg.general.download_dir.join(&folder);
|
||||
|
||||
for item in ctx.db.pending(id, budget).await? {
|
||||
if download::looks_like_torrent(&item.url, item.mime.as_deref()) {
|
||||
if !ctx.cfg().torrent.on() {
|
||||
ctx.db.mark_enclosure(&item.url, "skipped", Some("torrents disabled")).await?;
|
||||
// NZBs go the torrents' way and are counted with them (#496).
|
||||
if let Some(via) = download::handed_on(&item.url, item.mime.as_deref()) {
|
||||
if !via.on(&ctx.cfg()) {
|
||||
ctx.db.mark_enclosure(&item.url, "skipped", Some(via.off())).await?;
|
||||
ctx.out.emit(Event::TorrentDeferred { feed: id.to_string(), url: item.url.clone() });
|
||||
scan.torrents += 1;
|
||||
continue;
|
||||
@@ -542,11 +543,11 @@ pub(crate) async fn scan_one(
|
||||
if ctx.detach_torrents {
|
||||
// 'downloading' keeps the next scan from queueing it a second time.
|
||||
ctx.db.mark_enclosure(&item.url, "downloading", None).await?;
|
||||
spawn_torrent(ctx, id.to_string(), item.id, item.url.clone(), dest_dir.clone());
|
||||
spawn_torrent(ctx, via, id.to_string(), item.id, item.url.clone(), dest_dir.clone());
|
||||
scan.torrents += 1;
|
||||
continue;
|
||||
}
|
||||
match torrent_one(ctx, id, item.id, &item.url, &dest_dir).await {
|
||||
match torrent_one(ctx, via, id, item.id, &item.url, &dest_dir).await {
|
||||
Ok((path, bytes)) => {
|
||||
ctx.db.mark_downloaded(&item.url, &path, bytes).await?;
|
||||
ctx.out.emit(Event::DownloadDone {
|
||||
@@ -746,23 +747,23 @@ pub(crate) async fn fetch_one(
|
||||
})
|
||||
.await?;
|
||||
|
||||
if matches!(got.kind, download::Kind::Torrent) {
|
||||
// The MIME lied. Hand the URL to the torrent session instead of filing a .torrent
|
||||
// as if it were an episode.
|
||||
if let download::Kind::Via(via) = got.kind {
|
||||
// The MIME lied. Hand the URL to qBittorrent or SABnzbd instead of filing a .torrent or
|
||||
// an .nzb as if it were an episode.
|
||||
let _ = tokio::fs::remove_file(&got.tmp).await;
|
||||
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");
|
||||
if !via.on(&ctx.cfg()) {
|
||||
ctx.db.mark_enclosure(url, "skipped", Some(via.off())).await?;
|
||||
anyhow::bail!("body is a {via:?} and {}", via.off());
|
||||
}
|
||||
// As one advertised as a torrent goes: off the worker where it can be, and recorded either
|
||||
// way. Run here and never recorded, it stayed pending, and every scan of its feed ran it
|
||||
// again, on the worker, for up to the stall limit and the seeding time (#155).
|
||||
if ctx.detach_torrents {
|
||||
ctx.db.mark_enclosure(url, "downloading", None).await?;
|
||||
spawn_torrent(ctx, feed_id.to_owned(), enclosure, url.to_owned(), dest_dir.to_owned());
|
||||
spawn_torrent(ctx, via, feed_id.to_owned(), enclosure, url.to_owned(), dest_dir.to_owned());
|
||||
return Ok(None);
|
||||
}
|
||||
let (path, bytes) = torrent_one(ctx, feed_id, enclosure, url, dest_dir).await?;
|
||||
let (path, bytes) = torrent_one(ctx, via, feed_id, enclosure, url, dest_dir).await?;
|
||||
ctx.db.mark_downloaded(url, &path, bytes).await?;
|
||||
return Ok(Some((path, bytes)));
|
||||
}
|
||||
@@ -772,9 +773,16 @@ pub(crate) async fn fetch_one(
|
||||
Ok(Some((path, got.bytes)))
|
||||
}
|
||||
|
||||
/// Runs a torrent off the command worker, so feed scans and HTTP downloads keep moving
|
||||
/// while it fetches metadata, transfers and then seeds.
|
||||
pub(crate) fn spawn_torrent(ctx: &Arc<Ctx>, feed_id: String, enclosure: i64, url: String, dest_dir: PathBuf) {
|
||||
/// Runs a torrent or an NZB off the command worker, so feed scans and HTTP downloads keep moving
|
||||
/// while qBittorrent or SABnzbd has it.
|
||||
pub(crate) fn spawn_torrent(
|
||||
ctx: &Arc<Ctx>,
|
||||
via: download::Via,
|
||||
feed_id: String,
|
||||
enclosure: i64,
|
||||
url: String,
|
||||
dest_dir: PathBuf,
|
||||
) {
|
||||
let ctx = ctx.clone();
|
||||
tokio::spawn(async move {
|
||||
// Held for the whole job, so a feed full of torrents cannot open hundreds at once.
|
||||
@@ -782,7 +790,7 @@ pub(crate) fn spawn_torrent(ctx: &Arc<Ctx>, feed_id: String, enclosure: i64, url
|
||||
Ok(p) => p,
|
||||
Err(_) => return,
|
||||
};
|
||||
let outcome = torrent_one(&ctx, &feed_id, enclosure, &url, &dest_dir).await;
|
||||
let outcome = torrent_one(&ctx, via, &feed_id, enclosure, &url, &dest_dir).await;
|
||||
let db = &ctx.db;
|
||||
match outcome {
|
||||
Ok((path, bytes)) => {
|
||||
@@ -830,20 +838,19 @@ pub(crate) async fn download_one(ctx: &Arc<Ctx>, id: i64) -> Result<()> {
|
||||
let dest_dir = cfg.general.download_dir.join(&folder);
|
||||
|
||||
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.on() && ctx.detach_torrents {
|
||||
let via = download::handed_on(&enc.url, enc.mime.as_deref());
|
||||
if let Some(via) = via
|
||||
&& via.on(&cfg)
|
||||
&& 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);
|
||||
spawn_torrent(ctx, via, enc.feed_id.clone(), enc.id, enc.url.clone(), dest_dir);
|
||||
return Ok(());
|
||||
}
|
||||
let result = if is_torrent {
|
||||
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)
|
||||
}
|
||||
} else {
|
||||
fetch_one(ctx, &enc.feed_id, enc.id, feed_cfg, &enc.url, &dest_dir).await
|
||||
let result = match via {
|
||||
Some(via) if !via.on(&cfg) => Err(anyhow::anyhow!("{}", via.off())),
|
||||
Some(via) => torrent_one(ctx, via, &enc.feed_id, enc.id, &enc.url, &dest_dir).await.map(Some),
|
||||
None => fetch_one(ctx, &enc.feed_id, enc.id, feed_cfg, &enc.url, &dest_dir).await,
|
||||
};
|
||||
|
||||
match result {
|
||||
@@ -879,6 +886,7 @@ pub(crate) async fn download_one(ctx: &Arc<Ctx>, id: i64) -> Result<()> {
|
||||
#[tracing::instrument(name = "torrent", skip_all, fields(feed = feed_id, enclosure = enclosure))]
|
||||
pub(crate) async fn torrent_one(
|
||||
ctx: &Arc<Ctx>,
|
||||
via: download::Via,
|
||||
feed_id: &str,
|
||||
enclosure: i64,
|
||||
url: &str,
|
||||
@@ -887,24 +895,27 @@ pub(crate) async fn torrent_one(
|
||||
let name = download::filename_for(url, None);
|
||||
let mut last_pct = -1i64;
|
||||
let cfg = ctx.cfg();
|
||||
ctx.torrents()
|
||||
.await?
|
||||
.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
|
||||
{
|
||||
last_pct = pct;
|
||||
ctx.out.emit(Event::Progress {
|
||||
feed: feed_id.to_string(),
|
||||
enclosure,
|
||||
url: url.to_string(),
|
||||
file: name.clone(),
|
||||
done,
|
||||
total: Some(total),
|
||||
});
|
||||
}
|
||||
})
|
||||
.await
|
||||
let progress = |done: u64, total: u64| {
|
||||
if let Some(pct) = (done * 100).checked_div(total).map(|p| p as i64)
|
||||
&& pct > last_pct
|
||||
{
|
||||
last_pct = pct;
|
||||
ctx.out.emit(Event::Progress {
|
||||
feed: feed_id.to_string(),
|
||||
enclosure,
|
||||
url: url.to_string(),
|
||||
file: name.clone(),
|
||||
done,
|
||||
total: Some(total),
|
||||
});
|
||||
}
|
||||
};
|
||||
match via {
|
||||
download::Via::Torrent => {
|
||||
ctx.torrents().await?.fetch(&cfg, &ctx.client, url, dest_dir, enclosure, progress).await
|
||||
}
|
||||
download::Via::Nzb => nzb::fetch(&cfg, &ctx.client, url, dest_dir, enclosure, progress).await,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -355,7 +355,14 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
crate::scan::spawn_torrent(&ctx, "f".into(), 9, url.clone(), downloads.join("Show"));
|
||||
crate::scan::spawn_torrent(
|
||||
&ctx,
|
||||
crate::download::Via::Torrent,
|
||||
"f".into(),
|
||||
9,
|
||||
url.clone(),
|
||||
downloads.join("Show"),
|
||||
);
|
||||
let row = tokio::time::timeout(Duration::from_secs(30), async {
|
||||
loop {
|
||||
let row = ctx.db.enclosure(9).await.unwrap().unwrap();
|
||||
|
||||
@@ -54,6 +54,7 @@ id, and Caddy's request lines theirs. ipx also serves Prometheus metrics (`[web]
|
||||
| `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/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/nzb.rs` | Hands NZBs to SABnzbd's API, watches them through post-processing, moves the finished folder in | |
|
||||
| `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/auth.rs` | Argon2id hashing, session tokens, header names | — |
|
||||
@@ -102,7 +103,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
|
||||
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
|
||||
qBittorrent whatever its advertised type; an HTML body is a failed download — a login wall
|
||||
qBittorrent and an `.nzb` body to SABnzbd whatever its advertised type; an HTML body is a failed download — a login wall
|
||||
or an error page — and is deleted.
|
||||
|
||||
## Data model
|
||||
|
||||
@@ -107,6 +107,24 @@ the same as in ipx's, say where in `save_path`. A `.torrent` body is handed to q
|
||||
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.
|
||||
|
||||
```toml
|
||||
[nzb]
|
||||
enabled = true
|
||||
sabnzbd_url = "http://sabnzbd:8080" # empty holds NZBs back
|
||||
api_key = "" # SABnzbd's API key (Config, General)
|
||||
category = "ipx" # the category jobs are added under
|
||||
save_path = "" # where SABnzbd sees download_dir, if not at the same path
|
||||
stall_mins = 30 # give up on an NZB making no progress
|
||||
```
|
||||
|
||||
NZBs go to [SABnzbd](https://sabnzbd.org/) the same way (#496): ipx fetches the `.nzb`, adds it
|
||||
under `category` named `nzb-<id>`, follows it through the queue and post-processing, then moves the
|
||||
finished folder into the episode's own and takes the job out of SABnzbd's history. SABnzbd takes no
|
||||
folder for a job, only for its category, so give the category a folder inside `download_dir` as
|
||||
SABnzbd sees it (for example `/ipx-downloads/.sabnzbd`), on the same disk, since the move is a
|
||||
rename. An `.nzb` body is handed to SABnzbd whatever MIME type it was advertised as, and NZBs share
|
||||
the torrents' two slots.
|
||||
|
||||
## `[web]`
|
||||
|
||||
```toml
|
||||
|
||||
Reference in New Issue
Block a user