연령제한 음원 받기: yt-dlp가 돌려준 쿠키를 받는 동안 파일이 바뀌었으면(서버가 갱신했거나 새 쿠키가 들어왔으면) 버림 — 무조건 합쳐서 새 세션 B의 PSIDTS·SIDCC를 이전 세션 A의 값으로 덮어쓰던 것. downloadWithCookie로 분리, 그대로·새 쿠키 교체·자동 갱신·실패 다운로드 회귀 테스트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-29 14:49:36 +09:00
parent e2a9e81c2c
commit c55702d440
3 changed files with 60 additions and 12 deletions

View File

@@ -41,6 +41,23 @@ export async function ytDlpAudio(videoId: string, out: string, cookieFile: strin
renameSync(tmp, out);
}
/**
* yt-dlp with the cookie file as it is now. yt-dlp writes its jar back when it exits: values YouTube changed on the way go
* into the file, so the session stays one — unless the file moved on during the download (the keeper rotated it, or the admin
* put in another cookie). Then the file's values are the newer ones and yt-dlp's are dropped.
*/
export async function downloadWithCookie(path: string, cookieFile: string, id: string, out: string, run = ytDlpAudio): Promise<void> {
const start = readFileSync(path, 'utf8');
const given = cookieForms(start).netscape;
writeFileSync(cookieFile, given, { mode: 0o600 });
try {
await run(id, out, cookieFile);
} finally {
const changes = existsSync(cookieFile) ? jarChanges(given, readFileSync(cookieFile, 'utf8')) : [];
if (changes.length && readFileSync(path, 'utf8') === start) writeCookieFile(path, mergeCookies(start, changes));
}
}
/** The cookie belongs to an account YouTube does not let watch age-restricted videos (expired, or not adult-verified). */
export class CookieProblem extends Error {}
@@ -119,17 +136,7 @@ export async function collectAgeAudio(db: Database, dir: string, opts: AgeAudioO
const cookieFile = join(tmp, 'cookies.txt');
// the file is read for every song: the server keeps rotating its values (cookie-keeper.ts)
fetchSignedIn ??= async (id) => fetchWatchPage(id, cookieForms(readFileSync(path, 'utf8')).header);
download ??= async (id, out) => {
const given = cookieForms(readFileSync(path, 'utf8')).netscape;
writeFileSync(cookieFile, given, { mode: 0o600 });
try {
await ytDlpAudio(id, out, cookieFile);
} finally {
// yt-dlp writes the jar back: values YouTube changed on the way go into the file, so the session stays one
const changes = existsSync(cookieFile) ? jarChanges(given, readFileSync(cookieFile, 'utf8')) : [];
if (changes.length) writeCookieFile(path, mergeCookies(readFileSync(path, 'utf8'), changes));
}
};
download ??= (id, out) => downloadWithCookie(path, cookieFile, id, out);
}
for (const s of todo) {
try {

View File

@@ -3,6 +3,7 @@ import { mkdtempSync, readFileSync, statSync, utimesSync, writeFileSync } from '
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { cookieForms, jarChanges, mergeCookies, parseSetCookies } from './cookie-jar';
import { downloadWithCookie } from './age-audio';
import { CookieKeeper } from './cookie-keeper';
import { CookieError, YtMusic } from './ytmusic';
@@ -160,3 +161,43 @@ describe('YtMusic reads the cookie file again when it changes', () => {
expect(sent[1]).toContain('__Secure-1PSIDTS=new1');
});
});
describe('연령제한 음원 받기: yt-dlp가 돌려준 쿠키', () => {
/** A fake yt-dlp that changes SIDCC in its jar, while `during` runs as if something else touched the cookie file. */
const ytDlp = (during: () => void) => async (_id: string, _out: string, jar: string) => {
writeFileSync(jar, readFileSync(jar, 'utf8').replace('\tSIDCC\tc0', '\tSIDCC\tytdlp'));
during();
};
const jarOf = () => join(mkdtempSync(join(tmpdir(), 'mq-jar-')), 'cookies.txt');
test('nothing else touched the file → the values yt-dlp got go in', async () => {
const path = tempFile(HEADER);
await downloadWithCookie(path, jarOf(), 'v1', '/dev/null', ytDlp(() => {}));
expect(readFileSync(path, 'utf8')).toBe(HEADER.replace('SIDCC=c0', 'SIDCC=ytdlp'));
});
test('a new cookie put in during the download stays as it is (no mix of the two sessions)', async () => {
const path = tempFile(HEADER);
const B = 'SID=b1; SAPISID=bsap; __Secure-1PSID=bp1; __Secure-1PSIDTS=b1ts; SIDCC=bc0\n';
await downloadWithCookie(path, jarOf(), 'v1', '/dev/null', ytDlp(() => writeFileSync(path, B)));
expect(readFileSync(path, 'utf8')).toBe(B);
});
test('the keeper rotating during the download wins: its newer values are not overwritten', async () => {
const path = tempFile(HEADER);
const rotated = mergeCookies(HEADER, parseSetCookies(ROTATED, NOW));
await downloadWithCookie(path, jarOf(), 'v1', '/dev/null', ytDlp(() => writeFileSync(path, rotated)));
expect(readFileSync(path, 'utf8')).toBe(rotated);
expect(rotated).toContain('SIDCC=c1');
});
test('a failed download still hands back what yt-dlp changed', async () => {
const path = tempFile(HEADER);
const fail = async (_id: string, _out: string, jar: string) => {
await ytDlp(() => {})(_id, _out, jar);
throw new Error('Requested format is not available');
};
await expect(downloadWithCookie(path, jarOf(), 'v1', '/dev/null', fail)).rejects.toThrow('Requested format');
expect(readFileSync(path, 'utf8')).toContain('SIDCC=ytdlp');
});
});