diff --git a/.github/ISSUE_TEMPLATE/theme_submission.yml b/.github/ISSUE_TEMPLATE/theme_submission.yml new file mode 100644 index 0000000000..4a88155b36 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/theme_submission.yml @@ -0,0 +1,77 @@ +name: Community theme submission +description: Share an independently styled SeerrNG theme for review. +title: '[Theme]: ' +body: + - type: markdown + attributes: + value: | + Share source and a reproducible `.seerrtheme` package. This form requests + review; it does not install or approve a theme automatically. + Read [the guide](https://github.com/snapetech-org/seerrng/blob/main/docs/interface-themes/submitting.md). + - type: input + id: identity + attributes: + label: Theme name, package ID and version + placeholder: My Cinema / my-cinema / 0.1.0 + validations: + required: true + - type: input + id: source + attributes: + label: Source repository and immutable tag or commit + validations: + required: true + - type: textarea + id: package + attributes: + label: Package and SHA-256 checksum URLs + description: Link the generated .seerrtheme and .sha256 files, plus the checksum text. + validations: + required: true + - type: input + id: license + attributes: + label: License and base-theme attribution + validations: + required: true + - type: dropdown + id: layout + attributes: + label: Native composition + options: + - Persius + - Classic + validations: + required: true + - type: textarea + id: compatibility + attributes: + label: Tested SeerrNG releases, browsers and enabled services + validations: + required: true + - type: textarea + id: evidence + attributes: + label: Screenshots, viewports and interaction results + description: Include desktop/phone and light/dark examples. Identify any mocked previews. + validations: + required: true + - type: textarea + id: limits + attributes: + label: Known limitations and untested states + validations: + required: true + - type: checkboxes + id: checks + attributes: + label: Submission checks + options: + - label: The source and packaged file both pass interface-theme:validate. + required: true + - label: The checksum matches the attached package and source release. + required: true + - label: I tested installation and account selection in SeerrNG without a UI-rewriting proxy. + required: true + - label: I retained applicable license notices and listed any untested or unsupported flows. + required: true diff --git a/.github/workflows/release-flatpak.yml b/.github/workflows/release-flatpak.yml index 041c39a517..14c8482ba4 100644 --- a/.github/workflows/release-flatpak.yml +++ b/.github/workflows/release-flatpak.yml @@ -72,8 +72,8 @@ jobs: set -euo pipefail mkdir -p flatpak-src/seerrng flatpak-src/node tar -xzf "seerrng-${{ steps.version.outputs.tag }}-linux-x64.tar.gz" --strip-components=1 -C flatpak-src/seerrng - curl -fsSLo node.tar.xz https://nodejs.org/dist/v24.22.1/node-v24.22.1-linux-x64.tar.xz - echo "6c172a9ab6718f7b801fb5a7bd486af2ee5e32758086a04b84fcce2aa77095e6 node.tar.xz" | sha256sum -c - + curl -fsSLo node.tar.xz https://nodejs.org/dist/v24.22.2/node-v24.22.2-linux-x64.tar.xz + echo "48cc0e21e048790e54c0cf5749c2725005313d652651c40b7a21feb9697aaf75 node.tar.xz" | sha256sum -c - tar -xJf node.tar.xz --strip-components=1 -C flatpak-src/node - name: Build Flatpak bundle run: | diff --git a/.github/workflows/release-linux-packages.yml b/.github/workflows/release-linux-packages.yml index 7766d0fa43..2446c58bfa 100644 --- a/.github/workflows/release-linux-packages.yml +++ b/.github/workflows/release-linux-packages.yml @@ -227,7 +227,7 @@ jobs: appimagetool_url='https://github.com/AppImage/appimagetool/releases/download/1.9.1/appimagetool-x86_64.AppImage' curl -fsSL --retry 5 "$appimagetool_url" -o appimagetool echo 'ed4ce84f0d9caff66f50bcca6ff6f35aae54ce8135408b3fa33abfc3cb384eb0 appimagetool' | sha256sum -c - - node_version='24.22.1' + node_version='24.22.2' node_archive="node-v${node_version}-linux-x64.tar.xz" node_base_url="https://nodejs.org/dist/v${node_version}" curl -fsSL --retry 5 "${node_base_url}/${node_archive}" -o "$node_archive" diff --git a/.prettierignore b/.prettierignore index 56bcc82c9e..3b79932aa2 100644 --- a/.prettierignore +++ b/.prettierignore @@ -16,6 +16,8 @@ coverage/ out/ build/ artifacts/ +test-results/ +playwright-report/ cypress/runtime-config/ cypress/videos/ cypress/screenshots/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a2f391934b..c452726f92 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,13 +2,31 @@ All help is welcome and greatly appreciated! If you would like to contribute to the project, the following instructions should get you started... +## Contribute a theme + +Themes have their own scoped stylesheet and do not require a UI proxy or changes +in the application’s source. Start with a native layout and make it your own: + +```sh +pnpm install +pnpm interface-theme:create my-cinema --from persiusNG --name "My Cinema" --author "Your name" +pnpm interface-theme:validate ./my-cinema +pnpm interface-theme:pack ./my-cinema +``` + +The [authoring guide](docs/interface-themes/authoring.md) covers independent CSS, +layout choices, local testing, packaging, installation and upgrades. Follow the +[submission guide](docs/interface-themes/submitting.md) to share your source, +package, checksum and screenshots for review. Submitting a community theme does +not require making it a built-in theme or adding executable code. + ## Development ### Tools Required - HTML/Typescript/Javascript editor - [VSCode](https://code.visualstudio.com/) is recommended. Upon opening the project, a few extensions will be automatically recommended for install. -- [Node.js](https://nodejs.org/en/download/) (Node 24.22.1 or newer in the 24.x line) +- [Node.js](https://nodejs.org/en/download/) (Node 24.22.2 or newer in the 24.x line) - [Pnpm](https://pnpm.io/cli/install) - [Git](https://git-scm.com/downloads) diff --git a/Dockerfile b/Dockerfile index 0bcade2e78..8cd25a6191 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ ARG BUILDPLATFORM ARG TARGETPLATFORM -FROM mirror.gcr.io/library/node:24.22.1-alpine3.23@sha256:4b00b6d1aa138805aace94cc2482808f2b4f01e5e9c9f8cdc0e217fd70600ef9 AS target-base +FROM mirror.gcr.io/library/node:24.22.2-alpine3.23@sha256:9b69af715c7f9d038150b54ccccbaeffa9064bbc93e2904c29591ca097316af1 AS target-base ARG SOURCE_DATE_EPOCH ARG TARGETPLATFORM ENV TARGETPLATFORM=${TARGETPLATFORM:-linux/amd64} @@ -43,7 +43,7 @@ RUN if [ -d node_modules/.pnpm ]; then \ # Remove dependency source maps before copying production modules into the final image. RUN find node_modules/.pnpm -type f -name '*.map' -delete -FROM --platform=$BUILDPLATFORM mirror.gcr.io/library/node:24.22.1-alpine3.23@sha256:4b00b6d1aa138805aace94cc2482808f2b4f01e5e9c9f8cdc0e217fd70600ef9 AS build-base +FROM --platform=$BUILDPLATFORM mirror.gcr.io/library/node:24.22.2-alpine3.23@sha256:9b69af715c7f9d038150b54ccccbaeffa9064bbc93e2904c29591ca097316af1 AS build-base ARG SOURCE_DATE_EPOCH ARG BUILDPLATFORM ARG TARGETPLATFORM @@ -79,7 +79,7 @@ RUN pnpm i18n:check && pnpm build:next && pnpm build:server RUN rm -rf .next/cache -FROM mirror.gcr.io/library/node:24.22.1-alpine3.23@sha256:4b00b6d1aa138805aace94cc2482808f2b4f01e5e9c9f8cdc0e217fd70600ef9 +FROM mirror.gcr.io/library/node:24.22.2-alpine3.23@sha256:9b69af715c7f9d038150b54ccccbaeffa9064bbc93e2904c29591ca097316af1 ARG SOURCE_DATE_EPOCH ARG COMMIT_TAG ARG BUILD_VERSION=main @@ -99,6 +99,7 @@ COPY --chown=node:node public ./public COPY --chown=node:node scripts/export-external-config.mjs ./scripts/export-external-config.mjs COPY --chown=node:node scripts/healthcheck.mjs ./scripts/healthcheck.mjs COPY --chown=node:node deploy/seerrng-migrate.mjs ./deploy/seerrng-migrate.mjs +COPY --chown=node:node scripts/interface-theme.mjs ./scripts/interface-theme.mjs COPY --chown=node:node --from=prod-deps /app/node_modules ./node_modules COPY --chown=node:node --from=build /app/.next ./.next COPY --chown=node:node --from=build /app/dist ./dist diff --git a/Dockerfile.local b/Dockerfile.local index 01dece0722..77aea88e70 100644 --- a/Dockerfile.local +++ b/Dockerfile.local @@ -1,4 +1,4 @@ -FROM node:24.22.1-alpine3.23@sha256:4b00b6d1aa138805aace94cc2482808f2b4f01e5e9c9f8cdc0e217fd70600ef9 +FROM node:24.22.2-alpine3.23@sha256:9b69af715c7f9d038150b54ccccbaeffa9064bbc93e2904c29591ca097316af1 ENV PNPM_HOME="/pnpm" ENV PATH="$PNPM_HOME:$PATH" diff --git a/NOTICE.md b/NOTICE.md index ed16631a3a..6edb96bb4b 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -27,6 +27,18 @@ The `RemapOverseerrDeletedStatus` migration files are imported from upstream Seerr to preserve compatibility with databases created there. Their migration names and source issue links are retained intentionally. +## Individual episode availability + +SeerrNG's per-episode availability feature is an independent implementation +adapting proposals from Seerr [PR #1671](https://github.com/seerr-team/seerr/pull/1671), +[PR #3355](https://github.com/seerr-team/seerr/pull/3355), +[PR #3361](https://github.com/seerr-team/seerr/pull/3361), +[PR #3527](https://github.com/seerr-team/seerr/pull/3527), and +[PR #3402](https://github.com/seerr-team/seerr/pull/3402). The SeerrNG-specific +implementation and maintenance are attributed to snapetech and SeerrNG +contributors. It adds source-scoped reconciliation and per-library episode +order configuration while preserving separate standard and 4K states. + ## Seerr and SeerrNG migration utility The bidirectional migration utility, its tests, and its operating guide are diff --git a/README.md b/README.md index 8c37820ae8..6eb47b49dc 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ For local MCP access, see the [SnapeTech MCP integration guide](./docs/integrati - [Move between Seerr and SeerrNG](./docs/using-seerr/migrating-between-seerr-and-seerrng.md) - [Choose available media categories](./docs/using-seerr/settings/media-categories.md) - [Manage the family age gate and per-user maturity limits](./docs/using-seerr/age-gate.md) + - [Track individual TV episode availability](./docs/using-seerr/individual-episode-availability.md) - [Software requests: ROMs and PC games](./docs/using-seerr/software-acquisition.md) - [Request Status and Download copy](./docs/using-seerr/request-status.md) - [Books, authors, and series](./docs/using-seerr/books-and-series.md) @@ -96,6 +97,8 @@ For local MCP access, see the [SnapeTech MCP integration guide](./docs/integrati - Viewer-scoped movie and TV availability checks for linked Plex, Jellyfin, and Emby accounts, including visible seasons and exact request destinations. This SeerrNG adaptation is informed by Seerr [issue #180](https://github.com/seerr-team/seerr/issues/180) and [PR #3296](https://github.com/seerr-team/seerr/pull/3296); it does not change media-server permissions. - Optional Jellyfin and Emby profile sync during user imports, refreshing linked provider names and avatars while preserving SeerrNG email addresses, local passwords, and permissions. - Labeled movie and TV request destinations across multiple Radarr and Sonarr instances, with per-user access and availability tracked for each destination. +- Optional per-instance Radarr/Sonarr tag exclusions for library scans, with existing request history preserved and non-excluded service copies still counted. +- Advanced movie and TV requests resolve service, anime, account, and rule defaults without treating every displayed value as a deliberate override; editable requests can return to the configured Servarr defaults. See [request defaults and overrides](./docs/using-seerr/request-defaults.md). - Temporary Radarr and Sonarr connection or server failures retry automatically with durable, bounded backoff; non-transient failures remain visible for review and manual retry. - Managers can approve a one-time movie or TV request exception when a user's quota is full; optional Slack actions use a mapped account and the same request permissions as the web app. Manager API clients need both user-management and request-management permission to attribute requests to a selected user; request admission and quota checks use that requester. - Movie and TV title cards show standard and 4K availability separately across search, Discover, collections, people, and list views, so a 4K-only copy is visible as 4K. @@ -105,6 +108,7 @@ For local MCP access, see the [SnapeTech MCP integration guide](./docs/integrati - SeerrNG [PR #446](https://github.com/snapetech-org/seerrng/pull/446) proposes bounded, paginated Servarr queue tracking with refresh-completion checks and a per-service Download Queue Size control. It covers 10–10,000 items per service, defaults to 1,000, and keeps recovery on strict complete snapshots. Source context: closed, unmerged Seerr [PR #3473](https://github.com/seerr-team/seerr/pull/3473) and open Seerr [PR #3535](https://github.com/seerr-team/seerr/pull/3535). - Notifications for email, Discord, Slack, Telegram, Gotify, ntfy, Pushover, Pushbullet, Apprise, Web Push, and custom webhooks, with provider-specific poster, priority, sound, and email transport options documented in the [notification guides](./docs/using-seerr/notifications/index.mdx). - Sonarr v5 support alongside v3/v4, including metadata-language and season-order options with explicit season mapping for recovery. Scans account for both TVDB and resolved TMDB identity, distinguish confirmed absence from incomplete or failed checks, and reconcile abandoned processing seasons and request selections only after relevant configured servers finish. +- Optional per-episode file availability from Sonarr, Plex, Jellyfin, and Emby on TV season pages. Badges preserve source and standard/4K distinctions; media-server library episode order must match the selected TV or anime metadata provider. File presence remains separate from per-user playback access. See [individual episode availability](./docs/using-seerr/individual-episode-availability.md). - An optional TV request gate that checks whether the previous regular season was watched through a linked Plex, Jellyfin, or Emby account. - Administrator-managed family controls: separate movie and TV rating limits for each account, plus an optional family age gate with a configurable default that filters Adult, explicit, and mature-tagged titles across supported media categories. - Admin-configured Prowlarr connection, per-indexer diagnostics, category coverage, and format-aware manual search across movies, TV, music, books, comics, magazines, ROMs, and PC games, with title-prefilled search links from media details; approved requests still go through their configured acquisition providers. @@ -172,7 +176,9 @@ For local MCP access, see the [SnapeTech MCP integration guide](./docs/integrati - Movie and Series Subject Tags can be hidden with a browser-saved preference shared across both detail pages. - Authenticated **Download copy** links in Request Status for verified movie, TV, book, comic, magazine, ROM, and PC game files. - Request lifecycle tracking and availability notifications link users back to the matching Request Status item, where available files can be selected and saved. +- Generic webhook notifications support bounded JSON templates, custom headers, and allowlisted lowercase, URL-encoding, and slugification filters. See the [webhook guide](./docs/using-seerr/notifications/webhook.md#json-payload). - Signed-in household members can follow another user's active movie or series request for a one-time availability notice through their own configured notification channels. +- Administrators can opt into a separate **Pending Request Updated** notification when an edit changes a pending request's owner, selected seasons or episodes, or acquisition options. The webhook event is `MEDIA_PENDING_UPDATED`; see the [notification guide](./docs/using-seerr/notifications/index.mdx#pending-request-edits). - Browser, service-worker, API, DNS, avatar, and image-proxy caching tuned for faster refreshes and tab restores. - Removing an item from an acquisition service such as Radarr or Sonarr preserves its SeerrNG media record and request history; Clear Data is a separate, explicitly destructive action. - Server-side Axios requests use a versioned User-Agent; provider-specific values are preserved. See [Network settings](docs/using-seerr/settings/network.md#outbound-request-identity). @@ -200,6 +206,10 @@ Recent repository updates include: confirms the requested media ([Seerr issue #3657](https://github.com/seerr-team/seerr/issues/3657), [PR #3659](https://github.com/seerr-team/seerr/pull/3659)). - **Search matching:** unmatched TMDB queries retry with normalized punctuation, spacing, apostrophes, and diacritics; successful literal-query results retain their order. + rules can also match a movie or series by its TMDB production countries, + with Sonarr language-profile selection on service versions that expose those + profiles. This adapts the use case in Seerr + [issue #3439](https://github.com/seerr-team/seerr/issues/3439). - **User workflows:** local watchlist filters, a browser-saved Subject Tags visibility preference, private one-time availability notices for followed requests, per-user shared-availability display choices, and opt-in @@ -223,6 +233,13 @@ Recent repository updates include: - **TMDB details:** Movie and series detail pages remain usable when optional appended sections such as credits, keywords, content ratings, or provider results are missing from a response. +- **Episode availability:** optional per-episode file indicators from Sonarr + and media-server libraries, with independent source reconciliation and + standard/4K state. Sonarr uses TVDB order; Plex, Jellyfin, and Emby libraries + require an explicit numbering-order choice that matches the active TV or + anime metadata provider. These indicators describe scanned file presence, + not a user's access or ability to play the file. See the + [setup and behavior guide](./docs/using-seerr/individual-episode-availability.md). - **Integrations:** MusicBrainz and Cover Art Archive connectivity checks with bounded artwork traffic controls; outbound proxy routing for Cover Art Archive and Steam library clients; and a preview-first BookshelfNG to @@ -278,6 +295,7 @@ SeerrNG documentation is maintained in the [docs folder](https://github.com/snap - [Filter movie and series Discover results](./docs/using-seerr/movie-series-discovery-filters.md) - [Configure Sonarr v5 and season orders](./docs/using-seerr/settings/services.md) - [Restrict administrator sign-in by client network](./docs/using-seerr/settings/network.md#restrict-administrator-sign-in-by-client-network) +- [Track individual TV episode availability](./docs/using-seerr/individual-episode-availability.md) - [Require previous-season watch progress](./docs/using-seerr/settings/general.md#require-the-previous-season-to-be-watched) - [Choose movie and TV request destinations](./docs/using-seerr/settings/services.md#request-destination-label-optional) - [Filter and sort local watchlists](./docs/using-seerr/plex/watchlist-auto-request.md#find-items-in-your-watchlist) @@ -395,11 +413,11 @@ no advertising SDKs. See the [pricing and monetization decision](./android/MONET The current tested mobile packages are attached to the [SeerrNG mobile prerelease](https://github.com/snapetech-org/seerrng/releases/tag/mobile-v3.63.0-ci.35): -| Package | Download | SHA-256 | -| --- | --- | --- | -| Android APK for direct install (stable project signing key) | [APK](https://github.com/snapetech-org/seerrng/releases/download/mobile-v3.63.0-ci.35/seerrng-v3.63.0-ci.35-android.apk) | [checksum](https://github.com/snapetech-org/seerrng/releases/download/mobile-v3.63.0-ci.35/seerrng-v3.63.0-ci.35-android.sha256) | -| Android App Bundle signed with the upload key | [AAB](https://github.com/snapetech-org/seerrng/releases/download/mobile-v3.63.0-ci.35/seerrng-v3.63.0-ci.35-android.aab) | [checksum](https://github.com/snapetech-org/seerrng/releases/download/mobile-v3.63.0-ci.35/seerrng-v3.63.0-ci.35-android-aab.sha256) | -| iOS Simulator build (not an iPhone/iPad installable IPA) | [Simulator ZIP](https://github.com/snapetech-org/seerrng/releases/download/mobile-v3.63.0-ci.35/seerrng-v3.63.0-ci.20-ios-simulator.zip) | [checksum](https://github.com/snapetech-org/seerrng/releases/download/mobile-v3.63.0-ci.35/seerrng-v3.63.0-ci.20-ios-simulator.sha256) | +| Package | Download | SHA-256 | +| ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| Android APK for direct install (stable project signing key) | [APK](https://github.com/snapetech-org/seerrng/releases/download/mobile-v3.63.0-ci.35/seerrng-v3.63.0-ci.35-android.apk) | [checksum](https://github.com/snapetech-org/seerrng/releases/download/mobile-v3.63.0-ci.35/seerrng-v3.63.0-ci.35-android.sha256) | +| Android App Bundle signed with the upload key | [AAB](https://github.com/snapetech-org/seerrng/releases/download/mobile-v3.63.0-ci.35/seerrng-v3.63.0-ci.35-android.aab) | [checksum](https://github.com/snapetech-org/seerrng/releases/download/mobile-v3.63.0-ci.35/seerrng-v3.63.0-ci.35-android-aab.sha256) | +| iOS Simulator build (not an iPhone/iPad installable IPA) | [Simulator ZIP](https://github.com/snapetech-org/seerrng/releases/download/mobile-v3.63.0-ci.35/seerrng-v3.63.0-ci.20-ios-simulator.zip) | [checksum](https://github.com/snapetech-org/seerrng/releases/download/mobile-v3.63.0-ci.35/seerrng-v3.63.0-ci.20-ios-simulator.sha256) | The GitHub Android packages have Play Billing disabled, so they remain unlimited evaluation builds; the 20-session cap and lifetime purchase UI are only enabled in a configured Play build. These are prerelease test builds, not store-approved releases. See the [mobile release readiness guide](./docs/mobile-release-readiness.md) for @@ -535,11 +553,11 @@ systemd service, metadata configuration, and SeerrNG connection. Hardcover metadata modes are: -| Mode | Path | Local proxy | Best for | -| --- | --- | --- | --- | +| Mode | Path | Local proxy | Best for | +| ------------------------------------------------------ | ----------------------------------------- | ------------------- | --------------------------------------------------------------------------- | | `compatibility` (default for fresh Hardcover installs) | BookshelfNG → rreading-glasses → upstream | On, with PostgreSQL | A durable shared cache, centralized throttling, or a compatibility boundary | -| `native` (explicit opt-in) | BookshelfNG → Hardcover GraphQL | Off | The simplest direct Hardcover deployment | -| `hosted` | BookshelfNG → `METADATA_URL` | Off | A hosted compatibility endpoint without local state | +| `native` (explicit opt-in) | BookshelfNG → Hardcover GraphQL | Off | The simplest direct Hardcover deployment | +| `hosted` | BookshelfNG → `METADATA_URL` | Off | A hosted compatibility endpoint without local state | Compatibility mode is the installer default because it keeps BookshelfNG decoupled from Hardcover's GraphQL API and centralizes authentication, caching, @@ -754,35 +772,35 @@ full layered chain. Common runtime variables: -| Variable | Purpose | -| --- | --- | -| `PORT` | HTTP port. Defaults to `5055`. | -| `LOG_LEVEL` | Server log level. | -| `NO_COLOR` | Set to a non-empty value to disable ANSI colors in console logs, unless `FORCE_COLOR` is non-empty. | -| `FORCE_COLOR` | A non-empty value overrides terminal detection and `NO_COLOR`; `0` or `false` disables console colors, and any other value enables them. | -| `TERM` | The terminal type; `dumb` disables console colors unless `FORCE_COLOR` is non-empty. | -| `CONFIG_DIRECTORY` | Alternate config directory for non-container installs. | -| `TMDB_API_KEY` | Optional TMDB v3 API key override. SeerrNG uses its bundled application key when this is unset. | -| `TMDB_READ_ACCESS_TOKEN` | Optional TMDB v4 bearer-token override. When set, it takes precedence over `TMDB_API_KEY`. | -| `SEARCH_CREDIT_CONCURRENCY` | Maximum concurrent TMDB credit lookups per server process during movie/TV searches; defaults to `10` and is capped at `40`. | -| `METRICS_ENABLED` | Enables the Prometheus `/metrics` endpoint when set to `true`. | -| `METRICS_AUTH_TOKEN` | Long random bearer token required by `/metrics` when metrics are enabled. | -| `OIDC_ALLOW_PRIVATE_ADDRESSES` | Allows server-side OIDC requests to private network addresses. Required only for an intentionally internal identity provider. | -| `OIDC_ALLOW_INSECURE` | Allows non-HTTPS OIDC provider requests. | -| `SEERR_EXTERNAL_READ_ONLY` | Blocks mutating requests to external automation APIs when enabled. Useful for test/lab environments. Production refuses to start with this enabled unless explicitly allowed. | -| `SEERR_ALLOW_PRODUCTION_EXTERNAL_READ_ONLY` | Allows `SEERR_EXTERNAL_READ_ONLY` in production for an intentional read-only clone. Do not set this on the writable request.snape.tech deployment. | -| `SEERR_REQUIRE_PUBLIC_SETUP_HOSTS` | Rejects private/LAN Jellyfin or Emby hostnames during the first-run setup wizard. Disabled by default because nearly all self-hosted media servers are on a LAN; see [Network settings](docs/using-seerr/settings/network.md). | -| `SEERR_ALLOW_PRIVATE_NOTIFICATION_URLS` | Allows Discord/Slack/webhook/ntfy/Gotify notification URLs to target private/internal addresses. Needed only if your notification receiver also runs on your LAN. Disabled by default. | -| `SEERR_ALLOW_PRIVATE_PUSH_ENDPOINTS` | Allows web push subscription endpoints to target private/internal addresses. Disabled by default; the browser push service is normally public. | -| `SEERR_TLS_MODE` | Explicit environment override selecting `disabled` (default), `self-signed`, or `provided` for direct HTTPS. Self-signed/provided modes serve HTTPS on `SEERR_HTTPS_PORT`; HTTP redirects only when the redirect setting is enabled. See [Built-in HTTPS](docs/using-seerr/advanced/built-in-tls.mdx). | -| `SEERR_HTTPS_PORT` | HTTPS listener port when `SEERR_TLS_MODE` is `self-signed` or `provided`. Defaults to `5056` and must differ from `PORT`. | -| `SEERR_TLS_HOSTS` | Comma-separated DNS names/IP addresses included in generated self-signed certificates and accepted for HTTP-to-HTTPS redirects. Defaults to `localhost,127.0.0.1,::1`. | -| `SEERR_TLS_CERT_FILE` / `SEERR_TLS_KEY_FILE` | PEM certificate and matching private key used when `SEERR_TLS_MODE=provided`. The certificate must include DNS/IP subject alternative names. | -| `SEERR_TLS_CA_FILE` | Optional PEM CA bundle passed to the Node TLS context in `provided` mode; serve intermediates in the certificate file itself. | -| `SEERR_HTTP_REDIRECT_TO_HTTPS` | Environment override for the saved HTTP behavior when built-in TLS is enabled. Set `true` for 308 redirects; set `false` to keep an HTTP upgrade/recovery response while HTTPS is verified. | -| `SEERR_ALLOW_HTTP_AUTH` | Explicitly permits browser sessions over direct HTTP when `SEERR_TLS_MODE=disabled`. Disabled by default; mutually exclusive with TLS and warns about session-cookie interception. | -| `SEERR_SKIP_DB_MIGRATIONS` | Skips automatically running database migrations at startup in production. Only relevant when migrations are run out-of-band (e.g. `pnpm migration:run`, or a prepared Cypress test database). | -| `JELLYFIN_TYPE` | One-time settings-migration hint. Set to `emby` before the first start after upgrading if your existing configuration was saved as `Jellyfin` but the server is actually Emby; relabels the stored media server type and can be unset afterward. | +| Variable | Purpose | +| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `PORT` | HTTP port. Defaults to `5055`. | +| `LOG_LEVEL` | Server log level. | +| `NO_COLOR` | Set to a non-empty value to disable ANSI colors in console logs, unless `FORCE_COLOR` is non-empty. | +| `FORCE_COLOR` | A non-empty value overrides terminal detection and `NO_COLOR`; `0` or `false` disables console colors, and any other value enables them. | +| `TERM` | The terminal type; `dumb` disables console colors unless `FORCE_COLOR` is non-empty. | +| `CONFIG_DIRECTORY` | Alternate config directory for non-container installs. | +| `TMDB_API_KEY` | Optional TMDB v3 API key override. SeerrNG uses its bundled application key when this is unset. | +| `TMDB_READ_ACCESS_TOKEN` | Optional TMDB v4 bearer-token override. When set, it takes precedence over `TMDB_API_KEY`. | +| `SEARCH_CREDIT_CONCURRENCY` | Maximum concurrent TMDB credit lookups per server process during movie/TV searches; defaults to `10` and is capped at `40`. | +| `METRICS_ENABLED` | Enables the Prometheus `/metrics` endpoint when set to `true`. | +| `METRICS_AUTH_TOKEN` | Long random bearer token required by `/metrics` when metrics are enabled. | +| `OIDC_ALLOW_PRIVATE_ADDRESSES` | Allows server-side OIDC requests to private network addresses. Required only for an intentionally internal identity provider. | +| `OIDC_ALLOW_INSECURE` | Allows non-HTTPS OIDC provider requests. | +| `SEERR_EXTERNAL_READ_ONLY` | Blocks mutating requests to external automation APIs when enabled. Useful for test/lab environments. Production refuses to start with this enabled unless explicitly allowed. | +| `SEERR_ALLOW_PRODUCTION_EXTERNAL_READ_ONLY` | Allows `SEERR_EXTERNAL_READ_ONLY` in production for an intentional read-only clone. Do not set this on the writable request.snape.tech deployment. | +| `SEERR_REQUIRE_PUBLIC_SETUP_HOSTS` | Rejects private/LAN Jellyfin or Emby hostnames during the first-run setup wizard. Disabled by default because nearly all self-hosted media servers are on a LAN; see [Network settings](docs/using-seerr/settings/network.md). | +| `SEERR_ALLOW_PRIVATE_NOTIFICATION_URLS` | Allows Discord/Slack/webhook/ntfy/Gotify notification URLs to target private/internal addresses. Needed only if your notification receiver also runs on your LAN. Disabled by default. | +| `SEERR_ALLOW_PRIVATE_PUSH_ENDPOINTS` | Allows web push subscription endpoints to target private/internal addresses. Disabled by default; the browser push service is normally public. | +| `SEERR_TLS_MODE` | Explicit environment override selecting `disabled` (default), `self-signed`, or `provided` for direct HTTPS. Self-signed/provided modes serve HTTPS on `SEERR_HTTPS_PORT`; HTTP redirects only when the redirect setting is enabled. See [Built-in HTTPS](docs/using-seerr/advanced/built-in-tls.mdx). | +| `SEERR_HTTPS_PORT` | HTTPS listener port when `SEERR_TLS_MODE` is `self-signed` or `provided`. Defaults to `5056` and must differ from `PORT`. | +| `SEERR_TLS_HOSTS` | Comma-separated DNS names/IP addresses included in generated self-signed certificates and accepted for HTTP-to-HTTPS redirects. Defaults to `localhost,127.0.0.1,::1`. | +| `SEERR_TLS_CERT_FILE` / `SEERR_TLS_KEY_FILE` | PEM certificate and matching private key used when `SEERR_TLS_MODE=provided`. The certificate must include DNS/IP subject alternative names. | +| `SEERR_TLS_CA_FILE` | Optional PEM CA bundle passed to the Node TLS context in `provided` mode; serve intermediates in the certificate file itself. | +| `SEERR_HTTP_REDIRECT_TO_HTTPS` | Environment override for the saved HTTP behavior when built-in TLS is enabled. Set `true` for 308 redirects; set `false` to keep an HTTP upgrade/recovery response while HTTPS is verified. | +| `SEERR_ALLOW_HTTP_AUTH` | Explicitly permits browser sessions over direct HTTP when `SEERR_TLS_MODE=disabled`. Disabled by default; mutually exclusive with TLS and warns about session-cookie interception. | +| `SEERR_SKIP_DB_MIGRATIONS` | Skips automatically running database migrations at startup in production. Only relevant when migrations are run out-of-band (e.g. `pnpm migration:run`, or a prepared Cypress test database). | +| `JELLYFIN_TYPE` | One-time settings-migration hint. Set to `emby` before the first start after upgrading if your existing configuration was saved as `Jellyfin` but the server is actually Emby; relabels the stored media server type and can be unset afterward. | ### First-run browser transport @@ -804,37 +822,37 @@ Use deployment secrets, `.env` files, or container environment variables. Do not Bookshelf deployment and migration variables live on the helper scripts rather than the SeerrNG runtime container. Common ones include: -| Variable | Purpose | -| --- | --- | -| `BOOKSHELF_BACKEND` | `auto`, `hardcover`, or `softcover`. | -| `BOOKSHELF_IMAGE` | Override the Bookshelf image. Hardcover mode uses the stable Snapetech `main` release tag by default; use a digest to pin it. | -| `BOOKSHELF_METADATA_MODE` | `compatibility` (default for fresh Hardcover), `native`, or `hosted`. | -| `BOOKSHELF_METADATA_URL` | Compatibility or hosted metadata URL. Native Hardcover uses it only when native mode is disabled. | -| `BOOKSHELF_HARDCOVER_NATIVE` | Rendered Bookshelf flag; the installer sets it from `BOOKSHELF_METADATA_MODE`. | -| `BOOKSHELF_HARDCOVER_AUTH` | Native-mode token passed to BookshelfNG; compatibility mode passes `HARDCOVER_AUTH` to rreading-glasses instead. | -| `BOOKSHELF_HARDCOVER_API_URL` | Optional native Hardcover GraphQL base URL. Defaults to `https://api.hardcover.app`. | -| `BOOKSHELF_METADATA_SOURCES` | Legacy shared runtime override. When supplied to the installer it applies to both services; otherwise the per-service values take precedence. | -| `BOOKSHELF_EBOOKS_METADATA_SOURCES` | Ebook source list; defaults to `gutendex,googlebooks,europeana`. Google Books and Europeana run only when their keys are configured. | -| `BOOKSHELF_AUDIOBOOKS_METADATA_SOURCES` | Audiobook source list; defaults to `loc,gutendex,googlebooks,europeana`. Google Books and Europeana run only when their keys are configured. | -| `GOOGLE_BOOKS_API_KEY` | Optional Google Books runtime/migration key; Google Books is skipped without it. | -| `EUROPEANA_API_KEY` | Optional Europeana runtime key; a free registered key is required, and runtime search uses openly reusable text records. | -| `HARDCOVER_APIFY_GOODREADS_ACTOR` / `HARDCOVER_APIFY_TOKEN` | Optional runtime/migration Goodreads-compatible Actor; usage may be metered. | -| `HARDCOVER_APIFY_GOODREADS_INPUT_TEMPLATE` | Optional Apify Actor JSON input template containing `{{query}}`. | -| `HARDCOVER_AUTH` | Hardcover API token. The installer passes it to native BookshelfNG by default, or to rreading-glasses in compatibility mode; include the `Bearer ` prefix. | -| `COOKIE` | Optional Goodreads cookie for softcover mode. | -| `BOOKSHELF_EBOOKS_CONFIG_DIR` | Ebook Bookshelf/Readarr config directory. | -| `BOOKSHELF_AUDIOBOOKS_CONFIG_DIR` | Audiobook Bookshelf/Readarr config directory. | -| `HARDCOVER_EBOOK_API_KEY` / `HARDCOVER_AUDIOBOOK_API_KEY` | API keys for target Hardcover Bookshelf instances. | -| `HARDCOVER_SOFTCOVER_EBOOK_BASE_URL` / `HARDCOVER_SOFTCOVER_AUDIOBOOK_BASE_URL` | Optional softcover recovery endpoints. | -| `HARDCOVER_OPENLIBRARY_RECOVERY` | Enables OpenLibrary-assisted native Hardcover remapping. Defaults to `true`. | -| `HARDCOVER_GOOGLEBOOKS_RECOVERY` | Enables Google Books recovery for migration/reconciliation. Defaults to `true`; `GOOGLE_BOOKS_API_KEY` is required by Google's public API. | -| `HARDCOVER_LOC_RECOVERY` | Enables Library of Congress catalog recovery for migration/reconciliation. Defaults to `true`. | -| `HARDCOVER_APIFY_GOODREADS_ACTOR` / `HARDCOVER_APIFY_TOKEN` | Optional Apify Actor adapter for Goodreads-compatible recovery. Actor runs may be metered; set a JSON `HARDCOVER_APIFY_GOODREADS_INPUT_TEMPLATE` containing `{{query}}` when the Actor uses a different input schema. | -| `HARDCOVER_APIFY_API_BASE_URL` | Apify API base URL; defaults to `https://api.apify.com`. | -| `HARDCOVER_GOOGLEBOOKS_BASE_URL` / `HARDCOVER_LOC_BASE_URL` | Override provider API bases for controlled deployments and tests. | -| `HARDCOVER_LOCAL_DB_IMPORT` | Enables deterministic local DB fallback after API and softcover recovery fail. | -| `HARDCOVER_MATCH_CONCURRENCY` | Match report lookup concurrency. | -| `HARDCOVER_API_TIMEOUT_MS` | Target API timeout for migration requests. | +| Variable | Purpose | +| ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `BOOKSHELF_BACKEND` | `auto`, `hardcover`, or `softcover`. | +| `BOOKSHELF_IMAGE` | Override the Bookshelf image. Hardcover mode uses the stable Snapetech `main` release tag by default; use a digest to pin it. | +| `BOOKSHELF_METADATA_MODE` | `compatibility` (default for fresh Hardcover), `native`, or `hosted`. | +| `BOOKSHELF_METADATA_URL` | Compatibility or hosted metadata URL. Native Hardcover uses it only when native mode is disabled. | +| `BOOKSHELF_HARDCOVER_NATIVE` | Rendered Bookshelf flag; the installer sets it from `BOOKSHELF_METADATA_MODE`. | +| `BOOKSHELF_HARDCOVER_AUTH` | Native-mode token passed to BookshelfNG; compatibility mode passes `HARDCOVER_AUTH` to rreading-glasses instead. | +| `BOOKSHELF_HARDCOVER_API_URL` | Optional native Hardcover GraphQL base URL. Defaults to `https://api.hardcover.app`. | +| `BOOKSHELF_METADATA_SOURCES` | Legacy shared runtime override. When supplied to the installer it applies to both services; otherwise the per-service values take precedence. | +| `BOOKSHELF_EBOOKS_METADATA_SOURCES` | Ebook source list; defaults to `gutendex,googlebooks,europeana`. Google Books and Europeana run only when their keys are configured. | +| `BOOKSHELF_AUDIOBOOKS_METADATA_SOURCES` | Audiobook source list; defaults to `loc,gutendex,googlebooks,europeana`. Google Books and Europeana run only when their keys are configured. | +| `GOOGLE_BOOKS_API_KEY` | Optional Google Books runtime/migration key; Google Books is skipped without it. | +| `EUROPEANA_API_KEY` | Optional Europeana runtime key; a free registered key is required, and runtime search uses openly reusable text records. | +| `HARDCOVER_APIFY_GOODREADS_ACTOR` / `HARDCOVER_APIFY_TOKEN` | Optional runtime/migration Goodreads-compatible Actor; usage may be metered. | +| `HARDCOVER_APIFY_GOODREADS_INPUT_TEMPLATE` | Optional Apify Actor JSON input template containing `{{query}}`. | +| `HARDCOVER_AUTH` | Hardcover API token. The installer passes it to native BookshelfNG by default, or to rreading-glasses in compatibility mode; include the `Bearer ` prefix. | +| `COOKIE` | Optional Goodreads cookie for softcover mode. | +| `BOOKSHELF_EBOOKS_CONFIG_DIR` | Ebook Bookshelf/Readarr config directory. | +| `BOOKSHELF_AUDIOBOOKS_CONFIG_DIR` | Audiobook Bookshelf/Readarr config directory. | +| `HARDCOVER_EBOOK_API_KEY` / `HARDCOVER_AUDIOBOOK_API_KEY` | API keys for target Hardcover Bookshelf instances. | +| `HARDCOVER_SOFTCOVER_EBOOK_BASE_URL` / `HARDCOVER_SOFTCOVER_AUDIOBOOK_BASE_URL` | Optional softcover recovery endpoints. | +| `HARDCOVER_OPENLIBRARY_RECOVERY` | Enables OpenLibrary-assisted native Hardcover remapping. Defaults to `true`. | +| `HARDCOVER_GOOGLEBOOKS_RECOVERY` | Enables Google Books recovery for migration/reconciliation. Defaults to `true`; `GOOGLE_BOOKS_API_KEY` is required by Google's public API. | +| `HARDCOVER_LOC_RECOVERY` | Enables Library of Congress catalog recovery for migration/reconciliation. Defaults to `true`. | +| `HARDCOVER_APIFY_GOODREADS_ACTOR` / `HARDCOVER_APIFY_TOKEN` | Optional Apify Actor adapter for Goodreads-compatible recovery. Actor runs may be metered; set a JSON `HARDCOVER_APIFY_GOODREADS_INPUT_TEMPLATE` containing `{{query}}` when the Actor uses a different input schema. | +| `HARDCOVER_APIFY_API_BASE_URL` | Apify API base URL; defaults to `https://api.apify.com`. | +| `HARDCOVER_GOOGLEBOOKS_BASE_URL` / `HARDCOVER_LOC_BASE_URL` | Override provider API bases for controlled deployments and tests. | +| `HARDCOVER_LOCAL_DB_IMPORT` | Enables deterministic local DB fallback after API and softcover recovery fail. | +| `HARDCOVER_MATCH_CONCURRENCY` | Match report lookup concurrency. | +| `HARDCOVER_API_TIMEOUT_MS` | Target API timeout for migration requests. | ### Cypress Runtime Config @@ -960,3 +978,13 @@ SeerrNG builds on Seerr, Jellyseerr, and Overseerr. Inherited code, documentatio ## Local security scanning Run `./scripts/security-scan-local.sh` for local Semgrep CE and the Trivy scanners that fit this repository. The installed pre-commit hook scans the staged source/config snapshot after linting; Trivy runs on demand or in CI. This public repository also runs Semgrep CE and Trivy in GitHub Actions on main changes, pull requests, and weekly. Semgrep reports are retained as run artifacts for triage. See [security-scanning.md](docs/security-scanning.md). Use `./scripts/update-security-tools.sh` to refresh local scanner data and the Trivy database. + +## Make the interface your own + +Choose SeerrOrig, SeerrNGJ or PersiusNG in the theme picker, or install a community +`.seerrtheme` package. Every theme owns its stylesheet and runs inside SeerrNG; +a UI-rewriting proxy is not required. + +[Create and package a theme](docs/interface-themes/authoring.md) · +[Submit a community theme](docs/interface-themes/submitting.md) · +[PersiusNG design and validation](docs/interface-themes/persiusng.md) diff --git a/bin/check-current-batch-contract-lib.js b/bin/check-current-batch-contract-lib.js index 60eb744872..a2ef3634cf 100644 --- a/bin/check-current-batch-contract-lib.js +++ b/bin/check-current-batch-contract-lib.js @@ -493,12 +493,21 @@ const validateRequestMediaArtwork = ( const validateTvRequestCanvas = (source, stylesheet, inset) => { try { const jsx = parsedJsx(source); + const retainsCanvas = (value) => { + if (!value) return false; + if (jsx.ts.isParenthesizedExpression(value)) + return retainsCanvas(value.expression); + if (jsx.ts.isConditionalExpression(value)) + return retainsCanvas(value.whenTrue) && retainsCanvas(value.whenFalse); + return ( + jsx.ts.isStringLiteral(value) && + value.text.split(/\s+/).includes('request-modal-site-surface') + ); + }; const modal = jsx.elements.find( (node) => jsx.tag(node) === 'Modal' && - (jsx.text(node, 'dialogClass') ?? '') - .split(/\s+/) - .includes('request-modal-site-surface') + retainsCanvas(jsx.expression(node, 'dialogClass')) ); const shell = jsx.elements.find( (node) => @@ -549,7 +558,13 @@ const validateTreeEligibility = (source, aspect) => { const row = elements.find( (node) => tag(node) === 'button' && - text(node, 'data-tree-part') === 'episode-selection' + text(node, 'data-tree-part') === 'episode-control' && + elements.some( + (owner) => + tag(owner) === 'span' && + text(owner, 'data-tree-part') === 'episode-selection' && + jsx.within(node, owner) + ) ); return ( row && @@ -1604,13 +1619,25 @@ const validateCurrentBatchContract = (files) => { fileName !== 'src/components/RequestModal/AdvancedRequester/index.tsx' ); for (const fileName of visibleTerminologyFiles) { - const sourceWithoutServiceNames = requireFile(fileName).replaceAll( + let sourceWithoutServiceNames = requireFile(fileName).replaceAll( 'Bookshelf-Ebook', '' ); + // The opt-in Persius book-format label follows the approved mockup. + // Other labels, including unrelated strings in this module, stay checked. + if (fileName === 'src/components/Persius/messages.ts') + sourceWithoutServiceNames = sourceWithoutServiceNames.replace( + /\bebooks:\s*'Ebooks'/, + "ebooks: 'Books'" + ); + if (fileName === 'src/i18n/locale/en.json') + sourceWithoutServiceNames = sourceWithoutServiceNames.replace( + /"components\.Persius\.ebooks":\s*"Ebooks"/, + '"components.Persius.ebooks": "Books"' + ); if (/\bEbooks?\b/.test(sourceWithoutServiceNames)) { errors.push( - `${fileName}: user-visible Ebook terminology must be Book; configured service names are the only exception` + `${fileName}: user-visible Ebook terminology must be Book outside configured service names and the approved Persius format label` ); } } @@ -2766,11 +2793,13 @@ const validateCurrentBatchContract = (files) => { 'next build --webpack', 'the public client build must retain the upstream Next compiler' ); - requirePublicCommand( - 'build:server', - 'tsc --project server/tsconfig.json && node scripts/copy-server-assets.mjs && node scripts/replace-server-import-aliases.mjs dist', - 'the public server build must retain upstream compilation, resources and alias resolution' - ); + for (const name of ['build:server', 'build:server:compile']) { + requirePublicCommand( + name, + 'tsc --project server/tsconfig.json && node scripts/copy-server-assets.mjs && node scripts/replace-server-import-aliases.mjs dist', + 'the public server build must retain upstream compilation, resources and alias resolution, including packaged interface themes' + ); + } requirePublicCommand( 'prebuild', 'pnpm i18n:check && pnpm current-batch:check', @@ -3487,6 +3516,16 @@ const validateCurrentBatchContract = (files) => { '--interface-compact-control-height: 1.5rem;', 'SeerrNGJ must retain its 24-pixel compact-control height' ); + for (const [theme, height] of [ + ['seerrOrig', '1.25rem'], + ['seerrNGJ', '1.5rem'], + ]) { + requireText( + `themes/${theme}/theme.css`, + `--interface-compact-control-height: ${height};`, + 'built-in themes must preserve their accepted compact input height' + ); + } requireText( globals, '.compact-control {\n height: var(--compact-control-height);', diff --git a/bin/check-current-batch-contract-lib.test.mjs b/bin/check-current-batch-contract-lib.test.mjs index 1b2cc89c67..0196d41ea8 100644 --- a/bin/check-current-batch-contract-lib.test.mjs +++ b/bin/check-current-batch-contract-lib.test.mjs @@ -710,8 +710,8 @@ test('semantic request JSX rejects lost owners, eligibility overrides, and count ], [ 'src/components/RequestModal/TvRequestModal.tsx', - 'dialogClass="request-modal-site-surface"', - 'dialogClass="legacy-canvas"', + "'request-modal-site-surface persius-season-modal'", + "'persius-season-modal'", 'Series new and pending requests must use the same site canvas', ], [ @@ -744,6 +744,24 @@ test('semantic request JSX rejects lost owners, eligibility overrides, and count 'className="retired-scrim"', 'request artwork must use the shared scrim', ], + [ + 'src/components/MediaDetails/SeasonEpisodeTree.tsx', + 'data-tree-part="episode-control"', + 'data-tree-part="unused-control"', + 'ineligible episodes must remain visible but cannot be selected', + ], + [ + 'src/components/MediaDetails/SeasonEpisodeTree.tsx', + 'data-tree-part="episode-selection"', + 'data-tree-part="unused-selection"', + 'ineligible episodes must remain visible but cannot be selected', + ], + [ + 'src/components/MediaDetails/SeasonEpisodeTree.tsx', + 'disabled={disabled || !isTreeEpisodeSelectable(episode)}', + 'disabled={disabled}', + 'ineligible episodes must remain visible but cannot be selected', + ], [ 'src/components/MediaDetails/SeasonEpisodeTree.tsx', 'episode.selectable ?? episode.available', @@ -1675,6 +1693,34 @@ test('compact Request geometry checker accepts the shared owner and rejects regr ); }); +test('compact-control heights are owned by the selected interface theme', () => { + const cases = [ + { + file: 'themes/seerrOrig/theme.css', + value: '--interface-compact-control-height: 1.25rem;', + replacement: '--interface-compact-control-height: 1rem;', + reason: 'SeerrOrig must retain its 20-pixel compact-control height', + }, + { + file: 'themes/seerrNGJ/theme.css', + value: '--interface-compact-control-height: 1.5rem;', + replacement: '--interface-compact-control-height: 1.25rem;', + reason: 'SeerrNGJ must retain its 24-pixel compact-control height', + }, + ]; + + for (const { file, value, replacement, reason } of cases) { + const source = repositoryFilesWith()[file]; + assert.ok(source.includes(value), `${file} has its package-owned value`); + assert.ok( + validateCurrentBatchContract( + repositoryFilesWith({ [file]: source.replace(value, replacement) }) + ).some((error) => error.includes(reason)), + `${file} rejects a missing theme-specific control height` + ); + } +}); + test('request dropdown portal stacking accepts native CSS and rejects lower or lost owners', () => { const cssFile = 'src/styles/globals.css'; const source = repositoryFilesWith()[cssFile]; @@ -2039,3 +2085,93 @@ test('music and legacy request filters retain rendered control order and current 'retired utility style is not the current filter owner' ); }); + +test('conditional request layouts retain the shared canvas in every branch', () => { + const file = 'src/components/RequestModal/TvRequestModal.tsx'; + const source = repositoryFilesWith()[file]; + const passes = (candidate) => + !validateCurrentBatchContract( + repositoryFilesWith({ [file]: candidate }) + ).some((error) => error.includes('must use the same site canvas')); + assert.equal(passes(source), true); + assert.equal( + passes( + source.replace( + "'request-modal-site-surface persius-season-modal'", + "'persius-season-modal'" + ) + ), + false + ); + assert.equal( + passes( + source.replace(": 'request-modal-site-surface'", ": 'legacy-canvas'") + ), + false + ); +}); + +test('server builds retain packaged themes and fail closed when resources are omitted', () => { + const source = JSON.parse(repositoryFilesWith()['package.json']); + const themeCopy = 'node scripts/copy-server-assets.mjs'; + for (const name of ['build:server', 'build:server:compile']) { + assert.ok(source.scripts[name].includes(themeCopy)); + const changed = structuredClone(source); + changed.scripts[name] = changed.scripts[name].replace( + themeCopy + ' && ', + '' + ); + assert.ok( + validateCurrentBatchContract( + repositoryFilesWith({ 'package.json': JSON.stringify(changed) }) + ).some((error) => error.includes('including packaged interface themes')) + ); + } +}); + +test('Persius format terminology does not exempt unrelated user-facing labels', () => { + const file = 'src/components/Persius/messages.ts'; + const source = repositoryFilesWith()[file]; + const reason = 'user-visible Ebook terminology'; + assert.equal( + validateCurrentBatchContract(repositoryFilesWith({ [file]: source })).some( + (error) => error.includes(reason) + ), + false + ); + assert.ok( + validateCurrentBatchContract( + repositoryFilesWith({ + [file]: source.replace("books: 'Books'", "books: 'Ebooks'"), + }) + ).some((error) => error.includes(reason)) + ); +}); + +test('compact inputs consume theme tokens and retain both built-in sizes', () => { + const shared = 'src/styles/interfaceThemes/shared.css'; + const source = repositoryFilesWith()[shared]; + assert.ok( + validateCurrentBatchContract( + repositoryFilesWith({ + [shared]: source.replace( + '--compact-control-height: var(--interface-compact-control-height);', + '--compact-control-height: 2rem;' + ), + }) + ).some((error) => error.includes('selected theme height')) + ); + for (const theme of ['seerrOrig', 'seerrNGJ']) { + const file = `themes/${theme}/theme.css`; + assert.ok( + validateCurrentBatchContract( + repositoryFilesWith({ + [file]: repositoryFilesWith()[file].replace( + /--interface-compact-control-height:\s*[^;]+;/, + '--interface-compact-control-height: 2rem;' + ), + }) + ).some((error) => error.includes('accepted compact input height')) + ); + } +}); diff --git a/bin/check-current-batch-contract.js b/bin/check-current-batch-contract.js index b96e7bf418..592b8517d3 100644 --- a/bin/check-current-batch-contract.js +++ b/bin/check-current-batch-contract.js @@ -38,6 +38,8 @@ const fileNames = [ 'seerr-api.yml', 'src/styles/globals.css', 'src/styles/interfaceThemes/shared.css', + 'themes/seerrOrig/theme.css', + 'themes/seerrNGJ/theme.css', 'src/styles/visual-lab.css', 'public/visual-lab/visual-lab.css', 'themes/seerrOrig/theme.css', diff --git a/bin/e2e-network-guard.cjs b/bin/e2e-network-guard.cjs new file mode 100644 index 0000000000..87bd707891 --- /dev/null +++ b/bin/e2e-network-guard.cjs @@ -0,0 +1,78 @@ +// Optional browser-test boundary. Loaded before the application, never by a +// normal production start. Provider reads must be deterministic browser fixtures. +const net = require('node:net'); +const connect = net.Socket.prototype.connect; + +const assertLoopback = (host) => { + if (!['localhost', '127.0.0.1', '::1', '[::1]'].includes(host)) { + const error = new Error( + 'Offline E2E tests cannot contact external services.' + ); + error.code = 'E2E_EXTERNAL_NETWORK_BLOCKED'; + throw error; + } +}; + +const assertRequest = (input) => { + if (typeof input === 'string' || input instanceof URL) { + assertLoopback(new URL(input).hostname); + } else if (input?.url) { + assertLoopback(new URL(input.url).hostname); + } else { + assertLoopback(input?.hostname ?? input?.host ?? 'localhost'); + } +}; + +// Check the original destination before an environment proxy can translate it +// to a local transport. Socket checks alone cannot see that original authority. +for (const name of ['node:http', 'node:https']) { + const client = require(name); + for (const method of ['request', 'get']) { + const original = client[method]; + client[method] = function (...args) { + assertRequest(args[0]); + if (args[1] && typeof args[1] === 'object') assertRequest(args[1]); + return original.apply(this, args); + }; + } +} +require('node:module').syncBuiltinESMExports(); +const originalFetch = globalThis.fetch; +globalThis.fetch = async function (...args) { + assertRequest(args[0]); + return originalFetch.apply(this, args); +}; +const undici = require('undici'); +for (const method of [ + 'fetch', + 'request', + 'stream', + 'pipeline', + 'connect', + 'upgrade', +]) { + const original = undici[method]; + undici[method] = function (...args) { + assertRequest(args[0]); + return original.apply(this, args); + }; +} + +net.Socket.prototype.connect = function (...input) { + let args = input; + while (Array.isArray(args[0])) args = args[0]; + const options = args[0]; + const unixSocket = + (typeof options === 'object' && options?.path) || + (typeof options === 'string' && !/^\d+$/.test(options)); + if (!unixSocket) { + const host = + typeof options === 'object' + ? (options?.host ?? 'localhost') + : typeof args[1] === 'string' + ? args[1] + : 'localhost'; + assertLoopback(host); + } + return connect.apply(this, input); +}; diff --git a/bin/e2e-network-guard.test.mjs b/bin/e2e-network-guard.test.mjs new file mode 100644 index 0000000000..ed3482ea1c --- /dev/null +++ b/bin/e2e-network-guard.test.mjs @@ -0,0 +1,43 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { test } from 'node:test'; +import { fileURLToPath } from 'node:url'; + +test('offline browser server permits loopback and rejects external socket forms before connecting', () => { + const guard = fileURLToPath( + new URL('./e2e-network-guard.cjs', import.meta.url) + ); + const result = spawnSync( + process.execPath, + [ + '--require', + guard, + '-e', + ` + const assert = require('node:assert/strict'); + const net = require('node:net'); + for (const args of [ + [{host: 'example.invalid', port: 443}], + [443, 'example.invalid'], + [{host: '192.0.2.1', port: 443}], + ]) { + assert.throws(() => net.connect(...args), {code: 'E2E_EXTERNAL_NETWORK_BLOCKED'}); + } + assert.throws(() => require('node:https').get('https://example.invalid'), {code: 'E2E_EXTERNAL_NETWORK_BLOCKED'}); + assert.throws(() => require('undici').request('https://example.invalid'), {code: 'E2E_EXTERNAL_NETWORK_BLOCKED'}); + fetch('https://example.invalid').then( + () => { throw new Error('External fetch must be rejected'); }, + error => assert.equal(error.code, 'E2E_EXTERNAL_NETWORK_BLOCKED') + ); + const server = net.createServer(socket => socket.end()); + server.listen(0, '127.0.0.1', () => { + const socket = net.connect({host: '127.0.0.1', port: server.address().port}); + socket.on('connect', () => { socket.destroy(); server.close(); }); + socket.on('error', error => { throw error; }); + }); + `, + ], + { encoding: 'utf8', timeout: 10000 } + ); + assert.equal(result.status, 0, result.stderr); +}); diff --git a/bin/interface-theme-postgres-migration.test.mjs b/bin/interface-theme-postgres-migration.test.mjs index ed4c828fbf..c6b4c64583 100644 --- a/bin/interface-theme-postgres-migration.test.mjs +++ b/bin/interface-theme-postgres-migration.test.mjs @@ -3,12 +3,13 @@ import { randomUUID } from 'node:crypto'; import { test } from 'node:test'; import { DataSource } from 'typeorm'; import { AddUserInterfaceTheme1792700000000 } from '../server/migration/postgres/1792700000000-AddUserInterfaceTheme.ts'; +import { RequestFutureSeasons1793400000000 } from '../server/migration/postgres/1793400000000-RequestFutureSeasons.ts'; const postgresUrl = process.env.SEERR_MIGRATION_TEST_POSTGRES_URL; const postgresTest = postgresUrl ? test : test.skip; postgresTest( - 'PostgreSQL interface-theme migration executes, preserves John, and rolls back', + 'PostgreSQL theme and future-season migrations preserve existing values and roll back', async () => { const schema = `seerrng_interface_theme_${randomUUID().replaceAll('-', '')}`; const admin = await new DataSource({ @@ -54,6 +55,35 @@ postgresTest( await queryRunner.hasColumn('user_settings', 'interfaceTheme'), false ); + + await queryRunner.query( + 'CREATE TABLE "media_request" ("id" integer PRIMARY KEY)' + ); + await queryRunner.query( + 'INSERT INTO "media_request" ("id") VALUES (1)' + ); + const futureSeasons = new RequestFutureSeasons1793400000000(); + await futureSeasons.up(queryRunner); + await futureSeasons.up(queryRunner); + await queryRunner.query( + 'INSERT INTO "media_request" ("id", "monitorFutureSeasons") VALUES (2, true), (3, false)' + ); + assert.deepEqual( + await queryRunner.query( + 'SELECT "id", "monitorFutureSeasons" FROM "media_request" ORDER BY "id"' + ), + [ + { id: 1, monitorFutureSeasons: null }, + { id: 2, monitorFutureSeasons: true }, + { id: 3, monitorFutureSeasons: false }, + ] + ); + await futureSeasons.down(queryRunner); + await futureSeasons.down(queryRunner); + assert.equal( + await queryRunner.hasColumn('media_request', 'monitorFutureSeasons'), + false + ); } finally { await queryRunner.release(); await dataSource.destroy(); diff --git a/bin/run-cypress-start.mjs b/bin/run-cypress-start.mjs index 1eae1042e1..7bf1a6d6dd 100644 --- a/bin/run-cypress-start.mjs +++ b/bin/run-cypress-start.mjs @@ -5,7 +5,15 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); -const result = spawnSync(process.execPath, ['dist/index.js'], { +const args = + process.env.E2E_OFFLINE === 'true' + ? [ + '--require', + path.join(root, 'bin/e2e-network-guard.cjs'), + 'dist/index.js', + ] + : ['dist/index.js']; +const result = spawnSync(process.execPath, args, { cwd: root, env: { ...process.env, diff --git a/bin/run-tooling-tests.mjs b/bin/run-tooling-tests.mjs index d3671dddca..7692eaa5a0 100644 --- a/bin/run-tooling-tests.mjs +++ b/bin/run-tooling-tests.mjs @@ -19,6 +19,8 @@ export function parseToolingWorkers(args) { } const portableTests = [ + 'bin/e2e-network-guard.test.mjs', + 'scripts/interface-theme.test.mjs', 'bin/interface-theme-postgres-migration.test.mjs', 'bin/check-current-batch-contract-lib.test.mjs', 'bin/check-i18n-lib.test.mjs', diff --git a/cypress/config/settings.cypress.json b/cypress/config/settings.cypress.json index be451ea426..d455b52357 100644 --- a/cypress/config/settings.cypress.json +++ b/cypress/config/settings.cypress.json @@ -29,8 +29,8 @@ }, "plex": { "name": "Seerr", - "ip": "192.168.1.1", - "port": 32400, + "ip": "127.0.0.1", + "port": 1, "useSsl": false, "libraries": [ { diff --git a/cypress/e2e/navigation-regrouping.cy.ts b/cypress/e2e/navigation-regrouping.cy.ts index 2e37923725..e72bdfb312 100644 --- a/cypress/e2e/navigation-regrouping.cy.ts +++ b/cypress/e2e/navigation-regrouping.cy.ts @@ -187,7 +187,9 @@ describe('primary navigation', () => { }); cy.visit('/discover/tv/genre/18?sortBy=popularity.desc&page=2'); - cy.get('[data-testid="discovery-mode-tab-swipe"]').click(); + cy.get('[data-testid="discovery-mode-tab-swipe"]') + .should('have.attr', 'aria-disabled', 'false') + .click(); cy.location('pathname').should('eq', '/swipe'); cy.location('search').should('include', 'returnTo'); cy.location('search').should((search) => { diff --git a/docs/README.md b/docs/README.md index a8458ce961..6c0ec21950 100644 --- a/docs/README.md +++ b/docs/README.md @@ -37,6 +37,8 @@ connects to. - [Find books, authors, and series](/using-seerr/books-and-series/) - [Browse, request, and track sports leagues with Sportarr](/using-seerr/sportarr/) - [Follow requests and status history](/using-seerr/request-status/) +- [Understand request defaults and overrides](/using-seerr/request-defaults/) +- [Configure bounded Servarr queue tracking and live download progress](/using-seerr/live-download-progress/) - [Opt in to the TV episode queue with Plex, Jellyfin, or Emby playback](/using-seerr/jellyfin-watch-ahead/) - [Browse and request ROMs and PC games](/using-seerr/software-acquisition/) - [Discover and request adult scenes with Whisparr](/using-seerr/adult-media/) @@ -65,7 +67,7 @@ connects to. ## Configure and operate - [Configure OIDC sign-in, provider callbacks, account admission, linking, and recovery](/using-seerr/settings/users/oidc) -- [Require Jellyfin Quick Connect for media-server sign-in](/using-seerr/settings/users/#require-jellyfin-quick-connect) +- [Require Jellyfin Quick Connect for media-server sign-in](/using-seerr/settings/users/#require-jellyfin-quick-connect-sign-in) - [Cross-project OIDC contract and rollout map](/maintainers/oidc-cross-project-template) · [provider IDs, official setup links, scopes, and caveats](/maintainers/oidc-provider-catalog) - [Choose metadata providers and configure music request limits](/using-seerr/settings/metadata/) - [Check MusicBrainz and Cover Art Archive connectivity](/using-seerr/settings/metadata/#music-metadata-providers) diff --git a/docs/fork-rationale.md b/docs/fork-rationale.md index d0d787e620..998f5604a7 100644 --- a/docs/fork-rationale.md +++ b/docs/fork-rationale.md @@ -61,14 +61,17 @@ and retry only after the relevant cache interval. | Tooltips and download details | Help and interactive download details support keyboard and touch input, fit within the viewport, and keep long details scrollable. Source context includes Seerr [PR #3562](https://github.com/seerr-team/seerr/pull/3562). | Checks cover keyboard focus, touch activation, placement near viewport edges, narrow screens, and scrolling within long download details. | | Subject-tag visibility | Users can hide or show potentially revealing Subject Tags across Movie and Series pages, with their choice isolated to the correct account. Source context includes Seerr [issue #2651](https://github.com/seerr-team/seerr/issues/2651) and [PR #3071](https://github.com/seerr-team/seerr/pull/3071). | The preference survives navigation and reloads, applies to both detail types, and preserves tag search links when tags are shown. | | TV availability and scanner behavior | Completed series remain available when their regular seasons are complete, even if an orphaned unknown season record exists. Scans distinguish confirmed removal from incomplete or failed checks, match series through TVDB and resolved TMDB identity, and settle abandoned processing seasons and requests per quality only after all relevant Sonarr scans finish. Source context includes Seerr [PR #3148](https://github.com/seerr-team/seerr/pull/3148), [issue #3604](https://github.com/seerr-team/seerr/issues/3604), [PR #3605](https://github.com/seerr-team/seerr/pull/3605), [PR #3606](https://github.com/seerr-team/seerr/pull/3606), [PR #3578](https://github.com/seerr-team/seerr/pull/3578), and [PR #3579](https://github.com/seerr-team/seerr/pull/3579). | Regression checks cover orphaned seasons and requests, HD and 4K rollups, specials, provider identity changes, failed or incomplete scans, concurrent processing across configured services, and removal only after confirmed absence. | +| Per-episode availability | TV season pages can show individual episodes reported by Sonarr, Plex, Jellyfin, or Emby, with source-specific standard and 4K state. Sonarr uses TVDB numbering. Each media-server TV library has an explicit TMDB or TVDB episode-order setting, and badges appear only when it matches the selected TV or anime metadata provider. File presence stays distinct from per-user playback access. Source context includes Seerr [PR #1671](https://github.com/seerr-team/seerr/pull/1671), [PR #3355](https://github.com/seerr-team/seerr/pull/3355), [PR #3361](https://github.com/seerr-team/seerr/pull/3361), [PR #3527](https://github.com/seerr-team/seerr/pull/3527), and media-server scanner work in [PR #3402](https://github.com/seerr-team/seerr/pull/3402). | A supported replacement provides Sonarr and media-server episode inventories with explicit numbering compatibility; keeps each scanner's source identity and standard/4K state independent; updates or removes rows only after a complete, correctly mapped scan; preserves state through failures, caps, incomplete provider responses, and ambiguous mappings; and exposes the distinction between file presence and user playback access. | | Sonarr anime profiles | Administrators can set and review an anime quality profile. If that profile is missing or cannot be checked at dispatch time, an approved anime request can use the standard profile on the same Sonarr service. Source context includes Seerr [issue #3159](https://github.com/seerr-team/seerr/issues/3159) and [PR #3160](https://github.com/seerr-team/seerr/pull/3160). | Checks cover profile creation and edits, missing or unavailable profiles, recovery at dispatch, and isolation across multiple Sonarr services. | | Sonarr future-season monitoring | Administrators can choose All, None, or Latest Season Requested. The last mode monitors future seasons only when a request includes the latest regular season; specials and older-only requests do not qualify. Automatic search remains separate. Source context includes Seerr [issue #3152](https://github.com/seerr-team/seerr/issues/3152) and [PR #3157](https://github.com/seerr-team/seerr/pull/3157). | Checks cover latest, older-only, special-only, and missing-season metadata, and confirm the setting round-trips while automatic-search behavior remains independent. | | Sonarr API and season orders | Sonarr v3/v4 and v5 remain supported. For v5, metadata language and season order are explicit request choices; manual season repair verifies standard seasons against TVDB and alternate orders against the selected Sonarr series. | Checks cover version detection, per-endpoint fallback, focused updates that preserve Sonarr-owned metadata, and mappings isolated by service, quality, and season order. | | Request destinations and variants | Movie and series requests can target labeled Radarr and Sonarr instances. Per-user grants, quality choices, destination-specific availability, and request history stay attached to the selected service. Anime requests use the anime-specific Sonarr root folder unless a folder override differs from the standard server root; a stored standard default does not override the anime setting. Other media preserve selected book format, game platform, and other request variants. Source context includes Seerr [issue #3410](https://github.com/seerr-team/seerr/issues/3410) and [PR #3560](https://github.com/seerr-team/seerr/pull/3560). | Checks cover permission enforcement, duplicate prevention, multiple services, scans, retries, and availability on each selected destination. | +| Production-country override rules | Radarr and Sonarr override rules can route movies and series using TMDB production-country metadata. Any selected country may match within that field; all other configured condition fields must also match. Missing country metadata does not match the rule. Sonarr services that expose language profiles can select one in the rule; Radarr continues to use its quality profile, and Sonarr v5 metadata language stays a separate lookup setting. Source context includes Seerr [issue #3439](https://github.com/seerr-team/seerr/issues/3439). | Checks cover movie and series metadata, country-code selection, OR within countries and AND across condition fields, missing metadata, catalog-rule rejection, fallback to the next rule or service defaults, explicit requester language-profile choices, and unavailable or stale Sonarr language profiles. | | Previous-season watch gate | Administrators can require playback of the immediately previous regular TV season before later seasons are requested. The requester’s linked Plex, Jellyfin, or Emby watch history is used; uncertain playback state fails closed, and authorized managers can override the gate. Source context includes Seerr [issue #3590](https://github.com/seerr-team/seerr/issues/3590). | Checks cover partial and full-season requests, specials and empty seasons, missing library or playback data, watch-state changes, and permission-checked overrides. | | Watchlist filters and ordering | Local watchlists support title search, media-type filters, and stable sorting. Combined Plex lists retain Plex order and do not claim that remote pages were fully filtered or sorted. Deliberate Plex Watchlist removals do not trigger repeated auto-requests while the item remains removed. Metadata lookups use bounded concurrency and skip isolated timeout or unreachable-item failures while preserving authentication errors. Source context includes Seerr [PR #3506](https://github.com/seerr-team/seerr/pull/3506), [issue #3235](https://github.com/seerr-team/seerr/issues/3235), and [PR #3251](https://github.com/seerr-team/seerr/pull/3251). | Checks cover user isolation, pagination, local ordering, combined Plex results, the remove/re-add auto-request cycle, bounded metadata concurrency, and continuation after individual network failures. | | OpenAPI watchlist contract | The request schema matches movie, TV, music, book, comic, and magazine identities. The create response requires its stable row fields, uses the public requester projection, and leaves TMDB, MusicBrainz, and external IDs optional across media types. Source context includes Seerr [issue #3298](https://github.com/seerr-team/seerr/issues/3298), [PR #3425](https://github.com/seerr-team/seerr/pull/3425), and response-schema [PR #3635](https://github.com/seerr-team/seerr/pull/3635). | Contract validation covers valid request and response payloads for all six media types, rejects missing `mediaType` or the wrong identifier, requires the stable response fields, accepts the media-specific optional IDs, and matches the server's 201 and 400 responses. | | Request availability subscriptions | A signed-in user can privately follow another user's active movie or series request and receive one notice through their own enabled agents and Media Available preference. Following does not create a request or reveal the requester. Source context includes Seerr [issue #3091](https://github.com/seerr-team/seerr/issues/3091) and [issue #375](https://github.com/seerr-team/seerr/issues/375). | Checks cover self-only API access, idempotent follow and cancellation, multiple request owners, notification preferences, durable delivery, privacy, and cleanup after decline, failure, or deletion. | +| Pending request edit notifications | Administrators can opt into a distinct event when a still-pending request changes owner, selected seasons or episodes, or acquisition options. Delivery uses the durable notification queue and works through webhook, ntfy, and other configured agents. Source context includes Seerr [PR #1879](https://github.com/seerr-team/seerr/pull/1879). | Checks cover material versus unchanged edits, pending-only scope, no duplicates with status transitions, permission-aware admin delivery, per-agent opt-in, and durable delivery. | | Slack actions and quota approvals | Slack approval or decline actions use a mapped SeerrNG account and the same current permission checks as the web app. Requests over quota follow an explicit manager approval path without silently bypassing configured limits. Source context includes Seerr [issue #3592](https://github.com/seerr-team/seerr/issues/3592) and [issue #3554](https://github.com/seerr-team/seerr/issues/3554). | Checks cover signature and freshness validation, account mapping, authorization, one serialized request transition, and correct quota accounting for approval, decline, cancellation, and retry. | | Query scale and data volume | Request details, status pages, and library summaries stay responsive for large catalogs and histories without multiplying independent collections or issuing one lookup per record. Request rows use their paginated list data on mount, focus, and reconnect; only active download details keep their refresh interval. Source context includes Seerr [issue #3515](https://github.com/seerr-team/seerr/issues/3515), [issue #3642](https://github.com/seerr-team/seerr/issues/3642), and [PR #3647](https://github.com/seerr-team/seerr/pull/3647). | Representative large datasets show bounded row and query growth, correct pagination, and acceptable response time across filtered views. | | TV identity and request recovery | Missing or conflicting TVDB identity and season numbering do not discard requests or silently select another series. Eligible requests can be repaired with a verified TVDB series and explicit season mapping scoped to the selected Sonarr service and quality. Source context includes Seerr [issues #3488](https://github.com/seerr-team/seerr/issues/3488), [PR #3489](https://github.com/seerr-team/seerr/pull/3489), [PR #3490](https://github.com/seerr-team/seerr/pull/3490), [PR #3495](https://github.com/seerr-team/seerr/pull/3495), and [PR #3496](https://github.com/seerr-team/seerr/pull/3496). | Checks cover missing, ambiguous, and unavailable metadata; verified season lists; retained request identity and history; destination and quality isolation; mapped dispatch; and safe retry after recovery. | @@ -86,6 +89,7 @@ and retry only after the relevant cache interval. | API contract | A maintained OpenAPI contract describes actual request payloads and response projections for supported media, services, and user behavior. Request and response schemas can differ; credentials and permission-restricted operational fields stay out of public responses. Source context includes Seerr [PR #2700](https://github.com/seerr-team/seerr/pull/2700) and the SeerrNG adaptation in [PR #429](https://github.com/snapetech-org/seerrng/pull/429). | Compare every documented route with its runtime validator, handler, and response filter. Verify nullable and optional fields, scalar and array shapes, service enums, and permission-sensitive fields for both authorized and unprivileged callers. | | Jellyfin Quick Connect-only sign-in | Administrators can require Jellyfin Quick Connect and reject Jellyfin password and plugin bridge sign-in. Emby, Plex, local-password, and OpenID Connect sign-in remain independently controlled. Source context includes Seerr [PR #3315](https://github.com/seerr-team/seerr/pull/3315). | Checks confirm the sign-in form and server enforcement agree, direct password and plugin bridge requests are rejected, Quick Connect still works, initial setup remains available, and other identity providers and linked-account management remain usable. | | Viewer-scoped media-server access | Movie and TV availability reflects the viewer's linked Plex, Jellyfin, or Emby account, visible seasons, quality, and verified playback links. Exact Radarr/Sonarr destinations remain distinct for duplicate checks and request completion. Provider ACLs are not changed. Source context includes Seerr [issue #180](https://github.com/seerr-team/seerr/issues/180) and [PR #3296](https://github.com/seerr-team/seerr/pull/3296). | Checks cover linked and unlinked users, multiple viewers and destinations, standard and 4K copies, restricted TV seasons, provider errors, scans, cache expiry, and request recovery without false completion or duplicate requests. | +| Webhook payload formatting | Custom JSON webhook payloads provide bounded, deterministic formatting for supported string variables, including lowercase, URL-component encoding, and slugification. Unknown filters fail clearly, and payload bounds and outbound URL protections remain in force. Source context includes Seerr [issue #3394](https://github.com/seerr-team/seerr/issues/3394) and the related [PR #2039](https://github.com/seerr-team/seerr/pull/2039). | Checks cover legacy placeholders, chained allowlisted filters, Unicode text, unknown and malformed filters, nested JSON values, and payload size/depth limits. | | Data and API transition | A supported path preserves or intentionally transforms requests, user preferences, permissions, provider links, API clients, and other state operators need. | A representative SeerrNG backup upgrades to the supported replacement in a disposable environment. Data integrity, client compatibility, rollback, and recovery are documented and verified. | | Container distribution and identity | Production images omit build-only payloads that are not required at runtime; Docker examples drop all Linux capabilities, prevent privilege escalation, and describe the container's UID/GID behavior and rootless Podman mapping. Source context includes Seerr [PR #3472](https://github.com/seerr-team/seerr/pull/3472), [issue #3598](https://github.com/seerr-team/seerr/issues/3598), and [issue #3602](https://github.com/seerr-team/seerr/issues/3602). | Compare current compressed and unpacked image sizes; verify startup and config-volume writes with the dropped capabilities, documented container identity, and rootless Podman mapping. | | Release and operator support | Installation, configuration, backup, upgrade, rollback, troubleshooting, and support guidance cover the deployment channels SeerrNG users rely on. Notification setup documentation explains provider-specific options for posters, priorities, sounds, public logos, webhook variables, and SMTP certificate verification. Source context includes Seerr [PR #3586](https://github.com/seerr-team/seerr/pull/3586); SeerrNG maintains corresponding [notification guides](./using-seerr/notifications/index.mdx). | Operators can move from a supported SeerrNG release to a supported replacement using documented steps and a tested recovery path. Notification documentation must match the shipped settings and explain security-sensitive transport options. | @@ -100,3 +104,11 @@ service can replace a gate once the behavior is supported and the evidence is available. The [documentation index](./README.md) links to current operator guides; [NOTICE.md](https://github.com/snapetech-org/seerrng/blob/main/NOTICE.md) records project attribution. + +## Advanced request defaults + +Movie and TV requests resolve service, anime, account and rule defaults separately from explicit requester selections. Pending request edits can clear a saved override back to the configured service default while keeping the selected destination. The [request defaults guide](./using-seerr/request-defaults.md) documents this SeerrNG adaptation of Seerr PR #3477 and the related #3410/#3539 discussions. + +## Radarr and Sonarr scan tag exclusions + +Administrators can exclude tagged library entries per instance without deleting media records or requests. Title-wide availability is cleared only when that instance was its recorded source and no alternate copy is known. Retirement requires matching settings validation, legacy defaults, fully excluded scan safety, source-specific status reconciliation, safe orphan cleanup and preservation of copies on other instances. This adapts the scope discussed in Seerr PR #1884, which closed without merging. diff --git a/docs/getting-started/buildfromsource.mdx b/docs/getting-started/buildfromsource.mdx index a227462170..f5311953b7 100644 --- a/docs/getting-started/buildfromsource.mdx +++ b/docs/getting-started/buildfromsource.mdx @@ -18,7 +18,7 @@ import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; ### Prerequisites - - [Node.js 24.22.1 or newer in the 24.x line](https://nodejs.org/en/download/) + - [Node.js 24.22.2 or newer in the 24.x line](https://nodejs.org/en/download/) - [Pnpm 10.x](https://pnpm.io/installation) - [Git](https://git-scm.com/downloads) diff --git a/docs/interface-themes/authoring.md b/docs/interface-themes/authoring.md index a7f829991b..810fb47876 100644 --- a/docs/interface-themes/authoring.md +++ b/docs/interface-themes/authoring.md @@ -1,7 +1,7 @@ # Creating and Sharing SeerrNG Interface Themes SeerrNG themes are small, versioned packages that own their visual CSS and a -few presentation choices such as navigation grouping. The application keeps +few presentation choices such as navigation grouping and native page composition. The application keeps the page markup, APIs, permissions, and actions. A theme package can restyle and rearrange existing interface roles; it cannot add executable code or replace application routes. @@ -16,13 +16,27 @@ my-theme/ theme.css ``` -Copy the [`template/` directory](https://github.com/snapetech-org/seerrng/tree/main/docs/interface-themes/template) -to start. Use a lowercase kebab-case ID such as `my-theme`; IDs are permanent -package identifiers and cannot be changed after users save them in their -account settings. +The quickest start uses a complete native theme and rebases every CSS selector: + +```sh +pnpm install +pnpm interface-theme:create my-cinema --from persiusNG --name "My Cinema" --author "Your name" +``` + +This creates `my-cinema/manifest.json`, `my-cinema/theme.css` and a short README. +No server build, running application, proxy, GitHub fork or account is required +for creation and packaging. The command refuses to overwrite an existing folder. +Use `--from seerrOrig` or `--from seerrNGJ` for those starting points, or an +installed custom theme ID. An optional second argument chooses the output folder. +The new package has its own ID and full stylesheet; it does not load or inherit +the original package at runtime. + +For a small hand-written example, copy [`template/`](https://github.com/snapetech-org/seerrng/tree/main/docs/interface-themes/template) instead. Use a lowercase kebab-case ID such as +`my-theme`; IDs are permanent package identifiers and cannot be changed after +users save them in their account settings. `manifest.json` declares the package identity, API versions, author, license, -and two app-level presentation choices. `theme.css` is ordinary CSS attached +and app-level presentation choices. `theme.css` is ordinary CSS attached only while that theme is selected. Use the existing shared classes and `data-interface-role` hooks to restyle the application's current controls and route families. @@ -41,7 +55,8 @@ checks CSS syntax, selector scope, resources, and package size. "author": "Your name", "license": "MIT", "navigation": "grouped", - "activeNavigationIcon": "filled" + "activeNavigationIcon": "outline", + "layout": "persius" } ``` @@ -56,6 +71,65 @@ choices. CSS is loaded only for the selected theme. Publishing a changed manifest or stylesheet uses a new package version; changing the ID creates a separate theme and does not replace saved account settings. +## Choose a native composition + +| Manifest `layout` | Application markup available to your stylesheet | +| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| Omitted or `classic` | Existing Seerr/SeerrNG catalog, detail, request and filter composition | +| `persius` | Cinematic discovery, captions below posters, book/narrator shelves, recording choices, compact requests, coming-soon releases and season shortcuts | + +The layout is app-owned, not a script shipped by an author. Your theme ID can be +anything valid: Persius layouts are activated by this metadata, not the reserved +`persiusNG` name. Forking PersiusNG carries the metadata automatically. Forking +SeerrOrig or SeerrNGJ preserves the classic composition. The CSS remains fully +independent in either case. Navigation and icons are also native application +choices. The `navigation` and `activeNavigationIcon` preferences apply to both +compositions. PersiusNG defaults to grouped navigation and outlined icons; a +derivative can select a flat menu or filled active icons without editing React. +Do not attempt to inject executable components into a package. + +Persius composition requires a SeerrNG release that includes PersiusNG in its +picker. Older releases reject the unrecognized metadata rather than silently +promising an equivalent layout. Publish the exact SeerrNG releases you tested. +Existing version 1 themes without `layout` remain supported unchanged. + +## Make the stylesheet your own + +Edit `theme.css` to change colors, typography, radius, density, shadows, grid/flex +arrangement and responsive behavior. Change the root variables first, then +change the scoped component rules. For example: + +```css +:root[data-interface-theme='my-cinema'] { + --interface-page: #101b1a; + --interface-panel: #192d2a; + --interface-accent-a: #91d6a6; + --interface-card-radius: 6px; +} + +[data-interface-theme='my-cinema'] .persius-request { + border-radius: var(--interface-card-radius); + border-inline-start: 3px solid var(--interface-accent-a); +} + +:root[data-interface-theme='my-cinema'][data-theme-mode='light'] { + --interface-page: #f5f7f0; + --interface-panel: #ffffff; + --interface-text: #172a23; + --interface-muted: #4b6258; +} +``` + +Keep `my-cinema` consistent in every selector. The generator already replaces +the base ID, including namespaced animation names. Classes such as +`.persius-request` are shared application hooks and should keep their names. +They do not make a custom theme depend on the PersiusNG stylesheet. For the full +supported surfaces and route families, use the [feature map](feature-map.md). + +Do not hide request, permission, availability, error or keyboard-focus states to +make a mockup look cleaner. Use the existing responsive rules as a starting point, +check long translated titles, and retain `prefers-reduced-motion` behavior. + ## CSS ownership and scope Every rule selector must begin with the package's theme root. For `my-theme`, @@ -92,15 +166,15 @@ theme root. Shared component roles resolve them to long-lived `--interface-*` tokens, so components keep semantic contracts while each package changes its effective appearance: -| Family | Package tokens | Controls | -| --- | --- | --- | -| Canvas and surfaces | `--interface-page`, `--interface-panel`, `--interface-panel-raised`, `--interface-border`, `--interface-muted`, `--interface-text`, `--interface-link`, `--interface-accent-a`, `--interface-accent-b`, `--interface-sidebar-top`, `--interface-sidebar-bottom`, `--interface-sidebar-selected`, `--interface-table-header`, `--interface-table-hover` | Backgrounds, copy, links, selected navigation, and table surfaces | -| Main geometry | `--interface-sidebar-width`, `--interface-page-gutter`, `--interface-grid-gap`, `--interface-card-radius`, `--interface-poster-radius`, `--interface-control-radius`, `--interface-main-card-padding`, `--interface-inset-card-padding`, `--interface-section-gap`, `--poster-width`, `--poster-aspect-ratio` | Navigation width, page columns, shelves, cards, controls, and poster grids | -| Navigation | `--interface-nav-group-gap`, `--interface-nav-item-gap`, `--interface-nav-inline-inset`, `--interface-nav-nested-indent`, `--interface-nav-mobile-offset`, `--interface-nav-desktop-offset`, `--interface-nav-heading-line-height` | Grouped navigation rhythm and nested/mobile alignment | -| Typography | `--interface-card-table-font-size`, `--interface-card-table-heading-weight`, `--interface-card-table-value-weight`, `--interface-card-title-font-size`, `--interface-page-heading-font-size`, `--interface-card-subheading-font-size`, `--interface-card-body-font-size`, `--interface-card-copy-line-height` | Page, card, and metadata hierarchy | -| Detail and compact cards | `--interface-detail-row-height`, `--interface-detail-row-gap`, `--interface-detail-divider-width`, `--interface-detail-first-column-limit`, `--interface-detail-first-value-limit`, `--interface-detail-last-column-limit`, `--interface-card-compact-title-font-size`, `--interface-card-compact-subheading-font-size`, `--interface-card-compact-line-height`, `--interface-card-compact-height`, `--interface-card-compact-padding-block`, `--interface-card-subheading-spacing-before`, `--interface-card-body-spacing-before` | Metadata tables, disclosure cards, and compact portrait rows | -| Controls and menus | `--interface-compact-control-height`, `--interface-profile-menu-row-height`, `--interface-button-padding-x`, `--interface-button-content-gap`, `--interface-poster-control-gap`, `--interface-dropdown-menu-surface`, `--interface-dropdown-menu-border` | Buttons, compact controls, poster badges, and menus | -| Effects and framing | `--interface-motion-duration`, `--app-card-frame-width`, `--app-card-frame-background` | Motion timing and card edge treatments | +| Family | Package tokens | Controls | +| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | +| Canvas and surfaces | `--interface-page`, `--interface-panel`, `--interface-panel-raised`, `--interface-border`, `--interface-muted`, `--interface-text`, `--interface-link`, `--interface-accent-a`, `--interface-accent-b`, `--interface-sidebar-top`, `--interface-sidebar-bottom`, `--interface-sidebar-selected`, `--interface-table-header`, `--interface-table-hover` | Backgrounds, copy, links, selected navigation, and table surfaces | +| Main geometry | `--interface-sidebar-width`, `--interface-page-gutter`, `--interface-grid-gap`, `--interface-card-radius`, `--interface-poster-radius`, `--interface-control-radius`, `--interface-main-card-padding`, `--interface-inset-card-padding`, `--interface-section-gap`, `--poster-width`, `--poster-aspect-ratio` | Navigation width, page columns, shelves, cards, controls, and poster grids | +| Navigation | `--interface-nav-group-gap`, `--interface-nav-item-gap`, `--interface-nav-inline-inset`, `--interface-nav-nested-indent`, `--interface-nav-mobile-offset`, `--interface-nav-desktop-offset`, `--interface-nav-heading-line-height` | Grouped navigation rhythm and nested/mobile alignment | +| Typography | `--interface-card-table-font-size`, `--interface-card-table-heading-weight`, `--interface-card-table-value-weight`, `--interface-card-title-font-size`, `--interface-page-heading-font-size`, `--interface-card-subheading-font-size`, `--interface-card-body-font-size`, `--interface-card-copy-line-height` | Page, card, and metadata hierarchy | +| Detail and compact cards | `--interface-detail-row-height`, `--interface-detail-row-gap`, `--interface-detail-divider-width`, `--interface-detail-first-column-limit`, `--interface-detail-first-value-limit`, `--interface-detail-last-column-limit`, `--interface-card-compact-title-font-size`, `--interface-card-compact-subheading-font-size`, `--interface-card-compact-line-height`, `--interface-card-compact-height`, `--interface-card-compact-padding-block`, `--interface-card-subheading-spacing-before`, `--interface-card-body-spacing-before` | Metadata tables, disclosure cards, and compact portrait rows | +| Controls and menus | `--interface-compact-control-height`, `--interface-profile-menu-row-height`, `--interface-button-padding-x`, `--interface-button-content-gap`, `--interface-poster-control-gap`, `--interface-dropdown-menu-surface`, `--interface-dropdown-menu-border` | Buttons, compact controls, poster badges, and menus | +| Effects and framing | `--interface-motion-duration`, `--app-card-frame-width`, `--app-card-frame-background` | Motion timing and card edge treatments | The tokens are supported design knobs, not a limit on package CSS. A theme may override any existing class or `data-interface-role` selector inside its exact @@ -108,6 +182,16 @@ scope, including grid/flex ordering, responsive layout, control shape, shadows, and component surfaces. Keep behavior and accessibility in shared role contracts; put design values on the theme root so changes remain easy to audit. +`data-theme-part` identifies inner composition boundaries without competing with +the broader `data-interface-role` contract. Supported hooks include +`searchbar-inner`, `searchbar-field`, `searchbar-account` and `request-media-card`. +Dialogs expose `data-modal-part="heading"` and `data-modal-part="content"`. +Use these hooks when an inner boundary needs an arrangement; retain their native +children and interactions. Shared request surfaces read `--theme-overlay-menu` +as RGB channels and `--main-card-padding` for their canvas. Override those tokens +on the scoped surface when its canvas differs from the rest of your package, +and use `--app-card-frame-width` for the existing decorative frame. + Themes can rearrange existing components with CSS Grid, Flexbox, `order`, and the app's semantic role hooks. Themes do not ship HTML, React components, route definitions, event handlers, icons, fonts, or images. That keeps a theme @@ -132,7 +216,8 @@ and again before serving their stylesheets. The installer accepts one JSON unknown format/API versions are rejected. The install catalog accepts at most 16 custom themes and 4 MiB of custom theme CSS total. - Only installed packages are listed or served. The selected package's CSS is - fetched from the same-origin API; unselected theme packages are not loaded. + fetched from the same-origin API with `nosniff` and same-origin resource + policy headers; unselected theme packages are not loaded. Install themes only from authors you trust. Scoped CSS cannot access account data through an application API, but a theme can still change or hide interface @@ -144,13 +229,21 @@ community packages. From the SeerrNG checkout, run: ```sh -pnpm build:server pnpm interface-theme:validate ./my-theme -pnpm interface-theme:pack ./my-theme ./my-theme.seerrtheme +pnpm interface-theme:pack ./my-theme +pnpm interface-theme:validate ./my-theme-0.1.0.seerrtheme +pnpm interface-theme:inspect ./my-theme-0.1.0.seerrtheme ``` -The build places the Node-only theme CLI in `dist/commands/interfaceTheme.js`. -The same commands work from a packaged SeerrNG host with Node available; for +Checkout commands use the existing development loader and run without compiling +the application. `pack` defaults to `-.seerrtheme` and also writes +`-.seerrtheme.sha256`. An optional output argument changes the name. +Both outputs are protected against overwrites; unchanged inputs produce identical +bundle bytes. `validate` accepts source directories and packaged files. `inspect` +prints metadata, composition, CSS size and SHA-256; `list` prints installed themes. + +Production builds place the Node-only CLI in `dist/commands/interfaceTheme.js`. +The same operations work from a packaged SeerrNG host with Node available; for example, `node dist/commands/interfaceTheme.js validate ./my-theme` runs the validator directly when that host does not use pnpm. @@ -158,14 +251,14 @@ Copy the resulting `.seerrtheme` file to the SeerrNG host and install it with the same release's CLI: ```sh -pnpm interface-theme:install ./my-theme.seerrtheme +pnpm interface-theme:install ./my-theme-0.1.0.seerrtheme ``` If the ID is already installed, installation stops. Updating an existing custom theme requires the explicit `--replace` option: ```sh -pnpm interface-theme:install ./my-theme.seerrtheme --replace +pnpm interface-theme:install ./my-theme-0.1.0.seerrtheme --replace ``` The installer validates the full package before writing, stages both files in @@ -179,7 +272,7 @@ accounts using it, then run: pnpm interface-theme:uninstall my-theme ``` -The built-in SeerrOrig and SeerrNGJ packages cannot be replaced or removed. +The built-in SeerrOrig, SeerrNGJ and PersiusNG packages cannot be replaced or removed. Installed packages remain in the app-data directory through application upgrades. Keep the source files and packaged `.seerrtheme` together when publishing so users can review, validate, and reproduce a release. @@ -188,12 +281,67 @@ For a community release, publish the source directory, the `.seerrtheme`, the SeerrNG version/API range, and a checksum together. For example: ```sh -sha256sum my-theme.seerrtheme > my-theme.seerrtheme.sha256 +sha256sum --check my-theme-0.1.0.seerrtheme.sha256 ``` Users should validate the package and compare its checksum against the author's release before installing it. +## Test and install without a UI proxy + +1. Run the normal SeerrNG application directly. Install the package using that + release’s CLI as the application user, with the same `CONFIG_DIRECTORY`. +2. Restart SeerrNG so its catalog discovers the package. Open **Theme picker → + Interface design** and select your theme. Refresh the page and verify your + account choice is restored. +3. Confirm the browser loads `/api/v1/interface-themes//theme.css` from + SeerrNG itself. No stylesheet injector, userscript or UI-rewriting proxy is + involved. Standard HTTPS/reverse-proxy hosting and Next.js authentication + middleware are separate and should remain configured as needed. +4. Review Discover, movies, series, books, audiobooks, details, requests, calendar, + settings and login at desktop and phone widths. Exercise request/cancel, + filtering, format changes, narration and season selection, keyboard focus, + loading/errors and authorized/unauthorized states. Also check light mode. +5. To revise an installed theme, increment its version, validate and pack it, + install the new bundle with `--replace`, restart and reload. The stable ID + preserves each user’s selection. Keep a previously validated bundle for rollback. + +Browser developer tools can experiment with CSS on the direct app; copy changes +back into the source stylesheet before packaging. The maintainer-only +`interface-theme:preview` command updates the legacy comparison document; it is +not a substitute for live testing of a community package. + +The [submission guide](submitting.md) gives a release checklist, supported review +routes and a ready-made GitHub form. [PersiusNG’s verification record](persiusng.md) +separates component evidence from the production acceptance that remains open. + +For a repeatable offline check of the production build, seed the disposable +Cypress configuration, build SeerrNG, and run the native browser specification: + +```sh +pnpm cypress:prepare +pnpm build +E2E_OFFLINE=true pnpm exec playwright test playwright/persius-integration.spec.ts +``` + +This uses local test accounts and deterministic catalog fixtures. The optional +server network guard rejects non-loopback service connections; the browser +fixture also rejects unhandled external requests. Do not point this command at +a live configuration. To include your installed Persius derivative in the test, +install it into the disposable `cypress/runtime-config` directory before startup +and set `E2E_CUSTOM_THEME_ID` to its ID. The test checks catalog discovery, native +composition, loading one independent stylesheet and account restoration after +reload. An unset ID explicitly skips only this additional package check. + +## Recording and season controls + +Persius derivatives may style `.persius-recordings`, `.persius-recording-choice`, +`.persius-recording-badges`, `.persius-sample` and `.persius-future-seasons`. +Retain visible keyboard focus, selected/disabled states and readable descriptions. +The application owns the audio element and request behavior. Do not create fake +availability, sample links or request actions with CSS generated content. +See [native request flows](native-request-flows.md) for data and provider behavior. + ## Versioning Increment the package's semantic `version` for each release that changes its diff --git a/docs/interface-themes/evidence/persiusng-desktop.jpg b/docs/interface-themes/evidence/persiusng-desktop.jpg new file mode 100644 index 0000000000..5a0fd8accf Binary files /dev/null and b/docs/interface-themes/evidence/persiusng-desktop.jpg differ diff --git a/docs/interface-themes/evidence/persiusng-native-desktop.jpg b/docs/interface-themes/evidence/persiusng-native-desktop.jpg new file mode 100644 index 0000000000..81efb39de8 Binary files /dev/null and b/docs/interface-themes/evidence/persiusng-native-desktop.jpg differ diff --git a/docs/interface-themes/evidence/persiusng-native-phone.jpg b/docs/interface-themes/evidence/persiusng-native-phone.jpg new file mode 100644 index 0000000000..448a21fd3d Binary files /dev/null and b/docs/interface-themes/evidence/persiusng-native-phone.jpg differ diff --git a/docs/interface-themes/evidence/persiusng-native-requests-1726.jpg b/docs/interface-themes/evidence/persiusng-native-requests-1726.jpg new file mode 100644 index 0000000000..2a791ee190 Binary files /dev/null and b/docs/interface-themes/evidence/persiusng-native-requests-1726.jpg differ diff --git a/docs/interface-themes/evidence/persiusng-native-season-dialog-1776.jpg b/docs/interface-themes/evidence/persiusng-native-season-dialog-1776.jpg new file mode 100644 index 0000000000..ae21aab04e Binary files /dev/null and b/docs/interface-themes/evidence/persiusng-native-season-dialog-1776.jpg differ diff --git a/docs/interface-themes/evidence/persiusng-native-season-dialog-390.jpg b/docs/interface-themes/evidence/persiusng-native-season-dialog-390.jpg new file mode 100644 index 0000000000..b326d89450 Binary files /dev/null and b/docs/interface-themes/evidence/persiusng-native-season-dialog-390.jpg differ diff --git a/docs/interface-themes/evidence/persiusng-native-verification.json b/docs/interface-themes/evidence/persiusng-native-verification.json new file mode 100644 index 0000000000..1688353677 --- /dev/null +++ b/docs/interface-themes/evidence/persiusng-native-verification.json @@ -0,0 +1,1584 @@ +{ + "schemaVersion": 1, + "date": "2026-10-31", + "sourceParent": "8a72b6db85e63b7560f5498194b22d33034d5d38", + "candidate": "The containing commit; modified source SHA-256 values are recorded below.", + "runtime": { + "node": "24.22.1", + "pnpm": "10.24.0", + "sqlite": "3.53.4", + "browser": "Chromium 138", + "playwright": "1.63.0" + }, + "verification": { + "nativeVitest": { + "passed": 4525, + "skipped": 5, + "failed": 0, + "filesPassed": 640, + "filesSkipped": 2, + "seconds": 657.48, + "scope": "Full suite before the final visual/fallback and runner changes; subsequent focused checks and production/browser verification are recorded separately." + }, + "focusedRequestTheme": { + "passed": 36, + "files": 6 + }, + "focusedFinalSeasonDialog": { + "passed": 36, + "files": 4 + }, + "runnerRegression": { + "nativePassed": 3, + "fixtureSubtestsPerReporter": 1600, + "matchingReportDestinations": true, + "coverageForwarded": true, + "delayedReporterAfterRetainedServiceHandle": true, + "cliOwnsWorkerAndReporterLifecycle": true, + "resultPipesFlushedBeforeExit": true, + "ciJunit": { + "passed": 3, + "junitTestcases": 3, + "junitFailures": 0, + "nestedInvocationsDoNotOverwriteReport": true + }, + "vitestPassed": 3, + "externalWorkingDirectoryReport": { + "externalWorkingDirectory": true, + "callerRelativeDestination": true, + "passed": 3 + } + }, + "nativeNode": { + "status": "passed", + "tests": 3824, + "suites": 746, + "passed": 3819, + "skipped": 5, + "failed": 0, + "cancelled": 0, + "seconds": 1155.406, + "concurrency": 4, + "matchingTerminalAndArchive": true, + "previousIncompleteInvocationsCountedAsPass": false, + "runnerLifecycle": "node-cli", + "files": 496 + }, + "tooling": { + "passed": 325, + "skipped": 4, + "failed": 0 + }, + "currentBatchAndUiStyle": { + "passed": true, + "geometryTests": 73 + }, + "types": { + "server": true, + "client": true + }, + "lint": { + "passed": true, + "warningsRemain": true + }, + "formatting": { + "passed": true, + "generatedBrowserOutputExcluded": true + }, + "productionBuild": { + "server": true, + "next": true, + "staticPages": 141, + "normalPrebuildChecks": true + }, + "browser": { + "startTime": "2026-10-31T00:52:21.801Z", + "duration": 110766.691, + "expected": 20, + "skipped": 0, + "unexpected": 0, + "flaky": 0 + }, + "classicBaselineBrowser": { + "startTime": "2026-10-31T00:54:24.304Z", + "duration": 34152.846000000005, + "expected": 2, + "skipped": 0, + "unexpected": 0, + "flaky": 0 + }, + "compiledCli": { + "compiledWrapper": true, + "sourceDirectoryPresent": false, + "createValidatePackInstallInspectListUninstall": true, + "checksum": "a20d4ec62ba299967c51d77c32f45435504d7f0ad372caf18c4d6610cfd4b18c" + }, + "installedDerivativeBrowser": { + "id": "integration-cinema", + "independentStylesheet": true, + "nativePersiusComposition": true, + "preferenceSurvivesReload": true + } + }, + "references": [ + { + "flow": "discover", + "desktop": [ + 1782, + 1055 + ], + "additionalWidths": [ + 768, + 390 + ] + }, + { + "flow": "movies", + "desktop": [ + 1788, + 1038 + ], + "additionalWidths": [ + 768, + 390 + ] + }, + { + "flow": "movie-detail", + "desktop": [ + 1782, + 1060 + ], + "additionalWidths": [ + 768, + 390 + ] + }, + { + "flow": "series", + "desktop": [ + 1776, + 1058 + ], + "additionalWidths": [ + 768, + 390 + ] + }, + { + "flow": "books", + "desktop": [ + 1772, + 1064 + ], + "additionalWidths": [ + 768, + 390 + ] + }, + { + "flow": "audiobooks", + "desktop": [ + 1726, + 1061 + ], + "additionalWidths": [ + 768, + 390 + ] + }, + { + "flow": "narrations", + "desktop": [ + 1736, + 1046 + ], + "additionalWidths": [ + 768, + 390 + ] + }, + { + "flow": "requests", + "desktop": [ + 1726, + 1067 + ], + "additionalWidths": [ + 768, + 390 + ] + }, + { + "flow": "coming-soon", + "desktop": [ + 1760, + 1055 + ], + "additionalWidths": [ + 768, + 390 + ] + } + ], + "documentOverflow": [ + { + "file": "audiobooks-1726-geometry.json", + "width": 1726, + "scrollWidth": 1726, + "elements": [] + }, + { + "file": "audiobooks-390-geometry.json", + "width": 390, + "scrollWidth": 390, + "elements": [] + }, + { + "file": "audiobooks-768-geometry.json", + "width": 768, + "scrollWidth": 768, + "elements": [] + }, + { + "file": "books-1772-geometry.json", + "width": 1772, + "scrollWidth": 1772, + "elements": [] + }, + { + "file": "books-390-geometry.json", + "width": 390, + "scrollWidth": 390, + "elements": [ + { + "tag": "A", + "class": "persius-series-card", + "width": 238, + "right": 508 + }, + { + "tag": "DIV", + "class": "persius-book-stack", + "width": 208, + "right": 493 + }, + { + "tag": "DIV", + "class": "", + "width": 80, + "right": 407 + }, + { + "tag": "IMG", + "class": "", + "width": 80, + "right": 407 + }, + { + "tag": "STRONG", + "class": "", + "width": 208, + "right": 493 + }, + { + "tag": "SMALL", + "class": "", + "width": 208, + "right": 493 + }, + { + "tag": "A", + "class": "persius-series-card", + "width": 238, + "right": 758 + }, + { + "tag": "DIV", + "class": "persius-book-stack", + "width": 208, + "right": 743 + }, + { + "tag": "DIV", + "class": "", + "width": 80, + "right": 615 + }, + { + "tag": "IMG", + "class": "", + "width": 80, + "right": 615 + }, + { + "tag": "DIV", + "class": "", + "width": 80, + "right": 657 + }, + { + "tag": "IMG", + "class": "", + "width": 80, + "right": 657 + }, + { + "tag": "STRONG", + "class": "", + "width": 208, + "right": 743 + }, + { + "tag": "SMALL", + "class": "", + "width": 208, + "right": 743 + } + ] + }, + { + "file": "books-768-geometry.json", + "width": 768, + "scrollWidth": 768, + "elements": [ + { + "tag": "A", + "class": "persius-series-card", + "width": 238, + "right": 778 + } + ] + }, + { + "file": "coming-soon-1760-geometry.json", + "width": 1760, + "scrollWidth": 1760, + "elements": [] + }, + { + "file": "coming-soon-390-geometry.json", + "width": 390, + "scrollWidth": 390, + "elements": [] + }, + { + "file": "coming-soon-768-geometry.json", + "width": 768, + "scrollWidth": 768, + "elements": [] + }, + { + "file": "discover-1782-geometry.json", + "width": 1782, + "scrollWidth": 1782, + "elements": [ + { + "tag": "ARTICLE", + "class": "persius-hero", + "width": 564, + "right": 2112 + }, + { + "tag": "IMG", + "class": "", + "width": 564, + "right": 2112 + }, + { + "tag": "DIV", + "class": "persius-hero-content", + "width": 564, + "right": 2112 + }, + { + "tag": "A", + "class": "persius-hero-title", + "width": 528, + "right": 2094 + }, + { + "tag": "DIV", + "class": "persius-hero-footer", + "width": 528, + "right": 2094 + }, + { + "tag": "BUTTON", + "class": "app-button app-button-primary button-standard Button_button__Ok99v", + "width": 110, + "right": 2094 + }, + { + "tag": "SPAN", + "class": "", + "width": 76, + "right": 2077 + }, + { + "tag": "svg", + "class": {}, + "width": 16, + "right": 2017 + }, + { + "tag": "path", + "class": {}, + "width": 10, + "right": 2014 + }, + { + "tag": "ARTICLE", + "class": "persius-hero", + "width": 564, + "right": 2688 + }, + { + "tag": "IMG", + "class": "", + "width": 564, + "right": 2688 + }, + { + "tag": "DIV", + "class": "persius-hero-content", + "width": 564, + "right": 2688 + }, + { + "tag": "SPAN", + "class": "persius-hero-kicker", + "width": 113.609375, + "right": 2255.609375 + }, + { + "tag": "A", + "class": "persius-hero-title", + "width": 528, + "right": 2670 + }, + { + "tag": "DIV", + "class": "persius-hero-footer", + "width": 528, + "right": 2670 + }, + { + "tag": "SPAN", + "class": "", + "width": 79.65625, + "right": 2221.65625 + }, + { + "tag": "A", + "class": "persius-chip", + "width": 112, + "right": 2670 + }, + { + "tag": "svg", + "class": {}, + "width": 16, + "right": 2591 + }, + { + "tag": "path", + "class": {}, + "width": 10, + "right": 2588 + }, + { + "tag": "ARTICLE", + "class": "persius-hero", + "width": 564, + "right": 3264 + }, + { + "tag": "IMG", + "class": "", + "width": 564, + "right": 3264 + }, + { + "tag": "DIV", + "class": "persius-hero-content", + "width": 564, + "right": 3264 + }, + { + "tag": "SPAN", + "class": "persius-hero-kicker", + "width": 113.609375, + "right": 2831.609375 + }, + { + "tag": "A", + "class": "persius-hero-title", + "width": 528, + "right": 3246 + }, + { + "tag": "DIV", + "class": "persius-hero-footer", + "width": 528, + "right": 3246 + }, + { + "tag": "SPAN", + "class": "", + "width": 79.65625, + "right": 2797.65625 + }, + { + "tag": "BUTTON", + "class": "app-button app-button-primary button-standard Button_button__Ok99v", + "width": 110, + "right": 3246 + }, + { + "tag": "SPAN", + "class": "", + "width": 76, + "right": 3229 + }, + { + "tag": "svg", + "class": {}, + "width": 16, + "right": 3169 + }, + { + "tag": "path", + "class": {}, + "width": 10, + "right": 3166 + } + ] + }, + { + "file": "discover-390-geometry.json", + "width": 390, + "scrollWidth": 390, + "elements": [ + { + "tag": "ARTICLE", + "class": "persius-hero", + "width": 327.59375, + "right": 687.1875 + }, + { + "tag": "IMG", + "class": "", + "width": 327.59375, + "right": 687.1875 + }, + { + "tag": "DIV", + "class": "persius-hero-content", + "width": 327.59375, + "right": 687.1875 + }, + { + "tag": "SPAN", + "class": "persius-hero-kicker", + "width": 113.609375, + "right": 491.203125 + }, + { + "tag": "A", + "class": "persius-hero-title", + "width": 291.59375, + "right": 669.1875 + }, + { + "tag": "DIV", + "class": "persius-hero-footer", + "width": 291.59375, + "right": 669.1875 + }, + { + "tag": "SPAN", + "class": "", + "width": 79.65625, + "right": 457.25 + }, + { + "tag": "BUTTON", + "class": "app-button app-button-primary button-standard Button_button__Ok99v", + "width": 110, + "right": 669.1875 + }, + { + "tag": "SPAN", + "class": "", + "width": 76, + "right": 652.1875 + }, + { + "tag": "svg", + "class": {}, + "width": 16, + "right": 592.1875 + }, + { + "tag": "path", + "class": {}, + "width": 10, + "right": 589.1875 + }, + { + "tag": "ARTICLE", + "class": "persius-hero", + "width": 327.59375, + "right": 1026.78125 + }, + { + "tag": "IMG", + "class": "", + "width": 327.59375, + "right": 1026.78125 + }, + { + "tag": "DIV", + "class": "persius-hero-content", + "width": 327.59375, + "right": 1026.78125 + }, + { + "tag": "SPAN", + "class": "persius-hero-kicker", + "width": 113.609375, + "right": 830.796875 + }, + { + "tag": "A", + "class": "persius-hero-title", + "width": 291.59375, + "right": 1008.78125 + }, + { + "tag": "DIV", + "class": "persius-hero-footer", + "width": 291.59375, + "right": 1008.78125 + }, + { + "tag": "SPAN", + "class": "", + "width": 79.65625, + "right": 796.84375 + }, + { + "tag": "BUTTON", + "class": "app-button app-button-primary button-standard Button_button__Ok99v", + "width": 110, + "right": 1008.78125 + }, + { + "tag": "SPAN", + "class": "", + "width": 76, + "right": 991.78125 + }, + { + "tag": "svg", + "class": {}, + "width": 16, + "right": 931.78125 + }, + { + "tag": "path", + "class": {}, + "width": 10, + "right": 928.78125 + }, + { + "tag": "ARTICLE", + "class": "persius-hero", + "width": 327.59375, + "right": 1366.375 + }, + { + "tag": "IMG", + "class": "", + "width": 327.59375, + "right": 1366.375 + }, + { + "tag": "DIV", + "class": "persius-hero-content", + "width": 327.59375, + "right": 1366.375 + }, + { + "tag": "SPAN", + "class": "persius-hero-kicker", + "width": 113.609375, + "right": 1170.390625 + }, + { + "tag": "A", + "class": "persius-hero-title", + "width": 291.59375, + "right": 1348.375 + }, + { + "tag": "DIV", + "class": "persius-hero-footer", + "width": 291.59375, + "right": 1348.375 + }, + { + "tag": "SPAN", + "class": "", + "width": 79.65625, + "right": 1136.4375 + }, + { + "tag": "A", + "class": "persius-chip", + "width": 112, + "right": 1348.375 + } + ] + }, + { + "file": "discover-768-geometry.json", + "width": 768, + "scrollWidth": 768, + "elements": [ + { + "tag": "ARTICLE", + "class": "persius-hero", + "width": 564, + "right": 1180 + }, + { + "tag": "IMG", + "class": "", + "width": 564, + "right": 1180 + }, + { + "tag": "DIV", + "class": "persius-hero-content", + "width": 564, + "right": 1180 + }, + { + "tag": "A", + "class": "persius-hero-title", + "width": 528, + "right": 1162 + }, + { + "tag": "DIV", + "class": "persius-hero-footer", + "width": 528, + "right": 1162 + }, + { + "tag": "BUTTON", + "class": "app-button app-button-primary button-standard Button_button__Ok99v", + "width": 110, + "right": 1162 + }, + { + "tag": "SPAN", + "class": "", + "width": 76, + "right": 1145 + }, + { + "tag": "svg", + "class": {}, + "width": 16, + "right": 1085 + }, + { + "tag": "path", + "class": {}, + "width": 10, + "right": 1082 + }, + { + "tag": "ARTICLE", + "class": "persius-hero", + "width": 564, + "right": 1756 + }, + { + "tag": "IMG", + "class": "", + "width": 564, + "right": 1756 + }, + { + "tag": "DIV", + "class": "persius-hero-content", + "width": 564, + "right": 1756 + }, + { + "tag": "SPAN", + "class": "persius-hero-kicker", + "width": 113.609375, + "right": 1323.609375 + }, + { + "tag": "A", + "class": "persius-hero-title", + "width": 528, + "right": 1738 + }, + { + "tag": "DIV", + "class": "persius-hero-footer", + "width": 528, + "right": 1738 + }, + { + "tag": "SPAN", + "class": "", + "width": 79.65625, + "right": 1289.65625 + }, + { + "tag": "BUTTON", + "class": "app-button app-button-primary button-standard Button_button__Ok99v", + "width": 110, + "right": 1738 + }, + { + "tag": "SPAN", + "class": "", + "width": 76, + "right": 1721 + }, + { + "tag": "svg", + "class": {}, + "width": 16, + "right": 1661 + }, + { + "tag": "path", + "class": {}, + "width": 10, + "right": 1658 + }, + { + "tag": "ARTICLE", + "class": "persius-hero", + "width": 564, + "right": 2332 + }, + { + "tag": "IMG", + "class": "", + "width": 564, + "right": 2332 + }, + { + "tag": "DIV", + "class": "persius-hero-content", + "width": 564, + "right": 2332 + }, + { + "tag": "SPAN", + "class": "persius-hero-kicker", + "width": 113.609375, + "right": 1899.609375 + }, + { + "tag": "A", + "class": "persius-hero-title", + "width": 528, + "right": 2314 + }, + { + "tag": "DIV", + "class": "persius-hero-footer", + "width": 528, + "right": 2314 + }, + { + "tag": "SPAN", + "class": "", + "width": 79.65625, + "right": 1865.65625 + }, + { + "tag": "A", + "class": "persius-chip", + "width": 112, + "right": 2314 + }, + { + "tag": "svg", + "class": {}, + "width": 16, + "right": 2235 + }, + { + "tag": "path", + "class": {}, + "width": 10, + "right": 2232 + } + ] + }, + { + "file": "movie-detail-1782-geometry.json", + "width": 1782, + "scrollWidth": 1782, + "elements": [] + }, + { + "file": "movie-detail-390-geometry.json", + "width": 390, + "scrollWidth": 390, + "elements": [] + }, + { + "file": "movie-detail-768-geometry.json", + "width": 768, + "scrollWidth": 768, + "elements": [] + }, + { + "file": "movies-1788-geometry.json", + "width": 1788, + "scrollWidth": 1788, + "elements": [] + }, + { + "file": "movies-390-geometry.json", + "width": 390, + "scrollWidth": 390, + "elements": [ + { + "tag": "DIV", + "class": "availability-quality-control ", + "width": 277, + "right": 493 + }, + { + "tag": "BUTTON", + "class": "availability-quality-option availability-quality-option-active", + "width": 48, + "right": 393 + }, + { + "tag": "BUTTON", + "class": "availability-quality-option ", + "width": 51, + "right": 444 + }, + { + "tag": "BUTTON", + "class": "availability-quality-option ", + "width": 48, + "right": 492 + }, + { + "tag": "INPUT", + "class": "app-filter-search-input", + "width": 32, + "right": 403 + }, + { + "tag": "BUTTON", + "class": "app-control-shadow-exempt app-filter-select-trigger", + "width": 81, + "right": 407 + }, + { + "tag": "BUTTON", + "class": "app-control-shadow-exempt app-filter-select-trigger", + "width": 81, + "right": 416 + }, + { + "tag": "svg", + "class": {}, + "width": 18, + "right": 400 + }, + { + "tag": "path", + "class": {}, + "width": 12.375, + "right": 397.2015380859375 + }, + { + "tag": "BUTTON", + "class": "app-control-shadow-exempt app-filter-select-trigger app-filter-select-trigger-rating", + "width": 81, + "right": 407 + }, + { + "tag": "BUTTON", + "class": "app-control-shadow-exempt app-filter-select-trigger", + "width": 81, + "right": 459 + }, + { + "tag": "SPAN", + "class": "", + "width": 23, + "right": 417 + }, + { + "tag": "svg", + "class": {}, + "width": 18, + "right": 443 + }, + { + "tag": "path", + "class": {}, + "width": 12.375, + "right": 440.2015380859375 + }, + { + "tag": "BUTTON", + "class": "app-filter-button app-filter-button-idle", + "width": 198, + "right": 414 + }, + { + "tag": "svg", + "class": {}, + "width": 18, + "right": 397 + }, + { + "tag": "path", + "class": {}, + "width": 12.375, + "right": 394.2015380859375 + }, + { + "tag": "BUTTON", + "class": "persius-chip", + "width": 88, + "right": 404 + } + ] + }, + { + "file": "movies-768-geometry.json", + "width": 768, + "scrollWidth": 768, + "elements": [] + }, + { + "file": "narrations-1736-geometry.json", + "width": 1736, + "scrollWidth": 1736, + "elements": [ + { + "tag": "IMG", + "class": "persius-detail-backdrop", + "width": 1518, + "right": 1775 + } + ] + }, + { + "file": "narrations-390-geometry.json", + "width": 390, + "scrollWidth": 390, + "elements": [ + { + "tag": "IMG", + "class": "persius-detail-backdrop", + "width": 448.5, + "right": 419.25 + } + ] + }, + { + "file": "narrations-768-geometry.json", + "width": 768, + "scrollWidth": 768, + "elements": [ + { + "tag": "IMG", + "class": "persius-detail-backdrop", + "width": 883.199951171875, + "right": 825.5999755859375 + } + ] + }, + { + "file": "requests-1726-geometry.json", + "width": 1726, + "scrollWidth": 1726, + "elements": [] + }, + { + "file": "requests-390-geometry.json", + "width": 390, + "scrollWidth": 390, + "elements": [] + }, + { + "file": "requests-768-geometry.json", + "width": 768, + "scrollWidth": 768, + "elements": [] + }, + { + "file": "series-1776-geometry.json", + "width": 1776, + "scrollWidth": 1776, + "elements": [] + }, + { + "file": "series-390-geometry.json", + "width": 390, + "scrollWidth": 390, + "elements": [ + { + "tag": "DIV", + "class": "availability-quality-control ", + "width": 277, + "right": 493 + }, + { + "tag": "BUTTON", + "class": "availability-quality-option availability-quality-option-active", + "width": 48, + "right": 393 + }, + { + "tag": "BUTTON", + "class": "availability-quality-option ", + "width": 51, + "right": 444 + }, + { + "tag": "BUTTON", + "class": "availability-quality-option ", + "width": 48, + "right": 492 + }, + { + "tag": "INPUT", + "class": "app-filter-search-input", + "width": 32, + "right": 403 + }, + { + "tag": "BUTTON", + "class": "app-control-shadow-exempt app-filter-select-trigger", + "width": 81, + "right": 407 + }, + { + "tag": "BUTTON", + "class": "app-control-shadow-exempt app-filter-select-trigger", + "width": 81, + "right": 416 + }, + { + "tag": "svg", + "class": {}, + "width": 18, + "right": 400 + }, + { + "tag": "path", + "class": {}, + "width": 12.375, + "right": 397.2015380859375 + }, + { + "tag": "BUTTON", + "class": "app-control-shadow-exempt app-filter-select-trigger app-filter-select-trigger-rating", + "width": 81, + "right": 407 + }, + { + "tag": "BUTTON", + "class": "app-control-shadow-exempt app-filter-select-trigger", + "width": 81, + "right": 459 + }, + { + "tag": "SPAN", + "class": "", + "width": 23, + "right": 417 + }, + { + "tag": "svg", + "class": {}, + "width": 18, + "right": 443 + }, + { + "tag": "path", + "class": {}, + "width": 12.375, + "right": 440.2015380859375 + }, + { + "tag": "BUTTON", + "class": "app-filter-button app-filter-button-idle", + "width": 198, + "right": 414 + }, + { + "tag": "svg", + "class": {}, + "width": 18, + "right": 397 + }, + { + "tag": "path", + "class": {}, + "width": 12.375, + "right": 394.2015380859375 + }, + { + "tag": "BUTTON", + "class": "persius-chip", + "width": 88, + "right": 404 + } + ] + }, + { + "file": "series-768-geometry.json", + "width": 768, + "scrollWidth": 768, + "elements": [] + } + ], + "classicThemeComparison": { + "baselineCommit": "8a72b6db85e63b7560f5498194b22d33034d5d38", + "themes": [ + "seerrOrig", + "seerrNGJ" + ], + "routes": [ + "/discover/movies", + "/movie/101", + "/book/OL999W", + "/requests", + "/settings/main" + ], + "method": "Matched viewports and fixtures; completed route progress, loaded fonts, decoded images, disabled screenshot animations and two identical capture frames. No masking or injected style overrides.", + "observed": "18 captures have identical pixels. Two show text/gradient rasterization variation; 74,275 of the 74,291 changed pixels differ by only one channel level. Three pixels exceed an eight-level channel delta. No layout regression was observed.", + "captures": [ + { + "file": "seerrNGJ-book-detail-1782.png", + "viewport": [ + 1782, + 1060 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrNGJ-book-detail-390.png", + "viewport": [ + 390, + 844 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrNGJ-movie-detail-1782.png", + "viewport": [ + 1782, + 1060 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrNGJ-movie-detail-390.png", + "viewport": [ + 390, + 844 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrNGJ-movies-1782.png", + "viewport": [ + 1782, + 1060 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrNGJ-movies-390.png", + "viewport": [ + 390, + 844 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrNGJ-requests-1782.png", + "viewport": [ + 1782, + 1060 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrNGJ-requests-390.png", + "viewport": [ + 390, + 844 + ], + "changedPixels": 6, + "maxChannelDelta": 4, + "bounds": [ + 16, + 486, + 18, + 493 + ] + }, + { + "file": "seerrNGJ-settings-1782.png", + "viewport": [ + 1782, + 1060 + ], + "changedPixels": 74285, + "maxChannelDelta": 24, + "bounds": [ + 0, + 0, + 287, + 1047 + ] + }, + { + "file": "seerrNGJ-settings-390.png", + "viewport": [ + 390, + 844 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrOrig-book-detail-1782.png", + "viewport": [ + 1782, + 1060 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrOrig-book-detail-390.png", + "viewport": [ + 390, + 844 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrOrig-movie-detail-1782.png", + "viewport": [ + 1782, + 1060 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrOrig-movie-detail-390.png", + "viewport": [ + 390, + 844 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrOrig-movies-1782.png", + "viewport": [ + 1782, + 1060 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrOrig-movies-390.png", + "viewport": [ + 390, + 844 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrOrig-requests-1782.png", + "viewport": [ + 1782, + 1060 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrOrig-requests-390.png", + "viewport": [ + 390, + 844 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrOrig-settings-1782.png", + "viewport": [ + 1782, + 1060 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + }, + { + "file": "seerrOrig-settings-390.png", + "viewport": [ + 390, + 844 + ], + "changedPixels": 0, + "maxChannelDelta": 0, + "bounds": null + } + ] + }, + "screenshotSha256": { + "audiobooks-1726.png": "6b001da8eb3070043a5d9ab4288e3179ef3157918e7b143948671e8e6909b22f", + "audiobooks-390.png": "e882e413fdc5215193986e26ee0aa032c25dbab1b880c09a55db8b5fcece0fa1", + "audiobooks-768.png": "83bf7759478595b7b93cf8b250f3cd044d4515a4cb73591b16cffd65faab4fa7", + "books-1772.png": "7f119ae65bd42a2efa9a22e41d3e2a32e67639fe19cb77943bc5072cbd645a91", + "books-390.png": "90036fc04304d2d537398514b328dd794cad8b23bfb86e990c36f1b0cd0135ca", + "books-768.png": "1741d7488f29318de446cf68d602e39812890e7295c03122ce59b3dfbc9765cf", + "coming-soon-1760.png": "aa7016b1246bccc575116d16451bf990333e9f65fd0f9bf4198cae6e668e79e7", + "coming-soon-390.png": "bf31827161f25f29e7d83c6445c3acc94374602853ee76746f2700be27bb1be1", + "coming-soon-768.png": "5181c65c14e3d0df99bbb8f44bcd095b4ee86f18a9bdbc22238dcc43ab9e03c2", + "community-package.png": "4308b7e31f3ba47016e7d5723cdca77b56090f343c455fb1e9ca2674a67a45bf", + "discover-1782.png": "3318e37d11a17cfad6f30320df10ef1be9c4ff41c51518d60a03e50ed896bbaf", + "discover-390.png": "38b7064a793554b473a76e0e49b0fd2d999b9c965b51c694525b5c22731b043e", + "discover-768.png": "bb67095668c8412c8b8723eba1dbfb549ca4aa4f563b20729482668cc3aea6ad", + "movie-detail-1782.png": "5397408a5fe67e0805d53c828f28aebc97b2e0b444bbff7afe3df856427b608e", + "movie-detail-390.png": "c30592b9f20c7f874baf6bd91c05d5efde4667863d8f70517c357eec28247318", + "movie-detail-768.png": "1e4b220febf73cdae74dcf63ffa5c96537e35394fa5f67ad4dc5415780411d89", + "movies-1788.png": "e110b730e6fcf4fd71bcc94a4d68d3feebc7eee93f134e9154cce092cb947feb", + "movies-390.png": "ecf6d0f4c450ecde51b3566a7824a3c278bb33799e970a84fa0b043f75bc9a21", + "movies-768.png": "c8b367a9366e087e06bd5430504ef232e610f13c8ca0166a7d78d2d47fce3ac0", + "narrations-1736.png": "52309c4c77d3c4667062006660636db55f7aeb3296655edf4bf98482971160d1", + "narrations-390.png": "b57b6396e50fddb907c0ce962c3b5825f58b0fa951923a31c386f971a5e58fbd", + "narrations-768.png": "2e5ddfdfeb88d10ebbc46f759fdbbc33f24a739139a3ee476819931d9ffe62ed", + "requests-1726.png": "d286f06257397735498b69cb05ec3c26280d87fb4d1941fda935560f88eabb2b", + "requests-390.png": "f2a9774e02289a954825d733ccd73ecc264a27cfdb7765a30f01dc2817f0a1b7", + "requests-768.png": "3e3bc0a636685c92110db03a806591835fdcdd5df45df9eacb207b099b1d8625", + "requests-empty.png": "97f2f139f4969170d0c791acbcb4f4426f9ceef5cec6757b63bc5c71caced659", + "requests-error.png": "9e13aad90eaeb016525e43ac8f5ae9e4fefdb4f1e6cc321558592623f36b3728", + "requests-loading.png": "b29b5fec07c0f964eff7d7e624df4b540bb32123dbaa9f78418cd058f3549c6f", + "season-dialog-1776.png": "239348c9d3928d9a7df4830f7720401c99b97bd368a9f79b75c1d32c04ef141e", + "season-dialog-390.png": "7315b4d122272804d2c08d9930a9a80d356145f8628001ed1686c4f60cad998b", + "seerrNGJ-book-detail-1782.png": "74ea0ec95b244da749d6f3909109d2273a1d9de0e671e8f95d700516a3eebffa", + "seerrNGJ-book-detail-390.png": "d45aa66c4598e5556fc53e70b18c92a36bf277bf2bb7af3686caf0bf6482ea40", + "seerrNGJ-movie-detail-1782.png": "bc4cbc5f329a2f39a292e948208068ee461ebb4eb1bb0a026de7cfcfbacb175f", + "seerrNGJ-movie-detail-390.png": "bed7da706db15e1829f57a9b73a7f5bc0de517bd81f3c1ddb06f718f4bb5dd96", + "seerrNGJ-movies-1782.png": "53edd5338b88688fdfcd99b599cbdb51861ef58afd54c1fe1bdc01dc27676d65", + "seerrNGJ-movies-390.png": "1da34f4345bff1ccf0d319fba62eb0b3d4c95792711a91de7cf3306afae3a8a7", + "seerrNGJ-requests-1782.png": "13dbd368f2a518ea6dae94319972aa291c31dd8d7d97cd4578b1e6acb6dc6e76", + "seerrNGJ-requests-390.png": "4d1d6466b0cb9a6d42d837a5a819bc0c664f8e09dda02cfe8abb8a32410818bc", + "seerrNGJ-settings-1782.png": "a86b52111044429910f95e88a35aef74e4e1a0d1588e8f271adf614496e20288", + "seerrNGJ-settings-390.png": "ecf69674edac77580c51532a600ba50bf0a7f4d7f320b851c0e1b1768dc2706c", + "seerrOrig-book-detail-1782.png": "062bdeebdfd778681e90690f86c9be20aa3d20a18b9afbae4c3b2a156e6334a3", + "seerrOrig-book-detail-390.png": "9fded43c4888e0d3a44031208680856a347af5d61616325beb324d01adff8731", + "seerrOrig-movie-detail-1782.png": "451784ae35a0c9d7d0543d171cf5bde328fbf9d7a09a3adcb802f83a167c7383", + "seerrOrig-movie-detail-390.png": "7db51ec7c20b2c214e890d9783bda7c63adf65f17943b710115a835072d3634b", + "seerrOrig-movies-1782.png": "fd924f15ff9d7e9f60b3759c643af0adb5b73d1e63649d08f84960fece39e788", + "seerrOrig-movies-390.png": "ef7fe7ff16e05c5eb34141091dc91e8812ff627b5bb5558b8a184c5fdb3a9938", + "seerrOrig-requests-1782.png": "b729ecb13455b4c618f871c4c7ae50f094ef24fa804fb27c798e9c067f9178be", + "seerrOrig-requests-390.png": "b51954587be115fb3c1e2cfe1426d6e2b448de06d7043f726112cdf151907656", + "seerrOrig-settings-1782.png": "08a226dcb40578c5734a8d866663cf173b31a08eaa2288f527ce65569a060adf", + "seerrOrig-settings-390.png": "cb6434ce12e383f233dff65d0591facc5c63802501f7f16ace06b131de2ac9d7", + "series-1776.png": "c5876a98131745f30e8256cb4f9dd42368c396e7c3bc7bed81f9901a417e5b9a", + "series-390.png": "afe879240f57c79053a872e0904bc6cf1f0e24656b3e79b513339f4f716b8726", + "series-768.png": "cd87e11aed5a50846258eb96eb61769fff73c23defa8a34c1062d678fdd42ae0" + }, + "applicationSourceSha256": { + "bin/e2e-network-guard.cjs": "0d01478d643ce153aa53f11e3bbdf270077311b20d54bcb94e8132c832c3a022", + "bin/e2e-network-guard.test.mjs": "9b3d80516f534c7a569d8ee02b1e9837cc1762a297b16ff1bd54bc074cf830dd", + "bin/interface-theme-postgres-migration.test.mjs": "adcba223e2d0ecbcee62df1d02a4d12671881cb16d08118de82fa9b2e1944705", + "bin/run-cypress-start.mjs": "682147e800d94d2a8bf5a04c148a576d8ca3c476e9819fd713092e926ce93481", + "bin/run-tooling-tests.mjs": "ae6e79b54d0d46f620c2fc39fdc1f0713c6a632b9670d3d03b16e0cdb970723b", + "cypress/config/settings.cypress.json": "b279575c502104f7c3bbda7d966273e2458f295094212b8625f199a372fa0e82", + "playwright/persius-integration.spec.ts": "940607e313bb6bbf96b5481ba41d0b6124a922789fdc12232446b0929647ea63", + "server/test/fixtures/runner-report.fixture.ts": "df48c3535494d168497127e2adedc88138d3484c60bda2aa609d9c00d8f305fb", + "server/test/index.mts": "60f0d112684226ea2be6c35e1c0f5dcab56f382fa6bef45f93044df1e82dbb4a", + "server/test/runner.test.ts": "5d29a6c83ab0550225e1a32ec5bbf08ff4aa332b75437bbf40c45f4441e8f3a2", + "src/components/Common/ConfirmButton/index.tsx": "a0da333a35fab73248e15b9e9dbb54fd02032e06f9723b611383c7f3556ce5e2", + "src/components/Common/ListView/index.tsx": "f2f8647eac555ce4b696de39876de23ab9f5aec9bb15ae6691bb8c8c9722a1e3", + "src/components/Common/Modal/index.tsx": "db7dd91b51478d7c2fb9e9703df7b270a138f651222c4e74a579f8db48dccbfc", + "src/components/MovieDetails/index.tsx": "b28ebca49709a6e34b38470d4cbeb58895f14891f2fb193eac3ff1d69e79848c", + "src/components/Persius/Requests.tsx": "cde0ebad488d955a3a1e3decd131ff6a61ede93bca60c7b4139f3b95bb3d5cc2", + "src/components/Persius/useDialogFocus.ts": "12a689071e9da709aa7c36741ce271e4fed867162820e77c50715d531d708d8c", + "src/components/Persius/useDialogFocus.vitest.test.tsx": "57dc3c64462181f00ff6c9fb58b9ee98ecc96d9a0cd620c2f02e40d82b08f7f5", + "src/components/RequestModal/RequestSeasonEpisodeTree.tsx": "2935dae10ec8460de1a5e32e7e440251cced937292e16023e6ca10904b15bebf", + "src/components/RequestModal/TvRequestModal.tree.test.tsx": "204ce7c433645f429a24995db9a8b505bc66d79bf835ebe118f7bee93f024609", + "src/components/RequestModal/TvRequestModal.tsx": "2173cf5bf9a18e6d14348e267d7378f3266d572206498ee1bf33b9a1b6f85f7e", + "src/components/Requests/index.tsx": "00ef72117ee195f0f77dd8c4b1e8d7d63c20df7b76fc45976a306a150556731e", + "src/styles/buttonGeometry.test.mjs": "4a20ca6f343dd4b0448606e7fecf61b477d47d486a4f6cb1edfc9170eec9027b", + "themes/persiusNG/theme.css": "05612825b7b89d144a4d47cdbd4e9220fc43374aa4505c8582761c0571a75352", + ".prettierignore": "25e62940d38df0b5b7d96915d6eeb90d7f95763c4b0c74f0b577e51a44a0406b", + "prettier-scope.txt": "25e62940d38df0b5b7d96915d6eeb90d7f95763c4b0c74f0b577e51a44a0406b", + "server/test/fixtures/delayed-reporter.fixture.mjs": "f10bb12c76100878c3fc2cdbc5c4a16f4c01ebdc7c94df0a79dd8fbc66466231", + "server/test/worker-bootstrap.cjs": "509429df4803841ddd423dcbeca30e05e3b20091e6992aef059f8df02e8a3efe" + }, + "boundaries": [ + "Real local sign-in, account preference writes, production native routes and same-origin theme catalog/CSS are exercised.", + "Catalog, service reads and artwork are deterministic browser fixtures. The test server and browser reject unhandled external network destinations.", + "Artwork is cropped from historical low-resolution contact-sheet evidence; it is not shipped as runtime artwork and does not establish original-artwork pixel parity.", + "Native PostgreSQL tests require a disposable external database and remain skipped here.", + "Cypress binary installation returned an invalid/truncated archive; Cypress was not executed.", + "Live provider acquisition and external playback were not performed.", + "Full Vitest preceded the final small presentation/fallback and runner changes; focused tests, native browser tests and the final production build cover those changes.", + "No CI dispatch, merge, deployment or external UI proxy configuration change was performed." + ] +} diff --git a/docs/interface-themes/evidence/persiusng-render-measurements.json b/docs/interface-themes/evidence/persiusng-render-measurements.json new file mode 100644 index 0000000000..50e5ea5724 --- /dev/null +++ b/docs/interface-themes/evidence/persiusng-render-measurements.json @@ -0,0 +1,411 @@ +{ + "renders": [ + { + "story": "discover", + "width": 1782, + "height": 1055, + "scrollWidth": 1782, + "viewport": 1782, + "boxes": { + ".sidebar": { + "x": 0, + "y": 0, + "w": 244, + "h": 1055 + }, + ".app-search-input": { + "x": 284, + "y": 13.5, + "w": 560, + "h": 42 + }, + ".persius-hero": { + "x": 396, + "y": 294.84375, + "w": 564, + "h": 352 + }, + "[data-poster-region=\"frame\"]": { + "x": 396, + "y": 732.84375, + "w": 164, + "h": 246 + }, + ".persius-request": null, + ".persius-release": null, + ".persius-season": null, + ".page-overlay-card": null + } + }, + { + "story": "movies", + "width": 1788, + "height": 1038, + "scrollWidth": 1788, + "viewport": 1788, + "boxes": { + ".sidebar": { + "x": 0, + "y": 0, + "w": 244, + "h": 1038 + }, + ".app-search-input": { + "x": 284, + "y": 13.5, + "w": 560, + "h": 42 + }, + ".persius-hero": null, + "[data-poster-region=\"frame\"]": { + "x": 396, + "y": 336, + "w": 191.65625, + "h": 287.484375 + }, + ".persius-request": null, + ".persius-release": null, + ".persius-season": null, + ".page-overlay-card": null + } + }, + { + "story": "detail", + "width": 1782, + "height": 1060, + "scrollWidth": 1782, + "viewport": 1782, + "boxes": { + ".sidebar": { + "x": 0, + "y": 0, + "w": 244, + "h": 1060 + }, + ".app-search-input": { + "x": 284, + "y": 13.5, + "w": 560, + "h": 42 + }, + ".persius-hero": null, + "[data-poster-region=\"frame\"]": null, + ".persius-request": null, + ".persius-release": null, + ".persius-season": null, + ".page-overlay-card": null + } + }, + { + "story": "seasons", + "width": 1776, + "height": 1058, + "scrollWidth": 1776, + "viewport": 1776, + "boxes": { + ".sidebar": { + "x": 0, + "y": 0, + "w": 244, + "h": 1058 + }, + ".app-search-input": { + "x": 284, + "y": 13.5, + "w": 560, + "h": 42 + }, + ".persius-hero": null, + "[data-poster-region=\"frame\"]": { + "x": 396, + "y": 336, + "w": 191.65625, + "h": 287.484375 + }, + ".persius-request": null, + ".persius-release": null, + ".persius-season": { + "x": 600, + "y": 241, + "w": 576, + "h": 65 + }, + ".page-overlay-card": { + "x": 568, + "y": 69, + "w": 640, + "h": 920 + } + } + }, + { + "story": "books", + "width": 1772, + "height": 1064, + "scrollWidth": 1772, + "viewport": 1772, + "boxes": { + ".sidebar": { + "x": 0, + "y": 0, + "w": 244, + "h": 1064 + }, + ".app-search-input": { + "x": 284, + "y": 13.5, + "w": 560, + "h": 42 + }, + ".persius-hero": null, + "[data-poster-region=\"frame\"]": { + "x": 396, + "y": 609, + "w": 191.65625, + "h": 287.484375 + }, + ".persius-request": null, + ".persius-release": null, + ".persius-season": null, + ".page-overlay-card": null + } + }, + { + "story": "audio", + "width": 1726, + "height": 1061, + "scrollWidth": 1726, + "viewport": 1726, + "boxes": { + ".sidebar": { + "x": 0, + "y": 0, + "w": 244, + "h": 1061 + }, + ".app-search-input": { + "x": 284, + "y": 13.5, + "w": 560, + "h": 42 + }, + ".persius-hero": null, + "[data-poster-region=\"frame\"]": { + "x": 396, + "y": 483.390625, + "w": 180, + "h": 180 + }, + ".persius-request": null, + ".persius-release": null, + ".persius-season": null, + ".page-overlay-card": null + } + }, + { + "story": "narrations", + "width": 1736, + "height": 1046, + "scrollWidth": 1736, + "viewport": 1736, + "boxes": { + ".sidebar": { + "x": 0, + "y": 0, + "w": 244, + "h": 1046 + }, + ".app-search-input": { + "x": 284, + "y": 13.5, + "w": 560, + "h": 42 + }, + ".persius-hero": null, + "[data-poster-region=\"frame\"]": null, + ".persius-request": null, + ".persius-release": null, + ".persius-season": null, + ".page-overlay-card": null + } + }, + { + "story": "requests", + "width": 1726, + "height": 1067, + "scrollWidth": 1726, + "viewport": 1726, + "boxes": { + ".sidebar": { + "x": 0, + "y": 0, + "w": 244, + "h": 1067 + }, + ".app-search-input": { + "x": 284, + "y": 13.5, + "w": 560, + "h": 42 + }, + ".persius-hero": null, + "[data-poster-region=\"frame\"]": null, + ".persius-request": { + "x": 396, + "y": 283.75, + "w": 615, + "h": 136 + }, + ".persius-release": null, + ".persius-season": null, + ".page-overlay-card": null + } + }, + { + "story": "coming", + "width": 1760, + "height": 1055, + "scrollWidth": 1760, + "viewport": 1760, + "boxes": { + ".sidebar": { + "x": 0, + "y": 0, + "w": 244, + "h": 1055 + }, + ".app-search-input": { + "x": 284, + "y": 13.5, + "w": 560, + "h": 42 + }, + ".persius-hero": null, + "[data-poster-region=\"frame\"]": null, + ".persius-request": null, + ".persius-release": { + "x": 396, + "y": 244, + "w": 408, + "h": 104 + }, + ".persius-season": null, + ".page-overlay-card": null + } + }, + { + "story": "discover", + "width": 390, + "overflow": 0 + }, + { + "story": "movies", + "width": 390, + "overflow": 0 + }, + { + "story": "detail", + "width": 390, + "overflow": 0 + }, + { + "story": "seasons", + "width": 390, + "overflow": 0 + }, + { + "story": "books", + "width": 390, + "overflow": 0 + }, + { + "story": "audio", + "width": 390, + "overflow": 0 + }, + { + "story": "narrations", + "width": 390, + "overflow": 0 + }, + { + "story": "requests", + "width": 390, + "overflow": 0 + }, + { + "story": "coming", + "width": 390, + "overflow": 0 + }, + { + "story": "discover", + "width": 768, + "overflow": 0 + }, + { + "story": "movies", + "width": 768, + "overflow": 0 + }, + { + "story": "detail", + "width": 768, + "overflow": 0 + }, + { + "story": "seasons", + "width": 768, + "overflow": 0 + }, + { + "story": "books", + "width": 768, + "overflow": 0 + }, + { + "story": "audio", + "width": 768, + "overflow": 0 + }, + { + "story": "narrations", + "width": 768, + "overflow": 0 + }, + { + "story": "requests", + "width": 768, + "overflow": 0 + }, + { + "story": "coming", + "width": 768, + "overflow": 0 + } + ], + "checks": [ + "season clear/latest/entire/individual selection", + "native future-season switch pointer and keyboard state", + "dialog focus trap, search shortcut suppression, trigger focus restoration", + "unavailable season and episode excluded from shortcuts", + "narration choice auto-selects missing recording and hides duplicate available request", + "search shortcut/editing, light mode and interface switch round trip", + "renamed custom theme retains native sidebar, profile and request composition with its own CSS palette and flat navigation" + ], + "errors": [], + "legacyComparisons": [ + { + "theme": "seerrOrig", + "width": 1782, + "height": 1060, + "changedPixels": 0 + }, + { + "theme": "seerrNGJ", + "width": 1782, + "height": 1060, + "changedPixels": 0 + } + ] +} diff --git a/docs/interface-themes/feature-map.md b/docs/interface-themes/feature-map.md index 133e8eaf6b..7db55a488a 100644 --- a/docs/interface-themes/feature-map.md +++ b/docs/interface-themes/feature-map.md @@ -12,14 +12,14 @@ request semantics. ## Design systems -| Design area | SeerrOrig | SeerrNGJ | -| --- | --- | --- | -| Primary nav | One flat list in upstream order: Discover, Movies, Series, Requests, Blocklist, Issues, Users, Settings; current extra routes follow the core links | Grouped headings and nested acquisition/discovery links, matching the current SeerrNG navigation model | -| Surfaces and color | Slate-gray page and sidebar, gray-800 cards, compact borders, indigo-to-purple selected nav, original Seerr gradients | Deep navy background, blue/silver chrome, blue selected nav, colored media/status controls, layered borders and restrained glow | -| Discovery cards | 150px-wide classic poster cards, tighter corners, understated frame and bottom title gradient | 169.2px poster cards, rounded framed surface, blue/silver edge, stronger hover elevation and data-dense badges | -| Detail pages | Centered poster/title at narrow widths; poster and title align horizontally at wide widths; facts in a compact slate card | Left-anchored hero, framed poster, blue contrast, overview paired with a right facts rail at wide widths | -| Custom media | Preserve current media types and controls while using the compact Orig poster and card roles | Preserve current data-rich poster badges and use the NGJ frame, category accents, and detail arrangement | -| Interaction | Keep current SeerrNG actions and accessibility contracts; apply original visual geometry and ordering where the upstream component still has the same concept | Keep the current grouped workflows and John-specific visual order, controls, and shapes | +| Design area | SeerrOrig | SeerrNGJ | +| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| Primary nav | One flat list in upstream order: Discover, Movies, Series, Requests, Blocklist, Issues, Users, Settings; current extra routes follow the core links | Grouped headings and nested acquisition/discovery links, matching the current SeerrNG navigation model | +| Surfaces and color | Slate-gray page and sidebar, gray-800 cards, compact borders, indigo-to-purple selected nav, original Seerr gradients | Deep navy background, blue/silver chrome, blue selected nav, colored media/status controls, layered borders and restrained glow | +| Discovery cards | 150px-wide classic poster cards, tighter corners, understated frame and bottom title gradient | 169.2px poster cards, rounded framed surface, blue/silver edge, stronger hover elevation and data-dense badges | +| Detail pages | Centered poster/title at narrow widths; poster and title align horizontally at wide widths; facts in a compact slate card | Left-anchored hero, framed poster, blue contrast, overview paired with a right facts rail at wide widths | +| Custom media | Preserve current media types and controls while using the compact Orig poster and card roles | Preserve current data-rich poster badges and use the NGJ frame, category accents, and detail arrangement | +| Interaction | Keep current SeerrNG actions and accessibility contracts; apply original visual geometry and ordering where the upstream component still has the same concept | Keep the current grouped workflows and John-specific visual order, controls, and shapes | ## Route-family coverage map @@ -30,23 +30,23 @@ application-owned, while layout, surfaces, spacing, and poster geometry come from the selected package. The matrix records where to audit behavior and theme parity; it does not imply that each listed route has already passed visual review. -| Feature family | Current route source | Shared visual contracts to audit | Theme-specific expression | -| --- | --- | --- | --- | -| Home and discovery shelves | `src/pages/index.tsx`, `src/pages/discover/**` | page title, section shelves, filters, poster grid/slider, empty/loading/error states | Orig uses compact shelves and classic poster cards; NGJ uses grouped sections, expanded card frames, and vivid category badges | -| Video catalogs | `src/pages/discover/movies/**`, `src/pages/discover/tv/**` | filter bars, grid sizing, pagination, provider/genre facets, poster actions | Orig restores upstream filter and poster density; NGJ keeps expanded filters, detail badges, and current card emphasis | -| Video details | `src/pages/movie/**`, `src/pages/tv/**`, `src/pages/series/**`, `src/pages/collection/**`, `src/pages/franchise/**` | hero, title metadata, overview, facts, ratings, cast/crew, recommendations/similar, request and playback actions | Orig uses upstream centered-to-horizontal hero and compact facts; NGJ uses left-anchored hero and split overview/facts composition | -| Music and artist catalog | `src/pages/discover/music/**`, `src/pages/music/**`, `src/pages/artist/**` | artist/album posters, quality and library state, ratings, discography and actions | Orig keeps the compact poster and simple card frame while retaining music-specific labels; NGJ keeps album quality/status badges and colored controls | -| Books and audiobooks | `src/pages/discover/books/**`, `src/pages/discover/audiobooks/**`, `src/pages/discover/book-recommendations.tsx`, `src/pages/book/**`, `src/pages/author/**`, `src/pages/book-series/**` | format badges, author and series navigation, request-format choices, reading/list state | Orig uses the familiar poster and flat metadata rhythm; NGJ emphasizes format/status slots and grouped recommendations | -| Comics and magazines | `src/pages/discover/comics/**`, `src/pages/discover/magazines/**`, `src/pages/comic/**`, `src/pages/magazine/**` | identity, issue/tracking state, request availability, cover ratio, status and error states | Preserve cover aspect and tracking semantics in both; vary frame, badge geometry, and facts layout | -| Software and games | `src/pages/software.tsx`, `src/pages/games.tsx`, `src/pages/discover/games.tsx`, `src/pages/sportarr/**` | platform/library badges, compatibility facts, monitoring/request state, safe external actions | Orig uses a subdued catalog card; NGJ keeps high-contrast library and monitoring states with category-coded badges | -| Sports, adult, and people | `src/pages/discover/sports/**`, `src/pages/discover/adult/**`, `src/pages/adult/**`, `src/pages/person/**` | eligibility/age gate, external identity, role/credit hierarchy, request availability | Preserve policy and role distinctions; change card proportion, hierarchy, and badge treatment per system | -| Requests and acquisition | `src/pages/requests/**`, `src/pages/track-requests.tsx`, `src/pages/downloads.tsx`, `src/pages/indexer-search.tsx`, shared request modals | queue/list hierarchy, status, quality, form validation, destructive actions, busy/error feedback | Orig follows compact upstream request rhythm; NGJ uses denser grouped panels and strong status accents | -| Libraries and saved items | `src/pages/library.tsx`, `src/pages/games.tsx`, `src/pages/profile/watchlist.tsx`, `src/pages/discover/watchlist.tsx`, `src/pages/collections/**` | tabs, sort/filter, watchlist actions, collection hierarchy, availability and empty states | Orig uses flat gray cards and upstream spacing; NGJ separates groups with framed panels and badge-led states | -| Following, calendar, swipe, sharing | `src/pages/following.tsx`, `src/pages/calendar.tsx`, `src/pages/swipe.tsx`, `src/pages/share.tsx`, `src/pages/identify.tsx` | timeline/list hierarchy, swipe hit targets, identity and sharing safety, overlays | Orig uses simple surfaces and classic action rows; NGJ uses grouped cards, category framing, and strong selected states | -| Issues and blocklist | `src/pages/issues/**`, `src/pages/blocklist/**` | triage, issue detail, permissions, confirm/cancel, hidden-item and recovery state | Orig keeps flat tables/cards and compact confirmation; NGJ distinguishes destructive and review states with color and framed panels | -| User management and profile | `src/pages/users/**`, `src/pages/profile/**` | permissions, linked accounts, notification forms, user request queues, account theme choices | Orig follows upstream compact form and profile hierarchy; NGJ uses grouped form sections and framed information cards | -| Admin and integrations | `src/pages/settings/**`, `src/pages/setup.tsx` | service setup, connection state, credentials, jobs/logs, category controls, warnings | Orig uses original Seerr slate panels and straightforward rows; NGJ uses blue/silver service panels and distinct status/action colors | -| Authentication and recovery | `src/pages/login/**`, `src/pages/resetpassword/**`, `src/pages/404.tsx`, `src/pages/_error.tsx` | keyboard access, error recovery, auth return path, disabled and loading states | Orig restores upstream visual weight and straightforward buttons; NGJ uses current shell/brand treatment without changing auth behavior | +| Feature family | Current route source | Shared visual contracts to audit | Theme-specific expression | +| ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | +| Home and discovery shelves | `src/pages/index.tsx`, `src/pages/discover/**` | page title, section shelves, filters, poster grid/slider, empty/loading/error states | Orig uses compact shelves and classic poster cards; NGJ uses grouped sections, expanded card frames, and vivid category badges | +| Video catalogs | `src/pages/discover/movies/**`, `src/pages/discover/tv/**` | filter bars, grid sizing, pagination, provider/genre facets, poster actions | Orig restores upstream filter and poster density; NGJ keeps expanded filters, detail badges, and current card emphasis | +| Video details | `src/pages/movie/**`, `src/pages/tv/**`, `src/pages/series/**`, `src/pages/collection/**`, `src/pages/franchise/**` | hero, title metadata, overview, facts, ratings, cast/crew, recommendations/similar, request and playback actions | Orig uses upstream centered-to-horizontal hero and compact facts; NGJ uses left-anchored hero and split overview/facts composition | +| Music and artist catalog | `src/pages/discover/music/**`, `src/pages/music/**`, `src/pages/artist/**` | artist/album posters, quality and library state, ratings, discography and actions | Orig keeps the compact poster and simple card frame while retaining music-specific labels; NGJ keeps album quality/status badges and colored controls | +| Books and audiobooks | `src/pages/discover/books/**`, `src/pages/discover/audiobooks/**`, `src/pages/discover/book-recommendations.tsx`, `src/pages/book/**`, `src/pages/author/**`, `src/pages/book-series/**` | format badges, author and series navigation, request-format choices, reading/list state | Orig uses the familiar poster and flat metadata rhythm; NGJ emphasizes format/status slots and grouped recommendations | +| Comics and magazines | `src/pages/discover/comics/**`, `src/pages/discover/magazines/**`, `src/pages/comic/**`, `src/pages/magazine/**` | identity, issue/tracking state, request availability, cover ratio, status and error states | Preserve cover aspect and tracking semantics in both; vary frame, badge geometry, and facts layout | +| Software and games | `src/pages/software.tsx`, `src/pages/games.tsx`, `src/pages/discover/games.tsx`, `src/pages/sportarr/**` | platform/library badges, compatibility facts, monitoring/request state, safe external actions | Orig uses a subdued catalog card; NGJ keeps high-contrast library and monitoring states with category-coded badges | +| Sports, adult, and people | `src/pages/discover/sports/**`, `src/pages/discover/adult/**`, `src/pages/adult/**`, `src/pages/person/**` | eligibility/age gate, external identity, role/credit hierarchy, request availability | Preserve policy and role distinctions; change card proportion, hierarchy, and badge treatment per system | +| Requests and acquisition | `src/pages/requests/**`, `src/pages/track-requests.tsx`, `src/pages/downloads.tsx`, `src/pages/indexer-search.tsx`, shared request modals | queue/list hierarchy, status, quality, form validation, destructive actions, busy/error feedback | Orig follows compact upstream request rhythm; NGJ uses denser grouped panels and strong status accents | +| Libraries and saved items | `src/pages/library.tsx`, `src/pages/games.tsx`, `src/pages/profile/watchlist.tsx`, `src/pages/discover/watchlist.tsx`, `src/pages/collections/**` | tabs, sort/filter, watchlist actions, collection hierarchy, availability and empty states | Orig uses flat gray cards and upstream spacing; NGJ separates groups with framed panels and badge-led states | +| Following, calendar, swipe, sharing | `src/pages/following.tsx`, `src/pages/calendar.tsx`, `src/pages/swipe.tsx`, `src/pages/share.tsx`, `src/pages/identify.tsx` | timeline/list hierarchy, swipe hit targets, identity and sharing safety, overlays | Orig uses simple surfaces and classic action rows; NGJ uses grouped cards, category framing, and strong selected states | +| Issues and blocklist | `src/pages/issues/**`, `src/pages/blocklist/**` | triage, issue detail, permissions, confirm/cancel, hidden-item and recovery state | Orig keeps flat tables/cards and compact confirmation; NGJ distinguishes destructive and review states with color and framed panels | +| User management and profile | `src/pages/users/**`, `src/pages/profile/**` | permissions, linked accounts, notification forms, user request queues, account theme choices | Orig follows upstream compact form and profile hierarchy; NGJ uses grouped form sections and framed information cards | +| Admin and integrations | `src/pages/settings/**`, `src/pages/setup.tsx` | service setup, connection state, credentials, jobs/logs, category controls, warnings | Orig uses original Seerr slate panels and straightforward rows; NGJ uses blue/silver service panels and distinct status/action colors | +| Authentication and recovery | `src/pages/login/**`, `src/pages/resetpassword/**`, `src/pages/404.tsx`, `src/pages/_error.tsx` | keyboard access, error recovery, auth return path, disabled and loading states | Orig restores upstream visual weight and straightforward buttons; NGJ uses current shell/brand treatment without changing auth behavior | ## Behavior and component contract boundaries @@ -72,3 +72,35 @@ There are 149 files under `src/pages/` in the rebuilt checkout. Route families above are the audit map, not a claim that 149 routes have already been rendered. See `implementation-status.md` for the current gate status and remaining coverage. + +## Persius and custom native compositions + +PersiusNG is a third built-in stylesheet and opts into the application-owned +`persius` composition. Installed community themes can opt into the same +composition through their validated manifest while keeping a separate ID and +stylesheet. The existing composition remains the default for older packages. +Neither choice needs a UI-rewriting proxy or additional theme JavaScript. + +The nine reference routes, dimensions, retained controls, responsive checks and +native browser evidence and release-environment boundaries are recorded in +[PersiusNG](persiusng.md). All +other routes still use the shared native owners above. Permission/service +filtering and backend features remain application-owned in every composition. +Use the [authoring guide](authoring.md) to build independent packages and the +[submission checklist](submitting.md) to document route and state coverage. + + +## Native Persius verification scope — 2026-10-31 + +The nine reference flows above now run in the production app with local sign-in, +real theme APIs and account persistence. Catalog/provider reads are fixtures; +no UI rewriting is involved. The current `/requests` route uses native status +snapshots and history, with compact presentation retaining the same permissions +and request mutations. The supported composition also works for an installed, +independently named community stylesheet. + +Representative classic-theme comparison routes are movies, movie detail, book +detail, requests and settings at matching desktop and phone viewports. This +bounded evidence does not establish visual acceptance for every route in the +broader family inventory. See the [verification report](evidence/persiusng-native-verification.json) +and [integration checkpoint](integration-checkpoint-20261030.md). diff --git a/docs/interface-themes/implementation-status.md b/docs/interface-themes/implementation-status.md index 012c17d9ae..ecf681ba8c 100644 --- a/docs/interface-themes/implementation-status.md +++ b/docs/interface-themes/implementation-status.md @@ -1,92 +1,59 @@ -# SeerrOrig / SeerrNGJ Rebuild Status +# SeerrOrig / SeerrNGJ Theme Package Readiness -This is the working status record for the two-interface rebuild. Update it in -the same commit as each implementation slice. A source change is not visual -acceptance: rendered review stays unverified until the application has been -captured at matching viewports and states. +Updated 2026-10-29 against the local verification worktree for draft PR #416. The package implementation and all available local automated gates have been rechecked. This record separates those results from checks that require external infrastructure or live visual acceptance. + +## Current integration follow-up — 2026-10-31 + +The restored checkout now has the native PersiusNG implementation, production +OpenAPI theme routes, current Requests page integration, recording retargeting, +independent community packages and authoring/submission documentation integrated. +The full native Vitest suite passes (4,525 tests; five database-dependent skips), and the +production server/Next.js build passes. Signed-in browser evidence now covers the +nine reference flows, native account preferences and an installed community theme. +The native Node suite also passes (3,819 tests; five database-dependent skips), +with complete matching terminal and archive reports. + +Use the [current integration checkpoint](integration-checkpoint-20261030.md) for +final check totals, old-theme comparisons and explicit release-environment gates. +The entries below are historical slices, including their former open gates; +they are not the current cumulative result. This work does not deploy or merge +the draft PR, and does not claim pixel-identical live catalog content. ## Implementation basis -- Rebuild base: `snapetech-org/seerrng` `main`, commit - `4f5541aa5d83cb95e2cbd214ebda72d025d5daf6`. -- Exact original UI reference: Seerr `v3.5.1`, commit - `564bfb08b54caa374bddaf820abfd226e5e69151`. -- Engine/backend decision: keep the SeerrNG engine, APIs, provider integrations, - database, and current dependency contracts. Upstream v3.5.1 is the visual and - interaction reference for SeerrOrig, not a backend rollback target. +- Keep the SeerrNG engine, backend, APIs, provider integrations, database, permission checks, migrations, and dependency contracts. +- Use Seerr `v3.5.1` (`564bfb08b54caa374bddaf820abfd226e5e69151`) as the visual and interaction reference for SeerrOrig only; do not roll the backend back to upstream Seerr. +- SeerrOrig restores the flatter upstream navigation, compact catalog cards, denser slate surfaces, and original detail-page flow. SeerrNGJ retains John's grouped navigation, larger cards, blue/silver surfaces, framed cards, and split detail layouts. Both themes use the same feature components and route/API semantics. + +## Theme package architecture + +- `src/styles/globals.css` owns resets, Tailwind foundations, palette infrastructure, shared interaction behavior, and structural component styles. Built-in theme tokens for geometry, spacing, poster sizing, compact cards, detail rows, controls, and menu surfaces live in the selected theme package. +- `src/styles/interfaceThemes/shared.css` maps semantic component roles to theme tokens. `themes/seerrOrig/` and `themes/seerrNGJ/` each ship a manifest and complete scoped stylesheet with their own colors, layout, navigation, discovery, card, detail, settings, table, and responsive rules. +- The theme provider activates only the selected stylesheet from the same-origin API after load and account preference resolution. `_document` starts with SeerrOrig before hydration. Theme selection remains independent of the palette and advanced-color controls. +- The comparison fixture embeds production shared CSS and both package stylesheets. JSDOM tests confirm source parity and distinct poster, filter, detail, settings, navigation, and token values. The fixture is not a live application render. + +## Custom theme authoring and safety -## Rebuilt in this slice +- A package is a directory containing `manifest.json` and `theme.css`; `.seerrtheme` distributions are JSON data and are never extracted as archives. +- `docs/interface-themes/authoring.md`, `manifest.schema.json`, and `template/` document the API version, scoping, layout tokens, packaging workflow, and checksums. +- The `interface-theme` CLI supports validate, pack, install, explicit replace, and uninstall. Installs are staged before activation; built-ins cannot be overwritten or removed. +- Validation covers manifest versions and fields, CSS syntax and scope, escaped/comment-split resource functions, at-rules and keyframe namespaces, and package/file/count/nesting limits. Installed CSS is revalidated before serving. The stylesheet endpoint uses `nosniff` and `Cross-Origin-Resource-Policy: same-origin`. +- API v1 packages are CSS-only: no JavaScript, HTML, fonts, images, or external resources. CSS can still hide existing controls, which the authoring guide documents. -- Added the account-level `interfaceTheme` preference with the stable values - `seerrOrig` and `seerrNGJ`; the default is `seerrOrig`. -- Added an own-profile API write route and SQLite/PostgreSQL migrations. - Accounts with the explicit legacy `john-redesign` preset migrate to NGJ; - other accounts use the new Orig default. -- Added a theme selector separate from the existing palette and advanced-color - controls. `_document` starts on SeerrOrig before hydration; the authenticated - account profile is restored as soon as user settings load. -- Added three independently owned stylesheets in - `src/styles/interfaceThemes/`. Each has its own navigation, poster, detail, - card, form, table, and surface rules. -- Expanded theme coverage to current video and cross-media detail roles, - acquisition cards, issue/blocklist summaries, service settings, and data - tables. The route components retain their existing behavior and contracts. -- Extracted theme-specific navigation presentation into a tested helper: - SeerrOrig flattens and orders the original core links while retaining current - visibility filtering; SeerrNGJ keeps the grouped SeerrNG navigation. -- Expanded the side-by-side static comparison harness with discovery, an - audiobook detail, a request action, and service administration examples. It - loads the same profile stylesheets used by the application. -- Added the initial route-family feature map and this implementation record. +## Local verification completed -## Verification status +- Full Node suite: **3,760 passed, 5 skipped, 0 failed** (3,765 total) with `corepack pnpm@10.24.0 test:node --test-concurrency 4`. The skips are the live PostgreSQL request-status and migration execution tests. +- Full Vitest/CI suite: **632 files passed, 2 skipped; 4,475 tests passed, 5 skipped, 0 failed**. The skipped tests require PostgreSQL. +- Tooling suite: **307 passed, 12 skipped, 0 failed**. Local-only skips are PostgreSQL, Helm (not installed), and git release tags (not fetched); CI provisions these dependencies. +- TypeScript server/client checks, ESLint, Oxlint, repository Prettier check, `git diff --check`, bundle-size check, and current-batch contract check passed. Lint reported warnings only. +- UI shared-style check inspected **486/486 components**; focused UI geometry/style tests passed **73/73**. +- Next.js production build generated all **140 static pages**. The bundle check inspected **303 chunks (7.08 MB)**. The server build emitted both theme packages under `dist/interface-themes/`. +- Workflow boundary tests passed **11/11**. Focused theme package, provider, security, and route tests are included in the full suites. -- CSS coverage now reaches the shared contracts used by the listed route - families; render acceptance is still needed to catch route-specific markup, - responsive, and state regressions. -- Focused theme-provider tests, server/client type checks, translation checks, - and lint have passed. The navigation presentation tests pass (2/2), client - typecheck passes, and the changed navigation files pass Prettier. A SQLite - migration execution test covers Orig defaults, the explicit John migration, - idempotency, and rollback. -- The four-worker full Node run reported 3,754 passed, 5 skipped, and 2 failed - out of 3,761. The provider deadline assertion missed its 6-second bound by - 51ms under suite load; it passes when isolated. The settings route test file - was killed during that run; it passes in isolation (93/93). A two-worker full - rerun was stopped before it produced a final summary, so a clean full-suite - result remains open. -- PostgreSQL migration execution has not yet been performed. This workspace - has no PostgreSQL client/server, container runtime, or configured database - URL; repository CI uses a private, manually dispatched runner for - database-backed checks. -- The full repository formatting check failed before formatting the changed - sidebar file. All changed files now pass the focused Prettier check; the full - repository check remains pending. -- The comparison page is a static fixture using the production profile - stylesheets. Live route screenshots, keyboard/touch review, and matching - viewport comparisons have not been completed; UI acceptance is - **unverified**. -- A theme audit caught and corrected the poster-size inversion: SeerrOrig now - uses the upstream 150px catalog track and SeerrNGJ uses the SeerrNG 169.2px - track. Both profile grids read their width from the profile token, and the - comparison page has been regenerated from those production stylesheets. - `node --test src/styles/interfaceThemeProfiles.test.mjs` passes 3/3, including - checks that the embedded CSS matches source and that the two computed layouts - differ. Changed-file Prettier and `git diff --check` also pass. -- A serial full Node-suite rerun did not produce a final TAP summary after its - execution session was lost during the `User persistence` tests. It is not a - clean suite result; the existing full-suite gate remains open. +## Remaining release gates -## Next gates +1. **Live PostgreSQL migrations:** execution remains unverified. Node and Vitest each skipped five PostgreSQL-gated cases; tooling skipped four database-dependent cases. No test URL/service is configured. PostgreSQL binaries are present, but this container blocks switching to the unprivileged UID required to start the server. The SQLite migration suite and PostgreSQL SQL contract tests pass; they do not replace a live PostgreSQL run. +2. **Rendered acceptance:** source-backed comparison tests prove the two package styles resolve differently, but live route review at desktop/mobile sizes, including keyboard, touch, loading, empty, and populated states, has not been completed. +3. **Repository CI:** the public-fork workflow produces no jobs for this same-repository branch. The project CI workflow is manual and requires a private JIT runner; no CI result exists for this candidate. -1. Complete a clean full Node suite run with a concurrency setting that fits - the available memory; retain the exact pass, skip, and fail counts. -2. Execute the PostgreSQL migration path against a disposable PostgreSQL - database. -3. Render both themes in the running app at matching desktop and phone - viewports. Review Home, video and cross-media detail, request flow, and admin - routes with loading, empty, and populated states. -4. Finish the route-level interaction and responsive review recorded in - `feature-map.md`, then update the mockup and status from verified renders. -5. Keep each implementation slice committed and pushed to the draft PR; do not - merge it. +The implementation and local automated gates are complete. The change is **not fully release-ready** until live PostgreSQL execution, rendered acceptance, and the project CI run are completed. PR #416 remains draft and unmerged. diff --git a/docs/interface-themes/integration-checkpoint-20261030.md b/docs/interface-themes/integration-checkpoint-20261030.md new file mode 100644 index 0000000000..66c17af1ea --- /dev/null +++ b/docs/interface-themes/integration-checkpoint-20261030.md @@ -0,0 +1,110 @@ +# PersiusNG native integration checkpoint — 2026-10-30/31 + +Status: **native code integration implemented and locally verified; draft PR +#424 remains unmerged for release-environment checks**. This record replaces the +interrupted-checkout status. It does not claim live provider acquisition or a +pixel-identical match of changing catalog content. + +## Native implementation + +| Area | Integrated behavior | +| --- | --- | +| Theme runtime | Built-in PersiusNG and separately named community packages load from SeerrNG's same-origin catalog/CSS API. The account preference persists through the real own-profile route. Production OpenAPI validation admits these routes. A superseded selection cannot strand a loaded stylesheet off-document. | +| Reference composition | Native Discover, movie/series catalogs, movie detail, ebooks, audiobooks, recording selection, current Requests, coming-soon calendar and season dialog use the Persius composition and independently owned CSS. Caption geometry, dialog surfaces, mobile chrome, request actions, detail search alignment, overflow and keyboard dismissal were reviewed in the production app. | +| Current Requests route | `components/Requests` uses native status snapshots, polling, owner-scoped Active/Ready/All tabs, progress, retries, cancellation and download actions. Detailed management/history remains reachable. Explicit All and All Users filters survive query restoration. Classic themes retain their existing rendering. | +| Recording identity | Provider work/edition identity, selected format and alongside policy survive the native request flow. Legacy Open Library ISBN IDs keep their original semantics. Edition lookup verifies exact ownership at the selected configured destination, including server ID zero. | +| Pending recording edits | Exact recording identity/format are immutable. Retargeting revalidates the destination edition and capability, then updates request and service targets together. Zero IDs, empty tags, both-format legacy behavior, permissions and failed-edit rollback are covered. | +| Recording completion | Completion shares the cancellation admission lock and saves the full entity, preserving notification intents and status-history subscribers. Another recording's work-level availability cannot complete the request. | +| Future seasons | Nullable SQLite/PostgreSQL preference, validation and Sonarr v3/v5 adapters preserve legacy defaults. Episode Queue and watch gates retain priority; opting out does not unmonitor another existing request. | +| Community authoring | Create, validate, inspect, pack, install, replace, list and uninstall work with independent CSS, manifest composition/navigation choices, reproducible bundles and checksum sidecars. The packaged CLI works without TypeScript source. Guides, template/schema, submission form and release notes are included. | +| Browser harness | Signed-in production routes use deterministic catalog/read fixtures. Optional offline server checks reject external HTTP/fetch/socket destinations before environment-proxy translation. Browser fixtures reject unhandled external traffic. The disposable media-server fixture uses loopback. | + +`src/proxy.ts` is still authentication/redirect middleware. A separate +UI-rewriting proxy is not a runtime dependency. No running deployment or external +proxy configuration was changed. + +## Verification + +The restored checkout uses Node 24.22.1 and the exact pnpm 10.24.0 lockfile (1,458 +packages), with native better-sqlite3/SQLite 3.53.4. Database tests use the normal +repository setup and real subscribers. The final production build includes both +the server and all 141 statically generated Next.js pages. + +| Check | Observed result | +| --- | --- | +| Full native Vitest suite | 640 files passed, two skipped; **4,525 tests passed, five skipped**, zero failures. | +| Focused post-review checks | 36 tests passed in six files, including native OpenAPI/theme contracts and request entry; a subsequent 36-test/four-file season and dialog run also passed. These runs overlap and are not an additional unique-test total. | +| Native Node runner | **3,819 passed, 5 skipped**, zero failures/cancellations; complete matching terminal/archive reports (1155.4 seconds, four workers). | +| Tooling | **325 passed, four skipped**, zero failures; includes theme CLI round trips, the offline boundary and native PostgreSQL opt-in gate. | +| Current-batch / UI style | Passed; 73 geometry/role tests passed. | +| Formatting / lint / types / translations | Server/client type checks, lint (warnings only) and translation/prebuild checks passed. Whole-repository formatting passed, including the new browser harness; generated browser output is excluded consistently with Git. | +| Production build | Passed server and Next.js production build with the normal prebuild checks. | +| Signed-in browser suite | **20 passed**, zero failures, skips or flaky results. Includes 27 route/viewport captures and document-overflow checks, plus ordinary-user season dialogs, classic themes and an installed derivative. | +| Classic theme comparisons | **20 matched baseline/candidate captures**, across SeerrOrig/SeerrNGJ, five route families and two widths. 18 have identical pixels; two show text/gradient rasterization variation, with no observed layout regression. Raw differences are recorded in the report. | +| Compiled theme package smoke | Create, validate, pack/checksum, install, inspect, list and uninstall passed from a staged runtime without server TypeScript sources. A separately installed derivative also passes native catalog/picker/persistence browser checks. | + +The full Vitest result precedes the final small visual and fallback changes; +those changes are covered by the focused checks, final production build and +browser suite. The complete native Node run uses the final application tree. +HTTP/TLS regressions were traced to test +transport using the host proxy; tests now own a direct dispatcher. Production +transport was not altered to accommodate the test environment. + +Earlier native Node invocations that lacked a complete report are not counted +as passes. The runner delegates isolated workers, coverage, reporter completion +and aggregate status to Node's native CLI. Its test-only bootstrap flushes piped +result output before forced exit; the CLI waits for registered reporters before +shutting down services that retain background handles. The wrapper preserves the +isolated environment, forwards interruption signals and returns the CLI's status. +Three regressions cover failure status, all 1,600 results plus coverage reaching +both report destinations, and a delayed final reporter completing despite a +retained worker service handle. Nested regression invocations cannot overwrite +the enclosing CI JUnit report. No application startup loads the test bootstrap. +The native Node result above refers to the subsequent full invocation. + +Screenshot capture now requires two identical frames after route/font/image +readiness. The final classic comparison contains 74,291 changed pixels, of which +74,275 differ by one channel level; only three exceed an eight-level channel +difference. The differences are in one phone Requests capture and the settings +sidebar gradient. They are recorded rather than masked or called exact matches. + +The [native browser report](evidence/persiusng-native-verification.json), +[desktop sheet](evidence/persiusng-native-desktop.jpg) and +[phone sheet](evidence/persiusng-native-phone.jpg) record the reference routes, +viewports, scope and comparison outcomes. The classic baseline is +`8a72b6db85e63b7560f5498194b22d33034d5d38`; the candidate is this commit's +application source. Earlier component-only evidence remains historical. + +## Release-environment checks + +1. **Native PostgreSQL execution.** SQLite round trips and PostgreSQL SQL/adapter + contracts are covered. The opt-in theme/future-season migration test checks + existing values, null/true/false, repeat up/down and rollback with TypeORM. + It needs `SEERR_MIGRATION_TEST_POSTGRES_URL` pointing to a disposable database. + This environment cannot run PostgreSQL as its available root-only identity. + The native PostgreSQL tests remain explicit skips, not passes. +2. **Cypress runner.** Verification found no installed Cypress executable. The + installation attempt returned a truncated/non-ZIP download. The production + route checks ran in Playwright/Chromium; the separate Cypress suite was not + executed. Run it on the project's private ephemeral JIT environment with its + browser dependencies before release. +3. **Live providers and original artwork.** Browser catalog/provider reads are + deterministic fixtures. Native tests exercise adapter payloads and real local + persistence, not live Sonarr/Bookshelf acquisition or external playback. + Test artwork is low-resolution contact-sheet material, not runtime assets. + Confirm provider round trips and compare original-resolution artwork on the + intended deployment before retiring its old UI proxy. Real titles, counts, + metadata, permissions and additional management controls remain data-driven. + +Initial compatibility attempts were stopped by automatic approval review +because the seeded Plex account could contact a private or external destination. +The completed browser runs use local accounts without linked provider credentials, +loopback configuration and the offline boundaries described above. No real media +provider credential was used for these acceptance checks. + +No CI workflow was dispatched. Commits carry `[skip ci]`, and the private +ephemeral JIT runner policy is preserved. No merge or deployment was performed. + +Confidence: **high** in native code integration, the observed checks and the +bounded rendered comparisons; **moderate** in exact live visual parity until the +original artwork/provider deployment checks above are performed. diff --git a/docs/interface-themes/manifest.schema.json b/docs/interface-themes/manifest.schema.json index 26df79bc7b..9e97f61142 100644 --- a/docs/interface-themes/manifest.schema.json +++ b/docs/interface-themes/manifest.schema.json @@ -16,13 +16,17 @@ "activeNavigationIcon" ], "properties": { - "formatVersion": { "const": 1 }, - "themeApiVersion": { "const": 1 }, + "formatVersion": { + "const": 1 + }, + "themeApiVersion": { + "const": 1 + }, "id": { "type": "string", "minLength": 1, "maxLength": 48, - "pattern": "^(?:seerrOrig|seerrNGJ|[a-z0-9]+(?:-[a-z0-9]+)*)$" + "pattern": "^(?:seerrOrig|seerrNGJ|persiusNG|[a-z0-9]+(?:-[a-z0-9]+)*)$" }, "name": { "type": "string", @@ -52,7 +56,15 @@ "maxLength": 48, "pattern": "^(?=.*\\S)[^\\u0000-\\u001f\\u007f]+$" }, - "navigation": { "enum": ["flat", "grouped"] }, - "activeNavigationIcon": { "enum": ["outline", "filled"] } + "navigation": { + "enum": ["flat", "grouped"] + }, + "activeNavigationIcon": { + "enum": ["outline", "filled"] + }, + "layout": { + "enum": ["classic", "persius"], + "description": "Optional native page composition; omitted means classic." + } } } diff --git a/docs/interface-themes/native-request-flows.md b/docs/interface-themes/native-request-flows.md new file mode 100644 index 0000000000..09413a9bb8 --- /dev/null +++ b/docs/interface-themes/native-request-flows.md @@ -0,0 +1,101 @@ +# Native recording and future-season requests + +These flows belong to SeerrNG. Theme packages change their CSS and composition; +they do not ship executable request logic or require a UI-rewriting proxy. + +## Recording choices + +`GET /api/v1/editions/book` accepts `format`, `mediaId`, canonical `bookId`, +`term`, expected `title`/`author`, optional `foreignBookId`, and optional +`serverId` (including zero). An explicit server selects the configured destination +for that format; exact ownership is evaluated there. Without an override, a +Bookshelf work identity selects its configured service and exact provider work. +Other lookups prefer the configured default service for the format. Other catalog +lookups require the supplied title and author to match. Library responses include +exact edition ownership; ordinary Readarr ownership is inferred only when a +single monitored edition matches and its monitored-edition file total is positive. +Multiple monitored editions need the companion's exact edition catalog. + +A recording choice opens the existing book request modal with the original work +ID and an initial edition choice. Submission uses `preferredEditionId`, +`editionPolicy` and `variantKey`. The server rechecks the selected edition against +the resolved destination before allowing a request for another version of an +available work. Service access, permissions, quotas, approval and blocklists +continue to apply. A specific edition must use one format, not `both`. + +`alongside` requires the companion's wanted-edition capability. Missing capability +or a missing catalog edition fails explicitly instead of replacing the existing +recording. The request modal explains the replacement policy on providers that +only support one monitored version. The background search and status projection +require the chosen edition's files; an older recording's generic work-level +availability does not complete the new request. Completion preserves concurrent +cancellation through the shared request admission lock and updates only the +corresponding service targets. Saving the full request entity preserves the +transactional notification intent and status-history subscribers. Legacy Open +Library edition IDs remain ISBN metadata, not provider recording identities. + +Editing a pending request keeps an exact recording's identity and single format +immutable. Changing its destination revalidates the edition and exact ownership +on that destination, including the alongside capability, before saving anything. +The request and its persisted service targets change together. Server/profile ID +zero and explicitly empty tags are valid values. Legacy ISBN requests and +requests for both formats retain their separate behavior. A failed destination +lookup leaves the original request and targets intact; ownership and request +management permissions still apply. + +Optional `sampleUrl` and `editionLabel` pass through from the provider. Samples +accept HTTPS without embedded credentials, are not fetched until a click, and +stop when another recording is selected or the component closes. Missing samples +remain disabled with an explanation. The Recommended label is a local suggestion: +a missing, named, unabridged recording matching the interface language. It is not +a provider rating or an invented edition annotation. + +## Future seasons + +TV request create/update accepts optional boolean `monitorFutureSeasons`. +Other media types and non-booleans are rejected. SQLite and PostgreSQL migrations +add a nullable column: old null values inherit the configured Sonarr default. + +| Preference | New series | Existing series | +| --------------------- | ------------------------------------------- | ------------------------------- | +| `true` | Monitor future seasons | Enable future-season monitoring | +| `false` | Do not monitor future seasons | Preserve existing monitoring | +| Omitted / legacy null | Inherit configured all/none/latest behavior | Preserve existing monitoring | + +Episode Queue and season watch gates prohibit a true preference. The dispatch +worker rechecks current policy before calling Sonarr. A false preference never +unmonitors a series requested by another person or already managed in Sonarr. +New seasons are acquired by Sonarr; this option does not create synthetic SeerrNG +request rows for seasons that do not yet exist. + +Sonarr v3 updates the existing series payload. Sonarr v5 reads the complete +series and preserves other fields when updating its future-season preference. +The option is available in the native Persius composition; custom themes can +style `.persius-future-seasons`, its label, description and switch. + +## Current request page + +`src/pages/requests/index.tsx` renders `components/Requests`, using +`GET /api/v1/request/status` and the per-request status/history endpoints. Persius +uses those same snapshots for its compact rows, status pills, download progress +and actions. Active/Ready/All counts retain the selected owner scope. The default +is the viewer's active requests; explicit All and All Users selections survive +query restoration. The additional filters and authorized management controls +remain available. **Details and actions** opens the existing request details and +history without expanding the compact row. Cancellation uses the native request +DELETE route and its confirmation, authorization and error handling. + +## Validation boundaries + +Native database/API tests cover recording edits, identity, destination ownership, +request permissions, completion/cancellation, notification history and provider +adapter payloads. The production build and signed-in browser checks also exercise +the actual page components, theme endpoints, saved preferences, recording entry, +season controls and current request status page. Provider transport and catalog +responses are deterministic fixtures in these checks; they do not acquire media. + +SQLite migration execution passes. PostgreSQL migration SQL has an executable, +opt-in round-trip test but requires a disposable PostgreSQL URL. Real provider +acquisition, external playback and deployment-specific proxy retirement remain +deployment checks. See the [integration checkpoint](integration-checkpoint-20261030.md) +and [visual evidence](persiusng.md) for exact results and exclusions. diff --git a/docs/interface-themes/persiusng.md b/docs/interface-themes/persiusng.md new file mode 100644 index 0000000000..302139fac6 --- /dev/null +++ b/docs/interface-themes/persiusng.md @@ -0,0 +1,156 @@ +# PersiusNG + +Select **Theme picker → Interface design → PersiusNG**. The existing account +preference and same-origin theme loader save and load this choice. The default +theme remains SeerrOrig. + +PersiusNG follows the nine owner-provided October 30, 2026 mockups: a charcoal +canvas, lavender controls, outlined navigation, posters with captions underneath, +wide discovery features, compact request cards and a grouped release calendar. +Its manifest selects `layout: persius`. Its package owns the visual values; application components retain catalog data, +permissions and request mutations. + +## Design measurements + +| Element | Desktop value | +| --------------------------------------- | --------------------------------------------------- | +| Canvas / panel / raised panel | `#0b0d11` / `#14171d` / `#1b1f27` | +| Border / lavender / selected navigation | `#2a303b` / `#8ba5ff` / `#1c2547` | +| Sidebar / top bar / search field | 244 px / 70 px / 560 × 42 px | +| Content including gutters | 1,320 px maximum; 40 px gutters | +| Page title / section heading | 40/48 px / 20/26 px | +| Discovery feature | 564 × 352 px; 22 px radius | +| Desktop poster grid | Six columns; approximately 192 × 288 px; 18 px gaps | +| Discovery shelf / audiobook shelf | 164 × 246 px / 180 × 180 px | +| Request row / release card | 615 × 136 px / 408 × 104 px | +| Season dialog / season row | 640 px wide / 65 px high | + +At desktop widths of 1,600 px and above, the content starts approximately 396 px +from the viewport edge, matching the references' nearly constant left alignment. +Smaller screens use fluid gutters, fewer poster columns, single-column request +cards and a scrolling dialog. Light mode is an adaptation; the supplied references +only specify dark mode. + +## Behavior and ownership + +- `themes/persiusNG/` contains the scoped stylesheet and validated manifest. + The application adds the built-in ID to the shared registry and client fallback. +- `src/components/Persius/` contains presentation components. Existing page, + modal, navigation, title-card and request owners opt in when the selected theme + declares the Persius composition. Extra navigation remains available under **More**. Custom packages can + select the same native composition with `"layout": "persius"` while supplying + their own ID and stylesheet; no code fork or UI proxy is involved. +- Library segments and genre chips update the existing catalog queries. Series + stacks and narrator counts describe loaded catalog results, not invented totals. + Full-cast shelves require explicit full-cast/GraphicAudio metadata. +- Narrations use the native edition catalog, with exact provider work identity + or a verified title/author lookup. The request retains the original work ID, + selected provider edition, audiobook format and explicit alongside/replacement + policy. Another recording's files cannot satisfy that request. Missing provider + identities cannot be requested. Samples load only after a click and only when + a provider supplies an HTTPS preview. Edition labels are provider metadata; + the recommendation chooses a missing unabridged recording in the UI language. +- The future-season switch is stored on TV requests and sent to Sonarr v3/v5 for + new and existing series. Episode Queue and watch-gate policy take priority. + Opting out preserves monitoring already established in Sonarr. Existing null + preferences keep the server default. See [native request flows](native-request-flows.md). +- Requests default to the viewer's active requests. **Active**, **Ready** and + **All** counts come from the request API. Authorized users can include other + users through the additional controls. Status actions and byte-based download + progress use the existing request data and handlers. +- `/coming-soon` groups upcoming movie results by release month and links to the + existing monitored calendar. Other interface themes continue to use that + calendar at this route. Dates are parsed without UTC day shifts. +- Season shortcuts feed the existing episode-selection adapter, exclude blocked + episodes and preserve its metadata readiness guards. Individual episode + controls remain available in a disclosure after the future-season option, in + the same visual and keyboard order. PersiusNG dialogs retain keyboard + focus and restore it to their trigger. + +## Native application evidence + +The current evidence comes from the compiled production server and Next.js app, +with real local sign-in, saved account preferences, the native theme catalog and +same-origin CSS endpoints. The browser tests provide deterministic catalog, +service-read and artwork fixtures; they do not rewrite the UI or replace the +page components. The server runs with the optional offline test guard and the +browser rejects unhandled external traffic. + +| View / native route | Reference desktop viewport | Additional widths | +| --- | --- | --- | +| Discover `/` | 1782 × 1055 | 768, 390 | +| Movies `/discover/movies` | 1788 × 1038 | 768, 390 | +| Movie detail `/movie/:id` | 1782 × 1060 | 768, 390 | +| Series `/discover/tv` and season dialog | 1776 × 1058 | 768, 390 | +| Books `/discover/books` | 1772 × 1064 | 768, 390 | +| Audiobooks `/discover/audiobooks` | 1726 × 1061 | 768, 390 | +| Narrations `/book/:id?format=audiobook` | 1736 × 1046 | 768, 390 | +| Requests `/requests` | 1726 × 1067 | 768, 390 | +| Coming soon `/coming-soon` | 1760 × 1055 | 768, 390 | + +The [desktop sheet](evidence/persiusng-native-desktop.jpg), +[phone sheet](evidence/persiusng-native-phone.jpg) and +[native verification report](evidence/persiusng-native-verification.json) record +these routes. Review covered the reference geometry, color and typography, +poster captions, card spacing, shared surfaces, search placement, request actions, +dialog scrolling, keyboard focus and document overflow. The season dialog also +uses an ordinary requester's account, with privileged controls retained for +administrators. + +Full-size examples show the [native Requests route](evidence/persiusng-native-requests-1726.jpg) +and season dialog at [desktop](evidence/persiusng-native-season-dialog-1776.jpg) +and [phone](evidence/persiusng-native-season-dialog-390.jpg) widths. + +The browser specification exercises library/genre/sort filters, keyboard poster +entry, all/latest/clear season selection, the future-season switch, Escape and +focus handling, narration selection into the native request modal, owner-scoped +request tabs, details/history, loading/empty/error recovery, the theme picker, +light mode and failed-save preservation. A separately named community package +is created by the compiled CLI, installed into the test app, selected, and +restored after reload with its own stylesheet and the native Persius composition. + +SeerrOrig and SeerrNGJ are also rendered at 1782 × 1060 and 390 × 844 for movies, +movie details, book details, requests and settings. The matching baseline is the +previous integrated revision `8a72b6db85e63b7560f5498194b22d33034d5d38`. +The verification report records comparison outcomes. Earlier component-only +[evidence](evidence/persiusng-desktop.jpg) remains historical and is used only +as an artwork fixture source by the native browser test. + +## Deliberate differences from static mockups + +Catalog titles, artwork, ratings, release dates, runtimes, counts, quotas and +availability come from the application data. The test artwork is cropped from +a small reference contact sheet, so its resolution is unsuitable for judging +production artwork quality or claiming a pixel-identical image comparison. +Provider attribution and existing management, filters, playback and request +controls remain available. Missing samples, trailers or edition metadata are +not fabricated. Coming-soon copy does not promise downloads on a theatrical +release date. Light mode and phone layouts are adaptations because the supplied +references specify desktop dark mode. + +The native implementation follows the mockups' composition and measurements; +a literal pixel-for-pixel match of live content has not been claimed. Use real +catalog data and the original-resolution references for deployment acceptance. + +## Native package and authoring + +PersiusNG and custom derivatives load through SeerrNG's same-origin theme API. +Validated manifest metadata selects the composition, so a renamed theme retains +its native pages. `src/proxy.ts` remains Next.js authentication/redirect middleware. +A UI-rewriting proxy is not a runtime dependency, and no external proxy or +production deployment configuration has been changed. + +Authoring supports `create → validate → pack → install`, plus inspect, list, +replace and uninstall. Packages carry an independent ID, CSS, composition and +navigation preferences. The compiled CLI works without TypeScript source files; +reproducible bundles have checksum sidecars. See [authoring](authoring.md), +[community submission](submitting.md) and [native request flows](native-request-flows.md). + +## Release verification boundaries + +The [integration checkpoint](integration-checkpoint-20261030.md) is the current +source of exact suite results and environment exclusions. It supersedes the +previous interrupted-checkout status. Native PostgreSQL execution, live provider +acquisition/external playback and the deployment's original-resolution visual +acceptance remain release-environment checks. No merge, deployment or CI dispatch +was performed as part of this integration. diff --git a/docs/interface-themes/submitting.md b/docs/interface-themes/submitting.md new file mode 100644 index 0000000000..27931e7278 --- /dev/null +++ b/docs/interface-themes/submitting.md @@ -0,0 +1,61 @@ +# Submit a SeerrNG theme + +A community theme is an independent source directory and a `.seerrtheme` file. +Users can install it without a fork of SeerrNG, executable plugins, or a +UI-rewriting proxy. It does not have to become a built-in theme. + +## Prepare a release + +1. Create a permanent lowercase ID. Set your name, description, author, license + and semantic version in `manifest.json`. +2. Make the scoped `theme.css` your own. Start with + `pnpm interface-theme:create my-theme --from persiusNG` or another installed + base. Preserve the base's license and attribution in your source release. +3. Run `pnpm interface-theme:validate ./my-theme`, then + `pnpm interface-theme:pack ./my-theme`. Keep the generated `.seerrtheme` and + `.seerrtheme.sha256` together. The packer ignores the README and other source + files; only validated metadata and CSS enter the package. +4. Validate the generated package, install it on the SeerrNG version you support, + and test through the native application. Record exact versions and browsers. +5. Publish the source, package, checksum, license and screenshots at stable URLs, + for example a tagged repository release. Describe unsupported states honestly. + +## Request community review + +Use the [theme submission form](https://github.com/snapetech-org/seerrng/issues/new?template=theme_submission.yml). +Include the source tag/commit, package and checksum URLs, package ID/version, +license, supported SeerrNG releases and screenshots. If GitHub will not attach +the `.seerrtheme` file directly, link to it on your source release. Do not rename +an archive to `.seerrtheme`: the actual package format is validated JSON. + +The form opens a review request; it does not automatically install, execute, +approve or publish your theme as an official built-in. Maintainers can review the +exact source and reproducible bundle before sharing it with users. A built-in +theme proposal needs a normal pull request and the repository's UI review gates. + +## Review checklist + +- Independent ID, clear author/version/license, complete source and matching checksum. +- Every selector scoped to that ID; no scripts, imported CSS, URLs or remote assets. +- Layout choice recorded: `classic`/omitted or `persius`. Persius composition + needs a release with the native PersiusNG implementation. +- Desktop and phone screenshots, with viewport dimensions and light/dark modes. +- Discover, movie/series catalogs, book/audiobook catalogs, details, requests, + calendar, settings and authentication checked where enabled. +- Long titles, loading, empty, failed, available, shared and requested states checked. +- Keyboard focus, menus/dialogs, reduced motion, responsive overflow and contrast checked. +- Request/cancel, playback, filters, season/episode selection and narration choice + tested on a running instance with appropriate permissions and services. +- Account persistence, switching away/back and explicit `--replace` upgrade checked. +- Known limitations listed. Static previews or mocked fixtures identified as such. + +## Publish an update + +Keep the ID and increase the version. Generate a new bundle and checksum, publish +release notes and retain the previous validated package. Users explicitly install +the update with `--replace`, restart SeerrNG and reload; their account selection +continues to use the same ID. A new ID is a separate theme. + +See the [authoring guide](authoring.md) for commands, supported CSS and package +limits. Community submissions do not add a new automatic CI workflow; repository +validation remains subject to the existing private-runner policy. diff --git a/docs/interface-themes/template/manifest.json b/docs/interface-themes/template/manifest.json index b55edcad15..39a5fb7c6c 100644 --- a/docs/interface-themes/template/manifest.json +++ b/docs/interface-themes/template/manifest.json @@ -4,7 +4,7 @@ "id": "my-theme", "name": "My Theme", "description": "A short description shown in the theme picker.", - "version": "1.0.0", + "version": "0.1.0", "author": "Your name", "license": "MIT", "navigation": "grouped", diff --git a/docs/maintainers/current-batch-acceptance-ledger.md b/docs/maintainers/current-batch-acceptance-ledger.md index 7af0274a87..b7644de5d6 100644 --- a/docs/maintainers/current-batch-acceptance-ledger.md +++ b/docs/maintainers/current-batch-acceptance-ledger.md @@ -865,3 +865,23 @@ asks for the work to start. for user-facing work. - A visual task is complete only after source checks, a fresh build, and rendered desktop and narrow-layout verification of the changed states. + +## PersiusNG production integration — 2026-10-30 + +- **Status: incomplete, draft PR #424.** The native interface and package-authoring + implementation remains under review. The execution environment became + unavailable during full-source integration, preventing final verification. +- Finish exact-recording pending-request edits: destination revalidation and + synchronized service targets, with permission/legacy ISBN/both-format tests. +- Rerun the native regression suites on the unchanged final source; investigate + the HTTP/TLS loopback failures without assuming a production transport defect. +- Complete format/lint/typecheck/build, built-container CLI validation, + PostgreSQL migration execution and signed-in browser acceptance. +- Compare all nine requested PersiusNG flows and representative existing-theme + consumers at matching reference desktop and responsive sizes. UI acceptance + is unverified; do not retire deployment proxy configuration from fixture + evidence alone. +- Exact source identity, preserved fixes, observed test counts and exclusions: + [integration checkpoint](../interface-themes/integration-checkpoint-20261030.md). + Preserve private ephemeral JIT policy; no CI dispatch, merge or production + deployment was authorized by this checkpoint. diff --git a/docs/maintainers/episode-availability-recovery-validation.md b/docs/maintainers/episode-availability-recovery-validation.md new file mode 100644 index 0000000000..c582c2d3aa --- /dev/null +++ b/docs/maintainers/episode-availability-recovery-validation.md @@ -0,0 +1,36 @@ +# Episode availability contribution recovery + +Preserve and integrate the original histories of PRs #454 and #493. These contributions add opt-in, source-scoped episode inventories for Sonarr, Plex, Jellyfin and Emby, with independent standard/4K state and explicit metadata-order matching. They are repaired before merging rather than closed without delivery. + +## Root causes repaired + +- Sonarr service ID zero was rejected as though it were an invalid database ID. It now persists and clears its own source records correctly. +- Malformed inventory identifiers could become an empty inventory during filtering and erase a complete snapshot. Reconciliation now rejects invalid or duplicate identifiers; only confirmed complete empty inventories clear a source. +- Sanitized provider responses could conceal omitted, invalid or partial episode/season lists. Tracking uses complete reads with raw counts, bounds and identity checks. Unknown Sonarr resolution preserves the prior quality snapshot. Ordinary scans retain their established path when tracking is off. +- Global media-server file records bypassed linked-viewer episode visibility. Responses now intersect them with identity-verified, viewer-visible episodes and file qualities. Provider failures hide those indicators. Acquisition-only Sonarr indicators remain distinct from playback access. +- The new settings component imported the server settings runtime into the browser, failing production compilation on filesystem/network dependencies. One browser-safe metadata-provider enum is shared by client and server. +- The original badge code targeted an unused legacy Season component. Source details now reach the live season/episode tree through the existing availability tooltip; the unused component is removed. +- Narrow layouts squeezed episode names and made status controls unreachable. The shared media-server panel stacks on phones, dates move below names in the shared tree, and a stable semantic selection wrapper preserves grid placement when a native disabled button needs a keyboard-accessible tooltip. Native disabled state and request/playback selection behavior remain unchanged. + +## Validation and evidence + +Evidence is retained at `/mnt/disks/scratch/task-deliverables/seerrng-contribution-recovery-20261105/`. + +- Actual baseline failures: zero service identity and destructive malformed inventory reconciliation (`episode-source-baseline-regressions.log`); production browser/server dependency import (`episode-production-build.log`); inaccessible phone status and unreadable name captures. +- Final focused native tests: 68 passed across provider APIs, snapshot persistence, linked-viewer projection and Jellyfin scanner consumers. The broader initial scanner/route run passed 150 cases; its seven tracking-path failures were repaired and the affected scanner checks pass. +- Shared tree and data projection checks: 20 passed. Request-modal component checks: six passed, preserving disabled and selectable episodes without external mutations. +- Production server/client build and later UI builds pass. i18n extraction/check, scoped ESLint and formatting pass. +- Sixteen browser cases pass across SeerrOrig and SeerrNGJ at 390×900, 639×900, 641×900 and 1440×900. They verify numbering-order saves preserve enabled libraries, visible episode names, source/quality tooltip interaction, no document overflow and no inferred playback availability. Matching baseline captures retain the prior absence of numbering controls and broken phone layout. +- Desktop and phone source captures were visually reviewed in `episode-final-theme-review.jpg`; numbering settings use the shared form owners. The table retains desktop geometry, and mobile names, dates and status controls use the shared responsive owner. No new page CSS or copied style values. + +External providers are fixtures. Existing unavailable saved-state feedback remains visible in the screenshots; this does not certify live media-server access or playback on physical devices. Final owner CI must pass before integration. + +## Combined theme and policy integration + +The final integration also preserves PRs #424/#416/#457, #447/#446/#491 and #461/#449/#489/#429 through integration heads #557/#556/#559. All 15 original/integration heads are verified ancestors of the combined head and every original targets main. + +Combining the source required two additional repairs: tag-excluded Sonarr series clear their episode records, and episode-source selection uses the scanner's enabled/quality gates before endpoint deduplication. Rule-selected language profiles retain their provenance instead of becoming explicit user overrides. New regressions cover each behavior, including service/profile zero and deliberate reselection. + +Combined production build passes on Node 24.22.2. The integration checks pass 279 native tests, 36 component tests, and 36 headless browser cases, including the installed Recovery Cinema derivative. A source scan of all 2,587 tracked TypeScript files finds no duplicate object keys after fixing the SQLite fixture. Of 53 matching prior theme captures, 44 are pixel-identical; changed captures were visually inspected. Remaining differences include fixture settings/selection values, added settings rows, and isolated raster/spinner frames. Shared geometry and native presentation are preserved; phone tree changes are documented above. Evidence: `all-recoveries-*` logs, screenshots, comparison JSON and changed-theme review montage. Provider access remains simulated. Full owner CI must pass before integration. + +The full `pnpm build` path, including i18n and current-batch prebuild gates, also passes. CI exposed a stale structural check that still required the selection marker on the native button after its stable wrapper was introduced. The checker now requires that wrapper, its native episode-control button, and the exact disabled eligibility condition. All 46 contract tests pass, including negative mutations removing each requirement. Evidence: `all-recoveries-prebuild-contract-tests.log` and `all-recoveries-full-prebuild-and-build.log`. diff --git a/docs/maintainers/request-controls-recovery-validation.md b/docs/maintainers/request-controls-recovery-validation.md new file mode 100644 index 0000000000..0ac9f1fc7a --- /dev/null +++ b/docs/maintainers/request-controls-recovery-validation.md @@ -0,0 +1,45 @@ +# Request controls contribution recovery + +Recovered original histories: #447 (destination defaults and provenance), #446 +(bounded queue snapshots), and #491 (source-aware scan tag exclusions). + +Review repairs include explicit SQL types for nullable destination defaults, +preservation of deliberately chosen defaults and profile zero, provider-page +validation before queue truncation, duplicate-ID rejection, and separate HTTP +and HTTPS scan policies. Disabled service aliases no longer suppress enabled +scanners. Excluded library reconciliation preserves pending, blocked and deleted +season states. + +The shared Modal owner now lets only the front dialog handle outside-click +dismissal. Previously a portaled request editor's profile selector dismissed its +parent Manage Media dialog and both disappeared. Existing portal/listbox ownership +checks remain in place. No shared styles or control dimensions changed. + +## Validation + +- 389 native request, queue, scan and recovery checks passed before the final + excluded-season repair; 64 scanner checks passed after that repair, including + its new regression. These totals overlap. +- Three AdvancedRequester component checks passed, covering profile zero, + unchanged saved values and intentional reselection of a service default. +- Production client and server builds passed after their respective changes. +- Main CI exposed an early-click discovery navigation race: before router + hydration the Swipe link used a canonical fallback and lost the nested genre + route and query. Both mode links now block navigation until readiness. Two + component regressions and all five Cypress navigation cases passed against + the rebuilt production app. Four existing modal/default component checks + also passed using Vitest (a mistaken native-runner invocation is retained + as a harness failure, not counted as application verification). +- Eight headless Chromium checks passed: Radarr, Sonarr and Lidarr settings at + 1440x900 and 390x900, plus nested request editing at 1440x900 and 390x844. + Queue bounds reject 9 and accept 1500; settings persist scan exclusions; + nested profile selection and child-only dismissal preserve the parent. +- Matched baseline/candidate screenshots were inspected for settings and the + shared Manage Media/request editor consumers. Existing control geometry, + typography and responsive wrapping are retained; the new settings extend + existing form rows. The phone profile menu stays inside the viewport. + +Browser provider responses are controlled fixtures; these checks do not certify +every live Servarr installation. Evidence, including initial failing cases and +accepted screenshots, is retained in the contribution-recovery task artifacts +for 2026-11-05. Integration CI validates the combined head with current main. diff --git a/docs/maintainers/request-policy-recovery-validation.md b/docs/maintainers/request-policy-recovery-validation.md new file mode 100644 index 0000000000..f79889d607 --- /dev/null +++ b/docs/maintainers/request-policy-recovery-validation.md @@ -0,0 +1,27 @@ +# Request policy contribution recovery + +Recover original PRs #461 (webhook filters), #449 (country and language-profile rules), #489 (pending-edit notifications), and #429 (API contracts) with their Git ancestry. These are useful contributions; they are repaired and integrated rather than discarded. CodeQL remains disabled; #429 introduces no workflow changes relative to its merge base. + +## Confirmed failures and repairs + +- A pending request edit with notifications enabled returned HTTP 500 because the durable notification outbox rejected the new notification type. Admit the type as a media-request event. A real request-route regression verifies one durable event for a material edit and no duplicate for a repeated no-op. Compare normalized acquisition targets as well as explicit overrides; provider progress and tag order do not count as edits. +- Missing TMDB production-country metadata caused an unconditional `.map` failure. Normalize only valid country entries and allow subsequent rules to match when metadata is absent. Preserve valid zero-valued service and language-profile IDs. +- The strict OpenAPI write contract rejected the new country/language fields. Add bounded nullable definitions to both read and write schemas. Tests exercise the actual authenticated, validated router and reject malformed country codes. +- Bookshelf-only service configuration left the New Override Rule button disabled. Include Readarr data in the existing enable condition and memo dependencies. No CSS or shared geometry changes. +- Repeated webhook substitutions bypassed the intended bounded expansion. Enforce a shared 64 KiB UTF-8 output limit, serialized JSON limit, eight-filter chain limit, and 1 MiB rendering-work budget. Reject invalid expressions before sending. Keep the existing deterministic filter allowlist and network destination controls. + +## Validation + +Evidence is retained outside Git at `/mnt/disks/scratch/task-deliverables/seerrng-contribution-recovery-20261105/`. + +- Native integration suite: 288 passed, including request routes, notification dispatch, country routing, and webhook agents. Additional focused checks cover effective destination changes and the rendering-work bound. +- Authenticated OpenAPI integration: 28 passed. +- Production server and client build passed; the final snapshot helper also passed a server rebuild. +- Browser fixtures at 1440×900 and 390×900 cover country/language-profile-zero submission, Bookshelf-only rule creation, and pending-edit notification opt-in. Six candidate cases pass. Matching baseline cases record the prior disabled Bookshelf action and absence of the added controls. +- Baseline regression logs retain the actual country TypeError, OpenAPI rejection, pending-edit HTTP 500, and oversized webhook delivery. Candidate regression tests pass. + +Browser provider responses are deterministic fixtures; this does not certify a live third-party notification service. Screenshots use reduced motion and disabled animations so modal transitions do not corrupt the comparison. Desktop and phone comparisons were visually reviewed: the existing modal spacing, typography, form owners, and notification layout are preserved. Added rows extend the existing scrolling forms. Evidence: `policy-stable-rules-review.jpg`, `policy-notifications-top-review.jpg`, and their full-resolution source captures. The final CI status must be recorded before integration. + +## Nullable enum response validation + +Full CI exposed three real Bookshelf series failures after API alignment: `comicServiceType: null` was rejected despite `nullable: true`. Explicit null members now match the declared null support in all 17 affected enum schemas, including optional request edition fields and resettable preferences. The three original cases fail on the unrepaired schema and all 30 Bookshelf series tests pass after repair. The entire affected Vitest shard passes: 162 files, 1,379 tests, with five existing skips. Evidence: `policy-book-series-baseline-vitest.log`, `policy-book-series-fixed-vitest.log`, and `policy-vitest-4-fixed-local.log`. diff --git a/docs/maintainers/theme-contribution-recovery-validation.md b/docs/maintainers/theme-contribution-recovery-validation.md new file mode 100644 index 0000000000..903190a339 --- /dev/null +++ b/docs/maintainers/theme-contribution-recovery-validation.md @@ -0,0 +1,81 @@ +# Theme contribution recovery + +Original histories #424 (native Persius and community theme authoring), #416 +(theme package hardening) and #457 (public stylesheet validation and Node patch) +are retained together. Their old readiness notes describe their original heads; +they are not proof of this integration's acceptance. + +## Review repairs + +- Preserve current shared styles, 20px/24px theme input sizes, narrow-phone + cascade fixes, request Episode Queue editing and discovery failure recovery. + The existing SeerrOrig, SeerrNGJ and shared interface CSS are byte-identical + to main. Persius has its independent package and native composition. +- Preserve public GitHub-hosted routing, current server asset copying and + migration packaging. Both server build entry points must retain the asset + copier. Node 24.22.2's archive checksum and official Alpine image digest were + verified; the Bookworm pin uses the current verified official index. +- Consolidate duplicate OpenAPI theme schemas and paths. The automatic merge + otherwise returned HTTP 500 before route admission. Keep strict metadata + bounds and the optional native layout field. +- Replace check-then-read theme files with bounded descriptor reads. Reject + symlinks, hard links, oversized input, swapped inodes and changed parent + directories; close descriptors on failure. A race regression substitutes a + symlink between validation and open, and another replaces a regular file. +- Preserve the pending-stylesheet race test by disabling both automatic fixture + load mechanisms while deliberately keeping the next stylesheet pending. + +## Observed verification + +- Production server and client builds and client/server type checks passed + using a checksum-verified task-local Node 24.22.2 installation. +- 370 native checks passed across request mutation, subscriber completion, + book destination and edition identity, future seasons/migration round trips, + theme API/package/file/registry and test-runner completion. The PostgreSQL + migration class round trip here uses SQLite SQL compatibility; this is not + proof of a live PostgreSQL upgrade. +- 68 component/adapter checks passed after correcting two stale fixtures; + 55 tooling checks passed, including CLI round trips and network isolation. +- The compiled CLI created, packed and installed `recovery-cinema`, an + independent Persius derivative used by the browser acceptance test. +- 20 headless Chromium cases passed: nine native screens at desktop, 768px + tablet and 390px phone widths, account switching, installed theme loading, + request recovery/owner scope, season selection, narration choice and palette + save recovery. The exact viewports are recorded in the test and captures. +- Two baseline browser cases captured 20 matching classic-theme route/state/ + viewport pairs. Eighteen PNGs are identical; the other two differ by a few + raster pixels without geometry changes. Desktop/phone contact sheets and the + 390x844 season dialog were visually checked against the contribution's + references. Overflow, keyboard and interaction assertions passed. + +CI follow-up repairs keep absolute server imports with an explicit checkout CLI +alias, associate native season/switch labels with stable input IDs, and retain +literal URL control-character rejection without an ESLint control-regex escape. +Provider audio-only samples have no supplied timed text; the preview's caption +lint exception is scoped and documented rather than adding fictitious tracks. +The repaired CLI passed seven round trips, the component group passed all 68 +checks, and 12 affected native checks passed. Production and documentation builds +passed; the remaining Quick Connect documentation anchor was matched to its +rendered target and corrected. Release fragments respect the current size limit. + +## Combined request-controls validation + +The branch also retains integration #556 and original histories #447, #446 and +#491. Both the video destination synchronization and exact-book edit planner +remain in the request route. The discovery hydration guard repairs the Cypress +failure seen on main and the first theme CI run. + +The combined production build passed, followed by 296 native checks, 74 component +checks and 28 headless browser cases. These groups overlap earlier validation; +their counts are not added to the earlier totals. All eight user-facing release +fragments pass the current contract. Main's validation container was advanced +to the verified Node 24.22.2 index through #558 before requesting combined CI. + +Evidence is retained in the 2026-11-05 contribution-recovery task artifacts, +including failing cases, screenshot comparisons, checksums and logs. Fixtures +control provider responses; no live provider acquisition or physical-device +handoff is certified. Combined integration CI remains required before delivery. + +## SVG loading-state capture + +The final full browser run passed 105 cases but timed out comparing identical loading-state frames because the visible SVG spinner uses SMIL, which Playwright CSS animation suppression does not freeze. The capture helper now pauses SVG animations at frame zero while taking the image and resumes them afterward. The loading, empty, error, and retry regression passes with the indicator preserved. No production UI code changes. diff --git a/docs/using-seerr/individual-episode-availability.md b/docs/using-seerr/individual-episode-availability.md new file mode 100644 index 0000000000..c0a20b4923 --- /dev/null +++ b/docs/using-seerr/individual-episode-availability.md @@ -0,0 +1,77 @@ +--- +title: Track individual TV episode availability +description: Show which TV episodes have files in connected Sonarr and media-server libraries. +--- + +# Track individual TV episode availability + +SeerrNG can show file-availability badges for individual episodes on a series' +season page. Badges identify whether a configured Sonarr, Plex, Jellyfin, or +Emby source reports the episode in its library, including standard and 4K +availability when **Enable 4K** is on. + +This is a file-inventory signal. A Sonarr badge does not confirm that a media +server has indexed the file. For a linked Plex, Jellyfin, or Emby account, media-server badges are intersected with episodes and file qualities visible to that account. Provider errors or unverifiable identity hide those badges. The badges do not guarantee that a particular client can play the encoding; accounts without a linked media-server identity retain the instance inventory view. + +## Enable tracking + +An administrator can enable **Track Individual Episode Availability** under +**Settings → General**. The setting is off by default. Enable the Sonarr or +media-server libraries that should be scanned. + +Sonarr episode matching uses TheTVDB numbering, so select **TheTVDB** as the +metadata provider for the relevant TV or anime category. Sonarr tracking does +not use TMDB episode order. + +For Plex, Jellyfin, or Emby, open the media-server settings and choose an +**Episode Numbering Order** for each TV library. Select **TMDB** or +**TheTVDB** only when it matches the episode order configured in that library. +Leave it as **Not Configured** if the library's order is unknown or uses a +different order. The library's choice must also match SeerrNG's selected +metadata provider for the series: the TV provider for regular series and the +anime provider for anime. + +Run a full scan after enabling tracking or changing a library's episode order. +Episode indicators appear after a source has supplied a complete series scan. +Each source is reconciled independently. A complete scan can replace or clear +that source's records; failed, capped, or incomplete scans keep its last known +results. A source cannot clear another source's records. Disabling or removing +a library, changing its configured numbering order, or connecting a different +media server clears records associated with the retired source identity. + +When **Enable 4K** is off, 4K results are not shown. Turning tracking off hides +episode availability and stops scanners from updating it; run a full scan +after turning it back on to refresh the displayed state. + +## Read the episode indicators + +On a series detail page, open a season to see its episode list. An **Available +· Sonarr**, **Available · Plex**, **Available · Jellyfin**, or **Available · +Emby** badge identifies a source that reported the episode. A separate badge +ending in **4K** means that source also reported a 4K file. + +Badges are aggregated by source type across the enabled, scanned libraries and +services. They do not identify a particular server or library. One episode may +have badges from several sources, and each source's records stay independent. + +The episode list and source mapping follow the selected TV or anime metadata +provider. SeerrNG only attaches a media-server badge when the library's +configured numbering order matches that provider and a supported external +series ID and episode mapping are available. Unknown or ambiguous mappings are +left unmarked. + +Tracking does not change request eligibility, season-level availability, or +per-user media-server permissions. It does not infer availability from watch +history or playback progress. + +## Upstream context + +This SeerrNG capability is an independently implemented adaptation of work +proposed in Seerr [PR #1671](https://github.com/seerr-team/seerr/pull/1671), +[PR #3355](https://github.com/seerr-team/seerr/pull/3355), +[PR #3361](https://github.com/seerr-team/seerr/pull/3361), +[PR #3527](https://github.com/seerr-team/seerr/pull/3527), and +[PR #3402](https://github.com/seerr-team/seerr/pull/3402). PR #3402 discusses +episode availability from media-server scanners; the SeerrNG implementation +adds explicit per-library episode-order configuration and keeps each source's +records independent during reconciliation. diff --git a/docs/using-seerr/live-download-progress.md b/docs/using-seerr/live-download-progress.md index a3b34191eb..0b5c0dd1c8 100644 --- a/docs/using-seerr/live-download-progress.md +++ b/docs/using-seerr/live-download-progress.md @@ -1,16 +1,32 @@ --- title: Live download progress -description: Show live torrent speed, seeds, and progress by connecting the download clients your *arr services use. +description: Configure bounded Servarr queue tracking and show live download speed, seeds, and progress. sidebar_position: 7 --- # Live download progress By default, SeerrNG updates download progress when the scheduled **Download -Sync** job reads the Radarr, Sonarr, Lidarr, and Bookshelf queues. If you connect -the torrent clients those services use, progress bars on request and media -pages update every few seconds while someone is viewing them. Each download also -shows its current speed and seed count. +Sync** job refreshes and reads the Radarr, Sonarr, Lidarr, Whisparr, and +Bookshelf/Readarr queues. +It waits for each monitored-download refresh command to finish before reading a +queue snapshot. Reads are paginated and bounded. If the refresh fails, a page is +missing, or the reported total changes between pages, SeerrNG keeps the last +verified progress state instead of treating unread items as gone. Download Sync +uses the **Download Queue Size** setting on each Radarr, Sonarr, Lidarr, +Whisparr, or Bookshelf/Readarr service under **Settings → Services**. Edit a +service to set its limit. The default is 1,000 items; choose a +whole number from 10 to 10,000. When a service has more queued items than its +limit, SeerrNG tracks only the first items returned up to that limit. Items +outside that window can appear once they move into the tracked range. This cap +affects SeerrNG progress tracking only; it does not change how the service +processes downloads. + +Queue recovery and intervention use separate, uncapped snapshots with strict +completeness checks. They do not act on a queue when a complete snapshot is +unavailable or exceeds the safety bound. If you connect the torrent clients those services use, progress bars on +request and media pages update every few seconds while someone is viewing them. +Each download also shows its current speed and seed count. SeerrNG only **reads** these clients. It never adds, pauses, moves, or removes torrents; your *arr services keep full control of downloads. diff --git a/docs/using-seerr/notifications/index.mdx b/docs/using-seerr/notifications/index.mdx index 691492e192..5f6bc80e7e 100644 --- a/docs/using-seerr/notifications/index.mdx +++ b/docs/using-seerr/notifications/index.mdx @@ -20,6 +20,20 @@ Simply configure your desired notification agents in **Settings -> Notifications Users can customize their notification preferences in their own user notification settings. +## Pending request edits + +Administrators can enable **Pending Request Updated** for each notification +agent. SeerrNG queues this event only when an edit changes a pending request's +owner, selected seasons or episodes, or saved acquisition options. Unchanged +saves do not create this event, and request lifecycle transitions continue to +use their existing event types. It uses the durable notification queue and is +supported by webhook, ntfy, and the other configured notification agents. + +The webhook event is named `MEDIA_PENDING_UPDATED`. Webhook templates can use +the existing `notification_type` and `event` values to distinguish it from a +new pending request. Review each agent's saved event selection in **Settings → +Notifications**; adding a new event does not change previously saved selections. + ## Follow a movie or series request When another user has an active request for a movie or series, the title's diff --git a/docs/using-seerr/notifications/webhook.md b/docs/using-seerr/notifications/webhook.md index 85a97c02f9..f961a8ec09 100644 --- a/docs/using-seerr/notifications/webhook.md +++ b/docs/using-seerr/notifications/webhook.md @@ -39,7 +39,27 @@ You cannot configure both the **Authorization Header** field and a custom `Autho ### JSON Payload -Customize the JSON payload to suit your needs. Seerr provides several [template variables](#template-variables) for use in the payload, which will be replaced with the relevant data when the notifications are triggered. +Customize the JSON payload to suit your needs. Seerr provides several [template variables](#template-variables) for use in the payload, which will be replaced with the relevant data when the notifications are triggered. String values also support a small set of filters for formatting data expected by the receiving service: + +| Filter | Result | +| --- | --- | +| `lowercase` | Converts text to lowercase. | +| `urlencode` | Encodes text with `encodeURIComponent` for a URL component. | +| `slugify` | Lowercases text, removes combining marks, and replaces runs of non-letter or non-number characters with a hyphen. | + +Use a filter after a variable name. Filters can be chained from left to right: + +```json +{ + "title": "{{subject}}", + "series_slug": "{{subject | slugify}}", + "search": "{{subject | lowercase | urlencode}}" +} +``` + +Filters apply to string values in the JSON payload, not to the webhook URL. Existing unfiltered variables keep their current behavior. Unknown variables without filters remain literal; an unknown variable with filters, an unknown filter, or a malformed filter expression fails that webhook delivery before a request is sent. This is formatting, not HTML or script escaping; encode or validate values for any additional context required by the receiving API. + +Each expression supports at most eight filters. Rendered JSON is limited to 64 KiB (including UTF-8 bytes and JSON escaping), with a shared limit across fields and keys. Repeated substitutions and filter operations also share a rendering-work budget of 1 MiB. A delivery that exceeds these limits fails before any network request is sent. ## Template Variables diff --git a/docs/using-seerr/override-rules.md b/docs/using-seerr/override-rules.md index 68cb858099..b708341d19 100644 --- a/docs/using-seerr/override-rules.md +++ b/docs/using-seerr/override-rules.md @@ -14,9 +14,14 @@ can also fill in request options when a requester opens **Advanced Options**. 1. Open **Settings > Services** and go to **Override Rules**. 2. Select **New Override Rule** and choose the Radarr, Sonarr, or Lidarr service the rule applies to. -3. For Radarr or Sonarr, choose any optional user, genre, language, or keyword - conditions. For Lidarr, rules match the selected requester. +3. For Radarr or Sonarr, choose any optional user, genre, language, keyword, or + production-country conditions. Production countries come from the title's + TMDB metadata; up to 100 countries can be selected. For Lidarr, rules match + the selected requester. 4. Choose the root folder, quality profile, and tags the rule should set. + Sonarr services that expose language profiles also let you select a + language profile. Radarr's quality profile can represent the preferred + language through the profile's own settings. 5. Save the rule. The service must be connected and its root folders, profiles, and tags must be @@ -28,15 +33,38 @@ service. For Radarr and Sonarr rules, every condition field you set must match the request. Within a field, matching any one of its selected values is enough. For example, if a rule has both a user and a genre condition, both the -requester and at least one selected genre must match. Lidarr rules are matched -to the selected requester. +requester and at least one selected genre must match. A production-country +condition matches when at least one selected country is present in the movie's +or series' TMDB production-country metadata. If TMDB has no production-country +metadata for the title, that condition does not match. Country matching uses +the country codes returned by TMDB, not the title's original language or a +studio's country. Lidarr rules are matched to the selected requester. If multiple rules match, SeerrNG applies the rule with the most condition fields. When matching rules have the same number of conditions, the older rule takes precedence. A rule's selected tags are added to the request's existing tags. +Country conditions are available only on Radarr and Sonarr rules. If a title +does not match, SeerrNG continues with the next matching rule or the selected +service's normal settings. + In **Advanced Options**, choose the requester, service, and media options as usual. When a saved rule matches a movie or series request, its configured root folder, quality profile, and tags are applied to the form so they can be -reviewed before submitting. +reviewed before submitting. For Sonarr, a matching language profile is also +selected when the connected version exposes language profiles. An explicit +language profile chosen by the requester is preserved. Sonarr v5 metadata +language remains a separate lookup setting and is not changed by this rule. + +An explicitly selected value takes precedence; an +untouched default can still be supplied by the matching rule when the request +is created. Displayed service and account defaults are not automatically +treated as choices that block a rule. If you deliberately select a value +already shown as the default, SeerrNG keeps that selection and the rule does +not replace it. + +When editing a pending request, choose the connected service's configured +default to clear a saved override. See [Request Defaults and Overrides](./request-defaults.md) +for how anime settings and account preferences affect the values shown in the +form. diff --git a/docs/using-seerr/request-defaults.md b/docs/using-seerr/request-defaults.md new file mode 100644 index 0000000000..0585adffb4 --- /dev/null +++ b/docs/using-seerr/request-defaults.md @@ -0,0 +1,58 @@ +--- +title: Request Defaults and Overrides +description: Understand how movie and series requests use Servarr defaults, account preferences, anime settings, and override rules. +--- + +# Request Defaults and Overrides + +The advanced request form can show values before you change anything. A value +shown in a dropdown is not automatically treated as a deliberate request +override. SeerrNG resolves the selected service and the request owner's +preferences when it creates the request, then applies any matching override +rules. + +## Which defaults are used + +The available values depend on the selected Radarr or Sonarr service and the +person the request is for: + +- Sonarr's anime profile, language profile, root folder, and tags are used when + SeerrNG has classified the series as anime. +- The request owner's preferred language can select matching quality and + language profiles. +- The request owner's preferred root folder for that service is used when it + is available. +- The selected service's configured profile, folder, and tags provide the + remaining defaults. +- A matching override rule can fill a folder, profile, or tags that have not + been changed by an advanced requester. + +Account preferences that differ from the connected service's own settings are +kept with the request so the request uses the preference shown in the form. + +## When a value becomes an override + +If you leave an advanced field at its resolved default, SeerrNG resolves that +default on the server instead of treating the displayed value as a custom +choice. A matching rule can therefore supply its value when the request is +submitted. If you explicitly select a value, that choice is kept even when it +matches the value already shown in the form; a rule does not replace an +explicit selection. + +Tags are compared as a set, so changing only their order does not create a +different request choice. + +## Editing a request + +When you edit a pending movie or series request, SeerrNG keeps saved choices +that you have not changed. To clear a saved folder, profile, language profile, +or tag override, select the connected service's configured default and save. +The saved request destination is updated with the options shown in the form, +so later duplicate checks use the edited destination. + +Requests created by an older SeerrNG version are not rewritten in the +background. Their saved options are considered when you edit them. + +For rule conditions and precedence, see [Configure override rules](./override-rules.md). + +Related Seerr reports provide context for these behaviors: [PR #3477](https://github.com/seerr-team/seerr/pull/3477), [issue #3410](https://github.com/seerr-team/seerr/issues/3410), and [PR #3539](https://github.com/seerr-team/seerr/pull/3539). They describe upstream discussion and do not define SeerrNG's request-target storage. diff --git a/docs/using-seerr/settings/services.md b/docs/using-seerr/settings/services.md index 988c7ac379..fe126407a0 100644 --- a/docs/using-seerr/settings/services.md +++ b/docs/using-seerr/settings/services.md @@ -152,6 +152,28 @@ If the hostname or IP address you configured above is not accessible outside you Enable this setting if you would like to scan your Radarr/Sonarr server for existing media/request status. It is recommended that you enable this setting, so that users cannot submit requests for media which has already been requested or is already available. +To show file availability for each TV episode, enable **Track Individual +Episode Availability** under **Settings → General** and use TheTVDB as the +selected TV or anime metadata provider. See [individual episode availability](../individual-episode-availability.md) +for the scan and display details. + +#### Exclude Tags from Scan (optional) + +After testing the connection, select any Radarr or Sonarr tags whose matching +movies or series should be omitted from that service's SeerrNG scan. A matching +item is marked unknown for that instance, so it will not block a request to the +same destination. Existing SeerrNG media records and requests are retained. If +that instance was the only recorded source, its title-wide availability is also +cleared; a matching copy on another non-excluded service can still count as +available. If the same endpoint is configured more than once, its active +entries share one scan and their excluded tags are combined. + +This setting only changes the Radarr or Sonarr scan. Other configured services +can still report the same media as available, including in Discover's Recently +Added shelf when a media-server integration reports it. Existing settings +files need no migration; an omitted exclusion list behaves as empty. The +feature is inactive until **Enable Scan** is selected. + #### Enable Automatic Search (optional) Enable this setting to have Radarr/Sonarr to automatically search for media upon approval of a request. diff --git a/docs/using-seerr/setup-assistant.md b/docs/using-seerr/setup-assistant.md index 01bdfb581a..228461e2f9 100644 --- a/docs/using-seerr/setup-assistant.md +++ b/docs/using-seerr/setup-assistant.md @@ -6,7 +6,7 @@ sidebar_position: 5 # Cross-platform setup assistant -The setup assistant runs on Windows, macOS, and Linux with Node.js 24.22.1 or +The setup assistant runs on Windows, macOS, and Linux with Node.js 24.22.2 or newer in the 24.x line. Docker is only required for Compose stack generation and Docker network discovery. The assistant does not install or configure Docker, native applications, or operating-system services. diff --git a/package.json b/package.json index 37dad639d1..a970e308ff 100644 --- a/package.json +++ b/package.json @@ -24,10 +24,10 @@ "lint:next": "oxlint --config .oxlintrc.next.json server src", "release-notes:preview": "node scripts/preview-release-notes.mjs", "interface-theme:preview": "node scripts/update-interface-theme-comparison.mjs", - "interface-theme:validate": "node dist/commands/interfaceTheme.js validate", - "interface-theme:pack": "node dist/commands/interfaceTheme.js pack", - "interface-theme:install": "node dist/commands/interfaceTheme.js install", - "interface-theme:uninstall": "node dist/commands/interfaceTheme.js uninstall", + "interface-theme:validate": "node scripts/interface-theme.mjs validate", + "interface-theme:pack": "node scripts/interface-theme.mjs pack", + "interface-theme:install": "node scripts/interface-theme.mjs install", + "interface-theme:uninstall": "node scripts/interface-theme.mjs uninstall", "backissue:service": "node scripts/backissue-service.mjs", "seerr:migrate": "node deploy/seerrng-migrate.mjs", "bookshelf:move": "node scripts/bookshelf-media-move.mjs", @@ -60,7 +60,10 @@ "cypress:prepare": "ts-node -r tsconfig-paths/register --files --project server/tsconfig.json server/scripts/prepareTestDb.ts", "cypress:build": "pnpm build && pnpm cypress:prepare", "cypress:start": "node bin/run-cypress-start.mjs", - "test:playwright": "pnpm cypress:prepare && playwright test" + "test:playwright": "pnpm cypress:prepare && playwright test", + "interface-theme:create": "node scripts/interface-theme.mjs create", + "interface-theme:inspect": "node scripts/interface-theme.mjs inspect", + "interface-theme:list": "node scripts/interface-theme.mjs list" }, "repository": { "type": "git", @@ -225,7 +228,7 @@ "vitest": "^4.1.12" }, "engines": { - "node": "^24.22.1", + "node": "^24.22.2", "pnpm": "^10.0.0" }, "scarfSettings": { diff --git a/packaging/aur/PKGBUILD-bin b/packaging/aur/PKGBUILD-bin index a7e0b09963..83ca04166f 100644 --- a/packaging/aur/PKGBUILD-bin +++ b/packaging/aur/PKGBUILD-bin @@ -6,7 +6,7 @@ arch=('x86_64') options=('!strip') url='https://github.com/snapetech-org/seerrng' license=('MIT') -depends=('nodejs>=24.22.1') +depends=('nodejs>=24.22.2') provides=('seerrng') conflicts=('seerrng') install=seerrng.install diff --git a/packaging/chocolatey/seerrng.nuspec b/packaging/chocolatey/seerrng.nuspec index e0c2ef58ef..a21c8eb457 100644 --- a/packaging/chocolatey/seerrng.nuspec +++ b/packaging/chocolatey/seerrng.nuspec @@ -15,7 +15,7 @@ SeerrNG helps users discover and request media from connected services. This package installs the Windows x64 release as the SeerrNG service and retains its configuration when the package is removed. seerrng seerr media requests discovery sonarr radarr - + diff --git a/packaging/debian/control b/packaging/debian/control index 49d15d3395..5923a50bdc 100644 --- a/packaging/debian/control +++ b/packaging/debian/control @@ -8,7 +8,7 @@ Rules-Requires-Root: no Package: seerrng Architecture: amd64 -Depends: nodejs (>= 24.22.1), adduser, ${misc:Depends} +Depends: nodejs (>= 24.22.2), adduser, ${misc:Depends} Description: Standalone media request and discovery service SeerrNG can be configured to integrate with external Plex, Jellyfin, Emby, Sonarr, Radarr, Lidarr, and Readarr-compatible services. Those services are diff --git a/packaging/rpm/seerrng.spec b/packaging/rpm/seerrng.spec index 7a18429b36..1cacb3cd53 100644 --- a/packaging/rpm/seerrng.spec +++ b/packaging/rpm/seerrng.spec @@ -10,7 +10,7 @@ Source2: seerrng.env Source3: seerrng.sysusers Source4: seerrng.tmpfiles BuildArch: x86_64 -Requires: nodejs >= 24.22.1 +Requires: nodejs >= 24.22.2 %{?systemd_requires} # The release archive bundles native Node modules for multiple platforms. diff --git a/playwright/episode-availability.spec.ts b/playwright/episode-availability.spec.ts new file mode 100644 index 0000000000..70f1b5fe08 --- /dev/null +++ b/playwright/episode-availability.spec.ts @@ -0,0 +1,250 @@ +import { expect, test, type Page } from '@playwright/test'; + +test.use({ serviceWorkers: 'block', reducedMotion: 'reduce' }); +const baseline = process.env.SEERR_EPISODE_BASELINE === 'true'; +const tv = { + id: 1396, + name: 'Episode availability fixture', + originalName: 'Episode availability fixture', + mediaType: 'tv', + firstAirDate: '2020-01-01', + lastAirDate: '2020-01-03', + numberOfSeasons: 1, + numberOfEpisodes: 2, + contentRatings: { results: [] }, + createdBy: [], + episodeRunTime: [22], + genres: [], + homepage: '', + inProduction: false, + languages: ['en'], + networks: [], + originCountry: ['US'], + originalLanguage: 'en', + overview: 'Source inventory and playback access stay independent.', + popularity: 1, + productionCompanies: [], + productionCountries: [], + spokenLanguages: [], + status: 'Ended', + type: 'Scripted', + voteAverage: 8, + voteCount: 100, + credits: { cast: [], crew: [] }, + externalIds: { tvdbId: 79168 }, + keywords: [], + seasons: [ + { + id: 1, + seasonNumber: 1, + name: 'Season 1', + episodeCount: 2, + airDate: '2020-01-01', + overview: '', + }, + ], + mediaInfo: { + id: 1396, + tmdbId: 1396, + mediaType: 'tv', + status: 1, + status4k: 1, + requests: [], + seasons: [], + }, +}; +async function login(page: Page, baseURL: string) { + expect( + ( + await page.request.post(`${baseURL}/api/v1/auth/local`, { + data: { email: 'admin@seerr.dev', password: 'test1234' }, + }) + ).status() + ).toBe(200); + expect( + ( + await page.request.post( + `${baseURL}/api/v1/user/1/settings/interface-theme`, + { data: { theme: process.env.SEERR_EPISODE_THEME ?? 'seerrNGJ' } } + ) + ).status() + ).toBe(200); +} +for (const width of process.env.SEERR_EPISODE_WIDTHS?.split(',').map( + Number +) ?? [1440, 390]) { + test(`library episode order saves without changing enabled libraries at ${width}px`, async ({ + page, + baseURL, + }, info) => { + await page.setViewportSize({ width, height: 900 }); + await login(page, baseURL!); + let saved: Record | undefined; + const library = { + id: '1', + name: 'TV fixture', + type: 'show', + enabled: true, + episodeOrderProvider: 'tmdb', + }; + await page.route('**/api/v1/settings/plex**', async (route) => { + const path = new URL(route.request().url()).pathname; + if (route.request().method() === 'POST') { + saved = route.request().postDataJSON(); + library.episodeOrderProvider = String(saved?.episodeOrderProvider); + return route.fulfill({ json: [library] }); + } + if (path.endsWith('/sync')) + return route.fulfill({ + json: { running: false, progress: 0, total: 0, libraries: [library] }, + }); + return route.fulfill({ + json: { + name: 'Fixture', + ip: '127.0.0.1', + port: 32400, + useSsl: false, + machineId: 'fixture', + libraries: [library], + }, + }); + }); + await page.route('**/api/v1/settings/tautulli', (route) => + route.fulfill({ + json: { hostname: '', port: 8181, apiKey: '', useSsl: false }, + }) + ); + await page.goto('/settings/plex'); + const control = page.getByLabel('Episode Order for TV fixture', { + exact: true, + }); + if (!baseline) { + await control.selectOption('tvdb'); + await expect + .poll(() => saved) + .toMatchObject({ + enable: '1', + episodeOrderLibraryId: '1', + episodeOrderProvider: 'tvdb', + }); + await expect(control).toHaveValue('tvdb'); + await control.scrollIntoViewIfNeeded(); + } else { + await expect(control).toHaveCount(0); + await page + .getByText('TV fixture', { exact: true }) + .first() + .scrollIntoViewIfNeeded(); + } + await page.evaluate(() => window.scrollTo({ top: 0, behavior: 'instant' })); + await page.screenshot({ + fullPage: true, + path: info.outputPath(`library-order-${width}.png`), + animations: 'disabled', + }); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth + ) + ).toBe(true); + }); + test(`live episode tree exposes source files without granting playback at ${width}px`, async ({ + page, + baseURL, + }, info) => { + await page.setViewportSize({ width, height: 900 }); + await login(page, baseURL!); + await page.route('**/_next/data/**/tv/1396.json*', (route) => + route.fulfill({ json: { pageProps: { tv }, __N_SSP: true } }) + ); + await page.route('**/api/v1/tv/1396**', (route) => { + const path = new URL(route.request().url()).pathname; + if (path.includes('/season/')) + return route.fulfill({ + json: { + seasonNumber: 1, + episodes: [ + { + id: 101, + episodeNumber: 1, + seasonNumber: 1, + name: 'Source file only', + airDate: '2020-01-01', + availabilitySources: [ + { sourceType: 'sonarr', hd: true, fourK: false }, + { sourceType: 'plex', hd: true, fourK: true }, + ], + }, + { + id: 102, + episodeNumber: 2, + seasonNumber: 1, + name: 'Missing file', + airDate: '2020-01-02', + }, + ], + }, + }); + if (path === '/api/v1/tv/1396') return route.fulfill({ json: tv }); + return route.fulfill({ + json: { page: 1, totalPages: 0, totalResults: 0, results: [] }, + }); + }); + await page.route('**/api/v1/playback/media/**', (route) => + route.fulfill({ + json: { mediaId: 1396, serverType: 1, is4k: false, groups: [] }, + }) + ); + await page.route('**/api/v1/watchstatus/**', (route) => + route.fulfill({ json: { serverType: 1, seasons: [] } }) + ); + await page.goto('/'); + await page.evaluate(() => (window as any).next.router.push('/tv/1396')); + await expect( + page + .getByRole('heading', { name: `${tv.name} (2020)`, exact: true }) + .first() + ).toBeVisible(); + await page + .getByRole('button', { name: 'Media Server', exact: true }) + .click(); + await page + .getByRole('button', { name: 'Expand Season 01', exact: true }) + .click(); + const episode = page + .locator('[data-tree-part="episode"]') + .filter({ hasText: 'Source file only' }); + await expect(episode).toBeVisible(); + const availability = episode.locator('[data-tree-part="availability"]'); + await expect(availability).toHaveAttribute('data-availability', 'missing'); + if (!baseline) { + await expect + .poll( + async () => + (await episode.locator('[data-tree-part="name"]').boundingBox()) + ?.width ?? 0 + ) + .toBeGreaterThan(40); + await availability.click(); + await expect( + page + .getByRole('tooltip') + .getByText('Available · Sonarr', { exact: true }) + ).toBeVisible(); + await expect( + page + .getByRole('tooltip') + .getByText('Available · Plex · 4K', { exact: true }) + ).toBeVisible(); + } + await page.screenshot({ + path: info.outputPath(`episode-sources-${width}.png`), + animations: 'disabled', + }); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth + ) + ).toBe(true); + }); +} diff --git a/playwright/persius-integration.spec.ts b/playwright/persius-integration.spec.ts new file mode 100644 index 0000000000..75e20ee75b --- /dev/null +++ b/playwright/persius-integration.spec.ts @@ -0,0 +1,1179 @@ +import { expect, test, type Page } from '@playwright/test'; +import { mkdirSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import sharp from 'sharp'; + +// Real signed-in pages, theme catalog/CSS and saved account preferences. Only +// external catalog/read data is deterministic; mutation contracts have native +// API/database coverage in interfaceThemes.openapi and request.test. +test.use({ serviceWorkers: 'block' }); +const screenshotRoot = process.env.SHOT_DIR ?? 'test-results/persius'; +const titles = [ + 'Spider-Man: Brand New Day', + 'The Odyssey', + 'Wildwood', + 'Fall 2: Deadpoint', + 'Resident Evil', + 'Insidious: Out of the Further', + 'Matchbox the Movie', + 'The Dog Stars', + 'Hope', + 'Clayface', + 'Buddy', + 'Forgotten Island', +]; +const bookTitles = [ + 'Fourth Wing', + 'The Martian', + 'Iron Flame', + 'Project Hail Mary', + 'Onyx Storm', + 'The Women', +]; +const imageUrl = (index: number) => + `https://image.tmdb.org/t/p/w500/persius-fixture-${index}.jpg`; +const media = (id: number, status = 1) => ({ + id, + tmdbId: id, + mediaType: 'movie', + status, + status4k: 1, + requests: [], + seasons: [], +}); +const movies = titles.map((title, i) => ({ + id: 100 + i, + title, + mediaType: 'movie', + posterPath: `/persius-fixture-${i}.jpg`, + backdropPath: `/persius-fixture-${i}.jpg`, + releaseDate: `2026-12-${String(10 + i).padStart(2, '0')}`, + genreIds: [28, 12], + voteAverage: 8.5, + voteCount: 100, + popularity: 100, + adult: false, + video: false, + originalLanguage: 'en', + originalTitle: title, + overview: 'A journey that changes everything.', + mediaInfo: media(100 + i, i % 3 === 0 ? 5 : 1), +})); +const movieDetails = (id = 100) => ({ + ...(movies.find((item) => item.id === id) ?? movies[0]), + id, + budget: 0, + revenue: 0, + runtime: 117, + genres: [ + { id: 28, name: 'Action' }, + { id: 12, name: 'Adventure' }, + ], + productionCompanies: [], + productionCountries: [], + spokenLanguages: [], + status: 'Released', + releases: { results: [] }, + credits: { cast: [], crew: [] }, + externalIds: {}, + keywords: [], + videos: { results: [] }, +}); +const books = bookTitles.map((title, i) => ({ + id: `OL${100 + i}W`, + mediaType: 'book', + bookFormat: 'ebook', + title, + author: [ + 'Rebecca Yarros', + 'Andy Weir', + 'Rebecca Yarros', + 'Andy Weir', + 'Rebecca Yarros', + 'Kristin Hannah', + ][i], + authorId: `OL${i + 1}A`, + firstPublishYear: 2023, + posterPath: imageUrl(12 + i), + numberOfPages: 632, + narrators: ['Elizabeth Evans'], + audiobookDuration: 74880, + subjects: ['Fantasy'], + series: [ + { + id: `series-${i % 3}`, + title: ['The Empyrean', 'Throne of Glass', 'A Court of Thorns and Roses'][ + i % 3 + ], + }, + ], + mediaInfo: { ...media(200 + i), mediaType: 'book' }, + description: + 'A story of loyalty, courage, and a world on the edge of change.', +})); +const narrationBook = { + ...books[0], + id: 'OL999W', + title: 'A Court of Wings and Ruin', + author: 'Sarah J. Maas', + firstPublishYear: 2017, + posterPath: imageUrl(18), + bookFormat: 'audiobook', + narrators: ['Elizabeth Evans', 'Amanda Leigh Cobb'], + audiobookDuration: 90360, + numberOfPages: 719, + mediaInfo: { + ...media(999), + mediaType: 'book', + serviceId: 1, + externalServiceId: 3, + }, + series: [ + { id: 'acotar', title: 'A Court of Thorns and Roses', position: '3' }, + ], +}; +const narrations = [ + 'Elizabeth Evans', + 'Amanda Leigh Cobb', + 'Amanda Forstrom, Anthony Palmini, Gabriel Michael', +].map((narrator, i) => ({ + id: `recording-${i}`, + title: narrationBook.title, + format: 'audiobook', + narrators: [narrator], + language: 'en', + production: i === 2 ? 'full-cast' : 'solo', + abridged: 'unabridged', + durationSeconds: i === 0 ? 74880 : 90360, + publisher: 'Recorded Books', + releaseDate: i === 0 ? '2025-01-01' : '2017-01-01', + selected: i === 0, + owned: i === 0, + requestable: true, + imageUrl: i === 0 ? imageUrl(18) : undefined, + unknownFields: [], + editionLabel: i === 0 ? '10th anniversary' : undefined, +})); +const tv = { + id: 1396, + name: 'Friends', + originalName: 'Friends', + mediaType: 'tv', + firstAirDate: '1994-09-22', + lastAirDate: '2004-05-06', + numberOfSeasons: 10, + numberOfEpisodes: 236, + contentRatings: { results: [] }, + createdBy: [], + episodeRunTime: [22], + genres: [{ id: 35, name: 'Comedy' }], + homepage: '', + inProduction: false, + languages: ['en'], + networks: [{ id: 1, name: 'NBC' }], + originCountry: ['US'], + originalLanguage: 'en', + overview: 'Six friends share their lives in New York.', + popularity: 100, + posterPath: '/persius-fixture-1.jpg', + backdropPath: '/persius-fixture-1.jpg', + productionCompanies: [], + productionCountries: [], + spokenLanguages: [], + seasons: Array.from({ length: 10 }, (_, i) => ({ + id: i + 1, + seasonNumber: i + 1, + name: `Season ${i + 1}`, + episodeCount: 24, + airDate: `${1994 + i}-09-22`, + overview: '', + })), + status: 'Ended', + type: 'Scripted', + voteAverage: 8.9, + voteCount: 1000, + credits: { cast: [], crew: [] }, + externalIds: { tvdbId: 79168 }, + keywords: [], + mediaInfo: { ...media(1396), mediaType: 'tv' }, +}; +const pageOf = (results: unknown[]) => ({ + page: 1, + totalPages: 1, + totalResults: results.length, + results, +}); +const requestRows = movies.slice(0, 7).map((item, i) => ({ + id: 700 + i, + type: 'movie', + is4k: false, + status: 1, + createdAt: '2026-10-30T10:00:00Z', + updatedAt: '2026-10-30T10:00:00Z', + requestedBy: { + id: 1, + displayName: 'Nick', + avatar: '/images/seerr_avatar.png', + }, + media: { ...media(item.id, 2), title: item.title }, + seasons: [], + modifiedBy: null, +})); + +const statusSnapshot = (i: number) => ({ + stage: i === 0 ? 'failed' : i > 4 ? 'downloading' : 'searching', + message: + i === 0 + ? 'This recording could not be found' + : i > 4 + ? 'Downloading' + : 'Searching for a copy', + messageKey: i > 4 ? 'downloading' : 'searching', + percent: i > 4 ? 64 : null, + size: null, + sizeLeft: null, + estimatedCompletionTime: null, + downloadCount: i > 4 ? 1 : 0, + downloadId: null, + service: 'Radarr', + isTerminal: i === 0, + needsAttention: i === 0, + retryable: i === 0, + observedAt: '2026-10-30T10:00:00Z', +}); + +async function login( + page: Page, + baseURL: string, + theme = 'persiusNG', + email = 'admin@seerr.dev' +) { + expect( + ( + await page.request.post(`${baseURL}/api/v1/auth/local`, { + data: { email, password: 'test1234' }, + }) + ).status() + ).toBe(200); + const me = await (await page.request.get(`${baseURL}/api/v1/auth/me`)).json(); + const result = await page.request.post( + `${baseURL}/api/v1/user/${me.id}/settings/interface-theme`, + { data: { theme } } + ); + expect(result.status()).toBe(200); + await page.emulateMedia({ colorScheme: 'dark', reducedMotion: 'reduce' }); +} + +async function fixtures(page: Page) { + mkdirSync(screenshotRoot, { recursive: true }); + const appOrigin = new URL(String(test.info().project.use.baseURL)).origin; + await page.route('**/*', (route) => + new URL(route.request().url()).origin === appOrigin + ? route.continue() + : route.abort('blockedbyclient') + ); + const crops = new Map(); + await page.route( + /(?:image\.tmdb\.org|\/imageproxy\/).*persius-fixture-(\d+)\.jpg/, + async (route) => { + const index = Number( + route + .request() + .url() + .match(/persius-fixture-(\d+)/)?.[1] ?? 0 + ); + if (!crops.has(index)) { + // Artwork comes from the previously committed reference-fixture sheet. + const crop = + index < 12 + ? { + left: 786 + (index % 6) * 73, + top: index < 6 ? 148 : 276, + width: 66, + height: 100, + } + : index < 18 + ? { + left: 786 + (index - 12) * 74, + top: 680, + width: 67, + height: 100, + } + : { left: 150, top: 946, width: 79, height: 78 }; + crops.set( + index, + await sharp( + path.join( + process.cwd(), + 'docs/interface-themes/evidence/persiusng-desktop.jpg' + ) + ) + .resize({ width: 1920 }) + .extract(crop) + .jpeg() + .toBuffer() + ); + } + await route.fulfill({ + contentType: 'image/jpeg', + body: crops.get(index), + }); + } + ); + await page.route('**/_next/data/**/movie/*.json*', (route) => + route.fulfill({ + json: { + pageProps: { + movie: movieDetails( + Number( + new URL(route.request().url()).pathname + .split('/') + .pop() + ?.replace('.json', '') + ) + ), + }, + __N_SSP: true, + }, + }) + ); + await page.route('**/_next/data/**/tv/*.json*', (route) => + route.fulfill({ json: { pageProps: { tv }, __N_SSP: true } }) + ); + await page.route('**/api/v1/**', async (route) => { + const url = new URL(route.request().url()); + const p = url.pathname.replace('/api/v1', ''); + let json: unknown; + if (p === '/settings/public') { + const response = await route.fetch(); + json = { + ...(await response.json()), + booksEnabled: true, + ebookServiceEnabled: true, + audiobookServiceEnabled: true, + cacheImages: false, + partialRequestsEnabled: true, + }; + } else if (p === '/settings/discover') + json = [{ id: 1, type: 1, enabled: true, isBuiltIn: true }]; + else if (p === '/discover/trending' || p === '/discover/movies') + json = pageOf(movies); + else if (p === '/discover/tv') + json = pageOf( + Array.from({ length: 12 }, (_, i) => ({ ...tv, id: 1396 + i })) + ); + else if ( + p.startsWith('/discover/books') || + p.startsWith('/discover/audiobooks') + ) + json = pageOf( + books.map((book) => ({ + ...book, + bookFormat: url.searchParams.get('format') ?? 'ebook', + })) + ); + else if (/^\/movie\/\d+$/.test(p)) + json = movieDetails(Number(p.split('/')[2])); + else if (/^\/tv\/\d+$/.test(p)) + json = { ...tv, id: Number(p.split('/')[2]) }; + else if (/^\/tv\/1396\/season\/\d+$/.test(p)) { + const seasonNumber = Number(p.split('/').pop()); + json = { + seasonNumber, + episodes: Array.from({ length: 24 }, (_, i) => ({ + id: seasonNumber * 100 + i, + episodeNumber: i + 1, + seasonNumber, + name: `Episode ${i + 1}`, + airDate: '2000-01-01', + })), + }; + } else if (/^\/book\/[^/]+$/.test(p)) + json = p.endsWith('OL999W') + ? narrationBook + : (books.find((book) => p.endsWith(book.id)) ?? books[0]); + else if (p === '/editions/book') + json = { + format: 'audiobook', + editions: narrations, + supportsAlongside: true, + source: 'library', + }; + else if (p.startsWith('/playback/media/')) + json = { + mediaId: Number(p.split('/').pop()), + serverType: 1, + is4k: false, + groups: [], + }; + else if (p.startsWith('/genres/')) + json = [ + { id: 28, name: 'Action' }, + { id: 12, name: 'Adventure' }, + { id: 35, name: 'Comedy' }, + ]; + else if (p === '/service/sonarr' || p === '/service/radarr') + json = [ + { + id: 1, + name: 'HD', + isDefault: true, + is4k: false, + activeProfileId: 1, + activeDirectory: '/media', + }, + ]; + else if (/^\/service\/(sonarr|radarr)\/1$/.test(p)) + json = { + server: { id: 1, name: 'HD', isDefault: true, is4k: false }, + profiles: [{ id: 1, name: 'HD' }], + rootFolders: [{ id: 1, path: '/media' }], + tags: [], + languageProfiles: [], + }; + else if (p === '/service/readarr') + json = [ + { id: 1, name: 'Books', isDefault: true, serviceType: 'ebook' }, + { + id: 2, + name: 'Audiobooks', + isDefault: true, + serviceType: 'audiobook', + }, + ]; + else if (p === '/request' && route.request().method() === 'GET') { + const count = + url.searchParams.get('filter') === 'available' + ? 3 + : url.searchParams.get('filter') === 'all' + ? 10 + : 7; + json = { + results: requestRows.slice( + 0, + Number(url.searchParams.get('take') ?? 7) + ), + pageInfo: { pages: 1, page: 1, results: count, pageSize: 20 }, + }; + } else if (/^\/request\/7\d\d$/.test(p)) + json = requestRows.find((item) => p.endsWith(String(item.id))); + else if (p === '/request/status/users') + json = { + results: [ + { id: 1, displayName: 'Nick', avatar: '/images/seerr_avatar.png' }, + ], + pageInfo: { results: 1, pages: 1 }, + }; + else if (p === '/request/status') { + const count = + url.searchParams.get('filter') === 'available' + ? 3 + : url.searchParams.get('filter') === 'all' + ? 10 + : 7; + json = { + results: requestRows + .slice(0, Number(url.searchParams.get('take') ?? 7)) + .map((request, i) => ({ + request, + status: statusSnapshot(i), + canRemove: false, + })), + pageInfo: { pages: 1, page: 1, results: count, pageSize: 20 }, + counts: { + total: 10, + active: 7, + incomplete: 7, + attention: 1, + completed: 3, + unavailable: 0, + failed: 1, + }, + olderCount: 0, + }; + } else if (/^\/request\/status\/7\d\d$/.test(p)) { + const i = Number(p.split('/').pop()) - 700; + json = { + request: requestRows[i], + current: statusSnapshot(i), + history: { results: [], total: 0 }, + }; + } else if (p === '/request/count') + json = { + total: 10, + pending: 7, + approved: 0, + processing: 0, + available: 3, + }; + else if (p === '/media') + json = { + results: movies.map((item) => ({ + ...item.mediaInfo, + title: item.title, + posterPath: item.posterPath, + releaseDate: item.releaseDate, + status: 5, + })), + pageInfo: { pages: 1, page: 1, results: 12, pageSize: 20 }, + }; + else if (/\/(ratings|ratingscombined)$/.test(p)) json = { count: 0 }; + else if (/\/(similar|recommendations|associations)$/.test(p)) + json = pageOf([]); + else if (p.startsWith('/watchproviders/') || p.startsWith('/languages')) + json = []; + if (json !== undefined) await route.fulfill({ json }); + else await route.continue(); + }); +} + +async function capture(page: Page, options: Parameters[0]) { + // Compare completed route paint, not a different point in the progress-bar fade. + await expect + .poll(() => + page.evaluate(() => + Array.from(document.body.children).some((element) => { + const style = getComputedStyle(element); + return ( + style.position === 'fixed' && + style.top === '0px' && + element.getBoundingClientRect().height === 3 && + Number(style.opacity) > 0 + ); + }) + ) + ) + .toBe(false); + await page.evaluate(async () => { + await document.fonts.ready; + await Promise.all( + Array.from(document.images) + .filter( + (image) => + image.complete && image.getBoundingClientRect().top < innerHeight + ) + .map((image) => image.decode().catch(() => undefined)) + ); + }); + // Playwright's CSS animation control does not freeze SVG SMIL spinners. + // Capture their first frame without hiding the visible loading indicator. + await page.evaluate(() => { + for (const svg of document.querySelectorAll('svg')) { + if (svg.querySelector('animate, animateTransform, animateMotion')) { + svg.pauseAnimations(); + svg.setCurrentTime(0); + } + } + }); + // Browser font/compositor paint can lag a resize even after fonts.ready. + // Require two identical frames, as snapshot assertions do; do not mask UI. + let previous: Buffer | undefined; + await expect + .poll( + async () => { + const current = await page.screenshot({ + ...options, + path: undefined, + animations: 'disabled', + }); + const stable = previous?.equals(current) ?? false; + previous = current; + return stable; + }, + { intervals: [100, 200, 500], timeout: 10000 } + ) + .toBe(true); + if (options?.path) writeFileSync(options.path, previous!); + await page.evaluate(() => { + for (const svg of document.querySelectorAll('svg')) svg.unpauseAnimations(); + }); +} + +async function navigate(page: Page, route: string) { + await page.goto('/'); + await expect(page.locator('html')).toHaveAttribute( + 'data-interface-theme', + 'persiusNG' + ); + await page.evaluate( + (route) => (window as any).next.router.push(route), + route + ); +} + +const screens = [ + { + name: 'discover', + route: '/', + ready: '.persius-hero', + width: 1782, + height: 1055, + }, + { + name: 'movies', + route: '/discover/movies', + ready: '[data-testid="title-card"]', + width: 1788, + height: 1038, + }, + { + name: 'movie-detail', + route: '/movie/101', + ready: '.persius-detail[data-media-type="movie"]', + width: 1782, + height: 1060, + }, + { + name: 'series', + route: '/discover/tv', + ready: '[data-testid="title-card"]', + width: 1776, + height: 1058, + }, + { + name: 'books', + route: '/discover/books', + ready: '.persius-series-card', + width: 1772, + height: 1064, + }, + { + name: 'audiobooks', + route: '/discover/audiobooks', + ready: '.persius-narrators', + width: 1726, + height: 1061, + }, + { + name: 'narrations', + route: '/book/OL999W?format=audiobook', + ready: '.persius-recordings', + width: 1736, + height: 1046, + }, + { + name: 'requests', + route: '/requests', + ready: '.persius-request', + width: 1726, + height: 1067, + }, + { + name: 'coming-soon', + route: '/coming-soon', + ready: '.persius-release', + width: 1760, + height: 1055, + }, +]; + +for (const screen of screens) { + test(`native Persius ${screen.name} at desktop, tablet and phone`, async ({ + page, + baseURL, + }) => { + const errors: string[] = []; + page.on('pageerror', (error) => errors.push(error.message)); + await login(page, baseURL!); + await fixtures(page); + await page.setViewportSize({ width: screen.width, height: screen.height }); + await page.goto('/'); + await expect(page.locator('html')).toHaveAttribute( + 'data-interface-theme', + 'persiusNG' + ); + await expect + .poll(() => + page + .locator('html') + .evaluate((element) => + getComputedStyle(element) + .getPropertyValue('--interface-sidebar-width') + .trim() + ) + ) + .toBe('244px'); + if (screen.route !== '/') + await page.evaluate( + (route) => (window as any).next.router.push(route), + screen.route + ); + await expect(page.locator(screen.ready).first()).toBeVisible(); + for (const size of [ + { width: screen.width, height: screen.height }, + { width: 768, height: 844 }, + { width: 390, height: 844 }, + ]) { + await page.setViewportSize(size); + const overflow = await page.evaluate(() => ({ + width: innerWidth, + scrollWidth: document.documentElement.scrollWidth, + elements: Array.from(document.querySelectorAll('*')) + .filter( + (element) => element.getBoundingClientRect().right > innerWidth + 1 + ) + .slice(0, 30) + .map((element) => ({ + tag: element.tagName, + class: element.className, + width: element.getBoundingClientRect().width, + right: element.getBoundingClientRect().right, + })), + })); + writeFileSync( + `${screenshotRoot}/${screen.name}-${size.width}-geometry.json`, + JSON.stringify(overflow, null, 2) + ); + await expect + .poll(() => + page.evaluate( + () => document.documentElement.scrollWidth <= window.innerWidth + 1 + ) + ) + .toBe(true); + await page.evaluate(async () => { + await document.fonts.ready; + await Promise.all( + Array.from(document.images) + .filter( + (image) => + image.complete && + image.getBoundingClientRect().top < window.innerHeight + ) + .map((image) => image.decode().catch(() => undefined)) + ); + }); + await capture(page, { + path: `${screenshotRoot}/${screen.name}-${size.width}.png`, + }); + } + expect(errors).toEqual([]); + }); +} + +test('native account theme switching survives reload and loads one package at a time', async ({ + page, + baseURL, +}) => { + await login(page, baseURL!); + await fixtures(page); + for (const theme of ['seerrOrig', 'seerrNGJ', 'persiusNG']) { + expect( + ( + await page.request.post( + `${baseURL}/api/v1/user/1/settings/interface-theme`, + { data: { theme } } + ) + ).status() + ).toBe(200); + await page.goto('/discover/movies'); + await expect(page.locator('html')).toHaveAttribute( + 'data-interface-theme', + theme + ); + await expect( + page.locator(`link[href*="/interface-themes/${theme}/theme.css"]`) + ).toHaveCount(1); + await page.reload(); + await expect(page.locator('html')).toHaveAttribute( + 'data-interface-theme', + theme + ); + } +}); + +test('installed community package uses native composition and restores its independent stylesheet', async ({ + page, + baseURL, +}) => { + const theme = process.env.E2E_CUSTOM_THEME_ID; + test.skip( + !theme, + 'Install a disposable Persius derivative and set E2E_CUSTOM_THEME_ID.' + ); + await login(page, baseURL!, theme); + await fixtures(page); + const catalog = await ( + await page.request.get(`${baseURL}/api/v1/interface-themes`) + ).json(); + expect( + catalog.themes.find((item: { id: string }) => item.id === theme)?.layout + ).toBe('persius'); + await page.goto('/discover/movies'); + await expect(page.locator('html')).toHaveAttribute( + 'data-interface-theme', + theme! + ); + await expect(page.locator('.persius-poster-caption').first()).toBeVisible(); + await expect( + page.locator('link[data-interface-theme-stylesheet]') + ).toHaveCount(1); + await expect( + page.locator(`link[href*="/interface-themes/${theme}/theme.css"]`) + ).toHaveCount(1); + await page.reload(); + await expect(page.locator('html')).toHaveAttribute( + 'data-interface-theme', + theme! + ); + await capture(page, { path: `${screenshotRoot}/community-package.png` }); + expect( + ( + await page.request.post( + `${baseURL}/api/v1/user/1/settings/interface-theme`, + { data: { theme: 'persiusNG' } } + ) + ).status() + ).toBe(200); +}); + +test('native catalog filters, poster captions and keyboard request entry', async ({ + page, + baseURL, +}) => { + await login(page, baseURL!); + await fixtures(page); + await navigate(page, '/discover/movies'); + await expect(page.locator('.persius-poster-caption').first()).toContainText( + '1h 57m' + ); + await page + .locator('.persius-segments') + .getByRole('button', { name: 'In library', exact: true }) + .click(); + await expect(page.locator('[data-testid="title-card"]')).toHaveCount(4); + await expect(page).toHaveURL(/libraryView=available/); + await page + .locator('.persius-segments') + .getByRole('button', { name: 'All', exact: true }) + .click(); + await page.getByRole('button', { name: 'Action', exact: true }).click(); + await expect(page).toHaveURL(/genre=28/); + await page.locator('.persius-sort select').selectOption('vote_average.desc'); + await expect(page).toHaveURL(/sortBy=vote_average.desc/); + const card = page.locator('[data-testid="title-card"]').nth(1); + await card.locator('[data-poster-region="frame"]').focus(); + await page.keyboard.press('Enter'); + await card.getByRole('button', { name: /Request/ }).click(); + await expect(page.getByRole('dialog')).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(page.getByRole('dialog')).toHaveCount(0); +}); + +test('catalog metadata failures preserve saved watchlist state and poster identity', async ({ + page, + baseURL, +}) => { + await login(page, baseURL!); + await fixtures(page); + // The default seed links a dummy Plex account. This scenario exercises the + // local-watchlist presentation; login and account theme persistence stay real. + await page.route('**/api/v1/auth/me', async (route) => { + const response = await route.fetch(); + await route.fulfill({ json: { ...(await response.json()), userType: 2 } }); + }); + await page.route('**/api/v1/discover/movies?*', (route) => + route.fulfill({ + json: pageOf( + movies.map((item) => ({ + ...item, + mediaInfo: { ...item.mediaInfo, watchlists: [{ id: 1 }] }, + })) + ), + }) + ); + await page.route('**/api/v1/movie/100', (route) => + route.fulfill({ + status: 503, + json: { message: 'Fixture metadata unavailable' }, + }) + ); + await navigate(page, '/discover/movies'); + const card = page.locator('[data-testid="title-card"]').first(); + await expect(card.locator('.persius-poster-caption')).toContainText( + titles[0] + ); + await card.locator('[data-poster-region="frame"]').focus(); + await page.keyboard.press('Enter'); + await expect( + card.getByRole('button', { name: /Remove .* from your Watchlist/ }) + ).toBeVisible(); +}); + +test('native season dialog selects all, latest and none and retains future-season preference', async ({ + page, + baseURL, +}) => { + await login(page, baseURL!, 'persiusNG', 'friend@seerr.dev'); + await fixtures(page); + await page.setViewportSize({ width: 1776, height: 1058 }); + await navigate(page, '/discover/tv'); + const card = page.locator('[data-testid="title-card"]').first(); + await card.locator('[data-poster-region="frame"]').hover(); + await card.getByRole('button', { name: /Request/ }).click(); + const dialog = page.getByRole('dialog'); + await expect(dialog.locator('.persius-season')).toHaveCount(10); + await dialog.getByRole('button', { name: 'Clear', exact: true }).click(); + await expect(dialog.locator('.persius-season input:checked')).toHaveCount(0); + await dialog + .getByRole('button', { name: 'Latest season only', exact: true }) + .click(); + await expect(dialog.locator('.persius-season input:checked')).toHaveCount(1); + await expect( + dialog.locator('.persius-season').last().locator('input') + ).toBeChecked(); + await dialog + .getByRole('button', { name: 'Entire series', exact: true }) + .click(); + await expect(dialog.locator('.persius-season input:checked')).toHaveCount(10); + await expect(dialog.getByRole('switch')).toBeChecked(); + await dialog.getByRole('switch').uncheck(); + await expect(dialog.getByRole('switch')).not.toBeChecked(); + await dialog.getByRole('switch').check(); + await expect(dialog.getByRole('switch')).toBeChecked(); + await dialog.evaluate((element) => element.scrollTo({ top: 0 })); + await expect(dialog.locator('.persius-modal-identity')).toBeInViewport(); + const futureOrder = await dialog.evaluate((element) => { + const future = element.querySelector('.persius-future-seasons')!; + const episodes = Array.from(element.querySelectorAll('summary')).find( + (item) => item.textContent === 'Choose individual episodes' + )!; + return Boolean( + future.compareDocumentPosition(episodes) & + Node.DOCUMENT_POSITION_FOLLOWING + ); + }); + expect(futureOrder).toBe(true); + await capture(page, { path: `${screenshotRoot}/season-dialog-1776.png` }); + await page.setViewportSize({ width: 390, height: 844 }); + await expect + .poll(() => + dialog.evaluate( + (element) => element.getBoundingClientRect().width <= innerWidth + ) + ) + .toBe(true); + await capture(page, { path: `${screenshotRoot}/season-dialog-390.png` }); + await page.keyboard.press('Escape'); + await expect(dialog).toHaveCount(0); +}); + +for (const theme of ['seerrOrig', 'seerrNGJ']) { + test(`existing interfaces: ${theme} shared consumers at desktop and phone`, async ({ + page, + baseURL, + }) => { + const errors: string[] = []; + page.on('pageerror', (error) => errors.push(error.message)); + await login(page, baseURL!, theme); + await fixtures(page); + await page.goto('/'); + await expect(page.locator('html')).toHaveAttribute( + 'data-interface-theme', + theme + ); + for (const [name, route, ready] of [ + ['movies', '/discover/movies', '[data-testid="title-card"]'], + ['movie-detail', '/movie/101', '.media-page'], + ['book-detail', '/book/OL999W', '.media-page'], + ['requests', '/requests', '[data-testid="request-status-700"]'], + ['settings', '/settings/main', '.settings-page-content'], + ]) { + await page.evaluate( + (route) => (window as any).next.router.push(route), + route + ); + await expect(page.locator(ready).first()).toBeVisible(); + for (const width of [1782, 390]) { + await page.setViewportSize({ + width, + height: width === 390 ? 844 : 1060, + }); + await page.evaluate(async () => { + window.scrollTo(0, 0); + await document.fonts.ready; + }); + await expect + .poll(() => + page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth + 1 + ) + ) + .toBe(true); + await capture(page, { + path: `${screenshotRoot}/${theme}-${name}-${width}.png`, + }); + } + } + expect(errors).toEqual([]); + }); +} + +test('native request loading, empty and error states retain a title and recovery', async ({ + page, + baseURL, +}) => { + await login(page, baseURL!); + await fixtures(page); + let state: 'loading' | 'empty' | 'error' = 'loading'; + let releaseLoading!: () => void; + const loading = new Promise((resolve) => { + releaseLoading = resolve; + }); + await page.route('**/request/status?*', async (route) => { + if (state === 'loading') await loading; + if (state === 'error') + return route.fulfill({ + status: 503, + json: { message: 'Temporary fixture outage' }, + }); + return route.fulfill({ + json: { + results: [], + pageInfo: { pages: 1, page: 1, results: 0, pageSize: 20 }, + counts: { + total: 0, + active: 0, + incomplete: 0, + attention: 0, + completed: 0, + unavailable: 0, + failed: 0, + }, + olderCount: 0, + }, + }); + }); + await navigate(page, '/requests'); + await expect(page.locator('.page-title').first()).toHaveText('Requests'); + await capture(page, { path: `${screenshotRoot}/requests-loading.png` }); + state = 'empty'; + releaseLoading(); + await expect( + page.getByRole('heading', { name: 'No Requests Found', exact: true }) + ).toBeVisible(); + await capture(page, { path: `${screenshotRoot}/requests-empty.png` }); + state = 'error'; + await page.reload(); + await expect( + page.getByRole('button', { name: 'Retry', exact: true }) + ).toBeVisible(); + await expect(page.locator('.page-title').first()).toHaveText('Requests'); + await capture(page, { path: `${screenshotRoot}/requests-error.png` }); + state = 'empty'; + await page.getByRole('button', { name: 'Retry', exact: true }).click(); + await expect( + page.getByRole('heading', { name: 'No Requests Found', exact: true }) + ).toBeVisible(); +}); + +test('native narration choice opens the request flow for that recording', async ({ + page, + baseURL, +}) => { + await login(page, baseURL!); + await fixtures(page); + await navigate(page, '/book/OL999W?format=audiobook'); + await expect(page.locator('.persius-recording')).toHaveCount(3); + await page.locator('input[value="recording-2"]').check(); + const request = page.getByRole('button', { + name: /Request · Amanda Forstrom/, + }); + await expect(request).toBeEnabled(); + await request.click(); + await expect(page.getByRole('dialog')).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(page.getByRole('dialog')).toHaveCount(0); + await expect(page.locator('input[value="recording-2"]')).toBeChecked(); +}); + +test('native request tabs keep owner scope and expose the existing management flow', async ({ + page, + baseURL, +}) => { + await login(page, baseURL!); + await fixtures(page); + const queries: string[] = []; + page.on('request', (request) => { + if (request.url().includes('/request/status?')) queries.push(request.url()); + }); + await navigate(page, '/requests'); + await expect(page.locator('.persius-request')).toHaveCount(7); + await page + .locator('.persius-request-tabs') + .getByRole('button', { name: 'Ready 3', exact: true }) + .click(); + await expect(page).toHaveURL(/filter=available/); + await page + .locator('.persius-request-tabs') + .getByRole('button', { name: 'All 10', exact: true }) + .click(); + await expect(page).toHaveURL(/filter=all/); + expect(queries.length).toBeGreaterThan(0); + expect( + queries.every((url) => new URL(url).searchParams.get('requestedBy') === '1') + ).toBe(true); + await page + .locator('.persius-request') + .first() + .getByRole('button', { name: 'Details and actions', exact: true }) + .click(); + await expect(page.getByRole('dialog')).toBeVisible(); + await expect( + page + .getByRole('dialog') + .getByRole('button', { name: 'History', exact: true }) + ).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(page.getByRole('dialog')).toHaveCount(0); +}); + +test('theme picker changes the loaded CSS, supports light mode and recovers from failed saves', async ({ + page, + baseURL, +}) => { + await login(page, baseURL!); + await fixtures(page); + await page.goto('/discover/movies'); + await expect(page.locator('.persius-dock')).toBeVisible(); + await page + .getByRole('button', { name: 'Toggle light and dark mode' }) + .click(); + await expect(page.locator('html')).toHaveAttribute( + 'data-theme-mode', + 'light' + ); + await page + .getByRole('button', { name: 'Toggle light and dark mode' }) + .click(); + await page + .getByRole('button', { name: 'Theme picker', exact: true }) + .filter({ visible: true }) + .click(); + await page.getByRole('menuitem', { name: /SeerrOrig/ }).click(); + await expect(page.locator('html')).toHaveAttribute( + 'data-interface-theme', + 'seerrOrig' + ); + await expect( + page.locator('link[data-interface-theme-stylesheet][media="all"]') + ).toHaveCount(1); + await page.route('**/settings/interface-theme', (route) => + route.fulfill({ status: 503, json: { message: 'Test unavailable' } }) + ); + await page + .getByRole('button', { name: 'Theme picker', exact: true }) + .filter({ visible: true }) + .click(); + await page.getByRole('menuitem', { name: /^PersiusNG/ }).click(); + await expect( + page.getByText('Could not save your theme. Please try again.') + ).toBeVisible(); + await expect(page.locator('html')).toHaveAttribute( + 'data-interface-theme', + 'seerrOrig' + ); + await expect( + page.locator('link[data-interface-theme-stylesheet]') + ).toHaveCount(1); +}); diff --git a/playwright/request-edit-without-media.spec.ts b/playwright/request-edit-without-media.spec.ts index cd73fdd85a..3aab044c3d 100644 --- a/playwright/request-edit-without-media.spec.ts +++ b/playwright/request-edit-without-media.spec.ts @@ -68,9 +68,9 @@ for (const viewport of [ createdAt: '2026-10-04T12:00:00.000Z', seasons: [], is4k: false, - serverId: null, - profileId: null, - rootFolder: null, + serverId: 42, + profileId: 0, + rootFolder: '/media', languageProfileId: null, tags: [], }; @@ -160,9 +160,43 @@ for (const viewport of [ json: { page: 1, totalPages: 0, totalResults: 0, results: [] }, }) ); - await page.route('**/api/v1/service/radarr*', (route) => - route.fulfill({ json: [] }) - ); + const service = { + id: 42, + name: 'Request fixture', + isDefault: true, + is4k: false, + activeProfileId: 0, + activeDirectory: '/media', + activeTags: [], + }; + await page.route('**/api/v1/service/radarr**', (route) => { + const pathname = new URL(route.request().url()).pathname; + return route.fulfill({ + json: + pathname === '/api/v1/service/radarr/42' + ? { + server: service, + profiles: [ + { id: 0, name: 'Zero Profile' }, + { id: 2, name: 'Other Profile' }, + ], + rootFolders: [{ id: 1, path: '/media' }], + tags: [], + } + : pathname === '/api/v1/service/radarr' + ? [service] + : [], + }); + }); + let saved: Record | undefined; + await page.route('**/api/v1/request/987654**', async (route) => { + if (new URL(route.request().url()).pathname.endsWith('/approve')) { + await route.fulfill({ json: { ...request, status: 2 } }); + } else if (route.request().method() === 'PUT') { + saved = route.request().postDataJSON(); + await route.fulfill({ json: { ...request, ...saved } }); + } else await route.fulfill({ json: request }); + }); await page.route('**/api/v1/media/987654/library*', (route) => route.fulfill({ json: { targets: [] } }) ); @@ -170,6 +204,13 @@ for (const viewport of [ route.fulfill({ status: 404, json: { message: 'Not found' } }) ); + await page.route('**/api/v1/playback/**', (route) => + route.fulfill({ + status: 503, + json: { message: 'Playback unavailable in this fixture' }, + }) + ); + const movieResponse = page.waitForResponse((response) => { const pathname = new URL(response.url()).pathname; return ( @@ -234,9 +275,36 @@ for (const viewport of [ }); } await expect(editDialog).toBeVisible(); + const profile = editDialog.locator('#profile'); + await expect(profile).toContainText('Zero Profile'); + if (process.env.SEERR_REQUEST_CONTROLS_BASELINE !== 'true') { + await expect(page.getByRole('dialog')).toHaveCount(2); + await page.mouse.click(2, 2); + await expect(editDialog).toHaveCount(0); + await expect(page.getByRole('dialog')).toHaveCount(1); + await editButton.click(); + await expect(editDialog).toBeVisible(); + await profile.click(); + await expect(editDialog).toBeVisible(); + await page + .getByRole('option', { name: 'Zero Profile', exact: true }) + .click(); + await expect(profile).toContainText('Zero Profile'); + } await page.screenshot({ path: testInfo.outputPath(`edit-request-modal-${viewport.name}.png`), animations: 'disabled', }); + if (process.env.SEERR_REQUEST_CONTROLS_BASELINE !== 'true') { + await editDialog + .getByRole('button', { name: 'Approve Request', exact: true }) + .click(); + await expect.poll(() => saved?.profileId).toBe(null); + expect(saved?.requestTargetOptions).toMatchObject({ + profileId: 0, + rootFolder: '/media', + }); + await expect(editDialog).toHaveCount(0); + } }); } diff --git a/playwright/request-policy-controls.spec.ts b/playwright/request-policy-controls.spec.ts new file mode 100644 index 0000000000..8184f1a45e --- /dev/null +++ b/playwright/request-policy-controls.spec.ts @@ -0,0 +1,208 @@ +import { expect, test, type Page } from '@playwright/test'; + +test.use({ serviceWorkers: 'block', reducedMotion: 'reduce' }); +const baseline = process.env.SEERR_POLICY_BASELINE === 'true'; +const fixture = { + id: 0, + name: 'Policy fixture', + hostname: '127.0.0.1', + port: 8989, + apiKey: 'fixture-only-api-key', + useSsl: false, + baseUrl: '', + activeProfileId: 0, + activeProfileName: 'Any', + activeDirectory: '/media', + activeLanguageProfileId: 0, + isDefault: true, + is4k: false, + syncEnabled: true, + preventSearch: false, + tagRequests: false, + tags: [], + minimumAvailability: 'released', + externalUrl: '', + backend: 'readarr', + serviceType: 'ebook', +}; +const serviceResponse = { + profiles: [{ id: 0, name: 'Any' }], + rootFolders: [{ id: 1, path: '/media' }], + tags: [], + languageProfiles: [{ id: 0, name: 'Zero language' }], +}; +async function configure(page: Page, service: 'sonarr' | 'readarr') { + await page.route('**/api/v1/settings/public', async (route) => { + const response = await route.fetch(); + await route.fulfill({ + json: { ...(await response.json()), booksEnabled: true }, + }); + }); + for (const kind of ['radarr', 'sonarr', 'lidarr', 'readarr']) { + await page.route(`**/api/v1/settings/${kind}**`, async (route) => { + await route.fulfill({ + json: new URL(route.request().url()).pathname.endsWith('/test') + ? serviceResponse + : kind === service + ? [fixture] + : [], + }); + }); + } + await page.route('**/api/v1/regions', (route) => + route.fulfill({ + json: [ + { iso_3166_1: 'CA', english_name: 'Canada', native_name: 'Canada' }, + { + iso_3166_1: 'US', + english_name: 'United States', + native_name: 'United States', + }, + ], + }) + ); +} +for (const width of [1440, 390]) { + test(`country and language profile override controls at ${width}px`, async ({ + page, + baseURL, + }, info) => { + await page.setViewportSize({ width, height: 900 }); + expect( + ( + await page.request.post(`${baseURL}/api/v1/auth/local`, { + data: { email: 'admin@seerr.dev', password: 'test1234' }, + }) + ).status() + ).toBe(200); + await configure(page, 'sonarr'); + let saved: Record | undefined; + await page.route('**/api/v1/overrideRule**', async (route) => { + if (route.request().method() === 'POST') { + saved = route.request().postDataJSON(); + await route.fulfill({ json: { ...saved, id: 91 } }); + } else await route.fulfill({ json: [] }); + }); + await page.goto('/settings/services'); + await page + .getByRole('button', { name: 'New Override Rule', exact: true }) + .click(); + const dialog = page.getByRole('dialog'); + await dialog.locator('#service').selectOption('sonarr-0'); + await expect( + dialog.locator('#profileIdRule option[value="0"]') + ).toHaveCount(1); + if (!baseline) { + await dialog.locator('#productionCountries').fill('Canada'); + await page.getByRole('option', { name: 'Canada', exact: true }).click(); + await dialog.locator('#languageProfileIdRule').selectOption('0'); + } + await dialog.screenshot({ + animations: 'disabled', + path: info.outputPath(`country-rule-${width}.png`), + }); + if (baseline) return; + await dialog + .getByRole('button', { name: 'Create rule', exact: true }) + .click(); + await expect + .poll(() => saved) + .toMatchObject({ + sonarrServiceId: 0, + productionCountries: 'CA', + languageProfileId: 0, + }); + await expect(dialog).toHaveCount(0); + }); + test(`Bookshelf-only configuration can create an override at ${width}px`, async ({ + page, + baseURL, + }, info) => { + await page.setViewportSize({ width, height: 900 }); + expect( + ( + await page.request.post(`${baseURL}/api/v1/auth/local`, { + data: { email: 'admin@seerr.dev', password: 'test1234' }, + }) + ).status() + ).toBe(200); + await configure(page, 'readarr'); + await page.route('**/api/v1/overrideRule**', (route) => + route.fulfill({ json: [] }) + ); + await page.goto('/settings/services'); + const action = page.getByRole('button', { + name: 'New Override Rule', + exact: true, + }); + if (baseline) { + await expect(action).toBeDisabled(); + await page.screenshot({ + animations: 'disabled', + path: info.outputPath(`books-only-${width}.png`), + }); + return; + } + await expect(action).toBeEnabled(); + await action.click(); + const dialog = page.getByRole('dialog'); + await dialog.locator('#service').selectOption('readarr-0'); + await expect(dialog.locator('#genre')).toBeVisible(); + await expect(dialog.locator('#productionCountries')).toHaveCount(0); + await dialog.screenshot({ + animations: 'disabled', + path: info.outputPath(`books-only-${width}.png`), + }); + }); + test(`pending-edit notification opt-in at ${width}px`, async ({ + page, + baseURL, + }, info) => { + await page.setViewportSize({ width, height: 900 }); + expect( + ( + await page.request.post(`${baseURL}/api/v1/auth/local`, { + data: { email: 'admin@seerr.dev', password: 'test1234' }, + }) + ).status() + ).toBe(200); + let saved: Record | undefined; + const state = { + enabled: false, + types: 0, + options: { + webhookUrl: 'https://example.invalid/notify', + jsonPayload: '{}', + authHeader: '', + customHeaders: [], + supportVariables: false, + }, + }; + await page.route( + '**/api/v1/settings/notifications/webhook', + async (route) => { + if (route.request().method() === 'POST') { + saved = route.request().postDataJSON(); + await route.fulfill({ json: saved }); + } else await route.fulfill({ json: state }); + } + ); + await page.goto('/settings/notifications/webhook'); + const option = page.locator('#media-pending-updated'); + if (!baseline) { + await option.check(); + await expect(option).toBeChecked(); + } else await expect(page.locator('#media-requested')).toBeVisible(); + await page.evaluate(() => window.scrollTo(0, 0)); + await page.screenshot({ + animations: 'disabled', + path: info.outputPath(`notification-types-${width}.png`), + fullPage: true, + }); + if (baseline) return; + await page.getByRole('button', { name: 'Save', exact: true }).click(); + await expect + .poll(() => saved) + .toMatchObject({ enabled: true, types: 32768 }); + }); +} diff --git a/playwright/request-service-controls.spec.ts b/playwright/request-service-controls.spec.ts new file mode 100644 index 0000000000..078c353b99 --- /dev/null +++ b/playwright/request-service-controls.spec.ts @@ -0,0 +1,121 @@ +import { expect, test } from '@playwright/test'; + +test.use({ serviceWorkers: 'block' }); +const baseline = process.env.SEERR_REQUEST_CONTROLS_BASELINE === 'true'; +for (const width of [1440, 390]) { + for (const service of ['radarr', 'sonarr', 'lidarr']) { + test(`${service} queue and scan controls at ${width}px`, async ({ + page, + baseURL, + }, info) => { + await page.setViewportSize({ width, height: 900 }); + const login = await page + .context() + .request.post(`${baseURL}/api/v1/auth/local`, { + data: { email: 'admin@seerr.dev', password: 'test1234' }, + }); + expect(login.status()).toBe(200); + const fixture = { + id: 42, + name: `${service} fixture`, + hostname: '127.0.0.1', + port: 8989, + apiKey: 'fixture-only-api-key', + useSsl: false, + baseUrl: '', + activeProfileId: 1, + activeProfileName: 'Any', + activeDirectory: '/media', + activeLanguageProfileId: 1, + activeMetadataProfileId: 1, + activeMetadataProfileName: 'Any', + isDefault: true, + is4k: false, + syncEnabled: true, + preventSearch: false, + tagRequests: false, + tags: [], + syncExcludedTags: [], + downloadQueueSize: 1000, + minimumAvailability: 'released', + externalUrl: '', + }; + let saved: Record | undefined; + await page.route(`**/api/v1/settings/${service}**`, async (route) => { + const pathname = new URL(route.request().url()).pathname; + if (pathname.endsWith('/test')) { + await route.fulfill({ + json: { + profiles: [{ id: 1, name: 'Any' }], + metadataProfiles: [{ id: 1, name: 'Any' }], + rootFolders: [{ id: 1, path: '/media' }], + tags: [{ id: 42, label: 'Archived' }], + languageProfiles: [{ id: 1, name: 'English' }], + }, + }); + } else if (route.request().method() === 'PUT') { + saved = route.request().postDataJSON(); + await route.fulfill({ json: { ...fixture, ...saved } }); + } else { + await route.fulfill({ json: [fixture] }); + } + }); + await page.goto('/settings/services'); + if (service === 'lidarr') + await page.getByRole('button', { name: 'Music', exact: true }).click(); + await page + .locator('.settings-service-card') + .filter({ hasText: fixture.name }) + .getByRole('button', { name: 'Edit', exact: true }) + .click(); + const dialog = page.getByRole('dialog'); + await expect(dialog).toBeVisible(); + const save = dialog.getByRole('button', { + name: 'Save Changes', + exact: true, + }); + const queue = dialog.getByLabel('Download Queue Size', { exact: true }); + if (baseline) { + await expect(queue).toHaveCount(0); + } else { + await expect(queue).toHaveValue('1000'); + await queue.fill('9'); + await queue.press('Tab'); + await expect(queue).toHaveAttribute('aria-invalid', 'true'); + await expect(save).toBeDisabled(); + await queue.fill('1500'); + await queue.press('Tab'); + await expect(queue).toHaveAttribute('aria-invalid', 'false'); + if (service !== 'lidarr') { + const tags = dialog.getByLabel('Exclude Tags from Scan', { + exact: true, + }); + await expect(tags).toBeEnabled(); + await tags.fill('Archived'); + await page + .getByRole('option', { name: 'Archived', exact: true }) + .click(); + } + } + await page.locator('#syncEnabled').scrollIntoViewIfNeeded(); + await page.screenshot({ + path: info.outputPath(`${service}-${width}.png`), + animations: 'disabled', + }); + await expect + .poll(() => + page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth + ) + ) + .toBe(true); + if (!baseline) { + await expect(save).toBeEnabled(); + await save.click(); + await expect.poll(() => saved?.downloadQueueSize).toBe(1500); + if (service !== 'lidarr') expect(saved?.syncExcludedTags).toEqual([42]); + await expect(dialog).toHaveCount(0); + } + }); + } +} diff --git a/prettier-scope.txt b/prettier-scope.txt index 56bcc82c9e..3b79932aa2 100644 --- a/prettier-scope.txt +++ b/prettier-scope.txt @@ -16,6 +16,8 @@ coverage/ out/ build/ artifacts/ +test-results/ +playwright-report/ cypress/runtime-config/ cypress/videos/ cypress/screenshots/ diff --git a/release-notes/2026-10-31-openapi-api-contract-alignment.md b/release-notes/2026-10-31-openapi-api-contract-alignment.md new file mode 100644 index 0000000000..14c6bab9d9 --- /dev/null +++ b/release-notes/2026-10-31-openapi-api-contract-alignment.md @@ -0,0 +1,9 @@ +--- +category: fixed +audience: users, operators +area: api +action: none +breaking: false +--- + +The API specification now separates user updates from safe user responses and accurately describes request, media, issue and provider data. Country and language-profile override rules pass production validation, while provider credentials remain excluded from the documented response contract. diff --git a/release-notes/2026-11-01-radarr-sonarr-sync-tag-exclusions.md b/release-notes/2026-11-01-radarr-sonarr-sync-tag-exclusions.md new file mode 100644 index 0000000000..bab8f18119 --- /dev/null +++ b/release-notes/2026-11-01-radarr-sonarr-sync-tag-exclusions.md @@ -0,0 +1,9 @@ +--- +category: changed +audience: users, operators +area: servarr +action: none +breaking: false +--- + +Administrators can exclude tagged Radarr or Sonarr library entries from scans while SeerrNG preserves existing requests and still recognizes non-excluded copies on other configured services. diff --git a/release-notes/2026-11-05-episode-inventory-recovery.md b/release-notes/2026-11-05-episode-inventory-recovery.md new file mode 100644 index 0000000000..a9145032b4 --- /dev/null +++ b/release-notes/2026-11-05-episode-inventory-recovery.md @@ -0,0 +1,9 @@ +--- +category: fixed +audience: users, operators +area: availability +action: none +breaking: false +--- + +Episode inventories preserve complete snapshots after malformed or partial scans and support Sonarr service zero. Linked accounts see only verified media-server episode files and qualities. Phone episode tables retain readable names and reachable status controls, including disabled rows with keyboard-accessible explanations. diff --git a/release-notes/2026-11-05-nullable-api-enums.md b/release-notes/2026-11-05-nullable-api-enums.md new file mode 100644 index 0000000000..54c6bdb9f6 --- /dev/null +++ b/release-notes/2026-11-05-nullable-api-enums.md @@ -0,0 +1,9 @@ +--- +category: fixed +audience: users, operators +area: api +action: none +breaking: false +--- + +Valid Bookshelf series and request responses no longer fail validation when optional enum fields are null. Nullable API enum declarations explicitly accept null, preserving documented preference-reset behavior and optional edition metadata. diff --git a/release-notes/2026-11-05-request-policy-recovery.md b/release-notes/2026-11-05-request-policy-recovery.md new file mode 100644 index 0000000000..21ee786dde --- /dev/null +++ b/release-notes/2026-11-05-request-policy-recovery.md @@ -0,0 +1,9 @@ +--- +category: fixed +audience: users, operators +area: requests +action: none +breaking: false +--- + +Pending request edits save successfully with update notifications enabled and notify once per effective change. Country rules tolerate missing metadata and accept language profile zero through the API. Bookshelf-only setups can create override rules. Webhook filters enforce shared output and work limits before delivery. diff --git a/release-notes/20261030-persiusng-interface-theme.md b/release-notes/20261030-persiusng-interface-theme.md new file mode 100644 index 0000000000..ff2920ab61 --- /dev/null +++ b/release-notes/20261030-persiusng-interface-theme.md @@ -0,0 +1,9 @@ +--- +category: added +audience: users +area: interface +action: none +breaking: false +--- + +Choose PersiusNG for cinematic discovery, book and narrator shelves, compact requests and a coming-soon calendar. Its account preference sits alongside the existing themes. Native recording requests retain edition identity, and TV requests can opt into future seasons while respecting Episode Queue and watch policies. diff --git a/release-notes/20261030-theme-authoring-workflow.md b/release-notes/20261030-theme-authoring-workflow.md new file mode 100644 index 0000000000..a459ebfc63 --- /dev/null +++ b/release-notes/20261030-theme-authoring-workflow.md @@ -0,0 +1,9 @@ +--- +category: added +audience: users +area: interface +action: none +breaking: false +--- + +Create, validate, inspect and package an independent CSS theme without building the server. Packages include SHA-256 checksums and can select native Persius layouts. The authoring guide and submission workflow cover installation, updates and sharing. diff --git a/release-notes/20261105-discovery-hydration-navigation.md b/release-notes/20261105-discovery-hydration-navigation.md new file mode 100644 index 0000000000..a455c88303 --- /dev/null +++ b/release-notes/20261105-discovery-hydration-navigation.md @@ -0,0 +1,9 @@ +--- +category: fixed +audience: users +area: discovery +action: none +breaking: false +--- + +Discovery mode tabs wait for the current route to be ready before navigating, preserving nested genre pages and filters when opening Swipe immediately after a page loads. diff --git a/release-notes/20261105-theme-package-read-safety.md b/release-notes/20261105-theme-package-read-safety.md new file mode 100644 index 0000000000..b0c351f55f --- /dev/null +++ b/release-notes/20261105-theme-package-read-safety.md @@ -0,0 +1,9 @@ +--- +category: security +audience: operators +area: interface-theme +action: none +breaking: false +--- + +Theme package loading and the authoring CLI now read bounded regular files through validated descriptors, reject multiply linked files, and detect file replacement during loading. diff --git a/release-notes/added-webhook-template-filters.md b/release-notes/added-webhook-template-filters.md new file mode 100644 index 0000000000..92e7503fb0 --- /dev/null +++ b/release-notes/added-webhook-template-filters.md @@ -0,0 +1,9 @@ +--- +category: added +audience: users +area: notifications +action: none +breaking: false +--- + +Webhook JSON payload values can use `lowercase`, `urlencode`, and `slugify` filters to format supported notification variables for receiving APIs. diff --git a/release-notes/individual-episode-availability.md b/release-notes/individual-episode-availability.md new file mode 100644 index 0000000000..25ec1f2393 --- /dev/null +++ b/release-notes/individual-episode-availability.md @@ -0,0 +1,9 @@ +--- +category: added +audience: users, operators +area: availability +action: Enable episode tracking and configure the numbering order for each TV library +breaking: false +--- + +TV season pages show source-specific episode files from Sonarr, Plex, Jellyfin, and Emby, with separate standard and 4K indicators. Complete scans reconcile each source independently; partial scans preserve prior records. Linked viewers see media-server badges only for episodes and qualities their account can access. diff --git a/release-notes/individual-sonarr-episode-availability.md b/release-notes/individual-sonarr-episode-availability.md new file mode 100644 index 0000000000..128bfa862c --- /dev/null +++ b/release-notes/individual-sonarr-episode-availability.md @@ -0,0 +1,9 @@ +--- +category: added +audience: users, operators +area: sonarr +action: none +breaking: false +--- + +Administrators can opt in to Sonarr episode-file tracking, and users can see which TV episodes have files on a season page. Enable the feature under Settings → General and use TheTVDB for the selected TV or anime metadata provider. The indicator describes Sonarr files, not playback access. diff --git a/release-notes/pending-request-edit-notifications.md b/release-notes/pending-request-edit-notifications.md new file mode 100644 index 0000000000..e6687f566c --- /dev/null +++ b/release-notes/pending-request-edit-notifications.md @@ -0,0 +1,13 @@ +--- +category: added +audience: users, operators +area: notifications +action: none +breaking: false +--- + +Administrators can enable a separate **Pending Request Updated** notification. +SeerrNG queues it when an edit changes a pending request's owner, selected +seasons or episodes, or saved acquisition options. Webhook templates expose the +`MEDIA_PENDING_UPDATED` event, and the event is supported by ntfy and the other +configured notification agents. diff --git a/release-notes/production-country-override-rules.md b/release-notes/production-country-override-rules.md new file mode 100644 index 0000000000..bbfca793b4 --- /dev/null +++ b/release-notes/production-country-override-rules.md @@ -0,0 +1,9 @@ +--- +category: added +audience: users, operators +area: requests +action: none +breaking: false +--- + +Radarr and Sonarr rules can match TMDB production countries, with alternatives within the country condition and other conditions still required. Missing country metadata does not match. Sonarr rules can select language profiles when supported, while explicit requester choices remain in effect. diff --git a/release-notes/request-controls-recovery-fixes.md b/release-notes/request-controls-recovery-fixes.md new file mode 100644 index 0000000000..cb032d3f93 --- /dev/null +++ b/release-notes/request-controls-recovery-fixes.md @@ -0,0 +1,9 @@ +--- +category: fixed +audience: users, operators +area: requests +action: none +breaking: false +--- + +Saved movie and series request destinations retain explicitly selected quality profiles and folders, including profile zero. Large queue snapshots remain bounded without rejecting valid provider pages. Excluded library scans preserve pending and blocked seasons, and nested request editors keep their parent dialog open while selecting options. diff --git a/release-notes/request-defaults-and-overrides.md b/release-notes/request-defaults-and-overrides.md new file mode 100644 index 0000000000..732ac59a7f --- /dev/null +++ b/release-notes/request-defaults-and-overrides.md @@ -0,0 +1,9 @@ +--- +category: fixed +audience: users, operators +area: requests +action: none +breaking: false +--- + +Advanced movie and TV requests now keep displayed defaults distinct from deliberate choices, let matching rules fill untouched fields, preserve explicit selections even when they match the displayed default, and clear saved overrides when you return to a service default. diff --git a/release-notes/servarr-queue-snapshots.md b/release-notes/servarr-queue-snapshots.md new file mode 100644 index 0000000000..03e71ef663 --- /dev/null +++ b/release-notes/servarr-queue-snapshots.md @@ -0,0 +1,9 @@ +--- +category: fixed +audience: users, operators +area: downloads +action: none +breaking: false +--- + +SeerrNG now waits for monitored-download refreshes and reads validated, paginated Servarr queue snapshots. Each official Servarr service can set its own Download Queue Size (10–10,000 items; default 1,000) for progress tracking. Queue recovery and intervention continue to require a complete snapshot within their safety bound. diff --git a/scripts/interface-theme.mjs b/scripts/interface-theme.mjs new file mode 100644 index 0000000000..4ab741fa96 --- /dev/null +++ b/scripts/interface-theme.mjs @@ -0,0 +1,41 @@ +import { existsSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { fileURLToPath } from 'node:url'; + +// Author themes from a checkout without compiling the application or starting +// its server. Packaged installations can keep using the compiled Node CLI. +const require = createRequire(import.meta.url); +const source = fileURLToPath( + new URL('../server/commands/interfaceTheme.ts', import.meta.url) +); +const compiled = fileURLToPath( + new URL('../dist/commands/interfaceTheme.js', import.meta.url) +); + +try { + let jitiPath; + try { + jitiPath = require.resolve('jiti'); + } catch { + // Production packages intentionally omit development dependencies. + } + if (existsSync(source) && jitiPath) { + const { createJiti } = require(jitiPath); + await createJiti(import.meta.url, { + alias: { + '@server': fileURLToPath(new URL('../server', import.meta.url)), + }, + }).import(source); + } else if (existsSync(compiled)) { + require(compiled); + } else { + throw new Error( + 'Run pnpm install in the SeerrNG checkout first, or use a packaged release with dist/commands/interfaceTheme.js.' + ); + } +} catch (error) { + console.error( + error instanceof Error ? error.message : 'Theme command failed.' + ); + process.exitCode = 1; +} diff --git a/scripts/interface-theme.test.mjs b/scripts/interface-theme.test.mjs new file mode 100644 index 0000000000..568f7c1802 --- /dev/null +++ b/scripts/interface-theme.test.mjs @@ -0,0 +1,195 @@ +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + existsSync, + linkSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; +import { fileURLToPath } from 'node:url'; + +const command = fileURLToPath( + new URL('./interface-theme.mjs', import.meta.url) +); +const sandbox = (t) => { + const directory = mkdtempSync(path.join(tmpdir(), 'seerr-theme-author-')); + t.after(() => rmSync(directory, { recursive: true, force: true })); + const options = { + cwd: directory, + env: { ...process.env, CONFIG_DIRECTORY: path.join(directory, 'config') }, + encoding: 'utf8', + }; + return { + directory, + run: (...args) => + execFileSync(process.execPath, [command, ...args], options), + reject: (...args) => { + const result = spawnSync(process.execPath, [command, ...args], options); + assert.notEqual(result.status, 0); + return result.stderr; + }, + }; +}; + +test('creates an independent native Persius theme from outside the checkout', (t) => { + const { directory, run } = sandbox(t); + run( + 'create', + 'paper-cinema', + '--name', + 'Paper Cinema', + '--author', + 'Theme Author' + ); + const manifest = JSON.parse( + readFileSync(path.join(directory, 'paper-cinema/manifest.json'), 'utf8') + ); + const css = readFileSync( + path.join(directory, 'paper-cinema/theme.css'), + 'utf8' + ); + assert.equal(manifest.id, 'paper-cinema'); + assert.equal(manifest.layout, 'persius'); + assert.equal(manifest.name, 'Paper Cinema'); + assert.equal(manifest.author, 'Theme Author'); + assert.match(css, /data-interface-theme='paper-cinema'/); + assert.doesNotMatch(css, /data-interface-theme='persiusNG'/); + assert.match(run('validate', 'paper-cinema'), /Valid:/); +}); + +test('classic bases remain supported; creation never overwrites an existing directory', (t) => { + const { directory, run, reject } = sandbox(t); + run('create', 'classic-paper', '--from', 'seerrOrig'); + assert.equal(JSON.parse(run('inspect', 'classic-paper')).layout, 'classic'); + const before = readFileSync( + path.join(directory, 'classic-paper/theme.css'), + 'utf8' + ); + reject('create', 'classic-paper'); + assert.equal( + readFileSync(path.join(directory, 'classic-paper/theme.css'), 'utf8'), + before + ); + reject('create', 'persiusNG'); + reject('create', '../escape'); + reject('create', 'valid-id', '--from', 'not-installed'); + reject('create', 'valid-id', '--unknown'); + assert.equal(existsSync(path.join(directory, 'valid-id')), false); +}); + +test('packs reproducibly with a matching checksum and validates the distributable', (t) => { + const { directory, run, reject } = sandbox(t); + run('create', 'ocean-room'); + run('pack', 'ocean-room'); + const filename = 'ocean-room-0.1.0.seerrtheme'; + const bytes = readFileSync(path.join(directory, filename)); + const hash = createHash('sha256').update(bytes).digest('hex'); + assert.equal( + readFileSync(path.join(directory, filename + '.sha256'), 'utf8'), + `${hash} ${filename}\n` + ); + assert.match(run('validate', filename), /Valid: Ocean Room/); + assert.equal(JSON.parse(run('inspect', filename)).sha256, hash); + run('pack', 'ocean-room', 'second.seerrtheme'); + assert.deepEqual( + readFileSync(path.join(directory, 'second.seerrtheme')), + bytes + ); + reject('pack', 'ocean-room'); + assert.deepEqual(readFileSync(path.join(directory, filename)), bytes); +}); + +test('refuses multiply linked theme bundles before validation or installation', (t) => { + const { directory, run, reject } = sandbox(t); + run('create', 'linked-theme'); + run('pack', 'linked-theme'); + linkSync( + path.join(directory, 'linked-theme-0.1.0.seerrtheme'), + path.join(directory, 'linked.seerrtheme') + ); + assert.match(reject('validate', 'linked.seerrtheme'), /bounded regular file/); + assert.match(reject('install', 'linked.seerrtheme'), /bounded regular file/); + assert.equal( + existsSync(path.join(directory, 'config/interface-themes/linked-theme')), + false + ); +}); + +test('installs, lists, explicitly replaces and removes a custom package', (t) => { + const { directory, run, reject } = sandbox(t); + run('create', 'custom-layout'); + run('pack', 'custom-layout'); + const filename = 'custom-layout-0.1.0.seerrtheme'; + run('install', filename); + assert.equal( + JSON.parse(run('list')).find((theme) => theme.id === 'custom-layout') + ?.layout, + 'persius' + ); + reject('install', filename); + const source = path.join(directory, 'custom-layout/theme.css'); + writeFileSync( + source, + readFileSync(source, 'utf8') + + "\n[data-interface-theme='custom-layout'] body { background: #030712; }\n" + ); + run('pack', 'custom-layout', 'updated.seerrtheme'); + run('install', 'updated.seerrtheme', '--replace'); + assert.match( + readFileSync( + path.join(directory, 'config/interface-themes/custom-layout/theme.css'), + 'utf8' + ), + /#030712/ + ); + reject('uninstall', 'persiusNG'); + run('uninstall', 'custom-layout'); + assert.equal( + JSON.parse(run('list')).some((theme) => theme.id === 'custom-layout'), + false + ); +}); + +test('rejects unsafe CSS and unsupported composition before installing files', (t) => { + const { directory, run, reject } = sandbox(t); + run('create', 'broken-theme'); + run('pack', 'broken-theme'); + const filename = path.join(directory, 'broken-theme-0.1.0.seerrtheme'); + const bundle = JSON.parse(readFileSync(filename, 'utf8')); + for (const update of [ + { css: 'body { display:none }' }, + { manifest: { ...bundle.manifest, layout: 'remote-script' } }, + { + css: "[data-interface-theme='broken-theme'] body { background:url(https://example.invalid/asset); }", + }, + ]) { + writeFileSync(filename, JSON.stringify({ ...bundle, ...update })); + reject('validate', filename); + reject('install', filename); + assert.equal( + existsSync(path.join(directory, 'config/interface-themes/broken-theme')), + false + ); + } +}); + +test('protects an existing checksum when packing and exposes built-in metadata', (t) => { + const { directory, run, reject } = sandbox(t); + run('create', 'custom-pack'); + writeFileSync(path.join(directory, 'custom.seerrtheme.sha256'), 'keep this'); + reject('pack', 'custom-pack', 'custom.seerrtheme'); + assert.equal(existsSync(path.join(directory, 'custom.seerrtheme')), false); + assert.equal( + readFileSync(path.join(directory, 'custom.seerrtheme.sha256'), 'utf8'), + 'keep this' + ); + const info = JSON.parse(run('inspect', 'persiusNG')); + assert.equal(info.layout, 'persius'); + assert.ok(info.cssBytes > 0); +}); diff --git a/scripts/release-notes.test.mjs b/scripts/release-notes.test.mjs index 8322284568..63717783b7 100644 --- a/scripts/release-notes.test.mjs +++ b/scripts/release-notes.test.mjs @@ -17,6 +17,25 @@ import { readReleaseNotes, } from './release-notes.mjs'; +const repositoryRoot = path.dirname( + path.dirname(fileURLToPath(import.meta.url)) +); +const releaseTagList = spawnSync('git', ['tag', '--list', 'v3.*'], { + cwd: repositoryRoot, + encoding: 'utf8', +}).stdout; +const hasFetchedReleaseTags = Boolean(releaseTagList?.trim()); +const releaseTagTest = (name, fn) => + test( + name, + { + skip: hasFetchedReleaseTags + ? false + : 'No SeerrNG release tags are fetched in this checkout', + }, + fn + ); + const validContent = `--- category: fixed audience: users, operators @@ -360,7 +379,7 @@ test('changelog assembly prepends a release without replacing prior history', () } }); -test('checked-in changelog covers every SeerrNG tag', () => { +releaseTagTest('checked-in changelog covers every SeerrNG tag', () => { const scriptPath = path.join( path.dirname(fileURLToPath(import.meta.url)), 'check-changelog-tags.mjs' diff --git a/seerr-api.yml b/seerr-api.yml index 46be4327b8..756d82b9b8 100644 --- a/seerr-api.yml +++ b/seerr-api.yml @@ -91,6 +91,11 @@ components: schema: $ref: '#/components/schemas/ErrorResponse' schemas: + InterfaceThemeId: + type: string + maxLength: 48 + pattern: '^(seerrOrig|seerrNGJ|persiusNG|[a-z0-9]+(?:-[a-z0-9]+)*)$' + description: A built-in or installed custom interface package identifier. ErrorResponse: type: object properties: @@ -222,6 +227,9 @@ components: activeNavigationIcon: type: string enum: [outline, filled] + layout: + type: string + enum: [classic, persius] Follow: type: object properties: @@ -2361,68 +2369,111 @@ components: $ref: '#/components/schemas/WatchlistListItem' User: type: object + description: User response. Provider credentials and password-reset tokens are never serialized. properties: - id: - type: integer - example: 1 - readOnly: true + id: { type: integer, example: 1, readOnly: true } + displayName: { type: string, readOnly: true } email: - type: string - example: 'hey@itsme.com' - readOnly: true - username: - type: string - plexUsername: - type: string - readOnly: true - plexToken: - type: string + { + type: string, + nullable: true, + example: 'hey@itsme.com', + readOnly: true, + } + username: { type: string, nullable: true, readOnly: true } + plexUsername: { type: string, nullable: true, readOnly: true } + jellyfinUsername: { type: string, nullable: true, readOnly: true } + plexId: { type: integer, nullable: true, readOnly: true } + jellyfinUserId: { type: string, nullable: true, readOnly: true } + userType: { type: integer, example: 1, readOnly: true } + permissions: { type: integer, example: 0, readOnly: true } + contentRestricted: { type: boolean, nullable: true, readOnly: true } + requestServices: + type: array + description: Additional Radarr or Sonarr request destinations granted to this user. readOnly: true - jellyfinAuthToken: - type: string + items: { type: string, pattern: '^(radarr|sonarr):[0-9]{1,10}$' } + linkedAccounts: + type: array readOnly: true - userType: - type: integer - example: 1 + items: { $ref: '#/components/schemas/LinkedAccount' } + settings: + allOf: + - { $ref: '#/components/schemas/UserSettings' } + description: Present on manager-authorized user responses; credential fields are omitted. readOnly: true - permissions: - type: number - example: 0 tvSeasonWatchGateStatus: type: string enum: [off, pending, approved, enabled, denied] description: Private to the account owner and callers with `MANAGE_USERS` permission. + readOnly: true tvSeasonWatchGateRequestedAt: type: string format: date-time nullable: true description: Private to the account owner and callers with `MANAGE_USERS` permission. - requestServices: + readOnly: true + episodeQueueAccessStatus: + { type: string, enum: [off, approved], readOnly: true } + episodeQueueAccessRequestedAt: + { type: string, format: date-time, nullable: true, readOnly: true } + avatar: { type: string, readOnly: true } + avatarETag: { type: string, nullable: true, readOnly: true } + avatarVersion: { type: string, nullable: true, readOnly: true } + movieQuotaLimit: { type: number, nullable: true, readOnly: true } + movieQuotaDays: { type: number, nullable: true, readOnly: true } + tvQuotaLimit: { type: number, nullable: true, readOnly: true } + tvQuotaDays: { type: number, nullable: true, readOnly: true } + musicQuotaLimit: { type: number, nullable: true, readOnly: true } + musicQuotaDays: { type: number, nullable: true, readOnly: true } + bookQuotaLimit: { type: number, nullable: true, readOnly: true } + bookQuotaDays: { type: number, nullable: true, readOnly: true } + comicQuotaLimit: { type: number, nullable: true, readOnly: true } + comicQuotaDays: { type: number, nullable: true, readOnly: true } + magazineQuotaLimit: { type: number, nullable: true, readOnly: true } + magazineQuotaDays: { type: number, nullable: true, readOnly: true } + adultQuotaLimit: { type: number, nullable: true, readOnly: true } + adultQuotaDays: { type: number, nullable: true, readOnly: true } + softwareQuotaLimit: { type: number, nullable: true, readOnly: true } + softwareQuotaDays: { type: number, nullable: true, readOnly: true } + requestCount: { type: number, example: 5, readOnly: true } + warnings: type: array - description: Additional Radarr or Sonarr request destinations granted to this user. - items: - type: string - pattern: '^(radarr|sonarr):[0-9]{1,10}$' - avatar: - type: string readOnly: true + items: { type: string } createdAt: - type: string - example: '2020-09-02T05:02:23.000Z' - readOnly: true + { + type: string, + format: date-time, + example: '2020-09-02T05:02:23.000Z', + readOnly: true, + } updatedAt: - type: string - example: '2020-09-02T05:02:23.000Z' - readOnly: true - requestCount: - type: number - example: 5 - readOnly: true - required: - - id - - email - - createdAt - - updatedAt + { + type: string, + format: date-time, + example: '2020-09-02T05:02:23.000Z', + readOnly: true, + } + required: [id, createdAt, updatedAt] + UserUpdatePayload: + type: object + description: Fields accepted by PUT /user/{userId}. + properties: + username: + { + type: string, + minLength: 1, + maxLength: 100, + description: Local username assigned to the user., + } + permissions: + { + type: integer, + minimum: 0, + description: Permission bitmask assigned to the user., + } + required: [username, permissions] PublicUser: type: object required: [id] @@ -2483,6 +2534,8 @@ components: UserSettings: type: object properties: + interfaceTheme: + $ref: '#/components/schemas/InterfaceThemeId' themePalette: type: string description: Account theme preference. SeerrNG is adopted once on installation or upgrade; subsequent user choices survive later upgrades. @@ -2689,41 +2742,33 @@ components: movieMaturityRatingLimit: type: string nullable: true - enum: [G, PG, PG-13, R, NC-17] + enum: ['G', 'PG', 'PG-13', 'R', 'NC-17', null] tvMaturityRatingLimit: type: string nullable: true - enum: [TV-Y, TV-Y7, TV-G, TV-PG, TV-14, TV-MA] + enum: ['TV-Y', 'TV-Y7', 'TV-G', 'TV-PG', 'TV-14', 'TV-MA', null] CardTextVisibilitySettings: type: object properties: movie: type: string nullable: true - enum: - - always - - hover + enum: ['always', 'hover', null] example: hover tv: type: string nullable: true - enum: - - always - - hover + enum: ['always', 'hover', null] example: hover album: type: string nullable: true - enum: - - always - - hover + enum: ['always', 'hover', null] example: always book: type: string nullable: true - enum: - - always - - hover + enum: ['always', 'hover', null] example: always DetailDisclosurePinSettings: type: object @@ -2809,6 +2854,11 @@ components: enableSpecialEpisodes: type: boolean example: false + trackEpisodeAvailability: + type: boolean + default: false + description: Records available TV episodes from synchronized Sonarr services. Tracking requires TheTVDB as the selected metadata provider for the series. + example: false includeAdult: type: boolean example: false @@ -2961,6 +3011,10 @@ components: enabled: type: boolean example: false + episodeOrderProvider: + type: string + enum: [tmdb, tvdb] + description: Episode numbering order configured for this TV library. type: type: string enum: [show, movie, music, book] @@ -3110,9 +3164,6 @@ components: sourceTitle: type: string example: 'xyzabc' - accessToken: - type: string - example: 'supersecretaccesstoken' publicAddress: type: string example: '127.0.0.1' @@ -3164,6 +3215,10 @@ components: enabled: type: boolean example: false + episodeOrderProvider: + type: string + enum: [tmdb, tvdb] + description: Episode numbering order configured for this TV library. type: type: string enum: [show, movie, music, book] @@ -3408,9 +3463,23 @@ components: syncEnabled: type: boolean example: false + syncExcludedTags: + type: array + maxItems: 100 + items: + type: integer + minimum: 0 + maximum: 1000000 + description: Servarr tag IDs excluded from this Radarr library scan. preventSearch: type: boolean example: false + downloadQueueSize: + type: integer + minimum: 10 + maximum: 10000 + default: 1000 + description: Maximum queue records included by Download Sync for this service instance. required: - name - hostname @@ -3479,6 +3548,12 @@ components: type: boolean tagRequests: type: boolean + downloadQueueSize: + type: integer + minimum: 10 + maximum: 10000 + default: 1000 + description: Maximum queue records included by Download Sync for this service instance. overrideRule: type: array items: @@ -3917,9 +3992,23 @@ components: syncEnabled: type: boolean example: false + syncExcludedTags: + type: array + maxItems: 100 + items: + type: integer + minimum: 0 + maximum: 1000000 + description: Servarr tag IDs excluded from this Sonarr library scan. preventSearch: type: boolean example: false + downloadQueueSize: + type: integer + minimum: 10 + maximum: 10000 + default: 1000 + description: Maximum queue records included by Download Sync for this service instance. required: - name - hostname @@ -5438,6 +5527,48 @@ components: type: array items: $ref: '#/components/schemas/BulkMediaRequestResult' + RequestTargetOptions: + type: object + description: >- + Effective profile, root folder, tags, and (for TV) language profile shown in the advanced request form. Accepted only when editing a movie or TV request with advanced request permission. These values keep the saved destination snapshot aligned with the form and are separate from explicit request overrides. + properties: + profileId: + type: integer + minimum: 0 + nullable: true + rootFolder: + type: string + nullable: true + languageProfileId: + type: integer + minimum: 0 + nullable: true + description: Required for TV requests; omit for movie requests. + tags: + type: array + nullable: true + items: + type: integer + minimum: 1 + required: + - profileId + - rootFolder + - tags + RequesterSelectedOptions: + type: object + description: >- + Advanced fields explicitly selected by the requester. A selected field remains explicit even when its value equals the value already shown as the default, so a matching override rule does not replace that choice. Accepted only for new movie or TV requests with advanced request permission. + properties: + profile: + type: boolean + rootFolder: + type: boolean + languageProfile: + type: boolean + description: TV requests only. + tags: + type: boolean + additionalProperties: false PersonMovieBulkRequestResult: type: object properties: @@ -5801,6 +5932,28 @@ components: stillPath: type: string nullable: true + sonarrAvailability: + type: object + description: Sonarr file availability by quality when individual episode tracking is enabled. + properties: + hd: + type: boolean + fourK: + type: boolean + availabilitySources: + type: array + description: File availability by configured Sonarr or media-server source and quality. Media-server file presence does not confirm access for a particular user. + items: + type: object + required: [sourceType, hd, fourK] + properties: + sourceType: + type: string + enum: [sonarr, plex, jellyfin, emby] + hd: + type: boolean + fourK: + type: boolean voteAverage: type: number voteCount: @@ -6186,6 +6339,33 @@ components: - request - current - history + SeasonRequest: + type: object + properties: + id: + type: integer + readOnly: true + seasonNumber: + type: integer + status: + type: integer + enum: [1, 2, 3, 4, 5] + description: Request status for this season. + episodeNumbers: + type: array + nullable: true + description: Omitted or null means the entire season; otherwise contains selected episode numbers. + items: + type: integer + minimum: 1 + createdAt: + type: string + format: date-time + readOnly: true + updatedAt: + type: string + format: date-time + readOnly: true MediaRequest: type: object properties: @@ -6194,10 +6374,24 @@ components: example: 123 readOnly: true status: - type: number - example: 0 - description: Status of the request. 1 = PENDING APPROVAL, 2 = APPROVED, 3 = DECLINED + type: integer + enum: [1, 2, 3, 4, 5] + example: 1 + description: Status of the request. 1 = PENDING, 2 = APPROVED, 3 = DECLINED, 4 = FAILED, 5 = COMPLETED. readOnly: true + type: + type: string + enum: [movie, tv, music, book, comic, magazine, adult, sports] + readOnly: true + seasonCount: + type: integer + minimum: 0 + readOnly: true + seasons: + type: array + readOnly: true + items: + $ref: '#/components/schemas/SeasonRequest' failureReason: type: string enum: @@ -6210,6 +6404,10 @@ components: nullable: true description: Stable, non-sensitive classification for the most recent failed movie or TV dispatch. Cleared when the request is retried or resubmitted. readOnly: true + monitorFutureSeasons: + type: boolean + nullable: true + description: TV-only future-season preference. Null inherits the service default. Episode Queue and season watch gates take priority. overrideTvdbId: type: integer minimum: 1 @@ -6242,6 +6440,7 @@ components: - $ref: '#/components/schemas/PublicUser' - type: string nullable: true + enum: [null] is4k: type: boolean example: false @@ -6260,6 +6459,73 @@ components: serverId: type: number nullable: true + languageProfileId: + type: integer + nullable: true + serviceTargets: + type: array + nullable: true + items: + type: object + required: [serviceType, format, serverId] + properties: + serviceType: + type: string + enum: + [ + radarr, + sonarr, + sportarr, + lidarr, + readarr, + mylar, + kapowarr, + backissue, + lazylibrarian, + whisparr, + ] + format: + type: string + enum: + [ + standard, + 4k, + music, + ebook, + audiobook, + comic, + magazine, + sports, + adult, + ] + serverId: + type: integer + profileId: + type: integer + nullable: true + metadataProfileId: + type: integer + nullable: true + languageProfileId: + type: integer + nullable: true + rootFolder: + type: string + nullable: true + tags: + type: array + nullable: true + items: + type: integer + externalServiceId: + type: integer + nullable: true + externalServiceSlug: + type: string + nullable: true + status: + type: integer + nullable: true profileId: type: number nullable: true @@ -6276,8 +6542,24 @@ components: type: number bookFormat: type: string - enum: [ebook, audiobook, both] + enum: ['ebook', 'audiobook', 'both', null] + nullable: true + preferredEditionId: + type: string nullable: true + preferredIsbn13: + type: string + nullable: true + editionPolicy: + type: string + enum: ['only', 'either', 'alongside', null] + nullable: true + variantKey: + type: string + nullable: true + isAutoRequest: + type: boolean + readOnly: true ignoreQuota: type: boolean example: false @@ -6290,6 +6572,53 @@ components: required: - id - status + DownloadProgressItem: + type: object + description: Live or tracked download state. Non-admin responses replace release titles and queue identifiers with empty or opaque values. + properties: + mediaType: + type: string + enum: [movie, tv, music, book, comic, magazine, adult, sports] + externalId: + type: integer + size: + type: number + sizeLeft: + type: number + status: + type: string + timeLeft: + type: string + estimatedCompletionTime: + type: string + format: date-time + title: + type: string + downloadId: + type: string + description: Opaque value for non-admin users; the raw downloader identifier is not exposed to them. + liveDownloadToken: + type: string + description: Short-lived user-scoped token for live progress. + percent: + type: number + trackedDownloadStatus: + type: string + trackedDownloadState: + type: string + protocol: + type: string + description: Available only to administrators. + downloadClient: + type: string + description: Available only to administrators. + episode: + type: object + properties: + seasonNumber: + type: integer + episodeNumber: + type: integer MediaInfo: type: object properties: @@ -6304,26 +6633,44 @@ components: type: number readOnly: true nullable: true + imdbId: + type: string + readOnly: true + nullable: true mbId: type: string readOnly: true nullable: true mediaType: type: string - enum: [movie, tv, music, book, comic, magazine, sports] + enum: [movie, tv, music, book, comic, magazine, adult, sports] serviceId: type: number nullable: true + serviceId4k: + type: number + nullable: true + availableMusicServiceIds: + type: array + nullable: true + items: + type: integer externalServiceId: type: number nullable: true externalServiceSlug: type: string nullable: true + externalServiceId4k: + type: number + nullable: true + externalServiceSlug4k: + type: string + nullable: true serviceStatuses: type: array readOnly: true - description: Availability tracked independently for each Radarr or Sonarr instance and quality. For linked media-server users, a destination that cannot be matched to verified primary media-server access may be returned as Unknown. + description: Availability tracked independently for each Radarr, Sonarr, or Whisparr instance and format. For linked media-server users, a destination without verified primary media-server access may be returned as Unknown. items: type: object properties: @@ -6333,14 +6680,15 @@ components: type: integer serviceType: type: string - enum: [radarr, sonarr] + enum: [radarr, sonarr, whisparr] serverId: type: integer format: type: string - enum: [standard, 4k] + enum: [standard, 4k, adult] status: type: integer + enum: [1, 2, 3, 4, 5, 6, 7] description: Instance availability status using the MediaStatus values. externalServiceId: type: integer @@ -6364,6 +6712,55 @@ components: audiobookExternalServiceSlug: type: string nullable: true + audiobookLibraryServiceId: + type: integer + nullable: true + audiobookLibraryItemId: + type: string + nullable: true + comicServiceType: + type: string + enum: ['mylar', 'kapowarr', 'backissue', null] + nullable: true + ratingKey: + type: string + nullable: true + description: Omitted from responses when the caller cannot manage requests. + ratingKey4k: + type: string + nullable: true + description: Omitted from responses when the caller cannot manage requests. + jellyfinMediaId: + type: string + nullable: true + description: Omitted from responses when the caller cannot manage requests. + jellyfinMediaId4k: + type: string + nullable: true + description: Omitted from responses when the caller cannot manage requests. + downloadStatus: + type: array + readOnly: true + items: + $ref: '#/components/schemas/DownloadProgressItem' + downloadStatus4k: + type: array + readOnly: true + items: + $ref: '#/components/schemas/DownloadProgressItem' + audiobookDownloadStatus: + type: array + readOnly: true + items: + $ref: '#/components/schemas/DownloadProgressItem' + mediaUrl: + type: string + nullable: true + readOnly: true + mediaUrl4k: + type: string + nullable: true + readOnly: true status: type: number example: 0 @@ -6521,7 +6918,7 @@ components: properties: musicQuality: type: string - enum: [mp3, flac] + enum: ['mp3', 'flac', null] nullable: true activeMetadataProfileId: type: number @@ -7178,30 +7575,39 @@ components: example: 1 name: type: string + birthday: + type: string + nullable: true deathday: type: string + nullable: true knownForDepartment: type: string alsoKnownAs: type: array + nullable: true items: type: string gender: - type: string + type: number biography: type: string popularity: - type: string + type: number placeOfBirth: type: string + nullable: true profilePath: type: string + nullable: true adult: type: boolean imdbId: type: string + nullable: true homepage: type: string + nullable: true CreditCast: type: object properties: @@ -7639,23 +8045,24 @@ components: webpush: type: number WatchProviders: - type: array - items: - type: object - properties: - iso_3166_1: - type: string - link: - type: string - buy: - type: array - items: - $ref: '#/components/schemas/WatchProviderDetails' - flatrate: - items: - $ref: '#/components/schemas/WatchProviderDetails' + type: object + required: [iso_3166_1] + properties: + iso_3166_1: + type: string + link: + type: string + buy: + type: array + items: + $ref: '#/components/schemas/WatchProviderDetails' + flatrate: + type: array + items: + $ref: '#/components/schemas/WatchProviderDetails' WatchProviderDetails: type: object + required: [id, name] properties: displayPriority: type: number @@ -7678,6 +8085,10 @@ components: type: string nullable: true example: missing_issue + status: + type: integer + enum: [1, 2] + description: 1 = open; 2 = resolved. problemSeason: type: number example: 2 @@ -7701,13 +8112,25 @@ components: media: $ref: '#/components/schemas/MediaInfo' createdBy: - $ref: '#/components/schemas/User' + $ref: '#/components/schemas/PublicUser' modifiedBy: - $ref: '#/components/schemas/User' + anyOf: + - $ref: '#/components/schemas/PublicUser' + - type: string + nullable: true + enum: [null] comments: type: array items: $ref: '#/components/schemas/IssueComment' + createdAt: + type: string + format: date-time + readOnly: true + updatedAt: + type: string + format: date-time + readOnly: true IssueComment: type: object properties: @@ -7715,7 +8138,7 @@ components: type: number example: 1 user: - $ref: '#/components/schemas/User' + $ref: '#/components/schemas/PublicUser' message: type: string example: A comment @@ -7883,6 +8306,11 @@ components: minimum: 0 maximum: 1000000000 nullable: true + readarrServiceId: + type: integer + minimum: 0 + maximum: 1000000000 + nullable: true users: type: string maxLength: 500 @@ -7903,6 +8331,18 @@ components: maxLength: 500 pattern: '^\d+(,\d+)*$' nullable: true + productionCountries: + type: string + nullable: true + maxLength: 500 + pattern: '^\s*[A-Za-z]{2}\s*(\|\s*[A-Za-z]{2}\s*)*$' + description: Up to 100 pipe-separated ISO alpha-2 production countries; normalized to uppercase. Only Radarr and Sonarr rules support this condition. + languageProfileId: + type: integer + nullable: true + minimum: 0 + maximum: 1000000000 + description: Legacy Sonarr language profile, on service versions that expose it. profileId: type: integer minimum: 0 @@ -7926,7 +8366,7 @@ components: OverrideRuleWrite: type: object additionalProperties: false - description: Exactly one service, at least one condition, and at least one setting must be configured. Lidarr rules support only the users condition. + description: Exactly one Radarr, Sonarr, Lidarr, or Readarr service, at least one condition, and at least one setting must be configured. Lidarr rules support only the users condition. properties: radarrServiceId: type: integer @@ -7943,6 +8383,11 @@ components: minimum: 0 maximum: 1000000000 nullable: true + readarrServiceId: + type: integer + minimum: 0 + maximum: 1000000000 + nullable: true users: type: string maxLength: 500 @@ -7963,6 +8408,18 @@ components: maxLength: 500 pattern: '^\d+(,\d+)*$' nullable: true + productionCountries: + type: string + nullable: true + maxLength: 500 + pattern: '^\s*[A-Za-z]{2}\s*(\|\s*[A-Za-z]{2}\s*)*$' + description: Up to 100 pipe-separated ISO alpha-2 production countries; normalized to uppercase. Only Radarr and Sonarr rules support this condition. + languageProfileId: + type: integer + nullable: true + minimum: 0 + maximum: 1000000000 + description: Legacy Sonarr language profile, on service versions that expose it. profileId: type: integer minimum: 0 @@ -8954,7 +9411,7 @@ paths: $ref: '#/components/schemas/JellyfinLibrary' post: summary: Update Jellyfin libraries - description: Optionally synchronizes libraries and updates which libraries are enabled. + description: Synchronizes libraries or updates enabled libraries and the episode numbering order for a TV library. Omitted enable preserves current enabled state; an empty enable string disables all libraries. Episode order updates must be sent separately from library synchronization. tags: - settings requestBody: @@ -8968,7 +9425,15 @@ paths: type: boolean enable: type: string - description: Comma-separated library IDs. Omitted or empty disables all libraries. + description: Comma-separated library IDs. Omit to preserve enabled state; an empty string disables all libraries. + episodeOrderLibraryId: + type: string + maxLength: 128 + description: ID of the TV library whose episode numbering order is being updated. + episodeOrderProvider: + type: string + enum: [none, tmdb, tvdb] + description: Set the library's episode numbering provider, or none to clear it. Send with episodeOrderLibraryId. responses: '200': description: 'Jellyfin libraries updated' @@ -8978,6 +9443,8 @@ paths: type: array items: $ref: '#/components/schemas/JellyfinLibrary' + '400': + description: Invalid library update or episode-order selection. /settings/jellyfin/users: get: summary: Get Jellyfin Users @@ -9123,7 +9590,7 @@ paths: $ref: '#/components/schemas/PlexLibrary' post: summary: Update Plex libraries - description: Optionally synchronizes libraries and updates which libraries are enabled. + description: Synchronizes libraries or updates enabled libraries and the episode numbering order for a TV library. Omitted enable preserves current enabled state; an empty enable string disables all libraries. Episode order updates must be sent separately from library synchronization. tags: - settings requestBody: @@ -9137,7 +9604,15 @@ paths: type: boolean enable: type: string - description: Comma-separated library IDs. Omitted or empty disables all libraries. + description: Comma-separated library IDs. Omit to preserve enabled state; an empty string disables all libraries. + episodeOrderLibraryId: + type: string + maxLength: 128 + description: ID of the TV library whose episode numbering order is being updated. + episodeOrderProvider: + type: string + enum: [none, tmdb, tvdb] + description: Set the library's episode numbering provider, or none to clear it. Send with episodeOrderLibraryId. responses: '200': description: 'Plex libraries updated' @@ -9153,6 +9628,8 @@ paths: application/json: schema: $ref: '#/components/schemas/ErrorResponse' + '400': + description: Invalid library update or episode-order selection. /settings/plex/library/{libraryId}/type: put: summary: Reclassify a Plex artist library @@ -12153,7 +12630,7 @@ paths: /editions/book: get: summary: Compare editions and narrations of a book - description: Returns comparable edition cards. Details the catalog does not provide are listed as unknown. + description: Returns comparable edition cards with exact edition ownership. Optional sampleUrl (HTTPS only) and editionLabel are present only when supplied by the provider. Details the catalog does not provide are listed as unknown. tags: - editions parameters: @@ -12167,6 +12644,12 @@ paths: name: mediaId schema: type: integer + - in: query + name: serverId + description: Configured destination for this format. Edition ownership is evaluated on this destination. + schema: + type: integer + minimum: 0 - in: query name: term allowReserved: true @@ -12182,6 +12665,18 @@ paths: allowReserved: true schema: type: string + - in: query + name: bookId + description: Canonical catalog book identity. Selects its configured provider and exact work. + schema: + type: string + maxLength: 2048 + - in: query + name: author + description: Expected author for a title lookup. + schema: + type: string + maxLength: 256 responses: '200': description: Edition comparison @@ -13596,7 +14091,7 @@ paths: schema: type: string nullable: true - enum: [debug, info, warn, error] + enum: ['debug', 'info', 'warn', 'error', null] default: debug - in: query name: search @@ -15261,7 +15756,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/User' + $ref: '#/components/schemas/UserUpdatePayload' responses: '200': description: Successfully updated user details @@ -16080,11 +16575,12 @@ paths: movieMaturityRatingLimit: type: string nullable: true - enum: [G, PG, PG-13, R, NC-17] + enum: ['G', 'PG', 'PG-13', 'R', 'NC-17', null] tvMaturityRatingLimit: type: string nullable: true - enum: [TV-Y, TV-Y7, TV-G, TV-PG, TV-14, TV-MA] + enum: + ['TV-Y', 'TV-Y7', 'TV-G', 'TV-PG', 'TV-14', 'TV-MA', null] responses: '200': description: Updated user maturity limits returned @@ -21184,16 +21680,18 @@ paths: nullable: true enum: [ - all, - recent, - approved, - available, - pending, - processing, - unavailable, - failed, - deleted, - completed, + 'all', + 'active', + 'recent', + 'approved', + 'available', + 'pending', + 'processing', + 'unavailable', + 'failed', + 'deleted', + 'completed', + null, ] - in: query name: sort @@ -21205,7 +21703,7 @@ paths: name: sortDirection schema: type: string - enum: [asc, desc] + enum: ['asc', 'desc', null] nullable: true default: desc - in: query @@ -21218,7 +21716,18 @@ paths: name: mediaType schema: type: string - enum: [movie, tv, music, book, comic, magazine, sports, all] + enum: + [ + 'movie', + 'tv', + 'music', + 'book', + 'comic', + 'magazine', + 'sports', + 'all', + null, + ] nullable: true default: all - in: query @@ -21311,6 +21820,9 @@ paths: minimum: 0 nullable: true description: Sonarr v5 metadata language ID. Requires advanced request permission. + monitorFutureSeasons: + type: boolean + description: Monitor future TV seasons in Sonarr. False preserves existing Sonarr monitoring; true is unavailable under Episode Queue or a season watch gate. sonarrSeasonType: type: string maxLength: 100 @@ -21323,6 +21835,8 @@ paths: type: array items: type: number + requesterSelectedOptions: + $ref: '#/components/schemas/RequesterSelectedOptions' format: type: string enum: [ebook, audiobook, both] @@ -22925,15 +23439,21 @@ paths: type: number profileId: type: number + nullable: true rootFolder: type: string + nullable: true languageProfileId: type: number + nullable: true metadataLanguageId: type: integer minimum: 0 nullable: true description: Sonarr v5 metadata language ID. Requires advanced request permission. + monitorFutureSeasons: + type: boolean + description: Monitor future TV seasons in Sonarr. False preserves existing Sonarr monitoring; true is unavailable under Episode Queue or a season watch gate. sonarrSeasonType: type: string maxLength: 100 @@ -22944,8 +23464,11 @@ paths: type: number tags: type: array + nullable: true items: type: number + requestTargetOptions: + $ref: '#/components/schemas/RequestTargetOptions' format: type: string enum: [ebook, audiobook, both] @@ -24122,13 +24645,14 @@ paths: nullable: true enum: [ - all, - available, - partial, - allavailable, - processing, - pending, - deleted, + 'all', + 'available', + 'partial', + 'allavailable', + 'processing', + 'pending', + 'deleted', + null, ] - in: query name: sort diff --git a/server/api/jellyfin.test.ts b/server/api/jellyfin.test.ts index c9713ccf5c..896b2a288c 100644 --- a/server/api/jellyfin.test.ts +++ b/server/api/jellyfin.test.ts @@ -516,3 +516,26 @@ describe('Jellyfin and Emby current-selection playlist replacement', () => { }); }); }); + +describe('complete Jellyfin episode reads', () => { + for (const [name, data, valid] of [ + ['missing items', { TotalRecordCount: 0 }, false], + ['confirmed empty', { TotalRecordCount: 0, Items: [] }, true], + ['partial page', { TotalRecordCount: 1, Items: [] }, false], + ['malformed entry', { TotalRecordCount: 1, Items: [null] }, false], + ] as const) { + it(name, async () => { + const api = new TestJellyfinAPI('http://localhost:8096', 'fixture-only'); + mock.method(api.getTransport(), 'get', async () => ({ data })); + if (valid) + assert.deepEqual( + await api.getEpisodes('series', 'season', { requireComplete: true }), + [] + ); + else + await assert.rejects( + api.getEpisodes('series', 'season', { requireComplete: true }) + ); + }); + } +}); diff --git a/server/api/jellyfin.ts b/server/api/jellyfin.ts index 27627dfa99..8722ec1051 100644 --- a/server/api/jellyfin.ts +++ b/server/api/jellyfin.ts @@ -187,6 +187,7 @@ export interface JellyfinPlaylist { export const MAX_JELLYFIN_USERS = 1_000; export const MAX_JELLYFIN_LIBRARIES = 10_000; export const MAX_JELLYFIN_LIBRARY_ITEMS = 100_000; +const JELLYFIN_LIBRARY_PAGE_SIZE = 1_000; export const MAX_JELLYFIN_EPISODES = 10_000; export const MAX_JELLYFIN_SEASONS = 1_000; export const MAX_JELLYFIN_MEDIA_SOURCES = 100; @@ -766,6 +767,28 @@ class JellyfinAPI extends ExternalAPI { }); } + public async getUserEpisodesForAvailability( + seriesId: string + ): Promise { + if (!this.userId) return []; + const response = await this.get('/Items', { + params: { + userId: this.userId, + parentId: boundedJellyfinText(seriesId, 128), + recursive: true, + includeItemTypes: 'Episode', + fields: 'MediaSources', + enableImages: false, + limit: MAX_JELLYFIN_EPISODES, + }, + }); + return sanitizeJellyfinLibraryItems( + isRecord(response) ? response.Items : undefined, + MAX_JELLYFIN_EPISODES, + { includeExtended: true, excludeVirtual: true } + ) as JellyfinLibraryItemExtended[]; + } + public async getSystemInfo(): Promise<{ Id: string; ServerName: string }> { try { const systemInfoResponse = sanitizeJellyfinSystemInfo( @@ -1104,25 +1127,113 @@ class JellyfinAPI extends ExternalAPI { id: string, libraryType?: JellyfinLibrary['type'] ): Promise { + const inventory = await this.getLibraryContentsWithInventory( + id, + libraryType + ); + return inventory.items; + } + + public async getLibraryContentsWithInventory( + id: string, + libraryType?: JellyfinLibrary['type'] + ): Promise<{ items: JellyfinLibraryItem[]; complete: boolean }> { try { - const libraryItemsResponse = await this.get('/Items', { - params: { - SortBy: 'SortName', - SortOrder: 'Ascending', - IncludeItemTypes: - libraryType === 'music' ? 'MusicAlbum' : 'Series,Movie,Others', - Recursive: true, - StartIndex: 0, - ParentId: boundedJellyfinText(id, 128), - collapseBoxSetItems: false, - }, - }); + const itemsById = new Map(); + let complete = true; + let expectedTotal: number | undefined; + let offset = 0; + let observedCount = 0; + + while (offset < MAX_JELLYFIN_LIBRARY_ITEMS) { + const response = await this.get('/Items', { + params: { + SortBy: 'SortName', + SortOrder: 'Ascending', + IncludeItemTypes: + libraryType === 'music' ? 'MusicAlbum' : 'Series,Movie,Others', + Recursive: true, + StartIndex: offset, + Limit: JELLYFIN_LIBRARY_PAGE_SIZE, + EnableTotalRecordCount: true, + EnableImages: false, + ParentId: boundedJellyfinText(id, 128), + collapseBoxSetItems: false, + }, + }); - return sanitizeJellyfinLibraryItems( - libraryItemsResponse?.Items, - MAX_JELLYFIN_LIBRARY_ITEMS, - { excludeVirtual: true } - ) as JellyfinLibraryItem[]; + if (!isRecord(response) || !Array.isArray(response.Items)) { + throw new Error('Jellyfin returned an invalid library inventory.'); + } + + const reportedTotal = response.TotalRecordCount; + if (Number.isSafeInteger(reportedTotal) && Number(reportedTotal) >= 0) { + const total = Number(reportedTotal); + if (expectedTotal === undefined) { + expectedTotal = total; + } else if (expectedTotal !== total) { + expectedTotal = Math.max(expectedTotal, total); + complete = false; + } + if (total >= MAX_JELLYFIN_LIBRARY_ITEMS) complete = false; + } else { + complete = false; + } + + const rawItems = response.Items.slice(0, JELLYFIN_LIBRARY_PAGE_SIZE); + if (response.Items.length > JELLYFIN_LIBRARY_PAGE_SIZE) { + complete = false; + } + const pageItems = sanitizeJellyfinLibraryItems( + rawItems, + JELLYFIN_LIBRARY_PAGE_SIZE, + { excludeVirtual: true } + ) as JellyfinLibraryItem[]; + const sanitizedSeriesIds = new Set( + pageItems.filter(({ Type }) => Type === 'Series').map(({ Id }) => Id) + ); + if ( + rawItems.some( + (item) => + !isRecord(item) || + (item.Type === 'Series' && + !sanitizedSeriesIds.has(boundedJellyfinText(item.Id, 128))) + ) + ) { + complete = false; + } + + for (const item of pageItems) { + if (itemsById.has(item.Id)) { + complete = false; + continue; + } + itemsById.set(item.Id, item); + } + + observedCount += rawItems.length; + if (rawItems.length === 0) break; + if ( + expectedTotal === undefined && + rawItems.length < JELLYFIN_LIBRARY_PAGE_SIZE + ) { + break; + } + offset += rawItems.length; + if (expectedTotal !== undefined && observedCount >= expectedTotal) { + break; + } + } + + if ( + expectedTotal === undefined || + observedCount !== expectedTotal || + offset >= MAX_JELLYFIN_LIBRARY_ITEMS + ) { + complete = false; + } + + return { items: [...itemsById.values()], complete }; } catch (e) { logger.error( `Something went wrong while getting library content from the Jellyfin server: ${e.message}`, @@ -1433,16 +1544,38 @@ class JellyfinAPI extends ExternalAPI { return { Id: playlistId, Name: safeName, MediaType: mediaType }; } - public async getSeasons(seriesID: string): Promise { + public async getSeasons( + seriesID: string, + options?: { requireComplete?: boolean } + ): Promise { try { const seasonResponse = await this.get( `/Shows/${encodeURIComponent(boundedJellyfinText(seriesID, 128))}/Seasons` ); - return sanitizeJellyfinLibraryItems( + const rawItems = seasonResponse?.Items; + const items = sanitizeJellyfinLibraryItems( seasonResponse?.Items, MAX_JELLYFIN_SEASONS ) as JellyfinLibraryItem[]; + if ( + options?.requireComplete && + (!Array.isArray(rawItems) || + rawItems.length >= MAX_JELLYFIN_SEASONS || + seasonResponse.TotalRecordCount !== rawItems.length || + items.length !== rawItems.length || + new Set(items.map((item) => item.Id)).size !== items.length || + new Set(items.map((item) => item.IndexNumber)).size !== + items.length || + items.some( + (item) => + item.Type !== 'Season' || + !Number.isSafeInteger(item.IndexNumber) || + item.IndexNumber! < 0 + )) + ) + throw new Error('Jellyfin season inventory is incomplete'); + return items; } catch (e) { logger.error( `Something went wrong while getting the list of seasons from the Jellyfin server: ${e.message}`, @@ -1458,7 +1591,9 @@ class JellyfinAPI extends ExternalAPI { } public async getEpisodes< - T extends { includeMediaInfo?: boolean } | undefined = undefined, + T extends + { includeMediaInfo?: boolean; requireComplete?: boolean } | undefined = + undefined, >( seriesID: string, seasonID: string, @@ -1475,7 +1610,8 @@ class JellyfinAPI extends ExternalAPI { } ); - return sanitizeJellyfinLibraryItems( + const rawItems = episodeResponse?.Items; + const items = sanitizeJellyfinLibraryItems( episodeResponse?.Items, MAX_JELLYFIN_EPISODES, { @@ -1483,6 +1619,20 @@ class JellyfinAPI extends ExternalAPI { excludeVirtual: true, } ) as EpisodeReturn; + if ( + options?.requireComplete && + (!Array.isArray(rawItems) || + rawItems.length >= MAX_JELLYFIN_EPISODES || + episodeResponse.TotalRecordCount !== rawItems.length || + items.length !== + rawItems.filter( + (item: unknown) => + !(isRecord(item) && item.LocationType === 'Virtual') + ).length || + new Set(items.map((item) => item.Id)).size !== items.length) + ) + throw new Error('Jellyfin episode inventory is incomplete'); + return items; } catch (e) { logger.error( `Something went wrong while getting the list of episodes from the Jellyfin server: ${e.message}`, diff --git a/server/api/plexapi.test.ts b/server/api/plexapi.test.ts index f9c0998fcb..724ff9abf5 100644 --- a/server/api/plexapi.test.ts +++ b/server/api/plexapi.test.ts @@ -634,3 +634,48 @@ describe('Plex library response integrity', () => { assert.deepEqual(await plex.getLibraries(), []); }); }); + +describe('complete Plex episode reads', () => { + for (const [name, data, valid] of [ + ['missing items', { MediaContainer: { size: 0 } }, false], + ['confirmed empty', { MediaContainer: { size: 0, Metadata: [] } }, true], + [ + 'partial page', + { MediaContainer: { size: 0, totalSize: 1, Metadata: [] } }, + false, + ], + [ + 'malformed entry', + { MediaContainer: { size: 1, Metadata: [null] } }, + false, + ], + ] as const) { + it(name, async () => { + const plex = new PlexAPI({ + plexToken: 'fixture-only', + plexSettings: { + ...getSettings().plex, + ip: '127.0.0.1', + port: 32400, + useSsl: false, + }, + }); + const client = ( + plex as unknown as { + axios: { get: (...args: unknown[]) => Promise }; + } + ).axios; + mock.method(client, 'get', async () => ({ data })); + if (valid) + assert.deepEqual( + await plex.getChildrenMetadata('42', { requireComplete: true }), + [] + ); + else + await assert.rejects( + plex.getChildrenMetadata('42', { requireComplete: true }), + /incomplete/ + ); + }); + } +}); diff --git a/server/api/plexapi.ts b/server/api/plexapi.ts index 0d8178210a..80f4aa921b 100644 --- a/server/api/plexapi.ts +++ b/server/api/plexapi.ts @@ -910,6 +910,7 @@ class PlexAPI extends ExternalAPI { existing?.enabled ?? false, type, + episodeOrderProvider: existing?.episodeOrderProvider, lastScan: existing?.lastScan, }; }), @@ -1031,7 +1032,10 @@ class PlexAPI extends ExternalAPI { return metadata; } - public async getChildrenMetadata(key: string): Promise { + public async getChildrenMetadata( + key: string, + options?: { requireComplete?: boolean } + ): Promise { const response = await this.get( `/library/metadata/${encodeURIComponent( boundedPlexText(key, 128) @@ -1042,14 +1046,25 @@ class PlexAPI extends ExternalAPI { ? response.MediaContainer : {}; - return ( - Array.isArray(mediaContainer.Metadata) ? mediaContainer.Metadata : [] - ) + const rawItems = mediaContainer.Metadata; + const items = (Array.isArray(rawItems) ? rawItems : []) .slice(0, MAX_PLEX_METADATA_ITEMS) .flatMap((item) => { const normalized = sanitizePlexMetadata(item); return normalized ? [normalized] : []; }); + if ( + options?.requireComplete && + (!Array.isArray(rawItems) || + rawItems.length >= MAX_PLEX_METADATA_ITEMS || + mediaContainer.size !== rawItems.length || + (mediaContainer.totalSize !== undefined && + mediaContainer.totalSize !== rawItems.length) || + items.length !== rawItems.length || + new Set(items.map((item) => item.ratingKey)).size !== items.length) + ) + throw new Error('Plex episode inventory is incomplete'); + return items; } public async getAllLeavesMetadata(key: string): Promise { diff --git a/server/api/servarr/base.ts b/server/api/servarr/base.ts index 001a3fff8e..cf42514e9d 100644 --- a/server/api/servarr/base.ts +++ b/server/api/servarr/base.ts @@ -4,6 +4,10 @@ import cacheManager from '@server/lib/cache'; import { getExternalRuntimeConfig } from '@server/lib/externalRuntimeConfig'; import type { DVRSettings } from '@server/lib/settings'; import logger from '@server/logger'; +import { + MAX_SERVARR_DOWNLOAD_QUEUE_SIZE, + validateServarrDownloadQueueSize, +} from '@server/utils/servarrSettings'; import { buildServiceUrl, trimTrailingSlashes } from '@server/utils/serviceUrl'; import type { AxiosRequestConfig } from 'axios'; @@ -107,18 +111,13 @@ export interface Tag { label: string; } -interface QueueResponse { - page: number; - pageSize: number; - sortKey: string; - sortDirection: string; - totalRecords: number; - records: (QueueItem & QueueItemAppendT)[]; -} - export const MAX_SERVARR_CONFIGURATION_RESULTS = 1_000; -export const MAX_SERVARR_QUEUE_RESULTS = 10_000; +export const MAX_SERVARR_QUEUE_RESULTS = MAX_SERVARR_DOWNLOAD_QUEUE_SIZE; export const MAX_SERVARR_QUEUE_PAGE_SIZE = 1_000; +const MAX_SERVARR_INTERVENTION_QUEUE_RESULTS = 5_000; +const SERVARR_INTERVENTION_QUEUE_PAGE_SIZE = 250; +const SERVARR_COMMAND_POLL_INTERVAL_MS = 1_000; +const SERVARR_COMMAND_TIMEOUT_MS = 60_000; export const MAX_SERVARR_LIBRARY_RESULTS = 100_000; /** Finite cap for provider endpoints that return a complete library in one response. */ export const MAX_SERVARR_LIBRARY_RESPONSE_BYTES = 64 * 1024 * 1024; @@ -126,6 +125,13 @@ export const MAX_SERVARR_LOOKUP_RESULTS = 1_000; export const MAX_SERVARR_COVER_IMAGES = 20; const MAX_SERVARR_TEXT_LENGTH = 10_000; const MAX_SERVARR_IMAGE_URL_LENGTH = 2_048; +const SERVARR_TERMINAL_COMMAND_STATES = new Set([ + 'completed', + 'failed', + 'aborted', + 'cancelled', + 'orphaned', +]); const isRecord = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); @@ -552,21 +558,19 @@ class ServarrBase extends ExternalAPI { } } - public async getQueue(): Promise<(QueueItem & QueueItemAppendT)[]> { + public async getQueue( + maxRecords?: number + ): Promise<(QueueItem & QueueItemAppendT)[]> { try { - const response = await this.request>( - 'GET', - `/queue`, - undefined, - this.getRequestConfig({ - includeEpisode: true, - page: 1, - pageSize: MAX_SERVARR_QUEUE_PAGE_SIZE, - }) - ); - - return sanitizeServarrQueue( - response.data?.records + const maximum = + maxRecords === undefined + ? MAX_SERVARR_QUEUE_RESULTS + : validateServarrDownloadQueueSize(maxRecords); + return await this.getQueueSnapshot( + Math.min(MAX_SERVARR_QUEUE_PAGE_SIZE, maximum), + maximum, + true, + maxRecords !== undefined ); } catch (e) { throw new Error( @@ -700,59 +704,120 @@ class ServarrBase extends ExternalAPI { return; } - await this.runCommand('RefreshMonitoredDownloads', {}); + let command = await this.runCommand('RefreshMonitoredDownloads', {}); + const deadline = Date.now() + SERVARR_COMMAND_TIMEOUT_MS; + + while (!SERVARR_TERMINAL_COMMAND_STATES.has(command.status)) { + const remaining = deadline - Date.now(); + if (remaining <= 0) { + throw new Error( + `[${this.apiName}] Monitored download refresh did not finish within ${SERVARR_COMMAND_TIMEOUT_MS} ms.` + ); + } + + await new Promise((resolve) => + setTimeout( + resolve, + Math.min(SERVARR_COMMAND_POLL_INTERVAL_MS, remaining) + ) + ); + command = await this.getCommand(command.id); + } + + if (command.status !== 'completed' || command.result === 'unsuccessful') { + const detail = command.exception || command.message; + throw new Error( + `[${this.apiName}] Monitored download refresh failed (${command.status})${detail ? `: ${detail}` : '.'}` + ); + } } - /** Complete bounded queue snapshot. Never infer disappearance from a partial page. */ + /** Read an uncapped, complete queue snapshot within the safety bound. */ public async getInterventionQueue(): Promise< (QueueItem & QueueItemAppendT)[] > { + return this.getQueueSnapshot( + SERVARR_INTERVENTION_QUEUE_PAGE_SIZE, + MAX_SERVARR_INTERVENTION_QUEUE_RESULTS, + true + ); + } + + private async getQueueSnapshot( + pageSize: number, + maximum: number, + includeEpisode: boolean, + allowCappedSnapshot = false + ): Promise<(QueueItem & QueueItemAppendT)[]> { const records: (QueueItem & QueueItemAppendT)[] = []; - const pageSize = 250; const seen = new Set(); - for (let page = 1; page <= 20; page++) { - const response = await this.request>( + let expectedTotal: number | undefined; + const maximumPages = Math.ceil(maximum / pageSize); + + for (let page = 1; page <= maximumPages; page++) { + const response = await this.request( 'GET', '/queue', undefined, - this.getRequestConfig({ includeEpisode: true, page, pageSize }) + this.getRequestConfig({ includeEpisode, page, pageSize }) ); - const total = response.data?.totalRecords; + + const data = response.data; + const total = isRecord(data) ? data.totalRecords : undefined; if ( + typeof total !== 'number' || !Number.isSafeInteger(total) || total < 0 || - total > 5000 || - !Array.isArray(response.data?.records) + (total > maximum && !allowCappedSnapshot) || + !isRecord(data) || + !Array.isArray(data.records) ) { throw new Error( 'Queue snapshot exceeds supported limits or is invalid.' ); } + + if (expectedTotal !== undefined && total !== expectedTotal) { + throw new Error('Queue changed while reading its pages.'); + } + expectedTotal = total; + + const targetRecords = Math.min(total, maximum); + const remaining = targetRecords - records.length; + // Keep the provider's page size fixed: reducing it on the last request + // would change its offset. Validate the full page, then apply our cap. + const expectedPageRecords = Math.min( + pageSize, + total - (page - 1) * pageSize + ); + if (remaining < 0 || data.records.length !== expectedPageRecords) { + throw new Error('Queue snapshot is incomplete.'); + } + const items = sanitizeServarrQueue( - response.data.records + data.records ); - if ( - items.length !== response.data.records.length || - items.some( - (item) => - !Number.isSafeInteger(item.id) || item.id <= 0 || seen.has(item.id) - ) - ) { + if (items.length !== data.records.length) { throw new Error('Queue snapshot contains invalid or repeated records.'); } - items.forEach((item) => { - if (seen.has(item.id)) - throw new Error('Queue snapshot contains repeated records.'); + for (const item of items) { + if ( + !Number.isSafeInteger(item.id) || + item.id <= 0 || + seen.has(item.id) + ) { + throw new Error( + 'Queue snapshot contains invalid or repeated records.' + ); + } seen.add(item.id); - }); - records.push(...items); - if (page * pageSize >= total) { - if (records.length !== total) - throw new Error('Queue changed while reading its pages.'); + } + records.push(...items.slice(0, remaining)); + if (records.length === targetRecords) { return records; } - if (items.length === 0) throw new Error('Queue snapshot is incomplete.'); } + throw new Error('Queue snapshot is incomplete.'); } diff --git a/server/api/servarr/queueSnapshot.test.ts b/server/api/servarr/queueSnapshot.test.ts new file mode 100644 index 0000000000..eb0b28607e --- /dev/null +++ b/server/api/servarr/queueSnapshot.test.ts @@ -0,0 +1,58 @@ +import assert from 'node:assert/strict'; +import { afterEach, describe, it, mock } from 'node:test'; +import ServarrBase from './base'; + +afterEach(() => mock.restoreAll()); +const client = () => + new ServarrBase({ + url: 'http://127.0.0.1:8989/api/v3', + apiKey: 'fixture-only-key', + cacheName: 'sonarr', + apiName: 'Sonarr', + }); +type RequestClient = { request: (...args: unknown[]) => Promise }; + +describe('bounded Servarr queue snapshots', () => { + it('keeps pagination offsets stable when a configured cap ends partway through a page', async () => { + const api = client(); + const pages: number[] = []; + mock.method( + api as unknown as RequestClient, + 'request', + async (...args: unknown[]) => { + const { page, pageSize } = ( + args[3] as { params: { page: number; pageSize: number } } + ).params; + assert.equal(pageSize, 1000); + pages.push(page); + return { + data: { + totalRecords: 3000, + records: Array.from({ length: 1000 }, (_, i) => ({ + id: (page - 1) * 1000 + i + 1, + title: 'Queue fixture', + })), + }, + }; + } + ); + const rows = await api.getQueue(1500); + assert.deepEqual(pages, [1, 2]); + assert.equal(rows.length, 1500); + assert.equal(rows[0].id, 1); + assert.equal(rows[1499].id, 1500); + }); + it('rejects duplicate IDs within a single provider page', async () => { + const api = client(); + mock.method(api as unknown as RequestClient, 'request', async () => ({ + data: { + totalRecords: 2, + records: [ + { id: 1, title: 'First' }, + { id: 1, title: 'Duplicate' }, + ], + }, + })); + await assert.rejects(api.getQueue(10), /repeated records/u); + }); +}); diff --git a/server/api/servarr/readarr.ts b/server/api/servarr/readarr.ts index 80335ec547..395087292c 100644 --- a/server/api/servarr/readarr.ts +++ b/server/api/servarr/readarr.ts @@ -73,6 +73,8 @@ export interface ChaptarrEditionCard { publisher?: string; releaseDate?: string; imageUrl?: string; + sampleUrl?: string; + editionLabel?: string; monitored: boolean; owned: boolean; } @@ -2835,30 +2837,34 @@ class ReadarrAPI extends ServarrBase { /** * Track a distinct performance next to the one already selected. Returns - * undefined when the policy, capability, or edition does not apply so the - * caller falls back to the ordinary single-selection path. + * undefined only when the request did not select alongside. Capability or + * catalog failures must not fall back to replacing the existing recording. */ private async addEditionAlongside( existingBook: ReadarrBook, options: ReadarrBookOptions ): Promise { - if (options.editionPolicy !== 'alongside' || !this.isChaptarr()) { - return undefined; - } + if (options.editionPolicy !== 'alongside') return undefined; + if (!this.isChaptarr()) + throw new Error('This destination cannot add an edition alongside.'); await this.ensureCapabilities(); if (!this.supportsWantedEditionVariants()) { - return undefined; + throw new Error( + 'This destination no longer supports additional editions.' + ); } const requested = options.editions?.find((edition) => edition.monitored); if (!requested) { - return undefined; + throw new Error('An additional edition requires an explicit selection.'); } const catalog = await this.getEditionCatalog(existingBook.id); const match = catalog.find( (edition) => edition.foreignEditionId === requested.foreignEditionId ); if (!match) { - return undefined; + throw new Error( + 'The selected additional edition is missing from the catalog.' + ); } if (match.monitored) { return { ...existingBook, createdBook: false, createdAuthor: false }; diff --git a/server/api/servarr/requestPreferences.vitest.test.ts b/server/api/servarr/requestPreferences.vitest.test.ts new file mode 100644 index 0000000000..fe8742a2a4 --- /dev/null +++ b/server/api/servarr/requestPreferences.vitest.test.ts @@ -0,0 +1,143 @@ +import { beforeEach, expect, test, vi } from 'vitest'; +import ReadarrAPI, { + type ReadarrBook, + type ReadarrBookOptions, +} from './readarr'; +import SonarrAPI, { type AddSeriesOptions, type SonarrSeries } from './sonarr'; +const transport = vi.hoisted(() => ({ request: vi.fn() })); +const options: AddSeriesOptions = { + tvdbid: 33, + title: 'A Series', + profileId: 1, + seasons: [], + seasonFolder: true, + rootFolderPath: '/shows', + seriesType: 'standard', + searchNow: false, +}; +const rawSeries = { + id: 42, + tvdbId: 33, + title: 'A Series', + seasons: [], + tags: [7], + monitored: true, + monitorNewItems: 'none', + language: { id: 1, name: 'English' }, + seasonType: 'standard', + qualityProfileId: 9, + path: '/shows/series', + customProviderField: 'preserved', +}; +beforeEach(() => transport.request.mockReset()); +for (const version of ['v3', 'v5'] as const) { + const build = (existing = true, monitorNewItems = 'none') => { + const api = new SonarrAPI({ + url: 'http://fixture:8989/api/v3', + apiKey: 'test', + }); + Object.defineProperty(api, 'request', { value: transport.request }); + const raw = { ...rawSeries, id: existing ? 42 : 0, monitorNewItems }; + Object.defineProperty(api, 'getApiVersion', { value: async () => version }); + vi.spyOn(api, 'getSeriesByTvdbId').mockResolvedValue( + raw as unknown as SonarrSeries + ); + vi.spyOn(api, 'getSeriesById').mockImplementation( + async () => + ({ ...raw, monitorNewItems: 'all' }) as unknown as SonarrSeries + ); + transport.request.mockImplementation( + async (method: string, _path: string, payload?: object) => ({ + data: method === 'GET' ? raw : { ...raw, ...payload, id: 42 }, + }) + ); + return api; + }; + test(`${version}: explicit future-season opt-in updates an existing series`, async () => { + const api = build(); + await api.addSeries({ + ...options, + enableFutureSeasons: true, + monitorNewItems: 'all', + }); + const put = transport.request.mock.calls.find( + ([method, path]) => + method === 'PUT' && + path === (version === 'v5' ? '/series/42' : '/series') + ); + expect(put?.[2]).toMatchObject({ + monitorNewItems: 'all', + path: '/shows/series', + qualityProfileId: 9, + }); + if (version === 'v5') + expect(put?.[2]).toMatchObject({ customProviderField: 'preserved' }); + }); + test(`${version}: opting out preserves existing service monitoring`, async () => { + const api = build(true, 'all'); + await api.addSeries({ + ...options, + enableFutureSeasons: false, + monitorNewItems: 'none', + }); + expect( + transport.request.mock.calls.some( + ([method, , payload]) => + method === 'PUT' && payload?.monitorNewItems === 'none' + ) + ).toBe(false); + }); + test(`${version}: a new series stores the requested monitoring policy`, async () => { + for (const monitoring of ['all', 'none'] as const) { + transport.request.mockClear(); + const api = build(false); + await api.addSeries({ ...options, monitorNewItems: monitoring }); + expect( + transport.request.mock.calls.find( + ([method, path]) => method === 'POST' && path === '/series' + )?.[2] + ).toMatchObject({ monitorNewItems: monitoring }); + } + }); +} + +test('alongside requests fail instead of silently replacing a recording', async () => { + const api = Object.create(ReadarrAPI.prototype) as ReadarrAPI; + const chaptarr = vi.fn().mockReturnValue(false); + Object.defineProperty(api, 'isChaptarr', { value: chaptarr }); + vi.spyOn(api, 'ensureCapabilities').mockResolvedValue(); + const support = vi + .spyOn(api, 'supportsWantedEditionVariants') + .mockReturnValue(false); + const catalog = vi.spyOn(api, 'getEditionCatalog').mockResolvedValue([]); + const wanted = vi + .spyOn(api, 'addWantedEdition') + .mockResolvedValue({ id: 21 } as ReadarrBook); + const add = ( + api as unknown as { + addEditionAlongside: ( + book: ReadarrBook, + options: ReadarrBookOptions + ) => Promise; + } + ).addEditionAlongside.bind(api); + const book = { id: 21 } as ReadarrBook; + const request = { + editionPolicy: 'alongside', + editions: [{ monitored: true, foreignEditionId: 'ed2' }], + } as ReadarrBookOptions; + await expect(add(book, request)).rejects.toThrow(); + chaptarr.mockReturnValue(true); + await expect(add(book, request)).rejects.toThrow(); + support.mockReturnValue(true); + await expect(add(book, request)).rejects.toThrow(); + expect(wanted).not.toHaveBeenCalled(); + catalog.mockResolvedValue([ + { editionId: 2, foreignEditionId: 'ed2', monitored: false }, + ] as never[]); + await add(book, request); + expect(wanted).toHaveBeenCalledWith(21, 2, { + asNewVariant: true, + search: false, + }); +}); diff --git a/server/api/servarr/sonarr.ts b/server/api/servarr/sonarr.ts index d9327795ca..08715eb1b9 100644 --- a/server/api/servarr/sonarr.ts +++ b/server/api/servarr/sonarr.ts @@ -497,6 +497,8 @@ export interface AddSeriesOptions { seriesType: SonarrSeries['seriesType']; monitored?: boolean; monitorNewItems?: SonarrSeries['monitorNewItems']; + /** Explicit opt-in for an existing series; never unmonitors another request. */ + enableFutureSeasons?: boolean; searchNow?: boolean; } @@ -717,6 +719,7 @@ class SonarrAPI extends ServarrBase<{ changes: { seasonType?: string; language?: SonarrMetadataLanguage; + monitorNewItems?: SonarrSeries['monitorNewItems']; } ): Promise { const currentResponse = await this.request( @@ -744,7 +747,12 @@ class SonarrAPI extends ServarrBase<{ public async getSeries({ strict = false, tvdbId, - }: { strict?: boolean; tvdbId?: number } = {}): Promise { + requireTvdbId = true, + }: { + strict?: boolean; + tvdbId?: number; + requireTvdbId?: boolean; + } = {}): Promise { try { const response = await this.request( 'GET', @@ -769,11 +777,11 @@ class SonarrAPI extends ServarrBase<{ series.length !== response.data.length || series.some( (item) => - !Number.isSafeInteger(item.tvdbId) || - item.tvdbId <= 0 || typeof item.id !== 'number' || !Number.isSafeInteger(item.id) || - item.id <= 0 + item.id <= 0 || + (requireTvdbId && + (!Number.isSafeInteger(item.tvdbId) || item.tvdbId <= 0)) )) ) { throw new Error( @@ -1062,11 +1070,16 @@ class SonarrAPI extends ServarrBase<{ if ( series.id && apiVersion === 'v5' && - (seasonTypeChanged || metadataLanguageChanged) + (seasonTypeChanged || + metadataLanguageChanged || + (options.enableFutureSeasons && series.monitorNewItems !== 'all')) ) { await this.updateSeriesV5Metadata(series.id, { ...(options.seasonType ? { seasonType: options.seasonType } : {}), ...(metadataLanguage ? { language: metadataLanguage } : {}), + ...(options.enableFutureSeasons + ? { monitorNewItems: 'all' as const } + : {}), }); series = await this.getSeriesById(series.id); } @@ -1079,6 +1092,7 @@ class SonarrAPI extends ServarrBase<{ // If the series already exists, we will simply just update it if (series.id) { series.monitored = options.monitored ?? series.monitored; + if (options.enableFutureSeasons) series.monitorNewItems = 'all'; series.tags = options.tags ? Array.from(new Set([...series.tags, ...options.tags])) : series.tags; diff --git a/server/commands/interfaceTheme.ts b/server/commands/interfaceTheme.ts index cee239df0c..c293f8f076 100644 --- a/server/commands/interfaceTheme.ts +++ b/server/commands/interfaceTheme.ts @@ -3,6 +3,7 @@ import { INTERFACE_THEME_IDS, parseInterfaceTheme, } from '@server/utils/interfaceTheme'; +import { readInterfaceThemeFile } from '@server/utils/interfaceThemeFile'; import { MAX_INSTALLED_INTERFACE_THEME_CSS_BYTES, MAX_INSTALLED_INTERFACE_THEMES, @@ -10,18 +11,23 @@ import { MAX_INTERFACE_THEME_MANIFEST_BYTES, validateInterfaceThemePackage, } from '@server/utils/interfaceThemePackage'; -import { randomUUID } from 'node:crypto'; import { + getInstalledInterfaceTheme, + listInstalledInterfaceThemes, +} from '@server/utils/interfaceThemeRegistry'; +import { createHash, randomUUID } from 'node:crypto'; +import { + chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, - readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs'; import path from 'node:path'; +import { parseArgs } from 'node:util'; const MAX_BUNDLE_BYTES = 2 * 1024 * 1024; const themeInstallRoot = path.join(appDataPath(), 'interface-themes'); @@ -31,21 +37,18 @@ const usage = (): never => { throw new Error( [ 'Usage:', - ' pnpm interface-theme:validate ', - ' pnpm interface-theme:pack ', + ' pnpm interface-theme:create [directory] [--from persiusNG] [--name Name] [--author Author]', + ' pnpm interface-theme:list', + ' pnpm interface-theme:inspect ', + ' pnpm interface-theme:validate ', + ' pnpm interface-theme:pack [output.seerrtheme]', ' pnpm interface-theme:install [--replace]', ' pnpm interface-theme:uninstall ', ].join('\n') ); }; -const readRegularFile = (filename: string, maxBytes: number): string => { - const stat = lstatSync(filename); - if (stat.isSymbolicLink() || !stat.isFile() || stat.size > maxBytes) { - throw new Error(`Unsupported or oversized package file: ${filename}`); - } - return readFileSync(filename, 'utf8'); -}; +const readRegularFile = readInterfaceThemeFile; const readThemeDirectory = (directory: string) => { const stat = lstatSync(directory); @@ -188,6 +191,8 @@ const installTheme = (filename: string, replace: boolean): void => { }); try { + // Stylesheets are public data and must remain readable by the app worker. + chmodSync(staging, 0o755); if (targetExists) renameSync(target, backup); renameSync(staging, target); if (targetExists) rmSync(backup, { recursive: true }); @@ -200,33 +205,166 @@ const installTheme = (filename: string, replace: boolean): void => { console.log('Restart SeerrNG to load the package into the theme catalog.'); }; +const serializeBundle = ( + theme: ReturnType +): string => + `${JSON.stringify({ formatVersion: 1, manifest: theme.manifest, css: theme.css }, null, 2)}\n`; + const [command, ...arguments_] = process.argv.slice(2); try { - if (command === 'validate') { - const [directory, ...rest] = arguments_; - if (!directory || rest.length > 0) usage(); - const theme = readThemeDirectory(path.resolve(directory)); + if (command === 'create') { + const { values, positionals } = parseArgs({ + args: arguments_, + allowPositionals: true, + options: { + from: { type: 'string', default: 'persiusNG' }, + name: { type: 'string' }, + author: { type: 'string' }, + }, + }); + const [id, directory = id, ...rest] = positionals; + if (!id || rest.length || !parseInterfaceTheme(id) || builtInIds.has(id)) { + throw new Error('Choose a new lowercase kebab-case custom theme ID.'); + } + const base = getInstalledInterfaceTheme(values.from); + if (!base) throw new Error(`Base theme "${values.from}" is not installed.`); + const css = base.css.split(base.manifest.id).join(id); + const manifest = { + ...base.manifest, + id, + name: + values.name ?? + id + .split('-') + .map((word) => word[0].toUpperCase() + word.slice(1)) + .join(' '), + description: `An independent stylesheet based on ${base.manifest.name}.`, + version: '0.1.0', + author: values.author ?? 'Your name', + }; + const theme = validateInterfaceThemePackage(manifest, css, id); + const target = path.resolve(directory); + // mkdir is exclusive; even an empty existing source directory is preserved. + mkdirSync(target, { mode: 0o755 }); + try { + writeFileSync( + path.join(target, 'manifest.json'), + `${JSON.stringify(theme.manifest, null, 2)}\n`, + { flag: 'wx' } + ); + writeFileSync(path.join(target, 'theme.css'), theme.css, { flag: 'wx' }); + writeFileSync( + path.join(target, 'README.md'), + [ + `# ${theme.manifest.name}`, + '', + `Independent CSS theme derived from ${base.manifest.name} (${base.manifest.version}).`, + `Keep the original license and attribution when redistributing derived styles.`, + '', + `Edit manifest.json and theme.css. Every selector is already scoped to ${id}.`, + `The layout field selects native application markup; omit it for classic markup.`, + `Run the following from a SeerrNG checkout, substituting this directory's path:`, + '', + '```sh', + `pnpm interface-theme:validate ./path-to-theme`, + `pnpm interface-theme:pack ./path-to-theme`, + '```', + '', + `Publish source, the .seerrtheme bundle, its .sha256 file, license, screenshots and supported SeerrNG versions.`, + `See https://github.com/snapetech-org/seerrng/blob/main/docs/interface-themes/authoring.md`, + '', + ].join('\n'), + { flag: 'wx' } + ); + } catch (error) { + rmSync(target, { recursive: true, force: true }); + throw error; + } console.log( - `Valid: ${theme.manifest.name} (${theme.manifest.id}) v${theme.manifest.version}` + `Created ${target} from ${base.manifest.id}. Edit its manifest.json and theme.css, then validate and pack it.` ); + } else if (command === 'list') { + if (arguments_.length) usage(); + console.log( + JSON.stringify( + listInstalledInterfaceThemes().map((manifest) => ({ + ...manifest, + builtIn: builtInIds.has(manifest.id), + })), + null, + 2 + ) + ); + } else if (command === 'inspect' || command === 'validate') { + const [input, ...rest] = arguments_; + if (!input || rest.length) usage(); + const target = path.resolve(input); + const installed = + command === 'inspect' && !existsSync(target) + ? getInstalledInterfaceTheme(input) + : undefined; + const directory = !installed && lstatSync(target).isDirectory(); + const theme = + installed ?? + (directory ? readThemeDirectory(target) : readThemeBundle(target)); + if (command === 'validate') { + console.log( + `Valid: ${theme.manifest.name} (${theme.manifest.id}) v${theme.manifest.version}` + ); + } else { + const bundleText = + !installed && !directory + ? readRegularFile(target, MAX_BUNDLE_BYTES) + : serializeBundle(theme); + console.log( + JSON.stringify( + { + ...theme.manifest, + layout: theme.manifest.layout ?? 'classic', + cssBytes: Buffer.byteLength(theme.css, 'utf8'), + sha256: createHash('sha256').update(bundleText).digest('hex'), + }, + null, + 2 + ) + ); + } } else if (command === 'pack') { const [directory, output, ...rest] = arguments_; - if (!directory || !output || rest.length > 0) usage(); + if (!directory || rest.length > 0) usage(); const theme = readThemeDirectory(path.resolve(directory)); - const target = path.resolve(output); - if (existsSync(target)) { - throw new Error('Output already exists; choose a new package filename.'); - } - writeFileSync( - target, - `${JSON.stringify( - { formatVersion: 1, manifest: theme.manifest, css: theme.css }, - null, - 2 - )}\n`, - { encoding: 'utf8', flag: 'wx', mode: 0o644 } + const target = path.resolve( + output ?? `${theme.manifest.id}-${theme.manifest.version}.seerrtheme` ); + const checksumTarget = `${target}.sha256`; + if ( + existsSync(target) || + existsSync(checksumTarget) || + /[\r\n]/.test(path.basename(target)) + ) { + throw new Error( + 'Output or checksum already exists, or the filename contains a line break; choose a new package filename.' + ); + } + const contents = serializeBundle(theme); + const checksum = createHash('sha256').update(contents).digest('hex'); + writeFileSync(target, contents, { + encoding: 'utf8', + flag: 'wx', + mode: 0o644, + }); + try { + writeFileSync(checksumTarget, `${checksum} ${path.basename(target)}\n`, { + encoding: 'utf8', + flag: 'wx', + mode: 0o644, + }); + } catch (error) { + rmSync(target); + throw error; + } console.log(`Created ${target}`); + console.log(`SHA-256 ${checksum} (${checksumTarget})`); } else if (command === 'install') { const [filename, ...options] = arguments_; if ( diff --git a/server/constants/metadata.ts b/server/constants/metadata.ts new file mode 100644 index 0000000000..8c5e917830 --- /dev/null +++ b/server/constants/metadata.ts @@ -0,0 +1,4 @@ +export enum MetadataProviderType { + TMDB = 'tmdb', + TVDB = 'tvdb', +} diff --git a/server/constants/settingsLibraryApi.ts b/server/constants/settingsLibraryApi.ts index b3317c5865..3ffa6dcf48 100644 --- a/server/constants/settingsLibraryApi.ts +++ b/server/constants/settingsLibraryApi.ts @@ -16,6 +16,8 @@ export const SETTINGS_PLEX_LIBRARY_TYPE_ROUTE_PATH = `${SETTINGS_LIBRARY_ROUTE_P export interface SettingsLibraryUpdateBody { sync?: boolean; enable?: string; + episodeOrderLibraryId?: string; + episodeOrderProvider?: 'none' | 'tmdb' | 'tvdb'; } export const getSettingsLibraryApiPath = ( @@ -28,6 +30,10 @@ export const getSettingsPlexLibraryTypeApiPath = (libraryId: string): string => export const createSettingsLibraryUpdateBody = (options: { sync?: boolean; enabledLibraryIds?: readonly string[]; + episodeOrder?: { + libraryId: string; + provider: 'none' | 'tmdb' | 'tvdb'; + }; }): SettingsLibraryUpdateBody => { const body: SettingsLibraryUpdateBody = {}; @@ -35,9 +41,14 @@ export const createSettingsLibraryUpdateBody = (options: { body.sync = options.sync; } - if (options.enabledLibraryIds && options.enabledLibraryIds.length > 0) { + if (options.enabledLibraryIds !== undefined) { body.enable = options.enabledLibraryIds.join(','); } + if (options.episodeOrder) { + body.episodeOrderLibraryId = options.episodeOrder.libraryId; + body.episodeOrderProvider = options.episodeOrder.provider; + } + return body; }; diff --git a/server/entity/EpisodeAvailability.ts b/server/entity/EpisodeAvailability.ts new file mode 100644 index 0000000000..73b69f4398 --- /dev/null +++ b/server/entity/EpisodeAvailability.ts @@ -0,0 +1,69 @@ +import type { MetadataProviderType } from '@server/lib/settings'; +import { + Column, + Entity, + Index, + JoinColumn, + ManyToOne, + PrimaryGeneratedColumn, + Unique, +} from 'typeorm'; +import Season from './Season'; + +export type EpisodeAvailabilitySourceType = + 'sonarr' | 'plex' | 'jellyfin' | 'emby'; + +/** A row represents one episode with a file reported by one configured source. */ +@Entity('episode_availability') +@Index('IDX_EPISODE_AVAILABILITY_SEASON_SOURCE', [ + 'season', + 'sourceType', + 'sourceId', +]) +@Index('IDX_EPISODE_AVAILABILITY_SOURCE_SERIES', [ + 'sourceType', + 'sourceId', + 'metadataProvider', + 'externalSeriesId', +]) +@Unique('UNIQUE_EPISODE_AVAILABILITY', [ + 'season', + 'episodeNumber', + 'sourceType', + 'sourceId', + 'metadataProvider', + 'externalSeriesId', + 'is4k', +]) +class EpisodeAvailability { + @PrimaryGeneratedColumn() + public id: number; + + @Column({ type: 'int' }) + public episodeNumber: number; + + @Column({ type: 'varchar', length: 16 }) + public sourceType: EpisodeAvailabilitySourceType; + + @Column({ type: 'varchar', length: 80 }) + public sourceId: string; + + @Column({ type: 'varchar', length: 16 }) + public metadataProvider: MetadataProviderType; + + @Column({ type: 'int' }) + public externalSeriesId: number; + + @Column({ type: 'boolean', default: false }) + public is4k: boolean; + + @ManyToOne(() => Season, { onDelete: 'CASCADE', nullable: false }) + @JoinColumn({ name: 'seasonId' }) + public season: Season; + + constructor(init?: Partial) { + Object.assign(this, init); + } +} + +export default EpisodeAvailability; diff --git a/server/entity/MediaRequest.ts b/server/entity/MediaRequest.ts index afc5a23c77..f0ea1958a7 100644 --- a/server/entity/MediaRequest.ts +++ b/server/entity/MediaRequest.ts @@ -3,7 +3,7 @@ import ListenBrainzAPI from '@server/api/listenbrainz'; import MusicBrainz from '@server/api/musicbrainz'; import OpenLibraryAPI from '@server/api/openlibrary'; import RadarrAPI from '@server/api/servarr/radarr'; -import SonarrAPI from '@server/api/servarr/sonarr'; +import SonarrAPI, { type LanguageProfile } from '@server/api/servarr/sonarr'; import SportarrAPI from '@server/api/servarr/sportarr'; import WhisparrAPI from '@server/api/servarr/whisparr'; import TheMovieDb from '@server/api/themoviedb'; @@ -24,8 +24,10 @@ import MediaServiceStatus from '@server/entity/MediaServiceStatus'; import OverrideRule from '@server/entity/OverrideRule'; import type { MediaRequestBody } from '@server/interfaces/api/requestInterfaces'; import type { SeasonEpisodeSelection } from '@server/interfaces/api/seasonInterfaces'; +import { compareBookEditions } from '@server/lib/editionCompare'; import { normalizeMusicBrainzId, + normalizeOpenLibraryAuthorId, normalizeOpenLibraryEditionId, normalizeOpenLibraryWorkId, } from '@server/lib/externalIds'; @@ -93,6 +95,7 @@ import { } from '@server/lib/videoMaturityPolicy'; import logger from '@server/logger'; import AsyncLock from '@server/utils/asyncLock'; +import { isProviderBookEdition } from '@server/utils/bookEdition'; import { parseBookshelfBookId } from '@server/utils/bookshelfCatalog'; import { DbAwareColumn, resolveDbType } from '@server/utils/DbColumnHelper'; import { @@ -113,6 +116,7 @@ import { UpdateDateColumn, VirtualColumn, type EntityManager, + type QueryRunner, } from 'typeorm'; import Media from './Media'; import SeasonRequest, { isActiveSeasonRequest } from './SeasonRequest'; @@ -215,6 +219,19 @@ const getRequestMediaLockKey = (requestBody: MediaRequestBody): string => : String(requestBody.mediaId).trim().toLowerCase(), ].join(':'); +const equalRequestTags = ( + left: number[] | null | undefined, + right: number[] | null | undefined +): boolean => { + const leftTags = [...new Set(left ?? [])].sort((a, b) => a - b); + const rightTags = [...new Set(right ?? [])].sort((a, b) => a - b); + + return ( + leftTags.length === rightTags.length && + leftTags.every((tag, index) => tag === rightTags[index]) + ); +}; + const canUseAdvancedRequestOptions = (user: User): boolean => user.hasPermission( [Permission.REQUEST_ADVANCED, Permission.MANAGE_REQUESTS], @@ -1591,16 +1608,97 @@ export class MediaRequest { 'request.metadataProfileId', 'request.rootFolder', 'request.bookFormat', + 'request.preferredEditionId', 'request.serviceTargets', 'requestedBy.id', ]) .where('request.media = :mediaId', { mediaId: media.id }) .getMany() : []; + // Verify the exact performance at the resolved destination before bypassing + // work-level availability. Client edition IDs are never authority. + const preferredEditionId = requestBody.preferredEditionId; + if ( + isProviderBookEdition(preferredEditionId) && + requestedBookFormat === 'both' + ) { + throw new ServiceConfigurationError( + 'A specific edition requires a single book format.' + ); + } + const hasEditionChoice = isProviderBookEdition(preferredEditionId); + if (requestBody.editionPolicy === 'alongside' && !hasEditionChoice) { + throw new ServiceConfigurationError( + 'Choose one book format and a specific edition to add alongside.' + ); + } + if (hasEditionChoice) { + const expectedWork = parseBookshelfBookId( + requestBody.mediaId.toString() + ) + ? undefined + : await openLibrary.getWork(openLibraryId); + const expectedTitle = expectedWork?.title; + const authorKey = expectedWork?.authors?.[0]?.author?.key; + const expectedAuthor = authorKey + ? ( + await openLibrary.getAuthor( + normalizeOpenLibraryAuthorId(authorKey) + ) + )?.name + : undefined; + const comparison = await compareBookEditions({ + title: expectedTitle, + author: expectedAuthor, + mediaId: media.id, + bookId: requestBody.mediaId.toString(), + serverId: selectedReadarr?.id, + format: requestedServiceType, + term: + requestBody.preferredIsbn13 || + requestBody.isbn13 || + parseBookshelfBookId(requestBody.mediaId.toString()) + ?.foreignBookId || + expectedTitle || + requestBody.mediaId.toString(), + }); + const selectedEdition = comparison.editions.find( + (edition) => edition.id === preferredEditionId + ); + if (!selectedEdition || selectedEdition.requestable === false) + throw new ServiceConfigurationError( + 'The selected edition could not be verified for this book and destination.' + ); + if (selectedEdition.owned) + throw new DuplicateMediaRequestError( + 'This exact edition is already available.' + ); + if ( + requestBody.editionPolicy === 'alongside' && + !comparison.supportsAlongside + ) { + throw new ServiceConfigurationError( + 'This destination cannot keep another edition alongside the existing one.' + ); + } + } + const editionRequests = hasEditionChoice + ? destinationRequests.filter( + (request) => request.preferredEditionId === preferredEditionId + ) + : destinationRequests; + const blockingRequests = hasEditionChoice + ? destinationRequests.filter( + (request) => + !isProviderBookEdition(request.preferredEditionId) || + request.preferredEditionId === preferredEditionId + ) + : destinationRequests; const isLegacyBookTargetAvailable = ( target: MediaRequestServiceTarget ): boolean => { if ( + hasEditionChoice || media.status !== MediaStatus.AVAILABLE || hasTrackedAvailableDestination(destinationRequests, target) ) { @@ -1622,17 +1720,17 @@ export class MediaRequest { const uncoveredBookTargets = bookTargets.filter( (target) => !isLegacyBookTargetAvailable(target) && - !isDestinationAvailableInTargets(destinationRequests, target) && - !isDestinationCoveredByActiveRequest(destinationRequests, target) + !isDestinationAvailableInTargets(editionRequests, target) && + !isDestinationCoveredByActiveRequest(blockingRequests, target) ); const unavailableBookTargets = bookTargets.filter( (target) => !isLegacyBookTargetAvailable(target) && - !isDestinationAvailableInTargets(destinationRequests, target) + !isDestinationAvailableInTargets(editionRequests, target) ); const promotablePendingRequest = findPromotablePendingRequest( - destinationRequests, + editionRequests, unavailableBookTargets, user, MediaType.BOOK @@ -1643,7 +1741,7 @@ export class MediaRequest { if ( bookTargets.some((target) => - isDestinationCoveredByActiveRequest(destinationRequests, target) + isDestinationCoveredByActiveRequest(blockingRequests, target) ) ) { throw new DuplicateMediaRequestError( @@ -2654,6 +2752,19 @@ export class MediaRequest { } const resolvedTvdbId = media.tvdbId ?? tvdbId; + const futureSeasonsRestricted = + watchAheadEpisodeCount > 0 || + isTvSeasonWatchGateEnabledForUser(requestUser); + if ( + requestBody.mediaType === MediaType.TV && + requestBody.monitorFutureSeasons === true && + futureSeasonsRestricted + ) { + throw new RequestPermissionError( + 'Future seasons are managed by Episode Queue or the season watch gate.' + ); + } + if (watchAheadEpisodeCount > 0) { if ( !Number.isSafeInteger(Number(resolvedTvdbId)) || @@ -2706,23 +2817,24 @@ export class MediaRequest { ); } const selectedServer = requestedServer ?? defaultServer; + const tmdbKeywords = tmdbMedia.keywords; + const isAnimeRequest = + requestBody.mediaType === MediaType.TV && + ('results' in tmdbKeywords + ? tmdbKeywords.results.some( + (keyword: TmdbKeyword) => keyword.id === ANIME_KEYWORD_ID + ) + : 'keywords' in tmdbKeywords + ? tmdbKeywords.keywords.some( + (keyword: TmdbKeyword) => keyword.id === ANIME_KEYWORD_ID + ) + : false); if ( (requestBody.mediaType === MediaType.MOVIE || requestBody.mediaType === MediaType.TV) && selectedServer?.requestButtonAnimeOnly ) { - const keywords = tmdbMedia.keywords; - const isAnime = - 'results' in keywords - ? keywords.results.some( - (keyword: TmdbKeyword) => keyword.id === ANIME_KEYWORD_ID - ) - : 'keywords' in keywords - ? keywords.keywords.some( - (keyword: TmdbKeyword) => keyword.id === ANIME_KEYWORD_ID - ) - : false; - if (!isAnime) { + if (!isAnimeRequest) { throw new RequestPermissionError( 'The selected request destination is limited to anime titles.' ); @@ -2740,25 +2852,32 @@ export class MediaRequest { requestBody.mediaType === MediaType.TV ? (selectedServer as SonarrSettings) : undefined; - - let rootFolder = useAdvancedOptions - ? (requestBody.rootFolder ?? - requestRootFolder ?? - selectedServer?.activeDirectory) - : (requestRootFolder ?? selectedServer?.activeDirectory); - let profileId = useAdvancedOptions - ? (requestBody.profileId ?? selectedServer?.activeProfileId) + const serviceDefaultRootFolder = + isAnimeRequest && selectedSonarr?.activeAnimeDirectory + ? selectedSonarr.activeAnimeDirectory + : selectedServer?.activeDirectory; + const serviceDefaultProfileId = isAnimeRequest + ? (selectedSonarr?.activeAnimeProfileId ?? + selectedServer?.activeProfileId) : selectedServer?.activeProfileId; - let tags = useAdvancedOptions - ? (requestBody.tags ?? selectedServer?.tags) - : selectedServer?.tags; + const serviceDefaultTags = selectedSonarr + ? isAnimeRequest + ? (selectedSonarr.animeTags ?? []) + : (selectedSonarr.tags ?? []) + : (selectedServer?.tags ?? []); + const serviceDefaultLanguageProfileId = isAnimeRequest + ? (selectedSonarr?.activeAnimeLanguageProfileId ?? + selectedSonarr?.activeLanguageProfileId) + : selectedSonarr?.activeLanguageProfileId; + + let rootFolder = requestRootFolder ?? serviceDefaultRootFolder; + let profileId = serviceDefaultProfileId; + let tags = [...serviceDefaultTags]; let languageProfileId = requestBody.mediaType === MediaType.TV - ? useAdvancedOptions - ? (requestBody.languageProfileId ?? - selectedSonarr?.activeLanguageProfileId) - : selectedSonarr?.activeLanguageProfileId + ? serviceDefaultLanguageProfileId : undefined; + let sonarrLanguageProfiles: LanguageProfile[] | undefined; const metadataLanguageId = requestBody.mediaType === MediaType.TV && useAdvancedOptions ? requestBody.metadataLanguageId @@ -2773,10 +2892,7 @@ export class MediaRequest { requestBody.mediaType === MediaType.MOVIE ? 'movie' : 'tv' ); if (mediaLanguagePreference) { - if ( - requestBody.mediaType === MediaType.MOVIE && - !(useAdvancedOptions && requestBody.profileId != null) - ) { + if (requestBody.mediaType === MediaType.MOVIE && selectedServer) { const radarrServer = selectedServer as RadarrSettings | undefined; if (radarrServer) { try { @@ -2805,28 +2921,27 @@ export class MediaRequest { apiKey: selectedSonarr.apiKey, url: SonarrAPI.buildUrl(selectedSonarr, '/api/v3'), }); - if (!(useAdvancedOptions && requestBody.languageProfileId != null)) { - const languageProfiles = await sonarr - .getLanguageProfiles() - .catch(() => []); - const preferredProfile = languageProfiles.find( - (profile) => - (profile.languages ?? []).some((language) => - languageNameMatchesCode(language, mediaLanguagePreference) - ) || - languageNameMatchesCode(profile.name, mediaLanguagePreference) - ); - if (preferredProfile) languageProfileId = preferredProfile.id; + const languageProfiles = await sonarr + .getLanguageProfiles() + .catch(() => []); + sonarrLanguageProfiles = languageProfiles; + const preferredLanguageProfile = languageProfiles.find( + (profile) => + (profile.languages ?? []).some((language) => + languageNameMatchesCode(language, mediaLanguagePreference) + ) || + languageNameMatchesCode(profile.name, mediaLanguagePreference) + ); + if (preferredLanguageProfile) { + languageProfileId = preferredLanguageProfile.id; } - if (!(useAdvancedOptions && requestBody.profileId != null)) { - const qualityProfiles = await sonarr.getProfiles(); - const preferredQualityProfile = qualityProfiles.find((profile) => - languageNameMatchesCode(profile.language, mediaLanguagePreference) - ); - if (preferredQualityProfile) { - profileId = preferredQualityProfile.id; - } + const qualityProfiles = await sonarr.getProfiles(); + const preferredQualityProfile = qualityProfiles.find((profile) => + languageNameMatchesCode(profile.language, mediaLanguagePreference) + ); + if (preferredQualityProfile) { + profileId = preferredQualityProfile.id; } } catch (error) { logger.debug( @@ -2841,6 +2956,53 @@ export class MediaRequest { } } + const requestDefaultRootFolder = rootFolder; + const requestDefaultProfileId = profileId; + const requestDefaultTags = tags; + const requestDefaultLanguageProfileId = languageProfileId; + // Older API clients supplied explicit values without provenance flags. + const legacyExplicitOptions = + requestBody.requesterSelectedOptions === undefined; + const requesterSelectedRootFolder = + useAdvancedOptions && + (requestBody.requesterSelectedOptions?.rootFolder === true || + (requestBody.rootFolder != null && + (legacyExplicitOptions || + requestBody.rootFolder !== requestDefaultRootFolder))); + const requesterSelectedProfile = + useAdvancedOptions && + (requestBody.requesterSelectedOptions?.profile === true || + (requestBody.profileId != null && + (legacyExplicitOptions || + requestBody.profileId !== requestDefaultProfileId))); + const requesterSelectedTags = + useAdvancedOptions && + (requestBody.requesterSelectedOptions?.tags === true || + (requestBody.tags != null && + (legacyExplicitOptions || + !equalRequestTags(requestBody.tags, requestDefaultTags)))); + const requesterSelectedLanguageProfile = + requestBody.mediaType === MediaType.TV && + useAdvancedOptions && + (requestBody.requesterSelectedOptions?.languageProfile === true || + (requestBody.languageProfileId != null && + (legacyExplicitOptions || + requestBody.languageProfileId !== + requestDefaultLanguageProfileId))); + + if (requesterSelectedRootFolder) { + rootFolder = requestBody.rootFolder ?? undefined; + } + if (requesterSelectedProfile) { + profileId = requestBody.profileId ?? undefined; + } + if (requesterSelectedTags) { + tags = requestBody.tags ?? []; + } + if (requesterSelectedLanguageProfile) { + languageProfileId = requestBody.languageProfileId ?? undefined; + } + const overrideResult = selectedServer ? await evaluateOverrideRules({ mediaType: requestBody.mediaType, @@ -2853,14 +3015,9 @@ export class MediaRequest { : undefined; if (overrideResult) { - const requesterSelectedRootFolder = - useAdvancedOptions && requestBody.rootFolder !== undefined; - const requesterSelectedProfile = - useAdvancedOptions && requestBody.profileId !== undefined; - const requesterSelectedTags = - useAdvancedOptions && requestBody.tags !== undefined; const addedRuleTags = overrideResult.tags?.filter((tag) => !tags?.includes(tag)) ?? []; + let appliedRuleLanguageProfile = false; if (overrideResult.rootFolder && !requesterSelectedRootFolder) { rootFolder = overrideResult.rootFolder; @@ -2868,6 +3025,29 @@ export class MediaRequest { if (overrideResult.profileId !== null && !requesterSelectedProfile) { profileId = overrideResult.profileId; } + if ( + overrideResult.languageProfileId !== null && + !requesterSelectedLanguageProfile && + selectedSonarr + ) { + const languageProfiles = + sonarrLanguageProfiles ?? + (await new SonarrAPI({ + apiKey: selectedSonarr.apiKey, + url: SonarrAPI.buildUrl(selectedSonarr, '/api/v3'), + }) + .getLanguageProfiles() + .catch(() => [])); + if ( + languageProfiles.some( + (languageProfile) => + languageProfile.id === overrideResult.languageProfileId + ) + ) { + languageProfileId = overrideResult.languageProfileId; + appliedRuleLanguageProfile = true; + } + } if (!requesterSelectedTags && overrideResult.tags !== null) { tags = overrideResult.tags; } @@ -2875,6 +3055,7 @@ export class MediaRequest { if ( (overrideResult.rootFolder && !requesterSelectedRootFolder) || (overrideResult.profileId !== null && !requesterSelectedProfile) || + appliedRuleLanguageProfile || (addedRuleTags.length > 0 && !requesterSelectedTags) ) { logger.debug('Override rule applied.', { @@ -2886,12 +3067,33 @@ export class MediaRequest { profileId: requesterSelectedProfile ? null : overrideResult.profileId, + languageProfileId: appliedRuleLanguageProfile + ? overrideResult.languageProfileId + : null, tags: requesterSelectedTags ? null : addedRuleTags, }, }); } } + const storedProfileId = + !requesterSelectedProfile && profileId === serviceDefaultProfileId + ? null + : (profileId ?? null); + const storedRootFolder = + !requesterSelectedRootFolder && rootFolder === serviceDefaultRootFolder + ? null + : (rootFolder ?? null); + const storedLanguageProfileId = + !requesterSelectedLanguageProfile && + languageProfileId === serviceDefaultLanguageProfileId + ? null + : (languageProfileId ?? null); + const storedTags = + !requesterSelectedTags && equalRequestTags(tags, serviceDefaultTags) + ? null + : (tags ?? null); + const selectedDestination: RequestDestination | undefined = serverId === undefined ? undefined @@ -3068,9 +3270,9 @@ export class MediaRequest { modifiedBy: autoApproved ? user : undefined, is4k: requestBody.is4k, serverId, - profileId: profileId, - rootFolder: rootFolder, - tags: tags, + profileId: storedProfileId, + rootFolder: storedRootFolder, + tags: storedTags, serviceTargets: serverId === undefined ? [] @@ -3359,14 +3561,17 @@ export class MediaRequest { modifiedBy: autoApproved ? user : undefined, is4k: requestBody.is4k, watchAheadEpisodeCount, + monitorFutureSeasons: futureSeasonsRestricted + ? false + : requestBody.monitorFutureSeasons, watchAheadUsesUserDefault, serverId, - profileId: profileId, - rootFolder: rootFolder, - languageProfileId, + profileId: storedProfileId, + rootFolder: storedRootFolder, + languageProfileId: storedLanguageProfileId, metadataLanguageId, sonarrSeasonType, - tags: tags, + tags: storedTags, serviceTargets: serverId === undefined ? [] @@ -3520,6 +3725,10 @@ export class MediaRequest { @Column({ default: false }) public is4k: boolean; + /** Null preserves the service default for existing requests. */ + @Column({ type: 'boolean', nullable: true }) + public monitorFutureSeasons?: boolean | null; + /** Number of upcoming unwatched episodes to keep requested automatically. */ @Column({ type: 'integer', default: 0 }) public watchAheadEpisodeCount = 0; @@ -3555,14 +3764,14 @@ export class MediaRequest { @Column({ nullable: true }) public serverId: number; - @Column({ nullable: true }) - public profileId: number; + @Column({ type: 'integer', nullable: true }) + public profileId: number | null; - @Column({ nullable: true }) - public rootFolder: string; + @Column({ type: 'varchar', nullable: true }) + public rootFolder: string | null; - @Column({ nullable: true }) - public languageProfileId: number; + @Column({ type: 'integer', nullable: true }) + public languageProfileId: number | null; @Column({ type: 'integer', nullable: true }) public metadataLanguageId?: number | null; @@ -3644,7 +3853,7 @@ export class MediaRequest { }, }, }) - public tags?: number[]; + public tags?: number[] | null; @Column({ default: false }) public isAutoRequest: boolean; @@ -3669,14 +3878,19 @@ export class MediaRequest { static async sendNotification( entity: MediaRequest, media: Media, - type: Notification + type: Notification, + queryRunner?: QueryRunner ) { try { if (Number.isSafeInteger(entity.id) && entity.id > 0) { - await notificationManager.sendNotificationIntent(type, { - kind: 'media-request', - requestId: entity.id, - }); + await notificationManager.sendNotificationIntent( + type, + { + kind: 'media-request', + requestId: entity.id, + }, + queryRunner + ); return; } const { buildMediaRequestNotificationPayload } = @@ -3686,7 +3900,7 @@ export class MediaRequest { media, type ); - await notificationManager.sendNotification(type, payload); + await notificationManager.sendNotification(type, payload, queryRunner); } catch (e) { logger.error('Something went wrong sending media notification(s)', { label: 'Notifications', @@ -3694,6 +3908,9 @@ export class MediaRequest { requestId: entity.id, mediaId: entity.media.id, }); + if (queryRunner) { + throw e; + } } } } diff --git a/server/entity/OverrideRule.ts b/server/entity/OverrideRule.ts index 17bae9baf3..5c946cc0f9 100644 --- a/server/entity/OverrideRule.ts +++ b/server/entity/OverrideRule.ts @@ -35,9 +35,15 @@ class OverrideRule { @Column({ nullable: true }) public keywords?: string; + @Column({ nullable: true }) + public productionCountries?: string; + @Column({ type: 'int', nullable: true }) public profileId?: number; + @Column({ type: 'int', nullable: true }) + public languageProfileId?: number; + @Column({ nullable: true }) public rootFolder?: string; diff --git a/server/i18n/globalMessages.ts b/server/i18n/globalMessages.ts index 5b4947fbcd..bdf16ebdcc 100644 --- a/server/i18n/globalMessages.ts +++ b/server/i18n/globalMessages.ts @@ -4,6 +4,7 @@ const globalMessages = defineMessages('notifications.common', { requestedBy: 'Requested By', requestStatus: 'Request Status', pendingApproval: 'Pending Approval', + requestUpdated: 'Request Updated', approve: 'Approve', decline: 'Decline', cancel: 'Cancel', diff --git a/server/i18n/locale/en.json b/server/i18n/locale/en.json index f881fb1d53..f41fcec50c 100644 --- a/server/i18n/locale/en.json +++ b/server/i18n/locale/en.json @@ -20,6 +20,8 @@ "notifications.agents.email.issueType": "{type} issue", "notifications.agents.email.pendingRequest": "A new request for the following {mediaType} is pending approval:", "notifications.agents.email.pendingRequest4k": "A new request for the following {mediaType} in 4K is pending approval:", + "notifications.agents.email.pendingRequestUpdated": "The pending request for the following {mediaType} has been updated:", + "notifications.agents.email.pendingRequestUpdated4k": "The pending request for the following {mediaType} in 4K has been updated:", "notifications.agents.webpush.approved": "Your {quality}{mediaType} request has been approved.", "notifications.agents.webpush.autoApproved": "Automatically approved a new {quality}{mediaType} request from {userName}.", "notifications.agents.webpush.autoRequested": "Automatically submitted a new {quality}{mediaType} request.", @@ -32,6 +34,7 @@ "notifications.agents.webpush.issueReopened": "The {issueType} was reopened by {userName}.", "notifications.agents.webpush.issueResolved": "The {issueType} was marked as resolved by {userName}!", "notifications.agents.webpush.pending": "Approval required for a new {quality}{mediaType} request from {userName}.", + "notifications.agents.webpush.pendingUpdated": "A pending {quality}{mediaType} request was updated.", "notifications.agents.webpush.viewIssue": "View Issue", "notifications.agents.webpush.viewMedia": "View Media", "notifications.agents.webpush.viewRequestStatus": "View Request Status", @@ -60,6 +63,7 @@ "notifications.common.processing": "Processing", "notifications.common.reportedBy": "Reported By", "notifications.common.requestStatus": "Request Status", + "notifications.common.requestUpdated": "Request Updated", "notifications.common.requestedBy": "Requested By", "notifications.common.resolved": "Resolved", "notifications.common.series": "series", diff --git a/server/interfaces/api/requestInterfaces.ts b/server/interfaces/api/requestInterfaces.ts index 7732caa64e..c44e003e3f 100644 --- a/server/interfaces/api/requestInterfaces.ts +++ b/server/interfaces/api/requestInterfaces.ts @@ -27,21 +27,36 @@ export interface RequestResultsResponse extends PaginatedResponse { }; } +export type RequestTargetOptions = { + profileId: number | null; + rootFolder: string | null; + languageProfileId?: number | null; + tags: number[] | null; +}; + +export type RequesterSelectedOptions = { + profile?: boolean; + rootFolder?: boolean; + languageProfile?: boolean; + tags?: boolean; +}; + export type MediaRequestBody = { mediaType: MediaType; mediaId: number | string; tvdbId?: number; seasons?: number[] | 'all'; seasonRequests?: SeasonEpisodeSelection[]; + monitorFutureSeasons?: boolean; watchAheadEpisodeCount?: number; watchAheadUsesUserDefault?: boolean; is4k?: boolean; serverId?: number; requestServiceServerId?: number; - profileId?: number; + profileId?: number | null; profileName?: string; - rootFolder?: string; - languageProfileId?: number; + rootFolder?: string | null; + languageProfileId?: number | null; metadataLanguageId?: number | null; sonarrSeasonType?: string | null; metadataProfileId?: number; @@ -54,7 +69,9 @@ export type MediaRequestBody = { variantKey?: string; authorId?: string; userId?: number; - tags?: number[]; + tags?: number[] | null; + requestTargetOptions?: RequestTargetOptions; + requesterSelectedOptions?: RequesterSelectedOptions; ignoreQuota?: boolean; requestQuotaApproval?: boolean; }; diff --git a/server/lib/bookRequestEdit.ts b/server/lib/bookRequestEdit.ts new file mode 100644 index 0000000000..259185c9cc --- /dev/null +++ b/server/lib/bookRequestEdit.ts @@ -0,0 +1,205 @@ +import OpenLibraryAPI from '@server/api/openlibrary'; +import { MediaStatus, MediaType } from '@server/constants/media'; +import { getRepository } from '@server/datasource'; +import MediaIdentifier, { + MediaIdentifierProvider, +} from '@server/entity/MediaIdentifier'; +import { + ServiceConfigurationError, + type MediaRequest, + type MediaRequestServiceTarget, +} from '@server/entity/MediaRequest'; +import type { MediaRequestBody } from '@server/interfaces/api/requestInterfaces'; +import { compareBookEditions } from '@server/lib/editionCompare'; +import { normalizeOpenLibraryAuthorId } from '@server/lib/externalIds'; +import { getExternalRuntimeConfig } from '@server/lib/externalRuntimeConfig'; +import { validateExternalServiceConfiguration } from '@server/lib/requestTransition'; +import { isProviderBookEdition } from '@server/utils/bookEdition'; +import { parseBookshelfBookId } from '@server/utils/bookshelfCatalog'; +import { readarrServiceSupportsFormat } from '@server/utils/readarrService'; + +export class BookRequestEditConflictError extends Error { + readonly status = 409; +} + +/** Plan first: failed destination/edition validation must leave the saved request intact. */ +export const planBookRequestEdit = async ( + request: MediaRequest, + body: Partial +) => { + const format = body.format ?? request.bookFormat ?? 'ebook'; + const exactEdition = isProviderBookEdition(request.preferredEditionId); + for (const field of [ + 'preferredEditionId', + 'preferredIsbn13', + 'editionPolicy', + 'variantKey', + ] as const) { + if (body[field] !== undefined && body[field] !== request[field]) { + throw new BookRequestEditConflictError( + 'Cancel this request and create a new one to change its edition selection.' + ); + } + } + if (exactEdition && format !== request.bookFormat) { + throw new BookRequestEditConflictError( + 'An exact edition cannot change book format. Create a new request for the other format.' + ); + } + + const serverId = body.serverId ?? request.serverId; + validateExternalServiceConfiguration(MediaType.BOOK, serverId, format); + const servers = getExternalRuntimeConfig().readarr; + const selected = servers.find((server) => server.id === serverId); + const stored = + request.serviceTargets?.filter( + (target) => target.serviceType === 'readarr' + ) ?? []; + // Creation can omit a format already covered by another request. A partial edit + // must not silently add that destination back to this request. + const formats: ('ebook' | 'audiobook')[] = + format === 'both' + ? request.bookFormat === 'both' && stored.length + ? stored.flatMap((target) => + target.format === 'ebook' || target.format === 'audiobook' + ? [target.format] + : [] + ) + : ['ebook', 'audiobook'] + : [format]; + + const serviceTargets: MediaRequestServiceTarget[] = formats.map( + (targetFormat) => { + const previous = stored.find((target) => target.format === targetFormat); + const server = + body.serverId === undefined && previous + ? servers.find((entry) => entry.id === previous.serverId) + : selected && readarrServiceSupportsFormat(selected, targetFormat) + ? selected + : servers.find( + (entry) => + entry.isDefault && + readarrServiceSupportsFormat(entry, targetFormat) + ); + if (!server || !readarrServiceSupportsFormat(server, targetFormat)) { + throw new ServiceConfigurationError( + `No valid ${targetFormat} Bookshelf destination is configured for this request.` + ); + } + const sameDestination = previous + ? previous.serverId === server.id + : request.serverId === server.id && + (request.bookFormat ?? 'ebook') === targetFormat; + const saved = previous ?? request; + const overrides = serverId == null || server.id === serverId; + return { + serviceType: 'readarr', + format: targetFormat, + serverId: server.id, + profileId: + overrides && body.profileId !== undefined + ? body.profileId + : sameDestination + ? (saved.profileId ?? server.activeProfileId) + : server.activeProfileId, + metadataProfileId: + overrides && body.metadataProfileId !== undefined + ? body.metadataProfileId + : sameDestination + ? (saved.metadataProfileId ?? null) + : (server.activeMetadataProfileId ?? null), + rootFolder: + overrides && body.rootFolder !== undefined + ? body.rootFolder + : sameDestination + ? (saved.rootFolder ?? server.activeDirectory) + : server.activeDirectory, + tags: + overrides && body.tags !== undefined + ? body.tags + : sameDestination + ? (saved.tags ?? null) + : (server.tags ?? null), + status: + sameDestination && previous ? previous.status : MediaStatus.PENDING, + ...(sameDestination && previous + ? { + externalServiceId: previous.externalServiceId, + externalServiceSlug: previous.externalServiceSlug, + } + : {}), + }; + } + ); + const primary = + serviceTargets.find((target) => target.serverId === serverId) ?? + serviceTargets[0]; + if (!primary) + throw new ServiceConfigurationError( + 'This request has no book destinations.' + ); + + if (exactEdition) { + const identifiers = await getRepository(MediaIdentifier).find({ + where: { media: { id: request.media.id } }, + }); + const bookId = + identifiers.find( + (entry) => entry.provider === MediaIdentifierProvider.BOOKSHELF + )?.value ?? + identifiers.find( + (entry) => entry.provider === MediaIdentifierProvider.OPENLIBRARY + )?.value; + const identity = bookId ? parseBookshelfBookId(bookId) : undefined; + const openLibrary = new OpenLibraryAPI(); + const work = + bookId && !identity ? await openLibrary.getWork(bookId) : undefined; + const authorKey = work?.authors?.[0]?.author?.key; + const author = authorKey + ? (await openLibrary.getAuthor(normalizeOpenLibraryAuthorId(authorKey))) + ?.name + : undefined; + const comparison = await compareBookEditions({ + bookId, + mediaId: request.media.id, + serverId: primary.serverId, + format: format === 'audiobook' ? 'audiobook' : 'ebook', + title: work?.title, + author, + term: + request.preferredIsbn13 || + identity?.foreignBookId || + work?.title || + bookId, + }); + const edition = comparison.editions.find( + (entry) => entry.id === request.preferredEditionId + ); + if (!edition || edition.requestable === false) { + throw new ServiceConfigurationError( + 'The selected edition could not be verified for this book and destination.' + ); + } + if (edition.owned) + throw new BookRequestEditConflictError( + 'This exact edition is already available at the selected destination.' + ); + if ( + request.editionPolicy === 'alongside' && + !comparison.supportsAlongside + ) { + throw new ServiceConfigurationError( + 'This destination cannot keep another edition alongside the existing one.' + ); + } + } + return { + bookFormat: format, + serverId: primary.serverId, + profileId: primary.profileId, + metadataProfileId: primary.metadataProfileId, + rootFolder: primary.rootFolder, + tags: primary.tags, + serviceTargets, + }; +}; diff --git a/server/lib/bookRequestSearch.test.ts b/server/lib/bookRequestSearch.test.ts index bed9712bcc..f9d80308ca 100644 --- a/server/lib/bookRequestSearch.test.ts +++ b/server/lib/bookRequestSearch.test.ts @@ -8,9 +8,14 @@ import { import { getRepository } from '@server/datasource'; import { BookRequestSearch } from '@server/entity/BookRequestSearch'; import Media from '@server/entity/Media'; -import { MediaRequest } from '@server/entity/MediaRequest'; +import { + MediaRequest, + getRequestMutationAdmissionKey, + runWithRequestAdmission, +} from '@server/entity/MediaRequest'; import MediaRequestStatusEvent from '@server/entity/MediaRequestStatusEvent'; import { User } from '@server/entity/User'; +import notificationManager, { Notification } from '@server/lib/notifications'; import { getSettings } from '@server/lib/settings'; import { resetTestDb, seedTestDb } from '@server/utils/seedTestDb'; import assert from 'node:assert/strict'; @@ -157,6 +162,106 @@ describe('BookRequestSearchManager', () => { getSettings().readarr = []; }); + it('completes an exact recording through notification and status history subscribers once', async () => { + const { request } = await createTrackedRequest({ + createdBook: false, + createdAuthor: false, + }); + await getRepository(MediaRequest).update(request.id, { + status: MediaRequestStatus.APPROVED, + preferredEditionId: 'hc:voice-2', + serviceTargets: [ + { + serviceType: 'readarr', + serverId: 20, + format: 'ebook', + status: MediaStatus.PROCESSING, + }, + ], + }); + await getRepository(BookRequestSearch).update( + { requestId: request.id }, + { state: 'available', providerEditionId: 'hc:voice-2' } + ); + const notification = mock.method( + notificationManager, + 'sendNotificationIntent' + ); + notification.mock.mockImplementation(async () => undefined); + + await bookRequestSearchManager.run(); + + const saved = await getRepository(MediaRequest).findOneByOrFail({ + id: request.id, + }); + assert.equal(saved.status, MediaRequestStatus.COMPLETED); + assert.equal(saved.serviceTargets?.[0].status, MediaStatus.AVAILABLE); + assert.equal(notification.mock.callCount(), 1); + assert.equal( + notification.mock.calls[0].arguments[0], + Notification.MEDIA_AVAILABLE + ); + assert.deepEqual(notification.mock.calls[0].arguments[1], { + kind: 'media-request', + requestId: request.id, + }); + const history = await getRepository(MediaRequestStatusEvent).findBy({ + requestId: request.id, + }); + assert.ok( + history.some((event) => event.stage === RequestStatusStage.AVAILABLE) + ); + + await bookRequestSearchManager.run(); + assert.equal(notification.mock.callCount(), 1); + }); + + it('does not complete a recording after cancellation wins the request admission lock', async () => { + const { request } = await createTrackedRequest({ + createdBook: false, + createdAuthor: false, + }); + await getRepository(MediaRequest).update(request.id, { + status: MediaRequestStatus.APPROVED, + preferredEditionId: 'hc:voice-2', + }); + await getRepository(BookRequestSearch).update( + { requestId: request.id }, + { state: 'available', providerEditionId: 'hc:voice-2' } + ); + let entered!: () => void; + let release!: () => void; + const locked = new Promise((resolve) => { + entered = resolve; + }); + const gate = new Promise((resolve) => { + release = resolve; + }); + const cancellation = runWithRequestAdmission( + [getRequestMutationAdmissionKey(request.id)], + async () => { + entered(); + await gate; + await getRepository(MediaRequest).update(request.id, { + status: MediaRequestStatus.DECLINED, + }); + } + ); + await locked; + const completion = bookRequestSearchManager.run(); + release(); + await Promise.all([cancellation, completion]); + + const saved = await getRepository(MediaRequest).findOneByOrFail({ + id: request.id, + }); + assert.equal(saved.status, MediaRequestStatus.DECLINED); + assert.equal( + await getRepository(BookRequestSearch).countBy({ requestId: request.id }), + 0 + ); + }); + it('keeps an active Bookshelf command in the searching state', async () => { const { request } = await createTrackedRequest({ createdBook: true, diff --git a/server/lib/bookRequestSearch.ts b/server/lib/bookRequestSearch.ts index e70a8aa02f..e044197f32 100644 --- a/server/lib/bookRequestSearch.ts +++ b/server/lib/bookRequestSearch.ts @@ -17,8 +17,11 @@ import MediaIdentifier, { } from '@server/entity/MediaIdentifier'; import { MediaRequest, + getRequestMutationAdmissionKey, + runWithRequestAdmission, type MediaRequestServiceTarget, } from '@server/entity/MediaRequest'; +import { hasRequestedEditionFiles } from '@server/lib/editionCompare/availability'; import { getExternalRuntimeConfig } from '@server/lib/externalRuntimeConfig'; import { normalizeValidIsbn } from '@server/lib/isbn'; import { @@ -27,6 +30,7 @@ import { } from '@server/lib/requestStatus'; import type { ReadarrSettings } from '@server/lib/settings'; import logger from '@server/logger'; +import { isProviderBookEdition } from '@server/utils/bookEdition'; const terminalCommandStates = new Set([ 'completed', @@ -345,7 +349,13 @@ class BookRequestSearchManager { Number.isFinite(eventTime) && eventTime >= operation.createdAt.getTime() ); }); - if ((book.statistics?.bookFileCount ?? 0) > 0) { + if ( + await hasRequestedEditionFiles( + readarr, + book, + operation.request.preferredEditionId + ) + ) { await this.setState(operation, 'available'); await this.finalizeRequest(operation.requestId); return; @@ -424,7 +434,13 @@ class BookRequestSearchManager { providerEditionId ); - if ((book?.statistics?.bookFileCount ?? 0) > 0) { + if ( + await hasRequestedEditionFiles( + readarr, + book, + operation.request.preferredEditionId + ) + ) { await this.setState(operation, 'available'); await this.finalizeRequest(operation.requestId); return; @@ -475,7 +491,13 @@ class BookRequestSearchManager { providerEditionId ); - if ((book?.statistics?.bookFileCount ?? 0) > 0) { + if ( + await hasRequestedEditionFiles( + readarr, + book, + operation.request.preferredEditionId + ) + ) { await this.setState(operation, 'available'); await this.finalizeRequest(operation.requestId); return; @@ -1039,6 +1061,19 @@ class BookRequestSearchManager { stage: RequestStatusStage.UNAVAILABLE | RequestStatusStage.FAILED; message: string; } + ): Promise { + return runWithRequestAdmission( + [getRequestMutationAdmissionKey(requestId)], + () => this.finalizeLockedRequest(requestId, detail) + ); + } + + private async finalizeLockedRequest( + requestId: number, + detail?: { + stage: RequestStatusStage.UNAVAILABLE | RequestStatusStage.FAILED; + message: string; + } ): Promise { const operations = await getRepository(BookRequestSearch).find({ where: { requestId }, @@ -1054,7 +1089,12 @@ class BookRequestSearchManager { where: { id: requestId }, relations: { media: true }, }); - if (!request) { + if ( + !request || + ![MediaRequestStatus.APPROVED, MediaRequestStatus.COMPLETED].includes( + request.status + ) + ) { await getRepository(BookRequestSearch).delete({ requestId }); return; } @@ -1063,6 +1103,27 @@ class BookRequestSearchManager { const unavailable = operations.find((item) => item.state === 'unavailable'); const terminalFailure = failed ?? unavailable; if (!terminalFailure) { + if ( + isProviderBookEdition(request.preferredEditionId) && + request.status === MediaRequestStatus.APPROVED + ) { + request.status = MediaRequestStatus.COMPLETED; + request.failureReason = null; + request.serviceTargets = request.serviceTargets?.map((target) => + operations.some( + (operation) => + target.serviceType === 'readarr' && + target.serverId === operation.serviceId && + target.format === operation.format + ) + ? { ...target, status: MediaStatus.AVAILABLE } + : target + ); + // The request admission lock is shared with cancellation. Save the full + // entity so the existing transactional notification outbox and status + // history subscribers observe this exact recording's completion. + await getRepository(MediaRequest).save(request); + } // Publish availability before removing the operation. Otherwise the // status projection loses its authoritative tracking state and falls // back to "Adding to library" until the next availability scan. diff --git a/server/lib/downloadRecovery.ts b/server/lib/downloadRecovery.ts index 33d4539de3..8477872ba2 100644 --- a/server/lib/downloadRecovery.ts +++ b/server/lib/downloadRecovery.ts @@ -286,15 +286,18 @@ class DownloadRecovery { const stateRepository = getRepository(DownloadRecoveryState); try { - await service.api.refreshMonitoredDownloads().catch((e) => { - logger.debug('Unable to refresh monitored downloads before recovery.', { - label: 'Download Recovery', - service: service.label, - server: service.server.name, - errorMessage: e instanceof Error ? e.message : String(e), - }); + await service.api.refreshMonitoredDownloads(); + } catch (e) { + logger.debug('Unable to refresh monitored downloads before recovery.', { + label: 'Download Recovery', + service: service.label, + server: service.server.name, + errorMessage: e instanceof Error ? e.message : String(e), }); + return; + } + try { const queueItems = await service.api.getQueue(); const uniqueQueueItems = deduplicateRecoveryQueue(queueItems); const activeDownloadIds = uniqueQueueItems.map((item) => item.downloadId); diff --git a/server/lib/downloadtracker.ts b/server/lib/downloadtracker.ts index f168462b28..2864cb27af 100644 --- a/server/lib/downloadtracker.ts +++ b/server/lib/downloadtracker.ts @@ -16,9 +16,12 @@ import { } from '@server/lib/serviceAdmission'; import type { DVRSettings, ReadarrSettings } from '@server/lib/settings'; import logger from '@server/logger'; -import { trackBackgroundTask } from '@server/utils/backgroundTasks'; import { mapWithConcurrency } from '@server/utils/concurrency'; -import { MAX_SERVARR_INSTANCES_PER_TYPE } from '@server/utils/servarrSettings'; +import { + DEFAULT_SERVARR_DOWNLOAD_QUEUE_SIZE, + MAX_SERVARR_INSTANCES_PER_TYPE, + validateServarrDownloadQueueSize, +} from '@server/utils/servarrSettings'; import { uniqWith } from 'lodash'; interface EpisodeNumberResult { @@ -101,6 +104,13 @@ export const DOWNLOAD_TRACKER_SERVER_CONCURRENCY = 5; type DownloadTrackerServerSettings = DVRSettings & Partial>; +const getServarrDownloadQueueSize = ( + server: Pick +): number => + validateServarrDownloadQueueSize( + server.downloadQueueSize ?? DEFAULT_SERVARR_DOWNLOAD_QUEUE_SIZE + ); + export const hasSameServarrDownloadAuthority = hasSameServarrServiceAuthority; export class DownloadTracker { @@ -117,8 +127,10 @@ export class DownloadTracker { private readarrServers: Record = {}; private kapowarrServers: Record = {}; private backissueServers: Record = {}; - private monitoredRefreshes = new Set(); + private monitoredRefreshes = new Map>(); private lastMonitoredRefresh = new Map(); + /** Keep stale snapshots visible without reading after a refresh that failed. */ + private failedMonitoredRefreshes = new Set(); private activeUpdate?: Promise; private runWithCurrentServarrDownloadServer< @@ -148,47 +160,55 @@ export class DownloadTracker { ); } - private refreshMonitoredDownloads( + private ensureMonitoredDownloadsRefreshed( key: string, serviceType: ServarrDownloadServiceType, server: DownloadTrackerServerSettings, refresh: () => Promise, serverName: string - ): void { + ): Promise { + const activeRefresh = this.monitoredRefreshes.get(key); + if (activeRefresh) { + return activeRefresh; + } + const lastRefresh = this.lastMonitoredRefresh.get(key) ?? 0; if (Date.now() - lastRefresh < DownloadTracker.monitoredRefreshCooldownMs) { - return; - } - - if (this.monitoredRefreshes.has(key)) { - return; + return Promise.resolve(!this.failedMonitoredRefreshes.has(key)); } - this.monitoredRefreshes.add(key); this.lastMonitoredRefresh.set(key, Date.now()); - trackBackgroundTask( - `refresh monitored downloads for ${serverName}`, - async () => { - try { - await this.runWithCurrentServarrDownloadServer( - serviceType, - server, - refresh - ); - } catch (e) { - logger.debug( - `Unable to refresh monitored downloads for server: ${serverName}`, - { - errorMessage: e instanceof Error ? e.message : String(e), - label: 'Download Tracker', - } - ); - } finally { - this.monitoredRefreshes.delete(key); + const refreshTask = this.runWithCurrentServarrDownloadServer( + serviceType, + server, + refresh + ) + .then(() => true) + .catch((e) => { + logger.debug( + `Unable to refresh monitored downloads for server: ${serverName}`, + { + errorMessage: e instanceof Error ? e.message : String(e), + label: 'Download Tracker', + } + ); + return false; + }) + .then((refreshed) => { + if (refreshed) { + this.failedMonitoredRefreshes.delete(key); + } else { + this.failedMonitoredRefreshes.add(key); } - } - ); + return refreshed; + }) + .finally(() => { + this.monitoredRefreshes.delete(key); + }); + + this.monitoredRefreshes.set(key, refreshTask); + return refreshTask; } private async loadHistory( @@ -443,7 +463,9 @@ export class DownloadTracker { // Remove duplicate servers const filteredServers = uniqWith( - settings.radarr.slice(0, MAX_SERVARR_INSTANCES_PER_TYPE), + settings.radarr + .filter((server) => server.syncEnabled) + .slice(0, MAX_SERVARR_INSTANCES_PER_TYPE), (radarrA, radarrB) => { return ( radarrA.hostname === radarrB.hostname && @@ -458,85 +480,98 @@ export class DownloadTracker { filteredServers, DOWNLOAD_TRACKER_SERVER_CONCURRENCY, async (server) => { - if (server.syncEnabled) { - const radarr = new RadarrAPI({ - apiKey: server.apiKey, - url: RadarrAPI.buildUrl(server, '/api/v3'), - }); + const radarr = new RadarrAPI({ + apiKey: server.apiKey, + url: RadarrAPI.buildUrl(server, '/api/v3'), + }); + const matchingServers = settings.radarr.filter( + (candidate) => + candidate.syncEnabled && + candidate.id !== server.id && + candidate.hostname === server.hostname && + candidate.port === server.port && + candidate.baseUrl === server.baseUrl + ); - try { - this.refreshMonitoredDownloads( + try { + const queueLimits = new Map( + [server, ...matchingServers].map((candidate) => [ + candidate.id, + getServarrDownloadQueueSize(candidate), + ]) + ); + const physicalQueueLimit = Math.max(...queueLimits.values()); + + if ( + !(await this.ensureMonitoredDownloadsRefreshed( `radarr:${server.id}`, 'radarr', server, () => radarr.refreshMonitoredDownloads(), server.name - ); - const [queueItems, historyItems] = await Promise.all([ - this.runWithCurrentServarrDownloadServer('radarr', server, () => - radarr.getQueue() - ), - this.loadHistory('radarr', server, radarr, server.name), - ]); - if (!queueItems) { - delete this.radarrServers[server.id]; - delete this.radarrHistory[server.id]; - return; - } + )) + ) { + return; + } + const [queueItems, historyItems] = await Promise.all([ + this.runWithCurrentServarrDownloadServer('radarr', server, () => + radarr.getQueue(physicalQueueLimit) + ), + this.loadHistory('radarr', server, radarr, server.name), + ]); + if (!queueItems) { + delete this.radarrServers[server.id]; + delete this.radarrHistory[server.id]; + return; + } + + const serverDownloads = queueItems.map((item) => ({ + externalId: item.movieId, + estimatedCompletionTime: new Date(item.estimatedCompletionTime), + mediaType: MediaType.MOVIE, + size: item.size, + sizeLeft: item.sizeleft, + status: item.status, + timeLeft: item.timeleft, + title: item.title, + downloadId: item.downloadId, + ...getQueueState(item), + })); + + for (const candidate of [server, ...matchingServers]) { + const queueLimit = queueLimits.get(candidate.id); + if (queueLimit === undefined) continue; + this.radarrServers[candidate.id] = serverDownloads.slice( + 0, + queueLimit + ); if (historyItems) { - this.radarrHistory[server.id] = historyItems; + this.radarrHistory[candidate.id] = historyItems; } - this.radarrServers[server.id] = queueItems.map((item) => ({ - externalId: item.movieId, - estimatedCompletionTime: new Date(item.estimatedCompletionTime), - mediaType: MediaType.MOVIE, - size: item.size, - sizeLeft: item.sizeleft, - status: item.status, - timeLeft: item.timeleft, - title: item.title, - downloadId: item.downloadId, - ...getQueueState(item), - })); + } - if (queueItems.length > 0) { - logger.debug( - `Found ${queueItems.length} item(s) in progress on Radarr server: ${server.name}`, - { label: 'Download Tracker' } - ); - } - } catch { - logger.error( - `Unable to get queue from Radarr server: ${server.name}`, - { - label: 'Download Tracker', - } + if (queueItems.length > 0) { + logger.debug( + `Found ${queueItems.length} item(s) in progress on Radarr server: ${server.name}`, + { label: 'Download Tracker' } ); } - - // Duplicate this data to matching servers - const matchingServers = settings.radarr.filter( - (rs) => - rs.hostname === server.hostname && - rs.port === server.port && - rs.baseUrl === server.baseUrl && - rs.id !== server.id - ); - if (matchingServers.length > 0) { logger.debug( `Matching download data to ${matchingServers.length} other Radarr server(s)`, { label: 'Download Tracker' } ); } - - matchingServers.forEach((ms) => { - if (ms.syncEnabled) { - this.radarrServers[ms.id] = this.radarrServers[server.id]; - this.radarrHistory[ms.id] = this.radarrHistory[server.id]; + } catch (error) { + logger.error( + `Unable to get queue from Radarr server: ${server.name}`, + { + errorMessage: + error instanceof Error ? error.message : String(error), + label: 'Download Tracker', } - }); + ); } } ); @@ -545,7 +580,9 @@ export class DownloadTracker { private async updateWhisparrDownloads() { const settings = getExternalRuntimeConfig(); const filteredServers = uniqWith( - settings.whisparr.slice(0, MAX_SERVARR_INSTANCES_PER_TYPE), + settings.whisparr + .filter((server) => server.syncEnabled) + .slice(0, MAX_SERVARR_INSTANCES_PER_TYPE), (left, right) => left.hostname === right.hostname && left.port === right.port && @@ -556,23 +593,42 @@ export class DownloadTracker { filteredServers, DOWNLOAD_TRACKER_SERVER_CONCURRENCY, async (server) => { - if (!server.syncEnabled) return; const whisparr = new WhisparrAPI({ apiKey: server.apiKey, url: WhisparrAPI.buildUrl(server, '/api/v3'), }); + const matchingServers = settings.whisparr.filter( + (candidate) => + candidate.syncEnabled && + candidate.id !== server.id && + candidate.hostname === server.hostname && + candidate.port === server.port && + candidate.baseUrl === server.baseUrl + ); try { - this.refreshMonitoredDownloads( - `whisparr:${server.id}`, - 'whisparr', - server, - () => whisparr.refreshMonitoredDownloads(), - server.name + const queueLimits = new Map( + [server, ...matchingServers].map((candidate) => [ + candidate.id, + getServarrDownloadQueueSize(candidate), + ]) ); + const physicalQueueLimit = Math.max(...queueLimits.values()); + + if ( + !(await this.ensureMonitoredDownloadsRefreshed( + `whisparr:${server.id}`, + 'whisparr', + server, + () => whisparr.refreshMonitoredDownloads(), + server.name + )) + ) { + return; + } const [queueItems, historyItems] = await Promise.all([ this.runWithCurrentServarrDownloadServer('whisparr', server, () => - whisparr.getQueue() + whisparr.getQueue(physicalQueueLimit) ), this.loadHistory('whisparr', server, whisparr, server.name), ]); @@ -581,8 +637,7 @@ export class DownloadTracker { delete this.whisparrHistory[server.id]; return; } - if (historyItems) this.whisparrHistory[server.id] = historyItems; - this.whisparrServers[server.id] = queueItems.flatMap((item) => + const serverDownloads = queueItems.flatMap((item) => item.movieId === undefined ? [] : [ @@ -602,6 +657,23 @@ export class DownloadTracker { }, ] ); + for (const candidate of [server, ...matchingServers]) { + const queueLimit = queueLimits.get(candidate.id); + if (queueLimit === undefined) continue; + this.whisparrServers[candidate.id] = serverDownloads.slice( + 0, + queueLimit + ); + if (historyItems) { + this.whisparrHistory[candidate.id] = historyItems; + } + } + if (matchingServers.length > 0) { + logger.debug( + `Matching download data to ${matchingServers.length} other Whisparr server(s)`, + { label: 'Download Tracker' } + ); + } } catch (error) { logger.error( `Unable to get queue from Whisparr server: ${server.name}`, @@ -611,20 +683,7 @@ export class DownloadTracker { label: 'Download Tracker', } ); - } - - for (const matching of settings.whisparr.filter( - (candidate) => - candidate.id !== server.id && - candidate.syncEnabled && - candidate.hostname === server.hostname && - candidate.port === server.port && - candidate.baseUrl === server.baseUrl - )) { - this.whisparrServers[matching.id] = - this.whisparrServers[server.id] ?? []; - this.whisparrHistory[matching.id] = - this.whisparrHistory[server.id] ?? []; + return; } } ); @@ -635,7 +694,9 @@ export class DownloadTracker { // Remove duplicate servers const filteredServers = uniqWith( - settings.sonarr.slice(0, MAX_SERVARR_INSTANCES_PER_TYPE), + settings.sonarr + .filter((server) => server.syncEnabled) + .slice(0, MAX_SERVARR_INSTANCES_PER_TYPE), (sonarrA, sonarrB) => { return ( sonarrA.hostname === sonarrB.hostname && @@ -650,86 +711,99 @@ export class DownloadTracker { filteredServers, DOWNLOAD_TRACKER_SERVER_CONCURRENCY, async (server) => { - if (server.syncEnabled) { - const sonarr = new SonarrAPI({ - apiKey: server.apiKey, - url: SonarrAPI.buildUrl(server, '/api/v3'), - }); + const sonarr = new SonarrAPI({ + apiKey: server.apiKey, + url: SonarrAPI.buildUrl(server, '/api/v3'), + }); + const matchingServers = settings.sonarr.filter( + (candidate) => + candidate.syncEnabled && + candidate.id !== server.id && + candidate.hostname === server.hostname && + candidate.port === server.port && + candidate.baseUrl === server.baseUrl + ); - try { - this.refreshMonitoredDownloads( + try { + const queueLimits = new Map( + [server, ...matchingServers].map((candidate) => [ + candidate.id, + getServarrDownloadQueueSize(candidate), + ]) + ); + const physicalQueueLimit = Math.max(...queueLimits.values()); + + if ( + !(await this.ensureMonitoredDownloadsRefreshed( `sonarr:${server.id}`, 'sonarr', server, () => sonarr.refreshMonitoredDownloads(), server.name - ); - const [queueItems, historyItems] = await Promise.all([ - this.runWithCurrentServarrDownloadServer('sonarr', server, () => - sonarr.getQueue() - ), - this.loadHistory('sonarr', server, sonarr, server.name), - ]); - if (!queueItems) { - delete this.sonarrServers[server.id]; - delete this.sonarrHistory[server.id]; - return; - } + )) + ) { + return; + } + + const [queueItems, historyItems] = await Promise.all([ + this.runWithCurrentServarrDownloadServer('sonarr', server, () => + sonarr.getQueue(physicalQueueLimit) + ), + this.loadHistory('sonarr', server, sonarr, server.name), + ]); + if (!queueItems) { + delete this.sonarrServers[server.id]; + delete this.sonarrHistory[server.id]; + return; + } + + const serverDownloads = queueItems.map((item) => ({ + externalId: item.seriesId, + estimatedCompletionTime: new Date(item.estimatedCompletionTime), + mediaType: MediaType.TV, + size: item.size, + sizeLeft: item.sizeleft, + status: item.status, + timeLeft: item.timeleft, + title: item.title, + episode: item.episode, + downloadId: item.downloadId, + ...getQueueState(item), + })); + for (const candidate of [server, ...matchingServers]) { + const queueLimit = queueLimits.get(candidate.id); + if (queueLimit === undefined) continue; + this.sonarrServers[candidate.id] = serverDownloads.slice( + 0, + queueLimit + ); if (historyItems) { - this.sonarrHistory[server.id] = historyItems; + this.sonarrHistory[candidate.id] = historyItems; } - this.sonarrServers[server.id] = queueItems.map((item) => ({ - externalId: item.seriesId, - estimatedCompletionTime: new Date(item.estimatedCompletionTime), - mediaType: MediaType.TV, - size: item.size, - sizeLeft: item.sizeleft, - status: item.status, - timeLeft: item.timeleft, - title: item.title, - episode: item.episode, - downloadId: item.downloadId, - ...getQueueState(item), - })); + } - if (queueItems.length > 0) { - logger.debug( - `Found ${queueItems.length} item(s) in progress on Sonarr server: ${server.name}`, - { label: 'Download Tracker' } - ); - } - } catch { - logger.error( - `Unable to get queue from Sonarr server: ${server.name}`, - { - label: 'Download Tracker', - } + if (queueItems.length > 0) { + logger.debug( + `Found ${queueItems.length} item(s) in progress on Sonarr server: ${server.name}`, + { label: 'Download Tracker' } ); } - - // Duplicate this data to matching servers - const matchingServers = settings.sonarr.filter( - (ss) => - ss.hostname === server.hostname && - ss.port === server.port && - ss.baseUrl === server.baseUrl && - ss.id !== server.id - ); - if (matchingServers.length > 0) { logger.debug( `Matching download data to ${matchingServers.length} other Sonarr server(s)`, { label: 'Download Tracker' } ); } - - matchingServers.forEach((ms) => { - if (ms.syncEnabled) { - this.sonarrServers[ms.id] = this.sonarrServers[server.id]; - this.sonarrHistory[ms.id] = this.sonarrHistory[server.id]; + } catch (error) { + logger.error( + `Unable to get queue from Sonarr server: ${server.name}`, + { + errorMessage: + error instanceof Error ? error.message : String(error), + label: 'Download Tracker', } - }); + ); } } ); @@ -739,7 +813,9 @@ export class DownloadTracker { const settings = getExternalRuntimeConfig(); const filteredServers = uniqWith( - settings.lidarr.slice(0, MAX_SERVARR_INSTANCES_PER_TYPE), + settings.lidarr + .filter((server) => server.syncEnabled) + .slice(0, MAX_SERVARR_INSTANCES_PER_TYPE), (lidarrA, lidarrB) => { return ( lidarrA.hostname === lidarrB.hostname && @@ -753,87 +829,100 @@ export class DownloadTracker { filteredServers, DOWNLOAD_TRACKER_SERVER_CONCURRENCY, async (server) => { - if (server.syncEnabled) { - const lidarr = new LidarrAPI({ - apiKey: server.apiKey, - url: LidarrAPI.buildUrl(server, '/api/v1'), - }); + const lidarr = new LidarrAPI({ + apiKey: server.apiKey, + url: LidarrAPI.buildUrl(server, '/api/v1'), + }); + const matchingServers = settings.lidarr.filter( + (candidate) => + candidate.syncEnabled && + candidate.id !== server.id && + candidate.hostname === server.hostname && + candidate.port === server.port && + candidate.baseUrl === server.baseUrl + ); - try { - this.refreshMonitoredDownloads( + try { + const queueLimits = new Map( + [server, ...matchingServers].map((candidate) => [ + candidate.id, + getServarrDownloadQueueSize(candidate), + ]) + ); + const physicalQueueLimit = Math.max(...queueLimits.values()); + + if ( + !(await this.ensureMonitoredDownloadsRefreshed( `lidarr:${server.id}`, 'lidarr', server, () => lidarr.refreshMonitoredDownloads(), server.name - ); - const [queueItems, historyItems] = await Promise.all([ - this.runWithCurrentServarrDownloadServer('lidarr', server, () => - lidarr.getQueue() - ), - this.loadHistory('lidarr', server, lidarr, server.name), - ]); - if (!queueItems) { - delete this.lidarrServers[server.id]; - delete this.lidarrHistory[server.id]; - return; - } + )) + ) { + return; + } + + const [queueItems, historyItems] = await Promise.all([ + this.runWithCurrentServarrDownloadServer('lidarr', server, () => + lidarr.getQueue(physicalQueueLimit) + ), + this.loadHistory('lidarr', server, lidarr, server.name), + ]); + if (!queueItems) { + delete this.lidarrServers[server.id]; + delete this.lidarrHistory[server.id]; + return; + } + + const serverDownloads = queueItems + .filter((item) => item.albumId !== undefined) + .map((item) => ({ + externalId: item.albumId, + estimatedCompletionTime: new Date(item.estimatedCompletionTime), + mediaType: MediaType.MUSIC, + size: item.size, + sizeLeft: item.sizeleft, + status: item.status, + timeLeft: item.timeleft, + title: item.title, + downloadId: item.downloadId, + ...getQueueState(item), + })); + for (const candidate of [server, ...matchingServers]) { + const queueLimit = queueLimits.get(candidate.id); + if (queueLimit === undefined) continue; + this.lidarrServers[candidate.id] = serverDownloads.slice( + 0, + queueLimit + ); if (historyItems) { - this.lidarrHistory[server.id] = historyItems; + this.lidarrHistory[candidate.id] = historyItems; } - this.lidarrServers[server.id] = queueItems - .filter((item) => item.albumId !== undefined) - .map((item) => ({ - externalId: item.albumId, - estimatedCompletionTime: new Date(item.estimatedCompletionTime), - mediaType: MediaType.MUSIC, - size: item.size, - sizeLeft: item.sizeleft, - status: item.status, - timeLeft: item.timeleft, - title: item.title, - downloadId: item.downloadId, - ...getQueueState(item), - })); + } - if (queueItems.length > 0) { - logger.debug( - `Found ${queueItems.length} item(s) in progress on Lidarr server: ${server.name}`, - { label: 'Download Tracker' } - ); - } - } catch (e) { - logger.error( - `Unable to get queue from Lidarr server: ${server.name}`, - { - errorMessage: e.message, - label: 'Download Tracker', - } + if (queueItems.length > 0) { + logger.debug( + `Found ${queueItems.length} item(s) in progress on Lidarr server: ${server.name}`, + { label: 'Download Tracker' } ); } - - const matchingServers = settings.lidarr.filter( - (ls) => - ls.hostname === server.hostname && - ls.port === server.port && - ls.baseUrl === server.baseUrl && - ls.id !== server.id - ); - if (matchingServers.length > 0) { logger.debug( `Matching download data to ${matchingServers.length} other Lidarr server(s)`, { label: 'Download Tracker' } ); } - - matchingServers.forEach((ms) => { - if (ms.syncEnabled) { - this.lidarrServers[ms.id] = this.lidarrServers[server.id]; - this.lidarrHistory[ms.id] = this.lidarrHistory[server.id]; + } catch (error) { + logger.error( + `Unable to get queue from Lidarr server: ${server.name}`, + { + errorMessage: + error instanceof Error ? error.message : String(error), + label: 'Download Tracker', } - }); + ); } } ); @@ -1000,7 +1089,7 @@ export class DownloadTracker { const filteredServers = uniqWith( settings.readarr - .filter((server) => server.backend !== 'bindery') + .filter((server) => server.backend !== 'bindery' && server.syncEnabled) .slice(0, MAX_SERVARR_INSTANCES_PER_TYPE), (readarrA, readarrB) => isMatchingReadarrDownloadServer(readarrA, readarrB) @@ -1010,91 +1099,102 @@ export class DownloadTracker { filteredServers, DOWNLOAD_TRACKER_SERVER_CONCURRENCY, async (server) => { - if (server.syncEnabled) { - const readarr = new ReadarrAPI({ - apiKey: server.apiKey, - url: ReadarrAPI.buildUrl(server, '/api/v1'), - mediaType: - server.serviceType === 'audiobook' ? 'audiobook' : 'ebook', - }); + const readarr = new ReadarrAPI({ + apiKey: server.apiKey, + url: ReadarrAPI.buildUrl(server, '/api/v1'), + mediaType: server.serviceType === 'audiobook' ? 'audiobook' : 'ebook', + }); + const matchingServers = settings.readarr.filter( + (candidate) => + candidate.backend !== 'bindery' && + candidate.syncEnabled && + candidate.id !== server.id && + isMatchingReadarrDownloadServer(candidate, server) + ); - try { - this.refreshMonitoredDownloads( + try { + const queueLimits = new Map( + [server, ...matchingServers].map((candidate) => [ + candidate.id, + getServarrDownloadQueueSize(candidate), + ]) + ); + const physicalQueueLimit = Math.max(...queueLimits.values()); + + if ( + !(await this.ensureMonitoredDownloadsRefreshed( `readarr:${server.id}`, 'readarr', server, () => readarr.refreshMonitoredDownloads(), server.name - ); - const queueItems = await this.runWithCurrentServarrDownloadServer( - 'readarr', - server, - () => readarr.getQueue() - ); - if (!queueItems) { - delete this.readarrServers[server.id]; - return; - } + )) + ) { + return; + } - this.readarrServers[server.id] = queueItems - .map((item) => ({ - item, - bookId: item.bookId ?? item.book?.id, - })) - .filter( - ( - queueItem - ): queueItem is typeof queueItem & { bookId: number } => - queueItem.bookId !== undefined - ) - .map(({ item, bookId }) => ({ - externalId: bookId, - estimatedCompletionTime: new Date(item.estimatedCompletionTime), - mediaType: MediaType.BOOK, - size: item.size, - sizeLeft: item.sizeleft, - status: item.status, - timeLeft: item.timeleft, - title: item.title, - downloadId: item.downloadId, - ...getQueueState(item), - })); + const queueItems = await this.runWithCurrentServarrDownloadServer( + 'readarr', + server, + () => readarr.getQueue(physicalQueueLimit) + ); + if (!queueItems) { + delete this.readarrServers[server.id]; + return; + } - if (queueItems.length > 0) { - logger.debug( - `Found ${queueItems.length} item(s) in progress on Bookshelf server: ${server.name}`, - { label: 'Download Tracker' } - ); - } - } catch (e) { - logger.error( - `Unable to get queue from Bookshelf server: ${server.name}`, - { - errorMessage: e.message, - label: 'Download Tracker', - } + const serverDownloads = queueItems + .map((item) => ({ + item, + bookId: item.bookId ?? item.book?.id, + })) + .filter( + (queueItem): queueItem is typeof queueItem & { bookId: number } => + queueItem.bookId !== undefined + ) + .map(({ item, bookId }) => ({ + externalId: bookId, + estimatedCompletionTime: new Date(item.estimatedCompletionTime), + mediaType: MediaType.BOOK, + size: item.size, + sizeLeft: item.sizeleft, + status: item.status, + timeLeft: item.timeleft, + title: item.title, + downloadId: item.downloadId, + ...getQueueState(item), + })); + + for (const candidate of [server, ...matchingServers]) { + const queueLimit = queueLimits.get(candidate.id); + if (queueLimit === undefined) continue; + this.readarrServers[candidate.id] = serverDownloads.slice( + 0, + queueLimit ); } - const matchingServers = settings.readarr.filter( - (rs) => - rs.backend !== 'bindery' && - isMatchingReadarrDownloadServer(rs, server) && - rs.id !== server.id - ); - + if (queueItems.length > 0) { + logger.debug( + `Found ${queueItems.length} item(s) in progress on Bookshelf server: ${server.name}`, + { label: 'Download Tracker' } + ); + } if (matchingServers.length > 0) { logger.debug( `Matching download data to ${matchingServers.length} other Bookshelf server(s)`, { label: 'Download Tracker' } ); } - - matchingServers.forEach((ms) => { - if (ms.syncEnabled) { - this.readarrServers[ms.id] = this.readarrServers[server.id]; + } catch (error) { + logger.error( + `Unable to get queue from Bookshelf server: ${server.name}`, + { + errorMessage: + error instanceof Error ? error.message : String(error), + label: 'Download Tracker', } - }); + ); } } ); diff --git a/server/lib/editionCompare/availability.ts b/server/lib/editionCompare/availability.ts new file mode 100644 index 0000000000..85cd232ce2 --- /dev/null +++ b/server/lib/editionCompare/availability.ts @@ -0,0 +1,45 @@ +import type ReadarrAPI from '@server/api/servarr/readarr'; +import type { + ChaptarrEditionCard, + ReadarrBook, + ReadarrEdition, +} from '@server/api/servarr/readarr'; + +/** Readarr's BookFileCount joins only monitored editions. Multiple monitored + * editions require the companion's exact edition catalog; totals cannot prove + * which performance exists. */ +export const hasExactEditionFiles = ( + preferredEditionId: string, + catalog: Pick[], + editions: Pick[], + bookFileCount: number +): boolean => { + if (catalog.length) + return catalog.some( + (item) => + item.foreignEditionId === preferredEditionId && item.owned === true + ); + const monitored = editions.filter((item) => item.monitored); + return ( + bookFileCount > 0 && + monitored.length === 1 && + monitored[0].foreignEditionId === preferredEditionId + ); +}; + +export const hasRequestedEditionFiles = async ( + api: Pick, + book: ReadarrBook | null | undefined, + editionId?: string | null +): Promise => { + if (!book) return false; + if (!editionId) return (book.statistics?.bookFileCount ?? 0) > 0; + const catalog = await api.getEditionCatalog(book.id); + const editions = catalog.length ? [] : await api.getEditions(book.id); + return hasExactEditionFiles( + editionId, + catalog, + editions, + book.statistics?.bookFileCount ?? 0 + ); +}; diff --git a/server/lib/editionCompare/cards.test.ts b/server/lib/editionCompare/cards.test.ts new file mode 100644 index 0000000000..cc1134a082 --- /dev/null +++ b/server/lib/editionCompare/cards.test.ts @@ -0,0 +1,127 @@ +import { + initialNarration, + recommendedNarration, +} from '@app/utils/narrationSelection'; +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { hasExactEditionFiles, hasRequestedEditionFiles } from './availability'; +import { cardFromCatalog, cardFromLookup, normalizeSampleUrl } from './cards'; + +const card = (id: string, extra = {}) => + cardFromLookup( + { + foreignEditionId: id, + title: 'Book', + monitored: false, + narrators: ['Narrator'], + ...extra, + }, + 'audiobook' + ); + +test('preserves supplied recording metadata without inventing samples or labels', () => { + const item = card('e2', { + audioSeconds: 7500, + language: 'eng', + editionInfo: '10th anniversary', + previewUrl: 'https://cdn.example/audio.mp3', + subtitle: 'Unabridged', + }); + assert.equal(item.durationSeconds, 7500); + assert.equal(item.editionLabel, '10th anniversary'); + assert.equal(item.sampleUrl, 'https://cdn.example/audio.mp3'); + assert.equal(card('unknown').sampleUrl, undefined); + assert.equal(card('unknown').editionLabel, undefined); +}); + +test('sample URLs exclude executable, insecure, credential and malformed URLs', () => { + for (const url of [ + 'javascript:alert(1)', + 'data:audio/mp3,a', + 'http://host/audio', + '//host/audio', + 'https://user:secret@host/audio', + 'https://host/\nfile', + 'https://host/with space', + ]) + assert.equal(normalizeSampleUrl(url), undefined); + assert.equal( + normalizeSampleUrl('https://cdn.example/sample.mp3'), + 'https://cdn.example/sample.mp3' + ); +}); + +test('only a missing unabridged recording in the viewer language is recommended', () => { + const records = [ + card('owned', { language: 'eng', subtitle: 'Unabridged' }), + card('foreign', { language: 'deu', subtitle: 'Unabridged' }), + card('preferred', { language: 'eng', subtitle: 'Unabridged' }), + ]; + records[0].owned = true; + assert.equal(recommendedNarration(records, 'en-CA')?.id, 'preferred'); + assert.equal(recommendedNarration(records, 'ja'), undefined); + assert.equal(initialNarration(records, 'ja')?.id, 'foreign'); +}); + +test('another owned edition never satisfies the chosen narration', () => { + const catalog = [ + { foreignEditionId: 'e1', owned: true }, + { foreignEditionId: 'e2', owned: false }, + ]; + assert.equal(hasExactEditionFiles('e2', catalog, [], 7), false); + assert.equal(hasExactEditionFiles('e1', catalog, [], 7), true); + assert.equal(hasExactEditionFiles('unknown', catalog, [], 7), false); +}); + +test('legacy file totals prove ownership only for exactly one matching monitored edition', () => { + const editions = [ + { foreignEditionId: 'e1', monitored: true }, + { foreignEditionId: 'e2', monitored: false }, + ]; + assert.equal(hasExactEditionFiles('e1', [], editions, 1), true); + assert.equal(hasExactEditionFiles('e2', [], editions, 1), false); + editions[1].monitored = true; + assert.equal(hasExactEditionFiles('e1', [], editions, 1), false); + assert.equal(hasExactEditionFiles('e1', [], editions, 0), false); +}); + +test('reconciliation uses exact companion ownership and preserves ordinary requests', async () => { + const calls: string[] = []; + const api = { + getEditionCatalog: async () => { + calls.push('catalog'); + return [{ foreignEditionId: 'e2', owned: false }] as never[]; + }, + getEditions: async () => { + calls.push('editions'); + return []; + }, + }; + const book = { + id: 4, + title: 'Book', + foreignBookId: 'work1', + statistics: { bookFileCount: 2 }, + }; + assert.equal(await hasRequestedEditionFiles(api, book, 'e2'), false); + assert.deepEqual(calls, ['catalog']); + assert.equal(await hasRequestedEditionFiles(api, book), true); + assert.equal(await hasRequestedEditionFiles(api, undefined, 'e2'), false); +}); + +test('a catalog row without a provider identity is not requestable', () => { + const card = cardFromCatalog( + { + editionId: 42, + title: 'A book', + isEbook: false, + narrators: [], + monitored: false, + owned: false, + production: 'unknown', + abridged: 'unknown', + }, + 'audiobook' + ); + assert.equal(card.requestable, false); +}); diff --git a/server/lib/editionCompare/cards.ts b/server/lib/editionCompare/cards.ts new file mode 100644 index 0000000000..5c4845cb02 --- /dev/null +++ b/server/lib/editionCompare/cards.ts @@ -0,0 +1,186 @@ +import type { + ChaptarrEditionCard, + ReadarrBookLookupResult, +} from '@server/api/servarr/readarr'; + +/** Samples are public HTTPS media; never interpret executable or credential URLs. */ +export const normalizeSampleUrl = (value: unknown): string | undefined => { + if ( + typeof value !== 'string' || + value.length > 2048 || + Array.from(value).some( + (character) => character === '\\' || character.codePointAt(0)! <= 0x20 + ) + ) + return undefined; + try { + const url = new URL(value); + return url.protocol === 'https:' && !url.username && !url.password + ? url.href + : undefined; + } catch { + return undefined; + } +}; + +export type BookFormat = 'ebook' | 'audiobook'; + +/** A materially different edition or performance, in comparable terms. */ +export interface EditionCard { + /** Provider edition id used as the request's preferredEditionId. */ + id: string; + /** Companion-local edition id, when the library already knows it. */ + localEditionId?: number; + /** False when the catalog lacks the provider identity needed for a request. */ + requestable?: boolean; + title: string; + format: BookFormat; + language?: string; + narrators: string[]; + production: 'solo' | 'full-cast' | 'unknown'; + abridged: 'abridged' | 'unabridged' | 'unknown'; + durationSeconds?: number; + publisher?: string; + releaseDate?: string; + imageUrl?: string; + /** Optional preview explicitly supplied by the catalog. */ + sampleUrl?: string; + editionLabel?: string; + /** The edition the library currently tracks. */ + selected: boolean; + /** A file for this exact edition exists. */ + owned: boolean; + /** Fields the catalog did not provide, so the UI says "unknown". */ + unknownFields: string[]; +} + +export interface EditionComparison { + format: BookFormat; + editions: EditionCard[]; + /** True when the companion can track a second performance next to the first. */ + supportsAlongside: boolean; + source: 'library' | 'lookup' | 'none'; +} + +const FULL_CAST = /full[-\s]?cast|dramati[sz]ed|multi[-\s]?cast|ensemble/i; +const ABRIDGED = /\babridged\b/i; +const UNABRIDGED = /\bunabridged\b/i; + +export const classifyProduction = ( + narrators: string[], + ...hints: (string | undefined)[] +): EditionCard['production'] => { + if (hints.some((hint) => hint && FULL_CAST.test(hint))) return 'full-cast'; + if (narrators.length === 1) return 'solo'; + if (narrators.length >= 6) return 'full-cast'; + return 'unknown'; +}; + +export const classifyAbridgement = ( + ...hints: (string | undefined)[] +): EditionCard['abridged'] => { + const text = hints.filter(Boolean).join(' '); + if (UNABRIDGED.test(text)) return 'unabridged'; + if (ABRIDGED.test(text)) return 'abridged'; + return 'unknown'; +}; + +const unknownFieldsFor = (card: Omit) => { + const unknown: string[] = []; + if (card.format === 'audiobook') { + if (!card.narrators.length) unknown.push('narrators'); + if (card.production === 'unknown') unknown.push('production'); + if (card.abridged === 'unknown') unknown.push('abridged'); + if (!card.durationSeconds) unknown.push('duration'); + } + if (!card.language) unknown.push('language'); + if (!card.releaseDate) unknown.push('releaseDate'); + return unknown; +}; + +const withUnknown = ( + card: Omit +): EditionCard => ({ + ...card, + unknownFields: unknownFieldsFor(card), +}); + +export const cardFromCatalog = ( + edition: ChaptarrEditionCard, + format: BookFormat +): EditionCard => + withUnknown({ + id: edition.foreignEditionId ?? String(edition.editionId), + localEditionId: edition.editionId, + requestable: Boolean(edition.foreignEditionId?.trim()), + title: edition.title, + format, + language: edition.language, + narrators: edition.narrators ?? [], + production: edition.production ?? 'unknown', + abridged: edition.abridged ?? 'unknown', + durationSeconds: edition.durationSeconds, + publisher: edition.publisher, + releaseDate: edition.releaseDate, + imageUrl: edition.imageUrl, + sampleUrl: normalizeSampleUrl(edition.sampleUrl), + editionLabel: edition.editionLabel?.trim().slice(0, 160) || undefined, + selected: edition.monitored, + owned: edition.owned, + }); + +export type LookupEdition = NonNullable< + ReadarrBookLookupResult['editions'] +>[number] & + Partial<{ + title: string; + language: string; + narrators: string[]; + narratorNames: string[]; + durationSeconds: number; + publisher: string; + releaseDate: string; + sampleUrl: string; + previewUrl: string; + subtitle: string; + disambiguation: string; + editionInfo: string; + format: string; + isEbook: boolean; + images: { url?: string; remoteUrl?: string }[]; + }>; + +export const cardFromLookup = ( + edition: LookupEdition, + format: BookFormat +): EditionCard => { + const narrators = edition.narratorNames?.length + ? edition.narratorNames + : (edition.narrators ?? []); + const hints = [ + edition.title, + edition.subtitle, + edition.disambiguation, + edition.editionInfo, + ]; + return withUnknown({ + id: edition.foreignEditionId, + title: edition.title ?? '', + format, + language: edition.language, + narrators, + production: classifyProduction(narrators, ...hints), + abridged: classifyAbridgement(...hints), + durationSeconds: + edition.durationSeconds ?? + edition.audioSeconds ?? + edition.audiobookDuration, + publisher: edition.publisher, + releaseDate: edition.releaseDate, + sampleUrl: normalizeSampleUrl(edition.sampleUrl ?? edition.previewUrl), + editionLabel: edition.editionInfo?.trim().slice(0, 160) || undefined, + imageUrl: edition.images?.[0]?.remoteUrl ?? edition.images?.[0]?.url, + selected: edition.monitored === true, + owned: false, + }); +}; diff --git a/server/lib/editionCompare/index.ts b/server/lib/editionCompare/index.ts index a174e681bc..e3c4d542c0 100644 --- a/server/lib/editionCompare/index.ts +++ b/server/lib/editionCompare/index.ts @@ -1,161 +1,23 @@ -import type { - ChaptarrEditionCard, - ChaptarrNarratorMatrix, - ReadarrBookLookupResult, -} from '@server/api/servarr/readarr'; +import type { ChaptarrNarratorMatrix } from '@server/api/servarr/readarr'; import ReadarrAPI from '@server/api/servarr/readarr'; import { MediaType } from '@server/constants/media'; import { getRepository } from '@server/datasource'; import Media from '@server/entity/Media'; +import { getExternalRuntimeConfig } from '@server/lib/externalRuntimeConfig'; import { titleSimilarity } from '@server/lib/resolve/match'; import type { ReadarrSettings } from '@server/lib/settings'; -import { getSettings } from '@server/lib/settings'; +import { parseBookshelfBookId } from '@server/utils/bookshelfCatalog'; import { readarrServiceSupportsFormat } from '@server/utils/readarrService'; +import { hasExactEditionFiles } from './availability'; +import { + cardFromCatalog, + cardFromLookup, + type BookFormat, + type EditionComparison, + type LookupEdition, +} from './cards'; -export type BookFormat = 'ebook' | 'audiobook'; - -/** A materially different edition or performance, in comparable terms. */ -export interface EditionCard { - /** Provider edition id used as the request's preferredEditionId. */ - id: string; - /** Companion-local edition id, when the library already knows it. */ - localEditionId?: number; - title: string; - format: BookFormat; - language?: string; - narrators: string[]; - production: 'solo' | 'full-cast' | 'unknown'; - abridged: 'abridged' | 'unabridged' | 'unknown'; - durationSeconds?: number; - publisher?: string; - releaseDate?: string; - imageUrl?: string; - /** The edition the library currently tracks. */ - selected: boolean; - /** A file for this exact edition exists. */ - owned: boolean; - /** Fields the catalog did not provide, so the UI says "unknown". */ - unknownFields: string[]; -} - -export interface EditionComparison { - format: BookFormat; - editions: EditionCard[]; - /** True when the companion can track a second performance next to the first. */ - supportsAlongside: boolean; - source: 'library' | 'lookup' | 'none'; -} - -const FULL_CAST = /full[-\s]?cast|dramati[sz]ed|multi[-\s]?cast|ensemble/i; -const ABRIDGED = /\babridged\b/i; -const UNABRIDGED = /\bunabridged\b/i; - -export const classifyProduction = ( - narrators: string[], - ...hints: (string | undefined)[] -): EditionCard['production'] => { - if (hints.some((hint) => hint && FULL_CAST.test(hint))) return 'full-cast'; - if (narrators.length === 1) return 'solo'; - if (narrators.length >= 6) return 'full-cast'; - return 'unknown'; -}; - -export const classifyAbridgement = ( - ...hints: (string | undefined)[] -): EditionCard['abridged'] => { - const text = hints.filter(Boolean).join(' '); - if (UNABRIDGED.test(text)) return 'unabridged'; - if (ABRIDGED.test(text)) return 'abridged'; - return 'unknown'; -}; - -const unknownFieldsFor = (card: Omit) => { - const unknown: string[] = []; - if (card.format === 'audiobook') { - if (!card.narrators.length) unknown.push('narrators'); - if (card.production === 'unknown') unknown.push('production'); - if (card.abridged === 'unknown') unknown.push('abridged'); - if (!card.durationSeconds) unknown.push('duration'); - } - if (!card.language) unknown.push('language'); - if (!card.releaseDate) unknown.push('releaseDate'); - return unknown; -}; - -const withUnknown = ( - card: Omit -): EditionCard => ({ - ...card, - unknownFields: unknownFieldsFor(card), -}); - -export const cardFromCatalog = ( - edition: ChaptarrEditionCard, - format: BookFormat -): EditionCard => - withUnknown({ - id: edition.foreignEditionId ?? String(edition.editionId), - localEditionId: edition.editionId, - title: edition.title, - format, - language: edition.language, - narrators: edition.narrators ?? [], - production: edition.production ?? 'unknown', - abridged: edition.abridged ?? 'unknown', - durationSeconds: edition.durationSeconds, - publisher: edition.publisher, - releaseDate: edition.releaseDate, - imageUrl: edition.imageUrl, - selected: edition.monitored, - owned: edition.owned, - }); - -type LookupEdition = NonNullable[number] & - Partial<{ - title: string; - language: string; - narrators: string[]; - narratorNames: string[]; - durationSeconds: number; - publisher: string; - releaseDate: string; - subtitle: string; - disambiguation: string; - editionInfo: string; - format: string; - isEbook: boolean; - images: { url?: string; remoteUrl?: string }[]; - }>; - -export const cardFromLookup = ( - edition: LookupEdition, - format: BookFormat -): EditionCard => { - const narrators = edition.narratorNames?.length - ? edition.narratorNames - : (edition.narrators ?? []); - const hints = [ - edition.title, - edition.subtitle, - edition.disambiguation, - edition.editionInfo, - ]; - return withUnknown({ - id: edition.foreignEditionId, - title: edition.title ?? '', - format, - language: edition.language, - narrators, - production: classifyProduction(narrators, ...hints), - abridged: classifyAbridgement(...hints), - durationSeconds: edition.durationSeconds, - publisher: edition.publisher, - releaseDate: edition.releaseDate, - imageUrl: edition.images?.[0]?.remoteUrl ?? edition.images?.[0]?.url, - selected: edition.monitored === true, - owned: false, - }); -}; +export * from './cards'; export interface LibraryBookService { server: ReadarrSettings; @@ -186,8 +48,12 @@ export const getLibraryBookService = async ( ) { return undefined; } - const server = getSettings().readarr.find( - (entry) => entry.id === serviceId && entry.backend !== 'bindery' + const servers = getExternalRuntimeConfig().readarr; + const server = servers.find( + (entry) => + entry.id === serviceId && + entry.backend !== 'bindery' && + readarrServiceSupportsFormat(entry, format) ); if (!server) return undefined; return { @@ -202,8 +68,56 @@ export const getLibraryBookService = async ( }; }; +const compareLibraryEditions = async ( + api: ReadarrAPI, + bookId: number, + format: BookFormat +): Promise => { + const catalog = await api.getEditionCatalog(bookId); + if (catalog.length) { + return { + format, + editions: catalog + .filter((edition) => edition.isEbook === (format === 'ebook')) + .map((edition) => cardFromCatalog(edition, format)), + supportsAlongside: api.supportsWantedEditionVariants(), + source: 'library', + }; + } + const [book, editions] = await Promise.all([ + api.getBookIfExists(bookId), + api.getEditions(bookId), + ]); + if (editions.length) + return { + format, + supportsAlongside: false, + source: 'library', + editions: (editions as LookupEdition[]) + .filter( + (edition) => + edition.isEbook === undefined || + edition.isEbook === (format === 'ebook') + ) + .map((edition) => ({ + ...cardFromLookup(edition, format), + owned: hasExactEditionFiles( + edition.foreignEditionId, + [], + editions, + book?.statistics?.bookFileCount ?? 0 + ), + })), + }; + return undefined; +}; + export const compareBookEditions = async (options: { mediaId?: number; + bookId?: string; + /** Configured destination used for edition lookup and exact ownership. */ + serverId?: number; + author?: string; format: BookFormat; /** Lookup term (title or ISBN) for books not yet in the library. */ term?: string; @@ -216,45 +130,80 @@ export const compareBookEditions = async (options: { options.mediaId, options.format ); - if (service) { - const catalog = await service.api.getEditionCatalog(service.bookId); - if (catalog.length) { - return { - format: options.format, - editions: catalog.map((edition) => - cardFromCatalog(edition, options.format) - ), - supportsAlongside: service.api.supportsWantedEditionVariants(), - source: 'library', - }; - } + if ( + service && + (options.serverId === undefined || service.server.id === options.serverId) + ) { + const comparison = await compareLibraryEditions( + service.api, + service.bookId, + options.format + ); + if (comparison) return comparison; } } - const server = getSettings().readarr.find( + const identity = options.bookId + ? parseBookshelfBookId(options.bookId) + : undefined; + const servers = getExternalRuntimeConfig().readarr; + const wantedServer = options.serverId ?? identity?.serviceId; + const candidates = servers.filter( (entry) => entry.backend !== 'bindery' && + (wantedServer === undefined || entry.id === wantedServer) && readarrServiceSupportsFormat(entry, options.format) ); - if (server && options.term) { + const server = + wantedServer === undefined + ? (candidates.find((entry) => entry.isDefault) ?? candidates[0]) + : candidates[0]; + if ( + server && + options.term && + (options.title || identity || options.foreignBookId) + ) { const api = new ReadarrAPI({ apiKey: server.apiKey, url: ReadarrAPI.buildUrl(server, '/api/v1'), mediaType: options.format, }); const results = await api.lookupBook(options.term).catch(() => []); - const match = options.foreignBookId - ? results.find((entry) => entry.foreignBookId === options.foreignBookId) - : results.find( + const foreignBookId = options.foreignBookId ?? identity?.foreignBookId; + const matches = foreignBookId + ? results.filter((entry) => entry.foreignBookId === foreignBookId) + : results.filter( (entry) => - !options.title || titleSimilarity(options.title, entry.title) >= 0.8 + (!options.title || + titleSimilarity(options.title, entry.title) >= 0.95) && + (!options.author || + (entry.author?.authorName && + titleSimilarity(options.author, entry.author.authorName) >= + 0.95)) + ); + const match = matches.length === 1 ? matches[0] : undefined; + if (match?.id && match.id > 0) { + const localBook = await api.getBookIfExists(match.id); + if (localBook?.foreignBookId === match.foreignBookId) { + const comparison = await compareLibraryEditions( + api, + match.id, + options.format ); + if (comparison) return comparison; + } + } const editions = (match?.editions ?? []) as LookupEdition[]; if (editions.length) { return { format: options.format, editions: editions - .filter((edition) => !!edition.foreignEditionId) + .filter( + (edition) => + !!edition.foreignEditionId && + (edition.isEbook === undefined || + edition.isEbook === (options.format === 'ebook')) + ) .map((edition) => cardFromLookup(edition, options.format)), supportsAlongside: api.supportsWantedEditionVariants(), source: 'lookup', diff --git a/server/lib/editionCompare/lookup.vitest.test.ts b/server/lib/editionCompare/lookup.vitest.test.ts new file mode 100644 index 0000000000..d175abea29 --- /dev/null +++ b/server/lib/editionCompare/lookup.vitest.test.ts @@ -0,0 +1,191 @@ +import ReadarrAPI from '@server/api/servarr/readarr'; +import { getRepository } from '@server/datasource'; +import Media from '@server/entity/Media'; +import { getSettings, type ReadarrSettings } from '@server/lib/settings'; +import { makeBookshelfBookId } from '@server/utils/bookshelfCatalog'; +import { afterEach, beforeEach, expect, test, vi } from 'vitest'; +import { compareBookEditions } from './index'; +const fixture = vi.hoisted(() => ({ + lookup: vi.fn(), + catalog: vi.fn(), + editions: vi.fn(), + book: vi.fn(), + media: vi.fn(), +})); +beforeEach(() => { + getSettings().readarr = [ + { + id: 1, + hostname: 'fixture.local', + port: 8787, + apiKey: 'test', + isDefault: true, + serviceType: 'audiobook', + } as ReadarrSettings, + ]; + vi.spyOn(ReadarrAPI.prototype, 'lookupBook').mockImplementation( + fixture.lookup + ); + vi.spyOn(ReadarrAPI.prototype, 'getEditionCatalog').mockImplementation( + fixture.catalog + ); + vi.spyOn(ReadarrAPI.prototype, 'getEditions').mockImplementation( + fixture.editions + ); + vi.spyOn(ReadarrAPI.prototype, 'getBookIfExists').mockImplementation( + fixture.book + ); + vi.spyOn( + ReadarrAPI.prototype, + 'supportsWantedEditionVariants' + ).mockReturnValue(true); + vi.spyOn(getRepository(Media), 'findOne').mockImplementation(fixture.media); + fixture.lookup.mockReset().mockResolvedValue([ + { + foreignBookId: 'work-1', + title: 'A Book', + author: { authorName: 'Author' }, + editions: [ + { + foreignEditionId: 'audio-1', + isEbook: false, + narrators: ['Voice'], + monitored: true, + }, + ], + }, + ]); + fixture.media.mockReset().mockResolvedValue(null); + fixture.catalog.mockReset().mockResolvedValue([]); + fixture.editions.mockReset().mockResolvedValue([]); + fixture.book.mockReset().mockResolvedValue(undefined); +}); +afterEach(() => { + vi.restoreAllMocks(); + getSettings().readarr = []; +}); + +test('a known work uses provider identity, not the first similarly titled search result', async () => { + fixture.lookup.mockResolvedValue([ + { + foreignBookId: 'wrong', + title: 'A Book', + editions: [{ foreignEditionId: 'wrong-edition' }], + }, + ...(await fixture.lookup()), + ]); + const result = await compareBookEditions({ + bookId: makeBookshelfBookId(1, 'work-1'), + format: 'audiobook', + term: 'A Book', + }); + expect(result.editions.map((item) => item.id)).toEqual(['audio-1']); +}); +test('unknown work lookups require a matching title and supplied author', async () => { + const base = { + format: 'audiobook' as const, + term: 'A Book', + title: 'A Book', + author: 'Author', + }; + expect((await compareBookEditions(base)).editions).toHaveLength(1); + expect( + (await compareBookEditions({ ...base, author: 'Someone Else' })).editions + ).toHaveLength(0); + expect( + (await compareBookEditions({ ...base, title: 'Another Book' })).editions + ).toHaveLength(0); +}); +test('does not invent a recording when a requested destination or format cannot resolve it', async () => { + expect( + ( + await compareBookEditions({ + serverId: 99, + format: 'audiobook', + term: 'A Book', + title: 'A Book', + }) + ).editions + ).toHaveLength(0); + expect( + ( + await compareBookEditions({ + bookId: makeBookshelfBookId(1, 'work-1'), + format: 'ebook', + term: 'A Book', + }) + ).editions + ).toHaveLength(0); +}); +test('legacy ownership is specific to the single monitored edition', async () => { + fixture.media.mockResolvedValue({ + audiobookServiceId: 1, + audiobookExternalServiceId: 21, + }); + fixture.book.mockResolvedValue({ id: 21, statistics: { bookFileCount: 1 } }); + fixture.editions.mockResolvedValue([ + { foreignEditionId: 'owned', isEbook: false, monitored: true }, + { foreignEditionId: 'missing', isEbook: false, monitored: false }, + ]); + const result = await compareBookEditions({ mediaId: 7, format: 'audiobook' }); + expect(result.editions.map((item) => [item.id, item.owned])).toEqual([ + ['owned', true], + ['missing', false], + ]); + expect(result.supportsAlongside).toBe(false); +}); + +test('explicit destination zero resolves ownership on that destination', async () => { + getSettings().readarr.push({ ...getSettings().readarr[0], id: 0 }); + fixture.media.mockResolvedValue({ + audiobookServiceId: 1, + audiobookExternalServiceId: 21, + }); + fixture.lookup.mockResolvedValue([ + { id: 42, foreignBookId: 'work-1', title: 'A Book' }, + ]); + fixture.book.mockResolvedValue({ id: 42, foreignBookId: 'work-1' }); + fixture.catalog.mockResolvedValue([ + { + editionId: 2, + foreignEditionId: 'owned', + isEbook: false, + owned: true, + narrators: [], + }, + ]); + const buildUrl = vi.spyOn(ReadarrAPI, 'buildUrl'); + const result = await compareBookEditions({ + mediaId: 7, + bookId: makeBookshelfBookId(1, 'work-1'), + serverId: 0, + format: 'audiobook', + term: 'A Book', + }); + expect(buildUrl.mock.calls.at(-1)?.[0].id).toBe(0); + expect(fixture.catalog).toHaveBeenCalledWith(42); + expect(result.editions[0].owned).toBe(true); +}); + +test('uses the default destination and rejects ambiguous title matches', async () => { + getSettings().readarr.unshift({ + ...getSettings().readarr[0], + id: 9, + isDefault: false, + }); + const buildUrl = vi.spyOn(ReadarrAPI, 'buildUrl'); + const query = { + format: 'audiobook' as const, + title: 'A Book', + term: 'A Book', + }; + expect((await compareBookEditions(query)).editions).toHaveLength(1); + expect(buildUrl.mock.calls.at(-1)?.[0].id).toBe(1); + + const [first] = await fixture.lookup(); + fixture.lookup.mockResolvedValue([ + first, + { ...first, foreignBookId: 'different-work' }, + ]); + expect((await compareBookEditions(query)).editions).toHaveLength(0); +}); diff --git a/server/lib/episodeAvailability.test.ts b/server/lib/episodeAvailability.test.ts new file mode 100644 index 0000000000..7df6d4fde5 --- /dev/null +++ b/server/lib/episodeAvailability.test.ts @@ -0,0 +1,170 @@ +import { MediaType } from '@server/constants/media'; +import { MediaServerType } from '@server/constants/server'; +import { getRepository } from '@server/datasource'; +import EpisodeAvailability from '@server/entity/EpisodeAvailability'; +import Media from '@server/entity/Media'; +import Season from '@server/entity/Season'; +import { + clearSonarrEpisodeAvailabilityForService, + getActiveEpisodeAvailabilitySources, + getEpisodeAvailability, + getSonarrEpisodeAvailabilitySourceId, + removeMissingEpisodeAvailabilitySeries, + syncEpisodeAvailabilityForSeries, + syncSonarrEpisodeAvailability, +} from '@server/lib/episodeAvailability'; +import { + getSettings, + MetadataProviderType, + type SonarrSettings, +} from '@server/lib/settings'; +import { setupTestDb } from '@server/test/db'; +import assert from 'node:assert/strict'; +import { it } from 'node:test'; + +setupTestDb(); +const provider = MetadataProviderType.TVDB; +const source = { type: 'sonarr' as const, id: 'sonarr:1' }; +async function fixture(tmdbId = 100) { + const media = await getRepository(Media).save( + new Media({ tmdbId, mediaType: MediaType.TV }) + ); + const season = await getRepository(Season).save( + new Season({ media: Promise.resolve(media), seasonNumber: 1 }) + ); + return { media, season }; +} +async function sync(tmdbId = 100, is4k = false) { + await syncEpisodeAvailabilityForSeries({ + source, + metadataProvider: provider, + externalSeriesId: 42, + tmdbId, + seasons: [{ seasonNumber: 1, episodes: [{ episodeNumber: 1, is4k }] }], + }); +} +it('persists and clears the valid zero-valued Sonarr service', async () => { + const { season } = await fixture(); + assert.equal(getSonarrEpisodeAvailabilitySourceId(0), 'sonarr:0'); + await syncSonarrEpisodeAvailability(0, 42, [ + { seasonId: season.id, episodes: [{ episodeNumber: 1, is4k: false }] }, + ]); + assert.equal(await getRepository(EpisodeAvailability).count(), 1); + await clearSonarrEpisodeAvailabilityForService(0); + assert.equal(await getRepository(EpisodeAvailability).count(), 0); +}); +it('preserves a complete snapshot on an incomplete or malformed inventory', async () => { + await fixture(); + await sync(); + for (const [ids, complete] of [ + [[], false], + [[NaN], true], + [[42, -1], true], + [[42, 42], true], + ] as const) { + await removeMissingEpisodeAvailabilitySeries( + source, + provider, + [...ids], + complete + ); + assert.equal(await getRepository(EpisodeAvailability).count(), 1); + } +}); +it('clears only the confirmed empty source and numbering order', async () => { + await fixture(); + await sync(); + const repository = getRepository(EpisodeAvailability); + const record = await repository.findOneOrFail({ + where: { externalSeriesId: 42 }, + relations: { season: true }, + }); + await repository.save( + repository.create({ ...record, id: undefined, sourceId: 'sonarr:2' }) + ); + await removeMissingEpisodeAvailabilitySeries(source, provider, [], true); + const remaining = await repository.find(); + assert.equal(remaining.length, 1); + assert.equal(remaining[0].sourceId, 'sonarr:2'); +}); +it('keeps source, numbering order, season and quality independent', async () => { + await fixture(); + await sync(100, true); + assert.equal( + (await getEpisodeAvailability(100, 1, provider, [source], false)).size, + 0 + ); + assert.equal( + ( + await getEpisodeAvailability( + 100, + 1, + MetadataProviderType.TMDB, + [source], + true + ) + ).size, + 0 + ); + assert.equal( + (await getEpisodeAvailability(100, 2, provider, [source], true)).size, + 0 + ); + assert.equal( + ( + await getEpisodeAvailability( + 100, + 1, + provider, + [{ ...source, id: 'sonarr:2' }], + true + ) + ).size, + 0 + ); + assert.deepEqual( + (await getEpisodeAvailability(100, 1, provider, [source], true)).get(1) + ?.sonarrAvailability, + { hd: false, fourK: true } + ); +}); +it('does not erase a prior snapshot when an unknown season prevents reconciliation', async () => { + await fixture(); + await sync(); + await syncEpisodeAvailabilityForSeries({ + source, + metadataProvider: provider, + externalSeriesId: 42, + tmdbId: 100, + seasons: [{ seasonNumber: 2, episodes: [] }], + }); + assert.equal(await getRepository(EpisodeAvailability).count(), 1); +}); + +it('matches scanner endpoint deduplication after enabled and quality gates', () => { + const server = (id: number, is4k: boolean, syncEnabled = true) => + ({ + id, + is4k, + syncEnabled, + hostname: 'fixture', + port: 8989, + useSsl: false, + baseUrl: '', + }) as SonarrSettings; + const settings = getSettings(); + const sourceSettings = { + sonarr: [server(9, false, false), server(0, true), server(1, false)], + plex: settings.plex, + jellyfin: settings.jellyfin, + mediaServerType: MediaServerType.NOT_CONFIGURED, + }; + assert.deepEqual( + getActiveEpisodeAvailabilitySources(provider, sourceSettings, true), + [{ type: 'sonarr', id: 'sonarr:0' }] + ); + assert.deepEqual( + getActiveEpisodeAvailabilitySources(provider, sourceSettings, false), + [{ type: 'sonarr', id: 'sonarr:1' }] + ); +}); diff --git a/server/lib/episodeAvailability.ts b/server/lib/episodeAvailability.ts new file mode 100644 index 0000000000..ea92c952b5 --- /dev/null +++ b/server/lib/episodeAvailability.ts @@ -0,0 +1,496 @@ +import { MediaType } from '@server/constants/media'; +import { MediaServerType } from '@server/constants/server'; +import dataSource, { getRepository } from '@server/datasource'; +import EpisodeAvailability, { + type EpisodeAvailabilitySourceType, +} from '@server/entity/EpisodeAvailability'; +import Media from '@server/entity/Media'; +import Season from '@server/entity/Season'; +import { isSameServarrSyncEndpoint } from '@server/lib/scanners/servarrTagFilters'; +import type { SonarrSettings } from '@server/lib/settings'; +import { + MetadataProviderType, + type JellyfinSettings, + type PlexSettings, +} from '@server/lib/settings'; +import { createHash } from 'node:crypto'; +import { In } from 'typeorm'; + +const EPISODE_AVAILABILITY_BATCH_SIZE = 100; + +export interface EpisodeAvailabilityEntry { + episodeNumber: number; + is4k: boolean; +} + +export interface EpisodeAvailabilitySeasonSync { + seasonNumber: number; + episodes: EpisodeAvailabilityEntry[]; +} + +export interface SonarrSeasonAvailabilitySync { + seasonId: number; + episodes: EpisodeAvailabilityEntry[]; +} + +export interface EpisodeAvailabilitySource { + type: EpisodeAvailabilitySourceType; + id: string; +} + +export interface EpisodeAvailabilitySourceSettings { + sonarr: SonarrSettings[]; + plex: PlexSettings; + jellyfin: JellyfinSettings; + mediaServerType: MediaServerType; +} + +export interface EpisodeAvailabilityByQuality { + hd: boolean; + fourK: boolean; +} + +export interface EpisodeAvailabilitySourceStatus extends EpisodeAvailabilityByQuality { + sourceType: EpisodeAvailabilitySourceType; +} + +const episodeAvailabilitySourceOrder: EpisodeAvailabilitySourceType[] = [ + 'sonarr', + 'plex', + 'jellyfin', + 'emby', +]; + +export interface EpisodeAvailabilityForEpisode { + sonarrAvailability?: EpisodeAvailabilityByQuality; + sources: EpisodeAvailabilitySourceStatus[]; +} + +const isPositiveSafeInteger = (value: number): boolean => + Number.isSafeInteger(value) && value > 0; + +const sourceIdForMediaServerLibrary = ( + type: 'plex' | 'jellyfin' | 'emby', + serverIdentity: string, + libraryId: string +): string => { + const identity = serverIdentity.trim(); + const id = libraryId.trim(); + if (!identity || !id) return ''; + + const digest = createHash('sha256') + .update(JSON.stringify([type, identity, id])) + .digest('hex'); + return `${type}:${digest}`; +}; + +export const getSonarrEpisodeAvailabilitySourceId = ( + serviceId: number +): string => + Number.isSafeInteger(serviceId) && serviceId >= 0 + ? `sonarr:${serviceId}` + : ''; + +export const getPlexEpisodeAvailabilitySourceId = ( + settings: PlexSettings, + libraryId: string +): string => { + const identity = + settings.machineId?.trim() || + `${settings.useSsl ? 'https' : 'http'}://${settings.ip}:${settings.port}`; + return sourceIdForMediaServerLibrary('plex', identity, libraryId); +}; + +export const getJellyfinEpisodeAvailabilitySourceId = ( + settings: JellyfinSettings, + libraryId: string, + type: 'jellyfin' | 'emby' +): string => { + const identity = + settings.serverId?.trim() || + `${settings.useSsl ? 'https' : 'http'}://${settings.ip}:${settings.port}${settings.urlBase ?? ''}`; + return sourceIdForMediaServerLibrary(type, identity, libraryId); +}; + +export const getActiveEpisodeAvailabilitySources = ( + metadataProvider: MetadataProviderType, + settings: EpisodeAvailabilitySourceSettings, + include4k = true +): EpisodeAvailabilitySource[] => { + const sources: EpisodeAvailabilitySource[] = []; + + if (metadataProvider === MetadataProviderType.TVDB) { + const selectedServers: SonarrSettings[] = []; + for (const server of settings.sonarr) { + if (!server.syncEnabled || (!include4k && server.is4k)) continue; + if ( + selectedServers.some((candidate) => + isSameServarrSyncEndpoint(candidate, server) + ) + ) + continue; + selectedServers.push(server); + const id = getSonarrEpisodeAvailabilitySourceId(server.id); + if (id) sources.push({ type: 'sonarr', id }); + } + } + + if (settings.mediaServerType === MediaServerType.PLEX) { + for (const library of settings.plex.libraries) { + if ( + !library.enabled || + library.type !== 'show' || + library.episodeOrderProvider !== metadataProvider + ) { + continue; + } + const id = getPlexEpisodeAvailabilitySourceId(settings.plex, library.id); + if (id) sources.push({ type: 'plex', id }); + } + } else if ( + settings.mediaServerType === MediaServerType.JELLYFIN || + settings.mediaServerType === MediaServerType.EMBY + ) { + const type = + settings.mediaServerType === MediaServerType.EMBY ? 'emby' : 'jellyfin'; + for (const library of settings.jellyfin.libraries) { + if ( + !library.enabled || + library.type !== 'show' || + library.episodeOrderProvider !== metadataProvider + ) { + continue; + } + const id = getJellyfinEpisodeAvailabilitySourceId( + settings.jellyfin, + library.id, + type + ); + if (id) sources.push({ type, id }); + } + } + + return sources; +}; + +export const syncEpisodeAvailabilityForSeries = async ({ + source, + metadataProvider, + externalSeriesId, + tmdbId, + seasons, +}: { + source: EpisodeAvailabilitySource; + metadataProvider: MetadataProviderType; + externalSeriesId: number; + tmdbId: number; + seasons: EpisodeAvailabilitySeasonSync[]; +}): Promise => { + if ( + !source.id || + !isPositiveSafeInteger(externalSeriesId) || + !isPositiveSafeInteger(tmdbId) || + !Array.isArray(seasons) || + seasons.length === 0 || + new Set(seasons.map(({ seasonNumber }) => seasonNumber)).size !== + seasons.length || + seasons.some( + (season) => + !Number.isSafeInteger(season.seasonNumber) || + season.seasonNumber < 0 || + !Array.isArray(season.episodes) || + season.episodes.some( + (episode) => + !Number.isSafeInteger(episode.episodeNumber) || + episode.episodeNumber < 0 || + typeof episode.is4k !== 'boolean' + ) + ) + ) { + return; + } + + await dataSource.transaction(async (manager) => { + const media = await manager.getRepository(Media).findOneBy({ + tmdbId, + mediaType: MediaType.TV, + }); + if (!media) return; + + const seasonRepository = manager.getRepository(Season); + const storedSeasons = await seasonRepository.find({ + where: { media: { id: media.id } }, + select: { id: true, seasonNumber: true }, + }); + const seasonIds = new Map( + storedSeasons.map((season) => [season.seasonNumber, season.id]) + ); + if (seasons.some(({ seasonNumber }) => !seasonIds.has(seasonNumber))) { + return; + } + + const repository = manager.getRepository(EpisodeAvailability); + await repository + .createQueryBuilder() + .delete() + .from(EpisodeAvailability) + .where('"sourceType" = :sourceType', { sourceType: source.type }) + .andWhere('"sourceId" = :sourceId', { sourceId: source.id }) + .andWhere('"metadataProvider" = :metadataProvider', { + metadataProvider, + }) + .andWhere('"externalSeriesId" = :externalSeriesId', { + externalSeriesId, + }) + .execute(); + + const rows = new Map(); + for (const season of seasons) { + const seasonId = seasonIds.get(season.seasonNumber); + if (!seasonId) continue; + + for (const episode of season.episodes) { + const key = `${seasonId}:${episode.episodeNumber}:${episode.is4k}`; + rows.set( + key, + repository.create({ + episodeNumber: episode.episodeNumber, + sourceType: source.type, + sourceId: source.id, + metadataProvider, + externalSeriesId, + is4k: episode.is4k, + season: new Season({ id: seasonId }), + }) + ); + } + } + + const entries = [...rows.values()]; + for ( + let offset = 0; + offset < entries.length; + offset += EPISODE_AVAILABILITY_BATCH_SIZE + ) { + await repository.save( + entries.slice(offset, offset + EPISODE_AVAILABILITY_BATCH_SIZE) + ); + } + }); +}; + +export const syncSonarrEpisodeAvailability = async ( + serviceId: number, + externalSeriesId: number, + seasons: SonarrSeasonAvailabilitySync[] +): Promise => { + if ( + !Number.isSafeInteger(serviceId) || + serviceId < 0 || + !isPositiveSafeInteger(externalSeriesId) || + !Array.isArray(seasons) || + seasons.length === 0 || + seasons.some( + (season) => + !isPositiveSafeInteger(season.seasonId) || + !Array.isArray(season.episodes) + ) + ) { + return; + } + + const seasonIds = [...new Set(seasons.map(({ seasonId }) => seasonId))]; + const storedSeasons = await getRepository(Season).find({ + where: { id: In(seasonIds) }, + relations: { media: true }, + }); + if (storedSeasons.length !== seasonIds.length) return; + + const seasonMedia = await Promise.all( + storedSeasons.map(({ media }) => media) + ); + const media = seasonMedia[0]; + if ( + !media || + media.mediaType !== MediaType.TV || + seasonMedia.some((season) => season.id !== media.id) + ) { + return; + } + + const seasonNumbers = new Map( + storedSeasons.map((season) => [season.id, season.seasonNumber]) + ); + await syncEpisodeAvailabilityForSeries({ + source: { + type: 'sonarr', + id: getSonarrEpisodeAvailabilitySourceId(serviceId), + }, + metadataProvider: MetadataProviderType.TVDB, + externalSeriesId, + tmdbId: media.tmdbId, + seasons: seasons.map(({ seasonId, episodes }) => ({ + seasonNumber: seasonNumbers.get(seasonId) ?? -1, + episodes, + })), + }); +}; + +export const removeMissingEpisodeAvailabilitySeries = async ( + source: EpisodeAvailabilitySource, + metadataProvider: MetadataProviderType, + presentSeriesIds: number[], + completeInventory: boolean +): Promise => { + if ( + !completeInventory || + !source.id || + !Array.isArray(presentSeriesIds) || + presentSeriesIds.some((id) => !isPositiveSafeInteger(id)) || + new Set(presentSeriesIds).size !== presentSeriesIds.length + ) + return; + const validSeriesIds = presentSeriesIds; + + const query = getRepository(EpisodeAvailability) + .createQueryBuilder() + .delete() + .from(EpisodeAvailability) + .where('"sourceType" = :sourceType', { sourceType: source.type }) + .andWhere('"sourceId" = :sourceId', { sourceId: source.id }) + .andWhere('"metadataProvider" = :metadataProvider', { + metadataProvider, + }); + + if (validSeriesIds.length > 0) { + query.andWhere('"externalSeriesId" NOT IN (:...validSeriesIds)', { + validSeriesIds, + }); + } + + await query.execute(); +}; + +export const removeMissingSonarrEpisodeSeries = async ( + serviceId: number, + presentSeriesIds: number[] +): Promise => { + const sourceId = getSonarrEpisodeAvailabilitySourceId(serviceId); + if (!sourceId) return; + + await removeMissingEpisodeAvailabilitySeries( + { type: 'sonarr', id: sourceId }, + MetadataProviderType.TVDB, + presentSeriesIds, + true + ); +}; + +export const clearEpisodeAvailabilityForSource = async ( + source: EpisodeAvailabilitySource +): Promise => { + if (!source.id) return; + + await getRepository(EpisodeAvailability) + .createQueryBuilder() + .delete() + .from(EpisodeAvailability) + .where('"sourceType" = :sourceType', { sourceType: source.type }) + .andWhere('"sourceId" = :sourceId', { sourceId: source.id }) + .execute(); +}; + +export const clearSonarrEpisodeAvailabilityForService = async ( + serviceId: number +): Promise => { + const sourceId = getSonarrEpisodeAvailabilitySourceId(serviceId); + if (!sourceId) return; + + await clearEpisodeAvailabilityForSource({ type: 'sonarr', id: sourceId }); +}; + +export const clearSonarrEpisodeAvailabilityForSeries = async ( + serviceId: number, + externalSeriesId: number +): Promise => { + const sourceId = getSonarrEpisodeAvailabilitySourceId(serviceId); + if (!sourceId || !isPositiveSafeInteger(externalSeriesId)) return; + + await getRepository(EpisodeAvailability) + .createQueryBuilder() + .delete() + .from(EpisodeAvailability) + .where('"sourceType" = :sourceType', { sourceType: 'sonarr' }) + .andWhere('"sourceId" = :sourceId', { sourceId }) + .andWhere('"metadataProvider" = :metadataProvider', { + metadataProvider: MetadataProviderType.TVDB, + }) + .andWhere('"externalSeriesId" = :externalSeriesId', { + externalSeriesId, + }) + .execute(); +}; + +export const getEpisodeAvailability = async ( + tmdbId: number, + seasonNumber: number, + metadataProvider: MetadataProviderType, + sources: EpisodeAvailabilitySource[], + include4k: boolean +): Promise> => { + const sourceIds = [...new Set(sources.map(({ id }) => id).filter(Boolean))]; + if (sourceIds.length === 0) return new Map(); + + const media = await getRepository(Media).findOneBy({ + tmdbId, + mediaType: MediaType.TV, + }); + if (!media) return new Map(); + + const season = await getRepository(Season).findOne({ + where: { media: { id: media.id }, seasonNumber }, + }); + if (!season) return new Map(); + + const records = await getRepository(EpisodeAvailability).find({ + where: { + season: { id: season.id }, + sourceId: In(sourceIds), + sourceType: In([...new Set(sources.map(({ type }) => type))]), + metadataProvider, + }, + }); + const availability = new Map(); + + for (const record of records) { + if (record.is4k && !include4k) continue; + + const current = availability.get(record.episodeNumber) ?? { sources: [] }; + let sourceStatus = current.sources.find( + ({ sourceType }) => sourceType === record.sourceType + ); + if (!sourceStatus) { + sourceStatus = { sourceType: record.sourceType, hd: false, fourK: false }; + current.sources.push(sourceStatus); + } + if (record.is4k) sourceStatus.fourK = true; + else sourceStatus.hd = true; + if (record.sourceType === 'sonarr') { + current.sonarrAvailability = { + hd: sourceStatus.hd, + fourK: sourceStatus.fourK, + }; + } + availability.set(record.episodeNumber, current); + } + + for (const episode of availability.values()) { + episode.sources.sort( + (left, right) => + episodeAvailabilitySourceOrder.indexOf(left.sourceType) - + episodeAvailabilitySourceOrder.indexOf(right.sourceType) + ); + } + + return availability; +}; diff --git a/server/lib/externalRuntimeConfig.ts b/server/lib/externalRuntimeConfig.ts index 72a69b9f5d..d12534fcd2 100644 --- a/server/lib/externalRuntimeConfig.ts +++ b/server/lib/externalRuntimeConfig.ts @@ -83,11 +83,39 @@ const normalizeServarrServices = ( ); } + const supportsSyncExcludedTags = + service === 'radarr' || service === 'sonarr'; + const syncExcludedTags = settings.syncExcludedTags; + if ( + supportsSyncExcludedTags && + syncExcludedTags !== undefined && + (!Array.isArray(syncExcludedTags) || + syncExcludedTags.length > 100 || + syncExcludedTags.some( + (tagId) => + typeof tagId !== 'number' || + !Number.isSafeInteger(tagId) || + tagId < 0 || + tagId > 1_000_000 + )) + ) { + throw new Error( + `SEERR_EXTERNAL_CONFIG.${service}[${index}].syncExcludedTags is invalid` + ); + } + return { ...settings, // Older settings files omitted this field or stored it as null. Both // representations mean the standard (non-4K) service. is4k: settings.is4k === true, + ...(supportsSyncExcludedTags + ? { + syncExcludedTags: Array.isArray(syncExcludedTags) + ? [...new Set(syncExcludedTags)] + : [], + } + : {}), }; }); }; diff --git a/server/lib/futureSeasonMonitoring.test.ts b/server/lib/futureSeasonMonitoring.test.ts new file mode 100644 index 0000000000..d1927b3547 --- /dev/null +++ b/server/lib/futureSeasonMonitoring.test.ts @@ -0,0 +1,83 @@ +import { RequestFutureSeasons1793400000000 as PostgresMigration } from '@server/migration/postgres/1793400000000-RequestFutureSeasons'; +import { RequestFutureSeasons1793400000000 as SqliteMigration } from '@server/migration/sqlite/1793400000000-RequestFutureSeasons'; +import assert from 'node:assert/strict'; +import { DatabaseSync } from 'node:sqlite'; +import { test } from 'node:test'; +import type { QueryRunner } from 'typeorm'; +import { + resolveFutureSeasonMonitoring, + validateFutureSeasonPreference, +} from './futureSeasonMonitoring'; + +test('future-season preference is a strict TV-only boolean', () => { + for (const value of [false, true]) + assert.equal(validateFutureSeasonPreference(value, 'tv'), undefined); + for (const value of [null, 0, 1, 'true', [], {}]) + assert.ok(validateFutureSeasonPreference(value, 'tv')); + for (const type of ['book', 'movie', undefined]) + assert.ok(validateFutureSeasonPreference(true, type)); + assert.equal(validateFutureSeasonPreference(undefined, 'movie'), undefined); +}); +test('opt-in, opt-out and inherited defaults remain distinct', () => { + assert.deepEqual(resolveFutureSeasonMonitoring(true, false, 'none'), { + monitorNewItems: 'all', + enableFutureSeasons: true, + }); + assert.deepEqual(resolveFutureSeasonMonitoring(false, false, 'all'), { + monitorNewItems: 'none', + enableFutureSeasons: false, + }); + for (const inherited of ['all', 'none'] as const) + for (const preference of [undefined, null]) + assert.deepEqual( + resolveFutureSeasonMonitoring(preference, false, inherited), + { monitorNewItems: inherited, enableFutureSeasons: false } + ); +}); +test('Episode Queue and watch-gate policy override new and legacy preferences', () => { + for (const preference of [true, false, undefined, null]) + assert.deepEqual(resolveFutureSeasonMonitoring(preference, true, 'all'), { + monitorNewItems: 'none', + enableFutureSeasons: false, + }); +}); +for (const Migration of [SqliteMigration, PostgresMigration]) { + test(`${new Migration().name}: migration preserves legacy nulls and survives repeated up/down`, async () => { + const db = new DatabaseSync(':memory:'); + db.exec( + 'CREATE TABLE media_request (id integer PRIMARY KEY); INSERT INTO media_request (id) VALUES (1)' + ); + const runner = { + hasTable: async () => true, + hasColumn: async (_: string, name: string) => + db + .prepare('PRAGMA table_info(media_request)') + .all() + .some((row) => row.name === name), + query: async (sql: string) => db.exec(sql), + dropColumn: async (_: string, name: string) => + db.exec(`ALTER TABLE media_request DROP COLUMN "${name}"`), + } as unknown as QueryRunner; + const migration = new Migration(); + try { + await migration.up(runner); + await migration.up(runner); + assert.equal( + db.prepare('SELECT monitorFutureSeasons FROM media_request').get() + ?.monitorFutureSeasons, + null + ); + db.exec('UPDATE media_request SET monitorFutureSeasons = 0'); + assert.equal( + db.prepare('SELECT monitorFutureSeasons FROM media_request').get() + ?.monitorFutureSeasons, + 0 + ); + await migration.down(runner); + await migration.down(runner); + assert.equal(db.prepare('SELECT id FROM media_request').get()?.id, 1); + } finally { + db.close(); + } + }); +} diff --git a/server/lib/futureSeasonMonitoring.ts b/server/lib/futureSeasonMonitoring.ts new file mode 100644 index 0000000000..820f37966a --- /dev/null +++ b/server/lib/futureSeasonMonitoring.ts @@ -0,0 +1,28 @@ +/** A request may opt into future seasons, but cannot bypass an enrollment policy. */ +export const validateFutureSeasonPreference = ( + value: unknown, + mediaType: unknown +): string | undefined => { + if (value === undefined) return undefined; + if (typeof value !== 'boolean') + return 'monitorFutureSeasons must be a boolean.'; + if (mediaType !== 'tv') + return 'Future-season monitoring is only valid for TV requests.'; + return undefined; +}; + +export const resolveFutureSeasonMonitoring = ( + preference: boolean | null | undefined, + restricted: boolean, + inherited: 'all' | 'none' +): { monitorNewItems: 'all' | 'none'; enableFutureSeasons: boolean } => ({ + monitorNewItems: restricted + ? 'none' + : preference == null + ? inherited + : preference + ? 'all' + : 'none', + // An opt-out never disables monitoring established by another requester or Sonarr. + enableFutureSeasons: !restricted && preference === true, +}); diff --git a/server/lib/mediaServerAvailability.test.ts b/server/lib/mediaServerAvailability.test.ts index 7588445228..f03ac7d985 100644 --- a/server/lib/mediaServerAvailability.test.ts +++ b/server/lib/mediaServerAvailability.test.ts @@ -9,6 +9,7 @@ import Media from '@server/entity/Media'; import Season from '@server/entity/Season'; import { User } from '@server/entity/User'; import cacheManager from '@server/lib/cache'; +import type { EpisodeAvailabilityForEpisode } from '@server/lib/episodeAvailability'; import { getSettings } from '@server/lib/settings'; import { resetTestDb, seedTestDb } from '@server/utils/seedTestDb'; import assert from 'node:assert/strict'; @@ -16,6 +17,7 @@ import { afterEach, before, beforeEach, describe, it, mock } from 'node:test'; import { applyUserMediaServerAvailability, getMediaServerAccessContext, + restrictEpisodeAvailabilityForUser, } from './mediaServerAvailability'; const media = (id = 1, tmdbId = 550) => @@ -276,3 +278,67 @@ describe('Jellyfin viewer library projection', () => { assert.equal(entry.seasons[1].status, MediaStatus.UNKNOWN); }); }); + +const episodeBadges = (): Map => + new Map( + [1, 2].map((number) => [ + number, + { + sources: [ + { sourceType: 'plex', hd: true, fourK: true }, + { sourceType: 'sonarr', hd: true, fourK: false }, + ], + }, + ]) + ); +it('projects episode badges through viewer-visible episode files and quality', async () => { + const show = new Media({ ...media(), mediaType: MediaType.TV }); + mock.method( + PlexAPI.prototype, + 'getMetadata', + async () => + ({ + ...metadata(), + type: 'show', + Children: { Metadata: [{ type: 'season', index: 1 }] }, + }) as PlexMetadata + ); + mock.method( + PlexAPI.prototype, + 'getAllLeavesMetadata', + async () => + [ + { + type: 'episode', + parentIndex: 1, + index: 1, + Media: [{ width: 1920, height: 1080 }], + }, + ] as PlexMetadata[] + ); + const badges = episodeBadges(); + await restrictEpisodeAvailabilityForUser(badges, show, await context(), 1); + assert.deepEqual(badges.get(1)?.sources, [ + { sourceType: 'plex', hd: true, fourK: false }, + { sourceType: 'sonarr', hd: true, fourK: false }, + ]); + assert.deepEqual(badges.get(2)?.sources, [ + { sourceType: 'sonarr', hd: true, fourK: false }, + ]); +}); +it('does not reveal global episode files after viewer access fails', async () => { + mock.method(PlexAPI.prototype, 'getMetadata', async () => { + throw new Error('Fixture denied'); + }); + const badges = episodeBadges(); + await restrictEpisodeAvailabilityForUser( + badges, + new Media({ ...media(), mediaType: MediaType.TV }), + await context(), + 1 + ); + for (const episode of badges.values()) + assert.deepEqual(episode.sources, [ + { sourceType: 'sonarr', hd: true, fourK: false }, + ]); +}); diff --git a/server/lib/mediaServerAvailability.ts b/server/lib/mediaServerAvailability.ts index 1d12c5d2fe..254ef14682 100644 --- a/server/lib/mediaServerAvailability.ts +++ b/server/lib/mediaServerAvailability.ts @@ -7,8 +7,10 @@ import type Media from '@server/entity/Media'; import MediaServiceStatus from '@server/entity/MediaServiceStatus'; import { User } from '@server/entity/User'; import cacheManager from '@server/lib/cache'; +import type { EpisodeAvailabilityForEpisode } from '@server/lib/episodeAvailability'; import type { PlexSettings } from '@server/lib/settings'; import { getSettings } from '@server/lib/settings'; +import { is4kResolution } from '@server/lib/videoResolution'; import { mapWithConcurrency } from '@server/utils/concurrency'; import { getHostname } from '@server/utils/getHostname'; import { normalizeJellyfinGuid } from '@server/utils/jellyfin'; @@ -718,3 +720,118 @@ export const applyUserMediaServerAvailability = async ( return true; }; + +/** Intersect scanned media-server badges with episodes visible to this viewer. + * Acquisition-only Sonarr indicators retain their separate meaning. */ +export const restrictEpisodeAvailabilityForUser = async ( + availability: Map, + media: Media | null, + context: MediaServerAccessContext | undefined, + seasonNumber: number +): Promise => { + if ( + !context || + ![...availability.values()].some((episode) => + episode.sources.some((source) => source.sourceType !== 'sonarr') + ) + ) + return; + const visible = new Map(); + const add = (episode: number, is4k: boolean | undefined) => { + if (!Number.isSafeInteger(episode) || episode < 1 || is4k === undefined) + return; + const entry = visible.get(episode) ?? { hd: false, fourK: false }; + if (is4k) entry.fourK = true; + else entry.hd = true; + visible.set(episode, entry); + }; + const visited = new Set(); + if (media && context.credential) { + for (const format of ['standard', '4k'] as const) { + const id = variantNativeId(media, format, context.source); + if (!id || visited.has(id)) continue; + visited.add(id); + const access = await resolveNativeItemAccess(context, media, format); + if (!access.visible || !access.seasonNumbers?.includes(seasonNumber)) + continue; + try { + if (context.source === 'plex' && context.plexSettings) { + const api = new PlexAPI({ + plexToken: context.credential, + plexSettings: context.plexSettings, + timeout: MEDIA_SERVER_CHECK_TIMEOUT_MS, + }); + const episodes = await api.getAllLeavesMetadata(id); + for (const episode of episodes) { + if (episode.parentIndex !== seasonNumber) continue; + for (const version of episode.Media ?? []) { + add( + episode.index, + is4kResolution(`${version.width}x${version.height}`) + ); + } + } + } else { + const api = new JellyfinAPI( + context.host, + context.credential, + context.deviceId, + undefined, + MEDIA_SERVER_CHECK_TIMEOUT_MS + ); + api.setUserId(context.linkedIdentity); + const episodes = await api.getUserEpisodesForAvailability(id); + for (const episode of episodes) { + if ( + episode.Type !== 'Episode' || + episode.ParentIndexNumber !== seasonNumber + ) + continue; + const first = episode.IndexNumber; + const last = episode.IndexNumberEnd ?? first; + if ( + !Number.isSafeInteger(first) || + !Number.isSafeInteger(last) || + first! < 1 || + last! < first! || + last! - first! > 1000 + ) + continue; + let hd = false; + let fourK = false; + for (const version of episode.MediaSources ?? []) { + for (const stream of version.MediaStreams ?? []) { + if (stream.Type !== 'Video') continue; + const is4k = is4kResolution(`${stream.Width}x${stream.Height}`); + if (is4k === true) fourK = true; + if (is4k === false) hd = true; + if (hd && fourK) break; + } + if (hd && fourK) break; + } + for (let number = first!; number <= last!; number += 1) { + if (!availability.has(number)) continue; + if (hd) add(number, false); + if (fourK) add(number, true); + } + } + } + } catch { + // Provider failures cannot reveal a global scan's episode inventory. + } + } + } + for (const [number, episode] of availability) { + const allowed = visible.get(number); + episode.sources = episode.sources.flatMap((source) => { + if (source.sourceType === 'sonarr') return [source]; + if (source.sourceType !== context.source || !allowed) return []; + const projected = { + ...source, + hd: source.hd && allowed.hd, + fourK: source.fourK && allowed.fourK, + }; + return projected.hd || projected.fourK ? [projected] : []; + }); + } +}; diff --git a/server/lib/notifications/agents/agent.test.ts b/server/lib/notifications/agents/agent.test.ts index fc20ab0637..abd90e20c4 100644 --- a/server/lib/notifications/agents/agent.test.ts +++ b/server/lib/notifications/agents/agent.test.ts @@ -134,6 +134,120 @@ describe('getMediaTypeLabel', () => { }); describe('WebhookAgent', () => { + const webhook = (template: unknown) => + new WebhookAgent({ + enabled: true, + embedPoster: false, + types: Notification.MEDIA_AVAILABLE, + options: { + webhookUrl: 'http://127.0.0.1/webhook', + jsonPayload: Buffer.from( + JSON.stringify(JSON.stringify(template)) + ).toString('base64'), + customHeaders: [], + supportVariables: false, + }, + }); + const notification = (subject = 'Crème Déjà Vu & More') => ({ + notifySystem: true, + notifyAdmin: false, + subject, + message: 'message', + }); + + it('renders allowlisted Unicode filters and keeps substituted placeholders literal', async () => { + process.env.SEERR_ALLOW_PRIVATE_NOTIFICATION_URLS = 'true'; + const post = mock.method(axios, 'post', async () => ({ data: {} })); + const sent = await webhook({ + plain: '{{subject}}', + nested: [ + { + slug: '{{subject | slugify}}', + encoded: '{{subject | lowercase | urlencode}}', + }, + ], + unknown: '{{legacy_unknown}}', + }).send(Notification.MEDIA_AVAILABLE, notification()); + assert.equal(sent, true); + assert.deepEqual(post.mock.calls[0].arguments[1], { + plain: 'Crème Déjà Vu & More', + nested: [ + { + slug: 'creme-deja-vu-more', + encoded: encodeURIComponent('crème déjà vu & more'), + }, + ], + unknown: '{{legacy_unknown}}', + }); + await webhook({ text: '{{subject}}' }).send( + Notification.MEDIA_AVAILABLE, + notification('{{message}}') + ); + assert.deepEqual(post.mock.calls[1].arguments[1], { text: '{{message}}' }); + }); + + it('bounds rendered webhook expansion across repeated placeholders before sending', async () => { + process.env.SEERR_ALLOW_PRIVATE_NOTIFICATION_URLS = 'true'; + const post = mock.method(axios, 'post', async () => ({ data: {} })); + const sent = await webhook({ text: '{{subject}}'.repeat(200) }).send( + Notification.MEDIA_AVAILABLE, + notification('x'.repeat(1024)) + ); + assert.equal(sent, false); + assert.equal(post.mock.callCount(), 0); + }); + + it('bounds rendering work even when filters shrink repeated large values to empty strings', async () => { + process.env.SEERR_ALLOW_PRIVATE_NOTIFICATION_URLS = 'true'; + const post = mock.method(axios, 'post', async () => ({ data: {} })); + assert.equal( + await webhook({ text: '{{subject | slugify}}'.repeat(80) }).send( + Notification.MEDIA_AVAILABLE, + notification(' '.repeat(20000)) + ), + false + ); + assert.equal(post.mock.callCount(), 0); + }); + + it('rejects invalid filters, excessive chains and escaped JSON expansion before sending', async () => { + process.env.SEERR_ALLOW_PRIVATE_NOTIFICATION_URLS = 'true'; + const post = mock.method(axios, 'post', async () => ({ data: {} })); + for (const template of [ + '{{subject | __proto__}}', + '{{subject | toString}}', + '{{subject | unknown}}', + '{{subject | }}', + '{{ | lowercase}}', + '{{subject | lowercase', + '{{subject' + ' | lowercase'.repeat(9) + '}}', + ]) { + assert.equal( + await webhook({ text: template }).send( + Notification.MEDIA_AVAILABLE, + notification() + ), + false, + template + ); + } + assert.equal( + await webhook({ text: '{{subject | urlencode | urlencode}}' }).send( + Notification.MEDIA_AVAILABLE, + notification('&'.repeat(20000)) + ), + false + ); + assert.equal( + await webhook({ text: '{{subject}}' }).send( + Notification.MEDIA_AVAILABLE, + notification('\u0000'.repeat(20000)) + ), + false + ); + assert.equal(post.mock.callCount(), 0); + }); + it('accepts only bounded object or array payload templates', () => { assert.deepStrictEqual(parseWebhookPayloadTemplate('{"ok":true}'), { ok: true, diff --git a/server/lib/notifications/agents/apprise.ts b/server/lib/notifications/agents/apprise.ts index 6c66b600c0..3d6817ee1d 100644 --- a/server/lib/notifications/agents/apprise.ts +++ b/server/lib/notifications/agents/apprise.ts @@ -91,6 +91,8 @@ class AppriseAgent switch (type) { case Notification.MEDIA_PENDING: return intl.formatMessage(globalMessages.pendingApproval); + case Notification.MEDIA_PENDING_UPDATED: + return intl.formatMessage(globalMessages.requestUpdated); case Notification.MEDIA_APPROVED: case Notification.MEDIA_AUTO_APPROVED: return intl.formatMessage(globalMessages.processing); diff --git a/server/lib/notifications/agents/discord.ts b/server/lib/notifications/agents/discord.ts index 3779af5a51..d29a876908 100644 --- a/server/lib/notifications/agents/discord.ts +++ b/server/lib/notifications/agents/discord.ts @@ -166,6 +166,10 @@ class DiscordAgent color = EmbedColors.ORANGE; status = `[${intl.formatMessage(globalMessages.pendingApproval)}](${appUrl}/requests)`; break; + case Notification.MEDIA_PENDING_UPDATED: + color = EmbedColors.ORANGE; + status = `[${intl.formatMessage(globalMessages.requestUpdated)}](${appUrl}/requests)`; + break; case Notification.MEDIA_APPROVED: case Notification.MEDIA_AUTO_APPROVED: color = EmbedColors.PURPLE; diff --git a/server/lib/notifications/agents/email.ts b/server/lib/notifications/agents/email.ts index 9b096948bc..cdd1800ad0 100644 --- a/server/lib/notifications/agents/email.ts +++ b/server/lib/notifications/agents/email.ts @@ -35,6 +35,10 @@ const messages = defineMessages('notifications.agents.email', { 'A new request for the following {mediaType} is pending approval:', pendingRequest4k: 'A new request for the following {mediaType} in 4K is pending approval:', + pendingRequestUpdated: + 'The pending request for the following {mediaType} has been updated:', + pendingRequestUpdated4k: + 'The pending request for the following {mediaType} in 4K has been updated:', autoRequested: 'A new request for the following {mediaType} was automatically submitted:', autoRequested4k: @@ -145,6 +149,14 @@ class EmailAgent { mediaType } ); break; + case Notification.MEDIA_PENDING_UPDATED: + body = intl.formatMessage( + is4k + ? messages.pendingRequestUpdated4k + : messages.pendingRequestUpdated, + { mediaType } + ); + break; case Notification.MEDIA_AUTO_REQUESTED: body = intl.formatMessage( is4k ? messages.autoRequested4k : messages.autoRequested, diff --git a/server/lib/notifications/agents/gotify.ts b/server/lib/notifications/agents/gotify.ts index acb6a7667a..7225fce2f6 100644 --- a/server/lib/notifications/agents/gotify.ts +++ b/server/lib/notifications/agents/gotify.ts @@ -104,6 +104,9 @@ class GotifyAgent case Notification.MEDIA_PENDING: status = intl.formatMessage(globalMessages.pendingApproval); break; + case Notification.MEDIA_PENDING_UPDATED: + status = intl.formatMessage(globalMessages.requestUpdated); + break; case Notification.MEDIA_APPROVED: case Notification.MEDIA_AUTO_APPROVED: status = intl.formatMessage(globalMessages.processing); diff --git a/server/lib/notifications/agents/ntfy.ts b/server/lib/notifications/agents/ntfy.ts index d62614167e..6f894cbf9c 100644 --- a/server/lib/notifications/agents/ntfy.ts +++ b/server/lib/notifications/agents/ntfy.ts @@ -77,6 +77,9 @@ class NtfyAgent case Notification.MEDIA_PENDING: status = intl.formatMessage(globalMessages.pendingApproval); break; + case Notification.MEDIA_PENDING_UPDATED: + status = intl.formatMessage(globalMessages.requestUpdated); + break; case Notification.MEDIA_APPROVED: case Notification.MEDIA_AUTO_APPROVED: status = intl.formatMessage(globalMessages.processing); diff --git a/server/lib/notifications/agents/pushbullet.ts b/server/lib/notifications/agents/pushbullet.ts index 1d275f7563..e65374010b 100644 --- a/server/lib/notifications/agents/pushbullet.ts +++ b/server/lib/notifications/agents/pushbullet.ts @@ -71,6 +71,9 @@ class PushbulletAgent case Notification.MEDIA_PENDING: status = intl.formatMessage(globalMessages.pendingApproval); break; + case Notification.MEDIA_PENDING_UPDATED: + status = intl.formatMessage(globalMessages.requestUpdated); + break; case Notification.MEDIA_APPROVED: case Notification.MEDIA_AUTO_APPROVED: status = intl.formatMessage(globalMessages.processing); diff --git a/server/lib/notifications/agents/pushover.ts b/server/lib/notifications/agents/pushover.ts index 9fbcd81377..a5323ad6e8 100644 --- a/server/lib/notifications/agents/pushover.ts +++ b/server/lib/notifications/agents/pushover.ts @@ -216,6 +216,9 @@ class PushoverAgent case Notification.MEDIA_PENDING: status = intl.formatMessage(globalMessages.pendingApproval); break; + case Notification.MEDIA_PENDING_UPDATED: + status = intl.formatMessage(globalMessages.requestUpdated); + break; case Notification.MEDIA_APPROVED: case Notification.MEDIA_AUTO_APPROVED: status = intl.formatMessage(globalMessages.processing); diff --git a/server/lib/notifications/agents/slack.ts b/server/lib/notifications/agents/slack.ts index 377554143a..765d442515 100644 --- a/server/lib/notifications/agents/slack.ts +++ b/server/lib/notifications/agents/slack.ts @@ -171,6 +171,9 @@ class SlackAgent case Notification.MEDIA_PENDING: status = intl.formatMessage(globalMessages.pendingApproval); break; + case Notification.MEDIA_PENDING_UPDATED: + status = intl.formatMessage(globalMessages.requestUpdated); + break; case Notification.MEDIA_APPROVED: case Notification.MEDIA_AUTO_APPROVED: status = intl.formatMessage(globalMessages.processing); @@ -283,7 +286,8 @@ class SlackAgent const elements: Element[] = []; if ( - type === Notification.MEDIA_PENDING && + (type === Notification.MEDIA_PENDING || + type === Notification.MEDIA_PENDING_UPDATED) && payload.request && settings.options.requestActionsEnabled === true && isValidSlackRequestActionSettings(settings.options) diff --git a/server/lib/notifications/agents/telegram.ts b/server/lib/notifications/agents/telegram.ts index 75a71a7359..e2ec39c1fc 100644 --- a/server/lib/notifications/agents/telegram.ts +++ b/server/lib/notifications/agents/telegram.ts @@ -161,6 +161,9 @@ class TelegramAgent case Notification.MEDIA_PENDING: status = intl.formatMessage(globalMessages.pendingApproval); break; + case Notification.MEDIA_PENDING_UPDATED: + status = intl.formatMessage(globalMessages.requestUpdated); + break; case Notification.MEDIA_APPROVED: case Notification.MEDIA_AUTO_APPROVED: status = intl.formatMessage(globalMessages.processing); diff --git a/server/lib/notifications/agents/webhook.ts b/server/lib/notifications/agents/webhook.ts index fccc13e986..39ac24d6ce 100644 --- a/server/lib/notifications/agents/webhook.ts +++ b/server/lib/notifications/agents/webhook.ts @@ -189,6 +189,115 @@ const KeyMap: Record = { commentedBy_settings_telegramChatId: 'comment.user.settings.telegramChatId', }; +type WebhookTemplateFilter = (value: string) => string; + +const WEBHOOK_TEMPLATE_FILTERS: Record = { + lowercase: (value) => value.toLowerCase(), + urlencode: (value) => encodeURIComponent(value), + slugify: (value) => + value + .normalize('NFKD') + .replace(/\p{M}/gu, '') + .toLowerCase() + .replace(/[^\p{L}\p{N}]+/gu, '-') + .replace(/^-+|-+$/g, ''), +}; + +type WebhookRenderBudget = { bytes: number; workBytes: number }; + +const renderWebhookTemplateString = ( + template: string, + payload: NotificationPayload, + type: Notification, + budget: WebhookRenderBudget +): string => { + const parts: string[] = []; + const consumeWork = (value: string) => { + budget.workBytes += Buffer.byteLength(value, 'utf8'); + if (budget.workBytes > MAX_WEBHOOK_PAYLOAD_BYTES * 16) { + throw new Error('Webhook template exceeds maximum rendering work.'); + } + }; + const assertWithinBudget = (value: string) => { + if ( + Buffer.byteLength(value, 'utf8') > + MAX_WEBHOOK_PAYLOAD_BYTES - budget.bytes + ) { + throw new Error('Rendered webhook payload exceeds maximum size.'); + } + }; + const append = (value: string) => { + assertWithinBudget(value); + budget.bytes += Buffer.byteLength(value, 'utf8'); + parts.push(value); + }; + const literal = (value: string) => { + if (/{{[^{}]*\|/.test(value)) { + throw new Error('Webhook template expression is invalid.'); + } + append(value); + }; + const resolve = (placeholder: string, expression: string): string => { + const [variableName, ...filterNames] = expression + .split('|') + .map((part) => part.trim()); + + if (!variableName || !/^[A-Za-z][A-Za-z0-9_]*$/.test(variableName)) { + if (expression.includes('|')) { + throw new Error('Webhook template expression is invalid.'); + } + return placeholder; + } + + if (filterNames.length > 8) { + throw new Error('Webhook template exceeds maximum filter count.'); + } + + const variable = Object.prototype.hasOwnProperty.call(KeyMap, variableName) + ? KeyMap[variableName] + : undefined; + if (!variable) { + if (filterNames.length > 0) { + throw new Error('Webhook template variable is unknown.'); + } + return placeholder; + } + + const variableValue = + typeof variable === 'function' + ? variable(payload, type) + : get(payload, variable); + let rendered = String(variableValue ?? ''); + assertWithinBudget(rendered); + consumeWork(rendered); + + for (const filterName of filterNames) { + const filter = Object.prototype.hasOwnProperty.call( + WEBHOOK_TEMPLATE_FILTERS, + filterName + ) + ? WEBHOOK_TEMPLATE_FILTERS[filterName] + : undefined; + if (!filter) { + throw new Error('Webhook template filter is unknown.'); + } + consumeWork(rendered); + rendered = filter(rendered); + assertWithinBudget(rendered); + } + + return rendered; + }; + let offset = 0; + for (const match of template.matchAll(/{{([^{}]*)}}/g)) { + literal(template.slice(offset, match.index)); + append(resolve(match[0], match[1])); + offset = match.index + match[0].length; + } + literal(template.slice(offset)); + return parts.join(''); +}; + class WebhookAgent extends BaseAgent implements NotificationAgent @@ -205,9 +314,14 @@ class WebhookAgent finalPayload: Record, payload: NotificationPayload, type: Notification, - options: { depth: number; nodes: { count: number } } = { + options: { + depth: number; + nodes: { count: number }; + budget: WebhookRenderBudget; + } = { depth: 0, nodes: { count: 0 }, + budget: { bytes: 0, workBytes: 0 }, } ): Record { if (options.depth > MAX_WEBHOOK_PAYLOAD_DEPTH) { @@ -220,6 +334,10 @@ class WebhookAgent } Object.keys(finalPayload).forEach((key) => { + options.budget.bytes += Buffer.byteLength(key, 'utf8'); + if (options.budget.bytes > MAX_WEBHOOK_PAYLOAD_BYTES) { + throw new Error('Rendered webhook payload exceeds maximum size.'); + } if (key === '{{extra}}') { finalPayload.extra = payload.extra ?? []; delete finalPayload[key]; @@ -259,15 +377,12 @@ class WebhookAgent } if (typeof finalPayload[key] === 'string') { - Object.keys(KeyMap).forEach((keymapKey) => { - const keymapValue = KeyMap[keymapKey as keyof typeof KeyMap]; - finalPayload[key] = (finalPayload[key] as string).replaceAll( - `{{${keymapKey}}}`, - typeof keymapValue === 'function' - ? keymapValue(payload, type) - : (get(payload, keymapValue) ?? '') - ); - }); + finalPayload[key] = renderWebhookTemplateString( + finalPayload[key] as string, + payload, + type, + options.budget + ); } else if (finalPayload[key] && typeof finalPayload[key] === 'object') { finalPayload[key] = this.parseKeys( finalPayload[key] as Record, @@ -276,6 +391,7 @@ class WebhookAgent { depth: options.depth + 1, nodes: options.nodes, + budget: options.budget, } ); } @@ -289,7 +405,18 @@ class WebhookAgent this.getSettings().options.jsonPayload ).template; - return this.parseKeys(parsedJSON as Record, payload, type); + const rendered = this.parseKeys( + parsedJSON as Record, + payload, + type + ); + if ( + Buffer.byteLength(JSON.stringify(rendered), 'utf8') > + MAX_WEBHOOK_PAYLOAD_BYTES + ) { + throw new Error('Rendered webhook payload exceeds maximum size.'); + } + return rendered; } public shouldSend(): boolean { diff --git a/server/lib/notifications/agents/webpush.ts b/server/lib/notifications/agents/webpush.ts index 4983f8cad8..c2f3a2f6ec 100644 --- a/server/lib/notifications/agents/webpush.ts +++ b/server/lib/notifications/agents/webpush.ts @@ -39,6 +39,7 @@ const messages = defineMessages('notifications.agents.webpush', { failed: 'Failed to process {quality}{mediaType} request.', pending: 'Approval required for a new {quality}{mediaType} request from {userName}.', + pendingUpdated: 'A pending {quality}{mediaType} request was updated.', issueCreated: 'A new {issueType} was reported by {userName}.', issueComment: '{userName} commented on the {issueType}.', issueResolved: 'The {issueType} was marked as resolved by {userName}!', @@ -190,6 +191,12 @@ class WebPushAgent userName: payload.request?.requestedBy.displayName, }); break; + case Notification.MEDIA_PENDING_UPDATED: + message = intl.formatMessage(messages.pendingUpdated, { + quality, + mediaType, + }); + break; case Notification.ISSUE_CREATED: message = intl.formatMessage(messages.issueCreated, { issueType, @@ -421,7 +428,8 @@ class WebPushAgent ) : this.buildPayload( type, - type === Notification.MEDIA_PENDING + type === Notification.MEDIA_PENDING || + type === Notification.MEDIA_PENDING_UPDATED ? { ...payload, pendingRequestsCount: pendingRequestCount, @@ -447,7 +455,10 @@ class WebPushAgent settings.vapidPrivate ); - if (type === Notification.MEDIA_PENDING) { + if ( + type === Notification.MEDIA_PENDING || + type === Notification.MEDIA_PENDING_UPDATED + ) { payload = { ...payload, pendingRequestsCount: pendingRequestCount }; } diff --git a/server/lib/notifications/index.ts b/server/lib/notifications/index.ts index efd510013e..420816864c 100644 --- a/server/lib/notifications/index.ts +++ b/server/lib/notifications/index.ts @@ -40,6 +40,7 @@ export enum Notification { MEDIA_AUTO_REQUESTED = 4096, SOFTWARE_AVAILABLE = 8192, SOFTWARE_STATUS = 16384, + MEDIA_PENDING_UPDATED = 32768, } export const hasNotificationType = ( @@ -71,6 +72,7 @@ export const hasNotificationType = ( export const getAdminPermission = (type: Notification): Permission => { switch (type) { case Notification.MEDIA_PENDING: + case Notification.MEDIA_PENDING_UPDATED: case Notification.MEDIA_APPROVED: case Notification.MEDIA_AVAILABLE: case Notification.MEDIA_FAILED: diff --git a/server/lib/notifications/intents.ts b/server/lib/notifications/intents.ts index 038d6a4bb4..7245835234 100644 --- a/server/lib/notifications/intents.ts +++ b/server/lib/notifications/intents.ts @@ -153,6 +153,9 @@ export const buildMediaRequestNotificationPayload = async ( case Notification.MEDIA_PENDING: event = `New ${entity.is4k ? '4K ' : ''}${mediaType} Request`; break; + case Notification.MEDIA_PENDING_UPDATED: + event = `Pending ${entity.is4k ? '4K ' : ''}${mediaType} Request Updated`; + break; case Notification.MEDIA_AUTO_REQUESTED: event = `${entity.is4k ? '4K ' : ''}${mediaType} Request Automatically Submitted`; notifyAdmin = false; diff --git a/server/lib/notifications/outbox.ts b/server/lib/notifications/outbox.ts index c80f441d55..689fe907e7 100644 --- a/server/lib/notifications/outbox.ts +++ b/server/lib/notifications/outbox.ts @@ -146,7 +146,7 @@ const validateIntentType = ( ): void => { const compatible = intent.kind === 'media-request' - ? [2, 4, 8, 16, 64, 128, 4096].includes(type) + ? [2, 4, 8, 16, 64, 128, 4096, 32768].includes(type) : intent.kind === 'media-availability-subscription' ? type === 8 : intent.kind === 'issue' diff --git a/server/lib/notifications/requestUpdate.test.ts b/server/lib/notifications/requestUpdate.test.ts new file mode 100644 index 0000000000..686c669ed0 --- /dev/null +++ b/server/lib/notifications/requestUpdate.test.ts @@ -0,0 +1,79 @@ +import { MediaRequestStatus } from '@server/constants/media'; +import type { MediaRequest } from '@server/entity/MediaRequest'; +import assert from 'node:assert/strict'; +import { it } from 'node:test'; +import { + capturePendingRequestEditSnapshot, + hasMaterialPendingRequestEdit, +} from './requestUpdate'; + +const pending = () => + ({ + status: MediaRequestStatus.PENDING, + requestedBy: { id: 2 }, + serverId: 0, + profileId: 0, + tags: [2, 1], + seasons: [ + { + seasonNumber: 2, + episodeNumbers: [3, 1], + status: MediaRequestStatus.PENDING, + }, + ], + }) as MediaRequest; + +it('ignores tag and episode ordering while detecting material pending changes', () => { + const request = pending(); + const before = capturePendingRequestEditSnapshot(request); + request.tags = [1, 2]; + request.seasons[0].episodeNumbers = [1, 3]; + assert.equal(hasMaterialPendingRequestEdit(before, request), false); + Object.assign(request, { profileId: null }); + assert.equal(hasMaterialPendingRequestEdit(before, request), true); +}); + +it('notifies ownership changes only while the request remains pending', () => { + const request = pending(); + const before = capturePendingRequestEditSnapshot(request); + request.requestedBy = { id: 3 } as MediaRequest['requestedBy']; + assert.equal(hasMaterialPendingRequestEdit(before, request), true); + for (const status of [ + MediaRequestStatus.APPROVED, + MediaRequestStatus.COMPLETED, + MediaRequestStatus.DECLINED, + ]) { + request.status = status; + assert.equal(hasMaterialPendingRequestEdit(before, request), false); + } +}); + +it('detects resolved destination and future-season edits even when saved overrides stay null', () => { + const request = pending(); + Object.assign(request, { + profileId: null, + monitorFutureSeasons: false, + serviceTargets: [ + { + serviceType: 'sonarr', + format: 'standard', + serverId: 0, + profileId: 7, + rootFolder: '/series', + tags: [2, 1], + }, + ], + }); + const before = capturePendingRequestEditSnapshot(request); + request.serviceTargets![0].profileId = 0; + assert.equal(hasMaterialPendingRequestEdit(before, request), true); + const changed = capturePendingRequestEditSnapshot(request); + Object.assign(request.serviceTargets![0], { + externalServiceId: 99, + status: 3, + tags: [1, 2], + }); + assert.equal(hasMaterialPendingRequestEdit(changed, request), false); + Object.assign(request, { monitorFutureSeasons: true }); + assert.equal(hasMaterialPendingRequestEdit(changed, request), true); +}); diff --git a/server/lib/notifications/requestUpdate.ts b/server/lib/notifications/requestUpdate.ts new file mode 100644 index 0000000000..f973d581cb --- /dev/null +++ b/server/lib/notifications/requestUpdate.ts @@ -0,0 +1,55 @@ +import { MediaRequestStatus } from '@server/constants/media'; +import type { MediaRequest } from '@server/entity/MediaRequest'; + +const getPendingRequestEditSnapshot = (request: MediaRequest): string => + JSON.stringify({ + requestedById: request.requestedBy?.id ?? null, + serverId: request.serverId ?? null, + profileId: request.profileId ?? null, + metadataProfileId: request.metadataProfileId ?? null, + rootFolder: request.rootFolder ?? null, + languageProfileId: request.languageProfileId ?? null, + metadataLanguageId: request.metadataLanguageId ?? null, + sonarrSeasonType: request.sonarrSeasonType ?? null, + bookFormat: request.bookFormat ?? null, + monitorFutureSeasons: + 'monitorFutureSeasons' in request + ? (request.monitorFutureSeasons ?? null) + : null, + serviceTargets: (request.serviceTargets ?? []) + .map((target) => ({ + serviceType: target.serviceType, + format: target.format, + serverId: target.serverId, + profileId: target.profileId ?? null, + metadataProfileId: target.metadataProfileId ?? null, + languageProfileId: target.languageProfileId ?? null, + rootFolder: target.rootFolder ?? null, + tags: [...(target.tags ?? [])].sort((left, right) => left - right), + })) + .sort((left, right) => + `${left.serviceType}:${left.format}:${left.serverId}`.localeCompare( + `${right.serviceType}:${right.format}:${right.serverId}` + ) + ), + tags: [...(request.tags ?? [])].sort((left, right) => left - right), + seasons: (request.seasons ?? []) + .map((season) => ({ + seasonNumber: season.seasonNumber, + episodeNumbers: + season.episodeNumbers == null + ? null + : [...season.episodeNumbers].sort((left, right) => left - right), + status: season.status, + })) + .sort((left, right) => left.seasonNumber - right.seasonNumber), + }); + +export const hasMaterialPendingRequestEdit = ( + previousSnapshot: string, + updatedRequest: MediaRequest +): boolean => + updatedRequest.status === MediaRequestStatus.PENDING && + getPendingRequestEditSnapshot(updatedRequest) !== previousSnapshot; + +export const capturePendingRequestEditSnapshot = getPendingRequestEditSnapshot; diff --git a/server/lib/overrideRuleProductionCountries.test.ts b/server/lib/overrideRuleProductionCountries.test.ts new file mode 100644 index 0000000000..43f9171fb7 --- /dev/null +++ b/server/lib/overrideRuleProductionCountries.test.ts @@ -0,0 +1,121 @@ +import type { + TmdbMovieDetails, + TmdbTvDetails, +} from '@server/api/themoviedb/interfaces'; +import { MediaType } from '@server/constants/media'; +import { getRepository } from '@server/datasource'; +import OverrideRule from '@server/entity/OverrideRule'; +import type { User } from '@server/entity/User'; +import { + getSettings, + type RadarrSettings, + type SonarrSettings, +} from '@server/lib/settings'; +import { setupTestDb } from '@server/test/db'; +import assert from 'node:assert/strict'; +import { it } from 'node:test'; +import { + catalogOverrideRuleMatches, + evaluateOverrideRules, +} from './overrideRules'; + +setupTestDb(); + +const evaluate = async ( + countryData: unknown, + mediaType: MediaType.MOVIE | MediaType.TV = MediaType.MOVIE, + genre = 18, + language = 'en' +) => { + const tmdbMedia = { + genres: [{ id: genre }], + original_language: language, + keywords: mediaType === MediaType.TV ? { results: [] } : { keywords: [] }, + ...(countryData === undefined ? {} : { production_countries: countryData }), + } as unknown as TmdbMovieDetails | TmdbTvDetails; + return evaluateOverrideRules({ + mediaType, + is4k: false, + tmdbMedia, + requestUser: { id: 1 } as User, + serviceId: 0, + }); +}; + +const rules = async ( + mediaType: MediaType.MOVIE | MediaType.TV = MediaType.MOVIE +) => { + const service = { id: 0, isDefault: true, is4k: false }; + getSettings().radarr = [service as RadarrSettings]; + getSettings().sonarr = [service as SonarrSettings]; + const field = + mediaType === MediaType.MOVIE ? 'radarrServiceId' : 'sonarrServiceId'; + await getRepository(OverrideRule).save([ + new OverrideRule({ [field]: 0, users: '1', profileId: 7 }), + new OverrideRule({ + [field]: 0, + users: '1', + genre: '18', + language: 'en', + productionCountries: 'CA|US', + profileId: 9, + languageProfileId: 0, + }), + ]); +}; + +it('falls back safely when production-country metadata is absent or malformed', async () => { + await rules(); + for (const countries of [ + undefined, + null, + {}, + [], + [{ iso_3166_1: null }], + [{ iso_3166_1: 'USA' }], + ]) { + assert.equal((await evaluate(countries)).profileId, 7); + } +}); + +it('matches any selected country while retaining the other conditions and service identity', async () => { + await rules(); + assert.equal((await evaluate([{ iso_3166_1: 'ca' }])).profileId, 9); + assert.equal( + (await evaluate([{ iso_3166_1: 'US' }], MediaType.MOVIE, 35)).profileId, + 7 + ); + assert.equal( + (await evaluate([{ iso_3166_1: 'US' }], MediaType.MOVIE, 18, 'ko')) + .profileId, + 7 + ); + assert.equal((await evaluate([{ iso_3166_1: 'JP' }])).profileId, 7); + await getRepository(OverrideRule).save( + new OverrideRule({ + radarrServiceId: 12, + users: '1', + genre: '18', + language: 'en', + productionCountries: 'CA|US', + profileId: 99, + }) + ); + const result = await evaluate([{ iso_3166_1: 'US' }]); + assert.equal(result.profileId, 9); + assert.equal(result.languageProfileId, null); +}); + +it('preserves language profile zero for matching Sonarr rules and excludes country rules from catalog matching', async () => { + await rules(MediaType.TV); + const result = await evaluate([{ iso_3166_1: 'US' }], MediaType.TV); + assert.equal(result.profileId, 9); + assert.equal(result.languageProfileId, 0); + assert.equal( + catalogOverrideRuleMatches( + new OverrideRule({ productionCountries: 'US' }), + 1 + ), + false + ); +}); diff --git a/server/lib/overrideRules.ts b/server/lib/overrideRules.ts index 758813555c..50da2ea276 100644 --- a/server/lib/overrideRules.ts +++ b/server/lib/overrideRules.ts @@ -16,13 +16,14 @@ export const overrideRuleConditionFields = [ 'genre', 'language', 'keywords', + 'productionCountries', ] as const satisfies readonly (keyof OverrideRule)[]; export type OverrideRuleConditionField = (typeof overrideRuleConditionFields)[number]; const MAX_OVERRIDE_RULE_ROUTING_ID = 1_000_000_000; const MAX_OVERRIDE_RULE_ROUTING_TAGS = 100; -const hasConditionValue = (value: unknown): boolean => +const hasConditionValue = (value: unknown): value is string => typeof value === 'string' && value.trim().length > 0; export const getOverrideRuleSpecificity = ( @@ -71,6 +72,15 @@ export const getOverrideRuleProfileId = ( ? rule.profileId : undefined; +export const getOverrideRuleLanguageProfileId = ( + rule: OverrideRule +): number | undefined => + Number.isSafeInteger(rule.languageProfileId) && + rule.languageProfileId! >= 0 && + rule.languageProfileId! <= MAX_OVERRIDE_RULE_ROUTING_ID + ? rule.languageProfileId + : undefined; + export const getOverrideRuleTagIds = (rule: OverrideRule): number[] => { if (!hasConditionValue(rule.tags)) { return []; @@ -95,6 +105,7 @@ export const getOverrideRuleTagIds = (rule: OverrideRule): number[] => { export type OverrideRulesResult = { rootFolder: string | null; profileId: number | null; + languageProfileId: number | null; tags: number[] | null; }; @@ -126,6 +137,7 @@ export const catalogOverrideRuleMatches = ( userId: number, metadata: CatalogRuleMetadata = {} ): boolean => + !hasConditionValue(rule.productionCountries) && overrideRuleMatchesUser(rule, userId) && matchesCatalogTerms(rule.genre, metadata.genres) && matchesCatalogTerms(rule.keywords, metadata.keywords) && @@ -167,6 +179,7 @@ export const evaluateRequesterOverrideRules = async ({ return { rootFolder: rule?.rootFolder || null, profileId: rule ? (getOverrideRuleProfileId(rule) ?? null) : null, + languageProfileId: null, tags: overrideTags.length > 0 ? [...new Set([...(tags ?? []), ...overrideTags])] @@ -219,6 +232,17 @@ export const evaluateOverrideRules = async ({ 'keywords' in tmdbMedia.keywords ? tmdbMedia.keywords.keywords : tmdbMedia.keywords.results; + const productionCountryCodes = new Set( + (Array.isArray(tmdbMedia.production_countries) + ? tmdbMedia.production_countries + : [] + ).flatMap((country) => + typeof country?.iso_3166_1 === 'string' && + /^[A-Za-z]{2}$/.test(country.iso_3166_1) + ? [country.iso_3166_1.toUpperCase()] + : [] + ) + ); const isAnimeTv = mediaType === MediaType.TV && hasTmdbKeyword(tmdbMedia); const matchingRules = rules.filter((rule) => { if ( @@ -254,6 +278,17 @@ export const evaluateOverrideRules = async ({ ) { return false; } + if (hasConditionValue(rule.productionCountries)) { + if ( + !rule.productionCountries + .split('|') + .some((country) => + productionCountryCodes.has(country.trim().toUpperCase()) + ) + ) { + return false; + } + } return true; }); const rule = selectMostSpecificOverrideRule(matchingRules); @@ -263,6 +298,10 @@ export const evaluateOverrideRules = async ({ return { rootFolder: rule?.rootFolder || null, profileId: profileId ?? null, + languageProfileId: + mediaType === MediaType.TV && rule + ? (getOverrideRuleLanguageProfileId(rule) ?? null) + : null, tags: overrideTags.length > 0 ? [...new Set([...(tags ?? []), ...overrideTags])] diff --git a/server/lib/requestStatus.ts b/server/lib/requestStatus.ts index a9c83dd654..353fae9113 100644 --- a/server/lib/requestStatus.ts +++ b/server/lib/requestStatus.ts @@ -25,6 +25,7 @@ import { reconcileRequestedMusicAvailability, } from '@server/lib/musicAvailability'; import logger from '@server/logger'; +import { isProviderBookEdition } from '@server/utils/bookEdition'; import { readarrServiceSupportsFormat } from '@server/utils/readarrService'; import type { EntityManager, Repository } from 'typeorm'; import { In, MoreThan } from 'typeorm'; @@ -208,6 +209,7 @@ type RequestLike = { type: MediaType; is4k: boolean; bookFormat?: 'ebook' | 'audiobook' | 'both' | null; + preferredEditionId?: string | null; serverId?: number | null; serviceTargets?: MediaRequestServiceTarget[] | null; createdAt: Date; @@ -421,6 +423,8 @@ const isRequestSatisfied = (request: RequestLike): boolean => { } if (request.type === MediaType.BOOK) { + if (isProviderBookEdition(request.preferredEditionId)) + return request.status === MediaRequestStatus.COMPLETED; if (!isAvailableStatus(mediaStatus)) { return false; } diff --git a/server/lib/scanners/excludedServarrAvailability.test.ts b/server/lib/scanners/excludedServarrAvailability.test.ts new file mode 100644 index 0000000000..4e669e7fc5 --- /dev/null +++ b/server/lib/scanners/excludedServarrAvailability.test.ts @@ -0,0 +1,45 @@ +import { MediaStatus, MediaType } from '@server/constants/media'; +import { getRepository } from '@server/datasource'; +import Media from '@server/entity/Media'; +import Season from '@server/entity/Season'; +import { setupTestDb } from '@server/test/db'; +import assert from 'node:assert/strict'; +import { it } from 'node:test'; +import { reconcileExcludedServarrAvailability } from './excludedServarrAvailability'; + +setupTestDb(); + +it('preserves pending and blocked seasons while clearing excluded library availability', async () => { + const repository = getRepository(Media); + const item = await repository.save( + new Media({ + tmdbId: 890901, + mediaType: MediaType.TV, + serviceId: 42, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + seasons: [ + MediaStatus.PENDING, + MediaStatus.BLOCKLISTED, + MediaStatus.AVAILABLE, + ].map( + (status, index) => + new Season({ + seasonNumber: index + 1, + status, + status4k: MediaStatus.UNKNOWN, + }) + ), + }) + ); + await reconcileExcludedServarrAvailability('sonarr', [ + { mediaId: item.id, serverId: 42, format: 'standard' }, + ]); + const result = await repository.findOneByOrFail({ id: item.id }); + const statuses = new Map( + result.seasons.map((season) => [season.seasonNumber, season.status]) + ); + assert.equal(statuses.get(1), MediaStatus.PENDING); + assert.equal(statuses.get(2), MediaStatus.BLOCKLISTED); + assert.equal(statuses.get(3), MediaStatus.UNKNOWN); +}); diff --git a/server/lib/scanners/excludedServarrAvailability.ts b/server/lib/scanners/excludedServarrAvailability.ts new file mode 100644 index 0000000000..18ac88045a --- /dev/null +++ b/server/lib/scanners/excludedServarrAvailability.ts @@ -0,0 +1,176 @@ +import { MediaStatus, MediaType } from '@server/constants/media'; +import dataSource from '@server/datasource'; +import Media from '@server/entity/Media'; +import MediaServiceStatus, { + type VideoRequestServiceType, +} from '@server/entity/MediaServiceStatus'; +import { In } from 'typeorm'; + +export type ExcludedServarrAvailabilitySource = { + mediaId: number; + serverId: number; + format: 'standard' | '4k'; +}; + +const libraryAvailabilityStatuses = new Set([ + MediaStatus.AVAILABLE, + MediaStatus.PARTIALLY_AVAILABLE, + MediaStatus.PROCESSING, +]); + +const reportedAvailabilityStatuses = new Set([ + MediaStatus.AVAILABLE, + MediaStatus.PARTIALLY_AVAILABLE, +]); + +export const reconcileExcludedServarrAvailability = async ( + serviceType: Extract, + sources: readonly ExcludedServarrAvailabilitySource[] +): Promise => { + const sourcesByMedia = new Map>>(); + const statusUpdates = new Map< + string, + { serverId: number; format: 'standard' | '4k'; mediaIds: Set } + >(); + + for (const source of sources) { + const formats = sourcesByMedia.get(source.mediaId) ?? new Map(); + const serverIds = formats.get(source.format) ?? new Set(); + serverIds.add(source.serverId); + formats.set(source.format, serverIds); + sourcesByMedia.set(source.mediaId, formats); + + const key = `${source.serverId}:${source.format}`; + const update = statusUpdates.get(key) ?? { + serverId: source.serverId, + format: source.format, + mediaIds: new Set(), + }; + update.mediaIds.add(source.mediaId); + statusUpdates.set(key, update); + } + + if (sourcesByMedia.size === 0) { + return; + } + + await dataSource.transaction(async (manager) => { + const serviceStatusRepository = manager.getRepository(MediaServiceStatus); + for (const { serverId, format, mediaIds } of statusUpdates.values()) { + await serviceStatusRepository.update( + { + mediaId: In([...mediaIds]), + serviceType, + serverId, + format, + }, + { + status: MediaStatus.UNKNOWN, + externalServiceId: null, + externalServiceSlug: null, + seasonStatuses: null, + } + ); + } + + const mediaRepository = manager.getRepository(Media); + const mediaItems = await mediaRepository.find({ + where: { id: In([...sourcesByMedia.keys()]) }, + relations: { seasons: true, serviceStatuses: true }, + }); + + for (const media of mediaItems) { + let changed = false; + const sourcesByFormat = sourcesByMedia.get(media.id); + if (!sourcesByFormat) continue; + + for (const format of ['standard', '4k'] as const) { + const excludedServerIds = sourcesByFormat.get(format); + if (!excludedServerIds?.size) continue; + + const is4k = format === '4k'; + const serviceIdField = is4k ? 'serviceId4k' : 'serviceId'; + const currentServiceId = media[serviceIdField]; + if ( + currentServiceId == null || + !excludedServerIds.has(currentServiceId) + ) { + continue; + } + + const formatStatuses = (media.serviceStatuses ?? []).filter( + (status) => + status.serviceType === serviceType && + status.format === format && + !excludedServerIds.has(status.serverId) + ); + const alternativeAvailability = formatStatuses + .filter((status) => reportedAvailabilityStatuses.has(status.status)) + .sort((left, right) => { + const rank = (status: MediaStatus): number => + status === MediaStatus.AVAILABLE ? 0 : 1; + return rank(left.status) - rank(right.status); + })[0]; + const hasMediaServerCopy = is4k + ? Boolean(media.ratingKey4k || media.jellyfinMediaId4k) + : Boolean(media.ratingKey || media.jellyfinMediaId); + const statusField = is4k ? 'status4k' : 'status'; + + if (!hasMediaServerCopy) { + if (alternativeAvailability) { + if ( + media[statusField] !== MediaStatus.BLOCKLISTED && + media[statusField] !== MediaStatus.DELETED && + media[statusField] !== MediaStatus.PENDING + ) { + media[statusField] = alternativeAvailability.status; + } + } else if (libraryAvailabilityStatuses.has(media[statusField])) { + media[statusField] = MediaStatus.UNKNOWN; + } + + if (media.mediaType === MediaType.TV) { + for (const season of media.seasons ?? []) { + if ( + season[statusField] === MediaStatus.PENDING || + season[statusField] === MediaStatus.BLOCKLISTED || + season[statusField] === MediaStatus.DELETED + ) { + continue; + } + const nextStatus = alternativeAvailability + ? (alternativeAvailability.seasonStatuses?.[ + season.seasonNumber + ] ?? MediaStatus.UNKNOWN) + : MediaStatus.UNKNOWN; + if (season[statusField] !== nextStatus) { + season[statusField] = nextStatus; + } + } + } + } + + if (alternativeAvailability) { + const externalServiceIdField = is4k + ? 'externalServiceId4k' + : 'externalServiceId'; + const externalServiceSlugField = is4k + ? 'externalServiceSlug4k' + : 'externalServiceSlug'; + media[serviceIdField] = alternativeAvailability.serverId; + media[externalServiceIdField] = + alternativeAvailability.externalServiceId ?? null; + media[externalServiceSlugField] = + alternativeAvailability.externalServiceSlug ?? null; + } else { + media.resetServiceDataForResolution(is4k, true); + } + changed = true; + } + + if (changed) { + await mediaRepository.save(media); + } + } + }); +}; diff --git a/server/lib/scanners/jellyfin/index.ts b/server/lib/scanners/jellyfin/index.ts index a897a8dfc1..52b484c1e9 100644 --- a/server/lib/scanners/jellyfin/index.ts +++ b/server/lib/scanners/jellyfin/index.ts @@ -3,7 +3,11 @@ import type { JellyfinLibraryItem, JellyfinLibraryItemExtended, } from '@server/api/jellyfin'; -import JellyfinAPI from '@server/api/jellyfin'; +import JellyfinAPI, { + MAX_JELLYFIN_EPISODES, + MAX_JELLYFIN_LIBRARY_ITEMS, + MAX_JELLYFIN_SEASONS, +} from '@server/api/jellyfin'; import { getMetadataProvider, isTheMovieDbProvider, @@ -24,6 +28,13 @@ import { runWithConfigurationSnapshot, type ConfigurationAuthoritySnapshot, } from '@server/lib/configurationAdmission'; +import { + getJellyfinEpisodeAvailabilitySourceId, + removeMissingEpisodeAvailabilitySeries, + syncEpisodeAvailabilityForSeries, + type EpisodeAvailabilitySeasonSync, + type EpisodeAvailabilitySource, +} from '@server/lib/episodeAvailability'; import { isValidMusicBrainzResourceId, normalizeMusicBrainzId, @@ -41,7 +52,7 @@ import type { } from '@server/lib/scanners/baseScanner'; import BaseScanner from '@server/lib/scanners/baseScanner'; import type { JellyfinSettings, Library } from '@server/lib/settings'; -import { getSettings } from '@server/lib/settings'; +import { MetadataProviderType, getSettings } from '@server/lib/settings'; import { getHostname } from '@server/utils/getHostname'; import { uniqWith } from 'lodash'; @@ -50,6 +61,27 @@ interface JellyfinSyncStatus extends StatusBase { libraries: Library[]; } +const episodeAvailabilityProviders = Object.values(MetadataProviderType); + +interface EpisodeAvailabilityCensus { + source: EpisodeAvailabilitySource; + presentSeriesIds: Map>; + complete: Map; +} + +const getJellyfinMetadataProviderId = ( + metadata: JellyfinLibraryItemExtended, + provider: MetadataProviderType +): number | undefined => { + const value = + provider === MetadataProviderType.TVDB + ? metadata.ProviderIds.Tvdb + : metadata.ProviderIds.Tmdb || metadata.ProviderIds.TheMovieDb; + if (typeof value !== 'string' || !/^\d+$/.test(value)) return undefined; + const id = Number(value); + return Number.isSafeInteger(id) && id > 0 ? id : undefined; +}; + export class JellyfinScanner extends BaseScanner implements RunnableScanner @@ -63,6 +95,7 @@ export class JellyfinScanner private configurationSnapshot: ConfigurationAuthoritySnapshot; private jellyfinSettingsSnapshot: JellyfinSettings; private ownerAuthoritySnapshot: MediaServerUserAuthoritySnapshot; + private episodeAvailabilityCensus?: EpisodeAvailabilityCensus; constructor({ isRecentOnly }: { isRecentOnly?: boolean } = {}) { super('Jellyfin Sync'); @@ -295,6 +328,7 @@ export class JellyfinScanner const metadata = await this.jfClient.getItemData(Id); if (!metadata?.Id) { + this.markEpisodeAvailabilityCensusIncomplete(); this.log('No Id metadata for this title. Skipping', 'debug', { jellyfinItemId: jellyfinitem.Id, }); @@ -352,16 +386,74 @@ export class JellyfinScanner if (tvShow) { const seasons = tvShow.seasons; - const jellyfinSeasons = await this.jfClient.getSeasons(Id); - const processableSeasons: ProcessableSeason[] = []; - const settings = getSettings(); + const isAnime = tvShow.keywords.results.some( + (keyword) => keyword.id === ANIME_KEYWORD_ID + ); + const episodeMetadataProvider = isAnime + ? settings.metadataSettings.anime + : settings.metadataSettings.tv; + const tracksEpisodeAvailability = Boolean( + settings.main.trackEpisodeAvailability && + this.currentLibrary?.type === 'show' && + this.currentLibrary.episodeOrderProvider === episodeMetadataProvider + ); + const jellyfinSeasons = await this.jfClient.getSeasons(Id, { + requireComplete: tracksEpisodeAvailability, + }); + const jellyfinSeasonsComplete = + jellyfinSeasons.length < MAX_JELLYFIN_SEASONS; + if ( + settings.main.trackEpisodeAvailability && + this.currentLibrary?.type === 'show' && + this.currentLibrary.episodeOrderProvider && + this.currentLibrary.episodeOrderProvider !== episodeMetadataProvider + ) { + this.markEpisodeAvailabilityCensusIncomplete( + this.currentLibrary.episodeOrderProvider + ); + } + const sourceType = + settings.main.mediaServerType === MediaServerType.EMBY + ? 'emby' + : 'jellyfin'; + const episodeAvailabilitySourceId = tracksEpisodeAvailability + ? getJellyfinEpisodeAvailabilitySourceId( + this.jellyfinSettingsSnapshot, + this.currentLibrary!.id, + sourceType + ) + : ''; + const episodeAvailabilitySeriesId = tracksEpisodeAvailability + ? getJellyfinMetadataProviderId(metadata, episodeMetadataProvider) + : undefined; + let episodeAvailabilityComplete = Boolean( + episodeAvailabilitySourceId && + episodeAvailabilitySeriesId && + jellyfinSeasonsComplete + ); + const episodeAvailabilitySeasons: EpisodeAvailabilitySeasonSync[] = []; + + if (tracksEpisodeAvailability && !episodeAvailabilityComplete) { + this.markEpisodeAvailabilityCensusIncomplete(episodeMetadataProvider); + } + if (tracksEpisodeAvailability && !jellyfinSeasonsComplete) { + this.markEpisodeAvailabilityCensusIncomplete(episodeMetadataProvider); + } + if (tracksEpisodeAvailability && tvdbSeasonFromAnidb) { + episodeAvailabilityComplete = false; + } + const filteredSeasons = settings.main.enableSpecialEpisodes ? seasons : seasons.filter((sn) => sn.season_number !== 0); for (const season of filteredSeasons) { + if (tracksEpisodeAvailability && season.episode_count <= 0) { + episodeAvailabilityComplete = false; + } + const matchedJellyfinSeason = jellyfinSeasons.find((md) => { if (tvdbSeasonFromAnidb) { // In AniDB we don't have the concept of seasons, @@ -381,12 +473,23 @@ export class JellyfinScanner if (matchedJellyfinSeason) { let totalStandard = 0; let total4k = 0; + const trackedEpisodes = new Map< + string, + { episodeNumber: number; is4k: boolean } + >(); if (!this.enable4kShow) { const episodes = await this.jfClient.getEpisodes( Id, - matchedJellyfinSeason.Id + matchedJellyfinSeason.Id, + { requireComplete: tracksEpisodeAvailability } ); + if ( + tracksEpisodeAvailability && + episodes.length >= MAX_JELLYFIN_EPISODES + ) { + episodeAvailabilityComplete = false; + } for (const episode of episodes) { let episodeCount = 1; @@ -401,14 +504,50 @@ export class JellyfinScanner } totalStandard += episodeCount; + if (tracksEpisodeAvailability) { + if ( + !Number.isSafeInteger(episode.IndexNumber) || + episode.IndexNumber! < 1 || + episodeCount < 1 || + !Number.isSafeInteger( + episode.IndexNumberEnd ?? episode.IndexNumber + ) || + (episode.IndexNumberEnd ?? episode.IndexNumber)! < + episode.IndexNumber! || + episode.IndexNumber! + episodeCount - 1 > + season.episode_count + ) { + episodeAvailabilityComplete = false; + continue; + } + for ( + let episodeNumber = episode.IndexNumber!; + episodeNumber < episode.IndexNumber! + episodeCount; + episodeNumber += 1 + ) { + trackedEpisodes.set(`${episodeNumber}:false`, { + episodeNumber, + is4k: false, + }); + } + } } } else { // 4K detection enabled - request media info to check resolution const episodes = await this.jfClient.getEpisodes( Id, matchedJellyfinSeason.Id, - { includeMediaInfo: true } + { + includeMediaInfo: true, + requireComplete: tracksEpisodeAvailability, + } ); + if ( + tracksEpisodeAvailability && + episodes.length >= MAX_JELLYFIN_EPISODES + ) { + episodeAvailabilityComplete = false; + } for (const episode of episodes) { let episodeCount = 1; @@ -448,9 +587,65 @@ export class JellyfinScanner // See issue https://github.com/seerr-team/seerr/issues/1744 for details. if (hasStandard) totalStandard += episodeCount; if (has4k) total4k += episodeCount; + + if (tracksEpisodeAvailability) { + if ( + !Number.isSafeInteger(episode.IndexNumber) || + episode.IndexNumber! < 1 || + episodeCount < 1 || + !Number.isSafeInteger( + episode.IndexNumberEnd ?? episode.IndexNumber + ) || + (episode.IndexNumberEnd ?? episode.IndexNumber)! < + episode.IndexNumber! || + episode.IndexNumber! + episodeCount - 1 > + season.episode_count || + !Array.isArray(episode.MediaSources) || + episode.MediaSources.length === 0 + ) { + episodeAvailabilityComplete = false; + continue; + } + + const videoStreams = episode.MediaSources.flatMap((source) => + source.MediaStreams.filter( + (stream) => stream.Type === 'Video' + ) + ); + if (videoStreams.length === 0) { + episodeAvailabilityComplete = false; + continue; + } + + for ( + let episodeNumber = episode.IndexNumber!; + episodeNumber < episode.IndexNumber! + episodeCount; + episodeNumber += 1 + ) { + if (hasStandard) { + trackedEpisodes.set(`${episodeNumber}:false`, { + episodeNumber, + is4k: false, + }); + } + if (has4k) { + trackedEpisodes.set(`${episodeNumber}:true`, { + episodeNumber, + is4k: true, + }); + } + } + } } } + if (tracksEpisodeAvailability) { + episodeAvailabilitySeasons.push({ + seasonNumber: season.season_number, + episodes: [...trackedEpisodes.values()], + }); + } + // With AniDB we can have multiple shows for one season, so we need to save // the episode from all the jellyfin entries to get the total if (tvdbSeasonFromAnidb) { @@ -480,6 +675,12 @@ export class JellyfinScanner episodes: 0, episodes4k: 0, }); + if (tracksEpisodeAvailability) { + episodeAvailabilitySeasons.push({ + seasonNumber: season.season_number, + episodes: [], + }); + } } } @@ -498,7 +699,43 @@ export class JellyfinScanner outerMutationGuard: (callback) => this.withOwnerAuthority(callback), } ); + + if (tracksEpisodeAvailability) { + const resolvedSeriesId = tvShow.id; + if ( + episodeAvailabilityComplete && + episodeAvailabilitySeriesId && + episodeAvailabilitySourceId + ) { + const source: EpisodeAvailabilitySource = { + type: sourceType, + id: episodeAvailabilitySourceId, + }; + await this.asyncLock.dispatch(resolvedSeriesId, () => + this.withOwnerAuthority(() => + this.withConfigurationSnapshot(() => + syncEpisodeAvailabilityForSeries({ + source, + metadataProvider: episodeMetadataProvider, + externalSeriesId: episodeAvailabilitySeriesId, + tmdbId: resolvedSeriesId, + seasons: episodeAvailabilitySeasons, + }) + ) + ) + ); + this.recordEpisodeAvailabilityCensusSeries( + episodeMetadataProvider, + episodeAvailabilitySeriesId + ); + } else { + this.markEpisodeAvailabilityCensusIncomplete( + episodeMetadataProvider + ); + } + } } else { + this.markEpisodeAvailabilityCensusIncomplete(); this.log( `No information found for the show: ${metadata.Name}`, 'debug', @@ -514,6 +751,7 @@ export class JellyfinScanner ) { throw e; } + this.markEpisodeAvailabilityCensusIncomplete(); this.log( `Failed to process Jellyfin item. Id: ${ jellyfinitem.SeriesId ?? jellyfinitem.SeasonId ?? jellyfinitem.Id @@ -747,13 +985,33 @@ export class JellyfinScanner } const libraryType = library.type; this.currentLibrary = library; + this.beginEpisodeAvailabilityCensus(library); // Reset AniDB season tracking per library this.processedAnidbSeason = new Map(); this.log(`Beginning to process library: ${library.name}`, 'info'); - this.items = await this.withConfigurationSnapshot(() => - this.jfClient.getLibraryContents(library.id, libraryType) + const inventory = await this.withConfigurationSnapshot(async () => + this.episodeAvailabilityCensus + ? this.jfClient.getLibraryContentsWithInventory( + library.id, + libraryType + ) + : { + items: await this.jfClient.getLibraryContents( + library.id, + libraryType + ), + complete: false, + } ); + this.items = inventory.items; + if ( + !inventory.complete || + this.items.length >= MAX_JELLYFIN_LIBRARY_ITEMS + ) { + this.markEpisodeAvailabilityCensusIncomplete(); + } await this.loop(this.processItem.bind(this), { sessionId }); + await this.finishEpisodeAvailabilityCensus(true); } } @@ -766,6 +1024,7 @@ export class JellyfinScanner } catch (e) { this.log('Sync interrupted', 'error', { errorMessage: e.message }); } finally { + this.episodeAvailabilityCensus = undefined; this.endRun(sessionId); } } @@ -780,6 +1039,93 @@ export class JellyfinScanner }; } + private beginEpisodeAvailabilityCensus(library: Library): void { + this.episodeAvailabilityCensus = undefined; + const settings = getSettings(); + if ( + !settings.main.trackEpisodeAvailability || + library.type !== 'show' || + !library.episodeOrderProvider + ) { + return; + } + + const sourceType = + settings.main.mediaServerType === MediaServerType.EMBY + ? 'emby' + : 'jellyfin'; + const sourceId = getJellyfinEpisodeAvailabilitySourceId( + this.jellyfinSettingsSnapshot, + library.id, + sourceType + ); + if (!sourceId) return; + + this.episodeAvailabilityCensus = { + source: { type: sourceType, id: sourceId }, + presentSeriesIds: new Map( + episodeAvailabilityProviders.map((provider) => [provider, new Set()]) + ), + complete: new Map( + episodeAvailabilityProviders.map((provider) => [ + provider, + provider === library.episodeOrderProvider, + ]) + ), + }; + } + + private markEpisodeAvailabilityCensusIncomplete( + provider?: MetadataProviderType + ): void { + if (!this.episodeAvailabilityCensus) return; + + if (provider) { + this.episodeAvailabilityCensus.complete.set(provider, false); + return; + } + + for (const metadataProvider of episodeAvailabilityProviders) { + this.episodeAvailabilityCensus.complete.set(metadataProvider, false); + } + } + + private recordEpisodeAvailabilityCensusSeries( + provider: MetadataProviderType, + externalSeriesId: number + ): void { + const series = + this.episodeAvailabilityCensus?.presentSeriesIds.get(provider); + if ( + series && + Number.isSafeInteger(externalSeriesId) && + externalSeriesId > 0 + ) { + series.add(externalSeriesId); + } + } + + private async finishEpisodeAvailabilityCensus( + confirmedInventoryComplete: boolean + ): Promise { + const census = this.episodeAvailabilityCensus; + this.episodeAvailabilityCensus = undefined; + if (!census || !confirmedInventoryComplete) return; + + await this.withOwnerAuthority(() => + this.withConfigurationSnapshot(async () => { + for (const provider of episodeAvailabilityProviders) { + await removeMissingEpisodeAvailabilitySeries( + census.source, + provider, + [...(census.presentSeriesIds.get(provider) ?? [])], + census.complete.get(provider) === true + ); + } + }) + ); + } + private withConfigurationSnapshot( callback: () => Promise ): Promise { diff --git a/server/lib/scanners/plex/index.ts b/server/lib/scanners/plex/index.ts index a3d20e07e7..e273a45e86 100644 --- a/server/lib/scanners/plex/index.ts +++ b/server/lib/scanners/plex/index.ts @@ -7,6 +7,7 @@ import MusicBrainz from '@server/api/musicbrainz'; import OpenLibraryAPI from '@server/api/openlibrary'; import PlexAPI, { MAX_PLEX_LIBRARY_ITEMS, + MAX_PLEX_METADATA_ITEMS, type PlexLibraryItem, type PlexMetadata, } from '@server/api/plexapi'; @@ -27,6 +28,13 @@ import { runWithConfigurationSnapshot, type ConfigurationAuthoritySnapshot, } from '@server/lib/configurationAdmission'; +import { + getPlexEpisodeAvailabilitySourceId, + removeMissingEpisodeAvailabilitySeries, + syncEpisodeAvailabilityForSeries, + type EpisodeAvailabilitySeasonSync, + type EpisodeAvailabilitySource, +} from '@server/lib/episodeAvailability'; import { isValidMusicBrainzResourceId, normalizeMusicBrainzId, @@ -46,7 +54,7 @@ import type { } from '@server/lib/scanners/baseScanner'; import BaseScanner from '@server/lib/scanners/baseScanner'; import type { Library, PlexSettings } from '@server/lib/settings'; -import { getSettings } from '@server/lib/settings'; +import { MetadataProviderType, getSettings } from '@server/lib/settings'; import { mapWithConcurrency } from '@server/utils/concurrency'; import { getHttpErrorDetails } from '@server/utils/httpError'; import { uniqWith } from 'lodash'; @@ -65,6 +73,34 @@ const plexCustomProviderRegex = new RegExp( const hamaTvdbRegex = new RegExp(/hama:\/\/tvdb[0-9]?-([0-9]+)/); const hamaAnidbRegex = new RegExp(/hama:\/\/anidb[0-9]?-([0-9]+)/); const HAMA_AGENT = 'com.plexapp.agents.hama'; +const episodeAvailabilityProviders = Object.values(MetadataProviderType); + +interface EpisodeAvailabilityCensus { + source: EpisodeAvailabilitySource; + presentSeriesIds: Map>; + complete: Map; + declaredTotal?: number; +} + +const getPlexMetadataProviderId = ( + metadata: Pick, + provider: MetadataProviderType +): number | undefined => { + const patterns = + provider === MetadataProviderType.TVDB + ? [tvdbRegex] + : [tmdbRegex, tmdbShowRegex]; + const values = [metadata.guid, ...(metadata.Guid ?? []).map(({ id }) => id)]; + + for (const value of values) { + for (const pattern of patterns) { + const id = Number(value.match(pattern)?.[1]); + if (Number.isSafeInteger(id) && id > 0) return id; + } + } + + return undefined; +}; export const PLEX_SCAN_PAGE_SIZE = 50; export const PLEX_SCAN_ITEM_CONCURRENCY = 10; @@ -158,6 +194,7 @@ export class PlexScanner private configurationSnapshot: ConfigurationAuthoritySnapshot; private plexSettingsSnapshot: PlexSettings; private ownerAuthoritySnapshot: MediaServerUserAuthoritySnapshot; + private episodeAvailabilityCensus?: EpisodeAvailabilityCensus; public constructor(isRecentOnly = false) { super('Plex Scan', { bundleSize: PLEX_SCAN_PAGE_SIZE }); @@ -210,6 +247,87 @@ export class PlexScanner }; } + private beginEpisodeAvailabilityCensus(library: Library): void { + this.episodeAvailabilityCensus = undefined; + if ( + !getSettings().main.trackEpisodeAvailability || + library.type !== 'show' || + !library.episodeOrderProvider + ) { + return; + } + + const sourceId = getPlexEpisodeAvailabilitySourceId( + this.plexSettingsSnapshot, + library.id + ); + if (!sourceId) return; + + this.episodeAvailabilityCensus = { + source: { type: 'plex', id: sourceId }, + presentSeriesIds: new Map( + episodeAvailabilityProviders.map((provider) => [provider, new Set()]) + ), + complete: new Map( + episodeAvailabilityProviders.map((provider) => [ + provider, + provider === library.episodeOrderProvider, + ]) + ), + }; + } + + private markEpisodeAvailabilityCensusIncomplete( + provider?: MetadataProviderType + ): void { + if (!this.episodeAvailabilityCensus) return; + + if (provider) { + this.episodeAvailabilityCensus.complete.set(provider, false); + return; + } + + for (const metadataProvider of episodeAvailabilityProviders) { + this.episodeAvailabilityCensus.complete.set(metadataProvider, false); + } + } + + private recordEpisodeAvailabilityCensusSeries( + provider: MetadataProviderType, + externalSeriesId: number + ): void { + const series = + this.episodeAvailabilityCensus?.presentSeriesIds.get(provider); + if ( + series && + Number.isSafeInteger(externalSeriesId) && + externalSeriesId > 0 + ) { + series.add(externalSeriesId); + } + } + + private async finishEpisodeAvailabilityCensus( + confirmedInventoryComplete: boolean + ): Promise { + const census = this.episodeAvailabilityCensus; + this.episodeAvailabilityCensus = undefined; + if (!census || !confirmedInventoryComplete) return; + + await this.withOwnerAuthority(() => + this.withConfigurationSnapshot(async () => { + for (const provider of episodeAvailabilityProviders) { + await removeMissingEpisodeAvailabilitySeries( + census.source, + provider, + [...(census.presentSeriesIds.get(provider) ?? [])], + census.complete.get(provider) === true + ); + } + }) + ); + } + public async run(): Promise { const settings = getSettings(); const sessionId = this.startRun(); @@ -295,8 +413,10 @@ export class PlexScanner } else { for (const library of this.libraries) { this.currentLibrary = library; + this.beginEpisodeAvailabilityCensus(library); this.log(`Beginning to process library: ${library.name}`, 'info'); await this.paginateLibrary(library, { sessionId }); + await this.finishEpisodeAvailabilityCensus(true); } } this.log( @@ -313,6 +433,7 @@ export class PlexScanner currentLibrary: this.currentLibrary?.name, }); } finally { + this.episodeAvailabilityCensus = undefined; this.endRun(sessionId); } } @@ -337,10 +458,35 @@ export class PlexScanner }) ); + if (this.episodeAvailabilityCensus) { + if (Number.isSafeInteger(response.totalSize) && response.totalSize >= 0) { + const census = this.episodeAvailabilityCensus; + if (census.declaredTotal === undefined) { + census.declaredTotal = response.totalSize; + } else if (census.declaredTotal !== response.totalSize) { + this.markEpisodeAvailabilityCensusIncomplete(); + } + } + } + + if ( + !Number.isSafeInteger(response.totalSize) || + response.totalSize < 0 || + response.totalSize > MAX_PLEX_LIBRARY_ITEMS + ) { + this.markEpisodeAvailabilityCensusIncomplete(); + } + const pageItems = preparePlexLibraryPageItems( response.items, this.protectedBundleSize ); + if ( + !Number.isSafeInteger(response.totalSize) || + response.totalSize < start + pageItems.length + ) { + this.markEpisodeAvailabilityCensusIncomplete(); + } this.progress = start; this.totalSize = getBoundedPlexScanTotal( response.totalSize, @@ -350,6 +496,9 @@ export class PlexScanner ); if (pageItems.length === 0) { + if (response.totalSize > start) { + this.markEpisodeAvailabilityCensusIncomplete(); + } return; } @@ -365,6 +514,18 @@ export class PlexScanner nextStart >= this.totalSize || nextStart >= MAX_PLEX_LIBRARY_ITEMS ) { + if ( + Number.isSafeInteger(response.totalSize) && + response.totalSize > start + pageItems.length + ) { + this.markEpisodeAvailabilityCensusIncomplete(); + } + if ( + nextStart >= MAX_PLEX_LIBRARY_ITEMS && + response.totalSize > nextStart + ) { + this.markEpisodeAvailabilityCensusIncomplete(); + } return; } @@ -398,6 +559,9 @@ export class PlexScanner } } } catch (e) { + if (this.currentLibrary?.type === 'show') { + this.markEpisodeAvailabilityCensusIncomplete(); + } if ( e instanceof ConfigurationAuthorityChangedError || e instanceof MediaServerUserAuthorityChangedError @@ -505,6 +669,7 @@ export class PlexScanner // If the media is from HAMA, and doesn't have a TVDb ID, we will treat it // as a special HAMA movie if (mediaIds.tmdbId && !mediaIds.tvdbId && mediaIds.isHama) { + this.markEpisodeAvailabilityCensusIncomplete(); await this.processHamaMovie(metadata, mediaIds.tmdbId); return; } @@ -512,6 +677,7 @@ export class PlexScanner // If the media is from HAMA and we have a TVDb ID, we will attempt // to process any specials that may exist if (mediaIds.tvdbId && mediaIds.isHama) { + this.markEpisodeAvailabilityCensusIncomplete(); await this.processHamaSpecials(metadata, mediaIds.tvdbId); } @@ -521,22 +687,85 @@ export class PlexScanner const seasons = tvShow.seasons; const processableSeasons: ProcessableSeason[] = []; - const settings = getSettings(); + const isAnime = tvShow.keywords.results.some( + (keyword) => keyword.id === ANIME_KEYWORD_ID + ); + const episodeMetadataProvider = isAnime + ? settings.metadataSettings.anime + : settings.metadataSettings.tv; + const tracksEpisodeAvailability = Boolean( + settings.main.trackEpisodeAvailability && + this.currentLibrary?.type === 'show' && + this.currentLibrary.episodeOrderProvider === episodeMetadataProvider + ); + if ( + settings.main.trackEpisodeAvailability && + this.currentLibrary?.type === 'show' && + this.currentLibrary.episodeOrderProvider && + this.currentLibrary.episodeOrderProvider !== episodeMetadataProvider + ) { + this.markEpisodeAvailabilityCensusIncomplete( + this.currentLibrary.episodeOrderProvider + ); + } + const episodeAvailabilitySourceId = tracksEpisodeAvailability + ? getPlexEpisodeAvailabilitySourceId( + this.plexSettingsSnapshot, + this.currentLibrary!.id + ) + : ''; + const episodeAvailabilitySeriesId = tracksEpisodeAvailability + ? getPlexMetadataProviderId(metadata, episodeMetadataProvider) + : undefined; + const plexSeasonList = metadata.Children?.Metadata; + let episodeAvailabilityComplete = Boolean( + episodeAvailabilitySourceId && + episodeAvailabilitySeriesId && + Array.isArray(plexSeasonList) && + plexSeasonList.length < MAX_PLEX_METADATA_ITEMS && + metadata.Children?.size === plexSeasonList.length && + plexSeasonList.every( + (item) => + item.type === 'season' && + Number.isSafeInteger(item.index) && + item.index >= 0 + ) && + new Set(plexSeasonList.map((item) => item.index)).size === + plexSeasonList.length + ); + const episodeAvailabilitySeasons: EpisodeAvailabilitySeasonSync[] = []; + + if (tracksEpisodeAvailability && !episodeAvailabilityComplete) { + this.markEpisodeAvailabilityCensusIncomplete(episodeMetadataProvider); + } + const filteredSeasons = settings.main.enableSpecialEpisodes ? seasons : seasons.filter((sn) => sn.season_number !== 0); for (const season of filteredSeasons) { - const matchedPlexSeason = metadata.Children?.Metadata.find( - (md) => Number(md.index) === season.season_number + if (tracksEpisodeAvailability && season.episode_count <= 0) { + episodeAvailabilityComplete = false; + } + + const matchedPlexSeason = plexSeasonList?.find( + (md) => + md.type === 'season' && Number(md.index) === season.season_number ); if (matchedPlexSeason) { // If we have a matched Plex season, get its children metadata so we can check details const episodes = await this.plexClient.getChildrenMetadata( - matchedPlexSeason.ratingKey + matchedPlexSeason.ratingKey, + { requireComplete: tracksEpisodeAvailability } ); + if ( + tracksEpisodeAvailability && + episodes.length >= MAX_PLEX_METADATA_ITEMS + ) { + episodeAvailabilityComplete = false; + } // Total episodes that are in standard definition (not 4k) const totalStandard = episodes.filter((episode) => !this.enable4kShow @@ -557,6 +786,51 @@ export class PlexScanner episodes4k: total4k, totalEpisodes: season.episode_count, }); + + if (tracksEpisodeAvailability) { + const trackedEpisodes = new Map< + string, + { number: number; is4k: boolean } + >(); + for (const episode of episodes) { + if ( + !Number.isSafeInteger(episode.index) || + episode.index < 1 || + episode.index > season.episode_count || + !Array.isArray(episode.Media) + ) { + episodeAvailabilityComplete = false; + continue; + } + if (episode.Media.length === 0) continue; + + const has4k = + this.enable4kShow && + episode.Media.some((media) => media.videoResolution === '4k'); + const hasStandard = this.enable4kShow + ? episode.Media.some((media) => media.videoResolution !== '4k') + : true; + if (hasStandard) { + trackedEpisodes.set(`${episode.index}:false`, { + number: episode.index, + is4k: false, + }); + } + if (has4k) { + trackedEpisodes.set(`${episode.index}:true`, { + number: episode.index, + is4k: true, + }); + } + } + episodeAvailabilitySeasons.push({ + seasonNumber: season.season_number, + episodes: [...trackedEpisodes.values()].map((episode) => ({ + episodeNumber: episode.number, + is4k: episode.is4k, + })), + }); + } } else { processableSeasons.push({ seasonNumber: season.season_number, @@ -564,6 +838,12 @@ export class PlexScanner episodes4k: 0, totalEpisodes: season.episode_count, }); + if (tracksEpisodeAvailability) { + episodeAvailabilitySeasons.push({ + seasonNumber: season.season_number, + episodes: [], + }); + } } } @@ -579,6 +859,38 @@ export class PlexScanner outerMutationGuard: (callback) => this.withOwnerAuthority(callback), } ); + + if (tracksEpisodeAvailability) { + if ( + episodeAvailabilityComplete && + episodeAvailabilitySeriesId && + episodeAvailabilitySourceId + ) { + const source: EpisodeAvailabilitySource = { + type: 'plex', + id: episodeAvailabilitySourceId, + }; + await this.asyncLock.dispatch(mediaIds.tmdbId, () => + this.withOwnerAuthority(() => + this.withConfigurationSnapshot(() => + syncEpisodeAvailabilityForSeries({ + source, + metadataProvider: episodeMetadataProvider, + externalSeriesId: episodeAvailabilitySeriesId, + tmdbId: mediaIds.tmdbId, + seasons: episodeAvailabilitySeasons, + }) + ) + ) + ); + this.recordEpisodeAvailabilityCensusSeries( + episodeMetadataProvider, + episodeAvailabilitySeriesId + ); + } else { + this.markEpisodeAvailabilityCensusIncomplete(episodeMetadataProvider); + } + } } // Plex's music agent (unlike its movie/tv agents) puts a matched external diff --git a/server/lib/scanners/radarr/index.ts b/server/lib/scanners/radarr/index.ts index e86e64adca..78d17bf1bd 100644 --- a/server/lib/scanners/radarr/index.ts +++ b/server/lib/scanners/radarr/index.ts @@ -3,6 +3,7 @@ import RadarrAPI from '@server/api/servarr/radarr'; import { MediaStatus, MediaType } from '@server/constants/media'; import { getRepository } from '@server/datasource'; import Media from '@server/entity/Media'; +import { runWithRequestAdmission } from '@server/entity/MediaRequest'; import { getExternalRuntimeConfig } from '@server/lib/externalRuntimeConfig'; import { runMediaEntityMutation } from '@server/lib/mediaMutation'; import { upsertMediaSearchMetadata } from '@server/lib/mediaSearchMetadata'; @@ -11,7 +12,17 @@ import type { StatusBase, } from '@server/lib/scanners/baseScanner'; import BaseScanner from '@server/lib/scanners/baseScanner'; +import { + reconcileExcludedServarrAvailability, + type ExcludedServarrAvailabilitySource, +} from '@server/lib/scanners/excludedServarrAvailability'; import { forEachMediaCleanupBatch } from '@server/lib/scanners/mediaCleanupBatches'; +import { + getServarrSyncExcludedTagsForEndpoint, + getServarrSyncServerIdsForEndpoint, + isSameServarrSyncEndpoint, + partitionServarrItemsBySyncExcludedTags, +} from '@server/lib/scanners/servarrTagFilters'; import { ServarrServiceAuthorityChangedError, runWithServarrServiceSnapshot, @@ -21,6 +32,7 @@ import { getSettings, type RadarrSettings } from '@server/lib/settings'; import { is4kResolution } from '@server/lib/videoResolution'; import { getHttpErrorDetails } from '@server/utils/httpError'; import { uniqWith } from 'lodash'; +import { In } from 'typeorm'; type SyncStatus = StatusBase & { currentServer: RadarrSettings; @@ -36,6 +48,11 @@ class RadarrScanner private radarrApi: RadarrAPI; private scannedTmdbIds: Set = new Set(); private scanned4kTmdbIds: Set = new Set(); + private excludedMovies: { + tmdbId: number; + serverId: number; + format: 'standard' | '4k'; + }[] = []; private didScanStandard = false; private didScan4k = false; private serverReturnedEmpty = false; @@ -64,6 +81,7 @@ class RadarrScanner } this.scannedTmdbIds.clear(); this.scanned4kTmdbIds.clear(); + this.excludedMovies = []; this.didScanStandard = false; this.didScan4k = false; this.serverReturnedEmpty = false; @@ -71,18 +89,20 @@ class RadarrScanner try { const fourKEnabled = getSettings().main.enable4k !== false; - this.servers = uniqWith( - structuredClone( - settings.radarr.filter((server) => fourKEnabled || !server.is4k) - ), - (radarrA, radarrB) => { - return ( - radarrA.hostname === radarrB.hostname && - radarrA.port === radarrB.port && - radarrA.baseUrl === radarrB.baseUrl - ); - } + const configuredServers = structuredClone( + settings.radarr.filter( + (server) => server.syncEnabled && (fourKEnabled || !server.is4k) + ) ); + this.servers = uniqWith(configuredServers, (radarrA, radarrB) => { + return isSameServarrSyncEndpoint(radarrA, radarrB); + }).map((server) => ({ + ...server, + syncExcludedTags: getServarrSyncExcludedTagsForEndpoint( + server, + configuredServers + ), + })); this.resolutionAwareSingleServer = fourKEnabled && this.servers.filter((server) => server.syncEnabled).length === 1 && @@ -90,9 +110,7 @@ class RadarrScanner (server) => server.syncEnabled && !server.is4k && - server.hostname === this.servers[0].hostname && - server.port === this.servers[0].port && - server.baseUrl === this.servers[0].baseUrl + isSameServarrSyncEndpoint(server, this.servers[0]) ); for (const server of this.servers) { @@ -103,7 +121,7 @@ class RadarrScanner 'info' ); - this.items = await runWithServarrServiceSnapshot( + const serverItems = await runWithServarrServiceSnapshot( 'radarr', server, async (current) => { @@ -118,7 +136,7 @@ class RadarrScanner if ( fourKEnabled && this.resolutionAwareSingleServer && - this.items.some( + serverItems.some( (movie) => movie.hasFile && is4kResolution(movie.movieFile?.mediaInfo.resolution) === true @@ -130,6 +148,52 @@ class RadarrScanner const server4k = this.enable4kMovie && server.is4k; const scansBothResolutions = this.resolutionAwareSingleServer && this.enable4kMovie; + + // Keep the provider response separate: excluded results still prove + // that a scan completed and should not trigger the empty-library + // safety path below. + const { included, excluded } = + partitionServarrItemsBySyncExcludedTags( + serverItems, + server.syncExcludedTags + ); + this.items = included; + for (const movie of excluded) { + if (!Number.isSafeInteger(movie.tmdbId) || movie.tmdbId <= 0) { + continue; + } + + // One resolution-aware endpoint owns both availability tracks; + // retain the media identity so neither request track is orphaned. + if (this.resolutionAwareSingleServer) { + this.scannedTmdbIds.add(movie.tmdbId); + this.scanned4kTmdbIds.add(movie.tmdbId); + } else { + const is4k = this.getMovieIs4k(movie, server); + (is4k ? this.scanned4kTmdbIds : this.scannedTmdbIds).add( + movie.tmdbId + ); + } + + const format = scansBothResolutions + ? this.getMovieIs4k(movie, server) + ? '4k' + : 'standard' + : server4k + ? '4k' + : 'standard'; + for (const serverId of getServarrSyncServerIdsForEndpoint( + server, + configuredServers + )) { + this.excludedMovies.push({ + tmdbId: movie.tmdbId, + serverId, + format, + }); + } + } + if (scansBothResolutions) { this.didScanStandard = true; this.didScan4k = true; @@ -139,7 +203,7 @@ class RadarrScanner this.didScanStandard = true; } - if (this.items.length === 0) { + if (serverItems.length === 0) { if (server4k) { this.server4kReturnedEmpty = true; } else { @@ -157,10 +221,10 @@ class RadarrScanner await this.loop(this.processRadarrMovie.bind(this), { sessionId }); - const hasCompleteMediaIdentity = this.items.every( + const hasCompleteMediaIdentity = serverItems.every( (movie) => Number.isSafeInteger(movie.tmdbId) && movie.tmdbId > 0 ); - if (this.items.length > 0 && hasCompleteMediaIdentity) { + if (serverItems.length > 0 && hasCompleteMediaIdentity) { const qualityTmdbIds = { standard: new Set(), '4k': new Set(), @@ -191,6 +255,11 @@ class RadarrScanner } } + await this.clearExcludedMovieAvailability( + configuredServers, + fourKEnabled + ); + // Only run cleanup if all servers of this profile type have sync enabled. // If any server is skipped, we can't distinguish truly orphaned media from // media that exists on an unscanned server (e.g. separate instances for @@ -334,6 +403,69 @@ class RadarrScanner return this.enable4kMovie && server.is4k; } + private async clearExcludedMovieAvailability( + configuredServers: RadarrSettings[], + fourKEnabled: boolean + ): Promise { + if (this.excludedMovies.length === 0) return; + + const excludedTmdbIds = [ + ...new Set(this.excludedMovies.map(({ tmdbId }) => tmdbId)), + ]; + const mediaItems: Media[] = []; + for (let offset = 0; offset < excludedTmdbIds.length; offset += 500) { + mediaItems.push( + ...(await getRepository(Media).find({ + where: { + mediaType: MediaType.MOVIE, + tmdbId: In(excludedTmdbIds.slice(offset, offset + 500)), + }, + })) + ); + } + const mediaIdsByTmdbId = new Map( + mediaItems.map((media) => [media.tmdbId, media.id]) + ); + const sources: ExcludedServarrAvailabilitySource[] = []; + + for (const excluded of this.excludedMovies) { + const mediaId = mediaIdsByTmdbId.get(excluded.tmdbId); + if (mediaId !== undefined) { + sources.push({ + mediaId, + serverId: excluded.serverId, + format: excluded.format, + }); + } + } + + for (let offset = 0; offset < mediaItems.length; offset += 50) { + const batch = mediaItems.slice(offset, offset + 50); + const batchIds = new Set(batch.map(({ id }) => id)); + const batchSources = sources.filter((source) => + batchIds.has(source.mediaId) + ); + if (batchSources.length === 0) continue; + + await runWithRequestAdmission( + batch.map( + (media) => `request-media:${MediaType.MOVIE}:${media.tmdbId}` + ), + () => + runWithServarrServiceSnapshots( + 'radarr', + configuredServers.filter((server) => server.syncEnabled), + () => reconcileExcludedServarrAvailability('radarr', batchSources), + { + requireExactAuthoritySet: true, + includeCurrent: (server) => + server.syncEnabled && (fourKEnabled || !server.is4k), + } + ) + ); + } + } + private async existsInAnyServer( tmdbId: number, is4k: boolean diff --git a/server/lib/scanners/radarr/radarr.test.ts b/server/lib/scanners/radarr/radarr.test.ts index d3506afa46..e6ecbdacd5 100644 --- a/server/lib/scanners/radarr/radarr.test.ts +++ b/server/lib/scanners/radarr/radarr.test.ts @@ -97,6 +97,17 @@ describe('Radarr Scanner', () => { getLibraryMoviesByTmdbIdImpl = async () => []; }); + it('scans an enabled endpoint even when its first alias has sync disabled', async () => { + configureRadarr([{ syncEnabled: false }, { syncEnabled: true }]); + let reads = 0; + getMoviesImpl = async () => { + reads++; + return []; + }; + await runWithMockTimers(() => radarrScanner.run()); + assert.equal(reads, 1); + }); + it('detects 4K files in a single mixed-resolution Radarr library', async () => { const mediaRepository = getRepository(Media); configureRadarr([{ syncEnabled: true }]); diff --git a/server/lib/scanners/servarrTagFilters.test.ts b/server/lib/scanners/servarrTagFilters.test.ts new file mode 100644 index 0000000000..88c030432e --- /dev/null +++ b/server/lib/scanners/servarrTagFilters.test.ts @@ -0,0 +1,28 @@ +import assert from 'node:assert/strict'; +import { it } from 'node:test'; +import { + getServarrSyncExcludedTagsForEndpoint, + getServarrSyncServerIdsForEndpoint, +} from './servarrTagFilters'; + +it('does not apply another protocol endpoint tag policy or clear its availability', () => { + const http = { + id: 1, + hostname: '127.0.0.1', + port: 8989, + baseUrl: '', + useSsl: false, + syncEnabled: true, + syncExcludedTags: [11], + }; + const https = { ...http, id: 2, useSsl: true, syncExcludedTags: [22] }; + const aliases = { ...http, id: 3, syncExcludedTags: [33] }; + assert.deepEqual( + getServarrSyncExcludedTagsForEndpoint(http, [http, https, aliases]), + [11, 33] + ); + assert.deepEqual( + getServarrSyncServerIdsForEndpoint(http, [http, https, aliases]), + [1, 3] + ); +}); diff --git a/server/lib/scanners/servarrTagFilters.ts b/server/lib/scanners/servarrTagFilters.ts new file mode 100644 index 0000000000..16c240d1b5 --- /dev/null +++ b/server/lib/scanners/servarrTagFilters.ts @@ -0,0 +1,79 @@ +type ServarrInstance = { + id: number; + hostname: string; + port: number; + useSsl?: boolean; + baseUrl?: string; + syncEnabled: boolean; + syncExcludedTags?: number[]; +}; + +type TaggedItem = { + tags?: readonly number[] | null; +}; + +export const isSameServarrSyncEndpoint = ( + left: ServarrInstance, + right: ServarrInstance +): boolean => + left.hostname === right.hostname && + left.port === right.port && + Boolean(left.useSsl) === Boolean(right.useSsl) && + left.baseUrl === right.baseUrl; + +export const getServarrSyncExcludedTagsForEndpoint = < + T extends ServarrInstance, +>( + instance: T, + instances: readonly T[] +): number[] => { + const excludedTags = new Set(); + + for (const candidate of instances) { + if ( + !candidate.syncEnabled || + !isSameServarrSyncEndpoint(candidate, instance) + ) { + continue; + } + + for (const tagId of candidate.syncExcludedTags ?? []) { + excludedTags.add(tagId); + } + } + + return [...excludedTags]; +}; + +export const getServarrSyncServerIdsForEndpoint = ( + instance: T, + instances: readonly T[] +): number[] => + instances + .filter( + (candidate) => + candidate.syncEnabled && isSameServarrSyncEndpoint(candidate, instance) + ) + .map(({ id }) => id); + +export const partitionServarrItemsBySyncExcludedTags = ( + items: readonly T[], + excludedTagIds: readonly number[] | undefined +): { included: T[]; excluded: T[] } => { + const excludedTags = new Set(excludedTagIds ?? []); + const included: T[] = []; + const excluded: T[] = []; + + for (const item of items) { + if ( + Array.isArray(item.tags) && + item.tags.some((tagId) => excludedTags.has(tagId)) + ) { + excluded.push(item); + } else { + included.push(item); + } + } + + return { included, excluded }; +}; diff --git a/server/lib/scanners/sonarr/index.ts b/server/lib/scanners/sonarr/index.ts index f1719218b0..372c4e1e5d 100644 --- a/server/lib/scanners/sonarr/index.ts +++ b/server/lib/scanners/sonarr/index.ts @@ -19,11 +19,20 @@ import Media from '@server/entity/Media'; import MediaIdentifier, { MediaIdentifierProvider, } from '@server/entity/MediaIdentifier'; -import MediaRequest from '@server/entity/MediaRequest'; +import MediaRequest, { + runWithRequestAdmission, +} from '@server/entity/MediaRequest'; import Season from '@server/entity/Season'; import SeasonRequest, { isActiveSeasonRequest, } from '@server/entity/SeasonRequest'; +import { + clearSonarrEpisodeAvailabilityForSeries, + clearSonarrEpisodeAvailabilityForService, + removeMissingSonarrEpisodeSeries, + syncSonarrEpisodeAvailability, + type SonarrSeasonAvailabilitySync, +} from '@server/lib/episodeAvailability'; import { getExternalRuntimeConfig } from '@server/lib/externalRuntimeConfig'; import { runMediaEntityMutation } from '@server/lib/mediaMutation'; import { upsertMediaSearchMetadata } from '@server/lib/mediaSearchMetadata'; @@ -33,22 +42,36 @@ import type { StatusBase, } from '@server/lib/scanners/baseScanner'; import BaseScanner from '@server/lib/scanners/baseScanner'; +import { + reconcileExcludedServarrAvailability, + type ExcludedServarrAvailabilitySource, +} from '@server/lib/scanners/excludedServarrAvailability'; import { forEachMediaCleanupBatch } from '@server/lib/scanners/mediaCleanupBatches'; +import { + getServarrSyncExcludedTagsForEndpoint, + getServarrSyncServerIdsForEndpoint, + isSameServarrSyncEndpoint, + partitionServarrItemsBySyncExcludedTags, +} from '@server/lib/scanners/servarrTagFilters'; import { externalSeasonNumberFor, findMediaForTvdbId, getSeasonMappingsForTvdbIdentifier, } from '@server/lib/seasonNumberMapping'; import { - ServarrServiceAuthorityChangedError, runWithServarrServiceSnapshot, runWithServarrServiceSnapshots, + ServarrServiceAuthorityChangedError, } from '@server/lib/serviceAdmission'; -import { getSettings, type SonarrSettings } from '@server/lib/settings'; +import { + getSettings, + MetadataProviderType, + type SonarrSettings, +} from '@server/lib/settings'; import { is4kResolution } from '@server/lib/videoResolution'; import { getHttpErrorDetails } from '@server/utils/httpError'; import { uniqWith } from 'lodash'; -import type { FindOptionsWhere } from 'typeorm'; +import { In, type FindOptionsWhere } from 'typeorm'; type SyncStatus = StatusBase & { currentServer: SonarrSettings; @@ -66,6 +89,13 @@ class SonarrScanner private scanned4kTvdbIds: Set = new Set(); private scannedTmdbIds: Set = new Set(); private scanned4kTmdbIds: Set = new Set(); + private excludedTvdbIds: Set = new Set(); + private excluded4kTvdbIds: Set = new Set(); + private excludedSeries: { + tvdbId: number; + serverId: number; + format: 'standard' | '4k'; + }[] = []; private currentServiceTvdbIds: Set = new Set(); private currentServiceTmdbIds: Set = new Set(); private currentService4kTvdbIds: Set = new Set(); @@ -100,6 +130,9 @@ class SonarrScanner this.scanned4kTvdbIds.clear(); this.scannedTmdbIds.clear(); this.scanned4kTmdbIds.clear(); + this.excludedTvdbIds.clear(); + this.excluded4kTvdbIds.clear(); + this.excludedSeries = []; this.didScanStandard = false; this.didScan4k = false; this.serverReturnedEmpty = false; @@ -107,15 +140,20 @@ class SonarrScanner try { const fourKEnabled = getSettings().main.enable4k !== false; - this.servers = uniqWith( - structuredClone( - settings.sonarr.filter((server) => fourKEnabled || !server.is4k) - ), - (sonarrA, sonarrB) => - sonarrA.hostname === sonarrB.hostname && - sonarrA.port === sonarrB.port && - sonarrA.baseUrl === sonarrB.baseUrl + const configuredServers = structuredClone( + settings.sonarr.filter( + (server) => server.syncEnabled && (fourKEnabled || !server.is4k) + ) ); + this.servers = uniqWith(configuredServers, (sonarrA, sonarrB) => + isSameServarrSyncEndpoint(sonarrA, sonarrB) + ).map((server) => ({ + ...server, + syncExcludedTags: getServarrSyncExcludedTagsForEndpoint( + server, + configuredServers + ), + })); this.resolutionAwareSingleServer = fourKEnabled && this.servers.filter((server) => server.syncEnabled).length === 1 && @@ -123,9 +161,7 @@ class SonarrScanner (server) => server.syncEnabled && !server.is4k && - server.hostname === this.servers[0].hostname && - server.port === this.servers[0].port && - server.baseUrl === this.servers[0].baseUrl + isSameServarrSyncEndpoint(server, this.servers[0]) ); if (fourKEnabled && this.resolutionAwareSingleServer) { this.enable4kShow = true; @@ -147,7 +183,8 @@ class SonarrScanner 'info' ); - this.items = await runWithServarrServiceSnapshot( + let episodeInventoryComplete = false; + const serverItems = await runWithServarrServiceSnapshot( 'sonarr', server, async (current) => { @@ -155,13 +192,87 @@ class SonarrScanner apiKey: current.apiKey, url: SonarrAPI.buildUrl(current, '/api/v3'), }); - return this.sonarrApi.getSeries(); + if (!getSettings().main.trackEpisodeAvailability) { + return this.sonarrApi.getSeries(); + } + + try { + const inventory = await this.sonarrApi.getSeries({ + strict: true, + requireTvdbId: false, + }); + episodeInventoryComplete = true; + return inventory; + } catch (error) { + this.log( + 'Could not confirm a complete Sonarr inventory; skipping episode availability cleanup for this scan.', + 'warn', + { + errorMessage: + error instanceof Error ? error.message : String(error), + server: current.name, + } + ); + return this.sonarrApi.getSeries(); + } } ); + // Keep the provider response separate: excluded results still prove + // that a scan completed and should not trigger the empty-library + // safety path below. + const { included, excluded } = + partitionServarrItemsBySyncExcludedTags( + serverItems, + server.syncExcludedTags + ); + this.items = included; + const server4k = this.enable4kShow && server.is4k; const scansBothResolutions = this.resolutionAwareSingleServer && this.enable4kShow; + for (const series of excluded) { + if (getSettings().main.trackEpisodeAvailability) { + await runWithServarrServiceSnapshot('sonarr', server, () => + clearSonarrEpisodeAvailabilityForSeries(server.id, series.id!) + ); + } + if (!Number.isSafeInteger(series.tvdbId) || series.tvdbId <= 0) { + continue; + } + + // One resolution-aware endpoint owns both availability tracks; + // retain the series identity so neither request track is orphaned. + if (this.resolutionAwareSingleServer) { + this.scannedTvdbIds.add(series.tvdbId); + this.scanned4kTvdbIds.add(series.tvdbId); + this.excludedTvdbIds.add(series.tvdbId); + this.excluded4kTvdbIds.add(series.tvdbId); + } else if (server4k) { + this.scanned4kTvdbIds.add(series.tvdbId); + this.excluded4kTvdbIds.add(series.tvdbId); + } else { + this.scannedTvdbIds.add(series.tvdbId); + this.excludedTvdbIds.add(series.tvdbId); + } + + const formats = scansBothResolutions + ? (['standard', '4k'] as const) + : ([server4k ? '4k' : 'standard'] as const); + for (const serverId of getServarrSyncServerIdsForEndpoint( + server, + configuredServers + )) { + for (const format of formats) { + this.excludedSeries.push({ + tvdbId: series.tvdbId, + serverId, + format, + }); + } + } + } + if (scansBothResolutions) { this.didScanStandard = true; this.didScan4k = true; @@ -171,7 +282,7 @@ class SonarrScanner this.didScanStandard = true; } - if (this.items.length === 0) { + if (serverItems.length === 0) { if (server4k) { this.server4kReturnedEmpty = true; } else { @@ -189,10 +300,23 @@ class SonarrScanner await this.loop(this.processSonarrSeries.bind(this), { sessionId }); - const hasCompleteMediaIdentity = this.items.every( + const hasCompleteMediaIdentity = serverItems.every( (series) => Number.isSafeInteger(series.tvdbId) && series.tvdbId > 0 ); - if (this.items.length > 0 && hasCompleteMediaIdentity) { + if ( + getSettings().main.trackEpisodeAvailability && + episodeInventoryComplete + ) { + await runWithServarrServiceSnapshot('sonarr', server, () => + serverItems.length === 0 + ? clearSonarrEpisodeAvailabilityForService(server.id) + : removeMissingSonarrEpisodeSeries( + server.id, + serverItems.map((series) => series.id!) + ) + ); + } + if (serverItems.length > 0 && hasCompleteMediaIdentity) { const formats = scansBothResolutions ? ([ { @@ -231,6 +355,11 @@ class SonarrScanner } } + await this.clearExcludedSeriesAvailability( + configuredServers, + fourKEnabled + ); + // Only run cleanup if all servers of this profile type have sync enabled. // If any server is skipped, we can't distinguish truly orphaned media from // media that exists on an unscanned server (e.g. separate instances for @@ -322,20 +451,65 @@ class SonarrScanner (season) => (season.statistics?.episodeFileCount ?? 0) > 0 ); const sonarrSeriesId = sonarrSeries.id; - const episodeFiles = + const settings = getSettings(); + const mayTrackEpisodeAvailability = + settings.main.trackEpisodeAvailability && + (settings.metadataSettings.tv === MetadataProviderType.TVDB || + settings.metadataSettings.anime === MetadataProviderType.TVDB); + let episodeFiles: + Awaited> | undefined; + let episodeListingFetched = false; + const hasValidSeriesId = + Number.isSafeInteger(sonarrSeriesId) && (sonarrSeriesId ?? 0) > 0; + if ( this.resolutionAwareSingleServer && hasEpisodeFiles && - typeof sonarrSeriesId === 'number' && - Number.isSafeInteger(sonarrSeriesId) && - sonarrSeriesId > 0 - ? await runWithServarrServiceSnapshot( - 'sonarr', - this.currentServer, - () => this.sonarrApi.getEpisodes(sonarrSeriesId, true) - ) - : this.resolutionAwareSingleServer - ? [] - : undefined; + hasValidSeriesId + ) { + episodeFiles = await runWithServarrServiceSnapshot( + 'sonarr', + this.currentServer, + () => this.sonarrApi.getEpisodes(sonarrSeriesId!, true) + ); + episodeListingFetched = true; + } else if (this.resolutionAwareSingleServer) { + episodeFiles = []; + } + if ( + mayTrackEpisodeAvailability && + hasValidSeriesId && + !episodeListingFetched + ) { + try { + episodeFiles = await runWithServarrServiceSnapshot( + 'sonarr', + this.currentServer, + () => + this.sonarrApi.getEpisodes( + sonarrSeriesId!, + this.resolutionAwareSingleServer + ) + ); + episodeListingFetched = true; + } catch (e) { + this.log( + 'Unable to refresh per-episode Sonarr availability; keeping the last successful scan.', + 'warn', + { + errorMessage: e instanceof Error ? e.message : String(e), + title: sonarrSeries.title, + } + ); + } + } + const expectedEpisodeCount = sonarrSeries.seasons.reduce( + (total, season) => total + (season.statistics?.totalEpisodeCount ?? 0), + 0 + ); + const episodeListingComplete = + episodeListingFetched && + expectedEpisodeCount > 0 && + (episodeFiles?.length ?? 0) >= expectedEpisodeCount; const mediaMatches = await findMediaForTvdbId( dataSource.manager, sonarrSeries.tvdbId @@ -350,7 +524,8 @@ class SonarrScanner sonarrSeries, media, server4k, - episodeFiles + episodeFiles, + episodeListingComplete ); } catch (e) { if (e instanceof ServarrServiceAuthorityChangedError) throw e; @@ -382,11 +557,101 @@ class SonarrScanner } } + private async clearExcludedSeriesAvailability( + configuredServers: SonarrSettings[], + fourKEnabled: boolean + ): Promise { + if (this.excludedSeries.length === 0) return; + + const excludedTvdbIds = [ + ...new Set(this.excludedSeries.map(({ tvdbId }) => tvdbId)), + ]; + const canonicalMedia: Media[] = []; + const matchingIdentifiers: MediaIdentifier[] = []; + for (let offset = 0; offset < excludedTvdbIds.length; offset += 500) { + const tvdbIdBatch = excludedTvdbIds.slice(offset, offset + 500); + const [canonicalBatch, identifierBatch] = await Promise.all([ + getRepository(Media).find({ + where: { mediaType: MediaType.TV, tvdbId: In(tvdbIdBatch) }, + }), + getRepository(MediaIdentifier).find({ + where: { + provider: MediaIdentifierProvider.TVDB, + value: In(tvdbIdBatch.map(String)), + media: { mediaType: MediaType.TV }, + }, + relations: { media: true }, + }), + ]); + canonicalMedia.push(...canonicalBatch); + matchingIdentifiers.push(...identifierBatch); + } + const mediaIdsByTvdbId = new Map>(); + const mediaItemsById = new Map(); + const addMediaId = (tvdbId: number, mediaId: number): void => { + const mediaIds = mediaIdsByTvdbId.get(tvdbId) ?? new Set(); + mediaIds.add(mediaId); + mediaIdsByTvdbId.set(tvdbId, mediaIds); + }; + + for (const media of canonicalMedia) { + mediaItemsById.set(media.id, media); + if (media.tvdbId != null) addMediaId(media.tvdbId, media.id); + } + for (const identifier of matchingIdentifiers) { + const tvdbId = Number(identifier.value); + if (identifier.media && Number.isSafeInteger(tvdbId) && tvdbId > 0) { + mediaItemsById.set(identifier.media.id, identifier.media); + addMediaId(tvdbId, identifier.media.id); + } + } + + const sources: ExcludedServarrAvailabilitySource[] = []; + for (const excluded of this.excludedSeries) { + for (const mediaId of mediaIdsByTvdbId.get(excluded.tvdbId) ?? []) { + sources.push({ + mediaId, + serverId: excluded.serverId, + format: excluded.format, + }); + } + } + + const mediaItems = [...new Set(sources.map(({ mediaId }) => mediaId))] + .map((mediaId) => mediaItemsById.get(mediaId)) + .filter((media): media is Media => media !== undefined); + + for (let offset = 0; offset < mediaItems.length; offset += 50) { + const batch = mediaItems.slice(offset, offset + 50); + const batchIds = new Set(batch.map(({ id }) => id)); + const batchSources = sources.filter((source) => + batchIds.has(source.mediaId) + ); + if (batchSources.length === 0) continue; + + await runWithRequestAdmission( + batch.map((media) => `request-media:${MediaType.TV}:${media.tmdbId}`), + () => + runWithServarrServiceSnapshots( + 'sonarr', + configuredServers.filter((server) => server.syncEnabled), + () => reconcileExcludedServarrAvailability('sonarr', batchSources), + { + requireExactAuthoritySet: true, + includeCurrent: (server) => + server.syncEnabled && (fourKEnabled || !server.is4k), + } + ) + ); + } + } + private async processSonarrSeriesForMedia( sonarrSeries: SonarrSeries, media: Media | undefined, server4k: boolean, - episodeFiles?: Awaited> + episodeFiles?: Awaited>, + episodeListingComplete = false ): Promise { let tvShow: TmdbTvScanDetails | TmdbTvDetails; if (!media || !media.tmdbId) { @@ -409,6 +674,11 @@ class SonarrScanner if (!this.resolutionAwareSingleServer) { (server4k ? this.scanned4kTmdbIds : this.scannedTmdbIds).add(tmdbId); } + const tmdbIdentifiesAnime = tvShow.keywords.results.some( + (keyword) => keyword.id === ANIME_KEYWORD_ID + ); + const seriesUsesAnimeMetadata = + this.isAnimeSeries(sonarrSeries) || tmdbIdentifiesAnime; tvShow = await this.applyMetadataProvider( tvShow, this.isAnimeSeries(sonarrSeries) @@ -549,6 +819,45 @@ class SonarrScanner tmdbId, mediaType: MediaType.TV, }); + const settingsForEpisodeAvailability = getSettings(); + const episodeMetadataProvider = seriesUsesAnimeMetadata + ? settingsForEpisodeAvailability.metadataSettings.anime + : settingsForEpisodeAvailability.metadataSettings.tv; + const displayedEpisodeMetadataProvider = tmdbIdentifiesAnime + ? settingsForEpisodeAvailability.metadataSettings.anime + : settingsForEpisodeAvailability.metadataSettings.tv; + if ( + updatedMedia && + Number.isSafeInteger(sonarrSeries.id) && + (sonarrSeries.id ?? 0) > 0 && + settingsForEpisodeAvailability.main.trackEpisodeAvailability && + episodeListingComplete && + episodeFiles + ) { + const episodeOrder = sonarrSeries.seasonType?.toLowerCase(); + const hasCompatibleEpisodeOrder = + !sonarrSeries.useSceneNumbering && + (!episodeOrder || + episodeOrder === 'standard' || + episodeOrder === 'official'); + await runWithServarrServiceSnapshot('sonarr', this.currentServer, () => + episodeMetadataProvider === MetadataProviderType.TVDB && + displayedEpisodeMetadataProvider === MetadataProviderType.TVDB && + hasCompatibleEpisodeOrder + ? this.syncEpisodeAvailabilityForSeries( + updatedMedia, + sonarrSeries, + processableSeasons, + seasonMappings, + episodeFiles, + server4k + ) + : clearSonarrEpisodeAvailabilityForSeries( + this.currentServer.id, + sonarrSeries.id! + ) + ); + } if (updatedMedia && this.isAnimeSeries(sonarrSeries)) { await this.persistAnimeIdentifiers(updatedMedia, sonarrSeries); } @@ -581,6 +890,87 @@ class SonarrScanner return tmdbId; } + private async syncEpisodeAvailabilityForSeries( + media: Media, + sonarrSeries: SonarrSeries, + processableSeasons: ProcessableSeason[], + seasonMappings: ReturnType, + episodes: Awaited>, + server4k: boolean + ): Promise { + const databaseSeasons = await getRepository(Season).find({ + where: { media: { id: media.id } }, + }); + const databaseSeasonByNumber = new Map( + databaseSeasons.map((season) => [season.seasonNumber, season]) + ); + const metadataSeasonByExternalNumber = new Map(); + const ambiguousExternalSeasonNumbers = new Set(); + + for (const season of processableSeasons) { + const externalSeasonNumber = externalSeasonNumberFor( + season.seasonNumber, + seasonMappings + ); + const existingSeasonNumber = + metadataSeasonByExternalNumber.get(externalSeasonNumber); + if ( + existingSeasonNumber !== undefined && + existingSeasonNumber !== season.seasonNumber + ) { + metadataSeasonByExternalNumber.delete(externalSeasonNumber); + ambiguousExternalSeasonNumbers.add(externalSeasonNumber); + } else if (!ambiguousExternalSeasonNumbers.has(externalSeasonNumber)) { + metadataSeasonByExternalNumber.set( + externalSeasonNumber, + season.seasonNumber + ); + } + } + + const episodesBySeason = new Map< + number, + SonarrSeasonAvailabilitySync['episodes'] + >(); + for (const episode of episodes) { + if (!episode.hasFile || !Number.isSafeInteger(episode.episodeNumber)) { + continue; + } + const metadataSeasonNumber = metadataSeasonByExternalNumber.get( + episode.seasonNumber + ); + if (metadataSeasonNumber === undefined) continue; + const databaseSeason = databaseSeasonByNumber.get(metadataSeasonNumber); + if (!databaseSeason) continue; + + const is4k = this.resolutionAwareSingleServer + ? is4kResolution(episode.fileResolution) + : server4k; + // Unknown resolution cannot confirm removal from either quality. + if (is4k === undefined) return; + + const seasonEpisodes = episodesBySeason.get(databaseSeason.id) ?? []; + seasonEpisodes.push({ episodeNumber: episode.episodeNumber, is4k }); + episodesBySeason.set(databaseSeason.id, seasonEpisodes); + } + + await syncSonarrEpisodeAvailability( + this.currentServer.id, + sonarrSeries.id!, + processableSeasons.flatMap((season) => { + const databaseSeason = databaseSeasonByNumber.get(season.seasonNumber); + return databaseSeason + ? [ + { + seasonId: databaseSeason.id, + episodes: episodesBySeason.get(databaseSeason.id) ?? [], + }, + ] + : []; + }) + ); + } + private async applyMetadataProvider( tvShow: TmdbTvScanDetails | TmdbTvDetails, sonarrIdentifiesAnime = false @@ -972,16 +1362,30 @@ class SonarrScanner const visitedMedia = new Set(); const scannedTvdbIds = is4k ? this.scanned4kTvdbIds : this.scannedTvdbIds; const scannedTmdbIds = is4k ? this.scanned4kTmdbIds : this.scannedTmdbIds; + const excludedTvdbIds = is4k + ? this.excluded4kTvdbIds + : this.excludedTvdbIds; + const hasExcludedTvdbIds = excludedTvdbIds.size > 0; await forEachMediaCleanupBatch( where, async (media) => { if (visitedMedia.has(media.id)) return; visitedMedia.add(media.id); + const hasExcludedTvdbIdentifier = + hasExcludedTvdbIds && + Boolean( + media.identifiers?.some( + (identifier) => + identifier.provider === MediaIdentifierProvider.TVDB && + excludedTvdbIds.has(Number(identifier.value)) + ) + ); if ( !media.tvdbId || scannedTvdbIds.has(media.tvdbId) || - scannedTmdbIds.has(media.tmdbId) + scannedTmdbIds.has(media.tmdbId) || + hasExcludedTvdbIdentifier ) { return; } @@ -994,7 +1398,13 @@ class SonarrScanner ); } }, - { relations: { seasons: true, requests: { seasons: true } } } + { + relations: { + seasons: true, + requests: { seasons: true }, + ...(hasExcludedTvdbIds ? { identifiers: true } : {}), + }, + } ); } diff --git a/server/lib/scanners/sonarr/sonarr.test.ts b/server/lib/scanners/sonarr/sonarr.test.ts index 9808d4f65e..cb8ef5a2fb 100644 --- a/server/lib/scanners/sonarr/sonarr.test.ts +++ b/server/lib/scanners/sonarr/sonarr.test.ts @@ -11,6 +11,7 @@ import { MediaType, } from '@server/constants/media'; import { getRepository } from '@server/datasource'; +import EpisodeAvailability from '@server/entity/EpisodeAvailability'; import Media from '@server/entity/Media'; import MediaIdentifier, { MediaIdentifierProvider, @@ -21,6 +22,7 @@ import MediaServiceStatus from '@server/entity/MediaServiceStatus'; import Season from '@server/entity/Season'; import SeasonRequest from '@server/entity/SeasonRequest'; import { User } from '@server/entity/User'; +import { syncSonarrEpisodeAvailability } from '@server/lib/episodeAvailability'; import requestDispatchManager from '@server/lib/requestDispatch'; import { sonarrScanner } from '@server/lib/scanners/sonarr'; import type { SonarrSettings } from '@server/lib/settings'; @@ -244,6 +246,38 @@ function configureSonarr(overrides: Partial[] = [{}]): void { } describe('Sonarr Scanner', () => { + it('clears the scanned episode source when a series becomes explicitly tag-excluded', async () => { + configureSonarr([{ id: 0, syncExcludedTags: [11] }]); + getSettings().main.trackEpisodeAvailability = true; + const media = await getRepository(Media).save( + new Media({ + tmdbId: 890999, + tvdbId: 100, + mediaType: MediaType.TV, + status: MediaStatus.AVAILABLE, + }) + ); + const season = await getRepository(Season).save( + new Season({ + media: Promise.resolve(media), + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + }) + ); + await syncSonarrEpisodeAvailability(0, 1, [ + { seasonId: season.id, episodes: [{ episodeNumber: 1, is4k: false }] }, + ]); + assert.equal(await getRepository(EpisodeAvailability).count(), 1); + getSeriesImpl = async () => [fakeSonarrSeries({ tags: [11] })]; + try { + await runWithMockTimers(() => sonarrScanner.run()); + } finally { + getSettings().main.trackEpisodeAvailability = false; + } + assert.equal(await getRepository(EpisodeAvailability).count(), 0); + assert.ok(await getRepository(Media).findOneBy({ id: media.id })); + }); + beforeEach(() => { getSeriesImpl = async () => []; getEpisodesImpl = async (seriesId) => { @@ -268,6 +302,17 @@ describe('Sonarr Scanner', () => { getTvShowImpl = async () => fakeTmdbShow(1); }); + it('scans an enabled endpoint even when its first alias has sync disabled', async () => { + configureSonarr([{ syncEnabled: false }, { syncEnabled: true }]); + let reads = 0; + getSeriesImpl = async () => { + reads++; + return []; + }; + await runWithMockTimers(() => sonarrScanner.run()); + assert.equal(reads, 1); + }); + it('detects mixed HD and 4K episode files in a single Sonarr library', async () => { const tmdbId = 890201; const seriesId = 890202; diff --git a/server/lib/serviceAdmission.ts b/server/lib/serviceAdmission.ts index 5e9158ae5e..38c5601738 100644 --- a/server/lib/serviceAdmission.ts +++ b/server/lib/serviceAdmission.ts @@ -56,8 +56,23 @@ export type ServarrServiceAuthority = Pick< 'id' | 'hostname' | 'port' | 'useSsl' | 'baseUrl' | 'apiKey' > & Partial> & + Partial<{ syncExcludedTags: number[] }> & Partial>; +const hasSameSyncExcludedTags = ( + current: readonly number[] | undefined, + snapshot: readonly number[] | undefined +): boolean => { + const currentTags = [...(current ?? [])].sort((left, right) => left - right); + const snapshotTags = [...(snapshot ?? [])].sort( + (left, right) => left - right + ); + return ( + currentTags.length === snapshotTags.length && + currentTags.every((tagId, index) => tagId === snapshotTags[index]) + ); +}; + export const hasSameServarrServiceAuthority = ( current: ServarrServiceAuthority, snapshot: ServarrServiceAuthority @@ -70,6 +85,10 @@ export const hasSameServarrServiceAuthority = ( current.apiKey === snapshot.apiKey && current.syncEnabled === snapshot.syncEnabled && Boolean(current.is4k) === Boolean(snapshot.is4k) && + hasSameSyncExcludedTags( + current.syncExcludedTags, + snapshot.syncExcludedTags + ) && (current.backend ?? 'readarr') === (snapshot.backend ?? 'readarr') && (current.serviceType ?? 'ebook') === (snapshot.serviceType ?? 'ebook'); diff --git a/server/lib/settings/index.ts b/server/lib/settings/index.ts index 894ea29712..9407dcbe94 100644 --- a/server/lib/settings/index.ts +++ b/server/lib/settings/index.ts @@ -7,6 +7,7 @@ import { type EnabledMediaCategories, type MediaCategoryKey, } from '@server/constants/mediaCategories'; +import { MetadataProviderType } from '@server/constants/metadata'; import { defaultProwlarrCategoryMappings, type ProwlarrCategoryMappings, @@ -31,6 +32,7 @@ import { withSettingsFileLock, writePrivateSettingsFile, } from './fileSecurity'; +export { MetadataProviderType } from '@server/constants/metadata'; export { MAX_SETTINGS_FILE_BYTES, assertSettingsFileSize }; @@ -49,6 +51,7 @@ export interface Library { name: string; enabled: boolean; type: 'show' | 'movie' | 'music' | 'book'; + episodeOrderProvider?: MetadataProviderType; lastScan?: number; } @@ -377,6 +380,7 @@ export interface DVRSettings { preventSearch: boolean; tagRequests: boolean; overrideRule: number[]; + downloadQueueSize?: number; } export interface ServiceRequestButtonSettings { @@ -387,6 +391,8 @@ export interface ServiceRequestButtonSettings { export interface RadarrSettings extends DVRSettings, ServiceRequestButtonSettings { minimumAvailability: string; + /** Tags that exclude matching library entries from synchronization. */ + syncExcludedTags?: number[]; } /** Whisparr's scene-focused v3 API uses Radarr-shaped service settings. */ @@ -406,6 +412,8 @@ export interface SonarrSettings animeTags?: number[]; enableSeasonFolders: boolean; monitorNewItems: 'all' | 'none' | 'latest'; + /** Tags that exclude matching library entries from synchronization. */ + syncExcludedTags?: number[]; } export interface SportarrSettings { @@ -495,11 +503,6 @@ interface Quota { quotaDays?: number; } -export enum MetadataProviderType { - TMDB = 'tmdb', - TVDB = 'tvdb', -} - export interface MetadataSettings { tv: MetadataProviderType; anime: MetadataProviderType; @@ -590,6 +593,7 @@ export interface MainSettings { tvSeasonWatchGateEnabled: boolean; personMovieBulkRequestsEnabled: boolean; enableSpecialEpisodes: boolean; + trackEpisodeAvailability: boolean; locale: string; youtubeUrl: string; versionCheck: boolean; @@ -1015,6 +1019,7 @@ class Settings { tvSeasonWatchGateEnabled: false, personMovieBulkRequestsEnabled: false, enableSpecialEpisodes: false, + trackEpisodeAvailability: false, locale: 'en', youtubeUrl: '', versionCheck: true, @@ -2091,6 +2096,7 @@ class Settings { tvSeasonWatchGateEnabled: false, personMovieBulkRequestsEnabled: false, enableSpecialEpisodes: false, + trackEpisodeAvailability: false, locale: 'en', youtubeUrl: '', versionCheck: true, diff --git a/server/lib/sqliteFileSecurity.test.ts b/server/lib/sqliteFileSecurity.test.ts index d444f50fd0..67a3333a98 100644 --- a/server/lib/sqliteFileSecurity.test.ts +++ b/server/lib/sqliteFileSecurity.test.ts @@ -96,6 +96,7 @@ describe('SQLite file permissions', () => { NODE_ENV: 'production', CONFIG_DIRECTORY: parent, TS_NODE_PROJECT: path.resolve(__dirname, '../tsconfig.json'), + TS_NODE_FILES: 'true', }, encoding: 'utf8', timeout: 30000, diff --git a/server/migration/postgres/1792710000000-AddOverrideRuleProductionCountries.ts b/server/migration/postgres/1792710000000-AddOverrideRuleProductionCountries.ts new file mode 100644 index 0000000000..60ff4e776e --- /dev/null +++ b/server/migration/postgres/1792710000000-AddOverrideRuleProductionCountries.ts @@ -0,0 +1,23 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddOverrideRuleProductionCountries1792710000000 implements MigrationInterface { + name = 'AddOverrideRuleProductionCountries1792710000000'; + + public async up(queryRunner: QueryRunner): Promise { + if ( + !(await queryRunner.hasColumn('override_rule', 'productionCountries')) + ) { + await queryRunner.query( + 'ALTER TABLE "override_rule" ADD COLUMN "productionCountries" character varying' + ); + } + } + + public async down(queryRunner: QueryRunner): Promise { + if (await queryRunner.hasColumn('override_rule', 'productionCountries')) { + await queryRunner.query( + 'ALTER TABLE "override_rule" DROP COLUMN "productionCountries"' + ); + } + } +} diff --git a/server/migration/postgres/1792720000000-AddOverrideRuleLanguageProfile.ts b/server/migration/postgres/1792720000000-AddOverrideRuleLanguageProfile.ts new file mode 100644 index 0000000000..29024763ca --- /dev/null +++ b/server/migration/postgres/1792720000000-AddOverrideRuleLanguageProfile.ts @@ -0,0 +1,21 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddOverrideRuleLanguageProfile1792720000000 implements MigrationInterface { + name = 'AddOverrideRuleLanguageProfile1792720000000'; + + public async up(queryRunner: QueryRunner): Promise { + if (!(await queryRunner.hasColumn('override_rule', 'languageProfileId'))) { + await queryRunner.query( + 'ALTER TABLE "override_rule" ADD COLUMN "languageProfileId" integer' + ); + } + } + + public async down(queryRunner: QueryRunner): Promise { + if (await queryRunner.hasColumn('override_rule', 'languageProfileId')) { + await queryRunner.query( + 'ALTER TABLE "override_rule" DROP COLUMN "languageProfileId"' + ); + } + } +} diff --git a/server/migration/postgres/1793400000000-RequestFutureSeasons.ts b/server/migration/postgres/1793400000000-RequestFutureSeasons.ts new file mode 100644 index 0000000000..b84d2f3e33 --- /dev/null +++ b/server/migration/postgres/1793400000000-RequestFutureSeasons.ts @@ -0,0 +1,25 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class RequestFutureSeasons1793400000000 implements MigrationInterface { + name = 'RequestFutureSeasons1793400000000'; + + public async up(queryRunner: QueryRunner): Promise { + if ( + (await queryRunner.hasTable('media_request')) && + !(await queryRunner.hasColumn('media_request', 'monitorFutureSeasons')) + ) { + await queryRunner.query( + 'ALTER TABLE "media_request" ADD COLUMN "monitorFutureSeasons" boolean' + ); + } + } + + public async down(queryRunner: QueryRunner): Promise { + if ( + (await queryRunner.hasTable('media_request')) && + (await queryRunner.hasColumn('media_request', 'monitorFutureSeasons')) + ) { + await queryRunner.dropColumn('media_request', 'monitorFutureSeasons'); + } + } +} diff --git a/server/migration/postgres/1793440362000-AddEpisodeAvailability.ts b/server/migration/postgres/1793440362000-AddEpisodeAvailability.ts new file mode 100644 index 0000000000..7b9bc29401 --- /dev/null +++ b/server/migration/postgres/1793440362000-AddEpisodeAvailability.ts @@ -0,0 +1,35 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddEpisodeAvailability1793440362000 implements MigrationInterface { + name = 'AddEpisodeAvailability1793440362000'; + + public async up(queryRunner: QueryRunner): Promise { + if (!(await queryRunner.hasTable('episode_availability'))) { + await queryRunner.query(` + CREATE TABLE "episode_availability" ( + "id" SERIAL NOT NULL, + "episodeNumber" integer NOT NULL, + "sourceType" varchar(16) NOT NULL, + "sourceId" varchar(80) NOT NULL, + "metadataProvider" varchar(16) NOT NULL, + "externalSeriesId" integer NOT NULL, + "is4k" boolean NOT NULL DEFAULT false, + "seasonId" integer NOT NULL, + CONSTRAINT "PK_EPISODE_AVAILABILITY" PRIMARY KEY ("id"), + CONSTRAINT "FK_EPISODE_AVAILABILITY_SEASON" FOREIGN KEY ("seasonId") REFERENCES "season" ("id") ON DELETE CASCADE, + CONSTRAINT "UNIQUE_EPISODE_AVAILABILITY" UNIQUE ("seasonId", "episodeNumber", "sourceType", "sourceId", "metadataProvider", "externalSeriesId", "is4k") + ) + `); + await queryRunner.query( + 'CREATE INDEX "IDX_EPISODE_AVAILABILITY_SEASON_SOURCE" ON "episode_availability" ("seasonId", "sourceType", "sourceId")' + ); + await queryRunner.query( + 'CREATE INDEX "IDX_EPISODE_AVAILABILITY_SOURCE_SERIES" ON "episode_availability" ("sourceType", "sourceId", "metadataProvider", "externalSeriesId")' + ); + } + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query('DROP TABLE IF EXISTS "episode_availability"'); + } +} diff --git a/server/migration/postgres/mediaUniqueness.test.ts b/server/migration/postgres/mediaUniqueness.test.ts index f93c9d0dc1..d35ba8b65a 100644 --- a/server/migration/postgres/mediaUniqueness.test.ts +++ b/server/migration/postgres/mediaUniqueness.test.ts @@ -7,7 +7,9 @@ import { EnforceScreenBlocklistUniqueness1782700000000 } from './1782700000000-E import { EnforceCanonicalBookIdentifierUniqueness1782800000000 } from './1782800000000-EnforceCanonicalBookIdentifierUniqueness'; import { EnforceMusicMediaUniqueness1782900000000 } from './1782900000000-EnforceMusicMediaUniqueness'; -const postgresUrl = process.env.SEERR_TEST_POSTGRES_URL; +const postgresUrl = + process.env.SEERR_MIGRATION_TEST_POSTGRES_URL ?? + process.env.SEERR_TEST_POSTGRES_URL; const postgresTest = postgresUrl ? test : test.skip; const createMigrationTables = async (queryRunner: QueryRunner) => { diff --git a/server/migration/sqlite/1792710000000-AddOverrideRuleProductionCountries.ts b/server/migration/sqlite/1792710000000-AddOverrideRuleProductionCountries.ts new file mode 100644 index 0000000000..374be9017c --- /dev/null +++ b/server/migration/sqlite/1792710000000-AddOverrideRuleProductionCountries.ts @@ -0,0 +1,23 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddOverrideRuleProductionCountries1792710000000 implements MigrationInterface { + name = 'AddOverrideRuleProductionCountries1792710000000'; + + public async up(queryRunner: QueryRunner): Promise { + if ( + !(await queryRunner.hasColumn('override_rule', 'productionCountries')) + ) { + await queryRunner.query( + 'ALTER TABLE "override_rule" ADD COLUMN "productionCountries" varchar' + ); + } + } + + public async down(queryRunner: QueryRunner): Promise { + if (await queryRunner.hasColumn('override_rule', 'productionCountries')) { + await queryRunner.query( + 'ALTER TABLE "override_rule" DROP COLUMN "productionCountries"' + ); + } + } +} diff --git a/server/migration/sqlite/1792720000000-AddOverrideRuleLanguageProfile.ts b/server/migration/sqlite/1792720000000-AddOverrideRuleLanguageProfile.ts new file mode 100644 index 0000000000..29024763ca --- /dev/null +++ b/server/migration/sqlite/1792720000000-AddOverrideRuleLanguageProfile.ts @@ -0,0 +1,21 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddOverrideRuleLanguageProfile1792720000000 implements MigrationInterface { + name = 'AddOverrideRuleLanguageProfile1792720000000'; + + public async up(queryRunner: QueryRunner): Promise { + if (!(await queryRunner.hasColumn('override_rule', 'languageProfileId'))) { + await queryRunner.query( + 'ALTER TABLE "override_rule" ADD COLUMN "languageProfileId" integer' + ); + } + } + + public async down(queryRunner: QueryRunner): Promise { + if (await queryRunner.hasColumn('override_rule', 'languageProfileId')) { + await queryRunner.query( + 'ALTER TABLE "override_rule" DROP COLUMN "languageProfileId"' + ); + } + } +} diff --git a/server/migration/sqlite/1793400000000-RequestFutureSeasons.ts b/server/migration/sqlite/1793400000000-RequestFutureSeasons.ts new file mode 100644 index 0000000000..b84d2f3e33 --- /dev/null +++ b/server/migration/sqlite/1793400000000-RequestFutureSeasons.ts @@ -0,0 +1,25 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class RequestFutureSeasons1793400000000 implements MigrationInterface { + name = 'RequestFutureSeasons1793400000000'; + + public async up(queryRunner: QueryRunner): Promise { + if ( + (await queryRunner.hasTable('media_request')) && + !(await queryRunner.hasColumn('media_request', 'monitorFutureSeasons')) + ) { + await queryRunner.query( + 'ALTER TABLE "media_request" ADD COLUMN "monitorFutureSeasons" boolean' + ); + } + } + + public async down(queryRunner: QueryRunner): Promise { + if ( + (await queryRunner.hasTable('media_request')) && + (await queryRunner.hasColumn('media_request', 'monitorFutureSeasons')) + ) { + await queryRunner.dropColumn('media_request', 'monitorFutureSeasons'); + } + } +} diff --git a/server/migration/sqlite/1793440362000-AddEpisodeAvailability.ts b/server/migration/sqlite/1793440362000-AddEpisodeAvailability.ts new file mode 100644 index 0000000000..fc421a5b72 --- /dev/null +++ b/server/migration/sqlite/1793440362000-AddEpisodeAvailability.ts @@ -0,0 +1,34 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddEpisodeAvailability1793440362000 implements MigrationInterface { + name = 'AddEpisodeAvailability1793440362000'; + + public async up(queryRunner: QueryRunner): Promise { + if (!(await queryRunner.hasTable('episode_availability'))) { + await queryRunner.query(` + CREATE TABLE "episode_availability" ( + "id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, + "episodeNumber" integer NOT NULL, + "sourceType" varchar(16) NOT NULL, + "sourceId" varchar(80) NOT NULL, + "metadataProvider" varchar(16) NOT NULL, + "externalSeriesId" integer NOT NULL, + "is4k" integer NOT NULL DEFAULT 0, + "seasonId" integer NOT NULL, + CONSTRAINT "FK_EPISODE_AVAILABILITY_SEASON" FOREIGN KEY ("seasonId") REFERENCES "season" ("id") ON DELETE CASCADE, + CONSTRAINT "UNIQUE_EPISODE_AVAILABILITY" UNIQUE ("seasonId", "episodeNumber", "sourceType", "sourceId", "metadataProvider", "externalSeriesId", "is4k") + ) + `); + await queryRunner.query( + 'CREATE INDEX "IDX_EPISODE_AVAILABILITY_SEASON_SOURCE" ON "episode_availability" ("seasonId", "sourceType", "sourceId")' + ); + await queryRunner.query( + 'CREATE INDEX "IDX_EPISODE_AVAILABILITY_SOURCE_SERIES" ON "episode_availability" ("sourceType", "sourceId", "metadataProvider", "externalSeriesId")' + ); + } + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query('DROP TABLE IF EXISTS "episode_availability"'); + } +} diff --git a/server/models/Tv.ts b/server/models/Tv.ts index fbc6643f36..4a3ac68dab 100644 --- a/server/models/Tv.ts +++ b/server/models/Tv.ts @@ -6,6 +6,7 @@ import type { TmdbTvRatingResult, TmdbTvSeasonResult, } from '@server/api/themoviedb/interfaces'; +import type { EpisodeAvailabilitySourceType } from '@server/entity/EpisodeAvailability'; import type Media from '@server/entity/Media'; import type { Video } from './Movie'; import type { @@ -41,6 +42,15 @@ interface Episode { seasonNumber: number; showId: number; stillPath?: string; + sonarrAvailability?: { + hd: boolean; + fourK: boolean; + }; + availabilitySources?: { + sourceType: EpisodeAvailabilitySourceType; + hd: boolean; + fourK: boolean; + }[]; voteAverage: number; voteCount: number; } diff --git a/server/routes/editions.ts b/server/routes/editions.ts index c70ba8492d..076d144235 100644 --- a/server/routes/editions.ts +++ b/server/routes/editions.ts @@ -4,9 +4,10 @@ import { getLibraryBookService, planSeriesWithNarrator, } from '@server/lib/editionCompare'; +import { getExternalRuntimeConfig } from '@server/lib/externalRuntimeConfig'; import { Permission } from '@server/lib/permissions'; -import { getSettings } from '@server/lib/settings'; import logger from '@server/logger'; +import { readarrServiceSupportsFormat } from '@server/utils/readarrService'; import { Router } from 'express'; import rateLimit from 'express-rate-limit'; @@ -43,12 +44,37 @@ editionRoutes.get('/book', async (req, res, next) => { .status(400) .json({ status: 400, message: 'format must be ebook or audiobook.' }); } + const rawServerId = req.query.serverId; + const serverId = + typeof rawServerId === 'number' || + (typeof rawServerId === 'string' && /^\d+$/.test(rawServerId)) + ? Number(rawServerId) + : undefined; + if ( + rawServerId !== undefined && + (serverId === undefined || + !Number.isSafeInteger(serverId) || + serverId < 0 || + !getExternalRuntimeConfig().readarr.some( + (server) => + server.id === serverId && + server.backend !== 'bindery' && + readarrServiceSupportsFormat(server, format) + )) + ) { + return res + .status(400) + .json({ status: 400, message: 'Invalid edition destination.' }); + } const term = str(req.query.term, 256); const foreignBookId = str(req.query.foreignBookId, 256); try { return res.status(200).json( await compareBookEditions({ mediaId: parseId(req.query.mediaId), + bookId: str(req.query.bookId, 2048), + serverId, + author: str(req.query.author, 256), format, term, foreignBookId, @@ -70,7 +96,7 @@ editionRoutes.get('/series-narrators', async (req, res, next) => { if (!title) { return res.status(400).json({ status: 400, message: 'title is required.' }); } - const servers = getSettings().readarr.filter( + const servers = getExternalRuntimeConfig().readarr.filter( (server) => server.backend !== 'bindery' && server.serviceType === 'audiobook' ); @@ -126,7 +152,7 @@ editionRoutes.post('/series-narrators/prefer', async (req, res) => { .status(400) .json({ error: 'A series and narrator are required.' }); } - const servers = getSettings().readarr.filter( + const servers = getExternalRuntimeConfig().readarr.filter( (server) => server.backend !== 'bindery' && server.serviceType === 'audiobook' ); diff --git a/server/routes/interfaceThemes.openapi.test.ts b/server/routes/interfaceThemes.openapi.test.ts new file mode 100644 index 0000000000..5206699a00 --- /dev/null +++ b/server/routes/interfaceThemes.openapi.test.ts @@ -0,0 +1,115 @@ +import { getSettings } from '@server/lib/settings'; +import router from '@server/routes'; +import { setupTestDb } from '@server/test/db'; +import express from 'express'; +import * as OpenApiValidator from 'express-openapi-validator'; +import session from 'express-session'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { before, beforeEach, describe, it } from 'node:test'; +import request from 'supertest'; + +setupTestDb(); + +describe('interface packages through the production API contract', () => { + const app = express(); + before(() => { + app.use(express.json()); + app.use( + session({ + secret: 'theme-contract-test', + resave: false, + saveUninitialized: false, + cookie: { secure: 'auto' }, + }) + ); + app.use( + OpenApiValidator.middleware({ + apiSpec: path.join(process.cwd(), 'seerr-api.yml'), + validateRequests: true, + validateSecurity: false, + }) + ); + app.use('/api/v1', router); + app.use( + ( + error: { status?: number; message?: string }, + _req: express.Request, + res: express.Response, + _next: express.NextFunction + ) => { + void _next; + res.status(error.status ?? 500).json({ message: error.message }); + } + ); + }); + beforeEach(() => { + getSettings().main.localLogin = true; + }); + + it('serves the catalog and every built-in stylesheet before authentication', async () => { + const catalog = await request(app).get('/api/v1/interface-themes'); + assert.equal(catalog.status, 200, JSON.stringify(catalog.body)); + for (const theme of catalog.body.themes) { + const response = await request(app).get( + `/api/v1/interface-themes/${theme.id}/theme.css` + ); + assert.equal(response.status, 200); + assert.match(response.headers['content-type'], /^text\/css/); + assert.equal(response.headers['x-content-type-options'], 'nosniff'); + assert.ok(response.text.includes(theme.id)); + } + assert.equal( + ( + await request(app).get( + '/api/v1/interface-themes/not-installed/theme.css' + ) + ).status, + 404 + ); + }); + + it('persists Persius and both existing themes and restores each in the authenticated profile', async () => { + const agent = request.agent(app); + const login = await agent + .post('/api/v1/auth/local') + .send({ email: 'admin@seerr.dev', password: 'test1234' }); + assert.equal(login.status, 200); + const id = login.body.id; + for (const theme of ['persiusNG', 'seerrNGJ', 'seerrOrig']) { + const result = await agent + .post(`/api/v1/user/${id}/settings/interface-theme`) + .send({ theme }); + assert.equal(result.status, 200, JSON.stringify(result.body)); + assert.deepEqual(result.body, { interfaceTheme: theme }); + const me = await agent.get('/api/v1/auth/me'); + assert.equal(me.body.settings.interfaceTheme, theme); + } + assert.equal( + ( + await agent + .post(`/api/v1/user/${id + 1}/settings/interface-theme`) + .send({ theme: 'persiusNG' }) + ).status, + 403 + ); + for (const body of [ + { theme: 'not-installed' }, + { theme: '../persiusNG' }, + { theme: 'persiusNG', css: 'body{}' }, + ]) { + assert.equal( + ( + await agent + .post(`/api/v1/user/${id}/settings/interface-theme`) + .send(body) + ).status, + 400 + ); + } + const anonymous = await request(app) + .post(`/api/v1/user/${id}/settings/interface-theme`) + .send({ theme: 'persiusNG' }); + assert.ok([401, 403].includes(anonymous.status)); + }); +}); diff --git a/server/routes/interfaceThemes.test.ts b/server/routes/interfaceThemes.test.ts index 9f24f7eabf..01904e6e0f 100644 --- a/server/routes/interfaceThemes.test.ts +++ b/server/routes/interfaceThemes.test.ts @@ -23,18 +23,27 @@ describe('public interface theme package routes', () => { assert.equal(response.headers['cache-control'], 'public, max-age=60'); assert.deepEqual( response.body.themes.map(({ id }: { id: string }) => id), - ['seerrOrig', 'seerrNGJ'] + ['seerrOrig', 'seerrNGJ', 'persiusNG'] + ); + assert.equal( + response.body.themes.find(({ id }: { id: string }) => id === 'persiusNG') + ?.layout, + 'persius' ); }); it('serves only a validated installed stylesheet from the same origin', async () => { const response = await request(app).get( - '/api/v1/interface-themes/seerrOrig/theme.css' + '/api/v1/interface-themes/persiusNG/theme.css' ); assert.equal(response.status, 200); assert.match(response.headers['content-type'], /^text\/css; charset=utf-8/); assert.equal(response.headers['x-content-type-options'], 'nosniff'); - assert.match(response.text, /data-interface-theme='seerrOrig'/); + assert.equal( + response.headers['cross-origin-resource-policy'], + 'same-origin' + ); + assert.match(response.text, /data-interface-theme='persiusNG'/); assert.equal( (await request(app).get('/api/v1/interface-themes/%2e%2e/theme.css')) .status, diff --git a/server/routes/overrideRule.openapi.test.ts b/server/routes/overrideRule.openapi.test.ts new file mode 100644 index 0000000000..039705df28 --- /dev/null +++ b/server/routes/overrideRule.openapi.test.ts @@ -0,0 +1,92 @@ +import { getRepository } from '@server/datasource'; +import OverrideRule from '@server/entity/OverrideRule'; +import { User } from '@server/entity/User'; +import { getSettings, type SonarrSettings } from '@server/lib/settings'; +import { setupTestDb } from '@server/test/db'; +import express from 'express'; +import * as OpenApiValidator from 'express-openapi-validator'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { it } from 'node:test'; +import request from 'supertest'; +import overrideRuleRoutes from './overrideRule'; + +setupTestDb(); + +it('accepts and returns country and language-profile rules through the real OpenAPI validator', async () => { + getSettings().sonarr = [ + { + id: 0, + name: 'Fixture Sonarr', + hostname: '127.0.0.1', + port: 8989, + apiKey: 'fixture', + useSsl: false, + isDefault: true, + is4k: false, + activeProfileId: 0, + activeDirectory: '/tv', + } as SonarrSettings, + ]; + const app = express(); + app.use(express.json()); + // Synthetic owner session: the production route still enforces ADMIN. + app.use(async (req, _res, next) => { + req.user = await getRepository(User).findOneByOrFail({ id: 1 }); + next(); + }); + app.use( + OpenApiValidator.middleware({ + apiSpec: path.resolve('seerr-api.yml'), + validateSecurity: false, + validateRequests: true, + validateResponses: true, + }) + ); + app.use('/api/v1/overrideRule', overrideRuleRoutes); + app.use( + ( + error: { status?: number; message?: string }, + _req: express.Request, + res: express.Response, + next: express.NextFunction + ) => { + void next; + return res.status(error.status ?? 500).json({ message: error.message }); + } + ); + const created = await request(app).post('/api/v1/overrideRule').send({ + sonarrServiceId: 0, + productionCountries: 'CA|US', + languageProfileId: 0, + }); + assert.equal(created.status, 200, created.body.message); + assert.equal(created.body.productionCountries, 'CA|US'); + assert.equal(created.body.languageProfileId, 0); + const listed = await request(app).get('/api/v1/overrideRule'); + assert.equal(listed.status, 200, listed.body.message); + assert.equal( + listed.body.find((rule: { id: number }) => rule.id === created.body.id) + ?.languageProfileId, + 0 + ); + const updated = await request(app) + .put(`/api/v1/overrideRule/${created.body.id}`) + .send({ productionCountries: 'US' }); + assert.equal(updated.status, 200, updated.body.message); + assert.equal( + (await getRepository(OverrideRule).findOneByOrFail({ id: created.body.id })) + .productionCountries, + 'US' + ); + assert.equal( + ( + await request(app).post('/api/v1/overrideRule').send({ + sonarrServiceId: 0, + productionCountries: 'USA', + languageProfileId: 0, + }) + ).status, + 400 + ); +}); diff --git a/server/routes/overrideRule.ts b/server/routes/overrideRule.ts index 9e09fcf81e..7a32fc730d 100644 --- a/server/routes/overrideRule.ts +++ b/server/routes/overrideRule.ts @@ -50,7 +50,9 @@ const overrideRuleBodyFields = new Set([ 'genre', 'language', 'keywords', + 'productionCountries', 'profileId', + 'languageProfileId', 'rootFolder', 'tags', 'radarrServiceId', @@ -64,7 +66,9 @@ type OverrideRuleBody = { genre?: string | null; language?: string | null; keywords?: string | null; + productionCountries?: string | null; profileId?: number | null; + languageProfileId?: number | null; rootFolder?: string | null; tags?: string | null; radarrServiceId?: number | null; @@ -78,7 +82,9 @@ type OverrideRulePatch = { genre?: string | null; language?: string | null; keywords?: string | null; + productionCountries?: string | null; profileId?: number | null; + languageProfileId?: number | null; rootFolder?: string | null; tags?: string | null; radarrServiceId?: number | null; @@ -258,6 +264,30 @@ const parseOptionalRuleLanguageList = ( return [...new Set(languages)].join('|'); }; +const parseOptionalRuleCountryList = ( + value: unknown +): string | null | undefined | { error: string } => { + const parsed = parseOptionalRuleString(value, 'Production countries'); + if (parsed === undefined || parsed === null || typeof parsed === 'object') { + return parsed; + } + + const countries = parsed + .split('|') + .map((country) => country.trim().toUpperCase()); + if ( + countries.length === 0 || + countries.length > MAX_OVERRIDE_RULE_LIST_ITEMS || + countries.some((country) => !/^[A-Z]{2}$/.test(country)) + ) { + return { + error: `Production countries must contain at most ${MAX_OVERRIDE_RULE_LIST_ITEMS} ISO 3166-1 alpha-2 codes.`, + }; + } + + return [...new Set(countries)].join('|'); +}; + const hasRuleValue = (value: unknown): boolean => typeof value === 'string' ? value.trim().length > 0 : value != null; @@ -290,12 +320,22 @@ const validateOverrideRuleShape = ( } if ( - ![rule.users, rule.genre, rule.language, rule.keywords].some(hasRuleValue) + ![ + rule.users, + rule.genre, + rule.language, + rule.keywords, + rule.productionCountries, + ].some(hasRuleValue) ) { return { error: 'Override rules must define at least one condition.' }; } - if (![rule.profileId, rule.rootFolder, rule.tags].some(hasRuleValue)) { + if ( + ![rule.profileId, rule.languageProfileId, rule.rootFolder, rule.tags].some( + hasRuleValue + ) + ) { return { error: 'Override rules must define at least one setting.' }; } @@ -303,6 +343,23 @@ const validateOverrideRuleShape = ( return { error: 'Album language is not available for Lidarr rules.' }; } + if ( + hasRuleValue(rule.productionCountries) && + rule.radarrServiceId == null && + rule.sonarrServiceId == null + ) { + return { + error: + 'Production countries are only available for Radarr and Sonarr rules.', + }; + } + + if (hasRuleValue(rule.languageProfileId) && rule.sonarrServiceId == null) { + return { + error: 'Language profiles are only available for Sonarr rules.', + }; + } + return undefined; }; @@ -340,6 +397,22 @@ const parseOverrideRuleBody = ( if (typeof language === 'object' && language && 'error' in language) { return language; } + const productionCountries = parseOptionalRuleCountryList( + bodyObject.productionCountries + ); + if ( + typeof productionCountries === 'object' && + productionCountries && + 'error' in productionCountries + ) { + return productionCountries; + } + if (isCatalogRule && hasRuleValue(productionCountries)) { + return { + error: + 'Production countries are only available for Radarr and Sonarr rules.', + }; + } const keywords = isCatalogRule ? parseOptionalCatalogTerms(bodyObject.keywords, 'Keywords') : parseOptionalRuleIdList(bodyObject.keywords, 'Keywords'); @@ -365,6 +438,17 @@ const parseOverrideRuleBody = ( if (typeof profileId === 'object' && profileId && 'error' in profileId) { return profileId; } + const languageProfileId = parseOptionalRuleInteger( + bodyObject.languageProfileId, + 'Language profile ID' + ); + if ( + typeof languageProfileId === 'object' && + languageProfileId && + 'error' in languageProfileId + ) { + return languageProfileId; + } const radarrServiceId = parseOptionalRuleInteger( bodyObject.radarrServiceId, 'Radarr service ID' @@ -415,7 +499,9 @@ const parseOverrideRuleBody = ( genre, language, keywords, + productionCountries, profileId, + languageProfileId, rootFolder, tags, radarrServiceId, @@ -660,6 +746,7 @@ overrideRuleRoutes.post< return res.status(200).json({ rootFolder: null, profileId: null, + languageProfileId: null, tags: req.body.tags ?? null, }); } diff --git a/server/routes/request.test.ts b/server/routes/request.test.ts index 0696481089..1a182cc9cb 100644 --- a/server/routes/request.test.ts +++ b/server/routes/request.test.ts @@ -33,12 +33,14 @@ import { MediaRequest, } from '@server/entity/MediaRequest'; import MediaRequestStatusEvent from '@server/entity/MediaRequestStatusEvent'; +import { NotificationOutbox } from '@server/entity/NotificationOutbox'; import OverrideRule from '@server/entity/OverrideRule'; import Season from '@server/entity/Season'; import SeasonRequest from '@server/entity/SeasonRequest'; import { User } from '@server/entity/User'; import { UserSettings } from '@server/entity/UserSettings'; import { aliasDownloadId } from '@server/lib/mediaResponse'; +import notificationManager, { Notification } from '@server/lib/notifications'; import { Permission } from '@server/lib/permissions'; import requestAdmissionCoordinator from '@server/lib/requestAdmission'; import requestDispatchManager from '@server/lib/requestDispatch'; @@ -55,6 +57,7 @@ import { runUserSecurityMutation } from '@server/lib/userSecurityMutation'; import { checkUser } from '@server/middleware/auth'; import { MediaRequestSubscriber } from '@server/subscriber/MediaRequestSubscriber'; import { setupTestDb } from '@server/test/db'; +import { makeBookshelfBookId } from '@server/utils/bookshelfCatalog'; import type { Express } from 'express'; import express from 'express'; import rateLimit from 'express-rate-limit'; @@ -1622,7 +1625,48 @@ describe('POST /request/:requestId/fail-download', () => { }); }); +const realSendRequestNotification = MediaRequest.sendNotification; + describe('PUT /request/:requestId (movie)', () => { + it('durably queues one pending-edit event and leaves a no-op edit quiet', async (t) => { + getSettings().radarr = [createRadarrSettings(3)]; + const pending = await seedRequest(); + mock.method(MediaRequest, 'sendNotification', realSendRequestNotification); + notificationManager.registerAgents([ + { shouldSend: () => true, send: async () => false }, + ]); + t.after(() => notificationManager.registerAgents([])); + const agent = await loginAs('admin@seerr.dev', 'test1234'); + const changes = { + mediaType: MediaType.MOVIE, + serverId: 3, + rootFolder: '/pending-edit', + }; + const response = await agent.put(`/request/${pending.id}`).send(changes); + assert.equal(response.status, 200, response.body.message); + const repository = getRepository(NotificationOutbox); + const records = await repository.find({ + where: { type: Notification.MEDIA_PENDING_UPDATED }, + }); + assert.equal(records.length, 1); + assert.ok(records[0].payload.includes('media-request')); + assert.equal( + (await getRepository(MediaRequest).findOneByOrFail({ id: pending.id })) + .rootFolder, + '/pending-edit' + ); + assert.equal( + (await agent.put(`/request/${pending.id}`).send(changes)).status, + 200 + ); + assert.equal( + await repository.count({ + where: { type: Notification.MEDIA_PENDING_UPDATED }, + }), + 1 + ); + }); + it('validates and preserves partial movie routing changes', async (t) => { const settings = getSettings(); settings.radarr = [createRadarrSettings(3)]; @@ -2738,9 +2782,14 @@ describe('POST /request', () => { assert.strictEqual(selectedResponse.status, 201); assert.strictEqual(selectedResponse.body.serverId, 0); - assert.strictEqual(selectedResponse.body.profileId, 0); - assert.strictEqual(selectedResponse.body.rootFolder, '/selected-movies'); - assert.deepStrictEqual(selectedResponse.body.tags, [7]); + assert.strictEqual(selectedResponse.body.profileId, null); + assert.strictEqual(selectedResponse.body.rootFolder, null); + assert.strictEqual(selectedResponse.body.tags, null); + assert.strictEqual(selectedResponse.body.serviceTargets[0].profileId, 0); + assert.strictEqual( + selectedResponse.body.serviceTargets[0].rootFolder, + '/selected-movies' + ); assert.strictEqual(unknownResponse.status, 400); assert.match(unknownResponse.body.message, /does not exist/i); assert.strictEqual(wrongTierResponse.status, 400); @@ -6710,6 +6759,276 @@ describe('PUT /request/:requestId', () => { }); }); +describe('pending book destination edits', () => { + async function seedBook(overrides: Partial = {}) { + const requestedBy = await getRepository(User).findOneOrFail({ + where: { email: 'friend@seerr.dev' }, + }); + const media = await getRepository(Media).save( + new Media({ + mediaType: MediaType.BOOK, + tmdbId: 0, + status: MediaStatus.PENDING, + status4k: MediaStatus.UNKNOWN, + }) + ); + await getRepository(MediaIdentifier).save( + new MediaIdentifier({ + media, + provider: MediaIdentifierProvider.BOOKSHELF, + value: makeBookshelfBookId(11, 'edit-work'), + canonical: true, + }) + ); + return getRepository(MediaRequest).save( + new MediaRequest({ + type: MediaType.BOOK, + media, + requestedBy, + status: MediaRequestStatus.PENDING, + is4k: false, + bookFormat: 'ebook', + serverId: 11, + profileId: 90, + metadataProfileId: 91, + rootFolder: '/old', + tags: [9], + serviceTargets: [ + { + serviceType: 'readarr', + format: 'ebook', + serverId: 11, + profileId: 90, + metadataProfileId: 91, + rootFolder: '/old', + tags: [9], + status: MediaStatus.PENDING, + }, + ], + ...overrides, + }) + ); + } + beforeEach(() => { + getSettings().readarr = [ + createReadarrSettings(11, 'ebook'), + { + ...createReadarrSettings(0, 'ebook', false), + activeProfileId: 7, + activeMetadataProfileId: undefined, + activeDirectory: '/new', + tags: [3], + }, + createReadarrSettings(12, 'audiobook'), + ]; + }); + afterEach(() => { + getSettings().readarr = []; + }); + + it('retargets dispatch and visible settings together, resetting destination defaults including nullable metadata', async () => { + const original = await seedBook(); + const agent = await loginAs('admin@seerr.dev', 'test1234'); + const result = await agent + .put(`/request/${original.id}`) + .send({ serverId: 0 }); + assert.equal(result.status, 200); + const saved = await getRepository(MediaRequest).findOneOrFail({ + where: { id: original.id }, + }); + assert.equal(saved.serverId, 0); + assert.equal(saved.profileId, 7); + assert.equal(saved.metadataProfileId, null); + assert.equal(saved.rootFolder, '/new'); + assert.deepEqual(saved.tags, [3]); + assert.deepEqual(saved.serviceTargets, [ + { + serviceType: 'readarr', + format: 'ebook', + serverId: 0, + profileId: 7, + metadataProfileId: null, + rootFolder: '/new', + tags: [3], + status: MediaStatus.PENDING, + }, + ]); + }); + + it('applies explicit zero profiles and empty tags to the saved worker target on a partial edit', async () => { + const original = await seedBook(); + const agent = await loginAs('admin@seerr.dev', 'test1234'); + const result = await agent + .put(`/request/${original.id}`) + .send({ profileId: 0, metadataProfileId: 0, tags: [] }); + assert.equal(result.status, 200); + const saved = await getRepository(MediaRequest).findOneOrFail({ + where: { id: original.id }, + }); + assert.equal(saved.serviceTargets?.[0].serverId, 11); + assert.equal(saved.serviceTargets?.[0].rootFolder, '/old'); + assert.equal(saved.serviceTargets?.[0].profileId, 0); + assert.equal(saved.serviceTargets?.[0].metadataProfileId, 0); + assert.deepEqual(saved.serviceTargets?.[0].tags, []); + }); + + it('preserves a covered format omission when editing a both-format request', async () => { + const original = await seedBook({ bookFormat: 'both' }); + const agent = await loginAs('admin@seerr.dev', 'test1234'); + const result = await agent + .put(`/request/${original.id}`) + .send({ tags: [1] }); + assert.equal(result.status, 200); + const saved = await getRepository(MediaRequest).findOneOrFail({ + where: { id: original.id }, + }); + assert.deepEqual( + saved.serviceTargets?.map((target) => target.format), + ['ebook'] + ); + }); + + it('keeps the audiobook destination independent when retargeting both formats', async () => { + const audio = { + serviceType: 'readarr' as const, + format: 'audiobook' as const, + serverId: 12, + profileId: 5, + rootFolder: '/audio', + metadataProfileId: 8, + tags: [4], + status: MediaStatus.PENDING, + }; + const original = await seedBook({ + bookFormat: 'both', + serviceTargets: [ + { + serviceType: 'readarr', + format: 'ebook', + serverId: 11, + profileId: 90, + rootFolder: '/old', + }, + audio, + ], + }); + const agent = await loginAs('admin@seerr.dev', 'test1234'); + const result = await agent + .put(`/request/${original.id}`) + .send({ serverId: 0, tags: [] }); + assert.equal(result.status, 200); + const saved = await getRepository(MediaRequest).findOneOrFail({ + where: { id: original.id }, + }); + assert.deepEqual(saved.serviceTargets?.[1], audio); + }); + + it('retains legacy Open Library ISBN metadata when changing format', async () => { + const original = await seedBook({ + preferredEditionId: 'OL123M', + preferredIsbn13: '9780000000002', + }); + const agent = await loginAs('admin@seerr.dev', 'test1234'); + const result = await agent + .put(`/request/${original.id}`) + .send({ serverId: 12, format: 'audiobook' }); + assert.equal(result.status, 200); + const saved = await getRepository(MediaRequest).findOneOrFail({ + where: { id: original.id }, + }); + assert.equal(saved.preferredEditionId, 'OL123M'); + assert.equal(saved.preferredIsbn13, '9780000000002'); + assert.equal(saved.serviceTargets?.[0].format, 'audiobook'); + assert.equal(saved.serviceTargets?.[0].serverId, 12); + }); + + it('rejects edition/format changes atomically and preserves edit authorization', async () => { + const original = await seedBook({ + preferredEditionId: 'edition-1', + editionPolicy: 'only', + }); + const agent = await loginAs('admin@seerr.dev', 'test1234'); + for (const body of [ + { format: 'audiobook', serverId: 12 }, + { preferredEditionId: 'edition-2' }, + { editionPolicy: 'alongside' }, + ]) { + assert.equal( + ( + await agent + .put(`/request/${original.id}`) + .send({ mediaType: MediaType.BOOK, ...body }) + ).status, + 409 + ); + } + const friend = await loginAs('friend@seerr.dev', 'test1234'); + assert.equal( + (await friend.put(`/request/${original.id}`).send({ serverId: 0 })) + .status, + 403 + ); + const saved = await getRepository(MediaRequest).findOneOrFail({ + where: { id: original.id }, + }); + assert.equal(saved.serverId, 11); + assert.equal(saved.serviceTargets?.[0].serverId, 11); + assert.equal(saved.preferredEditionId, 'edition-1'); + assert.equal(saved.editionPolicy, 'only'); + }); + + it('verifies the exact edition against the new destination before saving', async (t) => { + const original = await seedBook({ + preferredEditionId: 'edition-1', + editionPolicy: 'alongside', + }); + let editions: { foreignEditionId: string; isEbook: boolean }[] = []; + const lookup = mock.method(ReadarrAPI.prototype, 'lookupBook', async () => [ + { foreignBookId: 'edit-work', title: 'Book', editions }, + ]); + const supports = mock.method( + ReadarrAPI.prototype, + 'supportsWantedEditionVariants', + () => false + ); + t.after(() => { + lookup.mock.restore(); + supports.mock.restore(); + }); + const agent = await loginAs('admin@seerr.dev', 'test1234'); + const missing = await agent + .put(`/request/${original.id}`) + .send({ serverId: 0 }); + assert.equal(missing.status, 400); + assert.match(missing.body.message, /could not be verified/i); + editions = [{ foreignEditionId: 'edition-1', isEbook: true }]; + const unsupported = await agent + .put(`/request/${original.id}`) + .send({ serverId: 0 }); + assert.equal(unsupported.status, 400); + assert.match(unsupported.body.message, /alongside/i); + assert.equal( + ( + await getRepository(MediaRequest).findOneOrFail({ + where: { id: original.id }, + }) + ).serverId, + 11 + ); + supports.mock.mockImplementation(() => true); + const valid = await agent + .put(`/request/${original.id}`) + .send({ serverId: 0 }); + assert.equal(valid.status, 200); + const saved = await getRepository(MediaRequest).findOneOrFail({ + where: { id: original.id }, + }); + assert.equal(saved.serviceTargets?.[0].serverId, 0); + assert.equal(saved.preferredEditionId, 'edition-1'); + assert.equal(saved.editionPolicy, 'alongside'); + }); +}); + async function seedUser( email: string, quotas: { @@ -8401,12 +8720,12 @@ describe('POST /request/bulk', () => { const getWorkEditionsMock = mock.method( OpenLibraryAPI.prototype, 'getWorkEditions', - async (workId: string) => + async () => ({ size: 1, entries: [ { - key: `/books/${workId.replace(/^\/?works\//, '')}-edition`, + key: '/books/OL123M', isbn_13: ['9780441478125'], }, ], @@ -8428,7 +8747,7 @@ describe('POST /request/bulk', () => { title: 'New Work', authorId: 'OL1A', isbn13: '9780441478125', - editionId: 'new-work-edition', + editionId: 'OL123M', }, { mediaId: 'available-work', title: 'Available Work' }, ], @@ -8580,12 +8899,12 @@ describe('POST /request/bulk', () => { const getWorkEditionsMock = mock.method( OpenLibraryAPI.prototype, 'getWorkEditions', - async (workId: string) => + async () => ({ size: 1, entries: [ { - key: `/books/${workId.replace(/^\/?works\//, '')}-edition`, + key: '/books/OL123M', isbn_13: ['9780441478125'], }, ], @@ -8610,7 +8929,7 @@ describe('POST /request/bulk', () => { title: 'Zero Book Work', authorId: 'OL1A', isbn13: '9780441478125', - editionId: 'zero-book-work-edition', + editionId: 'OL123M', }, ], }); @@ -8768,12 +9087,12 @@ describe('POST /request/bulk', () => { const getWorkEditionsMock = mock.method( OpenLibraryAPI.prototype, 'getWorkEditions', - async (workId: string) => + async () => ({ size: 1, entries: [ { - key: `/books/${workId.replace(/^\/?works\//, '')}-edition`, + key: '/books/OL123M', isbn_13: ['9780441478125'], }, ], @@ -8798,7 +9117,7 @@ describe('POST /request/bulk', () => { title: 'New Work', authorId: 'OL1A', isbn13: '9780441478125', - editionId: 'new-work-edition', + editionId: 'OL123M', }, ], }); @@ -9536,6 +9855,60 @@ describe('POST /request, destination-scoped override rules', () => { assert.strictEqual(explicitResponse.body.profileId, 0); assert.deepStrictEqual(explicitResponse.body.tags, []); }); + it('preserves explicitly selected service defaults against override rules', async () => { + configureRadarr([ + { + id: 5, + isDefault: true, + is4k: false, + activeProfileId: 1, + activeDirectory: '/default/movies', + tags: [], + }, + ]); + getSettings().sonarr = []; + const requester = await setDemoPermissions( + Permission.REQUEST | Permission.REQUEST_ADVANCED + ); + await getRepository(OverrideRule).save( + new OverrideRule({ + radarrServiceId: 5, + users: String(requester.id), + rootFolder: '/rule/movies', + profileId: 7, + tags: '2', + }) + ); + mock.method( + MediaRequestSubscriber.prototype, + 'sendToRadarr', + async () => true + ); + const agent = await loginAs('demo@seerr.dev', 'test1234'); + const response = await agent.post('/request').send({ + mediaType: MediaType.MOVIE, + mediaId: 88026, + serverId: 5, + profileId: 1, + rootFolder: '/default/movies', + tags: [], + requesterSelectedOptions: { + profile: true, + rootFolder: true, + tags: true, + }, + }); + assert.equal(response.status, 201); + assert.equal(response.body.profileId, 1); + assert.equal(response.body.rootFolder, '/default/movies'); + assert.deepEqual(response.body.tags, []); + const saved = await getRepository(MediaRequest).findOneByOrFail({ + id: response.body.id, + }); + assert.equal(saved.profileId, 1); + assert.equal(saved.rootFolder, '/default/movies'); + assert.deepEqual(saved.tags, []); + }); }); describe('DELETE /request/:requestId, orphaned season status reset', () => { diff --git a/server/routes/request.ts b/server/routes/request.ts index d8fb8a41c2..c1e0d52ee4 100644 --- a/server/routes/request.ts +++ b/server/routes/request.ts @@ -29,6 +29,7 @@ import { getRequestMutationAdmissionKey, hasMediaRequestPermission, runWithRequestAdmission, + type MediaRequestServiceTarget, } from '@server/entity/MediaRequest'; import MediaRequestStatusEvent from '@server/entity/MediaRequestStatusEvent'; import SeasonRequest, { @@ -45,9 +46,15 @@ import type { RequestStatusDetailResponse, RequestStatusResultsResponse, RequestStatusUsersResponse, + RequestTargetOptions, + RequesterSelectedOptions, } from '@server/interfaces/api/requestInterfaces'; import type { SeasonEpisodeSelection } from '@server/interfaces/api/seasonInterfaces'; import { hasAvailableBookFormat } from '@server/lib/bookAvailability'; +import { + BookRequestEditConflictError, + planBookRequestEdit, +} from '@server/lib/bookRequestEdit'; import { isValidMusicBrainzResourceId, isValidOpenLibraryResourceId, @@ -57,12 +64,18 @@ import { normalizeOpenLibraryWorkId, } from '@server/lib/externalIds'; import { getExternalRuntimeConfig } from '@server/lib/externalRuntimeConfig'; +import { validateFutureSeasonPreference } from '@server/lib/futureSeasonMonitoring'; import { normalizeValidIsbn } from '@server/lib/isbn'; import { cleanMagazineTitle } from '@server/lib/magazineIdentity'; import { isMediaCategoryEnabled } from '@server/lib/mediaCategories'; import { hydrateMediaRequestRelations } from '@server/lib/mediaRequestHydration'; import { aliasDownloadId } from '@server/lib/mediaResponse'; import { hydrateMediaSummaryRelations } from '@server/lib/mediaSummaryHydration'; +import { Notification } from '@server/lib/notifications'; +import { + capturePendingRequestEditSnapshot, + hasMaterialPendingRequestEdit, +} from '@server/lib/notifications/requestUpdate'; import { Permission } from '@server/lib/permissions'; import requestDispatchManager from '@server/lib/requestDispatch'; import { @@ -310,6 +323,7 @@ const hasAdultRequestAccess = (user?: User | null): boolean => ) ?? false; const requestStatusFilters = [ 'all', + 'active', 'recent', 'approved', 'processing', @@ -808,6 +822,195 @@ const parseOptionalRequestTags = ( return { value: tags }; }; +const parseRequestTargetOptions = ( + value: unknown, + mediaType: MediaType | undefined, + isEdit: boolean +): RequestOptionValidationResult => { + if (value === undefined) { + return { value: undefined }; + } + + if ( + !isEdit || + (mediaType !== MediaType.MOVIE && mediaType !== MediaType.TV) + ) { + return { + error: { + status: 400, + message: + 'requestTargetOptions are only valid when editing movie or TV requests.', + }, + }; + } + + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return { + error: { + status: 400, + message: 'requestTargetOptions must be an object.', + }, + }; + } + + const options = value as Record; + const requiredFields = [ + 'profileId', + 'rootFolder', + 'tags', + ...(mediaType === MediaType.TV ? ['languageProfileId'] : []), + ]; + if ( + requiredFields.some( + (field) => !Object.prototype.hasOwnProperty.call(options, field) + ) || + Object.keys(options).some((field) => !requiredFields.includes(field)) + ) { + return { + error: { + status: 400, + message: 'requestTargetOptions contains missing or unsupported fields.', + }, + }; + } + + const profileId = parseOptionalRequestOptionId( + options.profileId, + 'requestTargetOptions.profileId', + true + ); + if ( + 'error' in profileId || + (options.profileId !== null && profileId.value === undefined) + ) { + return 'error' in profileId + ? profileId + : { + error: { + status: 400, + message: + 'requestTargetOptions.profileId must be a non-negative integer or null.', + }, + }; + } + + const rootFolder = parseOptionalRequestString( + options.rootFolder, + 'requestTargetOptions.rootFolder', + maxRequestRootFolderLength + ); + if ( + 'error' in rootFolder || + (options.rootFolder !== null && rootFolder.value === undefined) + ) { + return 'error' in rootFolder + ? rootFolder + : { + error: { + status: 400, + message: + 'requestTargetOptions.rootFolder must be a string or null.', + }, + }; + } + + const tags = parseOptionalRequestTags(options.tags); + if ('error' in tags || (options.tags !== null && tags.value === undefined)) { + return 'error' in tags + ? tags + : { + error: { + status: 400, + message: 'requestTargetOptions.tags must be an array or null.', + }, + }; + } + + let languageProfileId: number | null | undefined; + if (mediaType === MediaType.TV) { + const language = parseOptionalRequestOptionId( + options.languageProfileId, + 'requestTargetOptions.languageProfileId', + true + ); + if ( + 'error' in language || + (options.languageProfileId !== null && language.value === undefined) + ) { + return 'error' in language + ? language + : { + error: { + status: 400, + message: + 'requestTargetOptions.languageProfileId must be a non-negative integer or null.', + }, + }; + } + languageProfileId = + options.languageProfileId === null ? null : language.value; + } + + return { + value: { + profileId: options.profileId === null ? null : profileId.value!, + rootFolder: options.rootFolder === null ? null : rootFolder.value!, + tags: options.tags === null ? null : tags.value!, + ...(mediaType === MediaType.TV ? { languageProfileId } : {}), + }, + }; +}; + +const parseRequesterSelectedOptions = ( + value: unknown, + mediaType: MediaType | undefined, + isCreate: boolean +): RequestOptionValidationResult => { + if (value === undefined) { + return { value: undefined }; + } + + if ( + !isCreate || + (mediaType !== MediaType.MOVIE && mediaType !== MediaType.TV) + ) { + return { + error: { + status: 400, + message: + 'requesterSelectedOptions are only valid for new movie or TV requests.', + }, + }; + } + + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return { + error: { + status: 400, + message: 'requesterSelectedOptions must be an object.', + }, + }; + } + + const options = value as Record; + const allowedFields = ['profile', 'rootFolder', 'languageProfile', 'tags']; + if ( + Object.keys(options).some((field) => !allowedFields.includes(field)) || + Object.values(options).some((field) => typeof field !== 'boolean') || + (mediaType === MediaType.MOVIE && 'languageProfile' in options) + ) { + return { + error: { + status: 400, + message: + 'requesterSelectedOptions contains unsupported fields or values.', + }, + }; + } + + return { value: options as RequesterSelectedOptions }; +}; + const parseOptionalRequestSeasons = ( value: unknown ): RequestOptionValidationResult => { @@ -976,7 +1179,10 @@ const parseOptionalSeasonRequests = ( const sanitizeMediaRequestBody = ( body: unknown, - options: { requireCreateIdentity?: boolean } = {} + options: { + requireCreateIdentity?: boolean; + preserveNullOverrides?: boolean; + } = {} ): RequestOptionValidationResult => { if (!body || typeof body !== 'object' || Array.isArray(body)) { return { @@ -1017,6 +1223,13 @@ const sanitizeMediaRequestBody = ( }; } + const futureSeasonError = validateFutureSeasonPreference( + bodyObject.monitorFutureSeasons, + mediaType + ); + if (futureSeasonError) + return { error: { status: 400, message: futureSeasonError } }; + if (bodyObject.is4k !== undefined && typeof bodyObject.is4k !== 'boolean') { return { error: { @@ -1504,6 +1717,41 @@ const sanitizeMediaRequestBody = ( return tags; } + const requesterSelectedOptions = parseRequesterSelectedOptions( + bodyObject.requesterSelectedOptions, + mediaType as MediaType | undefined, + options.requireCreateIdentity ?? false + ); + if ('error' in requesterSelectedOptions) { + return requesterSelectedOptions; + } + if ( + (requesterSelectedOptions.value?.profile && + profileId.value === undefined) || + (requesterSelectedOptions.value?.rootFolder && + rootFolder.value === undefined) || + (requesterSelectedOptions.value?.tags && tags.value === undefined) || + (requesterSelectedOptions.value?.languageProfile && + languageProfileId.value === undefined) + ) { + return { + error: { + status: 400, + message: + 'Each selected requester option must include its corresponding value.', + }, + }; + } + + const requestTargetOptions = parseRequestTargetOptions( + bodyObject.requestTargetOptions, + mediaType as MediaType | undefined, + options.preserveNullOverrides ?? false + ); + if ('error' in requestTargetOptions) { + return requestTargetOptions; + } + const seasons = parseOptionalRequestSeasons(bodyObject.seasons); if ('error' in seasons) { return seasons; @@ -1531,10 +1779,19 @@ const sanitizeMediaRequestBody = ( is4k: bodyObject.is4k ?? false, serverId: serverId.value, requestServiceServerId: requestServiceServerId.value, - profileId: profileId.value, + profileId: + options.preserveNullOverrides && bodyObject.profileId === null + ? null + : profileId.value, profileName: profileName.value, - rootFolder: rootFolder.value, - languageProfileId: languageProfileId.value, + rootFolder: + options.preserveNullOverrides && bodyObject.rootFolder === null + ? null + : rootFolder.value, + languageProfileId: + options.preserveNullOverrides && bodyObject.languageProfileId === null + ? null + : languageProfileId.value, metadataLanguageId: sanitizedMetadataLanguageId, sonarrSeasonType: sanitizedSonarrSeasonType, metadataProfileId: metadataProfileId.value, @@ -1545,7 +1802,12 @@ const sanitizeMediaRequestBody = ( 'only' | 'either' | 'alongside' | undefined, variantKey: variantKey.value, userId: userId.value, - tags: tags.value, + tags: + options.preserveNullOverrides && bodyObject.tags === null + ? null + : tags.value, + requestTargetOptions: requestTargetOptions.value, + requesterSelectedOptions: requesterSelectedOptions.value, seasons: seasonRequests.value?.map((selection) => selection.seasonNumber) ?? seasons.value, @@ -1707,16 +1969,72 @@ const sanitizeBulkMediaRequestBody = ( items: sanitizedItems, format: sanitized.value.format, serverId: sanitized.value.serverId, - profileId: sanitized.value.profileId, + profileId: sanitized.value.profileId ?? undefined, profileName: sanitized.value.profileName, - rootFolder: sanitized.value.rootFolder, + rootFolder: sanitized.value.rootFolder ?? undefined, metadataProfileId: sanitized.value.metadataProfileId, userId: sanitized.value.userId, - tags: sanitized.value.tags, + tags: sanitized.value.tags ?? undefined, }, }; }; +const synchronizeVideoRequestTargetOptions = ( + request: MediaRequest, + options: RequestTargetOptions, + preservePreviousTargets: boolean +): void => { + if ( + (request.type !== MediaType.MOVIE && request.type !== MediaType.TV) || + request.serverId == null + ) { + return; + } + + const serviceType = request.type === MediaType.MOVIE ? 'radarr' : 'sonarr'; + const format = request.is4k ? '4k' : 'standard'; + const targets = request.serviceTargets ?? []; + const targetIndex = targets.findIndex( + (target) => + target.serviceType === serviceType && + target.format === format && + target.serverId === request.serverId + ); + const previousTarget = targetIndex === -1 ? undefined : targets[targetIndex]; + const nextTarget: MediaRequestServiceTarget = { + ...previousTarget, + serviceType, + format, + serverId: request.serverId, + profileId: options.profileId, + rootFolder: options.rootFolder, + tags: options.tags, + ...(request.type === MediaType.TV + ? { languageProfileId: options.languageProfileId ?? null } + : {}), + status: previousTarget?.status ?? MediaStatus.PENDING, + }; + + if (preservePreviousTargets) { + request.serviceTargets = + targetIndex === -1 + ? [...targets, nextTarget] + : targets.map((target, index) => + index === targetIndex ? nextTarget : target + ); + return; + } + + // A pending request has no dispatched service identity to preserve. Replace + // its quality target so edits cannot leave stale exact-match data behind. + request.serviceTargets = [ + ...targets.filter( + (target) => target.serviceType !== serviceType || target.format !== format + ), + nextTarget, + ]; +}; + const inactiveMediaRequestStatuses = [ MediaRequestStatus.DECLINED, MediaRequestStatus.FAILED, @@ -1878,6 +2196,13 @@ requestRoutes.get< let statusFilter: MediaRequestStatus[]; switch (filter) { + case 'active': + statusFilter = [ + MediaRequestStatus.PENDING, + MediaRequestStatus.APPROVED, + MediaRequestStatus.FAILED, + ]; + break; case 'approved': case 'processing': statusFilter = [MediaRequestStatus.APPROVED]; @@ -3926,7 +4251,9 @@ requestRoutes.put<{ requestId: string }>( return next({ status: 404, message: 'Request not found.' }); } - const sanitizedBody = sanitizeMediaRequestBody(req.body); + const sanitizedBody = sanitizeMediaRequestBody(req.body, { + preserveNullOverrides: true, + }); if ('error' in sanitizedBody) { logRequestValidationFailure( 'edit', @@ -4009,6 +4336,10 @@ requestRoutes.put<{ requestId: string }>( } const originalServerId = request.serverId; + const originalPendingRequestEditSnapshot = + request.status === MediaRequestStatus.PENDING + ? capturePendingRequestEditSnapshot(request) + : undefined; if ( (body.mediaType ?? request.type) === MediaType.TV && @@ -4049,6 +4380,20 @@ requestRoutes.put<{ requestId: string }>( }); } + if ( + body.requestTargetOptions && + !actor.hasPermission( + [Permission.REQUEST_ADVANCED, Permission.MANAGE_REQUESTS], + { type: 'or' } + ) + ) { + return next({ + status: 403, + message: + 'You do not have permission to change service request options.', + }); + } + let requestUser = request.requestedBy; const changesRequestUser = body.userId !== undefined && @@ -4135,31 +4480,36 @@ requestRoutes.put<{ requestId: string }>( request.serverId = body.serverId as number; } if (body.profileId !== undefined) { - request.profileId = body.profileId as number; + request.profileId = body.profileId; } if (body.rootFolder !== undefined) { - request.rootFolder = body.rootFolder as string; + request.rootFolder = body.rootFolder; } if (body.tags !== undefined) { request.tags = body.tags; } - } else if ( - request.type === MediaType.MUSIC || - request.type === MediaType.BOOK - ) { + if (body.requestTargetOptions) { + synchronizeVideoRequestTargetOptions( + request, + body.requestTargetOptions, + isFailedRequestRepair + ); + } + } else if (request.type === MediaType.BOOK) { + Object.assign( + request, + await planBookRequestEdit(request, body) + ); + } else if (request.type === MediaType.MUSIC) { const nextServerId = body.serverId === undefined ? request.serverId : body.serverId; - const nextBookFormat = - request.type === MediaType.BOOK - ? (body.format ?? request.bookFormat ?? 'ebook') - : null; validateExternalServiceConfiguration( request.type, nextServerId, - nextBookFormat + null ); if (body.serverId !== undefined) { @@ -4177,10 +4527,6 @@ requestRoutes.put<{ requestId: string }>( if (body.tags !== undefined) { request.tags = body.tags; } - if (request.type === MediaType.BOOK) { - request.bookFormat = - body.format ?? request.bookFormat ?? 'ebook'; - } } else if (request.type === MediaType.TV) { const requestedSeasons = body.seasons === 'all' ? undefined : body.seasons; @@ -4485,14 +4831,13 @@ requestRoutes.put<{ requestId: string }>( request.serverId = body.serverId as number; } if (body.profileId !== undefined) { - request.profileId = body.profileId as number; + request.profileId = body.profileId; } if (body.rootFolder !== undefined) { - request.rootFolder = body.rootFolder as string; + request.rootFolder = body.rootFolder; } if (body.languageProfileId !== undefined) { - request.languageProfileId = - body.languageProfileId as number; + request.languageProfileId = body.languageProfileId; } if ( (body.metadataLanguageId !== undefined || @@ -4522,6 +4867,13 @@ requestRoutes.put<{ requestId: string }>( if (body.tags !== undefined) { request.tags = body.tags; } + if (body.requestTargetOptions) { + synchronizeVideoRequestTargetOptions( + request, + body.requestTargetOptions, + isFailedRequestRepair + ); + } } const selectionBySeason = new Map( @@ -4587,6 +4939,22 @@ requestRoutes.put<{ requestId: string }>( } } + if (request.type === MediaType.TV) { + const restricted = + (request.watchAheadEpisodeCount ?? 0) > 0 || + isTvSeasonWatchGateEnabledForUser(requestUser); + if (body.monitorFutureSeasons === true && restricted) { + return next({ + status: 403, + message: + 'Future seasons are managed by Episode Queue or the season watch gate.', + }); + } + if (restricted) request.monitorFutureSeasons = false; + else if (body.monitorFutureSeasons !== undefined) + request.monitorFutureSeasons = body.monitorFutureSeasons; + } + if (changesRequestUser && request.type === MediaType.TV) { request.watchAheadEpisodeCount = 0; request.watchAheadLastSeason = null; @@ -4614,7 +4982,25 @@ requestRoutes.put<{ requestId: string }>( request.quotaException = false; } request.requestedBy = requestUser; - await requestRepository.save(request); + const shouldNotifyPendingRequestUpdate = + originalPendingRequestEditSnapshot !== undefined && + hasMaterialPendingRequestEdit( + originalPendingRequestEditSnapshot, + request + ); + if (shouldNotifyPendingRequestUpdate) { + await dataSource.transaction(async (manager) => { + await manager.getRepository(MediaRequest).save(request); + await MediaRequest.sendNotification( + request, + request.media, + Notification.MEDIA_PENDING_UPDATED, + manager.queryRunner + ); + }); + } else { + await requestRepository.save(request); + } const [viewerRequest] = await hydrateMediaRequestRelations( [request], { viewer: req.user } @@ -4637,7 +5023,10 @@ requestRoutes.put<{ requestId: string }>( message: 'You do not have permission to modify this request.', }); } - if (e instanceof TvSeasonWatchGateError) { + if ( + e instanceof TvSeasonWatchGateError || + e instanceof BookRequestEditConflictError + ) { return next({ status: e.status, message: e.message }); } if (e instanceof ServiceConfigurationError) { diff --git a/server/routes/settings/index.ts b/server/routes/settings/index.ts index 19231496e4..40f9587aac 100644 --- a/server/routes/settings/index.ts +++ b/server/routes/settings/index.ts @@ -54,6 +54,11 @@ import { runWithConfigurationAdmissions, } from '@server/lib/configurationAdmission'; import { parseDownloadPathMappings } from '@server/lib/downloadPathMappings'; +import { + clearEpisodeAvailabilityForSource, + getJellyfinEpisodeAvailabilitySourceId, + getPlexEpisodeAvailabilitySourceId, +} from '@server/lib/episodeAvailability'; import ImageProxy from '@server/lib/imageproxy'; import { assertNoSymlinkDirectoryComponents } from '@server/lib/pathSecurity'; import { @@ -72,7 +77,7 @@ import type { PlexSettings, TautulliSettings, } from '@server/lib/settings'; -import { getSettings } from '@server/lib/settings'; +import { MetadataProviderType, getSettings } from '@server/lib/settings'; import logger from '@server/logger'; import { isAuthenticated } from '@server/middleware/auth'; import { @@ -267,6 +272,39 @@ const parseEnableList = (value: unknown) => { }; }; +const parseLibraryEpisodeOrderUpdate = (body: Record) => { + const libraryId = body.episodeOrderLibraryId; + const provider = body.episodeOrderProvider; + if (libraryId === undefined && provider === undefined) { + return { value: undefined }; + } + if (libraryId === undefined || provider === undefined) { + return { error: 'Library ID and episode order must be provided together.' }; + } + + const parsedLibraryId = parseBoundedString(libraryId, { + fieldName: 'Episode order library ID', + maxLength: MAX_SETTINGS_PATH_ID_LENGTH, + }); + if ('error' in parsedLibraryId) return parsedLibraryId; + + const parsedProvider = parseOptionalAllowedString(provider, { + fieldName: 'Episode order provider', + allowedValues: ['none', 'tmdb', 'tvdb'] as const, + maxLength: 16, + }); + if ('error' in parsedProvider || !parsedProvider.value) { + return { error: 'Episode order must be none, tmdb, or tvdb.' }; + } + + return { + value: { + libraryId: parsedLibraryId.value, + provider: parsedProvider.value, + }, + }; +}; + const parseSettingsPathId = (value: unknown, fieldName: string) => parseBoundedString(value, { fieldName, @@ -1267,6 +1305,7 @@ const parseMainSettingsBody = ( ['tvSeasonWatchGateEnabled', 'tvSeasonWatchGateEnabled'], ['personMovieBulkRequestsEnabled', 'personMovieBulkRequestsEnabled'], ['enableSpecialEpisodes', 'enableSpecialEpisodes'], + ['trackEpisodeAvailability', 'trackEpisodeAvailability'], ['cacheImages', 'cacheImages'], ['includeAdult', 'includeAdult'], ] as const) { @@ -1755,6 +1794,7 @@ settingsRoutes.post( return runWithConfigurationAdmission('plex', async () => { const userRepository = getRepository(User); const settings = getSettings(); + const previousPlexSettings = structuredClone(settings.plex); const parsedPlex = parsePlexSettingsBody(parsedBody.value, settings.plex); if ('error' in parsedPlex) { return res.status(400).json({ message: parsedPlex.error }); @@ -1777,24 +1817,55 @@ settingsRoutes.post( throw new Error('Server not found'); } - await settings.persistSection('plex', (current) => ({ - ...parsedPlex.value, - // A different machineId means this connection now points at a - // different physical Plex server. Stored library ids are only - // meaningful within one server (Plex reuses small sequential - // keys across installs), so carrying them over risks silently - // applying a stale enabled/type classification to an unrelated - // library on the new server. Only preserve libraries when we're - // re-confirming the same server (or connecting for the first - // time, when current.machineId is unset). - libraries: - current.machineId && - current.machineId !== result.MediaContainer.machineIdentifier - ? [] - : current.libraries, - machineId: result.MediaContainer.machineIdentifier, - name: result.MediaContainer.friendlyName, - })); + const updatedPlexSettings = await settings.persistSection( + 'plex', + (current) => ({ + ...parsedPlex.value, + // A different machineId means this connection now points at a + // different physical Plex server. Stored library ids are only + // meaningful within one server (Plex reuses small sequential + // keys across installs), so carrying them over risks silently + // applying a stale enabled/type classification to an unrelated + // library on the new server. Only preserve libraries when we're + // re-confirming the same server (or connecting for the first + // time, when current.machineId is unset). + libraries: + current.machineId && + current.machineId !== result.MediaContainer.machineIdentifier + ? [] + : current.libraries, + machineId: result.MediaContainer.machineIdentifier, + name: result.MediaContainer.friendlyName, + }) + ); + + for (const library of previousPlexSettings.libraries) { + if (library.type !== 'show') continue; + const previousSourceId = getPlexEpisodeAvailabilitySourceId( + previousPlexSettings, + library.id + ); + const nextSourceId = getPlexEpisodeAvailabilitySourceId( + updatedPlexSettings, + library.id + ); + if (previousSourceId === nextSourceId) continue; + try { + await clearEpisodeAvailabilityForSource({ + type: 'plex', + id: previousSourceId, + }); + } catch (error) { + logger.warn( + 'Unable to clear episode availability for the previous Plex server.', + { + libraryId: library.id, + errorMessage: + error instanceof Error ? error.message : String(error), + } + ); + } + } } catch (e) { logger.error('Something went wrong testing Plex connection', { label: 'API', @@ -1891,10 +1962,20 @@ settingsRoutes.post( if ('error' in enabledLibraries) { return res.status(400).json({ message: enabledLibraries.error }); } + const episodeOrder = parseLibraryEpisodeOrderUpdate(parsedBody.value); + if ('error' in episodeOrder) { + return res.status(400).json({ message: episodeOrder.error }); + } + if (sync.value && episodeOrder.value) { + return res.status(400).json({ + message: 'Library sync and episode order updates must be separate.', + }); + } return runWithConfigurationAdmission('plex', async () => { const settings = getSettings(); if (sync.value) { + const previousSettings = structuredClone(settings.plex); const userRepository = getRepository(User); const admin = await userRepository.findOneOrFail({ select: { id: true, plexToken: true }, @@ -1903,18 +1984,110 @@ settingsRoutes.post( const plexapi = new PlexAPI({ plexToken: admin.plexToken }); const libraries = await plexapi.syncLibraries({ - enabledLibraryIds: enabledLibraries.value, + enabledLibraryIds: + parsedBody.value.enable === undefined + ? undefined + : enabledLibraries.value, }); + for (const previousLibrary of previousSettings.libraries) { + if (previousLibrary.type !== 'show') continue; + const nextLibrary = libraries.find( + (library) => library.id === previousLibrary.id + ); + if ( + nextLibrary?.enabled && + nextLibrary.type === 'show' && + nextLibrary.episodeOrderProvider === + previousLibrary.episodeOrderProvider + ) { + continue; + } + + try { + await clearEpisodeAvailabilityForSource({ + type: 'plex', + id: getPlexEpisodeAvailabilitySourceId( + previousSettings, + previousLibrary.id + ), + }); + } catch (error) { + logger.warn('Unable to clear retired Plex episode availability.', { + libraryId: previousLibrary.id, + errorMessage: + error instanceof Error ? error.message : String(error), + }); + } + } return res.status(200).json(libraries); } + const previousLibraries = structuredClone(settings.plex.libraries); + if ( + episodeOrder.value && + !previousLibraries.some( + (library) => + library.id === episodeOrder.value!.libraryId && + library.type === 'show' + ) + ) { + return res.status(400).json({ + message: 'Episode order can only be set for an existing TV library.', + }); + } const plex = await settings.persistSection('plex', (current) => ({ ...current, - libraries: current.libraries.map((library) => ({ - ...library, - enabled: enabledLibraries.value.includes(library.id), - })), + libraries: current.libraries.map((library) => { + const nextLibrary = { + ...library, + enabled: + parsedBody.value.enable === undefined + ? library.enabled + : enabledLibraries.value.includes(library.id), + }; + if (episodeOrder.value?.libraryId === library.id) { + nextLibrary.episodeOrderProvider = + episodeOrder.value.provider === 'tmdb' + ? MetadataProviderType.TMDB + : episodeOrder.value.provider === 'tvdb' + ? MetadataProviderType.TVDB + : undefined; + } + return nextLibrary; + }), })); + + for (const previousLibrary of previousLibraries) { + if (previousLibrary.type !== 'show') continue; + const nextLibrary = plex.libraries.find( + (library) => library.id === previousLibrary.id + ); + if ( + nextLibrary?.enabled && + nextLibrary.type === 'show' && + nextLibrary.episodeOrderProvider === + previousLibrary.episodeOrderProvider + ) { + continue; + } + + const sourceId = getPlexEpisodeAvailabilitySourceId( + settings.plex, + previousLibrary.id + ); + try { + await clearEpisodeAvailabilityForSource({ + type: 'plex', + id: sourceId, + }); + } catch (error) { + logger.warn('Unable to clear retired Plex episode availability.', { + libraryId: previousLibrary.id, + errorMessage: + error instanceof Error ? error.message : String(error), + }); + } + } return res.status(200).json(plex.libraries); }); }) @@ -2095,6 +2268,7 @@ settingsRoutes.post( return runWithConfigurationAdmission('jellyfin', async () => { const userRepository = getRepository(User); const settings = getSettings(); + const previousJellyfinSettings = structuredClone(settings.jellyfin); const preservedBody = preserveConnectionApiKey( parsedBody.value, settings.jellyfin.apiKey @@ -2122,26 +2296,64 @@ settingsRoutes.post( const result = await jellyfinClient.getSystemInfo(); - await settings.persistSection('jellyfin', (current) => ({ - ...parsedJellyfin.value, - // A redacted API key means "keep the persisted value", not "keep - // the value that happened to be loaded before the connection test". - // Rebase it after the settings file is refreshed under its lock so - // a concurrent rotation cannot be undone. - apiKey: - parsedBody.value.apiKey === REDACTED_SECRET - ? current.apiKey - : parsedJellyfin.value.apiKey, - // See the analogous Plex machineId check above: a different - // serverId means a different physical server, so stale library - // ids must not carry over their enabled state to it. - libraries: - current.serverId && current.serverId !== result.Id - ? [] - : current.libraries, - serverId: result.Id, - name: result.ServerName, - })); + const updatedJellyfinSettings = await settings.persistSection( + 'jellyfin', + (current) => ({ + ...parsedJellyfin.value, + // A redacted API key means "keep the persisted value", not "keep + // the value that happened to be loaded before the connection test". + // Rebase it after the settings file is refreshed under its lock so + // a concurrent rotation cannot be undone. + apiKey: + parsedBody.value.apiKey === REDACTED_SECRET + ? current.apiKey + : parsedJellyfin.value.apiKey, + // See the analogous Plex machineId check above: a different + // serverId means a different physical server, so stale library + // ids must not carry over their enabled state to it. + libraries: + current.serverId && current.serverId !== result.Id + ? [] + : current.libraries, + serverId: result.Id, + name: result.ServerName, + }) + ); + + const sourceType = + settings.main.mediaServerType === MediaServerType.EMBY + ? 'emby' + : 'jellyfin'; + for (const library of previousJellyfinSettings.libraries) { + if (library.type !== 'show') continue; + const previousSourceId = getJellyfinEpisodeAvailabilitySourceId( + previousJellyfinSettings, + library.id, + sourceType + ); + const nextSourceId = getJellyfinEpisodeAvailabilitySourceId( + updatedJellyfinSettings, + library.id, + sourceType + ); + if (previousSourceId === nextSourceId) continue; + try { + await clearEpisodeAvailabilityForSource({ + type: sourceType, + id: previousSourceId, + }); + } catch (error) { + logger.warn( + 'Unable to clear episode availability for the previous media server.', + { + libraryId: library.id, + sourceType, + errorMessage: + error instanceof Error ? error.message : String(error), + } + ); + } + } } catch (e) { if (e instanceof ApiError) { logger.error('Something went wrong testing Jellyfin connection', { @@ -2198,9 +2410,32 @@ settingsRoutes.post( if ('error' in enabledLibraries) { return res.status(400).json({ message: enabledLibraries.error }); } + const episodeOrder = parseLibraryEpisodeOrderUpdate(parsedBody.value); + if ('error' in episodeOrder) { + return res.status(400).json({ message: episodeOrder.error }); + } + if (sync.value && episodeOrder.value) { + return res.status(400).json({ + message: 'Library sync and episode order updates must be separate.', + }); + } return runWithConfigurationAdmission('jellyfin', async () => { const settings = getSettings(); + const previousSettings = structuredClone(settings.jellyfin); + const previousLibraries = previousSettings.libraries; + if ( + episodeOrder.value && + !previousLibraries.some( + (library) => + library.id === episodeOrder.value!.libraryId && + library.type === 'show' + ) + ) { + return res.status(400).json({ + message: 'Episode order can only be set for an existing TV library.', + }); + } let synchronizedLibraries: Library[] | undefined; if (sync.value) { @@ -2250,6 +2485,7 @@ settingsRoutes.post( enabled: existing?.enabled ?? false, type: library.type, lastScan: existing?.lastScan, + episodeOrderProvider: existing?.episodeOrderProvider, }; }); @@ -2261,10 +2497,64 @@ settingsRoutes.post( libraries: (synchronizedLibraries ?? current.libraries).map( (library) => ({ ...library, - enabled: enabledLibraries.value.includes(library.id), + enabled: + parsedBody.value.enable === undefined + ? library.enabled + : enabledLibraries.value.includes(library.id), + ...(episodeOrder.value?.libraryId === library.id + ? { + episodeOrderProvider: + episodeOrder.value.provider === 'tmdb' + ? MetadataProviderType.TMDB + : episodeOrder.value.provider === 'tvdb' + ? MetadataProviderType.TVDB + : undefined, + } + : {}), }) ), })); + + const sourceType = + settings.main.mediaServerType === MediaServerType.EMBY + ? 'emby' + : 'jellyfin'; + for (const previousLibrary of previousLibraries) { + if (previousLibrary.type !== 'show') continue; + const nextLibrary = jellyfin.libraries.find( + (library) => library.id === previousLibrary.id + ); + if ( + nextLibrary?.enabled && + nextLibrary.type === 'show' && + nextLibrary.episodeOrderProvider === + previousLibrary.episodeOrderProvider + ) { + continue; + } + + const sourceId = getJellyfinEpisodeAvailabilitySourceId( + previousSettings, + previousLibrary.id, + sourceType + ); + try { + await clearEpisodeAvailabilityForSource({ + type: sourceType, + id: sourceId, + }); + } catch (error) { + logger.warn( + 'Unable to clear retired media-server episode availability.', + { + libraryId: previousLibrary.id, + sourceType, + errorMessage: + error instanceof Error ? error.message : String(error), + } + ); + } + } return res.status(200).json(jellyfin.libraries); }); }) diff --git a/server/routes/settings/sonarr.ts b/server/routes/settings/sonarr.ts index bdc746c4cc..e4cc7e7fe7 100644 --- a/server/routes/settings/sonarr.ts +++ b/server/routes/settings/sonarr.ts @@ -1,4 +1,5 @@ import SonarrAPI from '@server/api/servarr/sonarr'; +import { clearSonarrEpisodeAvailabilityForService } from '@server/lib/episodeAvailability'; import { getExternalRuntimeConfig } from '@server/lib/externalRuntimeConfig'; import { Permission } from '@server/lib/permissions'; import { runWithServarrServiceCollectionMutationAdmission } from '@server/lib/serviceAdmission'; @@ -303,6 +304,19 @@ sonarrRoutes.delete<{ id: string }>( current.filter(({ id }) => id !== sonarrId) ); + try { + await clearSonarrEpisodeAvailabilityForService(sonarrId); + } catch (error) { + logger.warn( + 'Could not clear episode availability after removing a Sonarr service.', + { + errorMessage: + error instanceof Error ? error.message : String(error), + serviceId: sonarrId, + } + ); + } + return res.status(200).json(redactSecrets(removed)); } ); diff --git a/server/routes/tv.ts b/server/routes/tv.ts index 3bd95f20d7..f831899e1f 100644 --- a/server/routes/tv.ts +++ b/server/routes/tv.ts @@ -14,8 +14,17 @@ import { MediaType } from '@server/constants/media'; import { getRepository } from '@server/datasource'; import Media from '@server/entity/Media'; import { Watchlist } from '@server/entity/Watchlist'; +import { + getActiveEpisodeAvailabilitySources, + getEpisodeAvailability, +} from '@server/lib/episodeAvailability'; +import { getExternalRuntimeConfig } from '@server/lib/externalRuntimeConfig'; import { enqueueImageCacheWarm } from '@server/lib/imageCacheWarmer'; import { upsertMediaSearchMetadata } from '@server/lib/mediaSearchMetadata'; +import { + getMediaServerAccessContext, + restrictEpisodeAvailabilityForUser, +} from '@server/lib/mediaServerAvailability'; import { getSettings, MetadataProviderType, @@ -412,11 +421,12 @@ tvRoutes.get('/:id/season/:seasonNumber', async (req, res, next) => { ) { return next({ status: 404, message: 'Season not found.' }); } - const metadataProvider = tmdbTv.keywords.results.some( + const isAnime = tmdbTv.keywords.results.some( (keyword: TmdbKeyword) => keyword.id === ANIME_KEYWORD_ID - ) - ? await getMetadataProvider('anime') - : await getMetadataProvider('tv'); + ); + const metadataProvider = await getMetadataProvider( + isAnime ? 'anime' : 'tv' + ); const season = await metadataProvider.getTvSeason({ tvId, @@ -424,7 +434,54 @@ tvRoutes.get('/:id/season/:seasonNumber', async (req, res, next) => { language, }); - return res.status(200).json(mapSeasonWithEpisodes(season)); + const mappedSeason = mapSeasonWithEpisodes(season); + const settings = getSettings(); + const metadataSource = isAnime + ? settings.metadataSettings.anime + : settings.metadataSettings.tv; + if (settings.main.trackEpisodeAvailability) { + const availabilitySources = getActiveEpisodeAvailabilitySources( + metadataSource, + { + sonarr: getExternalRuntimeConfig().sonarr, + plex: settings.plex, + jellyfin: settings.jellyfin, + mediaServerType: settings.main.mediaServerType, + }, + settings.main.enable4k + ); + const availability = await getEpisodeAvailability( + tvId, + seasonNumber, + metadataSource, + availabilitySources, + settings.main.enable4k + ); + await restrictEpisodeAvailabilityForUser( + availability, + await getRepository(Media).findOneBy({ + tmdbId: tvId, + mediaType: MediaType.TV, + }), + await getMediaServerAccessContext(req.user), + seasonNumber + ); + mappedSeason.episodes = mappedSeason.episodes.map((episode) => { + const episodeAvailability = availability.get(episode.episodeNumber); + if (!episodeAvailability) return episode; + return { + ...episode, + ...(episodeAvailability.sonarrAvailability + ? { sonarrAvailability: episodeAvailability.sonarrAvailability } + : {}), + ...(episodeAvailability.sources.length > 0 + ? { availabilitySources: episodeAvailability.sources } + : {}), + }; + }); + } + + return res.status(200).json(mappedSeason); } catch (e) { logger.debug('Something went wrong retrieving season', { label: 'API', diff --git a/server/subscriber/MediaRequestSubscriber.ts b/server/subscriber/MediaRequestSubscriber.ts index 48bb9e715c..9bdd63cfb6 100644 --- a/server/subscriber/MediaRequestSubscriber.ts +++ b/server/subscriber/MediaRequestSubscriber.ts @@ -57,6 +57,7 @@ import { normalizeOpenLibraryWorkId, } from '@server/lib/externalIds'; import { getExternalRuntimeConfig } from '@server/lib/externalRuntimeConfig'; +import { resolveFutureSeasonMonitoring } from '@server/lib/futureSeasonMonitoring'; import { normalizeValidIsbn } from '@server/lib/isbn'; import { cleanMagazineTitle, @@ -89,7 +90,9 @@ import { type SonarrSettings, } from '@server/lib/settings'; import { isSportarrLeagueExternalId } from '@server/lib/sportarrIdentity'; +import { isTvSeasonWatchGateEnabledForUser } from '@server/lib/tvSeasonWatchGate'; import logger from '@server/logger'; +import { isProviderBookEdition } from '@server/utils/bookEdition'; import { parseBookshelfBookId } from '@server/utils/bookshelfCatalog'; import { hydrateBookshelfLookupResult, @@ -1863,12 +1866,17 @@ export class MediaRequestSubscriber implements EntitySubscriberInterface season.seasonNumber), - series.seasons.map((season) => season.season_number) + ...resolveFutureSeasonMonitoring( + entity.monitorFutureSeasons, + (entity.watchAheadEpisodeCount ?? 0) > 0 || + isTvSeasonWatchGateEnabledForUser(entity.requestedBy), + resolveSonarrMonitorNewItems( + sonarrSettings.monitorNewItems, + entity.seasons + .filter(isActiveSeasonRequest) + .map((season) => season.seasonNumber), + series.seasons.map((season) => season.season_number) + ) ), searchNow: !sonarrSettings.preventSearch, }; @@ -2270,7 +2278,11 @@ export class MediaRequestSubscriber implements EntitySubscriberInterface { return true; } + if (isProviderBookEdition(request.preferredEditionId)) + return request.status === MediaRequestStatus.COMPLETED; return isRequestedBookFormatAvailable(media, request.bookFormat ?? 'ebook'); } diff --git a/server/test/fixtures/delayed-reporter.fixture.mjs b/server/test/fixtures/delayed-reporter.fixture.mjs new file mode 100644 index 0000000000..c481bc0e84 --- /dev/null +++ b/server/test/fixtures/delayed-reporter.fixture.mjs @@ -0,0 +1,9 @@ +export default async function* delayedReporter(events) { + for await (const event of events) { + if (event.type === 'test:summary' && event.data.file === undefined) { + // A formatter or filesystem sink can still have work after the tests end. + await new Promise((resolve) => setTimeout(resolve, 200)); + yield `Complete summary: ${event.data.counts.tests} tests; success=${event.data.success}\n`; + } + } +} diff --git a/server/test/fixtures/runner-report.fixture.ts b/server/test/fixtures/runner-report.fixture.ts new file mode 100644 index 0000000000..72f2369050 --- /dev/null +++ b/server/test/fixtures/runner-report.fixture.ts @@ -0,0 +1,14 @@ +import { describe, it } from 'node:test'; + +// Simulate an imported service whose handle outlives the test assertions. +setInterval(() => {}, 60000); + +// Enough IPC output to exceed a single reporter buffer. This is only invoked +// by runner.test.ts; it is not part of the normal *.test.ts discovery pattern. +for (let suite = 0; suite < 80; suite++) { + describe(`suite ${suite}`, () => { + for (let item = 0; item < 20; item++) { + it(`item ${item}`, () => {}); + } + }); +} diff --git a/server/test/index.mts b/server/test/index.mts index af2a5afad5..4dc14a908e 100644 --- a/server/test/index.mts +++ b/server/test/index.mts @@ -1,12 +1,12 @@ // Runs unit tests using the `node:test` runner. import { Command, Option } from 'commander'; -import { createWriteStream, mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'; import { glob, readFile } from 'node:fs/promises'; import { availableParallelism, tmpdir } from 'node:os'; -import { join, resolve } from 'node:path'; -import { run } from 'node:test'; -import * as reporters from 'node:test/reporters'; +import { join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { setIsolatedTestEnvironment } from './test-environment.mjs'; @@ -110,30 +110,38 @@ process.on('exit', () => { process.env.TS_NODE_PROJECT = resolveImport('../tsconfig.json'); process.env.TS_NODE_FILES = 'true'; -const stream = run({ - files, - // Process isolation gives each file its own application DataSource and - // in-memory SQLite database while keeping concurrent work bounded. - concurrency: testConcurrency, - isolation: 'process', - execArgv: [ - '--experimental-test-module-mocks', - '-r', - 'ts-node/register', - '-r', - 'tsconfig-paths/register', - '-r', - resolveImport('./setup.ts'), - ], - coverage: opts.experimentalTestCoverage, - coverageExcludeGlobs: [ - join(BASE_DIR, 'server/test/**'), - join(BASE_DIR, 'server/migration/**'), - ], - testNamePatterns: opts.testNamePattern, - // ensure test process doesn't hang when tests fail - forceExit: true, -}); +// Delegate reporting and shutdown to Node's CLI. Manually composing reporters +// around run() can return zero with a truncated report after a large run. The +// CLI owns reporter completion, worker shutdown and the aggregate exit status. +const args = [ + '--test', + '--test-isolation=process', + '--test-force-exit', + '--experimental-test-module-mocks', + `--test-concurrency=${testConcurrency}`, + '--require', + resolveImport('./worker-bootstrap.cjs'), +]; +if (opts.experimentalTestCoverage) { + args.push( + '--experimental-test-coverage', + `--test-coverage-exclude=${join(BASE_DIR, 'server/test/**')}`, + `--test-coverage-exclude=${join(BASE_DIR, 'server/migration/**')}` + ); +} +for (const pattern of opts.testNamePattern) { + args.push('--test-name-pattern', pattern); +} +const addReporter = (reporter: string, destination: string) => { + args.push( + '--test-reporter', + reporter, + '--test-reporter-destination', + destination === 'stdout' || destination === 'stderr' + ? destination + : resolve(destination) + ); +}; // A failed assertion or test file sets the final exit status but does not stop // the remaining files. Preserve a complete, human-readable local report for a @@ -143,47 +151,46 @@ if (isFullSuite && !runningInCi) { const reportTimestamp = new Date().toISOString().replace(/[:.]/g, '-'); const reportPath = join(reportDirectory, `unit-tests-${reportTimestamp}.log`); mkdirSync(reportDirectory, { recursive: true }); - stream.compose(reporters.spec).pipe(createWriteStream(reportPath)); + addReporter('spec', reportPath); console.log(`Full test report: ${reportPath}`); } -// Unlike `node --test`, the programmatic runner does not set a failing process -// status for us. Propagate any failed test file, assertion, or compilation to -// callers and CI. -stream.on('test:fail', () => { - process.exitCode = 1; -}); - // In CI, write a JUnit report to a file for use by GitHub if (runningInCi) { - const reportStream = createWriteStream(join(BASE_DIR, 'report.xml')); - stream.compose(reporters.junit).pipe(reportStream); + addReporter('junit', join(BASE_DIR, 'report.xml')); } if (opts.testReporter.length > 0) { for (let i = 0; i < opts.testReporter.length; i++) { - const reporterName = opts.testReporter[i]; - // check built-in reporters, otherwise import - const reporter = - reporterName in reporters - ? reporters[reporterName as keyof typeof reporters] - : await import(reporterName).then((m) => m.default); - - if (reporter == null) { - console.error('Invalid test reporter: ', reporterName); - process.exit(1); - } - - const destArg = opts.testReporterDestination[i]; - const dest = - destArg === 'stdout' || destArg == null - ? process.stdout - : destArg === 'stderr' - ? process.stderr - : createWriteStream(destArg); - - stream.compose(reporter).pipe(dest); + addReporter( + opts.testReporter[i], + opts.testReporterDestination[i] ?? 'stdout' + ); } } else { - stream.compose(reporters.spec).pipe(process.stdout); + addReporter('spec', 'stdout'); +} + +// Relative file arguments keep a full checkout below Windows' command-line +// length limit while preserving each test file's own isolated process. +const child = spawn( + process.execPath, + [...args, '--', ...files.map((file) => relative(BASE_DIR, file))], + { + cwd: BASE_DIR, + env: process.env, + stdio: 'inherit', + } +); +const interrupt = () => child.kill('SIGINT'); +const terminate = () => child.kill('SIGTERM'); +process.on('SIGINT', interrupt); +process.on('SIGTERM', terminate); +try { + const [code, signal] = await once(child, 'close'); + process.exitCode = + code ?? (signal === 'SIGINT' ? 130 : signal === 'SIGTERM' ? 143 : 1); +} finally { + process.off('SIGINT', interrupt); + process.off('SIGTERM', terminate); } diff --git a/server/test/loopbackHttpRequest.ts b/server/test/loopbackHttpRequest.ts new file mode 100644 index 0000000000..169b7192fb --- /dev/null +++ b/server/test/loopbackHttpRequest.ts @@ -0,0 +1,29 @@ +import http from 'node:http'; + +export type LoopbackHttpResponse = { + statusCode: number | undefined; + headers: http.IncomingHttpHeaders; + body: string; +}; + +/** Make a direct local request without routing loopback traffic through proxies. */ +export const getLoopbackHttpResponse = ( + url: string +): Promise => + new Promise((resolve, reject) => { + const request = http.get(url, (response) => { + const chunks: Buffer[] = []; + response.on('data', (chunk: Buffer | string) => + chunks.push(Buffer.from(chunk)) + ); + response.once('error', reject); + response.once('end', () => + resolve({ + statusCode: response.statusCode, + headers: response.headers, + body: Buffer.concat(chunks).toString('utf8'), + }) + ); + }); + request.once('error', reject); + }); diff --git a/server/test/runner.test.ts b/server/test/runner.test.ts index ebf541978b..d29554b452 100644 --- a/server/test/runner.test.ts +++ b/server/test/runner.test.ts @@ -1,8 +1,11 @@ import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import { once } from 'node:events'; +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; import path from 'node:path'; import { test } from 'node:test'; +import { pathToFileURL } from 'node:url'; test('the custom test runner returns a failure status', async () => { const repoRoot = path.resolve(__dirname, '../..'); @@ -13,6 +16,8 @@ test('the custom test runner returns a failure status', async () => { // Node marks test-runner children to prevent accidental recursive run() // calls. This subprocess intentionally starts an independent runner. delete childEnvironment['NODE_TEST_CONTEXT']; + // Nested regression invocations must not overwrite the enclosing CI report. + delete childEnvironment['CI']; const child = spawn( process.execPath, [ @@ -42,3 +47,96 @@ test('the custom test runner returns a failure status', async () => { assert.strictEqual(signal, null, output); assert.match(output, /intentional runner failure/); }); + +test('the custom runner drains complete high-volume reports to every destination', async () => { + const repoRoot = path.resolve(__dirname, '../..'); + const directory = await mkdtemp(path.join(tmpdir(), 'seerr-runner-report-')); + const reportPath = path.join(directory, 'report.log'); + const childEnvironment: NodeJS.ProcessEnv = { + ...process.env, + NODE_ENV: 'test', + }; + delete childEnvironment['NODE_TEST_CONTEXT']; + delete childEnvironment['CI']; + const child = spawn( + process.execPath, + [ + path.join(repoRoot, 'server/test/index.mts'), + path.join(repoRoot, 'server/test/fixtures/runner-report.fixture.ts'), + '--coverage', + '--test-reporter', + 'spec', + '--test-reporter-destination', + 'stdout', + '--test-reporter', + 'spec', + '--test-reporter-destination', + reportPath, + ], + { cwd: repoRoot, env: childEnvironment, stdio: ['ignore', 'pipe', 'pipe'] } + ); + let output = ''; + child.stdout.on('data', (chunk) => { + output += chunk.toString(); + }); + child.stderr.on('data', (chunk) => { + output += chunk.toString(); + }); + const deadline = setTimeout(() => child.kill('SIGKILL'), 60000); + try { + const [code, signal] = await once(child, 'close'); + assert.equal(code, 0, output); + assert.equal(signal, null, output); + for (const report of [output, await readFile(reportPath, 'utf8')]) { + assert.match(report, /suite 79/); + assert.match(report, /tests 1600/); + assert.match(report, /pass 1600/); + assert.match(report, /fail 0/); + assert.match(report, /duration_ms/); + assert.match(report, /start of coverage report/); + } + } finally { + clearTimeout(deadline); + if (child.exitCode === null && child.signalCode === null) child.kill(); + await rm(directory, { recursive: true, force: true }); + } +}); + +test('the runner exits service workers but waits for asynchronous final reports', async () => { + const repoRoot = path.resolve(__dirname, '../..'); + const childEnvironment: NodeJS.ProcessEnv = { + ...process.env, + NODE_ENV: 'test', + }; + delete childEnvironment['NODE_TEST_CONTEXT']; + delete childEnvironment['CI']; + const child = spawn( + process.execPath, + [ + path.join(repoRoot, 'server/test/index.mts'), + path.join(repoRoot, 'server/test/fixtures/runner-report.fixture.ts'), + '--test-reporter', + pathToFileURL( + path.join(repoRoot, 'server/test/fixtures/delayed-reporter.fixture.mjs') + ).href, + ], + { cwd: repoRoot, env: childEnvironment, stdio: ['ignore', 'pipe', 'pipe'] } + ); + let output = ''; + child.stdout.on('data', (chunk) => { + output += chunk.toString(); + }); + child.stderr.on('data', (chunk) => { + output += chunk.toString(); + }); + const deadline = setTimeout(() => child.kill('SIGKILL'), 60000); + try { + const [code, signal] = await once(child, 'close'); + assert.equal(code, 0, output); + assert.equal(signal, null, output); + assert.match(output, /Complete summary: 1600 tests; success=true/); + } finally { + clearTimeout(deadline); + if (child.exitCode === null && child.signalCode === null) child.kill(); + } +}); diff --git a/server/test/worker-bootstrap.cjs b/server/test/worker-bootstrap.cjs new file mode 100644 index 0000000000..a308aad778 --- /dev/null +++ b/server/test/worker-bootstrap.cjs @@ -0,0 +1,13 @@ +// Only the native test CLI preloads this module; application startup does not. +// Forced exits must not discard pending result writes to a redirected pipe. +for (const output of [process.stdout, process.stderr]) { + output._handle?.setBlocking?.(true); +} + +// Load application/test hooks only in isolated workers. Loading node:test hooks +// in the CLI coordinator would create a second, unrelated root test harness. +if (process.env.NODE_TEST_CONTEXT === 'child-v8') { + require('ts-node/register'); + require('tsconfig-paths/register'); + require('./setup.ts'); +} diff --git a/server/utils/bookEdition.ts b/server/utils/bookEdition.ts new file mode 100644 index 0000000000..465678f97e --- /dev/null +++ b/server/utils/bookEdition.ts @@ -0,0 +1,6 @@ +/** + * Open Library edition IDs describe ISBN metadata, not a provider's recording. + * Older clients persist these with preferredIsbn13; keep their request semantics. + */ +export const isProviderBookEdition = (id?: string | null): boolean => + !!id?.trim() && !/^(?:\/?books\/)?OL\d+M$/i.test(id.trim()); diff --git a/server/utils/httpServer.test.ts b/server/utils/httpServer.test.ts index 7b463a477c..a60e7d32df 100644 --- a/server/utils/httpServer.test.ts +++ b/server/utils/httpServer.test.ts @@ -1,6 +1,7 @@ import assert from 'node:assert/strict'; import http from 'node:http'; import { describe, it } from 'node:test'; +import { Agent, fetch as directFetch } from 'undici'; import { HTTP_SERVER_LIMITS, configureHttpServer, @@ -56,6 +57,7 @@ describe('configureHttpServer', () => { describe('startLoopbackHttpServer', () => { it('serves its handler on an ephemeral loopback-only port', async () => { + const dispatcher = new Agent(); const { server, port } = await startLoopbackHttpServer( (_request, response) => { response.writeHead(200, { 'Content-Type': 'text/plain' }); @@ -69,10 +71,14 @@ describe('startLoopbackHttpServer', () => { assert.equal(address.address, '127.0.0.1'); assert.equal(address.port, port); - const response = await fetch(`http://127.0.0.1:${port}/api/v1/movie/1`); + const response = await directFetch( + `http://127.0.0.1:${port}/api/v1/movie/1`, + { dispatcher } + ); assert.equal(response.status, 200); assert.equal(await response.text(), 'internal API'); } finally { + await dispatcher.close(); await new Promise((resolve, reject) => { server.close((error) => (error ? reject(error) : resolve())); }); diff --git a/server/utils/interfaceTheme.ts b/server/utils/interfaceTheme.ts index bc125b8bdd..92528c70a6 100644 --- a/server/utils/interfaceTheme.ts +++ b/server/utils/interfaceTheme.ts @@ -1,11 +1,17 @@ /** Stable identifiers for installed application interface systems. */ export const DEFAULT_INTERFACE_THEME_ID = 'seerrOrig'; -export const INTERFACE_THEME_IDS = ['seerrOrig', 'seerrNGJ'] as const; +export const INTERFACE_THEME_IDS = [ + 'seerrOrig', + 'seerrNGJ', + 'persiusNG', +] as const; /** Custom theme IDs are lowercase kebab-case; built-in IDs retain their names. */ export type InterfaceThemeId = string; export type InterfaceThemeNavigation = 'flat' | 'grouped'; +export type InterfaceThemeLayout = 'classic' | 'persius'; + export type InterfaceThemeActiveNavigationIcon = 'outline' | 'filled'; export type InterfaceThemeManifest = { @@ -19,6 +25,8 @@ export type InterfaceThemeManifest = { license: string; navigation: InterfaceThemeNavigation; activeNavigationIcon: InterfaceThemeActiveNavigationIcon; + /** App-owned page composition; CSS remains unique to this package. */ + layout?: InterfaceThemeLayout; }; const customThemeIdPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; diff --git a/server/utils/interfaceThemeFile.test.ts b/server/utils/interfaceThemeFile.test.ts new file mode 100644 index 0000000000..5e279b6c10 --- /dev/null +++ b/server/utils/interfaceThemeFile.test.ts @@ -0,0 +1,71 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { it } from 'node:test'; +import { readInterfaceThemeFile } from './interfaceThemeFile'; + +// Retain the native call-through before any runner can reuse a spy object. +const openFile = fs.openSync.bind(fs); + +it('reads bounded UTF-8 theme data and rejects hard links and oversized files', (t) => { + const directory = fs.mkdtempSync(path.join(tmpdir(), 'seerr-theme-file-')); + t.after(() => fs.rmSync(directory, { recursive: true, force: true })); + const filename = path.join(directory, 'theme.css'); + fs.writeFileSync(filename, '🎬'); + assert.equal(readInterfaceThemeFile(filename, 4), '🎬'); + assert.throws( + () => readInterfaceThemeFile(filename, 3), + /bounded regular file/ + ); + fs.linkSync(filename, path.join(directory, 'linked.css')); + assert.throws( + () => readInterfaceThemeFile(filename, 4), + /bounded regular file/ + ); +}); + +it( + 'rejects a symlink substituted between validation and open', + { skip: process.platform === 'win32' }, + (t) => { + const directory = fs.mkdtempSync(path.join(tmpdir(), 'seerr-theme-race-')); + t.after(() => fs.rmSync(directory, { recursive: true, force: true })); + const filename = path.join(directory, 'theme.css'); + const privateFile = path.join(directory, 'private.css'); + fs.writeFileSync(filename, 'safe'); + fs.writeFileSync(privateFile, 'private'); + t.after(() => t.mock.restoreAll()); + t.mock.method(fs, 'openSync', (...args: Parameters) => { + if (args[0] === filename) { + fs.unlinkSync(filename); + fs.symlinkSync(privateFile, filename); + } + return openFile(...args); + }); + assert.throws(() => readInterfaceThemeFile(filename, 32)); + assert.equal(fs.readFileSync(privateFile, 'utf8'), 'private'); + } +); + +it('rejects a replacement regular file and closes the opened descriptor', (t) => { + const directory = fs.mkdtempSync(path.join(tmpdir(), 'seerr-theme-replace-')); + t.after(() => fs.rmSync(directory, { recursive: true, force: true })); + const filename = path.join(directory, 'theme.css'); + const replacement = path.join(directory, 'replacement.css'); + fs.writeFileSync(filename, 'safe'); + fs.writeFileSync(replacement, 'other'); + t.after(() => t.mock.restoreAll()); + let descriptor: number | undefined; + t.mock.method(fs, 'openSync', (...args: Parameters) => { + if (args[0] === filename) fs.renameSync(replacement, filename); + descriptor = openFile(...args); + return descriptor; + }); + assert.throws( + () => readInterfaceThemeFile(filename, 32), + /changed while opening/ + ); + assert.notEqual(descriptor, undefined); + assert.throws(() => fs.fstatSync(descriptor!), { code: 'EBADF' }); +}); diff --git a/server/utils/interfaceThemeFile.ts b/server/utils/interfaceThemeFile.ts new file mode 100644 index 0000000000..29f6b3ebce --- /dev/null +++ b/server/utils/interfaceThemeFile.ts @@ -0,0 +1,79 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +/** Read the same bounded regular file we validated, without following links. */ +export const readInterfaceThemeFile = ( + filename: string, + maxBytes: number +): string => { + if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) { + throw new Error('Invalid theme package size limit.'); + } + const directory = path.dirname(path.resolve(filename)); + const parent = fs.lstatSync(directory); + const before = fs.lstatSync(filename); + if ( + !parent.isDirectory() || + parent.isSymbolicLink() || + !before.isFile() || + before.isSymbolicLink() || + before.nlink !== 1 || + before.size > maxBytes + ) { + throw new Error( + 'Theme package file is not a supported bounded regular file.' + ); + } + const descriptor = fs.openSync( + filename, + fs.constants.O_RDONLY | + (fs.constants.O_NOFOLLOW ?? 0) | + (fs.constants.O_NONBLOCK ?? 0) + ); + try { + const opened = fs.fstatSync(descriptor); + if ( + !opened.isFile() || + opened.nlink !== 1 || + opened.size > maxBytes || + opened.dev !== before.dev || + opened.ino !== before.ino + ) { + throw new Error('Theme package file changed while opening.'); + } + const bytes = Buffer.alloc(maxBytes + 1); + let length = 0; + while (length < bytes.length) { + const count = fs.readSync( + descriptor, + bytes, + length, + bytes.length - length, + null + ); + if (count === 0) break; + length += count; + } + const after = fs.fstatSync(descriptor); + const current = fs.lstatSync(filename); + const currentParent = fs.lstatSync(directory); + if ( + length > maxBytes || + after.nlink !== 1 || + after.size !== opened.size || + after.mtimeMs !== opened.mtimeMs || + after.ctimeMs !== opened.ctimeMs || + current.isSymbolicLink() || + current.dev !== opened.dev || + current.ino !== opened.ino || + currentParent.isSymbolicLink() || + currentParent.dev !== parent.dev || + currentParent.ino !== parent.ino + ) { + throw new Error('Theme package file changed while reading.'); + } + return bytes.subarray(0, length).toString('utf8'); + } finally { + fs.closeSync(descriptor); + } +}; diff --git a/server/utils/interfaceThemePackage.test.ts b/server/utils/interfaceThemePackage.test.ts index 6afcaca26a..fdcff086fd 100644 --- a/server/utils/interfaceThemePackage.test.ts +++ b/server/utils/interfaceThemePackage.test.ts @@ -1,5 +1,8 @@ import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; import { describe, it } from 'node:test'; +import { INTERFACE_THEME_IDS } from './interfaceTheme'; import { validateInterfaceThemeCss, validateInterfaceThemeManifest, @@ -20,6 +23,18 @@ const manifest = { } as const; describe('interface theme package contract', () => { + it('loads every registered built-in package with its exact ID and scoped CSS', () => { + for (const id of INTERFACE_THEME_IDS) { + const directory = resolve(process.cwd(), 'themes', id); + const result = validateInterfaceThemePackage( + JSON.parse(readFileSync(resolve(directory, 'manifest.json'), 'utf8')), + readFileSync(resolve(directory, 'theme.css'), 'utf8'), + id + ); + assert.equal(result.manifest.id, id); + } + }); + it('validates metadata and selectors scoped to the package theme root', () => { const css = ` :root[data-interface-theme='studio-dark'] { @@ -39,6 +54,22 @@ describe('interface theme package contract', () => { assert.equal(theme.css, css); }); + it('supports native composition without changing legacy manifests', () => { + assert.equal(validateInterfaceThemeManifest(manifest).layout, undefined); + assert.equal( + validateInterfaceThemeManifest({ ...manifest, layout: 'persius' }).layout, + 'persius' + ); + assert.equal( + validateInterfaceThemeManifest({ ...manifest, layout: 'classic' }).layout, + 'classic' + ); + assert.throws( + () => validateInterfaceThemeManifest({ ...manifest, layout: 'script' }), + /layout must be/ + ); + }); + it('rejects an unscoped rule and selector groups with any global selector', () => { assert.throws( () => validateInterfaceThemeCss('body { color: red; }', manifest.id), @@ -67,6 +98,21 @@ describe('interface theme package contract', () => { } }); + it('rejects resource functions split by CSS comments', () => { + for (const value of [ + 'u/**/rl(https://example.invalid/pixel.png)', + 'url/**/(https://example.invalid/pixel.png)', + 'image/**/-set("https://example.invalid/pixel.png" 1x)', + ]) { + assert.throws(() => + validateInterfaceThemeCss( + `[data-interface-theme='${manifest.id}'] .page { background-image: ${value}; }`, + manifest.id + ) + ); + } + }); + it('allows namespaced package keyframes and rejects unknown package fields', () => { assert.doesNotThrow(() => validateInterfaceThemeCss( diff --git a/server/utils/interfaceThemePackage.ts b/server/utils/interfaceThemePackage.ts index 8de236a93a..739439ac1b 100644 --- a/server/utils/interfaceThemePackage.ts +++ b/server/utils/interfaceThemePackage.ts @@ -1,5 +1,8 @@ import postcss, { type AtRule } from 'postcss'; -import type { InterfaceThemeManifest } from './interfaceTheme'; +import { + INTERFACE_THEME_IDS, + type InterfaceThemeManifest, +} from './interfaceTheme'; export const INTERFACE_THEME_FORMAT_VERSION = 1; export const INTERFACE_THEME_API_VERSION = 1; @@ -28,10 +31,11 @@ const allowedManifestKeys = new Set([ 'license', 'navigation', 'activeNavigationIcon', + 'layout', ]); const customThemeIdPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; -const builtInThemeIds = new Set(['seerrOrig', 'seerrNGJ']); +const builtInThemeIds = new Set(INTERFACE_THEME_IDS); const allowedAtRules = new Set(['media', 'supports', 'container']); const keyframesAtRules = new Set(['keyframes', '-webkit-keyframes']); const dangerousCssValuePattern = @@ -117,6 +121,14 @@ export const validateInterfaceThemeManifest = ( return fail('activeNavigationIcon must be outline or filled'); } + if ( + value.layout !== undefined && + value.layout !== 'classic' && + value.layout !== 'persius' + ) { + return fail('layout must be classic or persius'); + } + return { formatVersion: INTERFACE_THEME_FORMAT_VERSION, themeApiVersion: INTERFACE_THEME_API_VERSION, @@ -128,6 +140,7 @@ export const validateInterfaceThemeManifest = ( license: requireText(value.license, 'license', 48), navigation: value.navigation, activeNavigationIcon: value.activeNavigationIcon, + ...(value.layout !== undefined ? { layout: value.layout } : {}), }; }; diff --git a/server/utils/interfaceThemeRegistry.test.ts b/server/utils/interfaceThemeRegistry.test.ts index 02ef6859a4..e24c9be1cb 100644 --- a/server/utils/interfaceThemeRegistry.test.ts +++ b/server/utils/interfaceThemeRegistry.test.ts @@ -17,16 +17,22 @@ after(() => { }); describe('built-in interface theme packages', () => { - it('loads two validated packages with independent layout metadata and CSS', () => { + it('loads three validated packages with independent layout metadata and CSS', () => { const themes = listInstalledInterfaceThemes(); assert.deepEqual( themes.map(({ id }) => id), - ['seerrOrig', 'seerrNGJ'] + ['seerrOrig', 'seerrNGJ', 'persiusNG'] ); assert.equal(themes[0].navigation, 'flat'); assert.equal(themes[1].navigation, 'grouped'); assert.equal(themes[0].activeNavigationIcon, 'outline'); assert.equal(themes[1].activeNavigationIcon, 'filled'); + assert.equal(themes[2].navigation, 'grouped'); + assert.equal(themes[2].activeNavigationIcon, 'outline'); + assert.match( + getInstalledInterfaceTheme('persiusNG')?.css ?? '', + /--interface-sidebar-width: 244px/ + ); assert.notEqual( getInstalledInterfaceTheme('seerrOrig')?.css, getInstalledInterfaceTheme('seerrNGJ')?.css diff --git a/server/utils/interfaceThemeRegistry.ts b/server/utils/interfaceThemeRegistry.ts index 1a52b87ede..4cc279fa13 100644 --- a/server/utils/interfaceThemeRegistry.ts +++ b/server/utils/interfaceThemeRegistry.ts @@ -1,11 +1,12 @@ -import { appDataPath } from '@server/utils/appDataVolume'; -import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs'; +import { existsSync, lstatSync, readdirSync } from 'node:fs'; import path from 'node:path'; +import { appDataPath } from './appDataVolume'; import { INTERFACE_THEME_IDS, parseInterfaceTheme, type InterfaceThemeManifest, } from './interfaceTheme'; +import { readInterfaceThemeFile } from './interfaceThemeFile'; import { MAX_INSTALLED_INTERFACE_THEME_CSS_BYTES, MAX_INSTALLED_INTERFACE_THEMES, @@ -27,16 +28,10 @@ const builtInThemeRoot = (): string => { ) { return compiledRoot; } - return path.resolve(process.cwd(), 'themes'); + return path.resolve(__dirname, '../../themes'); }; -const regularFile = (filename: string, maxBytes: number): string => { - const stat = lstatSync(filename); - if (stat.isSymbolicLink() || !stat.isFile() || stat.size > maxBytes) { - throw new Error('Theme package file is not a supported regular file.'); - } - return readFileSync(filename, 'utf8'); -}; +const regularFile = readInterfaceThemeFile; const readPackageDirectory = ( directory: string, diff --git a/server/utils/servarrSettings.ts b/server/utils/servarrSettings.ts index 19ab8215a6..4e787b2601 100644 --- a/server/utils/servarrSettings.ts +++ b/server/utils/servarrSettings.ts @@ -29,6 +29,24 @@ const MAX_SERVICE_TAGS = 100; const MAX_SERVICE_PORT = 65535; const MAX_SERVICE_ID = 1_000_000; export const MAX_SERVARR_INSTANCES_PER_TYPE = 50; +export const DEFAULT_SERVARR_DOWNLOAD_QUEUE_SIZE = 1_000; +export const MIN_SERVARR_DOWNLOAD_QUEUE_SIZE = 10; +export const MAX_SERVARR_DOWNLOAD_QUEUE_SIZE = 10_000; + +export const validateServarrDownloadQueueSize = (value: unknown): number => { + if ( + typeof value !== 'number' || + !Number.isSafeInteger(value) || + value < MIN_SERVARR_DOWNLOAD_QUEUE_SIZE || + value > MAX_SERVARR_DOWNLOAD_QUEUE_SIZE + ) { + throw new Error( + `downloadQueueSize must be an integer between ${MIN_SERVARR_DOWNLOAD_QUEUE_SIZE} and ${MAX_SERVARR_DOWNLOAD_QUEUE_SIZE}.` + ); + } + + return value; +}; export const assertServarrInstanceCapacity = ( current: readonly unknown[] @@ -320,6 +338,18 @@ const parseDvrSettings = ( if ('error' in preventSearch) return preventSearch; const tagRequests = parseServiceBoolean(settings.tagRequests, 'tagRequests'); if ('error' in tagRequests) return tagRequests; + let downloadQueueSize: number; + try { + downloadQueueSize = validateServarrDownloadQueueSize( + settings.downloadQueueSize ?? + current?.downloadQueueSize ?? + DEFAULT_SERVARR_DOWNLOAD_QUEUE_SIZE + ); + } catch (e) { + return { + error: e instanceof Error ? e.message : 'downloadQueueSize is invalid.', + }; + } const port = parseOptionalNonNegativeInteger(settings.port, MAX_SERVICE_PORT); const activeProfileId = parseOptionalNonNegativeInteger( @@ -355,6 +385,7 @@ const parseDvrSettings = ( preventSearch: preventSearch.value, tagRequests: tagRequests.value, overrideRule: overrideRule.value, + downloadQueueSize, }, }; }; @@ -429,11 +460,20 @@ export const parseRadarrSettings = ( ); if ('error' in minimumAvailability) return minimumAvailability; + const syncExcludedTags = parseNumberArray( + settings.syncExcludedTags === undefined + ? (current?.syncExcludedTags ?? []) + : settings.syncExcludedTags, + 'syncExcludedTags' + ); + if ('error' in syncExcludedTags) return syncExcludedTags; + return { value: { ...parsed.value, ...requestButton.value, minimumAvailability: minimumAvailability.value, + syncExcludedTags: syncExcludedTags.value, }, }; }; @@ -479,6 +519,13 @@ export const parseSonarrSettings = ( const animeTags = parseNumberArray(settings.animeTags, 'animeTags'); if ('error' in animeTags) return animeTags; + const syncExcludedTags = parseNumberArray( + settings.syncExcludedTags === undefined + ? (current?.syncExcludedTags ?? []) + : settings.syncExcludedTags, + 'syncExcludedTags' + ); + if ('error' in syncExcludedTags) return syncExcludedTags; const activeAnimeProfileId = parseOptionalServiceId( settings.activeAnimeProfileId, 'activeAnimeProfileId' @@ -539,6 +586,7 @@ export const parseSonarrSettings = ( defaultMetadataLanguageId: defaultMetadataLanguageId.value, defaultSeasonType, animeTags: animeTags.value, + syncExcludedTags: syncExcludedTags.value, enableSeasonFolders: enableSeasonFolders.value, monitorNewItems, }, diff --git a/server/utils/tls.test.ts b/server/utils/tls.test.ts index ac1bc444cf..54a98d42cc 100644 --- a/server/utils/tls.test.ts +++ b/server/utils/tls.test.ts @@ -9,6 +9,7 @@ import http from 'node:http'; import os from 'node:os'; import path from 'node:path'; import { describe, it } from 'node:test'; +import { Agent, fetch as directFetch } from 'undici'; import { startLoopbackHttpServer } from './httpServer'; import { buildHttpsRedirectLocation, @@ -136,6 +137,7 @@ describe('TLS configuration parsing', () => { }); it('routes SSR API calls through loopback while public HTTP only upgrades', async () => { + const dispatcher = new Agent(); const originalInternalApiPort = process.env[INTERNAL_API_PORT_ENV]; const internalApi = await startLoopbackHttpServer((_request, response) => { response.writeHead(200, { 'Content-Type': 'application/json' }); @@ -154,14 +156,16 @@ describe('TLS configuration parsing', () => { assert.ok(publicAddress && typeof publicAddress !== 'string'); process.env[INTERNAL_API_PORT_ENV] = String(internalApi.port); - const internalResponse = await fetch( - `${getInternalApiBaseUrl()}/api/v1/movie/1` + const internalResponse = await directFetch( + `${getInternalApiBaseUrl()}/api/v1/movie/1`, + { dispatcher } ); assert.equal(internalResponse.status, 200); assert.deepEqual(await internalResponse.json(), { id: 1 }); - const publicResponse = await fetch( - `http://127.0.0.1:${publicAddress.port}/api/v1/movie/1` + const publicResponse = await directFetch( + `http://127.0.0.1:${publicAddress.port}/api/v1/movie/1`, + { dispatcher } ); assert.equal(publicResponse.status, 426); assert.equal( @@ -169,6 +173,7 @@ describe('TLS configuration parsing', () => { 'https://127.0.0.1:5056/api/v1/movie/1' ); } finally { + await dispatcher.close(); if (originalInternalApiPort === undefined) { delete process.env[INTERNAL_API_PORT_ENV]; } else { diff --git a/src/components/BookDetails/BookDetailsLayout.tsx b/src/components/BookDetails/BookDetailsLayout.tsx index 4c9da3785f..3e18355bb7 100644 --- a/src/components/BookDetails/BookDetailsLayout.tsx +++ b/src/components/BookDetails/BookDetailsLayout.tsx @@ -8,6 +8,8 @@ import DetailDisclosureButton from '@app/components/MediaDetails/DetailDisclosur import MediaQualitySelect from '@app/components/MediaDetails/MediaQualitySelect'; import PlaybackTrackList from '@app/components/MediaDetails/PlaybackTrackList'; import { subjectTagClassName } from '@app/components/MediaDetails/subjectTagStyle'; +import PersiusBookDetail from '@app/components/Persius/BookDetail'; +import usePersius from '@app/components/Persius/usePersius'; import useDetailDisclosurePins from '@app/hooks/useDetailDisclosurePins'; import usePlaybackCatalog from '@app/hooks/usePlaybackCatalog'; import { encodeApiPathSegment } from '@app/utils/apiPath'; @@ -71,6 +73,9 @@ interface BookDetailsLayoutProps { ) => ReactNode; playbackUnavailableReason?: (format: 'ebook' | 'audiobook') => string; additionalContent?: ReactNode; + canRequestNarration?: boolean; + onChanged?: () => void; + onFormatChange?: (format: 'ebook' | 'audiobook') => void; } const BookDetailsLayout = ({ @@ -84,8 +89,12 @@ const BookDetailsLayout = ({ playbackActions, playbackUnavailableReason, additionalContent, + canRequestNarration = false, + onChanged, + onFormatChange, }: BookDetailsLayoutProps) => { const intl = useIntl(); + const persius = usePersius(); const { pins, togglePinned } = useDetailDisclosurePins('book'); const [showDetails, setShowDetails] = useState(false); const [showCollection, setShowCollection] = useState(false); @@ -156,6 +165,261 @@ const BookDetailsLayout = ({ : messages.notAvailable ); + const bookDetailExtras = ( + <> + {' '} + + {!persius && ( +
+

+ {intl.formatMessage(messages.overview)} +

+
+ ( + + {children} + + ), + }} + > + {normalizeBookOverviewMarkdown( + data.description || + intl.formatMessage(messages.overviewUnavailable) + )} + +
+
+ )} +
+ {data.series && data.series.length > 0 && ( + setShowCollection((open) => !open)} + pinned={pins.collection} + onPinClick={() => void togglePinned('collection')} + /> + )} + setShowGenres((open) => !open)} + pinned={pins.subjectTags} + onPinClick={() => void togglePinned('subjectTags')} + /> + setShowDetails((open) => !open)} + pinned={pins.details} + onPinClick={() => void togglePinned('details')} + controls="book-additional-details" + /> + {catalogActions} +
+ {showCollection && data.series && data.series.length > 0 && ( +
+ {data.series.map((series) => ( + + ))} +
+ )} + {showGenres && ( +
+

+ {intl.formatMessage(messages.keywords)} +

+ {genres.length === 0 ? ( +

+ {intl.formatMessage(messages.noKeywords)} +

+ ) : ( +
+ {genres.map((genre, index) => ( + + {genre} + + ))} +
+ )} +
+ )} + {showDetails && ( +
+

+ {intl.formatMessage(messages.bookDetails)} +

+
+
+
+ {intl.formatMessage(messages.publisher)}: +
+
{data.publisher || unavailable}
+
+ {intl.formatMessage(messages.edition)}: +
+
{data.editionId || unavailable}
+
+
+
+ {intl.formatMessage(messages.openLibrary)}: +
+
+ + {data.id} + +
+
+
+
+ {intl.formatMessage(messages.isbnCandidates)}: +
+
+ {data.isbnCandidates?.length + ? data.isbnCandidates.slice(0, 4).map((candidate) => ( + + {candidate.isbn} + + )) + : unavailable} +
+
+
+
+ )} + + ); + + const bookPlaybackControls = ( +
+ + {playbackActions?.(effectivePlaybackItemIds, selectedPlaybackFormat)} + {playbackActions && ( + + )} + 0 + ? ratingData.source === 'bookshelf' + ? 'Bookshelf' + : 'Open Library' + : data.provider === 'bookshelf' + ? 'Bookshelf' + : 'Open Library' + } + href={ + ratingData?.workId && ratingData.source === 'openlibrary' + ? `https://openlibrary.org/works/${encodeURIComponent(ratingData.workId)}` + : data.provider !== 'bookshelf' + ? `https://openlibrary.org/works/${encodeURIComponent(data.id)}` + : undefined + } + /> +
+ ); + + if (persius) + return ( + { + setSelectedPlaybackFormat(format); + onFormatChange?.(format); + }} + actions={ + <> + {primaryActions} + {secondaryActions} + + } + playback={playbackActions?.( + effectivePlaybackItemIds, + selectedPlaybackFormat + )} + extra={ + <> + {bookPlaybackControls} + {bookDetailExtras} + {additionalContent} + {playbackCatalog && availablePlaybackItemIds.length > 0 && ( + + )} + + } + canRequest={canRequestNarration} + onChanged={onChanged} + /> + ); + return (
@@ -338,231 +602,14 @@ const BookDetailsLayout = ({ onSelectionChange={setSelectedPlaybackItemIds} /> )} -
- - {playbackActions?.( - effectivePlaybackItemIds, - selectedPlaybackFormat - )} - {playbackActions && ( - - )} - 0 - ? ratingData.source === 'bookshelf' - ? 'Bookshelf' - : 'Open Library' - : data.provider === 'bookshelf' - ? 'Bookshelf' - : 'Open Library' - } - href={ - ratingData?.workId && ratingData.source === 'openlibrary' - ? `https://openlibrary.org/works/${encodeURIComponent(ratingData.workId)}` - : data.provider !== 'bookshelf' - ? `https://openlibrary.org/works/${encodeURIComponent(data.id)}` - : undefined - } - /> -
+ {bookPlaybackControls}
{primaryActions} {secondaryActions}
- - -
-

- {intl.formatMessage(messages.overview)} -

-
- ( - - {children} - - ), - }} - > - {normalizeBookOverviewMarkdown( - data.description || - intl.formatMessage(messages.overviewUnavailable) - )} - -
-
- -
- {data.series && data.series.length > 0 && ( - setShowCollection((open) => !open)} - pinned={pins.collection} - onPinClick={() => void togglePinned('collection')} - /> - )} - setShowGenres((open) => !open)} - pinned={pins.subjectTags} - onPinClick={() => void togglePinned('subjectTags')} - /> - setShowDetails((open) => !open)} - pinned={pins.details} - onPinClick={() => void togglePinned('details')} - controls="book-additional-details" - /> - {catalogActions} -
- - {showCollection && data.series && data.series.length > 0 && ( -
- {data.series.map((series) => ( - - ))} -
- )} - - {showGenres && ( -
-

- {intl.formatMessage(messages.keywords)} -

- {genres.length === 0 ? ( -

- {intl.formatMessage(messages.noKeywords)} -

- ) : ( -
- {genres.map((genre, index) => ( - - {genre} - - ))} -
- )} -
- )} - - {showDetails && ( -
-

- {intl.formatMessage(messages.bookDetails)} -

-
-
-
- {intl.formatMessage(messages.publisher)}: -
-
- {data.publisher || unavailable} -
-
- {intl.formatMessage(messages.edition)}: -
-
- {data.editionId || unavailable} -
-
-
-
- {intl.formatMessage(messages.openLibrary)}: -
-
- - {data.id} - -
-
-
-
- {intl.formatMessage(messages.isbnCandidates)}: -
-
- {data.isbnCandidates?.length - ? data.isbnCandidates.slice(0, 4).map((candidate) => ( - - {candidate.isbn} - - )) - : unavailable} -
-
-
-
- )} + {bookDetailExtras} {additionalContent}
diff --git a/src/components/BookDetails/index.tsx b/src/components/BookDetails/index.tsx index 605320d9e3..ac12163390 100644 --- a/src/components/BookDetails/index.tsx +++ b/src/components/BookDetails/index.tsx @@ -888,6 +888,20 @@ const BookDetails = () => { playbackActions={playbackActions} playbackUnavailableReason={playbackUnavailableReason} additionalContent={additionalContent} + canRequestNarration={ + canRequest && + audiobookCategoryEnabled && + hasAudiobookService && + data.mediaInfo?.status !== MediaStatus.BLOCKLISTED + } + onChanged={() => void revalidate()} + onFormatChange={(format) => + void router.replace( + { pathname: router.pathname, query: { ...router.query, format } }, + undefined, + { shallow: true, scroll: false } + ) + } /> ); diff --git a/src/components/Common/Badge/index.tsx b/src/components/Common/Badge/index.tsx index 6c9527d3ce..9caac6dfba 100644 --- a/src/components/Common/Badge/index.tsx +++ b/src/components/Common/Badge/index.tsx @@ -114,6 +114,8 @@ const Badge = ( href={safeHref} target="_blank" rel="noopener noreferrer" + data-interface-role="status-badge" + data-badge-tone={badgeType} className={badgeStyle.join(' ')} aria-describedby={ariaDescribedBy} ref={ref as React.Ref} @@ -126,6 +128,8 @@ const Badge = ( } @@ -137,6 +141,8 @@ const Badge = ( return ( } diff --git a/src/components/Common/ConfirmButton/index.tsx b/src/components/Common/ConfirmButton/index.tsx index 7b578e04f8..c4c5a9d672 100644 --- a/src/components/Common/ConfirmButton/index.tsx +++ b/src/components/Common/ConfirmButton/index.tsx @@ -1,4 +1,4 @@ -import Button from '@app/components/Common/Button'; +import Button, { type ButtonType } from '@app/components/Common/Button'; import useClickOutside from '@app/hooks/useClickOutside'; import { forwardRef, useRef, useState, type ButtonHTMLAttributes } from 'react'; @@ -8,13 +8,22 @@ interface ConfirmButtonProps extends Omit< > { onClick: () => void; confirmText: React.ReactNode; + buttonType?: ButtonType; buttonSize?: 'standard' | 'default' | 'lg' | 'md' | 'sm'; children: React.ReactNode; } const ConfirmButton = forwardRef( ( - { onClick, children, confirmText, className, buttonSize, ...buttonProps }, + { + onClick, + children, + confirmText, + className, + buttonSize, + buttonType = 'danger', + ...buttonProps + }, parentRef ) => { const ref = useRef(null); @@ -24,7 +33,7 @@ const ConfirmButton = forwardRef( - - - - - - - + )} + + + + + + + + + + ); + return ( + <> + +
+
{persius ? intl.formatMessage(messages.books) : title}
+ {persius && showFormatTabs && ( + + )} + {!persius && bookFilters}
+ {persius && ( + <> + +
+
+

+ {intl.formatMessage( + activeFormat === 'audiobook' + ? persiusMessages.popularAudio + : persiusMessages.allEbooks + )} +

+
+
+ {bookFilters} + + setParam({ libraryView: value === 'all' ? undefined : value }) + } + /> + + + {intl.formatMessage(persiusMessages.loadedTitles, { + count: discover.titles.length, + })} + +
+
+ + )} {isRouteReady && query.trim().length >= 2 && ( { const intl = useIntl(); + const persius = usePersius(); const router = useRouter(); const preparedFilters = withDefaultTmdbRatingMinimumVotes({ ...initialFilters, @@ -51,9 +57,12 @@ const DiscoverMovies = ({ '/api/v1/discover/movies', preparedFilters, { - randomizeOrder: randomizeOrder ?? !preparedFilters.sortBy, + randomizeOrder: randomizeOrder ?? (!persius && !preparedFilters.sortBy), availableQuality: preparedFilters.availability, - hideAvailable: !preparedFilters.availability, + hideAvailable: !persius && !preparedFilters.availability, + availabilityView: persius + ? libraryView(router.query.libraryView) + : undefined, recoverSinglePageFailure: true, } ); @@ -97,6 +106,11 @@ const DiscoverMovies = ({
{title}
+ {persius && ( +

+ {intl.formatMessage(persiusMessages.moviesDescription)} +

+ )} {mediaFilters} {studioLogo && (
@@ -111,7 +125,18 @@ const DiscoverMovies = ({ />
)} - + {persius ? ( + + ) : ( + + )}
{ const intl = useIntl(); + const persius = usePersius(); const router = useRouter(); const watchlistPreview = process.env.NODE_ENV === 'development' && @@ -65,9 +71,12 @@ const DiscoverTv = ({ '/api/v1/discover/tv', preparedFilters, { - randomizeOrder: randomizeOrder ?? !preparedFilters.sortBy, + randomizeOrder: randomizeOrder ?? (!persius && !preparedFilters.sortBy), availableQuality: preparedFilters.availability, - hideAvailable: !preparedFilters.availability, + hideAvailable: !persius && !preparedFilters.availability, + availabilityView: persius + ? libraryView(router.query.libraryView) + : undefined, recoverSinglePageFailure: true, } ); @@ -102,6 +111,11 @@ const DiscoverTv = ({
{title}
+ {persius && ( +

+ {intl.formatMessage(persiusMessages.seriesDescription)} +

+ )} {mediaFilters} {networkLogo && (
@@ -114,7 +128,15 @@ const DiscoverTv = ({ />
)} - + {persius ? ( + + ) : ( + + )} {watchlistPreview && ( -
+
-
+
@@ -301,15 +315,27 @@ const Layout = ({ children }: LayoutProps) => {
{hasPermission(Permission.ADMIN) && } - {discoveryMediaType && currentSettings.swipeEnabled !== false && ( -
- -
- )} + {!persius && + discoveryMediaType && + currentSettings.swipeEnabled !== false && ( +
+ +
+ )} {children} + {persius && + discoveryMediaType && + currentSettings.swipeEnabled !== false && ( + + + + )}
diff --git a/src/components/MediaDetails/SeasonEpisodeTree.tsx b/src/components/MediaDetails/SeasonEpisodeTree.tsx index eb13fc4a4e..4c5861dcb3 100644 --- a/src/components/MediaDetails/SeasonEpisodeTree.tsx +++ b/src/components/MediaDetails/SeasonEpisodeTree.tsx @@ -1,4 +1,7 @@ import Button from '@app/components/Common/Button'; +import EpisodeFileAvailability, { + type EpisodeFileSource, +} from '@app/components/Common/EpisodeFileAvailability'; import MediaServerIcon, { getMediaServerName, } from '@app/components/Common/MediaServerIcon'; @@ -100,6 +103,7 @@ export interface TreeEpisode { episodeNumber: number; name: string; available: boolean; + availabilitySources?: EpisodeFileSource[]; // Request selection is independent of library availability. selectable?: boolean; watched?: boolean; @@ -347,40 +351,43 @@ const SeasonEpisodeTree = ({ ) } > - + + + + {intl.formatMessage( + episode.available + ? messages.availableInLibrary + : messages.unavailableInLibrary + )} + {Boolean(episode.availabilitySources?.length) && ( + + )} + + } > - + {intl.formatMessage(messages.releaseDate)} diff --git a/src/components/MediaDetails/seriesTreeData.ts b/src/components/MediaDetails/seriesTreeData.ts index 233277b43a..6d751be7cc 100644 --- a/src/components/MediaDetails/seriesTreeData.ts +++ b/src/components/MediaDetails/seriesTreeData.ts @@ -45,6 +45,16 @@ export const buildSeriesTreeData = ( name: episode.name || untitled, releaseDate: episode.airDate || undefined, available: Boolean(playableItem), + availabilitySources: + episode.availabilitySources ?? + (episode.sonarrAvailability + ? [ + { + sourceType: 'sonarr' as const, + ...episode.sonarrAvailability, + }, + ] + : []), watched: watchedSeason?.episodes.find( (candidate) => candidate.episodeNumber === episode.episodeNumber )?.watched, diff --git a/src/components/MetadataSelector/index.tsx b/src/components/MetadataSelector/index.tsx index d156a921ba..63f388a0dd 100644 --- a/src/components/MetadataSelector/index.tsx +++ b/src/components/MetadataSelector/index.tsx @@ -2,10 +2,7 @@ import defineMessages from '@app/utils/defineMessages'; import { useIntl } from 'react-intl'; import Select, { type StylesConfig } from 'react-select'; -enum MetadataProviderType { - TMDB = 'tmdb', - TVDB = 'tvdb', -} +import { MetadataProviderType } from '@server/constants/metadata'; type MetadataProviderOptionType = { testId?: string; diff --git a/src/components/MovieDetails/MovieDetailsLayout.tsx b/src/components/MovieDetails/MovieDetailsLayout.tsx index 9f89caeef6..97f5ed9318 100644 --- a/src/components/MovieDetails/MovieDetailsLayout.tsx +++ b/src/components/MovieDetails/MovieDetailsLayout.tsx @@ -10,6 +10,8 @@ import SubjectTagVisibilityPanel from '@app/components/MediaDetails/SubjectTagVi import VideoRatings from '@app/components/MediaDetails/VideoRatings'; import { subjectTagClassName } from '@app/components/MediaDetails/subjectTagStyle'; import MediaSlider from '@app/components/MediaSlider'; +import PersiusMovieDetail from '@app/components/Persius/MovieDetail'; +import usePersius from '@app/components/Persius/usePersius'; import useDetailDisclosurePins from '@app/hooks/useDetailDisclosurePins'; import useSettings from '@app/hooks/useSettings'; import useWatchStatus from '@app/hooks/useWatchStatus'; @@ -72,6 +74,7 @@ interface MovieDetailsLayoutProps { }[]; show4kAvailability: boolean; primaryActions: ReactNode; + trailerAction?: ReactNode; secondaryActions: ReactNode; indexerSearchAction: ReactNode; indexerCompanionActions: ReactNode; @@ -92,6 +95,7 @@ const MovieDetailsLayout = ({ filteredReleases, show4kAvailability, primaryActions, + trailerAction, secondaryActions, indexerSearchAction, indexerCompanionActions, @@ -100,6 +104,7 @@ const MovieDetailsLayout = ({ playbackActions, }: MovieDetailsLayoutProps) => { const intl = useIntl(); + const persius = usePersius(); const settings = useSettings(); const { data: watchedStatus } = useWatchStatus( 'movie', @@ -208,6 +213,285 @@ const MovieDetailsLayout = ({ : undefined, ].filter(Boolean); + const movieDetailExtras = ( + <> + {' '} +
+ {data.collection && ( + setShowCollection((open) => !open)} + pinned={pins.collection} + onPinClick={() => void togglePinned('collection')} + /> + )} + setShowCast((open) => !open)} + pinned={pins.cast} + onPinClick={() => void togglePinned('cast')} + /> + setShowCrew((open) => !open)} + pinned={pins.crew} + onPinClick={() => void togglePinned('crew')} + /> + setShowTags((open) => !open)} + pinned={pins.subjectTags} + onPinClick={() => void togglePinned('subjectTags')} + /> + setShowDetails((open) => !open)} + pinned={pins.details} + onPinClick={() => void togglePinned('details')} + controls="movie-additional-details" + /> +
+ {data.collection && showCollection && ( + + )} + {showCast && ( + + )} + {showCrew && ( + + )} + {showTags && ( +
+ 0} + title={intl.formatMessage(messages.subjectTags)} + > + {data.keywords.length === 0 ? ( +

+ {intl.formatMessage(messages.noTags)} +

+ ) : ( +
+ {data.keywords.map((keyword, index) => ( + + {keyword.name} + + ))} +
+ )} +
+
+ )} + {showDetails && ( +
+

+ {intl.formatMessage(messages.movieDetails)} +

+
+
+
+ {intl.formatMessage(messages.status)}: +
+
{data.status || unavailable}
+
+ {intl.formatMessage(messages.releaseDates)}: +
+
+ {displayedReleases.length > 0 + ? displayedReleases.map((release, index) => ( + + {releaseTypeLabel(release.type)} ·{' '} + {intl.formatDate(release.release_date, { + year: 'numeric', + month: 'short', + day: 'numeric', + timeZone: 'UTC', + })} + + )) + : unavailable} +
+
+ +
+
+ {intl.formatMessage(messages.revenue)}: +
+
{formatCurrency(data.revenue)}
+
+ {intl.formatMessage(messages.budget)}: +
+
{formatCurrency(data.budget)}
+
+ {intl.formatMessage(messages.language)}: +
+
+ + {originalLanguage} + +
+
+ {intl.formatMessage(messages.country)}: +
+
+ {data.productionCountries.length > 0 + ? data.productionCountries.map((country, index) => ( + + {index > 0 && ', '} + + {intl.formatDisplayName(country.iso_3166_1, { + type: 'region', + fallback: 'none', + }) ?? country.name} + + + )) + : unavailable} +
+
+ +
+
+ {intl.formatMessage(messages.studios)}: +
+
+ {data.productionCompanies.length > 0 + ? data.productionCompanies.slice(0, 4).map((studio) => + studio.id > 0 ? ( + + {studio.name} + + ) : ( + + {studio.name} + + ) + ) + : unavailable} +
+
+
+
+ )} + + ); + + const relatedTitles = ( + <> + {' '} + + + + ); + + if (persius) + return ( + <> + + } + playbackActions={ + availableFormats.length + ? playbackActions?.(selectedQuality === '4k') + : undefined + } + tools={ + <> + {movieDetailExtras} + {primaryActions} + {secondaryActions} + {reportIssueAction} + {indexerSearchAction} + {indexerCompanionActions} + + setSelectedQuality(quality === '4k' ? '4k' : 'hd') + } + label={intl.formatMessage(messages.quality)} + /> + + } + /> + {relatedTitles} + + ); + return (
@@ -278,212 +562,7 @@ const MovieDetailsLayout = ({
)} -
- {data.collection && ( - setShowCollection((open) => !open)} - pinned={pins.collection} - onPinClick={() => void togglePinned('collection')} - /> - )} - setShowCast((open) => !open)} - pinned={pins.cast} - onPinClick={() => void togglePinned('cast')} - /> - setShowCrew((open) => !open)} - pinned={pins.crew} - onPinClick={() => void togglePinned('crew')} - /> - setShowTags((open) => !open)} - pinned={pins.subjectTags} - onPinClick={() => void togglePinned('subjectTags')} - /> - setShowDetails((open) => !open)} - pinned={pins.details} - onPinClick={() => void togglePinned('details')} - controls="movie-additional-details" - /> -
- {data.collection && showCollection && ( - - )} - {showCast && ( - - )} - {showCrew && ( - - )} - {showTags && ( -
- 0} - title={intl.formatMessage(messages.subjectTags)} - > - {data.keywords.length === 0 ? ( -

- {intl.formatMessage(messages.noTags)} -

- ) : ( -
- {data.keywords.map((keyword, index) => ( - - {keyword.name} - - ))} -
- )} -
-
- )} - {showDetails && ( -
-

- {intl.formatMessage(messages.movieDetails)} -

-
-
-
- {intl.formatMessage(messages.status)}: -
-
{data.status || unavailable}
-
- {intl.formatMessage(messages.releaseDates)}: -
-
- {displayedReleases.length > 0 - ? displayedReleases.map((release, index) => ( - - {releaseTypeLabel(release.type)} ·{' '} - {intl.formatDate(release.release_date, { - year: 'numeric', - month: 'short', - day: 'numeric', - timeZone: 'UTC', - })} - - )) - : unavailable} -
-
- -
-
- {intl.formatMessage(messages.revenue)}: -
-
- {formatCurrency(data.revenue)} -
-
- {intl.formatMessage(messages.budget)}: -
-
- {formatCurrency(data.budget)} -
-
- {intl.formatMessage(messages.language)}: -
-
- - {originalLanguage} - -
-
- {intl.formatMessage(messages.country)}: -
-
- {data.productionCountries.length > 0 - ? data.productionCountries.map((country, index) => ( - - {index > 0 && ', '} - - {intl.formatDisplayName(country.iso_3166_1, { - type: 'region', - fallback: 'none', - }) ?? country.name} - - - )) - : unavailable} -
-
- -
-
- {intl.formatMessage(messages.studios)}: -
-
- {data.productionCompanies.length > 0 - ? data.productionCompanies - .slice(0, 4) - .map((studio) => - studio.id > 0 ? ( - - {studio.name} - - ) : ( - - {studio.name} - - ) - ) - : unavailable} -
-
-
-
- )} + {movieDetailExtras}