관리자 "원곡 찾기" 화면: 유튜브 원곡 찾기 결과를 확정·후보·못 찾음·원곡 없음·재생 불가·아직 안 찾음 탭으로(방금 처리된 곡이 위), 진행률·끝 예상·이번 작업 결과, 5초 자동 새로고침(보고 있을 때만, 목록 위에서는 멈춤), 줄에서 바로 확정 + 패널에서 미리듣기·다른 후보·주소 붙여넣기·확정 취소(관리자 후보로, 게임에서 빠지고 자동 확정 안 됨)·원곡 없음 표시·다시 찾기, 처리하면 다음 곡으로. 저장은 기존 경로, 감사 로그 기록

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-19 21:47:10 +09:00
parent c4edccf352
commit 8d4e32d737
11 changed files with 760 additions and 5 deletions

View File

@@ -0,0 +1,131 @@
/**
* 관리자 → 원곡 찾기: 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';
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>;
}
/** The latest match-youtube run, with what it has decided so far. */
export function reviewJob(db: Database) {
const job = db
.query<{ id: number; status: string; done: number; total: number; started_at: number; finished_at: number | null }, []>(
"SELECT id, status, done, total, started_at, finished_at FROM collect_jobs WHERE kind = 'match-youtube' ORDER BY id DESC LIMIT 1",
)
.get();
if (!job) return null;
const end = job.finished_at ?? Date.now() + 1;
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 t.kind LIKE 'yt_tried_%' AND t.value >= ? AND t.value <= ?)`,
)
.get(job.started_at, end)!;
return { ...job, result: { matched: r.matched ?? 0, candidate: r.candidate ?? 0, none: r.none ?? 0 } };
}
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;
candidates: { video_id: string; title: string | null; channel: string | null; duration_sec: number | null; score: number; source: 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'>, 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);
const cands = new Map<number, ReviewRow['candidates']>();
if (rows.length) {
for (const c of db
.query<ReviewRow['candidates'][number] & { 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 = cands.get(c.song_id) ?? [];
if (list.length < 6) list.push({ video_id: c.video_id, title: c.title, channel: c.channel, duration_sec: c.duration_sec, score: c.score, source: c.source });
cands.set(c.song_id, list);
}
}
return { total, page, pageSize: REVIEW_PAGE, rows: rows.map((r) => ({ ...r, candidates: cands.get(r.id) ?? [] })) };
}
/**
* 확정 취소: 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
);
}