From 3c5e26f9b76cc328f0b4339f6c4a95338987e5d8 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Fri, 23 Oct 2026 18:06:28 +0900 Subject: [PATCH] =?UTF-8?q?=ED=80=B4=EC=A6=88=20=ED=8C=8C=EC=9D=BC=20A?= =?UTF-8?q?=EB=8B=A8=EA=B3=84:=20=EA=B4=80=EB=A6=AC=EC=9E=90=20=E2=86=92?= =?UTF-8?q?=20=ED=80=B4=EC=A6=88=20'=ED=8C=8C=EC=9D=BC=EB=A1=9C=20?= =?UTF-8?q?=EB=A7=8C=EB=93=A4=EA=B8=B0'(.xlsx=C2=B7.csv=EB=A5=BC=20?= =?UTF-8?q?=EB=B8=8C=EB=9D=BC=EC=9A=B0=EC=A0=80=EA=B0=80=20=EB=9D=BC?= =?UTF-8?q?=EC=9D=B4=EB=B8=8C=EB=9F=AC=EB=A6=AC=20=EC=97=86=EC=9D=B4=20?= =?UTF-8?q?=EC=9D=BD=EC=9D=8C,=20=EC=97=B4=20=EC=9D=B4=EB=A6=84=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EB=A7=81=ED=81=AC=C2=B7=EC=A0=95=EB=8B=B5=C2=B7?= =?UTF-8?q?=EC=84=A4=EB=AA=85=C2=B7=ED=9E=8C=ED=8A=B8=C2=B7=EC=88=9C?= =?UTF-8?q?=EB=B2=88=20=EC=9D=B8=EC=8B=9D,=20=EC=8B=9C=ED=8A=B8=20?= =?UTF-8?q?=EC=84=A0=ED=83=9D,=20=EC=9E=98=EB=AA=BB=EB=90=9C=20=EB=A7=81?= =?UTF-8?q?=ED=81=AC=C2=B7=EC=A4=91=EB=B3=B5=20=EC=98=81=EC=83=81=20?= =?UTF-8?q?=ED=91=9C=EC=8B=9C),=20=ED=8E=B8=EC=A7=91=20=ED=99=94=EB=A9=B4?= =?UTF-8?q?=20'=ED=8C=8C=EC=9D=BC=EC=97=90=EC=84=9C=20=EA=B0=80=EC=A0=B8?= =?UTF-8?q?=EC=98=A4=EA=B8=B0'(=EB=92=A4=EC=97=90=20=EC=B6=94=EA=B0=80?= =?UTF-8?q?=C2=B7=EB=AA=A9=EB=A1=9D=20=EB=B0=94=EA=BE=B8=EA=B8=B0)=C2=B7'?= =?UTF-8?q?=EC=97=91=EC=85=80=EB=A1=9C=20=EB=82=B4=EB=B3=B4=EB=82=B4?= =?UTF-8?q?=EA=B8=B0'=C2=B7=EB=B9=88=20=EC=96=91=EC=8B=9D.=20=ED=8C=8C?= =?UTF-8?q?=EC=9D=BC=20=EA=B3=A1=EC=9D=80=20=EC=A0=81=ED=9E=8C=20=EA=B0=92?= =?UTF-8?q?=20=EA=B7=B8=EB=8C=80=EB=A1=9C(DB=20=EC=97=B0=EA=B2=B0=C2=B7?= =?UTF-8?q?=EA=B2=80=ED=86=A0=20=EB=8C=80=EA=B8=B0=20=EC=97=86=EC=9D=8C).?= =?UTF-8?q?=20=EA=B3=A1=EB=B3=84=20=ED=9E=8C=ED=8A=B8=EB=A5=BC=20=ED=95=98?= =?UTF-8?q?=EB=82=98=EC=94=A9=20=EB=B3=B4=EC=97=AC=20=EC=A4=80=20=EB=92=A4?= =?UTF-8?q?=20=EC=B4=88=EC=84=B1=20=ED=9E=8C=ED=8A=B8(=EC=9E=90=EB=8F=99?= =?UTF-8?q?=EC=9D=80=20N=EC=B4=88=EB=A7=88=EB=8B=A4,=20=ED=88=AC=ED=91=9C?= =?UTF-8?q?=EB=8A=94=20=ED=95=9C=20=EB=B2=88=EC=97=90=20=ED=95=98=EB=82=98?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/server/src/custom-quiz.test.ts | 70 ++++ .../src/db/migrations/012_quiz_file.sql | 4 + apps/server/src/game/engine.ts | 36 +- apps/server/src/http/admin-quizzes.ts | 20 +- apps/server/src/http/admin.ts | 18 +- apps/server/src/quizzes/review.ts | 3 +- apps/server/src/quizzes/store.ts | 16 +- apps/server/src/songs/quiz.ts | 7 +- apps/web/src/pages/GameScreen.tsx | 13 +- apps/web/src/pages/admin/QuizFile.tsx | 299 ++++++++++++++++ apps/web/src/pages/admin/QuizzesPage.tsx | 103 +++++- apps/web/src/styles/global.css | 3 + docs/10-roadmap.md | 1 + e2e/quiz.e2e.ts | 67 ++++ packages/shared/src/custom-quiz-schema.ts | 7 +- packages/shared/src/custom-quiz.ts | 4 + packages/shared/src/index.ts | 2 + packages/shared/src/lite.ts | 2 + packages/shared/src/protocol.ts | 7 +- packages/shared/src/quiz-file.test.ts | 98 ++++++ packages/shared/src/quiz-file.ts | 210 +++++++++++ packages/shared/src/sheet.ts | 329 ++++++++++++++++++ packages/shared/src/zip-fixture.ts | 21 ++ 23 files changed, 1285 insertions(+), 55 deletions(-) create mode 100644 apps/server/src/db/migrations/012_quiz_file.sql create mode 100644 apps/web/src/pages/admin/QuizFile.tsx create mode 100644 packages/shared/src/quiz-file.test.ts create mode 100644 packages/shared/src/quiz-file.ts create mode 100644 packages/shared/src/sheet.ts create mode 100644 packages/shared/src/zip-fixture.ts diff --git a/apps/server/src/custom-quiz.test.ts b/apps/server/src/custom-quiz.test.ts index 47bc26a..932851d 100644 --- a/apps/server/src/custom-quiz.test.ts +++ b/apps/server/src/custom-quiz.test.ts @@ -246,3 +246,73 @@ test('검토 대기: a 전체공개 quiz sends new songs and differences to admi const again = await save({ items: (await api(s.base, `/api/admin/quizzes/${q.id}`, { cookie: sa })).body.quiz.items }); expect(again.body.reviews.pending).toBe(0); }); + +test('파일로 만들기: values as written, hints by vote, never sent to 검토 대기; a game shows the own hint, then the 초성', async () => { + start(); + const sa = await adminCookie(TEST_SUPERADMINS[0]); + const fileItem = (p: Record) => item({ fromFile: true, hints: [], ...p }); + const bad = await api(s.base, '/api/admin/quizzes/file', { method: 'POST', cookie: sa, body: JSON.stringify({ name: '빈 파일', items: [] }) }); + expect(bad.res.status).toBe(400); + const r = await api(s.base, '/api/admin/quizzes/file', { + method: 'POST', + cookie: sa, + body: JSON.stringify({ + name: '게임 BGM', + items: [ + // the video is the DB song's, but a file song is not linked to it (no DB comparison) + fileItem({ videoId: 'goodday0001', title: '리그 오브 레전드', artist: 'Still Here', hints: ['AOS(MOBA)'], songId: 5 }), + fileItem({ videoId: 'nodesc00001', title: '원신', artist: '', hints: ['확인필요'] }), + ], + }), + }); + expect(r.res.status).toBe(200); + 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 }, + ]); + // 전체공개 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}`, { + method: 'PUT', + cookie: sa, + body: JSON.stringify({ ...q, visibility: 'public', items: [...q.items, item({ videoId: 'editor00001', title: '직접 넣은 곡', artist: '가수' })] }), + }); + expect(saved.res.status).toBe(200); + expect(saved.body.reviews.pending).toBe(1); + // an editor song still needs a singer + const noArtist = await api(s.base, `/api/admin/quizzes/${q.id}`, { method: 'PUT', cookie: sa, body: JSON.stringify({ ...q, items: [item({ videoId: 'editor00002', title: '곡', artist: '' })] }) }); + expect(noArtist.res.status).toBe(400); + + const code: string = (await api(s.base, '/api/rooms', { method: 'POST', cookie: sa, body: '{}' })).body.code; + const cl = await new Client(s.base, sa).connect(); + cl.send({ t: 'join', code }); + await cl.waitFor((m) => m.t === 'room'); + cl.send({ t: 'config', patch: { quizId: q.id, hint: 'manual', hintVotes: '1' } }); + await cl.waitFor((m) => m.t === 'room' && m.room.config.quizId === q.id && m.room.config.hint === 'manual'); + let seen = 0; + const iv = setInterval(() => { + for (const m of cl.messages.slice(seen)) if (m.t === 'prepare') cl.send({ t: 'audio', n: m.n, ev: 'ready' }); + seen = cl.messages.length; + }, 5); + try { + cl.send({ t: 'start' }); + const play = (await cl.waitFor((m) => m.t === 'play' && m.n === 1)) as Msg<'play'>; + await sleep(Math.max(0, play.startAt - Date.now()) + 15); + cl.send({ t: 'vote', kind: 'hint' }); + const g1 = (await cl.waitFor((m) => m.t === 'game' && !!m.game?.hints.length)) as Msg<'game'>; + expect(g1.game!.hints).toEqual([{ text: 'AOS(MOBA)', chosung: false }]); + expect(g1.game!.hintMore).toBe(true); + cl.send({ t: 'vote', kind: 'hint' }); + const g2 = (await cl.waitFor((m) => m.t === 'game' && m.game?.hints.length === 2)) as Msg<'game'>; + expect(g2.game!.hints[1]).toEqual({ text: 'ㄹㄱ ㅇㅂ ㄹㅈㄷ', chosung: true }); + expect(g2.game!.hint).toBe('AOS(MOBA) · ㄹㄱ ㅇㅂ ㄹㅈㄷ'); + expect(g2.game!.hintMore).toBe(false); + cl.send({ t: 'chat', text: '리그 오브 레전드' }); + const ans = (await cl.waitFor((m) => m.t === 'answer')) as Msg<'answer'>; + expect(ans.line.answer?.text).toBe('리그 오브 레전드 - Still Here'); + } finally { + clearInterval(iv); + cl.close(); + } +}); diff --git a/apps/server/src/db/migrations/012_quiz_file.sql b/apps/server/src/db/migrations/012_quiz_file.sql new file mode 100644 index 0000000..6cb32ed --- /dev/null +++ b/apps/server/src/db/migrations/012_quiz_file.sql @@ -0,0 +1,4 @@ +-- 퀴즈 파일로 만들기: hints per song (shown one by one before the 초성 hint) and songs that came from a file +-- (used as written, never sent to 검토 대기). +ALTER TABLE custom_quiz_items ADD COLUMN hints TEXT NOT NULL DEFAULT '[]'; +ALTER TABLE custom_quiz_items ADD COLUMN from_file INTEGER NOT NULL DEFAULT 0; diff --git a/apps/server/src/game/engine.ts b/apps/server/src/game/engine.ts index a2a554a..ddd392b 100644 --- a/apps/server/src/game/engine.ts +++ b/apps/server/src/game/engine.ts @@ -90,6 +90,8 @@ export class Game { private runningSince: number | null = null; private limitMs: number | null = null; hint: string | null = null; + /** Hints shown in this question: the song's own (제작된 퀴즈) one by one, then the 초성 hint. */ + private shownHints: { text: string; chosung: boolean }[] = []; /** 통계: how the hint came (null = none), chat lines that were not the answer and who sent them, replays. */ private stat = { hint: null as 'auto' | 'vote' | null, wrong: 0, wrongBy: new Set(), replays: 0 }; private lyrics: string[] | null = null; @@ -196,6 +198,7 @@ export class Game { this.elapsedMs = 0; this.runningSince = null; this.hint = null; + this.shownHints = []; this.stat = { hint: null, wrong: 0, wrongBy: new Set(), replays: 0 }; this.revealUntil = null; for (const v of Object.values(this.votes)) v.clear(); @@ -288,13 +291,26 @@ export class Game { this.broadcast(); } + /** Hints this song has: its own ones, then the 초성 hint. */ + private hintCount(): number { + return (this.song?.hints?.length ?? 0) + 1; + } + private hintMore(): boolean { + return !!this.song && this.shownHints.length < this.hintCount(); + } + + /** The next hint: the song's own hints one by one, the 초성 hint last. */ private showHint(how: 'auto' | 'vote' = 'auto'): void { - if (this.hint || !this.song) return; - this.stat.hint = how; - this.hint = hintText(this.song, this.room.config.answer); - if (this.lyrics && this.song.lyrics) this.lyrics = lyricsCard(this.song.lyrics, this.song.title, 1); + if (!this.song || !this.hintMore()) return; + this.stat.hint ??= how; + const own = this.song.hints ?? []; + const i = this.shownHints.length; + const next = i < own.length ? { text: own[i]!, chosung: false } : { text: hintText(this.song, this.room.config.answer), chosung: true }; + this.shownHints.push(next); + this.hint = this.shownHints.map((h) => h.text).join(' · '); + if (next.chosung && this.lyrics && this.song.lyrics) this.lyrics = lyricsCard(this.song.lyrics, this.song.title, 1); this.votes.hint.clear(); - this.room.say(null, `힌트가 공개됐어요: ${this.hint}`); + this.room.say(null, `${this.hintCount() > 1 ? `힌트 ${i + 1}` : '힌트'}가 공개됐어요: ${next.text}`); this.broadcast(); } @@ -417,7 +433,7 @@ export class Game { if (this.phase !== 'play') return; const el = this.elapsed(now); const c = this.room.config; - if (typeof c.hint === 'number' && !this.hint && this.runningSince !== null && el >= c.hint * 1000) this.showHint(); + if (typeof c.hint === 'number' && this.hintMore() && this.runningSince !== null && el >= c.hint * 1000 * (this.shownHints.length + 1)) this.showHint(); if (this.limitMs !== null && el >= this.limitMs) return this.endQuestion(null, 'timeout'); if (this.playing && !this.clipOver && this.clip.endSec !== null) { const expectedEnd = this.audioStartAt + (this.clip.endSec - this.audioAtSec) * 1000; @@ -503,9 +519,9 @@ export class Game { const c = this.room.config; if (kind === 'hint') { if (c.hint === 'none') return '이 방은 힌트가 꺼져 있어요.'; - if (this.hint) return '이미 공개된 힌트예요.'; + if (!this.hintMore()) return this.hintCount() > 1 ? '힌트를 모두 공개했어요.' : '이미 공개된 힌트예요.'; if (c.hint !== 'manual') { - const left = Math.max(1, Math.ceil(c.hint - (this.elapsed() / 1000))); + const left = Math.max(1, Math.ceil(c.hint * (this.shownHints.length + 1) - this.elapsed() / 1000)); return `힌트는 ${left}초 뒤에 공개돼요.`; } } @@ -636,7 +652,9 @@ export class Game { clipSec: this.clip.endSec !== null ? this.clip.endSec - this.clip.startSec : null, clipOver: this.clipOver, hint: this.hint, - hintAtSec: typeof c.hint === 'number' ? c.hint : null, + hints: this.shownHints, + hintMore: this.hintMore(), + hintAtSec: typeof c.hint === 'number' && this.hintMore() ? c.hint * (this.shownHints.length + 1) : null, lyrics: this.lyrics, votes: { skip: [...this.votes.skip], hint: [...this.votes.hint], replay: [...this.votes.replay], next: [...this.votes.next] }, need: { skip: this.need('skip'), hint: this.need('hint'), replay: this.need('replay'), next: this.need('next') }, diff --git a/apps/server/src/http/admin-quizzes.ts b/apps/server/src/http/admin-quizzes.ts index 9186301..aeb740e 100644 --- a/apps/server/src/http/admin-quizzes.ts +++ b/apps/server/src/http/admin-quizzes.ts @@ -4,7 +4,7 @@ */ import type { Context, Hono } from 'hono'; import { z } from 'zod'; -import { QuizSaveSchema, songMatchKey, type Role } from '@mq/shared'; +import { DEFAULT_QUIZ_SETTINGS, QuizSaveSchema, songMatchKey, type Role } from '@mq/shared'; import type { Database } from 'bun:sqlite'; import { CustomQuizzes, type QuizLimits } from '../quizzes/store'; import type { YtmSong } from '../collector/ytmusic'; @@ -63,6 +63,24 @@ export function mountQuizAdmin(app: Hono, d: QuizAdminDeps, h: { actor: (c: return c.json({ id }); }); + /** 파일로 만들기: a new quiz with the songs read from a file (the browser reads the file; values used as written). */ + app.post('/quizzes/file', async (c) => { + const p = z.object({ name: z.string().trim().min(1).max(60), items: QuizSaveSchema.shape.items.min(1) }).safeParse(await h.body(c)); + if (!p.success) return c.json({ error: `만들 내용이 올바르지 않아요: ${p.error.issues.slice(0, 3).map((i) => i.path.join('.') || i.message).join(', ')}` }, 400); + const limits = d.limits(); + 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); + if (typeof id === 'string') return c.json({ error: id }, 400); + const items = p.data.items.map((it) => ({ ...it, id: undefined, songId: null, fromFile: true })); + // 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); + if (typeof saved === 'string') return c.json({ error: saved }, 400); + d.audit.log(h.actor(c), 'quiz.create', String(id), null, { name: p.data.name, songs: items.length, from: 'file' }); + d.onChange?.(); + return c.json({ id }); + }); + // ---------------------------------------------------------------- 검토 대기 (전체공개 퀴즈 → 서버 노래 DB) app.get('/reviews/count', (c) => { const levels = playStats(d.db, { sort: 'suggest', size: 1 }).suggestions; diff --git a/apps/server/src/http/admin.ts b/apps/server/src/http/admin.ts index d3e14f5..d39deb8 100644 --- a/apps/server/src/http/admin.ts +++ b/apps/server/src/http/admin.ts @@ -1,7 +1,7 @@ /** Admin API (docs/02 관리자 페이지). Mounted under /api/admin. Ported from joke-app (rooms/games parts come later). */ import { Hono, type Context } from 'hono'; import { z } from 'zod'; -import { nicknameError, normalizeNickname, type Role } from '@mq/shared'; +import { nicknameError, normalizeNickname, parseVideoId, type Role } from '@mq/shared'; import type { Audit, Roles } from '../admin/roles'; import { SiteSettingsSchema, type SettingsStore } from '../admin/settings'; import type { Sessions } from '../auth/sessions'; @@ -48,20 +48,8 @@ export interface AdminDeps { type Env = { Variables: { userId: string | null; role: Role } }; const DISCORD_ID = /^\d{17,20}$/; -const VIDEO_ID = /^[\w-]{11}$/; - -/** Accepts https://youtu.be/ID, youtube.com/watch?v=ID, music.youtube.com/watch?v=ID or the bare ID. */ -export function parseVideoId(s: string): string | null { - const t = s.trim(); - if (VIDEO_ID.test(t)) return t; - try { - const u = new URL(t); - const id = u.hostname === 'youtu.be' ? u.pathname.slice(1) : u.searchParams.get('v'); - return id && VIDEO_ID.test(id) ? id : null; - } catch { - return null; - } -} +/** Accepts the usual YouTube URL shapes or the bare ID (shared with the quiz file reader). */ +export { parseVideoId }; const SongPatchSchema = z.object({ title: z.string().trim().min(1).max(200).optional(), diff --git a/apps/server/src/quizzes/review.ts b/apps/server/src/quizzes/review.ts index 390f284..6933aba 100644 --- a/apps/server/src/quizzes/review.ts +++ b/apps/server/src/quizzes/review.ts @@ -2,6 +2,7 @@ * 검토 대기 (전체공개 퀴즈 → 서버 노래 DB): after a 전체공개 quiz is saved, every song that is not in the DB, or whose * video / title / artist / 직접 정한 하이라이트 differs from its DB song, waits here. An admin picks, field by field, the DB * value or the quiz's; new songs get year/genres/level filled in and are added. Decided proposals are not asked again. + * Songs that came from a quiz file (파일로 만들기) are used as written and never wait here. */ import type { Database } from 'bun:sqlite'; import { createSong } from '../songs/admin-ops'; @@ -42,7 +43,7 @@ export function syncReviews(db: Database, quizId: number, now = Date.now()): { p return { pending: 0 }; } const items = db - .query('SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, duration_sec, auto, highlight_sec FROM custom_quiz_items WHERE quiz_id = ?') + .query('SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, duration_sec, auto, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? AND from_file = 0') .all(quizId); const song = db.query<{ title: string; artist: string; youtube_id: string | null; youtube_status: string; highlight_sec: number | null }, [number]>( 'SELECT title, artist, youtube_id, youtube_status, highlight_sec FROM songs WHERE id = ? AND deleted_at IS NULL', diff --git a/apps/server/src/quizzes/store.ts b/apps/server/src/quizzes/store.ts index e236502..97ffcc9 100644 --- a/apps/server/src/quizzes/store.ts +++ b/apps/server/src/quizzes/store.ts @@ -26,6 +26,8 @@ interface ItemRow { artist: string; title_answers: string; artist_answers: string; + hints: string; + from_file: number; duration_sec: number | null; auto: number; start_sec: number | null; @@ -62,6 +64,8 @@ const item = (r: ItemRow): QuizItem => ({ artist: r.artist, titleAnswers: JSON.parse(r.title_answers) as string[], artistAnswers: JSON.parse(r.artist_answers) as string[], + hints: JSON.parse(r.hints) as string[], + fromFile: !!r.from_file, durationSec: r.duration_sec, auto: !!r.auto, startSec: r.start_sec, @@ -112,7 +116,7 @@ export class CustomQuizzes { items(id: number): QuizItem[] { return this.db .query( - 'SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? ORDER BY pos, id', + 'SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? ORDER BY pos, id', ) .all(id) .map(item); @@ -121,7 +125,7 @@ export class CustomQuizzes { item(quizId: number, itemId: number): QuizItem | null { const r = this.db .query( - 'SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? AND id = ?', + 'SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? AND id = ?', ) .get(quizId, itemId); return r ? item(r) : null; @@ -142,11 +146,11 @@ export class CustomQuizzes { .run(data.name, data.description, data.visibility, JSON.stringify(data.settings), now, id); const keep = new Set(); const ins = this.db.query( - `INSERT INTO custom_quiz_items (quiz_id, pos, song_id, video_id, title, artist, title_answers, artist_answers, duration_sec, auto, start_sec, highlight_sec) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + `INSERT INTO custom_quiz_items (quiz_id, pos, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, duration_sec, auto, start_sec, highlight_sec) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ); const upd = this.db.query( - `UPDATE custom_quiz_items SET pos = ?, song_id = ?, video_id = ?, title = ?, artist = ?, title_answers = ?, artist_answers = ?, duration_sec = ?, auto = ?, + `UPDATE custom_quiz_items SET pos = ?, song_id = ?, video_id = ?, title = ?, artist = ?, title_answers = ?, artist_answers = ?, hints = ?, from_file = ?, duration_sec = ?, auto = ?, start_sec = ?, highlight_sec = ? WHERE id = ? AND quiz_id = ?`, ); const alias = this.db.query("INSERT OR IGNORE INTO song_aliases (song_id, part, alias, source) VALUES (?, ?, ?, 'quiz')"); @@ -161,6 +165,8 @@ export class CustomQuizzes { it.artist, JSON.stringify(titleAnswers), JSON.stringify(artistAnswers), + JSON.stringify(it.hints ?? []), + it.fromFile ? 1 : 0, it.durationSec, it.auto ? 1 : 0, it.auto ? null : it.startSec, diff --git a/apps/server/src/songs/quiz.ts b/apps/server/src/songs/quiz.ts index 249b4b7..3cff937 100644 --- a/apps/server/src/songs/quiz.ts +++ b/apps/server/src/songs/quiz.ts @@ -30,6 +30,8 @@ export interface QuizSong { /** Main artist ids (same singer not twice in a row, docs/05 출제 목록). */ artistIds: number[]; lyrics: string | null; + /** 제작된 퀴즈: the song's own hints, shown one by one before the 초성 hint. */ + hints?: string[]; } export function quizSong(db: Database, id: number): QuizSong | null { @@ -73,9 +75,9 @@ export function quizSong(db: Database, id: number): QuizSong | null { export function quizItemSong(db: Database, quizId: number, itemId: number): QuizSong | null { const it = db .query< - { id: number; song_id: number | null; video_id: string; title: string; artist: string; title_answers: string; artist_answers: string; duration_sec: number | null; auto: number; start_sec: number | null; highlight_sec: number | null }, + { id: number; song_id: number | null; video_id: string; title: string; artist: string; title_answers: string; artist_answers: string; hints: string; duration_sec: number | null; auto: number; start_sec: number | null; highlight_sec: number | null }, [number, number] - >('SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? AND id = ?') + >('SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, hints, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? AND id = ?') .get(quizId, itemId); if (!it) return null; const base = it.song_id ? quizSong(db, it.song_id) : null; @@ -103,6 +105,7 @@ export function quizItemSong(db: Database, quizId: number, itemId: number): Quiz artistAliases: uniq([...(JSON.parse(it.artist_answers) as string[]), ...(base ? [base.artist, ...base.artistAliases] : [])]), artistIds: base?.artistIds ?? [], lyrics: base?.lyrics ?? null, + hints: JSON.parse(it.hints) as string[], }; } diff --git a/apps/web/src/pages/GameScreen.tsx b/apps/web/src/pages/GameScreen.tsx index 3b02c76..1ba4166 100644 --- a/apps/web/src/pages/GameScreen.tsx +++ b/apps/web/src/pages/GameScreen.tsx @@ -217,12 +217,15 @@ export function GameScreen({ room, game }: { room: RoomView; game: GameView }) { )}
- {game.hint ? ( - - {game.hint} 초성 힌트 + {(game.hints ?? []).map((h, i) => ( + + {h.text} {h.chosung ? '초성 힌트' : `힌트 ${i + 1}`} + + ))} + {game.hintAtSec !== null && game.phase === 'play' ? ( + + {game.hints?.length ? '다음 힌트' : '힌트'}는 {Math.max(0, Math.ceil(game.hintAtSec - elapsed / 1000))}초 뒤에 공개돼요 - ) : game.hintAtSec !== null && game.phase === 'play' ? ( - 힌트는 {Math.max(0, Math.ceil(game.hintAtSec - elapsed / 1000))}초 뒤에 공개돼요 ) : null}
diff --git a/apps/web/src/pages/admin/QuizFile.tsx b/apps/web/src/pages/admin/QuizFile.tsx new file mode 100644 index 0000000..8c850f1 --- /dev/null +++ b/apps/web/src/pages/admin/QuizFile.tsx @@ -0,0 +1,299 @@ +/** + * 퀴즈 파일 (관리자 → 퀴즈): 파일로 만들기 (a new quiz from .xlsx / .csv), 파일에서 가져오기 (into the open quiz), + * 엑셀로 내보내기 and 빈 양식. The browser reads the file; columns are recognised by their headers and can be changed. + * Values are used as written — bad links and repeated videos are listed and left out. + */ +import { useMemo, useState } from 'react'; +import { + QUIZ_COLUMN_LABEL, + guessColumns, + headerRow, + parseQuizRows, + quizTemplateRows, + quizToRows, + readSheetFile, + writeXlsx, + type QuizColumn, + type QuizItem, + type Sheet, +} from '@mq/shared/lite'; +import { toast } from '../../store/toast'; +import { ConfirmSheet } from '../../components/ui'; + +const MAX_BYTES = 20 * 1024 * 1024; +const COLUMN_ORDER: QuizColumn[] = ['link', 'answer', 'desc', 'hint', 'answers', 'descAnswers', 'order', 'start', 'highlight']; + +function download(name: string, bytes: Uint8Array) { + const url = URL.createObjectURL(new Blob([bytes as Uint8Array], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })); + const a = document.createElement('a'); + a.href = url; + a.download = `${name.replace(/[\\/:*?"<>|]/g, ' ').trim() || '퀴즈'}.xlsx`; + document.body.append(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 1000); +} + +/** 엑셀로 내보내기: the songs as a file this screen reads back. */ +export function exportQuiz(name: string, items: QuizItem[]) { + const { rows, widths } = quizToRows(items); + download(name, writeXlsx(name, rows, widths)); +} + +export function downloadTemplate() { + const { rows, widths } = quizTemplateRows(); + download('퀴즈 양식', writeXlsx('퀴즈', rows, widths)); +} + +export function QuizFileImport({ + mode, + existing = [], + onCreate, + onApply, + onClose, +}: { + /** create: 파일로 만들기 (new quiz) · into: 파일에서 가져오기 (the open quiz). */ + mode: 'create' | 'into'; + existing?: QuizItem[]; + onCreate?: (name: string, items: QuizItem[]) => Promise; + onApply?: (items: QuizItem[], replace: boolean) => void; + onClose: () => void; +}) { + const [file, setFile] = useState<{ name: string; sheets: Sheet[] } | null>(null); + const [sheetIdx, setSheetIdx] = useState(0); + const [columns, setColumns] = useState<(QuizColumn | null)[]>([]); + const [headerAt, setHeaderAt] = useState(0); + const [name, setName] = useState(''); + const [busy, setBusy] = useState(false); + const [confirmReplace, setConfirmReplace] = useState(false); + + const pickSheet = (sheets: Sheet[], i: number) => { + const rows = sheets[i]?.rows ?? []; + const h = headerRow(rows); + setSheetIdx(i); + setHeaderAt(h); + setColumns(guessColumns(rows[h] ?? [])); + }; + const open = async (f: File) => { + if (f.size > MAX_BYTES) return toast('파일이 너무 커요(20MB까지).', 'error'); + try { + const sheets = (await readSheetFile(f.name, new Uint8Array(await f.arrayBuffer()))).filter((s) => s.rows.length > 0); + if (!sheets.length) return toast('파일에 내용이 없어요.', 'error'); + setFile({ name: f.name, sheets }); + setName(f.name.replace(/\.[^.]+$/, '').slice(0, 60)); + // the sheet that has the most usable rows + const best = sheets.map((s, i) => [i, parseQuizRows(s.rows, guessColumns(s.rows[headerRow(s.rows)] ?? []), headerRow(s.rows)).items.length] as const).sort((a, b) => b[1] - a[1])[0]![0]; + pickSheet(sheets, best); + } catch (e) { + toast((e as Error).message || '파일을 읽지 못했어요.', 'error'); + } + }; + + const sheet = file?.sheets[sheetIdx]; + const header = sheet?.rows[headerAt] ?? []; + const parsed = useMemo(() => (sheet ? parseQuizRows(sheet.rows, columns, headerAt) : null), [sheet, columns, headerAt]); + const missing = (['link', 'answer'] as const).filter((c) => !columns.includes(c)); + const bad = parsed?.rows.filter((r) => r.problem) ?? []; + const items = parsed?.items ?? []; + const inList = new Set(existing.map((x) => x.videoId)); + const appendable = items.filter((x) => !inList.has(x.videoId)); + const width = Math.max(header.length, ...(sheet?.rows.slice(headerAt, headerAt + 20).map((r) => r.length) ?? [0])); + + const setColumn = (i: number, v: QuizColumn | null) => + setColumns((cur) => { + const next = [...cur]; + while (next.length < width) next.push(null); + // one column per use (힌트 may be several) + if (v && v !== 'hint') for (let k = 0; k < next.length; k++) if (next[k] === v) next[k] = null; + next[i] = v; + return next; + }); + + const create = async () => { + if (!onCreate || !name.trim() || !items.length) return; + setBusy(true); + try { + await onCreate(name.trim(), items); + } finally { + setBusy(false); + } + }; + + return ( +
+
+ 📄 {mode === 'create' ? '파일로 만들기' : '파일에서 가져오기'} + +
+
+ + + {file && {file.name}} +
+ {!file && ( +

+ 한 줄에 한 곡씩, 첫 줄은 열 이름이에요. 유튜브 영상 링크와 정답(예: 게임 제목)은 꼭 있어야 하고, 설명(예: 노래 제목)은 정답을 공개할 때 같이 + 보여요. 힌트 열은 문제마다 먼저 나오고, 그다음 힌트로 초성이 나와요. 순번 열이 있으면 그 순서대로 넣어요. 적힌 값은 고치지 않고 그대로 써요. +

+ )} + {file && sheet && ( + <> + {file.sheets.length > 1 && ( + + )} +
+ 열 {missing.length ? '— 아래에서 골라 주세요' : '(열 이름으로 찾았어요. 다르면 바꿔 주세요)'} +
+ {Array.from({ length: width }, (_, i) => ( + + ))} +
+ {missing.length > 0 && {missing.map((c) => QUIZ_COLUMN_LABEL[c]).join(', ')} 열을 골라 주세요.} +
+ {!missing.length && parsed && ( + <> +
+ {items.length}곡 + {bad.length > 0 && · 빠지는 줄 {bad.length}개} + {mode === 'into' && items.length > appendable.length && · 이미 목록에 있는 영상 {items.length - appendable.length}곡} +
+ {bad.length > 0 && ( +
+ + + + + + + + + + {bad.map((r) => ( + + + + + + ))} + +
줄빠지는 이유링크
{r.line}{r.problem} + + {r.link || '-'} + +
+
+ )} + {items.length > 0 && ( +
+ + + + + + + + + + + + {items.map((it, i) => ( + + + + + + + + ))} + +
#정답설명힌트영상
{i + 1} + {it.title} + {it.titleAnswers.length > 0 &&
또는 {it.titleAnswers.join(', ')}
} +
{it.artist || -}{[...it.hints, '초성'].join(' → ')} + + {it.videoId} ↗ + +
+
+ )} + {mode === 'create' ? ( +
{ + e.preventDefault(); + void create(); + }} + > + + +
+ ) : ( +
+ + +
+ )} + + )} + + )} + {confirmReplace && ( + setConfirmReplace(false)} + onConfirm={() => onApply?.(items, true)} + /> + )} +
+ ); +} diff --git a/apps/web/src/pages/admin/QuizzesPage.tsx b/apps/web/src/pages/admin/QuizzesPage.tsx index dd99f14..dad173c 100644 --- a/apps/web/src/pages/admin/QuizzesPage.tsx +++ b/apps/web/src/pages/admin/QuizzesPage.tsx @@ -24,6 +24,7 @@ import { PlayRules, Section, Seg } from '../../components/RoomSettings'; import { YtPreview } from './SongsPage'; import { PositionEditor } from './PositionEditor'; import { useReviewCount } from './reviewCount'; +import { QuizFileImport, exportQuiz } from './QuizFile'; const mmss = (s: number | null | undefined) => (s == null ? '-' : `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, '0')}`); const VIS_LABEL: Record = { private: '비공개', partial: '일부공개', public: '전체공개' }; @@ -36,6 +37,7 @@ export function QuizzesPage() { const [list, setList] = useState(null); const [name, setName] = useState(''); const [adding, setAdding] = useState(false); + const [fromFile, setFromFile] = useState(false); const nav = useNavigate(); const load = useCallback(() => { apiCall<{ quizzes: QuizSummary[] }>('GET', `/api/admin/quizzes${all ? '?all=1' : ''}`) @@ -63,6 +65,21 @@ export function QuizzesPage() { )}

직접 만든 퀴즈예요. 방 설정에서 "제작된 퀴즈"를 고르면 이 퀴즈의 곡이 순서대로(또는 섞어서) 전부 나와요. 듣고맞추기에서만 쓸 수 있어요.

+ {fromFile && ( + setFromFile(false)} + onCreate={async (quizName, items) => { + try { + const r = await apiCall<{ id: number }>('POST', '/api/admin/quizzes/file', { name: quizName, items }); + toast(`"${quizName}" 퀴즈를 ${items.length}곡으로 만들었어요.`); + nav(`/admin/quizzes/${r.id}`); + } catch (e) { + toast((e as Error).message, 'error'); + } + }} + /> + )}
{list?.map((q) => ( @@ -103,6 +120,12 @@ export function QuizzesPage() { + 퀴즈 추가 )} + {!fromFile && ( + + )}
{list && list.length === 0 && !adding &&

아직 만든 퀴즈가 없어요. "퀴즈 추가"를 눌러 시작해 보세요.

} @@ -126,6 +149,10 @@ export interface DbInfo { videoId: string | null; } +/** A song picked in the editor (search, address, playlist): answers, hints and positions start empty. */ +type NewSong = Omit; +const fresh = (it: NewSong): QuizItem => ({ ...it, titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, auto: true, startSec: null, highlightSec: null }); + let keySeq = 0; const newKey = () => `k${++keySeq}`; const toDraft = (q: QuizDetail): Draft => ({ @@ -151,6 +178,7 @@ export function QuizEditor() { const [confirmDelete, setConfirmDelete] = useState(false); const [owner, setOwner] = useState<{ ownerName: string; plays: number } | null>(null); const [importOpen, setImportOpen] = useState(false); + const [fileOpen, setFileOpen] = useState(false); const load = useCallback(() => { apiCall<{ quiz: QuizDetail; db: Record }>('GET', `/api/admin/quizzes/${id}`) @@ -274,6 +302,9 @@ export function QuizEditor() {

{draft.name || '이름 없는 퀴즈'}

{dirty ? ● 저장하지 않은 변경이 있어요 : 저장됨} + @@ -298,6 +329,9 @@ export function QuizEditor() { + @@ -305,7 +339,17 @@ export function QuizEditor() { )} {tab === 'songs' ? ( - set({ items })} importOpen={importOpen} setImportOpen={setImportOpen} /> + set({ items })} + importOpen={importOpen} + setImportOpen={setImportOpen} + fileOpen={fileOpen} + setFileOpen={setFileOpen} + onHints={() => draft.settings.hint === 'none' && set({ settings: { ...draft.settings, hint: 'manual' } })} + /> ) : ( setConfirmDelete(true)} /> )} @@ -406,6 +450,9 @@ function SongsTab({ onItems, importOpen, setImportOpen, + fileOpen, + setFileOpen, + onHints, }: { items: DraftItem[]; db: Record; @@ -413,17 +460,21 @@ function SongsTab({ onItems: (items: DraftItem[]) => void; importOpen: boolean; setImportOpen: (on: boolean) => void; + fileOpen: boolean; + setFileOpen: (on: boolean) => void; + /** Songs with their own hints came in: hints should not stay off. */ + onHints: () => void; }) { const [sel, setSel] = useState(null); const [dragKey, setDragKey] = useState(null); const [overKey, setOverKey] = useState(null); const selected = items.find((i) => i.key === sel) ?? null; - const add = (it: Omit) => { + const add = (it: NewSong) => { if (items.some((x) => x.videoId === it.videoId || (it.songId && x.songId === it.songId))) { toast('이미 목록에 있는 곡이에요.', 'error'); return false; } - const n: DraftItem = { ...it, titleAnswers: [], artistAnswers: [], auto: true, startSec: null, highlightSec: null, key: newKey() }; + const n: DraftItem = { ...fresh(it), key: newKey() }; onItems([...items, n]); toast(`${items.length + 1}번에 추가했어요: ${it.title}`); return true; @@ -443,28 +494,42 @@ function SongsTab({ return (
- {importOpen ? ( + {fileOpen ? ( + setFileOpen(false)} + onApply={(rows, replace) => { + const added = rows.map((r) => ({ ...r, key: newKey() })); + onItems(replace ? added : [...items, ...added]); + setSel(null); + setFileOpen(false); + if (rows.some((r) => r.hints.length)) onHints(); + toast(`${added.length}곡을 ${replace ? '새 목록으로 넣었어요' : '목록 뒤에 추가했어요'}. 저장해야 반영돼요.`); + }} + /> + ) : importOpen ? ( setImportOpen(false)} onApply={(rows, replace) => { const base = replace ? [] : items; const seen = new Set(base.flatMap((x) => [x.videoId, x.songId ? `s${x.songId}` : ''])); - const fresh: DraftItem[] = []; + const added: DraftItem[] = []; for (const r of rows) { if (seen.has(r.videoId!) || (r.songId && seen.has(`s${r.songId}`))) continue; seen.add(r.videoId!); if (r.songId) seen.add(`s${r.songId}`); - fresh.push({ songId: r.songId, videoId: r.videoId!, title: r.title, artist: r.artist, durationSec: r.durationSec, titleAnswers: [], artistAnswers: [], auto: true, startSec: null, highlightSec: null, key: newKey() }); + added.push({ ...fresh({ songId: r.songId, videoId: r.videoId!, title: r.title, artist: r.artist, durationSec: r.durationSec }), key: newKey() }); } - onItems([...base, ...fresh]); + onItems([...base, ...added]); setSel(null); setImportOpen(false); - toast(`${fresh.length}곡을 ${replace ? '새 목록으로 넣었어요' : '목록 뒤에 추가했어요'}${rows.length > fresh.length ? ` (이미 있는 ${rows.length - fresh.length}곡 제외)` : ''}. 저장해야 반영돼요.`); + toast(`${added.length}곡을 ${replace ? '새 목록으로 넣었어요' : '목록 뒤에 추가했어요'}${rows.length > added.length ? ` (이미 있는 ${rows.length - added.length}곡 제외)` : ''}. 저장해야 반영돼요.`); }} /> ) : ( - setImportOpen(true)} /> + setImportOpen(true)} onFile={() => setFileOpen(true)} /> )} {items.length === 0 ? (

아직 곡이 없어요. 위에서 제목·가수로 찾거나 유튜브 주소를 붙여 넣어 추가해 주세요.

@@ -516,8 +581,9 @@ function SongsTab({ {it.title}
{it.artist} - {!it.songId && DB에 없음} + {it.fromFile ? 파일 : !it.songId && DB에 없음}
+ {it.hints.length > 0 &&
힌트: {it.hints.join(' → ')}
} {[...it.titleAnswers, ...it.artistAnswers].join(', ') || -} {mmss(it.durationSec ?? (it.songId ? db[it.songId]?.durationSec : null))} @@ -561,7 +627,7 @@ function SongsTab({ ); } -function AddSong({ onAdd, onImport }: { onAdd: (it: Omit) => boolean; onImport: () => void }) { +function AddSong({ onAdd, onImport, onFile }: { onAdd: (it: NewSong) => boolean; onImport: () => void; onFile: () => void }) { const [q, setQ] = useState(''); const [dbHits, setDbHits] = useState(null); const [ytHits, setYtHits] = useState(null); @@ -618,6 +684,9 @@ function AddSong({ onAdd, onImport }: { onAdd: (it: Omit 🔗 플레이리스트 가져오기 + {video && done(onAdd(it))} />} {dbHits && ( @@ -672,7 +741,7 @@ function AddSong({ onAdd, onImport }: { onAdd: (it: Omit) => void }) { +function VideoAdd({ v, onAdd }: { v: VideoInfo; onAdd: (it: NewSong) => void }) { const [title, setTitle] = useState(v.title); const [artist, setArtist] = useState(v.artist); const api = useRef<{ time(): number | undefined } | null>(null); @@ -1003,9 +1072,13 @@ function ItemPanel({ onPatch({ title: e.target.value })} /> +
+ 힌트 (적은 순서대로 하나씩 나오고, 마지막에 초성 힌트가 나와요) + onPatch({ hints: hints.slice(0, 5) })} label="힌트" placeholder="힌트 입력 후 Enter (예: 액션 RPG)" /> +
제목 추가 정답 (복수정답) onPatch({ titleAnswers })} label="제목 추가 정답" placeholder="다른 표기 입력 후 Enter (예: 좋은날, Good Day)" /> @@ -1014,7 +1087,9 @@ function ItemPanel({ 가수 추가 정답 onPatch({ artistAnswers })} label="가수 추가 정답" placeholder="다른 표기 입력 후 Enter (예: IU)" />
- {item.songId ? ( + {item.fromFile ? ( +

파일에서 넣은 곡이에요. 적힌 값 그대로 쓰고, 서버 노래 DB 검토에는 올라가지 않아요.

+ ) : item.songId ? (

서버 노래 #{item.songId}와 연결된 곡이에요. 추가 정답은 저장할 때 서버 DB 별칭에도 들어가요. {db && (db.titleAliases.length > 0 || db.artistAliases.length > 0) && ( diff --git a/apps/web/src/styles/global.css b/apps/web/src/styles/global.css index 032947f..1d1d163 100644 --- a/apps/web/src/styles/global.css +++ b/apps/web/src/styles/global.css @@ -360,6 +360,9 @@ input.input.sm { width: 76px; } .quiz-card.plus { align-items: center; justify-content: center; font-weight: 800; cursor: pointer; gap: 4px; } .quiz-card.plus span { font-size: 1.6rem; } .clamp2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } +.clamp1 { display: block; max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.file-cols { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 8px; } +.file-col { display: flex; flex-direction: column; gap: 4px; min-width: 0; font-weight: 700; } .quiz-head { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; } .quiz-head h1 { margin: 0; } .songs-layout.with-panel.quiz { grid-template-columns: minmax(0, 1fr) 520px; } diff --git a/docs/10-roadmap.md b/docs/10-roadmap.md index 5b6e511..ba988a9 100644 --- a/docs/10-roadmap.md +++ b/docs/10-roadmap.md @@ -32,3 +32,4 @@ - 2026-10-22 원곡 찾기 후보 자동 확정 기준 정리(12 문서), 후보 282곡 확정. 제작된 퀴즈 1~3단계: 관리자 퀴즈 편집(곡 추가·검색·순서·복수정답→DB 별칭·수동 저장·설정·공개방식·제한), 곡별 처음·하이라이트 위치 편집기, 방 설정 "제작된 퀴즈 / 직접 선택"과 실제 플레이. 서버 테스트 130개, e2e 전체 통과 - 2026-10-22 제작된 퀴즈 4~6단계: 플레이리스트 가져오기(.6 Lavalink, 유튜브·스포티파이), 검토 대기(전체공개 퀴즈 → 서버 DB, 난이도 조정), 통계 상세(힌트·오답·다시듣기·퀴즈별). 서버 테스트 132개, e2e 전체 통과 +- 2026-10-23 퀴즈 파일 A단계: 관리자 → 퀴즈 "파일로 만들기"(.xlsx·.csv, 라이브러리 없이 브라우저가 읽음 — `packages/shared/src/sheet.ts`), 열 이름으로 링크·정답·설명·힌트·순번 등을 찾고(`quiz-file.ts`) 못 찾은 열만 고름, 시트 고르기, 잘못된 링크·같은 영상 줄 표시. 편집 화면 "파일에서 가져오기"(뒤에 추가·목록 바꾸기), "엑셀로 내보내기"(다시 올릴 수 있는 형식)·빈 양식. 파일 곡은 적힌 값 그대로(서버 DB 연결·검토 대기 없음, 설명 비어도 됨). 곡별 힌트(`custom_quiz_items.hints`): 힌트를 하나씩 → 마지막에 초성(자동은 N초마다, 직접선택은 투표마다). 사용자 BGM 파일 390곡 그대로 생성 확인. 테스트 140개, e2e quiz·game·admin·a11y 통과 diff --git a/e2e/quiz.e2e.ts b/e2e/quiz.e2e.ts index f2b25d3..260e4dc 100644 --- a/e2e/quiz.e2e.ts +++ b/e2e/quiz.e2e.ts @@ -2,6 +2,7 @@ * 관리자 → 퀴즈 editor in a real browser: * - a DB song added from the search shows (and, with 자동 off, keeps) the DB highlight, not the 30% guess * - an edit made while 저장 is on its way stays and stays unsaved + * - 파일로 만들기 from an Excel-style (deflated) .xlsx, 엑셀로 내보내기 reads back, 파일에서 가져오기 a CP949 .csv * Run: bun run build && bun e2e/quiz.e2e.ts (needs /usr/bin/google-chrome) */ import { chromium, type Browser, type BrowserContext } from 'playwright-core'; @@ -10,6 +11,8 @@ import { join } from 'node:path'; import { loadConfig } from '../apps/server/src/config'; import { startServer } from '../apps/server/src/server'; import { Catalog } from '../apps/server/src/collector/catalog'; +import { readXlsx } from '../packages/shared/src/sheet'; +import { deflatedZip } from '../packages/shared/src/zip-fixture'; const PORT = Number(process.env.E2E_PORT ?? 4627); const ORIGIN = `http://localhost:${PORT}`; @@ -113,6 +116,70 @@ try { await p.getByText('저장됨').waitFor(); expect(db.query<{ name: string }, []>('SELECT name FROM custom_quizzes').get()!.name === '이름 2', '두 번째 저장'); }); + await step('파일로 만들기: 엑셀(.xlsx) → 순번 순서·힌트, 빠지는 줄 표시 → 만들기; 내보내기가 같은 곡으로 읽힘; CSV(CP949) 뒤에 추가', async () => { + const cell = (ref: string, v: string) => `${v}`; + const head = ['번호', '유튜브 영상 링크', '게임 제목(한글)', '노래 제목', '힌트(게임장르)', '재생목록 순번']; + const data = [ + ['1', 'https://youtu.be/iIIjS6yDMQo', '감옥탈출(구토할배)', '트레일러', '방탈출(플래시)', '3'], + ['2', 'https://youtu.be/x0-xFqvJ-U8', '갓 오브 워 2', 'The End Begins', '액션', '1'], + ['3', 'https://example.com/x', '잘못된 링크', '', '', '4'], + ['4', 'https://youtu.be/x0-xFqvJ-U8', '같은 영상', '', '', '5'], + ['5', 'https://youtu.be/Yz-Af4p_Vv8', '건파이어 리본', 'Desert Theme', '확인필요', '2'], + ]; + const sheetXml = `${[head, ...data].map((r, i) => `${r.map((v, k) => cell(`${'ABCDEF'[k]}${i + 1}`, v)).join('')}`).join('')}`; + const xlsx = deflatedZip({ + 'xl/workbook.xml': '', + 'xl/_rels/workbook.xml.rels': '', + 'xl/worksheets/sheet1.xml': sheetXml, + 'xl/worksheets/sheet2.xml': `${cell('A1', '메모')}`, + }); + await p.goto(`${ORIGIN}/admin/quizzes`); + await p.getByRole('button', { name: /파일로 만들기/ }).click(); + await p.getByLabel('퀴즈 파일').setInputFiles({ name: '게임 BGM.xlsx', mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', buffer: Buffer.from(xlsx) }); + await p.getByText('빠지는 줄 2개').waitFor(); + expect((await p.getByLabel('시트').inputValue()) === '0', '곡이 있는 시트를 먼저 고르지 않음'); + expect((await p.getByLabel('퀴즈 이름').inputValue()) === '게임 BGM', '이름이 파일 이름이 아님'); + await p.screenshot({ path: join(SHOTS, 'quiz-file-preview.png'), fullPage: true }); + await p.getByRole('button', { name: '3곡으로 만들기' }).click(); + await p.waitForURL(/\/admin\/quizzes\/\d+$/); + await p.locator('.quiz-songs tbody tr').nth(2).waitFor(); + const quizId = Number(new URL(p.url()).pathname.split('/').pop()); + const rows = db + .query<{ title: string; artist: string; hints: string; from_file: number; song_id: number | null }, [number]>('SELECT title, artist, hints, from_file, song_id FROM custom_quiz_items WHERE quiz_id = ? ORDER BY pos') + .all(quizId); + expect( + JSON.stringify(rows) === + JSON.stringify([ + { title: '갓 오브 워 2', artist: 'The End Begins', hints: '["액션"]', from_file: 1, song_id: null }, + { title: '건파이어 리본', artist: 'Desert Theme', hints: '["확인필요"]', from_file: 1, song_id: null }, + { title: '감옥탈출(구토할배)', artist: '트레일러', hints: '["방탈출(플래시)"]', from_file: 1, song_id: null }, + ]), + `저장된 곡: ${JSON.stringify(rows)}`, + ); + expect(JSON.parse(db.query<{ s: string }, [number]>('SELECT settings_json s FROM custom_quizzes WHERE id = ?').get(quizId)!.s).hint === 'manual', '힌트가 투표로 켜지지 않음'); + await p.screenshot({ path: join(SHOTS, 'quiz-file-editor.png'), fullPage: true }); + // 엑셀로 내보내기 → the same songs come back + const [dl] = await Promise.all([p.waitForEvent('download'), p.getByRole('button', { name: /엑셀로 내보내기/ }).click()]); + expect(dl.suggestedFilename() === '게임 BGM.xlsx', `내보낸 파일 이름: ${dl.suggestedFilename()}`); + const back = (await readXlsx(new Uint8Array(await Bun.file((await dl.path())!).arrayBuffer())))[0]!.rows; + expect(back.length === 4 && back[1]![2] === '갓 오브 워 2' && back[1]![4] === '액션' && back[3]![1] === 'https://youtu.be/iIIjS6yDMQo', `내보낸 내용: ${JSON.stringify(back.slice(0, 2))}`); + // 파일에서 가져오기: a Korean Excel CSV (CP949), one new song and one already in the list + const csv = new Uint8Array([ + ...new TextEncoder().encode('link,'), + 0xc1, 0xa4, 0xb4, 0xe4, // 정답 + ...new TextEncoder().encode('\nhttps://youtu.be/9hzKkTpXDwM,'), + 0xb0, 0xd9, 0xbe, 0xda, 0xc7, 0xc1, 0xb5, 0xe5, // 겟앰프드 + ...new TextEncoder().encode('\nhttps://youtu.be/iIIjS6yDMQo,x\n'), + ]); + await p.getByRole('button', { name: '📄 파일' }).click(); + await p.getByLabel('퀴즈 파일').setInputFiles({ name: 'more.csv', mimeType: 'text/csv', buffer: Buffer.from(csv) }); + await p.getByText('이미 목록에 있는 영상 1곡').waitFor(); + await p.getByRole('button', { name: '1곡 목록 뒤에 추가' }).click(); + await p.locator('.quiz-songs tbody tr', { hasText: '겟앰프드' }).waitFor(); + await p.keyboard.press('Control+s'); + await p.getByText('저장됨').waitFor(); + expect(db.query<{ n: number }, [number]>('SELECT COUNT(*) n FROM custom_quiz_items WHERE quiz_id = ?').get(quizId)!.n === 4, '가져온 곡 저장'); + }); expect(errors.length === 0, `페이지 오류: ${errors.join(' | ')}`); } catch (e) { console.log(e instanceof Error ? e.message.slice(0, 400) : e); diff --git a/packages/shared/src/custom-quiz-schema.ts b/packages/shared/src/custom-quiz-schema.ts index 13ee93b..f054e02 100644 --- a/packages/shared/src/custom-quiz-schema.ts +++ b/packages/shared/src/custom-quiz-schema.ts @@ -14,14 +14,17 @@ export const QuizItemSchema = z.object({ songId: z.number().int().positive().nullable(), videoId: z.string().regex(/^[\w-]{11}$/), title: z.string().trim().min(1).max(200), - artist: z.string().trim().min(1).max(200), + // 파일로 만들기: the 설명 column may be empty + artist: z.string().trim().max(200), titleAnswers: answers, artistAnswers: answers, + hints: z.array(z.string().trim().min(1).max(200)).max(5).default([]), + fromFile: z.boolean().default(false), durationSec: z.number().int().min(0).max(36000).nullable(), auto: z.boolean(), startSec: sec, highlightSec: sec, -}); +}).refine((it) => it.fromFile || it.artist.length > 0, { path: ['artist'], message: '가수를 넣어 주세요.' }); export const QuizSaveSchema = z.object({ name: z.string().trim().min(1).max(60), diff --git a/packages/shared/src/custom-quiz.ts b/packages/shared/src/custom-quiz.ts index ee31a5d..9f64f02 100644 --- a/packages/shared/src/custom-quiz.ts +++ b/packages/shared/src/custom-quiz.ts @@ -37,6 +37,10 @@ export interface QuizItem { /** Extra accepted answers for this quiz (also added to the DB song's aliases on save). */ titleAnswers: string[]; artistAnswers: string[]; + /** Hints of this song, shown one by one before the 초성 hint (파일로 만들기의 힌트 열). */ + hints: string[]; + /** Came from a quiz file: used as written, never sent to 검토 대기 (서버 노래 DB). */ + fromFile: boolean; durationSec: number | null; /** 자동: start at 0 and the DB highlight; off = startSec/highlightSec below. */ auto: boolean; diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 9c18c9e..715e42b 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -7,3 +7,5 @@ export * from './room-config-schema'; export * from './answer'; export * from './custom-quiz'; export * from './custom-quiz-schema'; +export * from './quiz-file'; +export * from './sheet'; diff --git a/packages/shared/src/lite.ts b/packages/shared/src/lite.ts index 71aa6eb..b6f1445 100644 --- a/packages/shared/src/lite.ts +++ b/packages/shared/src/lite.ts @@ -4,3 +4,5 @@ export * from './types'; export * from './room-config'; export type { ChatLine, RoomView, RoomPlayerView, ServerMessage, GameView, GameScore, GameHistoryItem, GamePhase } from './protocol'; export * from './custom-quiz'; +export * from './quiz-file'; +export * from './sheet'; diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts index 85bedac..0bc646c 100644 --- a/packages/shared/src/protocol.ts +++ b/packages/shared/src/protocol.ts @@ -124,8 +124,13 @@ export interface GameView { /** Seconds of the clip (null = 끝까지 with unknown length) for the progress bar. */ clipSec: number | null; clipOver: boolean; + /** Every hint shown so far, joined (null = none yet). */ hint: string | null; - /** 자동 공개 at this many seconds (null = none / 직접선택). */ + /** The hints shown so far, in order: the song's own hints (제작된 퀴즈) first, the 초성 hint last. */ + hints: { text: string; chosung: boolean }[]; + /** More hints to come after the ones shown. */ + hintMore: boolean; + /** 자동 공개 of the next hint at this many seconds (null = none / 직접선택 / all shown). */ hintAtSec: number | null; lyrics: string[] | null; /** next = 바로 다음 문제, only during the reveal. */ diff --git a/packages/shared/src/quiz-file.test.ts b/packages/shared/src/quiz-file.test.ts new file mode 100644 index 0000000..6a7fdf3 --- /dev/null +++ b/packages/shared/src/quiz-file.test.ts @@ -0,0 +1,98 @@ +/** 퀴즈 파일: .xlsx / .csv reading and writing, column guessing, rows → quiz songs. */ +import { expect, test } from 'bun:test'; +import { decodeCsv, parseCsv, readSheetFile, readXlsx, writeXlsx } from './sheet'; +import { deflatedZip } from './zip-fixture'; +import { guessColumns, headerRow, parseQuizRows, parseSec, parseVideoId, quizTemplateRows, quizToRows } from './quiz-file'; + +test('reads an Excel-style workbook: shared strings, rich text, numbers, gaps, sheet order and names', async () => { + const x = deflatedZip({ + 'xl/workbook.xml': '', + 'xl/_rels/workbook.xml.rels': '', + 'xl/sharedStrings.xml': '링크게임 제목げーむA&B <1>', + 'xl/worksheets/a.xml': '01https://youtu.be/iIIjS6yDMQo742', + 'xl/worksheets/b.xml': '하나1', + }); + const sheets = await readXlsx(x); + expect(sheets.map((s) => s.name)).toEqual(['게임별 정렬', '재생목록 & 순서']); + expect(sheets[0]!.rows).toEqual([['링크', '', '게임 제목'], [], ['https://youtu.be/iIIjS6yDMQo', '74', 'A&B <1>']]); + expect(sheets[1]!.rows).toEqual([['하나', 'TRUE']]); + await expect(readXlsx(new Uint8Array([1, 2, 3]))).rejects.toThrow('엑셀'); +}); + +test('writes an .xlsx that reads back the same (numbers, empty cells, symbols, Korean)', async () => { + const rows = [['순번', '정답', '설명'], [1, '리그 오브 레전드', 'Still Here <2024> & "롤드컵"'], [2, null, '']]; + const back = await readXlsx(writeXlsx('퀴즈/시트', rows, [6, 30])); + expect(back[0]!.name).toBe('퀴즈 시트'); + expect(back[0]!.rows).toEqual([['순번', '정답', '설명'], ['1', '리그 오브 레전드', 'Still Here <2024> & "롤드컵"'], ['2']]); +}); + +test('CSV: quotes, commas and line breaks inside, tab files, BOM, and Korean Excel (CP949) files', async () => { + expect(parseCsv('링크,정답\r\n"https://youtu.be/x0-xFqvJ-U8","갓 오브 워, 2"\n"줄\n바꿈","따옴표 ""안"""\n\n')).toEqual([ + ['링크', '정답'], + ['https://youtu.be/x0-xFqvJ-U8', '갓 오브 워, 2'], + ['줄\n바꿈', '따옴표 "안"'], + ]); + expect(parseCsv('링크\t정답\nabc\t가, 나')).toEqual([['링크', '정답'], ['abc', '가, 나']]); + const cp949 = new Uint8Array([0xc1, 0xa4, 0xb4, 0xe4, 0x2c, 0x41]); // "정답,A" + expect(decodeCsv(cp949)).toBe('정답,A'); + expect((await readSheetFile('목록.csv', cp949))[0]).toEqual({ name: '목록', rows: [['정답', 'A']] }); + await expect(readSheetFile('old.xls', new Uint8Array([0xd0, 0xcf]))).rejects.toThrow('.xls'); +}); + +test('columns are found by their headers (the sent BGM sheet, our export, English)', () => { + expect(guessColumns(['번호', '유튜브 영상 링크', '게임 제목(한글)', '노래 제목', '힌트(게임장르)', '재생목록 순번'])).toEqual([null, 'link', 'answer', 'desc', 'hint', 'order']); + expect(guessColumns(quizToRows([]).rows[0] as string[])).toEqual(['order', 'link', 'answer', 'desc', 'hint', 'answers', 'descAnswers', 'start', 'highlight']); + expect(guessColumns(['URL', 'Title', 'Artist', 'Hint 1', 'Hint 2'])).toEqual(['link', 'answer', 'desc', 'hint', 'hint']); + // the header row may sit under a title line + expect(headerRow([['게임 BGM 모음'], ['링크', '정답'], ['x', 'y']])).toBe(1); +}); + +test('rows → quiz songs: as written, 순번 order, bad links / no answer / repeated videos listed and left out', () => { + const rows = [ + ['번호', '유튜브 영상 링크', '게임 제목(한글)', '노래 제목', '힌트(게임장르)', '재생목록 순번'], + ['1', 'https://youtu.be/iIIjS6yDMQo', '감옥탈출(구토할배)', '트레일러', '방탈출(플래시)', '3'], + ['2', 'https://www.youtube.com/watch?v=x0-xFqvJ-U8&t=5', '갓 오브 워 2', 'The End Begins', '확인필요', '1'], + ['', '', '', '', '', ''], + ['3', 'https://example.com/a', '없음', '', '', '2'], + ['4', 'youtu.be/iIIjS6yDMQo', '같은 영상', '', '', '4'], + ['5', 'https://youtube.com/shorts/Yz-Af4p_Vv8', '', '설명만', '', '5'], + ['6', 'Es6JbQQE79g', '번호 없음', '', '', ''], + ]; + const p = parseQuizRows(rows, guessColumns(rows[0]!), 0); + expect(p.items.map((i) => [i.videoId, i.title, i.artist, i.hints])).toEqual([ + ['x0-xFqvJ-U8', '갓 오브 워 2', 'The End Begins', ['확인필요']], + ['iIIjS6yDMQo', '감옥탈출(구토할배)', '트레일러', ['방탈출(플래시)']], + ['Es6JbQQE79g', '번호 없음', '', []], + ]); + expect(p.items.every((i) => i.fromFile && i.songId === null && i.auto)).toBe(true); + expect(p.rows.filter((r) => r.problem).map((r) => [r.line, r.problem])).toEqual([ + [5, '유튜브 링크가 아니에요'], + [6, '2번째 줄과 같은 영상이에요'], + [7, '정답이 비어 있어요'], + ]); +}); + +test('our export reads back to the same songs (answers, own positions, several hints) and the template is valid', () => { + const items = [ + { songId: null, videoId: 'iIIjS6yDMQo', title: '감옥탈출', artist: '트레일러', titleAnswers: ['구토할배'], artistAnswers: ['trailer'], hints: ['방탈출', '플래시'], fromFile: true, durationSec: null, auto: false, startSec: 12, highlightSec: 61.5 }, + { songId: 3, videoId: 'x0-xFqvJ-U8', title: '갓 오브 워 2', artist: '', titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, durationSec: 200, auto: true, startSec: null, highlightSec: null }, + ]; + const { rows } = quizToRows(items); + const text = rows.map((r) => r.map((c) => (c === null ? '' : String(c)))); + const back = parseQuizRows(text, guessColumns(text[0]!), 0).items; + expect(back).toEqual([ + { ...items[0]!, durationSec: null }, + { ...items[1]!, songId: null, fromFile: true, durationSec: null }, + ]); + const t = quizTemplateRows().rows.map((r) => r.map((c) => (c === null ? '' : String(c)))); + expect(parseQuizRows(t, guessColumns(t[0]!), 0).items).toHaveLength(1); +}); + +test('video links and times', () => { + expect(parseVideoId('https://youtu.be/VO88htcm09E?si=x')).toBe('VO88htcm09E'); + expect(parseVideoId('https://music.youtube.com/watch?v=VO88htcm09E&list=1')).toBe('VO88htcm09E'); + expect(parseVideoId('m.youtube.com/watch?v=VO88htcm09E')).toBe('VO88htcm09E'); + expect(parseVideoId('https://www.youtube.com/live/VO88htcm09E')).toBe('VO88htcm09E'); + expect(parseVideoId('https://example.com/watch?v=VO88htcm09E')).toBeNull(); + expect([parseSec('95'), parseSec('1:35'), parseSec('01:01:01'), parseSec('1분 5초'), parseSec(''), parseSec('조금')]).toEqual([95, 95, 3661, 65, null, undefined]); +}); diff --git a/packages/shared/src/quiz-file.ts b/packages/shared/src/quiz-file.ts new file mode 100644 index 0000000..5a72ebb --- /dev/null +++ b/packages/shared/src/quiz-file.ts @@ -0,0 +1,210 @@ +/** + * 퀴즈 파일 (관리자 → 퀴즈 → 파일로 만들기 / 내보내기): which column is what, rows → quiz songs, quiz songs → rows. + * Values are used as written (no DB lookup): 정답 = the answer, 설명 = shown with it on the reveal, 힌트 columns in order + * before the 초성 hint. + */ +import type { QuizItem } from './custom-quiz'; + +export type QuizColumn = 'link' | 'answer' | 'desc' | 'hint' | 'answers' | 'descAnswers' | 'order' | 'start' | 'highlight'; + +export const QUIZ_COLUMN_LABEL: Record = { + link: '유튜브 영상 링크', + answer: '정답', + desc: '설명', + hint: '힌트', + answers: '다른 정답', + descAnswers: '설명 다른 정답', + order: '순번', + start: '시작(초)', + highlight: '하이라이트(초)', +}; + +/** Accepts https://youtu.be/ID, youtube.com/watch?v=ID, /shorts/ID, /embed/ID, /live/ID, music.youtube.com or the bare ID. */ +export function parseVideoId(s: string): string | null { + const t = s.trim(); + if (/^[\w-]{11}$/.test(t)) return t; + try { + const u = new URL(/^[a-z]+:\/\//i.test(t) ? t : `https://${t}`); + const host = u.hostname.replace(/^(www|m|music)\./, ''); + let id: string | null = null; + if (host === 'youtu.be') id = u.pathname.slice(1).split('/')[0] ?? null; + else if (host === 'youtube.com' || host === 'youtube-nocookie.com') + id = u.searchParams.get('v') ?? /^\/(?:shorts|embed|live|v)\/([\w-]{11})/.exec(u.pathname)?.[1] ?? null; + return id && /^[\w-]{11}$/.test(id) ? id : null; + } catch { + return null; + } +} + +const norm = (h: string) => h.toLowerCase().replace(/\s+/g, ''); + +/** Guess each column from its header. Several 힌트 columns are allowed (shown in column order); others once. */ +export function guessColumns(header: string[]): (QuizColumn | null)[] { + const out: (QuizColumn | null)[] = header.map(() => null); + const taken = new Set(); + const rules: [QuizColumn, RegExp][] = [ + ['order', /순번|순서|^order$|^no\.?$/], + ['link', /링크|주소|url|영상|유튜브|youtube|video|link/], + ['descAnswers', /(설명|가수|노래|artist).*(다른|추가|복수)정답|(다른|추가|복수)정답.*(설명|가수|노래|artist)/], + ['answers', /(다른|추가|복수)정답|별칭|alias|answers/], + ['hint', /힌트|hint/], + ['highlight', /하이라이트|highlight/], + ['start', /시작|처음|^start/], + ['answer', /정답|게임제목|게임이름|^제목|^title|answer|^게임/], + ['desc', /설명|노래제목|곡명|곡제목|가수|artist|song|desc/], + ]; + header.forEach((h, i) => { + const n = norm(h); + if (!n) return; + for (const [col, re] of rules) { + if (!re.test(n) || (col !== 'hint' && taken.has(col))) continue; + out[i] = col; + taken.add(col); + return; + } + }); + return out; +} + +/** Which row holds the headers: the first of the top rows where a link and an answer column are recognised (else 0). */ +export function headerRow(rows: string[][]): number { + for (let i = 0; i < Math.min(rows.length, 10); i++) { + const g = guessColumns(rows[i]!); + if (g.includes('link') && g.includes('answer')) return i; + } + return 0; +} + +/** "95", "1:35", "01:02:03", "1분 35초" → seconds; '' → null; anything else → undefined (invalid). */ +export function parseSec(s: string): number | null | undefined { + const t = s.trim(); + if (!t) return null; + if (/^\d+(\.\d+)?$/.test(t)) return Number(t); + const hms = /^(?:(\d+):)?(\d+):(\d{1,2}(?:\.\d+)?)$/.exec(t); + if (hms) return Number(hms[1] ?? 0) * 3600 + Number(hms[2]) * 60 + Number(hms[3]); + const ko = /^(?:(\d+)\s*분)?\s*(?:(\d+(?:\.\d+)?)\s*초)?$/.exec(t); + if (ko && (ko[1] || ko[2])) return Number(ko[1] ?? 0) * 60 + Number(ko[2] ?? 0); + return undefined; +} + +const splitAnswers = (s: string) => [...new Set(s.split(/[;\n]/).map((x) => x.trim()).filter(Boolean))].map((x) => x.slice(0, 200)).slice(0, 30); + +export interface FileRow { + /** Row number in the sheet (1-based, as Excel shows it). */ + line: number; + item: QuizItem | null; + /** Why the row is left out: bad link, no answer, same video as an earlier row. */ + problem: string | null; + /** Raw link text, for the preview of bad rows. */ + link: string; +} + +export interface ParsedQuizFile { + rows: FileRow[]; + items: QuizItem[]; +} + +/** + * Sheet rows (header at `headerAt`) → quiz songs. Empty rows are skipped silently; rows with a bad link, no answer or a + * video already used above are listed with the reason and left out. A 순번 column decides the order (rows without one last). + */ +export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[], headerAt = 0): ParsedQuizFile { + const at = (c: QuizColumn) => columns.indexOf(c); + const hintCols = columns.flatMap((c, i) => (c === 'hint' ? [i] : [])); + const cell = (r: string[], i: number) => (i >= 0 ? (r[i] ?? '').trim() : ''); + const body = rows + .map((r, i) => ({ r, line: i + 1 })) + .slice(headerAt + 1) + .filter(({ r }) => r.some((c) => c.trim())); + const oi = at('order'); + if (oi >= 0) { + const key = (r: string[]) => { + const n = Number(cell(r, oi).replace(/,/g, '')); + return cell(r, oi) && Number.isFinite(n) ? n : Infinity; + }; + body.sort((a, b) => key(a.r) - key(b.r) || a.line - b.line); + } + const seen = new Map(); + const out: FileRow[] = []; + for (const { r, line } of body) { + const link = cell(r, at('link')); + const videoId = parseVideoId(link); + const title = cell(r, at('answer')).slice(0, 200); + const problem = !link + ? '링크가 비어 있어요' + : !videoId + ? '유튜브 링크가 아니에요' + : !title + ? '정답이 비어 있어요' + : seen.has(videoId) + ? `${seen.get(videoId)}번째 줄과 같은 영상이에요` + : null; + if (problem) { + out.push({ line, item: null, problem, link }); + continue; + } + seen.set(videoId!, line); + const start = parseSec(cell(r, at('start'))); + const highlight = parseSec(cell(r, at('highlight'))); + const own = (start !== null && start !== undefined) || (highlight !== null && highlight !== undefined); + out.push({ + line, + link, + problem: null, + item: { + songId: null, + videoId: videoId!, + title, + artist: cell(r, at('desc')).slice(0, 200), + titleAnswers: splitAnswers(cell(r, at('answers'))).filter((a) => a !== title), + artistAnswers: splitAnswers(cell(r, at('descAnswers'))), + hints: hintCols.map((i) => cell(r, i).slice(0, 200)).filter(Boolean).slice(0, 5), + fromFile: true, + durationSec: null, + auto: !own, + startSec: own ? (start ?? 0) : null, + highlightSec: own ? (highlight ?? null) : null, + }, + }); + } + return { rows: out, items: out.flatMap((x) => (x.item ? [x.item] : [])) }; +} + +/** Quiz songs → sheet rows with the headers this file format reads back (내보내기, 빈 양식). */ +export function quizToRows(items: QuizItem[]): { rows: (string | number | null)[][]; widths: number[] } { + const hintN = Math.max(1, ...items.map((i) => i.hints.length)); + const hintHeads = hintN === 1 ? ['힌트'] : Array.from({ length: hintN }, (_, i) => `힌트${i + 1}`); + const header = ['순번', QUIZ_COLUMN_LABEL.link, '정답', '설명', ...hintHeads, '다른 정답(;로 구분)', '설명 다른 정답(;로 구분)', '시작(초)', '하이라이트(초)']; + const rows = items.map((it, i) => [ + i + 1, + `https://youtu.be/${it.videoId}`, + it.title, + it.artist, + ...Array.from({ length: hintN }, (_, k) => it.hints[k] ?? ''), + it.titleAnswers.join('; '), + it.artistAnswers.join('; '), + it.auto ? null : (it.startSec ?? 0), + it.auto ? null : it.highlightSec, + ]); + return { rows: [header, ...rows], widths: [6, 32, 30, 30, ...hintHeads.map(() => 20), 24, 24, 10, 14] }; +} + +/** 빈 양식: the headers and one example row. */ +export function quizTemplateRows(): { rows: (string | number | null)[][]; widths: number[] } { + return quizToRows([ + { + songId: null, + videoId: 'iIIjS6yDMQo', + title: '감옥탈출', + artist: '트레일러', + titleAnswers: ['구토할배 감옥탈출'], + artistAnswers: [], + hints: ['방탈출(플래시)'], + fromFile: true, + durationSec: null, + auto: true, + startSec: null, + highlightSec: null, + }, + ]); +} diff --git a/packages/shared/src/sheet.ts b/packages/shared/src/sheet.ts new file mode 100644 index 0000000..a3e2fac --- /dev/null +++ b/packages/shared/src/sheet.ts @@ -0,0 +1,329 @@ +/** + * Spreadsheet files without a library (퀴즈 파일로 만들기·내보내기): read .xlsx / .csv into rows of text, write a + * one-sheet .xlsx. Works in the browser and in Bun (DecompressionStream 'deflate-raw' for zip entries). + */ + +export interface Sheet { + name: string; + /** Cell text, row by row; empty cells are ''. Trailing empty rows are dropped. */ + rows: string[][]; +} + +// ------------------------------------------------------------------ zip +interface ZipEntry { + method: number; + size: number; + offset: number; +} + +function zipEntries(b: Uint8Array): Map { + const v = new DataView(b.buffer, b.byteOffset, b.byteLength); + let eocd = -1; + for (let i = b.length - 22; i >= Math.max(0, b.length - 22 - 65535); i--) + if (v.getUint32(i, true) === 0x06054b50) { + eocd = i; + break; + } + if (eocd < 0) throw new Error('엑셀(.xlsx) 파일이 아니에요.'); + const count = v.getUint16(eocd + 10, true); + let p = v.getUint32(eocd + 16, true); + const out = new Map(); + const dec = new TextDecoder(); + for (let n = 0; n < count && p + 46 <= b.length; n++) { + if (v.getUint32(p, true) !== 0x02014b50) break; + const method = v.getUint16(p + 10, true); + const size = v.getUint32(p + 20, true); + const nameLen = v.getUint16(p + 28, true); + const extraLen = v.getUint16(p + 30, true); + const commentLen = v.getUint16(p + 32, true); + const local = v.getUint32(p + 42, true); + const name = dec.decode(b.subarray(p + 46, p + 46 + nameLen)); + const offset = local + 30 + v.getUint16(local + 26, true) + v.getUint16(local + 28, true); + out.set(name.replace(/^\/+/, ''), { method, size, offset }); + p += 46 + nameLen + extraLen + commentLen; + } + return out; +} + +async function unzipText(b: Uint8Array, e: ZipEntry): Promise { + const raw = b.slice(e.offset, e.offset + e.size); + if (e.method === 0) return new TextDecoder().decode(raw); + if (e.method !== 8) throw new Error('이 엑셀 파일의 압축 방식은 읽을 수 없어요.'); + const stream = new Blob([raw]).stream().pipeThrough(new DecompressionStream('deflate-raw')); + return new Response(stream).text(); +} + +// ------------------------------------------------------------------ xml bits +const ENT: Record = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" }; +const unescapeXml = (s: string) => + s.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (m, e: string) => + e[0] === '#' ? String.fromCodePoint(e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : Number(e.slice(1))) : (ENT[e] ?? m), + ); +const escapeXml = (s: string) => + s + .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); +const attr = (tag: string, name: string) => new RegExp(`\\s${name}="([^"]*)"`).exec(tag)?.[1]; +/** Text of every inside (rich text runs joined), phonetic guides left out. */ +const textOf = (xml: string) => + [...xml.replace(/<(?:\w+:)?rPh\b[\s\S]*?<\/(?:\w+:)?rPh>/g, '').matchAll(/<(?:\w+:)?t(?:\s[^>]*)?>([\s\S]*?)<\/(?:\w+:)?t>/g)].map((m) => unescapeXml(m[1]!)).join(''); + +const colIndex = (ref: string) => { + let n = 0; + for (const ch of ref.replace(/\d+$/, '')) n = n * 26 + (ch.charCodeAt(0) - 64); + return n - 1; +}; +const colName = (i: number) => { + let s = ''; + for (let n = i + 1; n > 0; n = Math.floor((n - 1) / 26)) s = String.fromCharCode(65 + ((n - 1) % 26)) + s; + return s; +}; + +function resolve(base: string, target: string): string { + if (target.startsWith('/')) return target.slice(1); + const parts = base.split('/').slice(0, -1); + for (const seg of target.split('/')) { + if (seg === '..') parts.pop(); + else if (seg !== '.') parts.push(seg); + } + return parts.join('/'); +} + +// ------------------------------------------------------------------ read +export async function readXlsx(bytes: Uint8Array): Promise { + const zip = zipEntries(bytes); + const read = async (path: string) => { + const e = zip.get(path); + return e ? unzipText(bytes, e) : null; + }; + const wb = await read('xl/workbook.xml'); + if (!wb) throw new Error('엑셀(.xlsx) 파일이 아니에요.'); + const rels = new Map(); + for (const m of ((await read('xl/_rels/workbook.xml.rels')) ?? '').matchAll(/<(?:\w+:)?Relationship\b[^>]*>/g)) { + const id = attr(m[0], 'Id'); + const target = attr(m[0], 'Target'); + if (id && target) rels.set(id, resolve('xl/workbook.xml', target)); + } + const shared = [...((await read('xl/sharedStrings.xml')) ?? '').matchAll(/<(?:\w+:)?si\b[^>]*>([\s\S]*?)<\/(?:\w+:)?si>|<(?:\w+:)?si\b[^>]*\/>/g)].map((m) => + m[1] === undefined ? '' : textOf(m[1]), + ); + const out: Sheet[] = []; + for (const m of wb.matchAll(/<(?:\w+:)?sheet\b[^>]*>/g)) { + const name = unescapeXml(attr(m[0], 'name') ?? `시트${out.length + 1}`); + const rid = attr(m[0], 'r:id') ?? /\s\w+:id="([^"]*)"/.exec(m[0])?.[1]; + const path = (rid && rels.get(rid)) ?? `xl/worksheets/sheet${out.length + 1}.xml`; + const xml = await read(path); + if (xml === null) continue; + out.push({ name, rows: sheetRows(xml, shared) }); + } + return out; +} + +function sheetRows(xml: string, shared: string[]): string[][] { + const rows: string[][] = []; + let nextRow = 0; + for (const rm of xml.matchAll(/<(?:\w+:)?row\b([^>]*?)(?:\/>|>([\s\S]*?)<\/(?:\w+:)?row>)/g)) { + const r = Number(attr(rm[1]!, 'r')); + const ri = Number.isInteger(r) && r > 0 ? r - 1 : nextRow; + nextRow = ri + 1; + const cells: string[] = []; + let nextCol = 0; + for (const cm of (rm[2] ?? '').matchAll(/<(?:\w+:)?c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/(?:\w+:)?c>)/g)) { + const ref = attr(cm[1]!, 'r'); + const ci = ref ? colIndex(ref) : nextCol; + nextCol = ci + 1; + const t = attr(cm[1]!, 't'); + const body = cm[2] ?? ''; + const v = /<(?:\w+:)?v>([\s\S]*?)<\/(?:\w+:)?v>/.exec(body)?.[1]; + let text = ''; + if (t === 's') text = shared[Number(v)] ?? ''; + else if (t === 'inlineStr') text = textOf(body); + else if (t === 'b') text = v === '1' ? 'TRUE' : v === '0' ? 'FALSE' : ''; + else if (v !== undefined) text = unescapeXml(v); + while (cells.length < ci) cells.push(''); + cells[ci] = text; + } + while (rows.length < ri) rows.push([]); + rows[ri] = cells; + } + while (rows.length && rows.at(-1)!.every((c) => !c.trim())) rows.pop(); + return rows; +} + +/** CSV / TSV text (comma, tab or semicolon — whichever the first line uses most), quotes as in Excel. */ +export function parseCsv(text: string): string[][] { + const s = text.replace(/^/, ''); + const first = s.slice(0, s.search(/\r?\n|$/)); + const delim = [',', '\t', ';'].map((d) => [d, first.split(d).length] as const).sort((a, b) => b[1] - a[1])[0]![0]; + const rows: string[][] = []; + let row: string[] = []; + let cell = ''; + let quoted = false; + for (let i = 0; i < s.length; i++) { + const ch = s[i]!; + if (quoted) { + if (ch === '"') { + if (s[i + 1] === '"') { + cell += '"'; + i++; + } else quoted = false; + } else cell += ch; + } else if (ch === '"' && cell === '') quoted = true; + else if (ch === delim) { + row.push(cell); + cell = ''; + } else if (ch === '\n' || ch === '\r') { + if (ch === '\r' && s[i + 1] === '\n') i++; + row.push(cell); + rows.push(row); + row = []; + cell = ''; + } else cell += ch; + } + if (cell !== '' || row.length) { + row.push(cell); + rows.push(row); + } + while (rows.length && rows.at(-1)!.every((c) => !c.trim())) rows.pop(); + return rows; +} + +/** Text of a .csv file: UTF-8, or the Korean Excel default (CP949) when it is not valid UTF-8. */ +export function decodeCsv(bytes: Uint8Array): string { + try { + return new TextDecoder('utf-8', { fatal: true }).decode(bytes); + } catch { + return new TextDecoder('euc-kr').decode(bytes); + } +} + +/** Reads an uploaded file by its name: .xlsx (every sheet) or .csv/.tsv/.txt (one sheet). */ +export async function readSheetFile(name: string, bytes: Uint8Array): Promise { + if (/\.xlsx$/i.test(name) || (bytes[0] === 0x50 && bytes[1] === 0x4b)) return readXlsx(bytes); + if (/\.xls$/i.test(name)) throw new Error('예전 엑셀(.xls) 형식은 읽을 수 없어요. 엑셀에서 .xlsx로 저장해 올려 주세요.'); + return [{ name: name.replace(/\.[^.]+$/, '') || '시트1', rows: parseCsv(decodeCsv(bytes)) }]; +} + +// ------------------------------------------------------------------ write +const CRC = (() => { + const t = new Uint32Array(256); + for (let n = 0; n < 256; n++) { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + t[n] = c >>> 0; + } + return t; +})(); +function crc32(b: Uint8Array): number { + let c = 0xffffffff; + for (let i = 0; i < b.length; i++) c = CRC[(c ^ b[i]!) & 0xff]! ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +} + +/** A zip with stored (uncompressed) entries — plenty for a few hundred rows. */ +function zip(files: [string, string][]): Uint8Array { + const enc = new TextEncoder(); + const parts: Uint8Array[] = []; + const central: Uint8Array[] = []; + let offset = 0; + for (const [name, text] of files) { + const nameB = enc.encode(name); + const data = enc.encode(text); + const crc = crc32(data); + const local = new Uint8Array(30 + nameB.length); + const lv = new DataView(local.buffer); + lv.setUint32(0, 0x04034b50, true); + lv.setUint16(4, 20, true); + lv.setUint16(6, 0x0800, true); // UTF-8 names + lv.setUint32(14, crc, true); + lv.setUint32(18, data.length, true); + lv.setUint32(22, data.length, true); + lv.setUint16(26, nameB.length, true); + local.set(nameB, 30); + const cen = new Uint8Array(46 + nameB.length); + const cv = new DataView(cen.buffer); + cv.setUint32(0, 0x02014b50, true); + cv.setUint16(4, 20, true); + cv.setUint16(6, 20, true); + cv.setUint16(8, 0x0800, true); + cv.setUint32(16, crc, true); + cv.setUint32(20, data.length, true); + cv.setUint32(24, data.length, true); + cv.setUint16(28, nameB.length, true); + cv.setUint32(42, offset, true); + cen.set(nameB, 46); + parts.push(local, data); + central.push(cen); + offset += local.length + data.length; + } + const size = central.reduce((a, c) => a + c.length, 0); + const end = new Uint8Array(22); + const ev = new DataView(end.buffer); + ev.setUint32(0, 0x06054b50, true); + ev.setUint16(8, files.length, true); + ev.setUint16(10, files.length, true); + ev.setUint32(12, size, true); + ev.setUint32(16, offset, true); + const out = new Uint8Array(offset + size + 22); + let p = 0; + for (const x of [...parts, ...central, end]) { + out.set(x, p); + p += x.length; + } + return out; +} + +/** + * One-sheet .xlsx: the first row is a bold, frozen header. Numbers stay numbers, everything else is text. + * `widths` are column widths in characters. + */ +export function writeXlsx(sheetName: string, rows: (string | number | null)[][], widths: number[] = []): Uint8Array { + const name = escapeXml(sheetName.replace(/[\\/?*[\]:]/g, ' ').slice(0, 31) || '시트1'); + const body = rows + .map( + (r, ri) => + `${r + .map((v, ci) => { + if (v === null || v === '') return ''; + const ref = `${colName(ci)}${ri + 1}`; + const s = ri === 0 ? ' s="1"' : ''; + return typeof v === 'number' && Number.isFinite(v) + ? `${v}` + : `${escapeXml(String(v))}`; + }) + .join('')}`, + ) + .join(''); + const cols = widths.length ? `${widths.map((w, i) => ``).join('')}` : ''; + const ns = 'xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"'; + const nsR = 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"'; + return zip([ + [ + '[Content_Types].xml', + ``, + ], + [ + '_rels/.rels', + ``, + ], + [ + 'xl/workbook.xml', + ``, + ], + [ + 'xl/_rels/workbook.xml.rels', + ``, + ], + [ + 'xl/styles.xml', + ``, + ], + [ + 'xl/worksheets/sheet1.xml', + `${cols}${body}`, + ], + ]); +} diff --git a/packages/shared/src/zip-fixture.ts b/packages/shared/src/zip-fixture.ts new file mode 100644 index 0000000..ef44509 --- /dev/null +++ b/packages/shared/src/zip-fixture.ts @@ -0,0 +1,21 @@ +/** Tests only: a zip with deflated entries, like Excel writes (the .xlsx reader must inflate them). */ +export function deflatedZip(files: Record): Uint8Array { + const enc = new TextEncoder(); + const parts: number[] = []; + const central: number[] = []; + const u16 = (a: number[], v: number) => a.push(v & 0xff, (v >> 8) & 0xff); + const u32 = (a: number[], v: number) => a.push(v & 0xff, (v >> 8) & 0xff, (v >> 16) & 0xff, (v >>> 24) & 0xff); + for (const [name, text] of Object.entries(files)) { + const nb = enc.encode(name); + const data = Bun.deflateSync(enc.encode(text)); + const offset = parts.length; + u32(parts, 0x04034b50); u16(parts, 20); u16(parts, 0x0800); u16(parts, 8); u32(parts, 0); u32(parts, 0); u32(parts, data.length); u32(parts, text.length); u16(parts, nb.length); u16(parts, 0); + parts.push(...nb, ...data); + u32(central, 0x02014b50); u16(central, 20); u16(central, 20); u16(central, 0x0800); u16(central, 8); u32(central, 0); u32(central, 0); u32(central, data.length); u32(central, text.length); + u16(central, nb.length); u16(central, 0); u16(central, 0); u16(central, 0); u16(central, 0); u32(central, 0); u32(central, offset); + central.push(...nb); + } + const end: number[] = []; + u32(end, 0x06054b50); u16(end, 0); u16(end, 0); u16(end, Object.keys(files).length); u16(end, Object.keys(files).length); u32(end, central.length); u32(end, parts.length); u16(end, 0); + return new Uint8Array([...parts, ...central, ...end]); +}