Files
music_quiz/apps/server/src/admin-catalog.test.ts

224 lines
15 KiB
TypeScript

/** 관리자 완성 (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, Melon id 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('UPDATE songs SET melon_id = 711627 WHERE id = ?').run(b);
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', melon_id: 711627 });
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
expect(suggestLevel(5, 10, 9, 3000, 5)).toBeNull(); // guessed fast, but only with hints: not easier
expect(suggestLevel(5, 10, 5, 9000, 7)).toBe(6); // half guessed with hints most of the time: harder
const lv = (await call('/level-reviews')).body.rows;
expect(lv.find((r: any) => r.id === hard).evidence[1]).toContain('정답 나온 문제 1번');
await call(`/level-reviews/${hard}/dismiss`, { method: 'POST' });
expect((await call('/level-reviews')).body.rows.find((r: any) => r.id === hard)).toBeUndefined();
});
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, () => {}, s.config.dbPath, [{ 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();
});
});