연령제한 곡 재생: 유튜브가 퍼가기 플레이어에서 막는(오류 150) 연령제한 영상은 서버가 성인 인증된 계정 쿠키로 소리만 받아 두고(/data/audio, yt-dlp) 게임은 그 파일을 숨긴 <audio>로 재생. 찾기는 소리 크기·하이라이트 수집(로그인 없는 페이지의 성인 인증 화면) + 게임 중 오류 시 age-audio 작업이 다시 확인해 되돌림. 받기 전에는 출제 안 함. prepare·catchup에 videoId 대신 문제마다 새 무작위 주소(/api/audio/<토큰>, Range 지원)라 영상 id가 안 보임. 같은 시각 시작·위치 정지·새로고침 이어 듣기·소리 크기(유튜브 -14 보정 없이) 그대로. 관리자 수집 화면·cli age-audio, Dockerfile에 yt-dlp(버전·체크섬 고정), 수집 CLI가 서버 DB 경로를 물려받게(테스트가 기본 DB를 건드리던 것). 실제 크롬 e2e로 받은 음원+유튜브 곡 섞어 재생 확인
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
123
apps/server/src/collector/age-audio.test.ts
Normal file
123
apps/server/src/collector/age-audio.test.ts
Normal file
@@ -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);
|
||||
});
|
||||
});
|
||||
182
apps/server/src/collector/age-audio.ts
Normal file
182
apps/server/src/collector/age-audio.ts
Normal file
@@ -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/<video>.m4a
|
||||
* 3. files no song uses any more are deleted
|
||||
* Age-restricted songs are found by the loudness / heatmap jobs (their anonymous page) and by step 1.
|
||||
*/
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { audioFile } from '../songs/audio';
|
||||
import { Catalog, Job, sleep } from './catalog';
|
||||
import { Blocked } from './charts';
|
||||
import { parseHeatmap, pickHighlight } from './heatmap';
|
||||
import { fetchWatchPage, isAgeGated, parseLoudness, saveLoudness } from './loudness';
|
||||
|
||||
/** The cookie file holds either a request header (`a=1; b=2`) or a Netscape cookies.txt; returns both forms. */
|
||||
export function cookieForms(raw: string): { header: string; netscape: string } {
|
||||
const text = raw.trim();
|
||||
if (text.includes('\t')) {
|
||||
const rows = text
|
||||
.split(/\r?\n/)
|
||||
.filter((l) => l && (!l.startsWith('#') || l.startsWith('#HttpOnly_')))
|
||||
.map((l) => l.split('\t'))
|
||||
.filter((p) => p.length >= 7 && /youtube\.com$/.test(p[0]!));
|
||||
return { header: rows.map((p) => `${p[5]}=${p[6]!.trim()}`).join('; '), netscape: `${text}\n` };
|
||||
}
|
||||
const exp = Math.floor(Date.now() / 1000) + 365 * 86400;
|
||||
const pairs = text
|
||||
.split(/;\s*/)
|
||||
.map((p) => [p.slice(0, p.indexOf('=')).trim(), p.slice(p.indexOf('=') + 1).trim()] as const)
|
||||
.filter(([k]) => k);
|
||||
const lines = pairs.map(([k, v]) => ['.youtube.com', 'TRUE', '/', 'TRUE', exp, k, v].join('\t'));
|
||||
return { header: pairs.map(([k, v]) => `${k}=${v}`).join('; '), netscape: ['# Netscape HTTP Cookie File', ...lines, ''].join('\n') };
|
||||
}
|
||||
|
||||
/** yt-dlp: the best m4a audio-only stream of the video into `out` (no ffmpeg in the image: browsers play the DASH m4a as is). */
|
||||
export async function ytDlpAudio(videoId: string, out: string, cookieFile: string, bin = process.env.YTDLP_BIN ?? 'yt-dlp'): Promise<void> {
|
||||
const tmp = `${out}.tmp`;
|
||||
rmSync(tmp, { force: true });
|
||||
const proc = Bun.spawn(
|
||||
[bin, '--cookies', cookieFile, '--js-runtimes', 'bun', '-f', 'bestaudio[ext=m4a]', '--fixup', 'never', '--no-playlist', '--no-progress', '--no-part', '--max-filesize', '40M', '-q', '--no-warnings', '-o', tmp, '--', videoId],
|
||||
{ stdin: 'ignore', stdout: 'ignore', stderr: 'pipe' },
|
||||
);
|
||||
const timer = setTimeout(() => proc.kill(), 180_000);
|
||||
const [code, err] = await Promise.all([proc.exited, new Response(proc.stderr).text()]);
|
||||
clearTimeout(timer);
|
||||
if (code !== 0 || !existsSync(tmp)) {
|
||||
rmSync(tmp, { force: true });
|
||||
const msg = err.trim().split('\n').pop() || `yt-dlp exit ${code}`;
|
||||
if (/not a bot|HTTP Error 429|Too Many Requests/i.test(err)) throw new Blocked(msg);
|
||||
throw new Error(msg);
|
||||
}
|
||||
renameSync(tmp, out);
|
||||
}
|
||||
|
||||
/** The cookie belongs to an account YouTube does not let watch age-restricted videos (expired, or not adult-verified). */
|
||||
export class CookieProblem extends Error {}
|
||||
|
||||
export interface AgeAudioOptions {
|
||||
limit?: number;
|
||||
delayMs?: number;
|
||||
cookiePath?: string;
|
||||
/** Tests inject these; by default the anonymous / signed-in watch page and yt-dlp. */
|
||||
fetchPage?: (id: string) => Promise<string>;
|
||||
fetchSignedIn?: (id: string) => Promise<string>;
|
||||
download?: (id: string, out: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export async function collectAgeAudio(db: Database, dir: string, opts: AgeAudioOptions = {}) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const now = Date.now();
|
||||
const recheck = db
|
||||
.query<{ id: number; youtube_id: string }, [number]>(
|
||||
`SELECT s.id, s.youtube_id FROM songs s WHERE s.deleted_at IS NULL AND s.youtube_status = 'dead' AND s.youtube_id IS NOT NULL
|
||||
AND s.note LIKE '%[재생 오류 %'
|
||||
AND NOT EXISTS (SELECT 1 FROM signals g WHERE g.song_id = s.id AND g.kind = 'yt_age_checked' AND g.value > ?)
|
||||
ORDER BY s.id`,
|
||||
)
|
||||
.all(now - 30 * 86400_000);
|
||||
const pending = () =>
|
||||
db
|
||||
.query<{ id: number; youtube_id: string; highlight_source: string | null }, [number, number]>(
|
||||
`SELECT s.id, s.youtube_id, s.highlight_source FROM songs s
|
||||
LEFT JOIN song_levels l ON l.song_id = s.id AND l.scope = 'all'
|
||||
WHERE s.deleted_at IS NULL AND s.youtube_status = 'matched' AND s.youtube_id IS NOT NULL
|
||||
AND s.age_video = s.youtube_id AND COALESCE(s.audio_video, '') <> s.youtube_id
|
||||
AND NOT EXISTS (SELECT 1 FROM signals g WHERE g.song_id = s.id AND g.kind = 'yt_audio_tried' AND g.value > ?)
|
||||
ORDER BY l.level IS NULL, l.level, s.id LIMIT ?`,
|
||||
)
|
||||
.all(Date.now() - 86400_000, opts.limit ?? 100);
|
||||
const fetchPage = opts.fetchPage ?? fetchWatchPage;
|
||||
const job = new Job(db, 'age-audio', recheck.length);
|
||||
const cat = new Catalog(db);
|
||||
const stats = { back: 0, downloaded: 0, failed: 0, removed: 0 };
|
||||
let tmp: string | null = null;
|
||||
let done = 0;
|
||||
try {
|
||||
// 1. a player could not play it: still age-restricted → back to 'matched' (left out until the audio is here)
|
||||
for (const s of recheck) {
|
||||
try {
|
||||
if (isAgeGated(await fetchPage(s.youtube_id))) {
|
||||
// the audio file may have been what failed (404 / broken): download it again
|
||||
rmSync(audioFile(dir, s.youtube_id), { force: true });
|
||||
const r = db
|
||||
.query(
|
||||
`UPDATE songs SET youtube_status = 'matched', age_video = youtube_id, audio_video = NULL, updated_at = ?,
|
||||
note = NULLIF(trim(replace(replace(replace(note, '[재생 오류 150]', ''), '[재생 오류 101]', ''), '[재생 오류 100]', '')), '')
|
||||
WHERE id = ? AND youtube_status = 'dead' AND youtube_id = ?`,
|
||||
)
|
||||
.run(Date.now(), s.id, s.youtube_id);
|
||||
if (r.changes) (stats.back++, job.log(`${s.youtube_id} age-restricted: back in the game once downloaded`));
|
||||
} else cat.signal(s.id, 'yt_age_checked', Date.now());
|
||||
} catch (e) {
|
||||
stats.failed++;
|
||||
if (e instanceof Blocked) throw e;
|
||||
job.log(`${s.youtube_id} check failed: ${(e as Error).message}`);
|
||||
}
|
||||
job.progress(++done);
|
||||
await sleep(opts.delayMs ?? 3000);
|
||||
}
|
||||
|
||||
// 2. download with the adult-verified account
|
||||
const todo = pending();
|
||||
job.progress(done, recheck.length + todo.length);
|
||||
let fetchSignedIn = opts.fetchSignedIn;
|
||||
let download = opts.download;
|
||||
if (todo.length && (!fetchSignedIn || !download)) {
|
||||
const path = opts.cookiePath ?? process.env.YT_COOKIE_PATH ?? '/home/claude/.config/music_quiz/ytm_cookie.txt';
|
||||
if (!existsSync(path)) throw new CookieProblem(`쿠키 파일이 없어요: ${path}`);
|
||||
const c = cookieForms(await Bun.file(path).text());
|
||||
tmp = mkdtempSync(join(tmpdir(), 'mq-cookie-'));
|
||||
const cookieFile = join(tmp, 'cookies.txt');
|
||||
writeFileSync(cookieFile, c.netscape, { mode: 0o600 });
|
||||
fetchSignedIn ??= (id) => fetchWatchPage(id, c.header);
|
||||
download ??= (id, out) => ytDlpAudio(id, out, cookieFile);
|
||||
}
|
||||
for (const s of todo) {
|
||||
try {
|
||||
const page = await fetchSignedIn!(s.youtube_id);
|
||||
if (isAgeGated(page)) throw new CookieProblem('쿠키 계정으로도 성인 인증 페이지가 나와요(쿠키가 만료됐거나 성인 인증이 안 된 계정)');
|
||||
// the anonymous page of an age-restricted video has no loudness / heatmap: take them from this one
|
||||
saveLoudness(db, s.id, s.youtube_id, parseLoudness(page));
|
||||
const sec = s.highlight_source === 'admin' || s.highlight_source === 'heatmap' ? null : pickHighlight(parseHeatmap(page));
|
||||
if (sec !== null)
|
||||
db.query("UPDATE songs SET highlight_sec = ?, highlight_source = 'heatmap', updated_at = ? WHERE id = ? AND COALESCE(highlight_source, '') <> 'admin'").run(sec, Date.now(), s.id);
|
||||
await download!(s.youtube_id, audioFile(dir, s.youtube_id));
|
||||
db.query('UPDATE songs SET audio_video = ?, updated_at = ? WHERE id = ? AND youtube_id = ?').run(s.youtube_id, Date.now(), s.id, s.youtube_id);
|
||||
stats.downloaded++;
|
||||
job.log(`${s.youtube_id} downloaded`);
|
||||
} catch (e) {
|
||||
if (e instanceof Blocked || e instanceof CookieProblem) throw e;
|
||||
stats.failed++;
|
||||
cat.signal(s.id, 'yt_audio_tried', Date.now());
|
||||
job.log(`${s.youtube_id} download failed: ${(e as Error).message}`);
|
||||
}
|
||||
job.progress(++done);
|
||||
await sleep(opts.delayMs ?? 3000);
|
||||
}
|
||||
|
||||
// 3. files of videos no song plays any more (the admin changed the video, the song was purged)
|
||||
const used = new Set(db.query<{ v: string }, []>('SELECT audio_video v FROM songs WHERE audio_video IS NOT NULL').all().map((r) => r.v));
|
||||
for (const f of readdirSync(dir)) {
|
||||
if (used.has(f.replace(/\.m4a$/, '')) && f.endsWith('.m4a')) continue;
|
||||
rmSync(join(dir, f), { force: true });
|
||||
stats.removed++;
|
||||
}
|
||||
job.log(`age-audio done: back ${stats.back}, downloaded ${stats.downloaded}, failed ${stats.failed}, removed ${stats.removed}`);
|
||||
job.finish('done');
|
||||
} catch (e) {
|
||||
job.log(`stopped: ${(e as Error).message}`);
|
||||
job.finish('failed');
|
||||
if (!(e instanceof Blocked || e instanceof CookieProblem)) throw e;
|
||||
} finally {
|
||||
if (tmp) rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
* bun apps/server/src/collector/cli.ts melon-detail [--limit N]
|
||||
* bun apps/server/src/collector/cli.ts heatmap [--limit N]
|
||||
* bun apps/server/src/collector/cli.ts loudness [--limit N] [--delay ms] [--deadline epochMs] (소리 크기: YouTube's LUFS per matched video, most popular level first)
|
||||
* bun apps/server/src/collector/cli.ts age-audio [--limit N] [--delay ms] (연령제한 곡: download their audio with the adult-verified cookie, docs/08 §2-1)
|
||||
* bun apps/server/src/collector/cli.ts levels
|
||||
* bun apps/server/src/collector/cli.ts fix-text (one-off: decode `'`/`&` saved in titles, let 원곡 찾기 retry them)
|
||||
* bun apps/server/src/collector/cli.ts stats
|
||||
@@ -24,6 +25,8 @@ import { collectCharts, fillMelonDetails } from './charts';
|
||||
import { collectHeatmaps } from './heatmap';
|
||||
import { collectLoudness } from './loudness';
|
||||
import { computeLevels } from './levels';
|
||||
import { collectAgeAudio } from './age-audio';
|
||||
import { audioDir } from '../songs/audio';
|
||||
import { fixEntities } from './text';
|
||||
|
||||
const [cmd, ...rest] = process.argv.slice(2);
|
||||
@@ -69,6 +72,9 @@ switch (cmd) {
|
||||
case 'loudness':
|
||||
console.log(await collectLoudness(db, { limit: flag('limit'), delayMs: flag('delay'), deadline: flag('deadline') }));
|
||||
break;
|
||||
case 'age-audio':
|
||||
console.log(await collectAgeAudio(db, audioDir(dbPath), { limit: flag('limit'), delayMs: flag('delay') }));
|
||||
break;
|
||||
case 'levels':
|
||||
console.log(computeLevels(db));
|
||||
break;
|
||||
@@ -79,7 +85,7 @@ switch (cmd) {
|
||||
console.log(JSON.stringify(catalogStats(db), null, 1));
|
||||
break;
|
||||
default:
|
||||
console.log('usage: cli.ts import-norabose|import-sta|match-youtube|charts|melon-detail|heatmap|loudness|levels|fix-text|stats');
|
||||
console.log('usage: cli.ts import-norabose|import-sta|match-youtube|charts|melon-detail|heatmap|loudness|age-audio|levels|fix-text|stats');
|
||||
process.exitCode = 1;
|
||||
}
|
||||
db.close();
|
||||
|
||||
@@ -13,6 +13,7 @@ export const COLLECT_KINDS: CollectControl['kinds'] = [
|
||||
{ id: 'melon-detail', label: '멜론 곡 정보 채우기 (발매일·장르·가사)', limit: true },
|
||||
{ id: 'heatmap', label: '하이라이트 찾기 (유튜브 많이 다시 본 구간)', limit: true },
|
||||
{ id: 'loudness', label: '소리 크기 재기 (유튜브가 잰 곡별 크기)', limit: true },
|
||||
{ id: 'age-audio', label: '연령제한 곡 음원 받기 (성인 인증 계정 쿠키)', limit: true },
|
||||
{ id: 'levels', label: '난이도 다시 계산' },
|
||||
];
|
||||
|
||||
@@ -27,7 +28,8 @@ function alive(pid: number): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
export function collectorControl(db: Database, log: LogFn, kinds = COLLECT_KINDS, args: (kind: string, limit?: number) => string[] = defaultArgs): CollectControl {
|
||||
/** `dbPath`: the server's DB, so the CLI never falls back to its default path (tests and e2e configure the DB in code). */
|
||||
export function collectorControl(db: Database, log: LogFn, dbPath: string, 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 {
|
||||
@@ -37,7 +39,7 @@ export function collectorControl(db: Database, log: LogFn, kinds = COLLECT_KINDS
|
||||
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 });
|
||||
const proc = Bun.spawn([process.execPath, CLI, ...args(kind, k.limit ? limit : undefined)], { stdout: 'ignore', stderr: 'ignore', stdin: 'ignore', env: { ...process.env, DB_PATH: dbPath } });
|
||||
proc.unref();
|
||||
log('info', 'collector started', { kind, limit, pid: proc.pid });
|
||||
return null;
|
||||
|
||||
2
apps/server/src/collector/fixtures/youtube-age-gate.txt
Normal file
2
apps/server/src/collector/fixtures/youtube-age-gate.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
var ytInitialPlayerResponse = {"responseContext"
|
||||
"playabilityStatus":{"status":"LOGIN_REQUIRED","reason":"성인 인증하려면 로그인하세요","errorScreen":{"playerInterstitialRenderer":{"content":{"interstitialViewModel":{"title":{"content":"성인 인증하려면 로그인하세요"},"description":{"content":"이 동영상은 일부 사용자에게는 부적절할 수 있습니다."},"primaryButton":{"buttonViewModel":{"onTap":{"innertubeCommand":{"clickTrackingParams":"CAUQtOoKIhMI6uzUxcnGlwMVFLUpAx0Sewg8ygEED2O7CQ==","commandMetadata":{"webCommandMetadata":{"url":"https://accounts.google.com/ServiceLogin?service=youtube\u0026uilel=3\u0026passive=true\u0026continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Faction_handle_signin%3Dtrue%26app%3Ddesktop%26hl%3Dko%26next%3D%252Fwatch%253Fv%253D6kLq3WMV1nU%2526hl%253Dko\u0026hl=ko","webPageType":"WEB_PAGE_TYPE_UNKNOWN","rootVe":83769}},"signInEndpoint":{"nextEndpoint":{"clickTrackingParams":"CAUQtOoKIhMI6uzUxcnGlwMVFLUpAx0Sewg8ygEED2O7CQ==","commandMetadata":{"webCommandMetadata":{"url":"/watch?v=6kLq3WMV1nU\u0026hl=ko","webPageType":"WEB_PAGE_TYPE_UNKNOWN","rootVe":83769}},"urlEndpoint":{"url":"/watch?v=6kLq3WMV1nU\u0026hl=ko"}}}}},"style":"BUTTON_VIEW_MODEL_STYLE_OVERLAY","trackingParams":"CAUQtOoKIhMI6uzUxcnGlwMVFLUpAx0Sewg8","isFullWidth":false,"type":"BUTTON_VIEW_MODEL_TYPE_FILLED","buttonSize":"BUTTON_VIEW_MODEL_SIZE_LARGE","accessibilityId":"id.interstitial_sign_in_button","titleFormatted":{"content":"로그인"},"useYoutubeLoggingDirectives":true,"shouldLogGestures":true,"loggingDirectives":{"trackingParams":"CAU
|
||||
@@ -6,7 +6,7 @@
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { Catalog, Job, sleep } from './catalog';
|
||||
import { Blocked } from './charts';
|
||||
import { fetchWatchPage, parseLoudness, saveLoudness } from './loudness';
|
||||
import { fetchWatchPage, isAgeGated, markAgeGated, parseLoudness, saveLoudness } from './loudness';
|
||||
|
||||
export interface Marker {
|
||||
startMs: number;
|
||||
@@ -59,6 +59,7 @@ export async function collectHeatmaps(db: Database, opts: { limit?: number; dela
|
||||
for (const [i, s] of rows.entries()) {
|
||||
try {
|
||||
const page = await fetchPage(s.youtube_id);
|
||||
if (isAgeGated(page)) markAgeGated(db, s.id, s.youtube_id);
|
||||
// same page: keep its loudness too, so the loudness job can skip this song
|
||||
saveLoudness(db, s.id, s.youtube_id, parseLoudness(page));
|
||||
const sec = pickHighlight(parseHeatmap(page));
|
||||
|
||||
@@ -38,7 +38,7 @@ describe('소리 크기 맞추기', () => {
|
||||
const asked: string[] = [];
|
||||
const lufs: Record<string, number> = { [`v${a}`]: -9, [`v${b}`]: -20 };
|
||||
const r = await collectLoudness(db, { delayMs: 0, fetchPage: async (id) => (asked.push(id), id in lufs ? page(lufs[id]!) : 'no config') });
|
||||
expect(r).toEqual({ set: 2, none: 1, failed: 0 });
|
||||
expect(r).toEqual({ set: 2, none: 1, age: 0, failed: 0 });
|
||||
expect(asked[0]).toBe(`v${b}`);
|
||||
expect(quizSong(db, a!)!.loudness).toBe(-9);
|
||||
expect(quizSong(db, b!)!.loudness).toBe(-20);
|
||||
@@ -48,7 +48,7 @@ describe('소리 크기 맞추기', () => {
|
||||
// the admin picks another video: the old number no longer applies, and the song is measured again
|
||||
db.query("UPDATE songs SET youtube_id = 'new' WHERE id = ?").run(a!);
|
||||
expect(quizSong(db, a!)!.loudness).toBeNull();
|
||||
expect(await collectLoudness(db, { delayMs: 0, fetchPage: async () => page(-12) })).toEqual({ set: 1, none: 0, failed: 0 });
|
||||
expect(await collectLoudness(db, { delayMs: 0, fetchPage: async () => page(-12) })).toEqual({ set: 1, none: 0, age: 0, failed: 0 });
|
||||
expect(quizSong(db, a!)!.loudness).toBe(-12);
|
||||
});
|
||||
|
||||
@@ -58,7 +58,7 @@ describe('소리 크기 맞추기', () => {
|
||||
const [a] = ['a', 'b'].map((t) => c.upsert({ title: t, artists: [{ name: 'x' }], source: 't', ref: t })[0]!);
|
||||
db.query("UPDATE songs SET youtube_status = 'matched', youtube_id = 'v' || id").run();
|
||||
let calls = 0;
|
||||
expect(await collectLoudness(db, { delayMs: 0, fetchPage: async () => (calls++, Promise.reject(new Blocked('youtube 429'))) })).toEqual({ set: 0, none: 0, failed: 1 });
|
||||
expect(await collectLoudness(db, { delayMs: 0, fetchPage: async () => (calls++, Promise.reject(new Blocked('youtube 429'))) })).toEqual({ set: 0, none: 0, age: 0, failed: 1 });
|
||||
expect(calls).toBe(1);
|
||||
await collectHeatmaps(db, { delayMs: 0, fetchPage: async () => page(-15) });
|
||||
expect(quizSong(db, a!)!.loudness).toBe(-15);
|
||||
|
||||
@@ -8,15 +8,31 @@ import type { Database } from 'bun:sqlite';
|
||||
import { Catalog, Job, sleep } from './catalog';
|
||||
import { BROWSER_UA, Blocked } from './charts';
|
||||
|
||||
/** The watch page (heatmap markers, audioConfig loudness); throws Blocked on a block signal. */
|
||||
export async function fetchWatchPage(id: string): Promise<string> {
|
||||
const res = await fetch(`https://www.youtube.com/watch?v=${id}&hl=ko`, { headers: { 'user-agent': BROWSER_UA, 'accept-language': 'ko-KR,ko;q=0.9' }, signal: AbortSignal.timeout(20_000) });
|
||||
/** The watch page (heatmap markers, audioConfig loudness); throws Blocked on a block signal. `cookie`: signed in (연령제한 곡). */
|
||||
export async function fetchWatchPage(id: string, cookie?: string): Promise<string> {
|
||||
const headers: Record<string, string> = { 'user-agent': BROWSER_UA, 'accept-language': 'ko-KR,ko;q=0.9', ...(cookie ? { cookie } : {}) };
|
||||
const res = await fetch(`https://www.youtube.com/watch?v=${id}&hl=ko`, { headers, signal: AbortSignal.timeout(20_000) });
|
||||
if (res.status === 429 || res.status === 403) throw new Blocked(`youtube ${res.status}`);
|
||||
const text = await res.text();
|
||||
if (/consent\.youtube\.com|google\.com\/sorry/.test(res.url) || (/g-recaptcha|unusual traffic/i.test(text) && text.length < 200_000)) throw new Blocked('youtube bot check');
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 연령제한: the anonymous watch page asks to sign in to confirm age. YouTube then refuses the video in every embedded player
|
||||
* (error 150), so the game plays downloaded audio instead (collector/age-audio.ts).
|
||||
*/
|
||||
export function isAgeGated(html: string): boolean {
|
||||
const m = /"playabilityStatus":\{"status":"([A-Z_]+)"(?:,"reason":"([^"]*)")?/.exec(html);
|
||||
if (!m) return false;
|
||||
return m[1]!.startsWith('AGE_') || (m[1] === 'LOGIN_REQUIRED' && /성인|연령|age/i.test(m[2] ?? ''));
|
||||
}
|
||||
|
||||
/** Remember that the song's current video is age-restricted (the game leaves it out until its audio is downloaded). */
|
||||
export function markAgeGated(db: Database, songId: number, videoId: string): boolean {
|
||||
return db.query("UPDATE songs SET age_video = ? WHERE id = ? AND youtube_id = ? AND COALESCE(age_video, '') <> ?").run(videoId, songId, videoId, videoId).changes === 1;
|
||||
}
|
||||
|
||||
/** Integrated loudness (LUFS) of the video from the watch page, or null when the page has none. */
|
||||
export function parseLoudness(html: string): number | null {
|
||||
const cfg = /"audioConfig":\{([^}]*)/.exec(html)?.[1];
|
||||
@@ -52,7 +68,7 @@ export async function collectLoudness(
|
||||
const fetchPage = opts.fetchPage ?? fetchWatchPage;
|
||||
const job = new Job(db, 'loudness', rows.length);
|
||||
const cat = new Catalog(db);
|
||||
const stats = { set: 0, none: 0, failed: 0 };
|
||||
const stats = { set: 0, none: 0, age: 0, failed: 0 };
|
||||
job.log(`start ${rows.length} songs${opts.deadline !== undefined ? ` deadline ${new Date(opts.deadline).toISOString()}` : ''}`);
|
||||
try {
|
||||
for (const [i, s] of rows.entries()) {
|
||||
@@ -61,7 +77,9 @@ export async function collectLoudness(
|
||||
break;
|
||||
}
|
||||
try {
|
||||
if (saveLoudness(db, s.id, s.youtube_id, parseLoudness(await fetchPage(s.youtube_id)))) stats.set++;
|
||||
const page = await fetchPage(s.youtube_id);
|
||||
if (isAgeGated(page) && markAgeGated(db, s.id, s.youtube_id)) stats.age++;
|
||||
if (saveLoudness(db, s.id, s.youtube_id, parseLoudness(page))) stats.set++;
|
||||
else (stats.none++, cat.signal(s.id, 'yt_loudness_tried', Date.now()));
|
||||
} catch (e) {
|
||||
stats.failed++;
|
||||
@@ -75,7 +93,7 @@ export async function collectLoudness(
|
||||
if ((i + 1) % 100 === 0) job.log(`loudness ${i + 1}/${rows.length}: set ${stats.set}, no data ${stats.none}`);
|
||||
await sleep(opts.delayMs ?? 3000);
|
||||
}
|
||||
job.log(`loudness done: set ${stats.set}, no data ${stats.none}, failed ${stats.failed}`);
|
||||
job.log(`loudness done: set ${stats.set}, no data ${stats.none}, age-restricted ${stats.age}, failed ${stats.failed}`);
|
||||
job.finish('done');
|
||||
} catch (e) {
|
||||
job.log(`stopped: ${(e as Error).message}`);
|
||||
|
||||
Reference in New Issue
Block a user