엑셀 양식 2단계: 일반 퀴즈 파일을 제목·가수·정답·가수 정답으로 나눔(정답은 ;로 여러 개, 제목·가수는 늘 정답, 내보내기는 제목·가수를 정답 칸 맨 앞에), 길이·비고 열. 예전 양식(정답=제목·설명·다른 정답)은 '제목' 열이 없으면 그대로 읽음. 파일 제목도 괄호·feat.·버전 표시를 지우고 괄호 안 다른 이름은 정답으로. 정답·가수 정답 칸이 빈 곡은 서버가 채움(POST /api/admin/quizzes/answers — 제목 정리 별칭 + 같은 DB 곡 별칭, answers/index.ts). 재생목록으로 엑셀 만들기: 일반 퀴즈용(정답·가수 정답·힌트)과 이지선다용(빈 조회수 열 → 파일로 만들기가 이지선다로 고름) 두 양식, 플레이리스트 가져오기 결과에 정리된 제목과 정답. 단위·API 테스트, e2e quiz(두 양식 받기)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
52
apps/server/src/answers/index.ts
Normal file
52
apps/server/src/answers/index.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* 정답 자동 생성 (docs/13): for a song's title and artist, the answers people may type besides the names shown.
|
||||
* - the title without brackets / feat. / version marks (cleanTitle) and the other names that were in brackets
|
||||
* - the aliases the server DB already has for that song and its artists
|
||||
* The names shown (제목·가수) always count on their own, so they are never listed again.
|
||||
*/
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { cleanTitle } from '@mq/shared';
|
||||
|
||||
export interface SongAnswers {
|
||||
/** The title to show (cleaned). */
|
||||
title: string;
|
||||
titleAnswers: string[];
|
||||
artistAnswers: string[];
|
||||
}
|
||||
|
||||
const MAX = 30;
|
||||
|
||||
function uniq(list: string[], except: string): string[] {
|
||||
const seen = new Set([except.trim().toLowerCase()]);
|
||||
const out: string[] = [];
|
||||
for (const raw of list) {
|
||||
const a = raw.replace(/\s+/g, ' ').trim().slice(0, 200);
|
||||
const k = a.toLowerCase();
|
||||
if (!a || seen.has(k)) continue;
|
||||
seen.add(k);
|
||||
out.push(a);
|
||||
}
|
||||
return out.slice(0, MAX);
|
||||
}
|
||||
|
||||
/** DB aliases of a song (its own and its artists'). */
|
||||
export function dbAliases(db: Database, songId: number): { title: string[]; artist: string[] } {
|
||||
const col = (sql: string) => db.query<{ v: string }, [number]>(sql).all(songId).map((r) => r.v);
|
||||
return {
|
||||
title: col("SELECT alias v FROM song_aliases WHERE song_id = ? AND part = 'title'"),
|
||||
artist: [
|
||||
...col("SELECT alias v FROM song_aliases WHERE song_id = ? AND part = 'artist'"),
|
||||
...col('SELECT x.alias v FROM song_artists sa JOIN artist_aliases x ON x.artist_id = sa.artist_id WHERE sa.song_id = ?'),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export function songAnswers(db: Database | null, s: { title: string; artist: string; songId?: number | null }): SongAnswers {
|
||||
const clean = cleanTitle(s.title);
|
||||
const fromDb = db && s.songId ? dbAliases(db, s.songId) : { title: [], artist: [] };
|
||||
return {
|
||||
title: clean.title,
|
||||
titleAnswers: uniq([...clean.aliases, ...fromDb.title], clean.title),
|
||||
artistAnswers: uniq(fromDb.artist, s.artist),
|
||||
};
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { Client, TEST_SUPERADMINS, api, boot, discordLogin, guest, sleep } from
|
||||
|
||||
type Msg<T extends ServerMessage['t']> = Extract<ServerMessage, { t: T }>;
|
||||
const TIMING = { countdownMs: 40, revealMs: 80, resumeLeadMs: 30, clipGraceMs: 150, lateMs: 150, tickMs: 20 };
|
||||
const addAliases = (song: number) => s.db.query("INSERT INTO song_aliases (song_id, part, alias) VALUES (?, 'title', 'Good Day'), (?, 'artist', 'IU')").run(song, song);
|
||||
const fakeDiscord = async (code: string) => ({ id: code, username: 'u', global_name: `회원${code.slice(-2)}`, avatar: null });
|
||||
|
||||
let s: ReturnType<typeof boot>;
|
||||
@@ -198,6 +199,7 @@ test('a quiz game plays every song in order from its own 처음 position and acc
|
||||
|
||||
test('플레이리스트 가져오기: DB songs by video, cleaned YouTube titles, Spotify tracks found on YouTube Music, misses marked', async () => {
|
||||
const song = start();
|
||||
addAliases(song);
|
||||
const sa = await adminCookie(TEST_SUPERADMINS[0]);
|
||||
const r = await api(s.base, '/api/admin/quizzes/pick/playlist', { method: 'POST', cookie: sa, body: JSON.stringify({ url: 'https://open.spotify.com/playlist/x' }) });
|
||||
expect(r.res.status).toBe(200);
|
||||
@@ -212,11 +214,30 @@ test('플레이리스트 가져오기: DB songs by video, cleaned YouTube titles
|
||||
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 });
|
||||
// answers besides the shown names (docs/13): the DB song's aliases come along
|
||||
expect(rows[0]).toMatchObject({ titleAnswers: ['Good Day'], artistAnswers: ['IU'] });
|
||||
// someone else's job is not visible
|
||||
const g = await guest(s.base, '손님');
|
||||
expect((await api(s.base, `/api/admin/quizzes/pick/playlist/${job.id}`, { cookie: g.cookie })).res.status).toBe(403);
|
||||
});
|
||||
|
||||
test('정답 자동 채우기 (docs/13): cleaned-title names and the aliases of the same DB song', async () => {
|
||||
addAliases(start());
|
||||
const sa = await adminCookie(TEST_SUPERADMINS[0]);
|
||||
const r = await api(s.base, '/api/admin/quizzes/answers', {
|
||||
method: 'POST',
|
||||
cookie: sa,
|
||||
body: JSON.stringify({ songs: [{ title: '좋은 날', artist: '아이유' }, { title: '사랑을 했다(LOVE SCENARIO)', artist: '아이콘' }, { title: '모르는 곡' }] }),
|
||||
});
|
||||
expect(r.body.answers).toEqual([
|
||||
{ titleAnswers: ['Good Day'], artistAnswers: ['IU'] },
|
||||
{ titleAnswers: ['LOVE SCENARIO', '사랑을 했다 LOVE SCENARIO'], artistAnswers: [] },
|
||||
{ titleAnswers: [], artistAnswers: [] },
|
||||
]);
|
||||
const g = await guest(s.base, '손님');
|
||||
expect((await api(s.base, '/api/admin/quizzes/answers', { method: 'POST', cookie: g.cookie, body: JSON.stringify({ songs: [] }) })).res.status).toBe(403);
|
||||
});
|
||||
|
||||
test('검토 대기: a 전체공개 quiz sends new songs and differences to admins; applied or rejected ones are not asked again', async () => {
|
||||
const song = start();
|
||||
const sa = await adminCookie(TEST_SUPERADMINS[0]);
|
||||
|
||||
@@ -16,6 +16,7 @@ import { getImportJob, startImport, type Lavalink } from '../quizzes/playlist';
|
||||
import { applyReview, listReviews, pendingCount, rejectReview, syncReviews } from '../quizzes/review';
|
||||
import { checkEmbed, type EmbedState } from '../collector/oembed';
|
||||
import { DuelViewsJob, type ViewsSource } from '../quizzes/duel-views';
|
||||
import { songAnswers } from '../answers';
|
||||
|
||||
type Env = { Variables: { userId: string | null; role: Role } };
|
||||
|
||||
@@ -246,6 +247,24 @@ export function mountQuizAdmin(app: Hono<Env>, d: QuizAdminDeps, h: { actor: (c:
|
||||
return job ? c.json({ job }) : c.json({ error: '가져오기 작업을 찾을 수 없어요.' }, 404);
|
||||
});
|
||||
|
||||
/**
|
||||
* 정답 자동 채우기 (파일로 만들기·파일에서 가져오기, docs/13): answers for songs whose 정답 / 가수 정답 cells were empty.
|
||||
* A song the server DB has (same title + artist) lends its aliases too.
|
||||
*/
|
||||
app.post('/quizzes/answers', async (c) => {
|
||||
const p = z
|
||||
.object({ songs: z.array(z.object({ title: z.string().max(200), artist: z.string().max(200).default('') })).max(1000) })
|
||||
.safeParse(await h.body(c));
|
||||
if (!p.success) return c.json({ error: '입력 값이 올바르지 않아요.' }, 400);
|
||||
const byKey = d.db.query<{ id: number }, [string]>('SELECT id FROM songs WHERE match_key = ? AND deleted_at IS NULL ORDER BY id LIMIT 1');
|
||||
const answers = p.data.songs.map((s) => {
|
||||
const songId = s.artist ? (byKey.get(songMatchKey(s.title, s.artist))?.id ?? null) : null;
|
||||
const a = songAnswers(d.db, { ...s, songId });
|
||||
return { titleAnswers: a.titleAnswers, artistAnswers: a.artistAnswers };
|
||||
});
|
||||
return c.json({ answers });
|
||||
});
|
||||
|
||||
/** DB facts of songs just added in the editor (before saving): aliases and the DB highlight for 자동. */
|
||||
app.get('/quizzes/pick/songs', (c) => {
|
||||
const ids = (c.req.query('ids') ?? '').split(',').map(Number).filter((x) => Number.isInteger(x) && x > 0).slice(0, 500);
|
||||
|
||||
@@ -13,6 +13,7 @@ import { isConfident, scoreResult } from '../collector/score';
|
||||
import type { YtmSong } from '../collector/ytmusic';
|
||||
import type { EmbedState } from '../collector/oembed';
|
||||
import { aliasesOf } from '../songs/youtube-review';
|
||||
import { songAnswers } from '../answers';
|
||||
|
||||
export interface LavalinkTrack {
|
||||
identifier: string;
|
||||
@@ -67,6 +68,9 @@ export interface ImportRow {
|
||||
source: { title: string; artist: string };
|
||||
title: string;
|
||||
artist: string;
|
||||
/** Accepted answers besides 제목·가수 (docs/13): other names, DB aliases, 한글 발음 … */
|
||||
titleAnswers: string[];
|
||||
artistAnswers: string[];
|
||||
durationSec: number | null;
|
||||
videoId: string | null;
|
||||
songId: number | null;
|
||||
@@ -132,7 +136,7 @@ async function runImport(d: ImportDeps, job: ImportJob, tracks: LavalinkTrack[])
|
||||
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, 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 row: ImportRow = { n: i + 1, source: { title: t.title, artist: t.author }, title: named.title, artist: named.artist, titleAnswers: [], artistAnswers: [], durationSec: dur, videoId: null, songId: null, status: 'missing', note: '' };
|
||||
const dbSong = (yt ? byVideo.get(t.identifier) : null) ?? byKey.get(songMatchKey(named.title, named.artist));
|
||||
// the video must play on other sites, the DB song's own video too (the DB state may be old)
|
||||
const playable = async (videoId: string) => {
|
||||
@@ -166,6 +170,9 @@ async function runImport(d: ImportDeps, job: ImportJob, tracks: LavalinkTrack[])
|
||||
} else if (!row.note) row.note = '유튜브에서 못 찾았어요';
|
||||
if (i < tracks.length - 1) await Bun.sleep(d.delayMs ?? 700);
|
||||
}
|
||||
// shown title without brackets / feat. / version marks, plus the answers worked out for it (docs/13)
|
||||
const a = songAnswers(d.db, row);
|
||||
Object.assign(row, { title: a.title, titleAnswers: a.titleAnswers, artistAnswers: a.artistAnswers });
|
||||
job.rows.push(row);
|
||||
job.done = i + 1;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* 재생목록으로 엑셀 만들기 (관리자 → 퀴즈): 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 빠진 곡.
|
||||
* 시작·하이라이트 and upload with 파일로 만들기. Two forms (docs/13): 일반 퀴즈 (제목·가수·정답·가수 정답·힌트) and
|
||||
* 이지선다 (제목·가수·an empty 조회수 column). Songs that would not play go to the sheet 빠진 곡.
|
||||
*/
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { playlistSheets, writeXlsxSheets, type PlaylistSheetRow } from '@mq/shared/lite';
|
||||
@@ -57,9 +58,10 @@ export function PlaylistSheet({ onClose }: { onClose: () => void }) {
|
||||
}
|
||||
};
|
||||
const sheets = useMemo(() => (job?.status === 'done' ? playlistSheets(job.rows) : null), [job]);
|
||||
const duelSheets = useMemo(() => (job?.status === 'done' ? playlistSheets(job.rows, 'duel') : 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 toCheck = kept.filter((r) => String(r[r.length - 1] ?? '').includes('확인 필요')).length;
|
||||
const fileName = job?.name.trim() || '재생목록 퀴즈';
|
||||
return (
|
||||
<div className="card stack" style={{ gap: 10 }}>
|
||||
@@ -82,9 +84,13 @@ export function PlaylistSheet({ onClose }: { onClose: () => void }) {
|
||||
</button>
|
||||
</form>
|
||||
<p className="muted small" style={{ margin: 0 }}>
|
||||
곡마다 서버 노래 DB, 영상 제목, 다른 사이트 재생 여부를 확인해서 <b>순번 · 유튜브 영상 링크 · 제목 · 가수 · 시작(초) · 하이라이트(초) · 길이(초) · 비고</b> 엑셀을
|
||||
만들어요. 시작·하이라이트를 채우고(비워 두면 올릴 때 자동 / 처음부터 중에 골라요) <b>파일로 만들기</b>에 그대로 올리면 돼요. 일반 퀴즈는 제목이 정답, 가수가 정답 공개 때
|
||||
같이 보이는 설명이 되고, 이지선다는 조회수를 서버가 불러와요. 재생이 막혔거나 없는 영상, 같은 영상은 <b>빠진 곡</b> 시트로 옮겨요.
|
||||
곡마다 서버 노래 DB, 영상 제목, 다른 사이트 재생 여부를 확인해서 엑셀을 만들어요. 제목의 괄호·feat.·버전 표시는 지우고, 정답으로 인정할 다른 표기는{' '}
|
||||
<b>정답 · 가수 정답</b> 열에 ;로 나눠 적어 둬요(제목·가수는 적지 않아도 늘 정답이에요). 양식은 두 가지예요.
|
||||
<br />· <b>일반 퀴즈용</b>: 순번 · 링크 · 제목 · 가수 · 정답 · 가수 정답 · 힌트 · 시작(초) · 하이라이트(초) · 길이(초) · 비고
|
||||
<br />· <b>이지선다용</b>: 순번 · 링크 · 제목 · 가수 · 조회수 · 시작(초) · 하이라이트(초) · 길이(초) · 비고 — 조회수는 비워 두면 서버가 불러와요
|
||||
<br />
|
||||
시작·하이라이트를 채우고(비워 두면 올릴 때 자동 / 처음부터 중에 골라요) <b>파일로 만들기</b>에 그대로 올리면 돼요. 재생이 막혔거나 없는 영상, 같은 영상은{' '}
|
||||
<b>빠진 곡</b> 시트로 옮겨요.
|
||||
</p>
|
||||
{job && (
|
||||
<div className="stack" style={{ gap: 4 }}>
|
||||
@@ -129,7 +135,10 @@ export function PlaylistSheet({ onClose }: { onClose: () => void }) {
|
||||
)}
|
||||
<div className="row">
|
||||
<button type="button" className="btn btn-primary" disabled={!kept.length && !left.length} onClick={() => download(fileName, writeXlsxSheets(sheets))}>
|
||||
📥 엑셀 받기 ({kept.length}곡)
|
||||
📥 일반 퀴즈용 엑셀 ({kept.length}곡)
|
||||
</button>
|
||||
<button type="button" className="btn" disabled={!kept.length && !left.length} onClick={() => download(`${fileName} (이지선다)`, writeXlsxSheets(duelSheets!))}>
|
||||
📥 이지선다용 엑셀 ({kept.length}곡)
|
||||
</button>
|
||||
{toCheck > 0 && <span className="muted small">비고에 "확인 필요"라고 적힌 곡은 영상을 보고 제목·가수를 고쳐 주세요.</span>}
|
||||
</div>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/**
|
||||
* 퀴즈 파일 (관리자 → 퀴즈): 파일로 만들기 (a new quiz from .xlsx / .csv), 파일에서 가져오기 (into the open quiz),
|
||||
* 엑셀로 내보내기 and 빈 양식. The browser reads the file; columns are recognised by their headers and can be changed.
|
||||
* Values are used as written — bad links and repeated videos are listed and left out.
|
||||
* Values are used as written — bad links and repeated videos are listed and left out. 일반 퀴즈 songs whose 정답 /
|
||||
* 가수 정답 cells are empty get answers worked out by the server (docs/13).
|
||||
*/
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
DUEL_COLUMN_LABEL,
|
||||
QUIZ_COLUMN_LABEL,
|
||||
@@ -23,6 +24,7 @@ import {
|
||||
type Sheet,
|
||||
} from '@mq/shared/lite';
|
||||
import { toast } from '../../store/toast';
|
||||
import { apiCall } from '../../net/api';
|
||||
import { ConfirmSheet } from '../../components/ui';
|
||||
import { Seg } from '../../components/RoomSettings';
|
||||
|
||||
@@ -112,7 +114,38 @@ export function QuizFileImport({
|
||||
const missing = (['link', 'answer'] as const).filter((c) => !columns.includes(c));
|
||||
const duel = kind === 'duel';
|
||||
const bad = parsed?.rows.filter((r) => r.problem) ?? [];
|
||||
const items = parsed?.items ?? [];
|
||||
// 정답 자동 채우기: the songs whose 정답 / 가수 정답 cells were empty, answered by the server
|
||||
const toFill = useMemo(() => (duel ? [] : (parsed?.rows ?? []).filter((r) => r.item && (r.fill.title || r.fill.artist))), [parsed, duel]);
|
||||
const fillKey = (it: { title: string; artist: string }) => `${it.title}\u0000${it.artist}`;
|
||||
const [filled, setFilled] = useState<Record<string, { titleAnswers: string[]; artistAnswers: string[] }>>({});
|
||||
const [filling, setFilling] = useState(false);
|
||||
useEffect(() => {
|
||||
const want = [...new Map(toFill.map((r) => [fillKey(r.item!), { title: r.item!.title, artist: r.item!.artist }])).values()].filter((x) => !filled[fillKey(x)]);
|
||||
if (!want.length) return;
|
||||
let live = true;
|
||||
setFilling(true);
|
||||
apiCall<{ answers: { titleAnswers: string[]; artistAnswers: string[] }[] }>('POST', '/api/admin/quizzes/answers', { songs: want.slice(0, 1000) })
|
||||
.then((r) => live && setFilled((cur) => ({ ...cur, ...Object.fromEntries(want.map((x, i) => [fillKey(x), r.answers[i] ?? { titleAnswers: [], artistAnswers: [] }])) })))
|
||||
.catch((e: Error) => live && toast(`정답 자동 채우기를 못 했어요(적힌 정답만 써요): ${e.message}`, 'error'))
|
||||
.finally(() => live && setFilling(false));
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [toFill]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const items = useMemo(() => {
|
||||
const fill = new Map(toFill.map((r) => [r.item!, r.fill]));
|
||||
return (parsed?.items ?? []).map((it) => {
|
||||
const f = fill.get(it);
|
||||
const got = f && filled[fillKey(it)];
|
||||
if (!f || !got) return it;
|
||||
const merge = (a: string[], b: string[], except: string) => [...new Set([...a, ...b])].filter((x) => x !== except).slice(0, 30);
|
||||
return {
|
||||
...it,
|
||||
titleAnswers: f.title ? merge(it.titleAnswers, got.titleAnswers, it.title) : it.titleAnswers,
|
||||
artistAnswers: f.artist ? merge(it.artistAnswers, got.artistAnswers, it.artist) : it.artistAnswers,
|
||||
};
|
||||
});
|
||||
}, [parsed, toFill, filled]);
|
||||
const inList = new Set(existing.map((x) => x.videoId));
|
||||
const appendable = items.filter((x) => !inList.has(x.videoId));
|
||||
const width = Math.max(header.length, ...(sheet?.rows.slice(headerAt, headerAt + 20).map((r) => r.length) ?? [0]));
|
||||
@@ -189,8 +222,10 @@ export function QuizFileImport({
|
||||
)}
|
||||
{!file && !duel && (
|
||||
<p className="muted small" style={{ margin: 0 }}>
|
||||
한 줄에 한 곡씩, 첫 줄은 열 이름이에요. <b>유튜브 영상 링크</b>와 <b>정답</b>(예: 게임 제목)은 꼭 있어야 하고, <b>설명</b>(예: 노래 제목)은 정답을 공개할 때 같이
|
||||
보여요. <b>힌트</b> 열은 문제마다 먼저 나오고, 그다음 힌트로 초성이 나와요. <b>순번</b> 열이 있으면 그 순서대로 넣어요. 적힌 값은 고치지 않고 그대로 써요.
|
||||
한 줄에 한 곡씩, 첫 줄은 열 이름이에요. <b>유튜브 영상 링크</b>와 <b>제목</b>은 꼭 있어야 하고, <b>가수</b>는 정답을 공개할 때 같이 보여요. 제목·가수는 늘
|
||||
정답이고, <b>정답 · 가수 정답</b> 열에 다른 표기를 ;로 나눠 적으면(예: 라일락; LILAC) 그것도 정답이 돼요. 이 칸이 비어 있으면 서버가 다른 표기(괄호 안 이름, 한글
|
||||
발음 등)를 자동으로 채워요. 제목의 괄호·feat.·버전 표시는 지워서 보여 줘요. <b>힌트</b> 열은 문제마다 먼저 나오고, 그다음 힌트로 초성이 나와요. <b>순번</b> 열이
|
||||
있으면 그 순서대로 넣어요. 예전 양식(정답 · 설명 · 다른 정답)도 그대로 읽어요.
|
||||
</p>
|
||||
)}
|
||||
{file && sheet && (
|
||||
@@ -235,6 +270,7 @@ export function QuizFileImport({
|
||||
<b>{items.length}곡</b>
|
||||
{bad.length > 0 && <span className="warn-text"> · 빠지는 줄 {bad.length}개</span>}
|
||||
{mode === 'into' && items.length > appendable.length && <span className="muted"> · 이미 목록에 있는 영상 {items.length - appendable.length}곡</span>}
|
||||
{toFill.length > 0 && <span className="muted"> · 정답 칸이 빈 곡 {toFill.length}곡{filling ? ' (자동으로 채우는 중…)' : ' (자동으로 채웠어요)'}</span>}
|
||||
</div>
|
||||
{blankCount > 0 && (
|
||||
<div className="stack" style={{ gap: 4 }}>
|
||||
@@ -288,8 +324,8 @@ export function QuizFileImport({
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: 44 }}>#</th>
|
||||
<th>{duel ? '제목' : '정답'}</th>
|
||||
<th>{duel ? '가수' : '설명'}</th>
|
||||
<th>제목</th>
|
||||
<th>가수</th>
|
||||
<th>{duel ? '조회수' : '힌트'}</th>
|
||||
<th>영상</th>
|
||||
</tr>
|
||||
@@ -302,7 +338,10 @@ export function QuizFileImport({
|
||||
<b>{it.title}</b>
|
||||
{it.titleAnswers.length > 0 && <div className="muted small">또는 {it.titleAnswers.join(', ')}</div>}
|
||||
</td>
|
||||
<td className="small">{it.artist || <span className="muted">-</span>}</td>
|
||||
<td className="small">
|
||||
{it.artist || <span className="muted">-</span>}
|
||||
{it.artistAnswers.length > 0 && <div className="muted small">또는 {it.artistAnswers.join(', ')}</div>}
|
||||
</td>
|
||||
{duel ? (
|
||||
<td className="small mono" title={it.views !== null ? `${it.views.toLocaleString('ko-KR')}회 (파일에 적힌 값)` : '올린 뒤 토픽 + MV 조회수를 불러와요'}>
|
||||
{it.views !== null ? `${viewsLabel(it.views)}회` : <span className="muted">자동</span>}
|
||||
@@ -333,16 +372,16 @@ export function QuizFileImport({
|
||||
퀴즈 이름
|
||||
<input className="input grow" value={name} maxLength={60} onChange={(e) => setName(e.target.value)} aria-label="퀴즈 이름" />
|
||||
</label>
|
||||
<button className="btn btn-primary" disabled={busy || !name.trim() || items.length < (duel ? 2 : 1)}>
|
||||
<button className="btn btn-primary" disabled={busy || filling || !name.trim() || items.length < (duel ? 2 : 1)}>
|
||||
{busy ? '만드는 중…' : `${items.length}곡으로 ${duel ? '이지선다 ' : ''}만들기`}
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="row">
|
||||
<button type="button" className="btn btn-primary" disabled={!appendable.length} onClick={() => onApply?.(appendable, false)}>
|
||||
<button type="button" className="btn btn-primary" disabled={filling || !appendable.length} onClick={() => onApply?.(appendable, false)}>
|
||||
{appendable.length}곡 목록 뒤에 추가
|
||||
</button>
|
||||
<button type="button" className="btn btn-danger" disabled={!items.length} onClick={() => setConfirmReplace(true)}>
|
||||
<button type="button" className="btn btn-danger" disabled={filling || !items.length} onClick={() => setConfirmReplace(true)}>
|
||||
지금 목록을 지우고 바꾸기
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -612,7 +612,9 @@ function SongsTab({
|
||||
if (seen.has(r.videoId!) || (r.songId && seen.has(`s${r.songId}`))) continue;
|
||||
seen.add(r.videoId!);
|
||||
if (r.songId) seen.add(`s${r.songId}`);
|
||||
added.push({ ...fresh({ songId: r.songId, videoId: r.videoId!, title: r.title, artist: r.artist, durationSec: r.durationSec }), key: newKey() });
|
||||
// answers worked out by the server (other names, 한글 발음 …, docs/13)
|
||||
const it = fresh({ songId: r.songId, videoId: r.videoId!, title: r.title, artist: r.artist, durationSec: r.durationSec });
|
||||
added.push({ ...it, titleAnswers: r.titleAnswers ?? [], artistAnswers: r.artistAnswers ?? [], key: newKey() });
|
||||
}
|
||||
onItems([...base, ...added]);
|
||||
setSel(null);
|
||||
@@ -898,6 +900,8 @@ interface ImportRow {
|
||||
source: { title: string; artist: string };
|
||||
title: string;
|
||||
artist: string;
|
||||
titleAnswers: string[];
|
||||
artistAnswers: string[];
|
||||
durationSec: number | null;
|
||||
videoId: string | null;
|
||||
songId: number | null;
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
|
||||
## 단계
|
||||
1. [x] `packages/shared/src/title-clean.ts` cleanTitle / versionKind / videoVersionKind, `cli.ts drop-versions`, 차트·원곡 찾기 규칙 (239c314)
|
||||
2. [ ] 엑셀 양식: 제목/정답 열 나누기(quiz-file.ts), 재생목록 엑셀 두 양식, 파일 정답 자동 채움
|
||||
2. [x] 엑셀 양식: 제목/정답 열 나누기(quiz-file.ts), 재생목록 엑셀 두 양식, 파일 정답 자동 채움(`POST /api/admin/quizzes/answers`, 서버 `answers/index.ts`)
|
||||
3. [ ] 정답 자동 생성: 영어 → 한글 발음(CMUdict + 규칙 + 용례), 일본어 → 원어·읽는 소리(kuromoji + 가나→한글)·위키백과 한글 이름
|
||||
4. [ ] 적용: 플레이리스트 가져오기·재생목록 엑셀·수집(새 곡)·서버 DB 정리 검토 목록(관리자)
|
||||
5. [ ] 배포: DB 백업 → `drop-versions --dry-run --keep 7985,9066` 확인 → 실행 → 제목 정리 검토 목록
|
||||
|
||||
@@ -169,7 +169,7 @@ try {
|
||||
JSON.stringify([
|
||||
{ title: '갓 오브 워 2', artist: 'The End Begins', hints: '["액션"]', from_file: 1, song_id: null },
|
||||
{ title: '건파이어 리본', artist: 'Desert Theme', hints: '["확인필요"]', from_file: 1, song_id: null },
|
||||
{ title: '감옥탈출(구토할배)', artist: '트레일러', hints: '["방탈출(플래시)"]', from_file: 1, song_id: null },
|
||||
{ title: '감옥탈출', artist: '트레일러', hints: '["방탈출(플래시)"]', from_file: 1, song_id: null },
|
||||
]),
|
||||
`저장된 곡: ${JSON.stringify(rows)}`,
|
||||
);
|
||||
@@ -179,7 +179,8 @@ try {
|
||||
const [dl] = await Promise.all([p.waitForEvent('download'), p.getByRole('button', { name: /엑셀로 내보내기/ }).click()]);
|
||||
expect(dl.suggestedFilename() === '게임 BGM.xlsx', `내보낸 파일 이름: ${dl.suggestedFilename()}`);
|
||||
const back = (await readXlsx(new Uint8Array(await Bun.file((await dl.path())!).arrayBuffer())))[0]!.rows;
|
||||
expect(back.length === 4 && back[1]![2] === '갓 오브 워 2' && back[1]![4] === '액션' && back[3]![1] === 'https://youtu.be/iIIjS6yDMQo', `내보낸 내용: ${JSON.stringify(back.slice(0, 2))}`);
|
||||
// 제목 · 가수 · 정답 · 가수 정답 · 힌트 …: the bracket went from the title and is an answer now (docs/13)
|
||||
expect(back.length === 4 && back[1]![2] === '갓 오브 워 2' && back[1]![6] === '액션' && back[3]![1] === 'https://youtu.be/iIIjS6yDMQo' && back[3]![4] === '감옥탈출; 구토할배; 감옥탈출 구토할배', `내보낸 내용: ${JSON.stringify(back)}`);
|
||||
// 파일에서 가져오기: a Korean Excel CSV (CP949), one new song and one already in the list
|
||||
const csv = new Uint8Array([
|
||||
...new TextEncoder().encode('link,'),
|
||||
@@ -208,7 +209,7 @@ try {
|
||||
await route.continue();
|
||||
});
|
||||
await p.getByRole('button', { name: '검토 시작' }).click();
|
||||
const get = p.getByRole('button', { name: /엑셀 받기/ });
|
||||
const get = p.getByRole('button', { name: /일반 퀴즈용 엑셀/ });
|
||||
await get.waitFor();
|
||||
expect(failedPolls >= 2, `다시 묻지 않음: ${failedPolls}`);
|
||||
await p.unroute(`${ORIGIN}/api/admin/quizzes/pick/playlist/*`);
|
||||
@@ -223,12 +224,24 @@ try {
|
||||
expect(
|
||||
JSON.stringify(book[0]!.rows) ===
|
||||
JSON.stringify([
|
||||
['순번', '유튜브 영상 링크', '제목', '가수', '시작(초)', '하이라이트(초)', '길이(초)', '비고'],
|
||||
['1', 'https://youtu.be/jeqdYqsrsA0', '좋은 날', '아이유', '', '', '236', 'DB 곡'],
|
||||
['2', 'https://youtu.be/iIIjS6yDMQo', '밤편지', '아이유', '', '', '260', '제목·가수 확인 필요 (영상 제목 형식이 달라 채널 이름을 가수로 씀)'],
|
||||
['순번', '유튜브 영상 링크', '제목', '가수', '정답(;로 구분)', '가수 정답(;로 구분)', '힌트', '시작(초)', '하이라이트(초)', '길이(초)', '비고'],
|
||||
['1', 'https://youtu.be/jeqdYqsrsA0', '좋은 날', '아이유', '좋은 날', '아이유', '', '', '', '236', 'DB 곡'],
|
||||
['2', 'https://youtu.be/iIIjS6yDMQo', '밤편지', '아이유', '밤편지', '아이유', '', '', '', '260', '제목·가수 확인 필요 (영상 제목 형식이 달라 채널 이름을 가수로 씀)'],
|
||||
]),
|
||||
`엑셀 내용: ${JSON.stringify(book[0]!.rows)}`,
|
||||
);
|
||||
// the 이지선다 form: an empty 조회수 column instead of the answers
|
||||
const [dlDuel] = await Promise.all([p.waitForEvent('download'), p.getByRole('button', { name: /이지선다용 엑셀/ }).click()]);
|
||||
expect(dlDuel.suggestedFilename() === '내 재생목록 (이지선다).xlsx', `파일 이름: ${dlDuel.suggestedFilename()}`);
|
||||
const duelBook = await readXlsx(new Uint8Array(await Bun.file((await dlDuel.path())!).arrayBuffer()));
|
||||
expect(
|
||||
JSON.stringify(duelBook[0]!.rows.slice(0, 2)) ===
|
||||
JSON.stringify([
|
||||
['순번', '유튜브 영상 링크', '제목', '가수', '조회수', '시작(초)', '하이라이트(초)', '길이(초)', '비고'],
|
||||
['1', 'https://youtu.be/jeqdYqsrsA0', '좋은 날', '아이유', '', '', '', '236', 'DB 곡'],
|
||||
]),
|
||||
`이지선다 엑셀: ${JSON.stringify(duelBook[0]!.rows)}`,
|
||||
);
|
||||
const upload = async (blank: '자동' | '처음부터', name: string) => {
|
||||
await p.goto(`${ORIGIN}/admin/quizzes`);
|
||||
await p.getByRole('button', { name: /^파일로 만들기/ }).click();
|
||||
|
||||
@@ -41,7 +41,11 @@ test('CSV: quotes, commas and line breaks inside, tab files, BOM, and Korean Exc
|
||||
|
||||
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(quizToRows([]).rows[0] as string[])).toEqual(['order', 'link', 'answer', 'desc', 'answers', 'descAnswers', 'hint', 'start', 'highlight', 'duration', null]);
|
||||
// old 일반 퀴즈 files: 정답 is the title, 설명 / 다른 정답 / 설명 다른 정답
|
||||
expect(guessColumns(['순번', '유튜브 영상 링크', '정답', '설명', '힌트', '다른 정답(;로 구분)', '설명 다른 정답(;로 구분)'])).toEqual(['order', 'link', 'answer', 'desc', 'hint', 'answers', 'descAnswers']);
|
||||
// new ones (docs/13): 제목 next to 정답 → 정답 lists more answers
|
||||
expect(guessColumns(['링크', '제목', '가수', '정답', '가수 정답', '비고'])).toEqual(['link', 'answer', 'desc', 'answers', 'descAnswers', null]);
|
||||
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);
|
||||
@@ -61,14 +65,36 @@ test('rows → quiz songs: as written, 순번 order, bad links / no answer / rep
|
||||
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', '감옥탈출(구토할배)', '트레일러', ['방탈출(플래시)']],
|
||||
['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, '정답이 비어 있어요'],
|
||||
[7, '제목이 비어 있어요'],
|
||||
]);
|
||||
// the bracket went from the title and stays an answer
|
||||
expect(p.items[1]!.titleAnswers).toEqual(['구토할배', '감옥탈출 구토할배']);
|
||||
});
|
||||
|
||||
test('일반 퀴즈 파일 (docs/13): 제목 cleaned, 정답 / 가수 정답 as written, empty ones marked for the server to fill', () => {
|
||||
const rows = [
|
||||
['링크', '제목', '가수', '정답', '가수 정답'],
|
||||
['iIIjS6yDMQo', 'Pretender (feat. 누구)', 'Official髭男dism', 'Pretender; 프리텐더', '오피셜히게단디즘'],
|
||||
['x0-xFqvJ-U8', '사랑을 했다(LOVE SCENARIO)', '아이콘', '', ''],
|
||||
['Es6JbQQE79g', 'Finesse (Remix)', '', '', ''],
|
||||
];
|
||||
const p = parseQuizRows(rows, guessColumns(rows[0]!), 0);
|
||||
expect(p.items.map((i) => [i.title, i.artist, i.titleAnswers, i.artistAnswers])).toEqual([
|
||||
['Pretender', 'Official髭男dism', ['프리텐더'], ['오피셜히게단디즘']],
|
||||
['사랑을 했다', '아이콘', ['LOVE SCENARIO', '사랑을 했다 LOVE SCENARIO'], []],
|
||||
['Finesse', '', [], []],
|
||||
]);
|
||||
expect(p.rows.map((r) => r.fill)).toEqual([
|
||||
{ title: false, artist: false },
|
||||
{ title: true, artist: true },
|
||||
{ title: true, artist: false },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -80,10 +106,8 @@ test('our export reads back to the same songs (answers, own positions, several h
|
||||
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 },
|
||||
]);
|
||||
expect(rows[1]!.slice(2, 6)).toEqual(['감옥탈출', '트레일러', '감옥탈출; 구토할배', '트레일러; trailer']);
|
||||
expect(back).toEqual([items[0]!, { ...items[1]!, songId: null, fromFile: true }]);
|
||||
const t = quizTemplateRows().rows.map((r) => r.map((c) => (c === null ? '' : String(c))));
|
||||
expect(parseQuizRows(t, guessColumns(t[0]!), 0).items).toHaveLength(1);
|
||||
});
|
||||
@@ -132,14 +156,14 @@ test('이지선다 파일: 제목·가수, 조회수 optional (empty = fetched b
|
||||
const fetched = { state: 'done' as const, topicId: 'aaaaaaaaaaa', topicViews: 10, mvId: 'bbbbbbbbbbb', mvViews: 20, error: null, at: 1 };
|
||||
const withAuto = p.items.map((it, i) => (i === 1 ? { ...it, views: 30, viewsAuto: fetched } : it));
|
||||
const { rows: out } = quizToRows(withAuto, 'duel');
|
||||
expect(out[0]).toEqual(['순번', '유튜브 영상 링크', '제목', '가수', '조회수', '시작(초)', '하이라이트(초)']);
|
||||
expect(out[0]).toEqual(['순번', '유튜브 영상 링크', '제목', '가수', '조회수', '시작(초)', '하이라이트(초)', '길이(초)', '비고']);
|
||||
const text = out.map((r) => r.map((c) => (c === null ? '' : String(c))));
|
||||
expect(parseQuizRows(text, guessColumns(text[0]!), 0, 'duel').items.map((i) => i.views)).toEqual([3456789, null, null]);
|
||||
// nothing written by hand: no 조회수 column at all
|
||||
expect(quizToRows([{ ...p.items[2]! }], 'duel').rows[0]).not.toContain('조회수');
|
||||
// 빈 양식: no 조회수 column, the example row reads back with its views left to the server
|
||||
const t = quizTemplateRows('duel').rows.map((r) => r.map((c) => (c === null ? '' : String(c))));
|
||||
expect(t[0]).toEqual(['순번', '유튜브 영상 링크', '제목', '가수', '시작(초)', '하이라이트(초)']);
|
||||
expect(t[0]).toEqual(['순번', '유튜브 영상 링크', '제목', '가수', '시작(초)', '하이라이트(초)', '길이(초)', '비고']);
|
||||
expect(parseQuizRows(t, guessColumns(t[0]!), 0, 'duel').items.map((i) => [i.title, i.views])).toEqual([['라일락', null]]);
|
||||
});
|
||||
|
||||
@@ -154,43 +178,58 @@ test('재생목록으로 엑셀 만들기: kept songs with 비고, unplayable /
|
||||
note: '',
|
||||
...p,
|
||||
});
|
||||
const sheets = playlistSheets([
|
||||
row({ n: 1, videoId: 'goodday0001', status: 'db', note: '서버 DB 곡 (플레이리스트 영상 사용)', title: '좋은 날', artist: '아이유', durationSec: 230 }),
|
||||
const list = [
|
||||
row({ n: 1, videoId: 'goodday0001', status: 'db', note: '서버 DB 곡 (플레이리스트 영상 사용)', title: '좋은 날', artist: '아이유', durationSec: 230, titleAnswers: ['Good Day'], artistAnswers: ['IU'] }),
|
||||
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 }),
|
||||
]);
|
||||
];
|
||||
const sheets = playlistSheets(list);
|
||||
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, '유튜브 뮤직에서 찾음'],
|
||||
['순번', '유튜브 영상 링크', '제목', '가수', '정답(;로 구분)', '가수 정답(;로 구분)', '힌트', '시작(초)', '하이라이트(초)', '길이(초)', '비고'],
|
||||
[1, 'https://youtu.be/goodday0001', '좋은 날', '아이유', '좋은 날; Good Day', '아이유; IU', null, null, null, 230, 'DB 곡'],
|
||||
[2, 'https://youtu.be/lovedive001', '곡 2', '가수 2', '곡 2', '가수 2', null, null, null, 200, '제목·가수 확인 필요 (영상 제목 형식이 달라 채널 이름을 가수로 씀)'],
|
||||
[3, 'https://youtu.be/hypeboy0001', '곡 6', '가수 6', '곡 6', '가수 6', null, null, null, 200, '확인 필요: NewJeans - Hype Boy'],
|
||||
[4, 'https://youtu.be/ditto000001', '곡 7', '가수 7', '곡 7', '가수 7', null, 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 duel = playlistSheets(list, 'duel');
|
||||
expect(duel[0]!.name).toBe('이지선다');
|
||||
expect(duel[0]!.rows.slice(0, 2)).toEqual([
|
||||
['순번', '유튜브 영상 링크', '제목', '가수', '조회수', '시작(초)', '하이라이트(초)', '길이(초)', '비고'],
|
||||
[1, 'https://youtu.be/goodday0001', '좋은 날', '아이유', null, null, null, 230, 'DB 곡'],
|
||||
]);
|
||||
// the files 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(cols).toEqual(['order', 'link', 'answer', 'desc', 'answers', 'descAnswers', 'hint', '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],
|
||||
]);
|
||||
}
|
||||
const normal = parseQuizRows(book[0]!.rows, cols, 0).items;
|
||||
expect(normal.map((i) => [i.videoId, i.title, i.artist, i.titleAnswers, i.artistAnswers, i.durationSec, i.auto])).toEqual([
|
||||
['goodday0001', '좋은 날', '아이유', ['Good Day'], ['IU'], 230, true],
|
||||
['lovedive001', '곡 2', '가수 2', [], [], 200, true],
|
||||
['hypeboy0001', '곡 6', '가수 6', [], [], 200, true],
|
||||
['ditto000001', '곡 7', '가수 7', [], [], null, true],
|
||||
]);
|
||||
// the 이지선다 file has the (empty) 조회수 column: 파일로 만들기 picks 이지선다 and leaves the views to the server
|
||||
const duelBook = await readSheetFile('재생목록.xlsx', writeXlsxSheets(duel));
|
||||
const duelCols = guessColumns(duelBook[0]!.rows[0]!);
|
||||
expect(duelCols).toContain('views');
|
||||
expect(parseQuizRows(duelBook[0]!.rows, duelCols, 0, 'duel').items.map((i) => [i.title, i.artist, i.views, i.durationSec])).toEqual([
|
||||
['좋은 날', '아이유', null, 230],
|
||||
['곡 2', '가수 2', null, 200],
|
||||
['곡 6', '가수 6', null, 200],
|
||||
['곡 7', '가수 7', null, null],
|
||||
]);
|
||||
});
|
||||
|
||||
test('시작·하이라이트가 빈 곡: 자동 (start 0 + highlight worked out) or 처음부터 (0 / 0); written values are kept either way', () => {
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
/**
|
||||
* 퀴즈 파일 (관리자 → 퀴즈 → 파일로 만들기 / 내보내기): 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.
|
||||
* 일반 퀴즈 (docs/13): 제목·가수 = the names shown when the answer is revealed (both always count as answers),
|
||||
* 정답·가수 정답 = more accepted answers (;로 여러 개). Old files (정답 = the title, 설명, 다른 정답) still read the same.
|
||||
* Titles lose brackets, feat. and version marks (cleanTitle); another name that was in brackets becomes an answer.
|
||||
*/
|
||||
import type { QuizItem, QuizKind } from './custom-quiz';
|
||||
import { cleanTitle } from './title-clean';
|
||||
|
||||
/** answer = 제목 (the title), desc = 가수, answers = 정답 (more title answers), descAnswers = 가수 정답. */
|
||||
export type QuizColumn = 'link' | 'answer' | 'desc' | 'hint' | 'answers' | 'descAnswers' | 'order' | 'start' | 'highlight' | 'duration' | 'views';
|
||||
|
||||
export const QUIZ_COLUMN_LABEL: Record<QuizColumn, string> = {
|
||||
link: '유튜브 영상 링크',
|
||||
answer: '정답',
|
||||
desc: '설명',
|
||||
answer: '제목',
|
||||
desc: '가수',
|
||||
hint: '힌트',
|
||||
answers: '다른 정답',
|
||||
descAnswers: '설명 다른 정답',
|
||||
answers: '정답',
|
||||
descAnswers: '가수 정답',
|
||||
order: '순번',
|
||||
start: '시작(초)',
|
||||
highlight: '하이라이트(초)',
|
||||
@@ -21,15 +24,18 @@ export const QUIZ_COLUMN_LABEL: Record<QuizColumn, string> = {
|
||||
views: '조회수',
|
||||
};
|
||||
|
||||
/** 이지선다 퀴즈 files call the same columns 제목 / 가수 (shown on the cards). */
|
||||
export const DUEL_COLUMN_LABEL: Partial<Record<QuizColumn, string>> = { answer: '제목', desc: '가수' };
|
||||
/** 이지선다 퀴즈 files: the same names (제목 / 가수 shown on the cards). */
|
||||
export const DUEL_COLUMN_LABEL: Partial<Record<QuizColumn, string>> = {};
|
||||
|
||||
/** 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', 'duration'],
|
||||
normal: ['link', 'answer', 'desc', 'answers', 'descAnswers', 'hint', 'order', 'start', 'highlight', 'duration'],
|
||||
duel: ['link', 'answer', 'desc', 'views', 'order', 'start', 'highlight', 'duration'],
|
||||
};
|
||||
|
||||
/** 일반 퀴즈 file headers (빈 양식, 내보내기, 재생목록으로 엑셀 만들기). */
|
||||
const NORMAL_HEAD = { answers: '정답(;로 구분)', descAnswers: '가수 정답(;로 구분)' };
|
||||
|
||||
/**
|
||||
* 조회수 as people write it: 1234567 · 1,234,567 · 1234567회 · 123만 · 1.2억 · 1억 2,345만 · 3.4M · 12K (Excel's 1.2E+9 too).
|
||||
* '' → null; anything else → undefined (invalid).
|
||||
@@ -64,16 +70,20 @@ export function parseVideoId(s: string): string | null {
|
||||
|
||||
const norm = (h: string) => h.toLowerCase().replace(/\s+/g, '');
|
||||
|
||||
/** A 제목 column next to a 정답 column: the new 일반 퀴즈 file, where 정답 lists more answers (not the title). */
|
||||
const TITLE_HEAD = /^(제목|title)(\(|$)|^(곡|노래)?제목\(|^songtitle$/;
|
||||
|
||||
/** 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 titled = header.some((h) => TITLE_HEAD.test(norm(h))) && header.some((h) => /^정답/.test(norm(h)));
|
||||
const rules: [QuizColumn, RegExp][] = [
|
||||
['views', /조회수|조회|재생수|views?|viewcount/],
|
||||
['order', /순번|순서|^order$|^no\.?$/],
|
||||
['link', /링크|주소|url|영상|유튜브|youtube|video|link/],
|
||||
['descAnswers', /(설명|가수|노래|artist).*(다른|추가|복수)정답|(다른|추가|복수)정답.*(설명|가수|노래|artist)/],
|
||||
['answers', /(다른|추가|복수)정답|별칭|alias|answers/],
|
||||
['descAnswers', /(설명|가수|노래|artist).*(다른|추가|복수)정답|(다른|추가|복수)정답.*(설명|가수|노래|artist)|^(설명|가수|artist)정답|^artistanswers?/],
|
||||
['answers', titled ? /(다른|추가|복수)정답|^정답|별칭|alias|answers/ : /(다른|추가|복수)정답|별칭|alias|answers/],
|
||||
['hint', /힌트|hint/],
|
||||
['highlight', /하이라이트|highlight/],
|
||||
['duration', /길이|duration|^length/],
|
||||
@@ -121,6 +131,8 @@ export interface FileRow {
|
||||
/** Row number in the sheet (1-based, as Excel shows it). */
|
||||
line: number;
|
||||
item: QuizItem | null;
|
||||
/** 일반 퀴즈: the 정답 / 가수 정답 cell was empty (or there is no such column): the server fills it in (docs/13). */
|
||||
fill: { title: boolean; artist: boolean };
|
||||
/** 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. */
|
||||
@@ -173,16 +185,14 @@ export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[],
|
||||
: !videoId
|
||||
? '유튜브 링크가 아니에요'
|
||||
: !title
|
||||
? duel
|
||||
? '제목이 비어 있어요'
|
||||
: '정답이 비어 있어요'
|
||||
? '제목이 비어 있어요'
|
||||
: views === undefined
|
||||
? `조회수를 읽을 수 없어요 (${cell(r, at('views')).slice(0, 30)})`
|
||||
: seen.has(videoId)
|
||||
? `${seen.get(videoId)}번째 줄과 같은 영상이에요`
|
||||
: null;
|
||||
if (problem) {
|
||||
out.push({ line, item: null, problem, link });
|
||||
out.push({ line, item: null, problem, link, fill: { title: false, artist: false } });
|
||||
continue;
|
||||
}
|
||||
seen.set(videoId!, line);
|
||||
@@ -191,17 +201,22 @@ export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[],
|
||||
const own = (start !== null && start !== undefined) || (highlight !== null && highlight !== undefined);
|
||||
const fromStart = !own && blank === 'start';
|
||||
const length = parseSec(cell(r, at('duration')));
|
||||
const clean = cleanTitle(title);
|
||||
const artist = cell(r, at('desc')).slice(0, 200);
|
||||
const written = splitAnswers(cell(r, at('answers')));
|
||||
const writtenArtist = splitAnswers(cell(r, at('descAnswers')));
|
||||
out.push({
|
||||
line,
|
||||
link,
|
||||
problem: null,
|
||||
fill: { title: !duel && !written.length, artist: !duel && !writtenArtist.length && !!artist },
|
||||
item: {
|
||||
songId: null,
|
||||
videoId: videoId!,
|
||||
title,
|
||||
artist: cell(r, at('desc')).slice(0, 200),
|
||||
titleAnswers: duel ? [] : splitAnswers(cell(r, at('answers'))).filter((a) => a !== title),
|
||||
artistAnswers: duel ? [] : splitAnswers(cell(r, at('descAnswers'))),
|
||||
title: clean.title.slice(0, 200),
|
||||
artist,
|
||||
titleAnswers: duel ? [] : [...new Set([...clean.aliases, ...written])].filter((a) => a !== clean.title).slice(0, 30),
|
||||
artistAnswers: duel ? [] : writtenArtist.filter((a) => a !== artist),
|
||||
hints: duel ? [] : hintCols.map((i) => cell(r, i).slice(0, 200)).filter(Boolean).slice(0, 5),
|
||||
fromFile: true,
|
||||
durationSec: length ? Math.min(36000, Math.round(length)) : null,
|
||||
@@ -218,58 +233,38 @@ export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[],
|
||||
|
||||
/** Quiz songs → sheet rows with the headers this file format reads back (내보내기, 빈 양식). */
|
||||
export function quizToRows(items: QuizItem[], kind: QuizKind = 'normal'): { rows: (string | number | null)[][]; widths: number[] } {
|
||||
const pos = (it: QuizItem) => [it.auto ? null : (it.startSec ?? 0), it.auto ? null : it.highlightSec, it.durationSec];
|
||||
if (kind === 'duel') {
|
||||
// 조회수 only for numbers written by hand: fetched ones (and empty ones) are fetched again when the file comes back
|
||||
const own = (it: QuizItem) => (it.viewsAuto ? null : it.views);
|
||||
const withViews = items.some((it) => own(it) !== null);
|
||||
const header = ['순번', QUIZ_COLUMN_LABEL.link, '제목', '가수', ...(withViews ? ['조회수'] : []), '시작(초)', '하이라이트(초)'];
|
||||
const rows = items.map((it, i) => [i + 1, `https://youtu.be/${it.videoId}`, it.title, it.artist, ...(withViews ? [own(it)] : []), it.auto ? null : (it.startSec ?? 0), it.auto ? null : it.highlightSec]);
|
||||
return { rows: [header, ...rows], widths: [6, 32, 30, 24, ...(withViews ? [16] : []), 10, 14] };
|
||||
const header = ['순번', QUIZ_COLUMN_LABEL.link, '제목', '가수', ...(withViews ? ['조회수'] : []), '시작(초)', '하이라이트(초)', '길이(초)', '비고'];
|
||||
const rows = items.map((it, i) => [i + 1, `https://youtu.be/${it.videoId}`, it.title, it.artist, ...(withViews ? [own(it)] : []), ...pos(it), null]);
|
||||
return { rows: [header, ...rows], widths: [6, 32, 30, 24, ...(withViews ? [16] : []), 10, 14, 10, 30] };
|
||||
}
|
||||
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 header = ['순번', QUIZ_COLUMN_LABEL.link, '제목', '가수', NORMAL_HEAD.answers, NORMAL_HEAD.descAnswers, ...hintHeads, '시작(초)', '하이라이트(초)', '길이(초)', '비고'];
|
||||
const rows = items.map((it, i) => [
|
||||
i + 1,
|
||||
`https://youtu.be/${it.videoId}`,
|
||||
it.title,
|
||||
it.artist,
|
||||
// the title and the artist always count: listed first so the cell shows every accepted answer
|
||||
[it.title, ...it.titleAnswers].join('; '),
|
||||
[it.artist, ...it.artistAnswers].filter(Boolean).join('; '),
|
||||
...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,
|
||||
...pos(it),
|
||||
null,
|
||||
]);
|
||||
return { rows: [header, ...rows], widths: [6, 32, 30, 30, ...hintHeads.map(() => 20), 24, 24, 10, 14] };
|
||||
return { rows: [header, ...rows], widths: [6, 32, 30, 24, 36, 30, ...hintHeads.map(() => 20), 10, 14, 10, 30] };
|
||||
}
|
||||
|
||||
/** 빈 양식: the headers and one example row. */
|
||||
export function quizTemplateRows(kind: QuizKind = 'normal'): { rows: (string | number | null)[][]; widths: number[] } {
|
||||
if (kind === 'duel')
|
||||
return quizToRows(
|
||||
[
|
||||
{ songId: null, videoId: 'v7bnOxV4jAc', title: '라일락', artist: '아이유', titleAnswers: [], artistAnswers: [], hints: [], fromFile: true, durationSec: null, auto: true, startSec: null, highlightSec: null, views: null, viewsAuto: null },
|
||||
],
|
||||
'duel',
|
||||
);
|
||||
return quizToRows([
|
||||
{
|
||||
songId: null,
|
||||
videoId: 'iIIjS6yDMQo',
|
||||
title: '감옥탈출',
|
||||
artist: '트레일러',
|
||||
titleAnswers: ['구토할배 감옥탈출'],
|
||||
artistAnswers: [],
|
||||
hints: ['방탈출(플래시)'],
|
||||
fromFile: true,
|
||||
durationSec: null,
|
||||
auto: true,
|
||||
startSec: null,
|
||||
highlightSec: null,
|
||||
views: null,
|
||||
viewsAuto: null,
|
||||
},
|
||||
]);
|
||||
const base = { songId: null, videoId: 'v7bnOxV4jAc', title: '라일락', artist: '아이유', fromFile: true, durationSec: null, auto: true, startSec: null, highlightSec: null, views: null, viewsAuto: null };
|
||||
if (kind === 'duel') return quizToRows([{ ...base, titleAnswers: [], artistAnswers: [], hints: [] }], 'duel');
|
||||
return quizToRows([{ ...base, titleAnswers: ['LILAC'], artistAnswers: ['IU'], hints: ['2021년 봄'] }]);
|
||||
}
|
||||
|
||||
/** One song of 플레이리스트 가져오기 (server quizzes/playlist.ts ImportRow), as 재생목록으로 엑셀 만들기 needs it. */
|
||||
@@ -278,6 +273,9 @@ export interface PlaylistSheetRow {
|
||||
source: { title: string; artist: string };
|
||||
title: string;
|
||||
artist: string;
|
||||
/** Accepted answers worked out by the server (docs/13): other names, 한글 발음, 일본어 원어·읽는 소리. */
|
||||
titleAnswers?: string[];
|
||||
artistAnswers?: string[];
|
||||
durationSec: number | null;
|
||||
videoId: string | null;
|
||||
status: 'db' | 'video' | 'found' | 'check' | 'missing' | 'blocked';
|
||||
@@ -285,11 +283,13 @@ export interface PlaylistSheetRow {
|
||||
}
|
||||
|
||||
/**
|
||||
* 재생목록으로 엑셀 만들기: 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.
|
||||
* 재생목록으로 엑셀 만들기: the checked playlist as a quiz file 파일로 만들기 reads as is, in the 일반 퀴즈 form
|
||||
* (제목 · 가수 · 정답 · 가수 정답 · 힌트) or the 이지선다 form (제목 · 가수 · an empty 조회수 column, which also makes
|
||||
* 파일로 만들기 pick 이지선다; the server fetches the views). 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[] }[] {
|
||||
export function playlistSheets(list: PlaylistSheetRow[], kind: QuizKind = 'normal'): { name: string; rows: (string | number | null)[][]; widths: number[] }[] {
|
||||
const kept: (string | number | null)[][] = [];
|
||||
const left: (string | number | null)[][] = [];
|
||||
const firstOf = new Map<string, number>();
|
||||
@@ -315,11 +315,22 @@ export function playlistSheets(list: PlaylistSheetRow[]): { name: string; rows:
|
||||
: 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 = [kept.length + 1, `https://youtu.be/${r.videoId}`, r.title, r.artist];
|
||||
const tail = [null, null, r.durationSec, note || null];
|
||||
if (kind === 'duel') kept.push([...head, null, ...tail]);
|
||||
else
|
||||
kept.push([
|
||||
...head,
|
||||
[r.title, ...(r.titleAnswers ?? []).filter((a) => a !== r.title)].join('; '),
|
||||
[r.artist, ...(r.artistAnswers ?? []).filter((a) => a !== r.artist)].filter(Boolean).join('; '),
|
||||
null,
|
||||
...tail,
|
||||
]);
|
||||
}
|
||||
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] },
|
||||
];
|
||||
const pos = [QUIZ_COLUMN_LABEL.start, QUIZ_COLUMN_LABEL.highlight, QUIZ_COLUMN_LABEL.duration, '비고'];
|
||||
const quiz =
|
||||
kind === 'duel'
|
||||
? { name: '이지선다', rows: [['순번', QUIZ_COLUMN_LABEL.link, '제목', '가수', QUIZ_COLUMN_LABEL.views, ...pos], ...kept], widths: [6, 32, 30, 24, 12, 10, 14, 10, 40] }
|
||||
: { name: '퀴즈', rows: [['순번', QUIZ_COLUMN_LABEL.link, '제목', '가수', NORMAL_HEAD.answers, NORMAL_HEAD.descAnswers, '힌트', ...pos], ...kept], widths: [6, 32, 30, 24, 36, 30, 16, 10, 14, 10, 40] };
|
||||
return [quiz, { name: '빠진 곡', rows: [['재생목록 순번', '링크', '곡 제목(재생목록)', '채널·가수(재생목록)', '빠진 이유'], ...left], widths: [12, 32, 36, 24, 40] }];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user