diff --git a/apps/server/src/collector/age-audio.ts b/apps/server/src/collector/age-audio.ts index d95fc12..435a1c6 100644 --- a/apps/server/src/collector/age-audio.ts +++ b/apps/server/src/collector/age-audio.ts @@ -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 { + 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 { diff --git a/apps/server/src/collector/cookie-keeper.test.ts b/apps/server/src/collector/cookie-keeper.test.ts index 96ca13d..7a3d27c 100644 --- a/apps/server/src/collector/cookie-keeper.test.ts +++ b/apps/server/src/collector/cookie-keeper.test.ts @@ -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'); + }); +}); diff --git a/docs/08-youtube-playback.md b/docs/08-youtube-playback.md index d921179..079fc57 100644 --- a/docs/08-youtube-playback.md +++ b/docs/08-youtube-playback.md @@ -39,7 +39,7 @@ - 원인: 구글 로그인 쿠키의 `__Secure-1PSIDTS`·`__Secure-3PSIDTS`·`*SIDCC`는 브라우저 탭이 10분마다 `accounts.youtube.com/RotateCookies`를 불러 새 값으로 바꾼다. 서버에 복사한 쿠키는 이 값을 못 받아 며칠 뒤 로그아웃됐다(10/19 쿠키 → 10/28 08:10 "로그인이 풀렸어요"). 쿠키를 뽑은 브라우저가 같은 세션을 계속 쓰면 더 빨리 끊긴다 - 서버(index.ts, `YT_COOKIE_PATH`가 있을 때)가 10분마다 같은 요청(`POST accounts.youtube.com/RotateCookies`, origin `https://www.youtube.com`, 본문 `[1,"-숫자"]`)을 보내고 응답 `Set-Cookie`의 youtube.com 값을 쿠키 파일에 그 형식 그대로(헤더/cookies.txt) 덮어쓴다. 그다음 유튜브 뮤직 노래 검색으로 로그인 상태인지 확인 - 갱신 401/403 또는 검색이 로그아웃 상태 → "로그인이 풀렸어요"(관리자 → 수집 맨 위). 새 쿠키를 넣을 때까지 갱신을 멈추고, 파일이 바뀌면 1분 안에 다시 확인. 네트워크 오류·429는 10분 뒤 재시도 -- 갱신은 서버 한 곳만(세션 하나에 갱신하는 쪽이 둘이면 서로의 값을 무효로 만든다). 수집기는 파일을 요청마다 새로 읽고(`YtMusic`은 파일이 바뀌면 다시 읽음, age-audio는 곡마다), yt-dlp가 돌려준 쿠키 중 값이 바뀐 것은 파일에 합친다 +- 갱신은 서버 한 곳만(세션 하나에 갱신하는 쪽이 둘이면 서로의 값을 무효로 만든다). 수집기는 파일을 요청마다 새로 읽고(`YtMusic`은 파일이 바뀌면 다시 읽음, age-audio는 곡마다), yt-dlp가 돌려준 쿠키 중 값이 바뀐 것은 파일에 합친다(받는 동안 파일이 바뀌었으면 — 서버가 갱신했거나 새 쿠키가 들어왔으면 — 파일 쪽이 더 새 값이라 yt-dlp 값은 버린다) - 잰 것(10/29, 이미 로그아웃된 쿠키): `accounts.youtube.com/RotateCookies` 200 + `SIDCC`만 새로 줌(PSIDTS 없음), 검색은 로그아웃 → 상태는 검색으로 판단해야 한다. 쿠키 없이 403, `accounts.google.com/RotateCookies`는 youtube 쿠키로 401 - 쿠키 받는 법: 크롬 시크릿 창에서 로그인 → music.youtube.com → 쿠키 내보내기 → 로그아웃하지 말고 창을 닫는다(브라우저가 그 세션을 다시 쓰지 않게). 비밀번호 변경·"모든 기기 로그아웃"·구글 보안 확인이 있으면 다시 끊긴다