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) => ({
|
||||
|
||||
@@ -17,7 +17,7 @@ interface RoomState {
|
||||
rtt: number | null;
|
||||
/** Join failed with this message (wrong password, unknown room…). */
|
||||
joinError: string | null;
|
||||
left: null | 'leave' | 'kicked' | 'closed' | 'elsewhere';
|
||||
left: null | 'leave' | 'kicked' | 'closed' | 'elsewhere' | 'admin';
|
||||
/** Room chat in seq order (docs/06), last CHAT_KEEP lines. */
|
||||
chat: ChatLine[];
|
||||
/** My lines not confirmed by the server yet: always drawn at the bottom (docs/06 지연 없는 전송). */
|
||||
|
||||
@@ -21,6 +21,7 @@ const LEFT_TEXT: Record<string, string> = {
|
||||
closed: '오래 접속하지 않아 방에서 나갔어요.',
|
||||
elsewhere: '다른 방에 들어가서 이 방에서는 나갔어요.',
|
||||
leave: '방에서 나왔어요.',
|
||||
admin: '관리자가 방을 닫았어요.',
|
||||
};
|
||||
|
||||
export default function RoomPage() {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
/**
|
||||
* 관리자 페이지 (docs/02): side menu + content. Stage 1 has 대시보드 · 사이트 · 사용자 · 관리자 · 기록;
|
||||
* 노래 · 가수 · 장르 · 수집 · 통계 · 방 are listed and open in later stages.
|
||||
* 관리자 페이지 (docs/02): side menu + content — 대시보드 · 노래 · 가수 · 장르 · 수집 · 통계 · 방 · 사이트 · 사용자 · 관리자 · 기록.
|
||||
*/
|
||||
import { useCallback, useEffect, useState, type FormEvent } from 'react';
|
||||
import { Link, NavLink, Navigate, Route, Routes } from 'react-router';
|
||||
@@ -9,7 +8,10 @@ import { ApiError, apiCall, discordLoginUrl } from '../../net/api';
|
||||
import { useSession } from '../../store/session';
|
||||
import { toast } from '../../store/toast';
|
||||
import { ConfirmSheet } from '../../components/ui';
|
||||
import { CollectPage, SongsPage } from './SongsPage';
|
||||
import { SongsPage } from './SongsPage';
|
||||
import { ArtistsPage, CollectPage, GenresPage, RoomsPage, StatsPage } from './AdminMore';
|
||||
import { RoomSettings, type CatalogMeta } from '../../components/RoomSettings';
|
||||
import { DEFAULT_ROOM_CONFIG, type RoomConfig } from '@mq/shared/lite';
|
||||
|
||||
const fmt = (ms: number | null | undefined) => (ms ? new Date(ms).toLocaleString('ko-KR', { dateStyle: 'short', timeStyle: 'short' }) : '-');
|
||||
|
||||
@@ -26,7 +28,6 @@ function useLoad<T>(path: string | null) {
|
||||
return { data, error, reload, setData };
|
||||
}
|
||||
|
||||
const SOON = ['가수', '장르', '통계', '방'];
|
||||
|
||||
export default function AdminApp() {
|
||||
const me = useSession((s) => s.me);
|
||||
@@ -62,13 +63,12 @@ export default function AdminApp() {
|
||||
</NavLink>
|
||||
<div className="sep">노래 DB</div>
|
||||
<NavLink to="/admin/songs">🎵 노래</NavLink>
|
||||
<NavLink to="/admin/artists">🎤 가수</NavLink>
|
||||
<NavLink to="/admin/genres">🏷 장르</NavLink>
|
||||
<NavLink to="/admin/collect">📥 수집</NavLink>
|
||||
{SOON.map((s) => (
|
||||
<a key={s} className="soon" aria-disabled="true" title="다음 단계에서 열려요">
|
||||
{s} <span className="badge">준비 중</span>
|
||||
</a>
|
||||
))}
|
||||
<NavLink to="/admin/stats">📈 통계</NavLink>
|
||||
<div className="sep">운영</div>
|
||||
<NavLink to="/admin/rooms">🚪 방</NavLink>
|
||||
<NavLink to="/admin/site">⚙️ 사이트</NavLink>
|
||||
{isSuper && <NavLink to="/admin/users">👤 사용자</NavLink>}
|
||||
{isSuper && <NavLink to="/admin/admins">🛡 관리자</NavLink>}
|
||||
@@ -79,6 +79,10 @@ export default function AdminApp() {
|
||||
<Route index element={<Dashboard role={role} />} />
|
||||
<Route path="songs" element={<SongsPage />} />
|
||||
<Route path="collect" element={<CollectPage />} />
|
||||
<Route path="artists" element={<ArtistsPage />} />
|
||||
<Route path="genres" element={<GenresPage />} />
|
||||
<Route path="stats" element={<StatsPage />} />
|
||||
<Route path="rooms" element={<RoomsPage />} />
|
||||
<Route path="site" element={<SiteSettings />} />
|
||||
{isSuper && <Route path="users" element={<UsersPage />} />}
|
||||
{isSuper && <Route path="admins" element={<AdminsPage />} />}
|
||||
@@ -91,9 +95,14 @@ export default function AdminApp() {
|
||||
}
|
||||
|
||||
function Dashboard({ role }: { role: Role }) {
|
||||
const { data, error } = useLoad<{ users: { total: number; guests: number; members: number; banned: number }; connections: number; uptimeSec: number; memoryMb: number }>(
|
||||
'/api/admin/overview',
|
||||
);
|
||||
const { data, error } = useLoad<{
|
||||
users: { total: number; guests: number; members: number; banned: number };
|
||||
connections: number;
|
||||
uptimeSec: number;
|
||||
memoryMb: number;
|
||||
rooms: { total: number; playing: number };
|
||||
}>('/api/admin/overview');
|
||||
const { data: plays } = useLoad<{ today: { plays: number; games: number } }>('/api/admin/stats?sort=suggest');
|
||||
const { data: cat } = useLoad<{ total: number; youtube: { matched: number }; lyrics: number }>('/api/admin/catalog');
|
||||
return (
|
||||
<>
|
||||
@@ -128,6 +137,18 @@ function Dashboard({ role }: { role: Role }) {
|
||||
<b>{data.memoryMb}MB</b>
|
||||
<span>서버 메모리</span>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<b>
|
||||
{data.rooms.playing} / {data.rooms.total}
|
||||
</b>
|
||||
<span>게임 중 / 열린 방</span>
|
||||
</div>
|
||||
{plays && (
|
||||
<div className="stat">
|
||||
<b>{plays.today.games}</b>
|
||||
<span>최근 24시간 게임 ({plays.today.plays}문제)</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{cat && (
|
||||
@@ -146,7 +167,6 @@ function Dashboard({ role }: { role: Role }) {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<p className="muted small">진행 중인 방과 오늘 플레이 수는 방 기능이 들어오면 여기에 보여요.</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -160,8 +180,25 @@ interface Site {
|
||||
chatRatePerSec: number;
|
||||
chatBurst: number;
|
||||
questionLimitSec: number;
|
||||
roomDefaults: Partial<RoomConfig>;
|
||||
roomLocks: string[];
|
||||
}
|
||||
|
||||
/** Settings an admin can pin for every room (사이트 → 잠금). */
|
||||
const LOCKABLE: [keyof RoomConfig, string][] = [
|
||||
['mode', '모드'],
|
||||
['listenSec', '듣고맞출시간'],
|
||||
['startAt', '재생위치'],
|
||||
['level', '난이도'],
|
||||
['answer', '정답방식'],
|
||||
['strict', '정답인식'],
|
||||
['hint', '힌트공개'],
|
||||
['skipVotes', '스킵인원'],
|
||||
['replayVotes', '다시듣기인원'],
|
||||
['count', '문제 수'],
|
||||
['visibility', '방 공개'],
|
||||
];
|
||||
|
||||
function SiteSettings() {
|
||||
const { data, error } = useLoad<{ site: Site }>('/api/admin/site');
|
||||
const [s, setS] = useState<Site | null>(null);
|
||||
@@ -230,6 +267,7 @@ function SiteSettings() {
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<RoomDefaults site={s} onChange={(p) => setS({ ...s, ...p })} />
|
||||
<div>
|
||||
<button className="btn btn-primary">저장</button>
|
||||
</div>
|
||||
@@ -237,6 +275,60 @@ function SiteSettings() {
|
||||
);
|
||||
}
|
||||
|
||||
/** 새 방의 기본 설정 + 잠금 (docs/04 설정 저장): the same settings form hosts use. */
|
||||
function RoomDefaults({ site, onChange }: { site: Site; onChange: (p: Partial<Site>) => void }) {
|
||||
const [meta, setMeta] = useState<CatalogMeta | null>(null);
|
||||
const [pool, setPool] = useState({ playable: 0, total: 0 });
|
||||
const config: RoomConfig = { ...DEFAULT_ROOM_CONFIG, ...site.roomDefaults, title: '새 방 기본값' } as RoomConfig;
|
||||
useEffect(() => {
|
||||
void apiCall<CatalogMeta>('GET', '/api/catalog/meta').then(setMeta, () => {});
|
||||
}, []);
|
||||
const key = JSON.stringify(site.roomDefaults);
|
||||
useEffect(() => {
|
||||
void apiCall<{ playable: number; total: number }>('POST', '/api/pool/count', site.roomDefaults).then(setPool, () => {});
|
||||
}, [key]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
return (
|
||||
<fieldset className="card stack" style={{ margin: 0 }}>
|
||||
<legend style={{ fontWeight: 800, padding: '0 6px' }}>새 방 기본 설정 · 잠금</legend>
|
||||
<p className="muted small">새로 만드는 방은 이 설정으로 시작해요. 잠근 항목은 방장이 바꿀 수 없어요(방 이름·비밀번호는 제외).</p>
|
||||
<div className="row" role="group" aria-label="잠금">
|
||||
{LOCKABLE.map(([k, label]) => (
|
||||
<label key={k} className="check small">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={site.roomLocks.includes(k)}
|
||||
onChange={(e) => onChange({ roomLocks: e.target.checked ? [...site.roomLocks, k] : site.roomLocks.filter((x) => x !== k) })}
|
||||
/>
|
||||
🔒 {label}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<div className="row">
|
||||
<button type="button" className="btn btn-sm" onClick={() => onChange({ roomDefaults: {}, roomLocks: [] })}>
|
||||
처음 기본값으로
|
||||
</button>
|
||||
</div>
|
||||
<div style={{ maxWidth: 560 }}>
|
||||
<RoomSettings
|
||||
config={config}
|
||||
editable
|
||||
meta={meta}
|
||||
artists={[]}
|
||||
pool={pool}
|
||||
hasPassword={false}
|
||||
onPatch={(p) => {
|
||||
const { title: _t, ...rest } = p as Partial<RoomConfig>;
|
||||
const merged: Record<string, unknown> = { ...site.roomDefaults, ...rest };
|
||||
if (rest.strict) merged.strict = { ...config.strict, ...rest.strict };
|
||||
onChange({ roomDefaults: merged as Partial<RoomConfig> });
|
||||
}}
|
||||
onPassword={() => {}}
|
||||
/>
|
||||
</div>
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
|
||||
interface AdminUser {
|
||||
id: string;
|
||||
nickname: string;
|
||||
|
||||
537
apps/web/src/pages/admin/AdminMore.tsx
Normal file
537
apps/web/src/pages/admin/AdminMore.tsx
Normal file
@@ -0,0 +1,537 @@
|
||||
/**
|
||||
* 관리자 → 가수 · 장르 · 통계 · 방 · 수집 (docs/02 관리자 페이지).
|
||||
*/
|
||||
import { useCallback, useEffect, useState, type FormEvent } from 'react';
|
||||
import { apiCall } from '../../net/api';
|
||||
import { toast } from '../../store/toast';
|
||||
import { ConfirmSheet } from '../../components/ui';
|
||||
|
||||
const fmt = (ms: number | null | undefined) => (ms ? new Date(ms).toLocaleString('ko-KR', { dateStyle: 'short', timeStyle: 'short' }) : '-');
|
||||
const pct = (n: number, d: number) => (d ? `${Math.round((n / d) * 100)}%` : '-');
|
||||
|
||||
function useLoad<T>(path: string) {
|
||||
const [data, setData] = useState<T | null>(null);
|
||||
const reload = useCallback(() => void apiCall<T>('GET', path).then(setData, (e: Error) => toast(e.message, 'error')), [path]);
|
||||
useEffect(reload, [reload]);
|
||||
return { data, reload };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 가수
|
||||
interface ArtistRow {
|
||||
id: number;
|
||||
name: string;
|
||||
kind: 'solo' | 'group' | 'unit' | null;
|
||||
songs: number;
|
||||
aliases: string[];
|
||||
}
|
||||
|
||||
export function ArtistsPage() {
|
||||
const [q, setQ] = useState('');
|
||||
const [query, setQuery] = useState('');
|
||||
const [page, setPage] = useState(0);
|
||||
const { data, reload } = useLoad<{ total: number; rows: ArtistRow[]; pageSize: number }>(`/api/admin/artists?q=${encodeURIComponent(query)}&page=${page}`);
|
||||
const [edit, setEdit] = useState<{ id: number; name: string; kind: string; aliases: string } | null>(null);
|
||||
const pages = data ? Math.max(1, Math.ceil(data.total / data.pageSize)) : 1;
|
||||
const save = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!edit) return;
|
||||
try {
|
||||
await apiCall('PATCH', `/api/admin/artists/${edit.id}`, {
|
||||
name: edit.name.trim(),
|
||||
kind: edit.kind || null,
|
||||
aliases: edit.aliases.split(',').map((x) => x.trim()).filter(Boolean),
|
||||
});
|
||||
toast('저장했어요.');
|
||||
setEdit(null);
|
||||
reload();
|
||||
} catch (ex) {
|
||||
toast((ex as Error).message, 'error');
|
||||
}
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<h1>가수</h1>
|
||||
<p className="muted small">별칭을 넣으면 그 가수의 모든 노래에서 정답으로 인정돼요. 예) 아이유 = IU = 이지은</p>
|
||||
<form
|
||||
className="row"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
setPage(0);
|
||||
setQuery(q.trim());
|
||||
}}
|
||||
>
|
||||
<input className="input grow" style={{ maxWidth: 360 }} placeholder="가수 이름·별칭" value={q} onChange={(e) => setQ(e.target.value)} aria-label="가수 검색" />
|
||||
<button className="btn">검색</button>
|
||||
{data && <span className="muted small">{data.total.toLocaleString()}명</span>}
|
||||
</form>
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>이름</th>
|
||||
<th>구분</th>
|
||||
<th>곡 수</th>
|
||||
<th>별칭</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.rows.map((a) =>
|
||||
edit?.id === a.id ? (
|
||||
<tr key={a.id} className="sel">
|
||||
<td colSpan={5}>
|
||||
<form className="row" onSubmit={save}>
|
||||
<input className="input sm" style={{ width: 160 }} value={edit.name} onChange={(e) => setEdit({ ...edit, name: e.target.value })} aria-label="이름" />
|
||||
<select className="input sm" style={{ width: 'auto' }} value={edit.kind} onChange={(e) => setEdit({ ...edit, kind: e.target.value })} aria-label="구분">
|
||||
<option value="">-</option>
|
||||
<option value="solo">솔로</option>
|
||||
<option value="group">그룹</option>
|
||||
<option value="unit">유닛</option>
|
||||
</select>
|
||||
<input className="input sm grow" style={{ width: 'auto', minWidth: 220 }} placeholder="별칭 (쉼표로 구분)" value={edit.aliases} onChange={(e) => setEdit({ ...edit, aliases: e.target.value })} aria-label="별칭" />
|
||||
<button className="btn btn-sm btn-primary">저장</button>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setEdit(null)}>
|
||||
취소
|
||||
</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
<tr key={a.id}>
|
||||
<td>{a.name}</td>
|
||||
<td className="small">{a.kind ? { solo: '솔로', group: '그룹', unit: '유닛' }[a.kind] : '-'}</td>
|
||||
<td className="mono">{a.songs}</td>
|
||||
<td className="small">{a.aliases.join(', ') || '-'}</td>
|
||||
<td>
|
||||
<button type="button" className="btn btn-sm" onClick={() => setEdit({ id: a.id, name: a.name, kind: a.kind ?? '', aliases: a.aliases.join(', ') })} aria-label={`${a.name} 고치기`}>
|
||||
고치기
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
),
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="row">
|
||||
<button className="btn btn-sm" disabled={page === 0} onClick={() => setPage(page - 1)}>
|
||||
이전
|
||||
</button>
|
||||
<span className="muted small mono">
|
||||
{page + 1} / {pages}
|
||||
</span>
|
||||
<button className="btn btn-sm" disabled={page + 1 >= pages} onClick={() => setPage(page + 1)}>
|
||||
다음
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 장르
|
||||
interface GenreRow {
|
||||
id: string;
|
||||
name: string;
|
||||
grp: 'region' | 'style' | 'theme';
|
||||
sort: number;
|
||||
hidden: boolean;
|
||||
songs: number;
|
||||
}
|
||||
const GRP: Record<GenreRow['grp'], string> = { region: '지역', style: '스타일', theme: '테마' };
|
||||
|
||||
export function GenresPage() {
|
||||
const { data, reload } = useLoad<{ genres: GenreRow[] }>('/api/admin/genres');
|
||||
const [add, setAdd] = useState({ id: '', name: '', grp: 'style' as GenreRow['grp'] });
|
||||
const patch = async (id: string, p: Partial<GenreRow>) => {
|
||||
try {
|
||||
await apiCall('PATCH', `/api/admin/genres/${id}`, p);
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
}
|
||||
};
|
||||
const list = data?.genres ?? [];
|
||||
const move = (g: GenreRow, dir: -1 | 1) => {
|
||||
const same = list.filter((x) => x.grp === g.grp);
|
||||
const i = same.findIndex((x) => x.id === g.id);
|
||||
const other = same[i + dir];
|
||||
if (!other) return;
|
||||
void Promise.all([apiCall('PATCH', `/api/admin/genres/${g.id}`, { sort: other.sort }), apiCall('PATCH', `/api/admin/genres/${other.id}`, { sort: g.sort })]).then(reload, (e: Error) => toast(e.message, 'error'));
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<h1>장르</h1>
|
||||
<p className="muted small">같은 묶음끼리는 "또는", 다른 묶음끼리는 "그리고"로 골라요(예: K-POP 그리고 발라드). 숨긴 장르는 방 설정에 안 보여요.</p>
|
||||
<form
|
||||
className="row"
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await apiCall('POST', '/api/admin/genres', add);
|
||||
toast('추가했어요.');
|
||||
setAdd({ id: '', name: '', grp: add.grp });
|
||||
reload();
|
||||
} catch (ex) {
|
||||
toast((ex as Error).message, 'error');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<input className="input sm" style={{ width: 140 }} placeholder="ID (영문, 예: citypop)" value={add.id} onChange={(e) => setAdd({ ...add, id: e.target.value.toLowerCase() })} aria-label="새 장르 ID" />
|
||||
<input className="input sm" style={{ width: 160 }} placeholder="이름" value={add.name} onChange={(e) => setAdd({ ...add, name: e.target.value })} aria-label="새 장르 이름" />
|
||||
<select className="input sm" style={{ width: 'auto' }} value={add.grp} onChange={(e) => setAdd({ ...add, grp: e.target.value as GenreRow['grp'] })} aria-label="묶음">
|
||||
{Object.entries(GRP).map(([k, v]) => (
|
||||
<option key={k} value={k}>
|
||||
{v}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button className="btn btn-sm btn-primary" disabled={!add.id || !add.name.trim()}>
|
||||
장르 추가
|
||||
</button>
|
||||
</form>
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>묶음</th>
|
||||
<th>이름</th>
|
||||
<th>ID</th>
|
||||
<th>곡 수</th>
|
||||
<th>순서</th>
|
||||
<th>숨김</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{list.map((g) => (
|
||||
<tr key={g.id}>
|
||||
<td className="small">{GRP[g.grp]}</td>
|
||||
<td>
|
||||
<input
|
||||
className="input sm"
|
||||
style={{ width: 150 }}
|
||||
defaultValue={g.name}
|
||||
aria-label={`${g.name} 이름`}
|
||||
onBlur={(e) => e.target.value.trim() && e.target.value.trim() !== g.name && void patch(g.id, { name: e.target.value.trim() })}
|
||||
/>
|
||||
</td>
|
||||
<td className="mono small">{g.id}</td>
|
||||
<td className="mono">{g.songs.toLocaleString()}</td>
|
||||
<td>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => move(g, -1)} aria-label={`${g.name} 위로`}>
|
||||
▲
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => move(g, 1)} aria-label={`${g.name} 아래로`}>
|
||||
▼
|
||||
</button>
|
||||
</td>
|
||||
<td>
|
||||
<input type="checkbox" checked={g.hidden} onChange={(e) => void patch(g.id, { hidden: e.target.checked })} aria-label={`${g.name} 숨김`} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 통계
|
||||
interface StatRow {
|
||||
id: number;
|
||||
title: string;
|
||||
artist: string;
|
||||
level: number | null;
|
||||
plays: number;
|
||||
correct: number;
|
||||
avg_ms: number | null;
|
||||
last_at: number;
|
||||
suggest: number | null;
|
||||
}
|
||||
|
||||
export function StatsPage() {
|
||||
const [sort, setSort] = useState('plays');
|
||||
const [page, setPage] = useState(0);
|
||||
const { data, reload } = useLoad<{ total: number; rows: StatRow[]; pageSize: number; today: { plays: number; games: number }; suggestions: number }>(`/api/admin/stats?sort=${sort}&page=${page}`);
|
||||
const pages = data ? Math.max(1, Math.ceil(data.total / data.pageSize)) : 1;
|
||||
return (
|
||||
<>
|
||||
<h1>통계</h1>
|
||||
{data && (
|
||||
<div className="stat-row">
|
||||
<div className="stat">
|
||||
<b>{data.today.games}</b>
|
||||
<span>최근 24시간 게임</span>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<b>{data.today.plays}</b>
|
||||
<span>최근 24시간 문제</span>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<b>{data.suggestions}</b>
|
||||
<span>난이도 조정 제안</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<p className="muted small">5번 이상 나온 곡만 제안해요. 80% 넘게 8초 안에 맞히면 한 단계 쉽게, 30% 아래로 맞히면 한 단계 어렵게.</p>
|
||||
<div className="row">
|
||||
<label className="field-inline">
|
||||
정렬
|
||||
<select className="input sm" value={sort} onChange={(e) => (setSort(e.target.value), setPage(0))}>
|
||||
<option value="plays">출제 수</option>
|
||||
<option value="correct">정답률</option>
|
||||
<option value="fast">빨리 맞힌 순</option>
|
||||
<option value="suggest">조정 제안만</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>노래</th>
|
||||
<th>난이도</th>
|
||||
<th>출제</th>
|
||||
<th>정답률</th>
|
||||
<th>평균 정답 시간</th>
|
||||
<th>마지막</th>
|
||||
<th>제안</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.rows.map((r) => (
|
||||
<tr key={r.id}>
|
||||
<td>
|
||||
<b>{r.title}</b> - {r.artist}
|
||||
</td>
|
||||
<td className="mono">{r.level ? `★${r.level}` : '-'}</td>
|
||||
<td className="mono">{r.plays}</td>
|
||||
<td className="mono">{pct(r.correct, r.plays)}</td>
|
||||
<td className="mono">{r.avg_ms !== null ? `${(r.avg_ms / 1000).toFixed(1)}초` : '-'}</td>
|
||||
<td className="small">{fmt(r.last_at)}</td>
|
||||
<td>
|
||||
{r.suggest !== null && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
onClick={() => void apiCall('POST', '/api/admin/stats/apply', { songId: r.id, level: r.suggest }).then(() => (toast(`★${r.suggest}로 바꿨어요.`), reload()), (e: Error) => toast(e.message, 'error'))}
|
||||
>
|
||||
★{r.level} → ★{r.suggest} 승인
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{data?.rows.length === 0 && <p className="muted">아직 게임 기록이 없어요.</p>}
|
||||
<div className="row">
|
||||
<button className="btn btn-sm" disabled={page === 0} onClick={() => setPage(page - 1)}>
|
||||
이전
|
||||
</button>
|
||||
<span className="muted small mono">
|
||||
{page + 1} / {pages}
|
||||
</span>
|
||||
<button className="btn btn-sm" disabled={page + 1 >= pages} onClick={() => setPage(page + 1)}>
|
||||
다음
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 방
|
||||
interface AdminRoom {
|
||||
code: string;
|
||||
title: string;
|
||||
visibility: string;
|
||||
status: 'lobby' | 'playing';
|
||||
host: string;
|
||||
createdAt: number;
|
||||
game: { phase: string; n: number; total: number } | null;
|
||||
players: { id: string; nickname: string; online: boolean }[];
|
||||
}
|
||||
|
||||
export function RoomsPage() {
|
||||
const { data, reload } = useLoad<{ rooms: AdminRoom[] }>('/api/admin/rooms');
|
||||
const [closing, setClosing] = useState<AdminRoom | null>(null);
|
||||
useEffect(() => {
|
||||
const t = setInterval(reload, 5000);
|
||||
return () => clearInterval(t);
|
||||
}, [reload]);
|
||||
return (
|
||||
<>
|
||||
<h1>방</h1>
|
||||
<p className="muted small">비공개 방까지 모두 보여요. 5초마다 새로 고쳐요.</p>
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>코드</th>
|
||||
<th>이름</th>
|
||||
<th>공개</th>
|
||||
<th>상태</th>
|
||||
<th>방장</th>
|
||||
<th>참가자</th>
|
||||
<th>만든 시각</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.rooms.map((r) => (
|
||||
<tr key={r.code}>
|
||||
<td className="mono">{r.code}</td>
|
||||
<td>{r.title}</td>
|
||||
<td className="small">{{ public: '공개', private: '비공개', password: '비밀번호' }[r.visibility] ?? r.visibility}</td>
|
||||
<td>
|
||||
<span className={`badge ${r.status === 'playing' ? 'live' : 'teal'}`}>{r.status === 'playing' ? (r.game ? `게임 ${r.game.n}/${r.game.total}` : '게임 중') : '대기'}</span>
|
||||
</td>
|
||||
<td>{r.host}</td>
|
||||
<td className="small">
|
||||
{r.players.length}명 · {r.players.map((p) => `${p.nickname}${p.online ? '' : '(끊김)'}`).join(', ')}
|
||||
</td>
|
||||
<td className="small">{fmt(r.createdAt)}</td>
|
||||
<td>
|
||||
<button type="button" className="btn btn-sm btn-danger" onClick={() => setClosing(r)}>
|
||||
강제 종료
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{data?.rooms.length === 0 && <p className="muted">열린 방이 없어요.</p>}
|
||||
{closing && (
|
||||
<ConfirmSheet
|
||||
title={`"${closing.title}" 방을 닫을까요?`}
|
||||
body={`${closing.players.length}명이 첫 화면으로 돌아가고 "관리자가 방을 닫았어요" 안내를 봐요.`}
|
||||
confirm="강제 종료"
|
||||
danger
|
||||
onConfirm={() => void apiCall('POST', `/api/admin/rooms/${closing.code}/close`).then(() => (toast('방을 닫았어요.'), reload()), (e: Error) => toast(e.message, 'error'))}
|
||||
onClose={() => setClosing(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 수집
|
||||
interface Job {
|
||||
id: number;
|
||||
kind: string;
|
||||
status: string;
|
||||
done: number;
|
||||
total: number;
|
||||
started_at: number;
|
||||
finished_at: number | null;
|
||||
}
|
||||
const STATUS: Record<string, string> = { running: '진행 중', done: '완료', failed: '실패', stopped: '멈춤' };
|
||||
|
||||
export function CollectPage() {
|
||||
const { data, reload } = useLoad<{ kinds: { id: string; label: string; limit?: boolean }[]; jobs: Job[]; cookieProblem: boolean }>('/api/admin/collect');
|
||||
const [limit, setLimit] = useState<Record<string, string>>({});
|
||||
const [log, setLog] = useState<{ id: number; text: string } | null>(null);
|
||||
useEffect(() => {
|
||||
const t = setInterval(reload, 5000);
|
||||
return () => clearInterval(t);
|
||||
}, [reload]);
|
||||
const label = (kind: string) => data?.kinds.find((k) => k.id === kind)?.label ?? { 'import-norabose': '노라보세 가져오기', 'import-sta': '스타맵 가져오기' }[kind] ?? kind;
|
||||
return (
|
||||
<>
|
||||
<h1>수집</h1>
|
||||
{data?.cookieProblem && <p className="guest-warning">⚠ 유튜브 뮤직 쿠키가 로그아웃된 것 같아요. 새 쿠키를 서버에 넣어야 원곡 찾기가 다시 돌아요.</p>}
|
||||
<p className="muted small">작업은 서버에서 따로 돌아가요(게임에는 영향 없음). 유튜브 원곡 찾기는 매일 새벽 4시 10분에 3,000곡씩 자동으로도 돌아요.</p>
|
||||
<div className="stack">
|
||||
{data?.kinds.map((k) => {
|
||||
const running = data.jobs.find((j) => j.kind === k.id && j.status === 'running');
|
||||
return (
|
||||
<div key={k.id} className="card row">
|
||||
<b className="grow">{k.label}</b>
|
||||
{k.limit && (
|
||||
<label className="field-inline">
|
||||
곡 수
|
||||
<input className="input sm" inputMode="numeric" placeholder="300" value={limit[k.id] ?? ''} onChange={(e) => setLimit({ ...limit, [k.id]: e.target.value.replace(/\D/g, '') })} aria-label={`${k.label} 곡 수`} />
|
||||
</label>
|
||||
)}
|
||||
{running ? (
|
||||
<>
|
||||
<span className="mono small">
|
||||
{running.done.toLocaleString()} / {running.total.toLocaleString()}
|
||||
</span>
|
||||
<button type="button" className="btn btn-sm btn-danger" onClick={() => void apiCall('POST', `/api/admin/collect/${running.id}/stop`).then(() => (toast('멈추라고 했어요.'), reload()), (e: Error) => toast(e.message, 'error'))}>
|
||||
멈추기
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-primary"
|
||||
onClick={() =>
|
||||
void apiCall('POST', '/api/admin/collect/run', { kind: k.id, ...(k.limit ? { limit: Number(limit[k.id] || 300) } : {}) }).then(
|
||||
() => (toast('시작했어요.'), setTimeout(reload, 1500)),
|
||||
(e: Error) => toast(e.message, 'error'),
|
||||
)
|
||||
}
|
||||
>
|
||||
실행
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<h2>기록</h2>
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>작업</th>
|
||||
<th>상태</th>
|
||||
<th>진행</th>
|
||||
<th>시작</th>
|
||||
<th>끝</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.jobs.map((j) => (
|
||||
<tr key={j.id}>
|
||||
<td>{label(j.kind)}</td>
|
||||
<td>{STATUS[j.status] ?? j.status}</td>
|
||||
<td className="mono">
|
||||
{j.done.toLocaleString()} / {j.total.toLocaleString()}
|
||||
</td>
|
||||
<td className="small">{fmt(j.started_at)}</td>
|
||||
<td className="small">{fmt(j.finished_at)}</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
onClick={() => void apiCall<{ job: { log: string } }>('GET', `/api/admin/collect/${j.id}`).then((r) => setLog({ id: j.id, text: r.job.log || '(기록 없음)' }), (e: Error) => toast(e.message, 'error'))}
|
||||
>
|
||||
로그
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{log && (
|
||||
<div className="card">
|
||||
<div className="row">
|
||||
<b className="grow">작업 #{log.id} 로그</b>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setLog(null)}>
|
||||
닫기
|
||||
</button>
|
||||
</div>
|
||||
<pre className="lyrics" style={{ maxHeight: 360, overflow: 'auto' }}>
|
||||
{log.text}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
/**
|
||||
* 관리자 → 노래 (docs/02 노래 관리 화면): 검색·필터·정렬 표 + 오른쪽 편집 패널(유튜브 미리듣기·후보 고르기·하이라이트·별칭).
|
||||
* 관리자 → 노래 (docs/02 노래 관리 화면): 검색(초성 포함)·필터·정렬 표 + 오른쪽 편집 패널(유튜브 미리듣기·후보 고르기·
|
||||
* 하이라이트 "지금 위치로"·별칭), 노래 추가, 선택한 곡 일괄 작업, 휴지통, 가져오기/내보내기, 중복 정리.
|
||||
*/
|
||||
import { useCallback, useEffect, useMemo, useState, type FormEvent } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type FormEvent } from 'react';
|
||||
import { apiCall } from '../../net/api';
|
||||
import { toast } from '../../store/toast';
|
||||
import { ConfirmSheet, Sheet } from '../../components/ui';
|
||||
|
||||
interface Genre {
|
||||
id: string;
|
||||
@@ -28,6 +30,9 @@ interface Row {
|
||||
sources: string[];
|
||||
has_lyrics: boolean;
|
||||
hidden: boolean;
|
||||
plays: number;
|
||||
correct: number;
|
||||
deleted_at: number | null;
|
||||
}
|
||||
interface Detail {
|
||||
song: Row & { youtube_title: string | null; highlight_sec: number | null; highlight_source: string | null; note: string | null; mv_youtube_id: string | null };
|
||||
@@ -52,7 +57,7 @@ const YT_LABEL: Record<Row['youtube_status'], [string, string]> = {
|
||||
none: ['없음', ''],
|
||||
dead: ['재생 불가', 'warn'],
|
||||
};
|
||||
const SOURCE_LABEL: Record<string, string> = { norabose: '노라보세', sta: '스타맵' };
|
||||
const SOURCE_LABEL: Record<string, string> = { norabose: '노라보세', sta: '스타맵', admin: '관리자' };
|
||||
const mmss = (s: number | null) => (s == null ? '-' : `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, '0')}`);
|
||||
const pct = (n: number, d: number) => (d ? `${Math.round((n / d) * 100)}%` : '-');
|
||||
|
||||
@@ -60,9 +65,16 @@ export function SongsPage() {
|
||||
const [genres, setGenres] = useState<Genre[]>([]);
|
||||
const [stats, setStats] = useState<Stats | null>(null);
|
||||
const [q, setQ] = useState('');
|
||||
const [f, setF] = useState({ q: '', genres: [] as string[], yearFrom: '', yearTo: '', level: '', youtube: '', source: '', sort: 'recent', page: 0 });
|
||||
const [f, setF] = useState({ q: '', genres: [] as string[], yearFrom: '', yearTo: '', level: '', youtube: '', source: '', sort: 'recent', lyrics: '', highlight: '', hidden: '', trash: '', page: 0 });
|
||||
const [data, setData] = useState<{ total: number; rows: Row[]; pageSize: number } | null>(null);
|
||||
const [selected, setSelected] = useState<number | null>(null);
|
||||
const [checked, setChecked] = useState<Set<number>>(new Set());
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [dupes, setDupes] = useState(false);
|
||||
const [bulkAct, setBulkAct] = useState('hide');
|
||||
const [bulkVal, setBulkVal] = useState('');
|
||||
const [confirmBulk, setConfirmBulk] = useState(false);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const loadStats = useCallback(() => void apiCall<Stats>('GET', '/api/admin/catalog').then(setStats).catch(() => {}), []);
|
||||
useEffect(() => {
|
||||
@@ -74,7 +86,7 @@ export function SongsPage() {
|
||||
const p = new URLSearchParams();
|
||||
if (f.q) p.set('q', f.q);
|
||||
if (f.genres.length) p.set('genres', f.genres.join(','));
|
||||
for (const k of ['yearFrom', 'yearTo', 'level', 'youtube', 'source', 'sort'] as const) if (f[k]) p.set(k, f[k]);
|
||||
for (const k of ['yearFrom', 'yearTo', 'level', 'youtube', 'source', 'sort', 'lyrics', 'highlight', 'hidden', 'trash'] as const) if (f[k]) p.set(k, f[k]);
|
||||
p.set('page', String(f.page));
|
||||
return p.toString();
|
||||
}, [f]);
|
||||
@@ -85,14 +97,81 @@ export function SongsPage() {
|
||||
}, [query]);
|
||||
useEffect(reload, [reload]);
|
||||
|
||||
const set = (patch: Partial<typeof f>) => setF((x) => ({ ...x, page: 0, ...patch }));
|
||||
const set = (patch: Partial<typeof f>) => {
|
||||
setChecked(new Set());
|
||||
setF((x) => ({ ...x, page: 0, ...patch }));
|
||||
};
|
||||
const trash = f.trash === '1';
|
||||
const exportQuery = query.replace(/(^|&)page=\d+/, '');
|
||||
const runBulk = async () => {
|
||||
const ids = [...checked];
|
||||
const body: Record<string, unknown> = { ids, action: bulkAct };
|
||||
if (bulkAct === 'level') body.level = bulkVal ? Number(bulkVal) : null;
|
||||
if (bulkAct === 'addGenre' || bulkAct === 'removeGenre') body.genre = bulkVal;
|
||||
try {
|
||||
const r = await apiCall<{ changed: number }>('POST', '/api/admin/songs/bulk', body);
|
||||
toast(`${r.changed}곡에 적용했어요.`);
|
||||
setChecked(new Set());
|
||||
reload();
|
||||
loadStats();
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
}
|
||||
};
|
||||
const importFile = async (file: File) => {
|
||||
const text = await file.text();
|
||||
const format = /\.csv$/i.test(file.name) ? 'csv' : 'json';
|
||||
try {
|
||||
const r = await apiCall<{ added: number; existing: number; skipped: number[]; badVideo: number }>('POST', '/api/admin/songs/import', { format, text });
|
||||
toast(`새 곡 ${r.added}곡, 이미 있던 곡 ${r.existing}곡${r.skipped.length ? `, 건너뛴 줄 ${r.skipped.length}개` : ''}${r.badVideo ? `, 쓸 수 없는 영상 ${r.badVideo}개` : ''}`, 'info', 6000);
|
||||
reload();
|
||||
loadStats();
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
}
|
||||
};
|
||||
const toggleGenre = (id: string) => set({ genres: f.genres.includes(id) ? f.genres.filter((g) => g !== id) : [...f.genres, id] });
|
||||
const pages = data ? Math.max(1, Math.ceil(data.total / data.pageSize)) : 1;
|
||||
|
||||
return (
|
||||
<div className={`songs-layout ${selected ? 'with-panel' : ''}`}>
|
||||
<div className="stack" style={{ minWidth: 0 }}>
|
||||
<h1>노래</h1>
|
||||
<div className="row">
|
||||
<h1 className="grow">{trash ? '휴지통' : '노래'}</h1>
|
||||
{!trash && (
|
||||
<button type="button" className="btn btn-primary btn-sm" onClick={() => setAdding(true)}>
|
||||
+ 노래 추가
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="btn btn-sm" onClick={() => setDupes(true)}>
|
||||
중복 정리
|
||||
</button>
|
||||
<a className="btn btn-sm" href={`/api/admin/songs/export?${exportQuery}&format=csv`} download>
|
||||
CSV 내보내기
|
||||
</a>
|
||||
<a className="btn btn-sm" href={`/api/admin/songs/export?${exportQuery}`} download>
|
||||
JSON 내보내기
|
||||
</a>
|
||||
<button type="button" className="btn btn-sm" onClick={() => fileRef.current?.click()}>
|
||||
가져오기
|
||||
</button>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept=".csv,.json,application/json,text/csv"
|
||||
hidden
|
||||
aria-label="가져올 파일"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) void importFile(file);
|
||||
e.target.value = '';
|
||||
}}
|
||||
/>
|
||||
<button type="button" className={`btn btn-sm ${trash ? 'btn-mustard' : ''}`} aria-pressed={trash} onClick={() => set({ trash: trash ? '' : '1' })}>
|
||||
🗑 휴지통
|
||||
</button>
|
||||
</div>
|
||||
{trash && <p className="muted small">지운 곡은 30일 동안 여기에 있다가 완전히 지워져요. 복원하면 다시 출제돼요.</p>}
|
||||
{stats && (
|
||||
<div className="stat-row">
|
||||
<div className="stat">
|
||||
@@ -179,13 +258,98 @@ export function SongsPage() {
|
||||
<option value="level">난이도</option>
|
||||
<option value="peak">차트 최고 순위</option>
|
||||
<option value="title">제목</option>
|
||||
<option value="plays">출제 수</option>
|
||||
<option value="correct">정답률</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="field-inline">
|
||||
가사
|
||||
<select className="input sm" value={f.lyrics} onChange={(e) => set({ lyrics: e.target.value })}>
|
||||
<option value="">전체</option>
|
||||
<option value="1">있음</option>
|
||||
<option value="0">없음</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="field-inline">
|
||||
하이라이트
|
||||
<select className="input sm" value={f.highlight} onChange={(e) => set({ highlight: e.target.value })}>
|
||||
<option value="">전체</option>
|
||||
<option value="1">있음</option>
|
||||
<option value="0">없음</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="field-inline">
|
||||
숨김
|
||||
<select className="input sm" value={f.hidden} onChange={(e) => set({ hidden: e.target.value })}>
|
||||
<option value="">전체</option>
|
||||
<option value="0">출제</option>
|
||||
<option value="1">숨김</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
{checked.size > 0 && (
|
||||
<div className="row bulk-bar" role="region" aria-label="선택한 곡 일괄 작업">
|
||||
<b>{checked.size}곡 선택</b>
|
||||
<select className="input sm" style={{ width: 'auto' }} value={bulkAct} onChange={(e) => (setBulkAct(e.target.value), setBulkVal(''))} aria-label="일괄 작업">
|
||||
{trash ? (
|
||||
<option value="restore">복원</option>
|
||||
) : (
|
||||
<>
|
||||
<option value="hide">숨기기</option>
|
||||
<option value="show">출제하기(숨김 해제)</option>
|
||||
<option value="level">난이도 바꾸기</option>
|
||||
<option value="addGenre">장르 넣기</option>
|
||||
<option value="removeGenre">장르 빼기</option>
|
||||
<option value="rematch">유튜브 다시 찾기</option>
|
||||
<option value="trash">휴지통으로</option>
|
||||
</>
|
||||
)}
|
||||
</select>
|
||||
{bulkAct === 'level' && (
|
||||
<select className="input sm" style={{ width: 'auto' }} value={bulkVal} onChange={(e) => setBulkVal(e.target.value)} aria-label="바꿀 난이도">
|
||||
<option value="">없음</option>
|
||||
{Array.from({ length: 10 }, (_, i) => (
|
||||
<option key={i + 1} value={i + 1}>
|
||||
{i + 1}단계
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{(bulkAct === 'addGenre' || bulkAct === 'removeGenre') && (
|
||||
<select className="input sm" style={{ width: 'auto' }} value={bulkVal} onChange={(e) => setBulkVal(e.target.value)} aria-label="장르">
|
||||
<option value="">장르 고르기</option>
|
||||
{genres.map((g) => (
|
||||
<option key={g.id} value={g.id}>
|
||||
{g.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-primary"
|
||||
disabled={(bulkAct === 'addGenre' || bulkAct === 'removeGenre') && !bulkVal}
|
||||
onClick={() => (bulkAct === 'trash' || bulkAct === 'rematch' ? setConfirmBulk(true) : void runBulk())}
|
||||
>
|
||||
적용
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setChecked(new Set())}>
|
||||
선택 해제
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label="이 쪽 전체 선택"
|
||||
checked={!!data?.rows.length && data.rows.every((r) => checked.has(r.id))}
|
||||
onChange={(e) => setChecked(e.target.checked ? new Set([...checked, ...(data?.rows.map((r) => r.id) ?? [])]) : new Set([...checked].filter((id) => !data?.rows.some((r) => r.id === id))))}
|
||||
/>
|
||||
</th>
|
||||
<th>제목</th>
|
||||
<th>가수</th>
|
||||
<th>연도</th>
|
||||
@@ -193,14 +357,29 @@ export function SongsPage() {
|
||||
<th>난이도</th>
|
||||
<th>유튜브</th>
|
||||
<th>가사</th>
|
||||
<th>출제·정답률</th>
|
||||
<th>출처</th>
|
||||
{trash && <th />}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data?.rows.map((r) => (
|
||||
<tr key={r.id} className={selected === r.id ? 'sel' : ''} onClick={() => setSelected(r.id)} style={{ cursor: 'pointer' }}>
|
||||
<tr key={r.id} className={selected === r.id ? 'sel' : ''} onClick={() => !trash && setSelected(r.id)} style={{ cursor: trash ? 'default' : 'pointer' }}>
|
||||
<td onClick={(e) => e.stopPropagation()}>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={`${r.title} 선택`}
|
||||
checked={checked.has(r.id)}
|
||||
onChange={(e) => {
|
||||
const next = new Set(checked);
|
||||
if (e.target.checked) next.add(r.id);
|
||||
else next.delete(r.id);
|
||||
setChecked(next);
|
||||
}}
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<button type="button" className="linklike" onClick={() => setSelected(r.id)}>
|
||||
<button type="button" className="linklike" disabled={trash} onClick={() => setSelected(r.id)}>
|
||||
{r.title}
|
||||
</button>
|
||||
{r.hidden && <span className="badge">숨김</span>}
|
||||
@@ -213,7 +392,25 @@ export function SongsPage() {
|
||||
<span className={`badge ${YT_LABEL[r.youtube_status][1]}`}>{YT_LABEL[r.youtube_status][0]}</span>
|
||||
</td>
|
||||
<td>{r.has_lyrics ? '있음' : '-'}</td>
|
||||
<td className="mono small">{r.plays ? `${r.plays}회 · ${pct(r.correct, r.plays)}` : '-'}</td>
|
||||
<td className="small">{r.sources.map((s) => SOURCE_LABEL[s] ?? s).join(', ')}</td>
|
||||
{trash && (
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
void apiCall('POST', `/api/admin/songs/${r.id}/restore`).then(
|
||||
() => (toast('복원했어요.'), reload(), loadStats()),
|
||||
(ex: Error) => toast(ex.message, 'error'),
|
||||
);
|
||||
}}
|
||||
>
|
||||
복원
|
||||
</button>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
@@ -243,14 +440,171 @@ export function SongsPage() {
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{adding && (
|
||||
<AddSongSheet
|
||||
genres={genres}
|
||||
onClose={() => setAdding(false)}
|
||||
onAdded={(id) => {
|
||||
setAdding(false);
|
||||
reload();
|
||||
loadStats();
|
||||
setSelected(id);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{dupes && <DuplicatesSheet onClose={() => setDupes(false)} onMerged={() => (reload(), loadStats())} />}
|
||||
{confirmBulk && (
|
||||
<ConfirmSheet
|
||||
title={bulkAct === 'trash' ? `${checked.size}곡을 휴지통으로 옮길까요?` : `${checked.size}곡의 유튜브를 다시 찾을까요?`}
|
||||
body={bulkAct === 'trash' ? '30일 안에는 휴지통에서 복원할 수 있어요.' : '지금 영상(관리자가 정한 영상 포함)을 지우고, 다음 원곡 찾기 때 다시 찾아요.'}
|
||||
confirm="적용"
|
||||
danger={bulkAct === 'trash'}
|
||||
onConfirm={() => void runBulk()}
|
||||
onClose={() => setConfirmBulk(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 노래 추가: 제목 + 가수만 넣어도 돼요. 유튜브 주소를 넣으면 퍼가기 가능 여부를 확인해요. */
|
||||
function AddSongSheet({ genres, onClose, onAdded }: { genres: Genre[]; onClose: () => void; onAdded: (id: number) => void }) {
|
||||
const [form, setForm] = useState({ title: '', artist: '', year: '', level: '', youtube: '', genres: [] as string[] });
|
||||
const [busy, setBusy] = useState(false);
|
||||
return (
|
||||
<Sheet label="노래 추가" onClose={onClose}>
|
||||
<h2>노래 추가</h2>
|
||||
<form
|
||||
className="stack"
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await apiCall<{ id: number }>('POST', '/api/admin/songs', {
|
||||
title: form.title.trim(),
|
||||
artist: form.artist.trim(),
|
||||
year: form.year ? Number(form.year) : null,
|
||||
level: form.level ? Number(form.level) : null,
|
||||
genres: form.genres,
|
||||
youtube: form.youtube.trim() || null,
|
||||
});
|
||||
toast('추가했어요.');
|
||||
onAdded(r.id);
|
||||
} catch (ex) {
|
||||
toast((ex as Error).message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<label className="field">
|
||||
제목
|
||||
<input className="input" autoFocus value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
가수 (여러 명이면 쉼표로)
|
||||
<input className="input" value={form.artist} onChange={(e) => setForm({ ...form, artist: e.target.value })} />
|
||||
</label>
|
||||
<div className="two">
|
||||
<label className="field">
|
||||
연도
|
||||
<input className="input" inputMode="numeric" value={form.year} onChange={(e) => setForm({ ...form, year: e.target.value.replace(/\D/g, '') })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
난이도
|
||||
<select className="input" value={form.level} onChange={(e) => setForm({ ...form, level: e.target.value })}>
|
||||
<option value="">없음</option>
|
||||
{Array.from({ length: 10 }, (_, i) => (
|
||||
<option key={i + 1} value={i + 1}>
|
||||
{i + 1}단계
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div className="row">
|
||||
{genres.map((g) => (
|
||||
<button
|
||||
key={g.id}
|
||||
type="button"
|
||||
className="chip"
|
||||
aria-pressed={form.genres.includes(g.id)}
|
||||
onClick={() => setForm({ ...form, genres: form.genres.includes(g.id) ? form.genres.filter((x) => x !== g.id) : [...form.genres, g.id] })}
|
||||
>
|
||||
{g.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<label className="field">
|
||||
유튜브 주소 (없으면 비워 두세요. 원곡 찾기가 찾아요)
|
||||
<input className="input" placeholder="https://youtu.be/…" value={form.youtube} onChange={(e) => setForm({ ...form, youtube: e.target.value })} />
|
||||
</label>
|
||||
<button className="btn btn-primary btn-block" disabled={busy || !form.title.trim() || !form.artist.trim()}>
|
||||
{busy ? '추가하는 중…' : '추가'}
|
||||
</button>
|
||||
</form>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
interface DupGroup {
|
||||
key: string;
|
||||
songs: { id: number; title: string; artist: string; year: number | null; youtube_status: string; plays: number }[];
|
||||
}
|
||||
|
||||
/** 중복 정리: same normalized title+artist. Pick the one to keep; the others merge into it. */
|
||||
function DuplicatesSheet({ onClose, onMerged }: { onClose: () => void; onMerged: () => void }) {
|
||||
const [groups, setGroups] = useState<DupGroup[] | null>(null);
|
||||
const [keep, setKeep] = useState<Record<string, number>>({});
|
||||
const load = useCallback(() => void apiCall<{ groups: DupGroup[] }>('GET', '/api/admin/songs/duplicates').then((r) => setGroups(r.groups), (e: Error) => toast(e.message, 'error')), []);
|
||||
useEffect(load, [load]);
|
||||
return (
|
||||
<Sheet label="중복 정리" onClose={onClose}>
|
||||
<h2>중복 정리</h2>
|
||||
<p className="muted small">제목·가수를 정리했을 때 같은 곡이에요. 남길 곡을 고르면 나머지의 별칭·장르·출처·영상·통계를 옮기고 휴지통으로 보내요.</p>
|
||||
{!groups ? (
|
||||
<p className="muted">불러오는 중…</p>
|
||||
) : groups.length === 0 ? (
|
||||
<p className="muted">중복된 곡이 없어요.</p>
|
||||
) : (
|
||||
<div className="stack" style={{ maxHeight: '60vh', overflowY: 'auto' }}>
|
||||
{groups.map((g) => {
|
||||
const target = keep[g.key] ?? g.songs.find((x) => x.youtube_status === 'matched')?.id ?? g.songs[0]!.id;
|
||||
return (
|
||||
<div key={g.key} className="card">
|
||||
{g.songs.map((x) => (
|
||||
<label key={x.id} className="check">
|
||||
<input type="radio" name={g.key} checked={target === x.id} onChange={() => setKeep({ ...keep, [g.key]: x.id })} />
|
||||
#{x.id} {x.title} - {x.artist} {x.year ?? ''} <span className="badge">{x.youtube_status}</span> {x.plays ? <span className="small muted">출제 {x.plays}</span> : null}
|
||||
</label>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-primary"
|
||||
onClick={() =>
|
||||
void apiCall('POST', '/api/admin/songs/merge', { target, others: g.songs.map((x) => x.id).filter((id) => id !== target) }).then(
|
||||
() => (toast('합쳤어요.'), load(), onMerged()),
|
||||
(e: Error) => toast(e.message, 'error'),
|
||||
)
|
||||
}
|
||||
>
|
||||
#{target}로 합치기
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
function SongEditor({ id, genres, onClose, onSaved }: { id: number; genres: Genre[]; onClose: () => void; onSaved: () => void }) {
|
||||
const [d, setD] = useState<Detail | null>(null);
|
||||
const [form, setForm] = useState({ title: '', artist: '', year: '', level: '', youtube: '', highlight: '', titleAliases: '', artistAliases: '', note: '', hidden: false, genres: [] as string[] });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [confirmTrash, setConfirmTrash] = useState(false);
|
||||
const previewRef = useRef<{ time(): number | undefined } | null>(null);
|
||||
/** The address as loaded: `youtube` is only sent when the admin changed it (review 2026-10-18). */
|
||||
const [loadedYoutube, setLoadedYoutube] = useState('');
|
||||
const load = useCallback(() => {
|
||||
@@ -406,14 +760,21 @@ function SongEditor({ id, genres, onClose, onSaved }: { id: number; genres: Genr
|
||||
</button>
|
||||
)}
|
||||
{videoId && (
|
||||
<div className="yt-preview">
|
||||
<iframe
|
||||
src={`https://www.youtube-nocookie.com/embed/${videoId}${form.highlight ? `?start=${Math.floor(Number(form.highlight))}` : ''}`}
|
||||
title="유튜브 미리듣기"
|
||||
allow="autoplay; encrypted-media"
|
||||
loading="lazy"
|
||||
/>
|
||||
</div>
|
||||
<>
|
||||
<YtPreview videoId={videoId} start={form.highlight ? Number(form.highlight) : 0} apiRef={previewRef} />
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
onClick={() => {
|
||||
const t = previewRef.current?.time();
|
||||
if (t === undefined) return toast('미리듣기를 먼저 재생해 주세요.', 'error');
|
||||
setForm({ ...form, highlight: t.toFixed(1) });
|
||||
toast(`하이라이트를 ${t.toFixed(1)}초로 정했어요. 저장을 눌러 주세요.`);
|
||||
}}
|
||||
>
|
||||
⏱ 지금 위치를 하이라이트로
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{d.candidates.length > 0 && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
@@ -466,51 +827,71 @@ function SongEditor({ id, genres, onClose, onSaved }: { id: number; genres: Genr
|
||||
<button className="btn btn-primary" disabled={busy}>
|
||||
{busy ? '저장 중…' : '저장'}
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setConfirmTrash(true)}>
|
||||
🗑 휴지통으로
|
||||
</button>
|
||||
</form>
|
||||
{confirmTrash && (
|
||||
<ConfirmSheet
|
||||
title="이 노래를 휴지통으로 옮길까요?"
|
||||
body="30일 안에는 휴지통에서 복원할 수 있어요."
|
||||
confirm="휴지통으로"
|
||||
danger
|
||||
onConfirm={() =>
|
||||
void apiCall('DELETE', `/api/admin/songs/${id}`).then(
|
||||
() => (toast('휴지통으로 옮겼어요.'), onSaved(), onClose()),
|
||||
(e: Error) => toast(e.message, 'error'),
|
||||
)
|
||||
}
|
||||
onClose={() => setConfirmTrash(false)}
|
||||
/>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
export function CollectPage() {
|
||||
const [stats, setStats] = useState<Stats | null>(null);
|
||||
useEffect(() => {
|
||||
const load = () => void apiCall<Stats>('GET', '/api/admin/catalog').then(setStats).catch(() => {});
|
||||
load();
|
||||
const t = setInterval(load, 10_000);
|
||||
return () => clearInterval(t);
|
||||
}, []);
|
||||
const KIND: Record<string, string> = { 'import-norabose': '노라보세 가져오기', 'import-sta': '스타맵 가져오기', 'match-youtube': '유튜브 원곡 찾기' };
|
||||
const STATUS: Record<string, string> = { running: '진행 중', done: '완료', failed: '실패', stopped: '멈춤' };
|
||||
return (
|
||||
<>
|
||||
<h1>수집</h1>
|
||||
<p className="muted small">수집 작업은 서버에서 따로 돌아가요. 지금은 실행 기록만 보여요(관리자 화면에서 실행하는 기능은 다음 단계).</p>
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>작업</th>
|
||||
<th>상태</th>
|
||||
<th>진행</th>
|
||||
<th>시작</th>
|
||||
<th>끝</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{stats?.jobs.map((j) => (
|
||||
<tr key={j.id}>
|
||||
<td>{KIND[j.kind] ?? j.kind}</td>
|
||||
<td>{STATUS[j.status] ?? j.status}</td>
|
||||
<td className="mono">
|
||||
{j.done.toLocaleString()} / {j.total.toLocaleString()}
|
||||
</td>
|
||||
<td className="small">{new Date(j.started_at).toLocaleString('ko-KR')}</td>
|
||||
<td className="small">{j.finished_at ? new Date(j.finished_at).toLocaleString('ko-KR') : '-'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
declare global {
|
||||
interface Window {
|
||||
YT?: any;
|
||||
onYouTubeIframeAPIReady?: () => void;
|
||||
}
|
||||
}
|
||||
|
||||
let ytApi: Promise<void> | null = null;
|
||||
function loadYt(): Promise<void> {
|
||||
ytApi ??= new Promise<void>((resolve) => {
|
||||
if (window.YT?.Player) return resolve();
|
||||
const prev = window.onYouTubeIframeAPIReady;
|
||||
window.onYouTubeIframeAPIReady = () => {
|
||||
prev?.();
|
||||
resolve();
|
||||
};
|
||||
const sc = document.createElement('script');
|
||||
sc.src = 'https://www.youtube.com/iframe_api';
|
||||
document.head.appendChild(sc);
|
||||
});
|
||||
return ytApi;
|
||||
}
|
||||
|
||||
/** 미리듣기 with the IFrame API, so "지금 위치를 하이라이트로" can read the position. */
|
||||
function YtPreview({ videoId, start, apiRef }: { videoId: string; start: number; apiRef: { current: { time(): number | undefined } | null } }) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
let player: any = null;
|
||||
let dead = false;
|
||||
void loadYt().then(() => {
|
||||
if (dead || !host.current) return;
|
||||
const el = document.createElement('div');
|
||||
host.current.replaceChildren(el);
|
||||
player = new window.YT.Player(el, { videoId, width: '100%', height: '100%', playerVars: { start: Math.floor(start), rel: 0, playsinline: 1 } });
|
||||
apiRef.current = { time: () => (typeof player?.getCurrentTime === 'function' ? player.getCurrentTime() : undefined) };
|
||||
});
|
||||
return () => {
|
||||
dead = true;
|
||||
apiRef.current = null;
|
||||
if (typeof player?.destroy === 'function') player.destroy();
|
||||
};
|
||||
// start only matters when the video changes
|
||||
}, [videoId]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
return <div className="yt-preview" ref={host} aria-label="유튜브 미리듣기" />;
|
||||
}
|
||||
|
||||
@@ -444,3 +444,4 @@ input.input.sm { width: 76px; }
|
||||
.welcome h1 { font-size: 1.75rem; }
|
||||
.header-user-name { display: none; }
|
||||
}
|
||||
.bulk-bar { background: var(--primary-soft); border: 2px solid var(--ink); border-radius: 12px; padding: 8px 12px; position: sticky; top: 72px; z-index: 5; }
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
| 5. 게임 핵심 ✔ | 라운드 진행, 숨긴 유튜브 플레이어 동기화 재생(준비·동시 시작·버퍼링 일시정지), 정답 판정, 점수, 결과, 이어풀기·저장/불러오기 | 3명 동시 e2e로 30문제 끝까지, 정답 판정 단위 테스트 |
|
||||
| 6. 채팅 ✔ | 가운데 아래 큰 채팅, 입력 중, 5줄 정답 블록, 단축키 | 체감 지연 없음(로컬 왕복 < 50ms), Ctrl+I/K 동작 |
|
||||
| 7. 힌트·스킵·모드 ✔ | 초성 힌트(시간/직접선택 투표), 스킵·다시듣기 투표, 가수노래·가사 모드, 하이라이트 | 모드 3종 e2e |
|
||||
| 8. 관리자 완성 | 노래 CRUD·필터·후보 확인·하이라이트 지정, 수집 작업 UI, 통계, 사용자/관리자 | 관리자 e2e(joke-app admin.e2e 확장) |
|
||||
| 8. 관리자 완성 ✔ | 노래 CRUD·필터·후보 확인·하이라이트 지정, 수집 작업 UI, 통계, 사용자/관리자 | 관리자 e2e(joke-app admin.e2e 확장) |
|
||||
| 9. 수집 확장 | 멜론·지니·벅스 연도별/실시간, 유튜브·스포티파이 플레이리스트, 노래방 차트, 난이도 계산 | 곡 1만+, 난이도 분포 확인 |
|
||||
| 10. 다듬기 | 휴대폰 화면, 다크 테마, 접근성 검사, 부하 테스트(100명 방) | axe 위반 0, 100명 방에서 채팅 지연 < 200ms |
|
||||
|
||||
@@ -26,4 +26,5 @@
|
||||
- 2026-10-18 4단계: 방 만들기(게스트 포함)·숫자 6자리 코드·열린 방 목록(전체/대기 중/진행 중, 🔒 비밀번호 방), 인원 무제한 대기실(방장·준비·방장 넘기기·내보내기, 끊겨도 60초 자리 유지), 방 설정 전체가 모두에게 즉시 반영, "조건에 맞는 곡 N곡" + 원곡 확인 중 곡 수(1분마다 다시 셈), 대기실 채팅, 서버 재시작 안내. 서버 테스트 49개, 브라우저 e2e(`e2e/rooms.e2e.ts`, 3명) 11단계 통과. 결정은 12 문서 "4단계 확인". 같은 날 새 쿠키로 유튜브 원곡 찾기 다시 시작(표본 20곡 중 16곡 확정)
|
||||
- 2026-10-18 사용자: "목록으로 나갔을 때 방에 아무도 없으면 바로 삭제, 나머지 전부 진행" → 마지막 사람이 나가면(← 방 목록·로고·뒤로 가기·나가기·내보내기 시간 초과) 방을 바로 닫음. 만들고 아무도 안 들어간 방만 5분. 탭 닫기·끊김은 60초 자리 유지 그대로
|
||||
- 2026-10-18 5~7단계(엔진이 하나라 함께 진행): 서버 게임 진행기(`apps/server/src/game/engine.ts`) — 출제 목록(최근 3게임 곡 뒤로, 같은 가수 연속 안 나오게), 전원 준비 뒤 같은 시각 재생, 버퍼링·소리 차단이면 모두 멈추고 같은 위치에서 다시, 30초 늦은 사람은 방장이 이번 문제만 제외, 재생 오류 100/101/150이면 같은 번호로 다른 곡(그 곡은 재생 불가 표시), 문제 시간(멈춘 시간 제외), 클립은 재생 위치로 정지. 정답 판정(`packages/shared/src/answer.ts`), 먼저 맞힌 1명 +1(동점은 평균 정답 시간), 정답 줄 + 5줄 블록 한 덩어리, 입력 중, Ctrl+I/K/R, 힌트(시간·직접선택), 스킵·다시듣기 투표, 3모드, 결과·이어풀기·다시 하기, 퀴즈 저장·불러오기(디스코드 계정, 20개). 서버 테스트 80개, 브라우저 e2e(`e2e/game.e2e.ts`) 3명 30문제 끝까지 + 모드 3종 + 실제 유튜브 2명 동시 재생(위치 차이 0.02초, 3초 클립 정지 오차 0.01초 이내) 통과. 결정은 12 문서 "5~7단계 확인"
|
||||
- 2026-10-18 8단계: 관리자 노래(추가·초성 검색·하이라이트/가사/숨김 필터·출제 수·정답률 정렬·일괄 작업(숨김·난이도·장르 넣기/빼기·유튜브 다시 찾기·휴지통)·휴지통 30일·CSV/JSON 내보내기·가져오기(이미 있는 곡은 그대로)·중복 병합·미리듣기 "지금 위치를 하이라이트로"), 가수 별칭(정답 인정), 장르 추가·이름·순서·숨김, 통계(곡별 출제·정답률·평균 시간, 5회 이상이면 난이도 제안 → 승인), 방(비공개 포함 목록·강제 종료), 수집(실행·멈추기·로그, 쿠키 로그아웃 경고), 사이트(문제 제한 시간, 새 방 기본 설정·잠금), 대시보드(게임 중 방·24시간 게임 수). 서버 테스트 91개, 브라우저 e2e(`e2e/admin.e2e.ts`) 10단계 통과. 가수의 그룹/유닛 연결·대표 이미지는 아직(이름·구분·별칭만)
|
||||
|
||||
|
||||
275
e2e/admin.e2e.ts
Normal file
275
e2e/admin.e2e.ts
Normal file
@@ -0,0 +1,275 @@
|
||||
/**
|
||||
* Stage 8 E2E (docs/10 관리자 완성): a superadmin in a real browser.
|
||||
* 노래 추가·일괄 작업·휴지통·초성 검색·내보내기/가져오기·중복 정리, 가수 별칭, 장르, 통계 승인, 방 강제 종료, 수집 실행/멈추기,
|
||||
* 새 방 기본 설정·잠금.
|
||||
* Run: bun run build && bun e2e/admin.e2e.ts (needs /usr/bin/google-chrome)
|
||||
*/
|
||||
import { chromium, type Browser, type BrowserContext, type Page } from 'playwright-core';
|
||||
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { loadConfig } from '../apps/server/src/config';
|
||||
import { startServer } from '../apps/server/src/server';
|
||||
import { Catalog } from '../apps/server/src/collector/catalog';
|
||||
|
||||
const PORT = Number(process.env.E2E_PORT ?? 4623);
|
||||
const ORIGIN = `http://localhost:${PORT}`;
|
||||
const SHOTS = process.env.E2E_SHOTS ?? join(import.meta.dir, '../test-results');
|
||||
mkdirSync(SHOTS, { recursive: true });
|
||||
const TMP = mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'mq-e2e-'));
|
||||
const SUPER = '900000000000000001';
|
||||
|
||||
const runs: { kind: string; limit?: number }[] = [];
|
||||
const stops: number[] = [];
|
||||
const app = startServer({
|
||||
config: loadConfig({
|
||||
PORT: String(PORT),
|
||||
DB_PATH: join(TMP, 'app.db'),
|
||||
PUBLIC_ORIGIN: ORIGIN,
|
||||
SUPERADMIN_DISCORD_IDS: SUPER,
|
||||
DISCORD_CLIENT_ID: '1561284577564037140',
|
||||
DISCORD_CLIENT_SECRET: 'e2e',
|
||||
}),
|
||||
log: () => {},
|
||||
staticDir: join(import.meta.dir, '../apps/web/dist'),
|
||||
stopWaitMs: 200,
|
||||
discordExchange: async (code) => ({ id: code, username: 'u', global_name: '사금향', avatar: null }),
|
||||
checkEmbed: async () => ({ state: 'ok', author: 'Someone - Topic', title: 'Official Audio' }),
|
||||
collect: {
|
||||
kinds: [{ id: 'match-youtube', label: '유튜브 원곡 찾기', limit: true }],
|
||||
run: (kind, limit) => {
|
||||
runs.push({ kind, limit });
|
||||
app.db.query("INSERT INTO collect_jobs (kind, status, total, started_at, log, pid) VALUES (?, 'running', ?, ?, 'started from e2e', 1)").run(kind, limit ?? 0, Date.now());
|
||||
return null;
|
||||
},
|
||||
stop: (id) => {
|
||||
stops.push(id);
|
||||
app.db.query("UPDATE collect_jobs SET status = 'stopped', finished_at = ? WHERE id = ?").run(Date.now(), id);
|
||||
return null;
|
||||
},
|
||||
},
|
||||
});
|
||||
const db = app.db;
|
||||
{
|
||||
const c = new Catalog(db);
|
||||
for (const [t, a, lv] of [
|
||||
['사건의 지평선', '윤하', 3],
|
||||
['좋은 날', '아이유', 3],
|
||||
['밤양갱', '비비', 3],
|
||||
['쉬운노래', '쉬운가수', 5],
|
||||
] as const) {
|
||||
const [id] = c.upsert({ title: t, artists: [{ name: a }], year: 2020, genres: ['kpop'], source: 'e2e', ref: t });
|
||||
c.autoLevel(id!, 'all', lv);
|
||||
db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = 'VO88htcm09E', duration_sec = 200 WHERE id = ?").run(id!);
|
||||
}
|
||||
// a duplicate row of 밤양갱 that an import missed
|
||||
db.query("INSERT INTO songs (title, artist, match_key, created_at, updated_at) SELECT '밤양갱 (Bam Yang Gang)', '비비', match_key, 0, 0 FROM songs WHERE title = '밤양갱'").run();
|
||||
// plays: 쉬운노래 is always guessed fast → suggestion ★5 → ★4
|
||||
const easy = db.query<{ id: number }, []>("SELECT id FROM songs WHERE title = '쉬운노래'").get()!.id;
|
||||
for (let i = 0; i < 6; i++) db.query("INSERT INTO song_plays (song_id, game_id, played_at, players, winner_id, ms, how) VALUES (?, 'g', ?, 3, 'u', 2500, 'correct')").run(easy, Date.now());
|
||||
}
|
||||
|
||||
const browser: Browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
|
||||
const errors: string[] = [];
|
||||
const step = async (name: string, fn: () => Promise<void>) => {
|
||||
const t0 = performance.now();
|
||||
try {
|
||||
await fn();
|
||||
console.log(`✓ ${name} (${Math.round(performance.now() - t0)}ms)`);
|
||||
} catch (e) {
|
||||
console.log(`✗ ${name}: ${(e as Error).message.split('\n')[0]}`);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
const expect = (ok: unknown, msg: string) => {
|
||||
if (!ok) throw new Error(msg);
|
||||
};
|
||||
|
||||
async function fakeDiscord(ctx: BrowserContext, discordId: string) {
|
||||
await ctx.route(`${ORIGIN}/api/auth/discord/start*`, async (route) => {
|
||||
const res = await fetch(route.request().url(), { redirect: 'manual', headers: { cookie: (await route.request().headerValue('cookie')) ?? '' } });
|
||||
const consent = new URL(res.headers.get('location')!);
|
||||
const back = `${ORIGIN}/api/auth/discord/callback?code=${discordId}&state=${consent.searchParams.get('state')}`;
|
||||
await route.fulfill({ status: 200, headers: { 'content-type': 'text/html', 'set-cookie': res.headers.get('set-cookie') ?? '' }, body: `<script>location.replace(${JSON.stringify(back)})</script>` });
|
||||
});
|
||||
}
|
||||
|
||||
const toastSeen = (p: Page, text: string | RegExp) => p.locator('.toast', { hasText: text }).first().waitFor({ timeout: 5000 });
|
||||
const row = (p: Page, title: string) => p.locator('.data-table tbody tr', { hasText: title });
|
||||
|
||||
let failed = false;
|
||||
try {
|
||||
const ctx = await browser.newContext({ viewport: { width: 1500, height: 950 }, locale: 'ko-KR', acceptDownloads: true });
|
||||
await fakeDiscord(ctx, SUPER);
|
||||
const p = await ctx.newPage();
|
||||
p.on('pageerror', (e) => errors.push(e.message));
|
||||
await p.goto(ORIGIN + '/');
|
||||
await p.getByRole('link', { name: '디스코드로 로그인' }).click();
|
||||
await p.getByRole('button', { name: '내 계정: 사금향' }).waitFor();
|
||||
|
||||
await step('노래: 추가(제목·가수·유튜브) → 편집 패널, 초성 검색, 미리듣기 + "지금 위치를 하이라이트로" 버튼', async () => {
|
||||
await p.goto(ORIGIN + '/admin/songs');
|
||||
await p.getByRole('button', { name: '+ 노래 추가' }).click();
|
||||
const sheet = p.getByRole('dialog', { name: '노래 추가' });
|
||||
await sheet.getByLabel('제목').fill('새로 넣은 노래');
|
||||
await sheet.getByLabel('가수 (여러 명이면 쉼표로)').fill('관리자가수');
|
||||
await sheet.getByLabel(/유튜브 주소/).fill('https://youtu.be/abcdefghijk');
|
||||
await sheet.getByRole('button', { name: '추가', exact: true }).click();
|
||||
await toastSeen(p, '추가했어요');
|
||||
await p.getByRole('complementary', { name: '노래 편집' }).getByRole('button', { name: '⏱ 지금 위치를 하이라이트로' }).waitFor();
|
||||
expect(db.query("SELECT youtube_status s FROM songs WHERE title = '새로 넣은 노래'").get() as { s: string }, '추가 안 됨');
|
||||
await p.getByLabel('노래 검색').fill('ㅅㄱㅇㅈㅍㅅ');
|
||||
await p.getByRole('button', { name: '검색' }).click();
|
||||
await p.locator('form .muted.small', { hasText: /^1곡$/ }).waitFor();
|
||||
await row(p, '사건의 지평선').waitFor();
|
||||
});
|
||||
|
||||
await step('노래: 2곡 골라 일괄 숨기기 → 숨김 배지, 휴지통으로 → 휴지통에서 복원', async () => {
|
||||
await p.getByLabel('노래 검색').fill('');
|
||||
await p.getByRole('button', { name: '검색' }).click();
|
||||
await row(p, '좋은 날').getByRole('checkbox').check();
|
||||
await row(p, '밤양갱 (Bam').getByRole('checkbox').check();
|
||||
await p.getByRole('region', { name: '선택한 곡 일괄 작업' }).getByText('2곡 선택').waitFor();
|
||||
await p.getByRole('button', { name: '적용' }).click();
|
||||
await toastSeen(p, '2곡에 적용했어요');
|
||||
await row(p, '좋은 날').locator('.badge', { hasText: '숨김' }).waitFor();
|
||||
await row(p, '좋은 날').getByRole('checkbox').check();
|
||||
await p.getByLabel('일괄 작업', { exact: true }).selectOption('trash');
|
||||
await p.getByRole('button', { name: '적용' }).click();
|
||||
await p.getByRole('dialog').getByRole('button', { name: '적용' }).click();
|
||||
await row(p, '좋은 날').waitFor({ state: 'detached' });
|
||||
await p.getByRole('button', { name: '🗑 휴지통', exact: true }).click();
|
||||
await p.getByRole('heading', { name: '휴지통' }).waitFor();
|
||||
await row(p, '좋은 날').getByRole('button', { name: '복원' }).click();
|
||||
await toastSeen(p, '복원했어요');
|
||||
await p.getByRole('button', { name: '🗑 휴지통', exact: true }).click();
|
||||
await row(p, '좋은 날').waitFor();
|
||||
});
|
||||
|
||||
await step('노래: CSV 내보내기(현재 필터) → 가져오기(새 곡 추가·있는 곡 건너뜀)', async () => {
|
||||
const href = await p.getByRole('link', { name: 'CSV 내보내기' }).getAttribute('href');
|
||||
const csv = await (await p.request.get(ORIGIN + href)).text();
|
||||
expect(csv.includes('title,artist') && csv.includes('사건의 지평선'), 'CSV 내용이 이상함');
|
||||
const file = join(TMP, 'songs.csv');
|
||||
writeFileSync(file, csv.replace(/^/, '') + ',가져온 노래,가져온가수,2011,ballad,4,,,0\n');
|
||||
await p.getByLabel('가져올 파일').setInputFiles(file);
|
||||
await toastSeen(p, /새 곡 1곡, 이미 있던 곡 \d+곡/);
|
||||
await p.getByLabel('노래 검색').fill('가져온');
|
||||
await p.getByRole('button', { name: '검색' }).click();
|
||||
await row(p, '가져온 노래').waitFor();
|
||||
});
|
||||
|
||||
await step('노래: 중복 정리 — 밤양갱 2곡을 하나로 합치기', async () => {
|
||||
await p.getByRole('button', { name: '중복 정리' }).click();
|
||||
const sheet = p.getByRole('dialog', { name: '중복 정리' });
|
||||
await sheet.getByText('밤양갱 (Bam Yang Gang)').waitFor();
|
||||
await sheet.getByRole('button', { name: /로 합치기$/ }).first().click();
|
||||
await toastSeen(p, '합쳤어요');
|
||||
await sheet.getByText('중복된 곡이 없어요.').waitFor();
|
||||
await p.keyboard.press('Escape');
|
||||
expect(db.query<{ n: number }, []>("SELECT COUNT(*) n FROM songs WHERE title LIKE '밤양갱%' AND deleted_at IS NULL").get()!.n === 1, '합쳐지지 않음');
|
||||
});
|
||||
|
||||
await step('가수: 아이유에 별칭 IU·이지은 → 별칭으로도 검색됨', async () => {
|
||||
await p.getByRole('link', { name: '🎤 가수' }).click();
|
||||
await p.getByLabel('가수 검색').fill('아이유');
|
||||
await p.getByRole('button', { name: '검색' }).click();
|
||||
await p.getByRole('button', { name: '아이유 고치기' }).click();
|
||||
await p.getByLabel('별칭').fill('IU, 이지은');
|
||||
await p.getByRole('button', { name: '저장' }).click();
|
||||
await toastSeen(p, '저장했어요');
|
||||
await p.getByLabel('가수 검색').fill('이지은');
|
||||
await p.getByRole('button', { name: '검색' }).click();
|
||||
await row(p, 'IU, 이지은').waitFor();
|
||||
});
|
||||
|
||||
await step('장르: 시티팝 추가 → 방 설정에 보임, 숨기면 사라짐', async () => {
|
||||
await p.getByRole('link', { name: '🏷 장르' }).click();
|
||||
await p.getByLabel('새 장르 ID').fill('citypop');
|
||||
await p.getByLabel('새 장르 이름').fill('시티팝');
|
||||
await p.getByRole('button', { name: '장르 추가' }).click();
|
||||
await toastSeen(p, '추가했어요');
|
||||
let meta = await (await p.request.get(ORIGIN + '/api/catalog/meta')).json();
|
||||
expect(meta.genres.some((g: { name: string }) => g.name === '시티팝'), '방 설정에 새 장르가 없음');
|
||||
await p.getByLabel('시티팝 숨김').click();
|
||||
await p.getByLabel('시티팝 숨김').and(p.locator(':checked')).waitFor();
|
||||
await p.waitForTimeout(300);
|
||||
meta = await (await p.request.get(ORIGIN + '/api/catalog/meta')).json();
|
||||
expect(!meta.genres.some((g: { name: string }) => g.name === '시티팝'), '숨긴 장르가 보임');
|
||||
});
|
||||
|
||||
await step('통계: 쉬운노래(6번 모두 2.5초) → ★5 → ★4 제안 승인', async () => {
|
||||
await p.getByRole('link', { name: '📈 통계' }).click();
|
||||
await p.getByText('난이도 조정 제안').waitFor();
|
||||
await p.getByRole('button', { name: '★5 → ★4 승인' }).click();
|
||||
await toastSeen(p, '★4로 바꿨어요');
|
||||
expect(db.query<{ level: number }, []>("SELECT level FROM song_levels l JOIN songs s ON s.id = l.song_id WHERE s.title = '쉬운노래' AND scope = 'all'").get()!.level === 4, '난이도가 안 바뀜');
|
||||
});
|
||||
|
||||
await step('방: 손님의 비공개 방이 보이고, 강제 종료하면 손님은 첫 화면 + "관리자가 방을 닫았어요"', async () => {
|
||||
const gctx = await browser.newContext({ locale: 'ko-KR' });
|
||||
const g = await gctx.newPage();
|
||||
g.on('pageerror', (e) => errors.push(`guest: ${e.message}`));
|
||||
await g.goto(ORIGIN + '/');
|
||||
await g.getByLabel('게스트 닉네임 (2~12자)').fill('손님');
|
||||
await g.getByRole('button', { name: '게스트로 시작' }).click();
|
||||
await g.getByRole('button', { name: '내 계정: 손님' }).waitFor();
|
||||
const code = await g.evaluate(async () => (await (await fetch('/api/rooms', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ config: { visibility: 'private' } }) })).json()).code as string);
|
||||
await g.goto(`${ORIGIN}/r/${code}`);
|
||||
await g.locator('.pool-banner').waitFor();
|
||||
await p.getByRole('link', { name: '🚪 방' }).click();
|
||||
await row(p, code).waitFor();
|
||||
await row(p, code).getByRole('button', { name: '강제 종료' }).click();
|
||||
await p.getByRole('dialog').getByRole('button', { name: '강제 종료' }).click();
|
||||
await g.locator('.toast', { hasText: '관리자가 방을 닫았어요.' }).waitFor({ timeout: 5000 });
|
||||
await g.waitForURL(ORIGIN + '/');
|
||||
await gctx.close();
|
||||
});
|
||||
|
||||
await step('수집: 곡 수 넣고 실행 → 진행 중 + 멈추기 → 기록과 로그', async () => {
|
||||
await p.getByRole('link', { name: '📥 수집' }).click();
|
||||
await p.getByLabel('유튜브 원곡 찾기 곡 수').fill('120');
|
||||
await p.getByRole('button', { name: '실행' }).click();
|
||||
await toastSeen(p, '시작했어요');
|
||||
expect(runs.at(-1)?.limit === 120, `실행 요청 ${JSON.stringify(runs)}`);
|
||||
await p.getByRole('button', { name: '멈추기' }).click({ timeout: 8000 });
|
||||
await row(p, '멈춤').waitFor();
|
||||
await p.getByRole('button', { name: '실행' }).waitFor();
|
||||
expect(stops.length === 1, '멈추기 요청 없음');
|
||||
await p.getByRole('button', { name: '로그' }).first().click();
|
||||
await p.getByText('started from e2e').waitFor();
|
||||
});
|
||||
|
||||
await step('사이트: 새 방 기본 난이도 ★2 + 난이도 잠금 → 손님이 만든 방은 ★2, 방장도 못 바꿈', async () => {
|
||||
await p.getByRole('link', { name: '⚙️ 사이트' }).click();
|
||||
await p.getByRole('radio', { name: /^2단계/ }).click();
|
||||
await p.getByLabel('🔒 난이도').check();
|
||||
await p.getByRole('button', { name: '저장', exact: true }).click();
|
||||
await toastSeen(p, '저장했어요');
|
||||
await p.screenshot({ path: join(SHOTS, 'stage8-site.png'), fullPage: true });
|
||||
const gctx = await browser.newContext({ locale: 'ko-KR' });
|
||||
const g = await gctx.newPage();
|
||||
await g.goto(ORIGIN + '/');
|
||||
await g.getByLabel('게스트 닉네임 (2~12자)').fill('새방장');
|
||||
await g.getByRole('button', { name: '게스트로 시작' }).click();
|
||||
await g.getByRole('button', { name: '+ 방 만들기' }).click();
|
||||
await g.waitForURL(/\/r\/\d{6}$/);
|
||||
await g.locator('.pool-banner', { hasText: '★2' }).waitFor();
|
||||
await g.getByRole('radio', { name: /^5단계/ }).click();
|
||||
await g.locator('.toast', { hasText: '관리자가 고정한 설정' }).waitFor({ timeout: 5000 });
|
||||
await gctx.close();
|
||||
});
|
||||
|
||||
await p.goto(ORIGIN + '/admin/songs');
|
||||
await p.locator('.data-table tbody tr').first().waitFor();
|
||||
await p.screenshot({ path: join(SHOTS, 'stage8-songs.png'), fullPage: true });
|
||||
expect(errors.length === 0, `페이지 오류: ${errors.join(' | ')}`);
|
||||
} catch (e) {
|
||||
console.log(e instanceof Error ? e.message.slice(0, 400) : e);
|
||||
for (const pg of browser.contexts().flatMap((c) => c.pages())) await pg.screenshot({ path: join(SHOTS, `stage8-fail-${Math.random().toString(36).slice(2, 6)}.png`) }).catch(() => {});
|
||||
failed = true;
|
||||
} finally {
|
||||
await browser.close();
|
||||
await app.stop();
|
||||
}
|
||||
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -11,7 +11,7 @@
|
||||
"build": "bun run --filter '@mq/web' build",
|
||||
"typecheck": "tsc -p packages/shared && tsc -p apps/server && tsc -p apps/web",
|
||||
"test": "bun test --timeout 20000",
|
||||
"e2e": "bun run build && bun e2e/login.e2e.ts && bun e2e/rooms.e2e.ts && bun e2e/game.e2e.ts"
|
||||
"e2e": "bun run build && bun e2e/login.e2e.ts && bun e2e/rooms.e2e.ts && bun e2e/game.e2e.ts && bun e2e/admin.e2e.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "1.4.2",
|
||||
|
||||
@@ -142,7 +142,7 @@ export interface GameView {
|
||||
export type ServerMessage =
|
||||
| { t: 'welcome'; protocol: number; userId: string; serverNow: number }
|
||||
| { t: 'room'; room: RoomView }
|
||||
| { t: 'left'; code: string; reason: 'leave' | 'kicked' | 'closed' | 'elsewhere' }
|
||||
| { t: 'left'; code: string; reason: 'leave' | 'kicked' | 'closed' | 'elsewhere' | 'admin' }
|
||||
| { t: 'chat'; code: string; line: ChatLine }
|
||||
/** 정답 줄 + 5줄 블록 in one message (docs/06). */
|
||||
| { t: 'answer'; code: string; line: ChatLine }
|
||||
|
||||
Reference in New Issue
Block a user