/** * 관리자 → 퀴즈 (제작된 퀴즈): 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 { 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'; 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; } 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/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 }) { 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 }); }); // ---------------------------------------------------------------- 검토 대기 (전체공개 퀴즈 → 서버 노래 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); }); // ---------------------------------------------------------------- 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 = {}; 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); // 전체공개: 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?.(); return c.json({ quiz: saved, reviews }); }); 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 }); }); }