/** * 제작된 퀴즈 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; hints: string; from_file: number; 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[], hints: JSON.parse(r.hints) as string[], fromFile: !!r.from_file, 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(`${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(`${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( 'SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, 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( 'SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, 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(); const ins = this.db.query( `INSERT INTO custom_quiz_items (quiz_id, pos, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, 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 = ?, hints = ?, from_file = ?, 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), JSON.stringify(it.hints ?? []), it.fromFile ? 1 : 0, 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( `${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); } }