Merge branch 'main' into feature/per-user-api-tokens

This commit is contained in:
kikootwo
2026-03-04 13:26:57 -05:00
committed by GitHub
50 changed files with 4728 additions and 434 deletions
+43
View File
@@ -12,6 +12,7 @@ import { prisma } from '@/lib/db';
import { getJobQueueService } from '@/lib/services/job-queue.service';
import { RMABLogger } from '@/lib/utils/logger';
import { AUDIO_EXTENSIONS } from '@/lib/constants/audio-formats';
import { getAudibleService } from '@/lib/integrations/audible.service';
const logger = RMABLogger.create('API.Admin.ManualImport');
@@ -174,6 +175,48 @@ export async function POST(request: NextRequest) {
);
}
// Enrich missing series/year data from Audnexus (mirrors request-creator.service.ts)
if (audiobook.audibleAsin && (!audiobook.series || !audiobook.year)) {
try {
const audibleService = getAudibleService();
const audnexusData = await audibleService.getAudiobookDetails(audiobook.audibleAsin);
if (audnexusData) {
const updates: Record<string, any> = {};
if (!audiobook.series && audnexusData.series) {
updates.series = audnexusData.series;
}
if (!audiobook.seriesPart && audnexusData.seriesPart) {
updates.seriesPart = audnexusData.seriesPart;
}
if (!audiobook.seriesAsin && audnexusData.seriesAsin) {
updates.seriesAsin = audnexusData.seriesAsin;
}
if (!audiobook.year && audnexusData.releaseDate) {
const releaseYear = new Date(audnexusData.releaseDate).getFullYear();
if (!isNaN(releaseYear)) {
updates.year = releaseYear;
}
}
if (!audiobook.narrator && audnexusData.narrator) {
updates.narrator = audnexusData.narrator;
}
if (Object.keys(updates).length > 0) {
await prisma.audiobook.update({
where: { id: audiobook.id },
data: updates,
});
logger.info(`Enriched audiobook metadata from Audnexus for ASIN ${audiobook.audibleAsin}`, updates);
}
}
} catch (error) {
// Non-fatal: series enrichment failure should never block the import
logger.warn(`Failed to enrich metadata from Audnexus for ASIN ${audiobook.audibleAsin}: ${error instanceof Error ? error.message : String(error)}`);
}
}
// Check for existing requests
const existingRequest = await prisma.request.findFirst({
where: {
+16 -7
View File
@@ -7,7 +7,7 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { enrichAudiobooksWithMatches } from '@/lib/utils/audiobook-matcher';
import { enrichAudiobooksWithMatches, getAvailableAsins } from '@/lib/utils/audiobook-matcher';
import { getCurrentUser } from '@/lib/middleware/auth';
import { RMABLogger } from '@/lib/utils/logger';
@@ -24,6 +24,7 @@ export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const page = parseInt(searchParams.get('page') || '1', 10);
const limit = parseInt(searchParams.get('limit') || '20', 10);
const hideAvailable = searchParams.get('hideAvailable') === 'true';
// Validate pagination parameters
if (page < 1 || limit < 1 || limit > 100) {
@@ -38,12 +39,22 @@ export async function GET(request: NextRequest) {
const skip = (page - 1) * limit;
// When hideAvailable is enabled, exclude ASINs that are in the library or have completed requests
let excludedAsins: string[] = [];
if (hideAvailable) {
const availableSet = await getAvailableAsins();
excludedAsins = [...availableSet];
}
const whereClause = {
isNewRelease: true,
...(excludedAsins.length > 0 ? { asin: { notIn: excludedAsins } } : {}),
};
// Query audible_cache for new release audiobooks
const [audiobooks, totalCount] = await Promise.all([
prisma.audibleCache.findMany({
where: {
isNewRelease: true,
},
where: whereClause,
orderBy: {
newReleaseRank: 'asc',
},
@@ -66,9 +77,7 @@ export async function GET(request: NextRequest) {
},
}),
prisma.audibleCache.count({
where: {
isNewRelease: true,
},
where: whereClause,
}),
]);
+16 -7
View File
@@ -7,7 +7,7 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { enrichAudiobooksWithMatches } from '@/lib/utils/audiobook-matcher';
import { enrichAudiobooksWithMatches, getAvailableAsins } from '@/lib/utils/audiobook-matcher';
import { getCurrentUser } from '@/lib/middleware/auth';
import { RMABLogger } from '@/lib/utils/logger';
@@ -24,6 +24,7 @@ export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const page = parseInt(searchParams.get('page') || '1', 10);
const limit = parseInt(searchParams.get('limit') || '20', 10);
const hideAvailable = searchParams.get('hideAvailable') === 'true';
// Validate pagination parameters
if (page < 1 || limit < 1 || limit > 100) {
@@ -38,12 +39,22 @@ export async function GET(request: NextRequest) {
const skip = (page - 1) * limit;
// When hideAvailable is enabled, exclude ASINs that are in the library or have completed requests
let excludedAsins: string[] = [];
if (hideAvailable) {
const availableSet = await getAvailableAsins();
excludedAsins = [...availableSet];
}
const whereClause = {
isPopular: true,
...(excludedAsins.length > 0 ? { asin: { notIn: excludedAsins } } : {}),
};
// Query audible_cache for popular audiobooks
const [audiobooks, totalCount] = await Promise.all([
prisma.audibleCache.findMany({
where: {
isPopular: true,
},
where: whereClause,
orderBy: {
popularRank: 'asc',
},
@@ -66,9 +77,7 @@ export async function GET(request: NextRequest) {
},
}),
prisma.audibleCache.count({
where: {
isPopular: true,
},
where: whereClause,
}),
]);
+12 -2
View File
@@ -6,6 +6,8 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAudibleService } from '@/lib/integrations/audible.service';
import { enrichAudiobooksWithMatches } from '@/lib/utils/audiobook-matcher';
import { deduplicateAndCollectGroups } from '@/lib/utils/deduplicate-audiobooks';
import { persistDedupGroups } from '@/lib/services/works.service';
import { getCurrentUser } from '@/lib/middleware/auth';
import { RMABLogger } from '@/lib/utils/logger';
@@ -38,14 +40,22 @@ export async function GET(request: NextRequest) {
const currentUser = getCurrentUser(request);
const userId = currentUser?.sub || undefined;
// Deduplicate before enrichment to avoid wasted DB queries on duplicate entries
const { books: dedupedResults, groups } = deduplicateAndCollectGroups(results.results);
// Fire-and-forget: persist dedup groups to works table for cross-ASIN matching
if (groups.length > 0) {
persistDedupGroups(groups).catch(() => {});
}
// Enrich search results with availability and request status information
const enrichedResults = await enrichAudiobooksWithMatches(results.results, userId);
const enrichedResults = await enrichAudiobooksWithMatches(dedupedResults, userId);
return NextResponse.json({
success: true,
query: results.query,
results: enrichedResults,
totalResults: results.totalResults,
totalResults: enrichedResults.length,
page: results.page,
hasMore: results.hasMore,
});
+3 -1
View File
@@ -38,9 +38,11 @@ export async function POST(request: NextRequest) {
);
}
const normalizedUsername = username.trim().toLowerCase();
// Find user by local admin identifier
const user = await prisma.user.findUnique({
where: { plexId: `local-${username}` },
where: { plexId: `local-${normalizedUsername}` },
});
if (!user) {
+12 -2
View File
@@ -6,6 +6,8 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAudibleService } from '@/lib/integrations/audible.service';
import { enrichAudiobooksWithMatches } from '@/lib/utils/audiobook-matcher';
import { deduplicateAndCollectGroups } from '@/lib/utils/deduplicate-audiobooks';
import { persistDedupGroups } from '@/lib/services/works.service';
import { getCurrentUser } from '@/lib/middleware/auth';
import { RMABLogger } from '@/lib/utils/logger';
@@ -53,9 +55,17 @@ export async function GET(
const audibleService = getAudibleService();
const result = await audibleService.searchByAuthorAsin(authorName.trim(), asin, page);
// Deduplicate before enrichment to avoid wasted DB queries on duplicate entries
const { books: dedupedBooks, groups } = deduplicateAndCollectGroups(result.books);
// Fire-and-forget: persist dedup groups to works table for cross-ASIN matching
if (groups.length > 0) {
persistDedupGroups(groups).catch(() => {});
}
// Enrich with library availability and request status
const userId = currentUser.sub || undefined;
const enrichedBooks = await enrichAudiobooksWithMatches(result.books, userId);
const enrichedBooks = await enrichAudiobooksWithMatches(dedupedBooks, userId);
logger.info(`Author books complete: "${authorName}" → ${enrichedBooks.length} books (page ${page})`);
@@ -64,7 +74,7 @@ export async function GET(
books: enrichedBooks,
authorName: authorName.trim(),
authorAsin: asin,
totalBooks: result.totalResults || enrichedBooks.length,
totalBooks: enrichedBooks.length,
hasMore: result.hasMore,
page: result.page,
});
+11 -1
View File
@@ -8,6 +8,8 @@ import { getCurrentUser } from '@/lib/middleware/auth';
import { RMABLogger } from '@/lib/utils/logger';
import { scrapeSeriesPage } from '@/lib/integrations/audible-series';
import { enrichAudiobooksWithMatches } from '@/lib/utils/audiobook-matcher';
import { deduplicateAndCollectGroups } from '@/lib/utils/deduplicate-audiobooks';
import { persistDedupGroups } from '@/lib/services/works.service';
const logger = RMABLogger.create('API.Series.Detail');
@@ -49,9 +51,17 @@ export async function GET(
);
}
// Deduplicate before enrichment to avoid wasted DB queries on duplicate entries
const { books: dedupedBooks, groups } = deduplicateAndCollectGroups(detail.books);
// Fire-and-forget: persist dedup groups to works table for cross-ASIN matching
if (groups.length > 0) {
persistDedupGroups(groups).catch(() => {});
}
// Enrich books with library availability and request status
const userId = currentUser.sub || undefined;
const enrichedBooks = await enrichAudiobooksWithMatches(detail.books, userId);
const enrichedBooks = await enrichAudiobooksWithMatches(dedupedBooks, userId);
logger.info(`Series detail complete: "${detail.title}" (${enrichedBooks.length} books, page ${page})`);
+3 -2
View File
@@ -140,14 +140,15 @@ export async function POST(request: NextRequest) {
);
}
const normalizedAdminUsername = admin.username.trim().toLowerCase();
const hashedPassword = await bcrypt.hash(admin.password, 10);
const encryptionService = getEncryptionService();
const encryptedPassword = encryptionService.encrypt(hashedPassword);
adminUser = await prisma.user.create({
data: {
plexId: `local-${admin.username}`,
plexUsername: admin.username,
plexId: `local-${normalizedAdminUsername}`,
plexUsername: normalizedAdminUsername,
plexEmail: null,
role: 'admin',
isSetupAdmin: true, // Mark as setup admin - role cannot be changed
@@ -0,0 +1,52 @@
/**
* Component: Watched Author Delete Route
* Documentation: documentation/features/watched-lists.md
*/
import { NextRequest, NextResponse } from 'next/server';
import { requireAuth, AuthenticatedRequest } from '@/lib/middleware/auth';
import { prisma } from '@/lib/db';
import { RMABLogger } from '@/lib/utils/logger';
const logger = RMABLogger.create('API.WatchedAuthors');
/**
* DELETE /api/user/watched-authors/[id]
* Remove an author from the user's watch list (ownership check)
*/
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' }, { status: 401 });
}
const { id } = await params;
const watched = await prisma.watchedAuthor.findUnique({
where: { id },
});
if (!watched) {
return NextResponse.json({ error: 'Watched author not found' }, { status: 404 });
}
// Ownership check
if (watched.userId !== req.user.id) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
await prisma.watchedAuthor.delete({ where: { id } });
logger.info(`User ${req.user.id} stopped watching author "${watched.authorName}" (${watched.authorAsin})`);
return NextResponse.json({ success: true });
} catch (error) {
logger.error('Failed to delete watched author', { error: error instanceof Error ? error.message : String(error) });
return NextResponse.json({ error: 'Failed to delete watched author' }, { status: 500 });
}
});
}
+125
View File
@@ -0,0 +1,125 @@
/**
* Component: Watched Authors API Routes
* Documentation: documentation/features/watched-lists.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 { z } from 'zod';
import { RMABLogger } from '@/lib/utils/logger';
const logger = RMABLogger.create('API.WatchedAuthors');
const AddWatchedAuthorSchema = z.object({
authorAsin: z.string().regex(/^[A-Z0-9]{10}$/, 'Invalid author ASIN'),
authorName: z.string().min(1).max(500),
coverArtUrl: z.string().url().optional(),
});
/**
* GET /api/user/watched-authors
* List the current user's watched authors
*/
export async function GET(request: NextRequest) {
return requireAuth(request, async (req: AuthenticatedRequest) => {
try {
if (!req.user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const authors = await prisma.watchedAuthor.findMany({
where: { userId: req.user.id },
orderBy: { createdAt: 'desc' },
});
return NextResponse.json({
success: true,
authors: authors.map((a) => ({
id: a.id,
authorAsin: a.authorAsin,
authorName: a.authorName,
coverArtUrl: a.coverArtUrl,
lastCheckedAt: a.lastCheckedAt,
createdAt: a.createdAt,
})),
});
} catch (error) {
logger.error('Failed to list watched authors', { error: error instanceof Error ? error.message : String(error) });
return NextResponse.json({ error: 'Failed to list watched authors' }, { status: 500 });
}
});
}
/**
* POST /api/user/watched-authors
* Add an author to the user's watch list
*/
export async function POST(request: NextRequest) {
return requireAuth(request, async (req: AuthenticatedRequest) => {
try {
if (!req.user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const body = await req.json();
const { authorAsin, authorName, coverArtUrl } = AddWatchedAuthorSchema.parse(body);
// Check for duplicate
const existing = await prisma.watchedAuthor.findUnique({
where: { userId_authorAsin: { userId: req.user.id, authorAsin } },
});
if (existing) {
return NextResponse.json(
{ error: 'AlreadyWatching', message: 'You are already watching this author' },
{ status: 409 }
);
}
const watched = await prisma.watchedAuthor.create({
data: {
userId: req.user.id,
authorAsin,
authorName,
coverArtUrl: coverArtUrl || null,
},
});
logger.info(`User ${req.user.id} started watching author "${authorName}" (${authorAsin})`);
// Trigger immediate targeted check for this author (fire-and-forget)
try {
const jobQueue = getJobQueueService();
await jobQueue.addCheckWatchedItemJob(req.user.id, undefined, authorAsin);
logger.info(`Triggered immediate check for watched author "${authorName}" (${authorAsin})`);
} catch (error) {
logger.error('Failed to trigger immediate watched author check', { error: error instanceof Error ? error.message : String(error) });
}
return NextResponse.json({
success: true,
author: {
id: watched.id,
authorAsin: watched.authorAsin,
authorName: watched.authorName,
coverArtUrl: watched.coverArtUrl,
lastCheckedAt: watched.lastCheckedAt,
createdAt: watched.createdAt,
},
}, { status: 201 });
} catch (error) {
logger.error('Failed to add watched author', { 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: 'Failed to add watched author' }, { status: 500 });
}
});
}
@@ -0,0 +1,52 @@
/**
* Component: Watched Series Delete Route
* Documentation: documentation/features/watched-lists.md
*/
import { NextRequest, NextResponse } from 'next/server';
import { requireAuth, AuthenticatedRequest } from '@/lib/middleware/auth';
import { prisma } from '@/lib/db';
import { RMABLogger } from '@/lib/utils/logger';
const logger = RMABLogger.create('API.WatchedSeries');
/**
* DELETE /api/user/watched-series/[id]
* Remove a series from the user's watch list (ownership check)
*/
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' }, { status: 401 });
}
const { id } = await params;
const watched = await prisma.watchedSeries.findUnique({
where: { id },
});
if (!watched) {
return NextResponse.json({ error: 'Watched series not found' }, { status: 404 });
}
// Ownership check
if (watched.userId !== req.user.id) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
await prisma.watchedSeries.delete({ where: { id } });
logger.info(`User ${req.user.id} stopped watching series "${watched.seriesTitle}" (${watched.seriesAsin})`);
return NextResponse.json({ success: true });
} catch (error) {
logger.error('Failed to delete watched series', { error: error instanceof Error ? error.message : String(error) });
return NextResponse.json({ error: 'Failed to delete watched series' }, { status: 500 });
}
});
}
+125
View File
@@ -0,0 +1,125 @@
/**
* Component: Watched Series API Routes
* Documentation: documentation/features/watched-lists.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 { z } from 'zod';
import { RMABLogger } from '@/lib/utils/logger';
const logger = RMABLogger.create('API.WatchedSeries');
const AddWatchedSeriesSchema = z.object({
seriesAsin: z.string().regex(/^[A-Z0-9]{10}$/, 'Invalid series ASIN'),
seriesTitle: z.string().min(1).max(500),
coverArtUrl: z.string().url().optional(),
});
/**
* GET /api/user/watched-series
* List the current user's watched series
*/
export async function GET(request: NextRequest) {
return requireAuth(request, async (req: AuthenticatedRequest) => {
try {
if (!req.user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const series = await prisma.watchedSeries.findMany({
where: { userId: req.user.id },
orderBy: { createdAt: 'desc' },
});
return NextResponse.json({
success: true,
series: series.map((s) => ({
id: s.id,
seriesAsin: s.seriesAsin,
seriesTitle: s.seriesTitle,
coverArtUrl: s.coverArtUrl,
lastCheckedAt: s.lastCheckedAt,
createdAt: s.createdAt,
})),
});
} catch (error) {
logger.error('Failed to list watched series', { error: error instanceof Error ? error.message : String(error) });
return NextResponse.json({ error: 'Failed to list watched series' }, { status: 500 });
}
});
}
/**
* POST /api/user/watched-series
* Add a series to the user's watch list
*/
export async function POST(request: NextRequest) {
return requireAuth(request, async (req: AuthenticatedRequest) => {
try {
if (!req.user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const body = await req.json();
const { seriesAsin, seriesTitle, coverArtUrl } = AddWatchedSeriesSchema.parse(body);
// Check for duplicate
const existing = await prisma.watchedSeries.findUnique({
where: { userId_seriesAsin: { userId: req.user.id, seriesAsin } },
});
if (existing) {
return NextResponse.json(
{ error: 'AlreadyWatching', message: 'You are already watching this series' },
{ status: 409 }
);
}
const watched = await prisma.watchedSeries.create({
data: {
userId: req.user.id,
seriesAsin,
seriesTitle,
coverArtUrl: coverArtUrl || null,
},
});
logger.info(`User ${req.user.id} started watching series "${seriesTitle}" (${seriesAsin})`);
// Trigger immediate targeted check for this series (fire-and-forget)
try {
const jobQueue = getJobQueueService();
await jobQueue.addCheckWatchedItemJob(req.user.id, seriesAsin);
logger.info(`Triggered immediate check for watched series "${seriesTitle}" (${seriesAsin})`);
} catch (error) {
logger.error('Failed to trigger immediate watched series check', { error: error instanceof Error ? error.message : String(error) });
}
return NextResponse.json({
success: true,
series: {
id: watched.id,
seriesAsin: watched.seriesAsin,
seriesTitle: watched.seriesTitle,
coverArtUrl: watched.coverArtUrl,
lastCheckedAt: watched.lastCheckedAt,
createdAt: watched.createdAt,
},
}, { status: 201 });
} catch (error) {
logger.error('Failed to add watched series', { 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: 'Failed to add watched series' }, { status: 500 });
}
});
}