제작된 퀴즈 1~3단계: 관리자 → 퀴즈(목록·추가·곡 목록: 서버 DB/유튜브 검색·주소로 추가, 끌어서·▲▼·번호로 순서, 복수정답은 연결된 DB 곡 별칭에도, 영상 바꾸기 / 설정: 설명·공개방식(비공개·일부공개·전체공개)·문제 순서·재생위치 기본·방 규칙). 저장은 버튼·Ctrl+S로만, 안 저장 시 탭 제목·표시·나가기 확인. 곡마다 처음·하이라이트 위치 편집기(영상+큰 재생바, 끌기·지금 위치로·여기서 듣기·±1초, 자동=0초+DB 하이라이트, 연령제한은 받아 둔 음원). 방 설정 '직접 선택 / 제작된 퀴즈'(검색·비공개/일부공개 먼저), 고르면 퀴즈 설정이 방 설정으로, 듣고맞추기·곡 전부, 곡별 위치로 재생, 플레이 수. 퀴즈당 곡 수·계정당 퀴즈 수 제한(사이트 설정, 기본 무제한). '퀴즈 저장·불러오기'는 '진행 저장·불러오기'로 이름 변경
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
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 });
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user