Files
music_quiz/apps/server/src/songs/youtube-review.ts

251 lines
12 KiB
TypeScript

/**
* 관리자 → 원곡 찾기: what the YouTube matcher decided, song by song, so an admin can check it while it runs.
* Tabs split "searched but nothing found" from "not searched yet" (both are youtube_status 'none').
*/
import type { Database } from 'bun:sqlite';
import { learnArtistAliases } from '../collector/artist-aliases';
import { notConfidentReasons, scoreResult, type ArtistAliases } from '../collector/score';
let aliasCache: { db: Database; at: number; map: ArtistAliases } | null = null;
/** Learnt artist names change only when songs get confirmed: re-learn at most every 10 minutes. */
export function aliasesOf(db: Database, now = Date.now()): ArtistAliases {
if (!aliasCache || aliasCache.db !== db || now - aliasCache.at > 600_000) aliasCache = { db, at: now, map: learnArtistAliases(db) };
return aliasCache.map;
}
type CandInfo = { video_id: string; title: string | null; channel: string | null; duration_sec: number | null; source: string };
/**
* Why the matcher would not confirm this result, in plain words ("가수 다름: Ashiyane", "길이 40초 차이");
* empty when it would. norabose videos carry no title/artist/length, so they are only labelled as such.
*/
export function explainCandidate(db: Database, song: { title: string; artist: string; duration_sec: number | null }, c: CandInfo): string[] {
if (c.source === 'norabose' && !c.title) return ['노라보세 영상이라 제목·가수·길이 정보 없음'];
const scored = scoreResult(
{ title: song.title, artist: song.artist, durationSec: song.duration_sec },
{ videoId: c.video_id, title: c.title ?? '', artists: c.channel ?? '', album: null, durationSec: c.duration_sec },
-1,
aliasesOf(db),
);
return notConfidentReasons(scored);
}
export const REVIEW_TABS = ['matched', 'candidate', 'missing', 'noorig', 'dead', 'pending'] as const;
export type ReviewTab = (typeof REVIEW_TABS)[number];
const TRIED = "EXISTS (SELECT 1 FROM signals t WHERE t.song_id = s.id AND t.kind LIKE 'yt_tried_%')";
const ADMIN = "COALESCE(s.youtube_source, '') = 'admin'";
const TAB_WHERE: Record<ReviewTab, string> = {
matched: "s.youtube_status = 'matched'",
candidate: "s.youtube_status = 'candidate'",
// searched, nothing playable found; the matcher retries these after a week
missing: `s.youtube_status = 'none' AND NOT ${ADMIN} AND ${TRIED}`,
// an admin said there is no original: the matcher leaves them alone
noorig: `s.youtube_status = 'none' AND ${ADMIN}`,
dead: "s.youtube_status = 'dead'",
pending: `s.youtube_status = 'none' AND NOT ${ADMIN} AND NOT ${TRIED}`,
};
/** When the song was last looked at: the matcher's try or an admin's choice (재생 불가: when it broke). */
const TOUCHED = `MAX(COALESCE(s.youtube_checked_at, 0), COALESCE((SELECT MAX(t.value) FROM signals t WHERE t.song_id = s.id AND t.kind LIKE 'yt_tried_%'), 0))`;
export const REVIEW_PAGE = 50;
export function reviewCounts(db: Database): Record<ReviewTab, number> {
const cols = REVIEW_TABS.map((t) => `SUM(${TAB_WHERE[t]}) ${t}`).join(', ');
const r = db.query<Record<ReviewTab, number | null>, []>(`SELECT ${cols} FROM songs s WHERE s.deleted_at IS NULL`).get()!;
return Object.fromEntries(REVIEW_TABS.map((t) => [t, r[t] ?? 0])) as Record<ReviewTab, number>;
}
const pidAlive = (pid: number) => {
try {
process.kill(pid, 0);
return true;
} catch (e) {
return (e as NodeJS.ErrnoException).code === 'EPERM'; // there, owned by someone else
}
};
/** Speed and ETA are taken over the last 10 minutes, so a slow start or a 60s retry wait fades out. */
export const RATE_WINDOW = 10 * 60_000;
/**
* The latest match-youtube run, in detail: what it decided so far, how fast it goes, when it should end,
* whether its process is still there, the last songs it looked at, its log, and the runs before it.
*/
export function reviewJob(db: Database, now = Date.now(), alive: (pid: number) => boolean = pidAlive) {
type JobRow = { id: number; status: string; done: number; total: number; started_at: number; finished_at: number | null };
const history = db
.query<JobRow, []>("SELECT id, status, done, total, started_at, finished_at FROM collect_jobs WHERE kind = 'match-youtube' ORDER BY id DESC LIMIT 6")
.all();
const job = history[0];
if (!job) return null;
const { pid, log } = db.query<{ pid: number | null; log: string }, [number]>('SELECT pid, log FROM collect_jobs WHERE id = ?').get(job.id)!;
const running = job.status === 'running';
const end = job.finished_at ?? now + 1;
const tried = `t.kind LIKE 'yt_tried_%' AND t.value >= ? AND t.value <= ?`;
const r = db
.query<{ matched: number | null; candidate: number | null; none: number | null }, [number, number]>(
`SELECT SUM(s.youtube_status = 'matched') matched, SUM(s.youtube_status = 'candidate') candidate, SUM(s.youtube_status = 'none') none
FROM songs s WHERE s.deleted_at IS NULL AND EXISTS (SELECT 1 FROM signals t WHERE t.song_id = s.id AND ${tried})`,
)
.get(job.started_at, end)!;
const recent = db
.query<
{ id: number; title: string; artist: string; youtube_status: string; youtube_source: string | null; youtube_title: string | null; youtube_channel: string | null; kind: string; at: number },
[number, number]
>(
`SELECT s.id, s.title, s.artist, s.youtube_status, s.youtube_source, s.youtube_title, s.youtube_channel, t.kind, t.value at
FROM signals t JOIN songs s ON s.id = t.song_id WHERE ${tried} ORDER BY t.value DESC LIMIT 8`,
)
.all(job.started_at, end);
// speed: songs per minute over the last 10 minutes of the run (the whole run while it is younger than that)
const runEnd = running ? now : end;
const from = Math.max(job.started_at, runEnd - RATE_WINDOW);
const inWindow = db.query<{ n: number }, [number, number]>(`SELECT COUNT(*) n FROM signals t WHERE ${tried}`).get(from, end)!.n;
const perMin = runEnd > from ? (inWindow / (runEnd - from)) * 60_000 : 0;
const left = Math.max(0, job.total - job.done);
const lines = parseLog(log, job.started_at);
const deadline = lines.reduce<number | null>((d, l) => (l.deadline ? l.deadline : d), null);
const { kind } = recent[0] ?? { kind: '' };
return {
...job,
result: { matched: r.matched ?? 0, candidate: r.candidate ?? 0, none: r.none ?? 0 },
/** Search used: ytmusic (with the cookie) or the youtube fallback. */
source: kind ? kind.slice('yt_tried_'.length) : null,
lastAt: recent[0]?.at ?? null,
perMin: Math.round(perMin * 10) / 10,
eta: running && perMin > 0 && left > 0 ? Math.round(now + (left / perMin) * 60_000) : null,
/** Running but its process is gone (container restarted, killed): the row is stale. */
alive: running && pid ? alive(pid) : null,
deadline,
recent: recent.map(({ kind: _, ...x }) => x),
log: lines.slice(-12).map(({ at, text }) => ({ at, text })),
history: history.slice(1),
};
}
/**
* Job log lines are "HH:MM:SS text" in UTC; turn the time back into epoch ms (the run may cross midnight).
* The matcher's start line carries its deadline ("deadline 2026-10-20T07:55:00.000Z").
*/
export function parseLog(log: string, startedAt: number) {
const out: { at: number; text: string; deadline?: number }[] = [];
let day = Math.floor(startedAt / 86400_000) * 86400_000;
let prev = startedAt - 60_000;
for (const line of log.split('\n')) {
const m = /^(\d\d):(\d\d):(\d\d) (.*)$/.exec(line);
if (!m) continue;
let at = day + ((+m[1]! * 60 + +m[2]!) * 60 + +m[3]!) * 1000;
if (at < prev - 3600_000) {
day += 86400_000;
at += 86400_000;
}
prev = at;
const d = / deadline (\S+)/.exec(m[4]!);
out.push({ at, text: m[4]!, ...(d && Number.isFinite(Date.parse(d[1]!)) ? { deadline: Date.parse(d[1]!) } : {}) });
}
return out;
}
export interface ReviewRow {
id: number;
title: string;
artist: string;
year: number | null;
level: number | null;
duration_sec: number | null;
youtube_id: string | null;
youtube_status: string;
youtube_source: string | null;
youtube_channel: string | null;
youtube_title: string | null;
score: number | null;
note: string | null;
touched: number;
/** The real artist of the attached video (YouTube Music's artist field), not the channel name ("Release - Topic"). */
video_artist: string | null;
/** 후보 only: why the attached video was not confirmed automatically. */
reasons: string[];
candidates: { video_id: string; title: string | null; channel: string | null; duration_sec: number | null; score: number; source: string; reasons: string[] }[];
}
export function reviewList(db: Database, tab: ReviewTab, opts: { q?: string; page?: number } = {}) {
const where = ['s.deleted_at IS NULL', TAB_WHERE[tab]];
const args: string[] = [];
if (opts.q) {
const like = `%${opts.q.replace(/[%_\\]/g, (m) => '\\' + m)}%`;
where.push("(s.title LIKE ? ESCAPE '\\' OR s.artist LIKE ? ESCAPE '\\' OR s.youtube_id = ?)");
args.push(like, like, opts.q);
}
const w = where.join(' AND ');
const total = db.query<{ n: number }, string[]>(`SELECT COUNT(*) n FROM songs s WHERE ${w}`).get(...args)!.n;
const page = Math.max(0, opts.page ?? 0);
// 대기: in the order the matcher will take them (most popular level first); the rest: latest first.
const order = tab === 'pending' ? 'lv.level IS NULL, lv.level, s.id' : tab === 'dead' ? 's.updated_at DESC, s.id DESC' : 'touched DESC, s.id DESC';
const rows = db
.query<Omit<ReviewRow, 'candidates' | 'video_artist' | 'reasons'>, string[]>(
`SELECT s.id, s.title, s.artist, s.year, lv.level, s.duration_sec, s.youtube_id, s.youtube_status, s.youtube_source, s.youtube_channel, s.youtube_title,
(SELECT c.score FROM youtube_candidates c WHERE c.song_id = s.id AND c.video_id = s.youtube_id) score, s.note,
${tab === 'dead' ? 's.updated_at' : TOUCHED} touched
FROM songs s LEFT JOIN song_levels lv ON lv.song_id = s.id AND lv.scope = 'all'
WHERE ${w} ORDER BY ${order} LIMIT ${REVIEW_PAGE} OFFSET ${page * REVIEW_PAGE}`,
)
.all(...args);
type C = Omit<ReviewRow['candidates'][number], 'reasons'>;
const all = new Map<number, C[]>();
if (rows.length) {
for (const c of db
.query<C & { song_id: number }, number[]>(
`SELECT song_id, video_id, title, channel, duration_sec, score, source FROM youtube_candidates
WHERE song_id IN (${rows.map(() => '?').join(',')}) ORDER BY score DESC`,
)
.all(...rows.map((r) => r.id))) {
const list = all.get(c.song_id) ?? [];
list.push({ video_id: c.video_id, title: c.title, channel: c.channel, duration_sec: c.duration_sec, score: c.score, source: c.source });
all.set(c.song_id, list);
}
}
return {
total,
page,
pageSize: REVIEW_PAGE,
rows: rows.map((r): ReviewRow => {
const list = all.get(r.id) ?? [];
// the attached video's own row: prefer YouTube Music's (it knows the artist), else norabose's
const own = list.filter((c) => c.video_id === r.youtube_id).sort((a, b) => Number(b.source === 'ytmusic') - Number(a.source === 'ytmusic'))[0];
const explain = (c: C) => (r.youtube_status === 'candidate' ? explainCandidate(db, r, c) : []);
return {
...r,
video_artist: own?.source === 'ytmusic' ? own.channel : null,
reasons: own ? explain(own) : r.youtube_status === 'candidate' && r.youtube_id ? ['찾기 결과에 없는 영상이라 정보 없음'] : [],
candidates: list.slice(0, 6).map((c) => ({ ...c, reasons: explain(c) })),
};
}),
};
}
/**
* 확정 취소: the video goes back to 후보 (out of the games) and the admin picks. Marked as admin so the matcher
* does not confirm the same video again. Returns false when the song had no confirmed video.
*/
export function unconfirmVideo(db: Database, id: number, now = Date.now()): boolean {
return (
db
.query("UPDATE songs SET youtube_status = 'candidate', youtube_source = 'admin', youtube_checked_at = ?, updated_at = ? WHERE id = ? AND deleted_at IS NULL AND youtube_status = 'matched'")
.run(now, now, id).changes === 1
);
}
/** 원곡 없음: no video, and the matcher never tries this song again (until 다시 찾기). */
export function markNoOriginal(db: Database, id: number, now = Date.now()): boolean {
return (
db
.query(
`UPDATE songs SET youtube_id = NULL, youtube_status = 'none', youtube_source = 'admin', youtube_channel = NULL, youtube_title = NULL, embeddable = NULL,
youtube_checked_at = ?, updated_at = ? WHERE id = ? AND deleted_at IS NULL`,
)
.run(now, now, id).changes === 1
);
}