mirror of
https://github.com/kikootwo/ReadMeABook.git
synced 2026-06-03 04:40:09 +00:00
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.
This commit is contained in:
@@ -243,7 +243,7 @@ type TorrentState =
|
|||||||
- `forcedUP` → `seeding`/`completed` enables monitor to trigger import
|
- `forcedUP` → `seeding`/`completed` enables monitor to trigger import
|
||||||
- `stoppedDL` → `paused` ensures qBittorrent v5.x compatibility
|
- `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
|
- `pausedUP` → `seeding` (unified) / `completed` (legacy) — triggers completion in monitor
|
||||||
- `stoppedUP` → `seeding` (unified) / `completed` (legacy) — same fix for qBittorrent v5.x
|
- `stoppedUP` → `seeding` (unified) / `completed` (legacy) — same fix for qBittorrent v5.x
|
||||||
- `pausedDL`/`stoppedDL` remain `paused` — download phase genuinely paused
|
- `pausedDL`/`stoppedDL` remain `paused` — download phase genuinely paused
|
||||||
|
|||||||
+209
-123
@@ -78,13 +78,11 @@ function AdminJobsPageContent() {
|
|||||||
const showEditDialog = (job: ScheduledJob) => {
|
const showEditDialog = (job: ScheduledJob) => {
|
||||||
setEditForm({ schedule: job.schedule, enabled: job.enabled });
|
setEditForm({ schedule: job.schedule, enabled: job.enabled });
|
||||||
|
|
||||||
// Check if it's a preset
|
|
||||||
const preset = SCHEDULE_PRESETS.find(p => p.cron === job.schedule);
|
const preset = SCHEDULE_PRESETS.find(p => p.cron === job.schedule);
|
||||||
if (preset) {
|
if (preset) {
|
||||||
setScheduleMode('preset');
|
setScheduleMode('preset');
|
||||||
setSelectedPreset(preset.cron);
|
setSelectedPreset(preset.cron);
|
||||||
} else {
|
} else {
|
||||||
// Try to parse as custom schedule
|
|
||||||
const parsed = cronToCustomSchedule(job.schedule);
|
const parsed = cronToCustomSchedule(job.schedule);
|
||||||
if (parsed.type === 'custom') {
|
if (parsed.type === 'custom') {
|
||||||
setScheduleMode('advanced');
|
setScheduleMode('advanced');
|
||||||
@@ -111,7 +109,7 @@ function AdminJobsPageContent() {
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
});
|
});
|
||||||
toast.success(`Job "${jobName}" triggered successfully`);
|
toast.success(`Job "${jobName}" triggered successfully`);
|
||||||
fetchJobs(); // Refresh list
|
fetchJobs();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errorMsg = err instanceof Error ? err.message : 'Failed to trigger job';
|
const errorMsg = err instanceof Error ? err.message : 'Failed to trigger job';
|
||||||
toast.error(errorMsg);
|
toast.error(errorMsg);
|
||||||
@@ -124,7 +122,6 @@ function AdminJobsPageContent() {
|
|||||||
const saveJobSchedule = async () => {
|
const saveJobSchedule = async () => {
|
||||||
if (!editDialog.job) return;
|
if (!editDialog.job) return;
|
||||||
|
|
||||||
// Calculate final cron expression based on mode
|
|
||||||
let finalCron: string;
|
let finalCron: string;
|
||||||
if (scheduleMode === 'preset') {
|
if (scheduleMode === 'preset') {
|
||||||
finalCron = selectedPreset;
|
finalCron = selectedPreset;
|
||||||
@@ -134,7 +131,6 @@ function AdminJobsPageContent() {
|
|||||||
finalCron = editForm.schedule;
|
finalCron = editForm.schedule;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate cron expression
|
|
||||||
if (!isValidCron(finalCron)) {
|
if (!isValidCron(finalCron)) {
|
||||||
toast.error('Invalid cron expression. Please check your schedule.');
|
toast.error('Invalid cron expression. Please check your schedule.');
|
||||||
return;
|
return;
|
||||||
@@ -151,7 +147,7 @@ function AdminJobsPageContent() {
|
|||||||
});
|
});
|
||||||
toast.success(`Job "${editDialog.job.name}" updated successfully`);
|
toast.success(`Job "${editDialog.job.name}" updated successfully`);
|
||||||
hideEditDialog();
|
hideEditDialog();
|
||||||
fetchJobs(); // Refresh list
|
fetchJobs();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errorMsg = err instanceof Error ? err.message : 'Failed to update job';
|
const errorMsg = err instanceof Error ? err.message : 'Failed to update job';
|
||||||
toast.error(errorMsg);
|
toast.error(errorMsg);
|
||||||
@@ -173,36 +169,131 @@ function AdminJobsPageContent() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
|
<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">
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm: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">
|
{/* Header — stacks on mobile, row on sm+ */}
|
||||||
<div>
|
<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">
|
||||||
<h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">
|
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||||
Scheduled Jobs
|
<div>
|
||||||
</h1>
|
<h1 className="text-2xl sm:text-3xl font-bold text-gray-900 dark:text-gray-100">
|
||||||
<p className="text-gray-600 dark:text-gray-400 mt-2">
|
Scheduled Jobs
|
||||||
Manage recurring tasks and automated jobs
|
</h1>
|
||||||
</p>
|
<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>
|
</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>
|
</div>
|
||||||
|
|
||||||
{error && (
|
{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">
|
<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>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Jobs Table */}
|
{/* Jobs — Card layout on mobile, Table on sm+ */}
|
||||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
|
<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">
|
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
|
||||||
<thead className="bg-gray-50 dark:bg-gray-900">
|
<thead className="bg-gray-50 dark:bg-gray-900">
|
||||||
<tr>
|
<tr>
|
||||||
@@ -312,31 +403,31 @@ function AdminJobsPageContent() {
|
|||||||
<ul className="text-sm text-blue-700 dark:text-blue-300 space-y-1">
|
<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>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>• <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 "Trigger Now" button</li>
|
||||||
<li>• Schedule format follows cron syntax (minute hour day month weekday)</li>
|
<li>• Schedule format follows cron syntax (minute hour day month weekday)</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Confirmation Dialog */}
|
{/* Confirmation Dialog */}
|
||||||
{confirmDialog.isOpen && (
|
{confirmDialog.isOpen && (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 p-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-lg shadow-xl max-w-md w-full p-6">
|
<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-4">
|
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-3">
|
||||||
Confirm Job Trigger
|
Confirm Job Trigger
|
||||||
</h3>
|
</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 "{confirmDialog.jobName}" now?
|
Are you sure you want to trigger "{confirmDialog.jobName}" now?
|
||||||
</p>
|
</p>
|
||||||
<div className="flex justify-end gap-3">
|
<div className="flex gap-3">
|
||||||
<button
|
<button
|
||||||
onClick={hideConfirmDialog}
|
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
|
Cancel
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={triggerJob}
|
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
|
Trigger Job
|
||||||
</button>
|
</button>
|
||||||
@@ -347,12 +438,27 @@ function AdminJobsPageContent() {
|
|||||||
|
|
||||||
{/* Edit Job Dialog */}
|
{/* Edit Job Dialog */}
|
||||||
{editDialog.isOpen && editDialog.job && (
|
{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="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-lg shadow-xl max-w-2xl w-full p-6 max-h-[90vh] overflow-y-auto">
|
<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">
|
||||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">
|
{/* Dialog header */}
|
||||||
Edit Job Schedule
|
<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">
|
||||||
</h3>
|
<div className="flex items-center justify-between">
|
||||||
<div className="space-y-4 mb-6">
|
<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 */}
|
{/* Job Name */}
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||||
@@ -362,46 +468,29 @@ function AdminJobsPageContent() {
|
|||||||
type="text"
|
type="text"
|
||||||
value={editDialog.job.name}
|
value={editDialog.job.name}
|
||||||
disabled
|
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>
|
</div>
|
||||||
|
|
||||||
{/* Schedule Mode Tabs */}
|
{/* Schedule Mode Tabs — grid on mobile to avoid overflow */}
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||||
Schedule Type
|
Schedule Type
|
||||||
</label>
|
</label>
|
||||||
<div className="flex gap-2 mb-3">
|
<div className="grid grid-cols-3 gap-1 p-1 bg-gray-100 dark:bg-gray-700/60 rounded-xl mb-4">
|
||||||
<button
|
{(['preset', 'custom', 'advanced'] as const).map((mode) => (
|
||||||
onClick={() => setScheduleMode('preset')}
|
<button
|
||||||
className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
|
key={mode}
|
||||||
scheduleMode === 'preset'
|
onClick={() => setScheduleMode(mode)}
|
||||||
? 'bg-blue-600 text-white'
|
className={`px-2 py-2 rounded-lg text-xs font-medium transition-colors ${
|
||||||
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
|
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'
|
||||||
Common Schedules
|
}`}
|
||||||
</button>
|
>
|
||||||
<button
|
{mode === 'preset' ? 'Common' : mode === 'custom' ? 'Custom' : 'Advanced'}
|
||||||
onClick={() => setScheduleMode('custom')}
|
</button>
|
||||||
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>
|
</div>
|
||||||
|
|
||||||
{/* Preset Mode */}
|
{/* Preset Mode */}
|
||||||
@@ -418,16 +507,16 @@ function AdminJobsPageContent() {
|
|||||||
value={preset.cron}
|
value={preset.cron}
|
||||||
checked={selectedPreset === preset.cron}
|
checked={selectedPreset === preset.cron}
|
||||||
onChange={(e) => setSelectedPreset(e.target.value)}
|
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">
|
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||||
{preset.label}
|
{preset.label}
|
||||||
</div>
|
</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}
|
{preset.description}
|
||||||
</div>
|
</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}
|
{preset.cron}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -445,8 +534,8 @@ function AdminJobsPageContent() {
|
|||||||
</label>
|
</label>
|
||||||
<select
|
<select
|
||||||
value={customSchedule.type}
|
value={customSchedule.type}
|
||||||
onChange={(e) => setCustomSchedule({ ...customSchedule, type: e.target.value as any })}
|
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"
|
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="minutes">Every X minutes</option>
|
||||||
<option value="hours">Every X hours</option>
|
<option value="hours">Every X hours</option>
|
||||||
@@ -456,7 +545,6 @@ function AdminJobsPageContent() {
|
|||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Minutes/Hours Interval */}
|
|
||||||
{(customSchedule.type === 'minutes' || customSchedule.type === 'hours') && (
|
{(customSchedule.type === 'minutes' || customSchedule.type === 'hours') && (
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
<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}
|
max={customSchedule.type === 'minutes' ? 59 : 23}
|
||||||
value={customSchedule.interval || 1}
|
value={customSchedule.interval || 1}
|
||||||
onChange={(e) => setCustomSchedule({ ...customSchedule, interval: parseInt(e.target.value, 10) })}
|
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">
|
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||||
Run every {customSchedule.interval || 1} {customSchedule.type}
|
Run every {customSchedule.interval || 1} {customSchedule.type}
|
||||||
@@ -476,12 +564,11 @@ function AdminJobsPageContent() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Daily/Weekly/Monthly Time */}
|
|
||||||
{(customSchedule.type === 'daily' || customSchedule.type === 'weekly' || customSchedule.type === 'monthly') && (
|
{(customSchedule.type === 'daily' || customSchedule.type === 'weekly' || customSchedule.type === 'monthly') && (
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<div className="grid grid-cols-2 gap-4">
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||||
Hour (0-23)
|
Hour (0–23)
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
@@ -494,12 +581,12 @@ function AdminJobsPageContent() {
|
|||||||
time: { hour: parseInt(e.target.value, 10), minute: customSchedule.time?.minute || 0 },
|
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>
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||||
Minute (0-59)
|
Minute (0–59)
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
@@ -512,13 +599,12 @@ function AdminJobsPageContent() {
|
|||||||
time: { hour: customSchedule.time?.hour || 0, minute: parseInt(e.target.value, 10) },
|
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>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Weekly Day Selection */}
|
|
||||||
{customSchedule.type === 'weekly' && (
|
{customSchedule.type === 'weekly' && (
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||||
@@ -527,7 +613,7 @@ function AdminJobsPageContent() {
|
|||||||
<select
|
<select
|
||||||
value={customSchedule.dayOfWeek || 0}
|
value={customSchedule.dayOfWeek || 0}
|
||||||
onChange={(e) => setCustomSchedule({ ...customSchedule, dayOfWeek: parseInt(e.target.value, 10) })}
|
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="0">Sunday</option>
|
||||||
<option value="1">Monday</option>
|
<option value="1">Monday</option>
|
||||||
@@ -540,11 +626,10 @@ function AdminJobsPageContent() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Monthly Day Selection */}
|
|
||||||
{customSchedule.type === 'monthly' && (
|
{customSchedule.type === 'monthly' && (
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||||
Day of Month (1-31)
|
Day of Month (1–31)
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
@@ -552,12 +637,11 @@ function AdminJobsPageContent() {
|
|||||||
max="31"
|
max="31"
|
||||||
value={customSchedule.dayOfMonth || 1}
|
value={customSchedule.dayOfMonth || 1}
|
||||||
onChange={(e) => setCustomSchedule({ ...customSchedule, dayOfMonth: parseInt(e.target.value, 10) })}
|
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>
|
</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="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">
|
<div className="text-sm font-medium text-blue-900 dark:text-blue-200">
|
||||||
Preview: {cronToHuman(customScheduleToCron(customSchedule))}
|
Preview: {cronToHuman(customScheduleToCron(customSchedule))}
|
||||||
@@ -571,30 +655,32 @@ function AdminJobsPageContent() {
|
|||||||
|
|
||||||
{/* Advanced Mode */}
|
{/* Advanced Mode */}
|
||||||
{scheduleMode === 'advanced' && (
|
{scheduleMode === 'advanced' && (
|
||||||
<div>
|
<div className="space-y-3">
|
||||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
<div>
|
||||||
Cron Expression
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||||
</label>
|
Cron Expression
|
||||||
<input
|
</label>
|
||||||
type="text"
|
<input
|
||||||
value={editForm.schedule}
|
type="text"
|
||||||
onChange={(e) => setEditForm({ ...editForm, schedule: e.target.value })}
|
value={editForm.schedule}
|
||||||
placeholder="0 */6 * * *"
|
onChange={(e) => setEditForm({ ...editForm, schedule: e.target.value })}
|
||||||
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"
|
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 className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||||
</p>
|
Format: minute hour day month weekday
|
||||||
<div className="mt-2 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
|
</p>
|
||||||
<div className="text-xs text-gray-600 dark:text-gray-400 space-y-1">
|
</div>
|
||||||
<div>• */15 * * * * = Every 15 minutes</div>
|
<div className="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
|
||||||
<div>• 0 */6 * * * = Every 6 hours</div>
|
<div className="text-xs text-gray-600 dark:text-gray-400 space-y-1 font-mono">
|
||||||
<div>• 0 0 * * * = Daily at midnight</div>
|
<div>*/15 * * * * = Every 15 minutes</div>
|
||||||
<div>• 0 0 * * 0 = Weekly on Sunday</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>
|
||||||
</div>
|
</div>
|
||||||
{editForm.schedule && (
|
{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">
|
<div className="text-sm font-medium text-blue-900 dark:text-blue-200">
|
||||||
Preview: {cronToHuman(editForm.schedule)}
|
Preview: {cronToHuman(editForm.schedule)}
|
||||||
</div>
|
</div>
|
||||||
@@ -604,34 +690,34 @@ function AdminJobsPageContent() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Enabled Checkbox */}
|
{/* Enabled toggle */}
|
||||||
<div className="flex items-center gap-2 pt-4 border-t border-gray-200 dark:border-gray-700">
|
<div className="flex items-center gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
id="enabled"
|
id="enabled"
|
||||||
checked={editForm.enabled}
|
checked={editForm.enabled}
|
||||||
onChange={(e) => setEditForm({ ...editForm, enabled: e.target.checked })}
|
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
|
Enable this job
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Actions */}
|
{/* Dialog footer */}
|
||||||
<div className="flex justify-end gap-3">
|
<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
|
<button
|
||||||
onClick={hideEditDialog}
|
onClick={hideEditDialog}
|
||||||
disabled={saving}
|
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
|
Cancel
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={saveJobSchedule}
|
onClick={saveJobSchedule}
|
||||||
disabled={saving}
|
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'}
|
{saving ? 'Saving...' : 'Save Changes'}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
+236
-148
@@ -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() {
|
export default function AdminLogsPage() {
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
const [statusFilter, setStatusFilter] = useState('all');
|
const [statusFilter, setStatusFilter] = useState('all');
|
||||||
@@ -65,9 +178,7 @@ export default function AdminLogsPage() {
|
|||||||
const { data, error } = useSWR<LogsData>(
|
const { data, error } = useSWR<LogsData>(
|
||||||
`/api/admin/logs?page=${page}&limit=50&status=${statusFilter}&type=${typeFilter}`,
|
`/api/admin/logs?page=${page}&limit=50&status=${statusFilter}&type=${typeFilter}`,
|
||||||
authenticatedFetcher,
|
authenticatedFetcher,
|
||||||
{
|
{ refreshInterval: 10000 }
|
||||||
refreshInterval: 10000, // Refresh every 10 seconds
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const isLoading = !data && !error;
|
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="min-h-screen bg-gray-50 dark:bg-gray-900 p-8">
|
||||||
<div className="max-w-7xl mx-auto">
|
<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">
|
<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">
|
<h3 className="text-sm font-medium text-red-800 dark:text-red-200">Error Loading Logs</h3>
|
||||||
Error Loading Logs
|
|
||||||
</h3>
|
|
||||||
<p className="text-sm text-red-700 dark:text-red-300 mt-1">
|
<p className="text-sm text-red-700 dark:text-red-300 mt-1">
|
||||||
{error?.message || 'Failed to load system logs'}
|
{error?.message || 'Failed to load system logs'}
|
||||||
</p>
|
</p>
|
||||||
@@ -101,80 +210,45 @@ export default function AdminLogsPage() {
|
|||||||
|
|
||||||
const logs = data?.logs || [];
|
const logs = data?.logs || [];
|
||||||
const pagination = data?.pagination;
|
const pagination = data?.pagination;
|
||||||
|
const hasDetails = (log: Log) => log.events.length > 0 || !!log.errorMessage || !!log.bullJobId || (log.result && Object.keys(log.result).length > 0);
|
||||||
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`;
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
|
<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">
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm: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">
|
{/* Header — stacks on mobile, row on sm+ */}
|
||||||
<div>
|
<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">
|
||||||
<h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">
|
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||||
System Logs
|
<div>
|
||||||
</h1>
|
<h1 className="text-2xl sm:text-3xl font-bold text-gray-900 dark:text-gray-100">
|
||||||
<p className="text-gray-600 dark:text-gray-400 mt-2">
|
System Logs
|
||||||
View background jobs and system activity
|
</h1>
|
||||||
</p>
|
<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>
|
</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>
|
</div>
|
||||||
|
|
||||||
{/* Filters */}
|
{/* Filters — full-width stacked on mobile */}
|
||||||
<div className="mb-6 flex flex-wrap gap-4">
|
<div className="mb-6 grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
|
||||||
<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">
|
||||||
Status
|
Status
|
||||||
</label>
|
</label>
|
||||||
<select
|
<select
|
||||||
value={statusFilter}
|
value={statusFilter}
|
||||||
onChange={(e) => {
|
onChange={(e) => { setStatusFilter(e.target.value); setPage(1); }}
|
||||||
setStatusFilter(e.target.value);
|
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"
|
||||||
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"
|
|
||||||
>
|
>
|
||||||
<option value="all">All Statuses</option>
|
<option value="all">All Statuses</option>
|
||||||
<option value="pending">Pending</option>
|
<option value="pending">Pending</option>
|
||||||
@@ -186,16 +260,13 @@ export default function AdminLogsPage() {
|
|||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<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
|
Job Type
|
||||||
</label>
|
</label>
|
||||||
<select
|
<select
|
||||||
value={typeFilter}
|
value={typeFilter}
|
||||||
onChange={(e) => {
|
onChange={(e) => { setTypeFilter(e.target.value); setPage(1); }}
|
||||||
setTypeFilter(e.target.value);
|
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"
|
||||||
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"
|
|
||||||
>
|
>
|
||||||
<option value="all">All Types</option>
|
<option value="all">All Types</option>
|
||||||
<option value="search_indexers">Search Indexers</option>
|
<option value="search_indexers">Search Indexers</option>
|
||||||
@@ -215,8 +286,77 @@ export default function AdminLogsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Logs Table */}
|
{/* Mobile card list — hidden on sm+ */}
|
||||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
|
<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} · {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">
|
<div className="overflow-x-auto">
|
||||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
|
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
|
||||||
<thead className="bg-gray-50 dark:bg-gray-900">
|
<thead className="bg-gray-50 dark:bg-gray-900">
|
||||||
@@ -253,13 +393,11 @@ export default function AdminLogsPage() {
|
|||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap">
|
<td className="px-6 py-4 whitespace-nowrap">
|
||||||
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
<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>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap">
|
<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)}`}>
|
<StatusBadge status={log.status} />
|
||||||
{log.status.toUpperCase()}
|
|
||||||
</span>
|
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4">
|
<td className="px-6 py-4">
|
||||||
{log.request?.audiobook ? (
|
{log.request?.audiobook ? (
|
||||||
@@ -285,7 +423,7 @@ export default function AdminLogsPage() {
|
|||||||
{log.attempts}/{log.maxAttempts}
|
{log.attempts}/{log.maxAttempts}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
|
<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
|
<button
|
||||||
onClick={() => setExpandedLog(expandedLog === log.id ? null : log.id)}
|
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"
|
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 && (
|
{expandedLog === log.id && (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={7} className="px-6 py-4 bg-gray-50 dark:bg-gray-900">
|
<td colSpan={7} className="px-6 py-4 bg-gray-50 dark:bg-gray-900">
|
||||||
<div className="space-y-4">
|
<LogDetails log={log} />
|
||||||
{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>
|
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
)}
|
)}
|
||||||
@@ -373,24 +455,31 @@ export default function AdminLogsPage() {
|
|||||||
|
|
||||||
{/* Pagination */}
|
{/* Pagination */}
|
||||||
{pagination && pagination.totalPages > 1 && (
|
{pagination && pagination.totalPages > 1 && (
|
||||||
<div className="mt-6 flex items-center justify-between">
|
<div className="mt-6 flex flex-col sm:flex-row items-center gap-3 sm:justify-between">
|
||||||
<div className="text-sm text-gray-700 dark:text-gray-300">
|
<div className="text-sm text-gray-600 dark:text-gray-400 order-2 sm:order-1">
|
||||||
Page {pagination.page} of {pagination.totalPages} ({pagination.total} total logs)
|
Page {pagination.page} of {pagination.totalPages}
|
||||||
|
<span className="hidden sm:inline"> ({pagination.total} total logs)</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2 order-1 sm:order-2">
|
||||||
<button
|
<button
|
||||||
onClick={() => setPage(page - 1)}
|
onClick={() => setPage(page - 1)}
|
||||||
disabled={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
|
Previous
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() => setPage(page + 1)}
|
onClick={() => setPage(page + 1)}
|
||||||
disabled={page === pagination.totalPages}
|
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
|
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>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -403,11 +492,10 @@ export default function AdminLogsPage() {
|
|||||||
</h3>
|
</h3>
|
||||||
<ul className="text-sm text-blue-700 dark:text-blue-300 space-y-1">
|
<ul className="text-sm text-blue-700 dark:text-blue-300 space-y-1">
|
||||||
<li>• Logs are automatically refreshed every 10 seconds</li>
|
<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>• Tap "Show Details" to view event logs, job results, and errors</li>
|
||||||
<li>• Event logs show all internal operations with timestamps (similar to Docker logs)</li>
|
<li>• Event logs show all internal operations with timestamps</li>
|
||||||
<li>• Jobs are retried automatically based on their max attempts setting</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>• 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>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+366
-245
@@ -41,6 +41,144 @@ interface PendingUser {
|
|||||||
createdAt: string;
|
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() {
|
function AdminUsersPageContent() {
|
||||||
const { data, error, mutate } = useSWR('/api/admin/users', authenticatedFetcher);
|
const { data, error, mutate } = useSWR('/api/admin/users', authenticatedFetcher);
|
||||||
const { data: pendingData, error: pendingError, mutate: mutatePending } = useSWR(
|
const { data: pendingData, error: pendingError, mutate: mutatePending } = useSWR(
|
||||||
@@ -86,7 +224,6 @@ function AdminUsersPageContent() {
|
|||||||
if (globalAutoApproveData?.autoApproveRequests !== undefined) {
|
if (globalAutoApproveData?.autoApproveRequests !== undefined) {
|
||||||
setGlobalAutoApprove(globalAutoApproveData.autoApproveRequests);
|
setGlobalAutoApprove(globalAutoApproveData.autoApproveRequests);
|
||||||
} else if (globalAutoApproveData !== undefined && globalAutoApproveData.autoApproveRequests === undefined) {
|
} else if (globalAutoApproveData !== undefined && globalAutoApproveData.autoApproveRequests === undefined) {
|
||||||
// API returned but no value - default to true
|
|
||||||
setGlobalAutoApprove(true);
|
setGlobalAutoApprove(true);
|
||||||
}
|
}
|
||||||
}, [globalAutoApproveData]);
|
}, [globalAutoApproveData]);
|
||||||
@@ -101,9 +238,7 @@ function AdminUsersPageContent() {
|
|||||||
}, [globalInteractiveSearchData]);
|
}, [globalInteractiveSearchData]);
|
||||||
|
|
||||||
const handleGlobalAutoApproveToggle = async (newValue: boolean) => {
|
const handleGlobalAutoApproveToggle = async (newValue: boolean) => {
|
||||||
// Optimistic update
|
|
||||||
setGlobalAutoApprove(newValue);
|
setGlobalAutoApprove(newValue);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await fetchJSON('/api/admin/settings/auto-approve', {
|
await fetchJSON('/api/admin/settings/auto-approve', {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
@@ -111,20 +246,16 @@ function AdminUsersPageContent() {
|
|||||||
});
|
});
|
||||||
toast.success(`Global auto-approve ${newValue ? 'enabled' : 'disabled'}`);
|
toast.success(`Global auto-approve ${newValue ? 'enabled' : 'disabled'}`);
|
||||||
mutateGlobalAutoApprove();
|
mutateGlobalAutoApprove();
|
||||||
mutate(); // Refresh users list to show updated state
|
mutate();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Revert on error
|
|
||||||
setGlobalAutoApprove(!newValue);
|
setGlobalAutoApprove(!newValue);
|
||||||
const errorMsg = err instanceof Error ? err.message : 'Failed to update auto-approve setting';
|
const errorMsg = err instanceof Error ? err.message : 'Failed to update auto-approve setting';
|
||||||
toast.error(errorMsg);
|
toast.error(errorMsg);
|
||||||
console.error(err);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleGlobalInteractiveSearchToggle = async (newValue: boolean) => {
|
const handleGlobalInteractiveSearchToggle = async (newValue: boolean) => {
|
||||||
// Optimistic update
|
|
||||||
setGlobalInteractiveSearch(newValue);
|
setGlobalInteractiveSearch(newValue);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await fetchJSON('/api/admin/settings/interactive-search', {
|
await fetchJSON('/api/admin/settings/interactive-search', {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
@@ -132,74 +263,51 @@ function AdminUsersPageContent() {
|
|||||||
});
|
});
|
||||||
toast.success(`Global interactive search ${newValue ? 'enabled' : 'disabled'}`);
|
toast.success(`Global interactive search ${newValue ? 'enabled' : 'disabled'}`);
|
||||||
mutateGlobalInteractiveSearch();
|
mutateGlobalInteractiveSearch();
|
||||||
mutate(); // Refresh users list to show updated state
|
mutate();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Revert on error
|
|
||||||
setGlobalInteractiveSearch(!newValue);
|
setGlobalInteractiveSearch(!newValue);
|
||||||
const errorMsg = err instanceof Error ? err.message : 'Failed to update interactive search setting';
|
const errorMsg = err instanceof Error ? err.message : 'Failed to update interactive search setting';
|
||||||
toast.error(errorMsg);
|
toast.error(errorMsg);
|
||||||
console.error(err);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleUserAutoApproveToggle = async (user: User, newValue: boolean) => {
|
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 previousUsers = data?.users || [];
|
||||||
const optimisticUsers = previousUsers.map((u: User) =>
|
const optimisticUsers = previousUsers.map((u: User) =>
|
||||||
u.id === user.id ? { ...u, autoApproveRequests: newValue } : u
|
u.id === user.id ? { ...u, autoApproveRequests: newValue } : u
|
||||||
);
|
);
|
||||||
console.log('[AutoApprove] Applying optimistic update');
|
|
||||||
mutate({ users: optimisticUsers }, false);
|
mutate({ users: optimisticUsers }, false);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log('[AutoApprove] Sending API request...');
|
await fetchJSON(`/api/admin/users/${user.id}`, {
|
||||||
const response = await fetchJSON(`/api/admin/users/${user.id}`, {
|
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({ role: user.role, autoApproveRequests: newValue }),
|
||||||
role: user.role,
|
|
||||||
autoApproveRequests: newValue
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
console.log('[AutoApprove] API response received:', response);
|
|
||||||
toast.success(`Auto-approve ${newValue ? 'enabled' : 'disabled'} for ${user.plexUsername}`);
|
toast.success(`Auto-approve ${newValue ? 'enabled' : 'disabled'} for ${user.plexUsername}`);
|
||||||
console.log('[AutoApprove] Triggering cache revalidation...');
|
mutate();
|
||||||
mutate(); // Refresh users list
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Revert on error
|
|
||||||
console.error('[AutoApprove] Error occurred, reverting:', err);
|
|
||||||
mutate({ users: previousUsers }, false);
|
mutate({ users: previousUsers }, false);
|
||||||
const errorMsg = err instanceof Error ? err.message : 'Failed to update user auto-approve setting';
|
const errorMsg = err instanceof Error ? err.message : 'Failed to update user auto-approve setting';
|
||||||
toast.error(errorMsg);
|
toast.error(errorMsg);
|
||||||
console.error(err);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleUserInteractiveSearchToggle = async (user: User, newValue: boolean) => {
|
const handleUserInteractiveSearchToggle = async (user: User, newValue: boolean) => {
|
||||||
// Optimistic update
|
|
||||||
const previousUsers = data?.users || [];
|
const previousUsers = data?.users || [];
|
||||||
const optimisticUsers = previousUsers.map((u: User) =>
|
const optimisticUsers = previousUsers.map((u: User) =>
|
||||||
u.id === user.id ? { ...u, interactiveSearchAccess: newValue } : u
|
u.id === user.id ? { ...u, interactiveSearchAccess: newValue } : u
|
||||||
);
|
);
|
||||||
mutate({ users: optimisticUsers }, false);
|
mutate({ users: optimisticUsers }, false);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await fetchJSON(`/api/admin/users/${user.id}`, {
|
await fetchJSON(`/api/admin/users/${user.id}`, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({ role: user.role, interactiveSearchAccess: newValue }),
|
||||||
role: user.role,
|
|
||||||
interactiveSearchAccess: newValue
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
toast.success(`Interactive search ${newValue ? 'enabled' : 'disabled'} for ${user.plexUsername}`);
|
toast.success(`Interactive search ${newValue ? 'enabled' : 'disabled'} for ${user.plexUsername}`);
|
||||||
mutate(); // Refresh users list
|
mutate();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Revert on error
|
|
||||||
mutate({ users: previousUsers }, false);
|
mutate({ users: previousUsers }, false);
|
||||||
const errorMsg = err instanceof Error ? err.message : 'Failed to update user interactive search setting';
|
const errorMsg = err instanceof Error ? err.message : 'Failed to update user interactive search setting';
|
||||||
toast.error(errorMsg);
|
toast.error(errorMsg);
|
||||||
console.error(err);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -214,7 +322,6 @@ function AdminUsersPageContent() {
|
|||||||
|
|
||||||
const saveUserRole = async () => {
|
const saveUserRole = async () => {
|
||||||
if (!editDialog.user) return;
|
if (!editDialog.user) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
setSaving(true);
|
setSaving(true);
|
||||||
await fetchJSON(`/api/admin/users/${editDialog.user.id}`, {
|
await fetchJSON(`/api/admin/users/${editDialog.user.id}`, {
|
||||||
@@ -223,11 +330,10 @@ function AdminUsersPageContent() {
|
|||||||
});
|
});
|
||||||
toast.success(`User "${editDialog.user.plexUsername}" updated successfully`);
|
toast.success(`User "${editDialog.user.plexUsername}" updated successfully`);
|
||||||
hideEditDialog();
|
hideEditDialog();
|
||||||
mutate(); // Refresh users list
|
mutate();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errorMsg = err instanceof Error ? err.message : 'Failed to update user';
|
const errorMsg = err instanceof Error ? err.message : 'Failed to update user';
|
||||||
toast.error(errorMsg);
|
toast.error(errorMsg);
|
||||||
console.error(err);
|
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false);
|
setSaving(false);
|
||||||
}
|
}
|
||||||
@@ -242,13 +348,12 @@ function AdminUsersPageContent() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const closeConfirmDialog = () => {
|
const closeConfirmDialog = () => {
|
||||||
if (processingUserId) return; // Don't close while processing
|
if (processingUserId) return;
|
||||||
setConfirmDialog({ isOpen: false, type: null, user: null });
|
setConfirmDialog({ isOpen: false, type: null, user: null });
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleConfirmAction = async () => {
|
const handleConfirmAction = async () => {
|
||||||
if (!confirmDialog.user) return;
|
if (!confirmDialog.user) return;
|
||||||
|
|
||||||
const isApprove = confirmDialog.type === 'approve';
|
const isApprove = confirmDialog.type === 'approve';
|
||||||
try {
|
try {
|
||||||
setProcessingUserId(confirmDialog.user.id);
|
setProcessingUserId(confirmDialog.user.id);
|
||||||
@@ -261,13 +366,12 @@ function AdminUsersPageContent() {
|
|||||||
? `User "${confirmDialog.user.plexUsername}" has been approved`
|
? `User "${confirmDialog.user.plexUsername}" has been approved`
|
||||||
: `User "${confirmDialog.user.plexUsername}" has been rejected`
|
: `User "${confirmDialog.user.plexUsername}" has been rejected`
|
||||||
);
|
);
|
||||||
mutatePending(); // Refresh pending users list
|
mutatePending();
|
||||||
if (isApprove) mutate(); // Refresh approved users list
|
if (isApprove) mutate();
|
||||||
closeConfirmDialog();
|
closeConfirmDialog();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errorMsg = err instanceof Error ? err.message : `Failed to ${isApprove ? 'approve' : 'reject'} user`;
|
const errorMsg = err instanceof Error ? err.message : `Failed to ${isApprove ? 'approve' : 'reject'} user`;
|
||||||
toast.error(errorMsg);
|
toast.error(errorMsg);
|
||||||
console.error(err);
|
|
||||||
} finally {
|
} finally {
|
||||||
setProcessingUserId(null);
|
setProcessingUserId(null);
|
||||||
}
|
}
|
||||||
@@ -278,25 +382,23 @@ function AdminUsersPageContent() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const closeDeleteDialog = () => {
|
const closeDeleteDialog = () => {
|
||||||
if (deleting) return; // Don't close while processing
|
if (deleting) return;
|
||||||
setDeleteDialog({ isOpen: false, user: null });
|
setDeleteDialog({ isOpen: false, user: null });
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteUser = async () => {
|
const handleDeleteUser = async () => {
|
||||||
if (!deleteDialog.user) return;
|
if (!deleteDialog.user) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
setDeleting(true);
|
setDeleting(true);
|
||||||
const response = await fetchJSON(`/api/admin/users/${deleteDialog.user.id}`, {
|
const response = await fetchJSON(`/api/admin/users/${deleteDialog.user.id}`, {
|
||||||
method: 'DELETE',
|
method: 'DELETE',
|
||||||
});
|
});
|
||||||
toast.success(response.message || `User "${deleteDialog.user.plexUsername}" has been deleted`);
|
toast.success(response.message || `User "${deleteDialog.user.plexUsername}" has been deleted`);
|
||||||
mutate(); // Refresh users list
|
mutate();
|
||||||
closeDeleteDialog();
|
closeDeleteDialog();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errorMsg = err instanceof Error ? err.message : 'Failed to delete user';
|
const errorMsg = err instanceof Error ? err.message : 'Failed to delete user';
|
||||||
toast.error(errorMsg);
|
toast.error(errorMsg);
|
||||||
console.error(err);
|
|
||||||
} finally {
|
} finally {
|
||||||
setDeleting(false);
|
setDeleting(false);
|
||||||
}
|
}
|
||||||
@@ -307,7 +409,6 @@ function AdminUsersPageContent() {
|
|||||||
await navigator.clipboard.writeText(text);
|
await navigator.clipboard.writeText(text);
|
||||||
toast.success(`${label} copied to clipboard`);
|
toast.success(`${label} copied to clipboard`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to copy to clipboard:', err);
|
|
||||||
toast.error('Failed to copy to clipboard');
|
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="min-h-screen bg-gray-50 dark:bg-gray-900 p-8">
|
||||||
<div className="max-w-7xl mx-auto">
|
<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">
|
<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">
|
<h3 className="text-sm font-medium text-red-800 dark:text-red-200">Error Loading Users</h3>
|
||||||
Error Loading Users
|
|
||||||
</h3>
|
|
||||||
<p className="text-sm text-red-700 dark:text-red-300 mt-1">
|
<p className="text-sm text-red-700 dark:text-red-300 mt-1">
|
||||||
{error?.message || 'Failed to load users'}
|
{error?.message || 'Failed to load users'}
|
||||||
</p>
|
</p>
|
||||||
@@ -344,80 +443,81 @@ function AdminUsersPageContent() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
|
<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">
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm: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">
|
{/* Header — stacks on mobile, row on sm+ */}
|
||||||
<div>
|
<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">
|
||||||
<h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">
|
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||||
User Management
|
<div>
|
||||||
</h1>
|
<h1 className="text-2xl sm:text-3xl font-bold text-gray-900 dark:text-gray-100">
|
||||||
<p className="text-gray-600 dark:text-gray-400 mt-2">
|
User Management
|
||||||
Manage user roles and permissions
|
</h1>
|
||||||
</p>
|
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||||
</div>
|
Manage user roles and permissions
|
||||||
<div className="flex items-center gap-3">
|
</p>
|
||||||
<button
|
</div>
|
||||||
onClick={() => setGlobalSettingsOpen(true)}
|
<div className="flex items-center gap-2 self-start sm:self-auto flex-shrink-0">
|
||||||
className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
|
<button
|
||||||
>
|
onClick={() => setGlobalSettingsOpen(true)}
|
||||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
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"
|
||||||
<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 className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
</svg>
|
<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" />
|
||||||
<span>Global User Permissions</span>
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||||
</button>
|
</svg>
|
||||||
<Link
|
<span className="hidden sm:inline">Global User Permissions</span>
|
||||||
href="/admin"
|
<span className="sm:hidden">Permissions</span>
|
||||||
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"
|
</button>
|
||||||
>
|
<Link
|
||||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
href="/admin"
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
|
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>
|
>
|
||||||
<span>Back to Dashboard</span>
|
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
</Link>
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
|
||||||
|
</svg>
|
||||||
|
<span>Back</span>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Pending Users Section */}
|
{/* Pending Users Section */}
|
||||||
{pendingUsers.length > 0 && (
|
{pendingUsers.length > 0 && (
|
||||||
<div className="mb-8">
|
<div className="mb-6 sm: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">
|
<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-lg font-semibold text-yellow-900 dark:text-yellow-200 mb-4 flex items-center gap-2">
|
<h2 className="text-base font-semibold text-amber-900 dark:text-amber-200 mb-1 flex items-center gap-2">
|
||||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
<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" />
|
<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>
|
</svg>
|
||||||
Pending Registrations ({pendingUsers.length})
|
Pending Registrations ({pendingUsers.length})
|
||||||
</h2>
|
</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.
|
The following users are awaiting approval to access the system.
|
||||||
</p>
|
</p>
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{pendingUsers.map((user) => (
|
{pendingUsers.map((user) => (
|
||||||
<div
|
<div
|
||||||
key={user.id}
|
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">
|
{/* Pending card — info */}
|
||||||
<div className="flex items-center gap-3">
|
<div className="px-4 py-3">
|
||||||
<div>
|
<div className="font-medium text-gray-900 dark:text-gray-100 text-sm">
|
||||||
<div className="font-medium text-gray-900 dark:text-gray-100">
|
{user.plexUsername}
|
||||||
{user.plexUsername}
|
</div>
|
||||||
</div>
|
<div className="text-sm text-gray-500 dark:text-gray-400">
|
||||||
<div className="text-sm text-gray-500 dark:text-gray-400">
|
{user.plexEmail || 'No email'}
|
||||||
{user.plexEmail || 'No email'}
|
</div>
|
||||||
</div>
|
<div className="text-xs text-gray-400 dark:text-gray-500 mt-1">
|
||||||
<div className="text-xs text-gray-400 dark:text-gray-500 mt-1">
|
Registered: {new Date(user.createdAt).toLocaleString()} · Provider: {user.authProvider}
|
||||||
Registered: {new Date(user.createdAt).toLocaleString()} •
|
|
||||||
Provider: {user.authProvider}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</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
|
<button
|
||||||
onClick={() => showApproveDialog(user)}
|
onClick={() => showApproveDialog(user)}
|
||||||
disabled={processingUserId === user.id}
|
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">
|
<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" />
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||||
@@ -427,7 +527,7 @@ function AdminUsersPageContent() {
|
|||||||
<button
|
<button
|
||||||
onClick={() => showRejectDialog(user)}
|
onClick={() => showRejectDialog(user)}
|
||||||
disabled={processingUserId === user.id}
|
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">
|
<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" />
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||||
@@ -442,8 +542,104 @@ function AdminUsersPageContent() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Users Table */}
|
{/* Users — Mobile card list (sm:hidden) */}
|
||||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-x-auto">
|
<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">
|
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
|
||||||
<thead className="bg-gray-50 dark:bg-gray-900">
|
<thead className="bg-gray-50 dark:bg-gray-900">
|
||||||
<tr>
|
<tr>
|
||||||
@@ -472,15 +668,21 @@ function AdminUsersPageContent() {
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
|
<tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
|
||||||
{users.map((user) => (
|
{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">
|
<td className="px-6 py-4 whitespace-nowrap">
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
{user.avatarUrl && (
|
{user.avatarUrl ? (
|
||||||
<img
|
<img
|
||||||
src={user.avatarUrl}
|
src={user.avatarUrl}
|
||||||
alt={user.plexUsername}
|
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>
|
||||||
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||||
@@ -507,52 +709,14 @@ function AdminUsersPageContent() {
|
|||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap">
|
<td className="px-6 py-4 whitespace-nowrap">
|
||||||
<div className="flex items-center gap-2">
|
<RoleBadge role={user.role} isSetupAdmin={user.isSetupAdmin} />
|
||||||
<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>
|
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap">
|
<td className="px-6 py-4 whitespace-nowrap">
|
||||||
<button
|
<PermissionBadge
|
||||||
|
user={user}
|
||||||
|
globalAutoApprove={globalAutoApprove}
|
||||||
onClick={() => setPermissionsUserId(user.id)}
|
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>
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
|
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
|
||||||
{user._count.requests}
|
{user._count.requests}
|
||||||
@@ -563,65 +727,7 @@ function AdminUsersPageContent() {
|
|||||||
: 'Never'}
|
: 'Never'}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
|
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
|
||||||
<div className="flex items-center justify-end gap-3">
|
<UserActionsCell user={user} onEdit={showEditDialog} onDelete={showDeleteDialog} />
|
||||||
{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>
|
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
@@ -643,31 +749,50 @@ function AdminUsersPageContent() {
|
|||||||
<ul className="text-sm text-blue-700 dark:text-blue-300 space-y-1">
|
<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>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>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>Setup Admin:</strong> The initial admin account — protected, cannot be changed or deleted</li>
|
||||||
<li>• <strong>Permissions:</strong> Click a user'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>Permissions:</strong> Click a user'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 - use admin role mapping in OIDC settings. Cannot be deleted as access is managed externally.</li>
|
<li>• <strong>OIDC Users:</strong> Role management is handled by the identity provider. Cannot be deleted.</li>
|
||||||
<li>• <strong>Plex Users:</strong> Can have their roles changed, but cannot be deleted as access is managed by Plex.</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 be freely assigned user or admin roles (except setup admin). Can be deleted (their requests are preserved for historical records).</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>
|
<li>• You cannot change your own role or delete yourself for security reasons</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Edit User Dialog */}
|
{/* Edit User Dialog — bottom sheet on mobile */}
|
||||||
{editDialog.isOpen && editDialog.user && (
|
{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="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-lg shadow-xl max-w-md w-full p-6">
|
<div className="bg-white dark:bg-gray-800 rounded-t-2xl sm:rounded-2xl shadow-xl w-full sm:max-w-md">
|
||||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">
|
{/* Dialog header */}
|
||||||
Edit User Role
|
<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>
|
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||||
<div className="space-y-4 mb-6">
|
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 */}
|
{/* User Info */}
|
||||||
<div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
|
<div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-xl">
|
||||||
{editDialog.user.avatarUrl && (
|
{editDialog.user.avatarUrl ? (
|
||||||
<img
|
<img
|
||||||
src={editDialog.user.avatarUrl}
|
src={editDialog.user.avatarUrl}
|
||||||
alt={editDialog.user.plexUsername}
|
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>
|
||||||
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||||
@@ -685,38 +810,34 @@ function AdminUsersPageContent() {
|
|||||||
Role
|
Role
|
||||||
</label>
|
</label>
|
||||||
<div className="space-y-2">
|
<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
|
<input
|
||||||
type="radio"
|
type="radio"
|
||||||
name="role"
|
name="role"
|
||||||
value="user"
|
value="user"
|
||||||
checked={editRole === 'user'}
|
checked={editRole === 'user'}
|
||||||
onChange={(e) => setEditRole(e.target.value as 'user' | '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="flex-1">
|
||||||
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">User</div>
|
||||||
User
|
<div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
|
||||||
</div>
|
|
||||||
<div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
|
||||||
Can request audiobooks and view own requests
|
Can request audiobooks and view own requests
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</label>
|
</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
|
<input
|
||||||
type="radio"
|
type="radio"
|
||||||
name="role"
|
name="role"
|
||||||
value="admin"
|
value="admin"
|
||||||
checked={editRole === 'admin'}
|
checked={editRole === 'admin'}
|
||||||
onChange={(e) => setEditRole(e.target.value as 'user' | '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="flex-1">
|
||||||
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">Admin</div>
|
||||||
Admin
|
<div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
|
||||||
</div>
|
|
||||||
<div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
|
||||||
Full system access including settings and user management
|
Full system access including settings and user management
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -725,19 +846,19 @@ function AdminUsersPageContent() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Actions */}
|
{/* Dialog footer */}
|
||||||
<div className="flex justify-end gap-3">
|
<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
|
<button
|
||||||
onClick={hideEditDialog}
|
onClick={hideEditDialog}
|
||||||
disabled={saving}
|
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
|
Cancel
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={saveUserRole}
|
onClick={saveUserRole}
|
||||||
disabled={saving}
|
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'}
|
{saving ? 'Saving...' : 'Save Changes'}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -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',
|
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',
|
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',
|
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;
|
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">
|
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-3">
|
||||||
Add Download Client
|
Add Download Client
|
||||||
</h3>
|
</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 */}
|
{/* 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={`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 className="flex items-start justify-between mb-3">
|
||||||
@@ -316,15 +316,15 @@ export function DownloadClientManagement({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</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={`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 className="flex items-start justify-between mb-3">
|
||||||
<div>
|
<div>
|
||||||
<h4 className="text-base font-semibold text-gray-900 dark:text-gray-100 mb-1">
|
<h4 className="text-base font-semibold text-gray-900 dark:text-gray-100 mb-1">
|
||||||
RDT-Client
|
Deluge
|
||||||
</h4>
|
</h4>
|
||||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||||
Torrent / Debrid
|
Torrent downloads
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</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">
|
<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>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<Button
|
<Button
|
||||||
onClick={() => handleAddClient('rdtclient')}
|
onClick={() => handleAddClient('deluge')}
|
||||||
variant="primary"
|
variant="primary"
|
||||||
size="sm"
|
size="sm"
|
||||||
disabled={loading}
|
disabled={loading}
|
||||||
>
|
>
|
||||||
Add RDT-Client
|
Add Deluge
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -278,7 +278,7 @@ export function DownloadClientModal({
|
|||||||
type,
|
type,
|
||||||
name,
|
name,
|
||||||
url,
|
url,
|
||||||
username: type !== 'sabnzbd' ? username : undefined,
|
username: type !== 'sabnzbd' && type !== 'deluge' ? username : undefined,
|
||||||
password: password === '********' ? undefined : password, // Don't send masked password on edit
|
password: password === '********' ? undefined : password, // Don't send masked password on edit
|
||||||
enabled,
|
enabled,
|
||||||
disableSSLVerify,
|
disableSSLVerify,
|
||||||
@@ -338,7 +338,7 @@ export function DownloadClientModal({
|
|||||||
<Input
|
<Input
|
||||||
value={url}
|
value={url}
|
||||||
onChange={(e) => setUrl(e.target.value)}
|
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}
|
error={errors.url}
|
||||||
/>
|
/>
|
||||||
<p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
<p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||||
@@ -346,8 +346,8 @@ export function DownloadClientModal({
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Username (qBittorrent and Transmission) */}
|
{/* Username (qBittorrent, Transmission, NZBGet — not SABnzbd or Deluge) */}
|
||||||
{type !== 'sabnzbd' && (
|
{type !== 'sabnzbd' && type !== 'deluge' && (
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||||
Username
|
Username
|
||||||
@@ -383,6 +383,11 @@ export function DownloadClientModal({
|
|||||||
Configured in NZBGet under Settings → Security → ControlPassword
|
Configured in NZBGet under Settings → Security → ControlPassword
|
||||||
</p>
|
</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>
|
</div>
|
||||||
|
|
||||||
{/* SSL Verification */}
|
{/* 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">
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||||
Post-Import Category
|
Post-Import Category
|
||||||
</label>
|
</label>
|
||||||
{type === 'qbittorrent' && availableCategories.length > 0 ? (
|
{(type === 'qbittorrent' || type === 'deluge') && availableCategories.length > 0 ? (
|
||||||
<select
|
<select
|
||||||
value={postImportCategory}
|
value={postImportCategory}
|
||||||
onChange={(e) => setPostImportCategory(e.target.value)}
|
onChange={(e) => setPostImportCategory(e.target.value)}
|
||||||
|
|||||||
@@ -414,10 +414,12 @@ function parseSeriesBooks(
|
|||||||
if (!bookAsin || seenAsins.has(bookAsin)) return;
|
if (!bookAsin || seenAsins.has(bookAsin)) return;
|
||||||
seenAsins.add(bookAsin);
|
seenAsins.add(bookAsin);
|
||||||
|
|
||||||
// Title
|
// Title: h3 a / .bc-heading a hold the real book title;
|
||||||
const title = $el.find('h2').first().text().trim() ||
|
// h2 on series pages is the position label ("Book 1"), so try it last.
|
||||||
$el.find('h3 a').first().text().trim() ||
|
const title = $el.find('h3 a').first().text().trim() ||
|
||||||
$el.find('.bc-heading 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;
|
if (!title) return;
|
||||||
|
|||||||
@@ -0,0 +1,385 @@
|
|||||||
|
/**
|
||||||
|
* Component: Deluge Integration Service
|
||||||
|
* Documentation: documentation/phase3/download-clients.md
|
||||||
|
*/
|
||||||
|
|
||||||
|
import axios, { AxiosInstance } from 'axios';
|
||||||
|
import https from 'https';
|
||||||
|
import path from 'path';
|
||||||
|
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: 30000, 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: 30000,
|
||||||
|
});
|
||||||
|
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: 30000, 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');
|
||||||
|
}
|
||||||
@@ -586,7 +586,19 @@ export class QBittorrentService implements IDownloadClient {
|
|||||||
throw new Error(`Torrent ${hash} not found`);
|
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) {
|
} catch (error) {
|
||||||
// Don't log error here - caller handles it (e.g., duplicate checking)
|
// Don't log error here - caller handles it (e.g., duplicate checking)
|
||||||
throw error;
|
throw error;
|
||||||
@@ -1103,7 +1115,7 @@ export class QBittorrentService implements IDownloadClient {
|
|||||||
stalledDL: 'downloading',
|
stalledDL: 'downloading',
|
||||||
stalledUP: 'seeding',
|
stalledUP: 'seeding',
|
||||||
pausedDL: 'paused',
|
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',
|
pausedUP: 'seeding',
|
||||||
queuedDL: 'queued',
|
queuedDL: 'queued',
|
||||||
queuedUP: 'seeding',
|
queuedUP: 'seeding',
|
||||||
@@ -1158,7 +1170,7 @@ export class QBittorrentService implements IDownloadClient {
|
|||||||
stalledDL: 'downloading',
|
stalledDL: 'downloading',
|
||||||
stalledUP: 'completed',
|
stalledUP: 'completed',
|
||||||
pausedDL: 'paused',
|
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',
|
pausedUP: 'completed',
|
||||||
queuedDL: 'queued',
|
queuedDL: 'queued',
|
||||||
queuedUP: 'completed',
|
queuedUP: 'completed',
|
||||||
|
|||||||
@@ -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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -11,7 +11,7 @@
|
|||||||
// =========================================================================
|
// =========================================================================
|
||||||
|
|
||||||
/** Supported download client types — single source of truth */
|
/** 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 */
|
/** Identifies the specific download client software */
|
||||||
export type DownloadClientType = (typeof SUPPORTED_CLIENT_TYPES)[number];
|
export type DownloadClientType = (typeof SUPPORTED_CLIENT_TYPES)[number];
|
||||||
@@ -22,7 +22,7 @@ export const CLIENT_DISPLAY_NAMES: Record<DownloadClientType, string> = {
|
|||||||
sabnzbd: 'SABnzbd',
|
sabnzbd: 'SABnzbd',
|
||||||
nzbget: 'NZBGet',
|
nzbget: 'NZBGet',
|
||||||
transmission: 'Transmission',
|
transmission: 'Transmission',
|
||||||
rdtclient: 'RDT-Client',
|
deluge: 'Deluge',
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Get display name for a client type, falling back to the raw type */
|
/** 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',
|
sabnzbd: 'usenet',
|
||||||
nzbget: 'usenet',
|
nzbget: 'usenet',
|
||||||
transmission: 'torrent',
|
transmission: 'torrent',
|
||||||
rdtclient: 'torrent',
|
deluge: 'torrent',
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Unified download status across all clients */
|
/** Unified download status across all clients */
|
||||||
|
|||||||
@@ -865,12 +865,9 @@ async function cleanupDownloadAfterOrganize(
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Check if this is a non-torrent indexer with cleanup enabled.
|
// 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';
|
const isTorrentProtocol = indexer?.protocol?.toLowerCase() === 'torrent';
|
||||||
|
|
||||||
if (!indexer || (!isRDTClient && isTorrentProtocol) || !indexer.removeAfterProcessing) {
|
if (!indexer || isTorrentProtocol || !indexer.removeAfterProcessing) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
* Component: Download Client Manager Service
|
* Component: Download Client Manager Service
|
||||||
* Documentation: documentation/phase3/download-clients.md
|
* 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.
|
* 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 { SABnzbdService } from '@/lib/integrations/sabnzbd.service';
|
||||||
import { NZBGetService } from '@/lib/integrations/nzbget.service';
|
import { NZBGetService } from '@/lib/integrations/nzbget.service';
|
||||||
import { TransmissionService } from '@/lib/integrations/transmission.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 { PathMappingConfig } from '@/lib/utils/path-mapper';
|
||||||
import { IDownloadClient, DownloadClientType, ProtocolType, CLIENT_PROTOCOL_MAP, getClientDisplayName } from '@/lib/interfaces/download-client.interface';
|
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);
|
return this.createNZBGetService(config, downloadDir);
|
||||||
case 'transmission':
|
case 'transmission':
|
||||||
return this.createTransmissionService(config, downloadDir);
|
return this.createTransmissionService(config, downloadDir);
|
||||||
case 'rdtclient':
|
case 'deluge':
|
||||||
return this.createRDTClientService(config, downloadDir);
|
return this.createDelugeService(config, downloadDir);
|
||||||
default:
|
default:
|
||||||
throw new Error(`Unsupported download client type: ${config.type}`);
|
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
|
const pathMapping: PathMappingConfig | undefined = config.remotePathMappingEnabled && config.remotePath && config.localPath
|
||||||
? {
|
? {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
@@ -350,7 +350,7 @@ export class DownloadClientManager {
|
|||||||
}
|
}
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
return new RDTClientService(
|
return new DelugeService(
|
||||||
config.url,
|
config.url,
|
||||||
config.username || '',
|
config.username || '',
|
||||||
config.password || '',
|
config.password || '',
|
||||||
|
|||||||
@@ -152,8 +152,8 @@ describe('Admin settings core routes', () => {
|
|||||||
it('rejects invalid download client types', async () => {
|
it('rejects invalid download client types', async () => {
|
||||||
const request = {
|
const request = {
|
||||||
json: vi.fn().mockResolvedValue({
|
json: vi.fn().mockResolvedValue({
|
||||||
type: 'deluge',
|
type: 'rtorrent',
|
||||||
url: 'http://deluge',
|
url: 'http://rtorrent',
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -182,7 +182,7 @@ describe('Setup test routes', () => {
|
|||||||
it('rejects invalid download client type', async () => {
|
it('rejects invalid download client type', async () => {
|
||||||
const { POST } = await import('@/app/api/setup/test-download-client/route');
|
const { POST } = await import('@/app/api/setup/test-download-client/route');
|
||||||
const response = await POST({
|
const response = await POST({
|
||||||
json: vi.fn().mockResolvedValue({ type: 'deluge', url: 'http://deluge' }),
|
json: vi.fn().mockResolvedValue({ type: 'rtorrent', url: 'http://rtorrent' }),
|
||||||
} as any);
|
} as any);
|
||||||
const payload = await response.json();
|
const payload = await response.json();
|
||||||
|
|
||||||
|
|||||||
@@ -55,9 +55,9 @@ describe('AdminJobsPage', () => {
|
|||||||
|
|
||||||
render(<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' }));
|
fireEvent.click(screen.getByRole('button', { name: 'Trigger Job' }));
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
@@ -88,7 +88,7 @@ describe('AdminJobsPage', () => {
|
|||||||
|
|
||||||
render(<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('radio', { name: /Every 2 hours/i }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
|
fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
|
||||||
|
|
||||||
|
|||||||
@@ -68,14 +68,14 @@ describe('AdminLogsPage', () => {
|
|||||||
render(<AdminLogsPage />);
|
render(<AdminLogsPage />);
|
||||||
|
|
||||||
expect(await screen.findByText('System Logs')).toBeInTheDocument();
|
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' }));
|
fireEvent.click(screen.getAllByRole('button', { name: 'Show Details' })[0]);
|
||||||
expect(screen.getByText('Event Log')).toBeInTheDocument();
|
expect(screen.getAllByText('Event Log')[0]).toBeInTheDocument();
|
||||||
expect(screen.getByText('Job Result')).toBeInTheDocument();
|
expect(screen.getAllByText('Job Result')[0]).toBeInTheDocument();
|
||||||
expect(screen.getByText('Error')).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();
|
expect(screen.queryByText('Event Log')).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -122,6 +122,6 @@ describe('AdminLogsPage', () => {
|
|||||||
|
|
||||||
render(<AdminLogsPage />);
|
render(<AdminLogsPage />);
|
||||||
|
|
||||||
expect(await screen.findByText('No logs found')).toBeInTheDocument();
|
expect((await screen.findAllByText('No logs found'))[0]).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -158,9 +158,9 @@ describe('AdminUsersPage', () => {
|
|||||||
|
|
||||||
render(<AdminUsersPage />);
|
render(<AdminUsersPage />);
|
||||||
|
|
||||||
expect(await screen.findByText('Full Access')).toBeDefined();
|
expect((await screen.findAllByText('Full Access'))[0]).toBeDefined();
|
||||||
expect(screen.getByText('Manual')).toBeDefined();
|
expect(screen.getAllByText('Manual')[0]).toBeDefined();
|
||||||
expect(screen.getByText('Auto-Approve')).toBeDefined();
|
expect(screen.getAllByText('Auto-Approve')[0]).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows Global Default badge when global auto-approve is on', async () => {
|
it('shows Global Default badge when global auto-approve is on', async () => {
|
||||||
@@ -171,7 +171,7 @@ describe('AdminUsersPage', () => {
|
|||||||
|
|
||||||
render(<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 () => {
|
it('opens user permissions modal and shows admin lock state for both permissions', async () => {
|
||||||
@@ -184,7 +184,7 @@ describe('AdminUsersPage', () => {
|
|||||||
render(<AdminUsersPage />);
|
render(<AdminUsersPage />);
|
||||||
|
|
||||||
// Click the permissions badge to open modal
|
// 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
|
// Modal should show user info and the locked state for both permissions
|
||||||
expect(await screen.findByText('User Permissions')).toBeDefined();
|
expect(await screen.findByText('User Permissions')).toBeDefined();
|
||||||
@@ -205,7 +205,7 @@ describe('AdminUsersPage', () => {
|
|||||||
render(<AdminUsersPage />);
|
render(<AdminUsersPage />);
|
||||||
|
|
||||||
// Click the Manual badge to open permissions modal
|
// 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
|
// Find and click the auto-approve toggle switch inside the modal
|
||||||
const toggle = await screen.findByRole('switch', { name: 'Auto-Approve Requests' });
|
const toggle = await screen.findByRole('switch', { name: 'Auto-Approve Requests' });
|
||||||
@@ -231,7 +231,7 @@ describe('AdminUsersPage', () => {
|
|||||||
render(<AdminUsersPage />);
|
render(<AdminUsersPage />);
|
||||||
|
|
||||||
// Click the Manual badge to open permissions modal
|
// 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
|
// Find and click the interactive search toggle switch inside the modal
|
||||||
const toggle = await screen.findByRole('switch', { name: 'Interactive Search Access' });
|
const toggle = await screen.findByRole('switch', { name: 'Interactive Search Access' });
|
||||||
@@ -255,7 +255,7 @@ describe('AdminUsersPage', () => {
|
|||||||
render(<AdminUsersPage />);
|
render(<AdminUsersPage />);
|
||||||
|
|
||||||
// Click the Global Default badge
|
// 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
|
// Modal should show the global override message for both
|
||||||
expect(await screen.findByText('Controlled by global auto-approve setting')).toBeDefined();
|
expect(await screen.findByText('Controlled by global auto-approve setting')).toBeDefined();
|
||||||
@@ -288,7 +288,7 @@ describe('AdminUsersPage', () => {
|
|||||||
|
|
||||||
render(<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('radio', { name: /Admin/i }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
|
fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
|
||||||
|
|
||||||
|
|||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -180,7 +180,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)', () => {
|
it('maps pausedUP to completed (download finished, paused on upload side)', () => {
|
||||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||||
const progress = service.getDownloadProgress({
|
const progress = service.getDownloadProgress({
|
||||||
@@ -254,7 +254,7 @@ describe('QBittorrentService', () => {
|
|||||||
expect(info!.status).toBe('seeding');
|
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');
|
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||||
(service as any).cookie = 'SID=pausedup';
|
(service as any).cookie = 'SID=pausedup';
|
||||||
clientMock.get.mockResolvedValueOnce({
|
clientMock.get.mockResolvedValueOnce({
|
||||||
@@ -770,6 +770,37 @@ describe('QBittorrentService', () => {
|
|||||||
await expect(service.getTorrent('hash-404')).rejects.toThrow('Torrent hash-404 not found');
|
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 () => {
|
it('returns error when getTorrents fails', async () => {
|
||||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||||
(service as any).cookie = 'SID=list';
|
(service as any).cookie = 'SID=list';
|
||||||
|
|||||||
@@ -343,9 +343,9 @@ describe('processMonitorDownload', () => {
|
|||||||
requestId: 'req-6',
|
requestId: 'req-6',
|
||||||
downloadHistoryId: 'dh-6',
|
downloadHistoryId: 'dh-6',
|
||||||
downloadClientId: 'id-6',
|
downloadClientId: 'id-6',
|
||||||
downloadClient: 'deluge',
|
downloadClient: 'rtorrent',
|
||||||
jobId: 'job-6',
|
jobId: 'job-6',
|
||||||
})).rejects.toThrow(/Unknown download client type: deluge/);
|
})).rejects.toThrow(/Unknown download client type: rtorrent/);
|
||||||
|
|
||||||
expect(prismaMock.request.update).toHaveBeenCalledWith(
|
expect(prismaMock.request.update).toHaveBeenCalledWith(
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
|
|||||||
Reference in New Issue
Block a user