이지선다 조회수 자동: 빈 양식에서 조회수 열을 빼고, 올린 뒤 서버가 곡마다 토픽 음원 + MV 조회수를 불러와 더함. 짝은 유튜브 뮤직 노래↔동영상 전환(watch 응답의 counterpart, 쿠키 필요), 조회수는 로그인 없이 player videoDetails.viewCount(안 되면 watch 화면 숫자). quizzes/duel-views.ts가 pending 곡을 한 곡씩 처리(재시작해도 이어서), 쿠키 만료면 남은 곡 모두 이유와 함께 failed. 짝이 없는 곡은 있는 영상 하나만 쓰고 비고 표시. 파일·편집기에 적은 숫자는 그대로 쓰고 다시 불러오기에서 빠짐, 칸을 비우고 저장하면 자동. 편집기: 조회수(토픽·MV)·비고 칸, 불러오는 중 표시와 2초 폴링(저장 안 됨으로 안 잡힘), 조회수 다시 불러오기(전체/곡), 저장 때 편집기의 옛 사본이 서버가 불러온 값을 덮지 않음. 내보내기는 직접 넣은 숫자만 조회수 열에. 파일로 만들기는 조회수 열이 없으면 고른 종류 유지. 014 마이그레이션, 단위·API 테스트, e2e duel 단계, docs 04·10·12

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-11-03 21:07:10 +09:00
parent c55702d440
commit aacc4133b5
20 changed files with 784 additions and 72 deletions

View File

