Compare commits

..

15 Commits

Author SHA1 Message Date
kikootwo 2972297903 Bump package version to 1.0.12
Update package.json version from 1.0.11 to 1.0.12 to publish a new patch release. No other changes were made in this commit.
2026-02-25 11:20:43 -05:00
kikootwo 03f82d4841 File rename templates & admin torrent approval
Add support for admin-driven interactive torrent selection and a file rename/template feature. Integrates an InteractiveTorrentSearchModal into the pending-approval admin UI, adds an admin approve flow that accepts an admin-selected torrent, and surfaces user/admin-selected torrent details in the UI. Introduces fileRenameEnabled and fileRenameTemplate settings (API + UI), persists them to configuration, and clears related caches. Pass renameConfig through the organize/organizeEbook flows and implement renaming in the FileOrganizer (single/multi-file handling). Enhance path-template utilities with conditional block resolution, filename-template validation, mock filename previews, and a buildRenamedFilename helper. Update tests to cover conditional templates and filename preview behavior.
2026-02-25 09:47:57 -05:00
kikootwo 33c2265e56 Use save_path for completed/seeding torrents
Resolve downloadPath using save_path for finished torrents to avoid TempPathEnabled race conditions where content_path can point to a stale temp location. Compute status once, treat 'seeding'/'completed' as finished, and prefer path.join(save_path, name) for those states while still using content_path (or falling back to save_path) for active downloads. Added tests covering multiple qBittorrent states (seeding/stalledUP/pausedUP/stoppedUP/forcedUP/queuedUP/downloading and empty content_path) and imported path in tests.
2026-02-24 02:03:20 -05:00
kikootwo b15a472bab Centralize download client timeout constant
Add DOWNLOAD_CLIENT_TIMEOUT (60000ms) in src/lib/constants/download-timeouts.ts and replace hardcoded 60000ms timeouts across Deluge, Prowlarr, qBittorrent and Transmission integrations. This centralizes the download/API timeout (gives headroom for indexers that enforce ~30s waits) and makes future adjustments easier without changing behavior.
2026-02-24 01:09:58 -05:00
kikootwo 3c680f2f38 Merge pull request #102 from Kikipeuk/ygg_timeout2
Extend the default timeout to add a torrent (Qbit, Transmission, Deluge)
2026-02-24 00:56:37 -05:00
kikootwo 16cd606421 Merge pull request #107 from kikootwo/feature-france-region
Feature france region
2026-02-24 00:53:01 -05:00
kikootwo 40d5363dc4 Fix French stopWords spacing and region name
Trim whitespace in the French stopWords array (add missing space after comma) to keep formatting consistent, and rename AUDIBLE_REGIONS.fr.name from "French" to "France" to better reflect the region label used for the Audible configuration.
2026-02-24 00:51:55 -05:00
kikootwo c138d8e642 Merge pull request #100 from Kikipeuk/french-traduction
Add French as Audible region
2026-02-24 00:40:50 -05:00
root 328fd8392b ygg_timeout2 2026-02-21 14:30:51 +01:00
root 9a460f808d french-Traduction 2026-02-21 13:57:47 +01:00
root c60b6214ce French Traduction 2026-02-21 12:44:56 +01:00
root aff5faaa58 French Traduction 2026-02-21 11:43:06 +01:00
root c43ce7ba8f French Traduction 2026-02-21 11:40:48 +01:00
root f570b87343 French Traduction 2026-02-21 10:48:24 +01:00
root dfa7a11674 French Traduction 2026-02-21 10:43:49 +01:00
24 changed files with 1339 additions and 125 deletions
+1
View File
@@ -33,6 +33,7 @@ Configurable Audible region for accurate metadata matching across different inte
- India (`in`) - `audible.in` (English) - India (`in`) - `audible.in` (English)
- Germany (`de`) - `audible.de` (non-English) - Germany (`de`) - `audible.de` (non-English)
- Spain (`es`) - `audible.es` (non-English) - Spain (`es`) - `audible.es` (non-English)
- French (`fr`) - `audible.fr` (non-English)
**`isEnglish` Flag:** **`isEnglish` Flag:**
- Each region has `isEnglish: boolean` in `AudibleRegionConfig` - Each region has `isEnglish: boolean` in `AudibleRegionConfig`
+1 -1
View File
@@ -271,7 +271,7 @@ src/app/admin/settings/
**PUT /api/admin/settings/audible** **PUT /api/admin/settings/audible**
- Updates Audible region - 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 - No validation required
**PUT /api/admin/settings/prowlarr/indexers** **PUT /api/admin/settings/prowlarr/indexers**
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "readmeabook", "name": "readmeabook",
"version": "1.0.11", "version": "1.0.12",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev",
+157 -70
View File
@@ -13,17 +13,34 @@ import { ActiveDownloadsTable } from './components/ActiveDownloadsTable';
import { RecentRequestsTable } from './components/RecentRequestsTable'; import { RecentRequestsTable } from './components/RecentRequestsTable';
import { ToastProvider, useToast } from '@/components/ui/Toast'; import { ToastProvider, useToast } from '@/components/ui/Toast';
import { ReportedIssuesSection } from './components/ReportedIssuesSection'; import { ReportedIssuesSection } from './components/ReportedIssuesSection';
import { InteractiveTorrentSearchModal } from '@/components/requests/InteractiveTorrentSearchModal';
import { TorrentResult } from '@/lib/utils/ranking-algorithm';
import { formatDistanceToNow } from 'date-fns'; import { formatDistanceToNow } from 'date-fns';
import { useState } from 'react'; 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 { interface PendingApprovalRequest {
id: string; id: string;
createdAt: string; createdAt: string;
type: 'audiobook' | 'ebook'; type: 'audiobook' | 'ebook';
selectedTorrent: SelectedTorrentData | null;
audiobook: { audiobook: {
title: string; title: string;
author: string; author: string;
coverArtUrl: string | null; coverArtUrl: string | null;
audibleAsin: string | null;
}; };
user: { user: {
id: string; 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[] }) { function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest[] }) {
const toast = useToast(); const toast = useToast();
const [loadingStates, setLoadingStates] = useState<Record<string, boolean>>({}); 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) => { const handleApproveRequest = async (requestId: string) => {
setLoadingStates((prev) => ({ ...prev, [requestId]: true })); setLoadingStates((prev) => ({ ...prev, [requestId]: true }));
@@ -47,7 +75,6 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
toast.success('Request approved'); toast.success('Request approved');
// Mutate both pending requests and recent requests caches
await mutate('/api/admin/requests/pending-approval'); await mutate('/api/admin/requests/pending-approval');
await mutate('/api/admin/requests/recent'); await mutate('/api/admin/requests/recent');
await mutate('/api/admin/metrics'); await mutate('/api/admin/metrics');
@@ -72,7 +99,6 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
toast.success('Request denied'); toast.success('Request denied');
// Mutate pending requests cache
await mutate('/api/admin/requests/pending-approval'); await mutate('/api/admin/requests/pending-approval');
await mutate('/api/admin/metrics'); await mutate('/api/admin/metrics');
} catch (error) { } 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 ( return (
<div className="mb-8"> <div className="mb-8">
{/* Section Header */} {/* 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"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{requests.map((request) => { {requests.map((request) => {
const isLoading = loadingStates[request.id] || false; const isLoading = loadingStates[request.id] || false;
const torrent = request.selectedTorrent;
const displayFormat = torrent?.format || torrent?.ebookFormat;
const isAnnasArchive = torrent?.source === 'annas_archive';
return ( return (
<div <div
@@ -205,89 +254,107 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
</div> </div>
</div> </div>
{/* Pre-Selected Release */}
{torrent && torrent.title && (
<div className="mx-4 mb-3 px-3 py-2.5 bg-gray-50 dark:bg-gray-900/60 rounded-lg border border-gray-200 dark:border-gray-700/60">
<div className="flex items-center gap-1.5 mb-1">
<svg className="w-3 h-3 text-gray-400 dark:text-gray-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
</svg>
<span className="text-[10px] font-semibold uppercase tracking-wider text-gray-400 dark:text-gray-500">
User-Selected Release
</span>
</div>
{torrent.infoUrl ? (
<a
href={torrent.infoUrl}
target="_blank"
rel="noopener noreferrer"
className="text-xs font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 transition-colors line-clamp-2 leading-snug"
title={torrent.title}
>
{torrent.title}
</a>
) : (
<p className="text-xs font-medium text-gray-700 dark:text-gray-300 line-clamp-2 leading-snug" title={torrent.title}>
{torrent.title}
</p>
)}
<div className="flex items-center gap-1 mt-1.5 text-[11px] text-gray-500 dark:text-gray-400 flex-wrap">
{isAnnasArchive ? (
<span className="text-orange-600 dark:text-orange-400 font-medium">Anna&apos;s Archive</span>
) : torrent.indexer ? (
<span>{torrent.indexer}</span>
) : null}
{torrent.size && torrent.size > 0 ? (
<>
<span className="text-gray-300 dark:text-gray-600 select-none">&middot;</span>
<span>{formatTorrentSize(torrent.size)}</span>
</>
) : null}
{displayFormat ? (
<>
<span className="text-gray-300 dark:text-gray-600 select-none">&middot;</span>
<span className="px-1 py-px text-[10px] font-semibold uppercase tracking-wide rounded bg-purple-100 dark:bg-purple-500/15 text-purple-700 dark:text-purple-300">
{displayFormat}
</span>
</>
) : null}
{torrent.protocol === 'usenet' ? (
<>
<span className="text-gray-300 dark:text-gray-600 select-none">&middot;</span>
<span className="text-sky-600 dark:text-sky-400 font-medium">NZB</span>
</>
) : torrent.seeders !== undefined && torrent.seeders !== null ? (
<>
<span className="text-gray-300 dark:text-gray-600 select-none">&middot;</span>
<span className="text-emerald-600 dark:text-emerald-400">{torrent.seeders} seeds</span>
</>
) : null}
{torrent.score !== undefined && torrent.score !== null ? (
<>
<span className="text-gray-300 dark:text-gray-600 select-none">&middot;</span>
<span className="font-medium">Score {Math.round(torrent.score)}</span>
</>
) : null}
</div>
</div>
)}
{/* Action Buttons */} {/* 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"> <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 <button
onClick={() => handleApproveRequest(request.id)} onClick={() => handleApproveRequest(request.id)}
disabled={isLoading} 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 ? ( {isLoading ? <LoadingSpinner /> : (
<svg <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
className="animate-spin h-4 w-4" <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
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"
/>
</svg> </svg>
)} )}
<span>Approve</span> <span>Approve</span>
</button> </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 <button
onClick={() => handleDenyRequest(request.id)} onClick={() => handleDenyRequest(request.id)}
disabled={isLoading} 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 ? ( {isLoading ? <LoadingSpinner /> : (
<svg <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
className="animate-spin h-4 w-4" <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
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"
/>
</svg> </svg>
)} )}
<span>Deny</span> <span>Deny</span>
@@ -297,6 +364,26 @@ function PendingApprovalSection({ requests }: { requests: PendingApprovalRequest
); );
})} })}
</div> </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> </div>
); );
} }
+2
View File
@@ -100,6 +100,8 @@ export interface PathsSettings {
ebookPathTemplate?: string; ebookPathTemplate?: string;
metadataTaggingEnabled: boolean; metadataTaggingEnabled: boolean;
chapterMergingEnabled: boolean; chapterMergingEnabled: boolean;
fileRenameEnabled: boolean;
fileRenameTemplate?: string;
} }
/** /**
@@ -10,7 +10,7 @@ import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input'; import { Input } from '@/components/ui/Input';
import { usePathsSettings } from './usePathsSettings'; import { usePathsSettings } from './usePathsSettings';
import type { PathsSettings } from '../../lib/types'; 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 { interface PathsTabProps {
paths: PathsSettings; paths: PathsSettings;
@@ -24,6 +24,13 @@ interface TemplatePreview {
previewPaths?: string[]; previewPaths?: string[];
} }
interface FilenamePreview {
isValid: boolean;
error?: string;
single?: string[];
multi?: string[];
}
export function PathsTab({ paths, onChange, onValidationChange }: PathsTabProps) { export function PathsTab({ paths, onChange, onValidationChange }: PathsTabProps) {
const { testing, testResult, updatePath, testPaths } = usePathsSettings({ const { testing, testResult, updatePath, testPaths } = usePathsSettings({
paths, paths,
@@ -73,6 +80,34 @@ export function PathsTab({ paths, onChange, onValidationChange }: PathsTabProps)
} }
}, [paths.ebookPathTemplate]); }, [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 audiobookTemplate = paths.audiobookPathTemplate || '{author}/{title} {asin}';
const ebookTemplate = paths.ebookPathTemplate || '{author}/{title} {asin}'; const ebookTemplate = paths.ebookPathTemplate || '{author}/{title} {asin}';
const ebookMatchesAudiobook = ebookTemplate === audiobookTemplate; const ebookMatchesAudiobook = ebookTemplate === audiobookTemplate;
@@ -218,6 +253,83 @@ export function PathsTab({ paths, onChange, onValidationChange }: PathsTabProps)
)} )}
</div> </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) */} {/* 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"> <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"> <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>
</div> </div>
{/* Conditional Syntax Help */}
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4">
<h3 className="text-sm font-semibold text-amber-900 dark:text-amber-100 mb-2">
Conditional Syntax
</h3>
<p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
Wrap text around a variable in <code className="text-amber-700 dark:text-amber-300 font-mono">{'{ }'}</code> to
include that text only when the variable has a value. If the variable is empty, the entire block is removed.
</p>
<div className="text-sm font-mono bg-white dark:bg-gray-900 rounded px-3 py-2 border border-amber-100 dark:border-amber-900">
<div className="text-gray-700 dark:text-gray-300">
<code className="text-amber-700 dark:text-amber-300">{'{Book seriesPart - }'}</code>
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
With value: <span className="text-green-700 dark:text-green-400">Book 1 - </span>
&nbsp;&bull;&nbsp;
Without value: <span className="text-red-700 dark:text-red-400">(removed)</span>
</div>
</div>
</div>
{/* Metadata Tagging Toggle */} {/* 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="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"> <div className="flex items-start gap-4">
@@ -14,6 +14,7 @@ const logger = RMABLogger.create('API.Admin.Requests.Approve');
const ApprovalActionSchema = z.object({ const ApprovalActionSchema = z.object({
action: z.enum(['approve', 'deny']), action: z.enum(['approve', 'deny']),
selectedTorrent: z.any().optional(),
}); });
/** /**
@@ -37,8 +38,8 @@ export async function POST(
const { id } = await params; const { id } = await params;
const body = await request.json(); const body = await request.json();
// Validate action // Validate action and optional admin-selected torrent
const { action } = ApprovalActionSchema.parse(body); const { action, selectedTorrent: adminSelectedTorrent } = ApprovalActionSchema.parse(body);
// Fetch the request // Fetch the request
const existingRequest = await prisma.request.findUnique({ const existingRequest = await prisma.request.findUnique({
@@ -78,12 +79,15 @@ export async function POST(
const jobQueue = getJobQueueService(); const jobQueue = getJobQueueService();
const isEbookRequest = existingRequest.type === 'ebook'; const isEbookRequest = existingRequest.type === 'ebook';
// Check if request has a pre-selected torrent (from interactive search) // Use admin-provided torrent (from admin interactive search) or fall back to user's pre-selected torrent
if (existingRequest.selectedTorrent) { const effectiveTorrent = adminSelectedTorrent || existingRequest.selectedTorrent;
const selectedTorrent = existingRequest.selectedTorrent as any;
// User pre-selected a specific torrent - download that torrent directly if (effectiveTorrent) {
logger.info(`Request ${id} has pre-selected torrent, starting download`, { 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, requestId: id,
userId: existingRequest.userId, userId: existingRequest.userId,
adminId: req.user.sub, 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.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, requestId: id,
userId: updatedRequest.userId, userId: updatedRequest.userId,
audiobookTitle: existingRequest.audiobook.title, audiobookTitle: existingRequest.audiobook.title,
adminId: req.user.sub, adminId: req.user.sub,
type: existingRequest.type, type: existingRequest.type,
torrentSource,
}); });
return NextResponse.json({ return NextResponse.json({
success: true, 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, request: updatedRequest,
}); });
} else { } else {
+29 -1
View File
@@ -15,7 +15,7 @@ export async function PUT(request: NextRequest) {
return requireAuth(request, async (req: AuthenticatedRequest) => { return requireAuth(request, async (req: AuthenticatedRequest) => {
return requireAdmin(req, async () => { return requireAdmin(req, async () => {
try { 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) { if (!downloadDir || !mediaDir) {
return NextResponse.json( 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'); logger.info('Paths settings updated');
// Clear config cache for all updated keys so services get fresh values // 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('ebook_path_template');
configService.clearCache('metadata_tagging_enabled'); configService.clearCache('metadata_tagging_enabled');
configService.clearCache('chapter_merging_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 // Invalidate all download client singletons to force reload of download_dir
const { invalidateDownloadClientManager } = await import('@/lib/services/download-client-manager.service'); const { invalidateDownloadClientManager } = await import('@/lib/services/download-client-manager.service');
+2
View File
@@ -128,6 +128,8 @@ export async function GET(request: NextRequest) {
ebookPathTemplate: configMap.get('ebook_path_template') || configMap.get('audiobook_path_template') || '{author}/{title} {asin}', ebookPathTemplate: configMap.get('ebook_path_template') || configMap.get('audiobook_path_template') || '{author}/{title} {asin}',
metadataTaggingEnabled: configMap.get('metadata_tagging_enabled') === 'true', metadataTaggingEnabled: configMap.get('metadata_tagging_enabled') === 'true',
chapterMergingEnabled: configMap.get('chapter_merging_enabled') === 'true', chapterMergingEnabled: configMap.get('chapter_merging_enabled') === 'true',
fileRenameEnabled: configMap.get('file_rename_enabled') === 'true',
fileRenameTemplate: configMap.get('file_rename_template') || '{title}',
}, },
ebook: { ebook: {
// New granular source toggles (with migration from legacy ebook_sidecar_enabled) // New granular source toggles (with migration from legacy ebook_sidecar_enabled)
@@ -67,8 +67,8 @@ export async function POST(
); );
} }
// Check if request is awaiting approval // Check if request is awaiting approval (admins can still search to override the user's selection)
if (requestRecord.status === 'awaiting_approval') { if (requestRecord.status === 'awaiting_approval' && req.user.role !== 'admin') {
return NextResponse.json( return NextResponse.json(
{ error: 'AwaitingApproval', message: 'This request is awaiting admin approval. You cannot search for torrents until it is approved.' }, { error: 'AwaitingApproval', message: 'This request is awaiting admin approval. You cannot search for torrents until it is approved.' },
{ status: 403 } { status: 403 }
@@ -38,6 +38,7 @@ interface InteractiveTorrentSearchModalProps {
onSuccess?: () => void; onSuccess?: () => void;
searchMode?: 'audiobook' | 'ebook'; // Search mode - defaults to audiobook searchMode?: 'audiobook' | 'ebook'; // Search mode - defaults to audiobook
replaceIssueId?: string; // Optional - when set, confirm handler calls replace endpoint instead 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 // Format relative time from publish date
@@ -90,6 +91,7 @@ export function InteractiveTorrentSearchModal({
onSuccess, onSuccess,
searchMode = 'audiobook', searchMode = 'audiobook',
replaceIssueId, replaceIssueId,
onConfirm,
}: InteractiveTorrentSearchModalProps) { }: InteractiveTorrentSearchModalProps) {
// Hooks for existing audiobook request flow // Hooks for existing audiobook request flow
const { searchTorrents: searchByRequestId, isLoading: isSearchingByRequest, error: searchByRequestError } = useInteractiveSearch(); 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 [results, setResults] = useState<(RankedTorrent & { qualityScore?: number; source?: string; ebookFormat?: string })[]>([]);
const [confirmTorrent, setConfirmTorrent] = useState<TorrentResult | null>(null); const [confirmTorrent, setConfirmTorrent] = useState<TorrentResult | null>(null);
const [searchTitle, setSearchTitle] = useState(audiobook.title); const [searchTitle, setSearchTitle] = useState(audiobook.title);
const [isCustomConfirming, setIsCustomConfirming] = useState(false);
const [mounted, setMounted] = useState(false); const [mounted, setMounted] = useState(false);
// Stable close handler via ref // Stable close handler via ref
@@ -130,11 +133,13 @@ export function InteractiveTorrentSearchModal({
const isSearching = isEbookMode const isSearching = isEbookMode
? (useAsinMode ? isSearchingEbooksByAsin : isSearchingEbooks) ? (useAsinMode ? isSearchingEbooksByAsin : isSearchingEbooks)
: (hasRequestId ? isSearchingByRequest : isSearchingByAudiobook); : (hasRequestId ? isSearchingByRequest : isSearchingByAudiobook);
const isDownloading = replaceIssueId const isDownloading = isCustomConfirming
? isReplacing ? true
: isEbookMode : replaceIssueId
? (useAsinMode ? isSelectingEbookByAsin : isSelectingEbook) ? isReplacing
: (hasRequestId ? isSelectingTorrent : isRequestingWithTorrent); : isEbookMode
? (useAsinMode ? isSelectingEbookByAsin : isSelectingEbook)
: (hasRequestId ? isSelectingTorrent : isRequestingWithTorrent);
const error = replaceIssueId const error = replaceIssueId
? (replaceError || (hasRequestId ? searchByRequestError : searchByAudiobookError)) ? (replaceError || (hasRequestId ? searchByRequestError : searchByAudiobookError))
: isEbookMode : isEbookMode
@@ -218,7 +223,11 @@ export function InteractiveTorrentSearchModal({
const handleConfirmDownload = async () => { const handleConfirmDownload = async () => {
if (!confirmTorrent) return; if (!confirmTorrent) return;
try { 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 // Reported issue replacement flow
await replaceWithTorrent(replaceIssueId, confirmTorrent); await replaceWithTorrent(replaceIssueId, confirmTorrent);
} else if (isEbookMode) { } else if (isEbookMode) {
@@ -241,6 +250,8 @@ export function InteractiveTorrentSearchModal({
} catch (err) { } catch (err) {
console.error('Failed to download:', err); console.error('Failed to download:', err);
setConfirmTorrent(null); setConfirmTorrent(null);
} finally {
setIsCustomConfirming(false);
} }
}; };
+10
View File
@@ -0,0 +1,10 @@
/**
* Component: Download Client Timeout Constants
* Documentation: documentation/phase3/download-clients.md
*
* Some indexers (e.g. YGGtorrent) enforce a ~30s wait before allowing
* .torrent file downloads. 60s gives sufficient headroom.
*/
/** Timeout for download client API calls and .torrent file fetches (ms) */
export const DOWNLOAD_CLIENT_TIMEOUT = 60000;
+35 -1
View File
@@ -16,7 +16,7 @@ import type { AudibleRegion } from '../types/audible';
// Types // Types
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
export type SupportedLanguage = 'en' | 'de' | 'es'; export type SupportedLanguage = 'en' | 'de' | 'es' | 'fr';
export interface ScrapingConfig { export interface ScrapingConfig {
/** Audible locale query-param value (e.g. 'english', 'deutsch') */ /** 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 // Lookup Maps
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -178,6 +210,7 @@ export const LANGUAGE_CONFIGS: Record<SupportedLanguage, LanguageConfig> = {
en: ENGLISH_CONFIG, en: ENGLISH_CONFIG,
de: GERMAN_CONFIG, de: GERMAN_CONFIG,
es: SPANISH_CONFIG, es: SPANISH_CONFIG,
fr: FRENCH_CONFIG,
}; };
/** /**
@@ -192,6 +225,7 @@ export const REGION_LANGUAGE_MAP: Record<AudibleRegion, SupportedLanguage> = {
in: 'en', in: 'en',
de: 'de', de: 'de',
es: 'es', es: 'es',
fr: 'fr',
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
+4 -3
View File
@@ -6,6 +6,7 @@
import axios, { AxiosInstance } from 'axios'; import axios, { AxiosInstance } from 'axios';
import https from 'https'; import https from 'https';
import path from 'path'; import path from 'path';
import { DOWNLOAD_CLIENT_TIMEOUT } from '../constants/download-timeouts';
import * as parseTorrentModule from 'parse-torrent'; import * as parseTorrentModule from 'parse-torrent';
import { RMABLogger } from '../utils/logger'; import { RMABLogger } from '../utils/logger';
import { PathMapper, PathMappingConfig } from '../utils/path-mapper'; import { PathMapper, PathMappingConfig } from '../utils/path-mapper';
@@ -49,7 +50,7 @@ export class DelugeService implements IDownloadClient {
? new https.Agent({ rejectUnauthorized: false }) : undefined; ? new https.Agent({ rejectUnauthorized: false }) : undefined;
if (httpsAgent) logger.info('[Deluge] SSL certificate verification disabled'); 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 */ /** JSON-RPC call with automatic re-authentication on auth failure */
@@ -190,7 +191,7 @@ export class DelugeService implements IDownloadClient {
try { try {
torrentResponse = await axios.get(torrentUrl, { torrentResponse = await axios.get(torrentUrl, {
responseType: 'arraybuffer', maxRedirects: 0, 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) { if (torrentResponse.data.length > 0) {
const magnetMatch = torrentResponse.data.toString().match(/^magnet:\?[^\s]+$/); const magnetMatch = torrentResponse.data.toString().match(/^magnet:\?[^\s]+$/);
@@ -203,7 +204,7 @@ export class DelugeService implements IDownloadClient {
const loc = error.response.headers['location']; const loc = error.response.headers['location'];
if (loc?.startsWith('magnet:')) return this.addMagnetLink(loc, category, options); if (loc?.startsWith('magnet:')) return this.addMagnetLink(loc, category, options);
if (loc?.startsWith('http://') || loc?.startsWith('https://')) { 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'); } catch { throw new Error('Failed to download torrent file after redirect'); }
} else { throw new Error(`Invalid redirect location: ${loc}`); } } else { throw new Error(`Invalid redirect location: ${loc}`); }
} else { throw new Error(`Failed to download torrent: HTTP ${status}`); } } else { throw new Error(`Failed to download torrent: HTTP ${status}`); }
+3 -2
View File
@@ -5,6 +5,7 @@
import axios, { AxiosInstance } from 'axios'; import axios, { AxiosInstance } from 'axios';
import { XMLParser } from 'fast-xml-parser'; import { XMLParser } from 'fast-xml-parser';
import { DOWNLOAD_CLIENT_TIMEOUT } from '../constants/download-timeouts';
import { TorrentResult } from '../utils/ranking-algorithm'; import { TorrentResult } from '../utils/ranking-algorithm';
import { RMABLogger } from '../utils/logger'; import { RMABLogger } from '../utils/logger';
@@ -87,7 +88,7 @@ export class ProwlarrService {
headers: { headers: {
'X-Api-Key': this.apiKey, '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: { paramsSerializer: {
serialize: (params) => { serialize: (params) => {
// Custom serializer to handle arrays correctly for Prowlarr API // Custom serializer to handle arrays correctly for Prowlarr API
@@ -314,7 +315,7 @@ export class ProwlarrService {
limit: 100, limit: 100,
extended: 1, extended: 1,
}, },
timeout: 60000, timeout: DOWNLOAD_CLIENT_TIMEOUT,
responseType: 'text', // Get XML as text responseType: 'text', // Get XML as text
}); });
+18 -5
View File
@@ -6,6 +6,7 @@
import axios, { AxiosInstance } from 'axios'; import axios, { AxiosInstance } from 'axios';
import https from 'https'; import https from 'https';
import path from 'path'; import path from 'path';
import { DOWNLOAD_CLIENT_TIMEOUT } from '../constants/download-timeouts';
import * as parseTorrentModule from 'parse-torrent'; import * as parseTorrentModule from 'parse-torrent';
import FormData from 'form-data'; import FormData from 'form-data';
import { RMABLogger } from '../utils/logger'; import { RMABLogger } from '../utils/logger';
@@ -140,7 +141,7 @@ export class QBittorrentService implements IDownloadClient {
this.client = axios.create({ this.client = axios.create({
baseURL: `${this.baseUrl}/api/v2`, baseURL: `${this.baseUrl}/api/v2`,
timeout: 30000, timeout: DOWNLOAD_CLIENT_TIMEOUT,
httpsAgent: this.httpsAgent, httpsAgent: this.httpsAgent,
// Support nginx/Apache reverse proxy with HTTP Basic Auth // Support nginx/Apache reverse proxy with HTTP Basic Auth
auth: { auth: {
@@ -352,7 +353,7 @@ export class QBittorrentService implements IDownloadClient {
responseType: 'arraybuffer', responseType: 'arraybuffer',
maxRedirects: 0, maxRedirects: 0,
validateStatus: (status) => status >= 200 && status < 300, // Only 2xx is success 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`); logger.info(` Got 2xx response, size=${torrentResponse.data.length} bytes`);
@@ -394,7 +395,7 @@ export class QBittorrentService implements IDownloadClient {
try { try {
torrentResponse = await axios.get(location, { torrentResponse = await axios.get(location, {
responseType: 'arraybuffer', responseType: 'arraybuffer',
timeout: 30000, timeout: DOWNLOAD_CLIENT_TIMEOUT,
maxRedirects: 5, maxRedirects: 5,
}); });
logger.info(` After following redirect: size=${torrentResponse.data.length} bytes`); logger.info(` After following redirect: size=${torrentResponse.data.length} bytes`);
@@ -1088,17 +1089,29 @@ export class QBittorrentService implements IDownloadClient {
* Map a TorrentInfo object to the unified DownloadInfo format. * Map a TorrentInfo object to the unified DownloadInfo format.
*/ */
protected mapTorrentToDownloadInfo(torrent: TorrentInfo): DownloadInfo { protected mapTorrentToDownloadInfo(torrent: TorrentInfo): DownloadInfo {
const status = this.mapStateToDownloadStatus(torrent.state);
// For completed/seeding torrents, always use save_path (the configured final destination)
// rather than content_path. When TempPathEnabled is active in qBittorrent, there is a race
// window where the torrent state transitions to uploading/seeding before the file move from
// the temp/incomplete directory to save_path finishes — content_path still references the
// stale temp location during this window, causing downstream ENOENT failures.
const isFinished = status === 'seeding' || status === 'completed';
const downloadPath = isFinished
? path.join(torrent.save_path, torrent.name)
: (torrent.content_path || path.join(torrent.save_path, torrent.name));
return { return {
id: torrent.hash, id: torrent.hash,
name: torrent.name, name: torrent.name,
size: torrent.size, size: torrent.size,
bytesDownloaded: torrent.downloaded, bytesDownloaded: torrent.downloaded,
progress: torrent.progress, progress: torrent.progress,
status: this.mapStateToDownloadStatus(torrent.state), status,
downloadSpeed: torrent.dlspeed, downloadSpeed: torrent.dlspeed,
eta: torrent.eta, eta: torrent.eta,
category: torrent.category, 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, completedAt: torrent.completion_on > 0 ? new Date(torrent.completion_on * 1000) : undefined,
seedingTime: torrent.seeding_time, seedingTime: torrent.seeding_time,
ratio: torrent.ratio, ratio: torrent.ratio,
+4 -3
View File
@@ -6,6 +6,7 @@
import axios, { AxiosInstance } from 'axios'; import axios, { AxiosInstance } from 'axios';
import https from 'https'; import https from 'https';
import path from 'path'; import path from 'path';
import { DOWNLOAD_CLIENT_TIMEOUT } from '../constants/download-timeouts';
import * as parseTorrentModule from 'parse-torrent'; import * as parseTorrentModule from 'parse-torrent';
import { RMABLogger } from '../utils/logger'; import { RMABLogger } from '../utils/logger';
import { PathMapper, PathMappingConfig } from '../utils/path-mapper'; import { PathMapper, PathMappingConfig } from '../utils/path-mapper';
@@ -106,7 +107,7 @@ export class TransmissionService implements IDownloadClient {
this.client = axios.create({ this.client = axios.create({
baseURL: this.baseUrl, baseURL: this.baseUrl,
timeout: 30000, timeout: DOWNLOAD_CLIENT_TIMEOUT,
httpsAgent: this.httpsAgent, httpsAgent: this.httpsAgent,
}); });
} }
@@ -274,7 +275,7 @@ export class TransmissionService implements IDownloadClient {
responseType: 'arraybuffer', responseType: 'arraybuffer',
maxRedirects: 0, maxRedirects: 0,
validateStatus: (status) => status >= 200 && status < 300, validateStatus: (status) => status >= 200 && status < 300,
timeout: 30000, timeout: DOWNLOAD_CLIENT_TIMEOUT,
}); });
// Check if response body is a magnet link // Check if response body is a magnet link
@@ -302,7 +303,7 @@ export class TransmissionService implements IDownloadClient {
try { try {
torrentResponse = await axios.get(location, { torrentResponse = await axios.get(location, {
responseType: 'arraybuffer', responseType: 'arraybuffer',
timeout: 30000, timeout: DOWNLOAD_CLIENT_TIMEOUT,
maxRedirects: 5, maxRedirects: 5,
}); });
} catch { } catch {
+29 -3
View File
@@ -128,7 +128,19 @@ export async function processOrganizeFiles(payload: OrganizeFilesPayload): Promi
}); });
const template = templateConfig?.value || '{author}/{title} {asin}'; 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( const result = await organizer.organize(
downloadPath, downloadPath,
{ {
@@ -142,7 +154,8 @@ export async function processOrganizeFiles(payload: OrganizeFilesPayload): Promi
seriesPart: audiobook.seriesPart || undefined, seriesPart: audiobook.seriesPart || undefined,
}, },
template, template,
jobId ? { jobId, context: 'FileOrganizer' } : undefined jobId ? { jobId, context: 'FileOrganizer' } : undefined,
renameConfig
); );
if (!result.success) { 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) // 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) // Pass all metadata that could be used in path templates (same as audiobooks)
const result = await organizer.organizeEbook( const result = await organizer.organizeEbook(
@@ -571,7 +596,8 @@ async function processEbookOrganization(
}, },
template, template,
jobId ? { jobId, context: 'FileOrganizer.Ebook' } : undefined, jobId ? { jobId, context: 'FileOrganizer.Ebook' } : undefined,
isIndexerDownload isIndexerDownload,
ebookRenameConfig
); );
// Clean up fixed EPUB temp file after organization (regardless of success) // Clean up fixed EPUB temp file after organization (regardless of success)
+8 -1
View File
@@ -5,7 +5,7 @@
import type { SupportedLanguage } from '../constants/language-config'; 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 { export interface AudibleRegionConfig {
code: AudibleRegion; code: AudibleRegion;
@@ -64,6 +64,13 @@ export const AUDIBLE_REGIONS: Record<AudibleRegion, AudibleRegionConfig> = {
baseUrl: 'https://www.audible.es', baseUrl: 'https://www.audible.es',
audnexusParam: 'es', audnexusParam: 'es',
language: 'es', language: 'es',
},
fr: {
code: 'fr',
name: 'France',
baseUrl: 'https://www.audible.fr',
audnexusParam: 'fr',
language: 'fr',
} }
}; };
+57 -7
View File
@@ -20,7 +20,7 @@ import {
checkDiskSpace, checkDiskSpace,
} from './chapter-merger'; } from './chapter-merger';
import { prisma } from '../db'; 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'; import { AUDIO_EXTENSIONS } from '../constants/audio-formats';
export interface AudiobookMetadata { export interface AudiobookMetadata {
@@ -77,7 +77,8 @@ export class FileOrganizer {
downloadPath: string, downloadPath: string,
audiobook: AudiobookMetadata, audiobook: AudiobookMetadata,
template: string, template: string,
loggerConfig?: LoggerConfig loggerConfig?: LoggerConfig,
renameConfig?: { enabled: boolean; template: string }
): Promise<OrganizationResult> { ): Promise<OrganizationResult> {
// Create logger if config provided // Create logger if config provided
const logger = loggerConfig ? RMABLogger.forJob(loggerConfig.jobId, loggerConfig.context) : null; const logger = loggerConfig ? RMABLogger.forJob(loggerConfig.jobId, loggerConfig.context) : null;
@@ -294,8 +295,17 @@ export class FileOrganizer {
// Create target directory // Create target directory
await fs.mkdir(targetPath, { recursive: true }); 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) // 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) // Handle merged files (absolute paths) vs original files (relative paths)
const isAbsolutePath = path.isAbsolute(audioFile); const isAbsolutePath = path.isAbsolute(audioFile);
const originalSourcePath = isAbsolutePath const originalSourcePath = isAbsolutePath
@@ -303,7 +313,30 @@ export class FileOrganizer {
: isFile : isFile
? downloadPath ? downloadPath
: path.join(downloadPath, audioFile); : 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); const targetFilePath = path.join(targetPath, filename);
// Check if we have a tagged version of this file // 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 }, metadata: { title: string; author: string; narrator?: string; asin?: string; year?: number; series?: string; seriesPart?: string },
template: string, template: string,
loggerConfig?: LoggerConfig, loggerConfig?: LoggerConfig,
isIndexerDownload: boolean = false isIndexerDownload: boolean = false,
renameConfig?: { enabled: boolean; template: string }
): Promise<EbookOrganizationResult> { ): Promise<EbookOrganizationResult> {
const logger = loggerConfig ? RMABLogger.forJob(loggerConfig.jobId, loggerConfig.context) : null; const logger = loggerConfig ? RMABLogger.forJob(loggerConfig.jobId, loggerConfig.context) : null;
@@ -739,9 +773,25 @@ export class FileOrganizer {
// Create target directory // Create target directory
await fs.mkdir(targetDir, { recursive: true }); 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 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); const targetPath = path.join(targetDir, targetFilename);
// Check if target already exists // Check if target already exists
+299 -6
View File
@@ -68,6 +68,81 @@ function sanitizePath(name: string): string {
); );
} }
/**
* Find valid template variable names within arbitrary content text.
* Sorts by length descending to prevent substring false matches
* (e.g., 'seriesPart' matched before 'series').
* Uses word-boundary detection to avoid matching variable names
* that are substrings of other words.
*/
function findVariablesInContent(content: string): string[] {
const sortedVars = [...VALID_VARIABLES].sort((a, b) => b.length - a.length);
const found: string[] = [];
for (const varName of sortedVars) {
const regex = new RegExp(`(?<![a-zA-Z0-9])${varName}(?![a-zA-Z0-9])`);
if (regex.test(content)) {
found.push(varName);
}
}
return found;
}
/**
* Resolve conditional blocks in the template.
* A conditional block is {literal text varName more text} where the entire
* content is rendered only if ALL variables inside have non-empty values.
* If any variable is empty/missing, the entire block is removed.
*
* Simple variable references like {author} are left untouched for the
* existing substitution logic to handle.
*
* Must run after escaped-brace replacement and before simple variable substitution.
*/
function resolveConditionalBlocks(
template: string,
variables: TemplateVariables
): string {
return template.replace(/\{([^}]+)\}/g, (match, content: string) => {
// If content is exactly a valid variable name, skip (leave for simple substitution)
if (VALID_VARIABLES.includes(content)) {
return match;
}
// Find variables in the content
const foundVars = findVariablesInContent(content);
// If no variables found, leave as-is (validation will catch it)
if (foundVars.length === 0) {
return match;
}
// Check if all found variables have non-empty values
const allPresent = foundVars.every(varName => {
const value = variables[varName as keyof TemplateVariables];
return value !== undefined && value !== null && String(value).trim() !== '';
});
if (!allPresent) {
return '';
}
// Substitute variables within the content, output rest as literal text
// Sort by length descending to prevent substring false matches
let result = content;
const sortedVars = [...foundVars].sort((a, b) => b.length - a.length);
for (const varName of sortedVars) {
const value = variables[varName as keyof TemplateVariables];
const sanitizedValue = sanitizePath(String(value).trim());
const regex = new RegExp(`(?<![a-zA-Z0-9])${varName}(?![a-zA-Z0-9])`, 'g');
result = result.replace(regex, sanitizedValue);
}
return result;
});
}
/** /**
* Substitute template variables with actual values * Substitute template variables with actual values
* *
@@ -99,6 +174,9 @@ export function substituteTemplate(
// so they survive the variable substitution and path cleanup steps // so they survive the variable substitution and path cleanup steps
result = result.replace(/\\\{/g, LBRACE_PLACEHOLDER).replace(/\\\}/g, RBRACE_PLACEHOLDER); result = result.replace(/\\\{/g, LBRACE_PLACEHOLDER).replace(/\\\}/g, RBRACE_PLACEHOLDER);
// Resolve conditional blocks before simple variable substitution
result = resolveConditionalBlocks(result, variables);
// Substitute each variable // Substitute each variable
for (const key of VALID_VARIABLES) { for (const key of VALID_VARIABLES) {
const value = variables[key as keyof TemplateVariables]; const value = variables[key as keyof TemplateVariables];
@@ -187,21 +265,47 @@ export function validateTemplate(template: string): ValidationResult {
if (variableMatches) { if (variableMatches) {
for (const match of 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 { return {
valid: false, 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; let templateWithoutVars = templateWithoutEscapedBraces;
for (const varName of VALID_VARIABLES) { if (variableMatches) {
templateWithoutVars = templateWithoutVars.replace(new RegExp(`\\{${varName}\\}`, 'g'), ''); for (const match of variableMatches) {
templateWithoutVars = templateWithoutVars.replace(match, '');
}
} }
// Check for invalid characters outside of variables // Check for invalid characters outside of variables
@@ -286,3 +390,192 @@ export function generateMockPreviews(template: string): string[] {
export function getValidVariables(): string[] { export function getValidVariables(): string[] {
return [...VALID_VARIABLES]; 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 -1
View File
@@ -433,7 +433,7 @@ describe('Setup test routes', () => {
expect(payload.success).toBe(true); expect(payload.success).toBe(true);
expect(payload.template).toBeDefined(); expect(payload.template).toBeDefined();
expect(payload.template.isValid).toBe(false); 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(); expect(payload.template.previewPaths).toBeUndefined();
}); });
@@ -3,6 +3,7 @@
* Documentation: documentation/phase3/qbittorrent.md * Documentation: documentation/phase3/qbittorrent.md
*/ */
import path from 'path';
import { beforeEach, describe, expect, it, vi } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
import { QBittorrentService, getQBittorrentService, invalidateQBittorrentService } from '@/lib/integrations/qbittorrent.service'; import { QBittorrentService, getQBittorrentService, invalidateQBittorrentService } from '@/lib/integrations/qbittorrent.service';
@@ -328,6 +329,164 @@ describe('QBittorrentService', () => {
}); });
}); });
describe('downloadPath resolution (TempPathEnabled race condition fix)', () => {
it('uses save_path for seeding torrents even when content_path points to temp dir', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=temppath';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
dlspeed: 0, upspeed: 5000, downloaded: 1000, uploaded: 500,
eta: 0, state: 'uploading', category: 'readmeabook', tags: '',
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
completion_on: 1700000000, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info).not.toBeNull();
expect(info!.status).toBe('seeding');
// Must use save_path + name, NOT the stale content_path
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
expect(info!.downloadPath).not.toContain('incomplete');
});
it('uses save_path for stalledUP torrents (completed, stalled on upload)', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=stalledup';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
dlspeed: 0, upspeed: 0, downloaded: 1000, uploaded: 200,
eta: 0, state: 'stalledUP', category: 'readmeabook', tags: '',
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
completion_on: 1700000000, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info!.status).toBe('seeding');
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
});
it('uses save_path for pausedUP torrents (completed, paused on upload)', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=pausedup2';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
dlspeed: 0, upspeed: 0, downloaded: 1000, uploaded: 0,
eta: 0, state: 'pausedUP', category: 'readmeabook', tags: '',
save_path: '/data/torrents/readmeabook/', content_path: '/tmp/incomplete/Audiobook',
completion_on: 1700000000, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info!.status).toBe('seeding');
expect(info!.downloadPath).toBe(path.join('/data/torrents/readmeabook/', 'Audiobook'));
});
it('uses save_path for stoppedUP torrents (qBittorrent v5.x completed)', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=stoppedup2';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
dlspeed: 0, upspeed: 0, downloaded: 1000, uploaded: 100,
eta: 0, state: 'stoppedUP', category: 'readmeabook', tags: '',
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
completion_on: 1700000000, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info!.status).toBe('seeding');
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
});
it('uses content_path for actively downloading torrents', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=downloading';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 0.5,
dlspeed: 5000, upspeed: 0, downloaded: 500, uploaded: 0,
eta: 100, state: 'downloading', category: 'readmeabook', tags: '',
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
completion_on: 0, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info!.status).toBe('downloading');
// During download, content_path is used (points to where files currently are)
expect(info!.downloadPath).toBe('/incomplete/Audiobook');
});
it('falls back to save_path + name when content_path is empty during download', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=nocontent';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 0.3,
dlspeed: 1000, upspeed: 0, downloaded: 300, uploaded: 0,
eta: 700, state: 'downloading', category: 'readmeabook', tags: '',
save_path: '/downloads/', content_path: '',
completion_on: 0, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info!.status).toBe('downloading');
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
});
it('uses save_path for forcedUP torrents (force-resumed seeding)', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=forcedup2';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
dlspeed: 0, upspeed: 10000, downloaded: 1000, uploaded: 2000,
eta: 0, state: 'forcedUP', category: 'readmeabook', tags: '',
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
completion_on: 1700000000, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info!.status).toBe('seeding');
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
});
it('uses save_path for queuedUP torrents (completed, queued for upload)', async () => {
const service = new QBittorrentService('http://qb', 'user', 'pass');
(service as any).cookie = 'SID=queuedup';
clientMock.get.mockResolvedValueOnce({
data: [{
hash: 'abc123', name: 'Audiobook', size: 1000, progress: 1.0,
dlspeed: 0, upspeed: 0, downloaded: 1000, uploaded: 0,
eta: 0, state: 'queuedUP', category: 'readmeabook', tags: '',
save_path: '/downloads/', content_path: '/incomplete/Audiobook',
completion_on: 1700000000, added_on: 1699000000,
}],
});
const info = await service.getDownload('abc123');
expect(info!.status).toBe('seeding');
expect(info!.downloadPath).toBe(path.join('/downloads/', 'Audiobook'));
});
});
it('authenticates and stores a session cookie', async () => { it('authenticates and stores a session cookie', async () => {
axiosMock.post.mockResolvedValue({ axiosMock.post.mockResolvedValue({
status: 200, status: 200,
+350 -2
View File
@@ -8,6 +8,9 @@ import {
validateTemplate, validateTemplate,
generateMockPreviews, generateMockPreviews,
getValidVariables, getValidVariables,
validateFilenameTemplate,
generateMockFilenamePreviews,
buildRenamedFilename,
type TemplateVariables type TemplateVariables
} from '@/lib/utils/path-template.util'; } from '@/lib/utils/path-template.util';
@@ -213,6 +216,142 @@ describe('substituteTemplate', () => {
const result = substituteTemplate(template, variables); const result = substituteTemplate(template, variables);
expect(result).toBe('Author/{narrated}/Title'); 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', () => { describe('validateTemplate', () => {
@@ -247,7 +386,7 @@ describe('validateTemplate', () => {
it('should reject unknown variables', () => { it('should reject unknown variables', () => {
const result = validateTemplate('{author}/{invalid}'); const result = validateTemplate('{author}/{invalid}');
expect(result.valid).toBe(false); 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}'); expect(result.error).toContain('{invalid}');
}); });
@@ -287,12 +426,13 @@ describe('validateTemplate', () => {
it('should provide helpful error messages for multiple unknown variables', () => { it('should provide helpful error messages for multiple unknown variables', () => {
const result = validateTemplate('{author}/{invalid1}/{invalid2}'); const result = validateTemplate('{author}/{invalid1}/{invalid2}');
expect(result.valid).toBe(false); 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', () => { it('should list valid variables in error message', () => {
const result = validateTemplate('{invalid}'); const result = validateTemplate('{invalid}');
expect(result.valid).toBe(false); 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('{author}');
expect(result.error).toContain('{title}'); expect(result.error).toContain('{title}');
expect(result.error).toContain('{narrator}'); expect(result.error).toContain('{narrator}');
@@ -334,6 +474,34 @@ describe('validateTemplate', () => {
const result = validateTemplate('\\{\\}'); const result = validateTemplate('\\{\\}');
expect(result.valid).toBe(true); 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', () => { describe('generateMockPreviews', () => {
@@ -444,3 +612,183 @@ describe('getValidVariables', () => {
expect(vars1).not.toBe(vars2); // Different array instances 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'
});
});