/** * norabose.com import (docs/07, Q11 ★예): quiz index (year, peak, genre mask, level mask) + song details in batches of 50. * Raw responses are cached under rawDir so a re-run does not fetch again. 1.5s between requests. */ import { existsSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; import type { Database } from 'bun:sqlite'; import { Catalog, Job, sleep } from './catalog'; const BASE = 'https://norabose.com'; const UA = 'Mozilla/5.0 (music_quiz catalog; contact via mquiz.tkrmagid.kr)'; /** norabose genre bits (their bundle, genres-*.js) → our genre ids (docs/04 장르). */ const GENRE_BITS: [number, string | null][] = [ [1, 'ballad'], [2, 'dance'], [4, 'hiphop'], [8, 'rock'], [16, 'rnb'], [32, 'ost'], [64, 'folk'], [128, 'trot'], [256, 'indie'], [512, 'pop'], [1024, 'ost'], [2048, 'electronic'], [4096, 'kids'], [8192, 'jpop'], [16384, 'anime'], [32768, 'jazz'], [65536, null], [131072, 'kids'], [262144, 'classical'], [524288, 'jazz'], [1048576, 'jazz'], [2097152, 'classical'], [4194304, 'anime'], [8388608, 'classical'], [16777216, 'classical'], [33554432, null], ]; export function genresOf(mask: number): string[] { const out = new Set(); for (const [bit, id] of GENRE_BITS) if (mask & bit && id) out.add(id); // Region: their data is the Melon chart; POP / J-POP bits mark foreign songs, everything else is Korean. if (!out.has('pop') && !out.has('jpop')) out.add('kpop'); return [...out]; } /** * Provisional 1~10 level (real calculation is stage 9): norabose has 5 levels (bit mask, a song can be in several). * Lowest level L → 2L-1 for weekly top-10 songs, else 2L. */ export function provisionalLevel(levelMask: number, peak: number | null): number | null { for (let l = 1; l <= 5; l++) if (levelMask & (1 << (l - 1))) return Math.min(10, 2 * l - (peak !== null && peak <= 10 ? 1 : 0)); return null; } interface NbSong { id: number; title: string; genre: number; length: number | null; youtube_id: string | null; mv_id: string | null; } interface NbBatch { songs: NbSong[]; song_artists: { song_id: number; artist_id: number; role_code: number }[]; artist_names: { artist_id: number; name: string }[]; lyrics: { song_id: number; text: string }[]; } async function getJson(url: string): Promise { for (let attempt = 0; ; attempt++) { const res = await fetch(url, { headers: { 'user-agent': UA }, signal: AbortSignal.timeout(20_000) }); if (res.ok) return (await res.json()) as T; if (attempt >= 1 || res.status === 404) throw new Error(`${url} → ${res.status}`); await sleep(5000 * (attempt + 1)); } } /** Their API answers 500 for a batch that holds a broken song: split the batch until only the broken ids are left out. */ async function fetchBatch(ids: number[], delayMs: number, skipped: number[]): Promise { try { const b = await getJson(`${BASE}/api/norabose/songs/${ids.join(',')}`); await sleep(delayMs); return b; } catch (e) { if (!/→ 5\d\d$/.test((e as Error).message)) throw e; await sleep(delayMs); if (ids.length === 1) { skipped.push(ids[0]!); return { songs: [], song_artists: [], artist_names: [], lyrics: [] }; } const half = Math.ceil(ids.length / 2); const [x, y] = [await fetchBatch(ids.slice(0, half), delayMs, skipped), await fetchBatch(ids.slice(half), delayMs, skipped)]; return { songs: [...x.songs, ...y.songs], song_artists: [...x.song_artists, ...y.song_artists], artist_names: [...x.artist_names, ...y.artist_names], lyrics: [...x.lyrics, ...y.lyrics] }; } } export async function importNorabose(db: Database, rawDir: string, opts: { limit?: number; delayMs?: number } = {}) { const dir = join(rawDir, 'norabose'); mkdirSync(dir, { recursive: true }); const indexPath = join(dir, 'quiz-index.json'); if (!existsSync(indexPath)) await Bun.write(indexPath, JSON.stringify(await getJson(`${BASE}/data/quiz-index.json`))); const index = (await Bun.file(indexPath).json()) as { songs: [number, number, number, number, number, string][] }; const rows = opts.limit ? index.songs.slice(0, opts.limit) : index.songs; const meta = new Map(rows.map((r) => [r[0], { year: r[1], peak: r[2], genreMask: r[3], levelMask: r[4] }])); const ids = [...meta.keys()]; const job = new Job(db, 'import-norabose', ids.length); const catalog = new Catalog(db); let created = 0; let done = 0; try { for (let i = 0; i < ids.length; i += 50) { const chunk = ids.slice(i, i + 50); const file = join(dir, `songs-${chunk[0]}-${chunk.length}.json`); if (!existsSync(file)) { const skipped: number[] = []; await Bun.write(file, JSON.stringify(await fetchBatch(chunk, opts.delayMs ?? 1500, skipped))); if (skipped.length) job.log(`norabose: skipped broken ids ${skipped.join(',')}`); } const b = (await Bun.file(file).json()) as NbBatch; const names = new Map(b.artist_names.map((a) => [a.artist_id, a.name])); const lyrics = new Map(b.lyrics.map((l) => [l.song_id, l.text.replace(/\\n/g, '\n')])); db.transaction(() => { for (const s of b.songs) { const m = meta.get(s.id); if (!m) continue; const singers = b.song_artists.filter((a) => a.song_id === s.id && a.role_code & 1).map((a) => ({ name: names.get(a.artist_id) ?? '?', melonArtistId: a.artist_id })); if (!singers.length) continue; const [songId, isNew] = catalog.upsert({ melonId: s.id, title: s.title, artists: singers, year: m.year, durationSec: s.length, peakRank: m.peak, mvYoutubeId: s.mv_id, genres: genresOf(m.genreMask | s.genre), lyrics: lyrics.get(s.id) ?? null, source: 'norabose', ref: String(s.id), }); if (isNew) created++; // Their youtube_id is often a fan lyric video: keep it only as a fallback candidate (docs/08). if (s.youtube_id) { db.query("INSERT OR IGNORE INTO youtube_candidates (song_id, video_id, score, source) VALUES (?, ?, 0, 'norabose')").run(songId, s.youtube_id); } catalog.signal(songId, 'norabose_level_mask', m.levelMask); catalog.signal(songId, 'norabose_peak', m.peak); const lv = provisionalLevel(m.levelMask, m.peak); if (lv) catalog.autoLevel(songId, 'all', lv); } })(); done += chunk.length; job.progress(done); if ((i / 50) % 20 === 0) job.log(`norabose ${done}/${ids.length}, new ${created}`); } job.log(`norabose done: ${done} songs, new ${created}`); job.finish('done'); } catch (e) { job.log(`failed: ${(e as Error).message}`); job.finish('failed'); throw e; } return { total: ids.length, created }; }