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 }
);
}
});
}