4단계 방·대기실: 방 만들기(게스트 포함)·6자리 코드·열린 방 목록(🔒 비밀번호 방), 인원 무제한 대기실(방장·준비·넘기기·내보내기·60초 자리 유지), 방 설정 전체 즉시 반영, 조건에 맞는 곡 N곡 + 원곡 확인 중 곡 수(1분마다 다시 셈), 대기실 채팅, 서버 재시작 안내
- 서버 테스트 49개, 브라우저 e2e(e2e/rooms.e2e.ts, 3명) 11단계 - 사용자 결정(추천안)은 docs/12 "4단계 확인" Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -21,6 +21,8 @@ export interface AdminDeps {
|
||||
db: Database;
|
||||
/** Injected for tests. */
|
||||
checkEmbed?: (videoId: string) => Promise<EmbedState>;
|
||||
/** Lobby song counts depend on the catalog. */
|
||||
onCatalogChange?: () => void;
|
||||
}
|
||||
|
||||
type Env = { Variables: { userId: string | null; role: Role } };
|
||||
@@ -140,6 +142,7 @@ export function createAdminApp(d: AdminDeps) {
|
||||
const genres = new Set(genreList(d.db).map((g) => g.id));
|
||||
if (rest.genres?.some((g) => !genres.has(g))) return c.json({ error: '없는 장르가 있어요.' }, 400);
|
||||
updateSong(d.db, id, { ...rest, youtubeId }, embed);
|
||||
d.onCatalogChange?.();
|
||||
const after = getSong(d.db, id)!;
|
||||
d.audit.log(actor(c), 'song.update', String(id), { title: before.song.title, artist: before.song.artist }, parsed.data);
|
||||
return c.json(after);
|
||||
|
||||
@@ -11,6 +11,11 @@ import { WindowLimiter } from '../ws/rate-limit';
|
||||
import { createAdminApp, type AdminDeps } from './admin';
|
||||
import type { Roles } from '../admin/roles';
|
||||
import type { SettingsStore } from '../admin/settings';
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import type { RoomManager } from '../rooms/manager';
|
||||
import { genreList } from '../songs/store';
|
||||
import { countPool, searchArtists, yearBounds } from '../songs/pool';
|
||||
import { DEFAULT_ROOM_CONFIG, applyConfigPatch, type RoomConfig } from '@mq/shared';
|
||||
|
||||
export interface HttpDeps {
|
||||
config: Config;
|
||||
@@ -18,6 +23,8 @@ export interface HttpDeps {
|
||||
sessions: Sessions;
|
||||
roles: Roles;
|
||||
settings: SettingsStore;
|
||||
rooms: RoomManager;
|
||||
db: Database;
|
||||
/** Injected for tests. */
|
||||
discordExchange?: (code: string, redirectUri: string) => Promise<DiscordUser>;
|
||||
ipOf: (req: Request) => string;
|
||||
@@ -195,6 +202,50 @@ export function createHttpApp(d: HttpDeps) {
|
||||
return c.json({ me: toPublicUser(d.users.get(u)!) });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ rooms (docs/04, stage 4)
|
||||
const createLimiter = new WindowLimiter(10, 60_000);
|
||||
const lookupLimiter = new WindowLimiter(60, 60_000);
|
||||
|
||||
/** Static data for the settings form: genres with groups, year span, level names come from @mq/shared. */
|
||||
app.get('/api/catalog/meta', (c) =>
|
||||
c.json({ genres: genreList(d.db).filter((g) => !g.hidden).map(({ id, name, grp }) => ({ id, name, grp })), years: yearBounds(d.db) }),
|
||||
);
|
||||
|
||||
app.get('/api/artists', (c) => {
|
||||
const q = (c.req.query('q') ?? '').trim().slice(0, 40);
|
||||
if (!q) return c.json({ artists: [] });
|
||||
if (!lookupLimiter.allow(d.ipOf(c.req.raw))) return c.json({ error: '잠시 후 다시 시도해 주세요.' }, 429);
|
||||
return c.json({ artists: searchArtists(d.db, q) });
|
||||
});
|
||||
|
||||
app.get('/api/rooms', (c) => c.json({ rooms: d.rooms.publicRooms() }));
|
||||
|
||||
app.post('/api/rooms', async (c) => {
|
||||
const u = userOf(c);
|
||||
if (!u) return c.json({ error: '로그인이 필요해요.' }, 401);
|
||||
if (d.settings.getSite().maintenance) return c.json({ error: '점검 중이라 새 방을 만들 수 없어요.' }, 503);
|
||||
if (!createLimiter.allow(d.ipOf(c.req.raw))) return c.json({ error: '잠시 후 다시 시도해 주세요.' }, 429);
|
||||
const body = (await c.req.json().catch(() => ({}))) as { config?: Partial<RoomConfig> };
|
||||
const r = d.rooms.create(u, body.config ?? {});
|
||||
if (typeof r === 'string') return c.json({ error: r }, 400);
|
||||
return c.json({ code: r.code });
|
||||
});
|
||||
|
||||
/** Room preview for the join screen (no login needed). */
|
||||
app.get('/api/rooms/:code', (c) => {
|
||||
if (!lookupLimiter.allow(d.ipOf(c.req.raw))) return c.json({ error: '잠시 후 다시 시도해 주세요.' }, 429);
|
||||
const r = d.rooms.get(c.req.param('code'));
|
||||
if (!r) return c.json({ error: '방을 찾을 수 없어요. 코드를 다시 확인해 주세요.' }, 404);
|
||||
return c.json({ code: r.code, title: r.config.title, players: r.players.size, status: r.status, needsPassword: r.config.visibility === 'password' && !!r.password });
|
||||
});
|
||||
|
||||
/** "조건에 맞는 곡 N곡" for a config that isn't a room yet (e.g. the 무제한 label). */
|
||||
app.post('/api/pool/count', async (c) => {
|
||||
const cfg = applyConfigPatch(DEFAULT_ROOM_CONFIG, await c.req.json().catch(() => null));
|
||||
if (typeof cfg === 'string') return c.json({ error: cfg }, 400);
|
||||
return c.json(countPool(d.db, cfg));
|
||||
});
|
||||
|
||||
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));
|
||||
|
||||
225
apps/server/src/rooms.test.ts
Normal file
225
apps/server/src/rooms.test.ts
Normal file
@@ -0,0 +1,225 @@
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { DEFAULT_ROOM_CONFIG, voteThreshold, type RoomView, type ServerMessage } from '@mq/shared';
|
||||
import { Catalog } from './collector/catalog';
|
||||
import { openDb } from './db';
|
||||
import { countPool } from './songs/pool';
|
||||
import { Client, api, boot, guest, sleep, tempDbPath } from './test-utils';
|
||||
|
||||
describe('song pool rules (docs/04, docs/12 Q7·Q9)', () => {
|
||||
const db = openDb(tempDbPath());
|
||||
const c = new Catalog(db);
|
||||
const add = (title: string, genres: string[], year: number, level: number, matched = true, extraLevels: [string, number][] = []) => {
|
||||
const [id] = c.upsert({ title, artists: [{ name: `가수${title}` }], year, genres, source: 't', ref: title });
|
||||
c.autoLevel(id, 'all', level);
|
||||
for (const [scope, lv] of extraLevels) c.autoLevel(id, scope, lv);
|
||||
if (matched) db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = 'x' WHERE id = ?").run(id);
|
||||
return id;
|
||||
};
|
||||
add('국내발라드', ['kpop', 'ballad'], 2005, 3);
|
||||
add('국내댄스', ['kpop', 'dance'], 2010, 3);
|
||||
add('해외발라드', ['pop', 'ballad'], 2005, 3);
|
||||
add('어려운국내발라드', ['kpop', 'ballad'], 1995, 6, true, [['genre:ballad', 3]]); // 전체 6단계, 발라드 안에서는 3단계
|
||||
add('90년대에선쉬움', ['kpop', 'rock'], 1994, 7, true, [['decade:1990', 3]]);
|
||||
add('미확정', ['kpop', 'ballad'], 2005, 3, false);
|
||||
const cfg = (p: Partial<typeof DEFAULT_ROOM_CONFIG>) => ({ ...DEFAULT_ROOM_CONFIG, ...p });
|
||||
|
||||
test('different groups AND, same group OR', () => {
|
||||
// kpop AND ballad: 국내발라드 + 어려운국내발라드 (level 3 within ballad); 미확정 has no video
|
||||
expect(countPool(db, cfg({ genres: ['kpop', 'ballad'] })).playable).toBe(2);
|
||||
// ballad OR dance: 국내발라드, 국내댄스, 해외발라드, 어려운국내발라드
|
||||
expect(countPool(db, cfg({ genres: ['ballad', 'dance'] })).playable).toBe(4);
|
||||
// kpop AND (ballad OR dance): 해외발라드 drops out
|
||||
expect(countPool(db, cfg({ genres: ['kpop', 'ballad', 'dance'] })).playable).toBe(3);
|
||||
});
|
||||
|
||||
test('level N only, with per-scope levels counting (a song can sit in several levels)', () => {
|
||||
expect(countPool(db, cfg({})).playable).toBe(3); // level 3 overall: 국내발라드, 국내댄스, 해외발라드
|
||||
expect(countPool(db, cfg({ genres: ['ballad'] })).playable).toBe(3); // + 어려운국내발라드 (ballad scope 3)
|
||||
expect(countPool(db, cfg({ level: 6 })).playable).toBe(1);
|
||||
expect(countPool(db, cfg({ yearFrom: 1990, yearTo: 1999 })).playable).toBe(1); // 90년대에선쉬움 via decade scope
|
||||
});
|
||||
|
||||
test('year range and playable vs total', () => {
|
||||
expect(countPool(db, cfg({ yearFrom: 2006 })).playable).toBe(1);
|
||||
expect(countPool(db, cfg({ genres: ['kpop', 'ballad'], yearFrom: 2000 }))).toEqual({ playable: 1, total: 2 }); // 국내발라드 + 미확정
|
||||
});
|
||||
|
||||
test('vote thresholds round up and stay within the player count', () => {
|
||||
expect(voteThreshold('1/3', 7)).toBe(3);
|
||||
expect(voteThreshold('2/3', 3)).toBe(2);
|
||||
expect(voteThreshold('all', 5)).toBe(5);
|
||||
expect(voteThreshold('2', 1)).toBe(1);
|
||||
expect(voteThreshold('none', 5)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('rooms over WebSocket', () => {
|
||||
let s: ReturnType<typeof boot>;
|
||||
afterEach(async () => s && (await s.stop()));
|
||||
|
||||
const lastRoom = (cl: Client) => [...cl.messages].reverse().find((m) => m.t === 'room') as { room: RoomView } | undefined;
|
||||
const nextRoom = (cl: Client, pred: (r: RoomView) => boolean = () => true) =>
|
||||
new Promise<RoomView>((resolve, reject) => {
|
||||
const start = Date.now();
|
||||
const tick = () => {
|
||||
const m = lastRoom(cl);
|
||||
if (m && pred(m.room)) return resolve(m.room);
|
||||
if (Date.now() - start > 2000) return reject(new Error(`no matching room view; last ${JSON.stringify(m?.room?.players)}`));
|
||||
setTimeout(tick, 10);
|
||||
};
|
||||
tick();
|
||||
});
|
||||
const errorOf = (cl: Client) => cl.waitFor((m) => m.t === 'error') as Promise<Extract<ServerMessage, { t: 'error' }>>;
|
||||
|
||||
async function setup() {
|
||||
s = boot();
|
||||
const a = await guest(s.base, '방장');
|
||||
const b = await guest(s.base, '손님');
|
||||
const create = await api(s.base, '/api/rooms', { method: 'POST', cookie: a.cookie, body: JSON.stringify({}) });
|
||||
expect(create.res.status).toBe(200);
|
||||
const code: string = create.body.code;
|
||||
const ca = await new Client(s.base, a.cookie).connect();
|
||||
const cb = await new Client(s.base, b.cookie).connect();
|
||||
ca.send({ t: 'join', code });
|
||||
await nextRoom(ca, (r) => r.players.length === 1);
|
||||
cb.send({ t: 'join', code });
|
||||
await nextRoom(ca, (r) => r.players.length === 2);
|
||||
return { a, b, ca, cb, code };
|
||||
}
|
||||
|
||||
test('create, join, both see each other; the creator is host with default settings', async () => {
|
||||
const { a, cb, code } = await setup();
|
||||
const r = await nextRoom(cb, (x) => x.players.length === 2);
|
||||
expect(r.hostId).toBe(a.id);
|
||||
expect(r.config).toMatchObject({ title: '방장님의 방', level: 3, answer: 'title', strict: { space: true, number: true, symbol: true }, hint: 'none', count: 30 });
|
||||
expect((await api(s.base, '/api/rooms')).body.rooms.map((x: any) => x.code)).toEqual([code]);
|
||||
expect((await api(s.base, `/api/rooms/${code}`)).body).toMatchObject({ code, players: 2, status: 'lobby' });
|
||||
});
|
||||
|
||||
test('only the host changes settings; a change resets ready and reaches everyone', async () => {
|
||||
const { ca, cb } = await setup();
|
||||
cb.send({ t: 'ready', on: true });
|
||||
await nextRoom(ca, (r) => r.players.some((p) => p.ready));
|
||||
cb.send({ t: 'config', patch: { level: 5 } });
|
||||
expect((await errorOf(cb)).message).toContain('방장만');
|
||||
ca.send({ t: 'config', patch: { level: 5, hint: 'manual', hintVotes: '1/2', genres: ['ballad'], count: 0 } });
|
||||
const r = await nextRoom(cb, (x) => x.config.level === 5);
|
||||
expect(r.config).toMatchObject({ hint: 'manual', hintVotes: '1/2', genres: ['ballad'], count: 0 });
|
||||
expect(r.players.every((p) => !p.ready)).toBe(true);
|
||||
ca.send({ t: 'config', patch: { listenSec: 7 } });
|
||||
expect((await errorOf(ca)).message).toContain('올바르지 않아요');
|
||||
});
|
||||
|
||||
test('host can kick and hand over; when the host leaves the next player becomes host', async () => {
|
||||
const { a, b, ca, cb, code } = await setup();
|
||||
ca.send({ t: 'host', userId: b.id });
|
||||
expect((await nextRoom(cb, (r) => r.hostId === b.id)).hostId).toBe(b.id);
|
||||
cb.send({ t: 'kick', userId: a.id });
|
||||
await ca.waitFor((m) => m.t === 'left' && m.reason === 'kicked');
|
||||
expect((await nextRoom(cb, (r) => r.players.length === 1)).players[0]!.id).toBe(b.id);
|
||||
// a comes back and b leaves: a is host again
|
||||
ca.send({ t: 'join', code });
|
||||
await nextRoom(cb, (r) => r.players.length === 2);
|
||||
cb.send({ t: 'leave' });
|
||||
expect((await nextRoom(ca, (r) => r.players.length === 1)).hostId).toBe(a.id);
|
||||
});
|
||||
|
||||
test('password rooms need the password; private rooms are not listed', async () => {
|
||||
const { ca, code } = await setup();
|
||||
ca.send({ t: 'config', patch: { visibility: 'password' } });
|
||||
ca.send({ t: 'password', value: 'abcd' });
|
||||
await nextRoom(ca, (r) => r.hasPassword);
|
||||
const c = await guest(s.base, '셋째');
|
||||
const cc = await new Client(s.base, c.cookie).connect();
|
||||
cc.send({ t: 'join', code });
|
||||
expect((await errorOf(cc)).message).toContain('비밀번호');
|
||||
cc.send({ t: 'join', code, password: 'abcd' });
|
||||
await nextRoom(cc, (r) => r.players.length === 3);
|
||||
expect((await api(s.base, '/api/rooms')).body.rooms[0].hasPassword).toBe(true);
|
||||
ca.send({ t: 'config', patch: { visibility: 'private' } });
|
||||
await nextRoom(ca, (r) => r.config.visibility === 'private');
|
||||
expect((await api(s.base, '/api/rooms')).body.rooms).toEqual([]);
|
||||
});
|
||||
|
||||
test('a disconnected player keeps the place for the grace period, then is removed', async () => {
|
||||
const { a, b, ca, cb } = await setup();
|
||||
cb.close();
|
||||
const r = await nextRoom(ca, (x) => x.players.some((p) => p.id === b.id && !p.online));
|
||||
expect(r.players.length).toBe(2);
|
||||
s.rooms.sweep(Date.now() + 61_000);
|
||||
expect((await nextRoom(ca, (x) => x.players.length === 1)).players[0]!.id).toBe(a.id);
|
||||
});
|
||||
|
||||
test('no player limit: 40 people in one room', async () => {
|
||||
const { ca, code } = await setup();
|
||||
const clients: Client[] = [];
|
||||
for (let i = 0; i < 38; i++) {
|
||||
// straight to the DB: the guest sign-up endpoint is rate limited per IP
|
||||
const u = s.users.createGuest(`손님${i}`);
|
||||
const cl = await new Client(s.base, `sid=${s.sessions.create(u.id, 'guest', null).token}`).connect();
|
||||
cl.send({ t: 'join', code });
|
||||
clients.push(cl);
|
||||
}
|
||||
expect((await nextRoom(ca, (r) => r.players.length === 40)).players.length).toBe(40);
|
||||
for (const cl of clients) cl.close();
|
||||
await sleep(20);
|
||||
});
|
||||
|
||||
test('joining another room leaves the first one', async () => {
|
||||
const { a, ca, cb, code } = await setup();
|
||||
const other = (await api(s.base, '/api/rooms', { method: 'POST', cookie: a.cookie, body: '{}' })).body.code;
|
||||
ca.send({ t: 'join', code: other });
|
||||
await nextRoom(ca, (r) => r.code === other);
|
||||
expect((await nextRoom(cb, (r) => r.code === code && r.players.length === 1)).players.length).toBe(1);
|
||||
});
|
||||
|
||||
const chatOf = (cl: Client) => cl.messages.filter((m) => m.t === 'chat').map((m) => (m as Extract<ServerMessage, { t: 'chat' }>).line);
|
||||
|
||||
test('waiting-room chat: relayed to everyone in order with a nonce echo, system lines for join/leave/host, history for newcomers', async () => {
|
||||
const { a, b, ca, cb, code } = await setup();
|
||||
ca.send({ t: 'chat', text: ' 안녕\u0007하세요 ', n: 'x1' });
|
||||
const got = await cb.waitFor((m) => m.t === 'chat' && m.line.userId === a.id);
|
||||
expect(got).toMatchObject({ t: 'chat', code, line: { userId: a.id, nickname: '방장', text: '안녕 하세요', n: 'x1' } });
|
||||
cb.send({ t: 'chat', text: 'ㅎㅇ' });
|
||||
await ca.waitFor((m) => m.t === 'chat' && m.line.userId === b.id);
|
||||
const lines = chatOf(ca);
|
||||
expect(lines.map((l) => l.seq)).toEqual([...lines.map((l) => l.seq)].sort((x, y) => x - y));
|
||||
expect(lines.filter((l) => l.userId === null).map((l) => l.text)).toEqual(['방장님이 들어왔어요', '손님님이 들어왔어요']);
|
||||
// newcomer gets the history at once
|
||||
const c = await guest(s.base, '셋째');
|
||||
const cc = await new Client(s.base, c.cookie).connect();
|
||||
cc.send({ t: 'join', code });
|
||||
const log = (await cc.waitFor((m) => m.t === 'chatlog')) as Extract<ServerMessage, { t: 'chatlog' }>;
|
||||
expect(log.lines.map((l) => l.text)).toEqual(['방장님이 들어왔어요', '손님님이 들어왔어요', '안녕 하세요', 'ㅎㅇ']);
|
||||
// host leaves → system lines
|
||||
ca.send({ t: 'leave' });
|
||||
await cb.waitFor((m) => m.t === 'chat' && m.line.text === '방장이 손님님으로 바뀌었어요');
|
||||
expect(chatOf(cb).some((l) => l.text === '방장님이 나갔어요')).toBe(true);
|
||||
// not in a room → refused
|
||||
ca.send({ t: 'chat', text: '아무도 없나' });
|
||||
expect((await errorOf(ca)).message).toContain('방에 들어가 있지 않아요');
|
||||
});
|
||||
|
||||
test('chat flood guard is off by default and limits only when the admin turns it on', async () => {
|
||||
const { a, ca, cb } = await setup();
|
||||
for (let i = 0; i < 30; i++) ca.send({ t: 'chat', text: `도배${i}` });
|
||||
await cb.waitFor((m) => m.t === 'chat' && m.line.text === '도배29');
|
||||
expect(ca.messages.some((m) => m.t === 'error')).toBe(false);
|
||||
s.settings.setSite({ ...s.settings.getSite(), chatFloodGuard: true, chatRatePerSec: 1, chatBurst: 3 }, a.id);
|
||||
for (let i = 0; i < 6; i++) ca.send({ t: 'chat', text: `또${i}` });
|
||||
expect((await errorOf(ca)).message).toContain('너무 빨리');
|
||||
await sleep(100);
|
||||
expect(chatOf(cb).filter((l) => l.text.startsWith('또')).length).toBe(3);
|
||||
});
|
||||
|
||||
test('lobby song count follows catalog changes made by another process', async () => {
|
||||
const { ca } = await setup();
|
||||
const before = (await nextRoom(ca)).pool;
|
||||
const cat = new Catalog(s.db);
|
||||
const [id] = cat.upsert({ title: '새로찾은곡', artists: [{ name: '누군가' }], year: 2015, genres: [], source: 't', ref: 'new' });
|
||||
cat.autoLevel(id, 'all', 3);
|
||||
s.db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = 'y' WHERE id = ?").run(id);
|
||||
s.rooms.recountAll();
|
||||
expect((await nextRoom(ca, (r) => r.pool.playable === before.playable + 1)).pool.total).toBe(before.total + 1);
|
||||
});
|
||||
});
|
||||
319
apps/server/src/rooms/manager.ts
Normal file
319
apps/server/src/rooms/manager.ts
Normal file
@@ -0,0 +1,319 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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 { artistsByIds, countPool } from '../songs/pool';
|
||||
import type { WsData } from '../ws/gateway';
|
||||
|
||||
/** Back within this long after a disconnect: keeps the place (and later the score). */
|
||||
export const GRACE_MS = 60_000;
|
||||
const EMPTY_ROOM_MS = 5 * 60_000;
|
||||
/** Chat lines a newcomer gets (the screen keeps 200, docs/06). */
|
||||
export const CHAT_HISTORY = 100;
|
||||
|
||||
interface Player {
|
||||
joinedAt: number;
|
||||
ready: boolean;
|
||||
conns: Set<ServerWebSocket<WsData>>;
|
||||
offlineSince: number | null;
|
||||
}
|
||||
|
||||
export interface PublicUserLookup {
|
||||
(id: string): { id: string; nickname: string; avatar: string | null; kind: 'guest' | 'member' } | null;
|
||||
}
|
||||
|
||||
export class Room {
|
||||
config: RoomConfig;
|
||||
hostId: string;
|
||||
password: string | null = null;
|
||||
status: 'lobby' | 'playing' = 'lobby';
|
||||
players = new Map<string, Player>();
|
||||
pool = { playable: 0, total: 0 };
|
||||
createdAt = Date.now();
|
||||
emptySince: number | null = null;
|
||||
chat: ChatLine[] = [];
|
||||
private seq = 0;
|
||||
|
||||
constructor(
|
||||
readonly code: string,
|
||||
hostId: string,
|
||||
config: RoomConfig,
|
||||
private deps: { db: Database; user: PublicUserLookup },
|
||||
) {
|
||||
this.hostId = hostId;
|
||||
this.config = config;
|
||||
this.recount();
|
||||
}
|
||||
|
||||
recount(): void {
|
||||
this.pool = countPool(this.deps.db, this.config);
|
||||
}
|
||||
|
||||
online(): string[] {
|
||||
return [...this.players].filter(([, p]) => p.conns.size > 0).map(([id]) => id);
|
||||
}
|
||||
|
||||
view(): RoomView {
|
||||
return {
|
||||
code: this.code,
|
||||
hostId: this.hostId,
|
||||
status: this.status,
|
||||
config: this.config,
|
||||
hasPassword: !!this.password,
|
||||
players: [...this.players].map(([id, p]) => {
|
||||
const u = this.deps.user(id);
|
||||
return { id, nickname: u?.nickname ?? '?', avatar: u?.avatar ?? null, kind: u?.kind ?? 'guest', ready: p.ready, online: p.conns.size > 0 };
|
||||
}),
|
||||
pool: this.pool,
|
||||
artists: artistsByIds(this.deps.db, this.config.artistIds),
|
||||
};
|
||||
}
|
||||
|
||||
send(m: ServerMessage, only?: string): void {
|
||||
const json = JSON.stringify(m);
|
||||
for (const [id, p] of this.players) if (!only || id === only) for (const ws of p.conns) ws.send(json);
|
||||
}
|
||||
|
||||
broadcast(): void {
|
||||
this.send({ t: 'room', room: this.view() });
|
||||
}
|
||||
|
||||
/** 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;
|
||||
this.chat.push(line);
|
||||
if (this.chat.length > CHAT_HISTORY) this.chat.shift();
|
||||
this.send({ t: 'chat', code: this.code, line });
|
||||
return line;
|
||||
}
|
||||
|
||||
nick(userId: string): string {
|
||||
return this.deps.user(userId)?.nickname ?? '?';
|
||||
}
|
||||
|
||||
/** Earliest joined online player becomes host (docs/05 방장이 나가면). */
|
||||
pickHost(): void {
|
||||
const next = [...this.players].filter(([, p]) => p.conns.size > 0).sort((a, b) => a[1].joinedAt - b[1].joinedAt)[0]
|
||||
?? [...this.players].sort((a, b) => a[1].joinedAt - b[1].joinedAt)[0];
|
||||
if (next) this.hostId = next[0];
|
||||
}
|
||||
}
|
||||
|
||||
export interface PublicRoom {
|
||||
code: string;
|
||||
title: string;
|
||||
host: string;
|
||||
players: number;
|
||||
status: 'lobby' | 'playing';
|
||||
hasPassword: boolean;
|
||||
summary: string[];
|
||||
pool: number;
|
||||
}
|
||||
|
||||
export class RoomManager {
|
||||
rooms = new Map<string, Room>();
|
||||
/** 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 }) {}
|
||||
|
||||
private newCode(): string {
|
||||
for (;;) {
|
||||
const code = String(100000 + Math.floor(Math.random() * 900000));
|
||||
if (!this.rooms.has(code)) return code;
|
||||
}
|
||||
}
|
||||
|
||||
create(hostId: string, init: Partial<RoomConfig> = {}): Room | string {
|
||||
const nick = this.deps.user(hostId)?.nickname ?? '';
|
||||
const cfg = applyConfigPatch({ ...DEFAULT_ROOM_CONFIG, title: `${nick}님의 방`.slice(0, 40) }, init);
|
||||
if (typeof cfg === 'string') return cfg;
|
||||
const room = new Room(this.newCode(), hostId, cfg, this.deps);
|
||||
this.rooms.set(room.code, room);
|
||||
this.deps.log?.('room created', { code: room.code, host: hostId });
|
||||
return room;
|
||||
}
|
||||
|
||||
get(code: string): Room | undefined {
|
||||
return this.rooms.get(code);
|
||||
}
|
||||
|
||||
roomOf(userId: string): Room | undefined {
|
||||
const c = this.where.get(userId);
|
||||
return c ? this.rooms.get(c) : undefined;
|
||||
}
|
||||
|
||||
publicRooms(): PublicRoom[] {
|
||||
return [...this.rooms.values()]
|
||||
.filter((r) => r.config.visibility !== 'private' && r.players.size > 0)
|
||||
.map((r) => ({
|
||||
code: r.code,
|
||||
title: r.config.title,
|
||||
host: this.deps.user(r.hostId)?.nickname ?? '',
|
||||
players: r.players.size,
|
||||
status: r.status,
|
||||
hasPassword: r.config.visibility === 'password' && !!r.password,
|
||||
summary: configSummary(r.config, this.deps.genreName),
|
||||
pool: r.pool.playable,
|
||||
}))
|
||||
.sort((a, b) => b.players - a.players);
|
||||
}
|
||||
|
||||
join(ws: ServerWebSocket<WsData>, code: string, password?: string): string | null {
|
||||
const userId = ws.data.userId;
|
||||
const room = this.rooms.get(code);
|
||||
if (!room) return '방을 찾을 수 없어요. 코드를 다시 확인해 주세요.';
|
||||
const already = room.players.get(userId);
|
||||
if (!already && room.config.visibility === 'password' && room.password && password !== room.password && room.hostId !== userId) {
|
||||
return room.password && password ? '비밀번호가 틀렸어요.' : '비밀번호가 필요한 방이에요.';
|
||||
}
|
||||
// One room at a time: leave the previous one (other tabs there are told).
|
||||
const prev = this.roomOf(userId);
|
||||
if (prev && prev !== room) this.removePlayer(prev, userId, 'elsewhere');
|
||||
if (ws.data.roomCode && ws.data.roomCode !== code) this.detach(ws);
|
||||
const p = already ?? { joinedAt: Date.now(), ready: false, conns: new Set(), offlineSince: null };
|
||||
p.conns.add(ws);
|
||||
p.offlineSince = null;
|
||||
room.players.set(userId, p);
|
||||
room.emptySince = null;
|
||||
this.where.set(userId, code);
|
||||
ws.data.roomCode = code;
|
||||
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)}님이 들어왔어요`);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Socket closed or switched rooms: the player stays (grace period) until swept. */
|
||||
detach(ws: ServerWebSocket<WsData>): void {
|
||||
const code = ws.data.roomCode;
|
||||
ws.data.roomCode = undefined;
|
||||
const room = code ? this.rooms.get(code) : undefined;
|
||||
const p = room?.players.get(ws.data.userId);
|
||||
if (!room || !p) return;
|
||||
p.conns.delete(ws);
|
||||
if (p.conns.size === 0) {
|
||||
p.offlineSince = Date.now();
|
||||
p.ready = false;
|
||||
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)}님으로 바뀌었어요`);
|
||||
}
|
||||
}
|
||||
|
||||
leave(ws: ServerWebSocket<WsData>): void {
|
||||
const room = this.roomOf(ws.data.userId);
|
||||
if (room) this.removePlayer(room, ws.data.userId, 'leave');
|
||||
}
|
||||
|
||||
removePlayer(room: Room, userId: string, reason: 'leave' | 'kicked' | 'closed' | 'elsewhere'): void {
|
||||
const p = room.players.get(userId);
|
||||
if (!p) return;
|
||||
room.send({ t: 'left', code: room.code, reason }, userId);
|
||||
for (const ws of p.conns) ws.data.roomCode = undefined;
|
||||
room.players.delete(userId);
|
||||
if (this.where.get(userId) === room.code) this.where.delete(userId);
|
||||
if (room.players.size === 0) {
|
||||
room.emptySince = Date.now();
|
||||
return;
|
||||
}
|
||||
const wasHost = room.hostId === userId;
|
||||
if (wasHost) room.pickHost();
|
||||
room.broadcast();
|
||||
room.say(null, `${room.nick(userId)}님이 ${reason === 'kicked' ? '내보내졌어요' : '나갔어요'}`);
|
||||
if (wasHost) room.say(null, `방장이 ${room.nick(room.hostId)}님으로 바뀌었어요`);
|
||||
}
|
||||
|
||||
/** Host-only actions. Returns an error message or null. */
|
||||
hostAction(ws: ServerWebSocket<WsData>, fn: (room: Room) => string | null): string | null {
|
||||
const room = this.roomOf(ws.data.userId);
|
||||
if (!room) return '방에 들어가 있지 않아요.';
|
||||
if (room.hostId !== ws.data.userId) return '방장만 할 수 있어요.';
|
||||
if (room.status !== 'lobby') return '대기실에서만 바꿀 수 있어요.';
|
||||
return fn(room);
|
||||
}
|
||||
|
||||
setConfig(ws: ServerWebSocket<WsData>, patch: Record<string, unknown>): string | null {
|
||||
return this.hostAction(ws, (room) => {
|
||||
const next = applyConfigPatch(room.config, patch);
|
||||
if (typeof next === 'string') return next;
|
||||
room.config = next;
|
||||
// Settings changed: everyone confirms again (joke-app behaviour, docs/04).
|
||||
for (const p of room.players.values()) p.ready = false;
|
||||
room.recount();
|
||||
room.broadcast();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
setPassword(ws: ServerWebSocket<WsData>, value: string | null): string | null {
|
||||
return this.hostAction(ws, (room) => {
|
||||
room.password = value;
|
||||
room.broadcast();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
ready(ws: ServerWebSocket<WsData>, on: boolean): string | null {
|
||||
const room = this.roomOf(ws.data.userId);
|
||||
const p = room?.players.get(ws.data.userId);
|
||||
if (!room || !p) return '방에 들어가 있지 않아요.';
|
||||
p.ready = on;
|
||||
room.broadcast();
|
||||
return null;
|
||||
}
|
||||
|
||||
kick(ws: ServerWebSocket<WsData>, target: string): string | null {
|
||||
const room = this.roomOf(ws.data.userId);
|
||||
if (!room) return '방에 들어가 있지 않아요.';
|
||||
if (room.hostId !== ws.data.userId) return '방장만 할 수 있어요.';
|
||||
if (target === ws.data.userId || !room.players.has(target)) return '내보낼 수 없는 사람이에요.';
|
||||
this.removePlayer(room, target, 'kicked');
|
||||
return null;
|
||||
}
|
||||
|
||||
giveHost(ws: ServerWebSocket<WsData>, target: string): string | null {
|
||||
const room = this.roomOf(ws.data.userId);
|
||||
if (!room) return '방에 들어가 있지 않아요.';
|
||||
if (room.hostId !== ws.data.userId) return '방장만 할 수 있어요.';
|
||||
if (!room.players.get(target)?.conns.size) return '접속 중인 사람에게만 넘길 수 있어요.';
|
||||
room.hostId = target;
|
||||
room.broadcast();
|
||||
room.say(null, `방장이 ${room.nick(target)}님으로 바뀌었어요`);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Chat line from a player in the room (docs/06). Flood guard is applied by 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 null;
|
||||
room.say(ws.data.userId, t, n);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Every 10s: drop players gone longer than the grace period, close rooms left empty. */
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/** Song catalog changed (admin edit / collector in its own process): refresh the counts shown in lobbies, only telling rooms whose count moved. */
|
||||
recountAll(): void {
|
||||
for (const r of this.rooms.values()) {
|
||||
if (r.players.size === 0) continue;
|
||||
const before = r.pool;
|
||||
r.recount();
|
||||
if (before.playable !== r.pool.playable || before.total !== r.pool.total) r.broadcast();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import { createHttpApp, type HttpDeps } from './http/app';
|
||||
import { Gateway, type WsData } from './ws/gateway';
|
||||
import { Audit, Roles } from './admin/roles';
|
||||
import { SettingsStore } from './admin/settings';
|
||||
import { RoomManager } from './rooms/manager';
|
||||
import { toPublicUser } from './auth/users';
|
||||
|
||||
/** A guest who closed the site and stayed away this long is deleted (docs/02). */
|
||||
export const GUEST_IDLE_MS = 24 * 3600_000;
|
||||
@@ -43,15 +45,35 @@ export function startServer(opts: StartOptions) {
|
||||
const roles = new Roles(db, config.superadminDiscordIds);
|
||||
const audit = new Audit(db);
|
||||
const startedAt = Date.now();
|
||||
const gateway = new Gateway({ log, onClose: (id) => users.touch(id) });
|
||||
const genreNames = new Map(db.query<{ id: string; name: string }, []>('SELECT id, name FROM genres').all().map((g) => [g.id, g.name]));
|
||||
const rooms = new RoomManager({
|
||||
db,
|
||||
user: (id) => {
|
||||
const u = users.get(id);
|
||||
return u ? toPublicUser(u) : null;
|
||||
},
|
||||
genreName: (id) => genreNames.get(id) ?? id,
|
||||
log: (msg, extra) => log('info', msg, extra),
|
||||
});
|
||||
const gateway = new Gateway({
|
||||
log,
|
||||
onClose: (id) => users.touch(id),
|
||||
rooms,
|
||||
chatGuard: () => {
|
||||
const site = settings.getSite();
|
||||
return { on: site.chatFloodGuard, ratePerSec: site.chatRatePerSec, burst: site.chatBurst };
|
||||
},
|
||||
});
|
||||
|
||||
const removeGuest = (id: string) => {
|
||||
const r = rooms.roomOf(id);
|
||||
if (r) rooms.removePlayer(r, id, 'closed');
|
||||
gateway.disconnectUser(id);
|
||||
if (users.deleteGuest(id)) log('info', 'guest removed', { user: id });
|
||||
};
|
||||
/** Guests who closed the site and stayed away a day are deleted. */
|
||||
const purgeIdleGuests = (now = Date.now()) => {
|
||||
for (const id of users.idleGuests(now - GUEST_IDLE_MS)) if (!gateway.isOnline(id)) removeGuest(id);
|
||||
for (const id of users.idleGuests(now - GUEST_IDLE_MS)) if (!gateway.isOnline(id) && !rooms.roomOf(id)) removeGuest(id);
|
||||
};
|
||||
let ready = true;
|
||||
|
||||
@@ -66,17 +88,21 @@ export function startServer(opts: StartOptions) {
|
||||
sessions,
|
||||
roles,
|
||||
settings,
|
||||
rooms,
|
||||
db,
|
||||
ipOf,
|
||||
discordExchange: opts.discordExchange,
|
||||
health: () => ({ ok: ready, connections: gateway.connectionCount }),
|
||||
health: () => ({ ok: ready, connections: gateway.connectionCount, rooms: rooms.rooms.size }),
|
||||
removeGuest,
|
||||
admin: {
|
||||
audit,
|
||||
db,
|
||||
checkEmbed: opts.checkEmbed,
|
||||
onCatalogChange: () => rooms.recountAll(),
|
||||
disconnectUser: (id) => gateway.disconnectUser(id),
|
||||
stats: () => ({
|
||||
connections: gateway.connectionCount,
|
||||
rooms: { total: rooms.rooms.size, playing: [...rooms.rooms.values()].filter((r) => r.status === 'playing').length },
|
||||
uptimeSec: Math.round((Date.now() - startedAt) / 1000),
|
||||
memoryMb: Math.round(process.memoryUsage().rss / 1048576),
|
||||
}),
|
||||
@@ -113,6 +139,15 @@ export function startServer(opts: StartOptions) {
|
||||
},
|
||||
});
|
||||
|
||||
const roomSweeper = setInterval(() => rooms.sweep(), 10_000);
|
||||
// The collector runs in its own process, so lobbies re-count now and then to show newly matched songs.
|
||||
const roomRecount = setInterval(() => {
|
||||
try {
|
||||
rooms.recountAll();
|
||||
} catch (e) {
|
||||
log('warn', 'room recount failed', { err: String(e) });
|
||||
}
|
||||
}, 60_000);
|
||||
const sweeper = setInterval(() => {
|
||||
try {
|
||||
sessions.purgeExpired();
|
||||
@@ -125,12 +160,14 @@ export function startServer(opts: StartOptions) {
|
||||
const stop = async () => {
|
||||
ready = false;
|
||||
clearInterval(sweeper);
|
||||
clearInterval(roomSweeper);
|
||||
clearInterval(roomRecount);
|
||||
gateway.shutdown();
|
||||
await Promise.race([server.stop(true), Bun.sleep(opts.stopWaitMs ?? 1000)]);
|
||||
db.close();
|
||||
};
|
||||
|
||||
return { server, stop, users, sessions, db, gateway, settings, roles, purgeIdleGuests };
|
||||
return { server, stop, users, sessions, db, gateway, settings, roles, rooms, purgeIdleGuests };
|
||||
}
|
||||
|
||||
async function serveFile(root: string, pathname: string): Promise<Response> {
|
||||
|
||||
93
apps/server/src/songs/pool.ts
Normal file
93
apps/server/src/songs/pool.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* Which songs a room's settings select (docs/04, docs/12 Q7·Q9).
|
||||
* - 장르: same group "또는", different groups "그리고"; empty = 전체
|
||||
* - 난이도 N: a song qualifies when any applicable scope has level N: 'all', each chosen genre, each decade the year range touches
|
||||
* - 재생 가능: listening modes need a confirmed (matched, embeddable) YouTube video; the lyrics mode needs lyrics
|
||||
*/
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import type { RoomConfig } from '@mq/shared';
|
||||
|
||||
type Args = (string | number)[];
|
||||
|
||||
function where(db: Database, c: RoomConfig): { sql: string; args: Args } {
|
||||
const w: string[] = ['s.deleted_at IS NULL', 's.hidden = 0'];
|
||||
const args: Args = [];
|
||||
if (c.genres.length) {
|
||||
const groups = new Map<string, string[]>();
|
||||
const known = db.query<{ id: string; grp: string }, []>('SELECT id, grp FROM genres').all();
|
||||
for (const g of c.genres) {
|
||||
const grp = known.find((k) => k.id === g)?.grp;
|
||||
if (!grp) continue;
|
||||
groups.set(grp, [...(groups.get(grp) ?? []), g]);
|
||||
}
|
||||
for (const ids of groups.values()) {
|
||||
w.push(`EXISTS (SELECT 1 FROM song_genres g WHERE g.song_id = s.id AND g.genre_id IN (${ids.map(() => '?').join(',')}))`);
|
||||
args.push(...ids);
|
||||
}
|
||||
}
|
||||
if (c.yearFrom) (w.push('s.year >= ?'), args.push(c.yearFrom));
|
||||
if (c.yearTo) (w.push('s.year <= ?'), args.push(c.yearTo));
|
||||
const scopes = ['all', ...c.genres.map((g) => `genre:${g}`)];
|
||||
if (c.yearFrom || c.yearTo) {
|
||||
const from = Math.floor((c.yearFrom ?? 1950) / 10) * 10;
|
||||
const to = Math.floor((c.yearTo ?? new Date().getFullYear()) / 10) * 10;
|
||||
for (let d = from; d <= to; d += 10) scopes.push(`decade:${d}`);
|
||||
}
|
||||
w.push(`EXISTS (SELECT 1 FROM song_levels l WHERE l.song_id = s.id AND l.level = ? AND l.scope IN (${scopes.map(() => '?').join(',')}))`);
|
||||
args.push(c.level, ...scopes);
|
||||
if (c.mode === 'artist') {
|
||||
if (!c.artistIds.length) w.push('0');
|
||||
else {
|
||||
w.push(`EXISTS (SELECT 1 FROM song_artists a WHERE a.song_id = s.id AND a.artist_id IN (${c.artistIds.map(() => '?').join(',')}))`);
|
||||
args.push(...c.artistIds);
|
||||
}
|
||||
}
|
||||
return { sql: w.join(' AND '), args };
|
||||
}
|
||||
|
||||
function playable(c: RoomConfig): string {
|
||||
return c.mode === 'lyrics' ? 'EXISTS (SELECT 1 FROM lyrics y WHERE y.song_id = s.id)' : "s.youtube_status = 'matched' AND s.embeddable = 1";
|
||||
}
|
||||
|
||||
/** playable = songs a game can use now; total = also those still waiting for a YouTube match (lyrics mode: same). */
|
||||
export function countPool(db: Database, c: RoomConfig): { playable: number; total: number } {
|
||||
const { sql, args } = where(db, c);
|
||||
const r = db
|
||||
.query<{ total: number; playable: number | null }, Args>(`SELECT COUNT(*) total, SUM(${playable(c)}) playable FROM songs s WHERE ${sql}`)
|
||||
.get(...args)!;
|
||||
return { total: r.total, playable: r.playable ?? 0 };
|
||||
}
|
||||
|
||||
/** Playable song ids for a game (stage 5 shuffles and picks from these), excluding already played ones. */
|
||||
export function poolIds(db: Database, c: RoomConfig, exclude: number[] = []): number[] {
|
||||
const { sql, args } = where(db, c);
|
||||
const ex = exclude.length ? ` AND s.id NOT IN (${exclude.map(() => '?').join(',')})` : '';
|
||||
return db
|
||||
.query<{ id: number }, Args>(`SELECT s.id FROM songs s WHERE ${sql} AND ${playable(c)}${ex}`)
|
||||
.all(...args, ...exclude)
|
||||
.map((r) => r.id);
|
||||
}
|
||||
|
||||
/** Year span of the catalog, for the 연도 slider. */
|
||||
export function yearBounds(db: Database): { min: number; max: number } {
|
||||
const r = db.query<{ min: number | null; max: number | null }, []>('SELECT MIN(year) min, MAX(year) max FROM songs WHERE deleted_at IS NULL AND year IS NOT NULL').get()!;
|
||||
return { min: r.min ?? 1980, max: Math.max(r.max ?? 0, new Date().getFullYear()) };
|
||||
}
|
||||
|
||||
/** 가수 선택 search (docs/04 가수노래): name or alias, with song counts. */
|
||||
export function searchArtists(db: Database, q: string, limit = 20) {
|
||||
const like = `%${q.replace(/[%_\\]/g, (m) => '\\' + m)}%`;
|
||||
return db
|
||||
.query<{ id: number; name: string; songs: number }, [string, string, number]>(
|
||||
`SELECT a.id, a.name, COUNT(DISTINCT sa.song_id) songs FROM artists a
|
||||
JOIN song_artists sa ON sa.artist_id = a.id JOIN songs s ON s.id = sa.song_id AND s.deleted_at IS NULL
|
||||
WHERE a.name LIKE ? ESCAPE '\\' OR EXISTS (SELECT 1 FROM artist_aliases x WHERE x.artist_id = a.id AND x.alias LIKE ? ESCAPE '\\')
|
||||
GROUP BY a.id ORDER BY songs DESC, a.name LIMIT ?`,
|
||||
)
|
||||
.all(like, like, limit);
|
||||
}
|
||||
|
||||
export function artistsByIds(db: Database, ids: number[]) {
|
||||
if (!ids.length) return [];
|
||||
return db.query<{ id: number; name: string }, number[]>(`SELECT id, name FROM artists WHERE id IN (${ids.map(() => '?').join(',')})`).all(...ids);
|
||||
}
|
||||
@@ -5,20 +5,28 @@
|
||||
import type { Server, ServerWebSocket } from 'bun';
|
||||
import { ClientMessage, MAX_CLIENT_MESSAGE_BYTES, PROTOCOL, type ServerMessage } from '@mq/shared';
|
||||
import type { LogFn } from '../server';
|
||||
import type { RoomManager } from '../rooms/manager';
|
||||
import { TokenBucket } from './rate-limit';
|
||||
|
||||
export interface WsData {
|
||||
userId: string;
|
||||
connId: number;
|
||||
/** The room this socket is in (docs/04). */
|
||||
roomCode?: string;
|
||||
}
|
||||
|
||||
export interface GatewayDeps {
|
||||
log: LogFn;
|
||||
onClose?: (userId: string) => void;
|
||||
rooms: RoomManager;
|
||||
/** Chat flood guard (docs/12 채팅): off by default, the admin turns it on in site settings. */
|
||||
chatGuard?: () => { on: boolean; ratePerSec: number; burst: number };
|
||||
}
|
||||
|
||||
export class Gateway {
|
||||
private conns = new Map<string, Set<ServerWebSocket<WsData>>>();
|
||||
private nextId = 1;
|
||||
private buckets = new Map<number, TokenBucket>();
|
||||
|
||||
constructor(private d: GatewayDeps) {}
|
||||
|
||||
@@ -57,7 +65,7 @@ export class Gateway {
|
||||
this.conns.set(ws.data.userId, set);
|
||||
this.send(ws, { t: 'welcome', protocol: PROTOCOL, userId: ws.data.userId, serverNow: Date.now() });
|
||||
},
|
||||
message: (ws: ServerWebSocket<WsData>, raw: string | Buffer) => {
|
||||
message: (ws: ServerWebSocket<WsData>, raw: string | Buffer): void => {
|
||||
const text = typeof raw === 'string' ? raw : raw.toString();
|
||||
if (text.length > MAX_CLIENT_MESSAGE_BYTES) return this.send(ws, { t: 'error', message: '메시지가 너무 길어요.' });
|
||||
let json: unknown;
|
||||
@@ -69,12 +77,41 @@ export class Gateway {
|
||||
const parsed = ClientMessage.safeParse(json);
|
||||
if (!parsed.success) return this.send(ws, { t: 'error', message: '잘못된 메시지예요.' });
|
||||
const m = parsed.data;
|
||||
const rooms = this.d.rooms;
|
||||
const err = (e: string | null): void => {
|
||||
if (e) this.send(ws, { t: 'error', message: e });
|
||||
};
|
||||
switch (m.t) {
|
||||
case 'ping':
|
||||
return this.send(ws, { t: 'pong', c: m.c, s: Date.now() });
|
||||
case 'join':
|
||||
return err(rooms.join(ws, m.code, m.password));
|
||||
case 'leave':
|
||||
return rooms.leave(ws);
|
||||
case 'config':
|
||||
return err(rooms.setConfig(ws, m.patch));
|
||||
case 'password':
|
||||
return err(rooms.setPassword(ws, m.value));
|
||||
case 'ready':
|
||||
return err(rooms.ready(ws, m.on));
|
||||
case 'kick':
|
||||
return err(rooms.kick(ws, m.userId));
|
||||
case 'host':
|
||||
return err(rooms.giveHost(ws, m.userId));
|
||||
case 'chat': {
|
||||
const g = this.d.chatGuard?.();
|
||||
if (g?.on) {
|
||||
let b = this.buckets.get(ws.data.connId);
|
||||
if (!b) this.buckets.set(ws.data.connId, (b = new TokenBucket(g.ratePerSec, g.burst)));
|
||||
if (!b.take()) return this.send(ws, { t: 'error', message: '채팅을 너무 빨리 보내고 있어요. 잠깐 쉬었다 보내 주세요.' });
|
||||
}
|
||||
return err(rooms.chat(ws, m.text, m.n));
|
||||
}
|
||||
}
|
||||
},
|
||||
close: (ws: ServerWebSocket<WsData>) => {
|
||||
this.buckets.delete(ws.data.connId);
|
||||
this.d.rooms.detach(ws);
|
||||
const set = this.conns.get(ws.data.userId);
|
||||
set?.delete(ws);
|
||||
if (set && set.size === 0) {
|
||||
|
||||
114
apps/web/src/components/ChatPanel.tsx
Normal file
114
apps/web/src/components/ChatPanel.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* 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).
|
||||
*/
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { CHAT_MAX, type ChatLine } from '@mq/shared/lite';
|
||||
|
||||
/** 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 function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: ChatLine[]; pending: { n: string; text: string }[]; meId: string; myName: string; onSend: (text: string) => void }) {
|
||||
const [text, setText] = useState('');
|
||||
const [stuck, setStuck] = useState(true);
|
||||
const [unseen, setUnseen] = useState(false);
|
||||
const logRef = useRef<HTMLDivElement>(null);
|
||||
const lastSent = useRef('');
|
||||
// Changes whenever a line arrives, also once the log is capped at 200 lines.
|
||||
const tick = `${lines.at(-1)?.seq ?? 0}:${pending.length}`;
|
||||
|
||||
// Auto-scroll only while the reader is at the bottom (docs/06 위로 스크롤하면 멈춤).
|
||||
useLayoutEffect(() => {
|
||||
const el = logRef.current;
|
||||
if (!el) return;
|
||||
if (stuck) el.scrollTop = el.scrollHeight;
|
||||
else setUnseen(true);
|
||||
}, [tick]);
|
||||
useEffect(() => {
|
||||
if (stuck) setUnseen(false);
|
||||
}, [stuck]);
|
||||
|
||||
const toBottom = () => {
|
||||
const el = logRef.current;
|
||||
if (el) el.scrollTop = el.scrollHeight;
|
||||
setStuck(true);
|
||||
};
|
||||
const submit = () => {
|
||||
const t = text.trim();
|
||||
if (!t) return;
|
||||
onSend(t.slice(0, CHAT_MAX));
|
||||
lastSent.current = t;
|
||||
setText('');
|
||||
toBottom();
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="card chat" aria-label="채팅">
|
||||
<div
|
||||
className="chat-log"
|
||||
ref={logRef}
|
||||
role="log"
|
||||
aria-live="polite"
|
||||
onScroll={(e) => {
|
||||
const el = e.currentTarget;
|
||||
setStuck(el.scrollHeight - el.scrollTop - el.clientHeight < 24);
|
||||
}}
|
||||
>
|
||||
{lines.length === 0 && pending.length === 0 && <div className="chat-sys">아직 대화가 없어요. 먼저 인사해 보세요!</div>}
|
||||
{lines.map((l) =>
|
||||
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>
|
||||
<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>
|
||||
<span>{p.text}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{unseen && !stuck && (
|
||||
<button type="button" className="btn btn-sm chat-new" onClick={toBottom}>
|
||||
새 메시지 ↓
|
||||
</button>
|
||||
)}
|
||||
<form
|
||||
className="chat-input"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
submit();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
className="input"
|
||||
value={text}
|
||||
maxLength={CHAT_MAX}
|
||||
placeholder="메시지 입력 (Enter)"
|
||||
aria-label="채팅 입력"
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') setText('');
|
||||
else if (e.key === 'ArrowUp' && !text && lastSent.current) {
|
||||
e.preventDefault();
|
||||
setText(lastSent.current);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<button className="btn btn-primary" disabled={!text.trim()}>
|
||||
보내기
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
448
apps/web/src/components/RoomSettings.tsx
Normal file
448
apps/web/src/components/RoomSettings.tsx
Normal file
@@ -0,0 +1,448 @@
|
||||
/**
|
||||
* 방 설정 (docs/04, docs/12): host edits, everyone else sees the same panel read-only.
|
||||
* Every change is sent at once as a partial patch; the server validates and broadcasts.
|
||||
*/
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import {
|
||||
COUNTS,
|
||||
HINT_TIMES,
|
||||
LEVELS,
|
||||
LISTEN_SECS,
|
||||
LYRICS_SECS,
|
||||
MODES,
|
||||
VOTE_RULES,
|
||||
listenLabel,
|
||||
voteLabel,
|
||||
type RoomConfig,
|
||||
type VoteRule,
|
||||
} from '@mq/shared/lite';
|
||||
import { apiCall } from '../net/api';
|
||||
|
||||
export interface CatalogMeta {
|
||||
genres: { id: string; name: string; grp: 'region' | 'style' | 'theme' }[];
|
||||
years: { min: number; max: number };
|
||||
}
|
||||
|
||||
type Patch = Partial<RoomConfig>;
|
||||
|
||||
function Seg<T extends string | number>({ value, options, onChange, disabled, label }: { value: T; options: { v: T; label: ReactNode }[]; onChange: (v: T) => void; disabled: boolean; label: string }) {
|
||||
return (
|
||||
<div className="seg" role="radiogroup" aria-label={label}>
|
||||
{options.map((o) => (
|
||||
<button key={String(o.v)} type="button" role="radio" aria-checked={o.v === value} className={o.v === value ? 'on' : ''} disabled={disabled && o.v !== value} onClick={() => !disabled && onChange(o.v)}>
|
||||
{o.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({ title, children, tip }: { title: string; children: ReactNode; tip?: string }) {
|
||||
return (
|
||||
<section className="sec">
|
||||
<div className="label">
|
||||
{title}
|
||||
{tip && (
|
||||
<span className="info" tabIndex={0} aria-label={tip} data-tip={tip}>
|
||||
!
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const STAR_COLOR = (n: number) => (n <= 3 ? 'var(--star-1)' : n <= 6 ? 'var(--star-2)' : n <= 8 ? 'var(--star-3)' : 'var(--star-4)');
|
||||
|
||||
function Stars({ level, onChange, disabled }: { level: number; onChange: (n: number) => void; disabled: boolean }) {
|
||||
const [hover, setHover] = useState<number | null>(null);
|
||||
const shown = hover ?? level;
|
||||
const [name, desc] = LEVELS[shown - 1]!;
|
||||
return (
|
||||
<div className="diff">
|
||||
<div className="stars" role="radiogroup" aria-label="난이도" onMouseLeave={() => setHover(null)}>
|
||||
{Array.from({ length: 10 }, (_, i) => {
|
||||
const n = i + 1;
|
||||
const filled = n <= shown;
|
||||
return (
|
||||
<button
|
||||
key={n}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={n === level}
|
||||
aria-label={`${n}단계 ${LEVELS[i]![0]}`}
|
||||
className="star-btn"
|
||||
disabled={disabled}
|
||||
onMouseEnter={() => !disabled && setHover(n)}
|
||||
onFocus={() => !disabled && setHover(n)}
|
||||
onClick={() => onChange(n)}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" width="26" height="26" aria-hidden>
|
||||
<path
|
||||
d="M12 2.6l2.9 6.1 6.6.8-4.9 4.6 1.3 6.6L12 17.4l-5.9 3.3 1.3-6.6-4.9-4.6 6.6-.8z"
|
||||
fill={filled ? STAR_COLOR(n) : 'none'}
|
||||
stroke={STAR_COLOR(n)}
|
||||
strokeWidth="2"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="t">
|
||||
<b>
|
||||
{shown}단계 · {name}
|
||||
</b>
|
||||
<span>{desc}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Two-handle year range (docs/04 연도, 참고 이미지 1.png) + 부터/까지 selects + decade chips. */
|
||||
function YearRange({ from, to, min, max, onChange, disabled }: { from: number | null; to: number | null; min: number; max: number; onChange: (f: number | null, t: number | null) => void; disabled: boolean }) {
|
||||
const f = from ?? min;
|
||||
const t = to ?? max;
|
||||
const pos = (y: number) => ((y - min) / Math.max(1, max - min)) * 100;
|
||||
const years = Array.from({ length: max - min + 1 }, (_, i) => min + i);
|
||||
const set = (a: number, b: number) => onChange(a <= min ? null : a, b >= max ? null : b);
|
||||
const decades = [1980, 1990, 2000, 2010, 2020].filter((d) => d + 9 >= min && d <= max);
|
||||
return (
|
||||
<div className="stack" style={{ gap: 10 }}>
|
||||
<div className="yr">
|
||||
<div className="track" />
|
||||
<div className="fill" style={{ left: `${pos(f)}%`, width: `${pos(t) - pos(f)}%` }} />
|
||||
<span className="bub dn" style={{ left: `${pos(f)}%` }}>
|
||||
{f}
|
||||
</span>
|
||||
<span className="bub up" style={{ left: `${pos(t)}%` }}>
|
||||
{t}
|
||||
</span>
|
||||
<input type="range" min={min} max={max} value={f} disabled={disabled} aria-label="시작 연도" onChange={(e) => set(Math.min(Number(e.target.value), t), t)} />
|
||||
<input type="range" min={min} max={max} value={t} disabled={disabled} aria-label="끝 연도" onChange={(e) => set(f, Math.max(Number(e.target.value), f))} />
|
||||
</div>
|
||||
<div className="row" style={{ flexWrap: 'nowrap' }}>
|
||||
<select className="input year-sel" value={f} disabled={disabled} aria-label="부터" onChange={(e) => set(Number(e.target.value), Math.max(t, Number(e.target.value)))}>
|
||||
{years.map((y) => (
|
||||
<option key={y} value={y}>
|
||||
{y}년부터
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select className="input year-sel" value={t} disabled={disabled} aria-label="까지" onChange={(e) => set(Math.min(f, Number(e.target.value)), Number(e.target.value))}>
|
||||
{years.map((y) => (
|
||||
<option key={y} value={y}>
|
||||
{y}년까지
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="row">
|
||||
<button type="button" className="chip" aria-pressed={from === null && to === null} disabled={disabled} onClick={() => onChange(null, null)}>
|
||||
전체
|
||||
</button>
|
||||
{decades.map((d) => (
|
||||
<button key={d} type="button" className="chip" aria-pressed={from === Math.max(d, min) && to === Math.min(d + 9, max)} disabled={disabled} onClick={() => onChange(Math.max(d, min), Math.min(d + 9, max))}>
|
||||
{d === 2000 ? '2000년대' : `${String(d).slice(2)}년대`}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 가수 선택 (docs/04 가수노래): search → add chip; tapping a chip removes it. */
|
||||
function ArtistPicker({ selected, onChange, disabled }: { selected: { id: number; name: string }[]; onChange: (ids: number[]) => void; disabled: boolean }) {
|
||||
const [q, setQ] = useState('');
|
||||
const [hits, setHits] = useState<{ id: number; name: string; songs: number }[]>([]);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
useEffect(() => {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
if (!q.trim()) return setHits([]);
|
||||
timer.current = setTimeout(() => {
|
||||
apiCall<{ artists: { id: number; name: string; songs: number }[] }>('GET', `/api/artists?q=${encodeURIComponent(q.trim())}`)
|
||||
.then((r) => setHits(r.artists))
|
||||
.catch(() => setHits([]));
|
||||
}, 200);
|
||||
}, [q]);
|
||||
const ids = selected.map((a) => a.id);
|
||||
return (
|
||||
<div className="stack" style={{ gap: 8 }}>
|
||||
<div className="row" aria-label="선택한 가수">
|
||||
{selected.length === 0 && <span className="muted small">아직 고른 가수가 없어요 (1명 이상 필요)</span>}
|
||||
{selected.map((a) => (
|
||||
<button key={a.id} type="button" className="chip x" aria-pressed="true" disabled={disabled} onClick={() => onChange(ids.filter((x) => x !== a.id))} aria-label={`${a.name} 빼기`}>
|
||||
{a.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{!disabled && (
|
||||
<>
|
||||
<input className="input" placeholder="가수 이름 검색" value={q} onChange={(e) => setQ(e.target.value)} aria-label="가수 검색" />
|
||||
{hits.length > 0 && (
|
||||
<div className="artist-hits" role="listbox" aria-label="가수 검색 결과">
|
||||
{hits.map((h) => (
|
||||
<button
|
||||
key={h.id}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={ids.includes(h.id)}
|
||||
className="artist-hit"
|
||||
onClick={() => onChange(ids.includes(h.id) ? ids.filter((x) => x !== h.id) : [...ids, h.id])}
|
||||
>
|
||||
<b>{h.name}</b>
|
||||
<span className="muted small">{h.songs}곡</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function RoomSettings({
|
||||
config,
|
||||
editable,
|
||||
meta,
|
||||
artists,
|
||||
pool,
|
||||
hasPassword,
|
||||
onPatch,
|
||||
onPassword,
|
||||
}: {
|
||||
config: RoomConfig;
|
||||
editable: boolean;
|
||||
meta: CatalogMeta | null;
|
||||
artists: { id: number; name: string }[];
|
||||
pool: { playable: number; total: number };
|
||||
hasPassword: boolean;
|
||||
onPatch: (p: Patch) => void;
|
||||
onPassword: (v: string | null) => void;
|
||||
}) {
|
||||
const ro = !editable;
|
||||
const c = config;
|
||||
const [title, setTitle] = useState(c.title);
|
||||
const [pw, setPw] = useState('');
|
||||
useEffect(() => setTitle(c.title), [c.title]);
|
||||
const groups: [string, 'region' | 'style' | 'theme'][] = [
|
||||
['지역', 'region'],
|
||||
['장르', 'style'],
|
||||
['테마', 'theme'],
|
||||
];
|
||||
const toggleGenre = (id: string) => onPatch({ genres: c.genres.includes(id) ? c.genres.filter((g) => g !== id) : [...c.genres, id] });
|
||||
const vote = (rules: readonly VoteRule[]) => rules.map((v) => ({ v, label: voteLabel(v) }));
|
||||
const listening = c.mode !== 'lyrics';
|
||||
return (
|
||||
<div className="settings card ink">
|
||||
<div className="hd">
|
||||
<h2>방 설정</h2>
|
||||
<span className="small" style={{ fontWeight: 700 }}>
|
||||
{editable ? '바꾸면 바로 모두에게 보여요' : '방장만 바꿀 수 있어요'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="bd">
|
||||
<Section title="방 이름">
|
||||
<input
|
||||
className="input"
|
||||
value={title}
|
||||
maxLength={40}
|
||||
disabled={ro}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
onBlur={() => title.trim() !== c.title && onPatch({ title: title.trim() })}
|
||||
onKeyDown={(e) => e.key === 'Enter' && (e.target as HTMLInputElement).blur()}
|
||||
aria-label="방 이름"
|
||||
/>
|
||||
</Section>
|
||||
<Section title="모드">
|
||||
<Seg label="모드" value={c.mode} disabled={ro} onChange={(mode) => onPatch({ mode })} options={MODES.map((m) => ({ v: m.id, label: `${m.icon} ${m.label}` }))} />
|
||||
<div className="subbox">
|
||||
{listening ? (
|
||||
<>
|
||||
<div>
|
||||
<div className="label">듣고맞출시간</div>
|
||||
<Seg label="듣고맞출시간" value={c.listenSec} disabled={ro} onChange={(listenSec) => onPatch({ listenSec })} options={LISTEN_SECS.map((v) => ({ v, label: listenLabel(v) }))} />
|
||||
</div>
|
||||
<div>
|
||||
<div className="label">재생위치</div>
|
||||
<Seg
|
||||
label="재생위치"
|
||||
value={c.startAt}
|
||||
disabled={ro}
|
||||
onChange={(startAt) => onPatch({ startAt })}
|
||||
options={[
|
||||
{ v: 'start', label: '처음부터' },
|
||||
{ v: 'highlight', label: '하이라이트부터' },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
{c.mode === 'artist' && (
|
||||
<div>
|
||||
<div className="label">가수 선택</div>
|
||||
<ArtistPicker selected={artists} disabled={ro} onChange={(artistIds) => onPatch({ artistIds })} />
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div>
|
||||
<div className="label">보고맞출시간</div>
|
||||
<Seg label="보고맞출시간" value={c.lyricsSec} disabled={ro} onChange={(lyricsSec) => onPatch({ lyricsSec })} options={LYRICS_SECS.map((v) => ({ v, label: v ? `${v}초` : '무제한' }))} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Section>
|
||||
<Section title="장르 · 여러 개 선택 가능">
|
||||
<div className="chipgroup">
|
||||
<span className="g">전체</span>
|
||||
<div className="row">
|
||||
<button type="button" className="chip" aria-pressed={c.genres.length === 0} disabled={ro} onClick={() => onPatch({ genres: [] })}>
|
||||
전체
|
||||
</button>
|
||||
</div>
|
||||
{groups.map(([label, grp]) => (
|
||||
<GenreRow key={grp} label={label}>
|
||||
{meta?.genres
|
||||
.filter((g) => g.grp === grp)
|
||||
.map((g) => (
|
||||
<button key={g.id} type="button" className="chip" aria-pressed={c.genres.includes(g.id)} disabled={ro} onClick={() => toggleGenre(g.id)}>
|
||||
{g.name}
|
||||
</button>
|
||||
))}
|
||||
</GenreRow>
|
||||
))}
|
||||
</div>
|
||||
<p className="muted small" style={{ marginTop: 6 }}>
|
||||
같은 줄은 "또는", 다른 줄끼리는 "그리고"예요. 예) K-POP + 발라드 = 국내 발라드
|
||||
</p>
|
||||
</Section>
|
||||
<Section title="연도">
|
||||
{meta && <YearRange from={c.yearFrom} to={c.yearTo} min={meta.years.min} max={meta.years.max} disabled={ro} onChange={(yearFrom, yearTo) => onPatch({ yearFrom, yearTo })} />}
|
||||
</Section>
|
||||
<Section title="난이도 · 고른 단계의 곡만 나와요">
|
||||
<Stars level={c.level} disabled={ro} onChange={(level) => onPatch({ level })} />
|
||||
<div className="tiers">
|
||||
<span>
|
||||
<i style={{ background: 'var(--star-1)' }} />
|
||||
1~3 쉬움
|
||||
</span>
|
||||
<span>
|
||||
<i style={{ background: 'var(--star-2)' }} />
|
||||
4~6 보통
|
||||
</span>
|
||||
<span>
|
||||
<i style={{ background: 'var(--star-3)' }} />
|
||||
7~8 어려움
|
||||
</span>
|
||||
<span>
|
||||
<i style={{ background: 'var(--star-4)' }} />
|
||||
9~10 극악
|
||||
</span>
|
||||
</div>
|
||||
</Section>
|
||||
<Section title="정답방식">
|
||||
<Seg
|
||||
label="정답방식"
|
||||
value={c.answer}
|
||||
disabled={ro}
|
||||
onChange={(answer) => onPatch({ answer })}
|
||||
options={[
|
||||
{ v: 'title', label: '제목만' },
|
||||
{ v: 'artist', label: '가수만' },
|
||||
{ v: 'both', label: '제목+가수 (순서 무관)' },
|
||||
]}
|
||||
/>
|
||||
</Section>
|
||||
<Section title="정답인식 · 켜면 그 요소까지 똑같이 쳐야 정답">
|
||||
<div className="row">
|
||||
{(
|
||||
[
|
||||
['space', '띄어쓰기'],
|
||||
['number', '숫자'],
|
||||
['symbol', '특수문자'],
|
||||
] as const
|
||||
).map(([k, label]) => (
|
||||
<button key={k} type="button" className={`toggle ${c.strict[k] ? 'on' : ''}`} aria-pressed={c.strict[k]} disabled={ro} onClick={() => onPatch({ strict: { ...c.strict, [k]: !c.strict[k] } })}>
|
||||
<i aria-hidden />
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
<Section title="힌트공개">
|
||||
<Seg
|
||||
label="힌트공개"
|
||||
value={c.hint}
|
||||
disabled={ro}
|
||||
onChange={(hint) => onPatch({ hint })}
|
||||
options={[{ v: 'none' as const, label: '없음' }, ...HINT_TIMES.map((v) => ({ v, label: `${v}초` })), { v: 'manual' as const, label: '직접선택' }]}
|
||||
/>
|
||||
{c.hint === 'manual' && (
|
||||
<div className="subbox">
|
||||
<div className="label">힌트인원(이상)</div>
|
||||
<Seg label="힌트인원" value={c.hintVotes} disabled={ro} onChange={(hintVotes) => onPatch({ hintVotes: hintVotes as RoomConfig['hintVotes'] })} options={vote(VOTE_RULES.filter((v) => v !== 'none'))} />
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
<Section title="스킵인원(이상)" tip="이번문제 스킵을 위해 스킵을 눌러야하는 인원 설정">
|
||||
<Seg label="스킵인원" value={c.skipVotes} disabled={ro} onChange={(skipVotes) => onPatch({ skipVotes })} options={vote(VOTE_RULES)} />
|
||||
</Section>
|
||||
{listening && (
|
||||
<Section title="다시듣기인원(이상)" tip="이번문제를 모두 같이 다시 들으려면 다시듣기를 눌러야하는 인원 설정">
|
||||
<Seg label="다시듣기인원" value={c.replayVotes} disabled={ro} onChange={(replayVotes) => onPatch({ replayVotes })} options={vote(VOTE_RULES)} />
|
||||
</Section>
|
||||
)}
|
||||
<Section title="문제 수">
|
||||
<Seg
|
||||
label="문제 수"
|
||||
value={c.count}
|
||||
disabled={ro}
|
||||
onChange={(count) => onPatch({ count })}
|
||||
options={COUNTS.map((v) => ({ v, label: v ? String(v) : `무제한(${pool.playable.toLocaleString()})` }))}
|
||||
/>
|
||||
</Section>
|
||||
<Section title="방 공개">
|
||||
<Seg
|
||||
label="방 공개"
|
||||
value={c.visibility}
|
||||
disabled={ro}
|
||||
onChange={(visibility) => onPatch({ visibility })}
|
||||
options={[
|
||||
{ v: 'public', label: '공개' },
|
||||
{ v: 'private', label: '비공개(코드로만)' },
|
||||
{ v: 'password', label: '비밀번호' },
|
||||
]}
|
||||
/>
|
||||
{c.visibility === 'password' && editable && (
|
||||
<form
|
||||
className="row"
|
||||
style={{ marginTop: 8 }}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (pw.trim()) onPassword(pw.trim());
|
||||
setPw('');
|
||||
}}
|
||||
>
|
||||
<input className="input grow" style={{ maxWidth: 220 }} placeholder={hasPassword ? '새 비밀번호' : '비밀번호 정하기'} value={pw} maxLength={40} onChange={(e) => setPw(e.target.value)} aria-label="방 비밀번호" />
|
||||
<button className="btn btn-sm">{hasPassword ? '바꾸기' : '정하기'}</button>
|
||||
{hasPassword ? <span className="badge ok">비밀번호 있음</span> : <span className="field-error small">비밀번호를 정해야 잠겨요</span>}
|
||||
</form>
|
||||
)}
|
||||
{c.visibility === 'password' && !editable && hasPassword && <p className="muted small" style={{ marginTop: 6 }}>🔒 비밀번호로 잠긴 방이에요</p>}
|
||||
{c.visibility === 'private' && <p className="muted small" style={{ marginTop: 6 }}>방 목록에 나오지 않아요. 코드나 링크로만 들어올 수 있어요.</p>}
|
||||
</Section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function GenreRow({ label, children }: { label: string; children: ReactNode }) {
|
||||
return (
|
||||
<>
|
||||
<span className="g">{label}</span>
|
||||
<div className="row">{children}</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import { Home } from './pages/Home';
|
||||
const LoginPage = lazy(() => import('./pages/LoginPage'));
|
||||
const NotFound = lazy(() => import('./pages/NotFound'));
|
||||
const AdminApp = lazy(() => import('./pages/admin/AdminApp'));
|
||||
const RoomPage = lazy(() => import('./pages/RoomPage'));
|
||||
|
||||
function Announcement() {
|
||||
const text = useSession((s) => s.announcement);
|
||||
@@ -53,6 +54,7 @@ function Shell() {
|
||||
<Routes>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/r/:code" element={<RoomPage />} />
|
||||
<Route path="/admin/*" element={<AdminApp />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
|
||||
183
apps/web/src/net/socket.ts
Normal file
183
apps/web/src/net/socket.ts
Normal file
@@ -0,0 +1,183 @@
|
||||
/**
|
||||
* 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 { toast } from '../store/toast';
|
||||
|
||||
type Status = 'idle' | 'connecting' | 'open' | 'reconnecting';
|
||||
|
||||
interface RoomState {
|
||||
status: Status;
|
||||
code: string | null;
|
||||
room: RoomView | null;
|
||||
/** serverNow ≈ Date.now() + offset */
|
||||
offset: number;
|
||||
rtt: number | null;
|
||||
/** Join failed with this message (wrong password, unknown room…). */
|
||||
joinError: string | null;
|
||||
left: null | 'leave' | 'kicked' | 'closed' | 'elsewhere';
|
||||
/** Room chat in seq order (docs/06), last CHAT_KEEP lines. */
|
||||
chat: ChatLine[];
|
||||
/** My lines not confirmed by the server yet: always drawn at the bottom (docs/06 지연 없는 전송). */
|
||||
pending: { n: string; text: string }[];
|
||||
}
|
||||
|
||||
const CHAT_KEEP = 200;
|
||||
/** The room this tab was last in: tells "the server restarted and the room is gone" apart from a wrong code. */
|
||||
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: [] }));
|
||||
|
||||
let ws: WebSocket | null = null;
|
||||
let retry = 0;
|
||||
let password: string | undefined;
|
||||
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;
|
||||
|
||||
function lastRoom(): string | null {
|
||||
try {
|
||||
return sessionStorage.getItem(LAST_ROOM_KEY);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
function setLastRoom(code: string | null): void {
|
||||
try {
|
||||
if (code) sessionStorage.setItem(LAST_ROOM_KEY, code);
|
||||
else sessionStorage.removeItem(LAST_ROOM_KEY);
|
||||
} catch {
|
||||
/* private mode */
|
||||
}
|
||||
}
|
||||
function sendJoin(code: string): void {
|
||||
joining = true;
|
||||
send({ t: 'join', code, password });
|
||||
}
|
||||
const samples: { sent: number; received: number; server: number }[] = [];
|
||||
|
||||
function send(m: unknown): void {
|
||||
if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify(m));
|
||||
}
|
||||
|
||||
function syncClock(): void {
|
||||
for (let i = 0; i < 5; i++) setTimeout(() => send({ t: 'ping', c: Date.now() }), i * 150);
|
||||
}
|
||||
|
||||
function onMessage(m: ServerMessage): void {
|
||||
switch (m.t) {
|
||||
case 'welcome': {
|
||||
useRoom.setState({ status: 'open', offset: m.serverNow - Date.now() });
|
||||
retry = 0;
|
||||
syncClock();
|
||||
const code = useRoom.getState().code;
|
||||
if (code) sendJoin(code);
|
||||
return;
|
||||
}
|
||||
case 'pong': {
|
||||
samples.push({ sent: m.c, received: Date.now(), server: m.s });
|
||||
if (samples.length > 10) samples.shift();
|
||||
let best: { offset: number; rtt: number } | null = null;
|
||||
for (const s of samples) {
|
||||
const rtt = s.received - s.sent;
|
||||
const offset = s.server - (s.sent + rtt / 2);
|
||||
if (!best || rtt < best.rtt) best = { offset, rtt };
|
||||
}
|
||||
if (best) useRoom.setState({ offset: best.offset, rtt: best.rtt });
|
||||
return;
|
||||
}
|
||||
case 'room':
|
||||
if (m.room.code === useRoom.getState().code) {
|
||||
joining = false;
|
||||
setLastRoom(m.room.code);
|
||||
useRoom.setState({ room: m.room, joinError: null, left: null });
|
||||
}
|
||||
return;
|
||||
case 'left':
|
||||
if (m.code === useRoom.getState().code) {
|
||||
setLastRoom(null);
|
||||
useRoom.setState({ room: null, left: m.reason, chat: [], pending: [] });
|
||||
}
|
||||
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 'chat':
|
||||
if (m.code === useRoom.getState().code) {
|
||||
const st = useRoom.getState();
|
||||
useRoom.setState({
|
||||
chat: [...st.chat, m.line].slice(-CHAT_KEEP),
|
||||
pending: m.line.n ? st.pending.filter((p) => p.n !== m.line.n) : st.pending,
|
||||
});
|
||||
}
|
||||
return;
|
||||
case 'notice':
|
||||
toast(m.text);
|
||||
return;
|
||||
case 'error': {
|
||||
const st = useRoom.getState();
|
||||
if (joining && st.code) {
|
||||
joining = false;
|
||||
// The room was there a moment ago (this tab was in it): the server restarted and rooms live in memory (docs/04 결정 1).
|
||||
// Kept after that, so a refresh still explains it.
|
||||
const gone = m.message.includes('찾을 수 없') && lastRoom() === st.code;
|
||||
useRoom.setState({ room: null, joinError: gone ? ROOM_GONE_TEXT : m.message });
|
||||
} else toast(m.message, 'error');
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function connect(): void {
|
||||
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
ws = new WebSocket(`${proto}://${location.host}/ws`);
|
||||
useRoom.setState({ status: retry ? 'reconnecting' : 'connecting' });
|
||||
ws.onmessage = (e) => onMessage(JSON.parse(String(e.data)) as ServerMessage);
|
||||
ws.onclose = () => {
|
||||
ws = null;
|
||||
if (useRoom.getState().status === 'idle') return;
|
||||
useRoom.setState({ status: 'reconnecting' });
|
||||
const wait = Math.min(10_000, 500 * 2 ** retry++);
|
||||
setTimeout(() => useRoom.getState().status !== 'idle' && connect(), wait);
|
||||
};
|
||||
}
|
||||
|
||||
export const socket = {
|
||||
start(): void {
|
||||
if (ws) return;
|
||||
connect();
|
||||
pingTimer ??= setInterval(syncClock, 30_000);
|
||||
},
|
||||
stop(): void {
|
||||
useRoom.setState({ status: 'idle' });
|
||||
ws?.close();
|
||||
ws = null;
|
||||
if (pingTimer) clearInterval(pingTimer);
|
||||
pingTimer = null;
|
||||
},
|
||||
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: [] }) });
|
||||
socket.start();
|
||||
sendJoin(code);
|
||||
},
|
||||
leave(): void {
|
||||
send({ t: 'leave' });
|
||||
setLastRoom(null);
|
||||
useRoom.setState({ code: null, room: null, chat: [], pending: [] });
|
||||
},
|
||||
chat(text: string): void {
|
||||
const n = `${Date.now().toString(36)}${(nonce++).toString(36)}`;
|
||||
useRoom.setState((st) => ({ pending: [...st.pending, { n, text }] }));
|
||||
send({ t: 'chat', text, n });
|
||||
},
|
||||
send,
|
||||
};
|
||||
|
||||
/** Server clock (ms) for countdowns and synced playback. */
|
||||
export const serverNow = () => Date.now() + useRoom.getState().offset;
|
||||
@@ -1,10 +1,59 @@
|
||||
/** 첫 화면 (docs/03): 소개 + 방 만들기/코드로 참여, 시작하기, 열린 방 목록. Rooms arrive in stage 4. */
|
||||
/** 첫 화면 (docs/03): 소개 + 방 만들기/코드로 참여, 시작하기, 열린 방 목록 (docs/11 Q17). */
|
||||
import { useEffect, useState, type FormEvent } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useSession } from '../store/session';
|
||||
import { LoginBox } from '../components/LoginBox';
|
||||
import { Avatar } from '../components/ui';
|
||||
import { apiCall } from '../net/api';
|
||||
import { toast } from '../store/toast';
|
||||
|
||||
interface PublicRoom {
|
||||
code: string;
|
||||
title: string;
|
||||
host: string;
|
||||
players: number;
|
||||
status: 'lobby' | 'playing';
|
||||
hasPassword: boolean;
|
||||
summary: string[];
|
||||
pool: number;
|
||||
}
|
||||
|
||||
export function Home() {
|
||||
const me = useSession((s) => s.me);
|
||||
const nav = useNavigate();
|
||||
const [rooms, setRooms] = useState<PublicRoom[] | null>(null);
|
||||
const [filter, setFilter] = useState<'all' | 'lobby' | 'playing'>('all');
|
||||
const [joining, setJoining] = useState(false);
|
||||
const [code, setCode] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const load = () => void apiCall<{ rooms: PublicRoom[] }>('GET', '/api/rooms').then((r) => setRooms(r.rooms)).catch(() => {});
|
||||
load();
|
||||
const t = setInterval(load, 5000);
|
||||
return () => clearInterval(t);
|
||||
}, []);
|
||||
|
||||
const create = async () => {
|
||||
if (!me) return toast('먼저 디스코드로 로그인하거나 게스트로 시작해 주세요.', 'error');
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await apiCall<{ code: string }>('POST', '/api/rooms', {});
|
||||
nav(`/r/${r.code}`);
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const join = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
const c = code.replace(/\D/g, '');
|
||||
if (c.length !== 6) return toast('방 코드는 숫자 6자리예요.', 'error');
|
||||
nav(`/r/${c}`);
|
||||
};
|
||||
const shown = (rooms ?? []).filter((r) => filter === 'all' || r.status === filter);
|
||||
|
||||
return (
|
||||
<main className="page">
|
||||
<div className="hero">
|
||||
@@ -17,14 +66,19 @@ export function Home() {
|
||||
</h1>
|
||||
<p>방 만들고 링크 하나 보내면 끝. 인원 제한 없이 같이 듣고, 채팅으로 제목을 먼저 치는 사람이 점수를 가져가요.</p>
|
||||
<div className="acts">
|
||||
<button className="btn btn-mustard btn-lg" disabled title="방 기능을 준비하고 있어요">
|
||||
<button className="btn btn-mustard btn-lg" onClick={() => void create()} disabled={busy}>
|
||||
+ 방 만들기
|
||||
</button>
|
||||
<button className="btn btn-lg" disabled title="방 기능을 준비하고 있어요">
|
||||
<button className="btn btn-lg" onClick={() => setJoining((j) => !j)} aria-expanded={joining}>
|
||||
코드로 참여
|
||||
</button>
|
||||
</div>
|
||||
<p className="note">방 만들기는 곧 열려요. 지금은 로그인만 먼저 해 볼 수 있어요.</p>
|
||||
{joining && (
|
||||
<form className="row code-join" onSubmit={join}>
|
||||
<input className="input" inputMode="numeric" autoFocus placeholder="방 코드 6자리" value={code} maxLength={7} onChange={(e) => setCode(e.target.value)} aria-label="방 코드" />
|
||||
<button className="btn btn-mustard">들어가기</button>
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
{me ? (
|
||||
<section className="login-card" aria-labelledby="me-title">
|
||||
@@ -42,9 +96,50 @@ export function Home() {
|
||||
)}
|
||||
</div>
|
||||
<div className="rooms-head">
|
||||
<h2>열린 방 0</h2>
|
||||
<h2>열린 방 {rooms?.length ?? 0}</h2>
|
||||
{(
|
||||
[
|
||||
['all', '전체'],
|
||||
['lobby', '대기 중'],
|
||||
['playing', '진행 중 (중간 참여 가능)'],
|
||||
] as const
|
||||
).map(([k, label]) => (
|
||||
<button key={k} type="button" className="chip" aria-pressed={filter === k} onClick={() => setFilter(k)}>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="empty">아직 열린 방이 없어요.</div>
|
||||
{rooms && shown.length === 0 ? (
|
||||
<div className="empty">{rooms.length ? '이 조건의 방이 없어요.' : '아직 열린 방이 없어요. 첫 방을 만들어 보세요!'}</div>
|
||||
) : (
|
||||
<div className="rooms">
|
||||
{shown.map((r) => (
|
||||
<article key={r.code} className="room-card">
|
||||
<div className="row" style={{ flexWrap: 'nowrap' }}>
|
||||
<span className="t grow">{r.title}</span>
|
||||
{r.status === 'playing' ? <span className="badge live">진행 중</span> : <span className="badge teal">대기</span>}
|
||||
</div>
|
||||
<div className="meta">
|
||||
{r.summary.map((s) => (
|
||||
<span key={s} className="badge">
|
||||
{s}
|
||||
</span>
|
||||
))}
|
||||
{r.hasPassword && <span className="badge">🔒 비밀번호</span>}
|
||||
</div>
|
||||
<div className="row">
|
||||
<span className="muted small">
|
||||
방장 {r.host} · {r.players}명
|
||||
</span>
|
||||
<div className="grow" />
|
||||
<button className="btn btn-sm" onClick={() => nav(`/r/${r.code}`)}>
|
||||
{r.status === 'playing' ? '중간 참여' : '들어가기'}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
223
apps/web/src/pages/RoomPage.tsx
Normal file
223
apps/web/src/pages/RoomPage.tsx
Normal file
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* 대기실 /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.
|
||||
*/
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router';
|
||||
import { configSummary, type RoomConfig } from '@mq/shared/lite';
|
||||
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 { LoginBox } from '../components/LoginBox';
|
||||
import { RoomSettings, type CatalogMeta } from '../components/RoomSettings';
|
||||
import { ChatPanel } from '../components/ChatPanel';
|
||||
|
||||
const LEFT_TEXT: Record<string, string> = {
|
||||
kicked: '방장이 방에서 내보냈어요.',
|
||||
closed: '오래 접속하지 않아 방에서 나갔어요.',
|
||||
elsewhere: '다른 방에 들어가서 이 방에서는 나갔어요.',
|
||||
leave: '방에서 나왔어요.',
|
||||
};
|
||||
|
||||
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 [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(() => {});
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (!me || !/^\d{6}$/.test(code)) return;
|
||||
socket.join(code);
|
||||
}, [me, code]);
|
||||
useEffect(() => {
|
||||
if (left && left !== 'leave') {
|
||||
toast(LEFT_TEXT[left]!, 'error', 5000);
|
||||
nav('/', { replace: true });
|
||||
}
|
||||
}, [left, nav]);
|
||||
|
||||
if (!me) {
|
||||
return (
|
||||
<main className="page narrow stack">
|
||||
<h1>방에 들어가려면 먼저 이름을 정해 주세요</h1>
|
||||
<LoginBox next={`/r/${code}`} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
if (!/^\d{6}$/.test(code)) return <JoinError text="방 코드는 숫자 6자리예요." />;
|
||||
if (!room) {
|
||||
if (joinError?.includes('비밀번호')) {
|
||||
return (
|
||||
<main className="page narrow stack">
|
||||
<h1>비밀번호가 필요한 방이에요</h1>
|
||||
<form
|
||||
className="stack"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
socket.join(code, pw);
|
||||
}}
|
||||
>
|
||||
<input className="input" type="password" autoFocus placeholder="방 비밀번호" value={pw} onChange={(e) => setPw(e.target.value)} aria-label="방 비밀번호" />
|
||||
{joinError.includes('틀렸') && <p className="field-error">{joinError}</p>}
|
||||
<button className="btn btn-primary">들어가기</button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
if (joinError) return <JoinError text={joinError} />;
|
||||
return <div className="page muted">{status === 'reconnecting' ? '다시 연결하는 중…' : '방에 들어가는 중…'}</div>;
|
||||
}
|
||||
|
||||
const isHost = room.hostId === me.id;
|
||||
const c = room.config;
|
||||
const send = (m: unknown) => socket.send(m);
|
||||
const patch = (p: Partial<RoomConfig>) => send({ t: 'config', patch: p });
|
||||
const myReady = room.players.find((p) => p.id === me.id)?.ready ?? false;
|
||||
const genreName = (id: string) => meta?.genres.find((g) => g.id === id)?.name ?? id;
|
||||
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;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="roombar">
|
||||
<Link to="/" className="btn btn-sm btn-ghost">
|
||||
← 방 목록
|
||||
</Link>
|
||||
<h1 className="room-title">{c.title || '이름 없는 방'}</h1>
|
||||
<span className="room-code" aria-label={`방 코드 ${room.code}`}>
|
||||
{room.code.slice(0, 3)} {room.code.slice(3)}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
onClick={() =>
|
||||
navigator.clipboard?.writeText(link).then(
|
||||
() => toast('링크를 복사했어요.'),
|
||||
() => toast(link, 'info', 6000),
|
||||
)
|
||||
}
|
||||
>
|
||||
링크 복사
|
||||
</button>
|
||||
<div className="grow" />
|
||||
<span className="badge teal">{room.status === 'lobby' ? '대기 중' : '게임 중'}</span>
|
||||
<span className="muted small">참가 {room.players.length}명 · 제한 없음</span>
|
||||
<button type="button" className="btn btn-sm" onClick={() => setConfirmLeave(true)}>
|
||||
🚪 나가기
|
||||
</button>
|
||||
</div>
|
||||
<main className="room-main">
|
||||
<div className="stack" style={{ minWidth: 0 }}>
|
||||
<section className="card">
|
||||
<div className="row" style={{ marginBottom: 10 }}>
|
||||
<h2>참가자 {room.players.length}</h2>
|
||||
<span className="muted small">인원 제한 없음 · 게임 중에도 들어올 수 있어요</span>
|
||||
</div>
|
||||
<ul className="players">
|
||||
{room.players.map((p) => (
|
||||
<li key={p.id} className={`pl ${p.id === room.hostId ? 'host' : ''} ${p.online ? '' : 'off'}`}>
|
||||
<Avatar user={p} size={34} />
|
||||
<span className="name">{p.nickname}</span>
|
||||
<span className="r">
|
||||
{p.id === room.hostId ? (
|
||||
<span title="방장" aria-label="방장">
|
||||
👑
|
||||
</span>
|
||||
) : !p.online ? (
|
||||
<span className="badge">접속 끊김</span>
|
||||
) : p.ready ? (
|
||||
<span className="badge teal">준비</span>
|
||||
) : (
|
||||
<span className="badge">대기</span>
|
||||
)}
|
||||
</span>
|
||||
{isHost && p.id !== me.id && (
|
||||
<span className="pl-actions">
|
||||
{p.online && (
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => send({ t: 'host', userId: p.id })} aria-label={`${p.nickname}에게 방장 넘기기`}>
|
||||
방장
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => send({ t: 'kick', userId: p.id })} aria-label={`${p.nickname} 내보내기`}>
|
||||
내보내기
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
<section className="pool-banner" aria-live="polite">
|
||||
<div className="grow">
|
||||
<h2>
|
||||
조건에 맞는 곡 <span className="mono">{room.pool.playable.toLocaleString()}</span>곡
|
||||
</h2>
|
||||
<p className="small">{configSummary(c, genreName).join(' · ')} · {c.count ? `${c.count}문제` : '무제한'}</p>
|
||||
{room.pool.total > room.pool.playable && (
|
||||
<p className="small" style={{ opacity: 0.85 }}>
|
||||
원곡 확인 중인 곡 {(room.pool.total - room.pool.playable).toLocaleString()}곡은 확인이 끝나면 나와요
|
||||
</p>
|
||||
)}
|
||||
{needArtist && <p className="small">가수를 1명 이상 골라 주세요.</p>}
|
||||
{!needArtist && short && room.pool.playable > 0 && <p className="small">문제 수보다 곡이 적어서 {room.pool.playable}문제만 나와요.</p>}
|
||||
{!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>
|
||||
) : (
|
||||
<button className={`btn btn-lg ${myReady ? 'btn-primary' : 'btn-mustard'}`} onClick={() => send({ t: 'ready', on: !myReady })} aria-pressed={myReady}>
|
||||
{myReady ? '준비 완료 ✓' : '준비'}
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
<ChatPanel lines={chat} pending={pending} meId={me.id} myName={me.nickname} onSend={(t) => socket.chat(t)} />
|
||||
<p className="muted small">게임 진행(노래 재생·채팅 정답)은 다음 업데이트에서 열려요. 지금은 방을 만들고 설정을 맞추면서 대화할 수 있어요.</p>
|
||||
</div>
|
||||
<RoomSettings
|
||||
config={c}
|
||||
editable={isHost && room.status === 'lobby'}
|
||||
meta={meta}
|
||||
artists={room.artists}
|
||||
pool={room.pool}
|
||||
hasPassword={room.hasPassword}
|
||||
onPatch={patch}
|
||||
onPassword={(value) => send({ t: 'password', value })}
|
||||
/>
|
||||
</main>
|
||||
{confirmLeave && (
|
||||
<ConfirmSheet
|
||||
title="방에서 나갈까요?"
|
||||
confirm="나가기"
|
||||
onConfirm={() => {
|
||||
socket.leave();
|
||||
nav('/');
|
||||
}}
|
||||
onClose={() => setConfirmLeave(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function JoinError({ text }: { text: string }) {
|
||||
return (
|
||||
<main className="page narrow stack">
|
||||
<h1>방에 들어갈 수 없어요</h1>
|
||||
<p className="muted">{text}</p>
|
||||
<Link className="btn" to="/">
|
||||
방 목록으로
|
||||
</Link>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -191,6 +191,95 @@ textarea.input { padding: 10px 14px; min-height: 90px; resize: vertical; }
|
||||
.rooms-head { display: flex; align-items: center; gap: 12px; margin: 30px 0 12px; flex-wrap: wrap; }
|
||||
.empty { border: 2px dashed var(--line); border-radius: 16px; padding: 28px; text-align: center; color: var(--text-sub); font-weight: 650; }
|
||||
|
||||
/* home: room cards, code join */
|
||||
.rooms { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 14px; }
|
||||
.room-card { background: var(--surface); border: 1.5px solid var(--line); border-radius: 16px; padding: 16px 18px; display: flex; flex-direction: column; gap: 9px; }
|
||||
.room-card .t { font-weight: 800; font-size: 1.1rem; letter-spacing: -0.02em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.room-card .meta { display: flex; flex-wrap: wrap; gap: 5px; }
|
||||
.code-join { margin-top: 12px; position: relative; }
|
||||
.code-join .input { max-width: 200px; border-color: #1e1b18; background: #fffdf8; color: #1e1b18; }
|
||||
|
||||
/* room (docs/03 대기실) */
|
||||
.roombar { display: flex; align-items: center; gap: 12px; padding: 10px 28px; border-bottom: 1.5px solid var(--line); background: var(--surface-2); flex-wrap: wrap; }
|
||||
.room-title { font-size: 1.25rem; max-width: 40vw; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.room-code { font-weight: 800; letter-spacing: 0.12em; background: var(--surface); border: 2px dashed var(--ink); border-radius: 9px; padding: 3px 10px; font-variant-numeric: tabular-nums; }
|
||||
.room-main { display: grid; grid-template-columns: minmax(0, 1fr) 560px; gap: 22px; padding: 22px 28px; max-width: 1440px; margin: 0 auto; align-items: start; }
|
||||
.players { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 8px; }
|
||||
.pl { display: flex; align-items: center; gap: 9px; padding: 8px 10px; border-radius: 12px; background: var(--surface); border: 1.5px solid var(--line); font-weight: 700; position: relative; min-width: 0; }
|
||||
.pl .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.pl .r { margin-left: auto; flex: none; }
|
||||
.pl.host { border: 2px solid var(--ink); }
|
||||
.pl.off { opacity: 0.55; }
|
||||
.pl-actions { display: none; position: absolute; right: 6px; top: 50%; transform: translateY(-50%); background: var(--surface); border-radius: 8px; box-shadow: 0 0 0 1.5px var(--line); }
|
||||
.pl:hover .pl-actions, .pl:focus-within .pl-actions { display: flex; }
|
||||
.pool-banner { display: flex; align-items: center; gap: 16px; background: #1f6f78; color: #fff; border: 2px solid var(--ink); border-radius: 16px; padding: 18px 20px; box-shadow: 4px 4px 0 var(--ink); }
|
||||
.pool-banner h2 { font-size: 1.3rem; }
|
||||
.pool-banner .btn:not(.btn-mustard):not(.btn-primary) { color: #1e1b18; }
|
||||
.settings { padding: 0; overflow: hidden; }
|
||||
/* chat (docs/06 한 줄 로그; waiting room) */
|
||||
.chat { display: flex; flex-direction: column; gap: 8px; position: relative; padding: 14px 16px; }
|
||||
.chat-log { height: 280px; overflow-y: auto; font-size: 0.95rem; line-height: 1.7; overscroll-behavior: contain; }
|
||||
.chat-line { padding: 0 6px; border-radius: 6px; overflow-wrap: anywhere; }
|
||||
.chat-line b { font-weight: 800; margin-right: 8px; color: hsl(var(--name-h, 200) 55% 38%); }
|
||||
.chat-line.me { background: var(--surface-2); }
|
||||
:root[data-theme='dark'] .chat-line b { color: hsl(var(--name-h, 200) 65% 72%); }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root[data-theme='auto'] .chat-line b { color: hsl(var(--name-h, 200) 65% 72%); }
|
||||
}
|
||||
.chat-line.pending { opacity: 0.55; }
|
||||
.chat-sys { text-align: center; font-size: 0.8rem; color: var(--text-sub); }
|
||||
.chat-new { position: absolute; right: 22px; bottom: 70px; box-shadow: 2px 2px 0 var(--ink); }
|
||||
.chat-input { display: flex; gap: 8px; }
|
||||
.chat-input .input { flex: 1; }
|
||||
.settings .hd { display: flex; align-items: center; justify-content: space-between; padding: 14px 20px; border-bottom: 2px solid var(--ink); background: var(--mustard); color: #1e1b18; }
|
||||
.settings .bd { padding: 4px 20px 18px; }
|
||||
.sec { padding: 14px 0; border-bottom: 1.5px dashed var(--line); }
|
||||
.sec:last-child { border-bottom: 0; }
|
||||
.label { font-size: 0.83rem; font-weight: 700; color: var(--text-sub); margin-bottom: 8px; display: flex; align-items: center; gap: 6px; }
|
||||
.subbox { margin-top: 10px; background: var(--surface-2); border-radius: 12px; padding: 12px 14px; display: flex; flex-direction: column; gap: 10px; }
|
||||
.seg { display: flex; border: 2px solid var(--ink); border-radius: 11px; overflow: hidden; background: var(--surface); }
|
||||
.seg button { flex: 1; min-height: 38px; border: 0; border-right: 1.5px solid var(--ink); background: transparent; font: inherit; font-weight: 700; font-size: 0.88rem; color: var(--ink); padding: 0 6px; cursor: pointer; }
|
||||
.seg button:last-child { border-right: 0; }
|
||||
.seg button.on { background: var(--ink); color: var(--surface); }
|
||||
.seg button:disabled { cursor: default; color: var(--text-sub); }
|
||||
.seg button.on:disabled { color: var(--surface); }
|
||||
.chipgroup { display: grid; grid-template-columns: 40px 1fr; gap: 6px 8px; align-items: start; }
|
||||
.chipgroup .g { font-size: 0.8rem; font-weight: 700; color: var(--text-sub); padding-top: 6px; }
|
||||
.chip:disabled { cursor: default; }
|
||||
.chip.x::after { content: '×'; font-weight: 800; opacity: 0.8; }
|
||||
.toggle { min-height: 36px; padding: 0 12px; border-radius: 9px; border: 2px solid var(--ink); display: inline-flex; align-items: center; gap: 8px; font: inherit; font-weight: 700; font-size: 0.9rem; background: var(--surface); color: var(--ink); cursor: pointer; }
|
||||
.toggle i { width: 26px; height: 15px; border-radius: 9px; background: var(--surface-3); position: relative; display: inline-block; }
|
||||
.toggle i::after { content: ''; position: absolute; top: 2px; left: 2px; width: 11px; height: 11px; border-radius: 50%; background: #fff; border: 1.5px solid var(--ink); box-sizing: border-box; transition: left 0.12s; }
|
||||
.toggle.on { background: var(--primary-soft); }
|
||||
.toggle.on i { background: var(--primary); }
|
||||
.toggle.on i::after { left: 13px; }
|
||||
.toggle:disabled { cursor: default; }
|
||||
.info { width: 16px; height: 16px; border-radius: 50%; border: 1.5px solid var(--text-sub); color: var(--text-sub); font-size: 11px; font-weight: 900; display: inline-flex; align-items: center; justify-content: center; position: relative; top: -4px; cursor: help; }
|
||||
.info:hover::after, .info:focus::after { content: attr(data-tip); position: absolute; left: 22px; top: -6px; background: var(--ink); color: var(--surface); font-size: 0.8rem; font-weight: 600; padding: 7px 10px; border-radius: 8px; white-space: nowrap; z-index: 5; }
|
||||
.diff { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
|
||||
.diff .t { flex: 1; min-width: 160px; }
|
||||
.diff .t b { font-size: 1.1rem; font-weight: 850; letter-spacing: -0.03em; display: block; }
|
||||
.diff .t span { font-size: 0.83rem; color: var(--text-sub); }
|
||||
.stars { display: flex; gap: 1px; }
|
||||
.star-btn { background: none; border: 0; padding: 1px; cursor: pointer; line-height: 0; }
|
||||
.star-btn:disabled { cursor: default; }
|
||||
.tiers { display: flex; gap: 10px; margin-top: 8px; font-size: 0.77rem; color: var(--text-sub); font-weight: 650; flex-wrap: wrap; }
|
||||
.tiers i { display: inline-block; width: 9px; height: 9px; border-radius: 3px; margin-right: 4px; vertical-align: -1px; }
|
||||
.yr { position: relative; height: 62px; margin: 0 10px; }
|
||||
.yr .track { position: absolute; top: 27px; left: 0; right: 0; height: 7px; border-radius: 9px; background: var(--surface-3); }
|
||||
.yr .fill { position: absolute; top: 27px; height: 7px; background: var(--primary); border-radius: 9px; }
|
||||
.yr .bub { position: absolute; margin-left: -24px; width: 48px; text-align: center; background: var(--primary); color: #fff; font-weight: 800; font-size: 0.85rem; border-radius: 7px; padding: 1px 0; pointer-events: none; }
|
||||
.yr .bub.up { top: 0; }
|
||||
.yr .bub.dn { top: 42px; }
|
||||
.yr input[type='range'] { position: absolute; top: 20px; left: -10px; width: calc(100% + 20px); margin: 0; background: none; pointer-events: none; -webkit-appearance: none; appearance: none; height: 21px; }
|
||||
.yr input[type='range']::-webkit-slider-thumb { pointer-events: auto; -webkit-appearance: none; width: 21px; height: 21px; border-radius: 50%; background: #fff; border: 2.5px solid var(--ink); cursor: pointer; }
|
||||
.yr input[type='range']::-moz-range-thumb { pointer-events: auto; width: 17px; height: 17px; border-radius: 50%; background: #fff; border: 2.5px solid var(--ink); cursor: pointer; }
|
||||
.yr input[type='range']:disabled::-webkit-slider-thumb { cursor: default; }
|
||||
.year-sel { flex: 1; text-align: center; font-weight: 800; }
|
||||
.artist-hits { display: flex; flex-direction: column; border: 1.5px solid var(--line); border-radius: 10px; max-height: 220px; overflow-y: auto; background: var(--surface); }
|
||||
.artist-hit { display: flex; justify-content: space-between; align-items: center; gap: 10px; padding: 8px 12px; border: 0; border-bottom: 1px solid var(--line); background: none; font: inherit; color: var(--text); cursor: pointer; text-align: left; }
|
||||
.artist-hit[aria-selected='true'] { background: var(--primary-soft); }
|
||||
|
||||
/* ---------------------------------------------------------------- admin (docs/02: side menu + content, .data-table) */
|
||||
.admin-layout { display: grid; grid-template-columns: 220px 1fr; min-height: calc(100vh - 66px); }
|
||||
.admin-side { background: var(--surface-2); border-right: 2px solid var(--ink); padding: 16px 12px; display: flex; flex-direction: column; gap: 3px; }
|
||||
@@ -248,6 +337,8 @@ input.input.sm { width: 76px; }
|
||||
.admin-side .sep { display: none; }
|
||||
.admin-side a { white-space: nowrap; }
|
||||
.admin-main { padding: 16px; }
|
||||
.room-main { grid-template-columns: 1fr; padding: 16px; }
|
||||
.roombar { padding: 10px 16px; }
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.site-header-inner { padding: 0 12px; gap: 10px; }
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
| 1. 뼈대 ✔ | joke-app에서 auth·세션·관리자·DB·UI 키트 가져오기, 봇 코드 제거, 새 색·아이콘 적용 | 디스코드 로그인 → 아이콘 보이는 동의 화면 → 로그인 성공(e2e), 슈퍼어드민 2명 관리자 접근 |
|
||||
| 2. 배포 먼저 ✔ | Docker, 2974 포트, NPMplus, 인증서 | https://mquiz.tkrmagid.kr 에서 로그인 실제 확인 |
|
||||
| 3. 노래 DB 1차 | sta_songs 803곡 + 노라보세 8,572곡 가져오기, 멜론 정보, 유튜브 Topic 매칭 | 곡 9천+, 유튜브 확정률 90%+, 관리자 노래 목록에서 확인 |
|
||||
| 4. 방·로비 | 방 목록, 방 만들기, 인원 무제한, 방 설정 전체(04 문서) | 설정 변경이 모두에게 즉시 반영, "조건에 맞는 곡 N곡" 정확 |
|
||||
| 4. 방·로비 ✔ | 방 목록, 방 만들기, 인원 무제한, 방 설정 전체(04 문서) | 설정 변경이 모두에게 즉시 반영, "조건에 맞는 곡 N곡" 정확 |
|
||||
| 5. 게임 핵심 | 라운드 진행, 숨긴 유튜브 플레이어 동기화 재생(준비·동시 시작·버퍼링 일시정지), 정답 판정, 점수, 결과, 이어풀기·저장/불러오기 | 3명 동시 e2e로 30문제 끝까지, 정답 판정 단위 테스트 |
|
||||
| 6. 채팅 | 가운데 아래 큰 채팅, 입력 중, 5줄 정답 블록, 단축키 | 체감 지연 없음(로컬 왕복 < 50ms), Ctrl+I/K 동작 |
|
||||
| 7. 힌트·스킵·모드 | 초성 힌트(시간/직접선택 투표), 스킵·다시듣기 투표, 가수노래·가사 모드, 하이라이트 | 모드 3종 e2e |
|
||||
@@ -23,3 +23,4 @@
|
||||
- 2026-10-18 1단계: joke-app에서 로그인(디스코드·게스트)·세션·권한·관리자(대시보드·사이트·사용자·관리자·기록)·DB 마이그레이션을 가져오고 보드게임·컴퓨터 대결 코드는 제외. 새 색·아이콘 적용, WebSocket 연결 + 시계 맞추기(ping). 서버·공용 테스트 20개, 브라우저 e2e 6단계(`e2e/login.e2e.ts`) 통과. 실제 디스코드 동의 화면 확인은 2단계(배포) 후
|
||||
- 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곡 확정)
|
||||
|
||||
@@ -122,3 +122,11 @@
|
||||
- 지움: pip·uv·npm·bun·node-gyp 설치 캐시(도커 빌드 캐시는 기존 `docker-disk-guard.sh`가 같은 기준으로 처리)
|
||||
- 안 지움: `~/.tmp`(파일이 오래됐다고 작업이 끝났다는 보장이 없음), 모델(huggingface 등), 브라우저(playwright), 프로젝트 폴더, DB·백업, 실행 중인 설치 작업이 있으면 그 캐시
|
||||
- Q1이 B안이라 음원 캐시가 없어 이 프로젝트가 쓰는 디스크는 DB 정도(수백 MB)
|
||||
|
||||
## 4단계 확인 (2026-10-18, 사용자: "추천대로 진행")
|
||||
1. 방은 서버 메모리에만 둔다. 서버를 다시 켜면(업데이트) 방이 사라지고, 그 방에 있던 화면에는 "서버가 업데이트되면서 방이 닫혔어요" 안내가 나온다(새로고침해도 같은 안내, 탭별 `sessionStorage`)
|
||||
2. 4단계에 간단한 대기실 채팅을 넣는다: 한 줄 로그, 입장·퇴장·방장 바뀜 시스템 줄, 내 말 먼저 표시, 새로 들어온 사람에게 최근 100줄. 정답 판정·"입력 중"은 6단계
|
||||
3. "조건에 맞는 곡"은 원곡이 확정된 곡만 센다. 원곡 확인 중인 곡 수를 따로 보여 준다. 후보 영상만 있는 곡으로 미리 하기는 하지 않는다(팬 영상 섞임). 수집기가 따로 돌기 때문에 대기실 곡 수는 1분마다 다시 센다
|
||||
4. 게스트도 방을 만들 수 있다. 퀴즈 저장은 디스코드 계정만(5단계)
|
||||
5. 비밀번호 방은 열린 방 목록에 🔒로 보이고 들어갈 때 비밀번호를 묻는다. 비밀번호를 정하기 전에는 잠기지 않는다고 방장에게 안내
|
||||
6. 방 공개 기본값은 공개. 비공개 방은 목록에 안 나오고 코드·링크로만 들어온다
|
||||
|
||||
242
e2e/rooms.e2e.ts
Normal file
242
e2e/rooms.e2e.ts
Normal file
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* Stage 4 E2E (docs/10 4단계): three guests in real browsers.
|
||||
* Room from the home page, join from the open-room list, host settings reach everyone at once with the song count,
|
||||
* ready reset, waiting-room chat, password room (🔒 in the list), kick, server restart notice, phone and dark screens.
|
||||
* Run: bun run build && bun e2e/rooms.e2e.ts (needs /usr/bin/google-chrome)
|
||||
*/
|
||||
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 ?? 4619);
|
||||
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 boot = () => startServer({ config, log: () => {}, staticDir: join(import.meta.dir, '../apps/web/dist'), stopWaitMs: 200 });
|
||||
let app = boot();
|
||||
|
||||
// Catalog: 국내 발라드 3단계 4곡(1곡은 원곡 확인 중), 댄스 3단계 2곡, 발라드 5단계 1곡.
|
||||
{
|
||||
const c = new Catalog(app.db);
|
||||
const add = (title: string, genres: string[], year: number, level: number, matched = true) => {
|
||||
const [id] = c.upsert({ title, artists: [{ name: `가수${title}` }], year, genres, source: 'e2e', ref: title });
|
||||
c.autoLevel(id!, 'all', level);
|
||||
if (matched) app.db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = 'VO88htcm09E' WHERE id = ?").run(id!);
|
||||
};
|
||||
add('발라드1', ['kpop', 'ballad'], 2005, 3);
|
||||
add('발라드2', ['kpop', 'ballad'], 2007, 3);
|
||||
add('발라드3', ['kpop', 'ballad'], 2012, 3);
|
||||
add('발라드확인중', ['kpop', 'ballad'], 2010, 3, false);
|
||||
add('댄스1', ['kpop', 'dance'], 2009, 3);
|
||||
add('댄스2', ['kpop', 'dance'], 2015, 3);
|
||||
add('어려운발라드', ['kpop', 'ballad'], 2001, 5);
|
||||
}
|
||||
|
||||
const browser: Browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
|
||||
const errors: string[] = [];
|
||||
const step = async (name: string, fn: () => Promise<void>) => {
|
||||
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: { 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,
|
||||
});
|
||||
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;
|
||||
}
|
||||
|
||||
const waitPool = (p: Page, n: number) => p.locator('.pool-banner h2', { hasText: `조건에 맞는 곡 ${n}곡` }).waitFor({ timeout: 5000 });
|
||||
|
||||
let failed = false;
|
||||
let code = '';
|
||||
try {
|
||||
const a = await guestPage('방장님');
|
||||
const b = await guestPage('철수');
|
||||
|
||||
await step('게스트가 첫 화면에서 방 만들기 → 대기실, 기본 설정(공개·★3·30문제), 조건에 맞는 곡과 원곡 확인 중 곡 수', async () => {
|
||||
await a.getByRole('button', { name: '+ 방 만들기' }).click();
|
||||
await a.waitForURL(/\/r\/\d{6}$/);
|
||||
code = a.url().slice(-6);
|
||||
await a.getByRole('heading', { name: '방장님님의 방' }).waitFor();
|
||||
await a.getByRole('heading', { name: '방 설정' }).waitFor();
|
||||
await a.getByText('바꾸면 바로 모두에게 보여요').waitFor();
|
||||
// 기본 ★3 전체 장르: 발라드1~3 + 댄스1~2 = 5곡, 원곡 확인 중 1곡
|
||||
await waitPool(a, 5);
|
||||
await a.getByText('원곡 확인 중인 곡 1곡은 확인이 끝나면 나와요').waitFor();
|
||||
expect((await a.getByRole('radiogroup', { name: '방 공개' }).getByRole('radio', { checked: true }).innerText()) === '공개', '기본 공개가 아님');
|
||||
expect(await a.getByRole('radio', { name: /^3단계/ }).getAttribute('aria-checked') === 'true', '기본 3단계 아님');
|
||||
});
|
||||
|
||||
await step('다른 게스트: 열린 방 목록(전체/대기 중)에서 보고 들어가기, 서로 보임, 설정은 읽기 전용', async () => {
|
||||
await b.goto(ORIGIN + '/');
|
||||
const card = b.locator('.room-card', { hasText: '방장님님의 방' });
|
||||
await card.waitFor({ timeout: 8000 });
|
||||
await b.getByRole('button', { name: '진행 중 (중간 참여 가능)' }).click();
|
||||
await card.waitFor({ state: 'detached' });
|
||||
await b.getByRole('button', { name: '대기 중' }).click();
|
||||
await card.getByRole('button', { name: '들어가기' }).click();
|
||||
await b.waitForURL(`**/r/${code}`);
|
||||
await b.getByText('방장만 바꿀 수 있어요').waitFor();
|
||||
await a.locator('.pl', { hasText: '철수' }).waitFor();
|
||||
await b.locator('.pl.host', { hasText: '방장님' }).waitFor();
|
||||
expect(await b.getByRole('radio', { name: /^5단계/ }).isDisabled(), '손님이 난이도를 바꿀 수 있음');
|
||||
});
|
||||
|
||||
await step('방장이 장르·난이도를 바꾸면 손님 화면에 바로 반영, 곡 수도 다시 셈(같은 묶음 또는·다른 묶음 그리고)', async () => {
|
||||
const t0 = performance.now();
|
||||
await a.locator('.chip', { hasText: '발라드' }).click();
|
||||
await waitPool(b, 3); // ★3 발라드: 발라드1~3
|
||||
const ms = Math.round(performance.now() - t0);
|
||||
expect(await b.locator('.chip[aria-pressed="true"]', { hasText: '발라드' }).isVisible(), '손님 화면에 발라드 선택 안 보임');
|
||||
await a.locator('.chip', { hasText: '댄스' }).click();
|
||||
await waitPool(b, 5); // 발라드 또는 댄스
|
||||
await a.getByRole('radio', { name: /^5단계/ }).click();
|
||||
await waitPool(b, 1); // ★5: 어려운발라드
|
||||
await b.getByText('5단계 · 장르 팬 필수곡').waitFor();
|
||||
await a.getByRole('radio', { name: /^3단계/ }).click();
|
||||
await waitPool(b, 5);
|
||||
console.log(` 설정 반영 → 손님 화면 ${ms}ms`);
|
||||
});
|
||||
|
||||
await step('손님 준비 → 방장 화면에 준비, 방장이 설정을 바꾸면 준비가 풀림', async () => {
|
||||
await b.getByRole('button', { name: '준비', exact: true }).click();
|
||||
await a.locator('.pl', { hasText: '철수' }).getByText('준비', { exact: true }).waitFor();
|
||||
await b.getByRole('button', { name: '준비 완료 ✓' }).waitFor();
|
||||
await a.getByRole('radiogroup', { name: '문제 수' }).getByRole('radio', { name: '50' }).click();
|
||||
await b.getByRole('button', { name: '준비', exact: true }).waitFor();
|
||||
await a.locator('.pl', { hasText: '철수' }).getByText('대기', { exact: true }).waitFor();
|
||||
await b.getByText('문제 수보다 곡이 적어서 5문제만 나와요.').waitFor();
|
||||
});
|
||||
|
||||
await step('대기실 채팅: 입장 안내, 서로 보낸 말이 바로 보임, 내 줄 표시', async () => {
|
||||
await a.getByText('— 철수님이 들어왔어요 —').waitFor();
|
||||
await b.getByLabel('채팅 입력').fill('안녕하세요 2000년대 발라드 ㄱㄱ');
|
||||
await b.getByLabel('채팅 입력').press('Enter');
|
||||
await a.locator('.chat-line', { hasText: '안녕하세요 2000년대 발라드 ㄱㄱ' }).waitFor();
|
||||
await b.locator('.chat-line.me:not(.pending)', { hasText: '안녕하세요 2000년대 발라드 ㄱㄱ' }).waitFor();
|
||||
await a.getByLabel('채팅 입력').fill('좋아요');
|
||||
await a.getByRole('button', { name: '보내기' }).click();
|
||||
await b.locator('.chat-line', { hasText: '좋아요' }).waitFor();
|
||||
expect((await a.getByLabel('채팅 입력').inputValue()) === '', '보낸 뒤 입력창이 비지 않음');
|
||||
});
|
||||
|
||||
await step('비밀번호 방: 목록에 🔒, 들어갈 때 비밀번호(틀리면 안내), 맞으면 입장하고 지난 채팅이 보임', async () => {
|
||||
await a.getByRole('radiogroup', { name: '방 공개' }).getByRole('radio', { name: '비밀번호' }).click();
|
||||
await a.getByText('비밀번호를 정해야 잠겨요').waitFor();
|
||||
await a.getByLabel('방 비밀번호').fill('4321');
|
||||
await a.getByRole('button', { name: '정하기' }).click();
|
||||
await a.getByText('비밀번호 있음').waitFor();
|
||||
const c = await guestPage('영희');
|
||||
const card = c.locator('.room-card', { hasText: '방장님님의 방' });
|
||||
await card.getByText('🔒 비밀번호').waitFor({ timeout: 8000 });
|
||||
await card.getByRole('button', { name: '들어가기' }).click();
|
||||
await c.getByRole('heading', { name: '비밀번호가 필요한 방이에요' }).waitFor();
|
||||
await c.getByLabel('방 비밀번호').fill('0000');
|
||||
await c.getByRole('button', { name: '들어가기' }).click();
|
||||
await c.getByText('비밀번호가 틀렸어요.').waitFor();
|
||||
await c.getByLabel('방 비밀번호').fill('4321');
|
||||
await c.getByRole('button', { name: '들어가기' }).click();
|
||||
await c.getByRole('heading', { name: '방장님님의 방' }).waitFor();
|
||||
await c.locator('.chat-line', { hasText: '안녕하세요 2000년대 발라드 ㄱㄱ' }).waitFor();
|
||||
await a.screenshot({ path: join(SHOTS, 'stage4-room-host.png'), fullPage: true });
|
||||
await c.screenshot({ path: join(SHOTS, 'stage4-room-guest.png'), fullPage: true });
|
||||
|
||||
await step('방장이 내보내기 → 첫 화면으로 돌아가며 안내', async () => {
|
||||
const row = a.locator('.pl', { hasText: '영희' });
|
||||
await row.hover();
|
||||
await row.getByRole('button', { name: '영희 내보내기' }).click();
|
||||
await c.waitForURL(`${ORIGIN}/`);
|
||||
await c.getByText('방장이 방에서 내보냈어요.').waitFor();
|
||||
await b.getByText('— 영희님이 내보내졌어요 —').waitFor();
|
||||
await c.context().close();
|
||||
});
|
||||
});
|
||||
|
||||
await step('방장 넘기기 → 손님이 방장이 되어 설정을 바꿀 수 있음', async () => {
|
||||
const row = a.locator('.pl', { hasText: '철수' });
|
||||
await row.hover();
|
||||
await row.getByRole('button', { name: '철수에게 방장 넘기기' }).click();
|
||||
await b.getByText('바꾸면 바로 모두에게 보여요').waitFor();
|
||||
await b.getByText('— 방장이 철수님으로 바뀌었어요 —').waitFor();
|
||||
await b.getByRole('radio', { name: /^4단계/ }).click();
|
||||
await a.getByText('4단계 · 가끔 들어도 아는 곡').waitFor();
|
||||
});
|
||||
|
||||
await step('휴대폰(390px)·다크 화면: 대기실이 가로로 넘치지 않음', async () => {
|
||||
const m = await guestPage('폰손님', { width: 390, height: 844, mobile: true });
|
||||
await m.goto(`${ORIGIN}/r/${code}`);
|
||||
await m.getByRole('heading', { name: '비밀번호가 필요한 방이에요' }).waitFor();
|
||||
await m.getByLabel('방 비밀번호').fill('4321');
|
||||
await m.getByRole('button', { name: '들어가기' }).click();
|
||||
await m.getByRole('heading', { name: '방 설정' }).waitFor();
|
||||
const overflow = await m.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
|
||||
expect(overflow <= 0, `휴대폰 가로 넘침 ${overflow}px`);
|
||||
await m.screenshot({ path: join(SHOTS, 'stage4-room-mobile.png'), fullPage: true });
|
||||
const d = await guestPage('밤손님', { dark: true });
|
||||
await d.goto(`${ORIGIN}/r/${code}`);
|
||||
await d.getByLabel('방 비밀번호').fill('4321');
|
||||
await d.getByRole('button', { name: '들어가기' }).click();
|
||||
await d.locator('.chat-line', { hasText: '좋아요' }).waitFor();
|
||||
await d.screenshot({ path: join(SHOTS, 'stage4-room-dark.png'), fullPage: true });
|
||||
await m.context().close();
|
||||
await d.context().close();
|
||||
});
|
||||
|
||||
await step('서버를 다시 켜면(업데이트) 방이 사라졌다고 안내 — 다시 연결한 화면과 새로고침한 화면 모두', async () => {
|
||||
await app.stop();
|
||||
app = boot();
|
||||
await a.getByText('서버가 업데이트되면서 방이 닫혔어요. 방을 새로 만들어 주세요.').waitFor({ timeout: 15000 });
|
||||
await b.reload();
|
||||
await b.getByText('서버가 업데이트되면서 방이 닫혔어요. 방을 새로 만들어 주세요.').waitFor({ timeout: 15000 });
|
||||
// 다른 사람이 없는 코드로 들어오면 원래 안내
|
||||
const fresh = await browser.newContext({ locale: 'ko-KR' });
|
||||
const f = await fresh.newPage();
|
||||
await f.goto(ORIGIN + '/');
|
||||
await f.getByLabel('게스트 닉네임 (2~12자)').fill('새손님');
|
||||
await f.getByRole('button', { name: '게스트로 시작' }).click();
|
||||
await f.getByRole('button', { name: '내 계정: 새손님' }).waitFor();
|
||||
await f.goto(`${ORIGIN}/r/${code}`);
|
||||
await f.getByText('방을 찾을 수 없어요. 코드를 다시 확인해 주세요.').waitFor();
|
||||
await fresh.close();
|
||||
});
|
||||
|
||||
expect(errors.length === 0, `페이지 오류: ${errors.join(' | ')}`);
|
||||
} catch (e) {
|
||||
if (!(e instanceof Error && e.message)) console.log(e);
|
||||
failed = true;
|
||||
} finally {
|
||||
await browser.close();
|
||||
await app.stop();
|
||||
}
|
||||
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -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"
|
||||
"e2e": "bun run build && bun e2e/login.e2e.ts && bun e2e/rooms.e2e.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "1.4.2",
|
||||
|
||||
@@ -2,3 +2,5 @@ export * from './nickname';
|
||||
export * from './protocol';
|
||||
export * from './types';
|
||||
export * from './match-key';
|
||||
export * from './room-config';
|
||||
export * from './room-config-schema';
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
/** Browser entry without zod: nickname rules and plain types. */
|
||||
export * from './nickname';
|
||||
export * from './types';
|
||||
export * from './room-config';
|
||||
export type { ChatLine, RoomView, RoomPlayerView, ServerMessage } from './protocol';
|
||||
|
||||
@@ -3,20 +3,69 @@
|
||||
* room/game messages are added in later stages.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import { CHAT_MAX } from './types';
|
||||
|
||||
export const PROTOCOL = 1;
|
||||
export const MAX_CLIENT_MESSAGE_BYTES = 16 * 1024;
|
||||
/** Chat line limit (docs/06). */
|
||||
export const CHAT_MAX = 200;
|
||||
|
||||
export const ClientMessage = z.discriminatedUnion('t', [
|
||||
/** Clock sync (docs/12 Q1): the client sends its own clock, the server echoes it with the server clock. */
|
||||
z.object({ t: z.literal('ping'), c: z.number() }),
|
||||
// ---- rooms (docs/04, stage 4)
|
||||
z.object({ t: z.literal('join'), code: z.string().regex(/^\d{6}$/), password: z.string().max(40).optional() }),
|
||||
z.object({ t: z.literal('leave') }),
|
||||
/** Host only: partial RoomConfig; validated with RoomConfigSchema on the server. */
|
||||
z.object({ t: z.literal('config'), patch: z.record(z.string(), z.unknown()) }),
|
||||
/** Host only: room password for visibility 'password' (null clears it). */
|
||||
z.object({ t: z.literal('password'), value: z.string().min(1).max(40).nullable() }),
|
||||
z.object({ t: z.literal('ready'), on: z.boolean() }),
|
||||
z.object({ t: z.literal('kick'), userId: z.string().max(40) }),
|
||||
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() }),
|
||||
]);
|
||||
export type ClientMessage = z.infer<typeof ClientMessage>;
|
||||
|
||||
export interface RoomPlayerView {
|
||||
id: string;
|
||||
nickname: string;
|
||||
avatar: string | null;
|
||||
kind: 'guest' | 'member';
|
||||
ready: boolean;
|
||||
online: boolean;
|
||||
}
|
||||
|
||||
export interface RoomView {
|
||||
code: string;
|
||||
hostId: string;
|
||||
status: 'lobby' | 'playing';
|
||||
config: import('./room-config').RoomConfig;
|
||||
hasPassword: boolean;
|
||||
players: RoomPlayerView[];
|
||||
/** 조건에 맞는 곡: playable now / including songs still waiting for a YouTube match. */
|
||||
pool: { playable: number; total: number };
|
||||
artists: { id: number; name: string }[];
|
||||
}
|
||||
|
||||
/** One chat log line (docs/06 한 줄 로그). `seq` is per room; system lines have no userId. */
|
||||
export interface ChatLine {
|
||||
seq: number;
|
||||
at: number;
|
||||
userId: string | null;
|
||||
nickname: string;
|
||||
text: string;
|
||||
/** Sender's nonce for its optimistic line. */
|
||||
n?: string;
|
||||
}
|
||||
|
||||
export type ServerMessage =
|
||||
| { t: 'welcome'; protocol: number; userId: string; serverNow: number }
|
||||
| { t: 'room'; room: RoomView }
|
||||
| { t: 'left'; code: string; reason: 'leave' | 'kicked' | 'closed' | 'elsewhere' }
|
||||
| { t: 'chat'; code: string; line: ChatLine }
|
||||
/** Recent lines for someone who just joined (or came back). */
|
||||
| { t: 'chatlog'; code: string; lines: ChatLine[] }
|
||||
| { t: 'notice'; text: string }
|
||||
| { t: 'pong'; c: number; s: number }
|
||||
| { t: 'error'; message: string };
|
||||
|
||||
|
||||
38
packages/shared/src/room-config-schema.ts
Normal file
38
packages/shared/src/room-config-schema.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { z } from 'zod';
|
||||
import { COUNTS, DEFAULT_ROOM_CONFIG, HINT_TIMES, LISTEN_SECS, LYRICS_SECS, VOTE_RULES, type RoomConfig } from './room-config';
|
||||
|
||||
const lit = <T extends readonly (string | number)[]>(xs: T) => z.union(xs.map((x) => z.literal(x)) as unknown as [z.ZodLiteral<T[number]>, z.ZodLiteral<T[number]>]);
|
||||
|
||||
export const RoomConfigSchema = z.object({
|
||||
title: z.string().trim().max(40),
|
||||
mode: z.enum(['listen', 'artist', 'lyrics']),
|
||||
listenSec: lit(LISTEN_SECS),
|
||||
startAt: z.enum(['start', 'highlight']),
|
||||
artistIds: z.array(z.number().int().positive()).max(50),
|
||||
lyricsSec: lit(LYRICS_SECS),
|
||||
genres: z.array(z.string().max(30)).max(30),
|
||||
yearFrom: z.number().int().min(1900).max(2100).nullable(),
|
||||
yearTo: z.number().int().min(1900).max(2100).nullable(),
|
||||
level: z.number().int().min(1).max(10),
|
||||
answer: z.enum(['title', 'artist', 'both']),
|
||||
strict: z.object({ space: z.boolean(), number: z.boolean(), symbol: z.boolean() }),
|
||||
hint: z.union([z.literal('none'), z.literal('manual'), lit(HINT_TIMES)]),
|
||||
hintVotes: z.enum(VOTE_RULES.filter((v) => v !== 'none') as ['1', '2', '1/3', '1/2', '2/3', 'all']),
|
||||
skipVotes: z.enum(VOTE_RULES),
|
||||
replayVotes: z.enum(VOTE_RULES),
|
||||
count: lit(COUNTS),
|
||||
visibility: z.enum(['public', 'private', 'password']),
|
||||
});
|
||||
|
||||
/** Partial update from the host; returns the merged config or an error message. */
|
||||
export function applyConfigPatch(cur: RoomConfig, patch: unknown): RoomConfig | string {
|
||||
if (!patch || typeof patch !== 'object') return '잘못된 설정이에요.';
|
||||
const merged = { ...cur, ...(patch as object), strict: { ...cur.strict, ...((patch as { strict?: object }).strict ?? {}) } };
|
||||
const r = RoomConfigSchema.safeParse(merged);
|
||||
if (!r.success) return `설정 값이 올바르지 않아요: ${r.error.issues.map((i) => i.path.join('.')).join(', ')}`;
|
||||
const c = r.data as RoomConfig;
|
||||
if (c.yearFrom && c.yearTo && c.yearFrom > c.yearTo) return '시작 연도가 끝 연도보다 늦어요.';
|
||||
return c;
|
||||
}
|
||||
|
||||
export { DEFAULT_ROOM_CONFIG };
|
||||
110
packages/shared/src/room-config.ts
Normal file
110
packages/shared/src/room-config.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* Room settings (docs/04, docs/12). One schema for server validation, defaults and the web form.
|
||||
* Plain data so lite.ts can share the constants with the browser; the zod schema lives in room-config-schema.ts.
|
||||
*/
|
||||
|
||||
export const MODES = [
|
||||
{ id: 'listen', label: '듣고맞추기', icon: '🎧' },
|
||||
{ id: 'artist', label: '가수노래 맞추기', icon: '🎤' },
|
||||
{ id: 'lyrics', label: '가사보고 맞추기', icon: '📜' },
|
||||
] as const;
|
||||
export type Mode = (typeof MODES)[number]['id'];
|
||||
|
||||
/** 듣고맞출시간: seconds, 0 = 끝까지. */
|
||||
export const LISTEN_SECS = [1, 3, 5, 10, 30, 60, 0] as const;
|
||||
/** 보고맞출시간: seconds, 0 = 무제한. */
|
||||
export const LYRICS_SECS = [30, 60, 90, 120, 150, 0] as const;
|
||||
export const HINT_TIMES = [15, 30, 45, 60] as const;
|
||||
/** 스킵·힌트·다시듣기 인원(이상). 'none' = 불가. */
|
||||
export const VOTE_RULES = ['none', '1', '2', '1/3', '1/2', '2/3', 'all'] as const;
|
||||
export type VoteRule = (typeof VOTE_RULES)[number];
|
||||
/** 문제 수, 0 = 무제한(조건에 맞는 곡 전부). */
|
||||
export const COUNTS = [10, 20, 30, 50, 100, 0] as const;
|
||||
|
||||
export interface RoomConfig {
|
||||
title: string;
|
||||
mode: Mode;
|
||||
listenSec: (typeof LISTEN_SECS)[number];
|
||||
startAt: 'start' | 'highlight';
|
||||
artistIds: number[];
|
||||
lyricsSec: (typeof LYRICS_SECS)[number];
|
||||
/** Empty = 전체. Same group "또는", different groups "그리고" (docs/04, Q9). */
|
||||
genres: string[];
|
||||
yearFrom: number | null;
|
||||
yearTo: number | null;
|
||||
/** Exactly this level (docs/12 Q7). */
|
||||
level: number;
|
||||
answer: 'title' | 'artist' | 'both';
|
||||
/** 정답인식: true = must match that element too (docs/12 Q2). */
|
||||
strict: { space: boolean; number: boolean; symbol: boolean };
|
||||
/** 'none' | seconds | 'manual' (직접선택). */
|
||||
hint: 'none' | (typeof HINT_TIMES)[number] | 'manual';
|
||||
hintVotes: Exclude<VoteRule, 'none'>;
|
||||
skipVotes: VoteRule;
|
||||
replayVotes: VoteRule;
|
||||
count: (typeof COUNTS)[number];
|
||||
visibility: 'public' | 'private' | 'password';
|
||||
}
|
||||
|
||||
export const DEFAULT_ROOM_CONFIG: RoomConfig = {
|
||||
title: '',
|
||||
mode: 'listen',
|
||||
listenSec: 0,
|
||||
startAt: 'start',
|
||||
artistIds: [],
|
||||
lyricsSec: 0,
|
||||
genres: [],
|
||||
yearFrom: null,
|
||||
yearTo: null,
|
||||
level: 3,
|
||||
answer: 'title',
|
||||
strict: { space: true, number: true, symbol: true },
|
||||
hint: 'none',
|
||||
hintVotes: '1/3',
|
||||
skipVotes: '1/3',
|
||||
replayVotes: '1/3',
|
||||
count: 30,
|
||||
visibility: 'public',
|
||||
};
|
||||
|
||||
/** Level names (docs/04 난이도). */
|
||||
export const LEVELS = [
|
||||
['누구나 아는 대표곡', '장르를 전혀 안 듣는 사람도 후렴을 따라 부를 수 있는 곡'],
|
||||
['길거리 단골 노래', '방송, 매장, 길거리에서 워낙 자주 나와서 귀에 익은 곡'],
|
||||
['한 번쯤 들어본 히트곡', '차트 상위권에 올라서 제목은 몰라도 대부분 들어본 곡'],
|
||||
['가끔 들어도 아는 곡', '장르를 자주 안 들어도 차트에서 한 번쯤 접해본 곡'],
|
||||
['장르 팬 필수곡', '크게 뜨진 않았지만 장르 팬이라면 다 아는 곡'],
|
||||
['뒤늦게 알려진 곡', '입소문이나 역주행으로 뒤늦게 조금 알려진 곡'],
|
||||
['고인물이 아끼는 숨은 명곡', '차트 성적은 없지만 고인물들 사이에서 명곡으로 꼽히는 곡'],
|
||||
['찾아 들어야 아는 곡', '어디서도 들을 일이 없어서 직접 찾아 들은 사람만 아는 곡'],
|
||||
['골수 리스너 인증곡', '고인물 중에서도 극소수만 들어본 곡'],
|
||||
['인간 샤잠만 가능', '들어본 사람 자체가 거의 없는 곡'],
|
||||
] as const;
|
||||
|
||||
/** How many votes pass a rule with `n` connected players (rounded up, docs/05 스킵). null = voting off. */
|
||||
export function voteThreshold(rule: VoteRule, n: number): number | null {
|
||||
if (rule === 'none') return null;
|
||||
if (n <= 0) return 1;
|
||||
const need = rule === '1' ? 1 : rule === '2' ? 2 : rule === 'all' ? n : Math.ceil((n * Number(rule[0])) / Number(rule[2]));
|
||||
return Math.max(1, Math.min(n, need));
|
||||
}
|
||||
|
||||
export function voteLabel(rule: VoteRule): string {
|
||||
return { none: '없음', '1': '1명', '2': '2명', '1/3': '1/3명', '1/2': '1/2명', '2/3': '2/3명', all: '전체' }[rule];
|
||||
}
|
||||
|
||||
export function listenLabel(s: number): string {
|
||||
return s === 0 ? '끝까지' : s >= 60 ? `${s / 60}분` : `${s}초`;
|
||||
}
|
||||
|
||||
/** One-line summary for room cards (docs/03 열린 방 목록). */
|
||||
export function configSummary(c: RoomConfig, genreName: (id: string) => string = (x) => x): string[] {
|
||||
const out: string[] = [];
|
||||
if (c.mode === 'lyrics') out.push(`📜 가사 ${c.lyricsSec ? `${c.lyricsSec}초` : '무제한'}`);
|
||||
else out.push(`${c.mode === 'artist' ? '🎤' : '🎧'} ${listenLabel(c.listenSec)}${c.startAt === 'highlight' ? ' · 하이라이트' : ''}`);
|
||||
out.push(c.yearFrom || c.yearTo ? `${c.yearFrom ?? '처음'}~${c.yearTo ?? '지금'}` : '전체 연도');
|
||||
out.push(c.genres.length ? c.genres.map(genreName).join(' · ') : '전체 장르');
|
||||
out.push(`★${c.level}`);
|
||||
if (c.answer !== 'title') out.push(c.answer === 'both' ? '제목+가수' : '가수만');
|
||||
return out;
|
||||
}
|
||||
@@ -6,3 +6,6 @@ export interface PublicUser {
|
||||
}
|
||||
|
||||
export type Role = 'user' | 'admin' | 'superadmin';
|
||||
|
||||
/** Chat line limit (docs/06). */
|
||||
export const CHAT_MAX = 200;
|
||||
|
||||
Reference in New Issue
Block a user