diff --git a/apps/server/src/http/admin-catalog.ts b/apps/server/src/http/admin-catalog.ts index f565cf7..82f74fd 100644 --- a/apps/server/src/http/admin-catalog.ts +++ b/apps/server/src/http/admin-catalog.ts @@ -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) => { diff --git a/apps/server/src/songs/youtube-review.ts b/apps/server/src/songs/youtube-review.ts new file mode 100644 index 0000000..d5a5b1b --- /dev/null +++ b/apps/server/src/songs/youtube-review.ts @@ -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 = { + 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 { + const cols = REVIEW_TABS.map((t) => `SUM(${TAB_WHERE[t]}) ${t}`).join(', '); + const r = db.query, []>(`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; +} + +/** 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, 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(); + if (rows.length) { + for (const c of db + .query( + `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 + ); +} diff --git a/apps/server/src/youtube-review.test.ts b/apps/server/src/youtube-review.test.ts new file mode 100644 index 0000000..14a7543 --- /dev/null +++ b/apps/server/src/youtube-review.test.ts @@ -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; +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'); +}); diff --git a/apps/web/src/pages/admin/AdminApp.tsx b/apps/web/src/pages/admin/AdminApp.tsx index 0d63d02..3c502db 100644 --- a/apps/web/src/pages/admin/AdminApp.tsx +++ b/apps/web/src/pages/admin/AdminApp.tsx @@ -1,5 +1,5 @@ /** - * 관리자 페이지 (docs/02): side menu + content — 대시보드 · 노래 · 가수 · 장르 · 수집 · 통계 · 방 · 사이트 · 사용자 · 관리자 · 기록. + * 관리자 페이지 (docs/02): side menu + content — 대시보드 · 노래 · 원곡 찾기 · 가수 · 장르 · 수집 · 통계 · 방 · 사이트 · 사용자 · 관리자 · 기록. */ import { useCallback, useEffect, useState, type FormEvent } from 'react'; import { Link, NavLink, Navigate, Route, Routes } from 'react-router'; @@ -9,6 +9,7 @@ import { useSession } from '../../store/session'; import { toast } from '../../store/toast'; import { ConfirmSheet } from '../../components/ui'; import { SongsPage } from './SongsPage'; +import { YoutubePage } from './YoutubePage'; import { ArtistsPage, CollectPage, GenresPage, RoomsPage, StatsPage } from './AdminMore'; import { RoomSettings, type CatalogMeta } from '../../components/RoomSettings'; import { DEFAULT_ROOM_CONFIG, type RoomConfig } from '@mq/shared/lite'; @@ -63,6 +64,7 @@ export default function AdminApp() {
노래 DB
🎵 노래 + 🔎 원곡 찾기 🎤 가수 🏷 장르 📥 수집 @@ -78,6 +80,7 @@ export default function AdminApp() { } /> } /> + } /> } /> } /> } /> diff --git a/apps/web/src/pages/admin/AdminMore.tsx b/apps/web/src/pages/admin/AdminMore.tsx index 9a1c9c4..ca2f95d 100644 --- a/apps/web/src/pages/admin/AdminMore.tsx +++ b/apps/web/src/pages/admin/AdminMore.tsx @@ -442,7 +442,7 @@ export function CollectPage() { <>

수집

{data?.cookieProblem &&

⚠ 유튜브 뮤직 쿠키가 로그아웃된 것 같아요. 새 쿠키를 서버에 넣어야 원곡 찾기가 다시 돌아요.

} -

작업은 서버에서 따로 돌아가요(게임에는 영향 없음). 유튜브 원곡 찾기는 매일 새벽 4시 10분에 3,000곡씩 자동으로도 돌아요.

+

작업은 서버에서 따로 돌아가요(게임에는 영향 없음). 유튜브 원곡 찾기는 매일 08:10에 3,000곡씩 자동으로도 돌아요. 찾은 결과는 ‘원곡 찾기’ 화면에서 확인·수정할 수 있어요.

{data?.kinds.map((k) => { const running = data.jobs.find((j) => j.kind === k.id && j.status === 'running'); diff --git a/apps/web/src/pages/admin/SongsPage.tsx b/apps/web/src/pages/admin/SongsPage.tsx index 7e40e41..7fbb1c4 100644 --- a/apps/web/src/pages/admin/SongsPage.tsx +++ b/apps/web/src/pages/admin/SongsPage.tsx @@ -7,7 +7,7 @@ import { apiCall } from '../../net/api'; import { toast } from '../../store/toast'; import { ConfirmSheet, Sheet } from '../../components/ui'; -interface Genre { +export interface Genre { id: string; name: string; grp: 'region' | 'style' | 'theme'; @@ -599,7 +599,7 @@ function DuplicatesSheet({ onClose, onMerged }: { onClose: () => void; onMerged: ); } -function SongEditor({ id, genres, onClose, onSaved }: { id: number; genres: Genre[]; onClose: () => void; onSaved: () => void }) { +export function SongEditor({ id, genres, onClose, onSaved }: { id: number; genres: Genre[]; onClose: () => void; onSaved: () => void }) { const [d, setD] = useState(null); const [form, setForm] = useState({ title: '', artist: '', year: '', level: '', youtube: '', highlight: '', titleAliases: '', artistAliases: '', note: '', hidden: false, genres: [] as string[] }); const [busy, setBusy] = useState(false); @@ -874,7 +874,7 @@ function loadYt(): Promise { } /** 미리듣기 with the IFrame API, so "지금 위치를 하이라이트로" can read the position. */ -function YtPreview({ videoId, start, apiRef }: { videoId: string; start: number; apiRef: { current: { time(): number | undefined } | null } }) { +export function YtPreview({ videoId, start, apiRef }: { videoId: string; start: number; apiRef: { current: { time(): number | undefined } | null } }) { const host = useRef(null); useEffect(() => { let player: any = null; diff --git a/apps/web/src/pages/admin/YoutubePage.tsx b/apps/web/src/pages/admin/YoutubePage.tsx new file mode 100644 index 0000000..89c6f00 --- /dev/null +++ b/apps/web/src/pages/admin/YoutubePage.tsx @@ -0,0 +1,454 @@ +/** + * 관리자 → 원곡 찾기: what the YouTube matcher decided, newest first, refreshed every 5 seconds while the page is in view. + * Each song can be fixed on the spot: 확정 · 다른 후보 · 주소 붙여넣기 · 확정 취소 · 원곡 없음 · 다시 찾기. + * Saving goes through the same paths as the song editor, so new games use the video right away. + */ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { Link } from 'react-router'; +import { apiCall } from '../../net/api'; +import { toast } from '../../store/toast'; +import { ConfirmSheet } from '../../components/ui'; +import { SongEditor, YtPreview, type Genre } from './SongsPage'; + +type Tab = 'matched' | 'candidate' | 'missing' | 'noorig' | 'dead' | 'pending'; +interface Cand { + video_id: string; + title: string | null; + channel: string | null; + duration_sec: number | null; + score: number; + source: string; +} +interface Row { + id: number; + title: string; + artist: string; + year: number | null; + level: 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: Cand[]; +} +interface Job { + id: number; + status: string; + done: number; + total: number; + started_at: number; + finished_at: number | null; + result: { matched: number; candidate: number; none: number }; +} +interface Data { + tab: Tab; + counts: Record; + job: Job | null; + total: number; + pageSize: number; + rows: Row[]; +} +interface Detail { + song: { id: number; title: string; artist: string; year: number | null; youtube_id: string | null; youtube_status: string; youtube_source: string | null; youtube_channel: string | null; youtube_title: string | null }; + candidates: Cand[]; + signals: { kind: string; value: number }[]; +} + +const TABS: [Tab, string, string][] = [ + ['matched', '확정', '게임에 나오는 영상이에요. 틀린 영상이면 확정 취소하거나 다른 영상으로 바꿔 주세요.'], + ['candidate', '후보', '자동으로 확신하지 못한 곡이에요. 게임에는 아직 안 나와요. 맞으면 확정을 눌러 주세요.'], + ['missing', '못 찾음', '찾아봤지만 쓸 만한 영상이 없었어요. 7일 뒤 자동으로 다시 찾아요. 주소를 직접 넣거나 원곡 없음으로 표시할 수 있어요.'], + ['noorig', '원곡 없음', '관리자가 원곡 없음으로 표시한 곡이에요. 자동 찾기가 건너뛰어요. 다시 찾기를 누르면 다음 작업에서 다시 찾아요.'], + ['dead', '재생 불가', '게임 중에 재생이 안 된 영상이에요(삭제·퍼가기 금지). 다른 영상으로 바꿔 주세요.'], + ['pending', '아직 안 찾음', '아직 한 번도 찾아보지 않은 곡이에요. 자동 찾기가 이 순서(인기 많은 곡부터)로 찾아요.'], +]; +const SOURCE: Record = { ytmusic: '유튜브 뮤직', youtube: '유튜브 검색', norabose: '노라보세', admin: '관리자' }; +const STATUS: Record = { matched: ['확정', 'ok'], candidate: ['후보', 'warn'], none: ['없음', ''], dead: ['재생 불가', 'warn'] }; +const JOB_STATUS: Record = { running: '찾는 중', done: '끝남', failed: '실패', stopped: '멈춤' }; +const mmss = (s: number | null) => (s == null ? '-' : `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, '0')}`); +const clock = (ms: number) => new Date(ms).toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit' }); +function ago(ms: number, now: number): string { + if (!ms) return '-'; + const s = Math.max(0, Math.round((now - ms) / 1000)); + if (s < 60) return `${s}초 전`; + if (s < 3600) return `${Math.floor(s / 60)}분 전`; + if (s < 86400) return `${Math.floor(s / 3600)}시간 전`; + return new Date(ms).toLocaleDateString('ko-KR', { month: 'short', day: 'numeric' }); +} +/** Which tab a song belongs to now (same rules as the server). */ +function tabOf(d: Detail): Tab { + const s = d.song; + if (s.youtube_status === 'matched' || s.youtube_status === 'candidate' || s.youtube_status === 'dead') return s.youtube_status; + if (s.youtube_source === 'admin') return 'noorig'; + return d.signals.some((x) => x.kind.startsWith('yt_tried_')) ? 'missing' : 'pending'; +} + +export function YoutubePage() { + const [tab, setTab] = useState('candidate'); + const [q, setQ] = useState(''); + const [query, setQuery] = useState(''); + const [page, setPage] = useState(0); + const [data, setData] = useState(null); + const [selected, setSelected] = useState(null); + const [editing, setEditing] = useState(false); + const [auto, setAuto] = useState(true); + const [hover, setHover] = useState(false); + const [lastAt, setLastAt] = useState(0); + const [genres, setGenres] = useState([]); + const seq = useRef(0); + // Read when an action finishes (the list may have refreshed meanwhile). + const latest = useRef({ data, selected, tab }); + latest.current = { data, selected, tab }; + + const reload = useCallback(() => { + const my = ++seq.current; + const p = new URLSearchParams({ tab, page: String(page) }); + if (query) p.set('q', query); + apiCall('GET', `/api/admin/youtube?${p}`).then( + (d) => { + if (my !== seq.current) return; // a newer request (other tab/page) is on its way + setData(d); + setLastAt(Date.now()); + }, + (e: Error) => my === seq.current && toast(e.message, 'error'), + ); + }, [tab, page, query]); + useEffect(reload, [reload]); + useEffect(() => void apiCall<{ genres: Genre[] }>('GET', '/api/admin/genres').then((r) => setGenres(r.genres), () => {}), []); + + // 5초마다, only while this page is on screen and the list is not under the pointer (rows would move under a click). + const paused = !auto || hover; + useEffect(() => { + if (paused) return; + const tick = () => document.visibilityState === 'visible' && reload(); + const t = setInterval(tick, 5000); + document.addEventListener('visibilitychange', tick); + return () => { + clearInterval(t); + document.removeEventListener('visibilitychange', tick); + }; + }, [paused, reload]); + + const choose = (t: Tab) => { + setTab(t); + setPage(0); + }; + /** After an action: refresh, and when the song left this tab, move on to the next one in the list. */ + const afterAction = (id: number, now: Tab | null) => { + const { data, selected, tab } = latest.current; + if (now !== null && now !== tab && selected === id && data) { + const i = data.rows.findIndex((r) => r.id === id); + const next = data.rows[i + 1] ?? data.rows[i - 1]; + setSelected(next && next.id !== id ? next.id : null); + } + reload(); + }; + const quickConfirm = async (r: Row) => { + try { + await apiCall('PATCH', `/api/admin/songs/${r.id}`, { youtube: `https://youtu.be/${r.youtube_id}` }); + toast(`'${r.title}' 확정했어요.`); + afterAction(r.id, 'matched'); + } catch (e) { + toast((e as Error).message, 'error'); + } + }; + + const job = data?.job; + const running = job?.status === 'running'; + const pages = data ? Math.max(1, Math.ceil(data.total / data.pageSize)) : 1; + const now = Date.now(); + const eta = running && job.done > 0 && job.total > job.done ? now + ((now - job.started_at) / job.done) * (job.total - job.done) : null; + + return ( +
+
+
+

원곡 찾기

+ + 수집 화면에서 실행·멈추기 + +
+
+ {job ? ( + <> +
+ + {running ? '🔎 지금 찾는 중' : `마지막 작업: ${JOB_STATUS[job.status] ?? job.status}`}{' '} + + {job.done.toLocaleString()} / {job.total.toLocaleString()} + {job.total ? ` (${Math.floor((job.done / job.total) * 100)}%)` : ''} + + + + 시작 {clock(job.started_at)} + {running && eta && ` · 끝 예상 ${clock(eta)}`} + {!running && job.finished_at && ` · 끝 ${new Date(job.finished_at).toLocaleString('ko-KR', { dateStyle: 'short', timeStyle: 'short' })}`} + +
+ +

+ 이번 작업 결과: 확정 {job.result.matched.toLocaleString()} · 후보 {job.result.candidate.toLocaleString()} · 못 찾음 {job.result.none.toLocaleString()} +

+ + ) : ( +

아직 돌린 원곡 찾기 작업이 없어요.

+ )} +

매일 08:10에 3,000곡씩 자동으로 찾아요. 확정한 영상은 저장하는 즉시 새 게임과 다음 문제부터 나와요(지금 재생 중인 곡은 그대로).

+
+
+ {TABS.map(([t, label]) => ( + + ))} +
+

{TABS.find((x) => x[0] === tab)![2]}

+
{ + e.preventDefault(); + setPage(0); + setQuery(q.trim()); + }} + > + setQ(e.target.value)} aria-label="제목·가수 검색" /> + + + + {auto && hover ? '목록 위에서는 잠깐 멈춰요' : lastAt ? `${clock(lastAt)} 기준` : ''} + +
+
setHover(true)} onMouseLeave={() => setHover(false)}> + + + + + + + + + {tab === 'candidate' && + + + {data?.rows.map((r) => ( + (setSelected(r.id), setEditing(false))} style={{ cursor: 'pointer' }}> + + + + + + {tab === 'candidate' && ( + + )} + + ))} + {data && !data.rows.length && ( + + + + )} + +
노래붙은 영상점수출처{tab === 'pending' ? '난이도' : '처리'}} +
+ +
+ {r.artist} + {r.year ? ` · ${r.year}` : ''} +
+
+ {r.youtube_id ? ( + <> + {r.youtube_title ?? r.youtube_id} +
{r.youtube_channel ?? ''}
+ + ) : r.candidates.length ? ( + 후보 {r.candidates.length}개 (붙은 영상 없음) + ) : ( + - + )} + {tab === 'dead' && r.note &&
{r.note}
} +
{r.score != null ? Math.round(r.score) : '-'}{r.youtube_source ? (SOURCE[r.youtube_source] ?? r.youtube_source) : '-'}{tab === 'pending' ? (r.level ? `★${r.level}` : '-') : ago(r.touched, now)} + {r.youtube_id && ( + + )} +
+ {query ? '검색한 곡이 없어요.' : '이 종류의 곡이 없어요.'} +
+
+
+ + + {page + 1} / {pages} · {data?.total.toLocaleString() ?? 0}곡 + + +
+
+ {selected && + (editing ? ( + setEditing(false)} onSaved={reload} /> + ) : ( + setSelected(null)} onEdit={() => setEditing(true)} onChanged={afterAction} /> + ))} +
+ ); +} + +/** One song: listen, then 확정 / 다른 영상 / 확정 취소 / 원곡 없음 / 다시 찾기. */ +function ReviewPanel({ id, onClose, onEdit, onChanged }: { id: number; onClose: () => void; onEdit: () => void; onChanged: (id: number, now: Tab | null) => void }) { + const [d, setD] = useState(null); + const [listen, setListen] = useState(null); + const [url, setUrl] = useState(''); + const [busy, setBusy] = useState(false); + const [confirmRematch, setConfirmRematch] = useState(false); + const previewRef = useRef<{ time(): number | undefined } | null>(null); + const load = useCallback( + () => + apiCall('GET', `/api/admin/songs/${id}`).then( + (x) => (setD(x), x), + (e: Error) => (toast(e.message, 'error'), null), + ), + [id], + ); + useEffect(() => void load().then((x) => x && setListen(x.song.youtube_id ?? x.candidates[0]?.video_id ?? null)), [load]); + if (!d) return ; + const s = d.song; + const act = async (what: () => Promise, done: string): Promise => { + setBusy(true); + try { + await what(); + toast(done); + const x = await load(); + if (x) setListen(x.song.youtube_id ?? listen); + onChanged(id, x ? tabOf(x) : null); + return true; + } catch (e) { + toast((e as Error).message, 'error'); + return false; + } finally { + setBusy(false); + } + }; + const setVideo = (video: string) => act(() => apiCall('PATCH', `/api/admin/songs/${id}`, { youtube: video }), '이 영상으로 확정했어요.'); + const rematch = () => act(() => apiCall('POST', '/api/admin/songs/bulk', { ids: [id], action: 'rematch' }), '다음 원곡 찾기 때 다시 찾아요.'); + const [label, cls] = STATUS[s.youtube_status] ?? [s.youtube_status, '']; + return ( + + ); +} diff --git a/apps/web/src/styles/global.css b/apps/web/src/styles/global.css index 5830847..228c38a 100644 --- a/apps/web/src/styles/global.css +++ b/apps/web/src/styles/global.css @@ -317,6 +317,7 @@ input.input.sm { width: 76px; } .yt-preview iframe { width: 100%; height: 100%; border: 0; } .cand { display: flex; align-items: center; gap: 8px; padding: 6px 8px; border: 1.5px solid var(--line); border-radius: 9px; background: var(--surface); color: var(--text); font: inherit; font-size: 0.85rem; font-weight: 650; cursor: pointer; } .cand.on { border-color: var(--ink); background: var(--primary-soft); } +.yt-progress { width: 100%; height: 10px; accent-color: var(--primary); } .lyrics { white-space: pre-wrap; font: inherit; font-size: 0.85rem; background: var(--surface-2); padding: 10px; border-radius: 8px; max-height: 260px; overflow: auto; } @media (max-width: 1100px) { .songs-layout.with-panel { grid-template-columns: 1fr; } .song-panel { position: static; max-height: none; } } diff --git a/docs/02-auth-admin.md b/docs/02-auth-admin.md index 91e2078..41a53cf 100644 --- a/docs/02-auth-admin.md +++ b/docs/02-auth-admin.md @@ -41,6 +41,7 @@ joke-app 관리자와 같은 레이아웃(왼쪽 사이드 메뉴 + 오른쪽 |---|---|---| | 대시보드 | 접속자 수, 진행 중 방, 전체 곡 수, 유튜브 매칭률, 가사 보유율, 최근 수집 작업, 오늘 플레이 수 | admin | | 노래 | 곡 목록 표 + 상세 편집 (아래) | admin | +| 원곡 찾기 | 유튜브 원곡 찾기 결과 확인·수정 (아래) | admin | | 가수 | 가수 별칭(아이유 = IU = 이지은), 그룹/유닛 연결, 대표 이미지 | admin | | 장르 | 장르 목록 추가·이름 변경·순서·숨김 | admin | | 수집 | 출처별 수집 실행(멜론 연도별 등), 진행률·로그, 자동 실행 주기, 유튜브 매칭/하이라이트 분석 일괄 실행 | admin | @@ -61,3 +62,10 @@ joke-app 관리자와 같은 레이아웃(왼쪽 사이드 메뉴 + 오른쪽 - **일괄 작업**: 선택 곡 장르/난이도 변경, 유튜브 재매칭, 숨김, 삭제(휴지통 30일 보관) - **가져오기/내보내기**: JSON·CSV - **중복 정리**: 제목·가수 정규화가 같은 곡 묶어서 보여주고 병합 + +### 원곡 찾기 화면 (2026-10-19) +- **진행 상황**: 지금(또는 마지막) 원곡 찾기 작업의 진행률·끝 예상 시각, 이번 작업 결과(확정·후보·못 찾음) +- **탭**: 확정 · 후보 · 못 찾음(찾아봤지만 없음, 7일 뒤 자동 재시도) · 원곡 없음(관리자 표시, 자동 찾기 제외) · 재생 불가 · 아직 안 찾음(자동 찾기 순서대로). 방금 처리된 곡이 맨 위 +- **자동 새로고침**: 5초마다, 화면을 보고 있을 때만. 마우스가 목록 위에 있으면 줄이 밀리지 않게 잠깐 멈춤 +- **바로 고치기**: 후보 줄의 [확정], 오른쪽 패널에서 미리듣기 · 다른 후보로 확정 · 주소 붙여넣기 · 확정 취소(→ 관리자 후보, 게임에서 빠지고 자동 찾기가 다시 확정하지 않음) · 원곡 없음으로 표시 · 다시 찾기. 처리한 곡이 탭에서 빠지면 다음 곡으로 넘어감 +- 저장은 노래 편집과 같은 경로(DB 바로 반영, 새 게임·다음 문제부터 적용), 모두 기록(감사 로그)에 남음. 제목·가수 수정은 패널의 "전체 편집" diff --git a/e2e/a11y.e2e.ts b/e2e/a11y.e2e.ts index aa2bb08..3817a5e 100644 --- a/e2e/a11y.e2e.ts +++ b/e2e/a11y.e2e.ts @@ -116,6 +116,10 @@ try { await p.goto(ORIGIN + '/admin/songs'); await p.locator('.data-table tbody tr').first().waitFor(); await audit(p, `PC/${theme} 관리자 노래`); + await p.goto(ORIGIN + '/admin/youtube'); + await p.getByRole('button', { name: /^확정 \d/ }).click(); + await p.locator('.data-table tbody tr', { hasText: '검사곡1' }).waitFor(); + await audit(p, `PC/${theme} 관리자 원곡 찾기`); await p.goto(ORIGIN + '/admin/stats'); await p.getByRole('heading', { name: '통계' }).waitFor(); await audit(p, `PC/${theme} 관리자 통계`); diff --git a/e2e/admin.e2e.ts b/e2e/admin.e2e.ts index 301a0f9..539ab9f 100644 --- a/e2e/admin.e2e.ts +++ b/e2e/admin.e2e.ts @@ -259,6 +259,53 @@ try { await gctx.close(); }); + await step('원곡 찾기: 진행률, 후보 바로 확정, 확정 취소 → 후보, 원곡 없음, 5초 자동 새로고침', async () => { + const c = new Catalog(db); + const now = Date.now(); + const tried = (id: number, at: number) => db.query("INSERT OR REPLACE INTO signals (song_id, kind, value, fetched_at) VALUES (?, 'yt_tried_ytmusic', ?, ?)").run(id, at, at); + const [guess] = c.upsert({ title: '후보곡', artists: [{ name: '후보가수' }], source: 'e2e', ref: 'g' }); + db.query("UPDATE songs SET youtube_status = 'candidate', youtube_source = 'ytmusic', youtube_id = 'candvideo01', youtube_title = '후보곡 (Live)', youtube_channel = '후보가수', embeddable = 1, youtube_checked_at = ? WHERE id = ?").run(now, guess!); + db.query("INSERT INTO youtube_candidates (song_id, video_id, title, channel, duration_sec, score, source) VALUES (?, 'candvideo01', '후보곡 (Live)', '후보가수', 200, 55, 'ytmusic')").run(guess!); + tried(guess!, now); + const [lost] = c.upsert({ title: '못찾은곡', artists: [{ name: '누구' }], source: 'e2e', ref: 'l' }); + tried(lost!, now - 1000); + const [auto] = c.upsert({ title: '자동확정곡', artists: [{ name: '자동가수' }], source: 'e2e', ref: 'a' }); + db.query("UPDATE songs SET youtube_status = 'matched', youtube_source = 'ytmusic', youtube_id = 'autovideo01', youtube_title = '자동확정곡', youtube_channel = '자동가수 - Topic', embeddable = 1, youtube_checked_at = ? WHERE id = ?").run(now, auto!); + tried(auto!, now); + db.query("INSERT INTO collect_jobs (kind, status, done, total, started_at, pid) VALUES ('match-youtube', 'running', 3, 10, ?, 1)").run(now - 60_000); + + await p.getByRole('link', { name: '🔎 원곡 찾기' }).click(); + await p.getByRole('heading', { name: '원곡 찾기' }).waitFor(); + await p.getByText('🔎 지금 찾는 중').waitFor(); + await p.getByText('3 / 10 (30%)').waitFor(); + // 후보 tab is first: one click confirms, and it moves to 확정 + await row(p, '후보곡').getByRole('button', { name: '확정', exact: true }).click(); + await toastSeen(p, "'후보곡' 확정했어요"); + const st = (t: string) => db.query<{ youtube_status: string; youtube_source: string | null }, [string]>('SELECT youtube_status, youtube_source FROM songs WHERE title = ?').get(t)!; + expect(st('후보곡').youtube_status === 'matched', '후보 확정 안 됨'); + await p.getByRole('button', { name: /^확정 \d/ }).click(); + await row(p, '자동확정곡').click(); + await p.getByRole('complementary', { name: '원곡 확인' }).getByRole('button', { name: '확정 취소' }).click(); + await toastSeen(p, '확정을 취소했어요'); + expect(st('자동확정곡').youtube_status === 'candidate' && st('자동확정곡').youtube_source === 'admin', '확정 취소가 후보(관리자)로 안 바뀜'); + await p.screenshot({ path: join(SHOTS, 'youtube-review-panel.png') }); + await p.getByRole('button', { name: /^못 찾음 \d/ }).click(); + await row(p, '못찾은곡').click(); + await p.getByRole('button', { name: '원곡 없음으로 표시' }).click(); + await toastSeen(p, '원곡 없음으로 표시했어요'); + expect(st('못찾은곡').youtube_source === 'admin', '원곡 없음 표시 안 됨'); + // the matcher finds a new song: it shows up by itself within 5 seconds (pointer away from the list) + await p.mouse.move(5, 5); + await p.getByRole('button', { name: /^못 찾음 \d/ }).click(); + const [fresh] = c.upsert({ title: '방금찾은곡', artists: [{ name: '새가수' }], source: 'e2e', ref: 'f' }); + tried(fresh!, Date.now()); + await row(p, '방금찾은곡').waitFor({ timeout: 8000 }); + await p.screenshot({ path: join(SHOTS, 'youtube-review.png'), fullPage: true }); + const acts = db.query<{ action: string }, []>("SELECT action FROM admin_audit WHERE action LIKE 'song.%' ORDER BY id DESC LIMIT 3").all().map((r) => r.action); + expect(acts.includes('song.youtube.unconfirm') && acts.includes('song.youtube.none'), `기록 없음: ${acts}`); + db.query("UPDATE collect_jobs SET status = 'done', finished_at = ? WHERE kind = 'match-youtube' AND status = 'running'").run(Date.now()); + }); + await p.goto(ORIGIN + '/admin/songs'); await p.locator('.data-table tbody tr').first().waitFor(); await p.screenshot({ path: join(SHOTS, 'stage8-songs.png'), fullPage: true });