8단계 관리자: 노래 추가·초성 검색·일괄 작업·휴지통·가져오기/내보내기·중복 병합·하이라이트 지정, 가수 별칭, 장르, 통계와 난이도 제안, 방 강제 종료, 수집 실행/멈추기, 새 방 기본 설정·잠금 + 출제 기록(song_plays)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
216
apps/server/src/admin-catalog.test.ts
Normal file
216
apps/server/src/admin-catalog.test.ts
Normal file
@@ -0,0 +1,216 @@
|
||||
/** 관리자 완성 (docs/02, 10 8단계): songs add/trash/bulk/import/export/merge, artists, genres, stats, rooms, collect, room defaults. */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Catalog } from './collector/catalog';
|
||||
import { quizSong } from './songs/quiz';
|
||||
import { isCorrect } from '@mq/shared';
|
||||
import { suggestLevel } from './songs/admin-ops';
|
||||
import { Client, api, boot, discordLogin, guest, TEST_SUPERADMINS } from './test-utils';
|
||||
|
||||
const fakeDiscord = async (code: string) => ({ id: code, username: 'u', global_name: `관리${code.slice(-2)}`, avatar: null });
|
||||
const fakeEmbed = async (id: string) => (id === 'noembed0000' ? ({ state: 'noembed' } as const) : ({ state: 'ok', author: 'X - Topic', title: `t${id}` } as const));
|
||||
|
||||
let s: ReturnType<typeof boot>;
|
||||
afterEach(async () => s && (await s.stop()));
|
||||
|
||||
async function admin(extra: Parameters<typeof boot>[0] = {}) {
|
||||
const runs: { kind: string; limit?: number }[] = [];
|
||||
s = boot(
|
||||
{
|
||||
discordExchange: fakeDiscord,
|
||||
checkEmbed: fakeEmbed,
|
||||
collect: {
|
||||
kinds: [{ id: 'match-youtube', label: '유튜브 원곡 찾기', limit: true }],
|
||||
run: (kind, limit) => (runs.push({ kind, limit }), null),
|
||||
stop: () => null,
|
||||
},
|
||||
...extra,
|
||||
},
|
||||
{ DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' },
|
||||
);
|
||||
const { cookie } = await discordLogin(s.base, TEST_SUPERADMINS[0]);
|
||||
const call = (path: string, init: RequestInit = {}) => api(s.base, `/api/admin${path}`, { ...init, cookie: cookie! });
|
||||
return { call, runs, cookie: cookie! };
|
||||
}
|
||||
|
||||
describe('admin songs', () => {
|
||||
test('add (duplicate → 409, no-embed video refused), trash → 휴지통 → restore', async () => {
|
||||
const { call } = await admin();
|
||||
const add = await call('/songs', { method: 'POST', body: JSON.stringify({ title: '사건의 지평선', artist: '윤하', year: 2022, genres: ['ballad'], level: 2, youtube: 'https://youtu.be/abcdefghijk' }) });
|
||||
expect(add.res.status).toBe(200);
|
||||
const id = add.body.id;
|
||||
const d = (await call(`/songs/${id}`)).body;
|
||||
expect(d.song).toMatchObject({ title: '사건의 지평선', artist: '윤하', year: 2022, youtube_id: 'abcdefghijk', youtube_status: 'matched' });
|
||||
expect(d.levels).toEqual([expect.objectContaining({ scope: 'all', level: 2, source: 'admin' })]);
|
||||
expect((await call('/songs', { method: 'POST', body: JSON.stringify({ title: '사건의 지평선', artist: '윤하' }) })).res.status).toBe(409);
|
||||
expect((await call('/songs', { method: 'POST', body: JSON.stringify({ title: '다른곡', artist: '윤하', youtube: 'noembed0000' }) })).body.error).toContain('퍼가기');
|
||||
// 초성 검색
|
||||
expect((await call('/songs?q=ㅅㄱㅇㅈㅍㅅ')).body.rows.map((r: any) => r.id)).toEqual([id]);
|
||||
expect((await call(`/songs/${id}`, { method: 'DELETE' })).res.status).toBe(200);
|
||||
expect((await call('/songs?q=사건')).body.total).toBe(0);
|
||||
expect((await call('/songs?trash=1')).body.rows.map((r: any) => r.id)).toEqual([id]);
|
||||
expect((await call(`/songs/${id}/restore`, { method: 'POST' })).res.status).toBe(200);
|
||||
expect((await call('/songs?q=사건')).body.total).toBe(1);
|
||||
});
|
||||
|
||||
test('bulk: hide, level, add/remove genre, rematch; highlight filter', async () => {
|
||||
const { call } = await admin();
|
||||
const ids: number[] = [];
|
||||
for (const t of ['하나', '둘', '셋']) ids.push((await call('/songs', { method: 'POST', body: JSON.stringify({ title: t, artist: '가수', youtube: `vid${t.length}abcdefg`.slice(0, 11) }) })).body.id);
|
||||
const b = (action: string, extra = {}) => call('/songs/bulk', { method: 'POST', body: JSON.stringify({ ids: ids.slice(0, 2), action, ...extra }) });
|
||||
expect((await b('hide')).body.changed).toBe(2);
|
||||
expect((await call('/songs?hidden=1')).body.total).toBe(2);
|
||||
await b('level', { level: 7 });
|
||||
expect((await call('/songs?level=7')).body.total).toBe(2);
|
||||
await b('addGenre', { genre: 'rock' });
|
||||
expect((await call('/songs?genres=rock')).body.total).toBe(2);
|
||||
await b('removeGenre', { genre: 'rock' });
|
||||
expect((await call('/songs?genres=rock')).body.total).toBe(0);
|
||||
expect((await b('addGenre', { genre: 'nope' })).res.status).toBe(400);
|
||||
await b('rematch');
|
||||
expect((await call(`/songs/${ids[0]}`)).body.song).toMatchObject({ youtube_status: 'none', youtube_id: null, youtube_source: null });
|
||||
await call(`/songs/${ids[2]}`, { method: 'PATCH', body: JSON.stringify({ highlightSec: 61.5 }) });
|
||||
expect((await call('/songs?highlight=1')).body.rows.map((r: any) => r.id)).toEqual([ids[2]]);
|
||||
});
|
||||
|
||||
test('export CSV/JSON and import CSV round trip; bad rows are skipped', async () => {
|
||||
const { call } = await admin();
|
||||
await call('/songs', { method: 'POST', body: JSON.stringify({ title: '쉼표, 그리고 "따옴표"', artist: '가수A', year: 2001, genres: ['ballad', 'kpop'], level: 3 }) });
|
||||
const r = await call('/songs/export?format=csv');
|
||||
expect(r.res.headers.get('content-type')).toContain('text/csv');
|
||||
const text = String(r.body);
|
||||
expect(text).toContain('"쉼표, 그리고 ""따옴표"""');
|
||||
const json = (await call('/songs/export')).body;
|
||||
expect(json[0]).toMatchObject({ title: '쉼표, 그리고 "따옴표"', artist: '가수A', year: 2001, level: 3 });
|
||||
expect(json[0].genres.sort()).toEqual(['ballad', 'kpop']);
|
||||
// import into the same DB: the existing song is recognised, a new one is added, a row without an artist is skipped
|
||||
const incoming = text + '\n,새노래,가수B,1999,dance,4,,,0\n,빈가수,,2000,,,,,0\n';
|
||||
const imp = await call('/songs/import', { method: 'POST', body: JSON.stringify({ format: 'csv', text: incoming }) });
|
||||
expect(imp.body).toMatchObject({ added: 1, existing: 1, skipped: [3] });
|
||||
const added = (await call('/songs?q=새노래')).body.rows[0];
|
||||
expect(added).toMatchObject({ year: 1999, level: 4, genres: ['dance'] });
|
||||
// the song that was already there is untouched (no extra source, genres as they were)
|
||||
const kept = (await call('/songs?q=따옴표')).body.rows[0];
|
||||
expect(kept.sources).toEqual(['admin']);
|
||||
expect(kept.genres.sort()).toEqual(['ballad', 'kpop']);
|
||||
const bad = await call('/songs/import', { method: 'POST', body: JSON.stringify({ format: 'json', text: '{"a":1}' }) });
|
||||
expect(bad.body.error).toContain('JSON');
|
||||
});
|
||||
|
||||
test('duplicates are grouped by the normalized key and merged into one (sources, aliases, plays move over)', async () => {
|
||||
const { call } = await admin();
|
||||
const cat = new Catalog(s.db);
|
||||
const [a] = cat.upsert({ title: '광', artists: [{ name: 'SG워너비' }], source: 'sta', ref: '1' });
|
||||
// a second row with the same key (an import that missed the match)
|
||||
const b = Number(s.db.query("INSERT INTO songs (title, artist, match_key, created_at, updated_at, youtube_status, youtube_id, embeddable) VALUES ('광 (狂)', 'SG워너비', (SELECT match_key FROM songs WHERE id = ?), 0, 0, 'matched', 'VO88htcm09E', 1)").run(a!).lastInsertRowid);
|
||||
s.db.query("INSERT INTO song_aliases (song_id, part, alias) VALUES (?, 'title', 'Crazy')").run(b);
|
||||
const groups = (await call('/songs/duplicates')).body.groups;
|
||||
expect(groups[0].songs.map((x: any) => x.id).sort()).toEqual([a, b].sort());
|
||||
expect((await call('/songs/merge', { method: 'POST', body: JSON.stringify({ target: a, others: [b] }) })).body.merged).toBe(1);
|
||||
const merged = (await call(`/songs/${a}`)).body;
|
||||
expect(merged.song).toMatchObject({ youtube_id: 'VO88htcm09E', youtube_status: 'matched' });
|
||||
expect(merged.aliases.map((x: any) => x.alias)).toContain('Crazy');
|
||||
expect((await call('/songs/duplicates')).body.groups).toEqual([]);
|
||||
expect((await call('/songs?trash=1')).body.rows.map((r: any) => r.id)).toEqual([b]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin artists, genres, stats, rooms, collect, room defaults', () => {
|
||||
test('artist aliases count as the artist answer', async () => {
|
||||
const { call } = await admin();
|
||||
const cat = new Catalog(s.db);
|
||||
const [id] = cat.upsert({ title: '좋은 날', artists: [{ name: '아이유' }], source: 't', ref: '1' });
|
||||
const artist = (await call('/artists?q=아이유')).body.rows[0];
|
||||
expect(artist).toMatchObject({ name: '아이유', songs: 1, aliases: [] });
|
||||
await call(`/artists/${artist.id}`, { method: 'PATCH', body: JSON.stringify({ aliases: ['IU', '이지은'], kind: 'solo' }) });
|
||||
expect((await call('/artists?q=이지은')).body.rows[0].aliases).toEqual(['IU', '이지은']);
|
||||
const song = quizSong(s.db, id!)!;
|
||||
expect(isCorrect('iu', song, 'artist', { space: true, number: true, symbol: true })).toBe(true);
|
||||
expect(isCorrect('이지은', song, 'artist', { space: true, number: true, symbol: true })).toBe(true);
|
||||
});
|
||||
|
||||
test('genres: add, rename, hide (hidden genres leave the room form)', async () => {
|
||||
const { call } = await admin();
|
||||
expect((await call('/genres', { method: 'POST', body: JSON.stringify({ id: 'citypop', name: '시티팝', grp: 'style' }) })).res.status).toBe(200);
|
||||
expect((await call('/genres', { method: 'POST', body: JSON.stringify({ id: 'citypop', name: '또', grp: 'style' }) })).body.error).toContain('이미');
|
||||
await call('/genres/citypop', { method: 'PATCH', body: JSON.stringify({ name: '시티 팝' }) });
|
||||
let meta = (await api(s.base, '/api/catalog/meta')).body.genres;
|
||||
expect(meta.find((g: any) => g.id === 'citypop').name).toBe('시티 팝');
|
||||
await call('/genres/citypop', { method: 'PATCH', body: JSON.stringify({ hidden: true }) });
|
||||
meta = (await api(s.base, '/api/catalog/meta')).body.genres;
|
||||
expect(meta.some((g: any) => g.id === 'citypop')).toBe(false);
|
||||
});
|
||||
|
||||
test('stats from plays: correct rate, average time, level suggestion and applying it', async () => {
|
||||
const { call } = await admin();
|
||||
const cat = new Catalog(s.db);
|
||||
const [easy] = cat.upsert({ title: '쉬운곡', artists: [{ name: '가' }], source: 't', ref: '1' });
|
||||
const [hard] = cat.upsert({ title: '어려운곡', artists: [{ name: '나' }], source: 't', ref: '2' });
|
||||
cat.autoLevel(easy!, 'all', 5);
|
||||
cat.autoLevel(hard!, 'all', 5);
|
||||
const play = (song: number, winner: string | null, ms: number | null) =>
|
||||
s.db.query('INSERT INTO song_plays (song_id, game_id, played_at, players, winner_id, ms, how) VALUES (?, ?, ?, 3, ?, ?, ?)').run(song, 'g1', Date.now(), winner, ms, winner ? 'correct' : 'timeout');
|
||||
for (let i = 0; i < 6; i++) play(easy!, 'u1', 3000);
|
||||
for (let i = 0; i < 6; i++) play(hard!, i === 0 ? 'u1' : null, i === 0 ? 40000 : null);
|
||||
const st = (await call('/stats')).body;
|
||||
expect(st.today).toEqual({ plays: 12, games: 1 });
|
||||
expect(st.suggestions).toBe(2);
|
||||
const e = st.rows.find((r: any) => r.id === easy);
|
||||
expect(e).toMatchObject({ plays: 6, correct: 6, avg_ms: 3000, level: 5, suggest: 4 });
|
||||
expect(st.rows.find((r: any) => r.id === hard)).toMatchObject({ correct: 1, suggest: 6 });
|
||||
await call('/stats/apply', { method: 'POST', body: JSON.stringify({ songId: easy, level: 4 }) });
|
||||
expect((await call('/stats')).body.rows.find((r: any) => r.id === easy)).toMatchObject({ level: 4 });
|
||||
expect(suggestLevel(1, 10, 10, 1000)).toBeNull();
|
||||
expect(suggestLevel(5, 4, 4, 1000)).toBeNull(); // too few plays
|
||||
});
|
||||
|
||||
test('rooms: the admin sees private rooms too and can close one; players are told', async () => {
|
||||
const { call } = await admin();
|
||||
const g = await guest(s.base, '손님');
|
||||
const code = (await api(s.base, '/api/rooms', { method: 'POST', cookie: g.cookie, body: JSON.stringify({ config: { visibility: 'private' } }) })).body.code;
|
||||
const cl = await new Client(s.base, g.cookie).connect();
|
||||
cl.send({ t: 'join', code });
|
||||
await cl.waitFor((m) => m.t === 'room');
|
||||
const list = (await call('/rooms')).body.rooms;
|
||||
expect(list).toEqual([expect.objectContaining({ code, visibility: 'private', status: 'lobby', players: [expect.objectContaining({ nickname: '손님', online: true })] })]);
|
||||
expect((await call(`/rooms/${code}/close`, { method: 'POST' })).res.status).toBe(200);
|
||||
await cl.waitFor((m) => m.t === 'left' && m.reason === 'admin');
|
||||
expect((await api(s.base, `/api/rooms/${code}`)).res.status).toBe(404);
|
||||
cl.close();
|
||||
});
|
||||
|
||||
test('collect: run from the page, job list, stop', async () => {
|
||||
const { call, runs } = await admin();
|
||||
const c = (await call('/collect')).body;
|
||||
expect(c.kinds.map((k: any) => k.id)).toEqual(['match-youtube']);
|
||||
expect((await call('/collect/run', { method: 'POST', body: JSON.stringify({ kind: 'match-youtube', limit: 50 }) })).res.status).toBe(200);
|
||||
expect(runs).toEqual([{ kind: 'match-youtube', limit: 50 }]);
|
||||
});
|
||||
|
||||
test('collect control: one run per kind, stop marks a dead process stopped', async () => {
|
||||
s = boot();
|
||||
const { collectorControl } = await import('./collector/control');
|
||||
const ctl = collectorControl(s.db, () => {}, [{ id: 'sleep', label: 't' }], () => ['stats']);
|
||||
const id = Number(s.db.query("INSERT INTO collect_jobs (kind, status, total, started_at, pid) VALUES ('sleep', 'running', 0, ?, ?)").run(Date.now(), process.pid).lastInsertRowid);
|
||||
expect(ctl.run('sleep')).toContain('이미');
|
||||
expect(ctl.run('nope')).toContain('없는');
|
||||
s.db.query('UPDATE collect_jobs SET pid = 999999 WHERE id = ?').run(id);
|
||||
expect(ctl.stop(id)).toBeNull();
|
||||
expect(s.db.query<{ status: string }, [number]>('SELECT status FROM collect_jobs WHERE id = ?').get(id)!.status).toBe('stopped');
|
||||
expect(ctl.stop(id)).toContain('돌고 있는');
|
||||
});
|
||||
|
||||
test('site room defaults apply to new rooms; locked settings cannot be changed by hosts', async () => {
|
||||
const { call } = await admin();
|
||||
const site = (await call('/site')).body.site;
|
||||
expect((await call('/site', { method: 'PUT', body: JSON.stringify({ ...site, roomDefaults: { level: 2, listenSec: 10, mode: 'nonsense' }, roomLocks: ['level'] }) })).res.status).toBe(200);
|
||||
const g = await guest(s.base, '방장');
|
||||
const code = (await api(s.base, '/api/rooms', { method: 'POST', cookie: g.cookie, body: JSON.stringify({ config: { level: 9 } }) })).body.code;
|
||||
const cl = await new Client(s.base, g.cookie).connect();
|
||||
cl.send({ t: 'join', code });
|
||||
const r = (await cl.waitFor((m) => m.t === 'room')) as any;
|
||||
expect(r.room.config).toMatchObject({ level: 2, listenSec: 10, mode: 'listen' }); // invalid default ignored, lock wins over the create request
|
||||
cl.send({ t: 'config', patch: { level: 4 } });
|
||||
expect(((await cl.waitFor((m) => m.t === 'error')) as any).message).toContain('고정');
|
||||
cl.close();
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,10 @@ export const SiteSettingsSchema = z.object({
|
||||
chatBurst: z.number().int().min(1).max(100).default(12),
|
||||
/** One question's time limit for short clips (docs/05 문제 진행: 기본 60초, 관리자 설정). */
|
||||
questionLimitSec: z.number().int().min(10).max(600).default(60),
|
||||
/** 새 방의 기본 설정 (docs/04 설정 저장): a partial room config, validated against the room schema when saved. */
|
||||
roomDefaults: z.record(z.string(), z.unknown()).default({}),
|
||||
/** 잠금: settings hosts cannot change (they stay at the default). */
|
||||
roomLocks: z.array(z.string().max(30)).max(30).default([]),
|
||||
});
|
||||
export type SiteSettings = z.infer<typeof SiteSettingsSchema>;
|
||||
|
||||
|
||||
@@ -85,6 +85,9 @@ export class Catalog {
|
||||
}
|
||||
}
|
||||
|
||||
/** The job of this process, for a clean stop on SIGTERM (admin 수집 → 멈추기). */
|
||||
export let currentJob: Job | null = null;
|
||||
|
||||
export class Job {
|
||||
readonly id: number;
|
||||
constructor(
|
||||
@@ -94,7 +97,8 @@ export class Job {
|
||||
) {
|
||||
// Only one runner per kind: a row left 'running' by a killed process is stale.
|
||||
this.db.query("UPDATE collect_jobs SET status = 'stopped', finished_at = ? WHERE kind = ? AND status = 'running'").run(Date.now(), kind);
|
||||
this.id = Number(this.db.query("INSERT INTO collect_jobs (kind, status, total, started_at) VALUES (?, 'running', ?, ?)").run(kind, total, Date.now()).lastInsertRowid);
|
||||
this.id = Number(this.db.query("INSERT INTO collect_jobs (kind, status, total, started_at, pid) VALUES (?, 'running', ?, ?, ?)").run(kind, total, Date.now(), process.pid).lastInsertRowid);
|
||||
currentJob = this;
|
||||
}
|
||||
progress(done: number, total?: number): void {
|
||||
this.db.query('UPDATE collect_jobs SET done = ?, total = COALESCE(?, total) WHERE id = ?').run(done, total ?? null, this.id);
|
||||
|
||||
@@ -13,6 +13,7 @@ import { importSta } from './sta';
|
||||
import { matchYoutube } from './match-youtube';
|
||||
import { pickSearcher } from './ytmusic';
|
||||
import { catalogStats } from '../songs/store';
|
||||
import { currentJob } from './catalog';
|
||||
|
||||
const [cmd, ...rest] = process.argv.slice(2);
|
||||
const flag = (name: string) => {
|
||||
@@ -22,6 +23,13 @@ const flag = (name: string) => {
|
||||
const dbPath = process.env.DB_PATH ?? './data/app.db';
|
||||
const rawDir = process.env.RAW_DIR ?? join(dbPath, '..', 'raw');
|
||||
const db = openDb(dbPath);
|
||||
// 멈추기 from the admin page (or docker stop): record it and leave.
|
||||
process.on('SIGTERM', () => {
|
||||
currentJob?.log('stopped by admin');
|
||||
currentJob?.finish('stopped');
|
||||
db.close();
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
switch (cmd) {
|
||||
case 'import-norabose':
|
||||
|
||||
52
apps/server/src/collector/control.ts
Normal file
52
apps/server/src/collector/control.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* 관리자 → 수집: starts the collector CLI as its own process (same container, same DB in WAL mode) and stops it with SIGTERM.
|
||||
* One run per kind; the job row carries the process id, so runs started by cron can be stopped too.
|
||||
*/
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { join } from 'node:path';
|
||||
import type { CollectControl } from '../http/admin-catalog';
|
||||
import type { LogFn } from '../server';
|
||||
|
||||
export const COLLECT_KINDS: CollectControl['kinds'] = [{ id: 'match-youtube', label: '유튜브 원곡 찾기', limit: true }];
|
||||
|
||||
const CLI = join(import.meta.dir, 'cli.ts');
|
||||
|
||||
function alive(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function collectorControl(db: Database, log: LogFn, kinds = COLLECT_KINDS, args: (kind: string, limit?: number) => string[] = defaultArgs): CollectControl {
|
||||
const running = (kind: string) =>
|
||||
db.query<{ id: number; pid: number | null }, [string]>("SELECT id, pid FROM collect_jobs WHERE kind = ? AND status = 'running' ORDER BY id DESC LIMIT 1").get(kind);
|
||||
return {
|
||||
kinds,
|
||||
run(kind, limit) {
|
||||
const k = kinds.find((x) => x.id === kind);
|
||||
if (!k) return '없는 작업이에요.';
|
||||
const r = running(kind);
|
||||
if (r && r.pid && alive(r.pid)) return '이미 돌고 있는 작업이에요. 끝나거나 멈춘 뒤에 다시 실행해 주세요.';
|
||||
const proc = Bun.spawn([process.execPath, CLI, ...args(kind, k.limit ? limit : undefined)], { stdout: 'ignore', stderr: 'ignore', stdin: 'ignore', env: process.env });
|
||||
proc.unref();
|
||||
log('info', 'collector started', { kind, limit, pid: proc.pid });
|
||||
return null;
|
||||
},
|
||||
stop(jobId) {
|
||||
const j = db.query<{ status: string; pid: number | null }, [number]>('SELECT status, pid FROM collect_jobs WHERE id = ?').get(jobId);
|
||||
if (!j) return '작업을 찾을 수 없어요.';
|
||||
if (j.status !== 'running') return '돌고 있는 작업이 아니에요.';
|
||||
if (j.pid && alive(j.pid)) process.kill(j.pid, 'SIGTERM');
|
||||
else db.query("UPDATE collect_jobs SET status = 'stopped', finished_at = ? WHERE id = ?").run(Date.now(), jobId);
|
||||
return null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function defaultArgs(kind: string, limit?: number): string[] {
|
||||
if (kind === 'match-youtube') return ['match-youtube', '--limit', String(limit ?? 300), '--require-cookie'];
|
||||
return [kind, ...(limit ? ['--limit', String(limit)] : [])];
|
||||
}
|
||||
16
apps/server/src/db/migrations/005_plays_admin.sql
Normal file
16
apps/server/src/db/migrations/005_plays_admin.sql
Normal file
@@ -0,0 +1,16 @@
|
||||
-- 통계 (docs/02 관리자 → 통계): one row per question played. Difficulty suggestions come from these.
|
||||
CREATE TABLE song_plays (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
song_id INTEGER NOT NULL REFERENCES songs(id) ON DELETE CASCADE,
|
||||
game_id TEXT NOT NULL,
|
||||
played_at INTEGER NOT NULL,
|
||||
players INTEGER NOT NULL,
|
||||
winner_id TEXT,
|
||||
ms INTEGER,
|
||||
how TEXT NOT NULL -- correct | skip | timeout
|
||||
);
|
||||
CREATE INDEX song_plays_song ON song_plays(song_id);
|
||||
CREATE INDEX song_plays_at ON song_plays(played_at);
|
||||
|
||||
-- The collector writes its process id so the admin page can stop it.
|
||||
ALTER TABLE collect_jobs ADD COLUMN pid INTEGER;
|
||||
@@ -85,6 +85,7 @@ export class Game {
|
||||
private timer: ReturnType<typeof setInterval> | null = null;
|
||||
/** Songs this game asked, for the room's "last 3 games" list. */
|
||||
private asked: number[] = [];
|
||||
readonly gameId = crypto.randomUUID();
|
||||
|
||||
constructor(
|
||||
private room: Room,
|
||||
@@ -314,6 +315,14 @@ export class Game {
|
||||
});
|
||||
this.room.quiz.played.push(s.id);
|
||||
this.asked.push(s.id);
|
||||
try {
|
||||
// 통계 (admin): never let a stats write break the game.
|
||||
this.room.deps.db
|
||||
.query('INSERT INTO song_plays (song_id, game_id, played_at, players, winner_id, ms, how) VALUES (?, ?, ?, ?, ?, ?, ?)')
|
||||
.run(s.id, this.gameId, now, Math.max(1, this.active().length), winner, ms, how === 'end' ? 'timeout' : how);
|
||||
} catch {
|
||||
/* stats only */
|
||||
}
|
||||
const answer = `${s.title} - ${s.artist}`;
|
||||
if (winner) this.room.post({ userId: winner, text: chat!.text, n: chat!.n, answer: { text: answer } });
|
||||
else this.room.post({ userId: null, text: how === 'skip' ? '스킵했어요 · 정답자 없음' : '시간이 다 됐어요 · 정답자 없음', answer: { text: answer, none: true } });
|
||||
|
||||
281
apps/server/src/http/admin-catalog.ts
Normal file
281
apps/server/src/http/admin-catalog.ts
Normal 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 });
|
||||
});
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { toPublicUser, type Users } from '../auth/users';
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { catalogStats, genreList, getSong, listSongs, updateSong } from '../songs/store';
|
||||
import { checkEmbed, type EmbedState } from '../collector/oembed';
|
||||
import { mountCatalogAdmin, songFilterFrom, type CollectControl } from './admin-catalog';
|
||||
|
||||
export interface AdminDeps {
|
||||
users: Users;
|
||||
@@ -23,6 +24,13 @@ export interface AdminDeps {
|
||||
checkEmbed?: (videoId: string) => Promise<EmbedState>;
|
||||
/** Lobby song counts depend on the catalog. */
|
||||
onCatalogChange?: () => void;
|
||||
/** Genre names shown on room cards. */
|
||||
onGenresChange?: () => void;
|
||||
rooms?: {
|
||||
adminList(): unknown[];
|
||||
adminClose(code: string): boolean;
|
||||
};
|
||||
collect?: CollectControl;
|
||||
}
|
||||
|
||||
type Env = { Variables: { userId: string | null; role: Role } };
|
||||
@@ -93,27 +101,21 @@ export function createAdminApp(d: AdminDeps) {
|
||||
// ------------------------------------------------------------ songs (docs/02 노래 관리)
|
||||
app.get('/catalog', (c) => c.json(catalogStats(d.db)));
|
||||
app.get('/genres', (c) => c.json({ genres: genreList(d.db) }));
|
||||
app.get('/songs', (c) => {
|
||||
const q = (k: string) => c.req.query(k) || undefined;
|
||||
const num = (k: string) => (q(k) ? Number(q(k)) || undefined : undefined);
|
||||
const yt = q('youtube');
|
||||
const sort = q('sort');
|
||||
return c.json(
|
||||
listSongs(d.db, {
|
||||
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: q('hidden') === undefined ? undefined : q('hidden') === '1',
|
||||
lyrics: q('lyrics') === undefined ? undefined : q('lyrics') === '1',
|
||||
sort: sort && ['recent', 'year', 'level', 'peak', 'title'].includes(sort) ? (sort as 'recent') : undefined,
|
||||
page: num('page'),
|
||||
}),
|
||||
);
|
||||
// Static paths (/songs/export, /songs/bulk …) before /songs/:id.
|
||||
mountCatalogAdmin(app, d, {
|
||||
actor,
|
||||
body,
|
||||
videoOf: async (url) => {
|
||||
const id = parseVideoId(url);
|
||||
if (!id) return '유튜브 주소를 알아볼 수 없어요. https://youtu.be/… 형식으로 넣어 주세요.';
|
||||
const e = await (d.checkEmbed ?? checkEmbed)(id);
|
||||
if (e.state === 'noembed') return '이 영상은 다른 사이트에서 재생할 수 없게 막혀 있어요(퍼가기 금지). 다른 영상을 골라 주세요.';
|
||||
if (e.state === 'dead') return '없는 영상이에요.';
|
||||
if (e.state === 'error') return '유튜브 확인에 실패했어요. 잠시 후 다시 시도해 주세요.';
|
||||
return { id, author: e.author, title: e.title };
|
||||
},
|
||||
});
|
||||
app.get('/songs', (c) => c.json(listSongs(d.db, songFilterFrom(c))));
|
||||
app.get('/songs/:id', (c) => {
|
||||
const r = getSong(d.db, Number(c.req.param('id')));
|
||||
return r ? c.json(r) : c.json({ error: '노래를 찾을 수 없어요.' }, 404);
|
||||
|
||||
@@ -156,6 +156,8 @@ export class RoomManager {
|
||||
/** Question time limit for short clips (site setting). */
|
||||
limitSec?: () => number;
|
||||
timing?: Partial<GameTiming>;
|
||||
/** Site room defaults and locked settings (admin 사이트 설정). */
|
||||
roomPolicy?: () => { defaults: Record<string, unknown>; locks: string[] };
|
||||
},
|
||||
) {
|
||||
this.saved = new SavedQuizzes(deps.db);
|
||||
@@ -169,9 +171,23 @@ export class RoomManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** The site's default room settings (invalid entries are ignored) and locked keys. */
|
||||
private policy(): { base: RoomConfig; locks: Set<string> } {
|
||||
const p = this.deps.roomPolicy?.() ?? { defaults: {}, locks: [] };
|
||||
let base = DEFAULT_ROOM_CONFIG;
|
||||
for (const [k, v] of Object.entries(p.defaults)) {
|
||||
if (k === 'title') continue;
|
||||
const next = applyConfigPatch(base, { [k]: v });
|
||||
if (typeof next !== 'string') base = next;
|
||||
}
|
||||
return { base, locks: new Set(p.locks) };
|
||||
}
|
||||
|
||||
create(hostId: string, init: Partial<RoomConfig> = {}): Room | string {
|
||||
const nick = this.deps.user(hostId)?.nickname ?? '';
|
||||
const cfg = applyConfigPatch({ ...DEFAULT_ROOM_CONFIG, title: `${nick}님의 방`.slice(0, 40) }, init);
|
||||
const { base, locks } = this.policy();
|
||||
const wanted = Object.fromEntries(Object.entries(init).filter(([k]) => !locks.has(k)));
|
||||
const cfg = applyConfigPatch({ ...base, title: `${nick}님의 방`.slice(0, 40) }, wanted);
|
||||
if (typeof cfg === 'string') return cfg;
|
||||
const room = new Room(this.newCode(), hostId, cfg, this.deps);
|
||||
// Empty until someone joins: a room created and never entered expires like any empty room.
|
||||
@@ -297,6 +313,8 @@ export class RoomManager {
|
||||
|
||||
setConfig(ws: ServerWebSocket<WsData>, patch: Record<string, unknown>): string | null {
|
||||
return this.hostAction(ws, (room) => {
|
||||
const { locks } = this.policy();
|
||||
if (Object.keys(patch).some((k) => locks.has(k))) return '관리자가 고정한 설정이라 바꿀 수 없어요.';
|
||||
const next = applyConfigPatch(room.config, patch);
|
||||
if (typeof next === 'string') return next;
|
||||
room.config = next;
|
||||
@@ -478,6 +496,34 @@ export class RoomManager {
|
||||
});
|
||||
}
|
||||
|
||||
/** 관리자 → 방: every room, private ones too. */
|
||||
adminList() {
|
||||
return [...this.rooms.values()].map((r) => ({
|
||||
code: r.code,
|
||||
title: r.config.title,
|
||||
visibility: r.config.visibility,
|
||||
status: r.status,
|
||||
host: r.nick(r.hostId),
|
||||
createdAt: r.createdAt,
|
||||
game: r.game ? { phase: r.game.phase, n: r.game.n, total: r.game.total } : null,
|
||||
players: [...r.players].map(([id, p]) => ({ id, nickname: r.nick(id), online: p.conns.size > 0 })),
|
||||
}));
|
||||
}
|
||||
|
||||
/** 강제 종료: everyone is told and the room is gone. */
|
||||
adminClose(code: string): boolean {
|
||||
const room = this.rooms.get(code);
|
||||
if (!room) return false;
|
||||
room.send({ t: 'left', code, reason: 'admin' });
|
||||
for (const [id, p] of room.players) {
|
||||
for (const ws of p.conns) ws.data.roomCode = undefined;
|
||||
if (this.where.get(id) === code) this.where.delete(id);
|
||||
}
|
||||
room.players.clear();
|
||||
this.close(room);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Every 10s: drop players gone longer than the grace period, close rooms created but never entered. */
|
||||
sweep(now = Date.now()): void {
|
||||
for (const room of this.rooms.values()) {
|
||||
|
||||
@@ -12,6 +12,9 @@ import { Audit, Roles } from './admin/roles';
|
||||
import { SettingsStore } from './admin/settings';
|
||||
import { RoomManager } from './rooms/manager';
|
||||
import { toPublicUser } from './auth/users';
|
||||
import { purgeTrash } from './songs/admin-ops';
|
||||
import { collectorControl } from './collector/control';
|
||||
import type { CollectControl } from './http/admin-catalog';
|
||||
|
||||
/** A guest who closed the site and stayed away this long is deleted (docs/02). */
|
||||
export const GUEST_IDLE_MS = 24 * 3600_000;
|
||||
@@ -35,6 +38,8 @@ export interface StartOptions {
|
||||
stopWaitMs?: number;
|
||||
/** Game pacing (tests and e2e shorten the countdown / reveal). */
|
||||
gameTiming?: Partial<import('./game/engine').GameTiming>;
|
||||
/** Collector runner for the admin page (tests inject a fake). */
|
||||
collect?: CollectControl;
|
||||
}
|
||||
|
||||
export function startServer(opts: StartOptions) {
|
||||
@@ -47,7 +52,9 @@ export function startServer(opts: StartOptions) {
|
||||
const roles = new Roles(db, config.superadminDiscordIds);
|
||||
const audit = new Audit(db);
|
||||
const startedAt = Date.now();
|
||||
const genreNames = new Map(db.query<{ id: string; name: string }, []>('SELECT id, name FROM genres').all().map((g) => [g.id, g.name]));
|
||||
let genreNames = new Map<string, string>();
|
||||
const loadGenres = () => (genreNames = new Map(db.query<{ id: string; name: string }, []>('SELECT id, name FROM genres').all().map((g) => [g.id, g.name])));
|
||||
loadGenres();
|
||||
const rooms = new RoomManager({
|
||||
db,
|
||||
user: (id) => {
|
||||
@@ -58,7 +65,9 @@ export function startServer(opts: StartOptions) {
|
||||
log: (msg, extra) => log('info', msg, extra),
|
||||
limitSec: () => settings.getSite().questionLimitSec,
|
||||
timing: opts.gameTiming,
|
||||
roomPolicy: () => ({ defaults: settings.getSite().roomDefaults, locks: settings.getSite().roomLocks }),
|
||||
});
|
||||
const collect = opts.collect ?? collectorControl(db, log);
|
||||
const gateway = new Gateway({
|
||||
log,
|
||||
onClose: (id) => users.touch(id),
|
||||
@@ -103,6 +112,9 @@ export function startServer(opts: StartOptions) {
|
||||
db,
|
||||
checkEmbed: opts.checkEmbed,
|
||||
onCatalogChange: () => rooms.recountAll(),
|
||||
onGenresChange: loadGenres,
|
||||
rooms,
|
||||
collect,
|
||||
disconnectUser: (id) => gateway.disconnectUser(id),
|
||||
stats: () => ({
|
||||
connections: gateway.connectionCount,
|
||||
@@ -158,6 +170,7 @@ export function startServer(opts: StartOptions) {
|
||||
try {
|
||||
sessions.purgeExpired();
|
||||
purgeIdleGuests();
|
||||
purgeTrash(db);
|
||||
} catch (err) {
|
||||
log('error', 'sweep failed', { err: String(err) });
|
||||
}
|
||||
|
||||
299
apps/server/src/songs/admin-ops.ts
Normal file
299
apps/server/src/songs/admin-ops.ts
Normal file
@@ -0,0 +1,299 @@
|
||||
/**
|
||||
* Admin catalog work (docs/02 노래 관리 화면 · 가수 · 장르 · 통계): add, 휴지통, 일괄 작업, 가져오기/내보내기,
|
||||
* 중복 정리(병합), artist aliases, genres, play statistics with level suggestions.
|
||||
*/
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { Catalog } from '../collector/catalog';
|
||||
import { songMatchKey } from '@mq/shared';
|
||||
import { updateSong } from './store';
|
||||
|
||||
export const TRASH_DAYS = 30;
|
||||
|
||||
export interface NewSong {
|
||||
title: string;
|
||||
artist: string;
|
||||
year?: number | null;
|
||||
genres?: string[];
|
||||
level?: number | null;
|
||||
youtubeId?: string | null;
|
||||
highlightSec?: number | null;
|
||||
titleAliases?: string[];
|
||||
}
|
||||
|
||||
/** Adds a song (or finds the same one): artists split on ", " like the imports. Returns [id, created]. */
|
||||
export function createSong(db: Database, s: NewSong, embed?: { author: string; title: string }): [number, boolean] {
|
||||
const artists = s.artist.split(/\s*,\s*/).filter(Boolean);
|
||||
// Already there: leave it exactly as it is (no source row, no field changes).
|
||||
const same = db.query<{ id: number }, [string]>('SELECT id FROM songs WHERE match_key = ? AND deleted_at IS NULL ORDER BY id LIMIT 1').get(songMatchKey(s.title, artists.join(', ')));
|
||||
if (same) return [same.id, false];
|
||||
const cat = new Catalog(db);
|
||||
const [id, created] = cat.upsert({ title: s.title, artists: artists.map((name) => ({ name })), year: s.year ?? null, genres: [], source: 'admin', ref: `${Date.now()}` });
|
||||
updateSong(
|
||||
db,
|
||||
id,
|
||||
{
|
||||
genres: s.genres,
|
||||
level: s.level ?? undefined,
|
||||
youtubeId: s.youtubeId ?? undefined,
|
||||
highlightSec: s.highlightSec ?? undefined,
|
||||
titleAliases: s.titleAliases,
|
||||
year: s.year ?? undefined,
|
||||
},
|
||||
embed,
|
||||
);
|
||||
return [id, created];
|
||||
}
|
||||
|
||||
export function trashSongs(db: Database, ids: number[], now = Date.now()): number {
|
||||
if (!ids.length) return 0;
|
||||
return db.query(`UPDATE songs SET deleted_at = ?, updated_at = ? WHERE deleted_at IS NULL AND id IN (${ids.map(() => '?').join(',')})`).run(now, now, ...ids).changes;
|
||||
}
|
||||
|
||||
export function restoreSongs(db: Database, ids: number[], now = Date.now()): number {
|
||||
if (!ids.length) return 0;
|
||||
return db.query(`UPDATE songs SET deleted_at = NULL, updated_at = ? WHERE deleted_at IS NOT NULL AND id IN (${ids.map(() => '?').join(',')})`).run(now, ...ids).changes;
|
||||
}
|
||||
|
||||
/** Songs in the 휴지통 longer than 30 days are gone for good. */
|
||||
export function purgeTrash(db: Database, now = Date.now()): number {
|
||||
return db.query('DELETE FROM songs WHERE deleted_at IS NOT NULL AND deleted_at < ?').run(now - TRASH_DAYS * 86400_000).changes;
|
||||
}
|
||||
|
||||
export type BulkAction =
|
||||
| { action: 'hide' | 'show' | 'trash' | 'restore' | 'rematch' }
|
||||
| { action: 'level'; level: number | null }
|
||||
| { action: 'addGenre' | 'removeGenre'; genre: string };
|
||||
|
||||
/** 일괄 작업 on selected songs. */
|
||||
export function bulk(db: Database, ids: number[], a: BulkAction, now = Date.now()): number {
|
||||
if (!ids.length) return 0;
|
||||
const inIds = `(${ids.map(() => '?').join(',')})`;
|
||||
return db.transaction(() => {
|
||||
switch (a.action) {
|
||||
case 'hide':
|
||||
case 'show':
|
||||
return db.query(`UPDATE songs SET hidden = ?, updated_at = ? WHERE id IN ${inIds}`).run(a.action === 'hide' ? 1 : 0, now, ...ids).changes;
|
||||
case 'trash':
|
||||
return trashSongs(db, ids, now);
|
||||
case 'restore':
|
||||
return restoreSongs(db, ids, now);
|
||||
case 'rematch':
|
||||
// Back to the automatic search: forget the video (even an admin one) and the "tried" marks.
|
||||
db.query(`DELETE FROM signals WHERE kind LIKE 'yt_tried_%' AND song_id IN ${inIds}`).run(...ids);
|
||||
return db
|
||||
.query(`UPDATE songs SET youtube_id = NULL, youtube_status = 'none', youtube_source = NULL, youtube_channel = NULL, youtube_title = NULL, embeddable = NULL, updated_at = ? WHERE id IN ${inIds}`)
|
||||
.run(now, ...ids).changes;
|
||||
case 'level':
|
||||
for (const id of ids) updateSong(db, id, { level: a.level }, undefined, now);
|
||||
return ids.length;
|
||||
case 'addGenre':
|
||||
for (const id of ids) {
|
||||
db.query("UPDATE songs SET genres_source = 'admin' WHERE id = ?").run(id);
|
||||
db.query("INSERT OR IGNORE INTO song_genres (song_id, genre_id, source) VALUES (?, ?, 'admin')").run(id, a.genre);
|
||||
}
|
||||
return ids.length;
|
||||
case 'removeGenre':
|
||||
db.query(`UPDATE songs SET genres_source = 'admin' WHERE id IN ${inIds}`).run(...ids);
|
||||
return db.query(`DELETE FROM song_genres WHERE genre_id = ? AND song_id IN ${inIds}`).run(a.genre, ...ids).changes;
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
/** 중복 정리: songs whose normalized title+artist key is the same. */
|
||||
export function duplicates(db: Database, limit = 100) {
|
||||
const groups = db
|
||||
.query<{ match_key: string; ids: string }, [number]>(
|
||||
'SELECT match_key, group_concat(id) ids FROM songs WHERE deleted_at IS NULL GROUP BY match_key HAVING COUNT(*) > 1 ORDER BY COUNT(*) DESC, match_key LIMIT ?',
|
||||
)
|
||||
.all(limit);
|
||||
return groups.map((g) => ({
|
||||
key: g.match_key,
|
||||
songs: db
|
||||
.query<{ id: number; title: string; artist: string; year: number | null; youtube_status: string; plays: number }, []>(
|
||||
`SELECT s.id, s.title, s.artist, s.year, s.youtube_status, (SELECT COUNT(*) FROM song_plays p WHERE p.song_id = s.id) plays
|
||||
FROM songs s WHERE s.id IN (${g.ids}) ORDER BY s.id`,
|
||||
)
|
||||
.all(),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Merge `others` into `target`: sources, aliases, genres, levels, lyrics, video and plays move over, the rest goes to the 휴지통. */
|
||||
export function mergeSongs(db: Database, target: number, others: number[], now = Date.now()): number {
|
||||
const rest = others.filter((x) => x !== target);
|
||||
if (!rest.length) return 0;
|
||||
db.transaction(() => {
|
||||
for (const o of rest) {
|
||||
for (const t of ['song_sources', 'song_aliases', 'song_genres', 'song_levels', 'song_artists', 'youtube_candidates', 'signals'])
|
||||
db.query(`UPDATE OR IGNORE ${t} SET song_id = ? WHERE song_id = ?`).run(target, o);
|
||||
db.query('UPDATE song_plays SET song_id = ? WHERE song_id = ?').run(target, o);
|
||||
db.query('INSERT OR IGNORE INTO lyrics (song_id, text, source, fetched_at) SELECT ?, text, source, fetched_at FROM lyrics WHERE song_id = ?').run(target, o);
|
||||
// take the other song's confirmed video when the target has none
|
||||
db.query(
|
||||
`UPDATE songs SET youtube_id = o.youtube_id, youtube_status = o.youtube_status, youtube_source = o.youtube_source, youtube_channel = o.youtube_channel,
|
||||
youtube_title = o.youtube_title, embeddable = o.embeddable
|
||||
FROM (SELECT youtube_id, youtube_status, youtube_source, youtube_channel, youtube_title, embeddable FROM songs WHERE id = ?) o
|
||||
WHERE songs.id = ? AND songs.youtube_status <> 'matched' AND o.youtube_status = 'matched'`,
|
||||
).run(o, target);
|
||||
db.query('UPDATE songs SET year = COALESCE(year, (SELECT year FROM songs WHERE id = ?)), melon_id = COALESCE(melon_id, (SELECT melon_id FROM songs x WHERE x.id = ? AND NOT EXISTS (SELECT 1 FROM songs y WHERE y.melon_id = x.melon_id AND y.id <> x.id))) WHERE id = ?').run(o, o, target);
|
||||
}
|
||||
trashSongs(db, rest, now);
|
||||
})();
|
||||
return rest.length;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 가져오기 / 내보내기
|
||||
export const EXPORT_COLUMNS = ['id', 'title', 'artist', 'year', 'genres', 'level', 'youtube', 'highlight_sec', 'hidden'] as const;
|
||||
|
||||
const csvCell = (v: unknown) => {
|
||||
const s = v === null || v === undefined ? '' : String(v);
|
||||
return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
||||
};
|
||||
|
||||
export function toCsv(rows: Record<string, unknown>[]): string {
|
||||
return [EXPORT_COLUMNS.join(','), ...rows.map((r) => EXPORT_COLUMNS.map((k) => csvCell(r[k])).join(','))].join('\n') + '\n';
|
||||
}
|
||||
|
||||
/** Small RFC 4180 reader (quotes, doubled quotes, newlines inside quotes). */
|
||||
export function parseCsv(text: string): Record<string, string>[] {
|
||||
const rows: string[][] = [];
|
||||
let row: string[] = [];
|
||||
let cell = '';
|
||||
let q = false;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i]!;
|
||||
if (q) {
|
||||
if (ch === '"' && text[i + 1] === '"') (cell += '"'), i++;
|
||||
else if (ch === '"') q = false;
|
||||
else cell += ch;
|
||||
} else if (ch === '"') q = true;
|
||||
else if (ch === ',') (row.push(cell), (cell = ''));
|
||||
else if (ch === '\n' || ch === '\r') {
|
||||
if (ch === '\r' && text[i + 1] === '\n') i++;
|
||||
row.push(cell);
|
||||
if (row.some((c) => c !== '')) rows.push(row);
|
||||
row = [];
|
||||
cell = '';
|
||||
} else cell += ch;
|
||||
}
|
||||
row.push(cell);
|
||||
if (row.some((c) => c !== '')) rows.push(row);
|
||||
const [head, ...body] = rows;
|
||||
if (!head) return [];
|
||||
const keys = head.map((h) => h.trim().replace(/^/, ''));
|
||||
return body.map((r) => Object.fromEntries(keys.map((k, i) => [k, r[i] ?? ''])));
|
||||
}
|
||||
|
||||
export interface ImportRow {
|
||||
title: string;
|
||||
artist: string;
|
||||
year?: number | null;
|
||||
genres?: string[];
|
||||
level?: number | null;
|
||||
youtube?: string | null;
|
||||
}
|
||||
|
||||
/** Normalizes JSON or CSV rows; returns the valid rows and the line numbers that were skipped. */
|
||||
export function importRows(raw: Record<string, unknown>[], known: Set<string>): { rows: ImportRow[]; skipped: number[] } {
|
||||
const rows: ImportRow[] = [];
|
||||
const skipped: number[] = [];
|
||||
raw.forEach((r, i) => {
|
||||
const title = String(r.title ?? '').trim();
|
||||
const artist = String(r.artist ?? '').trim();
|
||||
if (!title || !artist || title.length > 200 || artist.length > 200) return void skipped.push(i + 1);
|
||||
const year = Number(r.year) || null;
|
||||
const level = Number(r.level) || null;
|
||||
const genres = (Array.isArray(r.genres) ? r.genres.map(String) : String(r.genres ?? '').split(/[|,;]/)).map((g) => g.trim()).filter((g) => known.has(g));
|
||||
rows.push({
|
||||
title,
|
||||
artist,
|
||||
year: year && year >= 1900 && year <= 2100 ? year : null,
|
||||
genres,
|
||||
level: level && level >= 1 && level <= 10 ? Math.round(level) : null,
|
||||
youtube: r.youtube ? String(r.youtube) : null,
|
||||
});
|
||||
});
|
||||
return { rows, skipped };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 가수
|
||||
export function listArtists(db: Database, q: string, page = 0, size = 50) {
|
||||
const like = `%${q.replace(/[%_\\]/g, (m) => '\\' + m)}%`;
|
||||
const where = q ? "WHERE a.name LIKE ? ESCAPE '\\' OR EXISTS (SELECT 1 FROM artist_aliases x WHERE x.artist_id = a.id AND x.alias LIKE ? ESCAPE '\\')" : '';
|
||||
const args = q ? [like, like] : [];
|
||||
const total = db.query<{ n: number }, string[]>(`SELECT COUNT(*) n FROM artists a ${where}`).get(...args)!.n;
|
||||
const rows = db
|
||||
.query<{ id: number; name: string; kind: string | null; songs: number; aliases: string | null }, (string | number)[]>(
|
||||
`SELECT a.id, a.name, a.kind, (SELECT COUNT(*) FROM song_artists sa JOIN songs s ON s.id = sa.song_id AND s.deleted_at IS NULL WHERE sa.artist_id = a.id) songs,
|
||||
(SELECT group_concat(alias, '|') FROM artist_aliases x WHERE x.artist_id = a.id) aliases
|
||||
FROM artists a ${where} ORDER BY songs DESC, a.name LIMIT ? OFFSET ?`,
|
||||
)
|
||||
.all(...args, size, page * size)
|
||||
.map((r) => ({ ...r, aliases: r.aliases ? r.aliases.split('|') : [] }));
|
||||
return { total, rows, pageSize: size };
|
||||
}
|
||||
|
||||
/** 가수 별칭 (아이유 = IU = 이지은): they count as the artist answer for every song of that artist. */
|
||||
export function updateArtist(db: Database, id: number, p: { name?: string; kind?: string | null; aliases?: string[] }): boolean {
|
||||
const cur = db.query<{ id: number }, [number]>('SELECT id FROM artists WHERE id = ?').get(id);
|
||||
if (!cur) return false;
|
||||
db.transaction(() => {
|
||||
if (p.name) db.query('UPDATE artists SET name = ? WHERE id = ?').run(p.name, id);
|
||||
if (p.kind !== undefined) db.query('UPDATE artists SET kind = ? WHERE id = ?').run(p.kind, id);
|
||||
if (p.aliases) {
|
||||
db.query('DELETE FROM artist_aliases WHERE artist_id = ?').run(id);
|
||||
for (const a of new Set(p.aliases.map((x) => x.trim()).filter(Boolean))) db.query('INSERT OR IGNORE INTO artist_aliases (artist_id, alias) VALUES (?, ?)').run(id, a);
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 장르
|
||||
export function addGenre(db: Database, g: { id: string; name: string; grp: 'region' | 'style' | 'theme' }): string | null {
|
||||
if (db.query('SELECT 1 FROM genres WHERE id = ?').get(g.id)) return '이미 있는 장르 ID예요.';
|
||||
const sort = db.query<{ m: number | null }, [string]>('SELECT MAX(sort) m FROM genres WHERE grp = ?').get(g.grp)!.m ?? 0;
|
||||
db.query('INSERT INTO genres (id, name, grp, sort) VALUES (?, ?, ?, ?)').run(g.id, g.name, g.grp, sort + 10);
|
||||
return null;
|
||||
}
|
||||
|
||||
export function updateGenre(db: Database, id: string, p: { name?: string; sort?: number; hidden?: boolean }): boolean {
|
||||
const r = db
|
||||
.query('UPDATE genres SET name = COALESCE(?, name), sort = COALESCE(?, sort), hidden = COALESCE(?, hidden) WHERE id = ?')
|
||||
.run(p.name ?? null, p.sort ?? null, p.hidden === undefined ? null : p.hidden ? 1 : 0, id);
|
||||
return r.changes > 0;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 통계
|
||||
export const MIN_PLAYS_FOR_SUGGESTION = 5;
|
||||
|
||||
/**
|
||||
* Level suggestion from how people did (docs/02 통계 → 난이도 조정 제안).
|
||||
* Levels go 1 (everyone knows) → 10 (nobody): mostly guessed and fast → one easier, rarely guessed → one harder.
|
||||
*/
|
||||
export function suggestLevel(level: number | null, plays: number, correct: number, avgMs: number | null): number | null {
|
||||
if (!level || plays < MIN_PLAYS_FOR_SUGGESTION) return null;
|
||||
const rate = correct / plays;
|
||||
if (rate >= 0.8 && avgMs !== null && avgMs <= 8000 && level > 1) return level - 1;
|
||||
if (rate <= 0.3 && level < 10) return level + 1;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function playStats(db: Database, opts: { sort?: 'plays' | 'correct' | 'fast' | 'suggest'; page?: number } = {}) {
|
||||
const size = 50;
|
||||
const page = Math.max(0, opts.page ?? 0);
|
||||
const order = { plays: 'plays DESC', correct: 'rate DESC', fast: 'avg_ms IS NULL, avg_ms', suggest: 'plays DESC' }[opts.sort ?? 'plays'];
|
||||
const all = db
|
||||
.query<{ id: number; title: string; artist: string; level: number | null; plays: number; correct: number; avg_ms: number | null; rate: number; last_at: number }, []>(
|
||||
`SELECT s.id, s.title, s.artist, lv.level, COUNT(*) plays, SUM(p.winner_id IS NOT NULL) correct, AVG(p.ms) avg_ms,
|
||||
1.0 * SUM(p.winner_id IS NOT NULL) / COUNT(*) rate, MAX(p.played_at) last_at
|
||||
FROM song_plays p JOIN songs s ON s.id = p.song_id AND s.deleted_at IS NULL
|
||||
LEFT JOIN song_levels lv ON lv.song_id = s.id AND lv.scope = 'all'
|
||||
GROUP BY s.id ORDER BY ${order}, s.id`,
|
||||
)
|
||||
.all()
|
||||
.map((r) => ({ ...r, avg_ms: r.avg_ms === null ? null : Math.round(r.avg_ms), suggest: suggestLevel(r.level, r.plays, r.correct, r.avg_ms) }));
|
||||
const list = opts.sort === 'suggest' ? all.filter((r) => r.suggest !== null) : all;
|
||||
const day = 86400_000;
|
||||
const since = Date.now() - day;
|
||||
const today = db.query<{ plays: number; games: number }, [number]>('SELECT COUNT(*) plays, COUNT(DISTINCT game_id) games FROM song_plays WHERE played_at >= ?').get(since)!;
|
||||
return { total: list.length, rows: list.slice(page * size, page * size + size), pageSize: size, today, suggestions: all.filter((r) => r.suggest !== null).length };
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Song catalog queries for the admin pages (docs/02 노래 관리 화면). */
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { songMatchKey } from '@mq/shared';
|
||||
import { chosung, songMatchKey } from '@mq/shared';
|
||||
|
||||
export function catalogStats(db: Database) {
|
||||
const one = <T>(sql: string) => db.query<T, []>(sql).get()!;
|
||||
@@ -35,16 +35,34 @@ export interface SongFilter {
|
||||
source?: string;
|
||||
hidden?: boolean;
|
||||
lyrics?: boolean;
|
||||
sort?: 'recent' | 'year' | 'level' | 'peak' | 'title';
|
||||
/** Has a highlight start (admin / heatmap / analysis). */
|
||||
highlight?: boolean;
|
||||
/** 휴지통: deleted songs (kept 30 days). */
|
||||
trash?: boolean;
|
||||
sort?: 'recent' | 'year' | 'level' | 'peak' | 'title' | 'plays' | 'correct';
|
||||
page?: number;
|
||||
/** Export: every matching row. */
|
||||
all?: boolean;
|
||||
}
|
||||
|
||||
const JAMO_ONLY = /^[\u3131-\u314e\s]+$/;
|
||||
|
||||
export const PAGE = 50;
|
||||
|
||||
export function listSongs(db: Database, f: SongFilter) {
|
||||
const where: string[] = ['s.deleted_at IS NULL'];
|
||||
const where: string[] = [f.trash ? 's.deleted_at IS NOT NULL' : 's.deleted_at IS NULL'];
|
||||
const args: (string | number)[] = [];
|
||||
if (f.q) {
|
||||
if (f.q && JAMO_ONLY.test(f.q)) {
|
||||
// 초성 검색 (docs/02): "ㅅㄱㅇㅈㅍㅅ" → 사건의 지평선
|
||||
const want = f.q.replace(/\s/g, '');
|
||||
const ids = db
|
||||
.query<{ id: number; title: string }, []>(`SELECT id, title FROM songs s WHERE ${where[0]}`)
|
||||
.all()
|
||||
.filter((r) => chosung(r.title).replace(/\s/g, '').includes(want))
|
||||
.map((r) => r.id)
|
||||
.slice(0, 2000);
|
||||
where.push(ids.length ? `s.id IN (${ids.join(',')})` : '0');
|
||||
} else if (f.q) {
|
||||
const like = `%${f.q.replace(/[%_\\]/g, (m) => '\\' + m)}%`;
|
||||
where.push(`(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 '\\') OR s.youtube_id = ? OR CAST(s.melon_id AS TEXT) = ?)`);
|
||||
args.push(like, like, like, f.q, f.q);
|
||||
@@ -60,12 +78,15 @@ export function listSongs(db: Database, f: SongFilter) {
|
||||
if (f.source) (where.push('EXISTS (SELECT 1 FROM song_sources x WHERE x.song_id = s.id AND x.source = ?)'), args.push(f.source));
|
||||
if (f.hidden !== undefined) (where.push('s.hidden = ?'), args.push(f.hidden ? 1 : 0));
|
||||
if (f.lyrics !== undefined) where.push(`${f.lyrics ? '' : 'NOT '}EXISTS (SELECT 1 FROM lyrics y WHERE y.song_id = s.id)`);
|
||||
if (f.highlight !== undefined) where.push(`s.highlight_sec IS ${f.highlight ? 'NOT ' : ''}NULL`);
|
||||
const order = {
|
||||
recent: 's.id DESC',
|
||||
year: 's.year DESC NULLS LAST, s.id',
|
||||
level: 'lv.level NULLS LAST, s.id',
|
||||
peak: 's.peak_rank NULLS LAST, s.id',
|
||||
title: 's.title COLLATE NOCASE',
|
||||
plays: 'plays DESC, s.id',
|
||||
correct: 'CASE WHEN plays > 0 THEN 1.0 * correct / plays END DESC NULLS LAST, s.id',
|
||||
}[f.sort ?? 'recent'];
|
||||
const w = where.join(' AND ');
|
||||
const total = db.query<{ n: number }, (string | number)[]>(`SELECT COUNT(*) n FROM songs s WHERE ${w}`).get(...args)!.n;
|
||||
@@ -76,9 +97,12 @@ export function listSongs(db: Database, f: SongFilter) {
|
||||
s.peak_rank, s.hidden, s.highlight_sec, lv.level,
|
||||
(SELECT group_concat(genre_id) FROM song_genres g WHERE g.song_id = s.id) genres,
|
||||
(SELECT group_concat(DISTINCT source) FROM song_sources x WHERE x.song_id = s.id) sources,
|
||||
EXISTS (SELECT 1 FROM lyrics y WHERE y.song_id = s.id) has_lyrics
|
||||
EXISTS (SELECT 1 FROM lyrics y WHERE y.song_id = s.id) has_lyrics,
|
||||
(SELECT COUNT(*) FROM song_plays p WHERE p.song_id = s.id) plays,
|
||||
(SELECT COUNT(*) FROM song_plays p WHERE p.song_id = s.id AND p.winner_id IS NOT NULL) correct,
|
||||
s.deleted_at
|
||||
FROM songs s LEFT JOIN song_levels lv ON lv.song_id = s.id AND lv.scope = 'all'
|
||||
WHERE ${w} ORDER BY ${order} LIMIT ${PAGE} OFFSET ${page * PAGE}`,
|
||||
WHERE ${w} ORDER BY ${order} ${f.all ? 'LIMIT 50000' : `LIMIT ${PAGE} OFFSET ${page * PAGE}`}`,
|
||||
)
|
||||
.all(...args)
|
||||
.map((r) => ({
|
||||
|
||||
Reference in New Issue
Block a user