Files
music_quiz/apps/server/src/http/admin-catalog.ts
EJClaw b360ff0eb7 정답: 가수가 제목 정답에 섞이던 것·틀린 한글 발음 정답 고치기 (docs 13)
- 퀴즈 편집 화면: '추가 정답' 한 칸을 '제목 정답'·'가수 정답' 두 칸으로
- 괄호 안이 그 곡 가수 이름이면 제목 정답이 아님: cleanTitle(title, artist) — Crank That (Soulja Boy), 레이 (LAY). 정답 생성·플레이리스트·파일 읽기 모두 가수를 넘김
- 재생목록으로 엑셀 만들기: 정답·가수 정답 칸에 제목·가수를 다시 적지 않음(다른 표기만)
- 한글 발음 정답은 검수한 표기표(answers/lexicon.json: 단어 2,299·제목 74·가수 이름 1,111, 띄어 쓴 꼴과 붙여 쓴 꼴)만. 표기표에 없는 단어가 있으면 발음 정답 없이 unknownWords → 새 곡은 '확인 필요'(발음 확인 필요: …), 관리자 → 제목 정리에서 제목/가수 정답을 더해 적용. 규칙 읽기(en-ko.ts)는 후보·옛 정답 찾기에만
- cli redo-readings [--dry-run] [--old-lexicon]: 옛 규칙(이나 이전 표기표)이 만든 발음 정답만 빼고 표기표 표기로 — DB 별칭(source auto)과 일반 퀴즈 정답, 관리자 별칭·직접 쓴 정답·이지선다는 그대로. cli lexicon-missing: 표기표에 없는 단어와 규칙 후보
- 멜론 차트: 재생이 막힌 곡은 제목 칸에 링크가 없어 가수 링크를 제목으로 읽던 것 → 제목 칸만 읽음. cli fix-melon-titles: 제목이 가수 이름인 멜론 곡을 곡 정보 페이지 제목으로(자기 이름 곡은 그대로), 같은 곡이 이미 있으면 합침, 잘못 찾은 후보 영상은 원곡 찾기로
- decodeEntities: é·° 등(Céline Dion)
- 가수 칸의 따옴표 안을 with로 자르지 않음('Miki Matsubara Official "stay with me"' → 가수 정답 '미')
- 테스트: 표기표 읽기(사용자가 짚은 10곡 포함), 확인 필요로 보내기·정답 더해 적용, 발음 정답 바꾸기(DB·퀴즈·이지선다 제외·이전 표기표), 멜론 제목 칸·곡명·fix-melon-titles, 가수 괄호, 엑셀 칸; e2e quiz(재생목록 엑셀 칸)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 20:44:05 +09:00

