79 lines
2.7 KiB
TypeScript
79 lines
2.7 KiB
TypeScript
|
|
import { NextResponse } from 'next/server';
|
|
import { PrismaClient } from '@prisma/client';
|
|
import { requireAdminAuth } from '@/lib/auth';
|
|
import { getReleaseYearFromItunes } from '@/lib/itunes';
|
|
|
|
const prisma = new PrismaClient();
|
|
|
|
// Helper to delay execution to avoid rate limits
|
|
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
|
|
|
|
export async function POST(request: Request) {
|
|
// Check authentication
|
|
const authError = await requireAdminAuth(request as any);
|
|
if (authError) return authError;
|
|
|
|
try {
|
|
const { offset = 0, limit = 20 } = await request.json();
|
|
|
|
// Fetch batch of songs
|
|
const songs = await prisma.song.findMany({
|
|
select: { id: true, title: true, artist: true },
|
|
orderBy: { id: 'asc' },
|
|
skip: offset,
|
|
take: limit
|
|
});
|
|
|
|
const totalSongs = await prisma.song.count();
|
|
|
|
console.log(`Processing batch: offset=${offset}, limit=${limit}, found=${songs.length}`);
|
|
|
|
let updatedCount = 0;
|
|
let failedCount = 0;
|
|
let skippedCount = 0;
|
|
const results = [];
|
|
|
|
for (const song of songs) {
|
|
try {
|
|
// Rate limiting: wait 2000ms between requests to be safe (iTunes can be strict)
|
|
await sleep(2000);
|
|
|
|
const year = await getReleaseYearFromItunes(song.artist, song.title);
|
|
|
|
if (year) {
|
|
await prisma.song.update({
|
|
where: { id: song.id },
|
|
data: { releaseYear: year }
|
|
});
|
|
updatedCount++;
|
|
results.push({ id: song.id, title: song.title, artist: song.artist, year, status: 'updated' });
|
|
} else {
|
|
skippedCount++;
|
|
results.push({ id: song.id, title: song.title, artist: song.artist, status: 'not_found' });
|
|
}
|
|
} catch (error) {
|
|
console.error(`Failed to update year for ${song.title} - ${song.artist}:`, error);
|
|
failedCount++;
|
|
results.push({ id: song.id, title: song.title, artist: song.artist, status: 'error' });
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
processed: songs.length,
|
|
total: totalSongs,
|
|
hasMore: offset + songs.length < totalSongs,
|
|
nextOffset: offset + songs.length,
|
|
updated: updatedCount,
|
|
failed: failedCount,
|
|
skipped: skippedCount,
|
|
results
|
|
});
|
|
|
|
} catch (error) {
|
|
console.error('Error refreshing release years:', error);
|
|
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
|
|
}
|
|
}
|