제작된 퀴즈 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;
|
||||
|
||||
Reference in New Issue
Block a user