Add series fields to audiobooks and update related logic

Introduces 'series' and 'seriesPart' fields to the Audiobook model and database schema. Updates API routes, file organization, and path template utilities to support series metadata. Enhances chapter merging logic, improves notification backend testing, and expands test coverage for admin and API routes.
This commit is contained in:
kikootwo
2026-01-22 15:56:55 -05:00
parent dc7e557694
commit 31bca0052f
105 changed files with 10384 additions and 75 deletions
@@ -45,7 +45,10 @@ export function RequestActionsDropdown({
const canSearch = ['pending', 'failed', 'awaiting_search'].includes(request.status);
const canCancel = ['pending', 'searching', 'downloading'].includes(request.status);
const canDelete = true; // Admins can always delete
const canViewSource = !!request.torrentUrl && ['downloading', 'processing', 'downloaded', 'available'].includes(request.status);
// Only show "View Source" if we have a valid indexer page URL (not a magnet link)
const canViewSource = !!request.torrentUrl &&
!request.torrentUrl.startsWith('magnet:') &&
['downloading', 'processing', 'downloaded', 'available'].includes(request.status);
const canFetchEbook = ebookSidecarEnabled && ['downloaded', 'available'].includes(request.status);
// Close dropdown when clicking outside
@@ -117,12 +117,15 @@ export function NotificationsTab() {
setIsTesting(true);
setTestResult(null);
// In edit mode, use backend ID to test with real config (masked values won't work)
// In add mode, use the form config directly
const testPayload = modalState.mode === 'edit' && modalState.backend
? { backendId: modalState.backend.id }
: { type: modalState.selectedType, config: formData.config };
const response = await fetchWithAuth('/api/admin/notifications/test', {
method: 'POST',
body: JSON.stringify({
type: modalState.selectedType,
config: formData.config,
}),
body: JSON.stringify(testPayload),
});
const data = await response.json();
@@ -137,6 +137,14 @@ export function PathsTab({ paths, onChange, onValidationChange }: PathsTabProps)
<code className="text-blue-700 dark:text-blue-300 font-mono">{'{asin}'}</code>
<span className="text-gray-600 dark:text-gray-400 ml-2">- Audible ASIN</span>
</div>
<div>
<code className="text-blue-700 dark:text-blue-300 font-mono">{'{series}'}</code>
<span className="text-gray-600 dark:text-gray-400 ml-2">- Book series name</span>
</div>
<div>
<code className="text-blue-700 dark:text-blue-300 font-mono">{'{seriesPart}'}</code>
<span className="text-gray-600 dark:text-gray-400 ml-2">- Series part/position</span>
</div>
</div>
</div>
+78 -6
View File
@@ -8,12 +8,29 @@ import { requireAuth, requireAdmin, AuthenticatedRequest } from '@/lib/middlewar
import { getNotificationService, NotificationBackendType, NotificationPayload } from '@/lib/services/notification.service';
import { RMABLogger } from '@/lib/utils/logger';
import { z } from 'zod';
import { prisma } from '@/lib/db';
const logger = RMABLogger.create('API.Admin.Notifications.Test');
const TestNotificationSchema = z.object({
type: z.enum(['discord', 'pushover', 'email', 'slack', 'telegram', 'webhook']),
config: z.record(z.any()),
const TestNotificationSchema = z.discriminatedUnion('mode', [
// Test existing backend by ID (uses stored config)
z.object({
mode: z.literal('backend'),
backendId: z.string(),
}),
// Test new config before saving
z.object({
mode: z.literal('config'),
type: z.enum(['discord', 'pushover', 'email', 'slack', 'telegram', 'webhook']),
config: z.record(z.any()),
}),
]);
// Support legacy format without mode
const LegacyTestNotificationSchema = z.object({
backendId: z.string().optional(),
type: z.enum(['discord', 'pushover', 'email', 'slack', 'telegram', 'webhook']).optional(),
config: z.record(z.any()).optional(),
});
/**
@@ -25,12 +42,67 @@ export async function POST(request: NextRequest) {
return requireAdmin(req, async () => {
try {
const body = await request.json();
const { type, config } = TestNotificationSchema.parse(body);
// Support legacy format for backward compatibility
const legacyParsed = LegacyTestNotificationSchema.safeParse(body);
let type: NotificationBackendType;
let encryptedConfig: any;
const notificationService = getNotificationService();
// Encrypt config values
const encryptedConfig = notificationService.encryptConfig(type, config);
if (legacyParsed.success) {
// Legacy format
if (legacyParsed.data.backendId) {
// Test existing backend
const backend = await prisma.notificationBackend.findUnique({
where: { id: legacyParsed.data.backendId },
});
if (!backend) {
return NextResponse.json(
{ error: 'NotFound', message: 'Backend not found' },
{ status: 404 }
);
}
type = backend.type as NotificationBackendType;
encryptedConfig = backend.config; // Already encrypted in DB
} else if (legacyParsed.data.type && legacyParsed.data.config) {
// Test new config
type = legacyParsed.data.type as NotificationBackendType;
encryptedConfig = notificationService.encryptConfig(type, legacyParsed.data.config);
} else {
return NextResponse.json(
{ error: 'ValidationError', message: 'Must provide either backendId or type+config' },
{ status: 400 }
);
}
} else {
// New format with discriminated union
const parsed = TestNotificationSchema.parse(body);
if (parsed.mode === 'backend') {
// Test existing backend
const backend = await prisma.notificationBackend.findUnique({
where: { id: parsed.backendId },
});
if (!backend) {
return NextResponse.json(
{ error: 'NotFound', message: 'Backend not found' },
{ status: 404 }
);
}
type = backend.type as NotificationBackendType;
encryptedConfig = backend.config; // Already encrypted in DB
} else {
// Test new config
type = parsed.type;
encryptedConfig = notificationService.encryptConfig(type, parsed.config);
}
}
// Create test payload
const testPayload: NotificationPayload = {
@@ -113,8 +113,10 @@ export async function POST(request: NextRequest) {
);
}
// Fetch full details from Audnexus to get releaseDate and year
// Fetch full details from Audnexus to get releaseDate, year, and series
let year: number | undefined;
let series: string | undefined;
let seriesPart: string | undefined;
try {
const audibleService = getAudibleService();
const audnexusData = await audibleService.getAudiobookDetails(audiobook.asin);
@@ -130,6 +132,16 @@ export async function POST(request: NextRequest) {
logger.warn(`Failed to parse Audnexus releaseDate "${audnexusData.releaseDate}": ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
// Extract series data
if (audnexusData?.series) {
series = audnexusData.series;
logger.debug(`Extracted series: ${series}`);
}
if (audnexusData?.seriesPart) {
seriesPart = audnexusData.seriesPart;
logger.debug(`Extracted seriesPart: ${seriesPart}`);
}
} catch (error) {
logger.warn(`Failed to fetch Audnexus data for ASIN ${audiobook.asin}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
@@ -150,17 +162,23 @@ export async function POST(request: NextRequest) {
description: audiobook.description,
coverArtUrl: audiobook.coverArtUrl,
year,
series,
seriesPart,
status: 'requested',
},
});
logger.debug(`Created audiobook ${audiobookRecord.id} with year: ${year || 'none'}`);
} else if (year) {
// Always update year if we have it from Audnexus (even if audiobook already has one)
logger.debug(`Created audiobook ${audiobookRecord.id} with year: ${year || 'none'}, series: ${series || 'none'}`);
} else if (year || series || seriesPart) {
// Always update year/series if we have them from Audnexus (even if audiobook already has them)
audiobookRecord = await prisma.audiobook.update({
where: { id: audiobookRecord.id },
data: { year },
data: {
...(year && { year }),
...(series && { series }),
...(seriesPart && { seriesPart }),
},
});
logger.debug(`Updated audiobook ${audiobookRecord.id} with year ${year}`);
logger.debug(`Updated audiobook ${audiobookRecord.id} with year: ${year || 'unchanged'}, series: ${series || 'unchanged'}`);
}
// Check if user already has an active (non-deleted) request for this audiobook
+25 -7
View File
@@ -63,8 +63,10 @@ async function handler(req: AuthenticatedRequest) {
// If swiped right and not marked as known, create request
if (action === 'right' && !markedAsKnown && recommendation.audnexusAsin) {
try {
// Fetch full details from Audnexus to get releaseDate and year
// Fetch full details from Audnexus to get releaseDate, year, and series
let year: number | undefined;
let series: string | undefined;
let seriesPart: string | undefined;
try {
const audibleService = getAudibleService();
const audnexusData = await audibleService.getAudiobookDetails(recommendation.audnexusAsin);
@@ -80,6 +82,16 @@ async function handler(req: AuthenticatedRequest) {
logger.warn(`Failed to parse Audnexus releaseDate "${audnexusData.releaseDate}": ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
// Extract series data
if (audnexusData?.series) {
series = audnexusData.series;
logger.debug(`Extracted series: ${series}`);
}
if (audnexusData?.seriesPart) {
seriesPart = audnexusData.seriesPart;
logger.debug(`Extracted seriesPart: ${seriesPart}`);
}
} catch (error) {
logger.warn(`Failed to fetch Audnexus data for ASIN ${recommendation.audnexusAsin}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
@@ -89,7 +101,7 @@ async function handler(req: AuthenticatedRequest) {
where: { audibleAsin: recommendation.audnexusAsin },
});
// If not, create it with year
// If not, create it with year and series
if (!audiobook) {
audiobook = await prisma.audiobook.create({
data: {
@@ -100,17 +112,23 @@ async function handler(req: AuthenticatedRequest) {
description: recommendation.description,
coverArtUrl: recommendation.coverUrl,
year,
series,
seriesPart,
status: 'requested',
},
});
logger.debug(`Created audiobook ${audiobook.id} with year: ${year || 'none'}`);
} else if (year) {
// Always update year if we have it from Audnexus (even if audiobook already has one)
logger.debug(`Created audiobook ${audiobook.id} with year: ${year || 'none'}, series: ${series || 'none'}`);
} else if (year || series || seriesPart) {
// Always update year/series if we have them from Audnexus (even if audiobook already has them)
audiobook = await prisma.audiobook.update({
where: { id: audiobook.id },
data: { year },
data: {
...(year && { year }),
...(series && { series }),
...(seriesPart && { seriesPart }),
},
});
logger.debug(`Updated audiobook ${audiobook.id} with year ${year}`);
logger.debug(`Updated audiobook ${audiobook.id} with year: ${year || 'unchanged'}, series: ${series || 'unchanged'}`);
}
// Create request (if not already exists)
+24 -6
View File
@@ -97,8 +97,10 @@ export async function POST(request: NextRequest) {
);
}
// Fetch full details from Audnexus to get releaseDate and year
// Fetch full details from Audnexus to get releaseDate, year, and series
let year: number | undefined;
let series: string | undefined;
let seriesPart: string | undefined;
try {
const audibleService = getAudibleService();
const audnexusData = await audibleService.getAudiobookDetails(audiobook.asin);
@@ -114,6 +116,16 @@ export async function POST(request: NextRequest) {
logger.warn(`Failed to parse Audnexus releaseDate "${audnexusData.releaseDate}": ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
// Extract series data
if (audnexusData?.series) {
series = audnexusData.series;
logger.debug(`Extracted series: ${series}`);
}
if (audnexusData?.seriesPart) {
seriesPart = audnexusData.seriesPart;
logger.debug(`Extracted seriesPart: ${seriesPart}`);
}
} catch (error) {
logger.warn(`Failed to fetch Audnexus data for ASIN ${audiobook.asin}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
@@ -134,17 +146,23 @@ export async function POST(request: NextRequest) {
description: audiobook.description,
coverArtUrl: audiobook.coverArtUrl,
year,
series,
seriesPart,
status: 'requested',
},
});
logger.debug(`Created audiobook ${audiobookRecord.id} with year: ${year || 'none'}`);
} else if (year) {
// Always update year if we have it from Audnexus (even if audiobook already has one)
logger.debug(`Created audiobook ${audiobookRecord.id} with year: ${year || 'none'}, series: ${series || 'none'}`);
} else if (year || series || seriesPart) {
// Always update year/series if we have them from Audnexus (even if audiobook already has them)
audiobookRecord = await prisma.audiobook.update({
where: { id: audiobookRecord.id },
data: { year },
data: {
...(year && { year }),
...(series && { series }),
...(seriesPart && { seriesPart }),
},
});
logger.debug(`Updated audiobook ${audiobookRecord.id} with year ${year}`);
logger.debug(`Updated audiobook ${audiobookRecord.id} with year: ${year || 'unchanged'}, series: ${series || 'unchanged'}`);
}
// Check if user already has an active (non-deleted) request for this audiobook
+7 -1
View File
@@ -23,6 +23,8 @@ export interface AudibleAudiobook {
releaseDate?: string;
rating?: number;
genres?: string[];
series?: string;
seriesPart?: string;
}
export interface AudibleSearchResult {
@@ -492,6 +494,8 @@ export class AudibleService {
releaseDate: data.releaseDate || undefined,
rating: data.rating ? parseFloat(data.rating) : undefined,
genres: data.genres?.map((g: any) => typeof g === 'string' ? g : g.name).slice(0, 5) || undefined,
series: data.seriesPrimary?.name || undefined,
seriesPart: data.seriesPrimary?.position || undefined,
};
// Ensure cover art URL is high quality
@@ -506,7 +510,9 @@ export class AudibleService {
descLength: result.description?.length || 0,
duration: result.durationMinutes,
rating: result.rating,
genreCount: result.genres?.length || 0
genreCount: result.genres?.length || 0,
series: result.series,
seriesPart: result.seriesPart
});
return result;
@@ -60,6 +60,9 @@ export async function processDownloadTorrent(payload: DownloadTorrentPayload): P
logger.info(`NZB added with ID: ${downloadClientId}`);
// Create DownloadHistory record
// Determine indexer page URL - exclude magnet links from guid fallback
const indexerPageUrl = torrent.infoUrl || (torrent.guid?.startsWith('magnet:') ? null : torrent.guid);
const downloadHistory = await prisma.downloadHistory.create({
data: {
requestId,
@@ -69,7 +72,7 @@ export async function processDownloadTorrent(payload: DownloadTorrentPayload): P
torrentName: torrent.title,
nzbId: downloadClientId, // Store NZB ID
torrentSizeBytes: torrent.size,
torrentUrl: torrent.infoUrl || torrent.guid, // Indexer page URL (prefer infoUrl, fallback to guid)
torrentUrl: indexerPageUrl, // Indexer page URL (only if available and not a magnet/download link)
magnetLink: torrent.downloadUrl, // Download URL (.nzb file)
seeders: torrent.seeders || 0, // Usenet doesn't have seeders, but include for consistency
leechers: 0,
@@ -121,6 +124,9 @@ export async function processDownloadTorrent(payload: DownloadTorrentPayload): P
logger.info(`Torrent added with hash: ${downloadClientId}`);
// Create DownloadHistory record
// Determine indexer page URL - exclude magnet links from guid fallback
const indexerPageUrl = torrent.infoUrl || (torrent.guid?.startsWith('magnet:') ? null : torrent.guid);
const downloadHistory = await prisma.downloadHistory.create({
data: {
requestId,
@@ -130,7 +136,7 @@ export async function processDownloadTorrent(payload: DownloadTorrentPayload): P
torrentName: torrent.title,
torrentHash: torrent.infoHash || downloadClientId, // Store torrent hash
torrentSizeBytes: torrent.size,
torrentUrl: torrent.infoUrl || torrent.guid, // Indexer page URL (prefer infoUrl, fallback to guid)
torrentUrl: indexerPageUrl, // Indexer page URL (only if available and not a magnet/download link)
magnetLink: torrent.downloadUrl,
seeders: torrent.seeders || 0,
leechers: torrent.leechers || 0,
@@ -94,6 +94,8 @@ export async function processOrganizeFiles(payload: OrganizeFilesPayload): Promi
coverArtUrl: audiobook.coverArtUrl || undefined,
asin: audiobook.audibleAsin || undefined,
year,
series: audiobook.series || undefined,
seriesPart: audiobook.seriesPart || undefined,
},
template,
jobId ? { jobId, context: 'FileOrganizer' } : undefined
+22 -3
View File
@@ -447,6 +447,23 @@ function determineOutputBitrate(chapters: ChapterFile[]): string {
return `${finalBitrate}k`;
}
/**
* Map bitrate to native AAC VBR quality value
* Quality range: 0.1-5 (higher = better quality/larger file)
*/
function bitrateToVbrQuality(bitrateStr: string): number {
const bitrate = parseInt(bitrateStr.replace('k', ''));
// Approximate mapping based on AAC VBR behavior
if (bitrate <= 64) return 1.0; // ~64kbps
if (bitrate <= 96) return 1.5; // ~96kbps
if (bitrate <= 128) return 2.0; // ~128kbps
if (bitrate <= 160) return 2.5; // ~160kbps
if (bitrate <= 192) return 3.0; // ~192kbps
if (bitrate <= 256) return 4.0; // ~256kbps
return 4.5; // ~320kbps+ (max quality)
}
/**
* Check if libfdk_aac encoder is available (higher quality than native AAC)
*/
@@ -640,10 +657,12 @@ export async function mergeChapters(
args.push('-vbr', '4'); // VBR mode 4 (~128-160kbps, high quality)
await logger?.info(`Merge strategy: Re-encoding MP3 → AAC/M4B using libfdk_aac (high quality VBR, target ~${bitrate})`);
} else {
// Use VBR for better quality at same average bitrate
const vbrQuality = bitrateToVbrQuality(bitrate);
args.push('-c:a', 'aac');
args.push('-b:a', bitrate);
args.push('-q:a', vbrQuality.toString());
args.push('-profile:a', 'aac_low'); // AAC-LC profile for maximum compatibility
await logger?.info(`Merge strategy: Re-encoding MP3 → AAC/M4B using native AAC at ${bitrate}`);
await logger?.info(`Merge strategy: Re-encoding MP3 → AAC/M4B using native AAC VBR (quality ${vbrQuality}, target ~${bitrate})`);
}
} else {
// M4A/M4B -> M4B can use codec copy (fast, lossless)
@@ -838,7 +857,7 @@ async function validateMergedFile(
const stats = await fs.stat(outputPath);
const sizeMB = stats.size / 1024 / 1024;
const durationMinutes = expectedDuration / 1000 / 60;
const expectedMinSize = durationMinutes * 0.5; // ~0.5MB per minute minimum for compressed audio
const expectedMinSize = durationMinutes * 0.4; // ~0.4MB per minute minimum (accommodates 64kbps encoding)
if (sizeMB < expectedMinSize) {
return {
+13 -3
View File
@@ -30,6 +30,8 @@ export interface AudiobookMetadata {
year?: number;
coverArtUrl?: string;
asin?: string;
series?: string;
seriesPart?: string;
}
export interface OrganizationResult {
@@ -275,7 +277,9 @@ export class FileOrganizer {
audiobook.title,
audiobook.narrator,
audiobook.asin,
audiobook.year
audiobook.year,
audiobook.series,
audiobook.seriesPart
);
await logger?.info(`Target path: ${targetPath}`);
@@ -556,7 +560,9 @@ export class FileOrganizer {
title: string,
narrator?: string,
asin?: string,
year?: number
year?: number,
series?: string,
seriesPart?: string
): string {
const variables: TemplateVariables = {
author,
@@ -564,6 +570,8 @@ export class FileOrganizer {
narrator,
asin,
year,
series,
seriesPart,
};
const relativePath = substituteTemplate(template, variables);
@@ -713,7 +721,7 @@ export async function getFileOrganizer(): Promise<FileOrganizer> {
export function buildAudiobookPath(
baseDir: string,
template: string,
variables: { author: string; title: string; narrator?: string; asin?: string; year?: number }
variables: { author: string; title: string; narrator?: string; asin?: string; year?: number; series?: string; seriesPart?: string }
): string {
const templateVars: TemplateVariables = {
author: variables.author,
@@ -721,6 +729,8 @@ export function buildAudiobookPath(
narrator: variables.narrator,
asin: variables.asin,
year: variables.year,
series: variables.series,
seriesPart: variables.seriesPart,
};
const relativePath = substituteTemplate(template, templateVars);
+10 -3
View File
@@ -15,6 +15,8 @@ export interface TemplateVariables {
narrator?: string;
asin?: string;
year?: number;
series?: string;
seriesPart?: string;
}
/**
@@ -28,7 +30,7 @@ export interface ValidationResult {
/**
* Supported template variable names
*/
const VALID_VARIABLES = ['author', 'title', 'narrator', 'asin', 'year'];
const VALID_VARIABLES = ['author', 'title', 'narrator', 'asin', 'year', 'series', 'seriesPart'];
/**
* Invalid file path characters (outside of template variables)
@@ -228,14 +230,18 @@ export function generateMockPreviews(template: string): string[] {
title: 'Mistborn: The Final Empire',
narrator: 'Michael Kramer',
asin: 'B002UZMLXM',
year: 2006
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
year: 2005,
series: "Hitchhiker's Guide",
seriesPart: '1'
},
{
author: 'Andy Weir',
@@ -243,6 +249,7 @@ export function generateMockPreviews(template: string): string[] {
// No narrator for this example
asin: 'B08G9PRS1K',
year: 2021
// No series data - to test empty handling
}
];