/** * 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) => { 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: `` }); }); } 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 step('원곡 찾기: 진행률, 후보 바로 확정, 확정 취소 → 후보, 원곡 없음, 5초 자동 새로고침', async () => { const c = new Catalog(db); const now = Date.now(); const tried = (id: number, at: number) => db.query("INSERT OR REPLACE INTO signals (song_id, kind, value, fetched_at) VALUES (?, 'yt_tried_ytmusic', ?, ?)").run(id, at, at); const [guess] = c.upsert({ title: '후보곡', artists: [{ name: '후보가수' }], source: 'e2e', ref: 'g' }); db.query("UPDATE songs SET youtube_status = 'candidate', youtube_source = 'ytmusic', youtube_id = 'candvideo01', youtube_title = '후보곡 (Live)', youtube_channel = '후보가수', embeddable = 1, youtube_checked_at = ? WHERE id = ?").run(now, guess!); db.query("INSERT INTO youtube_candidates (song_id, video_id, title, channel, duration_sec, score, source) VALUES (?, 'candvideo01', '후보곡 (Live)', '후보가수', 200, 55, 'ytmusic')").run(guess!); tried(guess!, now); const [lost] = c.upsert({ title: '못찾은곡', artists: [{ name: '누구' }], source: 'e2e', ref: 'l' }); tried(lost!, now - 1000); const [auto] = c.upsert({ title: '자동확정곡', artists: [{ name: '자동가수' }], source: 'e2e', ref: 'a' }); db.query("UPDATE songs SET youtube_status = 'matched', youtube_source = 'ytmusic', youtube_id = 'autovideo01', youtube_title = '자동확정곡', youtube_channel = '자동가수 - Topic', embeddable = 1, youtube_checked_at = ? WHERE id = ?").run(now, auto!); tried(auto!, now); const hms = (t: number) => new Date(t).toISOString().slice(11, 19); const log = `${hms(now - 60_000)} start 10 songs via ytmusic\n${hms(now - 30_000)} search failed (timeout), waiting 60s\n`; db.query("INSERT INTO collect_jobs (kind, status, done, total, started_at, pid, log) VALUES ('match-youtube', 'running', 3, 10, ?, ?, ?)").run(now - 60_000, process.pid, log); await p.getByRole('link', { name: '🔎 원곡 찾기' }).click(); await p.getByRole('heading', { name: '원곡 찾기' }).waitFor(); const status = p.getByRole('region', { name: '진행 상황' }); await status.getByText('● 찾는 중').waitFor(); await status.getByText('3 / 10', { exact: true }).waitFor(); await status.getByText('7곡', { exact: true }).waitFor(); await status.getByText('검색: 유튜브 뮤직 (쿠키 사용)').waitFor(); await status.locator('.yt-stat', { hasText: '끝 예상' }).waitFor(); await status.locator('.yt-recent li', { hasText: '자동확정곡' }).getByText('확정', { exact: true }).waitFor(); await status.getByText('작업 기록 (최근 2줄)').click(); await status.getByText('⚠ 검색 실패 (timeout) → 60초 쉬고 다시 해요').waitFor(); await status.screenshot({ path: join(SHOTS, 'youtube-progress.png') }); // 후보 tab is first: one click confirms, and it moves to 확정 await row(p, '후보곡').getByRole('button', { name: '확정', exact: true }).click(); await toastSeen(p, "'후보곡' 확정했어요"); const st = (t: string) => db.query<{ youtube_status: string; youtube_source: string | null }, [string]>('SELECT youtube_status, youtube_source FROM songs WHERE title = ?').get(t)!; expect(st('후보곡').youtube_status === 'matched', '후보 확정 안 됨'); await p.getByRole('button', { name: /^확정 \d/ }).click(); await row(p, '자동확정곡').click(); await p.getByRole('complementary', { name: '원곡 확인' }).getByRole('button', { name: '확정 취소' }).click(); await toastSeen(p, '확정을 취소했어요'); expect(st('자동확정곡').youtube_status === 'candidate' && st('자동확정곡').youtube_source === 'admin', '확정 취소가 후보(관리자)로 안 바뀜'); await p.screenshot({ path: join(SHOTS, 'youtube-review-panel.png') }); await p.getByRole('button', { name: /^못 찾음 \d/ }).click(); await row(p, '못찾은곡').click(); await p.getByRole('button', { name: '원곡 없음으로 표시' }).click(); await toastSeen(p, '원곡 없음으로 표시했어요'); expect(st('못찾은곡').youtube_source === 'admin', '원곡 없음 표시 안 됨'); // the matcher finds a new song: it shows up by itself within 5 seconds (pointer away from the list) await p.mouse.move(5, 5); await p.getByRole('button', { name: /^못 찾음 \d/ }).click(); const [fresh] = c.upsert({ title: '방금찾은곡', artists: [{ name: '새가수' }], source: 'e2e', ref: 'f' }); tried(fresh!, Date.now()); await row(p, '방금찾은곡').waitFor({ timeout: 8000 }); await p.screenshot({ path: join(SHOTS, 'youtube-review.png'), fullPage: true }); const acts = db.query<{ action: string }, []>("SELECT action FROM admin_audit WHERE action LIKE 'song.%' ORDER BY id DESC LIMIT 3").all().map((r) => r.action); expect(acts.includes('song.youtube.unconfirm') && acts.includes('song.youtube.none'), `기록 없음: ${acts}`); db.query("UPDATE collect_jobs SET status = 'done', finished_at = ? WHERE kind = 'match-youtube' AND status = 'running'").run(Date.now()); }); 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);