diff --git a/apps/server/src/custom-quiz.test.ts b/apps/server/src/custom-quiz.test.ts index 932851d..5519af1 100644 --- a/apps/server/src/custom-quiz.test.ts +++ b/apps/server/src/custom-quiz.test.ts @@ -2,6 +2,7 @@ import { afterEach, expect, test } from 'bun:test'; import type { ServerMessage } from '@mq/shared'; import { Catalog } from './collector/catalog'; +import { cleanVideoTitle } from './quizzes/playlist'; import { Client, TEST_SUPERADMINS, api, boot, discordLogin, guest, sleep } from './test-utils'; type Msg = Extract; @@ -208,7 +209,7 @@ test('플레이리스트 가져오기: DB songs by video, cleaned YouTube titles expect(job).toMatchObject({ status: 'done', name: '내 플레이리스트', total: 4 }); const rows = job.rows as { title: string; artist: string; videoId: string | null; songId: number | null; status: string }[]; expect(rows[0]).toMatchObject({ status: 'db', songId: song, title: '좋은 날', artist: '아이유', videoId: 'goodday0001' }); - expect(rows[1]).toMatchObject({ status: 'video', title: 'LOVE DIVE', artist: 'IVE 아이브', videoId: 'lovedive001' }); + expect(rows[1]).toMatchObject({ status: 'video', title: 'LOVE DIVE', artist: 'IVE 아이브', videoId: 'lovedive001', note: '' }); expect(rows[2]).toMatchObject({ status: 'found', videoId: 'hypeboy0001' }); expect(rows[3]).toMatchObject({ status: 'missing', videoId: null }); // someone else's job is not visible @@ -269,8 +270,9 @@ test('파일로 만들기: values as written, hints by vote, never sent to 검 const q = (await api(s.base, `/api/admin/quizzes/${r.body.id}`, { cookie: sa })).body.quiz; expect(q.settings.hint).toBe('manual'); expect(q.items).toMatchObject([ - { songId: null, title: '리그 오브 레전드', artist: 'Still Here', hints: ['AOS(MOBA)'], fromFile: true }, - { songId: null, title: '원신', artist: '', hints: ['확인필요'], fromFile: true }, + // 자동: the DB song with the same video lends its highlight (as the song's own positions), still unlinked + { songId: null, title: '리그 오브 레전드', artist: 'Still Here', hints: ['AOS(MOBA)'], fromFile: true, auto: false, startSec: 0, highlightSec: 61 }, + { songId: null, title: '원신', artist: '', hints: ['확인필요'], fromFile: true, auto: true, durationSec: 200 }, ]); // 전체공개 save: file songs stay out of 검토 대기, an editor song next to them does not const saved = await api(s.base, `/api/admin/quizzes/${q.id}`, { @@ -316,3 +318,10 @@ test('파일로 만들기: values as written, hints by vote, never sent to 검 cl.close(); } }); + +test('영상 제목 정리: 가수 - 제목 / 가수 \'제목\' / 토픽은 그대로, 형식이 다르면 채널 이름을 가수로 쓰고 확인 필요로 표시', () => { + expect(cleanVideoTitle('아이유(IU) - 좋은 날 (Official MV)', 'LOEN')).toEqual({ title: '좋은 날', artist: '아이유(IU)', guessed: false }); + expect(cleanVideoTitle("IVE 아이브 'LOVE DIVE' MV", 'STARSHIP')).toEqual({ title: 'LOVE DIVE', artist: 'IVE 아이브', guessed: false }); + expect(cleanVideoTitle('Ditto', 'NewJeans - Topic')).toEqual({ title: 'Ditto', artist: 'NewJeans', guessed: false }); + expect(cleanVideoTitle('밤편지 (Official MV)', '아이유 공식')).toEqual({ title: '밤편지', artist: '아이유', guessed: true }); +}); diff --git a/apps/server/src/http/admin-quizzes.ts b/apps/server/src/http/admin-quizzes.ts index 9403c16..1a8fc7a 100644 --- a/apps/server/src/http/admin-quizzes.ts +++ b/apps/server/src/http/admin-quizzes.ts @@ -82,8 +82,17 @@ export function mountQuizAdmin(app: Hono, d: QuizAdminDeps, h: { actor: (c: if (limits.maxSongs && p.data.items.length > limits.maxSongs) return c.json({ error: `퀴즈 하나에는 곡을 ${limits.maxSongs}곡까지 넣을 수 있어요.` }, 400); const id = d.quizzes.create(h.actor(c), p.data.name, limits, Date.now(), p.data.kind); if (typeof id === 'string') return c.json({ error: id }, 400); - // 이지선다: a 조회수 written in the file is used as is, the others are fetched (토픽 + MV) after saving - const items = p.data.items.map((it) => ({ ...it, id: undefined, songId: null, fromFile: true, viewsAuto: null, ...(duel ? {} : { views: null }) })); + // 자동 (시작·하이라이트 칸이 빈 곡): the item stays unlinked (values as written), so the DB song with this very video + // lends its highlight (stored as the song's own positions) and its length (for the 30% rule when there is no highlight) + const sameVideo = d.db.query<{ highlight_sec: number | null; duration_sec: number | null }, [string]>( + "SELECT highlight_sec, duration_sec FROM songs WHERE youtube_id = ? AND youtube_status = 'matched' AND deleted_at IS NULL ORDER BY highlight_sec IS NULL, id LIMIT 1", + ); + const items = p.data.items.map((it) => { + const s = it.auto ? sameVideo.get(it.videoId) : null; + const pos = s?.highlight_sec != null ? { auto: false, startSec: 0, highlightSec: s.highlight_sec } : {}; + // 이지선다: a 조회수 written in the file is used as is, the others are fetched (토픽 + MV) after saving + return { ...it, ...pos, durationSec: it.durationSec ?? s?.duration_sec ?? null, id: undefined, songId: null, fromFile: true, viewsAuto: null, ...(duel ? {} : { views: null }) }; + }); // songs with their own hints: hints come by vote unless the maker changes it in 설정 const settings = { ...DEFAULT_QUIZ_SETTINGS, ...(items.some((it) => it.hints.length) ? { hint: 'manual' as const } : {}) }; const saved = d.quizzes.save(id, { name: p.data.name, description: '', visibility: 'private', settings, items }, limits); diff --git a/apps/server/src/quizzes/playlist.ts b/apps/server/src/quizzes/playlist.ts index 2db27cb..f27483d 100644 --- a/apps/server/src/quizzes/playlist.ts +++ b/apps/server/src/quizzes/playlist.ts @@ -46,15 +46,18 @@ export async function loadPlaylist(ll: Lavalink, url: string, fetchImpl: typeof const NOISE = /\s*[([【][^)\]】]*(official|m\/?v|music video|lyric|audio|visuali[sz]er|performance|teaser|live clip|가사|뮤직비디오)[^)\]】]*[)\]】]\s*/gi; -/** "아이유(IU) - 좋은 날 (Official MV)" → 좋은 날 / 아이유(IU); "IVE 아이브 'LOVE DIVE' MV" → LOVE DIVE / IVE 아이브; Topic channels are the artist. */ -export function cleanVideoTitle(title: string, channel: string): { title: string; artist: string } { +/** + * "아이유(IU) - 좋은 날 (Official MV)" → 좋은 날 / 아이유(IU); "IVE 아이브 'LOVE DIVE' MV" → LOVE DIVE / IVE 아이브; Topic channels are the artist. + * `guessed`: the title had neither form, so the whole title is the song and the channel name the artist (worth a look). + */ +export function cleanVideoTitle(title: string, channel: string): { title: string; artist: string; guessed: boolean } { const t = title.replace(NOISE, ' ').replace(/\s+(M\/?V|MV|Official Video)$/i, '').replace(/\s+/g, ' ').trim(); - if (/ - Topic$/.test(channel)) return { title: t, artist: channel.replace(/ - Topic$/, '') }; + if (/ - Topic$/.test(channel)) return { title: t, artist: channel.replace(/ - Topic$/, ''), guessed: false }; const dash = /^(.+?)\s+[-–—]\s+(.+)$/.exec(t); - if (dash) return { artist: dash[1]!.trim(), title: dash[2]!.trim() }; + if (dash) return { artist: dash[1]!.trim(), title: dash[2]!.trim(), guessed: false }; const quoted = /^(.+?)\s*['"‘“『「](.+?)['"’”』」]/.exec(t); - if (quoted) return { artist: quoted[1]!.trim(), title: quoted[2]!.trim() }; - return { title: t, artist: channel.replace(/(Official|VEVO|공식)$/i, '').trim() || channel }; + if (quoted) return { artist: quoted[1]!.trim(), title: quoted[2]!.trim(), guessed: false }; + return { title: t, artist: channel.replace(/(Official|VEVO|공식)$/i, '').trim() || channel, guessed: true }; } export type ImportStatus = 'db' | 'video' | 'found' | 'check' | 'missing' | 'blocked'; @@ -128,13 +131,13 @@ async function runImport(d: ImportDeps, job: ImportJob, tracks: LavalinkTrack[]) for (const [i, t] of tracks.entries()) { const dur = t.length ? Math.round(t.length / 1000) : null; const yt = t.sourceName === 'youtube'; - const named = yt ? cleanVideoTitle(t.title, t.author) : { title: t.title, artist: t.author }; + const named = yt ? cleanVideoTitle(t.title, t.author) : { title: t.title, artist: t.author, guessed: false }; const row: ImportRow = { n: i + 1, source: { title: t.title, artist: t.author }, title: named.title, artist: named.artist, durationSec: dur, videoId: null, songId: null, status: 'missing', note: '' }; const dbSong = (yt ? byVideo.get(t.identifier) : null) ?? byKey.get(songMatchKey(named.title, named.artist)); if (yt) { row.videoId = t.identifier; if (dbSong) Object.assign(row, { songId: dbSong.id, title: dbSong.title, artist: dbSong.artist, status: 'db', note: '서버 DB 곡 (플레이리스트 영상 사용)' }); - else row.status = 'video'; + else Object.assign(row, { status: 'video', note: named.guessed ? '제목·가수 확인 필요 (영상 제목 형식이 달라 채널 이름을 가수로 씀)' : '' }); const e = await d.embed(t.identifier); if (e.state !== 'ok') Object.assign(row, { status: 'blocked', note: e.state === 'noembed' ? '다른 사이트 재생이 막힌 영상' : e.state === 'dead' ? '없는 영상' : '영상 확인 실패' }); } else if (dbSong?.youtube_id && dbSong.youtube_status === 'matched') { diff --git a/apps/web/src/pages/admin/PlaylistSheet.tsx b/apps/web/src/pages/admin/PlaylistSheet.tsx new file mode 100644 index 0000000..05b1c75 --- /dev/null +++ b/apps/web/src/pages/admin/PlaylistSheet.tsx @@ -0,0 +1,126 @@ +/** + * 재생목록으로 엑셀 만들기 (관리자 → 퀴즈): a playlist address → the server checks every song (플레이리스트 가져오기의 같은 + * 작업: 서버 DB 곡, 영상 제목 정리, 스포티파이는 유튜브 뮤직에서 찾기, 다른 사이트 재생 확인) → a quiz file to fill in + * 시작·하이라이트 and upload with 파일로 만들기 (일반 or 이지선다). Songs that would not play go to the sheet 빠진 곡. + */ +import { useEffect, useMemo, useState } from 'react'; +import { playlistSheets, writeXlsxSheets, type PlaylistSheetRow } from '@mq/shared/lite'; +import { apiCall } from '../../net/api'; +import { toast } from '../../store/toast'; +import { download } from './QuizFile'; + +interface ImportJob { + id: string; + name: string; + status: 'running' | 'done' | 'failed'; + done: number; + total: number; + rows: PlaylistSheetRow[]; + error: string | null; +} + +export function PlaylistSheet({ onClose }: { onClose: () => void }) { + const [url, setUrl] = useState(''); + const [job, setJob] = useState(null); + const [busy, setBusy] = useState(false); + useEffect(() => { + if (!job || job.status !== 'running') return; + const t = setTimeout(() => { + apiCall<{ job: ImportJob }>('GET', `/api/admin/quizzes/pick/playlist/${job.id}`) + .then((r) => setJob(r.job)) + .catch((e: Error) => toast(e.message, 'error')); + }, 1000); + return () => clearTimeout(t); + }, [job]); + const begin = async () => { + setBusy(true); + try { + setJob((await apiCall<{ job: ImportJob }>('POST', '/api/admin/quizzes/pick/playlist', { url: url.trim() })).job); + } catch (e) { + toast((e as Error).message, 'error'); + } finally { + setBusy(false); + } + }; + const sheets = useMemo(() => (job?.status === 'done' ? playlistSheets(job.rows) : null), [job]); + const kept = sheets ? sheets[0]!.rows.slice(1) : []; + const left = sheets ? sheets[1]!.rows.slice(1) : []; + const toCheck = kept.filter((r) => String(r[7] ?? '').includes('확인 필요')).length; + const fileName = job?.name.trim() || '재생목록 퀴즈'; + return ( +
+
+ 🔗 재생목록으로 엑셀 만들기 + +
+
{ + e.preventDefault(); + if (url.trim()) void begin(); + }} + > + setUrl(e.target.value)} placeholder="유튜브·유튜브 뮤직·스포티파이 재생목록 주소" aria-label="재생목록 주소" /> + +
+

