diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index 09caf30362..b92199824d 100644 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -9,6 +9,9 @@ body: Thanks for taking the time to fill out this bug report! Please note that we use GitHub issues exclusively for bug reports and feature requests. For support requests, please use our other support channels to get help. + + > [!IMPORTANT] + > Our [AI policy](https://github.com/seerr-team/seerr/blob/develop/CONTRIBUTING.md#issues) applies to issues too. Write this issue yourself and disclose any AI use below. Issues that read as unreviewed AI output will be closed and locked. - type: textarea id: description attributes: @@ -16,6 +19,13 @@ body: description: Please provide a clear and concise description of the bug or issue. validations: required: true + - type: textarea + id: ai-disclosure + attributes: + label: AI Disclosure + description: How did you use AI to find or write up this issue, if at all? Write "None" if you didn't. + validations: + required: true - type: input id: version attributes: @@ -100,6 +110,13 @@ body: options: - label: Yes, I have searched existing issues. required: true + - type: checkboxes + id: ai-policy + attributes: + label: AI Policy + options: + - label: I have read the [AI policy](https://github.com/seerr-team/seerr/blob/develop/CONTRIBUTING.md#ai-assistance-notice) and this issue follows it. + required: true - type: checkboxes id: terms attributes: diff --git a/.github/ISSUE_TEMPLATE/documentation.yml b/.github/ISSUE_TEMPLATE/documentation.yml index 8d380a4931..498c446973 100644 --- a/.github/ISSUE_TEMPLATE/documentation.yml +++ b/.github/ISSUE_TEMPLATE/documentation.yml @@ -11,6 +11,9 @@ body: Use this template for documentation issues (typos, unclear steps, missing info, outdated screenshots). For app bugs or feature ideas, please use the other templates. + + > [!IMPORTANT] + > Our [AI policy](https://github.com/seerr-team/seerr/blob/develop/CONTRIBUTING.md#issues) applies to issues too. Write this issue yourself and disclose any AI use below. Issues that read as unreviewed AI output will be closed and locked. - type: input id: doc-location attributes: @@ -38,6 +41,13 @@ body: description: Describe the issue in the docs. validations: required: true + - type: textarea + id: ai-disclosure + attributes: + label: AI Disclosure + description: How did you use AI to find or write up this issue, if at all? Write "None" if you didn't. + validations: + required: true - type: textarea id: suggested-fix attributes: @@ -53,6 +63,13 @@ body: options: - label: Yes, I have searched existing issues. required: true + - type: checkboxes + id: ai-policy + attributes: + label: AI Policy + options: + - label: I have read the [AI policy](https://github.com/seerr-team/seerr/blob/develop/CONTRIBUTING.md#ai-assistance-notice) and this issue follows it. + required: true - type: checkboxes id: terms attributes: diff --git a/.github/ISSUE_TEMPLATE/enhancement.yml b/.github/ISSUE_TEMPLATE/enhancement.yml index 28d0e59877..66a54d1783 100644 --- a/.github/ISSUE_TEMPLATE/enhancement.yml +++ b/.github/ISSUE_TEMPLATE/enhancement.yml @@ -9,6 +9,9 @@ body: Thanks for taking the time to fill out this feature request! Please note that we use GitHub issues exclusively for bug reports and feature requests. For support requests, please use our other support channels to get help. + + > [!IMPORTANT] + > Our [AI policy](https://github.com/seerr-team/seerr/blob/develop/CONTRIBUTING.md#issues) applies to issues too. Write this issue yourself and disclose any AI use below. Issues that read as unreviewed AI output will be closed and locked. - type: textarea id: description attributes: @@ -16,6 +19,13 @@ body: description: Is your feature request related to a problem? If so, please provide a clear and concise description of the problem; e.g., "I'm always frustrated when [...]." validations: required: true + - type: textarea + id: ai-disclosure + attributes: + label: AI Disclosure + description: How did you use AI to find or write up this issue, if at all? Write "None" if you didn't. + validations: + required: true - type: textarea id: desired-behavior attributes: @@ -36,6 +46,13 @@ body: options: - label: Yes, I have searched existing issues. required: true + - type: checkboxes + id: ai-policy + attributes: + label: AI Policy + options: + - label: I have read the [AI policy](https://github.com/seerr-team/seerr/blob/develop/CONTRIBUTING.md#ai-assistance-notice) and this issue follows it. + required: true - type: checkboxes id: terms attributes: diff --git a/.github/ISSUE_TEMPLATE/maintenance.yml b/.github/ISSUE_TEMPLATE/maintenance.yml index 061d4ec98c..9a7bf553b7 100644 --- a/.github/ISSUE_TEMPLATE/maintenance.yml +++ b/.github/ISSUE_TEMPLATE/maintenance.yml @@ -9,6 +9,9 @@ body: value: | Maintainers / contributors: use this for internal tasks (CI, workflows, tooling, refactors). If you're reporting a user-facing bug or requesting a feature, use the other templates. + + > [!IMPORTANT] + > Our [AI policy](https://github.com/seerr-team/seerr/blob/develop/CONTRIBUTING.md#issues) applies to issues too. Write this issue yourself and disclose any AI use below. Issues that read as unreviewed AI output will be closed and locked. - type: dropdown id: area attributes: @@ -30,6 +33,13 @@ body: description: What needs doing and why? validations: required: true + - type: textarea + id: ai-disclosure + attributes: + label: AI Disclosure + description: How did you use AI to find or write up this issue, if at all? Write "None" if you didn't. + validations: + required: true - type: textarea id: acceptance attributes: @@ -55,6 +65,13 @@ body: options: - label: Yes, I have searched existing issues. required: true + - type: checkboxes + id: ai-policy + attributes: + label: AI Policy + options: + - label: I have read the [AI policy](https://github.com/seerr-team/seerr/blob/develop/CONTRIBUTING.md#ai-assistance-notice) and this issue follows it. + required: true - type: checkboxes id: terms attributes: diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 41a153440f..b7595a039f 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -11,6 +11,11 @@ - Fixes #XXXX +## AI Disclosure + + + + ## How Has This Been Tested? @@ -25,7 +30,6 @@ - [ ] I have read and followed the contribution [guidelines](https://github.com/seerr-team/seerr/blob/develop/CONTRIBUTING.md). -- [ ] Disclosed any use of AI (see our [policy](https://github.com/seerr-team/seerr/blob/develop/CONTRIBUTING.md#ai-assistance-notice)) - [ ] I have updated the documentation accordingly. - [ ] All new and existing tests passed. - [ ] Successful build `pnpm build` diff --git a/.github/cliff.toml b/.github/cliff.toml index 4ddd432b75..ea736e7b82 100644 --- a/.github/cliff.toml +++ b/.github/cliff.toml @@ -27,7 +27,20 @@ body = """ ## [unreleased] {% endif %}\ +{%- set embargoed = commits | filter(attribute="group", value="") | length %} +{%- if version and embargoed > 0 %} +{%- set one = embargoed == 1 %} +{%- set disclosure = timestamp + 3 * 86400 %} +> [!WARNING] +> **This release fixes {% if one %}a security vulnerability{% else %}{{ embargoed }} security vulnerabilities{% endif %}. All users should update to {{ version | trim_start_matches(pat="v") }} as soon as possible.** +> +> To give everyone time to upgrade, full details will be published as {% if one %}a security advisory{% else %}security advisories{% endif %} on **{{ disclosure | date(format="%B %-d, %Y") }}**. Once published, the details will be public, so update now rather than waiting for the {% if one %}advisory{% else %}advisories{% endif %}. +> +> These release notes will be updated with {% if one %}a link to the advisory once it's{% else %}links to the advisories once they're{% endif %} published. +{% endif %} + {%- for group, commits in commits | group_by(attribute="group") %} + {%- if group == "" %}{% continue %}{% endif %} ### {{ group | striptags | trim | upper_first }} {%- for commit in commits | filter(attribute="scope") | sort(attribute="scope") %} {{ self::print_commit(commit=commit) }} @@ -63,6 +76,9 @@ filter_unconventional = true split_commits = false filter_commits = true commit_preprocessors = [ + { pattern = '(?ms)\A.*^Disclosure: embargoed$.*', replace = "security(embargoed): undisclosed fix" }, + { pattern = '(?s)^Merge commit from fork.*?(GHSA(?:-[0-9a-z]{4}){3}).*', replace = "security: Patch [$1](https://github.com/seerr-team/seerr/security/advisories/$1)" }, + { pattern = '(?s)^Merge commit from fork.*', replace = "security(embargoed): undisclosed fix" }, { pattern = '.*\[skip ci\].*', replace = "" }, { pattern = '.*\[ci skip\].*', replace = "" }, ] @@ -70,6 +86,8 @@ commit_parsers = [ { message = '.*\(helm\).*', skip = true }, { message = '^chore\(release\): prepare for', skip = true }, { message = '^chore\(deps.*\)', skip = true }, + { message = '^security\(embargoed\)', group = "" }, + { message = '^security', group = "🛡️ Security" }, { body = ".*security", group = "🛡️ Security" }, { message = "^feat", group = "🚀 Features" }, { message = "^fix", group = "🐛 Bug Fixes" }, diff --git a/.github/renovate.json5 b/.github/renovate.json5 index 8ecd1d4b4e..eb89f482ed 100644 --- a/.github/renovate.json5 +++ b/.github/renovate.json5 @@ -2,6 +2,7 @@ $schema: 'https://docs.renovatebot.com/renovate-schema.json', extends: [ 'config:recommended', + 'mergeConfidence:all-badges', ':dependencyDashboard', ':timezone(UTC)', 'group:allNonMajor', diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index b83aea8ca6..a077347036 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -89,7 +89,12 @@ workflows: - 'actions/checkout@v7.0.1' - 'actions/create-github-app-token@v3.3.0' - 'helm/chart-testing-action@v2.9.0' - '.github/workflows/seerr-labeller.yml': [] + '.github/workflows/scorecard.yml': + - 'actions/checkout@v7.0.1' + - 'github/codeql-action@v4.39.3' + - 'ossf/scorecard-action@v2.6.0' + '.github/workflows/seerr-labeller.yml': + - 'actions/github-script@v9.0.0' '.github/workflows/stale.yml': - 'actions/stale@v11.0.0' '.github/workflows/test-docs.yml': @@ -277,6 +282,11 @@ dependencies: commit: 'sha1-a9a95522b26fe6403f7bb24031f21fb573d0f5ff' owner_id: 24392180 repo_id: 377964066 + 'ossf/scorecard-action@v2.6.0': + ref: 'v2.6.0' + commit: 'sha1-23f22cd43608bae7a1f1fa2603d7314dee9538a5' + owner_id: 67707773 + repo_id: 421101922 'pnpm/action-setup@v6.1.1': ref: 'v6.1.1' commit: 'sha1-73e46992e05b19abd31f2f3c20e0e7370d762115' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 98508b8354..ebaadf7673 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -200,6 +200,13 @@ jobs: - name: Set up Docker Buildx uses: docker/setup-buildx-action@v4.4.1 + - name: Log in to Docker Hardened Images + uses: docker/login-action@v4.8.0 + with: + registry: dhi.io + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_TOKEN_RO }} + - name: Commit timestamp id: ts run: echo "TIMESTAMP=$(git log -1 --pretty=%ct)" >> "$GITHUB_OUTPUT" @@ -241,7 +248,14 @@ jobs: uses: docker/login-action@v4.8.0 with: username: ${{ secrets.DOCKER_USERNAME }} - password: ${{ secrets.DOCKER_TOKEN }} + password: ${{ secrets.DOCKER_TOKEN_RW }} + + - name: Log in to Docker Hardened Images + uses: docker/login-action@v4.8.0 + with: + registry: dhi.io + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_TOKEN_RO }} - name: Log in to GitHub Container Registry uses: docker/login-action@v4.8.0 diff --git a/.github/workflows/preview.yml b/.github/workflows/preview.yml index 28f5961da5..89c86fdb9c 100644 --- a/.github/workflows/preview.yml +++ b/.github/workflows/preview.yml @@ -51,6 +51,13 @@ jobs: echo "version=${VER}" >> "$GITHUB_OUTPUT" echo "Building preview version: ${VER}" + - name: Log in to Docker Hardened Images + uses: docker/login-action@v4.8.0 + with: + registry: dhi.io + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_TOKEN_RO }} + - name: Commit timestamp id: ts run: echo "TIMESTAMP=$(git log -1 --pretty=%ct)" >> "$GITHUB_OUTPUT" @@ -102,7 +109,14 @@ jobs: uses: docker/login-action@v4.8.0 with: username: ${{ secrets.DOCKER_USERNAME }} - password: ${{ secrets.DOCKER_TOKEN }} + password: ${{ secrets.DOCKER_TOKEN_RW }} + + - name: Log in to Docker Hardened Images + uses: docker/login-action@v4.8.0 + with: + registry: dhi.io + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_TOKEN_RO }} - name: Log in to GitHub Container Registry uses: docker/login-action@v4.8.0 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 02305e3aef..1d49648210 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -84,6 +84,13 @@ jobs: - name: Set up Docker Buildx uses: docker/setup-buildx-action@v4.4.1 + - name: Log in to Docker Hardened Images + uses: docker/login-action@v4.8.0 + with: + registry: dhi.io + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_TOKEN_RO }} + - name: Commit timestamp id: ts run: echo "TIMESTAMP=$(git log -1 --pretty=%ct)" >> "$GITHUB_OUTPUT" @@ -128,7 +135,14 @@ jobs: uses: docker/login-action@v4.8.0 with: username: ${{ secrets.DOCKER_USERNAME }} - password: ${{ secrets.DOCKER_TOKEN }} + password: ${{ secrets.DOCKER_TOKEN_RW }} + + - name: Log in to Docker Hardened Images + uses: docker/login-action@v4.8.0 + with: + registry: dhi.io + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_TOKEN_RO }} - name: Log in to GitHub Container Registry uses: docker/login-action@v4.8.0 @@ -222,7 +236,7 @@ jobs: uses: docker/login-action@v4.8.0 with: username: ${{ secrets.DOCKER_USERNAME }} - password: ${{ secrets.DOCKER_TOKEN }} + password: ${{ secrets.DOCKER_TOKEN_RW }} - name: Log in to GitHub Container Registry uses: docker/login-action@v4.8.0 diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml new file mode 100644 index 0000000000..b3df02577f --- /dev/null +++ b/.github/workflows/scorecard.yml @@ -0,0 +1,40 @@ +--- +name: Scorecard supply-chain security + +on: + schedule: + - cron: '0 7 * * *' + push: + branches: + - develop + +permissions: {} + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + analysis: + name: Scorecard analysis + runs-on: ubuntu-26.04 + permissions: + security-events: write + id-token: write + steps: + - name: Checkout code + uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + + - name: Run analysis + uses: ossf/scorecard-action@v2.6.0 + with: + results_file: results.sarif + results_format: sarif + publish_results: true + + - name: Upload to code-scanning + uses: github/codeql-action/upload-sarif@v4.39.3 + with: + sarif_file: results.sarif diff --git a/.github/workflows/seerr-labeller.yml b/.github/workflows/seerr-labeller.yml index 7a4f41d2df..15a36daa5b 100644 --- a/.github/workflows/seerr-labeller.yml +++ b/.github/workflows/seerr-labeller.yml @@ -6,7 +6,7 @@ on: pull_request_target: types: [labeled, unlabeled, reopened] issues: - types: [labeled, unlabeled, reopened] + types: [opened, labeled, unlabeled, reopened] permissions: {} @@ -111,3 +111,140 @@ jobs: run: | gh issue edit "$NUMBER" -R "$GH_REPO" --remove-label "support" || true gh issue unlock "$NUMBER" -R "$GH_REPO" || true + + ai-disclosure: + if: > + github.event_name == 'issues' && + github.event.issue.user.type != 'Bot' && + (github.event.action == 'opened' || + (github.event.action == 'labeled' && github.event.label.name == 'ai-disclosure')) + runs-on: ubuntu-26.04 + concurrency: + group: ai-disclosure-${{ github.event.issue.number }} + permissions: + issues: write + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + NUMBER: ${{ github.event.issue.number }} + ISSUE_AUTHOR: ${{ github.event.issue.user.login }} + steps: + - name: Detect a missing or contradicted AI disclosure + id: detect + if: github.event.action == 'opened' + uses: actions/github-script@v9.0.0 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + result-encoding: string + script: | + const SIGNATURES = [ + 'utm_source=chatgpt.com', + 'Generated with [Claude Code]', + 'chatgpt.com/share/', + 'chat.openai.com/share/', + 'claude.ai/share/', + 'gemini.google.com/share/', + 'g.co/gemini/share/', + 'perplexity.ai/search/', + 'grok.com/share/', + ]; + const TOOLS = /chatgpt|claude|copilot|gemini|gpt|llm|cursor|perplexity|deepseek|grok|translat/i; + const issue = context.payload.issue; + + let permission = 'none'; + try { + const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner: context.repo.owner, + repo: context.repo.repo, + username: issue.user.login, + }); + permission = data.permission; + } catch (e) { + console.log('Could not look up author permission:', e.message); + } + if (['admin', 'write'].includes(permission)) return 'false'; + // issue-template already asks for a new issue through the form + if (!issue.labels.some((l) => l.name === 'awaiting triage')) return 'false'; + + const body = (issue.body ?? '').replace(/\r\n?/g, '\n'); + const match = body.match(/(?:^|\n)### AI Disclosure[ \t]*(?=\n|$)([\s\S]*?)(?=\n### |$)/); + const answer = match ? match[1].trim() : ''; + if (!answer) return 'true'; + return String( + /^(none|no|n\/?a)\b/i.test(answer) && + !TOOLS.test(answer) && + SIGNATURES.some((s) => body.includes(s)) + ); + + - name: Ask for an AI disclosure + if: github.event.action == 'labeled' || steps.detect.outputs.result == 'true' + shell: bash + env: + BODY: > + :wave: @${{ env.ISSUE_AUTHOR }}, issues are a contribution as well, and they fall under our [AI policy](https://github.com/seerr-team/seerr/blob/develop/CONTRIBUTING.md#ai-assistance-notice). + + Please update the AI Disclosure in this issue, or add one if it's missing, to say how you used AI to find or write it up, if at all. Issues must be written in your own words. AI-assisted translation is fine, but please note it. + run: | + retry() { n=0; until "$@"; do n=$((n+1)); [ $n -ge 3 ] && break; echo "retry $n: $*" >&2; sleep 2; done; } + retry gh issue comment "$NUMBER" -R "$GH_REPO" -b "$BODY" || true + + - name: Label the issue + if: steps.detect.outputs.result == 'true' + shell: bash + run: | + retry() { n=0; until "$@"; do n=$((n+1)); [ $n -ge 3 ] && break; echo "retry $n: $*" >&2; sleep 2; done; } + retry gh issue edit "$NUMBER" -R "$GH_REPO" --add-label ai-disclosure || true + + issue-template: + if: > + github.event_name == 'issues' && + github.event.action == 'opened' && + github.event.issue.user.type != 'Bot' + runs-on: ubuntu-26.04 + concurrency: + group: issue-template-${{ github.event.issue.number }} + permissions: + issues: write + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + NUMBER: ${{ github.event.issue.number }} + ISSUE_AUTHOR: ${{ github.event.issue.user.login }} + steps: + - name: Detect an issue opened outside the issue forms + id: detect + uses: actions/github-script@v9.0.0 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + result-encoding: string + script: | + // every form applies it, and GitHub drops labels set by users without push access + const labels = context.payload.issue.labels.map((l) => l.name); + if (labels.includes('awaiting triage')) return 'false'; + + // sender, not author, so issues a maintainer transfers in pass + let permission = 'none'; + try { + const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner: context.repo.owner, + repo: context.repo.repo, + username: context.payload.sender.login, + }); + permission = data.permission; + } catch (e) { + console.log('Could not look up sender permission:', e.message); + } + return String(!['admin', 'write'].includes(permission)); + + - name: Label and comment + if: steps.detect.outputs.result == 'true' + shell: bash + env: + BODY: > + :wave: @${{ env.ISSUE_AUTHOR }}, this issue wasn't opened through one of our issue forms. The forms add the labels and issue type we triage with, along with the required AI Policy and Code of Conduct checkboxes, so issues filed outside them break our [contributing guidelines](https://github.com/seerr-team/seerr/blob/develop/CONTRIBUTING.md#issues). + + Please open a new issue using the form. Issues filed outside the forms may be closed without review. + run: | + retry() { n=0; until "$@"; do n=$((n+1)); [ $n -ge 3 ] && break; echo "retry $n: $*" >&2; sleep 2; done; } + retry gh issue edit "$NUMBER" -R "$GH_REPO" --add-label "blocked:template" || true + retry gh issue comment "$NUMBER" -R "$GH_REPO" -b "$BODY" || true diff --git a/.husky/commit-msg b/.husky/commit-msg index 522117da14..6c5d855926 100755 --- a/.husky/commit-msg +++ b/.husky/commit-msg @@ -1 +1,7 @@ [ -n "$HUSKY_BYPASS" ] || npx commitlint --edit $1 + +ghsa=$(git remote get-url origin 2>/dev/null | sed -nE 's#.*/seerr-ghsa-([0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4})(\.git)?$#GHSA-\1#p') +if [ -z "$HUSKY_BYPASS" ] && [ -n "$ghsa" ] && ! sed '1d;/^#/d' "$1" | grep -qE "$ghsa|^Disclosure: embargoed$"; then + echo "Name $ghsa in the commit body, as the advisory merge keeps only the body. Add 'Disclosure: embargoed' to hold the details for 3 days instead." >&2 + exit 1 +fi diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 879f57239a..7c9a55ae5b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,6 +20,8 @@ Depending on maintainer availability and how much review a change needs, it can > [!IMPORTANT] > +> Issues and comments are contributions as well, and this policy covers them. +> > AI-driven contributions are not allowed and will be rejected, even if you reviewed and tested them. This is an open-source project maintained by volunteers, and our time goes to reviewing your work, not your AI's. We have no issue with contributors using AI tools as an aid, but the contribution has to be yours, and it is your responsibility to make sure it meets our quality standards. > > **We expect AI-assisted development, not AI-driven development.** Use AI as a tool to help you understand the codebase, debug, or scaffold something you then write yourself. If an AI wrote the change, reviewing it, testing it, and submitting it yourself does not make it AI-assisted. The approach and the implementation have to be yours, and you have to understand every line of it. Whether a PR is AI-assisted or AI-driven is the maintainers' call, based on how the contribution reads and how you handle review, and claiming you drove it doesn't override that. We have been increasingly receiving low-effort, fully AI-generated PRs and will not tolerate them. Contributors who repeatedly submit AI-driven work may be banned. @@ -37,13 +39,21 @@ Depending on maintainer availability and how much review a change needs, it can > **Read and follow the [Contributing Guide](CONTRIBUTING.md) before submitting.** > If your AI tool generates its own PR description format, it is your responsibility to rewrite it to follow our template before submitting, and rewrite means write the content yourself, not relabel the AI's output under our section headers. An incomplete PR template tells maintainers that insufficient review has been performed on the submission, regardless of the actual code quality. We may close such PRs without review. > -> If you are using **any kind of AI assistance** to contribute to Seerr, it must be disclosed in the pull request. +> If you are using **any kind of AI assistance** to contribute to Seerr, it must be disclosed in the pull request or issue. + +### Issues + +Write your issue yourself, using the issue form. Bypassing the form breaks this policy on its own. Moving AI output under the form's headings doesn't count as filling it in. + +For bug reports, describe what happened, how to reproduce it, your logs and your setup. Don't include a root cause or diagnosis that came from AI, as that's where wrong details creep in. If you found the cause yourself and understand it, put it under Additional Context. + +AI-generated issues will be closed and locked. ### Disclosure Requirements -If you are using any kind of AI assistance while contributing to Seerr, **this must be disclosed in the pull request description**, along with the extent to which AI assistance was used (e.g., docs only vs. code generation). +If you are using any kind of AI assistance while contributing to Seerr, **this must be disclosed in the AI Disclosure section of your pull request or issue**, along with the extent to which AI assistance was used (e.g., docs only vs. code generation). -PR responses (comments, review replies) must be written in your own words, per the Expectations below. The one exception is AI-assisted translation, if you use AI to translate a response into English, disclose that here too. +Issue comments and PR responses (comments, review replies) must be written in your own words, per the Expectations below. The one exception is AI-assisted translation, if you use AI to translate a response into English, disclose that here too. As a small exception, trivial tab-completion doesn't need to be disclosed, so long as it is limited to single keywords or short phrases. diff --git a/Dockerfile b/Dockerfile index 33187c2844..e619e57c50 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM node:22.23.5-alpine3.23@sha256:6868d4695b947ee120bffaa463fecd68cde370d7bfec92955e7c8ac576b4f475 AS base +FROM dhi.io/node:22-alpine3.24-dev@sha256:31a9f092cdf2d7e2eddebf5d80494341daa7efe344f6f5aebce01a5b19ad9944 AS base ARG SOURCE_DATE_EPOCH ARG TARGETPLATFORM ENV TARGETPLATFORM=${TARGETPLATFORM:-linux/amd64} @@ -7,7 +7,7 @@ ENV PNPM_HOME="/pnpm" ENV PATH="$PNPM_HOME:$PATH" RUN corepack enable -COPY . ./app +COPY . /app WORKDIR /app FROM base AS prod-deps @@ -25,10 +25,9 @@ ENV COMMIT_TAG=${COMMIT_TAG} RUN \ case "${TARGETPLATFORM}" in \ - 'linux/arm64' | 'linux/arm/v7') \ + 'linux/arm64') \ apk update && \ - apk add --no-cache python3 make g++ gcc libc6-compat bash && \ - npm install --global node-gyp \ + apk add --no-cache python3 make g++ gcc libc6-compat bash \ ;; \ esac @@ -36,13 +35,13 @@ RUN --mount=type=cache,id=pnpm,target=/pnpm/store CYPRESS_INSTALL_BINARY=0 pnpm RUN pnpm build -FROM node:22.23.5-alpine3.23@sha256:6868d4695b947ee120bffaa463fecd68cde370d7bfec92955e7c8ac576b4f475 +FROM dhi.io/node:22-alpine3.24-dev@sha256:31a9f092cdf2d7e2eddebf5d80494341daa7efe344f6f5aebce01a5b19ad9944 ARG SOURCE_DATE_EPOCH ARG COMMIT_TAG ENV NODE_ENV=production ENV COMMIT_TAG=${COMMIT_TAG} -RUN apk add --no-cache tzdata +RUN apk add --no-cache tzdata && chown node:node /app USER node:node diff --git a/bin/check-pr-template.mjs b/bin/check-pr-template.mjs index 2362fc2a3b..bf24c4a185 100644 --- a/bin/check-pr-template.mjs +++ b/bin/check-pr-template.mjs @@ -13,7 +13,7 @@ if (!bodyFile) { process.exit(2); } -const body = readFileSync(resolve(bodyFile), 'utf8'); +const body = readFileSync(resolve(bodyFile), 'utf8').replace(/\r\n?/g, '\n'); const issues = []; const MAINTAINER_PERMISSIONS = ['admin', 'write']; @@ -33,7 +33,9 @@ const stripComments = (s) => { const stripFixesPlaceholder = (s) => s.replace(/-\s*Fixes\s*`?#XXXX`?/gi, ''); -const descriptionMatch = body.match(/## Description\s*\n([\s\S]*?)(?=\n## |$)/); +const descriptionMatch = body.match( + /(?:^|\n) {0,3}## Description[ \t]*(?=\n|$)([\s\S]*?)(?=\n {0,3}## |$)/ +); const descriptionContent = descriptionMatch ? stripFixesPlaceholder(stripComments(descriptionMatch[1])).trim() : ''; @@ -45,7 +47,7 @@ if (!descriptionContent) { } const testingMatch = body.match( - /## How Has This Been Tested\?\s*\n([\s\S]*?)(?=\n## |$)/ + /(?:^|\n) {0,3}## How Has This Been Tested\?[ \t]*(?=\n|$)([\s\S]*?)(?=\n {0,3}## |$)/ ); const testingContent = testingMatch ? stripComments(testingMatch[1]).trim() @@ -55,7 +57,9 @@ if (!testingContent) { issues.push('**How Has This Been Tested?** section is empty.'); } -const checklistMatch = body.match(/## Checklist:\s*\n([\s\S]*?)$/); +const checklistMatch = body.match( + /(?:^|\n) {0,3}## Checklist:[ \t]*\n([\s\S]*?)$/ +); const checklistContent = checklistMatch ? checklistMatch[1] : ''; const totalBoxes = (checklistContent.match(/- \[[ x]\]/gi) || []).length; @@ -75,11 +79,17 @@ if ( issues.push('The **contribution guidelines** checkbox has not been checked.'); } -if ( - !isMaintainer && - !/- \[x\] Disclosed any use of AI/i.test(checklistContent) -) { - issues.push('The **AI disclosure** checkbox has not been checked.'); +const aiMatch = body.match( + /(?:^|\n) {0,3}## AI Disclosure[ \t]*(?=\n|$)([\s\S]*?)(?=\n {0,3}## |$)/ +); +const aiContent = aiMatch ? stripComments(aiMatch[1]).trim() : ''; +const legacyAiBox = + !aiMatch && /- \[x\] Disclosed any use of AI/i.test(checklistContent); + +if (!isMaintainer && !aiContent && !legacyAiBox) { + issues.push( + '**AI Disclosure** section is empty. Describe how you used AI, or write "None".' + ); } if (/-\s*Fixes\s*`?#XXXX`?/i.test(body)) { diff --git a/server/entity/Media.ts b/server/entity/Media.ts index 3709e363e1..abbcf4863c 100644 --- a/server/entity/Media.ts +++ b/server/entity/Media.ts @@ -212,6 +212,27 @@ class Media { @Column({ nullable: true, type: 'varchar' }) public ratingKey4k?: string | null; + @Column({ + type: 'text', + nullable: true, + transformer: { + from: (value: string | null): string[] | null => { + if (value == null) { + return null; + } + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed : null; + } catch { + return null; + } + }, + to: (value: string[] | null): string | null => + value == null ? null : JSON.stringify(value), + }, + }) + public plexRatingKeys?: string[] | null; + @Column({ nullable: true, type: 'varchar' }) public jellyfinMediaId?: string | null; @@ -237,6 +258,36 @@ class Media { Object.assign(this, init); } + public addPlexRatingKey(ratingKey?: string | null): boolean { + if (!ratingKey) { + return false; + } + + const keys = this.getPlexRatingKeys(); + if (keys.includes(ratingKey)) { + if (this.plexRatingKeys != null) { + return false; + } + this.plexRatingKeys = keys; + return true; + } + + this.plexRatingKeys = [...keys, ratingKey]; + return true; + } + + public getPlexRatingKeys(): string[] { + if (this.plexRatingKeys) { + return this.plexRatingKeys; + } + + return [ + ...new Set( + [this.ratingKey, this.ratingKey4k].filter((key): key is string => !!key) + ), + ]; + } + public resetServiceData(is4k?: boolean): void { if (is4k === undefined || !is4k) { this.serviceId = null; @@ -252,6 +303,9 @@ class Media { this.ratingKey4k = null; this.jellyfinMediaId4k = null; } + if (is4k === undefined) { + this.plexRatingKeys = null; + } } @AfterLoad() diff --git a/server/lib/availabilitySync.test.ts b/server/lib/availabilitySync.test.ts index 7e861e38c5..46a23f7778 100644 --- a/server/lib/availabilitySync.test.ts +++ b/server/lib/availabilitySync.test.ts @@ -90,11 +90,27 @@ Object.defineProperty(JellyfinAPI.prototype, 'setUserId', { }); // --- Mock PlexAPI --- +function plexNotFoundError(): Error & { response: { status: number } } { + return Object.assign(new Error('Request failed with status code 404'), { + response: { status: 404 }, + isAxiosError: true, + toJSON: () => ({}), + name: 'AxiosError', + }); +} + +function rethrowPlexTestError(error: unknown): never { + if (error instanceof Error && error.message === '404') { + throw plexNotFoundError(); + } + throw error; +} + let getMetadataImpl: ( key: string, options?: { includeChildren?: boolean } ) => Promise = async () => { - throw new Error('404'); + throw plexNotFoundError(); }; let getChildrenMetadataImpl: ( key: string @@ -102,8 +118,13 @@ let getChildrenMetadataImpl: ( Object.defineProperty(PlexAPI.prototype, 'getMetadata', { get() { - return async (key: string, options?: { includeChildren?: boolean }) => - getMetadataImpl(key, options); + return async (key: string, options?: { includeChildren?: boolean }) => { + try { + return await getMetadataImpl(key, options); + } catch (error) { + rethrowPlexTestError(error); + } + }; }, set() {}, configurable: true, @@ -111,7 +132,13 @@ Object.defineProperty(PlexAPI.prototype, 'getMetadata', { Object.defineProperty(PlexAPI.prototype, 'getChildrenMetadata', { get() { - return async (key: string) => getChildrenMetadataImpl(key); + return async (key: string) => { + try { + return await getChildrenMetadataImpl(key); + } catch (error) { + rethrowPlexTestError(error); + } + }; }, set() {}, configurable: true, @@ -394,6 +421,38 @@ function fakePlexEpisodes(count: number): PlexMetadata[] { })); } +function fakePlex4kEpisodes(count: number): PlexMetadata[] { + return Array.from({ length: count }, (_, i) => ({ + ratingKey: `ep4k-${i}`, + guid: `plex://episode/ep4k-${i}`, + type: 'movie' as const, + title: `Episode ${i + 1}`, + Guid: [], + index: i + 1, + leafCount: 0, + viewedLeafCount: 0, + addedAt: 0, + updatedAt: 0, + Media: [ + { + id: i, + duration: 2400, + bitrate: 20000, + width: 3840, + height: 2160, + aspectRatio: 1.78, + audioChannels: 6, + audioCodec: 'eac3', + videoCodec: 'hevc', + videoResolution: '4k', + container: 'mkv', + videoFrameRate: '24p', + videoProfile: 'main 10', + }, + ], + })); +} + function fakePlexShow(ratingKey: string): PlexMetadata { return { ratingKey, @@ -953,6 +1012,95 @@ describe('AvailabilitySync', () => { 'Show should be PARTIALLY_AVAILABLE when some seasons are available and some are unknown' ); }); + + it('should not probe or clear retained Plex rating keys during a Jellyfin sync', async () => { + configureJellyfin(); + configureSonarr([{ syncEnabled: true }]); + + const mediaRepository = getRepository(Media); + const media = new Media(); + media.tmdbId = 1413; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.jellyfinMediaId = 'jellyfin-retain-plex-id'; + media.ratingKey = 'retained-plex-rk'; + media.plexRatingKeys = ['retained-plex-rk']; + media.externalServiceId = 413; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }), + ]; + await mediaRepository.save(media); + + let plexMetadataCalls = 0; + getMetadataImpl = async () => { + plexMetadataCalls += 1; + throw new Error('404'); + }; + + getItemDataImpl = async (id: string) => { + if (id === 'jellyfin-retain-plex-id') { + return fakeJellyfinShow('jellyfin-retain-plex-id', '1413'); + } + return undefined; + }; + + getSeasonsImpl = async (seriesID: string) => { + if (seriesID === 'jellyfin-retain-plex-id') { + return [fakeJellyfinSeason(1, 'jellyfin-retain-plex-s1-id')]; + } + return []; + }; + + getEpisodesImpl = async (_seriesID: string, seasonID: string) => { + if (seasonID === 'jellyfin-retain-plex-s1-id') { + return fakeJellyfinEpisodes(10); + } + return []; + }; + + getSeriesByIdImpl = async (id: number) => { + if (id === 413) { + return { + tvdbId: 1413, + id: 413, + title: 'Retained Plex Keys', + titleSlug: 'retained-plex-keys', + monitored: true, + statistics: { + episodeFileCount: 10, + totalEpisodeCount: 10, + episodeCount: 10, + percentOfEpisodes: 100, + sizeOnDisk: 0, + seasonCount: 1, + }, + seasons: fakeSonarrSeasons(1, { 1: 10 }), + } as unknown as SonarrSeries; + } + throw new Error('404'); + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 1413 }, + relations: ['seasons'], + }); + + assert.strictEqual( + plexMetadataCalls, + 0, + 'Jellyfin sync must not probe Plex for retained rating keys' + ); + assert.deepStrictEqual(updated.plexRatingKeys, ['retained-plex-rk']); + assert.strictEqual(updated.ratingKey, 'retained-plex-rk'); + assert.strictEqual(updated.status, MediaStatus.AVAILABLE); + assert.strictEqual(updated.seasons[0].status, MediaStatus.AVAILABLE); + }); }); describe('TV season availability - Plex', () => { @@ -1000,7 +1148,7 @@ describe('AvailabilitySync', () => { if (key === 'plex-house-s6-rk') { return fakePlexEpisodes(21); } - return []; + return undefined as unknown as PlexMetadata[]; }; // Sonarr: only season 6 has files @@ -1303,150 +1451,565 @@ describe('AvailabilitySync', () => { 'Show should be PARTIALLY_AVAILABLE after season removal' ); }); - }); - describe('movie availability - Radarr', () => { - it('should mark a deleted movie as DELETED when a second standard Radarr instance has a colliding externalServiceId', async () => { + it('should not mark seasons DELETED when a show is split across a 1080p and a 4K Plex library', async () => { configurePlex(); - configureRadarr([{ syncEnabled: true }, { syncEnabled: true }]); + // No Sonarr configured for this user: only Plex is the source of truth. + const settings = getSettings(); + settings.sonarr = []; + settings.radarr = []; const mediaRepository = getRepository(Media); const media = new Media(); - media.tmdbId = 5000; - media.mediaType = MediaType.MOVIE; + media.tmdbId = 2010; + media.mediaType = MediaType.TV; media.status = MediaStatus.AVAILABLE; - media.ratingKey = 'gone-from-plex-rk'; - media.externalServiceId = 300; - media.serviceId = 0; + // Season 1 lives in the 1080p Plex library, S2-S4 live in the 4K + // Plex library. Simulate the 4K copy scanning last and taking + // ratingKey; both keys must still be checked. + media.ratingKey = 'plex-split-4k-rk'; + media.ratingKey4k = 'plex-split-4k-rk'; + media.plexRatingKeys = ['plex-split-1080p-rk', 'plex-split-4k-rk']; + media.seasons = []; + + for (let i = 1; i <= 4; i++) { + media.seasons.push( + new Season({ + seasonNumber: i, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }) + ); + } await mediaRepository.save(media); - // Probed once per standard instance with the same id (300): origin 404s - // (deleted); the other instance has a different movie at 300. - let radarrCall = 0; - getMovieImpl = async (id: number) => { - if (id !== 300) { - throw new Error('404'); + getMetadataImpl = async (key: string) => { + if (key === 'plex-split-1080p-rk') { + return fakePlexShow('plex-split-1080p-rk'); } - radarrCall += 1; - if (radarrCall === 1) { - throw new Error('404'); + if (key === 'plex-split-4k-rk') { + return fakePlexShow('plex-split-4k-rk'); } - return { - id: 300, - tmdbId: 999999, - title: 'Unrelated Colliding Movie', - hasFile: true, - } as unknown as RadarrMovie; + throw new Error('404'); + }; + + getChildrenMetadataImpl = async (key: string) => { + if (key === 'plex-split-1080p-rk') { + return [fakePlexSeason(1, 'plex-split-1080p-s1-rk')]; + } + if (key === 'plex-split-4k-rk') { + return [ + fakePlexSeason(2, 'plex-split-4k-s2-rk'), + fakePlexSeason(3, 'plex-split-4k-s3-rk'), + fakePlexSeason(4, 'plex-split-4k-s4-rk'), + ]; + } + if (key === 'plex-split-1080p-s1-rk') { + return fakePlexEpisodes(10); + } + if ( + key === 'plex-split-4k-s2-rk' || + key === 'plex-split-4k-s3-rk' || + key === 'plex-split-4k-s4-rk' + ) { + return fakePlex4kEpisodes(10); + } + return []; }; await availabilitySync.run(); const updated = await mediaRepository.findOneOrFail({ - where: { tmdbId: 5000 }, + where: { tmdbId: 2010 }, + relations: ['seasons'], }); + for (const season of updated.seasons) { + assert.notStrictEqual( + season.status, + MediaStatus.DELETED, + `Season ${season.seasonNumber} should not be DELETED` + ); + assert.strictEqual( + season.status, + MediaStatus.AVAILABLE, + `Season ${season.seasonNumber} should remain AVAILABLE` + ); + } + assert.strictEqual( updated.status, - MediaStatus.DELETED, - 'Movie deleted from its origin instance and Plex must not be kept alive by a colliding externalServiceId on another standard instance' + MediaStatus.AVAILABLE, + 'Show should remain AVAILABLE' ); }); - }); - - describe('movie availability - Plex 4K detection', () => { - function fakePlexMovie(ratingKey: string, widths: number[]): PlexMetadata { - return { - ratingKey, - guid: `plex://movie/${ratingKey}`, - type: 'movie', - title: 'Test Movie', - Guid: [], - index: 1, - leafCount: 0, - viewedLeafCount: 0, - addedAt: 0, - updatedAt: 0, - Media: widths.map((width, i) => ({ - id: i, - duration: 7200, - bitrate: 20000, - width, - height: width >= 2000 ? 2160 : 1080, - aspectRatio: 1.78, - audioChannels: 6, - audioCodec: 'eac3', - videoCodec: width >= 2000 ? 'hevc' : 'h264', - videoResolution: width >= 2000 ? '4k' : '1080', - container: 'mkv', - videoFrameRate: '24p', - videoProfile: 'main 10', - })), - }; - } - it('should keep the 4K status when both statuses share a Plex item that has a 4K version (merged versions)', async () => { + it('should still mark seasons DELETED when neither rating key contains them (legacy single-ratingKey)', async () => { configurePlex(); - configureRadarr([ - { syncEnabled: true }, - { is4k: true, syncEnabled: true }, - ]); + const settings = getSettings(); + settings.sonarr = []; + settings.radarr = []; const mediaRepository = getRepository(Media); - // The Plex scanner writes the same rating key to both versions of a - // merged item, and a prior deletion left no externalServiceId4k to - // query, so retention rides on the Plex check alone. const media = new Media(); - media.tmdbId = 687163; - media.mediaType = MediaType.MOVIE; + media.tmdbId = 2011; + media.mediaType = MediaType.TV; media.status = MediaStatus.AVAILABLE; - media.status4k = MediaStatus.AVAILABLE; - media.ratingKey = 'merged-versions-rk'; - media.ratingKey4k = 'merged-versions-rk'; + // Only the primary rating key is set (no ratingKey4k), exercising + // the secondary-lookup branch when the fallback has nothing to find. + media.ratingKey = 'plex-legacy-rk'; + media.seasons = []; + + for (let i = 1; i <= 4; i++) { + media.seasons.push( + new Season({ + seasonNumber: i, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }) + ); + } + await mediaRepository.save(media); getMetadataImpl = async (key: string) => { - if (key === 'merged-versions-rk') { - return fakePlexMovie('merged-versions-rk', [1920, 3840]); + if (key === 'plex-legacy-rk') { + return fakePlexShow('plex-legacy-rk'); } throw new Error('404'); }; + getChildrenMetadataImpl = async (key: string) => { + if (key === 'plex-legacy-rk') { + return [fakePlexSeason(2, 'plex-legacy-s2-rk')]; + } + if (key === 'plex-legacy-s2-rk') { + return fakePlexEpisodes(10); + } + return []; + }; + await availabilitySync.run(); const updated = await mediaRepository.findOneOrFail({ - where: { tmdbId: 687163 }, + where: { tmdbId: 2011 }, + relations: ['seasons'], }); + const s2 = updated.seasons.find((s) => s.seasonNumber === 2); assert.strictEqual( - updated.status4k, + s2?.status, MediaStatus.AVAILABLE, - 'A 4K version present on the media server must prevent 4K removal even when both statuses share one rating key' + 'Season 2 should remain AVAILABLE' ); + + for (const season of updated.seasons) { + if (season.seasonNumber !== 2) { + assert.strictEqual( + season.status, + MediaStatus.DELETED, + `Season ${season.seasonNumber} should be DELETED` + ); + } + } + assert.strictEqual( updated.status, - MediaStatus.AVAILABLE, - 'The non-4K status must be unaffected' + MediaStatus.PARTIALLY_AVAILABLE, + 'Show should be PARTIALLY_AVAILABLE after season removal' ); }); - it('should still remove a stale 4K status when the shared Plex item has no 4K version', async () => { + it('should drop a stored Plex rating key when Plex returns 404 for it', async () => { configurePlex(); - configureRadarr([ - { syncEnabled: true }, - { is4k: true, syncEnabled: true }, - ]); + const settings = getSettings(); + settings.sonarr = []; + settings.radarr = []; const mediaRepository = getRepository(Media); - const media = new Media(); - media.tmdbId = 687164; - media.mediaType = MediaType.MOVIE; + media.tmdbId = 2012; + media.mediaType = MediaType.TV; media.status = MediaStatus.AVAILABLE; - media.status4k = MediaStatus.AVAILABLE; - media.ratingKey = 'stale-4k-rk'; + media.ratingKey = 'plex-dead-rk'; + media.ratingKey4k = 'plex-dead-rk'; + media.plexRatingKeys = ['plex-dead-rk', 'plex-live-rk']; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }), + ]; + await mediaRepository.save(media); + + getMetadataImpl = async (key: string) => { + if (key === 'plex-live-rk') { + return fakePlexShow('plex-live-rk'); + } + throw new Error('404'); + }; + + getChildrenMetadataImpl = async (key: string) => { + if (key === 'plex-live-rk') { + return [fakePlexSeason(1, 'plex-live-s1-rk')]; + } + if (key === 'plex-live-s1-rk') { + return fakePlexEpisodes(10); + } + return []; + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 2012 }, + relations: ['seasons'], + }); + + assert.deepStrictEqual(updated.plexRatingKeys?.sort(), ['plex-live-rk']); + assert.strictEqual(updated.seasons[0].status, MediaStatus.AVAILABLE); + assert.strictEqual(updated.ratingKey, 'plex-dead-rk'); + assert.strictEqual(updated.ratingKey4k, 'plex-dead-rk'); + }); + + it('should clear deep-link keys and plexRatingKeys when the last stored key 404s', async () => { + configurePlex(); + const settings = getSettings(); + settings.sonarr = []; + settings.radarr = []; + + const mediaRepository = getRepository(Media); + const media = new Media(); + media.tmdbId = 2014; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.ratingKey = 'plex-only-dead-rk'; + media.plexRatingKeys = ['plex-only-dead-rk']; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }), + ]; + await mediaRepository.save(media); + + getMetadataImpl = async () => { + throw new Error('404'); + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 2014 }, + relations: ['seasons'], + }); + + assert.deepStrictEqual(updated.plexRatingKeys, []); + assert.strictEqual(updated.ratingKey, null); + assert.strictEqual(updated.seasons[0].status, MediaStatus.DELETED); + assert.strictEqual(updated.status, MediaStatus.DELETED); + }); + + it('should keep seasons when one rating key errors even if another key lacks them', async () => { + configurePlex(); + const settings = getSettings(); + settings.sonarr = []; + settings.radarr = []; + + const mediaRepository = getRepository(Media); + const media = new Media(); + media.tmdbId = 2015; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.ratingKey = 'plex-live-partial-rk'; + media.plexRatingKeys = ['plex-error-rk', 'plex-live-partial-rk']; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }), + new Season({ + seasonNumber: 2, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }), + ]; + await mediaRepository.save(media); + + getMetadataImpl = async (key: string) => { + if (key === 'plex-error-rk') { + throw new Error('ECONNRESET'); + } + if (key === 'plex-live-partial-rk') { + return fakePlexShow('plex-live-partial-rk'); + } + throw new Error('404'); + }; + + getChildrenMetadataImpl = async (key: string) => { + if (key === 'plex-live-partial-rk') { + return [fakePlexSeason(1, 'plex-live-partial-s1-rk')]; + } + if (key === 'plex-live-partial-s1-rk') { + return fakePlexEpisodes(10); + } + return []; + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 2015 }, + relations: ['seasons'], + }); + const s1 = updated.seasons.find((s) => s.seasonNumber === 1); + const s2 = updated.seasons.find((s) => s.seasonNumber === 2); + + assert.strictEqual(s1?.status, MediaStatus.AVAILABLE); + assert.strictEqual(s2?.status, MediaStatus.AVAILABLE); + assert.strictEqual(updated.status, MediaStatus.AVAILABLE); + assert.deepStrictEqual( + updated.plexRatingKeys?.slice().sort(), + ['plex-error-rk', 'plex-live-partial-rk'].sort() + ); + }); + + it('should fail open when Plex returns a non-404 error for a stored rating key', async () => { + configurePlex(); + const settings = getSettings(); + settings.sonarr = []; + settings.radarr = []; + + const mediaRepository = getRepository(Media); + const media = new Media(); + media.tmdbId = 2013; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.ratingKey = 'plex-error-rk'; + media.plexRatingKeys = ['plex-error-rk']; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }), + ]; + await mediaRepository.save(media); + + getMetadataImpl = async () => { + throw new Error('ECONNRESET'); + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 2013 }, + relations: ['seasons'], + }); + + assert.strictEqual(updated.seasons[0].status, MediaStatus.AVAILABLE); + assert.strictEqual(updated.status, MediaStatus.AVAILABLE); + assert.deepStrictEqual(updated.plexRatingKeys, ['plex-error-rk']); + }); + + it('should treat an empty successful Plex metadata response as unverified, not missing', async () => { + configurePlex(); + const settings = getSettings(); + settings.sonarr = []; + settings.radarr = []; + + const mediaRepository = getRepository(Media); + const media = new Media(); + media.tmdbId = 2016; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.ratingKey = 'plex-empty-meta-rk'; + media.plexRatingKeys = ['plex-empty-meta-rk']; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }), + ]; + await mediaRepository.save(media); + + getMetadataImpl = async () => undefined as unknown as PlexMetadata; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 2016 }, + relations: ['seasons'], + }); + + assert.strictEqual( + updated.status, + MediaStatus.AVAILABLE, + 'Empty successful Metadata must not mark the show deleted' + ); + assert.strictEqual( + updated.seasons[0].status, + MediaStatus.AVAILABLE, + 'Empty successful Metadata must not mark seasons deleted' + ); + assert.deepStrictEqual( + updated.plexRatingKeys, + ['plex-empty-meta-rk'], + 'Empty successful Metadata must not drop the rating key' + ); + assert.strictEqual(updated.ratingKey, 'plex-empty-meta-rk'); + }); + }); + + describe('movie availability - Radarr', () => { + it('should mark a deleted movie as DELETED when a second standard Radarr instance has a colliding externalServiceId', async () => { + configurePlex(); + configureRadarr([{ syncEnabled: true }, { syncEnabled: true }]); + + const mediaRepository = getRepository(Media); + + const media = new Media(); + media.tmdbId = 5000; + media.mediaType = MediaType.MOVIE; + media.status = MediaStatus.AVAILABLE; + media.ratingKey = 'gone-from-plex-rk'; + media.externalServiceId = 300; + media.serviceId = 0; + + await mediaRepository.save(media); + + // Probed once per standard instance with the same id (300): origin 404s + // (deleted); the other instance has a different movie at 300. + let radarrCall = 0; + getMovieImpl = async (id: number) => { + if (id !== 300) { + throw new Error('404'); + } + radarrCall += 1; + if (radarrCall === 1) { + throw new Error('404'); + } + return { + id: 300, + tmdbId: 999999, + title: 'Unrelated Colliding Movie', + hasFile: true, + } as unknown as RadarrMovie; + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 5000 }, + }); + + assert.strictEqual( + updated.status, + MediaStatus.DELETED, + 'Movie deleted from its origin instance and Plex must not be kept alive by a colliding externalServiceId on another standard instance' + ); + }); + }); + + describe('movie availability - Plex 4K detection', () => { + function fakePlexMovie(ratingKey: string, widths: number[]): PlexMetadata { + return { + ratingKey, + guid: `plex://movie/${ratingKey}`, + type: 'movie', + title: 'Test Movie', + Guid: [], + index: 1, + leafCount: 0, + viewedLeafCount: 0, + addedAt: 0, + updatedAt: 0, + Media: widths.map((width, i) => ({ + id: i, + duration: 7200, + bitrate: 20000, + width, + height: width >= 2000 ? 2160 : 1080, + aspectRatio: 1.78, + audioChannels: 6, + audioCodec: 'eac3', + videoCodec: width >= 2000 ? 'hevc' : 'h264', + videoResolution: width >= 2000 ? '4k' : '1080', + container: 'mkv', + videoFrameRate: '24p', + videoProfile: 'main 10', + })), + }; + } + + it('should keep the 4K status when both statuses share a Plex item that has a 4K version (merged versions)', async () => { + configurePlex(); + configureRadarr([ + { syncEnabled: true }, + { is4k: true, syncEnabled: true }, + ]); + + const mediaRepository = getRepository(Media); + + // The Plex scanner writes the same rating key to both versions of a + // merged item, and a prior deletion left no externalServiceId4k to + // query, so retention rides on the Plex check alone. + const media = new Media(); + media.tmdbId = 687163; + media.mediaType = MediaType.MOVIE; + media.status = MediaStatus.AVAILABLE; + media.status4k = MediaStatus.AVAILABLE; + media.ratingKey = 'merged-versions-rk'; + media.ratingKey4k = 'merged-versions-rk'; + await mediaRepository.save(media); + + getMetadataImpl = async (key: string) => { + if (key === 'merged-versions-rk') { + return fakePlexMovie('merged-versions-rk', [1920, 3840]); + } + throw new Error('404'); + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 687163 }, + }); + + assert.strictEqual( + updated.status4k, + MediaStatus.AVAILABLE, + 'A 4K version present on the media server must prevent 4K removal even when both statuses share one rating key' + ); + assert.strictEqual( + updated.status, + MediaStatus.AVAILABLE, + 'The non-4K status must be unaffected' + ); + }); + + it('should still remove a stale 4K status when the shared Plex item has no 4K version', async () => { + configurePlex(); + configureRadarr([ + { syncEnabled: true }, + { is4k: true, syncEnabled: true }, + ]); + + const mediaRepository = getRepository(Media); + + const media = new Media(); + media.tmdbId = 687164; + media.mediaType = MediaType.MOVIE; + media.status = MediaStatus.AVAILABLE; + media.status4k = MediaStatus.AVAILABLE; + media.ratingKey = 'stale-4k-rk'; media.ratingKey4k = 'stale-4k-rk'; await mediaRepository.save(media); @@ -1546,6 +2109,40 @@ describe('AvailabilitySync', () => { ); }); + it('should keep 4K movie availability in Plex after the last 4K Radarr server is removed', async () => { + configurePlex(); + configureRadarr([{ syncEnabled: true }]); + + const mediaRepository = getRepository(Media); + + const media = new Media(); + media.tmdbId = 687180; + media.mediaType = MediaType.MOVIE; + media.status = MediaStatus.UNKNOWN; + media.status4k = MediaStatus.AVAILABLE; + media.ratingKey4k = 'orphan-4k-rk'; + await mediaRepository.save(media); + + getMetadataImpl = async (key: string) => { + if (key === 'orphan-4k-rk') { + return fakePlexMovie('orphan-4k-rk', [3840]); + } + throw new Error('404'); + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 687180 }, + }); + + assert.strictEqual( + updated.status4k, + MediaStatus.AVAILABLE, + 'Removing the last 4K Radarr server must not delete a 4K movie that still exists in Plex' + ); + }); + it('should remove the non-4K status when the shared Plex item only has a 4K version left', async () => { configurePlex(); configureRadarr([ @@ -2032,6 +2629,270 @@ describe('AvailabilitySync', () => { assert.strictEqual(updated.status, MediaStatus.AVAILABLE); assert.strictEqual(s1?.status, MediaStatus.AVAILABLE); }); + + it('should keep non-4K show availability when one season is 4K-only and another episode fetch fails', async () => { + configurePlex(); + configureSonarr([ + { syncEnabled: true }, + { is4k: true, syncEnabled: true }, + ]); + + const mediaRepository = getRepository(Media); + + const media = new Media(); + media.tmdbId = 687181; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.status4k = MediaStatus.AVAILABLE; + media.ratingKey = 'partial-error-show-rk'; + media.ratingKey4k = 'partial-error-show-rk'; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.AVAILABLE, + }), + new Season({ + seasonNumber: 2, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.AVAILABLE, + }), + ]; + await mediaRepository.save(media); + + getMetadataImpl = async (key: string) => { + if (key === 'partial-error-show-rk') { + return fakePlexShow('partial-error-show-rk'); + } + throw new Error('404'); + }; + + getChildrenMetadataImpl = async (key: string) => { + if (key === 'partial-error-show-rk') { + return [fakePlexSeason(1, 'pe-s1-rk'), fakePlexSeason(2, 'pe-s2-rk')]; + } + if (key === 'pe-s1-rk') { + return [fakeVersionedEpisode('pe-s1-e1', [3840])]; + } + if (key === 'pe-s2-rk') { + throw new Error('ECONNRESET'); + } + return []; + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 687181 }, + relations: ['seasons'], + }); + + assert.notStrictEqual( + updated.status, + MediaStatus.DELETED, + 'A failed episode fetch must fail open at show level even if another season only verified 4K' + ); + assert.strictEqual( + updated.status, + MediaStatus.PARTIALLY_AVAILABLE, + 'The verified 4K-only season can still drop non-4K status while the failed season is preserved' + ); + assert.strictEqual(updated.status4k, MediaStatus.AVAILABLE); + const s1 = updated.seasons.find((s) => s.seasonNumber === 1); + const s2 = updated.seasons.find((s) => s.seasonNumber === 2); + assert.strictEqual(s1?.status, MediaStatus.DELETED); + assert.strictEqual(s1?.status4k, MediaStatus.AVAILABLE); + assert.strictEqual(s2?.status, MediaStatus.AVAILABLE); + assert.strictEqual(s2?.status4k, MediaStatus.AVAILABLE); + }); + + it('should not treat unverified empty Media caches as proof a tier is missing', async () => { + configurePlex(); + configureSonarr([ + { syncEnabled: true }, + { is4k: true, syncEnabled: true }, + ]); + + const mediaRepository = getRepository(Media); + + const media = new Media(); + media.tmdbId = 687182; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.status4k = MediaStatus.AVAILABLE; + media.ratingKey = 'empty-media-show-rk'; + media.ratingKey4k = 'empty-media-show-rk'; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.AVAILABLE, + }), + ]; + await mediaRepository.save(media); + + getMetadataImpl = async (key: string) => { + if (key === 'empty-media-show-rk') { + return fakePlexShow('empty-media-show-rk'); + } + throw new Error('404'); + }; + + getChildrenMetadataImpl = async (key: string) => { + if (key === 'empty-media-show-rk') { + return [fakePlexSeason(1, 'em-s1-rk')]; + } + if (key === 'em-s1-rk') { + return [fakeVersionedEpisode('em-s1-e1', [])]; + } + return []; + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 687182 }, + relations: ['seasons'], + }); + const s1 = updated.seasons.find((s) => s.seasonNumber === 1); + + assert.strictEqual( + updated.status, + MediaStatus.AVAILABLE, + 'Empty Media arrays must not let a later tier pass treat a cached miss as verified' + ); + assert.strictEqual(updated.status4k, MediaStatus.AVAILABLE); + assert.strictEqual(s1?.status, MediaStatus.AVAILABLE); + assert.strictEqual(s1?.status4k, MediaStatus.AVAILABLE); + }); + + it('should keep non-4K show availability when a verified 4K-only season sits beside an unverified season', async () => { + configurePlex(); + configureSonarr([ + { syncEnabled: true }, + { is4k: true, syncEnabled: true }, + ]); + + const mediaRepository = getRepository(Media); + + const media = new Media(); + media.tmdbId = 687183; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.status4k = MediaStatus.AVAILABLE; + media.ratingKey = 'mixed-verified-show-rk'; + media.ratingKey4k = 'mixed-verified-show-rk'; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.AVAILABLE, + }), + new Season({ + seasonNumber: 2, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.AVAILABLE, + }), + ]; + await mediaRepository.save(media); + + getMetadataImpl = async (key: string) => { + if (key === 'mixed-verified-show-rk') { + return fakePlexShow('mixed-verified-show-rk'); + } + throw new Error('404'); + }; + + getChildrenMetadataImpl = async (key: string) => { + if (key === 'mixed-verified-show-rk') { + return [fakePlexSeason(1, 'mv-s1-rk'), fakePlexSeason(2, 'mv-s2-rk')]; + } + if (key === 'mv-s1-rk') { + return [fakeVersionedEpisode('mv-s1-e1', [3840])]; + } + if (key === 'mv-s2-rk') { + return [fakeVersionedEpisode('mv-s2-e1', [])]; + } + return []; + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 687183 }, + relations: ['seasons'], + }); + + assert.notStrictEqual( + updated.status, + MediaStatus.DELETED, + 'A verified 4K-only season must not prove the non-4K tier is gone while another season is still unverified' + ); + assert.strictEqual(updated.status4k, MediaStatus.AVAILABLE); + }); + + it('should not treat a same-season mix of verified and empty Media episodes as proof a tier is missing', async () => { + configurePlex(); + configureSonarr([ + { syncEnabled: true }, + { is4k: true, syncEnabled: true }, + ]); + + const mediaRepository = getRepository(Media); + + const media = new Media(); + media.tmdbId = 687184; + media.mediaType = MediaType.TV; + media.status = MediaStatus.AVAILABLE; + media.status4k = MediaStatus.AVAILABLE; + media.ratingKey = 'same-season-mixed-rk'; + media.ratingKey4k = 'same-season-mixed-rk'; + media.seasons = [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.AVAILABLE, + }), + ]; + await mediaRepository.save(media); + + getMetadataImpl = async (key: string) => { + if (key === 'same-season-mixed-rk') { + return fakePlexShow('same-season-mixed-rk'); + } + throw new Error('404'); + }; + + getChildrenMetadataImpl = async (key: string) => { + if (key === 'same-season-mixed-rk') { + return [fakePlexSeason(1, 'ssm-s1-rk')]; + } + if (key === 'ssm-s1-rk') { + return [ + fakeVersionedEpisode('ssm-s1-e1', [3840]), + fakeVersionedEpisode('ssm-s1-e2', []), + ]; + } + return []; + }; + + await availabilitySync.run(); + + const updated = await mediaRepository.findOneOrFail({ + where: { tmdbId: 687184 }, + relations: ['seasons'], + }); + const s1 = updated.seasons.find((s) => s.seasonNumber === 1); + + assert.strictEqual( + updated.status, + MediaStatus.AVAILABLE, + 'A width-3840 episode must not prove the non-4K tier is gone while another episode in the same season has empty Media' + ); + assert.strictEqual(updated.status4k, MediaStatus.AVAILABLE); + assert.strictEqual(s1?.status, MediaStatus.AVAILABLE); + assert.strictEqual(s1?.status4k, MediaStatus.AVAILABLE); + }); }); describe('specials season handling', () => { diff --git a/server/lib/availabilitySync.ts b/server/lib/availabilitySync.ts index 4a700ef355..2af2d70d21 100644 --- a/server/lib/availabilitySync.ts +++ b/server/lib/availabilitySync.ts @@ -26,7 +26,15 @@ class AvailabilitySync { public running = false; private plexClient: PlexAPI; private plexSeasonsCache: Record; - private plexEpisodeExistsCache: Record; + private plexEpisodeExistsCache: Record< + string, + { exists: boolean; verified: boolean } + >; + private plexMetadataCache: Record; + private plexRatingKeyProbeCache: Record< + string, + 'exists' | 'missing' | 'error' + >; private jellyfinClient: JellyfinAPI; private jellyfinSeasonsCache: Record; @@ -46,6 +54,8 @@ class AvailabilitySync { this.running = true; this.plexSeasonsCache = {}; this.plexEpisodeExistsCache = {}; + this.plexMetadataCache = {}; + this.plexRatingKeyProbeCache = {}; this.jellyfinSeasonsCache = {}; this.jellyfinEpisodeExistsCache = {}; this.sonarrSeasonsCache = {}; @@ -154,9 +164,18 @@ class AvailabilitySync { // plex if (mediaServerType === MediaServerType.PLEX) { - const { existsInPlex } = await this.mediaExistsInPlex(media, false); - const { existsInPlex: existsInPlex4k } = - await this.mediaExistsInPlex(media, true); + let existsInPlex = false; + let existsInPlex4k = false; + + if (this.mediaHasAvailableTier(media, false)) { + ({ existsInPlex } = await this.mediaExistsInPlex(media, false)); + } + if (this.mediaHasAvailableTier(media, true)) { + ({ existsInPlex: existsInPlex4k } = await this.mediaExistsInPlex( + media, + true + )); + } if (existsInPlex || existsInRadarr) { movieExists = true; @@ -228,13 +247,23 @@ class AvailabilitySync { let showExists4k = false; //plex + let existsInPlex = false; + let existsInPlex4k = false; + let plexSeasonsMap: Map = new Map(); + let plexSeasonsMap4k: Map = new Map(); - const { existsInPlex, seasonsMap: plexSeasonsMap = new Map() } = - await this.mediaExistsInPlex(media, false); - const { - existsInPlex: existsInPlex4k, - seasonsMap: plexSeasonsMap4k = new Map(), - } = await this.mediaExistsInPlex(media, true); + if (mediaServerType === MediaServerType.PLEX) { + if (this.mediaHasAvailableTier(media, false)) { + ({ existsInPlex, seasonsMap: plexSeasonsMap = new Map() } = + await this.mediaExistsInPlex(media, false)); + } + if (this.mediaHasAvailableTier(media, true)) { + ({ + existsInPlex: existsInPlex4k, + seasonsMap: plexSeasonsMap4k = new Map(), + } = await this.mediaExistsInPlex(media, true)); + } + } //jellyfin const { @@ -868,135 +897,230 @@ class AvailabilitySync { } // Plex - private async mediaExistsInPlex( + private isPlexNotFound(ex: unknown): boolean { + return (ex as { response?: { status?: number } })?.response?.status === 404; + } + + private async dropStoredPlexRatingKey( media: Media, - is4k: boolean - ): Promise<{ existsInPlex: boolean; seasonsMap?: Map }> { - const ratingKey = media.ratingKey; - const ratingKey4k = media.ratingKey4k; - let existsInPlex = false; - let preventSeasonSearch = false; + ratingKey: string + ): Promise { + const keys = media.getPlexRatingKeys(); + if (!keys.includes(ratingKey)) { + return; + } + + media.plexRatingKeys = keys.filter((stored) => stored !== ratingKey); + await getRepository(Media).save(media); + } + + private mediaHasAvailableTier(media: Media, is4k: boolean): boolean { + if (media.mediaType === 'movie') { + return media[is4k ? 'status4k' : 'status'] === MediaStatus.AVAILABLE; + } + + return ( + media[is4k ? 'status4k' : 'status'] === MediaStatus.AVAILABLE || + media[is4k ? 'status4k' : 'status'] === MediaStatus.PARTIALLY_AVAILABLE || + media.seasons.some( + (season) => + season[is4k ? 'status4k' : 'status'] === MediaStatus.AVAILABLE || + season[is4k ? 'status4k' : 'status'] === + MediaStatus.PARTIALLY_AVAILABLE + ) + ); + } + + private async probePlexRatingKey( + media: Media, + ratingKey: string + ): Promise<'exists' | 'missing' | 'error'> { + if (ratingKey in this.plexRatingKeyProbeCache) { + return this.plexRatingKeyProbeCache[ratingKey]; + } - // Check each plex instance to see if the media still exists - // If found, we will assume the media exists and prevent removal - // We can use the cache we built when we fetched the series with mediaExistsInPlex try { - let plexMedia: PlexMetadata | undefined; + const plexMedia = await this.plexClient?.getMetadata(ratingKey); + // Empty successful Metadata responses are unverified — only HTTP 404 + // confirms the rating key is missing. + if (!plexMedia) { + this.plexRatingKeyProbeCache[ratingKey] = 'error'; + return 'error'; + } - if (ratingKey && !is4k) { - plexMedia = await this.plexClient?.getMetadata(ratingKey); + this.plexMetadataCache[ratingKey] = plexMedia; - if (media.mediaType === 'tv') { - this.plexSeasonsCache[ratingKey] = - await this.plexClient?.getChildrenMetadata(ratingKey); + if (media.mediaType === 'tv') { + this.plexSeasonsCache[ratingKey] = + (await this.plexClient?.getChildrenMetadata(ratingKey)) ?? []; + } + + this.plexRatingKeyProbeCache[ratingKey] = 'exists'; + return 'exists'; + } catch (ex) { + if (this.isPlexNotFound(ex)) { + this.plexRatingKeyProbeCache[ratingKey] = 'missing'; + this.plexSeasonsCache[ratingKey] = []; + return 'missing'; + } + + logger.debug( + `Failure retrieving Plex metadata for rating key ${ratingKey} [TMDB ID ${media.tmdbId}].`, + { + errorMessage: ex instanceof Error ? ex.message : String(ex), + label: 'AvailabilitySync', } + ); + this.plexRatingKeyProbeCache[ratingKey] = 'error'; + return 'error'; + } + } - if ( - plexMedia && - media.mediaType === 'movie' && - this.enable4kMovie && - plexMedia.Media?.length && - !plexMedia.Media.some((mediaItem) => (mediaItem.width ?? 0) < 2000) - ) { - plexMedia = undefined; + private async tvKeyHasTieredEpisodes( + ratingKey: string, + is4k: boolean + ): Promise<{ + hasTier: boolean; + verified: boolean; + }> { + const cachedSeasons = this.plexSeasonsCache[ratingKey]; + if (!cachedSeasons?.length) { + return { hasTier: false, verified: false }; + } + + let hasTier = false; + let verified = true; + + for (const season of cachedSeasons) { + const cacheKey = `${is4k ? '4k' : 'std'}-${season.ratingKey}`; + const otherCacheKey = `${is4k ? 'std' : '4k'}-${season.ratingKey}`; + + if (cacheKey in this.plexEpisodeExistsCache) { + const cached = this.plexEpisodeExistsCache[cacheKey]; + if (!cached.verified) { + verified = false; } + if (cached.exists) { + hasTier = true; + break; + } + continue; } - if (ratingKey4k && is4k) { - plexMedia = await this.plexClient?.getMetadata(ratingKey4k); - - if (media.mediaType === 'tv') { - this.plexSeasonsCache[ratingKey4k] = - await this.plexClient?.getChildrenMetadata(ratingKey4k); + try { + const episodes = + (await this.plexClient?.getChildrenMetadata(season.ratingKey)) ?? []; + const episodeVerified = + episodes.length === 0 || + episodes.every((episode) => episode.Media?.length); + if (!episodeVerified) { + verified = false; + } + const episodeVersions = episodes.flatMap( + (episode) => episode.Media ?? [] + ); + const seasonHasTier = this.seasonHasTieredEpisodes( + episodeVersions, + is4k + ); + this.plexEpisodeExistsCache[cacheKey] = { + exists: seasonHasTier, + verified: episodeVerified, + }; + if (!(otherCacheKey in this.plexEpisodeExistsCache)) { + this.plexEpisodeExistsCache[otherCacheKey] = { + exists: this.seasonHasTieredEpisodes(episodeVersions, !is4k), + verified: episodeVerified, + }; + } + if (seasonHasTier) { + hasTier = true; + break; } + } catch { + verified = false; + } + } - if (plexMedia) { - if ( - plexMedia && - media.mediaType === 'movie' && - plexMedia.Media?.length && - !plexMedia.Media.some((mediaItem) => (mediaItem.width ?? 0) >= 2000) - ) { - plexMedia = undefined; - } + return { hasTier, verified }; + } - if (plexMedia && media.mediaType === 'tv') { - const cachedSeasons = this.plexSeasonsCache[ratingKey4k]; - if (cachedSeasons?.length) { - let has4kInAnySeason = false; - let verifiedAnySeason = false; - for (const season of cachedSeasons) { - try { - const episodes = await this.plexClient?.getChildrenMetadata( - season.ratingKey - ); - if (episodes?.some((episode) => episode.Media?.length)) { - verifiedAnySeason = true; - } - const has4kEpisode = episodes?.some((episode) => - episode.Media?.some( - (mediaItem) => (mediaItem.width ?? 0) >= 2000 - ) - ); - if (has4kEpisode) { - has4kInAnySeason = true; - break; - } - } catch { - // If we can't fetch episodes for a season, continue checking other seasons - } - } - if (verifiedAnySeason && !has4kInAnySeason) { - plexMedia = undefined; - } + private async mediaExistsInPlex( + media: Media, + is4k: boolean + ): Promise<{ existsInPlex: boolean; seasonsMap?: Map }> { + const ratingKeys = media.getPlexRatingKeys(); + let existsInPlex = false; + + for (const ratingKey of ratingKeys) { + const probe = await this.probePlexRatingKey(media, ratingKey); + + if (probe === 'missing') { + await this.dropStoredPlexRatingKey(media, ratingKey); + continue; + } + + if (probe === 'error') { + existsInPlex = true; + continue; + } + + const plexMedia = this.plexMetadataCache[ratingKey]; + + if (media.mediaType === 'movie') { + if (!existsInPlex) { + if (is4k) { + if ( + !plexMedia?.Media?.length || + plexMedia.Media.some( + (mediaItem) => (mediaItem.width ?? 0) >= 2000 + ) + ) { + existsInPlex = true; } + } else if ( + !this.enable4kMovie || + !plexMedia?.Media?.length || + plexMedia.Media.some((mediaItem) => (mediaItem.width ?? 0) < 2000) + ) { + existsInPlex = true; } } + continue; } - if (plexMedia) { + if (!is4k && !this.enable4kShow) { existsInPlex = true; + continue; } - } catch (ex) { - if (!ex.message.includes('404')) { + + if (existsInPlex) { + continue; + } + + const { hasTier, verified } = await this.tvKeyHasTieredEpisodes( + ratingKey, + is4k + ); + if (hasTier || !verified) { existsInPlex = true; - preventSeasonSearch = true; - logger.debug( - `Failure retrieving the ${is4k ? '4K' : 'non-4K'} ${ - media.mediaType === 'tv' ? 'show' : 'movie' - } [TMDB ID ${media.tmdbId}] from Plex.`, - { - errorMessage: ex.message, - label: 'AvailabilitySync', - } - ); } } - // Here we check each season in plex for availability - // If the API returns an error other than a 404, - // we will have to prevent the season check from happening if (media.mediaType === 'tv') { const seasonsMap: Map = new Map(); + const filteredSeasons = media.seasons.filter( + (season) => + season[is4k ? 'status4k' : 'status'] === MediaStatus.AVAILABLE || + season[is4k ? 'status4k' : 'status'] === + MediaStatus.PARTIALLY_AVAILABLE + ); - if (!preventSeasonSearch) { - const filteredSeasons = media.seasons.filter( - (season) => - season[is4k ? 'status4k' : 'status'] === MediaStatus.AVAILABLE || - season[is4k ? 'status4k' : 'status'] === - MediaStatus.PARTIALLY_AVAILABLE - ); - - for (const season of filteredSeasons) { - const seasonExists = await this.seasonExistsInPlex( - media, - season, - is4k - ); + for (const season of filteredSeasons) { + const seasonExists = await this.seasonExistsInPlex(media, season, is4k); - if (seasonExists) { - seasonsMap.set(season.seasonNumber, true); - } + if (seasonExists) { + seasonsMap.set(season.seasonNumber, true); } } @@ -1006,67 +1130,98 @@ class AvailabilitySync { return { existsInPlex }; } + private seasonHasTieredEpisodes( + episodeVersions: { width?: number }[], + is4k: boolean + ): boolean { + if (is4k) { + return episodeVersions.some( + (mediaItem) => (mediaItem.width ?? 0) >= 2000 + ); + } + if (this.enable4kShow) { + return episodeVersions.some((mediaItem) => (mediaItem.width ?? 0) < 2000); + } + return episodeVersions.length > 0; + } + private async seasonExistsInPlex( media: Media, season: Season, is4k: boolean ): Promise { - const ratingKey = media.ratingKey; - const ratingKey4k = media.ratingKey4k; - let seasonExistsInPlex = false; - - let plexSeasons: PlexMetadata[] | undefined; - - if (ratingKey && !is4k) { - plexSeasons = this.plexSeasonsCache[ratingKey]; - } + const ratingKeys = media.getPlexRatingKeys(); + let sawError = false; + + for (const ratingKey of ratingKeys) { + if (!(ratingKey in this.plexSeasonsCache)) { + const probe = await this.probePlexRatingKey(media, ratingKey); + if (probe === 'missing') { + await this.dropStoredPlexRatingKey(media, ratingKey); + continue; + } + if (probe === 'error') { + sawError = true; + continue; + } + } - if (ratingKey4k && is4k) { - plexSeasons = this.plexSeasonsCache[ratingKey4k]; - } + const seasonMeta = this.plexSeasonsCache[ratingKey]?.find( + (plexSeason) => plexSeason.index === season.seasonNumber + ); - const seasonMeta = plexSeasons?.find( - (plexSeason) => plexSeason.index === season.seasonNumber - ); + if (!seasonMeta) { + continue; + } - if (seasonMeta) { const cacheKey = `${is4k ? '4k' : 'std'}-${seasonMeta.ratingKey}`; + const otherCacheKey = `${is4k ? 'std' : '4k'}-${seasonMeta.ratingKey}`; if (cacheKey in this.plexEpisodeExistsCache) { - seasonExistsInPlex = this.plexEpisodeExistsCache[cacheKey]; - } else { - try { - // Season metadata exists, but we need to verify it has actual - // episode files. Plex can keep empty season entries. - const episodes = await this.plexClient?.getChildrenMetadata( - seasonMeta.ratingKey - ); - - const episodeVersions = - episodes?.flatMap((episode) => episode.Media ?? []) ?? []; - - if (is4k) { - seasonExistsInPlex = episodeVersions.some( - (mediaItem) => (mediaItem.width ?? 0) >= 2000 - ); - } else if (this.enable4kShow) { - seasonExistsInPlex = episodeVersions.some( - (mediaItem) => (mediaItem.width ?? 0) < 2000 - ); - } else { - seasonExistsInPlex = episodeVersions.length > 0; - } - } catch { - // If we can't fetch episodes, assume the season exists - // to avoid false removal - seasonExistsInPlex = true; + const cached = this.plexEpisodeExistsCache[cacheKey]; + if (cached.exists || !cached.verified) { + return true; } + continue; + } - this.plexEpisodeExistsCache[cacheKey] = seasonExistsInPlex; + try { + const episodes = + (await this.plexClient?.getChildrenMetadata(seasonMeta.ratingKey)) ?? + []; + const episodeVersions = episodes.flatMap( + (episode) => episode.Media ?? [] + ); + const episodeVerified = + episodes.length === 0 || + episodes.every((episode) => episode.Media?.length); + const seasonExists = this.seasonHasTieredEpisodes( + episodeVersions, + is4k + ); + this.plexEpisodeExistsCache[cacheKey] = { + exists: seasonExists, + verified: episodeVerified, + }; + if (!(otherCacheKey in this.plexEpisodeExistsCache)) { + this.plexEpisodeExistsCache[otherCacheKey] = { + exists: this.seasonHasTieredEpisodes(episodeVersions, !is4k), + verified: episodeVerified, + }; + } + if (seasonExists || !episodeVerified) { + return true; + } + } catch { + this.plexEpisodeExistsCache[cacheKey] = { + exists: true, + verified: true, + }; + return true; } } - return seasonExistsInPlex; + return sawError; } // Jellyfin diff --git a/server/lib/scanners/baseScanner.ts b/server/lib/scanners/baseScanner.ts index 93f4716650..35e67f0049 100644 --- a/server/lib/scanners/baseScanner.ts +++ b/server/lib/scanners/baseScanner.ts @@ -178,10 +178,17 @@ class BaseScanner { ratingKey && existing[is4k ? 'ratingKey4k' : 'ratingKey'] !== ratingKey ) { + existing.addPlexRatingKey( + existing[is4k ? 'ratingKey4k' : 'ratingKey'] + ); existing[is4k ? 'ratingKey4k' : 'ratingKey'] = ratingKey; changedExisting = true; } + if (existing.addPlexRatingKey(ratingKey)) { + changedExisting = true; + } + if ( jellyfinMediaId && existing[is4k ? 'jellyfinMediaId4k' : 'jellyfinMediaId'] !== @@ -274,6 +281,7 @@ class BaseScanner { newMedia.ratingKey = !is4k ? ratingKey : undefined; newMedia.ratingKey4k = is4k && this.enable4kMovie ? ratingKey : undefined; + newMedia.addPlexRatingKey(ratingKey); } if (jellyfinMediaId) { @@ -346,6 +354,7 @@ class BaseScanner { // We update the rating keys and jellyfinMediaId in the seasons loop because we need episode counts if (media && season.episodes > 0 && media.ratingKey !== ratingKey) { + media.addPlexRatingKey(media.ratingKey); media.ratingKey = ratingKey; } @@ -355,6 +364,7 @@ class BaseScanner { this.enable4kShow && media.ratingKey4k !== ratingKey ) { + media.addPlexRatingKey(media.ratingKey4k); media.ratingKey4k = ratingKey; } @@ -468,6 +478,7 @@ class BaseScanner { } if (media) { + media.addPlexRatingKey(ratingKey); media.seasons = [...media.seasons, ...newSeasons]; const newStandardSeasonsAvailable = ( @@ -651,6 +662,7 @@ class BaseScanner { ? MediaStatus.PROCESSING : MediaStatus.UNKNOWN, }); + newMedia.addPlexRatingKey(ratingKey); await mediaRepository.save(newMedia); this.log(`Saved ${title}`); } diff --git a/server/lib/scanners/plex/plex.test.ts b/server/lib/scanners/plex/plex.test.ts index 49089a6592..70229f3ba9 100644 --- a/server/lib/scanners/plex/plex.test.ts +++ b/server/lib/scanners/plex/plex.test.ts @@ -22,8 +22,9 @@ import MediaRequest from '@server/entity/MediaRequest'; import Season from '@server/entity/Season'; import SeasonRequest from '@server/entity/SeasonRequest'; import { User } from '@server/entity/User'; +import availabilitySync from '@server/lib/availabilitySync'; import { plexFullScanner } from '@server/lib/scanners/plex'; -import type { Library } from '@server/lib/settings'; +import type { Library, SonarrSettings } from '@server/lib/settings'; import { getSettings } from '@server/lib/settings'; import { setupTestDb } from '@server/test/db'; import { runWithMockTimers } from '@server/test/runWithMockTimers'; @@ -36,6 +37,19 @@ Object.defineProperty(animeList, 'sync', { writable: true, }); +function plexNotFoundError(): Error & { response: { status: number } } { + return Object.assign(new Error('Request failed with status code 404'), { + response: { status: 404 }, + }); +} + +function rethrowPlexTestError(error: unknown): never { + if (error instanceof Error && error.message === '404') { + throw plexNotFoundError(); + } + throw error; +} + let getLibrariesImpl: () => Promise = async () => []; let getLibraryContentsImpl: ( id: string @@ -44,8 +58,11 @@ let getLibraryContentsImpl: ( items: [], }); let getMetadataImpl: ( - key: string -) => Promise = async () => undefined; + key: string, + options?: { includeChildren?: boolean } +) => Promise = async () => { + throw plexNotFoundError(); +}; let getChildrenMetadataImpl: ( key: string ) => Promise = async () => []; @@ -68,7 +85,13 @@ Object.defineProperty(PlexAPI.prototype, 'getLibraryContents', { Object.defineProperty(PlexAPI.prototype, 'getMetadata', { get() { - return async (key: string) => getMetadataImpl(key); + return async (key: string, options?: { includeChildren?: boolean }) => { + try { + return await getMetadataImpl(key, options); + } catch (error) { + rethrowPlexTestError(error); + } + }; }, set() {}, configurable: true, @@ -76,7 +99,13 @@ Object.defineProperty(PlexAPI.prototype, 'getMetadata', { Object.defineProperty(PlexAPI.prototype, 'getChildrenMetadata', { get() { - return async (key: string) => getChildrenMetadataImpl(key); + return async (key: string) => { + try { + return await getChildrenMetadataImpl(key); + } catch (error) { + rethrowPlexTestError(error); + } + }; }, set() {}, configurable: true, @@ -84,20 +113,38 @@ Object.defineProperty(PlexAPI.prototype, 'getChildrenMetadata', { let getTvShowImpl: (args: { tvId: number; + language?: string; }) => Promise = async () => fakeTmdbShow(1); +Object.defineProperty(TheMovieDb.prototype, 'getTvShow', { + get() { + return async (args: { tvId: number; language?: string }) => + getTvShowImpl(args); + }, + set() {}, + configurable: true, +}); + +Object.defineProperty(TheMovieDb.prototype, 'getTvShowForScan', { + get() { + return async (args: { tvId: number; language?: string }) => + getTvShowImpl(args); + }, + set() {}, + configurable: true, +}); + for (const method of ['getTvShow', 'getTvShowForScan'] as const) { - Object.defineProperty(TheMovieDb.prototype, method, { - get() { - return async (args: { tvId: number }) => getTvShowImpl(args); - }, - set() {}, + // plexFullScanner / availabilitySync built their own TheMovieDb on import, + // before the stubs above. + Object.defineProperty(plexFullScanner.tmdb, method, { + value: async (args: { tvId: number; language?: string }) => + getTvShowImpl(args), configurable: true, }); - - // plexFullScanner built its own TheMovieDb on import, before the stubs above. - Object.defineProperty(plexFullScanner.tmdb, method, { - value: async (args: { tvId: number }) => getTvShowImpl(args), + Object.defineProperty(availabilitySync.tmdb, method, { + value: async (args: { tvId: number; language?: string }) => + getTvShowImpl(args), configurable: true, }); } @@ -106,18 +153,20 @@ mock.method(MediaRequest, 'sendNotification', async () => undefined); setupTestDb(); +function tmdbSeasons(count: number): TmdbTvSeasonResult[] { + return Array.from({ length: count }, (_, i) => ({ + id: i + 1, + air_date: '2024-01-01', + episode_count: 10, + name: `Season ${i + 1}`, + overview: '', + season_number: i + 1, + })); +} + function fakeTmdbShow( tmdbId: number, - seasons: TmdbTvSeasonResult[] = [ - { - id: 1, - air_date: '2024-01-01', - episode_count: 10, - name: 'Season 1', - overview: '', - season_number: 1, - }, - ] + seasons: TmdbTvSeasonResult[] = tmdbSeasons(1) ): TmdbTvDetails { return { id: tmdbId, @@ -132,7 +181,10 @@ function fakeTmdbShow( last_air_date: '2024-01-01', name: 'Test Show', networks: [], - number_of_episodes: 10, + number_of_episodes: seasons.reduce( + (sum, season) => sum + season.episode_count, + 0 + ), number_of_seasons: seasons.length, origin_country: ['US'], original_language: 'en', @@ -155,65 +207,104 @@ function fakeTmdbShow( }; } -function fakePlexShowItem(ratingKey: string): PlexLibraryItem { +function fakePlexSeason(seasonNumber: number, ratingKey: string): PlexMetadata { return { ratingKey, - title: 'Test Show', - guid: 'plex://show/test-show', - addedAt: 1700000000, - updatedAt: 1700000000, - type: 'show', + guid: `plex://season/${ratingKey}`, + type: 'season', + title: `Season ${seasonNumber}`, + Guid: [], + index: seasonNumber, + leafCount: 0, + viewedLeafCount: 0, + addedAt: 1, + updatedAt: 1, Media: [], }; } -function fakePlexShowMetadata( +function fakePlexEpisodes( + prefix: string, + count: number, + width: number +): PlexMetadata[] { + const videoResolution = width >= 2000 ? '4k' : '1080'; + return Array.from({ length: count }, (_, i) => ({ + ratingKey: `${prefix}-ep-${i}`, + guid: `plex://episode/${prefix}-ep-${i}`, + type: 'movie' as const, + title: `Episode ${i + 1}`, + Guid: [], + index: i + 1, + leafCount: 0, + viewedLeafCount: 0, + addedAt: 1, + updatedAt: 1, + Media: [ + { + id: i, + duration: 2400, + bitrate: width >= 2000 ? 20000 : 4000, + width, + height: width >= 2000 ? 2160 : 1080, + aspectRatio: 1.78, + audioChannels: 2, + audioCodec: 'aac', + videoCodec: 'h264', + videoResolution, + container: 'mkv', + videoFrameRate: '24p', + videoProfile: 'high', + }, + ], + })); +} + +function fakePlexLibraryShow( ratingKey: string, tmdbId: number, - children: PlexMetadata[] -): PlexMetadata { + title = 'Split Show' +): PlexLibraryItem { return { ratingKey, - title: 'Test Show', - guid: 'plex://show/test-show', + title, + guid: `tmdb://${tmdbId}`, type: 'show', - Guid: [{ id: `tmdb://${tmdbId}` }], - Children: { size: 12, Metadata: children }, - index: 1, - leafCount: 0, - viewedLeafCount: 0, - addedAt: 1700000000, - updatedAt: 1700000000, + addedAt: 1, + updatedAt: 1, Media: [], }; } -function fakePlexSeasonMetadata( - seasonNumber: number, - ratingKey: string +function fakePlexShowMetadata( + ratingKey: string, + tmdbId: number, + seasons: PlexMetadata[] ): PlexMetadata { return { ratingKey, - title: `Season ${seasonNumber}`, - guid: `plex://season/test-season-${seasonNumber}`, - type: 'season', - Guid: [], - index: seasonNumber, + guid: `tmdb://${tmdbId}`, + type: 'show', + title: 'Test Show', + Guid: [{ id: `tmdb://${tmdbId}` }], + Children: { + size: 12, + Metadata: seasons, + }, + index: 1, leafCount: 0, viewedLeafCount: 0, - addedAt: 1700000000, - updatedAt: 1700000000, + addedAt: 1, + updatedAt: 1, Media: [], }; } -function configurePlexWithLibrary( - libraries: Library[] = [ - { id: 'test-library-id', name: 'TV Shows', enabled: true, type: 'show' }, - ] -): void { +function configurePlexLibraries(libraries: Library[]): void { const settings = getSettings(); settings.main.mediaServerType = MediaServerType.PLEX; + settings.sonarr = []; + settings.radarr = []; settings.plex = { ...settings.plex, ip: '127.0.0.1', @@ -222,25 +313,77 @@ function configurePlexWithLibrary( }; } +/** Enables BaseScanner.startRun() 4K show detection via settings.sonarr. */ +function enableSonarr4k(): void { + getSettings().sonarr = [ + { + id: 0, + name: 'Sonarr 4K', + hostname: 'localhost', + port: 8989, + apiKey: 'test-key', + baseUrl: '', + useSsl: false, + activeProfileId: 1, + activeProfileName: 'Default', + activeDirectory: '/tv', + activeLanguageProfileId: 1, + seriesType: 'standard', + animeSeriesType: 'standard', + animeTags: [], + is4k: true, + enableSeasonFolders: true, + monitorNewItems: 'all', + tags: [], + isDefault: true, + syncEnabled: true, + preventSearch: false, + tagRequests: false, + overrideRule: [], + externalUrl: '', + } satisfies SonarrSettings, + ]; +} + +async function assertSeasonsAvailable(tmdbId: number, count: number) { + const updated = await getRepository(Media).findOneOrFail({ + where: { tmdbId, mediaType: MediaType.TV }, + relations: ['seasons'], + }); + + assert.strictEqual(updated.seasons.length, count); + for (const season of updated.seasons) { + assert.strictEqual( + season.status, + MediaStatus.AVAILABLE, + `Season ${season.seasonNumber} should remain AVAILABLE` + ); + } + assert.strictEqual(updated.status, MediaStatus.AVAILABLE); + return updated; +} + describe('Plex Scanner', () => { beforeEach(() => { - getLibrariesImpl = async () => [ - { - key: 'test-library-id', - title: 'TV Shows', - type: 'show', - agent: 'tv.plex.agents.series', - }, - ]; + getLibrariesImpl = async () => []; getLibraryContentsImpl = async () => ({ totalSize: 0, items: [] }); - getMetadataImpl = async () => undefined; + getMetadataImpl = async () => { + throw new Error('404'); + }; getChildrenMetadataImpl = async () => []; getTvShowImpl = async () => fakeTmdbShow(1); }); describe('in-flight request handling', () => { it('leaves an approved request alone when the show has no episodes yet', async () => { - configurePlexWithLibrary(); + configurePlexLibraries([ + { + id: 'test-library-id', + name: 'TV Shows', + enabled: true, + type: 'show', + }, + ]); const mediaRepository = getRepository(Media); const requestRepository = getRepository(MediaRequest); @@ -290,21 +433,37 @@ describe('Plex Scanner', () => { ); getTvShowImpl = async () => fakeTmdbShow(6100); + getLibrariesImpl = async () => [ + { + key: 'test-library-id', + title: 'TV Shows', + type: 'show', + agent: 'tv.plex.agents.series', + }, + ]; getLibraryContentsImpl = async (id: string) => id === 'test-library-id' ? { totalSize: 1, - items: [fakePlexShowItem('plex-inflight-show-key')], + items: [ + fakePlexLibraryShow( + 'plex-inflight-show-key', + 6100, + 'Test Show' + ), + ], } : { totalSize: 0, items: [] }; - getMetadataImpl = async (key: string) => - key === 'plex-inflight-show-key' - ? fakePlexShowMetadata('plex-inflight-show-key', 6100, [ - fakePlexSeasonMetadata(1, 'plex-inflight-s1-key'), - ]) - : undefined; + getMetadataImpl = async (key: string) => { + if (key === 'plex-inflight-show-key') { + return fakePlexShowMetadata('plex-inflight-show-key', 6100, [ + fakePlexSeason(1, 'plex-inflight-s1-key'), + ]); + } + throw new Error('404'); + }; getChildrenMetadataImpl = async () => []; @@ -321,4 +480,279 @@ describe('Plex Scanner', () => { ); }); }); + + describe('split-library availability', () => { + const split1080p: Library = { + id: 'lib-1080', + name: 'TV 1080p', + enabled: true, + type: 'show', + }; + const split4k: Library = { + id: 'lib-4k', + name: 'TV 4K', + enabled: true, + type: 'show', + }; + const libA: Library = { + id: 'lib-a', + name: 'TV A', + enabled: true, + type: 'show', + }; + const libB: Library = { + id: 'lib-b', + name: 'TV B', + enabled: true, + type: 'show', + }; + + function mockSplitShow(tmdbId: number) { + const rk1080 = `split-${tmdbId}-1080`; + const rk4k = `split-${tmdbId}-4k`; + + getTvShowImpl = async () => fakeTmdbShow(tmdbId, tmdbSeasons(4)); + getLibrariesImpl = async () => [ + { + type: 'show', + key: split1080p.id, + title: split1080p.name, + agent: 'tv.plex.agents.series', + }, + { + type: 'show', + key: split4k.id, + title: split4k.name, + agent: 'tv.plex.agents.series', + }, + ]; + getLibraryContentsImpl = async (id: string) => { + if (id === split1080p.id) { + return { + totalSize: 1, + items: [fakePlexLibraryShow(rk1080, tmdbId)], + }; + } + if (id === split4k.id) { + return { + totalSize: 1, + items: [fakePlexLibraryShow(rk4k, tmdbId)], + }; + } + return { totalSize: 0, items: [] }; + }; + getMetadataImpl = async (key: string) => { + if (key === rk1080) { + return fakePlexShowMetadata(rk1080, tmdbId, [ + fakePlexSeason(1, `${rk1080}-s1`), + ]); + } + if (key === rk4k) { + return fakePlexShowMetadata(rk4k, tmdbId, [ + fakePlexSeason(2, `${rk4k}-s2`), + fakePlexSeason(3, `${rk4k}-s3`), + fakePlexSeason(4, `${rk4k}-s4`), + ]); + } + throw new Error('404'); + }; + getChildrenMetadataImpl = async (key: string) => { + if (key === rk1080) { + return [fakePlexSeason(1, `${rk1080}-s1`)]; + } + if (key === rk4k) { + return [ + fakePlexSeason(2, `${rk4k}-s2`), + fakePlexSeason(3, `${rk4k}-s3`), + fakePlexSeason(4, `${rk4k}-s4`), + ]; + } + if (key === `${rk1080}-s1`) { + return fakePlexEpisodes(key, 10, 1920); + } + if (key === `${rk4k}-s2`) { + // One 1080p episode in the 4K library copy, which used to steal ratingKey. + return [ + ...fakePlexEpisodes(`${key}-4k`, 9, 3840), + ...fakePlexEpisodes(`${key}-1080`, 1, 1920), + ]; + } + if (key === `${rk4k}-s3` || key === `${rk4k}-s4`) { + return fakePlexEpisodes(key, 10, 3840); + } + return []; + }; + + return { rk1080, rk4k }; + } + + function mockTwoStandardLibraries(tmdbId: number) { + const rkA = `std-${tmdbId}-a`; + const rkB = `std-${tmdbId}-b`; + + getTvShowImpl = async () => fakeTmdbShow(tmdbId, tmdbSeasons(4)); + getLibrariesImpl = async () => [ + { + type: 'show', + key: libA.id, + title: libA.name, + agent: 'tv.plex.agents.series', + }, + { + type: 'show', + key: libB.id, + title: libB.name, + agent: 'tv.plex.agents.series', + }, + ]; + getLibraryContentsImpl = async (id: string) => { + if (id === libA.id) { + return { totalSize: 1, items: [fakePlexLibraryShow(rkA, tmdbId)] }; + } + if (id === libB.id) { + return { totalSize: 1, items: [fakePlexLibraryShow(rkB, tmdbId)] }; + } + return { totalSize: 0, items: [] }; + }; + getMetadataImpl = async (key: string) => { + if (key === rkA) { + return fakePlexShowMetadata(rkA, tmdbId, [ + fakePlexSeason(1, `${rkA}-s1`), + ]); + } + if (key === rkB) { + return fakePlexShowMetadata(rkB, tmdbId, [ + fakePlexSeason(2, `${rkB}-s2`), + fakePlexSeason(3, `${rkB}-s3`), + fakePlexSeason(4, `${rkB}-s4`), + ]); + } + throw new Error('404'); + }; + getChildrenMetadataImpl = async (key: string) => { + if (key === rkA) { + return [fakePlexSeason(1, `${rkA}-s1`)]; + } + if (key === rkB) { + return [ + fakePlexSeason(2, `${rkB}-s2`), + fakePlexSeason(3, `${rkB}-s3`), + fakePlexSeason(4, `${rkB}-s4`), + ]; + } + if ( + key === `${rkA}-s1` || + key === `${rkB}-s2` || + key === `${rkB}-s3` || + key === `${rkB}-s4` + ) { + return fakePlexEpisodes(key, 10, 1920); + } + return []; + }; + + return { rkA, rkB }; + } + + for (const order of [ + [split1080p, split4k], + [split4k, split1080p], + ] as const) { + it(`keeps every season after scanning ${order.map((library) => library.name).join(' then ')} then running availability sync`, async () => { + const tmdbId = order[0].id === split1080p.id ? 9010 : 9011; + const { rk1080, rk4k } = mockSplitShow(tmdbId); + configurePlexLibraries([...order]); + + await runWithMockTimers(() => plexFullScanner.run()); + + const scanned = await getRepository(Media).findOneOrFail({ + where: { tmdbId, mediaType: MediaType.TV }, + }); + assert.deepStrictEqual( + scanned.plexRatingKeys?.slice().sort(), + [rk1080, rk4k].sort() + ); + + await availabilitySync.run(); + await assertSeasonsAvailable(tmdbId, 4); + }); + } + + for (const order of [ + [libA, libB], + [libB, libA], + ] as const) { + it(`keeps every season after scanning two non-4K libraries ${order.map((library) => library.name).join(' then ')} then running availability sync`, async () => { + const tmdbId = order[0].id === libA.id ? 9020 : 9021; + const { rkA, rkB } = mockTwoStandardLibraries(tmdbId); + configurePlexLibraries([...order]); + + await runWithMockTimers(() => plexFullScanner.run()); + + const scanned = await getRepository(Media).findOneOrFail({ + where: { tmdbId, mediaType: MediaType.TV }, + }); + assert.deepStrictEqual( + scanned.plexRatingKeys?.slice().sort(), + [rkA, rkB].sort() + ); + + await availabilitySync.run(); + await assertSeasonsAvailable(tmdbId, 4); + }); + } + + it('records ratingKey4k and 4K season/show availability when Sonarr enables 4K detection', async () => { + const tmdbId = 9030; + const { rk1080, rk4k } = mockSplitShow(tmdbId); + + // Pure 4K season 2 so the 4K library copy does not also claim ratingKey. + const baseChildren = getChildrenMetadataImpl; + getChildrenMetadataImpl = async (key: string) => { + if (key === `${rk4k}-s2`) { + return fakePlexEpisodes(key, 10, 3840); + } + return baseChildren(key); + }; + + configurePlexLibraries([split1080p, split4k]); + enableSonarr4k(); + + await runWithMockTimers(() => plexFullScanner.run()); + + const scanned = await getRepository(Media).findOneOrFail({ + where: { tmdbId, mediaType: MediaType.TV }, + relations: ['seasons'], + }); + + assert.deepStrictEqual( + scanned.plexRatingKeys?.slice().sort(), + [rk1080, rk4k].sort() + ); + assert.strictEqual(scanned.ratingKey, rk1080); + assert.strictEqual(scanned.ratingKey4k, rk4k); + + const seasons = Object.fromEntries( + scanned.seasons.map((season) => [season.seasonNumber, season]) + ); + + assert.strictEqual(seasons[1].status, MediaStatus.AVAILABLE); + assert.strictEqual(seasons[1].status4k, MediaStatus.UNKNOWN); + for (const seasonNumber of [2, 3, 4]) { + assert.strictEqual( + seasons[seasonNumber].status, + MediaStatus.UNKNOWN, + `Season ${seasonNumber} should have no standard availability` + ); + assert.strictEqual( + seasons[seasonNumber].status4k, + MediaStatus.AVAILABLE, + `Season ${seasonNumber} should be 4K AVAILABLE` + ); + } + + assert.strictEqual(scanned.status, MediaStatus.PARTIALLY_AVAILABLE); + assert.strictEqual(scanned.status4k, MediaStatus.PARTIALLY_AVAILABLE); + }); + }); }); diff --git a/server/lib/scanners/radarr/radarr.test.ts b/server/lib/scanners/radarr/radarr.test.ts index 0ea41958e9..ac3337925b 100644 --- a/server/lib/scanners/radarr/radarr.test.ts +++ b/server/lib/scanners/radarr/radarr.test.ts @@ -798,7 +798,6 @@ describe('Radarr Scanner', () => { media, requestedBy, is4k: false, - serverId, }) ); } diff --git a/server/lib/scanners/sonarr/sonarr.test.ts b/server/lib/scanners/sonarr/sonarr.test.ts index 8d8699dbce..f799c2bf0d 100644 --- a/server/lib/scanners/sonarr/sonarr.test.ts +++ b/server/lib/scanners/sonarr/sonarr.test.ts @@ -1079,7 +1079,6 @@ describe('Sonarr Scanner', () => { media, requestedBy, is4k: false, - serverId, }) ); } diff --git a/server/migration/postgres/1794666034616-AddMediaPlexRatingKeys.ts b/server/migration/postgres/1794666034616-AddMediaPlexRatingKeys.ts new file mode 100644 index 0000000000..fe0769984c --- /dev/null +++ b/server/migration/postgres/1794666034616-AddMediaPlexRatingKeys.ts @@ -0,0 +1,13 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddMediaPlexRatingKeys1794666034616 implements MigrationInterface { + name = 'AddMediaPlexRatingKeys1794666034616'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE "media" ADD "plexRatingKeys" text`); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE "media" DROP COLUMN "plexRatingKeys"`); + } +} diff --git a/server/migration/sqlite/1794666022028-AddMediaPlexRatingKeys.ts b/server/migration/sqlite/1794666022028-AddMediaPlexRatingKeys.ts new file mode 100644 index 0000000000..41b1099ed8 --- /dev/null +++ b/server/migration/sqlite/1794666022028-AddMediaPlexRatingKeys.ts @@ -0,0 +1,75 @@ +import type { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddMediaPlexRatingKeys1794666022028 implements MigrationInterface { + name = 'AddMediaPlexRatingKeys1794666022028'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DROP INDEX "IDX_f8233358694d1677a67899b90a"`); + await queryRunner.query(`DROP INDEX "IDX_5d6218de4f547909391a5c1347"`); + await queryRunner.query(`DROP INDEX "IDX_c730c2d67f271a372c39a07b7e"`); + await queryRunner.query(`DROP INDEX "IDX_7ff2d11f6a83cb52386eaebe74"`); + await queryRunner.query(`DROP INDEX "IDX_41a289eb1fa489c1bc6f38d9c3"`); + await queryRunner.query(`DROP INDEX "IDX_7157aad07c73f6a6ae3bbd5ef5"`); + await queryRunner.query( + `CREATE TABLE "temporary_media" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "mediaType" varchar NOT NULL, "tmdbId" integer NOT NULL, "tvdbId" integer, "imdbId" varchar, "status" integer NOT NULL DEFAULT (1), "status4k" integer NOT NULL DEFAULT (1), "createdAt" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP), "updatedAt" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP), "lastSeasonChange" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP), "mediaAddedAt" datetime DEFAULT (CURRENT_TIMESTAMP), "serviceId" integer, "serviceId4k" integer, "externalServiceId" integer, "externalServiceId4k" integer, "externalServiceSlug" varchar, "externalServiceSlug4k" varchar, "ratingKey" varchar, "ratingKey4k" varchar, "jellyfinMediaId" varchar, "jellyfinMediaId4k" varchar, "plexRatingKeys" text, CONSTRAINT "UQ_41a289eb1fa489c1bc6f38d9c3c" UNIQUE ("tvdbId"))` + ); + await queryRunner.query( + `INSERT INTO "temporary_media"("id", "mediaType", "tmdbId", "tvdbId", "imdbId", "status", "status4k", "createdAt", "updatedAt", "lastSeasonChange", "mediaAddedAt", "serviceId", "serviceId4k", "externalServiceId", "externalServiceId4k", "externalServiceSlug", "externalServiceSlug4k", "ratingKey", "ratingKey4k", "jellyfinMediaId", "jellyfinMediaId4k") SELECT "id", "mediaType", "tmdbId", "tvdbId", "imdbId", "status", "status4k", "createdAt", "updatedAt", "lastSeasonChange", "mediaAddedAt", "serviceId", "serviceId4k", "externalServiceId", "externalServiceId4k", "externalServiceSlug", "externalServiceSlug4k", "ratingKey", "ratingKey4k", "jellyfinMediaId", "jellyfinMediaId4k" FROM "media"` + ); + await queryRunner.query(`DROP TABLE "media"`); + await queryRunner.query(`ALTER TABLE "temporary_media" RENAME TO "media"`); + await queryRunner.query( + `CREATE INDEX "IDX_f8233358694d1677a67899b90a" ON "media" ("tmdbId", "mediaType") ` + ); + await queryRunner.query( + `CREATE INDEX "IDX_5d6218de4f547909391a5c1347" ON "media" ("status4k") ` + ); + await queryRunner.query( + `CREATE INDEX "IDX_c730c2d67f271a372c39a07b7e" ON "media" ("status") ` + ); + await queryRunner.query( + `CREATE INDEX "IDX_7ff2d11f6a83cb52386eaebe74" ON "media" ("imdbId") ` + ); + await queryRunner.query( + `CREATE INDEX "IDX_41a289eb1fa489c1bc6f38d9c3" ON "media" ("tvdbId") ` + ); + await queryRunner.query( + `CREATE INDEX "IDX_7157aad07c73f6a6ae3bbd5ef5" ON "media" ("tmdbId") ` + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DROP INDEX "IDX_7157aad07c73f6a6ae3bbd5ef5"`); + await queryRunner.query(`DROP INDEX "IDX_41a289eb1fa489c1bc6f38d9c3"`); + await queryRunner.query(`DROP INDEX "IDX_7ff2d11f6a83cb52386eaebe74"`); + await queryRunner.query(`DROP INDEX "IDX_c730c2d67f271a372c39a07b7e"`); + await queryRunner.query(`DROP INDEX "IDX_5d6218de4f547909391a5c1347"`); + await queryRunner.query(`DROP INDEX "IDX_f8233358694d1677a67899b90a"`); + await queryRunner.query(`ALTER TABLE "media" RENAME TO "temporary_media"`); + await queryRunner.query( + `CREATE TABLE "media" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "mediaType" varchar NOT NULL, "tmdbId" integer NOT NULL, "tvdbId" integer, "imdbId" varchar, "status" integer NOT NULL DEFAULT (1), "status4k" integer NOT NULL DEFAULT (1), "createdAt" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP), "updatedAt" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP), "lastSeasonChange" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP), "mediaAddedAt" datetime DEFAULT (CURRENT_TIMESTAMP), "serviceId" integer, "serviceId4k" integer, "externalServiceId" integer, "externalServiceId4k" integer, "externalServiceSlug" varchar, "externalServiceSlug4k" varchar, "ratingKey" varchar, "ratingKey4k" varchar, "jellyfinMediaId" varchar, "jellyfinMediaId4k" varchar, CONSTRAINT "UQ_41a289eb1fa489c1bc6f38d9c3c" UNIQUE ("tvdbId"))` + ); + await queryRunner.query( + `INSERT INTO "media"("id", "mediaType", "tmdbId", "tvdbId", "imdbId", "status", "status4k", "createdAt", "updatedAt", "lastSeasonChange", "mediaAddedAt", "serviceId", "serviceId4k", "externalServiceId", "externalServiceId4k", "externalServiceSlug", "externalServiceSlug4k", "ratingKey", "ratingKey4k", "jellyfinMediaId", "jellyfinMediaId4k") SELECT "id", "mediaType", "tmdbId", "tvdbId", "imdbId", "status", "status4k", "createdAt", "updatedAt", "lastSeasonChange", "mediaAddedAt", "serviceId", "serviceId4k", "externalServiceId", "externalServiceId4k", "externalServiceSlug", "externalServiceSlug4k", "ratingKey", "ratingKey4k", "jellyfinMediaId", "jellyfinMediaId4k" FROM "temporary_media"` + ); + await queryRunner.query(`DROP TABLE "temporary_media"`); + await queryRunner.query( + `CREATE INDEX "IDX_7157aad07c73f6a6ae3bbd5ef5" ON "media" ("tmdbId") ` + ); + await queryRunner.query( + `CREATE INDEX "IDX_41a289eb1fa489c1bc6f38d9c3" ON "media" ("tvdbId") ` + ); + await queryRunner.query( + `CREATE INDEX "IDX_7ff2d11f6a83cb52386eaebe74" ON "media" ("imdbId") ` + ); + await queryRunner.query( + `CREATE INDEX "IDX_c730c2d67f271a372c39a07b7e" ON "media" ("status") ` + ); + await queryRunner.query( + `CREATE INDEX "IDX_5d6218de4f547909391a5c1347" ON "media" ("status4k") ` + ); + await queryRunner.query( + `CREATE INDEX "IDX_f8233358694d1677a67899b90a" ON "media" ("tmdbId", "mediaType") ` + ); + } +} diff --git a/server/routes/request.test.ts b/server/routes/request.test.ts index fbe513902b..7959c79770 100644 --- a/server/routes/request.test.ts +++ b/server/routes/request.test.ts @@ -1,5 +1,5 @@ import assert from 'node:assert/strict'; -import { before, beforeEach, describe, it, mock } from 'node:test'; +import { afterEach, before, beforeEach, describe, it, mock } from 'node:test'; import TheMovieDb from '@server/api/themoviedb'; import type { @@ -18,6 +18,7 @@ import OverrideRule from '@server/entity/OverrideRule'; import Season from '@server/entity/Season'; import SeasonRequest from '@server/entity/SeasonRequest'; import { User } from '@server/entity/User'; +import notificationManager, { Notification } from '@server/lib/notifications'; import { Permission } from '@server/lib/permissions'; import type { RadarrSettings, SonarrSettings } from '@server/lib/settings'; import { getSettings } from '@server/lib/settings'; @@ -41,6 +42,12 @@ const sendNotificationMock = mock.method( async () => undefined ).mock; +const managerSendNotificationMock = mock.method( + notificationManager, + 'sendNotification', + () => undefined +).mock; + const getMovieImpl: (args: { movieId: number; language?: string; @@ -174,6 +181,7 @@ before(async () => { beforeEach(() => { sendNotificationMock.resetCalls(); + managerSendNotificationMock.resetCalls(); }); setupTestDb(); @@ -193,7 +201,10 @@ async function loginAs(email: string, password: string) { } } -async function seedRequest(status = MediaRequestStatus.PENDING) { +async function seedRequest( + status = MediaRequestStatus.PENDING, + overrides: Partial = {} +) { const userRepo = getRepository(User); const mediaRepo = getRepository(Media); const requestRepo = getRepository(MediaRequest); @@ -219,12 +230,58 @@ async function seedRequest(status = MediaRequestStatus.PENDING) { requestedBy, is4k: false, updatedAt: new Date('2025-03-01T00:00:00.000Z'), + ...overrides, + }) + ); + + return requestRepo.findOneOrFail({ + where: { id: created.id }, + relations: { requestedBy: true, modifiedBy: true, media: true }, + }); +} + +async function seedPendingTvRequest( + status = MediaRequestStatus.PENDING, + overrides: Partial = {} +) { + const userRepo = getRepository(User); + const mediaRepo = getRepository(Media); + const requestRepo = getRepository(MediaRequest); + + const requestedBy = await userRepo.findOneOrFail({ + where: { email: 'demo@seerr.dev' }, + }); + + const media = await mediaRepo.save( + new Media({ + mediaType: MediaType.TV, + tmdbId: 67890, + status: MediaStatus.UNKNOWN, + status4k: MediaStatus.UNKNOWN, + }) + ); + + const created = await requestRepo.save( + new MediaRequest({ + type: MediaType.TV, + status, + media, + requestedBy, + is4k: false, + seasons: [new SeasonRequest({ seasonNumber: 1, status })], + updatedAt: new Date('2025-03-01T00:00:00.000Z'), + ...overrides, }) ); return requestRepo.findOneOrFail({ where: { id: created.id }, - relations: { requestedBy: true, modifiedBy: true }, + relations: { + requestedBy: true, + modifiedBy: true, + media: true, + seasons: true, + }, }); } @@ -1066,6 +1123,345 @@ describe('POST /request/:requestId/retry', () => { }); }); +describe('POST /request/:requestId/:status, unresolved *arr server', () => { + afterEach(() => { + // configureRadarr/configureSonarr mutate the shared settings singleton and + // nothing else resets it; clear it so later suites start clean. + const settings = getSettings(); + settings.radarr = []; + settings.sonarr = []; + }); + + function failedNotificationSent(): boolean { + return sendNotificationMock.calls.some( + (call) => call.arguments[2] === Notification.MEDIA_FAILED + ); + } + + it('fails a movie request whose serverId no longer exists instead of silently abandoning it', async () => { + configureRadarr([{ id: 0, isDefault: false, is4k: false }]); + getSettings().sonarr = []; + + const pending = await seedRequest(MediaRequestStatus.PENDING, { + serverId: 999, + }); + const admin = await loginAs('admin@seerr.dev', 'test1234'); + + const res = await admin.post(`/request/${pending.id}/approve`); + assert.strictEqual(res.status, 200); + + const persisted = await getRepository(MediaRequest).findOneOrFail({ + where: { id: pending.id }, + }); + assert.strictEqual(persisted.status, MediaRequestStatus.FAILED); + + const media = await getRepository(Media).findOneOrFail({ + where: { id: pending.media.id }, + }); + assert.strictEqual(media.status, MediaStatus.UNKNOWN); + + assert.ok(failedNotificationSent()); + }); + + it('completes a movie request whose serverId no longer exists when the media is already available', async () => { + configureRadarr([{ id: 0, isDefault: false, is4k: false }]); + getSettings().sonarr = []; + + const mediaRepo = getRepository(Media); + const requestRepo = getRepository(MediaRequest); + const userRepo = getRepository(User); + + const requestedBy = await userRepo.findOneOrFail({ + where: { email: 'demo@seerr.dev' }, + }); + + const media = await mediaRepo.save( + new Media({ + mediaType: MediaType.MOVIE, + tmdbId: 12346, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }) + ); + + const pending = await requestRepo.save( + new MediaRequest({ + type: MediaType.MOVIE, + status: MediaRequestStatus.PENDING, + media, + requestedBy, + is4k: false, + serverId: 999, + updatedAt: new Date('2025-03-01T00:00:00.000Z'), + }) + ); + + const admin = await loginAs('admin@seerr.dev', 'test1234'); + const res = await admin.post(`/request/${pending.id}/approve`); + assert.strictEqual(res.status, 200); + + const persisted = await requestRepo.findOneOrFail({ + where: { id: pending.id }, + }); + assert.strictEqual(persisted.status, MediaRequestStatus.COMPLETED); + assert.strictEqual(failedNotificationSent(), false); + + const availableCalls = managerSendNotificationMock.calls.filter( + (call) => call.arguments[0] === Notification.MEDIA_AVAILABLE + ); + assert.strictEqual(availableCalls.length, 1); + }); + + it('does not fail a movie request when no default Radarr server is configured (silent skip preserved)', async () => { + configureRadarr([{ isDefault: false, is4k: false }]); + getSettings().sonarr = []; + + const pending = await seedRequest(); + const admin = await loginAs('admin@seerr.dev', 'test1234'); + + const res = await admin.post(`/request/${pending.id}/approve`); + assert.strictEqual(res.status, 200); + + const persisted = await getRepository(MediaRequest).findOneOrFail({ + where: { id: pending.id }, + }); + assert.strictEqual(persisted.status, MediaRequestStatus.APPROVED); + assert.strictEqual(failedNotificationSent(), false); + }); + + it('completes a series request whose serverId no longer exists when every requested season is already available', async () => { + configureSonarr([{ id: 0, isDefault: false, is4k: false }]); + getSettings().radarr = []; + + const mediaRepo = getRepository(Media); + const requestRepo = getRepository(MediaRequest); + const userRepo = getRepository(User); + + const requestedBy = await userRepo.findOneOrFail({ + where: { email: 'demo@seerr.dev' }, + }); + + // Media is only PARTIALLY_AVAILABLE overall, but the requested season is. + const media = await mediaRepo.save( + new Media({ + mediaType: MediaType.TV, + tmdbId: 67891, + status: MediaStatus.PARTIALLY_AVAILABLE, + status4k: MediaStatus.UNKNOWN, + seasons: [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }), + new Season({ + seasonNumber: 2, + status: MediaStatus.PENDING, + status4k: MediaStatus.UNKNOWN, + }), + ], + }) + ); + + const pending = await requestRepo.save( + new MediaRequest({ + type: MediaType.TV, + status: MediaRequestStatus.PENDING, + media, + requestedBy, + is4k: false, + serverId: 999, + seasons: [ + new SeasonRequest({ + seasonNumber: 1, + status: MediaRequestStatus.PENDING, + }), + ], + updatedAt: new Date('2025-03-01T00:00:00.000Z'), + }) + ); + + const admin = await loginAs('admin@seerr.dev', 'test1234'); + const res = await admin.post(`/request/${pending.id}/approve`); + assert.strictEqual(res.status, 200); + + const persisted = await requestRepo.findOneOrFail({ + where: { id: pending.id }, + relations: { seasons: true }, + }); + assert.strictEqual(persisted.status, MediaRequestStatus.COMPLETED); + assert.ok( + persisted.seasons.every( + (season) => season.status === MediaRequestStatus.COMPLETED + ) + ); + assert.strictEqual(failedNotificationSent(), false); + + const availableCalls = managerSendNotificationMock.calls.filter( + (call) => call.arguments[0] === Notification.MEDIA_AVAILABLE + ); + assert.strictEqual(availableCalls.length, 1); + }); + + it('still fails a series request whose serverId no longer exists when only some requested seasons are available', async () => { + configureSonarr([{ id: 0, isDefault: false, is4k: false }]); + getSettings().radarr = []; + + const mediaRepo = getRepository(Media); + const requestRepo = getRepository(MediaRequest); + const userRepo = getRepository(User); + + const requestedBy = await userRepo.findOneOrFail({ + where: { email: 'demo@seerr.dev' }, + }); + + // Season 1 is available, but this request also covers season 2, which isn't. + const media = await mediaRepo.save( + new Media({ + mediaType: MediaType.TV, + tmdbId: 67892, + status: MediaStatus.PARTIALLY_AVAILABLE, + status4k: MediaStatus.UNKNOWN, + seasons: [ + new Season({ + seasonNumber: 1, + status: MediaStatus.AVAILABLE, + status4k: MediaStatus.UNKNOWN, + }), + new Season({ + seasonNumber: 2, + status: MediaStatus.PENDING, + status4k: MediaStatus.UNKNOWN, + }), + ], + }) + ); + + const pending = await requestRepo.save( + new MediaRequest({ + type: MediaType.TV, + status: MediaRequestStatus.PENDING, + media, + requestedBy, + is4k: false, + serverId: 999, + seasons: [ + new SeasonRequest({ + seasonNumber: 1, + status: MediaRequestStatus.PENDING, + }), + new SeasonRequest({ + seasonNumber: 2, + status: MediaRequestStatus.PENDING, + }), + ], + updatedAt: new Date('2025-03-01T00:00:00.000Z'), + }) + ); + + const admin = await loginAs('admin@seerr.dev', 'test1234'); + const res = await admin.post(`/request/${pending.id}/approve`); + assert.strictEqual(res.status, 200); + + const persisted = await requestRepo.findOneOrFail({ + where: { id: pending.id }, + }); + assert.strictEqual(persisted.status, MediaRequestStatus.FAILED); + assert.ok(failedNotificationSent()); + }); + + it('does not fail a series request when no default Sonarr server is configured (silent skip preserved)', async () => { + configureSonarr([{ isDefault: false, is4k: false }]); + getSettings().radarr = []; + + const pending = await seedPendingTvRequest(); + const admin = await loginAs('admin@seerr.dev', 'test1234'); + + const res = await admin.post(`/request/${pending.id}/approve`); + assert.strictEqual(res.status, 200); + + const persisted = await getRepository(MediaRequest).findOneOrFail({ + where: { id: pending.id }, + }); + assert.strictEqual(persisted.status, MediaRequestStatus.APPROVED); + assert.strictEqual(failedNotificationSent(), false); + }); + + it('fails a movie request with an explicit serverId when the last Radarr server is deleted', async () => { + getSettings().radarr = []; + getSettings().sonarr = []; + + const pending = await seedRequest(MediaRequestStatus.PENDING, { + serverId: 0, + }); + const admin = await loginAs('admin@seerr.dev', 'test1234'); + + const res = await admin.post(`/request/${pending.id}/approve`); + assert.strictEqual(res.status, 200); + + const persisted = await getRepository(MediaRequest).findOneOrFail({ + where: { id: pending.id }, + }); + assert.strictEqual(persisted.status, MediaRequestStatus.FAILED); + + assert.ok(failedNotificationSent()); + }); + + it('fails a series request with an explicit serverId when the last Sonarr server is deleted', async () => { + getSettings().radarr = []; + getSettings().sonarr = []; + + const pending = await seedPendingTvRequest(MediaRequestStatus.PENDING, { + serverId: 0, + }); + const admin = await loginAs('admin@seerr.dev', 'test1234'); + + const res = await admin.post(`/request/${pending.id}/approve`); + assert.strictEqual(res.status, 200); + + const persisted = await getRepository(MediaRequest).findOneOrFail({ + where: { id: pending.id }, + }); + assert.strictEqual(persisted.status, MediaRequestStatus.FAILED); + + assert.ok(failedNotificationSent()); + }); + + it('does not fail a movie request without an override when the last Radarr server is deleted (silent skip preserved)', async () => { + getSettings().radarr = []; + getSettings().sonarr = []; + + const pending = await seedRequest(); + const admin = await loginAs('admin@seerr.dev', 'test1234'); + + const res = await admin.post(`/request/${pending.id}/approve`); + assert.strictEqual(res.status, 200); + + const persisted = await getRepository(MediaRequest).findOneOrFail({ + where: { id: pending.id }, + }); + assert.strictEqual(persisted.status, MediaRequestStatus.APPROVED); + assert.strictEqual(failedNotificationSent(), false); + }); + + it('does not fail a series request without an override when the last Sonarr server is deleted (silent skip preserved)', async () => { + getSettings().radarr = []; + getSettings().sonarr = []; + + const pending = await seedPendingTvRequest(); + const admin = await loginAs('admin@seerr.dev', 'test1234'); + + const res = await admin.post(`/request/${pending.id}/approve`); + assert.strictEqual(res.status, 200); + + const persisted = await getRepository(MediaRequest).findOneOrFail({ + where: { id: pending.id }, + }); + assert.strictEqual(persisted.status, MediaRequestStatus.APPROVED); + assert.strictEqual(failedNotificationSent(), false); + }); +}); + describe('DELETE /request/:requestId, deleted media status restoration', () => { async function seedDeletedMediaScenario() { const userRepo = getRepository(User); diff --git a/server/subscriber/MediaRequestSubscriber.ts b/server/subscriber/MediaRequestSubscriber.ts index b1ee231739..0a78051ef3 100644 --- a/server/subscriber/MediaRequestSubscriber.ts +++ b/server/subscriber/MediaRequestSubscriber.ts @@ -181,10 +181,90 @@ export class MediaRequestSubscriber implements EntitySubscriberInterface { + const tier = entity.is4k ? '4K ' : ''; + const hasExplicitServer = entity.serverId !== null && entity.serverId >= 0; + + if (!hasExplicitServer) { + const servers = getSettings()[service === 'Radarr' ? 'radarr' : 'sonarr']; + logger.warn( + servers.length === 0 + ? `No ${service} server configured, skipping request processing` + : `There is no default ${tier}${service} server configured. Did you set any of your ${tier}${service} servers as default?`, + { + label: 'Media Request', + requestId: entity.id, + mediaId: entity.media.id, + } + ); + return false; + } + + const media = await manager.getRepository(Media).findOne({ + where: { id: entity.media.id }, + }); + if (!media) { + return false; + } + + const statusKey = entity.is4k ? 'status4k' : 'status'; + const isAvailable = + entity.type === MediaType.TV + ? entity.seasons.length > 0 && + entity.seasons.every((rs) => + media.seasons.some( + (s) => + s.seasonNumber === rs.seasonNumber && + s[statusKey] === MediaStatus.AVAILABLE + ) + ) + : media[statusKey] === MediaStatus.AVAILABLE; + + if (isAvailable) { + logger.warn('Media already exists, marking request as COMPLETED', { + label: 'Media Request', + requestId: entity.id, + mediaId: entity.media.id, + }); + + entity.status = MediaRequestStatus.COMPLETED; + if (entity.type === MediaType.TV) { + entity.seasons.forEach((season) => { + season.status = MediaRequestStatus.COMPLETED; + }); + } + await manager.getRepository(MediaRequest).save(entity); + return true; + } + + logger.warn( + `The ${tier}${service} server for this request no longer exists, marking status as FAILED`, + { + label: 'Media Request', + requestId: entity.id, + mediaId: entity.media.id, + serverId: entity.serverId, + is4k: entity.is4k, + } + ); + + if (entity.status !== MediaRequestStatus.FAILED) { + entity.status = MediaRequestStatus.FAILED; + await manager.getRepository(MediaRequest).save(entity); + MediaRequest.sendNotification(entity, media, Notification.MEDIA_FAILED); + } + return false; + } + public async sendToRadarr( entity: MediaRequest, manager: EntityManager - ): Promise { + ): Promise { if ( entity.status === MediaRequestStatus.APPROVED && entity.type === MediaType.MOVIE @@ -193,15 +273,7 @@ export class MediaRequestSubscriber implements EntitySubscriberInterface { + ): Promise { if ( entity.status === MediaRequestStatus.APPROVED && entity.type === MediaType.TV @@ -516,15 +577,7 @@ export class MediaRequestSubscriber implements EntitySubscriberInterface setQuotaLimit(Number(e.target.value))} @@ -74,6 +75,7 @@ const QuotaSelector = ({ ), quotaDays: (