5~7단계 게임: 숨긴 유튜브 동기화 재생(전원 준비·버퍼링이면 모두 멈춤·30초 늦은 사람 제외·재생 오류 곡 교체), 정답 판정·점수·정답 블록, 입력 중·단축키, 힌트·스킵·다시듣기 투표, 3모드, 결과·이어풀기·다시 하기, 퀴즈 저장·불러오기 + 마지막 사람이 나가면 방 바로 닫기

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 22:11:14 +09:00
parent af2dce5b50
commit 7266fc8d25
27 changed files with 3461 additions and 46 deletions

View File

@@ -14,6 +14,8 @@ export const SiteSettingsSchema = z.object({
chatFloodGuard: z.boolean().default(false),
chatRatePerSec: z.number().int().min(1).max(50).default(6),
chatBurst: z.number().int().min(1).max(100).default(12),
/** One question's time limit for short clips (docs/05 문제 진행: 기본 60초, 관리자 설정). */
questionLimitSec: z.number().int().min(10).max(600).default(60),
});
export type SiteSettings = z.infer<typeof SiteSettingsSchema>;

View File

@@ -0,0 +1,13 @@
-- 퀴즈 저장·불러오기 (docs/12 Q8): settings, songs played so far, scores per account. Discord accounts only, 20 per account.
CREATE TABLE saved_quizzes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
config_json TEXT NOT NULL,
played_json TEXT NOT NULL, -- song ids already asked
scores_json TEXT NOT NULL, -- [{id, nickname, score, correct, totalMs}]
questions INTEGER NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE INDEX saved_quizzes_user ON saved_quizzes(user_id, updated_at);

View File

