/** * 관리자 → 원곡 찾기: 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 JobBase { id: number; status: string; done: number; total: number; started_at: number; finished_at: number | null; } interface Job extends JobBase { result: { matched: number; candidate: number; none: number }; source: string | null; lastAt: number | null; perMin: number; eta: number | null; alive: boolean | null; deadline: number | null; recent: { id: number; title: string; artist: string; youtube_status: string; youtube_source: string | null; youtube_title: string | null; youtube_channel: string | null; at: number }[]; log: { at: number; text: string }[]; history: JobBase[]; } 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' }); } /** 1시간 43분 · 12분 · 40초 */ function span(ms: number): string { const m = Math.round(ms / 60_000); if (ms < 60_000) return `${Math.max(0, Math.round(ms / 1000))}초`; return m >= 60 ? `${Math.floor(m / 60)}시간${m % 60 ? ` ${m % 60}분` : ''}` : `${m}분`; } /** 23:46, or 내일 00:12 / 10. 21. 08:10 when it is not today. */ function when(ms: number, now: number): string { const day = (t: number) => new Date(t).toDateString(); if (day(ms) === day(now)) return clock(ms); if (day(ms) === day(now + 86400_000)) return `내일 ${clock(ms)}`; return new Date(ms).toLocaleString('ko-KR', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' }); } /** The daily cron: 08:10 local. */ function nextCron(now: number): number { const d = new Date(now); d.setHours(8, 10, 0, 0); if (d.getTime() <= now) d.setDate(d.getDate() + 1); return d.getTime(); } const SEARCH: Record = { ytmusic: '유튜브 뮤직 (쿠키 사용)', youtube: '유튜브 검색 (쿠키 없이, 정확도 낮음)' }; /** The matcher's log in plain words. */ function logText(t: string): string { let m: RegExpExecArray | null; const n = (x: string) => Number(x).toLocaleString(); if ((m = /^start (\d+) songs via (\w+)(?: deadline (\S+))?/.exec(t))) return `시작: ${n(m[1]!)}곡 · ${SEARCH[m[2]!] ?? m[2]}${m[3] ? ` · ${clock(Date.parse(m[3]))}에 마감` : ''}`; if ((m = /^youtube (done )?(\d+)\/(\d+):? matched (\d+) candidate (\d+) none (\d+)/.exec(t))) return `${m[1] ? '끝: ' : ''}${n(m[2]!)} / ${n(m[3]!)}곡 · 확정 ${n(m[4]!)} · 후보 ${n(m[5]!)} · 못 찾음 ${n(m[6]!)}`; if ((m = /^search failed \((.*)\), waiting 60s/.exec(t))) return `⚠ 검색 실패 (${m[1]}) → 60초 쉬고 다시 해요`; if ((m = /^deadline reached after (\d+)\/(\d+)/.exec(t))) return `마감 시각이 돼서 ${n(m[1]!)} / ${n(m[2]!)}곡에서 멈췄어요`; if ((m = /^stopped: (.*)/.exec(t))) return `⚠ 멈춤: ${m[1]}`; return t; } /** No song finished for this long while running: the run is probably stuck (normal pace is a few seconds a song). */ const STALL_MS = 3 * 60_000; /** 진행 상황: is it running, how far, how fast, when it ends, what it decided, and what it just did. */ function JobStatus({ job, counts, now, onPick }: { job: Job | null | undefined; counts: Record | undefined; now: number; onPick: (id: number) => void }) { const all = counts ? Object.values(counts).reduce((a, b) => a + b, 0) : 0; const footer = (

{counts && all > 0 && ( <> 전체 {all.toLocaleString()}곡 중 게임에 나오는 곡(확정) {counts.matched.toLocaleString()}곡 ({Math.floor((counts.matched / all) * 100)}%) · 아직 안 찾은 곡{' '} {counts.pending.toLocaleString()}곡 ·{' '} )} 다음 자동 실행 {when(nextCron(now), now)} (매일 08:10, 3,000곡까지). 확정한 영상은 저장하는 즉시 새 게임과 다음 문제부터 나와요(지금 재생 중인 곡은 그대로).

); if (!job) return (

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

{footer}
); const running = job.status === 'running'; const left = Math.max(0, job.total - job.done); const pct = job.total ? Math.floor((job.done / job.total) * 100) : 0; const since = job.lastAt ?? job.started_at; const gone = running && job.alive === false; const stalled = running && !gone && now - since > STALL_MS; const lastLog = job.log[job.log.length - 1]; // a search failed and no song has finished since: the matcher waits 60s and tries again const waiting = running && !!lastLog && /^search failed/.test(lastLog.text) && (job.lastAt ?? 0) < lastLog.at; const elapsed = (job.finished_at ?? now) - job.started_at; const r = job.result; const decided = r.matched + r.candidate + r.none; const share = (n: number) => (decided ? `${Math.round((n / decided) * 100)}%` : '-'); const cutByDeadline = running && job.deadline && job.eta && job.eta > job.deadline; let badge: [string, string]; if (gone) badge = ['⚠ 멈춘 것 같아요', 'warn']; else if (stalled) badge = [`⚠ ${span(now - since)}째 진행 없음`, 'warn']; else if (waiting) badge = ['⏳ 검색 실패, 잠깐 쉬는 중', 'warn']; else if (running) badge = ['● 찾는 중', 'live']; else badge = [JOB_STATUS[job.status] ?? job.status, job.status === 'done' ? 'ok' : 'warn']; const stats: [string, string, string?][] = [ ['처리', `${job.done.toLocaleString()} / ${job.total.toLocaleString()}`, `${pct}%`], ['남은 곡', `${left.toLocaleString()}곡`], ['속도', job.perMin ? `${job.perMin.toLocaleString()}곡/분` : '-', job.perMin ? `1곡에 ${(60 / job.perMin).toFixed(1)}초 · 최근 10분` : undefined], [running ? '지난 시간' : '걸린 시간', span(elapsed), `시작 ${when(job.started_at, now)}`], ...(running ? ([ ['남은 시간', job.eta ? `약 ${span(job.eta - now)}` : '-'], ['끝 예상', job.eta ? when(job.eta, now) : '-', cutByDeadline ? `${clock(job.deadline!)} 마감에 멈춰요` : undefined], ] as [string, string, string?][]) : ([['끝난 시각', job.finished_at ? when(job.finished_at, now) : '-']] as [string, string, string?][])), ['마지막 처리', job.lastAt ? ago(job.lastAt, now) : '-', job.lastAt ? clock(job.lastAt) : undefined], ]; return (
{badge[0]} 작업 #{job.id} {pct}% {job.source && 검색: {SEARCH[job.source] ?? job.source}}
{gone &&

작업 기록은 '찾는 중'인데 작업 프로세스가 없어요(서버 재시작 등). 수집 화면에서 다시 실행하면 이어서 찾아요.

} {stalled &&

보통 1곡에 몇 초면 끝나는데 {span(now - since)} 동안 처리한 곡이 없어요. 아래 작업 기록을 확인하고, 계속 그러면 수집 화면에서 멈췄다 다시 실행해 주세요.

} {!running && job.status !== 'done' && lastLog &&

{logText(lastLog.text)}

}
{stats.map(([k, v, sub]) => (
{k} {v} {sub && {sub}}
))}
{cutByDeadline && (

{clock(job.deadline!)}가 되면 정기 작업과 겹치지 않게 멈춰요. 그때까지 약 {Math.round(((job.deadline! - now) / 60_000) * job.perMin).toLocaleString()}곡 더 찾고, 남은 곡은 다음 작업이 이어서 찾아요.

)}
이번 작업 결과 ({decided.toLocaleString()}곡): 확정 {r.matched.toLocaleString()} ({share(r.matched)}) · 후보 {r.candidate.toLocaleString()} ({share(r.candidate)}) · 못 찾음{' '} {r.none.toLocaleString()} ({share(r.none)}) {decided > 0 && ( )}
{job.recent.length > 0 && (
방금 처리한 곡
    {job.recent.map((x) => { const [label, cls] = x.youtube_status === 'none' && x.youtube_source === 'admin' ? ['원곡 없음', ''] : x.youtube_status === 'none' ? ['못 찾음', ''] : (STATUS[x.youtube_status] ?? [x.youtube_status, '']); return (
  • {ago(x.at, now)} {label} {x.artist} {x.youtube_title ? ` → ${x.youtube_title}${x.youtube_channel ? ` · ${x.youtube_channel}` : ''}` : ''}
  • ); })}
)} {job.log.length > 0 && (
작업 기록 (최근 {job.log.length}줄)
    {job.log.map((l, i) => (
  • {clock(l.at)} {logText(l.text)}
  • ))}
)} {job.history.length > 0 && (
지난 작업 {job.history.length}개
    {job.history.map((h) => (
  • #{h.id} {when(h.started_at, now)} 시작 · {JOB_STATUS[h.status] ?? h.status} · {h.done.toLocaleString()} / {h.total.toLocaleString()}곡 {h.finished_at ? ` · ${span(h.finished_at - h.started_at)} 걸림` : ''}
  • ))}
)} {footer}
); } /** 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 pages = data ? Math.max(1, Math.ceil(data.total / data.pageSize)) : 1; const now = Date.now(); return (

원곡 찾기

수집 화면에서 실행·멈추기
(setSelected(id), setEditing(false))} />
{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 ( ); }