퀴즈 파일 A단계: 관리자 → 퀴즈 '파일로 만들기'(.xlsx·.csv를 브라우저가 라이브러리 없이 읽음, 열 이름으로 링크·정답·설명·힌트·순번 인식, 시트 선택, 잘못된 링크·중복 영상 표시), 편집 화면 '파일에서 가져오기'(뒤에 추가·목록 바꾸기)·'엑셀로 내보내기'·빈 양식. 파일 곡은 적힌 값 그대로(DB 연결·검토 대기 없음). 곡별 힌트를 하나씩 보여 준 뒤 초성 힌트(자동은 N초마다, 투표는 한 번에 하나)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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