Add request approval system and audiobook path template

Implements admin approval workflow for user requests with global and per-user auto-approve controls. Adds new request statuses ('awaiting_approval', 'denied'), related API endpoints, and UI for pending approvals. Introduces configurable audiobook organization path template with validation and preview in settings, updates database schema and migrations for new fields.
This commit is contained in:
kikootwo
2026-01-16 13:47:36 -05:00
parent 428d9a12e0
commit 3a9ae4a439
59 changed files with 4043 additions and 256 deletions
+18 -52
View File
@@ -9,53 +9,13 @@ import { NextRequest, NextResponse } from 'next/server';
import { requireAuth, requireAdmin, AuthenticatedRequest } from '@/lib/middleware/auth';
import { prisma } from '@/lib/db';
import { downloadEbook } from '@/lib/services/ebook-scraper';
import { buildAudiobookPath } from '@/lib/utils/file-organizer';
import fs from 'fs/promises';
import path from 'path';
import { RMABLogger } from '@/lib/utils/logger';
const logger = RMABLogger.create('API.FetchEbook');
/**
* Sanitize path component (same logic as file-organizer)
*/
function sanitizePath(name: string): string {
return (
name
.replace(/[<>:"/\\|?*]/g, '')
.trim()
.replace(/^\.+/, '')
.replace(/\.+$/, '')
.replace(/\s+/g, ' ')
.slice(0, 200)
);
}
/**
* Build target path (same logic as file-organizer)
*/
function buildTargetPath(
baseDir: string,
author: string,
title: string,
year?: number | null,
asin?: string | null
): string {
const authorClean = sanitizePath(author);
const titleClean = sanitizePath(title);
let folderName = titleClean;
if (year) {
folderName = `${folderName} (${year})`;
}
if (asin) {
folderName = `${folderName} ${asin}`;
}
return path.join(baseDir, authorClean, folderName);
}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
@@ -103,37 +63,43 @@ export async function POST(
const audiobook = requestRecord.audiobook;
// Get configuration
const [mediaDirConfig, formatConfig, baseUrlConfig, flaresolverrConfig] = await Promise.all([
const [mediaDirConfig, templateConfig, formatConfig, baseUrlConfig, flaresolverrConfig] = await Promise.all([
prisma.configuration.findUnique({ where: { key: 'media_dir' } }),
prisma.configuration.findUnique({ where: { key: 'audiobook_path_template' } }),
prisma.configuration.findUnique({ where: { key: 'ebook_sidecar_preferred_format' } }),
prisma.configuration.findUnique({ where: { key: 'ebook_sidecar_base_url' } }),
prisma.configuration.findUnique({ where: { key: 'ebook_sidecar_flaresolverr_url' } }),
]);
const mediaDir = mediaDirConfig?.value || '/media/audiobooks';
const template = templateConfig?.value || '{author}/{title} {asin}';
const preferredFormat = formatConfig?.value || 'epub';
const baseUrl = baseUrlConfig?.value || 'https://annas-archive.li';
const flaresolverrUrl = flaresolverrConfig?.value || undefined;
// Get year from AudibleCache if available
// Fetch year from audible cache if ASIN is available
let year: number | undefined;
if (audiobook.audibleAsin) {
const audibleCacheData = await prisma.audibleCache.findUnique({
const audibleCache = await prisma.audibleCache.findUnique({
where: { asin: audiobook.audibleAsin },
select: { releaseDate: true },
});
if (audibleCacheData?.releaseDate) {
year = new Date(audibleCacheData.releaseDate).getFullYear();
if (audibleCache?.releaseDate) {
year = new Date(audibleCache.releaseDate).getFullYear();
}
}
// Build target path
const targetPath = buildTargetPath(
// Build target path using centralized function
const targetPath = buildAudiobookPath(
mediaDir,
audiobook.author,
audiobook.title,
year,
audiobook.audibleAsin
template,
{
author: audiobook.author,
title: audiobook.title,
narrator: audiobook.narrator || undefined,
asin: audiobook.audibleAsin || undefined,
year,
}
);
logger.debug('Fetch e-book request', {
+86 -3
View File
@@ -8,6 +8,7 @@ import { requireAuth, AuthenticatedRequest } from '@/lib/middleware/auth';
import { prisma } from '@/lib/db';
import { getJobQueueService } from '@/lib/services/job-queue.service';
import { findPlexMatch } from '@/lib/utils/audiobook-matcher';
import { getAudibleService } from '@/lib/integrations/audible.service';
import { z } from 'zod';
import { RMABLogger } from '@/lib/utils/logger';
@@ -96,6 +97,27 @@ export async function POST(request: NextRequest) {
);
}
// Fetch full details from Audnexus to get releaseDate and year
let year: number | undefined;
try {
const audibleService = getAudibleService();
const audnexusData = await audibleService.getAudiobookDetails(audiobook.asin);
if (audnexusData?.releaseDate) {
try {
const releaseYear = new Date(audnexusData.releaseDate).getFullYear();
if (!isNaN(releaseYear)) {
year = releaseYear;
logger.debug(`Extracted year ${year} from Audnexus releaseDate: ${audnexusData.releaseDate}`);
}
} catch (error) {
logger.warn(`Failed to parse Audnexus releaseDate "${audnexusData.releaseDate}": ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
} catch (error) {
logger.warn(`Failed to fetch Audnexus data for ASIN ${audiobook.asin}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
// Try to find existing audiobook record by ASIN
let audiobookRecord = await prisma.audiobook.findFirst({
where: { audibleAsin: audiobook.asin },
@@ -111,9 +133,18 @@ export async function POST(request: NextRequest) {
narrator: audiobook.narrator,
description: audiobook.description,
coverArtUrl: audiobook.coverArtUrl,
year,
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)
audiobookRecord = await prisma.audiobook.update({
where: { id: audiobookRecord.id },
data: { year },
});
logger.debug(`Updated audiobook ${audiobookRecord.id} with year ${year}`);
}
// Check if user already has an active (non-deleted) request for this audiobook
@@ -150,12 +181,64 @@ export async function POST(request: NextRequest) {
// Check if we should skip auto-search (for interactive search)
const skipAutoSearch = req.nextUrl.searchParams.get('skipAutoSearch') === 'true';
// Check if request needs approval
let needsApproval = false;
let shouldTriggerSearch = !skipAutoSearch;
// Fetch user with autoApproveRequests setting
const user = await prisma.user.findUnique({
where: { id: req.user.id },
select: {
role: true,
autoApproveRequests: true,
},
});
if (!user) {
return NextResponse.json(
{ error: 'UserNotFound', message: 'User not found' },
{ status: 404 }
);
}
// Determine if approval is needed
if (user.role === 'admin') {
// Admins always auto-approve
needsApproval = false;
} else {
// Check user's personal setting first
if (user.autoApproveRequests === true) {
needsApproval = false;
} else if (user.autoApproveRequests === false) {
needsApproval = true;
} else {
// User setting is null, check global setting
const globalConfig = await prisma.configuration.findUnique({
where: { key: 'auto_approve_requests' },
});
// Default to true if not configured (backward compatibility)
const globalAutoApprove = globalConfig === null ? true : globalConfig.value === 'true';
needsApproval = !globalAutoApprove;
}
}
// Determine initial status
let initialStatus: string;
if (needsApproval) {
initialStatus = 'awaiting_approval';
shouldTriggerSearch = false; // Don't trigger search if awaiting approval
} else if (skipAutoSearch) {
initialStatus = 'awaiting_search';
} else {
initialStatus = 'pending';
}
// Create request with appropriate status
const newRequest = await prisma.request.create({
data: {
userId: req.user.id,
audiobookId: audiobookRecord.id,
status: skipAutoSearch ? 'awaiting_search' : 'pending',
status: initialStatus,
progress: 0,
},
include: {
@@ -169,8 +252,8 @@ export async function POST(request: NextRequest) {
},
});
// Trigger search job only if not skipped
if (!skipAutoSearch) {
// Trigger search job only if not skipped and not awaiting approval
if (shouldTriggerSearch) {
const jobQueue = getJobQueueService();
await jobQueue.addSearchJob(newRequest.id, {
id: audiobookRecord.id,