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

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

View File

@@ -1,8 +1,8 @@
/** 퀴즈 파일: .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 { decodeCsv, parseCsv, readSheetFile, readXlsx, writeXlsx, writeXlsxSheets } from './sheet';
import { deflatedZip } from './zip-fixture';
import { guessColumns, headerRow, parseQuizRows, parseSec, parseVideoId, parseViews, quizTemplateRows, quizToRows } from './quiz-file';
import { guessColumns, headerRow, parseQuizRows, parseSec, parseVideoId, parseViews, playlistSheets, quizTemplateRows, quizToRows, type PlaylistSheetRow } from './quiz-file';
test('reads an Excel-style workbook: shared strings, rich text, numbers, gaps, sheet order and names', async () => {
const x = deflatedZip({
@@ -142,3 +142,74 @@ test('이지선다 파일: 제목·가수, 조회수 optional (empty = fetched b
expect(t[0]).toEqual(['순번', '유튜브 영상 링크', '제목', '가수', '시작(초)', '하이라이트(초)']);
expect(parseQuizRows(t, guessColumns(t[0]!), 0, 'duel').items.map((i) => [i.title, i.views])).toEqual([['라일락', null]]);
});
test('재생목록으로 엑셀 만들기: kept songs with 비고, unplayable / missing / repeated videos on 빠진 곡, read back by 파일로 만들기', async () => {
const row = (p: Partial<PlaylistSheetRow> & { n: number }): PlaylistSheetRow => ({
source: { title: `원래 ${p.n}`, artist: '채널' },
title: `곡 ${p.n}`,
artist: `가수 ${p.n}`,
durationSec: 200,
videoId: null,
status: 'video',
note: '',
...p,
});
const sheets = playlistSheets([
row({ n: 1, videoId: 'goodday0001', status: 'db', note: '서버 DB 곡 (플레이리스트 영상 사용)', title: '좋은 날', artist: '아이유', durationSec: 230 }),
row({ n: 2, videoId: 'lovedive001', note: '제목·가수 확인 필요 (영상 제목 형식이 달라 채널 이름을 가수로 씀)' }),
row({ n: 3, videoId: 'blocked0001', status: 'blocked', note: '다른 사이트 재생이 막힌 영상' }),
row({ n: 4, videoId: 'goodday0001', status: 'db' }),
row({ n: 5, status: 'missing', note: '유튜브에서 못 찾았어요' }),
row({ n: 6, videoId: 'hypeboy0001', status: 'check', note: '확인 필요: NewJeans - Hype Boy' }),
row({ n: 7, videoId: 'ditto000001', status: 'found', durationSec: null }),
]);
expect(sheets.map((x) => x.name)).toEqual(['퀴즈', '빠진 곡']);
expect(sheets[0]!.rows).toEqual([
['순번', '유튜브 영상 링크', '제목', '가수', '시작(초)', '하이라이트(초)', '길이(초)', '비고'],
[1, 'https://youtu.be/goodday0001', '좋은 날', '아이유', null, null, 230, 'DB 곡'],
[2, 'https://youtu.be/lovedive001', '곡 2', '가수 2', null, null, 200, '제목·가수 확인 필요 (영상 제목 형식이 달라 채널 이름을 가수로 씀)'],
[3, 'https://youtu.be/hypeboy0001', '곡 6', '가수 6', null, null, 200, '확인 필요: NewJeans - Hype Boy'],
[4, 'https://youtu.be/ditto000001', '곡 7', '가수 7', null, null, null, '유튜브 뮤직에서 찾음'],
]);
expect(sheets[1]!.rows.slice(1)).toEqual([
[3, 'https://youtu.be/blocked0001', '원래 3', '채널', '다른 사이트 재생이 막힌 영상'],
[4, 'https://youtu.be/goodday0001', '원래 4', '채널', '재생목록 1번 곡과 같은 영상'],
[5, '', '원래 5', '채널', '유튜브에서 못 찾았어요'],
]);
// the file as downloaded: 파일로 만들기 finds the columns by name, and the 빠진 곡 sheet gives no songs
const book = await readSheetFile('재생목록.xlsx', writeXlsxSheets(sheets));
expect(book.map((x) => x.name)).toEqual(['퀴즈', '빠진 곡']);
const cols = guessColumns(book[0]!.rows[0]!);
expect(cols).toEqual(['order', 'link', 'answer', 'desc', 'start', 'highlight', 'duration', null]);
expect(parseQuizRows(book[1]!.rows, guessColumns(book[1]!.rows[headerRow(book[1]!.rows)]!), headerRow(book[1]!.rows)).items).toEqual([]);
for (const kind of ['normal', 'duel'] as const) {
const items = parseQuizRows(book[0]!.rows, cols, 0, kind).items;
expect(items.map((i) => [i.videoId, i.title, i.artist, i.durationSec, i.auto])).toEqual([
['goodday0001', '좋은 날', '아이유', 230, true],
['lovedive001', '곡 2', '가수 2', 200, true],
['hypeboy0001', '곡 6', '가수 6', 200, true],
['ditto000001', '곡 7', '가수 7', null, true],
]);
}
});
test('시작·하이라이트가 빈 곡: 자동 (start 0 + highlight worked out) or 처음부터 (0 / 0); written values are kept either way', () => {
const rows = [
['링크', '정답', '시작(초)', '하이라이트(초)', '길이'],
['iIIjS6yDMQo', '빈 곡', '', '', '3:20'],
['x0-xFqvJ-U8', '하이라이트만', '', '1:05', ''],
['Es6JbQQE79g', '시작만', '12', '', 'abc'],
];
const cols = guessColumns(rows[0]!);
const pos = (blank: 'auto' | 'start') => parseQuizRows(rows, cols, 0, 'normal', blank).items.map((i) => [i.auto, i.startSec, i.highlightSec, i.durationSec]);
expect(pos('auto')).toEqual([
[true, null, null, 200],
[false, 0, 65, null],
[false, 12, null, null],
]);
expect(pos('start')).toEqual([
[false, 0, 0, 200],
[false, 0, 65, null],
[false, 12, null, null],
]);
});

View File

@@ -5,7 +5,7 @@
*/
import type { QuizItem, QuizKind } from './custom-quiz';
export type QuizColumn = 'link' | 'answer' | 'desc' | 'hint' | 'answers' | 'descAnswers' | 'order' | 'start' | 'highlight' | 'views';
export type QuizColumn = 'link' | 'answer' | 'desc' | 'hint' | 'answers' | 'descAnswers' | 'order' | 'start' | 'highlight' | 'duration' | 'views';
export const QUIZ_COLUMN_LABEL: Record<QuizColumn, string> = {
link: '유튜브 영상 링크',
@@ -17,6 +17,7 @@ export const QUIZ_COLUMN_LABEL: Record<QuizColumn, string> = {
order: '순번',
start: '시작(초)',
highlight: '하이라이트(초)',
duration: '길이(초)',
views: '조회수',
};
@@ -25,8 +26,8 @@ export const DUEL_COLUMN_LABEL: Partial<Record<QuizColumn, string>> = { answer:
/** The columns each kind of quiz file uses, in the order the column pickers list them. */
export const QUIZ_FILE_COLUMNS: Record<QuizKind, QuizColumn[]> = {
normal: ['link', 'answer', 'desc', 'hint', 'answers', 'descAnswers', 'order', 'start', 'highlight'],
duel: ['link', 'answer', 'desc', 'views', 'order', 'start', 'highlight'],
normal: ['link', 'answer', 'desc', 'hint', 'answers', 'descAnswers', 'order', 'start', 'highlight', 'duration'],
duel: ['link', 'answer', 'desc', 'views', 'order', 'start', 'highlight', 'duration'],
};
/**
@@ -75,6 +76,7 @@ export function guessColumns(header: string[]): (QuizColumn | null)[] {
['answers', /(다른|추가|복수)정답|별칭|alias|answers/],
['hint', /힌트|hint/],
['highlight', /하이라이트|highlight/],
['duration', /길이|duration|^length/],
['start', /시작|처음|^start/],
['answer', /정답|게임제목|게임이름|^제목|^title|answer|^게임/],
['desc', /설명|노래제목|곡명|곡제목|가수|artist|song|desc/],
@@ -130,13 +132,19 @@ export interface ParsedQuizFile {
items: QuizItem[];
}
/**
* Songs whose 시작·하이라이트 cells are both empty: 자동 (start at 0, the highlight worked out: the DB highlight of the
* same video, else 30% of the 길이) or 처음부터 (played from 0 even in rooms set to 하이라이트부터).
*/
export type BlankPositions = 'auto' | 'start';
/**
* 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).
* 이지선다 (`kind` duel): 정답 = 제목, 설명 = 가수. 조회수 is optional: a number written there is used as is,
* an empty one is fetched by the server after upload (토픽 + MV).
*/
export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[], headerAt = 0, kind: QuizKind = 'normal'): ParsedQuizFile {
export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[], headerAt = 0, kind: QuizKind = 'normal', blank: BlankPositions = 'auto'): ParsedQuizFile {
const duel = kind === 'duel';
const at = (c: QuizColumn) => columns.indexOf(c);
const hintCols = columns.flatMap((c, i) => (c === 'hint' ? [i] : []));
@@ -181,6 +189,8 @@ export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[],
const start = parseSec(cell(r, at('start')));
const highlight = parseSec(cell(r, at('highlight')));
const own = (start !== null && start !== undefined) || (highlight !== null && highlight !== undefined);
const fromStart = !own && blank === 'start';
const length = parseSec(cell(r, at('duration')));
out.push({
line,
link,
@@ -194,10 +204,10 @@ export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[],
artistAnswers: duel ? [] : splitAnswers(cell(r, at('descAnswers'))),
hints: duel ? [] : 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,
durationSec: length ? Math.min(36000, Math.round(length)) : null,
auto: !own && !fromStart,
startSec: own ? (start ?? 0) : fromStart ? 0 : null,
highlightSec: own ? (highlight ?? null) : fromStart ? 0 : null,
views: duel ? (views ?? null) : null,
viewsAuto: null,
},
@@ -261,3 +271,55 @@ export function quizTemplateRows(kind: QuizKind = 'normal'): { rows: (string | n
},
]);
}
/** One song of 플레이리스트 가져오기 (server quizzes/playlist.ts ImportRow), as 재생목록으로 엑셀 만들기 needs it. */
export interface PlaylistSheetRow {
n: number;
source: { title: string; artist: string };
title: string;
artist: string;
durationSec: number | null;
videoId: string | null;
status: 'db' | 'video' | 'found' | 'check' | 'missing' | 'blocked';
note: string;
}
/**
* 재생목록으로 엑셀 만들기: the checked playlist as a quiz file 파일로 만들기 reads as is (일반 or 이지선다). Songs that
* would not play (재생 불가, 못 찾음, the same video again) go to a second sheet 빠진 곡 with the reason; that sheet has no
* 제목 column, so 파일로 만들기 never reads songs from it. 비고 says where each title/artist came from.
*/
export function playlistSheets(list: PlaylistSheetRow[]): { name: string; rows: (string | number | null)[][]; widths: number[] }[] {
const kept: (string | number | null)[][] = [];
const left: (string | number | null)[][] = [];
const firstOf = new Map<string, number>();
for (const r of list) {
const why =
r.status === 'blocked'
? r.note || '재생할 수 없는 영상'
: !r.videoId || r.status === 'missing'
? r.note || '유튜브에서 못 찾았어요'
: firstOf.has(r.videoId)
? `재생목록 ${firstOf.get(r.videoId)}번 곡과 같은 영상`
: null;
if (why) {
left.push([r.n, r.videoId ? `https://youtu.be/${r.videoId}` : '', r.source.title, r.source.artist, why]);
continue;
}
firstOf.set(r.videoId!, r.n);
const note =
r.status === 'db'
? 'DB 곡'
: r.status === 'check'
? r.note || '확인 필요'
: r.status === 'found'
? '유튜브 뮤직에서 찾음'
: r.note;
kept.push([kept.length + 1, `https://youtu.be/${r.videoId}`, r.title, r.artist, null, null, r.durationSec, note || null]);
}
const head = ['순번', QUIZ_COLUMN_LABEL.link, '제목', '가수', QUIZ_COLUMN_LABEL.start, QUIZ_COLUMN_LABEL.highlight, QUIZ_COLUMN_LABEL.duration, '비고'];
return [
{ name: '퀴즈', rows: [head, ...kept], widths: [6, 32, 30, 24, 10, 14, 10, 40] },
{ name: '빠진 곡', rows: [['재생목록 순번', '링크', '곡 제목(재생목록)', '채널·가수(재생목록)', '빠진 이유'], ...left], widths: [12, 32, 36, 24, 40] },
];
}

View File

@@ -281,7 +281,13 @@ function zip(files: [string, string][]): Uint8Array {
* `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');
return writeXlsxSheets([{ name: sheetName, rows, widths }]);
}
const NS = 'xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"';
const NS_R = 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"';
function sheetXml(rows: (string | number | null)[][], widths: number[]): string {
const body = rows
.map(
(r, ri) =>
@@ -298,12 +304,17 @@ export function writeXlsx(sheetName: string, rows: (string | number | null)[][],
)
.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 `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet ${NS} ${NS_R}><sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews>${cols}<sheetData>${body}</sheetData></worksheet>`;
}
/** .xlsx with several sheets (each like writeXlsx's). Sheet names are cleaned of characters Excel refuses. */
export function writeXlsxSheets(sheets: { name: string; rows: (string | number | null)[][]; widths?: number[] }[]): Uint8Array {
const names = sheets.map((sh, i) => escapeXml(sh.name.replace(/[\\/?*[\]:]/g, ' ').slice(0, 31).trim() || `시트${i + 1}`));
const ids = sheets.map((_, i) => i + 1);
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>`,
`<?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"/>${ids.map((i) => `<Override PartName="/xl/worksheets/sheet${i}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`).join('')}<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>`,
],
[
'_rels/.rels',
@@ -311,19 +322,16 @@ export function writeXlsx(sheetName: string, rows: (string | number | null)[][],
],
[
'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>`,
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><workbook ${NS} ${NS_R}><sheets>${ids.map((i) => `<sheet name="${names[i - 1]}" sheetId="${i}" r:id="rId${i}"/>`).join('')}</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>`,
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${ids.map((i) => `<Relationship Id="rId${i}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${i}.xml"/>`).join('')}<Relationship Id="rId${ids.length + 1}" 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>`,
`<?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>`,
],
...sheets.map((sh, i): [string, string] => [`xl/worksheets/sheet${i + 1}.xml`, sheetXml(sh.rows, sh.widths ?? [])]),
]);
}