@@ -292,7 +292,7 @@ export function RoomSettings({
/>
</Section>
{allowQuiz && duel && (
<Section title="이지선다 퀴즈" tip="조회수가 든 파일로 만든 이지선다 퀴즈만 고를 수 있어요">
<Section title="이지선다 퀴즈" tip="관리자 → 퀴즈에서 이지선다로 만든 퀴즈만 고를 수 있어요">
<QuizPicker kind="duel" chosen={c.quizId ? { id: c.quizId, name: c.quizName } : null} songs={pool.playable} ro={ro} onPick={(quizId) => onPatch({ quizId })} />
</Section>
)}
@@ -642,7 +642,7 @@ function QuizPicker({ kind, chosen, songs, ro, onPick }: { kind: QuizKind; chose
<div className="quiz-pick" role="listbox" aria-label={kind === 'duel' ? '이지선다 퀴즈 목록' : '제작된 퀴즈 목록'}>
{list?.length === 0 && (
<span className="muted small" style={{ padding: 10 }}>
{q.trim() ? '검색 결과가 없어요.' : kind === 'duel' ? '고를 수 있는 이지선다 퀴즈가 없어요. 관리자 → 퀴즈 → 파일로 만들기에서 조회수가 든 파일로 만들 수 있어요.' : '고를 수 있는 퀴즈가 없어요.'}
{q.trim() ? '검색 결과가 없어요.' : kind === 'duel' ? '고를 수 있는 이지선다 퀴즈가 없어요. 관리자 → 퀴즈 → 파일로 만들기에서 이지선다로 만들 수 있어요.' : '고를 수 있는 퀴즈가 없어요.'}
</span>
)}
{list?.map((x) => (

View File

@@ -84,8 +84,8 @@ export function QuizFileImport({
setHeaderAt(h);
const cols = guessColumns(rows[h] ?? []);
setColumns(cols);
// a 조회수 column: this is an 이지선다 file
if (!fixedKind) setChosenKind(cols.includes('views') ? 'duel' : 'normal');
// a 조회수 column: this is an 이지선다 file (without one the kind picked above stays: the 이지선다 양식 has none)
if (!fixedKind && cols.includes('views')) setChosenKind('duel');
};
const open = async (f: File) => {
if (f.size > MAX_BYTES) return toast('파일이 너무 커요(20MB까지).', 'error');
@@ -105,7 +105,7 @@ export function QuizFileImport({
const sheet = file?.sheets[sheetIdx];
const header = sheet?.rows[headerAt] ?? [];
const parsed = useMemo(() => (sheet ? parseQuizRows(sheet.rows, columns, headerAt, kind) : null), [sheet, columns, headerAt, kind]);
const missing = (kind === 'duel' ? (['link', 'answer', 'views'] as const) : (['link', 'answer'] as const)).filter((c) => !columns.includes(c));
const missing = (['link', 'answer'] as const).filter((c) => !columns.includes(c));
const duel = kind === 'duel';
const bad = parsed?.rows.filter((r) => r.problem) ?? [];
const items = parsed?.items ?? [];
@@ -178,8 +178,9 @@ export function QuizFileImport({
</div>
{!file && duel && (
<p className="muted small" style={{ margin: 0 }}>
한 줄에 한 곡씩, 첫 줄은 열 이름이에요. <b>유튜브 영상 링크</b>, <b>제목</b>, <b>조회수</b>는 꼭 있어야 하고 <b>가수</b>는 카드에 같이 보여요. 조회수는 1234567, 1,234,567,
123만, 1.2억처럼 써도 돼요. 게임에서는 곡을 무작위로 두 개씩 짝지어 A/B 카드로 보여 줘요.
한 줄에 한 곡씩, 첫 줄은 열 이름이에요. <b>유튜브 영상 링크</b>와 <b>제목</b>은 꼭 있어야 하고 <b>가수</b>는 카드에 같이 보여요. 조회수는 올린 뒤 서버가 곡마다
유튜브 뮤직의 <b>토픽 음원 + MV</b> 조회수를 더해 불러와요(링크는 토픽이든 MV든 괜찮아요). 직접 정한 숫자를 쓰려면 <b>조회수</b> 열에 1234567, 123만, 1.2억처럼 적으면 그 숫자를
그대로 써요. 게임에서는 곡을 무작위로 두 개씩 짝지어 A/B 카드로 보여 줘요.
</p>
)}
{!file && !duel && (
@@ -279,8 +280,8 @@ export function QuizFileImport({
</td>
<td className="small">{it.artist || <span className="muted">-</span>}</td>
{duel ? (
<td className="small mono" title={`${it.views?.toLocaleString('ko-KR')}회`}>
{viewsLabel(it.views ?? 0)}회
<td className="small mono" title={it.views !== null ? `${it.views.toLocaleString('ko-KR')}회 (파일에 적힌 값)` : '올린 뒤 토픽 + MV 조회수를 불러와요'}>
{it.views !== null ? `${viewsLabel(it.views)}회` : <span className="muted">자동</span>}
</td>
) : (
<td className="small">{[...it.hints, '초성'].join(' → ')}</td>

View File

@@ -10,10 +10,13 @@ import {
DUEL_FLOWS,
DUEL_SECS,
LISTEN_SECS,
PENDING_VIEWS,
QUIZ_VISIBILITIES,
duelViewsNote,
listenLabel,
parseViews,
viewsLabel,
type DuelViews,
type QuizDetail,
type QuizItem,
type QuizKind,
@@ -70,8 +73,8 @@ export function QuizzesPage() {
)}
</div>
<p className="muted">
직접 만든 퀴즈예요. 일반 퀴즈는 방 설정에서 "제작된 퀴즈"를 고르면 곡이 순서대로(또는 섞어서) 전부 나오고, 듣고맞추기에서만 쓸 수 있어요. 🆚 이지선다 퀴즈는 조회수가 든 파일로 만들고, 이지선다
모드에서만 쓸 수 있어요.
직접 만든 퀴즈예요. 일반 퀴즈는 방 설정에서 "제작된 퀴즈"를 고르면 곡이 순서대로(또는 섞어서) 전부 나오고, 듣고맞추기에서만 쓸 수 있어요. 🆚 이지선다 퀴즈는 파일로 만들고(조회수는
서버가 토픽 + MV로 불러와요), 이지선다 모드에서만 쓸 수 있어요.
</p>
{fromFile && (
<QuizFileImport
@@ -159,8 +162,18 @@ export interface DbInfo {
}
/** A song picked in the editor (search, address, playlist): answers, hints and positions start empty. */
type NewSong = Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'hints' | 'fromFile' | 'auto' | 'startSec' | 'highlightSec' | 'views'>;
const fresh = (it: NewSong): QuizItem => ({ ...it, titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, auto: true, startSec: null, highlightSec: null, views: null });
type NewSong = Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'hints' | 'fromFile' | 'auto' | 'startSec' | 'highlightSec' | 'views' | 'viewsAuto'>;
const fresh = (it: NewSong): QuizItem => ({ ...it, titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, auto: true, startSec: null, highlightSec: null, views: null, viewsAuto: null });
/** 이지선다 조회수 자동: what the server fetched, put into the editor's copy (songs still 자동 there with the same video). */
type FetchedViews = { id: number; videoId: string; views: number | null; viewsAuto: DuelViews };
function withFetched<T extends QuizItem>(items: T[], fetched: FetchedViews[]): T[] {
const by = new Map(fetched.map((f) => [f.id, f]));
return items.map((it) => {
const f = it.id ? by.get(it.id) : undefined;
return f && it.viewsAuto && f.videoId === it.videoId ? { ...it, views: f.views, viewsAuto: f.viewsAuto } : it;
});
}
let keySeq = 0;
const newKey = () => `k${++keySeq}`;
@@ -236,6 +249,46 @@ export function QuizEditor() {
setBusy(false);
}
}, [id]);
// 이지선다 조회수 자동: while songs wait, the server's results are taken in (also into the saved copy: not a change)
const waiting = !!draft?.items.some((i) => i.viewsAuto?.state === 'pending');
useEffect(() => {
if (!waiting) return;
const t = setInterval(() => {
apiCall<{ items: FetchedViews[] }>('GET', `/api/admin/quizzes/${id}/views`)
.then((r) => {
setDraft((d) => (d ? { ...d, items: withFetched(d.items, r.items) } : d));
setSaved((json) => {
if (!json) return json;
const p = JSON.parse(json) as ReturnType<typeof payload>;
return JSON.stringify({ ...p, items: withFetched(p.items, r.items) });
});
})
.catch(() => {});
}, 2000);
return () => clearInterval(t);
}, [waiting, id]);
const refreshViews = useCallback(
async (itemIds?: number[]) => {
try {
const r = await apiCall<{ queued: number }>('POST', `/api/admin/quizzes/${id}/views`, itemIds ? { itemIds } : {});
if (!r.queued) return toast('다시 불러올 곡이 없어요. 새로 넣은 곡은 저장하면 불러와요.');
const ids = itemIds ? new Set(itemIds) : null;
// waiting from now on (a written number named here becomes 자동): the poll above brings the results
const mark = <T extends QuizItem>(items: T[]) =>
items.map((it) => (it.id && (ids ? ids.has(it.id) : it.viewsAuto) ? { ...it, viewsAuto: { ...(it.viewsAuto ?? PENDING_VIEWS), state: 'pending' as const } } : it));
setDraft((d) => (d ? { ...d, items: mark(d.items) } : d));
setSaved((json) => {
if (!json) return json;
const p = JSON.parse(json) as ReturnType<typeof payload>;
return JSON.stringify({ ...p, items: mark(p.items) });
});
toast(`${r.queued}곡의 조회수를 다시 불러와요.`);
} catch (e) {
toast((e as Error).message, 'error');
}
},
[id],
);
// DB facts (aliases, the DB highlight for 자동) of songs added since loading: fetched as soon as they appear
const asked = useRef(new Set<number>());
useEffect(() => {
@@ -312,6 +365,17 @@ export function QuizEditor() {
</Link>
<h1 className="grow">{draft.name || '이름 없는 퀴즈'}</h1>
{dirty ? <span className="badge warn" role="status">● 저장하지 않은 변경이 있어요</span> : <span className="muted small">저장됨</span>}
{kind === 'duel' && (
<button
type="button"
className="btn"
disabled={!draft.items.some((i) => i.id && i.viewsAuto && i.viewsAuto.state !== 'pending')}
onClick={() => void refreshViews()}
title="자동으로 불러온 곡의 토픽·MV 조회수를 지금 값으로 다시 불러와요 (직접 넣은 조회수는 그대로)"
>
🔄 조회수 다시 불러오기
</button>
)}
<button type="button" className="btn" disabled={!draft.items.length} onClick={() => exportQuiz(draft.name, draft.items, kind)} title="곡 목록을 다시 올릴 수 있는 엑셀 파일로 받아요">
📥 엑셀로 내보내기
</button>
@@ -361,6 +425,7 @@ export function QuizEditor() {
fileOpen={fileOpen}
setFileOpen={setFileOpen}
onHints={() => draft.settings.hint === 'none' && set({ settings: { ...draft.settings, hint: 'manual' } })}
onRefreshViews={(itemId) => void refreshViews([itemId])}
/>
) : (
<SettingsTab kind={kind} draft={draft} onChange={set} onDelete={() => setConfirmDelete(true)} />
@@ -466,6 +531,7 @@ function SongsTab({
fileOpen,
setFileOpen,
onHints,
onRefreshViews,
}: {
kind: QuizKind;
items: DraftItem[];
@@ -478,6 +544,7 @@ function SongsTab({
setFileOpen: (on: boolean) => void;
/** Songs with their own hints came in: hints should not stay off. */
onHints: () => void;
onRefreshViews: (itemId: number) => void;
}) {
const [sel, setSel] = useState<string | null>(null);
const [dragKey, setDragKey] = useState<string | null>(null);
@@ -551,9 +618,15 @@ function SongsTab({
<p className="muted">아직 곡이 없어요. 위에서 제목·가수로 찾거나 유튜브 주소를 붙여 넣어 추가해 주세요.</p>
) : (
<div className="table-wrap">
{duel && items.some((i) => i.views === null) && (
{duel && items.some((i) => i.viewsAuto?.state === 'pending') && (
<p className="muted small" role="status" style={{ margin: '8px 10px' }}>
⏳ 토픽·MV 조회수를 불러오는 중이에요 ({items.filter((i) => i.viewsAuto?.state === 'pending').length}곡 남음). 다 불러오면 저절로 채워져요.
</p>
)}
{duel && items.some((i) => i.views === null && i.viewsAuto?.state !== 'pending') && (
<p className="warn-text small" style={{ margin: '8px 10px' }}>
조회수가 없는 곡 {items.filter((i) => i.views === null).length}곡은 게임에 나오지 않아요. 곡을 눌러 조회수를 넣어 주세요.
조회수가 없는 곡 {items.filter((i) => i.views === null && i.viewsAuto?.state !== 'pending').length}곡은 게임에 나오지 않아요. 곡을 눌러 조회수를 직접 넣거나 다시
불러와 주세요.{items.some((i) => i.views === null && !i.viewsAuto) && ' 새로 넣은 곡은 저장하면 불러와요.'}
</p>
)}
<table className="data-table quiz-songs">
@@ -563,6 +636,7 @@ function SongsTab({
<th style={{ width: 44 }}>번호</th>
<th>노래</th>
<th>{duel ? '조회수' : '추가 정답'}</th>
{duel && <th>비고</th>}
<th>길이</th>
<th>재생 위치</th>
<th style={{ width: 120 }} />
@@ -607,9 +681,12 @@ function SongsTab({
{it.hints.length > 0 && <div className="muted small">힌트: {it.hints.join(' → ')}</div>}
</td>
{duel ? (
<td className="mono small" title={it.views !== null ? `${it.views.toLocaleString('ko-KR')}회` : undefined}>
{it.views !== null ? `${viewsLabel(it.views)}회` : <span className="warn-text">없음</span>}
</td>
<>
<td className="mono small" title={it.views !== null ? `${it.views.toLocaleString('ko-KR')}회` : undefined}>
<ViewsCell item={it} />
</td>
<td className="small">{duelViewsNote(it) ?? <span className="muted">-</span>}</td>
</>
) : (
<td className="small">{[...it.titleAnswers, ...it.artistAnswers].join(', ') || <span className="muted">-</span>}</td>
)}
@@ -649,6 +726,7 @@ function SongsTab({
onRemove={() => remove(selected.key)}
onClose={() => setSel(null)}
isDuplicate={(videoId) => items.some((x) => x.key !== selected.key && x.videoId === videoId)}
onRefreshViews={selected.id ? () => onRefreshViews(selected.id!) : null}
/>
)}
</div>
@@ -1038,6 +1116,24 @@ function ChipsInput({ values, onChange, label, placeholder }: { values: string[]
);
}
/** 이지선다 조회수 칸: the number the game uses, how it stands when fetched (토픽 · MV each). */
function ViewsCell({ item }: { item: QuizItem }) {
const a = item.viewsAuto;
const total = item.views !== null ? `${viewsLabel(item.views)}회` : null;
if (a?.state === 'pending') return <span className="muted">불러오는 중…{total && ` (${total})`}</span>;
if (item.views === null) return a ? <span className="warn-text">없음</span> : <span className="muted">저장하면 불러와요</span>;
return (
<>
{total}
{a?.state === 'done' && (
<div className="muted">{[a.topicViews !== null && `토픽 ${viewsLabel(a.topicViews)}`, a.mvViews !== null && `MV ${viewsLabel(a.mvViews)}`].filter(Boolean).join(' · ')}</div>
)}
</>
);
}
const fullViews = (n: number | null) => (n === null ? '-' : `${n.toLocaleString('ko-KR')}회`);
function ItemPanel({
duel,
item,
@@ -1050,6 +1146,7 @@ function ItemPanel({
onRemove,
onClose,
isDuplicate,
onRefreshViews,
}: {
duel: boolean;
item: DraftItem;
@@ -1063,12 +1160,20 @@ function ItemPanel({
onRemove: () => void;
onClose: () => void;
isDuplicate: (videoId: string) => boolean;
/** 이지선다: fetch this saved song's views again (null: not saved yet — saving fetches them). */
onRefreshViews: (() => void) | null;
}) {
const [url, setUrl] = useState('');
const [pos, setPos] = useState(String(index + 1));
useEffect(() => setPos(String(index + 1)), [index]);
const [viewsText, setViewsText] = useState(item.views === null ? '' : String(item.views));
// 자동 songs show the fetched numbers above; the box is for a number of one's own
const [viewsText, setViewsText] = useState(item.viewsAuto || item.views === null ? '' : String(item.views));
const isAuto = !!item.viewsAuto;
useEffect(() => {
if (isAuto) setViewsText('');
}, [isAuto]);
const viewsBad = parseViews(viewsText) === undefined;
const a = item.viewsAuto;
const changeVideo = async () => {
try {
const v = await apiCall<VideoInfo>('POST', '/api/admin/quizzes/pick/video', { url: url.trim() });
@@ -1108,21 +1213,63 @@ function ItemPanel({
<input className="input" value={item.artist} maxLength={200} onChange={(e) => onPatch({ artist: e.target.value })} />
</label>
{duel && (
<label className="field">
조회수 (예: 1234567, 123만, 1.2억)
<div className="field">
조회수
{a ? (
<div className="stack small" style={{ gap: 4 }} role="status">
{a.state === 'pending' ? (
<span className="muted">토픽·MV 조회수를 불러오는 중이에요…</span>
) : a.state === 'failed' ? (
<span className="warn-text">{a.error}</span>
) : (
<>
<span>
<b>{fullViews(item.views)}</b> = 토픽 {fullViews(a.topicViews)} + MV {fullViews(a.mvViews)}
</span>
<span className="muted">
{a.topicId && (
<a href={`https://youtu.be/${a.topicId}`} target="_blank" rel="noreferrer">
토픽 영상 ↗
</a>
)}
{a.topicId && a.mvId && ' · '}
{a.mvId && (
<a href={`https://youtu.be/${a.mvId}`} target="_blank" rel="noreferrer">
MV ↗
</a>
)}
{a.at && ` · ${new Date(a.at).toLocaleString('ko-KR')}에 불러옴`}
</span>
{duelViewsNote(item) && <span className="badge warn" style={{ alignSelf: 'flex-start' }}>비고: {duelViewsNote(item)}</span>}
</>
)}
</div>
) : (
<span className="muted small">
{item.views === null ? '저장하면 토픽·MV 조회수를 자동으로 불러와요.' : item.fromFile ? '파일에 적힌 조회수를 써요.' : '직접 넣은 조회수를 써요.'}
</span>
)}
<input
className="input"
value={viewsText}
inputMode="numeric"
aria-label="조회수 직접 넣기"
placeholder={a ? '직접 넣기 (예: 1234567, 123만, 1.2억)' : '예: 1234567, 123만, 1.2억 (비우면 자동)'}
onChange={(e) => {
setViewsText(e.target.value);
const v = parseViews(e.target.value);
if (v !== undefined) onPatch({ views: v });
// a number of one's own replaces the fetched one; emptying the box goes back to 자동 (fetched on save)
if (v !== undefined && (v !== null || !a)) onPatch({ views: v, viewsAuto: null });
}}
aria-invalid={viewsBad}
/>
{viewsBad ? <span className="field-error small">조회수를 읽을 수 없어요.</span> : item.views !== null && <span className="muted small">{item.views.toLocaleString('ko-KR')}회</span>}
</label>
{viewsBad ? <span className="field-error small">조회수를 읽을 수 없어요.</span> : !a && item.views !== null && <span className="muted small">{item.views.toLocaleString('ko-KR')}회</span>}
{onRefreshViews && (
<button type="button" className="btn btn-sm" style={{ alignSelf: 'flex-start' }} disabled={a?.state === 'pending'} onClick={onRefreshViews}>
🔄 {a ? '조회수 다시 불러오기' : '자동으로 불러오기 (토픽 + MV)'}
</button>
)}
</div>
)}
{!duel && (
<>