/** * 관리자 → 퀴즈 (제작된 퀴즈): 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 { DEFAULT_QUIZ_SETTINGS, 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 { playStats } from '../songs/admin-ops'; import { audioFile, type AudioLinks } from '../songs/audio'; import { getImportJob, startImport, type Lavalink } from '../quizzes/playlist'; import { applyReview, listReviews, pendingCount, rejectReview, syncReviews } from '../quizzes/review'; import { checkEmbed, type EmbedState } from '../collector/oembed'; import { DuelViewsJob, type ViewsSource } from '../quizzes/duel-views'; import { songAnswers } from '../answers'; 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; audio?: AudioLinks; /** 플레이리스트 가져오기 through the .6 Lavalink (LAVALINK_URL / LAVALINK_PW); tests inject a fake fetch. */ lavalink?: Lavalink | null; lavalinkFetch?: typeof fetch; checkEmbed?: (videoId: string) => Promise; importDelayMs?: number; videoOf: (url: string) => Promise<{ id: string; author: string; title: string } | string>; onChange?: () => void; /** 이지선다 조회수 자동: where pairs and view counts come from (tests inject a fake) and the pause between songs. */ viewsSource?: () => Promise; viewsDelayMs?: number; } let searcher: Promise<(q: string) => Promise> | null = null; function defaultSearch(q: string): Promise { // 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/music_quiz/ytm_cookie.txt', () => {}).then((s) => s.searchSongs); return searcher.then((f) => f(q)).catch((e) => { searcher = null; throw e; }); } export function mountQuizAdmin(app: Hono, d: QuizAdminDeps, h: { actor: (c: Context) => string; body: (c: Context) => Promise }) { // 이지선다 조회수 자동: songs left waiting by a restart go on right away const views = new DuelViewsJob(d.db, d.viewsSource, { delayMs: d.viewsDelayMs, retryMs: d.viewsDelayMs, onChange: d.onChange }); views.kick(); const mine = (c: Context) => { 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 }); }); /** 파일로 만들기: a new quiz with the songs read from a file (the browser reads the file; values used as written). */ app.post('/quizzes/file', async (c) => { const p = z .object({ name: z.string().trim().min(1).max(60), kind: z.enum(['normal', 'duel']).default('normal'), items: QuizSaveSchema.shape.items.min(1) }) .safeParse(await h.body(c)); if (!p.success) return c.json({ error: `만들 내용이 올바르지 않아요: ${p.error.issues.slice(0, 3).map((i) => i.path.join('.') || i.message).join(', ')}` }, 400); const duel = p.data.kind === 'duel'; if (duel && p.data.items.length < 2) return c.json({ error: '이지선다 퀴즈에는 곡이 2곡 이상 있어야 해요.' }, 400); const limits = d.limits(); if (limits.maxSongs && p.data.items.length > limits.maxSongs) return c.json({ error: `퀴즈 하나에는 곡을 ${limits.maxSongs}곡까지 넣을 수 있어요.` }, 400); const id = d.quizzes.create(h.actor(c), p.data.name, limits, Date.now(), p.data.kind); if (typeof id === 'string') return c.json({ error: id }, 400); // 자동 (시작·하이라이트 칸이 빈 곡): the item stays unlinked (values as written), so the DB song with this very video // lends its highlight (stored as the song's own positions) and its length (for the 30% rule when there is no highlight) const sameVideo = d.db.query<{ highlight_sec: number | null; duration_sec: number | null }, [string]>( "SELECT highlight_sec, duration_sec FROM songs WHERE youtube_id = ? AND youtube_status = 'matched' AND deleted_at IS NULL ORDER BY highlight_sec IS NULL, id LIMIT 1", ); const items = p.data.items.map((it) => { const s = it.auto ? sameVideo.get(it.videoId) : null; const pos = s?.highlight_sec != null ? { auto: false, startSec: 0, highlightSec: s.highlight_sec } : {}; // 이지선다: a 조회수 written in the file is used as is, the others are fetched (토픽 + MV) after saving return { ...it, ...pos, durationSec: it.durationSec ?? s?.duration_sec ?? null, id: undefined, songId: null, fromFile: true, viewsAuto: null, ...(duel ? {} : { views: null }) }; }); // songs with their own hints: hints come by vote unless the maker changes it in 설정 const settings = { ...DEFAULT_QUIZ_SETTINGS, ...(items.some((it) => it.hints.length) ? { hint: 'manual' as const } : {}) }; const saved = d.quizzes.save(id, { name: p.data.name, description: '', visibility: 'private', settings, items }, limits); if (typeof saved === 'string') return c.json({ error: saved }, 400); d.audit.log(h.actor(c), 'quiz.create', String(id), null, { name: p.data.name, songs: items.length, from: 'file', kind: p.data.kind }); d.onChange?.(); if (duel) views.kick(); return c.json({ id }); }); // ---------------------------------------------------------------- 검토 대기 (전체공개 퀴즈 → 서버 노래 DB) app.get('/reviews/count', (c) => { const levels = playStats(d.db, { sort: 'suggest', size: 1 }).suggestions; const songs = pendingCount(d.db); return c.json({ pending: songs + levels, songs, levels }); }); app.get('/reviews', (c) => c.json({ reviews: listReviews(d.db, c.req.query('status') === 'done' ? 'done' : 'pending'), pending: pendingCount(d.db) })); app.post('/reviews/:id/apply', async (c) => { const id = Number(c.req.param('id')); const p = z .object({ take: z.array(z.enum(['title', 'artist', 'video', 'highlight'])).optional(), song: z .object({ title: z.string().trim().max(200).optional(), artist: z.string().trim().max(200).optional(), year: z.number().int().min(1900).max(2100).nullable().optional(), genres: z.array(z.string().max(30)).max(20).optional(), level: z.number().int().min(1).max(10).nullable().optional(), }) .optional(), }) .safeParse(await h.body(c)); if (!p.success) return c.json({ error: '입력 값이 올바르지 않아요.' }, 400); const r = listReviews(d.db).find((x) => x.id === id); if (!r) return c.json({ error: '이미 처리했거나 없는 검토예요.' }, 404); // a video that becomes the DB video is checked like any admin edit let embed: { author: string; title: string } | undefined; if (r.kind === 'new' || p.data.take?.includes('video')) { const v = await d.videoOf(r.proposal.videoId); if (typeof v === 'string') return c.json({ error: v }, 400); embed = { author: v.author, title: v.title }; } const result = applyReview(d.db, id, p.data, h.actor(c), embed); if (result.startsWith('!')) return c.json({ error: result.slice(1) }, 400); d.audit.log(h.actor(c), 'review.apply', String(id), { quiz: r.quiz.name, song: r.db?.id ?? null }, { result, take: p.data.take ?? null }); d.onChange?.(); return c.json({ ok: true, result, pending: pendingCount(d.db) }); }); app.post('/reviews/:id/reject', (c) => { const id = Number(c.req.param('id')); if (!rejectReview(d.db, id, h.actor(c))) return c.json({ error: '이미 처리했거나 없는 검토예요.' }, 404); d.audit.log(h.actor(c), 'review.reject', String(id), null, null); return c.json({ ok: true, pending: pendingCount(d.db) }); }); // ---------------------------------------------------------------- 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) }); }); /** 플레이리스트 가져오기: starts a background job; the editor polls it. */ app.post('/quizzes/pick/playlist', async (c) => { const p = z.object({ url: z.string().trim().min(1).max(500) }).safeParse(await h.body(c)); if (!p.success) return c.json({ error: '플레이리스트 주소를 넣어 주세요.' }, 400); const lavalink = d.lavalink !== undefined ? d.lavalink : process.env.LAVALINK_URL && process.env.LAVALINK_PW ? { url: process.env.LAVALINK_URL, password: process.env.LAVALINK_PW } : null; const job = await startImport( { db: d.db, lavalink, search: d.searchYoutube ?? defaultSearch, embed: d.checkEmbed ?? ((id) => checkEmbed(id)), delayMs: d.importDelayMs, fetchImpl: d.lavalinkFetch }, h.actor(c), p.data.url, ); if (typeof job === 'string') return c.json({ error: job }, 400); return c.json({ job }); }); app.get('/quizzes/pick/playlist/:job', (c) => { const job = getImportJob(c.req.param('job'), h.actor(c)); return job ? c.json({ job }) : c.json({ error: '가져오기 작업을 찾을 수 없어요.' }, 404); }); /** * 정답 자동 채우기 (파일로 만들기·파일에서 가져오기, docs/13): answers for songs whose 정답 / 가수 정답 cells were empty. * A song the server DB has (same title + artist) lends its aliases too. */ app.post('/quizzes/answers', async (c) => { const p = z .object({ songs: z.array(z.object({ title: z.string().max(200), artist: z.string().max(200).default('') })).max(1000) }) .safeParse(await h.body(c)); if (!p.success) return c.json({ error: '입력 값이 올바르지 않아요.' }, 400); const byKey = d.db.query<{ id: number }, [string]>('SELECT id FROM songs WHERE match_key = ? AND deleted_at IS NULL ORDER BY id LIMIT 1'); const answers = p.data.songs.map((s) => { const songId = s.artist ? (byKey.get(songMatchKey(s.title, s.artist))?.id ?? null) : null; const a = songAnswers(d.db, { ...s, songId }); return { titleAnswers: a.titleAnswers, artistAnswers: a.artistAnswers }; }); return c.json({ answers }); }); /** DB facts of songs just added in the editor (before saving): aliases and the DB highlight for 자동. */ app.get('/quizzes/pick/songs', (c) => { const ids = (c.req.query('ids') ?? '').split(',').map(Number).filter((x) => Number.isInteger(x) && x > 0).slice(0, 500); return c.json({ db: dbFacts(d.db, ids) }); }); // ---------------------------------------------------------------- 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)!; const db = dbFacts(d.db, detail.items.map((i) => i.songId).filter((x): x is number => !!x)); 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); // 전체공개: songs that differ from the server DB wait for an admin (검토 대기) const reviews = syncReviews(d.db, q.id); 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?.(); if (q.kind === 'duel') views.kick(); return c.json({ quiz: saved, reviews }); }); /** 이지선다 조회수 자동: where each fetched song stands (the editor polls this while songs are waiting). */ app.get('/quizzes/:id/views', (c) => { const q = mine(c); if (!q) return c.json({ error: '퀴즈를 찾을 수 없어요.' }, 404); const items = d.quizzes.items(q.id).flatMap((it) => (it.viewsAuto ? [{ id: it.id!, videoId: it.videoId, views: it.views, viewsAuto: it.viewsAuto }] : [])); return c.json({ items }); }); /** 조회수 다시 불러오기: every fetched song of the saved quiz, or the songs named (which then switch from a written number to 자동). */ app.post('/quizzes/:id/views', async (c) => { const q = mine(c); if (!q) return c.json({ error: '퀴즈를 찾을 수 없어요.' }, 404); if (q.kind !== 'duel') return c.json({ error: '이지선다 퀴즈에서만 조회수를 불러와요.' }, 400); const p = z.object({ itemIds: z.array(z.number().int().positive()).max(5000).optional() }).safeParse(await h.body(c)); if (!p.success) return c.json({ error: '입력 값이 올바르지 않아요.' }, 400); const queued = views.refresh(q.id, p.data.itemIds); d.audit.log(h.actor(c), 'quiz.views', String(q.id), null, { queued, items: p.data.itemIds?.length ?? 'all' }); return c.json({ queued }); }); app.delete('/quizzes/:id', (c) => { const q = mine(c); if (!q) return c.json({ error: '퀴즈를 찾을 수 없어요.' }, 404); d.quizzes.remove(q.id); syncReviews(d.db, 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 }); }); } /** DB facts the editor shows next to each linked song: aliases that already count, the DB highlight/length/video for 자동. */ function dbFacts(db: Database, songIds: number[]) { const out: Record = {}; const song = 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 = ?'); const aliases = db.query<{ part: string; alias: string }, [number]>('SELECT part, alias FROM song_aliases WHERE song_id = ?'); for (const id of new Set(songIds)) { const s = song.get(id); if (!s) continue; const al = aliases.all(id); out[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 out; }