371 lines
19 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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 { TITLE_REVIEW_KINDS, applyTitleReviews, listTitleReviews, skipTitleReviews, type TitleReviewKind } from '../songs/title-review';
import {
addGenre,
bulk,
createSong,
duplicates,
importRows,
listArtists,
mergeSongs,
parseCsv,
playStats,
quizStats,
quizItemStats,
levelReviews,
dismissLevel,
restoreSongs,
toCsv,
trashSongs,
updateArtist,
updateGenre,
type BulkAction,
} from '../songs/admin-ops';
import { updateSong } from '../songs/store';
import { REVIEW_TABS, markNoOriginal, reviewCounts, reviewJob, reviewList, unconfirmVideo, type ReviewTab } from '../songs/youtube-review';
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 });
});
// ------------------------------------------------------------ 원곡 찾기 (matcher results, checked while it runs)
// Choosing a video goes through PATCH /songs/:id { youtube } and 다시 찾기 through /songs/bulk { action: 'rematch' }.
app.get('/youtube', (c) => {
const t = c.req.query('tab');
const tab: ReviewTab = (REVIEW_TABS as readonly string[]).includes(t ?? '') ? (t as ReviewTab) : 'candidate';
const list = reviewList(d.db, tab, { q: c.req.query('q')?.trim().slice(0, 100) || undefined, page: Number(c.req.query('page') ?? 0) || 0 });
return c.json({ tab, counts: reviewCounts(d.db), job: reviewJob(d.db), ...list });
});
/** The video before an admin change, for the 기록. */
const videoOf = (id: number) => d.db.query<{ youtube_id: string | null; youtube_status: string; youtube_source: string | null }, [number]>('SELECT youtube_id, youtube_status, youtube_source FROM songs WHERE id = ?').get(id);
app.post('/youtube/:id/unconfirm', (c) => {
const id = Number(c.req.param('id'));
const before = videoOf(id);
if (!unconfirmVideo(d.db, id)) return c.json({ error: '확정된 영상이 있는 노래가 아니에요.' }, 400);
d.audit.log(h.actor(c), 'song.youtube.unconfirm', String(id), before, null);
changed();
return c.json({ ok: true });
});
app.post('/youtube/:id/no-original', (c) => {
const id = Number(c.req.param('id'));
const before = videoOf(id);
if (!markNoOriginal(d.db, id)) return c.json({ error: '노래를 찾을 수 없어요.' }, 404);
d.audit.log(h.actor(c), 'song.youtube.none', String(id), before, null);
changed();
return c.json({ ok: true });
});
// ------------------------------------------------------------ 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 });
});
// 통계 → 퀴즈별
app.get('/stats/quizzes', (c) => c.json({ quizzes: quizStats(d.db) }));
app.get('/stats/quizzes/:id', (c) => c.json({ items: quizItemStats(d.db, Number(c.req.param('id'))) }));
// 검토 대기 → 난이도 조정 (승인은 /stats/apply)
app.get('/level-reviews', (c) => c.json({ rows: levelReviews(d.db) }));
app.post('/level-reviews/:songId/dismiss', (c) => {
const id = Number(c.req.param('songId'));
dismissLevel(d.db, id, h.actor(c));
d.audit.log(h.actor(c), 'song.level.dismiss', String(id), null, null);
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 });
});
// ------------------------------------------------------------ 제목 정리 검토 (docs/13)
const kindIds = TITLE_REVIEW_KINDS.map((k) => k.id) as [TitleReviewKind, ...TitleReviewKind[]];
app.get('/title-reviews', (c) => {
const kind = kindIds.includes(c.req.query('kind') as TitleReviewKind) ? (c.req.query('kind') as TitleReviewKind) : undefined;
const r = listTitleReviews(d.db, { kind, status: c.req.query('status') === 'done' ? 'done' : 'pending', page: Number(c.req.query('page') ?? 0) || 0 });
return c.json({ ...r, kinds: TITLE_REVIEW_KINDS });
});
app.post('/title-reviews/apply', async (c) => {
const p = z
.object({
ids: z.array(z.number().int()).max(5000).optional(),
kind: z.enum(kindIds).optional(),
edits: z
.array(
z.object({
id: z.number().int(),
title: z.string().trim().max(200).optional(),
artist: z.string().trim().max(200).optional(),
titleAnswers: z.array(z.string().trim().min(1).max(200)).max(30).optional(),
artistAnswers: z.array(z.string().trim().min(1).max(200)).max(30).optional(),
}),
)
.max(5000)
.optional(),
})
.refine((x) => x.ids?.length || x.kind, '곡이나 묶음을 골라 주세요.')
.safeParse(await h.body(c));
if (!p.success) return c.json({ error: '곡이나 묶음을 골라 주세요.' }, 400);
const r = applyTitleReviews(d.db, p.data, h.actor(c));
d.audit.log(h.actor(c), 'title-review.apply', p.data.kind ?? null, null, { ids: p.data.ids?.length ?? null, kind: p.data.kind ?? null, applied: r.applied });
d.onCatalogChange?.();
return c.json(r);
});
app.post('/title-reviews/skip', async (c) => {
const p = z.object({ ids: z.array(z.number().int()).min(1).max(5000) }).safeParse(await h.body(c));
if (!p.success) return c.json({ error: '곡을 골라 주세요.' }, 400);
const n = skipTitleReviews(d.db, p.data.ids, h.actor(c));
d.audit.log(h.actor(c), 'title-review.skip', null, null, { ids: p.data.ids.length, skipped: n });
return c.json({ skipped: n });
});
// ------------------------------------------------------------ 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();
const status = d.cookieStatus?.() ?? null;
// without the keeper (dev), the last 원곡 찾기 stopping on the cookie is the only sign
const cookieProblem = status ? status.state === 'expired' || status.state === 'missing' : !!cookie && /cookie|쿠키|로그인/i.test(cookie.log.split('\n').slice(-4).join('\n')) && /stopped/.test(cookie.log);
return c.json({ kinds: d.collect?.kinds ?? [], jobs, cookieProblem, cookie: status });
});
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 });
});
}