Compare commits
No commits in common. "main" and "v0.1.1" have entirely different histories.
35 changed files with 762 additions and 3978 deletions
|
|
@ -4,8 +4,7 @@ name: check
|
|||
# main and triggers a dev-track release build.
|
||||
on:
|
||||
push:
|
||||
branches: ['feature/**', 'fix/**', 'main']
|
||||
pull_request:
|
||||
branches: ['feature/**', 'fix/**']
|
||||
|
||||
jobs:
|
||||
check:
|
||||
|
|
|
|||
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -1,13 +1,11 @@
|
|||
/target
|
||||
/.ci-old-glibc
|
||||
config.toml
|
||||
breadarrd.toml
|
||||
*.db
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
|
||||
# Local hygiene notes (not for commit)
|
||||
CLAUDE.md
|
||||
|
||||
# Leftover source tarballs (never commit these)
|
||||
**/src.tar.xz
|
||||
|
|
|
|||
|
|
@ -82,8 +82,7 @@ Host tools the daemon shells out to: `mkvtoolnix-cli` (`mkvmerge`) and
|
|||
|
||||
## CI
|
||||
|
||||
- `check.yml` — clippy + test on push to `feature/**`, `fix/**`, and
|
||||
`main`, and on pull requests.
|
||||
- `check.yml` — clippy + test on push to `feature/**` and `fix/**`.
|
||||
- `dev-release.yml` — triggered on push to `main`.
|
||||
- `rc-release.yml` — triggered on any `vX.Y.Z-rc.N` tag push.
|
||||
- `release.yml` — triggered on any other `v*` tag push, cuts the actual
|
||||
|
|
|
|||
35
README.md
35
README.md
|
|
@ -26,12 +26,10 @@ Sonarr + Radarr + Prowlarr is three separate services, three databases, three we
|
|||
|
||||
- **nyaa.si** (RSS) — anime TV, polled continuously. Full-auto, no request budget concerns (it's a plain RSS feed).
|
||||
- **apibay.org** (a community JSON API mirror of The Pirate Bay's search) — the primary search-driven source for general TV and movies. Unlike 1337x this is a genuine machine-readable API, needs no HTML scraping, and its search actually ranks by relevance rather than pure seeder count, which matters a lot for titles made of common words.
|
||||
- **torrents-csv** (JSON DHT-dump search) — first general-content fallback when TPB fails or returns nothing. Same hash-to-magnet grab as TPB; covers movies and TV.
|
||||
- **YTS** (JSON `list_movies` API via `yts.lt` — `yts.mx` no longer resolves) — movie-only fallback after TPB. Each hit expands into one candidate per quality so the scorer sees 720p/1080p/2160p separately.
|
||||
- **1337x** (scraped HTML, via community mirrors) — last-resort general-content fallback after the JSON sources. 1337x's main domain is Cloudflare-protected and has a ban history, so requests are round-robined across mirrors with automatic cooldown/backoff on failures, jittered between searches, and rate-limit responses are honored explicitly.
|
||||
- **nyaa.si search mode** — anime movies specifically route here instead of the general-content chain, since nyaa is the safe, official-RSS-interface target and gives materially better results for anime content.
|
||||
- **1337x** (scraped HTML, via community mirrors) — secondary search-driven source, tried after TPB. 1337x's main domain is Cloudflare-protected and has a ban history, so requests are round-robined across mirrors with automatic cooldown/backoff on failures, jittered between searches, and rate-limit responses are honored explicitly.
|
||||
- **nyaa.si search mode** — anime movies specifically route here instead of TPB/1337x, since nyaa is the safe, official-RSS-interface target and gives materially better results for anime content.
|
||||
|
||||
Search-driven sources share one per-cycle request budget (default: 5 searches per 30-minute cycle). General content tries TPB, then YTS (movies) / torrents-csv, then 1337x; anime movies go to nyaa search. Kept conservative since 1337x has a ban history and the goal is steady backlog clearing, not maximum throughput. A whole cycle failing outright backs off the *next cycle's* interval (1h → 2h → 4h, capped), on top of each source's own per-mirror cooldowns.
|
||||
All three search-driven sources share one per-cycle request budget (default: 5 searches per 30-minute cycle, TPB tried first, then 1337x, then nyaa search) — kept conservative since 1337x has a ban history and the goal is steady backlog clearing, not maximum throughput. A whole cycle failing outright backs off the *next cycle's* interval (1h → 2h → 4h, capped), on top of each source's own per-mirror cooldowns.
|
||||
|
||||
## Setup
|
||||
|
||||
|
|
@ -54,27 +52,24 @@ Install via bakery (`bakery install breadarr`) on a homelab host, or build from
|
|||
|
||||
## Using the TUI
|
||||
|
||||
`Tab` / `Shift+Tab` cycle Library / History / Review / Add / Stuck / Calendar / Health / Profiles; `1`–`8` jump straight to a tab. `j`/`k` or arrows move, `g`/`G` jump to first/last, `PgUp`/`PgDn` page, `Enter` opens detail or runs a search, `Esc` backs out. `?` is the full key list.
|
||||
`Tab` cycles Library / History / Review Queue / Add Show / Stuck / Calendar / Health. `j`/`k` or arrow keys navigate, `Enter` opens detail or runs a search, `Esc` backs out.
|
||||
|
||||
- **Review** — `a` approves and `r` rejects a pending low-confidence title match. The tab title badges the pending count. Check this periodically, especially early on.
|
||||
- **Library** — `/` incrementally filters the list by title; `f`/`o` cycle kind-filter and sort. With an item's detail open: `s` triggers an immediate search-now pass for that item's backlog; `n` jumps to the next missing monitored episode; `m`/`e`/`S` toggle monitored on the show/episode/season respectively; `x` (confirm with a second `x`) removes the item from tracking without touching files on disk; `d` (confirm with a second `d`) deletes a bad imported file from disk and clears its tracking, freeing the episode/movie to be re-grabbed on the next cycle — the redownload path for a file that turned out to be wrong or broken; `c` fetches the manual release picker for the selected episode/movie, `Enter` grabs the highlighted candidate, `Esc` cancels. Movies (no episode list) show a summary pane with the same keys.
|
||||
- **Stuck** — surfaces grabs that look stalled (no download progress advancing, or missing from qBittorrent) before the daemon's own auto-fail timers would catch them. `Enter` jumps to that show.
|
||||
- **Calendar** — upcoming/recently-aired episodes in a roughly week-either-side window. `Enter` opens the matching episode.
|
||||
- **Health** — daemon cycle outcomes plus the library-health report (see below), scrollable.
|
||||
- **Profiles** — quality-profile weight axes; open a profile and edit a weight in place.
|
||||
- **Review Queue** — `a` approves and `r` rejects a pending low-confidence title match. Check this periodically, especially early on.
|
||||
- **Library** (with an item's detail open) — `s` triggers an immediate search-now pass for that item's backlog; `m`/`e`/`S` toggle monitored on the show/episode/season respectively; `x` (confirm with a second `x`) removes the item from tracking without touching files on disk; `d` (confirm with a second `d`) deletes a bad imported file from disk and clears its tracking, freeing the episode/movie to be re-grabbed on the next cycle — the redownload path for a file that turned out to be wrong or broken; `c` fetches the manual release picker for the selected episode/movie, `Enter` grabs the highlighted candidate, `Esc` cancels.
|
||||
- **Stuck** — surfaces grabs that look stalled (no download progress advancing, or missing from qBittorrent) before the daemon's own auto-fail timers would catch them.
|
||||
- **Calendar** — upcoming/recently-aired episodes in a roughly week-either-side window.
|
||||
- **Health** — the library-health report (see below) rendered as a tab instead of curled by hand.
|
||||
|
||||
## Operational notes
|
||||
|
||||
- `curl http://127.0.0.1:7879/health` is liveness-only (is the process up). Cycle outcomes live at `/health/detail` (requires `Authorization: Bearer <token>` when `daemon.api_token` is set).
|
||||
- `curl http://127.0.0.1:7879/health` reports daemon status plus the last grab/import/search/upgrade cycle outcome — the cheapest way to confirm the automation loop is actually alive.
|
||||
- `curl http://127.0.0.1:7879/library/health` (or the TUI's Health tab) reports corrupt files, under-1080p files, missing-English-audio files, non-English-default-audio files, missing-subtitle files, duplicate-file groups, and library-wide summary stats (codec breakdown, resolution distribution, subtitle coverage %) — all derived from `ffprobe` data, not release-title claims.
|
||||
- The API is plaintext HTTP — there is no TLS. Binding `listen_addr` off loopback requires a non-empty `daemon.api_token`.
|
||||
- If `daemon.api_token` is set, every route except `/health` requires `Authorization: Bearer <token>`.
|
||||
- Library normalization is a manual, explicit action (not run automatically against your files): `breadarrd debug-scan-tv <root-dir>` / `breadarrd debug-scan-movies <root-dir>`.
|
||||
- `breadarrd remux-backlog` sweeps the whole library for files with a non-English default audio track and applies the same track-promotion fix used automatically on fresh imports — a one-time (or occasional) pass against files that predate the fix, or were imported before breadarr started tracking them.
|
||||
- `breadarrd probe-library` backfills `ffprobe` data for the whole library in one run (the running daemon does this incrementally, a bounded batch per hour, so it doesn't stall the grab/import/search cycles — this command is for getting it all done immediately instead).
|
||||
- `breadarrd verify-library` runs the expensive full-decode corruption check (`ffmpeg -xerror`, actually decoding every frame) against every file whose cheap header probe succeeded but hasn't been decode-verified yet. This is opt-in and can take minutes per file, so — unlike `probe-library` — it's never run automatically by any ticker; run it by hand (or on a cron) whenever you want a real, not-just-header-parseable confirmation the library is intact.
|
||||
- Other `debug-*` subcommands are diagnostics for exercising one piece of the pipeline directly — run `breadarrd <name>` with no args to see its usage. Currently: `debug-qbit-add`, `debug-qbit-list`, `debug-jellyfin-refresh`, `debug-tvdb-add`, `debug-tvdb-search`, `debug-anime-map-refresh`, `debug-match-title`, `debug-grab-cycle`, `debug-import-cycle`, `debug-1337x-search`, `debug-scan-tv`, `debug-scan-movies`, `debug-search-show` (a manually-triggered, unthrottled search pass over one already-tracked title's whole backlog), `debug-reconcile-report` (dry-run of the disk-reconciliation pass — safe to run against a freshly-restored or otherwise suspect database before trusting the hourly ticker with it unattended).
|
||||
- `breadarrd transcode-library` backfills AV1 transcode over existing library files (requires `[transcode] enabled = true`). `breadarrd retranscode-oversized` re-encodes already-AV1 files that landed larger than the current ceiling. `breadarrd relink-orphaned-files` reattaches episode files on disk that tracking lost.
|
||||
- The embedding model (~90MB) downloads automatically on first run.
|
||||
- The database is backed up (with its WAL/SHM sidecars) to `<db-dir>/backups/` on every daemon startup, keeping the 5 most recent copies — there's no migration framework, so this stands in for the pre-upgrade backup Sonarr/Radarr do on every schema change.
|
||||
- An hourly background pass reconciles tracked `episode_file` paths against what's actually on disk: a file renamed or transcoded in place (e.g. Tdarr converting codec/container) gets its path repaired rather than being wrongly treated as deleted; a file genuinely gone gets cleared from tracking so it becomes searchable again. A circuit breaker refuses to touch anything if an anomalous fraction of the library looks missing at once (the classic false signal of an offline mount), rather than mass-clearing tracking for files that are actually still there.
|
||||
|
|
@ -82,8 +77,8 @@ Install via bakery (`bakery install breadarr`) on a homelab host, or build from
|
|||
## Known limitations
|
||||
|
||||
- No subtitle generation yet — a Whisper-based reimplementation of an existing external tool is planned (see [Roadmap](#roadmap)), with the schema (`episode_file.subtitle_status`) already reserved for it.
|
||||
- No Sonarr/Radarr API compatibility shim yet, so tools expecting that API (e.g. Overseerr/Seerr) can't integrate directly — still a future idea (see [Roadmap](#roadmap)).
|
||||
- Quality-profile weights are loaded and editable (Profiles tab). `min_seeders` and the group denylist are still hardcoded defaults, not user-configurable.
|
||||
- No Sonarr/Radarr API compatibility shim, so tools expecting that API (e.g. Overseerr/Seerr) can't integrate directly yet — also planned, with an empty `compat/` module reserved so it isn't a retrofit later.
|
||||
- **Quality-scoring weights are hardcoded, not configurable.** Every axis — resolution tier, source tier, codec tier, bit depth, HDR, repack/proper bonus, and so on — is a fixed constant in `QualityProfile::default_tv`/`default_movie` (`scoring/profile.rs`). The `quality_profile` table and its `weights` JSON column already exist in the schema and are already parsed on load; `scoring/profile.rs` just doesn't read them yet, so every install currently gets the same scoring behavior regardless of what tradeoffs you'd actually prefer (e.g. valuing efficient codecs over raw resolution, or not caring about HDR at all). This is the single biggest gap between "works great for the specific setup it shipped with" and "works well for a range of libraries and preferences" — see [Roadmap](#roadmap).
|
||||
- The title-matching embedding model (all-MiniLM-L6-v2) doesn't actually discriminate between unrelated romanized-Japanese titles — it clusters any two romaji strings as "similar foreign text" regardless of content (verified live: several unrelated anime auto-matched at >0.85 confidence against a handful of "attractor" shows with zero real relation). A token-overlap gate (`MIN_TOKEN_OVERLAP` in `matcher/mod.rs`) blocks this from both auto-matching *and* reaching the review queue, but the underlying model limitation is a workaround, not a fix.
|
||||
- The search loop's per-cycle budget is intentionally conservative; raising it trades faster backlog clearing for more request volume against 1337x specifically, which has a ban history. The upgrade-search loop shares the same underlying sources and the same conservatism applies.
|
||||
|
||||
|
|
@ -91,6 +86,10 @@ Install via bakery (`bakery install breadarr`) on a homelab host, or build from
|
|||
|
||||
Everything above is shipped and running. This section is the honest, disciplined version of "what would this become if taken all the way" — grounded in subsystems that already exist, not a wishlist. Nothing here contradicts the project's two foundational design choices (a small hardcoded set of sources, not a general indexer-plugin architecture; a TUI, not a web UI) — anything that would require reconsidering either is flagged as such.
|
||||
|
||||
### Near-term (extends existing, working subsystems)
|
||||
|
||||
- **Configurable quality-profile weights.** The most user-facing gap in the project today. Different people reasonably want different tradeoffs — some care most about resolution, some would rather have a smaller, more-efficient-codec file, some don't watch anything HDR and don't want it influencing scores at all — and right now every install gets identical hardcoded behavior. The `quality_profile.weights` column already exists in the schema and is already parsed as JSON on load; the gap is purely that `scoring/profile.rs` ignores it in favor of the `default_tv`/`default_movie` constants. Wiring the column through the scoring engine and exposing it as an editable profile in the TUI turns an already-half-built feature into a real one, without changing the scoring model's shape — same axes, same gates, just user-owned numbers instead of fixed ones.
|
||||
|
||||
### Medium-term (closes the loop on data already being collected)
|
||||
|
||||
- **Tdarr hand-off.** `media_file_probe` already has `video_codec`, `container_bitrate`, `video_bitrate`, and `hdr` per file — everything needed to generate a "these files are still H.264/high-bitrate and are good AV1-transcode candidates" list without re-scanning the filesystem. Whether that's a report the user acts on manually or a direct trigger into the existing Tdarr pipeline is a judgment call for whenever this is built — but the *data* side of this is already sitting in the database, unused.
|
||||
|
|
@ -101,7 +100,7 @@ Everything above is shipped and running. This section is the honest, disciplined
|
|||
### Longer-term (larger, still-plausible extensions)
|
||||
|
||||
- **Learning from review-queue decisions.** Every approve/reject in the review queue is already a labeled example of "was this match actually correct." Logging outcomes (not just acting on them) and periodically comparing auto-tuned per-library confidence thresholds against the fixed `AUTO_MATCH_CONFIDENCE`/`MIN_TOKEN_OVERLAP` constants in `matcher/mod.rs` is a plausible way to let the matcher get measurably better over time for *this* library's actual title vocabulary — anime is the library segment most exposed to the token-overlap workaround today, so it's also the segment most likely to benefit first. This is a genuine judgment call (a wrong auto-tune silently degrades match quality with no review-queue visibility into it happening), not a slam dunk — worth prototyping as an offline analysis of logged decisions before it's ever allowed to write back to live thresholds.
|
||||
- **Seerr/Overseerr compatibility shim, then real request fulfillment.** A Sonarr/Radarr v3-API-compatible shim is the integration path Seerr's client code expects. Once that shim exists, the natural next step isn't just protocol compatibility — it's tracking *fulfillment* end-to-end (a request maps to a `media_item`, which maps to `release`/`event_history` rows that already record exactly when and how it was grabbed and imported), giving a requester real status instead of Seerr's own best-effort polling.
|
||||
- **Seerr/Overseerr compatibility shim, then real request fulfillment.** The `compat/` extension point has been reserved from the start for a Sonarr/Radarr v3-API-compatible shim, since that's what Seerr's client code expects. Once that shim exists, the natural next step isn't just protocol compatibility — it's tracking *fulfillment* end-to-end (a request maps to a `media_item`, which maps to `release`/`event_history` rows that already record exactly when and how it was grabbed and imported), giving a requester real status instead of Seerr's own best-effort polling.
|
||||
- **Whisper subtitle generation.** Fully speced already: reimplement the existing external Python/Whisper tool's exact behavior — "Full Subtitles" (everything transcribed) and "Foreign Parts" (segments where a translate-pass diverges from the transcribe-pass, via text-similarity diff at a 0.80 threshold) SRT tracks, muxed with `mkvmerge` — but gated and on-demand (triggered post-import only when a file lacks subtitles and has non-English/fallback audio), unlike the external tool's full-library batch sweep. `episode_file.subtitle_status` is already wired through the schema for this. The open technical questions are a Rust equivalent of Python's `difflib.SequenceMatcher` for the similarity diff, and which Whisper-in-Rust GPU backend story actually works well across the range of consumer GPU hardware this runs on in practice (CUDA/Metal/Vulkan-centric crates like `whisper-rs` have no strong story for e.g. Intel Arc or other OpenVINO-friendly hardware).
|
||||
|
||||
### Deliberately not on this list
|
||||
|
|
|
|||
17
bakery.toml
17
bakery.toml
|
|
@ -14,17 +14,17 @@ binaries = ["breadarrd", "breadarr-tui"]
|
|||
# on the built binary is full of onnxruntime's own C++ symbol names --
|
||||
# confirming the `ort` crate's default strategy statically bundled its own
|
||||
# onnxruntime build directly into breadarrd rather than dynamically linking
|
||||
# the system onnxruntime-cpu package. TLS is vendored: breadarrd builds
|
||||
# OpenSSL via openssl-sys's `vendored` feature, so the shipped binary does
|
||||
# not depend on the host's libssl/libcrypto. libstdc++/libgcc/glibc/zlib/
|
||||
# zstd/brotli also appear in `ldd` but are omitted here the same way
|
||||
# breadcast's bakery.toml omits them: glibc/gcc-libs are unavoidable
|
||||
# base-system dependencies, and zlib/zstd/brotli are themselves
|
||||
# transitive deps of curl/pacman already guaranteed present on any real
|
||||
# Arch install.
|
||||
# the system onnxruntime-cpu package. openssl: libssl.so.3/libcrypto.so.3
|
||||
# (reqwest's TLS backend) show up directly in `ldd` for both breadarrd and
|
||||
# breadarr-tui. libstdc++/libgcc/glibc/zlib/zstd/brotli also appear in
|
||||
# `ldd` but are omitted here the same way breadcast's bakery.toml omits
|
||||
# them: glibc/gcc-libs are unavoidable base-system dependencies, and
|
||||
# zlib/zstd/brotli are themselves transitive deps of openssl/curl/pacman
|
||||
# already guaranteed present on any real Arch install.
|
||||
system_deps = [
|
||||
"mkvtoolnix-cli",
|
||||
"ffmpeg",
|
||||
"openssl",
|
||||
]
|
||||
optional_system_deps = []
|
||||
bread_deps = []
|
||||
|
|
@ -40,6 +40,5 @@ example = "config.example.toml"
|
|||
|
||||
[install]
|
||||
post_install = [
|
||||
"loginctl enable-linger \"$USER\" || true",
|
||||
"systemctl --user is-active --quiet breadarrd || systemctl --user start breadarrd",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ use crate::dto::{
|
|||
SearchResult, StuckReport, UpdateQualityProfileWeightsRequest, WeightsDto,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DaemonClient {
|
||||
base_url: String,
|
||||
client: reqwest::Client,
|
||||
|
|
@ -17,9 +16,8 @@ impl DaemonClient {
|
|||
/// `api_token` mirrors `config.daemon.api_token` server-side — empty
|
||||
/// means "no auth configured," so this stays a no-op default header
|
||||
/// rather than sending a meaningless empty bearer token on every
|
||||
/// request. A non-empty token that cannot be encoded as an HTTP header
|
||||
/// is an error (not a silent unauthenticated client).
|
||||
pub fn new(base_url: impl Into<String>, api_token: &str) -> Result<Self> {
|
||||
/// request.
|
||||
pub fn new(base_url: impl Into<String>, api_token: &str) -> Self {
|
||||
let mut builder = reqwest::Client::builder()
|
||||
// A default so no request can hang the TUI forever with zero
|
||||
// feedback if the daemon is unreachable or a connection stalls.
|
||||
|
|
@ -28,23 +26,20 @@ impl DaemonClient {
|
|||
// which overrides this.
|
||||
.timeout(std::time::Duration::from_secs(30));
|
||||
if !api_token.is_empty() {
|
||||
let token = api_token.replace(['\r', '\n'], "");
|
||||
anyhow::ensure!(
|
||||
!token.is_empty(),
|
||||
"daemon.api_token is non-empty but contains only CR/LF"
|
||||
);
|
||||
let value = reqwest::header::HeaderValue::from_str(&format!("Bearer {token}"))
|
||||
.context("daemon.api_token is not a valid HTTP header value")?;
|
||||
let mut headers = reqwest::header::HeaderMap::new();
|
||||
headers.insert(reqwest::header::AUTHORIZATION, value);
|
||||
if let Ok(value) =
|
||||
reqwest::header::HeaderValue::from_str(&format!("Bearer {api_token}"))
|
||||
{
|
||||
headers.insert(reqwest::header::AUTHORIZATION, value);
|
||||
}
|
||||
builder = builder.default_headers(headers);
|
||||
}
|
||||
Ok(Self {
|
||||
Self {
|
||||
base_url: base_url.into(),
|
||||
client: builder
|
||||
.build()
|
||||
.expect("reqwest client builder should not fail with only a timeout/headers set"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn health(&self) -> Result<bool> {
|
||||
|
|
@ -64,7 +59,7 @@ impl DaemonClient {
|
|||
pub async fn health_detail(&self) -> Result<HealthDetail> {
|
||||
let resp = self
|
||||
.client
|
||||
.get(format!("{}/health/detail", self.base_url))
|
||||
.get(format!("{}/health", self.base_url))
|
||||
.timeout(std::time::Duration::from_secs(2))
|
||||
.send()
|
||||
.await
|
||||
|
|
|
|||
|
|
@ -97,16 +97,6 @@ pub struct SourcesConfig {
|
|||
/// titles made of common words.
|
||||
#[serde(default = "default_tpb_api_url")]
|
||||
pub tpb_api_url: String,
|
||||
/// torrents.csv DHT-dump search — first fallback when TPB fails or
|
||||
/// returns nothing. Same hash-to-magnet grab shape as TPB, covers
|
||||
/// movies and TV.
|
||||
#[serde(default = "default_torrents_csv_url")]
|
||||
pub torrents_csv_url: String,
|
||||
/// YTS v2 list_movies JSON — movie-only fallback after TPB / torrents-csv.
|
||||
/// `yts.mx` does not resolve; this default is a working host as of
|
||||
/// 2026-08-16.
|
||||
#[serde(default = "default_yts_api_url")]
|
||||
pub yts_api_url: String,
|
||||
/// Human kill switch for the upgrade-search loop, same reasoning as
|
||||
/// `search_enabled` — off by default would mean nothing ever improves,
|
||||
/// but a user who's happy with their current files (or wants to save
|
||||
|
|
@ -144,8 +134,6 @@ impl Default for SourcesConfig {
|
|||
search_budget_per_cycle: default_search_budget_per_cycle(),
|
||||
search_enabled: default_search_enabled(),
|
||||
tpb_api_url: default_tpb_api_url(),
|
||||
torrents_csv_url: default_torrents_csv_url(),
|
||||
yts_api_url: default_yts_api_url(),
|
||||
upgrade_enabled: default_upgrade_enabled(),
|
||||
upgrade_poll_interval_secs: default_upgrade_poll_interval_secs(),
|
||||
upgrade_budget_per_cycle: default_upgrade_budget_per_cycle(),
|
||||
|
|
@ -158,14 +146,6 @@ fn default_tpb_api_url() -> String {
|
|||
"https://apibay.org/q.php".to_string()
|
||||
}
|
||||
|
||||
fn default_torrents_csv_url() -> String {
|
||||
"https://torrents-csv.com/service/search".to_string()
|
||||
}
|
||||
|
||||
fn default_yts_api_url() -> String {
|
||||
"https://yts.lt/api/v2/list_movies.json".to_string()
|
||||
}
|
||||
|
||||
fn default_upgrade_enabled() -> bool {
|
||||
true
|
||||
}
|
||||
|
|
@ -212,7 +192,6 @@ fn default_import_poll_interval_secs() -> u64 {
|
|||
|
||||
fn default_1337x_mirrors() -> Vec<String> {
|
||||
[
|
||||
"https://www.1337xx.to",
|
||||
"https://13377x.info",
|
||||
"https://13377x.email",
|
||||
"https://1337xto.info",
|
||||
|
|
@ -243,10 +222,12 @@ pub struct DaemonConfig {
|
|||
#[serde(default = "default_model_dir")]
|
||||
pub model_dir: String,
|
||||
/// Bearer token required on every API request when non-empty. Empty
|
||||
/// (the default) means auth is off entirely — allowed only when
|
||||
/// `listen_addr` is loopback. A non-loopback bind with an empty token
|
||||
/// is rejected at load. When set, the token must be at least 16
|
||||
/// characters so a length-oracle of short guesses is useless.
|
||||
/// (the default) means auth is off entirely — `listen_addr` defaults to
|
||||
/// loopback-only, so a fresh install isn't suddenly locked out of its
|
||||
/// own unconfigured daemon. This matters once `listen_addr` is changed
|
||||
/// to bind non-loopback (e.g. so a TUI on a different host on the same
|
||||
/// tailnet can reach it) — without a token, that's unauthenticated
|
||||
/// add/delete/search access to anyone who can reach the port.
|
||||
#[serde(default)]
|
||||
pub api_token: String,
|
||||
}
|
||||
|
|
@ -614,10 +595,11 @@ impl Config {
|
|||
Ok(cfg)
|
||||
}
|
||||
|
||||
/// Rejects values that are individually syntactically valid TOML but
|
||||
/// make the daemon unsafe or the transcode pipeline's math nonsensical
|
||||
/// — a typo here would otherwise only surface much later, or bind an
|
||||
/// unauthenticated API on a reachable address.
|
||||
/// Rejects a handful of `transcode` values that are individually
|
||||
/// syntactically valid TOML but make the transcode pipeline's math
|
||||
/// nonsensical — there's no other validation anywhere in this config,
|
||||
/// so a typo here would otherwise only surface much later, deep inside
|
||||
/// an encode.
|
||||
fn validate(&self) -> Result<()> {
|
||||
// `target_bitrate_kbps` divides by `reference_height` (via
|
||||
// `reference_pixels`); zero makes that ratio `f64::INFINITY`, which
|
||||
|
|
@ -641,69 +623,9 @@ impl Config {
|
|||
(0.0..=1.0).contains(&self.transcode.min_size_reduction_pct),
|
||||
"transcode.min_size_reduction_pct must be between 0.0 and 1.0"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
(0.0..=1.0).contains(&self.transcode.skip_below_ceiling_ratio),
|
||||
"transcode.skip_below_ceiling_ratio must be between 0.0 and 1.0"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
self.transcode.parallelism_min >= 1,
|
||||
"transcode.parallelism_min must be at least 1"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
self.transcode.parallelism_max >= self.transcode.parallelism_min,
|
||||
"transcode.parallelism_max must be >= parallelism_min"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
self.transcode.parallelism_max_anime >= 1,
|
||||
"transcode.parallelism_max_anime must be at least 1"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
(0..=63).contains(&self.transcode.quality_anime),
|
||||
"transcode.quality_anime must be between 0 and 63"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
(0..=13).contains(&self.transcode.anime_svtav1_preset),
|
||||
"transcode.anime_svtav1_preset must be between 0 and 13"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
self.transcode.verify_sample_secs.is_finite()
|
||||
&& self.transcode.verify_sample_secs > 0.0,
|
||||
"transcode.verify_sample_secs must be greater than 0"
|
||||
);
|
||||
const LOG_LEVELS: &[&str] = &["error", "warn", "info", "debug", "trace", "off"];
|
||||
anyhow::ensure!(
|
||||
LOG_LEVELS
|
||||
.iter()
|
||||
.any(|l| self.daemon.log_level.eq_ignore_ascii_case(l)),
|
||||
"daemon.log_level must be one of error, warn, info, debug, trace, off"
|
||||
);
|
||||
if !self.daemon.api_token.is_empty() {
|
||||
anyhow::ensure!(
|
||||
self.daemon.api_token.len() >= 16,
|
||||
"daemon.api_token must be at least 16 characters when set"
|
||||
);
|
||||
}
|
||||
if self.daemon.api_token.is_empty() && !is_loopback_listen_addr(&self.daemon.listen_addr) {
|
||||
anyhow::bail!(
|
||||
"daemon.api_token is required when listen_addr ({}) is not loopback",
|
||||
self.daemon.listen_addr
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `true` when `daemon.listen_addr` is loopback (`127.0.0.1`, `::1`,
|
||||
/// `localhost`). Used at startup to decide whether an empty token is
|
||||
/// merely a local-process warning or already refused by `validate`.
|
||||
pub fn listen_is_loopback(&self) -> bool {
|
||||
is_loopback_listen_addr(&self.daemon.listen_addr)
|
||||
}
|
||||
|
||||
/// Expand a `~/...` path the same way configured library roots are.
|
||||
pub fn expand_path(input: &str) -> PathBuf {
|
||||
expand_home(input)
|
||||
}
|
||||
|
||||
pub fn db_path(&self) -> PathBuf {
|
||||
expand_home(&self.daemon.db_path)
|
||||
}
|
||||
|
|
@ -744,29 +666,6 @@ fn expand_home(input: &str) -> PathBuf {
|
|||
PathBuf::from(input)
|
||||
}
|
||||
|
||||
/// Loopback hosts we allow to bind without an API token: IPv4/IPv6
|
||||
/// loopback socket addresses, plus the `localhost` hostname form.
|
||||
fn is_loopback_listen_addr(listen_addr: &str) -> bool {
|
||||
if let Ok(addr) = listen_addr.parse::<std::net::SocketAddr>() {
|
||||
return addr.ip().is_loopback();
|
||||
}
|
||||
let host = if let Some(rest) = listen_addr.strip_prefix('[') {
|
||||
rest.split(']').next().unwrap_or(rest)
|
||||
} else if let Some((h, port)) = listen_addr.rsplit_once(':') {
|
||||
if port.parse::<u16>().is_ok() && !h.contains(':') {
|
||||
h
|
||||
} else {
|
||||
listen_addr
|
||||
}
|
||||
} else {
|
||||
listen_addr
|
||||
};
|
||||
host.eq_ignore_ascii_case("localhost")
|
||||
|| host
|
||||
.parse::<std::net::IpAddr>()
|
||||
.is_ok_and(|ip| ip.is_loopback())
|
||||
}
|
||||
|
||||
fn default_log_level() -> String {
|
||||
"info".to_string()
|
||||
}
|
||||
|
|
@ -850,99 +749,4 @@ mod tests {
|
|||
let cfg: Config = toml::from_str("[transcode]\nmin_size_reduction_pct = 1.5\n").unwrap();
|
||||
assert!(cfg.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_loopback_with_empty_token_is_ok() {
|
||||
Config::default().validate().unwrap();
|
||||
assert!(is_loopback_listen_addr("127.0.0.1:7879"));
|
||||
assert!(is_loopback_listen_addr("localhost:7879"));
|
||||
assert!(is_loopback_listen_addr("[::1]:7879"));
|
||||
assert!(is_loopback_listen_addr("::1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_loopback_without_token_is_rejected() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.daemon.listen_addr = "0.0.0.0:7879".into();
|
||||
assert!(cfg.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_loopback_with_token_is_ok() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.daemon.listen_addr = "0.0.0.0:7879".into();
|
||||
cfg.daemon.api_token = "a-token-16-chars+".into();
|
||||
cfg.validate().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_api_token_is_rejected() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.daemon.api_token = "tooshort".into();
|
||||
assert!(cfg.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_log_level() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.daemon.log_level = "loud".into();
|
||||
assert!(cfg.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_off_log_level() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.daemon.log_level = "off".into();
|
||||
cfg.validate().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_skip_below_ceiling_ratio_out_of_range() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.transcode.skip_below_ceiling_ratio = 1.5;
|
||||
assert!(cfg.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_parallelism_min() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.transcode.parallelism_min = 0;
|
||||
assert!(cfg.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_parallelism_max_below_min() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.transcode.parallelism_min = 3;
|
||||
cfg.transcode.parallelism_max = 2;
|
||||
assert!(cfg.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_parallelism_max_anime() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.transcode.parallelism_max_anime = 0;
|
||||
assert!(cfg.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_quality_anime_out_of_range() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.transcode.quality_anime = 64;
|
||||
assert!(cfg.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_anime_svtav1_preset_out_of_range() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.transcode.anime_svtav1_preset = 14;
|
||||
assert!(cfg.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_verify_sample_secs() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.transcode.verify_sample_secs = 0.0;
|
||||
assert!(cfg.validate().is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -136,12 +136,6 @@ pub struct CalendarEntry {
|
|||
pub has_file: bool,
|
||||
}
|
||||
|
||||
/// Cheap liveness payload for unauthenticated `GET /health`.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct HealthStatus {
|
||||
pub status: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct HealthDetail {
|
||||
pub status: String,
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -6,7 +6,7 @@ use std::time::Duration;
|
|||
|
||||
use anyhow::Result;
|
||||
use breadarr_shared::{Config, DaemonClient};
|
||||
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind};
|
||||
use crossterm::event::{self, Event, KeyCode, KeyEventKind};
|
||||
use crossterm::execute;
|
||||
use crossterm::terminal::{
|
||||
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
|
||||
|
|
@ -20,7 +20,7 @@ use app::{App, Focus, LibraryRoots, StuckSection, Tab};
|
|||
async fn main() -> Result<()> {
|
||||
let config = Config::load()?;
|
||||
let base_url = format!("http://{}", config.daemon.listen_addr);
|
||||
let client = DaemonClient::new(base_url, &config.daemon.api_token)?;
|
||||
let client = DaemonClient::new(base_url, &config.daemon.api_token);
|
||||
let roots = LibraryRoots {
|
||||
series: config.default_root_folder().to_string_lossy().to_string(),
|
||||
movies: config.movies_root_folder().to_string_lossy().to_string(),
|
||||
|
|
@ -50,9 +50,6 @@ async fn run(
|
|||
let mut last_refresh = tokio::time::Instant::now() - Duration::from_secs(10);
|
||||
|
||||
loop {
|
||||
app.poll_background().await;
|
||||
app.expire_status();
|
||||
|
||||
if last_refresh.elapsed() >= Duration::from_secs(3) || app.force_refresh {
|
||||
app.refresh_active_tab().await;
|
||||
app.force_refresh = false;
|
||||
|
|
@ -66,7 +63,7 @@ async fn run(
|
|||
if key.kind != KeyEventKind::Press {
|
||||
continue;
|
||||
}
|
||||
handle_key(app, key, roots).await;
|
||||
handle_key(app, key.code, roots).await;
|
||||
if app.should_quit {
|
||||
return Ok(());
|
||||
}
|
||||
|
|
@ -75,9 +72,7 @@ async fn run(
|
|||
}
|
||||
}
|
||||
|
||||
async fn handle_key(app: &mut App, key: KeyEvent, roots: &LibraryRoots) {
|
||||
let code = key.code;
|
||||
|
||||
async fn handle_key(app: &mut App, code: KeyCode, roots: &LibraryRoots) {
|
||||
// Typing into the add-show search box takes priority over global keys.
|
||||
if matches!(app.tab, Tab::Add) && matches!(app.focus, Focus::AddSearchInput) {
|
||||
match code {
|
||||
|
|
@ -86,31 +81,8 @@ async fn handle_key(app: &mut App, key: KeyEvent, roots: &LibraryRoots) {
|
|||
KeyCode::Backspace => {
|
||||
app.add_query.pop();
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
app.add_query.clear();
|
||||
}
|
||||
KeyCode::Tab => switch_tab(app, tab_offset(app.tab, 1)),
|
||||
KeyCode::BackTab => switch_tab(app, tab_offset(app.tab, -1)),
|
||||
_ => {}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Incremental Library title filter — same input-mode isolation as Add.
|
||||
if matches!(app.tab, Tab::Library) && matches!(app.focus, Focus::LibraryFilterInput) {
|
||||
match code {
|
||||
KeyCode::Enter => app.confirm_library_filter(),
|
||||
KeyCode::Char(c) => {
|
||||
app.library_query.push(c);
|
||||
app.recompute_library_view();
|
||||
}
|
||||
KeyCode::Backspace => {
|
||||
app.library_query.pop();
|
||||
app.recompute_library_view();
|
||||
}
|
||||
KeyCode::Esc => app.clear_library_filter(),
|
||||
KeyCode::Tab => switch_tab(app, tab_offset(app.tab, 1)),
|
||||
KeyCode::BackTab => switch_tab(app, tab_offset(app.tab, -1)),
|
||||
KeyCode::Esc => app.should_quit = true,
|
||||
KeyCode::Tab => cycle_tab(app),
|
||||
_ => {}
|
||||
}
|
||||
return;
|
||||
|
|
@ -155,25 +127,12 @@ async fn handle_key(app: &mut App, key: KeyEvent, roots: &LibraryRoots) {
|
|||
|
||||
match code {
|
||||
KeyCode::Char('q') => app.should_quit = true,
|
||||
KeyCode::Tab => switch_tab(app, tab_offset(app.tab, 1)),
|
||||
KeyCode::BackTab => switch_tab(app, tab_offset(app.tab, -1)),
|
||||
KeyCode::Char(c) if c.is_ascii_digit() => {
|
||||
if let Some(n) = c.to_digit(10) {
|
||||
if (1..=Tab::ALL.len() as u32).contains(&n) {
|
||||
switch_tab(app, Tab::ALL[(n as usize) - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
KeyCode::Tab => cycle_tab(app),
|
||||
KeyCode::Char('j') | KeyCode::Down => app.move_selection(1),
|
||||
KeyCode::Char('k') | KeyCode::Up => app.move_selection(-1),
|
||||
KeyCode::Char('g') => app.select_edge(false),
|
||||
KeyCode::Char('G') => app.select_edge(true),
|
||||
KeyCode::PageDown => app.move_selection(10),
|
||||
KeyCode::PageUp => app.move_selection(-10),
|
||||
KeyCode::Esc => match app.tab {
|
||||
Tab::Library if matches!(app.focus, Focus::Candidates) => app.close_candidates(),
|
||||
Tab::Library if app.detail.is_some() => app.close_detail(),
|
||||
Tab::Library if !app.library_query.is_empty() => app.clear_library_filter(),
|
||||
Tab::Add => app.focus = Focus::AddSearchInput,
|
||||
Tab::Profiles if app.profile_detail.is_some() => app.close_profile_detail(),
|
||||
_ => {}
|
||||
|
|
@ -192,7 +151,6 @@ async fn handle_key(app: &mut App, key: KeyEvent, roots: &LibraryRoots) {
|
|||
}
|
||||
Tab::Profiles => app.open_profile_detail(),
|
||||
Tab::Stuck => app.jump_to_stuck_target().await,
|
||||
Tab::Calendar => app.jump_to_calendar_entry().await,
|
||||
_ => {}
|
||||
},
|
||||
KeyCode::Left | KeyCode::Right if matches!(app.tab, Tab::Stuck) => {
|
||||
|
|
@ -220,16 +178,6 @@ async fn handle_key(app: &mut App, key: KeyEvent, roots: &LibraryRoots) {
|
|||
KeyCode::Char('r') if matches!(app.tab, Tab::Review) => {
|
||||
app.reject_selected_review().await;
|
||||
}
|
||||
KeyCode::Char('/') if matches!(app.tab, Tab::Library) && app.detail.is_none() => {
|
||||
app.start_library_filter();
|
||||
}
|
||||
KeyCode::Char('n')
|
||||
if matches!(app.tab, Tab::Library)
|
||||
&& app.detail.is_some()
|
||||
&& !matches!(app.focus, Focus::Candidates) =>
|
||||
{
|
||||
app.select_next_missing_episode();
|
||||
}
|
||||
KeyCode::Char('s') if matches!(app.tab, Tab::Library) && app.detail.is_some() => {
|
||||
app.search_now_selected().await;
|
||||
}
|
||||
|
|
@ -259,20 +207,9 @@ async fn handle_key(app: &mut App, key: KeyEvent, roots: &LibraryRoots) {
|
|||
}
|
||||
}
|
||||
|
||||
fn tab_offset(current: Tab, delta: i32) -> Tab {
|
||||
let idx = Tab::ALL.iter().position(|t| *t == current).unwrap_or(0) as i32;
|
||||
let len = Tab::ALL.len() as i32;
|
||||
Tab::ALL[(idx + delta).rem_euclid(len) as usize]
|
||||
}
|
||||
|
||||
fn switch_tab(app: &mut App, tab: Tab) {
|
||||
if app.tab == tab {
|
||||
return;
|
||||
}
|
||||
if matches!(app.focus, Focus::Candidates) {
|
||||
app.close_candidates();
|
||||
}
|
||||
app.tab = tab;
|
||||
fn cycle_tab(app: &mut App) {
|
||||
let idx = Tab::ALL.iter().position(|t| *t == app.tab).unwrap_or(0);
|
||||
app.tab = Tab::ALL[(idx + 1) % Tab::ALL.len()];
|
||||
app.detail = None;
|
||||
app.profile_detail = None;
|
||||
app.profile_weight_state.select(None);
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ use ratatui::widgets::{Block, Borders, Clear, List, ListItem, Paragraph, Tabs};
|
|||
use ratatui::Frame;
|
||||
|
||||
use crate::app::{App, Focus, StuckSection, Tab};
|
||||
use breadarr_shared::dto::CycleInfo;
|
||||
|
||||
// Shared color palette — kept to these meanings so a color never has to be
|
||||
// second-guessed at a glance:
|
||||
|
|
@ -59,7 +58,6 @@ fn context_keybindings(app: &App) -> Vec<(&'static str, &'static str)> {
|
|||
Tab::Library if app.detail.is_some() => vec![
|
||||
("Esc", "back"),
|
||||
("s", "search now"),
|
||||
("n", "next missing"),
|
||||
("m", "monitor show"),
|
||||
("e", "monitor episode"),
|
||||
("S", "monitor season"),
|
||||
|
|
@ -67,19 +65,15 @@ fn context_keybindings(app: &App) -> Vec<(&'static str, &'static str)> {
|
|||
("d", "delete file"),
|
||||
("c", "pick release"),
|
||||
],
|
||||
Tab::Library if matches!(app.focus, Focus::LibraryFilterInput) => {
|
||||
vec![("Enter", "keep filter"), ("Esc", "clear filter")]
|
||||
}
|
||||
Tab::Library => vec![
|
||||
("Enter", "open detail"),
|
||||
("/", "filter title"),
|
||||
("f", "cycle filter"),
|
||||
("o", "cycle sort"),
|
||||
("m", "monitor toggle"),
|
||||
],
|
||||
Tab::Review => vec![("a", "approve"), ("r", "reject")],
|
||||
Tab::Add => match app.focus {
|
||||
Focus::AddSearchInput => vec![("Enter", "search"), ("Esc", "clear")],
|
||||
Focus::AddSearchInput => vec![("Enter", "search")],
|
||||
_ => vec![("Enter", "add"), ("Esc", "back to search")],
|
||||
},
|
||||
Tab::Profiles if app.profile_detail.is_some() => {
|
||||
|
|
@ -87,17 +81,13 @@ fn context_keybindings(app: &App) -> Vec<(&'static str, &'static str)> {
|
|||
}
|
||||
Tab::Profiles => vec![("Enter", "open profile")],
|
||||
Tab::Stuck => vec![("Left/Right", "switch section"), ("Enter", "jump to show")],
|
||||
Tab::Calendar => vec![("Enter", "jump to show")],
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
const GLOBAL_KEYS: &[(&str, &str)] = &[
|
||||
("Tab/S-Tab", "switch tab"),
|
||||
("1-8", "jump tab"),
|
||||
("Tab", "switch tab"),
|
||||
("j/k", "move"),
|
||||
("g/G", "first/last"),
|
||||
("PgUp/PgDn", "page"),
|
||||
("?", "help"),
|
||||
("R", "refresh now"),
|
||||
("q", "quit"),
|
||||
|
|
@ -138,7 +128,7 @@ fn draw_help_overlay(frame: &mut Frame, area: Rect, app: &App) {
|
|||
])
|
||||
}));
|
||||
|
||||
let popup = centered_rect(52, lines.len() as u16 + 2, area);
|
||||
let popup = centered_rect(50, lines.len() as u16 + 2, area);
|
||||
frame.render_widget(Clear, popup);
|
||||
let paragraph = Paragraph::new(lines).block(
|
||||
Block::default()
|
||||
|
|
@ -148,47 +138,8 @@ fn draw_help_overlay(frame: &mut Frame, area: Rect, app: &App) {
|
|||
frame.render_widget(paragraph, popup);
|
||||
}
|
||||
|
||||
fn tab_label(tab: Tab, app: &App) -> String {
|
||||
match tab {
|
||||
Tab::Library => {
|
||||
let missing: i64 = app.media_items.iter().map(|m| m.missing_count).sum();
|
||||
if missing > 0 {
|
||||
format!("Library ({missing})")
|
||||
} else {
|
||||
tab.title().to_string()
|
||||
}
|
||||
}
|
||||
Tab::Review => {
|
||||
let n = if matches!(app.tab, Tab::Review) {
|
||||
app.review_items.len()
|
||||
} else {
|
||||
app.review_count
|
||||
};
|
||||
if n > 0 {
|
||||
format!("Review ({n})")
|
||||
} else {
|
||||
tab.title().to_string()
|
||||
}
|
||||
}
|
||||
Tab::Stuck => {
|
||||
let n = app.stuck.as_ref().map_or(app.stuck_count, |r| {
|
||||
r.stalled_grabs.len() + r.maxed_out_search_targets.len()
|
||||
});
|
||||
if n > 0 {
|
||||
format!("Stuck ({n})")
|
||||
} else {
|
||||
tab.title().to_string()
|
||||
}
|
||||
}
|
||||
_ => tab.title().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_tabs(frame: &mut Frame, area: Rect, app: &App) {
|
||||
let titles: Vec<Line> = Tab::ALL
|
||||
.iter()
|
||||
.map(|t| Line::from(tab_label(*t, app)))
|
||||
.collect();
|
||||
let titles: Vec<Line> = Tab::ALL.iter().map(|t| Line::from(t.title())).collect();
|
||||
let selected = Tab::ALL.iter().position(|t| *t == app.tab).unwrap_or(0);
|
||||
|
||||
let (daemon_label, daemon_color) = match (&app.daemon_up, &app.health) {
|
||||
|
|
@ -239,11 +190,6 @@ fn draw_library(frame: &mut Frame, area: Rect, app: &App) {
|
|||
return;
|
||||
}
|
||||
|
||||
if detail.kind == "movie" || detail.episodes.is_empty() {
|
||||
draw_movie_detail(frame, area, app, detail);
|
||||
return;
|
||||
}
|
||||
|
||||
let items: Vec<ListItem> = detail
|
||||
.episodes
|
||||
.iter()
|
||||
|
|
@ -340,19 +286,9 @@ fn draw_library(frame: &mut Frame, area: Rect, app: &App) {
|
|||
]))
|
||||
})
|
||||
.collect();
|
||||
let search = if app.library_query.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" search: {}", app.library_query)
|
||||
};
|
||||
let filter_caret = if matches!(app.focus, Focus::LibraryFilterInput) {
|
||||
"▋"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let list = List::new(items)
|
||||
.block(Block::default().borders(Borders::ALL).title(format!(
|
||||
"Library ({}/{}) — filter: {} sort: {}{search}{filter_caret}",
|
||||
"Monitored Shows ({}/{}) — filter: {} sort: {}",
|
||||
app.library_view.len(),
|
||||
app.media_items.len(),
|
||||
app.library_filter.label(),
|
||||
|
|
@ -363,61 +299,6 @@ fn draw_library(frame: &mut Frame, area: Rect, app: &App) {
|
|||
frame.render_stateful_widget(list, area, &mut state);
|
||||
}
|
||||
|
||||
fn draw_movie_detail(
|
||||
frame: &mut Frame,
|
||||
area: Rect,
|
||||
app: &App,
|
||||
detail: &breadarr_shared::dto::MediaItemDetail,
|
||||
) {
|
||||
let confirm = if app.confirm_delete {
|
||||
" — x AGAIN TO DELETE"
|
||||
} else if app.confirm_delete_file {
|
||||
" — d AGAIN TO DELETE FILE"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let monitor_label = if detail.monitored {
|
||||
"monitored"
|
||||
} else {
|
||||
"unmonitored"
|
||||
};
|
||||
let have = app
|
||||
.media_items
|
||||
.iter()
|
||||
.find(|m| m.id == detail.id)
|
||||
.map(|m| m.missing_count == 0);
|
||||
let file_line = match have {
|
||||
Some(true) => ("file on disk", Color::Green),
|
||||
Some(false) => ("missing", Color::Yellow),
|
||||
None => ("file status unknown", Color::DarkGray),
|
||||
};
|
||||
let kind = if detail.kind == "movie" {
|
||||
"Movie"
|
||||
} else {
|
||||
"Series"
|
||||
};
|
||||
let year = detail
|
||||
.year
|
||||
.map(|y| y.to_string())
|
||||
.unwrap_or_else(|| "—".into());
|
||||
let lines = vec![
|
||||
Line::from(Span::styled(
|
||||
format!("{} ({year})", detail.title),
|
||||
Style::default().add_modifier(Modifier::BOLD),
|
||||
)),
|
||||
Line::from(""),
|
||||
Line::from(format!("{kind} · {monitor_label}")),
|
||||
Line::from(Span::styled(file_line.0, Style::default().fg(file_line.1))),
|
||||
Line::from(format!("root: {}", detail.root_folder)),
|
||||
Line::from(""),
|
||||
Line::from("s search now c pick release m monitor d delete file x remove"),
|
||||
];
|
||||
let paragraph = Paragraph::new(lines).block(Block::default().borders(Borders::ALL).title(
|
||||
format!("{} ({year}) [{monitor_label}]{confirm}", detail.title),
|
||||
));
|
||||
frame.render_widget(paragraph, area);
|
||||
}
|
||||
|
||||
/// Manual release picker — candidates for whatever episode/movie was
|
||||
/// selected when `c` was pressed, scored (or gate-rejected with a reason)
|
||||
/// exactly like the automatic search pipeline would see them.
|
||||
|
|
@ -449,19 +330,15 @@ fn draw_candidates(frame: &mut Frame, area: Rect, app: &App, media_title: &str)
|
|||
if c.is_season_pack { " [PACK]" } else { "" },
|
||||
if c.is_repack { " [REPACK]" } else { "" },
|
||||
);
|
||||
let (verdict, color) = match (c.score, &c.rejected_reason) {
|
||||
(Some(score), _) if score >= 8.0 => (format!("score {score:.1}"), Color::Green),
|
||||
(Some(score), _) => (format!("score {score:.1}"), Color::Yellow),
|
||||
(None, Some(reason)) => (format!("REJECTED: {reason}"), Color::Red),
|
||||
(None, None) => ("unscored".to_string(), Color::DarkGray),
|
||||
let verdict = match (c.score, &c.rejected_reason) {
|
||||
(Some(score), _) => format!("score {score:.1}"),
|
||||
(None, Some(reason)) => format!("REJECTED: {reason}"),
|
||||
(None, None) => "unscored".to_string(),
|
||||
};
|
||||
ListItem::new(Line::from(vec![
|
||||
Span::raw(format!(
|
||||
"[{}] {} — {seeders} seeders, {size}{flags} — ",
|
||||
c.source_name, c.raw_title
|
||||
)),
|
||||
Span::styled(verdict, Style::default().fg(color)),
|
||||
]))
|
||||
ListItem::new(format!(
|
||||
"[{}] {} — {seeders} seeders, {size}{flags} — {verdict}",
|
||||
c.source_name, c.raw_title
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
let list = List::new(items)
|
||||
|
|
@ -473,32 +350,18 @@ fn draw_candidates(frame: &mut Frame, area: Rect, app: &App, media_title: &str)
|
|||
frame.render_stateful_widget(list, area, &mut state);
|
||||
}
|
||||
|
||||
fn history_status_color(status: &str) -> Color {
|
||||
match status {
|
||||
"imported" => Color::Green,
|
||||
"grabbed" => Color::Yellow,
|
||||
"failed" => Color::Red,
|
||||
_ => Color::DarkGray,
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_history(frame: &mut Frame, area: Rect, app: &App) {
|
||||
let items: Vec<ListItem> = app
|
||||
.releases
|
||||
.iter()
|
||||
.map(|r| {
|
||||
ListItem::new(Line::from(vec![
|
||||
Span::styled(
|
||||
format!("[{}]", r.status),
|
||||
Style::default().fg(history_status_color(&r.status)),
|
||||
),
|
||||
Span::raw(format!(
|
||||
" {} — {} (score {:.1})",
|
||||
r.media_title,
|
||||
r.raw_title,
|
||||
r.score.unwrap_or(0.0)
|
||||
)),
|
||||
]))
|
||||
ListItem::new(format!(
|
||||
"[{}] {} — {} (score {:.1})",
|
||||
r.status,
|
||||
r.media_title,
|
||||
r.raw_title,
|
||||
r.score.unwrap_or(0.0)
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
let list = List::new(items)
|
||||
|
|
@ -521,10 +384,7 @@ fn draw_review(frame: &mut Frame, area: Rect, app: &App) {
|
|||
Color::Green
|
||||
};
|
||||
ListItem::new(Line::from(vec![
|
||||
Span::styled(
|
||||
format!("({:.0}%)", r.confidence * 100.0),
|
||||
Style::default().fg(color),
|
||||
),
|
||||
Span::styled(format!("({:.0}%)", r.confidence * 100.0), Style::default().fg(color)),
|
||||
Span::raw(format!(
|
||||
" {} -> {}",
|
||||
r.raw_release_title,
|
||||
|
|
@ -579,10 +439,7 @@ fn draw_stuck(frame: &mut Frame, area: Rect, app: &App) {
|
|||
.iter()
|
||||
.map(|g| {
|
||||
ListItem::new(Line::from(Span::styled(
|
||||
format!(
|
||||
"{} — {} (grabbed {})",
|
||||
g.media_title, g.raw_title, g.grabbed_at
|
||||
),
|
||||
format!("{} — {} (grabbed {})", g.media_title, g.raw_title, g.grabbed_at),
|
||||
Style::default().fg(Color::Yellow),
|
||||
)))
|
||||
})
|
||||
|
|
@ -662,21 +519,12 @@ fn draw_add(frame: &mut Frame, area: Rect, app: &App) {
|
|||
.add_results
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let kind_color = match r.kind {
|
||||
crate::app::AddKind::Movie => Color::Magenta,
|
||||
crate::app::AddKind::Series => Color::Blue,
|
||||
};
|
||||
ListItem::new(Line::from(vec![
|
||||
Span::styled(
|
||||
format!("[{}] ", r.kind.label()),
|
||||
Style::default().fg(kind_color),
|
||||
),
|
||||
Span::raw(format!(
|
||||
"{} ({})",
|
||||
r.result.title,
|
||||
r.result.year.map(|y| y.to_string()).unwrap_or_default()
|
||||
)),
|
||||
]))
|
||||
ListItem::new(format!(
|
||||
"[{}] {} ({})",
|
||||
r.kind.label(),
|
||||
r.result.title,
|
||||
r.result.year.map(|y| y.to_string()).unwrap_or_default()
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
let list = List::new(items)
|
||||
|
|
@ -691,43 +539,36 @@ fn draw_add(frame: &mut Frame, area: Rect, app: &App) {
|
|||
}
|
||||
|
||||
/// What's aired recently or airs soon (a week back, three weeks forward —
|
||||
/// see `calendar::DAYS_PAST`/`DAYS_FUTURE` server-side). Selectable —
|
||||
/// Enter jumps to that episode in Library.
|
||||
/// see `calendar::DAYS_PAST`/`DAYS_FUTURE` server-side). Read-only, no
|
||||
/// selection — a lookahead view, not something acted on directly here.
|
||||
fn draw_calendar(frame: &mut Frame, area: Rect, app: &App) {
|
||||
let today = chrono::Local::now().date_naive().to_string();
|
||||
let items: Vec<ListItem> = app
|
||||
.calendar
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let (status, color) = if e.has_file {
|
||||
("✓", Color::Green)
|
||||
let status = if e.has_file {
|
||||
"✓"
|
||||
} else if !e.monitored {
|
||||
("-", Color::DarkGray)
|
||||
"-"
|
||||
} else if e.air_date.as_str() > today.as_str() {
|
||||
("…", Color::Yellow)
|
||||
"…"
|
||||
} else {
|
||||
("!", Color::Red)
|
||||
"!" // aired, monitored, still missing
|
||||
};
|
||||
let today_mark = if e.air_date == today { " today" } else { "" };
|
||||
let title = e.title.as_deref().unwrap_or("");
|
||||
ListItem::new(Line::from(vec![
|
||||
Span::styled(status, Style::default().fg(color)),
|
||||
Span::raw(format!(
|
||||
" {} {} S{:02}E{:02} {title}{today_mark}",
|
||||
e.air_date, e.media_title, e.season_number, e.episode_number
|
||||
)),
|
||||
]))
|
||||
ListItem::new(format!(
|
||||
"{status} {} {} S{:02}E{:02} {title}",
|
||||
e.air_date, e.media_title, e.season_number, e.episode_number
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
let list = List::new(items)
|
||||
.block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title("Calendar — Enter: jump ✓ have it … upcoming ! aired but missing"),
|
||||
)
|
||||
.highlight_style(Style::default().add_modifier(Modifier::REVERSED));
|
||||
let mut state = app.calendar_state.clone();
|
||||
frame.render_stateful_widget(list, area, &mut state);
|
||||
let list = List::new(items).block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title("Calendar — ✓ have it … upcoming ! aired but missing"),
|
||||
);
|
||||
frame.render_widget(list, area);
|
||||
}
|
||||
|
||||
/// Read-only report on `media_file_probe` state: corruption, under-quality,
|
||||
|
|
@ -747,7 +588,7 @@ fn draw_library_health(frame: &mut Frame, area: Rect, app: &App) {
|
|||
|
||||
let chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([Constraint::Length(6), Constraint::Min(3)])
|
||||
.constraints([Constraint::Length(5), Constraint::Min(3)])
|
||||
.split(area);
|
||||
|
||||
let s = &report.summary;
|
||||
|
|
@ -757,13 +598,8 @@ fn draw_library_health(frame: &mut Frame, area: Rect, app: &App) {
|
|||
.map(|c| format!("{}={}", c.codec, c.count))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let cycles = app
|
||||
.health
|
||||
.as_ref()
|
||||
.map(cycle_summary_line)
|
||||
.unwrap_or_default();
|
||||
let summary_text = format!(
|
||||
"{cycles}\n{} files, {:.1} GB total, {} probed — resolution: SD={} 720p={} 1080p={} 4K={} \
|
||||
"{} files, {:.1} GB total, {} probed — resolution: SD={} 720p={} 1080p={} 4K={} \
|
||||
— subtitles: {:.0}% — codecs: {codec_summary}",
|
||||
s.total_files,
|
||||
s.total_size_bytes as f64 / 1_073_741_824.0,
|
||||
|
|
@ -832,38 +668,12 @@ fn draw_library_health(frame: &mut Frame, area: Rect, app: &App) {
|
|||
items.push(ListItem::new("Nothing flagged — library looks clean."));
|
||||
}
|
||||
|
||||
let list = List::new(items)
|
||||
.block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title("Flagged files"),
|
||||
)
|
||||
.highlight_style(Style::default().add_modifier(Modifier::REVERSED));
|
||||
let mut state = app.health_state.clone();
|
||||
frame.render_stateful_widget(list, chunks[1], &mut state);
|
||||
}
|
||||
|
||||
fn cycle_bit(name: &str, info: &Option<CycleInfo>) -> String {
|
||||
match info {
|
||||
Some(c) if c.ok => format!("{name}: ok"),
|
||||
Some(_) => format!("{name}: FAIL"),
|
||||
None => format!("{name}: —"),
|
||||
}
|
||||
}
|
||||
|
||||
fn cycle_summary_line(h: &breadarr_shared::dto::HealthDetail) -> String {
|
||||
format!(
|
||||
"{} | {} | {} | {}{}",
|
||||
cycle_bit("grab", &h.last_grab_cycle),
|
||||
cycle_bit("import", &h.last_import_cycle),
|
||||
cycle_bit("search", &h.last_search_cycle),
|
||||
cycle_bit("upgrade", &h.last_upgrade_cycle),
|
||||
if h.search_halted {
|
||||
" | search HALTED"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
)
|
||||
let list = List::new(items).block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.title("Flagged files"),
|
||||
);
|
||||
frame.render_widget(list, chunks[1]);
|
||||
}
|
||||
|
||||
/// Quality-profile weight editing — list of profiles, then (once one is
|
||||
|
|
@ -935,13 +745,6 @@ fn draw_status(frame: &mut Frame, area: Rect, app: &App) {
|
|||
.collect();
|
||||
format!("{} | ?: help", hints.join(" | "))
|
||||
};
|
||||
let style = if app.busy {
|
||||
Style::default().fg(Color::Yellow)
|
||||
} else {
|
||||
Style::default()
|
||||
};
|
||||
let status = Paragraph::new(text)
|
||||
.style(style)
|
||||
.block(Block::default().borders(Borders::ALL));
|
||||
let status = Paragraph::new(text).block(Block::default().borders(Borders::ALL));
|
||||
frame.render_widget(status, area);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -71,7 +71,7 @@ pub enum BackgroundRequest {
|
|||
/// Mutex` is fine here (unlike `conn`) since updates are a single field
|
||||
/// write with no `.await` in between. Exists so a silently-stalled
|
||||
/// background loop (e.g. every cycle erroring for hours) is visible from a
|
||||
/// single `/health/detail` call instead of only in the journal.
|
||||
/// single `/health` call instead of only in the journal.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct CycleStatus {
|
||||
pub last_grab: Option<CycleRecord>,
|
||||
|
|
@ -96,11 +96,10 @@ pub struct CycleRecord {
|
|||
/// Rejects any request lacking `Authorization: Bearer <config.daemon.api_token>`
|
||||
/// once a token is actually configured — a no-op (every request passes)
|
||||
/// when it's empty, so an unconfigured install behaves exactly as before.
|
||||
/// Exact `/health` is deliberately exempt even with a token configured:
|
||||
/// it's commonly polled by external monitoring (e.g. an uptime dashboard)
|
||||
/// that has no reason to hold the same credential as the TUI/API client,
|
||||
/// and it exposes nothing more sensitive than "is the process alive."
|
||||
/// `/health/detail` is *not* exempt — it includes cycle status.
|
||||
/// `/health` is deliberately exempt even with a token configured: it's
|
||||
/// commonly polled by external monitoring (e.g. an uptime dashboard) that
|
||||
/// has no reason to hold the same credential as the TUI/API client, and it
|
||||
/// exposes nothing more sensitive than "is the process alive."
|
||||
async fn require_api_token(State(state): State<AppState>, req: Request, next: Next) -> Response {
|
||||
if state.config.daemon.api_token.is_empty() || req.uri().path() == "/health" {
|
||||
return next.run(req).await;
|
||||
|
|
@ -119,27 +118,21 @@ async fn require_api_token(State(state): State<AppState>, req: Request, next: Ne
|
|||
|
||||
/// Byte-wise `==` short-circuits on the first mismatching byte, making
|
||||
/// comparison time a (weak, but real) signal of how many leading bytes of a
|
||||
/// guessed token were correct — a classic timing oracle. This always walks
|
||||
/// the longer input (padding the shorter against a dummy) and folds a
|
||||
/// length mismatch into the accumulator so a length difference is not a
|
||||
/// first-instruction return. Pair with `api_token.len() >= 16` in
|
||||
/// `Config::validate` so a length-oracle of short guesses is useless.
|
||||
/// guessed token were correct — a classic timing oracle. This always
|
||||
/// touches every byte of the shorter input regardless of where they first
|
||||
/// differ. Real-world exposure here is low (loopback-bound by default, a
|
||||
/// personal single-user daemon), but it costs nothing to close.
|
||||
fn constant_time_eq(a: &str, b: &str) -> bool {
|
||||
let (a, b) = (a.as_bytes(), b.as_bytes());
|
||||
let max = a.len().max(b.len());
|
||||
let mut acc = u8::from(a.len() != b.len());
|
||||
for i in 0..max {
|
||||
let x = *a.get(i).unwrap_or(&0);
|
||||
let y = *b.get(i).unwrap_or(&0);
|
||||
acc |= x ^ y;
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
acc == 0
|
||||
a.iter().zip(b.iter()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
||||
}
|
||||
|
||||
pub fn router(state: AppState) -> Router {
|
||||
Router::new()
|
||||
.route("/health", get(routes::health::health))
|
||||
.route("/health/detail", get(routes::health::health_detail))
|
||||
.route("/media", get(routes::media::list).post(routes::media::add))
|
||||
.route(
|
||||
"/media/:id",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use axum::extract::State;
|
||||
use axum::Json;
|
||||
use breadarr_shared::dto::{CycleInfo, HealthDetail, HealthStatus};
|
||||
use breadarr_shared::dto::{CycleInfo, HealthDetail};
|
||||
|
||||
use crate::api::AppState;
|
||||
|
||||
|
|
@ -12,15 +12,7 @@ fn to_info(r: &crate::api::CycleRecord) -> CycleInfo {
|
|||
}
|
||||
}
|
||||
|
||||
/// Unauthenticated liveness — cheap, no cycle detail.
|
||||
pub async fn health() -> Json<HealthStatus> {
|
||||
Json(HealthStatus {
|
||||
status: "ok".to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Authenticated cycle-status payload (same as the old `/health`).
|
||||
pub async fn health_detail(State(state): State<AppState>) -> Json<HealthDetail> {
|
||||
pub async fn health(State(state): State<AppState>) -> Json<HealthDetail> {
|
||||
let status = state.cycle_status.lock().expect("cycle_status poisoned");
|
||||
Json(HealthDetail {
|
||||
status: "ok".to_string(),
|
||||
|
|
|
|||
|
|
@ -1,5 +1,3 @@
|
|||
use std::path::{Component, Path as FsPath, PathBuf};
|
||||
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
|
|
@ -7,7 +5,6 @@ use breadarr_shared::dto::{
|
|||
AddMovieRequest, AddMovieResponse, AddSeriesRequest, AddSeriesResponse, EpisodeSummary,
|
||||
MediaItemDetail, MediaItemSummary, SearchNowResult,
|
||||
};
|
||||
use breadarr_shared::Config;
|
||||
use rusqlite::{params, OptionalExtension};
|
||||
|
||||
use crate::api::AppState;
|
||||
|
|
@ -48,7 +45,7 @@ pub async fn detail(
|
|||
Path(id): Path<i64>,
|
||||
) -> Result<Json<MediaItemDetail>, (StatusCode, String)> {
|
||||
let conn = state.conn.lock().await;
|
||||
let row = conn
|
||||
let (kind, title, year, monitored, root_folder) = conn
|
||||
.query_row(
|
||||
"SELECT kind, title, year, monitored, root_folder FROM media_item WHERE id = ?1",
|
||||
params![id],
|
||||
|
|
@ -62,11 +59,7 @@ pub async fn detail(
|
|||
))
|
||||
},
|
||||
)
|
||||
.optional()
|
||||
.map_err(internal)?;
|
||||
let Some((kind, title, year, monitored, root_folder)) = row else {
|
||||
return Err((StatusCode::NOT_FOUND, format!("no media_item {id}")));
|
||||
};
|
||||
.map_err(|e| (StatusCode::NOT_FOUND, e.to_string()))?;
|
||||
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
|
|
@ -112,8 +105,6 @@ pub async fn add(
|
|||
));
|
||||
};
|
||||
|
||||
let root_folder = constrain_root_folder(&req.root_folder, &state.config.default_root_folder())?;
|
||||
|
||||
// Fetch before taking the lock — a sync MutexGuard can't be held across
|
||||
// an `.await` point.
|
||||
let episodes = tvdb.episodes(&req.tvdb_id).await.map_err(internal)?;
|
||||
|
|
@ -126,7 +117,7 @@ pub async fn add(
|
|||
&req.title,
|
||||
req.year.map(|y| y as u32),
|
||||
&req.aliases,
|
||||
&root_folder,
|
||||
&req.root_folder,
|
||||
1,
|
||||
&episodes,
|
||||
)
|
||||
|
|
@ -140,14 +131,13 @@ pub async fn add_movie(
|
|||
State(state): State<AppState>,
|
||||
Json(req): Json<AddMovieRequest>,
|
||||
) -> Result<Json<AddMovieResponse>, (StatusCode, String)> {
|
||||
let root_folder = constrain_root_folder(&req.root_folder, &state.config.movies_root_folder())?;
|
||||
let conn = state.conn.lock().await;
|
||||
let media_item_id = metadata::insert_movie(
|
||||
&conn,
|
||||
&req.tmdb_id,
|
||||
&req.title,
|
||||
req.year.map(|y| y as u32),
|
||||
&root_folder,
|
||||
&req.root_folder,
|
||||
2,
|
||||
)
|
||||
.map_err(internal)?;
|
||||
|
|
@ -218,9 +208,13 @@ async fn set_episode_monitored(
|
|||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// Toggles every episode in one season and the `season.monitored` flag
|
||||
/// when a season row exists (`insert_series` writes those). A missing
|
||||
/// season row is not an error — episodes still update.
|
||||
/// Toggles every episode in one season at once — a season-level "row" isn't
|
||||
/// separately tracked (the `season` table exists in the schema but was
|
||||
/// never actually populated by any insert path, so resurrecting it just to
|
||||
/// hold one redundant monitored flag would mean keeping two copies of the
|
||||
/// same state in sync for no behavioral gain); bulk-updating the episodes
|
||||
/// directly gets the identical practical effect — this season's episodes
|
||||
/// stop appearing in search enumeration — with one source of truth.
|
||||
pub async fn monitor_season(
|
||||
State(state): State<AppState>,
|
||||
Path((media_item_id, season_number)): Path<(i64, i64)>,
|
||||
|
|
@ -248,11 +242,6 @@ async fn set_season_monitored(
|
|||
params![monitored as i64, media_item_id, season_number],
|
||||
)
|
||||
.map_err(internal)?;
|
||||
// Season row is best-effort — older libraries (or movies) may have none.
|
||||
let _ = conn.execute(
|
||||
"UPDATE season SET monitored = ?1 WHERE media_item_id = ?2 AND season_number = ?3",
|
||||
params![monitored as i64, media_item_id, season_number],
|
||||
);
|
||||
if rows == 0 {
|
||||
return Err((
|
||||
StatusCode::NOT_FOUND,
|
||||
|
|
@ -294,20 +283,21 @@ pub async fn delete_episode_file(
|
|||
Path(episode_id): Path<i64>,
|
||||
) -> Result<StatusCode, (StatusCode, String)> {
|
||||
let conn = state.conn.lock().await;
|
||||
let files = tracked_files(
|
||||
&conn,
|
||||
"SELECT id, path FROM episode_file WHERE episode_id = ?1",
|
||||
episode_id,
|
||||
)?;
|
||||
if files.is_empty() {
|
||||
let row: Option<(i64, String)> = conn
|
||||
.query_row(
|
||||
"SELECT id, path FROM episode_file WHERE episode_id = ?1",
|
||||
params![episode_id],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.optional()
|
||||
.map_err(internal)?;
|
||||
let Some((file_id, path)) = row else {
|
||||
return Err((
|
||||
StatusCode::NOT_FOUND,
|
||||
format!("no file tracked for episode {episode_id}"),
|
||||
));
|
||||
}
|
||||
for (file_id, path) in files {
|
||||
delete_file_and_clear(&conn, &path, file_id)?;
|
||||
}
|
||||
};
|
||||
delete_file_and_clear(&conn, &path, file_id)?;
|
||||
conn.execute(
|
||||
"UPDATE episode SET has_file = 0 WHERE id = ?1",
|
||||
params![episode_id],
|
||||
|
|
@ -325,20 +315,21 @@ pub async fn delete_movie_file(
|
|||
Path(media_item_id): Path<i64>,
|
||||
) -> Result<StatusCode, (StatusCode, String)> {
|
||||
let conn = state.conn.lock().await;
|
||||
let files = tracked_files(
|
||||
&conn,
|
||||
"SELECT id, path FROM episode_file WHERE media_item_id = ?1 AND episode_id IS NULL",
|
||||
media_item_id,
|
||||
)?;
|
||||
if files.is_empty() {
|
||||
let row: Option<(i64, String)> = conn
|
||||
.query_row(
|
||||
"SELECT id, path FROM episode_file WHERE media_item_id = ?1 AND episode_id IS NULL",
|
||||
params![media_item_id],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.optional()
|
||||
.map_err(internal)?;
|
||||
let Some((file_id, path)) = row else {
|
||||
return Err((
|
||||
StatusCode::NOT_FOUND,
|
||||
format!("no file tracked for media_item {media_item_id}"),
|
||||
));
|
||||
}
|
||||
for (file_id, path) in files {
|
||||
delete_file_and_clear(&conn, &path, file_id)?;
|
||||
}
|
||||
};
|
||||
delete_file_and_clear(&conn, &path, file_id)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
|
|
@ -348,20 +339,6 @@ pub async fn delete_movie_file(
|
|||
/// alone, which a TV show shares across every one of its episode rows and
|
||||
/// would otherwise risk wiping an entire show's tracked files instead of
|
||||
/// the one the caller actually looked up.
|
||||
fn tracked_files(
|
||||
conn: &rusqlite::Connection,
|
||||
sql: &str,
|
||||
id: i64,
|
||||
) -> Result<Vec<(i64, String)>, (StatusCode, String)> {
|
||||
let mut stmt = conn.prepare(sql).map_err(internal)?;
|
||||
let files = stmt
|
||||
.query_map(params![id], |row| Ok((row.get(0)?, row.get(1)?)))
|
||||
.map_err(internal)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()
|
||||
.map_err(internal)?;
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn delete_file_and_clear(
|
||||
conn: &rusqlite::Connection,
|
||||
path: &str,
|
||||
|
|
@ -525,59 +502,6 @@ async fn grab_candidate_via_background(
|
|||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// After `~/` expand and lexical normalize, the path must stay under
|
||||
/// `allowed_root`. `..` components and absolute paths outside that root
|
||||
/// are rejected with 400.
|
||||
fn constrain_root_folder(
|
||||
requested: &str,
|
||||
allowed_root: &FsPath,
|
||||
) -> Result<String, (StatusCode, String)> {
|
||||
let requested = requested.trim();
|
||||
if requested.is_empty() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
"root_folder must not be empty".into(),
|
||||
));
|
||||
}
|
||||
let expanded = Config::expand_path(requested);
|
||||
if expanded
|
||||
.components()
|
||||
.any(|c| matches!(c, Component::ParentDir))
|
||||
{
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
"root_folder must not contain '..'".into(),
|
||||
));
|
||||
}
|
||||
let candidate = if expanded.is_absolute() {
|
||||
normalize_lexically(&expanded)
|
||||
} else {
|
||||
normalize_lexically(&allowed_root.join(expanded))
|
||||
};
|
||||
let root = normalize_lexically(allowed_root);
|
||||
if !candidate.starts_with(&root) {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!("root_folder must be under {}", root.display()),
|
||||
));
|
||||
}
|
||||
Ok(candidate.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
fn normalize_lexically(path: &FsPath) -> PathBuf {
|
||||
let mut out = PathBuf::new();
|
||||
for c in path.components() {
|
||||
match c {
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
out.pop();
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn internal<E: std::fmt::Display>(e: E) -> (StatusCode, String) {
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -68,12 +68,6 @@ pub async fn update_weights(
|
|||
Path(id): Path<i64>,
|
||||
Json(req): Json<UpdateQualityProfileWeightsRequest>,
|
||||
) -> Result<StatusCode, (StatusCode, String)> {
|
||||
if !weights_are_valid(&req.weights) {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
"quality-profile weights must be finite and >= 0".into(),
|
||||
));
|
||||
}
|
||||
let weights_json = serde_json::to_string(&req.weights).map_err(internal)?;
|
||||
let conn = state.conn.lock().await;
|
||||
let updated = conn
|
||||
|
|
@ -88,59 +82,6 @@ pub async fn update_weights(
|
|||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
fn weights_are_valid(w: &WeightsDto) -> bool {
|
||||
[
|
||||
w.seeder,
|
||||
w.resolution_tier,
|
||||
w.source_tier,
|
||||
w.codec_tier,
|
||||
w.bit_depth,
|
||||
w.container,
|
||||
w.group_allowlist,
|
||||
w.repack,
|
||||
w.hdr,
|
||||
]
|
||||
.into_iter()
|
||||
.all(|v| v.is_finite() && v >= 0.0)
|
||||
}
|
||||
|
||||
fn internal<E: std::fmt::Display>(e: E) -> (StatusCode, String) {
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn valid_weights() -> WeightsDto {
|
||||
WeightsDto {
|
||||
seeder: 1.0,
|
||||
resolution_tier: 1.0,
|
||||
source_tier: 1.0,
|
||||
codec_tier: 1.0,
|
||||
bit_depth: 1.0,
|
||||
container: 1.0,
|
||||
group_allowlist: 1.0,
|
||||
repack: 1.0,
|
||||
hdr: 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weights_are_valid_accepts_finite_non_negative() {
|
||||
assert!(weights_are_valid(&valid_weights()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weights_are_valid_rejects_nan_inf_and_negative() {
|
||||
let mut w = valid_weights();
|
||||
w.seeder = f32::NAN;
|
||||
assert!(!weights_are_valid(&w));
|
||||
w = valid_weights();
|
||||
w.hdr = f32::INFINITY;
|
||||
assert!(!weights_are_valid(&w));
|
||||
w = valid_weights();
|
||||
w.repack = -0.1;
|
||||
assert!(!weights_are_valid(&w));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -75,22 +75,21 @@ pub async fn approve(
|
|||
}
|
||||
};
|
||||
|
||||
let torrent_hash =
|
||||
match scheduler::grab_prepared_approval(qbit, &state.qbit_category, &prepared).await {
|
||||
Ok(hash) => hash,
|
||||
Err(e) => {
|
||||
// The grab errored outright (not just "added but no hash
|
||||
// captured" — `finalize_review_approval` below handles that
|
||||
// case and still runs to completion). `prepare_review_approval`
|
||||
// already claimed this row into `approved` before we got here;
|
||||
// without releasing it back to `pending`, a transient
|
||||
// qBittorrent error would strand the review permanently
|
||||
// unapprovable with nothing ever recorded for it.
|
||||
let conn = state.conn.lock().await;
|
||||
let _ = scheduler::release_review_claim(&conn, id);
|
||||
return Err(internal(e));
|
||||
}
|
||||
};
|
||||
let torrent_hash = match scheduler::grab_prepared_approval(qbit, &state.qbit_category, &prepared).await {
|
||||
Ok(hash) => hash,
|
||||
Err(e) => {
|
||||
// The grab errored outright (not just "added but no hash
|
||||
// captured" — `finalize_review_approval` below handles that
|
||||
// case and still runs to completion). `prepare_review_approval`
|
||||
// already claimed this row into `approved` before we got here;
|
||||
// without releasing it back to `pending`, a transient
|
||||
// qBittorrent error would strand the review permanently
|
||||
// unapprovable with nothing ever recorded for it.
|
||||
let conn = state.conn.lock().await;
|
||||
let _ = scheduler::release_review_claim(&conn, id);
|
||||
return Err(internal(e));
|
||||
}
|
||||
};
|
||||
|
||||
{
|
||||
let conn = state.conn.lock().await;
|
||||
|
|
@ -111,12 +110,7 @@ pub async fn reject(
|
|||
Path(id): Path<i64>,
|
||||
) -> Result<StatusCode, (StatusCode, String)> {
|
||||
let conn = state.conn.lock().await;
|
||||
if !scheduler::reject_review(&conn, id).map_err(internal)? {
|
||||
return Err((
|
||||
StatusCode::NOT_FOUND,
|
||||
format!("no pending review item {id}"),
|
||||
));
|
||||
}
|
||||
scheduler::reject_review(&conn, id).map_err(internal)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -21,50 +21,43 @@ pub async fn search(
|
|||
State(state): State<AppState>,
|
||||
Query(params): Query<SearchParams>,
|
||||
) -> Result<Json<Vec<SearchResult>>, (StatusCode, String)> {
|
||||
match params.kind.as_str() {
|
||||
"movie" => {
|
||||
let Some(tmdb) = &state.tmdb else {
|
||||
return Err((
|
||||
StatusCode::PRECONDITION_FAILED,
|
||||
"tmdb.bearer_token is not configured".into(),
|
||||
));
|
||||
};
|
||||
let results = tmdb
|
||||
.search_movie(¶ms.q)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::BAD_GATEWAY, e.to_string()))?
|
||||
.into_iter()
|
||||
.map(|r| SearchResult {
|
||||
external_id: r.external_id,
|
||||
title: r.title,
|
||||
year: r.year.map(|y| y as i64),
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(results))
|
||||
}
|
||||
"series" => {
|
||||
let Some(tvdb) = &state.tvdb else {
|
||||
return Err((
|
||||
StatusCode::PRECONDITION_FAILED,
|
||||
"tvdb.api_key is not configured".into(),
|
||||
));
|
||||
};
|
||||
let results = tvdb
|
||||
.search_series(¶ms.q)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::BAD_GATEWAY, e.to_string()))?
|
||||
.into_iter()
|
||||
.map(|r| SearchResult {
|
||||
external_id: r.external_id,
|
||||
title: r.name,
|
||||
year: r.year.map(|y| y as i64),
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(results))
|
||||
}
|
||||
other => Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!("kind must be series or movie, got {other:?}"),
|
||||
)),
|
||||
if params.kind == "movie" {
|
||||
let Some(tmdb) = &state.tmdb else {
|
||||
return Err((
|
||||
StatusCode::PRECONDITION_FAILED,
|
||||
"tmdb.bearer_token is not configured".into(),
|
||||
));
|
||||
};
|
||||
let results = tmdb
|
||||
.search_movie(¶ms.q)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::BAD_GATEWAY, e.to_string()))?
|
||||
.into_iter()
|
||||
.map(|r| SearchResult {
|
||||
external_id: r.external_id,
|
||||
title: r.title,
|
||||
year: r.year.map(|y| y as i64),
|
||||
})
|
||||
.collect();
|
||||
return Ok(Json(results));
|
||||
}
|
||||
|
||||
let Some(tvdb) = &state.tvdb else {
|
||||
return Err((
|
||||
StatusCode::PRECONDITION_FAILED,
|
||||
"tvdb.api_key is not configured".into(),
|
||||
));
|
||||
};
|
||||
let results = tvdb
|
||||
.search_series(¶ms.q)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::BAD_GATEWAY, e.to_string()))?
|
||||
.into_iter()
|
||||
.map(|r| SearchResult {
|
||||
external_id: r.external_id,
|
||||
title: r.name,
|
||||
year: r.year.map(|y| y as i64),
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(results))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,14 +5,14 @@ use rusqlite::Connection;
|
|||
/// doesn't slowly fill the disk with an ever-growing pile of copies.
|
||||
const MAX_BACKUPS: usize = 5;
|
||||
|
||||
/// Writes a consistent snapshot of the existing database to a timestamped
|
||||
/// file under `<db-dir>/backups/`, then prunes old backups beyond
|
||||
/// Copies the database (and its WAL/SHM sidecar files, if present — WAL
|
||||
/// mode means the real state can be split across all three) to a timestamped
|
||||
/// backup before the daemon opens it, then prunes old backups beyond
|
||||
/// `MAX_BACKUPS`. A no-op if there's no existing database yet (fresh
|
||||
/// install — nothing to back up). Uses `VACUUM INTO` so WAL state is
|
||||
/// folded into one standalone file; a raw `fs::copy` of a live WAL
|
||||
/// database can be torn. Sonarr/Radarr back themselves up before every
|
||||
/// upgrade; breadarr has no migration framework to trigger that same
|
||||
/// moment, so this runs on every startup instead.
|
||||
/// install — nothing to back up). Sonarr/Radarr back themselves up before
|
||||
/// every upgrade; breadarr has no migration framework to trigger that same
|
||||
/// moment, so this runs on every startup instead, which is a superset of
|
||||
/// the same protection.
|
||||
pub fn backup_before_open(db_path: &std::path::Path) -> anyhow::Result<()> {
|
||||
if !db_path.exists() {
|
||||
return Ok(());
|
||||
|
|
@ -32,13 +32,15 @@ pub fn backup_before_open(db_path: &std::path::Path) -> anyhow::Result<()> {
|
|||
// and dedupe correctly instead of the second one silently overwriting.
|
||||
let timestamp = chrono::Utc::now().format("%Y%m%dT%H%M%S%3fZ");
|
||||
let dest = backup_dir.join(format!("{timestamp}-{stem}"));
|
||||
std::fs::copy(db_path, &dest)?;
|
||||
|
||||
let src = Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
|
||||
// Path is interpolated (VACUUM INTO does not bind `?` parameters);
|
||||
// single quotes in the path are doubled so the SQL string stays valid.
|
||||
let dest_sql = dest.to_string_lossy().replace('\'', "''");
|
||||
src.execute(&format!("VACUUM INTO '{dest_sql}'"), [])?;
|
||||
drop(src);
|
||||
for sidecar_ext in ["-wal", "-shm"] {
|
||||
let sidecar = std::path::PathBuf::from(format!("{}{sidecar_ext}", db_path.display()));
|
||||
if sidecar.exists() {
|
||||
let dest_sidecar = backup_dir.join(format!("{timestamp}-{stem}{sidecar_ext}"));
|
||||
std::fs::copy(&sidecar, &dest_sidecar)?;
|
||||
}
|
||||
}
|
||||
|
||||
prune_old_backups(&backup_dir, stem)?;
|
||||
Ok(())
|
||||
|
|
@ -278,7 +280,9 @@ pub fn init(conn: &Connection) -> anyhow::Result<()> {
|
|||
CREATE INDEX IF NOT EXISTS idx_event_history_media_item
|
||||
ON event_history(media_item_id, occurred_at);
|
||||
|
||||
-- Default profiles. Scoring reads these rows' `weights` on every grab.
|
||||
-- Placeholder profiles until Phase 6 builds real quality-scoring
|
||||
-- weights; media_item.quality_profile_id needs something to
|
||||
-- reference in the meantime.
|
||||
INSERT OR IGNORE INTO quality_profile (id, name, kind, weights)
|
||||
VALUES (1, 'Default TV', 'tv', '{}');
|
||||
INSERT OR IGNORE INTO quality_profile (id, name, kind, weights)
|
||||
|
|
@ -374,14 +378,7 @@ pub fn init(conn: &Connection) -> anyhow::Result<()> {
|
|||
-- concurrently regardless of how it happened (a stray duplicate
|
||||
-- enqueue, a daemon-restart reset racing a still-alive backfill).
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_transcode_job_active_episode_file
|
||||
ON transcode_job(episode_file_id) WHERE status IN ('pending','running');
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_release_status ON release(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_release_torrent_hash ON release(torrent_hash);
|
||||
CREATE INDEX IF NOT EXISTS idx_release_episode_id ON release(episode_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_episode_file_episode_id ON episode_file(episode_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_review_queue_status ON review_queue(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_episode_air_date ON episode(air_date);",
|
||||
ON transcode_job(episode_file_id) WHERE status IN ('pending','running');",
|
||||
)?;
|
||||
|
||||
// Progress watermark for stalled-download detection (added after the
|
||||
|
|
@ -480,155 +477,6 @@ pub fn init(conn: &Connection) -> anyhow::Result<()> {
|
|||
"INTEGER NOT NULL DEFAULT 0",
|
||||
)?;
|
||||
|
||||
ensure_indexes(conn)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn index_exists(conn: &Connection, name: &str) -> anyhow::Result<bool> {
|
||||
let n: i64 = conn.query_row(
|
||||
"SELECT count(*) FROM sqlite_master WHERE type = 'index' AND name = ?1",
|
||||
[name],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
Ok(n > 0)
|
||||
}
|
||||
|
||||
/// `CREATE UNIQUE INDEX IF NOT EXISTS` still errors when existing rows
|
||||
/// violate uniqueness (IF NOT EXISTS only checks the index name). A dirty
|
||||
/// production DB must still start, so uniqueness failures warn and skip.
|
||||
fn create_unique_index_best_effort(conn: &Connection, name: &str, ddl: &str) -> bool {
|
||||
match conn.execute(ddl, []) {
|
||||
Ok(_) => true,
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
index = name,
|
||||
error = %e,
|
||||
"skipping unique index; existing rows would violate it"
|
||||
);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete extra `media_item` rows that share a non-NULL `tvdb_id`/`tmdb_id`,
|
||||
/// keeping the lowest `id`. Extras with any `episode` or `episode_file`
|
||||
/// rows are left in place — those are not safe to drop. Returns whether
|
||||
/// every duplicate group was reduced to a single row.
|
||||
fn dedupe_media_item_external_id(conn: &Connection, column: &str) -> anyhow::Result<bool> {
|
||||
debug_assert!(column == "tvdb_id" || column == "tmdb_id");
|
||||
let sql = format!(
|
||||
"SELECT {column}, MIN(id) FROM media_item
|
||||
WHERE {column} IS NOT NULL
|
||||
GROUP BY {column}
|
||||
HAVING COUNT(*) > 1"
|
||||
);
|
||||
let dupes: Vec<(i64, i64)> = {
|
||||
let mut stmt = conn.prepare(&sql)?;
|
||||
let rows = stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
};
|
||||
|
||||
let mut safe = true;
|
||||
let extra_sql = format!("SELECT id FROM media_item WHERE {column} = ?1 AND id != ?2");
|
||||
for (ext_id, keep_id) in dupes {
|
||||
let extras: Vec<i64> = {
|
||||
let mut stmt = conn.prepare(&extra_sql)?;
|
||||
let rows = stmt.query_map(rusqlite::params![ext_id, keep_id], |row| row.get(0))?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
};
|
||||
for extra_id in extras {
|
||||
let episode_count: i64 = conn.query_row(
|
||||
"SELECT count(*) FROM episode WHERE media_item_id = ?1",
|
||||
[extra_id],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
let file_count: i64 = conn.query_row(
|
||||
"SELECT count(*) FROM episode_file WHERE media_item_id = ?1",
|
||||
[extra_id],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
if episode_count == 0 && file_count == 0 {
|
||||
conn.execute("DELETE FROM media_item WHERE id = ?1", [extra_id])?;
|
||||
} else {
|
||||
tracing::warn!(
|
||||
column,
|
||||
ext_id,
|
||||
keep_id,
|
||||
extra_id,
|
||||
episode_count,
|
||||
file_count,
|
||||
"cannot safely dedupe media_item; extra row has episodes or files"
|
||||
);
|
||||
safe = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(safe)
|
||||
}
|
||||
|
||||
fn ensure_unique_external_id_index(
|
||||
conn: &Connection,
|
||||
column: &str,
|
||||
unique_name: &str,
|
||||
unique_ddl: &str,
|
||||
lookup_ddl: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
let unique_ok = if dedupe_media_item_external_id(conn, column)? {
|
||||
create_unique_index_best_effort(conn, unique_name, unique_ddl)
|
||||
} else {
|
||||
tracing::warn!(
|
||||
index = unique_name,
|
||||
column,
|
||||
"skipping unique index; media_item still has unsafely-duplicated rows"
|
||||
);
|
||||
false
|
||||
};
|
||||
if !unique_ok && !index_exists(conn, unique_name)? {
|
||||
conn.execute(lookup_ddl, [])?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_indexes(conn: &Connection) -> anyhow::Result<()> {
|
||||
ensure_unique_external_id_index(
|
||||
conn,
|
||||
"tvdb_id",
|
||||
"idx_media_item_tvdb",
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_media_item_tvdb
|
||||
ON media_item(tvdb_id) WHERE tvdb_id IS NOT NULL",
|
||||
"CREATE INDEX IF NOT EXISTS idx_media_item_tvdb_lookup ON media_item(tvdb_id)",
|
||||
)?;
|
||||
ensure_unique_external_id_index(
|
||||
conn,
|
||||
"tmdb_id",
|
||||
"idx_media_item_tmdb",
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_media_item_tmdb
|
||||
ON media_item(tmdb_id) WHERE tmdb_id IS NOT NULL",
|
||||
"CREATE INDEX IF NOT EXISTS idx_media_item_tmdb_lookup ON media_item(tmdb_id)",
|
||||
)?;
|
||||
|
||||
create_unique_index_best_effort(
|
||||
conn,
|
||||
"idx_episode_file_path",
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_episode_file_path ON episode_file(path)",
|
||||
);
|
||||
create_unique_index_best_effort(
|
||||
conn,
|
||||
"idx_alias_item_text",
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_alias_item_text ON alias(media_item_id, text)",
|
||||
);
|
||||
create_unique_index_best_effort(
|
||||
conn,
|
||||
"idx_review_pending_title",
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_review_pending_title
|
||||
ON review_queue(candidate_media_item_id, raw_release_title)
|
||||
WHERE status = 'pending'",
|
||||
);
|
||||
// No unique on release(source_id, guid): status can cycle and a
|
||||
// re-grab of the same guid is legitimate. `seen_guid` already records
|
||||
// first-seen.
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -792,145 +640,19 @@ mod tests {
|
|||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
fn write_real_sqlite(db_path: &std::path::Path) {
|
||||
let conn = Connection::open(db_path).unwrap();
|
||||
init(&conn).unwrap();
|
||||
drop(conn);
|
||||
}
|
||||
|
||||
fn seed_movie(conn: &Connection, title: &str, tmdb_id: i64) -> i64 {
|
||||
conn.execute(
|
||||
"INSERT INTO media_item (kind, title, year, tmdb_id, monitored, quality_profile_id, root_folder)
|
||||
VALUES ('movie', ?1, NULL, ?2, 1, 2, '/tmp')",
|
||||
rusqlite::params![title, tmdb_id],
|
||||
)
|
||||
.unwrap();
|
||||
conn.last_insert_rowid()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_creates_unique_and_lookup_indexes_on_a_clean_database() {
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
init(&conn).unwrap();
|
||||
|
||||
assert!(index_exists(&conn, "idx_media_item_tvdb").unwrap());
|
||||
assert!(index_exists(&conn, "idx_media_item_tmdb").unwrap());
|
||||
assert!(index_exists(&conn, "idx_episode_file_path").unwrap());
|
||||
assert!(index_exists(&conn, "idx_alias_item_text").unwrap());
|
||||
assert!(index_exists(&conn, "idx_release_status").unwrap());
|
||||
assert!(index_exists(&conn, "idx_release_torrent_hash").unwrap());
|
||||
assert!(index_exists(&conn, "idx_release_episode_id").unwrap());
|
||||
assert!(index_exists(&conn, "idx_episode_file_episode_id").unwrap());
|
||||
assert!(index_exists(&conn, "idx_review_queue_status").unwrap());
|
||||
assert!(index_exists(&conn, "idx_review_pending_title").unwrap());
|
||||
assert!(index_exists(&conn, "idx_episode_air_date").unwrap());
|
||||
assert!(!index_exists(&conn, "idx_media_item_tvdb_lookup").unwrap());
|
||||
assert!(!index_exists(&conn, "idx_media_item_tmdb_lookup").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_dedupes_empty_duplicate_tmdb_rows_and_creates_unique_index() {
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
init(&conn).unwrap();
|
||||
conn.execute("DROP INDEX IF EXISTS idx_media_item_tmdb", [])
|
||||
.unwrap();
|
||||
|
||||
let first = seed_movie(&conn, "A", 99);
|
||||
seed_movie(&conn, "B", 99);
|
||||
|
||||
init(&conn).unwrap();
|
||||
|
||||
let count: i64 = conn
|
||||
.query_row(
|
||||
"SELECT count(*) FROM media_item WHERE tmdb_id = 99",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(count, 1);
|
||||
let kept: i64 = conn
|
||||
.query_row("SELECT id FROM media_item WHERE tmdb_id = 99", [], |r| {
|
||||
r.get(0)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(kept, first);
|
||||
assert!(index_exists(&conn, "idx_media_item_tmdb").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_skips_tmdb_unique_index_when_duplicate_has_files() {
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
init(&conn).unwrap();
|
||||
conn.execute("DROP INDEX IF EXISTS idx_media_item_tmdb", [])
|
||||
.unwrap();
|
||||
|
||||
seed_movie(&conn, "A", 99);
|
||||
let extra = seed_movie(&conn, "B", 99);
|
||||
conn.execute(
|
||||
"INSERT INTO episode_file (media_item_id, path, size_bytes, subtitle_status)
|
||||
VALUES (?1, '/tmp/b.mkv', 1, 'none')",
|
||||
[extra],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
init(&conn).unwrap();
|
||||
|
||||
let count: i64 = conn
|
||||
.query_row(
|
||||
"SELECT count(*) FROM media_item WHERE tmdb_id = 99",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(count, 2);
|
||||
assert!(!index_exists(&conn, "idx_media_item_tmdb").unwrap());
|
||||
assert!(index_exists(&conn, "idx_media_item_tmdb_lookup").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_skips_path_unique_index_when_duplicates_exist() {
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
init(&conn).unwrap();
|
||||
conn.execute("DROP INDEX IF EXISTS idx_episode_file_path", [])
|
||||
.unwrap();
|
||||
|
||||
let id = seed_movie(&conn, "A", 1);
|
||||
for _ in 0..2 {
|
||||
conn.execute(
|
||||
"INSERT INTO episode_file (media_item_id, path, size_bytes, subtitle_status)
|
||||
VALUES (?1, '/tmp/x.mkv', 1, 'none')",
|
||||
[id],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
init(&conn).unwrap();
|
||||
assert!(!index_exists(&conn, "idx_episode_file_path").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backup_before_open_copies_an_existing_database() {
|
||||
let dir = std::env::temp_dir().join(format!("breadarr-backup-copy-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let db_path = dir.join("breadarr.db");
|
||||
write_real_sqlite(&db_path);
|
||||
std::fs::write(&db_path, b"fake sqlite data").unwrap();
|
||||
|
||||
backup_before_open(&db_path).unwrap();
|
||||
|
||||
let backup_dir = dir.join("backups");
|
||||
let backups: Vec<_> = std::fs::read_dir(&backup_dir)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().path())
|
||||
.collect();
|
||||
let backups: Vec<_> = std::fs::read_dir(&backup_dir).unwrap().collect();
|
||||
assert_eq!(backups.len(), 1, "expected exactly one backup file");
|
||||
|
||||
let verify = Connection::open(&backups[0]).unwrap();
|
||||
let n: i64 = verify
|
||||
.query_row("SELECT count(*) FROM quality_profile", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(n, 2);
|
||||
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
|
|
@ -938,10 +660,9 @@ mod tests {
|
|||
fn backup_before_open_prunes_beyond_max_backups() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("breadarr-backup-prune-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let db_path = dir.join("breadarr.db");
|
||||
write_real_sqlite(&db_path);
|
||||
std::fs::write(&db_path, b"fake sqlite data").unwrap();
|
||||
|
||||
// One more than MAX_BACKUPS, sleeping a few ms between each so the
|
||||
// millisecond-resolution timestamp in the filename is guaranteed to
|
||||
|
|
|
|||
|
|
@ -201,17 +201,9 @@ pub(crate) fn walk_files(dir: &Path) -> Result<Vec<PathBuf>> {
|
|||
let mut out = Vec::new();
|
||||
for entry in std::fs::read_dir(dir)? {
|
||||
let path = entry?.path();
|
||||
// `path.is_dir()` follows symlinks, which would let a planted
|
||||
// directory link walk the importer (and library-scan) out of the
|
||||
// download/library root. Skip every symlink — file links to videos
|
||||
// included — and only recurse into real directories.
|
||||
let ft = std::fs::symlink_metadata(&path)?.file_type();
|
||||
if ft.is_symlink() {
|
||||
continue;
|
||||
}
|
||||
if ft.is_dir() {
|
||||
if path.is_dir() {
|
||||
out.extend(walk_files(&path)?);
|
||||
} else if ft.is_file() {
|
||||
} else {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
|
|
@ -271,25 +263,9 @@ pub(crate) fn deterministic_movie_filename(title: &str, year: Option<i64>, ext:
|
|||
}
|
||||
|
||||
pub(crate) fn sanitize(s: &str) -> String {
|
||||
let cleaned: String = s
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_control() || "/\\:*?\"<>|".contains(c) {
|
||||
'_'
|
||||
} else {
|
||||
c
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// After the replacements above, a title of `.` or `..` is still a
|
||||
// hostile path component (`root_folder/../file`). Slash-containing
|
||||
// titles become `foo_.._bar`, which is fine — only a lone `.`/`..`
|
||||
// can climb.
|
||||
if cleaned == "." || cleaned == ".." {
|
||||
"_".to_string()
|
||||
} else {
|
||||
cleaned
|
||||
}
|
||||
s.chars()
|
||||
.map(|c| if "/\\:*?\"<>|".contains(c) { '_' } else { c })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// True when there isn't enough free space at `dir` to hold `needed_bytes`.
|
||||
|
|
@ -359,116 +335,6 @@ fn move_or_copy_file(src: &Path, dest: &Path) -> Result<()> {
|
|||
})
|
||||
}
|
||||
|
||||
fn is_video_path(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.map(|e| VIDEO_EXTS.contains(&e.to_lowercase().as_str()))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Lexical `..`/`.` collapse without touching the filesystem — used when
|
||||
/// `canonicalize` can't (path missing) and by `remap_path` before the
|
||||
/// joined result is allowed to escape `host_prefix`.
|
||||
fn normalize_lexically(path: &Path) -> PathBuf {
|
||||
use std::path::Component;
|
||||
let mut out = PathBuf::new();
|
||||
for comp in path.components() {
|
||||
match comp {
|
||||
Component::Prefix(p) => out.push(p.as_os_str()),
|
||||
Component::RootDir => out.push(Component::RootDir.as_os_str()),
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
out.pop();
|
||||
}
|
||||
Component::Normal(c) => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn canonicalize_or_normalize(path: &Path) -> PathBuf {
|
||||
if let Ok(canon) = std::fs::canonicalize(path) {
|
||||
return canon;
|
||||
}
|
||||
if let Some(parent) = path.parent() {
|
||||
if let (Ok(canon_parent), Some(name)) = (std::fs::canonicalize(parent), path.file_name()) {
|
||||
return canon_parent.join(name);
|
||||
}
|
||||
}
|
||||
if path.is_absolute() {
|
||||
return normalize_lexically(path);
|
||||
}
|
||||
std::env::current_dir()
|
||||
.map(|cwd| normalize_lexically(&cwd.join(path)))
|
||||
.unwrap_or_else(|_| normalize_lexically(path))
|
||||
}
|
||||
|
||||
fn is_strictly_inside(path: &Path, root: &Path) -> bool {
|
||||
let path = canonicalize_or_normalize(path);
|
||||
let root = canonicalize_or_normalize(root);
|
||||
path.starts_with(&root) && path != root
|
||||
}
|
||||
|
||||
fn is_common_filesystem_root(path: &Path) -> bool {
|
||||
let normalized = canonicalize_or_normalize(path);
|
||||
if normalized == Path::new("/")
|
||||
|| normalized == Path::new("/mnt")
|
||||
|| normalized == Path::new("/media")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if let Some(home) = std::env::var_os("HOME") {
|
||||
if normalized == Path::new(&home) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// `true` only for a per-torrent folder we are willing to `remove_dir_all`.
|
||||
/// A configured `host_downloads_path` must strictly contain `content_path`;
|
||||
/// an empty host falls back to "has a real parent that isn't `/` and isn't
|
||||
/// a well-known root" so a default-empty config cannot wipe `/` or `$HOME`.
|
||||
fn is_safe_cleanup_target(content_path: &Path, host_downloads_path: &str) -> bool {
|
||||
let meta = match std::fs::symlink_metadata(content_path) {
|
||||
Ok(m) => m,
|
||||
Err(_) => return false,
|
||||
};
|
||||
if !meta.is_dir() || meta.file_type().is_symlink() {
|
||||
return false;
|
||||
}
|
||||
if !host_downloads_path.is_empty() {
|
||||
return is_strictly_inside(content_path, Path::new(host_downloads_path));
|
||||
}
|
||||
if is_common_filesystem_root(content_path) {
|
||||
return false;
|
||||
}
|
||||
let Some(parent) = content_path.parent() else {
|
||||
return false;
|
||||
};
|
||||
if parent == Path::new("/") || parent.as_os_str().is_empty() || !parent.exists() {
|
||||
return false;
|
||||
}
|
||||
content_path != parent
|
||||
}
|
||||
|
||||
fn dir_contains_video_files(dir: &Path) -> bool {
|
||||
match walk_files(dir) {
|
||||
Ok(files) => files.iter().any(|p| is_video_path(p)),
|
||||
// A walk failure must not authorize a wipe.
|
||||
Err(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_non_video_files(dir: &Path) -> Result<()> {
|
||||
for path in walk_files(dir)? {
|
||||
if !is_video_path(&path) {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes whatever's left of a torrent's download folder once every file
|
||||
/// breadarr cares about has already been moved out of it — split out from
|
||||
/// `run_import_cycle` so it's directly testable without a real qBittorrent
|
||||
|
|
@ -477,21 +343,14 @@ fn remove_non_video_files(dir: &Path) -> Result<()> {
|
|||
/// `.jpg` sidecars) is otherwise left behind forever, since nothing else
|
||||
/// ever points at it once the torrent itself is gone from qBittorrent. A
|
||||
/// bare file (a release with no wrapping folder) needs no cleanup here —
|
||||
/// `move_or_copy_file` already consumed it.
|
||||
///
|
||||
/// Never wipes a directory that still contains a video we didn't import
|
||||
/// (unmatched pack files), and never `remove_dir_all`s the downloads root
|
||||
/// itself — `host_downloads_path` defaults to `""`, so a raw `!= host`
|
||||
/// comparison is not enough.
|
||||
/// `move_or_copy_file` already consumed it. The `!= host_downloads_path`
|
||||
/// guard is defense in depth against a malformed `content_path` resolving
|
||||
/// to the downloads root itself; every real torrent lands in its own
|
||||
/// subdirectory or as a single file, never the root.
|
||||
fn cleanup_leftover_download_dir(content_path: &Path, host_downloads_path: &str) -> Result<()> {
|
||||
if !is_safe_cleanup_target(content_path, host_downloads_path) {
|
||||
return Ok(());
|
||||
if content_path.is_dir() && content_path != Path::new(host_downloads_path) {
|
||||
std::fs::remove_dir_all(content_path)?;
|
||||
}
|
||||
if dir_contains_video_files(content_path) {
|
||||
remove_non_video_files(content_path)?;
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::remove_dir_all(content_path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -1477,22 +1336,7 @@ fn remap_path(reported: &str, container_prefix: &str, host_prefix: &str) -> Path
|
|||
return PathBuf::from(reported);
|
||||
}
|
||||
match reported.strip_prefix(container_prefix) {
|
||||
Some(rest) => {
|
||||
let rest_path = Path::new(rest);
|
||||
if rest_path
|
||||
.components()
|
||||
.any(|c| matches!(c, std::path::Component::ParentDir))
|
||||
{
|
||||
return PathBuf::from(reported);
|
||||
}
|
||||
let joined = PathBuf::from(format!("{host_prefix}{rest}"));
|
||||
let normalized = normalize_lexically(&joined);
|
||||
let host = normalize_lexically(Path::new(host_prefix));
|
||||
if !normalized.starts_with(&host) {
|
||||
return PathBuf::from(reported);
|
||||
}
|
||||
normalized
|
||||
}
|
||||
Some(rest) => PathBuf::from(format!("{host_prefix}{rest}")),
|
||||
None => PathBuf::from(reported),
|
||||
}
|
||||
}
|
||||
|
|
@ -1579,13 +1423,17 @@ fn process_pending_grabs(
|
|||
transcode_cfg: Option<&breadarr_shared::config::TranscodeConfig>,
|
||||
) -> Result<(ImportStats, Vec<(String, PathBuf)>)> {
|
||||
let mut stats = ImportStats::default();
|
||||
// Torrents whose data has been fully dealt with this cycle — imported,
|
||||
// skipped as already-better, or given up on (stall / missing past grace
|
||||
// / MAX_IMPORT_ERRORS). The caller (`run_import_cycle`) removes each
|
||||
// from qBittorrent afterward and runs leftover-dir cleanup, which now
|
||||
// refuses to wipe leftover videos or the downloads root. `fail_grab`
|
||||
// itself only writes SQLite; hashes collected here are how the torrent
|
||||
// actually leaves qBit.
|
||||
// Torrents whose data has been fully dealt with this cycle — moved into
|
||||
// the library, or deleted outright because a better file already existed
|
||||
// (see `ImportOutcome::SkippedAlreadyHaveBetter`, whose only producer,
|
||||
// `import_one`, deletes the losing download itself). Either way nothing
|
||||
// *breadarr still needs* remains at the torrent's original location, so
|
||||
// the caller (`run_import_cycle`, the async I/O boundary this function is
|
||||
// deliberately kept free of) removes each from qBittorrent afterward and
|
||||
// clears out whatever's left of `content_path` — a multi-file release
|
||||
// only ever has its video moved out by `move_or_copy_file`, so without
|
||||
// this the surrounding folder (sample clips, .nfo/.srt/.jpg sidecars)
|
||||
// sits there forever with no torrent left to account for it.
|
||||
let mut imported_hashes: Vec<(String, PathBuf)> = Vec::new();
|
||||
|
||||
for grab in pending {
|
||||
|
|
@ -1593,10 +1441,6 @@ fn process_pending_grabs(
|
|||
if grab_missing_past_grace(conn, grab.release_id())? {
|
||||
fail_grab(conn, grab, "torrent hash absent from qBittorrent")?;
|
||||
stats.failed += 1;
|
||||
// Torrent is already gone from qBit; still collect the hash
|
||||
// so delete is attempted (best-effort) and any known path
|
||||
// would be cleaned. No `content_path` is available here.
|
||||
imported_hashes.push((grab.torrent_hash().to_string(), PathBuf::new()));
|
||||
}
|
||||
continue;
|
||||
};
|
||||
|
|
@ -1610,12 +1454,6 @@ fn process_pending_grabs(
|
|||
"no progress for longer than the stall threshold",
|
||||
)?;
|
||||
stats.failed += 1;
|
||||
let content_path = remap_path(
|
||||
&torrent.content_path,
|
||||
container_downloads_path,
|
||||
host_downloads_path,
|
||||
);
|
||||
imported_hashes.push((grab.torrent_hash().to_string(), content_path));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
|
@ -1659,11 +1497,7 @@ fn process_pending_grabs(
|
|||
Ok(outcome) => {
|
||||
stats.imported += outcome.episodes_imported;
|
||||
stats.quality_flagged += outcome.quality_flagged;
|
||||
// Imported files *or* a no-op upgrade (`upgraded` with
|
||||
// 0 imported): nothing breadarr still needs lives in
|
||||
// qBit. Unmatched leftover videos are left on disk by
|
||||
// `cleanup_leftover_download_dir`.
|
||||
if outcome.episodes_imported > 0 || outcome.episodes_already_had_better > 0 {
|
||||
if outcome.episodes_imported > 0 {
|
||||
imported_hashes.push((grab.torrent_hash().to_string(), content_path.clone()));
|
||||
}
|
||||
}
|
||||
|
|
@ -1676,7 +1510,6 @@ fn process_pending_grabs(
|
|||
&format!("season pack import failed {error_count} times in a row: {e}"),
|
||||
)?;
|
||||
stats.failed += 1;
|
||||
imported_hashes.push((grab.torrent_hash().to_string(), content_path.clone()));
|
||||
} else {
|
||||
tracing::warn!(
|
||||
error = %e,
|
||||
|
|
@ -1720,7 +1553,6 @@ fn process_pending_grabs(
|
|||
&format!("import failed {error_count} times in a row: {e}"),
|
||||
)?;
|
||||
stats.failed += 1;
|
||||
imported_hashes.push((grab.torrent_hash().to_string(), content_path.clone()));
|
||||
} else {
|
||||
tracing::warn!(
|
||||
error = %e,
|
||||
|
|
@ -2236,12 +2068,6 @@ fn import_season_pack(
|
|||
|
||||
std::fs::create_dir_all(root_folder)?;
|
||||
|
||||
let tvdb_id: Option<i64> = conn.query_row(
|
||||
"SELECT tvdb_id FROM media_item WHERE id = ?1",
|
||||
params![media_item_id],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
|
||||
let mut outcome = SeasonPackImportOutcome::default();
|
||||
for source_path in &video_files {
|
||||
let filename_only = source_path
|
||||
|
|
@ -2249,24 +2075,18 @@ fn import_season_pack(
|
|||
.and_then(|f| f.to_str())
|
||||
.unwrap_or_default();
|
||||
let parsed = crate::parser::parse(filename_only);
|
||||
// Anime packs name files `[SubsPlease] Show - 15.mkv` (absolute
|
||||
// only). Treating that as S01E15 skipped the AniDB map that
|
||||
// `library_scan` already uses via `resolve_episode`.
|
||||
let resolved = crate::scheduler::resolve_episode(conn, tvdb_id, &parsed)?;
|
||||
let (file_season, episode_number) = match resolved {
|
||||
Some(pair) => pair,
|
||||
None => match (parsed.season, parsed.episode) {
|
||||
(Some(season), Some(episode)) => (season, episode),
|
||||
_ => {
|
||||
outcome.episodes_unmatched += 1;
|
||||
tracing::warn!(
|
||||
file = filename_only,
|
||||
"season pack: could not determine an episode number for this file, skipping"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
},
|
||||
let Some(episode_number) = parsed.episode.or(parsed.absolute_episode) else {
|
||||
outcome.episodes_unmatched += 1;
|
||||
tracing::warn!(
|
||||
file = filename_only,
|
||||
"season pack: could not determine an episode number for this file, skipping"
|
||||
);
|
||||
continue;
|
||||
};
|
||||
// Prefer the individual file's own season marker when it has one
|
||||
// (a pack can occasionally mix seasons); fall back to the pack's
|
||||
// own season otherwise.
|
||||
let file_season = parsed.season.unwrap_or(season_number);
|
||||
|
||||
let episode_id = match crate::scheduler::find_episode_id(
|
||||
conn,
|
||||
|
|
@ -3338,11 +3158,6 @@ mod tests {
|
|||
#[test]
|
||||
fn sanitizes_path_hostile_characters() {
|
||||
assert_eq!(sanitize("Kill: Ao / Blue?"), "Kill_ Ao _ Blue_");
|
||||
assert_eq!(sanitize(".."), "_");
|
||||
assert_eq!(sanitize("."), "_");
|
||||
// Slashes become `_` first, so this is not a lone `..` component.
|
||||
assert_eq!(sanitize("foo/../bar"), "foo_.._bar");
|
||||
assert_eq!(sanitize("title\nwith\x00ctrl"), "title_with_ctrl");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -3492,70 +3307,6 @@ mod tests {
|
|||
std::fs::remove_dir_all(&downloads).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_leftover_download_dir_leaves_unmatched_videos() {
|
||||
let downloads = std::env::temp_dir().join(format!(
|
||||
"breadarr-cleanup-leftover-video-{}",
|
||||
std::process::id()
|
||||
));
|
||||
let release_dir = downloads.join("Some Show S01");
|
||||
std::fs::create_dir_all(&release_dir).unwrap();
|
||||
let unmatched = release_dir.join("Show - 15.mkv");
|
||||
std::fs::write(&unmatched, b"unmatched video").unwrap();
|
||||
std::fs::write(release_dir.join("release.nfo"), b"nfo").unwrap();
|
||||
std::fs::write(release_dir.join("poster.jpg"), b"jpeg").unwrap();
|
||||
|
||||
cleanup_leftover_download_dir(&release_dir, &downloads.to_string_lossy()).unwrap();
|
||||
|
||||
assert!(
|
||||
unmatched.exists(),
|
||||
"an unmatched video must survive leftover-dir cleanup"
|
||||
);
|
||||
assert!(
|
||||
!release_dir.join("release.nfo").exists(),
|
||||
"sidecars next to leftover videos should still be dropped"
|
||||
);
|
||||
assert!(!release_dir.join("poster.jpg").exists());
|
||||
assert!(release_dir.exists());
|
||||
|
||||
std::fs::remove_dir_all(&downloads).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_leftover_download_dir_empty_host_still_removes_a_per_torrent_folder() {
|
||||
let downloads = std::env::temp_dir().join(format!(
|
||||
"breadarr-cleanup-empty-host-{}",
|
||||
std::process::id()
|
||||
));
|
||||
let release_dir = downloads.join("Some Movie 2016 1080p");
|
||||
std::fs::create_dir_all(&release_dir).unwrap();
|
||||
std::fs::write(release_dir.join("poster.jpg"), b"jpeg").unwrap();
|
||||
|
||||
cleanup_leftover_download_dir(&release_dir, "").unwrap();
|
||||
|
||||
assert!(!release_dir.exists());
|
||||
assert!(downloads.exists());
|
||||
|
||||
std::fs::remove_dir_all(&downloads).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_leftover_download_dir_empty_host_refuses_common_roots() {
|
||||
cleanup_leftover_download_dir(Path::new("/"), "").unwrap();
|
||||
assert!(Path::new("/").exists());
|
||||
|
||||
cleanup_leftover_download_dir(Path::new("/mnt"), "").unwrap();
|
||||
cleanup_leftover_download_dir(Path::new("/media"), "").unwrap();
|
||||
|
||||
if let Some(home) = std::env::var_os("HOME") {
|
||||
let home_path = PathBuf::from(&home);
|
||||
if home_path.is_dir() {
|
||||
cleanup_leftover_download_dir(&home_path, "").unwrap();
|
||||
assert!(home_path.exists(), "must never wipe $HOME");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locates_a_single_file_torrent() {
|
||||
let dir = std::env::temp_dir().join(format!("breadarr-test-{}", std::process::id()));
|
||||
|
|
@ -3569,42 +3320,6 @@ mod tests {
|
|||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn walk_files_does_not_follow_symlinks() {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"breadarr-walk-symlink-{}",
|
||||
std::process::id()
|
||||
));
|
||||
let outside = std::env::temp_dir().join(format!(
|
||||
"breadarr-walk-outside-{}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::fs::write(dir.join("real.mkv"), b"inside").unwrap();
|
||||
std::fs::write(outside.join("secret.mkv"), b"escaped").unwrap();
|
||||
std::os::unix::fs::symlink(&outside, dir.join("escape")).unwrap();
|
||||
std::os::unix::fs::symlink(outside.join("secret.mkv"), dir.join("link.mkv")).unwrap();
|
||||
|
||||
let walked = walk_files(&dir).unwrap();
|
||||
let names: Vec<String> = walked
|
||||
.iter()
|
||||
.filter_map(|p| p.file_name().and_then(|n| n.to_str()).map(str::to_string))
|
||||
.collect();
|
||||
assert!(names.contains(&"real.mkv".to_string()));
|
||||
assert!(
|
||||
!names.contains(&"secret.mkv".to_string()),
|
||||
"a directory symlink must not pull files from outside the scan root"
|
||||
);
|
||||
assert!(
|
||||
!names.contains(&"link.mkv".to_string()),
|
||||
"a file symlink to a video must be skipped"
|
||||
);
|
||||
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
std::fs::remove_dir_all(&outside).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remap_path_translates_container_prefix_to_host_prefix() {
|
||||
assert_eq!(
|
||||
|
|
@ -3625,31 +3340,6 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remap_path_rejects_parent_dir_escape() {
|
||||
let remapped = remap_path(
|
||||
"/downloads/../../etc",
|
||||
"/downloads",
|
||||
"/home/breadway/downloads",
|
||||
);
|
||||
assert_eq!(remapped, PathBuf::from("/downloads/../../etc"));
|
||||
assert!(
|
||||
!normalize_lexically(&remapped).starts_with("/home/breadway/downloads")
|
||||
|| remapped.as_os_str() == "/downloads/../../etc",
|
||||
"a `..` remainder must not be rewritten under the host prefix"
|
||||
);
|
||||
|
||||
let remapped = remap_path(
|
||||
"/downloads/show/../../../etc/passwd",
|
||||
"/downloads",
|
||||
"/home/breadway/downloads",
|
||||
);
|
||||
assert_eq!(
|
||||
remapped,
|
||||
PathBuf::from("/downloads/show/../../../etc/passwd")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_pending_grabs_routes_each_grab_by_torrent_state() {
|
||||
use crate::qbit::TorrentInfo;
|
||||
|
|
@ -3755,22 +3445,12 @@ mod tests {
|
|||
// absent — simulating torrents qBit no longer knows about.
|
||||
];
|
||||
|
||||
let (stats, hashes) = process_pending_grabs(&conn, &pending, &torrents, "", "", None).unwrap();
|
||||
let (stats, _) = process_pending_grabs(&conn, &pending, &torrents, "", "", None).unwrap();
|
||||
|
||||
assert_eq!(stats.imported, 1);
|
||||
assert_eq!(stats.skipped_incomplete, 1);
|
||||
assert_eq!(stats.failed, 1);
|
||||
assert_eq!(stats.errors, 0);
|
||||
assert!(
|
||||
hashes.iter().any(|(h, _)| h == "hash-complete"),
|
||||
"a successful import must still be queued for qBit delete"
|
||||
);
|
||||
assert!(
|
||||
hashes.iter().any(|(h, _)| h == "hash-missing-stale"),
|
||||
"a grab failed for a missing torrent must be queued for qBit delete"
|
||||
);
|
||||
assert!(!hashes.iter().any(|(h, _)| h == "hash-downloading"));
|
||||
assert!(!hashes.iter().any(|(h, _)| h == "hash-missing-fresh"));
|
||||
|
||||
let statuses: Vec<(i64, String)> = {
|
||||
let mut stmt = conn
|
||||
|
|
@ -3895,13 +3575,9 @@ mod tests {
|
|||
|
||||
// The Nth failure crosses the threshold and gives up.
|
||||
let pending = fetch_pending_grabs(&conn).unwrap();
|
||||
let (stats, hashes) = process_pending_grabs(&conn, &pending, &torrents, "", "", None).unwrap();
|
||||
let (stats, _) = process_pending_grabs(&conn, &pending, &torrents, "", "", None).unwrap();
|
||||
assert_eq!(stats.failed, 1);
|
||||
assert_eq!(stats.errors, 0);
|
||||
assert!(
|
||||
hashes.iter().any(|(h, _)| h == "hash-broken"),
|
||||
"a grab failed after MAX_IMPORT_ERRORS must be queued for qBit delete"
|
||||
);
|
||||
let status: String = conn
|
||||
.query_row("SELECT status FROM release WHERE id = 1", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
|
|
@ -3914,51 +3590,6 @@ mod tests {
|
|||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stalled_grab_is_queued_for_qbit_delete() {
|
||||
use crate::qbit::TorrentInfo;
|
||||
|
||||
let (conn, release_id) = seeded_release_conn(STALL_THRESHOLD_HOURS + 1.0);
|
||||
// Same progress already recorded — otherwise `update_grab_progress`
|
||||
// would stamp `last_progress_at = now` and reset the stall clock.
|
||||
conn.execute(
|
||||
"UPDATE release SET last_seen_progress = 0.4, last_progress_at = datetime('now', ?1) WHERE id = ?2",
|
||||
params![format!("-{} hours", STALL_THRESHOLD_HOURS + 1.0), release_id],
|
||||
)
|
||||
.unwrap();
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"breadarr-stall-delete-{}",
|
||||
std::process::id()
|
||||
));
|
||||
let content = dir.join("partial");
|
||||
std::fs::create_dir_all(&content).unwrap();
|
||||
std::fs::write(content.join("movie.mp4"), b"partial").unwrap();
|
||||
|
||||
let pending = fetch_pending_grabs(&conn).unwrap();
|
||||
let torrents = vec![TorrentInfo {
|
||||
hash: "deadbeef".to_string(),
|
||||
name: "stalled".to_string(),
|
||||
state: "downloading".to_string(),
|
||||
progress: 0.4,
|
||||
save_path: dir.to_string_lossy().to_string(),
|
||||
content_path: content.to_string_lossy().to_string(),
|
||||
}];
|
||||
|
||||
let (stats, hashes) = process_pending_grabs(&conn, &pending, &torrents, "", "", None).unwrap();
|
||||
assert_eq!(stats.failed, 1);
|
||||
assert!(
|
||||
hashes.iter().any(|(h, p)| h == "deadbeef" && p == &content),
|
||||
"a stalled grab must be queued for qBit delete with its content_path"
|
||||
);
|
||||
cleanup_leftover_download_dir(&content, "").unwrap();
|
||||
assert!(
|
||||
content.join("movie.mp4").exists(),
|
||||
"cleanup of a failed grab must not wipe leftover videos"
|
||||
);
|
||||
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_a_movie_release_with_no_episode_id() {
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
|
|
@ -5062,196 +4693,4 @@ mod tests {
|
|||
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_season_pack_uses_anime_absolute_mapping() {
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
crate::db::init(&conn).unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO media_item (id, kind, title, year, tvdb_id, monitored, quality_profile_id, root_folder)
|
||||
VALUES (1, 'series', 'Show', 2020, 366263, 1, 1, '/tmp')",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
// Bookworm-style offsets: cours starting at absolute 1/15/27/37.
|
||||
for (anidb_id, offset) in [(1, 0), (2, 14), (3, 26), (4, 36)] {
|
||||
conn.execute(
|
||||
"INSERT INTO anime_mapping (anidb_id, tvdb_id, season_offset, episode_offset)
|
||||
VALUES (?1, 366263, 1, ?2)",
|
||||
params![anidb_id, offset],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
// Mapped landing spot for absolute 15 (offset 14 → S01E01).
|
||||
conn.execute(
|
||||
"INSERT INTO episode (id, media_item_id, season_number, episode_number, monitored, has_file)
|
||||
VALUES (1, 1, 1, 1, 1, 0)",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
// Naive S01E15 — must not be chosen over the mapped episode.
|
||||
conn.execute(
|
||||
"INSERT INTO episode (id, media_item_id, season_number, episode_number, monitored, has_file)
|
||||
VALUES (15, 1, 1, 15, 1, 0)",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO source (id, name, kind, base_url) VALUES (1, 'tpb', 'scrape', 'http://x')",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO release (id, media_item_id, episode_id, season_number, raw_title, source_id, guid, score, status, torrent_hash, grabbed_at)
|
||||
VALUES (1, 1, NULL, 1, '[SubsPlease] Show (01-12)', 1, 'guid-1', 15.0, 'grabbed', 'aaaa', datetime('now'))",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"breadarr-season-pack-anime-{}",
|
||||
std::process::id()
|
||||
));
|
||||
let pack_dir = dir.join("pack");
|
||||
std::fs::create_dir_all(&pack_dir).unwrap();
|
||||
std::fs::write(pack_dir.join("[SubsPlease] Show - 15.mkv"), b"abs 15").unwrap();
|
||||
let dest_root = dir.join("library");
|
||||
|
||||
let outcome = import_season_pack(
|
||||
&conn,
|
||||
1,
|
||||
1,
|
||||
"Show",
|
||||
1,
|
||||
&dest_root.to_string_lossy(),
|
||||
&pack_dir,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(outcome.episodes_imported, 1);
|
||||
assert_eq!(outcome.episodes_unmatched, 0);
|
||||
|
||||
let (has_mapped, has_naive): (i64, i64) = conn
|
||||
.query_row(
|
||||
"SELECT
|
||||
(SELECT has_file FROM episode WHERE id = 1),
|
||||
(SELECT has_file FROM episode WHERE id = 15)",
|
||||
[],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(has_mapped, 1, "absolute 15 must land on mapped S01E01");
|
||||
assert_eq!(has_naive, 0, "must not treat absolute 15 as S01E15");
|
||||
assert!(dest_root.join("Season 01").join("Show - S01E01.mkv").exists());
|
||||
assert!(!dest_root.join("Season 01").join("Show - S01E15.mkv").exists());
|
||||
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_season_pack_cleanup_preserves_unmatched_videos() {
|
||||
let conn = seeded_season_pack_conn(1);
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"breadarr-season-pack-leftover-{}",
|
||||
std::process::id()
|
||||
));
|
||||
let pack_dir = dir.join("pack");
|
||||
std::fs::create_dir_all(&pack_dir).unwrap();
|
||||
std::fs::write(pack_dir.join("Show.S01E01.mkv"), b"matched").unwrap();
|
||||
let unmatched = pack_dir.join("Show - 15.mkv");
|
||||
std::fs::write(&unmatched, b"did not parse as SxxExx").unwrap();
|
||||
std::fs::write(pack_dir.join("release.nfo"), b"nfo").unwrap();
|
||||
let dest_root = dir.join("library");
|
||||
|
||||
let outcome = import_season_pack(
|
||||
&conn,
|
||||
1,
|
||||
1,
|
||||
"Some Show",
|
||||
1,
|
||||
&dest_root.to_string_lossy(),
|
||||
&pack_dir,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(outcome.episodes_imported, 1);
|
||||
assert_eq!(outcome.episodes_unmatched, 1);
|
||||
|
||||
cleanup_leftover_download_dir(&pack_dir, &dir.to_string_lossy()).unwrap();
|
||||
|
||||
assert!(
|
||||
unmatched.exists(),
|
||||
"unmatched pack video must survive leftover-dir cleanup"
|
||||
);
|
||||
assert!(
|
||||
dest_root
|
||||
.join("Season 01")
|
||||
.join("Some Show - S01E01.mkv")
|
||||
.exists()
|
||||
);
|
||||
assert!(!pack_dir.join("release.nfo").exists());
|
||||
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_pending_grabs_queues_a_noop_season_pack_upgrade_for_qbit_delete() {
|
||||
use crate::qbit::TorrentInfo;
|
||||
|
||||
let conn = seeded_season_pack_conn(1);
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"breadarr-season-pack-noop-upgrade-{}",
|
||||
std::process::id()
|
||||
));
|
||||
let pack_dir = dir.join("pack");
|
||||
std::fs::create_dir_all(&pack_dir).unwrap();
|
||||
std::fs::write(pack_dir.join("Show.S01E01.mkv"), b"new e01").unwrap();
|
||||
let dest_root = dir.join("library");
|
||||
let season = dest_root.join("Season 01");
|
||||
std::fs::create_dir_all(&season).unwrap();
|
||||
let existing = season.join("Some Show - S01E01.mkv");
|
||||
std::fs::write(&existing, b"already-better").unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO release (id, media_item_id, episode_id, raw_title, source_id, guid, score, status, torrent_hash, grabbed_at)
|
||||
VALUES (2, 1, 1, 'Some Show S01E01 REMUX', 1, 'guid-2', 50.0, 'imported', 'bbbb', datetime('now'))",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO episode_file (episode_id, media_item_id, path, size_bytes, subtitle_status)
|
||||
VALUES (1, NULL, ?1, 14, 'none')",
|
||||
params![existing.to_string_lossy()],
|
||||
)
|
||||
.unwrap();
|
||||
conn.execute(
|
||||
"UPDATE media_item SET root_folder = ?1 WHERE id = 1",
|
||||
params![dest_root.to_string_lossy()],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let pending = fetch_pending_grabs(&conn).unwrap();
|
||||
let torrents = vec![TorrentInfo {
|
||||
hash: "aaaa".to_string(),
|
||||
name: "pack".to_string(),
|
||||
state: "uploading".to_string(),
|
||||
progress: 1.0,
|
||||
save_path: dir.to_string_lossy().to_string(),
|
||||
content_path: pack_dir.to_string_lossy().to_string(),
|
||||
}];
|
||||
|
||||
let (stats, hashes) = process_pending_grabs(&conn, &pending, &torrents, "", "", None).unwrap();
|
||||
assert_eq!(stats.imported, 0);
|
||||
assert_eq!(stats.failed, 0);
|
||||
let status: String = conn
|
||||
.query_row("SELECT status FROM release WHERE id = 1", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(status, "upgraded");
|
||||
assert!(
|
||||
hashes.iter().any(|(h, _)| h == "aaaa"),
|
||||
"a no-op season-pack upgrade must still be removed from qBit"
|
||||
);
|
||||
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -435,15 +435,7 @@ pub async fn scan_tv_root(
|
|||
report.unmatched.push(folder_name);
|
||||
continue;
|
||||
};
|
||||
let Some(tvdb_id) = metadata::parse_external_id(&best.external_id) else {
|
||||
tracing::warn!(
|
||||
folder = %folder_name,
|
||||
external_id = %best.external_id,
|
||||
"tvdb id was not a positive integer, skipping"
|
||||
);
|
||||
report.unmatched.push(folder_name);
|
||||
continue;
|
||||
};
|
||||
let tvdb_id: i64 = best.external_id.parse().unwrap_or_default();
|
||||
let canonical_year = best.year.or(year);
|
||||
// Normalize the folder itself down to "Title (Year)" — release
|
||||
// tags/resolution/group cruft in the original folder name isn't
|
||||
|
|
@ -737,15 +729,7 @@ pub async fn scan_movie_root(
|
|||
report.unmatched.push(folder_name);
|
||||
continue;
|
||||
};
|
||||
let Some(tmdb_id) = metadata::parse_external_id(&best.external_id) else {
|
||||
tracing::warn!(
|
||||
folder = %folder_name,
|
||||
external_id = %best.external_id,
|
||||
"tmdb id was not a positive integer, skipping"
|
||||
);
|
||||
report.unmatched.push(folder_name);
|
||||
continue;
|
||||
};
|
||||
let tmdb_id: i64 = best.external_id.parse().unwrap_or_default();
|
||||
let canonical_year = best.year.or(year);
|
||||
|
||||
// Normalizes the folder itself down to "Title (Year)" too — release
|
||||
|
|
@ -899,12 +883,4 @@ mod tests {
|
|||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_external_id_never_yields_zero() {
|
||||
assert_eq!(metadata::parse_external_id("0"), None);
|
||||
assert_eq!(metadata::parse_external_id("000"), None);
|
||||
assert_eq!(metadata::parse_external_id("not-a-number"), None);
|
||||
assert_eq!(metadata::parse_external_id("550"), Some(550));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -150,10 +150,7 @@ async fn run_daemon(config: Config) -> Result<()> {
|
|||
info!(path = %config.db_path().display(), "database ready");
|
||||
match transcode::reset_orphaned_running_jobs(&conn) {
|
||||
Ok(0) => {}
|
||||
Ok(n) => info!(
|
||||
n,
|
||||
"reset orphaned 'running' transcode jobs left over from a previous crash"
|
||||
),
|
||||
Ok(n) => info!(n, "reset orphaned 'running' transcode jobs left over from a previous crash"),
|
||||
Err(e) => tracing::warn!(error = %e, "failed to reset orphaned transcode jobs"),
|
||||
}
|
||||
|
||||
|
|
@ -171,14 +168,6 @@ async fn run_daemon(config: Config) -> Result<()> {
|
|||
|
||||
let listener = tokio::net::TcpListener::bind(&config.daemon.listen_addr).await?;
|
||||
info!(addr = %config.daemon.listen_addr, "listening");
|
||||
if config.daemon.api_token.is_empty() {
|
||||
tracing::warn!(
|
||||
"daemon.api_token is empty; any local process can add/delete/grab via {}",
|
||||
config.daemon.listen_addr
|
||||
);
|
||||
} else if !config.listen_is_loopback() {
|
||||
info!("API token auth is required (listen_addr is non-loopback)");
|
||||
}
|
||||
|
||||
let tvdb = if config.tvdb.api_key.is_empty() {
|
||||
None
|
||||
|
|
@ -206,10 +195,6 @@ async fn run_daemon(config: Config) -> Result<()> {
|
|||
)))
|
||||
};
|
||||
let (background_tx, background_rx) = tokio::sync::mpsc::channel(8);
|
||||
// Lifted out of `background_loop` so shutdown can wait for an in-flight
|
||||
// ffmpeg encode instead of dropping the process the instant SIGTERM
|
||||
// arrives (systemd's TimeoutStopSec is longer than this wait).
|
||||
let transcode_busy = std::sync::Arc::new(tokio::sync::Mutex::new(()));
|
||||
|
||||
let background_conn = std::sync::Arc::new(tokio::sync::Mutex::new(conn));
|
||||
let state = api::AppState {
|
||||
|
|
@ -239,7 +224,6 @@ async fn run_daemon(config: Config) -> Result<()> {
|
|||
config.clone(),
|
||||
state.cycle_status.clone(),
|
||||
background_rx,
|
||||
transcode_busy.clone(),
|
||||
)
|
||||
});
|
||||
let mut state = state;
|
||||
|
|
@ -284,15 +268,6 @@ async fn run_daemon(config: Config) -> Result<()> {
|
|||
}
|
||||
}
|
||||
|
||||
// Wait for an in-flight transcode (it holds this mutex for the whole
|
||||
// cycle) so ffmpeg can finish, or at least so systemd's longer
|
||||
// TimeoutStopSec applies instead of an instant drop.
|
||||
info!("waiting up to 120s for in-flight transcode to finish");
|
||||
match tokio::time::timeout(std::time::Duration::from_secs(120), transcode_busy.lock()).await {
|
||||
Ok(_) => info!("no in-flight transcode (or it finished)"),
|
||||
Err(_) => tracing::warn!("timed out waiting 120s for in-flight transcode"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -315,7 +290,6 @@ async fn background_loop(
|
|||
config: Config,
|
||||
cycle_status: std::sync::Arc<std::sync::Mutex<api::CycleStatus>>,
|
||||
mut background_rx: tokio::sync::mpsc::Receiver<api::BackgroundRequest>,
|
||||
transcode_busy: std::sync::Arc<tokio::sync::Mutex<()>>,
|
||||
) {
|
||||
let notifier = notify::Notifier::new(&config.notifications.webhook_url);
|
||||
{
|
||||
|
|
@ -355,26 +329,6 @@ async fn background_loop(
|
|||
) {
|
||||
error!(error = %e, "failed to register tpb source row");
|
||||
}
|
||||
if let Err(e) = conn.execute(
|
||||
"INSERT OR IGNORE INTO source (id, name, kind, base_url, poll_interval_secs, enabled)
|
||||
VALUES (4, 'torrents-csv', 'scrape', ?1, ?2, 1)",
|
||||
rusqlite::params![
|
||||
config.sources.torrents_csv_url,
|
||||
config.sources.search_poll_interval_secs
|
||||
],
|
||||
) {
|
||||
error!(error = %e, "failed to register torrents-csv source row");
|
||||
}
|
||||
if let Err(e) = conn.execute(
|
||||
"INSERT OR IGNORE INTO source (id, name, kind, base_url, poll_interval_secs, enabled)
|
||||
VALUES (5, 'yts', 'scrape', ?1, ?2, 1)",
|
||||
rusqlite::params![
|
||||
config.sources.yts_api_url,
|
||||
config.sources.search_poll_interval_secs
|
||||
],
|
||||
) {
|
||||
error!(error = %e, "failed to register yts source row");
|
||||
}
|
||||
}
|
||||
|
||||
// A transient failure here (network blip during the one-time model
|
||||
|
|
@ -397,21 +351,6 @@ async fn background_loop(
|
|||
let scrape_source =
|
||||
sources::scrape::ScrapeSource::new(config.sources.torrent_1337x_mirrors.clone());
|
||||
let tpb_source = sources::tpb::TpbSource::new(config.sources.tpb_api_url.clone());
|
||||
let torrents_csv_source =
|
||||
sources::torrents_csv::TorrentsCsvSource::new(config.sources.torrents_csv_url.clone());
|
||||
let yts_source = sources::yts::YtsSource::new(config.sources.yts_api_url.clone());
|
||||
let search_sources = scheduler::SearchSources {
|
||||
tpb: &tpb_source,
|
||||
tpb_id: 3,
|
||||
torrents_csv: &torrents_csv_source,
|
||||
torrents_csv_id: 4,
|
||||
yts: &yts_source,
|
||||
yts_id: 5,
|
||||
scrape: &scrape_source,
|
||||
scrape_id: 2,
|
||||
nyaa_search: &nyaa_source,
|
||||
nyaa_id: 1,
|
||||
};
|
||||
|
||||
let mut grab_ticker = tokio::time::interval(std::time::Duration::from_secs(
|
||||
config.sources.grab_poll_interval_secs,
|
||||
|
|
@ -433,7 +372,8 @@ async fn background_loop(
|
|||
// fires (a real possibility: files easily take longer to encode than
|
||||
// `poll_interval_secs`). `claim_pending_jobs`'s own concurrency cap
|
||||
// already makes overlap *safe*; this just keeps it from happening
|
||||
// pointlessly. Created in `run_daemon` so shutdown can wait on it.
|
||||
// pointlessly.
|
||||
let transcode_busy = std::sync::Arc::new(tokio::sync::Mutex::new(()));
|
||||
let mut transcode_ticker = tokio::time::interval(std::time::Duration::from_secs(
|
||||
config.transcode.poll_interval_secs,
|
||||
));
|
||||
|
|
@ -536,7 +476,9 @@ async fn background_loop(
|
|||
let conn = conn.lock().await;
|
||||
scheduler::run_search_cycle(
|
||||
&conn,
|
||||
&search_sources,
|
||||
&tpb_source, 3,
|
||||
&scrape_source, 2,
|
||||
&nyaa_source, 1,
|
||||
&mut title_matcher,
|
||||
&qbit, &config.qbit.category,
|
||||
config.sources.search_budget_per_cycle,
|
||||
|
|
@ -595,7 +537,9 @@ async fn background_loop(
|
|||
let conn = conn.lock().await;
|
||||
scheduler::run_upgrade_cycle(
|
||||
&conn,
|
||||
&search_sources,
|
||||
&tpb_source, 3,
|
||||
&scrape_source, 2,
|
||||
&nyaa_source, 1,
|
||||
&mut title_matcher,
|
||||
&qbit, &config.qbit.category,
|
||||
config.sources.upgrade_budget_per_cycle,
|
||||
|
|
@ -710,7 +654,9 @@ async fn background_loop(
|
|||
Ok(targets) => scheduler::execute_search_targets(
|
||||
&conn,
|
||||
&targets,
|
||||
&search_sources,
|
||||
&tpb_source, 3,
|
||||
&scrape_source, 2,
|
||||
&nyaa_source, 1,
|
||||
&mut title_matcher,
|
||||
&qbit, &config.qbit.category,
|
||||
).await,
|
||||
|
|
@ -734,7 +680,9 @@ async fn background_loop(
|
|||
&conn,
|
||||
media_item_id,
|
||||
episode_id,
|
||||
&search_sources,
|
||||
&tpb_source, 3,
|
||||
&scrape_source, 2,
|
||||
&nyaa_source, 1,
|
||||
).await
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
|
|
@ -1160,22 +1108,6 @@ async fn debug_search_show(config: &Config, title: &str) -> Result<()> {
|
|||
config.sources.search_poll_interval_secs
|
||||
],
|
||||
)?;
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO source (id, name, kind, base_url, poll_interval_secs, enabled)
|
||||
VALUES (4, 'torrents-csv', 'scrape', ?1, ?2, 1)",
|
||||
rusqlite::params![
|
||||
config.sources.torrents_csv_url,
|
||||
config.sources.search_poll_interval_secs
|
||||
],
|
||||
)?;
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO source (id, name, kind, base_url, poll_interval_secs, enabled)
|
||||
VALUES (5, 'yts', 'scrape', ?1, ?2, 1)",
|
||||
rusqlite::params![
|
||||
config.sources.yts_api_url,
|
||||
config.sources.search_poll_interval_secs
|
||||
],
|
||||
)?;
|
||||
|
||||
let qbit = QbitClient::new(config.qbit.base_url.clone())?;
|
||||
if !config.qbit.username.is_empty() {
|
||||
|
|
@ -1187,21 +1119,6 @@ async fn debug_search_show(config: &Config, title: &str) -> Result<()> {
|
|||
let scrape_source =
|
||||
sources::scrape::ScrapeSource::new(config.sources.torrent_1337x_mirrors.clone());
|
||||
let nyaa_source = sources::rss::RssSource::new(config.sources.nyaa_rss_url.clone());
|
||||
let torrents_csv_source =
|
||||
sources::torrents_csv::TorrentsCsvSource::new(config.sources.torrents_csv_url.clone());
|
||||
let yts_source = sources::yts::YtsSource::new(config.sources.yts_api_url.clone());
|
||||
let search_sources = scheduler::SearchSources {
|
||||
tpb: &tpb_source,
|
||||
tpb_id: 3,
|
||||
torrents_csv: &torrents_csv_source,
|
||||
torrents_csv_id: 4,
|
||||
yts: &yts_source,
|
||||
yts_id: 5,
|
||||
scrape: &scrape_source,
|
||||
scrape_id: 2,
|
||||
nyaa_search: &nyaa_source,
|
||||
nyaa_id: 1,
|
||||
};
|
||||
|
||||
let targets = scheduler::enumerate_search_targets_for_media_item(&conn, media_item_id)?;
|
||||
println!("{} missing episode(s)/movie for {title:?}", targets.len());
|
||||
|
|
@ -1209,7 +1126,12 @@ async fn debug_search_show(config: &Config, title: &str) -> Result<()> {
|
|||
let stats = scheduler::execute_search_targets(
|
||||
&conn,
|
||||
&targets,
|
||||
&search_sources,
|
||||
&tpb_source,
|
||||
3,
|
||||
&scrape_source,
|
||||
2,
|
||||
&nyaa_source,
|
||||
1,
|
||||
&mut title_matcher,
|
||||
&qbit,
|
||||
&config.qbit.category,
|
||||
|
|
|
|||
|
|
@ -4,20 +4,14 @@ use std::collections::HashMap;
|
|||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension};
|
||||
use rusqlite::{params, Connection};
|
||||
|
||||
use embed::{cosine_similarity, OrtEmbedder};
|
||||
|
||||
// Pinned to Xenova/all-MiniLM-L6-v2 @ 751bff37182d3f1213fa05d7196b954e230abad9
|
||||
// (current `main` as of this change) — not the floating `main` branch.
|
||||
const MODEL_URL: &str =
|
||||
"https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/751bff37182d3f1213fa05d7196b954e230abad9/onnx/model.onnx";
|
||||
"https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/onnx/model.onnx";
|
||||
const TOKENIZER_URL: &str =
|
||||
"https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/751bff37182d3f1213fa05d7196b954e230abad9/tokenizer.json";
|
||||
// Official LFS sha256 of onnx/model.onnx at that commit.
|
||||
const MODEL_SHA256: &str = "759c3cd2b7fe7e93933ad23c4c9181b7396442a2ed746ec7c1d46192c469c46e";
|
||||
// sha256 of tokenizer.json at the same revision (not LFS; hashed from the published file).
|
||||
const TOKENIZER_SHA256: &str = "da0e79933b9ed51798a3ae27893d3c5fa4a201126cef75586296df9b4d2c62a0";
|
||||
"https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/tokenizer.json";
|
||||
|
||||
/// Downloads the embedding model into `model_dir` if it isn't already
|
||||
/// there — keeps setup to "run the daemon," no separate fetch step, in
|
||||
|
|
@ -38,21 +32,19 @@ pub async fn ensure_model(model_dir: &Path) -> Result<(PathBuf, PathBuf)> {
|
|||
|
||||
if !model_path.exists() {
|
||||
tracing::info!("downloading title-matching model (~90MB, one-time)");
|
||||
download(MODEL_URL, model_path.clone(), MODEL_SHA256).await?;
|
||||
download(MODEL_URL, model_path.clone()).await?;
|
||||
}
|
||||
if !tokenizer_path.exists() {
|
||||
download(TOKENIZER_URL, tokenizer_path.clone(), TOKENIZER_SHA256).await?;
|
||||
download(TOKENIZER_URL, tokenizer_path.clone()).await?;
|
||||
}
|
||||
|
||||
Ok((model_path, tokenizer_path))
|
||||
}
|
||||
|
||||
async fn download(url: &'static str, dest: PathBuf, sha256: &'static str) -> Result<()> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
bread_onnx::download::ensure_file(url, &dest, Some(sha256))
|
||||
})
|
||||
.await
|
||||
.context("download task panicked")??;
|
||||
async fn download(url: &'static str, dest: PathBuf) -> Result<()> {
|
||||
tokio::task::spawn_blocking(move || bread_onnx::download::ensure_file(url, &dest, None))
|
||||
.await
|
||||
.context("download task panicked")??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -258,36 +250,6 @@ pub fn queue_for_review(
|
|||
link: Option<&str>,
|
||||
source_id: Option<i64>,
|
||||
) -> Result<i64> {
|
||||
// Same release + same library row already sitting in pending: a
|
||||
// no-op instead of another TUI row. Upgrade-search used to re-list
|
||||
// the same movie 7–11 times (verified live on hestia).
|
||||
if let Some(existing) = conn
|
||||
.query_row(
|
||||
"SELECT id FROM review_queue
|
||||
WHERE status = 'pending'
|
||||
AND candidate_media_item_id = ?1
|
||||
AND raw_release_title = ?2",
|
||||
params![candidate.media_item_id, raw_release_title],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()?
|
||||
{
|
||||
return Ok(existing);
|
||||
}
|
||||
if let (Some(link), Some(source_id)) = (link, source_id) {
|
||||
if let Some(existing) = conn
|
||||
.query_row(
|
||||
"SELECT id FROM review_queue
|
||||
WHERE status = 'pending' AND source_id = ?1 AND link = ?2",
|
||||
params![source_id, link],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()?
|
||||
{
|
||||
return Ok(existing);
|
||||
}
|
||||
}
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO review_queue (raw_release_title, candidate_media_item_id, confidence, link, source_id, status, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, 'pending', datetime('now'))",
|
||||
|
|
@ -361,81 +323,4 @@ mod tests {
|
|||
0.0
|
||||
);
|
||||
}
|
||||
|
||||
fn review_queue_conn() -> Connection {
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
crate::db::init(&conn).unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO media_item (id, kind, title, monitored, quality_profile_id, root_folder)
|
||||
VALUES (1, 'movie', 'Cars 3', 1, 2, '/tmp')",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO source (id, name, kind, base_url) VALUES (1, 'tpb', 'scrape', 'http://x')",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
conn
|
||||
}
|
||||
|
||||
fn review_candidate() -> MatchCandidate {
|
||||
MatchCandidate {
|
||||
media_item_id: 1,
|
||||
matched_text: "Cars 3".into(),
|
||||
confidence: 0.7,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queue_for_review_is_idempotent_for_the_same_pending_title() {
|
||||
let conn = review_queue_conn();
|
||||
let c = review_candidate();
|
||||
let first = queue_for_review(&conn, "Cars.3.2017.1080p", &c, Some("magnet:a"), Some(1)).unwrap();
|
||||
let second =
|
||||
queue_for_review(&conn, "Cars.3.2017.1080p", &c, Some("magnet:a"), Some(1)).unwrap();
|
||||
assert_eq!(first, second);
|
||||
let n: i64 = conn
|
||||
.query_row(
|
||||
"SELECT count(*) FROM review_queue WHERE status = 'pending'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(n, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queue_for_review_is_idempotent_for_the_same_pending_link() {
|
||||
let conn = review_queue_conn();
|
||||
let c = review_candidate();
|
||||
let first =
|
||||
queue_for_review(&conn, "Cars.3.2017.1080p", &c, Some("magnet:same"), Some(1)).unwrap();
|
||||
let second = queue_for_review(
|
||||
&conn,
|
||||
"Cars.3.2017.2160p.UHD",
|
||||
&c,
|
||||
Some("magnet:same"),
|
||||
Some(1),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(first, second);
|
||||
let n: i64 = conn
|
||||
.query_row(
|
||||
"SELECT count(*) FROM review_queue WHERE status = 'pending'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(n, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queue_for_review_still_accepts_a_different_title_and_link() {
|
||||
let conn = review_queue_conn();
|
||||
let c = review_candidate();
|
||||
let a = queue_for_review(&conn, "Cars.3.2017.1080p", &c, Some("magnet:a"), Some(1)).unwrap();
|
||||
let b = queue_for_review(&conn, "Cars.3.2017.2160p", &c, Some("magnet:b"), Some(1)).unwrap();
|
||||
assert_ne!(a, b);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ pub mod tvdb;
|
|||
use std::collections::HashSet;
|
||||
|
||||
use anyhow::Result;
|
||||
use rusqlite::{params, Connection, OptionalExtension};
|
||||
use rusqlite::{params, Connection};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct SeriesSearchResult {
|
||||
|
|
@ -65,21 +65,6 @@ pub async fn add_series(
|
|||
)
|
||||
}
|
||||
|
||||
/// TVDB/TMDB ids are positive integers. `"0"` and non-numeric strings
|
||||
/// must not be stored — `0` would collide under the unique external-id
|
||||
/// indexes the same way a parse-failure `unwrap_or_default()` used to.
|
||||
pub(crate) fn parse_external_id(raw: &str) -> Option<i64> {
|
||||
raw.parse().ok().filter(|&id| id > 0)
|
||||
}
|
||||
|
||||
fn existing_media_item_id(conn: &Connection, column: &str, value: i64) -> Result<Option<i64>> {
|
||||
debug_assert!(column == "tvdb_id" || column == "tmdb_id");
|
||||
let sql = format!("SELECT id FROM media_item WHERE {column} = ?1 ORDER BY id ASC LIMIT 1");
|
||||
conn.query_row(&sql, params![value], |row| row.get(0))
|
||||
.optional()
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn insert_series(
|
||||
conn: &Connection,
|
||||
|
|
@ -91,23 +76,21 @@ pub fn insert_series(
|
|||
quality_profile_id: i64,
|
||||
episodes: &[EpisodeInfo],
|
||||
) -> Result<i64> {
|
||||
let tvdb_id = parse_external_id(tvdb_series_id);
|
||||
if let Some(tvdb_id) = tvdb_id {
|
||||
if let Some(existing) = existing_media_item_id(conn, "tvdb_id", tvdb_id)? {
|
||||
return Ok(existing);
|
||||
}
|
||||
}
|
||||
|
||||
let tx = conn.unchecked_transaction()?;
|
||||
tx.execute(
|
||||
conn.execute(
|
||||
"INSERT INTO media_item (kind, title, year, tvdb_id, monitored, quality_profile_id, root_folder)
|
||||
VALUES ('series', ?1, ?2, ?3, 1, ?4, ?5)",
|
||||
params![title, year, tvdb_id, quality_profile_id, root_folder],
|
||||
params![
|
||||
title,
|
||||
year,
|
||||
tvdb_series_id.parse::<i64>().ok(),
|
||||
quality_profile_id,
|
||||
root_folder
|
||||
],
|
||||
)?;
|
||||
let media_item_id = tx.last_insert_rowid();
|
||||
let media_item_id = conn.last_insert_rowid();
|
||||
|
||||
for alias in aliases {
|
||||
tx.execute(
|
||||
conn.execute(
|
||||
"INSERT INTO alias (media_item_id, text, source) VALUES (?1, ?2, 'tvdb')",
|
||||
params![media_item_id, alias],
|
||||
)?;
|
||||
|
|
@ -126,12 +109,12 @@ pub fn insert_series(
|
|||
// seasons keep the previous default of monitored.
|
||||
let monitored = i64::from(ep.season_number != 0);
|
||||
if seasons_seen.insert(ep.season_number) {
|
||||
tx.execute(
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO season (media_item_id, season_number, monitored) VALUES (?1, ?2, ?3)",
|
||||
params![media_item_id, ep.season_number, monitored],
|
||||
)?;
|
||||
}
|
||||
tx.execute(
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO episode
|
||||
(media_item_id, season_number, episode_number, absolute_number, title, air_date, monitored, has_file)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, 0)",
|
||||
|
|
@ -147,7 +130,6 @@ pub fn insert_series(
|
|||
)?;
|
||||
}
|
||||
|
||||
tx.commit()?;
|
||||
Ok(media_item_id)
|
||||
}
|
||||
|
||||
|
|
@ -163,177 +145,16 @@ pub fn insert_movie(
|
|||
root_folder: &str,
|
||||
quality_profile_id: i64,
|
||||
) -> Result<i64> {
|
||||
let tmdb_id = parse_external_id(tmdb_movie_id);
|
||||
if let Some(tmdb_id) = tmdb_id {
|
||||
if let Some(existing) = existing_media_item_id(conn, "tmdb_id", tmdb_id)? {
|
||||
return Ok(existing);
|
||||
}
|
||||
}
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO media_item (kind, title, year, tmdb_id, monitored, quality_profile_id, root_folder)
|
||||
VALUES ('movie', ?1, ?2, ?3, 1, ?4, ?5)",
|
||||
params![title, year, tmdb_id, quality_profile_id, root_folder],
|
||||
params![
|
||||
title,
|
||||
year,
|
||||
tmdb_movie_id.parse::<i64>().ok(),
|
||||
quality_profile_id,
|
||||
root_folder
|
||||
],
|
||||
)?;
|
||||
Ok(conn.last_insert_rowid())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::db;
|
||||
|
||||
fn conn() -> Connection {
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
db::init(&conn).unwrap();
|
||||
conn
|
||||
}
|
||||
|
||||
fn ep(season: u32, episode: u32) -> EpisodeInfo {
|
||||
EpisodeInfo {
|
||||
season_number: season,
|
||||
episode_number: episode,
|
||||
absolute_number: None,
|
||||
title: Some(format!("E{episode}")),
|
||||
air_date: Some("2020-01-01".into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_external_id_rejects_zero_and_garbage() {
|
||||
assert_eq!(parse_external_id("550"), Some(550));
|
||||
assert_eq!(parse_external_id("0"), None);
|
||||
assert_eq!(parse_external_id("-12"), None);
|
||||
assert_eq!(parse_external_id("not-a-number"), None);
|
||||
assert_eq!(parse_external_id(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_series_writes_seasons_and_episodes_together() {
|
||||
let conn = conn();
|
||||
let id = insert_series(
|
||||
&conn,
|
||||
"12345",
|
||||
"Show",
|
||||
Some(2020),
|
||||
&["Alias".into()],
|
||||
"/tv/Show",
|
||||
1,
|
||||
&[ep(1, 1), ep(1, 2), ep(2, 1)],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let seasons: i64 = conn
|
||||
.query_row(
|
||||
"SELECT count(*) FROM season WHERE media_item_id = ?1",
|
||||
[id],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
let episodes: i64 = conn
|
||||
.query_row(
|
||||
"SELECT count(*) FROM episode WHERE media_item_id = ?1",
|
||||
[id],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
let aliases: i64 = conn
|
||||
.query_row(
|
||||
"SELECT count(*) FROM alias WHERE media_item_id = ?1",
|
||||
[id],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(seasons, 2);
|
||||
assert_eq!(episodes, 3);
|
||||
assert_eq!(aliases, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_series_rolls_back_when_an_episode_insert_fails() {
|
||||
let conn = conn();
|
||||
conn.execute(
|
||||
"CREATE TRIGGER fail_episode BEFORE INSERT ON episode
|
||||
BEGIN SELECT RAISE(ABORT, 'boom'); END",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let err = insert_series(
|
||||
&conn,
|
||||
"99",
|
||||
"Show",
|
||||
None,
|
||||
&["A".into()],
|
||||
"/tv/Show",
|
||||
1,
|
||||
&[ep(1, 1)],
|
||||
);
|
||||
assert!(err.is_err());
|
||||
|
||||
let items: i64 = conn
|
||||
.query_row("SELECT count(*) FROM media_item", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
let seasons: i64 = conn
|
||||
.query_row("SELECT count(*) FROM season", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
let aliases: i64 = conn
|
||||
.query_row("SELECT count(*) FROM alias", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(items, 0);
|
||||
assert_eq!(seasons, 0);
|
||||
assert_eq!(aliases, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_series_is_idempotent_on_tvdb_id() {
|
||||
let conn = conn();
|
||||
let first = insert_series(
|
||||
&conn,
|
||||
"12345",
|
||||
"Show",
|
||||
None,
|
||||
&[],
|
||||
"/tv/Show",
|
||||
1,
|
||||
&[ep(1, 1)],
|
||||
)
|
||||
.unwrap();
|
||||
let second = insert_series(
|
||||
&conn,
|
||||
"12345",
|
||||
"Other Title",
|
||||
None,
|
||||
&[],
|
||||
"/tv/Other",
|
||||
1,
|
||||
&[],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(first, second);
|
||||
let count: i64 = conn
|
||||
.query_row(
|
||||
"SELECT count(*) FROM media_item WHERE tvdb_id = 12345",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_movie_is_idempotent_on_tmdb_id() {
|
||||
let conn = conn();
|
||||
let first = insert_movie(&conn, "550", "Fight Club", Some(1999), "/movies", 2).unwrap();
|
||||
let second = insert_movie(&conn, "550", "Fight Club 2", Some(2000), "/movies", 2).unwrap();
|
||||
assert_eq!(first, second);
|
||||
let count: i64 = conn
|
||||
.query_row(
|
||||
"SELECT count(*) FROM media_item WHERE tmdb_id = 550",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(count, 1);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,7 +34,6 @@ pub struct ParsedRelease {
|
|||
pub bit_depth: Option<u8>,
|
||||
pub container: Option<String>,
|
||||
pub is_repack: bool,
|
||||
pub has_hdr: bool,
|
||||
}
|
||||
|
||||
pub fn parse(raw_title: &str) -> ParsedRelease {
|
||||
|
|
@ -54,7 +53,6 @@ pub fn parse(raw_title: &str) -> ParsedRelease {
|
|||
let codec = tokens::extract_codec(&work);
|
||||
let bit_depth = tokens::extract_bit_depth(&work);
|
||||
let is_repack = tokens::REPACK_RE.is_match(&work);
|
||||
let has_hdr = tokens::extract_hdr(&work);
|
||||
let year = tokens::extract_year(&work);
|
||||
let (season, episode, absolute_episode, title_span_end) = tokens::extract_episode_info(&work);
|
||||
|
||||
|
|
@ -74,7 +72,6 @@ pub fn parse(raw_title: &str) -> ParsedRelease {
|
|||
bit_depth,
|
||||
container,
|
||||
is_repack,
|
||||
has_hdr,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -363,16 +360,6 @@ mod tests {
|
|||
assert_eq!(p.year, Some(2023));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_hdr_hdr10_and_dolby_vision_tokens() {
|
||||
assert!(parse("Movie.2024.2160p.HDR.mkv").has_hdr);
|
||||
assert!(parse("Movie.2024.DV.mkv").has_hdr);
|
||||
assert!(parse("Movie.2024.2160p.HDR10.BluRay").has_hdr);
|
||||
assert!(parse("Movie.2024.2160p.DoVi.mkv").has_hdr);
|
||||
assert!(parse("Movie.2024.Dolby.Vision.2160p").has_hdr);
|
||||
assert!(!parse("Movie.2024.1080p.WEB-DL.H264").has_hdr);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_panic_on_unparsable_manga_release() {
|
||||
// Not a video release at all — should degrade gracefully, not crash.
|
||||
|
|
|
|||
|
|
@ -29,9 +29,6 @@ static BIT_DEPTH_RE: LazyLock<Regex> =
|
|||
pub(super) static REPACK_RE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"(?i)\b(REPACK|PROPER)\b").unwrap());
|
||||
|
||||
static HDR_RE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"(?i)\b(?:HDR10\+?|HDR|Dolby[.\s]?Vision|DoVi|DV)\b").unwrap());
|
||||
|
||||
static YEAR_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[(\[](19|20)\d{2}[)\]]").unwrap());
|
||||
// Scene-style releases ("Dune.1984.1080p.BluRay.x264-GROUP") carry the year
|
||||
// bare, with no surrounding brackets — `YEAR_RE` above never matches these
|
||||
|
|
@ -184,10 +181,6 @@ pub(super) fn extract_bit_depth(s: &str) -> Option<u8> {
|
|||
BIT_DEPTH_RE.captures(s)?[1].parse().ok()
|
||||
}
|
||||
|
||||
pub(super) fn extract_hdr(s: &str) -> bool {
|
||||
HDR_RE.is_match(s)
|
||||
}
|
||||
|
||||
pub(super) fn extract_year(s: &str) -> Option<u32> {
|
||||
if let Some(m) = YEAR_RE.find(s) {
|
||||
return s[m.start() + 1..m.end() - 1].parse().ok();
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,4 +1,4 @@
|
|||
use crate::parser::{Codec, ParsedRelease, Source};
|
||||
use crate::parser::ParsedRelease;
|
||||
|
||||
use super::profile::{ProfileKind, QualityProfile};
|
||||
|
||||
|
|
@ -8,8 +8,8 @@ pub fn score(parsed: &ParsedRelease, seeders: u32, has_hdr: bool, profile: &Qual
|
|||
|
||||
total += w.seeder * seeder_score(seeders);
|
||||
total += w.resolution_tier * resolution_tier(parsed.resolution);
|
||||
total += w.source_tier * source_tier(parsed.source);
|
||||
total += w.codec_tier * codec_tier(parsed.codec);
|
||||
total += w.source_tier * parsed.source.map(|s| s as u8 as f32).unwrap_or(0.0);
|
||||
total += w.codec_tier * parsed.codec.map(|c| c as u8 as f32).unwrap_or(0.0);
|
||||
|
||||
if parsed.bit_depth == Some(10) {
|
||||
total += w.bit_depth;
|
||||
|
|
@ -52,29 +52,6 @@ fn resolution_tier(resolution: Option<u32>) -> f32 {
|
|||
}
|
||||
}
|
||||
|
||||
/// Explicit tiers — `Source::Hdtv` is discriminant 0, so casting the enum
|
||||
/// to `u8` scored HDTV identically to an unknown/missing source.
|
||||
fn source_tier(source: Option<Source>) -> f32 {
|
||||
match source {
|
||||
Some(Source::Hdtv) => 1.0,
|
||||
Some(Source::WebRip) => 2.0,
|
||||
Some(Source::WebDl) => 3.0,
|
||||
Some(Source::BluRay) => 4.0,
|
||||
Some(Source::Remux) => 5.0,
|
||||
None => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Same reason as `source_tier`: `Codec::H264` is discriminant 0.
|
||||
fn codec_tier(codec: Option<Codec>) -> f32 {
|
||||
match codec {
|
||||
Some(Codec::H264) => 1.0,
|
||||
Some(Codec::Hevc) => 2.0,
|
||||
Some(Codec::Av1) => 3.0,
|
||||
None => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -175,36 +152,6 @@ mod tests {
|
|||
assert!(s720 > s480);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hdtv_h264_scores_strictly_above_a_release_with_no_source_or_codec() {
|
||||
let profile = QualityProfile::default_tv();
|
||||
let known = parser::parse("Show S01E01 1080p HDTV H264");
|
||||
let unknown = parser::parse("Show S01E01 1080p");
|
||||
assert!(known.source.is_some());
|
||||
assert!(known.codec.is_some());
|
||||
assert!(unknown.source.is_none());
|
||||
assert!(unknown.codec.is_none());
|
||||
assert!(score(&known, 50, false, &profile) > score(&unknown, 50, false, &profile));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remux_av1_scores_above_hdtv_h264() {
|
||||
let profile = QualityProfile::default_movie();
|
||||
let remux_av1 = parser::parse("Movie 2024 2160p Remux AV1");
|
||||
let hdtv_h264 = parser::parse("Movie 2024 2160p HDTV H264");
|
||||
assert!(score(&remux_av1, 50, false, &profile) > score(&hdtv_h264, 50, false, &profile));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parsed_hdr_movie_scores_higher_than_the_same_release_without_hdr() {
|
||||
let profile = QualityProfile::default_movie();
|
||||
let hdr = parser::parse("Movie.2024.2160p.BluRay.HDR.H264");
|
||||
let sdr = parser::parse("Movie.2024.2160p.BluRay.H264");
|
||||
assert!(hdr.has_hdr);
|
||||
assert!(!sdr.has_hdr);
|
||||
assert!(score(&hdr, 50, hdr.has_hdr, &profile) > score(&sdr, 50, sdr.has_hdr, &profile));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allowlisted_group_scores_higher_than_unlisted() {
|
||||
let mut profile = QualityProfile::default_tv();
|
||||
|
|
|
|||
|
|
@ -1,8 +1,6 @@
|
|||
pub mod rss;
|
||||
pub mod scrape;
|
||||
pub mod torrents_csv;
|
||||
pub mod tpb;
|
||||
pub mod yts;
|
||||
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
|
|
@ -27,39 +25,6 @@ pub trait ReleaseSource {
|
|||
async fn fetch(&self, query: Option<&str>) -> Result<Vec<RawReleaseItem>>;
|
||||
}
|
||||
|
||||
/// Trackers attached to every magnet we synthesize from an info-hash
|
||||
/// (TPB, torrents-csv, YTS). Same set the TPB client has used since it
|
||||
/// landed — qBittorrent needs *some* announce list or the torrent sits
|
||||
/// hash-only until DHT finds peers.
|
||||
const MAGNET_TRACKERS: &[&str] = &[
|
||||
"udp://tracker.opentrackr.org:1337/announce",
|
||||
"udp://open.stealth.si:80/announce",
|
||||
"udp://tracker.torrent.eu.org:451/announce",
|
||||
"udp://tracker.openbittorrent.com:6969/announce",
|
||||
"udp://exodus.desync.com:6969/announce",
|
||||
];
|
||||
|
||||
/// A valid BitTorrent v1 info_hash: 40 hex chars or 32 base32 chars — same
|
||||
/// shape `qbit::extract_btih` accepts out of a magnet URI. Shared by every
|
||||
/// hash-to-magnet source so a malformed value can't silently produce a
|
||||
/// magnet the grab path then fails to parse back.
|
||||
pub(crate) fn is_valid_info_hash(hash: &str) -> bool {
|
||||
(hash.len() == 40 && hash.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
|| (hash.len() == 32
|
||||
&& hash
|
||||
.bytes()
|
||||
.all(|b| matches!(b, b'2'..=b'7' | b'a'..=b'z' | b'A'..=b'Z')))
|
||||
}
|
||||
|
||||
pub(crate) fn build_magnet(info_hash: &str, name: &str) -> String {
|
||||
let mut magnet = format!("magnet:?xt=urn:btih:{info_hash}&dn={}", urlencode(name));
|
||||
for t in MAGNET_TRACKERS {
|
||||
magnet.push_str("&tr=");
|
||||
magnet.push_str(&urlencode(t));
|
||||
}
|
||||
magnet
|
||||
}
|
||||
|
||||
pub(crate) fn urlencode(s: &str) -> String {
|
||||
s.chars()
|
||||
.map(|c| {
|
||||
|
|
|
|||
|
|
@ -313,9 +313,6 @@ fn parse_search_results(html: &str, mirror: &str) -> Option<Vec<RawReleaseItem>>
|
|||
continue;
|
||||
}
|
||||
let detail_url = if href.starts_with("http") {
|
||||
if !same_origin(href, mirror) {
|
||||
continue;
|
||||
}
|
||||
href.to_string()
|
||||
} else {
|
||||
format!("{mirror}{href}")
|
||||
|
|
@ -363,27 +360,6 @@ fn parse_search_results(html: &str, mirror: &str) -> Option<Vec<RawReleaseItem>>
|
|||
Some(items)
|
||||
}
|
||||
|
||||
/// Scheme+host(+port) origin of an `http(s)://...` URL. `None` if the
|
||||
/// string isn't an absolute http(s) URL with a host.
|
||||
fn url_origin(url: &str) -> Option<(&str, &str)> {
|
||||
let (scheme, rest) = if let Some(r) = url.strip_prefix("https://") {
|
||||
("https", r)
|
||||
} else {
|
||||
let r = url.strip_prefix("http://")?;
|
||||
("http", r)
|
||||
};
|
||||
let hostport = rest.split('/').next().filter(|s| !s.is_empty())?;
|
||||
let hostport = hostport.rsplit('@').next().unwrap_or(hostport);
|
||||
Some((scheme, hostport))
|
||||
}
|
||||
|
||||
fn same_origin(href: &str, mirror: &str) -> bool {
|
||||
match (url_origin(href), url_origin(mirror)) {
|
||||
(Some((as_, ah)), Some((bs, bh))) => as_ == bs && ah.eq_ignore_ascii_case(bh),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_magnet(html: &str) -> Option<String> {
|
||||
let doc = Html::parse_document(html);
|
||||
let sel = Selector::parse(r#"a[href^="magnet:"]"#).unwrap();
|
||||
|
|
@ -444,32 +420,6 @@ mod tests {
|
|||
assert_eq!(a[0].guid, b[0].guid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drops_off_origin_absolute_hrefs_but_keeps_relative() {
|
||||
let html = r#"
|
||||
<table class="table-list table table-responsive table-striped">
|
||||
<thead><tr><th class="coll-1 name">name</th><th class="coll-2">se</th><th class="coll-3">le</th><th class="coll-4">size</th></tr></thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td class="coll-1 name"><a href="http://127.0.0.1/evil">Evil</a></td>
|
||||
<td class="coll-2">1</td>
|
||||
<td class="coll-3">1</td>
|
||||
<td class="coll-4">1 MB</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="coll-1 name"><a href="/torrent/3250239/Ok/">Good</a></td>
|
||||
<td class="coll-2">2</td>
|
||||
<td class="coll-3">2</td>
|
||||
<td class="coll-4">2 MB</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>"#;
|
||||
let items = parse_search_results(html, "https://13377x.info").unwrap();
|
||||
assert_eq!(items.len(), 1);
|
||||
assert_eq!(items[0].title, "Good");
|
||||
assert_eq!(items[0].link, "https://13377x.info/torrent/3250239/Ok/");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_torrent_id_handles_relative_and_absolute_hrefs() {
|
||||
assert_eq!(
|
||||
|
|
|
|||
|
|
@ -1,130 +0,0 @@
|
|||
use anyhow::{Context, Result};
|
||||
use async_trait::async_trait;
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::{build_magnet, is_valid_info_hash, urlencode, RawReleaseItem, ReleaseSource};
|
||||
|
||||
/// Public JSON search over the torrents.csv DHT dump. Same grab shape as
|
||||
/// TPB (info-hash → magnet, no HTML): used as the first general-content
|
||||
/// fallback when apibay is down or returns nothing. Seeders are scrape
|
||||
/// snapshots, not live tracker data, so a high number can still stall —
|
||||
/// the existing seeder gate still applies.
|
||||
pub struct TorrentsCsvSource {
|
||||
api_url: String,
|
||||
client: reqwest::Client,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CsvResponse {
|
||||
#[serde(default)]
|
||||
torrents: Vec<CsvTorrent>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CsvTorrent {
|
||||
infohash: String,
|
||||
name: String,
|
||||
size_bytes: Option<u64>,
|
||||
seeders: Option<i64>,
|
||||
leechers: Option<i64>,
|
||||
}
|
||||
|
||||
impl TorrentsCsvSource {
|
||||
pub fn new(api_url: impl Into<String>) -> Self {
|
||||
Self {
|
||||
api_url: api_url.into(),
|
||||
client: reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(30))
|
||||
.build()
|
||||
.expect("reqwest client build"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn as_u32(n: Option<i64>) -> Option<u32> {
|
||||
n.and_then(|v| u32::try_from(v.max(0)).ok())
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ReleaseSource for TorrentsCsvSource {
|
||||
async fn fetch(&self, query: Option<&str>) -> Result<Vec<RawReleaseItem>> {
|
||||
let Some(query) = query else {
|
||||
anyhow::bail!(
|
||||
"TorrentsCsvSource requires a search query (this is a search-driven source, not a feed)"
|
||||
);
|
||||
};
|
||||
let sep = if self.api_url.contains('?') { '&' } else { '?' };
|
||||
let url = format!(
|
||||
"{}{sep}q={}&size=25",
|
||||
self.api_url.trim_end_matches('/'),
|
||||
urlencode(query)
|
||||
);
|
||||
let parsed: CsvResponse = self
|
||||
.client
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
.with_context(|| format!("request to {url} failed"))?
|
||||
.error_for_status()
|
||||
.with_context(|| format!("{url} returned an error status"))?
|
||||
.json()
|
||||
.await
|
||||
.context("failed to parse torrents-csv response as JSON")?;
|
||||
|
||||
Ok(parsed
|
||||
.torrents
|
||||
.into_iter()
|
||||
.filter(|t| is_valid_info_hash(&t.infohash))
|
||||
.map(|t| RawReleaseItem {
|
||||
title: t.name.clone(),
|
||||
link: build_magnet(&t.infohash, &t.name),
|
||||
guid: t.infohash,
|
||||
size_bytes: t.size_bytes,
|
||||
seeders: as_u32(t.seeders),
|
||||
leechers: as_u32(t.leechers),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_a_real_captured_response() {
|
||||
let body = r#"{
|
||||
"torrents": [
|
||||
{
|
||||
"infohash": "ed0da850c273e3e15a819bdcbbf418bc85107ec8",
|
||||
"name": "Dune (2021) [1080p] [WEBRip]",
|
||||
"size_bytes": 2947989023,
|
||||
"seeders": 746,
|
||||
"leechers": 38
|
||||
},
|
||||
{
|
||||
"infohash": "not-a-hash",
|
||||
"name": "garbage",
|
||||
"size_bytes": 1,
|
||||
"seeders": 0,
|
||||
"leechers": 0
|
||||
}
|
||||
]
|
||||
}"#;
|
||||
let parsed: CsvResponse = serde_json::from_str(body).unwrap();
|
||||
let items: Vec<_> = parsed
|
||||
.torrents
|
||||
.into_iter()
|
||||
.filter(|t| is_valid_info_hash(&t.infohash))
|
||||
.collect();
|
||||
assert_eq!(items.len(), 1);
|
||||
assert_eq!(items[0].name, "Dune (2021) [1080p] [WEBRip]");
|
||||
assert_eq!(items[0].seeders, Some(746));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_payload_is_no_results_not_an_error() {
|
||||
let parsed: CsvResponse = serde_json::from_str(r#"{"torrents":[]}"#).unwrap();
|
||||
assert!(parsed.torrents.is_empty());
|
||||
}
|
||||
}
|
||||
|
|
@ -2,7 +2,18 @@ use anyhow::{Context, Result};
|
|||
use async_trait::async_trait;
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::{build_magnet, is_valid_info_hash, urlencode, RawReleaseItem, ReleaseSource};
|
||||
use super::{urlencode, RawReleaseItem, ReleaseSource};
|
||||
|
||||
/// A valid BitTorrent v1 info_hash: 40 hex chars or 32 base32 chars — same
|
||||
/// shape `qbit::extract_btih` accepts out of a magnet URI. Checked before
|
||||
/// building a magnet from `info_hash` at all: apibay is normally reliable,
|
||||
/// but a malformed value would otherwise silently produce a magnet
|
||||
/// `extract_btih` can't parse back out, downgrading that grab to the slow
|
||||
/// ~30s `torrents/info` polling path with no visible error anywhere.
|
||||
fn is_valid_info_hash(hash: &str) -> bool {
|
||||
(hash.len() == 40 && hash.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
|| (hash.len() == 32 && hash.bytes().all(|b| matches!(b, b'2'..=b'7' | b'a'..=b'z' | b'A'..=b'Z')))
|
||||
}
|
||||
|
||||
/// A community-run JSON API mirror of The Pirate Bay's search — unlike
|
||||
/// 1337x, this is a genuine machine-readable API (not HTML scraping), and
|
||||
|
|
@ -27,6 +38,23 @@ struct TpbResult {
|
|||
size: String,
|
||||
}
|
||||
|
||||
const TRACKERS: &[&str] = &[
|
||||
"udp://tracker.opentrackr.org:1337/announce",
|
||||
"udp://open.stealth.si:80/announce",
|
||||
"udp://tracker.torrent.eu.org:451/announce",
|
||||
"udp://tracker.openbittorrent.com:6969/announce",
|
||||
"udp://exodus.desync.com:6969/announce",
|
||||
];
|
||||
|
||||
fn build_magnet(info_hash: &str, name: &str) -> String {
|
||||
let mut magnet = format!("magnet:?xt=urn:btih:{info_hash}&dn={}", urlencode(name));
|
||||
for t in TRACKERS {
|
||||
magnet.push_str("&tr=");
|
||||
magnet.push_str(&urlencode(t));
|
||||
}
|
||||
magnet
|
||||
}
|
||||
|
||||
impl TpbSource {
|
||||
pub fn new(api_url: impl Into<String>) -> Self {
|
||||
Self {
|
||||
|
|
@ -126,9 +154,7 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn is_valid_info_hash_accepts_both_real_shapes() {
|
||||
assert!(is_valid_info_hash(
|
||||
"8F87C7C186172F17E35F4512BB1A3E93B614ADED"
|
||||
)); // 40 hex
|
||||
assert!(is_valid_info_hash("8F87C7C186172F17E35F4512BB1A3E93B614ADED")); // 40 hex
|
||||
assert!(is_valid_info_hash("abcdefghijklmnopqrstuvwxyz234567")); // 32 base32
|
||||
}
|
||||
|
||||
|
|
@ -141,11 +167,7 @@ mod tests {
|
|||
fn is_valid_info_hash_rejects_malformed_values() {
|
||||
assert!(!is_valid_info_hash(""));
|
||||
assert!(!is_valid_info_hash("too-short"));
|
||||
assert!(!is_valid_info_hash(
|
||||
"not-a-hex-string-at-all-nope!!!!!!!!!!!!"
|
||||
)); // 40 chars, non-hex
|
||||
assert!(!is_valid_info_hash(
|
||||
"8F87C7C186172F17E35F4512BB1A3E93B614ADE"
|
||||
)); // 39 hex chars
|
||||
assert!(!is_valid_info_hash("not-a-hex-string-at-all-nope!!!!!!!!!!!!")); // 40 chars, non-hex
|
||||
assert!(!is_valid_info_hash("8F87C7C186172F17E35F4512BB1A3E93B614ADE")); // 39 hex chars
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,194 +0,0 @@
|
|||
use anyhow::{Context, Result};
|
||||
use async_trait::async_trait;
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::{build_magnet, is_valid_info_hash, urlencode, RawReleaseItem, ReleaseSource};
|
||||
|
||||
/// YTS movie API. `yts.mx` itself no longer resolves (checked 2026-07-12
|
||||
/// and again 2026-08-16); the `yts.lt` / `yts.am` hosts still serve the
|
||||
/// v2 JSON API, which is why the default URL is a working mirror rather
|
||||
/// than the brand domain. Movies only — each hit expands into one
|
||||
/// `RawReleaseItem` per quality so the scorer sees 720p/1080p/2160p as
|
||||
/// distinct candidates, same as if they were separate TPB rows.
|
||||
pub struct YtsSource {
|
||||
api_url: String,
|
||||
client: reqwest::Client,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct YtsResponse {
|
||||
status: String,
|
||||
data: Option<YtsData>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
struct YtsData {
|
||||
#[serde(default)]
|
||||
movies: Vec<YtsMovie>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct YtsMovie {
|
||||
title: String,
|
||||
year: Option<i64>,
|
||||
#[serde(default)]
|
||||
torrents: Vec<YtsTorrent>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct YtsTorrent {
|
||||
hash: String,
|
||||
quality: Option<String>,
|
||||
#[serde(rename = "type")]
|
||||
source_type: Option<String>,
|
||||
video_codec: Option<String>,
|
||||
seeds: Option<i64>,
|
||||
peers: Option<i64>,
|
||||
size_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
impl YtsSource {
|
||||
pub fn new(api_url: impl Into<String>) -> Self {
|
||||
Self {
|
||||
api_url: api_url.into(),
|
||||
client: reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(30))
|
||||
.build()
|
||||
.expect("reqwest client build"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn as_u32(n: Option<i64>) -> Option<u32> {
|
||||
n.and_then(|v| u32::try_from(v.max(0)).ok())
|
||||
}
|
||||
|
||||
/// Builds a release title the existing parser can read quality/source/codec
|
||||
/// out of — YTS stores those as structured fields, not in `title`.
|
||||
fn release_title(movie: &YtsMovie, torrent: &YtsTorrent) -> String {
|
||||
let mut title = movie.title.clone();
|
||||
if let Some(year) = movie.year {
|
||||
title.push_str(&format!(" ({year})"));
|
||||
}
|
||||
for part in [
|
||||
torrent.quality.as_deref(),
|
||||
torrent.source_type.as_deref(),
|
||||
torrent.video_codec.as_deref(),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
if !part.is_empty() {
|
||||
title.push_str(&format!(" [{part}]"));
|
||||
}
|
||||
}
|
||||
title
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ReleaseSource for YtsSource {
|
||||
async fn fetch(&self, query: Option<&str>) -> Result<Vec<RawReleaseItem>> {
|
||||
let Some(query) = query else {
|
||||
anyhow::bail!(
|
||||
"YtsSource requires a search query (this is a search-driven source, not a feed)"
|
||||
);
|
||||
};
|
||||
let sep = if self.api_url.contains('?') { '&' } else { '?' };
|
||||
let url = format!(
|
||||
"{}{sep}query_term={}&limit=20&sort_by=seeds",
|
||||
self.api_url.trim_end_matches('/'),
|
||||
urlencode(query)
|
||||
);
|
||||
let parsed: YtsResponse = self
|
||||
.client
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
.with_context(|| format!("request to {url} failed"))?
|
||||
.error_for_status()
|
||||
.with_context(|| format!("{url} returned an error status"))?
|
||||
.json()
|
||||
.await
|
||||
.context("failed to parse YTS response as JSON")?;
|
||||
anyhow::ensure!(
|
||||
parsed.status == "ok",
|
||||
"YTS returned status {:?}",
|
||||
parsed.status
|
||||
);
|
||||
|
||||
let movies = parsed.data.unwrap_or_default().movies;
|
||||
let mut items = Vec::new();
|
||||
for movie in movies {
|
||||
for torrent in &movie.torrents {
|
||||
if !is_valid_info_hash(&torrent.hash) {
|
||||
continue;
|
||||
}
|
||||
let title = release_title(&movie, torrent);
|
||||
items.push(RawReleaseItem {
|
||||
title: title.clone(),
|
||||
link: build_magnet(&torrent.hash, &title),
|
||||
guid: torrent.hash.clone(),
|
||||
size_bytes: torrent.size_bytes,
|
||||
seeders: as_u32(torrent.seeds),
|
||||
leechers: as_u32(torrent.peers),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(items)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SAMPLE: &str = r#"{
|
||||
"status": "ok",
|
||||
"data": {
|
||||
"movie_count": 1,
|
||||
"movies": [{
|
||||
"title": "Dune: Part One",
|
||||
"year": 2021,
|
||||
"torrents": [
|
||||
{
|
||||
"hash": "DEB6929BEEB09ADCBD14DC4D6081F7E6B297B88C",
|
||||
"quality": "1080p",
|
||||
"type": "web",
|
||||
"video_codec": "x264",
|
||||
"seeds": 12,
|
||||
"peers": 3,
|
||||
"size_bytes": 2147483648
|
||||
},
|
||||
{
|
||||
"hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"quality": "720p",
|
||||
"type": "bluray",
|
||||
"video_codec": "x265",
|
||||
"seeds": 4,
|
||||
"peers": 1,
|
||||
"size_bytes": 1073741824
|
||||
}
|
||||
]
|
||||
}]
|
||||
}
|
||||
}"#;
|
||||
|
||||
#[test]
|
||||
fn expands_one_movie_into_per_quality_rows() {
|
||||
let parsed: YtsResponse = serde_json::from_str(SAMPLE).unwrap();
|
||||
assert_eq!(parsed.status, "ok");
|
||||
let movie = &parsed.data.unwrap().movies[0];
|
||||
assert_eq!(movie.torrents.len(), 2);
|
||||
let t0 = release_title(movie, &movie.torrents[0]);
|
||||
assert_eq!(t0, "Dune: Part One (2021) [1080p] [web] [x264]");
|
||||
let t1 = release_title(movie, &movie.torrents[1]);
|
||||
assert_eq!(t1, "Dune: Part One (2021) [720p] [bluray] [x265]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_movies_array_is_empty_not_an_error() {
|
||||
let parsed: YtsResponse =
|
||||
serde_json::from_str(r#"{"status":"ok","data":{"movie_count":0}}"#).unwrap();
|
||||
assert!(parsed.data.unwrap_or_default().movies.is_empty());
|
||||
}
|
||||
}
|
||||
13
ci/build.sh
13
ci/build.sh
|
|
@ -12,11 +12,8 @@ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
|||
REV="$(cat "${ROOT}/ci/bread-ecosystem.rev")"
|
||||
|
||||
CACHE_DIR="/tmp/bread-ecosystem-ci-${REV}"
|
||||
# Only create/replace this product's own pin directory. A glob rm of
|
||||
# /tmp/bread-ecosystem-ci-* races other products' mktemp clones used by
|
||||
# release-index regen.
|
||||
if [ ! -d "$CACHE_DIR/.git" ]; then
|
||||
rm -rf "$CACHE_DIR"
|
||||
if [ ! -d "$CACHE_DIR" ]; then
|
||||
rm -rf /tmp/bread-ecosystem-ci-*
|
||||
git clone https://git.breadway.dev/Breadway/bread-ecosystem.git "$CACHE_DIR"
|
||||
git -C "$CACHE_DIR" checkout --quiet "$REV"
|
||||
fi
|
||||
|
|
@ -38,10 +35,6 @@ fi
|
|||
# linked via --sysroot, sidesteps that entirely.
|
||||
GLIBC_VER="2.39-4"
|
||||
GCC_LIBS_VER="13.2.1-6"
|
||||
# Pinned to the archive.archlinux.org packages fetched above (sha256 of
|
||||
# the two .pkg.tar.zst files, not the extracted trees).
|
||||
GLIBC_SHA256="c6aef7065e0d53d700cc5ff65d4db775cb84e2f4e3912a609223ed72fb1799d4"
|
||||
GCC_LIBS_SHA256="edbb8c4772b8852fe102853a84d197253127418f50cca475feda9bbaa842a378"
|
||||
OLD_GLIBC_CACHE="/tmp/bread-ci-old-glibc-${GLIBC_VER}"
|
||||
if [ ! -d "${OLD_GLIBC_CACHE}/usr/lib" ]; then
|
||||
rm -rf "${OLD_GLIBC_CACHE}"
|
||||
|
|
@ -50,8 +43,6 @@ if [ ! -d "${OLD_GLIBC_CACHE}/usr/lib" ]; then
|
|||
"https://archive.archlinux.org/packages/g/glibc/glibc-${GLIBC_VER}-x86_64.pkg.tar.zst"
|
||||
curl -sfL -o /tmp/old-gcc-libs.pkg.tar.zst \
|
||||
"https://archive.archlinux.org/packages/g/gcc-libs/gcc-libs-${GCC_LIBS_VER}-x86_64.pkg.tar.zst"
|
||||
echo "${GLIBC_SHA256} /tmp/old-glibc.pkg.tar.zst" | sha256sum -c -
|
||||
echo "${GCC_LIBS_SHA256} /tmp/old-gcc-libs.pkg.tar.zst" | sha256sum -c -
|
||||
tar --zstd -xf /tmp/old-glibc.pkg.tar.zst -C "${OLD_GLIBC_CACHE}"
|
||||
tar --zstd -xf /tmp/old-gcc-libs.pkg.tar.zst -C "${OLD_GLIBC_CACHE}"
|
||||
rm -f /tmp/old-glibc.pkg.tar.zst /tmp/old-gcc-libs.pkg.tar.zst
|
||||
|
|
|
|||
|
|
@ -12,9 +12,7 @@ model_dir = "~/.cache/breadarr/models/all-MiniLM-L6-v2"
|
|||
# Empty (default) means no auth at all. Set this if listen_addr is ever
|
||||
# changed to bind non-loopback (e.g. so a TUI on another host on the same
|
||||
# tailnet can reach it) — otherwise that's unauthenticated add/delete/search
|
||||
# access to anyone who can reach the port. The API is plaintext HTTP; there
|
||||
# is no TLS. /health is always exempt (liveness only). /health/detail
|
||||
# carries cycle info and is authenticated when this token is set.
|
||||
# access to anyone who can reach the port. /health is always exempt.
|
||||
api_token = ""
|
||||
|
||||
[qbit]
|
||||
|
|
@ -65,19 +63,7 @@ movies_root_folder = "~/breadarr-library/Movies"
|
|||
# automatically and grabs anything matching a monitored, missing episode.
|
||||
nyaa_rss_url = "https://nyaa.si/?page=rss&c=1_2"
|
||||
grab_poll_interval_secs = 300
|
||||
# Kill switch for the passive RSS-feed grab loop (nyaa). Independent of
|
||||
# search_enabled / upgrade_enabled.
|
||||
grab_enabled = true
|
||||
import_poll_interval_secs = 60
|
||||
# Community JSON API mirror of The Pirate Bay — primary general-content
|
||||
# search source (movies + non-anime TV).
|
||||
tpb_api_url = "https://apibay.org/q.php"
|
||||
# torrents.csv DHT-dump search — first fallback when TPB fails or returns
|
||||
# nothing. Same hash-to-magnet grab; movies and TV.
|
||||
torrents_csv_url = "https://torrents-csv.com/service/search"
|
||||
# YTS v2 list_movies JSON — movie-only fallback. yts.mx does not resolve;
|
||||
# yts.lt is a working host as of 2026-08-16.
|
||||
yts_api_url = "https://yts.lt/api/v2/list_movies.json"
|
||||
# Search-driven acquisition (movies + non-anime TV via 1337x, anime movies
|
||||
# via nyaa's search mode) — unlike the nyaa RSS feed watch above, this
|
||||
# actively queries a Cloudflare-fronted service with a ban history, so keep
|
||||
|
|
@ -102,7 +88,6 @@ upgrade_min_score_gain = 5.0
|
|||
# tried in a fixed fallback order), with a failing mirror demoted into a
|
||||
# cooldown rather than re-probed on the very next search.
|
||||
torrent_1337x_mirrors = [
|
||||
"https://www.1337xx.to",
|
||||
"https://13377x.info",
|
||||
"https://13377x.email",
|
||||
"https://1337xto.info",
|
||||
|
|
@ -117,31 +102,3 @@ torrent_1337x_mirrors = [
|
|||
"https://1337x.unblocktorrent.info",
|
||||
"https://1337x.unblocktor.xyz",
|
||||
]
|
||||
|
||||
# Off by default — GPU/CPU AV1 encode needs a calibration pass against
|
||||
# real content on the target hardware before it's safe unattended.
|
||||
# Defaults match breadarr-shared/src/config.rs.
|
||||
[transcode]
|
||||
enabled = false
|
||||
poll_interval_secs = 60
|
||||
vaapi_device = "/dev/dri/renderD128"
|
||||
parallelism_min = 1
|
||||
# Live-action (av1_vaapi) concurrent-stream ceiling; Jellyfin viewers
|
||||
# are subtracted from this each cycle.
|
||||
parallelism_max = 7
|
||||
# Separate CPU-bound anime (libsvtav1) ceiling.
|
||||
parallelism_max_anime = 2
|
||||
reference_bitrate_kbps = 5320
|
||||
reference_height = 1080
|
||||
av1_efficiency_factor = 0.7
|
||||
exclude_hdr = true
|
||||
exclude_min_height = 2000
|
||||
quality_live_action = 26
|
||||
# Path prefixes routed to the anime encode pipeline. Empty is a no-op.
|
||||
anime_root_folders = []
|
||||
quality_anime = 24
|
||||
anime_svtav1_preset = 10
|
||||
anime_svtav1_max_threads = 4
|
||||
min_size_reduction_pct = 0.10
|
||||
skip_below_ceiling_ratio = 0.5
|
||||
verify_sample_secs = 20.0
|
||||
|
|
|
|||
|
|
@ -17,14 +17,7 @@ UMask=0022
|
|||
RuntimeDirectory=breadarr
|
||||
RuntimeDirectoryMode=0700
|
||||
KillSignal=SIGTERM
|
||||
# Transcode jobs can run for minutes; 5s was cutting them off on stop.
|
||||
TimeoutStopSec=180
|
||||
# Modest hardening valid in a user unit. Skip ProtectHome (library +
|
||||
# config live under $HOME) and MemoryDenyWriteExecute (ort/onnxruntime
|
||||
# may need JIT / RWX mappings).
|
||||
NoNewPrivileges=yes
|
||||
RestrictSUIDSGID=yes
|
||||
LockPersonality=yes
|
||||
TimeoutStopSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue