Files
music_quiz/apps/server/src/collector/catalog.ts

120 lines
6.2 KiB
TypeScript

/** Writes into the song catalog (docs/07). Idempotent: re-running an import never duplicates songs. */
import type { Database } from 'bun:sqlite';
import { songMatchKey } from '@mq/shared';
import { decodeEntities } from './text';
export interface SongInput {
melonId?: number | null;
title: string;
artists: { name: string; melonArtistId?: number | null }[];
year?: number | null;
durationSec?: number | null;
peakRank?: number | null;
mvYoutubeId?: string | null;
genres?: string[];
lyrics?: string | null;
source: string;
ref: string;
}
export class Catalog {
constructor(private db: Database) {}
private artistId(name: string, melonArtistId: number | null | undefined): number {
if (melonArtistId) {
const r = this.db.query<{ id: number }, [number]>('SELECT id FROM artists WHERE melon_artist_id = ?').get(melonArtistId);
if (r) return r.id;
return Number(this.db.query('INSERT INTO artists (melon_artist_id, name) VALUES (?, ?)').run(melonArtistId, name).lastInsertRowid);
}
const r = this.db.query<{ id: number }, [string]>('SELECT id FROM artists WHERE name = ? ORDER BY melon_artist_id IS NULL LIMIT 1').get(name);
if (r) return r.id;
return Number(this.db.query('INSERT INTO artists (name) VALUES (?)').run(name).lastInsertRowid);
}
/** Finds the song by Melon id, else by match key; creates it when new. Returns [id, created]. */
upsert(input: SongInput, now = Date.now()): [number, boolean] {
// Sources hand us HTML-escaped text now and then (norabose `Salty &amp; Sweet`): store what people read.
const s = { ...input, title: decodeEntities(input.title), artists: input.artists.map((a) => ({ ...a, name: decodeEntities(a.name) })) };
return this.db.transaction((): [number, boolean] => {
const artist = s.artists.map((a) => a.name).join(', ');
const key = songMatchKey(s.title, artist);
let row = s.melonId ? this.db.query<{ id: number }, [number]>('SELECT id FROM songs WHERE melon_id = ?').get(s.melonId) : null;
row ??= this.db.query<{ id: number }, [string]>('SELECT id FROM songs WHERE match_key = ? AND deleted_at IS NULL ORDER BY id LIMIT 1').get(key);
let id: number;
let created = false;
if (row) {
id = row.id;
// Fill gaps only: never overwrite what an earlier source or an admin already set.
this.db
.query(
`UPDATE songs SET melon_id = COALESCE(melon_id, ?), year = COALESCE(year, ?), duration_sec = COALESCE(duration_sec, ?),
peak_rank = COALESCE(peak_rank, ?), mv_youtube_id = COALESCE(mv_youtube_id, ?), updated_at = ? WHERE id = ?`,
)
.run(s.melonId ?? null, s.year ?? null, s.durationSec ?? null, s.peakRank ?? null, s.mvYoutubeId ?? null, now, id);
} else {
id = Number(
this.db
.query(
`INSERT INTO songs (melon_id, title, artist, year, duration_sec, peak_rank, mv_youtube_id, match_key, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(s.melonId ?? null, s.title, artist, s.year ?? null, s.durationSec ?? null, s.peakRank ?? null, s.mvYoutubeId ?? null, key, now, now).lastInsertRowid,
);
created = true;
s.artists.forEach((a) => {
this.db.query('INSERT OR IGNORE INTO song_artists (song_id, artist_id, role) VALUES (?, ?, ?)').run(id, this.artistId(a.name, a.melonArtistId), 'main');
});
}
// Genres an admin has set (even to none) are final: imports only add genres to songs nobody edited.
const adminGenres = this.db.query<{ g: string | null }, [number]>('SELECT genres_source g FROM songs WHERE id = ?').get(id)?.g === 'admin';
if (!adminGenres) for (const g of s.genres ?? []) this.db.query('INSERT OR IGNORE INTO song_genres (song_id, genre_id, source) VALUES (?, ?, ?)').run(id, g, s.source);
if (s.lyrics) this.db.query('INSERT OR IGNORE INTO lyrics (song_id, text, source, fetched_at) VALUES (?, ?, ?, ?)').run(id, s.lyrics, s.source, now);
this.db.query('INSERT OR IGNORE INTO song_sources (song_id, source, ref) VALUES (?, ?, ?)').run(id, s.source, s.ref);
return [id, created];
})();
}
signal(songId: number, kind: string, value: number, now = Date.now()): void {
this.db
.query('INSERT INTO signals (song_id, kind, value, fetched_at) VALUES (?, ?, ?, ?) ON CONFLICT(song_id, kind) DO UPDATE SET value = excluded.value, fetched_at = excluded.fetched_at')
.run(songId, kind, value, now);
}
/** Automatic level; an admin-set level for the scope is never overwritten. */
autoLevel(songId: number, scope: string, level: number): void {
this.db
.query(`INSERT INTO song_levels (song_id, scope, level, source) VALUES (?, ?, ?, 'auto') ON CONFLICT(song_id, scope) DO UPDATE SET level = excluded.level WHERE song_levels.source = 'auto'`)
.run(songId, scope, level);
}
}
/** The job of this process, for a clean stop on SIGTERM (admin 수집 → 멈추기). */
export let currentJob: Job | null = null;
export class Job {
readonly id: number;
constructor(
private db: Database,
kind: string,
total = 0,
) {
// Only one runner per kind: a row left 'running' by a killed process is stale.
this.db.query("UPDATE collect_jobs SET status = 'stopped', finished_at = ? WHERE kind = ? AND status = 'running'").run(Date.now(), kind);
this.id = Number(this.db.query("INSERT INTO collect_jobs (kind, status, total, started_at, pid) VALUES (?, 'running', ?, ?, ?)").run(kind, total, Date.now(), process.pid).lastInsertRowid);
currentJob = this;
}
progress(done: number, total?: number): void {
this.db.query('UPDATE collect_jobs SET done = ?, total = COALESCE(?, total) WHERE id = ?').run(done, total ?? null, this.id);
}
log(line: string): void {
console.log(line);
// keep the last ~20KB of log
this.db.query("UPDATE collect_jobs SET log = substr(log || ? || char(10), -20000) WHERE id = ?").run(`${new Date().toISOString().slice(11, 19)} ${line}`, this.id);
}
finish(status: 'done' | 'failed' | 'stopped'): void {
this.db.query('UPDATE collect_jobs SET status = ?, finished_at = ? WHERE id = ?').run(status, Date.now(), this.id);
}
}
export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));