mirror of
https://github.com/kikootwo/ReadMeABook.git
synced 2026-06-03 21:00:09 +00:00
edc56bc457
Introduce manual import workflow and download permission support. Adds a Prisma migration and schema field (users.download_access) to track per-user download access, and updates admin UI to toggle global and per-user download access. Implements new APIs: filesystem browse, manual-import endpoint, download-access settings, audiobook download-status, and on-demand download-token generation. Adds frontend components for manual import and related tests, plus documentation for the manual-import feature and the documentation-agent prompt. Key files: prisma/migrations/20260212000000_add_download_access_permission/migration.sql, prisma/schema.prisma, src/app/api/admin/filesystem/browse/route.ts, src/app/api/admin/manual-import/route.ts, src/app/api/admin/settings/download-access/route.ts, src/app/api/requests/[id]/download-token/route.ts, src/app/api/audiobooks/[asin]/download-status/route.ts, and updated admin users pages/components and permissions util.
175 lines
5.5 KiB
TypeScript
175 lines
5.5 KiB
TypeScript
/**
|
|
* Component: Requests API Routes
|
|
* Documentation: documentation/backend/api.md
|
|
*/
|
|
|
|
import { NextRequest, NextResponse } from 'next/server';
|
|
import { requireAuth, AuthenticatedRequest } from '@/lib/middleware/auth';
|
|
import { prisma } from '@/lib/db';
|
|
import { z } from 'zod';
|
|
import { RMABLogger } from '@/lib/utils/logger';
|
|
import { createRequestForUser } from '@/lib/services/request-creator.service';
|
|
import { COMPLETED_STATUSES } from '@/lib/constants/request-statuses';
|
|
|
|
const logger = RMABLogger.create('API.Requests');
|
|
|
|
const CreateRequestSchema = z.object({
|
|
audiobook: z.object({
|
|
asin: z.string(),
|
|
title: z.string(),
|
|
author: z.string(),
|
|
narrator: z.string().optional(),
|
|
description: z.string().optional(),
|
|
coverArtUrl: z.string().optional(),
|
|
durationMinutes: z.number().optional(),
|
|
releaseDate: z.string().optional(),
|
|
rating: z.number().nullable().optional(),
|
|
}),
|
|
});
|
|
|
|
/**
|
|
* POST /api/requests
|
|
* Create a new audiobook request
|
|
*/
|
|
export async function POST(request: NextRequest) {
|
|
return requireAuth(request, async (req: AuthenticatedRequest) => {
|
|
try {
|
|
if (!req.user) {
|
|
return NextResponse.json(
|
|
{ error: 'Unauthorized', message: 'User not authenticated' },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
const body = await req.json();
|
|
const { audiobook } = CreateRequestSchema.parse(body);
|
|
|
|
const skipAutoSearch = req.nextUrl.searchParams.get('skipAutoSearch') === 'true';
|
|
|
|
const result = await createRequestForUser(req.user.id, {
|
|
asin: audiobook.asin,
|
|
title: audiobook.title,
|
|
author: audiobook.author,
|
|
narrator: audiobook.narrator,
|
|
description: audiobook.description,
|
|
coverArtUrl: audiobook.coverArtUrl,
|
|
}, { skipAutoSearch });
|
|
|
|
if (!result.success) {
|
|
const statusMap: Record<string, { error: string; status: number }> = {
|
|
already_available: { error: 'AlreadyAvailable', status: 409 },
|
|
being_processed: { error: 'BeingProcessed', status: 409 },
|
|
duplicate: { error: 'DuplicateRequest', status: 409 },
|
|
user_not_found: { error: 'UserNotFound', status: 404 },
|
|
};
|
|
const mapped = statusMap[result.reason] || { error: 'RequestError', status: 500 };
|
|
return NextResponse.json(
|
|
{ error: mapped.error, message: result.message },
|
|
{ status: mapped.status }
|
|
);
|
|
}
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
request: result.request,
|
|
}, { status: 201 });
|
|
} catch (error) {
|
|
logger.error('Failed to create request', { error: error instanceof Error ? error.message : String(error) });
|
|
|
|
if (error instanceof z.ZodError) {
|
|
return NextResponse.json(
|
|
{
|
|
error: 'ValidationError',
|
|
details: error.errors,
|
|
},
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
return NextResponse.json(
|
|
{
|
|
error: 'RequestError',
|
|
message: 'Failed to create audiobook request',
|
|
},
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* GET /api/requests?status=pending&limit=50
|
|
* Get user's audiobook requests (or all requests for admins)
|
|
*/
|
|
export async function GET(request: NextRequest) {
|
|
return requireAuth(request, async (req: AuthenticatedRequest) => {
|
|
try {
|
|
if (!req.user) {
|
|
return NextResponse.json(
|
|
{ error: 'Unauthorized', message: 'User not authenticated' },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
const searchParams = req.nextUrl.searchParams;
|
|
const status = searchParams.get('status');
|
|
const limit = parseInt(searchParams.get('limit') || '50', 10);
|
|
const myOnly = searchParams.get('myOnly') === 'true';
|
|
const type = searchParams.get('type'); // 'audiobook', 'ebook', or null for all
|
|
const isAdmin = req.user.role === 'admin';
|
|
|
|
// Build query
|
|
// If myOnly=true, always filter by current user (even for admins)
|
|
// Otherwise, admins see all requests, users see only their own
|
|
const where: any = myOnly || !isAdmin ? { userId: req.user.id } : {};
|
|
if (status) {
|
|
where.status = status;
|
|
}
|
|
// Filter by type if specified (otherwise returns all types)
|
|
if (type && ['audiobook', 'ebook'].includes(type)) {
|
|
where.type = type;
|
|
}
|
|
// Only show active (non-deleted) requests
|
|
where.deletedAt = null;
|
|
|
|
const requests = await prisma.request.findMany({
|
|
where,
|
|
include: {
|
|
audiobook: true,
|
|
user: {
|
|
select: {
|
|
id: true,
|
|
plexUsername: true,
|
|
},
|
|
},
|
|
},
|
|
orderBy: { createdAt: 'desc' },
|
|
take: limit,
|
|
});
|
|
|
|
const enriched = requests.map(r => {
|
|
const isCompleted = COMPLETED_STATUSES.includes(r.status as typeof COMPLETED_STATUSES[number]);
|
|
const downloadAvailable = isCompleted && !!r.audiobook?.filePath;
|
|
// Strip server-side absolute path from client response
|
|
const audiobook = r.audiobook ? { ...r.audiobook, filePath: undefined } : r.audiobook;
|
|
return { ...r, audiobook, downloadAvailable };
|
|
});
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
requests: enriched,
|
|
count: enriched.length,
|
|
});
|
|
} catch (error) {
|
|
logger.error('Failed to get requests', { error: error instanceof Error ? error.message : String(error) });
|
|
return NextResponse.json(
|
|
{
|
|
error: 'FetchError',
|
|
message: 'Failed to fetch requests',
|
|
},
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
});
|
|
}
|