mirror of
https://github.com/kikootwo/ReadMeABook.git
synced 2026-06-03 12:50:09 +00:00
Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d38f03b8f4 | |||
| dbea15a34f | |||
| 2972297903 | |||
| 03f82d4841 | |||
| 33c2265e56 | |||
| b15a472bab | |||
| 3c680f2f38 | |||
| 16cd606421 | |||
| 40d5363dc4 | |||
| c138d8e642 | |||
| 3d590b38cc | |||
| aa7ba8a76d | |||
| 328fd8392b | |||
| 9a460f808d | |||
| c60b6214ce | |||
| aff5faaa58 | |||
| c43ce7ba8f | |||
| f570b87343 | |||
| dfa7a11674 |
@@ -33,6 +33,7 @@ Configurable Audible region for accurate metadata matching across different inte
|
||||
- India (`in`) - `audible.in` (English)
|
||||
- Germany (`de`) - `audible.de` (non-English)
|
||||
- Spain (`es`) - `audible.es` (non-English)
|
||||
- French (`fr`) - `audible.fr` (non-English)
|
||||
|
||||
**`isEnglish` Flag:**
|
||||
- Each region has `isEnglish: boolean` in `AudibleRegionConfig`
|
||||
|
||||
@@ -271,7 +271,7 @@ src/app/admin/settings/
|
||||
|
||||
**PUT /api/admin/settings/audible**
|
||||
- Updates Audible region
|
||||
- Body: `{ region: string }` (one of: us, ca, uk, au, in, es)
|
||||
- Body: `{ region: string }` (one of: us, ca, uk, au, in, es, fr)
|
||||
- No validation required
|
||||
|
||||
**PUT /api/admin/settings/prowlarr/indexers**
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "readmeabook",
|
||||
"version": "1.0.10",
|
||||
"version": "1.0.13",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
+157
-70
@@ -13,17 +13,34 @@ import { ActiveDownloadsTable } from './components/ActiveDownloadsTable';
|
||||
import { RecentRequestsTable } from './components/RecentRequestsTable';
|
||||
import { ToastProvider, useToast } from '@/components/ui/Toast';
|
||||
import { ReportedIssuesSection } from './components/ReportedIssuesSection';
|
||||
import { InteractiveTorrentSearchModal } from '@/components/requests/InteractiveTorrentSearchModal';
|
||||
import { TorrentResult } from '@/lib/utils/ranking-algorithm';
|
||||
import { formatDistanceToNow } from 'date-fns';
|
||||
import { useState } from 'react';
|
||||
|
||||
interface SelectedTorrentData {
|
||||
title?: string;
|
||||
indexer?: string;
|
||||
size?: number;
|
||||
format?: string;
|
||||
ebookFormat?: string;
|
||||
seeders?: number;
|
||||
infoUrl?: string;
|
||||
source?: string;
|
||||
protocol?: string;
|
||||
score?: number;
|
||||
}
|
||||
|
||||
interface PendingApprovalRequest {
|
||||
id: string;
|
||||
createdAt: string;
|
||||
type: 'audiobook' | 'ebook';
|
||||
selectedTorrent: SelectedTorrentData | null;
|
||||
audiobook: {
|
||||
title: string;
|
||||
author: string;
|
||||
coverArtUrl: string | null;
|
||||
audibleAsin: string | null;
|
||||
};
|
||||
user: {
|
||||
id: string;
|
||||
@@ -32,9 +49,20 @@ interface PendingApprovalRequest {
|
||||
};
|
||||
}
|
||||
|
||||
function formatTorrentSize(bytes: number): string {
|
||||
const gb = bytes / (1024 ** 3);
|
||||
const mb = bytes / (1024 ** 2);
|
||||
return gb >= 1 ? `${gb.toFixed(1)} GB` : `${mb.toFixed(0)} MB`;
|
||||
}
|
||||
|
||||
function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest[] }) {
|
||||
const toast = useToast();
|
||||
const [loadingStates, setLoadingStates] = useState<Record<string, boolean>>({});
|
||||
const [searchModalRequestId, setSearchModalRequestId] = useState<string | null>(null);
|
||||
|
||||
const searchModalRequest = searchModalRequestId
|
||||
? requests.find((r) => r.id === searchModalRequestId)
|
||||
: null;
|
||||
|
||||
const handleApproveRequest = async (requestId: string) => {
|
||||
setLoadingStates((prev) => ({ ...prev, [requestId]: true }));
|
||||
@@ -47,7 +75,6 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
|
||||
|
||||
toast.success('Request approved');
|
||||
|
||||
// Mutate both pending requests and recent requests caches
|
||||
await mutate('/api/admin/requests/pending-approval');
|
||||
await mutate('/api/admin/requests/recent');
|
||||
await mutate('/api/admin/metrics');
|
||||
@@ -72,7 +99,6 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
|
||||
|
||||
toast.success('Request denied');
|
||||
|
||||
// Mutate pending requests cache
|
||||
await mutate('/api/admin/requests/pending-approval');
|
||||
await mutate('/api/admin/metrics');
|
||||
} catch (error) {
|
||||
@@ -85,6 +111,26 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
|
||||
}
|
||||
};
|
||||
|
||||
const handleApproveWithTorrent = async (requestId: string, torrent: TorrentResult) => {
|
||||
await fetchJSON(`/api/admin/requests/${requestId}/approve`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ action: 'approve', selectedTorrent: torrent }),
|
||||
});
|
||||
|
||||
toast.success('Request approved and download started');
|
||||
|
||||
await mutate('/api/admin/requests/pending-approval');
|
||||
await mutate('/api/admin/requests/recent');
|
||||
await mutate('/api/admin/metrics');
|
||||
};
|
||||
|
||||
const LoadingSpinner = () => (
|
||||
<svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="mb-8">
|
||||
{/* Section Header */}
|
||||
@@ -116,6 +162,9 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{requests.map((request) => {
|
||||
const isLoading = loadingStates[request.id] || false;
|
||||
const torrent = request.selectedTorrent;
|
||||
const displayFormat = torrent?.format || torrent?.ebookFormat;
|
||||
const isAnnasArchive = torrent?.source === 'annas_archive';
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -205,89 +254,107 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Pre-Selected Release */}
|
||||
{torrent && torrent.title && (
|
||||
<div className="mx-4 mb-3 px-3 py-2.5 bg-gray-50 dark:bg-gray-900/60 rounded-lg border border-gray-200 dark:border-gray-700/60">
|
||||
<div className="flex items-center gap-1.5 mb-1">
|
||||
<svg className="w-3 h-3 text-gray-400 dark:text-gray-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
|
||||
</svg>
|
||||
<span className="text-[10px] font-semibold uppercase tracking-wider text-gray-400 dark:text-gray-500">
|
||||
User-Selected Release
|
||||
</span>
|
||||
</div>
|
||||
{torrent.infoUrl ? (
|
||||
<a
|
||||
href={torrent.infoUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 transition-colors line-clamp-2 leading-snug"
|
||||
title={torrent.title}
|
||||
>
|
||||
{torrent.title}
|
||||
</a>
|
||||
) : (
|
||||
<p className="text-xs font-medium text-gray-700 dark:text-gray-300 line-clamp-2 leading-snug" title={torrent.title}>
|
||||
{torrent.title}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center gap-1 mt-1.5 text-[11px] text-gray-500 dark:text-gray-400 flex-wrap">
|
||||
{isAnnasArchive ? (
|
||||
<span className="text-orange-600 dark:text-orange-400 font-medium">Anna's Archive</span>
|
||||
) : torrent.indexer ? (
|
||||
<span>{torrent.indexer}</span>
|
||||
) : null}
|
||||
{torrent.size && torrent.size > 0 ? (
|
||||
<>
|
||||
<span className="text-gray-300 dark:text-gray-600 select-none">·</span>
|
||||
<span>{formatTorrentSize(torrent.size)}</span>
|
||||
</>
|
||||
) : null}
|
||||
{displayFormat ? (
|
||||
<>
|
||||
<span className="text-gray-300 dark:text-gray-600 select-none">·</span>
|
||||
<span className="px-1 py-px text-[10px] font-semibold uppercase tracking-wide rounded bg-purple-100 dark:bg-purple-500/15 text-purple-700 dark:text-purple-300">
|
||||
{displayFormat}
|
||||
</span>
|
||||
</>
|
||||
) : null}
|
||||
{torrent.protocol === 'usenet' ? (
|
||||
<>
|
||||
<span className="text-gray-300 dark:text-gray-600 select-none">·</span>
|
||||
<span className="text-sky-600 dark:text-sky-400 font-medium">NZB</span>
|
||||
</>
|
||||
) : torrent.seeders !== undefined && torrent.seeders !== null ? (
|
||||
<>
|
||||
<span className="text-gray-300 dark:text-gray-600 select-none">·</span>
|
||||
<span className="text-emerald-600 dark:text-emerald-400">{torrent.seeders} seeds</span>
|
||||
</>
|
||||
) : null}
|
||||
{torrent.score !== undefined && torrent.score !== null ? (
|
||||
<>
|
||||
<span className="text-gray-300 dark:text-gray-600 select-none">·</span>
|
||||
<span className="font-medium">Score {Math.round(torrent.score)}</span>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="border-t border-amber-200 dark:border-amber-800 bg-gray-50 dark:bg-gray-900/50 px-4 py-3 flex gap-2">
|
||||
<button
|
||||
onClick={() => handleApproveRequest(request.id)}
|
||||
disabled={isLoading}
|
||||
className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 bg-green-600 hover:bg-green-700 disabled:bg-green-400 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition-colors"
|
||||
className="flex-1 inline-flex items-center justify-center gap-1.5 px-3 py-2 bg-green-600 hover:bg-green-700 disabled:bg-green-400 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition-colors"
|
||||
>
|
||||
{isLoading ? (
|
||||
<svg
|
||||
className="animate-spin h-4 w-4"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<circle
|
||||
className="opacity-25"
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="4"
|
||||
/>
|
||||
<path
|
||||
className="opacity-75"
|
||||
fill="currentColor"
|
||||
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
||||
/>
|
||||
</svg>
|
||||
) : (
|
||||
<svg
|
||||
className="w-4 h-4"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M5 13l4 4L19 7"
|
||||
/>
|
||||
{isLoading ? <LoadingSpinner /> : (
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
)}
|
||||
<span>Approve</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setSearchModalRequestId(request.id)}
|
||||
disabled={isLoading}
|
||||
className="flex-1 inline-flex items-center justify-center gap-1.5 px-3 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition-colors"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
|
||||
</svg>
|
||||
<span>Search</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => handleDenyRequest(request.id)}
|
||||
disabled={isLoading}
|
||||
className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 bg-red-600 hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition-colors"
|
||||
className="flex-1 inline-flex items-center justify-center gap-1.5 px-3 py-2 bg-red-600 hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition-colors"
|
||||
>
|
||||
{isLoading ? (
|
||||
<svg
|
||||
className="animate-spin h-4 w-4"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<circle
|
||||
className="opacity-25"
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="4"
|
||||
/>
|
||||
<path
|
||||
className="opacity-75"
|
||||
fill="currentColor"
|
||||
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
||||
/>
|
||||
</svg>
|
||||
) : (
|
||||
<svg
|
||||
className="w-4 h-4"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/>
|
||||
{isLoading ? <LoadingSpinner /> : (
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
)}
|
||||
<span>Deny</span>
|
||||
@@ -297,6 +364,26 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Interactive Search Modal */}
|
||||
{searchModalRequest && (
|
||||
<InteractiveTorrentSearchModal
|
||||
isOpen={!!searchModalRequestId}
|
||||
onClose={() => setSearchModalRequestId(null)}
|
||||
requestId={searchModalRequest.id}
|
||||
audiobook={{
|
||||
title: searchModalRequest.audiobook.title,
|
||||
author: searchModalRequest.audiobook.author,
|
||||
}}
|
||||
searchMode={searchModalRequest.type === 'ebook' ? 'ebook' : 'audiobook'}
|
||||
onConfirm={async (torrent) => {
|
||||
await handleApproveWithTorrent(searchModalRequest.id, torrent);
|
||||
}}
|
||||
onSuccess={() => {
|
||||
setSearchModalRequestId(null);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -100,6 +100,8 @@ export interface PathsSettings {
|
||||
ebookPathTemplate?: string;
|
||||
metadataTaggingEnabled: boolean;
|
||||
chapterMergingEnabled: boolean;
|
||||
fileRenameEnabled: boolean;
|
||||
fileRenameTemplate?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -10,7 +10,7 @@ import { Button } from '@/components/ui/Button';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { usePathsSettings } from './usePathsSettings';
|
||||
import type { PathsSettings } from '../../lib/types';
|
||||
import { validateTemplate, generateMockPreviews } from '@/lib/utils/path-template.util';
|
||||
import { validateTemplate, generateMockPreviews, validateFilenameTemplate, generateMockFilenamePreviews } from '@/lib/utils/path-template.util';
|
||||
|
||||
interface PathsTabProps {
|
||||
paths: PathsSettings;
|
||||
@@ -24,6 +24,13 @@ interface TemplatePreview {
|
||||
previewPaths?: string[];
|
||||
}
|
||||
|
||||
interface FilenamePreview {
|
||||
isValid: boolean;
|
||||
error?: string;
|
||||
single?: string[];
|
||||
multi?: string[];
|
||||
}
|
||||
|
||||
export function PathsTab({ paths, onChange, onValidationChange }: PathsTabProps) {
|
||||
const { testing, testResult, updatePath, testPaths } = usePathsSettings({
|
||||
paths,
|
||||
@@ -73,6 +80,34 @@ export function PathsTab({ paths, onChange, onValidationChange }: PathsTabProps)
|
||||
}
|
||||
}, [paths.ebookPathTemplate]);
|
||||
|
||||
// Live preview state for filename template
|
||||
const [filenamePreview, setFilenamePreview] = useState<FilenamePreview | null>(null);
|
||||
|
||||
// Update filename live preview whenever template changes
|
||||
useEffect(() => {
|
||||
if (!paths.fileRenameEnabled) {
|
||||
setFilenamePreview(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const template = paths.fileRenameTemplate || '{title}';
|
||||
const validation = validateFilenameTemplate(template);
|
||||
|
||||
if (validation.valid) {
|
||||
const previews = generateMockFilenamePreviews(template);
|
||||
setFilenamePreview({
|
||||
isValid: true,
|
||||
single: previews.single,
|
||||
multi: previews.multi,
|
||||
});
|
||||
} else {
|
||||
setFilenamePreview({
|
||||
isValid: false,
|
||||
error: validation.error,
|
||||
});
|
||||
}
|
||||
}, [paths.fileRenameTemplate, paths.fileRenameEnabled]);
|
||||
|
||||
const audiobookTemplate = paths.audiobookPathTemplate || '{author}/{title} {asin}';
|
||||
const ebookTemplate = paths.ebookPathTemplate || '{author}/{title} {asin}';
|
||||
const ebookMatchesAudiobook = ebookTemplate === audiobookTemplate;
|
||||
@@ -218,6 +253,83 @@ export function PathsTab({ paths, onChange, onValidationChange }: PathsTabProps)
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* File Rename Toggle */}
|
||||
<div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
|
||||
<div className="flex items-start gap-4">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="file-rename-settings"
|
||||
checked={paths.fileRenameEnabled}
|
||||
onChange={(e) => updatePath('fileRenameEnabled', e.target.checked)}
|
||||
className="mt-1 h-5 w-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<label
|
||||
htmlFor="file-rename-settings"
|
||||
className="block text-sm font-medium text-gray-900 dark:text-gray-100 cursor-pointer"
|
||||
>
|
||||
Rename files during organization
|
||||
</label>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||
Rename audio and ebook files using a custom naming template when organizing into the media
|
||||
library. When multiple files exist (e.g. chapterized MP3s), an index number is appended.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* File Naming Template (shown when enabled) */}
|
||||
{paths.fileRenameEnabled && (
|
||||
<div className="mt-4 pl-9">
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
File Naming Template
|
||||
</label>
|
||||
<Input
|
||||
type="text"
|
||||
value={paths.fileRenameTemplate || '{title}'}
|
||||
onChange={(e) => updatePath('fileRenameTemplate', e.target.value)}
|
||||
placeholder="{title}"
|
||||
className="font-mono"
|
||||
/>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
|
||||
Uses the same variables as the organization template. Do not include the file extension.
|
||||
</p>
|
||||
|
||||
{/* Filename Validation Error */}
|
||||
{filenamePreview && !filenamePreview.isValid && (
|
||||
<div className="mt-3 p-3 rounded-lg text-sm flex items-start gap-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-800 dark:text-red-200">
|
||||
<span className="flex-shrink-0 mt-0.5">✗</span>
|
||||
<div className="flex-1">
|
||||
<span>{filenamePreview.error || 'Invalid filename template'}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Filename Preview */}
|
||||
{filenamePreview && filenamePreview.isValid && (
|
||||
<div className="mt-3 bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
|
||||
<h4 className="text-sm font-semibold text-gray-900 dark:text-gray-100 mb-2">
|
||||
Single File
|
||||
</h4>
|
||||
<div className="space-y-1.5 text-sm font-mono text-gray-700 dark:text-gray-300">
|
||||
{filenamePreview.single?.map((preview, index) => (
|
||||
<div key={index} className="text-xs">{preview}</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<h4 className="text-sm font-semibold text-gray-900 dark:text-gray-100 mt-3 mb-2">
|
||||
Multiple Files (chapterized)
|
||||
</h4>
|
||||
<div className="space-y-1.5 text-sm font-mono text-gray-700 dark:text-gray-300">
|
||||
{filenamePreview.multi?.map((preview, index) => (
|
||||
<div key={index} className="text-xs">{preview}</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Variable Reference Panel (shared for both templates) */}
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
|
||||
<h3 className="text-sm font-semibold text-blue-900 dark:text-blue-100 mb-3">
|
||||
@@ -255,6 +367,27 @@ export function PathsTab({ paths, onChange, onValidationChange }: PathsTabProps)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Conditional Syntax Help */}
|
||||
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4">
|
||||
<h3 className="text-sm font-semibold text-amber-900 dark:text-amber-100 mb-2">
|
||||
Conditional Syntax
|
||||
</h3>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
|
||||
Wrap text around a variable in <code className="text-amber-700 dark:text-amber-300 font-mono">{'{ }'}</code> to
|
||||
include that text only when the variable has a value. If the variable is empty, the entire block is removed.
|
||||
</p>
|
||||
<div className="text-sm font-mono bg-white dark:bg-gray-900 rounded px-3 py-2 border border-amber-100 dark:border-amber-900">
|
||||
<div className="text-gray-700 dark:text-gray-300">
|
||||
<code className="text-amber-700 dark:text-amber-300">{'{Book seriesPart - }'}</code>
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
With value: <span className="text-green-700 dark:text-green-400">Book 1 - </span>
|
||||
•
|
||||
Without value: <span className="text-red-700 dark:text-red-400">(removed)</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Metadata Tagging Toggle */}
|
||||
<div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
|
||||
<div className="flex items-start gap-4">
|
||||
|
||||
@@ -14,6 +14,7 @@ const logger = RMABLogger.create('API.Admin.Requests.Approve');
|
||||
|
||||
const ApprovalActionSchema = z.object({
|
||||
action: z.enum(['approve', 'deny']),
|
||||
selectedTorrent: z.any().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -37,8 +38,8 @@ export async function POST(
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
|
||||
// Validate action
|
||||
const { action } = ApprovalActionSchema.parse(body);
|
||||
// Validate action and optional admin-selected torrent
|
||||
const { action, selectedTorrent: adminSelectedTorrent } = ApprovalActionSchema.parse(body);
|
||||
|
||||
// Fetch the request
|
||||
const existingRequest = await prisma.request.findUnique({
|
||||
@@ -78,12 +79,15 @@ export async function POST(
|
||||
const jobQueue = getJobQueueService();
|
||||
const isEbookRequest = existingRequest.type === 'ebook';
|
||||
|
||||
// Check if request has a pre-selected torrent (from interactive search)
|
||||
if (existingRequest.selectedTorrent) {
|
||||
const selectedTorrent = existingRequest.selectedTorrent as any;
|
||||
// Use admin-provided torrent (from admin interactive search) or fall back to user's pre-selected torrent
|
||||
const effectiveTorrent = adminSelectedTorrent || existingRequest.selectedTorrent;
|
||||
|
||||
// User pre-selected a specific torrent - download that torrent directly
|
||||
logger.info(`Request ${id} has pre-selected torrent, starting download`, {
|
||||
if (effectiveTorrent) {
|
||||
const selectedTorrent = effectiveTorrent as any;
|
||||
const torrentSource = adminSelectedTorrent ? 'admin' : 'user';
|
||||
|
||||
// Download the selected torrent directly
|
||||
logger.info(`Request ${id} has ${torrentSource}-selected torrent, starting download`, {
|
||||
requestId: id,
|
||||
userId: existingRequest.userId,
|
||||
adminId: req.user.sub,
|
||||
@@ -167,17 +171,20 @@ export async function POST(
|
||||
logger.error('Failed to queue notification', { error: error instanceof Error ? error.message : String(error) });
|
||||
});
|
||||
|
||||
logger.info(`Request ${id} approved by admin ${req.user.sub}, downloading pre-selected torrent`, {
|
||||
logger.info(`Request ${id} approved by admin ${req.user.sub}, downloading ${torrentSource}-selected torrent`, {
|
||||
requestId: id,
|
||||
userId: updatedRequest.userId,
|
||||
audiobookTitle: existingRequest.audiobook.title,
|
||||
adminId: req.user.sub,
|
||||
type: existingRequest.type,
|
||||
torrentSource,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Request approved and download started with pre-selected torrent',
|
||||
message: adminSelectedTorrent
|
||||
? 'Request approved and download started with admin-selected torrent'
|
||||
: 'Request approved and download started with pre-selected torrent',
|
||||
request: updatedRequest,
|
||||
});
|
||||
} else {
|
||||
|
||||
@@ -15,7 +15,7 @@ export async function PUT(request: NextRequest) {
|
||||
return requireAuth(request, async (req: AuthenticatedRequest) => {
|
||||
return requireAdmin(req, async () => {
|
||||
try {
|
||||
const { downloadDir, mediaDir, audiobookPathTemplate, ebookPathTemplate, metadataTaggingEnabled, chapterMergingEnabled } = await request.json();
|
||||
const { downloadDir, mediaDir, audiobookPathTemplate, ebookPathTemplate, metadataTaggingEnabled, chapterMergingEnabled, fileRenameEnabled, fileRenameTemplate } = await request.json();
|
||||
|
||||
if (!downloadDir || !mediaDir) {
|
||||
return NextResponse.json(
|
||||
@@ -97,6 +97,32 @@ export async function PUT(request: NextRequest) {
|
||||
},
|
||||
});
|
||||
|
||||
// Update file rename setting
|
||||
await prisma.configuration.upsert({
|
||||
where: { key: 'file_rename_enabled' },
|
||||
update: { value: String(fileRenameEnabled ?? false) },
|
||||
create: {
|
||||
key: 'file_rename_enabled',
|
||||
value: String(fileRenameEnabled ?? false),
|
||||
category: 'automation',
|
||||
description: 'Rename audio and ebook files using a custom naming template during organization',
|
||||
},
|
||||
});
|
||||
|
||||
// Update file rename template
|
||||
if (fileRenameTemplate !== undefined) {
|
||||
await prisma.configuration.upsert({
|
||||
where: { key: 'file_rename_template' },
|
||||
update: { value: fileRenameTemplate },
|
||||
create: {
|
||||
key: 'file_rename_template',
|
||||
value: fileRenameTemplate,
|
||||
category: 'automation',
|
||||
description: 'Template for renaming audio and ebook files during organization',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
logger.info('Paths settings updated');
|
||||
|
||||
// Clear config cache for all updated keys so services get fresh values
|
||||
@@ -107,6 +133,8 @@ export async function PUT(request: NextRequest) {
|
||||
configService.clearCache('ebook_path_template');
|
||||
configService.clearCache('metadata_tagging_enabled');
|
||||
configService.clearCache('chapter_merging_enabled');
|
||||
configService.clearCache('file_rename_enabled');
|
||||
configService.clearCache('file_rename_template');
|
||||
|
||||
// Invalidate all download client singletons to force reload of download_dir
|
||||
const { invalidateDownloadClientManager } = await import('@/lib/services/download-client-manager.service');
|
||||
|
||||
@@ -128,6 +128,8 @@ export async function GET(request: NextRequest) {
|
||||
ebookPathTemplate: configMap.get('ebook_path_template') || configMap.get('audiobook_path_template') || '{author}/{title} {asin}',
|
||||
metadataTaggingEnabled: configMap.get('metadata_tagging_enabled') === 'true',
|
||||
chapterMergingEnabled: configMap.get('chapter_merging_enabled') === 'true',
|
||||
fileRenameEnabled: configMap.get('file_rename_enabled') === 'true',
|
||||
fileRenameTemplate: configMap.get('file_rename_template') || '{title}',
|
||||
},
|
||||
ebook: {
|
||||
// New granular source toggles (with migration from legacy ebook_sidecar_enabled)
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
/**
|
||||
* Component: Configuration API Routes (by category)
|
||||
* Documentation: documentation/backend/services/config.md
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getConfigService } from '@/lib/services/config.service';
|
||||
import { RMABLogger } from '@/lib/utils/logger';
|
||||
|
||||
const logger = RMABLogger.create('API.Config.Category');
|
||||
|
||||
// GET /api/config/:category - Get all config for a category
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ category: string }> }
|
||||
) {
|
||||
try {
|
||||
// TODO: Add authentication middleware - admin only
|
||||
const { category } = await params;
|
||||
const configService = getConfigService();
|
||||
|
||||
const config = await configService.getCategory(category);
|
||||
|
||||
return NextResponse.json({
|
||||
category,
|
||||
config,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to get config for category', { error: error instanceof Error ? error.message : String(error) });
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Failed to get configuration',
|
||||
message: error instanceof Error ? error.message : 'Unknown error',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
/**
|
||||
* Component: Configuration API Routes
|
||||
* Documentation: documentation/backend/services/config.md
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getConfigService, ConfigUpdate } from '@/lib/services/config.service';
|
||||
import { z } from 'zod';
|
||||
import { RMABLogger } from '@/lib/utils/logger';
|
||||
|
||||
const logger = RMABLogger.create('API.Config');
|
||||
|
||||
const ConfigUpdateSchema = z.object({
|
||||
updates: z.array(
|
||||
z.object({
|
||||
key: z.string(),
|
||||
value: z.string(),
|
||||
encrypted: z.boolean().optional(),
|
||||
category: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
// PUT /api/config - Update multiple configuration values
|
||||
export async function PUT(request: NextRequest) {
|
||||
try {
|
||||
// TODO: Add authentication middleware - admin only
|
||||
|
||||
const body = await request.json();
|
||||
const { updates } = ConfigUpdateSchema.parse(body);
|
||||
|
||||
const configService = getConfigService();
|
||||
await configService.setMany(updates as ConfigUpdate[]);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
updated: updates.length,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to update configuration', { error: error instanceof Error ? error.message : String(error) });
|
||||
|
||||
if (error instanceof z.ZodError) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Validation error',
|
||||
details: error.errors,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Failed to update configuration',
|
||||
message: error instanceof Error ? error.message : 'Unknown error',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// GET /api/config - Get all configuration (masked sensitive values)
|
||||
export async function GET() {
|
||||
try {
|
||||
// TODO: Add authentication middleware - admin only
|
||||
|
||||
const configService = getConfigService();
|
||||
const allConfig = await configService.getAll();
|
||||
|
||||
return NextResponse.json({
|
||||
config: allConfig,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to get all configuration', { error: error instanceof Error ? error.message : String(error) });
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Failed to get configuration',
|
||||
message: error instanceof Error ? error.message : 'Unknown error',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -67,8 +67,8 @@ export async function POST(
|
||||
);
|
||||
}
|
||||
|
||||
// Check if request is awaiting approval
|
||||
if (requestRecord.status === 'awaiting_approval') {
|
||||
// Check if request is awaiting approval (admins can still search to override the user's selection)
|
||||
if (requestRecord.status === 'awaiting_approval' && req.user.role !== 'admin') {
|
||||
return NextResponse.json(
|
||||
{ error: 'AwaitingApproval', message: 'This request is awaiting admin approval. You cannot search for torrents until it is approved.' },
|
||||
{ status: 403 }
|
||||
|
||||
@@ -38,6 +38,7 @@ interface InteractiveTorrentSearchModalProps {
|
||||
onSuccess?: () => void;
|
||||
searchMode?: 'audiobook' | 'ebook'; // Search mode - defaults to audiobook
|
||||
replaceIssueId?: string; // Optional - when set, confirm handler calls replace endpoint instead
|
||||
onConfirm?: (torrent: TorrentResult) => Promise<void>; // Optional - overrides default confirm handler
|
||||
}
|
||||
|
||||
// Format relative time from publish date
|
||||
@@ -90,6 +91,7 @@ export function InteractiveTorrentSearchModal({
|
||||
onSuccess,
|
||||
searchMode = 'audiobook',
|
||||
replaceIssueId,
|
||||
onConfirm,
|
||||
}: InteractiveTorrentSearchModalProps) {
|
||||
// Hooks for existing audiobook request flow
|
||||
const { searchTorrents: searchByRequestId, isLoading: isSearchingByRequest, error: searchByRequestError } = useInteractiveSearch();
|
||||
@@ -113,6 +115,7 @@ export function InteractiveTorrentSearchModal({
|
||||
const [results, setResults] = useState<(RankedTorrent & { qualityScore?: number; source?: string; ebookFormat?: string })[]>([]);
|
||||
const [confirmTorrent, setConfirmTorrent] = useState<TorrentResult | null>(null);
|
||||
const [searchTitle, setSearchTitle] = useState(audiobook.title);
|
||||
const [isCustomConfirming, setIsCustomConfirming] = useState(false);
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
// Stable close handler via ref
|
||||
@@ -130,11 +133,13 @@ export function InteractiveTorrentSearchModal({
|
||||
const isSearching = isEbookMode
|
||||
? (useAsinMode ? isSearchingEbooksByAsin : isSearchingEbooks)
|
||||
: (hasRequestId ? isSearchingByRequest : isSearchingByAudiobook);
|
||||
const isDownloading = replaceIssueId
|
||||
? isReplacing
|
||||
: isEbookMode
|
||||
? (useAsinMode ? isSelectingEbookByAsin : isSelectingEbook)
|
||||
: (hasRequestId ? isSelectingTorrent : isRequestingWithTorrent);
|
||||
const isDownloading = isCustomConfirming
|
||||
? true
|
||||
: replaceIssueId
|
||||
? isReplacing
|
||||
: isEbookMode
|
||||
? (useAsinMode ? isSelectingEbookByAsin : isSelectingEbook)
|
||||
: (hasRequestId ? isSelectingTorrent : isRequestingWithTorrent);
|
||||
const error = replaceIssueId
|
||||
? (replaceError || (hasRequestId ? searchByRequestError : searchByAudiobookError))
|
||||
: isEbookMode
|
||||
@@ -218,7 +223,11 @@ export function InteractiveTorrentSearchModal({
|
||||
const handleConfirmDownload = async () => {
|
||||
if (!confirmTorrent) return;
|
||||
try {
|
||||
if (replaceIssueId) {
|
||||
if (onConfirm) {
|
||||
// Custom confirm handler (e.g., admin approve-with-torrent flow)
|
||||
setIsCustomConfirming(true);
|
||||
await onConfirm(confirmTorrent);
|
||||
} else if (replaceIssueId) {
|
||||
// Reported issue replacement flow
|
||||
await replaceWithTorrent(replaceIssueId, confirmTorrent);
|
||||
} else if (isEbookMode) {
|
||||
@@ -241,6 +250,8 @@ export function InteractiveTorrentSearchModal({
|
||||
} catch (err) {
|
||||
console.error('Failed to download:', err);
|
||||
setConfirmTorrent(null);
|
||||
} finally {
|
||||
setIsCustomConfirming(false);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Component: Download Client Timeout Constants
|
||||
* Documentation: documentation/phase3/download-clients.md
|
||||
*
|
||||
* Some indexers (e.g. YGGtorrent) enforce a ~30s wait before allowing
|
||||
* .torrent file downloads. 60s gives sufficient headroom.
|
||||
*/
|
||||
|
||||
/** Timeout for download client API calls and .torrent file fetches (ms) */
|
||||
export const DOWNLOAD_CLIENT_TIMEOUT = 60000;
|
||||
@@ -16,7 +16,7 @@ import type { AudibleRegion } from '../types/audible';
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type SupportedLanguage = 'en' | 'de' | 'es';
|
||||
export type SupportedLanguage = 'en' | 'de' | 'es' | 'fr';
|
||||
|
||||
export interface ScrapingConfig {
|
||||
/** Audible locale query-param value (e.g. 'english', 'deutsch') */
|
||||
@@ -170,6 +170,38 @@ const SPANISH_CONFIG: LanguageConfig = {
|
||||
},
|
||||
};
|
||||
|
||||
const FRENCH_CONFIG: LanguageConfig = {
|
||||
code: 'fr',
|
||||
annasArchiveLang: 'fr',
|
||||
epubCode: 'fr',
|
||||
stopWords: ['le', 'la', 'les', 'un', 'une', 'de', 'des', 'sur', 'dans', '\u00e0', 'et', 'par', 'pour'],
|
||||
characterReplacements: {},
|
||||
scraping: {
|
||||
audibleLocaleParam: 'français',
|
||||
authorPrefixes: ['De :', '\u00c9crit par :', 'Auteur :'],
|
||||
narratorPrefixes: ['Lu par :'],
|
||||
lengthLabels: ['Dur\u00e9e :'],
|
||||
languageLabels: ['Langue :'],
|
||||
releaseDateLabels: ['Date de publication :'],
|
||||
seriesLabels: ['S\u00e9rie :'],
|
||||
acceptedLanguageValues: ['français', 'french'],
|
||||
runtimeHourPatterns: [/(\d+)\s*h\b/i, /(\d+)\s*heures?/i],
|
||||
runtimeMinutePatterns: [/(\d+)\s*min/i, /(\d+)\s*minutes?/i],
|
||||
ratingPatterns: [/(\d+[.,]?\d*)\s*de\s*5/i],
|
||||
releaseDatePatterns: [/Date de publication:\s*(.+)/i],
|
||||
descriptionExcludePatterns: [
|
||||
/\$\d+\.\d+/,
|
||||
/\d+,\d+\s*\u20ac/,
|
||||
/Essayer pour/i,
|
||||
/R\u00e9siliez \u00e0 tout moment/i,
|
||||
/Acheter pour/i,
|
||||
/^\s*de\s+[\w\s,]+$/i,
|
||||
],
|
||||
durationDetectionPattern: /\d+\s*(h|heures?)\s*\d*\s*(min|minutes?)?/i,
|
||||
ratingTextSelector: 'sur 5 étoiles',
|
||||
},
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Lookup Maps
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -178,6 +210,7 @@ export const LANGUAGE_CONFIGS: Record<SupportedLanguage, LanguageConfig> = {
|
||||
en: ENGLISH_CONFIG,
|
||||
de: GERMAN_CONFIG,
|
||||
es: SPANISH_CONFIG,
|
||||
fr: FRENCH_CONFIG,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -192,6 +225,7 @@ export const REGION_LANGUAGE_MAP: Record<AudibleRegion, SupportedLanguage> = {
|
||||
in: 'en',
|
||||
de: 'de',
|
||||
es: 'es',
|
||||
fr: 'fr',
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
import https from 'https';
|
||||
import path from 'path';
|
||||
import { DOWNLOAD_CLIENT_TIMEOUT } from '../constants/download-timeouts';
|
||||
import * as parseTorrentModule from 'parse-torrent';
|
||||
import { RMABLogger } from '../utils/logger';
|
||||
import { PathMapper, PathMappingConfig } from '../utils/path-mapper';
|
||||
@@ -49,7 +50,7 @@ export class DelugeService implements IDownloadClient {
|
||||
? 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 });
|
||||
this.client = axios.create({ baseURL: this.baseUrl, timeout: DOWNLOAD_CLIENT_TIMEOUT, httpsAgent });
|
||||
}
|
||||
|
||||
/** JSON-RPC call with automatic re-authentication on auth failure */
|
||||
@@ -190,7 +191,7 @@ export class DelugeService implements IDownloadClient {
|
||||
try {
|
||||
torrentResponse = await axios.get(torrentUrl, {
|
||||
responseType: 'arraybuffer', maxRedirects: 0,
|
||||
validateStatus: (s) => s >= 200 && s < 300, timeout: 30000,
|
||||
validateStatus: (s) => s >= 200 && s < 300, timeout: DOWNLOAD_CLIENT_TIMEOUT,
|
||||
});
|
||||
if (torrentResponse.data.length > 0) {
|
||||
const magnetMatch = torrentResponse.data.toString().match(/^magnet:\?[^\s]+$/);
|
||||
@@ -203,7 +204,7 @@ export class DelugeService implements IDownloadClient {
|
||||
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 }); }
|
||||
try { torrentResponse = await axios.get(loc, { responseType: 'arraybuffer', timeout: DOWNLOAD_CLIENT_TIMEOUT, maxRedirects: 5 }); }
|
||||
catch { throw new Error('Failed to download torrent file after redirect'); }
|
||||
} else { throw new Error(`Invalid redirect location: ${loc}`); }
|
||||
} else { throw new Error(`Failed to download torrent: HTTP ${status}`); }
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
import { XMLParser } from 'fast-xml-parser';
|
||||
import { DOWNLOAD_CLIENT_TIMEOUT } from '../constants/download-timeouts';
|
||||
import { TorrentResult } from '../utils/ranking-algorithm';
|
||||
import { RMABLogger } from '../utils/logger';
|
||||
|
||||
@@ -87,7 +88,7 @@ export class ProwlarrService {
|
||||
headers: {
|
||||
'X-Api-Key': this.apiKey,
|
||||
},
|
||||
timeout: 60000, // 60 seconds - some indexers (e.g. yggtorrent) enforce a 30s wait before download
|
||||
timeout: DOWNLOAD_CLIENT_TIMEOUT,
|
||||
paramsSerializer: {
|
||||
serialize: (params) => {
|
||||
// Custom serializer to handle arrays correctly for Prowlarr API
|
||||
@@ -314,7 +315,7 @@ export class ProwlarrService {
|
||||
limit: 100,
|
||||
extended: 1,
|
||||
},
|
||||
timeout: 60000,
|
||||
timeout: DOWNLOAD_CLIENT_TIMEOUT,
|
||||
responseType: 'text', // Get XML as text
|
||||
});
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
import https from 'https';
|
||||
import path from 'path';
|
||||
import { DOWNLOAD_CLIENT_TIMEOUT } from '../constants/download-timeouts';
|
||||
import * as parseTorrentModule from 'parse-torrent';
|
||||
import FormData from 'form-data';
|
||||
import { RMABLogger } from '../utils/logger';
|
||||
@@ -140,7 +141,7 @@ export class QBittorrentService implements IDownloadClient {
|
||||
|
||||
this.client = axios.create({
|
||||
baseURL: `${this.baseUrl}/api/v2`,
|
||||
timeout: 30000,
|
||||
timeout: DOWNLOAD_CLIENT_TIMEOUT,
|
||||
httpsAgent: this.httpsAgent,
|
||||
// Support nginx/Apache reverse proxy with HTTP Basic Auth
|
||||
auth: {
|
||||
@@ -352,7 +353,7 @@ export class QBittorrentService implements IDownloadClient {
|
||||
responseType: 'arraybuffer',
|
||||
maxRedirects: 0,
|
||||
validateStatus: (status) => status >= 200 && status < 300, // Only 2xx is success
|
||||
timeout: 30000, // 30 seconds - public indexers can be slow
|
||||
timeout: DOWNLOAD_CLIENT_TIMEOUT,
|
||||
});
|
||||
|
||||
logger.info(` Got 2xx response, size=${torrentResponse.data.length} bytes`);
|
||||
@@ -394,7 +395,7 @@ export class QBittorrentService implements IDownloadClient {
|
||||
try {
|
||||
torrentResponse = await axios.get(location, {
|
||||
responseType: 'arraybuffer',
|
||||
timeout: 30000,
|
||||
timeout: DOWNLOAD_CLIENT_TIMEOUT,
|
||||
maxRedirects: 5,
|
||||
});
|
||||
logger.info(` After following redirect: size=${torrentResponse.data.length} bytes`);
|
||||
@@ -1088,17 +1089,34 @@ export class QBittorrentService implements IDownloadClient {
|
||||
* Map a TorrentInfo object to the unified DownloadInfo format.
|
||||
*/
|
||||
protected mapTorrentToDownloadInfo(torrent: TorrentInfo): DownloadInfo {
|
||||
const status = this.mapStateToDownloadStatus(torrent.state);
|
||||
|
||||
// For completed/seeding torrents, combine save_path with the content folder basename.
|
||||
// Two problems are solved simultaneously:
|
||||
// 1. TempPathEnabled race — content_path may still reference the temp/incomplete directory
|
||||
// after qBittorrent marks the torrent as seeding but before the file move finishes.
|
||||
// 2. Name mismatch — torrent.name (display name) can differ from the actual folder name
|
||||
// on disk (the root folder inside the torrent archive). content_path always reflects
|
||||
// the real filesystem name, so we extract its basename for the join.
|
||||
const isFinished = status === 'seeding' || status === 'completed';
|
||||
const contentBasename = torrent.content_path
|
||||
? path.basename(torrent.content_path)
|
||||
: torrent.name;
|
||||
const downloadPath = isFinished
|
||||
? path.join(torrent.save_path, contentBasename)
|
||||
: (torrent.content_path || path.join(torrent.save_path, torrent.name));
|
||||
|
||||
return {
|
||||
id: torrent.hash,
|
||||
name: torrent.name,
|
||||
size: torrent.size,
|
||||
bytesDownloaded: torrent.downloaded,
|
||||
progress: torrent.progress,
|
||||
status: this.mapStateToDownloadStatus(torrent.state),
|
||||
status,
|
||||
downloadSpeed: torrent.dlspeed,
|
||||
eta: torrent.eta,
|
||||
category: torrent.category,
|
||||
downloadPath: torrent.content_path || path.join(torrent.save_path, torrent.name),
|
||||
downloadPath,
|
||||
completedAt: torrent.completion_on > 0 ? new Date(torrent.completion_on * 1000) : undefined,
|
||||
seedingTime: torrent.seeding_time,
|
||||
ratio: torrent.ratio,
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
import https from 'https';
|
||||
import path from 'path';
|
||||
import { DOWNLOAD_CLIENT_TIMEOUT } from '../constants/download-timeouts';
|
||||
import * as parseTorrentModule from 'parse-torrent';
|
||||
import { RMABLogger } from '../utils/logger';
|
||||
import { PathMapper, PathMappingConfig } from '../utils/path-mapper';
|
||||
@@ -106,7 +107,7 @@ export class TransmissionService implements IDownloadClient {
|
||||
|
||||
this.client = axios.create({
|
||||
baseURL: this.baseUrl,
|
||||
timeout: 30000,
|
||||
timeout: DOWNLOAD_CLIENT_TIMEOUT,
|
||||
httpsAgent: this.httpsAgent,
|
||||
});
|
||||
}
|
||||
@@ -274,7 +275,7 @@ export class TransmissionService implements IDownloadClient {
|
||||
responseType: 'arraybuffer',
|
||||
maxRedirects: 0,
|
||||
validateStatus: (status) => status >= 200 && status < 300,
|
||||
timeout: 30000,
|
||||
timeout: DOWNLOAD_CLIENT_TIMEOUT,
|
||||
});
|
||||
|
||||
// Check if response body is a magnet link
|
||||
@@ -302,7 +303,7 @@ export class TransmissionService implements IDownloadClient {
|
||||
try {
|
||||
torrentResponse = await axios.get(location, {
|
||||
responseType: 'arraybuffer',
|
||||
timeout: 30000,
|
||||
timeout: DOWNLOAD_CLIENT_TIMEOUT,
|
||||
maxRedirects: 5,
|
||||
});
|
||||
} catch {
|
||||
|
||||
@@ -128,7 +128,19 @@ export async function processOrganizeFiles(payload: OrganizeFilesPayload): Promi
|
||||
});
|
||||
const template = templateConfig?.value || '{author}/{title} {asin}';
|
||||
|
||||
// Organize files (pass template and logger to file organizer)
|
||||
// Read file rename configuration
|
||||
const fileRenameEnabledConfig = await prisma.configuration.findUnique({
|
||||
where: { key: 'file_rename_enabled' },
|
||||
});
|
||||
const fileRenameTemplateConfig = await prisma.configuration.findUnique({
|
||||
where: { key: 'file_rename_template' },
|
||||
});
|
||||
const renameConfig = {
|
||||
enabled: fileRenameEnabledConfig?.value === 'true',
|
||||
template: fileRenameTemplateConfig?.value || '{title}',
|
||||
};
|
||||
|
||||
// Organize files (pass template, logger, and rename config to file organizer)
|
||||
const result = await organizer.organize(
|
||||
downloadPath,
|
||||
{
|
||||
@@ -142,7 +154,8 @@ export async function processOrganizeFiles(payload: OrganizeFilesPayload): Promi
|
||||
seriesPart: audiobook.seriesPart || undefined,
|
||||
},
|
||||
template,
|
||||
jobId ? { jobId, context: 'FileOrganizer' } : undefined
|
||||
jobId ? { jobId, context: 'FileOrganizer' } : undefined,
|
||||
renameConfig
|
||||
);
|
||||
|
||||
if (!result.success) {
|
||||
@@ -556,6 +569,18 @@ async function processEbookOrganization(
|
||||
}
|
||||
}
|
||||
|
||||
// Read file rename configuration
|
||||
const fileRenameEnabledConfig = await prisma.configuration.findUnique({
|
||||
where: { key: 'file_rename_enabled' },
|
||||
});
|
||||
const fileRenameTemplateConfig = await prisma.configuration.findUnique({
|
||||
where: { key: 'file_rename_template' },
|
||||
});
|
||||
const ebookRenameConfig = {
|
||||
enabled: fileRenameEnabledConfig?.value === 'true',
|
||||
template: fileRenameTemplateConfig?.value || '{title}',
|
||||
};
|
||||
|
||||
// Organize ebook files (organizer will detect ebook type and skip audio-specific processing)
|
||||
// Pass all metadata that could be used in path templates (same as audiobooks)
|
||||
const result = await organizer.organizeEbook(
|
||||
@@ -571,7 +596,8 @@ async function processEbookOrganization(
|
||||
},
|
||||
template,
|
||||
jobId ? { jobId, context: 'FileOrganizer.Ebook' } : undefined,
|
||||
isIndexerDownload
|
||||
isIndexerDownload,
|
||||
ebookRenameConfig
|
||||
);
|
||||
|
||||
// Clean up fixed EPUB temp file after organization (regardless of success)
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
import type { SupportedLanguage } from '../constants/language-config';
|
||||
|
||||
export type AudibleRegion = 'us' | 'ca' | 'uk' | 'au' | 'in' | 'de' | 'es';
|
||||
export type AudibleRegion = 'us' | 'ca' | 'uk' | 'au' | 'in' | 'de' | 'es' | 'fr';
|
||||
|
||||
export interface AudibleRegionConfig {
|
||||
code: AudibleRegion;
|
||||
@@ -64,6 +64,13 @@ export const AUDIBLE_REGIONS: Record<AudibleRegion, AudibleRegionConfig> = {
|
||||
baseUrl: 'https://www.audible.es',
|
||||
audnexusParam: 'es',
|
||||
language: 'es',
|
||||
},
|
||||
fr: {
|
||||
code: 'fr',
|
||||
name: 'France',
|
||||
baseUrl: 'https://www.audible.fr',
|
||||
audnexusParam: 'fr',
|
||||
language: 'fr',
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
checkDiskSpace,
|
||||
} from './chapter-merger';
|
||||
import { prisma } from '../db';
|
||||
import { substituteTemplate, type TemplateVariables } from './path-template.util';
|
||||
import { substituteTemplate, buildRenamedFilename, type TemplateVariables } from './path-template.util';
|
||||
import { AUDIO_EXTENSIONS } from '../constants/audio-formats';
|
||||
|
||||
export interface AudiobookMetadata {
|
||||
@@ -77,7 +77,8 @@ export class FileOrganizer {
|
||||
downloadPath: string,
|
||||
audiobook: AudiobookMetadata,
|
||||
template: string,
|
||||
loggerConfig?: LoggerConfig
|
||||
loggerConfig?: LoggerConfig,
|
||||
renameConfig?: { enabled: boolean; template: string }
|
||||
): Promise<OrganizationResult> {
|
||||
// Create logger if config provided
|
||||
const logger = loggerConfig ? RMABLogger.forJob(loggerConfig.jobId, loggerConfig.context) : null;
|
||||
@@ -294,8 +295,17 @@ export class FileOrganizer {
|
||||
// Create target directory
|
||||
await fs.mkdir(targetPath, { recursive: true });
|
||||
|
||||
// Determine if file renaming should be applied
|
||||
const shouldRename = renameConfig?.enabled && renameConfig.template;
|
||||
const isMultiFile = audioFiles.length > 1;
|
||||
|
||||
if (shouldRename) {
|
||||
await logger?.info(`File renaming enabled with template: ${renameConfig.template}${isMultiFile ? ` (${audioFiles.length} files, indices will be appended)` : ''}`);
|
||||
}
|
||||
|
||||
// Copy audio files (do NOT delete originals - needed for seeding)
|
||||
for (const audioFile of audioFiles) {
|
||||
for (let i = 0; i < audioFiles.length; i++) {
|
||||
const audioFile = audioFiles[i];
|
||||
// Handle merged files (absolute paths) vs original files (relative paths)
|
||||
const isAbsolutePath = path.isAbsolute(audioFile);
|
||||
const originalSourcePath = isAbsolutePath
|
||||
@@ -303,7 +313,30 @@ export class FileOrganizer {
|
||||
: isFile
|
||||
? downloadPath
|
||||
: path.join(downloadPath, audioFile);
|
||||
const filename = path.basename(audioFile);
|
||||
|
||||
// Determine target filename (apply rename template if enabled)
|
||||
let filename: string;
|
||||
if (shouldRename) {
|
||||
const ext = path.extname(audioFile);
|
||||
const variables: TemplateVariables = {
|
||||
author: audiobook.author,
|
||||
title: audiobook.title,
|
||||
narrator: audiobook.narrator,
|
||||
asin: audiobook.asin,
|
||||
year: audiobook.year,
|
||||
series: audiobook.series,
|
||||
seriesPart: audiobook.seriesPart,
|
||||
};
|
||||
filename = buildRenamedFilename(
|
||||
renameConfig.template,
|
||||
variables,
|
||||
ext,
|
||||
isMultiFile ? i + 1 : undefined,
|
||||
);
|
||||
} else {
|
||||
filename = path.basename(audioFile);
|
||||
}
|
||||
|
||||
const targetFilePath = path.join(targetPath, filename);
|
||||
|
||||
// Check if we have a tagged version of this file
|
||||
@@ -690,7 +723,8 @@ export class FileOrganizer {
|
||||
metadata: { title: string; author: string; narrator?: string; asin?: string; year?: number; series?: string; seriesPart?: string },
|
||||
template: string,
|
||||
loggerConfig?: LoggerConfig,
|
||||
isIndexerDownload: boolean = false
|
||||
isIndexerDownload: boolean = false,
|
||||
renameConfig?: { enabled: boolean; template: string }
|
||||
): Promise<EbookOrganizationResult> {
|
||||
const logger = loggerConfig ? RMABLogger.forJob(loggerConfig.jobId, loggerConfig.context) : null;
|
||||
|
||||
@@ -739,9 +773,25 @@ export class FileOrganizer {
|
||||
// Create target directory
|
||||
await fs.mkdir(targetDir, { recursive: true });
|
||||
|
||||
// Build target filename (sanitize source filename)
|
||||
// Build target filename (apply rename template if enabled, otherwise sanitize source filename)
|
||||
const sourceFilename = path.basename(ebookFile);
|
||||
const targetFilename = this.sanitizePath(sourceFilename);
|
||||
let targetFilename: string;
|
||||
if (renameConfig?.enabled && renameConfig.template) {
|
||||
const originalExt = path.extname(ebookFile);
|
||||
const variables: TemplateVariables = {
|
||||
author: metadata.author,
|
||||
title: metadata.title,
|
||||
narrator: metadata.narrator,
|
||||
asin: metadata.asin,
|
||||
year: metadata.year,
|
||||
series: metadata.series,
|
||||
seriesPart: metadata.seriesPart,
|
||||
};
|
||||
targetFilename = buildRenamedFilename(renameConfig.template, variables, originalExt);
|
||||
await logger?.info(`Renamed ebook file: ${sourceFilename} -> ${targetFilename}`);
|
||||
} else {
|
||||
targetFilename = this.sanitizePath(sourceFilename);
|
||||
}
|
||||
const targetPath = path.join(targetDir, targetFilename);
|
||||
|
||||
// Check if target already exists
|
||||
|
||||
@@ -68,6 +68,81 @@ function sanitizePath(name: string): string {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find valid template variable names within arbitrary content text.
|
||||
* Sorts by length descending to prevent substring false matches
|
||||
* (e.g., 'seriesPart' matched before 'series').
|
||||
* Uses word-boundary detection to avoid matching variable names
|
||||
* that are substrings of other words.
|
||||
*/
|
||||
function findVariablesInContent(content: string): string[] {
|
||||
const sortedVars = [...VALID_VARIABLES].sort((a, b) => b.length - a.length);
|
||||
const found: string[] = [];
|
||||
|
||||
for (const varName of sortedVars) {
|
||||
const regex = new RegExp(`(?<![a-zA-Z0-9])${varName}(?![a-zA-Z0-9])`);
|
||||
if (regex.test(content)) {
|
||||
found.push(varName);
|
||||
}
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve conditional blocks in the template.
|
||||
* A conditional block is {literal text varName more text} where the entire
|
||||
* content is rendered only if ALL variables inside have non-empty values.
|
||||
* If any variable is empty/missing, the entire block is removed.
|
||||
*
|
||||
* Simple variable references like {author} are left untouched for the
|
||||
* existing substitution logic to handle.
|
||||
*
|
||||
* Must run after escaped-brace replacement and before simple variable substitution.
|
||||
*/
|
||||
function resolveConditionalBlocks(
|
||||
template: string,
|
||||
variables: TemplateVariables
|
||||
): string {
|
||||
return template.replace(/\{([^}]+)\}/g, (match, content: string) => {
|
||||
// If content is exactly a valid variable name, skip (leave for simple substitution)
|
||||
if (VALID_VARIABLES.includes(content)) {
|
||||
return match;
|
||||
}
|
||||
|
||||
// Find variables in the content
|
||||
const foundVars = findVariablesInContent(content);
|
||||
|
||||
// If no variables found, leave as-is (validation will catch it)
|
||||
if (foundVars.length === 0) {
|
||||
return match;
|
||||
}
|
||||
|
||||
// Check if all found variables have non-empty values
|
||||
const allPresent = foundVars.every(varName => {
|
||||
const value = variables[varName as keyof TemplateVariables];
|
||||
return value !== undefined && value !== null && String(value).trim() !== '';
|
||||
});
|
||||
|
||||
if (!allPresent) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Substitute variables within the content, output rest as literal text
|
||||
// Sort by length descending to prevent substring false matches
|
||||
let result = content;
|
||||
const sortedVars = [...foundVars].sort((a, b) => b.length - a.length);
|
||||
for (const varName of sortedVars) {
|
||||
const value = variables[varName as keyof TemplateVariables];
|
||||
const sanitizedValue = sanitizePath(String(value).trim());
|
||||
const regex = new RegExp(`(?<![a-zA-Z0-9])${varName}(?![a-zA-Z0-9])`, 'g');
|
||||
result = result.replace(regex, sanitizedValue);
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Substitute template variables with actual values
|
||||
*
|
||||
@@ -99,6 +174,9 @@ export function substituteTemplate(
|
||||
// so they survive the variable substitution and path cleanup steps
|
||||
result = result.replace(/\\\{/g, LBRACE_PLACEHOLDER).replace(/\\\}/g, RBRACE_PLACEHOLDER);
|
||||
|
||||
// Resolve conditional blocks before simple variable substitution
|
||||
result = resolveConditionalBlocks(result, variables);
|
||||
|
||||
// Substitute each variable
|
||||
for (const key of VALID_VARIABLES) {
|
||||
const value = variables[key as keyof TemplateVariables];
|
||||
@@ -187,21 +265,47 @@ export function validateTemplate(template: string): ValidationResult {
|
||||
|
||||
if (variableMatches) {
|
||||
for (const match of variableMatches) {
|
||||
const varName = match.slice(1, -1); // Remove { and }
|
||||
const content = match.slice(1, -1); // Remove { and }
|
||||
|
||||
if (!VALID_VARIABLES.includes(varName)) {
|
||||
// Simple variable — exact match to a valid variable name
|
||||
if (VALID_VARIABLES.includes(content)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Conditional block — must contain at least one valid variable
|
||||
const foundVars = findVariablesInContent(content);
|
||||
if (foundVars.length === 0) {
|
||||
return {
|
||||
valid: false,
|
||||
error: `Unknown variable: {${varName}}. Valid variables are: ${VALID_VARIABLES.map(v => `{${v}}`).join(', ')}`
|
||||
error: `No valid variable found in conditional block: {${content}}. Valid variables are: ${VALID_VARIABLES.map(v => `{${v}}`).join(', ')}`
|
||||
};
|
||||
}
|
||||
|
||||
// Check literal text inside conditional block for invalid path chars
|
||||
let literalText = content;
|
||||
const sortedVars = [...foundVars].sort((a, b) => b.length - a.length);
|
||||
for (const varName of sortedVars) {
|
||||
literalText = literalText.replace(
|
||||
new RegExp(`(?<![a-zA-Z0-9])${varName}(?![a-zA-Z0-9])`, 'g'),
|
||||
''
|
||||
);
|
||||
}
|
||||
const invalidCharsInBlock = literalText.match(INVALID_PATH_CHARS);
|
||||
if (invalidCharsInBlock) {
|
||||
return {
|
||||
valid: false,
|
||||
error: `Invalid characters found: ${[...new Set(invalidCharsInBlock)].join(', ')}. These characters are not allowed in path templates.`
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove valid variables temporarily to check for invalid characters
|
||||
// Remove valid variables and conditional blocks to check remaining text for invalid chars
|
||||
let templateWithoutVars = templateWithoutEscapedBraces;
|
||||
for (const varName of VALID_VARIABLES) {
|
||||
templateWithoutVars = templateWithoutVars.replace(new RegExp(`\\{${varName}\\}`, 'g'), '');
|
||||
if (variableMatches) {
|
||||
for (const match of variableMatches) {
|
||||
templateWithoutVars = templateWithoutVars.replace(match, '');
|
||||
}
|
||||
}
|
||||
|
||||
// Check for invalid characters outside of variables
|
||||
@@ -286,3 +390,192 @@ export function generateMockPreviews(template: string): string[] {
|
||||
export function getValidVariables(): string[] {
|
||||
return [...VALID_VARIABLES];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a filename template string
|
||||
*
|
||||
* Similar to validateTemplate but for filenames (not paths):
|
||||
* - Disallows forward slashes (no directory separators in filenames)
|
||||
* - Does not require relative path structure
|
||||
* - Must contain at least one variable
|
||||
*
|
||||
* @param template - Filename template string to validate
|
||||
* @returns Validation result with error message if invalid
|
||||
*/
|
||||
export function validateFilenameTemplate(template: string): ValidationResult {
|
||||
if (!template || template.trim().length === 0) {
|
||||
return {
|
||||
valid: false,
|
||||
error: 'Filename template cannot be empty',
|
||||
};
|
||||
}
|
||||
|
||||
// Disallow forward slashes — filenames cannot contain directory separators
|
||||
if (template.includes('/')) {
|
||||
return {
|
||||
valid: false,
|
||||
error: 'Filename template cannot contain "/" (directory separators). Use the organization template for directory structure.',
|
||||
};
|
||||
}
|
||||
|
||||
// Disallow backslashes that aren't brace escapes
|
||||
if (/\\(?![{}])/.test(template)) {
|
||||
return {
|
||||
valid: false,
|
||||
error: 'Filename template cannot contain backslashes. Use the organization template for directory structure.',
|
||||
};
|
||||
}
|
||||
|
||||
// Strip escaped braces before parsing
|
||||
const templateWithoutEscapedBraces = template.replace(/\\[{}]/g, '');
|
||||
|
||||
// Extract all variables from the stripped template
|
||||
const variableMatches = templateWithoutEscapedBraces.match(/\{[^}]+\}/g);
|
||||
|
||||
if (variableMatches) {
|
||||
for (const match of variableMatches) {
|
||||
const content = match.slice(1, -1);
|
||||
|
||||
// Simple variable
|
||||
if (VALID_VARIABLES.includes(content)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Conditional block — must contain at least one valid variable
|
||||
const foundVars = findVariablesInContent(content);
|
||||
if (foundVars.length === 0) {
|
||||
return {
|
||||
valid: false,
|
||||
error: `No valid variable found in: {${content}}. Valid variables are: ${VALID_VARIABLES.map(v => `{${v}}`).join(', ')}`,
|
||||
};
|
||||
}
|
||||
|
||||
// Check literal text inside conditional block for invalid filename chars
|
||||
let literalText = content;
|
||||
const sortedVars = [...foundVars].sort((a, b) => b.length - a.length);
|
||||
for (const varName of sortedVars) {
|
||||
literalText = literalText.replace(
|
||||
new RegExp(`(?<![a-zA-Z0-9])${varName}(?![a-zA-Z0-9])`, 'g'),
|
||||
''
|
||||
);
|
||||
}
|
||||
const invalidCharsInBlock = literalText.match(INVALID_PATH_CHARS);
|
||||
if (invalidCharsInBlock) {
|
||||
return {
|
||||
valid: false,
|
||||
error: `Invalid characters found: ${[...new Set(invalidCharsInBlock)].join(', ')}. These characters are not allowed in filenames.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove valid variables and conditional blocks to check remaining text
|
||||
let templateWithoutVars = templateWithoutEscapedBraces;
|
||||
if (variableMatches) {
|
||||
for (const match of variableMatches) {
|
||||
templateWithoutVars = templateWithoutVars.replace(match, '');
|
||||
}
|
||||
}
|
||||
|
||||
// Check for invalid characters outside of variables
|
||||
const invalidChars = templateWithoutVars.match(INVALID_PATH_CHARS);
|
||||
if (invalidChars) {
|
||||
return {
|
||||
valid: false,
|
||||
error: `Invalid characters found: ${[...new Set(invalidChars)].join(', ')}. These characters are not allowed in filenames.`,
|
||||
};
|
||||
}
|
||||
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate mock filename previews using sample audiobook data
|
||||
*
|
||||
* Creates example filenames with extensions to demonstrate how the template will look.
|
||||
* Shows both single-file and multi-file (with index) examples.
|
||||
*
|
||||
* @param template - Filename template string
|
||||
* @returns Object with single and multi-file preview arrays
|
||||
*/
|
||||
export function generateMockFilenamePreviews(template: string): {
|
||||
single: string[];
|
||||
multi: string[];
|
||||
} {
|
||||
const mockData: TemplateVariables[] = [
|
||||
{
|
||||
author: 'Brandon Sanderson',
|
||||
title: 'Mistborn: The Final Empire',
|
||||
narrator: 'Michael Kramer',
|
||||
asin: 'B002UZMLXM',
|
||||
year: 2006,
|
||||
series: 'The Mistborn Saga',
|
||||
seriesPart: '1',
|
||||
},
|
||||
{
|
||||
author: 'Douglas Adams',
|
||||
title: "The Hitchhiker's Guide to the Galaxy",
|
||||
narrator: 'Stephen Fry',
|
||||
asin: 'B0009JKV9W',
|
||||
year: 2005,
|
||||
series: "Hitchhiker's Guide",
|
||||
seriesPart: '1',
|
||||
},
|
||||
];
|
||||
|
||||
const single = mockData.map((variables) => {
|
||||
const name = substituteTemplate(template, variables);
|
||||
return `${name}.m4b`;
|
||||
});
|
||||
|
||||
// Show multi-file example with first mock data only
|
||||
const multiName = substituteTemplate(template, mockData[0]);
|
||||
const multi = [
|
||||
`${multiName} - 1.mp3`,
|
||||
`${multiName} - 2.mp3`,
|
||||
`${multiName} - 3.mp3`,
|
||||
];
|
||||
|
||||
return { single, multi };
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a renamed filename from a template, metadata variables, and original extension.
|
||||
* Optionally appends a 1-based index for multi-file scenarios.
|
||||
*
|
||||
* @param template - Filename template string (e.g., "{title}")
|
||||
* @param variables - Template variables with metadata values
|
||||
* @param originalExtension - File extension including dot (e.g., ".m4b")
|
||||
* @param index - Optional 1-based index for multi-file scenarios
|
||||
* @returns Sanitized filename with extension
|
||||
*/
|
||||
export function buildRenamedFilename(
|
||||
template: string,
|
||||
variables: TemplateVariables,
|
||||
originalExtension: string,
|
||||
index?: number,
|
||||
): string {
|
||||
let baseName = substituteTemplate(template, variables);
|
||||
|
||||
// substituteTemplate cleans up slashes for paths — but since this is a filename,
|
||||
// remove any residual slashes that conditional blocks might have introduced
|
||||
baseName = baseName.replace(/[/\\]/g, '');
|
||||
|
||||
// Sanitize again for filename safety
|
||||
baseName = baseName
|
||||
.replace(/[<>:"/\\|?*]/g, '')
|
||||
.trim()
|
||||
.replace(/^\.+/, '')
|
||||
.replace(/\.+$/, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.slice(0, 200);
|
||||
|
||||
if (index !== undefined) {
|
||||
baseName = `${baseName} - ${index}`;
|
||||
}
|
||||
|
||||
// Ensure extension starts with a dot
|
||||
const ext = originalExtension.startsWith('.') ? originalExtension : `.${originalExtension}`;
|
||||
|
||||
return `${baseName}${ext}`;
|
||||
}
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
/**
|
||||
* Component: Config API Route Tests
|
||||
* Documentation: documentation/testing.md
|
||||
*/
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const configServiceMock = vi.hoisted(() => ({
|
||||
setMany: vi.fn(),
|
||||
getAll: vi.fn(),
|
||||
getCategory: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/services/config.service', () => ({
|
||||
getConfigService: () => configServiceMock,
|
||||
}));
|
||||
|
||||
describe('Config API routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('returns full configuration', async () => {
|
||||
configServiceMock.getAll.mockResolvedValue({ plex_url: 'http://plex' });
|
||||
const { GET } = await import('@/app/api/config/route');
|
||||
|
||||
const response = await GET();
|
||||
const payload = await response.json();
|
||||
|
||||
expect(payload.config.plex_url).toBe('http://plex');
|
||||
});
|
||||
|
||||
it('updates configuration values', async () => {
|
||||
const { PUT } = await import('@/app/api/config/route');
|
||||
const response = await PUT({
|
||||
json: vi.fn().mockResolvedValue({
|
||||
updates: [{ key: 'plex_url', value: 'http://plex' }],
|
||||
}),
|
||||
} as any);
|
||||
const payload = await response.json();
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(payload.updated).toBe(1);
|
||||
expect(configServiceMock.setMany).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 400 when configuration update payload is invalid', async () => {
|
||||
const { PUT } = await import('@/app/api/config/route');
|
||||
const response = await PUT({ json: vi.fn().mockResolvedValue({}) } as any);
|
||||
const payload = await response.json();
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(payload.error).toMatch(/Validation error/);
|
||||
});
|
||||
|
||||
it('returns 500 when configuration update fails', async () => {
|
||||
configServiceMock.setMany.mockRejectedValueOnce(new Error('db down'));
|
||||
const { PUT } = await import('@/app/api/config/route');
|
||||
const response = await PUT({
|
||||
json: vi.fn().mockResolvedValue({
|
||||
updates: [{ key: 'plex_url', value: 'http://plex' }],
|
||||
}),
|
||||
} as any);
|
||||
const payload = await response.json();
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(payload.error).toMatch(/Failed to update configuration/);
|
||||
});
|
||||
|
||||
it('returns 500 when configuration lookup fails', async () => {
|
||||
configServiceMock.getAll.mockRejectedValueOnce(new Error('db down'));
|
||||
const { GET } = await import('@/app/api/config/route');
|
||||
|
||||
const response = await GET();
|
||||
const payload = await response.json();
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(payload.error).toMatch(/Failed to get configuration/);
|
||||
});
|
||||
|
||||
it('returns category configuration', async () => {
|
||||
configServiceMock.getCategory.mockResolvedValue({ plex_url: 'http://plex' });
|
||||
const { GET } = await import('@/app/api/config/[category]/route');
|
||||
|
||||
const response = await GET({} as any, { params: Promise.resolve({ category: 'plex' }) });
|
||||
const payload = await response.json();
|
||||
|
||||
expect(payload.category).toBe('plex');
|
||||
expect(payload.config.plex_url).toBe('http://plex');
|
||||
});
|
||||
|
||||
it('returns 500 when category configuration lookup fails', async () => {
|
||||
configServiceMock.getCategory.mockRejectedValueOnce(new Error('db down'));
|
||||
const { GET } = await import('@/app/api/config/[category]/route');
|
||||
|
||||
const response = await GET({} as any, { params: Promise.resolve({ category: 'plex' }) });
|
||||
const payload = await response.json();
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(payload.error).toMatch(/Failed to get configuration/);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -433,7 +433,7 @@ describe('Setup test routes', () => {
|
||||
expect(payload.success).toBe(true);
|
||||
expect(payload.template).toBeDefined();
|
||||
expect(payload.template.isValid).toBe(false);
|
||||
expect(payload.template.error).toContain('Unknown variable');
|
||||
expect(payload.template.error).toContain('No valid variable found in conditional block');
|
||||
expect(payload.template.previewPaths).toBeUndefined();
|
||||
});
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* Documentation: documentation/phase3/qbittorrent.md
|
||||
*/
|
||||
|
||||
import path from 'path';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { QBittorrentService, getQBittorrentService, invalidateQBittorrentService } from '@/lib/integrations/qbittorrent.service';
|
||||
|
||||
@@ -328,6 +329,236 @@ describe('QBittorrentService', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('downloadPath resolution (TempPathEnabled race + name mismatch fix)', () => {
|
||||
it('uses save_path + content basename for seeding torrents even when content_path points to temp dir', async () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
(service as any).cookie = 'SID=temppath';
|
||||
clientMock.get.mockResolvedValueOnce({
|
||||
data: [{
|
||||
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
|
||||
dlspeed: 0, upspeed: 5000, downloaded: 1000, uploaded: 500,
|
||||
eta: 0, state: 'uploading', category: 'readmeabook', tags: '',
|
||||
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
|
||||
completion_on: 1700000000, added_on: 1699000000,
|
||||
}],
|
||||
});
|
||||
|
||||
const info = await service.getDownload('abc123');
|
||||
|
||||
expect(info).not.toBeNull();
|
||||
expect(info!.status).toBe('seeding');
|
||||
// Must use save_path + content_path basename, NOT the stale full content_path
|
||||
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
|
||||
expect(info!.downloadPath).not.toContain('incomplete');
|
||||
});
|
||||
|
||||
it('uses save_path for stalledUP torrents (completed, stalled on upload)', async () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
(service as any).cookie = 'SID=stalledup';
|
||||
clientMock.get.mockResolvedValueOnce({
|
||||
data: [{
|
||||
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
|
||||
dlspeed: 0, upspeed: 0, downloaded: 1000, uploaded: 200,
|
||||
eta: 0, state: 'stalledUP', category: 'readmeabook', tags: '',
|
||||
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
|
||||
completion_on: 1700000000, added_on: 1699000000,
|
||||
}],
|
||||
});
|
||||
|
||||
const info = await service.getDownload('abc123');
|
||||
|
||||
expect(info!.status).toBe('seeding');
|
||||
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
|
||||
});
|
||||
|
||||
it('uses save_path for pausedUP torrents (completed, paused on upload)', async () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
(service as any).cookie = 'SID=pausedup2';
|
||||
clientMock.get.mockResolvedValueOnce({
|
||||
data: [{
|
||||
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
|
||||
dlspeed: 0, upspeed: 0, downloaded: 1000, uploaded: 0,
|
||||
eta: 0, state: 'pausedUP', category: 'readmeabook', tags: '',
|
||||
save_path: '/data/torrents/readmeabook/', content_path: '/tmp/incomplete/Audiobook',
|
||||
completion_on: 1700000000, added_on: 1699000000,
|
||||
}],
|
||||
});
|
||||
|
||||
const info = await service.getDownload('abc123');
|
||||
|
||||
expect(info!.status).toBe('seeding');
|
||||
expect(info!.downloadPath).toBe(path.join('/data/torrents/readmeabook/', 'Audiobook'));
|
||||
});
|
||||
|
||||
it('uses save_path for stoppedUP torrents (qBittorrent v5.x completed)', async () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
(service as any).cookie = 'SID=stoppedup2';
|
||||
clientMock.get.mockResolvedValueOnce({
|
||||
data: [{
|
||||
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
|
||||
dlspeed: 0, upspeed: 0, downloaded: 1000, uploaded: 100,
|
||||
eta: 0, state: 'stoppedUP', category: 'readmeabook', tags: '',
|
||||
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
|
||||
completion_on: 1700000000, added_on: 1699000000,
|
||||
}],
|
||||
});
|
||||
|
||||
const info = await service.getDownload('abc123');
|
||||
|
||||
expect(info!.status).toBe('seeding');
|
||||
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
|
||||
});
|
||||
|
||||
it('uses content_path for actively downloading torrents', async () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
(service as any).cookie = 'SID=downloading';
|
||||
clientMock.get.mockResolvedValueOnce({
|
||||
data: [{
|
||||
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 0.5,
|
||||
dlspeed: 5000, upspeed: 0, downloaded: 500, uploaded: 0,
|
||||
eta: 100, state: 'downloading', category: 'readmeabook', tags: '',
|
||||
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
|
||||
completion_on: 0, added_on: 1699000000,
|
||||
}],
|
||||
});
|
||||
|
||||
const info = await service.getDownload('abc123');
|
||||
|
||||
expect(info!.status).toBe('downloading');
|
||||
// During download, content_path is used (points to where files currently are)
|
||||
expect(info!.downloadPath).toBe('/incomplete/Audiobook');
|
||||
});
|
||||
|
||||
it('falls back to save_path + name when content_path is empty during download', async () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
(service as any).cookie = 'SID=nocontent';
|
||||
clientMock.get.mockResolvedValueOnce({
|
||||
data: [{
|
||||
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 0.3,
|
||||
dlspeed: 1000, upspeed: 0, downloaded: 300, uploaded: 0,
|
||||
eta: 700, state: 'downloading', category: 'readmeabook', tags: '',
|
||||
save_path: '/downloads/', content_path: '',
|
||||
completion_on: 0, added_on: 1699000000,
|
||||
}],
|
||||
});
|
||||
|
||||
const info = await service.getDownload('abc123');
|
||||
|
||||
expect(info!.status).toBe('downloading');
|
||||
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
|
||||
});
|
||||
|
||||
it('uses save_path for forcedUP torrents (force-resumed seeding)', async () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
(service as any).cookie = 'SID=forcedup2';
|
||||
clientMock.get.mockResolvedValueOnce({
|
||||
data: [{
|
||||
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
|
||||
dlspeed: 0, upspeed: 10000, downloaded: 1000, uploaded: 2000,
|
||||
eta: 0, state: 'forcedUP', category: 'readmeabook', tags: '',
|
||||
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
|
||||
completion_on: 1700000000, added_on: 1699000000,
|
||||
}],
|
||||
});
|
||||
|
||||
const info = await service.getDownload('abc123');
|
||||
|
||||
expect(info!.status).toBe('seeding');
|
||||
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
|
||||
});
|
||||
|
||||
it('uses save_path for queuedUP torrents (completed, queued for upload)', async () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
(service as any).cookie = 'SID=queuedup';
|
||||
clientMock.get.mockResolvedValueOnce({
|
||||
data: [{
|
||||
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
|
||||
dlspeed: 0, upspeed: 0, downloaded: 1000, uploaded: 0,
|
||||
eta: 0, state: 'queuedUP', category: 'readmeabook', tags: '',
|
||||
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
|
||||
completion_on: 1700000000, added_on: 1699000000,
|
||||
}],
|
||||
});
|
||||
|
||||
const info = await service.getDownload('abc123');
|
||||
|
||||
expect(info!.status).toBe('seeding');
|
||||
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
|
||||
});
|
||||
|
||||
it('uses content_path basename when torrent name differs from folder name on disk', async () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
(service as any).cookie = 'SID=namemismatch';
|
||||
clientMock.get.mockResolvedValueOnce({
|
||||
data: [{
|
||||
hash: 'abc123',
|
||||
name: 'Harry Potter and the Sorcerers Stone [Full-Cast] (aka Harry Potter and the Philosophers Stone) - J.K. Rowling',
|
||||
size: 3006477107, progress: 1.0,
|
||||
dlspeed: 0, upspeed: 0, downloaded: 3006477107, uploaded: 500000,
|
||||
eta: 0, state: 'uploading', category: 'readmeabook', tags: '',
|
||||
save_path: '/downloads/books/',
|
||||
content_path: '/incomplete/Harry Potter and the Sorcerers Stone (Full-Cast Edition) EAC3+Atmos 6ch - J.K. Rowling',
|
||||
completion_on: 1700000000, added_on: 1699000000,
|
||||
}],
|
||||
});
|
||||
|
||||
const info = await service.getDownload('abc123');
|
||||
|
||||
expect(info!.status).toBe('seeding');
|
||||
// Must use the content_path basename (actual folder on disk), NOT torrent.name
|
||||
expect(info!.downloadPath).toBe(
|
||||
path.join('/downloads/books/', 'Harry Potter and the Sorcerers Stone (Full-Cast Edition) EAC3+Atmos 6ch - J.K. Rowling')
|
||||
);
|
||||
// Must NOT use the torrent name (which differs from the real folder)
|
||||
expect(info!.downloadPath).not.toContain('[Full-Cast]');
|
||||
expect(info!.downloadPath).not.toContain('incomplete');
|
||||
});
|
||||
|
||||
it('falls back to torrent name when content_path is empty for finished torrents', async () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
(service as any).cookie = 'SID=nocontent-finished';
|
||||
clientMock.get.mockResolvedValueOnce({
|
||||
data: [{
|
||||
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
|
||||
dlspeed: 0, upspeed: 0, downloaded: 1000, uploaded: 0,
|
||||
eta: 0, state: 'pausedUP', category: 'readmeabook', tags: '',
|
||||
save_path: '/downloads/', content_path: '',
|
||||
completion_on: 1700000000, added_on: 1699000000,
|
||||
}],
|
||||
});
|
||||
|
||||
const info = await service.getDownload('abc123');
|
||||
|
||||
expect(info!.status).toBe('seeding');
|
||||
// With no content_path, falls back to torrent name
|
||||
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
|
||||
});
|
||||
|
||||
it('uses content_path basename for single-file torrent where name differs', async () => {
|
||||
const service = new QBittorrentService('http://qb', 'user', 'pass');
|
||||
(service as any).cookie = 'SID=singlefile';
|
||||
clientMock.get.mockResolvedValueOnce({
|
||||
data: [{
|
||||
hash: 'abc123',
|
||||
name: 'My Audiobook - Special Edition',
|
||||
size: 500000000, progress: 1.0,
|
||||
dlspeed: 0, upspeed: 1000, downloaded: 500000000, uploaded: 100000,
|
||||
eta: 0, state: 'uploading', category: 'readmeabook', tags: '',
|
||||
save_path: '/downloads/books/',
|
||||
content_path: '/incomplete/My Audiobook.m4b',
|
||||
completion_on: 1700000000, added_on: 1699000000,
|
||||
}],
|
||||
});
|
||||
|
||||
const info = await service.getDownload('abc123');
|
||||
|
||||
expect(info!.status).toBe('seeding');
|
||||
// Single file: basename is the filename itself
|
||||
expect(info!.downloadPath).toBe(path.join('/downloads/books/', 'My Audiobook.m4b'));
|
||||
expect(info!.downloadPath).not.toContain('Special Edition');
|
||||
});
|
||||
});
|
||||
|
||||
it('authenticates and stores a session cookie', async () => {
|
||||
axiosMock.post.mockResolvedValue({
|
||||
status: 200,
|
||||
|
||||
@@ -8,6 +8,9 @@ import {
|
||||
validateTemplate,
|
||||
generateMockPreviews,
|
||||
getValidVariables,
|
||||
validateFilenameTemplate,
|
||||
generateMockFilenamePreviews,
|
||||
buildRenamedFilename,
|
||||
type TemplateVariables
|
||||
} from '@/lib/utils/path-template.util';
|
||||
|
||||
@@ -213,6 +216,142 @@ describe('substituteTemplate', () => {
|
||||
const result = substituteTemplate(template, variables);
|
||||
expect(result).toBe('Author/{narrated}/Title');
|
||||
});
|
||||
|
||||
// Conditional block tests
|
||||
it('should render conditional block when variable has a value', () => {
|
||||
const template = '{author}/{Book seriesPart - }{title}';
|
||||
const variables: TemplateVariables = {
|
||||
author: 'Brandon Sanderson',
|
||||
title: 'Mistborn',
|
||||
seriesPart: '1'
|
||||
};
|
||||
|
||||
const result = substituteTemplate(template, variables);
|
||||
expect(result).toBe('Brandon Sanderson/Book 1 - Mistborn');
|
||||
});
|
||||
|
||||
it('should remove conditional block when variable is missing', () => {
|
||||
const template = '{author}/{Book seriesPart - }{title}';
|
||||
const variables: TemplateVariables = {
|
||||
author: 'Andy Weir',
|
||||
title: 'Project Hail Mary'
|
||||
// seriesPart is missing
|
||||
};
|
||||
|
||||
const result = substituteTemplate(template, variables);
|
||||
expect(result).toBe('Andy Weir/Project Hail Mary');
|
||||
});
|
||||
|
||||
it('should handle conditional block with path separator', () => {
|
||||
const template = '{author}/{series/Book seriesPart - }{title}';
|
||||
const variables: TemplateVariables = {
|
||||
author: 'Brandon Sanderson',
|
||||
title: 'Mistborn',
|
||||
series: 'The Mistborn Saga',
|
||||
seriesPart: '1'
|
||||
};
|
||||
|
||||
const result = substituteTemplate(template, variables);
|
||||
expect(result).toBe('Brandon Sanderson/The Mistborn Saga/Book 1 - Mistborn');
|
||||
});
|
||||
|
||||
it('should render conditional block when all variables present', () => {
|
||||
const template = '{author}/{series Book seriesPart}/{title}';
|
||||
const variables: TemplateVariables = {
|
||||
author: 'Brandon Sanderson',
|
||||
title: 'Mistborn',
|
||||
series: 'The Mistborn Saga',
|
||||
seriesPart: '1'
|
||||
};
|
||||
|
||||
const result = substituteTemplate(template, variables);
|
||||
expect(result).toBe('Brandon Sanderson/The Mistborn Saga Book 1/Mistborn');
|
||||
});
|
||||
|
||||
it('should remove conditional block when any variable is missing', () => {
|
||||
const template = '{author}/{series Book seriesPart}/{title}';
|
||||
const variables: TemplateVariables = {
|
||||
author: 'Andy Weir',
|
||||
title: 'Project Hail Mary',
|
||||
series: 'Some Series'
|
||||
// seriesPart is missing
|
||||
};
|
||||
|
||||
const result = substituteTemplate(template, variables);
|
||||
expect(result).toBe('Andy Weir/Project Hail Mary');
|
||||
});
|
||||
|
||||
it('should handle adjacent conditional blocks', () => {
|
||||
const template = '{author}/{series - }{Book seriesPart - }{title}';
|
||||
const variables: TemplateVariables = {
|
||||
author: 'Brandon Sanderson',
|
||||
title: 'Mistborn',
|
||||
series: 'The Mistborn Saga',
|
||||
seriesPart: '1'
|
||||
};
|
||||
|
||||
const result = substituteTemplate(template, variables);
|
||||
expect(result).toBe('Brandon Sanderson/The Mistborn Saga - Book 1 - Mistborn');
|
||||
});
|
||||
|
||||
it('should handle conditional block next to simple variable', () => {
|
||||
const template = '{author}/{series - }{title}';
|
||||
const variables: TemplateVariables = {
|
||||
author: 'Andy Weir',
|
||||
title: 'Project Hail Mary'
|
||||
// series is missing
|
||||
};
|
||||
|
||||
const result = substituteTemplate(template, variables);
|
||||
expect(result).toBe('Andy Weir/Project Hail Mary');
|
||||
});
|
||||
|
||||
it('should handle conditional block with year variable', () => {
|
||||
const template = '{author}/{title} {(year)}';
|
||||
const variables: TemplateVariables = {
|
||||
author: 'Brandon Sanderson',
|
||||
title: 'Mistborn',
|
||||
year: 2006
|
||||
};
|
||||
|
||||
const result = substituteTemplate(template, variables);
|
||||
expect(result).toBe('Brandon Sanderson/Mistborn (2006)');
|
||||
});
|
||||
|
||||
it('should remove year conditional block when year is missing', () => {
|
||||
const template = '{author}/{title} {(year)}';
|
||||
const variables: TemplateVariables = {
|
||||
author: 'Andy Weir',
|
||||
title: 'Project Hail Mary'
|
||||
// year is missing
|
||||
};
|
||||
|
||||
const result = substituteTemplate(template, variables);
|
||||
expect(result).toBe('Andy Weir/Project Hail Mary');
|
||||
});
|
||||
|
||||
it('should still handle simple variables correctly (regression)', () => {
|
||||
const template = '{author}/{title}';
|
||||
const variables: TemplateVariables = {
|
||||
author: 'Brandon Sanderson',
|
||||
title: 'Mistborn'
|
||||
};
|
||||
|
||||
const result = substituteTemplate(template, variables);
|
||||
expect(result).toBe('Brandon Sanderson/Mistborn');
|
||||
});
|
||||
|
||||
it('should remove conditional block when variable is empty string', () => {
|
||||
const template = '{author}/{Book seriesPart - }{title}';
|
||||
const variables: TemplateVariables = {
|
||||
author: 'Author',
|
||||
title: 'Title',
|
||||
seriesPart: ''
|
||||
};
|
||||
|
||||
const result = substituteTemplate(template, variables);
|
||||
expect(result).toBe('Author/Title');
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateTemplate', () => {
|
||||
@@ -247,7 +386,7 @@ describe('validateTemplate', () => {
|
||||
it('should reject unknown variables', () => {
|
||||
const result = validateTemplate('{author}/{invalid}');
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toContain('Unknown variable');
|
||||
expect(result.error).toContain('No valid variable found in conditional block');
|
||||
expect(result.error).toContain('{invalid}');
|
||||
});
|
||||
|
||||
@@ -287,12 +426,13 @@ describe('validateTemplate', () => {
|
||||
it('should provide helpful error messages for multiple unknown variables', () => {
|
||||
const result = validateTemplate('{author}/{invalid1}/{invalid2}');
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toContain('Unknown variable');
|
||||
expect(result.error).toContain('No valid variable found in conditional block');
|
||||
});
|
||||
|
||||
it('should list valid variables in error message', () => {
|
||||
const result = validateTemplate('{invalid}');
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toContain('No valid variable found in conditional block');
|
||||
expect(result.error).toContain('{author}');
|
||||
expect(result.error).toContain('{title}');
|
||||
expect(result.error).toContain('{narrator}');
|
||||
@@ -334,6 +474,34 @@ describe('validateTemplate', () => {
|
||||
const result = validateTemplate('\\{\\}');
|
||||
expect(result.valid).toBe(true);
|
||||
});
|
||||
|
||||
// Conditional block validation tests
|
||||
it('should accept conditional blocks with valid variables', () => {
|
||||
const result = validateTemplate('{author}/{Book seriesPart - }{title}');
|
||||
expect(result.valid).toBe(true);
|
||||
});
|
||||
|
||||
it('should accept conditional blocks with multiple variables', () => {
|
||||
const result = validateTemplate('{author}/{series Book seriesPart}/{title}');
|
||||
expect(result.valid).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject conditional blocks with no valid variables', () => {
|
||||
const result = validateTemplate('{author}/{random text}/{title}');
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toContain('No valid variable found in conditional block');
|
||||
});
|
||||
|
||||
it('should reject conditional blocks with invalid path chars inside', () => {
|
||||
const result = validateTemplate('{author}/{series: part}/{title}');
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toContain('Invalid characters');
|
||||
});
|
||||
|
||||
it('should accept mix of simple variables and conditional blocks', () => {
|
||||
const result = validateTemplate('{author}/{series - }{Book seriesPart - }{title} {(year)}');
|
||||
expect(result.valid).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateMockPreviews', () => {
|
||||
@@ -444,3 +612,183 @@ describe('getValidVariables', () => {
|
||||
expect(vars1).not.toBe(vars2); // Different array instances
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateFilenameTemplate', () => {
|
||||
it('should accept valid filename templates', () => {
|
||||
const templates = [
|
||||
'{title}',
|
||||
'{author} - {title}',
|
||||
'{title} ({year})',
|
||||
'{author} - {title} {(year)}',
|
||||
];
|
||||
|
||||
templates.forEach(template => {
|
||||
const result = validateFilenameTemplate(template);
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.error).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
it('should reject empty templates', () => {
|
||||
const result = validateFilenameTemplate('');
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toContain('empty');
|
||||
});
|
||||
|
||||
it('should reject templates containing forward slashes', () => {
|
||||
const result = validateFilenameTemplate('{author}/{title}');
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toContain('/');
|
||||
expect(result.error).toContain('directory separator');
|
||||
});
|
||||
|
||||
it('should reject templates containing backslashes (not brace escapes)', () => {
|
||||
const result = validateFilenameTemplate('{author}\\n{title}');
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toContain('backslash');
|
||||
});
|
||||
|
||||
it('should accept escaped braces in filename templates', () => {
|
||||
const result = validateFilenameTemplate('\\{{title}\\}');
|
||||
expect(result.valid).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject unknown variables', () => {
|
||||
const result = validateFilenameTemplate('{invalid}');
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toContain('No valid variable found');
|
||||
});
|
||||
|
||||
it('should reject invalid characters', () => {
|
||||
const invalidChars = ['<', '>', ':', '"', '|', '?', '*'];
|
||||
|
||||
invalidChars.forEach(char => {
|
||||
const result = validateFilenameTemplate(`{title}${char}extra`);
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.error).toContain('Invalid characters');
|
||||
});
|
||||
});
|
||||
|
||||
it('should accept conditional blocks in filename templates', () => {
|
||||
const result = validateFilenameTemplate('{title} {(year)}');
|
||||
expect(result.valid).toBe(true);
|
||||
});
|
||||
|
||||
it('should accept templates with only static text', () => {
|
||||
const result = validateFilenameTemplate('audiobook');
|
||||
expect(result.valid).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateMockFilenamePreviews', () => {
|
||||
it('should return single and multi-file previews', () => {
|
||||
const result = generateMockFilenamePreviews('{title}');
|
||||
|
||||
expect(result.single).toBeDefined();
|
||||
expect(result.multi).toBeDefined();
|
||||
expect(result.single.length).toBe(2);
|
||||
expect(result.multi.length).toBe(3);
|
||||
});
|
||||
|
||||
it('should include file extensions in single previews', () => {
|
||||
const result = generateMockFilenamePreviews('{title}');
|
||||
|
||||
result.single.forEach(preview => {
|
||||
expect(preview).toMatch(/\.m4b$/);
|
||||
});
|
||||
});
|
||||
|
||||
it('should include index and extensions in multi-file previews', () => {
|
||||
const result = generateMockFilenamePreviews('{title}');
|
||||
|
||||
expect(result.multi[0]).toMatch(/ - 1\.mp3$/);
|
||||
expect(result.multi[1]).toMatch(/ - 2\.mp3$/);
|
||||
expect(result.multi[2]).toMatch(/ - 3\.mp3$/);
|
||||
});
|
||||
|
||||
it('should substitute variables correctly', () => {
|
||||
const result = generateMockFilenamePreviews('{author} - {title}');
|
||||
|
||||
expect(result.single[0]).toContain('Brandon Sanderson');
|
||||
expect(result.single[0]).toContain('Mistborn');
|
||||
expect(result.single[1]).toContain('Douglas Adams');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildRenamedFilename', () => {
|
||||
const baseVariables: TemplateVariables = {
|
||||
author: 'Brandon Sanderson',
|
||||
title: 'Mistborn: The Final Empire',
|
||||
narrator: 'Michael Kramer',
|
||||
asin: 'B002UZMLXM',
|
||||
year: 2006,
|
||||
};
|
||||
|
||||
it('should build a renamed filename with extension', () => {
|
||||
const result = buildRenamedFilename('{title}', baseVariables, '.m4b');
|
||||
expect(result).toBe('Mistborn The Final Empire.m4b');
|
||||
});
|
||||
|
||||
it('should append index for multi-file scenarios', () => {
|
||||
const result = buildRenamedFilename('{title}', baseVariables, '.mp3', 1);
|
||||
expect(result).toBe('Mistborn The Final Empire - 1.mp3');
|
||||
});
|
||||
|
||||
it('should handle multiple variables', () => {
|
||||
const result = buildRenamedFilename('{author} - {title}', baseVariables, '.m4b');
|
||||
expect(result).toBe('Brandon Sanderson - Mistborn The Final Empire.m4b');
|
||||
});
|
||||
|
||||
it('should handle extension without leading dot', () => {
|
||||
const result = buildRenamedFilename('{title}', baseVariables, 'mp3');
|
||||
expect(result).toBe('Mistborn The Final Empire.mp3');
|
||||
});
|
||||
|
||||
it('should sanitize invalid characters from variable values', () => {
|
||||
const vars: TemplateVariables = {
|
||||
author: 'Author: <Test>',
|
||||
title: 'Title|Book*'
|
||||
};
|
||||
const result = buildRenamedFilename('{author} - {title}', vars, '.m4b');
|
||||
expect(result).not.toContain(':');
|
||||
expect(result).not.toContain('<');
|
||||
expect(result).not.toContain('>');
|
||||
expect(result).not.toContain('|');
|
||||
expect(result).not.toContain('*');
|
||||
});
|
||||
|
||||
it('should strip slashes from conditional block output', () => {
|
||||
const result = buildRenamedFilename('{author}/{title}', baseVariables, '.m4b');
|
||||
expect(result).not.toContain('/');
|
||||
expect(result).not.toContain('\\');
|
||||
});
|
||||
|
||||
it('should handle conditional blocks', () => {
|
||||
const result = buildRenamedFilename('{title} {(year)}', baseVariables, '.m4b');
|
||||
expect(result).toBe('Mistborn The Final Empire (2006).m4b');
|
||||
});
|
||||
|
||||
it('should remove conditional blocks when variable is missing', () => {
|
||||
const vars: TemplateVariables = {
|
||||
author: 'Andy Weir',
|
||||
title: 'Project Hail Mary',
|
||||
};
|
||||
const result = buildRenamedFilename('{title} {(year)}', vars, '.m4b');
|
||||
expect(result).toBe('Project Hail Mary.m4b');
|
||||
});
|
||||
|
||||
it('should handle index appended after conditional blocks', () => {
|
||||
const result = buildRenamedFilename('{title} {(year)}', baseVariables, '.mp3', 5);
|
||||
expect(result).toBe('Mistborn The Final Empire (2006) - 5.mp3');
|
||||
});
|
||||
|
||||
it('should limit very long filenames', () => {
|
||||
const vars: TemplateVariables = {
|
||||
author: 'Author',
|
||||
title: 'A'.repeat(300),
|
||||
};
|
||||
const result = buildRenamedFilename('{title}', vars, '.m4b');
|
||||
// 200 char limit on base name + extension
|
||||
expect(result.length).toBeLessThanOrEqual(204); // 200 + '.m4b'
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user