+ 곡마다 서버 노래 DB, 영상 제목, 다른 사이트 재생 여부를 확인해서 순번 · 유튜브 영상 링크 · 제목 · 가수 · 시작(초) · 하이라이트(초) · 길이(초) · 비고 엑셀을 + 만들어요. 시작·하이라이트를 채우고(비워 두면 올릴 때 자동 / 처음부터 중에 골라요) 파일로 만들기에 그대로 올리면 돼요. 일반 퀴즈는 제목이 정답, 가수가 정답 공개 때 + 같이 보이는 설명이 되고, 이지선다는 조회수를 서버가 불러와요. 재생이 막혔거나 없는 영상, 같은 영상은 빠진 곡 시트로 옮겨요. +

+ {job && ( +
+ + {job.name || '재생목록'} · {job.status === 'running' ? `검토 중 ${job.done}/${job.total}곡` : job.status === 'failed' ? `실패: ${job.error}` : `${job.total}곡 검토 끝`} + {sheets && ( + + {' '} + · 엑셀에 넣을 곡 {kept.length} + {toCheck > 0 && ` (확인 필요 ${toCheck})`} · 빠진 곡 {left.length} + + )} + + +
+ )} + {sheets && ( + <> + {left.length > 0 && ( +
+ + + + + + + + + + {left.map((r) => ( + + + + + + ))} + +
순번곡 (재생목록)빠진 이유
{r[0]} + {r[3]} - {r[2]} + {r[4]}
+
+ )} +
+ + {toCheck > 0 && 비고에 "확인 필요"라고 적힌 곡은 영상을 보고 제목·가수를 고쳐 주세요.} +
+ + )} +
+ ); +} diff --git a/apps/web/src/pages/admin/QuizFile.tsx b/apps/web/src/pages/admin/QuizFile.tsx index 301bd03..9bb19cf 100644 --- a/apps/web/src/pages/admin/QuizFile.tsx +++ b/apps/web/src/pages/admin/QuizFile.tsx @@ -16,6 +16,7 @@ import { quizToRows, readSheetFile, writeXlsx, + type BlankPositions, type QuizColumn, type QuizItem, type QuizKind, @@ -28,7 +29,7 @@ import { Seg } from '../../components/RoomSettings'; const MAX_BYTES = 20 * 1024 * 1024; const colLabel = (c: QuizColumn, kind: QuizKind) => (kind === 'duel' ? (DUEL_COLUMN_LABEL[c] ?? QUIZ_COLUMN_LABEL[c]) : QUIZ_COLUMN_LABEL[c]); -function download(name: string, bytes: Uint8Array) { +export function download(name: string, bytes: Uint8Array) { const url = URL.createObjectURL(new Blob([bytes as Uint8Array], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })); const a = document.createElement('a'); a.href = url; @@ -75,6 +76,7 @@ export function QuizFileImport({ const [busy, setBusy] = useState(false); const [confirmReplace, setConfirmReplace] = useState(false); const [chosenKind, setChosenKind] = useState(fixedKind ?? 'normal'); + const [blank, setBlank] = useState('auto'); const kind = fixedKind ?? chosenKind; const pickSheet = (sheets: Sheet[], i: number) => { @@ -104,7 +106,9 @@ export function QuizFileImport({ const sheet = file?.sheets[sheetIdx]; const header = sheet?.rows[headerAt] ?? []; - const parsed = useMemo(() => (sheet ? parseQuizRows(sheet.rows, columns, headerAt, kind) : null), [sheet, columns, headerAt, kind]); + const parsed = useMemo(() => (sheet ? parseQuizRows(sheet.rows, columns, headerAt, kind, blank) : null), [sheet, columns, headerAt, kind, blank]); + // songs whose 시작·하이라이트 cells are both empty (자동 or 처음부터 below) + const blankCount = useMemo(() => (sheet ? parseQuizRows(sheet.rows, columns, headerAt, kind).items.filter((it) => it.auto).length : 0), [sheet, columns, headerAt, kind]); const missing = (['link', 'answer'] as const).filter((c) => !columns.includes(c)); const duel = kind === 'duel'; const bad = parsed?.rows.filter((r) => r.problem) ?? []; @@ -232,6 +236,26 @@ export function QuizFileImport({ {bad.length > 0 && · 빠지는 줄 {bad.length}개} {mode === 'into' && items.length > appendable.length && · 이미 목록에 있는 영상 {items.length - appendable.length}곡} + {blankCount > 0 && ( +
+ 시작·하이라이트가 빈 곡 {blankCount}곡 + + + {blank === 'auto' + ? `방이 '하이라이트부터'면 ${mode === 'create' ? '서버 노래 DB에 같은 영상의 하이라이트가 있으면 그 위치, 없으면 ' : ''}곡 길이의 30% 지점부터 들려줘요(길이를 모르면 처음부터). 적힌 시작·하이라이트는 그대로 써요.` + : '하이라이트 없이 언제나 영상 처음부터 들려줘요. 적힌 시작·하이라이트는 그대로 써요.'} + +
+ )} {bad.length > 0 && (
diff --git a/apps/web/src/pages/admin/QuizzesPage.tsx b/apps/web/src/pages/admin/QuizzesPage.tsx index 77fe1d7..1c55dcd 100644 --- a/apps/web/src/pages/admin/QuizzesPage.tsx +++ b/apps/web/src/pages/admin/QuizzesPage.tsx @@ -33,6 +33,7 @@ import { YtPreview } from './SongsPage'; import { PositionEditor } from './PositionEditor'; import { useReviewCount } from './reviewCount'; import { QuizFileImport, exportQuiz } from './QuizFile'; +import { PlaylistSheet } from './PlaylistSheet'; const mmss = (s: number | null | undefined) => (s == null ? '-' : `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, '0')}`); const VIS_LABEL: Record = { private: '비공개', partial: '일부공개', public: '전체공개' }; @@ -46,6 +47,7 @@ export function QuizzesPage() { const [name, setName] = useState(''); const [adding, setAdding] = useState(false); const [fromFile, setFromFile] = useState(false); + const [toSheet, setToSheet] = useState(false); const nav = useNavigate(); const load = useCallback(() => { apiCall<{ quizzes: QuizSummary[] }>('GET', `/api/admin/quizzes${all ? '?all=1' : ''}`) @@ -91,6 +93,7 @@ export function QuizzesPage() { }} /> )} + {toSheet && setToSheet(false)} />}
{list?.map((q) => ( @@ -138,6 +141,12 @@ export function QuizzesPage() { 엑셀(.xlsx)·CSV · 일반 / 이지선다 )} + {!toSheet && ( + + )}
{list && list.length === 0 && !adding &&

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

} diff --git a/docs/10-roadmap.md b/docs/10-roadmap.md index 0658aca..b409692 100644 --- a/docs/10-roadmap.md +++ b/docs/10-roadmap.md @@ -35,3 +35,4 @@ - 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 통과 - 2026-10-23 이지선다(B단계): 모드 "이지선다"와 이지선다 퀴즈(파일의 조회수, `kind`/`views` 013 마이그레이션). 서버 `game/duel.ts`(A/B 카드, 고르기·바꾸기, 시간 끝나면 조회수 공개, 1점·역배 2점, 매번 새 두 곡/연속), 화면 `DuelScreen.tsx`(카드마다 숨은 플레이어 `net/duel-player.ts`로 각자 듣고 이어 듣기, 고른 사람 프로필), 방 설정(제한 시간·진행 방식·재생위치·문제 수), 관리자 파일로 만들기 종류 선택·조회수 편집·내보내기. 테스트 146개, e2e duel(실제 유튜브 이어 듣기 포함)·game·quiz·admin·rooms·login·a11y 통과 - 2026-11-03 이지선다 조회수 자동: 빈 양식에서 조회수 열을 빼고, 올린 뒤 서버가 곡마다 토픽 + MV 조회수를 불러와 더함(유튜브 뮤직 노래↔동영상 짝, 쿠키 필요 · 조회수는 로그인 없이). 편집기에 곡마다 토픽·MV 조회수, 비고(한쪽만 있는 곡·직접 넣은 값·실패 이유), 불러오는 중 표시, 조회수 다시 불러오기(전체/곡). 파일에 적힌 숫자는 그대로 씀. 014 마이그레이션, 단위·API 테스트, e2e duel 단계 추가 +- 2026-11-03 재생목록으로 엑셀 만들기: 관리자 → 퀴즈 카드, 플레이리스트 검토 결과를 파일로 만들기용 엑셀(퀴즈 + 빠진 곡 시트, 비고·길이)로 받음. 파일로 만들기에 "시작·하이라이트가 빈 곡: 자동 / 처음부터", 길이(초) 열, 자동이면 같은 영상의 DB 하이라이트·길이를 씀. 영상 제목 형식이 달라 채널 이름을 가수로 쓴 곡은 "제목·가수 확인 필요". 단위·API 테스트, e2e quiz 단계 추가 (12 문서 제작된 퀴즈 13·14) diff --git a/docs/12-decisions.md b/docs/12-decisions.md index c09f42f..38bbf3b 100644 --- a/docs/12-decisions.md +++ b/docs/12-decisions.md @@ -183,6 +183,8 @@ 10. 플레이리스트 가져오기: 유튜브·유튜브 뮤직·스포티파이 주소를 .6 Lavalink(`LAVALINK_URL`·`LAVALINK_PW`)로 읽는다(스포티파이 키로는 플레이리스트를 못 읽음). 서버 DB에 있는 곡은 그 곡, 유튜브는 그 영상(제목의 Official MV 등 정리), 스포티파이는 유튜브 뮤직에서 원곡 찾기와 같은 기준으로 찾고 애매하면 "확인 필요". 결과에서 고른 곡만 뒤에 추가하거나 목록을 바꾼다 11. 검토 대기(관리자 → 검토 대기): 전체공개로 저장하면 서버 DB에 없는 곡과 DB와 영상·제목·가수·직접 정한 하이라이트가 다른 곡이 올라간다. 다른 값은 항목마다 "DB 유지 / 퀴즈 값"을 고르고, 없는 곡은 연도·장르·난이도를 채워 추가한다(퀴즈 곡이 그 DB 곡과 연결됨). 복수정답은 DB 별칭에 들어가고, 한 번 정한 값(항목+값)은 다시 묻지 않는다 12. 플레이 통계: 문제마다 힌트(시간/투표), 정답이 아닌 입력 수와 사람 수, 다시듣기 수, 제작된 퀴즈·곡을 함께 저장(DB에 없는 퀴즈 곡도 퀴즈 통계에 들어감). 관리자 통계는 곡별·퀴즈별 탭. 난이도 제안은 힌트도 본다(80% 넘게 8초 안에 힌트 30% 미만 → 쉽게, 30% 이하 또는 50% 이하+힌트 60% 이상 → 어렵게)이고 검토 대기 → 난이도 조정에 근거와 함께 나온다. "반영 안 함"은 5번 더 나온 뒤 다시 계산 +13. **재생목록으로 엑셀 만들기 (2026-11-03, 사용자 답변)**: 관리자 → 퀴즈 목록의 카드. 플레이리스트 가져오기와 같은 검토(서버 DB 곡, 영상 제목 정리, 스포티파이는 유튜브 뮤직 검색, 다른 사이트 재생 확인)를 거쳐 `순번 | 유튜브 영상 링크 | 제목 | 가수 | 시작(초) | 하이라이트(초) | 길이(초) | 비고` 엑셀을 브라우저가 만든다(`playlistSheets`, `writeXlsxSheets`). 파일로 만들기가 열 이름으로 바로 읽고, 일반이면 제목=정답·가수=설명, 이지선다면 조회수는 서버가 불러온다(조회수 열은 넣지 않음 — 빈 열이 있으면 이지선다로 자동 선택되므로). 재생 막힘·없는 영상·못 찾은 곡·같은 영상은 둘째 시트 "빠진 곡"(제목 열이 없어 곡으로 읽히지 않음)에 이유와 함께. 비고: DB 곡 / 제목·가수 확인 필요(제목에 `가수 - 제목`·`가수 '제목'` 형식이 없어 채널 이름을 가수로 씀) / 확인 필요(스포티파이 애매한 검색) / 유튜브 뮤직에서 찾음. 곡마다 유튜브 뮤직에 다시 묻지는 않는다(쿠키·429) +14. **시작·하이라이트가 빈 곡 (2026-11-03, 사용자 답변)**: 파일로 만들기·파일에서 가져오기에서 고른다. 적힌 값은 언제나 그대로. 자동 = 처음 0초, 하이라이트는 서버 DB에 같은 영상이 있으면 그 하이라이트(파일 곡은 DB와 연결하지 않으므로 만들 때 곡의 직접 위치 0초/DB 하이라이트로 적어 둠, 파일로 만들기만), 없으면 곡 길이(길이 열·DB 길이) 30%, 길이를 모르면 처음부터. 처음부터 = 시작 0·하이라이트 0으로 적어 방이 "하이라이트부터"여도 영상 처음부터 ## 이지선다 (2026-10-22~23, 사용자 답변) 1. 조회수가 더 높은 곡을 고르는 모드. 곡 목록은 사용자가 파일(.xlsx·.csv: 영상 링크·제목·가수, 조회수는 선택)로 올린다. 조회수는 아래 7번(2026-11-03)처럼 서버가 불러온다. 조회수 칸에 숫자(1,234,567·123만·1.2억도 읽음)가 적혀 있으면 그 숫자를 그대로 쓰고, 읽을 수 없는 값이 적힌 줄은 빠진다 diff --git a/e2e/duel.e2e.ts b/e2e/duel.e2e.ts index 0cedfb5..52af9ca 100644 --- a/e2e/duel.e2e.ts +++ b/e2e/duel.e2e.ts @@ -109,7 +109,7 @@ try { await step('파일로 만들기: 조회수 열이 있는 CSV → 이지선다로 골라짐, 읽을 수 없는 조회수 줄은 빠짐 → 4곡으로 만들기 → 내보내기', async () => { const csv = ['유튜브 링크,제목,가수,조회수', 'https://youtu.be/duelvid0001,노래1,가수1,1.2억', 'duelvid0002,노래2,가수2,"34,000,000"', 'https://youtu.be/duelvid0003,노래3,가수3,500만', 'https://youtu.be/duelvid0004,노래4,가수4,12345회', 'https://youtu.be/duelvid0005,노래5,가수5,많음'].join('\n'); await host.goto(`${ORIGIN}/admin/quizzes`); - await host.getByRole('button', { name: /파일로 만들기/ }).click(); + await host.getByRole('button', { name: /^파일로 만들기/ }).click(); await host.getByLabel('퀴즈 파일').setInputFiles({ name: '조회수 대결.csv', mimeType: 'text/csv', buffer: Buffer.from(csv) }); await host.getByText('빠지는 줄 1개').waitFor(); expect((await host.getByRole('radio', { name: /이지선다/ }).getAttribute('aria-checked')) === 'true', '조회수 열이 있는데 이지선다로 골라지지 않음'); @@ -132,7 +132,7 @@ try { await step('이지선다 양식(조회수 열 없음) → 자동: 올린 뒤 토픽 + MV 조회수를 불러오고, 토픽만 있는 곡은 비고로 표시', async () => { await host.goto(`${ORIGIN}/admin/quizzes`); - await host.getByRole('button', { name: /파일로 만들기/ }).click(); + await host.getByRole('button', { name: /^파일로 만들기/ }).click(); await host.getByRole('radio', { name: /이지선다/ }).click(); const [dl] = await Promise.all([host.waitForEvent('download'), host.getByRole('button', { name: /빈 양식 받기/ }).click()]); const template = (await readXlsx(new Uint8Array(await Bun.file((await dl.path())!).arrayBuffer())))[0]!.rows; diff --git a/e2e/quiz.e2e.ts b/e2e/quiz.e2e.ts index 260e4dc..b01c5f5 100644 --- a/e2e/quiz.e2e.ts +++ b/e2e/quiz.e2e.ts @@ -3,6 +3,7 @@ * - 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 + * - 재생목록으로 엑셀 만들기 → the file goes back into 파일로 만들기 (빈 시작·하이라이트: 자동 / 처음부터) * Run: bun run build && bun e2e/quiz.e2e.ts (needs /usr/bin/google-chrome) */ import { chromium, type Browser, type BrowserContext } from 'playwright-core'; @@ -28,7 +29,23 @@ const app = startServer({ stopWaitMs: 200, discordExchange: async (code) => ({ id: code, username: 'u', global_name: '사금향', avatar: null }), checkEmbed: async () => ({ state: 'ok', author: 'IU - Topic', title: 'Official Audio' }), - quizAdmin: { searchYoutube: async () => [], lavalink: null }, + quizAdmin: { + searchYoutube: async () => [], + lavalink: { url: 'http://lavalink.e2e', password: 'x' }, + importDelayMs: 0, + lavalinkFetch: (async () => + Response.json({ + loadType: 'playlist', + data: { + info: { name: '내 재생목록' }, + tracks: [ + { info: { identifier: 'jeqdYqsrsA0', title: '아이유 - 좋은 날 (Official MV)', author: 'LOEN', length: 236000, sourceName: 'youtube' } }, + { info: { identifier: 'iIIjS6yDMQo', title: '밤편지 (Official MV)', author: '아이유 공식', length: 260000, sourceName: 'youtube' } }, + { info: { identifier: 'jeqdYqsrsA0', title: '아이유 - 좋은 날', author: 'LOEN', length: 236000, sourceName: 'youtube' } }, + ], + }, + })) as unknown as typeof fetch, + }, }); const db = app.db; { @@ -134,7 +151,7 @@ try { 'xl/worksheets/sheet2.xml': `${cell('A1', '메모')}`, }); await p.goto(`${ORIGIN}/admin/quizzes`); - await p.getByRole('button', { name: /파일로 만들기/ }).click(); + 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', '곡이 있는 시트를 먼저 고르지 않음'); @@ -180,6 +197,66 @@ try { await p.getByText('저장됨').waitFor(); expect(db.query<{ n: number }, [number]>('SELECT COUNT(*) n FROM custom_quiz_items WHERE quiz_id = ?').get(quizId)!.n === 4, '가져온 곡 저장'); }); + await step('재생목록으로 엑셀 만들기 → 검토(DB 곡·확인 필요·같은 영상은 빠진 곡) → 받은 엑셀을 파일로 만들기: 자동은 DB 하이라이트, 처음부터는 0초', async () => { + await p.goto(`${ORIGIN}/admin/quizzes`); + await p.getByRole('button', { name: /재생목록으로 엑셀 만들기/ }).click(); + await p.getByLabel('재생목록 주소').fill('https://www.youtube.com/playlist?list=PLe2e'); + await p.getByRole('button', { name: '검토 시작' }).click(); + const get = p.getByRole('button', { name: /엑셀 받기/ }); + await get.waitFor(); + expect((await get.innerText()).includes('2곡'), `받기 버튼: ${await get.innerText()}`); + await p.getByText('재생목록 1번 곡과 같은 영상').waitFor(); + await p.screenshot({ path: join(SHOTS, 'quiz-playlist-sheet.png'), fullPage: true }); + const [dl] = await Promise.all([p.waitForEvent('download'), get.click()]); + expect(dl.suggestedFilename() === '내 재생목록.xlsx', `파일 이름: ${dl.suggestedFilename()}`); + const bytes = new Uint8Array(await Bun.file((await dl.path())!).arrayBuffer()); + const book = await readXlsx(bytes); + expect(book.map((x) => x.name).join() === '퀴즈,빠진 곡', `시트: ${book.map((x) => x.name)}`); + expect( + JSON.stringify(book[0]!.rows) === + JSON.stringify([ + ['순번', '유튜브 영상 링크', '제목', '가수', '시작(초)', '하이라이트(초)', '길이(초)', '비고'], + ['1', 'https://youtu.be/jeqdYqsrsA0', '좋은 날', '아이유', '', '', '236', 'DB 곡'], + ['2', 'https://youtu.be/iIIjS6yDMQo', '밤편지', '아이유', '', '', '260', '제목·가수 확인 필요 (영상 제목 형식이 달라 채널 이름을 가수로 씀)'], + ]), + `엑셀 내용: ${JSON.stringify(book[0]!.rows)}`, + ); + const upload = async (blank: '자동' | '처음부터', name: string) => { + await p.goto(`${ORIGIN}/admin/quizzes`); + await p.getByRole('button', { name: /^파일로 만들기/ }).click(); + await p.getByLabel('퀴즈 파일').setInputFiles({ name: '내 재생목록.xlsx', mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', buffer: Buffer.from(bytes) }); + await p.getByText('시작·하이라이트가 빈 곡 2곡').waitFor(); + if (blank === '처음부터') { + await p.getByRole('radio', { name: /처음부터 재생/ }).click(); + await p.screenshot({ path: join(SHOTS, 'quiz-file-blank-positions.png'), fullPage: true }); + } + await p.getByLabel('퀴즈 이름').fill(name); + await p.getByRole('button', { name: '2곡으로 만들기' }).click(); + await p.waitForURL(/\/admin\/quizzes\/\d+$/); + const id = Number(new URL(p.url()).pathname.split('/').pop()); + return db.query<{ title: string; auto: number; start_sec: number | null; highlight_sec: number | null; duration_sec: number | null }, [number]>( + 'SELECT title, auto, start_sec, highlight_sec, duration_sec FROM custom_quiz_items WHERE quiz_id = ? ORDER BY pos', + ).all(id); + }; + const auto = await upload('자동', '재생목록 자동'); + expect( + JSON.stringify(auto) === + JSON.stringify([ + { title: '좋은 날', auto: 0, start_sec: 0, highlight_sec: 95, duration_sec: 236 }, + { title: '밤편지', auto: 1, start_sec: null, highlight_sec: null, duration_sec: 260 }, + ]), + `자동: ${JSON.stringify(auto)}`, + ); + const fromStart = await upload('처음부터', '재생목록 처음부터'); + expect( + JSON.stringify(fromStart) === + JSON.stringify([ + { title: '좋은 날', auto: 0, start_sec: 0, highlight_sec: 0, duration_sec: 236 }, + { title: '밤편지', auto: 0, start_sec: 0, highlight_sec: 0, duration_sec: 260 }, + ]), + `처음부터: ${JSON.stringify(fromStart)}`, + ); + }); expect(errors.length === 0, `페이지 오류: ${errors.join(' | ')}`); } catch (e) { console.log(e instanceof Error ? e.message.slice(0, 400) : e); diff --git a/packages/shared/src/quiz-file.test.ts b/packages/shared/src/quiz-file.test.ts index b9c7348..d42084b 100644 --- a/packages/shared/src/quiz-file.test.ts +++ b/packages/shared/src/quiz-file.test.ts @@ -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 & { 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], + ]); +}); diff --git a/packages/shared/src/quiz-file.ts b/packages/shared/src/quiz-file.ts index 235f295..fa6cd32 100644 --- a/packages/shared/src/quiz-file.ts +++ b/packages/shared/src/quiz-file.ts @@ -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 = { link: '유튜브 영상 링크', @@ -17,6 +17,7 @@ export const QUIZ_COLUMN_LABEL: Record = { order: '순번', start: '시작(초)', highlight: '하이라이트(초)', + duration: '길이(초)', views: '조회수', }; @@ -25,8 +26,8 @@ export const DUEL_COLUMN_LABEL: Partial> = { answer: /** The columns each kind of quiz file uses, in the order the column pickers list them. */ export const QUIZ_FILE_COLUMNS: Record = { - 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(); + 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] }, + ]; +} diff --git a/packages/shared/src/sheet.ts b/packages/shared/src/sheet.ts index a3e2fac..5833056 100644 --- a/packages/shared/src/sheet.ts +++ b/packages/shared/src/sheet.ts @@ -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 ? `${widths.map((w, i) => `
`).join('')}` : ''; - const ns = 'xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"'; - const nsR = 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"'; + return `${cols}${body}`; +} + +/** .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', - ``, + `${ids.map((i) => ``).join('')}`, ], [ '_rels/.rels', @@ -311,19 +322,16 @@ export function writeXlsx(sheetName: string, rows: (string | number | null)[][], ], [ 'xl/workbook.xml', - ``, + `${ids.map((i) => ``).join('')}`, ], [ 'xl/_rels/workbook.xml.rels', - ``, + `${ids.map((i) => ``).join('')}`, ], [ 'xl/styles.xml', - ``, - ], - [ - 'xl/worksheets/sheet1.xml', - `${cols}${body}`, + ``, ], + ...sheets.map((sh, i): [string, string] => [`xl/worksheets/sheet${i + 1}.xml`, sheetXml(sh.rows, sh.widths ?? [])]), ]); }