Initial commit

This commit is contained in:
kikootwo
2026-01-28 11:41:24 -05:00
commit a3ba192fbd
257 changed files with 89482 additions and 0 deletions
@@ -0,0 +1,99 @@
/**
* Component: Interactive Search API
* Documentation: documentation/phase3/prowlarr.md
*/
import { NextRequest, NextResponse } from 'next/server';
import { requireAuth, AuthenticatedRequest } from '@/lib/middleware/auth';
import { prisma } from '@/lib/db';
import { getProwlarrService } from '@/lib/integrations/prowlarr.service';
import { rankTorrents } from '@/lib/utils/ranking-algorithm';
/**
* POST /api/requests/[id]/interactive-search
* Search for torrents and return results for user selection
*/
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
return requireAuth(request, async (req: AuthenticatedRequest) => {
try {
if (!req.user) {
return NextResponse.json(
{ error: 'Unauthorized', message: 'User not authenticated' },
{ status: 401 }
);
}
const { id } = await params;
const requestRecord = await prisma.request.findUnique({
where: { id },
include: {
audiobook: true,
},
});
if (!requestRecord) {
return NextResponse.json(
{ error: 'NotFound', message: 'Request not found' },
{ status: 404 }
);
}
// Check authorization
if (requestRecord.userId !== req.user.id && req.user.role !== 'admin') {
return NextResponse.json(
{ error: 'Forbidden', message: 'You do not have access to this request' },
{ status: 403 }
);
}
// Search Prowlarr for torrents
const prowlarr = await getProwlarrService();
const searchQuery = `${requestRecord.audiobook.title} ${requestRecord.audiobook.author}`;
console.log(`[InteractiveSearch] Searching for: ${searchQuery}`);
const results = await prowlarr.search(searchQuery);
if (results.length === 0) {
return NextResponse.json({
success: true,
results: [],
message: 'No torrents found',
});
}
// Rank torrents using the ranking algorithm
const rankedResults = rankTorrents(results, {
title: requestRecord.audiobook.title,
author: requestRecord.audiobook.author,
});
// Add rank position to each result
const resultsWithRank = rankedResults.map((result, index) => ({
...result,
rank: index + 1,
}));
console.log(`[InteractiveSearch] Found ${resultsWithRank.length} results for request ${id}`);
return NextResponse.json({
success: true,
results: resultsWithRank,
message: `Found ${resultsWithRank.length} torrents`,
});
} catch (error) {
console.error('Failed to perform interactive search:', error);
return NextResponse.json(
{
error: 'SearchError',
message: error instanceof Error ? error.message : 'Failed to search for torrents',
},
{ status: 500 }
);
}
});
}
@@ -0,0 +1,102 @@
/**
* Component: Manual Search API
* Documentation: documentation/phase3/prowlarr.md
*/
import { NextRequest, NextResponse } from 'next/server';
import { requireAuth, AuthenticatedRequest } from '@/lib/middleware/auth';
import { prisma } from '@/lib/db';
import { getJobQueueService } from '@/lib/services/job-queue.service';
/**
* POST /api/requests/[id]/manual-search
* Manually trigger a search for torrents
*/
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
return requireAuth(request, async (req: AuthenticatedRequest) => {
try {
if (!req.user) {
return NextResponse.json(
{ error: 'Unauthorized', message: 'User not authenticated' },
{ status: 401 }
);
}
const { id } = await params;
const requestRecord = await prisma.request.findUnique({
where: { id },
include: {
audiobook: true,
},
});
if (!requestRecord) {
return NextResponse.json(
{ error: 'NotFound', message: 'Request not found' },
{ status: 404 }
);
}
// Check authorization
if (requestRecord.userId !== req.user.id && req.user.role !== 'admin') {
return NextResponse.json(
{ error: 'Forbidden', message: 'You do not have access to this request' },
{ status: 403 }
);
}
// Only allow manual search for pending, failed, awaiting_search statuses
const searchableStatuses = ['pending', 'failed', 'awaiting_search'];
if (!searchableStatuses.includes(requestRecord.status)) {
return NextResponse.json(
{
error: 'ValidationError',
message: `Cannot manually search for request with status: ${requestRecord.status}`,
},
{ status: 400 }
);
}
// Trigger search job
const jobQueue = getJobQueueService();
await jobQueue.addSearchJob(id, {
id: requestRecord.audiobook.id,
title: requestRecord.audiobook.title,
author: requestRecord.audiobook.author,
});
// Update request status
const updated = await prisma.request.update({
where: { id },
data: {
status: 'pending',
progress: 0,
errorMessage: null,
updatedAt: new Date(),
},
include: {
audiobook: true,
},
});
return NextResponse.json({
success: true,
request: updated,
message: 'Manual search initiated',
});
} catch (error) {
console.error('Failed to trigger manual search:', error);
return NextResponse.json(
{
error: 'SearchError',
message: 'Failed to initiate manual search',
},
{ status: 500 }
);
}
});
}
+325
View File
@@ -0,0 +1,325 @@
/**
* Component: Individual Request 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';
/**
* GET /api/requests/[id]
* Get a specific request by ID
*/
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
return requireAuth(request, async (req: AuthenticatedRequest) => {
try {
if (!req.user) {
return NextResponse.json(
{ error: 'Unauthorized', message: 'User not authenticated' },
{ status: 401 }
);
}
const { id } = await params;
const requestRecord = await prisma.request.findUnique({
where: { id },
include: {
audiobook: true,
user: {
select: {
id: true,
plexUsername: true,
},
},
downloadHistory: {
where: { selected: true },
take: 1,
},
jobs: {
orderBy: { createdAt: 'desc' },
take: 5,
},
},
});
if (!requestRecord) {
return NextResponse.json(
{ error: 'NotFound', message: 'Request not found' },
{ status: 404 }
);
}
// Check authorization: users can only see their own requests, admins can see all
if (requestRecord.userId !== req.user.id && req.user.role !== 'admin') {
return NextResponse.json(
{ error: 'Forbidden', message: 'You do not have access to this request' },
{ status: 403 }
);
}
return NextResponse.json({
success: true,
request: requestRecord,
});
} catch (error) {
console.error('Failed to get request:', error);
return NextResponse.json(
{
error: 'FetchError',
message: 'Failed to fetch request',
},
{ status: 500 }
);
}
});
}
/**
* PATCH /api/requests/[id]
* Update a request (cancel, retry, etc.)
*/
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
return requireAuth(request, async (req: AuthenticatedRequest) => {
try {
if (!req.user) {
return NextResponse.json(
{ error: 'Unauthorized', message: 'User not authenticated' },
{ status: 401 }
);
}
const { id } = await params;
const body = await req.json();
const { action } = body;
const requestRecord = await prisma.request.findUnique({
where: { id },
});
if (!requestRecord) {
return NextResponse.json(
{ error: 'NotFound', message: 'Request not found' },
{ status: 404 }
);
}
// Check authorization
if (requestRecord.userId !== req.user.id && req.user.role !== 'admin') {
return NextResponse.json(
{ error: 'Forbidden', message: 'You do not have access to this request' },
{ status: 403 }
);
}
if (action === 'cancel') {
// Cancel the request
const updated = await prisma.request.update({
where: { id },
data: {
status: 'cancelled',
updatedAt: new Date(),
},
include: {
audiobook: true,
},
});
return NextResponse.json({
success: true,
request: updated,
message: 'Request cancelled successfully',
});
} else if (action === 'retry') {
// Retry failed request - allow users to retry their own warn/failed requests
// Only allow retry for failed, warn, or awaiting_* statuses
const retryableStatuses = ['failed', 'warn', 'awaiting_search', 'awaiting_import'];
if (!retryableStatuses.includes(requestRecord.status)) {
return NextResponse.json(
{
error: 'ValidationError',
message: `Cannot retry request with status: ${requestRecord.status}`,
},
{ status: 400 }
);
}
// Determine which job to trigger based on the current status
const { getJobQueueService } = await import('@/lib/services/job-queue.service');
const jobQueue = getJobQueueService();
let jobType: string;
let updated;
if (requestRecord.status === 'warn' || requestRecord.status === 'awaiting_import') {
// Retry import
const requestWithData = await prisma.request.findUnique({
where: { id },
include: {
audiobook: true,
downloadHistory: {
where: { selected: true },
orderBy: { createdAt: 'desc' },
take: 1,
},
},
});
if (!requestWithData || !requestWithData.downloadHistory[0]) {
return NextResponse.json(
{
error: 'ValidationError',
message: 'No download history found, cannot retry import',
},
{ status: 400 }
);
}
const downloadHistory = requestWithData.downloadHistory[0];
// Get download path from qBittorrent
const { getQBittorrentService } = await import('@/lib/integrations/qbittorrent.service');
const qbt = await getQBittorrentService();
const torrent = await qbt.getTorrent(downloadHistory.downloadClientId!);
const downloadPath = `${torrent.save_path}/${torrent.name}`;
await jobQueue.addOrganizeJob(
id,
requestWithData.audiobook.id,
downloadPath,
`/media/audiobooks/${requestWithData.audiobook.author}/${requestWithData.audiobook.title}`
);
updated = await prisma.request.update({
where: { id },
data: {
status: 'processing',
progress: 100,
errorMessage: null,
updatedAt: new Date(),
},
include: {
audiobook: true,
},
});
jobType = 'import';
} else {
// Retry search
const requestWithData = await prisma.request.findUnique({
where: { id },
include: {
audiobook: true,
},
});
if (!requestWithData) {
return NextResponse.json(
{ error: 'NotFound', message: 'Request not found' },
{ status: 404 }
);
}
await jobQueue.addSearchJob(id, {
id: requestWithData.audiobook.id,
title: requestWithData.audiobook.title,
author: requestWithData.audiobook.author,
});
updated = await prisma.request.update({
where: { id },
data: {
status: 'pending',
progress: 0,
errorMessage: null,
updatedAt: new Date(),
},
include: {
audiobook: true,
},
});
jobType = 'search';
}
return NextResponse.json({
success: true,
request: updated,
message: `Request retry initiated (${jobType})`,
});
}
return NextResponse.json(
{
error: 'ValidationError',
message: 'Invalid action',
},
{ status: 400 }
);
} catch (error) {
console.error('Failed to update request:', error);
return NextResponse.json(
{
error: 'UpdateError',
message: 'Failed to update request',
},
{ status: 500 }
);
}
});
}
/**
* DELETE /api/requests/[id]
* Delete a request (admin only)
*/
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
return requireAuth(request, async (req: AuthenticatedRequest) => {
try {
if (!req.user) {
return NextResponse.json(
{ error: 'Unauthorized', message: 'User not authenticated' },
{ status: 401 }
);
}
if (req.user.role !== 'admin') {
return NextResponse.json(
{ error: 'Forbidden', message: 'Admin access required' },
{ status: 403 }
);
}
const { id } = await params;
await prisma.request.delete({
where: { id },
});
return NextResponse.json({
success: true,
message: 'Request deleted successfully',
});
} catch (error) {
console.error('Failed to delete request:', error);
return NextResponse.json(
{
error: 'DeleteError',
message: 'Failed to delete request',
},
{ status: 500 }
);
}
});
}
@@ -0,0 +1,106 @@
/**
* Component: Select Torrent API
* Documentation: documentation/phase3/prowlarr.md
*/
import { NextRequest, NextResponse } from 'next/server';
import { requireAuth, AuthenticatedRequest } from '@/lib/middleware/auth';
import { prisma } from '@/lib/db';
import { getJobQueueService } from '@/lib/services/job-queue.service';
import { TorrentResult } from '@/lib/utils/ranking-algorithm';
/**
* POST /api/requests/[id]/select-torrent
* Select and download a specific torrent from interactive search results
*/
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
return requireAuth(request, async (req: AuthenticatedRequest) => {
try {
if (!req.user) {
return NextResponse.json(
{ error: 'Unauthorized', message: 'User not authenticated' },
{ status: 401 }
);
}
const { id } = await params;
const body = await req.json();
const { torrent } = body as { torrent: TorrentResult };
if (!torrent) {
return NextResponse.json(
{ error: 'ValidationError', message: 'Torrent data is required' },
{ status: 400 }
);
}
const requestRecord = await prisma.request.findUnique({
where: { id },
include: {
audiobook: true,
},
});
if (!requestRecord) {
return NextResponse.json(
{ error: 'NotFound', message: 'Request not found' },
{ status: 404 }
);
}
// Check authorization
if (requestRecord.userId !== req.user.id && req.user.role !== 'admin') {
return NextResponse.json(
{ error: 'Forbidden', message: 'You do not have access to this request' },
{ status: 403 }
);
}
console.log(`[SelectTorrent] User selected torrent: ${torrent.title} for request ${id}`);
// Trigger download job with the selected torrent
const jobQueue = getJobQueueService();
await jobQueue.addDownloadJob(
id,
{
id: requestRecord.audiobook.id,
title: requestRecord.audiobook.title,
author: requestRecord.audiobook.author,
},
torrent
);
// Update request status
const updated = await prisma.request.update({
where: { id },
data: {
status: 'downloading',
progress: 0,
errorMessage: null,
updatedAt: new Date(),
},
include: {
audiobook: true,
},
});
return NextResponse.json({
success: true,
request: updated,
message: 'Torrent download initiated',
});
} catch (error) {
console.error('Failed to select torrent:', error);
return NextResponse.json(
{
error: 'DownloadError',
message: error instanceof Error ? error.message : 'Failed to initiate torrent download',
},
{ status: 500 }
);
}
});
}
+229
View File
@@ -0,0 +1,229 @@
/**
* 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 { getJobQueueService } from '@/lib/services/job-queue.service';
import { findPlexMatch } from '@/lib/utils/audiobook-matcher';
import { z } from 'zod';
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().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);
// Check if audiobook is already available in Plex library
const plexMatch = await findPlexMatch({
asin: audiobook.asin,
title: audiobook.title,
author: audiobook.author,
narrator: audiobook.narrator,
});
if (plexMatch) {
return NextResponse.json(
{
error: 'AlreadyAvailable',
message: 'This audiobook is already available in your Plex library',
plexGuid: plexMatch.plexGuid,
},
{ status: 409 }
);
}
// Try to find existing audiobook record by ASIN
let audiobookRecord = await prisma.audiobook.findFirst({
where: { audibleAsin: audiobook.asin },
});
// If not found, create new audiobook record
if (!audiobookRecord) {
audiobookRecord = await prisma.audiobook.create({
data: {
audibleAsin: audiobook.asin,
title: audiobook.title,
author: audiobook.author,
narrator: audiobook.narrator,
description: audiobook.description,
coverArtUrl: audiobook.coverArtUrl,
status: 'requested',
},
});
}
// Check if user already has a request for this audiobook
const existingRequest = await prisma.request.findUnique({
where: {
userId_audiobookId: {
userId: req.user.id,
audiobookId: audiobookRecord.id,
},
},
});
if (existingRequest) {
// Allow re-requesting if the status is failed, warn, or cancelled
const canReRequest = ['failed', 'warn', 'cancelled'].includes(existingRequest.status);
if (!canReRequest) {
return NextResponse.json(
{
error: 'DuplicateRequest',
message: 'You have already requested this audiobook',
request: existingRequest,
},
{ status: 409 }
);
}
// Delete the existing failed/warn/cancelled request
console.log(`[Requests] Deleting existing ${existingRequest.status} request ${existingRequest.id} to allow re-request`);
await prisma.request.delete({
where: { id: existingRequest.id },
});
}
// Create request
const newRequest = await prisma.request.create({
data: {
userId: req.user.id,
audiobookId: audiobookRecord.id,
status: 'pending',
progress: 0,
},
include: {
audiobook: true,
user: {
select: {
id: true,
plexUsername: true,
},
},
},
});
// Trigger search job
const jobQueue = getJobQueueService();
await jobQueue.addSearchJob(newRequest.id, {
id: audiobookRecord.id,
title: audiobookRecord.title,
author: audiobookRecord.author,
});
return NextResponse.json({
success: true,
request: newRequest,
}, { status: 201 });
} catch (error) {
console.error('Failed to create request:', 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 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;
}
const requests = await prisma.request.findMany({
where,
include: {
audiobook: true,
user: {
select: {
id: true,
plexUsername: true,
},
},
},
orderBy: { createdAt: 'desc' },
take: limit,
});
return NextResponse.json({
success: true,
requests,
count: requests.length,
});
} catch (error) {
console.error('Failed to get requests:', error);
return NextResponse.json(
{
error: 'FetchError',
message: 'Failed to fetch requests',
},
{ status: 500 }
);
}
});
}