재생목록으로 엑셀 만들기: 관리자 → 퀴즈 목록 카드. 플레이리스트 가져오기와 같은 검토(서버 DB 곡, 영상 제목 정리, 스포티파이는 유튜브 뮤직 검색, 다른 사이트 재생 확인) 결과를 파일로 만들기가 그대로 읽는 엑셀로 받음 — 시트 '퀴즈'(순번·유튜브 영상 링크·제목·가수·시작(초)·하이라이트(초)·길이(초)·비고)와 '빠진 곡'(재생 막힘·없는 영상·못 찾은 곡·같은 영상, 이유와 함께; 제목 열이 없어 곡으로 읽히지 않음). 비고: DB 곡 / 제목·가수 확인 필요(영상 제목에 가수-제목 형식이 없어 채널 이름을 가수로 씀, 플레이리스트 가져오기에도 표시) / 확인 필요 / 유튜브 뮤직에서 찾음. 조회수 열은 넣지 않음(이지선다는 서버가 불러옴). 파일로 만들기·파일에서 가져오기: '시작·하이라이트가 빈 곡: 자동 / 처음부터' 선택(처음부터 = 0/0으로 적어 하이라이트부터 방에서도 처음부터), 길이(초) 열 읽기. 파일로 만들기의 자동 곡은 서버 DB에 같은 영상이 있으면 그 하이라이트(직접 위치로)와 길이를 씀 — 파일 곡은 DB와 연결하지 않아 자동이 늘 처음부터였던 것. writeXlsxSheets(여러 시트). 단위·API 테스트, e2e quiz 단계, docs 10·12

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-11-03 23:20:04 +09:00
parent 8a52fd3b68
commit 70edadfe36
13 changed files with 441 additions and 40 deletions

View File

