Compare commits

...
Author SHA1 Message Date
Flaminel ad8c5f23cf fixed some early returns causing a retry 2026-06-17 15:47:06 +03:00
Flaminel 9eebeed990 fixed log again 2026-06-17 15:46:32 +03:00
Flaminel a79a60a339 fixed ignored downloads bloating with each run 2026-06-17 15:27:32 +03:00
Flaminel d1bd9fddcc retried webhook malware scans while the torrent metadata is not yet available 2026-06-17 15:06:25 +03:00
Flaminel 96823adcc3 reworked webhooks controller to ProblemDetails errors and [controller] route 2026-06-17 12:14:31 +03:00
Flaminel e0e88147aa added more retries 2026-06-17 12:05:45 +03:00
Flaminel f278a0dad0 fixed log 2026-06-17 12:05:35 +03:00
Flaminel f61300b869 fixed docs link 2026-06-16 23:51:01 +03:00
Flaminel 561c05778c showed only the instance id on the arr card instead of the full webhook url 2026-06-16 23:47:11 +03:00
Flaminel 60d273991d used an enum for arr webhook event type instead of hardcoded strings 2026-06-16 23:43:18 +03:00
Flaminel ddb1042ca5 mapped malware-blocker triggerMode help key to its docs anchor 2026-06-16 23:29:07 +03:00
Flaminel 9a31e86ad8 removed unused method 2026-06-16 23:21:56 +03:00
Flaminel 614e97313e passed WebhookScanTarget to ScheduleMalwareBlockerWebhookRetry instead of individual fields 2026-06-16 23:21:56 +03:00
Flaminel a34a3d3c7e made MalwareBlocker webhook retries conditional on the download not being found 2026-06-16 23:21:56 +03:00
Flaminel f9588d89c0 changed some stuff 2026-06-16 23:21:56 +03:00
Flaminel eacd9346a5 generalized MalwareBlockerTriggerMode to JobTriggerMode 2026-06-16 23:21:56 +03:00
Flaminel 0561c64ddf added tests for MalwareBlocker webhook triggering 2026-06-16 23:21:56 +03:00
Flaminel 304a8e78ee documented MalwareBlocker webhook triggering 2026-06-16 23:21:56 +03:00
Flaminel e008b64a1d added MalwareBlocker webhook frontend (trigger mode and per-instance URL) 2026-06-16 23:21:56 +03:00
Flaminel 4f7e2d33b4 added webhook-triggered targeted MalwareBlocker scan 2026-06-16 23:21:56 +03:00
Flaminel b1b19e5f29 added content-id filter to arr queue fetch 2026-06-16 23:21:56 +03:00
Flaminel 40ab0e9fad added MalwareBlocker trigger mode config and migration 2026-06-16 23:21:56 +03:00
Flaminel fa1801875e Update frontend packages (#633) 2026-06-16 17:17:52 +03:00
Flaminel c6ef6ad979 Use ProblemDetails handling for the API (#632) 2026-06-16 15:26:56 +03:00
Flaminel 74f11f5beb Migrate from DateTime to DateTimeOffset (#629) 2026-06-15 17:15:06 +03:00
Flaminel c0950537ab Fix width of the recent events card (#630) 2026-06-14 17:49:32 +03:00
Flaminel 7cc079c61b Add new feature badge (#628) 2026-06-14 17:04:59 +03:00
Flaminel 7aa3224f4d Add dead torrent handling (#627) 2026-06-14 02:14:10 +03:00
Flaminel 1cc068c2ab Add Transmission label option for unlinked downloads (#626) 2026-06-13 23:09:26 +03:00
Flaminel 28f22f1085 Fix running orphaned files cleanup for unavailable clients (#624) 2026-06-01 00:36:02 +03:00
Flaminel 084f83efca Add option to remove malware if any file is blocked (#621) 2026-05-30 01:33:51 +03:00
Flaminel 26b76908eb Add min seeders to seeding rules (#620) 2026-05-28 17:23:41 +03:00
Flaminel ffc8a0a39a Fix some backgrounds not respecting the custom color (#619) 2026-05-27 20:08:43 +03:00
Flaminel 8ccd93dc97 Add orphaned files cleanup (#618) 2026-05-27 19:26:39 +03:00
Flaminel 1ca935b62b Fix Deluge crashing when removing malware (#308) 2026-05-15 03:53:05 +03:00
Flaminel 90a4909e57 Fix qBittorrent v5.2.0 login (#607) 2026-05-09 03:55:13 +03:00
Flaminel ef8fb2dd0b Fix flaky unit tests (#604) 2026-05-06 10:49:16 +03:00
Flaminel 20ad056400 Add seeding completed Transmission status for Download Cleaner (#603) 2026-05-05 16:53:12 +03:00
Flaminel ab792f5fad Add option to change the category instead of deleting queue items (#602) 2026-05-05 15:59:42 +03:00
Flaminel 48c36fab8f Add paused and queued Deluge states for Download Cleaner (#596) 2026-05-04 14:50:07 +03:00
Flaminel 3553fce597 Fix Seeker failing in dry run mode (#601) 2026-05-04 12:17:19 +03:00
Flaminel c1d2790c8d Fix value step for number inputs when using decimals (#599) 2026-05-03 23:11:31 +03:00
Flaminel 18a9c66ce7 Add name clarification (#598) 2026-05-03 01:40:13 +03:00
Flaminel 7ec60c7ea0 Update application description (#597) 2026-05-03 00:53:41 +03:00
Flaminel a96bc36a1e Add AI usage policy in contributing guide (#593) 2026-04-28 17:39:34 +03:00
Flaminel b575644d5f Improve docs layout (#570) 2026-04-28 16:22:07 +03:00
David Young 13bc71c3cd Add ElfHosted as managed deployment option in the docs (#590) 2026-04-28 13:54:03 +03:00
Flaminel c3f3ee880d Add UI warning when not linking an OIDC account (#587) 2026-04-27 13:19:46 +03:00
Flaminel 8ab4a55595 Remove CORS policy for production environments (#588) 2026-04-27 13:13:06 +03:00
Flaminel 85de80a463 Fix forwarded header parsing (#586) 2026-04-27 12:49:33 +03:00
Flaminel 9f48d3565a Add customizable theme color (#582) 2026-04-26 01:28:07 +03:00
Mike Lonergan db2e3e71db Fix number input eager clamping on keystrokes (#583) 2026-04-26 01:06:26 +03:00
Flaminel 5d400ad854 Fix Custom Format score syncer not being scheduled accordingly (#584) 2026-04-25 23:57:12 +03:00
Flaminel 02a07d4fa3 Add sorting and filters for Seeker stats (#576) 2026-04-25 11:57:38 +03:00
Flaminel 41ca55d615 Fix log config inputs not allowing for zero (#579) 2026-04-22 16:15:56 +03:00
Flaminel 8770a8b18e Add hour intervals for Seeker (#578) 2026-04-21 16:56:58 +03:00
Flaminel 24ecd88cd0 Fix backend page size to be in sync with the UI (#577) 2026-04-21 16:29:59 +03:00
Flaminel 7ed0f307be Add customizable pagination size (#575) 2026-04-20 19:51:02 +03:00
Flaminel 5b500c533e Improve the scrollbar position and visibility (#574) 2026-04-20 15:40:19 +03:00
Flaminel b1ef63ef43 Add sticky headers for pages with tables (#573) 2026-04-20 15:37:45 +03:00
Flaminel f14e345b52 Add full width UI toggle (#572) 2026-04-20 15:33:04 +03:00
Flaminel 89a0d1281f Fix Seeker's filters allowing searching for all types of movies regardless of settings (#567) 2026-04-16 18:21:36 +03:00
Flaminel ee5e7c0819 Replace Moq with NSubstitute for unit tests (#566) 2026-04-16 12:13:36 +03:00
Flaminel d875d88191 Add per-instance Seeker settings (#565) 2026-04-15 23:16:16 +03:00
Flaminel 447db6990a Add item grabbed notification (#564) 2026-04-15 21:51:09 +03:00
Flaminel 4e9d20db0a Improve seeding rule customization (#553) 2026-04-11 17:13:41 +03:00
Flaminel 53fc5eff3b Fix qBittorrent tracker fetching (#555) 2026-04-10 21:00:28 +03:00
Flaminel 69fa09e23a Fix disabled arr instances being processed in some cases (#554) 2026-04-09 14:41:32 +03:00
Flaminel 3360b7a849 Fix db migration not being applied (#552) 2026-04-07 11:51:07 +03:00
Flaminel 80b46df8e5 Add search event reason (#546) 2026-04-06 09:59:31 +03:00
Flaminel 88aa71c343 Fix duplicated grabbed items reported for Sonarr on season packs (#549) 2026-04-05 22:11:48 +03:00
Flaminel 7b80e038cc Fix rTorrent path evaluation for items without a subdirectory (#548) 2026-04-05 22:11:22 +03:00
Flaminel ef280ec398 Fix queue rules upper bound to never allow 0 (#543) 2026-04-03 16:11:12 +03:00
Flaminel 81f6de03e7 Improve Seeker's total number description (#542) 2026-04-03 15:59:23 +03:00
Flaminel 17c3a6b02a Fix duplicated event search when changing instance for Seeker stats (#537) 2026-04-01 13:29:14 +03:00
Flaminel 4903b3137b Add hide unmonitored toggle for quality scores (#535) 2026-04-01 13:28:43 +03:00
Flaminel 868406c95c Fix tags not being excluded by Seeker (#533) 2026-03-31 12:22:45 +03:00
Flaminel 7122b16a7a Add support for separate Download Cleaner settings per download client (#531) 2026-03-30 18:31:48 +03:00
Flaminel b9fbac4ddc Add performance mode description (#532) 2026-03-30 18:30:37 +03:00
Flaminel 33e948d1e7 Update frontend packages (#528) 2026-03-29 17:36:02 +03:00
Flaminel 9f551f151e Fix duplicated events on the dashboard (#527) 2026-03-29 17:22:58 +03:00
Flaminel 9447cb37c0 Fix round robin toggle not changing state correctly (#526) 2026-03-29 17:22:27 +03:00
Flaminel 8183b324a0 Fix Seeker being scheduled when disabled (#523) 2026-03-28 00:25:49 +02:00
Flaminel a6a25de19c Fix Seeker not grouping season packs when checking active downloads (#522) 2026-03-28 00:18:11 +02:00
Flaminel 51a2a1b391 Add missing and upgrade search (#507) 2026-03-27 19:40:09 +02:00
Flaminel d7ab81ddcf Fix Firefox missing the bookmark icon (#520) 2026-03-26 02:14:39 +02:00
Flaminel 8da07d4e93 Fix dashboard logs initial order (#519) 2026-03-26 01:16:04 +02:00
Flaminel 20b93f6853 Fix Transmission ratio not being fetched (#518) 2026-03-24 15:13:39 +02:00
Flaminel 2ce204c1bc Fix animated counter having negative values (#515) 2026-03-23 10:18:11 +02:00
Flaminel d653b7fa3f Remove the suggested apps section (#514) 2026-03-22 23:25:59 +02:00
Flaminel 0dcb42efa2 Add failed import edge case handling for Sonarr and Radarr (#510) 2026-03-22 12:01:08 +02:00
Flaminel 820d254553 Fix PR build bot reacting to all comments (#511) 2026-03-22 12:00:03 +02:00
Flaminel 715ef5711b Add better tracking for dry run events (#512) 2026-03-19 23:53:42 +02:00
Flaminel ea3244367e Fix Windows PR build (#509) 2026-03-17 11:37:11 +02:00
Flaminel f26768bcf7 Add Windows build trigger on PR comment (#508) 2026-03-17 11:29:50 +02:00
Flaminel 87bb92fac0 Fix process time difference between valid and invalid user login (#503) 2026-03-13 14:33:36 +02:00
Flaminel 01dc90bfa7 Fix test workflows cancelling each other (#502) 2026-03-12 22:30:59 +02:00
Flaminel c37e6384a5 Add failed screen before login when the API can not be reached (#501) 2026-03-12 22:16:15 +02:00
Flaminel 70fc955d37 Add OIDC support (#500) 2026-03-12 22:12:20 +02:00
744 changed files with 90651 additions and 14138 deletions

No files matched your search

+7 -1
View File
@@ -2,6 +2,12 @@ name: Build Frontend
on:
workflow_call:
inputs:
ref:
description: 'Git ref to checkout (branch, tag, or SHA). Defaults to github.ref_name.'
type: string
required: false
default: ''
jobs:
build-frontend:
@@ -22,7 +28,7 @@ jobs:
timeout-minutes: 1
with:
repository: ${{ github.repository }}
ref: ${{ github.ref_name }}
ref: ${{ inputs.ref || github.ref_name }}
token: ${{ env.REPO_READONLY_PAT }}
- name: Setup Node.js
@@ -8,6 +8,11 @@ on:
type: string
required: false
default: ''
ref:
description: 'Git ref to checkout (branch, tag, or SHA). Defaults to github.ref_name.'
type: string
required: false
default: ''
jobs:
build-windows-installer:
@@ -58,7 +63,7 @@ jobs:
uses: actions/checkout@v4
with:
repository: ${{ env.githubRepository }}
ref: ${{ github.ref_name }}
ref: ${{ inputs.ref || github.ref_name }}
token: ${{ env.REPO_READONLY_PAT }}
- name: Download frontend artifact
+105
View File
@@ -0,0 +1,105 @@
name: E2E Tests
on:
push:
branches:
- main
paths:
- 'code/**'
- 'e2e/**'
- '.github/workflows/e2e.yml'
pull_request:
paths:
- 'code/**'
- 'e2e/**'
- '.github/workflows/e2e.yml'
workflow_call:
concurrency:
group: E2E Tests-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
e2e:
runs-on: ubuntu-latest
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
suite:
- name: api
make-target: up-api
- name: download-clients
make-target: up-dc
name: e2e (${{ matrix.suite.name }})
steps:
- name: Checkout repository
uses: actions/checkout@v4
timeout-minutes: 1
- name: Get vault secrets
uses: hashicorp/vault-action@v2
with:
url: ${{ secrets.VAULT_HOST }}
method: approle
roleId: ${{ secrets.VAULT_ROLE_ID }}
secretId: ${{ secrets.VAULT_SECRET_ID }}
secrets:
secrets/data/github packages_pat | PACKAGES_PAT
- name: Start services
working-directory: e2e
run: make ${{ matrix.suite.make-target }}
env:
PACKAGES_USERNAME: ${{ github.repository_owner }}
PACKAGES_PAT: ${{ env.PACKAGES_PAT }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
- name: Install E2E dependencies
working-directory: e2e
run: npm ci
- name: Install Playwright browsers
working-directory: e2e
run: npx playwright install --with-deps chromium
- name: Wait for Keycloak
run: |
echo "Waiting for Keycloak realm to be ready..."
timeout 120 bash -c 'until curl -sf http://localhost:8080/realms/cleanuparr-test/.well-known/openid-configuration; do sleep 3; done'
echo "Keycloak ready!"
- name: Wait for app
run: |
echo "Waiting for Cleanuparr to be ready..."
timeout 120 bash -c 'until curl -sf http://localhost:5000/health; do sleep 3; done'
echo "App ready!"
- name: Run E2E tests
working-directory: e2e
run: npx playwright test --project=${{ matrix.suite.name }}
- name: Upload test results
uses: actions/upload-artifact@v4
if: always()
with:
name: e2e-test-results-${{ matrix.suite.name }}
path: |
e2e/playwright-report/
e2e/test-results/
retention-days: 7
- name: Stop services
if: always()
working-directory: e2e
run: docker compose -f docker-compose.e2e.yml down
+181
View File
@@ -0,0 +1,181 @@
name: PR Build (Comment Triggered)
on:
issue_comment:
types: [created]
concurrency:
group: pr-build-${{ github.event.issue.number }}
cancel-in-progress: true
permissions:
issues: write
pull-requests: write
actions: read
jobs:
validate:
runs-on: ubuntu-latest
if: github.event.issue.pull_request != null
outputs:
build_windows: ${{ steps.parse.outputs.build_windows }}
pr_ref: ${{ steps.parse.outputs.pr_ref }}
pr_sha: ${{ steps.parse.outputs.pr_sha }}
pr_number: ${{ steps.parse.outputs.pr_number }}
steps:
- name: Parse command and check permissions
id: parse
uses: actions/github-script@v7
with:
script: |
const comment = context.payload.comment.body.trim();
// Parse supported commands
const commands = {
'/build-windows': 'build_windows'
};
const command = commands[comment];
if (!command) {
console.log(`Comment "${comment}" is not a recognized build command, skipping.`);
core.setOutput('build_windows', 'false');
return;
}
try {
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
content: 'eyes'
});
} catch (e) {
console.log(`Could not add reaction: ${e}`);
}
// Fetch PR details
const pr = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number
});
// Verify PR is open
if (pr.data.state !== 'open') {
console.log('PR is not open, skipping.');
core.setOutput('build_windows', 'false');
return;
}
// Block fork PRs — fork code should not run with access to secrets
const isFork = pr.data.head.repo.full_name !== context.repo.owner + '/' + context.repo.repo;
if (isFork) {
console.log(`PR is from fork ${pr.data.head.repo.full_name}, blocking build.`);
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: 'On-demand builds are not available for PRs from forks.'
});
core.setOutput('build_windows', 'false');
return;
}
// Verify commenter has write access
let permission = 'none';
try {
const resp = await github.rest.repos.getCollaboratorPermissionLevel({
owner: context.repo.owner,
repo: context.repo.repo,
username: context.payload.comment.user.login
});
permission = resp.data.permission;
} catch (_) {}
if (!['admin', 'write'].includes(permission)) {
console.log(`User ${context.payload.comment.user.login} has '${permission}' permission — insufficient.`);
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `@${context.payload.comment.user.login} Only collaborators with write access can trigger builds.`
});
core.setOutput('build_windows', 'false');
return;
}
console.log(`User ${context.payload.comment.user.login} has '${permission}' permission — proceeding with ${command}.`);
core.setOutput(command, 'true');
// Export PR details for downstream jobs
core.setOutput('pr_ref', pr.data.head.ref);
core.setOutput('pr_sha', pr.data.head.sha);
core.setOutput('pr_number', String(pr.data.number));
build-frontend:
needs: validate
if: needs.validate.outputs.build_windows == 'true'
uses: ./.github/workflows/build-frontend.yml
with:
ref: ${{ needs.validate.outputs.pr_ref }}
secrets: inherit
build-windows:
needs: [validate, build-frontend]
if: needs.validate.outputs.build_windows == 'true'
uses: ./.github/workflows/build-windows-installer.yml
with:
ref: ${{ needs.validate.outputs.pr_ref }}
secrets: inherit
post-result:
needs: [validate, build-windows]
if: always() && needs.validate.outputs.build_windows == 'true'
runs-on: ubuntu-latest
steps:
- name: Post result comment
uses: actions/github-script@v7
with:
script: |
const buildResult = '${{ needs.build-windows.result }}';
const runUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
const prRef = '${{ needs.validate.outputs.pr_ref }}';
const prSha = '${{ needs.validate.outputs.pr_sha }}';
const shortSha = prSha.substring(0, 7);
// Skip comment for skipped builds
if (buildResult === 'skipped') {
console.log('Build was skipped, no comment needed.');
return;
}
let body;
if (buildResult === 'success') {
body = [
`Windows installer build **succeeded** for \`${prRef}\` (\`${shortSha}\`).`,
``,
`**Download:** open the [workflow run](${runUrl}), scroll to the **Artifacts** section at the bottom.`,
`The artifact \`Cleanuparr-windows-installer\` is retained for 30 days.`
].join('\n');
} else if (buildResult === 'cancelled') {
body = [
`Windows installer build was **cancelled** for \`${prRef}\` (\`${shortSha}\`).`,
``,
`See the [workflow run](${runUrl}) for details.`
].join('\n');
} else {
body = [
`Windows installer build **failed** for \`${prRef}\` (\`${shortSha}\`).`,
``,
`See the [workflow run](${runUrl}) for details.`
].join('\n');
}
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: parseInt('${{ needs.validate.outputs.pr_number }}'),
body
});
+19 -6
View File
@@ -96,24 +96,33 @@ jobs:
uses: ./.github/workflows/test.yml
secrets: inherit
# Run E2E tests
e2e:
needs: validate
if: ${{ needs.validate.outputs.is_tag == 'true' || github.event.inputs.runTests == 'true' }}
uses: ./.github/workflows/e2e.yml
secrets: inherit
# Build frontend once for all build jobs and cache it
build-frontend:
needs: [validate, test]
needs: [validate, test, e2e]
if: |
always() &&
needs.validate.result == 'success' &&
(needs.test.result == 'success' || needs.test.result == 'skipped') &&
(needs.e2e.result == 'success' || needs.e2e.result == 'skipped') &&
(needs.validate.outputs.is_tag == 'true' || github.event.inputs.buildBinaries == 'true')
uses: ./.github/workflows/build-frontend.yml
secrets: inherit
# Build portable executables
build-executables:
needs: [validate, test, build-frontend]
needs: [validate, test, e2e, build-frontend]
if: |
always() &&
needs.validate.result == 'success' &&
(needs.test.result == 'success' || needs.test.result == 'skipped') &&
(needs.e2e.result == 'success' || needs.e2e.result == 'skipped') &&
needs.build-frontend.result == 'success' &&
(needs.validate.outputs.is_tag == 'true' || github.event.inputs.buildBinaries == 'true')
uses: ./.github/workflows/build-executable.yml
@@ -123,11 +132,12 @@ jobs:
# Build Windows installer
build-windows-installer:
needs: [validate, test, build-frontend]
needs: [validate, test, e2e, build-frontend]
if: |
always() &&
needs.validate.result == 'success' &&
(needs.test.result == 'success' || needs.test.result == 'skipped') &&
(needs.e2e.result == 'success' || needs.e2e.result == 'skipped') &&
needs.build-frontend.result == 'success' &&
(needs.validate.outputs.is_tag == 'true' || github.event.inputs.buildBinaries == 'true')
uses: ./.github/workflows/build-windows-installer.yml
@@ -137,11 +147,12 @@ jobs:
# Build macOS installers (Intel and ARM)
build-macos:
needs: [validate, test, build-frontend]
needs: [validate, test, e2e, build-frontend]
if: |
always() &&
needs.validate.result == 'success' &&
(needs.test.result == 'success' || needs.test.result == 'skipped') &&
(needs.e2e.result == 'success' || needs.e2e.result == 'skipped') &&
needs.build-frontend.result == 'success' &&
(needs.validate.outputs.is_tag == 'true' || github.event.inputs.buildBinaries == 'true')
uses: ./.github/workflows/build-macos-installer.yml
@@ -151,11 +162,12 @@ jobs:
# Build and push Docker image(s)
build-docker:
needs: [validate, test]
needs: [validate, test, e2e]
if: |
always() &&
needs.validate.result == 'success' &&
(needs.test.result == 'success' || needs.test.result == 'skipped') &&
(needs.e2e.result == 'success' || needs.e2e.result == 'skipped') &&
(needs.validate.outputs.is_tag == 'true' || github.event.inputs.buildDocker == 'true')
uses: ./.github/workflows/build-docker.yml
with:
@@ -232,7 +244,7 @@ jobs:
# Summary job
summary:
needs: [validate, test, build-frontend, build-executables, build-windows-installer, build-macos, build-docker]
needs: [validate, test, e2e, build-frontend, build-executables, build-windows-installer, build-macos, build-docker]
runs-on: ubuntu-latest
if: always()
@@ -277,6 +289,7 @@ jobs:
}
print_result "Tests" "${{ needs.test.result }}"
print_result "E2E Tests" "${{ needs.e2e.result }}"
print_result "Frontend Build" "${{ needs.build-frontend.result }}"
print_result "Portable Executables" "${{ needs.build-executables.result }}"
print_result "Windows Installer" "${{ needs.build-windows-installer.result }}"
+1 -1
View File
@@ -15,7 +15,7 @@ on:
# Cancel in-progress runs for the same PR
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
group: Tests-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
+104 -265
View File
@@ -1,83 +1,122 @@
# Cleanuparr - Claude AI Rules
## 🚨 Critical Guidelines
## Rules
**READ THIS FIRST:**
1. ⚠️ **DO NOT break existing functionality** - All features are critical and must continue to work
2. **When in doubt, ASK** - Always clarify before implementing uncertain changes
3. 📋 **Follow existing patterns** - Study the codebase style before making changes
4. 🆕 **Ask before introducing new patterns** - Use current coding standards or get approval first
1. **DO NOT break existing functionality** - All features are critical and must continue to work
2. **When in doubt, ASK** - Don't assume, clarify with the maintainer first
3. **Always read existing code before making changes** - Understand the current architecture and patterns
4. **Follow existing patterns** - Study the codebase style and match it exactly
5. **Ask before introducing new patterns** - Use current coding standards or get approval first
6. **Prefer editing existing files over creating new ones** - Build on existing work
7. **Flag potential gotchas or issues immediately** - Document and report anything unexpected
8. **If unsure about an approach, ask before implementing**
## Project Overview
Cleanuparr is a tool for automating the cleanup of unwanted or blocked files in Sonarr, Radarr, Lidarr, Readarr, Whisparr and supported download clients like qBittorrent, Transmission, Deluge, µTorrent and rTorrent. It provides malware protection, automated cleanup, and queue management for *arr applications.
Cleanuparr is a tool for automating the cleanup of unwanted or blocked files in Sonarr, Radarr, Lidarr, Readarr, Whisparr and supported download clients (qBittorrent, Transmission, Deluge, uTorrent, rTorrent). It provides malware protection, automated cleanup, and queue management for *arr applications.
**Key Features:**
- Strike system for bad downloads
- Malware detection and blocking
- Automatic search triggering after removal
- Automatic search triggering after removal (Seeker)
- Missing and upgrade search
- Orphaned download cleanup with cross-seed support
- Support for multiple notification providers (Discord, etc.)
- Authentication (OIDC, 2FA)
- Notification providers (Apprise, Discord, Gotify, Notifiarr, Ntfy, Pushover, Telegram)
## Architecture & Tech Stack
### Backend
- **.NET 10.0** (C#) with ASP.NET Core
- **Architecture**: Clean Architecture pattern
- `Cleanuparr.Domain` - Domain models and business logic
- **Architecture**: Clean Architecture with `Features/` subdirectory pattern
- `Cleanuparr.Api` - REST API and web host (`Features/` for endpoint groups)
- `Cleanuparr.Application` - Application services and use cases
- `Cleanuparr.Infrastructure` - External integrations (*arr apps, download clients)
- `Cleanuparr.Domain` - Domain models (Entities, Enums, Exceptions)
- `Cleanuparr.Infrastructure` - External integrations (`Features/` for Arr, DownloadClient, Notifications, etc.)
- `Cleanuparr.Persistence` - Data access with EF Core (SQLite)
- `Cleanuparr.Api` - REST API and web host
- `Cleanuparr.Shared` - Shared utilities
- **Database**: SQLite with Entity Framework Core 10.0
- Two separate contexts: `DataContext` and `EventsContext`
- **Database**: SQLite with Entity Framework Core
- Three separate contexts: `DataContext`, `EventsContext`, `UsersContext`
- **Key Libraries**:
- MassTransit (messaging)
- Quartz.NET (scheduling)
- Serilog (logging)
- SignalR (real-time communication)
- **Testing**: xUnit + NSubstitute + Shouldly
- Always use **NSubstitute** for mocking in new tests (Moq is being phased out)
### Frontend
- **Angular 21** with TypeScript 5.9 (standalone components, zoneless, OnPush)
- **UI**: Custom glassmorphism design system (no external UI frameworks)
- **UI**: Custom glassmorphism design system with 33 custom components — no external UI frameworks
- **Icons**: @ng-icons/core + @ng-icons/tabler-icons
- **Design System**: 3-layer SCSS (`_variables` `_tokens` `_themes`), dark/light themes
- **Design System**: 3-layer SCSS (`_variables` -> `_tokens` -> `_themes`), dark/light themes
- **State Management**: @ngrx/signals (Angular signals-based)
- **Real-time Updates**: SignalR (@microsoft/signalr)
- **Real-time Updates**: @microsoft/signalr 10.0.0
- **PWA**: Service Worker support enabled
### Documentation
- **Docusaurus** (TypeScript-based static site)
- Hosted at https://cleanuparr.github.io/Cleanuparr/
## Project Structure
### Deployment
- **Docker** (primary distribution method)
- Standalone executables for Windows, macOS, and Linux
- Platform installers for Windows (.exe) and macOS (.pkg)
## Development Setup
### Prerequisites
- .NET 10.0 SDK
- Node.js 18+
- Git
- (Optional) Make for database migrations
- (Optional) JetBrains Rider or Visual Studio
### GitHub Packages Authentication
Cleanuparr uses GitHub Packages for NuGet dependencies. Configure access:
```bash
dotnet nuget add source \
--username YOUR_GITHUB_USERNAME \
--password YOUR_GITHUB_PAT \
--store-password-in-clear-text \
--name Cleanuparr \
https://nuget.pkg.github.com/Cleanuparr/index.json
```
Cleanuparr/
├── code/
│ ├── backend/
│ │ ├── Cleanuparr.Api/ # REST API (Features/ for endpoint groups)
│ │ ├── Cleanuparr.Api.Tests/ # API layer tests
│ │ ├── Cleanuparr.Application/ # Business logic layer
│ │ ├── Cleanuparr.Domain/ # Domain models
│ │ ├── Cleanuparr.Infrastructure/ # External integrations (Features/ subdirs)
│ │ ├── Cleanuparr.Infrastructure.Tests/
│ │ ├── Cleanuparr.Persistence/ # SQLite data access
│ │ ├── Cleanuparr.Persistence.Tests/
│ │ └── Cleanuparr.Shared/ # Shared utilities
│ ├── frontend/ # Angular 21 application
│ ├── e2e/ # Playwright E2E tests
│ ├── Dockerfile # Multi-stage Docker build
│ ├── entrypoint.sh # Docker entrypoint
│ └── Makefile # Build & migration helpers
├── docs/ # Docusaurus documentation
├── .github/workflows/ # CI/CD pipelines
├── blacklist # Default malware patterns (strict)
├── blacklist_permissive # Less strict malware patterns
├── whitelist # Safe file extensions
└── whitelist_with_subtitles # Includes subtitle formats
```
You need a GitHub PAT with `read:packages` permission.
## Code Standards & Conventions
**IMPORTANT:** Always study existing code in the relevant area before making changes. Match the existing style exactly.
### Backend (C#)
- Follow Microsoft C# Coding Conventions
- Use nullable reference types (`<Nullable>enable</Nullable>`)
- Add XML documentation comments for public APIs
- Use meaningful names - avoid abbreviations unless widely understood
- Keep services focused - single responsibility principle
- New integrations go under `Features/` subdirectories (e.g., `Infrastructure/Features/Arr/`)
### Frontend (TypeScript/Angular)
- All components must be **standalone** with **ChangeDetectionStrategy.OnPush**
- Use `input()` / `output()` function APIs (not `@Input()` / `@Output()` decorators)
- Use Angular **signals** for reactive state (`signal()`, `computed()`, `effect()`)
- Follow the 3-layer SCSS design system (`_variables` -> `_tokens` -> `_themes`)
- **Do not introduce external UI frameworks** (no PrimeNG, Material, Tailwind, etc.)
- Component naming: `{feature}.component.ts`
- Service naming: `{feature}.service.ts`
- **Look at similar existing components before creating new ones**
### Testing
- **Backend**: xUnit + NSubstitute + Shouldly
- Always use **NSubstitute** for mocking (Moq is being phased out)
- Write unit tests for new features and bug fixes
- Use descriptive test names that explain what is being tested
- No frontend unit tests currently
### Git Commit Messages
- Use clear, descriptive messages in imperative mood
- Examples: "Add Discord notification support", "Fix memory leak in download client polling"
- Reference issue numbers when applicable: "Fix #123: Handle null response from Radarr API"
## Development Setup
### Running the Backend
```bash
@@ -101,250 +140,50 @@ cd code/backend
dotnet test
```
### Running Documentation
```bash
cd docs
npm install
npm start
```
Docs run at http://localhost:3000
## Project Structure
```
Cleanuparr/
├── code/
│ ├── backend/
│ │ ├── Cleanuparr.Api/ # API entry point
│ │ ├── Cleanuparr.Application/ # Business logic layer
│ │ ├── Cleanuparr.Domain/ # Domain models
│ │ ├── Cleanuparr.Infrastructure/ # External integrations
│ │ ├── Cleanuparr.Persistence/ # Database & EF Core
│ │ ├── Cleanuparr.Shared/ # Shared utilities
│ │ └── *.Tests/ # Unit tests
│ ├── frontend/ # Angular 21 application
│ ├── ui/ # Built frontend assets
│ ├── Dockerfile # Multi-stage Docker build
│ ├── entrypoint.sh # Docker entrypoint
│ └── Makefile # Build & migration helpers
├── docs/ # Docusaurus documentation
├── Logo/ # Branding assets
├── .github/workflows/ # CI/CD pipelines
├── blacklist # Default malware patterns
├── blacklist_permissive # Alternative blacklist
├── whitelist # Safe file patterns
└── CONTRIBUTING.md # Contribution guidelines
```
## Code Standards & Conventions
**IMPORTANT:** Always study existing code in the relevant area before making changes. Match the existing style exactly.
### Backend (C#)
- Follow [Microsoft C# Coding Conventions](https://docs.microsoft.com/dotnet/csharp/fundamentals/coding-style/coding-conventions)
- Use nullable reference types (`<Nullable>enable</Nullable>`)
- Add XML documentation comments for public APIs
- Write unit tests for business logic
- Use meaningful names - avoid abbreviations unless widely understood
- Keep services focused - single responsibility principle
- **Study existing service implementations before creating new ones**
### Frontend (TypeScript/Angular)
- Follow [Angular Style Guide](https://angular.io/guide/styleguide)
- Use TypeScript strict mode
- All components must be **standalone** (no NgModules) with **ChangeDetectionStrategy.OnPush**
- Use `input()` / `output()` function APIs (not `@Input()` / `@Output()` decorators)
- Use Angular **signals** for reactive state (`signal()`, `computed()`, `effect()`)
- Follow the 3-layer SCSS design system (`_variables``_tokens``_themes`) for styling
- Component naming: `{feature}.component.ts`
- Service naming: `{feature}.service.ts`
- **Look at similar existing components before creating new ones**
### Testing
- Write unit tests for new features and bug fixes
- Use descriptive test names that explain what is being tested
- Backend: xUnit or NUnit conventions
- Frontend: Jasmine/Karma
- **Test that existing functionality still works after changes**
### Git Commit Messages
- Use clear, descriptive messages in imperative mood
- Examples: "Add Discord notification support", "Fix memory leak in download client polling"
- Reference issue numbers when applicable: "Fix #123: Handle null response from Radarr API"
### Discovering Issues
If you encounter potential gotchas, common mistakes, or areas that need special attention during development:
- **Flag them to the maintainer immediately**
- Document them if confirmed
- Consider if they should be added to this guide
## Database Migrations
Cleanuparr uses two separate database contexts:
- **DataContext**: Main application data
- **EventsContext**: Event logging and audit trail
### Creating Migrations
From the `code` directory:
Three separate database contexts, all commands run from the `code` directory:
```bash
# Data migrations
# Data migrations (DataContext)
make migrate-data name=YourMigrationName
# Events migrations
# Events migrations (EventsContext)
make migrate-events name=YourMigrationName
```
Example:
```bash
make migrate-data name=AddDownloadClientConfig
make migrate-events name=AddStrikeEvents
# Users migrations (UsersContext)
make migrate-users name=YourMigrationName
```
## Common Development Workflows
### Adding a New *arr Application Integration
1. Add integration in `Cleanuparr.Infrastructure/Arr/`
1. Add integration in `Cleanuparr.Infrastructure/Features/Arr/`
2. Update domain models in `Cleanuparr.Domain/`
3. Create/update services in `Cleanuparr.Application/`
4. Add API endpoints in `Cleanuparr.Api/`
4. Add API endpoints in `Cleanuparr.Api/Features/Arr/`
5. Update frontend in `code/frontend/src/app/`
6. Document in `docs/docs/`
### Adding a New Download Client
1. Add client implementation in `Cleanuparr.Infrastructure/DownloadClients/`
1. Add client implementation in `Cleanuparr.Infrastructure/Features/DownloadClient/`
2. Follow existing patterns (qBittorrent, Transmission, etc.)
3. Add configuration models to `Cleanuparr.Domain/`
4. Update API and frontend as above
### Adding a New Notification Provider
1. Add provider in `Cleanuparr.Infrastructure/Notifications/`
1. Add provider in `Cleanuparr.Infrastructure/Features/Notifications/`
2. Update configuration models
3. Add UI configuration in frontend
4. Test with actual service
## Important Files
### Configuration Files
- `code/backend/Cleanuparr.Api/appsettings.json` - Backend configuration
- `code/frontend/angular.json` - Angular build configuration
- `code/Dockerfile` - Docker multi-stage build
- `docs/docusaurus.config.ts` - Documentation site config
### CI/CD Workflows
- `.github/workflows/test.yml` - Run tests
- `.github/workflows/build-docker.yml` - Build Docker images
- `.github/workflows/build-executable.yml` - Build standalone executables
- `.github/workflows/release.yml` - Create releases
- `.github/workflows/docs.yml` - Deploy documentation
### Malware Protection
- `blacklist` - Default malware file patterns (strict)
- `blacklist_permissive` - Less strict patterns
- `whitelist` - Known safe file extensions
- `whitelist_with_subtitles` - Includes subtitle formats
## Contributing Guidelines
### Before Starting Work
1. **Announce your intent** - Comment on an issue or create a new one
2. **Wait for approval** from maintainers
3. Fork the repository and create a feature branch
4. Make your changes following code standards
5. Test thoroughly (both manual and automated tests)
6. Submit a PR with clear description and testing notes
### Pull Request Requirements
- Link to related issue
- Clear description of changes
- Evidence of testing
- Updated documentation if needed
- No breaking changes without discussion
## Docker Development
### Build Local Docker Image
```bash
cd code
docker build \
--build-arg PACKAGES_USERNAME=YOUR_GITHUB_USERNAME \
--build-arg PACKAGES_PAT=YOUR_GITHUB_PAT \
-t cleanuparr:local \
-f Dockerfile .
```
### Multi-Architecture Build
```bash
docker buildx build \
--platform linux/amd64,linux/arm64 \
--build-arg PACKAGES_USERNAME=YOUR_GITHUB_USERNAME \
--build-arg PACKAGES_PAT=YOUR_GITHUB_PAT \
-t cleanuparr:local \
-f Dockerfile .
```
## Environment Variables
When running via Docker:
- `PORT` - API port (default: 11011)
- `PUID` - User ID for file permissions
- `PGID` - Group ID for file permissions
- `TZ` - Timezone (e.g., `America/New_York`)
## Security & Safety
- Never commit sensitive data (API keys, tokens, passwords)
- All *arr and download client credentials are stored encrypted
- The malware detection system uses pattern matching on file extensions and names
- Always validate user input on both frontend and backend
- Follow OWASP guidelines for web application security
## Additional Resources
- **Documentation**: https://cleanuparr.github.io/Cleanuparr/
- **Discord**: https://discord.gg/SCtMCgtsc4
- **GitHub Issues**: https://github.com/Cleanuparr/Cleanuparr/issues
- **Releases**: https://github.com/Cleanuparr/Cleanuparr/releases
## Working with Claude - IMPORTANT
### Core Principles
1. **When in doubt, ASK** - Don't assume, clarify with the maintainer first
2. **Don't break existing functionality** - Everything is important and needs to work
3. **Follow existing coding style** - Study the codebase patterns before making changes
4. **Use current coding standards** - If you want to introduce something new, ask first
### When Modifying Code
- **ALWAYS read existing files before suggesting changes**
- Understand the current architecture and patterns
- Prefer editing existing files over creating new ones
- Follow the established conventions in the codebase exactly
- Test changes locally when possible
- **If you're unsure about an approach, ask before implementing**
### When Adding Features
- Review similar existing features first to understand patterns
- Maintain consistency with existing UI/UX patterns
- Update both backend and frontend together
- Add/update documentation
- Consider backwards compatibility
- **Ask about architectural decisions before implementing new patterns**
### When Fixing Bugs
- Understand the root cause before proposing a fix
- **Be careful not to break other functionality** - test related areas
- Add tests to prevent regression
- Update relevant documentation if behavior changes
- Consider if other parts of the codebase might have similar issues
- **Flag any potential gotchas or issues you discover**
## Notes
## Key Gotchas
- **Custom glassmorphism design system** - Do not introduce external UI frameworks (no PrimeNG, Material, Tailwind)
- **All frontend components** must be standalone with OnPush change detection
- **Database migrations** require awareness of all three contexts (Data, Events, Users)
- **Malware blocker** is a critical security feature - changes require careful testing
- **Cross-seed integration** allows keeping torrents that are actively seeding
- **Real-time updates** use SignalR - maintain websocket patterns when adding features
- Use `@ng-icons/core` + `@ng-icons/tabler-icons` for icons (NOT `angular-tabler-icons` which doesn't support Angular 21)
- **Sidebar** stays dark purple in both themes - uses sidebar-specific CSS variables
- The project uses **Clean Architecture** - respect layer boundaries
- Database migrations require both contexts - don't forget EventsContext
- Frontend uses a **custom glassmorphism design system** - don't introduce external UI frameworks (no PrimeNG, Material, etc.)
- All frontend components are **standalone** with **OnPush** change detection
- All downloads from *arr apps are processed through a **strike system**
- The malware blocker is a critical security feature - changes require careful testing
- Cross-seed integration allows keeping torrents that are actively seeding
- Real-time updates use **SignalR** - maintain websocket patterns when adding features
- **Settings dirty tracking** uses JSON snapshot comparison (`buildSnapshot()` + `hasPendingChanges()`)
+7
View File
@@ -4,6 +4,13 @@ Thanks for your interest in contributing to Cleanuparr! This guide will help you
## Before You Start
### AI usage
In this ever-evolving field of work, AI is now the shiny new tool to help programmers work faster and there's nothing wrong with that.
But it is **very** wrong to rely solely on AI tools to write, review and test your code.
**If you do not have a background in programming and you do not intend to test your code properly, please do not submit AI-generated code.** If you still want to help in other ways such as testing features, that would also help a lot!
### Announce Your Intent
Before starting any work, please let us know what you want to contribute:
+12 -9
View File
File diff suppressed because one or more lines are too long.

Before

Width:  |  Height:  |  Size: 112 KiB

After

Width:  |  Height:  |  Size: 69 KiB

+14 -1
View File
@@ -1,7 +1,11 @@
<div align="center">
_Love this project? Give it a ⭐️ and let others know!_
# <img width="24px" src="./Logo/256.png" alt="Cleanuparr"></img> Cleanuparr
_/kliː.nʌp.ər/ — like "cleanuper", someone who does the cleanup. Not "CleanupArr" or "CleanUpArr"._
![Version](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fcleanuparr-status.pages.dev%2Fstatus.json&query=%24.version&logo=git&label=version&color=blue)
![Total Downloads](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fghcr-badge.elias.eu.org%2Fapi%2FCleanuparr%2FCleanuparr%2Fcleanuparr&query=%24.downloadCount&style=flat&logo=docker&label=Total%20Downloads&color=blue)
[![Tests](https://github.com/Cleanuparr/Cleanuparr/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/Cleanuparr/Cleanuparr/actions/workflows/test.yml)
@@ -9,7 +13,9 @@ _Love this project? Give it a ⭐️ and let others know!_
[![Discord](https://img.shields.io/discord/1306721212587573389?color=7289DA&label=Discord&style=for-the-badge&logo=discord)](https://discord.gg/SCtMCgtsc4)
Cleanuparr is a tool for automating the cleanup of unwanted or blocked files in Sonarr, Radarr, and supported download clients like qBittorrent. It removes incomplete or blocked downloads, updates queues, and enforces blacklists or whitelists to manage file selection. After removing blocked content, Cleanuparr can also trigger a search to replace the deleted shows/movies.
</div>
Cleanuparr is an advanced download manager for the Servarr ecosystem. It works with Sonarr, Radarr, Lidarr, Readarr, and Whisparr alongside download clients like qBittorrent, Transmission, and Deluge. Beyond cleaning up stalled, blocked, and malicious downloads, it searches for missing content and quality upgrades, manages seeding, and removes orphaned files.
Cleanuparr was created primarily to address malicious files, such as `*.lnk` or `*.zipx`, that were getting stuck in Sonarr/Radarr and required manual intervention. Some of the reddit posts that made Cleanuparr come to life can be found [here](https://www.reddit.com/r/sonarr/comments/1gqnx16/psa_sonarr_downloaded_a_virus/), [here](https://www.reddit.com/r/sonarr/comments/1gqwklr/sonar_downloaded_a_mkv_file_which_looked_like_a/), [here](https://www.reddit.com/r/sonarr/comments/1gpw2wa/downloaded_waiting_to_import/) and [here](https://www.reddit.com/r/sonarr/comments/1gpi344/downloads_not_importing_no_files_found/).
@@ -23,8 +29,12 @@ Cleanuparr was created primarily to address malicious files, such as `*.lnk` or
> - Remove and block downloads blocked by qBittorrent or by Cleanuparr's **Malware Blocker**.
> - Remove and block known malware based on patterns found by the community.
> - Automatically trigger a search for downloads removed from the arrs.
> - Proactively search for **missing** items across your Radarr and Sonarr libraries.
> - Search for **quality upgrades** for items that haven't met their quality profile's cutoff (a.k.a. **Cutoff Unmet**).
> - Search for **custom format score upgrades** with automatic score tracking.
> - Clean up downloads that have been **seeding** for a certain amount of time.
> - Remove downloads that are **orphaned**/have no **hardlinks**/are not referenced by the arrs anymore (with [cross-seed](https://www.cross-seed.org/) support).
> - Scan configured directories for **files not claimed by any active torrent**, move them to a dedicated orphaned directory, and optionally auto-purge.
> - Notify on strike or download removal.
> - Ignore certain torrent hashes, categories, tags or trackers from being processed by Cleanuparr.
@@ -43,6 +53,7 @@ https://cleanuparr.github.io/Cleanuparr/docs/screenshots
- **Lidarr**
- **Readarr**
- **Whisparr v2**
- **Whisparr v3**
### Download Clients (latest version)
- **qBittorrent**
@@ -74,6 +85,8 @@ docker run -d --name cleanuparr \
For Docker Compose, health checks, and other installation methods, see the [Complete Installation Guide](https://cleanuparr.github.io/Cleanuparr/docs/installation/detailed), but not before reading the [Prerequisites](https://cleanuparr.github.io/Cleanuparr/docs/installation/).
> Prefer not to self-host? A managed Cleanuparr instance is available via [ElfHosted](https://store.elfhosted.com/product-category/personal-stacks/?utm_source=github&utm_medium=readme&utm_campaign=cleanuparr-readme), bundled alongside Sonarr/Radarr to keep your queues tidy (7-day trial).
### 🌐 Access the Web Interface
After installation, open your browser and navigate to:
@@ -11,6 +11,7 @@
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="NSubstitute" Version="5.3.0" />
<PackageReference Include="Shouldly" Version="4.3.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
@@ -24,4 +25,8 @@
<ProjectReference Include="..\Cleanuparr.Api\Cleanuparr.Api.csproj" />
</ItemGroup>
<ItemGroup>
<Content Include="xunit.runner.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>
@@ -1,14 +1,17 @@
using Cleanuparr.Persistence;
using Cleanuparr.Shared.Helpers;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Xunit;
// Integration tests share file-system state (config-dir used by SetupGuardMiddleware),
// so they must be run sequentially to avoid interference between factories.
[assembly: CollectionBehavior(DisableTestParallelization = true)]
namespace Cleanuparr.Api.Tests;
/// <summary>
/// Custom WebApplicationFactory that uses an isolated SQLite database for each test fixture.
/// The database file is created in a temp directory so both DI and static contexts share the same data.
/// Custom WebApplicationFactory that redirects all database contexts to an isolated temp directory
/// </summary>
public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
@@ -18,6 +21,8 @@ public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
_tempDir = Path.Combine(Path.GetTempPath(), $"cleanuparr-test-{Guid.NewGuid():N}");
Directory.CreateDirectory(_tempDir);
ConfigurationPathProvider.SetConfigPath(_tempDir);
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
@@ -26,26 +31,12 @@ public class CustomWebApplicationFactory : WebApplicationFactory<Program>
builder.ConfigureServices(services =>
{
// Remove the existing UsersContext registration
var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<UsersContext>));
if (descriptor != null) services.Remove(descriptor);
// Also remove the DbContext registration itself
var contextDescriptor = services.SingleOrDefault(d => d.ServiceType == typeof(UsersContext));
if (contextDescriptor != null) services.Remove(contextDescriptor);
var dbPath = Path.Combine(_tempDir, "users.db");
services.AddDbContext<UsersContext>(options =>
// Remove all hosted services (Quartz scheduler, BackgroundJobManager) to prevent
// Quartz.Logging.LogProvider.ResolvedLogProvider (a cached Lazy<T>) from being accessed
foreach (var hostedService in services.Where(d => d.ServiceType == typeof(IHostedService)).ToList())
{
options.UseSqlite($"Data Source={dbPath}");
});
// Ensure DB is created
var sp = services.BuildServiceProvider();
using var scope = sp.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<UsersContext>();
db.Database.EnsureCreated();
services.Remove(hostedService);
}
});
}
@@ -0,0 +1,149 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using Shouldly;
namespace Cleanuparr.Api.Tests.Features.Auth;
/// <summary>
/// Integration tests for POST /api/account/feature-views. Verifies that feature "first seen"
/// timestamps are recorded per user, that recording is idempotent, and that the endpoint
/// requires authentication.
/// </summary>
[Collection("Auth Integration Tests")]
[TestCaseOrderer("Cleanuparr.Api.Tests.PriorityOrderer", "Cleanuparr.Api.Tests")]
public class AccountControllerFeatureViewsTests : IClassFixture<CustomWebApplicationFactory>
{
private readonly CustomWebApplicationFactory _factory;
private readonly HttpClient _client;
private static string? _accessToken;
public AccountControllerFeatureViewsTests(CustomWebApplicationFactory factory)
{
_factory = factory;
_client = factory.CreateClient();
if (_accessToken is not null)
{
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
}
}
[Fact, TestPriority(0)]
public async Task Setup_CreateAccountAndLogin()
{
var createResponse = await _client.PostAsJsonAsync("/api/auth/setup/account", new
{
username = "featureadmin",
password = "FeaturePassword123!"
});
createResponse.StatusCode.ShouldBe(HttpStatusCode.Created);
var completeResponse = await _client.PostAsJsonAsync("/api/auth/setup/complete", new { });
completeResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var loginResponse = await _client.PostAsJsonAsync("/api/auth/login", new
{
username = "featureadmin",
password = "FeaturePassword123!"
});
loginResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await loginResponse.Content.ReadFromJsonAsync<JsonElement>();
_accessToken = body.GetProperty("tokens").GetProperty("accessToken").GetString();
_accessToken.ShouldNotBeNullOrEmpty();
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
}
[Fact, TestPriority(1)]
public async Task RecordFeatureViews_NewIds_RecordsTimestampsAndReturnsMapWithAnchor()
{
var response = await _client.PostAsJsonAsync("/api/account/feature-views", new
{
featureIds = new[] { "feature-a", "feature-b" }
});
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<FeatureViewsResponseDto>();
body.ShouldNotBeNull();
body.CreatedAt.ShouldNotBe(default);
body.Views.ShouldContainKey("feature-a");
body.Views.ShouldContainKey("feature-b");
body.Views["feature-a"].Offset.ShouldBe(TimeSpan.Zero);
}
[Fact, TestPriority(2)]
public async Task RecordFeatureViews_DuplicateId_IsIdempotentAndKeepsOriginalTimestamp()
{
var firstResponse = await _client.PostAsJsonAsync("/api/account/feature-views", new
{
featureIds = new[] { "feature-a" }
});
firstResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var firstBody = await firstResponse.Content.ReadFromJsonAsync<FeatureViewsResponseDto>();
var originalTimestamp = firstBody!.Views["feature-a"];
var secondResponse = await _client.PostAsJsonAsync("/api/account/feature-views", new
{
featureIds = new[] { "feature-a" }
});
secondResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var secondBody = await secondResponse.Content.ReadFromJsonAsync<FeatureViewsResponseDto>();
secondBody!.Views["feature-a"].ShouldBe(originalTimestamp);
}
[Fact, TestPriority(3)]
public async Task RecordFeatureViews_WhenUnauthenticated_ReturnsUnauthorized()
{
var unauthClient = _factory.CreateClient();
var response = await unauthClient.PostAsJsonAsync("/api/account/feature-views", new
{
featureIds = new[] { "feature-a" }
});
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact, TestPriority(4)]
public async Task RecordFeatureViews_TooManyIds_ReturnsBadRequest()
{
var tooMany = Enumerable.Range(0, 101).Select(i => $"feature-{i}").ToArray();
var response = await _client.PostAsJsonAsync("/api/account/feature-views", new
{
featureIds = tooMany
});
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
}
[Fact, TestPriority(5)]
public async Task RecordFeatureViews_OverLengthId_IsSkipped()
{
var overLengthId = new string('x', 65);
var response = await _client.PostAsJsonAsync("/api/account/feature-views", new
{
featureIds = new[] { "feature-ok", overLengthId }
});
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<FeatureViewsResponseDto>();
body.ShouldNotBeNull();
body.Views.ShouldContainKey("feature-ok");
body.Views.ShouldNotContainKey(overLengthId);
}
private sealed record FeatureViewsResponseDto
{
public DateTimeOffset CreatedAt { get; init; }
public Dictionary<string, DateTimeOffset> Views { get; init; } = new();
}
}
@@ -0,0 +1,423 @@
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using Cleanuparr.Infrastructure.Features.Auth;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Auth;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
namespace Cleanuparr.Api.Tests.Features.Auth;
/// <summary>
/// Integration tests for the OIDC account linking flow (POST /api/account/oidc/link and
/// GET /api/account/oidc/link/callback). Uses a mock IOidcAuthService that tracks the
/// initiatorUserId passed from StartOidcLink so OidcLinkCallback can complete the flow.
/// </summary>
[Collection("Auth Integration Tests")]
[TestCaseOrderer("Cleanuparr.Api.Tests.PriorityOrderer", "Cleanuparr.Api.Tests")]
public class AccountControllerOidcTests : IClassFixture<AccountControllerOidcTests.OidcLinkWebApplicationFactory>
{
private readonly HttpClient _client;
private readonly OidcLinkWebApplicationFactory _factory;
// Shared across ordered tests
private static string? _accessToken;
public AccountControllerOidcTests(OidcLinkWebApplicationFactory factory)
{
_factory = factory;
_client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
if (_accessToken is not null)
{
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
}
}
[Fact, TestPriority(0)]
public async Task Setup_CreateAccountAndComplete()
{
var createResponse = await _client.PostAsJsonAsync("/api/auth/setup/account", new
{
username = "linkadmin",
password = "LinkPassword123!"
});
createResponse.StatusCode.ShouldBe(HttpStatusCode.Created);
var completeResponse = await _client.PostAsJsonAsync("/api/auth/setup/complete", new { });
completeResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
}
[Fact, TestPriority(1)]
public async Task Login_StoreAccessToken()
{
var response = await _client.PostAsJsonAsync("/api/auth/login", new
{
username = "linkadmin",
password = "LinkPassword123!"
});
var bodyText = await response.Content.ReadAsStringAsync();
response.StatusCode.ShouldBe(HttpStatusCode.OK, $"Login failed. Body: {bodyText}");
var body = JsonSerializer.Deserialize<JsonElement>(bodyText);
body.TryGetProperty("requiresTwoFactor", out var rtf)
.ShouldBeTrue($"Missing 'requiresTwoFactor' in body: {bodyText}");
rtf.GetBoolean().ShouldBeFalse();
// Tokens are nested: { "requiresTwoFactor": false, "tokens": { "accessToken": "..." } }
_accessToken = body.GetProperty("tokens").GetProperty("accessToken").GetString();
_accessToken.ShouldNotBeNullOrEmpty();
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
}
[Fact, TestPriority(2)]
public async Task OidcLink_WhenOidcDisabled_ReturnsBadRequest()
{
var response = await _client.PostAsync("/api/account/oidc/link", null);
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
body.GetProperty("detail").GetString().ShouldContain("OIDC is not enabled");
}
[Fact, TestPriority(3)]
public async Task EnableOidcConfig_ViaDirectDbUpdate()
{
await _factory.EnableOidcAsync();
var statusResponse = await _client.GetAsync("/api/auth/status");
statusResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await statusResponse.Content.ReadFromJsonAsync<JsonElement>();
body.GetProperty("oidcEnabled").GetBoolean().ShouldBeTrue();
}
[Fact, TestPriority(4)]
public async Task OidcLink_WhenAuthenticated_ReturnsAuthorizationUrl()
{
var response = await _client.PostAsync("/api/account/oidc/link", null);
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
var authUrl = body.GetProperty("authorizationUrl").GetString();
authUrl.ShouldNotBeNullOrEmpty();
authUrl.ShouldContain("authorize");
}
[Fact, TestPriority(5)]
public async Task OidcLinkCallback_WithErrorParam_RedirectsToSettingsWithError()
{
var response = await _client.GetAsync("/api/account/oidc/link/callback?error=access_denied");
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
var location = response.Headers.Location?.ToString();
location.ShouldNotBeNull();
location.ShouldContain("/settings/account");
location.ShouldContain("oidc_link_error=failed");
}
[Fact, TestPriority(6)]
public async Task OidcLinkCallback_MissingCodeOrState_RedirectsWithError()
{
var noParams = await _client.GetAsync("/api/account/oidc/link/callback");
noParams.StatusCode.ShouldBe(HttpStatusCode.Redirect);
noParams.Headers.Location?.ToString().ShouldContain("oidc_link_error=failed");
var onlyCode = await _client.GetAsync("/api/account/oidc/link/callback?code=some-code");
onlyCode.StatusCode.ShouldBe(HttpStatusCode.Redirect);
onlyCode.Headers.Location?.ToString().ShouldContain("oidc_link_error=failed");
}
[Fact, TestPriority(7)]
public async Task OidcLinkCallback_ValidFlow_SavesSubjectAndRedirectsToSuccess()
{
// First trigger StartOidcLink so the mock captures the initiatorUserId
var linkResponse = await _client.PostAsync("/api/account/oidc/link", null);
linkResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
// Now simulate the IdP callback with the mock's success state
var callbackResponse = await _client.GetAsync(
$"/api/account/oidc/link/callback?code=valid-code&state={MockOidcAuthService.LinkSuccessState}");
callbackResponse.StatusCode.ShouldBe(HttpStatusCode.Redirect);
var location = callbackResponse.Headers.Location?.ToString();
location.ShouldNotBeNull();
location.ShouldContain("/settings/account");
location.ShouldContain("oidc_link=success");
location.ShouldNotContain("oidc_link_error");
// Verify the subject was saved to config
var savedSubject = await _factory.GetAuthorizedSubjectAsync();
savedSubject.ShouldBe(MockOidcAuthService.LinkedSubject);
}
[Fact, TestPriority(8)]
public async Task OidcLinkCallback_NoInitiatorUserId_RedirectsWithError()
{
var response = await _client.GetAsync(
$"/api/account/oidc/link/callback?code=valid-code&state={MockOidcAuthService.NoInitiatorState}");
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
var location = response.Headers.Location?.ToString();
location.ShouldNotBeNull();
location.ShouldContain("oidc_link_error=failed");
}
[Fact, TestPriority(9)]
public async Task OidcLink_WhenUnauthenticated_ReturnsUnauthorized()
{
// Create a fresh unauthenticated client
var unauthClient = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var response = await unauthClient.PostAsync("/api/account/oidc/link", null);
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
#region Exclusive Mode
[Fact, TestPriority(10)]
public async Task EnableExclusiveMode_ViaDirectDbUpdate()
{
await _factory.SetOidcExclusiveModeAsync(true);
var response = await _client.GetAsync("/api/auth/status");
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
body.GetProperty("oidcExclusiveMode").GetBoolean().ShouldBeTrue();
}
[Fact, TestPriority(11)]
public async Task ChangePassword_Blocked_WhenExclusiveModeActive()
{
var response = await _client.PutAsJsonAsync("/api/account/password", new
{
currentPassword = "LinkPassword123!",
newPassword = "NewPassword456!"
});
response.StatusCode.ShouldBe(HttpStatusCode.Forbidden);
}
[Fact, TestPriority(12)]
public async Task PlexLink_Blocked_WhenExclusiveModeActive()
{
var response = await _client.PostAsync("/api/account/plex/link", null);
response.StatusCode.ShouldBe(HttpStatusCode.Forbidden);
}
[Fact, TestPriority(13)]
public async Task PlexUnlink_Blocked_WhenExclusiveModeActive()
{
var response = await _client.DeleteAsync("/api/account/plex/link");
response.StatusCode.ShouldBe(HttpStatusCode.Forbidden);
}
[Fact, TestPriority(14)]
public async Task OidcConfigUpdate_StillWorks_WhenExclusiveModeActive()
{
var response = await _client.PutAsJsonAsync("/api/account/oidc", new
{
enabled = true,
issuerUrl = "https://mock-oidc-provider.test",
clientId = "test-client",
clientSecret = "test-secret",
scopes = "openid profile email",
authorizedSubject = MockOidcAuthService.LinkedSubject,
providerName = "TestProvider",
redirectUrl = "",
exclusiveMode = true
});
response.StatusCode.ShouldBe(HttpStatusCode.OK);
}
[Fact, TestPriority(15)]
public async Task OidcUnlink_ResetsExclusiveMode()
{
var response = await _client.DeleteAsync("/api/account/oidc/link");
response.StatusCode.ShouldBe(HttpStatusCode.OK);
// Verify exclusive mode was reset
var exclusiveMode = await _factory.GetExclusiveModeAsync();
exclusiveMode.ShouldBeFalse();
}
[Fact, TestPriority(16)]
public async Task DisableExclusiveMode_PasswordChangeWorks_Again()
{
// Re-enable OIDC with a linked subject but without exclusive mode
await _factory.EnableOidcAsync();
await _factory.SetOidcExclusiveModeAsync(false);
var response = await _client.PutAsJsonAsync("/api/account/password", new
{
currentPassword = "LinkPassword123!",
newPassword = "NewPassword789!"
});
response.StatusCode.ShouldBe(HttpStatusCode.OK);
}
#endregion
#region Test Infrastructure
public class OidcLinkWebApplicationFactory : CustomWebApplicationFactory
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
builder.ConfigureServices(services =>
{
var oidcDescriptor = services.SingleOrDefault(d => d.ServiceType == typeof(IOidcAuthService));
if (oidcDescriptor != null) services.Remove(oidcDescriptor);
services.AddSingleton<IOidcAuthService, MockOidcAuthService>();
});
}
public async Task EnableOidcAsync()
{
using var scope = Services.CreateScope();
var usersContext = scope.ServiceProvider.GetRequiredService<UsersContext>();
var user = await usersContext.Users.FirstOrDefaultAsync();
if (user is null)
{
return;
}
user.Oidc = new OidcConfig
{
Enabled = true,
IssuerUrl = "https://mock-oidc-provider.test",
ClientId = "test-client",
ClientSecret = "test-secret",
Scopes = "openid profile email",
AuthorizedSubject = "initial-subject",
ProviderName = "TestProvider"
};
await usersContext.SaveChangesAsync();
}
public async Task<string?> GetAuthorizedSubjectAsync()
{
using var scope = Services.CreateScope();
var usersContext = scope.ServiceProvider.GetRequiredService<UsersContext>();
var user = await usersContext.Users.AsNoTracking().FirstOrDefaultAsync();
return user?.Oidc.AuthorizedSubject;
}
public async Task SetOidcExclusiveModeAsync(bool enabled)
{
using var scope = Services.CreateScope();
var usersContext = scope.ServiceProvider.GetRequiredService<UsersContext>();
var user = await usersContext.Users.FirstOrDefaultAsync();
if (user is not null)
{
user.Oidc.ExclusiveMode = enabled;
await usersContext.SaveChangesAsync();
}
}
public async Task<bool> GetExclusiveModeAsync()
{
using var scope = Services.CreateScope();
var usersContext = scope.ServiceProvider.GetRequiredService<UsersContext>();
var user = await usersContext.Users.AsNoTracking().FirstOrDefaultAsync();
return user?.Oidc.ExclusiveMode ?? false;
}
}
private sealed class MockOidcAuthService : IOidcAuthService
{
public const string LinkSuccessState = "mock-link-success-state";
public const string NoInitiatorState = "mock-no-initiator-state";
public const string LinkedSubject = "newly-linked-subject-123";
private string? _lastInitiatorUserId;
private readonly ConcurrentDictionary<string, OidcTokenExchangeResult> _oneTimeCodes = new();
public Task<OidcAuthorizationResult> StartAuthorization(string redirectUri, string? initiatorUserId = null)
{
_lastInitiatorUserId = initiatorUserId;
return Task.FromResult(new OidcAuthorizationResult
{
AuthorizationUrl = $"https://mock-oidc-provider.test/authorize?state={LinkSuccessState}",
State = LinkSuccessState
});
}
public Task<OidcCallbackResult> HandleCallback(string code, string state, string redirectUri)
{
if (state == LinkSuccessState)
{
return Task.FromResult(new OidcCallbackResult
{
Success = true,
Subject = LinkedSubject,
PreferredUsername = "linkuser",
Email = "link@example.com",
InitiatorUserId = _lastInitiatorUserId
});
}
if (state == NoInitiatorState)
{
return Task.FromResult(new OidcCallbackResult
{
Success = true,
Subject = LinkedSubject,
InitiatorUserId = null // No initiator — controller should redirect with error
});
}
return Task.FromResult(new OidcCallbackResult
{
Success = false,
Error = "Invalid or expired OIDC state"
});
}
public string StoreOneTimeCode(string accessToken, string refreshToken, int expiresIn)
{
var code = Guid.NewGuid().ToString("N");
_oneTimeCodes.TryAdd(code, new OidcTokenExchangeResult
{
AccessToken = accessToken,
RefreshToken = refreshToken,
ExpiresIn = expiresIn
});
return code;
}
public OidcTokenExchangeResult? ExchangeOneTimeCode(string code) =>
_oneTimeCodes.TryRemove(code, out var result) ? result : null;
}
#endregion
}
@@ -10,6 +10,7 @@ namespace Cleanuparr.Api.Tests.Features.Auth;
/// Uses a single shared factory to avoid static state conflicts.
/// Tests are ordered to build on each other: setup → login → protected endpoints.
/// </summary>
[Collection("Auth Integration Tests")]
[TestCaseOrderer("Cleanuparr.Api.Tests.PriorityOrderer", "Cleanuparr.Api.Tests")]
public class AuthControllerTests : IClassFixture<CustomWebApplicationFactory>
{
@@ -243,6 +244,30 @@ public class AuthControllerTests : IClassFixture<CustomWebApplicationFactory>
body.GetProperty("setupCompleted").GetBoolean().ShouldBeTrue();
}
[Fact, TestPriority(16)]
public async Task OidcExchange_WithNonexistentCode_ReturnsNotFound()
{
var response = await _client.PostAsJsonAsync("/api/auth/oidc/exchange", new
{
code = "nonexistent-one-time-code"
});
response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
}
[Fact, TestPriority(17)]
public async Task AuthStatus_IncludesOidcFields()
{
var response = await _client.GetAsync("/api/auth/status");
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
// Verify OIDC fields exist in the response (values depend on shared static DB state)
body.TryGetProperty("oidcEnabled", out _).ShouldBeTrue();
body.TryGetProperty("oidcProviderName", out _).ShouldBeTrue();
}
#region TOTP helpers
private static string _totpSecret = "";
@@ -0,0 +1,182 @@
using System.Diagnostics;
using System.Net;
using System.Net.Http.Json;
using Cleanuparr.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
namespace Cleanuparr.Api.Tests.Features.Auth;
/// <summary>
/// Tests that the login endpoint always runs BCrypt verification regardless of
/// username validity, preventing timing-based username enumeration.
/// </summary>
[Collection("Login Timing Tests")]
[TestCaseOrderer("Cleanuparr.Api.Tests.PriorityOrderer", "Cleanuparr.Api.Tests")]
public class LoginTimingTests : IClassFixture<TimingTestWebApplicationFactory>
{
private readonly HttpClient _client;
private readonly TimingTestWebApplicationFactory _factory;
public LoginTimingTests(TimingTestWebApplicationFactory factory)
{
_factory = factory;
_client = factory.CreateClient();
}
[Fact, TestPriority(0)]
public async Task Login_NoUserExists_StillCallsPasswordVerification()
{
_factory.TrackingPasswordService.Reset();
var response = await _client.PostAsJsonAsync("/api/auth/login", new
{
username = "nouser",
password = "SomePassword123!"
});
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
_factory.TrackingPasswordService.VerifyPasswordCallCount.ShouldBeGreaterThanOrEqualTo(1);
}
[Fact, TestPriority(1)]
public async Task Setup_CreateAccountAndComplete()
{
var createResponse = await _client.PostAsJsonAsync("/api/auth/setup/account", new
{
username = "timingtest",
password = "TimingTestPassword123!"
});
createResponse.StatusCode.ShouldBe(HttpStatusCode.Created);
var completeResponse = await _client.PostAsJsonAsync("/api/auth/setup/complete", new { });
completeResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
}
[Fact, TestPriority(2)]
public async Task Login_ValidUsername_CallsPasswordVerification()
{
_factory.TrackingPasswordService.Reset();
await _client.PostAsJsonAsync("/api/auth/login", new
{
username = "timingtest",
password = "TimingTestPassword123!"
});
_factory.TrackingPasswordService.VerifyPasswordCallCount.ShouldBeGreaterThanOrEqualTo(1);
}
[Fact, TestPriority(3)]
public async Task Login_NonexistentUsername_StillCallsPasswordVerification()
{
_factory.TrackingPasswordService.Reset();
var response = await _client.PostAsJsonAsync("/api/auth/login", new
{
username = "doesnotexist",
password = "SomePassword123!"
});
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
_factory.TrackingPasswordService.VerifyPasswordCallCount.ShouldBeGreaterThanOrEqualTo(1);
}
[Fact, TestPriority(4)]
public async Task Login_LockedOutUser_StillCallsPasswordVerification()
{
// Set lockout state directly in the database to avoid timing sensitivity
using (var scope = _factory.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<UsersContext>();
var user = await context.Users.FirstAsync();
user.FailedLoginAttempts = 5;
user.LockoutEnd = DateTime.UtcNow.AddMinutes(5);
await context.SaveChangesAsync();
}
_factory.TrackingPasswordService.Reset();
var response = await _client.PostAsJsonAsync("/api/auth/login", new
{
username = "timingtest",
password = "WrongPassword!"
});
response.StatusCode.ShouldBe(HttpStatusCode.TooManyRequests);
_factory.TrackingPasswordService.VerifyPasswordCallCount.ShouldBeGreaterThanOrEqualTo(1);
// Reset lockout for subsequent tests
using (var scope = _factory.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<UsersContext>();
var user = await context.Users.FirstAsync();
user.FailedLoginAttempts = 0;
user.LockoutEnd = null;
await context.SaveChangesAsync();
}
}
[Fact, TestPriority(5)]
public async Task Login_TimingConsistency_InvalidAndValidUsernamesTakeSimilarTime()
{
const int iterations = 10;
// Warm up the server and BCrypt static init
await _client.PostAsJsonAsync("/api/auth/login", new
{
username = "warmup",
password = "WarmupPassword123!"
});
var invalidTimings = new List<long>(iterations);
var validTimings = new List<long>(iterations);
for (var i = 0; i < iterations; i++)
{
// Alternate to avoid ordering bias
var invalidSw = Stopwatch.StartNew();
await _client.PostAsJsonAsync("/api/auth/login", new
{
username = $"nonexistent_{i}",
password = "SomePassword123!"
});
invalidSw.Stop();
invalidTimings.Add(invalidSw.ElapsedMilliseconds);
var validSw = Stopwatch.StartNew();
await _client.PostAsJsonAsync("/api/auth/login", new
{
username = "timingtest",
password = "WrongPasswordForTiming!"
});
validSw.Stop();
validTimings.Add(validSw.ElapsedMilliseconds);
}
var invalidMedian = Median(invalidTimings);
var validMedian = Median(validTimings);
// The invalid-username path must not be suspiciously fast
invalidMedian.ShouldBeGreaterThan(50,
$"Non-existent username median too fast ({invalidMedian}ms) — BCrypt may have been skipped");
// Medians should be in the same ballpark
var ratio = invalidMedian > validMedian
? (double)invalidMedian / validMedian
: (double)validMedian / invalidMedian;
ratio.ShouldBeLessThan(3.0,
$"Timing difference too large: invalid median={invalidMedian}ms, valid median={validMedian}ms (ratio={ratio:F1}x)");
}
private static long Median(List<long> values)
{
values.Sort();
var mid = values.Count / 2;
return values.Count % 2 == 0
? (values[mid - 1] + values[mid]) / 2
: values[mid];
}
}
@@ -0,0 +1,630 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Cleanuparr.Infrastructure.Features.Auth;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Auth;
using Cleanuparr.Shared.Helpers;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Shouldly;
namespace Cleanuparr.Api.Tests.Features.Auth;
/// <summary>
/// Integration tests for the OIDC authentication flow.
/// Uses a mock IOidcAuthService to simulate IdP behavior.
/// Tests are ordered to build on each other: setup → enable OIDC → test flow.
/// </summary>
[Collection("Auth Integration Tests")]
[TestCaseOrderer("Cleanuparr.Api.Tests.PriorityOrderer", "Cleanuparr.Api.Tests")]
public class OidcAuthControllerTests : IClassFixture<OidcAuthControllerTests.OidcWebApplicationFactory>
{
private readonly HttpClient _client;
private readonly OidcWebApplicationFactory _factory;
public OidcAuthControllerTests(OidcWebApplicationFactory factory)
{
_factory = factory;
_client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false // We want to inspect redirects
});
}
[Fact, TestPriority(0)]
public async Task OidcStart_BeforeSetup_ReturnsBadRequest()
{
var response = await _client.PostAsync("/api/auth/oidc/start", null);
// OIDC start is on /api/auth/ path (not blocked by SetupGuardMiddleware)
// but the controller returns BadRequest because OIDC is not configured
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
}
[Fact, TestPriority(1)]
public async Task Setup_CreateAccountAndComplete()
{
// Create account
var createResponse = await _client.PostAsJsonAsync("/api/auth/setup/account", new
{
username = "admin",
password = "TestPassword123!"
});
createResponse.StatusCode.ShouldBe(HttpStatusCode.Created);
// Complete setup (skip 2FA for this test suite)
var completeResponse = await _client.PostAsJsonAsync("/api/auth/setup/complete", new { });
completeResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
}
[Fact, TestPriority(2)]
public async Task OidcStart_WhenDisabled_ReturnsBadRequest()
{
var response = await _client.PostAsync("/api/auth/oidc/start", null);
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
response.Content.Headers.ContentType!.MediaType.ShouldBe("application/problem+json");
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
body.GetProperty("detail").GetString()!.ShouldContain("OIDC is not enabled");
body.GetProperty("traceId").GetString().ShouldNotBeNullOrEmpty();
}
[Fact, TestPriority(3)]
public async Task OidcExchange_WhenDisabled_ReturnsNotFound()
{
var response = await _client.PostAsJsonAsync("/api/auth/oidc/exchange", new
{
code = "some-random-code"
});
response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
}
[Fact, TestPriority(4)]
public async Task OidcCallback_WithErrorParam_RedirectsToLoginWithError()
{
var response = await _client.GetAsync("/api/auth/oidc/callback?error=access_denied");
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
var location = response.Headers.Location?.ToString();
location.ShouldNotBeNull();
location.ShouldContain("/auth/login");
location.ShouldContain("oidc_error=provider_error");
}
[Fact, TestPriority(5)]
public async Task OidcCallback_WithoutCodeOrState_RedirectsToLoginWithError()
{
var response = await _client.GetAsync("/api/auth/oidc/callback");
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
var location = response.Headers.Location?.ToString();
location.ShouldNotBeNull();
location.ShouldContain("oidc_error=invalid_request");
}
[Fact, TestPriority(6)]
public async Task OidcCallback_WithOnlyCode_RedirectsToLoginWithError()
{
var response = await _client.GetAsync("/api/auth/oidc/callback?code=some-code");
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
var location = response.Headers.Location?.ToString();
location.ShouldNotBeNull();
location.ShouldContain("oidc_error=invalid_request");
}
[Fact, TestPriority(7)]
public async Task OidcCallback_WithInvalidState_RedirectsToLoginWithError()
{
// Even with code and state, if the state is invalid the mock will return failure
var response = await _client.GetAsync("/api/auth/oidc/callback?code=some-code&state=invalid-state");
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
var location = response.Headers.Location?.ToString();
location.ShouldNotBeNull();
location.ShouldContain("oidc_error=authentication_failed");
}
[Fact, TestPriority(8)]
public async Task EnableOidcConfig_ViaDirectDbUpdate()
{
// Simulate enabling OIDC via direct DB manipulation (since we'd normally do this through settings UI)
await _factory.EnableOidcAsync();
// Verify auth status reflects OIDC enabled
var response = await _client.GetAsync("/api/auth/status");
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
body.GetProperty("oidcEnabled").GetBoolean().ShouldBeTrue();
body.GetProperty("oidcProviderName").GetString().ShouldBe("TestProvider");
}
[Fact, TestPriority(9)]
public async Task OidcStart_WhenEnabled_ReturnsAuthorizationUrl()
{
var response = await _client.PostAsync("/api/auth/oidc/start", null);
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
var authUrl = body.GetProperty("authorizationUrl").GetString();
authUrl.ShouldNotBeNullOrEmpty();
authUrl.ShouldContain("authorize");
}
[Fact, TestPriority(10)]
public async Task OidcCallback_ValidFlow_RedirectsWithOneTimeCode()
{
// Use the mock's valid state to simulate a successful callback
var response = await _client.GetAsync(
$"/api/auth/oidc/callback?code=valid-auth-code&state={MockOidcAuthService.ValidState}");
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
var location = response.Headers.Location?.ToString();
location.ShouldNotBeNull();
location.ShouldContain("/auth/oidc/callback");
location.ShouldContain("code=");
// Should NOT contain oidc_error
location.ShouldNotContain("oidc_error");
}
[Fact, TestPriority(11)]
public async Task OidcExchange_ValidOneTimeCode_ReturnsTokens()
{
// First, trigger a valid callback to get a one-time code
var callbackResponse = await _client.GetAsync(
$"/api/auth/oidc/callback?code=valid-auth-code&state={MockOidcAuthService.ValidState}");
callbackResponse.StatusCode.ShouldBe(HttpStatusCode.Redirect);
var location = callbackResponse.Headers.Location?.ToString();
location.ShouldNotBeNull();
// Extract the one-time code from the redirect URL
var uri = new Uri("http://localhost" + location);
var queryParams = System.Web.HttpUtility.ParseQueryString(uri.Query);
var oneTimeCode = queryParams["code"];
oneTimeCode.ShouldNotBeNullOrEmpty();
// Exchange the one-time code for tokens
var exchangeResponse = await _client.PostAsJsonAsync("/api/auth/oidc/exchange", new
{
code = oneTimeCode
});
exchangeResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await exchangeResponse.Content.ReadFromJsonAsync<JsonElement>();
body.GetProperty("accessToken").GetString().ShouldNotBeNullOrEmpty();
body.GetProperty("refreshToken").GetString().ShouldNotBeNullOrEmpty();
body.GetProperty("expiresIn").GetInt32().ShouldBeGreaterThan(0);
}
[Fact, TestPriority(12)]
public async Task OidcExchange_SameCodeTwice_SecondFails()
{
// First, trigger a valid callback
var callbackResponse = await _client.GetAsync(
$"/api/auth/oidc/callback?code=valid-auth-code&state={MockOidcAuthService.ValidState}");
var location = callbackResponse.Headers.Location?.ToString()!;
var uri = new Uri("http://localhost" + location);
var queryParams = System.Web.HttpUtility.ParseQueryString(uri.Query);
var oneTimeCode = queryParams["code"]!;
// First exchange succeeds
var response1 = await _client.PostAsJsonAsync("/api/auth/oidc/exchange", new { code = oneTimeCode });
response1.StatusCode.ShouldBe(HttpStatusCode.OK);
// Second exchange with same code fails
var response2 = await _client.PostAsJsonAsync("/api/auth/oidc/exchange", new { code = oneTimeCode });
response2.StatusCode.ShouldBe(HttpStatusCode.NotFound);
}
[Fact, TestPriority(13)]
public async Task OidcExchange_InvalidCode_ReturnsNotFound()
{
var response = await _client.PostAsJsonAsync("/api/auth/oidc/exchange", new
{
code = "completely-invalid-code"
});
response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
}
[Fact, TestPriority(14)]
public async Task OidcCallback_UnauthorizedSubject_RedirectsWithError()
{
// Use the mock's state that returns a different subject
var response = await _client.GetAsync(
$"/api/auth/oidc/callback?code=valid-auth-code&state={MockOidcAuthService.WrongSubjectState}");
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
var location = response.Headers.Location?.ToString();
location.ShouldNotBeNull();
location.ShouldContain("oidc_error=unauthorized");
}
[Fact, TestPriority(15)]
public async Task AuthStatus_IncludesOidcFields()
{
var response = await _client.GetAsync("/api/auth/status");
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
body.GetProperty("setupCompleted").GetBoolean().ShouldBeTrue();
body.GetProperty("oidcEnabled").GetBoolean().ShouldBeTrue();
body.GetProperty("oidcProviderName").GetString().ShouldBe("TestProvider");
}
[Fact, TestPriority(16)]
public async Task PasswordLogin_StillWorks_AfterOidcEnabled()
{
var response = await _client.PostAsJsonAsync("/api/auth/login", new
{
username = "admin",
password = "TestPassword123!"
});
// Should succeed (no 2FA since we skipped it in setup)
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
// No 2FA, so should have tokens directly
body.GetProperty("requiresTwoFactor").GetBoolean().ShouldBeFalse();
}
[Fact, TestPriority(17)]
public async Task OidcStatus_WhenSubjectCleared_StillEnabled()
{
// Clearing the authorized subject should NOT disable OIDC — it just means any user can log in
await _factory.SetOidcAuthorizedSubjectAsync("");
var response = await _client.GetAsync("/api/auth/status");
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
body.GetProperty("oidcEnabled").GetBoolean().ShouldBeTrue();
// Restore for subsequent tests
await _factory.SetOidcAuthorizedSubjectAsync(MockOidcAuthService.AuthorizedSubject);
}
[Fact, TestPriority(17)]
public async Task OidcStatus_WhenMissingIssuerUrl_ReturnsFalse()
{
// OIDC should be disabled when essential config (IssuerUrl) is missing
await _factory.SetOidcIssuerUrlAsync("");
var response = await _client.GetAsync("/api/auth/status");
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
body.GetProperty("oidcEnabled").GetBoolean().ShouldBeFalse();
// Restore for subsequent tests
await _factory.SetOidcIssuerUrlAsync("https://mock-oidc-provider.test");
}
[Fact, TestPriority(17)]
public async Task OidcCallback_WithoutLinkedSubject_AllowsAnyUser()
{
// Clear the authorized subject — any OIDC user should be allowed
await _factory.SetOidcAuthorizedSubjectAsync("");
// Use the "wrong subject" state — this returns a different subject than the authorized one
// With no linked subject, it should still succeed
var response = await _client.GetAsync(
$"/api/auth/oidc/callback?code=valid-auth-code&state={MockOidcAuthService.WrongSubjectState}");
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
var location = response.Headers.Location?.ToString();
location.ShouldNotBeNull();
location.ShouldContain("code=");
location.ShouldNotContain("oidc_error");
// Restore for subsequent tests
await _factory.SetOidcAuthorizedSubjectAsync(MockOidcAuthService.AuthorizedSubject);
}
[Fact, TestPriority(18)]
public async Task OidcExchange_RandomCode_ReturnsNotFound()
{
var response = await _client.PostAsJsonAsync("/api/auth/oidc/exchange", new
{
code = "completely-random-nonexistent-code"
});
response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
}
#region Exclusive Mode
[Fact, TestPriority(19)]
public async Task EnableExclusiveMode_AuthStatusReflectsIt()
{
await _factory.SetOidcExclusiveModeAsync(true);
var response = await _client.GetAsync("/api/auth/status");
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
body.GetProperty("oidcExclusiveMode").GetBoolean().ShouldBeTrue();
}
[Fact, TestPriority(20)]
public async Task PasswordLogin_Blocked_WhenExclusiveModeActive()
{
var response = await _client.PostAsJsonAsync("/api/auth/login", new
{
username = "admin",
password = "TestPassword123!"
});
response.StatusCode.ShouldBe(HttpStatusCode.Forbidden);
}
[Fact, TestPriority(21)]
public async Task TwoFactorLogin_Blocked_WhenExclusiveModeActive()
{
var response = await _client.PostAsJsonAsync("/api/auth/login/2fa", new
{
loginToken = "some-token",
code = "123456"
});
response.StatusCode.ShouldBe(HttpStatusCode.Forbidden);
}
[Fact, TestPriority(22)]
public async Task PlexLoginPin_Blocked_WhenExclusiveModeActive()
{
var response = await _client.PostAsync("/api/auth/login/plex/pin", null);
response.StatusCode.ShouldBe(HttpStatusCode.Forbidden);
}
[Fact, TestPriority(23)]
public async Task PlexLoginVerify_Blocked_WhenExclusiveModeActive()
{
var response = await _client.PostAsJsonAsync("/api/auth/login/plex/verify", new
{
pinId = 12345
});
response.StatusCode.ShouldBe(HttpStatusCode.Forbidden);
}
[Fact, TestPriority(24)]
public async Task OidcStart_StillWorks_WhenExclusiveModeActive()
{
var response = await _client.PostAsync("/api/auth/oidc/start", null);
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
body.GetProperty("authorizationUrl").GetString().ShouldNotBeNullOrEmpty();
}
[Fact, TestPriority(25)]
public async Task OidcCallback_StillWorks_WhenExclusiveModeActive()
{
var response = await _client.GetAsync(
$"/api/auth/oidc/callback?code=valid-auth-code&state={MockOidcAuthService.ValidState}");
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
var location = response.Headers.Location?.ToString();
location.ShouldNotBeNull();
location.ShouldContain("code=");
location.ShouldNotContain("oidc_error");
}
[Fact, TestPriority(26)]
public async Task DisableExclusiveMode_PasswordLoginWorks_Again()
{
await _factory.SetOidcExclusiveModeAsync(false);
var response = await _client.PostAsJsonAsync("/api/auth/login", new
{
username = "admin",
password = "TestPassword123!"
});
response.StatusCode.ShouldBe(HttpStatusCode.OK);
}
#endregion
#region Test Infrastructure
/// <summary>
/// Custom factory that replaces IOidcAuthService with a mock for testing.
/// </summary>
public class OidcWebApplicationFactory : WebApplicationFactory<Program>
{
private readonly string _tempDir;
public OidcWebApplicationFactory()
{
_tempDir = Path.Combine(Path.GetTempPath(), $"cleanuparr-oidc-test-{Guid.NewGuid():N}");
Directory.CreateDirectory(_tempDir);
// Redirect all database contexts to this factory's temp directory.
ConfigurationPathProvider.SetConfigPath(_tempDir);
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Testing");
builder.ConfigureServices(services =>
{
// Replace IOidcAuthService with mock
var oidcDescriptor = services.SingleOrDefault(d => d.ServiceType == typeof(IOidcAuthService));
if (oidcDescriptor != null) services.Remove(oidcDescriptor);
services.AddSingleton<IOidcAuthService, MockOidcAuthService>();
// Remove all hosted services (Quartz scheduler, BackgroundJobManager) to prevent
// Quartz.Logging.LogProvider.ResolvedLogProvider (a cached Lazy<T>) from being accessed
// with a disposed ILoggerFactory from the previous factory lifecycle.
// Auth tests don't depend on background job scheduling, so this is safe.
foreach (var hostedService in services.Where(d => d.ServiceType == typeof(IHostedService)).ToList())
services.Remove(hostedService);
});
}
/// <summary>
/// Enables OIDC on the user in the UsersContext database.
/// </summary>
public async Task EnableOidcAsync()
{
using var scope = Services.CreateScope();
var usersContext = scope.ServiceProvider.GetRequiredService<UsersContext>();
var user = await usersContext.Users.FirstOrDefaultAsync();
if (user is null)
{
return;
}
user.Oidc = new OidcConfig
{
Enabled = true,
IssuerUrl = "https://mock-oidc-provider.test",
ClientId = "test-client",
ClientSecret = "test-secret",
Scopes = "openid profile email",
AuthorizedSubject = MockOidcAuthService.AuthorizedSubject,
ProviderName = "TestProvider"
};
await usersContext.SaveChangesAsync();
}
public async Task SetOidcIssuerUrlAsync(string issuerUrl)
{
using var scope = Services.CreateScope();
var usersContext = scope.ServiceProvider.GetRequiredService<UsersContext>();
var user = await usersContext.Users.FirstOrDefaultAsync();
if (user is not null)
{
user.Oidc.IssuerUrl = issuerUrl;
await usersContext.SaveChangesAsync();
}
}
public async Task SetOidcAuthorizedSubjectAsync(string subject)
{
using var scope = Services.CreateScope();
var usersContext = scope.ServiceProvider.GetRequiredService<UsersContext>();
var user = await usersContext.Users.FirstOrDefaultAsync();
if (user is not null)
{
user.Oidc.AuthorizedSubject = subject;
await usersContext.SaveChangesAsync();
}
}
public async Task SetOidcExclusiveModeAsync(bool enabled)
{
using var scope = Services.CreateScope();
var usersContext = scope.ServiceProvider.GetRequiredService<UsersContext>();
var user = await usersContext.Users.FirstOrDefaultAsync();
if (user is not null)
{
user.Oidc.ExclusiveMode = enabled;
await usersContext.SaveChangesAsync();
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && Directory.Exists(_tempDir))
{
try { Directory.Delete(_tempDir, true); } catch { /* best effort */ }
}
}
}
/// <summary>
/// Mock OIDC auth service that simulates IdP behavior without network calls.
/// </summary>
private sealed class MockOidcAuthService : IOidcAuthService
{
public const string ValidState = "mock-valid-state";
public const string WrongSubjectState = "mock-wrong-subject-state";
public const string AuthorizedSubject = "mock-authorized-subject-123";
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, OidcTokenExchangeResult> _oneTimeCodes = new();
public Task<OidcAuthorizationResult> StartAuthorization(string redirectUri, string? initiatorUserId = null)
{
return Task.FromResult(new OidcAuthorizationResult
{
AuthorizationUrl = $"https://mock-oidc-provider.test/authorize?redirect_uri={Uri.EscapeDataString(redirectUri)}&state={ValidState}",
State = ValidState
});
}
public Task<OidcCallbackResult> HandleCallback(string code, string state, string redirectUri)
{
if (state == ValidState)
{
return Task.FromResult(new OidcCallbackResult
{
Success = true,
Subject = AuthorizedSubject,
PreferredUsername = "testuser",
Email = "testuser@example.com"
});
}
if (state == WrongSubjectState)
{
return Task.FromResult(new OidcCallbackResult
{
Success = true,
Subject = "wrong-subject-that-doesnt-match",
PreferredUsername = "wronguser",
Email = "wrong@example.com"
});
}
return Task.FromResult(new OidcCallbackResult
{
Success = false,
Error = "Invalid or expired OIDC state"
});
}
public string StoreOneTimeCode(string accessToken, string refreshToken, int expiresIn)
{
var code = Guid.NewGuid().ToString("N");
_oneTimeCodes.TryAdd(code, new OidcTokenExchangeResult
{
AccessToken = accessToken,
RefreshToken = refreshToken,
ExpiresIn = expiresIn
});
return code;
}
public OidcTokenExchangeResult? ExchangeOneTimeCode(string code)
{
return _oneTimeCodes.TryRemove(code, out var result) ? result : null;
}
}
#endregion
}
@@ -0,0 +1,29 @@
using Cleanuparr.Infrastructure.Features.Auth;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Cleanuparr.Api.Tests.Features.Auth;
/// <summary>
/// Factory variant that replaces <see cref="IPasswordService"/> with a
/// <see cref="TrackingPasswordService"/> spy so tests can assert that
/// password verification is always called regardless of username validity.
/// </summary>
public class TimingTestWebApplicationFactory : CustomWebApplicationFactory
{
public TrackingPasswordService TrackingPasswordService { get; } = new();
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
builder.ConfigureServices(services =>
{
// Replace IPasswordService with our tracking spy
var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(IPasswordService));
if (descriptor != null) services.Remove(descriptor);
services.AddSingleton<IPasswordService>(TrackingPasswordService);
});
}
}
@@ -0,0 +1,33 @@
using Cleanuparr.Infrastructure.Features.Auth;
namespace Cleanuparr.Api.Tests.Features.Auth;
/// <summary>
/// Spy wrapper around <see cref="PasswordService"/> that tracks calls to
/// <see cref="VerifyPassword"/> for behavioral assertions in timing tests.
/// </summary>
public sealed class TrackingPasswordService : IPasswordService
{
private readonly PasswordService _inner = new();
private int _verifyPasswordCallCount;
public int VerifyPasswordCallCount => _verifyPasswordCallCount;
public string DummyHash => _inner.DummyHash;
public string HashPassword(string password)
{
return _inner.HashPassword(password);
}
public bool VerifyPassword(string password, string hash)
{
Interlocked.Increment(ref _verifyPasswordCallCount);
return _inner.VerifyPassword(password, hash);
}
public void Reset()
{
Interlocked.Exchange(ref _verifyPasswordCallCount, 0);
}
}
@@ -0,0 +1,106 @@
using Cleanuparr.Api.Features.DownloadCleaner.Contracts.Requests;
using Cleanuparr.Api.Features.DownloadCleaner.Contracts.Responses;
using Cleanuparr.Api.Features.DownloadCleaner.Controllers;
using Cleanuparr.Api.Tests.Features.DownloadCleaner.TestHelpers;
using Cleanuparr.Api.Tests.TestHelpers;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Configuration.DownloadCleaner;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Shouldly;
using ValidationException = Cleanuparr.Domain.Exceptions.ValidationException;
namespace Cleanuparr.Api.Tests.Features.DownloadCleaner;
public class DeadTorrentConfigControllerTests : IDisposable
{
private readonly DataContext _dataContext;
private readonly DeadTorrentConfigController _controller;
public DeadTorrentConfigControllerTests()
{
_dataContext = SeedingRulesTestDataFactory.CreateDataContext();
var logger = Substitute.For<ILogger<DeadTorrentConfigController>>();
_controller = new DeadTorrentConfigController(logger, _dataContext);
ControllerTestContext.Attach(_controller);
}
public void Dispose()
{
_dataContext.Dispose();
GC.SuppressFinalize(this);
}
private static DeadTorrentConfigRequest ValidRequest(
bool enabled = true,
string targetCategory = "cleanuparr-dead",
bool useTag = false,
ushort maxStrikes = 3,
List<string>? categories = null)
=> new()
{
Enabled = enabled,
TargetCategory = targetCategory,
UseTag = useTag,
MaxStrikes = maxStrikes,
Categories = categories ?? ["movies"],
};
[Fact]
public async Task Update_ValidRequest_PersistsConfig()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var result = await _controller.UpdateDeadTorrentConfig(client.Id, ValidRequest(maxStrikes: 5, categories: ["movies", "tv"]));
result.ShouldBeOfType<OkObjectResult>();
var saved = await _dataContext.DeadTorrentConfigs.AsNoTracking().SingleAsync(d => d.DownloadClientConfigId == client.Id);
saved.Enabled.ShouldBeTrue();
saved.MaxStrikes.ShouldBe((ushort)5);
saved.Categories.ShouldBe(new List<string> { "movies", "tv" });
}
[Fact]
public async Task Update_ThenGet_RoundTrips()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
await _controller.UpdateDeadTorrentConfig(client.Id, ValidRequest(useTag: true, maxStrikes: 4));
var result = await _controller.GetDeadTorrentConfig(client.Id);
var ok = result.ShouldBeOfType<OkObjectResult>();
var config = ok.Value.ShouldBeOfType<DeadTorrentConfigResponse>();
config.UseTag.ShouldBeTrue();
config.MaxStrikes.ShouldBe((ushort)4);
}
[Fact]
public async Task Update_StrikesBelowMinimum_ThrowsValidationException()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
await Should.ThrowAsync<ValidationException>(() => _controller.UpdateDeadTorrentConfig(client.Id, ValidRequest(maxStrikes: 2)));
}
[Fact]
public async Task Update_EnabledForRTorrent_ReturnsBadRequest()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext, DownloadClientTypeName.rTorrent, "Test rTorrent");
var result = await _controller.UpdateDeadTorrentConfig(client.Id, ValidRequest());
result.ShouldBeOfType<ObjectResult>().StatusCode.ShouldBe(StatusCodes.Status400BadRequest);
}
[Fact]
public async Task Update_NonExistentClient_ReturnsNotFound()
{
var result = await _controller.UpdateDeadTorrentConfig(Guid.NewGuid(), ValidRequest());
result.ShouldBeOfType<ObjectResult>().StatusCode.ShouldBe(StatusCodes.Status404NotFound);
}
}
@@ -0,0 +1,473 @@
using Cleanuparr.Api.Features.DownloadCleaner.Contracts.Requests;
using Cleanuparr.Api.Features.DownloadCleaner.Contracts.Responses;
using Cleanuparr.Api.Features.DownloadCleaner.Controllers;
using Cleanuparr.Api.Tests.Features.DownloadCleaner.TestHelpers;
using Cleanuparr.Api.Tests.TestHelpers;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Domain.Exceptions;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Configuration.DownloadCleaner;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Shouldly;
namespace Cleanuparr.Api.Tests.Features.DownloadCleaner;
public class SeedingRulesControllerTests : IDisposable
{
private readonly DataContext _dataContext;
private readonly SeedingRulesController _controller;
public SeedingRulesControllerTests()
{
_dataContext = SeedingRulesTestDataFactory.CreateDataContext();
var logger = Substitute.For<ILogger<SeedingRulesController>>();
_controller = new SeedingRulesController(logger, _dataContext);
ControllerTestContext.Attach(_controller);
}
public void Dispose()
{
_dataContext.Dispose();
GC.SuppressFinalize(this);
}
private static SeedingRuleRequest CreateValidRequest(
string name = "Test Rule",
List<string>? categories = null,
List<string>? trackerPatterns = null,
List<string>? tagsAny = null,
List<string>? tagsAll = null,
int? priority = null,
double maxRatio = 2.0,
double minSeedTime = 0,
double maxSeedTime = -1,
int minSeeders = 0,
bool deleteSourceFiles = true)
{
return new SeedingRuleRequest
{
Name = name,
Categories = categories ?? ["movies"],
TrackerPatterns = trackerPatterns ?? [],
TagsAny = tagsAny ?? [],
TagsAll = tagsAll ?? [],
Priority = priority,
PrivacyType = TorrentPrivacyType.Both,
MaxRatio = maxRatio,
MinSeedTime = minSeedTime,
MaxSeedTime = maxSeedTime,
MinSeeders = minSeeders,
DeleteSourceFiles = deleteSourceFiles,
};
}
private static List<SeedingRuleResponse> GetRulesFromOk(IActionResult result)
{
var okResult = result.ShouldBeOfType<OkObjectResult>();
IEnumerable<SeedingRuleResponse> rules = okResult.Value.ShouldBeAssignableTo<IEnumerable<SeedingRuleResponse>>()!;
return rules.ToList();
}
private static T GetCreatedRule<T>(IActionResult result) where T : ISeedingRule
{
var createdResult = result.ShouldBeOfType<CreatedAtActionResult>();
return createdResult.Value.ShouldBeOfType<T>();
}
// ──────────────────────────────────────────────────────────────────────
// GetSeedingRules
// ──────────────────────────────────────────────────────────────────────
[Fact]
public async Task GetSeedingRules_EmptyRules_ReturnsEmptyList()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var result = await _controller.GetSeedingRules(client.Id);
GetRulesFromOk(result).ShouldBeEmpty();
}
[Fact]
public async Task GetSeedingRules_ReturnsRulesOrderedByPriority()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, name: "Rule C", priority: 3);
SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, name: "Rule A", priority: 1);
SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, name: "Rule B", priority: 2);
var result = await _controller.GetSeedingRules(client.Id);
List<SeedingRuleResponse> rules = GetRulesFromOk(result);
rules.Count.ShouldBe(3);
rules[0].Name.ShouldBe("Rule A");
rules[1].Name.ShouldBe("Rule B");
rules[2].Name.ShouldBe("Rule C");
}
[Fact]
public async Task GetSeedingRules_NonExistentClient_ReturnsNotFound()
{
var result = await _controller.GetSeedingRules(Guid.NewGuid());
result.ShouldBeOfType<ObjectResult>().StatusCode.ShouldBe(StatusCodes.Status404NotFound);
}
[Fact]
public async Task GetSeedingRules_QBitClient_ReturnsTagFields()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id,
tagsAny: ["hd", "private"], tagsAll: ["required"]);
var result = await _controller.GetSeedingRules(client.Id);
SeedingRuleResponse rule = GetRulesFromOk(result).Single();
rule.TagsAny.ShouldBe(new List<string> { "hd", "private" });
rule.TagsAll.ShouldBe(new List<string> { "required" });
}
[Fact]
public async Task GetSeedingRules_ReturnsMinSeeders()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, minSeeders: 5);
var result = await _controller.GetSeedingRules(client.Id);
SeedingRuleResponse rule = GetRulesFromOk(result).Single();
rule.MinSeeders.ShouldBe(5);
}
[Fact]
public async Task GetSeedingRules_DelugeClient_ReturnsEmptyTagFields()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext, DownloadClientTypeName.Deluge, "Test Deluge");
SeedingRulesTestDataFactory.AddDelugeSeedingRule(_dataContext, client.Id);
var result = await _controller.GetSeedingRules(client.Id);
SeedingRuleResponse rule = GetRulesFromOk(result).Single();
rule.TagsAny.ShouldBeEmpty();
rule.TagsAll.ShouldBeEmpty();
}
// ──────────────────────────────────────────────────────────────────────
// CreateSeedingRule
// ──────────────────────────────────────────────────────────────────────
[Fact]
public async Task CreateSeedingRule_ValidRequest_ReturnsCreated()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var request = CreateValidRequest(name: "Movies Rule", categories: ["movies", "films"]);
var result = await _controller.CreateSeedingRule(client.Id, request);
var createdResult = result.ShouldBeOfType<CreatedAtActionResult>();
createdResult.StatusCode.ShouldBe(201);
QBitSeedingRule rule = GetCreatedRule<QBitSeedingRule>(result);
rule.Name.ShouldBe("Movies Rule");
rule.Categories.ShouldBe(new List<string> { "movies", "films" });
}
[Fact]
public async Task CreateSeedingRule_AutoAssignsPriority_WhenNotProvided()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var request = CreateValidRequest();
var result = await _controller.CreateSeedingRule(client.Id, request);
GetCreatedRule<QBitSeedingRule>(result).Priority.ShouldBe(1);
}
[Fact]
public async Task CreateSeedingRule_SetsMinSeeders()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var request = CreateValidRequest(minSeeders: 5);
var result = await _controller.CreateSeedingRule(client.Id, request);
GetCreatedRule<QBitSeedingRule>(result).MinSeeders.ShouldBe(5);
}
[Fact]
public async Task CreateSeedingRule_AutoAssignsSequentialPriority()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, priority: 1);
var request = CreateValidRequest(name: "Second Rule", categories: ["tv"]);
var result = await _controller.CreateSeedingRule(client.Id, request);
GetCreatedRule<QBitSeedingRule>(result).Priority.ShouldBe(2);
}
[Fact]
public async Task CreateSeedingRule_DuplicatePriority_ReturnsBadRequest()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, priority: 1);
var request = CreateValidRequest(priority: 1);
var result = await _controller.CreateSeedingRule(client.Id, request);
result.ShouldBeOfType<ObjectResult>().StatusCode.ShouldBe(StatusCodes.Status400BadRequest);
}
[Fact]
public async Task CreateSeedingRule_NonExistentClient_ReturnsNotFound()
{
var request = CreateValidRequest();
var result = await _controller.CreateSeedingRule(Guid.NewGuid(), request);
result.ShouldBeOfType<ObjectResult>().StatusCode.ShouldBe(StatusCodes.Status404NotFound);
}
[Fact]
public async Task CreateSeedingRule_EmptyCategories_ReturnsBadRequest()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var request = CreateValidRequest(categories: []);
await Should.ThrowAsync<ValidationException>(() => _controller.CreateSeedingRule(client.Id, request));
}
[Fact]
public async Task CreateSeedingRule_SanitizesWhitespaceInLists()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var request = CreateValidRequest(
trackerPatterns: ["", " ", "valid.com", " trimmed.com "]);
var result = await _controller.CreateSeedingRule(client.Id, request);
QBitSeedingRule rule = GetCreatedRule<QBitSeedingRule>(result);
rule.TrackerPatterns.ShouldBe(new List<string> { "valid.com", "trimmed.com" });
}
[Fact]
public async Task CreateSeedingRule_ForTransmission_CreatesTransmissionRule()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext,
DownloadClientTypeName.Transmission, "Test Transmission");
var request = CreateValidRequest(tagsAny: ["tag1"]);
var result = await _controller.CreateSeedingRule(client.Id, request);
GetCreatedRule<TransmissionSeedingRule>(result).TagsAny.ShouldBe(new List<string> { "tag1" });
}
// ──────────────────────────────────────────────────────────────────────
// UpdateSeedingRule
// ──────────────────────────────────────────────────────────────────────
[Fact]
public async Task UpdateSeedingRule_ValidRequest_ReturnsOk()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var rule = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id);
var request = CreateValidRequest(name: "Updated Name", categories: ["tv", "anime"]);
var result = await _controller.UpdateSeedingRule(rule.Id, request);
var okResult = result.ShouldBeOfType<OkObjectResult>();
var updated = okResult.Value.ShouldBeOfType<QBitSeedingRule>();
updated.Name.ShouldBe("Updated Name");
updated.Categories.ShouldBe(new List<string> { "tv", "anime" });
}
[Fact]
public async Task UpdateSeedingRule_DoesNotChangePriority()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var rule = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, priority: 5);
var request = CreateValidRequest(priority: 1);
var result = await _controller.UpdateSeedingRule(rule.Id, request);
var okResult = result.ShouldBeOfType<OkObjectResult>();
var updated = okResult.Value.ShouldBeOfType<QBitSeedingRule>();
updated.Priority.ShouldBe(5);
}
[Fact]
public async Task UpdateSeedingRule_UpdatesTagsForTagFilterableClient()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var rule = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id);
var request = CreateValidRequest(tagsAny: ["new-tag"], tagsAll: ["must-have"]);
var result = await _controller.UpdateSeedingRule(rule.Id, request);
var okResult = result.ShouldBeOfType<OkObjectResult>();
var updated = okResult.Value.ShouldBeOfType<QBitSeedingRule>();
updated.TagsAny.ShouldBe(new List<string> { "new-tag" });
updated.TagsAll.ShouldBe(new List<string> { "must-have" });
}
[Fact]
public async Task UpdateSeedingRule_UpdatesMinSeeders()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var rule = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id);
var request = CreateValidRequest(minSeeders: 5);
var result = await _controller.UpdateSeedingRule(rule.Id, request);
var okResult = result.ShouldBeOfType<OkObjectResult>();
var updated = okResult.Value.ShouldBeOfType<QBitSeedingRule>();
updated.MinSeeders.ShouldBe(5);
}
[Fact]
public async Task UpdateSeedingRule_NonExistentRule_ReturnsNotFound()
{
var request = CreateValidRequest();
var result = await _controller.UpdateSeedingRule(Guid.NewGuid(), request);
result.ShouldBeOfType<ObjectResult>().StatusCode.ShouldBe(StatusCodes.Status404NotFound);
}
[Fact]
public async Task UpdateSeedingRule_ValidationFailure_ReturnsBadRequest()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var rule = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id);
// Both maxRatio and maxSeedTime negative → validation failure
var request = CreateValidRequest(maxRatio: -1, maxSeedTime: -1);
await Should.ThrowAsync<ValidationException>(() => _controller.UpdateSeedingRule(rule.Id, request));
}
// ──────────────────────────────────────────────────────────────────────
// ReorderSeedingRules
// ──────────────────────────────────────────────────────────────────────
[Fact]
public async Task ReorderSeedingRules_ValidRequest_ReturnsNoContent()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var rule1 = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, name: "A", priority: 1);
var rule2 = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, name: "B", priority: 2);
var request = new ReorderSeedingRulesRequest { OrderedIds = [rule2.Id, rule1.Id] };
var result = await _controller.ReorderSeedingRules(client.Id, request);
result.ShouldBeOfType<NoContentResult>();
}
[Fact]
public async Task ReorderSeedingRules_AssignsSequentialPriorities()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var rule1 = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, name: "A", priority: 1);
var rule2 = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, name: "B", priority: 2);
var rule3 = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, name: "C", priority: 3);
// Reverse order
var request = new ReorderSeedingRulesRequest { OrderedIds = [rule3.Id, rule2.Id, rule1.Id] };
await _controller.ReorderSeedingRules(client.Id, request);
List<SeedingRuleResponse> rules = GetRulesFromOk(await _controller.GetSeedingRules(client.Id));
rules[0].Name.ShouldBe("C");
rules[0].Priority.ShouldBe(1);
rules[1].Name.ShouldBe("B");
rules[1].Priority.ShouldBe(2);
rules[2].Name.ShouldBe("A");
rules[2].Priority.ShouldBe(3);
}
[Fact]
public async Task ReorderSeedingRules_NonExistentClient_ReturnsNotFound()
{
var request = new ReorderSeedingRulesRequest { OrderedIds = [Guid.NewGuid()] };
var result = await _controller.ReorderSeedingRules(Guid.NewGuid(), request);
result.ShouldBeOfType<ObjectResult>().StatusCode.ShouldBe(StatusCodes.Status404NotFound);
}
[Fact]
public async Task ReorderSeedingRules_DuplicateIds_ReturnsBadRequest()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var rule1 = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, name: "A", priority: 1);
var rule2 = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, name: "B", priority: 2);
var request = new ReorderSeedingRulesRequest { OrderedIds = [rule1.Id, rule1.Id] };
var result = await _controller.ReorderSeedingRules(client.Id, request);
result.ShouldBeOfType<ObjectResult>().StatusCode.ShouldBe(StatusCodes.Status400BadRequest);
}
[Fact]
public async Task ReorderSeedingRules_WrongCount_ReturnsBadRequest()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var rule1 = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, name: "A", priority: 1);
SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, name: "B", priority: 2);
// Only send 1 of 2 IDs
var request = new ReorderSeedingRulesRequest { OrderedIds = [rule1.Id] };
var result = await _controller.ReorderSeedingRules(client.Id, request);
result.ShouldBeOfType<ObjectResult>().StatusCode.ShouldBe(StatusCodes.Status400BadRequest);
}
[Fact]
public async Task ReorderSeedingRules_UnknownRuleId_ReturnsBadRequest()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var rule1 = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, name: "A", priority: 1);
SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id, name: "B", priority: 2);
var request = new ReorderSeedingRulesRequest { OrderedIds = [rule1.Id, Guid.NewGuid()] };
var result = await _controller.ReorderSeedingRules(client.Id, request);
result.ShouldBeOfType<ObjectResult>().StatusCode.ShouldBe(StatusCodes.Status400BadRequest);
}
// ──────────────────────────────────────────────────────────────────────
// DeleteSeedingRule
// ──────────────────────────────────────────────────────────────────────
[Fact]
public async Task DeleteSeedingRule_ExistingRule_ReturnsNoContent()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var rule = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id);
var result = await _controller.DeleteSeedingRule(rule.Id);
result.ShouldBeOfType<NoContentResult>();
}
[Fact]
public async Task DeleteSeedingRule_VerifiesRuleRemoved()
{
var client = SeedingRulesTestDataFactory.AddDownloadClient(_dataContext);
var rule = SeedingRulesTestDataFactory.AddQBitSeedingRule(_dataContext, client.Id);
await _controller.DeleteSeedingRule(rule.Id);
GetRulesFromOk(await _controller.GetSeedingRules(client.Id)).ShouldBeEmpty();
}
[Fact]
public async Task DeleteSeedingRule_NonExistentRule_ReturnsNotFound()
{
var result = await _controller.DeleteSeedingRule(Guid.NewGuid());
result.ShouldBeOfType<ObjectResult>().StatusCode.ShouldBe(StatusCodes.Status404NotFound);
}
}
@@ -0,0 +1,211 @@
using Cleanuparr.Domain.Enums;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Configuration;
using Cleanuparr.Persistence.Models.Configuration.Arr;
using Cleanuparr.Persistence.Models.Configuration.DownloadCleaner;
using Cleanuparr.Persistence.Models.Configuration.General;
using Cleanuparr.Persistence.Models.Configuration.MalwareBlocker;
using Cleanuparr.Persistence.Models.Configuration.QueueCleaner;
using Cleanuparr.Persistence.Models.Configuration.Seeker;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace Cleanuparr.Api.Tests.Features.DownloadCleaner.TestHelpers;
/// <summary>
/// Factory for creating SQLite in-memory contexts for SeedingRulesController tests
/// </summary>
public static class SeedingRulesTestDataFactory
{
public static DataContext CreateDataContext()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<DataContext>()
.UseSqlite(connection)
.Options;
var context = new DataContext(options);
context.Database.EnsureCreated();
SeedDefaultData(context);
return context;
}
private static void SeedDefaultData(DataContext context)
{
context.GeneralConfigs.Add(new GeneralConfig
{
Id = Guid.NewGuid(),
DryRun = false,
IgnoredDownloads = [],
Log = new LoggingConfig()
});
context.ArrConfigs.AddRange(
new ArrConfig { Id = Guid.NewGuid(), Type = InstanceType.Sonarr, Instances = [], FailedImportMaxStrikes = 3 },
new ArrConfig { Id = Guid.NewGuid(), Type = InstanceType.Radarr, Instances = [], FailedImportMaxStrikes = 3 },
new ArrConfig { Id = Guid.NewGuid(), Type = InstanceType.Lidarr, Instances = [], FailedImportMaxStrikes = 3 },
new ArrConfig { Id = Guid.NewGuid(), Type = InstanceType.Readarr, Instances = [], FailedImportMaxStrikes = 3 },
new ArrConfig { Id = Guid.NewGuid(), Type = InstanceType.Whisparr, Instances = [], FailedImportMaxStrikes = 3 }
);
context.QueueCleanerConfigs.Add(new QueueCleanerConfig
{
Id = Guid.NewGuid(),
IgnoredDownloads = [],
FailedImport = new FailedImportConfig()
});
context.ContentBlockerConfigs.Add(new ContentBlockerConfig
{
Id = Guid.NewGuid(),
IgnoredDownloads = [],
DeletePrivate = false,
Sonarr = new BlocklistSettings { Enabled = false },
Radarr = new BlocklistSettings { Enabled = false },
Lidarr = new BlocklistSettings { Enabled = false },
Readarr = new BlocklistSettings { Enabled = false },
Whisparr = new BlocklistSettings { Enabled = false }
});
context.DownloadCleanerConfigs.Add(new DownloadCleanerConfig
{
Id = Guid.NewGuid(),
IgnoredDownloads = []
});
context.SeekerConfigs.Add(new SeekerConfig
{
Id = Guid.NewGuid(),
SearchEnabled = true,
ProactiveSearchEnabled = false
});
context.SaveChanges();
}
public static DownloadClientConfig AddDownloadClient(
DataContext context,
DownloadClientTypeName typeName = DownloadClientTypeName.qBittorrent,
string name = "Test qBittorrent")
{
var config = new DownloadClientConfig
{
Id = Guid.NewGuid(),
Name = name,
TypeName = typeName,
Type = DownloadClientType.Torrent,
Enabled = true,
Host = new Uri("http://localhost:8080"),
Username = "admin",
Password = "admin"
};
context.DownloadClients.Add(config);
context.SaveChanges();
return config;
}
public static QBitSeedingRule AddQBitSeedingRule(
DataContext context,
Guid downloadClientId,
string name = "Test Rule",
int priority = 1,
List<string>? categories = null,
List<string>? trackerPatterns = null,
List<string>? tagsAny = null,
List<string>? tagsAll = null,
double maxRatio = 2.0,
double minSeedTime = 0,
double maxSeedTime = -1,
int minSeeders = 0)
{
var rule = new QBitSeedingRule
{
Id = Guid.NewGuid(),
DownloadClientConfigId = downloadClientId,
Name = name,
Priority = priority,
Categories = categories ?? ["movies"],
TrackerPatterns = trackerPatterns ?? [],
TagsAny = tagsAny ?? [],
TagsAll = tagsAll ?? [],
PrivacyType = TorrentPrivacyType.Both,
MaxRatio = maxRatio,
MinSeedTime = minSeedTime,
MaxSeedTime = maxSeedTime,
MinSeeders = minSeeders,
DeleteSourceFiles = true,
};
context.QBitSeedingRules.Add(rule);
context.SaveChanges();
return rule;
}
public static DelugeSeedingRule AddDelugeSeedingRule(
DataContext context,
Guid downloadClientId,
string name = "Test Rule",
int priority = 1,
List<string>? categories = null,
double maxRatio = 2.0,
double maxSeedTime = -1,
int minSeeders = 0)
{
var rule = new DelugeSeedingRule
{
Id = Guid.NewGuid(),
DownloadClientConfigId = downloadClientId,
Name = name,
Priority = priority,
Categories = categories ?? ["movies"],
TrackerPatterns = [],
PrivacyType = TorrentPrivacyType.Both,
MaxRatio = maxRatio,
MinSeedTime = 0,
MaxSeedTime = maxSeedTime,
MinSeeders = minSeeders,
DeleteSourceFiles = true,
};
context.DelugeSeedingRules.Add(rule);
context.SaveChanges();
return rule;
}
public static TransmissionSeedingRule AddTransmissionSeedingRule(
DataContext context,
Guid downloadClientId,
string name = "Test Rule",
int priority = 1,
List<string>? categories = null,
double maxRatio = 2.0,
double maxSeedTime = -1,
int minSeeders = 0)
{
var rule = new TransmissionSeedingRule
{
Id = Guid.NewGuid(),
DownloadClientConfigId = downloadClientId,
Name = name,
Priority = priority,
Categories = categories ?? ["movies"],
TrackerPatterns = [],
TagsAny = [],
TagsAll = [],
PrivacyType = TorrentPrivacyType.Both,
MaxRatio = maxRatio,
MinSeedTime = 0,
MaxSeedTime = maxSeedTime,
MinSeeders = minSeeders,
DeleteSourceFiles = true,
};
context.TransmissionSeedingRules.Add(rule);
context.SaveChanges();
return rule;
}
}
@@ -0,0 +1,539 @@
using System.Text.Json;
using Cleanuparr.Api.Features.Seeker.Contracts.Responses;
using Cleanuparr.Api.Features.Seeker.Controllers;
using Cleanuparr.Api.Tests.Features.Seeker.TestHelpers;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.State;
using Microsoft.AspNetCore.Mvc;
using Shouldly;
namespace Cleanuparr.Api.Tests.Features.Seeker;
public class CustomFormatScoreControllerTests : IDisposable
{
private readonly DataContext _dataContext;
private readonly CustomFormatScoreController _controller;
public CustomFormatScoreControllerTests()
{
_dataContext = SeekerTestDataFactory.CreateDataContext();
_controller = new CustomFormatScoreController(_dataContext);
}
public void Dispose()
{
_dataContext.Dispose();
GC.SuppressFinalize(this);
}
private static JsonElement GetResponseBody(IActionResult result)
{
var okResult = result.ShouldBeOfType<OkObjectResult>();
var json = JsonSerializer.Serialize(okResult.Value);
return JsonDocument.Parse(json).RootElement;
}
#region GetCustomFormatScores Tests
[Fact]
public async Task GetCustomFormatScores_WithPageBelowMinimum_ClampsToOne()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddScoreEntry(radarr.Id, 1, "Movie A", currentScore: 100, cutoffScore: 500);
AddScoreEntry(radarr.Id, 2, "Movie B", currentScore: 200, cutoffScore: 500);
var result = await _controller.GetCustomFormatScores(page: -5, pageSize: 50);
var body = GetResponseBody(result);
body.GetProperty("Page").GetInt32().ShouldBe(1);
body.GetProperty("Items").GetArrayLength().ShouldBe(2);
}
[Fact]
public async Task GetCustomFormatScores_WithPageSizeAboveMaximum_ClampsToHundred()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddScoreEntry(radarr.Id, 1, "Movie A", currentScore: 100, cutoffScore: 500);
var result = await _controller.GetCustomFormatScores(page: 1, pageSize: 999);
var body = GetResponseBody(result);
body.GetProperty("PageSize").GetInt32().ShouldBe(500);
}
[Fact]
public async Task GetCustomFormatScores_WithHideMetTrue_ExcludesItemsAtOrAboveCutoff()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddScoreEntry(radarr.Id, 1, "Below Cutoff", currentScore: 100, cutoffScore: 500);
AddScoreEntry(radarr.Id, 2, "At Cutoff", currentScore: 500, cutoffScore: 500);
AddScoreEntry(radarr.Id, 3, "Above Cutoff", currentScore: 600, cutoffScore: 500);
var result = await _controller.GetCustomFormatScores(cutoffFilter: CutoffFilter.Below);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(1);
body.GetProperty("Items")[0].GetProperty("Title").GetString().ShouldBe("Below Cutoff");
}
[Fact]
public async Task GetCustomFormatScores_WithHideUnmonitoredTrue_ExcludesUnmonitoredItems()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddScoreEntry(radarr.Id, 1, "Monitored Movie", currentScore: 100, cutoffScore: 500, isMonitored: true);
AddScoreEntry(radarr.Id, 2, "Unmonitored Movie", currentScore: 200, cutoffScore: 500, isMonitored: false);
AddScoreEntry(radarr.Id, 3, "Another Monitored", currentScore: 300, cutoffScore: 500, isMonitored: true);
var result = await _controller.GetCustomFormatScores(monitoredFilter: MonitoredFilter.Monitored);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(2);
var items = body.GetProperty("Items");
items.GetArrayLength().ShouldBe(2);
items[0].GetProperty("Title").GetString().ShouldBe("Another Monitored");
items[1].GetProperty("Title").GetString().ShouldBe("Monitored Movie");
}
[Fact]
public async Task GetCustomFormatScores_WithSearchFilter_ReturnsMatchingTitlesOnly()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddScoreEntry(radarr.Id, 1, "The Matrix", currentScore: 100, cutoffScore: 500);
AddScoreEntry(radarr.Id, 2, "Inception", currentScore: 200, cutoffScore: 500);
AddScoreEntry(radarr.Id, 3, "The Matrix Reloaded", currentScore: 300, cutoffScore: 500);
var result = await _controller.GetCustomFormatScores(search: "matrix");
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(2);
}
[Fact]
public async Task GetCustomFormatScores_WithSortByDate_OrdersByLastSyncedDescending()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddScoreEntry(radarr.Id, 1, "Older", currentScore: 100, cutoffScore: 500,
lastSynced: DateTime.UtcNow.AddHours(-2));
AddScoreEntry(radarr.Id, 2, "Newer", currentScore: 200, cutoffScore: 500,
lastSynced: DateTime.UtcNow.AddHours(-1));
var result = await _controller.GetCustomFormatScores(sortBy: CfScoresSortBy.LastSyncedAt);
var body = GetResponseBody(result);
body.GetProperty("Items")[0].GetProperty("Title").GetString().ShouldBe("Newer");
body.GetProperty("Items")[1].GetProperty("Title").GetString().ShouldBe("Older");
}
[Fact]
public async Task GetCustomFormatScores_WithInstanceIdFilter_ReturnsOnlyThatInstance()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
var sonarr = SeekerTestDataFactory.AddSonarrInstance(_dataContext);
AddScoreEntry(radarr.Id, 1, "Movie", currentScore: 100, cutoffScore: 500);
AddScoreEntry(sonarr.Id, 2, "Series", currentScore: 200, cutoffScore: 500,
itemType: InstanceType.Sonarr);
var result = await _controller.GetCustomFormatScores(instanceId: radarr.Id);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(1);
body.GetProperty("Items")[0].GetProperty("Title").GetString().ShouldBe("Movie");
}
[Fact]
public async Task GetCustomFormatScores_ReturnsCorrectTotalPagesCalculation()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
for (int i = 1; i <= 7; i++)
{
AddScoreEntry(radarr.Id, i, $"Movie {i}", currentScore: 100, cutoffScore: 500);
}
var result = await _controller.GetCustomFormatScores(page: 1, pageSize: 3);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(7);
body.GetProperty("TotalPages").GetInt32().ShouldBe(3); // ceil(7/3) = 3
body.GetProperty("Items").GetArrayLength().ShouldBe(3);
}
[Fact]
public async Task GetCustomFormatScores_WithCutoffFilterMet_ExcludesBelowCutoff()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddScoreEntry(radarr.Id, 1, "Below", currentScore: 100, cutoffScore: 500);
AddScoreEntry(radarr.Id, 2, "At", currentScore: 500, cutoffScore: 500);
AddScoreEntry(radarr.Id, 3, "Above", currentScore: 600, cutoffScore: 500);
var result = await _controller.GetCustomFormatScores(cutoffFilter: CutoffFilter.Met);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(2);
}
[Fact]
public async Task GetCustomFormatScores_WithCutoffFilterAll_IncludesEverything()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddScoreEntry(radarr.Id, 1, "Below", currentScore: 100, cutoffScore: 500);
AddScoreEntry(radarr.Id, 2, "Above", currentScore: 600, cutoffScore: 500);
var result = await _controller.GetCustomFormatScores(cutoffFilter: CutoffFilter.All);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(2);
}
[Fact]
public async Task GetCustomFormatScores_WithMonitoredFilterUnmonitored_ReturnsOnlyUnmonitored()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddScoreEntry(radarr.Id, 1, "A", currentScore: 100, cutoffScore: 500, isMonitored: true);
AddScoreEntry(radarr.Id, 2, "B", currentScore: 100, cutoffScore: 500, isMonitored: false);
var result = await _controller.GetCustomFormatScores(monitoredFilter: MonitoredFilter.Unmonitored);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(1);
body.GetProperty("Items")[0].GetProperty("Title").GetString().ShouldBe("B");
}
[Fact]
public async Task GetCustomFormatScores_WithQualityProfileFilter_ReturnsOnlyMatchingProfile()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddScoreEntry(radarr.Id, 1, "HD Movie", currentScore: 100, cutoffScore: 500, qualityProfileName: "HD");
AddScoreEntry(radarr.Id, 2, "UHD Movie", currentScore: 200, cutoffScore: 500, qualityProfileName: "UHD");
var result = await _controller.GetCustomFormatScores(qualityProfile: "UHD");
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(1);
body.GetProperty("Items")[0].GetProperty("Title").GetString().ShouldBe("UHD Movie");
}
[Fact]
public async Task GetCustomFormatScores_WithExplicitSortDirectionAsc_OverridesDefault()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddScoreEntry(radarr.Id, 1, "A", currentScore: 100, cutoffScore: 500);
AddScoreEntry(radarr.Id, 2, "B", currentScore: 300, cutoffScore: 500);
// CurrentScore default is descending; overriding with Asc should flip it.
var result = await _controller.GetCustomFormatScores(
sortBy: CfScoresSortBy.CurrentScore,
sortDirection: Cleanuparr.Domain.Enums.SortDirection.Asc);
var body = GetResponseBody(result);
var items = body.GetProperty("Items");
items[0].GetProperty("CurrentScore").GetInt32().ShouldBe(100);
items[1].GetProperty("CurrentScore").GetInt32().ShouldBe(300);
}
[Fact]
public async Task GetCustomFormatScores_WithSortByTitleDescending_OrdersReverseAlphabetically()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddScoreEntry(radarr.Id, 1, "Apple", currentScore: 100, cutoffScore: 500);
AddScoreEntry(radarr.Id, 2, "Banana", currentScore: 200, cutoffScore: 500);
var result = await _controller.GetCustomFormatScores(
sortBy: CfScoresSortBy.Title,
sortDirection: Cleanuparr.Domain.Enums.SortDirection.Desc);
var body = GetResponseBody(result);
body.GetProperty("Items")[0].GetProperty("Title").GetString().ShouldBe("Banana");
}
#endregion
#region GetRecentUpgrades Tests
[Fact]
public async Task GetRecentUpgrades_WithNoHistory_ReturnsEmptyList()
{
var result = await _controller.GetRecentUpgrades();
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(0);
body.GetProperty("Items").GetArrayLength().ShouldBe(0);
}
[Fact]
public async Task GetRecentUpgrades_WithSingleEntryPerItem_ReturnsNoUpgrades()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 100, recordedAt: DateTime.UtcNow.AddDays(-1));
var result = await _controller.GetRecentUpgrades();
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(0);
}
[Fact]
public async Task GetRecentUpgrades_WithScoreIncrease_DetectsUpgrade()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 100, recordedAt: DateTime.UtcNow.AddDays(-2));
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 250, recordedAt: DateTime.UtcNow.AddDays(-1));
var result = await _controller.GetRecentUpgrades();
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(1);
var upgrade = body.GetProperty("Items")[0];
upgrade.GetProperty("PreviousScore").GetInt32().ShouldBe(100);
upgrade.GetProperty("NewScore").GetInt32().ShouldBe(250);
}
[Fact]
public async Task GetRecentUpgrades_WithScoreDecrease_DoesNotCountAsUpgrade()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 300, recordedAt: DateTime.UtcNow.AddDays(-2));
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 150, recordedAt: DateTime.UtcNow.AddDays(-1));
var result = await _controller.GetRecentUpgrades();
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(0);
}
[Fact]
public async Task GetRecentUpgrades_WithMultipleUpgradesInSameGroup_CountsEach()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
// 100 -> 200 -> 300 = two upgrades for the same item
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 100, recordedAt: DateTime.UtcNow.AddDays(-3));
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 200, recordedAt: DateTime.UtcNow.AddDays(-2));
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 300, recordedAt: DateTime.UtcNow.AddDays(-1));
var result = await _controller.GetRecentUpgrades();
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(2);
}
[Fact]
public async Task GetRecentUpgrades_WithDaysFilter_ExcludesOlderHistory()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
// Old upgrade (outside 7-day window)
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 100, recordedAt: DateTime.UtcNow.AddDays(-20));
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 250, recordedAt: DateTime.UtcNow.AddDays(-15));
// Recent upgrade (inside 7-day window)
AddHistoryEntry(radarr.Id, externalItemId: 2, score: 100, recordedAt: DateTime.UtcNow.AddDays(-3));
AddHistoryEntry(radarr.Id, externalItemId: 2, score: 300, recordedAt: DateTime.UtcNow.AddDays(-1));
var result = await _controller.GetRecentUpgrades(days: 7);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(1);
}
[Fact]
public async Task GetRecentUpgrades_WithUpgradeCrossingWindowBoundary_IsDetected()
{
// CR2: pre-window baseline must still participate so the first in-window
// row can be recognised as an upgrade.
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 100, recordedAt: DateTime.UtcNow.AddDays(-10));
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 200, recordedAt: DateTime.UtcNow.AddDays(-3));
var result = await _controller.GetRecentUpgrades(days: 7);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(1);
var upgrade = body.GetProperty("Items")[0];
upgrade.GetProperty("PreviousScore").GetInt32().ShouldBe(100);
upgrade.GetProperty("NewScore").GetInt32().ShouldBe(200);
}
[Fact]
public async Task GetRecentUpgrades_WithSortByScoreDeltaDescending_OrdersByLargestDelta()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
// Item 1: +50
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 100, recordedAt: DateTime.UtcNow.AddDays(-3));
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 150, recordedAt: DateTime.UtcNow.AddDays(-2));
// Item 2: +400
AddHistoryEntry(radarr.Id, externalItemId: 2, score: 100, recordedAt: DateTime.UtcNow.AddDays(-3));
AddHistoryEntry(radarr.Id, externalItemId: 2, score: 500, recordedAt: DateTime.UtcNow.AddDays(-2));
var result = await _controller.GetRecentUpgrades(sortBy: CfUpgradesSortBy.ScoreDelta);
var body = GetResponseBody(result);
var items = body.GetProperty("Items");
items[0].GetProperty("NewScore").GetInt32().ShouldBe(500);
items[1].GetProperty("NewScore").GetInt32().ShouldBe(150);
}
[Fact]
public async Task GetRecentUpgrades_WithSortByTitleAscending_OrdersAlphabetically()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddHistoryEntry(radarr.Id, externalItemId: 2, score: 100, recordedAt: DateTime.UtcNow.AddDays(-3));
AddHistoryEntry(radarr.Id, externalItemId: 2, score: 200, recordedAt: DateTime.UtcNow.AddDays(-2));
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 100, recordedAt: DateTime.UtcNow.AddDays(-3));
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 200, recordedAt: DateTime.UtcNow.AddDays(-2));
var result = await _controller.GetRecentUpgrades(sortBy: CfUpgradesSortBy.Title);
var body = GetResponseBody(result);
var items = body.GetProperty("Items");
items[0].GetProperty("Title").GetString().ShouldBe("Item 1");
items[1].GetProperty("Title").GetString().ShouldBe("Item 2");
}
[Fact]
public async Task GetRecentUpgrades_WithSearchFilter_ReturnsMatchingTitlesOnly()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
// AddHistoryEntry titles as "Item {externalItemId}".
AddHistoryEntry(radarr.Id, externalItemId: 42, score: 100, recordedAt: DateTime.UtcNow.AddDays(-3));
AddHistoryEntry(radarr.Id, externalItemId: 42, score: 200, recordedAt: DateTime.UtcNow.AddDays(-2));
AddHistoryEntry(radarr.Id, externalItemId: 99, score: 100, recordedAt: DateTime.UtcNow.AddDays(-3));
AddHistoryEntry(radarr.Id, externalItemId: 99, score: 200, recordedAt: DateTime.UtcNow.AddDays(-2));
var result = await _controller.GetRecentUpgrades(search: "42");
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(1);
body.GetProperty("Items")[0].GetProperty("Title").GetString().ShouldBe("Item 42");
}
[Fact]
public async Task GetRecentUpgrades_ReturnsSortedByMostRecentFirst()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
// Item 1: upgrade happened 5 days ago
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 100, recordedAt: DateTime.UtcNow.AddDays(-6));
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 200, recordedAt: DateTime.UtcNow.AddDays(-5));
// Item 2: upgrade happened 1 day ago
AddHistoryEntry(radarr.Id, externalItemId: 2, score: 100, recordedAt: DateTime.UtcNow.AddDays(-2));
AddHistoryEntry(radarr.Id, externalItemId: 2, score: 300, recordedAt: DateTime.UtcNow.AddDays(-1));
var result = await _controller.GetRecentUpgrades();
var body = GetResponseBody(result);
var items = body.GetProperty("Items");
items.GetArrayLength().ShouldBe(2);
// Most recent upgrade (item 2) should be first
items[0].GetProperty("NewScore").GetInt32().ShouldBe(300);
items[1].GetProperty("NewScore").GetInt32().ShouldBe(200);
}
#endregion
#region GetStats Tests
[Fact]
public async Task GetStats_WithNoEntries_ReturnsZeroes()
{
var result = await _controller.GetStats();
var okResult = result.ShouldBeOfType<OkObjectResult>();
var stats = okResult.Value.ShouldBeOfType<CustomFormatScoreStatsResponse>();
stats.TotalTracked.ShouldBe(0);
stats.BelowCutoff.ShouldBe(0);
stats.AtOrAboveCutoff.ShouldBe(0);
stats.RecentUpgrades.ShouldBe(0);
}
[Fact]
public async Task GetStats_CorrectlyCategorizesBelowAndAboveCutoff()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddScoreEntry(radarr.Id, 1, "Below", currentScore: 100, cutoffScore: 500);
AddScoreEntry(radarr.Id, 2, "At", currentScore: 500, cutoffScore: 500);
AddScoreEntry(radarr.Id, 3, "Above", currentScore: 600, cutoffScore: 500);
var result = await _controller.GetStats();
var okResult = result.ShouldBeOfType<OkObjectResult>();
var stats = okResult.Value.ShouldBeOfType<CustomFormatScoreStatsResponse>();
stats.TotalTracked.ShouldBe(3);
stats.BelowCutoff.ShouldBe(1);
stats.AtOrAboveCutoff.ShouldBe(2);
}
[Fact]
public async Task GetStats_CountsRecentUpgradesFromLast7Days()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddScoreEntry(radarr.Id, 1, "Movie", currentScore: 300, cutoffScore: 500);
// Upgrade within 7 days
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 100, recordedAt: DateTime.UtcNow.AddDays(-3));
AddHistoryEntry(radarr.Id, externalItemId: 1, score: 300, recordedAt: DateTime.UtcNow.AddDays(-1));
// Upgrade outside 7 days (should not be counted)
AddHistoryEntry(radarr.Id, externalItemId: 2, score: 50, recordedAt: DateTime.UtcNow.AddDays(-20));
AddHistoryEntry(radarr.Id, externalItemId: 2, score: 200, recordedAt: DateTime.UtcNow.AddDays(-15));
var result = await _controller.GetStats();
var okResult = result.ShouldBeOfType<OkObjectResult>();
var stats = okResult.Value.ShouldBeOfType<CustomFormatScoreStatsResponse>();
stats.RecentUpgrades.ShouldBe(1);
}
#endregion
#region Helpers
private void AddScoreEntry(
Guid arrInstanceId,
long externalItemId,
string title,
int currentScore,
int cutoffScore,
InstanceType itemType = InstanceType.Radarr,
DateTime? lastSynced = null,
bool isMonitored = true,
string qualityProfileName = "HD")
{
_dataContext.CustomFormatScoreEntries.Add(new CustomFormatScoreEntry
{
ArrInstanceId = arrInstanceId,
ExternalItemId = externalItemId,
EpisodeId = 0,
ItemType = itemType,
Title = title,
FileId = externalItemId * 10,
CurrentScore = currentScore,
CutoffScore = cutoffScore,
QualityProfileName = qualityProfileName,
IsMonitored = isMonitored,
LastSyncedAt = lastSynced ?? DateTime.UtcNow
});
_dataContext.SaveChanges();
}
private void AddHistoryEntry(
Guid arrInstanceId,
long externalItemId,
int score,
DateTime recordedAt,
long episodeId = 0,
int cutoffScore = 500,
InstanceType itemType = InstanceType.Radarr)
{
_dataContext.CustomFormatScoreHistory.Add(new CustomFormatScoreHistory
{
ArrInstanceId = arrInstanceId,
ExternalItemId = externalItemId,
EpisodeId = episodeId,
ItemType = itemType,
Title = $"Item {externalItemId}",
Score = score,
CutoffScore = cutoffScore,
RecordedAt = recordedAt
});
_dataContext.SaveChanges();
}
#endregion
}
@@ -0,0 +1,300 @@
using System.Text.Json;
using Cleanuparr.Api.Features.Seeker.Controllers;
using Cleanuparr.Api.Tests.Features.Seeker.TestHelpers;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Events;
using Microsoft.AspNetCore.Mvc;
using Shouldly;
namespace Cleanuparr.Api.Tests.Features.Seeker;
public class SearchStatsControllerTests : IDisposable
{
private readonly DataContext _dataContext;
private readonly EventsContext _eventsContext;
private readonly SearchStatsController _controller;
public SearchStatsControllerTests()
{
_dataContext = SeekerTestDataFactory.CreateDataContext();
_eventsContext = SeekerTestDataFactory.CreateEventsContext();
_controller = new SearchStatsController(_dataContext, _eventsContext);
}
public void Dispose()
{
_dataContext.Dispose();
_eventsContext.Dispose();
GC.SuppressFinalize(this);
}
private static JsonElement GetResponseBody(IActionResult result)
{
var okResult = result.ShouldBeOfType<OkObjectResult>();
var json = JsonSerializer.Serialize(okResult.Value);
return JsonDocument.Parse(json).RootElement;
}
#region GetEvents with SearchEventData
[Fact]
public async Task GetEvents_WithNoSearchEventData_ReturnsUnknownDefaults()
{
AddSearchEvent();
var result = await _controller.GetEvents();
var body = GetResponseBody(result);
var item = body.GetProperty("Items")[0];
item.GetProperty("ItemTitle").GetString().ShouldBe("Unknown");
}
[Fact]
public async Task GetEvents_WithSearchEventData_ReturnsAllFields()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
AddSearchEvent(
arrInstanceId: radarr.Id,
itemTitle: "Movie A",
searchType: SeekerSearchType.Proactive,
searchReason: SeekerSearchReason.Missing,
grabbedItems: ["Movie A (2024)"]);
var result = await _controller.GetEvents();
var body = GetResponseBody(result);
var item = body.GetProperty("Items")[0];
item.GetProperty("ArrInstanceId").GetString().ShouldBe(radarr.Id.ToString());
item.GetProperty("InstanceType").GetString().ShouldBe(nameof(InstanceType.Radarr));
item.GetProperty("ItemTitle").GetString().ShouldBe("Movie A");
item.GetProperty("SearchType").GetString().ShouldBe(nameof(SeekerSearchType.Proactive));
item.GetProperty("SearchReason").GetString().ShouldBe(nameof(SeekerSearchReason.Missing));
item.GetProperty("GrabbedItems")[0].GetString().ShouldBe("Movie A (2024)");
}
[Fact]
public async Task GetEvents_WithReplacementSearchType_ParsesCorrectEnum()
{
AddSearchEvent(
itemTitle: "Series A",
searchType: SeekerSearchType.Replacement,
searchReason: SeekerSearchReason.Replacement);
var result = await _controller.GetEvents();
var body = GetResponseBody(result);
var item = body.GetProperty("Items")[0];
item.GetProperty("SearchType").GetString().ShouldBe(nameof(SeekerSearchType.Replacement));
item.GetProperty("SearchReason").GetString().ShouldBe(nameof(SeekerSearchReason.Replacement));
}
#endregion
#region GetEvents Filtering
[Fact]
public async Task GetEvents_WithInstanceIdFilter_FiltersByArrInstanceId()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
var sonarr = SeekerTestDataFactory.AddSonarrInstance(_dataContext);
AddSearchEvent(arrInstanceId: radarr.Id, itemTitle: "Radarr Movie");
AddSearchEvent(arrInstanceId: sonarr.Id, itemTitle: "Sonarr Series");
var result = await _controller.GetEvents(instanceId: radarr.Id);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(1);
body.GetProperty("Items")[0].GetProperty("ArrInstanceId").GetString().ShouldBe(radarr.Id.ToString());
}
[Fact]
public async Task GetEvents_WithCycleIdFilter_ReturnsOnlyMatchingCycle()
{
var cycleA = Guid.NewGuid();
var cycleB = Guid.NewGuid();
AddSearchEvent(cycleId: cycleA, itemTitle: "Cycle A Movie");
AddSearchEvent(cycleId: cycleB, itemTitle: "Cycle B Movie");
var result = await _controller.GetEvents(cycleId: cycleA);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(1);
body.GetProperty("Items")[0].GetProperty("ItemTitle").GetString().ShouldBe("Cycle A Movie");
}
[Fact]
public async Task GetEvents_WithSearchFilter_FiltersOnItemTitle()
{
AddSearchEvent(itemTitle: "The Matrix");
AddSearchEvent(itemTitle: "Breaking Bad");
var result = await _controller.GetEvents(search: "matrix");
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(1);
}
[Fact]
public async Task GetEvents_WithPagination_ReturnsCorrectPageAndCount()
{
for (int i = 0; i < 5; i++)
{
AddSearchEvent(itemTitle: $"Event {i}");
}
var result = await _controller.GetEvents(page: 2, pageSize: 2);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(5);
body.GetProperty("TotalPages").GetInt32().ShouldBe(3);
body.GetProperty("Page").GetInt32().ShouldBe(2);
body.GetProperty("Items").GetArrayLength().ShouldBe(2);
}
[Fact]
public async Task GetEvents_WithSortByTitleAscending_OrdersAlphabetically()
{
AddSearchEvent(itemTitle: "Charlie");
AddSearchEvent(itemTitle: "Alpha");
AddSearchEvent(itemTitle: "Bravo");
var result = await _controller.GetEvents(
sortBy: SearchEventsSortBy.Title,
sortDirection: Cleanuparr.Domain.Enums.SortDirection.Asc);
var body = GetResponseBody(result);
var items = body.GetProperty("Items");
items[0].GetProperty("ItemTitle").GetString().ShouldBe("Alpha");
items[1].GetProperty("ItemTitle").GetString().ShouldBe("Bravo");
items[2].GetProperty("ItemTitle").GetString().ShouldBe("Charlie");
}
[Fact]
public async Task GetEvents_WithSortByTimestampAscending_OldestFirst()
{
AddSearchEvent(itemTitle: "Newest", timestamp: DateTime.UtcNow);
AddSearchEvent(itemTitle: "Oldest", timestamp: DateTime.UtcNow.AddHours(-2));
AddSearchEvent(itemTitle: "Middle", timestamp: DateTime.UtcNow.AddHours(-1));
var result = await _controller.GetEvents(sortDirection: Cleanuparr.Domain.Enums.SortDirection.Asc);
var body = GetResponseBody(result);
var items = body.GetProperty("Items");
items[0].GetProperty("ItemTitle").GetString().ShouldBe("Oldest");
items[2].GetProperty("ItemTitle").GetString().ShouldBe("Newest");
}
[Fact]
public async Task GetEvents_WithSearchStatusFilter_ReturnsOnlyMatchingStatuses()
{
AddSearchEvent(itemTitle: "A", searchStatus: SearchCommandStatus.Completed);
AddSearchEvent(itemTitle: "B", searchStatus: SearchCommandStatus.Failed);
AddSearchEvent(itemTitle: "C", searchStatus: SearchCommandStatus.TimedOut);
var result = await _controller.GetEvents(
searchStatus: [SearchCommandStatus.Completed, SearchCommandStatus.Failed]);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(2);
}
[Fact]
public async Task GetEvents_WithSearchTypeFilter_ReturnsOnlyMatchingType()
{
AddSearchEvent(itemTitle: "Proactive Movie", searchType: SeekerSearchType.Proactive);
AddSearchEvent(itemTitle: "Replacement Movie", searchType: SeekerSearchType.Replacement);
var result = await _controller.GetEvents(searchType: SeekerSearchType.Replacement);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(1);
body.GetProperty("Items")[0].GetProperty("ItemTitle").GetString().ShouldBe("Replacement Movie");
}
[Fact]
public async Task GetEvents_WithSearchReasonFilter_ReturnsOnlyMatchingReason()
{
AddSearchEvent(itemTitle: "Missing", searchReason: SeekerSearchReason.Missing);
AddSearchEvent(itemTitle: "Cutoff", searchReason: SeekerSearchReason.QualityCutoffNotMet);
var result = await _controller.GetEvents(searchReason: SeekerSearchReason.QualityCutoffNotMet);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(1);
body.GetProperty("Items")[0].GetProperty("ItemTitle").GetString().ShouldBe("Cutoff");
}
[Fact]
public async Task GetEvents_WithGrabbedTrue_KeepsOnlyEventsWithGrabbedItems()
{
AddSearchEvent(itemTitle: "With Grabs", grabbedItems: ["movie (2024)"]);
AddSearchEvent(itemTitle: "No Grabs", grabbedItems: []);
var result = await _controller.GetEvents(grabbed: true);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(1);
body.GetProperty("Items")[0].GetProperty("ItemTitle").GetString().ShouldBe("With Grabs");
}
[Fact]
public async Task GetEvents_WithGrabbedFalse_KeepsOnlyEventsWithoutGrabbedItems()
{
AddSearchEvent(itemTitle: "With Grabs", grabbedItems: ["movie (2024)"]);
AddSearchEvent(itemTitle: "No Grabs", grabbedItems: []);
var result = await _controller.GetEvents(grabbed: false);
var body = GetResponseBody(result);
body.GetProperty("TotalCount").GetInt32().ShouldBe(1);
body.GetProperty("Items")[0].GetProperty("ItemTitle").GetString().ShouldBe("No Grabs");
}
#endregion
#region Helpers
private void AddSearchEvent(
string? itemTitle = null,
SeekerSearchType searchType = SeekerSearchType.Proactive,
SeekerSearchReason searchReason = SeekerSearchReason.Missing,
List<string>? grabbedItems = null,
Guid? arrInstanceId = null,
Guid? cycleId = null,
SearchCommandStatus? searchStatus = null,
DateTime? timestamp = null)
{
var appEvent = new AppEvent
{
EventType = EventType.SearchTriggered,
Message = "Search triggered",
Severity = EventSeverity.Information,
ArrInstanceId = arrInstanceId,
CycleId = cycleId,
SearchStatus = searchStatus,
Timestamp = timestamp ?? DateTime.UtcNow
};
_eventsContext.Events.Add(appEvent);
_eventsContext.SaveChanges();
if (itemTitle is not null)
{
_eventsContext.SearchEventData.Add(new SearchEventData
{
AppEventId = appEvent.Id,
ItemTitle = itemTitle,
SearchType = searchType,
SearchReason = searchReason,
GrabbedItems = grabbedItems ?? [],
});
_eventsContext.SaveChanges();
}
}
#endregion
}
@@ -0,0 +1,388 @@
using Cleanuparr.Api.Features.Seeker.Contracts.Requests;
using Cleanuparr.Api.Features.Seeker.Contracts.Responses;
using Cleanuparr.Api.Features.Seeker.Controllers;
using Cleanuparr.Api.Tests.Features.Seeker.TestHelpers;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Infrastructure.Services.Interfaces;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Configuration.Seeker;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Shouldly;
using ValidationException = Cleanuparr.Domain.Exceptions.ValidationException;
namespace Cleanuparr.Api.Tests.Features.Seeker;
public class SeekerConfigControllerTests : IDisposable
{
private readonly DataContext _dataContext;
private readonly ILogger<SeekerConfigController> _logger;
private readonly IJobManagementService _jobManagementService;
private readonly SeekerConfigController _controller;
public SeekerConfigControllerTests()
{
_dataContext = SeekerTestDataFactory.CreateDataContext();
_logger = Substitute.For<ILogger<SeekerConfigController>>();
_jobManagementService = Substitute.For<IJobManagementService>();
_controller = new SeekerConfigController(_logger, _dataContext, _jobManagementService);
}
public void Dispose()
{
_dataContext.Dispose();
GC.SuppressFinalize(this);
}
#region GetSeekerConfig Tests
[Fact]
public async Task GetSeekerConfig_WithNoSeekerInstanceConfigs_ReturnsDefaults()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
var result = await _controller.GetSeekerConfig();
var okResult = result.ShouldBeOfType<OkObjectResult>();
var response = okResult.Value.ShouldBeOfType<SeekerConfigResponse>();
var instance = response.Instances.ShouldHaveSingleItem();
instance.ArrInstanceId.ShouldBe(radarr.Id);
instance.Enabled.ShouldBeFalse();
instance.SkipTags.ShouldBeEmpty();
instance.ActiveDownloadLimit.ShouldBe(3);
instance.MinCycleTimeDays.ShouldBe(7);
}
[Fact]
public async Task GetSeekerConfig_OnlyReturnsSonarrAndRadarrInstances()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
var sonarr = SeekerTestDataFactory.AddSonarrInstance(_dataContext);
var lidarr = SeekerTestDataFactory.AddLidarrInstance(_dataContext);
var result = await _controller.GetSeekerConfig();
var okResult = result.ShouldBeOfType<OkObjectResult>();
var response = okResult.Value.ShouldBeOfType<SeekerConfigResponse>();
response.Instances.Count.ShouldBe(2);
response.Instances.ShouldContain(i => i.ArrInstanceId == radarr.Id);
response.Instances.ShouldContain(i => i.ArrInstanceId == sonarr.Id);
response.Instances.ShouldNotContain(i => i.ArrInstanceId == lidarr.Id);
}
#endregion
#region UpdateSeekerConfig Tests
[Fact]
public async Task UpdateSeekerConfig_WithProactiveEnabledAndNoInstancesEnabled_ThrowsValidationException()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
var request = new UpdateSeekerConfigRequest
{
SearchEnabled = true,
SearchInterval = 5,
ProactiveSearchEnabled = true,
Instances =
[
new UpdateSeekerInstanceConfigRequest
{
ArrInstanceId = radarr.Id,
Enabled = false // No instances enabled
}
]
};
await Should.ThrowAsync<ValidationException>(() => _controller.UpdateSeekerConfig(request));
}
[Fact]
public async Task UpdateSeekerConfig_WhenIntervalChanges_ReschedulesSeeker()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
_dataContext.SeekerInstanceConfigs.Add(new SeekerInstanceConfig
{
ArrInstanceId = radarr.Id,
Enabled = true
});
await _dataContext.SaveChangesAsync();
// Default interval is 3, change to 5
var request = new UpdateSeekerConfigRequest
{
SearchEnabled = true,
SearchInterval = 5,
ProactiveSearchEnabled = true,
Instances =
[
new UpdateSeekerInstanceConfigRequest { ArrInstanceId = radarr.Id, Enabled = true }
]
};
await _controller.UpdateSeekerConfig(request);
await _jobManagementService.Received(1)
.StartJob(JobType.Seeker, null, Arg.Any<string>());
}
[Fact]
public async Task UpdateSeekerConfig_WhenIntervalUnchanged_DoesNotReschedule()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
_dataContext.SeekerInstanceConfigs.Add(new SeekerInstanceConfig
{
ArrInstanceId = radarr.Id,
Enabled = true
});
await _dataContext.SaveChangesAsync();
// Keep interval at default (3)
var request = new UpdateSeekerConfigRequest
{
SearchEnabled = true,
SearchInterval = 3,
ProactiveSearchEnabled = true,
Instances =
[
new UpdateSeekerInstanceConfigRequest { ArrInstanceId = radarr.Id, Enabled = true }
]
};
await _controller.UpdateSeekerConfig(request);
await _jobManagementService.DidNotReceive()
.StartJob(Arg.Any<JobType>(), null, Arg.Any<string>());
}
[Fact]
public async Task UpdateSeekerConfig_WhenCustomFormatScoreEnabled_StartsAndTriggersSyncerJob()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
_dataContext.SeekerInstanceConfigs.Add(new SeekerInstanceConfig
{
ArrInstanceId = radarr.Id,
Enabled = true
});
await _dataContext.SaveChangesAsync();
// UseCustomFormatScore was false (default), now enable it on the instance
var request = new UpdateSeekerConfigRequest
{
SearchEnabled = true,
SearchInterval = 3,
ProactiveSearchEnabled = true,
Instances =
[
new UpdateSeekerInstanceConfigRequest { ArrInstanceId = radarr.Id, Enabled = true, UseCustomFormatScore = true }
]
};
await _controller.UpdateSeekerConfig(request);
await _jobManagementService.Received(1)
.StartJob(JobType.CustomFormatScoreSyncer, null, Arg.Any<string>());
await _jobManagementService.Received(1)
.TriggerJobOnce(JobType.CustomFormatScoreSyncer);
}
[Fact]
public async Task UpdateSeekerConfig_WhenCustomFormatScoreDisabled_StopsSyncerJob()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
_dataContext.SeekerInstanceConfigs.Add(new SeekerInstanceConfig
{
ArrInstanceId = radarr.Id,
Enabled = true,
UseCustomFormatScore = true
});
// Syncer was running: both proactive and CF score were enabled
var config = await _dataContext.SeekerConfigs.FirstAsync();
config.ProactiveSearchEnabled = true;
await _dataContext.SaveChangesAsync();
// Disable CF score — syncer conditions no longer met
var request = new UpdateSeekerConfigRequest
{
SearchEnabled = true,
SearchInterval = 3,
ProactiveSearchEnabled = true,
Instances =
[
new UpdateSeekerInstanceConfigRequest { ArrInstanceId = radarr.Id, Enabled = true, UseCustomFormatScore = false }
]
};
await _controller.UpdateSeekerConfig(request);
await _jobManagementService.Received(1)
.StopJob(JobType.CustomFormatScoreSyncer);
}
[Fact]
public async Task UpdateSeekerConfig_WhenProactiveSearchDisabled_StopsSyncerJob()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
_dataContext.SeekerInstanceConfigs.Add(new SeekerInstanceConfig
{
ArrInstanceId = radarr.Id,
Enabled = true,
UseCustomFormatScore = true
});
// Syncer was running: both proactive and CF score were enabled
var config = await _dataContext.SeekerConfigs.FirstAsync();
config.ProactiveSearchEnabled = true;
await _dataContext.SaveChangesAsync();
// Disable proactive search — syncer should stop even though CF score is still enabled
var request = new UpdateSeekerConfigRequest
{
SearchEnabled = true,
SearchInterval = 3,
ProactiveSearchEnabled = false,
Instances =
[
new UpdateSeekerInstanceConfigRequest { ArrInstanceId = radarr.Id, Enabled = true, UseCustomFormatScore = true }
]
};
await _controller.UpdateSeekerConfig(request);
await _jobManagementService.Received(1)
.StopJob(JobType.CustomFormatScoreSyncer);
}
[Fact]
public async Task UpdateSeekerConfig_WhenProactiveSearchEnabled_WithCfScoreActive_StartsAndTriggersSyncer()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
_dataContext.SeekerInstanceConfigs.Add(new SeekerInstanceConfig
{
ArrInstanceId = radarr.Id,
Enabled = true,
UseCustomFormatScore = true
});
// Syncer was NOT running: CF score enabled but proactive was off (default)
await _dataContext.SaveChangesAsync();
// Enable proactive search — syncer should start
var request = new UpdateSeekerConfigRequest
{
SearchEnabled = true,
SearchInterval = 3,
ProactiveSearchEnabled = true,
Instances =
[
new UpdateSeekerInstanceConfigRequest { ArrInstanceId = radarr.Id, Enabled = true, UseCustomFormatScore = true }
]
};
await _controller.UpdateSeekerConfig(request);
await _jobManagementService.Received(1)
.StartJob(JobType.CustomFormatScoreSyncer, null, Arg.Any<string>());
await _jobManagementService.Received(1)
.TriggerJobOnce(JobType.CustomFormatScoreSyncer);
}
[Fact]
public async Task UpdateSeekerConfig_WhenCustomFormatScoreEnabledButProactiveDisabled_DoesNotStartSyncer()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
_dataContext.SeekerInstanceConfigs.Add(new SeekerInstanceConfig
{
ArrInstanceId = radarr.Id,
Enabled = true,
UseCustomFormatScore = false
});
// ProactiveSearchEnabled stays false (default)
await _dataContext.SaveChangesAsync();
// Enable CF score but keep proactive disabled — syncer should NOT start
var request = new UpdateSeekerConfigRequest
{
SearchEnabled = true,
SearchInterval = 3,
ProactiveSearchEnabled = false,
Instances =
[
new UpdateSeekerInstanceConfigRequest { ArrInstanceId = radarr.Id, Enabled = true, UseCustomFormatScore = true }
]
};
await _controller.UpdateSeekerConfig(request);
await _jobManagementService.DidNotReceive()
.StartJob(JobType.CustomFormatScoreSyncer, null, Arg.Any<string>());
await _jobManagementService.DidNotReceive()
.TriggerJobOnce(JobType.CustomFormatScoreSyncer);
}
[Fact]
public async Task UpdateSeekerConfig_SyncsExistingAndCreatesNewInstanceConfigs()
{
var radarr = SeekerTestDataFactory.AddRadarrInstance(_dataContext);
var sonarr = SeekerTestDataFactory.AddSonarrInstance(_dataContext);
// Radarr already has a config
_dataContext.SeekerInstanceConfigs.Add(new SeekerInstanceConfig
{
ArrInstanceId = radarr.Id,
Enabled = false,
SkipTags = ["old-tag"],
ActiveDownloadLimit = 2,
MinCycleTimeDays = 5
});
await _dataContext.SaveChangesAsync();
var request = new UpdateSeekerConfigRequest
{
SearchEnabled = true,
SearchInterval = 3,
ProactiveSearchEnabled = true,
Instances =
[
// Update existing radarr config
new UpdateSeekerInstanceConfigRequest
{
ArrInstanceId = radarr.Id,
Enabled = true,
SkipTags = ["new-tag"],
ActiveDownloadLimit = 5,
MinCycleTimeDays = 14
},
// Create new sonarr config
new UpdateSeekerInstanceConfigRequest
{
ArrInstanceId = sonarr.Id,
Enabled = true,
SkipTags = ["sonarr-tag"],
ActiveDownloadLimit = 3,
MinCycleTimeDays = 7
}
]
};
await _controller.UpdateSeekerConfig(request);
var configs = await _dataContext.SeekerInstanceConfigs.ToListAsync();
configs.Count.ShouldBe(2);
var radarrConfig = configs.First(c => c.ArrInstanceId == radarr.Id);
radarrConfig.Enabled.ShouldBeTrue();
radarrConfig.SkipTags.ShouldContain("new-tag");
radarrConfig.ActiveDownloadLimit.ShouldBe(5);
radarrConfig.MinCycleTimeDays.ShouldBe(14);
var sonarrConfig = configs.First(c => c.ArrInstanceId == sonarr.Id);
sonarrConfig.Enabled.ShouldBeTrue();
sonarrConfig.SkipTags.ShouldContain("sonarr-tag");
}
#endregion
}
@@ -0,0 +1,166 @@
using Cleanuparr.Domain.Enums;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Configuration;
using Cleanuparr.Persistence.Models.Configuration.Arr;
using Cleanuparr.Persistence.Models.Configuration.DownloadCleaner;
using Cleanuparr.Persistence.Models.Configuration.General;
using Cleanuparr.Persistence.Models.Configuration.MalwareBlocker;
using Cleanuparr.Persistence.Models.Configuration.QueueCleaner;
using Cleanuparr.Persistence.Models.Configuration.Seeker;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace Cleanuparr.Api.Tests.Features.Seeker.TestHelpers;
/// <summary>
/// Factory for creating SQLite in-memory contexts for Seeker controller tests
/// </summary>
public static class SeekerTestDataFactory
{
public static DataContext CreateDataContext()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<DataContext>()
.UseSqlite(connection)
.UseLowerCaseNamingConvention()
.UseSnakeCaseNamingConvention()
.Options;
var context = new DataContext(options);
context.Database.EnsureCreated();
SeedDefaultData(context);
return context;
}
public static EventsContext CreateEventsContext()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<EventsContext>()
.UseSqlite(connection)
.UseLowerCaseNamingConvention()
.UseSnakeCaseNamingConvention()
.Options;
var context = new EventsContext(options);
context.Database.EnsureCreated();
return context;
}
private static void SeedDefaultData(DataContext context)
{
context.GeneralConfigs.Add(new GeneralConfig
{
Id = Guid.NewGuid(),
DryRun = false,
IgnoredDownloads = [],
Log = new LoggingConfig()
});
context.ArrConfigs.AddRange(
new ArrConfig { Id = Guid.NewGuid(), Type = InstanceType.Sonarr, Instances = [], FailedImportMaxStrikes = 3 },
new ArrConfig { Id = Guid.NewGuid(), Type = InstanceType.Radarr, Instances = [], FailedImportMaxStrikes = 3 },
new ArrConfig { Id = Guid.NewGuid(), Type = InstanceType.Lidarr, Instances = [], FailedImportMaxStrikes = 3 },
new ArrConfig { Id = Guid.NewGuid(), Type = InstanceType.Readarr, Instances = [], FailedImportMaxStrikes = 3 },
new ArrConfig { Id = Guid.NewGuid(), Type = InstanceType.Whisparr, Instances = [], FailedImportMaxStrikes = 3 }
);
context.QueueCleanerConfigs.Add(new QueueCleanerConfig
{
Id = Guid.NewGuid(),
IgnoredDownloads = [],
FailedImport = new FailedImportConfig()
});
context.ContentBlockerConfigs.Add(new ContentBlockerConfig
{
Id = Guid.NewGuid(),
IgnoredDownloads = [],
DeletePrivate = false,
Sonarr = new BlocklistSettings { Enabled = false },
Radarr = new BlocklistSettings { Enabled = false },
Lidarr = new BlocklistSettings { Enabled = false },
Readarr = new BlocklistSettings { Enabled = false },
Whisparr = new BlocklistSettings { Enabled = false }
});
context.DownloadCleanerConfigs.Add(new DownloadCleanerConfig
{
Id = Guid.NewGuid(),
IgnoredDownloads = []
});
context.SeekerConfigs.Add(new SeekerConfig
{
Id = Guid.NewGuid(),
SearchEnabled = true,
ProactiveSearchEnabled = false
});
context.SaveChanges();
}
public static ArrInstance AddSonarrInstance(DataContext context, bool enabled = true)
{
var arrConfig = context.ArrConfigs.First(x => x.Type == InstanceType.Sonarr);
var instance = new ArrInstance
{
Id = Guid.NewGuid(),
Name = "Test Sonarr",
Url = new Uri("http://sonarr:8989"),
ApiKey = "test-api-key",
Enabled = enabled,
ArrConfigId = arrConfig.Id,
ArrConfig = arrConfig
};
arrConfig.Instances.Add(instance);
context.ArrInstances.Add(instance);
context.SaveChanges();
return instance;
}
public static ArrInstance AddRadarrInstance(DataContext context, bool enabled = true)
{
var arrConfig = context.ArrConfigs.First(x => x.Type == InstanceType.Radarr);
var instance = new ArrInstance
{
Id = Guid.NewGuid(),
Name = "Test Radarr",
Url = new Uri("http://radarr:7878"),
ApiKey = "test-api-key",
Enabled = enabled,
ArrConfigId = arrConfig.Id,
ArrConfig = arrConfig
};
arrConfig.Instances.Add(instance);
context.ArrInstances.Add(instance);
context.SaveChanges();
return instance;
}
public static ArrInstance AddLidarrInstance(DataContext context, bool enabled = true)
{
var arrConfig = context.ArrConfigs.First(x => x.Type == InstanceType.Lidarr);
var instance = new ArrInstance
{
Id = Guid.NewGuid(),
Name = "Test Lidarr",
Url = new Uri("http://lidarr:8686"),
ApiKey = "test-api-key",
Enabled = enabled,
ArrConfigId = arrConfig.Id,
ArrConfig = arrConfig
};
arrConfig.Instances.Add(instance);
context.ArrInstances.Add(instance);
context.SaveChanges();
return instance;
}
}
@@ -1,6 +1,9 @@
using Cleanuparr.Api.Features.Arr.Contracts.Requests;
using Cleanuparr.Api.Features.DownloadClient.Contracts.Requests;
using Cleanuparr.Api.Features.Auth.Contracts.Requests;
using Cleanuparr.Api.Features.General.Contracts.Requests;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Persistence.Models.Auth;
using Cleanuparr.Persistence.Models.Configuration.Arr;
using Cleanuparr.Persistence.Models.Configuration;
using Cleanuparr.Shared.Helpers;
@@ -314,4 +317,65 @@ public class SensitiveDataInputTests
}
#endregion
#region UpdateOidcConfigRequest UPDATE
[Fact]
public void UpdateOidcConfigRequest_ApplyTo_WithPlaceholderClientSecret_PreservesExistingValue()
{
var request = new UpdateOidcConfigRequest
{
Enabled = true,
IssuerUrl = "http://localhost:8080/realms/test",
ClientId = "cleanuparr",
ClientSecret = Placeholder,
Scopes = "openid profile email",
ProviderName = "Keycloak",
};
var existingConfig = new OidcConfig
{
Enabled = true,
IssuerUrl = "http://localhost:8080/realms/test",
ClientId = "cleanuparr",
ClientSecret = "original-secret",
Scopes = "openid profile email",
ProviderName = "OIDC",
};
request.ApplyTo(existingConfig);
existingConfig.ClientSecret.ShouldBe("original-secret");
existingConfig.ProviderName.ShouldBe("Keycloak");
}
[Fact]
public void UpdateOidcConfigRequest_ApplyTo_WithRealClientSecret_UpdatesValue()
{
var request = new UpdateOidcConfigRequest
{
Enabled = true,
IssuerUrl = "http://localhost:8080/realms/test",
ClientId = "cleanuparr",
ClientSecret = "brand-new-secret",
Scopes = "openid profile email",
ProviderName = "Keycloak",
};
var existingConfig = new OidcConfig
{
Enabled = true,
IssuerUrl = "http://localhost:8080/realms/test",
ClientId = "cleanuparr",
ClientSecret = "original-secret",
Scopes = "openid profile email",
ProviderName = "OIDC",
};
request.ApplyTo(existingConfig);
existingConfig.ClientSecret.ShouldBe("brand-new-secret");
}
#endregion
}
@@ -0,0 +1,164 @@
using Cleanuparr.Api.Features.Webhooks.Contracts;
using Cleanuparr.Api.Features.Webhooks.Controllers;
using Cleanuparr.Api.Tests.TestHelpers;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Infrastructure.Services.Interfaces;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Configuration.Arr;
using Cleanuparr.Persistence.Models.Configuration.MalwareBlocker;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Shouldly;
namespace Cleanuparr.Api.Tests.Features.Webhooks;
public class WebhooksControllerTests : IDisposable
{
private readonly DataContext _dataContext;
private readonly IJobManagementService _jobManagement;
private readonly WebhooksController _controller;
private Guid _sonarrInstanceId;
private Guid _lidarrInstanceId;
public WebhooksControllerTests()
{
_dataContext = CreateDataContext();
_jobManagement = Substitute.For<IJobManagementService>();
var logger = Substitute.For<ILogger<WebhooksController>>();
_controller = new WebhooksController(logger, _dataContext, _jobManagement);
ControllerTestContext.Attach(_controller);
}
public void Dispose()
{
_dataContext.Dispose();
GC.SuppressFinalize(this);
}
private DataContext CreateDataContext()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<DataContext>().UseSqlite(connection).Options;
var context = new DataContext(options);
context.Database.EnsureCreated();
var sonarrInstance = new ArrInstance { Enabled = true, Name = "Sonarr", Url = new Uri("http://sonarr:8989"), ApiKey = "key" };
var lidarrInstance = new ArrInstance { Enabled = true, Name = "Lidarr", Url = new Uri("http://lidarr:8686"), ApiKey = "key" };
_sonarrInstanceId = sonarrInstance.Id;
_lidarrInstanceId = lidarrInstance.Id;
context.ArrConfigs.AddRange(
new ArrConfig { Type = InstanceType.Sonarr, Instances = [sonarrInstance] },
new ArrConfig { Type = InstanceType.Lidarr, Instances = [lidarrInstance] }
);
context.ContentBlockerConfigs.Add(new ContentBlockerConfig
{
Enabled = true,
TriggerMode = JobTriggerMode.Both,
IgnoredDownloads = [],
});
context.SaveChanges();
return context;
}
private void SetConfig(bool enabled, JobTriggerMode mode)
{
var config = _dataContext.ContentBlockerConfigs.First();
config.Enabled = enabled;
config.TriggerMode = mode;
_dataContext.SaveChanges();
}
private static ArrWebhookPayload GrabPayload(string? downloadId = "HASH123", long seriesId = 42) => new()
{
EventType = "Grab",
DownloadId = downloadId,
Series = new ArrWebhookContent { Id = seriesId },
};
[Fact]
public async Task TestEvent_ReturnsOk_AndDoesNotSchedule()
{
var result = await _controller.TriggerMalwareBlocker(_sonarrInstanceId, new ArrWebhookPayload { EventType = "Test" });
result.ShouldBeOfType<OkResult>();
await _jobManagement.DidNotReceive()
.TriggerMalwareBlockerWebhook(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<long>(), Arg.Any<InstanceType>());
}
[Fact]
public async Task ValidGrab_SchedulesTargetedScan()
{
var result = await _controller.TriggerMalwareBlocker(_sonarrInstanceId, GrabPayload());
result.ShouldBeOfType<OkResult>();
await _jobManagement.Received(1)
.TriggerMalwareBlockerWebhook(_sonarrInstanceId, "HASH123", 42, InstanceType.Sonarr);
}
[Fact]
public async Task UnknownInstance_ReturnsNotFound()
{
var result = await _controller.TriggerMalwareBlocker(Guid.NewGuid(), GrabPayload());
var notFound = result.ShouldBeOfType<ObjectResult>();
notFound.StatusCode.ShouldBe(StatusCodes.Status404NotFound);
notFound.Value.ShouldBeOfType<ProblemDetails>();
await _jobManagement.DidNotReceive()
.TriggerMalwareBlockerWebhook(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<long>(), Arg.Any<InstanceType>());
}
[Fact]
public async Task NonSonarrRadarrInstance_ReturnsUnprocessable()
{
var result = await _controller.TriggerMalwareBlocker(_lidarrInstanceId, GrabPayload());
var unprocessable = result.ShouldBeOfType<ObjectResult>();
unprocessable.StatusCode.ShouldBe(StatusCodes.Status422UnprocessableEntity);
unprocessable.Value.ShouldBeOfType<ProblemDetails>();
await _jobManagement.DidNotReceive()
.TriggerMalwareBlockerWebhook(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<long>(), Arg.Any<InstanceType>());
}
[Fact]
public async Task Disabled_ReturnsOk_AndDoesNotSchedule()
{
SetConfig(enabled: false, JobTriggerMode.Both);
var result = await _controller.TriggerMalwareBlocker(_sonarrInstanceId, GrabPayload());
result.ShouldBeOfType<OkResult>();
await _jobManagement.DidNotReceive()
.TriggerMalwareBlockerWebhook(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<long>(), Arg.Any<InstanceType>());
}
[Fact]
public async Task ScheduleOnlyMode_ReturnsOk_AndDoesNotSchedule()
{
SetConfig(enabled: true, JobTriggerMode.Schedule);
var result = await _controller.TriggerMalwareBlocker(_sonarrInstanceId, GrabPayload());
result.ShouldBeOfType<OkResult>();
await _jobManagement.DidNotReceive()
.TriggerMalwareBlockerWebhook(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<long>(), Arg.Any<InstanceType>());
}
[Fact]
public async Task EmptyDownloadId_ReturnsOk_AndDoesNotSchedule()
{
var result = await _controller.TriggerMalwareBlocker(_sonarrInstanceId, GrabPayload(downloadId: null));
result.ShouldBeOfType<OkResult>();
await _jobManagement.DidNotReceive()
.TriggerMalwareBlockerWebhook(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<long>(), Arg.Any<InstanceType>());
}
}
@@ -0,0 +1,108 @@
using Cleanuparr.Api.DependencyInjection;
using Cleanuparr.Api.Middleware;
using Cleanuparr.Domain.Exceptions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Shouldly;
namespace Cleanuparr.Api.Tests.Middleware;
public class GlobalExceptionHandlerTests
{
private static readonly ProblemDetailsFactory ProblemDetailsFactory = BuildProblemDetailsFactory();
private static ProblemDetailsFactory BuildProblemDetailsFactory()
{
ServiceCollection services = new();
services.AddLogging();
services.AddControllers();
services.AddCleanuparrProblemDetails();
return services.BuildServiceProvider().GetRequiredService<ProblemDetailsFactory>();
}
private static async Task<(bool handled, HttpContext context, ProblemDetails problemDetails)> Handle(Exception exception)
{
IProblemDetailsService problemDetailsService = Substitute.For<IProblemDetailsService>();
problemDetailsService
.TryWriteAsync(Arg.Any<ProblemDetailsContext>())
.Returns(callInfo => ValueTask.FromResult(true));
DefaultHttpContext context = new();
GlobalExceptionHandler handler = new(problemDetailsService, ProblemDetailsFactory, NullLogger<GlobalExceptionHandler>.Instance);
bool handled = await handler.TryHandleAsync(context, exception, CancellationToken.None);
ProblemDetailsContext captured = (ProblemDetailsContext)problemDetailsService
.ReceivedCalls()
.Single()
.GetArguments()[0]!;
return (handled, context, captured.ProblemDetails);
}
[Fact]
public async Task ValidationException_MapsTo400_WithMessageAsDetail()
{
(bool handled, HttpContext context, ProblemDetails problemDetails) = await Handle(new ValidationException("Name is required"));
handled.ShouldBeTrue();
context.Response.StatusCode.ShouldBe(StatusCodes.Status400BadRequest);
problemDetails.Status.ShouldBe(StatusCodes.Status400BadRequest);
problemDetails.Title.ShouldBe("Validation failed");
problemDetails.Detail.ShouldBe("Name is required");
problemDetails.Type.ShouldNotBeNullOrEmpty();
problemDetails.Extensions.ShouldContainKey("traceId");
}
[Fact]
public async Task NotificationTestException_MapsTo400()
{
(bool handled, HttpContext context, ProblemDetails problemDetails) = await Handle(new NotificationTestException("Test failed: connection refused"));
handled.ShouldBeTrue();
context.Response.StatusCode.ShouldBe(StatusCodes.Status400BadRequest);
problemDetails.Status.ShouldBe(StatusCodes.Status400BadRequest);
problemDetails.Title.ShouldBe("Notification test failed");
problemDetails.Detail.ShouldBe("Test failed: connection refused");
}
[Fact]
public async Task RateLimitException_MapsTo429_WithRetryAfterExtensionAndHeader()
{
(bool handled, HttpContext context, ProblemDetails problemDetails) = await Handle(new RateLimitException("Account is locked", 30));
handled.ShouldBeTrue();
context.Response.StatusCode.ShouldBe(StatusCodes.Status429TooManyRequests);
problemDetails.Status.ShouldBe(StatusCodes.Status429TooManyRequests);
problemDetails.Title.ShouldBe("Too many requests");
problemDetails.Extensions["retryAfterSeconds"].ShouldBe(30);
context.Response.Headers.RetryAfter.ToString().ShouldBe("30");
}
[Fact]
public async Task RateLimitException_WithZeroRetry_MapsTo429_WithoutRetryAfter()
{
(bool handled, HttpContext context, ProblemDetails problemDetails) = await Handle(new RateLimitException("Too many pending OIDC flows", 0));
handled.ShouldBeTrue();
context.Response.StatusCode.ShouldBe(StatusCodes.Status429TooManyRequests);
problemDetails.Extensions.ShouldNotContainKey("retryAfterSeconds");
context.Response.Headers.RetryAfter.ToString().ShouldBeEmpty();
}
[Fact]
public async Task UnknownException_MapsTo500_WithGenericDetail_AndDoesNotLeakMessage()
{
(bool handled, HttpContext context, ProblemDetails problemDetails) = await Handle(new InvalidOperationException("internal connection string leaked"));
handled.ShouldBeTrue();
context.Response.StatusCode.ShouldBe(StatusCodes.Status500InternalServerError);
problemDetails.Status.ShouldBe(StatusCodes.Status500InternalServerError);
problemDetails.Detail.ShouldBe("An unexpected error occurred");
problemDetails.Detail.ShouldNotContain("connection string");
}
}
@@ -0,0 +1,226 @@
using System.Net;
using Cleanuparr.Api.Middleware;
using Microsoft.AspNetCore.Http;
using Shouldly;
namespace Cleanuparr.Api.Tests.Middleware;
public class TrustedForwardedHeadersMiddlewareTests
{
private static HttpContext NewContext(IPAddress peer, Action<HttpContext>? configure = null)
{
var ctx = new DefaultHttpContext();
ctx.Connection.RemoteIpAddress = peer;
ctx.Request.Scheme = "http";
ctx.Request.Host = new HostString("backend.local");
configure?.Invoke(ctx);
return ctx;
}
[Fact]
public void Untrusted_direct_peer_leaves_everything_alone()
{
var ctx = NewContext(IPAddress.Parse("203.0.113.1"), c =>
{
c.Request.Headers["X-Forwarded-For"] = "10.0.0.5";
c.Request.Headers["X-Forwarded-Proto"] = "https";
c.Request.Headers["X-Forwarded-Host"] = "spoofed.example.com";
});
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string>());
ctx.Connection.RemoteIpAddress.ShouldBe(IPAddress.Parse("203.0.113.1"));
ctx.Request.Scheme.ShouldBe("http");
ctx.Request.Host.Value.ShouldBe("backend.local");
}
[Fact]
public void Local_peer_no_xff_is_a_no_op()
{
var ctx = NewContext(IPAddress.Loopback);
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string>());
ctx.Connection.RemoteIpAddress.ShouldBe(IPAddress.Loopback);
}
[Fact]
public void Spoofed_local_xff_with_appended_attacker_promotes_attacker_ip_only()
{
var ctx = NewContext(IPAddress.Loopback, c =>
c.Request.Headers["X-Forwarded-For"] = "10.0.0.5, 99.99.99.99");
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string>());
ctx.Connection.RemoteIpAddress.ShouldBe(IPAddress.Parse("99.99.99.99"));
}
[Fact]
public void Single_xff_entry_from_overwrite_mode_proxy_becomes_client_ip()
{
var ctx = NewContext(IPAddress.Loopback, c => c.Request.Headers["X-Forwarded-For"] = "203.0.113.45");
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string>());
ctx.Connection.RemoteIpAddress.ShouldBe(IPAddress.Parse("203.0.113.45"));
}
[Fact]
public void Legitimate_lan_client_through_local_proxy_resolves_to_lan_ip()
{
var ctx = NewContext(IPAddress.Loopback, c => c.Request.Headers["X-Forwarded-For"] = "192.168.1.50");
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string>());
ctx.Connection.RemoteIpAddress.ShouldBe(IPAddress.Parse("192.168.1.50"));
}
[Fact]
public void Custom_trusted_network_pops_through_to_real_client()
{
var ctx = NewContext(IPAddress.Loopback, c => c.Request.Headers["X-Forwarded-For"] = "100.64.1.5, 100.64.0.7");
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string> { "100.64.0.0/10" });
ctx.Connection.RemoteIpAddress.ShouldBe(IPAddress.Parse("100.64.1.5"));
}
[Fact]
public void Forwarded_proto_and_host_applied_when_chain_consumed()
{
var ctx = NewContext(IPAddress.Loopback, c =>
{
c.Request.Headers["X-Forwarded-For"] = "203.0.113.45";
c.Request.Headers["X-Forwarded-Proto"] = "https";
c.Request.Headers["X-Forwarded-Host"] = "cleanuparr.example.com";
});
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string>());
ctx.Request.Scheme.ShouldBe("https");
ctx.Request.Host.Value.ShouldBe("cleanuparr.example.com");
}
[Fact]
public void Forwarded_proto_not_applied_when_peer_untrusted()
{
var ctx = NewContext(IPAddress.Parse("203.0.113.1"), c => c.Request.Headers["X-Forwarded-Proto"] = "https");
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string>());
ctx.Request.Scheme.ShouldBe("http");
}
[Fact]
public void X_real_ip_is_ignored()
{
var ctx = NewContext(IPAddress.Loopback, c => c.Request.Headers["X-Real-IP"] = "10.0.0.5");
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string>());
ctx.Connection.RemoteIpAddress.ShouldBe(IPAddress.Loopback);
}
[Fact]
public void Malformed_xff_entry_fails_closed()
{
var ctx = NewContext(IPAddress.Loopback, c =>
{
c.Request.Headers["X-Forwarded-For"] = "10.0.0.5, not-an-ip";
c.Request.Headers["X-Forwarded-Proto"] = "https";
});
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string>());
ctx.Connection.RemoteIpAddress.ShouldBe(IPAddress.Loopback);
ctx.Request.Scheme.ShouldBe("http");
}
[Fact]
public void Empty_entries_in_xff_are_skipped()
{
// nginx with `proxy_set_header X-Forwarded-For "$http_x_forwarded_for, 1.2.3.4"`
// produces a leading empty entry when the input header was absent.
var ctx = NewContext(IPAddress.Loopback, c => c.Request.Headers["X-Forwarded-For"] = ", 99.99.99.99");
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string>());
ctx.Connection.RemoteIpAddress.ShouldBe(IPAddress.Parse("99.99.99.99"));
}
[Fact]
public void Ipv4_mapped_ipv6_loopback_is_treated_as_trusted()
{
// Kestrel may surface "::ffff:127.0.0.1" as the peer.
var mapped = IPAddress.Parse("::ffff:127.0.0.1");
var ctx = NewContext(mapped, c => c.Request.Headers["X-Forwarded-For"] = "203.0.113.45");
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string>());
ctx.Connection.RemoteIpAddress.ShouldBe(IPAddress.Parse("203.0.113.45"));
}
[Fact]
public void Forwarded_proto_with_multiple_values_uses_only_first_token()
{
// Chained proxies that append (rather than overwrite) X-Forwarded-Proto
// produce comma-separated values like "https, http". Only the leftmost
// hop's value should be applied — matching how XFF is handled.
var ctx = NewContext(IPAddress.Loopback, c =>
{
c.Request.Headers["X-Forwarded-For"] = "203.0.113.45";
c.Request.Headers["X-Forwarded-Proto"] = "https, http";
});
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string>());
ctx.Request.Scheme.ShouldBe("https");
}
[Fact]
public void Forwarded_proto_with_unknown_scheme_is_ignored()
{
// Anything outside the http/https allowlist is dropped to keep
// arbitrary values (e.g. "javascript:") from flowing into URLs.
var ctx = NewContext(IPAddress.Loopback, c =>
{
c.Request.Headers["X-Forwarded-For"] = "203.0.113.45";
c.Request.Headers["X-Forwarded-Proto"] = "javascript:";
});
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string>());
ctx.Request.Scheme.ShouldBe("http");
}
[Fact]
public void Forwarded_host_with_multiple_values_uses_only_first_token()
{
// Same multi-hop concern as X-Forwarded-Proto — the host string must
// not end up as "a.example, b.example".
var ctx = NewContext(IPAddress.Loopback, c =>
{
c.Request.Headers["X-Forwarded-For"] = "203.0.113.45";
c.Request.Headers["X-Forwarded-Host"] = "cleanuparr.example.com, attacker.example.com";
});
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string>());
ctx.Request.Host.Value.ShouldBe("cleanuparr.example.com");
}
[Fact]
public void Malformed_entry_mid_chain_does_not_partially_mutate_remote_ip()
{
// Walk right-to-left: 10.0.0.5 (trusted) is popped first, then
// "not-an-ip" fails. The pre-fix middleware committed mutation eagerly,
// leaving RemoteIpAddress = 10.0.0.5. Fix: validate-then-commit, so the
// original peer is preserved when any chain entry is malformed.
var ctx = NewContext(IPAddress.Loopback, c =>
c.Request.Headers["X-Forwarded-For"] = "not-an-ip, 10.0.0.5");
TrustedForwardedHeadersMiddleware.ApplyForwardedHeaders(ctx, new List<string>());
ctx.Connection.RemoteIpAddress.ShouldBe(IPAddress.Loopback);
}
}
@@ -0,0 +1,9 @@
namespace Cleanuparr.Api.Tests;
/// <summary>
/// Auth integration tests share the file-system config directory (users.db via
/// SetupGuardMiddleware.CreateStaticInstance). Grouping them in one collection
/// forces sequential execution and prevents inter-factory interference.
/// </summary>
[CollectionDefinition("Auth Integration Tests")]
public class AuthIntegrationTestsCollection { }
@@ -0,0 +1,35 @@
using Cleanuparr.Api.DependencyInjection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
namespace Cleanuparr.Api.Tests.TestHelpers;
/// <summary>
/// Attaches a minimal MVC <see cref="ControllerContext"/> (with a real <see cref="ProblemDetailsFactory"/>
/// and <see cref="HttpContext"/>) to a directly-instantiated controller so that
/// <c>this.ProblemResult(...)</c> can build problem-details responses in unit tests.
/// </summary>
public static class ControllerTestContext
{
private static readonly IServiceProvider Services = BuildServices();
private static IServiceProvider BuildServices()
{
ServiceCollection services = new();
services.AddLogging();
services.AddControllers();
services.AddCleanuparrProblemDetails();
return services.BuildServiceProvider();
}
public static void Attach(ControllerBase controller)
{
controller.ControllerContext = new ControllerContext
{
HttpContext = new DefaultHttpContext { RequestServices = Services },
};
controller.ProblemDetailsFactory = Services.GetRequiredService<ProblemDetailsFactory>();
}
}
@@ -0,0 +1,5 @@
{
"$schema": "https://xunit.net/schema/current/xunit.runner.schema.json",
"parallelizeAssembly": false,
"parallelizeTestCollections": false
}
@@ -16,19 +16,22 @@ public static class TrustedNetworkAuthenticationDefaults
public class TrustedNetworkAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly DataContext _dataContext;
public TrustedNetworkAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder)
UrlEncoder encoder,
DataContext dataContext)
: base(options, logger, encoder)
{
_dataContext = dataContext;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
// Load auth config from database
await using var dataContext = DataContext.CreateStaticInstance();
var config = await dataContext.GeneralConfigs.AsNoTracking().FirstOrDefaultAsync();
var config = await _dataContext.GeneralConfigs.AsNoTracking().FirstOrDefaultAsync();
if (config is null || !config.Auth.DisableAuthForLocalAddresses)
{
@@ -36,7 +39,7 @@ public class TrustedNetworkAuthenticationHandler : AuthenticationHandler<Authent
}
// Determine client IP
var clientIp = GetClientIp(config.Auth.TrustForwardedHeaders);
var clientIp = ResolveClientIp(Context);
if (clientIp is null)
{
return AuthenticateResult.NoResult();
@@ -73,42 +76,13 @@ public class TrustedNetworkAuthenticationHandler : AuthenticationHandler<Authent
return AuthenticateResult.Success(ticket);
}
private IPAddress? GetClientIp(bool trustForwardedHeaders) =>
ResolveClientIp(Context, trustForwardedHeaders);
public static IPAddress? ResolveClientIp(HttpContext httpContext, bool trustForwardedHeaders)
{
var remoteIp = httpContext.Connection.RemoteIpAddress;
if (remoteIp is null)
{
return null;
}
// Only trust forwarded headers if the direct connection is from a local address
if (trustForwardedHeaders && remoteIp.IsLocalAddress())
{
// Check X-Forwarded-For first, then X-Real-IP
var forwardedFor = httpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (!string.IsNullOrEmpty(forwardedFor))
{
// X-Forwarded-For can contain multiple IPs: client, proxy1, proxy2
// The first one is the original client
var firstIp = forwardedFor.Split(',')[0].Trim();
if (IPAddress.TryParse(firstIp, out var parsedIp))
{
return parsedIp;
}
}
var realIp = httpContext.Request.Headers["X-Real-IP"].FirstOrDefault();
if (!string.IsNullOrEmpty(realIp) && IPAddress.TryParse(realIp, out var realParsedIp))
{
return realParsedIp;
}
}
return remoteIp;
}
/// <summary>
/// Returns the connection's remote IP address. Callers must run <see cref="Cleanuparr.Api.Middleware.TrustedForwardedHeadersMiddleware"/>
/// earlier in the pipeline so that <c>X-Forwarded-*</c> headers from trusted proxy chains have already been resolved into <c>Connection.RemoteIpAddress</c>.
/// </summary>
/// <param name="httpContext">The current HTTP context.</param>
/// <returns>The resolved client IP, or <c>null</c> when unavailable.</returns>
public static IPAddress? ResolveClientIp(HttpContext httpContext) => httpContext.Connection.RemoteIpAddress;
public static bool IsTrustedAddress(IPAddress clientIp, List<string> trustedNetworks)
{
@@ -26,11 +26,11 @@ public class EventsController : ControllerBase
[HttpGet]
public async Task<ActionResult<PaginatedResult<AppEvent>>> GetEvents(
[FromQuery] int page = 1,
[FromQuery] int pageSize = 100,
[FromQuery] int pageSize = 50,
[FromQuery] string? severity = null,
[FromQuery] string? eventType = null,
[FromQuery] DateTime? fromDate = null,
[FromQuery] DateTime? toDate = null,
[FromQuery] DateTimeOffset? fromDate = null,
[FromQuery] DateTimeOffset? toDate = null,
[FromQuery] string? search = null,
[FromQuery] string? jobRunId = null)
{
@@ -42,12 +42,12 @@ public class EventsController : ControllerBase
if (pageSize < 1)
{
pageSize = 100;
pageSize = 50;
}
if (pageSize > 1000)
if (pageSize > 500)
{
pageSize = 1000; // Cap at 1000 for performance
pageSize = 500;
}
var query = _context.Events.AsQueryable();
@@ -90,8 +90,6 @@ public class EventsController : ControllerBase
EF.Functions.Like(e.Message, pattern) ||
EF.Functions.Like(e.Data, pattern) ||
EF.Functions.Like(e.TrackingId.ToString(), pattern) ||
EF.Functions.Like(e.InstanceUrl, pattern) ||
EF.Functions.Like(e.DownloadClientName, pattern) ||
EF.Functions.Like(e.JobRunId.ToString(), pattern)
);
}
@@ -157,7 +155,7 @@ public class EventsController : ControllerBase
[HttpPost("cleanup")]
public async Task<ActionResult<object>> CleanupOldEvents([FromQuery] int retentionDays = 30)
{
var cutoffDate = DateTime.UtcNow.AddDays(-retentionDays);
var cutoffDate = DateTimeOffset.UtcNow.AddDays(-retentionDays);
await _context.Events
.Where(e => e.Timestamp < cutoffDate)
@@ -1,3 +1,4 @@
using Cleanuparr.Api.Extensions;
using Cleanuparr.Infrastructure.Health;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -12,17 +13,13 @@ namespace Cleanuparr.Api.Controllers;
[Authorize]
public class HealthCheckController : ControllerBase
{
private readonly ILogger<HealthCheckController> _logger;
private readonly IHealthCheckService _healthCheckService;
/// <summary>
/// Initializes a new instance of the <see cref="HealthCheckController"/> class
/// </summary>
public HealthCheckController(
ILogger<HealthCheckController> logger,
IHealthCheckService healthCheckService)
public HealthCheckController(IHealthCheckService healthCheckService)
{
_logger = logger;
_healthCheckService = healthCheckService;
}
@@ -32,16 +29,8 @@ public class HealthCheckController : ControllerBase
[HttpGet]
public IActionResult GetAllHealth()
{
try
{
var healthStatuses = _healthCheckService.GetAllClientHealth();
return Ok(healthStatuses);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error retrieving client health statuses");
return StatusCode(500, new { Error = "An error occurred while retrieving client health statuses" });
}
var healthStatuses = _healthCheckService.GetAllClientHealth();
return Ok(healthStatuses);
}
/// <summary>
@@ -50,21 +39,13 @@ public class HealthCheckController : ControllerBase
[HttpGet("{id:guid}")]
public IActionResult GetClientHealth(Guid id)
{
try
var healthStatus = _healthCheckService.GetClientHealth(id);
if (healthStatus == null)
{
var healthStatus = _healthCheckService.GetClientHealth(id);
if (healthStatus == null)
{
return NotFound(new { Message = $"Health status for client with ID '{id}' not found" });
}
return this.ProblemResult(StatusCodes.Status404NotFound, $"Health status for client with ID '{id}' not found");
}
return Ok(healthStatus);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error retrieving health status for client {id}", id);
return StatusCode(500, new { Error = "An error occurred while retrieving the client health status" });
}
return Ok(healthStatus);
}
/// <summary>
@@ -73,16 +54,8 @@ public class HealthCheckController : ControllerBase
[HttpPost("check")]
public async Task<IActionResult> CheckAllHealth()
{
try
{
var results = await _healthCheckService.CheckAllClientsHealthAsync();
return Ok(results);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error checking health for all clients");
return StatusCode(500, new { Error = "An error occurred while checking client health" });
}
var results = await _healthCheckService.CheckAllClientsHealthAsync();
return Ok(results);
}
/// <summary>
@@ -91,15 +64,7 @@ public class HealthCheckController : ControllerBase
[HttpPost("check/{id:guid}")]
public async Task<IActionResult> CheckClientHealth(Guid id)
{
try
{
var result = await _healthCheckService.CheckClientHealthAsync(id);
return Ok(result);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error checking health for client {id}", id);
return StatusCode(500, new { Error = "An error occurred while checking client health" });
}
var result = await _healthCheckService.CheckClientHealthAsync(id);
return Ok(result);
}
}
@@ -36,13 +36,13 @@ public class HealthController : ControllerBase
registration => registration.Tags.Contains("liveness"));
return result.Status == HealthStatus.Healthy
? Ok(new { status = "healthy", timestamp = DateTime.UtcNow })
: StatusCode(503, new { status = "unhealthy", timestamp = DateTime.UtcNow });
? Ok(new { status = "healthy", timestamp = DateTimeOffset.UtcNow })
: StatusCode(503, new { status = "unhealthy", timestamp = DateTimeOffset.UtcNow });
}
catch (Exception ex)
{
_logger.LogError(ex, "Health check failed");
return StatusCode(503, new { status = "unhealthy", error = "Health check failed", timestamp = DateTime.UtcNow });
return StatusCode(503, new { status = "unhealthy", error = "Health check failed", timestamp = DateTimeOffset.UtcNow });
}
}
@@ -62,13 +62,13 @@ public class HealthController : ControllerBase
if (result.Status == HealthStatus.Healthy)
{
return Ok(new { status = "ready", timestamp = DateTime.UtcNow });
return Ok(new { status = "ready", timestamp = DateTimeOffset.UtcNow });
}
// For readiness, we consider degraded as not ready
return StatusCode(503, new {
status = "not_ready",
timestamp = DateTime.UtcNow,
timestamp = DateTimeOffset.UtcNow,
details = result.Entries.Where(e => e.Value.Status != HealthStatus.Healthy)
.ToDictionary(e => e.Key, e => new {
status = e.Value.Status.ToString().ToLowerInvariant(),
@@ -79,7 +79,7 @@ public class HealthController : ControllerBase
catch (Exception ex)
{
_logger.LogError(ex, "Readiness check failed");
return StatusCode(503, new { status = "not_ready", error = "Readiness check failed", timestamp = DateTime.UtcNow });
return StatusCode(503, new { status = "not_ready", error = "Readiness check failed", timestamp = DateTimeOffset.UtcNow });
}
}
@@ -97,7 +97,7 @@ public class HealthController : ControllerBase
var response = new
{
status = result.Status.ToString().ToLowerInvariant(),
timestamp = DateTime.UtcNow,
timestamp = DateTimeOffset.UtcNow,
totalDuration = result.TotalDuration.TotalMilliseconds,
entries = result.Entries.ToDictionary(
e => e.Key,
@@ -122,7 +122,7 @@ public class HealthController : ControllerBase
return StatusCode(503, new {
status = "unhealthy",
error = "Detailed health check failed",
timestamp = DateTime.UtcNow
timestamp = DateTimeOffset.UtcNow
});
}
}
@@ -1,3 +1,4 @@
using Cleanuparr.Api.Extensions;
using Cleanuparr.Api.Models;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Infrastructure.Models;
@@ -13,114 +14,87 @@ namespace Cleanuparr.Api.Controllers;
public class JobsController : ControllerBase
{
private readonly IJobManagementService _jobManagementService;
private readonly ILogger<JobsController> _logger;
public JobsController(IJobManagementService jobManagementService, ILogger<JobsController> logger)
public JobsController(IJobManagementService jobManagementService)
{
_jobManagementService = jobManagementService;
_logger = logger;
}
[HttpGet]
public async Task<IActionResult> GetAllJobs()
{
try
{
var result = await _jobManagementService.GetAllJobs();
return Ok(result);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting all jobs");
return StatusCode(500, "An error occurred while retrieving jobs");
}
var result = await _jobManagementService.GetAllJobs();
return Ok(result);
}
[HttpGet("{jobType}")]
public async Task<IActionResult> GetJob(JobType jobType)
{
try
var jobInfo = await _jobManagementService.GetJob(jobType);
if (jobInfo.Status == "Not Found")
{
var jobInfo = await _jobManagementService.GetJob(jobType);
if (jobInfo.Status == "Not Found")
{
return NotFound($"Job '{jobType}' not found");
}
return Ok(jobInfo);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting job {jobType}", jobType);
return StatusCode(500, $"An error occurred while retrieving job '{jobType}'");
return this.ProblemResult(StatusCodes.Status404NotFound, $"Job '{jobType}' not found");
}
return Ok(jobInfo);
}
[HttpPost("{jobType}/start")]
public async Task<IActionResult> StartJob(JobType jobType, [FromBody] ScheduleRequest scheduleRequest = null)
public async Task<IActionResult> StartJob(JobType jobType, [FromBody] ScheduleRequest scheduleRequest)
{
try
if (jobType == JobType.Seeker)
{
// Get the schedule from the request body if provided
JobSchedule jobSchedule = scheduleRequest.Schedule;
var result = await _jobManagementService.StartJob(jobType, jobSchedule);
if (!result)
{
return BadRequest($"Failed to start job '{jobType}'");
}
return Ok(new { Message = $"Job '{jobType}' started successfully" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "The Seeker job cannot be manually controlled");
}
catch (Exception ex)
// Get the schedule from the request body if provided
JobSchedule jobSchedule = scheduleRequest.Schedule;
var result = await _jobManagementService.StartJob(jobType, jobSchedule);
if (!result)
{
_logger.LogError(ex, "Error starting job {jobType}", jobType);
return StatusCode(500, $"An error occurred while starting job '{jobType}'");
return this.ProblemResult(StatusCodes.Status400BadRequest, $"Failed to start job '{jobType}'");
}
return Ok(new { Message = $"Job '{jobType}' started successfully" });
}
[HttpPost("{jobType}/trigger")]
public async Task<IActionResult> TriggerJob(JobType jobType)
{
try
if (jobType == JobType.Seeker)
{
var result = await _jobManagementService.TriggerJobOnce(jobType);
if (!result)
{
return BadRequest($"Failed to trigger job '{jobType}' - job may not exist or be configured");
}
return Ok(new { Message = $"Job '{jobType}' triggered successfully for one-time execution" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "The Seeker job cannot be manually triggered");
}
catch (Exception ex)
var result = await _jobManagementService.TriggerJobOnce(jobType);
if (!result)
{
_logger.LogError(ex, "Error triggering job {jobType}", jobType);
return StatusCode(500, $"An error occurred while triggering job '{jobType}'");
return this.ProblemResult(StatusCodes.Status400BadRequest, $"Failed to trigger job '{jobType}' - job may not exist or be configured");
}
return Ok(new { Message = $"Job '{jobType}' triggered successfully for one-time execution" });
}
[HttpPut("{jobType}/schedule")]
public async Task<IActionResult> UpdateJobSchedule(JobType jobType, [FromBody] ScheduleRequest scheduleRequest)
{
if (scheduleRequest?.Schedule == null)
if (jobType == JobType.Seeker)
{
return BadRequest("Schedule is required");
return this.ProblemResult(StatusCodes.Status400BadRequest, "The Seeker job schedule cannot be manually modified");
}
try
if (scheduleRequest?.Schedule == null)
{
var result = await _jobManagementService.UpdateJobSchedule(jobType, scheduleRequest.Schedule);
if (!result)
{
return BadRequest($"Failed to update schedule for job '{jobType}'");
}
return Ok(new { Message = $"Job '{jobType}' schedule updated successfully" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "Schedule is required");
}
catch (Exception ex)
var result = await _jobManagementService.UpdateJobSchedule(jobType, scheduleRequest.Schedule);
if (!result)
{
_logger.LogError(ex, "Error updating job {jobType} schedule", jobType);
return StatusCode(500, $"An error occurred while updating schedule for job '{jobType}'");
return this.ProblemResult(StatusCodes.Status400BadRequest, $"Failed to update schedule for job '{jobType}'");
}
return Ok(new { Message = $"Job '{jobType}' schedule updated successfully" });
}
}
@@ -25,17 +25,28 @@ public class ManualEventsController : ControllerBase
[HttpGet]
public async Task<ActionResult<PaginatedResult<ManualEvent>>> GetManualEvents(
[FromQuery] int page = 1,
[FromQuery] int pageSize = 100,
[FromQuery] int pageSize = 50,
[FromQuery] bool? isResolved = null,
[FromQuery] string? severity = null,
[FromQuery] DateTime? fromDate = null,
[FromQuery] DateTime? toDate = null,
[FromQuery] DateTimeOffset? fromDate = null,
[FromQuery] DateTimeOffset? toDate = null,
[FromQuery] string? search = null)
{
// Validate pagination parameters
if (page < 1) page = 1;
if (pageSize < 1) pageSize = 100;
if (pageSize > 1000) pageSize = 1000; // Cap at 1000 for performance
if (page < 1)
{
page = 1;
}
if (pageSize < 1)
{
pageSize = 50;
}
if (pageSize > 500)
{
pageSize = 500;
}
var query = _context.ManualEvents.AsQueryable();
@@ -68,9 +79,7 @@ public class ManualEventsController : ControllerBase
string pattern = EventsContext.GetLikePattern(search);
query = query.Where(e =>
EF.Functions.Like(e.Message, pattern) ||
EF.Functions.Like(e.Data, pattern) ||
EF.Functions.Like(e.InstanceUrl, pattern) ||
EF.Functions.Like(e.DownloadClientName, pattern)
EF.Functions.Like(e.Data, pattern)
);
}
@@ -173,7 +182,7 @@ public class ManualEventsController : ControllerBase
[HttpPost("cleanup")]
public async Task<ActionResult<object>> CleanupOldResolvedEvents([FromQuery] int retentionDays = 30)
{
var cutoffDate = DateTime.UtcNow.AddDays(-retentionDays);
var cutoffDate = DateTimeOffset.UtcNow.AddDays(-retentionDays);
var deletedCount = await _context.ManualEvents
.Where(e => e.IsResolved && e.Timestamp < cutoffDate)
@@ -12,14 +12,10 @@ namespace Cleanuparr.Api.Controllers;
[Authorize]
public class StatsController : ControllerBase
{
private readonly ILogger<StatsController> _logger;
private readonly IStatsService _statsService;
public StatsController(
ILogger<StatsController> logger,
IStatsService statsService)
public StatsController(IStatsService statsService)
{
_logger = logger;
_statsService = statsService;
}
@@ -35,19 +31,11 @@ public class StatsController : ControllerBase
[FromQuery] int includeEvents = 0,
[FromQuery] int includeStrikes = 0)
{
try
{
hours = Math.Clamp(hours, 1, 720);
includeEvents = Math.Clamp(includeEvents, 0, 100);
includeStrikes = Math.Clamp(includeStrikes, 0, 100);
hours = Math.Clamp(hours, 1, 720);
includeEvents = Math.Clamp(includeEvents, 0, 100);
includeStrikes = Math.Clamp(includeStrikes, 0, 100);
var stats = await _statsService.GetStatsAsync(hours, includeEvents, includeStrikes);
return Ok(stats);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error retrieving stats");
return StatusCode(500, new { Error = "An error occurred while retrieving stats" });
}
var stats = await _statsService.GetStatsAsync(hours, includeEvents, includeStrikes);
return Ok(stats);
}
}
@@ -13,16 +13,13 @@ namespace Cleanuparr.Api.Controllers;
[Authorize]
public class StatusController : ControllerBase
{
private readonly ILogger<StatusController> _logger;
private readonly DataContext _dataContext;
private readonly IArrClientFactory _arrClientFactory;
public StatusController(
ILogger<StatusController> logger,
DataContext dataContext,
IArrClientFactory arrClientFactory)
{
_logger = logger;
_dataContext = dataContext;
_arrClientFactory = arrClientFactory;
}
@@ -30,247 +27,219 @@ public class StatusController : ControllerBase
[HttpGet]
public async Task<IActionResult> GetSystemStatus()
{
try
{
var process = Process.GetCurrentProcess();
// Get configuration
var downloadClients = await _dataContext.DownloadClients
.AsNoTracking()
.ToListAsync();
var sonarrConfig = await _dataContext.ArrConfigs
.Include(x => x.Instances)
.AsNoTracking()
.FirstAsync(x => x.Type == InstanceType.Sonarr);
var radarrConfig = await _dataContext.ArrConfigs
.Include(x => x.Instances)
.AsNoTracking()
.FirstAsync(x => x.Type == InstanceType.Radarr);
var lidarrConfig = await _dataContext.ArrConfigs
.Include(x => x.Instances)
.AsNoTracking()
.FirstAsync(x => x.Type == InstanceType.Lidarr);
var readarrConfig = await _dataContext.ArrConfigs
.Include(x => x.Instances)
.AsNoTracking()
.FirstAsync(x => x.Type == InstanceType.Readarr);
var status = new
{
Application = new
{
Version = GetType().Assembly.GetName().Version?.ToString() ?? "Unknown",
process.StartTime,
UpTime = DateTime.Now - process.StartTime,
MemoryUsageMB = Math.Round(process.WorkingSet64 / 1024.0 / 1024.0, 2),
ProcessorTime = process.TotalProcessorTime
},
DownloadClient = new
{
// TODO
},
MediaManagers = new
{
Sonarr = new
{
InstanceCount = sonarrConfig.Instances.Count
},
Radarr = new
{
InstanceCount = radarrConfig.Instances.Count
},
Lidarr = new
{
InstanceCount = lidarrConfig.Instances.Count
},
Readarr = new
{
InstanceCount = readarrConfig.Instances.Count
}
}
};
using var process = Process.GetCurrentProcess();
return Ok(status);
}
catch (Exception ex)
// Get configuration
var sonarrConfig = await _dataContext.ArrConfigs
.Include(x => x.Instances)
.AsNoTracking()
.FirstAsync(x => x.Type == InstanceType.Sonarr);
var radarrConfig = await _dataContext.ArrConfigs
.Include(x => x.Instances)
.AsNoTracking()
.FirstAsync(x => x.Type == InstanceType.Radarr);
var lidarrConfig = await _dataContext.ArrConfigs
.Include(x => x.Instances)
.AsNoTracking()
.FirstAsync(x => x.Type == InstanceType.Lidarr);
var readarrConfig = await _dataContext.ArrConfigs
.Include(x => x.Instances)
.AsNoTracking()
.FirstAsync(x => x.Type == InstanceType.Readarr);
var status = new
{
_logger.LogError(ex, "Error retrieving system status");
return StatusCode(500, "An error occurred while retrieving system status");
}
Application = new
{
Version = GetType().Assembly.GetName().Version?.ToString() ?? "Unknown",
process.StartTime,
UpTime = DateTimeOffset.UtcNow - process.StartTime.ToUniversalTime(),
MemoryUsageMB = Math.Round(process.WorkingSet64 / 1024.0 / 1024.0, 2),
ProcessorTime = process.TotalProcessorTime
},
DownloadClient = new
{
// TODO
},
MediaManagers = new
{
Sonarr = new
{
InstanceCount = sonarrConfig.Instances.Count
},
Radarr = new
{
InstanceCount = radarrConfig.Instances.Count
},
Lidarr = new
{
InstanceCount = lidarrConfig.Instances.Count
},
Readarr = new
{
InstanceCount = readarrConfig.Instances.Count
}
}
};
return Ok(status);
}
[HttpGet("download-client")]
public async Task<IActionResult> GetDownloadClientStatus()
{
try
var downloadClients = await _dataContext.DownloadClients
.AsNoTracking()
.ToListAsync();
var result = new Dictionary<string, object>();
// Check for configured clients
if (downloadClients.Count > 0)
{
var downloadClients = await _dataContext.DownloadClients
.AsNoTracking()
.ToListAsync();
var result = new Dictionary<string, object>();
// Check for configured clients
if (downloadClients.Count > 0)
var clientsStatus = new List<object>();
foreach (var client in downloadClients)
{
var clientsStatus = new List<object>();
foreach (var client in downloadClients)
clientsStatus.Add(new
{
clientsStatus.Add(new
{
client.Id,
client.Name,
Type = client.TypeName,
client.Host,
client.Enabled,
IsConnected = client.Enabled, // We can't check connection status without implementing test methods
});
}
result["Clients"] = clientsStatus;
client.Id,
client.Name,
Type = client.TypeName,
client.Host,
client.Enabled,
IsConnected = client.Enabled, // We can't check connection status without implementing test methods
});
}
return Ok(result);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error retrieving download client status");
return StatusCode(500, "An error occurred while retrieving download client status");
result["Clients"] = clientsStatus;
}
return Ok(result);
}
[HttpGet("arrs")]
public async Task<IActionResult> GetMediaManagersStatus()
{
try
var status = new Dictionary<string, object>();
// Get configurations
var enabledSonarrInstances = await _dataContext.ArrConfigs
.Include(x => x.Instances)
.Where(x => x.Type == InstanceType.Sonarr)
.SelectMany(x => x.Instances)
.Where(x => x.Enabled)
.AsNoTracking()
.ToListAsync();
var enabledRadarrInstances = await _dataContext.ArrConfigs
.Include(x => x.Instances)
.Where(x => x.Type == InstanceType.Radarr)
.SelectMany(x => x.Instances)
.Where(x => x.Enabled)
.AsNoTracking()
.ToListAsync();
var enabledLidarrInstances = await _dataContext.ArrConfigs
.Include(x => x.Instances)
.Where(x => x.Type == InstanceType.Lidarr)
.SelectMany(x => x.Instances)
.Where(x => x.Enabled)
.AsNoTracking()
.ToListAsync();
// Check Sonarr instances
var sonarrStatus = new List<object>();
foreach (var instance in enabledSonarrInstances)
{
var status = new Dictionary<string, object>();
// Get configurations
var enabledSonarrInstances = await _dataContext.ArrConfigs
.Include(x => x.Instances)
.Where(x => x.Type == InstanceType.Sonarr)
.SelectMany(x => x.Instances)
.Where(x => x.Enabled)
.AsNoTracking()
.ToListAsync();
var enabledRadarrInstances = await _dataContext.ArrConfigs
.Include(x => x.Instances)
.Where(x => x.Type == InstanceType.Radarr)
.SelectMany(x => x.Instances)
.Where(x => x.Enabled)
.AsNoTracking()
.ToListAsync();
var enabledLidarrInstances = await _dataContext.ArrConfigs
.Include(x => x.Instances)
.Where(x => x.Type == InstanceType.Lidarr)
.SelectMany(x => x.Instances)
.Where(x => x.Enabled)
.AsNoTracking()
.ToListAsync();;
// Check Sonarr instances
var sonarrStatus = new List<object>();
foreach (var instance in enabledSonarrInstances)
try
{
try
var sonarrClient = _arrClientFactory.GetClient(InstanceType.Sonarr, instance.Version);
await sonarrClient.HealthCheckAsync(instance);
sonarrStatus.Add(new
{
var sonarrClient = _arrClientFactory.GetClient(InstanceType.Sonarr, instance.Version);
await sonarrClient.HealthCheckAsync(instance);
sonarrStatus.Add(new
{
instance.Name,
instance.Url,
IsConnected = true,
Message = "Successfully connected"
});
}
catch (Exception ex)
{
sonarrStatus.Add(new
{
instance.Name,
instance.Url,
IsConnected = false,
Message = $"Connection failed: {ex.Message}"
});
}
instance.Name,
instance.Url,
IsConnected = true,
Message = "Successfully connected"
});
}
status["Sonarr"] = sonarrStatus;
// Check Radarr instances
var radarrStatus = new List<object>();
foreach (var instance in enabledRadarrInstances)
catch (Exception ex)
{
try
sonarrStatus.Add(new
{
var radarrClient = _arrClientFactory.GetClient(InstanceType.Radarr, instance.Version);
await radarrClient.HealthCheckAsync(instance);
radarrStatus.Add(new
{
instance.Name,
instance.Url,
IsConnected = true,
Message = "Successfully connected"
});
}
catch (Exception ex)
{
radarrStatus.Add(new
{
instance.Name,
instance.Url,
IsConnected = false,
Message = $"Connection failed: {ex.Message}"
});
}
instance.Name,
instance.Url,
IsConnected = false,
Message = $"Connection failed: {ex.Message}"
});
}
status["Radarr"] = radarrStatus;
// Check Lidarr instances
var lidarrStatus = new List<object>();
foreach (var instance in enabledLidarrInstances)
{
try
{
var lidarrClient = _arrClientFactory.GetClient(InstanceType.Lidarr, instance.Version);
await lidarrClient.HealthCheckAsync(instance);
lidarrStatus.Add(new
{
instance.Name,
instance.Url,
IsConnected = true,
Message = "Successfully connected"
});
}
catch (Exception ex)
{
lidarrStatus.Add(new
{
instance.Name,
instance.Url,
IsConnected = false,
Message = $"Connection failed: {ex.Message}"
});
}
}
status["Lidarr"] = lidarrStatus;
return Ok(status);
}
catch (Exception ex)
status["Sonarr"] = sonarrStatus;
// Check Radarr instances
var radarrStatus = new List<object>();
foreach (var instance in enabledRadarrInstances)
{
_logger.LogError(ex, "Error retrieving media managers status");
return StatusCode(500, "An error occurred while retrieving media managers status");
try
{
var radarrClient = _arrClientFactory.GetClient(InstanceType.Radarr, instance.Version);
await radarrClient.HealthCheckAsync(instance);
radarrStatus.Add(new
{
instance.Name,
instance.Url,
IsConnected = true,
Message = "Successfully connected"
});
}
catch (Exception ex)
{
radarrStatus.Add(new
{
instance.Name,
instance.Url,
IsConnected = false,
Message = $"Connection failed: {ex.Message}"
});
}
}
status["Radarr"] = radarrStatus;
// Check Lidarr instances
var lidarrStatus = new List<object>();
foreach (var instance in enabledLidarrInstances)
{
try
{
var lidarrClient = _arrClientFactory.GetClient(InstanceType.Lidarr, instance.Version);
await lidarrClient.HealthCheckAsync(instance);
lidarrStatus.Add(new
{
instance.Name,
instance.Url,
IsConnected = true,
Message = "Successfully connected"
});
}
catch (Exception ex)
{
lidarrStatus.Add(new
{
instance.Name,
instance.Url,
IsConnected = false,
Message = $"Connection failed: {ex.Message}"
});
}
}
status["Lidarr"] = lidarrStatus;
return Ok(status);
}
}
@@ -29,9 +29,20 @@ public class StrikesController : ControllerBase
[FromQuery] string? search = null,
[FromQuery] string? type = null)
{
if (page < 1) page = 1;
if (pageSize < 1) pageSize = 50;
if (pageSize > 100) pageSize = 100;
if (page < 1)
{
page = 1;
}
if (pageSize < 1)
{
pageSize = 50;
}
if (pageSize > 500)
{
pageSize = 500;
}
var query = _context.DownloadItems
.Include(d => d.Strikes)
@@ -77,6 +88,7 @@ public class StrikesController : ControllerBase
IsMarkedForRemoval = d.IsMarkedForRemoval,
IsRemoved = d.IsRemoved,
IsReturning = d.IsReturning,
HasDryRunStrikes = d.Strikes.Any(s => s.IsDryRun),
Strikes = d.Strikes
.OrderByDescending(s => s.CreatedAt)
.Select(s => new StrikeDetailDto
@@ -86,6 +98,7 @@ public class StrikesController : ControllerBase
CreatedAt = s.CreatedAt,
LastDownloadedBytes = s.LastDownloadedBytes,
JobRunId = s.JobRunId,
IsDryRun = s.IsDryRun,
}).ToList(),
}).ToList();
@@ -120,6 +133,7 @@ public class StrikesController : ControllerBase
CreatedAt = s.CreatedAt,
DownloadId = s.DownloadItem.DownloadId,
Title = s.DownloadItem.Title,
IsDryRun = s.IsDryRun,
})
.ToListAsync();
@@ -164,11 +178,12 @@ public class DownloadItemStrikesDto
public string Title { get; set; } = string.Empty;
public int TotalStrikes { get; set; }
public Dictionary<string, int> StrikesByType { get; set; } = new();
public DateTime LatestStrikeAt { get; set; }
public DateTime FirstStrikeAt { get; set; }
public DateTimeOffset LatestStrikeAt { get; set; }
public DateTimeOffset FirstStrikeAt { get; set; }
public bool IsMarkedForRemoval { get; set; }
public bool IsRemoved { get; set; }
public bool IsReturning { get; set; }
public bool HasDryRunStrikes { get; set; }
public List<StrikeDetailDto> Strikes { get; set; } = [];
}
@@ -176,16 +191,18 @@ public class StrikeDetailDto
{
public Guid Id { get; set; }
public string Type { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public long? LastDownloadedBytes { get; set; }
public Guid JobRunId { get; set; }
public bool IsDryRun { get; set; }
}
public class RecentStrikeDto
{
public Guid Id { get; set; }
public string Type { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public string DownloadId { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public bool IsDryRun { get; set; }
}
@@ -1,3 +1,4 @@
using System.Diagnostics;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using Cleanuparr.Api.Filters;
@@ -55,29 +56,53 @@ public static class ApiDI
// Add health status broadcaster
services.AddHostedService<HealthStatusBroadcaster>();
services.AddCleanuparrProblemDetails();
services.AddExceptionHandler<GlobalExceptionHandler>();
return services;
}
/// <summary>
/// Registers RFC 9457 problem-details responses for both the exception handler and
/// [ApiController] model-state validation, attaching a uniform Activity-tied traceId.
/// </summary>
public static IServiceCollection AddCleanuparrProblemDetails(this IServiceCollection services)
{
services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = ctx =>
ctx.ProblemDetails.Extensions.TryAdd(
"traceId", Activity.Current?.Id ?? ctx.HttpContext.TraceIdentifier);
});
return services;
}
public static WebApplication ConfigureApi(this WebApplication app)
{
ILogger<Program> logger = app.Services.GetRequiredService<ILogger<Program>>();
// Map unhandled exceptions to RFC 9457 problem-details responses (GlobalExceptionHandler).
// Registered first so it also covers exceptions thrown by downstream middleware.
app.UseExceptionHandler();
// Enable compression
app.UseResponseCompression();
// Serve static files without caching
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx => NoCacheAttribute.Apply(ctx.Context.Response.Headers)
});
// Add the global exception handling middleware first
app.UseMiddleware<ExceptionMiddleware>();
// Resolve the real client IP / scheme / host from X-Forwarded-* headers
app.UseMiddleware<TrustedForwardedHeadersMiddleware>();
// Block non-auth requests until setup is complete
app.UseMiddleware<SetupGuardMiddleware>();
app.UseCors("Any");
if (app.Environment.IsDevelopment())
{
app.UseCors("DevSpa");
}
app.UseRouting();
app.UseAuthentication();
@@ -1,13 +1,11 @@
using System.Text.Json.Serialization;
using Cleanuparr.Domain.Entities.Arr;
using Cleanuparr.Infrastructure.Features.DownloadHunter.Consumers;
using Cleanuparr.Infrastructure.Features.DownloadRemover.Consumers;
using Cleanuparr.Infrastructure.Features.Notifications.Consumers;
using Cleanuparr.Infrastructure.Features.Notifications.Models;
using Cleanuparr.Infrastructure.Health;
using Cleanuparr.Infrastructure.Http;
using Cleanuparr.Infrastructure.Http.DynamicHttpClientSystem;
using Data.Models.Arr;
using MassTransit;
using Microsoft.Extensions.Caching.Memory;
@@ -30,9 +28,6 @@ public static class MainDI
config.AddConsumer<DownloadRemoverConsumer<SearchItem>>();
config.AddConsumer<DownloadRemoverConsumer<SeriesSearchItem>>();
config.AddConsumer<DownloadHunterConsumer<SearchItem>>();
config.AddConsumer<DownloadHunterConsumer<SeriesSearchItem>>();
config.AddConsumer<NotificationConsumer<FailedImportStrikeNotification>>();
config.AddConsumer<NotificationConsumer<StalledStrikeNotification>>();
config.AddConsumer<NotificationConsumer<SlowSpeedStrikeNotification>>();
@@ -60,14 +55,6 @@ public static class MainDI
e.PrefetchCount = 1;
});
cfg.ReceiveEndpoint("download-hunter-queue", e =>
{
e.ConfigureConsumer<DownloadHunterConsumer<SearchItem>>(context);
e.ConfigureConsumer<DownloadHunterConsumer<SeriesSearchItem>>(context);
e.ConcurrentMessageLimit = 1;
e.PrefetchCount = 1;
});
cfg.ReceiveEndpoint("notification-queue", e =>
{
e.ConfigureConsumer<NotificationConsumer<FailedImportStrikeNotification>>(context);
@@ -94,6 +81,9 @@ public static class MainDI
// Add HTTP client for Plex authentication
services.AddHttpClient("PlexAuth");
// Add HTTP client for OIDC authentication
services.AddHttpClient("OidcAuth");
return services;
}
@@ -4,9 +4,8 @@ using Cleanuparr.Infrastructure.Features.Arr;
using Cleanuparr.Infrastructure.Features.Arr.Interfaces;
using Cleanuparr.Infrastructure.Features.Auth;
using Cleanuparr.Infrastructure.Features.BlacklistSync;
using Cleanuparr.Infrastructure.Features.DownloadCleaner.Services;
using Cleanuparr.Infrastructure.Features.DownloadClient;
using Cleanuparr.Infrastructure.Features.DownloadHunter;
using Cleanuparr.Infrastructure.Features.DownloadHunter.Interfaces;
using Cleanuparr.Infrastructure.Features.DownloadRemover;
using Cleanuparr.Infrastructure.Features.DownloadRemover.Interfaces;
using Cleanuparr.Infrastructure.Features.Files;
@@ -33,6 +32,7 @@ public static class ServicesDI
.AddSingleton<IPasswordService, PasswordService>()
.AddSingleton<ITotpService, TotpService>()
.AddScoped<IPlexAuthService, PlexAuthService>()
.AddScoped<IOidcAuthService, OidcAuthService>()
.AddScoped<IEventPublisher, EventPublisher>()
.AddHostedService<EventCleanupService>()
.AddScoped<IDryRunInterceptor, DryRunInterceptor>()
@@ -48,8 +48,13 @@ public static class ServicesDI
.AddScoped<BlacklistSynchronizer>()
.AddScoped<MalwareBlocker>()
.AddScoped<DownloadCleaner>()
.AddScoped<ISeedingRulesCleanupService, SeedingRulesCleanupService>()
.AddScoped<IUnlinkedDownloadsService, UnlinkedDownloadsService>()
.AddScoped<IDeadTorrentService, DeadTorrentService>()
.AddScoped<IOrphanedFilesCleanupService, OrphanedFilesCleanupService>()
.AddScoped<Seeker>()
.AddScoped<CustomFormatScoreSyncer>()
.AddScoped<IQueueItemRemover, QueueItemRemover>()
.AddScoped<IDownloadHunter, DownloadHunter>()
.AddScoped<IFilenameEvaluator, FilenameEvaluator>()
.AddScoped<IHardLinkFileService, HardLinkFileService>()
.AddScoped<IUnixHardLinkFileService, UnixHardLinkFileService>()
@@ -58,13 +63,15 @@ public static class ServicesDI
.AddScoped<IDownloadServiceFactory, DownloadServiceFactory>()
.AddScoped<IStriker, Striker>()
.AddScoped<FileReader>()
.AddScoped<IRuleManager, RuleManager>()
.AddScoped<IRuleEvaluator, RuleEvaluator>()
.AddScoped<IQueueRuleManager, QueueRuleManager>()
.AddScoped<IQueueRuleEvaluator, QueueRuleEvaluator>()
.AddScoped<ISeedingRuleEvaluator, SeedingRuleEvaluator>()
.AddScoped<IRuleIntervalValidator, RuleIntervalValidator>()
.AddScoped<IStatsService, StatsService>()
.AddSingleton<IJobManagementService, JobManagementService>()
.AddSingleton<IBlocklistProvider, BlocklistProvider>()
.AddSingleton(TimeProvider.System)
.AddSingleton<AppStatusSnapshot>()
.AddHostedService<AppStatusRefreshService>();
.AddHostedService<AppStatusRefreshService>()
.AddHostedService<SeekerCommandMonitor>();
}
@@ -0,0 +1,38 @@
using Microsoft.AspNetCore.Mvc;
namespace Cleanuparr.Api.Extensions;
public static class ControllerBaseExtensions
{
/// <summary>
/// Builds an RFC 9457 problem-details error response for a direct (non-throwing) controller return.
/// Mirrors the shape produced by <see cref="Middleware.GlobalExceptionHandler"/> so every error
/// response carries the same <c>application/problem+json</c> body and <c>traceId</c>. The
/// <c>traceId</c> extension is added by the shared <c>CustomizeProblemDetails</c> hook inside
/// <see cref="ProblemDetailsFactory.CreateProblemDetails"/>.
/// </summary>
public static ObjectResult ProblemResult(
this ControllerBase controller,
int statusCode,
string detail,
string? title = null,
IReadOnlyDictionary<string, object?>? extensions = null)
{
ProblemDetails problemDetails = controller.ProblemDetailsFactory
.CreateProblemDetails(controller.HttpContext, statusCode: statusCode, title: title, detail: detail);
if (extensions is not null)
{
foreach (KeyValuePair<string, object?> extension in extensions)
{
problemDetails.Extensions[extension.Key] = extension.Value;
}
}
return new ObjectResult(problemDetails)
{
StatusCode = statusCode,
ContentTypes = { "application/problem+json" },
};
}
}
@@ -0,0 +1,29 @@
namespace Cleanuparr.Api.Extensions;
public static class HttpRequestExtensions
{
/// <summary>
/// Returns the request PathBase as a safe relative path.
/// Rejects absolute URLs (e.g. "://" or "//") to prevent open redirect attacks.
/// </summary>
public static string GetSafeBasePath(this HttpRequest request)
{
var basePath = request.PathBase.Value?.TrimEnd('/') ?? "";
if (basePath.Contains("://") || basePath.StartsWith("//"))
{
return "";
}
return basePath;
}
/// <summary>
/// Returns the external base URL (scheme + host + basePath).
/// TrustedForwardedHeadersMiddleware has already applied X-Forwarded-Proto and X-Forwarded-Host to <see cref="HttpRequest.Scheme"/> / <see cref="HttpRequest.Host"/>.
/// </summary>
public static string GetExternalBaseUrl(this HttpContext context)
{
var request = context.Request;
var basePath = request.GetSafeBasePath();
return $"{request.Scheme}://{request.Host}{basePath}";
}
}
@@ -1,3 +1,4 @@
using Cleanuparr.Api.Extensions;
using Cleanuparr.Api.Features.Arr.Contracts.Requests;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Infrastructure.Features.Arr.Dtos;
@@ -182,11 +183,6 @@ public sealed class ArrConfigController : ControllerBase
return Ok(new { Message = $"{type} configuration updated successfully" });
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to save {Type} configuration", type);
throw;
}
finally
{
DataContext.Lock.Release();
@@ -207,11 +203,6 @@ public sealed class ArrConfigController : ControllerBase
return CreatedAtAction(GetConfigActionName(type), new { id = instance.Id }, instance.Adapt<ArrInstanceDto>());
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create {Type} instance", type);
throw;
}
finally
{
DataContext.Lock.Release();
@@ -230,7 +221,7 @@ public sealed class ArrConfigController : ControllerBase
var instance = config.Instances.FirstOrDefault(i => i.Id == id);
if (instance is null)
{
return NotFound($"{type} instance with ID {id} not found");
return this.ProblemResult(StatusCodes.Status404NotFound, $"{type} instance with ID {id} not found");
}
request.ApplyTo(instance);
@@ -239,11 +230,6 @@ public sealed class ArrConfigController : ControllerBase
return Ok(instance.Adapt<ArrInstanceDto>());
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update {Type} instance with ID {Id}", type, id);
throw;
}
finally
{
DataContext.Lock.Release();
@@ -262,7 +248,7 @@ public sealed class ArrConfigController : ControllerBase
var instance = config.Instances.FirstOrDefault(i => i.Id == id);
if (instance is null)
{
return NotFound($"{type} instance with ID {id} not found");
return this.ProblemResult(StatusCodes.Status404NotFound, $"{type} instance with ID {id} not found");
}
config.Instances.Remove(instance);
@@ -270,11 +256,6 @@ public sealed class ArrConfigController : ControllerBase
return NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to delete {Type} instance with ID {Id}", type, id);
throw;
}
finally
{
DataContext.Lock.Release();
@@ -295,7 +276,7 @@ public sealed class ArrConfigController : ControllerBase
if (existingInstance is null)
{
return NotFound($"Instance with ID {request.InstanceId.Value} not found");
return this.ProblemResult(StatusCodes.Status404NotFound, $"Instance with ID {request.InstanceId.Value} not found");
}
resolvedApiKey = existingInstance.ApiKey;
@@ -310,7 +291,7 @@ public sealed class ArrConfigController : ControllerBase
catch (Exception ex)
{
_logger.LogError(ex, "Failed to test {Type} instance connection", type);
return BadRequest(new { Message = $"Connection failed: {ex.Message}" });
return this.ProblemResult(StatusCodes.Status400BadRequest, $"Connection failed: {ex.Message}");
}
}
@@ -0,0 +1,9 @@
using System.ComponentModel.DataAnnotations;
namespace Cleanuparr.Api.Features.Auth.Contracts.Requests;
public sealed record OidcExchangeRequest
{
[Required]
public required string Code { get; init; }
}
@@ -0,0 +1,17 @@
using System.ComponentModel.DataAnnotations;
namespace Cleanuparr.Api.Features.Auth.Contracts.Requests;
/// <summary>
/// Request to record that the current user has seen the given features, used to drive the "NEW" feature badges in the UI.
/// </summary>
public sealed record RecordFeatureViewsRequest
{
/// <summary>
/// The feature identifiers the user has been exposed to.
/// Unknown ids are recorded with the current timestamp; already-seen ids are ignored.
/// </summary>
[Required]
[MaxLength(100)]
public required IReadOnlyList<string> FeatureIds { get; init; }
}
@@ -0,0 +1,49 @@
using Cleanuparr.Infrastructure.Features.Auth;
using Cleanuparr.Persistence.Models.Auth;
using Cleanuparr.Shared.Helpers;
namespace Cleanuparr.Api.Features.Auth.Contracts.Requests;
public sealed record UpdateOidcConfigRequest
{
public bool Enabled { get; init; }
public string IssuerUrl { get; init; } = string.Empty;
public string ClientId { get; init; } = string.Empty;
public string ClientSecret { get; init; } = string.Empty;
public string Scopes { get; init; } = "openid profile email";
public string ProviderName { get; init; } = "OIDC";
public string RedirectUrl { get; init; } = string.Empty;
public bool ExclusiveMode { get; init; }
public void ApplyTo(OidcConfig existingConfig)
{
var previousIssuerUrl = existingConfig.IssuerUrl;
existingConfig.Enabled = Enabled;
existingConfig.IssuerUrl = IssuerUrl;
existingConfig.ClientId = ClientId;
existingConfig.Scopes = Scopes;
existingConfig.ProviderName = ProviderName;
existingConfig.RedirectUrl = RedirectUrl;
existingConfig.ExclusiveMode = ExclusiveMode;
if (!ClientSecret.IsPlaceholder())
{
existingConfig.ClientSecret = ClientSecret;
}
// AuthorizedSubject is intentionally NOT mapped here — it is set only via the OIDC link callback
if (previousIssuerUrl != IssuerUrl)
{
OidcAuthService.ClearDiscoveryCache();
}
}
}
@@ -5,4 +5,7 @@ public sealed record AuthStatusResponse
public required bool SetupCompleted { get; init; }
public bool PlexLinked { get; init; }
public bool AuthBypassActive { get; init; }
public bool OidcEnabled { get; init; }
public string OidcProviderName { get; init; } = string.Empty;
public bool OidcExclusiveMode { get; init; }
}
@@ -0,0 +1,15 @@
namespace Cleanuparr.Api.Features.Auth.Contracts.Responses;
public sealed record FeatureViewsResponse
{
/// <summary>
/// The user's account creation timestamp, used as the anchor for "new feature" detection:
/// a feature is only considered new if it was first seen meaningfully after this point.
/// </summary>
public required DateTimeOffset CreatedAt { get; init; }
/// <summary>
/// Map of feature id to the UTC timestamp the user first saw it.
/// </summary>
public required Dictionary<string, DateTimeOffset> Views { get; init; }
}
@@ -0,0 +1,6 @@
namespace Cleanuparr.Api.Features.Auth.Contracts.Responses;
public sealed record OidcStartResponse
{
public required string AuthorizationUrl { get; init; }
}
@@ -1,8 +1,10 @@
using System.Security.Claims;
using System.Security.Cryptography;
using Cleanuparr.Api.Extensions;
using Cleanuparr.Api.Features.Auth.Contracts.Requests;
using Cleanuparr.Api.Features.Auth.Contracts.Responses;
using Cleanuparr.Api.Filters;
using Cleanuparr.Domain.Exceptions;
using Cleanuparr.Infrastructure.Features.Auth;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Auth;
@@ -22,6 +24,7 @@ public sealed class AccountController : ControllerBase
private readonly IPasswordService _passwordService;
private readonly ITotpService _totpService;
private readonly IPlexAuthService _plexAuthService;
private readonly IOidcAuthService _oidcAuthService;
private readonly ILogger<AccountController> _logger;
public AccountController(
@@ -29,12 +32,14 @@ public sealed class AccountController : ControllerBase
IPasswordService passwordService,
ITotpService totpService,
IPlexAuthService plexAuthService,
IOidcAuthService oidcAuthService,
ILogger<AccountController> logger)
{
_usersContext = usersContext;
_passwordService = passwordService;
_totpService = totpService;
_plexAuthService = plexAuthService;
_oidcAuthService = oidcAuthService;
_logger = logger;
}
@@ -42,7 +47,10 @@ public sealed class AccountController : ControllerBase
public async Task<IActionResult> GetAccountInfo()
{
var user = await GetCurrentUser();
if (user is null) return Unauthorized();
if (user is null)
{
return Unauthorized();
}
return Ok(new AccountInfoResponse
{
@@ -57,247 +65,230 @@ public sealed class AccountController : ControllerBase
[HttpPut("password")]
public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequest request)
{
await UsersContext.Lock.WaitAsync();
try
if (await IsOidcExclusiveModeActive())
{
var user = await GetCurrentUser();
if (user is null) return Unauthorized();
if (!_passwordService.VerifyPassword(request.CurrentPassword, user.PasswordHash))
{
return BadRequest(new { error = "Current password is incorrect" });
}
DateTime now = DateTime.UtcNow;
user.PasswordHash = _passwordService.HashPassword(request.NewPassword);
user.UpdatedAt = now;
// Revoke all existing refresh tokens so old sessions can't be reused
var activeTokens = await _usersContext.RefreshTokens
.Where(r => r.UserId == user.Id && r.RevokedAt == null)
.ToListAsync();
foreach (var token in activeTokens)
{
token.RevokedAt = now;
}
await _usersContext.SaveChangesAsync();
_logger.LogInformation("Password changed for user {Username}", user.Username);
return Ok(new { message = "Password changed" });
return this.ProblemResult(StatusCodes.Status403Forbidden, "Password changes are disabled while OIDC exclusive mode is active.");
}
finally
var user = await GetCurrentUser();
if (user is null)
{
UsersContext.Lock.Release();
return Unauthorized();
}
if (!_passwordService.VerifyPassword(request.CurrentPassword, user.PasswordHash))
{
return this.ProblemResult(StatusCodes.Status400BadRequest, "Current password is incorrect");
}
DateTimeOffset now = DateTimeOffset.UtcNow;
user.PasswordHash = _passwordService.HashPassword(request.NewPassword);
user.UpdatedAt = now;
// Revoke all existing refresh tokens so old sessions can't be reused
var activeTokens = await _usersContext.RefreshTokens
.Where(r => r.UserId == user.Id && r.RevokedAt == null)
.ToListAsync();
foreach (var token in activeTokens)
{
token.RevokedAt = now;
}
await _usersContext.SaveChangesAsync();
_logger.LogInformation("Password changed for user {Username}", user.Username);
return Ok(new { message = "Password changed" });
}
[HttpPost("2fa/regenerate")]
public async Task<IActionResult> Regenerate2fa([FromBody] Regenerate2faRequest request)
{
await UsersContext.Lock.WaitAsync();
try
var user = await GetCurrentUser(includeRecoveryCodes: true);
if (user is null)
{
var user = await GetCurrentUser(includeRecoveryCodes: true);
if (user is null) return Unauthorized();
return Unauthorized();
}
// Verify current credentials
if (!_passwordService.VerifyPassword(request.Password, user.PasswordHash))
// Verify current credentials
if (!_passwordService.VerifyPassword(request.Password, user.PasswordHash))
{
return this.ProblemResult(StatusCodes.Status400BadRequest, "Incorrect password");
}
if (!_totpService.ValidateCode(user.TotpSecret, request.TotpCode))
{
return this.ProblemResult(StatusCodes.Status400BadRequest, "Invalid 2FA code");
}
// Generate new TOTP
var secret = _totpService.GenerateSecret();
var qrUri = _totpService.GetQrCodeUri(secret, user.Username);
var recoveryCodes = _totpService.GenerateRecoveryCodes();
user.TotpSecret = secret;
user.UpdatedAt = DateTimeOffset.UtcNow;
// Replace recovery codes
_usersContext.RecoveryCodes.RemoveRange(user.RecoveryCodes);
foreach (var code in recoveryCodes)
{
_usersContext.RecoveryCodes.Add(new RecoveryCode
{
return BadRequest(new { error = "Incorrect password" });
}
if (!_totpService.ValidateCode(user.TotpSecret, request.TotpCode))
{
return BadRequest(new { error = "Invalid 2FA code" });
}
// Generate new TOTP
var secret = _totpService.GenerateSecret();
var qrUri = _totpService.GetQrCodeUri(secret, user.Username);
var recoveryCodes = _totpService.GenerateRecoveryCodes();
user.TotpSecret = secret;
user.UpdatedAt = DateTime.UtcNow;
// Replace recovery codes
_usersContext.RecoveryCodes.RemoveRange(user.RecoveryCodes);
foreach (var code in recoveryCodes)
{
_usersContext.RecoveryCodes.Add(new RecoveryCode
{
Id = Guid.NewGuid(),
UserId = user.Id,
CodeHash = _totpService.HashRecoveryCode(code),
IsUsed = false
});
}
await _usersContext.SaveChangesAsync();
_logger.LogInformation("2FA regenerated for user {Username}", user.Username);
return Ok(new TotpSetupResponse
{
Secret = secret,
QrCodeUri = qrUri,
RecoveryCodes = recoveryCodes
Id = Guid.NewGuid(),
UserId = user.Id,
CodeHash = _totpService.HashRecoveryCode(code),
IsUsed = false
});
}
finally
await _usersContext.SaveChangesAsync();
_logger.LogInformation("2FA regenerated for user {Username}", user.Username);
return Ok(new TotpSetupResponse
{
UsersContext.Lock.Release();
}
Secret = secret,
QrCodeUri = qrUri,
RecoveryCodes = recoveryCodes
});
}
[HttpPost("2fa/enable")]
public async Task<IActionResult> Enable2fa([FromBody] Enable2faRequest request)
{
await UsersContext.Lock.WaitAsync();
try
var user = await GetCurrentUser(includeRecoveryCodes: true);
if (user is null)
{
var user = await GetCurrentUser(includeRecoveryCodes: true);
if (user is null) return Unauthorized();
return Unauthorized();
}
if (user.TotpEnabled)
if (user.TotpEnabled)
{
return this.ProblemResult(StatusCodes.Status409Conflict, "2FA is already enabled");
}
if (!_passwordService.VerifyPassword(request.Password, user.PasswordHash))
{
return this.ProblemResult(StatusCodes.Status400BadRequest, "Incorrect password");
}
// Generate new TOTP
var secret = _totpService.GenerateSecret();
var qrUri = _totpService.GetQrCodeUri(secret, user.Username);
var recoveryCodes = _totpService.GenerateRecoveryCodes();
user.TotpSecret = secret;
user.UpdatedAt = DateTimeOffset.UtcNow;
// Replace any existing recovery codes
_usersContext.RecoveryCodes.RemoveRange(user.RecoveryCodes);
foreach (var code in recoveryCodes)
{
_usersContext.RecoveryCodes.Add(new RecoveryCode
{
return Conflict(new { error = "2FA is already enabled" });
}
if (!_passwordService.VerifyPassword(request.Password, user.PasswordHash))
{
return BadRequest(new { error = "Incorrect password" });
}
// Generate new TOTP
var secret = _totpService.GenerateSecret();
var qrUri = _totpService.GetQrCodeUri(secret, user.Username);
var recoveryCodes = _totpService.GenerateRecoveryCodes();
user.TotpSecret = secret;
user.UpdatedAt = DateTime.UtcNow;
// Replace any existing recovery codes
_usersContext.RecoveryCodes.RemoveRange(user.RecoveryCodes);
foreach (var code in recoveryCodes)
{
_usersContext.RecoveryCodes.Add(new RecoveryCode
{
Id = Guid.NewGuid(),
UserId = user.Id,
CodeHash = _totpService.HashRecoveryCode(code),
IsUsed = false
});
}
await _usersContext.SaveChangesAsync();
_logger.LogInformation("2FA setup generated for user {Username}", user.Username);
return Ok(new TotpSetupResponse
{
Secret = secret,
QrCodeUri = qrUri,
RecoveryCodes = recoveryCodes
Id = Guid.NewGuid(),
UserId = user.Id,
CodeHash = _totpService.HashRecoveryCode(code),
IsUsed = false
});
}
finally
await _usersContext.SaveChangesAsync();
_logger.LogInformation("2FA setup generated for user {Username}", user.Username);
return Ok(new TotpSetupResponse
{
UsersContext.Lock.Release();
}
Secret = secret,
QrCodeUri = qrUri,
RecoveryCodes = recoveryCodes
});
}
[HttpPost("2fa/enable/verify")]
public async Task<IActionResult> VerifyEnable2fa([FromBody] VerifyTotpRequest request)
{
await UsersContext.Lock.WaitAsync();
try
var user = await GetCurrentUser();
if (user is null)
{
var user = await GetCurrentUser();
if (user is null) return Unauthorized();
if (user.TotpEnabled)
{
return Conflict(new { error = "2FA is already enabled" });
}
if (string.IsNullOrEmpty(user.TotpSecret))
{
return BadRequest(new { error = "Generate 2FA setup first" });
}
if (!_totpService.ValidateCode(user.TotpSecret, request.Code))
{
return BadRequest(new { error = "Invalid verification code" });
}
user.TotpEnabled = true;
user.UpdatedAt = DateTime.UtcNow;
await _usersContext.SaveChangesAsync();
_logger.LogInformation("2FA enabled for user {Username}", user.Username);
return Ok(new { message = "2FA enabled" });
return Unauthorized();
}
finally
if (user.TotpEnabled)
{
UsersContext.Lock.Release();
return this.ProblemResult(StatusCodes.Status409Conflict, "2FA is already enabled");
}
if (string.IsNullOrEmpty(user.TotpSecret))
{
return this.ProblemResult(StatusCodes.Status400BadRequest, "Generate 2FA setup first");
}
if (!_totpService.ValidateCode(user.TotpSecret, request.Code))
{
return this.ProblemResult(StatusCodes.Status400BadRequest, "Invalid verification code");
}
user.TotpEnabled = true;
user.UpdatedAt = DateTimeOffset.UtcNow;
await _usersContext.SaveChangesAsync();
_logger.LogInformation("2FA enabled for user {Username}", user.Username);
return Ok(new { message = "2FA enabled" });
}
[HttpPost("2fa/disable")]
public async Task<IActionResult> Disable2fa([FromBody] Disable2faRequest request)
{
await UsersContext.Lock.WaitAsync();
try
var user = await GetCurrentUser(includeRecoveryCodes: true);
if (user is null)
{
var user = await GetCurrentUser(includeRecoveryCodes: true);
if (user is null) return Unauthorized();
if (!user.TotpEnabled)
{
return BadRequest(new { error = "2FA is not enabled" });
}
if (!_passwordService.VerifyPassword(request.Password, user.PasswordHash))
{
return BadRequest(new { error = "Incorrect password" });
}
if (!_totpService.ValidateCode(user.TotpSecret, request.TotpCode))
{
return BadRequest(new { error = "Invalid 2FA code" });
}
user.TotpEnabled = false;
user.TotpSecret = string.Empty;
user.UpdatedAt = DateTime.UtcNow;
// Remove all recovery codes
_usersContext.RecoveryCodes.RemoveRange(user.RecoveryCodes);
await _usersContext.SaveChangesAsync();
_logger.LogInformation("2FA disabled for user {Username}", user.Username);
return Ok(new { message = "2FA disabled" });
return Unauthorized();
}
finally
if (!user.TotpEnabled)
{
UsersContext.Lock.Release();
return this.ProblemResult(StatusCodes.Status400BadRequest, "2FA is not enabled");
}
if (!_passwordService.VerifyPassword(request.Password, user.PasswordHash))
{
return this.ProblemResult(StatusCodes.Status400BadRequest, "Incorrect password");
}
if (!_totpService.ValidateCode(user.TotpSecret, request.TotpCode))
{
return this.ProblemResult(StatusCodes.Status400BadRequest, "Invalid 2FA code");
}
user.TotpEnabled = false;
user.TotpSecret = string.Empty;
user.UpdatedAt = DateTimeOffset.UtcNow;
// Remove all recovery codes
_usersContext.RecoveryCodes.RemoveRange(user.RecoveryCodes);
await _usersContext.SaveChangesAsync();
_logger.LogInformation("2FA disabled for user {Username}", user.Username);
return Ok(new { message = "2FA disabled" });
}
[HttpGet("api-key")]
public async Task<IActionResult> GetApiKey()
{
var user = await GetCurrentUser();
if (user is null) return Unauthorized();
if (user is null)
{
return Unauthorized();
}
return Ok(new { apiKey = user.ApiKey });
}
@@ -305,33 +296,33 @@ public sealed class AccountController : ControllerBase
[HttpPost("api-key/regenerate")]
public async Task<IActionResult> RegenerateApiKey()
{
await UsersContext.Lock.WaitAsync();
try
var user = await GetCurrentUser();
if (user is null)
{
var user = await GetCurrentUser();
if (user is null) return Unauthorized();
var bytes = new byte[32];
using var rng = RandomNumberGenerator.Create();
rng.GetBytes(bytes);
user.ApiKey = Convert.ToHexString(bytes).ToLowerInvariant();
user.UpdatedAt = DateTime.UtcNow;
await _usersContext.SaveChangesAsync();
_logger.LogInformation("API key regenerated for user {Username}", user.Username);
return Ok(new { apiKey = user.ApiKey });
}
finally
{
UsersContext.Lock.Release();
return Unauthorized();
}
var bytes = new byte[32];
using var rng = RandomNumberGenerator.Create();
rng.GetBytes(bytes);
user.ApiKey = Convert.ToHexString(bytes).ToLowerInvariant();
user.UpdatedAt = DateTimeOffset.UtcNow;
await _usersContext.SaveChangesAsync();
_logger.LogInformation("API key regenerated for user {Username}", user.Username);
return Ok(new { apiKey = user.ApiKey });
}
[HttpPost("plex/link")]
public async Task<IActionResult> StartPlexLink()
{
if (await IsOidcExclusiveModeActive())
{
return this.ProblemResult(StatusCodes.Status403Forbidden, "Plex account management is disabled while OIDC exclusive mode is active.");
}
var pin = await _plexAuthService.RequestPin();
return Ok(new { pinId = pin.PinId, authUrl = pin.AuthUrl });
@@ -340,6 +331,11 @@ public sealed class AccountController : ControllerBase
[HttpPost("plex/link/verify")]
public async Task<IActionResult> VerifyPlexLink([FromBody] PlexPinRequest request)
{
if (await IsOidcExclusiveModeActive())
{
return this.ProblemResult(StatusCodes.Status403Forbidden, "Plex account management is disabled while OIDC exclusive mode is active.");
}
var pinResult = await _plexAuthService.CheckPin(request.PinId);
if (!pinResult.Completed || pinResult.AuthToken is null)
@@ -349,23 +345,186 @@ public sealed class AccountController : ControllerBase
var plexAccount = await _plexAuthService.GetAccount(pinResult.AuthToken);
var user = await GetCurrentUser();
if (user is null)
{
return Unauthorized();
}
user.PlexAccountId = plexAccount.AccountId;
user.PlexUsername = plexAccount.Username;
user.PlexEmail = plexAccount.Email;
user.PlexAuthToken = pinResult.AuthToken;
user.UpdatedAt = DateTimeOffset.UtcNow;
await _usersContext.SaveChangesAsync();
_logger.LogInformation("Plex account linked for user {Username}: {PlexUsername}",
user.Username, plexAccount.Username);
return Ok(new { completed = true, plexUsername = plexAccount.Username });
}
[HttpDelete("plex/link")]
public async Task<IActionResult> UnlinkPlex()
{
if (await IsOidcExclusiveModeActive())
{
return this.ProblemResult(StatusCodes.Status403Forbidden, "Plex account management is disabled while OIDC exclusive mode is active.");
}
var user = await GetCurrentUser();
if (user is null)
{
return Unauthorized();
}
user.PlexAccountId = null;
user.PlexUsername = null;
user.PlexEmail = null;
user.PlexAuthToken = null;
user.UpdatedAt = DateTimeOffset.UtcNow;
await _usersContext.SaveChangesAsync();
_logger.LogInformation("Plex account unlinked for user {Username}", user.Username);
return Ok(new { message = "Plex account unlinked" });
}
[HttpGet("oidc")]
public async Task<IActionResult> GetOidcConfig()
{
var user = await GetCurrentUser();
if (user is null)
{
return Unauthorized();
}
return Ok(user.Oidc);
}
[HttpPut("oidc")]
public async Task<IActionResult> UpdateOidcConfig([FromBody] UpdateOidcConfigRequest request)
{
var user = await GetCurrentUser();
if (user is null)
{
return Unauthorized();
}
request.ApplyTo(user.Oidc);
user.Oidc.Validate();
user.UpdatedAt = DateTimeOffset.UtcNow;
await _usersContext.SaveChangesAsync();
return Ok(new { message = "OIDC configuration updated" });
}
[HttpPost("oidc/link")]
public async Task<IActionResult> StartOidcLink()
{
var user = await GetCurrentUser();
if (user is null)
{
return Unauthorized();
}
if (user.Oidc is not { Enabled: true })
{
return this.ProblemResult(StatusCodes.Status400BadRequest, "OIDC is not enabled");
}
var redirectUri = GetOidcLinkCallbackUrl(user.Oidc.RedirectUrl);
_logger.LogDebug("OIDC link start: using redirect URI {RedirectUri}", redirectUri);
try
{
var result = await _oidcAuthService.StartAuthorization(redirectUri, user.Id.ToString());
return Ok(new OidcStartResponse { AuthorizationUrl = result.AuthorizationUrl });
}
catch (InvalidOperationException ex)
{
throw new RateLimitException(ex.Message, ex);
}
}
/// <remarks>
/// This endpoint must be [AllowAnonymous] because the IdP redirects the user's browser here
/// without a Bearer token. Security is ensured by validating that the OIDC flow was initiated
/// by an authenticated user (InitiatorUserId stored in the flow state during StartOidcLink).
/// </remarks>
[AllowAnonymous]
[HttpGet("oidc/link/callback")]
public async Task<IActionResult> OidcLinkCallback(
[FromQuery] string? code,
[FromQuery] string? state,
[FromQuery] string? error)
{
var basePath = HttpContext.Request.GetSafeBasePath();
if (!string.IsNullOrEmpty(error) || string.IsNullOrEmpty(code) || string.IsNullOrEmpty(state))
{
return Redirect($"{basePath}/settings/account?oidc_link_error=failed");
}
// Fetch any user to get the configured redirect URL for the OIDC callback
var oidcConfig = (await _usersContext.Users.AsNoTracking().FirstOrDefaultAsync())?.Oidc;
var redirectUri = GetOidcLinkCallbackUrl(oidcConfig?.RedirectUrl);
_logger.LogDebug("OIDC link callback: using redirect URI {RedirectUri}", redirectUri);
var result = await _oidcAuthService.HandleCallback(code, state, redirectUri);
if (!result.Success || string.IsNullOrEmpty(result.Subject))
{
_logger.LogWarning("OIDC link callback failed: {Error}", result.Error);
return Redirect($"{basePath}/settings/account?oidc_link_error=failed");
}
// Verify the flow was initiated by an authenticated user
if (string.IsNullOrEmpty(result.InitiatorUserId) ||
!Guid.TryParse(result.InitiatorUserId, out var initiatorId))
{
_logger.LogWarning("OIDC link callback missing initiator user ID");
return Redirect($"{basePath}/settings/account?oidc_link_error=failed");
}
// Save the authorized subject to the user's OIDC config
var user = await _usersContext.Users.FirstOrDefaultAsync(u => u.Id == initiatorId);
if (user is null)
{
_logger.LogWarning("OIDC link callback initiator user not found: {UserId}", result.InitiatorUserId);
return Redirect($"{basePath}/settings/account?oidc_link_error=failed");
}
user.Oidc.AuthorizedSubject = result.Subject;
user.UpdatedAt = DateTimeOffset.UtcNow;
await _usersContext.SaveChangesAsync();
_logger.LogInformation("OIDC account linked with subject: {Subject} by user: {Username}",
result.Subject, user.Username);
return Redirect($"{basePath}/settings/account?oidc_link=success");
}
[HttpDelete("oidc/link")]
public async Task<IActionResult> UnlinkOidc()
{
await UsersContext.Lock.WaitAsync();
try
{
var user = await GetCurrentUser();
if (user is null) return Unauthorized();
if (user is null)
{
return Unauthorized();
}
user.PlexAccountId = plexAccount.AccountId;
user.PlexUsername = plexAccount.Username;
user.PlexEmail = plexAccount.Email;
user.PlexAuthToken = pinResult.AuthToken;
user.UpdatedAt = DateTime.UtcNow;
user.Oidc.AuthorizedSubject = string.Empty;
user.Oidc.ExclusiveMode = false;
user.UpdatedAt = DateTimeOffset.UtcNow;
await _usersContext.SaveChangesAsync();
_logger.LogInformation("Plex account linked for user {Username}: {PlexUsername}",
user.Username, plexAccount.Username);
_logger.LogInformation("OIDC account unlinked for user {Username}", user.Username);
return Ok(new { completed = true, plexUsername = plexAccount.Username });
return Ok(new { message = "OIDC account unlinked" });
}
finally
{
@@ -373,25 +532,72 @@ public sealed class AccountController : ControllerBase
}
}
[HttpDelete("plex/link")]
public async Task<IActionResult> UnlinkPlex()
private const int MaxFeatureIdsPerRequest = 100;
private const int MaxFeatureIdLength = 64;
/// <summary>
/// Records that the current user has seen the given features, used to drive the "NEW" feature badges in the UI.
/// Recording is idempotent: unknown ids are stamped with the current time, already-seen ids keep their original timestamp.
/// </summary>
/// <param name="request">The feature ids the user has been exposed to.</param>
/// <returns>
/// The user's account creation timestamp and the full map of feature id to first-seen timestamp.
/// </returns>
[HttpPost("feature-views")]
public async Task<IActionResult> RecordFeatureViews([FromBody] RecordFeatureViewsRequest request)
{
if (request.FeatureIds.Count > MaxFeatureIdsPerRequest)
{
return this.ProblemResult(StatusCodes.Status400BadRequest, $"featureIds exceeds the maximum allowed ({MaxFeatureIdsPerRequest}).");
}
await UsersContext.Lock.WaitAsync();
try
{
var user = await GetCurrentUser();
if (user is null) return Unauthorized();
if (user is null)
{
return Unauthorized();
}
var existing = await _usersContext.UserFeatureViews
.Where(v => v.UserId == user.Id)
.ToListAsync();
var existingIds = existing
.Select(v => v.FeatureId)
.ToHashSet();
DateTimeOffset now = DateTimeOffset.UtcNow;
foreach (var featureId in request.FeatureIds.Distinct())
{
if (string.IsNullOrWhiteSpace(featureId) ||
featureId.Length > MaxFeatureIdLength ||
existingIds.Contains(featureId))
{
continue;
}
var view = new UserFeatureView
{
Id = Guid.NewGuid(),
UserId = user.Id,
FeatureId = featureId,
FirstSeenAt = now
};
_usersContext.UserFeatureViews.Add(view);
existing.Add(view);
}
user.PlexAccountId = null;
user.PlexUsername = null;
user.PlexEmail = null;
user.PlexAuthToken = null;
user.UpdatedAt = DateTime.UtcNow;
await _usersContext.SaveChangesAsync();
_logger.LogInformation("Plex account unlinked for user {Username}", user.Username);
return Ok(new { message = "Plex account unlinked" });
return Ok(new FeatureViewsResponse
{
CreatedAt = user.CreatedAt,
Views = existing.ToDictionary(v => v.FeatureId, v => v.FirstSeenAt)
});
}
finally
{
@@ -399,6 +605,26 @@ public sealed class AccountController : ControllerBase
}
}
private string GetOidcLinkCallbackUrl(string? redirectUrl = null)
{
var baseUrl = string.IsNullOrEmpty(redirectUrl)
? HttpContext.GetExternalBaseUrl()
: redirectUrl.TrimEnd('/');
return $"{baseUrl}/api/account/oidc/link/callback";
}
private async Task<bool> IsOidcExclusiveModeActive()
{
var user = await _usersContext.Users.AsNoTracking().FirstOrDefaultAsync();
if (user is not { SetupCompleted: true })
{
return false;
}
var oidc = user.Oidc;
return oidc is { Enabled: true, ExclusiveMode: true };
}
private async Task<User?> GetCurrentUser(bool includeRecoveryCodes = false)
{
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
@@ -1,8 +1,10 @@
using System.Security.Cryptography;
using Cleanuparr.Api.Auth;
using Cleanuparr.Api.Extensions;
using Cleanuparr.Api.Features.Auth.Contracts.Requests;
using Cleanuparr.Api.Features.Auth.Contracts.Responses;
using Cleanuparr.Api.Filters;
using Cleanuparr.Domain.Exceptions;
using Cleanuparr.Infrastructure.Features.Auth;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Auth;
@@ -19,25 +21,31 @@ namespace Cleanuparr.Api.Features.Auth.Controllers;
public sealed class AuthController : ControllerBase
{
private readonly UsersContext _usersContext;
private readonly DataContext _dataContext;
private readonly IJwtService _jwtService;
private readonly IPasswordService _passwordService;
private readonly ITotpService _totpService;
private readonly IPlexAuthService _plexAuthService;
private readonly IOidcAuthService _oidcAuthService;
private readonly ILogger<AuthController> _logger;
public AuthController(
UsersContext usersContext,
DataContext dataContext,
IJwtService jwtService,
IPasswordService passwordService,
ITotpService totpService,
IPlexAuthService plexAuthService,
IOidcAuthService oidcAuthService,
ILogger<AuthController> logger)
{
_usersContext = usersContext;
_dataContext = dataContext;
_jwtService = jwtService;
_passwordService = passwordService;
_totpService = totpService;
_plexAuthService = plexAuthService;
_oidcAuthService = oidcAuthService;
_logger = logger;
}
@@ -47,12 +55,10 @@ public sealed class AuthController : ControllerBase
var user = await _usersContext.Users.AsNoTracking().FirstOrDefaultAsync();
var authBypass = false;
await using var dataContext = DataContext.CreateStaticInstance();
var generalConfig = await dataContext.GeneralConfigs.AsNoTracking().FirstOrDefaultAsync();
var generalConfig = await _dataContext.GeneralConfigs.AsNoTracking().FirstOrDefaultAsync();
if (generalConfig is { Auth.DisableAuthForLocalAddresses: true })
{
var clientIp = TrustedNetworkAuthenticationHandler.ResolveClientIp(
HttpContext, generalConfig.Auth.TrustForwardedHeaders);
var clientIp = TrustedNetworkAuthenticationHandler.ResolveClientIp(HttpContext);
if (clientIp is not null)
{
authBypass = TrustedNetworkAuthenticationHandler.IsTrustedAddress(
@@ -60,11 +66,21 @@ public sealed class AuthController : ControllerBase
}
}
var oidcConfig = user?.Oidc;
var oidcEnabled = oidcConfig is { Enabled: true } &&
!string.IsNullOrEmpty(oidcConfig.IssuerUrl) &&
!string.IsNullOrEmpty(oidcConfig.ClientId);
var oidcExclusiveMode = oidcEnabled && oidcConfig!.ExclusiveMode;
return Ok(new AuthStatusResponse
{
SetupCompleted = user is { SetupCompleted: true },
PlexLinked = user?.PlexAccountId is not null,
AuthBypassActive = authBypass
AuthBypassActive = authBypass,
OidcEnabled = oidcEnabled,
OidcProviderName = oidcEnabled ? oidcConfig!.ProviderName : string.Empty,
OidcExclusiveMode = oidcExclusiveMode
});
}
@@ -77,7 +93,7 @@ public sealed class AuthController : ControllerBase
var existingUser = await _usersContext.Users.FirstOrDefaultAsync();
if (existingUser is not null)
{
return Conflict(new { error = "Account already exists" });
return this.ProblemResult(StatusCodes.Status409Conflict, "Account already exists");
}
var user = new User
@@ -89,8 +105,8 @@ public sealed class AuthController : ControllerBase
TotpEnabled = false,
ApiKey = GenerateApiKey(),
SetupCompleted = false,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
CreatedAt = DateTimeOffset.UtcNow,
UpdatedAt = DateTimeOffset.UtcNow
};
_usersContext.Users.Add(user);
@@ -118,12 +134,12 @@ public sealed class AuthController : ControllerBase
if (user is null)
{
return BadRequest(new { error = "Create an account first" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "Create an account first");
}
if (user.SetupCompleted)
{
return Conflict(new { error = "Setup already completed. Use account settings to manage 2FA." });
return this.ProblemResult(StatusCodes.Status409Conflict, "Setup already completed. Use account settings to manage 2FA.");
}
// Generate new TOTP secret
@@ -135,7 +151,7 @@ public sealed class AuthController : ControllerBase
// Store secret (will be finalized on verify)
user.TotpSecret = secret;
user.UpdatedAt = DateTime.UtcNow;
user.UpdatedAt = DateTimeOffset.UtcNow;
// Remove old recovery codes and add new ones
_usersContext.RecoveryCodes.RemoveRange(user.RecoveryCodes);
@@ -175,26 +191,26 @@ public sealed class AuthController : ControllerBase
var user = await _usersContext.Users.FirstOrDefaultAsync();
if (user is null)
{
return BadRequest(new { error = "Create an account first" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "Create an account first");
}
if (user.SetupCompleted)
{
return Conflict(new { error = "Setup already completed. Use account settings to manage 2FA." });
return this.ProblemResult(StatusCodes.Status409Conflict, "Setup already completed. Use account settings to manage 2FA.");
}
if (string.IsNullOrEmpty(user.TotpSecret))
{
return BadRequest(new { error = "Generate 2FA setup first" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "Generate 2FA setup first");
}
if (!_totpService.ValidateCode(user.TotpSecret, request.Code))
{
return Unauthorized(new { error = "Invalid verification code" });
return this.ProblemResult(StatusCodes.Status401Unauthorized, "Invalid verification code");
}
user.TotpEnabled = true;
user.UpdatedAt = DateTime.UtcNow;
user.UpdatedAt = DateTimeOffset.UtcNow;
await _usersContext.SaveChangesAsync();
_logger.LogInformation("2FA enabled for user {Username}", user.Username);
@@ -216,16 +232,16 @@ public sealed class AuthController : ControllerBase
var user = await _usersContext.Users.FirstOrDefaultAsync();
if (user is null)
{
return BadRequest(new { error = "Create an account first" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "Create an account first");
}
if (user.SetupCompleted)
{
return Conflict(new { error = "Setup already completed" });
return this.ProblemResult(StatusCodes.Status409Conflict, "Setup already completed");
}
user.SetupCompleted = true;
user.UpdatedAt = DateTime.UtcNow;
user.UpdatedAt = DateTimeOffset.UtcNow;
await _usersContext.SaveChangesAsync();
_logger.LogInformation("Setup completed for user {Username}", user.Username);
@@ -241,25 +257,35 @@ public sealed class AuthController : ControllerBase
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequest request)
{
if (await IsOidcExclusiveModeActive())
{
return this.ProblemResult(StatusCodes.Status403Forbidden, "Login with credentials is disabled. Use OIDC to sign in.");
}
var user = await _usersContext.Users.AsNoTracking().FirstOrDefaultAsync();
// Always verify the submitted password to prevent timing-based username enumeration
var userHasPassword = user?.PasswordHash is not null;
var passwordHash = user?.PasswordHash ?? _passwordService.DummyHash;
var passwordValid = _passwordService.VerifyPassword(request.Password, passwordHash) && userHasPassword;
if (user is null || !user.SetupCompleted)
{
return Unauthorized(new { error = "Invalid credentials" });
return this.ProblemResult(StatusCodes.Status401Unauthorized, "Invalid credentials");
}
// Check lockout
if (user.LockoutEnd.HasValue && user.LockoutEnd.Value > DateTime.UtcNow)
if (user.LockoutEnd.HasValue && user.LockoutEnd.Value > DateTimeOffset.UtcNow)
{
var remaining = (int)(user.LockoutEnd.Value - DateTime.UtcNow).TotalSeconds;
return StatusCode(429, new { error = "Account is locked", retryAfterSeconds = remaining });
int remaining = (int)Math.Ceiling((user.LockoutEnd.Value - DateTimeOffset.UtcNow).TotalSeconds);
throw new RateLimitException("Account is locked", remaining);
}
if (!_passwordService.VerifyPassword(request.Password, user.PasswordHash) ||
!string.Equals(user.Username, request.Username, StringComparison.OrdinalIgnoreCase))
if (!passwordValid || !string.Equals(user.Username, request.Username, StringComparison.OrdinalIgnoreCase))
{
var retryAfterSeconds = await IncrementFailedAttempts(user.Id);
return Unauthorized(new { error = "Invalid credentials", retryAfterSeconds });
int retryAfterSeconds = await IncrementFailedAttempts(user.Id);
return this.ProblemResult(StatusCodes.Status401Unauthorized, "Invalid credentials",
extensions: new Dictionary<string, object?> { ["retryAfterSeconds"] = retryAfterSeconds });
}
// Reset failed attempts on successful password verification
@@ -294,10 +320,15 @@ public sealed class AuthController : ControllerBase
[HttpPost("login/2fa")]
public async Task<IActionResult> VerifyTwoFactor([FromBody] TwoFactorRequest request)
{
if (await IsOidcExclusiveModeActive())
{
return this.ProblemResult(StatusCodes.Status403Forbidden, "Login with credentials is disabled. Use OIDC to sign in.");
}
var userId = _jwtService.ValidateLoginToken(request.LoginToken);
if (userId is null)
{
return Unauthorized(new { error = "Invalid or expired login token" });
return this.ProblemResult(StatusCodes.Status401Unauthorized, "Invalid or expired login token");
}
var user = await _usersContext.Users
@@ -306,7 +337,7 @@ public sealed class AuthController : ControllerBase
if (user is null)
{
return Unauthorized(new { error = "Invalid login token" });
return this.ProblemResult(StatusCodes.Status401Unauthorized, "Invalid login token");
}
bool codeValid;
@@ -322,7 +353,7 @@ public sealed class AuthController : ControllerBase
if (!codeValid)
{
return Unauthorized(new { error = "Invalid verification code" });
return this.ProblemResult(StatusCodes.Status401Unauthorized, "Invalid verification code");
}
return Ok(await GenerateTokenResponse(user));
@@ -340,13 +371,13 @@ public sealed class AuthController : ControllerBase
.Include(r => r.User)
.FirstOrDefaultAsync(r => r.TokenHash == tokenHash && r.RevokedAt == null);
if (storedToken is null || storedToken.ExpiresAt < DateTime.UtcNow)
if (storedToken is null || storedToken.ExpiresAt < DateTimeOffset.UtcNow)
{
return Unauthorized(new { error = "Invalid or expired refresh token" });
return this.ProblemResult(StatusCodes.Status401Unauthorized, "Invalid or expired refresh token");
}
// Revoke the old token (rotation)
storedToken.RevokedAt = DateTime.UtcNow;
storedToken.RevokedAt = DateTimeOffset.UtcNow;
// Generate new tokens
var response = await GenerateTokenResponse(storedToken.User);
@@ -373,7 +404,7 @@ public sealed class AuthController : ControllerBase
if (storedToken is not null)
{
storedToken.RevokedAt = DateTime.UtcNow;
storedToken.RevokedAt = DateTimeOffset.UtcNow;
await _usersContext.SaveChangesAsync();
}
@@ -391,12 +422,12 @@ public sealed class AuthController : ControllerBase
var user = await _usersContext.Users.AsNoTracking().FirstOrDefaultAsync();
if (user is null)
{
return BadRequest(new { error = "Create an account first" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "Create an account first");
}
if (user.SetupCompleted)
{
return Conflict(new { error = "Setup already completed. Use account settings to manage Plex." });
return this.ProblemResult(StatusCodes.Status409Conflict, "Setup already completed. Use account settings to manage Plex.");
}
var pin = await _plexAuthService.RequestPin();
@@ -426,19 +457,19 @@ public sealed class AuthController : ControllerBase
var user = await _usersContext.Users.FirstOrDefaultAsync();
if (user is null)
{
return BadRequest(new { error = "Create an account first" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "Create an account first");
}
if (user.SetupCompleted)
{
return Conflict(new { error = "Setup already completed. Use account settings to manage Plex." });
return this.ProblemResult(StatusCodes.Status409Conflict, "Setup already completed. Use account settings to manage Plex.");
}
user.PlexAccountId = plexAccount.AccountId;
user.PlexUsername = plexAccount.Username;
user.PlexEmail = plexAccount.Email;
user.PlexAuthToken = pinResult.AuthToken;
user.UpdatedAt = DateTime.UtcNow;
user.UpdatedAt = DateTimeOffset.UtcNow;
await _usersContext.SaveChangesAsync();
_logger.LogInformation("Plex account linked during setup for user {Username}: {PlexUsername}",
@@ -455,10 +486,15 @@ public sealed class AuthController : ControllerBase
[HttpPost("login/plex/pin")]
public async Task<IActionResult> RequestPlexPin()
{
if (await IsOidcExclusiveModeActive())
{
return this.ProblemResult(StatusCodes.Status403Forbidden, "Plex login is disabled. Use OIDC to sign in.");
}
var user = await _usersContext.Users.AsNoTracking().FirstOrDefaultAsync();
if (user is null || !user.SetupCompleted || user.PlexAccountId is null)
{
return BadRequest(new { error = "Plex login is not available" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "Plex login is not available");
}
var pin = await _plexAuthService.RequestPin();
@@ -473,10 +509,15 @@ public sealed class AuthController : ControllerBase
[HttpPost("login/plex/verify")]
public async Task<IActionResult> VerifyPlexLogin([FromBody] PlexPinRequest request)
{
if (await IsOidcExclusiveModeActive())
{
return this.ProblemResult(StatusCodes.Status403Forbidden, "Plex login is disabled. Use OIDC to sign in.");
}
var user = await _usersContext.Users.FirstOrDefaultAsync();
if (user is null || !user.SetupCompleted || user.PlexAccountId is null)
{
return BadRequest(new { error = "Plex login is not available" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "Plex login is not available");
}
var pinResult = await _plexAuthService.CheckPin(request.PinId);
@@ -491,7 +532,7 @@ public sealed class AuthController : ControllerBase
if (plexAccount.AccountId != user.PlexAccountId)
{
return Unauthorized(new { error = "Plex account does not match the linked account" });
return this.ProblemResult(StatusCodes.Status401Unauthorized, "Plex account does not match the linked account");
}
// Plex OAuth acts as a trusted identity provider — the user explicitly linked their
@@ -509,6 +550,118 @@ public sealed class AuthController : ControllerBase
});
}
[HttpPost("oidc/start")]
public async Task<IActionResult> StartOidc()
{
var user = await _usersContext.Users.AsNoTracking().FirstOrDefaultAsync();
var oidcConfig = user?.Oidc;
if (oidcConfig is not { Enabled: true } ||
string.IsNullOrEmpty(oidcConfig.IssuerUrl) ||
string.IsNullOrEmpty(oidcConfig.ClientId))
{
return this.ProblemResult(StatusCodes.Status400BadRequest, "OIDC is not enabled or not configured");
}
var redirectUri = GetOidcCallbackUrl(oidcConfig.RedirectUrl);
_logger.LogDebug("OIDC login start: using redirect URI {RedirectUri}", redirectUri);
try
{
var result = await _oidcAuthService.StartAuthorization(redirectUri);
return Ok(new OidcStartResponse { AuthorizationUrl = result.AuthorizationUrl });
}
catch (InvalidOperationException ex)
{
throw new RateLimitException(ex.Message, ex);
}
}
[HttpGet("oidc/callback")]
public async Task<IActionResult> OidcCallback(
[FromQuery] string? code,
[FromQuery] string? state,
[FromQuery] string? error)
{
var basePath = HttpContext.Request.GetSafeBasePath();
// Handle IdP error responses
if (!string.IsNullOrEmpty(error))
{
_logger.LogWarning("OIDC callback received error: {Error}", error);
return Redirect($"{basePath}/auth/login?oidc_error=provider_error");
}
if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(state))
{
return Redirect($"{basePath}/auth/login?oidc_error=invalid_request");
}
// Load the user early so we can use the configured redirect URL
var user = await _usersContext.Users.FirstOrDefaultAsync(u => u.SetupCompleted);
if (user is null)
{
return Redirect($"{basePath}/auth/login?oidc_error=no_account");
}
var redirectUri = GetOidcCallbackUrl(user.Oidc.RedirectUrl);
_logger.LogDebug("OIDC login callback: using redirect URI {RedirectUri}", redirectUri);
var result = await _oidcAuthService.HandleCallback(code, state, redirectUri);
if (!result.Success)
{
_logger.LogWarning("OIDC callback failed: {Error}", result.Error);
return Redirect($"{basePath}/auth/login?oidc_error=authentication_failed");
}
if (!string.IsNullOrEmpty(user.Oidc.AuthorizedSubject) &&
result.Subject != user.Oidc.AuthorizedSubject)
{
_logger.LogWarning("OIDC subject mismatch. Expected: {Expected}, Got: {Got}",
user.Oidc.AuthorizedSubject, result.Subject);
return Redirect($"{basePath}/auth/login?oidc_error=unauthorized");
}
var tokenResponse = await GenerateTokenResponse(user);
// Store tokens with a one-time code (never put tokens in the URL)
var oneTimeCode = _oidcAuthService.StoreOneTimeCode(
tokenResponse.AccessToken,
tokenResponse.RefreshToken,
tokenResponse.ExpiresIn);
_logger.LogInformation("User {Username} authenticated via OIDC (subject: {Subject})",
user.Username, result.Subject);
return Redirect($"{basePath}/auth/oidc/callback?code={Uri.EscapeDataString(oneTimeCode)}");
}
[HttpPost("oidc/exchange")]
public IActionResult ExchangeOidcCode([FromBody] OidcExchangeRequest request)
{
var result = _oidcAuthService.ExchangeOneTimeCode(request.Code);
if (result is null)
{
return this.ProblemResult(StatusCodes.Status404NotFound, "Invalid or expired code");
}
return Ok(new TokenResponse
{
AccessToken = result.AccessToken,
RefreshToken = result.RefreshToken,
ExpiresIn = result.ExpiresIn
});
}
private string GetOidcCallbackUrl(string? redirectUrl = null)
{
var baseUrl = string.IsNullOrEmpty(redirectUrl)
? HttpContext.GetExternalBaseUrl()
: redirectUrl.TrimEnd('/');
return $"{baseUrl}/api/auth/oidc/callback";
}
private async Task<TokenResponse> GenerateTokenResponse(User user)
{
var accessToken = _jwtService.GenerateAccessToken(user);
@@ -519,8 +672,8 @@ public sealed class AuthController : ControllerBase
Id = Guid.NewGuid(),
UserId = user.Id,
TokenHash = HashRefreshToken(refreshToken),
ExpiresAt = DateTime.UtcNow.AddDays(7),
CreatedAt = DateTime.UtcNow
ExpiresAt = DateTimeOffset.UtcNow.AddDays(7),
CreatedAt = DateTimeOffset.UtcNow
});
await _usersContext.SaveChangesAsync();
@@ -543,7 +696,7 @@ public sealed class AuthController : ControllerBase
if (_totpService.VerifyRecoveryCode(code, recoveryCode.CodeHash))
{
recoveryCode.IsUsed = true;
recoveryCode.UsedAt = DateTime.UtcNow;
recoveryCode.UsedAt = DateTimeOffset.UtcNow;
await _usersContext.SaveChangesAsync();
_logger.LogWarning("Recovery code used for user {Username}", user.Username);
@@ -566,7 +719,7 @@ public sealed class AuthController : ControllerBase
{
var user = await _usersContext.Users.FirstAsync(u => u.Id == userId);
user.FailedLoginAttempts++;
user.LockoutEnd = DateTime.UtcNow.AddSeconds(user.FailedLoginAttempts * 2);
user.LockoutEnd = DateTimeOffset.UtcNow.AddSeconds(user.FailedLoginAttempts * 2);
await _usersContext.SaveChangesAsync();
_logger.LogWarning("Failed login attempt {Attempts} for user {Username}, locked for {Seconds}s",
@@ -610,4 +763,16 @@ public sealed class AuthController : ControllerBase
var hash = SHA256.HashData(bytes);
return Convert.ToBase64String(hash);
}
private async Task<bool> IsOidcExclusiveModeActive()
{
var user = await _usersContext.Users.AsNoTracking().FirstOrDefaultAsync();
if (user is not { SetupCompleted: true })
{
return false;
}
var oidc = user.Oidc;
return oidc is { Enabled: true, ExclusiveMode: true };
}
}
@@ -89,11 +89,6 @@ public sealed class BlacklistSyncConfigController : ControllerBase
return Ok(new { Message = "BlacklistSynchronizer configuration updated successfully" });
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to save BlacklistSync configuration");
throw;
}
finally
{
DataContext.Lock.Release();
@@ -0,0 +1,14 @@
namespace Cleanuparr.Api.Features.DownloadCleaner.Contracts.Requests;
public sealed record DeadTorrentConfigRequest
{
public bool Enabled { get; init; }
public string TargetCategory { get; init; } = "cleanuparr-dead";
public bool UseTag { get; init; }
public ushort MaxStrikes { get; init; }
public List<string> Categories { get; init; } = [];
}
@@ -0,0 +1,21 @@
using System.ComponentModel.DataAnnotations;
namespace Cleanuparr.Api.Features.DownloadCleaner.Contracts.Requests;
public sealed record OrphanedFilesConfigRequest
{
public bool Enabled { get; init; }
public List<string> ScanDirectories { get; init; } = [];
[Required]
public string OrphanedDirectory { get; init; } = string.Empty;
public List<string> ExcludePatterns { get; init; } = [];
[Range(0, int.MaxValue)]
public int MinFileAgeHours { get; init; } = 24;
[Range(1, int.MaxValue)]
public int? PurgeAfterHours { get; init; }
}
@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace Cleanuparr.Api.Features.DownloadCleaner.Contracts.Requests;
public record ReorderSeedingRulesRequest
{
/// <summary>
/// IDs of seeding rules in the desired priority order (first = highest priority).
/// </summary>
[Required]
public List<Guid> OrderedIds { get; init; } = [];
}
@@ -1,4 +1,4 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations;
using Cleanuparr.Domain.Enums;
namespace Cleanuparr.Api.Features.DownloadCleaner.Contracts.Requests;
@@ -8,6 +8,36 @@ public record SeedingRuleRequest
[Required]
public string Name { get; init; } = string.Empty;
/// <summary>
/// Categories this rule applies to. At least one must be specified.
/// </summary>
[Required]
[MinLength(1, ErrorMessage = "At least one category must be specified.")]
public List<string> Categories { get; init; } = [];
/// <summary>
/// Tracker domain suffixes to match (e.g. "tracker.example.com"). Empty = any tracker.
/// </summary>
public List<string> TrackerPatterns { get; init; } = [];
/// <summary>
/// Torrent must have at least one of these tags/labels. Accepted for all clients;
/// silently ignored for Deluge, rTorrent, and µTorrent.
/// </summary>
public List<string> TagsAny { get; init; } = [];
/// <summary>
/// Torrent must have ALL of these tags/labels. Accepted for all clients;
/// silently ignored for Deluge, rTorrent, and µTorrent.
/// </summary>
public List<string> TagsAll { get; init; } = [];
/// <summary>
/// Evaluation priority (lower = evaluated first). Auto-assigned if not provided.
/// </summary>
[Range(1, int.MaxValue, ErrorMessage = "Priority must be a positive integer.")]
public int? Priority { get; init; }
/// <summary>
/// Which torrent privacy types this rule applies to.
/// </summary>
@@ -28,8 +58,14 @@ public record SeedingRuleRequest
/// </summary>
public double MaxSeedTime { get; init; } = -1;
/// <summary>
/// Minimum number of seeders required before removing a download. Set to 0 to disable.
/// </summary>
[Range(0, int.MaxValue, ErrorMessage = "Min seeders must be 0 or greater.")]
public int MinSeeders { get; init; }
/// <summary>
/// Whether to delete the source files when cleaning the download.
/// </summary>
public bool DeleteSourceFiles { get; init; } = true;
}
}
@@ -0,0 +1,14 @@
namespace Cleanuparr.Api.Features.DownloadCleaner.Contracts.Requests;
public sealed record UnlinkedConfigRequest
{
public bool Enabled { get; init; }
public string TargetCategory { get; init; } = "cleanuparr-unlinked";
public bool UseTag { get; init; }
public List<string> IgnoredRootDirs { get; init; } = [];
public List<string> Categories { get; init; } = [];
}
@@ -11,20 +11,5 @@ public sealed record UpdateDownloadCleanerConfigRequest
/// </summary>
public bool UseAdvancedScheduling { get; init; }
public List<SeedingRuleRequest> Categories { get; init; } = [];
/// <summary>
/// Indicates whether unlinked download handling is enabled.
/// </summary>
public bool UnlinkedEnabled { get; init; }
public string UnlinkedTargetCategory { get; init; } = "cleanuparr-unlinked";
public bool UnlinkedUseTag { get; init; }
public List<string> UnlinkedIgnoredRootDirs { get; init; } = [];
public List<string> UnlinkedCategories { get; init; } = [];
public List<string> IgnoredDownloads { get; init; } = [];
}
@@ -0,0 +1,25 @@
using Cleanuparr.Persistence.Models.Configuration.DownloadCleaner;
namespace Cleanuparr.Api.Features.DownloadCleaner.Contracts.Responses;
public sealed record DeadTorrentConfigResponse
{
public bool Enabled { get; init; }
public required string TargetCategory { get; init; }
public bool UseTag { get; init; }
public ushort MaxStrikes { get; init; }
public required List<string> Categories { get; init; }
public static DeadTorrentConfigResponse From(DeadTorrentConfig config) => new()
{
Enabled = config.Enabled,
TargetCategory = config.TargetCategory,
UseTag = config.UseTag,
MaxStrikes = config.MaxStrikes,
Categories = config.Categories,
};
}
@@ -0,0 +1,22 @@
using Cleanuparr.Domain.Enums;
namespace Cleanuparr.Api.Features.DownloadCleaner.Contracts.Responses;
public sealed record DownloadCleanerClientResponse
{
public Guid DownloadClientId { get; init; }
public required string DownloadClientName { get; init; }
public bool DownloadClientEnabled { get; init; }
public DownloadClientTypeName DownloadClientTypeName { get; init; }
public required IReadOnlyList<SeedingRuleResponse> SeedingRules { get; init; }
public UnlinkedConfigResponse? UnlinkedConfig { get; init; }
public DeadTorrentConfigResponse? DeadTorrentConfig { get; init; }
public OrphanedFilesConfigResponse? OrphanedFilesConfig { get; init; }
}
@@ -0,0 +1,28 @@
using Cleanuparr.Persistence.Models.Configuration.DownloadCleaner;
namespace Cleanuparr.Api.Features.DownloadCleaner.Contracts.Responses;
public sealed record OrphanedFilesConfigResponse
{
public bool Enabled { get; init; }
public required List<string> ScanDirectories { get; init; }
public required string OrphanedDirectory { get; init; }
public required List<string> ExcludePatterns { get; init; }
public int MinFileAgeHours { get; init; }
public int? PurgeAfterHours { get; init; }
public static OrphanedFilesConfigResponse From(OrphanedFilesConfig config) => new()
{
Enabled = config.Enabled,
ScanDirectories = config.ScanDirectories,
OrphanedDirectory = config.OrphanedDirectory,
ExcludePatterns = config.ExcludePatterns,
MinFileAgeHours = config.MinFileAgeHours,
PurgeAfterHours = config.PurgeAfterHours,
};
}
@@ -0,0 +1,50 @@
using Cleanuparr.Domain.Enums;
using Cleanuparr.Persistence.Models.Configuration.DownloadCleaner;
namespace Cleanuparr.Api.Features.DownloadCleaner.Contracts.Responses;
public sealed record SeedingRuleResponse
{
public Guid Id { get; init; }
public required string Name { get; init; }
public required List<string> Categories { get; init; }
public required List<string> TrackerPatterns { get; init; }
public required List<string> TagsAny { get; init; }
public required List<string> TagsAll { get; init; }
public int Priority { get; init; }
public TorrentPrivacyType PrivacyType { get; init; }
public double MaxRatio { get; init; }
public double MinSeedTime { get; init; }
public double MaxSeedTime { get; init; }
public int? MinSeeders { get; init; }
public bool DeleteSourceFiles { get; init; }
public static SeedingRuleResponse From(ISeedingRule rule) => new()
{
Id = rule.Id,
Name = rule.Name,
Categories = rule.Categories,
TrackerPatterns = rule.TrackerPatterns,
TagsAny = (rule as ITagFilterable)?.TagsAny ?? [],
TagsAll = (rule as ITagFilterable)?.TagsAll ?? [],
Priority = rule.Priority,
PrivacyType = rule.PrivacyType,
MaxRatio = rule.MaxRatio,
MinSeedTime = rule.MinSeedTime,
MaxSeedTime = rule.MaxSeedTime,
MinSeeders = (rule as ISeedersFilterable)?.MinSeeders,
DeleteSourceFiles = rule.DeleteSourceFiles,
};
}
@@ -0,0 +1,25 @@
using Cleanuparr.Persistence.Models.Configuration.DownloadCleaner;
namespace Cleanuparr.Api.Features.DownloadCleaner.Contracts.Responses;
public sealed record UnlinkedConfigResponse
{
public bool Enabled { get; init; }
public required string TargetCategory { get; init; }
public bool UseTag { get; init; }
public required List<string> IgnoredRootDirs { get; init; }
public required List<string> Categories { get; init; }
public static UnlinkedConfigResponse From(UnlinkedConfig config) => new()
{
Enabled = config.Enabled,
TargetCategory = config.TargetCategory,
UseTag = config.UseTag,
IgnoredRootDirs = config.IgnoredRootDirs,
Categories = config.Categories,
};
}
@@ -0,0 +1,108 @@
using Cleanuparr.Api.Extensions;
using Cleanuparr.Api.Features.DownloadCleaner.Contracts.Requests;
using Cleanuparr.Api.Features.DownloadCleaner.Contracts.Responses;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Configuration.DownloadCleaner;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Cleanuparr.Api.Features.DownloadCleaner.Controllers;
[ApiController]
[Route("api/dead-torrent-config")]
[Authorize]
public class DeadTorrentConfigController : ControllerBase
{
private readonly ILogger<DeadTorrentConfigController> _logger;
private readonly DataContext _dataContext;
public DeadTorrentConfigController(
ILogger<DeadTorrentConfigController> logger,
DataContext dataContext)
{
_logger = logger;
_dataContext = dataContext;
}
[HttpGet("{downloadClientId}")]
public async Task<IActionResult> GetDeadTorrentConfig(Guid downloadClientId)
{
await DataContext.Lock.WaitAsync();
try
{
var client = await _dataContext.DownloadClients
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == downloadClientId);
if (client is null)
{
return this.ProblemResult(StatusCodes.Status404NotFound, $"Download client with ID {downloadClientId} not found");
}
var config = await _dataContext.DeadTorrentConfigs
.AsNoTracking()
.FirstOrDefaultAsync(d => d.DownloadClientConfigId == downloadClientId);
return Ok(config is null ? null : DeadTorrentConfigResponse.From(config));
}
finally
{
DataContext.Lock.Release();
}
}
[HttpPut("{downloadClientId}")]
public async Task<IActionResult> UpdateDeadTorrentConfig(Guid downloadClientId, [FromBody] DeadTorrentConfigRequest dto)
{
await DataContext.Lock.WaitAsync();
try
{
var client = await _dataContext.DownloadClients
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == downloadClientId);
if (client is null)
{
return this.ProblemResult(StatusCodes.Status404NotFound, $"Download client with ID {downloadClientId} not found");
}
if (dto.Enabled && client.TypeName is DownloadClientTypeName.rTorrent)
{
return this.ProblemResult(StatusCodes.Status400BadRequest, "Dead torrent handling is not supported for rTorrent (no seeder count available)");
}
var existing = await _dataContext.DeadTorrentConfigs
.FirstOrDefaultAsync(d => d.DownloadClientConfigId == downloadClientId);
if (existing is null)
{
existing = new DeadTorrentConfig
{
DownloadClientConfigId = downloadClientId,
};
_dataContext.DeadTorrentConfigs.Add(existing);
}
existing.Enabled = dto.Enabled;
existing.TargetCategory = dto.TargetCategory;
existing.UseTag = dto.UseTag;
existing.MaxStrikes = dto.MaxStrikes;
existing.Categories = dto.Categories;
existing.Validate();
await _dataContext.SaveChangesAsync();
_logger.LogInformation("Updated dead torrent config for client {ClientId}", downloadClientId);
return Ok(DeadTorrentConfigResponse.From(existing));
}
finally
{
DataContext.Lock.Release();
}
}
}
@@ -1,8 +1,7 @@
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using Cleanuparr.Api.Features.DownloadCleaner.Contracts.Requests;
using Cleanuparr.Api.Features.DownloadCleaner.Contracts.Responses;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Infrastructure.Services.Interfaces;
using Cleanuparr.Infrastructure.Utilities;
@@ -42,10 +41,63 @@ public sealed class DownloadCleanerConfigController : ControllerBase
try
{
var config = await _dataContext.DownloadCleanerConfigs
.Include(x => x.Categories)
.AsNoTracking()
.FirstAsync();
return Ok(config);
var downloadClients = await _dataContext.DownloadClients
.AsNoTracking()
.ToListAsync();
var allQBitRules = await _dataContext.QBitSeedingRules.AsNoTracking().ToListAsync();
var allDelugeRules = await _dataContext.DelugeSeedingRules.AsNoTracking().ToListAsync();
var allTransmissionRules = await _dataContext.TransmissionSeedingRules.AsNoTracking().ToListAsync();
var allUTorrentRules = await _dataContext.UTorrentSeedingRules.AsNoTracking().ToListAsync();
var allRTorrentRules = await _dataContext.RTorrentSeedingRules.AsNoTracking().ToListAsync();
List<UnlinkedConfig> allUnlinkedConfigs = await _dataContext.UnlinkedConfigs.AsNoTracking().ToListAsync();
List<DeadTorrentConfig> allDeadTorrentConfigs = await _dataContext.DeadTorrentConfigs.AsNoTracking().ToListAsync();
List<OrphanedFilesConfig> allOrphanedFilesConfigs = await _dataContext.OrphanedFilesConfigs.AsNoTracking().ToListAsync();
Dictionary<Guid, UnlinkedConfig> unlinkedConfigsByClientId = allUnlinkedConfigs
.GroupBy(u => u.DownloadClientConfigId)
.ToDictionary(g => g.Key, g => g.First());
Dictionary<Guid, DeadTorrentConfig> deadTorrentConfigsByClientId = allDeadTorrentConfigs
.GroupBy(d => d.DownloadClientConfigId)
.ToDictionary(g => g.Key, g => g.First());
Dictionary<Guid, OrphanedFilesConfig> orphanedFilesConfigsByClientId = allOrphanedFilesConfigs
.GroupBy(o => o.DownloadClientConfigId)
.ToDictionary(g => g.Key, g => g.First());
var clients = new List<DownloadCleanerClientResponse>();
foreach (var client in downloadClients)
{
List<ISeedingRule> seedingRules = SeedingRuleHelper
.FilterForClient(client, allQBitRules, allDelugeRules, allTransmissionRules, allUTorrentRules, allRTorrentRules);
unlinkedConfigsByClientId.TryGetValue(client.Id, out UnlinkedConfig? unlinkedConfig);
deadTorrentConfigsByClientId.TryGetValue(client.Id, out DeadTorrentConfig? deadTorrentConfig);
orphanedFilesConfigsByClientId.TryGetValue(client.Id, out OrphanedFilesConfig? orphanedFilesConfig);
clients.Add(new DownloadCleanerClientResponse
{
DownloadClientId = client.Id,
DownloadClientName = client.Name,
DownloadClientEnabled = client.Enabled,
DownloadClientTypeName = client.TypeName,
SeedingRules = seedingRules.Select(SeedingRuleResponse.From).ToList(),
UnlinkedConfig = unlinkedConfig is not null ? UnlinkedConfigResponse.From(unlinkedConfig) : null,
DeadTorrentConfig = deadTorrentConfig is not null ? DeadTorrentConfigResponse.From(deadTorrentConfig) : null,
OrphanedFilesConfig = orphanedFilesConfig is not null ? OrphanedFilesConfigResponse.From(orphanedFilesConfig) : null,
});
}
return Ok(new
{
config.Enabled,
config.CronExpression,
config.UseAdvancedScheduling,
config.IgnoredDownloads,
clients,
});
}
finally
{
@@ -70,40 +122,13 @@ public sealed class DownloadCleanerConfigController : ControllerBase
CronValidationHelper.ValidateCronExpression(newConfigDto.CronExpression);
}
// Get existing configuration
var oldConfig = await _dataContext.DownloadCleanerConfigs
.Include(x => x.Categories)
.FirstAsync();
// Update global config only
var oldConfig = await _dataContext.DownloadCleanerConfigs.FirstAsync();
oldConfig.Enabled = newConfigDto.Enabled;
oldConfig.CronExpression = newConfigDto.CronExpression;
oldConfig.UseAdvancedScheduling = newConfigDto.UseAdvancedScheduling;
oldConfig.UnlinkedEnabled = newConfigDto.UnlinkedEnabled;
oldConfig.UnlinkedTargetCategory = newConfigDto.UnlinkedTargetCategory;
oldConfig.UnlinkedUseTag = newConfigDto.UnlinkedUseTag;
oldConfig.UnlinkedIgnoredRootDirs = newConfigDto.UnlinkedIgnoredRootDirs;
oldConfig.UnlinkedCategories = newConfigDto.UnlinkedCategories;
oldConfig.IgnoredDownloads = newConfigDto.IgnoredDownloads;
oldConfig.Categories.Clear();
_dataContext.SeedingRules.RemoveRange(oldConfig.Categories);
_dataContext.DownloadCleanerConfigs.Update(oldConfig);
foreach (var categoryDto in newConfigDto.Categories)
{
_dataContext.SeedingRules.Add(new SeedingRule
{
Name = categoryDto.Name,
PrivacyType = categoryDto.PrivacyType,
MaxRatio = categoryDto.MaxRatio,
MinSeedTime = categoryDto.MinSeedTime,
MaxSeedTime = categoryDto.MaxSeedTime,
DeleteSourceFiles = categoryDto.DeleteSourceFiles,
DownloadCleanerConfigId = oldConfig.Id
});
}
oldConfig.Validate();
await _dataContext.SaveChangesAsync();
@@ -111,15 +136,6 @@ public sealed class DownloadCleanerConfigController : ControllerBase
return Ok(new { Message = "DownloadCleaner configuration updated successfully" });
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to save DownloadCleaner configuration");
throw;
}
finally
{
DataContext.Lock.Release();
@@ -0,0 +1,120 @@
using Cleanuparr.Api.Extensions;
using Cleanuparr.Api.Features.DownloadCleaner.Contracts.Requests;
using Cleanuparr.Api.Features.DownloadCleaner.Contracts.Responses;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Configuration.DownloadCleaner;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Cleanuparr.Api.Features.DownloadCleaner.Controllers;
[ApiController]
[Route("api/orphaned-files-config")]
[Authorize]
public sealed class OrphanedFilesConfigController : ControllerBase
{
private readonly ILogger<OrphanedFilesConfigController> _logger;
private readonly DataContext _dataContext;
public OrphanedFilesConfigController(
ILogger<OrphanedFilesConfigController> logger,
DataContext dataContext)
{
_logger = logger;
_dataContext = dataContext;
}
[HttpGet("{downloadClientId}")]
public async Task<IActionResult> GetClientConfig(Guid downloadClientId)
{
await DataContext.Lock.WaitAsync();
try
{
var client = await _dataContext.DownloadClients
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == downloadClientId);
if (client is null)
{
return this.ProblemResult(StatusCodes.Status404NotFound, $"Download client with ID {downloadClientId} not found");
}
var config = await _dataContext.OrphanedFilesConfigs
.AsNoTracking()
.FirstOrDefaultAsync(c => c.DownloadClientConfigId == downloadClientId);
return Ok(config is null ? null : OrphanedFilesConfigResponse.From(config));
}
finally
{
DataContext.Lock.Release();
}
}
[HttpPut("{downloadClientId}")]
public async Task<IActionResult> UpdateClientConfig(Guid downloadClientId, [FromBody] OrphanedFilesConfigRequest dto)
{
await DataContext.Lock.WaitAsync();
try
{
var client = await _dataContext.DownloadClients
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == downloadClientId);
if (client is null)
{
return this.ProblemResult(StatusCodes.Status404NotFound, $"Download client with ID {downloadClientId} not found");
}
var existing = await _dataContext.OrphanedFilesConfigs
.FirstOrDefaultAsync(c => c.DownloadClientConfigId == downloadClientId);
var candidate = (existing ?? new OrphanedFilesConfig { DownloadClientConfigId = downloadClientId }) with
{
Enabled = dto.Enabled,
ScanDirectories = dto.ScanDirectories,
OrphanedDirectory = dto.OrphanedDirectory,
ExcludePatterns = dto.ExcludePatterns,
MinFileAgeHours = dto.MinFileAgeHours,
PurgeAfterHours = dto.PurgeAfterHours,
};
var siblings = await _dataContext.OrphanedFilesConfigs
.AsNoTracking()
.Where(c => c.DownloadClientConfigId != downloadClientId)
.ToListAsync();
var otherDownloadClients = await _dataContext.DownloadClients
.AsNoTracking()
.Where(c => c.Id != downloadClientId)
.ToListAsync();
candidate.Validate(siblings, otherDownloadClients);
if (existing is null)
{
_dataContext.OrphanedFilesConfigs.Add(candidate);
}
else
{
existing.Enabled = candidate.Enabled;
existing.ScanDirectories = candidate.ScanDirectories;
existing.OrphanedDirectory = candidate.OrphanedDirectory;
existing.ExcludePatterns = candidate.ExcludePatterns;
existing.MinFileAgeHours = candidate.MinFileAgeHours;
existing.PurgeAfterHours = candidate.PurgeAfterHours;
}
await _dataContext.SaveChangesAsync();
_logger.LogInformation("Updated orphaned files client config for client {ClientId}", downloadClientId);
return Ok(OrphanedFilesConfigResponse.From(existing ?? candidate));
}
finally
{
DataContext.Lock.Release();
}
}
}
@@ -0,0 +1,355 @@
using Cleanuparr.Api.Extensions;
using Cleanuparr.Api.Features.DownloadCleaner.Contracts.Requests;
using Cleanuparr.Api.Features.DownloadCleaner.Contracts.Responses;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Configuration;
using Cleanuparr.Persistence.Models.Configuration.DownloadCleaner;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Cleanuparr.Api.Features.DownloadCleaner.Controllers;
[ApiController]
[Route("api/seeding-rules")]
[Authorize]
public class SeedingRulesController : ControllerBase
{
private readonly ILogger<SeedingRulesController> _logger;
private readonly DataContext _dataContext;
public SeedingRulesController(
ILogger<SeedingRulesController> logger,
DataContext dataContext)
{
_logger = logger;
_dataContext = dataContext;
}
[HttpGet("{downloadClientId}")]
public async Task<IActionResult> GetSeedingRules(Guid downloadClientId)
{
await DataContext.Lock.WaitAsync();
try
{
var client = await _dataContext.DownloadClients
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == downloadClientId);
if (client is null)
{
return this.ProblemResult(StatusCodes.Status404NotFound, $"Download client with ID {downloadClientId} not found");
}
var rules = await SeedingRuleHelper.GetForClientAsync(_dataContext, client);
return Ok(rules.Select(SeedingRuleResponse.From));
}
finally
{
DataContext.Lock.Release();
}
}
[HttpPost("{downloadClientId}")]
public async Task<IActionResult> CreateSeedingRule(Guid downloadClientId, [FromBody] SeedingRuleRequest ruleDto)
{
await DataContext.Lock.WaitAsync();
try
{
var client = await _dataContext.DownloadClients
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == downloadClientId);
if (client is null)
{
return this.ProblemResult(StatusCodes.Status404NotFound, $"Download client with ID {downloadClientId} not found");
}
var existingRules = await SeedingRuleHelper.GetForClientAsync(_dataContext, client);
if (ruleDto.Priority.HasValue && existingRules.Any(r => r.Priority == ruleDto.Priority.Value))
{
return this.ProblemResult(StatusCodes.Status400BadRequest, $"A seeding rule with priority {ruleDto.Priority.Value} already exists for this client");
}
int priority = ruleDto.Priority ?? (existingRules.Count == 0 ? 1 : existingRules.Max(r => r.Priority) + 1);
var rule = CreateRule(client.TypeName, client.Id, ruleDto, priority);
rule.Validate();
AddRuleToDbSet(rule);
await _dataContext.SaveChangesAsync();
_logger.LogInformation("Created seeding rule: {RuleName} with ID: {RuleId} for client {ClientId}",
rule.Name, rule.Id, downloadClientId);
return CreatedAtAction(nameof(GetSeedingRules), new { downloadClientId }, rule);
}
finally
{
DataContext.Lock.Release();
}
}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateSeedingRule(Guid id, [FromBody] SeedingRuleRequest ruleDto)
{
await DataContext.Lock.WaitAsync();
try
{
var (existingRule, _) = await SeedingRuleHelper.FindByIdAsync(_dataContext, id);
if (existingRule is null)
{
return this.ProblemResult(StatusCodes.Status404NotFound, $"Seeding rule with ID {id} not found");
}
existingRule.Name = ruleDto.Name.Trim();
existingRule.Categories = SanitizeStringList(ruleDto.Categories);
existingRule.TrackerPatterns = SanitizeStringList(ruleDto.TrackerPatterns);
existingRule.PrivacyType = ruleDto.PrivacyType;
existingRule.MaxRatio = ruleDto.MaxRatio;
existingRule.MinSeedTime = ruleDto.MinSeedTime;
existingRule.MaxSeedTime = ruleDto.MaxSeedTime;
existingRule.DeleteSourceFiles = ruleDto.DeleteSourceFiles;
// Priority is intentionally NOT updated here — use the reorder endpoint
if (existingRule is ITagFilterable tagFilterable)
{
tagFilterable.TagsAny = SanitizeStringList(ruleDto.TagsAny);
tagFilterable.TagsAll = SanitizeStringList(ruleDto.TagsAll);
}
if (existingRule is ISeedersFilterable seedersFilterable)
{
seedersFilterable.MinSeeders = ruleDto.MinSeeders;
}
existingRule.Validate();
await _dataContext.SaveChangesAsync();
_logger.LogInformation("Updated seeding rule: {RuleName} with ID: {RuleId}", existingRule.Name, id);
return Ok(existingRule);
}
finally
{
DataContext.Lock.Release();
}
}
[HttpPut("{downloadClientId}/reorder")]
public async Task<IActionResult> ReorderSeedingRules(Guid downloadClientId, [FromBody] ReorderSeedingRulesRequest request)
{
await DataContext.Lock.WaitAsync();
try
{
var client = await _dataContext.DownloadClients
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == downloadClientId);
if (client is null)
{
return this.ProblemResult(StatusCodes.Status404NotFound, $"Download client with ID {downloadClientId} not found");
}
List<ISeedingRule> rules = await SeedingRuleHelper.GetForClientTrackedAsync(_dataContext, client);
if (request.OrderedIds.Distinct().Count() != request.OrderedIds.Count)
{
return this.ProblemResult(StatusCodes.Status400BadRequest, "Duplicate rule IDs are not allowed");
}
if (request.OrderedIds.Count != rules.Count)
{
return this.ProblemResult(StatusCodes.Status400BadRequest, $"Expected {rules.Count} rule IDs but received {request.OrderedIds.Count}. All rules must be included.");
}
foreach (Guid id in request.OrderedIds.Where(id => rules.All(r => r.Id != id)))
{
return this.ProblemResult(StatusCodes.Status400BadRequest, $"Rule with ID {id} not found for client {downloadClientId}");
}
int priority = 1;
var lookup = rules.ToDictionary(r => r.Id);
foreach (var id in request.OrderedIds)
{
lookup[id].Priority = priority++;
}
await _dataContext.SaveChangesAsync();
_logger.LogInformation("Reordered {Count} seeding rules for client {ClientId}", rules.Count, downloadClientId);
return NoContent();
}
finally
{
DataContext.Lock.Release();
}
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteSeedingRule(Guid id)
{
await DataContext.Lock.WaitAsync();
try
{
var (existingRule, _) = await SeedingRuleHelper.FindByIdAsync(_dataContext, id);
if (existingRule is null)
{
return this.ProblemResult(StatusCodes.Status404NotFound, $"Seeding rule with ID {id} not found");
}
RemoveRuleFromDbSet(existingRule);
await _dataContext.SaveChangesAsync();
_logger.LogInformation("Deleted seeding rule: {RuleName} with ID: {RuleId}", existingRule.Name, id);
return NoContent();
}
finally
{
DataContext.Lock.Release();
}
}
private static List<string> SanitizeStringList(List<string> list)
=> list.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()).ToList();
private static ISeedingRule CreateRule(DownloadClientTypeName typeName, Guid clientId, SeedingRuleRequest dto, int priority)
{
var categories = SanitizeStringList(dto.Categories);
var trackerPatterns = SanitizeStringList(dto.TrackerPatterns);
var tagsAny = SanitizeStringList(dto.TagsAny);
var tagsAll = SanitizeStringList(dto.TagsAll);
return typeName switch
{
DownloadClientTypeName.qBittorrent => new QBitSeedingRule
{
DownloadClientConfigId = clientId,
Name = dto.Name.Trim(),
Categories = categories,
TrackerPatterns = trackerPatterns,
TagsAny = tagsAny,
TagsAll = tagsAll,
Priority = priority,
PrivacyType = dto.PrivacyType,
MaxRatio = dto.MaxRatio,
MinSeedTime = dto.MinSeedTime,
MaxSeedTime = dto.MaxSeedTime,
MinSeeders = dto.MinSeeders,
DeleteSourceFiles = dto.DeleteSourceFiles,
},
DownloadClientTypeName.Deluge => new DelugeSeedingRule
{
DownloadClientConfigId = clientId,
Name = dto.Name.Trim(),
Categories = categories,
TrackerPatterns = trackerPatterns,
Priority = priority,
PrivacyType = dto.PrivacyType,
MaxRatio = dto.MaxRatio,
MinSeedTime = dto.MinSeedTime,
MaxSeedTime = dto.MaxSeedTime,
MinSeeders = dto.MinSeeders,
DeleteSourceFiles = dto.DeleteSourceFiles,
},
DownloadClientTypeName.Transmission => new TransmissionSeedingRule
{
DownloadClientConfigId = clientId,
Name = dto.Name.Trim(),
Categories = categories,
TrackerPatterns = trackerPatterns,
TagsAny = tagsAny,
TagsAll = tagsAll,
Priority = priority,
PrivacyType = dto.PrivacyType,
MaxRatio = dto.MaxRatio,
MinSeedTime = dto.MinSeedTime,
MaxSeedTime = dto.MaxSeedTime,
MinSeeders = dto.MinSeeders,
DeleteSourceFiles = dto.DeleteSourceFiles,
},
DownloadClientTypeName.uTorrent => new UTorrentSeedingRule
{
DownloadClientConfigId = clientId,
Name = dto.Name.Trim(),
Categories = categories,
TrackerPatterns = trackerPatterns,
Priority = priority,
PrivacyType = dto.PrivacyType,
MaxRatio = dto.MaxRatio,
MinSeedTime = dto.MinSeedTime,
MaxSeedTime = dto.MaxSeedTime,
MinSeeders = dto.MinSeeders,
DeleteSourceFiles = dto.DeleteSourceFiles,
},
DownloadClientTypeName.rTorrent => new RTorrentSeedingRule
{
DownloadClientConfigId = clientId,
Name = dto.Name.Trim(),
Categories = categories,
TrackerPatterns = trackerPatterns,
Priority = priority,
PrivacyType = dto.PrivacyType,
MaxRatio = dto.MaxRatio,
MinSeedTime = dto.MinSeedTime,
MaxSeedTime = dto.MaxSeedTime,
DeleteSourceFiles = dto.DeleteSourceFiles,
},
_ => throw new ArgumentOutOfRangeException(nameof(typeName), typeName, "Unsupported download client type")
};
}
private void AddRuleToDbSet(ISeedingRule rule)
{
switch (rule)
{
case QBitSeedingRule qbit:
_dataContext.QBitSeedingRules.Add(qbit);
break;
case DelugeSeedingRule deluge:
_dataContext.DelugeSeedingRules.Add(deluge);
break;
case TransmissionSeedingRule transmission:
_dataContext.TransmissionSeedingRules.Add(transmission);
break;
case UTorrentSeedingRule utorrent:
_dataContext.UTorrentSeedingRules.Add(utorrent);
break;
case RTorrentSeedingRule rtorrent:
_dataContext.RTorrentSeedingRules.Add(rtorrent);
break;
}
}
private void RemoveRuleFromDbSet(ISeedingRule rule)
{
switch (rule)
{
case QBitSeedingRule qbit:
_dataContext.QBitSeedingRules.Remove(qbit);
break;
case DelugeSeedingRule deluge:
_dataContext.DelugeSeedingRules.Remove(deluge);
break;
case TransmissionSeedingRule transmission:
_dataContext.TransmissionSeedingRules.Remove(transmission);
break;
case UTorrentSeedingRule utorrent:
_dataContext.UTorrentSeedingRules.Remove(utorrent);
break;
case RTorrentSeedingRule rtorrent:
_dataContext.RTorrentSeedingRules.Remove(rtorrent);
break;
}
}
}
@@ -0,0 +1,102 @@
using Cleanuparr.Api.Extensions;
using Cleanuparr.Api.Features.DownloadCleaner.Contracts.Requests;
using Cleanuparr.Api.Features.DownloadCleaner.Contracts.Responses;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Configuration.DownloadCleaner;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Cleanuparr.Api.Features.DownloadCleaner.Controllers;
[ApiController]
[Route("api/unlinked-config")]
[Authorize]
public class UnlinkedConfigController : ControllerBase
{
private readonly ILogger<UnlinkedConfigController> _logger;
private readonly DataContext _dataContext;
public UnlinkedConfigController(
ILogger<UnlinkedConfigController> logger,
DataContext dataContext)
{
_logger = logger;
_dataContext = dataContext;
}
[HttpGet("{downloadClientId}")]
public async Task<IActionResult> GetUnlinkedConfig(Guid downloadClientId)
{
await DataContext.Lock.WaitAsync();
try
{
var client = await _dataContext.DownloadClients
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == downloadClientId);
if (client is null)
{
return this.ProblemResult(StatusCodes.Status404NotFound, $"Download client with ID {downloadClientId} not found");
}
var config = await _dataContext.UnlinkedConfigs
.AsNoTracking()
.FirstOrDefaultAsync(u => u.DownloadClientConfigId == downloadClientId);
return Ok(config is null ? null : UnlinkedConfigResponse.From(config));
}
finally
{
DataContext.Lock.Release();
}
}
[HttpPut("{downloadClientId}")]
public async Task<IActionResult> UpdateUnlinkedConfig(Guid downloadClientId, [FromBody] UnlinkedConfigRequest dto)
{
await DataContext.Lock.WaitAsync();
try
{
var client = await _dataContext.DownloadClients
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == downloadClientId);
if (client is null)
{
return this.ProblemResult(StatusCodes.Status404NotFound, $"Download client with ID {downloadClientId} not found");
}
var existing = await _dataContext.UnlinkedConfigs
.FirstOrDefaultAsync(u => u.DownloadClientConfigId == downloadClientId);
if (existing is null)
{
existing = new UnlinkedConfig
{
DownloadClientConfigId = downloadClientId,
};
_dataContext.UnlinkedConfigs.Add(existing);
}
existing.Enabled = dto.Enabled;
existing.TargetCategory = dto.TargetCategory;
existing.UseTag = dto.UseTag;
existing.IgnoredRootDirs = dto.IgnoredRootDirs;
existing.Categories = dto.Categories;
existing.Validate();
await _dataContext.SaveChangesAsync();
_logger.LogInformation("Updated unlinked config for client {ClientId}", downloadClientId);
return Ok(UnlinkedConfigResponse.From(existing));
}
finally
{
DataContext.Lock.Release();
}
}
}
@@ -0,0 +1,147 @@
using Cleanuparr.Domain.Enums;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Configuration;
using Cleanuparr.Persistence.Models.Configuration.DownloadCleaner;
using Microsoft.EntityFrameworkCore;
namespace Cleanuparr.Api.Features.DownloadCleaner;
internal static class SeedingRuleHelper
{
/// <summary>
/// Queries the appropriate per-type seeding rules table for a single client.
/// </summary>
public static async Task<List<ISeedingRule>> GetForClientAsync(DataContext ctx, DownloadClientConfig client)
{
return client.TypeName switch
{
DownloadClientTypeName.qBittorrent => (await ctx.QBitSeedingRules
.Where(r => r.DownloadClientConfigId == client.Id)
.OrderBy(r => r.Priority).ThenBy(r => r.Id)
.AsNoTracking().ToListAsync()).Cast<ISeedingRule>().ToList(),
DownloadClientTypeName.Deluge => (await ctx.DelugeSeedingRules
.Where(r => r.DownloadClientConfigId == client.Id)
.OrderBy(r => r.Priority).ThenBy(r => r.Id)
.AsNoTracking().ToListAsync()).Cast<ISeedingRule>().ToList(),
DownloadClientTypeName.Transmission => (await ctx.TransmissionSeedingRules
.Where(r => r.DownloadClientConfigId == client.Id)
.OrderBy(r => r.Priority).ThenBy(r => r.Id)
.AsNoTracking().ToListAsync()).Cast<ISeedingRule>().ToList(),
DownloadClientTypeName.uTorrent => (await ctx.UTorrentSeedingRules
.Where(r => r.DownloadClientConfigId == client.Id)
.OrderBy(r => r.Priority).ThenBy(r => r.Id)
.AsNoTracking().ToListAsync()).Cast<ISeedingRule>().ToList(),
DownloadClientTypeName.rTorrent => (await ctx.RTorrentSeedingRules
.Where(r => r.DownloadClientConfigId == client.Id)
.OrderBy(r => r.Priority).ThenBy(r => r.Id)
.AsNoTracking().ToListAsync()).Cast<ISeedingRule>().ToList(),
_ => [],
};
}
/// <summary>
/// Queries the appropriate per-type seeding rules table for a single client with change tracking enabled.
/// Use this when you need to modify and save the returned entities.
/// </summary>
public static async Task<List<ISeedingRule>> GetForClientTrackedAsync(DataContext ctx, DownloadClientConfig client)
{
return client.TypeName switch
{
DownloadClientTypeName.qBittorrent => (await ctx.QBitSeedingRules
.Where(r => r.DownloadClientConfigId == client.Id)
.OrderBy(r => r.Priority).ThenBy(r => r.Id)
.ToListAsync()).Cast<ISeedingRule>().ToList(),
DownloadClientTypeName.Deluge => (await ctx.DelugeSeedingRules
.Where(r => r.DownloadClientConfigId == client.Id)
.OrderBy(r => r.Priority).ThenBy(r => r.Id)
.ToListAsync()).Cast<ISeedingRule>().ToList(),
DownloadClientTypeName.Transmission => (await ctx.TransmissionSeedingRules
.Where(r => r.DownloadClientConfigId == client.Id)
.OrderBy(r => r.Priority).ThenBy(r => r.Id)
.ToListAsync()).Cast<ISeedingRule>().ToList(),
DownloadClientTypeName.uTorrent => (await ctx.UTorrentSeedingRules
.Where(r => r.DownloadClientConfigId == client.Id)
.OrderBy(r => r.Priority).ThenBy(r => r.Id)
.ToListAsync()).Cast<ISeedingRule>().ToList(),
DownloadClientTypeName.rTorrent => (await ctx.RTorrentSeedingRules
.Where(r => r.DownloadClientConfigId == client.Id)
.OrderBy(r => r.Priority).ThenBy(r => r.Id)
.ToListAsync()).Cast<ISeedingRule>().ToList(),
_ => [],
};
}
/// <summary>
/// Loads the client by ID then queries its seeding rules.
/// </summary>
public static async Task<List<ISeedingRule>> GetForClientIdAsync(DataContext ctx, Guid clientId)
{
var client = await ctx.DownloadClients
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == clientId);
return client is null ? [] : await GetForClientAsync(ctx, client);
}
/// <summary>
/// Filters seeding rules for a client from pre-loaded in-memory lists.
/// Use this in bulk-load scenarios to avoid N+1 queries.
/// </summary>
public static List<ISeedingRule> FilterForClient(
DownloadClientConfig client,
List<QBitSeedingRule> qbitRules,
List<DelugeSeedingRule> delugeRules,
List<TransmissionSeedingRule> transmissionRules,
List<UTorrentSeedingRule> utorrentRules,
List<RTorrentSeedingRule> rtorrentRules)
{
return client.TypeName switch
{
DownloadClientTypeName.qBittorrent => qbitRules
.Where(r => r.DownloadClientConfigId == client.Id)
.OrderBy(r => r.Priority).ThenBy(r => r.Id)
.Cast<ISeedingRule>().ToList(),
DownloadClientTypeName.Deluge => delugeRules
.Where(r => r.DownloadClientConfigId == client.Id)
.OrderBy(r => r.Priority).ThenBy(r => r.Id)
.Cast<ISeedingRule>().ToList(),
DownloadClientTypeName.Transmission => transmissionRules
.Where(r => r.DownloadClientConfigId == client.Id)
.OrderBy(r => r.Priority).ThenBy(r => r.Id)
.Cast<ISeedingRule>().ToList(),
DownloadClientTypeName.uTorrent => utorrentRules
.Where(r => r.DownloadClientConfigId == client.Id)
.OrderBy(r => r.Priority).ThenBy(r => r.Id)
.Cast<ISeedingRule>().ToList(),
DownloadClientTypeName.rTorrent => rtorrentRules
.Where(r => r.DownloadClientConfigId == client.Id)
.OrderBy(r => r.Priority).ThenBy(r => r.Id)
.Cast<ISeedingRule>().ToList(),
_ => [],
};
}
/// <summary>
/// Searches all five per-type seeding rule tables for a rule with the given ID.
/// Returns the rule and a sentinel string identifying its type, or (null, null) if not found.
/// </summary>
public static async Task<(ISeedingRule? rule, object? dbSet)> FindByIdAsync(DataContext ctx, Guid id)
{
var qbit = await ctx.QBitSeedingRules.FirstOrDefaultAsync(r => r.Id == id);
if (qbit is not null) return (qbit, ctx.QBitSeedingRules);
var deluge = await ctx.DelugeSeedingRules.FirstOrDefaultAsync(r => r.Id == id);
if (deluge is not null) return (deluge, ctx.DelugeSeedingRules);
var transmission = await ctx.TransmissionSeedingRules.FirstOrDefaultAsync(r => r.Id == id);
if (transmission is not null) return (transmission, ctx.TransmissionSeedingRules);
var utorrent = await ctx.UTorrentSeedingRules.FirstOrDefaultAsync(r => r.Id == id);
if (utorrent is not null) return (utorrent, ctx.UTorrentSeedingRules);
var rtorrent = await ctx.RTorrentSeedingRules.FirstOrDefaultAsync(r => r.Id == id);
if (rtorrent is not null) return (rtorrent, ctx.RTorrentSeedingRules);
return (null, null);
}
}
@@ -27,6 +27,10 @@ public sealed record CreateDownloadClientRequest
public string? ExternalUrl { get; init; }
public string? DownloadDirectorySource { get; init; }
public string? DownloadDirectoryTarget { get; init; }
public void Validate()
{
if (string.IsNullOrWhiteSpace(Name))
@@ -66,5 +70,7 @@ public sealed record CreateDownloadClientRequest
Password = Password,
UrlBase = UrlBase,
ExternalUrl = !string.IsNullOrWhiteSpace(ExternalUrl) ? new Uri(ExternalUrl, UriKind.RelativeOrAbsolute) : null,
DownloadDirectorySource = DownloadDirectorySource,
DownloadDirectoryTarget = DownloadDirectoryTarget,
};
}
@@ -27,6 +27,10 @@ public sealed record UpdateDownloadClientRequest
public string? ExternalUrl { get; init; }
public string? DownloadDirectorySource { get; init; }
public string? DownloadDirectoryTarget { get; init; }
public void Validate()
{
if (string.IsNullOrWhiteSpace(Name))
@@ -61,5 +65,7 @@ public sealed record UpdateDownloadClientRequest
Password = Password.IsPlaceholder() ? existing.Password : Password,
UrlBase = UrlBase,
ExternalUrl = !string.IsNullOrWhiteSpace(ExternalUrl) ? new Uri(ExternalUrl, UriKind.RelativeOrAbsolute) : null,
DownloadDirectorySource = DownloadDirectorySource,
DownloadDirectoryTarget = DownloadDirectoryTarget,
};
}
@@ -1,6 +1,7 @@
using System;
using System.Linq;
using Cleanuparr.Api.Extensions;
using Cleanuparr.Api.Features.DownloadClient.Contracts.Requests;
using Cleanuparr.Infrastructure.Features.DownloadClient;
using Cleanuparr.Infrastructure.Http.DynamicHttpClientSystem;
@@ -66,17 +67,13 @@ public sealed class DownloadClientController : ControllerBase
newClient.Validate();
var clientConfig = newClient.ToEntity();
clientConfig.Validate();
_dataContext.DownloadClients.Add(clientConfig);
await _dataContext.SaveChangesAsync();
return CreatedAtAction(nameof(GetDownloadClientConfig), new { id = clientConfig.Id }, clientConfig);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create download client");
throw;
}
finally
{
DataContext.Lock.Release();
@@ -96,21 +93,17 @@ public sealed class DownloadClientController : ControllerBase
if (existingClient is null)
{
return NotFound($"Download client with ID {id} not found");
return this.ProblemResult(StatusCodes.Status404NotFound, $"Download client with ID {id} not found");
}
var clientToPersist = updatedClient.ApplyTo(existingClient);
clientToPersist.Validate();
_dataContext.Entry(existingClient).CurrentValues.SetValues(clientToPersist);
await _dataContext.SaveChangesAsync();
return Ok(clientToPersist);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update download client with ID {Id}", id);
throw;
}
finally
{
DataContext.Lock.Release();
@@ -128,7 +121,7 @@ public sealed class DownloadClientController : ControllerBase
if (existingClient is null)
{
return NotFound($"Download client with ID {id} not found");
return this.ProblemResult(StatusCodes.Status404NotFound, $"Download client with ID {id} not found");
}
_dataContext.DownloadClients.Remove(existingClient);
@@ -141,11 +134,6 @@ public sealed class DownloadClientController : ControllerBase
return NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to delete download client with ID {Id}", id);
throw;
}
finally
{
DataContext.Lock.Release();
@@ -169,7 +157,7 @@ public sealed class DownloadClientController : ControllerBase
if (existingClient is null)
{
return NotFound($"Download client with ID {request.ClientId.Value} not found");
return this.ProblemResult(StatusCodes.Status404NotFound, $"Download client with ID {request.ClientId.Value} not found");
}
resolvedPassword = existingClient.Password;
@@ -188,12 +176,12 @@ public sealed class DownloadClientController : ControllerBase
});
}
return BadRequest(new { Message = healthResult.ErrorMessage ?? "Connection failed" });
return this.ProblemResult(StatusCodes.Status400BadRequest, healthResult.ErrorMessage ?? "Connection failed");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to test {TypeName} client connection", request.TypeName);
return BadRequest(new { Message = $"Connection failed: {ex.Message}" });
return this.ProblemResult(StatusCodes.Status400BadRequest, $"Connection failed: {ex.Message}");
}
}
}
@@ -2,7 +2,6 @@ using Cleanuparr.Domain.Enums;
using Cleanuparr.Infrastructure.Http.DynamicHttpClientSystem;
using Cleanuparr.Infrastructure.Logging;
using Cleanuparr.Persistence.Models.Configuration.General;
using Cleanuparr.Shared.Helpers;
using Serilog.Events;
using ValidationException = Cleanuparr.Domain.Exceptions.ValidationException;
@@ -20,10 +19,6 @@ public sealed record UpdateGeneralConfigRequest
public CertificateValidationType HttpCertificateValidation { get; init; } = CertificateValidationType.Enabled;
public bool SearchEnabled { get; init; } = true;
public ushort SearchDelay { get; init; } = Constants.DefaultSearchDelaySeconds;
public bool StatusCheckEnabled { get; init; } = true;
public string EncryptionKey { get; init; } = Guid.NewGuid().ToString();
@@ -43,8 +38,6 @@ public sealed record UpdateGeneralConfigRequest
existingConfig.HttpMaxRetries = HttpMaxRetries;
existingConfig.HttpTimeout = HttpTimeout;
existingConfig.HttpCertificateValidation = HttpCertificateValidation;
existingConfig.SearchEnabled = SearchEnabled;
existingConfig.SearchDelay = SearchDelay;
existingConfig.StatusCheckEnabled = StatusCheckEnabled;
existingConfig.EncryptionKey = EncryptionKey;
existingConfig.IgnoredDownloads = IgnoredDownloads;
@@ -63,23 +63,42 @@ public sealed class GeneralConfigController : ControllerBase
if (wasDryRun && !config.DryRun)
{
var deletedStrikes = await eventsContext.Strikes.ExecuteDeleteAsync();
var deletedItems = await eventsContext.DownloadItems
.Where(d => !d.Strikes.Any())
.ExecuteDeleteAsync();
await using var transaction = await eventsContext.Database.BeginTransactionAsync();
_logger.LogWarning(
"Dry run disabled — purged all strikes: {Strikes} strikes, {Items} download items removed",
deletedStrikes, deletedItems);
try
{
var deletedStrikes = await eventsContext.Strikes
.Where(s => s.IsDryRun)
.ExecuteDeleteAsync();
var deletedEvents = await eventsContext.Events
.Where(e => e.IsDryRun)
.ExecuteDeleteAsync();
var deletedManualEvents = await eventsContext.ManualEvents
.Where(e => e.IsDryRun)
.ExecuteDeleteAsync();
var deletedItems = await eventsContext.DownloadItems
.Where(d => !d.Strikes.Any())
.ExecuteDeleteAsync();
var deletedHistory = await _dataContext.SeekerHistory
.Where(h => h.IsDryRun)
.ExecuteDeleteAsync();
_logger.LogWarning(
"Dry run disabled — purged dry-run data: {Strikes} strikes, {Events} events, {ManualEvents} manual events, {Items} orphaned download items, {History} search history entries removed",
deletedStrikes, deletedEvents, deletedManualEvents, deletedItems, deletedHistory);
await transaction.CommitAsync();
}
catch
{
await transaction.RollbackAsync();
throw;
}
}
return Ok(new { Message = "General configuration updated successfully" });
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to save General configuration");
throw;
}
finally
{
DataContext.Lock.Release();
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Persistence.Models.Configuration.MalwareBlocker;
namespace Cleanuparr.Api.Features.MalwareBlocker.Contracts.Requests;
@@ -8,6 +9,8 @@ public sealed record UpdateMalwareBlockerConfigRequest
{
public bool Enabled { get; init; }
public JobTriggerMode TriggerMode { get; init; } = JobTriggerMode.Schedule;
public string CronExpression { get; init; } = "0/5 * * * * ?";
public bool UseAdvancedScheduling { get; init; }
@@ -18,6 +21,8 @@ public sealed record UpdateMalwareBlockerConfigRequest
public bool ProcessNoContentId { get; init; }
public bool DeleteIfAnyFileBlocked { get; init; }
public BlocklistSettings Sonarr { get; init; } = new();
public BlocklistSettings Radarr { get; init; } = new();
@@ -33,11 +38,13 @@ public sealed record UpdateMalwareBlockerConfigRequest
public ContentBlockerConfig ApplyTo(ContentBlockerConfig config)
{
config.Enabled = Enabled;
config.TriggerMode = TriggerMode;
config.CronExpression = CronExpression;
config.UseAdvancedScheduling = UseAdvancedScheduling;
config.IgnorePrivate = IgnorePrivate;
config.DeletePrivate = DeletePrivate;
config.ProcessNoContentId = ProcessNoContentId;
config.DeleteIfAnyFileBlocked = DeleteIfAnyFileBlocked;
config.Sonarr = Sonarr;
config.Radarr = Radarr;
config.Lidarr = Lidarr;
@@ -74,15 +74,6 @@ public sealed class MalwareBlockerConfigController : ControllerBase
return Ok(new { Message = "MalwareBlocker configuration updated successfully" });
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to save MalwareBlocker configuration");
throw;
}
finally
{
DataContext.Lock.Release();
@@ -91,7 +82,11 @@ public sealed class MalwareBlockerConfigController : ControllerBase
private async Task UpdateJobSchedule(IJobConfig config, JobType jobType)
{
if (config.Enabled)
// Webhook-only mode keeps the feature enabled but removes the cron trigger.
bool scheduleEnabled = config.Enabled &&
config is not ContentBlockerConfig { TriggerMode: JobTriggerMode.Webhook };
if (scheduleEnabled)
{
if (!string.IsNullOrEmpty(config.CronExpression))
{
@@ -17,4 +17,8 @@ public abstract record CreateNotificationProviderRequestBase
public bool OnDownloadCleaned { get; init; }
public bool OnCategoryChanged { get; init; }
public bool OnSearchTriggered { get; init; }
public bool OnSearchItemGrabbed { get; init; }
}
@@ -17,4 +17,8 @@ public abstract record UpdateNotificationProviderRequestBase
public bool OnDownloadCleaned { get; init; }
public bool OnCategoryChanged { get; init; }
public bool OnSearchTriggered { get; init; }
public bool OnSearchItemGrabbed { get; init; }
}
@@ -1,14 +1,11 @@
using System.Net;
using Cleanuparr.Api.Extensions;
using Cleanuparr.Api.Features.Notifications.Contracts.Requests;
using Cleanuparr.Api.Features.Notifications.Contracts.Responses;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Domain.Exceptions;
using Cleanuparr.Infrastructure.Features.Notifications;
using Cleanuparr.Infrastructure.Features.Notifications.Apprise;
using Cleanuparr.Infrastructure.Features.Notifications.Discord;
using Cleanuparr.Infrastructure.Features.Notifications.Models;
using Cleanuparr.Infrastructure.Features.Notifications.Telegram;
using Cleanuparr.Infrastructure.Features.Notifications.Gotify;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Configuration.Notification;
using Cleanuparr.Shared.Helpers;
@@ -74,7 +71,9 @@ public sealed class NotificationProvidersController : ControllerBase
OnSlowStrike = p.OnSlowStrike,
OnQueueItemDeleted = p.OnQueueItemDeleted,
OnDownloadCleaned = p.OnDownloadCleaned,
OnCategoryChanged = p.OnCategoryChanged
OnCategoryChanged = p.OnCategoryChanged,
OnSearchTriggered = p.OnSearchTriggered,
OnSearchItemGrabbed = p.OnSearchItemGrabbed
},
Configuration = p.Type switch
{
@@ -121,18 +120,18 @@ public sealed class NotificationProvidersController : ControllerBase
{
if (string.IsNullOrWhiteSpace(newProvider.Name))
{
return BadRequest("Provider name is required");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Provider name is required");
}
var duplicateConfig = await _dataContext.NotificationConfigs.CountAsync(x => x.Name == newProvider.Name);
if (duplicateConfig > 0)
{
return BadRequest("A provider with this name already exists");
return this.ProblemResult(StatusCodes.Status400BadRequest, "A provider with this name already exists");
}
if (newProvider.ApiKey.IsPlaceholder())
{
return BadRequest("API key cannot be a placeholder value");
return this.ProblemResult(StatusCodes.Status400BadRequest, "API key cannot be a placeholder value");
}
var notifiarrConfig = new NotifiarrConfig
@@ -153,6 +152,8 @@ public sealed class NotificationProvidersController : ControllerBase
OnQueueItemDeleted = newProvider.OnQueueItemDeleted,
OnDownloadCleaned = newProvider.OnDownloadCleaned,
OnCategoryChanged = newProvider.OnCategoryChanged,
OnSearchTriggered = newProvider.OnSearchTriggered,
OnSearchItemGrabbed = newProvider.OnSearchItemGrabbed,
NotifiarrConfiguration = notifiarrConfig
};
@@ -164,11 +165,6 @@ public sealed class NotificationProvidersController : ControllerBase
var providerDto = MapProvider(provider);
return CreatedAtAction(nameof(GetNotificationProviders), new { id = provider.Id }, providerDto);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create Notifiarr provider");
throw;
}
finally
{
DataContext.Lock.Release();
@@ -183,23 +179,23 @@ public sealed class NotificationProvidersController : ControllerBase
{
if (string.IsNullOrWhiteSpace(newProvider.Name))
{
return BadRequest("Provider name is required");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Provider name is required");
}
var duplicateConfig = await _dataContext.NotificationConfigs.CountAsync(x => x.Name == newProvider.Name);
if (duplicateConfig > 0)
{
return BadRequest("A provider with this name already exists");
return this.ProblemResult(StatusCodes.Status400BadRequest, "A provider with this name already exists");
}
if (newProvider.Key.IsPlaceholder())
{
return BadRequest("Key cannot be a placeholder value");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Key cannot be a placeholder value");
}
if (newProvider.ServiceUrls.IsPlaceholder())
{
return BadRequest("Service URLs cannot be a placeholder value");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Service URLs cannot be a placeholder value");
}
var appriseConfig = new AppriseConfig
@@ -223,6 +219,8 @@ public sealed class NotificationProvidersController : ControllerBase
OnQueueItemDeleted = newProvider.OnQueueItemDeleted,
OnDownloadCleaned = newProvider.OnDownloadCleaned,
OnCategoryChanged = newProvider.OnCategoryChanged,
OnSearchTriggered = newProvider.OnSearchTriggered,
OnSearchItemGrabbed = newProvider.OnSearchItemGrabbed,
AppriseConfiguration = appriseConfig
};
@@ -234,15 +232,6 @@ public sealed class NotificationProvidersController : ControllerBase
var providerDto = MapProvider(provider);
return CreatedAtAction(nameof(GetNotificationProviders), new { id = provider.Id }, providerDto);
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create Apprise provider");
throw;
}
finally
{
DataContext.Lock.Release();
@@ -257,23 +246,23 @@ public sealed class NotificationProvidersController : ControllerBase
{
if (string.IsNullOrWhiteSpace(newProvider.Name))
{
return BadRequest("Provider name is required");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Provider name is required");
}
var duplicateConfig = await _dataContext.NotificationConfigs.CountAsync(x => x.Name == newProvider.Name);
if (duplicateConfig > 0)
{
return BadRequest("A provider with this name already exists");
return this.ProblemResult(StatusCodes.Status400BadRequest, "A provider with this name already exists");
}
if (newProvider.Password.IsPlaceholder())
{
return BadRequest("Password cannot be a placeholder value");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Password cannot be a placeholder value");
}
if (newProvider.AccessToken.IsPlaceholder())
{
return BadRequest("Access token cannot be a placeholder value");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Access token cannot be a placeholder value");
}
var ntfyConfig = new NtfyConfig
@@ -300,6 +289,8 @@ public sealed class NotificationProvidersController : ControllerBase
OnQueueItemDeleted = newProvider.OnQueueItemDeleted,
OnDownloadCleaned = newProvider.OnDownloadCleaned,
OnCategoryChanged = newProvider.OnCategoryChanged,
OnSearchTriggered = newProvider.OnSearchTriggered,
OnSearchItemGrabbed = newProvider.OnSearchItemGrabbed,
NtfyConfiguration = ntfyConfig
};
@@ -311,15 +302,6 @@ public sealed class NotificationProvidersController : ControllerBase
var providerDto = MapProvider(provider);
return CreatedAtAction(nameof(GetNotificationProviders), new { id = provider.Id }, providerDto);
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create Ntfy provider");
throw;
}
finally
{
DataContext.Lock.Release();
@@ -334,18 +316,18 @@ public sealed class NotificationProvidersController : ControllerBase
{
if (string.IsNullOrWhiteSpace(newProvider.Name))
{
return BadRequest("Provider name is required");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Provider name is required");
}
var duplicateConfig = await _dataContext.NotificationConfigs.CountAsync(x => x.Name == newProvider.Name);
if (duplicateConfig > 0)
{
return BadRequest("A provider with this name already exists");
return this.ProblemResult(StatusCodes.Status400BadRequest, "A provider with this name already exists");
}
if (newProvider.BotToken.IsPlaceholder())
{
return BadRequest("Bot token cannot be a placeholder value");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Bot token cannot be a placeholder value");
}
var telegramConfig = new TelegramConfig
@@ -368,6 +350,8 @@ public sealed class NotificationProvidersController : ControllerBase
OnQueueItemDeleted = newProvider.OnQueueItemDeleted,
OnDownloadCleaned = newProvider.OnDownloadCleaned,
OnCategoryChanged = newProvider.OnCategoryChanged,
OnSearchTriggered = newProvider.OnSearchTriggered,
OnSearchItemGrabbed = newProvider.OnSearchItemGrabbed,
TelegramConfiguration = telegramConfig
};
@@ -379,15 +363,6 @@ public sealed class NotificationProvidersController : ControllerBase
var providerDto = MapProvider(provider);
return CreatedAtAction(nameof(GetNotificationProviders), new { id = provider.Id }, providerDto);
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create Telegram provider");
throw;
}
finally
{
DataContext.Lock.Release();
@@ -406,12 +381,12 @@ public sealed class NotificationProvidersController : ControllerBase
if (existingProvider == null)
{
return NotFound($"Notifiarr provider with ID {id} not found");
return this.ProblemResult(StatusCodes.Status404NotFound, $"Notifiarr provider with ID {id} not found");
}
if (string.IsNullOrWhiteSpace(updatedProvider.Name))
{
return BadRequest("Provider name is required");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Provider name is required");
}
var duplicateConfig = await _dataContext.NotificationConfigs
@@ -420,7 +395,7 @@ public sealed class NotificationProvidersController : ControllerBase
.CountAsync();
if (duplicateConfig > 0)
{
return BadRequest("A provider with this name already exists");
return this.ProblemResult(StatusCodes.Status400BadRequest, "A provider with this name already exists");
}
var notifiarrConfig = new NotifiarrConfig
@@ -447,8 +422,10 @@ public sealed class NotificationProvidersController : ControllerBase
OnQueueItemDeleted = updatedProvider.OnQueueItemDeleted,
OnDownloadCleaned = updatedProvider.OnDownloadCleaned,
OnCategoryChanged = updatedProvider.OnCategoryChanged,
OnSearchTriggered = updatedProvider.OnSearchTriggered,
OnSearchItemGrabbed = updatedProvider.OnSearchItemGrabbed,
NotifiarrConfiguration = notifiarrConfig,
UpdatedAt = DateTime.UtcNow
UpdatedAt = DateTimeOffset.UtcNow
};
_dataContext.NotificationConfigs.Remove(existingProvider);
@@ -460,15 +437,6 @@ public sealed class NotificationProvidersController : ControllerBase
var providerDto = MapProvider(newProvider);
return Ok(providerDto);
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update Notifiarr provider with ID {Id}", id);
throw;
}
finally
{
DataContext.Lock.Release();
@@ -487,12 +455,12 @@ public sealed class NotificationProvidersController : ControllerBase
if (existingProvider == null)
{
return NotFound($"Apprise provider with ID {id} not found");
return this.ProblemResult(StatusCodes.Status404NotFound, $"Apprise provider with ID {id} not found");
}
if (string.IsNullOrWhiteSpace(updatedProvider.Name))
{
return BadRequest("Provider name is required");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Provider name is required");
}
var duplicateConfig = await _dataContext.NotificationConfigs
@@ -501,7 +469,7 @@ public sealed class NotificationProvidersController : ControllerBase
.CountAsync();
if (duplicateConfig > 0)
{
return BadRequest("A provider with this name already exists");
return this.ProblemResult(StatusCodes.Status400BadRequest, "A provider with this name already exists");
}
var appriseConfig = new AppriseConfig
@@ -533,8 +501,10 @@ public sealed class NotificationProvidersController : ControllerBase
OnQueueItemDeleted = updatedProvider.OnQueueItemDeleted,
OnDownloadCleaned = updatedProvider.OnDownloadCleaned,
OnCategoryChanged = updatedProvider.OnCategoryChanged,
OnSearchTriggered = updatedProvider.OnSearchTriggered,
OnSearchItemGrabbed = updatedProvider.OnSearchItemGrabbed,
AppriseConfiguration = appriseConfig,
UpdatedAt = DateTime.UtcNow
UpdatedAt = DateTimeOffset.UtcNow
};
_dataContext.NotificationConfigs.Remove(existingProvider);
@@ -546,15 +516,6 @@ public sealed class NotificationProvidersController : ControllerBase
var providerDto = MapProvider(newProvider);
return Ok(providerDto);
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update Apprise provider with ID {Id}", id);
throw;
}
finally
{
DataContext.Lock.Release();
@@ -573,12 +534,12 @@ public sealed class NotificationProvidersController : ControllerBase
if (existingProvider == null)
{
return NotFound($"Ntfy provider with ID {id} not found");
return this.ProblemResult(StatusCodes.Status404NotFound, $"Ntfy provider with ID {id} not found");
}
if (string.IsNullOrWhiteSpace(updatedProvider.Name))
{
return BadRequest("Provider name is required");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Provider name is required");
}
var duplicateConfig = await _dataContext.NotificationConfigs
@@ -587,7 +548,7 @@ public sealed class NotificationProvidersController : ControllerBase
.CountAsync();
if (duplicateConfig > 0)
{
return BadRequest("A provider with this name already exists");
return this.ProblemResult(StatusCodes.Status400BadRequest, "A provider with this name already exists");
}
var ntfyConfig = new NtfyConfig
@@ -622,8 +583,10 @@ public sealed class NotificationProvidersController : ControllerBase
OnQueueItemDeleted = updatedProvider.OnQueueItemDeleted,
OnDownloadCleaned = updatedProvider.OnDownloadCleaned,
OnCategoryChanged = updatedProvider.OnCategoryChanged,
OnSearchTriggered = updatedProvider.OnSearchTriggered,
OnSearchItemGrabbed = updatedProvider.OnSearchItemGrabbed,
NtfyConfiguration = ntfyConfig,
UpdatedAt = DateTime.UtcNow
UpdatedAt = DateTimeOffset.UtcNow
};
_dataContext.NotificationConfigs.Remove(existingProvider);
@@ -635,15 +598,6 @@ public sealed class NotificationProvidersController : ControllerBase
var providerDto = MapProvider(newProvider);
return Ok(providerDto);
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update Ntfy provider with ID {Id}", id);
throw;
}
finally
{
DataContext.Lock.Release();
@@ -662,12 +616,12 @@ public sealed class NotificationProvidersController : ControllerBase
if (existingProvider == null)
{
return NotFound($"Telegram provider with ID {id} not found");
return this.ProblemResult(StatusCodes.Status404NotFound, $"Telegram provider with ID {id} not found");
}
if (string.IsNullOrWhiteSpace(updatedProvider.Name))
{
return BadRequest("Provider name is required");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Provider name is required");
}
var duplicateConfig = await _dataContext.NotificationConfigs
@@ -676,7 +630,7 @@ public sealed class NotificationProvidersController : ControllerBase
.CountAsync();
if (duplicateConfig > 0)
{
return BadRequest("A provider with this name already exists");
return this.ProblemResult(StatusCodes.Status400BadRequest, "A provider with this name already exists");
}
var telegramConfig = new TelegramConfig
@@ -705,8 +659,10 @@ public sealed class NotificationProvidersController : ControllerBase
OnQueueItemDeleted = updatedProvider.OnQueueItemDeleted,
OnDownloadCleaned = updatedProvider.OnDownloadCleaned,
OnCategoryChanged = updatedProvider.OnCategoryChanged,
OnSearchTriggered = updatedProvider.OnSearchTriggered,
OnSearchItemGrabbed = updatedProvider.OnSearchItemGrabbed,
TelegramConfiguration = telegramConfig,
UpdatedAt = DateTime.UtcNow
UpdatedAt = DateTimeOffset.UtcNow
};
_dataContext.NotificationConfigs.Remove(existingProvider);
@@ -718,15 +674,6 @@ public sealed class NotificationProvidersController : ControllerBase
var providerDto = MapProvider(newProvider);
return Ok(providerDto);
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update Telegram provider with ID {Id}", id);
throw;
}
finally
{
DataContext.Lock.Release();
@@ -751,7 +698,7 @@ public sealed class NotificationProvidersController : ControllerBase
if (existingProvider == null)
{
return NotFound($"Notification provider with ID {id} not found");
return this.ProblemResult(StatusCodes.Status404NotFound, $"Notification provider with ID {id} not found");
}
_dataContext.NotificationConfigs.Remove(existingProvider);
@@ -764,11 +711,6 @@ public sealed class NotificationProvidersController : ControllerBase
return NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to delete notification provider with ID {Id}", id);
throw;
}
finally
{
DataContext.Lock.Release();
@@ -789,7 +731,7 @@ public sealed class NotificationProvidersController : ControllerBase
if (existing is null)
{
return BadRequest(new { Message = "API key cannot be a placeholder value" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "API key cannot be a placeholder value");
}
apiKey = existing.ApiKey;
@@ -815,7 +757,9 @@ public sealed class NotificationProvidersController : ControllerBase
OnSlowStrike = false,
OnQueueItemDeleted = false,
OnDownloadCleaned = false,
OnCategoryChanged = false
OnCategoryChanged = false,
OnSearchTriggered = false,
OnSearchItemGrabbed = false
},
Configuration = notifiarrConfig
};
@@ -825,8 +769,7 @@ public sealed class NotificationProvidersController : ControllerBase
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to test Notifiarr provider");
return BadRequest(new { Message = $"Test failed: {ex.Message}" });
throw new NotificationTestException($"Test failed: {ex.Message}", ex);
}
}
@@ -845,7 +788,7 @@ public sealed class NotificationProvidersController : ControllerBase
if (existing is null)
{
return BadRequest(new { Message = "Sensitive fields cannot be placeholder values" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "Sensitive fields cannot be placeholder values");
}
if (key.IsPlaceholder())
@@ -882,7 +825,9 @@ public sealed class NotificationProvidersController : ControllerBase
OnSlowStrike = false,
OnQueueItemDeleted = false,
OnDownloadCleaned = false,
OnCategoryChanged = false
OnCategoryChanged = false,
OnSearchTriggered = false,
OnSearchItemGrabbed = false
},
Configuration = appriseConfig
};
@@ -890,14 +835,9 @@ public sealed class NotificationProvidersController : ControllerBase
await _notificationService.SendTestNotificationAsync(providerDto);
return Ok(new { Message = "Test notification sent successfully" });
}
catch (AppriseException exception)
{
return StatusCode((int)HttpStatusCode.InternalServerError, exception.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to test Apprise provider");
return BadRequest(new { Message = $"Test failed: {ex.Message}" });
throw new NotificationTestException($"Test failed: {ex.Message}", ex);
}
}
@@ -916,7 +856,7 @@ public sealed class NotificationProvidersController : ControllerBase
if (existing is null)
{
return BadRequest(new { Message = "Sensitive fields cannot be placeholder values" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "Sensitive fields cannot be placeholder values");
}
if (password.IsPlaceholder())
@@ -956,7 +896,9 @@ public sealed class NotificationProvidersController : ControllerBase
OnSlowStrike = false,
OnQueueItemDeleted = false,
OnDownloadCleaned = false,
OnCategoryChanged = false
OnCategoryChanged = false,
OnSearchTriggered = false,
OnSearchItemGrabbed = false
},
Configuration = ntfyConfig
};
@@ -966,8 +908,7 @@ public sealed class NotificationProvidersController : ControllerBase
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to test Ntfy provider");
return BadRequest(new { Message = $"Test failed: {ex.Message}" });
throw new NotificationTestException($"Test failed: {ex.Message}", ex);
}
}
@@ -985,7 +926,7 @@ public sealed class NotificationProvidersController : ControllerBase
if (existing is null)
{
return BadRequest(new { Message = "Bot token cannot be a placeholder value" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "Bot token cannot be a placeholder value");
}
botToken = existing.BotToken;
@@ -1013,7 +954,9 @@ public sealed class NotificationProvidersController : ControllerBase
OnSlowStrike = false,
OnQueueItemDeleted = false,
OnDownloadCleaned = false,
OnCategoryChanged = false
OnCategoryChanged = false,
OnSearchTriggered = false,
OnSearchItemGrabbed = false
},
Configuration = telegramConfig
};
@@ -1021,15 +964,9 @@ public sealed class NotificationProvidersController : ControllerBase
await _notificationService.SendTestNotificationAsync(providerDto);
return Ok(new { Message = "Test notification sent successfully" });
}
catch (TelegramException ex)
{
_logger.LogWarning(ex, "Failed to test Telegram provider");
return BadRequest(new { Message = $"Test failed: {ex.Message}" });
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to test Telegram provider");
return BadRequest(new { Message = $"Test failed: {ex.Message}" });
throw new NotificationTestException($"Test failed: {ex.Message}", ex);
}
}
@@ -1048,7 +985,9 @@ public sealed class NotificationProvidersController : ControllerBase
OnSlowStrike = provider.OnSlowStrike,
OnQueueItemDeleted = provider.OnQueueItemDeleted,
OnDownloadCleaned = provider.OnDownloadCleaned,
OnCategoryChanged = provider.OnCategoryChanged
OnCategoryChanged = provider.OnCategoryChanged,
OnSearchTriggered = provider.OnSearchTriggered,
OnSearchItemGrabbed = provider.OnSearchItemGrabbed
},
Configuration = provider.Type switch
{
@@ -1072,18 +1011,18 @@ public sealed class NotificationProvidersController : ControllerBase
{
if (string.IsNullOrWhiteSpace(newProvider.Name))
{
return BadRequest("Provider name is required");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Provider name is required");
}
var duplicateConfig = await _dataContext.NotificationConfigs.CountAsync(x => x.Name == newProvider.Name);
if (duplicateConfig > 0)
{
return BadRequest("A provider with this name already exists");
return this.ProblemResult(StatusCodes.Status400BadRequest, "A provider with this name already exists");
}
if (newProvider.WebhookUrl.IsPlaceholder())
{
return BadRequest("Webhook URL cannot be a placeholder value");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Webhook URL cannot be a placeholder value");
}
var discordConfig = new DiscordConfig
@@ -1105,6 +1044,8 @@ public sealed class NotificationProvidersController : ControllerBase
OnQueueItemDeleted = newProvider.OnQueueItemDeleted,
OnDownloadCleaned = newProvider.OnDownloadCleaned,
OnCategoryChanged = newProvider.OnCategoryChanged,
OnSearchTriggered = newProvider.OnSearchTriggered,
OnSearchItemGrabbed = newProvider.OnSearchItemGrabbed,
DiscordConfiguration = discordConfig
};
@@ -1116,15 +1057,6 @@ public sealed class NotificationProvidersController : ControllerBase
var providerDto = MapProvider(provider);
return CreatedAtAction(nameof(GetNotificationProviders), new { id = provider.Id }, providerDto);
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create Discord provider");
throw;
}
finally
{
DataContext.Lock.Release();
@@ -1143,12 +1075,12 @@ public sealed class NotificationProvidersController : ControllerBase
if (existingProvider == null)
{
return NotFound($"Discord provider with ID {id} not found");
return this.ProblemResult(StatusCodes.Status404NotFound, $"Discord provider with ID {id} not found");
}
if (string.IsNullOrWhiteSpace(updatedProvider.Name))
{
return BadRequest("Provider name is required");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Provider name is required");
}
var duplicateConfig = await _dataContext.NotificationConfigs
@@ -1157,7 +1089,7 @@ public sealed class NotificationProvidersController : ControllerBase
.CountAsync();
if (duplicateConfig > 0)
{
return BadRequest("A provider with this name already exists");
return this.ProblemResult(StatusCodes.Status400BadRequest, "A provider with this name already exists");
}
var discordConfig = new DiscordConfig
@@ -1185,8 +1117,10 @@ public sealed class NotificationProvidersController : ControllerBase
OnQueueItemDeleted = updatedProvider.OnQueueItemDeleted,
OnDownloadCleaned = updatedProvider.OnDownloadCleaned,
OnCategoryChanged = updatedProvider.OnCategoryChanged,
OnSearchTriggered = updatedProvider.OnSearchTriggered,
OnSearchItemGrabbed = updatedProvider.OnSearchItemGrabbed,
DiscordConfiguration = discordConfig,
UpdatedAt = DateTime.UtcNow
UpdatedAt = DateTimeOffset.UtcNow
};
_dataContext.NotificationConfigs.Remove(existingProvider);
@@ -1198,15 +1132,6 @@ public sealed class NotificationProvidersController : ControllerBase
var providerDto = MapProvider(newProvider);
return Ok(providerDto);
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update Discord provider with ID {Id}", id);
throw;
}
finally
{
DataContext.Lock.Release();
@@ -1227,7 +1152,7 @@ public sealed class NotificationProvidersController : ControllerBase
if (existing is null)
{
return BadRequest(new { Message = "Webhook URL cannot be a placeholder value" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "Webhook URL cannot be a placeholder value");
}
webhookUrl = existing.WebhookUrl;
@@ -1254,7 +1179,9 @@ public sealed class NotificationProvidersController : ControllerBase
OnSlowStrike = false,
OnQueueItemDeleted = false,
OnDownloadCleaned = false,
OnCategoryChanged = false
OnCategoryChanged = false,
OnSearchTriggered = false,
OnSearchItemGrabbed = false
},
Configuration = discordConfig
};
@@ -1262,15 +1189,9 @@ public sealed class NotificationProvidersController : ControllerBase
await _notificationService.SendTestNotificationAsync(providerDto);
return Ok(new { Message = "Test notification sent successfully" });
}
catch (DiscordException ex)
{
_logger.LogWarning(ex, "Failed to test Discord provider");
return BadRequest(new { Message = $"Test failed: {ex.Message}" });
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to test Discord provider");
return BadRequest(new { Message = $"Test failed: {ex.Message}" });
throw new NotificationTestException($"Test failed: {ex.Message}", ex);
}
}
@@ -1282,23 +1203,23 @@ public sealed class NotificationProvidersController : ControllerBase
{
if (string.IsNullOrWhiteSpace(newProvider.Name))
{
return BadRequest("Provider name is required");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Provider name is required");
}
var duplicateConfig = await _dataContext.NotificationConfigs.CountAsync(x => x.Name == newProvider.Name);
if (duplicateConfig > 0)
{
return BadRequest("A provider with this name already exists");
return this.ProblemResult(StatusCodes.Status400BadRequest, "A provider with this name already exists");
}
if (newProvider.ApiToken.IsPlaceholder())
{
return BadRequest("API token cannot be a placeholder value");
return this.ProblemResult(StatusCodes.Status400BadRequest, "API token cannot be a placeholder value");
}
if (newProvider.UserKey.IsPlaceholder())
{
return BadRequest("User key cannot be a placeholder value");
return this.ProblemResult(StatusCodes.Status400BadRequest, "User key cannot be a placeholder value");
}
var pushoverConfig = new PushoverConfig
@@ -1325,6 +1246,8 @@ public sealed class NotificationProvidersController : ControllerBase
OnQueueItemDeleted = newProvider.OnQueueItemDeleted,
OnDownloadCleaned = newProvider.OnDownloadCleaned,
OnCategoryChanged = newProvider.OnCategoryChanged,
OnSearchTriggered = newProvider.OnSearchTriggered,
OnSearchItemGrabbed = newProvider.OnSearchItemGrabbed,
PushoverConfiguration = pushoverConfig
};
@@ -1336,15 +1259,6 @@ public sealed class NotificationProvidersController : ControllerBase
var providerDto = MapProvider(provider);
return CreatedAtAction(nameof(GetNotificationProviders), new { id = provider.Id }, providerDto);
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create Pushover provider");
throw;
}
finally
{
DataContext.Lock.Release();
@@ -1363,12 +1277,12 @@ public sealed class NotificationProvidersController : ControllerBase
if (existingProvider == null)
{
return NotFound($"Pushover provider with ID {id} not found");
return this.ProblemResult(StatusCodes.Status404NotFound, $"Pushover provider with ID {id} not found");
}
if (string.IsNullOrWhiteSpace(updatedProvider.Name))
{
return BadRequest("Provider name is required");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Provider name is required");
}
var duplicateConfig = await _dataContext.NotificationConfigs
@@ -1377,7 +1291,7 @@ public sealed class NotificationProvidersController : ControllerBase
.CountAsync();
if (duplicateConfig > 0)
{
return BadRequest("A provider with this name already exists");
return this.ProblemResult(StatusCodes.Status400BadRequest, "A provider with this name already exists");
}
var pushoverConfig = new PushoverConfig
@@ -1412,8 +1326,10 @@ public sealed class NotificationProvidersController : ControllerBase
OnQueueItemDeleted = updatedProvider.OnQueueItemDeleted,
OnDownloadCleaned = updatedProvider.OnDownloadCleaned,
OnCategoryChanged = updatedProvider.OnCategoryChanged,
OnSearchTriggered = updatedProvider.OnSearchTriggered,
OnSearchItemGrabbed = updatedProvider.OnSearchItemGrabbed,
PushoverConfiguration = pushoverConfig,
UpdatedAt = DateTime.UtcNow
UpdatedAt = DateTimeOffset.UtcNow
};
_dataContext.NotificationConfigs.Remove(existingProvider);
@@ -1425,15 +1341,6 @@ public sealed class NotificationProvidersController : ControllerBase
var providerDto = MapProvider(newProvider);
return Ok(providerDto);
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update Pushover provider with ID {Id}", id);
throw;
}
finally
{
DataContext.Lock.Release();
@@ -1455,7 +1362,7 @@ public sealed class NotificationProvidersController : ControllerBase
if (existing is null)
{
return BadRequest(new { Message = "Sensitive fields cannot be placeholder values" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "Sensitive fields cannot be placeholder values");
}
if (apiToken.IsPlaceholder())
@@ -1495,7 +1402,9 @@ public sealed class NotificationProvidersController : ControllerBase
OnSlowStrike = false,
OnQueueItemDeleted = false,
OnDownloadCleaned = false,
OnCategoryChanged = false
OnCategoryChanged = false,
OnSearchTriggered = false,
OnSearchItemGrabbed = false
},
Configuration = pushoverConfig
};
@@ -1505,8 +1414,7 @@ public sealed class NotificationProvidersController : ControllerBase
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to test Pushover provider");
return BadRequest(new { Message = $"Test failed: {ex.Message}" });
throw new NotificationTestException($"Test failed: {ex.Message}", ex);
}
}
@@ -1518,18 +1426,18 @@ public sealed class NotificationProvidersController : ControllerBase
{
if (string.IsNullOrWhiteSpace(newProvider.Name))
{
return BadRequest("Provider name is required");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Provider name is required");
}
var duplicateConfig = await _dataContext.NotificationConfigs.CountAsync(x => x.Name == newProvider.Name);
if (duplicateConfig > 0)
{
return BadRequest("A provider with this name already exists");
return this.ProblemResult(StatusCodes.Status400BadRequest, "A provider with this name already exists");
}
if (newProvider.ApplicationToken.IsPlaceholder())
{
return BadRequest("Application token cannot be a placeholder value");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Application token cannot be a placeholder value");
}
var gotifyConfig = new GotifyConfig
@@ -1551,6 +1459,8 @@ public sealed class NotificationProvidersController : ControllerBase
OnQueueItemDeleted = newProvider.OnQueueItemDeleted,
OnDownloadCleaned = newProvider.OnDownloadCleaned,
OnCategoryChanged = newProvider.OnCategoryChanged,
OnSearchTriggered = newProvider.OnSearchTriggered,
OnSearchItemGrabbed = newProvider.OnSearchItemGrabbed,
GotifyConfiguration = gotifyConfig
};
@@ -1562,15 +1472,6 @@ public sealed class NotificationProvidersController : ControllerBase
var providerDto = MapProvider(provider);
return CreatedAtAction(nameof(GetNotificationProviders), new { id = provider.Id }, providerDto);
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create Gotify provider");
throw;
}
finally
{
DataContext.Lock.Release();
@@ -1589,12 +1490,12 @@ public sealed class NotificationProvidersController : ControllerBase
if (existingProvider == null)
{
return NotFound($"Gotify provider with ID {id} not found");
return this.ProblemResult(StatusCodes.Status404NotFound, $"Gotify provider with ID {id} not found");
}
if (string.IsNullOrWhiteSpace(updatedProvider.Name))
{
return BadRequest("Provider name is required");
return this.ProblemResult(StatusCodes.Status400BadRequest, "Provider name is required");
}
var duplicateConfig = await _dataContext.NotificationConfigs
@@ -1603,7 +1504,7 @@ public sealed class NotificationProvidersController : ControllerBase
.CountAsync();
if (duplicateConfig > 0)
{
return BadRequest("A provider with this name already exists");
return this.ProblemResult(StatusCodes.Status400BadRequest, "A provider with this name already exists");
}
var gotifyConfig = new GotifyConfig
@@ -1631,8 +1532,10 @@ public sealed class NotificationProvidersController : ControllerBase
OnQueueItemDeleted = updatedProvider.OnQueueItemDeleted,
OnDownloadCleaned = updatedProvider.OnDownloadCleaned,
OnCategoryChanged = updatedProvider.OnCategoryChanged,
OnSearchTriggered = updatedProvider.OnSearchTriggered,
OnSearchItemGrabbed = updatedProvider.OnSearchItemGrabbed,
GotifyConfiguration = gotifyConfig,
UpdatedAt = DateTime.UtcNow
UpdatedAt = DateTimeOffset.UtcNow
};
_dataContext.NotificationConfigs.Remove(existingProvider);
@@ -1644,15 +1547,6 @@ public sealed class NotificationProvidersController : ControllerBase
var providerDto = MapProvider(newProvider);
return Ok(providerDto);
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update Gotify provider with ID {Id}", id);
throw;
}
finally
{
DataContext.Lock.Release();
@@ -1672,7 +1566,9 @@ public sealed class NotificationProvidersController : ControllerBase
testRequest.ProviderId, NotificationProviderType.Gotify, p => p.GotifyConfiguration);
if (existing is null)
return BadRequest(new { Message = "Application token cannot be a placeholder value" });
{
return this.ProblemResult(StatusCodes.Status400BadRequest, "Application token cannot be a placeholder value");
}
applicationToken = existing.ApplicationToken;
}
@@ -1698,7 +1594,9 @@ public sealed class NotificationProvidersController : ControllerBase
OnSlowStrike = false,
OnQueueItemDeleted = false,
OnDownloadCleaned = false,
OnCategoryChanged = false
OnCategoryChanged = false,
OnSearchTriggered = false,
OnSearchItemGrabbed = false
},
Configuration = gotifyConfig
};
@@ -1706,15 +1604,9 @@ public sealed class NotificationProvidersController : ControllerBase
await _notificationService.SendTestNotificationAsync(providerDto);
return Ok(new { Message = "Test notification sent successfully" });
}
catch (GotifyException ex)
{
_logger.LogWarning(ex, "Failed to test Gotify provider");
return BadRequest(new { Message = $"Test failed: {ex.Message}" });
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to test Gotify provider");
return BadRequest(new { Message = $"Test failed: {ex.Message}" });
throw new NotificationTestException($"Test failed: {ex.Message}", ex);
}
}
@@ -20,8 +20,10 @@ public abstract record QueueRuleDto
[Range(0, 100, ErrorMessage = "Minimum completion percentage must be between 0 and 100")]
public ushort MinCompletionPercentage { get; set; }
[Range(0, 100, ErrorMessage = "Maximum completion percentage must be between 0 and 100")]
[Range(1, 100, ErrorMessage = "Maximum completion percentage must be between 1 and 100")]
public ushort MaxCompletionPercentage { get; set; }
public bool DeletePrivateTorrentsFromClient { get; set; } = false;
public bool ChangeCategory { get; set; } = false;
}
@@ -1,5 +1,3 @@
using System.ComponentModel.DataAnnotations;
using Cleanuparr.Api.Features.QueueCleaner.Contracts.Requests;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Infrastructure.Services.Interfaces;
@@ -80,15 +78,6 @@ public sealed class QueueCleanerConfigController : ControllerBase
return Ok(new { Message = "QueueCleaner configuration updated successfully" });
}
catch (ValidationException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to save QueueCleaner configuration");
throw;
}
finally
{
DataContext.Lock.Release();
@@ -1,5 +1,5 @@
using Cleanuparr.Api.Extensions;
using Cleanuparr.Api.Features.QueueCleaner.Contracts.Requests;
using Cleanuparr.Domain.Exceptions;
using Cleanuparr.Infrastructure.Services.Interfaces;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Configuration.QueueCleaner;
@@ -43,11 +43,6 @@ public class QueueRulesController : ControllerBase
return Ok(rules);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve stall rules");
return StatusCode(500, new { Message = "Failed to retrieve stall rules", Error = ex.Message });
}
finally
{
DataContext.Lock.Release();
@@ -57,11 +52,6 @@ public class QueueRulesController : ControllerBase
[HttpPost("stall")]
public async Task<IActionResult> CreateStallRule([FromBody] StallRuleDto ruleDto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
await DataContext.Lock.WaitAsync();
try
{
@@ -73,7 +63,7 @@ public class QueueRulesController : ControllerBase
if (existingRule != null)
{
return BadRequest(new { Message = "A stall rule with this name already exists" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "A stall rule with this name already exists");
}
var rule = new StallRule
@@ -88,6 +78,7 @@ public class QueueRulesController : ControllerBase
MaxCompletionPercentage = ruleDto.MaxCompletionPercentage,
ResetStrikesOnProgress = ruleDto.ResetStrikesOnProgress,
DeletePrivateTorrentsFromClient = ruleDto.DeletePrivateTorrentsFromClient,
ChangeCategory = ruleDto.ChangeCategory,
MinimumProgress = ruleDto.MinimumProgress?.Trim(),
};
@@ -96,7 +87,7 @@ public class QueueRulesController : ControllerBase
var intervalValidationResult = _ruleIntervalValidator.ValidateStallRuleIntervals(rule, existingRules);
if (!intervalValidationResult.IsValid)
{
return BadRequest(new { Message = intervalValidationResult.ErrorMessage });
return this.ProblemResult(StatusCodes.Status400BadRequest, intervalValidationResult.ErrorMessage);
}
rule.Validate();
@@ -108,16 +99,6 @@ public class QueueRulesController : ControllerBase
return CreatedAtAction(nameof(GetStallRules), new { id = rule.Id }, rule);
}
catch (ValidationException ex)
{
_logger.LogWarning("Validation failed for stall rule creation: {Message}", ex.Message);
return BadRequest(new { Message = ex.Message });
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create stall rule: {RuleName}", ruleDto.Name);
return StatusCode(500, new { Message = "Failed to create stall rule", Error = ex.Message });
}
finally
{
DataContext.Lock.Release();
@@ -127,11 +108,6 @@ public class QueueRulesController : ControllerBase
[HttpPut("stall/{id}")]
public async Task<IActionResult> UpdateStallRule(Guid id, [FromBody] StallRuleDto ruleDto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
await DataContext.Lock.WaitAsync();
try
{
@@ -140,15 +116,15 @@ public class QueueRulesController : ControllerBase
if (existingRule == null)
{
return NotFound(new { Message = $"Stall rule with ID {id} not found" });
return this.ProblemResult(StatusCodes.Status404NotFound, $"Stall rule with ID {id} not found");
}
var duplicateRule = await _dataContext.StallRules
.FirstOrDefaultAsync(r => r.Id != id && r.Name.ToLower() == ruleDto.Name.ToLower());
if (duplicateRule != null)
{
return BadRequest(new { Message = "A stall rule with this name already exists" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "A stall rule with this name already exists");
}
var updatedRule = existingRule with
@@ -161,6 +137,7 @@ public class QueueRulesController : ControllerBase
MaxCompletionPercentage = ruleDto.MaxCompletionPercentage,
ResetStrikesOnProgress = ruleDto.ResetStrikesOnProgress,
DeletePrivateTorrentsFromClient = ruleDto.DeletePrivateTorrentsFromClient,
ChangeCategory = ruleDto.ChangeCategory,
MinimumProgress = ruleDto.MinimumProgress?.Trim(),
};
@@ -171,7 +148,7 @@ public class QueueRulesController : ControllerBase
var intervalValidationResult = _ruleIntervalValidator.ValidateStallRuleIntervals(updatedRule, existingRules);
if (!intervalValidationResult.IsValid)
{
return BadRequest(new { Message = intervalValidationResult.ErrorMessage });
return this.ProblemResult(StatusCodes.Status400BadRequest, intervalValidationResult.ErrorMessage);
}
updatedRule.Validate();
@@ -183,16 +160,6 @@ public class QueueRulesController : ControllerBase
return Ok(updatedRule);
}
catch (ValidationException ex)
{
_logger.LogWarning("Validation failed for stall rule update: {Message}", ex.Message);
return BadRequest(new { Message = ex.Message });
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update stall rule with ID: {RuleId}", id);
return StatusCode(500, new { Message = "Failed to update stall rule", Error = ex.Message });
}
finally
{
DataContext.Lock.Release();
@@ -210,7 +177,7 @@ public class QueueRulesController : ControllerBase
if (existingRule == null)
{
return NotFound(new { Message = $"Stall rule with ID {id} not found" });
return this.ProblemResult(StatusCodes.Status404NotFound, $"Stall rule with ID {id} not found");
}
_dataContext.StallRules.Remove(existingRule);
@@ -220,11 +187,6 @@ public class QueueRulesController : ControllerBase
return NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to delete stall rule with ID: {RuleId}", id);
return StatusCode(500, new { Message = "Failed to delete stall rule", Error = ex.Message });
}
finally
{
DataContext.Lock.Release();
@@ -245,11 +207,6 @@ public class QueueRulesController : ControllerBase
return Ok(rules);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve slow rules");
return StatusCode(500, new { Message = "Failed to retrieve slow rules", Error = ex.Message });
}
finally
{
DataContext.Lock.Release();
@@ -259,11 +216,6 @@ public class QueueRulesController : ControllerBase
[HttpPost("slow")]
public async Task<IActionResult> CreateSlowRule([FromBody] SlowRuleDto ruleDto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
await DataContext.Lock.WaitAsync();
try
{
@@ -275,7 +227,7 @@ public class QueueRulesController : ControllerBase
if (existingRule != null)
{
return BadRequest(new { Message = "A slow rule with this name already exists" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "A slow rule with this name already exists");
}
var rule = new SlowRule
@@ -293,6 +245,7 @@ public class QueueRulesController : ControllerBase
MaxTimeHours = ruleDto.MaxTimeHours,
IgnoreAboveSize = ruleDto.IgnoreAboveSize,
DeletePrivateTorrentsFromClient = ruleDto.DeletePrivateTorrentsFromClient,
ChangeCategory = ruleDto.ChangeCategory,
};
var existingRules = await _dataContext.SlowRules.ToListAsync();
@@ -300,7 +253,7 @@ public class QueueRulesController : ControllerBase
var intervalValidationResult = _ruleIntervalValidator.ValidateSlowRuleIntervals(rule, existingRules);
if (!intervalValidationResult.IsValid)
{
return BadRequest(new { Message = intervalValidationResult.ErrorMessage });
return this.ProblemResult(StatusCodes.Status400BadRequest, intervalValidationResult.ErrorMessage);
}
rule.Validate();
@@ -312,16 +265,6 @@ public class QueueRulesController : ControllerBase
return CreatedAtAction(nameof(GetSlowRules), new { id = rule.Id }, rule);
}
catch (ValidationException ex)
{
_logger.LogWarning("Validation failed for slow rule creation: {Message}", ex.Message);
return BadRequest(new { Message = ex.Message });
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create slow rule: {RuleName}", ruleDto.Name);
return StatusCode(500, new { Message = "Failed to create slow rule", Error = ex.Message });
}
finally
{
DataContext.Lock.Release();
@@ -331,11 +274,6 @@ public class QueueRulesController : ControllerBase
[HttpPut("slow/{id}")]
public async Task<IActionResult> UpdateSlowRule(Guid id, [FromBody] SlowRuleDto ruleDto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
await DataContext.Lock.WaitAsync();
try
{
@@ -344,15 +282,15 @@ public class QueueRulesController : ControllerBase
if (existingRule == null)
{
return NotFound(new { Message = $"Slow rule with ID {id} not found" });
return this.ProblemResult(StatusCodes.Status404NotFound, $"Slow rule with ID {id} not found");
}
var duplicateRule = await _dataContext.SlowRules
.FirstOrDefaultAsync(r => r.Id != id && r.Name.ToLower() == ruleDto.Name.ToLower());
if (duplicateRule != null)
{
return BadRequest(new { Message = "A slow rule with this name already exists" });
return this.ProblemResult(StatusCodes.Status400BadRequest, "A slow rule with this name already exists");
}
var updatedRule = existingRule with
@@ -368,6 +306,7 @@ public class QueueRulesController : ControllerBase
MaxTimeHours = ruleDto.MaxTimeHours,
IgnoreAboveSize = ruleDto.IgnoreAboveSize,
DeletePrivateTorrentsFromClient = ruleDto.DeletePrivateTorrentsFromClient,
ChangeCategory = ruleDto.ChangeCategory,
};
var existingRules = await _dataContext.SlowRules
@@ -377,7 +316,7 @@ public class QueueRulesController : ControllerBase
var intervalValidationResult = _ruleIntervalValidator.ValidateSlowRuleIntervals(updatedRule, existingRules);
if (!intervalValidationResult.IsValid)
{
return BadRequest(new { Message = intervalValidationResult.ErrorMessage });
return this.ProblemResult(StatusCodes.Status400BadRequest, intervalValidationResult.ErrorMessage);
}
updatedRule.Validate();
@@ -389,16 +328,6 @@ public class QueueRulesController : ControllerBase
return Ok(updatedRule);
}
catch (ValidationException ex)
{
_logger.LogWarning("Validation failed for slow rule update: {Message}", ex.Message);
return BadRequest(new { Message = ex.Message });
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update slow rule with ID: {RuleId}", id);
return StatusCode(500, new { Message = "Failed to update slow rule", Error = ex.Message });
}
finally
{
DataContext.Lock.Release();
@@ -416,7 +345,7 @@ public class QueueRulesController : ControllerBase
if (existingRule == null)
{
return NotFound(new { Message = $"Slow rule with ID {id} not found" });
return this.ProblemResult(StatusCodes.Status404NotFound, $"Slow rule with ID {id} not found");
}
_dataContext.SlowRules.Remove(existingRule);
@@ -426,11 +355,6 @@ public class QueueRulesController : ControllerBase
return NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to delete slow rule with ID: {RuleId}", id);
return StatusCode(500, new { Message = "Failed to delete slow rule", Error = ex.Message });
}
finally
{
DataContext.Lock.Release();
@@ -0,0 +1,33 @@
using Cleanuparr.Domain.Enums;
using Cleanuparr.Persistence.Models.Configuration.Seeker;
namespace Cleanuparr.Api.Features.Seeker.Contracts.Requests;
public sealed record UpdateSeekerConfigRequest
{
public bool SearchEnabled { get; init; } = true;
public ushort SearchInterval { get; init; } = 3;
public bool ProactiveSearchEnabled { get; init; }
public SelectionStrategy SelectionStrategy { get; init; } = SelectionStrategy.BalancedWeighted;
public bool UseRoundRobin { get; init; } = true;
public int PostReleaseGraceHours { get; init; } = 6;
public List<UpdateSeekerInstanceConfigRequest> Instances { get; init; } = [];
public SeekerConfig ApplyTo(SeekerConfig config)
{
config.SearchEnabled = SearchEnabled;
config.SearchInterval = SearchInterval;
config.ProactiveSearchEnabled = ProactiveSearchEnabled;
config.SelectionStrategy = SelectionStrategy;
config.UseRoundRobin = UseRoundRobin;
config.PostReleaseGraceHours = PostReleaseGraceHours;
return config;
}
}
@@ -0,0 +1,20 @@
namespace Cleanuparr.Api.Features.Seeker.Contracts.Requests;
public sealed record UpdateSeekerInstanceConfigRequest
{
public Guid ArrInstanceId { get; init; }
public bool Enabled { get; init; } = true;
public List<string> SkipTags { get; init; } = [];
public int ActiveDownloadLimit { get; init; } = 3;
public int MinCycleTimeDays { get; init; } = 7;
public bool MonitoredOnly { get; init; } = true;
public bool UseCutoff { get; init; }
public bool UseCustomFormatScore { get; init; }
}
@@ -0,0 +1,26 @@
using Cleanuparr.Domain.Enums;
namespace Cleanuparr.Api.Features.Seeker.Contracts.Responses;
public sealed record CustomFormatScoreEntryResponse
{
public Guid Id { get; init; }
public Guid ArrInstanceId { get; init; }
public long ExternalItemId { get; init; }
public long EpisodeId { get; init; }
public InstanceType ItemType { get; init; }
public string Title { get; init; } = string.Empty;
public long FileId { get; init; }
public int CurrentScore { get; init; }
public int CutoffScore { get; init; }
public string QualityProfileName { get; init; } = string.Empty;
public bool IsBelowCutoff { get; init; }
public bool IsMonitored { get; init; }
public DateTimeOffset LastSyncedAt { get; init; }
/// <summary>
/// Timestamp at which this item last saw its custom format score strictly
/// exceed the prior recorded score. Null when no upgrade has been recorded.
/// </summary>
public DateTimeOffset? LastUpgradedAt { get; init; }
}
@@ -0,0 +1,8 @@
namespace Cleanuparr.Api.Features.Seeker.Contracts.Responses;
public sealed record CustomFormatScoreHistoryEntryResponse
{
public int Score { get; init; }
public int CutoffScore { get; init; }
public DateTimeOffset RecordedAt { get; init; }
}
@@ -0,0 +1,25 @@
namespace Cleanuparr.Api.Features.Seeker.Contracts.Responses;
public sealed record CustomFormatScoreStatsResponse
{
public int TotalTracked { get; init; }
public int BelowCutoff { get; init; }
public int AtOrAboveCutoff { get; init; }
public int Monitored { get; init; }
public int Unmonitored { get; init; }
public int RecentUpgrades { get; init; }
public List<InstanceCfScoreStat> PerInstanceStats { get; init; } = [];
}
public sealed record InstanceCfScoreStat
{
public Guid InstanceId { get; init; }
public string InstanceName { get; init; } = string.Empty;
public string InstanceType { get; init; } = string.Empty;
public int TotalTracked { get; init; }
public int BelowCutoff { get; init; }
public int AtOrAboveCutoff { get; init; }
public int Monitored { get; init; }
public int Unmonitored { get; init; }
public int RecentUpgrades { get; init; }
}
@@ -0,0 +1,16 @@
using Cleanuparr.Domain.Enums;
namespace Cleanuparr.Api.Features.Seeker.Contracts.Responses;
public sealed record CustomFormatScoreUpgradeResponse
{
public Guid ArrInstanceId { get; init; }
public long ExternalItemId { get; init; }
public long EpisodeId { get; init; }
public InstanceType ItemType { get; init; }
public string Title { get; init; } = string.Empty;
public int PreviousScore { get; init; }
public int NewScore { get; init; }
public int CutoffScore { get; init; }
public DateTimeOffset UpgradedAt { get; init; }
}
@@ -0,0 +1,16 @@
namespace Cleanuparr.Api.Features.Seeker.Contracts.Responses;
public sealed record InstanceSearchStat
{
public Guid InstanceId { get; init; }
public string InstanceName { get; init; } = string.Empty;
public string InstanceType { get; init; } = string.Empty;
public int ItemsTracked { get; init; }
public int TotalSearchCount { get; init; }
public DateTimeOffset? LastSearchedAt { get; init; }
public DateTimeOffset? LastProcessedAt { get; init; }
public Guid? CurrentCycleId { get; init; }
public int CycleItemsSearched { get; init; }
public int CycleItemsTotal { get; init; }
public DateTimeOffset? CycleStartedAt { get; init; }
}
@@ -0,0 +1,19 @@
using Cleanuparr.Domain.Enums;
namespace Cleanuparr.Api.Features.Seeker.Contracts.Responses;
public sealed record SearchEventResponse
{
public Guid Id { get; init; }
public DateTimeOffset Timestamp { get; init; }
public Guid? ArrInstanceId { get; init; }
public string? InstanceType { get; init; }
public string ItemTitle { get; init; } = string.Empty;
public SeekerSearchType SearchType { get; init; }
public SeekerSearchReason? SearchReason { get; init; }
public SearchCommandStatus? SearchStatus { get; init; }
public DateTimeOffset? CompletedAt { get; init; }
public List<string> GrabbedItems { get; init; } = [];
public Guid? CycleId { get; init; }
public bool IsDryRun { get; init; }
}
@@ -0,0 +1,12 @@
namespace Cleanuparr.Api.Features.Seeker.Contracts.Responses;
public sealed record SearchStatsSummaryResponse
{
public int TotalSearchesAllTime { get; init; }
public int SearchesLast7Days { get; init; }
public int SearchesLast30Days { get; init; }
public int UniqueItemsSearched { get; init; }
public int PendingReplacementSearches { get; init; }
public int EnabledInstances { get; init; }
public List<InstanceSearchStat> PerInstanceStats { get; init; } = [];
}
@@ -0,0 +1,20 @@
using Cleanuparr.Domain.Enums;
namespace Cleanuparr.Api.Features.Seeker.Contracts.Responses;
public sealed record SeekerConfigResponse
{
public bool SearchEnabled { get; init; }
public ushort SearchInterval { get; init; }
public bool ProactiveSearchEnabled { get; init; }
public SelectionStrategy SelectionStrategy { get; init; }
public bool UseRoundRobin { get; init; }
public int PostReleaseGraceHours { get; init; }
public List<SeekerInstanceConfigResponse> Instances { get; init; } = [];
}
@@ -0,0 +1,30 @@
using Cleanuparr.Domain.Enums;
namespace Cleanuparr.Api.Features.Seeker.Contracts.Responses;
public sealed record SeekerInstanceConfigResponse
{
public Guid ArrInstanceId { get; init; }
public string InstanceName { get; init; } = string.Empty;
public InstanceType InstanceType { get; init; }
public bool Enabled { get; init; }
public List<string> SkipTags { get; init; } = [];
public DateTimeOffset? LastProcessedAt { get; init; }
public bool ArrInstanceEnabled { get; init; }
public int ActiveDownloadLimit { get; init; }
public int MinCycleTimeDays { get; init; }
public bool MonitoredOnly { get; init; }
public bool UseCutoff { get; init; }
public bool UseCustomFormatScore { get; init; }
}
@@ -0,0 +1,505 @@
using Cleanuparr.Api.Features.Seeker.Contracts.Responses;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.State;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace Cleanuparr.Api.Features.Seeker.Controllers;
[ApiController]
[Route("api/seeker/cf-scores")]
[Authorize]
public sealed class CustomFormatScoreController : ControllerBase
{
private readonly DataContext _dataContext;
public CustomFormatScoreController(DataContext dataContext)
{
_dataContext = dataContext;
}
/// <summary>
/// Gets current CF scores with pagination, optionally filtered by instance.
/// </summary>
[HttpGet]
public async Task<IActionResult> GetCustomFormatScores(
[FromQuery] int page = 1,
[FromQuery] int pageSize = 50,
[FromQuery] Guid? instanceId = null,
[FromQuery] string? search = null,
[FromQuery] CfScoresSortBy sortBy = CfScoresSortBy.Title,
[FromQuery] SortDirection? sortDirection = null,
[FromQuery] string? qualityProfile = null,
[FromQuery] InstanceType? itemType = null,
[FromQuery] CutoffFilter cutoffFilter = CutoffFilter.All,
[FromQuery] MonitoredFilter monitoredFilter = MonitoredFilter.All)
{
if (page < 1)
{
page = 1;
}
if (pageSize < 1)
{
pageSize = 50;
}
if (pageSize > 500)
{
pageSize = 500;
}
var query = _dataContext.CustomFormatScoreEntries
.AsNoTracking()
.AsQueryable();
if (instanceId.HasValue)
{
query = query.Where(e => e.ArrInstanceId == instanceId.Value);
}
if (!string.IsNullOrWhiteSpace(search))
{
string pattern = EventsContext.GetLikePattern(search);
query = query.Where(e => EF.Functions.Like(e.Title, pattern));
}
if (!string.IsNullOrWhiteSpace(qualityProfile))
{
query = query.Where(e => e.QualityProfileName == qualityProfile);
}
if (itemType.HasValue)
{
InstanceType typeValue = itemType.Value;
query = query.Where(e => e.ItemType == typeValue);
}
switch (cutoffFilter)
{
case CutoffFilter.Below:
query = query.Where(e => e.CurrentScore < e.CutoffScore);
break;
case CutoffFilter.Met:
query = query.Where(e => e.CurrentScore >= e.CutoffScore);
break;
}
switch (monitoredFilter)
{
case MonitoredFilter.Monitored:
query = query.Where(e => e.IsMonitored);
break;
case MonitoredFilter.Unmonitored:
query = query.Where(e => !e.IsMonitored);
break;
}
int totalCount = await query.CountAsync();
bool ascending = sortDirection.HasValue
? sortDirection.Value == SortDirection.Asc
: DefaultAscendingForScoreSortBy(sortBy);
IOrderedQueryable<CustomFormatScoreEntry> ordered = sortBy switch
{
CfScoresSortBy.CurrentScore => ascending
? query.OrderBy(e => e.CurrentScore)
: query.OrderByDescending(e => e.CurrentScore),
CfScoresSortBy.CutoffScore => ascending
? query.OrderBy(e => e.CutoffScore)
: query.OrderByDescending(e => e.CutoffScore),
CfScoresSortBy.QualityProfile => ascending
? query.OrderBy(e => e.QualityProfileName)
: query.OrderByDescending(e => e.QualityProfileName),
CfScoresSortBy.LastSyncedAt => ascending
? query.OrderBy(e => e.LastSyncedAt)
: query.OrderByDescending(e => e.LastSyncedAt),
CfScoresSortBy.LastUpgradedAt => ascending
? query.OrderBy(e => e.LastUpgradedAt)
: query.OrderByDescending(e => e.LastUpgradedAt),
_ => ascending
? query.OrderBy(e => e.Title)
: query.OrderByDescending(e => e.Title),
};
var items = await ordered
.ThenBy(e => e.Id)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(e => new CustomFormatScoreEntryResponse
{
Id = e.Id,
ArrInstanceId = e.ArrInstanceId,
ExternalItemId = e.ExternalItemId,
EpisodeId = e.EpisodeId,
ItemType = e.ItemType,
Title = e.Title,
FileId = e.FileId,
CurrentScore = e.CurrentScore,
CutoffScore = e.CutoffScore,
QualityProfileName = e.QualityProfileName,
IsBelowCutoff = e.CurrentScore < e.CutoffScore,
IsMonitored = e.IsMonitored,
LastSyncedAt = e.LastSyncedAt,
LastUpgradedAt = e.LastUpgradedAt,
})
.ToListAsync();
return Ok(new
{
Items = items,
Page = page,
PageSize = pageSize,
TotalCount = totalCount,
TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize),
});
}
private static bool DefaultAscendingForScoreSortBy(CfScoresSortBy sortBy)
{
// Default directions match user expectations:
// - textual fields sort ascending (A→Z)
// - numeric/date fields sort descending (most recent / highest first)
return sortBy switch
{
CfScoresSortBy.CurrentScore => false,
CfScoresSortBy.CutoffScore => false,
CfScoresSortBy.LastSyncedAt => false,
CfScoresSortBy.LastUpgradedAt => false,
_ => true,
};
}
/// <summary>
/// Gets recent CF score upgrades (where score strictly exceeded the prior recorded score).
/// </summary>
/// <remarks>
/// Upgrade detection runs in SQL via <c>LAG()</c> over the full per-item history so
/// an improvement crossing the <paramref name="days"/> window boundary is still
/// detected. Sorting and pagination happen at the database level.
/// </remarks>
[HttpGet("upgrades")]
public async Task<IActionResult> GetRecentUpgrades(
[FromQuery] int page = 1,
[FromQuery] int pageSize = 50,
[FromQuery] Guid? instanceId = null,
[FromQuery] int days = 30,
[FromQuery] string? search = null,
[FromQuery] CfUpgradesSortBy sortBy = CfUpgradesSortBy.UpgradedAt,
[FromQuery] SortDirection? sortDirection = null)
{
if (page < 1) page = 1;
if (pageSize < 1) pageSize = 50;
if (pageSize > 500) pageSize = 500;
bool ascending = sortDirection.HasValue
? sortDirection.Value == SortDirection.Asc
: DefaultAscendingForUpgradeSortBy(sortBy);
string orderByClause = BuildUpgradeOrderByClause(sortBy, ascending);
DateTimeOffset? cutoff = days > 0 ? DateTimeOffset.UtcNow.AddDays(-days) : null;
string? searchPattern = string.IsNullOrWhiteSpace(search)
? null
: EventsContext.GetLikePattern(search);
const string upgradesCte =
"""
WITH scored AS (
SELECT
arr_instance_id,
external_item_id,
episode_id,
item_type,
title,
score,
cutoff_score,
recorded_at,
LAG(score) OVER (
PARTITION BY arr_instance_id, external_item_id, episode_id
ORDER BY recorded_at
) AS prev_score
FROM custom_format_score_history
),
upgrades AS (
SELECT
arr_instance_id AS arr_instance_id,
external_item_id AS external_item_id,
episode_id AS episode_id,
item_type AS item_type,
title AS title,
prev_score AS previous_score,
score AS new_score,
cutoff_score AS cutoff_score,
recorded_at AS upgraded_at
FROM scored
WHERE prev_score IS NOT NULL AND score > prev_score
)
""";
const string filterClause =
"""
WHERE (@instanceId IS NULL OR arr_instance_id = @instanceId)
AND (@search IS NULL OR title LIKE @search ESCAPE '\')
AND (@cutoff IS NULL OR upgraded_at >= @cutoff)
""";
SqliteParameter[] BuildCommonParameters() => new[]
{
new SqliteParameter("@instanceId", instanceId.HasValue ? instanceId.Value : DBNull.Value),
new SqliteParameter("@search", (object?)searchPattern ?? DBNull.Value),
new SqliteParameter("@cutoff", (object?)cutoff ?? DBNull.Value),
};
string listSql =
$"""
{upgradesCte}
SELECT * FROM upgrades
{filterClause}
ORDER BY {orderByClause}, upgraded_at DESC
LIMIT @take OFFSET @skip
""";
SqliteParameter[] listParams =
[
..BuildCommonParameters(),
new("@take", pageSize),
new("@skip", (page - 1) * pageSize),
];
var rows = await _dataContext.Database
.SqlQueryRaw<UpgradeSqlRow>(listSql, listParams)
.ToListAsync();
string countSql = $"{upgradesCte} SELECT COUNT(*) AS value FROM upgrades {filterClause}";
int totalCount = await _dataContext.Database
.SqlQueryRaw<int>(countSql, BuildCommonParameters())
.FirstAsync();
var paged = rows.Select(r => new CustomFormatScoreUpgradeResponse
{
ArrInstanceId = r.ArrInstanceId,
ExternalItemId = r.ExternalItemId,
EpisodeId = r.EpisodeId,
ItemType = Enum.Parse<InstanceType>(r.ItemType, ignoreCase: true),
Title = r.Title,
PreviousScore = r.PreviousScore,
NewScore = r.NewScore,
CutoffScore = r.CutoffScore,
UpgradedAt = r.UpgradedAt,
}).ToList();
return Ok(new
{
Items = paged,
Page = page,
PageSize = pageSize,
TotalCount = totalCount,
TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize),
});
}
private static bool DefaultAscendingForUpgradeSortBy(CfUpgradesSortBy sortBy)
{
return sortBy switch
{
CfUpgradesSortBy.Title => true,
_ => false,
};
}
private static string BuildUpgradeOrderByClause(CfUpgradesSortBy sortBy, bool ascending)
{
string column = sortBy switch
{
CfUpgradesSortBy.Title => "LOWER(title)",
CfUpgradesSortBy.NewScore => "new_score",
CfUpgradesSortBy.PreviousScore => "previous_score",
CfUpgradesSortBy.ScoreDelta => "(new_score - previous_score)",
CfUpgradesSortBy.CutoffScore => "cutoff_score",
_ => "upgraded_at",
};
return $"{column} {(ascending ? "ASC" : "DESC")}";
}
private sealed class UpgradeSqlRow
{
public Guid ArrInstanceId { get; set; }
public long ExternalItemId { get; set; }
public long EpisodeId { get; set; }
public string ItemType { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public int PreviousScore { get; set; }
public int NewScore { get; set; }
public int CutoffScore { get; set; }
public DateTimeOffset UpgradedAt { get; set; }
}
/// <summary>
/// Gets the *arr instances that currently have tracked CF scores, along with
/// the set of quality profile names observed for each instance. Used to
/// populate instance and profile filter controls.
/// </summary>
[HttpGet("instances")]
public async Task<IActionResult> GetInstances()
{
var raw = await _dataContext.CustomFormatScoreEntries
.AsNoTracking()
.Join(
_dataContext.ArrInstances.AsNoTracking(),
e => e.ArrInstanceId,
a => a.Id,
(e, a) => new
{
Id = e.ArrInstanceId,
a.Name,
e.ItemType,
e.QualityProfileName,
})
.Distinct()
.ToListAsync();
var instances = raw
.GroupBy(x => new { x.Id, x.Name, x.ItemType })
.Select(g => new
{
g.Key.Id,
g.Key.Name,
ItemType = g.Key.ItemType,
QualityProfiles = g
.Select(x => x.QualityProfileName)
.Where(n => !string.IsNullOrWhiteSpace(n))
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(n => n, StringComparer.OrdinalIgnoreCase)
.ToList(),
})
.OrderBy(x => x.Name)
.ToList();
return Ok(new { Instances = instances });
}
/// <summary>
/// Gets summary statistics for CF score tracking.
/// </summary>
[HttpGet("stats")]
public async Task<IActionResult> GetStats()
{
var entries = await _dataContext.CustomFormatScoreEntries
.AsNoTracking()
.ToListAsync();
int totalTracked = entries.Count;
int belowCutoff = entries.Count(e => e.CurrentScore < e.CutoffScore);
int atOrAboveCutoff = totalTracked - belowCutoff;
int monitored = entries.Count(e => e.IsMonitored);
int unmonitored = totalTracked - monitored;
// Count upgrades in the last 7 days
var sevenDaysAgo = DateTimeOffset.UtcNow.AddDays(-7);
var recentHistory = await _dataContext.CustomFormatScoreHistory
.AsNoTracking()
.Where(h => h.RecordedAt >= sevenDaysAgo)
.OrderBy(h => h.RecordedAt)
.ToListAsync();
int recentUpgrades = 0;
var recentGrouped = recentHistory
.GroupBy(h => new { h.ArrInstanceId, h.ExternalItemId, h.EpisodeId });
foreach (var group in recentGrouped)
{
var ordered = group.OrderBy(h => h.RecordedAt).ToList();
for (int i = 1; i < ordered.Count; i++)
{
if (ordered[i].Score > ordered[i - 1].Score)
recentUpgrades++;
}
}
// Per-instance stats
var instanceIds = entries.Select(e => e.ArrInstanceId).Distinct().ToList();
var instances = await _dataContext.ArrInstances
.AsNoTracking()
.Include(a => a.ArrConfig)
.Where(a => instanceIds.Contains(a.Id))
.ToListAsync();
var perInstanceStats = instanceIds.Select(instanceId =>
{
var instanceEntries = entries.Where(e => e.ArrInstanceId == instanceId).ToList();
int instTracked = instanceEntries.Count;
int instBelow = instanceEntries.Count(e => e.CurrentScore < e.CutoffScore);
int instMonitored = instanceEntries.Count(e => e.IsMonitored);
int instUpgrades = 0;
var instHistory = recentGrouped
.Where(g => g.Key.ArrInstanceId == instanceId);
foreach (var group in instHistory)
{
var ordered = group.OrderBy(h => h.RecordedAt).ToList();
for (int i = 1; i < ordered.Count; i++)
{
if (ordered[i].Score > ordered[i - 1].Score)
instUpgrades++;
}
}
var instance = instances.FirstOrDefault(a => a.Id == instanceId);
return new InstanceCfScoreStat
{
InstanceId = instanceId,
InstanceName = instance?.Name ?? "Unknown",
InstanceType = instance?.ArrConfig.Type.ToString() ?? "Unknown",
TotalTracked = instTracked,
BelowCutoff = instBelow,
AtOrAboveCutoff = instTracked - instBelow,
Monitored = instMonitored,
Unmonitored = instTracked - instMonitored,
RecentUpgrades = instUpgrades,
};
}).OrderBy(s => s.InstanceName).ToList();
return Ok(new CustomFormatScoreStatsResponse
{
TotalTracked = totalTracked,
BelowCutoff = belowCutoff,
AtOrAboveCutoff = atOrAboveCutoff,
Monitored = monitored,
Unmonitored = unmonitored,
RecentUpgrades = recentUpgrades,
PerInstanceStats = perInstanceStats,
});
}
/// <summary>
/// Gets CF score history for a specific item.
/// </summary>
[HttpGet("{instanceId}/{itemId}/history")]
public async Task<IActionResult> GetItemHistory(
Guid instanceId,
long itemId,
[FromQuery] long episodeId = 0)
{
var history = await _dataContext.CustomFormatScoreHistory
.AsNoTracking()
.Where(h => h.ArrInstanceId == instanceId
&& h.ExternalItemId == itemId
&& h.EpisodeId == episodeId)
.OrderByDescending(h => h.RecordedAt)
.Select(h => new CustomFormatScoreHistoryEntryResponse
{
Score = h.Score,
CutoffScore = h.CutoffScore,
RecordedAt = h.RecordedAt,
})
.ToListAsync();
return Ok(new { Entries = history });
}
}
@@ -0,0 +1,295 @@
using Cleanuparr.Api.Features.Seeker.Contracts.Responses;
using Cleanuparr.Domain.Enums;
using Cleanuparr.Persistence;
using Cleanuparr.Persistence.Models.Configuration.Seeker;
using Cleanuparr.Persistence.Models.State;
using AppEvent = Cleanuparr.Persistence.Models.Events.AppEvent;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Cleanuparr.Api.Features.Seeker.Controllers;
[ApiController]
[Route("api/seeker/search-stats")]
[Authorize]
public sealed class SearchStatsController : ControllerBase
{
private readonly DataContext _dataContext;
private readonly EventsContext _eventsContext;
public SearchStatsController(DataContext dataContext, EventsContext eventsContext)
{
_dataContext = dataContext;
_eventsContext = eventsContext;
}
/// <summary>
/// Gets aggregate search statistics across all instances.
/// </summary>
[HttpGet("summary")]
public async Task<IActionResult> GetSummary()
{
DateTimeOffset sevenDaysAgo = DateTimeOffset.UtcNow.AddDays(-7);
DateTimeOffset thirtyDaysAgo = DateTimeOffset.UtcNow.AddDays(-30);
// Event counts from EventsContext
var searchEvents = _eventsContext.Events
.AsNoTracking()
.Where(e => e.EventType == EventType.SearchTriggered);
int totalSearchesAllTime = await searchEvents.CountAsync();
int searchesLast7Days = await searchEvents.CountAsync(e => e.Timestamp >= sevenDaysAgo);
int searchesLast30Days = await searchEvents.CountAsync(e => e.Timestamp >= thirtyDaysAgo);
// History stats from DataContext
int uniqueItemsSearched = await _dataContext.SeekerHistory
.AsNoTracking()
.Select(h => h.ExternalItemId)
.Distinct()
.CountAsync();
int pendingReplacementSearches = await _dataContext.SearchQueue.CountAsync();
// Per-instance stats
List<SeekerInstanceConfig> instanceConfigs = await _dataContext.SeekerInstanceConfigs
.AsNoTracking()
.Include(s => s.ArrInstance)
.ThenInclude(a => a.ArrConfig)
.Where(s => s.Enabled && s.ArrInstance.Enabled)
.ToListAsync();
var historyByInstance = await _dataContext.SeekerHistory
.AsNoTracking()
.GroupBy(h => h.ArrInstanceId)
.Select(g => new
{
InstanceId = g.Key,
ItemsTracked = g.Select(h => h.ExternalItemId).Distinct().Count(),
LastSearchedAt = g.Max(h => h.LastSearchedAt),
TotalSearchCount = g.Sum(h => h.SearchCount),
})
.ToListAsync();
// Count items searched in current cycle per instance
List<Guid> currentCycleIds = instanceConfigs.Select(ic => ic.CurrentCycleId).ToList();
var cycleItemsByInstance = await _dataContext.SeekerHistory
.AsNoTracking()
.Where(h => currentCycleIds.Contains(h.CycleId))
.GroupBy(h => h.ArrInstanceId)
.Select(g => new
{
InstanceId = g.Key,
CycleItemsSearched = g.Select(h => h.ExternalItemId).Distinct().Count(),
CycleStartedAt = (DateTimeOffset?)g.Min(h => h.LastSearchedAt),
})
.ToListAsync();
var perInstanceStats = instanceConfigs.Select(ic =>
{
var history = historyByInstance.FirstOrDefault(h => h.InstanceId == ic.ArrInstanceId);
var cycleProgress = cycleItemsByInstance.FirstOrDefault(c => c.InstanceId == ic.ArrInstanceId);
return new InstanceSearchStat
{
InstanceId = ic.ArrInstanceId,
InstanceName = ic.ArrInstance.Name,
InstanceType = ic.ArrInstance.ArrConfig.Type.ToString(),
ItemsTracked = history?.ItemsTracked ?? 0,
TotalSearchCount = history?.TotalSearchCount ?? 0,
LastSearchedAt = history?.LastSearchedAt,
LastProcessedAt = ic.LastProcessedAt,
CurrentCycleId = ic.CurrentCycleId,
CycleItemsSearched = cycleProgress?.CycleItemsSearched ?? 0,
CycleItemsTotal = ic.TotalEligibleItems,
CycleStartedAt = cycleProgress?.CycleStartedAt,
};
}).ToList();
return Ok(new SearchStatsSummaryResponse
{
TotalSearchesAllTime = totalSearchesAllTime,
SearchesLast7Days = searchesLast7Days,
SearchesLast30Days = searchesLast30Days,
UniqueItemsSearched = uniqueItemsSearched,
PendingReplacementSearches = pendingReplacementSearches,
EnabledInstances = instanceConfigs.Count,
PerInstanceStats = perInstanceStats,
});
}
/// <summary>
/// Gets paginated search-triggered events with optional filtering and sorting.
/// Results default to newest-first by timestamp. Ties on non-timestamp sort keys
/// fall back to <c>Timestamp</c> descending for stable ordering.
/// </summary>
/// <param name="page">1-based page number. Clamped to at least 1.</param>
/// <param name="pageSize">Rows per page. Clamped to the inclusive range [1, 100]; defaults to 50.</param>
/// <param name="instanceId">When set, restricts results to events produced by this *arr instance.</param>
/// <param name="cycleId">When set, restricts results to events from this seeker cycle.</param>
/// <param name="search">Case-insensitive substring match against the stored item title.</param>
/// <param name="sortBy">Primary sort column. Defaults to <see cref="SearchEventsSortBy.Timestamp"/>.</param>
/// <param name="sortDirection">Sort direction for the primary column. Defaults to descending.</param>
/// <param name="searchStatus">When supplied, keeps only events whose <see cref="SearchCommandStatus"/> appears in this list.</param>
/// <param name="searchType">When supplied, keeps only events matching this <see cref="SeekerSearchType"/>.</param>
/// <param name="searchReason">When supplied, keeps only events matching this <see cref="SeekerSearchReason"/>.</param>
/// <param name="grabbed">When <c>true</c>, keeps only events that recorded at least one grabbed item; when <c>false</c>, keeps only events with none.</param>
[HttpGet("events")]
public async Task<IActionResult> GetEvents(
[FromQuery] int page = 1,
[FromQuery] int pageSize = 50,
[FromQuery] Guid? instanceId = null,
[FromQuery] Guid? cycleId = null,
[FromQuery] string? search = null,
[FromQuery] SearchEventsSortBy sortBy = SearchEventsSortBy.Timestamp,
[FromQuery] SortDirection sortDirection = SortDirection.Desc,
[FromQuery] SearchCommandStatus[]? searchStatus = null,
[FromQuery] SeekerSearchType? searchType = null,
[FromQuery] SeekerSearchReason? searchReason = null,
[FromQuery] bool? grabbed = null)
{
if (page < 1)
{
page = 1;
}
if (pageSize < 1)
{
pageSize = 50;
}
if (pageSize > 500)
{
pageSize = 500;
}
var query = _eventsContext.Events
.AsNoTracking()
.Include(e => e.SearchEventData)
.Where(e => e.EventType == EventType.SearchTriggered);
// Filter by instance ID
if (instanceId.HasValue)
{
query = query.Where(e => e.ArrInstanceId == instanceId.Value);
}
// Filter by cycle ID
if (cycleId.HasValue)
{
query = query.Where(e => e.CycleId == cycleId.Value);
}
// Search by item title in SearchEventData
if (!string.IsNullOrWhiteSpace(search))
{
string pattern = EventsContext.GetLikePattern(search);
query = query.Where(e => e.SearchEventData != null
&& EF.Functions.Like(e.SearchEventData.ItemTitle, pattern));
}
// Filter by search status (multi-valued)
if (searchStatus is { Length: > 0 })
{
SearchCommandStatus[] statuses = searchStatus.Distinct().ToArray();
query = query.Where(e => e.SearchStatus.HasValue && statuses.Contains(e.SearchStatus.Value));
}
if (searchType.HasValue)
{
SeekerSearchType typeValue = searchType.Value;
query = query.Where(e => e.SearchEventData != null && e.SearchEventData.SearchType == typeValue);
}
if (searchReason.HasValue)
{
SeekerSearchReason reasonValue = searchReason.Value;
query = query.Where(e => e.SearchEventData != null && e.SearchEventData.SearchReason == reasonValue);
}
// Filter by grabbed-result presence
if (grabbed.HasValue)
{
if (grabbed.Value)
{
query = query.Where(e => e.SearchEventData != null && e.SearchEventData.GrabbedItems.Count > 0);
}
else
{
query = query.Where(e => e.SearchEventData == null || e.SearchEventData.GrabbedItems.Count == 0);
}
}
int totalCount = await query.CountAsync();
bool ascending = sortDirection == SortDirection.Asc;
IOrderedQueryable<AppEvent> ordered = sortBy switch
{
SearchEventsSortBy.Title => ascending
? query.OrderBy(e => e.SearchEventData != null ? e.SearchEventData.ItemTitle : string.Empty)
: query.OrderByDescending(e => e.SearchEventData != null ? e.SearchEventData.ItemTitle : string.Empty),
SearchEventsSortBy.Status => ascending
? query.OrderBy(e => e.SearchStatus)
: query.OrderByDescending(e => e.SearchStatus),
SearchEventsSortBy.Type => ascending
? query.OrderBy(e => e.SearchEventData != null ? (int)e.SearchEventData.SearchType : 0)
: query.OrderByDescending(e => e.SearchEventData != null ? (int)e.SearchEventData.SearchType : 0),
_ => ascending
? query.OrderBy(e => e.Timestamp)
: query.OrderByDescending(e => e.Timestamp),
};
// Secondary sort by timestamp desc for stable ordering when primary ties
if (sortBy != SearchEventsSortBy.Timestamp)
{
ordered = ordered.ThenByDescending(e => e.Timestamp);
}
var rawEvents = await ordered
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
// Resolve instance types from DataContext via ArrInstanceId
var arrInstanceIds = rawEvents
.Where(e => e.ArrInstanceId.HasValue)
.Select(e => e.ArrInstanceId!.Value)
.Distinct()
.ToList();
var instanceTypeMap = arrInstanceIds.Count > 0
? await _dataContext.ArrInstances
.AsNoTracking()
.Include(a => a.ArrConfig)
.Where(a => arrInstanceIds.Contains(a.Id))
.ToDictionaryAsync(a => a.Id, a => a.ArrConfig.Type)
: new Dictionary<Guid, InstanceType>();
var items = rawEvents.Select(e => new SearchEventResponse
{
Id = e.Id,
Timestamp = e.Timestamp,
ArrInstanceId = e.ArrInstanceId,
InstanceType = e.ArrInstanceId.HasValue && instanceTypeMap.TryGetValue(e.ArrInstanceId.Value, out var it)
? it.ToString()
: null,
ItemTitle = e.SearchEventData?.ItemTitle ?? "Unknown",
SearchType = e.SearchEventData?.SearchType ?? SeekerSearchType.Proactive,
SearchReason = e.SearchEventData?.SearchReason,
SearchStatus = e.SearchStatus,
CompletedAt = e.CompletedAt,
GrabbedItems = e.SearchEventData?.GrabbedItems ?? [],
CycleId = e.CycleId,
IsDryRun = e.IsDryRun,
}).ToList();
return Ok(new
{
Items = items,
Page = page,
PageSize = pageSize,
TotalCount = totalCount,
TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize),
});
}
}
Loaded 100 of 744 files, more files were not shown because too many files have changed in this diff. Show more