diff --git a/apps/server/src/admin-catalog.test.ts b/apps/server/src/admin-catalog.test.ts index a52765b..054d50d 100644 --- a/apps/server/src/admin-catalog.test.ts +++ b/apps/server/src/admin-catalog.test.ts @@ -190,7 +190,7 @@ describe('admin artists, genres, stats, rooms, collect, room defaults', () => { 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 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('없는'); diff --git a/apps/server/src/collector/age-audio.test.ts b/apps/server/src/collector/age-audio.test.ts new file mode 100644 index 0000000..3f1e066 --- /dev/null +++ b/apps/server/src/collector/age-audio.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, test } from 'bun:test'; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { DEFAULT_ROOM_CONFIG } from '@mq/shared'; +import { openDb } from '../db'; +import { audioDir, audioFile } from '../songs/audio'; +import { countPool } from '../songs/pool'; +import { loudnessGain, quizSong } from '../songs/quiz'; +import { tempDbPath } from '../test-utils'; +import { cookieForms, collectAgeAudio } from './age-audio'; +import { Catalog } from './catalog'; +import { Blocked } from './charts'; +import { collectLoudness, isAgeGated } from './loudness'; + +const fx = (f: string) => Bun.file(join(import.meta.dir, 'fixtures', f)).text(); +const gate = '"playabilityStatus":{"status":"LOGIN_REQUIRED","reason":"성인 인증하려면 로그인하세요"}'; +const ok = (lufs: number) => `"playabilityStatus":{"status":"OK"},"audioConfig":{"trackAbsoluteLoudnessLkfs":${lufs},"loudnessTargetLkfs":-14}`; + +function setup(n: number) { + const path = tempDbPath(); + const db = openDb(path); + const c = new Catalog(db); + const ids = Array.from({ length: n }, (_, i) => c.upsert({ title: `t${i}`, artists: [{ name: 'x' }], source: 't', ref: `r${i}` })[0]!); + for (const id of ids) c.autoLevel(id, 'all', 3); + db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = 'v' || id, duration_sec = 200").run(); + return { db, ids, dir: audioDir(path) }; +} +const cfg = { ...DEFAULT_ROOM_CONFIG, level: 3 as const }; + +describe('연령제한 곡', () => { + test('tells an age gate from a playable or Premium-only page (real anonymous page of an age-restricted video)', async () => { + expect(isAgeGated(await fx('youtube-age-gate.txt'))).toBe(true); + expect(isAgeGated(ok(-10))).toBe(false); + expect(isAgeGated('"playabilityStatus":{"status":"UNPLAYABLE","reason":"Music Premium 회원만 시청할 수 있는 동영상입니다."}')).toBe(false); + expect(isAgeGated('"playabilityStatus":{"status":"LOGIN_REQUIRED","reason":"Sign in to confirm your age"}')).toBe(true); + }); + + test('cookie file as a header or as cookies.txt → both forms', () => { + const h = cookieForms('SID=a; SAPISID=b=c\n'); + expect(h.header).toBe('SID=a; SAPISID=b=c'); + expect(h.netscape).toContain('.youtube.com\tTRUE\t/\tTRUE\t'); + expect(h.netscape).toContain('\tSAPISID\tb=c'); + const n = cookieForms('# Netscape HTTP Cookie File\n.youtube.com\tTRUE\t/\tTRUE\t0\tSID\ta\n.google.com\tTRUE\t/\tTRUE\t0\tNID\tz\n'); + expect(n.header).toBe('SID=a'); + expect(n.netscape).toContain('NID'); + }); + + test('the loudness job finds them; the game leaves them out until the audio is downloaded, then plays the file', async () => { + const { db, ids, dir } = setup(3); + const [a, b] = ids as [number, number, number]; + await collectLoudness(db, { delayMs: 0, fetchPage: async (id) => (id === `v${a}` ? gate : ok(-12)) }); + expect(quizSong(db, a)).toMatchObject({ ageRestricted: true, audio: false, loudness: null }); + expect(quizSong(db, b)).toMatchObject({ ageRestricted: false, audio: false, loudness: -12 }); + expect(countPool(db, cfg)).toEqual({ playable: 2, total: 3 }); + + const asked: string[] = []; + const r = await collectAgeAudio(db, dir, { + delayMs: 0, + fetchPage: async () => gate, + fetchSignedIn: async (id) => (asked.push(id), ok(-8)), + download: async (id, out) => writeFileSync(out, `audio of ${id}`), + }); + expect(r).toEqual({ back: 0, downloaded: 1, failed: 0, removed: 0 }); + expect(asked).toEqual([`v${a}`]); + expect(readFileSync(audioFile(dir, `v${a}`), 'utf8')).toBe(`audio of v${a}`); + // loudness from the signed-in page; our file gets no YouTube turn-down + expect(quizSong(db, a)).toMatchObject({ ageRestricted: true, audio: true, loudness: -8 }); + expect(loudnessGain(-8, true)).toBeCloseTo(10 ** (-10 / 20), 3); + expect(loudnessGain(-8, true)).toBeLessThan(loudnessGain(-8)); + expect(loudnessGain(null, true)).toBe(loudnessGain(-9, true)); + expect(countPool(db, cfg)).toEqual({ playable: 3, total: 3 }); + + // the admin picks another video: the old file is no longer used and goes away + db.query("UPDATE songs SET youtube_id = 'other' WHERE id = ?").run(a); + db.query('UPDATE songs SET audio_video = NULL WHERE id = ?').run(a); + expect(quizSong(db, a)).toMatchObject({ ageRestricted: false, audio: false }); + expect((await collectAgeAudio(db, dir, { delayMs: 0, fetchPage: async () => gate })).removed).toBe(1); + expect(existsSync(audioFile(dir, `v${a}`))).toBe(false); + }); + + test('a song a player could not play (150) comes back when it is age-restricted; others stay 재생 불가', async () => { + const { db, ids, dir } = setup(2); + const [a, b] = ids as [number, number]; + db.query("UPDATE songs SET youtube_status = 'dead', note = '[재생 오류 150]'").run(); + // a broken old file of song a is replaced + mkdirSync(dir, { recursive: true }); + writeFileSync(audioFile(dir, `v${a}`), 'broken'); + db.query('UPDATE songs SET audio_video = youtube_id, age_video = youtube_id WHERE id = ?').run(a); + const r = await collectAgeAudio(db, dir, { + delayMs: 0, + fetchPage: async (id) => (id === `v${a}` ? gate : '"playabilityStatus":{"status":"ERROR","reason":"동영상을 재생할 수 없음"}'), + fetchSignedIn: async () => ok(-9), + download: async (id, out) => writeFileSync(out, 'fresh'), + }); + expect(r).toMatchObject({ back: 1, downloaded: 1 }); + expect(db.query<{ youtube_status: string; note: string | null }, [number]>('SELECT youtube_status, note FROM songs WHERE id = ?').get(a)).toEqual({ youtube_status: 'matched', note: null }); + expect(readFileSync(audioFile(dir, `v${a}`), 'utf8')).toBe('fresh'); + expect(db.query<{ youtube_status: string }, [number]>('SELECT youtube_status FROM songs WHERE id = ?').get(b)!.youtube_status).toBe('dead'); + // checked once a month, not every run + let calls = 0; + await collectAgeAudio(db, dir, { delayMs: 0, fetchPage: async () => (calls++, gate) }); + expect(calls).toBe(0); + }); + + test('stops when the cookie account cannot watch them, or at a block signal; a failed download waits a day', async () => { + const { db, ids, dir } = setup(2); + db.query('UPDATE songs SET age_video = youtube_id').run(); + let downloads = 0; + const cookieGone = await collectAgeAudio(db, dir, { delayMs: 0, fetchSignedIn: async () => gate, download: async () => void downloads++ }); + expect(cookieGone.downloaded).toBe(0); + expect(downloads).toBe(0); + expect(db.query<{ status: string; log: string }, []>("SELECT status, log FROM collect_jobs WHERE kind = 'age-audio' ORDER BY id DESC").get()).toMatchObject({ status: 'failed', log: expect.stringContaining('성인 인증') }); + + await collectAgeAudio(db, dir, { delayMs: 0, fetchSignedIn: async () => ok(-9), download: async () => (downloads++, Promise.reject(new Blocked('HTTP Error 429'))) }); + expect(downloads).toBe(1); + + const r = await collectAgeAudio(db, dir, { delayMs: 0, fetchSignedIn: async () => ok(-9), download: async () => Promise.reject(new Error('Requested format is not available')) }); + expect(r).toMatchObject({ downloaded: 0, failed: 2 }); + expect((await collectAgeAudio(db, dir, { delayMs: 0, fetchSignedIn: async () => ok(-9), download: async (_, out) => writeFileSync(out, 'x') })).downloaded).toBe(0); + expect(ids.every((id) => !quizSong(db, id)!.audio)).toBe(true); + expect(existsSync(dirname(audioFile(dir, 'x')))).toBe(true); + }); +}); diff --git a/apps/server/src/collector/age-audio.ts b/apps/server/src/collector/age-audio.ts new file mode 100644 index 0000000..c0ea840 --- /dev/null +++ b/apps/server/src/collector/age-audio.ts @@ -0,0 +1,182 @@ +/** + * 연령제한 곡 (docs/08 §2-1): YouTube refuses age-restricted videos in every embedded player (error 150), even for adults who + * are signed in. The server downloads their audio once with the adult-verified account's cookie and the game plays that + * file (songs/audio.ts). One song at a time, a few seconds apart, stops at the first block signal: + * 1. songs a player could not play (재생 오류): still age-restricted? → back in the game once the audio is here + * 2. age-restricted songs without audio: the signed-in watch page (loudness and 하이라이트 — the anonymous page has neither), + * then yt-dlp downloads the audio-only m4a (3~5MB) → AUDIO_DIR/