Compare commits

..

19 Commits

Author SHA1 Message Date
kikootwo 2972297903 Bump package version to 1.0.12
Update package.json version from 1.0.11 to 1.0.12 to publish a new patch release. No other changes were made in this commit.
2026-02-25 11:20:43 -05:00
kikootwo 03f82d4841 File rename templates & admin torrent approval
Add support for admin-driven interactive torrent selection and a file rename/template feature. Integrates an InteractiveTorrentSearchModal into the pending-approval admin UI, adds an admin approve flow that accepts an admin-selected torrent, and surfaces user/admin-selected torrent details in the UI. Introduces fileRenameEnabled and fileRenameTemplate settings (API + UI), persists them to configuration, and clears related caches. Pass renameConfig through the organize/organizeEbook flows and implement renaming in the FileOrganizer (single/multi-file handling). Enhance path-template utilities with conditional block resolution, filename-template validation, mock filename previews, and a buildRenamedFilename helper. Update tests to cover conditional templates and filename preview behavior.
2026-02-25 09:47:57 -05:00
kikootwo 33c2265e56 Use save_path for completed/seeding torrents
Resolve downloadPath using save_path for finished torrents to avoid TempPathEnabled race conditions where content_path can point to a stale temp location. Compute status once, treat 'seeding'/'completed' as finished, and prefer path.join(save_path, name) for those states while still using content_path (or falling back to save_path) for active downloads. Added tests covering multiple qBittorrent states (seeding/stalledUP/pausedUP/stoppedUP/forcedUP/queuedUP/downloading and empty content_path) and imported path in tests.
2026-02-24 02:03:20 -05:00
kikootwo b15a472bab Centralize download client timeout constant
Add DOWNLOAD_CLIENT_TIMEOUT (60000ms) in src/lib/constants/download-timeouts.ts and replace hardcoded 60000ms timeouts across Deluge, Prowlarr, qBittorrent and Transmission integrations. This centralizes the download/API timeout (gives headroom for indexers that enforce ~30s waits) and makes future adjustments easier without changing behavior.
2026-02-24 01:09:58 -05:00
kikootwo 3c680f2f38 Merge pull request #102 from Kikipeuk/ygg_timeout2
Extend the default timeout to add a torrent (Qbit, Transmission, Deluge)
2026-02-24 00:56:37 -05:00
kikootwo 16cd606421 Merge pull request #107 from kikootwo/feature-france-region
Feature france region
2026-02-24 00:53:01 -05:00
kikootwo 40d5363dc4 Fix French stopWords spacing and region name
Trim whitespace in the French stopWords array (add missing space after comma) to keep formatting consistent, and rename AUDIBLE_REGIONS.fr.name from "French" to "France" to better reflect the region label used for the Audible configuration.
2026-02-24 00:51:55 -05:00
kikootwo c138d8e642 Merge pull request #100 from Kikipeuk/french-traduction
Add French as Audible region
2026-02-24 00:40:50 -05:00
kikootwo 3d590b38cc Bump package version to 1.0.11
Update package.json version from 1.0.10 to 1.0.11 to mark a new patch release.
2026-02-24 00:20:15 -05:00
kikootwo aa7ba8a76d Remove legacy config API routes and tests
Delete legacy configuration API handlers and their tests. Removes src/app/api/config/route.ts (GET/PUT for config), src/app/api/config/[category]/route.ts (category GET), and tests/api/config.routes.test.ts. This cleans up deprecated/duplicated config endpoints and associated tests from the codebase.
2026-02-24 00:19:52 -05:00
root 328fd8392b ygg_timeout2 2026-02-21 14:30:51 +01:00
root 9a460f808d french-Traduction 2026-02-21 13:57:47 +01:00
root c60b6214ce French Traduction 2026-02-21 12:44:56 +01:00
root aff5faaa58 French Traduction 2026-02-21 11:43:06 +01:00
root c43ce7ba8f French Traduction 2026-02-21 11:40:48 +01:00
root f570b87343 French Traduction 2026-02-21 10:48:24 +01:00
root dfa7a11674 French Traduction 2026-02-21 10:43:49 +01:00
kikootwo 7a1a8ffa50 Bump package version to 1.0.10
Update package.json version from 1.0.9 to 1.0.10 to prepare a new release.
2026-02-20 20:44:47 -05:00
kikootwo d70f6c9957 Add Deluge integration; revamp admin Jobs & Logs UI
Introduce Deluge download client service and tests, remove obsolete rdtclient service, and update qbittorrent integration/tests and download-client interfaces/manager. Large UI refactor for admin pages: Jobs and Logs were redesigned to be responsive (mobile card views + desktop tables), improved headers, dialogs, controls, and better status/detail rendering. Also updated DownloadClient components (card, management, modal), organize-files processor, audible-series integration, and related unit tests to align with integration changes. Minor UX and accessibility tweaks, cron handling/validation adjustments, and a few formatting/cleanup fixes throughout.
2026-02-20 20:44:26 -05:00
44 changed files with 3078 additions and 1027 deletions
+1
View File
@@ -33,6 +33,7 @@ Configurable Audible region for accurate metadata matching across different inte
- India (`in`) - `audible.in` (English)
- Germany (`de`) - `audible.de` (non-English)
- Spain (`es`) - `audible.es` (non-English)
- French (`fr`) - `audible.fr` (non-English)
**`isEnglish` Flag:**
- Each region has `isEnglish: boolean` in `AudibleRegionConfig`
+1 -1
View File
@@ -243,7 +243,7 @@ type TorrentState =
- `forcedUP``seeding`/`completed` enables monitor to trigger import
- `stoppedDL``paused` ensures qBittorrent v5.x compatibility
**16. pausedUP/stoppedUP mapped as paused instead of completed** - RDT-Client (and qBittorrent after ratio limits) transitions directly to `pausedUP`/`stoppedUP` without passing through `uploading`/`stalledUP`. The `*UP` suffix means the download phase is complete and the torrent is on the upload side. Both states were incorrectly mapped to `'paused'`, causing the monitor to re-schedule checks indefinitely instead of triggering file organization. Fixed by:
**16. pausedUP/stoppedUP mapped as paused instead of completed** - qBittorrent (after ratio limits) transitions directly to `pausedUP`/`stoppedUP` without passing through `uploading`/`stalledUP`. The `*UP` suffix means the download phase is complete and the torrent is on the upload side. Both states were incorrectly mapped to `'paused'`, causing the monitor to re-schedule checks indefinitely instead of triggering file organization. Fixed by:
- `pausedUP``seeding` (unified) / `completed` (legacy) — triggers completion in monitor
- `stoppedUP``seeding` (unified) / `completed` (legacy) — same fix for qBittorrent v5.x
- `pausedDL`/`stoppedDL` remain `paused` — download phase genuinely paused
+1 -1
View File
@@ -271,7 +271,7 @@ src/app/admin/settings/
**PUT /api/admin/settings/audible**
- Updates Audible region
- Body: `{ region: string }` (one of: us, ca, uk, au, in, es)
- Body: `{ region: string }` (one of: us, ca, uk, au, in, es, fr)
- No validation required
**PUT /api/admin/settings/prowlarr/indexers**
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "readmeabook",
"version": "1.0.9",
"version": "1.0.12",
"private": true,
"scripts": {
"dev": "next dev",
+209 -123
View File
@@ -78,13 +78,11 @@ function AdminJobsPageContent() {
const showEditDialog = (job: ScheduledJob) => {
setEditForm({ schedule: job.schedule, enabled: job.enabled });
// Check if it's a preset
const preset = SCHEDULE_PRESETS.find(p => p.cron === job.schedule);
if (preset) {
setScheduleMode('preset');
setSelectedPreset(preset.cron);
} else {
// Try to parse as custom schedule
const parsed = cronToCustomSchedule(job.schedule);
if (parsed.type === 'custom') {
setScheduleMode('advanced');
@@ -111,7 +109,7 @@ function AdminJobsPageContent() {
method: 'POST',
});
toast.success(`Job "${jobName}" triggered successfully`);
fetchJobs(); // Refresh list
fetchJobs();
} catch (err) {
const errorMsg = err instanceof Error ? err.message : 'Failed to trigger job';
toast.error(errorMsg);
@@ -124,7 +122,6 @@ function AdminJobsPageContent() {
const saveJobSchedule = async () => {
if (!editDialog.job) return;
// Calculate final cron expression based on mode
let finalCron: string;
if (scheduleMode === 'preset') {
finalCron = selectedPreset;
@@ -134,7 +131,6 @@ function AdminJobsPageContent() {
finalCron = editForm.schedule;
}
// Validate cron expression
if (!isValidCron(finalCron)) {
toast.error('Invalid cron expression. Please check your schedule.');
return;
@@ -151,7 +147,7 @@ function AdminJobsPageContent() {
});
toast.success(`Job "${editDialog.job.name}" updated successfully`);
hideEditDialog();
fetchJobs(); // Refresh list
fetchJobs();
} catch (err) {
const errorMsg = err instanceof Error ? err.message : 'Failed to update job';
toast.error(errorMsg);
@@ -173,36 +169,131 @@ function AdminJobsPageContent() {
return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{/* Header */}
<div className="sticky top-0 z-10 mb-8 flex items-center justify-between bg-gray-50 dark:bg-gray-900 py-4 -mx-4 px-4 sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8 border-b border-gray-200 dark:border-gray-800">
<div>
<h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">
Scheduled Jobs
</h1>
<p className="text-gray-600 dark:text-gray-400 mt-2">
Manage recurring tasks and automated jobs
</p>
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8">
{/* Header — stacks on mobile, row on sm+ */}
<div className="sticky top-0 z-10 mb-6 sm:mb-8 bg-gray-50 dark:bg-gray-900 py-4 -mx-4 px-4 sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8 border-b border-gray-200 dark:border-gray-800">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-2xl sm:text-3xl font-bold text-gray-900 dark:text-gray-100">
Scheduled Jobs
</h1>
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
Manage recurring tasks and automated jobs
</p>
</div>
<Link
href="/admin"
className="inline-flex items-center gap-2 px-4 py-2.5 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100 rounded-lg transition-colors text-sm font-medium self-start sm:self-auto flex-shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
</svg>
<span>Back to Dashboard</span>
</Link>
</div>
<Link
href="/admin"
className="inline-flex items-center gap-2 px-4 py-2 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100 rounded-lg transition-colors"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
</svg>
<span>Back to Dashboard</span>
</Link>
</div>
{error && (
<div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
<p className="text-red-800 dark:text-red-200">{error}</p>
<p className="text-red-800 dark:text-red-200 text-sm">{error}</p>
</div>
)}
{/* Jobs Table */}
<div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
{/* Jobs — Card layout on mobile, Table on sm+ */}
<div className="space-y-3 sm:hidden">
{jobs.map((job) => (
<div
key={job.id}
className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden"
>
{/* Card header */}
<div className="px-4 py-3 flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="font-semibold text-gray-900 dark:text-gray-100 text-sm leading-snug">
{job.name}
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
{job.type}
</div>
</div>
<span
className={`flex-shrink-0 mt-0.5 px-2.5 py-0.5 inline-flex text-xs font-medium rounded-full ${
job.enabled
? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
: 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400'
}`}
>
{job.enabled ? 'Enabled' : 'Disabled'}
</span>
</div>
{/* Card body */}
<div className="px-4 pb-3 space-y-2 border-t border-gray-100 dark:border-gray-700/60 pt-3">
<div>
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-0.5">
Schedule
</div>
<div className="text-sm text-gray-900 dark:text-gray-100">
{cronToHuman(job.schedule)}
</div>
<div className="text-xs text-gray-400 dark:text-gray-500 font-mono mt-0.5">
{job.schedule}
</div>
</div>
<div>
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-0.5">
Last Run
</div>
<div className="text-sm text-gray-700 dark:text-gray-300">
{job.lastRun ? new Date(job.lastRun).toLocaleString() : 'Never'}
</div>
</div>
</div>
{/* Card actions */}
<div className="px-4 py-3 border-t border-gray-100 dark:border-gray-700/60 flex gap-2">
<button
onClick={() => showEditDialog(job)}
className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2.5 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 rounded-lg text-sm font-medium transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
Edit
</button>
<button
onClick={() => showConfirmDialog(job.id, job.name)}
disabled={triggering === job.id}
className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2.5 bg-blue-50 dark:bg-blue-900/20 hover:bg-blue-100 dark:hover:bg-blue-900/40 text-blue-700 dark:text-blue-400 rounded-lg text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{triggering === job.id ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>
Running...
</>
) : (
<>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
Trigger
</>
)}
</button>
</div>
</div>
))}
{jobs.length === 0 && (
<div className="text-center py-12">
<p className="text-gray-500 dark:text-gray-400">No scheduled jobs found</p>
</div>
)}
</div>
{/* Jobs Table — hidden on mobile, visible on sm+ */}
<div className="hidden sm:block bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
<thead className="bg-gray-50 dark:bg-gray-900">
<tr>
@@ -312,31 +403,31 @@ function AdminJobsPageContent() {
<ul className="text-sm text-blue-700 dark:text-blue-300 space-y-1">
<li> <strong>Library Scan:</strong> Automatically scans your media library for new audiobooks</li>
<li> <strong>Audible Data Refresh:</strong> Caches popular and new release audiobooks from Audible</li>
<li> Trigger jobs manually using the "Trigger Now" button</li>
<li> Trigger jobs manually using the &quot;Trigger Now&quot; button</li>
<li> Schedule format follows cron syntax (minute hour day month weekday)</li>
</ul>
</div>
{/* Confirmation Dialog */}
{confirmDialog.isOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 p-4">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">
<div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black bg-opacity-50 p-4">
<div className="bg-white dark:bg-gray-800 rounded-2xl sm:rounded-lg shadow-xl w-full max-w-md p-6">
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-3">
Confirm Job Trigger
</h3>
<p className="text-gray-600 dark:text-gray-400 mb-6">
<p className="text-gray-600 dark:text-gray-400 text-sm mb-6">
Are you sure you want to trigger &quot;{confirmDialog.jobName}&quot; now?
</p>
<div className="flex justify-end gap-3">
<div className="flex gap-3">
<button
onClick={hideConfirmDialog}
className="px-4 py-2 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
className="flex-1 px-4 py-2.5 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors text-sm font-medium"
>
Cancel
</button>
<button
onClick={triggerJob}
className="px-4 py-2 text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors"
className="flex-1 px-4 py-2.5 text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors text-sm font-medium"
>
Trigger Job
</button>
@@ -347,12 +438,27 @@ function AdminJobsPageContent() {
{/* Edit Job Dialog */}
{editDialog.isOpen && editDialog.job && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 p-4">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full p-6 max-h-[90vh] overflow-y-auto">
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">
Edit Job Schedule
</h3>
<div className="space-y-4 mb-6">
<div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black bg-opacity-50 p-0 sm:p-4">
<div className="bg-white dark:bg-gray-800 rounded-t-2xl sm:rounded-2xl shadow-xl w-full sm:max-w-2xl max-h-[92vh] sm:max-h-[90vh] overflow-y-auto">
{/* Dialog header */}
<div className="sticky top-0 bg-white dark:bg-gray-800 px-5 py-4 border-b border-gray-200 dark:border-gray-700 rounded-t-2xl">
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
Edit Job Schedule
</h3>
<button
onClick={hideEditDialog}
className="p-2 -mr-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
aria-label="Close dialog"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
<div className="px-5 py-5 space-y-5">
{/* Job Name */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
@@ -362,46 +468,29 @@ function AdminJobsPageContent() {
type="text"
value={editDialog.job.name}
disabled
className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 border border-gray-300 dark:border-gray-600 rounded-lg cursor-not-allowed"
className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 border border-gray-300 dark:border-gray-600 rounded-lg cursor-not-allowed text-sm"
/>
</div>
{/* Schedule Mode Tabs */}
{/* Schedule Mode Tabs — grid on mobile to avoid overflow */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Schedule Type
</label>
<div className="flex gap-2 mb-3">
<button
onClick={() => setScheduleMode('preset')}
className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
scheduleMode === 'preset'
? 'bg-blue-600 text-white'
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
}`}
>
Common Schedules
</button>
<button
onClick={() => setScheduleMode('custom')}
className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
scheduleMode === 'custom'
? 'bg-blue-600 text-white'
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
}`}
>
Custom Schedule
</button>
<button
onClick={() => setScheduleMode('advanced')}
className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
scheduleMode === 'advanced'
? 'bg-blue-600 text-white'
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
}`}
>
Advanced (Cron)
</button>
<div className="grid grid-cols-3 gap-1 p-1 bg-gray-100 dark:bg-gray-700/60 rounded-xl mb-4">
{(['preset', 'custom', 'advanced'] as const).map((mode) => (
<button
key={mode}
onClick={() => setScheduleMode(mode)}
className={`px-2 py-2 rounded-lg text-xs font-medium transition-colors ${
scheduleMode === mode
? 'bg-white dark:bg-gray-600 text-gray-900 dark:text-white shadow-sm'
: 'text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200'
}`}
>
{mode === 'preset' ? 'Common' : mode === 'custom' ? 'Custom' : 'Advanced'}
</button>
))}
</div>
{/* Preset Mode */}
@@ -418,16 +507,16 @@ function AdminJobsPageContent() {
value={preset.cron}
checked={selectedPreset === preset.cron}
onChange={(e) => setSelectedPreset(e.target.value)}
className="mt-1 w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600"
className="mt-1 w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 flex-shrink-0"
/>
<div className="flex-1">
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
{preset.label}
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
<div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
{preset.description}
</div>
<div className="text-xs text-gray-400 dark:text-gray-500 font-mono mt-1">
<div className="text-xs text-gray-400 dark:text-gray-500 font-mono mt-0.5">
{preset.cron}
</div>
</div>
@@ -445,8 +534,8 @@ function AdminJobsPageContent() {
</label>
<select
value={customSchedule.type}
onChange={(e) => setCustomSchedule({ ...customSchedule, type: e.target.value as any })}
className="w-full px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500"
onChange={(e) => setCustomSchedule({ ...customSchedule, type: e.target.value as CustomSchedule['type'] })}
className="w-full px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm"
>
<option value="minutes">Every X minutes</option>
<option value="hours">Every X hours</option>
@@ -456,7 +545,6 @@ function AdminJobsPageContent() {
</select>
</div>
{/* Minutes/Hours Interval */}
{(customSchedule.type === 'minutes' || customSchedule.type === 'hours') && (
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
@@ -468,7 +556,7 @@ function AdminJobsPageContent() {
max={customSchedule.type === 'minutes' ? 59 : 23}
value={customSchedule.interval || 1}
onChange={(e) => setCustomSchedule({ ...customSchedule, interval: parseInt(e.target.value, 10) })}
className="w-full px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500"
className="w-full px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm"
/>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Run every {customSchedule.interval || 1} {customSchedule.type}
@@ -476,12 +564,11 @@ function AdminJobsPageContent() {
</div>
)}
{/* Daily/Weekly/Monthly Time */}
{(customSchedule.type === 'daily' || customSchedule.type === 'weekly' || customSchedule.type === 'monthly') && (
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Hour (0-23)
Hour (023)
</label>
<input
type="number"
@@ -494,12 +581,12 @@ function AdminJobsPageContent() {
time: { hour: parseInt(e.target.value, 10), minute: customSchedule.time?.minute || 0 },
})
}
className="w-full px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500"
className="w-full px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Minute (0-59)
Minute (059)
</label>
<input
type="number"
@@ -512,13 +599,12 @@ function AdminJobsPageContent() {
time: { hour: customSchedule.time?.hour || 0, minute: parseInt(e.target.value, 10) },
})
}
className="w-full px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500"
className="w-full px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
</div>
)}
{/* Weekly Day Selection */}
{customSchedule.type === 'weekly' && (
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
@@ -527,7 +613,7 @@ function AdminJobsPageContent() {
<select
value={customSchedule.dayOfWeek || 0}
onChange={(e) => setCustomSchedule({ ...customSchedule, dayOfWeek: parseInt(e.target.value, 10) })}
className="w-full px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500"
className="w-full px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm"
>
<option value="0">Sunday</option>
<option value="1">Monday</option>
@@ -540,11 +626,10 @@ function AdminJobsPageContent() {
</div>
)}
{/* Monthly Day Selection */}
{customSchedule.type === 'monthly' && (
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Day of Month (1-31)
Day of Month (131)
</label>
<input
type="number"
@@ -552,12 +637,11 @@ function AdminJobsPageContent() {
max="31"
value={customSchedule.dayOfMonth || 1}
onChange={(e) => setCustomSchedule({ ...customSchedule, dayOfMonth: parseInt(e.target.value, 10) })}
className="w-full px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500"
className="w-full px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm"
/>
</div>
)}
{/* Preview */}
<div className="p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
<div className="text-sm font-medium text-blue-900 dark:text-blue-200">
Preview: {cronToHuman(customScheduleToCron(customSchedule))}
@@ -571,30 +655,32 @@ function AdminJobsPageContent() {
{/* Advanced Mode */}
{scheduleMode === 'advanced' && (
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Cron Expression
</label>
<input
type="text"
value={editForm.schedule}
onChange={(e) => setEditForm({ ...editForm, schedule: e.target.value })}
placeholder="0 */6 * * *"
className="w-full px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 font-mono"
/>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Format: minute hour day month weekday
</p>
<div className="mt-2 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
<div className="text-xs text-gray-600 dark:text-gray-400 space-y-1">
<div> */15 * * * * = Every 15 minutes</div>
<div> 0 */6 * * * = Every 6 hours</div>
<div> 0 0 * * * = Daily at midnight</div>
<div> 0 0 * * 0 = Weekly on Sunday</div>
<div className="space-y-3">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Cron Expression
</label>
<input
type="text"
value={editForm.schedule}
onChange={(e) => setEditForm({ ...editForm, schedule: e.target.value })}
placeholder="0 */6 * * *"
className="w-full px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 font-mono text-sm"
/>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Format: minute hour day month weekday
</p>
</div>
<div className="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
<div className="text-xs text-gray-600 dark:text-gray-400 space-y-1 font-mono">
<div>*/15 * * * * = Every 15 minutes</div>
<div>0 */6 * * * = Every 6 hours</div>
<div>0 0 * * * = Daily at midnight</div>
<div>0 0 * * 0 = Weekly on Sunday</div>
</div>
</div>
{editForm.schedule && (
<div className="mt-2 p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
<div className="p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
<div className="text-sm font-medium text-blue-900 dark:text-blue-200">
Preview: {cronToHuman(editForm.schedule)}
</div>
@@ -604,34 +690,34 @@ function AdminJobsPageContent() {
)}
</div>
{/* Enabled Checkbox */}
<div className="flex items-center gap-2 pt-4 border-t border-gray-200 dark:border-gray-700">
{/* Enabled toggle */}
<div className="flex items-center gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
<input
type="checkbox"
id="enabled"
checked={editForm.enabled}
onChange={(e) => setEditForm({ ...editForm, enabled: e.target.checked })}
className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600"
className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 flex-shrink-0"
/>
<label htmlFor="enabled" className="text-sm font-medium text-gray-700 dark:text-gray-300">
<label htmlFor="enabled" className="text-sm font-medium text-gray-700 dark:text-gray-300 cursor-pointer">
Enable this job
</label>
</div>
</div>
{/* Actions */}
<div className="flex justify-end gap-3">
{/* Dialog footer */}
<div className="sticky bottom-0 bg-white dark:bg-gray-800 px-5 py-4 border-t border-gray-200 dark:border-gray-700 flex gap-3">
<button
onClick={hideEditDialog}
disabled={saving}
className="px-4 py-2 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
className="flex-1 sm:flex-none px-4 py-2.5 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed"
>
Cancel
</button>
<button
onClick={saveJobSchedule}
disabled={saving}
className="px-4 py-2 text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
className="flex-1 sm:flex-none px-4 py-2.5 text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed"
>
{saving ? 'Saving...' : 'Save Changes'}
</button>
+236 -148
View File
@@ -56,6 +56,119 @@ interface LogsData {
};
}
function StatusBadge({ status }: { status: string }) {
const config: Record<string, { dot: string; text: string; bg: string }> = {
completed: { dot: 'bg-emerald-500', text: 'text-emerald-700 dark:text-emerald-400', bg: 'bg-emerald-500/10' },
failed: { dot: 'bg-red-500', text: 'text-red-700 dark:text-red-400', bg: 'bg-red-500/10' },
active: { dot: 'bg-blue-500', text: 'text-blue-700 dark:text-blue-400', bg: 'bg-blue-500/10' },
pending: { dot: 'bg-amber-500', text: 'text-amber-700 dark:text-amber-400', bg: 'bg-amber-500/10' },
delayed: { dot: 'bg-orange-500', text: 'text-orange-700 dark:text-orange-400', bg: 'bg-orange-500/10' },
stuck: { dot: 'bg-purple-500', text: 'text-purple-700 dark:text-purple-400', bg: 'bg-purple-500/10' },
};
const c = config[status] ?? { dot: 'bg-gray-400', text: 'text-gray-600 dark:text-gray-400', bg: 'bg-gray-500/10' };
return (
<span className={`inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium ${c.bg} ${c.text}`}>
<span className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${c.dot}`} />
{status.charAt(0).toUpperCase() + status.slice(1)}
</span>
);
}
function LogDetails({ log }: { log: Log }) {
return (
<div className="space-y-4">
{log.bullJobId && (
<div className="flex flex-wrap gap-1.5 items-baseline">
<span className="text-xs font-medium text-gray-500 dark:text-gray-400">Bull Job ID:</span>
<span className="text-xs text-gray-700 dark:text-gray-300 font-mono break-all">{log.bullJobId}</span>
</div>
)}
{log.events.length > 0 && (
<div>
<h4 className="text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wide mb-2">
Event Log
</h4>
<div className="space-y-px max-h-72 sm:max-h-96 overflow-y-auto bg-gray-950 dark:bg-black/60 rounded-xl p-3 font-mono text-xs">
{log.events.map((event) => {
const timestamp = new Date(event.createdAt).toISOString().split('T')[1].split('.')[0];
const levelColor = event.level === 'error'
? 'text-red-400'
: event.level === 'warn'
? 'text-amber-400'
: 'text-emerald-400';
return (
<div key={event.id} className="text-gray-300 leading-relaxed">
<span className={levelColor}>[{event.context}]</span>
{' '}
<span className="break-words">{event.message}</span>
<span className="text-gray-500 ml-2">{timestamp}</span>
{event.metadata && Object.keys(event.metadata).length > 0 && (
<pre className="ml-4 mt-1 text-gray-400 text-xs overflow-x-auto">
{JSON.stringify(event.metadata, null, 2)}
</pre>
)}
</div>
);
})}
</div>
</div>
)}
{log.result && Object.keys(log.result).length > 0 && (
<div>
<h4 className="text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wide mb-2">
Job Result
</h4>
<pre className="p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-xl text-xs text-blue-900 dark:text-blue-300 font-mono overflow-x-auto max-h-48">
{JSON.stringify(log.result, null, 2)}
</pre>
</div>
)}
{log.errorMessage && (
<div>
<h4 className="text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wide mb-2">
Error
</h4>
<div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl text-xs text-red-700 dark:text-red-300 font-mono whitespace-pre-wrap break-words">
{log.errorMessage}
</div>
</div>
)}
</div>
);
}
function formatDuration(startedAt: string | null, completedAt: string | null) {
if (!startedAt) return 'N/A';
if (!completedAt) return 'Running…';
const durationMs = new Date(completedAt).getTime() - new Date(startedAt).getTime();
const seconds = Math.floor(durationMs / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) return `${hours}h ${minutes % 60}m`;
if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
return `${seconds}s`;
}
function formatType(type: string) {
return type.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase());
}
function formatDateShort(dateStr: string) {
const d = new Date(dateStr);
const now = new Date();
const isToday = d.toDateString() === now.toDateString();
if (isToday) {
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}
return d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' +
d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
export default function AdminLogsPage() {
const [page, setPage] = useState(1);
const [statusFilter, setStatusFilter] = useState('all');
@@ -65,9 +178,7 @@ export default function AdminLogsPage() {
const { data, error } = useSWR<LogsData>(
`/api/admin/logs?page=${page}&limit=50&status=${statusFilter}&type=${typeFilter}`,
authenticatedFetcher,
{
refreshInterval: 10000, // Refresh every 10 seconds
}
{ refreshInterval: 10000 }
);
const isLoading = !data && !error;
@@ -87,9 +198,7 @@ export default function AdminLogsPage() {
<div className="min-h-screen bg-gray-50 dark:bg-gray-900 p-8">
<div className="max-w-7xl mx-auto">
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
<h3 className="text-sm font-medium text-red-800 dark:text-red-200">
Error Loading Logs
</h3>
<h3 className="text-sm font-medium text-red-800 dark:text-red-200">Error Loading Logs</h3>
<p className="text-sm text-red-700 dark:text-red-300 mt-1">
{error?.message || 'Failed to load system logs'}
</p>
@@ -101,80 +210,45 @@ export default function AdminLogsPage() {
const logs = data?.logs || [];
const pagination = data?.pagination;
const getStatusBadgeColor = (status: string) => {
switch (status) {
case 'completed':
return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400';
case 'failed':
return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400';
case 'active':
return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400';
case 'pending':
return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400';
case 'delayed':
return 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-400';
case 'stuck':
return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400';
default:
return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-400';
}
};
const formatDuration = (startedAt: string | null, completedAt: string | null) => {
if (!startedAt) return 'N/A';
if (!completedAt) return 'Running...';
const start = new Date(startedAt).getTime();
const end = new Date(completedAt).getTime();
const durationMs = end - start;
const seconds = Math.floor(durationMs / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) return `${hours}h ${minutes % 60}m`;
if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
return `${seconds}s`;
};
const hasDetails = (log: Log) => log.events.length > 0 || !!log.errorMessage || !!log.bullJobId || (log.result && Object.keys(log.result).length > 0);
return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{/* Header */}
<div className="sticky top-0 z-10 mb-8 flex items-center justify-between bg-gray-50 dark:bg-gray-900 py-4 -mx-4 px-4 sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8 border-b border-gray-200 dark:border-gray-800">
<div>
<h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">
System Logs
</h1>
<p className="text-gray-600 dark:text-gray-400 mt-2">
View background jobs and system activity
</p>
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8">
{/* Header — stacks on mobile, row on sm+ */}
<div className="sticky top-0 z-10 mb-6 sm:mb-8 bg-gray-50 dark:bg-gray-900 py-4 -mx-4 px-4 sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8 border-b border-gray-200 dark:border-gray-800">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-2xl sm:text-3xl font-bold text-gray-900 dark:text-gray-100">
System Logs
</h1>
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
View background jobs and system activity
</p>
</div>
<Link
href="/admin"
className="inline-flex items-center gap-2 px-4 py-2.5 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100 rounded-lg transition-colors text-sm font-medium self-start sm:self-auto flex-shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
</svg>
<span>Back to Dashboard</span>
</Link>
</div>
<Link
href="/admin"
className="inline-flex items-center gap-2 px-4 py-2 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100 rounded-lg transition-colors"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
</svg>
<span>Back to Dashboard</span>
</Link>
</div>
{/* Filters */}
<div className="mb-6 flex flex-wrap gap-4">
{/* Filters — full-width stacked on mobile */}
<div className="mb-6 grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
<label className="block text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1.5">
Status
</label>
<select
value={statusFilter}
onChange={(e) => {
setStatusFilter(e.target.value);
setPage(1);
}}
className="px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500"
onChange={(e) => { setStatusFilter(e.target.value); setPage(1); }}
className="w-full px-3 py-2.5 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm"
>
<option value="all">All Statuses</option>
<option value="pending">Pending</option>
@@ -186,16 +260,13 @@ export default function AdminLogsPage() {
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
<label className="block text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1.5">
Job Type
</label>
<select
value={typeFilter}
onChange={(e) => {
setTypeFilter(e.target.value);
setPage(1);
}}
className="px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500"
onChange={(e) => { setTypeFilter(e.target.value); setPage(1); }}
className="w-full px-3 py-2.5 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm"
>
<option value="all">All Types</option>
<option value="search_indexers">Search Indexers</option>
@@ -215,8 +286,77 @@ export default function AdminLogsPage() {
</div>
</div>
{/* Logs Table */}
<div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
{/* Mobile card list — hidden on sm+ */}
<div className="space-y-3 sm:hidden">
{logs.map((log) => (
<div
key={log.id}
className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden"
>
{/* Card header */}
<div className="px-4 py-3">
<div className="flex items-start justify-between gap-3 mb-2">
<div className="font-semibold text-gray-900 dark:text-gray-100 text-sm leading-snug">
{formatType(log.type)}
</div>
<StatusBadge status={log.status} />
</div>
{/* Related item */}
{log.request?.audiobook ? (
<div className="text-sm mb-2">
<div className="text-gray-700 dark:text-gray-300 font-medium leading-snug">
{log.request.audiobook.title}
</div>
<div className="text-gray-500 dark:text-gray-400 text-xs">
by {log.request.audiobook.author} &middot; {log.request.user.plexUsername}
</div>
</div>
) : (
<div className="text-xs text-gray-500 dark:text-gray-400 mb-2">System job</div>
)}
{/* Meta row */}
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
<span>{formatDateShort(log.createdAt)}</span>
<span>Duration: {formatDuration(log.startedAt, log.completedAt)}</span>
<span>Attempts: {log.attempts}/{log.maxAttempts}</span>
</div>
</div>
{/* Expandable details */}
{hasDetails(log) && (
<>
<button
onClick={() => setExpandedLog(expandedLog === log.id ? null : log.id)}
className="w-full flex items-center justify-between px-4 py-2.5 border-t border-gray-100 dark:border-gray-700/60 text-xs font-medium text-blue-600 dark:text-blue-400 hover:bg-gray-50 dark:hover:bg-gray-700/40 transition-colors"
>
<span>{expandedLog === log.id ? 'Hide Details' : 'Show Details'}</span>
<svg
className={`w-4 h-4 transition-transform duration-200 ${expandedLog === log.id ? 'rotate-180' : ''}`}
fill="none" stroke="currentColor" viewBox="0 0 24 24"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</button>
{expandedLog === log.id && (
<div className="px-4 pb-4 pt-3 bg-gray-50 dark:bg-gray-900/50 border-t border-gray-100 dark:border-gray-700/60">
<LogDetails log={log} />
</div>
)}
</>
)}
</div>
))}
{logs.length === 0 && (
<div className="text-center py-12">
<p className="text-gray-500 dark:text-gray-400">No logs found</p>
</div>
)}
</div>
{/* Desktop table — hidden on mobile */}
<div className="hidden sm:block bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
<thead className="bg-gray-50 dark:bg-gray-900">
@@ -253,13 +393,11 @@ export default function AdminLogsPage() {
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
{log.type.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase())}
{formatType(log.type)}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${getStatusBadgeColor(log.status)}`}>
{log.status.toUpperCase()}
</span>
<StatusBadge status={log.status} />
</td>
<td className="px-6 py-4">
{log.request?.audiobook ? (
@@ -285,7 +423,7 @@ export default function AdminLogsPage() {
{log.attempts}/{log.maxAttempts}
</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
{(log.events.length > 0 || log.errorMessage || log.bullJobId || log.result) && (
{hasDetails(log) && (
<button
onClick={() => setExpandedLog(expandedLog === log.id ? null : log.id)}
className="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300"
@@ -298,63 +436,7 @@ export default function AdminLogsPage() {
{expandedLog === log.id && (
<tr>
<td colSpan={7} className="px-6 py-4 bg-gray-50 dark:bg-gray-900">
<div className="space-y-4">
{log.bullJobId && (
<div>
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">Bull Job ID: </span>
<span className="text-sm text-gray-600 dark:text-gray-400 font-mono">{log.bullJobId}</span>
</div>
)}
{/* Event Logs */}
{log.events.length > 0 && (
<div>
<h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Event Log</h4>
<div className="space-y-1 max-h-96 overflow-y-auto bg-black/5 dark:bg-black/30 rounded p-3 font-mono text-xs">
{log.events.map((event) => {
const timestamp = new Date(event.createdAt).toISOString().split('T')[1].split('.')[0];
const levelColor = event.level === 'error'
? 'text-red-500'
: event.level === 'warn'
? 'text-yellow-500'
: 'text-green-500';
return (
<div key={event.id} className="text-gray-800 dark:text-gray-200">
<span className={levelColor}>[{event.context}]</span> {event.message}
<span className="text-gray-500 dark:text-gray-400 ml-2">{timestamp}</span>
{event.metadata && Object.keys(event.metadata).length > 0 && (
<pre className="ml-4 mt-1 text-gray-600 dark:text-gray-400 text-xs">
{JSON.stringify(event.metadata, null, 2)}
</pre>
)}
</div>
);
})}
</div>
</div>
)}
{/* Result Data */}
{log.result && Object.keys(log.result).length > 0 && (
<div>
<h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Job Result</h4>
<pre className="p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded text-xs text-blue-900 dark:text-blue-300 font-mono overflow-x-auto">
{JSON.stringify(log.result, null, 2)}
</pre>
</div>
)}
{/* Error Message */}
{log.errorMessage && (
<div>
<h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Error</h4>
<div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded text-sm text-red-700 dark:text-red-300 font-mono whitespace-pre-wrap">
{log.errorMessage}
</div>
</div>
)}
</div>
<LogDetails log={log} />
</td>
</tr>
)}
@@ -373,24 +455,31 @@ export default function AdminLogsPage() {
{/* Pagination */}
{pagination && pagination.totalPages > 1 && (
<div className="mt-6 flex items-center justify-between">
<div className="text-sm text-gray-700 dark:text-gray-300">
Page {pagination.page} of {pagination.totalPages} ({pagination.total} total logs)
<div className="mt-6 flex flex-col sm:flex-row items-center gap-3 sm:justify-between">
<div className="text-sm text-gray-600 dark:text-gray-400 order-2 sm:order-1">
Page {pagination.page} of {pagination.totalPages}
<span className="hidden sm:inline"> ({pagination.total} total logs)</span>
</div>
<div className="flex gap-2">
<div className="flex gap-2 order-1 sm:order-2">
<button
onClick={() => setPage(page - 1)}
disabled={page === 1}
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
Previous
</button>
<button
onClick={() => setPage(page + 1)}
disabled={page === pagination.totalPages}
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Next
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</button>
</div>
</div>
@@ -403,11 +492,10 @@ export default function AdminLogsPage() {
</h3>
<ul className="text-sm text-blue-700 dark:text-blue-300 space-y-1">
<li> Logs are automatically refreshed every 10 seconds</li>
<li> Click "Show Details" to view detailed event logs, job results, and error messages</li>
<li> Event logs show all internal operations with timestamps (similar to Docker logs)</li>
<li> Tap &quot;Show Details&quot; to view event logs, job results, and errors</li>
<li> Event logs show all internal operations with timestamps</li>
<li> Jobs are retried automatically based on their max attempts setting</li>
<li> Use filters to find specific job types or statuses</li>
<li> All job types are tracked: searches, downloads, file organization, library scans, RSS monitoring, and more</li>
</ul>
</div>
</div>
+157 -70
View File
@@ -13,17 +13,34 @@ import { ActiveDownloadsTable } from './components/ActiveDownloadsTable';
import { RecentRequestsTable } from './components/RecentRequestsTable';
import { ToastProvider, useToast } from '@/components/ui/Toast';
import { ReportedIssuesSection } from './components/ReportedIssuesSection';
import { InteractiveTorrentSearchModal } from '@/components/requests/InteractiveTorrentSearchModal';
import { TorrentResult } from '@/lib/utils/ranking-algorithm';
import { formatDistanceToNow } from 'date-fns';
import { useState } from 'react';
interface SelectedTorrentData {
title?: string;
indexer?: string;
size?: number;
format?: string;
ebookFormat?: string;
seeders?: number;
infoUrl?: string;
source?: string;
protocol?: string;
score?: number;
}
interface PendingApprovalRequest {
id: string;
createdAt: string;
type: 'audiobook' | 'ebook';
selectedTorrent: SelectedTorrentData | null;
audiobook: {
title: string;
author: string;
coverArtUrl: string | null;
audibleAsin: string | null;
};
user: {
id: string;
@@ -32,9 +49,20 @@ interface PendingApprovalRequest {
};
}
function formatTorrentSize(bytes: number): string {
const gb = bytes / (1024 ** 3);
const mb = bytes / (1024 ** 2);
return gb >= 1 ? `${gb.toFixed(1)} GB` : `${mb.toFixed(0)} MB`;
}
function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest[] }) {
const toast = useToast();
const [loadingStates, setLoadingStates] = useState<Record<string, boolean>>({});
const [searchModalRequestId, setSearchModalRequestId] = useState<string | null>(null);
const searchModalRequest = searchModalRequestId
? requests.find((r) => r.id === searchModalRequestId)
: null;
const handleApproveRequest = async (requestId: string) => {
setLoadingStates((prev) => ({ ...prev, [requestId]: true }));
@@ -47,7 +75,6 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
toast.success('Request approved');
// Mutate both pending requests and recent requests caches
await mutate('/api/admin/requests/pending-approval');
await mutate('/api/admin/requests/recent');
await mutate('/api/admin/metrics');
@@ -72,7 +99,6 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
toast.success('Request denied');
// Mutate pending requests cache
await mutate('/api/admin/requests/pending-approval');
await mutate('/api/admin/metrics');
} catch (error) {
@@ -85,6 +111,26 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
}
};
const handleApproveWithTorrent = async (requestId: string, torrent: TorrentResult) => {
await fetchJSON(`/api/admin/requests/${requestId}/approve`, {
method: 'POST',
body: JSON.stringify({ action: 'approve', selectedTorrent: torrent }),
});
toast.success('Request approved and download started');
await mutate('/api/admin/requests/pending-approval');
await mutate('/api/admin/requests/recent');
await mutate('/api/admin/metrics');
};
const LoadingSpinner = () => (
<svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
</svg>
);
return (
<div className="mb-8">
{/* Section Header */}
@@ -116,6 +162,9 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{requests.map((request) => {
const isLoading = loadingStates[request.id] || false;
const torrent = request.selectedTorrent;
const displayFormat = torrent?.format || torrent?.ebookFormat;
const isAnnasArchive = torrent?.source === 'annas_archive';
return (
<div
@@ -205,89 +254,107 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
</div>
</div>
{/* Pre-Selected Release */}
{torrent && torrent.title && (
<div className="mx-4 mb-3 px-3 py-2.5 bg-gray-50 dark:bg-gray-900/60 rounded-lg border border-gray-200 dark:border-gray-700/60">
<div className="flex items-center gap-1.5 mb-1">
<svg className="w-3 h-3 text-gray-400 dark:text-gray-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
</svg>
<span className="text-[10px] font-semibold uppercase tracking-wider text-gray-400 dark:text-gray-500">
User-Selected Release
</span>
</div>
{torrent.infoUrl ? (
<a
href={torrent.infoUrl}
target="_blank"
rel="noopener noreferrer"
className="text-xs font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 transition-colors line-clamp-2 leading-snug"
title={torrent.title}
>
{torrent.title}
</a>
) : (
<p className="text-xs font-medium text-gray-700 dark:text-gray-300 line-clamp-2 leading-snug" title={torrent.title}>
{torrent.title}
</p>
)}
<div className="flex items-center gap-1 mt-1.5 text-[11px] text-gray-500 dark:text-gray-400 flex-wrap">
{isAnnasArchive ? (
<span className="text-orange-600 dark:text-orange-400 font-medium">Anna&apos;s Archive</span>
) : torrent.indexer ? (
<span>{torrent.indexer}</span>
) : null}
{torrent.size && torrent.size > 0 ? (
<>
<span className="text-gray-300 dark:text-gray-600 select-none">&middot;</span>
<span>{formatTorrentSize(torrent.size)}</span>
</>
) : null}
{displayFormat ? (
<>
<span className="text-gray-300 dark:text-gray-600 select-none">&middot;</span>
<span className="px-1 py-px text-[10px] font-semibold uppercase tracking-wide rounded bg-purple-100 dark:bg-purple-500/15 text-purple-700 dark:text-purple-300">
{displayFormat}
</span>
</>
) : null}
{torrent.protocol === 'usenet' ? (
<>
<span className="text-gray-300 dark:text-gray-600 select-none">&middot;</span>
<span className="text-sky-600 dark:text-sky-400 font-medium">NZB</span>
</>
) : torrent.seeders !== undefined && torrent.seeders !== null ? (
<>
<span className="text-gray-300 dark:text-gray-600 select-none">&middot;</span>
<span className="text-emerald-600 dark:text-emerald-400">{torrent.seeders} seeds</span>
</>
) : null}
{torrent.score !== undefined && torrent.score !== null ? (
<>
<span className="text-gray-300 dark:text-gray-600 select-none">&middot;</span>
<span className="font-medium">Score {Math.round(torrent.score)}</span>
</>
) : null}
</div>
</div>
)}
{/* Action Buttons */}
<div className="border-t border-amber-200 dark:border-amber-800 bg-gray-50 dark:bg-gray-900/50 px-4 py-3 flex gap-2">
<button
onClick={() => handleApproveRequest(request.id)}
disabled={isLoading}
className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 bg-green-600 hover:bg-green-700 disabled:bg-green-400 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition-colors"
className="flex-1 inline-flex items-center justify-center gap-1.5 px-3 py-2 bg-green-600 hover:bg-green-700 disabled:bg-green-400 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition-colors"
>
{isLoading ? (
<svg
className="animate-spin h-4 w-4"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
) : (
<svg
className="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M5 13l4 4L19 7"
/>
{isLoading ? <LoadingSpinner /> : (
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
)}
<span>Approve</span>
</button>
<button
onClick={() => setSearchModalRequestId(request.id)}
disabled={isLoading}
className="flex-1 inline-flex items-center justify-center gap-1.5 px-3 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<span>Search</span>
</button>
<button
onClick={() => handleDenyRequest(request.id)}
disabled={isLoading}
className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 bg-red-600 hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition-colors"
className="flex-1 inline-flex items-center justify-center gap-1.5 px-3 py-2 bg-red-600 hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition-colors"
>
{isLoading ? (
<svg
className="animate-spin h-4 w-4"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
) : (
<svg
className="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M6 18L18 6M6 6l12 12"
/>
{isLoading ? <LoadingSpinner /> : (
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
)}
<span>Deny</span>
@@ -297,6 +364,26 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
);
})}
</div>
{/* Interactive Search Modal */}
{searchModalRequest && (
<InteractiveTorrentSearchModal
isOpen={!!searchModalRequestId}
onClose={() => setSearchModalRequestId(null)}
requestId={searchModalRequest.id}
audiobook={{
title: searchModalRequest.audiobook.title,
author: searchModalRequest.audiobook.author,
}}
searchMode={searchModalRequest.type === 'ebook' ? 'ebook' : 'audiobook'}
onConfirm={async (torrent) => {
await handleApproveWithTorrent(searchModalRequest.id, torrent);
}}
onSuccess={() => {
setSearchModalRequestId(null);
}}
/>
)}
</div>
);
}
+2
View File
@@ -100,6 +100,8 @@ export interface PathsSettings {
ebookPathTemplate?: string;
metadataTaggingEnabled: boolean;
chapterMergingEnabled: boolean;
fileRenameEnabled: boolean;
fileRenameTemplate?: string;
}
/**
@@ -10,7 +10,7 @@ import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { usePathsSettings } from './usePathsSettings';
import type { PathsSettings } from '../../lib/types';
import { validateTemplate, generateMockPreviews } from '@/lib/utils/path-template.util';
import { validateTemplate, generateMockPreviews, validateFilenameTemplate, generateMockFilenamePreviews } from '@/lib/utils/path-template.util';
interface PathsTabProps {
paths: PathsSettings;
@@ -24,6 +24,13 @@ interface TemplatePreview {
previewPaths?: string[];
}
interface FilenamePreview {
isValid: boolean;
error?: string;
single?: string[];
multi?: string[];
}
export function PathsTab({ paths, onChange, onValidationChange }: PathsTabProps) {
const { testing, testResult, updatePath, testPaths } = usePathsSettings({
paths,
@@ -73,6 +80,34 @@ export function PathsTab({ paths, onChange, onValidationChange }: PathsTabProps)
}
}, [paths.ebookPathTemplate]);
// Live preview state for filename template
const [filenamePreview, setFilenamePreview] = useState<FilenamePreview | null>(null);
// Update filename live preview whenever template changes
useEffect(() => {
if (!paths.fileRenameEnabled) {
setFilenamePreview(null);
return;
}
const template = paths.fileRenameTemplate || '{title}';
const validation = validateFilenameTemplate(template);
if (validation.valid) {
const previews = generateMockFilenamePreviews(template);
setFilenamePreview({
isValid: true,
single: previews.single,
multi: previews.multi,
});
} else {
setFilenamePreview({
isValid: false,
error: validation.error,
});
}
}, [paths.fileRenameTemplate, paths.fileRenameEnabled]);
const audiobookTemplate = paths.audiobookPathTemplate || '{author}/{title} {asin}';
const ebookTemplate = paths.ebookPathTemplate || '{author}/{title} {asin}';
const ebookMatchesAudiobook = ebookTemplate === audiobookTemplate;
@@ -218,6 +253,83 @@ export function PathsTab({ paths, onChange, onValidationChange }: PathsTabProps)
)}
</div>
{/* File Rename Toggle */}
<div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
<div className="flex items-start gap-4">
<input
type="checkbox"
id="file-rename-settings"
checked={paths.fileRenameEnabled}
onChange={(e) => updatePath('fileRenameEnabled', e.target.checked)}
className="mt-1 h-5 w-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<div className="flex-1">
<label
htmlFor="file-rename-settings"
className="block text-sm font-medium text-gray-900 dark:text-gray-100 cursor-pointer"
>
Rename files during organization
</label>
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
Rename audio and ebook files using a custom naming template when organizing into the media
library. When multiple files exist (e.g. chapterized MP3s), an index number is appended.
</p>
</div>
</div>
{/* File Naming Template (shown when enabled) */}
{paths.fileRenameEnabled && (
<div className="mt-4 pl-9">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
File Naming Template
</label>
<Input
type="text"
value={paths.fileRenameTemplate || '{title}'}
onChange={(e) => updatePath('fileRenameTemplate', e.target.value)}
placeholder="{title}"
className="font-mono"
/>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
Uses the same variables as the organization template. Do not include the file extension.
</p>
{/* Filename Validation Error */}
{filenamePreview && !filenamePreview.isValid && (
<div className="mt-3 p-3 rounded-lg text-sm flex items-start gap-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-800 dark:text-red-200">
<span className="flex-shrink-0 mt-0.5"></span>
<div className="flex-1">
<span>{filenamePreview.error || 'Invalid filename template'}</span>
</div>
</div>
)}
{/* Filename Preview */}
{filenamePreview && filenamePreview.isValid && (
<div className="mt-3 bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
<h4 className="text-sm font-semibold text-gray-900 dark:text-gray-100 mb-2">
Single File
</h4>
<div className="space-y-1.5 text-sm font-mono text-gray-700 dark:text-gray-300">
{filenamePreview.single?.map((preview, index) => (
<div key={index} className="text-xs">{preview}</div>
))}
</div>
<h4 className="text-sm font-semibold text-gray-900 dark:text-gray-100 mt-3 mb-2">
Multiple Files (chapterized)
</h4>
<div className="space-y-1.5 text-sm font-mono text-gray-700 dark:text-gray-300">
{filenamePreview.multi?.map((preview, index) => (
<div key={index} className="text-xs">{preview}</div>
))}
</div>
</div>
)}
</div>
)}
</div>
{/* Variable Reference Panel (shared for both templates) */}
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
<h3 className="text-sm font-semibold text-blue-900 dark:text-blue-100 mb-3">
@@ -255,6 +367,27 @@ export function PathsTab({ paths, onChange, onValidationChange }: PathsTabProps)
</div>
</div>
{/* Conditional Syntax Help */}
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4">
<h3 className="text-sm font-semibold text-amber-900 dark:text-amber-100 mb-2">
Conditional Syntax
</h3>
<p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
Wrap text around a variable in <code className="text-amber-700 dark:text-amber-300 font-mono">{'{ }'}</code> to
include that text only when the variable has a value. If the variable is empty, the entire block is removed.
</p>
<div className="text-sm font-mono bg-white dark:bg-gray-900 rounded px-3 py-2 border border-amber-100 dark:border-amber-900">
<div className="text-gray-700 dark:text-gray-300">
<code className="text-amber-700 dark:text-amber-300">{'{Book seriesPart - }'}</code>
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
With value: <span className="text-green-700 dark:text-green-400">Book 1 - </span>
&nbsp;&bull;&nbsp;
Without value: <span className="text-red-700 dark:text-red-400">(removed)</span>
</div>
</div>
</div>
{/* Metadata Tagging Toggle */}
<div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
<div className="flex items-start gap-4">
+366 -245
View File
@@ -41,6 +41,144 @@ interface PendingUser {
createdAt: string;
}
// Tinted-dot status badge following admin design system
function RoleBadge({ role, isSetupAdmin }: { role: 'user' | 'admin'; isSetupAdmin: boolean }) {
if (isSetupAdmin) {
return (
<span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-500/10 text-blue-700 dark:text-blue-400">
<span className="w-1.5 h-1.5 rounded-full flex-shrink-0 bg-blue-500" />
Setup Admin
</span>
);
}
if (role === 'admin') {
return (
<span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium bg-purple-500/10 text-purple-700 dark:text-purple-400">
<span className="w-1.5 h-1.5 rounded-full flex-shrink-0 bg-purple-500" />
Admin
</span>
);
}
return (
<span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-500/10 text-gray-600 dark:text-gray-400">
<span className="w-1.5 h-1.5 rounded-full flex-shrink-0 bg-gray-400" />
User
</span>
);
}
function PermissionBadge({
user,
globalAutoApprove,
onClick,
}: {
user: User;
globalAutoApprove: boolean;
onClick: () => void;
}) {
let badge: React.ReactNode;
if (user.role === 'admin') {
badge = (
<span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium rounded-full bg-purple-500/10 text-purple-700 dark:text-purple-400">
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
Full Access
</span>
);
} else if (globalAutoApprove) {
badge = (
<span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium rounded-full bg-blue-500/10 text-blue-700 dark:text-blue-400">
Global Default
</span>
);
} else if (user.autoApproveRequests ?? false) {
badge = (
<span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium rounded-full bg-emerald-500/10 text-emerald-700 dark:text-emerald-400">
Auto-Approve
</span>
);
} else {
badge = (
<span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium rounded-full bg-gray-500/10 text-gray-600 dark:text-gray-400">
Manual
</span>
);
}
return (
<button
onClick={onClick}
className="inline-flex items-center gap-1.5 text-sm transition-opacity hover:opacity-70"
>
{badge}
<svg className="w-3.5 h-3.5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</button>
);
}
function UserActionsCell({ user, onEdit, onDelete }: { user: User; onEdit: (u: User) => void; onDelete: (u: User) => void }) {
if (user.isSetupAdmin) {
return (
<span className="inline-flex items-center gap-1 text-gray-400 dark:text-gray-600 cursor-not-allowed" title="Setup admin role cannot be changed">
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
<span>Protected</span>
</span>
);
}
if (user.authProvider === 'oidc') {
return (
<span className="inline-flex items-center gap-1 text-gray-400 dark:text-gray-600 cursor-not-allowed" title="OIDC user roles are managed by the identity provider">
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span>OIDC Managed</span>
</span>
);
}
if (user.authProvider === 'local') {
return (
<div className="flex items-center gap-3">
<button
onClick={() => onEdit(user)}
className="inline-flex items-center gap-1 text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
<span>Edit Role</span>
</button>
<button
onClick={() => onDelete(user)}
className="inline-flex items-center gap-1 text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300 transition-colors"
title="Delete user and all their requests"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
<span>Delete</span>
</button>
</div>
);
}
// plex or other
return (
<button
onClick={() => onEdit(user)}
className="inline-flex items-center gap-1 text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
<span>Edit Role</span>
</button>
);
}
function AdminUsersPageContent() {
const { data, error, mutate } = useSWR('/api/admin/users', authenticatedFetcher);
const { data: pendingData, error: pendingError, mutate: mutatePending } = useSWR(
@@ -86,7 +224,6 @@ function AdminUsersPageContent() {
if (globalAutoApproveData?.autoApproveRequests !== undefined) {
setGlobalAutoApprove(globalAutoApproveData.autoApproveRequests);
} else if (globalAutoApproveData !== undefined && globalAutoApproveData.autoApproveRequests === undefined) {
// API returned but no value - default to true
setGlobalAutoApprove(true);
}
}, [globalAutoApproveData]);
@@ -101,9 +238,7 @@ function AdminUsersPageContent() {
}, [globalInteractiveSearchData]);
const handleGlobalAutoApproveToggle = async (newValue: boolean) => {
// Optimistic update
setGlobalAutoApprove(newValue);
try {
await fetchJSON('/api/admin/settings/auto-approve', {
method: 'PATCH',
@@ -111,20 +246,16 @@ function AdminUsersPageContent() {
});
toast.success(`Global auto-approve ${newValue ? 'enabled' : 'disabled'}`);
mutateGlobalAutoApprove();
mutate(); // Refresh users list to show updated state
mutate();
} catch (err) {
// Revert on error
setGlobalAutoApprove(!newValue);
const errorMsg = err instanceof Error ? err.message : 'Failed to update auto-approve setting';
toast.error(errorMsg);
console.error(err);
}
};
const handleGlobalInteractiveSearchToggle = async (newValue: boolean) => {
// Optimistic update
setGlobalInteractiveSearch(newValue);
try {
await fetchJSON('/api/admin/settings/interactive-search', {
method: 'PATCH',
@@ -132,74 +263,51 @@ function AdminUsersPageContent() {
});
toast.success(`Global interactive search ${newValue ? 'enabled' : 'disabled'}`);
mutateGlobalInteractiveSearch();
mutate(); // Refresh users list to show updated state
mutate();
} catch (err) {
// Revert on error
setGlobalInteractiveSearch(!newValue);
const errorMsg = err instanceof Error ? err.message : 'Failed to update interactive search setting';
toast.error(errorMsg);
console.error(err);
}
};
const handleUserAutoApproveToggle = async (user: User, newValue: boolean) => {
console.log('[AutoApprove] Toggle clicked:', { userId: user.id, username: user.plexUsername, newValue });
// Optimistic update
const previousUsers = data?.users || [];
const optimisticUsers = previousUsers.map((u: User) =>
u.id === user.id ? { ...u, autoApproveRequests: newValue } : u
);
console.log('[AutoApprove] Applying optimistic update');
mutate({ users: optimisticUsers }, false);
try {
console.log('[AutoApprove] Sending API request...');
const response = await fetchJSON(`/api/admin/users/${user.id}`, {
await fetchJSON(`/api/admin/users/${user.id}`, {
method: 'PUT',
body: JSON.stringify({
role: user.role,
autoApproveRequests: newValue
}),
body: JSON.stringify({ role: user.role, autoApproveRequests: newValue }),
});
console.log('[AutoApprove] API response received:', response);
toast.success(`Auto-approve ${newValue ? 'enabled' : 'disabled'} for ${user.plexUsername}`);
console.log('[AutoApprove] Triggering cache revalidation...');
mutate(); // Refresh users list
mutate();
} catch (err) {
// Revert on error
console.error('[AutoApprove] Error occurred, reverting:', err);
mutate({ users: previousUsers }, false);
const errorMsg = err instanceof Error ? err.message : 'Failed to update user auto-approve setting';
toast.error(errorMsg);
console.error(err);
}
};
const handleUserInteractiveSearchToggle = async (user: User, newValue: boolean) => {
// Optimistic update
const previousUsers = data?.users || [];
const optimisticUsers = previousUsers.map((u: User) =>
u.id === user.id ? { ...u, interactiveSearchAccess: newValue } : u
);
mutate({ users: optimisticUsers }, false);
try {
await fetchJSON(`/api/admin/users/${user.id}`, {
method: 'PUT',
body: JSON.stringify({
role: user.role,
interactiveSearchAccess: newValue
}),
body: JSON.stringify({ role: user.role, interactiveSearchAccess: newValue }),
});
toast.success(`Interactive search ${newValue ? 'enabled' : 'disabled'} for ${user.plexUsername}`);
mutate(); // Refresh users list
mutate();
} catch (err) {
// Revert on error
mutate({ users: previousUsers }, false);
const errorMsg = err instanceof Error ? err.message : 'Failed to update user interactive search setting';
toast.error(errorMsg);
console.error(err);
}
};
@@ -214,7 +322,6 @@ function AdminUsersPageContent() {
const saveUserRole = async () => {
if (!editDialog.user) return;
try {
setSaving(true);
await fetchJSON(`/api/admin/users/${editDialog.user.id}`, {
@@ -223,11 +330,10 @@ function AdminUsersPageContent() {
});
toast.success(`User "${editDialog.user.plexUsername}" updated successfully`);
hideEditDialog();
mutate(); // Refresh users list
mutate();
} catch (err) {
const errorMsg = err instanceof Error ? err.message : 'Failed to update user';
toast.error(errorMsg);
console.error(err);
} finally {
setSaving(false);
}
@@ -242,13 +348,12 @@ function AdminUsersPageContent() {
};
const closeConfirmDialog = () => {
if (processingUserId) return; // Don't close while processing
if (processingUserId) return;
setConfirmDialog({ isOpen: false, type: null, user: null });
};
const handleConfirmAction = async () => {
if (!confirmDialog.user) return;
const isApprove = confirmDialog.type === 'approve';
try {
setProcessingUserId(confirmDialog.user.id);
@@ -261,13 +366,12 @@ function AdminUsersPageContent() {
? `User "${confirmDialog.user.plexUsername}" has been approved`
: `User "${confirmDialog.user.plexUsername}" has been rejected`
);
mutatePending(); // Refresh pending users list
if (isApprove) mutate(); // Refresh approved users list
mutatePending();
if (isApprove) mutate();
closeConfirmDialog();
} catch (err) {
const errorMsg = err instanceof Error ? err.message : `Failed to ${isApprove ? 'approve' : 'reject'} user`;
toast.error(errorMsg);
console.error(err);
} finally {
setProcessingUserId(null);
}
@@ -278,25 +382,23 @@ function AdminUsersPageContent() {
};
const closeDeleteDialog = () => {
if (deleting) return; // Don't close while processing
if (deleting) return;
setDeleteDialog({ isOpen: false, user: null });
};
const handleDeleteUser = async () => {
if (!deleteDialog.user) return;
try {
setDeleting(true);
const response = await fetchJSON(`/api/admin/users/${deleteDialog.user.id}`, {
method: 'DELETE',
});
toast.success(response.message || `User "${deleteDialog.user.plexUsername}" has been deleted`);
mutate(); // Refresh users list
mutate();
closeDeleteDialog();
} catch (err) {
const errorMsg = err instanceof Error ? err.message : 'Failed to delete user';
toast.error(errorMsg);
console.error(err);
} finally {
setDeleting(false);
}
@@ -307,7 +409,6 @@ function AdminUsersPageContent() {
await navigator.clipboard.writeText(text);
toast.success(`${label} copied to clipboard`);
} catch (err) {
console.error('Failed to copy to clipboard:', err);
toast.error('Failed to copy to clipboard');
}
};
@@ -327,9 +428,7 @@ function AdminUsersPageContent() {
<div className="min-h-screen bg-gray-50 dark:bg-gray-900 p-8">
<div className="max-w-7xl mx-auto">
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
<h3 className="text-sm font-medium text-red-800 dark:text-red-200">
Error Loading Users
</h3>
<h3 className="text-sm font-medium text-red-800 dark:text-red-200">Error Loading Users</h3>
<p className="text-sm text-red-700 dark:text-red-300 mt-1">
{error?.message || 'Failed to load users'}
</p>
@@ -344,80 +443,81 @@ function AdminUsersPageContent() {
return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{/* Header */}
<div className="sticky top-0 z-10 mb-8 flex items-center justify-between bg-gray-50 dark:bg-gray-900 py-4 -mx-4 px-4 sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8 border-b border-gray-200 dark:border-gray-800">
<div>
<h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">
User Management
</h1>
<p className="text-gray-600 dark:text-gray-400 mt-2">
Manage user roles and permissions
</p>
</div>
<div className="flex items-center gap-3">
<button
onClick={() => setGlobalSettingsOpen(true)}
className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
<span>Global User Permissions</span>
</button>
<Link
href="/admin"
className="inline-flex items-center gap-2 px-4 py-2 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100 rounded-lg transition-colors"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
</svg>
<span>Back to Dashboard</span>
</Link>
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8">
{/* Header — stacks on mobile, row on sm+ */}
<div className="sticky top-0 z-10 mb-6 sm:mb-8 bg-gray-50 dark:bg-gray-900 py-4 -mx-4 px-4 sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8 border-b border-gray-200 dark:border-gray-800">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-2xl sm:text-3xl font-bold text-gray-900 dark:text-gray-100">
User Management
</h1>
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
Manage user roles and permissions
</p>
</div>
<div className="flex items-center gap-2 self-start sm:self-auto flex-shrink-0">
<button
onClick={() => setGlobalSettingsOpen(true)}
className="inline-flex items-center gap-2 px-3 sm:px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors text-sm font-medium"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
<span className="hidden sm:inline">Global User Permissions</span>
<span className="sm:hidden">Permissions</span>
</button>
<Link
href="/admin"
className="inline-flex items-center gap-2 px-3 sm:px-4 py-2.5 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100 rounded-lg transition-colors text-sm font-medium"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
</svg>
<span>Back</span>
</Link>
</div>
</div>
</div>
{/* Pending Users Section */}
{pendingUsers.length > 0 && (
<div className="mb-8">
<div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4 mb-4">
<h2 className="text-lg font-semibold text-yellow-900 dark:text-yellow-200 mb-4 flex items-center gap-2">
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<div className="mb-6 sm:mb-8">
<div className="bg-amber-50 dark:bg-amber-900/10 border border-amber-200 dark:border-amber-800/60 rounded-xl p-4">
<h2 className="text-base font-semibold text-amber-900 dark:text-amber-200 mb-1 flex items-center gap-2">
<svg className="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
Pending Registrations ({pendingUsers.length})
</h2>
<p className="text-sm text-yellow-800 dark:text-yellow-300 mb-4">
<p className="text-xs text-amber-700 dark:text-amber-300/80 mb-4">
The following users are awaiting approval to access the system.
</p>
<div className="space-y-3">
{pendingUsers.map((user) => (
<div
key={user.id}
className="bg-white dark:bg-gray-800 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4 flex items-center justify-between"
className="bg-white dark:bg-gray-800 border border-amber-200 dark:border-amber-800/40 rounded-xl overflow-hidden"
>
<div className="flex-1">
<div className="flex items-center gap-3">
<div>
<div className="font-medium text-gray-900 dark:text-gray-100">
{user.plexUsername}
</div>
<div className="text-sm text-gray-500 dark:text-gray-400">
{user.plexEmail || 'No email'}
</div>
<div className="text-xs text-gray-400 dark:text-gray-500 mt-1">
Registered: {new Date(user.createdAt).toLocaleString()}
Provider: {user.authProvider}
</div>
</div>
{/* Pending card — info */}
<div className="px-4 py-3">
<div className="font-medium text-gray-900 dark:text-gray-100 text-sm">
{user.plexUsername}
</div>
<div className="text-sm text-gray-500 dark:text-gray-400">
{user.plexEmail || 'No email'}
</div>
<div className="text-xs text-gray-400 dark:text-gray-500 mt-1">
Registered: {new Date(user.createdAt).toLocaleString()} &middot; Provider: {user.authProvider}
</div>
</div>
<div className="flex items-center gap-2">
{/* Pending card — actions, full-width on mobile */}
<div className="px-4 py-3 border-t border-amber-100 dark:border-amber-800/30 flex gap-2">
<button
onClick={() => showApproveDialog(user)}
disabled={processingUserId === user.id}
className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2.5 bg-emerald-50 dark:bg-emerald-500/10 hover:bg-emerald-100 dark:hover:bg-emerald-500/20 text-emerald-700 dark:text-emerald-400 border border-emerald-200/60 dark:border-emerald-500/20 rounded-xl text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
@@ -427,7 +527,7 @@ function AdminUsersPageContent() {
<button
onClick={() => showRejectDialog(user)}
disabled={processingUserId === user.id}
className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2.5 bg-red-50 dark:bg-red-500/10 hover:bg-red-100 dark:hover:bg-red-500/20 text-red-700 dark:text-red-400 border border-red-200/60 dark:border-red-500/20 rounded-xl text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
@@ -442,8 +542,104 @@ function AdminUsersPageContent() {
</div>
)}
{/* Users Table */}
<div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-x-auto">
{/* Users — Mobile card list (sm:hidden) */}
<div className="space-y-3 sm:hidden">
{users.map((user) => (
<div
key={user.id}
className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden"
>
{/* Card header — avatar + name + role badge */}
<div className="px-4 py-3 flex items-start gap-3">
{user.avatarUrl ? (
<img
src={user.avatarUrl}
alt={user.plexUsername}
className="h-10 w-10 rounded-full flex-shrink-0 mt-0.5"
/>
) : (
<div className="h-10 w-10 rounded-full flex-shrink-0 mt-0.5 bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
<svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
</div>
)}
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between gap-2">
<div className="font-semibold text-gray-900 dark:text-gray-100 text-sm leading-snug truncate">
{user.plexUsername}
</div>
<RoleBadge role={user.role} isSetupAdmin={user.isSetupAdmin} />
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 truncate">
{user.plexEmail || 'No email'}
</div>
</div>
</div>
{/* Card body — labeled fields */}
<div className="px-4 pb-3 pt-2 space-y-2 border-t border-gray-100 dark:border-gray-700/60">
<div className="grid grid-cols-2 gap-2">
<div>
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-0.5">
Permissions
</div>
<PermissionBadge
user={user}
globalAutoApprove={globalAutoApprove}
onClick={() => setPermissionsUserId(user.id)}
/>
</div>
<div>
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-0.5">
Requests
</div>
<div className="text-sm text-gray-900 dark:text-gray-100">
{user._count.requests}
</div>
</div>
</div>
<div>
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-0.5">
Last Login
</div>
<div className="text-sm text-gray-700 dark:text-gray-300">
{user.lastLoginAt
? new Date(user.lastLoginAt).toLocaleDateString()
: 'Never'}
</div>
</div>
<div>
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-0.5">
User ID
</div>
<button
onClick={() => copyToClipboard(user.plexId, 'User ID')}
className="text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors inline-flex items-center gap-1"
>
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
{user.plexId.length > 16 ? `${user.plexId.substring(0, 16)}` : user.plexId}
</button>
</div>
</div>
{/* Card actions */}
<div className="px-4 py-3 border-t border-gray-100 dark:border-gray-700/60">
<UserActionsCell user={user} onEdit={showEditDialog} onDelete={showDeleteDialog} />
</div>
</div>
))}
{users.length === 0 && (
<div className="text-center py-12">
<p className="text-gray-500 dark:text-gray-400">No users found</p>
</div>
)}
</div>
{/* Users Table — hidden on mobile, visible on sm+ */}
<div className="hidden sm:block bg-white dark:bg-gray-800 rounded-lg shadow overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
<thead className="bg-gray-50 dark:bg-gray-900">
<tr>
@@ -472,15 +668,21 @@ function AdminUsersPageContent() {
</thead>
<tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
{users.map((user) => (
<tr key={user.id}>
<tr key={user.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/40 transition-colors">
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center">
{user.avatarUrl && (
{user.avatarUrl ? (
<img
src={user.avatarUrl}
alt={user.plexUsername}
className="h-10 w-10 rounded-full mr-3"
className="h-10 w-10 rounded-full mr-3 flex-shrink-0"
/>
) : (
<div className="h-10 w-10 rounded-full mr-3 flex-shrink-0 bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
<svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
</div>
)}
<div>
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
@@ -507,52 +709,14 @@ function AdminUsersPageContent() {
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center gap-2">
<span
className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
user.role === 'admin'
? 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400'
: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-400'
}`}
>
{user.role.toUpperCase()}
</span>
{user.isSetupAdmin && (
<span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400">
SETUP ADMIN
</span>
)}
</div>
<RoleBadge role={user.role} isSetupAdmin={user.isSetupAdmin} />
</td>
<td className="px-6 py-4 whitespace-nowrap">
<button
<PermissionBadge
user={user}
globalAutoApprove={globalAutoApprove}
onClick={() => setPermissionsUserId(user.id)}
className="inline-flex items-center gap-1.5 text-sm text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 transition-colors"
>
{user.role === 'admin' ? (
<span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium rounded-full bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400">
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
Full Access
</span>
) : globalAutoApprove ? (
<span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium rounded-full bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400">
Global Default
</span>
) : (user.autoApproveRequests ?? false) ? (
<span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium rounded-full bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400">
Auto-Approve
</span>
) : (
<span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium rounded-full bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400">
Manual
</span>
)}
<svg className="w-3.5 h-3.5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</button>
/>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
{user._count.requests}
@@ -563,65 +727,7 @@ function AdminUsersPageContent() {
: 'Never'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<div className="flex items-center justify-end gap-3">
{user.isSetupAdmin ? (
<span className="inline-flex items-center gap-1 text-gray-400 dark:text-gray-600 cursor-not-allowed" title="Setup admin role cannot be changed">
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
<span>Protected</span>
</span>
) : user.authProvider === 'oidc' ? (
<span className="inline-flex items-center gap-1 text-gray-400 dark:text-gray-600 cursor-not-allowed" title="OIDC user roles are managed by the identity provider (use admin role mapping in settings)">
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span>OIDC Managed</span>
</span>
) : user.authProvider === 'plex' ? (
<button
onClick={() => showEditDialog(user)}
className="inline-flex items-center gap-1 text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
<span>Edit Role</span>
</button>
) : user.authProvider === 'local' ? (
<>
<button
onClick={() => showEditDialog(user)}
className="inline-flex items-center gap-1 text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
<span>Edit Role</span>
</button>
<button
onClick={() => showDeleteDialog(user)}
className="inline-flex items-center gap-1 text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300"
title="Delete user and all their requests"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
<span>Delete</span>
</button>
</>
) : (
<button
onClick={() => showEditDialog(user)}
className="inline-flex items-center gap-1 text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
<span>Edit Role</span>
</button>
)}
</div>
<UserActionsCell user={user} onEdit={showEditDialog} onDelete={showDeleteDialog} />
</td>
</tr>
))}
@@ -643,31 +749,50 @@ function AdminUsersPageContent() {
<ul className="text-sm text-blue-700 dark:text-blue-300 space-y-1">
<li> <strong>User:</strong> Can request audiobooks, view own requests, and search the catalog</li>
<li> <strong>Admin:</strong> Full system access including settings, user management, and all requests</li>
<li> <strong>Setup Admin:</strong> The initial admin account created during setup - this account is protected and cannot be changed or deleted</li>
<li> <strong>Permissions:</strong> Click a user&apos;s permission badge to manage individual settings (auto-approve, interactive search). Use Global User Permissions to control system-wide defaults. Admins always have full access.</li>
<li> <strong>OIDC Users:</strong> Role management is handled by the identity provider - use admin role mapping in OIDC settings. Cannot be deleted as access is managed externally.</li>
<li> <strong>Plex Users:</strong> Can have their roles changed, but cannot be deleted as access is managed by Plex.</li>
<li> <strong>Local Users:</strong> Can be freely assigned user or admin roles (except setup admin). Can be deleted (their requests are preserved for historical records).</li>
<li> <strong>Setup Admin:</strong> The initial admin account protected, cannot be changed or deleted</li>
<li> <strong>Permissions:</strong> Click a user&apos;s permission badge to manage individual settings. Use Global User Permissions for system-wide defaults. Admins always have full access.</li>
<li> <strong>OIDC Users:</strong> Role management is handled by the identity provider. Cannot be deleted.</li>
<li> <strong>Plex Users:</strong> Role can be changed, but cannot be deleted (access managed by Plex).</li>
<li> <strong>Local Users:</strong> Can have roles freely assigned. Can be deleted (requests are preserved).</li>
<li> You cannot change your own role or delete yourself for security reasons</li>
</ul>
</div>
{/* Edit User Dialog */}
{/* Edit User Dialog — bottom sheet on mobile */}
{editDialog.isOpen && editDialog.user && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 p-4">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">
Edit User Role
</h3>
<div className="space-y-4 mb-6">
<div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black bg-opacity-50 p-0 sm:p-4">
<div className="bg-white dark:bg-gray-800 rounded-t-2xl sm:rounded-2xl shadow-xl w-full sm:max-w-md">
{/* Dialog header */}
<div className="sticky top-0 bg-white dark:bg-gray-800 px-5 py-4 border-b border-gray-200 dark:border-gray-700 rounded-t-2xl flex items-center justify-between">
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
Edit User Role
</h3>
<button
onClick={hideEditDialog}
className="p-2 -mr-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
aria-label="Close dialog"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<div className="px-5 py-5 space-y-4">
{/* User Info */}
<div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
{editDialog.user.avatarUrl && (
<div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-xl">
{editDialog.user.avatarUrl ? (
<img
src={editDialog.user.avatarUrl}
alt={editDialog.user.plexUsername}
className="h-12 w-12 rounded-full"
className="h-12 w-12 rounded-full flex-shrink-0"
/>
) : (
<div className="h-12 w-12 rounded-full flex-shrink-0 bg-gray-200 dark:bg-gray-600 flex items-center justify-center">
<svg className="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
</div>
)}
<div>
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
@@ -685,38 +810,34 @@ function AdminUsersPageContent() {
Role
</label>
<div className="space-y-2">
<label className="flex items-start gap-3 p-3 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer">
<label className="flex items-start gap-3 p-3 border border-gray-300 dark:border-gray-600 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer transition-colors">
<input
type="radio"
name="role"
value="user"
checked={editRole === 'user'}
onChange={(e) => setEditRole(e.target.value as 'user' | 'admin')}
className="mt-1 w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600"
className="mt-1 w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 flex-shrink-0"
/>
<div className="flex-1">
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
User
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">User</div>
<div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
Can request audiobooks and view own requests
</div>
</div>
</label>
<label className="flex items-start gap-3 p-3 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer">
<label className="flex items-start gap-3 p-3 border border-gray-300 dark:border-gray-600 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer transition-colors">
<input
type="radio"
name="role"
value="admin"
checked={editRole === 'admin'}
onChange={(e) => setEditRole(e.target.value as 'user' | 'admin')}
className="mt-1 w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600"
className="mt-1 w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 flex-shrink-0"
/>
<div className="flex-1">
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
Admin
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">Admin</div>
<div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
Full system access including settings and user management
</div>
</div>
@@ -725,19 +846,19 @@ function AdminUsersPageContent() {
</div>
</div>
{/* Actions */}
<div className="flex justify-end gap-3">
{/* Dialog footer */}
<div className="sticky bottom-0 bg-white dark:bg-gray-800 px-5 py-4 border-t border-gray-200 dark:border-gray-700 flex gap-3">
<button
onClick={hideEditDialog}
disabled={saving}
className="px-4 py-2 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
className="flex-1 px-4 py-2.5 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed"
>
Cancel
</button>
<button
onClick={saveUserRole}
disabled={saving}
className="px-4 py-2 text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
className="flex-1 px-4 py-2.5 text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed"
>
{saving ? 'Saving...' : 'Save Changes'}
</button>
@@ -14,6 +14,7 @@ const logger = RMABLogger.create('API.Admin.Requests.Approve');
const ApprovalActionSchema = z.object({
action: z.enum(['approve', 'deny']),
selectedTorrent: z.any().optional(),
});
/**
@@ -37,8 +38,8 @@ export async function POST(
const { id } = await params;
const body = await request.json();
// Validate action
const { action } = ApprovalActionSchema.parse(body);
// Validate action and optional admin-selected torrent
const { action, selectedTorrent: adminSelectedTorrent } = ApprovalActionSchema.parse(body);
// Fetch the request
const existingRequest = await prisma.request.findUnique({
@@ -78,12 +79,15 @@ export async function POST(
const jobQueue = getJobQueueService();
const isEbookRequest = existingRequest.type === 'ebook';
// Check if request has a pre-selected torrent (from interactive search)
if (existingRequest.selectedTorrent) {
const selectedTorrent = existingRequest.selectedTorrent as any;
// Use admin-provided torrent (from admin interactive search) or fall back to user's pre-selected torrent
const effectiveTorrent = adminSelectedTorrent || existingRequest.selectedTorrent;
// User pre-selected a specific torrent - download that torrent directly
logger.info(`Request ${id} has pre-selected torrent, starting download`, {
if (effectiveTorrent) {
const selectedTorrent = effectiveTorrent as any;
const torrentSource = adminSelectedTorrent ? 'admin' : 'user';
// Download the selected torrent directly
logger.info(`Request ${id} has ${torrentSource}-selected torrent, starting download`, {
requestId: id,
userId: existingRequest.userId,
adminId: req.user.sub,
@@ -167,17 +171,20 @@ export async function POST(
logger.error('Failed to queue notification', { error: error instanceof Error ? error.message : String(error) });
});
logger.info(`Request ${id} approved by admin ${req.user.sub}, downloading pre-selected torrent`, {
logger.info(`Request ${id} approved by admin ${req.user.sub}, downloading ${torrentSource}-selected torrent`, {
requestId: id,
userId: updatedRequest.userId,
audiobookTitle: existingRequest.audiobook.title,
adminId: req.user.sub,
type: existingRequest.type,
torrentSource,
});
return NextResponse.json({
success: true,
message: 'Request approved and download started with pre-selected torrent',
message: adminSelectedTorrent
? 'Request approved and download started with admin-selected torrent'
: 'Request approved and download started with pre-selected torrent',
request: updatedRequest,
});
} else {
+29 -1
View File
@@ -15,7 +15,7 @@ export async function PUT(request: NextRequest) {
return requireAuth(request, async (req: AuthenticatedRequest) => {
return requireAdmin(req, async () => {
try {
const { downloadDir, mediaDir, audiobookPathTemplate, ebookPathTemplate, metadataTaggingEnabled, chapterMergingEnabled } = await request.json();
const { downloadDir, mediaDir, audiobookPathTemplate, ebookPathTemplate, metadataTaggingEnabled, chapterMergingEnabled, fileRenameEnabled, fileRenameTemplate } = await request.json();
if (!downloadDir || !mediaDir) {
return NextResponse.json(
@@ -97,6 +97,32 @@ export async function PUT(request: NextRequest) {
},
});
// Update file rename setting
await prisma.configuration.upsert({
where: { key: 'file_rename_enabled' },
update: { value: String(fileRenameEnabled ?? false) },
create: {
key: 'file_rename_enabled',
value: String(fileRenameEnabled ?? false),
category: 'automation',
description: 'Rename audio and ebook files using a custom naming template during organization',
},
});
// Update file rename template
if (fileRenameTemplate !== undefined) {
await prisma.configuration.upsert({
where: { key: 'file_rename_template' },
update: { value: fileRenameTemplate },
create: {
key: 'file_rename_template',
value: fileRenameTemplate,
category: 'automation',
description: 'Template for renaming audio and ebook files during organization',
},
});
}
logger.info('Paths settings updated');
// Clear config cache for all updated keys so services get fresh values
@@ -107,6 +133,8 @@ export async function PUT(request: NextRequest) {
configService.clearCache('ebook_path_template');
configService.clearCache('metadata_tagging_enabled');
configService.clearCache('chapter_merging_enabled');
configService.clearCache('file_rename_enabled');
configService.clearCache('file_rename_template');
// Invalidate all download client singletons to force reload of download_dir
const { invalidateDownloadClientManager } = await import('@/lib/services/download-client-manager.service');
+2
View File
@@ -128,6 +128,8 @@ export async function GET(request: NextRequest) {
ebookPathTemplate: configMap.get('ebook_path_template') || configMap.get('audiobook_path_template') || '{author}/{title} {asin}',
metadataTaggingEnabled: configMap.get('metadata_tagging_enabled') === 'true',
chapterMergingEnabled: configMap.get('chapter_merging_enabled') === 'true',
fileRenameEnabled: configMap.get('file_rename_enabled') === 'true',
fileRenameTemplate: configMap.get('file_rename_template') || '{title}',
},
ebook: {
// New granular source toggles (with migration from legacy ebook_sidecar_enabled)
-38
View File
@@ -1,38 +0,0 @@
/**
* Component: Configuration API Routes (by category)
* Documentation: documentation/backend/services/config.md
*/
import { NextRequest, NextResponse } from 'next/server';
import { getConfigService } from '@/lib/services/config.service';
import { RMABLogger } from '@/lib/utils/logger';
const logger = RMABLogger.create('API.Config.Category');
// GET /api/config/:category - Get all config for a category
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ category: string }> }
) {
try {
// TODO: Add authentication middleware - admin only
const { category } = await params;
const configService = getConfigService();
const config = await configService.getCategory(category);
return NextResponse.json({
category,
config,
});
} catch (error) {
logger.error('Failed to get config for category', { error: error instanceof Error ? error.message : String(error) });
return NextResponse.json(
{
error: 'Failed to get configuration',
message: error instanceof Error ? error.message : 'Unknown error',
},
{ status: 500 }
);
}
}
-84
View File
@@ -1,84 +0,0 @@
/**
* Component: Configuration API Routes
* Documentation: documentation/backend/services/config.md
*/
import { NextRequest, NextResponse } from 'next/server';
import { getConfigService, ConfigUpdate } from '@/lib/services/config.service';
import { z } from 'zod';
import { RMABLogger } from '@/lib/utils/logger';
const logger = RMABLogger.create('API.Config');
const ConfigUpdateSchema = z.object({
updates: z.array(
z.object({
key: z.string(),
value: z.string(),
encrypted: z.boolean().optional(),
category: z.string().optional(),
description: z.string().optional(),
})
),
});
// PUT /api/config - Update multiple configuration values
export async function PUT(request: NextRequest) {
try {
// TODO: Add authentication middleware - admin only
const body = await request.json();
const { updates } = ConfigUpdateSchema.parse(body);
const configService = getConfigService();
await configService.setMany(updates as ConfigUpdate[]);
return NextResponse.json({
success: true,
updated: updates.length,
});
} catch (error) {
logger.error('Failed to update configuration', { error: error instanceof Error ? error.message : String(error) });
if (error instanceof z.ZodError) {
return NextResponse.json(
{
error: 'Validation error',
details: error.errors,
},
{ status: 400 }
);
}
return NextResponse.json(
{
error: 'Failed to update configuration',
message: error instanceof Error ? error.message : 'Unknown error',
},
{ status: 500 }
);
}
}
// GET /api/config - Get all configuration (masked sensitive values)
export async function GET() {
try {
// TODO: Add authentication middleware - admin only
const configService = getConfigService();
const allConfig = await configService.getAll();
return NextResponse.json({
config: allConfig,
});
} catch (error) {
logger.error('Failed to get all configuration', { error: error instanceof Error ? error.message : String(error) });
return NextResponse.json(
{
error: 'Failed to get configuration',
message: error instanceof Error ? error.message : 'Unknown error',
},
{ status: 500 }
);
}
}
@@ -67,8 +67,8 @@ export async function POST(
);
}
// Check if request is awaiting approval
if (requestRecord.status === 'awaiting_approval') {
// Check if request is awaiting approval (admins can still search to override the user's selection)
if (requestRecord.status === 'awaiting_approval' && req.user.role !== 'admin') {
return NextResponse.json(
{ error: 'AwaitingApproval', message: 'This request is awaiting admin approval. You cannot search for torrents until it is approved.' },
{ status: 403 }
@@ -29,6 +29,7 @@ export function DownloadClientCard({ client, onEdit, onDelete }: DownloadClientC
transmission: 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300',
sabnzbd: 'bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300',
nzbget: 'bg-orange-100 dark:bg-orange-900/30 text-orange-700 dark:text-orange-300',
deluge: 'bg-teal-100 dark:bg-teal-900/30 text-teal-700 dark:text-teal-300',
};
const typeColor = typeColorMap[client.type] || typeColorMap.qbittorrent;
@@ -253,7 +253,7 @@ export function DownloadClientManagement({
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-3">
Add Download Client
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4">
{/* qBittorrent Card */}
<div className={`bg-white dark:bg-gray-800 rounded-lg shadow-md border border-gray-200 dark:border-gray-700 p-6${hasTorrentClient ? ' opacity-50' : ''}`}>
<div className="flex items-start justify-between mb-3">
@@ -316,15 +316,15 @@ export function DownloadClientManagement({
)}
</div>
{/* RDT-Client Card */}
{/* Deluge Card */}
<div className={`bg-white dark:bg-gray-800 rounded-lg shadow-md border border-gray-200 dark:border-gray-700 p-6${hasTorrentClient ? ' opacity-50' : ''}`}>
<div className="flex items-start justify-between mb-3">
<div>
<h4 className="text-base font-semibold text-gray-900 dark:text-gray-100 mb-1">
RDT-Client
Deluge
</h4>
<p className="text-sm text-gray-600 dark:text-gray-400">
Torrent / Debrid
Torrent downloads
</p>
</div>
<span className="inline-block text-xs px-2 py-1 rounded bg-teal-100 dark:bg-teal-900/30 text-teal-700 dark:text-teal-300 font-medium">
@@ -337,12 +337,12 @@ export function DownloadClientManagement({
</div>
) : (
<Button
onClick={() => handleAddClient('rdtclient')}
onClick={() => handleAddClient('deluge')}
variant="primary"
size="sm"
disabled={loading}
>
Add RDT-Client
Add Deluge
</Button>
)}
</div>
@@ -278,7 +278,7 @@ export function DownloadClientModal({
type,
name,
url,
username: type !== 'sabnzbd' ? username : undefined,
username: type !== 'sabnzbd' && type !== 'deluge' ? username : undefined,
password: password === '********' ? undefined : password, // Don't send masked password on edit
enabled,
disableSSLVerify,
@@ -338,7 +338,7 @@ export function DownloadClientModal({
<Input
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder={type === 'rdtclient' ? 'http://localhost:6500' : type === 'transmission' ? 'http://localhost:9091' : type === 'qbittorrent' ? 'http://localhost:8080' : type === 'nzbget' ? 'http://localhost:6789' : 'http://localhost:8081'}
placeholder={type === 'transmission' ? 'http://localhost:9091' : type === 'qbittorrent' ? 'http://localhost:8080' : type === 'deluge' ? 'http://localhost:8112' : type === 'nzbget' ? 'http://localhost:6789' : 'http://localhost:8081'}
error={errors.url}
/>
<p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
@@ -346,8 +346,8 @@ export function DownloadClientModal({
</p>
</div>
{/* Username (qBittorrent and Transmission) */}
{type !== 'sabnzbd' && (
{/* Username (qBittorrent, Transmission, NZBGet — not SABnzbd or Deluge) */}
{type !== 'sabnzbd' && type !== 'deluge' && (
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Username
@@ -383,6 +383,11 @@ export function DownloadClientModal({
Configured in NZBGet under Settings Security ControlPassword
</p>
)}
{type === 'deluge' && (
<p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
Web UI password configured in Deluge under Preferences Interface
</p>
)}
</div>
{/* SSL Verification */}
@@ -448,7 +453,7 @@ export function DownloadClientModal({
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Post-Import Category
</label>
{type === 'qbittorrent' && availableCategories.length > 0 ? (
{(type === 'qbittorrent' || type === 'deluge') && availableCategories.length > 0 ? (
<select
value={postImportCategory}
onChange={(e) => setPostImportCategory(e.target.value)}
@@ -38,6 +38,7 @@ interface InteractiveTorrentSearchModalProps {
onSuccess?: () => void;
searchMode?: 'audiobook' | 'ebook'; // Search mode - defaults to audiobook
replaceIssueId?: string; // Optional - when set, confirm handler calls replace endpoint instead
onConfirm?: (torrent: TorrentResult) => Promise<void>; // Optional - overrides default confirm handler
}
// Format relative time from publish date
@@ -90,6 +91,7 @@ export function InteractiveTorrentSearchModal({
onSuccess,
searchMode = 'audiobook',
replaceIssueId,
onConfirm,
}: InteractiveTorrentSearchModalProps) {
// Hooks for existing audiobook request flow
const { searchTorrents: searchByRequestId, isLoading: isSearchingByRequest, error: searchByRequestError } = useInteractiveSearch();
@@ -113,6 +115,7 @@ export function InteractiveTorrentSearchModal({
const [results, setResults] = useState<(RankedTorrent & { qualityScore?: number; source?: string; ebookFormat?: string })[]>([]);
const [confirmTorrent, setConfirmTorrent] = useState<TorrentResult | null>(null);
const [searchTitle, setSearchTitle] = useState(audiobook.title);
const [isCustomConfirming, setIsCustomConfirming] = useState(false);
const [mounted, setMounted] = useState(false);
// Stable close handler via ref
@@ -130,11 +133,13 @@ export function InteractiveTorrentSearchModal({
const isSearching = isEbookMode
? (useAsinMode ? isSearchingEbooksByAsin : isSearchingEbooks)
: (hasRequestId ? isSearchingByRequest : isSearchingByAudiobook);
const isDownloading = replaceIssueId
? isReplacing
: isEbookMode
? (useAsinMode ? isSelectingEbookByAsin : isSelectingEbook)
: (hasRequestId ? isSelectingTorrent : isRequestingWithTorrent);
const isDownloading = isCustomConfirming
? true
: replaceIssueId
? isReplacing
: isEbookMode
? (useAsinMode ? isSelectingEbookByAsin : isSelectingEbook)
: (hasRequestId ? isSelectingTorrent : isRequestingWithTorrent);
const error = replaceIssueId
? (replaceError || (hasRequestId ? searchByRequestError : searchByAudiobookError))
: isEbookMode
@@ -218,7 +223,11 @@ export function InteractiveTorrentSearchModal({
const handleConfirmDownload = async () => {
if (!confirmTorrent) return;
try {
if (replaceIssueId) {
if (onConfirm) {
// Custom confirm handler (e.g., admin approve-with-torrent flow)
setIsCustomConfirming(true);
await onConfirm(confirmTorrent);
} else if (replaceIssueId) {
// Reported issue replacement flow
await replaceWithTorrent(replaceIssueId, confirmTorrent);
} else if (isEbookMode) {
@@ -241,6 +250,8 @@ export function InteractiveTorrentSearchModal({
} catch (err) {
console.error('Failed to download:', err);
setConfirmTorrent(null);
} finally {
setIsCustomConfirming(false);
}
};
+10
View File
@@ -0,0 +1,10 @@
/**
* Component: Download Client Timeout Constants
* Documentation: documentation/phase3/download-clients.md
*
* Some indexers (e.g. YGGtorrent) enforce a ~30s wait before allowing
* .torrent file downloads. 60s gives sufficient headroom.
*/
/** Timeout for download client API calls and .torrent file fetches (ms) */
export const DOWNLOAD_CLIENT_TIMEOUT = 60000;
+35 -1
View File
@@ -16,7 +16,7 @@ import type { AudibleRegion } from '../types/audible';
// Types
// ---------------------------------------------------------------------------
export type SupportedLanguage = 'en' | 'de' | 'es';
export type SupportedLanguage = 'en' | 'de' | 'es' | 'fr';
export interface ScrapingConfig {
/** Audible locale query-param value (e.g. 'english', 'deutsch') */
@@ -170,6 +170,38 @@ const SPANISH_CONFIG: LanguageConfig = {
},
};
const FRENCH_CONFIG: LanguageConfig = {
code: 'fr',
annasArchiveLang: 'fr',
epubCode: 'fr',
stopWords: ['le', 'la', 'les', 'un', 'une', 'de', 'des', 'sur', 'dans', '\u00e0', 'et', 'par', 'pour'],
characterReplacements: {},
scraping: {
audibleLocaleParam: 'français',
authorPrefixes: ['De :', '\u00c9crit par :', 'Auteur :'],
narratorPrefixes: ['Lu par :'],
lengthLabels: ['Dur\u00e9e :'],
languageLabels: ['Langue :'],
releaseDateLabels: ['Date de publication :'],
seriesLabels: ['S\u00e9rie :'],
acceptedLanguageValues: ['français', 'french'],
runtimeHourPatterns: [/(\d+)\s*h\b/i, /(\d+)\s*heures?/i],
runtimeMinutePatterns: [/(\d+)\s*min/i, /(\d+)\s*minutes?/i],
ratingPatterns: [/(\d+[.,]?\d*)\s*de\s*5/i],
releaseDatePatterns: [/Date de publication:\s*(.+)/i],
descriptionExcludePatterns: [
/\$\d+\.\d+/,
/\d+,\d+\s*\u20ac/,
/Essayer pour/i,
/R\u00e9siliez \u00e0 tout moment/i,
/Acheter pour/i,
/^\s*de\s+[\w\s,]+$/i,
],
durationDetectionPattern: /\d+\s*(h|heures?)\s*\d*\s*(min|minutes?)?/i,
ratingTextSelector: 'sur 5 étoiles',
},
};
// ---------------------------------------------------------------------------
// Lookup Maps
// ---------------------------------------------------------------------------
@@ -178,6 +210,7 @@ export const LANGUAGE_CONFIGS: Record<SupportedLanguage, LanguageConfig> = {
en: ENGLISH_CONFIG,
de: GERMAN_CONFIG,
es: SPANISH_CONFIG,
fr: FRENCH_CONFIG,
};
/**
@@ -192,6 +225,7 @@ export const REGION_LANGUAGE_MAP: Record<AudibleRegion, SupportedLanguage> = {
in: 'en',
de: 'de',
es: 'es',
fr: 'fr',
};
// ---------------------------------------------------------------------------
+5 -3
View File
@@ -414,10 +414,12 @@ function parseSeriesBooks(
if (!bookAsin || seenAsins.has(bookAsin)) return;
seenAsins.add(bookAsin);
// Title
const title = $el.find('h2').first().text().trim() ||
$el.find('h3 a').first().text().trim() ||
// Title: h3 a / .bc-heading a hold the real book title;
// h2 on series pages is the position label ("Book 1"), so try it last.
const title = $el.find('h3 a').first().text().trim() ||
$el.find('.bc-heading a').first().text().trim() ||
$el.find('h2 a').first().text().trim() ||
$el.find('h2').first().text().trim() ||
'';
if (!title) return;
+386
View File
@@ -0,0 +1,386 @@
/**
* Component: Deluge Integration Service
* Documentation: documentation/phase3/download-clients.md
*/
import axios, { AxiosInstance } from 'axios';
import https from 'https';
import path from 'path';
import { DOWNLOAD_CLIENT_TIMEOUT } from '../constants/download-timeouts';
import * as parseTorrentModule from 'parse-torrent';
import { RMABLogger } from '../utils/logger';
import { PathMapper, PathMappingConfig } from '../utils/path-mapper';
import {
IDownloadClient, DownloadClientType, ProtocolType,
DownloadInfo, DownloadStatus, AddDownloadOptions, ConnectionTestResult,
} from '../interfaces/download-client.interface';
const parseTorrent = (parseTorrentModule as any).default || parseTorrentModule;
const logger = RMABLogger.create('Deluge');
export class DelugeService implements IDownloadClient {
readonly clientType: DownloadClientType = 'deluge';
readonly protocol: ProtocolType = 'torrent';
private client: AxiosInstance;
private baseUrl: string;
private password: string;
private defaultSavePath: string;
private defaultCategory: string;
private pathMappingConfig: PathMappingConfig;
private sessionCookie: string = '';
private requestId: number = 0;
constructor(
baseUrl: string,
_username: string, // Unused — Deluge uses password-only auth; kept for consistent signature
password: string,
defaultSavePath: string = '/downloads',
defaultCategory: string = 'readmeabook',
disableSSLVerify: boolean = false,
pathMappingConfig?: PathMappingConfig
) {
this.baseUrl = baseUrl.replace(/\/$/, '');
this.password = password;
this.defaultSavePath = defaultSavePath;
this.defaultCategory = defaultCategory;
this.pathMappingConfig = pathMappingConfig || { enabled: false, remotePath: '', localPath: '' };
const httpsAgent = disableSSLVerify && this.baseUrl.startsWith('https')
? new https.Agent({ rejectUnauthorized: false }) : undefined;
if (httpsAgent) logger.info('[Deluge] SSL certificate verification disabled');
this.client = axios.create({ baseURL: this.baseUrl, timeout: DOWNLOAD_CLIENT_TIMEOUT, httpsAgent });
}
/** JSON-RPC call with automatic re-authentication on auth failure */
private async rpc(method: string, params: any[] = [], retried = false): Promise<any> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (this.sessionCookie) headers['Cookie'] = this.sessionCookie;
try {
const reqId = ++this.requestId;
const { data } = await this.client.post('/json', { method, params, id: reqId }, { headers });
// Deluge error.code === 1: "Not authenticated" — re-login then retry
if (data.error?.code === 1 && !retried) {
await this.login();
return this.rpc(method, params, true);
}
// Deluge error.code === 2: "Unknown method" — daemon disconnected, force reconnect
// Only retry for core.* methods — plugin methods (label.*) fail because the plugin
// isn't enabled, not because the daemon is disconnected.
if (data.error?.code === 2 && !retried && method.startsWith('core.')) {
await this.login(true);
return this.rpc(method, params, true);
}
return data;
} catch (error) {
if (!retried) { await this.login(); return this.rpc(method, params, true); }
throw error;
}
}
private async login(forceReconnect: boolean = false): Promise<void> {
const { data, headers } = await this.client.post(
'/json',
{ method: 'auth.login', params: [this.password], id: ++this.requestId },
{ headers: { 'Content-Type': 'application/json' } }
);
if (!data?.result) throw new Error('Failed to authenticate with Deluge — check your password');
const cookies = headers['set-cookie'];
if (cookies?.length) this.sessionCookie = cookies[0].split(';')[0];
logger.info('Successfully authenticated with Deluge');
// Deluge Web UI requires a daemon connection before core.* methods work.
// When forceReconnect is true, skip the web.connected check and force a fresh connection.
await this.ensureDaemonConnected(forceReconnect);
}
/**
* Ensure the Web UI is connected to a deluged daemon host.
* Uses web.connected (returns boolean) as the check daemon.info is NOT a valid
* method through the Deluge Web UI JSON-RPC; only web.* and core.* methods work.
*/
private async ensureDaemonConnected(force: boolean = false): Promise<void> {
if (!force) {
const test = await this.rpc('web.connected', [], true);
if (test.result === true) return;
}
logger.info('Connecting to daemon...');
const hostsData = await this.rpc('web.get_hosts', [], true);
const hosts: any[] = hostsData.result || [];
if (hosts.length === 0) {
throw new Error('Deluge has no daemon hosts configured. Add a host in the Deluge Web UI under Connection Manager.');
}
const hostId = hosts[0][0];
const connectResult = await this.rpc('web.connect', [hostId], true);
if (connectResult.error) {
throw new Error(`Failed to connect to Deluge daemon: ${connectResult.error.message}`);
}
// Verify connection is established
const verify = await this.rpc('web.connected', [], true);
if (verify.result !== true) {
throw new Error('Deluge daemon failed to respond after web.connect. Check that deluged is running.');
}
logger.info('Connected to Deluge daemon');
}
// =========================================================================
// IDownloadClient Implementation
// =========================================================================
async testConnection(): Promise<ConnectionTestResult> {
try {
await this.login();
return { success: true, message: 'Connected to Deluge' };
} catch (error) {
const msg = error instanceof Error ? error.message : 'Connection failed';
if (axios.isAxiosError(error)) {
const c = error.code;
if (c?.includes('CERT') || c?.includes('SSL')) return { success: false, message: `SSL verification failed (${c}). Enable "Disable SSL Verification".` };
if (c === 'ECONNREFUSED') return { success: false, message: `Connection refused at: ${this.baseUrl}` };
if (c === 'ETIMEDOUT' || c === 'ECONNABORTED') return { success: false, message: `Connection timeout: ${this.baseUrl}` };
if (c === 'ENOTFOUND') return { success: false, message: `Host not found: ${this.baseUrl}` };
if (error.response?.status === 401) return { success: false, message: 'Authentication failed. Check your password.' };
}
logger.error('Connection test failed', { error: msg });
return { success: false, message: msg };
}
}
async addDownload(url: string, options?: AddDownloadOptions): Promise<string> {
if (!url || typeof url !== 'string' || url.trim() === '') {
throw new Error('Invalid download URL: URL is required and must be a non-empty string');
}
const category = options?.category || this.defaultCategory;
return url.startsWith('magnet:')
? this.addMagnetLink(url, category, options)
: this.addTorrentFile(url, category, options);
}
private async addMagnetLink(magnetUrl: string, category: string, options?: AddDownloadOptions): Promise<string> {
const infoHash = this.extractHashFromMagnet(magnetUrl);
if (!infoHash) throw new Error('Invalid magnet link - could not extract info_hash');
logger.info(`Extracted info_hash from magnet: ${infoHash}`);
const existing = await this.rpc('core.get_torrent_status', [infoHash, ['name']]);
if (existing.result && Object.keys(existing.result).length > 0) {
logger.info(`Torrent ${infoHash} already exists (duplicate)`);
return infoHash;
}
const opts = this.buildTorrentOptions(options?.paused);
const data = await this.rpc('core.add_torrent_magnet', [magnetUrl, opts]);
if (!data.result) throw new Error(`Deluge rejected magnet link: ${data.error?.message || 'unknown error'}`);
await this.postAddSetup(data.result, category);
logger.info(`Successfully added magnet link: ${infoHash}`);
return infoHash;
}
private async addTorrentFile(torrentUrl: string, category: string, options?: AddDownloadOptions): Promise<string> {
logger.info(`Downloading .torrent file from: ${torrentUrl}`);
let torrentResponse;
try {
torrentResponse = await axios.get(torrentUrl, {
responseType: 'arraybuffer', maxRedirects: 0,
validateStatus: (s) => s >= 200 && s < 300, timeout: DOWNLOAD_CLIENT_TIMEOUT,
});
if (torrentResponse.data.length > 0) {
const magnetMatch = torrentResponse.data.toString().match(/^magnet:\?[^\s]+$/);
if (magnetMatch) return this.addMagnetLink(magnetMatch[0], category, options);
}
} catch (error) {
if (!axios.isAxiosError(error) || !error.response) throw error;
const status = error.response.status;
if (status >= 300 && status < 400) {
const loc = error.response.headers['location'];
if (loc?.startsWith('magnet:')) return this.addMagnetLink(loc, category, options);
if (loc?.startsWith('http://') || loc?.startsWith('https://')) {
try { torrentResponse = await axios.get(loc, { responseType: 'arraybuffer', timeout: DOWNLOAD_CLIENT_TIMEOUT, maxRedirects: 5 }); }
catch { throw new Error('Failed to download torrent file after redirect'); }
} else { throw new Error(`Invalid redirect location: ${loc}`); }
} else { throw new Error(`Failed to download torrent: HTTP ${status}`); }
}
const torrentBuffer = Buffer.from(torrentResponse.data);
let parsed: any;
try { parsed = await parseTorrent(torrentBuffer); }
catch { throw new Error('Invalid .torrent file - failed to parse'); }
const infoHash = parsed.infoHash;
if (!infoHash) throw new Error('Failed to extract info_hash from .torrent file');
logger.info(`Extracted info_hash: ${infoHash}`);
const existing = await this.rpc('core.get_torrent_status', [infoHash, ['name']]);
if (existing.result && Object.keys(existing.result).length > 0) {
logger.info(`Torrent ${infoHash} already exists (duplicate)`);
return infoHash;
}
const filename = parsed.name ? `${parsed.name}.torrent` : 'torrent.torrent';
const opts = this.buildTorrentOptions(options?.paused);
const data = await this.rpc('core.add_torrent_file', [filename, torrentBuffer.toString('base64'), opts]);
if (!data.result) throw new Error(`Deluge rejected .torrent file: ${data.error?.message || 'unknown error'}`);
await this.postAddSetup(infoHash, category);
logger.info(`Successfully added torrent: ${infoHash}`);
return infoHash;
}
async getDownload(id: string): Promise<DownloadInfo | null> {
const fields = ['name', 'total_size', 'total_done', 'progress', 'state',
'download_payload_rate', 'eta', 'label', 'save_path',
'time_added', 'is_finished', 'seeding_time', 'ratio', 'message'];
for (let attempt = 0; attempt <= 3; attempt++) {
const { result } = await this.rpc('core.get_torrent_status', [id, fields]);
if (result && Object.keys(result).length > 0) return this.mapToDownloadInfo(id, result);
if (attempt === 3) return null;
const delay = 500 * Math.pow(2, attempt);
logger.warn(`Torrent ${id} not found, retrying in ${delay}ms (${attempt + 1}/3)`);
await new Promise(r => setTimeout(r, delay));
}
return null;
}
async pauseDownload(id: string): Promise<void> {
await this.rpc('core.pause_torrent', [[id]]);
logger.info(`Paused torrent: ${id}`);
}
async resumeDownload(id: string): Promise<void> {
await this.rpc('core.resume_torrent', [[id]]);
logger.info(`Resumed torrent: ${id}`);
}
async deleteDownload(id: string, deleteFiles: boolean = false): Promise<void> {
await this.rpc('core.remove_torrent', [id, deleteFiles]);
logger.info(`Deleted torrent: ${id}`);
}
async postProcess(_id: string): Promise<void> {} // No-op: seeding cleanup scheduler manages lifecycle
async getCategories(): Promise<string[]> {
try { const { result } = await this.rpc('label.get_labels'); return Array.isArray(result) ? result : []; }
catch { return []; }
}
async setCategory(id: string, category: string): Promise<void> {
await this.applyLabel(id, category);
logger.info(`Set label for torrent ${id}: ${category}`);
}
// =========================================================================
// Internal Helpers
// =========================================================================
private buildTorrentOptions(paused?: boolean): Record<string, any> {
const remoteSavePath = PathMapper.reverseTransform(this.defaultSavePath, this.pathMappingConfig);
const opts: Record<string, any> = { download_location: remoteSavePath, move_completed: false, move_completed_path: '' };
if (paused) opts.add_paused = true;
return opts;
}
private async postAddSetup(hash: string, category: string): Promise<void> {
await this.disableSeedLimits(hash);
await this.applyLabel(hash, category);
}
private async applyLabel(hash: string, label: string): Promise<void> {
try {
try { await this.rpc('label.add', [label]); } catch { /* may already exist */ }
await this.rpc('label.set_torrent', [hash, label]);
} catch (error) {
logger.warn(`Failed to apply label "${label}" to ${hash}: ${error instanceof Error ? error.message : String(error)}`);
}
}
private async disableSeedLimits(hash: string): Promise<void> {
try {
await this.rpc('core.set_torrent_options', [[hash], { stop_at_ratio: false, seed_time_limit: -1 }]);
} catch (error) {
logger.warn(`Failed to disable seed limits for ${hash}: ${error instanceof Error ? error.message : String(error)}`);
}
}
private mapToDownloadInfo(hash: string, t: Record<string, any>): DownloadInfo {
return {
id: hash, name: t.name || '', size: t.total_size || 0,
bytesDownloaded: t.total_done || 0, progress: (t.progress || 0) / 100,
status: this.mapStatus(t.state), downloadSpeed: t.download_payload_rate || 0,
eta: t.eta > 0 ? t.eta : 0, category: t.label || '',
downloadPath: t.save_path ? path.join(t.save_path, t.name || '') : undefined,
completedAt: t.is_finished && t.time_added ? new Date(t.time_added * 1000) : undefined,
errorMessage: t.message || undefined, seedingTime: t.seeding_time,
ratio: t.ratio >= 0 ? t.ratio : undefined,
};
}
private mapStatus(state: string): DownloadStatus {
const map: Record<string, DownloadStatus> = {
'Downloading': 'downloading', 'Seeding': 'seeding', 'Paused': 'paused',
'Checking': 'checking', 'Queued': 'queued', 'Error': 'failed', 'Moving': 'downloading',
};
return map[state] || 'downloading';
}
private extractHashFromMagnet(magnetUrl: string): string | null {
const match = magnetUrl.match(/xt=urn:btih:([a-fA-F0-9]{40}|[a-zA-Z0-9]{32})/i);
return match ? match[1].toLowerCase() : null;
}
}
// Singleton factory (matches Transmission/qBittorrent pattern)
let delugeServiceInstance: DelugeService | null = null;
let configLoaded = false;
export async function getDelugeService(): Promise<DelugeService> {
if (delugeServiceInstance && configLoaded) return delugeServiceInstance;
try {
const { getConfigService } = await import('../services/config.service');
const { getDownloadClientManager } = await import('../services/download-client-manager.service');
const configService = await getConfigService();
const manager = getDownloadClientManager(configService);
const clientConfig = await manager.getClientForProtocol('torrent');
if (!clientConfig) throw new Error('Deluge is not configured. Please configure a Deluge client in admin settings.');
if (clientConfig.type !== 'deluge') throw new Error(`Expected Deluge client but found ${clientConfig.type}`);
if (!clientConfig.url) throw new Error('Deluge is not fully configured. Check your configuration in admin settings.');
const baseDir = await configService.get('download_dir') || '/downloads';
const downloadDir = clientConfig.customPath ? require('path').join(baseDir, clientConfig.customPath) : baseDir;
delugeServiceInstance = new DelugeService(
clientConfig.url, clientConfig.username || '', clientConfig.password || '',
downloadDir, clientConfig.category || 'readmeabook', clientConfig.disableSSLVerify,
{ enabled: clientConfig.remotePathMappingEnabled || false, remotePath: clientConfig.remotePath || '', localPath: clientConfig.localPath || '' }
);
const result = await delugeServiceInstance.testConnection();
if (!result.success) throw new Error(result.message || 'Deluge connection test failed.');
logger.info('[Deluge] Connection test successful');
configLoaded = true;
return delugeServiceInstance;
} catch (error) {
logger.error('[Deluge] Failed to initialize service', { error: error instanceof Error ? error.message : String(error) });
delugeServiceInstance = null;
configLoaded = false;
throw error;
}
}
export function invalidateDelugeService(): void {
delugeServiceInstance = null;
configLoaded = false;
logger.info('[Deluge] Service singleton invalidated');
}
+3 -2
View File
@@ -5,6 +5,7 @@
import axios, { AxiosInstance } from 'axios';
import { XMLParser } from 'fast-xml-parser';
import { DOWNLOAD_CLIENT_TIMEOUT } from '../constants/download-timeouts';
import { TorrentResult } from '../utils/ranking-algorithm';
import { RMABLogger } from '../utils/logger';
@@ -87,7 +88,7 @@ export class ProwlarrService {
headers: {
'X-Api-Key': this.apiKey,
},
timeout: 60000, // 60 seconds - some indexers (e.g. yggtorrent) enforce a 30s wait before download
timeout: DOWNLOAD_CLIENT_TIMEOUT,
paramsSerializer: {
serialize: (params) => {
// Custom serializer to handle arrays correctly for Prowlarr API
@@ -314,7 +315,7 @@ export class ProwlarrService {
limit: 100,
extended: 1,
},
timeout: 60000,
timeout: DOWNLOAD_CLIENT_TIMEOUT,
responseType: 'text', // Get XML as text
});
+33 -8
View File
@@ -6,6 +6,7 @@
import axios, { AxiosInstance } from 'axios';
import https from 'https';
import path from 'path';
import { DOWNLOAD_CLIENT_TIMEOUT } from '../constants/download-timeouts';
import * as parseTorrentModule from 'parse-torrent';
import FormData from 'form-data';
import { RMABLogger } from '../utils/logger';
@@ -140,7 +141,7 @@ export class QBittorrentService implements IDownloadClient {
this.client = axios.create({
baseURL: `${this.baseUrl}/api/v2`,
timeout: 30000,
timeout: DOWNLOAD_CLIENT_TIMEOUT,
httpsAgent: this.httpsAgent,
// Support nginx/Apache reverse proxy with HTTP Basic Auth
auth: {
@@ -352,7 +353,7 @@ export class QBittorrentService implements IDownloadClient {
responseType: 'arraybuffer',
maxRedirects: 0,
validateStatus: (status) => status >= 200 && status < 300, // Only 2xx is success
timeout: 30000, // 30 seconds - public indexers can be slow
timeout: DOWNLOAD_CLIENT_TIMEOUT,
});
logger.info(` Got 2xx response, size=${torrentResponse.data.length} bytes`);
@@ -394,7 +395,7 @@ export class QBittorrentService implements IDownloadClient {
try {
torrentResponse = await axios.get(location, {
responseType: 'arraybuffer',
timeout: 30000,
timeout: DOWNLOAD_CLIENT_TIMEOUT,
maxRedirects: 5,
});
logger.info(` After following redirect: size=${torrentResponse.data.length} bytes`);
@@ -586,7 +587,19 @@ export class QBittorrentService implements IDownloadClient {
throw new Error(`Torrent ${hash} not found`);
}
return torrents[0];
// Find the torrent with the exact matching hash.
// Some qBittorrent-compatible clients (e.g. RDTClient) ignore the hashes
// filter and return all torrents, so we must verify the hash ourselves.
const normalizedHash = hash.toLowerCase();
const match = torrents.find(
(t: TorrentInfo) => t.hash?.toLowerCase() === normalizedHash
);
if (!match) {
throw new Error(`Torrent ${hash} not found`);
}
return match;
} catch (error) {
// Don't log error here - caller handles it (e.g., duplicate checking)
throw error;
@@ -1076,17 +1089,29 @@ export class QBittorrentService implements IDownloadClient {
* Map a TorrentInfo object to the unified DownloadInfo format.
*/
protected mapTorrentToDownloadInfo(torrent: TorrentInfo): DownloadInfo {
const status = this.mapStateToDownloadStatus(torrent.state);
// For completed/seeding torrents, always use save_path (the configured final destination)
// rather than content_path. When TempPathEnabled is active in qBittorrent, there is a race
// window where the torrent state transitions to uploading/seeding before the file move from
// the temp/incomplete directory to save_path finishes — content_path still references the
// stale temp location during this window, causing downstream ENOENT failures.
const isFinished = status === 'seeding' || status === 'completed';
const downloadPath = isFinished
? path.join(torrent.save_path, torrent.name)
: (torrent.content_path || path.join(torrent.save_path, torrent.name));
return {
id: torrent.hash,
name: torrent.name,
size: torrent.size,
bytesDownloaded: torrent.downloaded,
progress: torrent.progress,
status: this.mapStateToDownloadStatus(torrent.state),
status,
downloadSpeed: torrent.dlspeed,
eta: torrent.eta,
category: torrent.category,
downloadPath: torrent.content_path || path.join(torrent.save_path, torrent.name),
downloadPath,
completedAt: torrent.completion_on > 0 ? new Date(torrent.completion_on * 1000) : undefined,
seedingTime: torrent.seeding_time,
ratio: torrent.ratio,
@@ -1103,7 +1128,7 @@ export class QBittorrentService implements IDownloadClient {
stalledDL: 'downloading',
stalledUP: 'seeding',
pausedDL: 'paused',
// pausedUP = download finished, paused on upload side (e.g. RDT-Client, ratio met)
// pausedUP = download finished, paused on upload side (e.g. ratio met)
pausedUP: 'seeding',
queuedDL: 'queued',
queuedUP: 'seeding',
@@ -1158,7 +1183,7 @@ export class QBittorrentService implements IDownloadClient {
stalledDL: 'downloading',
stalledUP: 'completed',
pausedDL: 'paused',
// pausedUP = download finished, paused on upload side (e.g. RDT-Client, ratio met)
// pausedUP = download finished, paused on upload side (e.g. ratio met)
pausedUP: 'completed',
queuedDL: 'queued',
queuedUP: 'completed',
-105
View File
@@ -1,105 +0,0 @@
/**
* Component: RDT-Client Integration Service
* Documentation: documentation/phase3/download-clients.md
*
* RDT-Client is a Real-Debrid torrent proxy that emulates the qBittorrent API.
* Extends QBittorrentService and overrides behavioral differences:
* - Duplicate detection: deletes stale torrent before adding fresh (no false matches)
* - postProcess: removes torrent entry from client after files are organized
* - ensureCategory: no-op (RDT-Client doesn't support categories)
*/
import { RMABLogger } from '../utils/logger';
import { DownloadClientType } from '../interfaces/download-client.interface';
import { QBittorrentService, AddTorrentOptions } from './qbittorrent.service';
const logger = RMABLogger.create('RDTClient');
export class RDTClientService extends QBittorrentService {
override readonly clientType: DownloadClientType = 'rdtclient';
/**
* Override: Delete any existing torrent with the same hash before adding.
* RDT-Client can have stale entries from previous requests that cause
* false duplicate detection always start fresh.
*/
protected override async addMagnetLink(
magnetUrl: string,
category: string,
options?: AddTorrentOptions
): Promise<string> {
const infoHash = this.extractHashFromMagnet(magnetUrl);
if (infoHash) {
await this.deleteStaleIfExists(infoHash);
}
return super.addMagnetLink(magnetUrl, category, options);
}
/**
* Override: Delete any existing torrent with the same hash before adding.
* Same rationale as addMagnetLink prevent false duplicate short-circuits.
*/
protected override async addTorrentFile(
torrentUrl: string,
category: string,
options?: AddTorrentOptions
): Promise<string> {
// We can't pre-extract the hash from a .torrent URL without downloading it,
// so we let the parent handle the full flow. The parent's duplicate check
// calls getTorrent which will find any stale entry — but the parent
// short-circuits on duplicates. To handle this, we override addTorrentFile
// to intercept after the parent downloads and parses the torrent.
//
// The parent's addTorrentFile downloads the .torrent, parses it, checks for
// duplicates, then uploads. Since we can't hook into the middle of that flow
// without duplicating the download logic, we accept that .torrent file adds
// may encounter a stale duplicate. The primary use case (magnet links from
// indexers) is handled by the addMagnetLink override above.
//
// For .torrent files, the parent will return the existing hash if a duplicate
// is found. The postProcess cleanup after organize will still clean it up.
return super.addTorrentFile(torrentUrl, category, options);
}
/**
* Override: Remove torrent entry from RDT-Client after files are organized.
* Unlike qBittorrent (which seeds), RDT-Client torrents should be cleaned up
* immediately Real-Debrid handles seeding on their infrastructure.
*/
override async postProcess(id: string): Promise<void> {
try {
logger.info(`Removing torrent ${id} from RDT-Client (post-organize cleanup)`);
await this.deleteTorrent(id, false);
logger.info(`Successfully removed torrent ${id} from RDT-Client`);
} catch (error) {
// Non-fatal: torrent may already have been removed
logger.warn(
`Failed to remove torrent ${id} from RDT-Client: ${error instanceof Error ? error.message : String(error)}`
);
}
}
/**
* Override: No-op. RDT-Client doesn't support qBittorrent categories.
* Avoids 404 errors that appear in logs when the parent tries to create/update categories.
*/
protected override async ensureCategory(_category: string): Promise<void> {
// No-op: RDT-Client does not support categories
}
/**
* Delete a stale torrent if it exists, so a fresh add doesn't short-circuit.
*/
private async deleteStaleIfExists(hash: string): Promise<void> {
try {
await this.getTorrent(hash);
// If we get here, torrent exists — delete it
logger.info(`Deleting stale torrent ${hash} from RDT-Client before fresh add`);
await this.deleteTorrent(hash, false);
} catch {
// Torrent doesn't exist — nothing to clean up
}
}
}
+4 -3
View File
@@ -6,6 +6,7 @@
import axios, { AxiosInstance } from 'axios';
import https from 'https';
import path from 'path';
import { DOWNLOAD_CLIENT_TIMEOUT } from '../constants/download-timeouts';
import * as parseTorrentModule from 'parse-torrent';
import { RMABLogger } from '../utils/logger';
import { PathMapper, PathMappingConfig } from '../utils/path-mapper';
@@ -106,7 +107,7 @@ export class TransmissionService implements IDownloadClient {
this.client = axios.create({
baseURL: this.baseUrl,
timeout: 30000,
timeout: DOWNLOAD_CLIENT_TIMEOUT,
httpsAgent: this.httpsAgent,
});
}
@@ -274,7 +275,7 @@ export class TransmissionService implements IDownloadClient {
responseType: 'arraybuffer',
maxRedirects: 0,
validateStatus: (status) => status >= 200 && status < 300,
timeout: 30000,
timeout: DOWNLOAD_CLIENT_TIMEOUT,
});
// Check if response body is a magnet link
@@ -302,7 +303,7 @@ export class TransmissionService implements IDownloadClient {
try {
torrentResponse = await axios.get(location, {
responseType: 'arraybuffer',
timeout: 30000,
timeout: DOWNLOAD_CLIENT_TIMEOUT,
maxRedirects: 5,
});
} catch {
@@ -11,7 +11,7 @@
// =========================================================================
/** Supported download client types — single source of truth */
export const SUPPORTED_CLIENT_TYPES = ['qbittorrent', 'sabnzbd', 'nzbget', 'transmission', 'rdtclient'] as const;
export const SUPPORTED_CLIENT_TYPES = ['qbittorrent', 'sabnzbd', 'nzbget', 'transmission', 'deluge'] as const;
/** Identifies the specific download client software */
export type DownloadClientType = (typeof SUPPORTED_CLIENT_TYPES)[number];
@@ -22,7 +22,7 @@ export const CLIENT_DISPLAY_NAMES: Record<DownloadClientType, string> = {
sabnzbd: 'SABnzbd',
nzbget: 'NZBGet',
transmission: 'Transmission',
rdtclient: 'RDT-Client',
deluge: 'Deluge',
};
/** Get display name for a client type, falling back to the raw type */
@@ -39,7 +39,7 @@ export const CLIENT_PROTOCOL_MAP: Record<DownloadClientType, ProtocolType> = {
sabnzbd: 'usenet',
nzbget: 'usenet',
transmission: 'torrent',
rdtclient: 'torrent',
deluge: 'torrent',
};
/** Unified download status across all clients */
+30 -7
View File
@@ -128,7 +128,19 @@ export async function processOrganizeFiles(payload: OrganizeFilesPayload): Promi
});
const template = templateConfig?.value || '{author}/{title} {asin}';
// Organize files (pass template and logger to file organizer)
// Read file rename configuration
const fileRenameEnabledConfig = await prisma.configuration.findUnique({
where: { key: 'file_rename_enabled' },
});
const fileRenameTemplateConfig = await prisma.configuration.findUnique({
where: { key: 'file_rename_template' },
});
const renameConfig = {
enabled: fileRenameEnabledConfig?.value === 'true',
template: fileRenameTemplateConfig?.value || '{title}',
};
// Organize files (pass template, logger, and rename config to file organizer)
const result = await organizer.organize(
downloadPath,
{
@@ -142,7 +154,8 @@ export async function processOrganizeFiles(payload: OrganizeFilesPayload): Promi
seriesPart: audiobook.seriesPart || undefined,
},
template,
jobId ? { jobId, context: 'FileOrganizer' } : undefined
jobId ? { jobId, context: 'FileOrganizer' } : undefined,
renameConfig
);
if (!result.success) {
@@ -556,6 +569,18 @@ async function processEbookOrganization(
}
}
// Read file rename configuration
const fileRenameEnabledConfig = await prisma.configuration.findUnique({
where: { key: 'file_rename_enabled' },
});
const fileRenameTemplateConfig = await prisma.configuration.findUnique({
where: { key: 'file_rename_template' },
});
const ebookRenameConfig = {
enabled: fileRenameEnabledConfig?.value === 'true',
template: fileRenameTemplateConfig?.value || '{title}',
};
// Organize ebook files (organizer will detect ebook type and skip audio-specific processing)
// Pass all metadata that could be used in path templates (same as audiobooks)
const result = await organizer.organizeEbook(
@@ -571,7 +596,8 @@ async function processEbookOrganization(
},
template,
jobId ? { jobId, context: 'FileOrganizer.Ebook' } : undefined,
isIndexerDownload
isIndexerDownload,
ebookRenameConfig
);
// Clean up fixed EPUB temp file after organization (regardless of success)
@@ -865,12 +891,9 @@ async function cleanupDownloadAfterOrganize(
});
// Check if this is a non-torrent indexer with cleanup enabled.
// RDT-Client is an exception: even though it's torrent protocol, it needs cleanup
// because Real-Debrid handles seeding — local torrent entries should be removed.
const isRDTClient = downloadHistory.downloadClient === 'rdtclient';
const isTorrentProtocol = indexer?.protocol?.toLowerCase() === 'torrent';
if (!indexer || (!isRDTClient && isTorrentProtocol) || !indexer.removeAfterProcessing) {
if (!indexer || isTorrentProtocol || !indexer.removeAfterProcessing) {
return;
}
@@ -2,7 +2,7 @@
* Component: Download Client Manager Service
* Documentation: documentation/phase3/download-clients.md
*
* Manages multiple download clients (qBittorrent, Transmission, SABnzbd, NZBGet) with protocol-based routing.
* Manages multiple download clients (qBittorrent, Transmission, Deluge, SABnzbd, NZBGet) with protocol-based routing.
* Supports migration from legacy single-client config to multi-client JSON array format.
*/
@@ -16,7 +16,7 @@ import { QBittorrentService } from '@/lib/integrations/qbittorrent.service';
import { SABnzbdService } from '@/lib/integrations/sabnzbd.service';
import { NZBGetService } from '@/lib/integrations/nzbget.service';
import { TransmissionService } from '@/lib/integrations/transmission.service';
import { RDTClientService } from '@/lib/integrations/rdtclient.service';
import { DelugeService } from '@/lib/integrations/deluge.service';
import { PathMappingConfig } from '@/lib/utils/path-mapper';
import { IDownloadClient, DownloadClientType, ProtocolType, CLIENT_PROTOCOL_MAP, getClientDisplayName } from '@/lib/interfaces/download-client.interface';
@@ -194,8 +194,8 @@ export class DownloadClientManager {
return this.createNZBGetService(config, downloadDir);
case 'transmission':
return this.createTransmissionService(config, downloadDir);
case 'rdtclient':
return this.createRDTClientService(config, downloadDir);
case 'deluge':
return this.createDelugeService(config, downloadDir);
default:
throw new Error(`Unsupported download client type: ${config.type}`);
}
@@ -339,9 +339,9 @@ export class DownloadClientManager {
}
/**
* Create RDT-Client service instance (same constructor as qBittorrent identical API)
* Create Deluge service instance
*/
private createRDTClientService(config: DownloadClientConfig, downloadDir: string): RDTClientService {
private createDelugeService(config: DownloadClientConfig, downloadDir: string): DelugeService {
const pathMapping: PathMappingConfig | undefined = config.remotePathMappingEnabled && config.remotePath && config.localPath
? {
enabled: true,
@@ -350,7 +350,7 @@ export class DownloadClientManager {
}
: undefined;
return new RDTClientService(
return new DelugeService(
config.url,
config.username || '',
config.password || '',
+8 -1
View File
@@ -5,7 +5,7 @@
import type { SupportedLanguage } from '../constants/language-config';
export type AudibleRegion = 'us' | 'ca' | 'uk' | 'au' | 'in' | 'de' | 'es';
export type AudibleRegion = 'us' | 'ca' | 'uk' | 'au' | 'in' | 'de' | 'es' | 'fr';
export interface AudibleRegionConfig {
code: AudibleRegion;
@@ -64,6 +64,13 @@ export const AUDIBLE_REGIONS: Record<AudibleRegion, AudibleRegionConfig> = {
baseUrl: 'https://www.audible.es',
audnexusParam: 'es',
language: 'es',
},
fr: {
code: 'fr',
name: 'France',
baseUrl: 'https://www.audible.fr',
audnexusParam: 'fr',
language: 'fr',
}
};
+57 -7
View File
@@ -20,7 +20,7 @@ import {
checkDiskSpace,
} from './chapter-merger';
import { prisma } from '../db';
import { substituteTemplate, type TemplateVariables } from './path-template.util';
import { substituteTemplate, buildRenamedFilename, type TemplateVariables } from './path-template.util';
import { AUDIO_EXTENSIONS } from '../constants/audio-formats';
export interface AudiobookMetadata {
@@ -77,7 +77,8 @@ export class FileOrganizer {
downloadPath: string,
audiobook: AudiobookMetadata,
template: string,
loggerConfig?: LoggerConfig
loggerConfig?: LoggerConfig,
renameConfig?: { enabled: boolean; template: string }
): Promise<OrganizationResult> {
// Create logger if config provided
const logger = loggerConfig ? RMABLogger.forJob(loggerConfig.jobId, loggerConfig.context) : null;
@@ -294,8 +295,17 @@ export class FileOrganizer {
// Create target directory
await fs.mkdir(targetPath, { recursive: true });
// Determine if file renaming should be applied
const shouldRename = renameConfig?.enabled && renameConfig.template;
const isMultiFile = audioFiles.length > 1;
if (shouldRename) {
await logger?.info(`File renaming enabled with template: ${renameConfig.template}${isMultiFile ? ` (${audioFiles.length} files, indices will be appended)` : ''}`);
}
// Copy audio files (do NOT delete originals - needed for seeding)
for (const audioFile of audioFiles) {
for (let i = 0; i < audioFiles.length; i++) {
const audioFile = audioFiles[i];
// Handle merged files (absolute paths) vs original files (relative paths)
const isAbsolutePath = path.isAbsolute(audioFile);
const originalSourcePath = isAbsolutePath
@@ -303,7 +313,30 @@ export class FileOrganizer {
: isFile
? downloadPath
: path.join(downloadPath, audioFile);
const filename = path.basename(audioFile);
// Determine target filename (apply rename template if enabled)
let filename: string;
if (shouldRename) {
const ext = path.extname(audioFile);
const variables: TemplateVariables = {
author: audiobook.author,
title: audiobook.title,
narrator: audiobook.narrator,
asin: audiobook.asin,
year: audiobook.year,
series: audiobook.series,
seriesPart: audiobook.seriesPart,
};
filename = buildRenamedFilename(
renameConfig.template,
variables,
ext,
isMultiFile ? i + 1 : undefined,
);
} else {
filename = path.basename(audioFile);
}
const targetFilePath = path.join(targetPath, filename);
// Check if we have a tagged version of this file
@@ -690,7 +723,8 @@ export class FileOrganizer {
metadata: { title: string; author: string; narrator?: string; asin?: string; year?: number; series?: string; seriesPart?: string },
template: string,
loggerConfig?: LoggerConfig,
isIndexerDownload: boolean = false
isIndexerDownload: boolean = false,
renameConfig?: { enabled: boolean; template: string }
): Promise<EbookOrganizationResult> {
const logger = loggerConfig ? RMABLogger.forJob(loggerConfig.jobId, loggerConfig.context) : null;
@@ -739,9 +773,25 @@ export class FileOrganizer {
// Create target directory
await fs.mkdir(targetDir, { recursive: true });
// Build target filename (sanitize source filename)
// Build target filename (apply rename template if enabled, otherwise sanitize source filename)
const sourceFilename = path.basename(ebookFile);
const targetFilename = this.sanitizePath(sourceFilename);
let targetFilename: string;
if (renameConfig?.enabled && renameConfig.template) {
const originalExt = path.extname(ebookFile);
const variables: TemplateVariables = {
author: metadata.author,
title: metadata.title,
narrator: metadata.narrator,
asin: metadata.asin,
year: metadata.year,
series: metadata.series,
seriesPart: metadata.seriesPart,
};
targetFilename = buildRenamedFilename(renameConfig.template, variables, originalExt);
await logger?.info(`Renamed ebook file: ${sourceFilename} -> ${targetFilename}`);
} else {
targetFilename = this.sanitizePath(sourceFilename);
}
const targetPath = path.join(targetDir, targetFilename);
// Check if target already exists
+299 -6
View File
@@ -68,6 +68,81 @@ function sanitizePath(name: string): string {
);
}
/**
* Find valid template variable names within arbitrary content text.
* Sorts by length descending to prevent substring false matches
* (e.g., 'seriesPart' matched before 'series').
* Uses word-boundary detection to avoid matching variable names
* that are substrings of other words.
*/
function findVariablesInContent(content: string): string[] {
const sortedVars = [...VALID_VARIABLES].sort((a, b) => b.length - a.length);
const found: string[] = [];
for (const varName of sortedVars) {
const regex = new RegExp(`(?<![a-zA-Z0-9])${varName}(?![a-zA-Z0-9])`);
if (regex.test(content)) {
found.push(varName);
}
}
return found;
}
/**
* Resolve conditional blocks in the template.
* A conditional block is {literal text varName more text} where the entire
* content is rendered only if ALL variables inside have non-empty values.
* If any variable is empty/missing, the entire block is removed.
*
* Simple variable references like {author} are left untouched for the
* existing substitution logic to handle.
*
* Must run after escaped-brace replacement and before simple variable substitution.
*/
function resolveConditionalBlocks(
template: string,
variables: TemplateVariables
): string {
return template.replace(/\{([^}]+)\}/g, (match, content: string) => {
// If content is exactly a valid variable name, skip (leave for simple substitution)
if (VALID_VARIABLES.includes(content)) {
return match;
}
// Find variables in the content
const foundVars = findVariablesInContent(content);
// If no variables found, leave as-is (validation will catch it)
if (foundVars.length === 0) {
return match;
}
// Check if all found variables have non-empty values
const allPresent = foundVars.every(varName => {
const value = variables[varName as keyof TemplateVariables];
return value !== undefined && value !== null && String(value).trim() !== '';
});
if (!allPresent) {
return '';
}
// Substitute variables within the content, output rest as literal text
// Sort by length descending to prevent substring false matches
let result = content;
const sortedVars = [...foundVars].sort((a, b) => b.length - a.length);
for (const varName of sortedVars) {
const value = variables[varName as keyof TemplateVariables];
const sanitizedValue = sanitizePath(String(value).trim());
const regex = new RegExp(`(?<![a-zA-Z0-9])${varName}(?![a-zA-Z0-9])`, 'g');
result = result.replace(regex, sanitizedValue);
}
return result;
});
}
/**
* Substitute template variables with actual values
*
@@ -99,6 +174,9 @@ export function substituteTemplate(
// so they survive the variable substitution and path cleanup steps
result = result.replace(/\\\{/g, LBRACE_PLACEHOLDER).replace(/\\\}/g, RBRACE_PLACEHOLDER);
// Resolve conditional blocks before simple variable substitution
result = resolveConditionalBlocks(result, variables);
// Substitute each variable
for (const key of VALID_VARIABLES) {
const value = variables[key as keyof TemplateVariables];
@@ -187,21 +265,47 @@ export function validateTemplate(template: string): ValidationResult {
if (variableMatches) {
for (const match of variableMatches) {
const varName = match.slice(1, -1); // Remove { and }
const content = match.slice(1, -1); // Remove { and }
if (!VALID_VARIABLES.includes(varName)) {
// Simple variable — exact match to a valid variable name
if (VALID_VARIABLES.includes(content)) {
continue;
}
// Conditional block — must contain at least one valid variable
const foundVars = findVariablesInContent(content);
if (foundVars.length === 0) {
return {
valid: false,
error: `Unknown variable: {${varName}}. Valid variables are: ${VALID_VARIABLES.map(v => `{${v}}`).join(', ')}`
error: `No valid variable found in conditional block: {${content}}. Valid variables are: ${VALID_VARIABLES.map(v => `{${v}}`).join(', ')}`
};
}
// Check literal text inside conditional block for invalid path chars
let literalText = content;
const sortedVars = [...foundVars].sort((a, b) => b.length - a.length);
for (const varName of sortedVars) {
literalText = literalText.replace(
new RegExp(`(?<![a-zA-Z0-9])${varName}(?![a-zA-Z0-9])`, 'g'),
''
);
}
const invalidCharsInBlock = literalText.match(INVALID_PATH_CHARS);
if (invalidCharsInBlock) {
return {
valid: false,
error: `Invalid characters found: ${[...new Set(invalidCharsInBlock)].join(', ')}. These characters are not allowed in path templates.`
};
}
}
}
// Remove valid variables temporarily to check for invalid characters
// Remove valid variables and conditional blocks to check remaining text for invalid chars
let templateWithoutVars = templateWithoutEscapedBraces;
for (const varName of VALID_VARIABLES) {
templateWithoutVars = templateWithoutVars.replace(new RegExp(`\\{${varName}\\}`, 'g'), '');
if (variableMatches) {
for (const match of variableMatches) {
templateWithoutVars = templateWithoutVars.replace(match, '');
}
}
// Check for invalid characters outside of variables
@@ -286,3 +390,192 @@ export function generateMockPreviews(template: string): string[] {
export function getValidVariables(): string[] {
return [...VALID_VARIABLES];
}
/**
* Validate a filename template string
*
* Similar to validateTemplate but for filenames (not paths):
* - Disallows forward slashes (no directory separators in filenames)
* - Does not require relative path structure
* - Must contain at least one variable
*
* @param template - Filename template string to validate
* @returns Validation result with error message if invalid
*/
export function validateFilenameTemplate(template: string): ValidationResult {
if (!template || template.trim().length === 0) {
return {
valid: false,
error: 'Filename template cannot be empty',
};
}
// Disallow forward slashes — filenames cannot contain directory separators
if (template.includes('/')) {
return {
valid: false,
error: 'Filename template cannot contain "/" (directory separators). Use the organization template for directory structure.',
};
}
// Disallow backslashes that aren't brace escapes
if (/\\(?![{}])/.test(template)) {
return {
valid: false,
error: 'Filename template cannot contain backslashes. Use the organization template for directory structure.',
};
}
// Strip escaped braces before parsing
const templateWithoutEscapedBraces = template.replace(/\\[{}]/g, '');
// Extract all variables from the stripped template
const variableMatches = templateWithoutEscapedBraces.match(/\{[^}]+\}/g);
if (variableMatches) {
for (const match of variableMatches) {
const content = match.slice(1, -1);
// Simple variable
if (VALID_VARIABLES.includes(content)) {
continue;
}
// Conditional block — must contain at least one valid variable
const foundVars = findVariablesInContent(content);
if (foundVars.length === 0) {
return {
valid: false,
error: `No valid variable found in: {${content}}. Valid variables are: ${VALID_VARIABLES.map(v => `{${v}}`).join(', ')}`,
};
}
// Check literal text inside conditional block for invalid filename chars
let literalText = content;
const sortedVars = [...foundVars].sort((a, b) => b.length - a.length);
for (const varName of sortedVars) {
literalText = literalText.replace(
new RegExp(`(?<![a-zA-Z0-9])${varName}(?![a-zA-Z0-9])`, 'g'),
''
);
}
const invalidCharsInBlock = literalText.match(INVALID_PATH_CHARS);
if (invalidCharsInBlock) {
return {
valid: false,
error: `Invalid characters found: ${[...new Set(invalidCharsInBlock)].join(', ')}. These characters are not allowed in filenames.`,
};
}
}
}
// Remove valid variables and conditional blocks to check remaining text
let templateWithoutVars = templateWithoutEscapedBraces;
if (variableMatches) {
for (const match of variableMatches) {
templateWithoutVars = templateWithoutVars.replace(match, '');
}
}
// Check for invalid characters outside of variables
const invalidChars = templateWithoutVars.match(INVALID_PATH_CHARS);
if (invalidChars) {
return {
valid: false,
error: `Invalid characters found: ${[...new Set(invalidChars)].join(', ')}. These characters are not allowed in filenames.`,
};
}
return { valid: true };
}
/**
* Generate mock filename previews using sample audiobook data
*
* Creates example filenames with extensions to demonstrate how the template will look.
* Shows both single-file and multi-file (with index) examples.
*
* @param template - Filename template string
* @returns Object with single and multi-file preview arrays
*/
export function generateMockFilenamePreviews(template: string): {
single: string[];
multi: string[];
} {
const mockData: TemplateVariables[] = [
{
author: 'Brandon Sanderson',
title: 'Mistborn: The Final Empire',
narrator: 'Michael Kramer',
asin: 'B002UZMLXM',
year: 2006,
series: 'The Mistborn Saga',
seriesPart: '1',
},
{
author: 'Douglas Adams',
title: "The Hitchhiker's Guide to the Galaxy",
narrator: 'Stephen Fry',
asin: 'B0009JKV9W',
year: 2005,
series: "Hitchhiker's Guide",
seriesPart: '1',
},
];
const single = mockData.map((variables) => {
const name = substituteTemplate(template, variables);
return `${name}.m4b`;
});
// Show multi-file example with first mock data only
const multiName = substituteTemplate(template, mockData[0]);
const multi = [
`${multiName} - 1.mp3`,
`${multiName} - 2.mp3`,
`${multiName} - 3.mp3`,
];
return { single, multi };
}
/**
* Build a renamed filename from a template, metadata variables, and original extension.
* Optionally appends a 1-based index for multi-file scenarios.
*
* @param template - Filename template string (e.g., "{title}")
* @param variables - Template variables with metadata values
* @param originalExtension - File extension including dot (e.g., ".m4b")
* @param index - Optional 1-based index for multi-file scenarios
* @returns Sanitized filename with extension
*/
export function buildRenamedFilename(
template: string,
variables: TemplateVariables,
originalExtension: string,
index?: number,
): string {
let baseName = substituteTemplate(template, variables);
// substituteTemplate cleans up slashes for paths — but since this is a filename,
// remove any residual slashes that conditional blocks might have introduced
baseName = baseName.replace(/[/\\]/g, '');
// Sanitize again for filename safety
baseName = baseName
.replace(/[<>:"/\\|?*]/g, '')
.trim()
.replace(/^\.+/, '')
.replace(/\.+$/, '')
.replace(/\s+/g, ' ')
.slice(0, 200);
if (index !== undefined) {
baseName = `${baseName} - ${index}`;
}
// Ensure extension starts with a dot
const ext = originalExtension.startsWith('.') ? originalExtension : `.${originalExtension}`;
return `${baseName}${ext}`;
}
+2 -2
View File
@@ -152,8 +152,8 @@ describe('Admin settings core routes', () => {
it('rejects invalid download client types', async () => {
const request = {
json: vi.fn().mockResolvedValue({
type: 'deluge',
url: 'http://deluge',
type: 'rtorrent',
url: 'http://rtorrent',
}),
};
-104
View File
@@ -1,104 +0,0 @@
/**
* Component: Config API Route Tests
* Documentation: documentation/testing.md
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
const configServiceMock = vi.hoisted(() => ({
setMany: vi.fn(),
getAll: vi.fn(),
getCategory: vi.fn(),
}));
vi.mock('@/lib/services/config.service', () => ({
getConfigService: () => configServiceMock,
}));
describe('Config API routes', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('returns full configuration', async () => {
configServiceMock.getAll.mockResolvedValue({ plex_url: 'http://plex' });
const { GET } = await import('@/app/api/config/route');
const response = await GET();
const payload = await response.json();
expect(payload.config.plex_url).toBe('http://plex');
});
it('updates configuration values', async () => {
const { PUT } = await import('@/app/api/config/route');
const response = await PUT({
json: vi.fn().mockResolvedValue({
updates: [{ key: 'plex_url', value: 'http://plex' }],
}),
} as any);
const payload = await response.json();
expect(response.status).toBe(200);
expect(payload.updated).toBe(1);
expect(configServiceMock.setMany).toHaveBeenCalled();
});
it('returns 400 when configuration update payload is invalid', async () => {
const { PUT } = await import('@/app/api/config/route');
const response = await PUT({ json: vi.fn().mockResolvedValue({}) } as any);
const payload = await response.json();
expect(response.status).toBe(400);
expect(payload.error).toMatch(/Validation error/);
});
it('returns 500 when configuration update fails', async () => {
configServiceMock.setMany.mockRejectedValueOnce(new Error('db down'));
const { PUT } = await import('@/app/api/config/route');
const response = await PUT({
json: vi.fn().mockResolvedValue({
updates: [{ key: 'plex_url', value: 'http://plex' }],
}),
} as any);
const payload = await response.json();
expect(response.status).toBe(500);
expect(payload.error).toMatch(/Failed to update configuration/);
});
it('returns 500 when configuration lookup fails', async () => {
configServiceMock.getAll.mockRejectedValueOnce(new Error('db down'));
const { GET } = await import('@/app/api/config/route');
const response = await GET();
const payload = await response.json();
expect(response.status).toBe(500);
expect(payload.error).toMatch(/Failed to get configuration/);
});
it('returns category configuration', async () => {
configServiceMock.getCategory.mockResolvedValue({ plex_url: 'http://plex' });
const { GET } = await import('@/app/api/config/[category]/route');
const response = await GET({} as any, { params: Promise.resolve({ category: 'plex' }) });
const payload = await response.json();
expect(payload.category).toBe('plex');
expect(payload.config.plex_url).toBe('http://plex');
});
it('returns 500 when category configuration lookup fails', async () => {
configServiceMock.getCategory.mockRejectedValueOnce(new Error('db down'));
const { GET } = await import('@/app/api/config/[category]/route');
const response = await GET({} as any, { params: Promise.resolve({ category: 'plex' }) });
const payload = await response.json();
expect(response.status).toBe(500);
expect(payload.error).toMatch(/Failed to get configuration/);
});
});
+2 -2
View File
@@ -182,7 +182,7 @@ describe('Setup test routes', () => {
it('rejects invalid download client type', async () => {
const { POST } = await import('@/app/api/setup/test-download-client/route');
const response = await POST({
json: vi.fn().mockResolvedValue({ type: 'deluge', url: 'http://deluge' }),
json: vi.fn().mockResolvedValue({ type: 'rtorrent', url: 'http://rtorrent' }),
} as any);
const payload = await response.json();
@@ -433,7 +433,7 @@ describe('Setup test routes', () => {
expect(payload.success).toBe(true);
expect(payload.template).toBeDefined();
expect(payload.template.isValid).toBe(false);
expect(payload.template.error).toContain('Unknown variable');
expect(payload.template.error).toContain('No valid variable found in conditional block');
expect(payload.template.previewPaths).toBeUndefined();
});
+3 -3
View File
@@ -55,9 +55,9 @@ describe('AdminJobsPage', () => {
render(<AdminJobsPage />);
expect(await screen.findByText('Library Scan')).toBeInTheDocument();
expect((await screen.findAllByText('Library Scan'))[0]).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Trigger Now/i }));
fireEvent.click(screen.getAllByRole('button', { name: /Trigger Now/i })[0]);
fireEvent.click(screen.getByRole('button', { name: 'Trigger Job' }));
await waitFor(() => {
@@ -88,7 +88,7 @@ describe('AdminJobsPage', () => {
render(<AdminJobsPage />);
fireEvent.click(await screen.findByRole('button', { name: 'Edit' }));
fireEvent.click((await screen.findAllByRole('button', { name: 'Edit' }))[0]);
fireEvent.click(screen.getByRole('radio', { name: /Every 2 hours/i }));
fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
+7 -7
View File
@@ -68,14 +68,14 @@ describe('AdminLogsPage', () => {
render(<AdminLogsPage />);
expect(await screen.findByText('System Logs')).toBeInTheDocument();
expect(screen.getByText('Search Book')).toBeInTheDocument();
expect(screen.getAllByText('Search Book')[0]).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Show Details' }));
expect(screen.getByText('Event Log')).toBeInTheDocument();
expect(screen.getByText('Job Result')).toBeInTheDocument();
expect(screen.getByText('Error')).toBeInTheDocument();
fireEvent.click(screen.getAllByRole('button', { name: 'Show Details' })[0]);
expect(screen.getAllByText('Event Log')[0]).toBeInTheDocument();
expect(screen.getAllByText('Job Result')[0]).toBeInTheDocument();
expect(screen.getAllByText('Error')[0]).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Hide Details' }));
fireEvent.click(screen.getAllByRole('button', { name: 'Hide Details' })[0]);
expect(screen.queryByText('Event Log')).not.toBeInTheDocument();
});
@@ -122,6 +122,6 @@ describe('AdminLogsPage', () => {
render(<AdminLogsPage />);
expect(await screen.findByText('No logs found')).toBeInTheDocument();
expect((await screen.findAllByText('No logs found'))[0]).toBeInTheDocument();
});
});
+9 -9
View File
@@ -158,9 +158,9 @@ describe('AdminUsersPage', () => {
render(<AdminUsersPage />);
expect(await screen.findByText('Full Access')).toBeDefined();
expect(screen.getByText('Manual')).toBeDefined();
expect(screen.getByText('Auto-Approve')).toBeDefined();
expect((await screen.findAllByText('Full Access'))[0]).toBeDefined();
expect(screen.getAllByText('Manual')[0]).toBeDefined();
expect(screen.getAllByText('Auto-Approve')[0]).toBeDefined();
});
it('shows Global Default badge when global auto-approve is on', async () => {
@@ -171,7 +171,7 @@ describe('AdminUsersPage', () => {
render(<AdminUsersPage />);
expect(await screen.findByText('Global Default')).toBeDefined();
expect((await screen.findAllByText('Global Default'))[0]).toBeDefined();
});
it('opens user permissions modal and shows admin lock state for both permissions', async () => {
@@ -184,7 +184,7 @@ describe('AdminUsersPage', () => {
render(<AdminUsersPage />);
// Click the permissions badge to open modal
fireEvent.click(await screen.findByText('Full Access'));
fireEvent.click((await screen.findAllByText('Full Access'))[0]);
// Modal should show user info and the locked state for both permissions
expect(await screen.findByText('User Permissions')).toBeDefined();
@@ -205,7 +205,7 @@ describe('AdminUsersPage', () => {
render(<AdminUsersPage />);
// Click the Manual badge to open permissions modal
fireEvent.click(await screen.findByText('Manual'));
fireEvent.click((await screen.findAllByText('Manual'))[0]);
// Find and click the auto-approve toggle switch inside the modal
const toggle = await screen.findByRole('switch', { name: 'Auto-Approve Requests' });
@@ -231,7 +231,7 @@ describe('AdminUsersPage', () => {
render(<AdminUsersPage />);
// Click the Manual badge to open permissions modal
fireEvent.click(await screen.findByText('Manual'));
fireEvent.click((await screen.findAllByText('Manual'))[0]);
// Find and click the interactive search toggle switch inside the modal
const toggle = await screen.findByRole('switch', { name: 'Interactive Search Access' });
@@ -255,7 +255,7 @@ describe('AdminUsersPage', () => {
render(<AdminUsersPage />);
// Click the Global Default badge
fireEvent.click(await screen.findByText('Global Default'));
fireEvent.click((await screen.findAllByText('Global Default'))[0]);
// Modal should show the global override message for both
expect(await screen.findByText('Controlled by global auto-approve setting')).toBeDefined();
@@ -288,7 +288,7 @@ describe('AdminUsersPage', () => {
render(<AdminUsersPage />);
fireEvent.click(await screen.findByRole('button', { name: 'Edit Role' }));
fireEvent.click((await screen.findAllByRole('button', { name: 'Edit Role' }))[0]);
fireEvent.click(screen.getByRole('radio', { name: /Admin/i }));
fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
+440
View File
@@ -0,0 +1,440 @@
/**
* Component: Deluge Integration Service Tests
* Documentation: documentation/phase3/download-clients.md
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { DelugeService, getDelugeService, invalidateDelugeService } from '@/lib/integrations/deluge.service';
const clientMock = vi.hoisted(() => ({
post: vi.fn(),
}));
const axiosMock = vi.hoisted(() => ({
create: vi.fn(() => clientMock),
get: vi.fn(),
isAxiosError: (error: any) => Boolean(error?.isAxiosError),
}));
const parseTorrentMock = vi.hoisted(() => vi.fn());
const configServiceMock = vi.hoisted(() => ({
get: vi.fn(),
}));
const downloadClientManagerMock = vi.hoisted(() => ({
getClientForProtocol: vi.fn(),
}));
vi.mock('axios', () => ({ default: axiosMock, ...axiosMock }));
vi.mock('parse-torrent', () => ({ default: parseTorrentMock }));
vi.mock('@/lib/services/config.service', () => ({
getConfigService: vi.fn(async () => configServiceMock),
}));
vi.mock('@/lib/services/download-client-manager.service', () => ({
getDownloadClientManager: () => downloadClientManagerMock,
}));
/** Helper: simulate a successful Deluge login + daemon connected response */
function mockLoginSuccess() {
// auth.login
clientMock.post.mockResolvedValueOnce({
data: { result: true, error: null, id: 1 },
headers: { 'set-cookie': ['_session_id=abc123; Path=/;'] },
});
// web.connected (daemon already connected)
clientMock.post.mockResolvedValueOnce({
data: { result: true, error: null, id: 2 },
headers: {},
});
}
/** Helper: simulate login + force daemon reconnection (get_hosts -> connect -> verify) */
function mockLoginForceReconnect() {
// auth.login
clientMock.post.mockResolvedValueOnce({
data: { result: true, error: null, id: 1 },
headers: { 'set-cookie': ['_session_id=abc123; Path=/;'] },
});
// web.get_hosts
mockRpc([['host-1', '127.0.0.1', 58846, '']]);
// web.connect
mockRpc(null);
// web.connected (verify)
mockRpc(true);
}
/** Helper: simulate a Deluge RPC response */
function mockRpc(result: any, error: any = null) {
clientMock.post.mockResolvedValueOnce({
data: { result, error, id: 1 },
headers: {},
});
}
describe('DelugeService', () => {
beforeEach(() => {
vi.clearAllMocks();
clientMock.post.mockReset();
axiosMock.get.mockReset();
parseTorrentMock.mockReset();
configServiceMock.get.mockReset();
downloadClientManagerMock.getClientForProtocol.mockReset();
invalidateDelugeService();
});
it('authenticates and stores session cookie', async () => {
const service = new DelugeService('http://deluge', '', 'mypass');
// Mock login (auth.login + web.connected check)
mockLoginSuccess();
const result = await service.testConnection();
expect(result.success).toBe(true);
});
it('fails authentication with wrong password', async () => {
const service = new DelugeService('http://deluge', '', 'bad');
clientMock.post.mockResolvedValueOnce({
data: { result: false, error: null, id: 1 },
headers: {},
});
const result = await service.testConnection();
expect(result.success).toBe(false);
expect(result.message).toContain('authenticate');
});
it('force reconnects daemon on error code 2 (Unknown method)', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
// First RPC returns error code 2 (daemon disconnected)
mockRpc(null, { code: 2, message: 'Unknown method' });
// rpc() retries via login(true) -> force reconnect
mockLoginForceReconnect();
// Retried core.get_torrent_status succeeds
mockRpc({
name: 'Test Torrent', total_size: 1000, total_done: 1000, progress: 100,
state: 'Seeding', download_payload_rate: 0, eta: 0,
label: 'readmeabook', save_path: '/downloads', time_added: 1700000000,
is_finished: true, seeding_time: 3600, ratio: 1.5, message: '',
});
const info = await service.getDownload('abc123');
expect(info).not.toBeNull();
expect(info!.name).toBe('Test Torrent');
expect(info!.status).toBe('seeding');
});
it('does not retry error code 2 more than once', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
// First RPC returns error code 2
mockRpc(null, { code: 2, message: 'Unknown method' });
// Force reconnect succeeds
mockLoginForceReconnect();
// Retried RPC also returns error code 2 (persistent failure) — retried=true, so no more retries
mockRpc(null, { code: 2, message: 'Unknown method' });
const result = await (service as any).rpc('core.get_torrent_status', ['abc123', ['name']]);
expect(result.error).toEqual({ code: 2, message: 'Unknown method' });
});
it('returns connection errors for refused connections', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
clientMock.post.mockRejectedValueOnce({
isAxiosError: true,
code: 'ECONNREFUSED',
message: 'refused',
});
const result = await service.testConnection();
expect(result.success).toBe(false);
expect(result.message).toContain('Connection refused');
});
it('maps Deluge status strings to unified DownloadStatus', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
const states: Record<string, string> = {
'Downloading': 'downloading',
'Seeding': 'seeding',
'Paused': 'paused',
'Checking': 'checking',
'Queued': 'queued',
'Error': 'failed',
'Moving': 'downloading',
'UnknownState': 'downloading', // fallback
};
for (const [delugeState, expectedStatus] of Object.entries(states)) {
clientMock.post.mockResolvedValueOnce({
data: {
result: {
name: 'Test', total_size: 1000, total_done: 500, progress: 50,
state: delugeState, download_payload_rate: 100, eta: 60,
label: 'readmeabook', save_path: '/downloads', time_added: 1700000000,
is_finished: false, seeding_time: 0, ratio: 0, message: '',
},
error: null,
id: 1,
},
headers: {},
});
const info = await service.getDownload('abc123');
expect(info).not.toBeNull();
expect(info!.status).toBe(expectedStatus);
}
});
it('normalizes progress from 0-100 to 0-1', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
mockRpc({
name: 'Audiobook', total_size: 1000, total_done: 420, progress: 42,
state: 'Downloading', download_payload_rate: 50, eta: 120,
label: 'readmeabook', save_path: '/downloads', time_added: 1700000000,
is_finished: false, seeding_time: 0, ratio: 0, message: '',
});
const info = await service.getDownload('hash1');
expect(info).not.toBeNull();
expect(info!.progress).toBeCloseTo(0.42);
expect(info!.bytesDownloaded).toBe(420);
});
it('returns null when torrent is not found (empty result)', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
// Mock 4 attempts (initial + 3 retries) returning empty results
for (let i = 0; i < 4; i++) {
mockRpc({});
}
const info = await service.getDownload('missing-hash');
expect(info).toBeNull();
});
it('rejects empty download URLs', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
await expect(service.addDownload('')).rejects.toThrow('Invalid download URL');
});
it('extracts info hash from magnet links', () => {
const service = new DelugeService('http://deluge', '', 'pass');
const hash = (service as any).extractHashFromMagnet(
'magnet:?xt=urn:btih:0123456789ABCDEF0123456789ABCDEF01234567'
);
expect(hash).toBe('0123456789abcdef0123456789abcdef01234567');
expect((service as any).extractHashFromMagnet('magnet:?xt=urn:btih:')).toBeNull();
});
it('adds magnet links successfully', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
// Mock: check duplicate (not found)
mockRpc({});
// Mock: add_torrent_magnet
mockRpc('0123456789abcdef0123456789abcdef01234567');
// Mock: set_torrent_options (disable seed limits)
mockRpc(null);
// Mock: label.add (ensure label)
mockRpc(null);
// Mock: label.set_torrent
mockRpc(null);
const hash = await service.addDownload(
'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567'
);
expect(hash).toBe('0123456789abcdef0123456789abcdef01234567');
});
it('skips adding duplicate magnet links', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
// Mock: duplicate found
mockRpc({ name: 'Existing Audiobook' });
const hash = await service.addDownload(
'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567'
);
expect(hash).toBe('0123456789abcdef0123456789abcdef01234567');
// Only 1 RPC call (the duplicate check), no add call
expect(clientMock.post).toHaveBeenCalledTimes(1);
});
it('throws when Deluge rejects a magnet link', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
mockRpc({}); // not duplicate
mockRpc(null, { message: 'rejected' }); // add returns null (failure)
await expect(service.addDownload(
'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567'
)).rejects.toThrow('Deluge rejected magnet link');
});
it('adds torrent files after parsing', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
axiosMock.get.mockResolvedValueOnce({ data: Buffer.from('torrent-data') });
parseTorrentMock.mockResolvedValueOnce({ infoHash: 'hash-1', name: 'Book' });
mockRpc({}); // not duplicate
mockRpc('hash-1'); // add_torrent_file
mockRpc(null); // set_torrent_options
mockRpc(null); // label.add
mockRpc(null); // label.set_torrent
const hash = await service.addDownload('http://example.com/file.torrent');
expect(hash).toBe('hash-1');
});
it('follows redirect to magnet link', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
axiosMock.get.mockRejectedValueOnce({
isAxiosError: true,
response: { status: 302, headers: { location: 'magnet:?xt=urn:btih:abcdef0123456789abcdef0123456789abcdef01' } },
});
// Magnet duplicate check
mockRpc({});
mockRpc('abcdef0123456789abcdef0123456789abcdef01');
mockRpc(null); // set_torrent_options
mockRpc(null); // label.add
mockRpc(null); // label.set_torrent
const hash = await service.addDownload('http://example.com/file.torrent');
expect(hash).toBe('abcdef0123456789abcdef0123456789abcdef01');
});
it('throws for invalid redirect locations', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
axiosMock.get.mockRejectedValueOnce({
isAxiosError: true,
response: { status: 302, headers: { location: 'ftp://bad' } },
});
await expect(service.addDownload('http://example.com/file.torrent')).rejects.toThrow('Invalid redirect location');
});
it('throws when torrent file parsing fails', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
axiosMock.get.mockResolvedValueOnce({ data: Buffer.from('bad-data') });
parseTorrentMock.mockRejectedValueOnce(new Error('bad torrent'));
await expect(service.addDownload('http://example.com/file.torrent')).rejects.toThrow('Invalid .torrent file');
});
it('pauses and resumes torrents', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
mockRpc(null);
await service.pauseDownload('hash-1');
mockRpc(null);
await service.resumeDownload('hash-1');
// Verify pause used array of hashes
const pauseCall = clientMock.post.mock.calls[0];
expect(pauseCall[1].method).toBe('core.pause_torrent');
expect(pauseCall[1].params).toEqual([['hash-1']]);
// Verify resume used array of hashes
const resumeCall = clientMock.post.mock.calls[1];
expect(resumeCall[1].method).toBe('core.resume_torrent');
expect(resumeCall[1].params).toEqual([['hash-1']]);
});
it('deletes torrents with correct parameters', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
mockRpc(null);
await service.deleteDownload('hash-1', true);
const deleteCall = clientMock.post.mock.calls[0];
expect(deleteCall[1].method).toBe('core.remove_torrent');
expect(deleteCall[1].params).toEqual(['hash-1', true]);
});
it('returns labels from Label plugin', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
mockRpc(['readmeabook', 'movies', 'tv']);
const categories = await service.getCategories();
expect(categories).toEqual(['readmeabook', 'movies', 'tv']);
});
it('returns empty array when Label plugin is not available', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
(service as any).sessionCookie = '_session_id=abc';
clientMock.post.mockRejectedValueOnce(new Error('Unknown method'));
const categories = await service.getCategories();
expect(categories).toEqual([]);
});
it('postProcess is a no-op', async () => {
const service = new DelugeService('http://deluge', '', 'pass');
await expect(service.postProcess('hash-1')).resolves.toBeUndefined();
});
describe('singleton getDelugeService()', () => {
it('throws when no Deluge client is configured', async () => {
downloadClientManagerMock.getClientForProtocol.mockResolvedValue(null);
await expect(getDelugeService()).rejects.toThrow('Deluge is not configured');
});
it('throws when configured client is not deluge type', async () => {
downloadClientManagerMock.getClientForProtocol.mockResolvedValue({
id: 'c1', type: 'qbittorrent', name: 'qB', enabled: true,
url: 'http://qb', password: 'pass', disableSSLVerify: false,
remotePathMappingEnabled: false,
});
configServiceMock.get.mockResolvedValue('/downloads');
await expect(getDelugeService()).rejects.toThrow('Expected Deluge client but found qbittorrent');
});
it('creates and caches instance on success', async () => {
downloadClientManagerMock.getClientForProtocol.mockResolvedValue({
id: 'c1', type: 'deluge', name: 'Deluge', enabled: true,
url: 'http://deluge', password: 'pass', disableSSLVerify: false,
remotePathMappingEnabled: false,
});
configServiceMock.get.mockResolvedValue('/downloads');
const testSpy = vi.spyOn(DelugeService.prototype, 'testConnection')
.mockResolvedValue({ success: true, message: 'Connected' });
const first = await getDelugeService();
const second = await getDelugeService();
expect(first).toBe(second);
expect(downloadClientManagerMock.getClientForProtocol).toHaveBeenCalledTimes(1);
testSpy.mockRestore();
});
});
});
+192 -2
View File
@@ -3,6 +3,7 @@
* Documentation: documentation/phase3/qbittorrent.md
*/
import path from 'path';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { QBittorrentService, getQBittorrentService, invalidateQBittorrentService } from '@/lib/integrations/qbittorrent.service';
@@ -180,7 +181,7 @@ describe('QBittorrentService', () => {
});
});
describe('mapState - pausedUP/stoppedUP as completion states (RDT-Client compatibility)', () => {
describe('mapState - pausedUP/stoppedUP as completion states', () => {
it('maps pausedUP to completed (download finished, paused on upload side)', () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
const progress = service.getDownloadProgress({
@@ -254,7 +255,7 @@ describe('QBittorrentService', () => {
expect(info!.status).toBe('seeding');
});
it('maps pausedUP to seeding status (RDT-Client: download finished, paused on upload side)', async () => {
it('maps pausedUP to seeding status (download finished, paused on upload side)', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=pausedup';
clientMock.get.mockResolvedValueOnce({
@@ -328,6 +329,164 @@ describe('QBittorrentService', () => {
});
});
describe('downloadPath resolution (TempPathEnabled race condition fix)', () => {
it('uses save_path for seeding torrents even when content_path points to temp dir', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=temppath';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
dlspeed: 0, upspeed: 5000, downloaded: 1000, uploaded: 500,
eta: 0, state: 'uploading', category: 'readmeabook', tags: '',
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
completion_on: 1700000000, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info).not.toBeNull();
expect(info!.status).toBe('seeding');
// Must use save_path + name, NOT the stale content_path
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
expect(info!.downloadPath).not.toContain('incomplete');
});
it('uses save_path for stalledUP torrents (completed, stalled on upload)', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=stalledup';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
dlspeed: 0, upspeed: 0, downloaded: 1000, uploaded: 200,
eta: 0, state: 'stalledUP', category: 'readmeabook', tags: '',
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
completion_on: 1700000000, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info!.status).toBe('seeding');
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
});
it('uses save_path for pausedUP torrents (completed, paused on upload)', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=pausedup2';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
dlspeed: 0, upspeed: 0, downloaded: 1000, uploaded: 0,
eta: 0, state: 'pausedUP', category: 'readmeabook', tags: '',
save_path: '/data/torrents/readmeabook/', content_path: '/tmp/incomplete/Audiobook',
completion_on: 1700000000, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info!.status).toBe('seeding');
expect(info!.downloadPath).toBe(path.join('/data/torrents/readmeabook/', 'Audiobook'));
});
it('uses save_path for stoppedUP torrents (qBittorrent v5.x completed)', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=stoppedup2';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
dlspeed: 0, upspeed: 0, downloaded: 1000, uploaded: 100,
eta: 0, state: 'stoppedUP', category: 'readmeabook', tags: '',
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
completion_on: 1700000000, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info!.status).toBe('seeding');
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
});
it('uses content_path for actively downloading torrents', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=downloading';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 0.5,
dlspeed: 5000, upspeed: 0, downloaded: 500, uploaded: 0,
eta: 100, state: 'downloading', category: 'readmeabook', tags: '',
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
completion_on: 0, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info!.status).toBe('downloading');
// During download, content_path is used (points to where files currently are)
expect(info!.downloadPath).toBe('/incomplete/Audiobook');
});
it('falls back to save_path + name when content_path is empty during download', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=nocontent';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 0.3,
dlspeed: 1000, upspeed: 0, downloaded: 300, uploaded: 0,
eta: 700, state: 'downloading', category: 'readmeabook', tags: '',
save_path: '/downloads/', content_path: '',
completion_on: 0, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info!.status).toBe('downloading');
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
});
it('uses save_path for forcedUP torrents (force-resumed seeding)', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=forcedup2';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
dlspeed: 0, upspeed: 10000, downloaded: 1000, uploaded: 2000,
eta: 0, state: 'forcedUP', category: 'readmeabook', tags: '',
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
completion_on: 1700000000, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info!.status).toBe('seeding');
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
});
it('uses save_path for queuedUP torrents (completed, queued for upload)', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=queuedup';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
dlspeed: 0, upspeed: 0, downloaded: 1000, uploaded: 0,
eta: 0, state: 'queuedUP', category: 'readmeabook', tags: '',
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
completion_on: 1700000000, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info!.status).toBe('seeding');
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
});
});
it('authenticates and stores a session cookie', async () => {
axiosMock.post.mockResolvedValue({
status: 200,
@@ -770,6 +929,37 @@ describe('QBittorrentService', () => {
await expect(service.getTorrent('hash-404')).rejects.toThrow('Torrent hash-404 not found');
});
it('ignores unrelated torrents returned by RDTClient-like clients that ignore hash filter', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=rdtclient';
// RDTClient ignores the hashes param and returns all torrents
clientMock.get.mockResolvedValueOnce({
data: [
{ hash: 'aaaa1111bbbb2222cccc3333dddd4444eeee5555', name: 'Other Book' },
{ hash: 'ffff6666aaaa7777bbbb8888cccc9999dddd0000', name: 'Another Book' },
],
});
await expect(
service.getTorrent('0f54898dc1b8e49d96e32827377f651ea6c935af')
).rejects.toThrow('Torrent 0f54898dc1b8e49d96e32827377f651ea6c935af not found');
});
it('finds the correct torrent when RDTClient returns all torrents including the match', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=rdtclient2';
clientMock.get.mockResolvedValueOnce({
data: [
{ hash: 'aaaa1111bbbb2222cccc3333dddd4444eeee5555', name: 'Other Book' },
{ hash: '0F54898DC1B8E49D96E32827377F651EA6C935AF', name: 'Target Book' },
],
});
const result = await service.getTorrent('0f54898dc1b8e49d96e32827377f651ea6c935af');
expect(result.name).toBe('Target Book');
});
it('returns error when getTorrents fails', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=list';
+350 -2
View File
@@ -8,6 +8,9 @@ import {
validateTemplate,
generateMockPreviews,
getValidVariables,
validateFilenameTemplate,
generateMockFilenamePreviews,
buildRenamedFilename,
type TemplateVariables
} from '@/lib/utils/path-template.util';
@@ -213,6 +216,142 @@ describe('substituteTemplate', () => {
const result = substituteTemplate(template, variables);
expect(result).toBe('Author/{narrated}/Title');
});
// Conditional block tests
it('should render conditional block when variable has a value', () => {
const template = '{author}/{Book seriesPart - }{title}';
const variables: TemplateVariables = {
author: 'Brandon Sanderson',
title: 'Mistborn',
seriesPart: '1'
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Brandon Sanderson/Book 1 - Mistborn');
});
it('should remove conditional block when variable is missing', () => {
const template = '{author}/{Book seriesPart - }{title}';
const variables: TemplateVariables = {
author: 'Andy Weir',
title: 'Project Hail Mary'
// seriesPart is missing
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Andy Weir/Project Hail Mary');
});
it('should handle conditional block with path separator', () => {
const template = '{author}/{series/Book seriesPart - }{title}';
const variables: TemplateVariables = {
author: 'Brandon Sanderson',
title: 'Mistborn',
series: 'The Mistborn Saga',
seriesPart: '1'
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Brandon Sanderson/The Mistborn Saga/Book 1 - Mistborn');
});
it('should render conditional block when all variables present', () => {
const template = '{author}/{series Book seriesPart}/{title}';
const variables: TemplateVariables = {
author: 'Brandon Sanderson',
title: 'Mistborn',
series: 'The Mistborn Saga',
seriesPart: '1'
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Brandon Sanderson/The Mistborn Saga Book 1/Mistborn');
});
it('should remove conditional block when any variable is missing', () => {
const template = '{author}/{series Book seriesPart}/{title}';
const variables: TemplateVariables = {
author: 'Andy Weir',
title: 'Project Hail Mary',
series: 'Some Series'
// seriesPart is missing
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Andy Weir/Project Hail Mary');
});
it('should handle adjacent conditional blocks', () => {
const template = '{author}/{series - }{Book seriesPart - }{title}';
const variables: TemplateVariables = {
author: 'Brandon Sanderson',
title: 'Mistborn',
series: 'The Mistborn Saga',
seriesPart: '1'
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Brandon Sanderson/The Mistborn Saga - Book 1 - Mistborn');
});
it('should handle conditional block next to simple variable', () => {
const template = '{author}/{series - }{title}';
const variables: TemplateVariables = {
author: 'Andy Weir',
title: 'Project Hail Mary'
// series is missing
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Andy Weir/Project Hail Mary');
});
it('should handle conditional block with year variable', () => {
const template = '{author}/{title} {(year)}';
const variables: TemplateVariables = {
author: 'Brandon Sanderson',
title: 'Mistborn',
year: 2006
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Brandon Sanderson/Mistborn (2006)');
});
it('should remove year conditional block when year is missing', () => {
const template = '{author}/{title} {(year)}';
const variables: TemplateVariables = {
author: 'Andy Weir',
title: 'Project Hail Mary'
// year is missing
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Andy Weir/Project Hail Mary');
});
it('should still handle simple variables correctly (regression)', () => {
const template = '{author}/{title}';
const variables: TemplateVariables = {
author: 'Brandon Sanderson',
title: 'Mistborn'
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Brandon Sanderson/Mistborn');
});
it('should remove conditional block when variable is empty string', () => {
const template = '{author}/{Book seriesPart - }{title}';
const variables: TemplateVariables = {
author: 'Author',
title: 'Title',
seriesPart: ''
};
const result = substituteTemplate(template, variables);
expect(result).toBe('Author/Title');
});
});
describe('validateTemplate', () => {
@@ -247,7 +386,7 @@ describe('validateTemplate', () => {
it('should reject unknown variables', () => {
const result = validateTemplate('{author}/{invalid}');
expect(result.valid).toBe(false);
expect(result.error).toContain('Unknown variable');
expect(result.error).toContain('No valid variable found in conditional block');
expect(result.error).toContain('{invalid}');
});
@@ -287,12 +426,13 @@ describe('validateTemplate', () => {
it('should provide helpful error messages for multiple unknown variables', () => {
const result = validateTemplate('{author}/{invalid1}/{invalid2}');
expect(result.valid).toBe(false);
expect(result.error).toContain('Unknown variable');
expect(result.error).toContain('No valid variable found in conditional block');
});
it('should list valid variables in error message', () => {
const result = validateTemplate('{invalid}');
expect(result.valid).toBe(false);
expect(result.error).toContain('No valid variable found in conditional block');
expect(result.error).toContain('{author}');
expect(result.error).toContain('{title}');
expect(result.error).toContain('{narrator}');
@@ -334,6 +474,34 @@ describe('validateTemplate', () => {
const result = validateTemplate('\\{\\}');
expect(result.valid).toBe(true);
});
// Conditional block validation tests
it('should accept conditional blocks with valid variables', () => {
const result = validateTemplate('{author}/{Book seriesPart - }{title}');
expect(result.valid).toBe(true);
});
it('should accept conditional blocks with multiple variables', () => {
const result = validateTemplate('{author}/{series Book seriesPart}/{title}');
expect(result.valid).toBe(true);
});
it('should reject conditional blocks with no valid variables', () => {
const result = validateTemplate('{author}/{random text}/{title}');
expect(result.valid).toBe(false);
expect(result.error).toContain('No valid variable found in conditional block');
});
it('should reject conditional blocks with invalid path chars inside', () => {
const result = validateTemplate('{author}/{series: part}/{title}');
expect(result.valid).toBe(false);
expect(result.error).toContain('Invalid characters');
});
it('should accept mix of simple variables and conditional blocks', () => {
const result = validateTemplate('{author}/{series - }{Book seriesPart - }{title} {(year)}');
expect(result.valid).toBe(true);
});
});
describe('generateMockPreviews', () => {
@@ -444,3 +612,183 @@ describe('getValidVariables', () => {
expect(vars1).not.toBe(vars2); // Different array instances
});
});
describe('validateFilenameTemplate', () => {
it('should accept valid filename templates', () => {
const templates = [
'{title}',
'{author} - {title}',
'{title} ({year})',
'{author} - {title} {(year)}',
];
templates.forEach(template => {
const result = validateFilenameTemplate(template);
expect(result.valid).toBe(true);
expect(result.error).toBeUndefined();
});
});
it('should reject empty templates', () => {
const result = validateFilenameTemplate('');
expect(result.valid).toBe(false);
expect(result.error).toContain('empty');
});
it('should reject templates containing forward slashes', () => {
const result = validateFilenameTemplate('{author}/{title}');
expect(result.valid).toBe(false);
expect(result.error).toContain('/');
expect(result.error).toContain('directory separator');
});
it('should reject templates containing backslashes (not brace escapes)', () => {
const result = validateFilenameTemplate('{author}\\n{title}');
expect(result.valid).toBe(false);
expect(result.error).toContain('backslash');
});
it('should accept escaped braces in filename templates', () => {
const result = validateFilenameTemplate('\\{{title}\\}');
expect(result.valid).toBe(true);
});
it('should reject unknown variables', () => {
const result = validateFilenameTemplate('{invalid}');
expect(result.valid).toBe(false);
expect(result.error).toContain('No valid variable found');
});
it('should reject invalid characters', () => {
const invalidChars = ['<', '>', ':', '"', '|', '?', '*'];
invalidChars.forEach(char => {
const result = validateFilenameTemplate(`{title}${char}extra`);
expect(result.valid).toBe(false);
expect(result.error).toContain('Invalid characters');
});
});
it('should accept conditional blocks in filename templates', () => {
const result = validateFilenameTemplate('{title} {(year)}');
expect(result.valid).toBe(true);
});
it('should accept templates with only static text', () => {
const result = validateFilenameTemplate('audiobook');
expect(result.valid).toBe(true);
});
});
describe('generateMockFilenamePreviews', () => {
it('should return single and multi-file previews', () => {
const result = generateMockFilenamePreviews('{title}');
expect(result.single).toBeDefined();
expect(result.multi).toBeDefined();
expect(result.single.length).toBe(2);
expect(result.multi.length).toBe(3);
});
it('should include file extensions in single previews', () => {
const result = generateMockFilenamePreviews('{title}');
result.single.forEach(preview => {
expect(preview).toMatch(/\.m4b$/);
});
});
it('should include index and extensions in multi-file previews', () => {
const result = generateMockFilenamePreviews('{title}');
expect(result.multi[0]).toMatch(/ - 1\.mp3$/);
expect(result.multi[1]).toMatch(/ - 2\.mp3$/);
expect(result.multi[2]).toMatch(/ - 3\.mp3$/);
});
it('should substitute variables correctly', () => {
const result = generateMockFilenamePreviews('{author} - {title}');
expect(result.single[0]).toContain('Brandon Sanderson');
expect(result.single[0]).toContain('Mistborn');
expect(result.single[1]).toContain('Douglas Adams');
});
});
describe('buildRenamedFilename', () => {
const baseVariables: TemplateVariables = {
author: 'Brandon Sanderson',
title: 'Mistborn: The Final Empire',
narrator: 'Michael Kramer',
asin: 'B002UZMLXM',
year: 2006,
};
it('should build a renamed filename with extension', () => {
const result = buildRenamedFilename('{title}', baseVariables, '.m4b');
expect(result).toBe('Mistborn The Final Empire.m4b');
});
it('should append index for multi-file scenarios', () => {
const result = buildRenamedFilename('{title}', baseVariables, '.mp3', 1);
expect(result).toBe('Mistborn The Final Empire - 1.mp3');
});
it('should handle multiple variables', () => {
const result = buildRenamedFilename('{author} - {title}', baseVariables, '.m4b');
expect(result).toBe('Brandon Sanderson - Mistborn The Final Empire.m4b');
});
it('should handle extension without leading dot', () => {
const result = buildRenamedFilename('{title}', baseVariables, 'mp3');
expect(result).toBe('Mistborn The Final Empire.mp3');
});
it('should sanitize invalid characters from variable values', () => {
const vars: TemplateVariables = {
author: 'Author: <Test>',
title: 'Title|Book*'
};
const result = buildRenamedFilename('{author} - {title}', vars, '.m4b');
expect(result).not.toContain(':');
expect(result).not.toContain('<');
expect(result).not.toContain('>');
expect(result).not.toContain('|');
expect(result).not.toContain('*');
});
it('should strip slashes from conditional block output', () => {
const result = buildRenamedFilename('{author}/{title}', baseVariables, '.m4b');
expect(result).not.toContain('/');
expect(result).not.toContain('\\');
});
it('should handle conditional blocks', () => {
const result = buildRenamedFilename('{title} {(year)}', baseVariables, '.m4b');
expect(result).toBe('Mistborn The Final Empire (2006).m4b');
});
it('should remove conditional blocks when variable is missing', () => {
const vars: TemplateVariables = {
author: 'Andy Weir',
title: 'Project Hail Mary',
};
const result = buildRenamedFilename('{title} {(year)}', vars, '.m4b');
expect(result).toBe('Project Hail Mary.m4b');
});
it('should handle index appended after conditional blocks', () => {
const result = buildRenamedFilename('{title} {(year)}', baseVariables, '.mp3', 5);
expect(result).toBe('Mistborn The Final Empire (2006) - 5.mp3');
});
it('should limit very long filenames', () => {
const vars: TemplateVariables = {
author: 'Author',
title: 'A'.repeat(300),
};
const result = buildRenamedFilename('{title}', vars, '.m4b');
// 200 char limit on base name + extension
expect(result.length).toBeLessThanOrEqual(204); // 200 + '.m4b'
});
});
@@ -343,9 +343,9 @@ describe('processMonitorDownload', () => {
requestId: 'req-6',
downloadHistoryId: 'dh-6',
downloadClientId: 'id-6',
downloadClient: 'deluge',
downloadClient: 'rtorrent',
jobId: 'job-6',
})).rejects.toThrow(/Unknown download client type: deluge/);
})).rejects.toThrow(/Unknown download client type: rtorrent/);
expect(prismaMock.request.update).toHaveBeenCalledWith(
expect.objectContaining({