@@ -0,0 +1,467 @@
/**
* Game engine over real WebSockets (docs/05, docs/12 Q1·Q3·Q4·Q5·Q8) with short timings.
* Clients play the browser's part: they report audio ready / stall / clip end like the hidden YouTube player would.
*/
import { afterEach, describe, expect, test } from 'bun:test';
import type { ChatLine, GameView, ServerMessage } from '@mq/shared';
import { Catalog } from './collector/catalog';
import { Client, api, boot, discordLogin, guest, sleep } from './test-utils';
type Msg<T extends ServerMessage['t']> = Extract<ServerMessage, { t: T }>;
const TIMING = { countdownMs: 60, revealMs: 120, resumeLeadMs: 40, clipGraceMs: 150, lateMs: 150, tickMs: 20 };
const fakeDiscord = async (code: string) => ({ id: code, username: 'u', global_name: `회원${code.slice(-2)}`, avatar: null });
let s: ReturnType<typeof boot>;
afterEach(async () => s && (await s.stop()));
function seed(n: number, opts: { artist?: (i: number) => string; lyrics?: boolean } = {}) {
const c = new Catalog(s.db);
const ids: number[] = [];
for (let i = 1; i <= n; i++) {
const [id] = c.upsert({ title: `노래${i}`, artists: [{ name: opts.artist?.(i) ?? `가수${i}` }], year: 2000 + i, genres: ['kpop'], source: 't', ref: `s${i}` });
c.autoLevel(id!, 'all', 3);
s.db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = ?, duration_sec = 200 WHERE id = ?").run(`vid${i}`, id!);
if (opts.lyrics) s.db.query('INSERT INTO lyrics (song_id, text, source, fetched_at) VALUES (?, ?, ?, 0)').run(id!, `첫 줄 ${i}\n둘째 줄\n노래${i} 셋째 줄\n넷째 줄\n다섯째 줄\n후렴\n후렴`, 't');
ids.push(id!);
}
return ids;
}
const last = <T extends ServerMessage['t']>(cl: Client, t: T) => [...cl.messages].reverse().find((m) => m.t === t) as Msg<T> | undefined;
/** Wait until the latest game view matches. */
const gameWhere = (cl: Client, pred: (g: GameView) => boolean, timeout = 3000) =>
new Promise<GameView>((resolve, reject) => {
const t0 = Date.now();
const tick = () => {
const g = last(cl, 'game')?.game;
if (g && pred(g)) return resolve(g);
if (Date.now() - t0 > timeout) return reject(new Error(`no matching game view; last ${JSON.stringify(g && { phase: g.phase, n: g.n, paused: g.paused, waiting: g.waiting })}`));
setTimeout(tick, 5);
};
tick();
});
const since = (cl: Client) => cl.messages.length;
const nextOf = <T extends ServerMessage['t']>(cl: Client, t: T, from: number, pred: (m: Msg<T>) => boolean = () => true, timeout = 3000) =>
new Promise<Msg<T>>((resolve, reject) => {
const t0 = Date.now();
const tick = () => {
const m = cl.messages.slice(from).find((x) => x.t === t && pred(x as Msg<T>)) as Msg<T> | undefined;
if (m) return resolve(m);
if (Date.now() - t0 > timeout) return reject(new Error(`no ${t} message; last ${JSON.stringify(cl.messages.slice(-2))}`));
setTimeout(tick, 5);
};
tick();
});
/** Pending catalog for the next room(): seeding needs the server's DB, so it runs right after boot. */
let pendingSeed: (() => void)[] = [];
function seedLater(fn: () => void) {
pendingSeed.push(fn);
}
async function room(players: string[], config: Record<string, unknown> = {}, timing: Record<string, number> = {}) {
s = boot({ gameTiming: { ...TIMING, ...timing }, discordExchange: fakeDiscord }, { DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' });
for (const f of pendingSeed) f();
pendingSeed = [];
const users = [];
for (const name of players) users.push(await guest(s.base, name));
const code: string = (await api(s.base, '/api/rooms', { method: 'POST', cookie: users[0]!.cookie, body: JSON.stringify({ config }) })).body.code;
const cls: Client[] = [];
for (const u of users) {
const cl = await new Client(s.base, u.cookie).connect();
cl.send({ t: 'join', code });
await cl.waitFor((m) => m.t === 'room');
cls.push(cl);
}
return { users, cls, code };
}
/** Act as browsers: every client reports ready for each prepare it gets. */
function autoReady(cls: Client[], skip: Set<Client> = new Set()) {
const seen = new Map<Client, number>();
const iv = setInterval(() => {
for (const cl of cls) {
if (skip.has(cl)) continue;
const from = seen.get(cl) ?? 0;
for (const m of cl.messages.slice(from)) if (m.t === 'prepare') cl.send({ t: 'audio', n: m.n, ev: 'ready' });
seen.set(cl, cl.messages.length);
}
}, 5);
return () => clearInterval(iv);
}
const chatLines = (cl: Client) => cl.messages.filter((m) => m.t === 'chat' || m.t === 'answer').map((m) => (m as Msg<'chat'>).line as ChatLine);
describe('game flow', () => {
test('nothing plays until everyone is ready; then one play time for all, answers count after the 3·2·1, first correct gets +1 with the answer block', async () => {
seedLater(() => seed(3));
const { users, cls } = await room(['방장', '철수']);
const [a, b] = cls as [Client, Client];
const fa = since(a);
a.send({ t: 'start' });
const pa = await nextOf(a, 'prepare', fa);
const pb = await nextOf(b, 'prepare', fa > 0 ? 0 : 0);
expect(pa).toMatchObject({ n: 1, startSec: 0 });
expect(pa.videoId).toMatch(/^vid\d$/);
expect(pb.videoId).toBe(pa.videoId);
// the room state never carries the video id
expect(JSON.stringify(last(a, 'game'))).not.toContain(pa.videoId);
a.send({ t: 'audio', n: 1, ev: 'ready' });
await sleep(80);
expect(a.messages.slice(fa).some((m) => m.t === 'play')).toBe(false); // 철수 is not ready
expect((await gameWhere(a, (g) => g.waiting.length === 1)).waiting[0]!.id).toBe(users[1]!.id);
const fb = since(b);
b.send({ t: 'audio', n: 1, ev: 'ready' });
const playA = await nextOf(a, 'play', fa);
const playB = await nextOf(b, 'play', fb);
expect(playA.startAt).toBe(playB.startAt);
expect(playA.atSec).toBe(0);
// answering during the 3·2·1 is just chat
const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(pa.videoId)!.title;
b.send({ t: 'chat', text: title, n: 'early' });
await b.waitFor((m) => m.t === 'chat' && m.line.n === 'early');
await sleep(Math.max(0, playA.startAt - Date.now()) + 10);
b.send({ t: 'chat', text: '모르겠다' });
b.send({ t: 'chat', text: title, n: 'win' });
a.send({ t: 'chat', text: title });
const ans = (await a.waitFor((m) => m.t === 'answer')) as Msg<'answer'>;
expect(ans.line).toMatchObject({ userId: users[1]!.id, text: title, n: 'win', answer: { text: expect.stringContaining(`${title} - `) } });
// nothing sits between the answer line and its block: it is one item, and the next line has a higher seq
const lines = chatLines(a);
const i = lines.findIndex((l) => l.answer);
expect(lines[i - 1]!.text).toBe('모르겠다');
const g = await gameWhere(a, (x) => x.phase === 'reveal');
expect(g.scores[0]).toMatchObject({ id: users[1]!.id, score: 1, correct: 1 });
expect(g.history[0]).toMatchObject({ n: 1, title, winnerId: users[1]!.id, how: 'correct' });
expect(g.history[0]!.ms).toBeGreaterThanOrEqual(0);
// reveal ends → question 2 is prepared
await nextOf(a, 'prepare', fa, (m) => m.n === 2);
});
test('a stall pauses everyone at the same position, timers stop, and play resumes for all from there', async () => {
seedLater(() => seed(2));
const { cls } = await room(['방장', '철수'], { listenSec: 30 });
const [a, b] = cls as [Client, Client];
const stop = autoReady(cls);
a.send({ t: 'start' });
const p1 = await nextOf(a, 'play', 0);
await sleep(p1.startAt - Date.now() + 120);
const fa = since(a);
b.send({ t: 'audio', n: 1, ev: 'stall' });
await nextOf(a, 'pause', fa);
const paused = (await nextOf(a, 'game', fa, (m) => !!m.game?.paused)).game!;
expect(paused.paused).toMatchObject({ reason: 'stall' });
expect(paused.clock.runningSince).toBeNull();
const frozen = paused.clock.elapsedMs;
const resume = await nextOf(a, 'play', fa);
expect(resume.atSec).toBeGreaterThan(0.08);
expect(resume.atSec).toBeLessThan(0.4);
const re = await nextOf(a, 'prepare', fa);
expect(re.startSec).toBe(resume.atSec);
const after = await gameWhere(a, (g) => !g.paused && g.clock.runningSince !== null);
expect(after.clock.elapsedMs).toBe(frozen);
stop();
});
test('the clip ends by reports (or grace), the question goes on until the time limit; 끝까지 ends the question with the song', async () => {
seedLater(() => seed(2));
const { cls } = await room(['방장', '철수'], { listenSec: 1 });
const [a, b] = cls as [Client, Client];
const stop = autoReady(cls);
a.send({ t: 'start' });
const p = await nextOf(a, 'play', 0);
expect(p.endSec).toBe(1);
await sleep(p.startAt - Date.now() + 30);
a.send({ t: 'audio', n: 1, ev: 'clipEnd' });
b.send({ t: 'audio', n: 1, ev: 'clipEnd' });
const g = await gameWhere(a, (x) => x.clipOver);
expect(g.phase).toBe('play'); // still answerable
stop();
});
test('time limit ends a question with no winner; the clock does not count paused time', async () => {
seedLater(() => seed(2));
const { cls } = await room(['혼자'], { listenSec: 5 }, { limitMs: 300 });
const [ca] = cls as [Client];
const stop = autoReady([ca]);
ca.send({ t: 'start' });
const p = await nextOf(ca, 'play', 0);
await sleep(p.startAt - Date.now() + 100);
ca.send({ t: 'game', action: 'pause' });
await gameWhere(ca, (g) => g.paused?.reason === 'host');
await sleep(400); // longer than the limit, but paused
expect(last(ca, 'game')!.game!.phase).toBe('play');
ca.send({ t: 'game', action: 'resume' });
const g = await gameWhere(ca, (x) => x.phase === 'reveal');
expect(g.history[0]).toMatchObject({ how: 'timeout', winnerId: null });
expect(chatLines(ca).find((l) => l.answer)?.answer?.none).toBe(true);
stop();
});
test('someone not ready blocks the start; after 30s the host may leave them out of this question only', async () => {
seedLater(() => seed(3));
const { users, cls } = await room(['방장', '느림']);
const [a, b] = cls as [Client, Client];
const stop = autoReady(cls, new Set([b]));
a.send({ t: 'start' });
await gameWhere(a, (g) => g.waiting.some((w) => w.id === users[1]!.id));
a.send({ t: 'exclude', userId: users[1]!.id });
expect(((await a.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toContain('30초');
await sleep(170);
b.send({ t: 'exclude', userId: users[0]!.id });
expect(((await b.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toContain('방장만');
const fa = since(a);
a.send({ t: 'exclude', userId: users[1]!.id });
await nextOf(a, 'play', fa);
const g = await gameWhere(a, (x) => x.excluded.includes(users[1]!.id));
expect(g.phase).toBe('play');
// excluded players cannot answer this question
const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(last(a, 'prepare')!.videoId)!.title;
await sleep(80);
b.send({ t: 'chat', text: title, n: 'x' });
await a.waitFor((m) => m.t === 'chat' && m.line.n === 'x');
expect(last(a, 'game')!.game!.phase).toBe('play');
stop();
});
test('a disconnected player is not waited for', async () => {
seedLater(() => seed(2));
const { cls } = await room(['방장', '나감']);
const [a, b] = cls as [Client, Client];
const stop = autoReady([a]);
a.send({ t: 'start' });
await nextOf(b, 'prepare', 0);
b.close();
await nextOf(a, 'play', 0);
stop();
});
test('player error 150 swaps the song for everyone under the same number and marks it unplayable', async () => {
seedLater(() => seed(3));
const { cls } = await room(['방장', '철수']);
const [a, b] = cls as [Client, Client];
a.send({ t: 'start' });
const first = await nextOf(a, 'prepare', 0);
const fa = since(a);
b.send({ t: 'audio', n: 1, ev: 'error', code: 150 });
const again = await nextOf(a, 'prepare', fa);
expect(again.n).toBe(1);
expect(again.videoId).not.toBe(first.videoId);
expect(s.db.query<{ youtube_status: string }, [string]>('SELECT youtube_status FROM songs WHERE youtube_id = ?').get(first.videoId)!.youtube_status).toBe('dead');
expect((await gameWhere(a, (g) => g.n === 1)).total).toBe(2);
});
test('skip votes over the connected players (1/2 of 2 → 1), hint votes when 직접선택, replay restarts the clip for all', async () => {
seedLater(() => seed(3));
const { users, cls } = await room(['방장', '철수'], { skipVotes: '2/3', hint: 'manual', hintVotes: '1', replayVotes: '1/2', listenSec: 10 });
const [a, b] = cls as [Client, Client];
const stop = autoReady(cls);
a.send({ t: 'start' });
const p = await nextOf(a, 'play', 0);
await sleep(p.startAt - Date.now() + 80);
let g = await gameWhere(a, (x) => x.phase === 'play');
expect(g.need).toEqual({ skip: 2, hint: 1, replay: 1 });
a.send({ t: 'vote', kind: 'hint' });
g = await gameWhere(a, (x) => !!x.hint);
expect(g.hint).toMatch(/^ㄴㄹ\d+$/);
const fa = since(a);
b.send({ t: 'vote', kind: 'replay' });
const re = await nextOf(a, 'prepare', fa);
expect(re.startSec).toBe(0);
const rp = await nextOf(a, 'play', fa);
expect(rp.atSec).toBe(0);
a.send({ t: 'vote', kind: 'skip' });
g = await gameWhere(a, (x) => x.votes.skip.length === 1);
expect(g.phase).toBe('play');
a.send({ t: 'vote', kind: 'skip' }); // toggle off
await gameWhere(a, (x) => x.votes.skip.length === 0);
a.send({ t: 'vote', kind: 'skip' });
b.send({ t: 'vote', kind: 'skip' });
g = await gameWhere(a, (x) => x.phase === 'reveal');
expect(g.history[0]!.how).toBe('skip');
expect(chatLines(a).find((l) => l.answer)?.text).toContain('스킵');
expect(users.length).toBe(2);
stop();
});
test('hint off / timed: the server explains instead of counting the vote', async () => {
seedLater(() => seed(2));
const { cls } = await room(['방장'], { hint: 30 });
const [a] = cls as [Client];
const stop = autoReady(cls);
a.send({ t: 'start' });
await nextOf(a, 'play', 0);
a.send({ t: 'vote', kind: 'hint' });
expect(((await a.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toMatch(/힌트는 \d+초 뒤에 공개돼요/);
stop();
});
test('somebody joining mid-game plays from the next question', async () => {
seedLater(() => seed(3));
const { cls, code } = await room(['방장']);
const [a] = cls as [Client];
const stop = autoReady(cls);
a.send({ t: 'start' });
await nextOf(a, 'play', 0);
const c = await guest(s.base, '늦게옴');
const cc = await new Client(s.base, c.cookie).connect();
cc.send({ t: 'join', code });
const g = await gameWhere(cc, (x) => x.phase === 'play');
expect(g.participants).not.toContain(c.id);
expect(cc.messages.some((m) => m.t === 'prepare')).toBe(false);
stop();
cc.close();
});
test('result → 이어풀기 leaves out the songs already asked and keeps the scores; 다시 하기 goes back with scores at 0', async () => {
let ids: number[] = [];
seedLater(() => (ids = seed(4)));
const { users, cls } = await room(['방장'], { count: 10 });
const [a] = cls as [Client];
const stop = autoReady(cls);
a.send({ t: 'start' });
const answerAll = async (round: number) => {
for (let n = 1; ; n++) {
const p = await nextOf(a, 'play', 0, (m) => m.n === n && !a.messages.some((x) => x.t === 'answer' && false));
await sleep(Math.max(0, p.startAt - Date.now()) + 10);
const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(last(a, 'prepare')!.videoId)!.title;
a.send({ t: 'chat', text: title });
const g = await gameWhere(a, (x) => x.history.length === n);
if (g.n >= g.total) return g;
await gameWhere(a, (x) => x.n === n + 1);
void round;
}
};
let g = await answerAll(1);
expect(g.total).toBe(4); // 10 asked, only 4 songs
g = await gameWhere(a, (x) => x.phase === 'result');
expect(g.scores[0]).toMatchObject({ id: users[0]!.id, score: 4 });
expect(g.left).toBe(0);
a.send({ t: 'game', action: 'continue' });
expect(((await a.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toContain('모두 풀었어요');
// two more songs appear: 이어풀기 plays only those, scores go on
const more = seed2(2);
const fa = since(a);
a.send({ t: 'game', action: 'continue' });
await gameWhere(a, (x) => x.phase !== 'result' && x.n === 1 && x.history.length === 0);
const asked: string[] = [];
for (let n = 1; n <= 2; n++) {
const pr = await nextOf(a, 'prepare', fa, (m) => m.n === n);
asked.push(pr.videoId);
const p = await nextOf(a, 'play', fa, (m) => m.n === n);
await sleep(Math.max(0, p.startAt - Date.now()) + 10);
const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(pr.videoId)!.title;
a.send({ t: 'chat', text: title });
await gameWhere(a, (x) => x.history.length === n);
}
expect(asked.sort()).toEqual(more.sort());
g = await gameWhere(a, (x) => x.phase === 'result');
expect(g.scores[0]!.score).toBe(6);
const fb = since(a);
a.send({ t: 'game', action: 'again' });
await nextOf(a, 'game', fb, (m) => m.game === null);
expect(s.rooms.roomOf(users[0]!.id)!.status).toBe('lobby');
expect(s.rooms.roomOf(users[0]!.id)!.quiz.scores.size).toBe(0);
expect(ids.length).toBe(4);
stop();
function seed2(k: number) {
const c = new Catalog(s.db);
const vids: string[] = [];
for (let i = 1; i <= k; i++) {
const [id] = c.upsert({ title: `추가곡${i}`, artists: [{ name: `추가가수${i}` }], year: 2020, genres: ['kpop'], source: 't', ref: `m${i}` });
c.autoLevel(id!, 'all', 3);
s.db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = ?, duration_sec = 200 WHERE id = ?").run(`more${i}`, id!);
vids.push(`more${i}`);
}
return vids;
}
});
test('host can end the game; the same singer never plays twice in a row when others are left', async () => {
seedLater(() => seed(6, { artist: (i) => (i <= 3 ? '같은가수' : `가수${i}`) }));
const { cls } = await room(['방장']);
const [a] = cls as [Client];
const stop = autoReady(cls);
a.send({ t: 'start' });
const order: string[] = [];
for (let n = 1; n <= 6; n++) {
const pr = await nextOf(a, 'prepare', 0, (m) => m.n === n);
order.push(s.db.query<{ artist: string }, [string]>('SELECT artist FROM songs WHERE youtube_id = ?').get(pr.videoId)!.artist);
a.send({ t: 'vote', kind: 'skip' });
await gameWhere(a, (x) => x.history.length === n);
}
for (let i = 1; i < order.length; i++) if (order[i] === '같은가수') expect(order[i - 1]).not.toBe('같은가수');
await gameWhere(a, (x) => x.phase === 'result');
stop();
});
test('lyrics mode: no audio, a masked lyrics card, the answer still counts', async () => {
seedLater(() => seed(2, { lyrics: true }));
const { users, cls } = await room(['방장'], { mode: 'lyrics' });
const [a] = cls as [Client];
a.send({ t: 'start' });
const g = await gameWhere(a, (x) => x.phase === 'play' && !!x.lyrics);
expect(a.messages.some((m) => m.t === 'prepare')).toBe(false);
expect(g.lyrics!.length).toBe(4);
expect(g.lyrics!.join('\n')).not.toMatch(/노래\d/);
expect(g.lyrics!.join('\n')).toContain('○○○');
await sleep(Math.max(0, g.startAt! - Date.now()) + 10);
const n = /첫 줄 (\d)/.exec(g.lyrics!.join('\n'))?.[1];
a.send({ t: 'chat', text: `노래${n}` });
const r = await gameWhere(a, (x) => x.phase === 'reveal');
expect(r.history[0]!.winnerId).toBe(users[0]!.id);
});
});
describe('퀴즈 저장·불러오기 (docs/12 Q8)', () => {
test('guests cannot save; a Discord host saves, loads in a new room, and players keep their scores', async () => {
seedLater(() => seed(3));
const { cls } = await room(['손님방장'], { count: 10 });
const [g] = cls as [Client];
g.send({ t: 'save', name: '안됨' });
expect(((await g.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toContain('디스코드');
g.close();
const login = await discordLogin(s.base, '700000000000000011');
const cookie = login.cookie!;
const me = (await api(s.base, '/api/me', { cookie })).body.me;
const code = (await api(s.base, '/api/rooms', { method: 'POST', cookie, body: JSON.stringify({ config: { count: 10, level: 3 } }) })).body.code;
const a = await new Client(s.base, cookie).connect();
a.send({ t: 'join', code });
await a.waitFor((m) => m.t === 'room');
a.send({ t: 'save', name: '빈퀴즈' });
expect(((await a.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toContain('아직 푼 문제가');
const stop = autoReady([a]);
a.send({ t: 'start' });
const p = await nextOf(a, 'play', 0, (m) => m.n === 1);
await sleep(Math.max(0, p.startAt - Date.now()) + 10);
const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(last(a, 'prepare')!.videoId)!.title;
a.send({ t: 'chat', text: title });
await gameWhere(a, (x) => x.history.length === 1);
a.send({ t: 'save', name: '중간' });
expect(((await a.waitFor((m) => m.t === 'error' && m.message.includes('멈춘'))) as Msg<'error'>).message).toContain('멈춘');
a.send({ t: 'game', action: 'end' });
await gameWhere(a, (x) => x.phase === 'result');
a.send({ t: 'save', name: '금요일 퀴즈' });
const saved = (await a.waitFor((m) => m.t === 'saved')) as Msg<'saved'>;
const list = (await api(s.base, '/api/quizzes', { cookie })).body.quizzes;
expect(list).toEqual([expect.objectContaining({ id: saved.id, name: '금요일 퀴즈', questions: 1, players: 1 })]);
// a new room: load → start asks only the other 2 songs, the score goes on from 1
const fb = since(a);
a.send({ t: 'game', action: 'again' });
await nextOf(a, 'game', fb, (m) => m.game === null);
a.send({ t: 'config', patch: { level: 5 } });
a.send({ t: 'load', id: saved.id });
const r = (await a.waitFor((m) => m.t === 'room' && m.room.config.level === 3 && m.room.config.count === 10)) as Msg<'room'>;
expect(r.room.config.count).toBe(10);
a.send({ t: 'start' });
const gv = await gameWhere(a, (x) => x.phase !== 'result' && x.n === 1 && x.history.length === 0);
expect(gv.total).toBe(2);
expect(gv.scores[0]).toMatchObject({ id: me.id, score: 1 });
stop();
// only the owner can delete
expect((await api(s.base, `/api/quizzes/${saved.id}`, { method: 'DELETE', cookie })).res.status).toBe(200);
expect((await api(s.base, '/api/quizzes', { cookie })).body.quizzes).toEqual([]);
});
});

View File

@@ -0,0 +1,545 @@
/**
* Quiz engine (docs/05 게임 진행, docs/12 Q1·Q3·Q4·Q5·Q8). One per running game, owned by its Room.
*
* Playback rule (docs/12 Q1): the music moves only while every player of the question can hear it.
* prepare → everyone reports ready → play{startAt} for all → stall/blocked → everyone pauses, re-prepares at the same
* position → play again. The host may leave out someone not ready for 30s, nobody is dropped automatically.
* Two clocks: the clip stops by playback position (clients), the question clock runs from the first play and stops while
* everyone is paused; it keeps running after the clip ends.
*/
import { hintText, isCorrect, voteThreshold, type GameHistoryItem, type GamePhase, type GameView, type ServerMessage } from '@mq/shared';
import { clipOf, lyricsCard, mainArtists, markUnplayable, orderSongs, quizSong, type QuizSong } from '../songs/quiz';
import { poolIds } from '../songs/pool';
import type { Room } from '../rooms/manager';
export interface GameTiming {
/** 3·2·1 before the first play of a question. */
countdownMs: number;
revealMs: number;
/** Lead time for a resume / replay so every client starts together (docs/12 Q1: now + 800ms). */
resumeLeadMs: number;
/** A client that has not reported the clip end this long after the expected end gets one more stop (docs/12 Q1). */
clipGraceMs: number;
/** After this long not ready the host may leave the player out of this question. */
lateMs: number;
tickMs: number;
/** Tests only: replaces the site's question time limit for short clips. */
limitMs?: number;
}
export const DEFAULT_TIMING: GameTiming = { countdownMs: 3000, revealMs: 5000, resumeLeadMs: 800, clipGraceMs: 3000, lateMs: 30_000, tickMs: 200 };
export interface Score {
nickname: string;
score: number;
correct: number;
totalMs: number;
}
/** What 이어풀기 / 퀴즈 저장 carry over: songs asked so far and scores per account (docs/12 Q8). */
export interface Quiz {
played: number[];
scores: Map<string, Score>;
}
export const newQuiz = (): Quiz => ({ played: [], scores: new Map() });
/** Build the song order for a game. Returns an error message when nothing is left. */
export function pickSongs(room: Room): number[] | string {
const db = room.deps.db;
const ids = poolIds(db, room.config, room.quiz.played);
if (!ids.length) return room.quiz.played.length ? '조건에 맞는 곡을 모두 풀었어요.' : '조건에 맞는 곡이 없어요. 장르·연도·난이도를 넓혀 보세요.';
const recent = new Set(room.recent.flat());
return orderSongs(ids, recent, mainArtists(db, ids), room.config.mode !== 'artist');
}
export class Game {
phase: GamePhase = 'prepare';
n = 0;
total: number;
song: QuizSong | null = null;
private clip: { startSec: number; endSec: number | null } = { startSec: 0, endSec: null };
participants = new Set<string>();
excluded = new Set<string>();
private ready = new Set<string>();
private waitingSince = new Map<string, number>();
private awaitingReady = false;
private hostHold = false;
private resumeAt = 0;
private clipDone = new Set<string>();
clipOver = false;
paused: GameView['paused'] = null;
/** Audio timeline: position `audioAtSec` at server time `audioStartAt`; `playing` while it should be running. */
private audioStartAt = 0;
private audioAtSec = 0;
private playing = false;
startAt: number | null = null;
/** First music start of this question: answers count only after it. */
private firstStartAt: number | null = null;
private elapsedMs = 0;
private runningSince: number | null = null;
private limitMs: number | null = null;
hint: string | null = null;
private lyrics: string[] | null = null;
votes = { skip: new Set<string>(), hint: new Set<string>(), replay: new Set<string>() };
history: GameHistoryItem[] = [];
private revealUntil: number | null = null;
private timer: ReturnType<typeof setInterval> | null = null;
/** Songs this game asked, for the room's "last 3 games" list. */
private asked: number[] = [];
constructor(
private room: Room,
private list: number[],
private timing: GameTiming,
private now: () => number = Date.now,
) {
const c = room.config.count;
this.total = c ? Math.min(c, list.length) : list.length;
}
get listening(): boolean {
return this.room.config.mode !== 'lyrics';
}
start(): void {
this.timer = setInterval(() => this.tick(), this.timing.tickMs);
this.room.say(null, `게임을 시작해요! ${this.total}문제`);
this.next();
}
stop(): void {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
// ------------------------------------------------------------------ helpers
private online(id: string): boolean {
return this.room.isOnline(id);
}
/** Players of this question who are connected and not left out. */
active(): string[] {
return [...this.participants].filter((id) => this.online(id) && !this.excluded.has(id));
}
private toActive(m: ServerMessage): void {
for (const id of this.active()) this.room.send(m, id);
}
elapsed(now = this.now()): number {
return this.elapsedMs + (this.runningSince !== null && now > this.runningSince ? now - this.runningSince : 0);
}
private stopClock(now: number): void {
this.elapsedMs = this.elapsed(now);
this.runningSince = null;
}
private position(now: number): number {
if (!this.playing) return this.resumeAt;
const p = this.audioAtSec + Math.max(0, now - this.audioStartAt) / 1000;
return this.clip.endSec !== null ? Math.min(p, this.clip.endSec) : p;
}
private need(kind: 'skip' | 'hint' | 'replay'): number | null {
const c = this.room.config;
const rule = kind === 'skip' ? c.skipVotes : kind === 'hint' ? (c.hint === 'manual' ? c.hintVotes : 'none') : this.listening ? c.replayVotes : 'none';
return voteThreshold(rule, this.active().length);
}
// ------------------------------------------------------------------ question flow
private next(): void {
this.n++;
this.setup();
}
/** Load question `n` (also used when a song is replaced under the same number). */
private setup(): void {
const c = this.room.config;
this.total = c.count ? Math.min(c.count, this.list.length) : this.list.length;
let song: QuizSong | null = null;
while (this.n <= this.total) {
song = quizSong(this.room.deps.db, this.list[this.n - 1]!);
if (song && (this.listening ? song.videoId : song.lyrics)) break;
this.list.splice(this.n - 1, 1);
this.total = c.count ? Math.min(c.count, this.list.length) : this.list.length;
song = null;
}
if (!song) return this.finish();
const now = this.now();
this.song = song;
this.clip = this.listening ? clipOf(song, c) : { startSec: 0, endSec: null };
this.participants = new Set(this.room.online());
this.excluded.clear();
this.ready.clear();
this.waitingSince.clear();
this.clipDone.clear();
this.clipOver = false;
this.paused = null;
this.hostHold = false;
this.playing = false;
this.startAt = null;
this.firstStartAt = null;
this.elapsedMs = 0;
this.runningSince = null;
this.hint = null;
this.revealUntil = null;
for (const v of Object.values(this.votes)) v.clear();
if (this.listening) {
this.limitMs = c.listenSec === 0 ? null : (this.timing.limitMs ?? Math.max(this.room.limitSec() * 1000, c.listenSec * 1000 + 5000));
this.lyrics = null;
this.phase = 'prepare';
this.prepareAll(this.clip.startSec);
} else {
this.limitMs = c.lyricsSec ? c.lyricsSec * 1000 : null;
this.lyrics = lyricsCard(song.lyrics!, song.title);
this.phase = 'play';
this.startAt = this.firstStartAt = now + this.timing.countdownMs;
this.runningSince = this.startAt;
}
this.room.say(null, `${this.n}번째 문제`);
this.broadcast();
}
/** Everyone loads/seeks muted to `atSec` and reports ready (docs/12 Q1 준비 단계). */
private prepareAll(atSec: number): void {
const now = this.now();
this.resumeAt = atSec;
this.awaitingReady = true;
this.ready.clear();
this.waitingSince.clear();
for (const id of this.active()) this.waitingSince.set(id, now);
this.toActive({ t: 'prepare', code: this.room.code, n: this.n, videoId: this.song!.videoId!, startSec: atSec, endSec: this.clip.endSec });
}
private checkReady(): void {
if (!this.awaitingReady || this.hostHold || (this.phase !== 'prepare' && this.phase !== 'play')) return;
const act = this.active();
if (!act.length) {
// Everyone of this question is gone: whoever is here now plays it.
const online = this.room.online();
if (!online.length) return;
this.participants = new Set(online);
this.excluded.clear();
return this.prepareAll(this.resumeAt);
}
if (!act.every((id) => this.ready.has(id))) return;
const now = this.now();
const first = this.firstStartAt === null;
const startAt = now + (first ? this.timing.countdownMs : this.timing.resumeLeadMs);
this.awaitingReady = false;
this.waitingSince.clear();
this.paused = null;
this.phase = 'play';
this.startAt = startAt;
if (first) this.firstStartAt = startAt;
this.audioStartAt = startAt;
this.audioAtSec = this.resumeAt;
this.playing = true;
this.runningSince = startAt;
this.toActive({ t: 'play', code: this.room.code, n: this.n, startAt, atSec: this.resumeAt, endSec: this.clip.endSec });
this.broadcast();
}
/** Stop everyone at the same position (buffering / no sound / host). */
private pauseAll(reason: 'stall' | 'blocked' | 'host', who: string[]): void {
const now = this.now();
const pos = this.position(now);
this.stopClock(now);
this.playing = false;
this.resumeAt = pos;
this.paused = { reason, who };
this.toActive({ t: 'pause', code: this.room.code, n: this.n });
if (reason === 'host') {
this.hostHold = true;
this.awaitingReady = false;
} else if (this.listening) this.prepareAll(pos);
this.broadcast();
}
private endClip(): void {
if (this.clipOver) return;
this.clipOver = true;
this.resumeAt = this.position(this.now());
this.playing = false;
// 끝까지: the song is over, so is the question (docs/05 문제 진행).
if (this.room.config.listenSec === 0) return this.endQuestion(null, 'timeout');
this.broadcast();
}
private showHint(): void {
if (this.hint || !this.song) return;
this.hint = hintText(this.song, this.room.config.answer);
if (this.lyrics && this.song.lyrics) this.lyrics = lyricsCard(this.song.lyrics, this.song.title, 1);
this.votes.hint.clear();
this.room.say(null, `힌트가 공개됐어요: ${this.hint}`);
this.broadcast();
}
private replay(): void {
if (!this.listening || !this.song) return;
for (const v of Object.values(this.votes)) v.clear();
this.clipDone.clear();
this.clipOver = false;
// 짧은 클립: the time limit counts again from the replay (docs/12 Q4).
this.elapsedMs = 0;
this.runningSince = null;
this.playing = false;
this.paused = null;
this.hostHold = false;
this.toActive({ t: 'pause', code: this.room.code, n: this.n });
this.room.say(null, '다 같이 다시 들어요');
this.prepareAll(this.clip.startSec);
this.broadcast();
}
private endQuestion(winner: string | null, how: GameHistoryItem['how'], chat?: { text: string; n?: string }): void {
if ((this.phase !== 'prepare' && this.phase !== 'play') || !this.song) return;
const now = this.now();
const ms = winner ? this.elapsed(now) : null;
const s = this.song;
if (winner) {
const sc = this.room.quiz.scores.get(winner) ?? { nickname: this.room.nick(winner), score: 0, correct: 0, totalMs: 0 };
sc.nickname = this.room.nick(winner);
sc.score += 1;
sc.correct += 1;
sc.totalMs += ms!;
this.room.quiz.scores.set(winner, sc);
}
this.history.push({
n: this.n,
title: s.title,
artist: s.artist,
year: s.year,
level: s.level,
genres: s.genres,
videoId: s.videoId,
winnerId: winner,
winner: winner ? this.room.nick(winner) : null,
ms,
how,
});
this.room.quiz.played.push(s.id);
this.asked.push(s.id);
const answer = `${s.title} - ${s.artist}`;
if (winner) this.room.post({ userId: winner, text: chat!.text, n: chat!.n, answer: { text: answer } });
else this.room.post({ userId: null, text: how === 'skip' ? '스킵했어요 · 정답자 없음' : '시간이 다 됐어요 · 정답자 없음', answer: { text: answer, none: true } });
this.stopClock(now);
this.awaitingReady = false;
this.hostHold = false;
this.paused = null;
this.playing = false;
this.phase = 'reveal';
this.revealUntil = now + this.timing.revealMs;
this.broadcast();
}
finish(): void {
if (this.phase === 'result') return;
this.phase = 'result';
this.playing = false;
this.awaitingReady = false;
this.paused = null;
this.stopClock(this.now());
this.stop();
if (this.asked.length) {
this.room.recent.push(this.asked);
while (this.room.recent.length > 3) this.room.recent.shift();
}
this.toActive({ t: 'pause', code: this.room.code, n: this.n });
this.room.say(null, '게임이 끝났어요');
this.broadcast();
}
tick(now = this.now()): void {
if (this.phase === 'reveal') {
if (this.revealUntil !== null && now >= this.revealUntil) {
if (this.n >= this.total) this.finish();
else this.next();
}
return;
}
if (this.phase !== 'play') return;
const el = this.elapsed(now);
const c = this.room.config;
if (typeof c.hint === 'number' && !this.hint && this.runningSince !== null && el >= c.hint * 1000) this.showHint();
if (this.limitMs !== null && el >= this.limitMs) return this.endQuestion(null, 'timeout');
if (this.playing && !this.clipOver && this.clip.endSec !== null) {
const expectedEnd = this.audioStartAt + (this.clip.endSec - this.audioAtSec) * 1000;
if (now > expectedEnd + this.timing.clipGraceMs) {
// Clients that did not report the end get one more stop; the question goes on (docs/12 Q1 재생 길이).
for (const id of this.active()) if (!this.clipDone.has(id)) this.room.send({ t: 'pause', code: this.room.code, n: this.n }, id);
this.endClip();
}
}
}
// ------------------------------------------------------------------ inputs
onAudio(userId: string, n: number, ev: 'ready' | 'blocked' | 'stall' | 'clipEnd' | 'error', code?: number): void {
if (n !== this.n || !this.participants.has(userId) || this.excluded.has(userId) || !this.listening) return;
if (ev === 'ready') {
if (!this.awaitingReady) return;
this.ready.add(userId);
this.waitingSince.delete(userId);
this.checkReady();
this.broadcast();
return;
}
if (ev === 'stall' || ev === 'blocked') {
if (this.phase !== 'play' || this.clipOver) return;
if (this.paused) {
if (!this.paused.who.includes(userId)) this.paused = { ...this.paused, who: [...this.paused.who, userId] };
this.ready.delete(userId);
if (!this.waitingSince.has(userId) && this.awaitingReady) this.waitingSince.set(userId, this.now());
return this.broadcast();
}
if (!this.playing) return;
return this.pauseAll(ev, [userId]);
}
if (ev === 'clipEnd') {
if (this.phase !== 'play' || !this.playing) return;
this.clipDone.add(userId);
if (this.active().every((id) => this.clipDone.has(id))) this.endClip();
return;
}
if (ev === 'error' && (code === 100 || code === 101 || code === 150) && (this.phase === 'prepare' || this.phase === 'play') && this.song) {
// The video is gone or may not be embedded: swap the song for everyone, same question number (docs/12 Q1).
markUnplayable(this.room.deps.db, this.song.id, code);
this.room.say(null, '이 곡은 재생할 수 없어서 다른 곡으로 바꿨어요');
this.toActive({ t: 'pause', code: this.room.code, n: this.n });
this.list.splice(this.n - 1, 1);
this.setup();
}
}
/** Is this chat line the answer? Then it becomes the 정답 줄 + 5줄 블록 (docs/06) and true is returned. */
judge(userId: string, text: string, n?: string): boolean {
if (this.phase !== 'play' || !this.song || this.firstStartAt === null || this.now() < this.firstStartAt) return false;
if (!this.participants.has(userId) || this.excluded.has(userId)) return false;
if (!isCorrect(text, this.song, this.room.config.answer, this.room.config.strict)) return false;
this.endQuestion(userId, 'correct', { text, n });
return true;
}
vote(userId: string, kind: 'skip' | 'hint' | 'replay'): string | null {
if (this.phase !== 'play' && this.phase !== 'prepare') return '지금은 투표할 수 없어요.';
if (!this.active().includes(userId)) return '이번 문제에 참가하고 있지 않아요.';
const c = this.room.config;
if (kind === 'hint') {
if (c.hint === 'none') return '이 방은 힌트가 꺼져 있어요.';
if (this.hint) return '이미 공개된 힌트예요.';
if (c.hint !== 'manual') {
const left = Math.max(1, Math.ceil(c.hint - (this.elapsed() / 1000)));
return `힌트는 ${left}초 뒤에 공개돼요.`;
}
}
if (kind === 'replay') {
if (!this.listening) return '가사 모드에는 다시듣기가 없어요.';
if (c.replayVotes === 'none') return '이 방은 다시듣기가 꺼져 있어요.';
if (this.phase !== 'play' || this.firstStartAt === null) return '노래가 나오면 다시듣기를 누를 수 있어요.';
}
if (kind === 'skip' && c.skipVotes === 'none') return '이 방은 스킵이 꺼져 있어요.';
const set = this.votes[kind];
if (set.has(userId)) set.delete(userId);
else set.add(userId);
this.checkVotes();
this.broadcast();
return null;
}
private checkVotes(): void {
const act = new Set(this.active());
for (const v of Object.values(this.votes)) for (const id of v) if (!act.has(id)) v.delete(id);
const pass = (k: 'skip' | 'hint' | 'replay') => {
const need = this.need(k);
return need !== null && this.votes[k].size >= need;
};
if (pass('skip')) return this.endQuestion(null, 'skip');
if (pass('hint') && this.phase === 'play') this.showHint();
if (pass('replay') && this.phase === 'play' && this.firstStartAt !== null) this.replay();
}
/** A player went offline or left: do not wait for them, drop their votes (docs/05 진행 중 나간 사람). */
onGone(userId: string): void {
if (this.phase !== 'prepare' && this.phase !== 'play') return this.broadcast();
this.waitingSince.delete(userId);
if (this.paused?.who.includes(userId)) this.paused = { ...this.paused, who: this.paused.who.filter((x) => x !== userId) };
this.checkVotes();
if ((this.phase as GamePhase) !== 'play' && (this.phase as GamePhase) !== 'prepare') return;
this.checkReady();
if (this.playing && this.active().length && this.active().every((id) => this.clipDone.has(id))) this.endClip();
this.broadcast();
}
/** Host: leave out someone who has not been ready for 30s (docs/12 Q1). */
exclude(target: string): string | null {
const since = this.waitingSince.get(target);
if (!this.awaitingReady || since === undefined) return '음원을 기다리는 사람이 아니에요.';
if (this.now() - since < this.timing.lateMs) return '30초가 지나야 뺄 수 있어요.';
this.excluded.add(target);
this.waitingSince.delete(target);
this.room.say(null, `${this.room.nick(target)}님은 음원을 불러오지 못해 이번 문제에서 빠져요`);
this.checkReady();
this.broadcast();
return null;
}
hostPause(on: boolean): string | null {
if (this.phase !== 'play' && this.phase !== 'prepare') return '지금은 멈출 수 없어요.';
if (on) {
if (this.hostHold) return null;
if (this.playing) {
this.pauseAll('host', []);
return null;
}
this.stopClock(this.now());
this.hostHold = true;
this.paused = { reason: 'host', who: [] };
this.broadcast();
return null;
}
if (!this.hostHold) return null;
this.hostHold = false;
this.paused = null;
if (this.phase === 'play' && this.firstStartAt !== null && this.listening && !this.clipOver) this.prepareAll(this.resumeAt);
else if (this.phase === 'play' && this.firstStartAt !== null) this.runningSince = this.now();
else this.checkReady();
this.broadcast();
return null;
}
// ------------------------------------------------------------------ view
view(): GameView {
const players = new Map<string, boolean>();
for (const [id] of this.room.players) players.set(id, this.online(id));
const scores = new Map(this.room.quiz.scores);
const ids = new Set([...players.keys(), ...[...scores].filter(([, s]) => s.score > 0).map(([id]) => id)]);
const c = this.room.config;
return {
phase: this.phase,
n: this.n,
total: this.total,
mode: c.mode,
participants: [...this.participants],
excluded: [...this.excluded],
waiting: this.awaitingReady ? [...this.waitingSince].map(([id, since]) => ({ id, since })) : [],
paused: this.paused,
startAt: this.startAt,
clock: { elapsedMs: this.elapsedMs, runningSince: this.runningSince, limitMs: this.limitMs },
clipSec: this.clip.endSec !== null ? this.clip.endSec - this.clip.startSec : null,
clipOver: this.clipOver,
hint: this.hint,
hintAtSec: typeof c.hint === 'number' ? c.hint : null,
lyrics: this.lyrics,
votes: { skip: [...this.votes.skip], hint: [...this.votes.hint], replay: [...this.votes.replay] },
need: { skip: this.need('skip'), hint: this.need('hint'), replay: this.need('replay') },
scores: [...ids]
.map((id) => {
const s = scores.get(id);
return { id, nickname: players.has(id) ? this.room.nick(id) : (s?.nickname ?? '?'), score: s?.score ?? 0, correct: s?.correct ?? 0, avgMs: s?.correct ? Math.round(s.totalMs / s.correct) : null, online: players.get(id) ?? false };
})
.sort((a, b) => b.score - a.score || (a.avgMs ?? Infinity) - (b.avgMs ?? Infinity) || a.nickname.localeCompare(b.nickname)),
history: this.history,
revealUntil: this.revealUntil,
left: Math.max(0, this.list.length - this.asked.length),
};
}
broadcast(): void {
this.room.send({ t: 'game', code: this.room.code, game: this.view() });
}
}

View File

@@ -0,0 +1,57 @@
/** 퀴즈 저장·불러오기 (docs/12 Q8): Discord accounts only, 20 per account, deleted only by the owner. */
import type { Database } from 'bun:sqlite';
import { applyConfigPatch, DEFAULT_ROOM_CONFIG, type RoomConfig } from '@mq/shared';
import type { Quiz, Score } from './engine';
export const SAVE_LIMIT = 20;
export interface SavedQuizRow {
id: number;
name: string;
questions: number;
players: number;
updatedAt: number;
}
export class SavedQuizzes {
constructor(private db: Database) {}
list(userId: string): SavedQuizRow[] {
return this.db
.query<{ id: number; name: string; questions: number; scores_json: string; updated_at: number }, [string]>(
'SELECT id, name, questions, scores_json, updated_at FROM saved_quizzes WHERE user_id = ? ORDER BY updated_at DESC',
)
.all(userId)
.map((r) => ({ id: r.id, name: r.name, questions: r.questions, players: (JSON.parse(r.scores_json) as unknown[]).length, updatedAt: r.updated_at }));
}
save(userId: string, name: string, config: RoomConfig, quiz: Quiz, now = Date.now()): number | string {
const n = this.db.query<{ n: number }, [string]>('SELECT COUNT(*) n FROM saved_quizzes WHERE user_id = ?').get(userId)!.n;
if (n >= SAVE_LIMIT) return `퀴즈는 ${SAVE_LIMIT}개까지 저장할 수 있어요. 안 쓰는 퀴즈를 지워 주세요.`;
const scores = [...quiz.scores].map(([id, s]) => ({ id, ...s }));
const r = this.db
.query<{ id: number }, [string, string, string, string, string, number, number, number]>(
'INSERT INTO saved_quizzes (user_id, name, config_json, played_json, scores_json, questions, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id',
)
.get(userId, name, JSON.stringify(config), JSON.stringify(quiz.played), JSON.stringify(scores), quiz.played.length, now, now)!;
return r.id;
}
load(userId: string, id: number): { name: string; config: RoomConfig; quiz: Quiz } | null {
const r = this.db
.query<{ name: string; config_json: string; played_json: string; scores_json: string }, [number, string]>(
'SELECT name, config_json, played_json, scores_json FROM saved_quizzes WHERE id = ? AND user_id = ?',
)
.get(id, userId);
if (!r) return null;
// Settings saved by an older version: whatever no longer validates falls back to the default.
const merged = applyConfigPatch(DEFAULT_ROOM_CONFIG, JSON.parse(r.config_json));
const config = typeof merged === 'string' ? DEFAULT_ROOM_CONFIG : merged;
const scores = new Map<string, Score>((JSON.parse(r.scores_json) as ({ id: string } & Score)[]).map(({ id: uid, ...s }) => [uid, s]));
return { name: r.name, config, quiz: { played: JSON.parse(r.played_json) as number[], scores } };
}
remove(userId: string, id: number): boolean {
return this.db.query('DELETE FROM saved_quizzes WHERE id = ? AND user_id = ?').run(id, userId).changes > 0;
}
}

View File

@@ -246,6 +246,19 @@ export function createHttpApp(d: HttpDeps) {
return c.json(countPool(d.db, cfg));
});
// ------------------------------------------------------------ saved quizzes (docs/12 Q8)
app.get('/api/quizzes', (c) => {
const u = userOf(c);
if (!u) return c.json({ error: '로그인이 필요해요.' }, 401);
return c.json({ quizzes: d.rooms.saved.list(u) });
});
app.delete('/api/quizzes/:id', (c) => {
const u = userOf(c);
if (!u) return c.json({ error: '로그인이 필요해요.' }, 401);
return d.rooms.saved.remove(u, Number(c.req.param('id'))) ? c.json({ ok: true }) : c.json({ error: '저장한 퀴즈를 찾을 수 없어요.' }, 404);
});
app.route('/api/admin', createAdminApp({ ...d.admin, users: d.users, sessions: d.sessions, roles: d.roles, settings: d.settings }));
app.all('/api/*', (c) => c.json({ error: '없는 주소예요.' }, 404));

View File

@@ -219,6 +219,18 @@ describe('rooms over WebSocket', () => {
expect(await ca.waitFor((m) => m.t === 'error' && m.n === 'blank')).toMatchObject({ message: '빈 메시지는 보낼 수 없어요.' });
});
test('the last player leaving closes the room at once (← 방 목록 / 나가기)', async () => {
const { ca, cb, code } = await setup();
cb.send({ t: 'leave' });
await nextRoom(ca, (r) => r.players.length === 1);
expect(s.rooms.get(code)).toBeDefined();
ca.send({ t: 'leave' });
await ca.waitFor((m) => m.t === 'left');
expect(s.rooms.get(code)).toBeUndefined();
expect((await api(s.base, `/api/rooms/${code}`)).res.status).toBe(404);
expect((await api(s.base, '/api/rooms')).body.rooms).toEqual([]);
});
test('a room created but never entered expires like an empty room', async () => {
s = boot();
const a = await guest(s.base, '만들기만');

View File

@@ -1,10 +1,12 @@
/**
* Rooms and waiting room (docs/04, docs/05 중간 입장·퇴장·방장). In memory; unlimited players (no seats).
* Stage 4: join/leave, host, kick, ready, settings with live song count. Games start in stage 5.
* join/leave, host, kick, ready, settings with live song count; the game itself lives in game/engine.ts.
*/
import type { Database } from 'bun:sqlite';
import type { ServerWebSocket } from 'bun';
import { DEFAULT_ROOM_CONFIG, applyConfigPatch, configSummary, type ChatLine, type RoomConfig, type RoomView, type ServerMessage } from '@mq/shared';
import { DEFAULT_TIMING, Game, newQuiz, pickSongs, type GameTiming, type Quiz } from '../game/engine';
import { SavedQuizzes } from '../game/saved';
import { artistsByIds, countPool } from '../songs/pool';
import type { WsData } from '../ws/gateway';
@@ -36,12 +38,20 @@ export class Room {
emptySince: number | null = null;
chat: ChatLine[] = [];
private seq = 0;
game: Game | null = null;
/** Songs asked and scores of this quiz: kept by 이어풀기, cleared by 다시 하기, restored by 불러오기 (docs/12 Q8). */
quiz: Quiz = newQuiz();
/** Songs of the room's last 3 games: pushed to the back of the next order (docs/05). */
recent: number[][] = [];
/** Who is typing, until when (docs/06 입력 중). */
typing = new Map<string, number>();
typingSent = '';
constructor(
readonly code: string,
hostId: string,
config: RoomConfig,
private deps: { db: Database; user: PublicUserLookup },
readonly deps: { db: Database; user: PublicUserLookup; limitSec?: () => number },
) {
this.hostId = hostId;
this.config = config;
@@ -56,6 +66,15 @@ export class Room {
return [...this.players].filter(([, p]) => p.conns.size > 0).map(([id]) => id);
}
isOnline(id: string): boolean {
return (this.players.get(id)?.conns.size ?? 0) > 0;
}
/** Question time limit for short clips (site setting, docs/05). */
limitSec(): number {
return this.deps.limitSec?.() ?? 60;
}
view(): RoomView {
return {
code: this.code,
@@ -83,11 +102,17 @@ export class Room {
/** Relays at once (docs/12 채팅 무조건 실시간). userId null = system line (입장/퇴장/방장). */
say(userId: string | null, text: string, n?: string): ChatLine {
const line: ChatLine = { seq: ++this.seq, at: Date.now(), userId, nickname: userId ? (this.deps.user(userId)?.nickname ?? '?') : '', text };
if (n) line.n = n;
return this.post({ userId, text, n });
}
/** Any log line; with `answer` it goes out as one `answer` message so nothing can come between the line and its block (docs/06). */
post(p: { userId: string | null; text: string; n?: string; answer?: ChatLine['answer'] }): ChatLine {
const line: ChatLine = { seq: ++this.seq, at: Date.now(), userId: p.userId, nickname: p.userId ? (this.deps.user(p.userId)?.nickname ?? '?') : '', text: p.text };
if (p.n) line.n = p.n;
if (p.answer) line.answer = p.answer;
this.chat.push(line);
if (this.chat.length > CHAT_HISTORY) this.chat.shift();
this.send({ t: 'chat', code: this.code, line });
this.send(p.answer ? { t: 'answer', code: this.code, line } : { t: 'chat', code: this.code, line });
return line;
}
@@ -119,7 +144,23 @@ export class RoomManager {
/** userId → room code (one room at a time). */
private where = new Map<string, string>();
constructor(private deps: { db: Database; user: PublicUserLookup; genreName: (id: string) => string; log?: (msg: string, extra?: Record<string, unknown>) => void }) {}
readonly saved: SavedQuizzes;
private timing: GameTiming;
constructor(
private deps: {
db: Database;
user: PublicUserLookup;
genreName: (id: string) => string;
log?: (msg: string, extra?: Record<string, unknown>) => void;
/** Question time limit for short clips (site setting). */
limitSec?: () => number;
timing?: Partial<GameTiming>;
},
) {
this.saved = new SavedQuizzes(deps.db);
this.timing = { ...DEFAULT_TIMING, ...deps.timing };
}
private newCode(): string {
for (;;) {
@@ -187,7 +228,9 @@ export class RoomManager {
if (!room.players.has(room.hostId)) room.hostId = userId;
ws.send(JSON.stringify({ t: 'chatlog', code, lines: room.chat } satisfies ServerMessage));
room.broadcast();
if (!already) room.say(null, `${room.nick(userId)}님이 들어왔어요`);
if (room.game) room.game.broadcast();
else ws.send(JSON.stringify({ t: 'game', code, game: null } satisfies ServerMessage));
if (!already) room.say(null, room.game && room.game.phase !== 'result' ? `${room.nick(userId)}님이 들어왔어요 · 다음 문제부터 같이 해요` : `${room.nick(userId)}님이 들어왔어요`);
return null;
}
@@ -202,10 +245,12 @@ export class RoomManager {
if (p.conns.size === 0) {
p.offlineSince = Date.now();
p.ready = false;
room.typing.delete(ws.data.userId);
const wasHost = room.hostId === ws.data.userId;
if (wasHost) room.pickHost();
room.broadcast();
if (wasHost && room.hostId !== ws.data.userId) room.say(null, `방장이 ${room.nick(room.hostId)}님으로 바뀌었어요`);
room.game?.onGone(ws.data.userId);
}
}
@@ -220,9 +265,11 @@ export class RoomManager {
room.send({ t: 'left', code: room.code, reason }, userId);
for (const ws of p.conns) ws.data.roomCode = undefined;
room.players.delete(userId);
room.typing.delete(userId);
if (this.where.get(userId) === room.code) this.where.delete(userId);
if (room.players.size === 0) {
room.emptySince = Date.now();
// Nobody has a place any more (left, kicked out by time, went elsewhere): close the room at once.
this.close(room);
return;
}
const wasHost = room.hostId === userId;
@@ -230,6 +277,13 @@ export class RoomManager {
room.broadcast();
room.say(null, `${room.nick(userId)}님이 ${reason === 'kicked' ? '내보내졌어요' : '나갔어요'}`);
if (wasHost) room.say(null, `방장이 ${room.nick(room.hostId)}님으로 바뀌었어요`);
room.game?.onGone(userId);
}
close(room: Room): void {
room.game?.stop();
this.rooms.delete(room.code);
this.deps.log?.('room closed', { code: room.code });
}
/** Host-only actions. Returns an error message or null. */
@@ -291,21 +345,144 @@ export class RoomManager {
return null;
}
/** Chat line from a player in the room (docs/06). Flood guard is applied by the gateway. */
/** Chat line from a player in the room (docs/06). Judged as an answer and relayed in the same step; flood guard is in the gateway. */
chat(ws: ServerWebSocket<WsData>, text: string, n?: string): string | null {
const room = this.roomOf(ws.data.userId);
if (!room || ws.data.roomCode !== room.code) return '방에 들어가 있지 않아요.';
const t = text.replace(/[\u0000-\u001f\u007f]/g, ' ').trim();
if (!t) return '빈 메시지는 보낼 수 없어요.';
room.typing.delete(ws.data.userId);
if (room.game?.judge(ws.data.userId, t, n)) return null;
room.say(ws.data.userId, t, n);
return null;
}
/** Every 10s: drop players gone longer than the grace period, close rooms left empty. */
private inRoom(ws: ServerWebSocket<WsData>): Room | undefined {
const room = this.roomOf(ws.data.userId);
return room && ws.data.roomCode === room.code ? room : undefined;
}
// ------------------------------------------------------------------ game (docs/05)
start(ws: ServerWebSocket<WsData>): string | null {
return this.hostAction(ws, (room) => this.startGame(room));
}
private startGame(room: Room): string | null {
if (room.config.mode === 'artist' && !room.config.artistIds.length) return '가수를 1명 이상 골라 주세요.';
const list = pickSongs(room);
if (typeof list === 'string') return list;
room.game?.stop();
room.status = 'playing';
for (const p of room.players.values()) p.ready = false;
room.game = new Game(room, list, this.timing);
room.broadcast();
room.game.start();
this.deps.log?.('game started', { code: room.code, songs: list.length, total: room.game.total });
return null;
}
audio(ws: ServerWebSocket<WsData>, n: number, ev: 'ready' | 'blocked' | 'stall' | 'clipEnd' | 'error', code?: number): void {
this.inRoom(ws)?.game?.onAudio(ws.data.userId, n, ev, code);
}
vote(ws: ServerWebSocket<WsData>, kind: 'skip' | 'hint' | 'replay'): string | null {
const room = this.inRoom(ws);
if (!room?.game) return '게임 중이 아니에요.';
return room.game.vote(ws.data.userId, kind);
}
/** 입력 중 (docs/06): remembered for 3s, sent at most once a second by flushTyping. */
typing(ws: ServerWebSocket<WsData>, on: boolean): void {
const room = this.inRoom(ws);
if (!room) return;
if (on) room.typing.set(ws.data.userId, Date.now() + 3000);
else room.typing.delete(ws.data.userId);
}
flushTyping(now = Date.now()): void {
for (const room of this.rooms.values()) {
for (const [id, until] of room.typing) if (until < now) room.typing.delete(id);
const ids = [...room.typing.keys()];
const key = ids.join(',');
if (key === room.typingSent) continue;
room.typingSent = key;
room.send({ t: 'typing', code: room.code, ids });
}
}
gameAction(ws: ServerWebSocket<WsData>, action: 'pause' | 'resume' | 'end' | 'continue' | 'again'): string | null {
const room = this.inRoom(ws);
if (!room) return '방에 들어가 있지 않아요.';
if (room.hostId !== ws.data.userId) return '방장만 할 수 있어요.';
const g = room.game;
if (!g) return '게임 중이 아니에요.';
switch (action) {
case 'pause':
case 'resume':
return g.hostPause(action === 'pause');
case 'end':
g.finish();
return null;
case 'continue':
if (g.phase !== 'result') return '게임이 끝난 뒤에 이어 풀 수 있어요.';
return this.startGame(room);
case 'again':
// 다시 하기: same settings, back to the waiting room, scores from 0 (docs/12 Q8).
g.stop();
room.game = null;
room.status = 'lobby';
room.quiz = newQuiz();
room.recount();
room.broadcast();
room.send({ t: 'game', code: room.code, game: null });
room.say(null, '대기실로 돌아왔어요');
return null;
}
}
exclude(ws: ServerWebSocket<WsData>, target: string): string | null {
const room = this.inRoom(ws);
if (!room?.game) return '게임 중이 아니에요.';
if (room.hostId !== ws.data.userId) return '방장만 할 수 있어요.';
return room.game.exclude(target);
}
/** 퀴즈 저장 (docs/12 Q8): the host with a Discord account, in the waiting room, on the results or while paused. */
save(ws: ServerWebSocket<WsData>, name: string): string | null {
const room = this.inRoom(ws);
if (!room) return '방에 들어가 있지 않아요.';
if (room.hostId !== ws.data.userId) return '방장만 저장할 수 있어요.';
if (this.deps.user(ws.data.userId)?.kind !== 'member') return '퀴즈 저장은 디스코드로 로그인하면 쓸 수 있어요.';
const g = room.game;
if (g && g.phase !== 'result' && !g.paused) return '게임을 잠시 멈춘 뒤나 끝난 뒤에 저장할 수 있어요.';
if (!room.quiz.played.length) return '아직 푼 문제가 없어요.';
const id = this.saved.save(ws.data.userId, name, room.config, room.quiz);
if (typeof id === 'string') return id;
ws.send(JSON.stringify({ t: 'saved', id, name } satisfies ServerMessage));
room.say(null, `퀴즈를 "${name}"(으)로 저장했어요 · ${room.quiz.played.length}문제`);
return null;
}
/** 퀴즈 불러오기: settings, songs asked and scores come back; starting skips the songs already asked. */
load(ws: ServerWebSocket<WsData>, id: number): string | null {
return this.hostAction(ws, (room) => {
const q = this.saved.load(ws.data.userId, id);
if (!q) return '저장한 퀴즈를 찾을 수 없어요.';
room.config = { ...q.config, title: room.config.title, visibility: room.config.visibility };
room.quiz = q.quiz;
for (const p of room.players.values()) p.ready = false;
room.recount();
room.broadcast();
room.say(null, `"${q.name}" 퀴즈를 불러왔어요 · 지금까지 ${q.quiz.played.length}문제, 시작하면 이어서 나와요`);
return null;
});
}
/** Every 10s: drop players gone longer than the grace period, close rooms created but never entered. */
sweep(now = Date.now()): void {
for (const room of this.rooms.values()) {
for (const [id, p] of room.players) if (p.offlineSince && now - p.offlineSince > GRACE_MS) this.removePlayer(room, id, 'closed');
if (room.players.size === 0 && room.emptySince && now - room.emptySince > EMPTY_ROOM_MS) this.rooms.delete(room.code);
if (room.players.size === 0 && room.emptySince && now - room.emptySince > EMPTY_ROOM_MS) this.close(room);
}
}

View File

@@ -33,6 +33,8 @@ export interface StartOptions {
checkEmbed?: import('./http/admin').AdminDeps['checkEmbed'];
/** Upper bound for waiting on Bun's server.stop() (tests shorten it). */
stopWaitMs?: number;
/** Game pacing (tests and e2e shorten the countdown / reveal). */
gameTiming?: Partial<import('./game/engine').GameTiming>;
}
export function startServer(opts: StartOptions) {
@@ -54,6 +56,8 @@ export function startServer(opts: StartOptions) {
},
genreName: (id) => genreNames.get(id) ?? id,
log: (msg, extra) => log('info', msg, extra),
limitSec: () => settings.getSite().questionLimitSec,
timing: opts.gameTiming,
});
const gateway = new Gateway({
log,
@@ -140,6 +144,8 @@ export function startServer(opts: StartOptions) {
});
const roomSweeper = setInterval(() => rooms.sweep(), 10_000);
// 입력 중 goes out at most once a second (docs/06); chat itself never waits.
const typingFlush = setInterval(() => rooms.flushTyping(), 1000);
// The collector runs in its own process, so lobbies re-count now and then to show newly matched songs.
const roomRecount = setInterval(() => {
try {
@@ -161,6 +167,8 @@ export function startServer(opts: StartOptions) {
ready = false;
clearInterval(sweeper);
clearInterval(roomSweeper);
clearInterval(typingFlush);
for (const r of rooms.rooms.values()) r.game?.stop();
clearInterval(roomRecount);
gateway.shutdown();
await Promise.race([server.stop(true), Bun.sleep(opts.stopWaitMs ?? 1000)]);

View File

@@ -0,0 +1,165 @@
/**
* What a game needs about one song (docs/05): answer spellings, video, start position, reveal card, lyrics card.
*/
import type { Database } from 'bun:sqlite';
import type { RoomConfig } from '@mq/shared';
export interface QuizSong {
id: number;
title: string;
artist: string;
year: number | null;
durationSec: number | null;
videoId: string | null;
highlightSec: number | null;
genres: string[];
/** Level shown on the reveal card: the 'all' scope level when there is one. */
level: number | null;
titleAliases: string[];
artistAliases: string[];
/** Main artist ids (same singer not twice in a row, docs/05 출제 목록). */
artistIds: number[];
lyrics: string | null;
}
export function quizSong(db: Database, id: number): QuizSong | null {
const s = db
.query<
{ id: number; title: string; artist: string; year: number | null; duration_sec: number | null; youtube_id: string | null; highlight_sec: number | null; youtube_status: string; deleted_at: number | null },
[number]
>('SELECT id, title, artist, year, duration_sec, youtube_id, highlight_sec, youtube_status, deleted_at FROM songs WHERE id = ?')
.get(id);
if (!s || s.deleted_at) return null;
const col = <T>(sql: string) => db.query<{ v: T }, [number]>(sql).all(id).map((r) => r.v);
return {
id: s.id,
title: s.title,
artist: s.artist,
year: s.year,
durationSec: s.duration_sec,
videoId: s.youtube_status === 'matched' ? s.youtube_id : null,
highlightSec: s.highlight_sec,
genres: col<string>('SELECT genre_id v FROM song_genres WHERE song_id = ?'),
level: db.query<{ level: number }, [number]>("SELECT level FROM song_levels WHERE song_id = ? ORDER BY scope = 'all' DESC LIMIT 1").get(id)?.level ?? null,
titleAliases: col<string>("SELECT alias v FROM song_aliases WHERE song_id = ? AND part = 'title'"),
artistAliases: [
...col<string>("SELECT alias v FROM song_aliases WHERE song_id = ? AND part = 'artist'"),
...col<string>('SELECT x.alias v FROM song_artists sa JOIN artist_aliases x ON x.artist_id = sa.artist_id WHERE sa.song_id = ?'),
...col<string>('SELECT a.name v FROM song_artists sa JOIN artists a ON a.id = sa.artist_id WHERE sa.song_id = ?'),
],
artistIds: col<number>("SELECT artist_id v FROM song_artists WHERE song_id = ? AND role = 'main' ORDER BY artist_id"),
lyrics: db.query<{ text: string }, [number]>('SELECT text FROM lyrics WHERE song_id = ?').get(id)?.text ?? null,
};
}
/** First main artist per song, for spreading singers apart. */
export function mainArtists(db: Database, ids: number[]): Map<number, number> {
const out = new Map<number, number>();
for (let i = 0; i < ids.length; i += 500) {
const chunk = ids.slice(i, i + 500);
for (const r of db
.query<{ song_id: number; a: number }, number[]>(`SELECT song_id, MIN(artist_id) a FROM song_artists WHERE song_id IN (${chunk.map(() => '?').join(',')}) GROUP BY song_id`)
.all(...chunk))
out.set(r.song_id, r.a);
}
return out;
}
/** The video stopped working for everyone (deleted 100, embedding off 101/150): the admin sees it as 재생 불가 (docs/12 Q1). */
export function markUnplayable(db: Database, id: number, code: number): void {
db.query("UPDATE songs SET youtube_status = 'dead', note = trim(coalesce(note, '') || ' ' || ?), updated_at = ? WHERE id = ? AND youtube_status = 'matched'").run(
`[재생 오류 ${code}]`,
Date.now(),
id,
);
}
/** Where playback starts and how long the clip is (docs/04 재생위치, docs/08 하이라이트). */
export function clipOf(song: QuizSong, c: RoomConfig): { startSec: number; endSec: number | null } {
const dur = song.durationSec;
let start = 0;
if (c.startAt === 'highlight') start = song.highlightSec ?? (dur ? Math.round(dur * 0.3) : 0);
if (dur && start > dur - 5) start = 0;
if (c.listenSec === 0) return { startSec: start, endSec: dur };
const end = start + c.listenSec;
return { startSec: start, endSec: dur ? Math.min(end, dur) : end };
}
/** Shuffle, push back songs from the room's last 3 games, keep the same singer apart (docs/05 출제 목록 뽑기). */
export function orderSongs(ids: number[], recent: Set<number>, artistOf: Map<number, number>, spreadArtists: boolean, rnd = Math.random): number[] {
const shuffle = (xs: number[]) => {
for (let i = xs.length - 1; i > 0; i--) {
const j = Math.floor(rnd() * (i + 1));
[xs[i], xs[j]] = [xs[j]!, xs[i]!];
}
return xs;
};
const list = [...shuffle(ids.filter((x) => !recent.has(x))), ...shuffle(ids.filter((x) => recent.has(x)))];
if (!spreadArtists) return list;
// Greedy: keep the order, but take the first song whose singer differs from the previous one. When one singer holds more
// than half of what is left, that singer must go now or it would have to repeat later.
const count = new Map<number, number>();
for (const id of list) {
const a = artistOf.get(id);
if (a !== undefined) count.set(a, (count.get(a) ?? 0) + 1);
}
const maxInitial = Math.max(0, ...count.values());
const rest = [...list];
const out: number[] = [];
let prev: number | undefined;
while (rest.length) {
let pick = -1;
if (rest.length < 2 * maxInitial + 2) {
let top: number | undefined;
let topN = 0;
for (const [a, n] of count) if (n > topN) ((top = a), (topN = n));
if (top !== undefined && top !== prev && topN > (rest.length + 1) / 2 - 1) pick = rest.findIndex((x) => artistOf.get(x) === top);
}
if (pick < 0) pick = rest.findIndex((x) => prev === undefined || artistOf.get(x) !== prev);
if (pick < 0) pick = 0;
const [id] = rest.splice(pick, 1);
const a = artistOf.get(id!);
if (a !== undefined) count.set(a, count.get(a)! - 1);
prev = a;
out.push(id!);
}
return out;
}
const norm = (s: string) => s.normalize('NFKC').toLowerCase().replace(/[^\p{L}\p{N}]/gu, '');
/**
* 가사 card (docs/08 4. 가사): verse lines (not the repeated chorus), 4 from the middle, then 2 more per hint;
* words of the title are masked with ○.
*/
export function lyricsCard(text: string, title: string, extra = 0): string[] {
const lines = text
.split(/\r?\n/)
.map((l) => l.trim())
.filter(Boolean);
const seen = new Map<string, number>();
for (const l of lines) seen.set(norm(l), (seen.get(norm(l)) ?? 0) + 1);
// first run of lines that are not repeated (verse 1)
let from = 0;
while (from < lines.length && seen.get(norm(lines[from]!))! > 1) from++;
let to = from;
while (to < lines.length && seen.get(norm(lines[to]!))! === 1) to++;
if (to - from < 4) ((from = 0), (to = lines.length));
const verse = lines.slice(from, to);
const want = 4 + extra * 2;
const mid = Math.max(0, Math.floor((verse.length - 4) / 2));
const picked = verse.slice(mid, mid + want);
if (picked.length < want) picked.push(...lines.slice(to, to + want - picked.length));
return picked.map((l) => maskTitle(l, title));
}
export function maskTitle(line: string, title: string): string {
const bare = title.replace(/[([{【].*?[)\]}】]/g, ' ').trim();
const words = [bare, ...bare.split(/\s+/)].filter((w) => [...w].length >= 2 || /[가-힣]/.test(w));
let out = line;
for (const w of words.sort((a, b) => b.length - a.length)) {
const esc = w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
out = out.replace(new RegExp(esc, 'gi'), (m) => m.replace(/\S/g, '○'));
}
return out;
}

View File

@@ -98,6 +98,22 @@ export class Gateway {
return err(rooms.kick(ws, m.userId));
case 'host':
return err(rooms.giveHost(ws, m.userId));
case 'start':
return err(rooms.start(ws));
case 'audio':
return rooms.audio(ws, m.n, m.ev, m.code);
case 'vote':
return err(rooms.vote(ws, m.kind));
case 'typing':
return rooms.typing(ws, m.on);
case 'game':
return err(rooms.gameAction(ws, m.action));
case 'exclude':
return err(rooms.exclude(ws, m.userId));
case 'save':
return err(rooms.save(ws, m.name));
case 'load':
return err(rooms.load(ws, m.id));
case 'chat': {
const g = this.d.chatGuard?.();
if (g?.on) {

View File

@@ -1,26 +1,47 @@
/**
* Room chat (docs/06): one-line log, system lines centred, my unconfirmed lines at the bottom.
* Stage 4 uses it in the waiting room; the answer block and "입력 중" come with the game chat (stage 6).
* Room chat (docs/06): one-line log, system lines centred, my unconfirmed lines at the bottom,
* the 정답 줄 + 5줄 블록 drawn as one item, "입력 중" above the input. The game screen uses the big variant.
*/
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react';
import { CHAT_MAX, type ChatLine } from '@mq/shared/lite';
import { userHue } from './ui';
/** Fixed colour per user (joke-app --name-h). */
function hue(id: string): number {
let h = 0;
for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) >>> 0;
return h % 360;
export interface ChatHandle {
focus(): void;
}
export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: ChatLine[]; pending: { n: string; text: string }[]; meId: string; myName: string; onSend: (text: string) => void }) {
function typingText(names: string[]): string {
if (names.length === 1) return `${names[0]}님이 입력 중…`;
if (names.length === 2) return `${names[0]}, ${names[1]}님이 입력 중…`;
return `${names[0]}, ${names[1]} 외 ${names.length - 2}명이 입력 중…`;
}
export const ChatPanel = forwardRef<
ChatHandle,
{
lines: ChatLine[];
pending: { n: string; text: string }[];
meId: string;
myName: string;
onSend: (text: string) => void;
/** 입력 중 signal: true on start and every 2s while typing, false when cleared or sent. */
onTyping?: (on: boolean) => void;
typing?: string[];
big?: boolean;
}
>(function ChatPanel({ lines, pending, meId, myName, onSend, onTyping, typing = [], big }, ref) {
const [text, setText] = useState('');
const [stuck, setStuck] = useState(true);
const [unseen, setUnseen] = useState(false);
const logRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const lastSent = useRef('');
const typingAt = useRef(0);
// Changes whenever a line arrives, also once the log is capped at 200 lines.
const tick = `${lines.at(-1)?.seq ?? 0}:${pending.length}`;
useImperativeHandle(ref, () => ({ focus: () => inputRef.current?.focus() }), []);
// Auto-scroll only while the reader is at the bottom (docs/06 위로 스크롤하면 멈춤).
useLayoutEffect(() => {
const el = logRef.current;
@@ -37,17 +58,23 @@ export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: Cha
if (el) el.scrollTop = el.scrollHeight;
setStuck(true);
};
const stopTyping = () => {
if (typingAt.current) onTyping?.(false);
typingAt.current = 0;
};
const submit = () => {
const t = text.trim();
if (!t) return;
onSend(t.slice(0, CHAT_MAX));
lastSent.current = t;
setText('');
typingAt.current = 0;
toBottom();
};
const others = typing.filter((n) => n !== myName);
return (
<section className="card chat" aria-label="채팅">
<section className={`card chat ${big ? 'big' : ''}`} aria-label="채팅">
<div
className="chat-log"
ref={logRef}
@@ -60,20 +87,38 @@ export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: Cha
>
{lines.length === 0 && pending.length === 0 && <div className="chat-sys">아직 대화가 없어요. 먼저 인사해 보세요!</div>}
{lines.map((l) =>
l.userId === null ? (
l.answer ? (
<div key={l.seq} className={`answer-item ${l.answer.none ? 'none' : ''}`}>
{l.userId ? (
<div className={`chat-line ok ${l.userId === meId ? 'me' : ''}`}>
<b style={{ ['--name-h' as string]: userHue(l.userId) }}>{l.nickname}</b>
<span>{l.text}</span> <span aria-label="정답">✔</span>
</div>
) : (
<div className="chat-sys">— {l.text} —</div>
)}
<div className="ans-gap" />
<div className="ans-gap" />
<div className="ans-text">
<span>{l.answer.text}</span>
</div>
<div className="ans-gap" />
<div className="ans-gap" />
</div>
) : l.userId === null ? (
<div key={l.seq} className="chat-sys">
— {l.text} —
</div>
) : (
<div key={l.seq} className={`chat-line ${l.userId === meId ? 'me' : ''}`}>
<b style={{ ['--name-h' as string]: hue(l.userId) }}>{l.nickname}</b>
<b style={{ ['--name-h' as string]: userHue(l.userId) }}>{l.nickname}</b>
<span>{l.text}</span>
</div>
),
)}
{pending.map((p) => (
<div key={p.n} className="chat-line me pending" aria-label="보내는 중">
<b style={{ ['--name-h' as string]: hue(meId) }}>{myName}</b>
<b style={{ ['--name-h' as string]: userHue(meId) }}>{myName}</b>
<span>{p.text}</span>
</div>
))}
@@ -83,6 +128,20 @@ export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: Cha
새 메시지 ↓
</button>
)}
{onTyping && (
<div className="typing" aria-live="off">
{others.length > 0 && (
<>
<span className="dots" aria-hidden>
<i />
<i />
<i />
</span>
{typingText(others)}
</>
)}
</div>
)}
<form
className="chat-input"
onSubmit={(e) => {
@@ -91,15 +150,29 @@ export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: Cha
}}
>
<input
ref={inputRef}
className="input"
value={text}
maxLength={CHAT_MAX}
placeholder="메시지 입력 (Enter)"
placeholder={big ? '정답이나 채팅 입력 (Enter)' : '메시지 입력 (Enter)'}
aria-label="채팅 입력"
onChange={(e) => setText(e.target.value)}
autoComplete="off"
onChange={(e) => {
const v = e.target.value;
setText(v);
if (!onTyping) return;
if (!v.trim()) return stopTyping();
if (Date.now() - typingAt.current > 2000) {
typingAt.current = Date.now();
onTyping(true);
}
}}
onBlur={stopTyping}
onKeyDown={(e) => {
if (e.key === 'Escape') setText('');
else if (e.key === 'ArrowUp' && !text && lastSent.current) {
if (e.key === 'Escape') {
setText('');
stopTyping();
} else if (e.key === 'ArrowUp' && !text && lastSent.current) {
e.preventDefault();
setText(lastSent.current);
}
@@ -111,4 +184,4 @@ export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: Cha
</form>
</section>
);
}
});

444
apps/web/src/net/player.ts Normal file
View File

@@ -0,0 +1,444 @@
/**
* Hidden YouTube IFrame player with server-timed playback (docs/12 Q1, prototype tools/prototypes/iframe-sync).
* - prepare: load muted at the start position, wait until really PLAYING (an ad would come first), pause, seek back → ready
* (reloads by itself at 8s and 16s)
* - play: at server time `startAt` unmute and play from `atSec`; stop by playback POSITION at `endSec`
* (checked every frame + 10ms); 0.3s drift correction every second; buffering > 0.5s → stall; muted / not playing
* 0.3s after the start → blocked
* A fake player (localStorage mq:fakePlayer = "1") lets e2e runs play 30 questions without YouTube.
*/
import { create } from 'zustand';
export type AudioEvent = 'ready' | 'blocked' | 'stall' | 'clipEnd' | 'error';
export interface PlayerState {
/** The browser let us play sound (entry click done). */
unlocked: boolean;
/** Sound was blocked: show the big "눌러서 소리 켜기" button. */
needsGesture: boolean;
/** Loading for this question (for "음원 준비 중…"). */
loading: boolean;
/** Playing right now (for the LP spin). */
playing: boolean;
/** Last known position / clip window for the progress bar. */
pos: number;
clip: { start: number; end: number | null } | null;
volume: number;
}
const VOLUME_KEY = 'mq:volume';
const readVolume = () => {
try {
const v = Number(localStorage.getItem(VOLUME_KEY));
return Number.isFinite(v) && localStorage.getItem(VOLUME_KEY) !== null ? Math.max(0, Math.min(100, v)) : 70;
} catch {
return 70;
}
};
export const usePlayer = create<PlayerState>(() => ({ unlocked: false, needsGesture: false, loading: false, playing: false, pos: 0, clip: null, volume: readVolume() }));
/** A harmless video the entry click plays at volume 0 to get sound permission (SG워너비 광, Topic — known to embed). */
const UNLOCK_VIDEO = 'VO88htcm09E';
interface Engine {
init(): Promise<void>;
unlock(): void;
load(id: string, startSec: number): void;
seek(sec: number): void;
play(): void;
pause(): void;
mute(on: boolean): void;
isMuted(): boolean;
volume(v: number): void;
time(): number;
/** YT.PlayerState: -1 unstarted, 0 ended, 1 playing, 2 paused, 3 buffering, 5 cued */
state(): number;
videoId(): string | null;
}
type Listener = { onState?: (s: number) => void; onError?: (code: number) => void; onBlocked?: () => void };
// ---------------------------------------------------------------- real YouTube engine
declare global {
interface Window {
YT?: any;
onYouTubeIframeAPIReady?: () => void;
mqPlayer?: unknown;
}
}
function youtubeEngine(l: Listener): Engine {
let player: any = null;
let ready: Promise<void> | null = null;
let current: string | null = null;
// The player object exists before onReady, its methods only after.
const call = (m: string, ...a: unknown[]): unknown => (typeof player?.[m] === 'function' ? player[m](...a) : undefined);
return {
init() {
ready ??= new Promise<void>((resolve) => {
const host = document.createElement('div');
host.setAttribute('aria-hidden', 'true');
// Off screen, not display:none (a hidden iframe may not play).
host.style.cssText = 'position:fixed;left:-10000px;top:0;width:200px;height:200px;overflow:hidden;pointer-events:none';
const el = document.createElement('div');
host.appendChild(el);
document.body.appendChild(host);
const make = () => {
player = new window.YT.Player(el, {
width: 200,
height: 200,
playerVars: { autoplay: 0, controls: 0, disablekb: 1, fs: 0, rel: 0, playsinline: 1, iv_load_policy: 3 },
events: {
onReady: () => resolve(),
onStateChange: (e: { data: number }) => l.onState?.(e.data),
onError: (e: { data: number }) => l.onError?.(e.data),
onAutoplayBlocked: () => l.onBlocked?.(),
},
});
};
if (window.YT?.Player) make();
else {
const prev = window.onYouTubeIframeAPIReady;
window.onYouTubeIframeAPIReady = () => {
prev?.();
make();
};
const s = document.createElement('script');
s.src = 'https://www.youtube.com/iframe_api';
document.head.appendChild(s);
}
});
return ready;
},
unlock() {
if (typeof player?.loadVideoById !== 'function') return;
// Inside the click: play something with sound on (volume 0), so later starts are allowed (docs/12 Q1 소리 허용).
player.setVolume(0);
player.unMute();
if (current) player.playVideo();
else {
current = UNLOCK_VIDEO;
player.loadVideoById({ videoId: UNLOCK_VIDEO, startSeconds: 30 });
}
},
load(id, startSec) {
current = id;
player.loadVideoById({ videoId: id, startSeconds: startSec });
},
seek: (sec) => call('seekTo', sec, true),
play: () => call('playVideo'),
pause: () => call('pauseVideo'),
mute: (on) => call(on ? 'mute' : 'unMute'),
isMuted: () => !!call('isMuted'),
volume: (v) => call('setVolume', v),
time: () => (call('getCurrentTime') as number | undefined) ?? 0,
state: () => (call('getPlayerState') as number | undefined) ?? -1,
videoId: () => current,
};
}
// ---------------------------------------------------------------- fake engine for e2e (no network)
function fakeEngine(l: Listener): Engine {
let state = -1;
let base = 0;
let since = 0;
let current: string | null = null;
let muted = false;
const set = (s: number) => {
state = s;
l.onState?.(s);
};
const fake = { loadMs: 40, failNext: 0 as number, stallNext: false };
(window as unknown as { mqFake: typeof fake }).mqFake = fake;
const time = () => (state === 1 ? base + (performance.now() - since) / 1000 : base);
return {
init: () => Promise.resolve(),
unlock: () => {},
load(id, startSec) {
current = id;
base = startSec;
set(3);
if (fake.failNext) {
const code = fake.failNext;
fake.failNext = 0;
setTimeout(() => l.onError?.(code), 30);
return;
}
setTimeout(() => {
since = performance.now();
set(1);
}, fake.loadMs);
},
seek(sec) {
base = sec;
since = performance.now();
},
play() {
since = performance.now();
if (fake.stallNext) {
fake.stallNext = false;
set(3);
return;
}
if (fake.loadMs > 100) {
// slow network: buffers before playing
set(3);
setTimeout(() => {
since = performance.now();
set(1);
}, fake.loadMs);
return;
}
set(1);
},
pause() {
base = time();
set(2);
},
mute: (on) => (muted = on),
isMuted: () => muted,
volume: () => {},
time,
state: () => state,
videoId: () => current,
};
}
// ---------------------------------------------------------------- controller
let engine: Engine | null = null;
let report: (n: number, ev: AudioEvent, code?: number) => void = () => {};
let now: () => number = Date.now;
/** Every command bumps the token; async steps of older commands stop. */
let token = 0;
let curN = 0;
let loop: { raf: number; iv: ReturnType<typeof setInterval>; drift: ReturnType<typeof setInterval> } | null = null;
let bufferingSince: number | null = null;
let stallSent = false;
let pendingReady: { n: number; tk: number; at: number } | null = null;
let timeline: { startAt: number; atSec: number; endSec: number | null } | null = null;
const useFake = () => {
try {
return localStorage.getItem('mq:fakePlayer') === '1';
} catch {
return false;
}
};
function eng(): Engine {
if (!engine) {
const l: Listener = {
onState: (s) => {
if (s === 3 && timeline) bufferingSince ??= performance.now();
else bufferingSince = null;
if (s === 0 && timeline) clipEnded();
},
onError: (code) => {
usePlayer.setState({ loading: false });
report(curN, 'error', code);
},
onBlocked: () => blocked(),
};
engine = useFake() ? fakeEngine(l) : youtubeEngine(l);
window.mqPlayer = { pos: () => engine!.time(), state: () => engine!.state(), muted: () => engine!.isMuted(), video: () => engine!.videoId() };
}
return engine;
}
const waitFor = (pred: () => boolean, ms: number, tk: number) =>
new Promise<boolean>((res) => {
const t0 = performance.now();
const iv = setInterval(() => {
if (tk !== token) return (clearInterval(iv), res(false));
if (pred()) return (clearInterval(iv), res(true));
if (performance.now() - t0 > ms) return (clearInterval(iv), res(false));
}, 20);
});
function stopLoop(): void {
if (!loop) return;
cancelAnimationFrame(loop.raf);
clearInterval(loop.iv);
clearInterval(loop.drift);
loop = null;
}
function blocked(): void {
if (!timeline) return;
usePlayer.setState({ needsGesture: true, playing: false });
report(curN, 'blocked');
}
function clipEnded(): void {
if (!timeline) return;
const e = eng();
e.pause();
stopLoop();
timeline = null;
usePlayer.setState({ playing: false, pos: e.time() });
report(curN, 'clipEnd');
}
export const player = {
/** Wire reports to the server and the server clock. */
setup(r: typeof report, serverNow: () => number): void {
report = r;
now = serverNow;
},
/** Load the API early (waiting room), so the entry click can unlock at once. */
warm(): void {
void eng().init();
},
/** Call inside a click: "참가 (소리 켜기)" / "눌러서 소리 켜기". */
unlock(): void {
const e = eng();
e.unlock();
const held = pendingReady;
pendingReady = null;
usePlayer.setState({ unlocked: true, needsGesture: false });
const tk = token;
const release = () => held && held.tk === token && report(held.n, 'ready');
if (useFake()) return void release();
void waitFor(() => e.state() === 1, 5000, tk).then(async () => {
e.volume(usePlayer.getState().volume);
if (tk !== token || timeline) return;
e.pause();
if (!held) return;
// The question was waiting for this click: back to the position everyone resumes from, then ready.
await waitFor(() => e.state() === 2, 2000, tk);
if (tk !== token) return;
e.seek(held.at);
release();
});
},
async prepare(n: number, videoId: string, startSec: number, endSec: number | null): Promise<void> {
const tk = ++token;
curN = n;
stopLoop();
timeline = null;
pendingReady = null;
usePlayer.setState({ loading: true, playing: false, pos: startSec, clip: { start: startSec, end: endSec } });
const e = eng();
await e.init();
if (tk !== token) return;
e.mute(true);
const load = () => {
if (e.videoId() === videoId && e.state() !== -1 && e.state() !== 5) {
e.seek(startSec);
e.play();
} else e.load(videoId, startSec);
};
load();
// Not playing yet: reload at 8s and 16s (docs/12 Q1), then keep waiting for the host's decision.
let ok = await waitFor(() => e.state() === 1, 8000, tk);
if (!ok && tk === token) (e.load(videoId, startSec), (ok = await waitFor(() => e.state() === 1, 8000, tk)));
if (!ok && tk === token) (e.load(videoId, startSec), (ok = await waitFor(() => e.state() === 1, 600_000, tk)));
if (!ok || tk !== token) return;
e.pause();
await waitFor(() => e.state() === 2, 3000, tk);
if (tk !== token) return;
e.seek(startSec);
usePlayer.setState({ loading: false, pos: startSec });
if (usePlayer.getState().needsGesture) pendingReady = { n, tk, at: startSec };
else report(n, 'ready');
},
play(n: number, startAt: number, atSec: number, endSec: number | null): void {
const tk = ++token;
curN = n;
stopLoop();
pendingReady = null;
const e = eng();
timeline = { startAt, atSec, endSec };
stallSent = false;
bufferingSince = null;
usePlayer.setState({ clip: { start: usePlayer.getState().clip?.start ?? atSec, end: endSec }, pos: atSec });
const go = () => {
if (tk !== token) return;
e.volume(usePlayer.getState().volume);
e.mute(false);
if (Math.abs(e.time() - atSec) > 0.15) e.seek(atSec);
e.play();
usePlayer.setState({ playing: true });
// 소리 확인 (docs/12 Q1): 0.3s later it must be unmuted and playing.
setTimeout(() => {
if (tk !== token || !timeline) return;
if (e.isMuted() || (e.state() !== 1 && e.state() !== 3)) blocked();
}, 300);
const check = () => {
if (tk !== token || !timeline) return;
const t = e.time();
if (endSec !== null && t >= endSec) return clipEnded();
if (bufferingSince !== null && !stallSent && performance.now() - bufferingSince > 500) {
stallSent = true;
report(n, 'stall');
}
if (loop) loop.raf = requestAnimationFrame(check);
};
loop = {
raf: requestAnimationFrame(check),
iv: setInterval(check, 10),
drift: setInterval(() => {
if (tk !== token || !timeline || e.state() !== 1) return;
const expected = atSec + (now() - startAt) / 1000;
const t = e.time();
usePlayer.setState({ pos: t });
if (Math.abs(t - expected) > 0.3) e.seek(expected);
}, 1000),
};
};
const wait = startAt - now();
if (wait > 0) setTimeout(go, wait);
else go();
},
pause(): void {
token++;
stopLoop();
timeline = null;
pendingReady = null;
const e = engine;
if (e && e.state() === 1) e.pause();
usePlayer.setState({ playing: false, loading: false, pos: e?.time() ?? 0 });
},
/** 정답 공개: the music goes on for the reveal (docs/05 정답 공개), then stops. */
reveal(ms: number): void {
const tk = ++token;
stopLoop();
timeline = null;
const e = engine;
if (!e || !e.videoId() || e.videoId() === UNLOCK_VIDEO || usePlayer.getState().needsGesture) return;
e.volume(usePlayer.getState().volume);
e.mute(false);
e.play();
usePlayer.setState({ playing: true, loading: false });
setTimeout(() => {
if (tk !== token) return;
e.pause();
usePlayer.setState({ playing: false });
}, ms);
},
stop(): void {
player.pause();
usePlayer.setState({ clip: null, pos: 0 });
},
setVolume(v: number): void {
const vol = Math.max(0, Math.min(100, Math.round(v)));
usePlayer.setState({ volume: vol });
try {
localStorage.setItem(VOLUME_KEY, String(vol));
} catch {
/* private mode */
}
engine?.volume(vol);
},
time(): number {
return engine?.time() ?? 0;
},
};

View File

@@ -2,8 +2,9 @@
* One WebSocket per tab (docs/01): reconnects with backoff, re-joins the room, keeps the server clock offset (docs/12 Q1).
*/
import { create } from 'zustand';
import type { ChatLine, RoomView, ServerMessage } from '@mq/shared/lite';
import type { ChatLine, GameView, RoomView, ServerMessage } from '@mq/shared/lite';
import { toast } from '../store/toast';
import { player } from './player';
type Status = 'idle' | 'connecting' | 'open' | 'reconnecting';
@@ -21,6 +22,12 @@ interface RoomState {
chat: ChatLine[];
/** My lines not confirmed by the server yet: always drawn at the bottom (docs/06 지연 없는 전송). */
pending: { n: string; text: string }[];
/** The running game (docs/05), null in the waiting room. */
game: GameView | null;
/** Who is typing (docs/06 입력 중). */
typing: string[];
/** Last 퀴즈 저장 result. */
saved: { id: number; name: string } | null;
}
const CHAT_KEEP = 200;
@@ -28,7 +35,7 @@ const CHAT_KEEP = 200;
const LAST_ROOM_KEY = 'mq:lastRoom';
export const ROOM_GONE_TEXT = '서버가 업데이트되면서 방이 닫혔어요. 방을 새로 만들어 주세요.';
export const useRoom = create<RoomState>(() => ({ status: 'idle', code: null, room: null, offset: 0, rtt: null, joinError: null, left: null, chat: [], pending: [] }));
export const useRoom = create<RoomState>(() => ({ status: 'idle', code: null, room: null, offset: 0, rtt: null, joinError: null, left: null, chat: [], pending: [], game: null, typing: [], saved: null }));
let ws: WebSocket | null = null;
let retry = 0;
@@ -37,6 +44,7 @@ let pingTimer: ReturnType<typeof setInterval> | null = null;
/** A join is on its way: the next error is the join's answer. */
let joining = false;
let nonce = 0;
let myId = '';
function lastRoom(): string | null {
try {
@@ -70,6 +78,7 @@ function syncClock(): void {
function onMessage(m: ServerMessage): void {
switch (m.t) {
case 'welcome': {
myId = m.userId;
useRoom.setState({ status: 'open', offset: m.serverNow - Date.now() });
retry = 0;
syncClock();
@@ -99,13 +108,40 @@ function onMessage(m: ServerMessage): void {
case 'left':
if (m.code === useRoom.getState().code) {
setLastRoom(null);
useRoom.setState({ room: null, left: m.reason, chat: [], pending: [] });
player.stop();
useRoom.setState({ room: null, left: m.reason, chat: [], pending: [], game: null, typing: [] });
}
return;
case 'chatlog':
// (Re)joined: the server's log is the truth; unconfirmed lines from before a drop are gone.
if (m.code === useRoom.getState().code) useRoom.setState({ chat: m.lines.slice(-CHAT_KEEP), pending: [] });
return;
case 'game': {
if (m.code !== useRoom.getState().code) return;
const prev = useRoom.getState().game;
const g = m.game;
if (!g || g.phase === 'result') player.stop();
else if (g.phase === 'reveal' && prev?.phase !== 'reveal' && g.mode !== 'lyrics' && g.participants.includes(myId)) player.reveal(Math.max(0, (g.revealUntil ?? 0) - serverNow() - 150));
useRoom.setState({ game: g });
return;
}
case 'prepare':
if (m.code === useRoom.getState().code) void player.prepare(m.n, m.videoId, m.startSec, m.endSec);
return;
case 'play':
if (m.code === useRoom.getState().code) player.play(m.n, m.startAt, m.atSec, m.endSec);
return;
case 'pause':
if (m.code === useRoom.getState().code) player.pause();
return;
case 'typing':
if (m.code === useRoom.getState().code) useRoom.setState({ typing: m.ids });
return;
case 'saved':
useRoom.setState({ saved: { id: m.id, name: m.name } });
toast(`"${m.name}"(으)로 저장했어요.`);
return;
case 'answer':
case 'chat':
if (m.code === useRoom.getState().code) {
const st = useRoom.getState();
@@ -166,14 +202,15 @@ export const socket = {
join(code: string, pw?: string): void {
password = pw;
const st = useRoom.getState();
useRoom.setState({ code, room: null, joinError: null, left: null, ...(st.code === code ? {} : { chat: [], pending: [] }) });
useRoom.setState({ code, room: null, joinError: null, left: null, ...(st.code === code ? {} : { chat: [], pending: [], game: null, typing: [] }) });
socket.start();
sendJoin(code);
},
leave(): void {
send({ t: 'leave' });
setLastRoom(null);
useRoom.setState({ code: null, room: null, chat: [], pending: [] });
player.stop();
useRoom.setState({ code: null, room: null, chat: [], pending: [], game: null, typing: [] });
},
chat(text: string): void {
const n = `${Date.now().toString(36)}${(nonce++).toString(36)}`;
@@ -185,3 +222,5 @@ export const socket = {
/** Server clock (ms) for countdowns and synced playback. */
export const serverNow = () => Date.now() + useRoom.getState().offset;
player.setup((n, ev, code) => send({ t: 'audio', n, ev, code }), serverNow);

View File

@@ -0,0 +1,395 @@
/**
* 게임 화면 (docs/03 게임 화면, docs/05, docs/06): black top bar with votes, stage (LP / lyrics card / hint), big chat,
* scoreboard on the left, past questions on the right, results at the end.
*/
import { useEffect, useRef, useState } from 'react';
import { listenLabel, type GameHistoryItem, type GameView, type RoomView } from '@mq/shared/lite';
import { serverNow, socket, useRoom } from '../net/socket';
import { player, usePlayer } from '../net/player';
import { useSession } from '../store/session';
import { toast } from '../store/toast';
import { Avatar, ConfirmSheet, Sheet } from '../components/ui';
import { ChatPanel, type ChatHandle } from '../components/ChatPanel';
const LATE_MS = 30_000;
/** Re-render every `ms` (timers, countdown). */
function useNow(ms: number): number {
const [, set] = useState(0);
useEffect(() => {
const iv = setInterval(() => set((x) => x + 1), ms);
return () => clearInterval(iv);
}, [ms]);
return serverNow();
}
const fmt = (sec: number) => `${Math.floor(sec / 60)}:${String(Math.floor(sec % 60)).padStart(2, '0')}`;
const secs = (ms: number | null) => (ms === null ? '' : `${(ms / 1000).toFixed(1)}초`);
function Stars({ n }: { n: number | null }) {
if (!n) return null;
const color = n <= 3 ? 'var(--star-1)' : n <= 6 ? 'var(--star-2)' : n <= 8 ? 'var(--star-3)' : 'var(--star-4)';
return (
<span className="mini-stars" style={{ color }} aria-label={`난이도 ${n}단계`}>
★{n}
</span>
);
}
export function GameScreen({ room, game }: { room: RoomView; game: GameView }) {
const me = useSession((s) => s.me)!;
const { chat, pending, typing } = useRoom();
const p = usePlayer();
const now = useNow(200);
const chatRef = useRef<ChatHandle>(null);
const [confirmEnd, setConfirmEnd] = useState(false);
const isHost = room.hostId === me.id;
const c = room.config;
const send = (m: unknown) => socket.send(m);
const vote = (kind: 'skip' | 'hint' | 'replay') => send({ t: 'vote', kind });
const name = (id: string) => room.players.find((x) => x.id === id)?.nickname ?? game.scores.find((x) => x.id === id)?.nickname ?? '?';
const inQuestion = game.participants.includes(me.id) && !game.excluded.includes(me.id);
const listening = game.mode !== 'lyrics';
useEffect(() => {
player.warm();
}, []);
// Shortcuts (docs/06): Ctrl+I 힌트, Ctrl+K 스킵, Ctrl+R 다시듣기 — only on the game screen; any key focuses the chat.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey) {
const k = e.key.toLowerCase();
const kind = k === 'i' ? 'hint' : k === 'k' ? 'skip' : k === 'r' ? 'replay' : null;
if (kind) {
e.preventDefault();
vote(kind);
}
return;
}
const t = e.target as HTMLElement | null;
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable)) return;
if (document.querySelector('.sheet')) return;
if (e.key.length === 1 || e.key === 'Enter') chatRef.current?.focus();
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
if (game.phase === 'result') return <ResultScreen room={room} game={game} />;
const elapsed = game.clock.elapsedMs + (game.clock.runningSince !== null ? Math.max(0, now - game.clock.runningSince) : 0);
const countdown = game.startAt !== null && now < game.startAt && !game.paused ? Math.ceil((game.startAt - now) / 1000) : 0;
const reveal = game.phase === 'reveal' ? game.history.at(-1) : undefined;
const voteBtn = (kind: 'skip' | 'hint' | 'replay', icon: string, label: string, key: string) => {
const need = game.need[kind];
const n = game.votes[kind].length;
const on = game.votes[kind].includes(me.id);
const off = need === null && (kind !== 'hint' || c.hint === 'none');
return (
<button type="button" className={`btn btn-sm gbtn ${on ? 'on' : ''}`} aria-pressed={on} disabled={kind === 'replay' && need === null} onClick={() => vote(kind)} title={off ? `${label}가 꺼져 있어요` : undefined}>
{icon} {label}
{need !== null && (
<span className="mono">
{' '}
{n}/{need}
</span>
)}
<span className="kbd">{key}</span>
</button>
);
};
const question = c.answer === 'title' ? '이 노래 제목은?' : c.answer === 'artist' ? '이 노래 부른 가수는?' : '제목과 가수를 한 줄에!';
const clipLen = game.clipSec;
const clipPos = p.clip ? Math.max(0, p.pos - p.clip.start) : 0;
const late = isHost ? game.waiting.filter((w) => now - w.since >= LATE_MS) : [];
return (
<div className="game">
<div className="gbar">
<div className="q">
문제 {game.n} <span>/ {game.total}</span>
</div>
<span className="badge dark">
{game.mode === 'lyrics'
? `📜 가사보고 맞추기 · ${c.lyricsSec ? `${c.lyricsSec}초` : '무제한'}`
: `${game.mode === 'artist' ? '🎤 가수노래' : '🎧 듣고맞추기'} · ${listenLabel(c.listenSec)} · ${c.startAt === 'highlight' ? '하이라이트부터' : '처음부터'}`}
</span>
<span className="badge dark">정답: {c.answer === 'title' ? '제목만' : c.answer === 'artist' ? '가수만' : '제목+가수'}</span>
<span className="badge dark">★{c.level}</span>
<div className="grow" />
{voteBtn('hint', '💡', '힌트', 'Ctrl+I')}
{voteBtn('skip', '⏭', '스킵', 'Ctrl+K')}
{listening && voteBtn('replay', '🔁', '다시듣기', 'Ctrl+R')}
{listening && (
<label className="vol" title="볼륨">
🔊
<input type="range" min={0} max={100} value={p.volume} onChange={(e) => player.setVolume(Number(e.target.value))} aria-label="볼륨" />
</label>
)}
{isHost && (
<>
<button type="button" className="btn btn-sm gbtn" onClick={() => send({ t: 'game', action: game.paused?.reason === 'host' ? 'resume' : 'pause' })}>
{game.paused?.reason === 'host' ? '▶ 계속' : '⏸ 일시정지'}
</button>
<button type="button" className="btn btn-sm gbtn" onClick={() => setConfirmEnd(true)}>
⏹ 끝내기
</button>
</>
)}
</div>
<div className="ggrid">
<aside className="side scoreboard" aria-label="점수판">
<h3>점수판 · {game.scores.length}명</h3>
<ol>
{game.scores.map((s, i) => {
// ties share a rank (same score and same average time)
const rank = 1 + game.scores.findIndex((o) => o.score === s.score && o.avgMs === s.avgMs);
return (
<li key={s.id} className={`sb ${s.id === me.id ? 'me' : ''} ${i === 0 && s.score > 0 ? 'first' : ''} ${s.online ? '' : 'off'}`}>
<span className="rk">{rank}</span>
<Avatar user={{ id: s.id, nickname: s.nickname, avatar: room.players.find((x) => x.id === s.id)?.avatar ?? null }} size={26} />
<span className="nm">
{s.nickname}
{s.id === me.id && ' (나)'}
{game.votes.skip.includes(s.id) && <span title="스킵"> ⏭</span>}
{s.id === room.hostId && <span title="방장"> 👑</span>}
</span>
<span className="sc mono">{s.score}</span>
</li>
);
})}
</ol>
</aside>
<div className="gcenter">
<section className={`stage ${reveal ? 'revealed' : ''}`} aria-live="polite">
{reveal ? (
<RevealCard item={reveal} />
) : (
<>
{listening ? <div className={`lp ${p.playing && !game.paused ? 'spin' : ''}`} aria-hidden /> : null}
<div className="sinfo">
<div className="mode">
{game.paused
? game.paused.reason === 'host'
? '⏸ 방장이 잠시 멈췄어요'
: `⏸ 잠시 멈춤 — ${game.paused.who.map(name).join(', ') || '누군가'}님 ${game.paused.reason === 'blocked' ? '소리 켜는 중' : '버퍼링 중'}`
: game.phase === 'prepare'
? game.waiting.length
? `${game.waiting.map((w) => name(w.id)).slice(0, 3).join(', ')}${game.waiting.length > 3 ? ` 외 ${game.waiting.length - 3}명` : ''}님 음원 준비 중…`
: '음원 준비 중…'
: countdown
? `${game.n}번째 문제`
: listening
? game.clipOver
? '재생이 끝났어요 · 계속 맞혀 보세요'
: `${game.n}번째 곡 재생 중 · 앨범아트와 제목은 정답 뒤에 공개`
: `${game.n}번째 가사`}
</div>
{game.mode === 'artist' && room.artists.length > 0 && <div className="small muted">선택한 가수: {room.artists.map((a) => a.name).join(', ')}</div>}
{countdown ? <div className="countdown mono">{countdown}</div> : <div className="big">{question}</div>}
{game.lyrics && (
<div className="lyrics-card">
{game.lyrics.map((l, i) => (
<div key={i}>{l}</div>
))}
</div>
)}
{listening && clipLen !== null && (
<>
<div className="bar" aria-hidden>
<i style={{ width: `${Math.min(100, (clipPos / Math.max(0.1, clipLen)) * 100)}%` }} />
</div>
<div className="times small">
<span>{fmt(clipPos)}</span>
<span>{fmt(clipLen)}</span>
</div>
</>
)}
{game.clock.limitMs !== null && game.phase === 'play' && (
<div className="limit small muted">
남은 시간 <b className="mono">{Math.max(0, Math.ceil((game.clock.limitMs - elapsed) / 1000))}초</b>
</div>
)}
<div className="row" style={{ marginTop: 8 }}>
{game.hint ? (
<span className="hint">
{game.hint} <small>초성 힌트</small>
</span>
) : game.hintAtSec !== null && game.phase === 'play' ? (
<span className="small muted">힌트는 {Math.max(0, Math.ceil(game.hintAtSec - elapsed / 1000))}초 뒤에 공개돼요</span>
) : null}
</div>
</div>
</>
)}
{!inQuestion && game.phase !== 'reveal' && (
<div className="stage-note">{game.excluded.includes(me.id) ? '음원을 불러오지 못해 이번 문제는 빠졌어요. 다음 문제부터 다시 같이 해요.' : '다음 문제부터 같이 해요. 지금은 채팅만 할 수 있어요.'}</div>
)}
{late.length > 0 && (
<div className="late">
{late.map((w) => (
<button key={w.id} type="button" className="btn btn-sm" onClick={() => send({ t: 'exclude', userId: w.id })}>
{name(w.id)}님 빼고 이번 문제 진행
</button>
))}
</div>
)}
</section>
<ChatPanel
ref={chatRef}
big
lines={chat}
pending={pending}
meId={me.id}
myName={me.nickname}
onSend={(t) => socket.chat(t)}
onTyping={(on) => send({ t: 'typing', on })}
typing={typing.filter((id) => id !== me.id).map(name)}
/>
</div>
<aside className="side hist" aria-label="지난 문제">
<h3>지난 문제</h3>
{game.history.length === 0 && <p className="small muted">아직 없어요</p>}
{[...game.history].reverse().map((h) => (
<div key={h.n} className="h">
<span className="n">{h.n}</span>
<span className="t">{h.title}</span> - {h.artist}
<div className="m">
<Stars n={h.level} />
{h.winner ? `${h.winner} · ${secs(h.ms)}` : h.how === 'skip' ? '스킵됨 (정답자 없음)' : '시간 초과 (정답자 없음)'}
</div>
</div>
))}
</aside>
</div>
{listening && (!p.unlocked || p.needsGesture) && inQuestion && (
<div className="unlock-overlay">
<button type="button" className="btn btn-mustard btn-lg" onClick={() => player.unlock()} autoFocus>
🔊 {p.needsGesture ? '눌러서 소리 켜기' : '참가 (소리 켜기)'}
</button>
<p className="small">브라우저가 소리를 막지 않도록 한 번 눌러 주세요.</p>
</div>
)}
{confirmEnd && <ConfirmSheet title="게임을 끝낼까요?" body="지금까지 점수로 결과를 보여 줘요." confirm="끝내기" danger onConfirm={() => send({ t: 'game', action: 'end' })} onClose={() => setConfirmEnd(false)} />}
</div>
);
}
function RevealCard({ item }: { item: GameHistoryItem }) {
return (
<div className="reveal">
{item.videoId ? <img className="art" src={`https://i.ytimg.com/vi/${item.videoId}/hqdefault.jpg`} alt="" /> : <div className="art lp" aria-hidden />}
<div className="sinfo">
<div className="mode">{item.winner ? `🎉 ${item.winner}님 정답! · ${secs(item.ms)}` : item.how === 'skip' ? '⏭ 스킵 · 정답자 없음' : '⌛ 시간 초과 · 정답자 없음'}</div>
<div className="big">
{item.title} <span className="muted">- {item.artist}</span>
</div>
<div className="small muted">
{[item.year, ...item.genres].filter(Boolean).join(' · ')} <Stars n={item.level} />
</div>
</div>
</div>
);
}
function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
const me = useSession((s) => s.me)!;
const isHost = room.hostId === me.id;
const [save, setSave] = useState(false);
const [name, setName] = useState('');
const send = (m: unknown) => socket.send(m);
const fastest = new Map<string, GameHistoryItem>();
for (const h of game.history) if (h.winnerId && h.ms !== null && (!fastest.get(h.winnerId) || fastest.get(h.winnerId)!.ms! > h.ms)) fastest.set(h.winnerId, h);
return (
<main className="page result stack">
<div className="row">
<h1>🏁 게임 결과</h1>
<span className="muted">{game.history.length}문제</span>
</div>
<section className="card ink">
<table className="data-table rank">
<thead>
<tr>
<th>순위</th>
<th>이름</th>
<th>점수</th>
<th>맞힌 곡</th>
<th>가장 빨리 맞힌 곡</th>
</tr>
</thead>
<tbody>
{game.scores.map((s, i) => {
const f = fastest.get(s.id);
return (
<tr key={s.id} className={s.id === me.id ? 'sel' : ''}>
<td className="mono">{i === 0 && s.score > 0 ? '🥇' : i === 1 && s.score > 0 ? '🥈' : i === 2 && s.score > 0 ? '🥉' : i + 1}</td>
<td>{s.nickname}</td>
<td className="mono">{s.score}</td>
<td className="mono">{s.correct}</td>
<td>{f ? `${f.title} · ${secs(f.ms)}` : '-'}</td>
</tr>
);
})}
</tbody>
</table>
</section>
<div className="row">
{isHost ? (
<>
<button className="btn btn-mustard btn-lg" disabled={game.left === 0} title={game.left === 0 ? '조건에 맞는 곡을 모두 풀었어요' : undefined} onClick={() => send({ t: 'game', action: 'continue' })}>
▶ 이어풀기 {game.left > 0 && <span className="small">(남은 곡 {game.left})</span>}
</button>
<button className="btn btn-lg" onClick={() => send({ t: 'game', action: 'again' })}>
↺ 다시 하기
</button>
<button
className="btn btn-lg"
onClick={() => (me.kind === 'member' ? setSave(true) : toast('퀴즈 저장은 디스코드로 로그인하면 쓸 수 있어요.', 'error'))}
>
💾 퀴즈 저장
</button>
</>
) : (
<span className="muted">방장이 이어풀기나 다시 하기를 고르면 바로 시작돼요.</span>
)}
<div className="grow" />
</div>
<section className="card">
<h2 style={{ marginBottom: 10 }}>이번 게임 곡 목록</h2>
<ol className="songlist">
{game.history.map((h) => (
<li key={h.n}>
<span className="mono muted">{h.n}.</span> <b>{h.title}</b> - {h.artist} <Stars n={h.level} />{' '}
{h.videoId && (
<a href={`https://youtu.be/${h.videoId}`} target="_blank" rel="noreferrer">
https://youtu.be/{h.videoId}
</a>
)}{' '}
<span className="small muted">{h.winner ? `${h.winner} ${secs(h.ms)}` : h.how === 'skip' ? '스킵' : '시간 초과'}</span>
</li>
))}
</ol>
</section>
{save && (
<Sheet label="퀴즈 저장" onClose={() => setSave(false)}>
<h2>퀴즈 저장</h2>
<p className="muted small">방 설정, 지금까지 나온 곡, 참가자 점수를 내 계정에 저장해요. 불러오면 나온 곡은 빼고 이어서 할 수 있어요.</p>
<form
className="stack"
onSubmit={(e) => {
e.preventDefault();
if (!name.trim()) return;
send({ t: 'save', name: name.trim() });
setSave(false);
}}
>
<input className="input" autoFocus maxLength={40} placeholder="퀴즈 이름 (예: 금요일 발라드)" value={name} onChange={(e) => setName(e.target.value)} aria-label="퀴즈 이름" />
<button className="btn btn-primary btn-block" disabled={!name.trim()}>
저장
</button>
</form>
</Sheet>
)}
</main>
);
}

View File

@@ -1,6 +1,6 @@
/**
* 대기실 /r/:code (docs/03, docs/04): players, live "조건에 맞는 곡 N곡", settings (host edits, everyone sees it at once).
* Games start in stage 5: the start button is shown but disabled until then.
* While a game runs the same page shows the game screen (GameScreen).
*/
import { useEffect, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router';
@@ -9,10 +9,12 @@ import { apiCall } from '../net/api';
import { socket, useRoom } from '../net/socket';
import { useSession } from '../store/session';
import { toast } from '../store/toast';
import { Avatar, ConfirmSheet } from '../components/ui';
import { Avatar, ConfirmSheet, Sheet } from '../components/ui';
import { LoginBox } from '../components/LoginBox';
import { RoomSettings, type CatalogMeta } from '../components/RoomSettings';
import { ChatPanel } from '../components/ChatPanel';
import { player, usePlayer } from '../net/player';
import { GameScreen } from './GameScreen';
const LEFT_TEXT: Record<string, string> = {
kicked: '방장이 방에서 내보냈어요.',
@@ -25,17 +27,29 @@ export default function RoomPage() {
const { code = '' } = useParams();
const me = useSession((s) => s.me);
const nav = useNavigate();
const { room, joinError, left, status, chat, pending } = useRoom();
const { room, joinError, left, status, chat, pending, game, typing } = useRoom();
const unlocked = usePlayer((s) => s.unlocked);
const [confirmStart, setConfirmStart] = useState(false);
const [loadOpen, setLoadOpen] = useState(false);
const [meta, setMeta] = useState<CatalogMeta | null>(null);
const [pw, setPw] = useState('');
const [confirmLeave, setConfirmLeave] = useState(false);
useEffect(() => {
void apiCall<CatalogMeta>('GET', '/api/catalog/meta').then(setMeta).catch(() => {});
// The YouTube player loads while people wait, so the entry click can turn the sound on at once (docs/12 Q1).
player.warm();
}, []);
useEffect(() => {
if (!me || !/^\d{6}$/.test(code)) return;
socket.join(code);
// Going anywhere else in the app (← 방 목록, logo, browser back) leaves the room, so an empty room closes at once.
// Checked a tick later: React StrictMode re-mounts on the same path, and a refresh keeps the 60s place instead.
return () => {
setTimeout(() => {
if (location.pathname !== `/r/${code}` && useRoom.getState().code === code) socket.leave();
}, 0);
};
}, [me, code]);
useEffect(() => {
if (left && left !== 'leave') {
@@ -85,6 +99,8 @@ export default function RoomPage() {
const link = `${location.origin}/r/${room.code}`;
const needArtist = c.mode === 'artist' && c.artistIds.length === 0;
const short = c.count !== 0 && room.pool.playable < c.count;
const start = () => (short && room.pool.playable > 0 ? setConfirmStart(true) : send({ t: 'start' }));
const playing = room.status === 'playing' && !!game;
return (
<>
@@ -109,12 +125,15 @@ export default function RoomPage() {
링크 복사
</button>
<div className="grow" />
<span className="badge teal">{room.status === 'lobby' ? '대기 중' : '게임 중'}</span>
<span className={`badge ${room.status === 'lobby' ? 'teal' : 'live'}`}>{room.status === 'lobby' ? '대기 중' : '게임 중'}</span>
<span className="muted small">참가 {room.players.length}명 · 제한 없음</span>
<button type="button" className="btn btn-sm" onClick={() => setConfirmLeave(true)}>
🚪 나가기
</button>
</div>
{playing ? (
<GameScreen room={room} game={game} />
) : (
<main className="room-main">
<div className="stack" style={{ minWidth: 0 }}>
<section className="card">
@@ -172,7 +191,7 @@ export default function RoomPage() {
{!needArtist && room.pool.playable === 0 && room.pool.total === 0 && <p className="small">이 조건에 맞는 곡이 없어요. 장르·연도·난이도를 넓혀 보세요.</p>}
</div>
{isHost ? (
<button className="btn btn-mustard btn-lg" disabled title="게임 진행은 다음 업데이트에서 열려요">
<button className="btn btn-mustard btn-lg" disabled={needArtist || room.pool.playable === 0} onClick={start}>
게임 시작
</button>
) : (
@@ -181,8 +200,30 @@ export default function RoomPage() {
</button>
)}
</section>
<ChatPanel lines={chat} pending={pending} meId={me.id} myName={me.nickname} onSend={(t) => socket.chat(t)} />
<p className="muted small">게임 진행(노래 재생·채팅 정답)은 다음 업데이트에서 열려요. 지금은 방을 만들고 설정을 맞추면서 대화할 수 있어요.</p>
{c.mode !== 'lyrics' && !unlocked && (
<section className="card sound-card row">
<span className="grow">🔊 노래가 들리도록 게임 전에 한 번 눌러 주세요. 브라우저가 소리를 막을 수 있어요.</span>
<button type="button" className="btn btn-mustard" onClick={() => player.unlock()}>
참가 (소리 켜기)
</button>
</section>
)}
{isHost && (
<div className="row">
<button type="button" className="btn btn-sm" onClick={() => (me.kind === 'member' ? setLoadOpen(true) : toast('퀴즈 저장·불러오기는 디스코드로 로그인하면 쓸 수 있어요.', 'error'))}>
📂 퀴즈 불러오기
</button>
</div>
)}
<ChatPanel
lines={chat}
pending={pending}
meId={me.id}
myName={me.nickname}
onSend={(t) => socket.chat(t)}
onTyping={(on) => send({ t: 'typing', on })}
typing={typing.filter((id) => id !== me.id).map((id) => room.players.find((x) => x.id === id)?.nickname ?? '?')}
/>
</div>
<RoomSettings
config={c}
@@ -195,6 +236,17 @@ export default function RoomPage() {
onPassword={(value) => send({ t: 'password', value })}
/>
</main>
)}
{confirmStart && (
<ConfirmSheet
title={`조건에 맞는 곡이 ${room.pool.playable}곡뿐이에요`}
body={`${c.count}문제 대신 ${room.pool.playable}문제로 시작할까요? 설정을 넓히면 곡이 늘어나요.`}
confirm="그대로 시작"
onConfirm={() => send({ t: 'start' })}
onClose={() => setConfirmStart(false)}
/>
)}
{loadOpen && <LoadSheet onClose={() => setLoadOpen(false)} />}
{confirmLeave && (
<ConfirmSheet
title="방에서 나갈까요?"
@@ -210,6 +262,68 @@ export default function RoomPage() {
);
}
interface SavedQuiz {
id: number;
name: string;
questions: number;
players: number;
updatedAt: number;
}
/** 퀴즈 불러오기 (docs/12 Q8): my saved quizzes; loading restores settings, songs asked and scores. */
function LoadSheet({ onClose }: { onClose: () => void }) {
const [list, setList] = useState<SavedQuiz[] | null>(null);
const refresh = () =>
apiCall<{ quizzes: SavedQuiz[] }>('GET', '/api/quizzes')
.then((r) => setList(r.quizzes))
.catch(() => setList([]));
useEffect(() => {
void refresh();
}, []);
return (
<Sheet label="퀴즈 불러오기" onClose={onClose}>
<h2>퀴즈 불러오기</h2>
<p className="muted small">불러오면 저장할 때의 설정과 점수가 돌아오고, 시작하면 이미 나온 곡은 빼고 이어서 나와요. (계정당 20개)</p>
{list === null ? (
<p className="muted">불러오는 중…</p>
) : list.length === 0 ? (
<p className="muted">저장한 퀴즈가 없어요. 게임이 끝난 뒤 결과 화면에서 저장할 수 있어요.</p>
) : (
<ul className="saved-list">
{list.map((q) => (
<li key={q.id}>
<div className="grow">
<b>{q.name}</b>
<div className="small muted">
{q.questions}문제 · {q.players}명 · {new Date(q.updatedAt).toLocaleString('ko-KR', { dateStyle: 'short', timeStyle: 'short' })}
</div>
</div>
<button
type="button"
className="btn btn-sm btn-primary"
onClick={() => {
socket.send({ t: 'load', id: q.id });
onClose();
}}
>
불러오기
</button>
<button
type="button"
className="btn btn-sm btn-ghost"
aria-label={`${q.name} 지우기`}
onClick={() => void apiCall('DELETE', `/api/quizzes/${q.id}`).then(refresh, () => toast('지우지 못했어요.', 'error'))}
>
지우기
</button>
</li>
))}
</ul>
)}
</Sheet>
);
}
function JoinError({ text }: { text: string }) {
return (
<main className="page narrow stack">

View File

@@ -159,6 +159,7 @@ interface Site {
chatFloodGuard: boolean;
chatRatePerSec: number;
chatBurst: number;
questionLimitSec: number;
}
function SiteSettings() {
@@ -206,6 +207,11 @@ function SiteSettings() {
금칙어 (쉼표로 구분, 닉네임·채팅에 적용)
<textarea className="input" value={words} onChange={(e) => setWords(e.target.value)} />
</label>
<label className="field" style={{ maxWidth: 320 }}>
문제 하나의 제한 시간 (초, 짧은 클립 모드)
<input className="input" type="number" min={10} max={600} value={s.questionLimitSec} onChange={(e) => setS({ ...s, questionLimitSec: Number(e.target.value) })} />
<span className="muted small">듣고맞출시간이 1초~1분인 방에서 이 시간 안에 아무도 못 맞히면 정답을 공개해요. "끝까지"는 곡이 끝날 때까지예요.</span>
</label>
<fieldset className="card stack" style={{ margin: 0 }}>
<legend style={{ fontWeight: 800, padding: '0 6px' }}>채팅 도배 방지</legend>
<label className="check">

View File

@@ -328,6 +328,100 @@ input.input.sm { width: 76px; }
.sheet { background: var(--surface); border: 2px solid var(--ink); border-radius: 18px; box-shadow: 6px 6px 0 var(--ink); padding: 22px; width: min(420px, 100%); display: flex; flex-direction: column; gap: 14px; }
.sheet:focus { outline: none; }
/* ---------------------------------------------------------------- game (docs/03 게임 화면, mockups/game.html) */
.kbd { display: inline-block; font-size: 0.72rem; font-weight: 750; padding: 0 5px; border-radius: 5px; border: 1.5px solid currentColor; opacity: 0.7; line-height: 1.5; }
.game { display: flex; flex-direction: column; min-height: calc(100vh - 64px - 56px); }
.gbar { display: flex; align-items: center; gap: 12px; padding: 9px 24px; background: #1e1b18; color: #f5efe3; flex-wrap: wrap; }
.gbar .q { font-weight: 850; font-size: 1.15rem; letter-spacing: -0.02em; }
.gbar .q span { opacity: 0.55; font-weight: 700; }
.badge.dark { background: #3a352f; color: #f5efe3; }
.gbtn { background: #2a2622; color: #fff; border-color: #f5efe3; box-shadow: 0 2px 0 #f5efe3; }
.gbtn.on { background: var(--mustard); color: #1e1b18; }
.gbtn:disabled { opacity: 0.45; }
.vol { display: inline-flex; align-items: center; gap: 6px; font-size: 0.9rem; }
.vol input { width: 90px; accent-color: var(--mustard); }
.ggrid { flex: 1; display: grid; grid-template-columns: 250px minmax(0, 1fr) 280px; gap: 16px; padding: 16px 20px; min-height: 0; max-width: 1600px; width: 100%; margin: 0 auto; }
.side { background: var(--surface); border: 1.5px solid var(--line); border-radius: var(--radius); padding: 14px; overflow-y: auto; max-height: calc(100vh - 190px); }
.side h3 { font-size: 0.85rem; font-weight: 800; color: var(--text-sub); margin-bottom: 8px; }
.scoreboard ol { list-style: none; margin: 0; padding: 0; }
.sb { display: flex; align-items: center; gap: 8px; padding: 6px; border-radius: 10px; font-weight: 700; font-size: 0.93rem; transition: transform 0.3s; }
.sb .rk { width: 20px; text-align: center; font-weight: 850; color: var(--text-sub); }
.sb .nm { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; }
.sb .sc { margin-left: auto; font-weight: 850; font-size: 1.05rem; }
.sb.me { background: var(--primary-soft); }
.sb.first .rk { color: var(--mustard); font-size: 1.1rem; }
.sb.off { opacity: 0.5; }
.gcenter { display: flex; flex-direction: column; gap: 12px; min-width: 0; min-height: 0; }
.stage { min-height: 190px; flex: none; background: var(--surface); border: 2px solid var(--ink); border-radius: var(--radius); display: flex; align-items: center; gap: 26px; padding: 16px 28px; position: relative; overflow: hidden; }
.stage .lp, .reveal .art.lp { width: 150px; height: 150px; border-radius: 50%; background: repeating-radial-gradient(circle at center, #1c1a1f 0 5px, #2a2830 5px 6.5px); position: relative; flex: none; box-shadow: 6px 6px 0 #174f56; }
.stage .lp::after { content: '?'; position: absolute; inset: 47px; border-radius: 50%; background: var(--mustard); display: flex; align-items: center; justify-content: center; font-weight: 900; font-size: 30px; color: #1e1b18; }
.stage .lp.spin { animation: lpspin 1.8s linear infinite; }
@keyframes lpspin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .stage .lp.spin { animation: none; } }
.sinfo { flex: 1; min-width: 0; }
.sinfo .mode { font-size: 0.87rem; font-weight: 750; color: var(--text-sub); }
.sinfo .big { font-size: 1.7rem; font-weight: 850; letter-spacing: -0.03em; margin: 4px 0 10px; }
.countdown { font-size: 3.2rem; font-weight: 900; line-height: 1.1; color: var(--primary); }
.bar { height: 10px; border-radius: 9px; background: var(--surface-3); overflow: hidden; }
.bar i { display: block; height: 100%; background: var(--primary); transition: width 0.2s linear; }
.times { display: flex; justify-content: space-between; color: var(--text-sub); font-weight: 700; margin-top: 4px; }
.limit { margin-top: 4px; }
.hint { display: inline-flex; align-items: center; gap: 10px; background: #fbf3e0; color: #1e1b18; border: 2px dashed #1e1b18; border-radius: 12px; padding: 6px 14px; font-weight: 850; font-size: 1.4rem; letter-spacing: 0.14em; }
.hint small { font-size: 0.75rem; letter-spacing: 0; font-weight: 750; color: #6b6157; }
.lyrics-card { background: var(--surface-2); border-radius: 12px; padding: 10px 16px; font-size: 1.1rem; font-weight: 700; line-height: 1.75; margin-bottom: 8px; }
.stage-note { position: absolute; left: 0; right: 0; bottom: 0; background: var(--warning-soft); padding: 6px 16px; font-weight: 700; font-size: 0.87rem; }
.late { position: absolute; right: 14px; top: 12px; display: flex; flex-direction: column; gap: 6px; }
.reveal { display: flex; align-items: center; gap: 24px; width: 100%; }
.reveal .art { width: 150px; height: 150px; object-fit: cover; border: 2px solid var(--ink); border-radius: 12px; flex: none; box-shadow: 5px 5px 0 #174f56; }
.chat.big { flex: 1; min-height: 340px; border: 2px solid var(--ink); padding: 12px 18px 14px; }
.chat.big .chat-log { height: auto; flex: 1; min-height: 240px; max-height: 52vh; font-size: 1.07rem; line-height: 1.62; }
.chat.big .input { min-height: 56px; font-size: 1.15rem; border-width: 2.5px; }
.chat-line.ok, .chat-line.ok b { color: var(--correct) !important; font-weight: 800; }
.ans-gap { height: 1.62em; }
.ans-text { height: 1.62em; text-align: center; font-weight: 900; font-size: 1.3rem; letter-spacing: -0.02em; }
.ans-text span { border-bottom: 4px solid var(--mustard); padding: 0 6px; }
.answer-item.none .ans-text { color: var(--text-sub); }
.answer-item.none .ans-text span { border-bottom-color: var(--line); }
.typing { font-size: 0.83rem; color: var(--text-sub); font-weight: 650; min-height: 1.3em; display: flex; align-items: center; gap: 6px; }
.dots { display: inline-flex; gap: 3px; }
.dots i { width: 5px; height: 5px; border-radius: 50%; background: var(--text-sub); animation: dot 1s infinite; }
.dots i:nth-child(2) { animation-delay: 0.15s; }
.dots i:nth-child(3) { animation-delay: 0.3s; }
@keyframes dot { 50% { opacity: 0.2; } }
.hist .h { padding: 8px 4px; border-bottom: 1.5px dashed var(--line); font-size: 0.9rem; }
.hist .h:last-child { border-bottom: 0; }
.hist .t { font-weight: 800; }
.hist .m { color: var(--text-sub); font-size: 0.8rem; margin-top: 2px; display: flex; align-items: center; gap: 6px; }
.hist .n { display: inline-block; width: 22px; font-weight: 850; color: var(--text-sub); }
.mini-stars { font-weight: 850; font-size: 0.8rem; }
.unlock-overlay { position: fixed; inset: 0; z-index: 40; background: rgba(20, 18, 14, 0.55); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; color: #fff; text-align: center; padding: 20px; }
.unlock-overlay .btn { font-size: 1.3rem; min-height: 64px; padding: 0 28px; }
.sound-card { background: var(--warning-soft); border-color: var(--ink); }
.result .rank td, .result .rank th { font-size: 0.95rem; }
.songlist { margin: 0; padding-left: 0; list-style: none; display: flex; flex-direction: column; gap: 6px; }
.songlist a { font-size: 0.85rem; }
.saved-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; max-height: 50vh; overflow-y: auto; }
.saved-list li { display: flex; align-items: center; gap: 8px; border: 1.5px solid var(--line); border-radius: 10px; padding: 8px 10px; }
@media (max-width: 1100px) {
.ggrid { grid-template-columns: minmax(0, 1fr); }
.ggrid .side { max-height: none; }
.scoreboard { order: 2; }
.scoreboard ol { display: flex; gap: 6px; overflow-x: auto; }
.scoreboard .sb { flex: none; border: 1.5px solid var(--line); }
.hist { order: 3; max-height: 220px !important; }
}
@media (max-width: 600px) {
.gbar { padding: 8px 12px; gap: 8px; }
.gbar .kbd { display: none; }
.ggrid { padding: 10px; gap: 10px; }
.stage { min-height: 0; padding: 10px 14px; gap: 14px; }
.stage .lp, .reveal .art, .reveal .art.lp { width: 72px; height: 72px; box-shadow: 3px 3px 0 #174f56; }
.stage .lp::after { inset: 24px; font-size: 16px; }
.sinfo .big { font-size: 1.2rem; margin: 2px 0 6px; }
.countdown { font-size: 2.2rem; }
.chat.big .chat-log { max-height: 46vh; }
}
/* ---------------------------------------------------------------- responsive */
@media (max-width: 960px) {
.hero { grid-template-columns: 1fr; }

View File

@@ -9,9 +9,9 @@
| 2. 배포 먼저 ✔ | Docker, 2974 포트, NPMplus, 인증서 | https://mquiz.tkrmagid.kr 에서 로그인 실제 확인 |
| 3. 노래 DB 1차 | sta_songs 803곡 + 노라보세 8,572곡 가져오기, 멜론 정보, 유튜브 Topic 매칭 | 곡 9천+, 유튜브 확정률 90%+, 관리자 노래 목록에서 확인 |
| 4. 방·로비 ✔ | 방 목록, 방 만들기, 인원 무제한, 방 설정 전체(04 문서) | 설정 변경이 모두에게 즉시 반영, "조건에 맞는 곡 N곡" 정확 |
| 5. 게임 핵심 | 라운드 진행, 숨긴 유튜브 플레이어 동기화 재생(준비·동시 시작·버퍼링 일시정지), 정답 판정, 점수, 결과, 이어풀기·저장/불러오기 | 3명 동시 e2e로 30문제 끝까지, 정답 판정 단위 테스트 |
| 6. 채팅 | 가운데 아래 큰 채팅, 입력 중, 5줄 정답 블록, 단축키 | 체감 지연 없음(로컬 왕복 < 50ms), Ctrl+I/K 동작 |
| 7. 힌트·스킵·모드 | 초성 힌트(시간/직접선택 투표), 스킵·다시듣기 투표, 가수노래·가사 모드, 하이라이트 | 모드 3종 e2e |
| 5. 게임 핵심 ✔ | 라운드 진행, 숨긴 유튜브 플레이어 동기화 재생(준비·동시 시작·버퍼링 일시정지), 정답 판정, 점수, 결과, 이어풀기·저장/불러오기 | 3명 동시 e2e로 30문제 끝까지, 정답 판정 단위 테스트 |
| 6. 채팅 ✔ | 가운데 아래 큰 채팅, 입력 중, 5줄 정답 블록, 단축키 | 체감 지연 없음(로컬 왕복 < 50ms), Ctrl+I/K 동작 |
| 7. 힌트·스킵·모드 ✔ | 초성 힌트(시간/직접선택 투표), 스킵·다시듣기 투표, 가수노래·가사 모드, 하이라이트 | 모드 3종 e2e |
| 8. 관리자 완성 | 노래 CRUD·필터·후보 확인·하이라이트 지정, 수집 작업 UI, 통계, 사용자/관리자 | 관리자 e2e(joke-app admin.e2e 확장) |
| 9. 수집 확장 | 멜론·지니·벅스 연도별/실시간, 유튜브·스포티파이 플레이리스트, 노래방 차트, 난이도 계산 | 곡 1만+, 난이도 분포 확인 |
| 10. 다듬기 | 휴대폰 화면, 다크 테마, 접근성 검사, 부하 테스트(100명 방) | axe 위반 0, 100명 방에서 채팅 지연 < 200ms |
@@ -24,3 +24,6 @@
- 2026-10-18 2단계: .9 `/home/claude/projects/music_quiz`에 Docker(포트 2974, 메모리 1GB) 배포, NPMplus 프록시 호스트 14 + Let's Encrypt(인증서 32, HTTP/2·HSTS·CSP·noindex). 실제 주소에서 첫 화면·게스트 로그인·WebSocket·디스코드 동의 화면 이동 확인. 디스코드 실제 로그인(Redirect 등록 확인)은 사용자 로그인으로 확인
- 2026-10-18 3단계(진행 중): 곡 8,958곡(노라보세 8,518 + 스타맵 새 곡 440, 겹치는 363곡은 합침), 가사 8,261곡, 관리자 노래·수집 화면 배포. 유튜브 원곡 확정은 쿠키가 로그아웃돼 멈춤 → 새 쿠키를 받으면 매일 04:10에 하루 3,000곡씩(약 3일) 진행. 로그인 없는 대체 검색은 표본 60곡 중 19곡만 확정돼 대량 실행하지 않음(같은 집 IP의 music_bot_v2 차단 위험)
- 2026-10-18 4단계: 방 만들기(게스트 포함)·숫자 6자리 코드·열린 방 목록(전체/대기 중/진행 중, 🔒 비밀번호 방), 인원 무제한 대기실(방장·준비·방장 넘기기·내보내기, 끊겨도 60초 자리 유지), 방 설정 전체가 모두에게 즉시 반영, "조건에 맞는 곡 N곡" + 원곡 확인 중 곡 수(1분마다 다시 셈), 대기실 채팅, 서버 재시작 안내. 서버 테스트 49개, 브라우저 e2e(`e2e/rooms.e2e.ts`, 3명) 11단계 통과. 결정은 12 문서 "4단계 확인". 같은 날 새 쿠키로 유튜브 원곡 찾기 다시 시작(표본 20곡 중 16곡 확정)
- 2026-10-18 사용자: "목록으로 나갔을 때 방에 아무도 없으면 바로 삭제, 나머지 전부 진행" → 마지막 사람이 나가면(← 방 목록·로고·뒤로 가기·나가기·내보내기 시간 초과) 방을 바로 닫음. 만들고 아무도 안 들어간 방만 5분. 탭 닫기·끊김은 60초 자리 유지 그대로
- 2026-10-18 5~7단계(엔진이 하나라 함께 진행): 서버 게임 진행기(`apps/server/src/game/engine.ts`) — 출제 목록(최근 3게임 곡 뒤로, 같은 가수 연속 안 나오게), 전원 준비 뒤 같은 시각 재생, 버퍼링·소리 차단이면 모두 멈추고 같은 위치에서 다시, 30초 늦은 사람은 방장이 이번 문제만 제외, 재생 오류 100/101/150이면 같은 번호로 다른 곡(그 곡은 재생 불가 표시), 문제 시간(멈춘 시간 제외), 클립은 재생 위치로 정지. 정답 판정(`packages/shared/src/answer.ts`), 먼저 맞힌 1명 +1(동점은 평균 정답 시간), 정답 줄 + 5줄 블록 한 덩어리, 입력 중, Ctrl+I/K/R, 힌트(시간·직접선택), 스킵·다시듣기 투표, 3모드, 결과·이어풀기·다시 하기, 퀴즈 저장·불러오기(디스코드 계정, 20개). 서버 테스트 80개, 브라우저 e2e(`e2e/game.e2e.ts`) 3명 30문제 끝까지 + 모드 3종 + 실제 유튜브 2명 동시 재생(위치 차이 0.02초, 3초 클립 정지 오차 0.01초 이내) 통과. 결정은 12 문서 "5~7단계 확인"

View File

@@ -130,3 +130,19 @@
4. 게스트도 방을 만들 수 있다. 퀴즈 저장은 디스코드 계정만(5단계)
5. 비밀번호 방은 열린 방 목록에 🔒로 보이고 들어갈 때 비밀번호를 묻는다. 비밀번호를 정하기 전에는 잠기지 않는다고 방장에게 안내
6. 방 공개 기본값은 공개. 비공개 방은 목록에 안 나오고 코드·링크로만 들어온다
## 5~7단계 확인 (2026-10-18, 사용자: "나머지 전부 진행", 문서 추천안대로)
1. 마지막 사람이 나가면 방을 바로 닫는다(사용자 요청). 끊김은 60초 자리 유지, 만들고 아무도 안 들어간 방은 5분
2. 게임 시작은 방장이 언제든(준비는 표시만). 곡이 문제 수보다 적으면 "N곡뿐이에요" 확인 뒤 시작
3. 정답은 첫 재생(3·2·1이 끝난 뒤)부터 인정. 카운트다운 중에 친 말은 그냥 채팅
4. 게임 중에 들어온 사람·다시 연결한 사람은 다음 문제부터 정답 인정(지금 문제는 채팅만). 그 문제의 참가자 명단은 문제를 준비할 때 정함
5. 문제 제한 시간: 짧은 클립은 사이트 설정 `문제 하나의 제한 시간`(기본 60초)과 클립 길이+5초 중 긴 쪽, "끝까지"는 곡이 끝나면 문제도 끝, 가사 모드는 보고맞출시간(무제한이면 맞히거나 스킵할 때까지)
6. 정답 공개 5초 동안 음악은 이어서 나온다(각자 화면에서, 동기화 없이)
7. 재생위치 "하이라이트부터": 관리자 지정·heatmap 값이 없으면 곡 길이의 30% 지점. 끝나기 5초 전보다 뒤면 처음부터
8. 소리 허용 클릭: 대기실의 `참가 (소리 켜기)` 또는 게임 화면 덮개 버튼. 클릭 안에서 소리 0으로 짧은 곡을 한 번 틀었다 멈춘다
9. 가사 카드: 두 번 이상 나오는 줄(후렴)을 뺀 첫 덩어리의 가운데 4줄, 제목 단어는 ○, 힌트가 나오면 2줄 더
10. 초성 힌트: 한글은 초성, 영문 단어는 첫 글자 + `_`(예: `L___ W___ A__`), 정답방식이 제목+가수면 `제목 - 가수` 둘 다
11. 점수판 순위: 점수 → 평균 정답 시간. 같으면 같은 순위
12. 퀴즈 저장: 결과 화면(또는 방장이 일시정지한 동안), 저장하면 설정·나온 곡·점수(계정별). 불러오면 방 이름·공개 설정은 지금 방 것을 유지
13. 남은 사람 검증(사람 손으로): 광고가 붙는 곡, 아이폰 사파리, 안드로이드 크롬, 클릭 없이 들어온 경우 — Q1 "남은 검증" 그대로

380
e2e/game.e2e.ts Normal file
View File

@@ -0,0 +1,380 @@
/**
* Stage 5~7 E2E (docs/10 5단계): three guests play 30 questions to the end in real browsers.
* Part A uses the fake player (localStorage mq:fakePlayer) so 30 questions run in about a minute without YouTube:
* start, synced play, answers by chat (정답 줄 + 5줄 블록 on every screen), scores, past questions, buffering pause for
* everyone, skip / hint / replay votes with Ctrl+K / Ctrl+I / Ctrl+R, a broken video swapped, typing indicator,
* reconnect mid-game, results with YouTube links, 이어풀기, 다시 하기, phone / dark screens, the last one out closes the room.
* Part B plays real YouTube Topic videos in two browsers: sound on after the entry click, same start, 3s clip stop.
* Run: bun run build && bun e2e/game.e2e.ts (needs /usr/bin/google-chrome; Part B needs internet, skip with E2E_NO_YT=1)
*/
import { chromium, type Browser, type Page } from 'playwright-core';
import { mkdirSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { loadConfig } from '../apps/server/src/config';
import { startServer } from '../apps/server/src/server';
import { Catalog } from '../apps/server/src/collector/catalog';
const PORT = Number(process.env.E2E_PORT ?? 4621);
const ORIGIN = `http://localhost:${PORT}`;
const SHOTS = process.env.E2E_SHOTS ?? join(import.meta.dir, '../test-results');
mkdirSync(SHOTS, { recursive: true });
const config = loadConfig({
PORT: String(PORT),
DB_PATH: join(mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'mq-e2e-')), 'app.db'),
PUBLIC_ORIGIN: ORIGIN,
SUPERADMIN_DISCORD_IDS: '900000000000000001',
});
const app = startServer({
config,
log: () => {},
staticDir: join(import.meta.dir, '../apps/web/dist'),
stopWaitMs: 200,
gameTiming: { countdownMs: 700, revealMs: 700, resumeLeadMs: 300 },
});
// Catalog: 32 fake songs (3 by the same singer) + 3 real Topic videos for part B (another level, so part A never picks them).
const db = app.db;
{
const c = new Catalog(db);
for (let i = 1; i <= 32; i++) {
const [id] = c.upsert({ title: `곡${i}`, artists: [{ name: i <= 3 ? '같은가수' : `가수${i}` }], year: 1990 + (i % 30), genres: ['kpop', 'ballad'], source: 'e2e', ref: `f${i}` });
c.autoLevel(id!, 'all', 3);
db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = ?, duration_sec = 200 WHERE id = ?").run(`fake${String(i).padStart(7, '0')}`, id!);
if (i <= 2) db.query('INSERT INTO lyrics (song_id, text, source, fetched_at) VALUES (?, ?, ?, 0)').run(id!, `첫 소절 곡${i}\n둘째 줄 ${i}\n셋째 줄\n넷째 줄\n다섯째 줄\n여섯째 줄\n후렴 곡${i}\n후렴 곡${i}`, 'e2e');
}
const real: [string, string, string, number][] = [
['광 (狂)', 'SG워너비', 'VO88htcm09E', 237],
['가져가', '홍경민', 'Q7Q_qavUPdM', 221],
['Be Natural', '에스이에스', 'YWP5K88l9G0', 282],
];
for (const [title, artist, vid, dur] of real) {
const [id] = c.upsert({ title, artists: [{ name: artist }], year: 2000, genres: ['kpop'], source: 'e2e', ref: vid });
c.autoLevel(id!, 'all', 9);
db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = ?, duration_sec = ? WHERE id = ?").run(vid, dur, id!);
}
}
const titleOf = (vid: string) => db.query<{ title: string; artist: string }, [string]>('SELECT title, artist FROM songs WHERE youtube_id = ?').get(vid)!;
const browser: Browser = await chromium.launch({
executablePath: process.env.CHROME ?? '/usr/bin/google-chrome',
headless: true,
args: ['--autoplay-policy=document-user-activation-required'],
});
const errors: string[] = [];
const step = async (name: string, fn: () => Promise<void>) => {
if (process.env.E2E_ONLY_YT && name.startsWith('A:')) return;
const t0 = performance.now();
try {
await fn();
console.log(`✓ ${name} (${Math.round(performance.now() - t0)}ms)`);
} catch (e) {
console.log(`✗ ${name}: ${(e as Error).message.split('\n')[0]}`);
throw e;
}
};
const expect = (ok: unknown, msg: string) => {
if (!ok) throw new Error(msg);
};
async function guestPage(name: string, opts: { fake?: boolean; width?: number; height?: number; dark?: boolean; mobile?: boolean } = {}): Promise<Page> {
const ctx = await browser.newContext({
viewport: { width: opts.width ?? 1440, height: opts.height ?? 900 },
locale: 'ko-KR',
colorScheme: opts.dark ? 'dark' : 'light',
isMobile: opts.mobile,
hasTouch: opts.mobile,
});
if (opts.fake !== false) await ctx.addInitScript(() => localStorage.setItem('mq:fakePlayer', '1'));
const p = await ctx.newPage();
p.on('pageerror', (e) => errors.push(`${name}: ${e.message}`));
await p.goto(ORIGIN + '/');
await p.getByLabel('게스트 닉네임 (2~12자)').fill(name);
await p.getByRole('button', { name: '게스트로 시작' }).click();
await p.getByRole('button', { name: `내 계정: ${name}` }).waitFor();
return p;
}
async function makeRoom(p: Page, cfg: Record<string, unknown>): Promise<string> {
const code = await p.evaluate(async (config) => {
const r = await fetch('/api/rooms', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ config }) });
return (await r.json()).code as string;
}, cfg);
await p.goto(`${ORIGIN}/r/${code}`);
await p.locator('.pool-banner').waitFor();
return code;
}
const video = (p: Page) => p.evaluate(() => (window as any).mqPlayer?.video() as string | null);
const qText = (p: Page) => p.locator('.gbar .q').innerText();
/** Wait until this page is on question n with the music running (after the 3·2·1). */
async function playing(p: Page, n: number, timeout = 15000) {
await p.locator('.gbar .q', { hasText: new RegExp(`^문제 ${n} `) }).waitFor({ timeout });
await p.locator('.stage .lp.spin').waitFor({ timeout });
}
async function say(p: Page, text: string) {
const input = p.getByLabel('채팅 입력');
await input.fill(text);
await input.press('Enter');
}
let failed = false;
let code = '';
try {
const a = await guestPage('방장');
const b = await guestPage('철수');
const c = await guestPage('영희');
const all = [a, b, c];
await step('A: 3명이 대기실에 모여 소리 켜기 → 방장이 시작, 모두 게임 화면 "문제 1 / 30"', async () => {
code = await makeRoom(a, { count: 30, listenSec: 3, hint: 'manual', hintVotes: '1', skipVotes: '2/3', replayVotes: '1' });
for (const p of [b, c]) {
await p.goto(`${ORIGIN}/r/${code}`);
await p.locator('.pool-banner').waitFor();
}
await a.locator('.pl', { hasText: '영희' }).waitFor();
for (const p of all) await p.getByRole('button', { name: '참가 (소리 켜기)' }).click();
await a.getByText('조건에 맞는 곡 32곡').waitFor();
await a.getByRole('button', { name: '게임 시작' }).click();
for (const p of all) await p.locator('.gbar .q', { hasText: '문제 1 / 30' }).waitFor({ timeout: 8000 });
await a.locator('.countdown').waitFor({ timeout: 4000 });
});
const answer = async (n: number, who: Page, opts: { wrongFirst?: boolean } = {}) => {
await playing(who, n);
const vid = await video(who);
expect(vid, `${n}번 영상 없음`);
const s = titleOf(vid!);
if (opts.wrongFirst) await say(who, '이거 뭐였지');
await say(who, s.title);
for (const p of all) await p.locator('.answer-item .ans-text', { hasText: `${s.title} - ${s.artist}` }).last().waitFor({ timeout: 5000 });
return s;
};
await step('A: 1번 — 3명 같은 곡·같은 시각 재생, 채팅 정답 → 모든 화면에 정답 줄(✔) + 5줄 블록, 점수판 +1, 지난 문제', async () => {
await Promise.all(all.map((p) => playing(p, 1)));
const vids = await Promise.all(all.map(video));
expect(new Set(vids).size === 1, `서로 다른 곡: ${vids.join(',')}`);
const pos = await Promise.all(all.map((p) => p.evaluate(() => (window as any).mqPlayer.pos() as number)));
expect(Math.max(...pos) - Math.min(...pos) < 0.3, `재생 위치 차이 ${pos.join(',')}`);
const s = await answer(1, b, { wrongFirst: true });
// the line right above the block is the answer line, with ✔
const item = c.locator('.answer-item').last();
expect((await item.locator('.chat-line.ok').innerText()).includes(s.title), '정답 줄이 블록 바로 위에 없음');
expect((await item.locator('.ans-gap').count()) === 4, '공백 줄 수가 다름');
await a.locator('.sb', { hasText: '철수' }).locator('.sc', { hasText: '1' }).waitFor();
await c.locator('.hist .h', { hasText: s.title }).waitFor();
await a.locator('.reveal .big', { hasText: s.title }).waitFor();
});
await step('A: 입력 중 표시 — 영희가 치는 동안 다른 사람 화면에 "영희님이 입력 중…"', async () => {
await playing(c, 2);
await c.getByLabel('채팅 입력').fill('음');
await a.getByText('영희님이 입력 중…').waitFor({ timeout: 4000 });
await c.getByLabel('채팅 입력').fill('');
await answer(2, a);
});
await step('A: 3번 — 철수 화면 버퍼링 → 모두 "잠시 멈춤 — 철수님 버퍼링 중", 같은 곳에서 다시 재생', async () => {
// set once question 3 is being prepared (the reveal of 2 also plays): 철수's next start buffers
await b.locator('.gbar .q', { hasText: /^문제 3 / }).waitFor({ timeout: 10000 });
// 철수 needs 2s to buffer again, so the pause is visible
await b.evaluate(() => Object.assign((window as any).mqFake, { stallNext: true, loadMs: 2000 }));
await a.getByText('잠시 멈춤 — 철수님 버퍼링 중').waitFor({ timeout: 10000 });
await c.getByText('잠시 멈춤 — 철수님 버퍼링 중').waitFor({ timeout: 3000 });
await b.evaluate(() => ((window as any).mqFake.loadMs = 40));
await answer(3, c);
});
await step('A: 4번 — Ctrl+K 2명(2/3) → 스킵, 회색 블록 "스킵했어요"', async () => {
await playing(a, 4);
await a.keyboard.press('Control+k');
await b.locator('.gbtn', { hasText: '스킵 1/2' }).waitFor();
await playing(b, 4);
await b.keyboard.press('Control+k');
for (const p of all) await p.locator('.answer-item.none', { hasText: '스킵했어요' }).last().waitFor({ timeout: 5000 });
});
await step('A: 5번 — Ctrl+I 힌트(직접선택, 1명) → 초성 공개, Ctrl+R 다시듣기 → "다 같이 다시 들어요"', async () => {
await playing(c, 5);
await c.keyboard.press('Control+i');
for (const p of all) await p.locator('.stage .hint').waitFor({ timeout: 4000 });
expect(/ㄱ\d+/.test(await a.locator('.stage .hint').innerText()), '초성 힌트 모양이 다름');
await a.keyboard.press('Control+r');
await b.locator('.chat-sys', { hasText: '다 같이 다시 들어요' }).waitFor({ timeout: 4000 });
await answer(5, a);
});
await step('A: 6번 — 한 명 화면에서 영상 오류 150 → 모두 다른 곡으로 바뀌고 번호는 그대로', async () => {
// the reveal of 5 is still showing: the next load fails on 영희's screen
await c.evaluate(() => ((window as any).mqFake.failNext = 150));
await a.locator('.chat-sys', { hasText: '다른 곡으로 바꿨어요' }).waitFor({ timeout: 8000 });
await a.locator('.gbar .q', { hasText: /^문제 6 \/ 30$/ }).waitFor();
await answer(6, b);
});
await step('A: 7~30번 — 돌아가며 정답, 15번에 영희 새로고침(다시 소리 켜기 → 다음 문제부터 참가)', async () => {
for (let n = 7; n <= 30; n++) {
const who = all[n % 3]!;
if (n === 15) {
await c.reload();
await c.getByRole('button', { name: /참가 \(소리 켜기\)|눌러서 소리 켜기/ }).click({ timeout: 10000 }).catch(() => {});
}
await answer(n, who === c && n === 15 ? a : who);
}
});
await step('A: 결과 화면 — 순위·점수·맞힌 곡·가장 빨리 맞힌 곡, 곡 목록 30개 + 유튜브 링크', async () => {
for (const p of all) await p.getByRole('heading', { name: '🏁 게임 결과' }).waitFor({ timeout: 10000 });
const rows = await a.locator('.rank tbody tr').count();
expect(rows === 3, `순위 줄 ${rows}`);
expect((await a.locator('.songlist li').count()) === 30, '곡 목록 30개 아님');
expect((await a.locator('.songlist a[href^="https://youtu.be/"]').count()) === 30, '유튜브 링크 30개 아님');
const total = await a.locator('.rank tbody td:nth-child(3)').allInnerTexts();
expect(total.map(Number).reduce((x, y) => x + y, 0) === 29, `점수 합 ${total.join(',')} (스킵 1문제 빼고 29)`);
await a.screenshot({ path: join(SHOTS, 'stage5-result.png'), fullPage: true });
expect(!(await b.getByRole('button', { name: /이어풀기/ }).isVisible()), '손님에게 이어풀기 버튼이 보임');
});
await step('A: 이어풀기 → 나온 곡을 뺀 남은 곡만, 점수 이어서 / 다시 하기 → 대기실', async () => {
await a.getByRole('button', { name: /이어풀기/ }).click();
await a.locator('.gbar .q', { hasText: /^문제 1 \/ [12]$/ }).waitFor({ timeout: 8000 });
const total = Number((await qText(a)).split('/')[1]);
for (let n = 1; n <= total; n++) await answer(n, a);
await a.getByRole('heading', { name: '🏁 게임 결과' }).waitFor({ timeout: 10000 });
await a.getByRole('button', { name: /이어풀기/ }).isDisabled();
await a.getByRole('button', { name: '↺ 다시 하기' }).click();
for (const p of all) await p.locator('.pool-banner').waitFor({ timeout: 5000 });
});
await step('A: 게임 화면 휴대폰(390px)·다크 화면', async () => {
const m = await guestPage('폰손님', { width: 390, height: 844, mobile: true });
await m.goto(`${ORIGIN}/r/${code}`);
await m.locator('.pool-banner').waitFor();
await m.getByRole('button', { name: '참가 (소리 켜기)' }).click();
const d = await guestPage('다크손님', { dark: true });
await d.goto(`${ORIGIN}/r/${code}`);
await d.locator('.pool-banner').waitFor();
await d.getByRole('button', { name: '참가 (소리 켜기)' }).click();
await a.getByRole('button', { name: '게임 시작' }).click();
await playing(m, 1);
await say(b, '모바일 화면 확인용');
await m.screenshot({ path: join(SHOTS, 'stage5-game-mobile.png'), fullPage: true });
await d.screenshot({ path: join(SHOTS, 'stage5-game-dark.png'), fullPage: true });
await a.screenshot({ path: join(SHOTS, 'stage5-game.png'), fullPage: true });
const overflow = await m.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
expect(overflow <= 0, `휴대폰 화면이 가로로 ${overflow}px 넘침`);
await a.getByRole('button', { name: '⏹ 끝내기' }).click();
await a.getByRole('button', { name: '끝내기', exact: true }).click();
await a.getByRole('heading', { name: '🏁 게임 결과' }).waitFor();
for (const p of [m, d]) {
await p.getByRole('link', { name: '← 방 목록' }).click();
await p.waitForURL(ORIGIN + '/');
await p.waitForTimeout(300);
await p.context().close();
}
});
await step('A: 모드 3종 — 가수노래(고른 가수 곡만, 위에 "선택한 가수"), 가사보고(음악 없이 가사 카드, 제목은 ○로 가림)', async () => {
// 가수노래: 같은가수 3곡 중에서만
await a.getByRole('button', { name: '↺ 다시 하기' }).click();
await a.locator('.pool-banner').waitFor();
await a.getByRole('radiogroup', { name: '모드' }).getByRole('radio', { name: /가수노래 맞추기/ }).click();
await a.getByLabel('가수 검색').fill('같은가수');
await a.getByRole('option', { name: /같은가수/ }).click();
await a.getByText('조건에 맞는 곡 3곡').waitFor({ timeout: 5000 });
await a.getByRole('button', { name: '게임 시작' }).click();
await a.getByRole('button', { name: '그대로 시작' }).click();
await playing(a, 1);
await a.getByText('선택한 가수: 같은가수').waitFor();
expect(/^곡[123]$/.test(titleOf((await video(a))!).title), '고른 가수 곡이 아님');
await answer(1, b);
await a.getByRole('button', { name: '⏹ 끝내기' }).click();
await a.getByRole('button', { name: '끝내기', exact: true }).click();
await a.getByRole('heading', { name: '🏁 게임 결과' }).waitFor();
await a.getByRole('button', { name: '↺ 다시 하기' }).click();
await a.locator('.pool-banner').waitFor();
// 가사보고: 가사가 있는 2곡
await a.getByRole('radiogroup', { name: '모드' }).getByRole('radio', { name: /가사보고 맞추기/ }).click();
await a.getByText('조건에 맞는 곡 2곡').waitFor({ timeout: 5000 });
await a.getByRole('button', { name: '게임 시작' }).click();
await a.getByRole('button', { name: '그대로 시작' }).click();
await c.locator('.lyrics-card').waitFor({ timeout: 8000 });
const card = await c.locator('.lyrics-card').innerText();
expect(!/곡\d/.test(card), `가사 카드에 제목이 보임: ${card}`);
expect(!(await c.locator('.stage .lp').count()), '가사 모드에 LP가 보임');
const n = /둘째 줄 (\d)/.exec(card)?.[1];
expect(n, `가사 카드 ${card}`);
await c.locator('.countdown').waitFor({ state: 'detached', timeout: 4000 });
await say(c, `곡${n}`);
for (const p of all) await p.locator('.answer-item .ans-text', { hasText: `곡${n} - 같은가수` }).last().waitFor({ timeout: 5000 });
await a.getByRole('button', { name: '⏹ 끝내기' }).click();
await a.getByRole('button', { name: '끝내기', exact: true }).click();
await a.getByRole('heading', { name: '🏁 게임 결과' }).waitFor();
});
await step('A: 모두 "← 방 목록"으로 나가면 방이 바로 사라짐', async () => {
for (const p of all) {
await p.getByRole('link', { name: '← 방 목록' }).click();
await p.waitForURL(ORIGIN + '/');
}
await a.waitForTimeout(300);
const r = await a.evaluate(async (cd) => (await fetch(`/api/rooms/${cd}`)).status, code);
const left = [...(app.rooms.get(code)?.players ?? new Map()).entries()].map(([id, pl]) => `${app.users.get(id)?.nickname}:${pl.conns.size}`);
expect(r === 404, `방이 남아 있음 (${r}) ${left.join(',')}`);
});
if (!process.env.E2E_NO_YT) {
await step('B: 실제 유튜브 — 소리 켜기 클릭 후 2명이 같은 순간 재생(소리 켜짐), 3초 클립은 재생 위치로 멈춤, 정답 공개', async () => {
const x = await guestPage('유튜브방장', { fake: false });
const y = await guestPage('유튜브손님', { fake: false });
const rc = await makeRoom(x, { count: 10, level: 9, listenSec: 3, startAt: 'highlight' }).catch(async (e) => {
console.log(' B room page:', (await x.locator('main').innerText().catch(() => '?')).slice(0, 300), x.url());
throw e;
});
await y.goto(`${ORIGIN}/r/${rc}`);
await y.locator('.pool-banner').waitFor();
for (const p of [x, y]) await p.getByRole('button', { name: '참가 (소리 켜기)' }).click();
await x.getByText('조건에 맞는 곡 3곡').waitFor({ timeout: 5000 }).catch(async (e) => {
console.log(' B pool:', await x.locator('.pool-banner').innerText());
throw e;
});
await x.getByRole('button', { name: '게임 시작' }).click();
await x.getByRole('button', { name: '그대로 시작' }).click();
await Promise.all([x, y].map((p) => playing(p, 1, 40000))).catch(async (e) => {
await x.screenshot({ path: join(SHOTS, 'stage5-youtube-fail-x.png') });
console.log(' debug', JSON.stringify(await Promise.all([x, y].map((p) => p.evaluate(() => ({ st: (window as any).mqPlayer?.state(), v: (window as any).mqPlayer?.video(), stage: document.querySelector('.stage')?.textContent }))))));
throw e;
});
await x.waitForTimeout(1200);
const st = await Promise.all([x, y].map((p) => p.evaluate(() => ({ pos: (window as any).mqPlayer.pos(), muted: (window as any).mqPlayer.muted(), state: (window as any).mqPlayer.state() }))));
expect(st.every((s) => s.state === 1 && !s.muted), `재생 상태 ${JSON.stringify(st)}`);
expect(Math.abs(st[0]!.pos - st[1]!.pos) < 0.3, `두 사람 위치 차이 ${JSON.stringify(st)}`);
console.log(` 위치 ${st.map((s) => s.pos.toFixed(3)).join(' / ')}`);
// 3s clip: stops by position
await x.locator('.stage .mode', { hasText: '재생이 끝났어요' }).waitFor({ timeout: 8000 });
const end = await Promise.all([x, y].map((p) => p.evaluate(() => ({ pos: (window as any).mqPlayer.pos(), state: (window as any).mqPlayer.state() }))));
console.log(` 멈춘 위치 ${end.map((s) => s.pos.toFixed(3)).join(' / ')}`);
expect(end.every((s) => s.state === 2), `클립 뒤 정지 안 됨 ${JSON.stringify(end)}`);
const s = titleOf((await video(x))!);
await say(y, s.title.replace(/\s*\(.*\)/, ''));
await x.locator('.reveal .big', { hasText: s.artist }).waitFor({ timeout: 5000 });
await x.screenshot({ path: join(SHOTS, 'stage5-youtube-reveal.png') });
await x.getByRole('button', { name: '⏹ 끝내기' }).click();
await x.getByRole('button', { name: '끝내기', exact: true }).click();
await x.getByRole('heading', { name: '🏁 게임 결과' }).waitFor();
await x.context().close();
await y.context().close();
});
}
expect(errors.length === 0, `페이지 오류: ${errors.join(' | ')}`);
} catch (e) {
console.log(e instanceof Error ? e.message.slice(0, 500) : e);
failed = true;
} finally {
await browser.close();
await app.stop();
}
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
process.exit(failed ? 1 : 0);

View File

@@ -11,7 +11,7 @@
"build": "bun run --filter '@mq/web' build",
"typecheck": "tsc -p packages/shared && tsc -p apps/server && tsc -p apps/web",
"test": "bun test --timeout 20000",
"e2e": "bun run build && bun e2e/login.e2e.ts && bun e2e/rooms.e2e.ts"
"e2e": "bun run build && bun e2e/login.e2e.ts && bun e2e/rooms.e2e.ts && bun e2e/game.e2e.ts"
},
"devDependencies": {
"@types/bun": "1.4.2",

View File

@@ -0,0 +1,100 @@
import { describe, expect, test } from 'bun:test';
import { artistCandidates, chosung, hintText, isCorrect, titleCandidates, type Strictness } from './answer';
const STRICT: Strictness = { space: true, number: true, symbol: true };
const LOOSE: Strictness = { space: false, number: false, symbol: false };
const st = (p: Partial<Strictness>): Strictness => ({ ...STRICT, ...p });
const song = (title: string, artist = '가수', extra: { titleAliases?: string[]; artistAliases?: string[] } = {}) => ({ title, artist, ...extra });
describe('answer candidates (docs/05 정규화)', () => {
test('brackets split into each part and the joined form', () => {
expect(titleCandidates('사랑을 했다(LOVE SCENARIO)')).toEqual(expect.arrayContaining(['사랑을 했다', 'love scenario', '사랑을 했다 love scenario']));
});
test('feat./prod./OST/원곡 tails are dropped', () => {
expect(titleCandidates('Love wins all (Prod. 누군가)')).toContain('love wins all');
expect(titleCandidates('취중고백 (feat. 누구)')).toContain('취중고백');
expect(titleCandidates('Stay With Me [도깨비 OST]')).toContain('stay with me');
expect(titleCandidates('밤양갱 feat. 누구')).toContain('밤양갱');
});
test('multi-artist credits accept any one name, `A (B)` both names', () => {
expect(artistCandidates('허각, 정은지')).toEqual(expect.arrayContaining(['허각', '정은지']));
expect(artistCandidates('RESCENE (리센느)')).toEqual(expect.arrayContaining(['rescene', '리센느']));
expect(artistCandidates('아이유', ['IU'])).toContain('iu');
});
});
describe('정답인식 toggles (docs/12 Q2): on = must match, off = ignored', () => {
test('case and outer spaces never matter', () => {
expect(isCorrect(' bubble pop! ', song('Bubble Pop!'), 'title', STRICT)).toBe(true);
expect(isCorrect('BUBBLE POP!', song('Bubble Pop!'), 'title', STRICT)).toBe(true);
});
test('띄어쓰기', () => {
expect(isCorrect('사건의지평선', song('사건의 지평선'), 'title', STRICT)).toBe(false);
expect(isCorrect('사건의지평선', song('사건의 지평선'), 'title', st({ space: false }))).toBe(true);
expect(isCorrect('사건 의지 평선', song('사건의 지평선'), 'title', st({ space: false }))).toBe(true);
});
test('특수문자', () => {
expect(isCorrect('bubble pop', song('Bubble Pop!'), 'title', STRICT)).toBe(false);
expect(isCorrect('bubble pop', song('Bubble Pop!'), 'title', st({ symbol: false }))).toBe(true);
});
test('숫자', () => {
expect(isCorrect('24시간이 모자라', song('24시간이 모자라'), 'title', STRICT)).toBe(true);
expect(isCorrect('시간이 모자라', song('24시간이 모자라'), 'title', STRICT)).toBe(false);
expect(isCorrect('시간이 모자라', song('24시간이 모자라'), 'title', st({ number: false }))).toBe(true);
});
test('no fuzzy matching', () => {
expect(isCorrect('사건의 지평산', song('사건의 지평선'), 'title', LOOSE)).toBe(false);
expect(isCorrect('사건의', song('사건의 지평선'), 'title', LOOSE)).toBe(false);
});
test('admin aliases absorb common spellings', () => {
expect(isCorrect('good day', song('좋은 날', '아이유', { titleAliases: ['Good Day'] }), 'title', STRICT)).toBe(true);
expect(isCorrect('광', song('광 (狂)', 'SG워너비'), 'title', STRICT)).toBe(true);
});
});
describe('empty-key guard (docs/05 빈 비교 키 방지): sta_songs number/symbol titles', () => {
const titles = ['0+0', '160', '365', '365일', '3! 4!', '3!4!', '11:11', '2 L0VE', 'A', 'Y'];
test('every fixed title is answerable by typing it exactly, under every toggle combination', () => {
for (const t of titles)
for (const space of [true, false])
for (const number of [true, false])
for (const symbol of [true, false]) expect([t, isCorrect(t, song(t), 'title', { space, number, symbol })]).toEqual([t, true]);
});
test('an empty chat or a chat that only loses its digits never matches', () => {
expect(isCorrect('', song('160'), 'title', LOOSE)).toBe(false);
expect(isCorrect('!!!', song('160'), 'title', LOOSE)).toBe(false);
expect(isCorrect('+', song('0+0'), 'title', st({ number: false }))).toBe(false);
expect(isCorrect('일', song('365일'), 'title', st({ number: false }))).toBe(false);
expect(isCorrect('365', song('160'), 'title', LOOSE)).toBe(false);
});
test('kept digits stay strict but other toggles still apply', () => {
expect(isCorrect('0 + 0', song('0+0'), 'title', LOOSE)).toBe(true);
expect(isCorrect('00', song('0+0'), 'title', LOOSE)).toBe(true);
expect(isCorrect('34', song('3! 4!'), 'title', LOOSE)).toBe(true);
expect(isCorrect('3 4', song('3! 4!'), 'title', st({ symbol: false }))).toBe(true);
expect(isCorrect('1111', song('11:11'), 'title', LOOSE)).toBe(true);
});
});
describe('정답방식', () => {
const gwang = song('광 (狂)', 'SG워너비');
test('가수만: one of several artists is enough', () => {
expect(isCorrect('정은지', song('짝사랑', '허각, 정은지'), 'artist', STRICT)).toBe(true);
expect(isCorrect('짝사랑', song('짝사랑', '허각, 정은지'), 'artist', STRICT)).toBe(false);
});
test('제목+가수: either order, separators - / , or space, or none', () => {
for (const t of ['광 sg워너비', 'sg워너비 광', 'sg워너비-광', '광/sg워너비', '광 - SG워너비', '광, sg워너비', '광sg워너비']) expect([t, isCorrect(t, gwang, 'both', STRICT)]).toEqual([t, true]);
expect(isCorrect('광', gwang, 'both', STRICT)).toBe(false);
expect(isCorrect('sg워너비', gwang, 'both', STRICT)).toBe(false);
expect(isCorrect('광 sg워너비 짱', gwang, 'both', STRICT)).toBe(false);
});
});
describe('초성 hint', () => {
test('Hangul initials, other words first letter, spaces kept', () => {
expect(chosung('사건의 지평선')).toBe('ㅅㄱㅇ ㅈㅍㅅ');
expect(chosung('Love wins all')).toBe('L___ W___ A__');
expect(hintText({ title: '광 (狂)', artist: 'SG워너비' }, 'both')).toBe('ㄱ (狂) - S_ㅇㄴㅂ');
expect(hintText({ title: '취중고백 (feat. 누구)', artist: '김민석' }, 'title')).toBe('ㅊㅈㄱㅂ');
});
});

View File

@@ -0,0 +1,183 @@
/**
* Quiz answer judge (docs/05 정답 판정, docs/12 Q2). Shared by the server (the judge) and the browser (nothing secret here).
* - Candidates: the title as is, without feat/prod/OST tails, without brackets, each bracketed part alone, admin aliases
* - 정답인식 toggles: on = that element must match too, off = ignored. Case and outer spaces never matter
* - Empty keys never match; a candidate that loses all its letters keeps digits, then symbols (`0+0`, `160`, `11:11`)
* - No fuzzy matching (유즈맵처럼 정확히)
*/
export interface Strictness {
space: boolean;
number: boolean;
symbol: boolean;
}
export type AnswerMode = 'title' | 'artist' | 'both';
export interface AnswerSong {
title: string;
/** Display artist ("허각, 정은지"). */
artist: string;
/** Admin aliases (song_aliases) for each part; artist aliases from artist_aliases go in artistAliases too. */
titleAliases?: string[];
artistAliases?: string[];
}
const BRACKET = /[([{【「『<]([^)\]}】」』>]*)[)\]}】」』>]/g;
/** Tails that are not part of the name people say: feat., (Prod. …), [… OST], (원곡: …), (inst), (Remastered)… */
const TAIL_WORD = /^(feat\.?|ft\.?|prod\.?|with|from|원곡|inst\.?|instrumental|remaster(ed)?|bonus|explicit|clean|sped up|live|ver\.?|version|mr)\b/i;
function base(s: string): string {
return s.normalize('NFKC').toLowerCase().replace(/\s+/g, ' ').trim();
}
function isTail(inner: string): boolean {
const t = inner.trim();
return TAIL_WORD.test(t) || /\bost\b/i.test(t) || /\b(ver|version)\.?$/i.test(t);
}
/** Title spellings that count (docs/05 정규화 2~4). */
export function titleCandidates(title: string, aliases: string[] = []): string[] {
const out = new Set<string>();
const add = (s: string) => {
const b = base(s);
if (b) out.add(b);
};
add(title);
// drop tails: `(feat. X)`, `[태양의 후예 OST]`, and bare `feat. X` at the end
const noTail = title.replace(BRACKET, (m, inner: string) => (isTail(inner) ? ' ' : m)).replace(/\s+(feat\.?|ft\.?|prod\.?)\s.*$/i, ' ');
add(noTail);
const parts = [...noTail.matchAll(BRACKET)].map((m) => m[1]!).filter((x) => x.trim());
const outside = noTail.replace(BRACKET, ' ');
add(outside);
for (const p of parts) add(p);
// `사랑을 했다(LOVE SCENARIO)` → also `사랑을 했다 LOVE SCENARIO`
if (parts.length) add(`${outside} ${parts.join(' ')}`);
for (const a of aliases) add(a);
return [...out];
}
/** Artist spellings: the whole credit, each name of a multi-artist credit, `RESCENE (리센느)` → both names, aliases. */
export function artistCandidates(artist: string, aliases: string[] = []): string[] {
const out = new Set<string>();
const add = (s: string) => {
const b = base(s);
if (b) out.add(b);
};
const names = [artist, ...artist.split(/\s*(?:,|&|\/|\bx\b|\band\b|·|\bfeat\.?|\bft\.?|\bwith\b)\s*/i)];
for (const n of names) {
add(n);
const inner = /^(.*?)\s*[((]([^))]+)[))]\s*$/.exec(n.trim());
if (inner) (add(inner[1]!), add(inner[2]!));
}
for (const a of aliases) add(a);
return [...out];
}
const LETTER = /\p{L}/u;
const DIGIT = /\p{N}/gu;
/** Symbols = anything that is not a letter, digit or space. */
const SYMBOL = /[^\p{L}\p{N}\s]/gu;
/** Comparison key at a preserve level: 0 = apply the toggles, 1 = keep digits, 2 = keep digits and symbols. */
function keyAt(s: string, st: Strictness, level: 0 | 1 | 2): string {
let k = base(s);
if (!st.symbol && level < 2) k = k.replace(SYMBOL, ' ');
if (!st.number && level < 1) k = k.replace(DIGIT, ' ');
k = k.replace(/\s+/g, ' ').trim();
if (!st.space) k = k.replace(/\s/g, '');
return k;
}
/** The preserve level a candidate needs so it does not vanish (docs/05 빈 비교 키 방지). */
function levelFor(cand: string, st: Strictness): 0 | 1 | 2 {
const raw = base(cand).replace(/\s/g, '');
for (const lv of [0, 1] as const) {
const k = keyAt(cand, st, lv).replace(/\s/g, '');
if (!k) continue;
if (!LETTER.test(k) && lv === 0 && /\p{N}/u.test(raw)) continue; // only symbols left: keep the digits
if (raw.length >= 2 && k.length < 2) continue;
return lv;
}
return 2;
}
/** Does `text` equal one of the candidates under the room's 정답인식? */
export function matchesAny(text: string, candidates: string[], st: Strictness): boolean {
for (const c of candidates) {
const lv = levelFor(c, st);
const ck = keyAt(c, st, lv);
if (!ck) continue;
const tk = keyAt(text, st, lv);
if (tk && tk === ck) return true;
}
return false;
}
/** Separators allowed between title and artist in 제목+가수 (docs/05): `- / , ·` and spaces. */
const SEP = /^[\s\-/,·:|~]*$/;
/**
* Judge one chat line (docs/05 정답방식별 판정). 제목+가수: both in one line, either order, split anywhere
* (`광 sg워너비`, `sg워너비-광`, `광/sg워너비`, `광sg워너비`).
*/
export function isCorrect(text: string, song: AnswerSong, mode: AnswerMode, st: Strictness): boolean {
const t = base(text);
if (!t) return false;
const titles = titleCandidates(song.title, song.titleAliases);
const artists = artistCandidates(song.artist, song.artistAliases);
if (mode === 'title') return matchesAny(t, titles, st);
if (mode === 'artist') return matchesAny(t, artists, st);
const chars = [...t];
for (let i = 1; i < chars.length; i++) {
// try every split, allowing separator runs around it
const left = chars.slice(0, i).join('');
for (let j = i; j < chars.length; j++) {
const mid = chars.slice(i, j).join('');
if (!SEP.test(mid)) break;
const right = chars.slice(j).join('');
const l = left.replace(/[\s\-/,·:|~]+$/, '');
const r = right.replace(/^[\s\-/,·:|~]+/, '');
if (!l || !r) continue;
if ((matchesAny(l, titles, st) && matchesAny(r, artists, st)) || (matchesAny(l, artists, st) && matchesAny(r, titles, st))) return true;
}
}
return false;
}
const CHO = ['ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'];
/** 초성 hint (docs/05 힌트): Hangul → initial consonant, other words → first letter + `_`, spaces and symbols kept. */
export function chosung(s: string): string {
return s
.normalize('NFC')
.split(/(\s+)/)
.map((w) => {
if (/^\s+$/.test(w)) return w;
let seenLatin = false;
return [...w]
.map((ch) => {
const code = ch.charCodeAt(0);
if (code >= 0xac00 && code <= 0xd7a3) {
seenLatin = false;
return CHO[Math.floor((code - 0xac00) / 588)]!;
}
if (/\p{L}/u.test(ch)) {
if (seenLatin) return '_';
seenLatin = true;
return ch.toUpperCase();
}
seenLatin = false;
return ch;
})
.join('');
})
.join('');
}
/** What the hint shows for the room's 정답방식: `ㄱ (ㄱ) - ㅅㄱㅇㄴㅂ` style. */
export function hintText(song: { title: string; artist: string }, mode: AnswerMode): string {
const title = song.title.replace(BRACKET, (m, inner: string) => (isTail(inner) ? '' : m)).trim();
if (mode === 'title') return chosung(title);
if (mode === 'artist') return chosung(song.artist);
return `${chosung(title)} - ${chosung(song.artist)}`;
}

View File

@@ -4,3 +4,4 @@ export * from './types';
export * from './match-key';
export * from './room-config';
export * from './room-config-schema';
export * from './answer';

View File

@@ -2,4 +2,4 @@
export * from './nickname';
export * from './types';
export * from './room-config';
export type { ChatLine, RoomView, RoomPlayerView, ServerMessage } from './protocol';
export type { ChatLine, RoomView, RoomPlayerView, ServerMessage, GameView, GameScore, GameHistoryItem, GamePhase } from './protocol';

View File

@@ -23,6 +23,21 @@ export const ClientMessage = z.discriminatedUnion('t', [
z.object({ t: z.literal('host'), userId: z.string().max(40) }),
/** Room chat (docs/06; stage 4 = waiting room only). `n` echoes back so the sender can confirm its optimistic line. */
z.object({ t: z.literal('chat'), text: z.string().min(1).max(CHAT_MAX), n: z.string().max(24).optional() }),
// ---- game (docs/05, stage 5~7)
/** Host: start a game from the waiting room. */
z.object({ t: z.literal('start') }),
/** Playback report for question `n` (docs/12 Q1): ready = buffered at the position, blocked = no sound, stall = buffering, clipEnd, error = player error code. */
z.object({ t: z.literal('audio'), n: z.number().int().min(1), ev: z.enum(['ready', 'blocked', 'stall', 'clipEnd', 'error']), code: z.number().int().optional() }),
/** Vote toggles (docs/05 스킵·힌트, docs/12 Q3·Q4). */
z.object({ t: z.literal('vote'), kind: z.enum(['skip', 'hint', 'replay']) }),
z.object({ t: z.literal('typing'), on: z.boolean() }),
/** Host game controls: pause/resume, end now, 이어풀기, 다시 하기 (back to the waiting room). */
z.object({ t: z.literal('game'), action: z.enum(['pause', 'resume', 'end', 'continue', 'again']) }),
/** Host: leave this player out of this question only (not ready for 30s, docs/12 Q1). */
z.object({ t: z.literal('exclude'), userId: z.string().max(40) }),
/** Host (Discord account): save / load the quiz (docs/12 Q8). */
z.object({ t: z.literal('save'), name: z.string().trim().min(1).max(40) }),
z.object({ t: z.literal('load'), id: z.number().int().positive() }),
]);
export type ClientMessage = z.infer<typeof ClientMessage>;
@@ -56,6 +71,72 @@ export interface ChatLine {
text: string;
/** Sender's nonce for its optimistic line. */
n?: string;
/**
* 정답 줄 + 5줄 블록 as one item (docs/06): the correct chat (or a system line when nobody got it) and `노래제목 - 가수`.
* none = skipped / time over (grey block).
*/
answer?: { text: string; none?: boolean };
}
export type GamePhase = 'prepare' | 'play' | 'reveal' | 'result';
export interface GameScore {
id: string;
nickname: string;
score: number;
correct: number;
/** Average answer time of the questions this player got (tie-break, docs/05 점수). */
avgMs: number | null;
online: boolean;
}
export interface GameHistoryItem {
n: number;
title: string;
artist: string;
year: number | null;
level: number | null;
genres: string[];
videoId: string | null;
winnerId: string | null;
winner: string | null;
ms: number | null;
how: 'correct' | 'skip' | 'timeout' | 'end';
}
/** Game state for everyone (docs/05). Never has the video id or the answer of the running question. */
export interface GameView {
phase: GamePhase;
n: number;
total: number;
mode: import('./room-config').Mode;
/** This question's players (heard it from the start); others join at the next one. */
participants: string[];
excluded: string[];
/** Not ready yet (prepare, or re-prepare after a pause), with the server time they started waiting. */
waiting: { id: string; since: number }[];
/** Everyone stopped (docs/12 Q1): buffering / no sound / the host paused. Timers do not run meanwhile. */
paused: null | { reason: 'stall' | 'blocked' | 'host'; who: string[] };
/** Server time the music (re)starts: before it the screen counts 3·2·1. */
startAt: number | null;
/** Question clock: elapsedMs + (runningSince ? serverNow - runningSince : 0); limitMs null = no limit. */
clock: { elapsedMs: number; runningSince: number | null; limitMs: number | null };
/** Seconds of the clip (null = 끝까지 with unknown length) for the progress bar. */
clipSec: number | null;
clipOver: boolean;
hint: string | null;
/** 자동 공개 at this many seconds (null = none / 직접선택). */
hintAtSec: number | null;
lyrics: string[] | null;
votes: { skip: string[]; hint: string[]; replay: string[] };
need: { skip: number | null; hint: number | null; replay: number | null };
scores: GameScore[];
/** Questions of this game so far, newest last; during reveal the last one is the current question. */
history: GameHistoryItem[];
/** Server time the reveal ends. */
revealUntil: number | null;
/** 이어풀기 possible: songs left that this quiz has not played. */
left: number;
}
export type ServerMessage =
@@ -63,6 +144,17 @@ export type ServerMessage =
| { t: 'room'; room: RoomView }
| { t: 'left'; code: string; reason: 'leave' | 'kicked' | 'closed' | 'elsewhere' }
| { t: 'chat'; code: string; line: ChatLine }
/** 정답 줄 + 5줄 블록 in one message (docs/06). */
| { t: 'answer'; code: string; line: ChatLine }
| { t: 'game'; code: string; game: GameView | null }
/** Load the video muted at `startSec`, buffer, report audio ready (docs/12 Q1). */
| { t: 'prepare'; code: string; n: number; videoId: string; startSec: number; endSec: number | null }
/** Everyone unmutes and plays from `atSec` at server time `startAt`; stop at `endSec` by playback position. */
| { t: 'play'; code: string; n: number; startAt: number; atSec: number; endSec: number | null }
/** Stop now (someone is buffering / the host paused / the clip is over). */
| { t: 'pause'; code: string; n: number }
| { t: 'typing'; code: string; ids: string[] }
| { t: 'saved'; id: number; name: string }
/** Recent lines for someone who just joined (or came back). */
| { t: 'chatlog'; code: string; lines: ChatLine[] }
| { t: 'notice'; text: string }