From 4df616b1f7e1a73f6af6c9362a43798757028379 Mon Sep 17 00:00:00 2001 From: snapetech Date: Thu, 1 Oct 2026 18:16:21 -0600 Subject: [PATCH 01/58] feat: add Docker network setup discovery --- README.md | 4 + bin/check-current-batch-contract-lib.js | 2 +- bin/run-tooling-tests.mjs | 1 + .../e2e/settings/prowlarr-responsive.cy.ts | 81 ++ docs/README.md | 1 + docs/using-seerr/setup-assistant.md | 188 ++++ package.json | 1 + ...0-01-add-cross-platform-setup-assistant.md | 8 + scripts/setup-assistant.mjs | 883 ++++++++++++++++++ scripts/setup-assistant.test.mjs | 338 +++++++ .../Settings/BackIssueModal/index.tsx | 6 +- .../Settings/KapowarrModal/index.tsx | 6 +- .../Settings/LazyLibrarianModal/index.tsx | 6 +- src/components/Settings/LidarrModal/index.tsx | 6 +- src/components/Settings/MylarModal/index.tsx | 6 +- src/components/Settings/RadarrModal/index.tsx | 6 +- .../Settings/ReadarrModal/index.tsx | 13 +- src/components/Settings/SettingsLayout.tsx | 2 +- src/components/Settings/SettingsProwlarr.tsx | 15 +- src/components/Settings/SettingsServices.tsx | 24 + .../Settings/SettingsSoftwareAcquisition.tsx | 29 +- .../Settings/SetupConnectionsImport.tsx | 83 ++ src/components/Settings/SonarrModal/index.tsx | 6 +- src/context/SetupConnectionsContext.tsx | 74 ++ src/i18n/locale/en.json | 8 + src/pages/_app.tsx | 5 +- src/utils/setupConnections.test.ts | 76 ++ src/utils/setupConnections.ts | 101 ++ 28 files changed, 1955 insertions(+), 24 deletions(-) create mode 100644 docs/using-seerr/setup-assistant.md create mode 100644 release-notes/2026-10-01-add-cross-platform-setup-assistant.md create mode 100644 scripts/setup-assistant.mjs create mode 100644 scripts/setup-assistant.test.mjs create mode 100644 src/components/Settings/SetupConnectionsImport.tsx create mode 100644 src/context/SetupConnectionsContext.tsx create mode 100644 src/utils/setupConnections.test.ts create mode 100644 src/utils/setupConnections.ts diff --git a/README.md b/README.md index f31e19c54f..f2cf2d7ec1 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ This fork is maintained by snapetech. Upstream Seerr remains the base project fo - [Configure comics](./docs/using-seerr/comics-backend.md) - [Configure magazines](./docs/using-seerr/magazines-backend.md) - [Companion services and SeerrNG NG forks](./docs/using-seerr/companion-services.md) + - [Cross-platform setup assistant](./docs/using-seerr/setup-assistant.md) - [Indexer searches by media category](./docs/using-seerr/indexer-searches.md) - [Configure services](./docs/using-seerr/settings/services.md) - [Screenshots](#screenshots) @@ -182,6 +183,9 @@ services: restart: unless-stopped ``` +To create a guided starter stack for SeerrNG and common media apps on Windows, +macOS, or Linux, use the [cross-platform setup assistant](./docs/using-seerr/setup-assistant.md). + ### Unraid Install SeerrNG from Community Applications with the [Unraid template](https://raw.githubusercontent.com/snapetech/seerrng/main/packaging/unraid/seerrng.xml). It uses the stable `latest` image, maps HTTP port `5055` and optional HTTPS port `5056`, and persists `/app/config`. The image runs as UID/GID `1000:1000`, so make the selected appdata directory writable by that user before the first start. Optional BookshelfNG, ChaptarrNG, ROMarrNG, and QuestarrNG templates live in each fork's own repository; the [Unraid guide](docs/getting-started/third-parties/unraid.mdx) links to their templates and to the existing Community Apps listings for LazyLibrarian, Mylar3, and Kapowarr. BackIssue has its own Docker image and Unraid template; see its [getting-started guide](https://backissue.app/getting-started). diff --git a/bin/check-current-batch-contract-lib.js b/bin/check-current-batch-contract-lib.js index 8a69fea200..8f63879907 100644 --- a/bin/check-current-batch-contract-lib.js +++ b/bin/check-current-batch-contract-lib.js @@ -3590,7 +3590,7 @@ const validateCurrentBatchContract = (files) => { '
{intl.formatMessage(globalMessages.settings)}
', '', 'className="discover-filter-control settings-page-search"', - '
', + '
', 'className="settings-page-actions"', 'buttonType="danger"', 'buttonType="success"', diff --git a/bin/run-tooling-tests.mjs b/bin/run-tooling-tests.mjs index 33c09acf57..0881e87e6b 100644 --- a/bin/run-tooling-tests.mjs +++ b/bin/run-tooling-tests.mjs @@ -13,6 +13,7 @@ const portableTests = [ 'scripts/chart-workflow.test.mjs', 'scripts/check-container-security.test.mjs', 'scripts/bookshelf-media-move.test.mjs', + 'scripts/setup-assistant.test.mjs', 'scripts/backissue-service.test.mjs', 'scripts/check-helm-security.test.mjs', 'scripts/check-workflow-boundaries.test.mjs', diff --git a/cypress/e2e/settings/prowlarr-responsive.cy.ts b/cypress/e2e/settings/prowlarr-responsive.cy.ts index 4afec8e373..edad393be3 100644 --- a/cypress/e2e/settings/prowlarr-responsive.cy.ts +++ b/cypress/e2e/settings/prowlarr-responsive.cy.ts @@ -132,4 +132,85 @@ describe('Prowlarr settings on a short mobile screen', () => { .click(); cy.wait('@saveProwlarr').its('response.statusCode').should('eq', 200); }); + + it('shows setup assistance without horizontal overflow on a narrow screen', () => { + cy.visit('/settings/services'); + + cy.contains('section.app-card-sub', 'Connect your apps') + .should('be.visible') + .and( + 'contain', + 'Generate a Docker Compose starter or discover apps on a Docker network.' + ); + cy.contains('a', 'Open the setup guide') + .should('be.visible') + .should( + 'have.attr', + 'href', + 'https://github.com/snapetech/seerrng/blob/main/docs/using-seerr/setup-assistant.md' + ); + cy.document().then((document) => { + expect(document.documentElement.scrollWidth).to.be.at.most( + document.documentElement.clientWidth + 1 + ); + }); + cy.screenshot('setup-assistant-mobile', { capture: 'viewport' }); + }); + + it('shows setup assistance at desktop width', () => { + cy.viewport(1280, 720); + cy.visit('/settings/services'); + + cy.contains('section.app-card-sub', 'Connect your apps').should( + 'be.visible' + ); + cy.contains('section.app-card-sub', 'Connect your apps').should(($card) => { + const bounds = $card[0].getBoundingClientRect(); + expect(bounds.right).to.be.at.most( + $card[0].ownerDocument.documentElement.clientWidth + 1 + ); + const description = $card.find('p')[0]; + expect(description.scrollWidth).to.be.at.most( + description.clientWidth + 1 + ); + }); + cy.document().then((document) => { + expect(document.documentElement.scrollWidth).to.be.at.most( + document.documentElement.clientWidth + 1 + ); + }); + cy.screenshot('setup-assistant-desktop', { capture: 'viewport' }); + }); + + it('imports a discovered address into the matching add form without importing credentials', () => { + cy.visit('/settings/services'); + + const report = { + network: 'seerrng-shared', + connections: [ + { + id: 'radarr', + title: 'Radarr', + hostname: 'radarr', + port: 7878, + state: 'running', + apiKey: 'must-not-be-imported', + }, + ], + }; + cy.get('input[aria-label="Import detected connections"]').selectFile( + { + contents: Cypress.Buffer.from(JSON.stringify(report)), + fileName: 'seerrng-connections.json', + mimeType: 'application/json', + }, + { force: true } + ); + + cy.contains('Loaded suggestions for 1 app').should('be.visible'); + cy.contains('button', 'Add Radarr Server').scrollIntoView().click(); + cy.get('input[name="hostname"]').should('have.value', 'radarr'); + cy.get('input[name="port"]').should('have.value', '7878'); + cy.get('input[name="apiKey"]').should('have.value', ''); + }); }); diff --git a/docs/README.md b/docs/README.md index 5026ad3bfa..c7af2d641a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -18,6 +18,7 @@ connects to. - [Kubernetes installation](/getting-started/kubernetes/) - [Unraid installation](/getting-started/third-parties/unraid) - [YunoHost installation](/getting-started/third-parties/yunohost) +- [Cross-platform setup assistant](/using-seerr/setup-assistant) - [Troubleshooting](/troubleshooting/) ## Use SeerrNG diff --git a/docs/using-seerr/setup-assistant.md b/docs/using-seerr/setup-assistant.md new file mode 100644 index 0000000000..8d192138ca --- /dev/null +++ b/docs/using-seerr/setup-assistant.md @@ -0,0 +1,188 @@ +--- +title: Cross-platform setup assistant +description: Create a starter Docker Compose stack and connect its apps to SeerrNG. +sidebar_position: 5 +--- + +# Cross-platform setup assistant + +The setup assistant creates a Docker Compose stack and a per-stack guide for +the media services you choose. It runs on Windows, macOS, and Linux with Node.js +24.15.0 or newer in the 24.x line and Docker Compose v2. Docker Desktop is +suitable on Windows and macOS; Docker Engine with the Compose plugin is +suitable on Linux. The assistant does not install or configure Docker itself. + +## Run the assistant + +You can download the standalone assistant without cloning the full SeerrNG +repository. It uses Node.js built-ins and does not need an npm install. + +On Windows, open PowerShell and run: + +```powershell +Invoke-WebRequest https://raw.githubusercontent.com/snapetech/seerrng/main/scripts/setup-assistant.mjs -OutFile setup-assistant.mjs +node .\setup-assistant.mjs +``` + +On macOS or Linux, run: + +```sh +curl --fail --location https://raw.githubusercontent.com/snapetech/seerrng/main/scripts/setup-assistant.mjs --output setup-assistant.mjs +node ./setup-assistant.mjs +``` + +You can also run the script directly from a SeerrNG source checkout: + +```text +node scripts/setup-assistant.mjs +``` + +Choose a starter profile, confirm the output directory, and optionally let the +assistant start the stack after it writes the files. It writes files only; it +does not install apps, configure API keys, or start containers unless you +explicitly choose that option. To select a profile and output location +directly: + +```text +node scripts/setup-assistant.mjs --profile movies-tv --output ./my-media-stack +``` + +For unattended file generation, add `--yes`; the assistant will write the +files but will not start containers. Add `--start` to explicitly start the +generated stack with Docker Compose. + +If SeerrNG is already installed, generate only the companion apps on a shared +Docker network: + +```text +node scripts/setup-assistant.mjs --profile movies-tv --apps -seerrng --network seerrng-shared --output ./media-apps +``` + +The generated guide includes the commands to create the shared network and +attach your existing SeerrNG container to it. The assistant does not scan +Docker networks or containers to guess which SeerrNG instance you mean. This +mode requires SeerrNG to run in a Docker container on the same Docker host; +native or remote SeerrNG installs need a separately reachable app address. + +Use `--detect --output ./my-media-stack` to report which containers Docker +Compose currently sees in that generated stack. To discover supported apps +already attached to a particular Docker network, name that network explicitly: + +```text +node scripts/setup-assistant.mjs --discover --network seerrng-shared +``` + +Add `--output ./connection-report` to write `CONNECTIONS.md` and +`seerrng-connections.json` with the detected app names, Compose hostnames, +container ports, and states. The assistant inspects only the named network and +refuses networks with more than 64 attached containers. It recognizes known +images and Compose service labels; custom images without a matching service +label may not be identified. The report contains no API keys or container +environment values. Enter each app's API key in SeerrNG, then use the existing +**Test** action to verify the connection and load its options before saving. + +In SeerrNG, open **Settings → Services** and choose **Import detected +connections** to load `seerrng-connections.json`. Detected hostnames and ports +prefill matching add forms, including Prowlarr and software acquisition +settings. Saved service addresses are left unchanged. API keys remain blank; +enter each key in the corresponding app and use **Test** so SeerrNG validates +the API and loads profiles, root folders, or provider capabilities. Imported +suggestions stay in memory until you clear them or reload SeerrNG. + +After choosing a profile, enter app IDs to add or prefix an ID with `-` to +remove it. For example, add `lidarr` to a Movies and TV profile or enter +`-qbittorrent` to omit its download client. Available app IDs are `seerrng`, +`radarr`, `sonarr`, `lidarr`, `bookshelf`, +`chaptarrng`, `prowlarr`, `qbittorrent`, `lazylibrarian`, `mylar3`, `kapowarr`, +`backissue`, `romarrng`, and `questarrng`. + +Use `--list-profiles` to see the available profiles. Each generated folder +contains `compose.yaml` and `SETUP.md`. Review both before starting the stack. +The output files are never overwritten; choose another output directory when +you want to regenerate them. + +## Starter profiles + +| Profile | Included apps | +| --- | --- | +| `movies-tv` | SeerrNG, Radarr, Sonarr, Prowlarr, qBittorrent | +| `books` | SeerrNG, BookshelfNG, Prowlarr, qBittorrent | +| `books-chaptarrng` | SeerrNG, ChaptarrNG, Prowlarr, qBittorrent | +| `music` | SeerrNG, Lidarr, Prowlarr, qBittorrent | +| `comics` | SeerrNG, Mylar3 | +| `magazines` | SeerrNG, LazyLibrarian, Prowlarr, qBittorrent | +| `software` | SeerrNG, QuestarrNG, ROMarrNG, qBittorrent | +| `media-library` | SeerrNG, Radarr, Sonarr, Lidarr, BookshelfNG, Prowlarr, qBittorrent | +| `all-media` | SeerrNG, Radarr, Sonarr, Lidarr, BookshelfNG, Mylar3, LazyLibrarian, QuestarrNG, ROMarrNG, Prowlarr, qBittorrent | + +These profiles are examples, not required SeerrNG dependencies. Choose a +smaller profile when you want fewer containers. BookshelfNG and ChaptarrNG are +alternatives for book automation; Mylar3, Kapowarr, and BackIssue are +alternatives for comics. The `all-media` profile chooses BookshelfNG and +Mylar3; add or remove providers with `--apps` for a different choice. For +example, replace BookshelfNG with ChaptarrNG using +`--profile books --apps -bookshelf,chaptarrng`, or add BackIssue as an +alternative with `--profile comics --apps -mylar3,backissue`. Connect only the +comic provider you want to use as the default destination. BackIssue currently +publishes a linux/amd64 image; on ARM64 hosts, choose Mylar3 or Kapowarr unless +you have enabled and verified x86 emulation. + +The software profile includes both NG services because QuestarrNG handles PC +game requests and ROMarrNG handles emulation requests. Assign each supported +ROMarrNG system to Retro or Modern in SeerrNG's Software Acquisition settings. +If you need separate destinations, such as independent HD and 4K libraries, +add separately named services and give them distinct host ports and +configuration volumes in your Compose file. + +## Link the apps + +After starting a new stack, open SeerrNG at `http://localhost:5055` and +complete its first run. After discovering an existing network, open the URL for +your existing SeerrNG instance. In **Settings → Services**, add each supported media service and copy its +API key from that app. Configure Prowlarr under **Settings → Prowlarr** and +QuestarrNG or ROMarrNG under **Settings → Services → Software Acquisition**. +Select **Test** before saving; SeerrNG will validate the connection and load +the available profiles and root folders. Enter the Docker +Compose service name as the hostname (for example, `radarr`) when SeerrNG and +that app are in the generated stack. Use each app's listed container port, not +the host's published port. For BookshelfNG or ChaptarrNG, add two connections +to the same hostname and port: one with Book format and one with Audiobook +format. For emulation requests, assign supported ROMarrNG systems to **Retro** +or **Modern**. + +Credentials are entered in SeerrNG's existing forms and are not generated, +copied between apps, or placed in the generated files. A successful connection +test does not save the service; review its options and save it explicitly. + +## Storage and network behavior + +The generated stack uses Docker named volumes for persistent app configuration, +media, and downloads when the selected apps need them. Media container paths +vary by app; the generated `SETUP.md` lists each mount so you can set matching +root folders. Apps in one generated stack share the `downloads` volume. Docker +manages where these volumes live on each operating system; back them up before +migrating the stack. + +When qBittorrent is included, its first-start temporary `admin` password is +printed in its container log. Sign in at `http://localhost:8080` and set a +permanent password in the Web UI settings before connecting download clients. + +Web ports bind to `127.0.0.1` so the interfaces are local to the Docker host by +default. When qBittorrent is included, it also publishes peer traffic on TCP +and UDP port `6881` on the Docker host for torrent transfers. To reach SeerrNG or an app's web +interface from another device, edit that service's host-side bind address after +reviewing your network and authentication setup. The app-to-app connections use +Compose DNS and remain inside the Compose network. + +If one of the default host ports is already in use, set the corresponding +`*_HOST_PORT` variable in a `.env` file in the generated folder. The app-to-app +addresses and container ports in the guide do not change. For qBittorrent peer +traffic, set `QBITTORRENT_PEER_PORT` to change its host port. + +The assistant does not configure indexers, download-client categories, media +root folders, quality profiles, TLS, or reverse proxies. Configure those in +the relevant app before relying on requests. ChaptarrNG is an alternative to +BookshelfNG; select one provider per format to avoid duplicate acquisitions. +After saving ROMarrNG, assign supported systems to **Retro** or **Modern** in +SeerrNG. Additional dashboards, monitoring, and update controllers remain +outside this acquisition-focused catalog. diff --git a/package.json b/package.json index 248ed2cda2..7fcf2bcb96 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "release-notes:preview": "node scripts/preview-release-notes.mjs", "backissue:service": "node scripts/backissue-service.mjs", "bookshelf:move": "node scripts/bookshelf-media-move.mjs", + "setup:assistant": "node scripts/setup-assistant.mjs", "attribution:check": "node bin/run-bash.mjs scripts/check-attribution.sh", "lintfix": "eslint \"./server/**/*.{ts,tsx}\" \"./src/**/*.{ts,tsx}\" --fix", "test": "vitest run", diff --git a/release-notes/2026-10-01-add-cross-platform-setup-assistant.md b/release-notes/2026-10-01-add-cross-platform-setup-assistant.md new file mode 100644 index 0000000000..f1c85ca598 --- /dev/null +++ b/release-notes/2026-10-01-add-cross-platform-setup-assistant.md @@ -0,0 +1,8 @@ +--- +category: added +audience: operators +area: setup-assistance +action: none +breaking: false +--- +Operators can generate a cross-platform Docker Compose starter, discover supported apps on a selected Docker network, and import connection suggestions to prefill hostnames and ports. API keys stay in each app and are verified through SeerrNG before saving. diff --git a/scripts/setup-assistant.mjs b/scripts/setup-assistant.mjs new file mode 100644 index 0000000000..3d62396817 --- /dev/null +++ b/scripts/setup-assistant.mjs @@ -0,0 +1,883 @@ +#!/usr/bin/env node + +import { spawnSync } from 'node:child_process'; +import { access, mkdir, unlink, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { stderr, stdin, stdout } from 'node:process'; +import readline from 'node:readline/promises'; +import { pathToFileURL } from 'node:url'; + +export const apps = { + seerrng: { + title: 'SeerrNG', + image: 'ghcr.io/snapetech/seerrng:latest', + port: '5055', + volumes: ['seerrng-config:/app/config'], + integrations: [], + }, + radarr: { + title: 'Radarr', + image: 'lscr.io/linuxserver/radarr:latest', + port: '7878', + volumes: [ + 'radarr-config:/config', + 'media-data:/data', + 'downloads:/downloads', + ], + integrations: ['Radarr: radarr:7878'], + }, + sonarr: { + title: 'Sonarr', + image: 'lscr.io/linuxserver/sonarr:latest', + port: '8989', + volumes: [ + 'sonarr-config:/config', + 'media-data:/data', + 'downloads:/downloads', + ], + integrations: ['Sonarr: sonarr:8989'], + }, + lidarr: { + title: 'Lidarr', + image: 'lscr.io/linuxserver/lidarr:latest', + port: '8686', + volumes: [ + 'lidarr-config:/config', + 'media-data:/data', + 'downloads:/downloads', + ], + integrations: ['Lidarr: lidarr:8686'], + }, + bookshelf: { + title: 'BookshelfNG', + image: 'ghcr.io/snapetech/bookshelfng:hardcover', + port: '8787', + volumes: [ + 'bookshelf-config:/config', + 'media-data:/data', + 'downloads:/downloads', + ], + integrations: [ + 'Books (BookshelfNG): bookshelf:8787 (Book format)', + 'Audiobooks (BookshelfNG): bookshelf:8787 (Audiobook format)', + ], + }, + chaptarrng: { + title: 'ChaptarrNG', + image: 'ghcr.io/snapetech/chaptarrng:0.9.937', + port: '8789', + volumes: [ + 'chaptarrng-config:/config', + 'ebook-data:/ebooks', + 'audiobook-data:/audiobooks', + 'downloads:/downloads', + ], + integrations: [ + 'Books (ChaptarrNG): chaptarrng:8789 (Book format)', + 'Audiobooks (ChaptarrNG): chaptarrng:8789 (Audiobook format)', + ], + }, + prowlarr: { + title: 'Prowlarr', + image: 'lscr.io/linuxserver/prowlarr:latest', + port: '9696', + volumes: ['prowlarr-config:/config'], + integrations: ['Prowlarr: prowlarr:9696'], + }, + qbittorrent: { + title: 'qBittorrent', + image: 'lscr.io/linuxserver/qbittorrent:latest', + port: '8080', + volumes: ['qbittorrent-config:/config', 'downloads:/downloads'], + integrations: [], + }, + lazylibrarian: { + title: 'LazyLibrarian', + image: 'lscr.io/linuxserver/lazylibrarian:latest', + port: '5299', + volumes: [ + 'lazylibrarian-config:/config', + 'media-data:/books', + 'downloads:/downloads', + ], + integrations: ['Magazines (LazyLibrarian): lazylibrarian:5299'], + }, + mylar3: { + title: 'Mylar3', + image: 'lscr.io/linuxserver/mylar3:latest', + port: '8090', + volumes: [ + 'mylar3-config:/config', + 'media-data:/comics', + 'downloads:/downloads', + ], + integrations: ['Comics (Mylar3): mylar3:8090'], + }, + kapowarr: { + title: 'Kapowarr', + image: 'mrcas/kapowarr:latest', + port: '5656', + volumes: [ + 'kapowarr-config:/app/db', + 'media-data:/comics', + 'downloads:/app/temp_downloads', + ], + integrations: ['Comics (Kapowarr): kapowarr:5656'], + }, + backissue: { + title: 'BackIssue', + image: 'ghcr.io/backissueapp/backissue:latest', + port: '8787', + hostPort: '8788', + architectures: ['amd64'], + volumes: [ + 'backissue-config:/data', + 'media-data:/comics', + 'downloads:/downloads', + ], + integrations: ['Comics (BackIssue): backissue:8787'], + }, + romarrng: { + title: 'ROMarrNG', + image: 'ghcr.io/snapetech/romarrng:latest', + port: '6868', + volumes: [ + 'romarrng-config:/config', + 'media-data:/roms', + 'downloads:/downloads', + ], + integrations: ['Emulation ROMs (ROMarrNG): romarrng:6868'], + }, + questarrng: { + title: 'QuestarrNG', + image: 'ghcr.io/snapetech/questarrng:latest', + port: '5000', + volumes: [ + 'questarrng-config:/app/data', + 'media-data:/data', + 'downloads:/downloads', + ], + integrations: ['PC games (QuestarrNG): questarrng:5000'], + }, +}; + +export const profiles = { + 'movies-tv': { + title: 'Movies and TV', + apps: ['seerrng', 'radarr', 'sonarr', 'prowlarr', 'qbittorrent'], + }, + books: { + title: 'Books and audiobooks', + apps: ['seerrng', 'bookshelf', 'prowlarr', 'qbittorrent'], + }, + 'books-chaptarrng': { + title: 'Books and audiobooks with ChaptarrNG', + apps: ['seerrng', 'chaptarrng', 'prowlarr', 'qbittorrent'], + }, + music: { + title: 'Music', + apps: ['seerrng', 'lidarr', 'prowlarr', 'qbittorrent'], + }, + comics: { + title: 'Comics with Mylar3', + apps: ['seerrng', 'mylar3'], + }, + magazines: { + title: 'Magazines', + apps: ['seerrng', 'lazylibrarian', 'prowlarr', 'qbittorrent'], + }, + software: { + title: 'PC games and emulation ROMs', + apps: ['seerrng', 'questarrng', 'romarrng', 'qbittorrent'], + }, + 'media-library': { + title: 'Starter media library', + apps: [ + 'seerrng', + 'radarr', + 'sonarr', + 'lidarr', + 'bookshelf', + 'prowlarr', + 'qbittorrent', + ], + }, + 'all-media': { + title: 'All media formats', + apps: [ + 'seerrng', + 'radarr', + 'sonarr', + 'lidarr', + 'bookshelf', + 'mylar3', + 'lazylibrarian', + 'questarrng', + 'romarrng', + 'prowlarr', + 'qbittorrent', + ], + }, +}; + +const quote = (value) => JSON.stringify(value); + +export const renderCompose = (selectedApps, sharedNetwork) => { + for (const id of selectedApps) { + if (!apps[id]) throw new Error(`Unknown app: ${id}`); + } + if (sharedNetwork && !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(sharedNetwork)) { + throw new Error('Invalid Docker network name.'); + } + if (!selectedApps.includes('seerrng') && !sharedNetwork) { + throw new Error( + 'An app-only stack requires --network so the existing SeerrNG container can reach its services.' + ); + } + const lines = ['services:']; + for (const id of selectedApps) { + const app = apps[id]; + lines.push(` ${id}:`); + lines.push(` image: ${quote(app.image)}`); + lines.push(' restart: unless-stopped'); + if (sharedNetwork) lines.push(' networks:', ' - seerrng-shared'); + lines.push(' ports:'); + const hostPortVariable = `${id.toUpperCase()}_HOST_PORT`; + lines.push( + ` - ${quote(`127.0.0.1:\${${hostPortVariable}:-${app.hostPort ?? app.port}}:${app.port}`)}` + ); + if (id === 'qbittorrent') { + lines.push(' - "${QBITTORRENT_PEER_PORT:-6881}:6881"'); + lines.push(' - "${QBITTORRENT_PEER_PORT:-6881}:6881/udp"'); + } + if ( + [ + 'radarr', + 'sonarr', + 'lidarr', + 'prowlarr', + 'qbittorrent', + 'chaptarrng', + 'lazylibrarian', + 'mylar3', + 'kapowarr', + 'backissue', + 'romarrng', + 'questarrng', + ].includes(id) + ) { + lines.push(' environment:'); + lines.push(' PUID: ${PUID:-1000}'); + lines.push(' PGID: ${PGID:-1000}'); + lines.push(' TZ: ${TZ:-Etc/UTC}'); + } + if (id === 'qbittorrent') { + lines.push(' WEBUI_PORT: "8080"'); + lines.push(' TORRENTING_PORT: "6881"'); + } + if (id === 'backissue') { + lines.push(' UMASK: "022"'); + } + if (id === 'romarrng') lines.push(' LIBRARY_PATH: /roms'); + if (id === 'questarrng') lines.push(' PORT: 5000'); + lines.push(' volumes:'); + for (const volume of app.volumes) lines.push(` - ${volume}`); + } + lines.push('volumes:'); + const volumeNames = new Set( + selectedApps.flatMap((id) => + apps[id].volumes.map((entry) => entry.split(':')[0]) + ) + ); + for (const volume of volumeNames) lines.push(` ${volume}: {}`); + if (sharedNetwork) { + lines.push( + 'networks:', + ' seerrng-shared:', + ' external: true', + ` name: ${quote(sharedNetwork)}` + ); + } + return `${lines.join('\n')}\n`; +}; + +export const renderGuide = (selectedApps, profileTitle, sharedNetwork) => { + const includesSeerr = selectedApps.includes('seerrng'); + const integrations = selectedApps.flatMap((id) => apps[id].integrations); + const hasDownloadVolume = selectedApps.some((id) => + apps[id].volumes.some((volume) => volume.startsWith('downloads:')) + ); + const contentVolumeNames = new Set( + selectedApps.flatMap((id) => + apps[id].volumes + .map((volume) => volume.split(':')[0]) + .filter((name) => name !== 'downloads' && !name.endsWith('-config')) + ) + ); + const lines = [ + `# ${profileTitle} setup`, + '', + sharedNetwork + ? `This app stack joins the existing Docker network \`${sharedNetwork}\`. Docker named volumes store persistent app configuration.` + : 'This stack uses Docker named volumes for persistent app configuration. Docker manages these volumes with Docker Desktop on Windows and macOS, and Docker Engine on Linux.', + '', + '## Start', + '', + ...(sharedNetwork && !includesSeerr + ? [ + `If the network does not exist yet, create it with \`docker network create ${sharedNetwork}\`. Run \`docker ps\` to find the existing SeerrNG container, then connect it with \`docker network connect ${sharedNetwork} CONTAINER_ID\` (replace \`CONTAINER_ID\` with its name or ID).`, + 'Run `docker compose up -d` in this folder. Open your existing SeerrNG instance.', + ] + : [ + ...(sharedNetwork + ? [ + `If the external network does not exist yet, create it with \`docker network create ${sharedNetwork}\`.`, + ] + : []), + 'Run `docker compose up -d` in this folder. Open SeerrNG at http://localhost:5055.', + ]), + '', + '## Connect apps to SeerrNG', + '', + `In SeerrNG, open **Settings → Services** for media services. Configure Prowlarr under **Settings → Prowlarr** and QuestarrNG or ROMarrNG under **Settings → Services → Software Acquisition**. Add each app, enter its API key from that app’s settings, and use **Test** before saving. ${sharedNetwork && !includesSeerr ? 'Because the existing SeerrNG container and these apps share a Docker network, use each service address below as its hostname.' : 'When SeerrNG runs in this Compose stack, use the service address below as its hostname.'} Use the listed container port. Leave SSL off unless you have configured TLS for that app.`, + '', + ]; + if (integrations.length) { + for (const entry of integrations) lines.push(`- ${entry}`); + } else { + lines.push( + 'This profile does not include an automation service to link yet.' + ); + } + lines.push( + '', + 'Web ports bind to this computer only. To reach a web interface from another device, deliberately change its host-side bind address after reviewing your network and authentication settings.' + ); + if (selectedApps.includes('qbittorrent')) { + lines.push( + 'qBittorrent also publishes peer traffic on TCP and UDP port 6881 on the Docker host so it can participate in torrent transfers.' + ); + } + if (selectedApps.includes('romarrng')) { + lines.push( + 'After saving ROMarrNG, assign each supported system to **Retro** or **Modern** in SeerrNG before enabling emulation requests. ROMarrNG handles emulation requests; QuestarrNG handles PC game requests.' + ); + } + if (selectedApps.includes('chaptarrng')) { + lines.push( + 'ChaptarrNG is an alternative Bookshelf-compatible provider. If one instance handles both formats, add both SeerrNG connections above with the same address and API key. Choose one provider per format to avoid duplicate acquisitions.' + ); + } + if (selectedApps.includes('backissue')) { + lines.push( + 'The BackIssue image currently publishes a linux/amd64 container. On ARM64 hosts, Docker may need x86 emulation; use Mylar3 or Kapowarr for a native multi-architecture option.' + ); + } + if (selectedApps.includes('kapowarr')) { + lines.push( + 'Kapowarr keeps its temporary downloads in `/app/temp_downloads` and uses its own GetComics and mirror sources; it does not use Prowlarr indexers.' + ); + } + const storageDetails = []; + if (contentVolumeNames.size) { + storageDetails.push( + `content files in ${[...contentVolumeNames].map((name) => `\`${name}\``).join(', ')} named volumes` + ); + } + if (hasDownloadVolume) storageDetails.push('downloads in `downloads`'); + if (storageDetails.length) { + const volumeMounts = selectedApps.flatMap((id) => + apps[id].volumes + .filter((volume) => { + const name = volume.split(':')[0]; + return name === 'downloads' || contentVolumeNames.has(name); + }) + .map((volume) => `${apps[id].title} \`${volume.split(':')[1]}\``) + ); + lines.push( + '', + `Docker manages ${storageDetails.join(' and ')}. Content and download volumes are mounted at ${volumeMounts.join(', ')}. Configure each app's root folders and download paths to match these mount points. Back up named volumes before moving this stack.` + ); + } + const portOverrides = selectedApps.map( + (id) => + `\`${id.toUpperCase()}_HOST_PORT\` (default ${apps[id].hostPort ?? apps[id].port})` + ); + if (selectedApps.includes('qbittorrent')) { + portOverrides.push('`QBITTORRENT_PEER_PORT` (default 6881)'); + } + lines.push( + '', + 'Resolve host-port conflicts by setting the matching variable in a `.env` file in this folder: ' + + `${portOverrides.join(', ')}. App-to-app container ports stay the same.`, + '' + ); + if (selectedApps.includes('qbittorrent')) { + lines.splice( + lines.length - 1, + 0, + 'Configure qBittorrent as the download client in each automation app that should use it. Use `qbittorrent` as its hostname, port `8080`, and the same `/downloads` path; enter the credentials configured in qBittorrent.' + ); + lines.splice( + lines.length - 1, + 0, + 'On first start, qBittorrent prints a temporary `admin` password in its container log. Sign in at http://localhost:8080 (or the host port you configured) and set a permanent password in the Web UI settings before connecting download clients.' + ); + } + return lines.join('\n'); +}; + +export const parseComposeStatus = (output) => { + const value = output.trim(); + if (!value) return []; + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed : [parsed]; + } catch { + return value + .split(/\r?\n/) + .map((line) => JSON.parse(line)) + .filter((entry) => entry && typeof entry === 'object'); + } +}; + +const runDocker = (args, options = {}) => + spawnSync('docker', args, { + encoding: 'utf8', + timeout: 15000, + maxBuffer: 2 * 1024 * 1024, + ...options, + }); + +const parseDockerJson = (output, description) => { + try { + return JSON.parse(output); + } catch { + throw new Error(`Docker returned invalid ${description} JSON.`); + } +}; + +const identifyApp = (container) => { + const image = String(container.Config?.Image ?? container.Image ?? '') + .toLowerCase() + .replace(/@sha256:[a-f0-9]+$/, '') + .replace(/:[^/]+$/, ''); + const composeService = String( + container.Config?.Labels?.['com.docker.compose.service'] ?? '' + ).toLowerCase(); + const name = String(container.Name ?? '') + .replace(/^\//, '') + .toLowerCase(); + + for (const [id, app] of Object.entries(apps)) { + const expectedImage = app.image.toLowerCase().replace(/:[^/]+$/, ''); + if (image === expectedImage) return id; + if (composeService === id || name === id) { + return id; + } + } + + return undefined; +}; + +const isSafeDockerHostname = (value) => + /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,252}$/.test(value); + +export const discoverNetworkApps = (networkName, docker = runDocker) => { + if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(networkName ?? '')) { + throw new Error('Provide a valid Docker network name with --network.'); + } + const networkResult = docker(['network', 'inspect', networkName]); + if (networkResult.error) throw networkResult.error; + if (networkResult.status !== 0) { + throw new Error( + networkResult.stderr?.trim() || + `Docker could not inspect network ${networkName}.` + ); + } + const networkDocument = parseDockerJson( + networkResult.stdout ?? '', + 'network inspection' + ); + const network = Array.isArray(networkDocument) + ? networkDocument[0] + : networkDocument; + if (!network || typeof network !== 'object') { + throw new Error(`Docker network ${networkName} was not found.`); + } + const attached = Object.keys(network.Containers ?? {}); + if (attached.length > 64) { + throw new Error( + `Network ${networkName} has more than 64 attached containers; narrow discovery to a dedicated app network.` + ); + } + if (attached.length === 0) return []; + + const inspectResult = docker(['inspect', '--type', 'container', ...attached]); + if (inspectResult.error) throw inspectResult.error; + if (inspectResult.status !== 0) { + throw new Error( + inspectResult.stderr?.trim() || + 'Docker could not inspect network containers.' + ); + } + const containers = parseDockerJson( + inspectResult.stdout ?? '', + 'container inspection' + ); + if (!Array.isArray(containers)) { + throw new Error( + 'Docker returned an unexpected container inspection result.' + ); + } + + return containers.flatMap((container) => { + const id = identifyApp(container); + if (!id) return []; + const networkDetails = + Object.entries(container.NetworkSettings?.Networks ?? {}).find( + ([name, entry]) => + entry.NetworkID === network.Id || name === network.Name + )?.[1] ?? {}; + const aliases = Array.isArray(networkDetails.Aliases) + ? networkDetails.Aliases.filter( + (alias) => typeof alias === 'string' && alias.length > 0 + ) + : []; + const service = String( + container.Config?.Labels?.['com.docker.compose.service'] ?? '' + ); + const containerName = String(container.Name ?? '').replace(/^\//, ''); + const hostname = [ + service, + ...aliases.filter((alias) => alias !== container.Id), + containerName, + ].find(isSafeDockerHostname); + if (!hostname) return []; + const reportedState = String(container.State?.Status ?? 'unknown'); + + return [ + { + id, + title: apps[id].title, + hostname, + port: apps[id].port, + state: /^[a-z]+$/.test(reportedState) ? reportedState : 'unknown', + }, + ]; + }); +}; + +export const renderDiscoveredConnections = (networkName, connections) => { + const lines = [ + `# Detected SeerrNG connections on ${networkName}`, + '', + 'These suggestions come from containers attached to the selected Docker network. Copy the hostname and port into the matching SeerrNG service form, enter that app’s API key, select **Test**, review the returned options, and save.', + '', + 'Discovery does not read container environment variables, API keys, or app settings. It only identifies known images and Compose service aliases.', + '', + ]; + if (connections.length === 0) { + lines.push( + 'No supported SeerrNG companion apps were found on this network.' + ); + } else { + for (const connection of connections) { + lines.push( + `- **${connection.title}** — hostname \`${connection.hostname}\`, port \`${connection.port}\` (${connection.state})` + ); + if (connection.id === 'bookshelf' || connection.id === 'chaptarrng') { + lines.push( + ' Add separate Book and Audiobook service entries using the same hostname, port, and API key.' + ); + } + if (connection.id === 'questarrng' || connection.id === 'romarrng') { + lines.push( + ' Configure this provider under **Settings → Services → Software Acquisition**.' + ); + } + if (connection.id === 'prowlarr') { + lines.push(' Configure this provider under **Settings → Prowlarr**.'); + } + } + } + return `${lines.join('\n')}\n`; +}; + +const discoverAndReport = async (networkName, outputDirectory) => { + const connections = discoverNetworkApps(networkName); + if (connections.length === 0) { + stdout.write( + `No supported apps detected on Docker network ${networkName}.\n` + ); + } else { + stdout.write(`Detected apps on Docker network ${networkName}:\n`); + for (const connection of connections) { + stdout.write( + ` ${connection.title}: hostname ${connection.hostname}, port ${connection.port} (${connection.state})\n` + ); + } + } + + if (outputDirectory) { + const resolvedDirectory = path.resolve(outputDirectory); + await mkdir(resolvedDirectory, { recursive: true }); + const jsonPath = path.join(resolvedDirectory, 'seerrng-connections.json'); + const guidePath = path.join(resolvedDirectory, 'CONNECTIONS.md'); + await writeFile( + jsonPath, + `${JSON.stringify({ network: networkName, connections }, null, 2)}\n`, + { flag: 'wx', mode: 0o600 } + ); + try { + await writeFile( + guidePath, + renderDiscoveredConnections(networkName, connections), + { + flag: 'wx', + mode: 0o600, + } + ); + } catch (error) { + await unlink(jsonPath).catch(() => {}); + throw error; + } + stdout.write( + `Wrote private connection suggestions to ${resolvedDirectory}.\n` + ); + } +}; + +const detectComposeApps = async (outputDirectory) => { + await access(path.join(outputDirectory, 'compose.yaml')); + const result = spawnSync('docker', ['compose', 'ps', '--format', 'json'], { + cwd: outputDirectory, + encoding: 'utf8', + }); + if (result.error) throw result.error; + if (result.status !== 0) { + throw new Error( + result.stderr?.trim() || + `Docker Compose status check exited with ${result.status ?? 'unknown'}.` + ); + } + const containers = parseComposeStatus(result.stdout ?? ''); + if (containers.length === 0) { + stdout.write( + 'No containers are currently detected in this Compose stack.\n' + ); + return; + } + stdout.write('Detected Compose services:\n'); + for (const container of containers) { + const service = container.Service ?? container.Name ?? 'Unknown service'; + const state = container.State ?? container.Status ?? 'unknown state'; + const health = container.Health ? ` (${container.Health})` : ''; + stdout.write(` ${service}: ${state}${health}\n`); + } +}; + +const help = () => { + stdout.write( + `SeerrNG setup assistant\n\nUsage: pnpm setup:assistant [options]\n\nOptions:\n --profile choose a media profile (see --list-profiles)\n --apps add app IDs or remove with - (comma-separated)\n --network join or discover apps on an explicitly named Docker network\n --output output folder (default: ./seerrng-stack)\n --yes create files without interactive prompts\n --start start the stack after creating files\n --detect report containers in an existing Compose stack\n --discover identify supported apps attached to --network\n --list-profiles print available profiles\n --help show this help\n\nUse --discover --network to write ready-to-use host and port suggestions. API keys stay in each app and are entered in SeerrNG.\nTo add apps to an existing SeerrNG, remove it with --apps -seerrng and set --network.\nWithout --profile, choose a profile from the interactive menu.\n` + ); +}; + +const run = async () => { + const args = process.argv.slice(2); + if (args.includes('--help') || args.includes('-h')) { + help(); + return; + } + if (args.includes('--list-profiles')) { + for (const [key, profile] of Object.entries(profiles)) { + stdout.write(`${key}\t${profile.title}\n`); + } + return; + } + + const optionValue = (name, fallback) => { + const index = args.indexOf(name); + return index >= 0 ? args[index + 1] : fallback; + }; + + if (args.includes('--detect')) { + const outputDirectory = path.resolve( + optionValue('--output', './seerrng-stack') + ); + try { + await detectComposeApps(outputDirectory); + } catch (error) { + stderr.write( + `${error instanceof Error ? error.message : String(error)}\n` + ); + process.exitCode = 1; + } + return; + } + + if (args.includes('--discover')) { + try { + const networkName = optionValue('--network'); + if (!networkName) { + throw new Error('--discover requires --network .'); + } + await discoverAndReport( + networkName, + args.includes('--output') ? optionValue('--output') : undefined + ); + } catch (error) { + stderr.write( + `${error instanceof Error ? error.message : String(error)}\n` + ); + process.exitCode = 1; + } + return; + } + + let profileName = optionValue('--profile'); + const rl = readline.createInterface({ input: stdin, output: stdout }); + try { + if (!profileName) { + stdout.write('Choose a starter profile:\n'); + Object.entries(profiles).forEach(([key, profile], index) => { + stdout.write(` ${index + 1}. ${profile.title} (${key})\n`); + }); + const answer = await rl.question('Profile number: '); + profileName = Object.keys(profiles)[Number(answer) - 1]; + } + + const profile = profiles[profileName]; + if (!profile) + throw new Error(`Unknown profile "${profileName}". Use --list-profiles.`); + const selected = [...profile.apps]; + const nonInteractive = args.includes('--yes'); + if (nonInteractive && !optionValue('--profile')) { + throw new Error('--yes requires --profile.'); + } + let changes = optionValue('--apps', ''); + if (!nonInteractive && !changes) { + stdout.write( + `\nApps in this profile: ${selected.map((id) => `${id} (${apps[id].title})`).join(', ')}\n` + ); + stdout.write(`Available app IDs: ${Object.keys(apps).join(', ')}\n`); + changes = await rl.question( + 'Optional app IDs to add, or prefix with - to remove (comma-separated; Enter keeps this profile): ' + ); + } + for (const change of changes + .split(',') + .map((value) => value.trim()) + .filter(Boolean)) { + const remove = change.startsWith('-'); + const id = remove ? change.slice(1) : change; + if (!apps[id]) throw new Error(`Unknown app "${id}".`); + if (remove) { + const index = selected.indexOf(id); + if (index >= 0) selected.splice(index, 1); + } else if (!selected.includes(id)) { + selected.push(id); + } + } + if (selected.length === 0) { + throw new Error('Select at least one app for the Compose stack.'); + } + const sharedNetwork = optionValue('--network'); + if (sharedNetwork && !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(sharedNetwork)) { + throw new Error( + 'Docker network names can contain letters, numbers, dots, underscores, and hyphens.' + ); + } + if (!selected.includes('seerrng') && !sharedNetwork) { + throw new Error( + 'Removing SeerrNG requires --network so your existing instance can reach the selected apps.' + ); + } + const outputDirectory = path.resolve( + optionValue('--output', './seerrng-stack') + ); + stdout.write( + `\nSelected: ${profile.title}\nApps: ${selected.map((id) => apps[id].title).join(', ')}\nOutput: ${outputDirectory}\n` + ); + const confirm = nonInteractive + ? 'y' + : await rl.question('Create the Compose stack and setup guide? [Y/n] '); + if (/^(n|no)$/i.test(confirm.trim())) return; + + await mkdir(outputDirectory, { recursive: true }); + const composePath = path.join(outputDirectory, 'compose.yaml'); + const guidePath = path.join(outputDirectory, 'SETUP.md'); + const fileExists = await Promise.all( + [composePath, guidePath].map(async (file) => { + try { + await access(file); + return true; + } catch (error) { + if (error?.code === 'ENOENT') return false; + throw error; + } + }) + ); + if (fileExists.some(Boolean)) { + throw Object.assign(new Error('Output files already exist.'), { + code: 'EEXIST', + }); + } + await writeFile(composePath, renderCompose(selected, sharedNetwork), { + flag: 'wx', + }); + try { + await writeFile( + guidePath, + renderGuide(selected, profile.title, sharedNetwork), + { flag: 'wx' } + ); + } catch (error) { + await unlink(composePath).catch(() => {}); + throw error; + } + stdout.write( + '\nCreated compose.yaml and SETUP.md. Review SETUP.md, then run `docker compose up -d` from the output folder.\n' + ); + const start = args.includes('--start') + ? 'y' + : nonInteractive + ? 'n' + : await rl.question('Start the stack now with Docker Compose? [y/N] '); + if (/^(y|yes)$/i.test(start.trim())) { + const result = spawnSync('docker', ['compose', 'up', '-d'], { + cwd: outputDirectory, + stdio: 'inherit', + }); + if (result.error) throw result.error; + if (result.status !== 0) + throw new Error( + `Docker Compose exited with status ${result.status ?? 'unknown'}.` + ); + stdout.write( + 'Stack started. Open http://localhost:5055 and follow SETUP.md to link the apps.\n' + ); + await detectComposeApps(outputDirectory); + } + } catch (error) { + if (error?.code === 'EEXIST') { + stderr.write( + 'The output files already exist. Choose a new --output folder to avoid overwriting them.\n' + ); + } else { + stderr.write( + `${error instanceof Error ? error.message : String(error)}\n` + ); + } + process.exitCode = 1; + } finally { + rl.close(); + } +}; + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href +) { + await run(); +} diff --git a/scripts/setup-assistant.test.mjs b/scripts/setup-assistant.test.mjs new file mode 100644 index 0000000000..0b02b658dd --- /dev/null +++ b/scripts/setup-assistant.test.mjs @@ -0,0 +1,338 @@ +import { load } from 'js-yaml'; +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { + apps, + discoverNetworkApps, + parseComposeStatus, + profiles, + renderCompose, + renderDiscoveredConnections, + renderGuide, +} from './setup-assistant.mjs'; + +test('every starter profile contains SeerrNG and known app definitions', () => { + for (const [name, profile] of Object.entries(profiles)) { + assert.ok(profile.apps.includes('seerrng'), `${name} includes SeerrNG`); + for (const app of profile.apps) + assert.ok(apps[app], `${name} app ${app} exists`); + } +}); + +test('the complete app catalog renders valid Compose with distinct format storage', () => { + const compose = renderCompose(Object.keys(apps)); + const document = load(compose); + + assert.deepEqual(Object.keys(document.services), Object.keys(apps)); + assert.equal( + document.services.bookshelf.ports[0], + '127.0.0.1:${BOOKSHELF_HOST_PORT:-8787}:8787' + ); + assert.equal( + document.services.backissue.ports[0], + '127.0.0.1:${BACKISSUE_HOST_PORT:-8788}:8787' + ); + assert.deepEqual(document.services.backissue.environment, { + PUID: '${PUID:-1000}', + PGID: '${PGID:-1000}', + TZ: '${TZ:-Etc/UTC}', + UMASK: '022', + }); + assert.equal(document.services.chaptarrng.volumes[1], 'ebook-data:/ebooks'); + assert.equal( + document.services.chaptarrng.volumes[2], + 'audiobook-data:/audiobooks' + ); + assert.equal(document.services.romarrng.environment.LIBRARY_PATH, '/roms'); + assert.equal(document.services.questarrng.environment.PORT, 5000); +}); + +test('profiles and optional app additions cover each supported media category', () => { + assert.ok(profiles['movies-tv'].apps.includes('radarr')); + assert.ok(profiles['movies-tv'].apps.includes('sonarr')); + assert.ok(profiles.music.apps.includes('lidarr')); + assert.ok(profiles.books.apps.includes('bookshelf')); + assert.ok(profiles['books-chaptarrng'].apps.includes('chaptarrng')); + assert.ok(profiles.comics.apps.includes('mylar3')); + assert.ok(profiles.magazines.apps.includes('lazylibrarian')); + assert.ok(profiles.software.apps.includes('questarrng')); + assert.ok(profiles.software.apps.includes('romarrng')); + assert.ok(apps.kapowarr && apps.backissue); +}); + +test('generated Compose uses persistent named volumes and configurable local web ports', () => { + const compose = renderCompose(profiles['movies-tv'].apps); + const document = load(compose); + assert.deepEqual(Object.keys(document.services), profiles['movies-tv'].apps); + assert.match(compose, /127\.0\.0\.1:\$\{SEERRNG_HOST_PORT:-5055\}:5055/); + assert.match(compose, /127\.0\.0\.1:\$\{RADARR_HOST_PORT:-7878\}:7878/); + assert.match(compose, /radarr-config:\/config/); + assert.match(compose, /media-data:\/data/); + assert.match(compose, /downloads:\/downloads/); + assert.match(compose, /media-data: \{\}/); + assert.doesNotMatch(compose, /container_name:/); + assert.match(compose, /WEBUI_PORT: "8080"/); + assert.match(compose, /TORRENTING_PORT: "6881"/); + assert.match(compose, /QBITTORRENT_PEER_PORT:-6881/); +}); + +test('setup guide uses Compose DNS names and keeps API keys out of generated content', () => { + const guide = renderGuide(profiles.books.apps, profiles.books.title); + assert.match(guide, /Books \(BookshelfNG\): bookshelf:8787/); + assert.match(guide, /use the service address below as its hostname/); + assert.match(guide, /API key from that app’s settings/); + assert.match(guide, /qBittorrent as the download client/); + assert.match(guide, /peer traffic on TCP and UDP port 6881/); + assert.match(guide, /temporary `admin` password in its container log/); + assert.match(guide, /BookshelfNG\): bookshelf:8787 \(Book format\)/); + assert.match(guide, /BookshelfNG\): bookshelf:8787 \(Audiobook format\)/); + assert.match(guide, /content files in `media-data` named volumes/); + assert.match(guide, /BookshelfNG `\/data`/); + assert.doesNotMatch(guide, /api[_ -]?key\s*[:=]\s*\S+/i); +}); + +test('generated guide only describes storage and ports present in that selection', () => { + const guide = renderGuide(['seerrng'], 'SeerrNG only'); + assert.doesNotMatch(guide, /qBittorrent/); + assert.doesNotMatch(guide, /media-data|`downloads`|qBittorrent/); + assert.match(guide, /SEERRNG_HOST_PORT/); +}); + +test('app-only stacks join an explicitly named external network', () => { + const selectedApps = profiles['movies-tv'].apps.filter( + (app) => app !== 'seerrng' + ); + assert.throws(() => renderCompose(selectedApps), /requires --network/); + + const compose = load(renderCompose(selectedApps, 'existing-seerr-network')); + assert.equal(compose.services.seerrng, undefined); + assert.deepEqual(compose.services.radarr.networks, ['seerrng-shared']); + assert.equal( + compose.networks['seerrng-shared'].name, + 'existing-seerr-network' + ); + const guide = renderGuide( + selectedApps, + profiles['movies-tv'].title, + 'existing-seerr-network' + ); + assert.match(guide, /docker network connect existing-seerr-network/); + assert.match(guide, /Open your existing SeerrNG instance/); + assert.match(guide, /use each service address below as its hostname/); +}); + +test('unknown app definitions fail rather than generating incomplete Compose', () => { + assert.throws(() => renderCompose(['missing-app']), /Unknown app/); + assert.throws( + () => renderCompose(['radarr'], 'bad network name'), + /Invalid Docker network name/ + ); +}); + +test('Compose detection accepts JSON arrays and Compose JSON-lines output', () => { + assert.deepEqual( + parseComposeStatus('[{"Service":"radarr","State":"running"}]'), + [{ Service: 'radarr', State: 'running' }] + ); + assert.deepEqual( + parseComposeStatus( + '{"Service":"radarr","State":"running"}\n{"Service":"sonarr","State":"exited"}' + ), + [ + { Service: 'radarr', State: 'running' }, + { Service: 'sonarr', State: 'exited' }, + ] + ); +}); + +test('network discovery inspects only the named network and suggests app DNS ports', () => { + const calls = []; + const docker = (args) => { + calls.push(args); + if (args[0] === 'network') { + return { + status: 0, + stdout: JSON.stringify([ + { + Id: 'network-id', + Name: 'media-net', + Containers: { radarrId: {}, bookshelfId: {}, unknownId: {} }, + }, + ]), + }; + } + return { + status: 0, + stdout: JSON.stringify([ + { + Id: 'radarrId', + Name: '/media-radarr-1', + Config: { + Image: 'lscr.io/linuxserver/radarr:latest', + Labels: { 'com.docker.compose.service': 'radarr' }, + Env: ['RADARR_API_KEY=must-not-appear'], + }, + State: { Status: 'running' }, + NetworkSettings: { + Networks: { + 'media-net': { + NetworkID: 'network-id', + Aliases: ['media-radarr-1', 'radarr'], + }, + }, + }, + }, + { + Id: 'bookshelfId', + Name: '/bookshelf', + Config: { + Image: 'ghcr.io/snapetech/bookshelfng:hardcover', + Labels: {}, + }, + State: { Status: 'running' }, + NetworkSettings: { + Networks: { + 'media-net': { + NetworkID: 'network-id', + Aliases: ['bookshelf'], + }, + }, + }, + }, + { + Id: 'unknownId', + Name: '/other', + Config: { + Image: 'example.invalid/unknown:latest', + Env: ['SECRET=private'], + }, + NetworkSettings: { Networks: {} }, + }, + ]), + }; + }; + + const connections = discoverNetworkApps('media-net', docker); + assert.deepEqual(calls, [ + ['network', 'inspect', 'media-net'], + ['inspect', '--type', 'container', 'radarrId', 'bookshelfId', 'unknownId'], + ]); + assert.deepEqual(connections, [ + { + id: 'radarr', + title: 'Radarr', + hostname: 'radarr', + port: '7878', + state: 'running', + }, + { + id: 'bookshelf', + title: 'BookshelfNG', + hostname: 'bookshelf', + port: '8787', + state: 'running', + }, + ]); + + const guide = renderDiscoveredConnections('media-net', connections); + assert.match(guide, /hostname `radarr`, port `7878`/); + assert.match(guide, /separate Book and Audiobook service entries/); + assert.doesNotMatch( + guide, + /must-not-appear|SECRET=private|api[_ -]?key\s*[:=]/i + ); +}); + +test('network discovery rejects invalid names and caps large network inspection', () => { + let callCount = 0; + const docker = () => { + callCount += 1; + return { + status: 0, + stdout: JSON.stringify([ + { + Id: 'large-network', + Name: 'media-net', + Containers: Object.fromEntries( + Array.from({ length: 65 }, (_, index) => [`container-${index}`, {}]) + ), + }, + ]), + }; + }; + + assert.throws( + () => discoverNetworkApps('invalid network', docker), + /valid Docker network/ + ); + assert.equal(callCount, 0); + assert.throws(() => discoverNetworkApps('media-net', docker), /more than 64/); + assert.equal(callCount, 1); +}); + +test('interactive setup writes the selected profile and refuses to overwrite it', async () => { + const temporaryDirectory = await mkdtemp( + path.join(tmpdir(), 'seerrng-setup-assistant-') + ); + const outputDirectory = path.join(temporaryDirectory, 'stack'); + const scriptPath = fileURLToPath( + new URL('./setup-assistant.mjs', import.meta.url) + ); + const run = (extraArguments = []) => + spawnSync( + process.execPath, + [scriptPath, '--profile', 'movies-tv', '--output', ...extraArguments], + { encoding: 'utf8' } + ); + + try { + const firstRun = run([outputDirectory, '--yes']); + assert.equal(firstRun.status, 0, firstRun.stderr); + const compose = await readFile( + path.join(outputDirectory, 'compose.yaml'), + 'utf8' + ); + const guide = await readFile( + path.join(outputDirectory, 'SETUP.md'), + 'utf8' + ); + assert.match(compose, /sonarr:/); + assert.match(guide, /Radarr: radarr:7878/); + + const secondRun = run([outputDirectory, '--yes']); + assert.equal(secondRun.status, 1); + assert.match(secondRun.stderr, /output files already exist/i); + + const appOnlyDirectory = path.join(temporaryDirectory, 'apps-only'); + const appOnlyRun = spawnSync( + process.execPath, + [ + scriptPath, + '--profile', + 'movies-tv', + '--apps', + '-seerrng', + '--network', + 'existing-seerr-network', + '--output', + appOnlyDirectory, + '--yes', + ], + { encoding: 'utf8' } + ); + assert.equal(appOnlyRun.status, 0, appOnlyRun.stderr); + const appOnlyCompose = await readFile( + path.join(appOnlyDirectory, 'compose.yaml'), + 'utf8' + ); + assert.doesNotMatch(appOnlyCompose, /\n seerrng:/); + assert.match(appOnlyCompose, /name: "existing-seerr-network"/); + } finally { + await rm(temporaryDirectory, { recursive: true, force: true }); + } +}); diff --git a/src/components/Settings/BackIssueModal/index.tsx b/src/components/Settings/BackIssueModal/index.tsx index bfbd96f9bd..b76023bd29 100644 --- a/src/components/Settings/BackIssueModal/index.tsx +++ b/src/components/Settings/BackIssueModal/index.tsx @@ -3,6 +3,7 @@ import SensitiveInput from '@app/components/Common/SensitiveInput'; import Field, { default as SettingsField, } from '@app/components/Settings/SettingsField'; +import { useSetupConnectionSuggestion } from '@app/context/SetupConnectionsContext'; import useToasts from '@app/hooks/useToasts'; import globalMessages from '@app/i18n/globalMessages'; import defineMessages from '@app/utils/defineMessages'; @@ -64,6 +65,7 @@ const BackIssueModal = ({ onSave, }: BackIssueModalProps) => { const intl = useIntl(); + const setupConnection = useSetupConnectionSuggestion('backissue'); const initialLoad = useRef(false); const { addToast } = useToasts(); const [isValidated, setIsValidated] = useState(Boolean(backissue)); @@ -157,8 +159,8 @@ const BackIssueModal = ({ { const intl = useIntl(); + const setupConnection = useSetupConnectionSuggestion('kapowarr'); const initialLoad = useRef(false); const { addToast } = useToasts(); const [isValidated, setIsValidated] = useState(kapowarr ? true : false); @@ -180,8 +182,8 @@ const KapowarrModal = ({ onClose, kapowarr, onSave }: KapowarrModalProps) => { { const intl = useIntl(); + const setupConnection = useSetupConnectionSuggestion('lazylibrarian'); const initialLoad = useRef(false); const { addToast } = useToasts(); const [isValidated, setIsValidated] = useState(Boolean(lazylibrarian)); @@ -163,8 +165,8 @@ const LazyLibrarianModal = ({ { const intl = useIntl(); + const setupConnection = useSetupConnectionSuggestion('lidarr'); const initialLoad = useRef(false); const { addToast } = useToasts(); const [isValidated, setIsValidated] = useState(lidarr ? true : false); @@ -246,8 +248,8 @@ const LidarrModal = ({ onClose, lidarr, onSave }: LidarrModalProps) => { { const intl = useIntl(); + const setupConnection = useSetupConnectionSuggestion('mylar3'); const initialLoad = useRef(false); const { addToast } = useToasts(); const [isValidated, setIsValidated] = useState(mylar ? true : false); @@ -171,8 +173,8 @@ const MylarModal = ({ onClose, mylar, onSave }: MylarModalProps) => { { const intl = useIntl(); + const setupConnection = useSetupConnectionSuggestion('radarr'); const initialLoad = useRef(false); const { addToast } = useToasts(); const [isValidated, setIsValidated] = useState(radarr ? true : false); @@ -234,8 +236,8 @@ const RadarrModal = ({ onClose, radarr, onSave }: RadarrModalProps) => { { const intl = useIntl(); + const bookshelfSuggestion = useSetupConnectionSuggestion('bookshelf'); + const chaptarrSuggestion = useSetupConnectionSuggestion('chaptarrng'); + const setupConnection = bookshelfSuggestion ?? chaptarrSuggestion; const initialLoad = useRef(false); const { addToast } = useToasts(); const [isValidated, setIsValidated] = useState(readarr ? true : false); @@ -315,8 +319,13 @@ const ReadarrModal = ({ { -
+
({ const SettingsProwlarr = () => { const intl = useIntl(); + const setupConnection = useSetupConnectionSuggestion('prowlarr'); const { data, error } = useSWR( '/api/v1/settings/prowlarr' ); @@ -195,8 +197,17 @@ const SettingsProwlarr = () => { const [errorMessage, setErrorMessage] = useState(''); useEffect(() => { - if (data) setForm(toForm(data)); - }, [data]); + if (!data) return; + setForm((current) => { + const next = current ?? toForm(data); + if (data.hostname || next.hostname || !setupConnection) return next; + return { + ...next, + hostname: setupConnection.hostname, + port: setupConnection.port, + }; + }); + }, [data, setupConnection]); const usingSavedConnection = Boolean( data && diff --git a/src/components/Settings/SettingsServices.tsx b/src/components/Settings/SettingsServices.tsx index ca9d3aaba4..ef3c5b68f0 100644 --- a/src/components/Settings/SettingsServices.tsx +++ b/src/components/Settings/SettingsServices.tsx @@ -11,6 +11,7 @@ import OverrideRuleTiles from '@app/components/Settings/OverrideRule/OverrideRul import { useSettingsPageAction } from '@app/components/Settings/SettingsLayout'; import SettingsProwlarr from '@app/components/Settings/SettingsProwlarr'; import SettingsSoftwareAcquisition from '@app/components/Settings/SettingsSoftwareAcquisition'; +import SetupConnectionsImport from '@app/components/Settings/SetupConnectionsImport'; import globalMessages from '@app/i18n/globalMessages'; import defineMessages from '@app/utils/defineMessages'; import { getSafeHref } from '@app/utils/safeUrl'; @@ -69,6 +70,10 @@ const SonarrModal = dynamic( const messages = defineMessages('components.Settings', { services: 'Services', + setupAssistantTitle: 'Connect your apps', + setupAssistantDescription: + 'Generate a Docker Compose starter or discover apps on a Docker network. Import the connection report to prefill hostnames and ports, then test each API connection before saving.', + setupAssistantGuide: 'Open the setup guide', radarrsettings: 'Radarr Settings', sonarrsettings: 'Sonarr Settings', lidarrsettings: 'Lidarr Settings', @@ -515,6 +520,25 @@ const SettingsServices = () => { intl.formatMessage(globalMessages.settings), ]} /> +
+

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

+

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

+ + +

{intl.formatMessage(messages.radarrsettings)} diff --git a/src/components/Settings/SettingsSoftwareAcquisition.tsx b/src/components/Settings/SettingsSoftwareAcquisition.tsx index 6eb0f1371b..06ff3f11cc 100644 --- a/src/components/Settings/SettingsSoftwareAcquisition.tsx +++ b/src/components/Settings/SettingsSoftwareAcquisition.tsx @@ -3,6 +3,7 @@ import Button from '@app/components/Common/Button'; import LoadingSpinner from '@app/components/Common/LoadingSpinner'; import SelectionCircle from '@app/components/Common/SelectionCircle'; import Tooltip from '@app/components/Common/Tooltip'; +import { useSetupConnectionSuggestion } from '@app/context/SetupConnectionsContext'; import defineMessages from '@app/utils/defineMessages'; import { QuestionMarkCircleIcon } from '@heroicons/react/24/outline'; import type { EmulationSystemGroup } from '@server/lib/settings'; @@ -127,6 +128,8 @@ const getProviderPayload = (provider: ProviderSettings) => ({ const SettingsSoftwareAcquisition = () => { const intl = useIntl(); + const romarrSuggestion = useSetupConnectionSuggestion('romarrng'); + const questarrSuggestion = useSetupConnectionSuggestion('questarrng'); const { data, error, isLoading } = useSWR( '/api/v1/settings/software-acquisition' ); @@ -155,11 +158,31 @@ const SettingsSoftwareAcquisition = () => { useEffect(() => { if (!data) return; - setRomarr(toProviderState(data.romarr)); - setQuestarr(toProviderState(data.questarr)); + setRomarr((current) => { + const next = current ?? toProviderState(data.romarr); + if (data.romarr.hostname || next.hostname || !romarrSuggestion) { + return next; + } + return { + ...next, + hostname: romarrSuggestion.hostname, + port: romarrSuggestion.port, + }; + }); + setQuestarr((current) => { + const next = current ?? toProviderState(data.questarr); + if (data.questarr.hostname || next.hostname || !questarrSuggestion) { + return next; + } + return { + ...next, + hostname: questarrSuggestion.hostname, + port: questarrSuggestion.port, + }; + }); setEmulationCatalogProvider(data.emulationCatalogProvider ?? 'questarr'); setSystemGroups(data.emulationSystemGroups ?? {}); - }, [data]); + }, [data, romarrSuggestion, questarrSuggestion]); const updateProvider = ( provider: 'romarr' | 'questarr', diff --git a/src/components/Settings/SetupConnectionsImport.tsx b/src/components/Settings/SetupConnectionsImport.tsx new file mode 100644 index 0000000000..ababe423f0 --- /dev/null +++ b/src/components/Settings/SetupConnectionsImport.tsx @@ -0,0 +1,83 @@ +import Button from '@app/components/Common/Button'; +import { useSetupConnections } from '@app/context/SetupConnectionsContext'; +import defineMessages from '@app/utils/defineMessages'; +import { useRef, useState } from 'react'; +import { useIntl } from 'react-intl'; + +const messages = defineMessages('components.Settings.SetupConnectionsImport', { + import: 'Import detected connections', + help: 'Choose the seerrng-connections.json file created by the setup assistant. Hostnames and ports will prefill matching service forms; API keys are never imported.', + imported: + 'Loaded suggestions for {count, plural, one {# app} other {# apps}}. Matching add forms will use these hostnames and ports.', + clear: 'Clear imported suggestions', + invalidFile: 'Unable to read this setup file.', +}); + +const SetupConnectionsImport = () => { + const intl = useIntl(); + const input = useRef(null); + const { connections, importFile, clearConnections } = useSetupConnections(); + const [error, setError] = useState(''); + + const handleFileChange = async ( + event: React.ChangeEvent + ) => { + const target = event.currentTarget; + const file = target.files?.[0]; + if (!file) return; + setError(''); + try { + await importFile(file); + } catch { + setError(intl.formatMessage(messages.invalidFile)); + } finally { + target.value = ''; + } + }; + + return ( + <> +
+ + + {connections.length > 0 && ( + <> +

+ {intl.formatMessage(messages.imported, { + count: connections.length, + })} +

+ + + )} +
+

{intl.formatMessage(messages.help)}

+ {error && ( +

+ {error} +

+ )} + + ); +}; + +export default SetupConnectionsImport; diff --git a/src/components/Settings/SonarrModal/index.tsx b/src/components/Settings/SonarrModal/index.tsx index a27b792ca1..bfa571e8be 100644 --- a/src/components/Settings/SonarrModal/index.tsx +++ b/src/components/Settings/SonarrModal/index.tsx @@ -4,6 +4,7 @@ import Field, { default as SettingsField, } from '@app/components/Settings/SettingsField'; import type { SonarrTestResponse } from '@app/components/Settings/SettingsServices'; +import { useSetupConnectionSuggestion } from '@app/context/SetupConnectionsContext'; import useToasts from '@app/hooks/useToasts'; import globalMessages from '@app/i18n/globalMessages'; import defineMessages from '@app/utils/defineMessages'; @@ -105,6 +106,7 @@ interface SonarrModalProps { const SonarrModal = ({ onClose, sonarr, onSave }: SonarrModalProps) => { const intl = useIntl(); + const setupConnection = useSetupConnectionSuggestion('sonarr'); const initialLoad = useRef(false); const { addToast } = useToasts(); const [isValidated, setIsValidated] = useState(sonarr ? true : false); @@ -246,8 +248,8 @@ const SonarrModal = ({ onClose, sonarr, onSave }: SonarrModalProps) => { Promise; + clearConnections: () => void; + suggestionFor: ( + appId: SetupConnectionAppId + ) => SetupConnectionSuggestion | undefined; +}; + +const SetupConnectionsContext = + createContext(null); + +export const SetupConnectionsProvider = ({ + children, +}: { + children: React.ReactNode; +}) => { + const [connections, setConnections] = useState( + [] + ); + const importFile = useCallback(async (file: File) => { + if (file.size > 256 * 1024) { + throw new Error('The setup file is larger than 256 KB.'); + } + const parsed = parseSetupConnections(await file.text()); + setConnections(parsed); + return parsed.length; + }, []); + const clearConnections = useCallback(() => setConnections([]), []); + const suggestionFor = useCallback( + (appId: SetupConnectionAppId) => + connections.find( + (connection) => + connection.id === appId && connection.state === 'running' + ) ?? connections.find((connection) => connection.id === appId), + [connections] + ); + const value = useMemo( + () => ({ connections, importFile, clearConnections, suggestionFor }), + [connections, importFile, clearConnections, suggestionFor] + ); + + return ( + + {children} + + ); +}; + +export const useSetupConnections = () => { + const context = useContext(SetupConnectionsContext); + if (!context) { + throw new Error( + 'Setup connection assistance must be used inside SetupConnectionsProvider.' + ); + } + return context; +}; + +export const useSetupConnectionSuggestion = (appId: SetupConnectionAppId) => + useSetupConnections().suggestionFor(appId); diff --git a/src/i18n/locale/en.json b/src/i18n/locale/en.json index 32ce8cc8a5..5dac8183e5 100644 --- a/src/i18n/locale/en.json +++ b/src/i18n/locale/en.json @@ -3024,6 +3024,11 @@ "components.Settings.SettingsUsers.userSettings": "User Settings", "components.Settings.SettingsUsers.userSettingsDescription": "Configure global and default user settings.", "components.Settings.SettingsUsers.users": "Users", + "components.Settings.SetupConnectionsImport.clear": "Clear imported suggestions", + "components.Settings.SetupConnectionsImport.help": "Choose the seerrng-connections.json file created by the setup assistant. Hostnames and ports will prefill matching service forms; API keys are never imported.", + "components.Settings.SetupConnectionsImport.import": "Import detected connections", + "components.Settings.SetupConnectionsImport.imported": "Loaded suggestions for {count, plural, one {# app} other {# apps}}. Matching add forms will use these hostnames and ports.", + "components.Settings.SetupConnectionsImport.invalidFile": "Unable to read this setup file.", "components.Settings.SonarrModal.add": "Add Server", "components.Settings.SonarrModal.animeSeriesType": "Anime Series Type", "components.Settings.SonarrModal.animeTags": "Anime Tags", @@ -3250,6 +3255,9 @@ "components.Settings.services": "Services", "components.Settings.settingUpPlexDescription": "To set up Plex, you can either enter the details manually or select a server retrieved from plex.tv. Press the button to the right of the dropdown to fetch the list of available servers.", "components.Settings.settings": "Settings", + "components.Settings.setupAssistantDescription": "Generate a Docker Compose starter or discover apps on a Docker network. Import the connection report to prefill hostnames and ports, then test each API connection before saving.", + "components.Settings.setupAssistantGuide": "Open the setup guide", + "components.Settings.setupAssistantTitle": "Connect your apps", "components.Settings.sonarrsettings": "Sonarr Settings", "components.Settings.ssl": "SSL", "components.Settings.startscan": "Start Scan", diff --git a/src/pages/_app.tsx b/src/pages/_app.tsx index fef8d07dba..68fd8d206e 100644 --- a/src/pages/_app.tsx +++ b/src/pages/_app.tsx @@ -6,6 +6,7 @@ import { InteractionProvider } from '@app/context/InteractionContext'; import { LanguageContext } from '@app/context/LanguageContext'; import { NativeRuntimeProvider } from '@app/context/NativeRuntimeContext'; import { SettingsProvider } from '@app/context/SettingsContext'; +import { SetupConnectionsProvider } from '@app/context/SetupConnectionsContext'; import { ThemeProvider } from '@app/context/ThemeContext'; import { UserContext } from '@app/context/UserContext'; import useSettings from '@app/hooks/useSettings'; @@ -208,7 +209,9 @@ const CoreApp = ({ Component, pageProps, router }: AppProps) => { - {component} + + {component} + { + it('keeps only supported connection fields and ignores credentials', () => { + const connections = parseSetupConnections( + JSON.stringify({ + network: 'media-net', + connections: [ + { + id: 'radarr', + hostname: 'radarr', + port: 7878, + state: 'running', + apiKey: 'must-not-be-imported', + }, + ], + }) + ); + + expect(connections).toEqual([ + { + id: 'radarr', + hostname: 'radarr', + port: 7878, + state: 'running', + }, + ]); + }); + + it('prefills duplicate providers with separate suggestions', () => { + const connections = parseSetupConnections( + JSON.stringify({ + connections: [ + { id: 'radarr', hostname: 'radarr-hd', port: 7878 }, + { id: 'radarr', hostname: 'radarr-4k', port: 7879 }, + ], + }) + ); + + expect(connections).toHaveLength(2); + expect(connections.map(({ hostname }) => hostname)).toEqual([ + 'radarr-hd', + 'radarr-4k', + ]); + }); + + it('rejects malformed, oversized, and unsupported reports', () => { + expect(() => parseSetupConnections('{')).toThrow(/valid.*JSON/i); + expect(() => parseSetupConnections(' '.repeat(256 * 1024 + 1))).toThrow( + /larger than 256 KB/ + ); + expect(() => + parseSetupConnections( + JSON.stringify({ + connections: [ + { + id: 'radarr', + hostname: 'radarr; rm -rf /', + port: 7878, + }, + ], + }) + ) + ).toThrow(/No supported app connection/); + expect(() => + parseSetupConnections( + JSON.stringify({ + connections: [ + { id: 'qbittorrent', hostname: 'qbittorrent', port: 8080 }, + ], + }) + ) + ).toThrow(/No supported app connection/); + }); +}); diff --git a/src/utils/setupConnections.ts b/src/utils/setupConnections.ts new file mode 100644 index 0000000000..b4a764aa5d --- /dev/null +++ b/src/utils/setupConnections.ts @@ -0,0 +1,101 @@ +export const setupConnectionAppIds = [ + 'seerrng', + 'radarr', + 'sonarr', + 'lidarr', + 'bookshelf', + 'chaptarrng', + 'prowlarr', + 'qbittorrent', + 'lazylibrarian', + 'mylar3', + 'kapowarr', + 'backissue', + 'romarrng', + 'questarrng', +] as const; + +export type SetupConnectionAppId = (typeof setupConnectionAppIds)[number]; + +const setupConnectionPrefillAppIds = [ + 'radarr', + 'sonarr', + 'lidarr', + 'bookshelf', + 'chaptarrng', + 'prowlarr', + 'lazylibrarian', + 'mylar3', + 'kapowarr', + 'backissue', + 'romarrng', + 'questarrng', +] as const satisfies readonly SetupConnectionAppId[]; + +export type SetupConnectionSuggestion = { + id: SetupConnectionAppId; + hostname: string; + port: number; + state?: string; +}; + +const appIdSet = new Set(setupConnectionPrefillAppIds); + +export const parseSetupConnections = ( + content: string +): SetupConnectionSuggestion[] => { + if (content.length > 256 * 1024) { + throw new Error('The setup file is larger than 256 KB.'); + } + + let document: unknown; + try { + document = JSON.parse(content); + } catch { + throw new Error('Choose a valid SeerrNG setup connections JSON file.'); + } + + if ( + !document || + typeof document !== 'object' || + !('connections' in document) || + !Array.isArray(document.connections) || + document.connections.length > 64 + ) { + throw new Error( + 'The setup file does not contain a valid connections list.' + ); + } + + const parsed: SetupConnectionSuggestion[] = []; + for (const candidate of document.connections) { + if (!candidate || typeof candidate !== 'object') continue; + const record = candidate as Record; + if ( + typeof record.id !== 'string' || + !appIdSet.has(record.id) || + typeof record.hostname !== 'string' || + !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,252}$/.test(record.hostname) || + !Number.isInteger(record.port) || + Number(record.port) < 1 || + Number(record.port) > 65535 + ) { + continue; + } + + parsed.push({ + id: record.id as SetupConnectionAppId, + hostname: record.hostname, + port: Number(record.port), + ...(typeof record.state === 'string' && /^[a-z]{1,24}$/.test(record.state) + ? { state: record.state } + : {}), + }); + } + + if (parsed.length === 0) { + throw new Error('No supported app connection suggestions were found.'); + } + + return parsed; +}; From 492d5a252e13cf17aaa03c88c6c6967c015f0e30 Mon Sep 17 00:00:00 2001 From: snapetech Date: Thu, 1 Oct 2026 18:35:49 -0600 Subject: [PATCH 02/58] feat: support native service setup assistance --- .../e2e/settings/prowlarr-responsive.cy.ts | 7 +- docs/using-seerr/setup-assistant.md | 64 +++++- ...0-01-add-cross-platform-setup-assistant.md | 2 +- scripts/setup-assistant.mjs | 191 +++++++++++++++--- scripts/setup-assistant.test.mjs | 114 +++++++++++ src/components/Settings/SettingsServices.tsx | 2 +- .../Settings/SetupConnectionsImport.tsx | 4 +- src/i18n/locale/en.json | 6 +- 8 files changed, 344 insertions(+), 46 deletions(-) diff --git a/cypress/e2e/settings/prowlarr-responsive.cy.ts b/cypress/e2e/settings/prowlarr-responsive.cy.ts index edad393be3..ef04ae27ca 100644 --- a/cypress/e2e/settings/prowlarr-responsive.cy.ts +++ b/cypress/e2e/settings/prowlarr-responsive.cy.ts @@ -138,10 +138,7 @@ describe('Prowlarr settings on a short mobile screen', () => { cy.contains('section.app-card-sub', 'Connect your apps') .should('be.visible') - .and( - 'contain', - 'Generate a Docker Compose starter or discover apps on a Docker network.' - ); + .and('contain', 'create a manual report for native and remote apps.'); cy.contains('a', 'Open the setup guide') .should('be.visible') .should( @@ -198,7 +195,7 @@ describe('Prowlarr settings on a short mobile screen', () => { }, ], }; - cy.get('input[aria-label="Import detected connections"]').selectFile( + cy.get('input[aria-label="Import connection report"]').selectFile( { contents: Cypress.Buffer.from(JSON.stringify(report)), fileName: 'seerrng-connections.json', diff --git a/docs/using-seerr/setup-assistant.md b/docs/using-seerr/setup-assistant.md index 8d192138ca..835d99d6f2 100644 --- a/docs/using-seerr/setup-assistant.md +++ b/docs/using-seerr/setup-assistant.md @@ -1,16 +1,15 @@ --- title: Cross-platform setup assistant -description: Create a starter Docker Compose stack and connect its apps to SeerrNG. +description: Set up Docker apps or connect native and remote services to SeerrNG. sidebar_position: 5 --- # Cross-platform setup assistant -The setup assistant creates a Docker Compose stack and a per-stack guide for -the media services you choose. It runs on Windows, macOS, and Linux with Node.js -24.15.0 or newer in the 24.x line and Docker Compose v2. Docker Desktop is -suitable on Windows and macOS; Docker Engine with the Compose plugin is -suitable on Linux. The assistant does not install or configure Docker itself. +The setup assistant runs on Windows, macOS, and Linux with Node.js 24.15.0 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. ## Run the assistant @@ -39,9 +38,8 @@ node scripts/setup-assistant.mjs Choose a starter profile, confirm the output directory, and optionally let the assistant start the stack after it writes the files. It writes files only; it -does not install apps, configure API keys, or start containers unless you -explicitly choose that option. To select a profile and output location -directly: +does not install apps or configure API keys. To select a profile and output +location directly: ```text node scripts/setup-assistant.mjs --profile movies-tv --output ./my-media-stack @@ -64,6 +62,48 @@ Docker networks or containers to guess which SeerrNG instance you mean. This mode requires SeerrNG to run in a Docker container on the same Docker host; native or remote SeerrNG installs need a separately reachable app address. +## Connect native or remote apps + +Use manual connection mode when SeerrNG or its companion apps are installed +from native archives, Linux packages, package managers, Unraid templates, or +other non-Compose methods. It does not call Docker or inspect operating-system +processes. It creates the same import file from an explicit hostname and the +selected apps’ common default ports; you can override ports interactively. + +```text +node scripts/setup-assistant.mjs --connections +``` + +Select app IDs from the menu, enter a hostname or IPv4 address that SeerrNG can +reach, and confirm each port. The assistant writes +`seerrng-connections.json` and `CONNECTIONS.md` into +`./seerrng-connections`. Enter values non-interactively with: + +```text +node scripts/setup-assistant.mjs --connections --apps radarr,sonarr,prowlarr --host media.example.net --output ./seerrng-connections --yes +``` + +The report supports SeerrNG integrations for Radarr, Sonarr, Lidarr, +BookshelfNG, ChaptarrNG, Prowlarr, LazyLibrarian, Mylar3, Kapowarr, BackIssue, +ROMarrNG, and QuestarrNG. qBittorrent has no SeerrNG service form, so it is not +included. BookshelfNG and ChaptarrNG require two SeerrNG entries, one for Books +and one for Audiobooks. + +`localhost` is relative to the machine or container where SeerrNG runs. Use it +only when SeerrNG and the target app share a network namespace. If SeerrNG runs +in Docker and the app runs directly on its host, use an address reachable from +inside the SeerrNG container. On Linux Docker Engine this may require a +host-gateway mapping or a routable host address. On Docker Desktop, verify +`host.docker.internal` resolves from inside the SeerrNG container. For apps on +another machine, use that machine’s LAN DNS name or IP. Ensure the app listens +on an interface reachable by SeerrNG and that the firewall permits its port. + +Manual reports work across SeerrNG’s supported Windows x64/ARM64, macOS +x64/ARM64, and Linux deployments, including Debian, RPM, AppImage, Flatpak, +Snap, PPA, COPR, and AUR packages. Companion apps may support fewer operating +systems or architectures; install them using their own supported method. The +connection workflow itself does not depend on how either service was installed. + Use `--detect --output ./my-media-stack` to report which containers Docker Compose currently sees in that generated stack. To discover supported apps already attached to a particular Docker network, name that network explicitly: @@ -89,6 +129,12 @@ enter each key in the corresponding app and use **Test** so SeerrNG validates the API and loads profiles, root folders, or provider capabilities. Imported suggestions stay in memory until you clear them or reload SeerrNG. +The report starts with each app’s common web port. Confirm custom ports, SSL, +and reverse-proxy paths in the target app. Enter API keys manually. **Test** is +the live API probe: it verifies that SeerrNG can reach the selected service +with the supplied credentials and loads its profiles, root folders, or +capabilities before saving. + After choosing a profile, enter app IDs to add or prefix an ID with `-` to remove it. For example, add `lidarr` to a Movies and TV profile or enter `-qbittorrent` to omit its download client. Available app IDs are `seerrng`, diff --git a/release-notes/2026-10-01-add-cross-platform-setup-assistant.md b/release-notes/2026-10-01-add-cross-platform-setup-assistant.md index f1c85ca598..95b4968274 100644 --- a/release-notes/2026-10-01-add-cross-platform-setup-assistant.md +++ b/release-notes/2026-10-01-add-cross-platform-setup-assistant.md @@ -5,4 +5,4 @@ area: setup-assistance action: none breaking: false --- -Operators can generate a cross-platform Docker Compose starter, discover supported apps on a selected Docker network, and import connection suggestions to prefill hostnames and ports. API keys stay in each app and are verified through SeerrNG before saving. +Operators can generate a Docker Compose starter, discover apps on a selected Docker network, or create connection reports for native and remote services on Windows, macOS, and Linux. Import reports to prefill hostnames and ports; API keys remain manual and SeerrNG tests each connection before saving. diff --git a/scripts/setup-assistant.mjs b/scripts/setup-assistant.mjs index 3d62396817..5ff545afed 100644 --- a/scripts/setup-assistant.mjs +++ b/scripts/setup-assistant.mjs @@ -161,6 +161,88 @@ export const apps = { }, }; +export const connectionAppIds = Object.keys(apps).filter( + (id) => !['seerrng', 'qbittorrent'].includes(id) +); + +const isSafeHostname = (value) => + typeof value === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,252}$/.test(value); + +export const buildManualConnections = ( + hostname, + appIds, + portOverrides = {} +) => { + if (!isSafeHostname(hostname)) { + throw new Error( + 'Host must be a DNS name or IPv4 address without a URL scheme or path.' + ); + } + if (!Array.isArray(appIds) || appIds.length === 0) { + throw new Error('Select at least one supported app to connect.'); + } + + const uniqueIds = [...new Set(appIds)]; + for (const id of uniqueIds) { + if (!connectionAppIds.includes(id)) { + throw new Error(`App "${id}" cannot be imported as a connection.`); + } + } + + return uniqueIds.map((id) => { + const rawPort = portOverrides[id] ?? apps[id].port; + const port = Number(rawPort); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error( + `Port for ${apps[id].title} must be between 1 and 65535.` + ); + } + return { + id, + title: apps[id].title, + hostname, + port, + state: 'manual', + }; + }); +}; + +export const renderManualConnections = (hostname, connections) => { + const lines = [ + '# SeerrNG connection suggestions', + '', + `These addresses were entered manually for ${hostname}. They work with native Windows, macOS, or Linux installs, package installs, and services hosted on another reachable machine.`, + '', + 'Import `seerrng-connections.json` in SeerrNG under **Settings → Services**. Enter each app’s API key in SeerrNG and use **Test** to verify the API and load its options before saving. No API keys are included in this report.', + '', + 'The port values start with each app’s common default. Change them if the app uses a custom port. Do not use `localhost` when SeerrNG runs in a container and the app runs on the host: `localhost` would point back into the SeerrNG container. Use a hostname or IP address reachable from SeerrNG instead.', + '', + ]; + if (connections.length === 0) { + lines.push('No apps were selected.'); + } else { + for (const connection of connections) { + lines.push( + `- **${connection.title}** — hostname \`${connection.hostname}\`, port \`${connection.port}\`` + ); + if (connection.id === 'bookshelf' || connection.id === 'chaptarrng') { + lines.push( + ' Add separate Book and Audiobook service entries using the same hostname, port, and API key.' + ); + } + if (connection.id === 'questarrng' || connection.id === 'romarrng') { + lines.push( + ' Configure this provider under **Settings → Services → Software Acquisition**.' + ); + } + if (connection.id === 'prowlarr') { + lines.push(' Configure this provider under **Settings → Prowlarr**.'); + } + } + } + return `${lines.join('\n')}\n`; +}; + export const profiles = { 'movies-tv': { title: 'Movies and TV', @@ -619,33 +701,87 @@ const discoverAndReport = async (networkName, outputDirectory) => { } } - if (outputDirectory) { - const resolvedDirectory = path.resolve(outputDirectory); - await mkdir(resolvedDirectory, { recursive: true }); - const jsonPath = path.join(resolvedDirectory, 'seerrng-connections.json'); - const guidePath = path.join(resolvedDirectory, 'CONNECTIONS.md'); - await writeFile( - jsonPath, - `${JSON.stringify({ network: networkName, connections }, null, 2)}\n`, - { flag: 'wx', mode: 0o600 } + if (outputDirectory) + await writeConnectionReport( + outputDirectory, + { network: networkName, connections }, + renderDiscoveredConnections(networkName, connections) ); - try { - await writeFile( - guidePath, - renderDiscoveredConnections(networkName, connections), - { - flag: 'wx', - mode: 0o600, - } +}; + +const writeConnectionReport = async (outputDirectory, document, guide) => { + const resolvedDirectory = path.resolve(outputDirectory); + await mkdir(resolvedDirectory, { recursive: true }); + const jsonPath = path.join(resolvedDirectory, 'seerrng-connections.json'); + const guidePath = path.join(resolvedDirectory, 'CONNECTIONS.md'); + await writeFile(jsonPath, `${JSON.stringify(document, null, 2)}\n`, { + flag: 'wx', + mode: 0o600, + }); + try { + await writeFile(guidePath, guide, { flag: 'wx', mode: 0o600 }); + } catch (error) { + await unlink(jsonPath).catch(() => {}); + throw error; + } + stdout.write( + `Wrote private connection suggestions to ${resolvedDirectory}.\n` + ); +}; + +const createManualConnections = async (args, optionValue, rl) => { + const nonInteractive = args.includes('--yes'); + let selectedIds = optionValue('--apps', '') + .split(',') + .map((value) => value.trim()) + .filter(Boolean); + if (!selectedIds.length) { + if (nonInteractive) throw new Error('--yes requires --apps.'); + stdout.write(`Apps: ${connectionAppIds.join(', ')}\n`); + selectedIds = (await rl.question('App IDs to connect (comma-separated): ')) + .split(',') + .map((value) => value.trim()) + .filter(Boolean); + } + + let hostname = optionValue('--host'); + if (!hostname) { + if (nonInteractive) throw new Error('--yes requires --host.'); + hostname = await rl.question( + 'Hostname or IPv4 address reachable from SeerrNG (use localhost only when both services share a network namespace): ' + ); + } + + const portOverrides = {}; + if (!nonInteractive) { + for (const id of [...new Set(selectedIds)]) { + if (!connectionAppIds.includes(id)) { + throw new Error(`Unknown or unsupported connection app "${id}".`); + } + const port = await rl.question( + `${apps[id].title} port [${apps[id].port}]: ` ); - } catch (error) { - await unlink(jsonPath).catch(() => {}); - throw error; + if (port.trim()) portOverrides[id] = port.trim(); } - stdout.write( - `Wrote private connection suggestions to ${resolvedDirectory}.\n` - ); } + const connections = buildManualConnections( + hostname.trim(), + selectedIds, + portOverrides + ); + const outputDirectory = optionValue('--output', './seerrng-connections'); + stdout.write( + `\nConnections for ${hostname}:\n${connections.map((entry) => ` ${entry.title}: ${entry.hostname}:${entry.port}`).join('\n')}\nOutput: ${path.resolve(outputDirectory)}\n` + ); + if (!nonInteractive) { + const confirm = await rl.question('Write the connection report? [Y/n] '); + if (/^(n|no)$/i.test(confirm.trim())) return; + } + await writeConnectionReport( + outputDirectory, + { source: 'manual', connections }, + renderManualConnections(hostname, connections) + ); }; const detectComposeApps = async (outputDirectory) => { @@ -679,7 +815,7 @@ const detectComposeApps = async (outputDirectory) => { const help = () => { stdout.write( - `SeerrNG setup assistant\n\nUsage: pnpm setup:assistant [options]\n\nOptions:\n --profile choose a media profile (see --list-profiles)\n --apps add app IDs or remove with - (comma-separated)\n --network join or discover apps on an explicitly named Docker network\n --output output folder (default: ./seerrng-stack)\n --yes create files without interactive prompts\n --start start the stack after creating files\n --detect report containers in an existing Compose stack\n --discover identify supported apps attached to --network\n --list-profiles print available profiles\n --help show this help\n\nUse --discover --network to write ready-to-use host and port suggestions. API keys stay in each app and are entered in SeerrNG.\nTo add apps to an existing SeerrNG, remove it with --apps -seerrng and set --network.\nWithout --profile, choose a profile from the interactive menu.\n` + `SeerrNG setup assistant\n\nUsage: pnpm setup:assistant [options]\n\nOptions:\n --profile choose a media profile (see --list-profiles)\n --apps add app IDs or remove with - (comma-separated)\n --network join or discover apps on an explicitly named Docker network\n --host target host for a non-Docker connection report\n --connections create a connection report without requiring Docker\n --output output folder (default: ./seerrng-stack)\n --yes create files without interactive prompts\n --start start the stack after creating files\n --detect report containers in an existing Compose stack\n --discover identify supported apps attached to --network\n --list-profiles print available profiles\n --help show this help\n\nUse --connections to create an importable report for apps installed on Windows, macOS, Linux, or another reachable host. It does not require Docker.\nUse --discover --network for Docker discovery. API keys stay in each app and are entered in SeerrNG.\nWithout --profile, choose a Docker starter profile from the interactive menu.\n` ); }; @@ -735,9 +871,14 @@ const run = async () => { return; } - let profileName = optionValue('--profile'); const rl = readline.createInterface({ input: stdin, output: stdout }); try { + if (args.includes('--connections')) { + await createManualConnections(args, optionValue, rl); + return; + } + + let profileName = optionValue('--profile'); if (!profileName) { stdout.write('Choose a starter profile:\n'); Object.entries(profiles).forEach(([key, profile], index) => { diff --git a/scripts/setup-assistant.test.mjs b/scripts/setup-assistant.test.mjs index 0b02b658dd..5f97956470 100644 --- a/scripts/setup-assistant.test.mjs +++ b/scripts/setup-assistant.test.mjs @@ -8,14 +8,57 @@ import test from 'node:test'; import { fileURLToPath } from 'node:url'; import { apps, + buildManualConnections, + connectionAppIds, discoverNetworkApps, parseComposeStatus, profiles, renderCompose, renderDiscoveredConnections, renderGuide, + renderManualConnections, } from './setup-assistant.mjs'; +test('manual connection suggestions cover native installs without Docker', () => { + const connections = buildManualConnections( + 'media.example.net', + ['radarr', 'sonarr', 'bookshelf', 'questarrng'], + { sonarr: 9999 } + ); + assert.deepEqual( + connections.map(({ id, hostname, port }) => ({ id, hostname, port })), + [ + { id: 'radarr', hostname: 'media.example.net', port: 7878 }, + { id: 'sonarr', hostname: 'media.example.net', port: 9999 }, + { id: 'bookshelf', hostname: 'media.example.net', port: 8787 }, + { id: 'questarrng', hostname: 'media.example.net', port: 5000 }, + ] + ); + assert.ok(connectionAppIds.includes('radarr')); + assert.ok(!connectionAppIds.includes('qbittorrent')); + assert.throws( + () => buildManualConnections('http://media.example.net', ['radarr']), + /DNS name or IPv4 address/ + ); + assert.throws( + () => buildManualConnections('localhost', ['radarr'], { radarr: 65536 }), + /between 1 and 65535/ + ); + assert.throws( + () => buildManualConnections('localhost', ['qbittorrent']), + /cannot be imported/ + ); + + const guide = renderManualConnections('media.example.net', connections); + assert.match(guide, /native Windows, macOS, or Linux installs/); + assert.match( + guide, + /Do not use `localhost` when SeerrNG runs in a container/ + ); + assert.match(guide, /separate Book and Audiobook service entries/); + assert.match(guide, /Software Acquisition/); +}); + test('every starter profile contains SeerrNG and known app definitions', () => { for (const [name, profile] of Object.entries(profiles)) { assert.ok(profile.apps.includes('seerrng'), `${name} includes SeerrNG`); @@ -336,3 +379,74 @@ test('interactive setup writes the selected profile and refuses to overwrite it' await rm(temporaryDirectory, { recursive: true, force: true }); } }); + +test('non-Docker connection report works unattended and refuses to overwrite files', async () => { + const temporaryDirectory = await mkdtemp( + path.join(tmpdir(), 'seerrng-connections-assistant-') + ); + const outputDirectory = path.join(temporaryDirectory, 'connections'); + const scriptPath = fileURLToPath( + new URL('./setup-assistant.mjs', import.meta.url) + ); + + try { + const result = spawnSync( + process.execPath, + [ + scriptPath, + '--connections', + '--apps', + 'radarr,sonarr', + '--host', + 'media.example.net', + '--output', + outputDirectory, + '--yes', + ], + { encoding: 'utf8' } + ); + assert.equal(result.status, 0, result.stderr); + const report = JSON.parse( + await readFile( + path.join(outputDirectory, 'seerrng-connections.json'), + 'utf8' + ) + ); + assert.deepEqual( + report.connections.map(({ id, hostname, port }) => ({ + id, + hostname, + port, + })), + [ + { id: 'radarr', hostname: 'media.example.net', port: 7878 }, + { id: 'sonarr', hostname: 'media.example.net', port: 8989 }, + ] + ); + const guide = await readFile( + path.join(outputDirectory, 'CONNECTIONS.md'), + 'utf8' + ); + assert.match(guide, /API keys are included/); + assert.match(guide, /Do not use `localhost`/); + + const secondRun = spawnSync( + process.execPath, + [ + scriptPath, + '--connections', + '--apps', + 'radarr', + '--host', + 'media.example.net', + '--output', + outputDirectory, + '--yes', + ], + { encoding: 'utf8' } + ); + assert.equal(secondRun.status, 1); + } finally { + await rm(temporaryDirectory, { recursive: true, force: true }); + } +}); diff --git a/src/components/Settings/SettingsServices.tsx b/src/components/Settings/SettingsServices.tsx index ef3c5b68f0..0405cf1586 100644 --- a/src/components/Settings/SettingsServices.tsx +++ b/src/components/Settings/SettingsServices.tsx @@ -72,7 +72,7 @@ const messages = defineMessages('components.Settings', { services: 'Services', setupAssistantTitle: 'Connect your apps', setupAssistantDescription: - 'Generate a Docker Compose starter or discover apps on a Docker network. Import the connection report to prefill hostnames and ports, then test each API connection before saving.', + 'Generate a Docker Compose starter, discover apps on a Docker network, or create a manual report for native and remote apps. Import connection suggestions to prefill hostnames and ports, then test each API connection before saving.', setupAssistantGuide: 'Open the setup guide', radarrsettings: 'Radarr Settings', sonarrsettings: 'Sonarr Settings', diff --git a/src/components/Settings/SetupConnectionsImport.tsx b/src/components/Settings/SetupConnectionsImport.tsx index ababe423f0..465ddc1b01 100644 --- a/src/components/Settings/SetupConnectionsImport.tsx +++ b/src/components/Settings/SetupConnectionsImport.tsx @@ -5,8 +5,8 @@ import { useRef, useState } from 'react'; import { useIntl } from 'react-intl'; const messages = defineMessages('components.Settings.SetupConnectionsImport', { - import: 'Import detected connections', - help: 'Choose the seerrng-connections.json file created by the setup assistant. Hostnames and ports will prefill matching service forms; API keys are never imported.', + import: 'Import connection report', + help: 'Choose a seerrng-connections.json file from Docker discovery or manual setup. Hostnames and ports will prefill matching service forms; API keys are never imported.', imported: 'Loaded suggestions for {count, plural, one {# app} other {# apps}}. Matching add forms will use these hostnames and ports.', clear: 'Clear imported suggestions', diff --git a/src/i18n/locale/en.json b/src/i18n/locale/en.json index 5dac8183e5..d6f966e8ef 100644 --- a/src/i18n/locale/en.json +++ b/src/i18n/locale/en.json @@ -3025,8 +3025,8 @@ "components.Settings.SettingsUsers.userSettingsDescription": "Configure global and default user settings.", "components.Settings.SettingsUsers.users": "Users", "components.Settings.SetupConnectionsImport.clear": "Clear imported suggestions", - "components.Settings.SetupConnectionsImport.help": "Choose the seerrng-connections.json file created by the setup assistant. Hostnames and ports will prefill matching service forms; API keys are never imported.", - "components.Settings.SetupConnectionsImport.import": "Import detected connections", + "components.Settings.SetupConnectionsImport.help": "Choose a seerrng-connections.json file from Docker discovery or manual setup. Hostnames and ports will prefill matching service forms; API keys are never imported.", + "components.Settings.SetupConnectionsImport.import": "Import connection report", "components.Settings.SetupConnectionsImport.imported": "Loaded suggestions for {count, plural, one {# app} other {# apps}}. Matching add forms will use these hostnames and ports.", "components.Settings.SetupConnectionsImport.invalidFile": "Unable to read this setup file.", "components.Settings.SonarrModal.add": "Add Server", @@ -3255,7 +3255,7 @@ "components.Settings.services": "Services", "components.Settings.settingUpPlexDescription": "To set up Plex, you can either enter the details manually or select a server retrieved from plex.tv. Press the button to the right of the dropdown to fetch the list of available servers.", "components.Settings.settings": "Settings", - "components.Settings.setupAssistantDescription": "Generate a Docker Compose starter or discover apps on a Docker network. Import the connection report to prefill hostnames and ports, then test each API connection before saving.", + "components.Settings.setupAssistantDescription": "Generate a Docker Compose starter, discover apps on a Docker network, or create a manual report for native and remote apps. Import connection suggestions to prefill hostnames and ports, then test each API connection before saving.", "components.Settings.setupAssistantGuide": "Open the setup guide", "components.Settings.setupAssistantTitle": "Connect your apps", "components.Settings.sonarrsettings": "Sonarr Settings", From 335abc75b9417dfa063f533df95a099ed1d5935a Mon Sep 17 00:00:00 2001 From: snapetech Date: Thu, 1 Oct 2026 19:04:04 -0600 Subject: [PATCH 03/58] feat: probe native app ports --- .../e2e/settings/prowlarr-responsive.cy.ts | 2 +- docs/using-seerr/setup-assistant.md | 15 ++ ...0-01-add-cross-platform-setup-assistant.md | 2 +- scripts/setup-assistant.mjs | 157 +++++++++++++++++- scripts/setup-assistant.test.mjs | 67 ++++++++ src/components/Settings/SettingsServices.tsx | 2 +- src/i18n/locale/en.json | 2 +- 7 files changed, 242 insertions(+), 5 deletions(-) diff --git a/cypress/e2e/settings/prowlarr-responsive.cy.ts b/cypress/e2e/settings/prowlarr-responsive.cy.ts index ef04ae27ca..26de7157e3 100644 --- a/cypress/e2e/settings/prowlarr-responsive.cy.ts +++ b/cypress/e2e/settings/prowlarr-responsive.cy.ts @@ -138,7 +138,7 @@ describe('Prowlarr settings on a short mobile screen', () => { cy.contains('section.app-card-sub', 'Connect your apps') .should('be.visible') - .and('contain', 'create a manual report for native and remote apps.'); + .and('contain', 'probe common ports on a selected host'); cy.contains('a', 'Open the setup guide') .should('be.visible') .should( diff --git a/docs/using-seerr/setup-assistant.md b/docs/using-seerr/setup-assistant.md index 835d99d6f2..b7486e0593 100644 --- a/docs/using-seerr/setup-assistant.md +++ b/docs/using-seerr/setup-assistant.md @@ -104,6 +104,21 @@ Snap, PPA, COPR, and AUR packages. Companion apps may support fewer operating systems or architectures; install them using their own supported method. The connection workflow itself does not depend on how either service was installed. +For a quick reachability check, probe common app ports on one host: + +```text +node scripts/setup-assistant.mjs --probe-host media.example.net --output ./seerrng-connections +``` + +The probe makes TCP connection attempts only to the selected host and the +catalog’s distinct default ports, with at most four attempts at a time. It does +not send HTTP requests, inspect processes, scan a subnet, or use credentials. +An open port is not proof of app identity; unique default-port matches become +suggestions for SeerrNG’s **Test** action. Ports shared by multiple apps are +reported as ambiguous and omitted from the import file. The probe cannot find +custom ports; use manual mode to enter them. You can restrict the probe to +selected app IDs with `--apps radarr,sonarr`. + Use `--detect --output ./my-media-stack` to report which containers Docker Compose currently sees in that generated stack. To discover supported apps already attached to a particular Docker network, name that network explicitly: diff --git a/release-notes/2026-10-01-add-cross-platform-setup-assistant.md b/release-notes/2026-10-01-add-cross-platform-setup-assistant.md index 95b4968274..064ea447d3 100644 --- a/release-notes/2026-10-01-add-cross-platform-setup-assistant.md +++ b/release-notes/2026-10-01-add-cross-platform-setup-assistant.md @@ -5,4 +5,4 @@ area: setup-assistance action: none breaking: false --- -Operators can generate a Docker Compose starter, discover apps on a selected Docker network, or create connection reports for native and remote services on Windows, macOS, and Linux. Import reports to prefill hostnames and ports; API keys remain manual and SeerrNG tests each connection before saving. +Operators can generate a Docker Compose starter, discover apps on a selected Docker network, probe common ports on a chosen host, or create manual reports for native and remote services. Import suggestions to prefill hostnames and ports; SeerrNG tests each connection before saving, and API keys stay manual. diff --git a/scripts/setup-assistant.mjs b/scripts/setup-assistant.mjs index 5ff545afed..9e08d56128 100644 --- a/scripts/setup-assistant.mjs +++ b/scripts/setup-assistant.mjs @@ -2,6 +2,7 @@ import { spawnSync } from 'node:child_process'; import { access, mkdir, unlink, writeFile } from 'node:fs/promises'; +import { createConnection } from 'node:net'; import path from 'node:path'; import { stderr, stdin, stdout } from 'node:process'; import readline from 'node:readline/promises'; @@ -243,6 +244,108 @@ export const renderManualConnections = (hostname, connections) => { return `${lines.join('\n')}\n`; }; +const probeTcpPort = (hostname, port, timeoutMs = 900) => + new Promise((resolve) => { + const socket = createConnection({ host: hostname, port }); + let settled = false; + const timer = setTimeout(() => finish(false), timeoutMs); + const finish = (reachable) => { + if (settled) return; + settled = true; + clearTimeout(timer); + socket.destroy(); + resolve(reachable); + }; + socket.setTimeout(timeoutMs, () => finish(false)); + socket.once('connect', () => finish(true)); + socket.once('error', () => finish(false)); + }); + +export const probeKnownAppPorts = async ( + hostname, + requestedAppIds = connectionAppIds, + connect = probeTcpPort +) => { + if (!isSafeHostname(hostname)) { + throw new Error( + 'Host must be a DNS name or IPv4 address without a URL scheme or path.' + ); + } + const selectedIds = [...new Set(requestedAppIds)]; + if (selectedIds.length === 0) { + throw new Error('Select at least one supported app to probe.'); + } + for (const id of selectedIds) { + if (!connectionAppIds.includes(id)) { + throw new Error(`App "${id}" cannot be probed as a SeerrNG connection.`); + } + } + + const candidatesByPort = new Map(); + for (const id of selectedIds) { + const port = Number(apps[id].port); + candidatesByPort.set(port, [...(candidatesByPort.get(port) ?? []), id]); + } + const ports = [...candidatesByPort.keys()]; + const results = Array(ports.length); + let nextIndex = 0; + const worker = async () => { + while (nextIndex < ports.length) { + const index = nextIndex++; + const port = ports[index]; + let reachable = false; + try { + reachable = await connect(hostname, port, 900); + } catch { + reachable = false; + } + results[index] = { + port, + candidates: candidatesByPort.get(port), + reachable: reachable === true, + }; + } + }; + await Promise.all( + Array.from({ length: Math.min(4, ports.length) }, () => worker()) + ); + + const openPorts = results.filter((result) => result.reachable); + const connections = openPorts.flatMap((result) => + result.candidates.length === 1 + ? buildManualConnections(hostname, result.candidates).map((connection) => + Object.assign(connection, { state: 'reachable' }) + ) + : [] + ); + return { openPorts, connections }; +}; + +export const renderProbedConnections = (hostname, openPorts, connections) => { + const lines = [ + '# Probed SeerrNG service ports', + '', + `The setup assistant attempted TCP connections to common app ports on the explicitly selected host \`${hostname}\`. A reachable port does not prove which app is listening; confirm each suggestion with SeerrNG’s **Test** action. No HTTP requests, API keys, or service settings were read.`, + '', + ]; + if (openPorts.length === 0) { + lines.push('No common service ports accepted a TCP connection.'); + } else { + for (const result of openPorts) { + const labels = result.candidates.map((id) => apps[id].title).join(' / '); + lines.push( + `- Port \`${result.port}\` is reachable; common default candidate${result.candidates.length > 1 ? 's' : ''}: ${labels}${result.candidates.length === 1 ? ' (added as a suggestion)' : ' (ambiguous; enter the app and port manually)'}.` + ); + } + } + lines.push( + '', + 'Only ports with one selected app using that default are included in the import file. Open ports can belong to unrelated software, and custom ports are not scanned. Use manual connection mode for custom ports or ambiguous matches.', + '' + ); + return `${lines.join('\n')}\n`; +}; + export const profiles = { 'movies-tv': { title: 'Movies and TV', @@ -784,6 +887,36 @@ const createManualConnections = async (args, optionValue, rl) => { ); }; +const probeHostAndReport = async (hostname, appIds, outputDirectory) => { + const { openPorts, connections } = await probeKnownAppPorts(hostname, appIds); + if (openPorts.length === 0) { + stdout.write( + `No common SeerrNG app ports accepted a TCP connection on ${hostname}. Use --connections to enter custom ports.\n` + ); + return; + } + stdout.write(`Reachable common app ports on ${hostname}:\n`); + for (const result of openPorts) { + const labels = result.candidates.map((id) => apps[id].title).join(' / '); + stdout.write( + ` ${result.port}: ${labels}${result.candidates.length > 1 ? ' (ambiguous)' : ''}\n` + ); + } + if (connections.length === 0) { + stdout.write( + 'No unambiguous suggestions to import. Use --connections to select the app and enter its port.\n' + ); + return; + } + if (outputDirectory) { + await writeConnectionReport( + outputDirectory, + { source: 'tcp-probe', connections }, + renderProbedConnections(hostname, openPorts, connections) + ); + } +}; + const detectComposeApps = async (outputDirectory) => { await access(path.join(outputDirectory, 'compose.yaml')); const result = spawnSync('docker', ['compose', 'ps', '--format', 'json'], { @@ -815,7 +948,7 @@ const detectComposeApps = async (outputDirectory) => { const help = () => { stdout.write( - `SeerrNG setup assistant\n\nUsage: pnpm setup:assistant [options]\n\nOptions:\n --profile choose a media profile (see --list-profiles)\n --apps add app IDs or remove with - (comma-separated)\n --network join or discover apps on an explicitly named Docker network\n --host target host for a non-Docker connection report\n --connections create a connection report without requiring Docker\n --output output folder (default: ./seerrng-stack)\n --yes create files without interactive prompts\n --start start the stack after creating files\n --detect report containers in an existing Compose stack\n --discover identify supported apps attached to --network\n --list-profiles print available profiles\n --help show this help\n\nUse --connections to create an importable report for apps installed on Windows, macOS, Linux, or another reachable host. It does not require Docker.\nUse --discover --network for Docker discovery. API keys stay in each app and are entered in SeerrNG.\nWithout --profile, choose a Docker starter profile from the interactive menu.\n` + `SeerrNG setup assistant\n\nUsage: pnpm setup:assistant [options]\n\nOptions:\n --profile choose a media profile (see --list-profiles)\n --apps add app IDs or remove with - (comma-separated)\n --network join or discover apps on an explicitly named Docker network\n --host target host for a manual connection report\n --connections create a manual report without requiring Docker\n --probe-host probe common app ports on one explicitly named host\n --output output folder (default: ./seerrng-stack)\n --yes create files without interactive prompts\n --start start the stack after creating files\n --detect report containers in an existing Compose stack\n --discover identify supported apps attached to --network\n --list-profiles print available profiles\n --help show this help\n\nUse --connections to create an importable report for apps installed on Windows, macOS, Linux, or another reachable host. It does not require Docker.\nUse --probe-host to check only the common default ports on one explicitly named host. TCP reachability is a suggestion, not app identification; API keys are never requested.\nUse --discover --network for Docker discovery. API keys stay in each app and are entered in SeerrNG.\nWithout --profile, choose a Docker starter profile from the interactive menu.\n` ); }; @@ -871,6 +1004,28 @@ const run = async () => { return; } + if (args.includes('--probe-host')) { + try { + const hostname = optionValue('--probe-host'); + if (!hostname) throw new Error('--probe-host requires a hostname.'); + const requestedApps = optionValue('--apps', '') + .split(',') + .map((value) => value.trim()) + .filter(Boolean); + await probeHostAndReport( + hostname, + requestedApps.length ? requestedApps : connectionAppIds, + optionValue('--output', './seerrng-connections') + ); + } catch (error) { + stderr.write( + `${error instanceof Error ? error.message : String(error)}\n` + ); + process.exitCode = 1; + } + return; + } + const rl = readline.createInterface({ input: stdin, output: stdout }); try { if (args.includes('--connections')) { diff --git a/scripts/setup-assistant.test.mjs b/scripts/setup-assistant.test.mjs index 5f97956470..945b457996 100644 --- a/scripts/setup-assistant.test.mjs +++ b/scripts/setup-assistant.test.mjs @@ -12,11 +12,13 @@ import { connectionAppIds, discoverNetworkApps, parseComposeStatus, + probeKnownAppPorts, profiles, renderCompose, renderDiscoveredConnections, renderGuide, renderManualConnections, + renderProbedConnections, } from './setup-assistant.mjs'; test('manual connection suggestions cover native installs without Docker', () => { @@ -59,6 +61,71 @@ test('manual connection suggestions cover native installs without Docker', () => assert.match(guide, /Software Acquisition/); }); +test('host probes stay on one host, use bounded known ports, and omit ambiguous app matches', async () => { + const calls = []; + let active = 0; + let maxActive = 0; + const result = await probeKnownAppPorts( + 'media.example.net', + ['radarr', 'sonarr', 'bookshelf', 'backissue'], + async (hostname, port, timeout) => { + calls.push({ hostname, port, timeout }); + active += 1; + maxActive = Math.max(maxActive, active); + await new Promise((resolve) => setTimeout(resolve, 1)); + active -= 1; + return port === 7878 || port === 8787; + } + ); + + assert.equal(calls.length, 3); + assert.ok(maxActive <= 4); + assert.ok(calls.every((call) => call.hostname === 'media.example.net')); + assert.ok(calls.every((call) => call.timeout === 900)); + assert.deepEqual(result.openPorts, [ + { port: 7878, candidates: ['radarr'], reachable: true }, + { + port: 8787, + candidates: ['bookshelf', 'backissue'], + reachable: true, + }, + ]); + assert.deepEqual( + result.connections.map(({ id }) => id), + ['radarr'] + ); + + const guide = renderProbedConnections( + 'media.example.net', + result.openPorts, + result.connections + ); + assert.match(guide, /does not prove which app is listening/); + assert.match(guide, /8787.*ambiguous/); + assert.match( + guide, + /No HTTP requests, API keys, or service settings were read/ + ); +}); + +test('host probes reject unsafe hosts and support an explicitly selected ambiguous app', async () => { + let calls = 0; + const connect = async () => { + calls += 1; + return true; + }; + await assert.rejects( + probeKnownAppPorts('http://localhost', ['radarr'], connect), + /DNS name or IPv4 address/ + ); + assert.equal(calls, 0); + + const result = await probeKnownAppPorts('localhost', ['backissue'], connect); + assert.equal(result.openPorts[0].port, 8787); + assert.equal(result.openPorts[0].candidates.length, 1); + assert.equal(result.connections[0].id, 'backissue'); +}); + test('every starter profile contains SeerrNG and known app definitions', () => { for (const [name, profile] of Object.entries(profiles)) { assert.ok(profile.apps.includes('seerrng'), `${name} includes SeerrNG`); diff --git a/src/components/Settings/SettingsServices.tsx b/src/components/Settings/SettingsServices.tsx index 0405cf1586..110b5c1e89 100644 --- a/src/components/Settings/SettingsServices.tsx +++ b/src/components/Settings/SettingsServices.tsx @@ -72,7 +72,7 @@ const messages = defineMessages('components.Settings', { services: 'Services', setupAssistantTitle: 'Connect your apps', setupAssistantDescription: - 'Generate a Docker Compose starter, discover apps on a Docker network, or create a manual report for native and remote apps. Import connection suggestions to prefill hostnames and ports, then test each API connection before saving.', + 'Generate a Docker Compose starter, discover apps on a Docker network, probe common ports on a selected host, or create a manual report. Import suggestions to prefill hostnames and ports, then test each API connection before saving.', setupAssistantGuide: 'Open the setup guide', radarrsettings: 'Radarr Settings', sonarrsettings: 'Sonarr Settings', diff --git a/src/i18n/locale/en.json b/src/i18n/locale/en.json index d6f966e8ef..01970a45b6 100644 --- a/src/i18n/locale/en.json +++ b/src/i18n/locale/en.json @@ -3255,7 +3255,7 @@ "components.Settings.services": "Services", "components.Settings.settingUpPlexDescription": "To set up Plex, you can either enter the details manually or select a server retrieved from plex.tv. Press the button to the right of the dropdown to fetch the list of available servers.", "components.Settings.settings": "Settings", - "components.Settings.setupAssistantDescription": "Generate a Docker Compose starter, discover apps on a Docker network, or create a manual report for native and remote apps. Import connection suggestions to prefill hostnames and ports, then test each API connection before saving.", + "components.Settings.setupAssistantDescription": "Generate a Docker Compose starter, discover apps on a Docker network, probe common ports on a selected host, or create a manual report. Import suggestions to prefill hostnames and ports, then test each API connection before saving.", "components.Settings.setupAssistantGuide": "Open the setup guide", "components.Settings.setupAssistantTitle": "Connect your apps", "components.Settings.sonarrsettings": "Sonarr Settings", From a5ce1cebcf31b17abd68bdba05ac914c74bc1bd1 Mon Sep 17 00:00:00 2001 From: snapetech Date: Sun, 4 Oct 2026 10:34:50 -0600 Subject: [PATCH 04/58] feat(requests): add per-user external list syncing Fixes #159. AI-assisted with OpenAI Codex. --- .../2026-10-04-per-user-request-lists.md | 9 + seerr-api.yml | 123 +++++ server/entity/ExternalRequestList.ts | 43 ++ server/job/schedule.ts | 22 + server/lib/externalRequestLists.test.ts | 245 ++++++++++ server/lib/externalRequestLists.ts | 446 ++++++++++++++++++ server/lib/settings/index.ts | 7 + ...add_external_request_list_sync_job.test.ts | 28 ++ ...0021_add_external_request_list_sync_job.ts | 26 + ...791010000000-CreateExternalRequestLists.ts | 32 ++ ...0000000-CreateExternalRequestLists.test.ts | 36 ++ ...791010000000-CreateExternalRequestLists.ts | 31 ++ server/routes/externalRequestLists.test.ts | 123 +++++ server/routes/externalRequestLists.ts | 159 +++++++ server/routes/index.ts | 2 + .../ExternalRequestLists.tsx | 231 +++++++++ .../UserGeneralSettings/index.tsx | 2 + src/i18n/locale/en.json | 17 + 18 files changed, 1582 insertions(+) create mode 100644 release-notes/2026-10-04-per-user-request-lists.md create mode 100644 server/entity/ExternalRequestList.ts create mode 100644 server/lib/externalRequestLists.test.ts create mode 100644 server/lib/externalRequestLists.ts create mode 100644 server/lib/settings/migrations/0021_add_external_request_list_sync_job.test.ts create mode 100644 server/lib/settings/migrations/0021_add_external_request_list_sync_job.ts create mode 100644 server/migration/postgres/1791010000000-CreateExternalRequestLists.ts create mode 100644 server/migration/sqlite/1791010000000-CreateExternalRequestLists.test.ts create mode 100644 server/migration/sqlite/1791010000000-CreateExternalRequestLists.ts create mode 100644 server/routes/externalRequestLists.test.ts create mode 100644 server/routes/externalRequestLists.ts create mode 100644 src/components/UserProfile/UserSettings/UserGeneralSettings/ExternalRequestLists.tsx diff --git a/release-notes/2026-10-04-per-user-request-lists.md b/release-notes/2026-10-04-per-user-request-lists.md new file mode 100644 index 0000000000..d5137da643 --- /dev/null +++ b/release-notes/2026-10-04-per-user-request-lists.md @@ -0,0 +1,9 @@ +--- +category: added +audience: users, operators +area: requests +action: none +breaking: false +--- + +Connect a public IMDb watchlist or Goodreads to-read shelf to your account. New titles are checked daily and enter your normal request flow, honoring your permissions, quotas, and approval settings. diff --git a/seerr-api.yml b/seerr-api.yml index 602fddc6bb..5eb72ca005 100644 --- a/seerr-api.yml +++ b/seerr-api.yml @@ -58,6 +58,57 @@ servers: components: schemas: + ExternalRequestList: + type: object + required: [id, provider, sourceUrl] + properties: + id: + type: integer + provider: + type: string + enum: [imdb, goodreads] + sourceUrl: + type: string + format: uri + lastSyncedAt: + type: string + format: date-time + nullable: true + lastSyncError: + type: string + nullable: true + ExternalRequestListSyncResult: + type: object + required: + - listId + - provider + - sourceItems + - requested + - alreadyRequested + - unmatched + - failed + - lastSyncedAt + properties: + listId: + type: integer + provider: + type: string + enum: [imdb, goodreads] + sourceItems: + type: integer + requested: + type: integer + alreadyRequested: + type: integer + unmatched: + type: integer + failed: + type: integer + lastSyncedAt: + type: string + format: date-time + error: + type: string SoftwareProviderSettingsInput: type: object properties: @@ -13272,6 +13323,78 @@ paths: application/json: schema: $ref: '#/components/schemas/LazyLibrarianSettings' + /request/lists: + get: + summary: Get the signed-in user's external request lists + tags: + - request + responses: + '200': + description: External request lists returned + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ExternalRequestList' + post: + summary: Add a public IMDb or Goodreads list for recurring requests + tags: + - request + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [url] + additionalProperties: false + properties: + url: + type: string + maxLength: 2048 + example: https://www.imdb.com/user/ur12345678/watchlist/ + responses: + '201': + description: External request list saved + content: + application/json: + schema: + $ref: '#/components/schemas/ExternalRequestList' + /request/lists/{listId}/sync: + post: + summary: Sync a configured public list now + tags: + - request + parameters: + - in: path + name: listId + required: true + schema: + type: integer + minimum: 1 + responses: + '200': + description: List synchronization results + content: + application/json: + schema: + $ref: '#/components/schemas/ExternalRequestListSyncResult' + /request/lists/{listId}: + delete: + summary: Remove a configured external request list + tags: + - request + parameters: + - in: path + name: listId + required: true + schema: + type: integer + minimum: 1 + responses: + '204': + description: External request list removed /request: get: summary: Get all requests diff --git a/server/entity/ExternalRequestList.ts b/server/entity/ExternalRequestList.ts new file mode 100644 index 0000000000..c2b701ee7b --- /dev/null +++ b/server/entity/ExternalRequestList.ts @@ -0,0 +1,43 @@ +import { DbAwareColumn } from '@server/utils/DbColumnHelper'; +import { + Column, + Entity, + Index, + ManyToOne, + PrimaryGeneratedColumn, +} from 'typeorm'; +import { User } from './User'; + +@Entity('external_request_list') +@Index('IDX_external_request_list_user_source', ['user', 'sourceId'], { + unique: true, +}) +export class ExternalRequestList { + public constructor(init?: Partial) { + Object.assign(this, init); + } + + @PrimaryGeneratedColumn() + public id: number; + + @ManyToOne(() => User, { onDelete: 'CASCADE' }) + public user: User; + + @Column({ type: 'varchar', length: 16 }) + public provider: 'imdb' | 'goodreads'; + + @Column({ type: 'varchar', length: 64 }) + public sourceId: string; + + @Column({ type: 'varchar', length: 2048 }) + public sourceUrl: string; + + @Column({ type: 'simple-json', nullable: true }) + public processedItemIds?: string[]; + + @DbAwareColumn({ type: 'datetime', nullable: true }) + public lastSyncedAt?: Date | null; + + @Column({ type: 'text', nullable: true }) + public lastSyncError?: string | null; +} diff --git a/server/job/schedule.ts b/server/job/schedule.ts index 541578b269..83d07c36d0 100644 --- a/server/job/schedule.ts +++ b/server/job/schedule.ts @@ -6,6 +6,7 @@ import { syncManagedCollections } from '@server/lib/collectionSync'; import downloadRecovery from '@server/lib/downloadRecovery'; import downloadTracker from '@server/lib/downloadtracker'; import episodeWatchAhead from '@server/lib/episodeWatchAhead'; +import { syncAllExternalRequestLists } from '@server/lib/externalRequestLists'; import ImageProxy from '@server/lib/imageproxy'; import refreshToken from '@server/lib/refreshToken'; import { captureReleaseCalendarHistory } from '@server/lib/releaseCalendar/history'; @@ -179,6 +180,27 @@ export const startJobs = (): void => { const jobs = getSettings().jobs; const mediaServerType = getSettings().main.mediaServerType; + scheduledJobs.push({ + id: 'external-request-list-sync', + name: 'External Request List Sync', + type: 'process', + interval: 'days', + cronSchedule: jobs['external-request-list-sync'].schedule, + job: schedule.scheduleJob( + jobs['external-request-list-sync'].schedule, + () => { + logger.info('Starting scheduled job: External Request List Sync', { + label: 'Jobs', + }); + return runTrackedJob( + 'External Request List Sync', + syncAllExternalRequestLists, + { logCompletion: true } + ); + } + ), + }); + if (mediaServerType === MediaServerType.PLEX) { // Run recently added plex scan every 5 minutes scheduledJobs.push({ diff --git a/server/lib/externalRequestLists.test.ts b/server/lib/externalRequestLists.test.ts new file mode 100644 index 0000000000..36b9d17f49 --- /dev/null +++ b/server/lib/externalRequestLists.test.ts @@ -0,0 +1,245 @@ +import assert from 'node:assert/strict'; +import { afterEach, describe, it, mock } from 'node:test'; + +import OpenLibraryAPI from '@server/api/openlibrary'; +import TheMovieDb from '@server/api/themoviedb'; +import { MediaType } from '@server/constants/media'; +import { getRepository } from '@server/datasource'; +import { ExternalRequestList } from '@server/entity/ExternalRequestList'; +import { + DuplicateMediaRequestError, + MediaRequest, +} from '@server/entity/MediaRequest'; +import { User } from '@server/entity/User'; +import { + parseExternalRequestListUrl, + parseGoodreadsToReadFeed, + parseImdbWatchlistHtml, + resolveGoodreadsItem, + resolveImdbItem, + syncExternalRequestList, + type ExternalRequestListSyncAdapters, +} from '@server/lib/externalRequestLists'; +import { setupTestDb } from '@server/test/db'; + +describe('external request list synchronization', () => { + setupTestDb(); + + afterEach(() => { + mock.restoreAll(); + }); + + it('accepts only supported public IMDb and Goodreads source URLs', () => { + assert.deepEqual( + parseExternalRequestListUrl( + 'https://www.imdb.com/user/ur12345678/watchlist/' + ), + { + provider: 'imdb', + sourceId: 'ur12345678', + sourceUrl: 'https://www.imdb.com/user/ur12345678/watchlist/', + } + ); + assert.deepEqual( + parseExternalRequestListUrl( + 'https://www.goodreads.com/user/show/1234567-example' + ), + { + provider: 'goodreads', + sourceId: 'goodreads:1234567:to-read', + sourceUrl: + 'https://www.goodreads.com/review/list_rss/1234567?shelf=to-read', + } + ); + for (const url of [ + 'http://www.imdb.com/user/ur12345678/watchlist/', + 'https://imdb.com.evil.example/user/ur12345678/watchlist/', + 'https://www.imdb.com/user/ur12345678/watchlist/?next=http://127.0.0.1', + 'https://www.goodreads.com/review/list_rss/1234567?shelf=read', + 'https://www.goodreads.com/review/list_rss/1234567?url=http://127.0.0.1', + ]) { + assert.equal(parseExternalRequestListUrl(url), undefined, url); + } + }); + + it('parses IMDb and Goodreads source data into bounded request identities', async () => { + assert.deepEqual( + parseImdbWatchlistHtml( + 'FilmFilm' + ), + [{ id: 'tt1234567' }] + ); + assert.deepEqual( + await parseGoodreadsToReadFeed(` + + 123456 + Example Book + Example Author + 9780441478125 + + `), + [ + { + id: '123456', + title: 'Example Book', + author: 'Example Author', + isbn13: '9780441478125', + }, + ] + ); + }); + + it('resolves Goodreads ISBNs to a requestable Open Library work', async () => { + const lookup = mock.method( + OpenLibraryAPI.prototype, + 'searchBooks', + async () => + ({ + numFound: 1, + start: 0, + docs: [ + { + key: '/works/OL27448W', + title: 'Example Book', + isbn: ['9780441478125'], + author_name: ['Example Author'], + }, + ], + }) as Awaited> + ); + + const result = await resolveGoodreadsItem({ + id: '123456', + title: 'Example Book', + author: 'Example Author', + isbn13: '9780441478125', + }); + + assert.deepEqual(result?.request, { + mediaType: MediaType.BOOK, + mediaId: 'OL27448W', + isbn13: '9780441478125', + format: 'ebook', + }); + assert.equal(lookup.mock.callCount(), 1); + assert.equal( + lookup.mock.calls[0]?.arguments[0]?.query, + 'isbn:9780441478125' + ); + }); + + it('resolves IMDb identities to a movie request', async () => { + mock.method( + TheMovieDb.prototype, + 'getByExternalId', + async () => + ({ + movie_results: [{ id: 123 }], + tv_results: [], + person_results: [], + }) as unknown as Awaited> + ); + + assert.deepEqual(await resolveImdbItem('tt1234567'), { + request: { mediaType: MediaType.MOVIE, mediaId: 123 }, + }); + }); + + it('submits new IMDb entries as the list owner through MediaRequest.request', async () => { + const user = await getRepository(User).findOneOrFail({ + where: { email: 'friend@seerr.dev' }, + }); + const repository = getRepository(ExternalRequestList); + const list = await repository.save( + new ExternalRequestList({ + user, + provider: 'imdb', + sourceId: 'ur12345678', + sourceUrl: 'https://www.imdb.com/user/ur12345678/watchlist/', + processedItemIds: [], + }) + ); + const requested: { body: unknown; userId: number; options: unknown[] }[] = + []; + let resolveCount = 0; + const requestMock = mock.method( + MediaRequest, + 'request', + async (...args: Parameters) => { + requested.push({ + body: args[0], + userId: args[1].id, + options: args.slice(2), + }); + return {} as MediaRequest; + } + ); + + const adapters: ExternalRequestListSyncAdapters = { + fetchImdbWatchlist: async () => [{ id: 'tt1234567' }], + fetchGoodreadsToRead: async () => [], + resolveImdbItem: async () => { + resolveCount += 1; + return { + request: { mediaType: MediaType.MOVIE, mediaId: 123 }, + }; + }, + resolveGoodreadsItem: async () => undefined, + requestMedia: (body, owner) => MediaRequest.request(body, owner), + saveList: (record) => repository.save(record), + now: () => new Date('2026-10-04T12:00:00.000Z'), + }; + + const firstSync = await syncExternalRequestList(list, user, adapters); + const secondSync = await syncExternalRequestList(list, user, adapters); + + assert.equal(firstSync.requested, 1); + assert.equal(firstSync.failed, 0); + assert.equal(secondSync.requested, 0); + assert.equal(requested.length, 1); + assert.equal(requested[0].userId, user.id); + assert.deepEqual(requested[0].body, { + mediaType: MediaType.MOVIE, + mediaId: 123, + }); + assert.deepEqual(requested[0].options, []); + assert.equal(resolveCount, 1); + assert.deepEqual(list.processedItemIds, ['tt1234567']); + assert.equal(requestMock.mock.callCount(), 1); + }); + + it('records duplicate requests as processed without submitting again', async () => { + const user = await getRepository(User).findOneOrFail({ + where: { email: 'friend@seerr.dev' }, + }); + const repository = getRepository(ExternalRequestList); + const list = await repository.save( + new ExternalRequestList({ + user, + provider: 'imdb', + sourceId: 'ur12345678', + sourceUrl: 'https://www.imdb.com/user/ur12345678/watchlist/', + processedItemIds: [], + }) + ); + const adapters: ExternalRequestListSyncAdapters = { + fetchImdbWatchlist: async () => [{ id: 'tt9876543' }], + fetchGoodreadsToRead: async () => [], + resolveImdbItem: async () => ({ + request: { mediaType: MediaType.MOVIE, mediaId: 456 }, + }), + resolveGoodreadsItem: async () => undefined, + requestMedia: async () => { + throw new DuplicateMediaRequestError('Already requested.'); + }, + saveList: (record) => repository.save(record), + now: () => new Date('2026-10-04T12:00:00.000Z'), + }; + + const result = await syncExternalRequestList(list, user, adapters); + + assert.equal(result.alreadyRequested, 1); + assert.equal(result.failed, 0); + assert.deepEqual(list.processedItemIds, ['tt9876543']); + }); +}); diff --git a/server/lib/externalRequestLists.ts b/server/lib/externalRequestLists.ts new file mode 100644 index 0000000000..27d11b764a --- /dev/null +++ b/server/lib/externalRequestLists.ts @@ -0,0 +1,446 @@ +import ExternalAPI from '@server/api/externalapi'; +import OpenLibraryAPI from '@server/api/openlibrary'; +import TheMovieDb from '@server/api/themoviedb'; +import { MediaType } from '@server/constants/media'; +import { getRepository } from '@server/datasource'; +import { ExternalRequestList } from '@server/entity/ExternalRequestList'; +import { + BlocklistedMediaError, + DuplicateMediaRequestError, + MediaRequest, +} from '@server/entity/MediaRequest'; +import type { User } from '@server/entity/User'; +import type { MediaRequestBody } from '@server/interfaces/api/requestInterfaces'; +import { normalizeOpenLibraryWorkId } from '@server/lib/externalIds'; +import { normalizeValidIsbn } from '@server/lib/isbn'; +import logger from '@server/logger'; +import xml2js from 'xml2js'; + +export const MAX_EXTERNAL_REQUEST_LISTS_PER_USER = 10; +export const MAX_EXTERNAL_REQUEST_LIST_ITEMS = 100; + +export type ExternalRequestListProvider = 'imdb' | 'goodreads'; + +export type ParsedExternalRequestListUrl = { + provider: ExternalRequestListProvider; + sourceId: string; + sourceUrl: string; +}; + +export type ExternalRequestListItem = { + id: string; + title?: string; + author?: string; + isbn13?: string; +}; + +export type ResolvedExternalRequestListItem = { + request: MediaRequestBody; +}; + +export type ExternalRequestListSyncResult = { + listId: number; + provider: ExternalRequestListProvider; + sourceItems: number; + requested: number; + alreadyRequested: number; + unmatched: number; + failed: number; + lastSyncedAt: string; + error?: string; +}; + +export type ExternalRequestListSyncAdapters = { + fetchImdbWatchlist: (userId: string) => Promise; + fetchGoodreadsToRead: (userId: string) => Promise; + resolveImdbItem: ( + imdbId: string + ) => Promise; + resolveGoodreadsItem: ( + item: ExternalRequestListItem + ) => Promise; + requestMedia: (body: MediaRequestBody, user: User) => Promise; + saveList: (list: ExternalRequestList) => Promise; + now: () => Date; +}; + +const isRecord = (value: unknown): value is Record => + !!value && typeof value === 'object' && !Array.isArray(value); + +export const parseExternalRequestListUrl = ( + value: unknown +): ParsedExternalRequestListUrl | undefined => { + if (typeof value !== 'string' || value.length > 2048) return undefined; + + let url: URL; + try { + url = new URL(value.trim()); + } catch { + return undefined; + } + + if ( + url.protocol !== 'https:' || + url.username || + url.password || + (url.port && url.port !== '443') || + url.hash + ) { + return undefined; + } + + if ( + (url.hostname === 'www.imdb.com' || url.hostname === 'imdb.com') && + url.search === '' + ) { + const match = url.pathname.match(/^\/user\/(ur[0-9]{1,20})\/watchlist\/?$/); + if (!match) return undefined; + return { + provider: 'imdb', + sourceId: match[1], + sourceUrl: `https://www.imdb.com/user/${match[1]}/watchlist/`, + }; + } + + if ( + url.hostname !== 'www.goodreads.com' && + url.hostname !== 'goodreads.com' + ) { + return undefined; + } + + const feedMatch = url.pathname.match( + /^\/review\/list_rss\/([0-9]{1,20})\/?$/ + ); + const profileMatch = url.pathname.match( + /^\/user\/show\/([0-9]{1,20})(?:-[A-Za-z0-9-]+)?\/?$/ + ); + const listMatch = url.pathname.match(/^\/review\/list\/([0-9]{1,20})\/?$/); + const userId = feedMatch?.[1] ?? profileMatch?.[1] ?? listMatch?.[1]; + if (!userId) return undefined; + + const allowedQueryKeys = new Set(['shelf', 'sort', 'order']); + if ( + [...url.searchParams.keys()].some((key) => !allowedQueryKeys.has(key)) || + (url.searchParams.get('shelf') && + url.searchParams.get('shelf') !== 'to-read') + ) { + return undefined; + } + + return { + provider: 'goodreads', + sourceId: `goodreads:${userId}:to-read`, + sourceUrl: `https://www.goodreads.com/review/list_rss/${userId}?shelf=to-read`, + }; +}; + +const boundedText = (value: unknown, maxLength = 512): string | undefined => { + if (typeof value !== 'string') return undefined; + const result = value.trim().slice(0, maxLength); + return result || undefined; +}; + +const asXmlText = (value: unknown): string | undefined => { + if (typeof value === 'string') return boundedText(value); + if (Array.isArray(value)) return asXmlText(value[0]); + return undefined; +}; + +class PublicListApi extends ExternalAPI { + constructor(baseUrl: string) { + super( + baseUrl, + {}, + { + timeout: 10_000, + maxContentLength: 2 * 1024 * 1024, + maxBodyLength: 1024, + headers: { + accept: + 'text/html,application/rss+xml,application/xml;q=0.9,*/*;q=0.8', + }, + rateLimit: { maxRequests: 1, perMilliseconds: 1000 }, + } + ); + } + + public fetchHtml(endpoint: string): Promise { + return this.get(endpoint, {}, 0); + } + + public fetchXml(endpoint: string): Promise { + return this.get(endpoint, {}, 0); + } +} + +export const parseImdbWatchlistHtml = ( + html: string +): ExternalRequestListItem[] => { + const matches = html.matchAll(/\/title\/(tt[0-9]{5,20})(?:[/?#"\\])/g); + const seen = new Set(); + const items: ExternalRequestListItem[] = []; + for (const match of matches) { + if (!seen.has(match[1])) { + seen.add(match[1]); + items.push({ id: match[1] }); + if (items.length >= MAX_EXTERNAL_REQUEST_LIST_ITEMS) break; + } + } + + if (items.length === 0 && !/watchlist/i.test(html)) { + throw new Error('IMDb did not return a public watchlist page.'); + } + return items; +}; + +const fetchImdbWatchlist = async ( + userId: string +): Promise => { + const html = await new PublicListApi('https://www.imdb.com').fetchHtml( + `/user/${userId}/watchlist/` + ); + return parseImdbWatchlistHtml(html); +}; + +export const parseGoodreadsToReadFeed = async ( + xml: string +): Promise => { + const parsed: unknown = await xml2js.parseStringPromise(xml, { + explicitArray: true, + trim: true, + }); + const rss = isRecord(parsed) && isRecord(parsed.rss) ? parsed.rss : undefined; + const channelValue = rss?.channel; + const channel = Array.isArray(channelValue) ? channelValue[0] : channelValue; + const rawItems = isRecord(channel) ? channel.item : undefined; + const entries = Array.isArray(rawItems) + ? rawItems + : rawItems + ? [rawItems] + : []; + + const seen = new Set(); + return entries.slice(0, MAX_EXTERNAL_REQUEST_LIST_ITEMS).flatMap((entry) => { + if (!isRecord(entry)) return []; + const id = asXmlText(entry.book_id); + const title = asXmlText(entry.title); + const author = asXmlText(entry.author_name); + if (!id || !/^[0-9]{1,20}$/.test(id) || !title || seen.has(id)) return []; + seen.add(id); + const isbn = normalizeValidIsbn( + asXmlText(entry.isbn13) ?? asXmlText(entry.isbn) + ); + return [{ id, title, author, isbn13: isbn }]; + }); +}; + +const fetchGoodreadsToRead = async ( + userId: string +): Promise => { + const xml = await new PublicListApi('https://www.goodreads.com').fetchXml( + `/review/list_rss/${userId}?shelf=to-read` + ); + return parseGoodreadsToReadFeed(xml); +}; + +export const resolveImdbItem = async ( + imdbId: string +): Promise => { + const result = await new TheMovieDb().getByExternalId({ + externalId: imdbId, + type: 'imdb', + }); + const movie = result.movie_results[0]; + if (movie) { + return { request: { mediaType: MediaType.MOVIE, mediaId: movie.id } }; + } + + const show = result.tv_results[0]; + return show + ? { + request: { + mediaType: MediaType.TV, + mediaId: show.id, + seasons: 'all', + }, + } + : undefined; +}; + +const normalizeBookIdentity = (value: string) => + value + .normalize('NFKD') + .toLocaleLowerCase() + .replace(/[\u0300-\u036f]/g, '') + .replace(/[^\p{L}\p{N}]+/gu, ''); + +export const resolveGoodreadsItem = async ( + item: ExternalRequestListItem +): Promise => { + const openLibrary = new OpenLibraryAPI(); + let candidates = item.isbn13 + ? ( + await openLibrary.searchBooks({ + query: `isbn:${item.isbn13}`, + limit: 20, + }) + ).docs.filter((book) => + book.isbn?.some((isbn) => normalizeValidIsbn(isbn) === item.isbn13) + ) + : []; + + if (candidates.length === 0 && item.title && item.author) { + const quote = (value: string) => value.replace(/["\\]/g, ' ').slice(0, 256); + candidates = ( + await openLibrary.searchBooks({ + query: `title:"${quote(item.title)}" author:"${quote(item.author)}"`, + limit: 20, + }) + ).docs.filter( + (book) => + normalizeBookIdentity(book.title) === + normalizeBookIdentity(item.title!) && + book.author_name?.some( + (author) => + normalizeBookIdentity(author) === + normalizeBookIdentity(item.author!) + ) + ); + } + + const candidate = candidates[0]; + const openLibraryId = candidate + ? normalizeOpenLibraryWorkId(candidate.key) + : undefined; + if (!openLibraryId || !/^OL[0-9]+W$/.test(openLibraryId)) return undefined; + + return { + request: { + mediaType: MediaType.BOOK, + mediaId: openLibraryId, + ...(item.isbn13 ? { isbn13: item.isbn13 } : {}), + format: 'ebook', + }, + }; +}; + +const defaultAdapters: ExternalRequestListSyncAdapters = { + fetchImdbWatchlist, + fetchGoodreadsToRead, + resolveImdbItem, + resolveGoodreadsItem, + requestMedia: (body, user) => MediaRequest.request(body, user), + saveList: (list) => getRepository(ExternalRequestList).save(list), + now: () => new Date(), +}; + +const errorMessage = (error: unknown): string => + error instanceof Error && error.message + ? error.message.slice(0, 512) + : 'The list sync failed.'; + +export const syncExternalRequestList = async ( + list: ExternalRequestList, + user: User, + adapters: ExternalRequestListSyncAdapters = defaultAdapters +): Promise => { + const result: ExternalRequestListSyncResult = { + listId: list.id, + provider: list.provider, + sourceItems: 0, + requested: 0, + alreadyRequested: 0, + unmatched: 0, + failed: 0, + lastSyncedAt: adapters.now().toISOString(), + }; + const processed = new Set( + Array.isArray(list.processedItemIds) ? list.processedItemIds : [] + ); + + try { + const userId = + list.provider === 'imdb' + ? list.sourceId + : list.sourceId.match(/^goodreads:([0-9]{1,20}):to-read$/)?.[1]; + if (!userId) throw new Error('The saved list source is invalid.'); + + const items = + list.provider === 'imdb' + ? await adapters.fetchImdbWatchlist(userId) + : await adapters.fetchGoodreadsToRead(userId); + result.sourceItems = items.length; + + for (const item of items.slice(0, MAX_EXTERNAL_REQUEST_LIST_ITEMS)) { + if (processed.has(item.id)) continue; + + const resolved = + list.provider === 'imdb' + ? await adapters.resolveImdbItem(item.id) + : await adapters.resolveGoodreadsItem(item); + if (!resolved) { + result.unmatched += 1; + continue; + } + + try { + await adapters.requestMedia(resolved.request, user); + result.requested += 1; + processed.add(item.id); + list.processedItemIds = [...processed]; + await adapters.saveList(list); + } catch (error) { + if (error instanceof DuplicateMediaRequestError) { + result.alreadyRequested += 1; + processed.add(item.id); + list.processedItemIds = [...processed]; + await adapters.saveList(list); + continue; + } + if (error instanceof BlocklistedMediaError) { + result.alreadyRequested += 1; + processed.add(item.id); + list.processedItemIds = [...processed]; + await adapters.saveList(list); + continue; + } + result.failed += 1; + result.error = errorMessage(error); + break; + } + } + } catch (error) { + result.failed += 1; + result.error = errorMessage(error); + } + + list.processedItemIds = [...processed]; + list.lastSyncedAt = adapters.now(); + list.lastSyncError = result.error ?? null; + await adapters.saveList(list); + result.lastSyncedAt = list.lastSyncedAt.toISOString(); + return result; +}; + +export const syncAllExternalRequestLists = async (): Promise => { + const lists = await getRepository(ExternalRequestList).find({ + relations: { user: true }, + order: { id: 'ASC' }, + }); + + for (const list of lists) { + if (!list.user) continue; + const result = await syncExternalRequestList(list, list.user); + logger.info('External request list synchronization completed.', { + label: 'External Request Lists', + listId: list.id, + provider: list.provider, + requested: result.requested, + alreadyRequested: result.alreadyRequested, + unmatched: result.unmatched, + failed: result.failed, + error: result.error, + }); + } +}; diff --git a/server/lib/settings/index.ts b/server/lib/settings/index.ts index 1ecf645793..71e2d05c72 100644 --- a/server/lib/settings/index.ts +++ b/server/lib/settings/index.ts @@ -523,6 +523,7 @@ export type JobId = | 'image-cache-cleanup' | 'release-calendar-history' | 'availability-sync' + | 'external-request-list-sync' | 'process-blocklisted-tags'; export interface DiscoveryIntegrationsSettings { @@ -821,6 +822,9 @@ class Settings { 'plex-watchlist-sync': { schedule: '0 */3 * * * *', }, + 'external-request-list-sync': { + schedule: '0 0 3 * * *', + }, 'plex-refresh-token': { schedule: '0 0 5 * * *', }, @@ -1693,6 +1697,9 @@ class Settings { 'plex-watchlist-sync': { schedule: '0 */3 * * * *', }, + 'external-request-list-sync': { + schedule: '0 0 3 * * *', + }, 'plex-refresh-token': { schedule: '0 0 5 * * *', }, diff --git a/server/lib/settings/migrations/0021_add_external_request_list_sync_job.test.ts b/server/lib/settings/migrations/0021_add_external_request_list_sync_job.test.ts new file mode 100644 index 0000000000..634b914cca --- /dev/null +++ b/server/lib/settings/migrations/0021_add_external_request_list_sync_job.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest'; +import addExternalRequestListSyncJob from './0021_add_external_request_list_sync_job'; + +describe('external request list sync job settings migration', () => { + it('adds its daily schedule and preserves an operator schedule', () => { + const defaults = addExternalRequestListSyncJob({ + jobs: {}, + migrations: [], + }); + expect(defaults.jobs['external-request-list-sync']).toEqual({ + schedule: '0 0 3 * * *', + }); + + const customized = addExternalRequestListSyncJob({ + jobs: { + 'external-request-list-sync': { + schedule: '0 30 4 * * *', + enabled: false, + }, + }, + migrations: [], + }); + expect(customized.jobs['external-request-list-sync']).toEqual({ + schedule: '0 30 4 * * *', + enabled: false, + }); + }); +}); diff --git a/server/lib/settings/migrations/0021_add_external_request_list_sync_job.ts b/server/lib/settings/migrations/0021_add_external_request_list_sync_job.ts new file mode 100644 index 0000000000..b496047b47 --- /dev/null +++ b/server/lib/settings/migrations/0021_add_external_request_list_sync_job.ts @@ -0,0 +1,26 @@ +import type { AllSettings } from '@server/lib/settings'; + +type SettingsWithJobMigrations = { + jobs?: Partial; + migrations?: string[]; +}; + +const addExternalRequestListSyncJob = ( + settings: SettingsWithJobMigrations +): AllSettings => { + if ( + settings.migrations?.includes('0021_add_external_request_list_sync_job') + ) { + return settings as AllSettings; + } + + settings.jobs ??= {}; + settings.jobs['external-request-list-sync'] ??= { + schedule: '0 0 3 * * *', + }; + settings.migrations ??= []; + settings.migrations.push('0021_add_external_request_list_sync_job'); + return settings as AllSettings; +}; + +export default addExternalRequestListSyncJob; diff --git a/server/migration/postgres/1791010000000-CreateExternalRequestLists.ts b/server/migration/postgres/1791010000000-CreateExternalRequestLists.ts new file mode 100644 index 0000000000..55b4be54bd --- /dev/null +++ b/server/migration/postgres/1791010000000-CreateExternalRequestLists.ts @@ -0,0 +1,32 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class CreateExternalRequestLists1791010000000 implements MigrationInterface { + name = 'CreateExternalRequestLists1791010000000'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + CREATE TABLE "external_request_list" ( + "id" SERIAL NOT NULL, + "userId" integer NOT NULL, + "provider" character varying(16) NOT NULL, + "sourceId" character varying(64) NOT NULL, + "sourceUrl" character varying(2048) NOT NULL, + "processedItemIds" text, + "lastSyncedAt" TIMESTAMP, + "lastSyncError" text, + CONSTRAINT "PK_external_request_list" PRIMARY KEY ("id"), + CONSTRAINT "FK_external_request_list_user" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE + ) + `); + await queryRunner.query( + 'CREATE UNIQUE INDEX "IDX_external_request_list_user_source" ON "external_request_list" ("userId", "sourceId")' + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + 'DROP INDEX "IDX_external_request_list_user_source"' + ); + await queryRunner.query('DROP TABLE "external_request_list"'); + } +} diff --git a/server/migration/sqlite/1791010000000-CreateExternalRequestLists.test.ts b/server/migration/sqlite/1791010000000-CreateExternalRequestLists.test.ts new file mode 100644 index 0000000000..006bbeee66 --- /dev/null +++ b/server/migration/sqlite/1791010000000-CreateExternalRequestLists.test.ts @@ -0,0 +1,36 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { DataSource } from 'typeorm'; +import { CreateExternalRequestLists1791010000000 } from './1791010000000-CreateExternalRequestLists'; + +test('external request list migration creates and removes its source table', async () => { + const dataSource = await new DataSource({ + type: 'better-sqlite3', + database: ':memory:', + }).initialize(); + const queryRunner = dataSource.createQueryRunner(); + const migration = new CreateExternalRequestLists1791010000000(); + + try { + await queryRunner.query( + 'CREATE TABLE "user" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL)' + ); + await migration.up(queryRunner); + + assert.equal(await queryRunner.hasTable('external_request_list'), true); + assert.equal( + await queryRunner.hasColumn('external_request_list', 'processedItemIds'), + true + ); + assert.equal( + await queryRunner.hasColumn('external_request_list', 'lastSyncError'), + true + ); + + await migration.down(queryRunner); + assert.equal(await queryRunner.hasTable('external_request_list'), false); + } finally { + await queryRunner.release(); + await dataSource.destroy(); + } +}); diff --git a/server/migration/sqlite/1791010000000-CreateExternalRequestLists.ts b/server/migration/sqlite/1791010000000-CreateExternalRequestLists.ts new file mode 100644 index 0000000000..e3de857f41 --- /dev/null +++ b/server/migration/sqlite/1791010000000-CreateExternalRequestLists.ts @@ -0,0 +1,31 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class CreateExternalRequestLists1791010000000 implements MigrationInterface { + name = 'CreateExternalRequestLists1791010000000'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + CREATE TABLE "external_request_list" ( + "id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, + "userId" integer NOT NULL, + "provider" varchar(16) NOT NULL, + "sourceId" varchar(64) NOT NULL, + "sourceUrl" varchar(2048) NOT NULL, + "processedItemIds" text, + "lastSyncedAt" datetime, + "lastSyncError" text, + CONSTRAINT "FK_external_request_list_user" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION + ) + `); + await queryRunner.query( + 'CREATE UNIQUE INDEX "IDX_external_request_list_user_source" ON "external_request_list" ("userId", "sourceId")' + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + 'DROP INDEX "IDX_external_request_list_user_source"' + ); + await queryRunner.query('DROP TABLE "external_request_list"'); + } +} diff --git a/server/routes/externalRequestLists.test.ts b/server/routes/externalRequestLists.test.ts new file mode 100644 index 0000000000..a9cca92ff3 --- /dev/null +++ b/server/routes/externalRequestLists.test.ts @@ -0,0 +1,123 @@ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { before, beforeEach, describe, it } from 'node:test'; + +import { getSettings } from '@server/lib/settings'; +import { setupTestDb } from '@server/test/db'; +import type { Express } from 'express'; +import express from 'express'; +import * as OpenApiValidator from 'express-openapi-validator'; +import session from 'express-session'; +import request from 'supertest'; +import router from './index'; + +describe('external request list routes', () => { + let app: Express; + + function createApp(): Express { + const testApp = express(); + testApp.use(express.json()); + testApp.use( + session({ + secret: 'test-secret', + cookie: { secure: 'auto' }, + resave: false, + saveUninitialized: false, + }) + ); + testApp.use( + OpenApiValidator.middleware({ + apiSpec: path.join(process.cwd(), 'seerr-api.yml'), + validateRequests: true, + validateSecurity: false, + }) + ); + testApp.use('/api/v1', router); + testApp.use( + ( + error: { status?: number; message?: string }, + _req: express.Request, + res: express.Response, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _next: express.NextFunction + ) => + res + .status(error.status ?? 500) + .json({ status: error.status ?? 500, message: error.message }) + ); + return testApp; + } + + before(async () => { + app = createApp(); + }); + + setupTestDb(); + + beforeEach(() => { + getSettings().main.localLogin = true; + }); + + async function loginAs(email: string) { + const agent = request.agent(app); + const response = await agent + .post('/api/v1/auth/local') + .send({ email, password: 'test1234' }); + assert.equal(response.status, 200); + return agent; + } + + it('creates a recurring list source for the signed-in user', async () => { + const agent = await loginAs('friend@seerr.dev'); + const response = await agent.post('/api/v1/request/lists').send({ + url: 'https://www.imdb.com/user/ur12345678/watchlist/', + }); + + assert.equal(response.status, 201, JSON.stringify(response.body)); + assert.equal(response.body.provider, 'imdb'); + assert.equal( + response.body.sourceUrl, + 'https://www.imdb.com/user/ur12345678/watchlist/' + ); + assert.equal(response.body.userId, undefined); + assert.equal(response.body.processedItemIds, undefined); + }); + + it('rejects a public-list URL that could target a private network', async () => { + const agent = await loginAs('friend@seerr.dev'); + const response = await agent + .post('/api/v1/request/lists') + .send({ url: 'http://127.0.0.1/admin' }); + + assert.equal(response.status, 400); + }); + + it('does not expose another user’s configured sources', async () => { + const requester = await loginAs('friend@seerr.dev'); + const created = await requester.post('/api/v1/request/lists').send({ + url: 'https://www.imdb.com/user/ur12345678/watchlist/', + }); + assert.equal(created.status, 201); + + const duplicate = await requester.post('/api/v1/request/lists').send({ + url: 'https://imdb.com/user/ur12345678/watchlist', + }); + assert.equal(duplicate.status, 409); + + const admin = await loginAs('admin@seerr.dev'); + const response = await admin.get('/api/v1/request/lists'); + + assert.equal(response.status, 200); + assert.deepEqual(response.body, []); + assert.equal( + (await admin.delete(`/api/v1/request/lists/${created.body.id}`)).status, + 404 + ); + + assert.equal( + (await requester.delete(`/api/v1/request/lists/${created.body.id}`)) + .status, + 204 + ); + }); +}); diff --git a/server/routes/externalRequestLists.ts b/server/routes/externalRequestLists.ts new file mode 100644 index 0000000000..2a237e0033 --- /dev/null +++ b/server/routes/externalRequestLists.ts @@ -0,0 +1,159 @@ +import { getRepository } from '@server/datasource'; +import { ExternalRequestList } from '@server/entity/ExternalRequestList'; +import { User } from '@server/entity/User'; +import { + MAX_EXTERNAL_REQUEST_LISTS_PER_USER, + parseExternalRequestListUrl, + syncExternalRequestList, +} from '@server/lib/externalRequestLists'; +import { isAuthenticated } from '@server/middleware/auth'; +import { isUniqueConstraintError } from '@server/utils/databaseError'; +import { parsePositiveRouteId } from '@server/utils/routeId'; +import { Router } from 'express'; + +const externalRequestListRoutes = Router(); +const maxRequestListId = 1_000_000_000; + +const filterExternalRequestList = (list: ExternalRequestList) => ({ + id: list.id, + provider: list.provider, + sourceUrl: list.sourceUrl, + lastSyncedAt: list.lastSyncedAt ?? null, + lastSyncError: list.lastSyncError ?? null, +}); + +externalRequestListRoutes.use(isAuthenticated()); + +externalRequestListRoutes.get('/', async (req, res, next) => { + try { + const lists = await getRepository(ExternalRequestList).find({ + where: { user: { id: req.user!.id } }, + order: { id: 'ASC' }, + }); + return res.status(200).json(lists.map(filterExternalRequestList)); + } catch (error) { + return next({ + status: 500, + message: + error instanceof Error + ? error.message + : 'Unable to retrieve external request lists.', + }); + } +}); + +externalRequestListRoutes.post('/', async (req, res, next) => { + if ( + !req.body || + typeof req.body !== 'object' || + Array.isArray(req.body) || + Object.keys(req.body).length !== 1 || + !Object.hasOwn(req.body, 'url') + ) { + return next({ status: 400, message: 'Provide one public list URL.' }); + } + + const source = parseExternalRequestListUrl(req.body.url); + if (!source) { + return next({ + status: 400, + message: + 'Use a public IMDb watchlist URL or a Goodreads to-read shelf URL.', + }); + } + + try { + const repository = getRepository(ExternalRequestList); + const currentCount = await repository.count({ + where: { user: { id: req.user!.id } }, + }); + if (currentCount >= MAX_EXTERNAL_REQUEST_LISTS_PER_USER) { + return next({ + status: 400, + message: `You can add up to ${MAX_EXTERNAL_REQUEST_LISTS_PER_USER} external lists.`, + }); + } + + const list = await repository.save( + new ExternalRequestList({ + user: req.user!, + provider: source.provider, + sourceId: source.sourceId, + sourceUrl: source.sourceUrl, + processedItemIds: [], + }) + ); + return res.status(201).json(filterExternalRequestList(list)); + } catch (error) { + if (isUniqueConstraintError(error)) { + return next({ status: 409, message: 'This list is already connected.' }); + } + return next({ + status: 500, + message: + error instanceof Error + ? error.message + : 'Unable to save the external request list.', + }); + } +}); + +externalRequestListRoutes.post<{ listId: string }>( + '/:listId/sync', + async (req, res, next) => { + const listId = parsePositiveRouteId(req.params.listId, maxRequestListId); + if (!listId) return next({ status: 404, message: 'List not found.' }); + + try { + const list = await getRepository(ExternalRequestList).findOne({ + where: { id: listId, user: { id: req.user!.id } }, + relations: { user: true }, + }); + if (!list) return next({ status: 404, message: 'List not found.' }); + + const user = await getRepository(User).findOne({ + where: { id: req.user!.id }, + }); + if (!user) return next({ status: 404, message: 'User not found.' }); + + const result = await syncExternalRequestList(list, user); + return res.status(200).json(result); + } catch (error) { + return next({ + status: 500, + message: + error instanceof Error + ? error.message + : 'Unable to sync the external request list.', + }); + } + } +); + +externalRequestListRoutes.delete<{ listId: string }>( + '/:listId', + async (req, res, next) => { + const listId = parsePositiveRouteId(req.params.listId, maxRequestListId); + if (!listId) return next({ status: 404, message: 'List not found.' }); + + try { + const repository = getRepository(ExternalRequestList); + const list = await repository.findOne({ + where: { id: listId, user: { id: req.user!.id } }, + }); + if (!list) return next({ status: 404, message: 'List not found.' }); + await repository.remove(list); + return res.status(204).send(); + } catch (error) { + return next({ + status: 500, + message: + error instanceof Error + ? error.message + : 'Unable to remove the external request list.', + }); + } + } +); + +export default externalRequestListRoutes; diff --git a/server/routes/index.ts b/server/routes/index.ts index 81e7a98356..df1107143a 100644 --- a/server/routes/index.ts +++ b/server/routes/index.ts @@ -64,6 +64,7 @@ import comicRoutes from './comic'; import desktopRoutes from './desktop'; import discoverRoutes, { createTmdbWithRegionLanguage } from './discover'; import discoveryIntegrationRoutes from './discoveryIntegrations'; +import externalRequestListRoutes from './externalRequestLists'; import { imageCacheWarmRateLimit, warmImageCache } from './imageproxy'; import indexerSearchRoutes from './indexerSearch'; import issueRoutes from './issue'; @@ -440,6 +441,7 @@ router.use( ); router.use('/search', isAuthenticated(), searchRoutes); router.use('/discover', isAuthenticated(), discoverRoutes); +router.use('/request/lists', externalRequestListRoutes); router.use('/request', isAuthenticated(), requestRoutes); router.use('/request/software', softwareRoutes); router.use('/calendar', isAuthenticated(), calendarRoutes); diff --git a/src/components/UserProfile/UserSettings/UserGeneralSettings/ExternalRequestLists.tsx b/src/components/UserProfile/UserSettings/UserGeneralSettings/ExternalRequestLists.tsx new file mode 100644 index 0000000000..e363f39360 --- /dev/null +++ b/src/components/UserProfile/UserSettings/UserGeneralSettings/ExternalRequestLists.tsx @@ -0,0 +1,231 @@ +import Button from '@app/components/Common/Button'; +import LoadingSpinner from '@app/components/Common/LoadingSpinner'; +import useLocale from '@app/hooks/useLocale'; +import defineMessages from '@app/utils/defineMessages'; +import axios from 'axios'; +import type { FormEvent } from 'react'; +import { useState } from 'react'; +import { useIntl } from 'react-intl'; +import useSWR from 'swr'; + +interface ExternalRequestList { + id: number; + provider: 'imdb' | 'goodreads'; + sourceUrl: string; + lastSyncedAt: string | null; + lastSyncError: string | null; +} + +interface ExternalRequestListSyncResult { + requested: number; + alreadyRequested: number; + unmatched: number; + failed: number; + error?: string; +} + +const messages = defineMessages( + 'components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists', + { + title: 'External request lists', + description: + 'Connect a public IMDb watchlist or Goodreads to-read shelf. New items are checked daily and requested through your normal permissions and approval settings.', + urlLabel: 'Public list URL', + urlPlaceholder: 'https://www.imdb.com/user/ur12345678/watchlist/', + add: 'Add list', + adding: 'Adding…', + empty: 'No external lists are connected.', + imdb: 'IMDb watchlist', + goodreads: 'Goodreads to-read shelf', + sync: 'Sync now', + syncing: 'Syncing…', + remove: 'Remove', + syncedNever: 'Not synced yet', + syncSummary: + 'Sync complete: {requested} requested, {alreadyRequested} already requested, {unmatched} not found, {failed} failed.', + saved: 'External list added.', + removed: 'External list removed.', + error: 'Could not update the external list. Try again.', + } +); + +const ExternalRequestLists = () => { + const intl = useIntl(); + const { locale } = useLocale(); + const [sourceUrl, setSourceUrl] = useState(''); + const [saving, setSaving] = useState(false); + const [busyListId, setBusyListId] = useState(null); + const [message, setMessage] = useState(); + const [errorMessage, setErrorMessage] = useState(); + const { + data: lists, + error, + isLoading, + mutate, + } = useSWR('/api/v1/request/lists'); + + const formatError = (error: unknown) => + axios.isAxiosError(error) && + typeof error.response?.data?.message === 'string' + ? error.response.data.message + : intl.formatMessage(messages.error); + + const addList = async (event: FormEvent) => { + event.preventDefault(); + setMessage(undefined); + setErrorMessage(undefined); + setSaving(true); + try { + await axios.post('/api/v1/request/lists', { url: sourceUrl.trim() }); + setSourceUrl(''); + setMessage(intl.formatMessage(messages.saved)); + await mutate(); + } catch (error) { + setErrorMessage(formatError(error)); + } finally { + setSaving(false); + } + }; + + const syncList = async (list: ExternalRequestList) => { + setMessage(undefined); + setErrorMessage(undefined); + setBusyListId(list.id); + try { + const { data } = await axios.post( + `/api/v1/request/lists/${list.id}/sync` + ); + setMessage( + intl.formatMessage(messages.syncSummary, { + requested: data.requested, + alreadyRequested: data.alreadyRequested, + unmatched: data.unmatched, + failed: data.failed, + }) + ); + if (data.error) setErrorMessage(data.error); + await mutate(); + } catch (error) { + setErrorMessage(formatError(error)); + } finally { + setBusyListId(null); + } + }; + + const removeList = async (list: ExternalRequestList) => { + setMessage(undefined); + setErrorMessage(undefined); + setBusyListId(list.id); + try { + await axios.delete(`/api/v1/request/lists/${list.id}`); + setMessage(intl.formatMessage(messages.removed)); + await mutate(); + } catch (error) { + setErrorMessage(formatError(error)); + } finally { + setBusyListId(null); + } + }; + + return ( +
+

{intl.formatMessage(messages.title)}

+

{intl.formatMessage(messages.description)}

+ +
+ +
+ setSourceUrl(event.target.value)} + required + /> +
+ +
+
+
+ + {message &&

{message}

} + {errorMessage &&

{errorMessage}

} + {error &&

{intl.formatMessage(messages.error)}

} + {isLoading && } + {!isLoading && lists?.length === 0 && ( +

{intl.formatMessage(messages.empty)}

+ )} + {lists?.length ? ( +
+
+ {lists.map((list) => ( +
+ + {intl.formatMessage( + list.provider === 'imdb' + ? messages.imdb + : messages.goodreads + )} + + + {list.sourceUrl} + + + {list.lastSyncedAt + ? new Intl.DateTimeFormat(locale, { + dateStyle: 'medium', + timeStyle: 'short', + }).format(new Date(list.lastSyncedAt)) + : intl.formatMessage(messages.syncedNever)} + + {list.lastSyncError && ( + {list.lastSyncError} + )} +
+ + +
+
+ ))} +
+
+ ) : null} +
+ ); +}; + +export default ExternalRequestLists; diff --git a/src/components/UserProfile/UserSettings/UserGeneralSettings/index.tsx b/src/components/UserProfile/UserSettings/UserGeneralSettings/index.tsx index df5baa5cc9..bda6a5f3b8 100644 --- a/src/components/UserProfile/UserSettings/UserGeneralSettings/index.tsx +++ b/src/components/UserProfile/UserSettings/UserGeneralSettings/index.tsx @@ -5,6 +5,7 @@ import PageTitle from '@app/components/Common/PageTitle'; import LanguageSelector from '@app/components/LanguageSelector'; import QuotaSelector from '@app/components/QuotaSelector'; import RegionSelector from '@app/components/RegionSelector'; +import ExternalRequestLists from '@app/components/UserProfile/UserSettings/UserGeneralSettings/ExternalRequestLists'; import RequestRootFolderSettings from '@app/components/UserProfile/UserSettings/UserGeneralSettings/RequestRootFolderSettings'; import { availableLanguages } from '@app/context/LanguageContext'; import useLocale from '@app/hooks/useLocale'; @@ -1260,6 +1261,7 @@ const UserGeneralSettings = () => { ); }}
+ {user?.id === currentUser?.id && } ); }; diff --git a/src/i18n/locale/en.json b/src/i18n/locale/en.json index f0b5567171..2a7049ba95 100644 --- a/src/i18n/locale/en.json +++ b/src/i18n/locale/en.json @@ -3825,6 +3825,23 @@ "components.UserProfile.UserSettings.LinkJellyfinQuickConnectModal.subtitle": "Quick Connect", "components.UserProfile.UserSettings.LinkJellyfinQuickConnectModal.title": "Link {mediaServerName} Account", "components.UserProfile.UserSettings.LinkJellyfinQuickConnectModal.usePassword": "Use Password Instead", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.add": "Add list", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.adding": "Adding…", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.description": "Connect a public IMDb watchlist or Goodreads to-read shelf. New items are checked daily and requested through your normal permissions and approval settings.", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.empty": "No external lists are connected.", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.error": "Could not update the external list. Try again.", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.goodreads": "Goodreads to-read shelf", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.imdb": "IMDb watchlist", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.remove": "Remove", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.removed": "External list removed.", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.saved": "External list added.", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.sync": "Sync now", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.syncSummary": "Sync complete: {requested} requested, {alreadyRequested} already requested, {unmatched} not found, {failed} failed.", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.syncedNever": "Not synced yet", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.syncing": "Syncing…", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.title": "External request lists", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.urlLabel": "Public list URL", + "components.UserProfile.UserSettings.UserGeneralSettings.ExternalRequestLists.urlPlaceholder": "https://www.imdb.com/user/ur12345678/watchlist/", "components.UserProfile.UserSettings.UserGeneralSettings.RequestRootFolders.audiobooks": "Audiobooks", "components.UserProfile.UserSettings.UserGeneralSettings.RequestRootFolders.books": "Books", "components.UserProfile.UserSettings.UserGeneralSettings.RequestRootFolders.comics": "Comics", From 1c231472159c4e61180180c73dfe7365b82595c4 Mon Sep 17 00:00:00 2001 From: snapetech Date: Sun, 4 Oct 2026 10:35:13 -0600 Subject: [PATCH 05/58] fix(software): fall back when paged game search fails Fixes #160. AI-assisted with OpenAI Codex. --- ...-10-04-software-catalog-search-fallback.md | 9 +++ server/routes/software.test.ts | 64 +++++++++++++++++++ server/routes/software.ts | 13 +++- 3 files changed, 83 insertions(+), 3 deletions(-) create mode 100644 release-notes/2026-10-04-software-catalog-search-fallback.md diff --git a/release-notes/2026-10-04-software-catalog-search-fallback.md b/release-notes/2026-10-04-software-catalog-search-fallback.md new file mode 100644 index 0000000000..63c8006afa --- /dev/null +++ b/release-notes/2026-10-04-software-catalog-search-fallback.md @@ -0,0 +1,9 @@ +--- +category: fixed +audience: users, operators +area: software-search +action: none +breaking: false +--- + +PC game searches now fall back to QuestarrNG’s unpaged catalog when the paged endpoint rejects a query, keeping valid game results available during provider incompatibilities. diff --git a/server/routes/software.test.ts b/server/routes/software.test.ts index e740247224..a37f6a8b53 100644 --- a/server/routes/software.test.ts +++ b/server/routes/software.test.ts @@ -1046,6 +1046,70 @@ describe('software request routes', () => { ); }); + it('uses unpaged game results when QuestarrNG paged search fails', async () => { + mock.method(QuestarrNGAPI.prototype, 'getCatalogPlatforms', async () => [ + { id: 6, name: 'PC (Microsoft Windows)' }, + ]); + const pagedSearch = mock.method( + QuestarrNGAPI.prototype, + 'searchCatalogPage', + async () => { + throw Object.assign(new AxiosError('Bad gateway'), { + response: { status: 502 }, + }); + } + ); + const unpagedSearch = mock.method( + QuestarrNGAPI.prototype, + 'searchCatalog', + async () => [ + { + ...pcGame, + igdbId: 2650, + id: 'igdb-2650', + title: 'Prison Architect', + }, + ] + ); + + const response = await request(createApp()) + .get('/request/software/catalog/search') + .query({ category: 'game', q: 'Prison Architect' }); + + assert.strictEqual(response.status, 200); + assert.deepStrictEqual( + response.body.results.map((game: SoftwareCatalogGame) => game.title), + ['Prison Architect'] + ); + assert.strictEqual(response.body.nextCursor, null); + assert.strictEqual(pagedSearch.mock.callCount(), 1); + assert.deepStrictEqual(unpagedSearch.mock.calls[0].arguments, [ + 'Prison Architect', + 50, + ]); + }); + + it('does not hide QuestarrNG search transport errors with unpaged results', async () => { + mock.method(QuestarrNGAPI.prototype, 'getCatalogPlatforms', async () => [ + { id: 6, name: 'PC (Microsoft Windows)' }, + ]); + mock.method(QuestarrNGAPI.prototype, 'searchCatalogPage', async () => { + throw new AxiosError('Network Error'); + }); + const unpagedSearch = mock.method( + QuestarrNGAPI.prototype, + 'searchCatalog', + async () => [pcGame] + ); + + const response = await request(createApp()) + .get('/request/software/catalog/search') + .query({ category: 'game', q: 'Prison Architect' }); + + assert.notStrictEqual(response.status, 200); + assert.strictEqual(unpagedSearch.mock.callCount(), 0); + }); + it('uses the selected ROMarr catalog for emulation and keeps Questarr for PC games', async () => { getSettings().softwareAcquisition.emulationCatalogProvider = 'romarr'; const emulationGame = { diff --git a/server/routes/software.ts b/server/routes/software.ts index 06d1a43d05..56ec388b36 100644 --- a/server/routes/software.ts +++ b/server/routes/software.ts @@ -857,16 +857,23 @@ softwareRoutes.get('/catalog/search', async (req, res) => { 'Upgrade ROMarrNG to the SeerrNG catalog contract or switch the emulation catalog source to QuestarrNG.', }); } + const status = axios.isAxiosError(error) + ? error.response?.status + : undefined; + const canUseUnpagedFallback = + status === 404 || + status === 405 || + (status !== undefined && status >= 500); if ( parsed.cursor || parsed.filters.genre || parsed.filters.releaseYear || - !axios.isAxiosError(error) || - error.response?.status !== 404 + !canUseUnpagedFallback ) { throw error; } - // Older QuestarrNG installs have only the capped array endpoint. + // The unpaged catalog can still return useful results when the optional + // paged endpoint is unavailable or rejects a search query. games = await api.searchCatalog( parsed.query, CATALOG_PROVIDER_FETCH_LIMIT From ead182d582df7efa235c0139ca4492b912657f06 Mon Sep 17 00:00:00 2001 From: snapetech Date: Sun, 4 Oct 2026 10:35:40 -0600 Subject: [PATCH 06/58] test(ui): cover manager blocklist preference Update the guard to preserve the approved per-user hide preference for managers. AI-assisted with OpenAI Codex. --- src/styles/watchlistPreview.test.mjs | 49 ++++++++++++++++++---------- 1 file changed, 32 insertions(+), 17 deletions(-) diff --git a/src/styles/watchlistPreview.test.mjs b/src/styles/watchlistPreview.test.mjs index 9fa465bfa6..a7c41494a3 100644 --- a/src/styles/watchlistPreview.test.mjs +++ b/src/styles/watchlistPreview.test.mjs @@ -78,7 +78,11 @@ test('blocked poster visibility follows management permission on filtering and r discover, (node) => ts.isIfStatement(node) && - node.expression.getText() === 'hideBlocklisted && !canManageBlocklist' + node.expression.getText().includes('hideBlocklisted') && + node.expression.getText().includes('canManageBlocklist') && + node.expression + .getText() + .includes('settings.currentSettings.hideBlocklisted') )[0]; assert.ok(discoverGate); const renderGate = nodes( @@ -90,23 +94,19 @@ test('blocked poster visibility follows management permission on filtering and r )[0]; assert.ok(renderGate); for (const canManageBlocklist of [false, true]) { - const filter = evaluate(listFilter, { - canManageBlocklist, - MediaStatus: statuses, - }); - assert.equal( - filter({ mediaInfo: { status: statuses.BLOCKLISTED } }), - canManageBlocklist - ); - assert.equal(filter({ mediaInfo: { status: statuses.AVAILABLE } }), true); - assert.equal(filter({}), true); - assert.equal( - evaluate(discoverGate.expression, { - hideBlocklisted: true, + for (const hidePreference of [false, true]) { + const filter = evaluate(listFilter, { canManageBlocklist, - }), - !canManageBlocklist - ); + currentSettings: { hideBlocklisted: hidePreference }, + MediaStatus: statuses, + }); + assert.equal( + filter({ mediaInfo: { status: statuses.BLOCKLISTED } }), + canManageBlocklist && !hidePreference + ); + assert.equal(filter({ mediaInfo: { status: statuses.AVAILABLE } }), true); + assert.equal(filter({}), true); + } assert.equal( evaluate(renderGate.expression, { currentStatus: statuses.BLOCKLISTED, @@ -116,6 +116,21 @@ test('blocked poster visibility follows management permission on filtering and r !canManageBlocklist ); } + // Managers bypass the default hide, but the explicit user preference still applies. + for (const hideBlocklisted of [false, true]) { + for (const canManageBlocklist of [false, true]) { + for (const hidePreference of [false, true]) { + assert.equal( + evaluate(discoverGate.expression, { + hideBlocklisted, + canManageBlocklist, + settings: { currentSettings: { hideBlocklisted: hidePreference } }, + }), + hideBlocklisted && (!canManageBlocklist || hidePreference) + ); + } + } + } assert.doesNotMatch(card.getText(), /wasBlocklistedHere/); const removeHandler = nodes( card, From e72f113e6354ccdb0315a947557639f4ef8293c3 Mon Sep 17 00:00:00 2001 From: snapetech Date: Sun, 4 Oct 2026 12:38:31 -0600 Subject: [PATCH 07/58] feat(software): integrate ROMarrNG DAT catalog --- .../e2e/software-acquisition-romarrng.cy.ts | 275 ++++++++++ docs/SEERRNG-INTEGRATION.contract-v2.json | 48 ++ docs/using-seerr/software-acquisition.md | 73 ++- .../2026-10-04-romarrng-dat-catalog.md | 8 + seerr-api.yml | 113 +++- server/api/software/romarrng.contract.test.ts | 149 +++++- server/api/software/romarrng.ts | 81 ++- server/api/software/types.ts | 33 +- server/entity/SoftwareRequest.ts | 13 + server/entity/SoftwareRequestStatusEvent.ts | 6 + server/lib/releaseCalendar/software.test.ts | 1 + server/lib/releaseCalendar/software.ts | 6 +- server/lib/settings/index.ts | 5 +- server/lib/softwareCatalogPlatformMapping.ts | 44 ++ server/lib/softwareRequests.ts | 126 ++++- ...twareCatalogIdentityAndProviderProgress.ts | 50 ++ ...CatalogIdentityAndProviderProgress.test.ts | 67 +++ ...twareCatalogIdentityAndProviderProgress.ts | 50 ++ server/routes/settings/softwareAcquisition.ts | 169 +++++- server/routes/software.test.ts | 262 +++++++++ server/routes/software.ts | 497 +++++++++++++----- .../RequestStatus/SoftwareRequests.tsx | 70 +++ .../Settings/SettingsSoftwareAcquisition.tsx | 265 +++++++++- src/components/SoftwareCatalog/index.tsx | 152 ++++-- src/i18n/locale/en.json | 25 +- 25 files changed, 2334 insertions(+), 254 deletions(-) create mode 100644 cypress/e2e/software-acquisition-romarrng.cy.ts create mode 100644 docs/SEERRNG-INTEGRATION.contract-v2.json create mode 100644 release-notes/2026-10-04-romarrng-dat-catalog.md create mode 100644 server/lib/softwareCatalogPlatformMapping.ts create mode 100644 server/migration/postgres/1791100000000-AddSoftwareCatalogIdentityAndProviderProgress.ts create mode 100644 server/migration/sqlite/1791100000000-AddSoftwareCatalogIdentityAndProviderProgress.test.ts create mode 100644 server/migration/sqlite/1791100000000-AddSoftwareCatalogIdentityAndProviderProgress.ts diff --git a/cypress/e2e/software-acquisition-romarrng.cy.ts b/cypress/e2e/software-acquisition-romarrng.cy.ts new file mode 100644 index 0000000000..052abbd096 --- /dev/null +++ b/cypress/e2e/software-acquisition-romarrng.cy.ts @@ -0,0 +1,275 @@ +const platformMappings = { + systems: [ + { + slug: 'nes', + name: 'Nintendo Entertainment System', + automaticMatch: { id: 18, name: 'Nintendo Entertainment System' }, + selectedMatch: { id: 18, name: 'Nintendo Entertainment System' }, + status: 'automatic', + }, + { + slug: 'sega-cd', + name: 'Sega CD', + automaticMatch: null, + selectedMatch: null, + status: 'unmatched', + }, + { + slug: 'snes', + name: 'Super Nintendo Entertainment System', + automaticMatch: { id: 19, name: 'Super Nintendo Entertainment System' }, + selectedMatch: { id: 19, name: 'Super Nintendo Entertainment System' }, + status: 'automatic', + }, + ], + catalogPlatforms: [ + { id: 18, name: 'Nintendo Entertainment System' }, + { id: 19, name: 'Super Nintendo Entertainment System' }, + { id: 29, name: 'Sega CD' }, + ], + unmatchedSystems: [{ slug: 'sega-cd', name: 'Sega CD' }], + unmatchedCatalogPlatforms: [{ id: 29, name: 'Sega CD' }], +}; + +const softwareSettings = { + romarr: { + hostname: 'romarr.example.test', + port: 6868, + useSsl: false, + baseUrl: '', + apiKey: '', + apiKeyConfigured: true, + }, + questarr: { + hostname: '', + port: 3000, + useSsl: false, + baseUrl: '', + apiKey: '', + apiKeyConfigured: false, + }, + emulationCatalogProvider: 'romarr-dat', + emulationSystemGroups: { nes: 'retro', 'sega-cd': 'retro', snes: 'retro' }, + emulationPlatformMappings: {}, +}; + +const catalogGame = { + id: `dat-${'a'.repeat(64)}`, + catalogProvider: 'dat', + catalogId: `dat-${'a'.repeat(64)}`, + title: 'Metroid', + summary: 'Explore the original Metroid DAT entry.', + coverUrl: '', + releaseDate: '1986-08-06', + platforms: ['Nintendo Entertainment System'], + platformOptions: [{ key: 'nes', name: 'Nintendo Entertainment System' }], + genres: [], + emulationSystems: [ + { + slug: 'nes', + name: 'Nintendo Entertainment System', + group: 'retro', + catalogPlatformId: 18, + }, + ], + availability: 'missing', +}; + +const softwareRequest = { + request: { + id: 42, + requestedBy: { id: 1, displayName: 'Admin', avatar: '' }, + category: 'retro', + provider: 'romarr', + status: 'downloading', + title: 'Metroid', + coverUrl: '', + platform: { name: 'Nintendo Entertainment System' }, + catalogProvider: 'dat', + catalogKey: catalogGame.catalogId, + percent: 46.5, + stage: 'verifying_archive', + failureCode: null, + actions: { cancel: true }, + createdAt: '2026-10-01T12:00:00.000Z', + }, + status: 'downloading', + message: null, + assets: [], +}; + +const mockIntegrationData = () => { + cy.intercept('GET', '**/api/v1/settings/**', (request) => { + const pathname = new URL(request.url).pathname; + if (pathname === '/api/v1/settings/public') { + request.reply({ + softwareEnabled: true, + romarrEnabled: true, + enabledMediaCategories: { retro: true, modern: true, game: true }, + }); + } else if (pathname === '/api/v1/settings/cache') { + request.reply({ + apiCaches: [], + imageCache: { + tmdb: { imageCount: 0, size: 0 }, + avatar: { imageCount: 0, size: 0 }, + }, + }); + } else if (pathname === '/api/v1/settings/software-acquisition') { + request.reply(softwareSettings); + } else if (pathname === '/api/v1/settings/prowlarr') { + request.reply({ + hostname: '', + port: 9696, + useSsl: false, + baseUrl: '', + apiKey: '', + apiKeyConfigured: false, + categoryMappings: {}, + }); + } else { + request.reply([]); + } + }); + + cy.intercept('GET', '/api/v1/request/software/catalog/systems', { + body: { + catalogProvider: 'dat', + catalogSystemSlugs: ['nes', 'snes'], + unmatchedDatNames: ['ColecoVision'], + results: [ + { slug: 'nes', name: 'Nintendo Entertainment System', group: 'retro' }, + { slug: 'sega-cd', name: 'Sega CD', group: 'retro' }, + { + slug: 'snes', + name: 'Super Nintendo Entertainment System', + group: 'retro', + }, + ], + }, + }); + cy.intercept( + 'GET', + '/api/v1/settings/software-acquisition/platform-mapping/preview', + { + body: platformMappings, + } + ); + cy.intercept('POST', '/api/v1/settings/software-acquisition/test/romarr', { + body: { + service: 'ROMarrNG', + platformCount: 3, + requestContractVersion: 2, + capabilities: { catalog: false, datCatalog: true }, + datCatalogPlatformCount: 2, + unmatchedDatNames: ['ColecoVision'], + }, + }); + cy.intercept('PUT', '/api/v1/settings/software-acquisition', { + body: { success: true }, + }).as('saveSoftwareSettings'); + cy.intercept('GET', '/api/v1/request/software/catalog/popular*', { + body: { results: [catalogGame], nextOffset: null }, + }); + cy.intercept('GET', '/api/v1/request/software/catalog/search*', { + body: { results: [catalogGame], nextCursor: null }, + }).as('datCatalogSearch'); + cy.intercept('GET', '/api/v1/user/*/quota', { + body: { software: { limit: 5, remaining: 3 } }, + }); + cy.intercept('GET', '/api/v1/request/software/status*', { + body: { + results: [softwareRequest], + pageInfo: { page: 1, pages: 1, pageSize: 20, results: 1 }, + }, + }); + cy.intercept('GET', '/api/v1/request/software/status/42', { + body: { + history: [ + { + id: 1, + status: 'downloading', + message: null, + percent: 46.5, + providerStage: 'verifying_archive', + failureCode: null, + createdAt: '2026-10-01T12:00:00.000Z', + }, + ], + }, + }); +}; + +describe('ROMarrNG software acquisition integration', () => { + beforeEach(() => { + cy.loginAsAdmin(); + mockIntegrationData(); + }); + + it('previews platform matches and saves a manual override', () => { + cy.viewport(1280, 720); + cy.visit('/settings/services'); + cy.contains('h4', 'ROMarrNG to IGDB platform matching').scrollIntoView(); + cy.contains('button', 'Preview platform matches').click(); + cy.contains('dt', 'Sega CD').parent().contains('No automatic match'); + cy.contains('Systems without a match: 1').should('be.visible'); + cy.get('select[aria-label="Sega CD: ROMarrNG to IGDB platform matching"]') + .select('29') + .parent() + .contains('Manual match · Sega CD'); + cy.contains('button', 'Save settings').click(); + cy.wait('@saveSoftwareSettings') + .its('request.body.emulationPlatformMappings.sega-cd') + .should('eq', 29); + + cy.get('button').contains('Test connection').first().click(); + cy.contains('DAT catalog ready for 2 systems').should('be.visible'); + cy.contains('ColecoVision').should('be.visible'); + cy.viewport(390, 720); + cy.reload(); + cy.contains('h4', 'ROMarrNG to IGDB platform matching').scrollIntoView(); + cy.contains('button', 'Preview platform matches').click(); + cy.get( + 'select[aria-label="Nintendo Entertainment System: ROMarrNG to IGDB platform matching"]' + ) + .should('be.visible') + .select(''); + cy.contains('ColecoVision').should('be.visible'); + }); + + it('searches the DAT catalog without IGDB-only filters', () => { + cy.viewport(1280, 720); + cy.visit('/software'); + cy.contains('DAT catalog').should('be.visible'); + cy.contains('Metroid').should('be.visible'); + cy.contains('Browse DAT titles').should('be.visible'); + cy.contains('label', 'Genre').should('not.exist'); + cy.contains('label', 'Release year').should('not.exist'); + cy.get('input[placeholder="Search software titles"]').type('Metroid'); + cy.contains('button', 'Search').click(); + cy.wait('@datCatalogSearch') + .its('request.url') + .should('include', 'q=Metroid'); + cy.contains('Metroid').should('be.visible'); + + cy.viewport(390, 720); + cy.reload(); + cy.contains('Metroid').should('be.visible'); + }); + + it('shows provider-reported progress and stage on desktop and mobile widths', () => { + cy.viewport(1280, 720); + cy.visit('/requests?mediaType=retro'); + cy.contains('Software Requests').should('be.visible'); + cy.contains('46.5% downloaded').should('be.visible'); + cy.get('[role="progressbar"]').should('have.attr', 'aria-valuenow', '46.5'); + cy.contains('Stage: verifying archive').should('be.visible'); + cy.contains('button', 'History').click(); + cy.contains('Downloading · verifying archive · 47%').should('be.visible'); + + cy.viewport(390, 720); + cy.reload(); + cy.contains('46.5% downloaded').should('be.visible'); + cy.get('[role="progressbar"]').should('be.visible'); + }); +}); diff --git a/docs/SEERRNG-INTEGRATION.contract-v2.json b/docs/SEERRNG-INTEGRATION.contract-v2.json new file mode 100644 index 0000000000..7888d28e82 --- /dev/null +++ b/docs/SEERRNG-INTEGRATION.contract-v2.json @@ -0,0 +1,48 @@ +{ + "requestContractVersion": 2, + "handshake": { + "service": "ROMarrNG", + "apiVersion": 1, + "requestContractVersion": 2, + "capabilities": { + "catalog": true, + "datCatalog": true, + "pcAcquisition": false, + "emulationAcquisition": true, + "requestActions": { + "retry": true, + "cancel": true + }, + "assetStreaming": true + } + }, + "identityExamples": { + "igdb": { + "catalogProvider": "igdb", + "catalogId": 42, + "platformId": 130 + }, + "dat": { + "catalogProvider": "dat", + "catalogKey": "dat-0000000000000000000000000000000000000000000000000000000000000000", + "platformSlug": "snes" + } + }, + "failureExample": { + "status": "failed", + "stage": "failed", + "percent": null, + "failureCode": "IMPORT_FAILED", + "failureMessage": "The download could not be imported into the library." + }, + "privacy": { + "requestStatusForbiddenFields": [ + "assets", + "path", + "paths", + "localPath", + "absolutePath" + ], + "assetMetadataFields": ["id", "name", "size"] + } +} diff --git a/docs/using-seerr/software-acquisition.md b/docs/using-seerr/software-acquisition.md index 82b16fe973..9b82696351 100644 --- a/docs/using-seerr/software-acquisition.md +++ b/docs/using-seerr/software-acquisition.md @@ -30,7 +30,7 @@ layers. | Provider | Used for | What SeerrNG reads or sends | | --- | --- | --- | | [QuestarrNG](https://github.com/snapetech/QuestarrNG) | Default IGDB catalog source and PC game acquisition | Searches and popular titles, IGDB platform details, stable request identity and selected PC target, request progress, and imported files | -| [ROMarrNG](https://github.com/snapetech/ROMarrNG) | Supported emulation systems and acquisition for ROM requests; optional IGDB catalog source for emulation | Supported platform list and aliases, optional IGDB search and browse, stable request identity and selected system, request progress, and imported files | +| [ROMarrNG](https://github.com/snapetech/ROMarrNG) | Supported emulation systems and acquisition for ROM requests; optional IGDB or loaded DAT catalog source for emulation | Supported platform list and aliases, optional IGDB search and browse or DAT-backed browse, stable request identity and selected system, request progress, and imported files | Both providers are separate **NG** forks maintained for SeerrNG integration. Their project documentation identifies the upstream project, describes the @@ -38,13 +38,14 @@ SeerrNG integration, and links back to the SeerrNG repository. Use the provider's SeerrNG integration API key and contract. SeerrNG does not use a provider's browser UI or expose its credentials to requesters. -Provider handshakes can report retry, cancel, asset, and catalog capabilities. +Provider handshakes can report retry, cancel, asset, IGDB catalog, and DAT +catalog capabilities. Request Status follows reported retry and cancel availability and shows the provider's reason when an action is unavailable. Providers that do not report these optional capabilities continue to use the existing v1 acquisition contract. The emulation catalog source is QuestarrNG by default; SeerrNG only -saves ROMarrNG as the source when ROMarrNG explicitly advertises the SeerrNG -catalog capability. +saves a ROMarrNG catalog source when that provider advertises the matching +capability in its SeerrNG handshake. ## Configure the providers @@ -56,12 +57,15 @@ port, optional base path, SSL setting, and API key. source. 2. Configure **ROMarrNG** if users should request emulation games. To use its IGDB catalog, configure an IGDB metadata provider in ROMarrNG first. -3. Select **Test connection** for each provider. ROMarrNG also reports its - supported-system count and whether that version advertises the optional - SeerrNG IGDB catalog API. -4. Under **Emulation catalog source**, choose QuestarrNG or ROMarrNG. Save - verifies ROMarrNG's catalog capability again. PC game catalog and - acquisition always use QuestarrNG, and ROM acquisition always uses ROMarrNG. +3. Select **Test connection** for each provider. ROMarrNG reports its + supported-system count and which optional IGDB or DAT catalog capabilities + are available. DAT readiness includes the number of systems with matched + entries and any unmatched DAT header names for review. +4. Under **Emulation catalog source**, choose QuestarrNG, ROMarrNG's IGDB + catalog, or **ROMarrNG · DAT**. The DAT option is available only when + ROMarrNG advertises the capability and has loaded DAT entries. Save checks + the selected capability again. PC game catalog and acquisition always use + QuestarrNG, and ROM acquisition always uses ROMarrNG. 5. Select **Save settings**. SeerrNG reloads the ROMarrNG system list after the provider settings are saved. 6. Assign each supported ROMarrNG system to **Retro** or **Modern**, then save @@ -75,12 +79,13 @@ browser URLs or user-facing links. The selected catalog provider must be configured for its categories to load. QuestarrNG remains required for PC game requests, and ROMarrNG is required for emulation systems and ROM acquisition. Existing ROMarrNG installations keep -using their documented v1 request and status routes. The newer ROMarrNG -catalog is enabled only by a provider build that advertises that capability. +using their documented v1 request and status routes. Each newer ROMarrNG +catalog option is enabled only by a provider build that advertises the matching +capability. These connections are independent of Radarr, Sonarr, Bookshelf, and the other media automation services. -## Assign emulation systems +## Match IGDB platforms and assign emulation systems ROMarrNG's supported platform list is the source of selectable emulation systems. The administrator assigns each system to one of these groups: @@ -95,10 +100,32 @@ change ROMarrNG's platform setup or automatically classify systems; choose the group for each platform that matches how you want users to browse it. The assignment is saved by the system's stable slug, so a provider display-name -change does not discard it. SeerrNG matches IGDB catalog platforms to a -ROMarrNG system name, slug, or alias. If there is no match, the title is not -offered for that emulation system. Review new systems after updating ROMarrNG -and save their group before users request them. +change does not discard it. For IGDB catalogs, SeerrNG matches catalog +platforms to a ROMarrNG system name, slug, or alias when the match is unique. +Open **Preview platform matches** to review automatic matches, unmatched +systems, and unused IGDB platforms. Choose a platform override when an +automatic match is missing or incorrect; choosing **Automatic match** removes +the saved override. A system without an IGDB match is hidden from IGDB-backed +emulation browsing until it is mapped. Review new systems after updating +ROMarrNG and save their group before users request them. + +## Use ROMarrNG's DAT catalog + +ROMarrNG can provide a second emulation catalog from its loaded DAT files. DAT +headers are matched against ROMarrNG's declared system names and aliases. +Unmatched or ambiguous headers stay out of browsing and appear in the +connection result so an administrator can identify DATs that need attention. +DAT browsing includes systems with matched entries; the system group still +controls whether each system appears under Retro or Modern. + +DAT entries are grouped by title and system and use ROMarrNG's configured 1G1R +region preference. The catalog supports title search and alphabetical +browsing. DATs do not provide IGDB's artwork, popularity, genres, ratings, or +release dates, so SeerrNG does not show IGDB genre or release-year filters for +this source. Requests retain the stable DAT catalog key and selected system, +including through provider retry, so a changed title cannot silently inherit +the same request identity. Replacing a DAT version keeps an existing key when +the same system, DAT name, and title group remain present. ## Browse and submit requests @@ -141,9 +168,9 @@ availability and downloadable-file availability remain separate in that case. Within PC Games, select Windows, Linux, or macOS to narrow the catalog. The PC platform choice is preselected when opening a request and can still be changed before submission. -Use **Genre** and **Release year** to narrow any software category. These filters -apply to the selected catalog provider before pages are returned and require a -build with SeerrNG's paged catalog contract. +For IGDB catalogs, use **Genre** and **Release year** to narrow any software +category. These filters apply before pages are returned. DAT catalogs support +title and system filters only. Software titles load as you scroll, with a **Load more titles** button available when another page exists. SeerrNG filters by the selected PC or emulation @@ -217,6 +244,12 @@ and while Request Status is open. An available library item may not have a download action when its files are remote or unavailable to SeerrNG. A provider-reported completion alone never exposes a download action. +When a provider reports a real percentage, Request Status shows it with a +progress bar. ROMarrNG currently reports the acquisition stage without a +percentage because it cannot measure a reliable overall download percentage. +Failure codes identify the type of failure while the displayed explanation +stays readable. Provider status never exposes local filesystem paths. + ### Cancel an active request QuestarrNG can cancel only downloads that its database links to this SeerrNG diff --git a/release-notes/2026-10-04-romarrng-dat-catalog.md b/release-notes/2026-10-04-romarrng-dat-catalog.md new file mode 100644 index 0000000000..ce081576b0 --- /dev/null +++ b/release-notes/2026-10-04-romarrng-dat-catalog.md @@ -0,0 +1,8 @@ +--- +category: added +audience: users, operators +area: software +action: Load DAT files in ROMarrNG to enable the DAT emulation catalog. +breaking: false +--- +Administrators can select ROMarrNG's DAT catalog for emulation requests. SeerrNG browses matched systems alphabetically, supports title search, and keeps requests tied to a stable DAT identity while reporting unmatched DAT headers for review. diff --git a/seerr-api.yml b/seerr-api.yml index 602fddc6bb..4db782c938 100644 --- a/seerr-api.yml +++ b/seerr-api.yml @@ -2320,6 +2320,14 @@ components: catalogId: type: integer nullable: true + description: Numeric IGDB ID; null for DAT catalog requests. + catalogProvider: + type: string + enum: [igdb, dat] + catalogKey: + type: string + nullable: true + description: Stable catalog identity used to deduplicate requests across catalog providers. actions: $ref: '#/components/schemas/SoftwareRequestActions' platform: @@ -2349,6 +2357,14 @@ components: percent: type: number nullable: true + stage: + type: string + nullable: true + description: Sanitized provider stage, when available. + failureCode: + type: string + nullable: true + description: Stable provider failure code, when available. error: type: string nullable: true @@ -2402,6 +2418,12 @@ components: percent: type: number nullable: true + providerStage: + type: string + nullable: true + failureCode: + type: string + nullable: true fingerprint: type: string createdAt: @@ -6866,7 +6888,7 @@ paths: /settings/software-acquisition: get: summary: Get software acquisition provider settings - description: Returns ROMarrNG and QuestarrNG connection settings with API keys redacted, the selected emulation catalog provider, and administrator-assigned Retro and Modern system groups. + description: Returns ROMarrNG and QuestarrNG connection settings with API keys redacted, the selected emulation catalog provider, administrator-assigned Retro and Modern system groups, and optional ROMarrNG-to-IGDB platform overrides. tags: - settings responses: @@ -6883,15 +6905,20 @@ paths: $ref: '#/components/schemas/SoftwareProviderSettingsView' emulationCatalogProvider: type: string - enum: [questarr, romarr] + enum: [questarr, romarr, romarr-dat] emulationSystemGroups: type: object additionalProperties: type: string enum: [retro, modern] + emulationPlatformMappings: + type: object + additionalProperties: + type: integer + minimum: 1 put: summary: Update software acquisition settings - description: Updates provider connections, the selected emulation IGDB catalog, and per-system emulation groups. API keys stay server-side and are redacted in responses. + description: Updates provider connections, the selected emulation catalog, per-system emulation groups, and optional ROMarrNG-to-IGDB platform overrides. API keys stay server-side and are redacted in responses. tags: - settings requestBody: @@ -6907,12 +6934,17 @@ paths: $ref: '#/components/schemas/SoftwareProviderSettingsInput' emulationCatalogProvider: type: string - enum: [questarr, romarr] + enum: [questarr, romarr, romarr-dat] emulationSystemGroups: type: object additionalProperties: type: string enum: [retro, modern] + emulationPlatformMappings: + type: object + additionalProperties: + type: integer + minimum: 1 responses: '200': description: Software acquisition settings updated @@ -6927,12 +6959,28 @@ paths: $ref: '#/components/schemas/SoftwareProviderSettingsView' emulationCatalogProvider: type: string - enum: [questarr, romarr] + enum: [questarr, romarr, romarr-dat] emulationSystemGroups: type: object additionalProperties: type: string enum: [retro, modern] + emulationPlatformMappings: + type: object + additionalProperties: + type: integer + minimum: 1 + /settings/software-acquisition/platform-mapping/preview: + get: + summary: Preview ROMarrNG to IGDB platform matches + description: Returns unique automatic name and alias matches, saved overrides, unmatched ROMarrNG systems, and IGDB platforms not currently selected. + tags: + - settings + responses: + '200': + description: Platform matching preview returned + '502': + description: ROMarrNG platform or IGDB catalog could not be read '400': description: Invalid provider or system-group settings /settings/software-acquisition/test/{provider}: @@ -13514,7 +13562,7 @@ paths: /request/software: post: summary: Submit a ROM or PC game request - description: Creates a SeerrNG software request from the configured IGDB catalog. Emulation uses the selected QuestarrNG or ROMarrNG catalog and is acquired by ROMarrNG; PC game requests use QuestarrNG and require operating system and architecture. + description: Creates a SeerrNG software request from the configured IGDB or ROMarrNG DAT catalog. Emulation is acquired by ROMarrNG; PC game requests use QuestarrNG and require operating system and architecture. tags: - request requestBody: @@ -13523,14 +13571,26 @@ paths: application/json: schema: type: object - required: [category, catalogId] + required: [category] + oneOf: + - required: [catalogId] + - required: [catalogProvider, catalogKey] properties: category: type: string enum: [retro, modern, game] catalogId: - type: integer - minimum: 1 + oneOf: + - type: integer + minimum: 1 + - type: string + pattern: '^dat-[0-9a-f]{64}$' + catalogProvider: + type: string + enum: [igdb, dat] + catalogKey: + type: string + pattern: '^dat-[0-9a-f]{64}$' platformSlug: type: string variant: @@ -13559,7 +13619,7 @@ paths: /request/software/catalog/systems: get: summary: List ROMarrNG-supported emulation systems - description: Returns ROMarrNG-supported platform slugs and the Retro or Modern group assigned by an administrator. Unassigned systems are not requestable, regardless of which service supplies the emulation IGDB catalog. + description: Returns ROMarrNG-supported platform slugs and the Retro or Modern group assigned by an administrator, plus the selected emulation catalog source. When ROMarrNG DAT is selected, matched DAT systems and unmatched DAT header names are included. Unassigned systems are not requestable. tags: - request responses: @@ -13574,10 +13634,22 @@ paths: type: array items: type: object + catalogProvider: + type: string + enum: [questarr, igdb, dat] + catalogSystemSlugs: + type: array + items: + type: string + unmatchedDatNames: + type: array + description: DAT header names that ROMarrNG could not match to an unambiguous supported system. + items: + type: string /request/software/catalog/search: get: summary: Search ROM and PC game catalog - description: Searches the selected QuestarrNG or ROMarrNG IGDB catalog for emulation categories, or QuestarrNG for PC games. Results are filtered to the requested emulation group or PC platform and include availability (available, tracked, downloading, missing, or unknown) and ROM availableSystems when known. Pass the returned nextCursor to load the next page. + description: Searches the selected QuestarrNG or ROMarrNG IGDB or DAT catalog for emulation categories, or QuestarrNG for PC games. DAT results support title and system filters and page through an alphabetical catalog; IGDB results also support genre and release year. Results include availability and ROM availableSystems when known. tags: - request parameters: @@ -13651,8 +13723,8 @@ paths: description: Selected emulation catalog is unavailable, unconfigured, or needs the SeerrNG integration contract. /request/software/catalog/popular: get: - summary: List popular ROM and PC game catalog titles - description: Returns popular titles from the selected QuestarrNG or ROMarrNG IGDB catalog for emulation, or QuestarrNG for PC games. Results are filtered to the selected emulation group or PC platform and include provider and SeerrNG request availability. Pass the returned nextOffset to load the next page. + summary: Browse ROM and PC game catalog titles + description: Returns popular titles from IGDB or QuestarrNG, or alphabetically browsed titles from the ROMarrNG DAT catalog. Results are filtered to the selected emulation group or PC platform and include provider and SeerrNG request availability. Pass the returned nextOffset to load the next page. tags: - request parameters: @@ -13721,7 +13793,7 @@ paths: /request/software/catalog/games/{id}: get: summary: Get one ROM or PC game catalog title - description: Returns metadata from the selected QuestarrNG or ROMarrNG IGDB catalog for emulation, or QuestarrNG for PC games, with supported request targets, screenshots, video IDs, rating normalized to a 0-10 scale, and provider or SeerrNG request availability. + description: Returns metadata from the selected QuestarrNG or ROMarrNG IGDB or DAT catalog for emulation, or QuestarrNG for PC games, with supported request targets and provider or SeerrNG request availability. tags: - request parameters: @@ -13729,14 +13801,23 @@ paths: name: id required: true schema: - type: integer - minimum: 1 + oneOf: + - type: integer + minimum: 1 + - type: string + pattern: '^dat-[0-9a-f]{64}$' - in: query name: category required: true schema: type: string enum: [retro, modern, game] + - in: query + name: catalogProvider + description: Set to dat when the path ID is a stable DAT key. Defaults to igdb. + schema: + type: string + enum: [igdb, dat] responses: '200': description: Software catalog title returned diff --git a/server/api/software/romarrng.contract.test.ts b/server/api/software/romarrng.contract.test.ts index a72b032fba..95e8b78303 100644 --- a/server/api/software/romarrng.contract.test.ts +++ b/server/api/software/romarrng.contract.test.ts @@ -1,9 +1,36 @@ import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; import { createServer } from 'node:http'; import type { AddressInfo } from 'node:net'; +import path from 'node:path'; import { it } from 'node:test'; import ROMarrNGAPI from './romarrng'; +const contractFixture = JSON.parse( + readFileSync( + path.join(process.cwd(), 'docs', 'SEERRNG-INTEGRATION.contract-v2.json'), + 'utf8' + ) +) as { + requestContractVersion: number; + handshake: { + service: string; + apiVersion: number; + requestContractVersion: number; + capabilities: Record; + }; + identityExamples: { + dat: { catalogProvider: 'dat'; catalogKey: string; platformSlug: string }; + }; + failureExample: { + status: string; + stage: string; + percent: number | null; + failureCode: string; + failureMessage: string; + }; +}; + it('uses the versioned SeerrNG catalog contract and preserves IGDB identity', async () => { const requests: { method: string; path: string; body?: unknown }[] = []; const server = createServer((request, response) => { @@ -205,7 +232,7 @@ it('rejects a request contract version it does not understand', async () => { JSON.stringify({ service: 'ROMarrNG', apiVersion: 1, - requestContractVersion: 2, + requestContractVersion: 3, }) ); }); @@ -221,7 +248,125 @@ it('rejects a request contract version it does not understand', async () => { }); await assert.rejects( api.lookupLibrary([{ title: 'Example', platform: 'nes' }]), - /request contract v2 is not supported/ + /request contract v3 is not supported/ + ); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +it('uses the shared version 2 DAT catalog and failure contract fixture', async () => { + const requests: { method: string; path: string; body?: unknown }[] = []; + const server = createServer((request, response) => { + const url = new URL(request.url ?? '/', 'http://localhost'); + let body = ''; + request.setEncoding('utf8'); + request.on('data', (chunk) => (body += chunk)); + request.on('end', () => { + requests.push({ + method: request.method ?? 'GET', + path: url.pathname, + ...(body ? { body: JSON.parse(body) as unknown } : {}), + }); + const payload = url.pathname.endsWith('/ping') + ? contractFixture.handshake + : url.pathname.endsWith('/dat/platforms') + ? { results: [{ slug: 'snes', name: 'SNES', gameCount: 1 }] } + : url.pathname.endsWith('/dat/search-page') + ? { results: [], nextCursor: null } + : url.pathname.endsWith('/dat/browse-page') + ? { results: [], nextOffset: null } + : url.pathname.endsWith( + `/dat/games/${contractFixture.identityExamples.dat.catalogKey}` + ) + ? { + id: contractFixture.identityExamples.dat.catalogKey, + catalogProvider: 'dat', + catalogId: contractFixture.identityExamples.dat.catalogKey, + title: 'Example DAT title', + } + : url.pathname.endsWith('/requests') + ? { + externalRequestId: 'request-dat-1', + ...contractFixture.failureExample, + deliverable: false, + } + : url.pathname.endsWith('/requests/request-dat-1') + ? { + externalRequestId: 'request-dat-1', + ...contractFixture.failureExample, + deliverable: false, + } + : { error: 'Unknown test endpoint' }; + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end(JSON.stringify(payload)); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + + try { + const api = new ROMarrNGAPI({ + hostname: '127.0.0.1', + port: (server.address() as AddressInfo).port, + baseUrl: '', + useSsl: false, + apiKey: 'romarr-contract-v2-test', + }); + const handshake = await api.getHandshake(); + const platforms = await api.getDatCatalogPlatforms(); + await api.searchDatCatalogPage('Example DAT title', 10, undefined, [ + 'snes', + ]); + await api.browseDatCatalogPage(10, 0, ['snes']); + const game = await api.getDatCatalogGame( + contractFixture.identityExamples.dat.catalogKey + ); + const created = await api.createRequest( + 'request-dat-1', + game.title, + 'snes', + undefined, + undefined, + contractFixture.identityExamples.dat + ); + const status = await api.getRequest('request-dat-1'); + + assert.equal( + handshake.requestContractVersion, + contractFixture.requestContractVersion + ); + assert.deepEqual(platforms.results[0], { + slug: 'snes', + name: 'SNES', + gameCount: 1, + }); + assert.equal(game.catalogProvider, 'dat'); + assert.equal( + created.failureCode, + contractFixture.failureExample.failureCode + ); + assert.equal(status.stage, contractFixture.failureExample.stage); + assert.equal(status.percent, null); + assert.deepEqual(requests[5].body, { + externalRequestId: 'request-dat-1', + game: 'Example DAT title', + platform: 'snes', + identity: contractFixture.identityExamples.dat, + }); + assert.deepEqual( + requests.map( + ({ method, path: requestPath }) => `${method} ${requestPath}` + ), + [ + 'GET /api/integration/seerrng/v1/ping', + 'GET /api/integration/seerrng/v1/catalog/dat/platforms', + 'GET /api/integration/seerrng/v1/catalog/dat/search-page', + 'GET /api/integration/seerrng/v1/catalog/dat/browse-page', + `GET /api/integration/seerrng/v1/catalog/dat/games/${contractFixture.identityExamples.dat.catalogKey}`, + 'POST /api/integration/seerrng/v1/requests', + 'GET /api/integration/seerrng/v1/requests/request-dat-1', + ] ); } finally { server.closeAllConnections(); diff --git a/server/api/software/romarrng.ts b/server/api/software/romarrng.ts index aea8d2027b..8e1c4eae13 100644 --- a/server/api/software/romarrng.ts +++ b/server/api/software/romarrng.ts @@ -9,6 +9,7 @@ import type { SoftwareAssetsResponse, SoftwareCatalogGame, SoftwareCatalogPlatform, + SoftwareDatCatalogPlatformsResponse, SoftwareProviderHandshake, SoftwareProviderRequest, } from './types'; @@ -95,7 +96,10 @@ export class ROMarrNGAPI extends ExternalAPI { private async getIntegrationBase(): Promise { const handshake = await this.getHandshake(); - if (handshake.requestContractVersion === 1) { + if ( + handshake.requestContractVersion === 1 || + handshake.requestContractVersion === 2 + ) { return '/api/integration/seerrng/v1'; } if (handshake.requestContractVersion === undefined) { @@ -194,6 +198,68 @@ export class ROMarrNGAPI extends ExternalAPI { ); } + public getDatCatalogPlatforms(): Promise { + return this.getIntegrationBase().then((base) => + this.get(`${base}/catalog/dat/platforms`, {}, 600) + ); + } + + public searchDatCatalogPage( + query: string, + limit = 24, + cursor?: string, + platformSlugs: string[] = [] + ): Promise { + return this.getIntegrationBase().then((base) => + this.get( + `${base}/catalog/dat/search-page`, + { + params: { + q: query, + limit, + ...(cursor ? { cursor } : {}), + ...(platformSlugs.length + ? { platformSlugs: platformSlugs.join(',') } + : {}), + }, + }, + 600 + ) + ); + } + + public browseDatCatalogPage( + limit = 24, + offset = 0, + platformSlugs: string[] = [] + ): Promise { + return this.getIntegrationBase().then((base) => + this.get( + `${base}/catalog/dat/browse-page`, + { + params: { + limit, + offset, + ...(platformSlugs.length + ? { platformSlugs: platformSlugs.join(',') } + : {}), + }, + }, + 600 + ) + ); + } + + public getDatCatalogGame(catalogKey: string): Promise { + return this.getIntegrationBase().then((base) => + this.get( + `${base}/catalog/dat/games/${encodeURIComponent(catalogKey)}`, + {}, + 600 + ) + ); + } + public getPlatforms(forceFresh = false): Promise { return this.get('/api/platforms', {}, forceFresh ? 0 : 300); } @@ -211,7 +277,8 @@ export class ROMarrNGAPI extends ExternalAPI { game: string, platform: string, catalogId?: number, - platformId?: number + platformId?: number, + datIdentity?: { catalogKey: string; platformSlug: string } ): Promise { return this.getIntegrationBase().then((base) => this.post(`${base}/requests`, { @@ -220,7 +287,15 @@ export class ROMarrNGAPI extends ExternalAPI { platform, ...(base.includes('/seerrng/v1') && catalogId ? { identity: { catalogProvider: 'igdb', catalogId, platformId } } - : {}), + : datIdentity && base.includes('/seerrng/v1') + ? { + identity: { + catalogProvider: 'dat', + catalogKey: datIdentity.catalogKey, + platformSlug: datIdentity.platformSlug, + }, + } + : {}), }) ); } diff --git a/server/api/software/types.ts b/server/api/software/types.ts index 83f3976829..9c8f011080 100644 --- a/server/api/software/types.ts +++ b/server/api/software/types.ts @@ -4,6 +4,7 @@ export type SoftwareProviderConnection = SoftwareProviderSettings; export interface SoftwareProviderCapabilities { catalog: boolean; + datCatalog?: boolean; pcAcquisition: boolean; emulationAcquisition: boolean; requestActions: { retry: boolean; cancel: boolean }; @@ -26,7 +27,9 @@ export interface SoftwareProviderActions { export interface SoftwareCatalogGame { id: string; - igdbId: number; + catalogProvider?: 'igdb' | 'dat'; + catalogId?: string; + igdbId?: number; title: string; summary: string; coverUrl: string; @@ -34,13 +37,20 @@ export interface SoftwareCatalogGame { /** Exact day-precision release for the requested IGDB platform, when asked. */ platformReleaseDate?: string | null; platforms: string[]; - platformOptions: { id: number; name: string }[]; + platformOptions: { id?: number; key?: string; name: string }[]; genres: string[]; rating?: number | null; publishers?: string[]; developers?: string[]; screenshots?: string[]; videos?: { name: string; videoId: string }[]; + source?: 'IGDB' | 'DAT'; + dat?: { + name: string; + version: string; + entry: string; + variants: number; + }; } export interface SoftwareCatalogPlatform { @@ -48,6 +58,17 @@ export interface SoftwareCatalogPlatform { name: string; } +export interface SoftwareDatCatalogPlatform { + slug: string; + name: string; + gameCount: number; +} + +export interface SoftwareDatCatalogPlatformsResponse { + results: SoftwareDatCatalogPlatform[]; + unmatchedDatNames: string[]; +} + export interface SoftwareAsset { id: string; name: string; @@ -80,6 +101,10 @@ export type SoftwareProviderStatus = export interface SoftwareProviderRequest { externalRequestId: string; status: SoftwareProviderStatus; + stage?: string | null; + percent?: number | null; + failureCode?: string | null; + failureMessage?: string | null; deliverable: boolean; error?: string | null; title?: string; @@ -88,8 +113,10 @@ export interface SoftwareProviderRequest { platform?: string; identity?: { catalogProvider: string; - catalogId: number; + catalogId?: number; + catalogKey?: string; platformId?: number; + platformSlug?: string; } | null; actions?: SoftwareProviderActions | null; } diff --git a/server/entity/SoftwareRequest.ts b/server/entity/SoftwareRequest.ts index 15c7332bfa..dda2bda274 100644 --- a/server/entity/SoftwareRequest.ts +++ b/server/entity/SoftwareRequest.ts @@ -12,6 +12,7 @@ import { User } from './User'; export type SoftwareRequestCategory = 'retro' | 'modern' | 'game'; export type SoftwareRequestProvider = 'romarr' | 'questarr'; +export type SoftwareCatalogProvider = 'igdb' | 'dat'; export type SoftwareRequestStatus = | 'pending' | 'approved' @@ -64,6 +65,12 @@ export class SoftwareRequest { @Column({ type: 'integer', nullable: true }) public catalogId?: number | null; + @Column({ type: 'varchar', length: 16, default: 'igdb' }) + public catalogProvider: SoftwareCatalogProvider; + + @Column({ type: 'varchar', length: 128, nullable: true }) + public catalogKey?: string | null; + @Column({ type: 'varchar', length: 512 }) public title: string; @@ -94,6 +101,12 @@ export class SoftwareRequest { @Column({ type: 'real', nullable: true }) public percent?: number | null; + @Column({ type: 'varchar', length: 64, nullable: true }) + public providerStage?: string | null; + + @Column({ type: 'varchar', length: 64, nullable: true }) + public failureCode?: string | null; + @Column({ type: 'varchar', length: 512, nullable: true }) public errorMessage?: string | null; diff --git a/server/entity/SoftwareRequestStatusEvent.ts b/server/entity/SoftwareRequestStatusEvent.ts index be540534a0..8a72c8d9f8 100644 --- a/server/entity/SoftwareRequestStatusEvent.ts +++ b/server/entity/SoftwareRequestStatusEvent.ts @@ -31,6 +31,12 @@ export class SoftwareRequestStatusEvent { @Column({ type: 'real', nullable: true }) public percent?: number | null; + @Column({ type: 'varchar', length: 64, nullable: true }) + public providerStage?: string | null; + + @Column({ type: 'varchar', length: 64, nullable: true }) + public failureCode?: string | null; + @Column({ type: 'varchar', length: 255 }) public fingerprint: string; diff --git a/server/lib/releaseCalendar/software.test.ts b/server/lib/releaseCalendar/software.test.ts index 67cb991378..c53ff4a8ee 100644 --- a/server/lib/releaseCalendar/software.test.ts +++ b/server/lib/releaseCalendar/software.test.ts @@ -47,6 +47,7 @@ const configureProviders = () => { }, emulationCatalogProvider: 'romarr', emulationSystemGroups: {}, + emulationPlatformMappings: {}, }; }; diff --git a/server/lib/releaseCalendar/software.ts b/server/lib/releaseCalendar/software.ts index 972ee189cd..e1a4c2d0e4 100644 --- a/server/lib/releaseCalendar/software.ts +++ b/server/lib/releaseCalendar/software.ts @@ -132,9 +132,13 @@ export async function getSoftwareReleaseCalendar( Number(request.catalogId) < 1 ) continue; + const selectedCatalogProvider = + settings.emulationCatalogProvider === 'romarr-dat' + ? 'romarr' + : settings.emulationCatalogProvider; const provider = catalogProviderFor( request.category, - settings.emulationCatalogProvider + selectedCatalogProvider ); const platformId = request.category === 'game' diff --git a/server/lib/settings/index.ts b/server/lib/settings/index.ts index 1ecf645793..87ff263049 100644 --- a/server/lib/settings/index.ts +++ b/server/lib/settings/index.ts @@ -123,8 +123,9 @@ export type EmulationSystemGroup = 'retro' | 'modern'; export interface SoftwareAcquisitionSettings { romarr: SoftwareProviderSettings; questarr: SoftwareProviderSettings; - emulationCatalogProvider: 'questarr' | 'romarr'; + emulationCatalogProvider: 'questarr' | 'romarr' | 'romarr-dat'; emulationSystemGroups: Record; + emulationPlatformMappings: Record; } export interface ProwlarrSettings extends SoftwareProviderSettings { @@ -691,6 +692,7 @@ class Settings { }, emulationCatalogProvider: 'questarr', emulationSystemGroups: {}, + emulationPlatformMappings: {}, }, prowlarr: { hostname: '', @@ -1564,6 +1566,7 @@ class Settings { }, emulationCatalogProvider: 'questarr', emulationSystemGroups: {}, + emulationPlatformMappings: {}, }, prowlarr: { hostname: '', diff --git a/server/lib/softwareCatalogPlatformMapping.ts b/server/lib/softwareCatalogPlatformMapping.ts new file mode 100644 index 0000000000..f80e439c81 --- /dev/null +++ b/server/lib/softwareCatalogPlatformMapping.ts @@ -0,0 +1,44 @@ +export interface CatalogPlatformLabel { + id: number; + name: string; +} + +export interface RomarrPlatformLabels { + slug: string; + name: string; + aliases?: string[]; +} + +export const normalizeCatalogPlatformName = (value: string): string => + value + .normalize('NFKD') + .replace(/[\u0300-\u036f]/g, '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, ' ') + .trim(); + +export const getCatalogPlatformCandidates = ( + system: RomarrPlatformLabels, + platforms: CatalogPlatformLabel[] +): CatalogPlatformLabel[] => { + const names = new Set( + [system.name, system.slug, ...(system.aliases ?? [])] + .map(normalizeCatalogPlatformName) + .filter(Boolean) + ); + return platforms.filter((platform) => + names.has(normalizeCatalogPlatformName(platform.name)) + ); +}; + +/** Automatic mapping is only safe when aliases resolve to one catalog ID. */ +export const getAutomaticCatalogPlatform = ( + system: RomarrPlatformLabels, + platforms: CatalogPlatformLabel[] +): CatalogPlatformLabel | undefined => { + const candidates = getCatalogPlatformCandidates(system, platforms); + const unique = [ + ...new Map(candidates.map((item) => [item.id, item])).values(), + ]; + return unique.length === 1 ? unique[0] : undefined; +}; diff --git a/server/lib/softwareRequests.ts b/server/lib/softwareRequests.ts index 2aaa63e7d6..1936917c46 100644 --- a/server/lib/softwareRequests.ts +++ b/server/lib/softwareRequests.ts @@ -56,11 +56,82 @@ const getProviderSettings = (provider: SoftwareRequestProvider) => { const getQuestarr = () => new QuestarrNGAPI(getProviderSettings('questarr')); const getRomarr = () => new ROMarrNGAPI(getProviderSettings('romarr')); -const safeErrorMessage = (status: SoftwareProviderStatus): string | null => - status === 'failed' - ? 'The acquisition provider could not complete this request.' +const SAFE_FAILURE_CODES = new Set([ + 'REQUEST_FAILED', + 'NO_RELEASE_FOUND', + 'DOWNLOAD_CLIENT_NOT_CONFIGURED', + 'DOWNLOAD_HANDOFF_FAILED', + 'IMPORT_FAILED', +]); + +const normalizePercent = (value: unknown): number | null => + typeof value === 'number' && + Number.isFinite(value) && + value >= 0 && + value <= 100 + ? Math.round(value * 100) / 100 : null; +const normalizeProviderStage = ( + value: unknown, + status: SoftwareProviderStatus +): string => { + if ( + typeof value === 'string' && + /^[a-z][a-z0-9_-]{0,31}$/i.test(value.trim()) + ) { + return value.trim().toLowerCase(); + } + return status; +}; + +const normalizeFailureCode = (value: unknown): string | null => { + if (typeof value !== 'string') return null; + const code = value.trim().toUpperCase(); + return /^[A-Z][A-Z0-9_]{0,63}$/.test(code) ? code : null; +}; + +const safeErrorMessage = ( + status: SoftwareProviderStatus, + failureCode: string | null +): string | null => { + if (status !== 'failed') return null; + if (failureCode && SAFE_FAILURE_CODES.has(failureCode)) { + switch (failureCode) { + case 'NO_RELEASE_FOUND': + return 'No usable release was found.'; + case 'DOWNLOAD_CLIENT_NOT_CONFIGURED': + return 'The acquisition service needs a download client for this release.'; + case 'DOWNLOAD_HANDOFF_FAILED': + return 'The selected release could not be handed to the download client.'; + case 'IMPORT_FAILED': + return 'The download could not be imported into the library.'; + default: + return 'The acquisition provider could not complete this request.'; + } + } + return 'The acquisition provider could not complete this request.'; +}; + +const applyProviderSnapshot = ( + request: SoftwareRequest, + providerRequest: SoftwareProviderRequest +) => { + request.providerStage = normalizeProviderStage( + providerRequest.stage, + providerRequest.status + ); + request.percent = normalizePercent(providerRequest.percent); + request.failureCode = + providerRequest.status === 'failed' + ? normalizeFailureCode(providerRequest.failureCode) + : null; + request.errorMessage = safeErrorMessage( + providerRequest.status, + request.failureCode + ); +}; + const isRecord = (value: unknown): value is Record => !!value && typeof value === 'object' && !Array.isArray(value); @@ -155,7 +226,13 @@ const recordStatusEvent = async ( message: string | null ): Promise => { const repository = getRepository(SoftwareRequestStatusEvent); - const fingerprint = `${request.status}:${request.attempt}:${request.percent ?? 'na'}`; + const fingerprint = [ + request.status, + request.attempt, + request.providerStage ?? 'na', + request.percent ?? 'na', + request.failureCode ?? 'na', + ].join(':'); const existing = await repository.findOneBy({ requestId: request.id, fingerprint, @@ -168,6 +245,8 @@ const recordStatusEvent = async ( status: request.status, message: message?.slice(0, 512) ?? null, percent: request.percent ?? null, + providerStage: request.providerStage ?? null, + failureCode: request.failureCode ?? null, fingerprint, }) ); @@ -298,7 +377,13 @@ const getProviderRequest = async ( request.title, request.platformSlug ?? '', request.catalogId ?? undefined, - request.platformId ?? undefined + request.platformId ?? undefined, + request.catalogProvider === 'dat' && request.catalogKey + ? { + catalogKey: request.catalogKey, + platformSlug: request.platformSlug ?? '', + } + : undefined ); } }; @@ -372,11 +457,23 @@ export const refreshSoftwareRequest = async ( const nextStatus = mapProviderStatus(providerRequest); const previousStatus = request.status; request.status = nextStatus; - request.errorMessage = safeErrorMessage(providerRequest.status); + const previousSnapshot = [ + request.providerStage ?? null, + request.percent ?? null, + request.failureCode ?? null, + request.errorMessage ?? null, + ].join('|'); + applyProviderSnapshot(request, providerRequest); + const nextSnapshot = [ + request.providerStage ?? null, + request.percent ?? null, + request.failureCode ?? null, + request.errorMessage ?? null, + ].join('|'); request.lastCheckedAt = new Date(); - if (nextStatus !== previousStatus) { + if (nextStatus !== previousStatus || previousSnapshot !== nextSnapshot) { await getRepository(SoftwareRequest).save(request); - await recordStatusEvent(request, request.errorMessage); + await recordStatusEvent(request, request.errorMessage ?? null); if (nextStatus === 'available') { await notifySoftwareAvailable(request); } else if (nextStatus === 'failed') { @@ -435,6 +532,9 @@ export const approveSoftwareRequest = async ( approvedById, attempt, errorMessage: null, + failureCode: null, + providerStage: 'approved', + percent: null, } ); if (!result.affected) { @@ -446,6 +546,9 @@ export const approveSoftwareRequest = async ( request.approvedById = approvedById; request.attempt = attempt; request.errorMessage = null; + request.failureCode = null; + request.providerStage = 'approved'; + request.percent = null; await recordStatusEvent(request, 'Request approved.'); await notifySoftwareRequestStatus(request, 'approved'); return refreshSoftwareRequest(request); @@ -539,6 +642,9 @@ export const cancelSoftwareRequest = async ( request.status = 'cancelled'; request.errorMessage = null; + request.failureCode = null; + request.providerStage = 'cancelled'; + request.percent = null; request.lastCheckedAt = new Date(); await getRepository(SoftwareRequest).save(request); await recordStatusEvent(request, 'Request cancelled by requester.'); @@ -563,7 +669,7 @@ export const retrySoftwareRequest = async ( const nextStatus = mapProviderStatus(providerRequest); request.attempt += 1; request.status = nextStatus; - request.errorMessage = safeErrorMessage(providerRequest.status); + applyProviderSnapshot(request, providerRequest); request.lastCheckedAt = new Date(); await getRepository(SoftwareRequest).save(request); await recordStatusEvent(request, request.errorMessage ?? 'Retry started.'); @@ -574,7 +680,7 @@ export const retrySoftwareRequest = async ( request, assets, status: nextStatus, - message: request.errorMessage, + message: request.errorMessage ?? null, actions: resolveProviderActions( request.provider, providerRequest.status, diff --git a/server/migration/postgres/1791100000000-AddSoftwareCatalogIdentityAndProviderProgress.ts b/server/migration/postgres/1791100000000-AddSoftwareCatalogIdentityAndProviderProgress.ts new file mode 100644 index 0000000000..13d02b1bee --- /dev/null +++ b/server/migration/postgres/1791100000000-AddSoftwareCatalogIdentityAndProviderProgress.ts @@ -0,0 +1,50 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddSoftwareCatalogIdentityAndProviderProgress1791100000000 implements MigrationInterface { + name = 'AddSoftwareCatalogIdentityAndProviderProgress1791100000000'; + + async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "software_request" ADD "catalogProvider" character varying(16) NOT NULL DEFAULT 'igdb'` + ); + await queryRunner.query( + 'ALTER TABLE "software_request" ADD "catalogKey" character varying(128)' + ); + await queryRunner.query( + 'ALTER TABLE "software_request" ADD "providerStage" character varying(64)' + ); + await queryRunner.query( + 'ALTER TABLE "software_request" ADD "failureCode" character varying(64)' + ); + await queryRunner.query( + 'UPDATE "software_request" SET "catalogKey" = CAST("catalogId" AS text) WHERE "catalogId" IS NOT NULL' + ); + await queryRunner.query( + 'ALTER TABLE "software_request_status_event" ADD "providerStage" character varying(64)' + ); + await queryRunner.query( + 'ALTER TABLE "software_request_status_event" ADD "failureCode" character varying(64)' + ); + } + + async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + 'ALTER TABLE "software_request_status_event" DROP COLUMN "failureCode"' + ); + await queryRunner.query( + 'ALTER TABLE "software_request_status_event" DROP COLUMN "providerStage"' + ); + await queryRunner.query( + 'ALTER TABLE "software_request" DROP COLUMN "failureCode"' + ); + await queryRunner.query( + 'ALTER TABLE "software_request" DROP COLUMN "providerStage"' + ); + await queryRunner.query( + 'ALTER TABLE "software_request" DROP COLUMN "catalogKey"' + ); + await queryRunner.query( + 'ALTER TABLE "software_request" DROP COLUMN "catalogProvider"' + ); + } +} diff --git a/server/migration/sqlite/1791100000000-AddSoftwareCatalogIdentityAndProviderProgress.test.ts b/server/migration/sqlite/1791100000000-AddSoftwareCatalogIdentityAndProviderProgress.test.ts new file mode 100644 index 0000000000..5b449823c8 --- /dev/null +++ b/server/migration/sqlite/1791100000000-AddSoftwareCatalogIdentityAndProviderProgress.test.ts @@ -0,0 +1,67 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { DataSource } from 'typeorm'; +import { AddSoftwareCatalogIdentityAndProviderProgress1791100000000 } from './1791100000000-AddSoftwareCatalogIdentityAndProviderProgress'; + +test('software catalog identity and provider progress migration backfills IGDB keys', async () => { + const dataSource = await new DataSource({ + type: 'better-sqlite3', + database: ':memory:', + }).initialize(); + const queryRunner = dataSource.createQueryRunner(); + const migration = + new AddSoftwareCatalogIdentityAndProviderProgress1791100000000(); + + try { + await queryRunner.query( + 'CREATE TABLE "software_request" ("id" integer PRIMARY KEY, "catalogId" integer)' + ); + await queryRunner.query( + 'CREATE TABLE "software_request_status_event" ("id" integer PRIMARY KEY)' + ); + await queryRunner.query( + 'INSERT INTO "software_request" ("id", "catalogId") VALUES (1, 42)' + ); + + await migration.up(queryRunner); + + assert.deepEqual( + await queryRunner.query( + 'SELECT "catalogProvider", "catalogKey", "providerStage", "failureCode" FROM "software_request" WHERE "id" = 1' + ), + [ + { + catalogProvider: 'igdb', + catalogKey: '42', + providerStage: null, + failureCode: null, + }, + ] + ); + const eventColumns = await queryRunner.query( + 'PRAGMA table_info("software_request_status_event")' + ); + assert.deepEqual( + eventColumns + .filter((column: { name: string }) => + ['providerStage', 'failureCode'].includes(column.name) + ) + .map((column: { name: string }) => column.name), + ['providerStage', 'failureCode'] + ); + + await migration.down(queryRunner); + const requestColumns = await queryRunner.query( + 'PRAGMA table_info("software_request")' + ); + assert.equal( + requestColumns.some( + (column: { name: string }) => column.name === 'catalogProvider' + ), + false + ); + } finally { + await queryRunner.release(); + await dataSource.destroy(); + } +}); diff --git a/server/migration/sqlite/1791100000000-AddSoftwareCatalogIdentityAndProviderProgress.ts b/server/migration/sqlite/1791100000000-AddSoftwareCatalogIdentityAndProviderProgress.ts new file mode 100644 index 0000000000..70c8a3267b --- /dev/null +++ b/server/migration/sqlite/1791100000000-AddSoftwareCatalogIdentityAndProviderProgress.ts @@ -0,0 +1,50 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddSoftwareCatalogIdentityAndProviderProgress1791100000000 implements MigrationInterface { + name = 'AddSoftwareCatalogIdentityAndProviderProgress1791100000000'; + + async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "software_request" ADD COLUMN "catalogProvider" varchar(16) NOT NULL DEFAULT 'igdb'` + ); + await queryRunner.query( + 'ALTER TABLE "software_request" ADD COLUMN "catalogKey" varchar(128)' + ); + await queryRunner.query( + 'ALTER TABLE "software_request" ADD COLUMN "providerStage" varchar(64)' + ); + await queryRunner.query( + 'ALTER TABLE "software_request" ADD COLUMN "failureCode" varchar(64)' + ); + await queryRunner.query( + 'UPDATE "software_request" SET "catalogKey" = CAST("catalogId" AS TEXT) WHERE "catalogId" IS NOT NULL' + ); + await queryRunner.query( + 'ALTER TABLE "software_request_status_event" ADD COLUMN "providerStage" varchar(64)' + ); + await queryRunner.query( + 'ALTER TABLE "software_request_status_event" ADD COLUMN "failureCode" varchar(64)' + ); + } + + async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + 'ALTER TABLE "software_request_status_event" DROP COLUMN "failureCode"' + ); + await queryRunner.query( + 'ALTER TABLE "software_request_status_event" DROP COLUMN "providerStage"' + ); + await queryRunner.query( + 'ALTER TABLE "software_request" DROP COLUMN "failureCode"' + ); + await queryRunner.query( + 'ALTER TABLE "software_request" DROP COLUMN "providerStage"' + ); + await queryRunner.query( + 'ALTER TABLE "software_request" DROP COLUMN "catalogKey"' + ); + await queryRunner.query( + 'ALTER TABLE "software_request" DROP COLUMN "catalogProvider"' + ); + } +} diff --git a/server/routes/settings/softwareAcquisition.ts b/server/routes/settings/softwareAcquisition.ts index 176506f80c..f1a6818f39 100644 --- a/server/routes/settings/softwareAcquisition.ts +++ b/server/routes/settings/softwareAcquisition.ts @@ -8,6 +8,10 @@ import type { SoftwareProviderSettings, } from '@server/lib/settings'; import { getSettings } from '@server/lib/settings'; +import { + getAutomaticCatalogPlatform, + type CatalogPlatformLabel, +} from '@server/lib/softwareCatalogPlatformMapping'; import { authorizedMutation } from '@server/middleware/authorizedMutation'; import { REDACTED_SECRET, @@ -108,6 +112,38 @@ const parseSystemGroups = ( return { value: groups }; }; +const parsePlatformMappings = ( + value: unknown, + current: SoftwareAcquisitionSettings['emulationPlatformMappings'] +): + | { value: SoftwareAcquisitionSettings['emulationPlatformMappings'] } + | { error: string } => { + if (value === undefined) return { value: current }; + if (!isRecord(value) || Object.keys(value).length > 500) { + return { + error: 'Platform mappings must be an object of at most 500 systems.', + }; + } + const mappings: Record = {}; + for (const [rawSlug, platformId] of Object.entries(value)) { + const slug = rawSlug.trim().toLowerCase(); + if ( + !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(slug) || + !Number.isSafeInteger(platformId) || + (platformId as number) < 1 || + (platformId as number) > 9_999_999_999 || + Object.prototype.hasOwnProperty.call(mappings, slug) + ) { + return { + error: + 'Each platform mapping needs a valid system slug and IGDB platform ID.', + }; + } + mappings[slug] = platformId as number; + } + return { value: mappings }; +}; + const settingsView = (settings: SoftwareAcquisitionSettings) => ({ romarr: { ...settings.romarr, @@ -121,6 +157,7 @@ const settingsView = (settings: SoftwareAcquisitionSettings) => ({ }, emulationCatalogProvider: settings.emulationCatalogProvider ?? 'questarr', emulationSystemGroups: settings.emulationSystemGroups, + emulationPlatformMappings: settings.emulationPlatformMappings ?? {}, }); const hasProviderCapabilities = ( @@ -129,6 +166,7 @@ const hasProviderCapabilities = ( if (!isRecord(value) || !isRecord(value.requestActions)) return false; return ( typeof value.catalog === 'boolean' && + (value.datCatalog === undefined || typeof value.datCatalog === 'boolean') && typeof value.pcAcquisition === 'boolean' && typeof value.emulationAcquisition === 'boolean' && typeof value.requestActions.retry === 'boolean' && @@ -156,7 +194,8 @@ const isSupportedHandshake = ( handshake.apiVersion !== 1 || !expectedServices.includes(service) || (handshake.requestContractVersion !== undefined && - handshake.requestContractVersion !== 1) + handshake.requestContractVersion !== 1 && + handshake.requestContractVersion !== 2) ) { return false; } @@ -203,6 +242,93 @@ softwareAcquisitionRoutes.get('/', (_req, res) => { res.status(200).json(settingsView(getSettings().softwareAcquisition)); }); +softwareAcquisitionRoutes.get( + '/platform-mapping/preview', + async (_req, res) => { + const settings = getSettings().softwareAcquisition; + if (!settings.romarr.hostname || !settings.romarr.apiKey) { + return res.status(503).json({ + error: 'Connect ROMarrNG before previewing platform matches.', + }); + } + try { + const api = new ROMarrNGAPI(settings.romarr); + const [romarrSystems, rawPlatforms] = await Promise.all([ + api.getPlatforms(true), + api.getCatalogPlatforms(), + ]); + const catalogPlatforms = rawPlatforms.filter( + (platform): platform is CatalogPlatformLabel => + Number.isSafeInteger(platform.id) && + platform.id > 0 && + typeof platform.name === 'string' && + platform.name.length > 0 && + platform.name.length <= 128 + ); + const systems = romarrSystems + .filter( + (system) => + typeof system.slug === 'string' && + /^[a-z0-9][a-z0-9_-]{0,63}$/.test(system.slug) && + typeof system.name === 'string' && + system.name.length > 0 + ) + .map((system) => { + const automaticMatch = getAutomaticCatalogPlatform( + system, + catalogPlatforms + ); + const overrideId = + settings.emulationPlatformMappings[system.slug] ?? null; + const selectedMatch = overrideId + ? catalogPlatforms.find((platform) => platform.id === overrideId) + : automaticMatch; + const status = overrideId + ? selectedMatch + ? 'manual' + : 'unmatched' + : automaticMatch + ? 'automatic' + : 'unmatched'; + return { + slug: system.slug, + name: system.name, + aliases: Array.isArray(system.aliases) + ? system.aliases + .filter( + (alias): alias is string => + typeof alias === 'string' && alias.length > 0 + ) + .slice(0, 100) + : [], + automaticMatch: automaticMatch ?? null, + selectedMatch: selectedMatch ?? null, + status, + }; + }); + const usedIds = new Set( + systems.flatMap((system) => + system.selectedMatch ? [system.selectedMatch.id] : [] + ) + ); + return res.status(200).json({ + systems, + catalogPlatforms, + unmatchedSystems: systems + .filter((system) => system.status === 'unmatched') + .map(({ slug, name }) => ({ slug, name })), + unmatchedCatalogPlatforms: catalogPlatforms.filter( + (platform) => !usedIds.has(platform.id) + ), + }); + } catch (error) { + return res.status(502).json({ + error: providerFailureMessage('romarr', 'platform list', error), + }); + } + } +); + softwareAcquisitionRoutes.put( '/', authorizedMutation(Permission.ADMIN, async (req, res) => { @@ -234,41 +360,58 @@ softwareAcquisitionRoutes.put( if ('error' in emulationSystemGroups) { return res.status(400).json({ error: emulationSystemGroups.error }); } + const emulationPlatformMappings = parsePlatformMappings( + req.body.emulationPlatformMappings, + current.emulationPlatformMappings ?? {} + ); + if ('error' in emulationPlatformMappings) { + return res.status(400).json({ error: emulationPlatformMappings.error }); + } const emulationCatalogProvider = req.body.emulationCatalogProvider ?? current.emulationCatalogProvider ?? 'questarr'; if ( emulationCatalogProvider !== 'questarr' && - emulationCatalogProvider !== 'romarr' + emulationCatalogProvider !== 'romarr' && + emulationCatalogProvider !== 'romarr-dat' ) { return res.status(400).json({ - error: 'Emulation catalog provider must be QuestarrNG or ROMarrNG.', + error: + 'Choose QuestarrNG, ROMarrNG IGDB, or ROMarrNG DAT as the emulation catalog.', }); } - if (emulationCatalogProvider === 'romarr') { + if ( + emulationCatalogProvider === 'romarr' || + emulationCatalogProvider === 'romarr-dat' + ) { if (!romarr.value.hostname || !romarr.value.apiKey) { return res.status(400).json({ error: - 'Connect ROMarrNG and confirm its IGDB catalog capability before selecting it as the emulation catalog.', + 'Connect ROMarrNG and confirm the selected catalog capability before choosing it as the emulation catalog.', }); } try { const handshake = await new ROMarrNGAPI(romarr.value).getHandshake(); if ( !isSupportedHandshake('romarr', handshake) || - handshake.capabilities?.catalog !== true + (emulationCatalogProvider === 'romarr' + ? handshake.capabilities?.catalog !== true + : handshake.requestContractVersion !== 2 || + handshake.capabilities?.datCatalog !== true) ) { return res.status(400).json({ error: - 'This ROMarrNG version does not advertise the SeerrNG IGDB catalog. Keep QuestarrNG selected or upgrade ROMarrNG.', + emulationCatalogProvider === 'romarr' + ? 'This ROMarrNG version does not advertise the SeerrNG IGDB catalog. Keep QuestarrNG selected or upgrade ROMarrNG.' + : 'ROMarrNG must advertise the version 2 DAT catalog and have DATs loaded before you select it.', }); } } catch { return res.status(400).json({ error: - 'ROMarrNG could not be reached to confirm its IGDB catalog capability.', + 'ROMarrNG could not be reached to confirm the selected catalog capability.', }); } } @@ -278,6 +421,7 @@ softwareAcquisitionRoutes.put( questarr: questarr.value, emulationCatalogProvider, emulationSystemGroups: emulationSystemGroups.value, + emulationPlatformMappings: emulationPlatformMappings.value, }; const settings = getSettings(); const saved = await settings.persistSection( @@ -328,6 +472,9 @@ softwareAcquisitionRoutes.post( } phase = 'platform list'; const platforms = await api.getPlatforms(true); + const datCatalog = handshake.capabilities?.datCatalog + ? await api.getDatCatalogPlatforms() + : undefined; return res.status(200).json({ success: true, service: 'ROMarrNG', @@ -340,6 +487,12 @@ softwareAcquisitionRoutes.post( ? { capabilities: handshake.capabilities } : {}), platformCount: platforms.length, + ...(datCatalog + ? { + datCatalogPlatformCount: datCatalog.results.length, + unmatchedDatNames: datCatalog.unmatchedDatNames, + } + : {}), }); } diff --git a/server/routes/software.test.ts b/server/routes/software.test.ts index e740247224..f360494725 100644 --- a/server/routes/software.test.ts +++ b/server/routes/software.test.ts @@ -73,6 +73,7 @@ const providerSettings = () => { }, emulationCatalogProvider: 'questarr', emulationSystemGroups: { nes: 'retro' }, + emulationPlatformMappings: {}, }; }; @@ -179,6 +180,8 @@ const createSoftwareRequest = async (options: { status: options.status ?? 'failed', externalRequestId: options.externalRequestId ?? 'seerrng:software:test', catalogId: 42, + catalogProvider: 'igdb', + catalogKey: '42', title: 'Test Game', summary: null, coverUrl: null, @@ -188,6 +191,8 @@ const createSoftwareRequest = async (options: { operatingSystem: null, architecture: null, attempt: 1, + providerStage: null, + failureCode: null, errorMessage: null, lastCheckedAt: null, }) @@ -336,6 +341,53 @@ describe('software request routes', () => { assert.deepStrictEqual(refreshed, [saved.externalRequestId]); }); + it('stores provider progress and safe failure codes in request history', async () => { + const saved = await createSoftwareRequest({ + status: 'approved', + externalRequestId: 'seerrng:software:progress-history', + }); + let providerStatus: SoftwareProviderRequest = { + ...acceptedRequest(saved.externalRequestId, 'downloading'), + stage: 'downloading', + percent: 38.5, + }; + mock.method( + ROMarrNGAPI.prototype, + 'getRequest', + async () => providerStatus + ); + + const progress = await request(createApp()).get( + `/request/software/status/${saved.id}` + ); + assert.strictEqual(progress.status, 200); + assert.strictEqual(progress.body.request.percent, 38.5); + assert.strictEqual(progress.body.request.stage, 'downloading'); + assert.strictEqual(progress.body.history[0].percent, 38.5); + assert.strictEqual(progress.body.history[0].providerStage, 'downloading'); + + providerStatus = { + ...acceptedRequest(saved.externalRequestId, 'failed'), + stage: 'failed', + percent: 143, + failureCode: 'IMPORT_FAILED', + failureMessage: 'A private path must not be shown to users.', + }; + const failed = await request(createApp()).get( + `/request/software/status/${saved.id}` + ); + assert.strictEqual(failed.status, 200); + assert.strictEqual(failed.body.request.percent, null); + assert.strictEqual(failed.body.request.failureCode, 'IMPORT_FAILED'); + assert.strictEqual( + failed.body.request.error, + 'The download could not be imported into the library.' + ); + assert.doesNotMatch(JSON.stringify(failed.body), /private path/); + assert.strictEqual(failed.body.history.length, 2); + assert.strictEqual(failed.body.history[1].failureCode, 'IMPORT_FAILED'); + }); + it('marks PC titles already owned in QuestarrNG as available', async () => { mock.method(QuestarrNGAPI.prototype, 'getCatalogPlatforms', async () => [ { id: 6, name: 'PC (Microsoft Windows)' }, @@ -618,6 +670,69 @@ describe('software request routes', () => { assert.strictEqual(invalid.status, 400); }); + it('previews unique platform matches and returns unmatched systems', async () => { + const app = createOpenApiValidatedSettingsApp(); + mock.method(ROMarrNGAPI.prototype, 'getPlatforms', async () => [ + { + slug: 'nes', + name: 'Nintendo Entertainment System', + aliases: ['Nintendo'], + media: 'rom', + extensions: ['.nes'], + max_size_mb: 16, + }, + { + slug: 'unknown', + name: 'Unlisted Console', + media: 'rom', + extensions: ['.rom'], + max_size_mb: 16, + }, + ]); + mock.method(ROMarrNGAPI.prototype, 'getCatalogPlatforms', async () => [ + { id: 130, name: 'Nintendo Entertainment System' }, + { id: 6, name: 'PC (Microsoft Windows)' }, + ]); + + const response = await request(app).get( + '/api/v1/settings/software-acquisition/platform-mapping/preview' + ); + + assert.strictEqual(response.status, 200); + assert.strictEqual(response.body.systems[0].status, 'automatic'); + assert.strictEqual(response.body.systems[0].automaticMatch.id, 130); + assert.deepStrictEqual(response.body.unmatchedSystems, [ + { slug: 'unknown', name: 'Unlisted Console' }, + ]); + assert.deepStrictEqual(response.body.unmatchedCatalogPlatforms, [ + { id: 6, name: 'PC (Microsoft Windows)' }, + ]); + }); + + it('requires ROMarrNG DAT catalog capability before selecting the DAT source', async () => { + const app = createOpenApiValidatedSettingsApp(); + mock.method(ROMarrNGAPI.prototype, 'getHandshake', async () => ({ + service: 'ROMarrNG', + apiVersion: 1, + requestContractVersion: 2, + capabilities: { + catalog: false, + datCatalog: true, + pcAcquisition: false, + emulationAcquisition: true, + requestActions: { retry: true, cancel: true }, + assetStreaming: true, + }, + })); + + const response = await request(app) + .put('/api/v1/settings/software-acquisition') + .send({ emulationCatalogProvider: 'romarr-dat' }); + + assert.strictEqual(response.status, 200); + assert.strictEqual(response.body.emulationCatalogProvider, 'romarr-dat'); + }); + it('requires ROMarrNG to advertise catalog support before selecting it', async () => { const app = createOpenApiValidatedSettingsApp(); mock.method(ROMarrNGAPI.prototype, 'getHandshake', async () => ({ @@ -978,6 +1093,153 @@ describe('software request routes', () => { ]); }); + it('browses DAT titles, keeps DAT keys, and submits the same identity to ROMarrNG', async () => { + getSettings().softwareAcquisition.emulationCatalogProvider = 'romarr-dat'; + getSettings().softwareAcquisition.emulationSystemGroups = { snes: 'retro' }; + const catalogKey = `dat-${'0'.repeat(64)}`; + const datGame: SoftwareCatalogGame = { + id: catalogKey, + catalogProvider: 'dat', + catalogId: catalogKey, + title: 'Chrono Trigger', + summary: '', + coverUrl: '', + releaseDate: '', + platforms: ['Super Nintendo Entertainment System'], + platformOptions: [ + { key: 'snes', name: 'Super Nintendo Entertainment System' }, + ], + genres: [], + source: 'DAT', + dat: { + name: 'Nintendo - Super Nintendo Entertainment System', + version: '2026', + entry: 'Chrono Trigger (USA)', + variants: 2, + }, + }; + mock.method(ROMarrNGAPI.prototype, 'getPlatforms', async () => [ + { + slug: 'snes', + name: 'Super Nintendo Entertainment System', + media: 'rom', + extensions: ['.sfc'], + max_size_mb: 32, + }, + ]); + mock.method(ROMarrNGAPI.prototype, 'getDatCatalogPlatforms', async () => ({ + results: [{ slug: 'snes', name: 'SNES', gameCount: 1 }], + unmatchedDatNames: [], + })); + const searchDat = mock.method( + ROMarrNGAPI.prototype, + 'searchDatCatalogPage', + async () => ({ results: [datGame], nextCursor: null }) + ); + const browseDat = mock.method( + ROMarrNGAPI.prototype, + 'browseDatCatalogPage', + async () => ({ results: [datGame], nextOffset: 24 }) + ); + const getDatGame = mock.method( + ROMarrNGAPI.prototype, + 'getDatCatalogGame', + async () => datGame + ); + + const systems = await request(createApp()).get( + '/request/software/catalog/systems' + ); + const search = await request(createApp()) + .get('/request/software/catalog/search') + .query({ category: 'retro', q: 'Chrono Trigger' }); + const browse = await request(createApp()) + .get('/request/software/catalog/popular') + .query({ category: 'retro', limit: 24 }); + const detail = await request(createApp()) + .get(`/request/software/catalog/games/${catalogKey}`) + .query({ category: 'retro', catalogProvider: 'dat' }); + + assert.strictEqual(systems.status, 200); + assert.strictEqual(systems.body.catalogProvider, 'dat'); + assert.deepStrictEqual(systems.body.catalogSystemSlugs, ['snes']); + assert.strictEqual(search.status, 200); + assert.strictEqual(search.body.results[0].catalogProvider, 'dat'); + assert.strictEqual(search.body.results[0].catalogId, catalogKey); + assert.deepStrictEqual(search.body.results[0].emulationSystems, [ + { + slug: 'snes', + name: 'Super Nintendo Entertainment System', + group: 'retro', + catalogPlatformKey: 'snes', + }, + ]); + assert.deepStrictEqual(searchDat.mock.calls[0].arguments, [ + 'Chrono Trigger', + 24, + undefined, + ['snes'], + ]); + assert.strictEqual(browse.status, 200); + assert.strictEqual(browse.body.results[0].catalogId, catalogKey); + assert.strictEqual(browse.body.nextOffset, 24); + assert.deepStrictEqual(browseDat.mock.calls[0].arguments, [ + 24, + 0, + ['snes'], + ]); + assert.strictEqual(detail.status, 200); + assert.strictEqual(detail.body.game.catalogProvider, 'dat'); + assert.strictEqual(getDatGame.mock.calls.length, 1); + + const created = await request(createApp()).post('/request/software').send({ + category: 'retro', + catalogProvider: 'dat', + catalogKey, + platformSlug: 'snes', + }); + assert.strictEqual(created.status, 201); + const saved = await getRepository(SoftwareRequest).findOneByOrFail({ + id: created.body.request.id, + }); + assert.strictEqual(saved.catalogProvider, 'dat'); + assert.strictEqual(saved.catalogId, null); + assert.strictEqual(saved.catalogKey, catalogKey); + assert.strictEqual(saved.platformId, null); + + mock.method(ROMarrNGAPI.prototype, 'getRequest', async () => { + throw Object.assign(new Error('Request not found.'), { + response: { status: 404 }, + }); + }); + const dispatched: unknown[] = []; + mock.method( + ROMarrNGAPI.prototype, + 'createRequest', + async ( + externalRequestId: string, + title: string, + platform: string, + _catalogId?: number, + _platformId?: number, + identity?: { catalogKey: string; platformSlug: string } + ) => { + dispatched.push({ externalRequestId, title, platform, identity }); + return acceptedRequest(externalRequestId); + } + ); + const approval = await request( + createApp(1, Permission.MANAGE_REQUESTS) + ).post(`/request/software/status/${saved.id}/approve`); + assert.strictEqual(approval.status, 200); + assert.deepStrictEqual(dispatched[0], { + externalRequestId: saved.externalRequestId, + title: 'Chrono Trigger', + platform: 'snes', + identity: { catalogKey, platformSlug: 'snes' }, + }); + }); + it('passes ROM platform IDs and a search cursor to QuestarrNG', async () => { getSettings().softwareAcquisition.emulationSystemGroups.snes = 'retro'; mock.method(QuestarrNGAPI.prototype, 'getCatalogPlatforms', async () => [ diff --git a/server/routes/software.ts b/server/routes/software.ts index 06d1a43d05..919d608514 100644 --- a/server/routes/software.ts +++ b/server/routes/software.ts @@ -20,6 +20,10 @@ import { enqueueImageCacheWarm } from '@server/lib/imageCacheWarmer'; import { isMediaCategoryEnabled } from '@server/lib/mediaCategories'; import { Permission } from '@server/lib/permissions'; import { getSettings } from '@server/lib/settings'; +import { + getAutomaticCatalogPlatform, + normalizeCatalogPlatformName, +} from '@server/lib/softwareCatalogPlatformMapping'; import { approveSoftwareRequest, cancelSoftwareRequest, @@ -249,19 +253,12 @@ const parseCatalogQuery = ( : null; }; -const normalizePlatformName = (value: string): string => - value - .normalize('NFKD') - .replace(/[\u0300-\u036f]/g, '') - .toLowerCase() - .replace(/[^a-z0-9]+/g, ' ') - .trim(); - const gameOptions = (game: SoftwareCatalogGame) => game.platformOptions.filter( (platform) => - Number.isSafeInteger(platform.id) && - platform.id > 0 && + ((Number.isSafeInteger(platform.id) && (platform.id ?? 0) > 0) || + (typeof platform.key === 'string' && + /^[a-z0-9][a-z0-9_-]{0,63}$/.test(platform.key))) && typeof platform.name === 'string' && platform.name.length > 0 && platform.name.length <= 128 @@ -285,67 +282,89 @@ const isSafeCatalogCoverUrl = (value: unknown): value is string => { } }; -const sanitizeGame = (game: SoftwareCatalogGame): SoftwareCatalogGame => ({ - id: `igdb-${game.igdbId}`, - igdbId: game.igdbId, - title: game.title.slice(0, 512), - summary: typeof game.summary === 'string' ? game.summary.slice(0, 5000) : '', - coverUrl: isSafeCatalogCoverUrl(game.coverUrl) ? game.coverUrl : '', - releaseDate: - typeof game.releaseDate === 'string' ? game.releaseDate.slice(0, 32) : '', - platforms: Array.isArray(game.platforms) - ? game.platforms - .filter((platform): platform is string => typeof platform === 'string') - .slice(0, 100) - .map((platform) => platform.slice(0, 128)) - : [], - platformOptions: gameOptions(game).slice(0, 100), - genres: Array.isArray(game.genres) - ? game.genres - .filter((genre): genre is string => typeof genre === 'string') - .slice(0, 40) - .map((genre) => genre.slice(0, 128)) - : [], - rating: - typeof game.rating === 'number' && - Number.isFinite(game.rating) && - game.rating >= 0 && - game.rating <= 100 - ? Math.round(game.rating) / 10 - : null, - publishers: Array.isArray(game.publishers) - ? game.publishers - .filter((name): name is string => typeof name === 'string') - .slice(0, 20) - .map((name) => name.slice(0, 128)) - : [], - developers: Array.isArray(game.developers) - ? game.developers - .filter((name): name is string => typeof name === 'string') - .slice(0, 20) - .map((name) => name.slice(0, 128)) - : [], - screenshots: Array.isArray(game.screenshots) - ? game.screenshots.filter(isSafeCatalogCoverUrl).slice(0, 12) - : [], - videos: Array.isArray(game.videos) - ? game.videos - .filter( - (video) => - video && - typeof video.videoId === 'string' && - /^[A-Za-z0-9_-]{11}$/.test(video.videoId) - ) - .slice(0, 6) - .map((video) => ({ - name: typeof video.name === 'string' ? video.name.slice(0, 120) : '', - videoId: video.videoId, - })) - : [], -}); +const sanitizeGame = (game: SoftwareCatalogGame): SoftwareCatalogGame => { + const catalogProvider = game.catalogProvider === 'dat' ? 'dat' : 'igdb'; + const catalogId = + catalogProvider === 'dat' + ? typeof game.catalogId === 'string' && + /^dat-[0-9a-f]{64}$/.test(game.catalogId) + ? game.catalogId + : '' + : Number.isSafeInteger(game.igdbId) && (game.igdbId ?? 0) > 0 + ? String(game.igdbId) + : ''; + return { + id: catalogProvider === 'dat' ? catalogId : `igdb-${catalogId}`, + catalogProvider, + catalogId, + ...(catalogProvider === 'igdb' && Number.isSafeInteger(game.igdbId) + ? { igdbId: game.igdbId } + : {}), + title: game.title.slice(0, 512), + summary: + typeof game.summary === 'string' ? game.summary.slice(0, 5000) : '', + coverUrl: isSafeCatalogCoverUrl(game.coverUrl) ? game.coverUrl : '', + releaseDate: + typeof game.releaseDate === 'string' ? game.releaseDate.slice(0, 32) : '', + platforms: Array.isArray(game.platforms) + ? game.platforms + .filter( + (platform): platform is string => typeof platform === 'string' + ) + .slice(0, 100) + .map((platform) => platform.slice(0, 128)) + : [], + platformOptions: gameOptions(game).slice(0, 100), + genres: Array.isArray(game.genres) + ? game.genres + .filter((genre): genre is string => typeof genre === 'string') + .slice(0, 40) + .map((genre) => genre.slice(0, 128)) + : [], + rating: + typeof game.rating === 'number' && + Number.isFinite(game.rating) && + game.rating >= 0 && + game.rating <= 100 + ? Math.round(game.rating) / 10 + : null, + publishers: Array.isArray(game.publishers) + ? game.publishers + .filter((name): name is string => typeof name === 'string') + .slice(0, 20) + .map((name) => name.slice(0, 128)) + : [], + developers: Array.isArray(game.developers) + ? game.developers + .filter((name): name is string => typeof name === 'string') + .slice(0, 20) + .map((name) => name.slice(0, 128)) + : [], + screenshots: Array.isArray(game.screenshots) + ? game.screenshots.filter(isSafeCatalogCoverUrl).slice(0, 12) + : [], + videos: Array.isArray(game.videos) + ? game.videos + .filter( + (video) => + video && + typeof video.videoId === 'string' && + /^[A-Za-z0-9_-]{11}$/.test(video.videoId) + ) + .slice(0, 6) + .map((video) => ({ + name: + typeof video.name === 'string' ? video.name.slice(0, 120) : '', + videoId: video.videoId, + })) + : [], + ...(game.source === 'DAT' ? { source: 'DAT' as const } : {}), + ...(game.dat ? { dat: game.dat } : {}), + }; +}; const isPcPlatformName = (value: string): boolean => { - const name = normalizePlatformName(value); + const name = normalizeCatalogPlatformName(value); return ( name === 'pc microsoft windows' || name === 'pc linux' || @@ -363,7 +382,7 @@ const isPcTargetPlatformName = ( target: CatalogFilters['pcPlatform'] ): boolean => { if (!target) return isPcPlatformName(value); - const name = normalizePlatformName(value); + const name = normalizeCatalogPlatformName(value); if (target === 'windows') { return ['pc microsoft windows', 'microsoft windows', 'windows'].includes( name @@ -406,26 +425,56 @@ const getEmulationPlatforms = async (): Promise< })); }; +const getRomarrApi = (): ROMarrNGAPI => { + const settings = getSettings().softwareAcquisition.romarr; + if (!settings.hostname || !settings.apiKey) { + throw new SoftwareProviderNotConfiguredError('ROMarrNG is not configured.'); + } + return new ROMarrNGAPI(settings); +}; + +const getDatCatalogCategoryContext = async ( + category: SoftwareRequestCategory, + filters: CatalogFilters +) => { + const api = getRomarrApi(); + const [catalog, allSystems] = await Promise.all([ + api.getDatCatalogPlatforms(), + getEmulationPlatforms(), + ]); + const availableSlugs = new Set(catalog.results.map((item) => item.slug)); + const systems = allSystems.filter( + (system) => + system.group === category && + availableSlugs.has(system.slug) && + (!filters.systemSlug || system.slug === filters.systemSlug) + ); + return { api, systems, platformSlugs: systems.map(({ slug }) => slug) }; +}; + const systemMatchesGame = ( system: RomarrPlatform, - game: SoftwareCatalogGame -): { id: number; name: string } | undefined => { + game: SoftwareCatalogGame, + platformMappings: Record = {} +): { id?: number; key?: string; name: string } | undefined => { + const overrideId = platformMappings[system.slug]; + if (overrideId && game.catalogProvider !== 'dat') { + return gameOptions(game).find((platform) => platform.id === overrideId); + } + const datPlatform = gameOptions(game).find( + (platform) => platform.key === system.slug + ); + if (datPlatform) return datPlatform; const names = new Set( [system.name, system.slug, ...(system.aliases ?? [])] - .map(normalizePlatformName) + .map(normalizeCatalogPlatformName) .filter(Boolean) ); return gameOptions(game).find((platform) => - names.has(normalizePlatformName(platform.name)) + names.has(normalizeCatalogPlatformName(platform.name)) ); }; -const systemMatchesPlatform = (system: RomarrPlatform, name: string): boolean => - [system.name, system.slug, ...(system.aliases ?? [])].some( - (candidate) => - normalizePlatformName(candidate) === normalizePlatformName(name) - ); - const getCatalogCategoryContext = async ( api: SoftwareCatalogApi, category: SoftwareRequestCategory, @@ -443,10 +492,18 @@ const getCatalogCategoryContext = async ( ) ), ]); + const mappings = + getSettings().softwareAcquisition.emulationPlatformMappings ?? {}; const matches = (platform: SoftwareCatalogPlatform) => category === 'game' ? isPcTargetPlatformName(platform.name, filters.pcPlatform) - : systems.some((system) => systemMatchesPlatform(system, platform.name)); + : systems.some((system) => { + const overrideId = mappings[system.slug]; + if (overrideId) return platform.id === overrideId; + return ( + getAutomaticCatalogPlatform(system, platforms)?.id === platform.id + ); + }); return { platformIds: platforms .filter(matches) @@ -462,7 +519,8 @@ type CatalogGameResult = SoftwareCatalogGame & { slug: string; name: string; group: 'retro' | 'modern' | null; - catalogPlatformId: number; + catalogPlatformId?: number; + catalogPlatformKey?: string; }[]; }; @@ -470,7 +528,8 @@ const mapCategoryGames = ( games: SoftwareCatalogGame[], category: SoftwareRequestCategory, systems: (RomarrPlatform & { group: 'retro' | 'modern' | null })[], - filters: CatalogFilters + filters: CatalogFilters, + platformMappings: Record = {} ): CatalogGameResult[] => { const sanitized = games.map(sanitizeGame); if (category === 'game') { @@ -482,14 +541,15 @@ const mapCategoryGames = ( } return sanitized.flatMap((game) => { const systemsForGame = systems.flatMap((system) => { - const platform = systemMatchesGame(system, game); + const platform = systemMatchesGame(system, game, platformMappings); return platform ? [ { slug: system.slug, name: system.name, group: system.group, - catalogPlatformId: platform.id, + ...(platform.id ? { catalogPlatformId: platform.id } : {}), + ...(platform.key ? { catalogPlatformKey: platform.key } : {}), }, ] : []; @@ -515,7 +575,18 @@ const addCatalogAvailability = async ( if (!results.length) return []; try { if (category === 'game') { - const ids = [...new Set(results.map((game) => game.igdbId))]; + const ids = [ + ...new Set( + results + .map((game) => game.igdbId) + .filter( + (id): id is number => Number.isSafeInteger(id) && (id ?? 0) > 0 + ) + ), + ]; + if (!ids.length) { + return results.map((game) => ({ ...game, availability: 'unknown' })); + } const response = await getQuestarrApi().lookupLibrary(ids); const statuses = new Map( response.games @@ -523,7 +594,7 @@ const addCatalogAvailability = async ( .map((game) => [game.igdbId, game.status]) ); return results.map((game) => { - const status = statuses.get(game.igdbId); + const status = statuses.get(game.igdbId ?? 0); const availability: CatalogAvailability = status === 'owned' || status === 'completed' ? 'available' @@ -592,10 +663,14 @@ const addTrackedRequestAvailability = async ( ) => { if (!results.length) return results; try { + const catalogKeys = [ + ...new Set(results.map((game) => game.catalogId).filter(Boolean)), + ]; + if (!catalogKeys.length) return results; const requests = await getRepository(SoftwareRequest).find({ where: { category, - catalogId: In(results.map((game) => game.igdbId)), + catalogKey: In(catalogKeys), status: In([ 'pending', 'approved', @@ -608,7 +683,9 @@ const addTrackedRequestAvailability = async ( }); return results.map((game) => { const tracked = requests.filter( - (request) => request.catalogId === game.igdbId + (request) => + request.catalogProvider === (game.catalogProvider ?? 'igdb') && + request.catalogKey === game.catalogId ); const availableSystems = [ ...new Set([ @@ -670,22 +747,25 @@ const getQuestarrApi = (): QuestarrNGAPI => { }; const getCatalogProviderName = (category: SoftwareRequestCategory) => - category !== 'game' && - getSettings().softwareAcquisition.emulationCatalogProvider === 'romarr' - ? 'ROMarrNG' - : 'QuestarrNG'; + category === 'game' + ? 'QuestarrNG' + : getSettings().softwareAcquisition.emulationCatalogProvider === 'romarr' + ? 'ROMarrNG IGDB' + : getSettings().softwareAcquisition.emulationCatalogProvider === + 'romarr-dat' + ? 'ROMarrNG DAT' + : 'QuestarrNG'; const getCatalogApi = ( category: SoftwareRequestCategory ): SoftwareCatalogApi => { const settings = getSettings().softwareAcquisition; - if (category !== 'game' && settings.emulationCatalogProvider === 'romarr') { - if (!settings.romarr.hostname || !settings.romarr.apiKey) { - throw new SoftwareProviderNotConfiguredError( - 'ROMarrNG is not configured.' - ); - } - return new ROMarrNGAPI(settings.romarr); + if ( + category !== 'game' && + (settings.emulationCatalogProvider === 'romarr' || + settings.emulationCatalogProvider === 'romarr-dat') + ) { + return getRomarrApi(); } return getQuestarrApi(); }; @@ -710,6 +790,8 @@ const serializeRequest = ( summary: request.summary ?? null, coverUrl: request.coverUrl ?? null, catalogId: request.catalogId ?? null, + catalogProvider: request.catalogProvider ?? 'igdb', + catalogKey: request.catalogKey ?? null, actions: actions ?? null, platform: request.platformSlug ? { @@ -727,6 +809,8 @@ const serializeRequest = ( : null, attempt: request.attempt, percent: request.percent ?? null, + stage: request.providerStage ?? null, + failureCode: request.failureCode ?? null, error: request.errorMessage ?? null, createdAt: request.createdAt, updatedAt: request.updatedAt, @@ -776,14 +860,16 @@ const respondEmulationCatalogUnavailable = ( : undefined; if ( category === 'game' || - getCatalogProviderName(category) !== 'ROMarrNG' || + !getCatalogProviderName(category).startsWith('ROMarrNG') || (status !== 503 && !(includeNotFound && status === 404)) ) { return false; } res.status(503).json({ error: - 'ROMarrNG’s emulation catalog is unavailable. Configure IGDB and the SeerrNG catalog contract in ROMarrNG, or select QuestarrNG as the emulation catalog source.', + getCatalogProviderName(category) === 'ROMarrNG DAT' + ? 'ROMarrNG’s DAT catalog is unavailable. Load DAT files in ROMarrNG or select another emulation catalog source.' + : 'ROMarrNG’s IGDB catalog is unavailable. Configure IGDB and the SeerrNG catalog contract in ROMarrNG, or select QuestarrNG as the emulation catalog source.', }); return true; }; @@ -792,7 +878,29 @@ softwareRoutes.use(isAuthenticated()); softwareRoutes.get('/catalog/systems', async (_req, res) => { try { - return res.status(200).json({ results: await getEmulationPlatforms() }); + const settings = getSettings().softwareAcquisition; + const results = await getEmulationPlatforms(); + const datCatalog = + settings.emulationCatalogProvider === 'romarr-dat' + ? await getRomarrApi().getDatCatalogPlatforms() + : undefined; + return res.status(200).json({ + results, + catalogProvider: + settings.emulationCatalogProvider === 'romarr-dat' + ? 'dat' + : settings.emulationCatalogProvider === 'romarr' + ? 'igdb' + : 'questarr', + ...(datCatalog + ? { + catalogSystemSlugs: datCatalog.results.map( + (platform) => platform.slug + ), + unmatchedDatNames: datCatalog.unmatchedDatNames, + } + : {}), + }); } catch (error) { return respondProviderError(res, error); } @@ -810,6 +918,43 @@ softwareRoutes.get('/catalog/search', async (req, res) => { } try { + if ( + parsed.category !== 'game' && + getSettings().softwareAcquisition.emulationCatalogProvider === + 'romarr-dat' + ) { + if (parsed.filters.genre || parsed.filters.releaseYear) { + return res.status(400).json({ + error: + 'The DAT catalog does not include genre or release-year filters.', + }); + } + const { api, systems, platformSlugs } = + await getDatCatalogCategoryContext(parsed.category, parsed.filters); + if (!platformSlugs.length) { + return res.status(200).json({ results: [], nextCursor: null }); + } + const page = await api.searchDatCatalogPage( + parsed.query, + parsed.limit, + parsed.cursor, + platformSlugs + ); + const mappings = + getSettings().softwareAcquisition.emulationPlatformMappings ?? {}; + const results = mapCategoryGames( + page.results, + parsed.category, + systems, + parsed.filters, + mappings + ).slice(0, parsed.limit); + enqueueImageCacheWarm(extractImageCacheUrls(results)); + return res.status(200).json({ + results: await catalogResultsWithAvailability(results, parsed.category), + nextCursor: normalizeNextCatalogCursor(page.nextCursor, parsed.cursor), + }); + } const api = getCatalogApi(parsed.category); const { platformIds, systems } = await getCatalogCategoryContext( api, @@ -845,7 +990,7 @@ softwareRoutes.get('/catalog/search', async (req, res) => { } if ( parsed.category !== 'game' && - getCatalogProviderName(parsed.category) === 'ROMarrNG' && + getCatalogProviderName(parsed.category).startsWith('ROMarrNG') && !parsed.cursor && !parsed.filters.genre && !parsed.filters.releaseYear && @@ -878,7 +1023,8 @@ softwareRoutes.get('/catalog/search', async (req, res) => { games, parsed.category, systems, - parsed.filters + parsed.filters, + getSettings().softwareAcquisition.emulationPlatformMappings ?? {} ).slice(0, legacyCatalog ? CATALOG_PROVIDER_FETCH_LIMIT : parsed.limit); enqueueImageCacheWarm(extractImageCacheUrls(results)); return res.status(200).json({ @@ -919,6 +1065,35 @@ softwareRoutes.get('/catalog/popular', async (req, res) => { } try { + if ( + category !== 'game' && + getSettings().softwareAcquisition.emulationCatalogProvider === + 'romarr-dat' + ) { + if (filters.genre || filters.releaseYear) { + return res.status(400).json({ + error: + 'The DAT catalog does not include genre or release-year filters.', + }); + } + const { api, systems, platformSlugs } = + await getDatCatalogCategoryContext(category, filters); + if (!platformSlugs.length) { + return res.status(200).json({ results: [], nextOffset: null }); + } + const page = await api.browseDatCatalogPage(limit, offset, platformSlugs); + const results = mapCategoryGames( + page.results, + category, + systems, + filters + ).slice(0, limit); + enqueueImageCacheWarm(extractImageCacheUrls(results)); + return res.status(200).json({ + results: await catalogResultsWithAvailability(results, category), + nextOffset: normalizeNextCatalogOffset(page.nextOffset, offset), + }); + } const api = getCatalogApi(category); const { platformIds, systems } = await getCatalogCategoryContext( api, @@ -953,7 +1128,7 @@ softwareRoutes.get('/catalog/popular', async (req, res) => { } if ( category !== 'game' && - getCatalogProviderName(category) === 'ROMarrNG' && + getCatalogProviderName(category).startsWith('ROMarrNG') && offset === 0 && !filters.genre && !filters.releaseYear && @@ -978,10 +1153,13 @@ softwareRoutes.get('/catalog/popular', async (req, res) => { nextOffset = null; legacyCatalog = true; } - const results = mapCategoryGames(games, category, systems, filters).slice( - 0, - legacyCatalog ? CATALOG_PROVIDER_FETCH_LIMIT : limit - ); + const results = mapCategoryGames( + games, + category, + systems, + filters, + getSettings().softwareAcquisition.emulationPlatformMappings ?? {} + ).slice(0, legacyCatalog ? CATALOG_PROVIDER_FETCH_LIMIT : limit); enqueueImageCacheWarm(extractImageCacheUrls(results)); return res.status(200).json({ results: await catalogResultsWithAvailability(results, category), @@ -997,11 +1175,24 @@ softwareRoutes.get('/catalog/popular', async (req, res) => { softwareRoutes.get('/catalog/games/:id', async (req, res) => { const category = req.query.category; + const rawCatalogProvider = req.query.catalogProvider; + if ( + rawCatalogProvider !== undefined && + rawCatalogProvider !== 'dat' && + rawCatalogProvider !== 'igdb' + ) { + return res.status(400).json({ + error: 'Choose IGDB or DAT as the catalog provider.', + }); + } + const catalogProvider = rawCatalogProvider === 'dat' ? 'dat' : 'igdb'; const catalogId = Number(req.params.id); + const catalogKey = req.params.id; if ( (category !== 'retro' && category !== 'modern' && category !== 'game') || - !/^[1-9]\d*$/.test(req.params.id) || - !Number.isSafeInteger(catalogId) + (catalogProvider === 'dat' + ? category === 'game' || !/^dat-[0-9a-f]{64}$/.test(catalogKey) + : !/^[1-9]\d*$/.test(req.params.id) || !Number.isSafeInteger(catalogId)) ) { return res .status(400) @@ -1012,10 +1203,23 @@ softwareRoutes.get('/catalog/games/:id', async (req, res) => { } try { - const api = getCatalogApi(category); + const isDat = catalogProvider === 'dat'; if ( + isDat !== + (category !== 'game' && + getSettings().softwareAcquisition.emulationCatalogProvider === + 'romarr-dat') + ) { + return res.status(409).json({ + error: + 'The selected catalog source changed. Reload the title before requesting it.', + }); + } + const api = isDat ? getRomarrApi() : getCatalogApi(category); + if ( + !isDat && category !== 'game' && - getCatalogProviderName(category) === 'ROMarrNG' + getCatalogProviderName(category).startsWith('ROMarrNG') ) { try { await api.getCatalogPlatforms(); @@ -1027,14 +1231,17 @@ softwareRoutes.get('/catalog/games/:id', async (req, res) => { } } const [game, systems] = await Promise.all([ - api.getCatalogGame(catalogId), + isDat + ? getRomarrApi().getDatCatalogGame(catalogKey) + : getCatalogApi(category).getCatalogGame(catalogId), category === 'game' ? Promise.resolve([]) : getEmulationPlatforms(), ]); const result = mapCategoryGames( [game], category, systems.filter((system) => system.group === category), - {} + {}, + getSettings().softwareAcquisition.emulationPlatformMappings ?? {} )[0]; if (!result) { return res @@ -1059,11 +1266,31 @@ softwareRoutes.get('/catalog/games/:id', async (req, res) => { softwareRoutes.post('/', async (req, res) => { const body = isRecord(req.body) ? req.body : {}; const category = body.category; - const catalogId = Number(body.catalogId); + const settings = getSettings().softwareAcquisition; + const expectedCatalogProvider = + category !== 'game' && settings.emulationCatalogProvider === 'romarr-dat' + ? 'dat' + : 'igdb'; + const catalogProvider = + body.catalogProvider === undefined + ? expectedCatalogProvider + : body.catalogProvider; + const catalogKey = + typeof body.catalogKey === 'string' + ? body.catalogKey + : typeof body.catalogId === 'string' + ? body.catalogId + : ''; + const catalogId = + catalogProvider === 'igdb' ? Number(body.catalogId ?? catalogKey) : null; if ( (category !== 'retro' && category !== 'modern' && category !== 'game') || - !Number.isSafeInteger(catalogId) || - catalogId <= 0 + (catalogProvider !== 'igdb' && catalogProvider !== 'dat') || + catalogProvider !== expectedCatalogProvider || + (catalogProvider === 'igdb' && + (!Number.isSafeInteger(catalogId) || (catalogId ?? 0) <= 0)) || + (catalogProvider === 'dat' && + (category === 'game' || !/^dat-[0-9a-f]{64}$/.test(catalogKey))) ) { return res.status(400).json({ error: 'A valid software category and catalog title are required.', @@ -1088,8 +1315,12 @@ softwareRoutes.post('/', async (req, res) => { const repository = getRepository(SoftwareRequest); try { const selectedGame = sanitizeGame( - await getCatalogApi(category).getCatalogGame(catalogId) + catalogProvider === 'dat' + ? await getRomarrApi().getDatCatalogGame(catalogKey) + : await getCatalogApi(category).getCatalogGame(catalogId as number) ); + const selectedCatalogKey = + catalogProvider === 'dat' ? catalogKey : String(catalogId); let provider: SoftwareRequestProvider; let platformSlug: string | null = null; let platformName: string | null = null; @@ -1124,7 +1355,11 @@ softwareRoutes.post('/', async (req, res) => { error: 'Choose a system assigned to this emulation category.', }); } - const catalogPlatform = systemMatchesGame(system, selectedGame); + const catalogPlatform = systemMatchesGame( + system, + selectedGame, + settings.emulationPlatformMappings ?? {} + ); if (!catalogPlatform) { return res .status(400) @@ -1133,13 +1368,18 @@ softwareRoutes.post('/', async (req, res) => { provider = 'romarr'; platformSlug = system.slug; platformName = system.name; - platformId = catalogPlatform.id; + platformId = catalogPlatform.id ?? null; } const query = repository .createQueryBuilder('request') .where('request.requestedById = :userId', { userId: req.user.id }) - .andWhere('request.catalogId = :catalogId', { catalogId }) + .andWhere('request.catalogProvider = :catalogProvider', { + catalogProvider, + }) + .andWhere('request.catalogKey = :catalogKey', { + catalogKey: selectedCatalogKey, + }) .andWhere('request.category = :category', { category }) .andWhere('request.status IN (:...statuses)', { statuses: [...ACTIVE_STATUSES, 'available'], @@ -1167,7 +1407,9 @@ softwareRoutes.post('/', async (req, res) => { provider, status: 'pending', externalRequestId: `seerrng:software:${randomUUID()}`, - catalogId, + catalogId: catalogId ?? null, + catalogProvider, + catalogKey: selectedCatalogKey, title: selectedGame.title, summary: selectedGame.summary, coverUrl: selectedGame.coverUrl, @@ -1177,6 +1419,8 @@ softwareRoutes.post('/', async (req, res) => { operatingSystem: variant?.operatingSystem ?? null, architecture: variant?.architecture ?? null, attempt: 0, + providerStage: 'pending', + failureCode: null, errorMessage: null, }); await repository.save(request); @@ -1187,7 +1431,10 @@ softwareRoutes.post('/', async (req, res) => { requestedById: request.requestedById, status: request.status, message: 'Request submitted.', - fingerprint: `${request.status}:0`, + providerStage: request.providerStage, + failureCode: null, + percent: null, + fingerprint: `${request.status}:0:${request.providerStage}:na:na`, }) ); diff --git a/src/components/RequestStatus/SoftwareRequests.tsx b/src/components/RequestStatus/SoftwareRequests.tsx index 21f688107d..361629d38c 100644 --- a/src/components/RequestStatus/SoftwareRequests.tsx +++ b/src/components/RequestStatus/SoftwareRequests.tsx @@ -74,6 +74,9 @@ const messages = defineMessages('components.RequestStatus.SoftwareRequests', { historyLoading: 'Loading status history…', historyError: 'Status history could not be loaded.', noHistory: 'No saved status updates are available.', + failureCode: 'Failure code: {code}', + progress: '{percent}% downloaded', + stage: 'Stage: {stage}', }); type SoftwareStatus = @@ -95,6 +98,10 @@ interface SoftwareRequestRow { status: SoftwareStatus; title: string; coverUrl?: string | null; + percent?: number | null; + stage?: string | null; + failureCode?: string | null; + error?: string | null; platform?: { slug: string; name: string | null; @@ -130,6 +137,8 @@ interface SoftwareRequestHistoryResponse { status: SoftwareStatus; message?: string | null; percent?: number | null; + providerStage?: string | null; + failureCode?: string | null; createdAt: string; }[]; } @@ -515,6 +524,57 @@ const SoftwareRequests = ({ {message && status === 'failed' && (

{message}

)} + {status === 'failed' && request.failureCode && ( +

+ {intl.formatMessage(messages.failureCode, { + code: request.failureCode, + })} +

+ )} + {status === 'downloading' && + request.percent != null && + Number.isFinite(request.percent) && + request.percent >= 0 && + request.percent <= 100 && ( +
+
+ + {intl.formatMessage(messages.progress, { + percent: request.percent + .toFixed(1) + .replace(/\.0$/, ''), + })} + + {request.stage && request.stage !== status && ( + + {intl.formatMessage(messages.stage, { + stage: request.stage.replace(/[_-]+/g, ' '), + })} + + )} +
+
+
+
+
+ )} {request.actions?.cancel === false && request.actions.cancelReason && (

@@ -670,6 +730,9 @@ const SoftwareRequests = ({ > {statusLabel(event.status)} + {event.providerStage && + event.providerStage !== event.status && + ` · ${event.providerStage.replace(/[_-]+/g, ' ')}`} {event.percent !== null && event.percent !== undefined && ` · ${Math.round(event.percent)}%`} @@ -688,6 +751,13 @@ const SoftwareRequests = ({ {event.message}

)} + {event.failureCode && ( +

+ {intl.formatMessage(messages.failureCode, { + code: event.failureCode, + })} +

+ )} ))} diff --git a/src/components/Settings/SettingsSoftwareAcquisition.tsx b/src/components/Settings/SettingsSoftwareAcquisition.tsx index 6eb0f1371b..65dbd7db47 100644 --- a/src/components/Settings/SettingsSoftwareAcquisition.tsx +++ b/src/components/Settings/SettingsSoftwareAcquisition.tsx @@ -40,6 +40,11 @@ const messages = defineMessages('components.SettingsSoftwareAcquisition', { catalogReady: 'IGDB catalog ready', catalogUnavailable: 'This ROMarrNG version does not advertise the SeerrNG IGDB catalog. QuestarrNG remains the default.', + datCatalogReady: 'DAT catalog ready for {count} systems', + datCatalogUnavailable: + 'This ROMarrNG version does not advertise a loaded DAT catalog.', + unmatchedDatNames: + '{count} DAT names are not linked to a ROMarrNG system: {names}', contractVersion: 'Integration API v{version}', saved: 'Software acquisition settings saved.', systemGroups: 'Emulation system groups', @@ -69,7 +74,23 @@ const messages = defineMessages('components.SettingsSoftwareAcquisition', { saveError: 'Settings could not be saved.', emulationCatalog: 'Emulation catalog source', emulationCatalogDescription: - 'QuestarrNG is the default. Choose ROMarrNG only when its connection test reports the SeerrNG IGDB catalog capability. ROMarrNG still acquires ROM requests; PC game requests always use QuestarrNG.', + 'QuestarrNG is the default. ROMarrNG can provide its IGDB catalog or a DAT-backed catalog when DAT files are loaded. ROMarrNG still acquires ROM requests; PC game requests always use QuestarrNG.', + platformMappings: 'ROMarrNG to IGDB platform matching', + platformMappingsDescription: + 'SeerrNG matches system names and aliases automatically when they resolve to one IGDB platform. Preview the matches and choose an override for systems that need a different platform.', + previewPlatformMappings: 'Preview platform matches', + loadingPlatformMappings: 'Loading platform matches…', + automaticMatch: 'Automatic match', + unmatched: 'No automatic match', + manualMatch: 'Manual match', + unavailableMatch: 'Saved platform is unavailable', + unmatchedSystems: 'Systems without a match: {count}', + unusedCatalogPlatforms: 'Unused IGDB platforms: {count}', + platformPreviewError: 'Platform matches could not be loaded.', + platformMappingHelp: + 'Choosing Automatic match removes a saved override. A system without a match is hidden from the ROM catalog until you choose an IGDB platform.', + unmatchedDatSystems: + '{count} DAT names are not linked to a ROMarrNG system. Update ROMarrNG platform aliases to include them: {names}', }); interface ProviderSettings { @@ -86,7 +107,8 @@ interface SoftwareSettingsResponse { romarr: Omit; questarr: Omit; emulationSystemGroups: Record; - emulationCatalogProvider: 'questarr' | 'romarr'; + emulationCatalogProvider: 'questarr' | 'romarr' | 'romarr-dat'; + emulationPlatformMappings: Record; } interface EmulationSystem { @@ -97,6 +119,22 @@ interface EmulationSystem { interface SystemResponse { results: EmulationSystem[]; + catalogProvider?: 'questarr' | 'igdb' | 'dat'; + catalogSystemSlugs?: string[]; + unmatchedDatNames?: string[]; +} + +interface PlatformMappingPreview { + systems: { + slug: string; + name: string; + automaticMatch: { id: number; name: string } | null; + selectedMatch: { id: number; name: string } | null; + status: 'automatic' | 'manual' | 'unmatched'; + }[]; + catalogPlatforms: { id: number; name: string }[]; + unmatchedSystems: { slug: string; name: string }[]; + unmatchedCatalogPlatforms: { id: number; name: string }[]; } interface TestState { @@ -143,8 +181,15 @@ const SettingsSoftwareAcquisition = () => { Record >({}); const [emulationCatalogProvider, setEmulationCatalogProvider] = useState< - 'questarr' | 'romarr' + 'questarr' | 'romarr' | 'romarr-dat' >('questarr'); + const [emulationPlatformMappings, setEmulationPlatformMappings] = useState< + Record + >({}); + const [mappingPreview, setMappingPreview] = + useState(null); + const [mappingPreviewError, setMappingPreviewError] = useState(''); + const [loadingMappingPreview, setLoadingMappingPreview] = useState(false); const [saving, setSaving] = useState(false); const [testing, setTesting] = useState<'romarr' | 'questarr' | null>(null); const [testState, setTestState] = useState(null); @@ -159,6 +204,7 @@ const SettingsSoftwareAcquisition = () => { setQuestarr(toProviderState(data.questarr)); setEmulationCatalogProvider(data.emulationCatalogProvider ?? 'questarr'); setSystemGroups(data.emulationSystemGroups ?? {}); + setEmulationPlatformMappings(data.emulationPlatformMappings ?? {}); }, [data]); const updateProvider = ( @@ -182,6 +228,26 @@ const SettingsSoftwareAcquisition = () => { }); }; + const previewPlatformMappings = async () => { + setLoadingMappingPreview(true); + setMappingPreviewError(''); + try { + const response = await axios.get( + '/api/v1/settings/software-acquisition/platform-mapping/preview' + ); + setMappingPreview(response.data); + } catch (error) { + const detail = + axios.isAxiosError(error) && + typeof error.response?.data?.error === 'string' + ? error.response.data.error + : intl.formatMessage(messages.platformPreviewError); + setMappingPreviewError(detail); + } finally { + setLoadingMappingPreview(false); + } + }; + const testProvider = async (provider: 'romarr' | 'questarr') => { const current = provider === 'romarr' ? romarr : questarr; if (!current) return; @@ -193,7 +259,9 @@ const SettingsSoftwareAcquisition = () => { platformCount?: number; apiVersion?: number; requestContractVersion?: number; - capabilities?: { catalog?: boolean }; + capabilities?: { catalog?: boolean; datCatalog?: boolean }; + datCatalogPlatformCount?: number; + unmatchedDatNames?: string[]; }>( `/api/v1/settings/software-acquisition/test/${provider}`, getProviderPayload(current) @@ -207,14 +275,33 @@ const SettingsSoftwareAcquisition = () => { : intl.formatMessage(messages.connectionSuccess, { service: response.data.service, }); - const providerDetail = + const providerDetails = provider === 'romarr' - ? intl.formatMessage( - response.data.capabilities?.catalog - ? messages.catalogReady - : messages.catalogUnavailable - ) - : ''; + ? [ + intl.formatMessage( + response.data.capabilities?.catalog + ? messages.catalogReady + : messages.catalogUnavailable + ), + response.data.capabilities?.datCatalog && + typeof response.data.datCatalogPlatformCount === 'number' + ? intl.formatMessage(messages.datCatalogReady, { + count: response.data.datCatalogPlatformCount, + }) + : intl.formatMessage(messages.datCatalogUnavailable), + ...(response.data.unmatchedDatNames?.length + ? [ + intl.formatMessage(messages.unmatchedDatNames, { + count: response.data.unmatchedDatNames.length, + names: response.data.unmatchedDatNames + .slice(0, 4) + .join(', '), + }), + ] + : []), + ] + : []; + const providerDetail = providerDetails.join(' · '); setTestState({ provider, success: true, @@ -265,6 +352,7 @@ const SettingsSoftwareAcquisition = () => { questarr: getProviderPayload(questarr), emulationCatalogProvider, emulationSystemGroups: systemGroups, + emulationPlatformMappings, }); await Promise.all([ mutate('/api/v1/settings/software-acquisition'), @@ -431,6 +519,31 @@ const SettingsSoftwareAcquisition = () => { ); } + const selectedPlatformForSystem = ( + system: PlatformMappingPreview['systems'][number] + ) => { + const override = emulationPlatformMappings[system.slug]; + return override + ? (mappingPreview?.catalogPlatforms.find( + (platform) => platform.id === override + ) ?? null) + : system.automaticMatch; + }; + const unmatchedSystemCount = + mappingPreview?.systems.filter( + (system) => !selectedPlatformForSystem(system) + ).length ?? 0; + const selectedPlatformIds = new Set( + (mappingPreview?.systems ?? []).flatMap((system) => { + const platform = selectedPlatformForSystem(system); + return platform ? [platform.id] : []; + }) + ); + const unusedCatalogPlatformCount = + mappingPreview?.catalogPlatforms.filter( + (platform) => !selectedPlatformIds.has(platform.id) + ).length ?? 0; + return ( <>
@@ -445,30 +558,134 @@ const SettingsSoftwareAcquisition = () => { {renderProvider('questarr', questarr)}
-
-

+
+

{intl.formatMessage(messages.emulationCatalog)}

-

+

{intl.formatMessage(messages.emulationCatalogDescription)}

-
+
+

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

+

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

+ + {mappingPreviewError && ( + + )} + {mappingPreview && ( + <> +

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

+
+
+ {mappingPreview.systems.map((system) => { + const override = emulationPlatformMappings[system.slug]; + const selectedMatch = selectedPlatformForSystem(system); + const status = override + ? selectedMatch + ? 'manual' + : 'unmatched' + : system.automaticMatch + ? 'automatic' + : 'unmatched'; + return ( +
+
+
{system.name}
+
+ {intl.formatMessage( + override && !selectedMatch + ? messages.unavailableMatch + : status === 'manual' + ? messages.manualMatch + : status === 'automatic' + ? messages.automaticMatch + : messages.unmatched + )} + {selectedMatch ? ` · ${selectedMatch.name}` : ''} +
+ +
+
+ ); + })} +
+
+
+

+ {intl.formatMessage(messages.unmatchedSystems, { + count: unmatchedSystemCount, + })} +

+

+ {intl.formatMessage(messages.unusedCatalogPlatforms, { + count: unusedCatalogPlatformCount, + })} +

+
+ + )} +
+
@@ -498,6 +715,18 @@ const SettingsSoftwareAcquisition = () => { {intl.formatMessage(messages.systemGroupsSourceHint)}

) : null} + {systemsData?.catalogProvider === 'dat' && + systemsData.unmatchedDatNames?.length ? ( +
+ +
+ ) : null}
{systemsLoading ? ( diff --git a/src/components/SoftwareCatalog/index.tsx b/src/components/SoftwareCatalog/index.tsx index 8ba90762a2..ee7380189c 100644 --- a/src/components/SoftwareCatalog/index.tsx +++ b/src/components/SoftwareCatalog/index.tsx @@ -51,6 +51,8 @@ const messages = defineMessages('components.SoftwareCatalog', { searchPlaceholder: 'Search software titles', search: 'Search', popular: 'Popular titles', + browseDat: 'Browse DAT titles', + datCatalog: 'DAT catalog', noResults: 'No titles match this search.', loadMore: 'Load more titles', retryLoad: 'Retry loading titles', @@ -59,6 +61,10 @@ const messages = defineMessages('components.SoftwareCatalog', { 'Update QuestarrNG to browse software by genre or release year.', configureHint: 'Ask an administrator to connect QuestarrNG and the required acquisition service in Settings → Services.', + datConfigureHint: + 'Ask an administrator to load DAT files in ROMarrNG and select ROMarrNG · DAT in Settings → Services.', + datUnavailable: + 'The ROMarrNG DAT catalog is unavailable. Ask an administrator to check that DAT files are loaded.', request: 'Request', details: 'Details', requestTitle: 'Request {title}', @@ -114,13 +120,15 @@ interface CatalogSystemOption { interface CatalogGame { id: string; - igdbId: number; + catalogProvider: 'igdb' | 'dat'; + catalogId: string; + igdbId?: number; title: string; summary: string; coverUrl: string; releaseDate: string; platforms: string[]; - platformOptions: { id: number; name: string }[]; + platformOptions: { id?: number; key?: string; name: string }[]; genres: string[]; emulationSystems?: EmulationSystemOption[]; availability?: @@ -177,23 +185,27 @@ const SoftwareCatalog = ({ const [requestError, setRequestError] = useState(''); const [requestSuccess, setRequestSuccess] = useState(''); const [requesting, setRequesting] = useState(false); - const hydratedGameId = useRef(undefined); + const hydratedGameId = useRef(undefined); const openedFromCatalog = useRef(false); const linkedCategory = typeof router.query.category === 'string' && categories.includes(router.query.category as Category) ? (router.query.category as Category) : undefined; + const linkedCatalogProvider = + router.query.catalogProvider === 'dat' ? 'dat' : 'igdb'; const linkedGameId = typeof router.query.game === 'string' && - /^[1-9]\d*$/.test(router.query.game) - ? Number(router.query.game) + (linkedCatalogProvider === 'dat' + ? /^dat-[0-9a-f]{64}$/.test(router.query.game) + : /^[1-9]\d*$/.test(router.query.game)) + ? router.query.game : undefined; const { data: linkedGame, error: linkedGameError } = useSWR<{ game: CatalogGame; }>( - linkedCategory && Number.isSafeInteger(linkedGameId) - ? `/api/v1/request/software/catalog/games/${linkedGameId}?category=${linkedCategory}` + linkedCategory && linkedGameId + ? `/api/v1/request/software/catalog/games/${encodeURIComponent(linkedGameId)}?category=${linkedCategory}&catalogProvider=${linkedCatalogProvider}` : null ); @@ -207,7 +219,11 @@ const SoftwareCatalog = ({ openedFromCatalog.current = false; hydratedGameId.current = undefined; setSelectedGame(null); - } else if (linkedGame?.game && linkedGame.game.igdbId === linkedGameId) { + } else if ( + linkedGame?.game && + linkedGame.game.catalogId === linkedGameId && + linkedGame.game.catalogProvider === linkedCatalogProvider + ) { if (hydratedGameId.current !== linkedGameId) { hydratedGameId.current = linkedGameId; setSelectedSystem(linkedGame.game.emulationSystems?.[0]?.slug ?? ''); @@ -216,7 +232,7 @@ const SoftwareCatalog = ({ } setSelectedGame(linkedGame.game); } - }, [linkedGame?.game, linkedGameId, router.isReady]); + }, [linkedGame?.game, linkedCatalogProvider, linkedGameId, router.isReady]); const visibleCategories = categories.filter((value) => { if (!isAnySoftwareCategoryEnabled(currentSettings)) return false; @@ -231,13 +247,25 @@ const SoftwareCatalog = ({ const selectedCategory = visibleCategories.includes(category) ? category : (visibleCategories[0] ?? category); - const { data: systemCatalog } = useSWR<{ results: CatalogSystemOption[] }>( + const { data: systemCatalog } = useSWR<{ + results: CatalogSystemOption[]; + catalogProvider?: 'questarr' | 'igdb' | 'dat'; + catalogSystemSlugs?: string[]; + }>( selectedCategory !== 'game' && visibleCategories.length ? '/api/v1/request/software/catalog/systems' : null ); + const catalogProvider = + selectedCategory === 'game' + ? 'igdb' + : (systemCatalog?.catalogProvider ?? 'igdb'); + const isDatCatalog = catalogProvider === 'dat'; + const datSystemSlugs = new Set(systemCatalog?.catalogSystemSlugs ?? []); const systemsForCategory = (systemCatalog?.results ?? []).filter( - (system) => system.group === selectedCategory + (system) => + system.group === selectedCategory && + (!isDatCatalog || datSystemSlugs.has(system.slug)) ); const query = (externalQuery ?? submittedQuery).trim(); @@ -264,7 +292,11 @@ const SoftwareCatalog = ({ }); const getCatalogKey = useCallback( (pageIndex: number, previousPage: CatalogResponse | null) => { - if (visibleCategories.length === 0 || !validReleaseYear) return null; + if ( + visibleCategories.length === 0 || + (!isDatCatalog && !validReleaseYear) + ) + return null; if (pageIndex > 0 && !previousPage) return null; const params = new URLSearchParams({ category: selectedCategory, @@ -275,8 +307,12 @@ const SoftwareCatalog = ({ } else if (selectedCategory !== 'game' && systemFilter) { params.set('system', systemFilter); } - if (genreFilter.trim()) params.set('genre', genreFilter.trim()); - if (releaseYearFilter) params.set('releaseYear', releaseYearFilter); + if (!isDatCatalog && genreFilter.trim()) { + params.set('genre', genreFilter.trim()); + } + if (!isDatCatalog && releaseYearFilter) { + params.set('releaseYear', releaseYearFilter); + } if (query) { params.set('q', query); if (pageIndex > 0) { @@ -300,6 +336,7 @@ const SoftwareCatalog = ({ systemFilter, validReleaseYear, visibleCategories.length, + isDatCatalog, ] ); const { @@ -315,11 +352,11 @@ const SoftwareCatalog = ({ dedupingInterval: 30000, }); const games = useMemo(() => { - const seen = new Set(); + const seen = new Set(); return (pages ?? []).flatMap((page) => page.results.filter((game) => { - if (seen.has(game.igdbId)) return false; - seen.add(game.igdbId); + if (seen.has(`${game.catalogProvider}:${game.catalogId}`)) return false; + seen.add(`${game.catalogProvider}:${game.catalogId}`); return true; }) ); @@ -335,7 +372,11 @@ const SoftwareCatalog = ({ error.response.data?.error === 'Upgrade QuestarrNG to use software genre and year filters.' ? messages.upgradeQuestarr - : messages.loadError; + : isDatCatalog && + axios.isAxiosError(error) && + error.response?.status === 503 + ? messages.datUnavailable + : messages.loadError; useEffect(() => { if (loadMoreInView && hasMore && !isLoadingMore && !error) { @@ -345,7 +386,7 @@ const SoftwareCatalog = ({ const openRequest = (game: CatalogGame) => { openedFromCatalog.current = true; - hydratedGameId.current = game.igdbId; + hydratedGameId.current = game.catalogId; setSelectedGame(game); setSelectedSystem(game.emulationSystems?.[0]?.slug ?? ''); setVariant({ @@ -359,7 +400,8 @@ const SoftwareCatalog = ({ query: { ...router.query, category: selectedCategory, - game: game.igdbId, + game: game.catalogId, + catalogProvider: game.catalogProvider, }, }, undefined, @@ -375,6 +417,7 @@ const SoftwareCatalog = ({ } const nextQuery = { ...router.query }; delete nextQuery.game; + delete nextQuery.catalogProvider; void router.replace( { pathname: router.pathname, query: nextQuery }, undefined, @@ -398,7 +441,10 @@ const SoftwareCatalog = ({ '/api/v1/request/software', { category: selectedCategory, - catalogId: selectedGame.igdbId, + catalogProvider: selectedGame.catalogProvider, + ...(selectedGame.catalogProvider === 'dat' + ? { catalogKey: selectedGame.catalogId } + : { catalogId: selectedGame.igdbId }), ...(selectedCategory === 'game' ? { variant: { @@ -538,28 +584,32 @@ const SoftwareCatalog = ({ ))} - setGenreInput(event.target.value)} - /> - setReleaseYearInput(event.target.value)} - /> + {!isDatCatalog && ( + <> + setGenreInput(event.target.value)} + /> + setReleaseYearInput(event.target.value)} + /> + + )}
)} - {!validReleaseYear && ( + {!isDatCatalog && !validReleaseYear && (

{intl.formatMessage(messages.invalidReleaseYear)}

@@ -612,9 +662,14 @@ const SoftwareCatalog = ({

{query ? intl.formatMessage(messages.searchPlaceholder) - : intl.formatMessage(messages.popular)} + : intl.formatMessage( + isDatCatalog ? messages.browseDat : messages.popular + )}

- {categoryTitle} + + {categoryTitle} + {isDatCatalog && ` · ${intl.formatMessage(messages.datCatalog)}`} +

{visibleCategories.length === 0 ? ( @@ -628,9 +683,14 @@ const SoftwareCatalog = ({ ) : error && !games.length ? (

{intl.formatMessage(catalogErrorMessage)}

- {catalogErrorMessage === messages.loadError && ( + {(catalogErrorMessage === messages.loadError || + catalogErrorMessage === messages.datUnavailable) && (

- {intl.formatMessage(messages.configureHint)} + {intl.formatMessage( + isDatCatalog + ? messages.datConfigureHint + : messages.configureHint + )}

)}
@@ -643,7 +703,7 @@ const SoftwareCatalog = ({ )}

+ {overrideRuleModal.open && radarrData && diff --git a/src/components/Settings/SettingsTunerr.tsx b/src/components/Settings/SettingsTunerr.tsx new file mode 100644 index 0000000000..d84269c5f8 --- /dev/null +++ b/src/components/Settings/SettingsTunerr.tsx @@ -0,0 +1,444 @@ +import Alert from '@app/components/Common/Alert'; +import Button from '@app/components/Common/Button'; +import LoadingSpinner from '@app/components/Common/LoadingSpinner'; +import SettingsField from '@app/components/Settings/SettingsField'; +import { useLiveTvStatus } from '@app/hooks/useLiveTv'; +import useToasts from '@app/hooks/useToasts'; +import defineMessages from '@app/utils/defineMessages'; +import type { TunerrSettings } from '@server/lib/settings'; +import axios from 'axios'; +import type { FormEvent } from 'react'; +import { useEffect, useState } from 'react'; +import { useIntl } from 'react-intl'; +import useSWR from 'swr'; + +const REDACTED = '[REDACTED]'; + +const messages = defineMessages('components.Settings.SettingsTunerr', { + title: 'Live TV (IPTV Tunerr)', + description: + 'Connect IPTV Tunerr so people can see when a movie or series airs on Live TV and request recordings. Recording requests use the same approval rules as other requests.', + setupNote: + 'SeerrNG talks to the Tunerr deck with its username and password. Set IPTV_TUNERR_WEBUI_ALLOW_LAN=1 on Tunerr so the deck accepts connections from SeerrNG, and run the Tunerr recorder with recording rules enabled.', + loadError: 'Tunerr settings could not be loaded.', + enabled: 'Enable Live TV', + hostname: 'Hostname or IP Address', + useSsl: 'Use HTTPS', + baseUrl: 'Deck URL Base', + deckPort: 'Deck Port', + tunerPort: 'Tuner Port', + guideUrl: 'Guide URL', + guideUrlDescription: + 'Leave empty to read /guide.xml from the tuner port. Set this when the guide is served from somewhere else.', + guideHours: 'Guide Window (Hours)', + guideHoursDescription: + 'How far ahead SeerrNG looks for airings. Larger windows use more memory.', + username: 'Deck Username', + password: 'Deck Password', + savedSecret: 'Saved — leave empty to keep it', + clearSecret: 'Remove the saved password', + test: 'Test Connection', + testing: 'Testing…', + testOk: 'Connected to the Tunerr deck and guide.', + testMissing: + 'Connected, but this Tunerr version cannot record SeerrNG requests (missing: {features}). Update Tunerr to enable recording.', + testGuideFailed: 'Guide: {error}', + guideStatus: + 'Guide loaded: {programmes} programmes on {channels} channels, refreshed {time}.', + guideTruncated: + 'The guide is larger than SeerrNG indexes; shorten the guide window to include every channel.', + guideError: 'Last guide refresh failed: {error}', + save: 'Save Changes', + saving: 'Saving…', + cancel: 'Discard Changes', + unsavedChanges: 'You have unsaved changes.', + saveSuccess: 'Tunerr settings saved.', + saveError: 'Tunerr settings could not be saved.', +}); + +type Draft = Omit & { + deckPort: string; + tunerPort: string; + guideHours: string; + clearPassword: boolean; +}; + +interface TestResult { + deck: boolean; + guide: boolean; + missingFeatures: string[]; + error?: string; + guideError?: string; +} + +const toDraft = (settings: TunerrSettings): Draft => ({ + ...settings, + deckPort: String(settings.deckPort), + tunerPort: String(settings.tunerPort), + guideHours: String(settings.guideHours), + clearPassword: false, +}); + +const toPayload = (draft: Draft) => ({ + enabled: draft.enabled, + hostname: draft.hostname.trim(), + useSsl: draft.useSsl, + baseUrl: draft.baseUrl.trim(), + deckPort: Number(draft.deckPort), + tunerPort: Number(draft.tunerPort), + guideUrl: draft.guideUrl.trim(), + guideHours: Number(draft.guideHours), + username: draft.username, + password: draft.password, + clearPassword: draft.clearPassword, +}); + +const errorMessage = (error: unknown): string | undefined => + axios.isAxiosError(error) && typeof error.response?.data?.error === 'string' + ? error.response.data.error + : undefined; + +const SettingsTunerr = () => { + const intl = useIntl(); + const { addToast } = useToasts(); + const { data, error, mutate } = useSWR( + '/api/v1/settings/tunerr' + ); + const { data: status, mutate: mutateStatus } = useLiveTvStatus(); + const [draft, setDraft] = useState(); + const [isDirty, setIsDirty] = useState(false); + const [isSaving, setIsSaving] = useState(false); + const [saveError, setSaveError] = useState(); + const [testing, setTesting] = useState(false); + const [testResult, setTestResult] = useState(); + + useEffect(() => { + if (data && !isDirty) setDraft(toDraft(data)); + }, [data, isDirty]); + + const update = (patch: Partial) => { + setDraft((current) => (current ? { ...current, ...patch } : current)); + setIsDirty(true); + setTestResult(undefined); + }; + + const submit = async (event: FormEvent) => { + event.preventDefault(); + if (!draft) return; + setIsSaving(true); + setSaveError(undefined); + try { + const response = await axios.put( + '/api/v1/settings/tunerr', + toPayload(draft) + ); + await mutate(response.data, { revalidate: false }); + void mutateStatus(); + setIsDirty(false); + addToast(intl.formatMessage(messages.saveSuccess), { + appearance: 'success', + autoDismiss: true, + }); + } catch (failure) { + setSaveError( + errorMessage(failure) ?? intl.formatMessage(messages.saveError) + ); + } finally { + setIsSaving(false); + } + }; + + const test = async () => { + if (!draft) return; + setTesting(true); + setTestResult(undefined); + try { + const response = await axios.post( + '/api/v1/settings/tunerr/test', + toPayload(draft) + ); + setTestResult(response.data); + } catch (failure) { + if (axios.isAxiosError(failure) && failure.response?.data) { + const body = failure.response.data as Partial; + setTestResult({ + deck: !!body.deck, + guide: !!body.guide, + missingFeatures: body.missingFeatures ?? [], + error: body.error ?? errorMessage(failure), + guideError: body.guideError, + }); + } else { + setTestResult({ deck: false, guide: false, missingFeatures: [] }); + } + } finally { + setTesting(false); + } + }; + + const textField = ( + id: keyof Draft, + label: string, + options: { + inputMode?: 'numeric' | 'url'; + maxLength?: number; + description?: string; + type?: string; + } = {} + ) => ( +
+ +
+
+ + update({ [id]: event.currentTarget.value } as Partial) + } + /> +
+ {options.description && ( +

{options.description}

+ )} +
+
+ ); + + const guide = status?.guide; + + return ( +
+

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

+

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

+
+ {!data && !error && } + {error && ( + + )} + {data && draft && !error && ( +
void submit(event)}> + {saveError && } + +

{intl.formatMessage(messages.setupNote)}

+
+ {guide?.ready && !isDirty && ( +

+ {intl.formatMessage(messages.guideStatus, { + programmes: guide.programmeCount, + channels: guide.channelCount, + time: guide.refreshedAt + ? intl.formatTime(guide.refreshedAt) + : '', + })} +

+ )} + {guide?.truncated && !isDirty && ( + + )} + {guide?.lastError && !isDirty && ( + + )} +
+ +
+
+ update({ enabled: checked })} + /> +
+
+
+ {textField('hostname', intl.formatMessage(messages.hostname))} + {textField('deckPort', intl.formatMessage(messages.deckPort), { + inputMode: 'numeric', + maxLength: 5, + })} + {textField('tunerPort', intl.formatMessage(messages.tunerPort), { + inputMode: 'numeric', + maxLength: 5, + })} +
+ +
+
+ update({ useSsl: checked })} + /> +
+
+
+ {textField('baseUrl', intl.formatMessage(messages.baseUrl), { + maxLength: 512, + })} + {textField('username', intl.formatMessage(messages.username), { + maxLength: 256, + })} +
+ +
+
+ + update({ + password: + event.currentTarget.value || + (data.password ? REDACTED : ''), + }) + } + /> +
+ {data.password && ( +
+ + update({ clearPassword: checked }) + } + /> + {intl.formatMessage(messages.clearSecret)} +
+ )} +
+
+ {textField('guideUrl', intl.formatMessage(messages.guideUrl), { + inputMode: 'url', + maxLength: 2048, + description: intl.formatMessage(messages.guideUrlDescription), + })} + {textField('guideHours', intl.formatMessage(messages.guideHours), { + inputMode: 'numeric', + maxLength: 3, + description: intl.formatMessage(messages.guideHoursDescription), + })} + {testResult && + (testResult.deck && + testResult.guide && + testResult.missingFeatures.length === 0 ? ( + {intl.formatMessage(messages.testOk)} + ) : ( + <> + {testResult.deck && testResult.missingFeatures.length > 0 && ( + + )} + {testResult.error && ( + + )} + {testResult.guideError && ( + + )} + + ))} + {isDirty && ( +

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

+ )} +
+
+ + {isDirty && ( + + )} + +
+
+ + )} +
+
+ ); +}; + +export default SettingsTunerr; diff --git a/src/components/TvDetails/index.tsx b/src/components/TvDetails/index.tsx index b55a38bd5a..a1900308fa 100644 --- a/src/components/TvDetails/index.tsx +++ b/src/components/TvDetails/index.tsx @@ -7,6 +7,7 @@ import MediaServerPlayButton from '@app/components/Common/MediaServerPlayButton' import PageErrorMessage from '@app/components/Common/PageErrorMessage'; import PageTitle from '@app/components/Common/PageTitle'; import Tooltip from '@app/components/Common/Tooltip'; +import LiveTvButton from '@app/components/LiveTv/LiveTvButton'; import MediaServerCollectionButton from '@app/components/MediaDetails/MediaServerCollectionButton'; import MediaServerWatchlistButton from '@app/components/MediaDetails/MediaServerWatchlistButton'; import RequestButton from '@app/components/RequestButton'; @@ -538,6 +539,11 @@ const TvDetails = ({ const secondaryActions = ( <> + {data.mediaInfo?.status !== MediaStatus.BLOCKLISTED && user?.userType !== UserType.PLEX && ( + useSWR('/api/v1/live-tv/status', { + revalidateOnFocus: false, + dedupingInterval: 60_000, + }); + +export const liveTvAiringsKey = (titles: string[], limit = 10) => { + const unique = [...new Set(titles.map((title) => title.trim()))].filter( + Boolean + ); + if (unique.length === 0) return null; + const query = unique + .slice(0, 4) + .map((title) => `title=${encodeURIComponent(title)}`) + .join('&'); + return `/api/v1/live-tv/airings?${query}&limit=${limit}`; +}; diff --git a/src/i18n/locale/en.json b/src/i18n/locale/en.json index b874dddaf3..7aa26ef389 100644 --- a/src/i18n/locale/en.json +++ b/src/i18n/locale/en.json @@ -1100,6 +1100,52 @@ "components.Layout.VersionStatus.streammain": "SeerrNG Main", "components.Layout.VersionStatus.streamstable": "SeerrNG Stable", "components.ListView.continueSearch": "Continue Search", + "components.LiveTv.LiveTvButton.airingsTitle": "On Live TV", + "components.LiveTv.LiveTvButton.airs": "Airs", + "components.LiveTv.LiveTvButton.cannotRequest": "You do not have permission to request recordings.", + "components.LiveTv.LiveTvButton.channel": "Channel", + "components.LiveTv.LiveTvButton.close": "Close", + "components.LiveTv.LiveTvButton.episode": "Episode", + "components.LiveTv.LiveTvButton.episodeValue": "Season {season} Episode {episode}", + "components.LiveTv.LiveTvButton.onLiveTv": "On Live TV", + "components.LiveTv.LiveTvButton.onLiveTvTooltip": "Airing soon on Live TV — watch or record it", + "components.LiveTv.LiveTvButton.record": "Record", + "components.LiveTv.LiveTvButton.recordSeries": "Record Every Airing", + "components.LiveTv.LiveTvButton.recordSeriesDescription": "Records this title whenever it airs while the request is active.", + "components.LiveTv.LiveTvButton.recording": "Requesting…", + "components.LiveTv.LiveTvButton.requestFailed": "The recording could not be requested.", + "components.LiveTv.LiveTvButton.requested": "Recording requested. It will be scheduled after approval.", + "components.LiveTv.LiveTvButton.scheduled": "Recording scheduled.", + "components.LiveTv.LiveTvButton.viewRecordings": "View My Recordings", + "components.LiveTv.RecordingList.actionFailed": "The recording could not be updated.", + "components.LiveTv.RecordingList.activeOnly": "Active Only", + "components.LiveTv.RecordingList.airs": "Airs", + "components.LiveTv.RecordingList.anyChannel": "Any channel", + "components.LiveTv.RecordingList.approve": "Approve", + "components.LiveTv.RecordingList.cancel": "Cancel Recording", + "components.LiveTv.RecordingList.channel": "Channel", + "components.LiveTv.RecordingList.decline": "Decline", + "components.LiveTv.RecordingList.empty": "No Recordings Yet", + "components.LiveTv.RecordingList.emptyHelp": "Open a movie or series that is airing on Live TV and select On Live TV to request a recording.", + "components.LiveTv.RecordingList.everyone": "All Recordings", + "components.LiveTv.RecordingList.loadError": "Recordings could not be loaded.", + "components.LiveTv.RecordingList.mine": "My Recordings", + "components.LiveTv.RecordingList.notConfigured": "Live TV recording is not set up. An administrator can connect IPTV Tunerr in Settings → Services.", + "components.LiveTv.RecordingList.oneAiring": "One Airing", + "components.LiveTv.RecordingList.recorded": "Recorded", + "components.LiveTv.RecordingList.requestedBy": "Requested By", + "components.LiveTv.RecordingList.retry": "Retry", + "components.LiveTv.RecordingList.series": "Every Airing", + "components.LiveTv.RecordingList.showAll": "Show All", + "components.LiveTv.RecordingList.statusCancelled": "Cancelled", + "components.LiveTv.RecordingList.statusCompleted": "Recorded", + "components.LiveTv.RecordingList.statusDeclined": "Declined", + "components.LiveTv.RecordingList.statusFailed": "Failed", + "components.LiveTv.RecordingList.statusPending": "Pending Approval", + "components.LiveTv.RecordingList.statusRecording": "Recording", + "components.LiveTv.RecordingList.statusScheduled": "Scheduled", + "components.LiveTv.RecordingList.title": "Recordings", + "components.LiveTv.RecordingList.working": "Working…", "components.Login.JellyfinQuickConnectModal.cancel": "Cancel", "components.Login.JellyfinQuickConnectModal.instructions": "Enter this code in your {mediaServerName} app", "components.Login.JellyfinQuickConnectModal.subtitle": "Sign in with Quick Connect", @@ -3354,6 +3400,38 @@ "components.Settings.SettingsNetwork.validationDnsCacheMaxTtl": "You must provide a valid maximum TTL", "components.Settings.SettingsNetwork.validationDnsCacheMinTtl": "You must provide a valid minimum TTL", "components.Settings.SettingsNetwork.validationProxyPort": "You must provide a valid port", + "components.Settings.SettingsTunerr.baseUrl": "Deck URL Base", + "components.Settings.SettingsTunerr.cancel": "Discard Changes", + "components.Settings.SettingsTunerr.clearSecret": "Remove the saved password", + "components.Settings.SettingsTunerr.deckPort": "Deck Port", + "components.Settings.SettingsTunerr.description": "Connect IPTV Tunerr so people can see when a movie or series airs on Live TV and request recordings. Recording requests use the same approval rules as other requests.", + "components.Settings.SettingsTunerr.enabled": "Enable Live TV", + "components.Settings.SettingsTunerr.guideError": "Last guide refresh failed: {error}", + "components.Settings.SettingsTunerr.guideHours": "Guide Window (Hours)", + "components.Settings.SettingsTunerr.guideHoursDescription": "How far ahead SeerrNG looks for airings. Larger windows use more memory.", + "components.Settings.SettingsTunerr.guideStatus": "Guide loaded: {programmes} programmes on {channels} channels, refreshed {time}.", + "components.Settings.SettingsTunerr.guideTruncated": "The guide is larger than SeerrNG indexes; shorten the guide window to include every channel.", + "components.Settings.SettingsTunerr.guideUrl": "Guide URL", + "components.Settings.SettingsTunerr.guideUrlDescription": "Leave empty to read /guide.xml from the tuner port. Set this when the guide is served from somewhere else.", + "components.Settings.SettingsTunerr.hostname": "Hostname or IP Address", + "components.Settings.SettingsTunerr.loadError": "Tunerr settings could not be loaded.", + "components.Settings.SettingsTunerr.password": "Deck Password", + "components.Settings.SettingsTunerr.save": "Save Changes", + "components.Settings.SettingsTunerr.saveError": "Tunerr settings could not be saved.", + "components.Settings.SettingsTunerr.saveSuccess": "Tunerr settings saved.", + "components.Settings.SettingsTunerr.savedSecret": "Saved — leave empty to keep it", + "components.Settings.SettingsTunerr.saving": "Saving…", + "components.Settings.SettingsTunerr.setupNote": "SeerrNG talks to the Tunerr deck with its username and password. Set IPTV_TUNERR_WEBUI_ALLOW_LAN=1 on Tunerr so the deck accepts connections from SeerrNG, and run the Tunerr recorder with recording rules enabled.", + "components.Settings.SettingsTunerr.test": "Test Connection", + "components.Settings.SettingsTunerr.testGuideFailed": "Guide: {error}", + "components.Settings.SettingsTunerr.testMissing": "Connected, but this Tunerr version cannot record SeerrNG requests (missing: {features}). Update Tunerr to enable recording.", + "components.Settings.SettingsTunerr.testOk": "Connected to the Tunerr deck and guide.", + "components.Settings.SettingsTunerr.testing": "Testing…", + "components.Settings.SettingsTunerr.title": "Live TV (IPTV Tunerr)", + "components.Settings.SettingsTunerr.tunerPort": "Tuner Port", + "components.Settings.SettingsTunerr.unsavedChanges": "You have unsaved changes.", + "components.Settings.SettingsTunerr.useSsl": "Use HTTPS", + "components.Settings.SettingsTunerr.username": "Deck Username", "components.Settings.SettingsUsers.atLeastOneAuth": "At least one authentication method must be selected.", "components.Settings.SettingsUsers.bookRequestLimitLabel": "Global Book Request Limit", "components.Settings.SettingsUsers.comicRequestLimitLabel": "Global Comic Request Limit", diff --git a/src/pages/recordings.tsx b/src/pages/recordings.tsx new file mode 100644 index 0000000000..240a50097a --- /dev/null +++ b/src/pages/recordings.tsx @@ -0,0 +1,6 @@ +import RecordingList from '@app/components/LiveTv/RecordingList'; +import type { NextPage } from 'next'; + +const RecordingsPage: NextPage = () => ; + +export default RecordingsPage; From 83c1f377b9e047700ac5f8ae7705ebb007faa938 Mon Sep 17 00:00:00 2001 From: Keith Snape Date: Tue, 6 Oct 2026 15:28:52 -0600 Subject: [PATCH 18/58] docs: record Tunerr recording-rule fork progress release-note: none Co-Authored-By: Claude Opus 5.5 --- docs/maintainers/ng-ecosystem-integration-plan.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/maintainers/ng-ecosystem-integration-plan.md b/docs/maintainers/ng-ecosystem-integration-plan.md index 9bb7e5d624..b886f6e6ba 100644 --- a/docs/maintainers/ng-ecosystem-integration-plan.md +++ b/docs/maintainers/ng-ecosystem-integration-plan.md @@ -57,7 +57,8 @@ human visual acceptance yet; testing is planned after the full build-out. | 2 RecordingRequest entity + migrations | done | SQLite and Postgres migrations `1791040000000`; SQLite migration test. Postgres migration not run locally. | | 2 Live TV API + sync job | done | `/api/v1/live-tv/*`, `/api/v1/settings/tunerr`, `live-tv-sync` job. Integration test against a fake deck and guide (4 tests), OpenAPI validator test (5), settings parser (5). | | 2 UI | built | On Live TV button + dialog on movie/series pages, `/recordings` page, Settings → Services section. Component test (4). Needs human visual review. No sidebar entry yet (sidebar links cannot be conditional on settings today). | -| 2 Tunerr fork: rule-driven recorder | pending | Required for recording to work at all: Tunerr's recorder ignores rules today. Add `title_equals`, `start_after`/`start_before`, a rules-only recorder mode, and `features` in the rules response. | +| 2 Tunerr fork: rule-driven recorder | done (local branch) | `~/Code/iptvtunerr` branch `feat/seerrng-recording-rules` (commit `0440d64`, not pushed): `title_equals`, `start_after`/`start_before`, response-only `features`, `catchup-daemon -rules-only`. 6 new Go tests; `go test ./...` passed. Tunerr `scripts/verify` not run (local Go 1.27 `gofmt` flags vendored files). Operators must run the recorder with `-rules-only`. | +| 2 Live check: deck proxy + Basic auth from another host | pending | Verified from Tunerr source only; needs a local Tunerr run. | | 2 Sports "follow my team" | pending | | | 2 Recently aired shelf, channel requests, Plex→Jellyfin users | pending | | | 2 Recording notifications | pending | Requests do not notify yet. | From e0583a9ba4d8e0aab74963c8f246432fe3ca064c Mon Sep 17 00:00:00 2001 From: Keith Snape Date: Tue, 6 Oct 2026 15:35:12 -0600 Subject: [PATCH 19/58] feat: add Soulseek track requests, album fixes, and SongID via slskdN Request single tracks through the slskdN wishlist with the usual approval rules, track them with a Soulseek Sync job, list and fix slskdN library-health issues for an album, and identify songs with SongID. Each slskdN feature is probed separately so plain slskd or slskr installs report it as unavailable. Co-Authored-By: Claude Opus 5.5 --- seerr-api.yml | 503 ++++++++++++++++++ server/api/slskdn.ts | 320 +++++++++++ server/entity/TrackRequest.ts | 93 ++++ server/job/schedule.ts | 18 + server/lib/settings/index.ts | 44 ++ server/lib/soulseek/libraryHealth.ts | 149 ++++++ server/lib/soulseek/trackRequests.ts | 279 ++++++++++ .../1791050000000-CreateTrackRequests.ts | 40 ++ .../1791050000000-CreateTrackRequests.test.ts | 49 ++ .../1791050000000-CreateTrackRequests.ts | 39 ++ server/routes/index.ts | 2 + server/routes/settings/index.ts | 2 + server/routes/settings/slskdn.ts | 166 ++++++ server/routes/soulseek.openapi.test.ts | 89 ++++ server/routes/soulseek.test.ts | 407 ++++++++++++++ server/routes/soulseek.ts | 340 ++++++++++++ .../Settings/SettingsJobsCache/index.tsx | 1 + src/i18n/locale/en.json | 1 + 18 files changed, 2542 insertions(+) create mode 100644 server/api/slskdn.ts create mode 100644 server/entity/TrackRequest.ts create mode 100644 server/lib/soulseek/libraryHealth.ts create mode 100644 server/lib/soulseek/trackRequests.ts create mode 100644 server/migration/postgres/1791050000000-CreateTrackRequests.ts create mode 100644 server/migration/sqlite/1791050000000-CreateTrackRequests.test.ts create mode 100644 server/migration/sqlite/1791050000000-CreateTrackRequests.ts create mode 100644 server/routes/settings/slskdn.ts create mode 100644 server/routes/soulseek.openapi.test.ts create mode 100644 server/routes/soulseek.test.ts create mode 100644 server/routes/soulseek.ts diff --git a/seerr-api.yml b/seerr-api.yml index 0542edcab2..e9790051c1 100644 --- a/seerr-api.yml +++ b/seerr-api.yml @@ -16,6 +16,8 @@ tags: description: Endpoints related to Seerr's settings and configuration. - name: live-tv description: Live TV airings and recording requests through IPTV Tunerr. + - name: soulseek + description: Soulseek track requests, library-health fixes, and SongID through slskdN. - name: auth description: Endpoints related to logging in or out, and the currently authenticated user. - name: users @@ -62,6 +64,108 @@ servers: components: schemas: + TrackRequest: + type: object + properties: + id: + type: integer + status: + type: string + enum: [pending, searching, completed, failed, declined, cancelled] + artist: + type: string + title: + type: string + recordingMbid: + type: string + source: + type: string + enum: [manual, playlist, songid] + searchCount: + type: integer + lastMatchCount: + type: integer + lastError: + type: string + createdAt: + type: string + format: date-time + updatedAt: + type: string + format: date-time + requestedBy: + type: object + properties: + id: + type: integer + displayName: + type: string + SlskdnSettings: + type: object + properties: + enabled: + type: boolean + hostname: + type: string + port: + type: integer + minimum: 1 + maximum: 65535 + useSsl: + type: boolean + baseUrl: + type: string + apiKey: + type: string + description: slskdN API key (read-write role; administrator for SongID). Omit or send the redacted value to keep the saved key. + clearApiKey: + type: boolean + searchFilter: + type: string + maxLength: 512 + SongIdResult: + type: object + properties: + id: + type: string + status: + type: string + summary: + type: string + stage: + type: string + percentComplete: + type: number + queuePosition: + type: integer + albums: + type: array + items: + type: object + properties: + releaseId: + type: string + releaseGroupId: + type: string + title: + type: string + artist: + type: string + isExact: + type: boolean + tracks: + type: array + items: + type: object + properties: + recordingId: + type: string + title: + type: string + artist: + type: string + isExact: + type: boolean RecordingRequest: type: object properties: @@ -8325,6 +8429,405 @@ paths: description: Invalid settings '502': description: The deck or guide could not be reached + /soulseek/status: + get: + summary: Get Soulseek request availability + tags: + - soulseek + responses: + '200': + description: Whether slskdN is configured and the user can request tracks + content: + application/json: + schema: + type: object + properties: + configured: + type: boolean + canRequest: + type: boolean + /soulseek/track-requests: + get: + summary: List Soulseek track requests + description: Returns the caller's track requests. Users who can manage or view all requests may pass `scope=all`. + tags: + - soulseek + parameters: + - in: query + name: scope + schema: + type: string + enum: [mine, all] + - in: query + name: filter + schema: + type: string + enum: [all, active] + - in: query + name: take + schema: + type: integer + minimum: 1 + maximum: 100 + - in: query + name: skip + schema: + type: integer + minimum: 0 + responses: + '200': + description: Track requests + content: + application/json: + schema: + type: object + properties: + pageInfo: + type: object + results: + type: array + items: + $ref: '#/components/schemas/TrackRequest' + post: + summary: Request tracks from Soulseek + description: >- + Requests individual tracks through the slskdN wishlist, for example + singles or playlist tracks without an album match. Requests by users + who can manage requests or auto-approve music start searching + immediately; others wait for approval. An identical active request is + returned instead of a duplicate. + tags: + - soulseek + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [tracks] + properties: + tracks: + type: array + minItems: 1 + maxItems: 50 + items: + type: object + required: [artist, title] + properties: + artist: + type: string + maxLength: 255 + title: + type: string + maxLength: 255 + recordingMbid: + type: string + source: + type: string + enum: [manual, playlist, songid] + responses: + '201': + description: Track requests created or reused + content: + application/json: + schema: + type: object + properties: + results: + type: array + items: + $ref: '#/components/schemas/TrackRequest' + '400': + description: Invalid tracks + '403': + description: The user cannot request music + '404': + description: slskdN is not set up + '409': + description: Too many active track requests + '502': + description: slskdN could not be reached + /soulseek/track-requests/{id}/approve: + post: + summary: Approve a track request + tags: + - soulseek + parameters: + - in: path + name: id + required: true + schema: + type: integer + responses: + '200': + description: Search started + content: + application/json: + schema: + $ref: '#/components/schemas/TrackRequest' + '403': + description: Access denied + '404': + description: Request not found + '409': + description: Not pending + '502': + description: slskdN could not be reached + /soulseek/track-requests/{id}/decline: + post: + summary: Decline a track request + tags: + - soulseek + parameters: + - in: path + name: id + required: true + schema: + type: integer + responses: + '200': + description: Declined + content: + application/json: + schema: + $ref: '#/components/schemas/TrackRequest' + '403': + description: Access denied + '404': + description: Request not found + '409': + description: Not pending + /soulseek/track-requests/{id}: + delete: + summary: Cancel a track request + description: Removes the slskdN wishlist entry. The requester or a manager can cancel. + tags: + - soulseek + parameters: + - in: path + name: id + required: true + schema: + type: integer + responses: + '200': + description: Cancelled + content: + application/json: + schema: + $ref: '#/components/schemas/TrackRequest' + '403': + description: Access denied + '404': + description: Request not found + '409': + description: No longer active + '502': + description: slskdN could not be reached + /soulseek/albums/{releaseGroupId}/issues: + get: + summary: List slskdN library-health issues for an album + description: Looks up open slskdN issues (transcodes, missing tracks, and similar) for each release of the MusicBrainz release group. Requires Manage Requests. + tags: + - soulseek + parameters: + - in: path + name: releaseGroupId + required: true + schema: + type: string + pattern: '^[0-9a-fA-F-]{36}$' + responses: + '200': + description: Album issues + content: + application/json: + schema: + type: object + properties: + configured: + type: boolean + issues: + type: array + items: + type: object + properties: + issueId: + type: string + type: + type: string + severity: + type: string + status: + type: string + title: + type: string + reason: + type: string + canAutoFix: + type: boolean + remediationJobId: + type: string + '400': + description: Invalid album ID + '403': + description: Access denied + '502': + description: slskdN could not be reached + /soulseek/albums/{releaseGroupId}/remediate: + post: + summary: Fix album issues with slskdN + description: Starts slskdN remediation for the given issues. Only issues that belong to this album and that slskdN can fix automatically are sent. Requires Manage Requests. + tags: + - soulseek + parameters: + - in: path + name: releaseGroupId + required: true + schema: + type: string + pattern: '^[0-9a-fA-F-]{36}$' + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [issueIds] + properties: + issueIds: + type: array + minItems: 1 + maxItems: 200 + items: + type: string + maxLength: 128 + responses: + '202': + description: Remediation started + content: + application/json: + schema: + type: object + properties: + jobId: + type: string + issueCount: + type: integer + '400': + description: Invalid request + '403': + description: Access denied + '409': + description: None of the issues can be fixed automatically + '502': + description: slskdN could not be reached + /soulseek/songid: + post: + summary: Identify a song with slskdN SongID + description: Starts a SongID analysis of a link or text. Poll the result with GET `/soulseek/songid/{id}`; only the requester (or a manager) can read it. The slskdN API key needs the administrator role. + tags: + - soulseek + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [source] + properties: + source: + type: string + maxLength: 2048 + responses: + '202': + description: Analysis started + content: + application/json: + schema: + $ref: '#/components/schemas/SongIdResult' + '400': + description: No source given + '403': + description: Access denied + '404': + description: slskdN is not set up + '502': + description: slskdN could not run SongID + '503': + description: This slskdN does not support SongID + /soulseek/songid/{id}: + get: + summary: Get a SongID result + tags: + - soulseek + parameters: + - in: path + name: id + required: true + schema: + type: string + maxLength: 64 + responses: + '200': + description: SongID result + content: + application/json: + schema: + $ref: '#/components/schemas/SongIdResult' + '404': + description: Not found + /settings/slskdn: + get: + summary: Get slskdN settings + description: The API key is always redacted. + tags: + - settings + responses: + '200': + description: slskdN settings + content: + application/json: + schema: + $ref: '#/components/schemas/SlskdnSettings' + put: + summary: Update slskdN settings + tags: + - settings + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SlskdnSettings' + responses: + '200': + description: Settings saved + content: + application/json: + schema: + $ref: '#/components/schemas/SlskdnSettings' + '400': + description: Invalid settings + /settings/slskdn/test: + post: + summary: Test the slskdN connection + description: Reads the slskdN version and reports which optional features (wishlist, library health, SongID) the API key can use. Settings are not saved. + tags: + - settings + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SlskdnSettings' + responses: + '200': + description: Connected + '400': + description: Invalid settings + '502': + description: slskdN could not be reached /settings/prowlarr: get: summary: Get Prowlarr connection settings diff --git a/server/api/slskdn.ts b/server/api/slskdn.ts new file mode 100644 index 0000000000..87808ad88a --- /dev/null +++ b/server/api/slskdn.ts @@ -0,0 +1,320 @@ +import type { SlskdnSettings } from '@server/lib/settings'; +import { buildServiceUrl } from '@server/utils/serviceUrl'; +import type { AxiosRequestConfig } from 'axios'; +import axios from 'axios'; + +/** + * Client for slskdN's REST API (slskd-compatible `/api/v0` routes plus the + * slskdN-native `/api/slskdn` routes). Every feature is probed separately so + * plain slskd or slskr installs simply report it as unavailable. + */ + +export interface SlskdnWishlistItem { + id: string; + searchText: string; + filter?: string; + enabled: boolean; + autoDownload: boolean; + lastSearchedAt?: string | null; + lastMatchCount?: number; + totalSearchCount?: number; + totalDownloadCount?: number; + maxDownloads?: number | null; +} + +export type SlskdnIssueType = + | 'SuspectedTranscode' + | 'NonCanonicalVariant' + | 'TrackNotInTaggedRelease' + | 'MissingTrackInRelease' + | 'CorruptedFile' + | 'MissingMetadata' + | 'MultipleVariants' + | 'WrongDuration'; + +export interface SlskdnLibraryIssue { + issueId: string; + type: SlskdnIssueType | string; + severity: string; + status: string; + filePath?: string; + musicBrainzReleaseId?: string; + artist?: string; + album?: string; + title?: string; + reason?: string; + canAutoFix?: boolean; + suggestedAction?: string; + remediationJobId?: string; + detectedAt?: string; +} + +export interface SlskdnSongIdAlbum { + releaseId: string; + title: string; + artist: string; + trackCount?: number; + isExact?: boolean; + identityScore?: number; +} + +export interface SlskdnSongIdTrack { + recordingId: string; + title: string; + artist: string; + isExact?: boolean; + searchText?: string; + identityScore?: number; +} + +export interface SlskdnSongIdRun { + id: string; + status: string; + summary?: string; + currentStage?: string; + percentComplete?: number; + queuePosition?: number | null; + albums?: SlskdnSongIdAlbum[]; + tracks?: SlskdnSongIdTrack[]; +} + +export interface SlskdnFeatures { + wishlist: boolean; + libraryHealth: boolean; + songId: boolean; +} + +export class SlskdnError extends Error { + constructor( + message: string, + public readonly kind: 'auth' | 'connection' | 'protocol' | 'unsupported' + ) { + super(message); + this.name = 'SlskdnError'; + } +} + +const REQUEST_CONFIG: AxiosRequestConfig = { + timeout: 15_000, + maxContentLength: 16 * 1024 * 1024, + maxBodyLength: 256 * 1024, + maxRedirects: 0, + validateStatus: () => true, +}; + +export default class SlskdnAPI { + constructor(private readonly settings: SlskdnSettings) {} + + private url(path: string): string { + return buildServiceUrl({ + useSsl: this.settings.useSsl, + hostname: this.settings.hostname, + port: this.settings.port, + urlBase: this.settings.baseUrl, + path, + }); + } + + private async request( + method: 'GET' | 'POST' | 'DELETE', + path: string, + what: string, + options: { data?: unknown; params?: Record } = {} + ): Promise<{ status: number; data: T }> { + let response; + try { + response = await axios.request({ + ...REQUEST_CONFIG, + method, + url: this.url(path), + data: options.data, + params: options.params, + paramsSerializer: { indexes: null }, + headers: { + 'X-API-Key': this.settings.apiKey, + Accept: 'application/json', + }, + }); + } catch { + throw new SlskdnError( + 'slskdN could not be reached. Check the hostname and port.', + 'connection' + ); + } + if (response.status === 401) { + throw new SlskdnError('slskdN rejected the API key.', 'auth'); + } + if (response.status === 403) { + throw new SlskdnError( + `The slskdN API key's role cannot use ${what}.`, + 'auth' + ); + } + return response; + } + + private ok( + response: { status: number; data: T }, + what: string, + accepted = [200] + ): T { + if (response.status === 404) { + throw new SlskdnError( + `This slskdN does not support ${what}.`, + 'unsupported' + ); + } + if (!accepted.includes(response.status)) { + throw new SlskdnError( + `slskdN ${what} returned HTTP ${response.status}.`, + 'protocol' + ); + } + return response.data; + } + + public async getVersion(): Promise { + const response = await this.request<{ + version?: { full?: string; current?: string }; + }>('GET', '/api/v0/application', 'application status'); + const data = this.ok(response, 'application status'); + const version = data?.version?.full ?? data?.version?.current; + return typeof version === 'string' ? version.slice(0, 64) : undefined; + } + + /** Probes each optional feature; a 404 or 403 means unavailable. */ + public async getFeatures(): Promise { + const probe = async (path: string) => { + try { + const response = await this.request('GET', path, 'feature probe'); + return response.status >= 200 && response.status < 300; + } catch (error) { + if (error instanceof SlskdnError && error.kind === 'auth') { + return false; + } + throw error; + } + }; + const [wishlist, libraryHealth, songId] = await Promise.all([ + probe('/api/v0/wishlist'), + probe('/api/v0/library/health/summary'), + probe('/api/v0/songid/capabilities'), + ]); + return { wishlist, libraryHealth, songId }; + } + + public async createWishlistItem(input: { + searchText: string; + filter?: string; + }): Promise { + const response = await this.request( + 'POST', + '/api/v0/wishlist', + 'the wishlist', + { + data: { + searchText: input.searchText, + filter: input.filter ?? '', + enabled: true, + autoDownload: true, + maxResults: 100, + maxDownloads: 1, + }, + } + ); + const item = this.ok(response, 'the wishlist', [200, 201]); + if (!item || typeof item.id !== 'string') { + throw new SlskdnError( + 'slskdN returned an invalid wishlist item.', + 'protocol' + ); + } + return item; + } + + public async getWishlistItem( + id: string + ): Promise { + const response = await this.request( + 'GET', + `/api/v0/wishlist/${encodeURIComponent(id)}`, + 'the wishlist' + ); + if (response.status === 404) return undefined; + return this.ok(response, 'the wishlist'); + } + + public async deleteWishlistItem(id: string): Promise { + const response = await this.request( + 'DELETE', + `/api/v0/wishlist/${encodeURIComponent(id)}`, + 'the wishlist' + ); + if (response.status === 404) return; + this.ok(response, 'the wishlist', [200, 204]); + } + + public async getLibraryIssues(filter: { + musicBrainzReleaseId?: string; + statuses?: string[]; + limit?: number; + }): Promise { + const response = await this.request<{ issues?: SlskdnLibraryIssue[] }>( + 'GET', + '/api/v0/library/health/issues', + 'library health', + { + params: { + musicBrainzReleaseId: filter.musicBrainzReleaseId, + statuses: filter.statuses, + limit: filter.limit ?? 200, + }, + } + ); + const data = this.ok(response, 'library health'); + return Array.isArray(data?.issues) ? data.issues : []; + } + + public async remediateIssues(issueIds: string[]): Promise { + const response = await this.request<{ job_id?: string }>( + 'POST', + '/api/slskdn/library/remediate', + 'library remediation', + { data: { issue_ids: issueIds } } + ); + const data = this.ok(response, 'library remediation'); + if (typeof data?.job_id !== 'string') { + throw new SlskdnError( + 'slskdN did not return a remediation job.', + 'protocol' + ); + } + return data.job_id; + } + + public async createSongIdRun(source: string): Promise { + const response = await this.request( + 'POST', + '/api/v0/songid/runs', + 'SongID', + { data: { source } } + ); + if (response.status === 400) { + throw new SlskdnError( + 'slskdN could not analyze that source.', + 'protocol' + ); + } + return this.ok(response, 'SongID', [200, 201, 202]); + } + + public async getSongIdRun(id: string): Promise { + const response = await this.request( + 'GET', + `/api/v0/songid/runs/${encodeURIComponent(id)}`, + 'SongID' + ); + if (response.status === 404) return undefined; + return this.ok(response, 'SongID'); + } +} diff --git a/server/entity/TrackRequest.ts b/server/entity/TrackRequest.ts new file mode 100644 index 0000000000..508f488b27 --- /dev/null +++ b/server/entity/TrackRequest.ts @@ -0,0 +1,93 @@ +import { DbAwareColumn, resolveDbType } from '@server/utils/DbColumnHelper'; +import { + Column, + Entity, + Index, + JoinColumn, + ManyToOne, + PrimaryGeneratedColumn, + UpdateDateColumn, +} from 'typeorm'; +import { User } from './User'; + +export type TrackRequestStatus = + 'pending' | 'searching' | 'completed' | 'failed' | 'declined' | 'cancelled'; + +export const ACTIVE_TRACK_STATUSES: TrackRequestStatus[] = [ + 'pending', + 'searching', +]; + +/** + * A single-track request fulfilled through the slskdN wishlist. Used for + * tracks Lidarr cannot request, such as singles or playlist tracks without a + * confident album match. + */ +@Entity('track_request') +@Index('IDX_track_request_requester_created', ['requestedById', 'createdAt']) +@Index('IDX_track_request_status_created', ['status', 'createdAt']) +export class TrackRequest { + public constructor(init?: Partial) { + Object.assign(this, init); + } + + @PrimaryGeneratedColumn() + public id: number; + + @Column({ type: 'integer' }) + public requestedById: number; + + @ManyToOne(() => User, { eager: true, onDelete: 'CASCADE' }) + @JoinColumn({ name: 'requestedById' }) + public requestedBy: User; + + @Column({ type: 'integer', nullable: true }) + public modifiedById?: number | null; + + @ManyToOne(() => User, { nullable: true, onDelete: 'SET NULL' }) + @JoinColumn({ name: 'modifiedById' }) + public modifiedBy?: User | null; + + @Column({ type: 'varchar', length: 16, default: 'pending' }) + public status: TrackRequestStatus; + + @Column({ type: 'varchar', length: 255 }) + public artist: string; + + @Column({ type: 'varchar', length: 255 }) + public title: string; + + /** MusicBrainz recording ID when known. */ + @Column({ type: 'varchar', length: 64, nullable: true }) + public recordingMbid?: string | null; + + /** Where the request came from, e.g. `playlist` or `songid`. */ + @Column({ type: 'varchar', length: 16, default: 'manual' }) + public source: string; + + @Column({ type: 'varchar', length: 64, nullable: true }) + public wishlistItemId?: string | null; + + @Column({ type: 'integer', default: 0 }) + public searchCount: number; + + @Column({ type: 'integer', default: 0 }) + public lastMatchCount: number; + + @Column({ type: 'varchar', length: 512, nullable: true }) + public lastError?: string | null; + + @DbAwareColumn({ type: 'datetime', nullable: true }) + public lastCheckedAt?: Date | null; + + @DbAwareColumn({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' }) + public createdAt: Date; + + @UpdateDateColumn({ + type: resolveDbType('datetime'), + default: () => 'CURRENT_TIMESTAMP', + }) + public updatedAt: Date; +} + +export default TrackRequest; diff --git a/server/job/schedule.ts b/server/job/schedule.ts index fa58c45985..9ebeadf739 100644 --- a/server/job/schedule.ts +++ b/server/job/schedule.ts @@ -33,6 +33,10 @@ import { sonarrScanner } from '@server/lib/scanners/sonarr'; import type { JobId } from '@server/lib/settings'; import { getSettings } from '@server/lib/settings'; import { refreshTrackedSoftwareRequests } from '@server/lib/softwareRequests'; +import { + isSlskdnConfigured, + syncTrackRequests, +} from '@server/lib/soulseek/trackRequests'; import { isWatchAheadMediaServer } from '@server/lib/watchAheadEligibility'; import watchlistSync from '@server/lib/watchlistsync'; import logger from '@server/logger'; @@ -584,6 +588,20 @@ export const startJobs = (): void => { }), }); + scheduledJobs.push({ + id: 'soulseek-sync', + name: 'Soulseek Sync', + type: 'process', + interval: 'minutes', + cronSchedule: jobs['soulseek-sync'].schedule, + job: schedule.scheduleJob(jobs['soulseek-sync'].schedule, () => { + if (!isSlskdnConfigured()) { + return; + } + return runTrackedJob('Soulseek Sync', syncTrackRequests); + }), + }); + scheduledJobs.push({ id: 'download-recovery', name: 'Download Recovery', diff --git a/server/lib/settings/index.ts b/server/lib/settings/index.ts index c16d65d17f..6861ffd7cc 100644 --- a/server/lib/settings/index.ts +++ b/server/lib/settings/index.ts @@ -203,6 +203,32 @@ export const defaultTunerrSettings = (): TunerrSettings => ({ guideHours: 72, }); +/** + * slskdN (or a compatible slskd/slskr) connection for Soulseek track + * requests, library-health fixes, and SongID. Uses an API key with the + * read-write role; SongID runs need the administrator role. + */ +export interface SlskdnSettings { + enabled: boolean; + hostname: string; + port: number; + useSsl: boolean; + baseUrl: string; + apiKey: string; + /** Optional slskdN wishlist filter applied to track requests. */ + searchFilter: string; +} + +export const defaultSlskdnSettings = (): SlskdnSettings => ({ + enabled: false, + hostname: '', + port: 5030, + useSsl: false, + baseUrl: '', + apiKey: '', + searchFilter: '', +}); + export interface DVRSettings { id: number; name: string; @@ -602,6 +628,7 @@ export type JobId = | 'download-sync' | 'software-request-reconciliation' | 'live-tv-sync' + | 'soulseek-sync' | 'download-recovery' | 'download-sync-reset' | 'jellyfin-recently-added-scan' @@ -673,6 +700,7 @@ export interface AllSettings { prowlarr: ProwlarrSettings; liveDownloads: LiveDownloadSettings; tunerr: TunerrSettings; + slskdn: SlskdnSettings; discoveryIntegrations: DiscoveryIntegrationsSettings; readerDelivery: ReaderDeliverySettings; public: PublicSettings; @@ -819,6 +847,7 @@ class Settings { }, liveDownloads: defaultLiveDownloadSettings(), tunerr: defaultTunerrSettings(), + slskdn: defaultSlskdnSettings(), public: { initialized: false, }, @@ -985,6 +1014,9 @@ class Settings { 'live-tv-sync': { schedule: '30 * * * * *', }, + 'soulseek-sync': { + schedule: '45 */2 * * * *', + }, 'download-recovery': { schedule: '0 */5 * * * *', enabled: true, @@ -1361,6 +1393,14 @@ class Settings { this.data.tunerr = data; } + get slskdn(): SlskdnSettings { + return this.data.slskdn; + } + + set slskdn(data: SlskdnSettings) { + this.data.slskdn = data; + } + get public(): PublicSettings { return this.data.public; } @@ -1731,6 +1771,7 @@ class Settings { }, liveDownloads: defaultLiveDownloadSettings(), tunerr: defaultTunerrSettings(), + slskdn: defaultSlskdnSettings(), public: { initialized: false, }, @@ -1896,6 +1937,9 @@ class Settings { 'live-tv-sync': { schedule: '30 * * * * *', }, + 'soulseek-sync': { + schedule: '45 */2 * * * *', + }, 'download-recovery': { schedule: '0 */5 * * * *', enabled: true, diff --git a/server/lib/soulseek/libraryHealth.ts b/server/lib/soulseek/libraryHealth.ts new file mode 100644 index 0000000000..9e5e72abca --- /dev/null +++ b/server/lib/soulseek/libraryHealth.ts @@ -0,0 +1,149 @@ +import MusicBrainz from '@server/api/musicbrainz'; +import SlskdnAPI, { + type SlskdnLibraryIssue, + type SlskdnSongIdRun, +} from '@server/api/slskdn'; +import { getSettings } from '@server/lib/settings'; +import { mapWithConcurrency } from '@server/utils/concurrency'; + +const OPEN_STATUSES = ['Detected', 'Acknowledged', 'Failed']; +const MAX_RELEASES_CHECKED = 25; + +export interface AlbumIssueView { + issueId: string; + type: string; + severity: string; + status: string; + title?: string; + reason?: string; + canAutoFix: boolean; + remediationJobId?: string; +} + +const toView = (issue: SlskdnLibraryIssue): AlbumIssueView => ({ + issueId: issue.issueId, + type: String(issue.type), + severity: String(issue.severity), + status: String(issue.status), + title: issue.title || undefined, + reason: issue.reason?.slice(0, 300) || undefined, + canAutoFix: issue.canAutoFix === true, + remediationJobId: issue.remediationJobId || undefined, +}); + +/** + * Open slskdN library-health issues for a SeerrNG album (a MusicBrainz + * release group), found through each of its releases. + */ +export const getAlbumIssues = async ( + releaseGroupId: string +): Promise => { + const details = await new MusicBrainz().getReleaseGroupDetails({ + releaseGroupId, + }); + const releaseIds = (details.releases ?? []) + .map((release) => release.id) + .filter((id): id is string => typeof id === 'string' && id.length > 0) + .slice(0, MAX_RELEASES_CHECKED); + const api = new SlskdnAPI(getSettings().slskdn); + const results = await mapWithConcurrency(releaseIds, 4, (releaseId) => + api.getLibraryIssues({ + musicBrainzReleaseId: releaseId, + statuses: OPEN_STATUSES, + }) + ); + const seen = new Set(); + return results + .flat() + .filter((issue) => { + if (!issue.issueId || seen.has(issue.issueId)) return false; + seen.add(issue.issueId); + return true; + }) + .map(toView); +}; + +/** Starts remediation only for issues that belong to the album. */ +export const remediateAlbumIssues = async ( + releaseGroupId: string, + issueIds: string[] +): Promise<{ jobId: string; issueCount: number }> => { + const albumIssues = await getAlbumIssues(releaseGroupId); + const allowed = new Set( + albumIssues + .filter((issue) => issue.canAutoFix) + .map((issue) => issue.issueId) + ); + const selected = issueIds.filter((id) => allowed.has(id)); + if (selected.length === 0) { + return { jobId: '', issueCount: 0 }; + } + const jobId = await new SlskdnAPI(getSettings().slskdn).remediateIssues( + selected + ); + return { jobId, issueCount: selected.length }; +}; + +export interface SongIdView { + id: string; + status: string; + summary?: string; + stage?: string; + percentComplete?: number; + queuePosition?: number; + albums: { + releaseId: string; + releaseGroupId?: string; + title: string; + artist: string; + isExact: boolean; + }[]; + tracks: { + recordingId: string; + title: string; + artist: string; + isExact: boolean; + }[]; +} + +/** + * Shapes a SongID run for SeerrNG. Album candidates are resolved to release + * groups so the UI can link to SeerrNG album pages. + */ +export const toSongIdView = async ( + run: SlskdnSongIdRun, + resolveReleaseGroup: (releaseId: string) => Promise = ( + releaseId + ) => new MusicBrainz().getReleaseGroup({ releaseId }) +): Promise => { + const albums = await mapWithConcurrency( + (run.albums ?? []).filter((album) => album.releaseId).slice(0, 5), + 2, + async (album) => ({ + releaseId: album.releaseId, + releaseGroupId: + (await resolveReleaseGroup(album.releaseId).catch(() => null)) ?? + undefined, + title: album.title, + artist: album.artist, + isExact: album.isExact === true, + }) + ); + return { + id: run.id, + status: run.status, + summary: run.summary?.slice(0, 500) || undefined, + stage: run.currentStage || undefined, + percentComplete: + typeof run.percentComplete === 'number' ? run.percentComplete : undefined, + queuePosition: + typeof run.queuePosition === 'number' ? run.queuePosition : undefined, + albums, + tracks: (run.tracks ?? []).slice(0, 10).map((track) => ({ + recordingId: track.recordingId, + title: track.title, + artist: track.artist, + isExact: track.isExact === true, + })), + }; +}; diff --git a/server/lib/soulseek/trackRequests.ts b/server/lib/soulseek/trackRequests.ts new file mode 100644 index 0000000000..15cfe8ca44 --- /dev/null +++ b/server/lib/soulseek/trackRequests.ts @@ -0,0 +1,279 @@ +import SlskdnAPI, { SlskdnError } from '@server/api/slskdn'; +import { getRepository } from '@server/datasource'; +import TrackRequest, { + ACTIVE_TRACK_STATUSES, +} from '@server/entity/TrackRequest'; +import type { User } from '@server/entity/User'; +import { Permission } from '@server/lib/permissions'; +import { getSettings, type SlskdnSettings } from '@server/lib/settings'; +import logger from '@server/logger'; +import { In } from 'typeorm'; + +export const MAX_ACTIVE_TRACK_REQUESTS_PER_USER = 50; +/** Give up on a wishlist search that has found nothing after this long. */ +const SEARCH_GIVE_UP_MS = 14 * 24 * 60 * 60 * 1000; + +export class TrackRequestError extends Error { + constructor( + message: string, + public readonly status: 400 | 403 | 404 | 409 | 502 | 503 + ) { + super(message); + this.name = 'TrackRequestError'; + } +} + +export const isSlskdnConfigured = ( + settings: SlskdnSettings = getSettings().slskdn +) => settings.enabled && !!settings.hostname && !!settings.apiKey; + +export const canRequestTracks = (user: User) => + user.hasPermission([Permission.REQUEST, Permission.REQUEST_MUSIC], { + type: 'or', + }); + +const canAutoApprove = (user: User) => + user.hasPermission( + [ + Permission.MANAGE_REQUESTS, + Permission.AUTO_APPROVE, + Permission.AUTO_APPROVE_MUSIC, + ], + { type: 'or' } + ); + +/** The Soulseek search text for a track. Exposed for tests. */ +export const trackSearchText = (artist: string, title: string) => + `${artist} ${title}` + // Soulseek search ignores most punctuation and rejects some characters. + .replace(/[^\p{L}\p{N}'&]+/gu, ' ') + .replace(/\s+/g, ' ') + .trim() + .slice(0, 200); + +export interface TrackInput { + artist: string; + title: string; + recordingMbid?: string; + source?: string; +} + +const apiFor = () => new SlskdnAPI(getSettings().slskdn); + +const toRequestError = (error: unknown, fallback: string) => + error instanceof TrackRequestError + ? error + : new TrackRequestError( + error instanceof SlskdnError ? error.message : fallback, + error instanceof SlskdnError && error.kind === 'unsupported' ? 503 : 502 + ); + +/** Adds the wishlist item in slskdN and marks the request searching. */ +export const startTrackSearch = async ( + request: TrackRequest, + approver: User +): Promise => { + try { + const item = await apiFor().createWishlistItem({ + searchText: trackSearchText(request.artist, request.title), + filter: getSettings().slskdn.searchFilter, + }); + request.wishlistItemId = item.id; + request.status = 'searching'; + request.lastError = null; + } catch (error) { + throw toRequestError(error, 'slskdN could not be reached to search.'); + } + request.modifiedBy = approver; + return getRepository(TrackRequest).save(request); +}; + +export const createTrackRequests = async ( + user: User, + tracks: TrackInput[] +): Promise => { + if (!isSlskdnConfigured()) { + throw new TrackRequestError('Soulseek requests are not set up.', 404); + } + const repository = getRepository(TrackRequest); + const active = await repository.count({ + where: { requestedById: user.id, status: In(ACTIVE_TRACK_STATUSES) }, + }); + if (active + tracks.length > MAX_ACTIVE_TRACK_REQUESTS_PER_USER) { + throw new TrackRequestError( + `You can have up to ${MAX_ACTIVE_TRACK_REQUESTS_PER_USER} active track requests.`, + 409 + ); + } + + const created: TrackRequest[] = []; + for (const track of tracks) { + const duplicate = await repository.findOne({ + where: { + requestedById: user.id, + artist: track.artist, + title: track.title, + status: In(ACTIVE_TRACK_STATUSES), + }, + }); + if (duplicate) { + created.push(duplicate); + continue; + } + created.push( + await repository.save( + new TrackRequest({ + requestedBy: user, + requestedById: user.id, + artist: track.artist, + title: track.title, + recordingMbid: track.recordingMbid ?? null, + source: track.source ?? 'manual', + status: 'pending', + }) + ) + ); + } + + if (!canAutoApprove(user)) { + return created; + } + const started: TrackRequest[] = []; + for (const request of created) { + if (request.status !== 'pending') { + started.push(request); + continue; + } + try { + started.push(await startTrackSearch(request, user)); + } catch (error) { + request.lastError = + error instanceof Error ? error.message.slice(0, 500) : null; + started.push(await repository.save(request)); + } + } + return started; +}; + +export const declineTrackRequest = async ( + request: TrackRequest, + manager: User +) => { + if (request.status !== 'pending') { + throw new TrackRequestError('Only pending requests can be declined.', 409); + } + request.status = 'declined'; + request.modifiedBy = manager; + return getRepository(TrackRequest).save(request); +}; + +export const cancelTrackRequest = async (request: TrackRequest, user: User) => { + if (!ACTIVE_TRACK_STATUSES.includes(request.status)) { + throw new TrackRequestError('This request is no longer active.', 409); + } + if (request.wishlistItemId) { + try { + await apiFor().deleteWishlistItem(request.wishlistItemId); + } catch (error) { + throw toRequestError(error, 'slskdN could not be reached to cancel.'); + } + } + request.status = 'cancelled'; + request.modifiedBy = user; + return getRepository(TrackRequest).save(request); +}; + +export interface TrackSyncUpdate { + status: TrackRequest['status']; + searchCount: number; + lastMatchCount: number; + lastError?: string | null; + removeWishlistItem: boolean; +} + +/** Decides the next state from the wishlist item. Exposed for tests. */ +export const nextTrackStatus = ( + request: Pick, + item: + | { + totalDownloadCount?: number; + totalSearchCount?: number; + lastMatchCount?: number; + } + | undefined, + now: Date +): TrackSyncUpdate => { + if (!item) { + return { + status: 'failed', + searchCount: 0, + lastMatchCount: 0, + lastError: 'The slskdN wishlist entry was removed.', + removeWishlistItem: false, + }; + } + const searchCount = item.totalSearchCount ?? 0; + const lastMatchCount = item.lastMatchCount ?? 0; + if ((item.totalDownloadCount ?? 0) > 0) { + return { + status: 'completed', + searchCount, + lastMatchCount, + lastError: null, + removeWishlistItem: false, + }; + } + if ( + now.getTime() - new Date(request.createdAt).getTime() > + SEARCH_GIVE_UP_MS + ) { + return { + status: 'failed', + searchCount, + lastMatchCount, + lastError: 'No downloadable copy was found on Soulseek within two weeks.', + removeWishlistItem: true, + }; + } + return { + status: 'searching', + searchCount, + lastMatchCount, + removeWishlistItem: false, + }; +}; + +let syncing = false; + +export const syncTrackRequests = async (): Promise => { + if (syncing || !isSlskdnConfigured()) return; + syncing = true; + try { + const repository = getRepository(TrackRequest); + const requests = await repository.find({ where: { status: 'searching' } }); + if (requests.length === 0) return; + const api = apiFor(); + const now = new Date(); + for (const request of requests) { + if (!request.wishlistItemId) continue; + const item = await api.getWishlistItem(request.wishlistItemId); + const update = nextTrackStatus(request, item, now); + if (update.removeWishlistItem) { + await api.deleteWishlistItem(request.wishlistItemId); + } + request.status = update.status; + request.searchCount = update.searchCount; + request.lastMatchCount = update.lastMatchCount; + if (update.lastError !== undefined) request.lastError = update.lastError; + request.lastCheckedAt = now; + await repository.save(request); + } + } catch (error) { + logger.warn('Soulseek track request sync failed', { + label: 'Soulseek', + errorMessage: error instanceof Error ? error.message : String(error), + }); + } finally { + syncing = false; + } +}; diff --git a/server/migration/postgres/1791050000000-CreateTrackRequests.ts b/server/migration/postgres/1791050000000-CreateTrackRequests.ts new file mode 100644 index 0000000000..ae7b9264f4 --- /dev/null +++ b/server/migration/postgres/1791050000000-CreateTrackRequests.ts @@ -0,0 +1,40 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class CreateTrackRequests1791050000000 implements MigrationInterface { + name = 'CreateTrackRequests1791050000000'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + CREATE TABLE "track_request" ( + "id" SERIAL NOT NULL, + "requestedById" integer NOT NULL, + "modifiedById" integer, + "status" character varying(16) NOT NULL DEFAULT 'pending', + "artist" character varying(255) NOT NULL, + "title" character varying(255) NOT NULL, + "recordingMbid" character varying(64), + "source" character varying(16) NOT NULL DEFAULT 'manual', + "wishlistItemId" character varying(64), + "searchCount" integer NOT NULL DEFAULT 0, + "lastMatchCount" integer NOT NULL DEFAULT 0, + "lastError" character varying(512), + "lastCheckedAt" TIMESTAMP WITH TIME ZONE, + "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), + "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), + CONSTRAINT "PK_track_request" PRIMARY KEY ("id"), + CONSTRAINT "FK_track_request_requested_by" FOREIGN KEY ("requestedById") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT "FK_track_request_modified_by" FOREIGN KEY ("modifiedById") REFERENCES "user"("id") ON DELETE SET NULL ON UPDATE NO ACTION + ) + `); + await queryRunner.query( + 'CREATE INDEX "IDX_track_request_requester_created" ON "track_request" ("requestedById", "createdAt")' + ); + await queryRunner.query( + 'CREATE INDEX "IDX_track_request_status_created" ON "track_request" ("status", "createdAt")' + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query('DROP TABLE "track_request"'); + } +} diff --git a/server/migration/sqlite/1791050000000-CreateTrackRequests.test.ts b/server/migration/sqlite/1791050000000-CreateTrackRequests.test.ts new file mode 100644 index 0000000000..517f901127 --- /dev/null +++ b/server/migration/sqlite/1791050000000-CreateTrackRequests.test.ts @@ -0,0 +1,49 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { DataSource } from 'typeorm'; +import { CreateTrackRequests1791050000000 } from './1791050000000-CreateTrackRequests'; + +test('creates track requests owned by users', async () => { + const dataSource = await new DataSource({ + type: 'better-sqlite3', + database: ':memory:', + }).initialize(); + const queryRunner = dataSource.createQueryRunner(); + const migration = new CreateTrackRequests1791050000000(); + + try { + await queryRunner.query('PRAGMA foreign_keys = ON'); + await queryRunner.query( + 'CREATE TABLE "user" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL)' + ); + await queryRunner.query('INSERT INTO "user" ("id") VALUES (1)'); + await migration.up(queryRunner); + assert.equal(await queryRunner.hasTable('track_request'), true); + + await queryRunner.query(` + INSERT INTO "track_request" ("requestedById", "artist", "title") + VALUES (1, 'Band', 'Single') + `); + const [row] = await queryRunner.query( + 'SELECT "status", "source", "searchCount", "wishlistItemId" FROM "track_request"' + ); + assert.deepEqual(row, { + status: 'pending', + source: 'manual', + searchCount: 0, + wishlistItemId: null, + }); + + await queryRunner.query('DELETE FROM "user" WHERE "id" = 1'); + const [{ count }] = await queryRunner.query( + 'SELECT COUNT(*) AS "count" FROM "track_request"' + ); + assert.equal(count, 0); + + await migration.down(queryRunner); + assert.equal(await queryRunner.hasTable('track_request'), false); + } finally { + await queryRunner.release(); + await dataSource.destroy(); + } +}); diff --git a/server/migration/sqlite/1791050000000-CreateTrackRequests.ts b/server/migration/sqlite/1791050000000-CreateTrackRequests.ts new file mode 100644 index 0000000000..a471713f2a --- /dev/null +++ b/server/migration/sqlite/1791050000000-CreateTrackRequests.ts @@ -0,0 +1,39 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class CreateTrackRequests1791050000000 implements MigrationInterface { + name = 'CreateTrackRequests1791050000000'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + CREATE TABLE "track_request" ( + "id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, + "requestedById" integer NOT NULL, + "modifiedById" integer, + "status" varchar(16) NOT NULL DEFAULT 'pending', + "artist" varchar(255) NOT NULL, + "title" varchar(255) NOT NULL, + "recordingMbid" varchar(64), + "source" varchar(16) NOT NULL DEFAULT 'manual', + "wishlistItemId" varchar(64), + "searchCount" integer NOT NULL DEFAULT 0, + "lastMatchCount" integer NOT NULL DEFAULT 0, + "lastError" varchar(512), + "lastCheckedAt" datetime, + "createdAt" datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "FK_track_request_requested_by" FOREIGN KEY ("requestedById") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT "FK_track_request_modified_by" FOREIGN KEY ("modifiedById") REFERENCES "user" ("id") ON DELETE SET NULL ON UPDATE NO ACTION + ) + `); + await queryRunner.query( + 'CREATE INDEX "IDX_track_request_requester_created" ON "track_request" ("requestedById", "createdAt")' + ); + await queryRunner.query( + 'CREATE INDEX "IDX_track_request_status_created" ON "track_request" ("status", "createdAt")' + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query('DROP TABLE "track_request"'); + } +} diff --git a/server/routes/index.ts b/server/routes/index.ts index 8ad675f98f..75c8291861 100644 --- a/server/routes/index.ts +++ b/server/routes/index.ts @@ -85,6 +85,7 @@ import searchRoutes from './search'; import seriesRoutes from './series'; import serviceRoutes from './service'; import softwareRoutes from './software'; +import soulseekRoutes from './soulseek'; import tvRoutes from './tv'; import user from './user'; @@ -361,6 +362,7 @@ router.get( router.use('/user', isAuthenticated(), user); router.use('/live', isAuthenticated(), liveRoutes); router.use('/live-tv', isAuthenticated(), liveTvRoutes); +router.use('/soulseek', isAuthenticated(), soulseekRoutes); router.get('/settings/public', async (req, res) => { const settings = getSettings(); diff --git a/server/routes/settings/index.ts b/server/routes/settings/index.ts index 93cd14e8f7..713aaf6534 100644 --- a/server/routes/settings/index.ts +++ b/server/routes/settings/index.ts @@ -124,6 +124,7 @@ import prowlarrRoutes from './prowlarr'; import radarrRoutes from './radarr'; import readarrRoutes from './readarr'; import readerDeliveryRoutes from './readerDelivery'; +import slskdnRoutes from './slskdn'; import softwareAcquisitionRoutes from './softwareAcquisition'; import sonarrRoutes from './sonarr'; import tunerrRoutes from './tunerr'; @@ -1435,6 +1436,7 @@ settingsRoutes.use('/software-acquisition', softwareAcquisitionRoutes); settingsRoutes.use('/prowlarr', prowlarrRoutes); settingsRoutes.use('/download-clients', downloadClientRoutes); settingsRoutes.use('/tunerr', tunerrRoutes); +settingsRoutes.use('/slskdn', slskdnRoutes); export const filteredMainSettings = ( user: User, diff --git a/server/routes/settings/slskdn.ts b/server/routes/settings/slskdn.ts new file mode 100644 index 0000000000..44d3c947fd --- /dev/null +++ b/server/routes/settings/slskdn.ts @@ -0,0 +1,166 @@ +import SlskdnAPI, { SlskdnError } from '@server/api/slskdn'; +import { Permission } from '@server/lib/permissions'; +import { getSettings, type SlskdnSettings } from '@server/lib/settings'; +import { authorizedMutation } from '@server/middleware/authorizedMutation'; +import { REDACTED_SECRET } from '@server/utils/security'; +import { + normalizeServiceHostname, + normalizeUrlBase, +} from '@server/utils/serviceUrl'; +import { Router } from 'express'; + +type ParseResult = { value: T } | { error: string }; + +const isRecord = (value: unknown): value is Record => + !!value && typeof value === 'object' && !Array.isArray(value); + +export const parseSlskdnSettings = ( + value: unknown, + current: SlskdnSettings +): ParseResult => { + if (!isRecord(value)) return { error: 'slskdN settings must be an object.' }; + + const enabled = value.enabled ?? current.enabled; + if (typeof enabled !== 'boolean') { + return { error: 'Enabled must be true or false.' }; + } + + const hostnameValue = value.hostname ?? current.hostname; + const hostname = + typeof hostnameValue === 'string' && hostnameValue.length <= 255 + ? normalizeServiceHostname(hostnameValue) + : ''; + if (hostnameValue !== '' && !hostname) { + return { error: 'slskdN hostname is invalid.' }; + } + + const port = value.port ?? current.port; + if ( + typeof port !== 'number' || + !Number.isInteger(port) || + port < 1 || + port > 65_535 + ) { + return { error: 'Port must be between 1 and 65535.' }; + } + + const useSsl = value.useSsl ?? current.useSsl; + if (typeof useSsl !== 'boolean') { + return { error: 'HTTPS setting must be true or false.' }; + } + + const baseUrlValue = value.baseUrl ?? current.baseUrl; + if (typeof baseUrlValue !== 'string' || baseUrlValue.length > 512) { + return { error: 'URL base is invalid.' }; + } + const baseUrl = normalizeUrlBase(baseUrlValue); + if (baseUrlValue.trim() !== '' && !baseUrl) { + return { error: 'URL base is invalid.' }; + } + + const searchFilter = value.searchFilter ?? current.searchFilter; + if ( + typeof searchFilter !== 'string' || + searchFilter.length > 512 || + /[\r\n\0]/.test(searchFilter) + ) { + return { error: 'Search filter is invalid.' }; + } + + let apiKey = current.apiKey; + if (value.clearApiKey === true) { + apiKey = ''; + } else if ( + typeof value.apiKey === 'string' && + value.apiKey !== REDACTED_SECRET && + value.apiKey !== '' + ) { + apiKey = value.apiKey; + } else if (value.apiKey !== undefined && typeof value.apiKey !== 'string') { + return { error: 'API key is invalid.' }; + } + if (apiKey.length > 2048 || /[\r\n\0]/.test(apiKey)) { + return { error: 'API key is invalid.' }; + } + + if (enabled && (!hostname || !apiKey)) { + return { error: 'Enter the slskdN hostname and API key before enabling.' }; + } + + return { + value: { + enabled, + hostname, + port, + useSsl, + baseUrl, + apiKey, + searchFilter: searchFilter.trim(), + }, + }; +}; + +export const slskdnSettingsView = (settings: SlskdnSettings) => ({ + ...settings, + apiKey: settings.apiKey ? REDACTED_SECRET : '', + apiKeyConfigured: Boolean(settings.apiKey), +}); + +const slskdnRoutes = Router(); + +slskdnRoutes.get('/', (_req, res) => { + res.status(200).json(slskdnSettingsView(getSettings().slskdn)); +}); + +slskdnRoutes.put( + '/', + authorizedMutation(Permission.ADMIN, async (req, res) => { + const settings = getSettings(); + const parsed = parseSlskdnSettings(req.body, settings.slskdn); + if ('error' in parsed) return res.status(400).json({ error: parsed.error }); + try { + const saved = await settings.persistSection('slskdn', (current) => { + const locked = parseSlskdnSettings(req.body, current); + if ('error' in locked) throw new Error(locked.error); + return locked.value; + }); + return res.status(200).json(slskdnSettingsView(saved)); + } catch { + return res + .status(500) + .json({ error: 'slskdN settings could not be saved.' }); + } + }) +); + +slskdnRoutes.post( + '/test', + authorizedMutation(Permission.ADMIN, async (req, res) => { + const parsed = parseSlskdnSettings( + { ...(isRecord(req.body) ? req.body : {}), enabled: false }, + getSettings().slskdn + ); + if ('error' in parsed) return res.status(400).json({ error: parsed.error }); + if (!parsed.value.hostname || !parsed.value.apiKey) { + return res + .status(400) + .json({ error: 'Enter the slskdN hostname and API key.' }); + } + const api = new SlskdnAPI(parsed.value); + try { + const version = await api.getVersion(); + const features = await api.getFeatures(); + return res.status(200).json({ success: true, version, features }); + } catch (error) { + return res.status(502).json({ + success: false, + error: + error instanceof SlskdnError + ? error.message + : 'slskdN could not be reached.', + }); + } + }) +); + +export default slskdnRoutes; diff --git a/server/routes/soulseek.openapi.test.ts b/server/routes/soulseek.openapi.test.ts new file mode 100644 index 0000000000..c7fc9273fc --- /dev/null +++ b/server/routes/soulseek.openapi.test.ts @@ -0,0 +1,89 @@ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { after, before, describe, it } from 'node:test'; + +import { User } from '@server/entity/User'; +import { Permission } from '@server/lib/permissions'; +import { getSettings, type SlskdnSettings } from '@server/lib/settings'; +import type { Express } from 'express'; +import express from 'express'; +import * as OpenApiValidator from 'express-openapi-validator'; +import request from 'supertest'; +import soulseekRoutes from './soulseek'; + +describe('Soulseek routes behind the OpenAPI validator', () => { + let app: Express; + let previous: SlskdnSettings; + + before(() => { + previous = getSettings().slskdn; + getSettings().slskdn = { ...previous, enabled: false }; + app = express(); + app.use(express.json()); + app.use( + OpenApiValidator.middleware({ + apiSpec: path.join(process.cwd(), 'seerr-api.yml'), + validateRequests: true, + validateSecurity: false, + }) + ); + app.use((req, _res, next) => { + req.user = new User({ + id: 1, + permissions: Permission.MANAGE_REQUESTS | Permission.REQUEST, + }); + next(); + }); + app.use('/api/v1/soulseek', soulseekRoutes); + app.use( + ( + err: { status?: number; message?: string }, + _req: express.Request, + res: express.Response, + _next: express.NextFunction + ) => (void _next, res.status(err.status ?? 500).json(err)) + ); + }); + + after(() => { + getSettings().slskdn = previous; + }); + + it('reports slskdN as not set up', async () => { + const response = await request(app).get('/api/v1/soulseek/status'); + assert.equal(response.status, 200); + assert.equal(response.body.configured, false); + }); + + it('validates track request bodies before the route runs', async () => { + const empty = await request(app) + .post('/api/v1/soulseek/track-requests') + .send({ tracks: [] }); + assert.equal(empty.status, 400); + + const valid = await request(app) + .post('/api/v1/soulseek/track-requests') + .send({ + tracks: [{ artist: 'Band', title: 'Song', source: 'playlist' }], + }); + assert.equal( + valid.status, + 404, + 'passes validation, then reports not set up' + ); + }); + + it('rejects malformed album IDs', async () => { + const response = await request(app).get( + '/api/v1/soulseek/albums/not-an-id/issues' + ); + assert.equal(response.status, 400); + }); + + it('accepts a SongID source', async () => { + const response = await request(app) + .post('/api/v1/soulseek/songid') + .send({ source: 'Song that goes la la la' }); + assert.equal(response.status, 404); + }); +}); diff --git a/server/routes/soulseek.test.ts b/server/routes/soulseek.test.ts new file mode 100644 index 0000000000..c25835143f --- /dev/null +++ b/server/routes/soulseek.test.ts @@ -0,0 +1,407 @@ +import assert from 'node:assert/strict'; +import { once } from 'node:events'; +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { after, before, beforeEach, describe, it, mock } from 'node:test'; + +import MusicBrainz from '@server/api/musicbrainz'; +import { getRepository } from '@server/datasource'; +import TrackRequest from '@server/entity/TrackRequest'; +import { User } from '@server/entity/User'; +import { getSettings, type SlskdnSettings } from '@server/lib/settings'; +import { toSongIdView } from '@server/lib/soulseek/libraryHealth'; +import { + nextTrackStatus, + syncTrackRequests, + trackSearchText, +} from '@server/lib/soulseek/trackRequests'; +import { parseSlskdnSettings } from '@server/routes/settings/slskdn'; +import { setupTestDb } from '@server/test/db'; +import express from 'express'; +import request from 'supertest'; +import soulseekRoutes, { parseTrackInputs } from './soulseek'; + +const RELEASE_GROUP = '11111111-1111-4111-8111-111111111111'; +const RELEASE = '22222222-2222-4222-8222-222222222222'; + +interface FakeSlskdn { + server: Server; + port: number; + wishlist: Map>; + deleted: string[]; + remediated: string[][]; + apiKeys: (string | undefined)[]; +} + +const startFake = async (): Promise => { + const fake: FakeSlskdn = { + server: createServer(), + port: 0, + wishlist: new Map(), + deleted: [], + remediated: [], + apiKeys: [], + }; + let nextId = 1; + fake.server.on('request', (req, res) => { + fake.apiKeys.push(req.headers['x-api-key'] as string | undefined); + let body = ''; + req.on('data', (chunk) => (body += chunk)); + req.on('end', () => { + res.setHeader('Content-Type', 'application/json'); + const url = new URL(req.url ?? '/', 'http://localhost'); + if (url.pathname === '/api/v0/wishlist' && req.method === 'POST') { + const id = `00000000-0000-4000-8000-00000000000${nextId++}`; + const item = { id, ...JSON.parse(body), totalDownloadCount: 0 }; + fake.wishlist.set(id, item); + res.statusCode = 201; + res.end(JSON.stringify(item)); + return; + } + const wishlistMatch = /^\/api\/v0\/wishlist\/(.+)$/.exec(url.pathname); + if (wishlistMatch) { + const item = fake.wishlist.get(wishlistMatch[1]); + if (req.method === 'DELETE') { + fake.deleted.push(wishlistMatch[1]); + fake.wishlist.delete(wishlistMatch[1]); + res.statusCode = 204; + res.end(); + return; + } + res.statusCode = item ? 200 : 404; + res.end(JSON.stringify(item ?? {})); + return; + } + if (url.pathname === '/api/v0/library/health/issues') { + const release = url.searchParams.get('musicBrainzReleaseId'); + res.end( + JSON.stringify({ + issues: + release === RELEASE + ? [ + { + issueId: 'fixable', + type: 'SuspectedTranscode', + severity: 'High', + status: 'Detected', + title: 'Track 1', + canAutoFix: true, + }, + { + issueId: 'manual', + type: 'MissingMetadata', + severity: 'Low', + status: 'Detected', + canAutoFix: false, + }, + ] + : [], + }) + ); + return; + } + if (url.pathname === '/api/slskdn/library/remediate') { + fake.remediated.push(JSON.parse(body).issue_ids); + res.end(JSON.stringify({ job_id: 'job-1' })); + return; + } + if (url.pathname === '/api/v0/songid/runs' && req.method === 'POST') { + res.statusCode = 202; + res.end( + JSON.stringify({ + id: 'run-1', + status: 'queued', + albums: [], + tracks: [], + }) + ); + return; + } + if (url.pathname === '/api/v0/songid/runs/run-1') { + res.end( + JSON.stringify({ + id: 'run-1', + status: 'completed', + albums: [ + { + releaseId: RELEASE, + title: 'Album', + artist: 'Band', + isExact: true, + }, + ], + tracks: [], + }) + ); + return; + } + res.statusCode = 404; + res.end('{}'); + }); + }); + fake.server.listen(0, '127.0.0.1'); + await once(fake.server, 'listening'); + fake.port = (fake.server.address() as AddressInfo).port; + return fake; +}; + +const createApp = () => { + const app = express(); + app.use(express.json()); + app.use(async (req, _res, next) => { + const id = Number(req.header('x-test-user')); + req.user = + (await getRepository(User).findOne({ where: { id } })) ?? undefined; + next(); + }); + app.use('/soulseek', soulseekRoutes); + return app; +}; + +describe('Soulseek routes', () => { + let fake: FakeSlskdn; + let previous: SlskdnSettings; + let admin: User; + let friend: User; + const app = createApp(); + + setupTestDb(); + + before(async () => { + previous = getSettings().slskdn; + fake = await startFake(); + }); + + beforeEach(async () => { + fake.wishlist.clear(); + fake.deleted = []; + fake.remediated = []; + fake.apiKeys = []; + getSettings().slskdn = { + enabled: true, + hostname: '127.0.0.1', + port: fake.port, + useSsl: false, + baseUrl: '', + apiKey: 'key-1', + searchFilter: 'flac', + }; + admin = await getRepository(User).findOneByOrFail({ + email: 'admin@seerr.dev', + }); + friend = await getRepository(User).findOneByOrFail({ + email: 'friend@seerr.dev', + }); + mock.method(MusicBrainz.prototype, 'getReleaseGroupDetails', async () => ({ + releases: [{ id: RELEASE }], + })); + mock.method( + MusicBrainz.prototype, + 'getReleaseGroup', + async () => RELEASE_GROUP + ); + }); + + after(() => { + getSettings().slskdn = previous; + mock.restoreAll(); + fake.server.close(); + }); + + const as = (user: User) => ({ + get: (path: string) => + request(app).get(path).set('x-test-user', String(user.id)), + post: (path: string, body?: object) => + request(app) + .post(path) + .set('x-test-user', String(user.id)) + .send(body ?? {}), + delete: (path: string) => + request(app).delete(path).set('x-test-user', String(user.id)), + }); + + it('queues a track for approval, then searches and completes it', async () => { + const created = await as(friend).post('/soulseek/track-requests', { + tracks: [{ artist: 'Band', title: 'B-Side!', source: 'playlist' }], + }); + assert.equal(created.status, 201); + const [track] = created.body.results; + assert.equal(track.status, 'pending'); + assert.equal(fake.wishlist.size, 0); + + const repeat = await as(friend).post('/soulseek/track-requests', { + tracks: [{ artist: 'Band', title: 'B-Side!' }], + }); + assert.equal(repeat.body.results[0].id, track.id, 'duplicates are reused'); + + const approved = await as(admin).post( + `/soulseek/track-requests/${track.id}/approve` + ); + assert.equal(approved.status, 200); + assert.equal(approved.body.status, 'searching'); + const [item] = fake.wishlist.values(); + assert.equal(item.searchText, 'Band B Side'); + assert.equal(item.filter, 'flac'); + assert.equal(item.autoDownload, true); + assert.equal(item.maxDownloads, 1); + assert.ok(fake.apiKeys.every((key) => key === 'key-1')); + + item.totalDownloadCount = 1; + await syncTrackRequests(); + const stored = await getRepository(TrackRequest).findOneByOrFail({ + id: track.id, + }); + assert.equal(stored.status, 'completed'); + }); + + it('starts manager requests immediately and cancels them in slskdN', async () => { + const created = await as(admin).post('/soulseek/track-requests', { + tracks: [{ artist: 'Band', title: 'Single' }], + }); + const [track] = created.body.results; + assert.equal(track.status, 'searching'); + + const forbidden = await as(friend).delete( + `/soulseek/track-requests/${track.id}` + ); + assert.equal(forbidden.status, 403); + + const cancelled = await as(admin).delete( + `/soulseek/track-requests/${track.id}` + ); + assert.equal(cancelled.body.status, 'cancelled'); + assert.equal(fake.deleted.length, 1); + }); + + it('lists album issues and only remediates fixable ones for that album', async () => { + const denied = await as(friend).get( + `/soulseek/albums/${RELEASE_GROUP}/issues` + ); + assert.equal(denied.status, 403); + + const issues = await as(admin).get( + `/soulseek/albums/${RELEASE_GROUP}/issues` + ); + assert.equal(issues.status, 200); + assert.deepEqual( + issues.body.issues.map((issue: { issueId: string }) => issue.issueId), + ['fixable', 'manual'] + ); + + const fixed = await as(admin).post( + `/soulseek/albums/${RELEASE_GROUP}/remediate`, + { issueIds: ['fixable', 'manual', 'other-album'] } + ); + assert.equal(fixed.status, 202); + assert.deepEqual(fake.remediated, [['fixable']]); + + const nothing = await as(admin).post( + `/soulseek/albums/${RELEASE_GROUP}/remediate`, + { issueIds: ['manual'] } + ); + assert.equal(nothing.status, 409); + }); + + it('lets only the requester read a SongID run', async () => { + const started = await as(friend).post('/soulseek/songid', { + source: 'https://example.com/clip', + }); + assert.equal(started.status, 202); + const other = await getRepository(User).findOneByOrFail({ + email: 'demo@seerr.dev', + }); + assert.equal((await as(other).get('/soulseek/songid/run-1')).status, 404); + + const result = await as(friend).get('/soulseek/songid/run-1'); + assert.equal(result.status, 200); + assert.equal(result.body.albums[0].releaseGroupId, RELEASE_GROUP); + }); +}); + +describe('Soulseek helpers', () => { + it('builds Soulseek-safe search text', () => { + assert.equal(trackSearchText('AC/DC', 'T.N.T.'), 'AC DC T N T'); + assert.equal( + trackSearchText('Björk', "It's Oh So Quiet"), + "Björk It's Oh So Quiet" + ); + }); + + it('decides track status from the wishlist item', () => { + const now = new Date('2026-10-06T00:00:00Z'); + const request = { + status: 'searching' as const, + createdAt: new Date('2026-10-05T00:00:00Z'), + }; + assert.equal( + nextTrackStatus(request, { totalDownloadCount: 1 }, now).status, + 'completed' + ); + assert.equal( + nextTrackStatus(request, { totalDownloadCount: 0 }, now).status, + 'searching' + ); + assert.equal(nextTrackStatus(request, undefined, now).status, 'failed'); + const stale = nextTrackStatus( + { status: 'searching', createdAt: new Date('2026-09-01T00:00:00Z') }, + { totalDownloadCount: 0 }, + now + ); + assert.equal(stale.status, 'failed'); + assert.equal(stale.removeWishlistItem, true); + }); + + it('validates track input', () => { + assert.ok('error' in parseTrackInputs({ tracks: [] })); + assert.ok('error' in parseTrackInputs({ tracks: [{ artist: 'A' }] })); + const parsed = parseTrackInputs({ + tracks: [ + { + artist: ' A ', + title: 'B', + recordingMbid: 'not-an-id', + source: 'evil', + }, + ], + }); + assert.ok(Array.isArray(parsed)); + assert.deepEqual(parsed[0], { + artist: 'A', + title: 'B', + recordingMbid: undefined, + source: 'manual', + }); + }); + + it('requires a hostname and API key before enabling slskdN', () => { + const current = { + enabled: false, + hostname: '', + port: 5030, + useSsl: false, + baseUrl: '', + apiKey: '', + searchFilter: '', + }; + assert.ok('error' in parseSlskdnSettings({ enabled: true }, current)); + const parsed = parseSlskdnSettings( + { enabled: true, hostname: 'slskdn', apiKey: 'k' }, + current + ); + assert.ok('value' in parsed); + }); + + it('keeps SongID albums without a resolvable release group', async () => { + const view = await toSongIdView( + { + id: 'r', + status: 'completed', + albums: [{ releaseId: RELEASE, title: 'A', artist: 'B' }], + }, + async () => { + throw new Error('offline'); + } + ); + assert.equal(view.albums[0].releaseGroupId, undefined); + }); +}); diff --git a/server/routes/soulseek.ts b/server/routes/soulseek.ts new file mode 100644 index 0000000000..235d529142 --- /dev/null +++ b/server/routes/soulseek.ts @@ -0,0 +1,340 @@ +import SlskdnAPI, { SlskdnError } from '@server/api/slskdn'; +import { getRepository } from '@server/datasource'; +import TrackRequest, { + ACTIVE_TRACK_STATUSES, +} from '@server/entity/TrackRequest'; +import { Permission } from '@server/lib/permissions'; +import { getSettings } from '@server/lib/settings'; +import { + getAlbumIssues, + remediateAlbumIssues, + toSongIdView, +} from '@server/lib/soulseek/libraryHealth'; +import { + TrackRequestError, + canRequestTracks, + cancelTrackRequest, + createTrackRequests, + declineTrackRequest, + isSlskdnConfigured, + startTrackSearch, + type TrackInput, +} from '@server/lib/soulseek/trackRequests'; +import { parseNonNegativeRouteId } from '@server/utils/routeId'; +import type { Response } from 'express'; +import { Router } from 'express'; +import { In } from 'typeorm'; + +const MBID_PATTERN = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const MAX_TRACKS_PER_REQUEST = 50; +const MAX_SONGID_SOURCE = 2048; + +/** SongID runs started by each user, so users can only read their own. */ +const songIdOwners = new Map(); +const MAX_TRACKED_SONGID_RUNS = 2_000; + +const soulseekRoutes = Router(); + +const sendError = (res: Response, error: unknown) => { + if (error instanceof TrackRequestError) { + return res.status(error.status).json({ message: error.message }); + } + if (error instanceof SlskdnError) { + return res + .status(error.kind === 'unsupported' ? 503 : 502) + .json({ message: error.message }); + } + throw error; +}; + +export const trackRequestView = (request: TrackRequest) => ({ + id: request.id, + status: request.status, + artist: request.artist, + title: request.title, + recordingMbid: request.recordingMbid ?? undefined, + source: request.source, + searchCount: request.searchCount, + lastMatchCount: request.lastMatchCount, + lastError: request.lastError ?? undefined, + createdAt: request.createdAt, + updatedAt: request.updatedAt, + requestedBy: request.requestedBy + ? { + id: request.requestedBy.id, + displayName: request.requestedBy.displayName, + } + : undefined, +}); + +const text = (value: unknown, max: number) => + typeof value === 'string' ? value.trim().slice(0, max) : ''; + +export const parseTrackInputs = ( + body: unknown +): TrackInput[] | { error: string } => { + const tracks = + body && typeof body === 'object' && !Array.isArray(body) + ? (body as { tracks?: unknown }).tracks + : undefined; + if (!Array.isArray(tracks) || tracks.length === 0) { + return { error: 'Add at least one track.' }; + } + if (tracks.length > MAX_TRACKS_PER_REQUEST) { + return { error: `Request up to ${MAX_TRACKS_PER_REQUEST} tracks at once.` }; + } + const parsed: TrackInput[] = []; + for (const track of tracks) { + if (!track || typeof track !== 'object') { + return { error: 'Each track needs an artist and title.' }; + } + const value = track as Record; + const artist = text(value.artist, 255); + const title = text(value.title, 255); + if (!artist || !title) { + return { error: 'Each track needs an artist and title.' }; + } + const recordingMbid = + typeof value.recordingMbid === 'string' && + MBID_PATTERN.test(value.recordingMbid) + ? value.recordingMbid.toLowerCase() + : undefined; + const source = ['playlist', 'songid', 'manual'].includes( + String(value.source) + ) + ? String(value.source) + : 'manual'; + parsed.push({ artist, title, recordingMbid, source }); + } + return parsed; +}; + +soulseekRoutes.get('/status', async (req, res) => { + const configured = isSlskdnConfigured(); + return res.status(200).json({ + configured, + canRequest: req.user ? canRequestTracks(req.user) : false, + }); +}); + +soulseekRoutes.get('/track-requests', async (req, res) => { + const user = req.user!; + const canViewAll = user.hasPermission( + [Permission.MANAGE_REQUESTS, Permission.REQUEST_VIEW], + { type: 'or' } + ); + const scopeAll = req.query.scope === 'all' && canViewAll; + const activeOnly = req.query.filter === 'active'; + const take = Math.min( + 100, + Math.max(1, Number.parseInt(String(req.query.take ?? '50'), 10) || 50) + ); + const skip = Math.max( + 0, + Number.parseInt(String(req.query.skip ?? '0'), 10) || 0 + ); + const [results, total] = await getRepository(TrackRequest).findAndCount({ + where: { + ...(scopeAll ? {} : { requestedById: user.id }), + ...(activeOnly ? { status: In(ACTIVE_TRACK_STATUSES) } : {}), + }, + order: { createdAt: 'DESC' }, + take, + skip, + }); + return res.status(200).json({ + pageInfo: { total, take, skip }, + results: results.map(trackRequestView), + }); +}); + +soulseekRoutes.post('/track-requests', async (req, res) => { + const user = req.user!; + if (!canRequestTracks(user)) { + return res + .status(403) + .json({ message: 'You do not have permission to request music.' }); + } + const tracks = parseTrackInputs(req.body); + if ('error' in tracks) { + return res.status(400).json({ message: tracks.error }); + } + try { + const created = await createTrackRequests(user, tracks); + return res.status(201).json({ results: created.map(trackRequestView) }); + } catch (error) { + return sendError(res, error); + } +}); + +const loadTrackRequest = async (rawId: string) => { + const id = parseNonNegativeRouteId(rawId); + if (id === undefined) return undefined; + return getRepository(TrackRequest).findOne({ where: { id } }); +}; + +soulseekRoutes.post('/track-requests/:id/approve', async (req, res) => { + if (!req.user?.hasPermission(Permission.MANAGE_REQUESTS)) { + return res.status(403).json({ message: 'Access denied.' }); + } + const request = await loadTrackRequest(req.params.id); + if (!request) return res.status(404).json({ message: 'Request not found.' }); + if (request.status !== 'pending') { + return res + .status(409) + .json({ message: 'Only pending requests can be approved.' }); + } + try { + return res + .status(200) + .json(trackRequestView(await startTrackSearch(request, req.user))); + } catch (error) { + return sendError(res, error); + } +}); + +soulseekRoutes.post('/track-requests/:id/decline', async (req, res) => { + if (!req.user?.hasPermission(Permission.MANAGE_REQUESTS)) { + return res.status(403).json({ message: 'Access denied.' }); + } + const request = await loadTrackRequest(req.params.id); + if (!request) return res.status(404).json({ message: 'Request not found.' }); + try { + return res + .status(200) + .json(trackRequestView(await declineTrackRequest(request, req.user))); + } catch (error) { + return sendError(res, error); + } +}); + +soulseekRoutes.delete('/track-requests/:id', async (req, res) => { + const user = req.user!; + const request = await loadTrackRequest(req.params.id); + if (!request) return res.status(404).json({ message: 'Request not found.' }); + if ( + !user.hasPermission(Permission.MANAGE_REQUESTS) && + request.requestedById !== user.id + ) { + return res.status(403).json({ message: 'Access denied.' }); + } + try { + return res + .status(200) + .json(trackRequestView(await cancelTrackRequest(request, user))); + } catch (error) { + return sendError(res, error); + } +}); + +soulseekRoutes.get('/albums/:releaseGroupId/issues', async (req, res) => { + if (!req.user?.hasPermission(Permission.MANAGE_REQUESTS)) { + return res.status(403).json({ message: 'Access denied.' }); + } + if (!isSlskdnConfigured()) { + return res.status(200).json({ configured: false, issues: [] }); + } + const releaseGroupId = req.params.releaseGroupId; + if (!MBID_PATTERN.test(releaseGroupId)) { + return res.status(400).json({ message: 'Invalid album ID.' }); + } + try { + return res.status(200).json({ + configured: true, + issues: await getAlbumIssues(releaseGroupId.toLowerCase()), + }); + } catch (error) { + return sendError(res, error); + } +}); + +soulseekRoutes.post('/albums/:releaseGroupId/remediate', async (req, res) => { + if (!req.user?.hasPermission(Permission.MANAGE_REQUESTS)) { + return res.status(403).json({ message: 'Access denied.' }); + } + if (!isSlskdnConfigured()) { + return res.status(404).json({ message: 'slskdN is not set up.' }); + } + const releaseGroupId = req.params.releaseGroupId; + const issueIds = (req.body as { issueIds?: unknown })?.issueIds; + if ( + !MBID_PATTERN.test(releaseGroupId) || + !Array.isArray(issueIds) || + issueIds.length === 0 || + issueIds.length > 200 || + !issueIds.every((id) => typeof id === 'string' && id.length <= 128) + ) { + return res.status(400).json({ message: 'Choose issues to fix.' }); + } + try { + const result = await remediateAlbumIssues( + releaseGroupId.toLowerCase(), + issueIds as string[] + ); + if (result.issueCount === 0) { + return res + .status(409) + .json({ message: 'None of those issues can be fixed automatically.' }); + } + return res.status(202).json(result); + } catch (error) { + return sendError(res, error); + } +}); + +soulseekRoutes.post('/songid', async (req, res) => { + const user = req.user!; + if (!canRequestTracks(user)) { + return res.status(403).json({ message: 'Access denied.' }); + } + if (!isSlskdnConfigured()) { + return res.status(404).json({ message: 'slskdN is not set up.' }); + } + const source = text( + (req.body as { source?: unknown })?.source, + MAX_SONGID_SOURCE + 1 + ); + if (!source || source.length > MAX_SONGID_SOURCE) { + return res + .status(400) + .json({ message: 'Paste a link or describe the song.' }); + } + try { + const run = await new SlskdnAPI(getSettings().slskdn).createSongIdRun( + source + ); + if (songIdOwners.size >= MAX_TRACKED_SONGID_RUNS) { + const oldest = songIdOwners.keys().next().value; + if (oldest) songIdOwners.delete(oldest); + } + songIdOwners.set(run.id, user.id); + return res.status(202).json(await toSongIdView(run)); + } catch (error) { + return sendError(res, error); + } +}); + +soulseekRoutes.get('/songid/:id', async (req, res) => { + const user = req.user!; + const owner = songIdOwners.get(req.params.id); + if ( + owner === undefined || + (owner !== user.id && !user.hasPermission(Permission.MANAGE_REQUESTS)) + ) { + return res.status(404).json({ message: 'Identification not found.' }); + } + try { + const run = await new SlskdnAPI(getSettings().slskdn).getSongIdRun( + req.params.id + ); + if (!run) { + return res.status(404).json({ message: 'Identification not found.' }); + } + return res.status(200).json(await toSongIdView(run)); + } catch (error) { + return sendError(res, error); + } +}); + +export default soulseekRoutes; diff --git a/src/components/Settings/SettingsJobsCache/index.tsx b/src/components/Settings/SettingsJobsCache/index.tsx index acc65a1185..d0c8431162 100644 --- a/src/components/Settings/SettingsJobsCache/index.tsx +++ b/src/components/Settings/SettingsJobsCache/index.tsx @@ -102,6 +102,7 @@ const messages: { [messageName: string]: MessageDescriptor } = defineMessages( 'download-sync': 'Download Sync', 'software-request-reconciliation': 'Software Request Reconciliation', 'live-tv-sync': 'Live TV Sync', + 'soulseek-sync': 'Soulseek Sync', 'download-recovery': 'Download Recovery', 'download-sync-reset': 'Download Sync Reset', 'image-cache-cleanup': 'Image Cache Cleanup', diff --git a/src/i18n/locale/en.json b/src/i18n/locale/en.json index 7aa26ef389..ae4d6f52fb 100644 --- a/src/i18n/locale/en.json +++ b/src/i18n/locale/en.json @@ -3253,6 +3253,7 @@ "components.Settings.SettingsJobsCache.size": "Size", "components.Settings.SettingsJobsCache.software-request-reconciliation": "Software Request Reconciliation", "components.Settings.SettingsJobsCache.sonarr-scan": "Sonarr Scan", + "components.Settings.SettingsJobsCache.soulseek-sync": "Soulseek Sync", "components.Settings.SettingsJobsCache.unknownJob": "Unknown Job", "components.Settings.SettingsJobsCache.usersavatars": "Users' Avatars", "components.Settings.SettingsLogs.copiedLogMessage": "Copied log message to clipboard.", From 715960eddfce986afd79cf859f2820547104dd94 Mon Sep 17 00:00:00 2001 From: Keith Snape Date: Tue, 6 Oct 2026 15:39:05 -0600 Subject: [PATCH 20/58] feat: add Soulseek request, album health, and SongID UI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Offer unmatched playlist tracks to Soulseek from the bulk request dialog, add Track Requests and Identify a Song pages, a manager-only Library Health dialog on album pages, and a Soulseek (slskdN) section under Settings → Services. Document setup. Co-Authored-By: Claude Opus 5.5 --- .../ng-ecosystem-integration-plan.md | 7 + docs/using-seerr/soulseek-slskdn.md | 45 ++ release-notes/2026-10-06-soulseek-slskdn.md | 9 + src/components/MusicDetails/index.tsx | 2 + .../RequestModal/BulkRequestModal.tsx | 8 + src/components/Settings/SettingsServices.tsx | 2 + src/components/Settings/SettingsSlskdn.tsx | 386 ++++++++++++++++++ .../Soulseek/AlbumLibraryHealthButton.tsx | 204 +++++++++ src/components/Soulseek/SongIdentify.tsx | 308 ++++++++++++++ .../Soulseek/SoulseekUnmatchedTracks.test.tsx | 98 +++++ .../Soulseek/SoulseekUnmatchedTracks.tsx | 108 +++++ src/components/Soulseek/TrackRequestList.tsx | 298 ++++++++++++++ src/i18n/locale/en.json | 99 +++++ src/pages/identify.tsx | 6 + src/pages/track-requests.tsx | 6 + 15 files changed, 1586 insertions(+) create mode 100644 docs/using-seerr/soulseek-slskdn.md create mode 100644 release-notes/2026-10-06-soulseek-slskdn.md create mode 100644 src/components/Settings/SettingsSlskdn.tsx create mode 100644 src/components/Soulseek/AlbumLibraryHealthButton.tsx create mode 100644 src/components/Soulseek/SongIdentify.tsx create mode 100644 src/components/Soulseek/SoulseekUnmatchedTracks.test.tsx create mode 100644 src/components/Soulseek/SoulseekUnmatchedTracks.tsx create mode 100644 src/components/Soulseek/TrackRequestList.tsx create mode 100644 src/pages/identify.tsx create mode 100644 src/pages/track-requests.tsx diff --git a/docs/maintainers/ng-ecosystem-integration-plan.md b/docs/maintainers/ng-ecosystem-integration-plan.md index b886f6e6ba..d153b00fb7 100644 --- a/docs/maintainers/ng-ecosystem-integration-plan.md +++ b/docs/maintainers/ng-ecosystem-integration-plan.md @@ -59,6 +59,13 @@ human visual acceptance yet; testing is planned after the full build-out. | 2 UI | built | On Live TV button + dialog on movie/series pages, `/recordings` page, Settings → Services section. Component test (4). Needs human visual review. No sidebar entry yet (sidebar links cannot be conditional on settings today). | | 2 Tunerr fork: rule-driven recorder | done (local branch) | `~/Code/iptvtunerr` branch `feat/seerrng-recording-rules` (commit `0440d64`, not pushed): `title_equals`, `start_after`/`start_before`, response-only `features`, `catchup-daemon -rules-only`. 6 new Go tests; `go test ./...` passed. Tunerr `scripts/verify` not run (local Go 1.27 `gofmt` flags vendored files). Operators must run the recorder with `-rules-only`. | | 2 Live check: deck proxy + Basic auth from another host | pending | Verified from Tunerr source only; needs a local Tunerr run. | +| 3 slskdN client + settings | done | `server/api/slskdn.ts` (X-API-Key), per-feature probes (wishlist, library health, SongID); `/api/v1/settings/slskdn`. Endpoints read from `~/slskdn-current` source. | +| 3 Track requests | done | `TrackRequest` entity + migrations `1791050000000`, wishlist-backed search with approval, `soulseek-sync` job, `/api/v1/soulseek/track-requests*`. Integration test against a fake slskdN. | +| 3 Album fixes (library health) | done | Release group → releases via MusicBrainz, then slskdN issues per release; remediation only for that album's auto-fixable issues. Manager-only. | +| 3 SongID | done | `/api/v1/soulseek/songid`; results readable only by the requester or a manager (in-memory owner map, lost on restart). Album candidates resolved to release groups. | +| 3 UI | built | Bulk dialog Soulseek card for unmatched playlist tracks, `/track-requests`, `/identify`, album Library Health button, Settings section. Component test for the bulk-dialog card. Needs human visual review. | +| 3 Peer previews | not started | Open question 3 (legal/permission decision) still applies. | +| 3 slskdN download progress in live progress | pending | slskdN transfers are not torrents; needs a separate adapter. | | 2 Sports "follow my team" | pending | | | 2 Recently aired shelf, channel requests, Plex→Jellyfin users | pending | | | 2 Recording notifications | pending | Requests do not notify yet. | diff --git a/docs/using-seerr/soulseek-slskdn.md b/docs/using-seerr/soulseek-slskdn.md new file mode 100644 index 0000000000..cc96750a8a --- /dev/null +++ b/docs/using-seerr/soulseek-slskdn.md @@ -0,0 +1,45 @@ +--- +title: Soulseek through slskdN +description: Request single tracks, fix flagged albums, and identify songs with slskdN. +sidebar_position: 9 +--- + +# Soulseek through slskdN + +Lidarr can already use slskdN as a download client for albums. Connecting +[slskdN](https://github.com/snapetech/slskdn) to SeerrNG directly adds three +things Lidarr cannot do: + +- **Single-track requests.** Playlist imports list tracks with no confident + album match. When slskdN is connected, the bulk request dialog offers + **Request … from Soulseek** for those tracks. Each becomes a slskdN wishlist + entry that downloads the first good match. +- **Album fixes.** Managers see **Library Health** on music album pages. It + lists issues slskdN's library-health scanner found for the album (suspected + transcodes, missing tracks, corrupted files, and similar), and starts + slskdN's remediation for issues it can fix automatically. +- **Song identification.** **Identify a Song** (`/identify`) sends a link or a + description to slskdN SongID. Album matches link to their SeerrNG album page; + track matches can be requested from Soulseek. + +Track requests follow the usual approval rules: people with **Manage +Requests**, **Auto-Approve**, or **Auto-Approve Music** start searching +immediately, and other requests wait for approval on **Track Requests** +(`/track-requests`). Each person can have up to 50 active track requests. A +search that finds nothing for two weeks is marked failed and its wishlist entry +removed. + +## Set up + +1. In slskdN, create an API key with the **read-write** role. SongID needs the + **administrator** role; without it, the other features still work. +2. Open **Settings → Services → Soulseek (slskdN)** in SeerrNG and enter the + hostname, port (default `5030`), and API key. +3. Select **Test Connection**. SeerrNG shows the slskdN version and which of + track requests, album fixes, and SongID this slskdN and key support. Plain + slskd and slskr installs report the slskdN-only features as unavailable. +4. Optionally set a **Search Filter** (a slskdN wishlist filter) to apply to + every track request. +5. Turn on **Enable Soulseek Requests** and select **Save Changes**. + +The **Soulseek Sync** job checks active track requests every two minutes. diff --git a/release-notes/2026-10-06-soulseek-slskdn.md b/release-notes/2026-10-06-soulseek-slskdn.md new file mode 100644 index 0000000000..14394c983f --- /dev/null +++ b/release-notes/2026-10-06-soulseek-slskdn.md @@ -0,0 +1,9 @@ +--- +category: added +audience: users, operators +area: soulseek +action: Optional. Connect slskdN under Settings → Services → Soulseek (slskdN) with a read-write API key. +breaking: false +--- + +SeerrNG can now request single tracks from Soulseek through slskdN, including playlist tracks with no album match, let managers fix albums slskdN flags as transcoded or incomplete, and identify songs with SongID. diff --git a/src/components/MusicDetails/index.tsx b/src/components/MusicDetails/index.tsx index 0b42988fc5..53b608173c 100644 --- a/src/components/MusicDetails/index.tsx +++ b/src/components/MusicDetails/index.tsx @@ -9,6 +9,7 @@ import PageTitle from '@app/components/Common/PageTitle'; import Tooltip from '@app/components/Common/Tooltip'; import IssueBlock from '@app/components/IssueBlock'; import MusicDetailsLayout from '@app/components/MusicDetails/MusicDetailsLayout'; +import AlbumLibraryHealthButton from '@app/components/Soulseek/AlbumLibraryHealthButton'; import useTitleBlocklist from '@app/hooks/useTitleBlocklist'; import useToasts from '@app/hooks/useToasts'; import { getQueryParamString } from '@app/hooks/useUpdateQueryParams'; @@ -508,6 +509,7 @@ const MusicDetails = () => { const secondaryActions = ( <> + {albumId && } {canWatchlist && ( + {mediaType === 'music' && !summary && ( + item.matchStatus === 'unmatched') + .map((item) => ({ title: item.title, artist: item.artist }))} + /> + )} {summary ? (
{ + {overrideRuleModal.open && radarrData && diff --git a/src/components/Settings/SettingsSlskdn.tsx b/src/components/Settings/SettingsSlskdn.tsx new file mode 100644 index 0000000000..72f4c2211c --- /dev/null +++ b/src/components/Settings/SettingsSlskdn.tsx @@ -0,0 +1,386 @@ +import Alert from '@app/components/Common/Alert'; +import Button from '@app/components/Common/Button'; +import LoadingSpinner from '@app/components/Common/LoadingSpinner'; +import SettingsField from '@app/components/Settings/SettingsField'; +import useToasts from '@app/hooks/useToasts'; +import defineMessages from '@app/utils/defineMessages'; +import type { SlskdnSettings } from '@server/lib/settings'; +import axios from 'axios'; +import type { FormEvent } from 'react'; +import { useEffect, useState } from 'react'; +import { useIntl } from 'react-intl'; +import useSWR from 'swr'; + +const REDACTED = '[REDACTED]'; + +const messages = defineMessages('components.Settings.SettingsSlskdn', { + title: 'Soulseek (slskdN)', + description: + 'Connect slskdN to request single tracks that Lidarr cannot, fix albums slskdN flags as transcoded or incomplete, and identify songs with SongID. Lidarr can keep using slskdN for album downloads as before.', + keyNote: + 'Use an slskdN API key with the read-write role. SongID needs the administrator role.', + loadError: 'slskdN settings could not be loaded.', + enabled: 'Enable Soulseek Requests', + hostname: 'Hostname or IP Address', + port: 'Port', + useSsl: 'Use HTTPS', + baseUrl: 'URL Base', + apiKey: 'API Key', + savedSecret: 'Saved — leave empty to keep it', + clearSecret: 'Remove the saved API key', + searchFilter: 'Search Filter', + searchFilterDescription: + 'Optional slskdN wishlist filter for track requests, for example to prefer lossless files.', + test: 'Test Connection', + testing: 'Testing…', + testOk: 'Connected to slskdN {version}.', + feature: + '{feature}: {available, select, true {available} other {not available}}', + wishlist: 'Track requests (wishlist)', + libraryHealth: 'Album fixes (library health)', + songId: 'SongID', + save: 'Save Changes', + saving: 'Saving…', + cancel: 'Discard Changes', + unsavedChanges: 'You have unsaved changes.', + saveSuccess: 'slskdN settings saved.', + saveError: 'slskdN settings could not be saved.', +}); + +type Draft = Omit & { + port: string; + clearApiKey: boolean; +}; + +interface TestResult { + success: boolean; + version?: string; + features?: { wishlist: boolean; libraryHealth: boolean; songId: boolean }; + error?: string; +} + +const toDraft = (settings: SlskdnSettings): Draft => ({ + ...settings, + port: String(settings.port), + clearApiKey: false, +}); + +const toPayload = (draft: Draft) => ({ + enabled: draft.enabled, + hostname: draft.hostname.trim(), + port: Number(draft.port), + useSsl: draft.useSsl, + baseUrl: draft.baseUrl.trim(), + apiKey: draft.apiKey, + clearApiKey: draft.clearApiKey, + searchFilter: draft.searchFilter, +}); + +const SettingsSlskdn = () => { + const intl = useIntl(); + const { addToast } = useToasts(); + const { data, error, mutate } = useSWR( + '/api/v1/settings/slskdn' + ); + const [draft, setDraft] = useState(); + const [isDirty, setIsDirty] = useState(false); + const [isSaving, setIsSaving] = useState(false); + const [saveError, setSaveError] = useState(); + const [testing, setTesting] = useState(false); + const [testResult, setTestResult] = useState(); + + useEffect(() => { + if (data && !isDirty) setDraft(toDraft(data)); + }, [data, isDirty]); + + const update = (patch: Partial) => { + setDraft((current) => (current ? { ...current, ...patch } : current)); + setIsDirty(true); + setTestResult(undefined); + }; + + const submit = async (event: FormEvent) => { + event.preventDefault(); + if (!draft) return; + setIsSaving(true); + setSaveError(undefined); + try { + const response = await axios.put( + '/api/v1/settings/slskdn', + toPayload(draft) + ); + await mutate(response.data, { revalidate: false }); + setIsDirty(false); + addToast(intl.formatMessage(messages.saveSuccess), { + appearance: 'success', + autoDismiss: true, + }); + } catch (failure) { + setSaveError( + axios.isAxiosError(failure) && + typeof failure.response?.data?.error === 'string' + ? failure.response.data.error + : intl.formatMessage(messages.saveError) + ); + } finally { + setIsSaving(false); + } + }; + + const test = async () => { + if (!draft) return; + setTesting(true); + setTestResult(undefined); + try { + const response = await axios.post( + '/api/v1/settings/slskdn/test', + toPayload(draft) + ); + setTestResult(response.data); + } catch (failure) { + setTestResult({ + success: false, + error: + axios.isAxiosError(failure) && + typeof failure.response?.data?.error === 'string' + ? failure.response.data.error + : undefined, + }); + } finally { + setTesting(false); + } + }; + + const textField = ( + id: 'hostname' | 'port' | 'baseUrl' | 'searchFilter', + label: string, + options: { + inputMode?: 'numeric'; + maxLength?: number; + description?: string; + } = {} + ) => ( +
+ +
+
+ update({ [id]: event.currentTarget.value })} + /> +
+ {options.description && ( +

{options.description}

+ )} +
+
+ ); + + return ( +
+

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

+

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

+
+ {!data && !error && } + {error && ( + + )} + {data && draft && !error && ( +
void submit(event)}> + {saveError && } + +

{intl.formatMessage(messages.keyNote)}

+
+
+ +
+
+ update({ enabled: checked })} + /> +
+
+
+ {textField('hostname', intl.formatMessage(messages.hostname))} + {textField('port', intl.formatMessage(messages.port), { + inputMode: 'numeric', + maxLength: 5, + })} +
+ +
+
+ update({ useSsl: checked })} + /> +
+
+
+ {textField('baseUrl', intl.formatMessage(messages.baseUrl), { + maxLength: 512, + })} +
+ +
+
+ + update({ + apiKey: + event.currentTarget.value || + (data.apiKey ? REDACTED : ''), + }) + } + /> +
+ {data.apiKey && ( +
+ + update({ clearApiKey: checked }) + } + /> + {intl.formatMessage(messages.clearSecret)} +
+ )} +
+
+ {textField( + 'searchFilter', + intl.formatMessage(messages.searchFilter), + { + maxLength: 512, + description: intl.formatMessage( + messages.searchFilterDescription + ), + } + )} + {testResult && + (testResult.success ? ( + +

+ {intl.formatMessage(messages.testOk, { + version: testResult.version ?? '', + })} +

+ {testResult.features && + ( + [ + ['wishlist', messages.wishlist], + ['libraryHealth', messages.libraryHealth], + ['songId', messages.songId], + ] as const + ).map(([key, label]) => ( +

+ {intl.formatMessage(messages.feature, { + feature: intl.formatMessage(label), + available: String(testResult.features?.[key]), + })} +

+ ))} +
+ ) : ( + + ))} + {isDirty && ( +

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

+ )} +
+
+ + {isDirty && ( + + )} + +
+
+ + )} +
+
+ ); +}; + +export default SettingsSlskdn; diff --git a/src/components/Soulseek/AlbumLibraryHealthButton.tsx b/src/components/Soulseek/AlbumLibraryHealthButton.tsx new file mode 100644 index 0000000000..f6a4040497 --- /dev/null +++ b/src/components/Soulseek/AlbumLibraryHealthButton.tsx @@ -0,0 +1,204 @@ +import Badge from '@app/components/Common/Badge'; +import Button from '@app/components/Common/Button'; +import LoadingSpinner from '@app/components/Common/LoadingSpinner'; +import Modal from '@app/components/Common/Modal'; +import Tooltip from '@app/components/Common/Tooltip'; +import useToasts from '@app/hooks/useToasts'; +import { Permission, useUser } from '@app/hooks/useUser'; +import defineMessages from '@app/utils/defineMessages'; +import { WrenchScrewdriverIcon } from '@heroicons/react/24/outline'; +import axios from 'axios'; +import { useState } from 'react'; +import { useIntl } from 'react-intl'; +import useSWR from 'swr'; + +interface AlbumIssue { + issueId: string; + type: string; + severity: string; + status: string; + title?: string; + reason?: string; + canAutoFix: boolean; + remediationJobId?: string; +} + +const messages = defineMessages( + 'components.Soulseek.AlbumLibraryHealthButton', + { + button: 'Library Health', + tooltip: 'Check this album for transcodes and missing tracks in slskdN', + title: 'Library Health', + loading: 'Checking slskdN…', + loadError: 'slskdN library health could not be loaded.', + none: 'slskdN has not found any open issues for this album.', + track: 'Track', + severity: 'Severity', + status: 'Status', + fixable: 'Fixable', + fixAll: 'Fix {count, plural, one {# Issue} other {# Issues}} with Soulseek', + fixing: 'Starting…', + fixStarted: + 'slskdN started fixing {count, plural, one {# issue} other {# issues}}.', + fixFailed: 'slskdN could not start the fix.', + close: 'Close', + SuspectedTranscode: 'Suspected Transcode', + NonCanonicalVariant: 'Non-Canonical Variant', + TrackNotInTaggedRelease: 'Track Not in Release', + MissingTrackInRelease: 'Missing Track', + CorruptedFile: 'Corrupted File', + MissingMetadata: 'Missing Metadata', + MultipleVariants: 'Multiple Variants', + WrongDuration: 'Wrong Duration', + } +); + +const issueLabel = (type: string) => + type in messages ? messages[type as keyof typeof messages] : undefined; + +interface AlbumLibraryHealthButtonProps { + releaseGroupId: string; +} + +/** + * Manager-only view of slskdN library-health issues for an album, with a + * one-step fix for issues slskdN can remediate automatically. + */ +const AlbumLibraryHealthButton = ({ + releaseGroupId, +}: AlbumLibraryHealthButtonProps) => { + const intl = useIntl(); + const { addToast } = useToasts(); + const { hasPermission } = useUser(); + const canManage = hasPermission(Permission.MANAGE_REQUESTS); + const { data: status } = useSWR<{ configured: boolean }>( + canManage ? '/api/v1/soulseek/status' : null, + { revalidateOnFocus: false } + ); + const [open, setOpen] = useState(false); + const [fixing, setFixing] = useState(false); + const { data, error, mutate } = useSWR<{ issues: AlbumIssue[] }>( + open + ? `/api/v1/soulseek/albums/${encodeURIComponent(releaseGroupId)}/issues` + : null + ); + + if (!canManage || !status?.configured) { + return null; + } + + const fixable = (data?.issues ?? []).filter( + (issue) => issue.canAutoFix && !issue.remediationJobId + ); + + const fix = async () => { + setFixing(true); + try { + const response = await axios.post<{ issueCount: number }>( + `/api/v1/soulseek/albums/${encodeURIComponent(releaseGroupId)}/remediate`, + { issueIds: fixable.map((issue) => issue.issueId) } + ); + addToast( + intl.formatMessage(messages.fixStarted, { + count: response.data.issueCount, + }), + { appearance: 'success', autoDismiss: true } + ); + await mutate(); + } catch (failure) { + addToast( + axios.isAxiosError(failure) && + typeof failure.response?.data?.message === 'string' + ? failure.response.data.message + : intl.formatMessage(messages.fixFailed), + { appearance: 'error', autoDismiss: true } + ); + } finally { + setFixing(false); + } + }; + + return ( + <> + + + + {open && ( + setOpen(false)} + cancelText={intl.formatMessage(messages.close)} + onOk={fixable.length > 0 ? () => void fix() : undefined} + okText={ + fixable.length > 0 + ? intl.formatMessage(fixing ? messages.fixing : messages.fixAll, { + count: fixable.length, + }) + : undefined + } + okDisabled={fixing} + > + {!data && !error && } + {error && ( +

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

+ )} + {data && data.issues.length === 0 && ( +

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

+ )} + {data && data.issues.length > 0 && ( +
    + {data.issues.map((issue) => { + const label = issueLabel(issue.type); + return ( +
  • +
    +
    +

    + {label ? intl.formatMessage(label) : issue.type} +

    + {issue.canAutoFix && ( + + {intl.formatMessage(messages.fixable)} + + )} +
    +
    + {issue.title && ( + <> +
    {intl.formatMessage(messages.track)}
    +
    {issue.title}
    + + )} +
    {intl.formatMessage(messages.severity)}
    +
    {issue.severity}
    +
    {intl.formatMessage(messages.status)}
    +
    {issue.status}
    +
    + {issue.reason && ( +

    {issue.reason}

    + )} +
    +
  • + ); + })} +
+ )} +
+ )} + + ); +}; + +export default AlbumLibraryHealthButton; diff --git a/src/components/Soulseek/SongIdentify.tsx b/src/components/Soulseek/SongIdentify.tsx new file mode 100644 index 0000000000..9b268787f5 --- /dev/null +++ b/src/components/Soulseek/SongIdentify.tsx @@ -0,0 +1,308 @@ +import Badge from '@app/components/Common/Badge'; +import Button from '@app/components/Common/Button'; +import LoadingSpinner from '@app/components/Common/LoadingSpinner'; +import PageTitle from '@app/components/Common/PageTitle'; +import useToasts from '@app/hooks/useToasts'; +import defineMessages from '@app/utils/defineMessages'; +import axios from 'axios'; +import { useRouter } from 'next/router'; +import type { FormEvent } from 'react'; +import { useEffect, useState } from 'react'; +import { useIntl } from 'react-intl'; +import useSWR from 'swr'; + +interface SongIdView { + id: string; + status: string; + summary?: string; + stage?: string; + percentComplete?: number; + queuePosition?: number; + albums: { + releaseId: string; + releaseGroupId?: string; + title: string; + artist: string; + isExact: boolean; + }[]; + tracks: { + recordingId: string; + title: string; + artist: string; + isExact: boolean; + }[]; +} + +const messages = defineMessages('components.Soulseek.SongIdentify', { + title: 'Identify a Song', + description: + 'Paste a link to a clip or video, or describe the song. SongID looks for the matching recording and album so you can request it.', + notConfigured: + 'Song identification is not set up. An administrator can connect slskdN in Settings → Services.', + source: 'Link or Description', + identify: 'Identify', + identifying: 'Identifying…', + queued: 'Waiting in queue (position {position})', + progress: '{stage} · {percent}%', + albums: 'Albums', + tracks: 'Tracks', + exact: 'Exact Match', + openAlbum: 'Open Album', + requestTrack: 'Request Track', + requested: 'Track requested from Soulseek.', + noMatches: 'No matching recordings were found.', + failed: 'Song identification failed.', + requestFailed: 'The track could not be requested.', +}); + +const FINISHED = new Set(['completed', 'failed', 'cancelled']); + +const SongIdentify = () => { + const intl = useIntl(); + const router = useRouter(); + const { addToast } = useToasts(); + const { data: status } = useSWR<{ configured: boolean; canRequest: boolean }>( + '/api/v1/soulseek/status' + ); + const [source, setSource] = useState(''); + const [runId, setRunId] = useState(); + const [starting, setStarting] = useState(false); + const [requested, setRequested] = useState>(new Set()); + const { data: run, error } = useSWR( + runId ? `/api/v1/soulseek/songid/${encodeURIComponent(runId)}` : null, + { + refreshInterval: (latest) => + latest && FINISHED.has(latest.status) ? 0 : 3_000, + } + ); + + useEffect(() => { + if (error) setRunId(undefined); + }, [error]); + + const start = async (event: FormEvent) => { + event.preventDefault(); + setStarting(true); + try { + const response = await axios.post('/api/v1/soulseek/songid', { + source: source.trim(), + }); + setRequested(new Set()); + setRunId(response.data.id); + } catch (failure) { + addToast( + axios.isAxiosError(failure) && + typeof failure.response?.data?.message === 'string' + ? failure.response.data.message + : intl.formatMessage(messages.failed), + { appearance: 'error', autoDismiss: true } + ); + } finally { + setStarting(false); + } + }; + + const requestTrack = async (track: SongIdView['tracks'][number]) => { + try { + await axios.post('/api/v1/soulseek/track-requests', { + tracks: [ + { + artist: track.artist, + title: track.title, + recordingMbid: track.recordingId, + source: 'songid', + }, + ], + }); + setRequested((current) => new Set(current).add(track.recordingId)); + addToast(intl.formatMessage(messages.requested), { + appearance: 'success', + autoDismiss: true, + }); + } catch (failure) { + addToast( + axios.isAxiosError(failure) && + typeof failure.response?.data?.message === 'string' + ? failure.response.data.message + : intl.formatMessage(messages.requestFailed), + { appearance: 'error', autoDismiss: true } + ); + } + }; + + const running = !!runId && (!run || !FINISHED.has(run.status)); + + return ( +
+ +
+

{intl.formatMessage(messages.title)}

+ {running && ( + + + + )} +
+ {status && !status.configured ? ( +
+

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

+
+ ) : ( + <> +
+

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

+
void start(event)}> +
+ +
+
+ setSource(event.currentTarget.value)} + /> +
+
+
+
+ +
+
+ {running && run && ( +

+ {run.queuePosition + ? intl.formatMessage(messages.queued, { + position: run.queuePosition, + }) + : intl.formatMessage(messages.progress, { + stage: run.stage ?? run.status, + percent: Math.round(run.percentComplete ?? 0), + })} +

+ )} +
+ {run && FINISHED.has(run.status) && ( + <> + {run.status !== 'completed' && ( +
+

+ {run.summary ?? intl.formatMessage(messages.failed)} +

+
+ )} + {run.status === 'completed' && + run.albums.length === 0 && + run.tracks.length === 0 && ( +
+

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

+
+ )} + {run.albums.length > 0 && ( + <> +

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

+
    + {run.albums.map((album) => ( +
  • +
    +
    +

    {album.title}

    + {album.isExact && ( + + {intl.formatMessage(messages.exact)} + + )} +
    +

    {album.artist}

    + {album.releaseGroupId && ( +
    + +
    + )} +
    +
  • + ))} +
+ + )} + {run.tracks.length > 0 && ( + <> +

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

+
    + {run.tracks.map((track) => ( +
  • +
    +
    +

    {track.title}

    + {track.isExact && ( + + {intl.formatMessage(messages.exact)} + + )} +
    +

    {track.artist}

    +
    + +
    +
    +
  • + ))} +
+ + )} + + )} + + )} +
+ ); +}; + +export default SongIdentify; diff --git a/src/components/Soulseek/SoulseekUnmatchedTracks.test.tsx b/src/components/Soulseek/SoulseekUnmatchedTracks.test.tsx new file mode 100644 index 0000000000..04425930ae --- /dev/null +++ b/src/components/Soulseek/SoulseekUnmatchedTracks.test.tsx @@ -0,0 +1,98 @@ +import { JSDOM } from 'jsdom'; +import React, { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import { IntlProvider } from 'react-intl'; +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import SoulseekUnmatchedTracks from './SoulseekUnmatchedTracks'; + +const state = vi.hoisted(() => ({ + status: { configured: true, canRequest: true }, + post: vi.fn(), + addToast: vi.fn(), +})); + +vi.mock('@app/hooks/useToasts', () => ({ + default: () => ({ addToast: state.addToast }), +})); + +vi.mock('axios', () => ({ + default: { post: state.post, isAxiosError: () => false }, +})); + +vi.mock('swr', () => ({ + default: () => ({ data: state.status }), +})); + +vi.mock('@app/components/Common/Button', () => ({ + default: ({ + children, + onClick, + disabled, + }: React.ButtonHTMLAttributes) => ( + + ), +})); + +let dom: JSDOM; +let root: ReturnType; + +const render = (tracks: { title: string; artist?: string }[]) => + act(async () => + root.render( + + + + ) + ); + +beforeEach(() => { + dom = new JSDOM('
'); + vi.stubGlobal('window', dom.window); + vi.stubGlobal('document', dom.window.document); + vi.stubGlobal('React', React); + vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); + root = createRoot(document.getElementById('root')!); + state.status = { configured: true, canRequest: true }; + state.post.mockReset(); + state.post.mockResolvedValue({ data: { results: [{}, {}] } }); + state.addToast.mockReset(); +}); + +afterEach(async () => { + await act(async () => root.unmount()); + vi.unstubAllGlobals(); +}); + +it('renders nothing without slskdN or request permission', async () => { + state.status = { configured: false, canRequest: true }; + await render([{ title: 'Song', artist: 'Band' }]); + expect(document.getElementById('root')?.innerHTML).toBe(''); + + state.status = { configured: true, canRequest: false }; + await render([{ title: 'Song', artist: 'Band' }]); + expect(document.getElementById('root')?.innerHTML).toBe(''); +}); + +it('requests only tracks with an artist, once', async () => { + await render([ + { title: 'Song A', artist: 'Band' }, + { title: 'Song B', artist: 'Band' }, + { title: 'No Artist' }, + ]); + const button = document.querySelector('button')!; + expect(button.textContent).toBe('Request 2 Tracks from Soulseek'); + await act(async () => button.click()); + expect(state.post).toHaveBeenCalledWith('/api/v1/soulseek/track-requests', { + tracks: [ + { artist: 'Band', title: 'Song A', source: 'playlist' }, + { artist: 'Band', title: 'Song B', source: 'playlist' }, + ], + }); + expect(document.querySelector('button')!.disabled).toBe(true); + expect(state.addToast).toHaveBeenCalledWith( + '2 tracks requested from Soulseek.', + expect.objectContaining({ appearance: 'success' }) + ); +}); diff --git a/src/components/Soulseek/SoulseekUnmatchedTracks.tsx b/src/components/Soulseek/SoulseekUnmatchedTracks.tsx new file mode 100644 index 0000000000..a22b6ef07d --- /dev/null +++ b/src/components/Soulseek/SoulseekUnmatchedTracks.tsx @@ -0,0 +1,108 @@ +import Button from '@app/components/Common/Button'; +import useToasts from '@app/hooks/useToasts'; +import defineMessages from '@app/utils/defineMessages'; +import axios from 'axios'; +import { useState } from 'react'; +import { useIntl } from 'react-intl'; +import useSWR from 'swr'; + +const messages = defineMessages('components.Soulseek.SoulseekUnmatchedTracks', { + title: 'Tracks Without an Album Match', + description: + '{count, plural, one {# track has} other {# tracks have}} no confident album match, so Lidarr cannot request {count, plural, one {it} other {them}}. Request {count, plural, one {it} other {them}} as individual tracks from Soulseek instead.', + request: + 'Request {count, plural, one {Track} other {# Tracks}} from Soulseek', + requesting: 'Requesting…', + requested: + '{count, plural, one {Track} other {# tracks}} requested from Soulseek.', + failed: 'The tracks could not be requested from Soulseek.', +}); + +export interface UnmatchedTrack { + title: string; + artist?: string; +} + +interface SoulseekUnmatchedTracksProps { + tracks: UnmatchedTrack[]; +} + +/** + * Offers playlist tracks Lidarr cannot request to the slskdN wishlist. Renders + * nothing unless slskdN is configured and the user can request music. + */ +const SoulseekUnmatchedTracks = ({ tracks }: SoulseekUnmatchedTracksProps) => { + const intl = useIntl(); + const { addToast } = useToasts(); + const { data: status } = useSWR<{ configured: boolean; canRequest: boolean }>( + '/api/v1/soulseek/status', + { revalidateOnFocus: false } + ); + const [busy, setBusy] = useState(false); + const [done, setDone] = useState(false); + + const requestable = tracks.filter( + (track) => track.artist?.trim() && track.title.trim() + ); + if (!status?.configured || !status.canRequest || requestable.length === 0) { + return null; + } + + const submit = async () => { + setBusy(true); + try { + const response = await axios.post<{ results: unknown[] }>( + '/api/v1/soulseek/track-requests', + { + tracks: requestable.slice(0, 50).map((track) => ({ + artist: track.artist, + title: track.title, + source: 'playlist', + })), + } + ); + setDone(true); + addToast( + intl.formatMessage(messages.requested, { + count: response.data.results.length, + }), + { appearance: 'success', autoDismiss: true } + ); + } catch (error) { + addToast( + axios.isAxiosError(error) && + typeof error.response?.data?.message === 'string' + ? error.response.data.message + : intl.formatMessage(messages.failed), + { appearance: 'error', autoDismiss: true } + ); + } finally { + setBusy(false); + } + }; + + return ( +
+

{intl.formatMessage(messages.title)}

+

+ {intl.formatMessage(messages.description, { + count: requestable.length, + })} +

+
+ +
+
+ ); +}; + +export default SoulseekUnmatchedTracks; diff --git a/src/components/Soulseek/TrackRequestList.tsx b/src/components/Soulseek/TrackRequestList.tsx new file mode 100644 index 0000000000..e1637783bb --- /dev/null +++ b/src/components/Soulseek/TrackRequestList.tsx @@ -0,0 +1,298 @@ +import Badge from '@app/components/Common/Badge'; +import Button from '@app/components/Common/Button'; +import LoadingSpinner from '@app/components/Common/LoadingSpinner'; +import PageTitle from '@app/components/Common/PageTitle'; +import useToasts from '@app/hooks/useToasts'; +import { Permission, useUser } from '@app/hooks/useUser'; +import defineMessages from '@app/utils/defineMessages'; +import axios from 'axios'; +import { useRouter } from 'next/router'; +import { useState } from 'react'; +import { useIntl } from 'react-intl'; +import useSWR from 'swr'; + +type TrackStatus = + 'pending' | 'searching' | 'completed' | 'failed' | 'declined' | 'cancelled'; + +interface TrackRequestView { + id: number; + status: TrackStatus; + artist: string; + title: string; + source: string; + searchCount: number; + lastMatchCount: number; + lastError?: string; + createdAt: string; + requestedBy?: { id: number; displayName: string }; +} + +const messages = defineMessages('components.Soulseek.TrackRequestList', { + title: 'Track Requests', + notConfigured: + 'Soulseek track requests are not set up. An administrator can connect slskdN in Settings → Services.', + empty: 'No Track Requests Yet', + emptyHelp: + 'Import a playlist from Requests, or identify a song, to request tracks that have no album match.', + identify: 'Identify a Song', + loadError: 'Track requests could not be loaded.', + retry: 'Retry', + mine: 'My Requests', + everyone: 'All Requests', + activeOnly: 'Active Only', + showAll: 'Show All', + artist: 'Artist', + searches: 'Searches', + matches: 'Last Matches', + requestedBy: 'Requested By', + approve: 'Approve', + decline: 'Decline', + cancel: 'Cancel Request', + working: 'Working…', + actionFailed: 'The request could not be updated.', + statusPending: 'Pending Approval', + statusSearching: 'Searching', + statusCompleted: 'Downloaded', + statusFailed: 'Failed', + statusDeclined: 'Declined', + statusCancelled: 'Cancelled', +}); + +const statusMessage: Record = { + pending: 'statusPending', + searching: 'statusSearching', + completed: 'statusCompleted', + failed: 'statusFailed', + declined: 'statusDeclined', + cancelled: 'statusCancelled', +}; + +const statusBadge: Record< + TrackStatus, + 'default' | 'primary' | 'success' | 'warning' | 'danger' +> = { + pending: 'warning', + searching: 'primary', + completed: 'success', + failed: 'danger', + declined: 'danger', + cancelled: 'default', +}; + +const ACTIVE: TrackStatus[] = ['pending', 'searching']; + +const TrackRequestList = () => { + const intl = useIntl(); + const router = useRouter(); + const { addToast } = useToasts(); + const { user, hasPermission } = useUser(); + const { data: status } = useSWR<{ configured: boolean }>( + '/api/v1/soulseek/status' + ); + const canManage = hasPermission(Permission.MANAGE_REQUESTS); + const canViewAll = hasPermission( + [Permission.MANAGE_REQUESTS, Permission.REQUEST_VIEW], + { type: 'or' } + ); + const [scopeAll, setScopeAll] = useState(false); + const [activeOnly, setActiveOnly] = useState(true); + const [busyId, setBusyId] = useState(); + + const key = status?.configured + ? `/api/v1/soulseek/track-requests?scope=${scopeAll ? 'all' : 'mine'}&filter=${ + activeOnly ? 'active' : 'all' + }&take=100` + : null; + const { data, error, mutate, isValidating } = useSWR<{ + results: TrackRequestView[]; + }>(key, { refreshInterval: 60_000 }); + + const act = async ( + request: TrackRequestView, + action: 'approve' | 'decline' | 'cancel' + ) => { + setBusyId(request.id); + try { + if (action === 'cancel') { + await axios.delete(`/api/v1/soulseek/track-requests/${request.id}`); + } else { + await axios.post( + `/api/v1/soulseek/track-requests/${request.id}/${action}` + ); + } + await mutate(); + } catch (failure) { + addToast( + axios.isAxiosError(failure) && + typeof failure.response?.data?.message === 'string' + ? failure.response.data.message + : intl.formatMessage(messages.actionFailed), + { appearance: 'error', autoDismiss: true } + ); + } finally { + setBusyId(undefined); + } + }; + + const renderRequest = (request: TrackRequestView) => { + const isOwner = request.requestedBy?.id === user?.id; + const active = ACTIVE.includes(request.status); + return ( +
  • +
    +
    +

    {request.title}

    + + {intl.formatMessage(messages[statusMessage[request.status]])} + +
    +
    +
    {intl.formatMessage(messages.artist)}
    +
    {request.artist}
    + {request.status === 'searching' && ( + <> +
    {intl.formatMessage(messages.searches)}
    +
    {request.searchCount}
    +
    {intl.formatMessage(messages.matches)}
    +
    {request.lastMatchCount}
    + + )} + {scopeAll && request.requestedBy && ( + <> +
    {intl.formatMessage(messages.requestedBy)}
    +
    {request.requestedBy.displayName}
    + + )} +
    + {request.lastError && ( +

    {request.lastError}

    + )} + {active && (canManage || isOwner) && ( +
    + {canManage && request.status === 'pending' && ( + <> + + + + )} + {(request.status !== 'pending' || isOwner) && ( + + )} +
    + )} +
    +
  • + ); + }; + + const results = data?.results ?? []; + + return ( +
    + +
    +

    {intl.formatMessage(messages.title)}

    + {isValidating && data && ( + + + + )} +
    + {status && !status.configured ? ( +
    +

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

    +
    + ) : ( + <> +
    + {canViewAll && ( + + )} + + +
    + {error && !data ? ( +
    +

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

    +
    + +
    +
    + ) : !data ? ( + + ) : results.length === 0 ? ( +
    +

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

    +

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

    +
    + ) : ( +
      + {results.map(renderRequest)} +
    + )} + + )} +
    + ); +}; + +export default TrackRequestList; diff --git a/src/i18n/locale/en.json b/src/i18n/locale/en.json index ae4d6f52fb..d1c926cd97 100644 --- a/src/i18n/locale/en.json +++ b/src/i18n/locale/en.json @@ -3401,6 +3401,33 @@ "components.Settings.SettingsNetwork.validationDnsCacheMaxTtl": "You must provide a valid maximum TTL", "components.Settings.SettingsNetwork.validationDnsCacheMinTtl": "You must provide a valid minimum TTL", "components.Settings.SettingsNetwork.validationProxyPort": "You must provide a valid port", + "components.Settings.SettingsSlskdn.apiKey": "API Key", + "components.Settings.SettingsSlskdn.baseUrl": "URL Base", + "components.Settings.SettingsSlskdn.cancel": "Discard Changes", + "components.Settings.SettingsSlskdn.clearSecret": "Remove the saved API key", + "components.Settings.SettingsSlskdn.description": "Connect slskdN to request single tracks that Lidarr cannot, fix albums slskdN flags as transcoded or incomplete, and identify songs with SongID. Lidarr can keep using slskdN for album downloads as before.", + "components.Settings.SettingsSlskdn.enabled": "Enable Soulseek Requests", + "components.Settings.SettingsSlskdn.feature": "{feature}: {available, select, true {available} other {not available}}", + "components.Settings.SettingsSlskdn.hostname": "Hostname or IP Address", + "components.Settings.SettingsSlskdn.keyNote": "Use an slskdN API key with the read-write role. SongID needs the administrator role.", + "components.Settings.SettingsSlskdn.libraryHealth": "Album fixes (library health)", + "components.Settings.SettingsSlskdn.loadError": "slskdN settings could not be loaded.", + "components.Settings.SettingsSlskdn.port": "Port", + "components.Settings.SettingsSlskdn.save": "Save Changes", + "components.Settings.SettingsSlskdn.saveError": "slskdN settings could not be saved.", + "components.Settings.SettingsSlskdn.saveSuccess": "slskdN settings saved.", + "components.Settings.SettingsSlskdn.savedSecret": "Saved — leave empty to keep it", + "components.Settings.SettingsSlskdn.saving": "Saving…", + "components.Settings.SettingsSlskdn.searchFilter": "Search Filter", + "components.Settings.SettingsSlskdn.searchFilterDescription": "Optional slskdN wishlist filter for track requests, for example to prefer lossless files.", + "components.Settings.SettingsSlskdn.songId": "SongID", + "components.Settings.SettingsSlskdn.test": "Test Connection", + "components.Settings.SettingsSlskdn.testOk": "Connected to slskdN {version}.", + "components.Settings.SettingsSlskdn.testing": "Testing…", + "components.Settings.SettingsSlskdn.title": "Soulseek (slskdN)", + "components.Settings.SettingsSlskdn.unsavedChanges": "You have unsaved changes.", + "components.Settings.SettingsSlskdn.useSsl": "Use HTTPS", + "components.Settings.SettingsSlskdn.wishlist": "Track requests (wishlist)", "components.Settings.SettingsTunerr.baseUrl": "Deck URL Base", "components.Settings.SettingsTunerr.cancel": "Discard Changes", "components.Settings.SettingsTunerr.clearSecret": "Remove the saved password", @@ -3919,6 +3946,78 @@ "components.SoftwareCatalog.windows": "Windows", "components.SoftwareCatalog.x64": "x64", "components.SoftwareCatalog.x86": "x86", + "components.Soulseek.AlbumLibraryHealthButton.CorruptedFile": "Corrupted File", + "components.Soulseek.AlbumLibraryHealthButton.MissingMetadata": "Missing Metadata", + "components.Soulseek.AlbumLibraryHealthButton.MissingTrackInRelease": "Missing Track", + "components.Soulseek.AlbumLibraryHealthButton.MultipleVariants": "Multiple Variants", + "components.Soulseek.AlbumLibraryHealthButton.NonCanonicalVariant": "Non-Canonical Variant", + "components.Soulseek.AlbumLibraryHealthButton.SuspectedTranscode": "Suspected Transcode", + "components.Soulseek.AlbumLibraryHealthButton.TrackNotInTaggedRelease": "Track Not in Release", + "components.Soulseek.AlbumLibraryHealthButton.WrongDuration": "Wrong Duration", + "components.Soulseek.AlbumLibraryHealthButton.button": "Library Health", + "components.Soulseek.AlbumLibraryHealthButton.close": "Close", + "components.Soulseek.AlbumLibraryHealthButton.fixAll": "Fix {count, plural, one {# Issue} other {# Issues}} with Soulseek", + "components.Soulseek.AlbumLibraryHealthButton.fixFailed": "slskdN could not start the fix.", + "components.Soulseek.AlbumLibraryHealthButton.fixStarted": "slskdN started fixing {count, plural, one {# issue} other {# issues}}.", + "components.Soulseek.AlbumLibraryHealthButton.fixable": "Fixable", + "components.Soulseek.AlbumLibraryHealthButton.fixing": "Starting…", + "components.Soulseek.AlbumLibraryHealthButton.loadError": "slskdN library health could not be loaded.", + "components.Soulseek.AlbumLibraryHealthButton.loading": "Checking slskdN…", + "components.Soulseek.AlbumLibraryHealthButton.none": "slskdN has not found any open issues for this album.", + "components.Soulseek.AlbumLibraryHealthButton.severity": "Severity", + "components.Soulseek.AlbumLibraryHealthButton.status": "Status", + "components.Soulseek.AlbumLibraryHealthButton.title": "Library Health", + "components.Soulseek.AlbumLibraryHealthButton.tooltip": "Check this album for transcodes and missing tracks in slskdN", + "components.Soulseek.AlbumLibraryHealthButton.track": "Track", + "components.Soulseek.SongIdentify.albums": "Albums", + "components.Soulseek.SongIdentify.description": "Paste a link to a clip or video, or describe the song. SongID looks for the matching recording and album so you can request it.", + "components.Soulseek.SongIdentify.exact": "Exact Match", + "components.Soulseek.SongIdentify.failed": "Song identification failed.", + "components.Soulseek.SongIdentify.identify": "Identify", + "components.Soulseek.SongIdentify.identifying": "Identifying…", + "components.Soulseek.SongIdentify.noMatches": "No matching recordings were found.", + "components.Soulseek.SongIdentify.notConfigured": "Song identification is not set up. An administrator can connect slskdN in Settings → Services.", + "components.Soulseek.SongIdentify.openAlbum": "Open Album", + "components.Soulseek.SongIdentify.progress": "{stage} · {percent}%", + "components.Soulseek.SongIdentify.queued": "Waiting in queue (position {position})", + "components.Soulseek.SongIdentify.requestFailed": "The track could not be requested.", + "components.Soulseek.SongIdentify.requestTrack": "Request Track", + "components.Soulseek.SongIdentify.requested": "Track requested from Soulseek.", + "components.Soulseek.SongIdentify.source": "Link or Description", + "components.Soulseek.SongIdentify.title": "Identify a Song", + "components.Soulseek.SongIdentify.tracks": "Tracks", + "components.Soulseek.SoulseekUnmatchedTracks.description": "{count, plural, one {# track has} other {# tracks have}} no confident album match, so Lidarr cannot request {count, plural, one {it} other {them}}. Request {count, plural, one {it} other {them}} as individual tracks from Soulseek instead.", + "components.Soulseek.SoulseekUnmatchedTracks.failed": "The tracks could not be requested from Soulseek.", + "components.Soulseek.SoulseekUnmatchedTracks.request": "Request {count, plural, one {Track} other {# Tracks}} from Soulseek", + "components.Soulseek.SoulseekUnmatchedTracks.requested": "{count, plural, one {Track} other {# tracks}} requested from Soulseek.", + "components.Soulseek.SoulseekUnmatchedTracks.requesting": "Requesting…", + "components.Soulseek.SoulseekUnmatchedTracks.title": "Tracks Without an Album Match", + "components.Soulseek.TrackRequestList.actionFailed": "The request could not be updated.", + "components.Soulseek.TrackRequestList.activeOnly": "Active Only", + "components.Soulseek.TrackRequestList.approve": "Approve", + "components.Soulseek.TrackRequestList.artist": "Artist", + "components.Soulseek.TrackRequestList.cancel": "Cancel Request", + "components.Soulseek.TrackRequestList.decline": "Decline", + "components.Soulseek.TrackRequestList.empty": "No Track Requests Yet", + "components.Soulseek.TrackRequestList.emptyHelp": "Import a playlist from Requests, or identify a song, to request tracks that have no album match.", + "components.Soulseek.TrackRequestList.everyone": "All Requests", + "components.Soulseek.TrackRequestList.identify": "Identify a Song", + "components.Soulseek.TrackRequestList.loadError": "Track requests could not be loaded.", + "components.Soulseek.TrackRequestList.matches": "Last Matches", + "components.Soulseek.TrackRequestList.mine": "My Requests", + "components.Soulseek.TrackRequestList.notConfigured": "Soulseek track requests are not set up. An administrator can connect slskdN in Settings → Services.", + "components.Soulseek.TrackRequestList.requestedBy": "Requested By", + "components.Soulseek.TrackRequestList.retry": "Retry", + "components.Soulseek.TrackRequestList.searches": "Searches", + "components.Soulseek.TrackRequestList.showAll": "Show All", + "components.Soulseek.TrackRequestList.statusCancelled": "Cancelled", + "components.Soulseek.TrackRequestList.statusCompleted": "Downloaded", + "components.Soulseek.TrackRequestList.statusDeclined": "Declined", + "components.Soulseek.TrackRequestList.statusFailed": "Failed", + "components.Soulseek.TrackRequestList.statusPending": "Pending Approval", + "components.Soulseek.TrackRequestList.statusSearching": "Searching", + "components.Soulseek.TrackRequestList.title": "Track Requests", + "components.Soulseek.TrackRequestList.working": "Working…", "components.StatusBadge.manageBookFormat": "Manage {format}", "components.StatusBadge.managemedia": "Manage {mediaType}", "components.StatusBadge.openinarr": "Open in {arr}", diff --git a/src/pages/identify.tsx b/src/pages/identify.tsx new file mode 100644 index 0000000000..8c9551f144 --- /dev/null +++ b/src/pages/identify.tsx @@ -0,0 +1,6 @@ +import SongIdentify from '@app/components/Soulseek/SongIdentify'; +import type { NextPage } from 'next'; + +const IdentifyPage: NextPage = () => ; + +export default IdentifyPage; diff --git a/src/pages/track-requests.tsx b/src/pages/track-requests.tsx new file mode 100644 index 0000000000..c3ea74edb4 --- /dev/null +++ b/src/pages/track-requests.tsx @@ -0,0 +1,6 @@ +import TrackRequestList from '@app/components/Soulseek/TrackRequestList'; +import type { NextPage } from 'next'; + +const TrackRequestsPage: NextPage = () => ; + +export default TrackRequestsPage; From 82a0a4da116d7e19774426a9c30d6e358ced67a2 Mon Sep 17 00:00:00 2001 From: Keith Snape Date: Tue, 6 Oct 2026 15:41:20 -0600 Subject: [PATCH 21/58] feat: show the download client handling each download to admins Carry the *arr queue's protocol and download client through download status so administrators can see whether a request is downloading via a torrent client, Usenet, or a direct source such as ChaptarrNG. The non-admin projection already drops both fields. Co-Authored-By: Claude Opus 5.5 --- .../2026-10-06-download-client-badge.md | 9 +++++++++ server/lib/downloadtracker.ts | 18 ++++++++++++++++- server/lib/mediaResponse.test.ts | 20 +++++++++++++++++++ src/components/DownloadBlock/index.tsx | 6 ++++++ 4 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 release-notes/2026-10-06-download-client-badge.md diff --git a/release-notes/2026-10-06-download-client-badge.md b/release-notes/2026-10-06-download-client-badge.md new file mode 100644 index 0000000000..2bf60e5b1c --- /dev/null +++ b/release-notes/2026-10-06-download-client-badge.md @@ -0,0 +1,9 @@ +--- +category: changed +audience: operators +area: downloads +action: none +breaking: false +--- + +Administrators now see which download client is handling each download, such as a ChaptarrNG direct download or a torrent client, beside its queue status. diff --git a/server/lib/downloadtracker.ts b/server/lib/downloadtracker.ts index c1d52d5492..764fad6221 100644 --- a/server/lib/downloadtracker.ts +++ b/server/lib/downloadtracker.ts @@ -59,6 +59,10 @@ export interface DownloadingItem { percent?: number; trackedDownloadStatus?: string; trackedDownloadState?: string; + /** `torrent` or `usenet`, as reported by the *arr queue. */ + protocol?: string; + /** Download client name configured in the *arr service. */ + downloadClient?: string; episode?: EpisodeNumberResult; } @@ -72,9 +76,21 @@ export interface ServarrHistoryEvidence { const getQueueState = ( item: QueueItem -): Pick => ({ +): Pick< + DownloadingItem, + | 'trackedDownloadStatus' + | 'trackedDownloadState' + | 'protocol' + | 'downloadClient' +> => ({ trackedDownloadStatus: item.trackedDownloadStatus, trackedDownloadState: item.trackedDownloadState, + protocol: + typeof item.protocol === 'string' ? item.protocol.slice(0, 32) : undefined, + downloadClient: + typeof item.downloadClient === 'string' + ? item.downloadClient.slice(0, 120) + : undefined, }); export const DOWNLOAD_TRACKER_SERVER_CONCURRENCY = 5; diff --git a/server/lib/mediaResponse.test.ts b/server/lib/mediaResponse.test.ts index de6bf76c7a..9d1c44df1b 100644 --- a/server/lib/mediaResponse.test.ts +++ b/server/lib/mediaResponse.test.ts @@ -154,6 +154,8 @@ const createOperationalMedia = () => estimatedCompletionTime: new Date('2026-03-01T00:00:00Z'), title: 'Private.Release.Name-GROUP', downloadId: 'private-downloader-id', + protocol: 'torrent', + downloadClient: 'Private qBittorrent', episode: { seasonNumber: 2, episodeNumber: 3, @@ -188,6 +190,24 @@ describe('restrictMediaOperationalFieldsForUser', () => { }); }); + it('keeps the download client name for administrators only', () => { + const user = restrictMediaOperationalFieldsForUser( + createOperationalMedia(), + new User({ id: 10, permissions: Permission.REQUEST }) + ); + assert.strictEqual(user?.downloadStatus?.[0].downloadClient, undefined); + assert.strictEqual(user?.downloadStatus?.[0].protocol, undefined); + + const admin = restrictMediaOperationalFieldsForUser( + createOperationalMedia(), + new User({ id: 1, permissions: Permission.ADMIN }) + ); + assert.strictEqual( + admin?.downloadStatus?.[0].downloadClient, + 'Private qBittorrent' + ); + }); + it('keeps service routes for request managers but still redacts releases', () => { const media = restrictMediaOperationalFieldsForUser( createOperationalMedia(), diff --git a/src/components/DownloadBlock/index.tsx b/src/components/DownloadBlock/index.tsx index 8c45a95699..b1446d717e 100644 --- a/src/components/DownloadBlock/index.tsx +++ b/src/components/DownloadBlock/index.tsx @@ -114,6 +114,12 @@ const DownloadBlock = ({ )} {downloadItem.status} + {downloadItem.downloadClient && ( + <> + {' '} + {downloadItem.downloadClient} + + )} {live && ( <> {' '} From 7db31a08ba5ac9832963403d701177dae432a9f7 Mon Sep 17 00:00:00 2001 From: Keith Snape Date: Tue, 6 Oct 2026 15:47:19 -0600 Subject: [PATCH 22/58] feat: show ROMarrNG DAT verification on available ROM requests Pass ROMarrNG's per-file datVerified verdict through the software asset sanitizer and request views, and show DAT Verified (or how many files matched) beside Download copy. Co-Authored-By: Claude Opus 5.5 --- .../ng-ecosystem-integration-plan.md | 6 +++ .../2026-10-06-rom-dat-verified-badge.md | 9 ++++ server/api/software/types.ts | 5 ++ server/lib/softwareRequests.test.ts | 41 +++++++++++++++++ server/lib/softwareRequests.ts | 3 ++ server/routes/software.ts | 3 ++ .../RequestStatus/SoftwareRequests.tsx | 46 ++++++++++++++++++- src/i18n/locale/en.json | 2 + 8 files changed, 114 insertions(+), 1 deletion(-) create mode 100644 release-notes/2026-10-06-rom-dat-verified-badge.md diff --git a/docs/maintainers/ng-ecosystem-integration-plan.md b/docs/maintainers/ng-ecosystem-integration-plan.md index d153b00fb7..cdceea6512 100644 --- a/docs/maintainers/ng-ecosystem-integration-plan.md +++ b/docs/maintainers/ng-ecosystem-integration-plan.md @@ -66,6 +66,12 @@ human visual acceptance yet; testing is planned after the full build-out. | 3 UI | built | Bulk dialog Soulseek card for unmatched playlist tracks, `/track-requests`, `/identify`, album Library Health button, Settings section. Component test for the bulk-dialog card. Needs human visual review. | | 3 Peer previews | not started | Open question 3 (legal/permission decision) still applies. | | 3 slskdN download progress in live progress | pending | slskdN transfers are not torrents; needs a separate adapter. | +| 4 Goodreads lists in External Request List Sync | already present | SeerrNG already supports Goodreads lists (`ExternalRequestListProvider = 'imdb' \| 'goodreads'`). Hardcover want-to-read is not supported (needs a per-user Hardcover token). | +| 4 ChaptarrNG direct download shown | done | Generalized: admins see the *arr queue's download client name (and protocol is carried) for every download. Non-admin projection drops it (test). | +| 4 ROMarrNG DAT verification | done | ROMarrNG local branch `feat/seerrng-dat-verification` (commit `06a6a67`, not pushed): `datVerified` per asset + `assetDatVerification` capability; 2 new pytest tests; ROMarrNG suite 2206 passed, 1 pre-existing failure (`test_json_request_bodies_are_bounded_before_parsing`, also fails on clean HEAD here). SeerrNG shows a DAT Verified badge on available ROM requests. | +| 4 ROMarrNG collections / 1G1R full-set requests | pending | Needs new ROMarrNG contract endpoints for collections; not started. | +| 4 BookshelfNG series-pack search, M4B option | pending | Needs BookshelfNG contract exposure; not started. | +| 4 QuestarrNG RomM/Playnite state into My Games | pending | Needs QuestarrNG contract exposure; not started. | | 2 Sports "follow my team" | pending | | | 2 Recently aired shelf, channel requests, Plex→Jellyfin users | pending | | | 2 Recording notifications | pending | Requests do not notify yet. | diff --git a/release-notes/2026-10-06-rom-dat-verified-badge.md b/release-notes/2026-10-06-rom-dat-verified-badge.md new file mode 100644 index 0000000000..8d29fc22bd --- /dev/null +++ b/release-notes/2026-10-06-rom-dat-verified-badge.md @@ -0,0 +1,9 @@ +--- +category: added +audience: users +area: software +action: none +breaking: false +--- + +Available ROM requests now show a DAT Verified badge when ROMarrNG confirms the delivered files match your loaded DATs, and say how many matched when only some did. diff --git a/server/api/software/types.ts b/server/api/software/types.ts index 0dac240083..dec79b86b6 100644 --- a/server/api/software/types.ts +++ b/server/api/software/types.ts @@ -61,6 +61,11 @@ export interface SoftwareAsset { name: string; size: number; url: string; + /** + * ROMarrNG DAT verdict: true matches the loaded DAT, false is hashed but + * not in it, undefined when unknown or not reported. + */ + datVerified?: boolean; } export interface SoftwareAssetsResponse { diff --git a/server/lib/softwareRequests.test.ts b/server/lib/softwareRequests.test.ts index 3b82d3e040..9e8802fefb 100644 --- a/server/lib/softwareRequests.test.ts +++ b/server/lib/softwareRequests.test.ts @@ -87,3 +87,44 @@ describe('refreshTrackedSoftwareRequests', () => { } }); }); + +describe('listSoftwareRequestAssets DAT verification', () => { + afterEach(() => mock.restoreAll()); + + it('keeps only boolean DAT verdicts from ROMarrNG', async () => { + const { listSoftwareRequestAssets } = await import('./softwareRequests'); + const settings = getSettings().softwareAcquisition.romarr; + const originalSettings = { ...settings }; + Object.assign(settings, { hostname: '127.0.0.1', apiKey: 'test-key' }); + try { + mock.method(ROMarrNGAPI.prototype, 'getAssets', async () => ({ + assets: [ + { id: 'a', name: 'Good.sfc', size: 1, url: 'x', datVerified: true }, + { id: 'b', name: 'Hack.sfc', size: 1, datVerified: false }, + { id: 'c', name: 'Bundle.tar', size: 1, datVerified: null }, + { id: 'd', name: 'Odd.sfc', size: 1, datVerified: 'yes' }, + ], + bundleSupported: false, + })); + const assets = await listSoftwareRequestAssets( + Object.assign(new SoftwareRequest(), { + id: 1, + provider: 'romarr' as const, + status: 'available' as const, + externalRequestId: 'seerrng:software:1', + }) + ); + assert.deepEqual( + assets.map((asset) => [asset.name, asset.datVerified, asset.url]), + [ + ['Good.sfc', true, ''], + ['Hack.sfc', false, ''], + ['Bundle.tar', undefined, ''], + ['Odd.sfc', undefined, ''], + ] + ); + } finally { + Object.assign(settings, originalSettings); + } + }); +}); diff --git a/server/lib/softwareRequests.ts b/server/lib/softwareRequests.ts index eafedc94fd..2b5c56ca11 100644 --- a/server/lib/softwareRequests.ts +++ b/server/lib/softwareRequests.ts @@ -140,6 +140,9 @@ const sanitizeSoftwareAssets = (value: unknown): SoftwareAsset[] => { // The upstream URL is deliberately discarded. Users receive only a // same-origin SeerrNG request-scoped download route. url: '', + ...(typeof asset.datVerified === 'boolean' + ? { datVerified: asset.datVerified } + : {}), })); }; diff --git a/server/routes/software.ts b/server/routes/software.ts index cc8b09d0ad..606535b05f 100644 --- a/server/routes/software.ts +++ b/server/routes/software.ts @@ -1379,6 +1379,7 @@ softwareRoutes.get('/status', async (req, res) => { name: asset.name, size: asset.size, url: `/api/v1/request/software/status/${request.id}/downloads/${encodeURIComponent(asset.id)}`, + datVerified: asset.datVerified, })), bundle: bundleName ? { @@ -1419,6 +1420,7 @@ softwareRoutes.get('/status/:id', async (req, res) => { name: asset.name, size: asset.size, url: `/api/v1/request/software/status/${request.id}/downloads/${encodeURIComponent(asset.id)}`, + datVerified: asset.datVerified, })), bundle: view.bundleName ? { @@ -1678,6 +1680,7 @@ softwareRoutes.get('/status/:id/downloads', async (req, res) => { name: asset.name, size: asset.size, url: `/api/v1/request/software/status/${request.id}/downloads/${encodeURIComponent(asset.id)}`, + datVerified: asset.datVerified, })), bundle: view.bundleName ? { diff --git a/src/components/RequestStatus/SoftwareRequests.tsx b/src/components/RequestStatus/SoftwareRequests.tsx index bf09f26876..ef3d7fb4bf 100644 --- a/src/components/RequestStatus/SoftwareRequests.tsx +++ b/src/components/RequestStatus/SoftwareRequests.tsx @@ -1,3 +1,4 @@ +import Badge from '@app/components/Common/Badge'; import Button from '@app/components/Common/Button'; import CachedImage from '@app/components/Common/CachedImage'; import LoadingSpinner from '@app/components/Common/LoadingSpinner'; @@ -24,6 +25,8 @@ import { useIntl } from 'react-intl'; import useSWR from 'swr'; const messages = defineMessages('components.RequestStatus.SoftwareRequests', { + datVerified: 'DAT Verified', + datPartlyVerified: '{verified} of {total} DAT Verified', title: 'Software Requests', requestedBy: 'Requested by {user}', pending: 'Pending Approval', @@ -117,7 +120,13 @@ interface SoftwareRequestResult { request: SoftwareRequestRow; status: SoftwareStatus; message: string | null; - assets: { id: string; name: string; size: number; url: string }[]; + assets: { + id: string; + name: string; + size: number; + url: string; + datVerified?: boolean; + }[]; bundle?: { name: string; url: string } | null; } @@ -136,6 +145,38 @@ interface SoftwareRequestHistoryResponse { }[]; } +/** + * ROMarrNG DAT verification for delivered files. Shown only when ROMarrNG + * reported a verdict for at least one file. + */ +const DatVerificationBadge = ({ + assets, +}: { + assets: SoftwareRequestResult['assets']; +}) => { + const intl = useIntl(); + const reported = assets.filter( + (asset) => typeof asset.datVerified === 'boolean' + ); + if (reported.length === 0) return null; + const verified = reported.filter((asset) => asset.datVerified).length; + if (verified === assets.length) { + return ( + + {intl.formatMessage(messages.datVerified)} + + ); + } + return ( + + {intl.formatMessage(messages.datPartlyVerified, { + verified, + total: assets.length, + })} + + ); +}; + const DownloadCopies = ({ requestId, assets, @@ -603,6 +644,9 @@ const SoftwareRequests = ({ onClick={() => setClearSelection(request.id)} /> )} + {status === 'available' && ( + + )} {status === 'available' && ( Date: Tue, 6 Oct 2026 15:50:48 -0600 Subject: [PATCH 23/58] feat: record followed sports teams' games through Tunerr Let users follow teams from IPTV Tunerr's sports schedule. Live TV Sync maps each matched upcoming game to its nearest guide airing and creates a normal recording request, skipping games the user already requested. Co-Authored-By: Claude Opus 5.5 --- .../ng-ecosystem-integration-plan.md | 2 +- docs/using-seerr/live-tv-recordings.md | 13 ++ .../2026-10-06-follow-team-recordings.md | 9 + seerr-api.yml | 85 +++++++++ server/api/tunerr.ts | 42 +++++ server/entity/SportsFollow.ts | 46 +++++ server/job/schedule.ts | 2 + server/lib/liveTv/guideIndex.ts | 26 +++ server/lib/liveTv/sports.ts | 170 ++++++++++++++++++ .../1791060000000-CreateSportsFollows.ts | 26 +++ .../1791060000000-CreateSportsFollows.test.ts | 40 +++++ .../1791060000000-CreateSportsFollows.ts | 25 +++ server/routes/liveTv.test.ts | 75 ++++++++ server/routes/liveTv.ts | 81 +++++++++ src/components/LiveTv/FollowedTeams.tsx | 161 +++++++++++++++++ src/components/LiveTv/RecordingList.tsx | 2 + src/i18n/locale/en.json | 9 + 17 files changed, 813 insertions(+), 1 deletion(-) create mode 100644 release-notes/2026-10-06-follow-team-recordings.md create mode 100644 server/entity/SportsFollow.ts create mode 100644 server/lib/liveTv/sports.ts create mode 100644 server/migration/postgres/1791060000000-CreateSportsFollows.ts create mode 100644 server/migration/sqlite/1791060000000-CreateSportsFollows.test.ts create mode 100644 server/migration/sqlite/1791060000000-CreateSportsFollows.ts create mode 100644 src/components/LiveTv/FollowedTeams.tsx diff --git a/docs/maintainers/ng-ecosystem-integration-plan.md b/docs/maintainers/ng-ecosystem-integration-plan.md index cdceea6512..6738d8bf71 100644 --- a/docs/maintainers/ng-ecosystem-integration-plan.md +++ b/docs/maintainers/ng-ecosystem-integration-plan.md @@ -72,7 +72,7 @@ human visual acceptance yet; testing is planned after the full build-out. | 4 ROMarrNG collections / 1G1R full-set requests | pending | Needs new ROMarrNG contract endpoints for collections; not started. | | 4 BookshelfNG series-pack search, M4B option | pending | Needs BookshelfNG contract exposure; not started. | | 4 QuestarrNG RomM/Playnite state into My Games | pending | Needs QuestarrNG contract exposure; not started. | -| 2 Sports "follow my team" | pending | | +| 2 Sports "follow my team" | done | `SportsFollow` entity + migrations `1791060000000`; Live TV Sync maps Tunerr `/v1/sports/events` matches to the nearest guide airing and creates normal recording requests; cancelled games are not re-requested. Integration test against the fake Tunerr. UI: Followed Teams on Recordings. | | 2 Recently aired shelf, channel requests, Plex→Jellyfin users | pending | | | 2 Recording notifications | pending | Requests do not notify yet. | diff --git a/docs/using-seerr/live-tv-recordings.md b/docs/using-seerr/live-tv-recordings.md index 7580d99068..0743bee22c 100644 --- a/docs/using-seerr/live-tv-recordings.md +++ b/docs/using-seerr/live-tv-recordings.md @@ -66,3 +66,16 @@ the next sync re-creates it. Cancelling the request in SeerrNG removes it. Recorded files are published by Tunerr into your media server's catch-up libraries according to Tunerr's own publish settings. + +## Follow a team + +When IPTV Tunerr's sports automation is set up (API-Sports schedules for NFL, +NCAA Football, MLB, or NBA), **Recordings** shows **Followed Teams**. Choose a +team and select **Follow**. Every minute, Live TV Sync looks for that team's +upcoming games that Tunerr matched to a channel, finds the guide airing closest +to the scheduled start (within three hours), and requests a recording of it on +your behalf, with the usual approval rules. + +A game you already requested is not requested again, even if you cancelled it. +Each person can follow up to 20 teams. Unfollowing a team does not cancel +recordings already requested. diff --git a/release-notes/2026-10-06-follow-team-recordings.md b/release-notes/2026-10-06-follow-team-recordings.md new file mode 100644 index 0000000000..27cb0de94c --- /dev/null +++ b/release-notes/2026-10-06-follow-team-recordings.md @@ -0,0 +1,9 @@ +--- +category: added +audience: users +area: recordings +action: Optional. Needs IPTV Tunerr sports automation and a connected Tunerr. +breaking: false +--- + +You can now follow sports teams on the Recordings page. SeerrNG requests a recording of each upcoming game that IPTV Tunerr finds in the guide, using the usual approval rules. diff --git a/seerr-api.yml b/seerr-api.yml index e9790051c1..0c96453cd2 100644 --- a/seerr-api.yml +++ b/seerr-api.yml @@ -8828,6 +8828,91 @@ paths: description: Invalid settings '502': description: slskdN could not be reached + /live-tv/sports/teams: + get: + summary: List teams in Tunerr's sports schedule + description: Teams from IPTV Tunerr's API-Sports schedules, for following. Requires Tunerr sports automation. + tags: + - live-tv + responses: + '200': + description: Teams + content: + application/json: + schema: + type: object + properties: + configured: + type: boolean + enabled: + type: boolean + teams: + type: array + items: + type: object + properties: + dataset: + type: string + league: + type: string + team: + type: string + '502': + description: Tunerr could not be reached + /live-tv/sports/follows: + get: + summary: List the teams the user follows + tags: + - live-tv + responses: + '200': + description: Followed teams + post: + summary: Follow a team + description: Live TV Sync requests a recording of each upcoming game Tunerr matches to a guide airing, using the usual approval rules. Up to 20 teams per user. + tags: + - live-tv + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [dataset, team] + properties: + dataset: + type: string + maxLength: 32 + team: + type: string + maxLength: 128 + responses: + '200': + description: Already following + '201': + description: Following + '400': + description: Invalid team + '403': + description: The user cannot request recordings + '409': + description: Too many followed teams + /live-tv/sports/follows/{id}: + delete: + summary: Stop following a team + tags: + - live-tv + parameters: + - in: path + name: id + required: true + schema: + type: integer + responses: + '204': + description: Unfollowed + '404': + description: Not following /settings/prowlarr: get: summary: Get Prowlarr connection settings diff --git a/server/api/tunerr.ts b/server/api/tunerr.ts index bf1ba32917..8194f0906e 100644 --- a/server/api/tunerr.ts +++ b/server/api/tunerr.ts @@ -49,6 +49,33 @@ export interface TunerrRuleHistory { matches: TunerrRuleHistoryMatch[]; } +export interface TunerrSportsEvent { + id: string; + dataset: string; + league?: string; + home_team: string; + away_team: string; + starts_at: string; + status?: string; +} + +export interface TunerrSportsEventChannel { + source_guide_number?: string; + source_channel_name?: string; + source_programme?: string; + starts_at?: string; + match_confidence?: string; +} + +export interface TunerrSportsReport { + enabled?: boolean; + events: { + event: TunerrSportsEvent; + matched: boolean; + channels?: TunerrSportsEventChannel[]; + }[]; +} + export class TunerrError extends Error { constructor( message: string, @@ -193,6 +220,21 @@ export default class TunerrAPI { return data; } + /** Tunerr's API-Sports schedule matched against its guide. */ + public async getSportsReport(): Promise { + const data = await this.get( + '/v1/sports/events', + 'sports events' + ); + if (!data || !Array.isArray(data.events)) { + throw new TunerrError( + 'Tunerr returned an invalid sports report.', + 'protocol' + ); + } + return data; + } + /** Streams the XMLTV guide. The caller must consume or destroy it. */ public async openGuide(): Promise { const response = await axios.get(this.guideUrl(), { diff --git a/server/entity/SportsFollow.ts b/server/entity/SportsFollow.ts new file mode 100644 index 0000000000..940991f19c --- /dev/null +++ b/server/entity/SportsFollow.ts @@ -0,0 +1,46 @@ +import { DbAwareColumn } from '@server/utils/DbColumnHelper'; +import { + Column, + Entity, + Index, + JoinColumn, + ManyToOne, + PrimaryGeneratedColumn, +} from 'typeorm'; +import { User } from './User'; + +/** + * A team a user follows. The Live TV Sync job requests recordings of the + * team's upcoming games that IPTV Tunerr has matched to a guide airing. + */ +@Entity('sports_follow') +@Index('IDX_sports_follow_identity', ['userId', 'dataset', 'team'], { + unique: true, +}) +export class SportsFollow { + public constructor(init?: Partial) { + Object.assign(this, init); + } + + @PrimaryGeneratedColumn() + public id: number; + + @Column({ type: 'integer' }) + public userId: number; + + @ManyToOne(() => User, { onDelete: 'CASCADE' }) + @JoinColumn({ name: 'userId' }) + public user: User; + + /** Tunerr / API-Sports dataset, e.g. `nfl`. */ + @Column({ type: 'varchar', length: 32 }) + public dataset: string; + + @Column({ type: 'varchar', length: 128 }) + public team: string; + + @DbAwareColumn({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' }) + public createdAt: Date; +} + +export default SportsFollow; diff --git a/server/job/schedule.ts b/server/job/schedule.ts index 9ebeadf739..acc8a7a33e 100644 --- a/server/job/schedule.ts +++ b/server/job/schedule.ts @@ -13,6 +13,7 @@ import { isTunerrConfigured, syncRecordings, } from '@server/lib/liveTv/recordings'; +import { syncSportsFollows } from '@server/lib/liveTv/sports'; import refreshToken from '@server/lib/refreshToken'; import { captureReleaseCalendarHistory } from '@server/lib/releaseCalendar/history'; import { reconcileActiveRequests } from '@server/lib/requestStatus'; @@ -583,6 +584,7 @@ export const startJobs = (): void => { }); return runTrackedJob('Live TV Sync', async () => { await guideIndex.get(); + await syncSportsFollows(); await syncRecordings(); }); }), diff --git a/server/lib/liveTv/guideIndex.ts b/server/lib/liveTv/guideIndex.ts index 9e63a45b28..40efb3a767 100644 --- a/server/lib/liveTv/guideIndex.ts +++ b/server/lib/liveTv/guideIndex.ts @@ -132,6 +132,32 @@ export const findProgrammeInSnapshot = ( return undefined; }; +/** + * Finds the guide programme on a channel whose title matches and whose start + * is closest to `around`, within `windowMs`. Used to turn a sports schedule + * time into the exact guide airing. + */ +export const findProgrammeNear = ( + snapshot: GuideSnapshot, + channel: string, + title: string, + around: Date, + windowMs: number +): GuideProgramme | undefined => { + let best: GuideProgramme | undefined; + let bestDistance = Number.POSITIVE_INFINITY; + for (const programme of snapshot.byTitle.get(normalizeGuideTitle(title)) ?? + []) { + if (programme.channel !== channel) continue; + const distance = Math.abs(programme.start.getTime() - around.getTime()); + if (distance <= windowMs && distance < bestDistance) { + best = programme; + bestDistance = distance; + } + } + return best; +}; + export const readGuideStream = async ( stream: Readable, now: Date, diff --git a/server/lib/liveTv/sports.ts b/server/lib/liveTv/sports.ts new file mode 100644 index 0000000000..8e097d7778 --- /dev/null +++ b/server/lib/liveTv/sports.ts @@ -0,0 +1,170 @@ +import TunerrAPI, { type TunerrSportsReport } from '@server/api/tunerr'; +import { getRepository } from '@server/datasource'; +import RecordingRequest from '@server/entity/RecordingRequest'; +import SportsFollow from '@server/entity/SportsFollow'; +import { User } from '@server/entity/User'; +import { + findProgrammeNear, + guideIndex, + type GuideSnapshot, +} from '@server/lib/liveTv/guideIndex'; +import { + createRecordingRequest, + isTunerrConfigured, + RecordingRequestError, +} from '@server/lib/liveTv/recordings'; +import { Permission } from '@server/lib/permissions'; +import { getSettings } from '@server/lib/settings'; +import logger from '@server/logger'; + +/** How far a guide airing may start from the scheduled game time. */ +const GAME_MATCH_WINDOW_MS = 3 * 60 * 60 * 1000; + +export interface SportsTeam { + dataset: string; + league?: string; + team: string; +} + +const teamKey = (dataset: string, team: string) => + `${dataset.toLowerCase()}|${team.trim().toLowerCase()}`; + +/** Teams seen in Tunerr's sports schedule, for the follow picker. */ +export const listSportsTeams = (report: TunerrSportsReport): SportsTeam[] => { + const teams = new Map(); + for (const { event } of report.events) { + for (const team of [event.home_team, event.away_team]) { + if (!team?.trim() || !event.dataset) continue; + const key = teamKey(event.dataset, team); + if (!teams.has(key)) { + teams.set(key, { + dataset: event.dataset, + league: event.league, + team: team.trim(), + }); + } + } + } + return [...teams.values()].sort( + (a, b) => a.dataset.localeCompare(b.dataset) || a.team.localeCompare(b.team) + ); +}; + +export interface PlannedGameRecording { + eventId: string; + channel: string; + start: string; + title: string; +} + +/** + * Upcoming games for the followed teams that Tunerr matched to a channel, + * resolved to the exact guide airing SeerrNG can request. Exposed for tests. + */ +export const planGameRecordings = ( + report: TunerrSportsReport, + follows: Pick[], + snapshot: GuideSnapshot, + now: Date +): PlannedGameRecording[] => { + const followed = new Set( + follows.map((follow) => teamKey(follow.dataset, follow.team)) + ); + const planned: PlannedGameRecording[] = []; + for (const { event, matched, channels } of report.events) { + if (!matched || !channels?.length) continue; + const isFollowed = [event.home_team, event.away_team].some((team) => + followed.has(teamKey(event.dataset, team ?? '')) + ); + if (!isFollowed) continue; + const startsAt = new Date(event.starts_at); + if (Number.isNaN(startsAt.getTime())) continue; + for (const channel of channels) { + if (!channel.source_guide_number || !channel.source_programme) continue; + const programme = findProgrammeNear( + snapshot, + channel.source_guide_number, + channel.source_programme, + startsAt, + GAME_MATCH_WINDOW_MS + ); + if (!programme || programme.stop <= now) continue; + planned.push({ + eventId: event.id, + channel: programme.channel, + start: programme.start.toISOString(), + title: programme.title, + }); + // One airing per game is enough. + break; + } + } + return planned; +}; + +let syncing = false; + +/** + * Requests recordings of followed teams' games. A game the user already + * requested in any state (including cancelled) is not requested again. + */ +export const syncSportsFollows = async (): Promise => { + if (syncing || !isTunerrConfigured()) return; + syncing = true; + try { + const follows = await getRepository(SportsFollow).find(); + if (follows.length === 0) return; + const snapshot = await guideIndex.get(); + if (!snapshot) return; + const report = await new TunerrAPI(getSettings().tunerr).getSportsReport(); + const now = new Date(); + + const byUser = new Map(); + for (const follow of follows) { + byUser.set(follow.userId, [...(byUser.get(follow.userId) ?? []), follow]); + } + + for (const [userId, userFollows] of byUser) { + const user = await getRepository(User).findOne({ where: { id: userId } }); + if (!user?.hasPermission(Permission.REQUEST)) continue; + for (const game of planGameRecordings( + report, + userFollows, + snapshot, + now + )) { + const existing = await getRepository(RecordingRequest).findOne({ + where: { + requestedById: userId, + channelId: game.channel, + startsAt: new Date(game.start), + }, + }); + if (existing) continue; + try { + await createRecordingRequest(user, { + kind: 'airing', + title: game.title, + channel: game.channel, + start: game.start, + }); + } catch (error) { + if (!(error instanceof RecordingRequestError)) throw error; + logger.debug('Skipped a followed-team recording', { + label: 'Live TV', + userId, + eventId: game.eventId, + reason: error.message, + }); + } + } + } + } catch (error) { + logger.warn('Followed-team recording sync failed', { + label: 'Live TV', + errorMessage: error instanceof Error ? error.message : String(error), + }); + } finally { + syncing = false; + } +}; diff --git a/server/migration/postgres/1791060000000-CreateSportsFollows.ts b/server/migration/postgres/1791060000000-CreateSportsFollows.ts new file mode 100644 index 0000000000..ed92afb24c --- /dev/null +++ b/server/migration/postgres/1791060000000-CreateSportsFollows.ts @@ -0,0 +1,26 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class CreateSportsFollows1791060000000 implements MigrationInterface { + name = 'CreateSportsFollows1791060000000'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + CREATE TABLE "sports_follow" ( + "id" SERIAL NOT NULL, + "userId" integer NOT NULL, + "dataset" character varying(32) NOT NULL, + "team" character varying(128) NOT NULL, + "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), + CONSTRAINT "PK_sports_follow" PRIMARY KEY ("id"), + CONSTRAINT "FK_sports_follow_user" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION + ) + `); + await queryRunner.query( + 'CREATE UNIQUE INDEX "IDX_sports_follow_identity" ON "sports_follow" ("userId", "dataset", "team")' + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query('DROP TABLE "sports_follow"'); + } +} diff --git a/server/migration/sqlite/1791060000000-CreateSportsFollows.test.ts b/server/migration/sqlite/1791060000000-CreateSportsFollows.test.ts new file mode 100644 index 0000000000..0bd608e272 --- /dev/null +++ b/server/migration/sqlite/1791060000000-CreateSportsFollows.test.ts @@ -0,0 +1,40 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { DataSource } from 'typeorm'; +import { CreateSportsFollows1791060000000 } from './1791060000000-CreateSportsFollows'; + +test('creates unique per-user team follows', async () => { + const dataSource = await new DataSource({ + type: 'better-sqlite3', + database: ':memory:', + }).initialize(); + const queryRunner = dataSource.createQueryRunner(); + const migration = new CreateSportsFollows1791060000000(); + + try { + await queryRunner.query('PRAGMA foreign_keys = ON'); + await queryRunner.query( + 'CREATE TABLE "user" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL)' + ); + await queryRunner.query('INSERT INTO "user" ("id") VALUES (1)'); + await migration.up(queryRunner); + await queryRunner.query( + `INSERT INTO "sports_follow" ("userId", "dataset", "team") VALUES (1, 'nfl', 'Denver Broncos')` + ); + await assert.rejects( + queryRunner.query( + `INSERT INTO "sports_follow" ("userId", "dataset", "team") VALUES (1, 'nfl', 'Denver Broncos')` + ) + ); + await queryRunner.query('DELETE FROM "user" WHERE "id" = 1'); + const [{ count }] = await queryRunner.query( + 'SELECT COUNT(*) AS "count" FROM "sports_follow"' + ); + assert.equal(count, 0); + await migration.down(queryRunner); + assert.equal(await queryRunner.hasTable('sports_follow'), false); + } finally { + await queryRunner.release(); + await dataSource.destroy(); + } +}); diff --git a/server/migration/sqlite/1791060000000-CreateSportsFollows.ts b/server/migration/sqlite/1791060000000-CreateSportsFollows.ts new file mode 100644 index 0000000000..173284394c --- /dev/null +++ b/server/migration/sqlite/1791060000000-CreateSportsFollows.ts @@ -0,0 +1,25 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class CreateSportsFollows1791060000000 implements MigrationInterface { + name = 'CreateSportsFollows1791060000000'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + CREATE TABLE "sports_follow" ( + "id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, + "userId" integer NOT NULL, + "dataset" varchar(32) NOT NULL, + "team" varchar(128) NOT NULL, + "createdAt" datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "FK_sports_follow_user" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION + ) + `); + await queryRunner.query( + 'CREATE UNIQUE INDEX "IDX_sports_follow_identity" ON "sports_follow" ("userId", "dataset", "team")' + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query('DROP TABLE "sports_follow"'); + } +} diff --git a/server/routes/liveTv.test.ts b/server/routes/liveTv.test.ts index 0a671576ea..5200f5df4f 100644 --- a/server/routes/liveTv.test.ts +++ b/server/routes/liveTv.test.ts @@ -6,9 +6,11 @@ import { after, before, beforeEach, describe, it } from 'node:test'; import { getRepository } from '@server/datasource'; import RecordingRequest from '@server/entity/RecordingRequest'; +import SportsFollow from '@server/entity/SportsFollow'; import { User } from '@server/entity/User'; import { guideIndex } from '@server/lib/liveTv/guideIndex'; import { syncRecordings } from '@server/lib/liveTv/recordings'; +import { syncSportsFollows } from '@server/lib/liveTv/sports'; import { getSettings, type TunerrSettings } from '@server/lib/settings'; import { setupTestDb } from '@server/test/db'; import express from 'express'; @@ -26,6 +28,7 @@ interface FakeTunerr { features: string[]; history: Record[]; authHeaders: (string | undefined)[]; + sports: Record; } const startFakeTunerr = async (start: Date): Promise => { @@ -44,6 +47,7 @@ const startFakeTunerr = async (start: Date): Promise => { features: ['title_equals', 'start_window', 'rules_only_recorder'], history: [], authHeaders: [], + sports: { events: [] }, }; fake.server.on('request', (req, res) => { if (req.url === '/guide.xml') { @@ -75,6 +79,10 @@ const startFakeTunerr = async (start: Date): Promise => { }); return; } + if (req.url === '/api/v1/sports/events') { + res.end(JSON.stringify(fake.sports)); + return; + } if (req.url === '/api/recordings/history.json') { res.end(JSON.stringify({ matches: fake.history })); return; @@ -276,4 +284,71 @@ describe('Live TV recording requests', () => { }); assert.equal(response.status, 404); }); + + it('records followed teams through matched guide airings', async () => { + fake.sports = { + enabled: true, + events: [ + { + event: { + id: 'nfl-1', + dataset: 'nfl', + home_team: 'Denver Broncos', + away_team: 'Kansas City Chiefs', + // Schedule time differs slightly from the guide airing. + starts_at: new Date( + airingStart.getTime() + 10 * 60_000 + ).toISOString(), + }, + matched: true, + channels: [ + { source_guide_number: '101', source_programme: 'Evening News' }, + ], + }, + ], + }; + + const teams = await as(friend).get('/live-tv/sports/teams'); + assert.equal(teams.status, 200); + assert.deepEqual( + teams.body.teams.map((team: { team: string }) => team.team), + ['Denver Broncos', 'Kansas City Chiefs'] + ); + + const followed = await as(friend).post('/live-tv/sports/follows', { + dataset: 'NFL', + team: 'Denver Broncos', + }); + assert.equal(followed.status, 201); + assert.equal(followed.body.dataset, 'nfl'); + + await syncSportsFollows(); + const [recording] = await getRepository(RecordingRequest).find({ + where: { requestedById: friend.id }, + }); + assert.equal(recording.kind, 'airing'); + assert.equal(recording.channelId, '101'); + assert.equal(recording.status, 'pending'); + assert.equal( + new Date(recording.startsAt as Date).toISOString(), + airingStart.toISOString() + ); + + // A cancelled game is not requested again. + recording.status = 'cancelled'; + await getRepository(RecordingRequest).save(recording); + await syncSportsFollows(); + assert.equal( + await getRepository(RecordingRequest).count({ + where: { requestedById: friend.id }, + }), + 1 + ); + + const unfollow = await as(friend).delete( + `/live-tv/sports/follows/${followed.body.id}` + ); + assert.equal(unfollow.status, 204); + assert.equal(await getRepository(SportsFollow).count(), 0); + }); }); diff --git a/server/routes/liveTv.ts b/server/routes/liveTv.ts index a3268f2edf..421442f6c8 100644 --- a/server/routes/liveTv.ts +++ b/server/routes/liveTv.ts @@ -1,7 +1,9 @@ +import TunerrAPI, { TunerrError } from '@server/api/tunerr'; import { getRepository } from '@server/datasource'; import RecordingRequest, { ACTIVE_RECORDING_STATUSES, } from '@server/entity/RecordingRequest'; +import SportsFollow from '@server/entity/SportsFollow'; import { findAiringsInSnapshot, guideIndex, @@ -15,7 +17,9 @@ import { RecordingRequestError, scheduleRecording, } from '@server/lib/liveTv/recordings'; +import { listSportsTeams } from '@server/lib/liveTv/sports'; import { Permission } from '@server/lib/permissions'; +import { getSettings } from '@server/lib/settings'; import { parseNonNegativeRouteId } from '@server/utils/routeId'; import type { Response } from 'express'; import { Router } from 'express'; @@ -265,4 +269,81 @@ liveTvRoutes.delete('/recordings/:id', async (req, res) => { } }); +liveTvRoutes.get('/sports/teams', async (_req, res) => { + if (!isTunerrConfigured()) { + return res.status(200).json({ configured: false, teams: [] }); + } + try { + const report = await new TunerrAPI(getSettings().tunerr).getSportsReport(); + return res.status(200).json({ + configured: true, + enabled: report.enabled !== false, + teams: listSportsTeams(report), + }); + } catch (error) { + return res.status(502).json({ + message: + error instanceof TunerrError + ? error.message + : 'Tunerr sports schedules could not be loaded.', + }); + } +}); + +const followView = (follow: SportsFollow) => ({ + id: follow.id, + dataset: follow.dataset, + team: follow.team, + createdAt: follow.createdAt, +}); + +liveTvRoutes.get('/sports/follows', async (req, res) => { + const follows = await getRepository(SportsFollow).find({ + where: { userId: req.user!.id }, + order: { dataset: 'ASC', team: 'ASC' }, + }); + return res.status(200).json({ results: follows.map(followView) }); +}); + +liveTvRoutes.post('/sports/follows', async (req, res) => { + const user = req.user!; + if (!user.hasPermission(Permission.REQUEST)) { + return res + .status(403) + .json({ message: 'You do not have permission to request recordings.' }); + } + const body = (req.body ?? {}) as Record; + const dataset = + typeof body.dataset === 'string' ? body.dataset.trim().toLowerCase() : ''; + const team = typeof body.team === 'string' ? body.team.trim() : ''; + if (!/^[a-z0-9_-]{1,32}$/.test(dataset) || !team || team.length > 128) { + return res.status(400).json({ message: 'Choose a team to follow.' }); + } + const repository = getRepository(SportsFollow); + const count = await repository.count({ where: { userId: user.id } }); + if (count >= 20) { + return res.status(409).json({ message: 'You can follow up to 20 teams.' }); + } + const existing = await repository.findOne({ + where: { userId: user.id, dataset, team }, + }); + if (existing) return res.status(200).json(followView(existing)); + const saved = await repository.save( + new SportsFollow({ userId: user.id, dataset, team }) + ); + return res.status(201).json(followView(saved)); +}); + +liveTvRoutes.delete('/sports/follows/:id', async (req, res) => { + const id = parseNonNegativeRouteId(req.params.id); + const repository = getRepository(SportsFollow); + const follow = + id === undefined + ? null + : await repository.findOne({ where: { id, userId: req.user!.id } }); + if (!follow) return res.status(404).json({ message: 'Not following.' }); + await repository.remove(follow); + return res.status(204).end(); +}); + export default liveTvRoutes; diff --git a/src/components/LiveTv/FollowedTeams.tsx b/src/components/LiveTv/FollowedTeams.tsx new file mode 100644 index 0000000000..ea2fa91c60 --- /dev/null +++ b/src/components/LiveTv/FollowedTeams.tsx @@ -0,0 +1,161 @@ +import Button from '@app/components/Common/Button'; +import useToasts from '@app/hooks/useToasts'; +import defineMessages from '@app/utils/defineMessages'; +import axios from 'axios'; +import { useState } from 'react'; +import { useIntl } from 'react-intl'; +import useSWR from 'swr'; + +interface SportsTeam { + dataset: string; + league?: string; + team: string; +} + +interface Follow { + id: number; + dataset: string; + team: string; +} + +const messages = defineMessages('components.LiveTv.FollowedTeams', { + title: 'Followed Teams', + description: + 'SeerrNG requests a recording of each upcoming game for these teams when Tunerr finds it in the guide. Recordings follow the usual approval rules.', + none: 'You are not following any teams.', + team: 'Team', + choose: 'Choose a team', + follow: 'Follow', + unfollow: 'Unfollow {team}', + unavailable: + 'Team schedules are not available. An administrator can turn on sports automation in IPTV Tunerr.', + failed: 'The team could not be updated.', +}); + +const FollowedTeams = ({ canRequest }: { canRequest: boolean }) => { + const intl = useIntl(); + const { addToast } = useToasts(); + const { data: teams, error: teamsError } = useSWR<{ + enabled?: boolean; + teams: SportsTeam[]; + }>('/api/v1/live-tv/sports/teams', { revalidateOnFocus: false }); + const { data: follows, mutate } = useSWR<{ results: Follow[] }>( + '/api/v1/live-tv/sports/follows' + ); + const [selected, setSelected] = useState(''); + const [busy, setBusy] = useState(false); + + const followed = new Set( + (follows?.results ?? []).map( + (follow) => `${follow.dataset}|${follow.team.toLowerCase()}` + ) + ); + const available = (teams?.teams ?? []).filter( + (team) => !followed.has(`${team.dataset}|${team.team.toLowerCase()}`) + ); + + const run = async (action: () => Promise) => { + setBusy(true); + try { + await action(); + await mutate(); + } catch (failure) { + addToast( + axios.isAxiosError(failure) && + typeof failure.response?.data?.message === 'string' + ? failure.response.data.message + : intl.formatMessage(messages.failed), + { appearance: 'error', autoDismiss: true } + ); + } finally { + setBusy(false); + } + }; + + const unavailable = + !!teamsError || (teams && (teams.enabled === false || !teams.teams.length)); + + return ( +
    +

    {intl.formatMessage(messages.title)}

    +

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

    + {(follows?.results ?? []).length === 0 ? ( +

    {intl.formatMessage(messages.none)}

    + ) : ( +
    + {follows?.results.map((follow) => ( + + ))} +
    + )} + {unavailable ? ( +

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

    + ) : ( +
    + +
    +
    + +
    +
    + +
    +
    +
    + )} +
    + ); +}; + +export default FollowedTeams; diff --git a/src/components/LiveTv/RecordingList.tsx b/src/components/LiveTv/RecordingList.tsx index 333837aa90..1a2a22d984 100644 --- a/src/components/LiveTv/RecordingList.tsx +++ b/src/components/LiveTv/RecordingList.tsx @@ -2,6 +2,7 @@ import Badge from '@app/components/Common/Badge'; import Button from '@app/components/Common/Button'; import LoadingSpinner from '@app/components/Common/LoadingSpinner'; import PageTitle from '@app/components/Common/PageTitle'; +import FollowedTeams from '@app/components/LiveTv/FollowedTeams'; import type { RecordingRequestView, RecordingStatus, @@ -245,6 +246,7 @@ const RecordingList = () => { ) : ( <> +
    {canViewAll && ( + )} + {isDirty && ( + + )} + +
    +
    + + )} +
    + + ); +}; + +export default SettingsSwipe; diff --git a/src/components/Swipe/SwipeCardView.tsx b/src/components/Swipe/SwipeCardView.tsx new file mode 100644 index 0000000000..277b485e83 --- /dev/null +++ b/src/components/Swipe/SwipeCardView.tsx @@ -0,0 +1,191 @@ +import Badge from '@app/components/Common/Badge'; +import CachedImage from '@app/components/Common/CachedImage'; +import defineMessages from '@app/utils/defineMessages'; +import type { CSSProperties, PointerEvent } from 'react'; +import { useRef, useState } from 'react'; +import { useIntl } from 'react-intl'; + +export type SwipeDirection = 'right' | 'left' | 'up'; + +export interface SwipeCardData { + mediaType: 'movie' | 'tv' | 'book'; + id: string; + title: string; + subtitle?: string; + year?: number; + overview?: string; + imageUrl?: string; + rating?: number; + authorId?: string; + because?: string; + reason?: string; +} + +const messages = defineMessages('components.Swipe.SwipeCardView', { + want: 'Request', + pass: 'Pass', + seen: 'Seen It', + rating: '{rating} / 10', + bookRating: '{rating} / 5', +}); + +/** Distance in pixels a drag must travel to count as a swipe. */ +export const SWIPE_THRESHOLD = 110; + +/** Decides a swipe from a finished drag. Exposed for tests. */ +export const swipeFromDrag = ( + dx: number, + dy: number +): SwipeDirection | undefined => { + if (-dy > SWIPE_THRESHOLD && Math.abs(dx) < SWIPE_THRESHOLD) return 'up'; + if (dx > SWIPE_THRESHOLD) return 'right'; + if (dx < -SWIPE_THRESHOLD) return 'left'; + return undefined; +}; + +interface SwipeCardViewProps { + card: SwipeCardData; + position: 0 | 1 | 2; + exit?: SwipeDirection; + disabled: boolean; + onSwipe: (direction: SwipeDirection) => void; +} + +const SwipeCardView = ({ + card, + position, + exit, + disabled, + onSwipe, +}: SwipeCardViewProps) => { + const intl = useIntl(); + const start = useRef<{ x: number; y: number; id: number }>(undefined); + const [offset, setOffset] = useState({ x: 0, y: 0 }); + const [dragging, setDragging] = useState(false); + const isTop = position === 0; + + const onPointerDown = (event: PointerEvent) => { + if (!isTop || disabled || event.button !== 0) return; + // Let the details panel scroll on touch devices. + if ((event.target as HTMLElement).closest('.swipe-card-body')) return; + start.current = { x: event.clientX, y: event.clientY, id: event.pointerId }; + event.currentTarget.setPointerCapture(event.pointerId); + setDragging(true); + }; + + const onPointerMove = (event: PointerEvent) => { + if (!start.current || start.current.id !== event.pointerId) return; + setOffset({ + x: event.clientX - start.current.x, + y: event.clientY - start.current.y, + }); + }; + + const finishDrag = (event: PointerEvent, cancelled = false) => { + if (!start.current || start.current.id !== event.pointerId) return; + const direction = cancelled ? undefined : swipeFromDrag(offset.x, offset.y); + start.current = undefined; + setDragging(false); + setOffset({ x: 0, y: 0 }); + if (direction) onSwipe(direction); + }; + + const stampOpacity = (stamp: 'want' | 'pass' | 'seen') => { + const progress = + stamp === 'want' + ? offset.x / SWIPE_THRESHOLD + : stamp === 'pass' + ? -offset.x / SWIPE_THRESHOLD + : -offset.y / SWIPE_THRESHOLD; + const fromExit = + (exit === 'right' && stamp === 'want') || + (exit === 'left' && stamp === 'pass') || + (exit === 'up' && stamp === 'seen'); + return fromExit ? 1 : Math.max(0, Math.min(1, progress)); + }; + + // Runtime drag geometry is the only inline styling (see .swipe-card). + const style = ( + dragging + ? { + '--swipe-offset-x': `${offset.x}px`, + '--swipe-offset-y': `${Math.min(offset.y, 0)}px`, + '--swipe-tilt': `${offset.x / 20}deg`, + } + : {} + ) as CSSProperties; + + const stamp = (kind: 'want' | 'pass' | 'seen') => ( + + ); + + return ( +
    finishDrag(event)} + onPointerCancel={(event) => finishDrag(event, true)} + > +
    + {card.imageUrl && ( + + )} + {isTop && ( + <> + {stamp('want')} + {stamp('pass')} + {stamp('seen')} + + )} +
    +
    +
    +

    {card.title}

    + {card.rating !== undefined && ( + + {intl.formatMessage( + card.mediaType === 'book' + ? messages.bookRating + : messages.rating, + { rating: card.rating } + )} + + )} +
    + {card.subtitle &&

    {card.subtitle}

    } + {(card.reason ?? card.because) && ( +

    {card.reason ?? card.because}

    + )} + {card.overview &&

    {card.overview}

    } +
    +
    + ); +}; + +export default SwipeCardView; diff --git a/src/components/Swipe/index.tsx b/src/components/Swipe/index.tsx new file mode 100644 index 0000000000..06cf52569f --- /dev/null +++ b/src/components/Swipe/index.tsx @@ -0,0 +1,554 @@ +import Button from '@app/components/Common/Button'; +import LoadingSpinner from '@app/components/Common/LoadingSpinner'; +import Modal from '@app/components/Common/Modal'; +import PageTitle from '@app/components/Common/PageTitle'; +import SwipeCardView, { + type SwipeCardData, + type SwipeDirection, +} from '@app/components/Swipe/SwipeCardView'; +import useToasts from '@app/hooks/useToasts'; +import defineMessages from '@app/utils/defineMessages'; +import { + ArrowUturnLeftIcon, + CheckIcon, + EyeIcon, + XMarkIcon, +} from '@heroicons/react/24/outline'; +import axios from 'axios'; +import { useCallback, useEffect, useRef, useState } from 'react'; +import { useIntl } from 'react-intl'; +import useSWR from 'swr'; + +type SwipeMediaType = 'movie' | 'tv' | 'book'; + +interface DeckResponse { + mediaType: SwipeMediaType; + ranked: boolean; + remaining: number; + cards: SwipeCardData[]; +} + +interface SwipeProfile { + tasteNotes: string; + seriesRequest: 'first-season' | 'all-seasons'; + bookFormat: 'ebook' | 'audiobook'; +} + +const messages = defineMessages('components.Swipe', { + title: 'Swipe', + unavailable: + 'Swipe is not available. An administrator may have turned it off, or your account cannot make requests.', + intro: + 'Swipe right to request, left to pass, or up if you have already seen or read it.', + movies: 'Movies', + series: 'Series', + books: 'Books', + request: 'Request', + pass: 'Pass', + seen: 'Seen It', + undo: 'Undo', + preferences: 'Preferences', + refresh: 'New Picks', + aiRanked: 'Ordered for you by AI', + loadError: 'Recommendations could not be loaded.', + retry: 'Retry', + empty: 'You Are All Caught Up', + emptyHelp: + 'Request or swipe a few more titles elsewhere, then check back for new picks.', + requested: '{title} requested.', + requestFailed: '{title} could not be requested: {reason}', + undone: 'Brought back {title}.', + saveFailed: 'Your swipe could not be saved. Try again.', + keyboardHint: 'Keyboard: ← pass, → request, ↑ seen it, Backspace to undo.', + tasteNotes: 'What Are You in the Mood For?', + tasteNotesHelp: + 'Optional. Used to order your picks when AI ordering is turned on, for example “cozy mysteries” or “nothing too scary”.', + seriesRequest: 'When I Request a Series', + firstSeason: 'Request the first season', + allSeasons: 'Request every season', + bookFormat: 'When I Request a Book', + audiobook: 'Request the audiobook', + ebook: 'Request the ebook', + save: 'Save', + close: 'Close', +}); + +const TABS: { mediaType: SwipeMediaType; label: keyof typeof messages }[] = [ + { mediaType: 'movie', label: 'movies' }, + { mediaType: 'tv', label: 'series' }, + { mediaType: 'book', label: 'books' }, +]; + +const EXIT_MS = 320; +const REFILL_BELOW = 4; + +const DECISION: Record = { + right: 'want', + left: 'pass', + up: 'seen', +}; + +/** The request body a right swipe submits. Exposed for tests. */ +export const requestBodyFor = (card: SwipeCardData, profile: SwipeProfile) => { + if (card.mediaType === 'movie') { + return { mediaType: 'movie', mediaId: Number(card.id) }; + } + if (card.mediaType === 'tv') { + return { + mediaType: 'tv', + mediaId: Number(card.id), + seasons: profile.seriesRequest === 'all-seasons' ? 'all' : [1], + }; + } + return { + mediaType: 'book', + mediaId: card.id, + authorId: card.authorId, + format: profile.bookFormat, + }; +}; + +const errorMessage = (error: unknown) => + axios.isAxiosError(error) && typeof error.response?.data?.message === 'string' + ? error.response.data.message + : undefined; + +const Swipe = () => { + const intl = useIntl(); + const { addToast } = useToasts(); + const [mediaType, setMediaType] = useState('movie'); + const [cards, setCards] = useState([]); + const [exiting, setExiting] = useState<{ + id: string; + direction: SwipeDirection; + }>(); + const [busy, setBusy] = useState(false); + const [showPreferences, setShowPreferences] = useState(false); + const [draftProfile, setDraftProfile] = useState(); + const lastLoaded = useRef(undefined); + + const { data: status, error: statusError } = useSWR<{ + aiRanking: boolean; + }>('/api/v1/swipe/status'); + const unavailable = + axios.isAxiosError(statusError) && + (statusError.response?.status === 404 || + statusError.response?.status === 403); + const { data: profile, mutate: mutateProfile } = useSWR( + '/api/v1/swipe/profile' + ); + const { + data: deck, + error, + isValidating, + mutate: reloadDeck, + } = useSWR(`/api/v1/swipe/deck?mediaType=${mediaType}`, { + revalidateOnFocus: false, + }); + + // Replace the local stack when a new deck arrives; keep cards the user is + // looking at and append the rest. + useEffect(() => { + if (!deck) return; + const key = `${deck.mediaType}:${deck.cards.map((card) => card.id).join(',')}`; + if (lastLoaded.current === key) return; + lastLoaded.current = key; + setCards((current) => { + if (current[0]?.mediaType !== deck.mediaType) return deck.cards; + const seen = new Set(current.map((card) => card.id)); + return [...current, ...deck.cards.filter((card) => !seen.has(card.id))]; + }); + }, [deck]); + + useEffect(() => { + setCards([]); + lastLoaded.current = undefined; + }, [mediaType]); + + const top = cards[0]; + + const swipe = useCallback( + async (direction: SwipeDirection) => { + if (!top || busy || exiting || !profile) return; + setBusy(true); + try { + if (direction === 'right') { + try { + await axios.post('/api/v1/request', requestBodyFor(top, profile)); + } catch (failure) { + addToast( + intl.formatMessage(messages.requestFailed, { + title: top.title, + reason: errorMessage(failure) ?? '', + }), + { appearance: 'error', autoDismiss: true } + ); + return; + } + addToast( + intl.formatMessage(messages.requested, { title: top.title }), + { + appearance: 'success', + autoDismiss: true, + } + ); + } + try { + await axios.post('/api/v1/swipe/decisions', { + mediaType: top.mediaType, + id: top.id, + decision: DECISION[direction], + }); + } catch (failure) { + // A right swipe already made its request; only a lost pass/seen + // needs to keep the card. + if (direction !== 'right') { + addToast(intl.formatMessage(messages.saveFailed), { + appearance: 'error', + autoDismiss: true, + }); + return; + } + void failure; + } + setExiting({ id: top.id, direction }); + window.setTimeout(() => { + setExiting(undefined); + setCards((current) => { + const next = current.filter((card) => card.id !== top.id); + if (next.length < REFILL_BELOW) void reloadDeck(); + return next; + }); + }, EXIT_MS); + } finally { + setBusy(false); + } + }, + [addToast, busy, exiting, intl, profile, reloadDeck, top] + ); + + const undo = useCallback(async () => { + if (busy) return; + setBusy(true); + try { + const response = await axios.post<{ card: SwipeCardData }>( + '/api/v1/swipe/undo', + { mediaType } + ); + const card = response.data.card; + setCards((current) => [ + card, + ...current.filter((item) => item.id !== card.id), + ]); + addToast(intl.formatMessage(messages.undone, { title: card.title }), { + appearance: 'info', + autoDismiss: true, + }); + } catch (failure) { + const message = errorMessage(failure); + if (message) { + addToast(message, { appearance: 'info', autoDismiss: true }); + } + } finally { + setBusy(false); + } + }, [addToast, busy, intl, mediaType]); + + useEffect(() => { + const onKey = (event: KeyboardEvent) => { + const target = event.target as HTMLElement | null; + if ( + showPreferences || + target?.closest('input, textarea, select, [contenteditable]') + ) { + return; + } + const direction: SwipeDirection | undefined = + event.key === 'ArrowRight' + ? 'right' + : event.key === 'ArrowLeft' + ? 'left' + : event.key === 'ArrowUp' + ? 'up' + : undefined; + if (direction) { + event.preventDefault(); + void swipe(direction); + } else if (event.key === 'Backspace') { + event.preventDefault(); + void undo(); + } + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }, [showPreferences, swipe, undo]); + + const savePreferences = async () => { + if (!draftProfile) return; + try { + const response = await axios.put( + '/api/v1/swipe/profile', + draftProfile + ); + await mutateProfile(response.data, { revalidate: false }); + setShowPreferences(false); + if (response.data.tasteNotes !== profile?.tasteNotes) { + setCards([]); + lastLoaded.current = undefined; + void reloadDeck(); + } + } catch (failure) { + addToast( + errorMessage(failure) ?? intl.formatMessage(messages.saveFailed), + { + appearance: 'error', + autoDismiss: true, + } + ); + } + }; + + const visible = cards.slice(0, 3); + const loading = !deck && !error; + + return ( +
    + +
    +

    {intl.formatMessage(messages.title)}

    + {(loading || (isValidating && cards.length === 0)) && ( + + + + )} +
    +

    {intl.formatMessage(messages.intro)}

    +
    + {TABS.map((tab) => ( + + ))} + +
    + {status?.aiRanking && deck?.ranked && ( +

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

    + )} + + {unavailable ? ( +
    +

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

    +
    + ) : error && cards.length === 0 ? ( +
    +

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

    +
    + +
    +
    + ) : deck && cards.length === 0 && !isValidating ? ( +
    +

    {intl.formatMessage(messages.empty)}

    +

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

    +
    + +
    +
    + ) : ( + <> +
    + {visible + .map((card, index) => ( + void swipe(direction)} + /> + )) + .reverse()} +
    +
    + + + + +
    +

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

    + + )} + + {showPreferences && draftProfile && ( + setShowPreferences(false)} + cancelText={intl.formatMessage(messages.close)} + onOk={() => void savePreferences()} + okText={intl.formatMessage(messages.save)} + > +
    + +
    +
    +