퀴즈 파일 A단계: 관리자 → 퀴즈 '파일로 만들기'(.xlsx·.csv를 브라우저가 라이브러리 없이 읽음, 열 이름으로 링크·정답·설명·힌트·순번 인식, 시트 선택, 잘못된 링크·중복 영상 표시), 편집 화면 '파일에서 가져오기'(뒤에 추가·목록 바꾸기)·'엑셀로 내보내기'·빈 양식. 파일 곡은 적힌 값 그대로(DB 연결·검토 대기 없음). 곡별 힌트를 하나씩 보여 준 뒤 초성 힌트(자동은 N초마다, 투표는 한 번에 하나)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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<string, unknown>) => 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();
|
||||
}
|
||||
});
|
||||
|
||||
4
apps/server/src/db/migrations/012_quiz_file.sql
Normal file
4
apps/server/src/db/migrations/012_quiz_file.sql
Normal file
@@ -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;
|
||||
@@ -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<string>(), 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') },
|
||||
|
||||
@@ -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<Env>, 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;
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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<ItemRow, [number]>('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<ItemRow, [number]>('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',
|
||||
|
||||
@@ -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<ItemRow, [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 = ? 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<ItemRow, [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, 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<number>();
|
||||
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,
|
||||
|
||||
@@ -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[],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -217,12 +217,15 @@ export function GameScreen({ room, game }: { room: RoomView; game: GameView }) {
|
||||
</div>
|
||||
)}
|
||||
<div className="row" style={{ marginTop: 8 }}>
|
||||
{game.hint ? (
|
||||
<span className="hint">
|
||||
{game.hint} <small>초성 힌트</small>
|
||||
{(game.hints ?? []).map((h, i) => (
|
||||
<span key={i} className="hint">
|
||||
{h.text} <small>{h.chosung ? '초성 힌트' : `힌트 ${i + 1}`}</small>
|
||||
</span>
|
||||
))}
|
||||
{game.hintAtSec !== null && game.phase === 'play' ? (
|
||||
<span className="small muted">
|
||||
{game.hints?.length ? '다음 힌트' : '힌트'}는 {Math.max(0, Math.ceil(game.hintAtSec - elapsed / 1000))}초 뒤에 공개돼요
|
||||
</span>
|
||||
) : game.hintAtSec !== null && game.phase === 'play' ? (
|
||||
<span className="small muted">힌트는 {Math.max(0, Math.ceil(game.hintAtSec - elapsed / 1000))}초 뒤에 공개돼요</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
299
apps/web/src/pages/admin/QuizFile.tsx
Normal file
299
apps/web/src/pages/admin/QuizFile.tsx
Normal file
@@ -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<ArrayBuffer>], { 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<void>;
|
||||
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 (
|
||||
<div className="card stack" style={{ gap: 12 }}>
|
||||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||||
<b>📄 {mode === 'create' ? '파일로 만들기' : '파일에서 가져오기'}</b>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={onClose} aria-label="닫기">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<div className="row">
|
||||
<label className="btn btn-primary">
|
||||
{file ? '다른 파일 고르기' : '파일 고르기 (.xlsx, .csv)'}
|
||||
<input
|
||||
type="file"
|
||||
accept=".xlsx,.csv,.tsv,.txt,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/csv"
|
||||
hidden
|
||||
aria-label="퀴즈 파일"
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0];
|
||||
e.target.value = '';
|
||||
if (f) void open(f);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<button type="button" className="btn" onClick={downloadTemplate}>
|
||||
📥 빈 양식 받기
|
||||
</button>
|
||||
{file && <span className="muted small">{file.name}</span>}
|
||||
</div>
|
||||
{!file && (
|
||||
<p className="muted small" style={{ margin: 0 }}>
|
||||
한 줄에 한 곡씩, 첫 줄은 열 이름이에요. <b>유튜브 영상 링크</b>와 <b>정답</b>(예: 게임 제목)은 꼭 있어야 하고, <b>설명</b>(예: 노래 제목)은 정답을 공개할 때 같이
|
||||
보여요. <b>힌트</b> 열은 문제마다 먼저 나오고, 그다음 힌트로 초성이 나와요. <b>순번</b> 열이 있으면 그 순서대로 넣어요. 적힌 값은 고치지 않고 그대로 써요.
|
||||
</p>
|
||||
)}
|
||||
{file && sheet && (
|
||||
<>
|
||||
{file.sheets.length > 1 && (
|
||||
<label className="field-inline">
|
||||
시트
|
||||
<select className="input sm" style={{ width: 'auto' }} value={sheetIdx} onChange={(e) => pickSheet(file.sheets, Number(e.target.value))} aria-label="시트">
|
||||
{file.sheets.map((s, i) => (
|
||||
<option key={i} value={i}>
|
||||
{s.name} ({Math.max(0, s.rows.length - 1)}줄)
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<span className="field">열 {missing.length ? '— 아래에서 골라 주세요' : '(열 이름으로 찾았어요. 다르면 바꿔 주세요)'}</span>
|
||||
<div className="file-cols">
|
||||
{Array.from({ length: width }, (_, i) => (
|
||||
<label key={i} className="file-col">
|
||||
<span className="small clamp1" title={header[i] ?? ''}>
|
||||
{header[i]?.trim() || `${i + 1}번째 열`}
|
||||
</span>
|
||||
<select className="input sm" value={columns[i] ?? ''} onChange={(e) => setColumn(i, (e.target.value || null) as QuizColumn | null)} aria-label={`${header[i] || `${i + 1}번째 열`} 쓰임`}>
|
||||
<option value="">안 씀</option>
|
||||
{COLUMN_ORDER.map((c) => (
|
||||
<option key={c} value={c}>
|
||||
{QUIZ_COLUMN_LABEL[c]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{missing.length > 0 && <span className="warn-text small">{missing.map((c) => QUIZ_COLUMN_LABEL[c]).join(', ')} 열을 골라 주세요.</span>}
|
||||
</div>
|
||||
{!missing.length && parsed && (
|
||||
<>
|
||||
<div className="small">
|
||||
<b>{items.length}곡</b>
|
||||
{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>
|
||||
{bad.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>
|
||||
{bad.map((r) => (
|
||||
<tr key={r.line}>
|
||||
<td className="mono">{r.line}</td>
|
||||
<td className="warn-text small">{r.problem}</td>
|
||||
<td className="small">
|
||||
<span className="clamp1" style={{ maxWidth: 360 }}>
|
||||
{r.link || '-'}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{items.length > 0 && (
|
||||
<div className="table-wrap" style={{ maxHeight: 420, overflowY: 'auto' }}>
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: 44 }}>#</th>
|
||||
<th>정답</th>
|
||||
<th>설명</th>
|
||||
<th>힌트</th>
|
||||
<th>영상</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map((it, i) => (
|
||||
<tr key={it.videoId}>
|
||||
<td className="mono">{i + 1}</td>
|
||||
<td>
|
||||
<b>{it.title}</b>
|
||||
{it.titleAnswers.length > 0 && <div className="muted small">또는 {it.titleAnswers.join(', ')}</div>}
|
||||
</td>
|
||||
<td className="small">{it.artist || <span className="muted">-</span>}</td>
|
||||
<td className="small">{[...it.hints, '초성'].join(' → ')}</td>
|
||||
<td className="small">
|
||||
<a href={`https://youtu.be/${it.videoId}`} target="_blank" rel="noreferrer">
|
||||
{it.videoId} ↗
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{mode === 'create' ? (
|
||||
<form
|
||||
className="row"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void create();
|
||||
}}
|
||||
>
|
||||
<label className="field-inline grow">
|
||||
퀴즈 이름
|
||||
<input className="input grow" value={name} maxLength={60} onChange={(e) => setName(e.target.value)} aria-label="퀴즈 이름" />
|
||||
</label>
|
||||
<button className="btn btn-primary" disabled={busy || !name.trim() || !items.length}>
|
||||
{busy ? '만드는 중…' : `${items.length}곡으로 만들기`}
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="row">
|
||||
<button type="button" className="btn btn-primary" disabled={!appendable.length} onClick={() => onApply?.(appendable, false)}>
|
||||
{appendable.length}곡 목록 뒤에 추가
|
||||
</button>
|
||||
<button type="button" className="btn btn-danger" disabled={!items.length} onClick={() => setConfirmReplace(true)}>
|
||||
지금 목록을 지우고 바꾸기
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{confirmReplace && (
|
||||
<ConfirmSheet
|
||||
title="지금 목록을 바꿀까요?"
|
||||
body={`지금 곡 목록 ${existing.length}곡과 그 곡들의 정답·위치 설정이 사라지고 파일의 ${items.length}곡으로 바뀌어요. 저장하기 전에는 되돌릴 수 있어요(저장하지 않고 나가기).`}
|
||||
confirm="목록 바꾸기"
|
||||
danger
|
||||
onClose={() => setConfirmReplace(false)}
|
||||
onConfirm={() => onApply?.(items, true)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<QuizVisibility, string> = { private: '비공개', partial: '일부공개', public: '전체공개' };
|
||||
@@ -36,6 +37,7 @@ export function QuizzesPage() {
|
||||
const [list, setList] = useState<QuizSummary[] | null>(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() {
|
||||
)}
|
||||
</div>
|
||||
<p className="muted">직접 만든 퀴즈예요. 방 설정에서 "제작된 퀴즈"를 고르면 이 퀴즈의 곡이 순서대로(또는 섞어서) 전부 나와요. 듣고맞추기에서만 쓸 수 있어요.</p>
|
||||
{fromFile && (
|
||||
<QuizFileImport
|
||||
mode="create"
|
||||
onClose={() => 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');
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<div className="quiz-grid">
|
||||
{list?.map((q) => (
|
||||
<Link key={q.id} to={`/admin/quizzes/${q.id}`} className="quiz-card">
|
||||
@@ -103,6 +120,12 @@ export function QuizzesPage() {
|
||||
<span aria-hidden>+</span> 퀴즈 추가
|
||||
</button>
|
||||
)}
|
||||
{!fromFile && (
|
||||
<button type="button" className="quiz-card add plus" onClick={() => setFromFile(true)}>
|
||||
<span aria-hidden>📄</span> 파일로 만들기
|
||||
<small className="muted">엑셀(.xlsx)·CSV</small>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{list && list.length === 0 && !adding && <p className="muted">아직 만든 퀴즈가 없어요. "퀴즈 추가"를 눌러 시작해 보세요.</p>}
|
||||
</>
|
||||
@@ -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<QuizItem, 'titleAnswers' | 'artistAnswers' | 'hints' | 'fromFile' | 'auto' | 'startSec' | 'highlightSec'>;
|
||||
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<number, DbInfo> }>('GET', `/api/admin/quizzes/${id}`)
|
||||
@@ -274,6 +302,9 @@ export function QuizEditor() {
|
||||
</Link>
|
||||
<h1 className="grow">{draft.name || '이름 없는 퀴즈'}</h1>
|
||||
{dirty ? <span className="badge warn" role="status">● 저장하지 않은 변경이 있어요</span> : <span className="muted small">저장됨</span>}
|
||||
<button type="button" className="btn" disabled={!draft.items.length} onClick={() => exportQuiz(draft.name, draft.items)} title="곡 목록을 다시 올릴 수 있는 엑셀 파일로 받아요">
|
||||
📥 엑셀로 내보내기
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" disabled={busy || !dirty} onClick={() => void save()} title="Ctrl+S">
|
||||
{busy ? '저장 중…' : '저장'} <span className="kbd">Ctrl+S</span>
|
||||
</button>
|
||||
@@ -298,6 +329,9 @@ export function QuizEditor() {
|
||||
<button type="button" className="btn" onClick={() => (setParams({}), setTab('songs'), setImportOpen(true))}>
|
||||
🔗 플레이리스트 가져오기
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={() => (setParams({}), setTab('songs'), setFileOpen(true))}>
|
||||
📄 파일에서 가져오기
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" onClick={() => setParams({})}>
|
||||
✋ 직접 하나씩 추가
|
||||
</button>
|
||||
@@ -305,7 +339,17 @@ export function QuizEditor() {
|
||||
</div>
|
||||
)}
|
||||
{tab === 'songs' ? (
|
||||
<SongsTab items={draft.items} db={db} settings={draft.settings} onItems={(items) => set({ items })} importOpen={importOpen} setImportOpen={setImportOpen} />
|
||||
<SongsTab
|
||||
items={draft.items}
|
||||
db={db}
|
||||
settings={draft.settings}
|
||||
onItems={(items) => set({ items })}
|
||||
importOpen={importOpen}
|
||||
setImportOpen={setImportOpen}
|
||||
fileOpen={fileOpen}
|
||||
setFileOpen={setFileOpen}
|
||||
onHints={() => draft.settings.hint === 'none' && set({ settings: { ...draft.settings, hint: 'manual' } })}
|
||||
/>
|
||||
) : (
|
||||
<SettingsTab draft={draft} onChange={set} onDelete={() => setConfirmDelete(true)} />
|
||||
)}
|
||||
@@ -406,6 +450,9 @@ function SongsTab({
|
||||
onItems,
|
||||
importOpen,
|
||||
setImportOpen,
|
||||
fileOpen,
|
||||
setFileOpen,
|
||||
onHints,
|
||||
}: {
|
||||
items: DraftItem[];
|
||||
db: Record<number, DbInfo | null>;
|
||||
@@ -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<string | null>(null);
|
||||
const [dragKey, setDragKey] = useState<string | null>(null);
|
||||
const [overKey, setOverKey] = useState<string | null>(null);
|
||||
const selected = items.find((i) => i.key === sel) ?? null;
|
||||
const add = (it: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => {
|
||||
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 (
|
||||
<div className={`songs-layout quiz ${selected ? 'with-panel' : ''}`}>
|
||||
<div className="stack" style={{ gap: 12, minWidth: 0 }}>
|
||||
{importOpen ? (
|
||||
{fileOpen ? (
|
||||
<QuizFileImport
|
||||
mode="into"
|
||||
existing={items}
|
||||
onClose={() => 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 ? (
|
||||
<PlaylistImport
|
||||
existing={items}
|
||||
onClose={() => 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}곡 제외)` : ''}. 저장해야 반영돼요.`);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<AddSong onAdd={add} onImport={() => setImportOpen(true)} />
|
||||
<AddSong onAdd={add} onImport={() => setImportOpen(true)} onFile={() => setFileOpen(true)} />
|
||||
)}
|
||||
{items.length === 0 ? (
|
||||
<p className="muted">아직 곡이 없어요. 위에서 제목·가수로 찾거나 유튜브 주소를 붙여 넣어 추가해 주세요.</p>
|
||||
@@ -516,8 +581,9 @@ function SongsTab({
|
||||
<b>{it.title}</b>
|
||||
<div className="muted small">
|
||||
{it.artist}
|
||||
{!it.songId && <span className="badge" style={{ marginLeft: 6 }}>DB에 없음</span>}
|
||||
{it.fromFile ? <span className="badge" style={{ marginLeft: 6 }}>파일</span> : !it.songId && <span className="badge" style={{ marginLeft: 6 }}>DB에 없음</span>}
|
||||
</div>
|
||||
{it.hints.length > 0 && <div className="muted small">힌트: {it.hints.join(' → ')}</div>}
|
||||
</td>
|
||||
<td className="small">{[...it.titleAnswers, ...it.artistAnswers].join(', ') || <span className="muted">-</span>}</td>
|
||||
<td className="mono small">{mmss(it.durationSec ?? (it.songId ? db[it.songId]?.durationSec : null))}</td>
|
||||
@@ -561,7 +627,7 @@ function SongsTab({
|
||||
);
|
||||
}
|
||||
|
||||
function AddSong({ onAdd, onImport }: { onAdd: (it: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => boolean; onImport: () => void }) {
|
||||
function AddSong({ onAdd, onImport, onFile }: { onAdd: (it: NewSong) => boolean; onImport: () => void; onFile: () => void }) {
|
||||
const [q, setQ] = useState('');
|
||||
const [dbHits, setDbHits] = useState<DbHit[] | null>(null);
|
||||
const [ytHits, setYtHits] = useState<YtHit[] | null>(null);
|
||||
@@ -618,6 +684,9 @@ function AddSong({ onAdd, onImport }: { onAdd: (it: Omit<QuizItem, 'titleAnswers
|
||||
<button type="button" className="btn" onClick={onImport}>
|
||||
🔗 플레이리스트 가져오기
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={onFile}>
|
||||
📄 파일
|
||||
</button>
|
||||
</form>
|
||||
{video && <VideoAdd v={video} onAdd={(it) => done(onAdd(it))} />}
|
||||
{dbHits && (
|
||||
@@ -672,7 +741,7 @@ function AddSong({ onAdd, onImport }: { onAdd: (it: Omit<QuizItem, 'titleAnswers
|
||||
);
|
||||
}
|
||||
|
||||
function VideoAdd({ v, onAdd }: { v: VideoInfo; onAdd: (it: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => 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({
|
||||
<input className="input" value={item.title} maxLength={200} onChange={(e) => onPatch({ title: e.target.value })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
가수
|
||||
{item.fromFile ? '설명 (정답과 같이 공개돼요)' : '가수'}
|
||||
<input className="input" value={item.artist} maxLength={200} onChange={(e) => onPatch({ artist: e.target.value })} />
|
||||
</label>
|
||||
<div className="field">
|
||||
힌트 (적은 순서대로 하나씩 나오고, 마지막에 초성 힌트가 나와요)
|
||||
<ChipsInput values={item.hints} onChange={(hints) => onPatch({ hints: hints.slice(0, 5) })} label="힌트" placeholder="힌트 입력 후 Enter (예: 액션 RPG)" />
|
||||
</div>
|
||||
<div className="field">
|
||||
제목 추가 정답 (복수정답)
|
||||
<ChipsInput values={item.titleAnswers} onChange={(titleAnswers) => onPatch({ titleAnswers })} label="제목 추가 정답" placeholder="다른 표기 입력 후 Enter (예: 좋은날, Good Day)" />
|
||||
@@ -1014,7 +1087,9 @@ function ItemPanel({
|
||||
가수 추가 정답
|
||||
<ChipsInput values={item.artistAnswers} onChange={(artistAnswers) => onPatch({ artistAnswers })} label="가수 추가 정답" placeholder="다른 표기 입력 후 Enter (예: IU)" />
|
||||
</div>
|
||||
{item.songId ? (
|
||||
{item.fromFile ? (
|
||||
<p className="muted small">파일에서 넣은 곡이에요. 적힌 값 그대로 쓰고, 서버 노래 DB 검토에는 올라가지 않아요.</p>
|
||||
) : item.songId ? (
|
||||
<p className="muted small">
|
||||
서버 노래 #{item.songId}와 연결된 곡이에요. 추가 정답은 저장할 때 서버 DB 별칭에도 들어가요.
|
||||
{db && (db.titleAliases.length > 0 || db.artistAliases.length > 0) && (
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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 통과
|
||||
|
||||
@@ -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) => `<c r="${ref}" t="inlineStr"><is><t>${v}</t></is></c>`;
|
||||
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 = `<worksheet><sheetData>${[head, ...data].map((r, i) => `<row r="${i + 1}">${r.map((v, k) => cell(`${'ABCDEF'[k]}${i + 1}`, v)).join('')}</row>`).join('')}</sheetData></worksheet>`;
|
||||
const xlsx = deflatedZip({
|
||||
'xl/workbook.xml': '<workbook xmlns:r="r"><sheets><sheet name="게임별 정렬" sheetId="1" r:id="rId1"/><sheet name="메모" sheetId="2" r:id="rId2"/></sheets></workbook>',
|
||||
'xl/_rels/workbook.xml.rels': '<Relationships><Relationship Id="rId1" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Target="worksheets/sheet2.xml"/></Relationships>',
|
||||
'xl/worksheets/sheet1.xml': sheetXml,
|
||||
'xl/worksheets/sheet2.xml': `<worksheet><sheetData><row r="1">${cell('A1', '메모')}</row></sheetData></worksheet>`,
|
||||
});
|
||||
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);
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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. */
|
||||
|
||||
98
packages/shared/src/quiz-file.test.ts
Normal file
98
packages/shared/src/quiz-file.test.ts
Normal file
@@ -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': '<workbook xmlns:r="r"><sheets><sheet name="게임별 정렬" sheetId="1" r:id="rId1"/><sheet name="재생목록 & 순서" sheetId="2" r:id="rId2"/></sheets></workbook>',
|
||||
'xl/_rels/workbook.xml.rels': '<Relationships><Relationship Id="rId2" Target="worksheets/b.xml"/><Relationship Id="rId1" Target="/xl/worksheets/a.xml"/></Relationships>',
|
||||
'xl/sharedStrings.xml': '<sst><si><t>링크</t></si><si><r><t>게임 </t></r><r><t xml:space="preserve">제목</t></r><rPh><t>げーむ</t></rPh></si><si><t>A&B <1></t></si></sst>',
|
||||
'xl/worksheets/a.xml': '<worksheet><sheetData><row r="1"><c r="A1" t="s"><v>0</v></c><c r="C1" t="s"><v>1</v></c></row><row r="3"><c r="A3" t="inlineStr"><is><t>https://youtu.be/iIIjS6yDMQo</t></is></c><c r="B3"><v>74</v></c><c r="C3" t="s"><v>2</v></c></row></sheetData></worksheet>',
|
||||
'xl/worksheets/b.xml': '<x:worksheet xmlns:x="m"><x:sheetData><x:row><x:c t="str"><x:v>하나</x:v></x:c><x:c t="b"><x:v>1</x:v></x:c></x:row><x:row r="2"/></x:sheetData></x:worksheet>',
|
||||
});
|
||||
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]);
|
||||
});
|
||||
210
packages/shared/src/quiz-file.ts
Normal file
210
packages/shared/src/quiz-file.ts
Normal file
@@ -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<QuizColumn, string> = {
|
||||
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<QuizColumn>();
|
||||
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<string, number>();
|
||||
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,
|
||||
},
|
||||
]);
|
||||
}
|
||||
329
packages/shared/src/sheet.ts
Normal file
329
packages/shared/src/sheet.ts
Normal file
@@ -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<string, ZipEntry> {
|
||||
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<string, ZipEntry>();
|
||||
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<string> {
|
||||
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<string, string> = { 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, '>')
|
||||
.replace(/"/g, '"');
|
||||
const attr = (tag: string, name: string) => new RegExp(`\\s${name}="([^"]*)"`).exec(tag)?.[1];
|
||||
/** Text of every <t> 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<Sheet[]> {
|
||||
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<string, string>();
|
||||
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<Sheet[]> {
|
||||
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) =>
|
||||
`<row r="${ri + 1}">${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)
|
||||
? `<c r="${ref}"${s}><v>${v}</v></c>`
|
||||
: `<c r="${ref}"${s} t="inlineStr"><is><t xml:space="preserve">${escapeXml(String(v))}</t></is></c>`;
|
||||
})
|
||||
.join('')}</row>`,
|
||||
)
|
||||
.join('');
|
||||
const cols = widths.length ? `<cols>${widths.map((w, i) => `<col min="${i + 1}" max="${i + 1}" width="${w}" customWidth="1"/>`).join('')}</cols>` : '';
|
||||
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',
|
||||
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>`,
|
||||
],
|
||||
[
|
||||
'_rels/.rels',
|
||||
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`,
|
||||
],
|
||||
[
|
||||
'xl/workbook.xml',
|
||||
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><workbook ${ns} ${nsR}><sheets><sheet name="${name}" sheetId="1" r:id="rId1"/></sheets></workbook>`,
|
||||
],
|
||||
[
|
||||
'xl/_rels/workbook.xml.rels',
|
||||
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>`,
|
||||
],
|
||||
[
|
||||
'xl/styles.xml',
|
||||
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><styleSheet ${ns}><fonts count="2"><font><sz val="11"/><name val="맑은 고딕"/></font><font><b/><sz val="11"/><name val="맑은 고딕"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/><xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs></styleSheet>`,
|
||||
],
|
||||
[
|
||||
'xl/worksheets/sheet1.xml',
|
||||
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet ${ns} ${nsR}><sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews>${cols}<sheetData>${body}</sheetData></worksheet>`,
|
||||
],
|
||||
]);
|
||||
}
|
||||
21
packages/shared/src/zip-fixture.ts
Normal file
21
packages/shared/src/zip-fixture.ts
Normal file
@@ -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<string, string>): 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]);
|
||||
}
|
||||
Reference in New Issue
Block a user