관리자 "원곡 찾기" 화면: 유튜브 원곡 찾기 결과를 확정·후보·못 찾음·원곡 없음·재생 불가·아직 안 찾음 탭으로(방금 처리된 곡이 위), 진행률·끝 예상·이번 작업 결과, 5초 자동 새로고침(보고 있을 때만, 목록 위에서는 멈춤), 줄에서 바로 확정 + 패널에서 미리듣기·다른 후보·주소 붙여넣기·확정 취소(관리자 후보로, 게임에서 빠지고 자동 확정 안 됨)·원곡 없음 표시·다시 찾기, 처리하면 다음 곡으로. 저장은 기존 경로, 감사 로그 기록
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -25,6 +25,7 @@ import {
|
||||
type BulkAction,
|
||||
} from '../songs/admin-ops';
|
||||
import { updateSong } from '../songs/store';
|
||||
import { REVIEW_TABS, markNoOriginal, reviewCounts, reviewJob, reviewList, unconfirmVideo, type ReviewTab } from '../songs/youtube-review';
|
||||
|
||||
type Env = { Variables: { userId: string | null; role: Role } };
|
||||
|
||||
@@ -193,6 +194,33 @@ export function mountCatalogAdmin(
|
||||
return c.json({ merged: n });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ 원곡 찾기 (matcher results, checked while it runs)
|
||||
// Choosing a video goes through PATCH /songs/:id { youtube } and 다시 찾기 through /songs/bulk { action: 'rematch' }.
|
||||
app.get('/youtube', (c) => {
|
||||
const t = c.req.query('tab');
|
||||
const tab: ReviewTab = (REVIEW_TABS as readonly string[]).includes(t ?? '') ? (t as ReviewTab) : 'candidate';
|
||||
const list = reviewList(d.db, tab, { q: c.req.query('q')?.trim().slice(0, 100) || undefined, page: Number(c.req.query('page') ?? 0) || 0 });
|
||||
return c.json({ tab, counts: reviewCounts(d.db), job: reviewJob(d.db), ...list });
|
||||
});
|
||||
/** The video before an admin change, for the 기록. */
|
||||
const videoOf = (id: number) => d.db.query<{ youtube_id: string | null; youtube_status: string; youtube_source: string | null }, [number]>('SELECT youtube_id, youtube_status, youtube_source FROM songs WHERE id = ?').get(id);
|
||||
app.post('/youtube/:id/unconfirm', (c) => {
|
||||
const id = Number(c.req.param('id'));
|
||||
const before = videoOf(id);
|
||||
if (!unconfirmVideo(d.db, id)) return c.json({ error: '확정된 영상이 있는 노래가 아니에요.' }, 400);
|
||||
d.audit.log(h.actor(c), 'song.youtube.unconfirm', String(id), before, null);
|
||||
changed();
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
app.post('/youtube/:id/no-original', (c) => {
|
||||
const id = Number(c.req.param('id'));
|
||||
const before = videoOf(id);
|
||||
if (!markNoOriginal(d.db, id)) return c.json({ error: '노래를 찾을 수 없어요.' }, 404);
|
||||
d.audit.log(h.actor(c), 'song.youtube.none', String(id), before, null);
|
||||
changed();
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ artists (가수 별칭)
|
||||
app.get('/artists', (c) => c.json(listArtists(d.db, (c.req.query('q') ?? '').trim().slice(0, 60), Number(c.req.query('page') ?? 0) || 0)));
|
||||
app.patch('/artists/:id', async (c) => {
|
||||
|
||||
131
apps/server/src/songs/youtube-review.ts
Normal file
131
apps/server/src/songs/youtube-review.ts
Normal 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
|
||||
);
|
||||
}
|
||||
79
apps/server/src/youtube-review.test.ts
Normal file
79
apps/server/src/youtube-review.test.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
/** 관리자 → 원곡 찾기: tabs from a real matcher run, and the row actions (확정 · 확정 취소 · 원곡 없음 · 다시 찾기). */
|
||||
import { afterEach, expect, test } from 'bun:test';
|
||||
import { Catalog } from './collector/catalog';
|
||||
import { matchYoutube } from './collector/match-youtube';
|
||||
import { quizSong } from './songs/quiz';
|
||||
import { api, boot, discordLogin, TEST_SUPERADMINS } from './test-utils';
|
||||
|
||||
let s: ReturnType<typeof boot>;
|
||||
afterEach(async () => s && (await s.stop()));
|
||||
|
||||
test('원곡 찾기 tabs and actions; admin choices stick across matcher runs', async () => {
|
||||
s = boot(
|
||||
{
|
||||
discordExchange: async (code) => ({ id: code, username: 'u', global_name: '관리', avatar: null }),
|
||||
checkEmbed: async (id) => ({ state: 'ok', author: 'X - Topic', title: `t${id}` }),
|
||||
},
|
||||
{ DISCORD_CLIENT_ID: 'c', DISCORD_CLIENT_SECRET: 's' },
|
||||
);
|
||||
const { cookie } = await discordLogin(s.base, TEST_SUPERADMINS[0]);
|
||||
const call = (path: string, init: RequestInit = {}) => api(s.base, `/api/admin${path}`, { ...init, cookie: cookie! });
|
||||
const c = new Catalog(s.db);
|
||||
const [found] = c.upsert({ title: 'Love wins all', artists: [{ name: '아이유' }], durationSec: 272, source: 't', ref: '1' });
|
||||
const [guess] = c.upsert({ title: '한사람을 위해', artists: [{ name: '안재모' }], durationSec: 293, source: 't', ref: '2' });
|
||||
const [nothing] = c.upsert({ title: '없는노래', artists: [{ name: '누구' }], source: 't', ref: '3' });
|
||||
const [later] = c.upsert({ title: '아직안찾음', artists: [{ name: '누구' }], source: 't', ref: '4' });
|
||||
const searcher = {
|
||||
searchSongs: async (q: string) =>
|
||||
({
|
||||
'아이유 Love wins all': [{ videoId: 'Wu5FY8J6P8Q', title: 'Love wins all', artists: '아이유', album: 'The Winning', durationSec: 272 }],
|
||||
'안재모 한사람을 위해': [
|
||||
{ videoId: 'othersong01', title: '한사람을 위해 (Live)', artists: '다른 가수', album: null, durationSec: 120 },
|
||||
{ videoId: 'othersong02', title: '한사람을 위해', artists: '안재모 팬', album: null, durationSec: 400 },
|
||||
],
|
||||
})[q] ?? [],
|
||||
};
|
||||
// the matcher has looked at three of the four songs
|
||||
s.db.query('UPDATE songs SET deleted_at = 1 WHERE id = ?').run(later);
|
||||
await matchYoutube(s.db, searcher, { delayMs: 0 }, async (id) => ({ state: 'ok', author: id === 'Wu5FY8J6P8Q' ? 'IU - Topic' : 'fan', title: id }));
|
||||
s.db.query('UPDATE songs SET deleted_at = NULL WHERE id = ?').run(later);
|
||||
|
||||
const tab = async (t: string) => (await call(`/youtube?tab=${t}`)).body;
|
||||
const ids = async (t: string) => (await tab(t)).rows.map((r: any) => r.id);
|
||||
const first = await tab('matched');
|
||||
expect(first.counts).toEqual({ matched: 1, candidate: 1, missing: 1, noorig: 0, dead: 0, pending: 1 });
|
||||
expect(first.job).toMatchObject({ status: 'done', done: 3, total: 3, result: { matched: 1, candidate: 1, none: 1 } });
|
||||
expect(first.rows[0]).toMatchObject({ id: found, youtube_id: 'Wu5FY8J6P8Q', youtube_channel: 'IU - Topic' });
|
||||
expect(first.rows[0].score).toBeGreaterThan(0);
|
||||
expect(first.rows[0].candidates[0].video_id).toBe('Wu5FY8J6P8Q');
|
||||
expect(await ids('candidate')).toEqual([guess]);
|
||||
expect(await ids('missing')).toEqual([nothing]);
|
||||
expect(await ids('pending')).toEqual([later]);
|
||||
expect((await call('/youtube?tab=matched&q=아이유')).body.total).toBe(1);
|
||||
expect((await call('/youtube?tab=matched&q=안재모')).body.total).toBe(0);
|
||||
|
||||
// 확정 취소: back to 후보, out of the game pool, and the matcher does not confirm it again
|
||||
expect((await call(`/youtube/${found}/unconfirm`, { method: 'POST' })).res.status).toBe(200);
|
||||
expect((await call(`/youtube/${found}/unconfirm`, { method: 'POST' })).res.status).toBe(400);
|
||||
expect((await ids('candidate')).sort()).toEqual([found, guess].sort());
|
||||
expect(quizSong(s.db, found)!.videoId).toBeNull();
|
||||
s.db.query("DELETE FROM signals WHERE kind LIKE 'yt_tried_%'").run(); // a week later
|
||||
await matchYoutube(s.db, searcher, { delayMs: 0 }, async () => ({ state: 'ok', author: 'IU - Topic', title: 'x' }));
|
||||
expect((await call(`/songs/${found}`)).body.song).toMatchObject({ youtube_status: 'candidate', youtube_source: 'admin' });
|
||||
|
||||
// 확정 with another candidate (the existing save path)
|
||||
expect((await call(`/songs/${guess}`, { method: 'PATCH', body: JSON.stringify({ youtube: 'https://youtu.be/othersong02' }) })).res.status).toBe(200);
|
||||
expect((await tab('matched')).rows[0]).toMatchObject({ id: guess, youtube_id: 'othersong02', youtube_source: 'admin' });
|
||||
|
||||
// 원곡 없음: own tab, never searched again
|
||||
expect((await call(`/youtube/${nothing}/no-original`, { method: 'POST' })).res.status).toBe(200);
|
||||
expect(await ids('noorig')).toEqual([nothing]);
|
||||
expect(await ids('missing')).toEqual([later]); // tried by the second run, nothing found
|
||||
// 다시 찾기 brings it back to 대기
|
||||
await call('/songs/bulk', { method: 'POST', body: JSON.stringify({ ids: [nothing], action: 'rematch' }) });
|
||||
expect(await ids('pending')).toEqual([nothing]);
|
||||
|
||||
const audit = (await call('/audit')).body.entries.map((e: any) => e.action);
|
||||
expect(audit).toEqual(expect.arrayContaining(['song.youtube.unconfirm', 'song.youtube.none', 'song.update']));
|
||||
expect((await call('/youtube?tab=nope')).body.tab).toBe('candidate');
|
||||
});
|
||||
Reference in New Issue
Block a user