제작된 퀴즈 1~3단계: 관리자 → 퀴즈(목록·추가·곡 목록: 서버 DB/유튜브 검색·주소로 추가, 끌어서·▲▼·번호로 순서, 복수정답은 연결된 DB 곡 별칭에도, 영상 바꾸기 / 설정: 설명·공개방식(비공개·일부공개·전체공개)·문제 순서·재생위치 기본·방 규칙). 저장은 버튼·Ctrl+S로만, 안 저장 시 탭 제목·표시·나가기 확인. 곡마다 처음·하이라이트 위치 편집기(영상+큰 재생바, 끌기·지금 위치로·여기서 듣기·±1초, 자동=0초+DB 하이라이트, 연령제한은 받아 둔 음원). 방 설정 '직접 선택 / 제작된 퀴즈'(검색·비공개/일부공개 먼저), 고르면 퀴즈 설정이 방 설정으로, 듣고맞추기·곡 전부, 곡별 위치로 재생, 플레이 수. 퀴즈당 곡 수·계정당 퀴즈 수 제한(사이트 설정, 기본 무제한). '퀴즈 저장·불러오기'는 '진행 저장·불러오기'로 이름 변경
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -20,6 +20,9 @@ export const SiteSettingsSchema = z.object({
|
||||
roomDefaults: z.record(z.string(), z.unknown()).default({}),
|
||||
/** 잠금: settings hosts cannot change (they stay at the default). */
|
||||
roomLocks: z.array(z.string().max(30)).max(30).default([]),
|
||||
/** 제작된 퀴즈 limits, 0 = 무제한 (the default). */
|
||||
quizMaxSongs: z.number().int().min(0).max(5000).default(0),
|
||||
quizMaxPerUser: z.number().int().min(0).max(1000).default(0),
|
||||
});
|
||||
export type SiteSettings = z.infer<typeof SiteSettingsSchema>;
|
||||
|
||||
|
||||
159
apps/server/src/custom-quiz.test.ts
Normal file
159
apps/server/src/custom-quiz.test.ts
Normal file
@@ -0,0 +1,159 @@
|
||||
/** 제작된 퀴즈: admin editor API, who may pick a quiz, and a game that plays the quiz's songs (in order, own positions). */
|
||||
import { afterEach, expect, test } from 'bun:test';
|
||||
import type { ServerMessage } from '@mq/shared';
|
||||
import { Catalog } from './collector/catalog';
|
||||
import { Client, TEST_SUPERADMINS, api, boot, discordLogin, guest, sleep } from './test-utils';
|
||||
|
||||
type Msg<T extends ServerMessage['t']> = Extract<ServerMessage, { t: T }>;
|
||||
const TIMING = { countdownMs: 40, revealMs: 80, resumeLeadMs: 30, clipGraceMs: 150, lateMs: 150, tickMs: 20 };
|
||||
const fakeDiscord = async (code: string) => ({ id: code, username: 'u', global_name: `회원${code.slice(-2)}`, avatar: null });
|
||||
|
||||
let s: ReturnType<typeof boot>;
|
||||
afterEach(async () => s && (await s.stop()));
|
||||
|
||||
function start() {
|
||||
s = boot({ gameTiming: TIMING, discordExchange: fakeDiscord, checkEmbed: async () => ({ state: 'ok', author: 'IU - Topic', title: 'x' }) }, { DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' });
|
||||
const c = new Catalog(s.db);
|
||||
const [song] = c.upsert({ title: '좋은 날', artists: [{ name: '아이유' }], year: 2010, durationSec: 230, source: 't', ref: '1' });
|
||||
s.db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = 'goodday0001', highlight_sec = 61 WHERE id = ?").run(song!);
|
||||
return song!;
|
||||
}
|
||||
|
||||
const item = (p: Record<string, unknown>) => ({ songId: null, titleAnswers: [], artistAnswers: [], durationSec: 200, auto: true, startSec: null, highlightSec: null, ...p });
|
||||
const settings = (p: Record<string, unknown> = {}) => ({
|
||||
order: 'ordered',
|
||||
listenSec: 0,
|
||||
startAt: 'start',
|
||||
answer: 'title',
|
||||
strict: { space: true, number: true, symbol: true },
|
||||
hint: 'none',
|
||||
hintVotes: '1/3',
|
||||
skipVotes: '1/3',
|
||||
replayVotes: '1/3',
|
||||
revealSec: 5,
|
||||
nextVotes: '1/3',
|
||||
...p,
|
||||
});
|
||||
|
||||
async function adminCookie(id: string) {
|
||||
return (await discordLogin(s.base, id)).cookie!;
|
||||
}
|
||||
|
||||
async function makeQuiz(cookie: string, body: Record<string, unknown>) {
|
||||
const id = (await api(s.base, '/api/admin/quizzes', { method: 'POST', cookie, body: JSON.stringify({ name: body.name ?? '퀴즈' }) })).body.id as number;
|
||||
const r = await api(s.base, `/api/admin/quizzes/${id}`, { method: 'PUT', cookie, body: JSON.stringify({ name: '퀴즈', description: '', visibility: 'private', settings: settings(), items: [], ...body }) });
|
||||
return { id, r };
|
||||
}
|
||||
|
||||
test('editor API: save items with extra answers (into the DB aliases for linked songs), only the maker opens it, limits', async () => {
|
||||
const song = start();
|
||||
const sa = await adminCookie(TEST_SUPERADMINS[0]);
|
||||
const { id, r } = await makeQuiz(sa, {
|
||||
name: '테스트',
|
||||
items: [item({ songId: song, videoId: 'goodday0001', title: '좋은 날', artist: '아이유', titleAnswers: ['Good Day'] }), item({ videoId: 'notindb0001', title: '없는 곡', artist: '누구' })],
|
||||
});
|
||||
expect(r.res.status).toBe(200);
|
||||
expect(r.body.quiz.items.map((i: { title: string }) => i.title)).toEqual(['좋은 날', '없는 곡']);
|
||||
expect(s.db.query<{ alias: string }, [number]>("SELECT alias FROM song_aliases WHERE song_id = ? AND part = 'title'").all(song).map((x) => x.alias)).toEqual(['Good Day']);
|
||||
// reorder + keep ids
|
||||
const items = r.body.quiz.items as { id: number }[];
|
||||
const re = await api(s.base, `/api/admin/quizzes/${id}`, { method: 'PUT', cookie: sa, body: JSON.stringify({ name: '테스트', description: '설명', visibility: 'public', settings: settings(), items: [r.body.quiz.items[1], r.body.quiz.items[0]] }) });
|
||||
expect(re.body.quiz.items.map((i: { id: number }) => i.id)).toEqual([items[1]!.id, items[0]!.id]);
|
||||
// an admin who did not make it cannot open it
|
||||
s.db.query("INSERT INTO admins (discord_id, note, added_by, added_at) VALUES ('900000000000000077', null, null, 0)").run();
|
||||
const other = await adminCookie('900000000000000077');
|
||||
expect((await api(s.base, `/api/admin/quizzes/${id}`, { cookie: other })).res.status).toBe(404);
|
||||
expect((await api(s.base, '/api/admin/quizzes', { cookie: other })).body.quizzes).toEqual([]);
|
||||
// a normal user cannot use the editor at all
|
||||
const g = await guest(s.base, '손님');
|
||||
expect((await api(s.base, '/api/admin/quizzes', { cookie: g.cookie })).res.status).toBe(403);
|
||||
// limits (관리자 → 사이트): songs per quiz
|
||||
s.settings.setSite({ ...s.settings.getSite(), quizMaxSongs: 1 }, 'test');
|
||||
const lim = await api(s.base, `/api/admin/quizzes/${id}`, { method: 'PUT', cookie: sa, body: JSON.stringify({ ...re.body.quiz, settings: settings() }) });
|
||||
expect(lim.res.status).toBe(400);
|
||||
expect(lim.body.error).toContain('1곡까지');
|
||||
});
|
||||
|
||||
test('rooms: 비공개 only for the maker, 일부공개 for admins, 전체공개 for all; picking applies the quiz settings', async () => {
|
||||
start();
|
||||
const sa = await adminCookie(TEST_SUPERADMINS[0]);
|
||||
const priv = await makeQuiz(sa, { name: '비공개 퀴즈', visibility: 'private', items: [item({ videoId: 'aaaaaaaaaaa', title: 'A', artist: 'a' })] });
|
||||
const part = await makeQuiz(sa, { name: '일부 퀴즈', visibility: 'partial', items: [item({ videoId: 'bbbbbbbbbbb', title: 'B', artist: 'b' })] });
|
||||
const pub = await makeQuiz(sa, {
|
||||
name: '전체 퀴즈',
|
||||
visibility: 'public',
|
||||
settings: settings({ answer: 'both', startAt: 'highlight' }),
|
||||
items: [item({ videoId: 'ccccccccccc', title: 'C', artist: 'c' }), item({ videoId: 'ddddddddddd', title: 'D', artist: 'd' })],
|
||||
});
|
||||
const g = await guest(s.base, '손님');
|
||||
const names = async (cookie: string) => (await api(s.base, '/api/made-quizzes', { cookie })).body.quizzes.map((q: { name: string }) => q.name);
|
||||
expect(await names(g.cookie)).toEqual(['전체 퀴즈']);
|
||||
// not-public first for the maker
|
||||
const mine = await names(sa);
|
||||
expect(mine.slice(0, 2).sort()).toEqual(['비공개 퀴즈', '일부 퀴즈']);
|
||||
expect(mine[2]).toBe('전체 퀴즈');
|
||||
s.db.query("INSERT INTO admins (discord_id, note, added_by, added_at) VALUES ('900000000000000077', null, null, 0)").run();
|
||||
const admin2 = await adminCookie('900000000000000077');
|
||||
expect(await names(admin2)).toEqual(['일부 퀴즈', '전체 퀴즈']);
|
||||
// the guest hosts a room: the private quiz is refused, the public one is applied
|
||||
const code: string = (await api(s.base, '/api/rooms', { method: 'POST', cookie: g.cookie, body: '{}' })).body.code;
|
||||
const cl = await new Client(s.base, g.cookie).connect();
|
||||
cl.send({ t: 'join', code });
|
||||
await cl.waitFor((m) => m.t === 'room');
|
||||
cl.send({ t: 'config', patch: { quizId: priv.id } });
|
||||
await cl.waitFor((m) => m.t === 'error' && m.message.includes('고를 수 없어요'));
|
||||
void part;
|
||||
cl.send({ t: 'config', patch: { quizId: pub.id } });
|
||||
const r = (await cl.waitFor((m) => m.t === 'room' && m.room.config.quizId === pub.id)) as Msg<'room'>;
|
||||
expect(r.room.config).toMatchObject({ quizName: '전체 퀴즈', answer: 'both', startAt: 'highlight', mode: 'listen' });
|
||||
expect(r.room.pool).toEqual({ playable: 2, total: 2 });
|
||||
// the host may still change the quiz defaults; other modes are refused while a quiz is chosen
|
||||
cl.send({ t: 'config', patch: { answer: 'title' } });
|
||||
await cl.waitFor((m) => m.t === 'room' && m.room.config.answer === 'title');
|
||||
cl.send({ t: 'config', patch: { mode: 'lyrics' } });
|
||||
await cl.waitFor((m) => m.t === 'error' && m.message.includes('듣고맞추기'));
|
||||
cl.close();
|
||||
});
|
||||
|
||||
test('a quiz game plays every song in order from its own 처음 position and accepts the extra answers', async () => {
|
||||
const song = start();
|
||||
const sa = await adminCookie(TEST_SUPERADMINS[0]);
|
||||
const q = await makeQuiz(sa, {
|
||||
visibility: 'private',
|
||||
items: [
|
||||
item({ videoId: 'first000001', title: '첫 곡', artist: '가수1', auto: false, startSec: 12, highlightSec: 50, titleAnswers: ['First'] }),
|
||||
item({ songId: song, videoId: 'goodday0001', title: '좋은 날', artist: '아이유' }),
|
||||
item({ videoId: 'third000001', title: '셋째', artist: '가수3' }),
|
||||
],
|
||||
});
|
||||
const code: string = (await api(s.base, '/api/rooms', { method: 'POST', cookie: sa, body: '{}' })).body.code;
|
||||
const cl = await new Client(s.base, sa).connect();
|
||||
cl.send({ t: 'join', code });
|
||||
await cl.waitFor((m) => m.t === 'room');
|
||||
cl.send({ t: 'config', patch: { quizId: q.id, count: 10 } });
|
||||
await cl.waitFor((m) => m.t === 'room' && m.room.config.quizId === q.id);
|
||||
// auto-ready like a browser
|
||||
let seen = 0;
|
||||
const iv = setInterval(() => {
|
||||
for (const m of cl.messages.slice(seen)) if (m.t === 'prepare') cl.send({ t: 'audio', n: m.n, ev: 'ready' });
|
||||
seen = cl.messages.length;
|
||||
}, 5);
|
||||
try {
|
||||
cl.send({ t: 'start' });
|
||||
const p1 = (await cl.waitFor((m) => m.t === 'prepare' && m.n === 1)) as Msg<'prepare'>;
|
||||
expect(p1).toMatchObject({ videoId: 'first000001', startSec: 12 });
|
||||
const g1 = (await cl.waitFor((m) => m.t === 'game' && m.game?.n === 1)) as Msg<'game'>;
|
||||
expect(g1.game!.total).toBe(3); // every song, whatever 문제 수 says
|
||||
const play = (await cl.waitFor((m) => m.t === 'play' && m.n === 1)) as Msg<'play'>;
|
||||
await sleep(Math.max(0, play.startAt - Date.now()) + 15);
|
||||
cl.send({ t: 'chat', text: 'First' });
|
||||
await cl.waitFor((m) => m.t === 'answer');
|
||||
// 2nd: the DB song, 자동 → starts at 0 ("처음부터")
|
||||
const p2 = (await cl.waitFor((m) => m.t === 'prepare' && m.n === 2)) as Msg<'prepare'>;
|
||||
expect(p2).toMatchObject({ videoId: 'goodday0001', startSec: 0 });
|
||||
} finally {
|
||||
clearInterval(iv);
|
||||
cl.close();
|
||||
}
|
||||
expect(s.db.query<{ plays: number }, [number]>('SELECT plays FROM custom_quizzes WHERE id = ?').get(q.id)!.plays).toBe(1);
|
||||
});
|
||||
31
apps/server/src/db/migrations/009_custom_quizzes.sql
Normal file
31
apps/server/src/db/migrations/009_custom_quizzes.sql
Normal file
@@ -0,0 +1,31 @@
|
||||
-- 제작된 퀴즈: admin-made quizzes (song list with own answers and start/highlight positions, room defaults, visibility).
|
||||
CREATE TABLE custom_quizzes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
owner_id TEXT NOT NULL REFERENCES users(id),
|
||||
name TEXT NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
visibility TEXT NOT NULL DEFAULT 'private' CHECK (visibility IN ('private','partial','public')),
|
||||
settings_json TEXT NOT NULL DEFAULT '{}',
|
||||
plays INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
deleted_at INTEGER
|
||||
);
|
||||
CREATE INDEX custom_quizzes_owner ON custom_quizzes(owner_id, updated_at);
|
||||
|
||||
CREATE TABLE custom_quiz_items (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
quiz_id INTEGER NOT NULL REFERENCES custom_quizzes(id) ON DELETE CASCADE,
|
||||
pos INTEGER NOT NULL,
|
||||
song_id INTEGER REFERENCES songs(id) ON DELETE SET NULL, -- the server DB song, NULL when not in the DB
|
||||
video_id TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
artist TEXT NOT NULL,
|
||||
title_answers TEXT NOT NULL DEFAULT '[]', -- extra accepted answers (JSON arrays)
|
||||
artist_answers TEXT NOT NULL DEFAULT '[]',
|
||||
duration_sec INTEGER,
|
||||
auto INTEGER NOT NULL DEFAULT 1, -- 1: start 0 + DB highlight; 0: start_sec/highlight_sec
|
||||
start_sec REAL,
|
||||
highlight_sec REAL
|
||||
);
|
||||
CREATE INDEX custom_quiz_items_quiz ON custom_quiz_items(quiz_id, pos);
|
||||
@@ -8,7 +8,7 @@
|
||||
* everyone is paused; it keeps running after the clip ends.
|
||||
*/
|
||||
import { hintText, isCorrect, voteThreshold, type GameHistoryItem, type GamePhase, type GameView, type ServerMessage } from '@mq/shared';
|
||||
import { clipOf, loudnessGain, lyricsCard, mainArtists, markUnplayable, orderSongs, quizSong, type QuizSong } from '../songs/quiz';
|
||||
import { clipOf, loudnessGain, lyricsCard, mainArtists, markUnplayable, orderSongs, type QuizSong } from '../songs/quiz';
|
||||
import { poolIds } from '../songs/pool';
|
||||
import type { Room } from '../rooms/manager';
|
||||
|
||||
@@ -46,6 +46,15 @@ export const newQuiz = (): Quiz => ({ played: [], scores: new Map() });
|
||||
/** Build the song order for a game. Returns an error message when nothing is left. */
|
||||
export function pickSongs(room: Room): number[] | string {
|
||||
const db = room.deps.db;
|
||||
if (room.config.quizId) {
|
||||
// 제작된 퀴즈: every song of it, as listed or shuffled (퀴즈 설정 → 문제 순서)
|
||||
const q = room.deps.quizzes.get(room.config.quizId);
|
||||
if (!q) return '고른 퀴즈를 찾을 수 없어요. 다른 퀴즈를 골라 주세요.';
|
||||
const played = new Set(room.quiz.played);
|
||||
const ids = q.items.map((i) => i.id!).filter((id) => !played.has(id));
|
||||
if (!ids.length) return room.quiz.played.length ? '이 퀴즈의 곡을 모두 풀었어요.' : '이 퀴즈에 곡이 없어요.';
|
||||
return q.settings.order === 'random' ? orderSongs(ids, new Set(), new Map(), false) : ids;
|
||||
}
|
||||
const ids = poolIds(db, room.config, room.quiz.played);
|
||||
if (!ids.length) return room.quiz.played.length ? '조건에 맞는 곡을 모두 풀었어요.' : '조건에 맞는 곡이 없어요. 장르·연도·난이도를 넓혀 보세요.';
|
||||
const recent = new Set(room.recent.flat());
|
||||
@@ -96,7 +105,8 @@ export class Game {
|
||||
private timing: GameTiming,
|
||||
private now: () => number = Date.now,
|
||||
) {
|
||||
const c = room.config.count;
|
||||
// 제작된 퀴즈: every song of it
|
||||
const c = room.config.quizId ? 0 : room.config.count;
|
||||
this.total = c ? Math.min(c, list.length) : list.length;
|
||||
}
|
||||
|
||||
@@ -155,13 +165,14 @@ export class Game {
|
||||
/** Load question `n` (also used when a song is replaced under the same number). */
|
||||
private setup(): void {
|
||||
const c = this.room.config;
|
||||
this.total = c.count ? Math.min(c.count, this.list.length) : this.list.length;
|
||||
const count = c.quizId ? 0 : c.count;
|
||||
this.total = count ? Math.min(count, this.list.length) : this.list.length;
|
||||
let song: QuizSong | null = null;
|
||||
while (this.n <= this.total) {
|
||||
song = quizSong(this.room.deps.db, this.list[this.n - 1]!);
|
||||
song = this.room.loadSong(this.list[this.n - 1]!);
|
||||
if (song && (this.listening ? song.videoId && (!song.ageRestricted || (song.audio && this.room.deps.audio)) : song.lyrics)) break;
|
||||
this.list.splice(this.n - 1, 1);
|
||||
this.total = c.count ? Math.min(c.count, this.list.length) : this.list.length;
|
||||
this.total = count ? Math.min(count, this.list.length) : this.list.length;
|
||||
song = null;
|
||||
}
|
||||
if (!song) return this.finish();
|
||||
@@ -330,9 +341,10 @@ export class Game {
|
||||
this.asked.push(s.id);
|
||||
try {
|
||||
// 통계 (admin): never let a stats write break the game.
|
||||
this.room.deps.db
|
||||
.query('INSERT INTO song_plays (song_id, game_id, played_at, players, winner_id, ms, how) VALUES (?, ?, ?, ?, ?, ?, ?)')
|
||||
.run(s.id, this.gameId, now, Math.max(1, this.active().length), winner, ms, how === 'end' ? 'timeout' : how);
|
||||
if (s.dbSongId !== null)
|
||||
this.room.deps.db
|
||||
.query('INSERT INTO song_plays (song_id, game_id, played_at, players, winner_id, ms, how) VALUES (?, ?, ?, ?, ?, ?, ?)')
|
||||
.run(s.dbSongId, this.gameId, now, Math.max(1, this.active().length), winner, ms, how === 'end' ? 'timeout' : how);
|
||||
} catch {
|
||||
/* stats only */
|
||||
}
|
||||
@@ -425,8 +437,13 @@ export class Game {
|
||||
if (ev === 'error' && (code === 100 || code === 101 || code === 150) && (this.phase === 'prepare' || this.phase === 'play') && this.song) {
|
||||
// The video is gone or may not be embedded: swap the song for everyone, same question number (docs/12 Q1).
|
||||
// 연령제한 곡 also land here (150): the collector checks it and brings the song back with downloaded audio.
|
||||
markUnplayable(this.room.deps.db, this.song.id, code);
|
||||
this.room.deps.onUnplayable?.(this.song.id);
|
||||
// only the DB song's own video is marked (a 제작된 퀴즈 may use another video of it)
|
||||
const db = this.room.deps.db;
|
||||
const dbId = this.song.dbSongId;
|
||||
if (dbId !== null && db.query<{ y: string | null }, [number]>('SELECT youtube_id y FROM songs WHERE id = ?').get(dbId)?.y === this.song.videoId) {
|
||||
markUnplayable(db, dbId, code);
|
||||
this.room.deps.onUnplayable?.(dbId);
|
||||
}
|
||||
this.room.say(null, '이 곡은 재생할 수 없어서 다른 곡으로 바꿨어요');
|
||||
this.toActive({ t: 'pause', code: this.room.code, n: this.n });
|
||||
this.list.splice(this.n - 1, 1);
|
||||
|
||||
@@ -27,7 +27,7 @@ export class SavedQuizzes {
|
||||
|
||||
save(userId: string, name: string, config: RoomConfig, quiz: Quiz, now = Date.now()): number | string {
|
||||
const n = this.db.query<{ n: number }, [string]>('SELECT COUNT(*) n FROM saved_quizzes WHERE user_id = ?').get(userId)!.n;
|
||||
if (n >= SAVE_LIMIT) return `퀴즈는 ${SAVE_LIMIT}개까지 저장할 수 있어요. 안 쓰는 퀴즈를 지워 주세요.`;
|
||||
if (n >= SAVE_LIMIT) return `진행은 ${SAVE_LIMIT}개까지 저장할 수 있어요. 안 쓰는 것을 지워 주세요.`;
|
||||
const scores = [...quiz.scores].map(([id, s]) => ({ id, ...s }));
|
||||
const r = this.db
|
||||
.query<{ id: number }, [string, string, string, string, string, number, number, number]>(
|
||||
|
||||
178
apps/server/src/http/admin-quizzes.ts
Normal file
178
apps/server/src/http/admin-quizzes.ts
Normal file
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* 관리자 → 퀴즈 (제작된 퀴즈): list, create, load, save (by hand), delete, and the song pickers of the editor
|
||||
* (server DB search, YouTube search, a pasted YouTube address). Only the maker (or a superadmin) may open a quiz.
|
||||
*/
|
||||
import type { Context, Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { QuizSaveSchema, songMatchKey, type Role } from '@mq/shared';
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { CustomQuizzes, type QuizLimits } from '../quizzes/store';
|
||||
import type { YtmSong } from '../collector/ytmusic';
|
||||
import { pickSearcher } from '../collector/ytmusic';
|
||||
import { listSongs } from '../songs/store';
|
||||
import { audioFile, type AudioLinks } from '../songs/audio';
|
||||
|
||||
type Env = { Variables: { userId: string | null; role: Role } };
|
||||
|
||||
export interface QuizAdminDeps {
|
||||
db: Database;
|
||||
quizzes: CustomQuizzes;
|
||||
limits: () => QuizLimits;
|
||||
audit: { log(actor: string, action: string, target: string | null, before: unknown, after: unknown): void };
|
||||
/** YouTube Music song search (cookie) with the plain YouTube fallback; injected in tests. */
|
||||
searchYoutube?: (q: string) => Promise<YtmSong[]>;
|
||||
audio?: AudioLinks;
|
||||
videoOf: (url: string) => Promise<{ id: string; author: string; title: string } | string>;
|
||||
onChange?: () => void;
|
||||
}
|
||||
|
||||
let searcher: Promise<(q: string) => Promise<YtmSong[]>> | null = null;
|
||||
function defaultSearch(q: string): Promise<YtmSong[]> {
|
||||
// Picked once per process: with the cookie when it is logged in, else plain YouTube (Topic channels first).
|
||||
searcher ??= pickSearcher(process.env.YT_COOKIE_PATH ?? '/run/secrets/ytm_cookie.txt', () => {}).then((s) => s.searchSongs);
|
||||
return searcher.then((f) => f(q)).catch((e) => {
|
||||
searcher = null;
|
||||
throw e;
|
||||
});
|
||||
}
|
||||
|
||||
export function mountQuizAdmin(app: Hono<Env>, d: QuizAdminDeps, h: { actor: (c: Context<Env>) => string; body: (c: Context<Env>) => Promise<unknown> }) {
|
||||
const mine = (c: Context<Env>) => {
|
||||
const q = d.quizzes.row(Number(c.req.param('id')));
|
||||
if (!q) return null;
|
||||
return q.owner_id === h.actor(c) || c.get('role') === 'superadmin' ? q : null;
|
||||
};
|
||||
|
||||
app.get('/quizzes', (c) => c.json({ quizzes: d.quizzes.listFor(h.actor(c), c.get('role') === 'superadmin' && c.req.query('all') === '1'), limits: d.limits() }));
|
||||
|
||||
app.post('/quizzes', async (c) => {
|
||||
const p = z.object({ name: z.string().trim().min(1).max(60) }).safeParse(await h.body(c));
|
||||
if (!p.success) return c.json({ error: '퀴즈 이름을 1~60자로 넣어 주세요.' }, 400);
|
||||
const id = d.quizzes.create(h.actor(c), p.data.name, d.limits());
|
||||
if (typeof id === 'string') return c.json({ error: id }, 400);
|
||||
d.audit.log(h.actor(c), 'quiz.create', String(id), null, { name: p.data.name });
|
||||
return c.json({ id });
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- song pickers (before /quizzes/:id)
|
||||
/** 서버 노래 검색: title/artist/초성, songs with a confirmed video first. */
|
||||
app.get('/quizzes/pick/db', (c) => {
|
||||
const q = (c.req.query('q') ?? '').trim().slice(0, 100);
|
||||
if (!q) return c.json({ songs: [] });
|
||||
// the whole text (also 초성) as the song list does, then "가수 제목" split into words that each hit title, artist or an alias
|
||||
const ids = new Set((listSongs(d.db, { q, page: 0 }).rows as unknown as { id: number }[]).map((r) => r.id));
|
||||
const words = q.split(/\s+/).filter(Boolean).slice(0, 6);
|
||||
if (words.length > 1) {
|
||||
const like = (w: string) => `%${w.replace(/[%_\\]/g, (m) => '\\' + m)}%`;
|
||||
const cond = words.map(() => "(s.title LIKE ? ESCAPE '\\' OR s.artist LIKE ? ESCAPE '\\' OR EXISTS (SELECT 1 FROM song_aliases a WHERE a.song_id = s.id AND a.alias LIKE ? ESCAPE '\\'))").join(' AND ');
|
||||
for (const r of d.db.query<{ id: number }, string[]>(`SELECT s.id FROM songs s WHERE s.deleted_at IS NULL AND ${cond} LIMIT 60`).all(...words.flatMap((w) => [like(w), like(w), like(w)])))
|
||||
ids.add(r.id);
|
||||
}
|
||||
const one = d.db.query<{ id: number; title: string; artist: string; year: number | null; youtube_id: string | null; youtube_status: string; duration_sec: number | null; highlight_sec: number | null }, [number]>(
|
||||
'SELECT id, title, artist, year, youtube_id, youtube_status, duration_sec, highlight_sec FROM songs WHERE id = ?',
|
||||
);
|
||||
const songs = [...ids]
|
||||
.map((id) => one.get(id)!)
|
||||
.map((r) => ({ id: r.id, title: r.title, artist: r.artist, year: r.year, videoId: r.youtube_id, status: r.youtube_status, durationSec: r.duration_sec, highlightSec: r.highlight_sec }))
|
||||
.sort((a, b) => Number(b.status === 'matched') - Number(a.status === 'matched'))
|
||||
.slice(0, 30);
|
||||
return c.json({ songs });
|
||||
});
|
||||
|
||||
/** 유튜브에서 찾기: YouTube Music songs for "가수 제목"; ones already in the server DB are marked. */
|
||||
app.get('/quizzes/pick/youtube', async (c) => {
|
||||
const q = (c.req.query('q') ?? '').trim().slice(0, 100);
|
||||
if (!q) return c.json({ results: [] });
|
||||
let results: YtmSong[];
|
||||
try {
|
||||
results = await (d.searchYoutube ?? defaultSearch)(q);
|
||||
} catch (e) {
|
||||
return c.json({ error: `유튜브 검색에 실패했어요: ${(e as Error).message}` }, 502);
|
||||
}
|
||||
const byVideo = d.db.query<{ id: number }, [string]>("SELECT id FROM songs WHERE youtube_id = ? AND deleted_at IS NULL ORDER BY youtube_status = 'matched' DESC LIMIT 1");
|
||||
const byKey = d.db.query<{ id: number }, [string]>('SELECT id FROM songs WHERE match_key = ? AND deleted_at IS NULL LIMIT 1');
|
||||
return c.json({
|
||||
results: results.slice(0, 10).map((r) => ({
|
||||
videoId: r.videoId,
|
||||
title: r.title,
|
||||
artist: r.artists,
|
||||
durationSec: r.durationSec,
|
||||
songId: byVideo.get(r.videoId)?.id ?? byKey.get(songMatchKey(r.title, r.artists))?.id ?? null,
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
/** 주소 직접 입력: checks the video can be played on other sites and guesses title/artist from it. */
|
||||
app.post('/quizzes/pick/video', async (c) => {
|
||||
const p = z.object({ url: z.string().max(300) }).safeParse(await h.body(c));
|
||||
if (!p.success) return c.json({ error: '유튜브 주소를 넣어 주세요.' }, 400);
|
||||
const v = await d.videoOf(p.data.url);
|
||||
if (typeof v === 'string') return c.json({ error: v }, 400);
|
||||
const song = d.db
|
||||
.query<{ id: number; title: string; artist: string; duration_sec: number | null }, [string]>(
|
||||
"SELECT id, title, artist, duration_sec FROM songs WHERE youtube_id = ? AND deleted_at IS NULL ORDER BY youtube_status = 'matched' DESC LIMIT 1",
|
||||
)
|
||||
.get(v.id);
|
||||
// "가수 - 제목" titles are common on fan/official uploads; "… - Topic" channels are the artist.
|
||||
const dash = /^(.+?)\s+[-–]\s+(.+)$/.exec(v.title);
|
||||
const guess = song
|
||||
? { title: song.title, artist: song.artist }
|
||||
: v.author.endsWith(' - Topic')
|
||||
? { title: v.title, artist: v.author.replace(/ - Topic$/, '') }
|
||||
: dash
|
||||
? { title: dash[2]!.replace(/\s*[([](official|m\/?v|music video|audio|lyrics?)[^)\]]*[)\]]/gi, '').trim(), artist: dash[1]!.trim() }
|
||||
: { title: v.title, artist: v.author };
|
||||
return c.json({ videoId: v.id, videoTitle: v.title, channel: v.author, songId: song?.id ?? null, durationSec: song?.duration_sec ?? null, ...guess });
|
||||
});
|
||||
|
||||
/** 연령제한 곡: the server's downloaded audio for this video (YouTube refuses to embed it), when there is one. */
|
||||
app.get('/quizzes/pick/audio/:videoId', async (c) => {
|
||||
const v = c.req.param('videoId');
|
||||
if (!/^[\w-]{11}$/.test(v) || !d.audio || !(await Bun.file(audioFile(d.audio.dir, v)).exists())) return c.json({ error: '받아 둔 음원이 없어요.' }, 404);
|
||||
return c.json({ src: d.audio.link(v) });
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- one quiz
|
||||
app.get('/quizzes/:id', (c) => {
|
||||
const q = mine(c);
|
||||
if (!q) return c.json({ error: '퀴즈를 찾을 수 없어요.' }, 404);
|
||||
const detail = d.quizzes.get(q.id)!;
|
||||
// DB facts the editor shows next to each song: aliases that already count, the DB highlight for 자동.
|
||||
const ids = [...new Set(detail.items.map((i) => i.songId).filter((x): x is number => !!x))];
|
||||
const db: Record<number, { titleAliases: string[]; artistAliases: string[]; highlightSec: number | null; durationSec: number | null; videoId: string | null }> = {};
|
||||
for (const id of ids) {
|
||||
const s = d.db.query<{ highlight_sec: number | null; duration_sec: number | null; youtube_id: string | null }, [number]>('SELECT highlight_sec, duration_sec, youtube_id FROM songs WHERE id = ?').get(id);
|
||||
if (!s) continue;
|
||||
const al = d.db.query<{ part: string; alias: string }, [number]>('SELECT part, alias FROM song_aliases WHERE song_id = ?').all(id);
|
||||
db[id] = {
|
||||
titleAliases: al.filter((a) => a.part === 'title').map((a) => a.alias),
|
||||
artistAliases: al.filter((a) => a.part === 'artist').map((a) => a.alias),
|
||||
highlightSec: s.highlight_sec,
|
||||
durationSec: s.duration_sec,
|
||||
videoId: s.youtube_id,
|
||||
};
|
||||
}
|
||||
return c.json({ quiz: detail, db, limits: d.limits() });
|
||||
});
|
||||
|
||||
app.put('/quizzes/:id', async (c) => {
|
||||
const q = mine(c);
|
||||
if (!q) return c.json({ error: '퀴즈를 찾을 수 없어요.' }, 404);
|
||||
const p = QuizSaveSchema.safeParse(await h.body(c));
|
||||
if (!p.success) return c.json({ error: `저장할 내용이 올바르지 않아요: ${p.error.issues.slice(0, 3).map((i) => i.path.join('.')).join(', ')}` }, 400);
|
||||
const saved = d.quizzes.save(q.id, p.data, d.limits());
|
||||
if (typeof saved === 'string') return c.json({ error: saved }, 400);
|
||||
d.audit.log(h.actor(c), 'quiz.save', String(q.id), { name: q.name, songs: q.songs, visibility: q.visibility }, { name: saved.name, songs: saved.items.length, visibility: saved.visibility });
|
||||
d.onChange?.();
|
||||
return c.json({ quiz: saved });
|
||||
});
|
||||
|
||||
app.delete('/quizzes/:id', (c) => {
|
||||
const q = mine(c);
|
||||
if (!q) return c.json({ error: '퀴즈를 찾을 수 없어요.' }, 404);
|
||||
d.quizzes.remove(q.id);
|
||||
d.audit.log(h.actor(c), 'quiz.delete', String(q.id), { name: q.name, songs: q.songs }, null);
|
||||
d.onChange?.();
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
}
|
||||
@@ -10,6 +10,10 @@ import type { Database } from 'bun:sqlite';
|
||||
import { catalogStats, genreList, getSong, listSongs, updateSong } from '../songs/store';
|
||||
import { checkEmbed, type EmbedState } from '../collector/oembed';
|
||||
import { mountCatalogAdmin, songFilterFrom, type CollectControl } from './admin-catalog';
|
||||
import { mountQuizAdmin } from './admin-quizzes';
|
||||
import { CustomQuizzes } from '../quizzes/store';
|
||||
import type { YtmSong } from '../collector/ytmusic';
|
||||
import type { AudioLinks } from '../songs/audio';
|
||||
|
||||
export interface AdminDeps {
|
||||
users: Users;
|
||||
@@ -31,6 +35,10 @@ export interface AdminDeps {
|
||||
adminClose(code: string): boolean;
|
||||
};
|
||||
collect?: CollectControl;
|
||||
/** 퀴즈 편집기의 유튜브 검색 (tests inject a fake). */
|
||||
searchYoutube?: (q: string) => Promise<YtmSong[]>;
|
||||
/** 연령제한 곡's downloaded audio, for the quiz editor's position bar. */
|
||||
audio?: AudioLinks;
|
||||
}
|
||||
|
||||
type Env = { Variables: { userId: string | null; role: Role } };
|
||||
@@ -102,6 +110,29 @@ export function createAdminApp(d: AdminDeps) {
|
||||
app.get('/catalog', (c) => c.json(catalogStats(d.db)));
|
||||
app.get('/genres', (c) => c.json({ genres: genreList(d.db) }));
|
||||
// Static paths (/songs/export, /songs/bulk …) before /songs/:id.
|
||||
const videoOf = async (url: string): Promise<{ id: string; author: string; title: string } | string> => {
|
||||
const id = parseVideoId(url);
|
||||
if (!id) return '유튜브 주소를 알아볼 수 없어요. https://youtu.be/… 형식으로 넣어 주세요.';
|
||||
const e = await (d.checkEmbed ?? checkEmbed)(id);
|
||||
if (e.state === 'noembed') return '이 영상은 다른 사이트에서 재생할 수 없게 막혀 있어요(퍼가기 금지). 다른 영상을 골라 주세요.';
|
||||
if (e.state === 'dead') return '없는 영상이에요.';
|
||||
if (e.state === 'error') return '유튜브 확인에 실패했어요. 잠시 후 다시 시도해 주세요.';
|
||||
return { id, author: e.author, title: e.title };
|
||||
};
|
||||
// 퀴즈 (제작된 퀴즈)
|
||||
mountQuizAdmin(
|
||||
app,
|
||||
{
|
||||
db: d.db,
|
||||
quizzes: new CustomQuizzes(d.db),
|
||||
limits: () => ({ maxSongs: d.settings.getSite().quizMaxSongs, maxPerUser: d.settings.getSite().quizMaxPerUser }),
|
||||
audit: d.audit,
|
||||
searchYoutube: d.searchYoutube,
|
||||
audio: d.audio,
|
||||
videoOf,
|
||||
},
|
||||
{ actor, body },
|
||||
);
|
||||
mountCatalogAdmin(app, d, {
|
||||
actor,
|
||||
body,
|
||||
|
||||
@@ -264,6 +264,14 @@ export function createHttpApp(d: HttpDeps) {
|
||||
return c.json(countPool(d.db, cfg));
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ 제작된 퀴즈: what this player may pick in a room
|
||||
app.get('/api/made-quizzes', (c) => {
|
||||
const u = userOf(c);
|
||||
if (!u) return c.json({ error: '로그인이 필요해요.' }, 401);
|
||||
const q = (c.req.query('q') ?? '').trim().slice(0, 60);
|
||||
return c.json({ quizzes: d.rooms.quizzes.forRoom(u, d.roles.roleOf(u), q) });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ saved quizzes (docs/12 Q8)
|
||||
app.get('/api/quizzes', (c) => {
|
||||
const u = userOf(c);
|
||||
@@ -274,10 +282,10 @@ export function createHttpApp(d: HttpDeps) {
|
||||
app.delete('/api/quizzes/:id', (c) => {
|
||||
const u = userOf(c);
|
||||
if (!u) return c.json({ error: '로그인이 필요해요.' }, 401);
|
||||
return d.rooms.saved.remove(u, Number(c.req.param('id'))) ? c.json({ ok: true }) : c.json({ error: '저장한 퀴즈를 찾을 수 없어요.' }, 404);
|
||||
return d.rooms.saved.remove(u, Number(c.req.param('id'))) ? c.json({ ok: true }) : c.json({ error: '저장한 진행을 찾을 수 없어요.' }, 404);
|
||||
});
|
||||
|
||||
app.route('/api/admin', createAdminApp({ ...d.admin, users: d.users, sessions: d.sessions, roles: d.roles, settings: d.settings }));
|
||||
app.route('/api/admin', createAdminApp({ ...d.admin, users: d.users, sessions: d.sessions, roles: d.roles, settings: d.settings, audio: d.audio }));
|
||||
|
||||
app.all('/api/*', (c) => c.json({ error: '없는 주소예요.' }, 404));
|
||||
|
||||
|
||||
204
apps/server/src/quizzes/store.ts
Normal file
204
apps/server/src/quizzes/store.ts
Normal file
@@ -0,0 +1,204 @@
|
||||
/**
|
||||
* 제작된 퀴즈 store: admins make quizzes (관리자 → 퀴즈), rooms pick them (방 설정 → 제작된 퀴즈).
|
||||
* Saving is all at once (the editor saves by hand): name, settings, visibility and the whole song list.
|
||||
*/
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { parseQuizSettings, type QuizDetail, type QuizItem, type QuizSave, type QuizSummary, type QuizVisibility, type Role } from '@mq/shared';
|
||||
|
||||
interface QuizRow {
|
||||
id: number;
|
||||
owner_id: string;
|
||||
owner_name: string | null;
|
||||
name: string;
|
||||
description: string;
|
||||
visibility: QuizVisibility;
|
||||
settings_json: string;
|
||||
plays: number;
|
||||
songs: number;
|
||||
updated_at: number;
|
||||
}
|
||||
|
||||
interface ItemRow {
|
||||
id: number;
|
||||
song_id: number | null;
|
||||
video_id: string;
|
||||
title: string;
|
||||
artist: string;
|
||||
title_answers: string;
|
||||
artist_answers: string;
|
||||
duration_sec: number | null;
|
||||
auto: number;
|
||||
start_sec: number | null;
|
||||
highlight_sec: number | null;
|
||||
}
|
||||
|
||||
const SELECT = `SELECT q.id, q.owner_id, u.nickname owner_name, q.name, q.description, q.visibility, q.settings_json, q.plays, q.updated_at,
|
||||
(SELECT COUNT(*) FROM custom_quiz_items i WHERE i.quiz_id = q.id) songs
|
||||
FROM custom_quizzes q LEFT JOIN users u ON u.id = q.owner_id`;
|
||||
|
||||
export interface QuizLimits {
|
||||
/** 0 = 무제한. */
|
||||
maxSongs: number;
|
||||
maxPerUser: number;
|
||||
}
|
||||
|
||||
const summary = (r: QuizRow): QuizSummary => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
description: r.description,
|
||||
visibility: r.visibility,
|
||||
songs: r.songs,
|
||||
plays: r.plays,
|
||||
ownerId: r.owner_id,
|
||||
ownerName: r.owner_name ?? '?',
|
||||
updatedAt: r.updated_at,
|
||||
});
|
||||
|
||||
const item = (r: ItemRow): QuizItem => ({
|
||||
id: r.id,
|
||||
songId: r.song_id,
|
||||
videoId: r.video_id,
|
||||
title: r.title,
|
||||
artist: r.artist,
|
||||
titleAnswers: JSON.parse(r.title_answers) as string[],
|
||||
artistAnswers: JSON.parse(r.artist_answers) as string[],
|
||||
durationSec: r.duration_sec,
|
||||
auto: !!r.auto,
|
||||
startSec: r.start_sec,
|
||||
highlightSec: r.highlight_sec,
|
||||
});
|
||||
|
||||
/** Who may pick a quiz for a room: 비공개 the maker, 일부공개 the maker and admins, 전체공개 everyone. */
|
||||
export function canPlay(q: { owner_id?: string; ownerId?: string; visibility: QuizVisibility }, userId: string, role: Role): boolean {
|
||||
const owner = q.ownerId ?? q.owner_id;
|
||||
if (q.visibility === 'public') return true;
|
||||
if (owner === userId) return true;
|
||||
return q.visibility === 'partial' && role !== 'user';
|
||||
}
|
||||
|
||||
export class CustomQuizzes {
|
||||
constructor(private db: Database) {}
|
||||
|
||||
/** 관리자 → 퀴즈: the maker's own quizzes (a superadmin sees everyone's). */
|
||||
listFor(userId: string, all = false): QuizSummary[] {
|
||||
return this.db
|
||||
.query<QuizRow, string[]>(`${SELECT} WHERE q.deleted_at IS NULL ${all ? '' : 'AND q.owner_id = ?'} ORDER BY q.updated_at DESC`)
|
||||
.all(...(all ? [] : [userId]))
|
||||
.map(summary);
|
||||
}
|
||||
|
||||
create(ownerId: string, name: string, limits: QuizLimits, now = Date.now()): number | string {
|
||||
if (limits.maxPerUser) {
|
||||
const n = this.db.query<{ n: number }, [string]>('SELECT COUNT(*) n FROM custom_quizzes WHERE owner_id = ? AND deleted_at IS NULL').get(ownerId)!.n;
|
||||
if (n >= limits.maxPerUser) return `퀴즈는 한 계정에 ${limits.maxPerUser}개까지 만들 수 있어요.`;
|
||||
}
|
||||
return this.db
|
||||
.query<{ id: number }, [string, string, number, number]>(
|
||||
"INSERT INTO custom_quizzes (owner_id, name, visibility, settings_json, created_at, updated_at) VALUES (?, ?, 'private', '{}', ?, ?) RETURNING id",
|
||||
)
|
||||
.get(ownerId, name, now, now)!.id;
|
||||
}
|
||||
|
||||
row(id: number): QuizRow | null {
|
||||
return this.db.query<QuizRow, [number]>(`${SELECT} WHERE q.id = ? AND q.deleted_at IS NULL`).get(id);
|
||||
}
|
||||
|
||||
get(id: number): QuizDetail | null {
|
||||
const r = this.row(id);
|
||||
if (!r) return null;
|
||||
return { ...summary(r), settings: parseQuizSettings(JSON.parse(r.settings_json)), items: this.items(id) };
|
||||
}
|
||||
|
||||
items(id: number): QuizItem[] {
|
||||
return this.db
|
||||
.query<ItemRow, [number]>(
|
||||
'SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? ORDER BY pos, id',
|
||||
)
|
||||
.all(id)
|
||||
.map(item);
|
||||
}
|
||||
|
||||
item(quizId: number, itemId: number): QuizItem | null {
|
||||
const r = this.db
|
||||
.query<ItemRow, [number, number]>(
|
||||
'SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? AND id = ?',
|
||||
)
|
||||
.get(quizId, itemId);
|
||||
return r ? item(r) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves everything the editor holds. Items keep their id (sent back), new ones get one; missing ones are removed.
|
||||
* Extra answers of songs that are in the server DB also become that song's aliases (source 'quiz').
|
||||
* Returns the saved quiz or an error message.
|
||||
*/
|
||||
save(id: number, data: QuizSave, limits: QuizLimits, now = Date.now()): QuizDetail | string {
|
||||
if (limits.maxSongs && data.items.length > limits.maxSongs) return `퀴즈 하나에는 곡을 ${limits.maxSongs}곡까지 넣을 수 있어요.`;
|
||||
const existing = new Set(this.db.query<{ id: number }, [number]>('SELECT id FROM custom_quiz_items WHERE quiz_id = ?').all(id).map((r) => r.id));
|
||||
const songExists = this.db.query<{ n: number }, [number]>('SELECT COUNT(*) n FROM songs WHERE id = ? AND deleted_at IS NULL');
|
||||
this.db.transaction(() => {
|
||||
this.db
|
||||
.query('UPDATE custom_quizzes SET name = ?, description = ?, visibility = ?, settings_json = ?, updated_at = ? WHERE id = ?')
|
||||
.run(data.name, data.description, data.visibility, JSON.stringify(data.settings), now, id);
|
||||
const keep = new Set<number>();
|
||||
const ins = this.db.query(
|
||||
`INSERT INTO custom_quiz_items (quiz_id, pos, song_id, video_id, title, artist, title_answers, artist_answers, duration_sec, auto, start_sec, highlight_sec)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
);
|
||||
const upd = this.db.query(
|
||||
`UPDATE custom_quiz_items SET pos = ?, song_id = ?, video_id = ?, title = ?, artist = ?, title_answers = ?, artist_answers = ?, duration_sec = ?, auto = ?,
|
||||
start_sec = ?, highlight_sec = ? WHERE id = ? AND quiz_id = ?`,
|
||||
);
|
||||
const alias = this.db.query("INSERT OR IGNORE INTO song_aliases (song_id, part, alias, source) VALUES (?, ?, ?, 'quiz')");
|
||||
for (const [pos, it] of data.items.entries()) {
|
||||
const songId = it.songId && songExists.get(it.songId)!.n ? it.songId : null;
|
||||
const titleAnswers = [...new Set(it.titleAnswers)];
|
||||
const artistAnswers = [...new Set(it.artistAnswers)];
|
||||
const args = [
|
||||
songId,
|
||||
it.videoId,
|
||||
it.title,
|
||||
it.artist,
|
||||
JSON.stringify(titleAnswers),
|
||||
JSON.stringify(artistAnswers),
|
||||
it.durationSec,
|
||||
it.auto ? 1 : 0,
|
||||
it.auto ? null : it.startSec,
|
||||
it.auto ? null : it.highlightSec,
|
||||
] as const;
|
||||
if (it.id && existing.has(it.id)) {
|
||||
upd.run(pos, ...args, it.id, id);
|
||||
keep.add(it.id);
|
||||
} else ins.run(id, pos, ...args);
|
||||
if (songId) {
|
||||
for (const a of titleAnswers) alias.run(songId, 'title', a);
|
||||
for (const a of artistAnswers) alias.run(songId, 'artist', a);
|
||||
}
|
||||
}
|
||||
for (const old of existing) if (!keep.has(old)) this.db.query('DELETE FROM custom_quiz_items WHERE id = ?').run(old);
|
||||
})();
|
||||
return this.get(id)!;
|
||||
}
|
||||
|
||||
remove(id: number, now = Date.now()): boolean {
|
||||
return this.db.query('UPDATE custom_quizzes SET deleted_at = ? WHERE id = ? AND deleted_at IS NULL').run(now, id).changes > 0;
|
||||
}
|
||||
|
||||
/** 방 설정 → 제작된 퀴즈: what this player may pick, not-public ones first (marked), then by plays. */
|
||||
forRoom(userId: string, role: Role, q = ''): QuizSummary[] {
|
||||
const like = `%${q.replace(/[%_\\]/g, (m) => '\\' + m)}%`;
|
||||
return this.db
|
||||
.query<QuizRow, [string, string, string]>(
|
||||
`${SELECT} WHERE q.deleted_at IS NULL AND (q.name LIKE ? ESCAPE '\\' OR q.description LIKE ? ESCAPE '\\')
|
||||
AND EXISTS (SELECT 1 FROM custom_quiz_items i WHERE i.quiz_id = q.id)
|
||||
ORDER BY q.visibility = 'public', q.owner_id <> ?, q.plays DESC, q.updated_at DESC LIMIT 500`,
|
||||
)
|
||||
.all(like, like, userId)
|
||||
.filter((r) => canPlay(r, userId, role))
|
||||
.map(summary);
|
||||
}
|
||||
|
||||
countPlay(id: number): void {
|
||||
this.db.query('UPDATE custom_quizzes SET plays = plays + 1 WHERE id = ?').run(id);
|
||||
}
|
||||
}
|
||||
@@ -4,11 +4,13 @@
|
||||
*/
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import type { ServerWebSocket } from 'bun';
|
||||
import { DEFAULT_ROOM_CONFIG, applyConfigPatch, configSummary, type ChatLine, type RoomConfig, type RoomView, type ServerMessage } from '@mq/shared';
|
||||
import { DEFAULT_ROOM_CONFIG, QUIZ_ROOM_KEYS, applyConfigPatch, configSummary, type ChatLine, type Role, type RoomConfig, type RoomView, type ServerMessage } from '@mq/shared';
|
||||
import { DEFAULT_TIMING, Game, newQuiz, pickSongs, type GameTiming, type Quiz } from '../game/engine';
|
||||
import { SavedQuizzes } from '../game/saved';
|
||||
import { artistsByIds, countPool } from '../songs/pool';
|
||||
import type { AudioLinks } from '../songs/audio';
|
||||
import { quizItemSong, quizSong, type QuizSong } from '../songs/quiz';
|
||||
import { CustomQuizzes, canPlay } from '../quizzes/store';
|
||||
import type { WsData } from '../ws/gateway';
|
||||
|
||||
/** Back within this long after a disconnect: keeps the place (and later the score). */
|
||||
@@ -54,7 +56,7 @@ export class Room {
|
||||
readonly code: string,
|
||||
hostId: string,
|
||||
config: RoomConfig,
|
||||
readonly deps: { db: Database; user: PublicUserLookup; limitSec?: () => number; audio?: AudioLinks; onUnplayable?: (songId: number) => void },
|
||||
readonly deps: { db: Database; user: PublicUserLookup; quizzes: CustomQuizzes; limitSec?: () => number; audio?: AudioLinks; onUnplayable?: (songId: number) => void },
|
||||
) {
|
||||
this.hostId = hostId;
|
||||
this.config = config;
|
||||
@@ -62,7 +64,16 @@ export class Room {
|
||||
}
|
||||
|
||||
recount(): void {
|
||||
this.pool = countPool(this.deps.db, this.config);
|
||||
if (this.config.quizId) {
|
||||
// 제작된 퀴즈: every song of it
|
||||
const n = this.deps.db.query<{ n: number }, [number]>('SELECT COUNT(*) n FROM custom_quiz_items WHERE quiz_id = ?').get(this.config.quizId)!.n;
|
||||
this.pool = { playable: n, total: n };
|
||||
} else this.pool = countPool(this.deps.db, this.config);
|
||||
}
|
||||
|
||||
/** A question's song: a DB song, or an item of the room's 제작된 퀴즈. */
|
||||
loadSong(id: number): QuizSong | null {
|
||||
return this.config.quizId ? quizItemSong(this.deps.db, this.config.quizId, id) : quizSong(this.deps.db, id);
|
||||
}
|
||||
|
||||
online(): string[] {
|
||||
@@ -148,7 +159,9 @@ export class RoomManager {
|
||||
private where = new Map<string, string>();
|
||||
|
||||
readonly saved: SavedQuizzes;
|
||||
readonly quizzes: CustomQuizzes;
|
||||
private timing: GameTiming;
|
||||
private roomDeps: Room['deps'];
|
||||
|
||||
constructor(
|
||||
private deps: {
|
||||
@@ -165,9 +178,13 @@ export class RoomManager {
|
||||
audio?: AudioLinks;
|
||||
/** A player could not play a song (deleted / not embeddable / 연령제한): the collector looks at it. */
|
||||
onUnplayable?: (songId: number) => void;
|
||||
/** Who may pick which 제작된 퀴즈 (비공개 / 일부공개 / 전체공개). */
|
||||
role?: (userId: string) => Role;
|
||||
},
|
||||
) {
|
||||
this.saved = new SavedQuizzes(deps.db);
|
||||
this.quizzes = new CustomQuizzes(deps.db);
|
||||
this.roomDeps = { ...deps, quizzes: this.quizzes };
|
||||
this.timing = { ...DEFAULT_TIMING, ...deps.timing };
|
||||
}
|
||||
|
||||
@@ -193,10 +210,11 @@ export class RoomManager {
|
||||
create(hostId: string, init: Partial<RoomConfig> = {}): Room | string {
|
||||
const nick = this.deps.user(hostId)?.nickname ?? '';
|
||||
const { base, locks } = this.policy();
|
||||
const wanted = Object.fromEntries(Object.entries(init).filter(([k]) => !locks.has(k)));
|
||||
// a 제작된 퀴즈 is picked in the room (access checked there), not at creation
|
||||
const wanted = Object.fromEntries(Object.entries(init).filter(([k]) => !locks.has(k) && k !== 'quizId' && k !== 'quizName'));
|
||||
const cfg = applyConfigPatch({ ...base, title: `${nick}님의 방`.slice(0, 40) }, wanted);
|
||||
if (typeof cfg === 'string') return cfg;
|
||||
const room = new Room(this.newCode(), hostId, cfg, this.deps);
|
||||
const room = new Room(this.newCode(), hostId, cfg, this.roomDeps);
|
||||
// Empty until someone joins: a room created and never entered expires like any empty room.
|
||||
room.emptySince = Date.now();
|
||||
this.rooms.set(room.code, room);
|
||||
@@ -324,9 +342,25 @@ export class RoomManager {
|
||||
return this.hostAction(ws, (room) => {
|
||||
const { locks } = this.policy();
|
||||
if (Object.keys(patch).some((k) => locks.has(k))) return '관리자가 고정한 설정이라 바꿀 수 없어요.';
|
||||
const next = applyConfigPatch(room.config, patch);
|
||||
const { quizName: _, ...p } = patch;
|
||||
let merged: Record<string, unknown> = p;
|
||||
// songs asked so far are quiz items or DB songs: switching between them starts over
|
||||
const switching = p.quizId !== undefined && p.quizId !== room.config.quizId;
|
||||
if (switching) {
|
||||
if (p.quizId === null) merged = { ...p, quizName: '' };
|
||||
else {
|
||||
const q = this.quizzes.row(Number(p.quizId));
|
||||
if (!q || !canPlay(q, ws.data.userId, this.deps.role?.(ws.data.userId) ?? 'user')) return '이 퀴즈는 고를 수 없어요.';
|
||||
// the quiz's own settings become the room's (except what the site locked); a new quiz starts from its first song
|
||||
const s = this.quizzes.get(q.id)!.settings;
|
||||
const defaults = Object.fromEntries(QUIZ_ROOM_KEYS.filter((k) => !locks.has(k)).map((k) => [k, s[k]]));
|
||||
merged = { ...defaults, ...p, mode: 'listen', quizName: q.name };
|
||||
}
|
||||
}
|
||||
const next = applyConfigPatch(room.config, merged);
|
||||
if (typeof next === 'string') return next;
|
||||
room.config = next;
|
||||
if (switching) room.quiz = newQuiz();
|
||||
// Settings changed: everyone confirms again (joke-app behaviour, docs/04).
|
||||
for (const p of room.players.values()) p.ready = false;
|
||||
room.recount();
|
||||
@@ -402,6 +436,7 @@ export class RoomManager {
|
||||
room.status = 'playing';
|
||||
for (const p of room.players.values()) p.ready = false;
|
||||
room.game = new Game(room, list, this.timing);
|
||||
if (room.config.quizId) this.quizzes.countPlay(room.config.quizId);
|
||||
room.broadcast();
|
||||
room.game.start();
|
||||
this.deps.log?.('game started', { code: room.code, songs: list.length, total: room.game.total });
|
||||
@@ -479,14 +514,14 @@ export class RoomManager {
|
||||
const room = this.inRoom(ws);
|
||||
if (!room) return '방에 들어가 있지 않아요.';
|
||||
if (room.hostId !== ws.data.userId) return '방장만 저장할 수 있어요.';
|
||||
if (this.deps.user(ws.data.userId)?.kind !== 'member') return '퀴즈 저장은 디스코드로 로그인하면 쓸 수 있어요.';
|
||||
if (this.deps.user(ws.data.userId)?.kind !== 'member') return '진행 저장은 디스코드로 로그인하면 쓸 수 있어요.';
|
||||
const g = room.game;
|
||||
if (g && g.phase !== 'result' && !g.paused) return '게임을 잠시 멈춘 뒤나 끝난 뒤에 저장할 수 있어요.';
|
||||
if (!room.quiz.played.length) return '아직 푼 문제가 없어요.';
|
||||
const id = this.saved.save(ws.data.userId, name, room.config, room.quiz);
|
||||
if (typeof id === 'string') return id;
|
||||
ws.send(JSON.stringify({ t: 'saved', id, name } satisfies ServerMessage));
|
||||
room.say(null, `퀴즈를 "${name}"(으)로 저장했어요 · ${room.quiz.played.length}문제`);
|
||||
room.say(null, `진행 상황을 "${name}"(으)로 저장했어요 · ${room.quiz.played.length}문제`);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -494,13 +529,13 @@ export class RoomManager {
|
||||
load(ws: ServerWebSocket<WsData>, id: number): string | null {
|
||||
return this.hostAction(ws, (room) => {
|
||||
const q = this.saved.load(ws.data.userId, id);
|
||||
if (!q) return '저장한 퀴즈를 찾을 수 없어요.';
|
||||
if (!q) return '저장한 진행을 찾을 수 없어요.';
|
||||
room.config = { ...q.config, title: room.config.title, visibility: room.config.visibility };
|
||||
room.quiz = q.quiz;
|
||||
for (const p of room.players.values()) p.ready = false;
|
||||
room.recount();
|
||||
room.broadcast();
|
||||
room.say(null, `"${q.name}" 퀴즈를 불러왔어요 · 지금까지 ${q.quiz.played.length}문제, 시작하면 이어서 나와요`);
|
||||
room.say(null, `"${q.name}" 진행을 불러왔어요 · 지금까지 ${q.quiz.played.length}문제, 시작하면 이어서 나와요`);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -69,6 +69,7 @@ export function startServer(opts: StartOptions) {
|
||||
timing: opts.gameTiming,
|
||||
roomPolicy: () => ({ defaults: settings.getSite().roomDefaults, locks: settings.getSite().roomLocks }),
|
||||
audio,
|
||||
role: (id) => roles.roleOf(id),
|
||||
// A player could not play a song: maybe 연령제한 — the collector checks it and downloads its audio (one run at a time).
|
||||
onUnplayable: (songId) => {
|
||||
const err = collect.run('age-audio');
|
||||
|
||||
@@ -5,7 +5,12 @@ import type { Database } from 'bun:sqlite';
|
||||
import type { RoomConfig } from '@mq/shared';
|
||||
|
||||
export interface QuizSong {
|
||||
/** Song id, or the item id in a 제작된 퀴즈 game. */
|
||||
id: number;
|
||||
/** The server DB song (stats, 재생 불가 marking): the song itself, a quiz item's linked song, or null. */
|
||||
dbSongId: number | null;
|
||||
/** 제작된 퀴즈: the item's own 처음 position (null = 0). */
|
||||
startSec?: number | null;
|
||||
title: string;
|
||||
artist: string;
|
||||
year: number | null;
|
||||
@@ -38,6 +43,7 @@ export function quizSong(db: Database, id: number): QuizSong | null {
|
||||
const col = <T>(sql: string) => db.query<{ v: T }, [number]>(sql).all(id).map((r) => r.v);
|
||||
return {
|
||||
id: s.id,
|
||||
dbSongId: s.id,
|
||||
title: s.title,
|
||||
artist: s.artist,
|
||||
year: s.year,
|
||||
@@ -60,6 +66,46 @@ export function quizSong(db: Database, id: number): QuizSong | null {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* One song of a 제작된 퀴즈 (quizzes/store.ts): the item's video, title, artist and positions; a linked DB song adds its
|
||||
* aliases, genres, level and — only for the same video — loudness, highlight and 연령제한 audio.
|
||||
*/
|
||||
export function quizItemSong(db: Database, quizId: number, itemId: number): QuizSong | null {
|
||||
const it = db
|
||||
.query<
|
||||
{ id: number; song_id: number | null; video_id: string; title: string; artist: string; title_answers: string; artist_answers: string; duration_sec: number | null; auto: number; start_sec: number | null; highlight_sec: number | null },
|
||||
[number, number]
|
||||
>('SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? AND id = ?')
|
||||
.get(quizId, itemId);
|
||||
if (!it) return null;
|
||||
const base = it.song_id ? quizSong(db, it.song_id) : null;
|
||||
const same = !!base && db.query<{ y: string | null }, [number]>('SELECT youtube_id y FROM songs WHERE id = ?').get(it.song_id!)?.y === it.video_id;
|
||||
const audio = same ? db.query<{ age_video: string | null; audio_video: string | null; loudness_video: string | null; loudness_lufs: number | null }, [number]>('SELECT age_video, audio_video, loudness_video, loudness_lufs FROM songs WHERE id = ?').get(it.song_id!)! : null;
|
||||
const uniq = (xs: string[]) => [...new Set(xs.filter(Boolean))];
|
||||
return {
|
||||
id: it.id,
|
||||
dbSongId: base ? it.song_id : null,
|
||||
title: it.title,
|
||||
artist: it.artist,
|
||||
year: base?.year ?? null,
|
||||
durationSec: it.duration_sec ?? (same ? (base?.durationSec ?? null) : null),
|
||||
videoId: it.video_id,
|
||||
loudness: audio && audio.loudness_video === it.video_id ? audio.loudness_lufs : null,
|
||||
// 자동: the DB highlight of this very video; 직접: the item's own positions
|
||||
highlightSec: it.auto ? (same ? (base?.highlightSec ?? null) : null) : it.highlight_sec,
|
||||
startSec: it.auto ? 0 : (it.start_sec ?? 0),
|
||||
ageRestricted: !!audio && audio.age_video === it.video_id,
|
||||
audio: !!audio && audio.age_video === it.video_id && audio.audio_video === it.video_id,
|
||||
genres: base?.genres ?? [],
|
||||
level: base?.level ?? null,
|
||||
// the DB title/artist count too when the quiz spells them differently
|
||||
titleAliases: uniq([...(JSON.parse(it.title_answers) as string[]), ...(base ? [base.title, ...base.titleAliases] : [])]),
|
||||
artistAliases: uniq([...(JSON.parse(it.artist_answers) as string[]), ...(base ? [base.artist, ...base.artistAliases] : [])]),
|
||||
artistIds: base?.artistIds ?? [],
|
||||
lyrics: base?.lyrics ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** First main artist per song, for spreading singers apart. */
|
||||
export function mainArtists(db: Database, ids: number[]): Map<number, number> {
|
||||
const out = new Map<number, number>();
|
||||
@@ -106,8 +152,8 @@ export function loudnessGain(lufs: number | null, file = false): number {
|
||||
/** Where playback starts and how long the clip is (docs/04 재생위치, docs/08 하이라이트). */
|
||||
export function clipOf(song: QuizSong, c: RoomConfig): { startSec: number; endSec: number | null } {
|
||||
const dur = song.durationSec;
|
||||
let start = 0;
|
||||
if (c.startAt === 'highlight') start = song.highlightSec ?? (dur ? Math.round(dur * 0.3) : 0);
|
||||
let start = song.startSec ?? 0;
|
||||
if (c.startAt === 'highlight') start = song.highlightSec ?? (dur ? Math.round(dur * 0.3) : start);
|
||||
if (dur && start > dur - 5) start = 0;
|
||||
if (c.listenSec === 0) return { startSec: start, endSec: dur };
|
||||
const end = start + c.listenSec;
|
||||
|
||||
@@ -59,7 +59,7 @@ export function NicknameForm({ onDone }: { onDone?: () => void }) {
|
||||
export function GuestWarning() {
|
||||
return (
|
||||
<p className="guest-warning small" role="note">
|
||||
게스트는 사이트에 들어오지 않은 채 하루가 지나면 계정이 지워져요. 퀴즈 저장은 디스코드 로그인 계정만 할 수 있어요.
|
||||
게스트는 사이트에 들어오지 않은 채 하루가 지나면 계정이 지워져요. 진행 저장은 디스코드 로그인 계정만 할 수 있어요.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
VOTE_RULES,
|
||||
listenLabel,
|
||||
voteLabel,
|
||||
type QuizSummary,
|
||||
type RoomConfig,
|
||||
type VoteRule,
|
||||
} from '@mq/shared/lite';
|
||||
@@ -26,7 +27,7 @@ export interface CatalogMeta {
|
||||
|
||||
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 }) {
|
||||
export 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) => (
|
||||
@@ -38,7 +39,7 @@ function Seg<T extends string | number>({ value, options, onChange, disabled, la
|
||||
);
|
||||
}
|
||||
|
||||
function Section({ title, children, tip }: { title: string; children: ReactNode; tip?: string }) {
|
||||
export function Section({ title, children, tip }: { title: string; children: ReactNode; tip?: string }) {
|
||||
return (
|
||||
<section className="sec">
|
||||
<div className="label">
|
||||
@@ -214,9 +215,17 @@ export function RoomSettings({
|
||||
hasPassword,
|
||||
onPatch,
|
||||
onPassword,
|
||||
allowQuiz = true,
|
||||
picking: pickingProp,
|
||||
onPicking,
|
||||
}: {
|
||||
config: RoomConfig;
|
||||
editable: boolean;
|
||||
/** 제작된 퀴즈 / 직접 선택 (off on the admin's 새 방 기본값 page). */
|
||||
allowQuiz?: boolean;
|
||||
/** 제작된 퀴즈 chosen but no quiz picked yet (kept by the room page so 게임 시작 waits for a quiz). */
|
||||
picking?: boolean;
|
||||
onPicking?: (on: boolean) => void;
|
||||
meta: CatalogMeta | null;
|
||||
artists: { id: number; name: string }[];
|
||||
pool: { playable: number; total: number };
|
||||
@@ -235,8 +244,16 @@ export function RoomSettings({
|
||||
['테마', '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';
|
||||
// 제작된 퀴즈 chosen but no quiz picked yet: only on this screen until a quiz is picked
|
||||
const [pickingOwn, setPickingOwn] = useState(false);
|
||||
const picking = pickingProp ?? pickingOwn;
|
||||
const setPicking = onPicking ?? setPickingOwn;
|
||||
useEffect(() => {
|
||||
if (c.quizId) setPicking(false);
|
||||
}, [c.quizId]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const source: 'pick' | 'quiz' = c.quizId || picking ? 'quiz' : 'pick';
|
||||
const quiz = source === 'quiz';
|
||||
return (
|
||||
<div className="settings card ink">
|
||||
<div className="hd">
|
||||
@@ -258,8 +275,38 @@ export function RoomSettings({
|
||||
aria-label="방 이름"
|
||||
/>
|
||||
</Section>
|
||||
{allowQuiz && (
|
||||
<Section title="문제 고르기">
|
||||
<Seg
|
||||
label="문제 고르기"
|
||||
value={source}
|
||||
disabled={ro}
|
||||
onChange={(v) => {
|
||||
if (v === 'pick') {
|
||||
setPicking(false);
|
||||
if (c.quizId) onPatch({ quizId: null });
|
||||
} else {
|
||||
setPicking(true);
|
||||
if (c.mode !== 'listen') onPatch({ mode: 'listen' });
|
||||
}
|
||||
}}
|
||||
options={[
|
||||
{ v: 'pick', label: '🎛 직접 선택' },
|
||||
{ v: 'quiz', label: '📋 제작된 퀴즈' },
|
||||
]}
|
||||
/>
|
||||
{quiz && <QuizPicker chosen={c.quizId ? { id: c.quizId, name: c.quizName } : null} songs={pool.playable} ro={ro} onPick={(quizId) => onPatch({ quizId })} />}
|
||||
</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}` }))} />
|
||||
<Seg
|
||||
label="모드"
|
||||
value={c.mode}
|
||||
disabled={ro || quiz}
|
||||
onChange={(mode) => onPatch({ mode })}
|
||||
options={MODES.map((m) => ({ v: m.id, label: `${m.icon} ${m.label}` }))}
|
||||
/>
|
||||
{quiz && <p className="muted small" style={{ marginTop: 6 }}>제작된 퀴즈는 듣고맞추기로만 할 수 있어요.</p>}
|
||||
<div className="subbox">
|
||||
{listening ? (
|
||||
<>
|
||||
@@ -295,6 +342,8 @@ export function RoomSettings({
|
||||
)}
|
||||
</div>
|
||||
</Section>
|
||||
{!quiz && (
|
||||
<>
|
||||
<Section title="장르 · 여러 개 선택 가능">
|
||||
<div className="chipgroup">
|
||||
<span className="g">전체</span>
|
||||
@@ -343,73 +392,24 @@ export function RoomSettings({
|
||||
</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)} />
|
||||
</>
|
||||
)}
|
||||
<PlayRules c={c} ro={ro} listening={listening} onPatch={onPatch} />
|
||||
{quiz ? (
|
||||
<Section title="문제 수">
|
||||
<p className="small" style={{ margin: 0 }}>{c.quizId ? `퀴즈에 든 곡 전부 (${pool.playable.toLocaleString()}문제)` : '퀴즈를 고르면 그 퀴즈의 곡 전부가 나와요'}</p>
|
||||
</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="다음 문제까지" tip="정답을 공개한 뒤 다음 문제로 넘어가기까지 기다리는 시간. 그동안 노래는 계속 나와요">
|
||||
<Seg label="다음 문제까지" value={c.revealSec} disabled={ro} onChange={(revealSec) => onPatch({ revealSec })} options={REVEAL_SECS.map((v) => ({ v, label: `${v}초` }))} />
|
||||
</Section>
|
||||
<Section title="다음문제인원(이상)" tip="정답 공개 중에 바로 다음 문제로 넘어가려면 다음 문제를 눌러야하는 인원 설정">
|
||||
<Seg label="다음문제인원" value={c.nextVotes} disabled={ro} onChange={(nextVotes) => onPatch({ nextVotes })} 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="방 공개"
|
||||
@@ -453,3 +453,141 @@ function GenreRow({ label, children }: { label: string; children: ReactNode }) {
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** 정답방식 … 다음문제인원: the rules a room plays by; also the defaults of a 제작된 퀴즈 (관리자 → 퀴즈 → 설정). */
|
||||
export function PlayRules({
|
||||
c,
|
||||
ro,
|
||||
listening,
|
||||
onPatch,
|
||||
}: {
|
||||
c: Pick<RoomConfig, 'answer' | 'strict' | 'hint' | 'hintVotes' | 'skipVotes' | 'replayVotes' | 'revealSec' | 'nextVotes'>;
|
||||
ro: boolean;
|
||||
listening: boolean;
|
||||
onPatch: (p: Patch) => void;
|
||||
}) {
|
||||
const vote = (rules: readonly VoteRule[]) => rules.map((v) => ({ v, label: voteLabel(v) }));
|
||||
return (
|
||||
<>
|
||||
<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="다음 문제까지" tip="정답을 공개한 뒤 다음 문제로 넘어가기까지 기다리는 시간. 그동안 노래는 계속 나와요">
|
||||
<Seg label="다음 문제까지" value={c.revealSec} disabled={ro} onChange={(revealSec) => onPatch({ revealSec })} options={REVEAL_SECS.map((v) => ({ v, label: `${v}초` }))} />
|
||||
</Section>
|
||||
<Section title="다음문제인원(이상)" tip="정답 공개 중에 바로 다음 문제로 넘어가려면 다음 문제를 눌러야하는 인원 설정">
|
||||
<Seg label="다음문제인원" value={c.nextVotes} disabled={ro} onChange={(nextVotes) => onPatch({ nextVotes })} options={vote(VOTE_RULES)} />
|
||||
</Section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const VIS: Record<string, string> = { private: '비공개', partial: '일부공개' };
|
||||
|
||||
/** 제작된 퀴즈 list with a search box; not-public quizzes come first, marked. */
|
||||
function QuizPicker({ chosen, songs, ro, onPick }: { chosen: { id: number; name: string } | null; songs: number; ro: boolean; onPick: (id: number) => void }) {
|
||||
const [open, setOpen] = useState(!chosen);
|
||||
const [q, setQ] = useState('');
|
||||
const [list, setList] = useState<QuizSummary[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!open || ro) return;
|
||||
const t = setTimeout(() => {
|
||||
apiCall<{ quizzes: QuizSummary[] }>('GET', `/api/made-quizzes?q=${encodeURIComponent(q.trim())}`)
|
||||
.then((r) => (setList(r.quizzes), setError(null)))
|
||||
.catch((e: Error) => setError(e.message));
|
||||
}, 200);
|
||||
return () => clearTimeout(t);
|
||||
}, [q, open, ro]);
|
||||
useEffect(() => {
|
||||
if (chosen) setOpen(false);
|
||||
}, [chosen?.id]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
return (
|
||||
<div className="subbox stack" style={{ gap: 8 }}>
|
||||
{chosen ? (
|
||||
<div className="row">
|
||||
<span className="grow">
|
||||
<b>📋 {chosen.name}</b> <span className="muted small">· {songs}곡</span>
|
||||
</span>
|
||||
{!ro && (
|
||||
<button type="button" className="btn btn-sm" onClick={() => setOpen(!open)}>
|
||||
{open ? '닫기' : '다른 퀴즈 고르기'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<span className="muted small">{ro ? '방장이 아직 퀴즈를 고르지 않았어요.' : '아래에서 퀴즈를 골라 주세요.'}</span>
|
||||
)}
|
||||
{open && !ro && (
|
||||
<>
|
||||
<input className="input" value={q} onChange={(e) => setQ(e.target.value)} placeholder="퀴즈 이름 검색" aria-label="퀴즈 이름 검색" />
|
||||
{error && <span className="field-error small">{error}</span>}
|
||||
<div className="quiz-pick" role="listbox" aria-label="제작된 퀴즈 목록">
|
||||
{list?.length === 0 && <span className="muted small" style={{ padding: 10 }}>{q.trim() ? '검색 결과가 없어요.' : '고를 수 있는 퀴즈가 없어요.'}</span>}
|
||||
{list?.map((x) => (
|
||||
<button key={x.id} type="button" role="option" aria-selected={chosen?.id === x.id} className="quiz-pick-item" onClick={() => onPick(x.id)}>
|
||||
<span className="row" style={{ gap: 6 }}>
|
||||
{VIS[x.visibility] && <span className="badge warn">{VIS[x.visibility]}</span>}
|
||||
<b>{x.name}</b>
|
||||
</span>
|
||||
{x.description && <span className="muted small clamp2">{x.description}</span>}
|
||||
<span className="muted small">
|
||||
{x.songs}곡 · 만든 사람 {x.ownerName} · 플레이 {x.plays}번
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ export function GameScreen({ room, game }: { room: RoomView; game: GameView }) {
|
||||
: `${game.mode === 'artist' ? '🎤 가수노래' : '🎧 듣고맞추기'} · ${listenLabel(c.listenSec)} · ${c.startAt === 'highlight' ? '하이라이트부터' : '처음부터'}`}
|
||||
</span>
|
||||
<span className="badge dark">정답: {c.answer === 'title' ? '제목만' : c.answer === 'artist' ? '가수만' : '제목+가수'}</span>
|
||||
<span className="badge dark">★{c.level}</span>
|
||||
<span className="badge dark">{c.quizId ? `📋 ${c.quizName}` : `★${c.level}`}</span>
|
||||
<div className="grow" />
|
||||
{voteBtn('hint', '💡', '힌트', 'Ctrl+I')}
|
||||
{reveal ? voteBtn('next', '⏭', '다음 문제', 'Ctrl+K') : voteBtn('skip', '⏭', '스킵', 'Ctrl+K')}
|
||||
@@ -353,9 +353,9 @@ function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-lg"
|
||||
onClick={() => (me.kind === 'member' ? setSave(true) : toast('퀴즈 저장은 디스코드로 로그인하면 쓸 수 있어요.', 'error'))}
|
||||
onClick={() => (me.kind === 'member' ? setSave(true) : toast('진행 저장은 디스코드로 로그인하면 쓸 수 있어요.', 'error'))}
|
||||
>
|
||||
💾 퀴즈 저장
|
||||
💾 진행 저장
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
@@ -380,8 +380,8 @@ function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
|
||||
</ol>
|
||||
</section>
|
||||
{save && (
|
||||
<Sheet label="퀴즈 저장" onClose={() => setSave(false)}>
|
||||
<h2>퀴즈 저장</h2>
|
||||
<Sheet label="진행 저장" onClose={() => setSave(false)}>
|
||||
<h2>진행 저장</h2>
|
||||
<p className="muted small">방 설정, 지금까지 나온 곡, 참가자 점수를 내 계정에 저장해요. 불러오면 나온 곡은 빼고 이어서 할 수 있어요.</p>
|
||||
<form
|
||||
className="stack"
|
||||
|
||||
@@ -32,6 +32,7 @@ export default function RoomPage() {
|
||||
const unlocked = usePlayer((s) => s.unlocked);
|
||||
const [confirmStart, setConfirmStart] = useState(false);
|
||||
const [loadOpen, setLoadOpen] = useState(false);
|
||||
const [quizPicking, setQuizPicking] = useState(false);
|
||||
const [meta, setMeta] = useState<CatalogMeta | null>(null);
|
||||
const [pw, setPw] = useState('');
|
||||
const [confirmLeave, setConfirmLeave] = useState(false);
|
||||
@@ -99,7 +100,8 @@ export default function RoomPage() {
|
||||
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;
|
||||
const needQuiz = quizPicking && !c.quizId;
|
||||
const short = !c.quizId && c.count !== 0 && room.pool.playable < c.count;
|
||||
const start = () => (short && room.pool.playable > 0 ? setConfirmStart(true) : send({ t: 'start' }));
|
||||
const playing = room.status === 'playing' && !!game;
|
||||
|
||||
@@ -179,20 +181,22 @@ export default function RoomPage() {
|
||||
<section className="pool-banner" aria-live="polite">
|
||||
<div className="grow">
|
||||
<h2>
|
||||
조건에 맞는 곡 <span className="mono">{room.pool.playable.toLocaleString()}</span>곡
|
||||
{c.quizId ? '퀴즈 곡' : '조건에 맞는 곡'} <span className="mono">{room.pool.playable.toLocaleString()}</span>곡
|
||||
</h2>
|
||||
<p className="small">{configSummary(c, genreName).join(' · ')} · {c.count ? `${c.count}문제` : '무제한'}</p>
|
||||
<p className="small">{configSummary(c, genreName).join(' · ')} · {c.quizId ? `${room.pool.playable}문제` : 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>}
|
||||
{needQuiz && <p className="small">방 설정에서 제작된 퀴즈를 골라 주세요.</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>}
|
||||
{!needArtist && !c.quizId && room.pool.playable === 0 && room.pool.total === 0 && <p className="small">이 조건에 맞는 곡이 없어요. 장르·연도·난이도를 넓혀 보세요.</p>}
|
||||
{!!c.quizId && room.pool.playable === 0 && <p className="small">이 퀴즈에는 아직 곡이 없어요.</p>}
|
||||
</div>
|
||||
{isHost ? (
|
||||
<button className="btn btn-mustard btn-lg" disabled={needArtist || room.pool.playable === 0} onClick={start}>
|
||||
<button className="btn btn-mustard btn-lg" disabled={needArtist || needQuiz || room.pool.playable === 0} onClick={start}>
|
||||
게임 시작
|
||||
</button>
|
||||
) : (
|
||||
@@ -211,8 +215,8 @@ export default function RoomPage() {
|
||||
)}
|
||||
{isHost && (
|
||||
<div className="row">
|
||||
<button type="button" className="btn btn-sm" onClick={() => (me.kind === 'member' ? setLoadOpen(true) : toast('퀴즈 저장·불러오기는 디스코드로 로그인하면 쓸 수 있어요.', 'error'))}>
|
||||
📂 퀴즈 불러오기
|
||||
<button type="button" className="btn btn-sm" onClick={() => (me.kind === 'member' ? setLoadOpen(true) : toast('진행 저장·불러오기는 디스코드로 로그인하면 쓸 수 있어요.', 'error'))}>
|
||||
📂 진행 불러오기
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
@@ -235,6 +239,8 @@ export default function RoomPage() {
|
||||
hasPassword={room.hasPassword}
|
||||
onPatch={patch}
|
||||
onPassword={(value) => send({ t: 'password', value })}
|
||||
picking={quizPicking}
|
||||
onPicking={setQuizPicking}
|
||||
/>
|
||||
</main>
|
||||
)}
|
||||
@@ -282,13 +288,13 @@ function LoadSheet({ onClose }: { onClose: () => void }) {
|
||||
void refresh();
|
||||
}, []);
|
||||
return (
|
||||
<Sheet label="퀴즈 불러오기" onClose={onClose}>
|
||||
<h2>퀴즈 불러오기</h2>
|
||||
<Sheet label="진행 불러오기" onClose={onClose}>
|
||||
<h2>진행 불러오기</h2>
|
||||
<p className="muted small">불러오면 저장할 때의 설정과 점수가 돌아오고, 시작하면 이미 나온 곡은 빼고 이어서 나와요. (계정당 20개)</p>
|
||||
{list === null ? (
|
||||
<p className="muted">불러오는 중…</p>
|
||||
) : list.length === 0 ? (
|
||||
<p className="muted">저장한 퀴즈가 없어요. 게임이 끝난 뒤 결과 화면에서 저장할 수 있어요.</p>
|
||||
<p className="muted">저장한 진행이 없어요. 게임이 끝난 뒤 결과 화면에서 "진행 저장"을 누르면 푼 곡과 점수가 저장돼요.</p>
|
||||
) : (
|
||||
<ul className="saved-list">
|
||||
{list.map((q) => (
|
||||
|
||||
@@ -10,6 +10,7 @@ import { toast } from '../../store/toast';
|
||||
import { ConfirmSheet } from '../../components/ui';
|
||||
import { SongsPage } from './SongsPage';
|
||||
import { YoutubePage } from './YoutubePage';
|
||||
import { QuizEditor, QuizzesPage } from './QuizzesPage';
|
||||
import { ArtistsPage, CollectPage, GenresPage, RoomsPage, StatsPage } from './AdminMore';
|
||||
import { RoomSettings, type CatalogMeta } from '../../components/RoomSettings';
|
||||
import { DEFAULT_ROOM_CONFIG, type RoomConfig } from '@mq/shared/lite';
|
||||
@@ -69,6 +70,8 @@ export default function AdminApp() {
|
||||
<NavLink to="/admin/genres">🏷 장르</NavLink>
|
||||
<NavLink to="/admin/collect">📥 수집</NavLink>
|
||||
<NavLink to="/admin/stats">📈 통계</NavLink>
|
||||
<div className="sep">퀴즈</div>
|
||||
<NavLink to="/admin/quizzes">📋 퀴즈</NavLink>
|
||||
<div className="sep">운영</div>
|
||||
<NavLink to="/admin/rooms">🚪 방</NavLink>
|
||||
<NavLink to="/admin/site">⚙️ 사이트</NavLink>
|
||||
@@ -85,6 +88,8 @@ export default function AdminApp() {
|
||||
<Route path="artists" element={<ArtistsPage />} />
|
||||
<Route path="genres" element={<GenresPage />} />
|
||||
<Route path="stats" element={<StatsPage />} />
|
||||
<Route path="quizzes" element={<QuizzesPage />} />
|
||||
<Route path="quizzes/:id" element={<QuizEditor />} />
|
||||
<Route path="rooms" element={<RoomsPage />} />
|
||||
<Route path="site" element={<SiteSettings />} />
|
||||
{isSuper && <Route path="users" element={<UsersPage />} />}
|
||||
@@ -185,6 +190,8 @@ interface Site {
|
||||
questionLimitSec: number;
|
||||
roomDefaults: Partial<RoomConfig>;
|
||||
roomLocks: string[];
|
||||
quizMaxSongs: number;
|
||||
quizMaxPerUser: number;
|
||||
}
|
||||
|
||||
/** Settings an admin can pin for every room (사이트 → 잠금). */
|
||||
@@ -254,6 +261,19 @@ function SiteSettings() {
|
||||
<input className="input" type="number" min={10} max={600} value={s.questionLimitSec} onChange={(e) => setS({ ...s, questionLimitSec: Number(e.target.value) })} />
|
||||
<span className="muted small">듣고맞출시간이 1초~1분인 방에서 이 시간 안에 아무도 못 맞히면 정답을 공개해요. "끝까지"는 곡이 끝날 때까지예요.</span>
|
||||
</label>
|
||||
<fieldset className="card stack" style={{ margin: 0 }}>
|
||||
<legend style={{ fontWeight: 800, padding: '0 6px' }}>제작된 퀴즈 제한</legend>
|
||||
<div className="form-grid">
|
||||
<label className="field">
|
||||
퀴즈 하나에 넣을 수 있는 곡 수 (0 = 무제한)
|
||||
<input className="input" type="number" min={0} max={5000} value={s.quizMaxSongs} onChange={(e) => setS({ ...s, quizMaxSongs: Math.max(0, Math.round(Number(e.target.value)) || 0) })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
한 계정이 만들 수 있는 퀴즈 수 (0 = 무제한)
|
||||
<input className="input" type="number" min={0} max={1000} value={s.quizMaxPerUser} onChange={(e) => setS({ ...s, quizMaxPerUser: Math.max(0, Math.round(Number(e.target.value)) || 0) })} />
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset className="card stack" style={{ margin: 0 }}>
|
||||
<legend style={{ fontWeight: 800, padding: '0 6px' }}>채팅 도배 방지</legend>
|
||||
<label className="check">
|
||||
@@ -317,6 +337,7 @@ function RoomDefaults({ site, onChange }: { site: Site; onChange: (p: Partial<Si
|
||||
<RoomSettings
|
||||
config={config}
|
||||
editable
|
||||
allowQuiz={false}
|
||||
meta={meta}
|
||||
artists={[]}
|
||||
pool={pool}
|
||||
|
||||
324
apps/web/src/pages/admin/PositionEditor.tsx
Normal file
324
apps/web/src/pages/admin/PositionEditor.tsx
Normal file
@@ -0,0 +1,324 @@
|
||||
/**
|
||||
* 시작·하이라이트 위치 편집 (관리자 → 퀴즈 → 곡): the video with sound and a big seek bar carrying two markers,
|
||||
* [처음] and [하이라이트]. Drag a marker, or move it to where the video is now (지금 위치로); click a marker label to
|
||||
* listen from there. 자동 (default): start at 0 and the server DB highlight; moving a marker turns 자동 off.
|
||||
* 연령제한 videos refuse embedding (error 150): the server's downloaded audio plays instead when it has one.
|
||||
*/
|
||||
import { useEffect, useRef, useState, type PointerEvent as RPointerEvent } from 'react';
|
||||
import { apiCall } from '../../net/api';
|
||||
import { loadYt } from './SongsPage';
|
||||
|
||||
interface Media {
|
||||
play(): void;
|
||||
pause(): void;
|
||||
seek(sec: number): void;
|
||||
time(): number;
|
||||
duration(): number;
|
||||
playing(): boolean;
|
||||
destroy(): void;
|
||||
}
|
||||
|
||||
const fmt = (s: number | null | undefined) => {
|
||||
if (s == null || !Number.isFinite(s)) return '-:--';
|
||||
const t = Math.max(0, s);
|
||||
return `${Math.floor(t / 60)}:${(t % 60).toFixed(1).padStart(4, '0')}`;
|
||||
};
|
||||
|
||||
export interface Positions {
|
||||
auto: boolean;
|
||||
startSec: number | null;
|
||||
highlightSec: number | null;
|
||||
}
|
||||
|
||||
export function PositionEditor({
|
||||
videoId,
|
||||
durationSec,
|
||||
auto,
|
||||
startSec,
|
||||
highlightSec,
|
||||
dbHighlightSec,
|
||||
defaultStartAt,
|
||||
onChange,
|
||||
}: Positions & {
|
||||
videoId: string;
|
||||
durationSec: number | null;
|
||||
/** The server DB highlight of this video (유튜브 "가장 많이 다시 본 구간"), used while 자동. */
|
||||
dbHighlightSec: number | null;
|
||||
defaultStartAt: 'start' | 'highlight';
|
||||
onChange: (p: Positions) => void;
|
||||
}) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const media = useRef<Media | null>(null);
|
||||
const [now, setNow] = useState(0);
|
||||
const [dur, setDur] = useState<number>(durationSec ?? 0);
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const [mode, setMode] = useState<'video' | 'audio' | 'blocked' | 'loading'>('loading');
|
||||
const bar = useRef<HTMLDivElement>(null);
|
||||
const drag = useRef<'start' | 'highlight' | 'seek' | null>(null);
|
||||
|
||||
// the player: YouTube first, the server's audio file when YouTube refuses (연령제한)
|
||||
useEffect(() => {
|
||||
let dead = false;
|
||||
let timer: ReturnType<typeof setInterval> | null = null;
|
||||
const useAudio = async () => {
|
||||
try {
|
||||
const { src } = await apiCall<{ src: string }>('GET', `/api/admin/quizzes/pick/audio/${videoId}`);
|
||||
if (dead) return;
|
||||
const a = new Audio(src);
|
||||
a.preload = 'auto';
|
||||
a.addEventListener('loadedmetadata', () => setDur(a.duration));
|
||||
a.addEventListener('play', () => setPlaying(true));
|
||||
a.addEventListener('pause', () => setPlaying(false));
|
||||
media.current = {
|
||||
play: () => void a.play(),
|
||||
pause: () => a.pause(),
|
||||
seek: (s) => (a.currentTime = s),
|
||||
time: () => a.currentTime,
|
||||
duration: () => a.duration || 0,
|
||||
playing: () => !a.paused,
|
||||
destroy: () => (a.pause(), a.removeAttribute('src')),
|
||||
};
|
||||
setMode('audio');
|
||||
} catch {
|
||||
if (!dead) setMode('blocked');
|
||||
}
|
||||
};
|
||||
void loadYt().then(() => {
|
||||
if (dead || !host.current) return;
|
||||
const el = document.createElement('div');
|
||||
host.current.replaceChildren(el);
|
||||
const p = new window.YT.Player(el, {
|
||||
videoId,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
playerVars: { rel: 0, playsinline: 1, controls: 1 },
|
||||
events: {
|
||||
onReady: () => {
|
||||
if (dead) return;
|
||||
setMode('video');
|
||||
const d = p.getDuration?.();
|
||||
if (d) setDur(d);
|
||||
},
|
||||
onStateChange: (e: { data: number }) => {
|
||||
setPlaying(e.data === 1);
|
||||
const d = p.getDuration?.();
|
||||
if (d) setDur(d);
|
||||
},
|
||||
onError: (e: { data: number }) => {
|
||||
if (dead) return;
|
||||
if (e.data === 150 || e.data === 101) {
|
||||
p.destroy?.();
|
||||
host.current?.replaceChildren();
|
||||
void useAudio();
|
||||
} else setMode('blocked');
|
||||
},
|
||||
},
|
||||
});
|
||||
media.current = {
|
||||
play: () => p.playVideo?.(),
|
||||
pause: () => p.pauseVideo?.(),
|
||||
seek: (s) => p.seekTo?.(s, true),
|
||||
time: () => p.getCurrentTime?.() ?? 0,
|
||||
duration: () => p.getDuration?.() ?? 0,
|
||||
playing: () => p.getPlayerState?.() === 1,
|
||||
destroy: () => p.destroy?.(),
|
||||
};
|
||||
});
|
||||
timer = setInterval(() => {
|
||||
const m = media.current;
|
||||
if (m && drag.current !== 'seek') setNow(m.time());
|
||||
}, 100);
|
||||
return () => {
|
||||
dead = true;
|
||||
if (timer) clearInterval(timer);
|
||||
media.current?.destroy();
|
||||
media.current = null;
|
||||
};
|
||||
}, [videoId]);
|
||||
|
||||
const length = dur || durationSec || 0;
|
||||
const autoStart = 0;
|
||||
const autoHighlight = dbHighlightSec ?? (length ? Math.round(length * 0.3) : null);
|
||||
const start = auto ? autoStart : (startSec ?? 0);
|
||||
const highlight = auto ? autoHighlight : highlightSec;
|
||||
const pct = (s: number | null) => (s == null || !length ? 0 : Math.min(100, Math.max(0, (s / length) * 100)));
|
||||
const at = (clientX: number) => {
|
||||
const r = bar.current!.getBoundingClientRect();
|
||||
return Math.round(Math.min(1, Math.max(0, (clientX - r.left) / r.width)) * length * 10) / 10;
|
||||
};
|
||||
/** Manual positions from now on: both markers keep where they are, the moved one changes. */
|
||||
const setMarker = (which: 'start' | 'highlight', sec: number) => {
|
||||
const s = Math.round(Math.min(Math.max(0, sec), length || sec) * 10) / 10;
|
||||
onChange({
|
||||
auto: false,
|
||||
startSec: which === 'start' ? s : start,
|
||||
highlightSec: which === 'highlight' ? s : (highlight ?? null),
|
||||
});
|
||||
};
|
||||
const listen = (sec: number) => {
|
||||
const m = media.current;
|
||||
if (!m) return;
|
||||
m.seek(sec);
|
||||
m.play();
|
||||
setNow(sec);
|
||||
};
|
||||
|
||||
const onDown = (e: RPointerEvent<HTMLDivElement>) => {
|
||||
if (!length) return;
|
||||
const t = e.target as HTMLElement;
|
||||
const which = t.dataset.marker as 'start' | 'highlight' | undefined;
|
||||
drag.current = which ?? 'seek';
|
||||
(e.currentTarget as HTMLDivElement).setPointerCapture(e.pointerId);
|
||||
if (!which) {
|
||||
const s = at(e.clientX);
|
||||
setNow(s);
|
||||
media.current?.seek(s);
|
||||
}
|
||||
};
|
||||
const onMove = (e: RPointerEvent<HTMLDivElement>) => {
|
||||
const d = drag.current;
|
||||
if (!d || !length) return;
|
||||
const s = at(e.clientX);
|
||||
if (d === 'seek') {
|
||||
setNow(s);
|
||||
media.current?.seek(s);
|
||||
} else setMarker(d, s);
|
||||
};
|
||||
const onUp = () => {
|
||||
drag.current = null;
|
||||
};
|
||||
const nudge = (which: 'start' | 'highlight', delta: number) => setMarker(which, (which === 'start' ? start : (highlight ?? 0)) + delta);
|
||||
|
||||
return (
|
||||
<div className="pos-editor stack" style={{ gap: 10 }}>
|
||||
<div className={`yt-preview ${mode === 'audio' || mode === 'blocked' ? 'hidden-video' : ''}`} ref={host} aria-label="유튜브 영상" />
|
||||
{mode === 'audio' && <p className="muted small">유튜브가 다른 사이트 재생을 막은 영상(연령제한)이라 서버가 받아 둔 소리만 나와요.</p>}
|
||||
{mode === 'blocked' && <p className="warn-text">이 영상은 다른 사이트에서 재생할 수 없어요(연령제한·퍼가기 금지). 서버에 받아 둔 음원도 없어서 위치를 들어 보며 정할 수 없어요.</p>}
|
||||
<div className="row" style={{ gap: 8 }}>
|
||||
<button type="button" className="btn btn-sm" disabled={mode === 'loading' || mode === 'blocked'} onClick={() => (playing ? media.current?.pause() : media.current?.play())} aria-label={playing ? '일시정지' : '재생'}>
|
||||
{playing ? '⏸' : '▶'}
|
||||
</button>
|
||||
<span className="mono small">
|
||||
{fmt(now)} / {fmt(length || null)}
|
||||
</span>
|
||||
<span className="grow" />
|
||||
<label className="toggle-inline" title="켜면 처음은 0초, 하이라이트는 서버 DB 값(유튜브 '가장 많이 다시 본 구간')">
|
||||
<button
|
||||
type="button"
|
||||
className={`toggle ${auto ? 'on' : ''}`}
|
||||
aria-pressed={auto}
|
||||
onClick={() =>
|
||||
onChange(auto ? { auto: false, startSec: 0, highlightSec: autoHighlight } : { auto: true, startSec: null, highlightSec: null })
|
||||
}
|
||||
>
|
||||
<i aria-hidden />
|
||||
자동
|
||||
</button>
|
||||
</label>
|
||||
</div>
|
||||
<div
|
||||
className={`pos-bar ${auto ? 'auto' : ''}`}
|
||||
ref={bar}
|
||||
onPointerDown={onDown}
|
||||
onPointerMove={onMove}
|
||||
onPointerUp={onUp}
|
||||
onPointerCancel={onUp}
|
||||
role="slider"
|
||||
aria-label="재생 위치"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={Math.round(length)}
|
||||
aria-valuenow={Math.round(now)}
|
||||
tabIndex={0}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
|
||||
const s = Math.max(0, Math.min(length, now + (e.key === 'ArrowRight' ? 5 : -5)));
|
||||
media.current?.seek(s);
|
||||
setNow(s);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="pos-played" style={{ width: `${pct(now)}%` }} />
|
||||
<div className="pos-head" style={{ left: `${pct(now)}%` }} />
|
||||
<div className="pos-marker start" data-marker="start" style={{ left: `${pct(start)}%` }} title={`처음 ${fmt(start)}`}>
|
||||
<span data-marker="start">처음</span>
|
||||
</div>
|
||||
{highlight != null && (
|
||||
<div className="pos-marker hl" data-marker="highlight" style={{ left: `${pct(highlight)}%` }} title={`하이라이트 ${fmt(highlight)}`}>
|
||||
<span data-marker="highlight">하이라이트</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="pos-rows">
|
||||
<MarkerRow
|
||||
label="처음"
|
||||
cls="start"
|
||||
sec={start}
|
||||
on={defaultStartAt === 'start'}
|
||||
onListen={() => listen(start)}
|
||||
onNow={() => setMarker('start', media.current?.time() ?? now)}
|
||||
onNudge={(d) => nudge('start', d)}
|
||||
disabled={mode === 'loading' || mode === 'blocked'}
|
||||
/>
|
||||
<MarkerRow
|
||||
label="하이라이트"
|
||||
cls="hl"
|
||||
sec={highlight}
|
||||
on={defaultStartAt === 'highlight'}
|
||||
onListen={() => highlight != null && listen(highlight)}
|
||||
onNow={() => setMarker('highlight', media.current?.time() ?? now)}
|
||||
onNudge={(d) => nudge('highlight', d)}
|
||||
disabled={mode === 'loading' || mode === 'blocked'}
|
||||
/>
|
||||
</div>
|
||||
<p className="muted small">
|
||||
{auto
|
||||
? `자동: 처음은 0초, 하이라이트는 ${dbHighlightSec != null ? '서버 DB 값' : '아직 서버 DB 값이 없어 곡 길이의 30% 지점'}이에요. 표시를 옮기면 자동이 꺼져요.`
|
||||
: '표시를 끌거나 "지금 위치로"를 눌러 정해요. 재생바를 누르면 그 위치로 이동해요.'}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MarkerRow({
|
||||
label,
|
||||
cls,
|
||||
sec,
|
||||
on,
|
||||
onListen,
|
||||
onNow,
|
||||
onNudge,
|
||||
disabled,
|
||||
}: {
|
||||
label: string;
|
||||
cls: string;
|
||||
sec: number | null;
|
||||
on: boolean;
|
||||
onListen: () => void;
|
||||
onNow: () => void;
|
||||
onNudge: (d: number) => void;
|
||||
disabled: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className="pos-row">
|
||||
<span className={`pos-dot ${cls}`} aria-hidden />
|
||||
<b style={{ minWidth: 76 }}>
|
||||
{label}
|
||||
{on && <span className="muted small"> (기본)</span>}
|
||||
</b>
|
||||
<span className="mono">{fmt(sec)}</span>
|
||||
<span className="grow" />
|
||||
<button type="button" className="btn btn-sm btn-ghost" disabled={disabled} onClick={() => onNudge(-1)} aria-label={`${label} 1초 앞으로`}>
|
||||
−1초
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-ghost" disabled={disabled} onClick={() => onNudge(1)} aria-label={`${label} 1초 뒤로`}>
|
||||
+1초
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm" disabled={disabled || sec == null} onClick={onListen}>
|
||||
▶ 여기서 듣기
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-primary" disabled={disabled} onClick={onNow}>
|
||||
지금 위치로
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
872
apps/web/src/pages/admin/QuizzesPage.tsx
Normal file
872
apps/web/src/pages/admin/QuizzesPage.tsx
Normal file
@@ -0,0 +1,872 @@
|
||||
/**
|
||||
* 관리자 → 퀴즈 (제작된 퀴즈): my quizzes, then one quiz's editor — 곡 목록 (add by search or address, edit, reorder,
|
||||
* extra answers) and 설정 (description, room defaults, order, 공개방식). Saving is by hand: 저장 button or Ctrl+S;
|
||||
* unsaved changes show in the tab title and above the editor, and leaving asks first.
|
||||
*/
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
|
||||
import {
|
||||
DEFAULT_QUIZ_SETTINGS,
|
||||
LISTEN_SECS,
|
||||
QUIZ_VISIBILITIES,
|
||||
listenLabel,
|
||||
type QuizDetail,
|
||||
type QuizItem,
|
||||
type QuizSettings,
|
||||
type QuizSummary,
|
||||
type QuizVisibility,
|
||||
} from '@mq/shared/lite';
|
||||
import { apiCall } from '../../net/api';
|
||||
import { useSession } from '../../store/session';
|
||||
import { toast } from '../../store/toast';
|
||||
import { ConfirmSheet, Sheet } from '../../components/ui';
|
||||
import { PlayRules, Section, Seg } from '../../components/RoomSettings';
|
||||
import { YtPreview } from './SongsPage';
|
||||
import { PositionEditor } from './PositionEditor';
|
||||
|
||||
const mmss = (s: number | null | undefined) => (s == null ? '-' : `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, '0')}`);
|
||||
const VIS_LABEL: Record<QuizVisibility, string> = { private: '비공개', partial: '일부공개', public: '전체공개' };
|
||||
const VIS_CLASS: Record<QuizVisibility, string> = { private: '', partial: 'warn', public: 'ok' };
|
||||
|
||||
// ------------------------------------------------------------------ list
|
||||
export function QuizzesPage() {
|
||||
const role = useSession((s) => s.role);
|
||||
const [all, setAll] = useState(false);
|
||||
const [list, setList] = useState<QuizSummary[] | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [adding, setAdding] = useState(false);
|
||||
const nav = useNavigate();
|
||||
const load = useCallback(() => {
|
||||
apiCall<{ quizzes: QuizSummary[] }>('GET', `/api/admin/quizzes${all ? '?all=1' : ''}`)
|
||||
.then((r) => setList(r.quizzes))
|
||||
.catch((e: Error) => toast(e.message, 'error'));
|
||||
}, [all]);
|
||||
useEffect(load, [load]);
|
||||
const create = async () => {
|
||||
if (!name.trim()) return;
|
||||
try {
|
||||
const r = await apiCall<{ id: number }>('POST', '/api/admin/quizzes', { name: name.trim() });
|
||||
nav(`/admin/quizzes/${r.id}?new=1`);
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
}
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||||
<h1>퀴즈</h1>
|
||||
{role === 'superadmin' && (
|
||||
<label className="field-inline">
|
||||
<input type="checkbox" checked={all} onChange={(e) => setAll(e.target.checked)} /> 모든 관리자 퀴즈 보기
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
<p className="muted">직접 만든 퀴즈예요. 방 설정에서 "제작된 퀴즈"를 고르면 이 퀴즈의 곡이 순서대로(또는 섞어서) 전부 나와요. 듣고맞추기에서만 쓸 수 있어요.</p>
|
||||
<div className="quiz-grid">
|
||||
{list?.map((q) => (
|
||||
<Link key={q.id} to={`/admin/quizzes/${q.id}`} className="quiz-card">
|
||||
<b className="nm">{q.name}</b>
|
||||
{q.description && <span className="muted small clamp2">{q.description}</span>}
|
||||
<span className="row small" style={{ gap: 6 }}>
|
||||
<span className={`badge ${VIS_CLASS[q.visibility]}`}>{VIS_LABEL[q.visibility]}</span>
|
||||
<span className="muted">
|
||||
{q.songs}곡 · 플레이 {q.plays}번{all ? ` · ${q.ownerName}` : ''}
|
||||
</span>
|
||||
</span>
|
||||
<span className="muted small">수정 {new Date(q.updatedAt).toLocaleString('ko-KR', { dateStyle: 'short', timeStyle: 'short' })}</span>
|
||||
</Link>
|
||||
))}
|
||||
{adding ? (
|
||||
<form
|
||||
className="quiz-card add"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void create();
|
||||
}}
|
||||
>
|
||||
<label className="field">
|
||||
퀴즈 이름
|
||||
<input className="input" autoFocus maxLength={60} value={name} onChange={(e) => setName(e.target.value)} placeholder="예) 2000년대 발라드 명곡" />
|
||||
</label>
|
||||
<div className="row">
|
||||
<button className="btn btn-primary btn-sm" disabled={!name.trim()}>
|
||||
확인
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm" onClick={() => (setAdding(false), setName(''))}>
|
||||
취소
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<button type="button" className="quiz-card add plus" onClick={() => setAdding(true)}>
|
||||
<span aria-hidden>+</span> 퀴즈 추가
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{list && list.length === 0 && !adding && <p className="muted">아직 만든 퀴즈가 없어요. "퀴즈 추가"를 눌러 시작해 보세요.</p>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ editor
|
||||
type DraftItem = QuizItem & { key: string };
|
||||
interface Draft {
|
||||
name: string;
|
||||
description: string;
|
||||
visibility: QuizVisibility;
|
||||
settings: QuizSettings;
|
||||
items: DraftItem[];
|
||||
}
|
||||
export interface DbInfo {
|
||||
titleAliases: string[];
|
||||
artistAliases: string[];
|
||||
highlightSec: number | null;
|
||||
durationSec: number | null;
|
||||
videoId: string | null;
|
||||
}
|
||||
|
||||
let keySeq = 0;
|
||||
const newKey = () => `k${++keySeq}`;
|
||||
const toDraft = (q: QuizDetail): Draft => ({
|
||||
name: q.name,
|
||||
description: q.description,
|
||||
visibility: q.visibility,
|
||||
settings: { ...DEFAULT_QUIZ_SETTINGS, ...q.settings },
|
||||
items: q.items.map((i) => ({ ...i, key: newKey() })),
|
||||
});
|
||||
/** What is compared for "저장 안 됨" and sent to the server (client keys left out). */
|
||||
const payload = (d: Draft) => ({ ...d, items: d.items.map(({ key: _, ...i }) => i) });
|
||||
|
||||
export function QuizEditor() {
|
||||
const { id } = useParams();
|
||||
const [params, setParams] = useSearchParams();
|
||||
const nav = useNavigate();
|
||||
const [saved, setSaved] = useState<string>('');
|
||||
const [draft, setDraft] = useState<Draft | null>(null);
|
||||
const [db, setDb] = useState<Record<number, DbInfo>>({});
|
||||
const [tab, setTab] = useState<'songs' | 'settings'>('songs');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [leaveTo, setLeaveTo] = useState<string | null>(null);
|
||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||
const [owner, setOwner] = useState<{ ownerName: string; plays: number } | null>(null);
|
||||
|
||||
const load = useCallback(() => {
|
||||
apiCall<{ quiz: QuizDetail; db: Record<number, DbInfo> }>('GET', `/api/admin/quizzes/${id}`)
|
||||
.then((r) => {
|
||||
const d = toDraft(r.quiz);
|
||||
setDraft(d);
|
||||
setSaved(JSON.stringify(payload(d)));
|
||||
setDb(r.db);
|
||||
setOwner({ ownerName: r.quiz.ownerName, plays: r.quiz.plays });
|
||||
})
|
||||
.catch((e: Error) => toast(e.message, 'error'));
|
||||
}, [id]);
|
||||
useEffect(load, [load]);
|
||||
|
||||
const dirty = !!draft && JSON.stringify(payload(draft)) !== saved;
|
||||
const dirtyRef = useRef(dirty);
|
||||
dirtyRef.current = dirty;
|
||||
|
||||
const save = useCallback(async (): Promise<boolean> => {
|
||||
if (!draft) return false;
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await apiCall<{ quiz: QuizDetail }>('PUT', `/api/admin/quizzes/${id}`, payload(draft));
|
||||
// keep the client keys (selection) of items that were already there, in order
|
||||
const d = toDraft(r.quiz);
|
||||
d.items = d.items.map((it, i) => ({ ...it, key: draft.items[i]?.key ?? it.key }));
|
||||
setDraft(d);
|
||||
setSaved(JSON.stringify(payload(d)));
|
||||
toast('저장했어요.');
|
||||
// DB facts of newly linked songs
|
||||
const fresh = await apiCall<{ db: Record<number, DbInfo> }>('GET', `/api/admin/quizzes/${id}`);
|
||||
setDb(fresh.db);
|
||||
return true;
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
return false;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [draft, id]);
|
||||
const saveRef = useRef(save);
|
||||
saveRef.current = save;
|
||||
|
||||
// Ctrl+S / ⌘S
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
|
||||
e.preventDefault();
|
||||
if (dirtyRef.current) void saveRef.current();
|
||||
else toast('바뀐 내용이 없어요.');
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, []);
|
||||
// tab title + leaving the page
|
||||
useEffect(() => {
|
||||
const prev = document.title;
|
||||
return () => {
|
||||
document.title = prev;
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (draft) document.title = `${dirty ? '● 저장 안 됨 · ' : ''}${draft.name} · 퀴즈 편집`;
|
||||
}, [dirty, draft]);
|
||||
useEffect(() => {
|
||||
const onUnload = (e: BeforeUnloadEvent) => {
|
||||
if (!dirtyRef.current) return;
|
||||
e.preventDefault();
|
||||
e.returnValue = '';
|
||||
};
|
||||
window.addEventListener('beforeunload', onUnload);
|
||||
// links inside the site: our own 저장하고 나가기 / 그냥 나가기 / 취소
|
||||
const onClick = (e: MouseEvent) => {
|
||||
if (!dirtyRef.current || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey) return;
|
||||
const a = (e.target as HTMLElement).closest?.('a[href]') as HTMLAnchorElement | null;
|
||||
if (!a || a.target === '_blank') return;
|
||||
const url = new URL(a.href, location.href);
|
||||
if (url.origin !== location.origin || url.pathname === location.pathname) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setLeaveTo(url.pathname + url.search);
|
||||
};
|
||||
document.addEventListener('click', onClick, true);
|
||||
return () => {
|
||||
window.removeEventListener('beforeunload', onUnload);
|
||||
document.removeEventListener('click', onClick, true);
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (!draft) return <p className="muted">불러오는 중…</p>;
|
||||
const set = (p: Partial<Draft>) => setDraft({ ...draft, ...p });
|
||||
const isNew = params.get('new') === '1' && draft.items.length === 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="quiz-head">
|
||||
<Link to="/admin/quizzes" className="btn btn-sm btn-ghost">
|
||||
← 퀴즈 목록
|
||||
</Link>
|
||||
<h1 className="grow">{draft.name || '이름 없는 퀴즈'}</h1>
|
||||
{dirty ? <span className="badge warn" role="status">● 저장하지 않은 변경이 있어요</span> : <span className="muted small">저장됨</span>}
|
||||
<button type="button" className="btn btn-primary" disabled={busy || !dirty} onClick={() => void save()} title="Ctrl+S">
|
||||
{busy ? '저장 중…' : '저장'} <span className="kbd">Ctrl+S</span>
|
||||
</button>
|
||||
</div>
|
||||
{owner && (
|
||||
<p className="muted small" style={{ marginTop: -8 }}>
|
||||
만든 사람 {owner.ownerName} · {draft.items.length}곡 · 플레이 {owner.plays}번 · <span className={`badge ${VIS_CLASS[draft.visibility]}`}>{VIS_LABEL[draft.visibility]}</span>
|
||||
</p>
|
||||
)}
|
||||
<div className="seg" role="tablist" style={{ maxWidth: 360 }}>
|
||||
<button type="button" role="tab" aria-selected={tab === 'songs'} className={tab === 'songs' ? 'on' : ''} onClick={() => setTab('songs')}>
|
||||
곡 목록 ({draft.items.length})
|
||||
</button>
|
||||
<button type="button" role="tab" aria-selected={tab === 'settings'} className={tab === 'settings' ? 'on' : ''} onClick={() => setTab('settings')}>
|
||||
설정
|
||||
</button>
|
||||
</div>
|
||||
{isNew && (
|
||||
<div className="card stack">
|
||||
<b>곡을 어떻게 넣을까요?</b>
|
||||
<div className="row">
|
||||
<button type="button" className="btn" disabled title="곧 추가돼요">
|
||||
🔗 플레이리스트 가져오기 (준비 중)
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" onClick={() => setParams({})}>
|
||||
✋ 직접 하나씩 추가
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tab === 'songs' ? (
|
||||
<SongsTab items={draft.items} db={db} settings={draft.settings} onItems={(items) => set({ items })} />
|
||||
) : (
|
||||
<SettingsTab draft={draft} onChange={set} onDelete={() => setConfirmDelete(true)} />
|
||||
)}
|
||||
{leaveTo && (
|
||||
<Sheet label="저장하지 않은 변경" onClose={() => setLeaveTo(null)}>
|
||||
<h2>저장하지 않은 변경이 있어요</h2>
|
||||
<p className="muted">이대로 나가면 바꾼 내용이 사라져요.</p>
|
||||
<div className="stack">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-block btn-primary"
|
||||
onClick={() =>
|
||||
void save().then((ok) => {
|
||||
if (!ok) return;
|
||||
const to = leaveTo;
|
||||
setLeaveTo(null);
|
||||
dirtyRef.current = false;
|
||||
nav(to);
|
||||
})
|
||||
}
|
||||
>
|
||||
저장하고 나가기
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-block btn-danger"
|
||||
onClick={() => {
|
||||
const to = leaveTo;
|
||||
setLeaveTo(null);
|
||||
dirtyRef.current = false;
|
||||
nav(to);
|
||||
}}
|
||||
>
|
||||
저장하지 않고 나가기
|
||||
</button>
|
||||
<button type="button" className="btn btn-block" onClick={() => setLeaveTo(null)}>
|
||||
취소
|
||||
</button>
|
||||
</div>
|
||||
</Sheet>
|
||||
)}
|
||||
{confirmDelete && (
|
||||
<ConfirmSheet
|
||||
title="이 퀴즈를 지울까요?"
|
||||
body={`"${draft.name}"와 곡 목록이 지워지고 방에서 고를 수 없게 돼요. 서버 노래 DB의 곡과 별칭은 그대로예요.`}
|
||||
confirm="퀴즈 지우기"
|
||||
danger
|
||||
onClose={() => setConfirmDelete(false)}
|
||||
onConfirm={() =>
|
||||
void apiCall('DELETE', `/api/admin/quizzes/${id}`)
|
||||
.then(() => {
|
||||
dirtyRef.current = false;
|
||||
toast('퀴즈를 지웠어요.');
|
||||
nav('/admin/quizzes');
|
||||
})
|
||||
.catch((e: Error) => toast(e.message, 'error'))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 곡 목록
|
||||
interface DbHit {
|
||||
id: number;
|
||||
title: string;
|
||||
artist: string;
|
||||
year: number | null;
|
||||
videoId: string | null;
|
||||
status: string;
|
||||
durationSec: number | null;
|
||||
highlightSec: number | null;
|
||||
}
|
||||
interface YtHit {
|
||||
videoId: string;
|
||||
title: string;
|
||||
artist: string;
|
||||
durationSec: number | null;
|
||||
songId: number | null;
|
||||
}
|
||||
interface VideoInfo {
|
||||
videoId: string;
|
||||
videoTitle: string;
|
||||
channel: string;
|
||||
title: string;
|
||||
artist: string;
|
||||
songId: number | null;
|
||||
durationSec: number | null;
|
||||
}
|
||||
|
||||
const looksLikeUrl = (s: string) => /^(https?:\/\/|www\.|youtu\.?be|m\.youtube|music\.youtube)/i.test(s.trim()) || /^[\w-]{11}$/.test(s.trim());
|
||||
|
||||
function SongsTab({ items, db, settings, onItems }: { items: DraftItem[]; db: Record<number, DbInfo>; settings: QuizSettings; onItems: (items: DraftItem[]) => void }) {
|
||||
const [sel, setSel] = useState<string | null>(null);
|
||||
const [dragKey, setDragKey] = useState<string | null>(null);
|
||||
const [overKey, setOverKey] = useState<string | null>(null);
|
||||
const selected = items.find((i) => i.key === sel) ?? null;
|
||||
const add = (it: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => {
|
||||
if (items.some((x) => x.videoId === it.videoId || (it.songId && x.songId === it.songId))) {
|
||||
toast('이미 목록에 있는 곡이에요.', 'error');
|
||||
return false;
|
||||
}
|
||||
const n: DraftItem = { ...it, titleAnswers: [], artistAnswers: [], auto: true, startSec: null, highlightSec: null, key: newKey() };
|
||||
onItems([...items, n]);
|
||||
toast(`${items.length + 1}번에 추가했어요: ${it.title}`);
|
||||
return true;
|
||||
};
|
||||
const patch = (key: string, p: Partial<QuizItem>) => onItems(items.map((i) => (i.key === key ? { ...i, ...p } : i)));
|
||||
const move = (from: number, to: number) => {
|
||||
if (to < 0 || to >= items.length || from === to) return;
|
||||
const next = [...items];
|
||||
const [x] = next.splice(from, 1);
|
||||
next.splice(to, 0, x!);
|
||||
onItems(next);
|
||||
};
|
||||
const remove = (key: string) => {
|
||||
onItems(items.filter((i) => i.key !== key));
|
||||
if (sel === key) setSel(null);
|
||||
};
|
||||
return (
|
||||
<div className={`songs-layout quiz ${selected ? 'with-panel' : ''}`}>
|
||||
<div className="stack" style={{ gap: 12, minWidth: 0 }}>
|
||||
<AddSong onAdd={add} />
|
||||
{items.length === 0 ? (
|
||||
<p className="muted">아직 곡이 없어요. 위에서 제목·가수로 찾거나 유튜브 주소를 붙여 넣어 추가해 주세요.</p>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="data-table quiz-songs">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: 28 }} aria-label="순서 옮기기" />
|
||||
<th style={{ width: 44 }}>번호</th>
|
||||
<th>노래</th>
|
||||
<th>추가 정답</th>
|
||||
<th>길이</th>
|
||||
<th>재생 위치</th>
|
||||
<th style={{ width: 120 }} />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map((it, i) => (
|
||||
<tr
|
||||
key={it.key}
|
||||
className={`${sel === it.key ? 'sel' : ''} ${overKey === it.key && dragKey !== it.key ? 'drop' : ''} ${dragKey === it.key ? 'dragging' : ''}`}
|
||||
onClick={() => setSel(sel === it.key ? null : it.key)}
|
||||
draggable
|
||||
onDragStart={(e) => {
|
||||
setDragKey(it.key);
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
}}
|
||||
onDragOver={(e) => {
|
||||
if (!dragKey) return;
|
||||
e.preventDefault();
|
||||
setOverKey(it.key);
|
||||
}}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
const from = items.findIndex((x) => x.key === dragKey);
|
||||
if (from >= 0) move(from, i);
|
||||
setDragKey(null);
|
||||
setOverKey(null);
|
||||
}}
|
||||
onDragEnd={() => (setDragKey(null), setOverKey(null))}
|
||||
style={{ cursor: 'pointer' }}
|
||||
>
|
||||
<td className="drag" aria-hidden title="끌어서 순서 바꾸기">
|
||||
⠿
|
||||
</td>
|
||||
<td className="mono">{i + 1}</td>
|
||||
<td>
|
||||
<b>{it.title}</b>
|
||||
<div className="muted small">
|
||||
{it.artist}
|
||||
{!it.songId && <span className="badge" style={{ marginLeft: 6 }}>DB에 없음</span>}
|
||||
</div>
|
||||
</td>
|
||||
<td className="small">{[...it.titleAnswers, ...it.artistAnswers].join(', ') || <span className="muted">-</span>}</td>
|
||||
<td className="mono small">{mmss(it.durationSec ?? (it.songId ? db[it.songId]?.durationSec : null))}</td>
|
||||
<td className="small">{it.auto ? <span className="muted">자동</span> : `처음 ${mmss(it.startSec ?? 0)} · 하이라이트 ${mmss(it.highlightSec)}`}</td>
|
||||
<td onClick={(e) => e.stopPropagation()}>
|
||||
<div className="row" style={{ gap: 4, flexWrap: 'nowrap' }}>
|
||||
<button type="button" className="btn btn-sm btn-ghost" disabled={i === 0} aria-label={`${i + 1}번 위로`} onClick={() => move(i, i - 1)}>
|
||||
▲
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-ghost" disabled={i === items.length - 1} aria-label={`${i + 1}번 아래로`} onClick={() => move(i, i + 1)}>
|
||||
▼
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-ghost" aria-label={`${it.title} 빼기`} onClick={() => remove(it.key)}>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{selected && (
|
||||
<ItemPanel
|
||||
key={selected.key}
|
||||
item={selected}
|
||||
index={items.indexOf(selected)}
|
||||
total={items.length}
|
||||
db={selected.songId ? (db[selected.songId] ?? null) : null}
|
||||
defaultStartAt={settings.startAt}
|
||||
onPatch={(p) => patch(selected.key, p)}
|
||||
onMove={(to) => move(items.indexOf(selected), to)}
|
||||
onRemove={() => remove(selected.key)}
|
||||
onClose={() => setSel(null)}
|
||||
isDuplicate={(videoId) => items.some((x) => x.key !== selected.key && x.videoId === videoId)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AddSong({ onAdd }: { onAdd: (it: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => boolean }) {
|
||||
const [q, setQ] = useState('');
|
||||
const [dbHits, setDbHits] = useState<DbHit[] | null>(null);
|
||||
const [ytHits, setYtHits] = useState<YtHit[] | null>(null);
|
||||
const [video, setVideo] = useState<VideoInfo | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const reset = () => (setDbHits(null), setYtHits(null), setVideo(null));
|
||||
const search = async () => {
|
||||
const text = q.trim();
|
||||
if (!text) return;
|
||||
reset();
|
||||
setBusy(true);
|
||||
try {
|
||||
if (looksLikeUrl(text)) setVideo(await apiCall<VideoInfo>('POST', '/api/admin/quizzes/pick/video', { url: text }));
|
||||
else setDbHits((await apiCall<{ songs: DbHit[] }>('GET', `/api/admin/quizzes/pick/db?q=${encodeURIComponent(text)}`)).songs);
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const searchYt = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
setYtHits((await apiCall<{ results: YtHit[] }>('GET', `/api/admin/quizzes/pick/youtube?q=${encodeURIComponent(q.trim())}`)).results);
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const done = (ok: boolean) => {
|
||||
if (!ok) return;
|
||||
reset();
|
||||
setQ('');
|
||||
};
|
||||
return (
|
||||
<div className="card stack" style={{ gap: 10 }}>
|
||||
<form
|
||||
className="row"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void search();
|
||||
}}
|
||||
>
|
||||
<input className="input grow" value={q} onChange={(e) => setQ(e.target.value)} placeholder="곡 추가: 제목·가수로 찾기 (예: 아이유 좋은 날) 또는 유튜브 주소 붙여넣기" aria-label="곡 추가 검색" />
|
||||
<button className="btn btn-primary" disabled={busy || !q.trim()}>
|
||||
{busy ? '찾는 중…' : '찾기'}
|
||||
</button>
|
||||
{(dbHits || ytHits || video) && (
|
||||
<button type="button" className="btn" onClick={reset}>
|
||||
닫기
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
{video && <VideoAdd v={video} onAdd={(it) => done(onAdd(it))} />}
|
||||
{dbHits && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<span className="field">서버 노래 DB {dbHits.length ? `(${dbHits.length}곡)` : ''}</span>
|
||||
{dbHits.length === 0 && <span className="muted small">서버 DB에서 못 찾았어요. 유튜브에서 찾아보세요.</span>}
|
||||
{dbHits.map((s) => (
|
||||
<div key={s.id} className="cand">
|
||||
<span className="grow">
|
||||
<b>{s.title}</b> <span className="muted small">· {s.artist}{s.year ? ` · ${s.year}` : ''} · {mmss(s.durationSec)}</span>
|
||||
{s.status !== 'matched' && <span className="warn-text small"> — 확정된 영상 없음{s.videoId ? ' (후보 영상으로 추가)' : ''}</span>}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
disabled={!s.videoId}
|
||||
onClick={() => done(onAdd({ songId: s.id, videoId: s.videoId!, title: s.title, artist: s.artist, durationSec: s.durationSec }))}
|
||||
>
|
||||
추가
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<div className="row">
|
||||
<button type="button" className="btn btn-sm" disabled={busy} onClick={() => void searchYt()}>
|
||||
🔎 유튜브에서 찾기
|
||||
</button>
|
||||
<span className="muted small">서버 DB에 없거나 다른 영상을 쓰고 싶을 때</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{ytHits && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<span className="field">유튜브 검색 결과</span>
|
||||
{ytHits.length === 0 && <span className="muted small">결과가 없어요. 유튜브 주소를 직접 붙여 넣어 주세요.</span>}
|
||||
{ytHits.map((r) => (
|
||||
<div key={r.videoId} className="cand">
|
||||
<span className="grow">
|
||||
<b>{r.title}</b> <span className="muted small">· {r.artist} · {mmss(r.durationSec)}</span>
|
||||
{r.songId && <span className="badge ok" style={{ marginLeft: 6 }}>서버 DB에 있는 곡</span>}
|
||||
</span>
|
||||
<a className="btn btn-sm btn-ghost" href={`https://youtu.be/${r.videoId}`} target="_blank" rel="noreferrer" aria-label={`${r.title} 유튜브에서 보기`}>
|
||||
↗
|
||||
</a>
|
||||
<button type="button" className="btn btn-sm" onClick={() => done(onAdd({ songId: r.songId, videoId: r.videoId, title: r.title, artist: r.artist, durationSec: r.durationSec }))}>
|
||||
추가
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function VideoAdd({ v, onAdd }: { v: VideoInfo; onAdd: (it: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => void }) {
|
||||
const [title, setTitle] = useState(v.title);
|
||||
const [artist, setArtist] = useState(v.artist);
|
||||
const api = useRef<{ time(): number | undefined } | null>(null);
|
||||
return (
|
||||
<div className="video-add">
|
||||
<YtPreview videoId={v.videoId} start={0} apiRef={api} />
|
||||
<form
|
||||
className="stack"
|
||||
style={{ gap: 8 }}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (title.trim() && artist.trim()) onAdd({ songId: v.songId, videoId: v.videoId, title: title.trim(), artist: artist.trim(), durationSec: v.durationSec });
|
||||
}}
|
||||
>
|
||||
<span className="muted small">
|
||||
영상: {v.videoTitle} · {v.channel}
|
||||
{v.songId && <span className="badge ok" style={{ marginLeft: 6 }}>서버 DB에 있는 곡</span>}
|
||||
</span>
|
||||
<label className="field">
|
||||
제목 (정답)
|
||||
<input className="input" value={title} maxLength={200} onChange={(e) => setTitle(e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
가수
|
||||
<input className="input" value={artist} maxLength={200} onChange={(e) => setArtist(e.target.value)} />
|
||||
</label>
|
||||
<button className="btn btn-primary" disabled={!title.trim() || !artist.trim()}>
|
||||
이 영상으로 추가
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Chips with an input: Enter or , adds, ✕ removes. */
|
||||
function ChipsInput({ values, onChange, label, placeholder }: { values: string[]; onChange: (v: string[]) => void; label: string; placeholder: string }) {
|
||||
const [text, setText] = useState('');
|
||||
const commit = () => {
|
||||
const t = text.trim();
|
||||
if (t && !values.includes(t)) onChange([...values, t]);
|
||||
setText('');
|
||||
};
|
||||
return (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<div className="row" style={{ gap: 6 }}>
|
||||
{values.map((v) => (
|
||||
<button key={v} type="button" className="chip x" aria-pressed="true" onClick={() => onChange(values.filter((x) => x !== v))} aria-label={`${v} 빼기`}>
|
||||
{v}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<input
|
||||
className="input"
|
||||
value={text}
|
||||
aria-label={label}
|
||||
placeholder={placeholder}
|
||||
maxLength={200}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ',') {
|
||||
e.preventDefault();
|
||||
commit();
|
||||
}
|
||||
}}
|
||||
onBlur={commit}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ItemPanel({
|
||||
item,
|
||||
index,
|
||||
total,
|
||||
db,
|
||||
defaultStartAt,
|
||||
onPatch,
|
||||
onMove,
|
||||
onRemove,
|
||||
onClose,
|
||||
isDuplicate,
|
||||
}: {
|
||||
item: DraftItem;
|
||||
index: number;
|
||||
total: number;
|
||||
db: DbInfo | null;
|
||||
defaultStartAt: 'start' | 'highlight';
|
||||
onPatch: (p: Partial<QuizItem>) => void;
|
||||
onMove: (to: number) => void;
|
||||
onRemove: () => void;
|
||||
onClose: () => void;
|
||||
isDuplicate: (videoId: string) => boolean;
|
||||
}) {
|
||||
const [url, setUrl] = useState('');
|
||||
const [pos, setPos] = useState(String(index + 1));
|
||||
useEffect(() => setPos(String(index + 1)), [index]);
|
||||
const changeVideo = async () => {
|
||||
try {
|
||||
const v = await apiCall<VideoInfo>('POST', '/api/admin/quizzes/pick/video', { url: url.trim() });
|
||||
if (isDuplicate(v.videoId)) return toast('이미 목록에 있는 영상이에요.', 'error');
|
||||
// a different video: the old positions belong to the old video
|
||||
onPatch({ videoId: v.videoId, songId: v.songId ?? item.songId, durationSec: v.durationSec ?? null, auto: true, startSec: null, highlightSec: null });
|
||||
setUrl('');
|
||||
toast('영상을 바꿨어요. 저장해야 반영돼요.');
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
}
|
||||
};
|
||||
return (
|
||||
<aside className="song-panel stack" aria-label="곡 편집">
|
||||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||||
<b>{index + 1}번 곡</b>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={onClose} aria-label="닫기">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<PositionEditor
|
||||
videoId={item.videoId}
|
||||
durationSec={item.durationSec}
|
||||
auto={item.auto}
|
||||
startSec={item.startSec}
|
||||
highlightSec={item.highlightSec}
|
||||
dbHighlightSec={db && db.videoId === item.videoId ? db.highlightSec : null}
|
||||
defaultStartAt={defaultStartAt}
|
||||
onChange={onPatch}
|
||||
/>
|
||||
<label className="field">
|
||||
제목 (정답)
|
||||
<input className="input" value={item.title} maxLength={200} onChange={(e) => onPatch({ title: e.target.value })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
가수
|
||||
<input className="input" value={item.artist} maxLength={200} onChange={(e) => onPatch({ artist: e.target.value })} />
|
||||
</label>
|
||||
<div className="field">
|
||||
제목 추가 정답 (복수정답)
|
||||
<ChipsInput values={item.titleAnswers} onChange={(titleAnswers) => onPatch({ titleAnswers })} label="제목 추가 정답" placeholder="다른 표기 입력 후 Enter (예: 좋은날, Good Day)" />
|
||||
</div>
|
||||
<div className="field">
|
||||
가수 추가 정답
|
||||
<ChipsInput values={item.artistAnswers} onChange={(artistAnswers) => onPatch({ artistAnswers })} label="가수 추가 정답" placeholder="다른 표기 입력 후 Enter (예: IU)" />
|
||||
</div>
|
||||
{item.songId ? (
|
||||
<p className="muted small">
|
||||
서버 노래 #{item.songId}와 연결된 곡이에요. 추가 정답은 저장할 때 서버 DB 별칭에도 들어가요.
|
||||
{db && (db.titleAliases.length > 0 || db.artistAliases.length > 0) && (
|
||||
<>
|
||||
<br />
|
||||
이미 정답으로 인정되는 별칭: {[...db.titleAliases, ...db.artistAliases].join(', ')}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
) : (
|
||||
<p className="muted small">서버 노래 DB에 없는 곡이에요. 이 퀴즈 안에서만 쓰여요.</p>
|
||||
)}
|
||||
<form
|
||||
className="row"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (url.trim()) void changeVideo();
|
||||
}}
|
||||
>
|
||||
<input className="input grow" value={url} onChange={(e) => setUrl(e.target.value)} placeholder="다른 유튜브 주소로 바꾸기" aria-label="영상 바꾸기" />
|
||||
<button className="btn btn-sm" disabled={!url.trim()}>
|
||||
바꾸기
|
||||
</button>
|
||||
</form>
|
||||
<div className="row">
|
||||
<label className="field-inline">
|
||||
순서
|
||||
<input
|
||||
className="input sm"
|
||||
type="number"
|
||||
min={1}
|
||||
max={total}
|
||||
value={pos}
|
||||
onChange={(e) => setPos(e.target.value)}
|
||||
onBlur={() => {
|
||||
const n = Math.min(total, Math.max(1, Math.round(Number(pos)) || index + 1));
|
||||
onMove(n - 1);
|
||||
setPos(String(n));
|
||||
}}
|
||||
onKeyDown={(e) => e.key === 'Enter' && (e.target as HTMLInputElement).blur()}
|
||||
aria-label="순서 번호"
|
||||
/>
|
||||
번으로
|
||||
</label>
|
||||
<span className="grow" />
|
||||
<button type="button" className="btn btn-sm btn-danger" onClick={onRemove}>
|
||||
목록에서 빼기
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 설정
|
||||
function SettingsTab({ draft, onChange, onDelete }: { draft: Draft; onChange: (p: Partial<Draft>) => void; onDelete: () => void }) {
|
||||
const s = draft.settings;
|
||||
const setS = (p: Partial<QuizSettings>) => onChange({ settings: { ...s, ...p } });
|
||||
const vis = useMemo(() => QUIZ_VISIBILITIES.find((v) => v.id === draft.visibility)!, [draft.visibility]);
|
||||
return (
|
||||
<div className="settings card ink" style={{ maxWidth: 860 }}>
|
||||
<div className="hd">
|
||||
<h2>퀴즈 설정</h2>
|
||||
<span className="small" style={{ fontWeight: 700 }}>
|
||||
방에서 이 퀴즈를 고르면 아래 값이 방 설정의 기본값이 돼요(방장이 바꿀 수 있어요)
|
||||
</span>
|
||||
</div>
|
||||
<div className="bd">
|
||||
<Section title="퀴즈 이름">
|
||||
<input className="input" value={draft.name} maxLength={60} onChange={(e) => onChange({ name: e.target.value })} aria-label="퀴즈 이름" />
|
||||
</Section>
|
||||
<Section title="설명">
|
||||
<textarea className="input" rows={3} value={draft.description} maxLength={500} onChange={(e) => onChange({ description: e.target.value })} aria-label="퀴즈 설명" placeholder="방에서 퀴즈를 고를 때 보이는 설명" />
|
||||
</Section>
|
||||
<Section title="공개방식">
|
||||
<Seg label="공개방식" value={draft.visibility} disabled={false} onChange={(visibility) => onChange({ visibility })} options={QUIZ_VISIBILITIES.map((v) => ({ v: v.id, label: v.label }))} />
|
||||
<p className="muted small" style={{ marginTop: 6 }}>
|
||||
{vis.help}
|
||||
</p>
|
||||
</Section>
|
||||
<Section title="문제 순서" tip="문제 수는 퀴즈에 든 곡 전부예요">
|
||||
<Seg
|
||||
label="문제 순서"
|
||||
value={s.order}
|
||||
disabled={false}
|
||||
onChange={(order) => setS({ order })}
|
||||
options={[
|
||||
{ v: 'ordered', label: '순서대로' },
|
||||
{ v: 'random', label: '무작위' },
|
||||
]}
|
||||
/>
|
||||
</Section>
|
||||
<Section title="재생위치 기본" tip="곡마다 정한 '처음' 위치 또는 '하이라이트' 위치에서 틀어요">
|
||||
<Seg
|
||||
label="재생위치 기본"
|
||||
value={s.startAt}
|
||||
disabled={false}
|
||||
onChange={(startAt) => setS({ startAt })}
|
||||
options={[
|
||||
{ v: 'start', label: '처음부터' },
|
||||
{ v: 'highlight', label: '하이라이트부터' },
|
||||
]}
|
||||
/>
|
||||
</Section>
|
||||
<Section title="듣고맞출시간">
|
||||
<Seg label="듣고맞출시간" value={s.listenSec} disabled={false} onChange={(listenSec) => setS({ listenSec })} options={LISTEN_SECS.map((v) => ({ v, label: listenLabel(v) }))} />
|
||||
</Section>
|
||||
<PlayRules c={s} ro={false} listening onPatch={(p) => setS(p as Partial<QuizSettings>)} />
|
||||
<section className="sec">
|
||||
<button type="button" className="btn btn-danger btn-sm" onClick={onDelete}>
|
||||
퀴즈 지우기
|
||||
</button>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -859,7 +859,7 @@ declare global {
|
||||
}
|
||||
|
||||
let ytApi: Promise<void> | null = null;
|
||||
function loadYt(): Promise<void> {
|
||||
export function loadYt(): Promise<void> {
|
||||
ytApi ??= new Promise<void>((resolve) => {
|
||||
if (window.YT?.Player) return resolve();
|
||||
const prev = window.onYouTubeIframeAPIReady;
|
||||
|
||||
@@ -345,7 +345,45 @@ input.input.sm { width: 76px; }
|
||||
.yt-recent li { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; min-width: 0; }
|
||||
.yt-log { max-height: 220px; overflow: auto; margin-top: 6px; }
|
||||
.lyrics { white-space: pre-wrap; font: inherit; font-size: 0.85rem; background: var(--surface-2); padding: 10px; border-radius: 8px; max-height: 260px; overflow: auto; }
|
||||
|
||||
/* 방 설정 → 제작된 퀴즈 */
|
||||
.quiz-pick { display: flex; flex-direction: column; border: 1.5px solid var(--line); border-radius: 10px; max-height: 320px; overflow-y: auto; background: var(--surface); }
|
||||
.quiz-pick-item { display: flex; flex-direction: column; gap: 3px; padding: 9px 12px; border: 0; border-bottom: 1px solid var(--line); background: none; font: inherit; color: var(--text); cursor: pointer; text-align: left; }
|
||||
.quiz-pick-item[aria-selected='true'] { background: var(--primary-soft); }
|
||||
.quiz-pick-item:hover { background: color-mix(in srgb, var(--primary-soft) 60%, transparent); }
|
||||
/* admin quizzes (관리자 → 퀴즈) */
|
||||
.quiz-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 12px; }
|
||||
.quiz-card { display: flex; flex-direction: column; gap: 6px; min-height: 120px; padding: 14px 16px; background: var(--surface); border: 2px solid var(--ink); border-radius: 14px; color: var(--text); text-decoration: none; box-shadow: 3px 3px 0 var(--ink); font: inherit; text-align: left; }
|
||||
.quiz-card:hover { background: var(--primary-soft); }
|
||||
.quiz-card .nm { font-size: 1.05rem; }
|
||||
.quiz-card.add { border-style: dashed; box-shadow: none; }
|
||||
.quiz-card.plus { align-items: center; justify-content: center; font-weight: 800; cursor: pointer; gap: 4px; }
|
||||
.quiz-card.plus span { font-size: 1.6rem; }
|
||||
.clamp2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
|
||||
.quiz-head { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
|
||||
.quiz-head h1 { margin: 0; }
|
||||
.songs-layout.with-panel.quiz { grid-template-columns: minmax(0, 1fr) 520px; }
|
||||
.quiz-songs td.drag { cursor: grab; color: var(--text-sub); user-select: none; }
|
||||
.quiz-songs tr.dragging td { opacity: 0.45; }
|
||||
.quiz-songs tr.drop td { box-shadow: inset 0 3px 0 var(--primary); }
|
||||
.video-add { display: grid; grid-template-columns: minmax(0, 320px) 1fr; gap: 14px; align-items: start; }
|
||||
@media (max-width: 800px) { .video-add { grid-template-columns: 1fr; } }
|
||||
.yt-preview.hidden-video { display: none; }
|
||||
.pos-bar { position: relative; height: 54px; margin: 18px 4px 4px; border: 2px solid var(--ink); border-radius: 10px; background: var(--surface-2); cursor: pointer; touch-action: none; }
|
||||
.pos-bar:focus-visible { outline: 3px solid var(--primary); outline-offset: 2px; }
|
||||
.pos-played { position: absolute; left: 0; top: 0; bottom: 0; background: color-mix(in srgb, var(--primary) 22%, transparent); border-radius: 8px 0 0 8px; pointer-events: none; }
|
||||
.pos-head { position: absolute; top: -4px; bottom: -4px; width: 2px; margin-left: -1px; background: var(--ink); pointer-events: none; }
|
||||
.pos-marker { position: absolute; top: -16px; bottom: -2px; width: 4px; margin-left: -2px; border-radius: 2px; cursor: ew-resize; }
|
||||
.pos-marker span { position: absolute; top: -6px; left: 50%; transform: translateX(-50%); white-space: nowrap; font-size: 0.72rem; font-weight: 800; padding: 1px 6px; border-radius: 6px; color: #fff; cursor: ew-resize; }
|
||||
.pos-marker.start, .pos-marker.start span, .pos-dot.start { background: var(--correct); }
|
||||
.pos-marker.hl, .pos-marker.hl span, .pos-dot.hl { background: var(--coral); }
|
||||
.pos-marker.hl span { top: auto; bottom: -20px; }
|
||||
.pos-bar.auto .pos-marker { opacity: 0.55; }
|
||||
.pos-rows { display: flex; flex-direction: column; gap: 6px; margin-top: 14px; }
|
||||
.pos-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
.pos-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; }
|
||||
@media (max-width: 1100px) { .songs-layout.with-panel { grid-template-columns: 1fr; } .song-panel { position: static; max-height: none; } }
|
||||
@media (max-width: 1300px) { .songs-layout.with-panel.quiz { grid-template-columns: 1fr; } }
|
||||
|
||||
/* ---------------------------------------------------------------- toasts */
|
||||
.toasts { position: fixed; left: 50%; bottom: 24px; transform: translateX(-50%); display: flex; flex-direction: column; gap: 8px; z-index: 100; pointer-events: none; }
|
||||
|
||||
@@ -30,3 +30,4 @@
|
||||
- 2026-10-18 9단계: 차트 수집(멜론 연도별 가요·팝 1984~2025와 실시간, 지니 연도별 1990~2025, 벅스 실시간, TJ 노래방 2024~2025) 140개 차트 10,670줄 → 새 곡 1,798곡, **전체 10,756곡**. 인기도 점수로 난이도 다시 계산(전체 + 장르 11개 + 연대 5개 기준, 전체 기준 1~10단계 333·548·1,059·1,290·1,632·1,605·1,283·1,303·1,185·518곡). 멜론 곡 정보(발매일·장르·가사)와 유튜브 하이라이트는 매일 새벽 나눠서 채움(cron 02:00 차트, 02:20 멜론 1,000곡, 03:15 하이라이트 400곡, 03:55 난이도, 04:10 원곡 찾기 3,000곡). 스포티파이·유튜브 플레이리스트는 하지 않음(키 없음·같은 IP 차단 위험)
|
||||
- 2026-10-18 10단계: axe 검사(`e2e/a11y.e2e.ts`) 첫 화면·대기실·게임·정답 공개·결과·관리자 × PC/휴대폰 × 밝은/어두운 화면 **위반 0**(정답 초록은 글자 대비 때문에 #24733d로 조금 어둡게). 부하 시험(`e2e/load.ts`, 서버 따로 띄움) 100명 한 방: 채팅이 100명 모두에게 닿는 시간 95% 1.8ms·최대 30ms, 20명 동시 8ms, 게임 3문제 모두 같은 시작 시각·정답 블록 9ms 이내, 서버 메모리 최대 102MB
|
||||
|
||||
- 2026-10-22 원곡 찾기 후보 자동 확정 기준 정리(12 문서), 후보 282곡 확정. 제작된 퀴즈 1~3단계: 관리자 퀴즈 편집(곡 추가·검색·순서·복수정답→DB 별칭·수동 저장·설정·공개방식·제한), 곡별 처음·하이라이트 위치 편집기, 방 설정 "제작된 퀴즈 / 직접 선택"과 실제 플레이. 서버 테스트 130개, e2e 전체 통과
|
||||
|
||||
@@ -167,3 +167,19 @@
|
||||
2. 기준은 -18 LUFS(곡의 약 96%가 같은 크기). 전체 소리는 보통 곡 기준 약 4dB(볼륨 0.63배) 작아진다. 끄는 옵션은 두지 않는다(항상 켬)
|
||||
3. 곡 안 구간별(처음부터/하이라이트부터) 보정은 하지 않는다. 유튜브 값은 곡 전체 평균 하나뿐이다
|
||||
4. 자세한 내용은 08 문서 3-1
|
||||
|
||||
## 제작된 퀴즈 (2026-10-22, 사용자 답변 1~9 + 추가 확인 1~3)
|
||||
1. 퀴즈는 관리자만 만든다(관리자 → 퀴즈). 목록 → 퀴즈 추가(이름) → 플레이리스트 가져오기 / 직접 하나씩 추가 → 곡 목록 화면
|
||||
2. 곡 목록: 제목·가수 검색(서버 노래 DB 먼저, 없으면 유튜브 뮤직 노래 검색) 또는 유튜브 주소 붙여넣기로 추가, 끌어서·▲▼·번호로 순서 바꾸기, 제목·가수 고치기, 영상 바꾸기, 복수정답. 서버 DB 곡과 연결된 곡의 복수정답은 저장할 때 DB 별칭(`song_aliases`, source `quiz`)에도 넣는다(검토 없음)
|
||||
3. 저장은 손으로만: 저장 버튼·Ctrl+S. 안 저장했으면 탭 제목 `● 저장 안 됨`과 위쪽 표시, 사이트 안 이동은 [저장하고 나가기/저장하지 않고 나가기/취소], 창 닫기는 브라우저 기본 경고(브라우저가 버튼을 못 바꾸게 함)
|
||||
4. 퀴즈 설정: 이름, 설명, 공개방식, 문제 순서(순서대로/무작위), 재생위치 기본(처음부터/하이라이트부터), 듣고맞출시간, 정답방식·정답인식·힌트·스킵·다시듣기·다음 문제까지·다음문제인원. 방에서 퀴즈를 고르면 이 값이 방 설정으로 들어가고(사이트가 잠근 항목 제외) 방장이 바꿀 수 있다
|
||||
5. 공개방식: 비공개 = 만든 사람 계정으로 방을 만들 때만, 일부공개 = 만든 사람과 관리자, 전체공개 = 모두. 방의 퀴즈 목록에서 비공개·일부공개가 맨 위에 표시와 함께 나온다
|
||||
6. 듣고맞추기에서만 쓴다. 문제 수는 퀴즈의 곡 전부
|
||||
7. 곡마다 "처음"·"하이라이트" 위치를 직접 정한다(영상+소리+큰 재생바, 끌기·지금 위치로·여기서 듣기·±1초). 자동(기본 켜짐) = 처음 0초, 하이라이트는 서버 DB 값(그 영상일 때만, 없으면 곡 길이 30%). 표시를 옮기면 자동이 꺼진다. 연령제한 영상은 서버가 받아 둔 음원으로 듣는다
|
||||
8. 퀴즈당 곡 수·계정당 퀴즈 수 제한은 관리자 → 사이트에서 정하고 기본은 무제한(0)
|
||||
9. 게임 중 "퀴즈 저장·불러오기"(진행 상황 저장)는 이름이 헷갈려서 "진행 저장·불러오기"로 바꿨다
|
||||
10. 다음 단계: 플레이리스트 가져오기(유튜브, 스포티파이는 .6 Lavalink로 — 스포티파이 키로는 플레이리스트를 못 읽음), 전체공개 퀴즈 곡·하이라이트 → 관리자 검토 대기 → 서버 DB, 플레이 통계(힌트·오답·다시듣기·퀴즈별) → 난이도 조정 검토 대기
|
||||
|
||||
## 원곡 찾기 자동 확정 기준 (2026-10-22)
|
||||
1. 제목 일치 + 가수 일치(라틴 악센트 무시 JAŸ-Z=JAY-Z, `및`·with·feat 구분, 앞 The 무시, 확정곡 2곡 이상에서 확인된 한글/영문 이름 짝 태연=TAEYEON) + 길이 차이 15초 이내 + 커버·노래방·라이브·다른 버전 아님. "Radio Edit/Original Version"은 같은 녹음으로 본다
|
||||
2. 쌓인 후보는 `cli.ts reconfirm-youtube`로 저장된 검색 결과를 다시 비교했다(2,313곡 중 282곡 확정). 관리자 원곡 찾기 목록은 채널 이름 대신 실제 가수와 확정 안 된 이유를 보여 준다
|
||||
|
||||
46
packages/shared/src/custom-quiz-schema.ts
Normal file
46
packages/shared/src/custom-quiz-schema.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { z } from 'zod';
|
||||
import { RoomConfigSchema } from './room-config-schema';
|
||||
import { DEFAULT_QUIZ_SETTINGS, QUIZ_ROOM_KEYS, type QuizSettings } from './custom-quiz';
|
||||
|
||||
const roomPart = RoomConfigSchema.pick(Object.fromEntries(QUIZ_ROOM_KEYS.map((k) => [k, true])) as { [K in (typeof QUIZ_ROOM_KEYS)[number]]: true });
|
||||
|
||||
export const QuizSettingsSchema = roomPart.extend({ order: z.enum(['ordered', 'random']) });
|
||||
|
||||
const answers = z.array(z.string().trim().min(1).max(200)).max(30);
|
||||
const sec = z.number().min(0).max(36000).nullable();
|
||||
|
||||
export const QuizItemSchema = z.object({
|
||||
id: z.number().int().positive().optional(),
|
||||
songId: z.number().int().positive().nullable(),
|
||||
videoId: z.string().regex(/^[\w-]{11}$/),
|
||||
title: z.string().trim().min(1).max(200),
|
||||
artist: z.string().trim().min(1).max(200),
|
||||
titleAnswers: answers,
|
||||
artistAnswers: answers,
|
||||
durationSec: z.number().int().min(0).max(36000).nullable(),
|
||||
auto: z.boolean(),
|
||||
startSec: sec,
|
||||
highlightSec: sec,
|
||||
});
|
||||
|
||||
export const QuizSaveSchema = z.object({
|
||||
name: z.string().trim().min(1).max(60),
|
||||
description: z.string().trim().max(500),
|
||||
visibility: z.enum(['private', 'partial', 'public']),
|
||||
settings: QuizSettingsSchema,
|
||||
items: z.array(QuizItemSchema).max(5000),
|
||||
});
|
||||
export type QuizSave = z.infer<typeof QuizSaveSchema>;
|
||||
|
||||
/** Settings saved by an older version: unknown or invalid keys fall back to the defaults. */
|
||||
export function parseQuizSettings(json: unknown): QuizSettings {
|
||||
const merged = { ...DEFAULT_QUIZ_SETTINGS, ...(json && typeof json === 'object' ? json : {}) };
|
||||
const r = QuizSettingsSchema.safeParse(merged);
|
||||
if (r.success) return r.data as QuizSettings;
|
||||
const out: Record<string, unknown> = { ...DEFAULT_QUIZ_SETTINGS };
|
||||
for (const [k, v] of Object.entries(merged)) {
|
||||
const one = QuizSettingsSchema.shape[k as keyof typeof QuizSettingsSchema.shape]?.safeParse(v);
|
||||
if (one?.success) out[k] = one.data;
|
||||
}
|
||||
return out as unknown as QuizSettings;
|
||||
}
|
||||
62
packages/shared/src/custom-quiz.ts
Normal file
62
packages/shared/src/custom-quiz.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* 제작된 퀴즈 (admin-made quizzes): a list of songs with their own answers and start/highlight positions,
|
||||
* plus the room settings a room takes over when it picks the quiz. Plain data for the browser; zod in custom-quiz-schema.ts.
|
||||
*/
|
||||
import { DEFAULT_ROOM_CONFIG, type RoomConfig } from './room-config';
|
||||
|
||||
/** 비공개: only the maker's rooms · 일부공개: the maker's and admins' rooms · 전체공개: everyone. */
|
||||
export const QUIZ_VISIBILITIES = [
|
||||
{ id: 'private', label: '비공개', help: '내 계정으로 방을 만들 때만 고를 수 있어요.' },
|
||||
{ id: 'partial', label: '일부공개', help: '나와 관리자 계정으로 방을 만들 때만 고를 수 있어요.' },
|
||||
{ id: 'public', label: '전체공개', help: '누구나 고를 수 있어요. 곡은 관리자 검토를 거쳐 서버 노래 DB에도 들어가요.' },
|
||||
] as const;
|
||||
export type QuizVisibility = (typeof QUIZ_VISIBILITIES)[number]['id'];
|
||||
|
||||
/** Room settings a quiz carries as its defaults (the host may still change them in the room). */
|
||||
export const QUIZ_ROOM_KEYS = ['listenSec', 'startAt', 'answer', 'strict', 'hint', 'hintVotes', 'skipVotes', 'replayVotes', 'revealSec', 'nextVotes'] as const;
|
||||
export type QuizRoomDefaults = Pick<RoomConfig, (typeof QUIZ_ROOM_KEYS)[number]>;
|
||||
|
||||
export interface QuizSettings extends QuizRoomDefaults {
|
||||
/** 문제 순서: as listed or shuffled each game. */
|
||||
order: 'ordered' | 'random';
|
||||
}
|
||||
|
||||
export const DEFAULT_QUIZ_SETTINGS: QuizSettings = {
|
||||
...(Object.fromEntries(QUIZ_ROOM_KEYS.map((k) => [k, DEFAULT_ROOM_CONFIG[k]])) as QuizRoomDefaults),
|
||||
order: 'ordered',
|
||||
};
|
||||
|
||||
export interface QuizItem {
|
||||
/** Stable id once saved; absent for a song added since the last save. */
|
||||
id?: number;
|
||||
/** The server DB song this item is (its aliases also count as answers), null when it is not in the DB. */
|
||||
songId: number | null;
|
||||
videoId: string;
|
||||
title: string;
|
||||
artist: string;
|
||||
/** Extra accepted answers for this quiz (also added to the DB song's aliases on save). */
|
||||
titleAnswers: string[];
|
||||
artistAnswers: string[];
|
||||
durationSec: number | null;
|
||||
/** 자동: start at 0 and the DB highlight; off = startSec/highlightSec below. */
|
||||
auto: boolean;
|
||||
startSec: number | null;
|
||||
highlightSec: number | null;
|
||||
}
|
||||
|
||||
export interface QuizSummary {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
visibility: QuizVisibility;
|
||||
songs: number;
|
||||
plays: number;
|
||||
ownerId: string;
|
||||
ownerName: string;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export interface QuizDetail extends QuizSummary {
|
||||
settings: QuizSettings;
|
||||
items: QuizItem[];
|
||||
}
|
||||
@@ -5,3 +5,5 @@ export * from './match-key';
|
||||
export * from './room-config';
|
||||
export * from './room-config-schema';
|
||||
export * from './answer';
|
||||
export * from './custom-quiz';
|
||||
export * from './custom-quiz-schema';
|
||||
|
||||
@@ -3,3 +3,4 @@ export * from './nickname';
|
||||
export * from './types';
|
||||
export * from './room-config';
|
||||
export type { ChatLine, RoomView, RoomPlayerView, ServerMessage, GameView, GameScore, GameHistoryItem, GamePhase } from './protocol';
|
||||
export * from './custom-quiz';
|
||||
|
||||
@@ -24,6 +24,8 @@ export const RoomConfigSchema = z.object({
|
||||
nextVotes: z.enum(VOTE_RULES),
|
||||
count: lit(COUNTS),
|
||||
visibility: z.enum(['public', 'private', 'password']),
|
||||
quizId: z.number().int().positive().nullable(),
|
||||
quizName: z.string().max(60),
|
||||
});
|
||||
|
||||
/** Partial update from the host; returns the merged config or an error message. */
|
||||
@@ -34,6 +36,7 @@ export function applyConfigPatch(cur: RoomConfig, patch: unknown): RoomConfig |
|
||||
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 '시작 연도가 끝 연도보다 늦어요.';
|
||||
if (c.quizId && c.mode !== 'listen') return '제작된 퀴즈는 듣고맞추기에서만 할 수 있어요.';
|
||||
return c;
|
||||
}
|
||||
|
||||
|
||||
@@ -49,6 +49,10 @@ export interface RoomConfig {
|
||||
nextVotes: VoteRule;
|
||||
count: (typeof COUNTS)[number];
|
||||
visibility: 'public' | 'private' | 'password';
|
||||
/** 제작된 퀴즈: the chosen quiz (listen mode only, every song of it); null = 직접 선택 (장르·연도·난이도). */
|
||||
quizId: number | null;
|
||||
/** Name of that quiz, filled in by the server for room cards. */
|
||||
quizName: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_ROOM_CONFIG: RoomConfig = {
|
||||
@@ -72,6 +76,8 @@ export const DEFAULT_ROOM_CONFIG: RoomConfig = {
|
||||
nextVotes: '1/3',
|
||||
count: 30,
|
||||
visibility: 'public',
|
||||
quizId: null,
|
||||
quizName: '',
|
||||
};
|
||||
|
||||
/** Level names (docs/04 난이도). */
|
||||
@@ -107,6 +113,12 @@ export function listenLabel(s: number): string {
|
||||
/** 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.quizId) {
|
||||
out.push(`📋 ${c.quizName || '제작된 퀴즈'}`, `🎧 ${listenLabel(c.listenSec)}${c.startAt === 'highlight' ? ' · 하이라이트' : ''}`);
|
||||
if (c.answer !== 'title') out.push(c.answer === 'both' ? '제목+가수' : '가수만');
|
||||
out.push(`공개 ${c.revealSec}초`);
|
||||
return out;
|
||||
}
|
||||
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 ?? '지금'}` : '전체 연도');
|
||||
|
||||
Reference in New Issue
Block a user