엑셀 양식 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:
EJClaw
2026-11-04 16:00:33 +09:00
parent 2e333dd3f7
commit 74eaeb85da
11 changed files with 331 additions and 117 deletions

View 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),
};
}

View File

@@ -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]);

View File

@@ -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);

View File

@@ -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;
}