@@ -2,6 +2,7 @@
import { afterEach, expect, test } from 'bun:test';
import type { ServerMessage } from '@mq/shared';
import { Catalog } from './collector/catalog';
import { cleanVideoTitle } from './quizzes/playlist';
import { Client, TEST_SUPERADMINS, api, boot, discordLogin, guest, sleep } from './test-utils';
type Msg<T extends ServerMessage['t']> = Extract<ServerMessage, { t: T }>;
@@ -208,7 +209,7 @@ test('플레이리스트 가져오기: DB songs by video, cleaned YouTube titles
expect(job).toMatchObject({ status: 'done', name: '내 플레이리스트', total: 4 });
const rows = job.rows as { title: string; artist: string; videoId: string | null; songId: number | null; status: string }[];
expect(rows[0]).toMatchObject({ status: 'db', songId: song, title: '좋은 날', artist: '아이유', videoId: 'goodday0001' });
expect(rows[1]).toMatchObject({ status: 'video', title: 'LOVE DIVE', artist: 'IVE 아이브', videoId: 'lovedive001' });
expect(rows[1]).toMatchObject({ status: 'video', title: 'LOVE DIVE', artist: 'IVE 아이브', videoId: 'lovedive001', note: '' });
expect(rows[2]).toMatchObject({ status: 'found', videoId: 'hypeboy0001' });
expect(rows[3]).toMatchObject({ status: 'missing', videoId: null });
// someone else's job is not visible
@@ -269,8 +270,9 @@ test('파일로 만들기: values as written, hints by vote, never sent to 검
const q = (await api(s.base, `/api/admin/quizzes/${r.body.id}`, { cookie: sa })).body.quiz;
expect(q.settings.hint).toBe('manual');
expect(q.items).toMatchObject([
{ songId: null, title: '리그 오브 레전드', artist: 'Still Here', hints: ['AOS(MOBA)'], fromFile: true },
{ songId: null, title: '원신', artist: '', hints: ['확인필요'], fromFile: true },
// 자동: the DB song with the same video lends its highlight (as the song's own positions), still unlinked
{ songId: null, title: '리그 오브 레전드', artist: 'Still Here', hints: ['AOS(MOBA)'], fromFile: true, auto: false, startSec: 0, highlightSec: 61 },
{ songId: null, title: '원신', artist: '', hints: ['확인필요'], fromFile: true, auto: true, durationSec: 200 },
]);
// 전체공개 save: file songs stay out of 검토 대기, an editor song next to them does not
const saved = await api(s.base, `/api/admin/quizzes/${q.id}`, {
@@ -316,3 +318,10 @@ test('파일로 만들기: values as written, hints by vote, never sent to 검
cl.close();
}
});
test('영상 제목 정리: 가수 - 제목 / 가수 \'제목\' / 토픽은 그대로, 형식이 다르면 채널 이름을 가수로 쓰고 확인 필요로 표시', () => {
expect(cleanVideoTitle('아이유(IU) - 좋은 날 (Official MV)', 'LOEN')).toEqual({ title: '좋은 날', artist: '아이유(IU)', guessed: false });
expect(cleanVideoTitle("IVE 아이브 'LOVE DIVE' MV", 'STARSHIP')).toEqual({ title: 'LOVE DIVE', artist: 'IVE 아이브', guessed: false });
expect(cleanVideoTitle('Ditto', 'NewJeans - Topic')).toEqual({ title: 'Ditto', artist: 'NewJeans', guessed: false });
expect(cleanVideoTitle('밤편지 (Official MV)', '아이유 공식')).toEqual({ title: '밤편지', artist: '아이유', guessed: true });
});

View File

@@ -82,8 +82,17 @@ export function mountQuizAdmin(app: Hono<Env>, d: QuizAdminDeps, h: { actor: (c:
if (limits.maxSongs && p.data.items.length > limits.maxSongs) return c.json({ error: `퀴즈 하나에는 곡을 ${limits.maxSongs}곡까지 넣을 수 있어요.` }, 400);
const id = d.quizzes.create(h.actor(c), p.data.name, limits, Date.now(), p.data.kind);
if (typeof id === 'string') return c.json({ error: id }, 400);
// 이지선다: a 조회수 written in the file is used as is, the others are fetched (토픽 + MV) after saving
const items = p.data.items.map((it) => ({ ...it, id: undefined, songId: null, fromFile: true, viewsAuto: null, ...(duel ? {} : { views: null }) }));
// 자동 (시작·하이라이트 칸이 빈 곡): the item stays unlinked (values as written), so the DB song with this very video
// lends its highlight (stored as the song's own positions) and its length (for the 30% rule when there is no highlight)
const sameVideo = d.db.query<{ highlight_sec: number | null; duration_sec: number | null }, [string]>(
"SELECT highlight_sec, duration_sec FROM songs WHERE youtube_id = ? AND youtube_status = 'matched' AND deleted_at IS NULL ORDER BY highlight_sec IS NULL, id LIMIT 1",
);
const items = p.data.items.map((it) => {
const s = it.auto ? sameVideo.get(it.videoId) : null;
const pos = s?.highlight_sec != null ? { auto: false, startSec: 0, highlightSec: s.highlight_sec } : {};
// 이지선다: a 조회수 written in the file is used as is, the others are fetched (토픽 + MV) after saving
return { ...it, ...pos, durationSec: it.durationSec ?? s?.duration_sec ?? null, id: undefined, songId: null, fromFile: true, viewsAuto: null, ...(duel ? {} : { views: null }) };
});
// songs with their own hints: hints come by vote unless the maker changes it in 설정
const settings = { ...DEFAULT_QUIZ_SETTINGS, ...(items.some((it) => it.hints.length) ? { hint: 'manual' as const } : {}) };
const saved = d.quizzes.save(id, { name: p.data.name, description: '', visibility: 'private', settings, items }, limits);

View File

@@ -46,15 +46,18 @@ export async function loadPlaylist(ll: Lavalink, url: string, fetchImpl: typeof
const NOISE = /\s*[([【][^)\]】]*(official|m\/?v|music video|lyric|audio|visuali[sz]er|performance|teaser|live clip|가사|뮤직비디오)[^)\]】]*[)\]】]\s*/gi;
/** "아이유(IU) - 좋은 날 (Official MV)" → 좋은 날 / 아이유(IU); "IVE 아이브 'LOVE DIVE' MV" → LOVE DIVE / IVE 아이브; Topic channels are the artist. */
export function cleanVideoTitle(title: string, channel: string): { title: string; artist: string } {
/**
* "아이유(IU) - 좋은 날 (Official MV)" → 좋은 날 / 아이유(IU); "IVE 아이브 'LOVE DIVE' MV" → LOVE DIVE / IVE 아이브; Topic channels are the artist.
* `guessed`: the title had neither form, so the whole title is the song and the channel name the artist (worth a look).
*/
export function cleanVideoTitle(title: string, channel: string): { title: string; artist: string; guessed: boolean } {
const t = title.replace(NOISE, ' ').replace(/\s+(M\/?V|MV|Official Video)$/i, '').replace(/\s+/g, ' ').trim();
if (/ - Topic$/.test(channel)) return { title: t, artist: channel.replace(/ - Topic$/, '') };
if (/ - Topic$/.test(channel)) return { title: t, artist: channel.replace(/ - Topic$/, ''), guessed: false };
const dash = /^(.+?)\s+[-–—]\s+(.+)$/.exec(t);
if (dash) return { artist: dash[1]!.trim(), title: dash[2]!.trim() };
if (dash) return { artist: dash[1]!.trim(), title: dash[2]!.trim(), guessed: false };
const quoted = /^(.+?)\s*['"‘“『「](.+?)['"’”』」]/.exec(t);
if (quoted) return { artist: quoted[1]!.trim(), title: quoted[2]!.trim() };
return { title: t, artist: channel.replace(/(Official|VEVO|공식)$/i, '').trim() || channel };
if (quoted) return { artist: quoted[1]!.trim(), title: quoted[2]!.trim(), guessed: false };
return { title: t, artist: channel.replace(/(Official|VEVO|공식)$/i, '').trim() || channel, guessed: true };
}
export type ImportStatus = 'db' | 'video' | 'found' | 'check' | 'missing' | 'blocked';
@@ -128,13 +131,13 @@ async function runImport(d: ImportDeps, job: ImportJob, tracks: LavalinkTrack[])
for (const [i, t] of tracks.entries()) {
const dur = t.length ? Math.round(t.length / 1000) : null;
const yt = t.sourceName === 'youtube';
const named = yt ? cleanVideoTitle(t.title, t.author) : { title: t.title, artist: t.author };
const named = yt ? cleanVideoTitle(t.title, t.author) : { title: t.title, artist: t.author, guessed: false };
const row: ImportRow = { n: i + 1, source: { title: t.title, artist: t.author }, title: named.title, artist: named.artist, durationSec: dur, videoId: null, songId: null, status: 'missing', note: '' };
const dbSong = (yt ? byVideo.get(t.identifier) : null) ?? byKey.get(songMatchKey(named.title, named.artist));
if (yt) {
row.videoId = t.identifier;
if (dbSong) Object.assign(row, { songId: dbSong.id, title: dbSong.title, artist: dbSong.artist, status: 'db', note: '서버 DB 곡 (플레이리스트 영상 사용)' });
else row.status = 'video';
else Object.assign(row, { status: 'video', note: named.guessed ? '제목·가수 확인 필요 (영상 제목 형식이 달라 채널 이름을 가수로 씀)' : '' });
const e = await d.embed(t.identifier);
if (e.state !== 'ok') Object.assign(row, { status: 'blocked', note: e.state === 'noembed' ? '다른 사이트 재생이 막힌 영상' : e.state === 'dead' ? '없는 영상' : '영상 확인 실패' });
} else if (dbSong?.youtube_id && dbSong.youtube_status === 'matched') {

View File

@@ -0,0 +1,126 @@
/**
* 재생목록으로 엑셀 만들기 (관리자 → 퀴즈): a playlist address → the server checks every song (플레이리스트 가져오기의 같은
* 작업: 서버 DB 곡, 영상 제목 정리, 스포티파이는 유튜브 뮤직에서 찾기, 다른 사이트 재생 확인) → a quiz file to fill in
* 시작·하이라이트 and upload with 파일로 만들기 (일반 or 이지선다). Songs that would not play go to the sheet 빠진 곡.
*/
import { useEffect, useMemo, useState } from 'react';
import { playlistSheets, writeXlsxSheets, type PlaylistSheetRow } from '@mq/shared/lite';
import { apiCall } from '../../net/api';
import { toast } from '../../store/toast';
import { download } from './QuizFile';
interface ImportJob {
id: string;
name: string;
status: 'running' | 'done' | 'failed';
done: number;
total: number;
rows: PlaylistSheetRow[];
error: string | null;
}
export function PlaylistSheet({ onClose }: { onClose: () => void }) {
const [url, setUrl] = useState('');
const [job, setJob] = useState<ImportJob | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
if (!job || job.status !== 'running') return;
const t = setTimeout(() => {
apiCall<{ job: ImportJob }>('GET', `/api/admin/quizzes/pick/playlist/${job.id}`)
.then((r) => setJob(r.job))
.catch((e: Error) => toast(e.message, 'error'));
}, 1000);
return () => clearTimeout(t);
}, [job]);
const begin = async () => {
setBusy(true);
try {
setJob((await apiCall<{ job: ImportJob }>('POST', '/api/admin/quizzes/pick/playlist', { url: url.trim() })).job);
} catch (e) {
toast((e as Error).message, 'error');
} finally {
setBusy(false);
}
};
const sheets = useMemo(() => (job?.status === 'done' ? playlistSheets(job.rows) : null), [job]);
const kept = sheets ? sheets[0]!.rows.slice(1) : [];
const left = sheets ? sheets[1]!.rows.slice(1) : [];
const toCheck = kept.filter((r) => String(r[7] ?? '').includes('확인 필요')).length;
const fileName = job?.name.trim() || '재생목록 퀴즈';
return (
<div className="card stack" style={{ gap: 10 }}>
<div className="row" style={{ justifyContent: 'space-between' }}>
<b>🔗 재생목록으로 엑셀 만들기</b>
<button type="button" className="btn btn-sm btn-ghost" onClick={onClose} aria-label="닫기">
✕
</button>
</div>
<form
className="row"
onSubmit={(e) => {
e.preventDefault();
if (url.trim()) void begin();
}}
>
<input className="input grow" value={url} onChange={(e) => setUrl(e.target.value)} placeholder="유튜브·유튜브 뮤직·스포티파이 재생목록 주소" aria-label="재생목록 주소" />
<button className="btn btn-primary" disabled={busy || !url.trim() || job?.status === 'running'}>
{busy ? '불러오는 중…' : '검토 시작'}
</button>
</form>
<p className="muted small" style={{ margin: 0 }}>
곡마다 서버 노래 DB, 영상 제목, 다른 사이트 재생 여부를 확인해서 <b>순번 · 유튜브 영상 링크 · 제목 · 가수 · 시작(초) · 하이라이트(초) · 길이(초) · 비고</b> 엑셀을
만들어요. 시작·하이라이트를 채우고(비워 두면 올릴 때 자동 / 처음부터 중에 골라요) <b>파일로 만들기</b>에 그대로 올리면 돼요. 일반 퀴즈는 제목이 정답, 가수가 정답 공개 때
같이 보이는 설명이 되고, 이지선다는 조회수를 서버가 불러와요. 재생이 막혔거나 없는 영상, 같은 영상은 <b>빠진 곡</b> 시트로 옮겨요.
</p>
{job && (
<div className="stack" style={{ gap: 4 }}>
<span className="small">
<b>{job.name || '재생목록'}</b> · {job.status === 'running' ? `검토 중 ${job.done}/${job.total}곡` : job.status === 'failed' ? `실패: ${job.error}` : `${job.total}곡 검토 끝`}
{sheets && (
<span className="muted">
{' '}
· 엑셀에 넣을 곡 {kept.length}
{toCheck > 0 && ` (확인 필요 ${toCheck})`} · 빠진 곡 {left.length}
</span>
)}
</span>
<progress className="yt-progress" max={job.total} value={job.done} />
</div>
)}
{sheets && (
<>
{left.length > 0 && (
<div className="table-wrap" style={{ maxHeight: 200, overflowY: 'auto' }}>
<table className="data-table">
<thead>
<tr>
<th style={{ width: 60 }}>순번</th>
<th>곡 (재생목록)</th>
<th>빠진 이유</th>
</tr>
</thead>
<tbody>
{left.map((r) => (
<tr key={String(r[0])}>
<td className="mono">{r[0]}</td>
<td className="small">
{r[3]} - {r[2]}
</td>
<td className="warn-text small">{r[4]}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="row">
<button type="button" className="btn btn-primary" disabled={!kept.length && !left.length} onClick={() => download(fileName, writeXlsxSheets(sheets))}>
📥 엑셀 받기 ({kept.length}곡)
</button>
{toCheck > 0 && <span className="muted small">비고에 "확인 필요"라고 적힌 곡은 영상을 보고 제목·가수를 고쳐 주세요.</span>}
</div>
</>
)}
</div>
);
}

View File

@@ -16,6 +16,7 @@ import {
quizToRows,
readSheetFile,
writeXlsx,
type BlankPositions,
type QuizColumn,
type QuizItem,
type QuizKind,
@@ -28,7 +29,7 @@ import { Seg } from '../../components/RoomSettings';
const MAX_BYTES = 20 * 1024 * 1024;
const colLabel = (c: QuizColumn, kind: QuizKind) => (kind === 'duel' ? (DUEL_COLUMN_LABEL[c] ?? QUIZ_COLUMN_LABEL[c]) : QUIZ_COLUMN_LABEL[c]);
function download(name: string, bytes: Uint8Array) {
export function download(name: string, bytes: Uint8Array) {
const url = URL.createObjectURL(new Blob([bytes as Uint8Array<ArrayBuffer>], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }));
const a = document.createElement('a');
a.href = url;
@@ -75,6 +76,7 @@ export function QuizFileImport({
const [busy, setBusy] = useState(false);
const [confirmReplace, setConfirmReplace] = useState(false);
const [chosenKind, setChosenKind] = useState<QuizKind>(fixedKind ?? 'normal');
const [blank, setBlank] = useState<BlankPositions>('auto');
const kind = fixedKind ?? chosenKind;
const pickSheet = (sheets: Sheet[], i: number) => {
@@ -104,7 +106,9 @@ 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 parsed = useMemo(() => (sheet ? parseQuizRows(sheet.rows, columns, headerAt, kind, blank) : null), [sheet, columns, headerAt, kind, blank]);
// songs whose 시작·하이라이트 cells are both empty (자동 or 처음부터 below)
const blankCount = useMemo(() => (sheet ? parseQuizRows(sheet.rows, columns, headerAt, kind).items.filter((it) => it.auto).length : 0), [sheet, columns, headerAt, kind]);
const missing = (['link', 'answer'] as const).filter((c) => !columns.includes(c));
const duel = kind === 'duel';
const bad = parsed?.rows.filter((r) => r.problem) ?? [];
@@ -232,6 +236,26 @@ export function QuizFileImport({
{bad.length > 0 && <span className="warn-text"> · 빠지는 줄 {bad.length}개</span>}
{mode === 'into' && items.length > appendable.length && <span className="muted"> · 이미 목록에 있는 영상 {items.length - appendable.length}곡</span>}
</div>
{blankCount > 0 && (
<div className="stack" style={{ gap: 4 }}>
<span className="field">시작·하이라이트가 빈 곡 {blankCount}곡</span>
<Seg
label="시작·하이라이트가 빈 곡"
value={blank}
disabled={false}
onChange={setBlank}
options={[
{ v: 'auto', label: '✨ 자동 (하이라이트 자동)' },
{ v: 'start', label: '⏮ 처음부터 재생' },
]}
/>
<span className="muted small">
{blank === 'auto'
? `방이 '하이라이트부터'면 ${mode === 'create' ? '서버 노래 DB에 같은 영상의 하이라이트가 있으면 그 위치, 없으면 ' : ''}곡 길이의 30% 지점부터 들려줘요(길이를 모르면 처음부터). 적힌 시작·하이라이트는 그대로 써요.`
: '하이라이트 없이 언제나 영상 처음부터 들려줘요. 적힌 시작·하이라이트는 그대로 써요.'}
</span>
</div>
)}
{bad.length > 0 && (
<div className="table-wrap" style={{ maxHeight: 200, overflowY: 'auto' }}>
<table className="data-table">

View File

@@ -33,6 +33,7 @@ import { YtPreview } from './SongsPage';
import { PositionEditor } from './PositionEditor';
import { useReviewCount } from './reviewCount';
import { QuizFileImport, exportQuiz } from './QuizFile';
import { PlaylistSheet } from './PlaylistSheet';
const mmss = (s: number | null | undefined) => (s == null ? '-' : `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, '0')}`);
const VIS_LABEL: Record<QuizVisibility, string> = { private: '비공개', partial: '일부공개', public: '전체공개' };
@@ -46,6 +47,7 @@ export function QuizzesPage() {
const [name, setName] = useState('');
const [adding, setAdding] = useState(false);
const [fromFile, setFromFile] = useState(false);
const [toSheet, setToSheet] = useState(false);
const nav = useNavigate();
const load = useCallback(() => {
apiCall<{ quizzes: QuizSummary[] }>('GET', `/api/admin/quizzes${all ? '?all=1' : ''}`)
@@ -91,6 +93,7 @@ export function QuizzesPage() {
}}
/>
)}
{toSheet && <PlaylistSheet onClose={() => setToSheet(false)} />}
<div className="quiz-grid">
{list?.map((q) => (
<Link key={q.id} to={`/admin/quizzes/${q.id}`} className="quiz-card">
@@ -138,6 +141,12 @@ export function QuizzesPage() {
<small className="muted">엑셀(.xlsx)·CSV · 일반 / 이지선다</small>
</button>
)}
{!toSheet && (
<button type="button" className="quiz-card add plus" onClick={() => setToSheet(true)}>
<span aria-hidden>🔗</span> 재생목록으로 엑셀 만들기
<small className="muted">유튜브·유튜브 뮤직·스포티파이 → 파일로 만들기용 엑셀</small>
</button>
)}
</div>
{list && list.length === 0 && !adding && <p className="muted">아직 만든 퀴즈가 없어요. "퀴즈 추가"를 눌러 시작해 보세요.</p>}
</>