8단계 관리자: 노래 추가·초성 검색·일괄 작업·휴지통·가져오기/내보내기·중복 병합·하이라이트 지정, 가수 별칭, 장르, 통계와 난이도 제안, 방 강제 종료, 수집 실행/멈추기, 새 방 기본 설정·잠금 + 출제 기록(song_plays)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 22:27:21 +09:00
parent 7266fc8d25
commit 4165712fac
23 changed files with 2367 additions and 105 deletions

View File

@@ -0,0 +1,281 @@
/**
* Admin API, catalog side (docs/02): 노래 추가·휴지통·일괄 작업·가져오기/내보내기·중복 정리, 가수, 장르, 통계, 방, 수집.
* Mounted by createAdminApp under /api/admin (the role check runs first).
*/
import type { Context, Hono } from 'hono';
import { z } from 'zod';
import type { Role } from '@mq/shared';
import type { AdminDeps } from './admin';
import { genreList, listSongs, type SongFilter } from '../songs/store';
import {
addGenre,
bulk,
createSong,
duplicates,
importRows,
listArtists,
mergeSongs,
parseCsv,
playStats,
restoreSongs,
toCsv,
trashSongs,
updateArtist,
updateGenre,
type BulkAction,
} from '../songs/admin-ops';
import { updateSong } from '../songs/store';
type Env = { Variables: { userId: string | null; role: Role } };
/** Collector processes started from the admin page (docs/02 수집). */
export interface CollectControl {
kinds: { id: string; label: string; limit?: boolean }[];
run(kind: string, limit?: number): string | null;
stop(jobId: number): string | null;
}
export function songFilterFrom(c: Context<Env>): SongFilter {
const q = (k: string) => c.req.query(k) || undefined;
const num = (k: string) => (q(k) ? Number(q(k)) || undefined : undefined);
const flag = (k: string) => (q(k) === undefined ? undefined : q(k) === '1');
const yt = q('youtube');
const sort = q('sort');
return {
q: q('q')?.trim().slice(0, 100),
genres: q('genres')?.split(',').filter(Boolean),
yearFrom: num('yearFrom'),
yearTo: num('yearTo'),
level: num('level'),
youtube: yt && ['matched', 'candidate', 'none', 'dead'].includes(yt) ? (yt as 'matched') : undefined,
source: q('source'),
hidden: flag('hidden'),
lyrics: flag('lyrics'),
highlight: flag('highlight'),
trash: q('trash') === '1',
sort: sort && ['recent', 'year', 'level', 'peak', 'title', 'plays', 'correct'].includes(sort) ? (sort as 'recent') : undefined,
page: num('page'),
};
}
const NewSongSchema = z.object({
title: z.string().trim().min(1).max(200),
artist: z.string().trim().min(1).max(200),
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(),
youtube: z.string().max(200).nullable().optional(),
titleAliases: z.array(z.string().max(200)).max(30).optional(),
});
const BulkSchema = z.object({
ids: z.array(z.number().int().positive()).min(1).max(5000),
action: z.enum(['hide', 'show', 'trash', 'restore', 'rematch', 'level', 'addGenre', 'removeGenre']),
level: z.number().int().min(1).max(10).nullable().optional(),
genre: z.string().max(30).optional(),
});
export function mountCatalogAdmin(
app: Hono<Env>,
d: AdminDeps,
h: { actor: (c: Context<Env>) => string; body: (c: Context<Env>) => Promise<unknown>; videoOf: (url: string) => Promise<{ id: string; author: string; title: string } | string> },
) {
const changed = () => d.onCatalogChange?.();
// ------------------------------------------------------------ songs: add / trash / bulk / export / import / duplicates
app.post('/songs', async (c) => {
const p = NewSongSchema.safeParse(await h.body(c));
if (!p.success) return c.json({ error: '제목과 가수를 넣어 주세요.' }, 400);
const known = new Set(genreList(d.db).map((g) => g.id));
if (p.data.genres?.some((g) => !known.has(g))) return c.json({ error: '없는 장르가 있어요.' }, 400);
let video: { id: string; author: string; title: string } | undefined;
if (p.data.youtube) {
const v = await h.videoOf(p.data.youtube);
if (typeof v === 'string') return c.json({ error: v }, 400);
video = v;
}
const [id, created] = createSong(d.db, { ...p.data, youtubeId: video?.id }, video && { author: video.author, title: video.title });
if (!created) return c.json({ error: '같은 노래가 이미 있어요.', id }, 409);
d.audit.log(h.actor(c), 'song.create', String(id), null, p.data);
changed();
return c.json({ id });
});
app.delete('/songs/:id', (c) => {
const id = Number(c.req.param('id'));
if (!trashSongs(d.db, [id])) return c.json({ error: '노래를 찾을 수 없어요.' }, 404);
d.audit.log(h.actor(c), 'song.trash', String(id), null, null);
changed();
return c.json({ ok: true });
});
app.post('/songs/:id/restore', (c) => {
const id = Number(c.req.param('id'));
if (!restoreSongs(d.db, [id])) return c.json({ error: '휴지통에 없는 노래예요.' }, 404);
d.audit.log(h.actor(c), 'song.restore', String(id), null, null);
changed();
return c.json({ ok: true });
});
app.post('/songs/bulk', async (c) => {
const p = BulkSchema.safeParse(await h.body(c));
if (!p.success) return c.json({ error: '입력 값이 올바르지 않아요.' }, 400);
const { ids, action } = p.data;
let a: BulkAction;
if (action === 'level') a = { action, level: p.data.level ?? null };
else if (action === 'addGenre' || action === 'removeGenre') {
if (!p.data.genre || !genreList(d.db).some((g) => g.id === p.data.genre)) return c.json({ error: '장르를 골라 주세요.' }, 400);
a = { action, genre: p.data.genre };
} else a = { action };
const n = bulk(d.db, ids, a);
d.audit.log(h.actor(c), `song.bulk.${action}`, null, null, { ids: ids.slice(0, 200), count: ids.length, level: p.data.level, genre: p.data.genre });
changed();
return c.json({ changed: n });
});
app.get('/songs/export', (c) => {
type R = { id: number; title: string; artist: string; year: number | null; level: number | null; highlight_sec: number | null; youtube_id: string | null; genres: string[]; hidden: boolean };
const rows = (listSongs(d.db, { ...songFilterFrom(c), all: true }).rows as unknown as R[]).map((r) => ({
...r,
genres: r.genres.join('|'),
youtube: r.youtube_id ? `https://youtu.be/${r.youtube_id}` : '',
hidden: r.hidden ? 1 : 0,
}));
const stamp = new Date().toISOString().slice(0, 10);
if (c.req.query('format') === 'csv') {
return new Response('' + toCsv(rows), { headers: { 'content-type': 'text/csv; charset=utf-8', 'content-disposition': `attachment; filename="songs-${stamp}.csv"` } });
}
return new Response(JSON.stringify(rows.map(({ id, title, artist, year, genres, level, youtube, highlight_sec, hidden }) => ({ id, title, artist, year, genres: genres ? genres.split('|') : [], level, youtube, highlight_sec, hidden: !!hidden }))), {
headers: { 'content-type': 'application/json; charset=utf-8', 'content-disposition': `attachment; filename="songs-${stamp}.json"` },
});
});
/** 가져오기: JSON array or CSV text (`title,artist,year,genres,level,youtube`). Songs already there are left alone. */
app.post('/songs/import', async (c) => {
const p = z.object({ format: z.enum(['json', 'csv']), text: z.string().max(5_000_000) }).safeParse(await h.body(c));
if (!p.success) return c.json({ error: '파일 내용을 읽을 수 없어요.' }, 400);
let raw: Record<string, unknown>[];
try {
raw = p.data.format === 'csv' ? parseCsv(p.data.text) : (JSON.parse(p.data.text) as Record<string, unknown>[]);
if (!Array.isArray(raw)) throw new Error('not an array');
} catch {
return c.json({ error: p.data.format === 'csv' ? 'CSV 형식이 아니에요.' : 'JSON 배열이 아니에요.' }, 400);
}
if (raw.length > 5000) return c.json({ error: '한 번에 5,000곡까지 가져올 수 있어요.' }, 400);
const { rows, skipped } = importRows(raw, new Set(genreList(d.db).map((g) => g.id)));
let added = 0;
let existing = 0;
let badVideo = 0;
for (const r of rows) {
let video: { id: string; author: string; title: string } | undefined;
if (r.youtube) {
const v = await h.videoOf(r.youtube);
if (typeof v === 'string') badVideo++;
else video = v;
}
const [, created] = createSong(d.db, { ...r, youtubeId: video?.id }, video && { author: video.author, title: video.title });
if (created) added++;
else existing++;
}
d.audit.log(h.actor(c), 'song.import', null, null, { format: p.data.format, added, existing, skipped: skipped.length, badVideo });
changed();
return c.json({ added, existing, skipped, badVideo });
});
app.get('/songs/duplicates', (c) => c.json({ groups: duplicates(d.db) }));
app.post('/songs/merge', async (c) => {
const p = z.object({ target: z.number().int().positive(), others: z.array(z.number().int().positive()).min(1).max(50) }).safeParse(await h.body(c));
if (!p.success) return c.json({ error: '입력 값이 올바르지 않아요.' }, 400);
const n = mergeSongs(d.db, p.data.target, p.data.others);
d.audit.log(h.actor(c), 'song.merge', String(p.data.target), null, p.data);
changed();
return c.json({ merged: n });
});
// ------------------------------------------------------------ artists (가수 별칭)
app.get('/artists', (c) => c.json(listArtists(d.db, (c.req.query('q') ?? '').trim().slice(0, 60), Number(c.req.query('page') ?? 0) || 0)));
app.patch('/artists/:id', async (c) => {
const p = z
.object({ name: z.string().trim().min(1).max(100).optional(), kind: z.enum(['solo', 'group', 'unit']).nullable().optional(), aliases: z.array(z.string().max(100)).max(30).optional() })
.safeParse(await h.body(c));
if (!p.success) return c.json({ error: '입력 값이 올바르지 않아요.' }, 400);
const id = Number(c.req.param('id'));
if (!updateArtist(d.db, id, p.data)) return c.json({ error: '가수를 찾을 수 없어요.' }, 404);
d.audit.log(h.actor(c), 'artist.update', String(id), null, p.data);
return c.json({ ok: true });
});
// ------------------------------------------------------------ genres
app.post('/genres', async (c) => {
const p = z.object({ id: z.string().regex(/^[a-z][a-z0-9-]{1,29}$/), name: z.string().trim().min(1).max(30), grp: z.enum(['region', 'style', 'theme']) }).safeParse(await h.body(c));
if (!p.success) return c.json({ error: 'ID는 영문 소문자로 시작하는 2~30자(숫자·- 가능), 이름은 1~30자예요.' }, 400);
const e = addGenre(d.db, p.data);
if (e) return c.json({ error: e }, 400);
d.audit.log(h.actor(c), 'genre.add', p.data.id, null, p.data);
d.onGenresChange?.();
return c.json({ genres: genreList(d.db) });
});
app.patch('/genres/:id', async (c) => {
const p = z.object({ name: z.string().trim().min(1).max(30).optional(), sort: z.number().int().min(0).max(100000).optional(), hidden: z.boolean().optional() }).safeParse(await h.body(c));
if (!p.success) return c.json({ error: '입력 값이 올바르지 않아요.' }, 400);
const id = c.req.param('id');
if (!updateGenre(d.db, id, p.data)) return c.json({ error: '장르를 찾을 수 없어요.' }, 404);
d.audit.log(h.actor(c), 'genre.update', id, null, p.data);
d.onGenresChange?.();
return c.json({ genres: genreList(d.db) });
});
// ------------------------------------------------------------ stats (곡별 출제 수·정답률·평균 정답 시간 → 난이도 제안)
app.get('/stats', (c) => {
const sort = c.req.query('sort');
return c.json(playStats(d.db, { sort: sort && ['plays', 'correct', 'fast', 'suggest'].includes(sort) ? (sort as 'plays') : undefined, page: Number(c.req.query('page') ?? 0) || 0 }));
});
app.post('/stats/apply', async (c) => {
const p = z.object({ songId: z.number().int().positive(), level: z.number().int().min(1).max(10) }).safeParse(await h.body(c));
if (!p.success) return c.json({ error: '입력 값이 올바르지 않아요.' }, 400);
updateSong(d.db, p.data.songId, { level: p.data.level });
d.audit.log(h.actor(c), 'song.level.suggested', String(p.data.songId), null, p.data);
changed();
return c.json({ ok: true });
});
// ------------------------------------------------------------ rooms (진행 중 방, 강제 종료)
app.get('/rooms', (c) => c.json({ rooms: d.rooms?.adminList() ?? [] }));
app.post('/rooms/:code/close', (c) => {
const code = c.req.param('code');
if (!d.rooms?.adminClose(code)) return c.json({ error: '방을 찾을 수 없어요.' }, 404);
d.audit.log(h.actor(c), 'room.close', code, null, null);
return c.json({ ok: true });
});
// ------------------------------------------------------------ collect (수집 실행·멈추기·기록)
app.get('/collect', (c) => {
const jobs = d.db
.query<{ id: number; kind: string; status: string; done: number; total: number; started_at: number; finished_at: number | null }, []>(
'SELECT id, kind, status, done, total, started_at, finished_at FROM collect_jobs ORDER BY id DESC LIMIT 30',
)
.all();
const cookie = d.db.query<{ log: string }, []>("SELECT log FROM collect_jobs WHERE kind = 'match-youtube' ORDER BY id DESC LIMIT 1").get();
return c.json({ kinds: d.collect?.kinds ?? [], jobs, cookieProblem: !!cookie && /cookie|쿠키|로그인/i.test(cookie.log.split('\n').slice(-4).join('\n')) && /stopped/.test(cookie.log) });
});
app.get('/collect/:id', (c) => {
const job = d.db.query<Record<string, unknown>, [number]>('SELECT * FROM collect_jobs WHERE id = ?').get(Number(c.req.param('id')));
return job ? c.json({ job }) : c.json({ error: '작업을 찾을 수 없어요.' }, 404);
});
app.post('/collect/run', async (c) => {
const p = z.object({ kind: z.string().max(40), limit: z.number().int().min(1).max(3000).optional() }).safeParse(await h.body(c));
if (!p.success || !d.collect) return c.json({ error: '입력 값이 올바르지 않아요.' }, 400);
const e = d.collect.run(p.data.kind, p.data.limit);
if (e) return c.json({ error: e }, 400);
d.audit.log(h.actor(c), 'collect.run', p.data.kind, null, p.data);
return c.json({ ok: true });
});
app.post('/collect/:id/stop', (c) => {
const id = Number(c.req.param('id'));
const e = d.collect?.stop(id) ?? '수집 기능이 없어요.';
if (e) return c.json({ error: e }, 400);
d.audit.log(h.actor(c), 'collect.stop', String(id), null, null);
return c.json({ ok: true });
});
}