Status: ✅ Implemented
Admin feature for deleting requests with intelligent cleanup of media files and torrents.
Allows admins to delete requests from the admin dashboard with smart handling of:
- Soft deletion (allows re-requesting)
- Media file cleanup
- Torrent seeding management
- Orphaned download tracking
- Soft Delete - Preserves request history, allows re-requesting
- 1:1 Request-to-Files - No duplicate requests for same audiobook
- Seeding Awareness - Keeps torrents seeding until requirements met
- Confirmation Dialog - Prevents accidental deletions
- Automatic Cleanup - Scheduled job handles orphaned downloads
- Navigate to Admin Dashboard → Recent Requests table
- Click "Delete" button next to request
- Review confirmation dialog with details:
- Request title
- Actions that will be taken
- Warning about re-requesting
- Click "Delete" to confirm or "Cancel" to abort
- Request deleted, UI updates automatically
Soft Delete Fields:
model Request {
// ... existing fields ...
deletedAt DateTime? @map("deleted_at")
deletedBy String? @map("deleted_by")
}Unique Constraint: Removed from schema, enforced in application code
Service: src/lib/services/request-delete.service.ts
Steps:
-
Find Request
- Query:
deletedAt: null - Return 404 if not found or already deleted
- Query:
-
Handle Downloads & Seeding
For each selected download:
IF torrent not in qBittorrent: → Skip (already removed) ELSE IF unlimited seeding (no indexer config, or seedingTimeMinutes AND ratioLimit both 0): → Log: "Keeping for unlimited seeding" → Do nothing (stop monitoring) → torrentsKeptUnlimited++ ELSE IF download not completed, OR evaluateSeeding(config, {seedingTime, ratio}).met: (src/lib/utils/seeding-policy.ts, same rule as cleanup_seeded_torrents: every set limit met; 0 turns a limit off; unreported ratio with ratioLimit > 0 = not met) IF another active request uses the same torrentHash (otherActiveRequestsUsingTorrent, src/lib/utils/shared-torrent.ts, shared with the cleanup job): → Keep torrent → torrentsKeptShared++ ELSE: → Delete torrent + files → torrentsRemoved++ ELSE (still seeding): → Log: "Keeping ... to finish seeding: ratio a/b, time x/y min" → torrentsKeptSeeding++ (cleanup job removes it later) -
Library Delete Guard (
src/lib/utils/library-delete-guard.ts, run fromsrc/lib/services/request-delete-files.ts)- Path: persisted
Audiobook.filePathonly (never rebuilt frommedia_diror a template) - The stored folder is removed (
rm -rf) only when ALL hold, else nothing is removed:Rule Refusal reason ( filesKeptReason)a. strictly inside media_dirit is the media library root/it is outside the media library (...)b. equals/contains no configured root (download dirs, client paths, mapped paths, /bookdrop)it is a configured root (...)/it contains a configured root (...)c. equals/contains no other book's filePath(each row canonicalized: realpath + dev/ino; missing rows skipped)it is also the folder of "<title>"/it contains the folder of "<title>"evidence: audio directly in the folder hashes to filesHashfolder contents changed since import/there is no import record (files hash) for this folderevidence: no audio in any subfolder (the removal is recursive) it has audio files in a subfolder - Roots are read strictly from the DB (
collectGuardRoots, fail closed: any error refuses) - Symlinked title folder: rules a-c on the target AND the link location; only the link is removed
- No stored path but a library item (
absItemId/plexGuid): kept (RMAB has no stored folder ...); no path and no item: nothing to remove - Missing folder: "already gone" only when the library looks mounted (
media_dirreadable and not empty, and some other stored book folder exists when other rows have one); otherwise kept (the folder is missing and ... is the media volume mounted?): no backend call, row untouched (protects against a media volume not mounted yet) - Mount-check limit: a mount point that received new imports while the share was unmounted is not empty, so it passes; a missing folder there then counts as gone (no Plex delete; ABS
hard=0only for an item inside that path; row cleared) - Stale record: the stored folder is gone AND outside the current
media_dir(library moved): nothing removed or protected; the delete clears onlyfilePath/filesHash/fileFormat(no backend call, records and status kept; message says so), a replace goes on rmfailure: kept (the folder was partly removed (permission denied); remove the rest manually);fs.rmstops at the first error, so earlier files are gone; backend and row untouched- After removal: empty parents swept up to the nearest root (
sweepEmptyParents) - Ebook requests (D2): rules a-c on
filePath, then unlink every ebook file directly in it if the folder passes the evidence rule, or the only one if it holds exactly one; otherwise kept (it holds N ebook files and is not provably this book's folder (...)). A shared{author}or flatEbooksfolder fails rule c when another book points at it. Never a sweep of other books' ebooks - Not handled (needs a separate ebook location, PR2): an ebook in a separate folder (custom
ebook_path_template) is not removed by the audiobook delete
- Path: persisted
-
Files kept: library left exactly as it is
- No backend delete, no plex_library cleanup, no status reset, linkage and stored paths kept
- Request still soft-deleted; result
filesDeleted: false,filesKeptReason, messageRequest deleted; files kept: <reason>
-
Backend item (only after RMAB removed the folder, or found it already gone)
- Audiobookshelf:
DELETE /api/items/<id>?hard=0(database entry only; RMAB already removed the files), only when the item'spathis inside the removed folder, or itsrelPathmatches the folder's path relative tomedia_dir(ABS mounting the library elsewhere). Otherwise skipped (a second copy elsewhere survives). TherelPathmatch can also hit the same relative path in another ABS library folder; withhard=0only that item's database entry goes (the next ABS scan re-adds it) - Plex:
DELETE /library/metadata/{ratingKey}only after RMAB removed the folder itself, and only when every file Plex lists for the item and its tracks (getItemFilePaths: Media > Partfile) is inside it; otherwise (incl. a folder that was already gone) skipped, the next library scan drops it deleteABSItem(id, { hard }):hard: true(?hard=1) also deletes files; only a replace of a book added outside RMAB (no request, no stored folder;replace-library-content.ts) uses it
- Audiobookshelf:
-
plex_library records, linkage, stored paths (only after removal / already gone)
- plex_library delete by ASIN, fallback exact title/author
- Audiobook:
status = 'requested', clearabsItemId(ABS) orplexGuid(Plex), clearfilePath,filesHash,fileFormat - Child requests soft-deleted:
parentRequestId = id, and ebook requests with no parent on the same book row
-
Soft Delete Request
- UPDATE:
deletedAt = NOW(), deletedBy = adminUserId - Preserves for audit trail and orphaned download tracking
- UPDATE:
Processor: src/lib/processors/cleanup-seeded-torrents.processor.ts
Query: Finds both active + soft-deleted requests
where: {
OR: [
{ status: ['available', 'downloaded'], deletedAt: null },
{ deletedAt: { not: null } }
]
}Behavior:
- Active requests: Delete torrent when seeding complete
- Soft-deleted requests: Delete torrent + hard-delete request when seeding complete
- Unlimited seeding: Hard-delete orphaned request immediately (no monitoring)
DELETE /api/admin/requests/:id
Authorization: Admin only
Request: No body
Response:
{
"success": true,
"message": "Request deleted successfully",
"details": {
"filesDeleted": true,
"torrentsRemoved": 2,
"torrentsKeptSeeding": 1,
"torrentsKeptUnlimited": 0,
"torrentsKeptShared": 0,
"filesKeptReason": "folder contents changed since import"
}
}filesKeptReasonpresent only when library files were kept; the request is still deleted (HTTP 200)
Errors:
- 401: Unauthorized (not logged in)
- 403: Forbidden (not admin)
- 404: Request not found or already deleted
- 500: Internal server error
ConfirmDialog (src/app/admin/components/ConfirmDialog.tsx)
- Reusable confirmation modal
- Props: title, message, confirmLabel, confirmVariant
- Supports danger (red) and primary (blue) variants
RecentRequestsTable (src/app/admin/components/RecentRequestsTable.tsx)
- Added "Actions" column with Delete button
- State management for confirmation dialog
- SWR cache invalidation after deletion
- Loading states during deletion
- Files kept: warning toast
Request deleted; files kept: <reason>(10 s) instead of the success toast
Application-Level Uniqueness:
All prisma.request.findMany/findFirst queries include:
where: {
// ... other conditions
deletedAt: null // Only active requests
}Re-Request Flow:
- User requests audiobook previously deleted
- Query checks for existing request:
deletedAt: null - No active request found → allowed to create new request
- Old soft-deleted request remains in DB for audit
- ✅ Torrent not in qBittorrent - Skip deletion, continue with files
- ✅ Unlimited seeding (time and ratio both 0, or no config) - Keep in qBittorrent, hard-delete orphaned request
- ✅ Incomplete download - Delete torrent + files immediately
- ✅ Seeding requirement met - Delete torrent + files
- ✅ Still seeding - Keep torrent, soft-delete request, cleanup job handles later
- ✅ Media folder not found - Log and continue (already deleted)
- ✅ Multiple delete clicks - Button disabled during deletion
- ✅ Network error - Alert shown, request remains
- ✅ ABS library item deletion fails - Log error, continue with soft delete
- ✅ No absItemId present - Skip ABS deletion (not yet in library)
- ✅ Plex library item deletion fails - Log error, continue with soft delete
- ✅ No plexGuid present - Skip Plex deletion (not yet in library)
- ✅ Plex deletion not enabled in settings - Log error, continue with soft delete
- ✅ Title mismatch in plex_library - ASIN-based deletion handles title variations (e.g., "(Unabridged)" suffix)
- ✅ No ASIN available - Falls back to exact title/author matching
- ✅ Path template changed after organization - Deletes only the persisted organized path
- ✅ Legacy row has no stored path - Skips file deletion without guessing a path
- ✅ Folder shared with other books, foreign files, symlinks, roots - Library delete guard keeps the files and says why
- ✅ Reported-issue replace when files would be kept -
replaceAudiobookstops with HTTP 409 and the reason before deleting anything (and again ifdeleteRequestkept files); no record reset, no new request, issue stays open - ✅ Replace with no active request but a stored folder (an earlier delete kept the files) -
removeLibraryContentForReplace: the folder goes through the guard (409 when kept), backend item as in step 5; never an ABS hard delete - ✅ Replace after a library move - stale stored folder (gone, outside
media_dir): no backend call, the replace resets the stored path and continues - ✅ Replace that keeps refusing (e.g. a legacy row whose stored folder is shared with other books): every 409 names the way out: "Remove those files manually, then re-request the book after the next library scan."
- ✅ ABS hard delete for a book added outside RMAB (no stored folder, item looked up by ASIN in plex_library): refused when more than one library item matches the ASIN
1. Book Shows "Available" After Deletion Until Library Scan
- Issue: Deleted books remained "available" until the next library scan
- Cause: plex_library deletion used title/author matching, but availability check used ASIN matching
- Impact: Title variations (e.g., "Book Title" vs "Book Title (Unabridged)") caused plex_library records to persist
- Fix: Changed plex_library deletion to use ASIN-based matching (same as availability check)
- Result: Books immediately show as NOT available after deletion, can be re-requested right away
2. Changed Path Template Deletes an Unrelated Directory
- Issue: Deletion rebuilt a directory from the current media path and template
- Cause:
Audiobook.filePathwas persisted during organization but omitted from the deletion query - Fix: Delete only the persisted path; legacy rows without one skip file cleanup
- Result: Configuration changes cannot redirect deletion to a newly rendered directory
3. Deleting a Request Removed Other Books' Files
- Issue:
fs.rm(filePath, { recursive })with no checks; an ebook import overwrotefilePathwith its folder ({author}or flatEbookstemplates), and the ebook delete unlinked every ebook in that folder. ABS deletes always senthard=1 - Fix: library delete guard (rules a-c + evidence); backend deletes only after RMAB removed the folder, ABS with
hard=0, Plex only for items inside the folder - Note:
filesHashcovers file names only (a same-named replacement passes); it is built from this import's audio after format coercion, excluding files the library already held with different content (differs)
4. Deletion Ignored the Indexer Ratio Limit
- Issue: Deleting a request removed a torrent once its seeding time was met even when its ratio limit was not; a ratio-only indexer (
seedingTimeMinutes: 0) was treated as unlimited and kept forever - Cause: request deletion had its own time-only check; the scheduled cleanup already used time AND ratio
- Fix: both use
evaluateSeeding()(src/lib/utils/seeding-policy.ts) - Also (rename): settings were found by indexer name, so a rename in Prowlarr made the torrent "unlimited"; both now match by
indexerIdfirst, name as fallback - Also: deletion now skips removing a torrent another active request still uses (
otherActiveRequestsUsingTorrent(), same check as the cleanup job). Behaviour change: a ratio-only indexer's incomplete download is removed on delete (it was kept forever as "unlimited")
Backend:
- prisma/schema.prisma (deletedAt, deletedBy fields)
- src/lib/services/request-delete.service.ts (deletion logic)
- src/lib/services/request-delete-files.ts (library files, backend items, plex_library records)
- src/lib/utils/library-delete-guard.ts (assertSafeLibraryDelete, planEbookDelete)
- src/lib/services/replace-library-content.ts (replace with no active request)
- src/app/api/admin/requests/[id]/route.ts (DELETE endpoint)
- src/lib/processors/cleanup-seeded-torrents.processor.ts (orphaned cleanup)
Frontend:
- src/app/admin/components/ConfirmDialog.tsx (confirmation modal)
- src/app/admin/components/RecentRequestsTable.tsx (Delete button + logic)
Queries Updated (deletedAt: null filters):
- src/app/api/requests/route.ts (GET, POST)
- src/app/api/requests/[id]/route.ts (GET, PATCH)
- src/app/api/admin/requests/recent/route.ts (GET)
- src/app/api/admin/metrics/route.ts (GET)
- src/app/api/admin/downloads/active/route.ts (GET)
- src/lib/processors/*.ts (all processors)
No new config required - uses existing:
prowlarr_indexers(per indexerseedingTimeMinutesandratioLimit), matched to the download by Prowlarr indexer id, else by name (findIndexerConfig(); the id is ignored when the recorded name is another configured indexer or the id's indexer has another protocol). Not a JSON list → the download is left in the client
- Authorization: Admin role required
- Audit Trail:
deletedBytracks admin user ID - Soft Delete: Preserves history, prevents permanent data loss
- Confirmation Required: Prevents accidental deletion
- Stored Path Only: File cleanup targets the path recorded by the organizer; no template-based fallback
Logs:
[RequestDelete]prefix for deletion service[CleanupSeededTorrents]prefix for cleanup job- Torrent status (removed/kept/unlimited)
- File deletion success/failure
- Orphaned request hard deletion
Admin Dashboard:
- Request count updates after deletion
- Recent requests table refreshes automatically
- Toast notifications (via console.log - can be enhanced)
- Toast notifications instead of console.log
- Deletion history view (soft-deleted requests)
- Bulk delete operations
- Restore deleted requests (undo)
- Email notifications for deletions
- Deletion reason/notes field
- Admin Dashboard - Dashboard overview
- Scheduler - Cleanup job details
- File Organization - Media directory structure
- qBittorrent - Torrent management