ott-player / server.js
dongsik22's picture
Claude Opus 4.8 (1M context)
fix(tvchak): ํ†ต๊ณผ ํƒญ ํ† ํฐ ๋งŒ๋ฃŒ ์‹œ ์ž๋™ ์žฌํ†ต๊ณผ โ€” "all paths failed" ๋‹ค์Œํ™” ์žฌ์ƒ ๋ถˆ๊ฐ€ ํ•ด์†Œ
c3f1743
Raw History Blame Contribute Delete
196 kB
// ๋กœ์ปฌ ๋ฐฑ์—”๋“œ (Playwright ํ—ค๋“œ๋ฆฌ์Šค๋กœ tvchak Cloudflare ๋ด‡์ฐจ๋‹จ ์šฐํšŒ) // GET / -> index.html // GET /api/domain -> ํ˜„์žฌ ๊ณต์‹ ๋„๋ฉ”์ธ // GET /api/episodes?id=ID -> ์‹œ๋ฆฌ์ฆˆ ํšŒ์ฐจ ๋ชฉ๋ก + ์ œ๋ชฉ // GET /api/play?id&sid&nid -> { url, url_next, link_next, link_pre, vod_data } // GET /api/search?wd=... -> ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ์นด๋“œ ๋ชฉ๋ก // GET /api/flush -> ์บ์‹œ ๋น„์šฐ๊ธฐ // GET /api/cdn?u=ENCODED -> mp4 CDN ํ”„๋ก์‹œ (Referer ํ—ค๋” ์ž๋™ ์ถ”๊ฐ€) // // ์‹คํ–‰: node server.js (ํฌํŠธ 8787) const http = require('http'); const https = require('https'); const fs = require('fs'); const path = require('path'); const url = require('url'); const { chromium } = require('playwright'); const PORT = process.env.PORT || 8787; const ROOT = __dirname; // ์บ์‹œ/๋ฐ์ดํ„ฐ ๋””๋ ‰ํ† ๋ฆฌ. HF Spaces ๊ฐ™์€ read-only FS ํ™˜๊ฒฝ ๋Œ€์‘์„ ์œ„ํ•ด ํ™˜๊ฒฝ๋ณ€์ˆ˜๋กœ override ๊ฐ€๋Šฅ. // CACHE_DIR=/tmp/.cache DATA_DIR=/tmp/.data const CACHE_DIR = process.env.CACHE_DIR || path.join(ROOT, '.cache'); // ๋ถ€ํŒ… ์‹œ ๋นˆ๊ฐ’ ์บ์‹œ๋œ namu ํฌ์Šคํ„ฐ ํŒŒ์ผ ์ •๋ฆฌ โ€” ์ฝ”๋“œ ๊ฐœ์„ ์œผ๋กœ ์ด์ œ ์ฐพ์„ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ ๋Œ€๋น„ try { if (fs.existsSync(CACHE_DIR)) { for (const f of fs.readdirSync(CACHE_DIR)) { if (!f.startsWith('namu_poster_')) continue; try { const j = JSON.parse(fs.readFileSync(path.join(CACHE_DIR, f), 'utf-8')); if (!j || !j.poster) fs.unlinkSync(path.join(CACHE_DIR, f)); } catch { try { fs.unlinkSync(path.join(CACHE_DIR, f)); } catch {} } } } } catch (e) { console.warn('[namu] cleanup empty cache failed:', e.message); } if (!fs.existsSync(CACHE_DIR)) fs.mkdirSync(CACHE_DIR, { recursive: true }); const DATA_DIR = process.env.DATA_DIR || path.join(ROOT, '.data'); if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true }); const LEGACY_FAVS_FILE = path.join(DATA_DIR, 'favs.json'); function profileFile(profile) { const p = Math.max(1, Math.min(5, parseInt(profile, 10) || 1)); return path.join(DATA_DIR, `favs_p${p}.json`); } function readFavs(profile) { // ๋งˆ์ด๊ทธ๋ ˆ์ด์…˜: profile=1์ด๊ณ  ๊ทธ์ชฝ ํŒŒ์ผ ์—†์œผ๋ฉด legacy favs.json์„ ์‚ฌ์šฉ const fp = profileFile(profile); if (!fs.existsSync(fp)) { if ((parseInt(profile, 10) || 1) === 1 && fs.existsSync(LEGACY_FAVS_FILE)) { try { const legacy = JSON.parse(fs.readFileSync(LEGACY_FAVS_FILE, 'utf-8')); fs.writeFileSync(fp, JSON.stringify(legacy, null, 2)); return legacy; } catch {} } return { favs: [], lastFavId: null, updatedAt: 0 }; } try { return JSON.parse(fs.readFileSync(fp, 'utf-8')); } catch { return { favs: [], lastFavId: null, updatedAt: 0 }; } } const { spawn, spawnSync } = require('child_process'); // NAS ๋™๊ธฐํ™” ์ž๋™ ํ™œ์„ฑ โ€” ํ•„์š”ํ•œ env๊ฐ€ ๋ชจ๋‘ ์žˆ์œผ๋ฉด ON const NAS_SYNC_ENABLED = !!( process.env.NAS_SSH_HOST && process.env.NAS_SSH_USER && fs.existsSync(`${process.env.KEY_DIR || '/tmp/ssh-key-dir'}/nas-key`) ); if (NAS_SYNC_ENABLED) console.log(`[nas-favs] sync enabled (host=${process.env.NAS_SSH_HOST})`); function writeFavs(profile, obj) { obj.updatedAt = Date.now(); fs.writeFileSync(profileFile(profile), JSON.stringify(obj, null, 2)); if (NAS_SYNC_ENABLED) schedulePushToNas(profile); return obj; } // latest-labels ๋ฐฑ๊ทธ๋ผ์šด๋“œ fetchEpisodes ์ค‘๋ณต ํ˜ธ์ถœ ๋ฐฉ์ง€. // ๊ฐ™์€ id+source๊ฐ€ in-flight๋ฉด ์ƒˆ ํ˜ธ์ถœ skip โ€” ํด๋ผ์ด์–ธํŠธ๊ฐ€ pending ๋ณด๊ณ  ์žฌํ˜ธ์ถœํ•˜๊ฑฐ๋‚˜ // ์—ฌ๋Ÿฌ ๋””๋ฐ”์ด์Šค/ํƒญ์ด ๋™์‹œ ํด๋งํ•ด๋„ ๊ฐ™์€ ep๋กœ ํ๊ฐ€ ๊ณฑ์…ˆ ํญ์ฃผํ•˜์ง€ ์•Š๊ฒŒ. const _latestLabelsInFlight = new Set(); // NAS ์ƒํƒœ โ€” ๋‹ค์šด ์‹œ ๋กœ์ปฌ ์บ์‹œ๋งŒ์œผ๋กœ ๋™์ž‘. ํšŒ๋ณต ์‹œ ๋ˆ„๋ฝ push ์ผ๊ด„ ์žฌ์‹œ๋„. const _failedPush = new Set(); // ๋งˆ์ง€๋ง‰ push๊ฐ€ ์‹คํŒจํ•œ ํ”„๋กœํ•„ ๋ฒˆํ˜ธ๋“ค let _nasReachable = null; // true=์ •์ƒ, false=๋‹ค์šด, null=๋ฏธํ™•์ธ. ์ƒํƒœ ์ „ํ™˜ ์‹œ์—๋งŒ ๋กœ๊ทธ function markNasStatus(reachable) { if (_nasReachable === reachable) return; _nasReachable = reachable; if (reachable) { console.log(`[nas-favs] ONLINE${_failedPush.size ? ` โ€” flushing ${_failedPush.size} pending push(es)` : ''}`); // ํšŒ๋ณต ์‹œ ๋ˆ„๋ฝ push ์ผ๊ด„ ์žฌ์‹œ๋„ if (_failedPush.size) { const ps = [..._failedPush]; _failedPush.clear(); for (const p of ps) doPushToNas(p); } } else { console.warn('[nas-favs] OFFLINE โ€” using local cache only (changes will sync when NAS recovers)'); } } function sshCommonArgs(keyPath) { const args = [ '-i', keyPath, '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'ConnectTimeout=5', // ์งง๊ฒŒ โ€” NAS ๋‹ค์šด์ด๋ฉด ๋นจ๋ฆฌ ํฌ๊ธฐ '-o', 'BatchMode=yes', ]; if (process.env.SSH_CONTROL_PATH) { args.push('-o', `ControlPath=${process.env.SSH_CONTROL_PATH}`); } args.push('-p', process.env.NAS_SSH_PORT || '22', `${process.env.NAS_SSH_USER}@${process.env.NAS_SSH_HOST}`); return args; } // ์‹œ์ž‘ ์‹œ NAS์—์„œ favs ๋น„๋™๊ธฐ pull โ€” ์„œ๋ฒ„ ์‹œ์ž‘์ด NAS ์‘๋‹ต์— ๋ฌถ์ด์ง€ ์•Š๊ฒŒ. // ์‹คํŒจํ•ด๋„ ๋กœ์ปฌ ํŒŒ์ผ์ด ๊ทธ๋Œ€๋กœ ๋‚จ์•„์žˆ์–ด ์•ˆ์ „ (writeFileSync๋Š” pull ์„ฑ๊ณต์‹œ์—๋งŒ). async function pullFavsFromNas() { if (!NAS_SYNC_ENABLED) return; const keyPath = `${process.env.KEY_DIR || '/tmp/ssh-key-dir'}/nas-key`; if (!fs.existsSync(keyPath)) { console.warn(`[nas-favs] key missing: ${keyPath}`); return; } const commonArgs = sshCommonArgs(keyPath); let anySuccess = false; for (let p = 1; p <= 5; p++) { const remote = `~/tvchak-favs/favs_p${p}.json`; const result = await new Promise(resolve => { const proc = spawn('ssh', [...commonArgs, `test -f ${remote} && cat ${remote}`], { stdio: ['ignore', 'pipe', 'pipe'] }); const chunks = []; proc.stdout.on('data', d => chunks.push(d)); let timedOut = false; const timer = setTimeout(() => { timedOut = true; try { proc.kill('SIGKILL'); } catch {} }, 8000); proc.on('close', code => { clearTimeout(timer); resolve({ code, stdout: Buffer.concat(chunks), timedOut }); }); proc.on('error', () => { clearTimeout(timer); resolve({ code: -1, stdout: Buffer.alloc(0), timedOut: false }); }); }); if (result.code === 0 && result.stdout.length > 10) { try { const remoteObj = JSON.parse(result.stdout.toString('utf-8')); // ์œ ํšจ์„ฑ ๊ฒ€์ฆ // nickname ๋ณด์กด ๊ฐ€๋“œ โ€” NAS ๊ฐ’์ด ๋น„์—ˆ๋Š”๋ฐ ๋กœ์ปฌ์— ๊ฐ’์ด ์žˆ์œผ๋ฉด ๋กœ์ปฌ ์œ ์ง€. // Why: NAS์˜ ๋นˆ nickname์ด ๋กœ์ปฌ 'DS'๋ฅผ ๋ฐ˜๋ณต์ ์œผ๋กœ ๋‚ ๋ฆฌ๋˜ ์‚ฌ๊ณ (2026-05-25). // ๋‹ค๋ฅธ ๋””๋ฐ”์ด์Šค๊ฐ€ ์˜›๋‚  ๋นˆ ๋‹‰ ์ƒํƒœ๋กœ pushํ–ˆ๊ฑฐ๋‚˜ NAS ํŒŒ์ผ์ด ์†์ƒ๋œ ๊ฒฝ์šฐ ๋ฐฉ์–ด. let finalBuf = result.stdout; try { const localObj = JSON.parse(fs.readFileSync(profileFile(p), 'utf-8')); const remoteNick = (typeof remoteObj.nickname === 'string') ? remoteObj.nickname.trim() : ''; const localNick = (typeof localObj.nickname === 'string') ? localObj.nickname.trim() : ''; if (!remoteNick && localNick) { remoteObj.nickname = localObj.nickname; finalBuf = Buffer.from(JSON.stringify(remoteObj, null, 2)); console.log(`[nas-favs] p${p} nickname preserved from local ("${localNick}") โ€” NAS had empty`); } } catch {} // ๋กœ์ปฌ ํŒŒ์ผ ์—†๊ฑฐ๋‚˜ ์†์ƒ โ€” NAS ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉ fs.writeFileSync(profileFile(p), finalBuf); console.log(`[nas-favs] pulled p${p} (${finalBuf.length} bytes)`); anySuccess = true; } catch (e) { console.warn(`[nas-favs] pull p${p} parse failed:`, e.message); } } else if (result.code === 0) { // ํŒŒ์ผ์ด NAS์— ์—†์Œ โ€” ์—ฐ๊ฒฐ์€ OK anySuccess = true; } } markNasStatus(anySuccess); } // NAS ํ—ฌ์Šค์ฒดํฌ โ€” 30์ดˆ ์ฃผ๊ธฐ. ๋‹ค์šด โ†’ ํšŒ๋ณต ์ „ํ™˜ ๊ฐ์ง€ ์œ„ํ•ด. async function pingNas() { if (!NAS_SYNC_ENABLED) return; const keyPath = `${process.env.KEY_DIR || '/tmp/ssh-key-dir'}/nas-key`; if (!fs.existsSync(keyPath)) return; const ok = await new Promise(resolve => { const proc = spawn('ssh', [...sshCommonArgs(keyPath), 'echo ok'], { stdio: ['ignore', 'pipe', 'pipe'] }); const timer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch {} }, 8000); proc.on('close', code => { clearTimeout(timer); resolve(code === 0); }); proc.on('error', () => { clearTimeout(timer); resolve(false); }); }); markNasStatus(ok); } // schedulePushToNas: ๋‘ ๊ฐ€์ง€ ๋ณดํ˜ธ์žฅ์น˜ // (1) ๋””๋ฐ”์šด์Šค 2์ดˆ โ€” ์—ฐ์†๋œ saveFavs ๋ฌถ๊ธฐ // (2) ์ตœ์†Œ ๊ฐ„๊ฒฉ 15์ดˆ โ€” ์žฌ์ƒ ์ค‘ timeupdate(5์ดˆ๋งˆ๋‹ค)์ฒ˜๋Ÿผ ๋„์—„๋„์—„ ๋“ค์–ด์˜ค๋Š” ํ˜ธ์ถœ throttle. // ๋งˆ์ง€๋ง‰ ํ‘ธ์‹œ ์„ฑ๊ณต ํ›„ 15์ดˆ ์ด๋‚ด ํ˜ธ์ถœ์ด๋ฉด ๋‚จ์€ ์‹œ๊ฐ„๋งŒํผ ์ง€์—ฐ. const _pushTimers = new Map(); const _lastPushAt = new Map(); // profile โ†’ ๋งˆ์ง€๋ง‰ doPushToNas ์ง„์ž… ์‹œ๊ฐ const MIN_PUSH_INTERVAL_MS = 15 * 1000; function schedulePushToNas(profile) { const key = `p${profile}`; if (_pushTimers.has(key)) clearTimeout(_pushTimers.get(key)); const sinceLast = Date.now() - (_lastPushAt.get(profile) || 0); const minDelay = Math.max(2000, MIN_PUSH_INTERVAL_MS - sinceLast); _pushTimers.set(key, setTimeout(() => { _pushTimers.delete(key); doPushToNas(profile); }, minDelay)); } // ์ง์ „์— ์„ฑ๊ณต์ ์œผ๋กœ ํ‘ธ์‹œํ•œ ํŒŒ์ผ์˜ ํ•ด์‹œ. ๋™์ผ ๋‚ด์šฉ ๋ฐ˜๋ณต ํ‘ธ์‹œ ์ฐจ๋‹จ์šฉ. // Why: ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์žฌ์ƒ ์ค‘ progress/latest-label ๋“ฑ์œผ๋กœ saveFavs๋ฅผ ์ž์ฃผ ๋ถ€๋ฅด๋Š”๋ฐ // ์‹ค์ œ ์ง๋ ฌํ™” ๊ฒฐ๊ณผ๊ฐ€ ๋™์ผํ•˜๋ฉด NAS์— ๋‹ค์‹œ ์“ธ ์ด์œ ๊ฐ€ ์—†์Œ. ๋ฌด์˜๋ฏธํ•œ ssh ํญ์ฃผ๋กœ // autossh tunnel์ด ๋ถ€ํ•˜๋ฐ›๊ณ  SOCKS5 stall์ด ์ƒ๊ฒจ zombie watchdog๊นŒ์ง€ ํŠธ๋ฆฌ๊ฑฐ๋˜๋˜ ๋ฌธ์ œ. // updatedAt์€ ๋งค๋ฒˆ ๊ฐฑ์‹ ๋˜๋ฏ€๋กœ ํ•ด์‹œ์—์„œ ์ œ์™ธํ•ด์•ผ ๋””๋“€ํ”„๊ฐ€ ๋™์ž‘ํ•จ. const _lastPushedHash = new Map(); function _hashFavsContent(buf) { try { const obj = JSON.parse(buf.toString('utf-8')); const { updatedAt, ...rest } = obj || {}; return require('crypto').createHash('sha1').update(JSON.stringify(rest)).digest('hex'); } catch { return require('crypto').createHash('sha1').update(buf).digest('hex'); } } function doPushToNas(profile) { const fp = profileFile(profile); if (!fs.existsSync(fp)) { console.warn(`[nas-favs] file missing: ${fp}`); return; } const remote = `~/tvchak-favs/favs_p${profile}.json`; const keyPath = `${process.env.KEY_DIR || '/tmp/ssh-key-dir'}/nas-key`; if (!fs.existsSync(keyPath)) { console.warn(`[nas-favs] key missing: ${keyPath}`); return; } // NAS๊ฐ€ ๋‹ค์šด ์ƒํƒœ๋กœ ํ™•์ธ๋œ ์ƒํ™ฉ์ด๋ฉด ์ฆ‰์‹œ ์‹คํŒจ ํ์— ๋„ฃ๊ณ  ssh ์‹œ๋„ ์•ˆ ํ•จ (๋ถˆํ•„์š”ํ•œ connect timeout ๋ฐฉ์ง€) if (_nasReachable === false) { _failedPush.add(profile); return; } const data = fs.readFileSync(fp); const hash = _hashFavsContent(data); // ๋””๋“€ํ”„: ์ง์ „ ํ‘ธ์‹œ ์„ฑ๊ณตํ•œ ๋‚ด์šฉ๊ณผ ๋™์ผํ•˜๋ฉด skip. // updatedAt ํ•„๋“œ ๋•Œ๋ฌธ์— ์˜๋ฏธ ์—†๋Š” timestamp diff๊ฐ€ ์ƒ๊ธธ ์ˆ˜ ์žˆ๋Š”๋ฐ, ์ด ๊ฒฝ์šฐ ssh๋Š” ์•ˆ ๊ฐ€์ง€๋งŒ // ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์˜๋„์ ์œผ๋กœ ๋ณด๋‚ธ PUT์€ writeFavs๋กœ ๋””์Šคํฌ์—” ๋ฐ˜์˜๋จ(updatedAt๋งŒ ๊ฐฑ์‹ ). ๋‹ค์Œ ์˜๋ฏธ์žˆ๋Š” // ๋ณ€๊ฒฝ ๋•Œ ํ•œ ๋ฒˆ์— ๋™๊ธฐํ™”๋จ. if (_lastPushedHash.get(profile) === hash) { return; } _lastPushAt.set(profile, Date.now()); const args = [...sshCommonArgs(keyPath), `cat > ${remote}`]; console.log(`[nas-favs] pushing p${profile} via ssh -p ${process.env.NAS_SSH_PORT || '22'}...`); const proc = spawn('ssh', args, { stdio: ['pipe', 'pipe', 'pipe'] }); proc.stdin.end(data); let errOut = ''; proc.stderr.on('data', d => errOut += d.toString()); proc.on('close', code => { if (code === 0) { console.log(`[nas-favs] push p${profile} OK (${data.length} bytes)`); _lastPushedHash.set(profile, hash); _failedPush.delete(profile); markNasStatus(true); } else { console.warn(`[nas-favs] push p${profile} FAIL exit=${code}: ${errOut.slice(0, 300)}`); _failedPush.add(profile); // exit 255 = connection failure โ†’ NAS ๋‹ค์šด์œผ๋กœ ์ถ”์ •. ๊ถŒํ•œยท์„œ๋ฒ„ ๊ฑฐ๋ถ€ ๋“ฑ ๋‹ค๋ฅธ ์—๋Ÿฌ๋Š” NAS๋Š” ์‚ด์•„์žˆ์„ ์ˆ˜ ์žˆ์–ด ์ƒํƒœ ์ „ํ™˜ ์•ˆ ํ•จ. if (code === 255) markNasStatus(false); } }); proc.on('error', e => { console.warn(`[nas-favs] spawn err:`, e.message); _failedPush.add(profile); }); } // โ”€โ”€โ”€โ”€โ”€ ์บ์‹œ ํ—ฌํผ โ”€โ”€โ”€โ”€โ”€ function readCache(name, maxAgeSec) { const p = path.join(CACHE_DIR, name); if (!fs.existsSync(p)) return null; const age = (Date.now() - fs.statSync(p).mtimeMs) / 1000; if (age > maxAgeSec) return null; try { return JSON.parse(fs.readFileSync(p, 'utf-8')); } catch { return null; } } function writeCache(name, obj) { fs.writeFileSync(path.join(CACHE_DIR, name), JSON.stringify(obj)); } // ์บ์‹œ ํŒŒ์ผ์ด ์กด์žฌํ•˜๋ฉด ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜ (์˜๊ตฌ ์บ์‹œ). ํ•œ ๋ฒˆ ๊ฐ€์ ธ์˜ค๋ฉด ๋. function readCachePermanent(name) { const p = path.join(CACHE_DIR, name); if (!fs.existsSync(p)) return null; try { return JSON.parse(fs.readFileSync(p, 'utf-8')); } catch { return null; } } // ์บ์‹œ์˜ checked_at(ISO)์„ ๊ฐ™์€ ๋‹จ์œ„ ๊ฒฝ๊ณ„์™€ ๋น„๊ตํ•ด์„œ ๊ฐ™์œผ๋ฉด ์žฌ์‚ฌ์šฉ, ๋‹ค๋ฅด๋ฉด ๋งŒ๋ฃŒ. // unit: 'day' | 'week' | 'month' // - day: YYYY-MM-DD ๋™์ผํ•˜๋ฉด ์žฌ์‚ฌ์šฉ // - week: ๊ฐ™์€ ISO ์ฃผ(์›”~์ผ) ์•ˆ์ด๋ฉด ์žฌ์‚ฌ์šฉ // - month: YYYY-MM ๋™์ผํ•˜๋ฉด ์žฌ์‚ฌ์šฉ function readCacheSameBucket(name, unit) { const cached = readCachePermanent(name); if (!cached || !cached.checked_at) return null; const then = new Date(cached.checked_at); if (isNaN(then.getTime())) return null; const now = new Date(); if (unit === 'day') { if (sameDay(then, now)) return cached; return null; } if (unit === 'month') { if (then.getFullYear() === now.getFullYear() && then.getMonth() === now.getMonth()) return cached; return null; } if (unit === 'week') { if (sameWeekMonToSun(then, now)) return cached; return null; } return null; } function sameDay(a, b) { return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate(); } // ์›”์š”์ผ์„ ์ฃผ์˜ ์‹œ์ž‘์œผ๋กœ ๋ณด๊ณ , ๊ฐ™์€ ์ฃผ(์›”~์ผ)๋ฉด true. function sameWeekMonToSun(a, b) { return mondayOf(a).getTime() === mondayOf(b).getTime(); } function mondayOf(d) { const x = new Date(d.getFullYear(), d.getMonth(), d.getDate()); const day = x.getDay(); // 0=Sun..6=Sat const diff = (day === 0 ? -6 : 1 - day); // Sun -> -6, Mon -> 0, ..., Sat -> -5 x.setDate(x.getDate() + diff); return x; } // โ”€โ”€โ”€โ”€โ”€ ๋ธŒ๋ผ์šฐ์ € ํ’€ (์žฌํ™œ์šฉ) โ”€โ”€โ”€โ”€โ”€ let _browser = null; let _context = null; // tvchak ์ „์šฉ โ€” SOCKS5 ์šฐํšŒ ์—†์ด ์ง์ ‘ ํ˜ธ์ถœ. KT์˜ SNI ์ฐจ๋‹จ์ด tvchak204.com์„ ๋ง‰์•„ NAS ๊ฒฝ์œ ๋Š” TLS reset. // HF datacenter IP๋กœ ์ง์ ‘ ๊ฐ€๋ฉด Cloudflare ์ฑŒ๋ฆฐ์ง€๊ฐ€ ๋œจ์ง€๋งŒ Chromium์€ ํ†ต๊ณผ ๊ฐ€๋Šฅ. let _tvBrowser = null; let _tvContext = null; // SOCKS5_PROXY ํ™˜๊ฒฝ๋ณ€์ˆ˜ ์žˆ์œผ๋ฉด ๋ชจ๋“  Playwright ํŠธ๋ž˜ํ”ฝ์ด ๊ทธ์ชฝ์œผ๋กœ. (NAS residential IP ์šฐํšŒ์šฉ) const PROXY_SERVER = process.env.SOCKS5_PROXY || null; if (PROXY_SERVER) console.log(`[proxy] all Playwright traffic via ${PROXY_SERVER} (tvchak ์ „์šฉ ์ปจํ…์ŠคํŠธ๋Š” ์šฐํšŒ ์•ˆ ํ•จ)`); const COMMON_CHROMIUM_ARGS = [ '--disable-blink-features=AutomationControlled', '--disable-features=IsolateOrigins,site-per-process', '--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu', '--no-zygote', '--disable-extensions', '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows', '--memory-pressure-off', '--js-flags=--max-old-space-size=128', ]; const COMMON_CONTEXT_OPTS = { userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', locale: 'ko-KR', viewport: { width: 1280, height: 720 }, extraHTTPHeaders: { 'Accept-Language': 'ko-KR,ko;q=0.9,en;q=0.8' }, }; async function _installRoute(ctx) { await ctx.route('**/*', (route) => { const req = route.request(); const type = req.resourceType(); const u = req.url(); if (['image', 'media', 'font', 'stylesheet'].includes(type)) return route.abort(); if (/disable-devtool|googletag|googlesyndication|doubleclick|google-analytics|gtag|adservice|tagmanager/i.test(u)) return route.abort(); return route.continue(); }); } // SOCKS5 ์šฐํšŒ๋˜๋Š” ๊ณต์šฉ ์ปจํ…์ŠคํŠธ โ€” anilife / gcdn / tvchak.org announce ํŽ˜์ด์ง€์šฉ. async function getContext() { if (_context) return _context; const launchOpts = { headless: true, args: COMMON_CHROMIUM_ARGS }; if (PROXY_SERVER) launchOpts.proxy = { server: PROXY_SERVER }; _browser = await chromium.launch(launchOpts); _context = await _browser.newContext(COMMON_CONTEXT_OPTS); await _installRoute(_context); return _context; } // tvchak ์ „์šฉ ์ปจํ…์ŠคํŠธ โ€” SOCKS5(NAS ํ•œ๊ตญ IP) ๊ฒฝ์œ . // NAS์— zapret nfqws(fakedsplit+md5sig)๊ฐ€ KT์˜ tvchak SNI ์ฐจ๋‹จ์„ ์šฐํšŒํ•˜๋ฏ€๋กœ SOCKS5๋กœ ํ•œ๊ตญ IP๋ฅผ ์“ฐ๋ฉด์„œ๋„ ํ†ต๊ณผ. // (datacenter IP ์ง์ ‘์€ Cloudflare๊ฐ€ ์ฐจ๋‹จ โ†’ ๋ฐ˜๋“œ์‹œ SOCKS5 ๊ฒฝ์œ ) async function getTvContext() { if (_tvContext) return _tvContext; // tvchak ์ „์šฉ: TLS 1.2 ๊ณ ์ • + Kyber off๋กœ ClientHello๋ฅผ ์ž‘๊ฒŒ ์œ ์ง€. // โ†’ NAS zapret nfqws์˜ desync ํŒจํ‚ท์ด MTU ์ดˆ๊ณผ("Message too large")๋กœ ์‹คํŒจํ•˜๋˜ ๊ฐ„ํ— ์ฐจ๋‹จ ํ•ด์†Œ. // anilife/gcdn(getContext)์€ TLS 1.3 ์œ ์ง€ํ•ด์•ผ ํ•˜๋ฏ€๋กœ ์ด ์ œํ•œ์„ tvchak ์ปจํ…์ŠคํŠธ์—๋งŒ ์ ์šฉ. const tvArgs = COMMON_CHROMIUM_ARGS .filter(a => !a.startsWith('--disable-features=')) .concat([ '--disable-features=IsolateOrigins,site-per-process,PostQuantumKyber,TLS13KyberSupport', '--ssl-version-max=tls1.2', ]); const launchOpts = { headless: true, args: tvArgs }; if (PROXY_SERVER) launchOpts.proxy = { server: PROXY_SERVER }; _tvBrowser = await chromium.launch(launchOpts); _tvContext = await _tvBrowser.newContext(COMMON_CONTEXT_OPTS); await _installRoute(_tvContext); console.log(`[tvCtx] dedicated tvchak context launched (proxy=${PROXY_SERVER || 'none'}; NAS zapret bypasses KT SNI block)`); return _tvContext; } // tvchak ๋„๋ฉ”์ธ์€ ํ•œ ๋ฒˆ ๋ฉ”์ธ ํŽ˜์ด์ง€์— ๊ฐ€์„œ ๊ทธ page ์ปจํ…์ŠคํŠธ์˜ fetch๋กœ ์ฒ˜๋ฆฌ. // page.evaluate(fetch)๋Š” ์ง„์งœ ๋ธŒ๋ผ์šฐ์ € fetch๋ผ Cloudflare ํ†ต๊ณผ. // ๊ด‘๊ณ  navigate๋ฅผ ํ”ผํ•˜๋ ค๊ณ  ๋ชจ๋“  ๋ฉ”์ธ-ํ”„๋ ˆ์ž„ ์ž๋™ ์ด๋™(์Šคํฌ๋ฆฝํŠธ๋กœ ์ธํ•œ location ๋ณ€๊ฒฝ)์„ ์ฐจ๋‹จ. let _tvPage = null; let _tvDomain = null; // evaluate ์‹คํ–‰ ์ค‘ ํ‘œ์‹ โ€” framenavigated ์ž๋™ goto๊ฐ€ evaluate context๋ฅผ ์ฃฝ์ด๋Š” ๊ฒƒ์„ ์ฐจ๋‹จ. // tvchak204.com ๊ฐ™์ด ๋ฉ”์ธ ํŽ˜์ด์ง€๊ฐ€ ์ž์ฒด ๊ด‘๊ณ  nav๋ฅผ ์ผ์œผํ‚ค๋Š” ๋„๋ฉ”์ธ์—์„œ evaluate ์งํ›„ ์ž๋™ goto๊ฐ€ ์ถฉ๋Œ. let _tvEvaluating = false; async function ensureTvPage(domain) { // USE_LOCAL_CDP ๋ชจ๋“œ: ์‚ฌ์šฉ์ž Chrome(9222)์— attachํ•ด์„œ ๊ทธ์ชฝ ํŽ˜์ด์ง€ ๋ฐ˜ํ™˜. // robots.txt์— ๋จธ๋ฌผ๋Ÿฌ์„œ ๊ด‘๊ณ  nav ํšŒํ”ผ (location.host๋Š” ๊ทธ๋Œ€๋กœ domain โ†’ same-origin fetch ๊ฐ€๋Šฅ). // searchSiteยทtvFetchPlaywright ๋“ฑ ๋ชจ๋“  ensureTvPage ํ˜ธ์ถœ์ž๊ฐ€ ์ด ํŽ˜์ด์ง€๋ฅผ ๋ฐ›๊ฒŒ ๋จ. // CDP attach ์‹คํŒจ ์‹œ ๊ธฐ์กด Playwright ๊ฒฝ๋กœ๋กœ ํด๋ฐฑ (Chrome ์•ˆ ๋„์›Œ๋‘” ์ƒํƒœ ๋Œ€๋น„). if (USE_LOCAL_CDP) { try { const cdpPage = await ensureCdpPage(domain); if (cdpPage) return cdpPage; } catch (e) { console.warn('[ensureTvPage] cdp attach failed, fallback to local Playwright:', String(e.message || e).slice(0, 100)); } } if (_tvPage && !_tvPage.isClosed() && _tvDomain === domain) { // ํŽ˜์ด์ง€๊ฐ€ ๊ด‘๊ณ ๋กœ ๋– ๋‚ฌ์œผ๋ฉด ๋ณต๊ท€ try { const u = _tvPage.url(); if (!u.includes(domain)) { await _tvPage.goto(`https://${domain}/`, { waitUntil: 'domcontentloaded', timeout: 25000 }); } } catch {} return _tvPage; } if (_tvPage && !_tvPage.isClosed()) await _tvPage.close().catch(() => {}); const ctx = await getTvContext(); _tvPage = await ctx.newPage(); _tvDomain = domain; _tvPage.on('popup', (p) => p.close().catch(() => {})); // ๊ด‘๊ณ /์ถ”์ /์žก ๋ฆฌ์†Œ์Šค ์ฐจ๋‹จ (๋ฉ”์ธ ํ”„๋ ˆ์ž„ navigate๋Š” ๊ฑด๋“œ๋ฆฌ์ง€ ์•Š์Œ โ€” ์ฐจ๋‹จํ•˜๋ฉด about:blank๊ฐ€ ๋จ) await _tvPage.route('**/*', (route) => { const req = route.request(); const u = req.url(); const type = req.resourceType(); if (/disable-devtool|googletagmanager|google-analytics|googlesyndication|doubleclick|adservice|tagmanager|hotjar|ckp\.wiselife/i.test(u)) { return route.abort(); } if (['image', 'media', 'font', 'stylesheet'].includes(type)) return route.abort(); return route.continue(); }); // ๋ฉ”์ธ ํ”„๋ ˆ์ž„ navigate๋ฅผ ๊ฐ€๋กœ์ฑ„๋Š” framenavigated ํ•ธ๋“ค๋Ÿฌ๋กœ ๊ด‘๊ณ  lander๋กœ ๊ฐ€๋ฉด ์ฆ‰์‹œ ๋ฉˆ์ถฐ์„œ ๋„๋ฉ”์ธ์œผ๋กœ ๋ณต๊ท€. // ๋‹จ, evaluate ์ง„ํ–‰ ์ค‘์—๋Š” ์ž๋™ goto๊ฐ€ ์‹คํ–‰ ์ค‘์ธ evaluate context๋ฅผ ํŒŒ๊ดดํ•˜๋ฏ€๋กœ skip โ€” ํ˜ธ์ถœ์ž๊ฐ€ ๋๋‚œ ๋’ค ๋‹ค์Œ ํ˜ธ์ถœ์—์„œ ensureTvPage๊ฐ€ ๋ณต๊ท€์‹œํ‚ด. _tvPage.on('framenavigated', async (frame) => { if (!_tvPage || _tvPage.isClosed()) return; if (frame !== _tvPage.mainFrame()) return; if (_tvEvaluating) return; const u = frame.url(); if (u && !u.startsWith('about:') && !u.includes(domain)) { try { await _tvPage.goto(`https://${domain}/`, { waitUntil: 'domcontentloaded', timeout: 15000 }); } catch {} } }); try { await _tvPage.goto(`https://${domain}/`, { waitUntil: 'domcontentloaded', timeout: 25000 }); } catch (e) { console.warn('tvPage initial nav:', e.message); } return _tvPage; } // _tvPage๋Š” ๋‹จ์ผ ํŽ˜์ด์ง€๋ฅผ ๊ณต์œ ํ•˜๋ฏ€๋กœ ๋™์‹œ evaluate ์‹œ race condition ์œ„ํ—˜. // ๋ชจ๋“  _tvPage ์ž‘์—…์„ ์ง๋ ฌํ™”ํ•˜๋Š” mutex. let _tvPageMutex = Promise.resolve(); let _tvMutexQueueLen = 0; let _tvInFlight = 0; // ์‹ค์ œ๋กœ fn ์‹คํ–‰ ์ค‘์ธ ํ˜ธ์ถœ ์ˆ˜ (queue ๋Œ€๊ธฐ์™€ ๋ณ„๊ฐœ) let _tvLastSuccessAt = Date.now(); let _tvLastActivityAt = Date.now(); const TV_MUTEX_QUEUE_MAX = 5; class TvMutexBusyError extends Error { constructor() { super('tvchak busy (queue saturated)'); this.code = 'TV_MUTEX_BUSY'; } } // tvchak ํŽ˜์ด์ง€ mutex. ์ง๋ ฌํ™”๋Š” race ๋ฐฉ์ง€์šฉ์ด์ง€๋งŒ, ์ด์ „ ์ž‘์—…์ด hangํ•˜๋ฉด ์ค„์„  ๋ชจ๋“  ์š”์ฒญ์ด ๋ง‰ํž˜. // โ†’ prev์— timeout(40์ดˆ) ๊ฑธ์–ด ์•ˆ์ „์žฅ์น˜. timeout ์ดˆ๊ณผํ•˜๋ฉด ๊ฐ•์ œ ์ง„ํ–‰ + tvPage ๋ฆฌ์…‹. // โ†’ ์ถ”๊ฐ€: queue ๊ธธ์ด ์ œํ•œ. ์ข€๋น„ ๋ฐœ์ƒ ์‹œ ์ค„์ด ๋ฌดํ•œ ๋ˆ„์ ๋˜๋ฉฐ ํญ์ฃผ(`prev timeout 40s` ์ˆ˜์‹ญ ํšŒ)๋˜๋˜ ๋ฌธ์ œ ๋ฐฉ์ง€. function withTvMutex(fn) { _tvLastActivityAt = Date.now(); if (_tvMutexQueueLen >= TV_MUTEX_QUEUE_MAX) { return Promise.reject(new TvMutexBusyError()); } _tvMutexQueueLen++; const prev = _tvPageMutex; let release; _tvPageMutex = new Promise(r => { release = r; }); return (async () => { try { // ์ด์ „ ์ž‘์—… ์ตœ๋Œ€ 40์ดˆ ๋Œ€๊ธฐ. ์ดˆ๊ณผํ•˜๋ฉด ์ข€๋น„๋กœ ๊ฐ„์ฃผํ•˜๊ณ  ๊ฐ•์ œ ์ง„ํ–‰ await Promise.race([ prev, new Promise((_, rej) => setTimeout(() => rej(new Error('tvMutex prev timeout 40s')), 40000)), ]).catch(async (e) => { console.warn('[tvMutex] previous task did not release in time โ€” forcing tvPage reset:', e.message); try { if (_tvPage && !_tvPage.isClosed()) await _tvPage.close().catch(() => {}); } catch {} _tvPage = null; _tvDomain = null; }); _tvInFlight++; try { const result = await fn(); _tvLastSuccessAt = Date.now(); return result; } finally { _tvInFlight--; } } finally { _tvMutexQueueLen--; release(); } })(); } // tvchak fetch ์ „์šฉ ๋ณ„๋„ ํŽ˜์ด์ง€ โ€” ๋ฉ”์ธ ํŽ˜์ด์ง€ ๊ด‘๊ณ  nav์™€ ๊ฒฉ๋ฆฌ. // about:blank๋กœ๋Š” same-origin fetch๊ฐ€ ์•ˆ ๋˜๋ฏ€๋กœ(CORS) tvchak ๋„๋ฉ”์ธ์˜ ๊ฐ€๋ฒผ์šด ๊ฒฝ๋กœ(/robots.txt)์—์„œ evaluate. // robots.txt๋Š” plain text๋ผ ๊ด‘๊ณ  JS๊ฐ€ ์—†์–ด ํŽ˜์ด์ง€๊ฐ€ ๋– ๋‚˜์ง€ ์•Š์Œ + same-origin์ด๋ผ fetch ํ†ต๊ณผ. let _tvFetchPage = null; let _tvFetchPageDomain = null; async function ensureTvFetchPage(domain) { const target = `https://${domain}/robots.txt`; if (_tvFetchPage && !_tvFetchPage.isClosed() && _tvFetchPageDomain === domain) { try { const u = _tvFetchPage.url(); // ๊ฐ™์€ origin์ด๋ฉด ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉ (์–ด๋–ค ๊ฒฝ๋กœ๋“  OK) if (u.includes(domain)) return _tvFetchPage; await _tvFetchPage.goto(target, { waitUntil: 'domcontentloaded', timeout: 15000 }).catch(() => {}); } catch {} return _tvFetchPage; } if (_tvFetchPage && !_tvFetchPage.isClosed()) await _tvFetchPage.close().catch(() => {}); const ctx = await getTvContext(); _tvFetchPage = await ctx.newPage(); _tvFetchPageDomain = domain; _tvFetchPage.on('popup', (p) => p.close().catch(() => {})); // robots.txt๋Š” plain text๋ผ JS ์‹คํ–‰์ด ์—†๊ณ  ๊ด‘๊ณ  nav ์˜ํ–ฅ์ด ์—†์Œ. 404์—ฌ๋„ ๋ณธ๋ฌธ ํŽ˜์ด์ง€์—์„œ same-origin fetch ๊ฐ€๋Šฅ. await _tvFetchPage.goto(target, { waitUntil: 'domcontentloaded', timeout: 15000 }).catch(() => {}); return _tvFetchPage; } // NAS fetch ํ”„๋ก์‹œ โ€” autossh -L 127.0.0.1:18080 โ†’ NAS์˜ 8899. // NAS๋Š” ํ•œ๊ตญ residential IP + zapret desync๋กœ tvchak์— 0.7์ดˆยท๊ณ ์„ฑ๊ณต๋ฅ  ์ ‘๊ทผ. // HF์—์„œ SOCKS5 raw TLS(๋А๋ฆผ+ํฐ ClientHello desync ์‹คํŒจ) ๋Œ€์‹  NAS๊ฐ€ fetchํ•œ ๊ฒฐ๊ณผ(JSON)๋งŒ ๋ฐ›์Œ. const NAS_FETCH_PROXY = process.env.NAS_FETCH_PROXY || 'http://127.0.0.1:18080'; function nasFetch(fullUrl, timeoutMs = 15000) { return new Promise((resolve) => { try { const proxyUrl = `${NAS_FETCH_PROXY}/fetch?url=${encodeURIComponent(fullUrl)}`; const req = http.get(proxyUrl, { timeout: timeoutMs }, (res) => { let buf = ''; res.on('data', (d) => { buf += d; }); res.on('end', () => { try { const j = JSON.parse(buf); if (j.status && j.status >= 200 && j.status < 300 && typeof j.body === 'string') { resolve({ ok: true, status: j.status, body: j.body }); } else { resolve({ ok: false, status: j.status || 0, error: j.error || `proxy status ${j.status}` }); } } catch (e) { resolve({ ok: false, error: `proxy parse: ${String(e.message || e).slice(0, 80)}` }); } }); }); req.on('error', (e) => resolve({ ok: false, error: `proxy conn: ${String(e.message || e).slice(0, 80)}` })); req.on('timeout', () => { req.destroy(); resolve({ ok: false, error: 'proxy timeout' }); }); } catch (e) { resolve({ ok: false, error: `proxy: ${String(e.message || e).slice(0, 80)}` }); } }); } // โ”€โ”€โ”€โ”€โ”€ ๋กœ์ปฌ CDP attach ๋ชจ๋“œ (USE_LOCAL_CDP=1) โ”€โ”€โ”€โ”€โ”€ // KT SNI ์ฐจ๋‹จ + Cloudflare bot์œผ๋กœ ๋กœ์ปฌ์—์„œ ์ง์ ‘ fetch ๋ถˆ๊ฐ€. ์‚ฌ์šฉ์ž Chrome(ECH + cf_clearance) // ์„ 9222 ๋””๋ฒ„๊น… ํฌํŠธ๋กœ ๋„์›Œ๋‘๊ณ  attachํ•ด์„œ fetch ์œ„์ž„. start-chrome-cdp.bat ์ฐธ์กฐ. // SNI ํ’€๋ฆฌ๋ฉด USE_LOCAL_CDP ํ™˜๊ฒฝ๋ณ€์ˆ˜๋งŒ ๋นผ๋ฉด ๊ธฐ์กด NAS/Playwright ๊ฒฝ๋กœ๋กœ ์ž๋™ ์›๋ณต. const USE_LOCAL_CDP = process.env.USE_LOCAL_CDP === '1'; const LOCAL_CDP_URL = process.env.LOCAL_CDP_URL || 'http://127.0.0.1:9222'; // ๋„๋ฉ”์ธ ๊ฐ•์ œ ๊ณ ์ • โ€” announce/์บ์‹œ ๋ฌด์‹œํ•˜๊ณ  ์ด ๋„๋ฉ”์ธ๋งŒ ์‚ฌ์šฉ. ๋นˆ ๊ฐ’์ด๋ฉด ํ‰์†Œ๋Œ€๋กœ announce ์ถ”์ข…. const FORCE_DOMAIN = process.env.FORCE_DOMAIN || ''; let _cdpBrowser = null; let _cdpCtx = null; let _cdpPage = null; let _cdpPageDomain = null; // server.js๊ฐ€ ์ง์ ‘ ์ƒ์„ฑํ•œ(navigateํ•œ) CDP ํƒญ๋งŒ ์ถ”์  โ€” ์‚ฌ์šฉ์ž๊ฐ€ ์ง์ ‘ ์—ฐ cf ํ†ต๊ณผ ํƒญ๊ณผ ๊ตฌ๋ถ„. // ํƒญ ํญ์ฆ ๋ฐฉ์ง€: ์šฐ๋ฆฌ ์†Œ์œ  ํƒญ์€ ํ•ญ์ƒ ์ตœ๋Œ€ 1๊ฐœ๋กœ ํšŒ์ˆ˜. ์‚ฌ์šฉ์ž ํƒญ์€ ์ ˆ๋Œ€ close ์•ˆ ํ•จ. let _cdpOwnedPages = new WeakSet(); // ์šด์˜์ž๊ฐ€ announce๋ฅผ ์ž์ฃผ ๋ฐ”๊ฟ”๋„(๋ฒˆํ˜ธ โ†” flat ๋„๋ฉ”์ธ) ๋Š˜ ํ›„๋ณด์— ๋„ฃ์„ ์•Œ๋ ค์ง„ ์ฝ˜ํ…์ธ  ๋„๋ฉ”์ธ. const KNOWN_CONTENT_DOMAINS = ['tvchak.live']; // 9222 CDP profile Chrome ์ฐฝ "ํฌ์ปค์Šค๋งŒ ๋’ค๋กœ" โ€” newPage/navigate๊ฐ€ ์ฐฝ์„ ํฌ์ปค์Šค๋กœ ๋Œ์–ด์˜ฌ๋ฆฌ๋Š” ๋ถ€์ž‘์šฉ ์ฐจ๋‹จ. // (2026-07-08 ๋ณ€๊ฒฝ) ์‚ฌ์šฉ์ž๊ฐ€ CDP ์ฐฝ์„ ํ™”๋ฉด์— ๋‘๊ณ  ์ง์ ‘ ์ปจํŠธ๋กคํ•˜๊ธฐ ์›ํ•จ โ†’ ํ™”๋ฉด ๋ฐ– ์ด๋™(-32000)ยท์ตœ์†Œํ™”(FORCEMINIMIZE) // ๋ฅผ ์ œ๊ฑฐํ•˜๊ณ , ์ฐฝ ์œ„์น˜ยทํฌ๊ธฐยทํ‘œ์‹œ์ƒํƒœ๋Š” ๊ทธ๋Œ€๋กœ ๋‘๋˜ Z์ˆœ์„œ๋งŒ ๋งจ ๋’ค(HWND_BOTTOM)๋กœ + NOACTIVATE๋กœ // ํ™œ์„ฑํ™”(ํฌ์ปค์Šค)๋งŒ ๋บ๊ธฐ์ง€ ์•Š๊ฒŒ ํ•œ๋‹ค. ์‚ฌ์šฉ์ž๊ฐ€ ๋†“์€ ์ž๋ฆฌ์— ์ฐฝ์ด ๊ทธ๋Œ€๋กœ ๋‚จ๋Š”๋‹ค. // SWP_NOACTIVATE(0x10)|SWP_NOMOVE(0x02)|SWP_NOSIZE(0x01) = 0x13. HWND_BOTTOM = 1. // debounce(in-flight) ๋ณดํ˜ธ๋กœ ๋™์‹œ ํ˜ธ์ถœ ์‹œ 1ํšŒ๋งŒ ์‹คํ–‰. Promise ๋ฐ˜ํ™˜ํ•ด์„œ await ๊ฐ€๋Šฅ. let _minimizeInFlight = null; function minimizeCdpChromeWindow() { if (_minimizeInFlight) return _minimizeInFlight; // Z์ˆœ์„œ๋งŒ ๋งจ ๋’ค๋กœ(HWND_BOTTOM=1) + NOMOVE|NOSIZE|NOACTIVATE โ†’ ์œ„์น˜/ํฌ๊ธฐ/ํฌ์ปค์Šค ์•ˆ ๊ฑด๋“œ๋ฆผ. // ํ•„ํ„ฐ๋Š” --remote-debugging-port=9222 ํ”„๋กœํŒŒ์ผ๋งŒ(์‚ฌ์šฉ์ž ์ผ๋ฐ˜ Chrome ์ ˆ๋Œ€ ์•ˆ ๊ฑด๋“œ๋ฆผ). const script = "$ErrorActionPreference='SilentlyContinue';" + "if(-not('W32C.Win'-as[Type])){Add-Type -Namespace W32C -Name Win -MemberDefinition '[DllImport(\"user32.dll\")]public static extern bool SetWindowPos(System.IntPtr hWnd,System.IntPtr after,int x,int y,int cx,int cy,uint flags);'};" + "Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\"|" + "?{$_.CommandLine -like '*--remote-debugging-port=9222*'}|" + "%{Get-Process -Id $_.ProcessId -EA SilentlyContinue}|" + "?{$_.MainWindowHandle -ne 0}|" + "%{[W32C.Win]::SetWindowPos($_.MainWindowHandle,[System.IntPtr]1,0,0,0,0,0x13)|Out-Null}"; const { spawn } = require('child_process'); _minimizeInFlight = new Promise((resolve) => { const p = spawn('powershell.exe', ['-NoProfile', '-WindowStyle', 'Hidden', '-Command', script], { windowsHide: true }); p.on('exit', () => { _minimizeInFlight = null; resolve(); }); p.on('error', () => { _minimizeInFlight = null; resolve(); }); }); return _minimizeInFlight; } // โ”€โ”€โ”€ CDP ์ฐฝ ํ™”๋ฉด ์œ ์ง€ ์›Œ์ฒ˜ (2026-07-08) โ”€โ”€โ”€ // ์‚ฌ์šฉ์ž๊ฐ€ CDP ์ฐฝ์„ ์ง์ ‘ ์ปจํŠธ๋กคํ•˜๊ธฐ ์›ํ•จ. navigate/ํƒญ์ •๋ฆฌ๊ฐ€ ์ฐฝ์„ ํ™”๋ฉด ๋ฐ–์œผ๋กœ ๋ฐ€๊ฑฐ๋‚˜ ์ตœ์†Œํ™”ํ•˜๋ฉด // ์ฃผ๊ธฐ์ ์œผ๋กœ ํ™”๋ฉด ์•ˆ(150,100 / 1280x860)์œผ๋กœ ๋˜๋Œ๋ฆฐ๋‹ค. ๋‹จ SWP_NOACTIVATE๋กœ ํฌ์ปค์Šค๋Š” ์ ˆ๋Œ€ ์•ˆ ๋บ์Œ. // ์ฐฝ์ด ์ด๋ฏธ ํ™”๋ฉด ์•ˆ ์ •์ƒ ์˜์—ญ(๊ฐ€์‹œ)์— ์žˆ๊ณ  ์ตœ์†Œํ™”๊ฐ€ ์•„๋‹ˆ๋ฉด ๊ฑด๋“œ๋ฆฌ์ง€ ์•Š์Œ(๋ถˆํ•„์š”ํ•œ ์žฌ๋ฐฐ์น˜ = ๊นœ๋นก์ž„ ๋ฐฉ์ง€). let _cdpWindowWatcher = null; function startCdpWindowWatcher() { if (_cdpWindowWatcher) return; // PowerShell ์ƒ์ฃผ ํ”„๋กœ์„ธ์Šค๋กœ 2์ดˆ๋งˆ๋‹ค ์ฒดํฌ โ€” node์—์„œ ๋งค๋ฒˆ spawnํ•˜๋ฉด ๋ฌด๊ฑฐ์šฐ๋ฏ€๋กœ PS ๋ฃจํ”„ ํ•˜๋‚˜๋กœ. // ์ตœ์†Œํ™”(iconic)๋ฉด SW_SHOWNOACTIVATE(4)๋กœ ๋ณต์›, ํ™”๋ฉด ๋ฐ–์ด๋ฉด ํ™”๋ฉด ์•ˆ์œผ๋กœ MoveWindow. // ํฌ์ปค์Šค๋Š” ์•ˆ ๊ฑด๋“œ๋ฆผ(ShowWindow 4 = SHOWNOACTIVATE, SetWindowPos๋Š” ์•ˆ ์”€). const script = [ "$ErrorActionPreference='SilentlyContinue';", "Add-Type @'", "using System;using System.Runtime.InteropServices;", "public class CdpW{", "[DllImport(\"user32.dll\")]public static extern bool GetWindowRect(IntPtr h,out RECT r);", "[DllImport(\"user32.dll\")]public static extern bool IsIconic(IntPtr h);", "[DllImport(\"user32.dll\")]public static extern bool ShowWindow(IntPtr h,int n);", "[DllImport(\"user32.dll\")]public static extern bool MoveWindow(IntPtr h,int x,int y,int w,int hh,bool r);", "[StructLayout(LayoutKind.Sequential)]public struct RECT{public int Left,Top,Right,Bottom;}}", "'@;", "while($true){", " try{", " $ps=Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\"|?{$_.CommandLine -like '*--remote-debugging-port=9222*'}|%{Get-Process -Id $_.ProcessId -EA SilentlyContinue}|?{$_.MainWindowHandle -ne 0}|Select-Object -First 1;", " if($ps){", " $h=$ps.MainWindowHandle;", " if([CdpW]::IsIconic($h)){ [CdpW]::ShowWindow($h,4)|Out-Null }", // SW_SHOWNOACTIVATE " $r=New-Object CdpW+RECT; [CdpW]::GetWindowRect($h,[ref]$r)|Out-Null;", " if($r.Left -lt -5000 -or $r.Top -lt -5000 -or $r.Left -gt 5000){ [CdpW]::MoveWindow($h,150,100,1280,860,$true)|Out-Null }", // ํ™”๋ฉด ๋ฐ–์ด๋ฉด ์•ˆ์œผ๋กœ " }", " }catch{}", " Start-Sleep -Seconds 2;", "}", ].join(''); try { const { spawn } = require('child_process'); _cdpWindowWatcher = spawn('powershell.exe', ['-NoProfile', '-WindowStyle', 'Hidden', '-Command', script], { windowsHide: true, detached: false }); _cdpWindowWatcher.on('exit', () => { _cdpWindowWatcher = null; }); _cdpWindowWatcher.on('error', () => { _cdpWindowWatcher = null; }); console.log('[cdp] window watcher started (ํ™”๋ฉด ์œ ์ง€, ํฌ์ปค์Šค ์•ˆ ๋บ์Œ)'); } catch (e) { console.warn('[cdp] window watcher spawn failed:', e.message); } } // โ”€โ”€โ”€ cf challenge ์ž๋™ ๊ฐ์ง€ ์‹œ CDP ์ฐฝ ํ™”๋ฉด ๋ณต์› (2026-07-02) โ”€โ”€โ”€ // CF_PASS_NEEDED๊ฐ€ ๊ฐ์ง€๋œ ์ˆœ๊ฐ„์—๋งŒ 1ํšŒ์„ฑ์œผ๋กœ 9222 ํ”„๋กœํŒŒ์ผ Chrome ์ฐฝ์„ ํ™”๋ฉด ์•ˆ(SW_RESTORE + ํ™”๋ฉด // ์ขŒํ‘œ ์ด๋™)์œผ๋กœ ๋Œ์–ด์˜ฌ๋ ค ์‚ฌ์šฉ์ž๊ฐ€ ์ฆ‰์‹œ ๋ด‡ ํ•ด์ œ๋ฅผ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•œ๋‹ค. // โš ๏ธ ๊ณผ๊ฑฐ ์‚ฌ๊ณ (6a3dbdb): ์ฃผ๊ธฐ์ ์œผ๋กœ ์ฐฝ์„ foreground๋กœ ์˜ฌ๋ฆฌ๊ณ  ์žฌํƒ์ƒ‰ํ•˜๋Š” ๋ฃจํ”„๊ฐ€ ๋„๋ฉ”์ธ ๋ณ€๊ฒฝ๊ณผ // ๋งž๋ฌผ๋ ค ๋ฌดํ•œ ๊นœ๋นก์ž„์„ ๋ƒˆ๋‹ค. ๊ทธ๋ž˜์„œ ์—ฌ๊ธฐ์„  (1)์ด๋ฒคํŠธ ๊ธฐ๋ฐ˜ 1ํšŒ์„ฑ, (2)์ฟจ๋‹ค์šด(REVEAL_COOLDOWN_MS)์œผ๋กœ // ๋ฐ˜๋ณต ํ˜ธ์ถœ ๋ฐฉ์ง€, (3)navigate/newPage minimize ๋กœ์ง๊ณผ ์™„์ „ ๋ถ„๋ฆฌ โ€” ์ด 3๊ฐ€์ง€๋กœ ๊นœ๋นก์ž„์„ ์›์ฒœ ์ฐจ๋‹จํ•œ๋‹ค. const REVEAL_COOLDOWN_MS = 3 * 60 * 1000; // 3๋ถ„: ํ•œ ๋ฒˆ ๋„์šฐ๋ฉด ์ด ์‹œ๊ฐ„ ๋™์•ˆ ๋‹ค์‹œ ์•ˆ ๋„์›€ let _lastRevealAt = 0; let _revealInFlight = null; function revealCdpChromeForChallenge() { const now = Date.now(); if (now - _lastRevealAt < REVEAL_COOLDOWN_MS) return Promise.resolve(); // ์ฟจ๋‹ค์šด ์ค‘ โ€” ๋ฌด์‹œ if (_revealInFlight) return _revealInFlight; _lastRevealAt = now; console.warn('[cdp] cf challenge ๊ฐ์ง€ โ€” CDP Chrome ์ฐฝ์„ ํ™”๋ฉด์— ๋„์›๋‹ˆ๋‹ค (๋ด‡ ํ•ด์ œ ํ•„์š”)'); // SW_RESTORE=9 ๋กœ ์ตœ์†Œํ™” ํ•ด์ œ + ํ™”๋ฉด ์•ˆ(100,100 / 1200x800)์œผ๋กœ ์ด๋™ + foreground. // ํ•„ํ„ฐ๋Š” --remote-debugging-port=9222 ํ”„๋กœํŒŒ์ผ๋งŒ (์‚ฌ์šฉ์ž ์ผ๋ฐ˜ Chrome ์ ˆ๋Œ€ ์•ˆ ๊ฑด๋“œ๋ฆผ). const script = "$ErrorActionPreference='SilentlyContinue';" + "if(-not('W32R.Win'-as[Type])){Add-Type -Namespace W32R -Name Win -MemberDefinition '[DllImport(\"user32.dll\")]public static extern bool ShowWindow(System.IntPtr hWnd,int nCmdShow);[DllImport(\"user32.dll\")]public static extern bool SetWindowPos(System.IntPtr hWnd,System.IntPtr after,int x,int y,int cx,int cy,uint flags);[DllImport(\"user32.dll\")]public static extern bool SetForegroundWindow(System.IntPtr hWnd);'};" + "Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\"|" + "?{$_.CommandLine -like '*--remote-debugging-port=9222*'}|" + "%{Get-Process -Id $_.ProcessId -EA SilentlyContinue}|" + "?{$_.MainWindowHandle -ne 0}|" + "%{[W32R.Win]::ShowWindow($_.MainWindowHandle,9)|Out-Null;[W32R.Win]::SetWindowPos($_.MainWindowHandle,[System.IntPtr]0,100,100,1200,800,0x0040)|Out-Null;[W32R.Win]::SetForegroundWindow($_.MainWindowHandle)|Out-Null}"; const { spawn } = require('child_process'); _revealInFlight = new Promise((resolve) => { const p = spawn('powershell.exe', ['-NoProfile', '-WindowStyle', 'Hidden', '-Command', script], { windowsHide: true }); p.on('exit', () => { _revealInFlight = null; resolve(); }); p.on('error', () => { _revealInFlight = null; resolve(); }); }); return _revealInFlight; } // (์ œ๊ฑฐ๋จ 2026-06-30) triggerCfChallengeUi / cfClearanceMonitor / announceFollower. // ์ฐฝ foreground ๋ณต์› + ์ฃผ๊ธฐ์  ์žฌํƒ์ƒ‰์ด ์šด์˜์ž์˜ ์žฆ์€ ๋„๋ฉ”์ธ ๋ฒˆํ˜ธ ๋ณ€๊ฒฝ๊ณผ ๋งž๋ฌผ๋ ค // robots ํƒญ ํญ์ฆ + ์ฐฝ ํ™œ์„ฑํ™”โ†”์ตœ์†Œํ™” ๋ฌดํ•œ ๊นœ๋นก์ž„์„ ์ผ์œผํ‚ด. ๋„๋ฉ”์ธ ๊ฒฐ์ •์€ findLiveDomain์ด // tvchak.org announce๋ฅผ ์ฝ์–ด ๊ทธ๋Œ€๋กœ ์ฑ„ํƒํ•˜๋Š” ๋‹จ์ˆœ ๊ฒฝ๋กœ๋กœ ์ผ์›ํ™”. cf challenge๊ฐ€ ํ•„์š”ํ•˜๋ฉด // ์‚ฌ์šฉ์ž๊ฐ€ CDP Chrome ์ฐฝ์—์„œ ์ง์ ‘ ํ†ต๊ณผ(navigator.webdriver=false๋ผ ์‚ฌ๋žŒ ํด๋ฆญ ๊ฐ€๋Šฅ). // 9222 CDP ์‘๋‹ต ์—ฌ๋ถ€ ๊ฐ€๋ฒผ์šด ์ฒดํฌ. 200/json/version์ด ์‘๋‹ตํ•˜๋ฉด alive. function checkCdpAlive(timeoutMs = 2000) { return new Promise((resolve) => { try { const u = new URL('/json/version', LOCAL_CDP_URL); const req = http.get({ hostname: u.hostname, port: u.port || 9222, path: u.pathname, timeout: timeoutMs }, (res) => { res.resume(); resolve(res.statusCode === 200); }); req.on('error', () => resolve(false)); req.on('timeout', () => { req.destroy(); resolve(false); }); } catch { resolve(false); } }); } // CDP Chrome์ด ์ฃฝ์—ˆ์„ ๋•Œ ์ž๋™ ๊ธฐ๋™. ps1๊ณผ ๋™์ผํ•œ args + ๋™์ผ ํ”„๋กœํŒŒ์ผ(C:\chrome-cdp)์„ ์‚ฌ์šฉํ•ด cf_clearance ์ฟ ํ‚ค ์œ ์ง€. // ๋™์‹œ ํ˜ธ์ถœ ๋ฐฉ์ง€๋ฅผ ์œ„ํ•œ in-flight Promise ์บ์‹œ. let _spawnCdpInFlight = null; function spawnCdpChrome() { if (_spawnCdpInFlight) return _spawnCdpInFlight; _spawnCdpInFlight = (async () => { console.warn('[cdp] 9222 down โ€” spawning Chrome'); const { spawn } = require('child_process'); // ps1๊ณผ ๋™์ผํ•œ args (start-server.ps1 ์ฐธ์กฐ). ์‹œ์ž‘ ํƒญ 3๊ฐœ (2026-07-12): // announce(tvchak.org) + ์ฝ˜ํ…์ธ  ๋„๋ฉ”์ธ 2์ข…(.live, 208). ์–ด๋А ๋„๋ฉ”์ธ์ด ์‚ด์•„์žˆ๋“  ํƒญ์ด ์ค€๋น„๋ผ ์žˆ์–ด // ์‚ฌ์šฉ์ž๋Š” cf ์ฒดํฌ๋ฐ•์Šค๋งŒ ํ†ต๊ณผํ•˜๋ฉด ๋จ(์ฃผ์†Œ์ฐฝ ํƒ€์ดํ•‘ ๋ถˆํ•„์š”). cf ํ†ต๊ณผ ์ž์ฒด๋Š” ์—ฌ์ „ํžˆ ์‚ฌ๋žŒ ํด๋ฆญ ํ•„์š”. const chromePath = process.env.CDP_CHROME_PATH || 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'; const profileDir = process.env.CDP_PROFILE_DIR || 'C:\\chrome-cdp'; const args = [ '--remote-debugging-port=9222', `--user-data-dir=${profileDir}`, '--no-first-run', '--no-default-browser-check', // ํ™”๋ฉด ์•ˆ ์ขŒํ‘œ๋กœ ๊ธฐ๋™ โ€” ์‚ฌ์šฉ์ž๊ฐ€ CDP ์ฐฝ์„ ์ง์ ‘ ๋ณด๊ณ  ์ปจํŠธ๋กค(2026-07-08). // navigate ์‹œ์—” minimizeCdpChromeWindow()๊ฐ€ Z์ˆœ์„œ๋งŒ ๋’ค๋กœ ๋ณด๋‚ด ํฌ์ปค์Šค๋งŒ ์•ˆ ๋บ์Œ(์ฐฝ์€ ํ™”๋ฉด์— ๋‚จ์Œ). '--window-position=150,100', '--window-size=1280,860', 'https://tvchak.org/', 'https://tvchak.live/', 'https://tvchak208.com/', ]; try { const p = spawn(chromePath, args, { detached: true, stdio: 'ignore', windowsHide: false }); p.unref(); } catch (e) { console.warn('[cdp] spawn failed:', e.message); return false; } // 9222๊ฐ€ ์‘๋‹ตํ•  ๋•Œ๊นŒ์ง€ ํด๋ง (์ตœ๋Œ€ 15์ดˆ) for (let i = 0; i < 30; i++) { await new Promise((r) => setTimeout(r, 500)); if (await checkCdpAlive(2000)) { console.log('[cdp] Chrome respawned, 9222 ready'); // ํฌ์ปค์Šค ๋บ๊ธฐ ๋ฐฉ์ง€ โ€” ์‚ด์•„๋‚˜์ž๋งˆ์ž ๊ฐ•์ œ ์ตœ์†Œํ™” minimizeCdpChromeWindow(); return true; } } console.warn('[cdp] respawn timeout โ€” 9222 did not come up in 15s'); return false; })().finally(() => { _spawnCdpInFlight = null; }); return _spawnCdpInFlight; } async function getCdpBrowser() { if (_cdpBrowser && _cdpBrowser.isConnected()) return _cdpBrowser; // attach ์ „์— 9222 ์‚ด์•„ ์žˆ๋Š”์ง€ ๋น ๋ฅด๊ฒŒ ํ™•์ธ. ์ฃฝ์—ˆ์œผ๋ฉด Chrome ์žฌ๊ธฐ๋™. if (!(await checkCdpAlive(2000))) { await spawnCdpChrome(); } _cdpBrowser = await chromium.connectOverCDP(LOCAL_CDP_URL, { timeout: 5000 }); _cdpBrowser.on('disconnected', () => { _cdpBrowser = null; _cdpCtx = null; _cdpPage = null; _cdpPageDomain = null; _cdpOwnedPages = new WeakSet(); // ๋ธŒ๋ผ์šฐ์ € ๋ฐ”๋€Œ๋ฉด ํŽ˜์ด์ง€ ํ•ธ๋“ค ๋ฌดํšจ โ€” ์ถ”์  ์ดˆ๊ธฐํ™” }); console.log('[cdp] connected to', LOCAL_CDP_URL); return _cdpBrowser; } // announce/probe์šฉ CDP fetch. tvFetchCDP์™€ ๋™์ผํ•œ same-origin fetch ํŒจํ„ด ์‚ฌ์šฉ โ€” // ensureCdpPage(host)๋กœ ๊ทธ ๋„๋ฉ”์ธ์˜ robots.txt ํŽ˜์ด์ง€๋ฅผ ๋„์šฐ๊ณ  page.evaluate(fetch)๋กœ ํ˜ธ์ถœ. // ์ด๋ ‡๊ฒŒ ํ•ด์•ผ cf_clearance ์ฟ ํ‚ค๊ฐ€ credentials:'include'๋กœ ํ•จ๊ป˜ ๊ฐ€์„œ ์ •์ƒ body ๋ฐ˜ํ™˜. // (์ด์ „ page.goto + page.content() ๋ฐฉ์‹์€ cf challenge HTML์ด ์žกํžˆ๊ฑฐ๋‚˜ redirect ํ›„ ๋‹ค๋ฅธ origin // HTML์ด ์žกํ˜€์„œ player_aaaa ์ •๊ทœ์‹์ด ๋งค๋ฒˆ ์‹คํŒจ โ†’ ์บ์‹œ dead ์˜คํŒ โ†’ rediscovering ํญ์ฃผ ์‚ฌ๊ณ  ๋ฐœ์ƒ.) async function cdpFetchPage(targetUrl, timeoutMs = 10000) { try { const u = new URL(targetUrl); const host = u.hostname; const page = await ensureCdpPage(host); const pageUrl = page.url(); if (!pageUrl.includes(host)) { _cdpPage = null; _cdpPageDomain = null; return { ok: false, error: `cdp page url not on host: ${pageUrl.slice(0, 60)}` }; } const result = await Promise.race([ page.evaluate(async (uu) => { try { const r = await fetch(uu, { credentials: 'include', headers: { 'X-Requested-With': 'XMLHttpRequest' } }); return { status: r.status, body: await r.text() }; } catch (e) { return { __fetchError: String(e && e.message || e) }; } }, targetUrl), new Promise((_, rej) => setTimeout(() => rej(new Error(`cdpFetchPage timeout ${timeoutMs}ms`)), timeoutMs)), ]); if (result && result.__fetchError) { return { ok: false, error: `cdpFetchPage fetchErr: ${result.__fetchError.slice(0, 100)}` }; } const status = result && result.status; const body = result && result.body || ''; if (status >= 200 && status < 400) return { ok: true, status, body }; return { ok: false, status, body, error: `cdpFetchPage status ${status}` }; } catch (e) { return { ok: false, error: `cdpFetchPage: ${String(e.message || e).slice(0, 120)}` }; } } // CF challenge "์ง„ํ–‰ ์ค‘" ํŽ˜์ด์ง€๋งŒ ํŒ๋ณ„. ํ†ต๊ณผ ์งํ›„ ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ URL์— ๋ถ™๋Š” ํ† ํฐ // (__cf_chl_f_tk / __cf_chl_rt_tk)์€ "์ด๋ฏธ ํ†ต๊ณผํ•œ ํ”์ "์ด๋ผ challenge๊ฐ€ ์•„๋‹˜ โ€” ์ฝ˜ํ…์ธ  ํƒญ์œผ๋กœ ์ฑ„ํƒํ•ด์•ผ ํ•จ. // ์‹ค์ œ ์ง„ํ–‰ ์ค‘ challenge๋งŒ: /cdn-cgi/challenge ๊ฒฝ๋กœ, ๋˜๋Š” jschl/managed/captcha ํ† ํฐ. // (์ด์ „ ์ •๊ทœ์‹ /__cf_chl/์ด ํ†ต๊ณผ ํ›„ ํ† ํฐ๊นŒ์ง€ challenge๋กœ ์˜คํŒ โ†’ ๋ฉ€์ฉกํ•œ ํ†ต๊ณผ ํƒญ์„ ๋ฒ„๋ฆฌ๊ณ  // CF_PASS_NEEDED๋ฅผ ๋˜์ง€๋˜ ๋ฒ„๊ทธ โ€” 2026-07-01 ์ˆ˜์ •.) function isCfChallengeUrl(u) { return /\/cdn-cgi\/challenge|__cf_chl_(jschl|managed|captcha)_tk/i.test(u || ''); } // โ”€โ”€โ”€ raw CDP WebSocket fetch (2026-07-01) โ”€โ”€โ”€ // Playwright connectOverCDP๋Š” "์‚ฌ์šฉ์ž๊ฐ€ ์ง์ ‘ ์—ฐ ํƒญ"(cf ํ†ต๊ณผ ํƒญ)์„ contexts()[0].pages()์— ๋ˆ„๋ฝํ•˜๋Š” // ๋ฒ„๊ทธ๊ฐ€ ์žˆ์Œ(๋นˆ url ํŽ˜์ด์ง€ 1๊ฐœ๋งŒ ๋…ธ์ถœ + evaluate hang). ๊ทธ๋Ÿฌ๋‚˜ CDP HTTP `/json/list`์—๋Š” ํ†ต๊ณผ ํƒญ์ด // page ํƒ€์ž…์œผ๋กœ ์ •์ƒ ๋…ธ์ถœ๋˜๊ณ , ๊ทธ webSocketDebuggerUrl์— raw WS๋กœ ๋ถ™์œผ๋ฉด Runtime.evaluate(same-origin // fetch)๊ฐ€ ์™„๋ฒฝํžˆ ๋™์ž‘ํ•จ(์‹ค์ธก: status 200, ์ฝ˜ํ…์ธ  HTML). ๊ทธ๋ž˜์„œ ํ†ต๊ณผ ํƒญ same-origin fetch๋Š” ์ด ๊ฒฝ๋กœ๋กœ ํ•œ๋‹ค. const { ws: _CdpWS } = require('playwright-core/lib/utilsBundle'); function _cdpHttpJson(pathOnCdp) { return new Promise((resolve, reject) => { const u = new URL(pathOnCdp, LOCAL_CDP_URL); http.get(u, (r) => { let d = ''; r.on('data', c => d += c); r.on('end', () => { try { resolve(JSON.parse(d)); } catch (e) { reject(e); } }); }).on('error', reject); }); } // ํ†ต๊ณผ ํƒญ(challenge ์•„๋‹˜ + ์ฝ˜ํ…์ธ  ๊ฒฝ๋กœ)์„ /json/list์—์„œ ์ฐพ์•„ ๊ทธ WS๋กœ same-origin fetch. // ์„ฑ๊ณต: { ok, status, body }. ํ†ต๊ณผ ํƒญ ์—†์Œ: { ok:false, code:'CF_PASS_NEEDED' }. async function rawCdpFetch(domain, pathOnSite, timeoutMs = 15000) { let list; try { list = await _cdpHttpJson('/json/list'); } catch (e) { return { ok: false, error: `cdp /json/list: ${String(e.message || e).slice(0, 80)}` }; } const pages = (list || []).filter(t => t.type === 'page' && t.webSocketDebuggerUrl); const tab = pages.find(t => { try { const url = t.url || ''; if (isCfChallengeUrl(url)) return false; const pu = new URL(url); if (pu.hostname !== domain) return false; const p = pu.pathname; return p === '/' || p.startsWith('/index.php'); } catch { return false; } }); if (!tab) { const err = new Error(`cf-pass-needed: ${domain} ํ†ต๊ณผ ํƒญ ์—†์Œ โ€” CDP Chrome์—์„œ ์ง์ ‘ cf ํ†ต๊ณผ ํ•„์š”`); err.code = 'CF_PASS_NEEDED'; throw err; } const targetUrl = `https://${domain}${pathOnSite}`; return await new Promise((resolve) => { let done = false; const finish = (v) => { if (done) return; done = true; try { ws.close(); } catch {} resolve(v); }; const to = setTimeout(() => finish({ ok: false, error: `rawCdp timeout ${timeoutMs}ms` }), timeoutMs); let id = 0; const pending = new Map(); const send = (method, params = {}) => new Promise((res) => { const myId = ++id; pending.set(myId, res); ws.send(JSON.stringify({ id: myId, method, params })); }); const ws = new _CdpWS(tab.webSocketDebuggerUrl, [], { perMessageDeflate: false, maxPayload: 256 * 1024 * 1024 }); ws.on('message', (raw) => { let msg; try { msg = JSON.parse(raw.toString()); } catch { return; } if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } }); ws.on('error', (e) => { clearTimeout(to); finish({ ok: false, error: `rawCdp ws: ${String(e.message || e).slice(0, 80)}` }); }); ws.on('open', async () => { try { await send('Runtime.enable'); // โš ๏ธ X-Requested-With:XMLHttpRequest ํ—ค๋”๋ฅผ ๋ถ™์ด๋ฉด ์‚ฌ์ดํŠธ๊ฐ€ detail ํŽ˜์ด์ง€์— ๋‹ค๋ฅธ(ํšŒ์ฐจ ๋งํฌ ์—†๋Š”) // HTML์„ ๋ฐ˜ํ™˜ํ•จ โ€” ํ—ค๋” ์—†์ด ์ผ๋ฐ˜ navigation์ฒ˜๋Ÿผ ์š”์ฒญํ•ด์•ผ ์ •์ƒ detail HTML์„ ๋ฐ›๋Š”๋‹ค (2026-07-01). const expr = `(async()=>{try{const r=await fetch(${JSON.stringify(targetUrl)},{credentials:'include'});return {status:r.status, body:await r.text()};}catch(e){return {__fetchError:String(e&&e.message||e)};}})()`; const res = await send('Runtime.evaluate', { expression: expr, awaitPromise: true, returnByValue: true }); clearTimeout(to); const v = res && res.result && res.result.result && res.result.result.value; if (!v) return finish({ ok: false, error: `rawCdp no value${res && res.exceptionDetails ? ' (exc)' : ''}` }); if (v.__fetchError) return finish({ ok: false, error: `rawCdp fetchErr: ${String(v.__fetchError).slice(0, 100)}` }); if (v.status >= 200 && v.status < 300) return finish({ ok: true, status: v.status, body: v.body }); return finish({ ok: false, status: v.status, error: `rawCdp status ${v.status}` }); } catch (e) { clearTimeout(to); finish({ ok: false, error: `rawCdp eval: ${String(e.message || e).slice(0, 80)}` }); } }); }); } // โ”€โ”€โ”€ ๋งŒ๋ฃŒ๋œ ํ†ต๊ณผ ํƒญ ์ฆ‰์‹œ ์žฌํ†ต๊ณผ (2026-07-24) โ”€โ”€โ”€ // rawCdpFetch๊ฐ€ 403์„ ๋ฐ›๋Š” ์ƒํ™ฉ = ํ†ต๊ณผ ํƒญ์€ ์žˆ์œผ๋‚˜ cf_clearance/WAF ํ† ํฐ ๋งŒ๋ฃŒ. // ๊ทธ ํƒญ์„ ๊ทธ ์ž๋ฆฌ์—์„œ Page.reloadํ•˜๋ฉด ๋Œ€๊ฐœ challenge ์—†์ด ์žฌํ†ต๊ณผ๋˜์–ด ํ† ํฐ์ด ๊ฐฑ์‹ ๋จ(์‚ฌ์šฉ์ž ๊ฐœ์ž… ๋ถˆํ•„์š”). // keepAlivePassedTab๊ณผ ๋‹ฌ๋ฆฌ load ์™„๋ฃŒ๊นŒ์ง€ ๊ธฐ๋‹ค๋ฆฐ ๋’ค ๋ฐ˜ํ™˜ โ†’ ํ˜ธ์ถœ์ธก์ด ๊ณง๋ฐ”๋กœ ์žฌfetchํ•  ์ˆ˜ ์žˆ๊ฒŒ. // โš ๏ธ ํ†ต๊ณผ ํƒญ์ด ์—†์œผ๋ฉด(=CF_PASS_NEEDED ์ƒํ™ฉ) ์•„๋ฌด๊ฒƒ๋„ ์•ˆ ํ•จ(false ๋ฐ˜ํ™˜) โ€” ์–ต์ง€๋กœ ์ƒˆ ํƒญ/์ฐฝ ๋งŒ๋“ค์ง€ ์•Š์Œ. let _reloadPassInFlight = false; async function reloadPassedTabOnce(domain, timeoutMs = 14000) { if (!USE_LOCAL_CDP) return false; if (_reloadPassInFlight) return false; // ๋™์‹œ ์žฌํ†ต๊ณผ ์ค‘๋ณต ๋ฐฉ์ง€ (์žฌ์ƒ attempt๊ฐ€ 3์—ฐํƒ€๋กœ ์˜ด) _reloadPassInFlight = true; try { let list; try { list = await _cdpHttpJson('/json/list'); } catch { return false; } const tab = (list || []).filter(t => t.type === 'page' && t.webSocketDebuggerUrl).find(t => { try { const url = t.url || ''; if (isCfChallengeUrl(url)) return false; const pu = new URL(url); if (pu.hostname !== domain) return false; const p = pu.pathname; return p === '/' || p.startsWith('/index.php'); } catch { return false; } }); if (!tab) return false; // ํ†ต๊ณผ ํƒญ ์—†์Œ โ†’ CF_PASS_NEEDED ๊ฒฝ๋กœ๊ฐ€ ์ฒ˜๋ฆฌ return await new Promise((resolve) => { let done = false; const finish = (v) => { if (done) return; done = true; try { ws.close(); } catch {} resolve(v); }; const to = setTimeout(() => finish(false), timeoutMs); let id = 0; const ws = new _CdpWS(tab.webSocketDebuggerUrl, [], { perMessageDeflate: false, maxPayload: 8 * 1024 * 1024 }); ws.on('error', () => { clearTimeout(to); finish(false); }); ws.on('message', (raw) => { let msg; try { msg = JSON.parse(raw.toString()); } catch { return; } // load ์™„๋ฃŒ ์ด๋ฒคํŠธ๊ฐ€ ์˜ค๋ฉด ์žฌํ†ต๊ณผ ์„ฑ๊ณต์œผ๋กœ ๋ณด๊ณ  ์ข…๋ฃŒ(ํ† ํฐ ๊ฐฑ์‹ ๋จ). if (msg.method === 'Page.loadEventFired') { clearTimeout(to); finish(true); } }); ws.on('open', () => { try { ws.send(JSON.stringify({ id: ++id, method: 'Page.enable', params: {} })); ws.send(JSON.stringify({ id: ++id, method: 'Page.reload', params: {} })); } catch { clearTimeout(to); return finish(false); } }); }); } catch { return false; } finally { _reloadPassInFlight = false; } } // โ”€โ”€โ”€ cf/WAF ํ†ต๊ณผ ํƒญ keep-alive (2026-07-03) โ”€โ”€โ”€ // ์ฆ์ƒ: ์‹œ๊ฐ„์ด ์ง€๋‚˜๋ฉด ํ†ต๊ณผ ํƒญ์˜ cf_clearance/WAF ํ† ํฐ์ด ๋งŒ๋ฃŒ๋ผ fetch๊ฐ€ 202/challenge โ†’ ์žฌ์ƒ ์‹คํŒจ. // ์‚ฌ์šฉ์ž๊ฐ€ CDP Chrome์—์„œ ๊ทธ ํƒญ์„ ์ง์ ‘ ์ƒˆ๋กœ๊ณ ์นจ(์žฌํ†ต๊ณผ)ํ•ด์•ผ๋งŒ ๋‹ค์‹œ ๋จ. // ํ•ด๊ฒฐ: ์„œ๋ฒ„๊ฐ€ ์ฃผ๊ธฐ์ ์œผ๋กœ ํ˜„์žฌ ๋„๋ฉ”์ธ์˜ ํ†ต๊ณผ ํƒญ์„ **ํ™”๋ฉด ๋ฐ– ๊ทธ๋Œ€๋กœ ์กฐ์šฉํžˆ Page.reload** โ†’ ํ† ํฐ ์„ ์ œ ๊ฐฑ์‹ . // ์‹คํ—˜(2026-07-03)์—์„œ reload ํ›„์—๋„ ํ†ต๊ณผ ์œ ์ง€(challenge๋กœ ์•ˆ ํŠ•๊น€) ํ™•์ธ. // โš ๏ธ ๊ณผ๊ฑฐ ๋ฌดํ•œ ๊นœ๋นก์ž„ ์‚ฌ๊ณ (6a3dbdb) ์žฌ๋ฐœ ๋ฐฉ์ง€ ์›์น™: // - ์ด๋ฏธ ์กด์žฌํ•˜๋Š” ํ†ต๊ณผ ํƒญ๋งŒ reload. ์ƒˆ ํƒญ/์ƒˆ ์ฐฝ ์ƒ์„ฑยท์ฐฝ foregroundยท๋„๋ฉ”์ธ ์žฌํƒ์ƒ‰ ์ ˆ๋Œ€ ์•ˆ ํ•จ. // - ํ†ต๊ณผ ํƒญ์ด ์—†์œผ๋ฉด(=CF_PASS_NEEDED ์ƒํ™ฉ) ์•„๋ฌด๊ฒƒ๋„ ์•ˆ ํ•จ(์‚ฌ์šฉ์ž๊ฐ€ ์ง์ ‘ ํ†ต๊ณผํ•ด์•ผ ํ•จ โ€” ์–ต์ง€๋กœ ์•ˆ ๋งŒ๋“ฆ). // - in-flight ๊ฐ€๋“œ + ๋„‰๋„‰ํ•œ ์ฃผ๊ธฐ. ์‹คํŒจํ•ด๋„ ๋ฌดํ•ด(silent). let _keepAliveInFlight = false; async function keepAlivePassedTab() { if (!USE_LOCAL_CDP) return; if (_keepAliveInFlight) return; _keepAliveInFlight = true; try { // ํ˜„์žฌ ์ฑ„ํƒ ๋„๋ฉ”์ธ โ€” ์บ์‹œ(override/announce ๊ฒฐ๊ณผ)์—์„œ ์ฝ์Œ. ์—†์œผ๋ฉด skip. const cached = readCachePermanent('domain.json'); const domain = cached && (cached.domain || cached.announced); if (!domain) return; let list; try { list = await _cdpHttpJson('/json/list'); } catch { return; } // rawCdpFetch์™€ ๋™์ผํ•œ ํ†ต๊ณผ ํƒญ ํŒ์ •: ํ•ด๋‹น ๋„๋ฉ”์ธ + challenge ์•„๋‹˜ + (/ ๋˜๋Š” /index.php). const tab = (list || []).filter(t => t.type === 'page' && t.webSocketDebuggerUrl).find(t => { try { const url = t.url || ''; if (isCfChallengeUrl(url)) return false; const pu = new URL(url); if (pu.hostname !== domain) return false; const p = pu.pathname; return p === '/' || p.startsWith('/index.php'); } catch { return false; } }); if (!tab) return; // ํ†ต๊ณผ ํƒญ ์—†์Œ โ€” ์–ต์ง€๋กœ ๋งŒ๋“ค์ง€ ์•Š์Œ(์‚ฌ์šฉ์ž ํ†ต๊ณผ ๋Œ€๊ธฐ) // ํ†ต๊ณผ ํƒญ์„ ์กฐ์šฉํžˆ reload. Page.reload๋งŒ โ€” ์ฐฝ ์กฐ์ž‘ยทnavigate URL ๋ณ€๊ฒฝ ์—†์Œ. await new Promise((resolve) => { let done = false; const finish = () => { if (done) return; done = true; try { ws.close(); } catch {} resolve(); }; const to = setTimeout(finish, 12000); let id = 0; const ws = new _CdpWS(tab.webSocketDebuggerUrl, [], { perMessageDeflate: false, maxPayload: 8 * 1024 * 1024 }); ws.on('error', () => { clearTimeout(to); finish(); }); ws.on('open', () => { try { ws.send(JSON.stringify({ id: ++id, method: 'Page.reload', params: {} })); } catch { clearTimeout(to); return finish(); } // reload ๋ช…๋ น๋งŒ ๋ณด๋‚ด๊ณ  ์งง๊ฒŒ ๋Œ€๊ธฐ ํ›„ ์ข…๋ฃŒ(๋กœ๋“œ ์™„๋ฃŒ๊นŒ์ง€ ๋ถ™์–ด์žˆ์„ ํ•„์š” ์—†์Œ). setTimeout(() => { clearTimeout(to); finish(); }, 2500); }); }); console.log(`[keepalive] ${domain} ํ†ต๊ณผ ํƒญ reload (ํ† ํฐ ์„ ์ œ ๊ฐฑ์‹ )`); } catch (e) { // ๋ฌดํ•ด โ€” ๋‹ค์Œ ์ฃผ๊ธฐ์— ์žฌ์‹œ๋„ } finally { _keepAliveInFlight = false; } } // ensureCdpPage ์ง๋ ฌํ™” โ€” ๋™์‹œ ํ˜ธ์ถœ์—์„œ newPage/close race๋กœ ํƒญ leak + ํฌ์ปค์Šค ๋บ๊น€ ๋ฐœ์ƒํ–ˆ๋˜ ์‚ฌ๊ณ  ๋ฐฉ์ง€. let _ensureCdpPageLock = Promise.resolve(); function ensureCdpPage(domain) { const run = async () => { const browser = await getCdpBrowser(); // ์‚ฌ์šฉ์ž Chrome์˜ ๊ธฐ๋ณธ ์ปจํ…์ŠคํŠธ๋ฅผ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉ (cf_clearance ์ฟ ํ‚คยท๋กœ๊ทธ์ธ ์„ธ์…˜ ๋ณด์กด) const contexts = browser.contexts(); _cdpCtx = contexts[0] || await browser.newContext(); const targetUrl = `https://${domain}/robots.txt`; // ๊ฐ™์€ ๋„๋ฉ”์ธ์ด๊ณ  ํŽ˜์ด์ง€ ์‚ด์•„์žˆ์œผ๋ฉด ๊ทธ๋Œ€๋กœ ์žฌ์‚ฌ์šฉ โ€” ๋‹จ challenge/robots ํƒญ์ด๋ฉด ์žฌ์‚ฌ์šฉ ๊ธˆ์ง€ // (๊ทธ๋Ÿฐ ํƒญ์—์„œ fetchํ•˜๋ฉด challenge HTML๋งŒ ๋‚˜์˜ด. ์•„๋ž˜ P2 ํ†ต๊ณผํƒญ ํƒ์ƒ‰์œผ๋กœ ๋„˜๊น€). if (_cdpPage && !_cdpPage.isClosed() && _cdpPageDomain === domain) { try { const cur = _cdpPage.url(); const curHost = new URL(cur).hostname; const curIsChallenge = isCfChallengeUrl(cur); const curIsRobots = /\/robots\.txt(\?|$)/.test(cur); if (curHost === domain && !curIsChallenge && !curIsRobots) return _cdpPage; } catch {} } // (P2) ์‚ฌ์šฉ์ž๊ฐ€ ์ง์ ‘ cf๋ฅผ ํ†ต๊ณผ์‹œํ‚จ ๊ฐ™์€ ๋„๋ฉ”์ธ ์ฝ˜ํ…์ธ  ํƒญ์ด ์žˆ์œผ๋ฉด ๊ทธ๊ฑธ ์ฑ„ํƒ โ€” navigate ์•ˆ ํ•จ(challenge ํšŒํ”ผ). // tvchak.live๋Š” robots.txt์—๋„ cf challenge๊ฐ€ ๊ฑธ๋ ค, ์šฐ๋ฆฌ๊ฐ€ ์ƒˆ๋กœ navigateํ•˜๋ฉด challenge HTML๋งŒ ๋ฐ›์Œ. // ์‚ฌ์šฉ์ž ํ†ต๊ณผ ํƒญ(cf_clearance ๋ณด์œ , challenge ํ”์  ์—†๋Š” ์ฝ˜ํ…์ธ  ๊ฒฝ๋กœ)์—์„œ same-origin fetchํ•˜๋ฉด ์ •์ƒ. // โš ๏ธ ์ด ํƒญ์€ _cdpOwnedPages์— ๋„ฃ์ง€ ์•Š์Œ โ†’ ์ ˆ๋Œ€ close ์•ˆ ํ•จ(์‚ฌ์šฉ์ž ์†Œ์œ ). for (const pg of _cdpCtx.pages()) { try { if (_cdpOwnedPages.has(pg)) continue; // ์šฐ๋ฆฌ ํƒญ์€ ํ†ต๊ณผ ํ›„๋ณด ์•„๋‹˜ // โš ๏ธ pg.url()์€ attach ์‹œ์  ์ด๋ฏธ ์กด์žฌํ•˜๋˜ ์‚ฌ์šฉ์ž ํƒญ์— ๋Œ€ํ•ด ๋นˆ ๋ฌธ์ž์—ด์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ์Œ // (Playwright over CDP๊ฐ€ main frame URL์„ ๋ชป ์ฝ์Œ โ€” 2026-07-01 ์‚ฌ๊ณ ). // ๋น„์–ด ์žˆ์œผ๋ฉด ํŽ˜์ด์ง€ ์•ˆ์—์„œ location.href๋ฅผ ์ง์ ‘ ์ฝ์–ด ์‹ค์ œ URL์„ ์–ป๋Š”๋‹ค. let u = pg.url(); if (!u || u === 'about:blank') { // pg.url()์ด ๋นˆ ๊ฒฝ์šฐ location.href๋ฅผ ์ฝ๋˜, ๋นˆ url ํŽ˜์ด์ง€(omnibox ๋“ฑ)์—์„œ evaluate๊ฐ€ hangํ•˜๋ฏ€๋กœ ํƒ€์ž„์•„์›ƒ. try { u = await Promise.race([pg.evaluate(() => location.href), new Promise((_, r) => setTimeout(() => r(new Error('to')), 2000))]); } catch {} } if (!u) continue; const h = new URL(u).hostname; const path = new URL(u).pathname; const isChallenge = isCfChallengeUrl(u); const isRobots = /\/robots\.txt(\?|$)/.test(u); // ์ฝ˜ํ…์ธ  ๊ฒฝ๋กœ = ๋ฃจํŠธ(/) ๋˜๋Š” /index.php... ์‚ฌ์šฉ์ž๊ฐ€ cf ํ†ต๊ณผ์‹œํ‚จ ๋ฉ”์ธ/์ƒ์„ธ/์žฌ์ƒ ํƒญ. const isContentPath = path === '/' || path.startsWith('/index.php'); if (h === domain && !isChallenge && !isRobots && isContentPath) { _cdpPage = pg; _cdpPageDomain = domain; return _cdpPage; } } catch {} } // ์šฐ๋ฆฌ๊ฐ€ ๋งŒ๋“  ํƒญ ์ •๋ฆฌ (ํƒญ ๋ˆ„์  ๋ฐฉ์ง€). _cdpOwnedPages๋กœ ์šฐ๋ฆฌ ์†Œ์œ ๋งŒ ๊ณจ๋ผ close โ†’ ์‚ฌ์šฉ์ž ํƒญ์€ ์ ˆ๋Œ€ ์•ˆ ๋‹ซ์Œ. // ์žฌ์—ฐ๊ฒฐ ์งํ›„์—” WeakSet์ด ๋น„์–ด ์žˆ์œผ๋ฏ€๋กœ, robots.txt ํŒจํ„ด(flat ๋„๋ฉ”์ธ ํฌํ•จ)๋„ ๋ณด์กฐ๋กœ stale ํŒ์ •. const stalePages = []; const robotsRe = /^https:\/\/(tvchak\d+\.com|tvchak\.(live|net|cc|me|tv|io)|tvchak\.org)\/robots\.txt/; for (const pg of _cdpCtx.pages()) { try { const u = pg.url(); if (u === targetUrl && _cdpOwnedPages.has(pg)) { // ์šฐ๋ฆฌ๊ฐ€ ๋งŒ๋“ , ์ •ํ™•ํžˆ ์ผ์น˜ํ•˜๋Š” robots.txt ํƒญ โ†’ ์žฌ์‚ฌ์šฉ _cdpPage = pg; _cdpPageDomain = domain; return _cdpPage; } if (pg === _cdpPage) continue; // ์šฐ๋ฆฌ ์†Œ์œ  ํƒญ์ด๊ฑฐ๋‚˜(URL ๋ฌด๊ด€ โ€” challenge๋กœ redirect๋์–ด๋„ ํšŒ์ˆ˜), ์ž”์กด robots.txt ํƒญ์ด๋ฉด stale. if (_cdpOwnedPages.has(pg) || robotsRe.test(u)) stalePages.push(pg); } catch {} } // challenge๊ฐ€ robots.txt๊นŒ์ง€ ๊ฑธ๋ฆฐ ๋„๋ฉ”์ธ(tvchak.live ๋“ฑ flat)์€ ์šฐ๋ฆฌ๊ฐ€ navigateํ•ด๋ด์•ผ // "Just a moment" challenge HTML๋งŒ ๋ฐ›๊ณ , ๊ทธ navigate๊ฐ€ ๋ฉ€์ฉกํ•œ ํ†ต๊ณผ ํƒญ์„ ๋ฎ์–ด์“ฐ๊ฑฐ๋‚˜ // ECONNRESET์„ ์œ ๋ฐœํ•จ(2026-06-30 ์‚ฌ๊ณ ). ํ†ต๊ณผ ์ฝ˜ํ…์ธ  ํƒญ์„ ์œ„์—์„œ ๋ชป ์ฐพ์•˜๋‹ค๋ฉด, navigate ํด๋ฐฑ์„ // ํƒ€์ง€ ๋ง๊ณ  ๋ช…ํ™•ํ•œ ์—๋Ÿฌ๋ฅผ ๋˜์ ธ ํ˜ธ์ถœ์ธก์ด "์‚ฌ์šฉ์ž cf ํ†ต๊ณผ ํ•„์š”"๋กœ ์ฒ˜๋ฆฌํ•˜๊ฒŒ ํ•œ๋‹ค. // (๋ฒˆํ˜ธ ๋„๋ฉ”์ธ tvchakNNN.com์€ robots.txt๊ฐ€ ํ†ต๊ณผ๋˜๋ฏ€๋กœ ๊ธฐ์กด navigate ํด๋ฐฑ ์œ ์ง€.) const isChallengeOnlyDomain = /^tvchak\.(live|net|cc|me|tv|io)$/.test(domain); if (isChallengeOnlyDomain) { _cdpPage = null; _cdpPageDomain = null; const err = new Error(`cf-pass-needed: ${domain} ํ†ต๊ณผ ํƒญ ์—†์Œ โ€” CDP Chrome์—์„œ ์ง์ ‘ cf ํ†ต๊ณผ ํ•„์š”`); err.code = 'CF_PASS_NEEDED'; throw err; } // ๊ธฐ์กด _cdpPage๊ฐ€ ์‚ด์•„์žˆ์œผ๋ฉด close ์—†์ด ๊ทธ๋Œ€๋กœ navigate (ํƒญ ๊ฐ์ฒด ์žฌ์‚ฌ์šฉ โ†’ newPage ์•ˆ ํ•จ โ†’ ํฌ์ปค์Šค ์˜ํ–ฅ ์—†์Œ). if (_cdpPage && !_cdpPage.isClosed()) { await _cdpPage.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 15000 }).catch(() => {}); // navigate๊ฐ€ Chrome ์ฐฝ์„ ๋‹ค์‹œ ํ™œ์„ฑํ™”์‹œํ‚ฌ ์ˆ˜ ์žˆ์œผ๋‹ˆ await์œผ๋กœ minimize ๋๊นŒ์ง€ ๋ณด์žฅ. await minimizeCdpChromeWindow(); } else { // ์ •๋ง ์ƒˆ๋กœ ๋งŒ๋“ค์–ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ๋งŒ newPage (๋ถ€ํŒ… ํ›„ ์ฒ˜์Œ 1ํšŒ๋งŒ ๋ฐœ์ƒ) _cdpPage = await _cdpCtx.newPage(); _cdpOwnedPages.add(_cdpPage); // ์šฐ๋ฆฌ ์†Œ์œ ๋กœ ํ‘œ์‹œ โ†’ ์ดํ›„ stale cleanup ๋Œ€์ƒ // newPage๊ฐ€ ์ฐฝ ํ™œ์„ฑํ™”์‹œํ‚ฌ ์ˆ˜ ์žˆ์œผ๋‹ˆ ์ฆ‰์‹œ ๊ฐ•์ œ ์ตœ์†Œํ™” (ํฌ์ปค์Šค ์•ˆ ๋บ์Œ). await์œผ๋กœ ๋ณด์žฅ. await minimizeCdpChromeWindow(); await _cdpPage.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 15000 }).catch(() => {}); // navigate ํ›„์—๋„ ํ•œ ๋ฒˆ ๋” minimize (์•ˆ์ „๋ง). await minimizeCdpChromeWindow(); } _cdpPageDomain = domain; // stale ํƒญ cleanup์€ navigate๊ฐ€ ๋๋‚œ ๋’ค์— (close๊ฐ€ active ํƒญ ๋ณ€๊ฒฝ ํŠธ๋ฆฌ๊ฑฐํ•  ์ˆ˜ ์žˆ์–ด ๋งˆ์ง€๋ง‰์—). // _cdpOwnedPages ๊ธฐ๋ฐ˜์ด๋ผ ์‚ฌ์šฉ์ž ํ†ต๊ณผ ํƒญ์€ ์—ฌ๊ธฐ ์•ˆ ๋“ค์–ด์˜ด โ†’ ํ•ญ์ƒ ์šฐ๋ฆฌ ํƒญ๋งŒ ์ตœ๋Œ€ 1๊ฐœ๋กœ ์ˆ˜๋ ด. // โš ๏ธ(2026-07-08) ๋งˆ์ง€๋ง‰ page๋ฅผ closeํ•˜๋ฉด CDP ํฌ๋กฌ ์ฐฝ์ด ์‚ฌ๋ผ์ง(window handle ์†Œ๋ฉธ) โ†’ ์‚ฌ์šฉ์ž๊ฐ€ // ์ฐฝ์„ ๋ชป ๋ด„. ๊ทธ๋ž˜์„œ close ํ›„ ๋‚จ๋Š” page๊ฐ€ ์ตœ์†Œ 1๊ฐœ๋Š” ๋˜๋„๋ก ๋ณด์žฅ(ํ˜„์žฌ _cdpPage๋Š” ์œ ์ง€๋˜๋ฏ€๋กœ // stalePages๋งŒ ๋‹ซ์œผ๋ฉด ๋จ. ํ˜น์‹œ ์ปจํ…์ŠคํŠธ์— page๊ฐ€ stale+ํ˜„์žฌ ํ•ฉ์ณ ๋”ฑ ๊ทธ๋งŒํผ์ด๋ฉด ํ•˜๋‚˜๋Š” ๋‚จ๊ธด๋‹ค). const totalPages = _cdpCtx.pages().length; let closable = stalePages.length; if (totalPages - closable < 1) closable = Math.max(0, totalPages - 1); // ์ตœ์†Œ 1๊ฐœ ์ฐฝ ์œ ์ง€ for (let i = 0; i < closable; i++) { try { await stalePages[i].close(); } catch {} } return _cdpPage; }; _ensureCdpPageLock = _ensureCdpPageLock.then(run, run); return _ensureCdpPageLock; } // Playwright ensureCdpPage(navigate) ๊ธฐ๋ฐ˜ same-origin fetch. // ๋ฒˆํ˜ธ ๋„๋ฉ”์ธ(tvchakNNN.com)์€ robots.txt๊ฐ€ cf ํ†ต๊ณผ๋˜๋ฏ€๋กœ ์šฐ๋ฆฌ๊ฐ€ navigateํ•ด์„œ ์ž๋™ ํ†ต๊ณผ ๊ฐ€๋Šฅ โ†’ // ์ด ๊ฒฝ๋กœ๊ฐ€ ์ •์ƒ ๋™์ž‘. flat ๋„๋ฉ”์ธ(.live)์€ ensureCdpPage๊ฐ€ CF_PASS_NEEDED๋ฅผ ๋˜์ง. async function tvFetchCDPViaPage(domain, pathOnSite) { const TV_FETCH_TIMEOUT_MS = 15000; try { const page = await ensureCdpPage(domain); const pageUrl = page.url(); if (!pageUrl.includes(domain)) { _cdpPage = null; _cdpPageDomain = null; return { ok: false, error: `cdp page url not on domain: ${pageUrl.slice(0, 60)}` }; } const targetUrl = `https://${domain}${pathOnSite}`; const result = await Promise.race([ page.evaluate(async (u) => { try { const r = await fetch(u, { credentials: 'include' }); return { status: r.status, body: await r.text() }; } catch (e) { return { __fetchError: String(e && e.message || e) }; } }, targetUrl), new Promise((_, rej) => setTimeout(() => rej(new Error(`cdp tvFetch ${pathOnSite} timeout ${TV_FETCH_TIMEOUT_MS}ms`)), TV_FETCH_TIMEOUT_MS)), ]); if (result && result.__fetchError) return { ok: false, error: `cdp fetchErr: ${result.__fetchError.slice(0, 100)}` }; if (result && result.status >= 200 && result.status < 300) return { ok: true, status: result.status, body: result.body }; return { ok: false, status: result && result.status, error: `cdp status ${result && result.status}` }; } catch (e) { if (e && e.code === 'CF_PASS_NEEDED') return { ok: false, code: 'CF_PASS_NEEDED', error: e.message }; _cdpBrowser = null; _cdpCtx = null; _cdpPage = null; _cdpPageDomain = null; return { ok: false, error: `cdp: ${String(e.message || e).slice(0, 120)}` }; } } async function tvFetchCDP(domain, pathOnSite) { // raw CDP WS ๊ฒฝ๋กœ ์šฐ์„  โ€” ์‚ฌ์šฉ์ž๊ฐ€ ์ง์ ‘ cf ํ†ต๊ณผ์‹œํ‚จ ํƒญ์„ /json/list์—์„œ ์ฐพ์•„ same-origin fetch. // (Playwright connectOverCDP๊ฐ€ ๊ทธ๋Ÿฐ ํƒญ์„ ๋ˆ„๋ฝํ•˜๋Š” ๋ฒ„๊ทธ ์šฐํšŒ โ€” 2026-07-01.) flat ๋„๋ฉ”์ธ(.live)์€ ์ด ๊ฒฝ๋กœ. const isFlat = /^tvchak\.(live|net|cc|me|tv|io)$/.test(domain); try { const r = await rawCdpFetch(domain, pathOnSite, 15000); if (r.ok) return r; // flat ๋„๋ฉ”์ธ์—์„œ ํ†ต๊ณผ ํƒญ์ด 403/503/202(challenge)๋ฅผ ๋ฐ›์œผ๋ฉด = ๊ทธ ํƒญ ํ† ํฐ ๋งŒ๋ฃŒ. NAS/Playwright๋กœ // ํด๋ฐฑํ•ด๋ด์•ผ KT SNI+WAF๋กœ ๋‹ค ๋ง‰ํžˆ๋ฏ€๋กœ("all paths failed") ๋ฌด์˜๋ฏธ. ๋Œ€์‹  ๊ทธ ํƒญ์„ ์ฆ‰์‹œ ์žฌํ†ต๊ณผ(reload) // ์‹œ์ผœ ํ† ํฐ์„ ๊ฐฑ์‹ ํ•˜๊ณ  1ํšŒ ์žฌfetch โ€” ์‚ฌ์šฉ์ž๊ฐ€ ์ˆ˜๋™์œผ๋กœ CDP ๊ฐฑ์‹ ํ•˜๋˜ ๊ฑธ ์ž๋™ํ™” (2026-07-24). if (isFlat && typeof r.status === 'number' && [403, 503, 202, 429].includes(r.status)) { const revived = await reloadPassedTabOnce(domain); if (revived) { const r2 = await rawCdpFetch(domain, pathOnSite, 15000); if (r2.ok) { console.log(`[cdp] ${domain} ํ†ต๊ณผ ํƒญ ํ† ํฐ ๋งŒ๋ฃŒ โ†’ ์ž๋™ ์žฌํ†ต๊ณผ ์„ฑ๊ณต`); return r2; } } // ์žฌํ†ต๊ณผ ์‹คํŒจ โ†’ ์‚ฌ์šฉ์ž์—๊ฒŒ ์ˆ˜๋™ ํ†ต๊ณผ ์‹ ํ˜ธ(์ฐฝ ๋…ธ์ถœ) + ํด๋ฐฑ ์ƒ๋žต(CF_PASS_NEEDED๋กœ ์Šน๊ฒฉ). console.warn(`[cdp] ${domain} ํ†ต๊ณผ ํƒญ ํ† ํฐ ๋งŒ๋ฃŒ(status ${r.status}) โ€” ์ž๋™ ์žฌํ†ต๊ณผ ์‹คํŒจ, ์ˆ˜๋™ ํ†ต๊ณผ ์š”์ฒญ`); revealCdpChromeForChallenge(); return { ok: false, code: 'CF_PASS_NEEDED', error: `passed-tab token expired (status ${r.status})` }; } // raw WS๊ฐ€ fetch๋Š” ํ–ˆ์œผ๋‚˜ ๋น„์ •์ƒ ์‘๋‹ต โ†’ ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜(ํด๋ฐฑํ•ด๋„ ๊ฐ™์€ ์ฐจ๋‹จ). return r; } catch (e) { // ํ†ต๊ณผ ํƒญ ์—†์Œ(CF_PASS_NEEDED) โ†’ ๋ฒˆํ˜ธ ๋„๋ฉ”์ธ์ด๋ฉด Playwright navigate๋กœ ์ž๋™ ํ†ต๊ณผ ์‹œ๋„. // flat ๋„๋ฉ”์ธ์€ navigateํ•ด๋„ challenge๋งŒ ๋ฐ›์œผ๋ฏ€๋กœ ํด๋ฐฑ ์•ˆ ํ•˜๊ณ  CF_PASS_NEEDED ์ „ํŒŒ. if (e && e.code === 'CF_PASS_NEEDED') { const isNumbered = /^tvchak\d+\.com$/.test(domain); if (isNumbered) return await tvFetchCDPViaPage(domain, pathOnSite); // flat ๋„๋ฉ”์ธ์€ ์‚ฌ์šฉ์ž๊ฐ€ ์ง์ ‘ ๋ด‡ ํ•ด์ œ๋ฅผ ํ•ด์ค˜์•ผ ํ•จ โ†’ ์ฐฝ์„ ํ™”๋ฉด์— ๋„์šด๋‹ค(์ฟจ๋‹ค์šด ๋‚ด์žฅ, 1ํšŒ์„ฑ). revealCdpChromeForChallenge(); return { ok: false, code: 'CF_PASS_NEEDED', error: e.message }; } return { ok: false, error: `cdp: ${String(e.message || e).slice(0, 120)}` }; } } async function tvFetch(domain, pathOnSite) { const fullUrl = `https://${domain}${pathOnSite}`; // 0์ฐจ: ๋กœ์ปฌ CDP(์‚ฌ์šฉ์ž Chrome) โ€” USE_LOCAL_CDP=1์ผ ๋•Œ๋งŒ. KT SNI ์ฐจ๋‹จ ์šฐํšŒ์šฉ. // 9222 ๋ฏธ์˜คํ”ˆ์ด๋ฉด ๋น ๋ฅด๊ฒŒ ์‹คํŒจ โ†’ NAS ํด๋ฐฑ. if (USE_LOCAL_CDP) { const r = await tvFetchCDP(domain, pathOnSite); if (r.ok) return r; // CF ํ†ต๊ณผ ํ•„์š”๋Š” NAS/Playwright๋กœ๋„ ๋ชป ๋šซ์Œ(.live challenge + KT SNI). ํด๋ฐฑ ์ƒ๋žตํ•˜๊ณ  ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜. if (r.code === 'CF_PASS_NEEDED') return r; console.warn('[tvFetch] cdp failed, falling back:', r.error); } // 1์ฐจ: NAS fetch ํ”„๋ก์‹œ (๊ฐ€์žฅ ๋น ๋ฅด๊ณ  ์•ˆ์ •์  โ€” NAS ๋กœ์ปฌ์—์„œ ์ง์ ‘ ํ˜ธ์ถœ). 2ํšŒ๊นŒ์ง€ ๋น ๋ฅธ ์žฌ์‹œ๋„. for (let attempt = 0; attempt < 2; attempt++) { const r = await nasFetch(fullUrl); if (r.ok) return r; // ํ”„๋ก์‹œ ์ž์ฒด๊ฐ€ ์ฃฝ์—ˆ๊ฑฐ๋‚˜(conn ์—๋Ÿฌ) status 0์ด๋ฉด Playwright ํด๋ฐฑ์œผ๋กœ. ๊ทธ ์™ธ(์ฐจ๋‹จ ๋“ฑ)๋Š” ์žฌ์‹œ๋„. if (/proxy conn|proxy timeout|proxy parse/.test(r.error || '')) break; } // 2์ฐจ: ๊ธฐ์กด Playwright(SOCKS5) ๊ฒฝ๋กœ ํด๋ฐฑ โ€” ํ”„๋ก์‹œ ๋ถˆ๊ฐ€ ์‹œ์—๋งŒ. return tvFetchPlaywright(domain, pathOnSite); } async function tvFetchPlaywright(domain, pathOnSite) { return withTvMutex(async () => { const TV_FETCH_TIMEOUT_MS = 15000; const trace = []; // ๋ฉ”์ธ ํŽ˜์ด์ง€๋กœ ํ•œ ๋ฒˆ ์›Œ๋ฐ์—…ํ•ด Cloudflare ์ฟ ํ‚ค๋ฅผ ์ปจํ…์ŠคํŠธ์— ์ฑ„์›€ (ํŽ˜์ด์ง€๊ฐ€ ๊ด‘๊ณ ๋กœ ํŠ•๊ฒจ๋„ ์ฟ ํ‚ค๋Š” ์ปจํ…์ŠคํŠธ์— ๋‚จ์Œ). try { await ensureTvPage(domain); } catch (e) { trace.push(`warmup=err:${String(e.message || e).slice(0, 80)}`); } // 1์ฐจ: context.request โ€” ํŽ˜์ด์ง€ navigation ์˜ํ–ฅ ์—†์Œ. tvchak๊ฐ€ ์šฐ๋ฆฌ IP๋ฅผ 403 ์ฐจ๋‹จ ์‹œ์ž‘ํ–ˆ์œผ๋ฉด ํ†ต๊ณผ ์•ˆ ๋จ. for (let attempt = 0; attempt < 2; attempt++) { try { const ctx = await getTvContext(); const url = `https://${domain}${pathOnSite}`; const resp = await ctx.request.get(url, { timeout: TV_FETCH_TIMEOUT_MS, headers: { 'Referer': `https://${domain}/`, 'X-Requested-With': 'XMLHttpRequest', }, }); const status = resp.status(); const body = await resp.text(); // 200์ด๋ฉด ์ฆ‰์‹œ ์„ฑ๊ณต. 403/503 ๊ฐ™์€ ์ฐจ๋‹จ/์ฑŒ๋ฆฐ์ง€ ์‘๋‹ต์€ evaluate fallback์œผ๋กœ ๋„˜๊น€. if (status >= 200 && status < 300) { if (trace.length) console.warn('[tvFetch] ok via context.request, prior trace:', trace.join(' | ')); return { ok: true, status, body }; } trace.push(`ctx#${attempt}=status${status}`); } catch (e) { trace.push(`ctx#${attempt}=err:${String(e.message || e).slice(0, 120)}`); } } // 2์ฐจ fallback: same-origin ํŽ˜์ด์ง€(robots.txt)์—์„œ evaluate(fetch). for (let attempt = 0; attempt < 2; attempt++) { let page; try { page = await ensureTvFetchPage(domain); } catch (e) { trace.push(`fetchpage#${attempt}=err:${String(e.message || e).slice(0, 80)}`); continue; } // ์ง„๋‹จ: ํ˜„์žฌ ํŽ˜์ด์ง€๊ฐ€ ์ง„์งœ tvchak ๋„๋ฉ”์ธ์ธ์ง€ ํ™•์ธ let pageUrl = ''; try { pageUrl = page.url(); } catch {} if (!pageUrl.includes(domain)) { trace.push(`eval#${attempt}=pageUrl-not-domain:${pageUrl.slice(0, 60)}`); _tvFetchPage = null; _tvFetchPageDomain = null; if (attempt === 1) { return { ok: false, error: `all paths failed: ${trace.join(' | ')}` }; } continue; } let timedOut = false; const targetUrl = `https://${domain}${pathOnSite}`; const evalPromise = page.evaluate(async (u) => { try { const r = await fetch(u, { credentials: 'include', headers: { 'X-Requested-With': 'XMLHttpRequest' } }); return { status: r.status, body: await r.text() }; } catch (e) { // origin / fetch ์‹คํŒจ ์ •ํ™•ํžˆ ์žก๊ธฐ return { __fetchError: String(e && e.message || e), __pageUrl: location.href }; } }, targetUrl); const timeoutPromise = new Promise((_, rej) => setTimeout(() => { timedOut = true; try { if (_tvFetchPage && !_tvFetchPage.isClosed()) _tvFetchPage.close().catch(() => {}); } catch {} rej(new Error(`tvFetch ${pathOnSite} timeout ${TV_FETCH_TIMEOUT_MS}ms`)); }, TV_FETCH_TIMEOUT_MS)); try { const result = await Promise.race([evalPromise, timeoutPromise]); if (result && result.__fetchError) { trace.push(`eval#${attempt}=fetchErr:${result.__fetchError.slice(0, 80)} pg:${(result.__pageUrl || '').slice(0, 60)}`); _tvFetchPage = null; _tvFetchPageDomain = null; if (attempt === 1) { console.warn('[tvFetch] all paths failed:', trace.join(' | ')); return { ok: false, error: `all paths failed: ${trace.join(' | ')}` }; } continue; } if (trace.length) console.warn('[tvFetch] ok via evaluate(fetchPage), prior trace:', trace.join(' | ')); return { ok: true, ...result }; } catch (e) { trace.push(`eval#${attempt}=err:${String(e.message || e).slice(0, 120)}`); if (!timedOut) { try { if (_tvFetchPage) await _tvFetchPage.close().catch(() => {}); } catch {} } _tvFetchPage = null; _tvFetchPageDomain = null; if (attempt === 1) { console.warn('[tvFetch] all paths failed:', trace.join(' | ')); return { ok: false, error: `all paths failed: ${trace.join(' | ')}` }; } } } }); } // โ”€โ”€โ”€โ”€โ”€ anilife provider โ”€โ”€โ”€โ”€โ”€ // API ํ˜ธ์ถœ์— x-device-token / x-build-id / x-anilife-referer / cookie(_csrf)๊ฐ€ ํ•„์š”. // ๋ฉ”์ธ ํŽ˜์ด์ง€๋ฅผ ๋„์›Œ๋‘๊ณ  page.evaluate(fetch) ๋กœ ํ˜ธ์ถœ โ†’ ํ—ค๋”/์ฟ ํ‚ค ์ž๋™ ์ฑ„์›Œ์ง. let _aniBrowser = null; let _aniCtx = null; let _aniPage = null; // anilife ์ „์šฉ Chromium ์ธ์Šคํ„ด์Šค โ€” tvchak ๋ธŒ๋ผ์šฐ์ €์™€ ์™„์ „ ๋ถ„๋ฆฌ. // anilife๊ฐ€ ์ข€๋น„/hang ๋˜์–ด๋„ tvchak์— ์˜ํ–ฅ ์—†๊ฒŒ ๊ฒฉ๋ฆฌ. async function getAniBrowser() { if (_aniBrowser) return _aniBrowser; const launchOpts = { headless: true, args: [ '--disable-blink-features=AutomationControlled', '--disable-features=IsolateOrigins,site-per-process', '--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu', '--no-zygote', '--disable-extensions', '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows', '--memory-pressure-off', '--js-flags=--max-old-space-size=128', ], }; if (PROXY_SERVER) launchOpts.proxy = { server: PROXY_SERVER }; _aniBrowser = await chromium.launch(launchOpts); console.log('[ani] dedicated browser launched (separate from tvchak)'); return _aniBrowser; } async function getAniContext() { if (_aniCtx) return _aniCtx; const browser = await getAniBrowser(); _aniCtx = await browser.newContext({ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', locale: 'ko-KR', viewport: { width: 1280, height: 800 }, extraHTTPHeaders: { 'Accept-Language': 'ko-KR,ko;q=0.9,en-US;q=0.8' }, }); // anilife ์ปจํ…์ŠคํŠธ๋Š” ์ด๋ฏธ์ง€/CSS๋„ ๋ฐ›์•„์•ผ ํŽ˜์ด์ง€๊ฐ€ ์ •์ƒ ๋กœ๋“œ๋จ. ๊ด‘๊ณ /ํŠธ๋ž˜์ปค๋งŒ ์ฐจ๋‹จ. await _aniCtx.route('**/*', (route) => { const req = route.request(); const u = req.url(); const type = req.resourceType(); if (/google-analytics|googletagmanager|gtag|clarity\.ms|doubleclick|adsense\/banners/i.test(u)) return route.abort(); if (type === 'media') return route.abort(); // ์˜์ƒ ์„ธ๊ทธ๋จผํŠธ๋Š” ์„œ๋ฒ„๊ฐ€ ์ง์ ‘ ์•ˆ ๊ฐ€์ ธ์˜ด return route.continue(); }); await _aniCtx.addInitScript(() => { Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); }); return _aniCtx; } // anilife ์ปจํ…์ŠคํŠธยท๋ธŒ๋ผ์šฐ์ € ๊ฐ•์ œ ํ๊ธฐ (์ข€๋น„ ํšŒ๋ณต / ์ฐจ๋‹จ ํ›„ fresh start). async function resetAniIsolated() { try { if (_aniPage && !_aniPage.isClosed()) await _aniPage.close().catch(() => {}); } catch {} _aniPage = null; try { if (_aniCtx) await _aniCtx.close().catch(() => {}); } catch {} _aniCtx = null; try { if (_aniBrowser) await _aniBrowser.close().catch(() => {}); } catch {} _aniBrowser = null; console.log('[ani] isolated reset (browser/context/page recycled)'); } async function ensureAniPage() { if (_aniPage && !_aniPage.isClosed()) { try { const u = _aniPage.url(); if (!u.includes('anilife.app')) { await _aniPage.goto('https://anilife.app/', { waitUntil: 'domcontentloaded', timeout: 15000 }); } } catch {} return _aniPage; } const ctx = await getAniContext(); const page = await ctx.newPage(); // ๋กœ์ปฌ ๋ณ€์ˆ˜๋กœ ์žก์•„๋‘๊ธฐ โ€” ์™ธ๋ถ€์—์„œ _aniPage = null๋กœ ๋งŒ๋“ค์–ด๋„ ์˜ํ–ฅ X _aniPage = page; page.on('popup', (p) => p.close().catch(() => {})); try { await page.goto('https://anilife.app/', { waitUntil: 'domcontentloaded', timeout: 15000 }); // ํŽ˜์ด์ง€๊ฐ€ ๊ทธ ์‚ฌ์ด ๋‹ซํ˜”๊ฑฐ๋‚˜ ์™ธ๋ถ€์—์„œ reset๋์œผ๋ฉด ์•ˆ์ „ํ•˜๊ฒŒ ์ข…๋ฃŒ if (page.isClosed()) throw new Error('page closed during init'); // SPA๊ฐ€ csrf ํ† ํฐ/๋””๋ฐ”์ด์Šค ํ† ํฐ ์ดˆ๊ธฐํ™”ํ•˜๋„๋ก ์ž ์‹œ ๋Œ€๊ธฐ await page.waitForTimeout(1500); } catch (e) { console.warn('aniPage initial nav:', e.message); // ํŽ˜์ด์ง€ ์ง„์ž… ์‹คํŒจ ์‹œ ์ •๋ฆฌ. _aniPage๊ฐ€ ๋‹ค๋ฅธ ํŽ˜์ด์ง€๋กœ ๋ฐ”๋€Œ์—ˆ์œผ๋ฉด ๊ทธ๊ฑด ๊ฑด๋“œ๋ฆฌ์ง€ ์•Š์Œ try { if (!page.isClosed()) await page.close().catch(() => {}); } catch {} if (_aniPage === page) _aniPage = null; throw e; } return page; } // โ”€โ”€โ”€โ”€โ”€ anilife circuit breaker โ”€โ”€โ”€โ”€โ”€ // ์—ฐ์† ์‹คํŒจ NํšŒ ์‹œ ์ผ์ • ์‹œ๊ฐ„ ์ฐจ๋‹จ โ†’ tvchak/ํ‚ค๋…ธ๋ผ์ด์ธ  ๋“ฑ ๋‹ค๋ฅธ API์— ์˜ํ–ฅ ์•ˆ ๊ฐ€๊ฒŒ. const ANI_BREAKER = { failures: 0, failuresMax: 3, openUntil: 0, // timestamp until which breaker is open (block calls) cooldownMs: 30 * 60 * 1000, // 30๋ถ„ }; function aniBreakerIsOpen() { if (Date.now() < ANI_BREAKER.openUntil) return true; return false; } function aniBreakerRecordSuccess() { ANI_BREAKER.failures = 0; ANI_BREAKER.openUntil = 0; } function aniBreakerRecordFailure() { ANI_BREAKER.failures++; if (ANI_BREAKER.failures >= ANI_BREAKER.failuresMax) { ANI_BREAKER.openUntil = Date.now() + ANI_BREAKER.cooldownMs; console.warn(`[ani-breaker] OPEN until ${new Date(ANI_BREAKER.openUntil).toISOString()} (${ANI_BREAKER.failures} consecutive failures)`); // anilife ๊ฒฉ๋ฆฌ ํ™˜๊ฒฝ ์ „์ฒด ํ๊ธฐ (page๋งŒ์ด ์•„๋‹ˆ๋ผ browser๊นŒ์ง€) โ€” ์ข€๋น„ ๋ˆ„์  ๋ฐฉ์ง€ // tvchak์€ ๋ณ„๋„ ๋ธŒ๋ผ์šฐ์ €๋ผ ์˜ํ–ฅ ์—†์Œ if (typeof resetAniIsolated === 'function') resetAniIsolated().catch(() => {}); } } // Promise + ๊ฐ•์ œ timeout function withTimeout(promise, ms, label) { return Promise.race([ promise, new Promise((_, reject) => setTimeout(() => reject(new Error(`${label} timeout ${ms}ms`)), ms)), ]); } // anilife API ํ˜ธ์ถœ. // ์‘๋‹ต์ด ํ•ญ์ƒ zstd ์••์ถ•์ด๋ผ ํŽ˜์ด์ง€์—์„œ raw bytes๋ฅผ base64๋กœ ๋ฐ›์•„ Node์—์„œ zstd ๋””์ฝ”๋”ฉํ•œ๋‹ค. // (๋ธŒ๋ผ์šฐ์ € fetch๋Š” content-encoding ํ—ค๋”๊ฐ€ ์‘๋‹ต์— ๋…ธ์ถœ๋ผ์•ผ ์ž๋™ decompressํ•˜๋Š”๋ฐ, anilife ์„œ๋ฒ„๋Š” ๊ทธ๊ฑธ ์•ˆ ๋ณด๋ƒ„) const zlib = require('zlib'); function zstdDecompressAsync(buf) { return new Promise((resolve, reject) => { zlib.zstdDecompress(buf, (err, result) => err ? reject(err) : resolve(result)); }); } async function aniApi(apiPath, opts = {}) { const aniReferer = opts.aniReferer || '/'; for (let attempt = 0; attempt < 2; attempt++) { const page = await ensureAniPage(); try { const result = await withTimeout(page.evaluate(async (args) => { const r = await fetch(`https://api.anilife.app${args.apiPath}`, { credentials: 'include', headers: { 'Accept': 'application/json', 'x-anilife-referer': encodeURIComponent(args.aniReferer), 'x-client-id': 'web', } }); const buf = await r.arrayBuffer(); // base64๋กœ ์ธ์ฝ”๋”ฉํ•ด์„œ Node๋กœ ์ „์†ก const bytes = new Uint8Array(buf); let bin = ''; const CHUNK = 0x8000; for (let i = 0; i < bytes.length; i += CHUNK) { bin += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK)); } return { status: r.status, b64: btoa(bin) }; }, { apiPath, aniReferer }), 15000, `aniApi ${apiPath}`); let body = Buffer.from(result.b64, 'base64'); // ์ฒซ ๋ฐ”์ดํŠธ๋กœ zstd ๋งค์ง(0x28 0xB5 0x2F 0xFD) ๋˜๋Š” ์ผ๋ฐ˜ JSON({, [) ํŒ๋ณ„ const isZstd = body.length >= 4 && body[0] === 0x28 && body[1] === 0xB5 && body[2] === 0x2F && body[3] === 0xFD; if (isZstd) { try { body = await zstdDecompressAsync(body); } catch (e) { return { ok: true, status: result.status, error: 'zstd decompress failed: ' + e.message }; } } const text = body.toString('utf-8'); let json = null; try { json = JSON.parse(text); } catch {} return { ok: true, status: result.status, json, raw: json ? null : text.slice(0, 400) }; } catch (e) { // 1์ฐจ ์‹คํŒจ: page๋งŒ null (๋‹ค์Œ ์‹œ๋„์—์„œ ์ƒˆ ํŽ˜์ด์ง€) // 2์ฐจ ์‹คํŒจ: ๊ฒฉ๋ฆฌ ํ™˜๊ฒฝ ์ „์ฒด ๋ฆฌ์…‹ (browserยทcontext ๋‹ค ์ƒˆ๋กœ) โ€” ์ข€๋น„ page ๋ˆ„์  ๋ฐฉ์ง€ if (attempt === 0) { _aniPage = null; } else { resetAniIsolated().catch(() => {}); return { ok: false, error: String(e.message || e) }; } } } } // ๊ฒ€์ƒ‰ async function aniSearch(wd) { wd = (wd || '').trim(); if (!wd) return { error: 'empty query', items: [] }; if (aniBreakerIsOpen()) { const mins = Math.ceil((ANI_BREAKER.openUntil - Date.now()) / 60000); return { error: `anilife temporarily unavailable (retry in ${mins}min)`, items: [], breakerOpen: true }; } let r; try { r = await withTimeout( aniApi(`/v1/search?keyword=${encodeURIComponent(wd)}&page=1&sort=accuracy&size=25`), 20000, 'aniSearch' ); } catch (e) { aniBreakerRecordFailure(); return { error: String(e.message || e), items: [] }; } if (!r.ok || !r.json) { aniBreakerRecordFailure(); return { error: r.error || `status ${r.status}`, items: [] }; } aniBreakerRecordSuccess(); const list = r.json.result?.item_list || []; // anilife API๋Š” fuzzy/์—ฐ๊ด€ ๊ฒ€์ƒ‰์ด๋ผ ๋ฌด๊ด€ํ•œ ์ž‘ํ’ˆ๋„ ๋ฐ˜ํ™˜๋จ. // ์ œ๋ชฉ์— ๊ฒ€์ƒ‰์–ด๊ฐ€ ์‹ค์ œ๋กœ ํฌํ•จ๋œ ๊ฒƒ๋งŒ ๊ณจ๋ผ๋‚ธ๋‹ค (๋Œ€์†Œ๋ฌธ์ž/๊ณต๋ฐฑ ๋ฌด์‹œ). const normalize = s => String(s || '').toLowerCase().replace(/\s+/g, ''); const needle = normalize(wd); const items = list .filter(it => normalize(it.name).includes(needle)) .map(it => ({ id: it.id, title: it.name, meta: [it.format, it.episode].filter(Boolean).join(' ยท '), poster: it.image || null, href: `/content/${it.id}`, source: 'anilife', })); return { wd, count: items.length, items, source: 'anilife' }; } // ํšŒ์ฐจ ๋ชฉ๋ก + ์ž‘ํ’ˆ ๋ฉ”ํƒ€ async function aniEpisodes(id, opts = {}) { id = parseInt(id, 10); if (!id) return { error: 'bad id' }; // ์งง์€ ์บ์‹œ (์ƒˆ ํ™” ๋นจ๋ฆฌ ๋ฐ˜์˜) const cacheFile = `ani_ep_${id}.json`; if (!opts.nocache) { const cached = readCache(cacheFile, 300); if (cached) return cached; } if (aniBreakerIsOpen()) { const mins = Math.ceil((ANI_BREAKER.openUntil - Date.now()) / 60000); return { error: `anilife temporarily unavailable (retry in ${mins}min)`, breakerOpen: true }; } let meta, episodes; try { [meta, episodes] = await withTimeout(Promise.all([ aniApi(`/v1/document/anime/${id}`), aniApi(`/v1/document/anime/${id}/episode`), ]), 25000, 'aniEpisodes'); } catch (e) { aniBreakerRecordFailure(); return { error: String(e.message || e) }; } if (!meta.ok || !meta.json) { aniBreakerRecordFailure(); return { error: meta.error || `meta status ${meta.status}` }; } if (!episodes.ok || !episodes.json) { aniBreakerRecordFailure(); return { error: episodes.error || `ep status ${episodes.status}` }; } aniBreakerRecordSuccess(); const m = meta.json.result || {}; // anilife๋Š” episode_num์ด ํด์ˆ˜๋ก ์ตœ์‹ . tvchak๊ณผ ์ผ๊ด€์„ฑ ๋งž์ถ”๊ธฐ ์œ„ํ•ด nid๋ฅผ ๋’ค์ง‘์–ด ์ €์žฅ: // ๊ฐ€์žฅ ์ตœ์‹  = nid 1, ๊ฐ€์žฅ ์˜ค๋ž˜๋œ = nid N. (tvchak๋„ ๋™์ผ ๊ทœ์น™) // ์‹ค์ œ ์žฌ์ƒ์—๋Š” uniqueId๋งŒ ์“ฐ์ด๋ฏ€๋กœ nid๋Š” ์ •๋ ฌ/๋ผ๋ฒจ์šฉ ๊ฐ€์ƒ ์ธ๋ฑ์Šค. const rawList = episodes.json.result?.item_list || []; // episode_num ๋‚ด๋ฆผ์ฐจ์ˆœ(์ตœ์‹  ๋จผ์ €)์œผ๋กœ ์ •๋ ฌํ•œ ํ›„ ์ธ๋ฑ์Šค๋ฅผ nid๋กœ ์‚ฌ์šฉ const sorted = [...rawList].sort((a, b) => (parseFloat(b.episode_num) || 0) - (parseFloat(a.episode_num) || 0)); const eps = sorted.map((e, i) => ({ sid: 0, nid: i + 1, // 1=์ตœ์‹ , ํฐ ๊ฐ’=์˜ค๋ž˜๋œ ํšŒ์ฐจ (tvchak๊ณผ ๋™์ผ ๊ทœ์น™) uniqueId: e.uniqueId, label: `${e.episode_num}ํ™”`, subject: e.subject || '', thumbnail: e.thumbnail || null, duration: e.duration || '', episodeNum: e.episode_num, // ์›๋ณธ ๋ณด์กด })); let posterAni = m.images?.cover || null; // anilife cdn ์ด๋ฏธ์ง€๊ฐ€ referer ์—†์œผ๋ฉด 403. ์™ธ๋ถ€ ๋ฉ”ํƒ€ ์†Œ์Šค๊ฐ€ ๋” ์•ˆ์ •์ . // ํด๋ฐฑ ์ˆœ์„œ: namu(๋” ์ •ํ™•, ์ฐจ๋‹จ ์‹œ viaProxy๋กœ ์šฐํšŒ) โ†’ TMDb โ†’ anilife const titleForMeta = m.name?.kr || m.name?.en || m.name?.romaji || ''; let posterMeta = null; if (titleForMeta) { try { posterMeta = await fetchNamuPoster(titleForMeta); } catch {} if (!posterMeta) { try { posterMeta = await fetchTmdbPoster(titleForMeta); } catch {} } } const out = { id, title: titleForMeta, titles: m.name || null, poster: posterMeta || posterAni || null, // TMDb/namu ์šฐ์„  (referer ์ œ์•ฝ ์—†์Œ) posterAlt: posterMeta && posterAni ? posterAni : null, description: m.description || '', genre: m.genre || [], format: m.format || '', rating: m.rating || 0, ageRating: m.ageRating || '', trailer: m.trailer || null, count: eps.length, episodes: eps, source: 'anilife', checked_at: new Date().toISOString(), }; writeCache(cacheFile, out); return out; } // ์žฌ์ƒ โ€” /v1/media ์‘๋‹ต์ด zstd+์ถ”๊ฐ€ ์ธ์ฝ”๋”ฉ์ด๋ผ ์ง์ ‘ ํŒŒ์‹ฑ ๋ถˆ๊ฐ€. // ๋Œ€์‹  /watch?id={uniqueId} ํŽ˜์ด์ง€๋ฅผ ์‹ค์ œ๋กœ ๋กœ๋“œ์‹œํ‚ค๊ณ  HLS.js๊ฐ€ ๋ฐ›๋Š” m3u8 URL์„ // performance.getEntriesByType('resource') ๋กœ ์บก์ฒ˜. async function aniPlay(uniqueId) { if (!uniqueId || !/^[0-9a-f-]{36}$/i.test(uniqueId)) return { error: 'bad uniqueId' }; if (aniBreakerIsOpen()) { const mins = Math.ceil((ANI_BREAKER.openUntil - Date.now()) / 60000); return { error: `anilife temporarily unavailable (retry in ${mins}min)`, breakerOpen: true }; } // ์žฌ์ƒ URL์€ ์งง์€ ๋งŒ๋ฃŒ ํ† ํฐ(๋ณดํ†ต ~1์‹œ๊ฐ„)์ด๋ผ ์บ์‹œ ์•ˆ ํ•จ. ์ „์ฒด์— timeout ์ ์šฉ. return await withTimeout(_aniPlayInternal(uniqueId), 60000, 'aniPlay').catch(e => { aniBreakerRecordFailure(); return { error: String(e.message || e) }; }); } async function _aniPlayInternal(uniqueId) { for (let attempt = 0; attempt < 2; attempt++) { const page = await ensureAniPage(); try { // /watch ํŽ˜์ด์ง€๋กœ navigate (page.goto๋Š” navigation ์•ˆ์ „ํ•˜๊ฒŒ ์ฒ˜๋ฆฌ) await page.goto(`https://anilife.app/watch?id=${uniqueId}`, { waitUntil: 'domcontentloaded', timeout: 15000 }); // m3u8 ํ˜ธ์ถœ์ด ๋ฐœ์ƒํ•  ๋•Œ๊นŒ์ง€ ํด๋ง (์ตœ๋Œ€ 15์ดˆ) const start = Date.now(); let manifest = null; while (Date.now() - start < 15000) { manifest = await page.evaluate(() => { const ents = performance.getEntriesByType('resource'); const masters = ents.map(e => e.name).filter(n => /\/master\.m3u8/i.test(n)); return masters[0] || null; }); if (manifest) break; await page.waitForTimeout(500); } if (!manifest) { if (attempt === 1) { aniBreakerRecordFailure(); return { error: 'manifest not found within 15s' }; } continue; } // ArtPlayer์˜ chapter ์ •๋ณด(์˜คํ”„๋‹/์—”๋”ฉ ๊ตฌ๊ฐ„) ์ถ”์ถœ ์‹œ๋„. ์‹คํŒจํ•ด๋„ ์žฌ์ƒ์—๋Š” ์˜ํ–ฅ ์—†์Œ. // ์ตœ๋Œ€ 3ํšŒ ์‹œ๋„ (1.5์ดˆ) โ€” ๋„ˆ๋ฌด ์˜ค๋ž˜ ๋Œ๋ฉด ์ „์ฒด timeout์— ์˜ํ–ฅ let chapters = null; try { for (let i = 0; i < 3; i++) { chapters = await page.evaluate(() => { const chs = [...document.querySelectorAll('.art-chapter')]; const v = document.querySelector('video'); if (chs.length === 0 || !v?.duration || isNaN(v.duration)) return null; const total = v.duration; // ๊ฐ chapter์˜ width% + left% ๊ณ„์‚ฐํ•ด์„œ (start, end, title) ํ˜•ํƒœ๋กœ ๋ณ€ํ™˜ const out = []; let acc = 0; for (const ch of chs) { const widthStr = (ch.style.width || '').replace('%', ''); const w = parseFloat(widthStr); if (!isFinite(w)) continue; const start = (acc / 100) * total; const end = ((acc + w) / 100) * total; // title์€ hover ์‹œ ํ‘œ์‹œ๋˜๋Š” .art-chapter-title โ€” ๊ฐ™์€ chapter ํŠธ๋ฆฌ๊ฑฐ์˜ ํ˜•์ œ ๋˜๋Š” ๋ถ€๋ชจ์—์„œ ์ฐพ๊ธฐ const title = ch.querySelector('.art-chapter-title')?.textContent?.trim() || null; out.push({ start: Math.round(start), end: Math.round(end), widthPct: w, title }); acc += w; } // ๋ชจ๋“  chapter title์„ ๋ณ„๋„๋กœ๋„ ์ˆ˜์ง‘ (DOM์— ๋ณ„๊ฐœ๋กœ ์กด์žฌํ•  ์ˆ˜ ์žˆ์Œ) const titles = [...document.querySelectorAll('.art-chapter-title')].map(t => t.textContent?.trim()).filter(Boolean); return { chapters: out, titles }; }); if (chapters?.chapters?.length) break; await page.waitForTimeout(500); } } catch {} // ๋ฉ”์ธ ํŽ˜์ด์ง€๋กœ ๋ณต๊ท€ (๋‹ค๋ฅธ API ํ˜ธ์ถœ์ด ์ •์ƒ ์ฒ˜๋ฆฌ๋˜๋„๋ก) page.evaluate(() => { try { history.replaceState(null, '', '/'); } catch {} }).catch(() => {}); aniBreakerRecordSuccess(); return { uniqueId, manifest, chapters: chapters?.chapters || null, chapterTitles: chapters?.titles || null, source: 'anilife', referer: 'https://anilife.app/', checked_at: new Date().toISOString(), }; } catch (e) { // 1์ฐจ: page๋งŒ ์žฌ์ƒ์„ฑ. 2์ฐจ: ๊ฒฉ๋ฆฌ ํ™˜๊ฒฝ ์ „์ฒด ๋ฆฌ์…‹ (browserยทcontext๊นŒ์ง€). if (attempt === 0) { try { if (_aniPage) await _aniPage.close(); } catch {} _aniPage = null; } else { await resetAniIsolated(); aniBreakerRecordFailure(); return { error: String(e.message || e) }; } } } } // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• // LINKKF โ€” anilife ํด๋ฐฑ ์†Œ์Šค (linkkf.tv) // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• // ๊ตฌ์กฐ: // /view/?wd=KEYWORD โ†’ ๊ฒ€์ƒ‰ (HTML) // /ani/{id}/ โ†’ ์‹œ๋ฆฌ์ฆˆ ์ƒ์„ธ + ํšŒ์ฐจ ๋งํฌ (HTML) // /watch/{id}/a{sid}/k{nid}/ โ†’ ์žฌ์ƒ ํŽ˜์ด์ง€ (player_aaaa.url ํ† ํฐ) // ํ† ํฐ 21707m1 โ†’ https://pp5.ssku1.top/{token}/index.m3u8 (Referer: play.sub3.top) // nid ์ปจ๋ฒค์…˜: linkkf ์›๋ณธ์€ k1=1ํ™”(๊ฐ€์žฅ ์˜›). ์šฐ๋ฆฌ ์‹œ์Šคํ…œ์€ nid=1์ด ์ตœ์‹  โ†’ ๋’ค์ง‘์–ด ์ •๊ทœํ™”. // player m3u8์€ Referer ํ•„์š” โ€” /api/cdn ํ”„๋ก์‹œ์—์„œ ์ฒ˜๋ฆฌ. const LINKKF_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'; // ๊ฐ€๋ฒผ์šด fetch ํ—ฌํผ (linkkf๋Š” Cloudflare ๊ฐ€๋ฒผ์šด ๋ณดํ˜ธ๋ผ ์ง์ ‘ fetch OK. ๋‹จ SOCKS5 ๋ฏธ์‚ฌ์šฉ โ€” datacenter IP๋ฉด ์ฐจ๋‹จ ๊ฐ€๋Šฅ์„ฑ). // HF ํ™˜๊ฒฝ์—์„œ datacenter IP๋ผ ์ฐจ๋‹จ๋˜๋ฉด Playwright ์ปจํ…์ŠคํŠธ ๋นŒ๋ ค ์šฐํšŒ. ์ผ๋‹จ fetch ์‹œ๋„ โ†’ ์‹คํŒจ ์‹œ Playwright fallback. async function linkkfFetchHtml(url, opts = {}) { const timeout = opts.timeout || 12000; try { const ctrl = new AbortController(); const t = setTimeout(() => ctrl.abort(), timeout); const r = await fetch(url, { headers: { 'User-Agent': LINKKF_UA, 'Accept-Language': 'ko-KR,ko;q=0.9' }, signal: ctrl.signal, }); clearTimeout(t); if (r.status >= 200 && r.status < 400) { const html = await r.text(); if (html && html.length > 1000) return html; } } catch (e) { console.warn(`[linkkf] fetch failed (${url}), trying Playwright:`, e.message); } // Playwright fallback โ€” anilife ์ปจํ…์ŠคํŠธ ๋นŒ๋ ค์„œ (SOCKS5 ๊ฒฝ์œ  ์‹œ ํ•œ๊ตญ IP ํšจ๊ณผ) try { if (!_browser) await getContext(); const ctx = await _browser.newContext({ userAgent: LINKKF_UA, locale: 'ko-KR' }); try { const p = await ctx.newPage(); await p.goto(url, { waitUntil: 'domcontentloaded', timeout }); const html = await p.content(); await p.close().catch(() => {}); return html; } finally { await ctx.close().catch(() => {}); } } catch (e) { console.warn(`[linkkf] Playwright fallback failed (${url}):`, e.message); return null; } } // ๊ฒ€์ƒ‰ โ€” /view/?wd=... async function linkkfSearch(wd) { wd = (wd || '').trim(); if (!wd) return { items: [] }; const html = await linkkfFetchHtml(`https://linkkf.tv/view/?wd=${encodeURIComponent(wd)}`); if (!html) return { items: [], error: 'fetch failed' }; // a ํƒœ๊ทธ: <a href="/ani/{id}/">์ œ๋ชฉ</a> โ€” ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ์นด๋“œ const re = /href="\/ani\/(\d+)\/"[^>]*>([^<]{1,80})</g; const items = []; const seen = new Set(); let m; while ((m = re.exec(html))) { const id = parseInt(m[1], 10); const title = m[2].trim(); if (!id || seen.has(id) || !title) continue; seen.add(id); items.push({ id, title, source: 'linkkf' }); } return { items }; } // ํšŒ์ฐจ ๋ชฉ๋ก + ์‹œ๋ฆฌ์ฆˆ ์ •๋ณด โ€” /ani/{id}/ async function linkkfEpisodes(id, opts = {}) { id = parseInt(id, 10); if (!id) return { error: 'bad id' }; const cacheFile = `linkkf_ep_${id}.json`; if (!opts.nocache) { const cached = readCache(cacheFile, 300); if (cached) return cached; } const html = await linkkfFetchHtml(`https://linkkf.tv/ani/${id}/`); if (!html) return { error: 'fetch failed' }; // ์ œ๋ชฉ const titleMatch = html.match(/<h1[^>]*class="detail-info-title[^"]*"[^>]*>([^<]+)</); const title = titleMatch ? titleMatch[1].trim() : null; // ํฌ์Šคํ„ฐ const posterMatch = html.match(/<img[^>]+class="[^"]*detail-pic[^"]*"[^>]+src="([^"]+)"/) || html.match(/<meta[^>]+property="og:image"[^>]+content="([^"]+)"/); const poster = posterMatch ? posterMatch[1] : null; // ํšŒ์ฐจ ๋งํฌ โ€” /watch/{id}/a{sid}/k{nid}/ + ๋ผ๋ฒจ const epRe = new RegExp(`href="/watch/${id}/a(\\d+)/k(\\d+)/"[^>]*>([^<]*)<`, 'g'); const rawEps = []; let m; while ((m = epRe.exec(html))) { const sid = parseInt(m[1], 10); const linkkfNid = parseInt(m[2], 10); let label = (m[3] || '').trim(); if (!label) continue; // ๋ผ๋ฒจ ์—†๋Š” โ–ถ ๋ฒ„ํŠผ ๊ฐ™์€ ํ•ญ๋ชฉ ์ œ์™ธ // ๋ผ๋ฒจ ์ •๊ทœํ™”: ์ˆซ์ž๋งŒ ์žˆ์œผ๋ฉด "Nํ™”" ํ˜•ํƒœ๋กœ (linkkf๋Š” "1", "720", "714-715" ๊ฐ™์ด ๋“ค์–ด์˜ด) if (/^\d+(-\d+)?$/.test(label)) label = `${label}ํ™”`; rawEps.push({ sid, linkkfNid, label }); } if (!rawEps.length) { return { id, title, poster, count: 0, episodes: [], source: 'linkkf', error: 'no episodes' }; } // linkkf ์›๋ณธ: k1์ด ๊ฐ€์žฅ ์˜›, ํฐ k๊ฐ€ ์ตœ์‹ . ์šฐ๋ฆฌ ์ปจ๋ฒค์…˜์€ nid=1์ด ์ตœ์‹ . // โ†’ linkkfNid ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•ด์„œ nid=1,2,3... ํ• ๋‹น rawEps.sort((a, b) => b.linkkfNid - a.linkkfNid); const eps = rawEps.map((e, i) => ({ sid: e.sid, nid: i + 1, label: e.label, linkkfNid: e.linkkfNid, // ์žฌ์ƒ ์‹œ ์›๋ณธ nid ํ•„์š” })); const out = { id, title, poster, count: eps.length, episodes: eps, source: 'linkkf', checked_at: new Date().toISOString(), }; writeCache(cacheFile, out); return out; } // ์žฌ์ƒ โ€” watch ํŽ˜์ด์ง€์—์„œ player_aaaa.url ํ† ํฐ ์ถ”์ถœ โ†’ m3u8 URL ์กฐ๋ฆฝ async function linkkfPlay(id, sid, linkkfNid) { id = parseInt(id, 10); sid = parseInt(sid, 10); linkkfNid = parseInt(linkkfNid, 10); if (!id || !sid || !linkkfNid) return { error: 'bad params' }; const html = await linkkfFetchHtml(`https://linkkf.tv/watch/${id}/a${sid}/k${linkkfNid}/`); if (!html) return { error: 'fetch failed' }; // player_aaaa JSON ์ถ”์ถœ (tvchak๊ณผ ๊ฐ™์€ ๊ตฌ์กฐ) const idx = html.indexOf('player_aaaa'); if (idx < 0) return { error: 'player_aaaa not found' }; const eqIdx = html.indexOf('=', idx); const startIdx = html.indexOf('{', eqIdx); if (startIdx < 0) return { error: 'player JSON start not found' }; // ๊ท ํ˜• ์ค‘๊ด„ํ˜ธ ํŒŒ์„œ let depth = 0, endIdx = -1; for (let i = startIdx; i < html.length; i++) { const c = html[i]; if (c === '{') depth++; else if (c === '}') { depth--; if (depth === 0) { endIdx = i; break; } } } if (endIdx < 0) return { error: 'player JSON end not found' }; let player; try { player = JSON.parse(html.slice(startIdx, endIdx + 1)); } catch (e) { return { error: 'player JSON parse: ' + e.message }; } const token = player.url; // ์˜ˆ: "21707m1" if (!token) return { error: 'no url token' }; // m3u8 ํŒจํ„ด ์กฐ๋ฆฝ. host๋Š” actual_url์—์„œ ์ถ”์ถœ ์‹œ๋„ (๋ณ€๋™ ๊ฐ€๋Šฅ์„ฑ ๋Œ€์‘) let host = 'pp5.ssku1.top'; if (player.actual_url) { const am = player.actual_url.match(/id=(\w+)/); if (am) host = `${am[1]}.ssku1.top`; } const m3u8 = `https://${host}/${token}/index.m3u8`; return { url: m3u8, url_next: player.url_next ? `https://${host}/${player.url_next}/index.m3u8` : null, link_next: player.link_next || null, link_pre: player.link_pre || null, vod_data: player.vod_data || null, referer: 'https://play.sub3.top/', source: 'linkkf', _fallbackSource: 'linkkf', }; } // ์ œ๋ชฉ ์ •๊ทœํ™” โ€” ๋งค์นญ ์ ์ˆ˜์šฉ. ๊ณต๋ฐฑ/๊ด„ํ˜ธ/ํŠน์ˆ˜๋ฌธ์ž ์ œ๊ฑฐ, ์†Œ๋ฌธ์ž. function normalizeTitle(s) { return String(s || '') .toLowerCase() .replace(/\([^)]*\)/g, '') // ๊ด„ํ˜ธ ์•ˆ ์ œ๊ฑฐ "(2023)" .replace(/[!?:ยท\-_,.\s]/g, '') // ๊ตฌ๋‘์ /๊ณต๋ฐฑ .replace(/์‹œ์ฆŒ\d+|season\d+|s\d+|๊ทน์žฅํŒ|ova|tvํŒ|tv์‹œ๋ฆฌ์ฆˆ|movie/g, '') .trim(); } // ๋งค์นญ ์ ์ˆ˜ (0~100). ๋†’์„์ˆ˜๋ก ์ข‹์Œ. // +60: ์ •๊ทœํ™” ์ œ๋ชฉ ์™„์ „ ์ผ์น˜ // +30: ํ•œ์ชฝ์ด ๋‹ค๋ฅธ ์ชฝ์„ ํฌํ•จ (์˜ˆ: "์ฃผ์ˆ ํšŒ์ „" โŠ‚ "์ฃผ์ˆ ํšŒ์ „2๊ธฐ") // +0~30: ํšŒ์ฐจ ์ˆ˜ ๊ทผ์ ‘๋„ (anilife knownCount์™€ ยฑ20% ์•ˆ์ด๋ฉด ๋งŒ์ , ๋ฉ€์ˆ˜๋ก ๊ฐ์†Œ) // -50: ํšŒ์ฐจ 0 (์žฌ์ƒ ๋ถˆ๊ฐ€) // -10: ์ œ๋ชฉ์ด ์•ˆ ๋น„์Šทํ•œ๋ฐ ํšŒ์ฐจ๋„ ์ ์Œ function scoreLinkkfCandidate(targetTitle, targetCount, candTitle, candCount) { const a = normalizeTitle(targetTitle); const b = normalizeTitle(candTitle); let score = 0; if (!a || !b) return -10; if (a === b) score += 60; else if (a.includes(b) || b.includes(a)) score += 30; else { // ๋ถ€๋ถ„ ํ† ํฐ ๋งค์นญ const ta = a.length, tb = b.length; const overlap = (() => { let cnt = 0; for (let i = 0; i < ta - 1; i++) { const bigram = a.slice(i, i + 2); if (b.includes(bigram)) cnt++; } return cnt / Math.max(1, ta - 1); })(); score += Math.round(overlap * 25); // 0~25 } if (candCount === 0) score -= 50; else if (targetCount && targetCount > 0) { const ratio = Math.min(candCount, targetCount) / Math.max(candCount, targetCount); score += Math.round(ratio * 30); // 0~30 } else { // targetCount ๋ชจ๋ฅด๋ฉด ํšŒ์ฐจ ๋งŽ์€ ๊ฒƒ ์•ฝ๊ฐ„ ์šฐ์„  score += Math.min(15, candCount); } return score; } // anilife id โ†’ linkkf id ๋งคํ•‘ ์บ์‹œ ์กฐํšŒ๋งŒ (์˜๊ตฌ). ์‹ ๊ทœ ๋งค์นญ์€ ์ ์ˆ˜ ๊ธฐ๋ฐ˜์œผ๋กœ aniEpisodesFallback์—์„œ ์ฒ˜๋ฆฌ. function getCachedLinkkfMap(anilifeId) { if (!anilifeId) return undefined; const cached = readCachePermanent(`linkkf_map_${anilifeId}.json`); if (!cached) return undefined; if (cached.linkkfId) return cached.linkkfId; // ์‹คํŒจ ์บ์‹œ: 7์ผ ์•ˆ์—” ์žฌ์‹œ๋„ ์•ˆ ํ•จ if (cached.matchedAt && Date.now() - new Date(cached.matchedAt).getTime() < 7 * 24 * 3600 * 1000) { return null; // ๋ช…์‹œ์  "์ตœ๊ทผ ์‹คํŒจ" โ€” ์žฌ์‹œ๋„ ์•ˆ ํ•จ } return undefined; // ์บ์‹œ ๋งŒ๋ฃŒ โ†’ ์ƒˆ๋กœ ๋งค์นญ } // fav.title์„ ๋ฐ›์•„ linkkf episodes ํด๋ฐฑ. // anilife ์‘๋‹ต๊ณผ ๋™์ผํ•œ ์Šคํ‚ค๋งˆ๋กœ ์ •๊ทœํ™”ํ•ด์„œ ํด๋ผ์ด์–ธํŠธ ์ฝ”๋“œ ๋ณ€๊ฒฝ ์—†์ด ๋™์ž‘. // opts.targetCount: anilife์˜ knownCount (์žˆ์œผ๋ฉด ํšŒ์ฐจ ์ˆ˜ ๊ทผ์ ‘๋„๋กœ ์ ์ˆ˜ ๊ฐ€์‚ฐ) // opts.fallbackId: ํด๋ผ์ด์–ธํŠธ๊ฐ€ ๋ฏธ๋ฆฌ ์•Œ๊ณ  ์žˆ๋Š” linkkf id (๊ฒ€์ƒ‰ ๋‹จ๊ณ„ ์Šคํ‚ต, ์ฆ‰์‹œ ๋งคํ•‘) async function aniEpisodesFallback(anilifeId, title, opts = {}) { // 1. ํด๋ผ์ด์–ธํŠธ๊ฐ€ fallbackId๋ฅผ ๋ณด๋ƒˆ์œผ๋ฉด ๊ทธ๊ฒƒ ์šฐ์„  (B ์ž๋™ ๋ฐฑ์—… ๋งคํ•‘) if (opts.fallbackId) { const ep = await linkkfEpisodes(opts.fallbackId); if (!ep.error && ep.episodes && ep.episodes.length) { return finalizeLinkkfFallback(anilifeId, title, opts.fallbackId, ep); } } // 2. ๋งคํ•‘ ์บ์‹œ โ€” ์ ์ˆ˜ ํ†ต๊ณผํ•ด์„œ ์ €์žฅ๋œ ๋งคํ•‘๋งŒ ์‹ ๋ขฐ const cachedId = getCachedLinkkfMap(anilifeId); if (cachedId === null) return { error: 'recent linkkf match failure (cached)' }; if (cachedId !== undefined) { const ep = await linkkfEpisodes(cachedId); if (!ep.error && ep.episodes && ep.episodes.length) { return finalizeLinkkfFallback(anilifeId, title, cachedId, ep); } } // 3. ์‹ ๊ทœ ๊ฒ€์ƒ‰ โ€” ์ ์ˆ˜ ๊ธฐ๋ฐ˜ best ๋งค์นญ const result = await linkkfSearch(title); const candidates = (result.items || []).slice(0, 8); if (!candidates.length) return { error: 'no linkkf candidates' }; // ๊ฐ ํ›„๋ณด์˜ ํšŒ์ฐจ ์ˆ˜ ๋น ๋ฅด๊ฒŒ ํ™•์ธ (๋ณ‘๋ ฌ) const scored = await Promise.all(candidates.map(async cand => { const e = await linkkfEpisodes(cand.id); const count = (!e.error && e.episodes) ? e.episodes.length : 0; const score = scoreLinkkfCandidate(title, opts.targetCount || 0, cand.title, count); return { cand, ep: e, score, count }; })); scored.sort((a, b) => b.score - a.score); console.log(`[linkkf-map] candidates for "${title}" (targetCount=${opts.targetCount || '?'}):`); for (const s of scored.slice(0, 5)) console.log(` score=${s.score} id=${s.cand.id} "${s.cand.title}" (${s.count}ep)`); const best = scored.find(s => s.count > 0 && s.score > 0); if (!best) return { error: 'no playable linkkf match' }; writeCache(`linkkf_map_${anilifeId}.json`, { linkkfId: best.cand.id, title, matchedAt: new Date().toISOString(), score: best.score }); return finalizeLinkkfFallback(anilifeId, title, best.cand.id, best.ep); } // ๊ณตํ†ต: linkkf ํšŒ์ฐจ๋ฅผ anilife ์Šคํ‚ค๋งˆ๋กœ ๋ณ€ํ™˜ function finalizeLinkkfFallback(anilifeId, title, linkkfId, ep) { // anilife ์Šคํ‚ค๋งˆ์— ๋งž์ถค: episodes์— uniqueId ์ž๋ฆฌ์— "linkkf:{id}:{sid}:{linkkfNid}" ๊ฐ™์€ ํ‚ค ์‚ฌ์šฉํ•ด์„œ // aniPlay ํ˜ธ์ถœ ์‹œ ๋ถ„๊ธฐ ๊ฐ€๋Šฅํ•˜๊ฒŒ. const eps = ep.episodes.map(e => ({ sid: 0, // anilife ์ปจ๋ฒค์…˜ nid: e.nid, uniqueId: `linkkf:${linkkfId}:${e.sid}:${e.linkkfNid}`, label: e.label, subject: '', thumbnail: null, duration: '', episodeNum: String(e.nid), })); return { id: anilifeId, // ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์•Œ๊ณ  ์žˆ๋Š” ID ์œ ์ง€ title: ep.title || title, titles: null, poster: ep.poster || null, posterAlt: null, description: '', genre: [], format: '', rating: 0, ageRating: '', trailer: null, count: eps.length, episodes: eps, source: 'anilife', // ํด๋ผ์ด์–ธํŠธ์—” anilife๋กœ ๋ณด์ž„ (ํด๋ฐฑ ์‚ฌ์‹ค ์ˆจ๊น€) _fallbackSource: 'linkkf', // ํด๋ผ์ด์–ธํŠธ๊ฐ€ ๋ฐฐ์ง€ ํ‘œ์‹œ์šฉ์œผ๋กœ ์‚ฌ์šฉ _fallbackLinkkfId: linkkfId, // ํด๋ผ์ด์–ธํŠธ๊ฐ€ fav.fallbackLinkkfId๋กœ ์ €์žฅํ•ด ๋‹ค์Œ ํ˜ธ์ถœ์— ์ง์ ‘ ์ „๋‹ฌ checked_at: new Date().toISOString(), }; } // uniqueId๊ฐ€ "linkkf:..."๋กœ ์‹œ์ž‘ํ•˜๋ฉด linkkf ์žฌ์ƒ. async function aniPlayMaybeFallback(uniqueId) { if (typeof uniqueId === 'string' && uniqueId.startsWith('linkkf:')) { const parts = uniqueId.split(':'); // linkkf:{linkkfId}:{sid}:{linkkfNid} const linkkfId = parseInt(parts[1], 10); const sid = parseInt(parts[2], 10); const linkkfNid = parseInt(parts[3], 10); return await linkkfPlay(linkkfId, sid, linkkfNid); } return null; // ์ผ๋ฐ˜ anilife ๊ฒฝ๋กœ๋กœ } // โ”€โ”€โ”€โ”€โ”€ ๋„๋ฉ”์ธ ํƒ์ง€ โ”€โ”€โ”€โ”€โ”€ async function findLiveDomain() { // ๋„๋ฉ”์ธ ๊ฐ•์ œ ๊ณ ์ • (2026-06-30): FORCE_DOMAIN ํ™˜๊ฒฝ๋ณ€์ˆ˜๊ฐ€ ์žˆ์œผ๋ฉด announce/์บ์‹œ ๋ฌด์‹œํ•˜๊ณ  ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉ. // ํ˜„์žฌ announce(tvchak208.com)๊ฐ€ ์ด PC ๊ณต์ธ IP์— ์ฐจ๋‹จ(์œ ์ง€๋ณด์ˆ˜์ค‘ ์œ„์žฅ)๋ผ, ์‚ฌ์šฉ์ž๊ฐ€ cf challenge๋ฅผ // ์ง์ ‘ ํ†ต๊ณผ์‹œํ‚จ tvchak.live๋กœ ๊ณ ์ • ์šด์˜. 208 ์ฐจ๋‹จ ํ’€๋ฆฌ๊ฑฐ๋‚˜ .live๊ฐ€ ์ฃฝ์œผ๋ฉด ์ด ํ™˜๊ฒฝ๋ณ€์ˆ˜๋งŒ ์ œ๊ฑฐ. if (FORCE_DOMAIN) { return { domain: FORCE_DOMAIN, announced: FORCE_DOMAIN, source: 'forced', checked_at: new Date().toISOString() }; } // ๋Ÿฐํƒ€์ž„ ์˜ค๋ฒ„๋ผ์ด๋“œ (2026-07-03): ์‚ฌ์šฉ์ž๊ฐ€ ํ—ค๋” ๋ฐฐ์ง€์—์„œ '๋ผ์ด๋ธŒ/208/์ง์ ‘์ž…๋ ฅ'์„ ๊ณจ๋ผ // POST /api/domain-override๋กœ ์ €์žฅํ•œ ๋„๋ฉ”์ธ. announce ์ž๋™์ถ”์ข…๋ณด๋‹ค ์šฐ์„ ํ•˜๋ฉฐ, ์„œ๋ฒ„ ์žฌ์‹œ์ž‘ํ•ด๋„ // domain-override.json ์บ์‹œ๋กœ ๋ณต์›๋œ๋‹ค. ํด๋ผ์ด์–ธํŠธ๊ฐ€ '์ž๋™'์„ ๊ณ ๋ฅด๋ฉด ์ด ํŒŒ์ผ์„ ์ง€์›Œ announce ์ถ”์ข… ๋ณต๊ท€. const ov = readCachePermanent('domain-override.json'); if (ov && ov.domain) { return { domain: ov.domain, announced: ov.domain, source: 'override', checked_at: ov.checked_at || new Date().toISOString() }; } // ๋„๋ฉ”์ธ ์บ์‹œ๋Š” 10๋ถ„ ์‹ ๋ขฐ (probe ์•ˆ ํ•จ โ€” probe๊ฐ€ robots ํƒญ์„ ๋งŒ๋“ค์–ด ํƒญ ํญ์ฆ์„ ์œ ๋ฐœํ–ˆ์Œ). // announce๋ฅผ ๊ทธ๋•Œ๊ทธ๋•Œ ์ฝ๋Š” ๋‹จ์ˆœ ๋ชจ๋ธ์ด๋ฏ€๋กœ, ๋งŒ๋ฃŒ๋˜๋ฉด _findLiveDomainImpl์ด tvchak.org๋ฅผ // ๋‹ค์‹œ ์ฝ์–ด ํ˜„์žฌ ํ™œ์„ฑ ์ฃผ์†Œ๋กœ ๊ฐฑ์‹ ํ•œ๋‹ค. announce๊ฐ€ 208โ†”.live๋กœ ๋ฐ”๋€Œ์–ด๋„ 10๋ถ„ ๋‚ด ์ž๋™ ์ถ”์ข…. const cached = readCache('domain.json', 600); if (cached && cached.domain) return cached; // stale (์ด์ „์— ๋ฐ›์•˜๋˜ ๋„๋ฉ”์ธ) โ€” ์ƒˆ ์‹œ๋„ ์‹คํŒจํ•ด๋„ ์ตœํ›„ fallback์œผ๋กœ ์‚ฌ์šฉ const stale = readCachePermanent('domain.json'); try { return await withTimeout(_findLiveDomainImpl(stale), 25000, 'findLiveDomain'); } catch (e) { console.warn('findLiveDomain timeout:', e.message); // tvchak ํ˜ธ์ถœ์ด hangํ•œ ๊ฑฐ๋‹ˆ๊นŒ _tvPage ์žฌ์ƒ์„ฑํ•˜๋„๋ก reset try { if (_tvPage) await _tvPage.close().catch(() => {}); } catch {} _tvPage = null; // stale ์žˆ์œผ๋ฉด ๊ทธ๊ฑฐ๋ผ๋„ ๋ฐ˜ํ™˜ (๋นˆ ํ™”๋ฉด ๋ฐฉ์ง€) if (stale && stale.domain) { return { ...stale, stale: true }; } return { domain: null, error: e.message, source: 'tvchak.org', checked_at: new Date().toISOString() }; } } // tvchak.org ๋žœ๋”ฉ HTML์—์„œ ํ˜„์žฌ announce๋œ ์ฝ˜ํ…์ธ  ๋„๋ฉ”์ธ์„ ์ถ”์ถœ. _findLiveDomainImpl์ด ๊ทธ๋Œ€๋กœ ์ฑ„ํƒ. // ๋ฒˆํ˜ธ ์ฒด๊ณ„(tvchakNNN.com)๋ฉด ๊ฐ€์žฅ ๋งŽ์ด ๋“ฑ์žฅํ•œ ๋ฒˆํ˜ธ, ๋‹จ์ผ ๋„๋ฉ”์ธ ์ฒด๊ณ„(2026-06-30~)๋ฉด flat ๋„๋ฉ”์ธ(tvchak.live ๋“ฑ). // counts๋Š” ๋‚ด๋ถ€ best ๊ณ„์‚ฐ์šฉ. announced: ์ฑ„ํƒ ๋„๋ฉ”์ธ. function parseAnnouncedDomain(html) { html = html || ''; let announced = null; const counts = {}; // (1) ์˜› ๋ฒˆํ˜ธ ๋„๋ฉ”์ธ ์ฒด๊ณ„: tvchakNNN.com โ€” ๋ณธ๋ฌธ์— ๊ฐ€์žฅ ๋งŽ์ด ๋“ฑ์žฅํ•˜๋Š” ๋ฒˆํ˜ธ๋ฅผ announce๋กœ. const re = /tvchak(\d+)\.com/gi; let m; while ((m = re.exec(html))) counts[m[1]] = (counts[m[1]] || 0) + 1; const best = Object.entries(counts).sort((a, b) => b[1] - a[1])[0]; if (best) announced = `tvchak${best[0]}.com`; // (2) ์‹  ๋‹จ์ผ ๋„๋ฉ”์ธ ์ฒด๊ณ„ (2026-06-30~): tvchak.org ๋žœ๋”ฉ์ด ๋ฒˆํ˜ธ ๋Œ€์‹  // "ํ˜„์žฌ ์ ‘์† ๊ฐ€๋Šฅํ•œ ๊ณต์‹ ์ฃผ์†Œ: tvchak.live" ์ฒ˜๋Ÿผ ๋น„๋ฒˆํ˜ธ ๋„๋ฉ”์ธ์„ ์•ˆ๋‚ดํ•จ. // ๋ฒˆํ˜ธ ๋„๋ฉ”์ธ์„ ๋ชป ์ฐพ์•˜์œผ๋ฉด ๋น„๋ฒˆํ˜ธ ์ฝ˜ํ…์ธ  ๋„๋ฉ”์ธ(tvchak.live ๋“ฑ)์„ announce๋กœ ์ฑ„ํƒ. // tvchak.org ์ž์‹ (๋žœ๋”ฉ, maccms ์ฝ˜ํ…์ธ  ์—†์Œ)์€ ํ›„๋ณด์—์„œ ์ œ์™ธ. if (!announced) { const reFlat = /tvchak\.(live|net|cc|me|tv|io)\b/gi; const flatCounts = {}; let fm; while ((fm = reFlat.exec(html))) { const d = `tvchak.${fm[1].toLowerCase()}`; flatCounts[d] = (flatCounts[d] || 0) + 1; } const bestFlat = Object.entries(flatCounts).sort((a, b) => b[1] - a[1])[0]; if (bestFlat) announced = bestFlat[0]; } return { announced, counts }; } // tvchak.org announce๋ฅผ ์ฝ์–ด์˜จ๋‹ค (CDP ๋˜๋Š” NAS ๊ฒฝ๋กœ). ์‹คํŒจ ์‹œ null. async function fetchAnnounceHtml(timeoutMs = 10000) { try { const r = USE_LOCAL_CDP ? await cdpFetchPage('https://tvchak.org/', timeoutMs) : await nasFetch('https://tvchak.org/', timeoutMs); return r.body || ''; } catch (e) { console.warn('[announce] fetch failed:', e.message); return null; } } async function _findLiveDomainImpl(stale) { // ๋‹จ์ˆœ ๋ชจ๋ธ (2026-06-30): tvchak.org๊ฐ€ ์•ˆ๋‚ดํ•˜๋Š” ํ˜„์žฌ ํ™œ์„ฑ ์ฃผ์†Œ๋ฅผ ๊ทธ๋Œ€๋กœ ์ฑ„ํƒ. // announce๊ฐ€ 208์ด๋ฉด tvchak208.com, .live๋ฉด tvchak.live. ยฑ5 ์ธ์ ‘๋ฒˆํ˜ธ polling/probe ์—†์Œ // (๊ทธ๊ฒŒ ๋งค๋ฒˆ ์ƒˆ robots ํƒญ์„ ๋งŒ๋“ค์–ด ํƒญ ํญ์ฆ + ๊นœ๋นก์ž„์˜ ์›์ธ์ด์—ˆ์Œ). // announce๋ฅผ ๋ชป ์ฝ์œผ๋ฉด ์ง์ „ ์บ์‹œ(stale) ๋„๋ฉ”์ธ์œผ๋กœ ํด๋ฐฑ โ€” ๋นˆ ํ™”๋ฉด ๋ฐฉ์ง€. const html = await fetchAnnounceHtml(10000); const { announced } = parseAnnouncedDomain(html); let domain = announced; if (!domain) { // announce ํŒŒ์‹ฑ ์‹คํŒจ(๋žœ๋”ฉ ๊ตฌ์กฐ ๋ณ€๊ฒฝ/๋„คํŠธ์›Œํฌ ์‹คํŒจ ๋“ฑ) โ†’ ์ง์ „ ๋„๋ฉ”์ธ ์œ ์ง€. if (stale && stale.domain) { console.warn(`[findLiveDomain] announce ํŒŒ์‹ฑ ์‹คํŒจ โ€” stale ${stale.domain} ์œ ์ง€`); return { ...stale, stale: true }; } console.warn('[findLiveDomain] announce ํŒŒ์‹ฑ ์‹คํŒจ + stale ์—†์Œ โ€” domain=null'); } else { console.log(`[findLiveDomain] announced=${announced} chosen=${domain}`); } const result = { domain, announced: announced || domain, source: 'tvchak.org', checked_at: new Date().toISOString(), }; if (domain) writeCache('domain.json', result); return result; } // โ”€โ”€โ”€โ”€โ”€ ํšŒ์ฐจ ๋ชฉ๋ก + ์‹œ๋ฆฌ์ฆˆ ๋ฉ”ํƒ€ โ”€โ”€โ”€โ”€โ”€ // ์ปจ๋ฒค์…˜: ์ •๊ทœํ™” ํ›„ ํ•ญ์ƒ nid=1์ด ์ตœ์‹ ํ™” = ํฐ ํ™”์ˆ˜, nid=N์ด 1ํ™” = ์ž‘์€ ํ™”์ˆ˜. // ์‚ฌ์ดํŠธ๋Š” ๋‘ ๊ฐ€์ง€ ํŒจํ„ด์„ ์„ž์–ด ์“ด๋‹ค: // (A) ์ง„ํ–‰์ž‘/์• ๋‹ˆ โ€” ์ƒˆ ํ™”๋ฅผ ์œ„๋กœ ์Œ“์•„์„œ ์‚ฌ์ดํŠธ nid=1์ด ์ตœ์‹  โ†’ ์ปจ๋ฒค์…˜๊ณผ ์ผ์น˜, ๋ณ€ํ™˜ ์—†์Œ. // (B) ์™„๊ฒฐ ๊ณผ๊ฑฐ์ž‘ โ€” 1ํ™”๋ถ€ํ„ฐ ์ˆœ์„œ๋Œ€๋กœ ์˜ฌ๋ ค ์‚ฌ์ดํŠธ nid=1์ด 1ํ™” โ†’ ์ •๊ทœํ™” ๋‹จ๊ณ„์—์„œ nid ๋’ค์ง‘๊ธฐ + siteNid ๋ณด์กด. // /api/play ๋Š” siteNid ์žˆ์œผ๋ฉด ๊ทธ๊ฑธ๋กœ ์‚ฌ์ดํŠธ์— ์ „๋‹ฌํ•ด ์‹ค์ œ ํšŒ์ฐจ์™€ ๋งค์นญ. // ์ •๋ฐฉํ–ฅ ๊ฐ์ง€๋Š” dateLabel("์ œNํ™”"/"์ œNํšŒ")์˜ N์ด nid์™€ ํ•จ๊ป˜ ์ฆ๊ฐ€ํ•˜๋Š”์ง€๋กœ ํŒ์ •. // detail HTML์„ ์„œ๋ฒ„์ธก์—์„œ ์ •๊ทœ์‹์œผ๋กœ ํŒŒ์‹ฑ (DOMParser ๋Œ€์ฒด). // raw CDP WS fetch๋Š” body ๋ฌธ์ž์—ด๋งŒ ์ฃผ๋ฏ€๋กœ ๋ธŒ๋ผ์šฐ์ € DOMParser๋ฅผ ๋ชป ์”€ โ†’ ์„œ๋ฒ„์—์„œ ์ถ”์ถœ (2026-07-01). function parseDetailHtml(html, id) { let title = null; const tm = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i); if (tm) { title = tm[1].replace(/&amp;/g, '&').trim() .replace(/\s*[-|]\s*.*?ํ‹ฐ๋น„์ฐฉ.*$/u, '') .replace(/\s*๋‹ค์‹œ๋ณด๊ธฐ\s*$/u, '').trim(); } let category = null; const cm = html.replace(/<[^>]+>/g, ' ').match(/(?:๋ถ„๋ฅ˜|ํƒ€์ž…|์œ ํ˜•|์žฅ๋ฅด)\s*[:๏ผš]\s*(๋“œ๋ผ๋งˆ|์˜ˆ๋Šฅ|์˜ํ™”|์• ๋‹ˆ|์‹œ์‚ฌ๊ต์–‘|๋‹คํ|ํ‚ค์ฆˆ|์Šคํฌ์ธ )/); if (cm) category = cm[1]; // ํšŒ์ฐจ ๋งํฌ: <a href=".../vod/play/id/ID/sid/S/nid/N...">label</a> const eps = []; const seen = new Set(); const re = new RegExp(`<a\\b[^>]*href="[^"]*\\/vod\\/play\\/id\\/${id}\\/sid\\/(\\d+)\\/nid\\/(\\d+)[^"]*"[^>]*>([\\s\\S]*?)<\\/a>`, 'gi'); let m; while ((m = re.exec(html))) { const sid = +m[1], nid = +m[2]; const key = sid + '_' + nid; if (seen.has(key)) continue; const label = m[3].replace(/<[^>]+>/g, '').replace(/&amp;/g, '&').replace(/&nbsp;/g, ' ').trim(); if (!label || label.length > 40 || label === '์˜์ƒ๋ณด๊ธฐ') continue; seen.add(key); eps.push({ sid, nid, label }); } return { title, category, episodes: eps }; } async function fetchEpisodes(id, opts = {}) { id = parseInt(id, 10); if (!id) return { error: 'bad id' }; // ํšŒ์ฐจ ๋ชฉ๋ก์€ ์ƒˆ ํ™”๊ฐ€ ์˜ฌ๋ผ์˜ค๋ฉด ๋ฐ”๋กœ ๋ฐ˜์˜๋˜์–ด์•ผ ํ•ด ์งง๊ฒŒ ์บ์‹œ (๊ฐ•์ œ ์ƒˆ๋กœ๊ณ ์นจ ์‹œ 0) if (!opts.nocache) { const cached = readCache(`ep_${id}.json`, 300); if (cached) return cached; } const d = await findLiveDomain(); if (!d.domain) return { error: 'no live domain' }; // DOM ํŒŒ์‹ฑ ๋ฐฉ์‹ (๋ผ๋ฒจ ํ…์ŠคํŠธ๊นŒ์ง€ ์ •ํ™•ํžˆ ์ถ”์ถœ). hang ๋ฐฉ์ง€ timeout. let result = null; // raw CDP WS fetch(ํ†ต๊ณผ ํƒญ)๋กœ detail HTML์„ ๋ฐ›์•„ ์„œ๋ฒ„์ธก ์ •๊ทœ์‹ ํŒŒ์‹ฑ (2026-07-01). // ๊ธฐ์กด ensureTvPage+page.evaluate(DOMParser)๋Š” Playwright๊ฐ€ ํ†ต๊ณผ ํƒญ์„ ๋ˆ„๋ฝํ•ด tvMutex hang์„ ์œ ๋ฐœํ–ˆ์Œ. result = await (async () => { const detailPath = `/index.php/vod/detail/id/${id}.html`; let lastErr = ''; for (let attempt = 0; attempt < 3; attempt++) { const r = await tvFetch(d.domain, detailPath); if (r.ok && r.status === 200) { const parsed = parseDetailHtml(r.body, id); if (parsed.episodes && parsed.episodes.length) return parsed; // ํšŒ์ฐจ๊ฐ€ ์•ˆ ์žกํ˜”์ง€๋งŒ ์ œ๋ชฉ์€ ์žˆ์„ ์ˆ˜ ์žˆ์Œ โ€” ๋งˆ์ง€๋ง‰ ์‹œ๋„๋ฉด ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜(๋นˆ ํšŒ์ฐจ ์ฒ˜๋ฆฌ๋จ) lastErr = 'no episode links parsed'; if (attempt === 2) return parsed; } else { if (r.code === 'CF_PASS_NEEDED') return { error: r.error, code: 'CF_PASS_NEEDED' }; lastErr = `fetch failed: ${r.status || r.error}`; } } return { error: lastErr || 'fetchEpisodes failed' }; })(); if (result?.error) return result; // ๋ผ๋ฒจ ์ •๊ทœํ™” + nid ์ •๋ฐฉํ–ฅ ์ž‘ํ’ˆ ๊ฐ์ง€/๋’ค์ง‘๊ธฐ. // ํด๋ผ์ด์–ธํŠธ๋Š” ์ผ๊ด€๋˜๊ฒŒ "nid=1=์ตœ์‹ ํ™”"๋ฅผ ๊ฐ€์ •ํ•˜๋ฏ€๋กœ(๋‹ค์Œ/์ด์ „ ํ™”ยทNEW ํŒ์ •ยท์ด์–ด๋ณด๊ธฐ ๋“ฑ), // ์‚ฌ์ดํŠธ๊ฐ€ ์ •๋ฐฉํ–ฅ(nid=1=1ํ™”)์œผ๋กœ ์ฃผ๋Š” ์™„๊ฒฐ ๊ณผ๊ฑฐ์ž‘์€ ์—ฌ๊ธฐ์„œ nid๋ฅผ ๋’ค์ง‘์–ด ์ปจ๋ฒค์…˜์„ ํ†ต์ผํ•œ๋‹ค. // ์›๋ณธ nid๋Š” siteNid ํ•„๋“œ์— ๋ณด์กดํ•˜๊ณ , /api/play ์—์„œ siteNid๊ฐ€ ์žˆ์œผ๋ฉด ๊ทธ๊ฑธ๋กœ ๋˜๋Œ๋ ค ์‚ฌ์ดํŠธ์— ์ „๋‹ฌ. // - dateLabel "์ œNํ™”"/"์ œNํšŒ"๊ฐ€ 2๊ฑด ์ด์ƒ์ด๋ฉด ์‚ฌ์ดํŠธ๊ฐ€ ๋ช…์‹œ์  ํšŒ์ฐจ ๋ฒˆํ˜ธ๋ฅผ ์ฃผ๋Š” ์ผ€์ด์Šค โ†’ ๊ทธ N์„ ์‹ ๋ขฐ. // - ๊ทธ ์™ธ(์งง์€ "Nํ™”" ๋˜๋Š” ๋‚ ์งœ ๋ผ๋ฒจ)๋Š” ๊ธฐ์กด์ฒ˜๋Ÿผ N-nid+1 ๋ณ€ํ™˜ (์‚ฌ์ดํŠธ๊ฐ€ ์œ„๋กœ ์Œ“๋Š” ์ง„ํ–‰์ž‘ ๊ฐ€์ •). const N = result.episodes.length; const reIsEpisodic = /^\d+ํ™”\s*$/; const reExplicitNum = /์ œ\s*(\d+)\s*[ํ™”ํšŒ]/; const explicitHits = result.episodes.filter(e => reExplicitNum.test(e.label || '')).length; const useExplicit = explicitHits >= 2; // ์ •๋ฐฉํ–ฅ(์‚ฌ์ดํŠธ nid=1 ์ด 1ํ™”) ๊ฐ์ง€: ๋ช…์‹œ ๋ฒˆํ˜ธ ์ผ€์ด์Šค์—์„œ nid ์ž‘์„์ˆ˜๋ก ํšŒ์ฐจ ๋ฒˆํ˜ธ๋„ ์ž‘์œผ๋ฉด ์ •๋ฐฉํ–ฅ. let reverseNid = false; if (useExplicit) { const first = result.episodes.find(e => e.nid === 1); const last = result.episodes.find(e => e.nid === N); const firstNum = first ? parseInt((first.label.match(reExplicitNum) || [])[1] || '0', 10) : 0; const lastNum = last ? parseInt((last.label.match(reExplicitNum) || [])[1] || '0', 10) : 0; if (firstNum && lastNum && firstNum < lastNum) reverseNid = true; } const normEps = result.episodes.map(e => { const orig = e.label || ''; let label = orig; let nid = e.nid; const siteNid = e.nid; if (useExplicit) { const m = orig.match(reExplicitNum); if (m) label = `${m[1]}ํ™”`; if (reverseNid) nid = N - e.nid + 1; // ์‚ฌ์ดํŠธ 1ํ™”(nid=1) โ†’ ์ •๊ทœํ™” nid=N } else if (!reIsEpisodic.test(orig)) { const epNum = N - e.nid + 1; label = `${epNum}ํ™”`; } return { sid: e.sid, nid, siteNid, label, dateLabel: orig }; }); // ์ •๊ทœํ™” ํ›„ nid asc ์ •๋ ฌ โ†’ nid=1์ด ์ตœ์‹ /ํฐ ํ™”์ˆ˜ normEps.sort((a, b) => a.sid - b.sid || a.nid - b.nid); let category = result.category || null; let poster = null; // detail์—์„œ ์นดํ…Œ๊ณ ๋ฆฌ ์ถ”์ถœ ์‹คํŒจํ•˜๋ฉด ์‚ฌ์ดํŠธ ๊ฒ€์ƒ‰์œผ๋กœ fallback. poster๋„ ๊ฐ™์ด ๊ฐ€์ ธ์˜ด. if (result.title) { for (let attempt = 0; attempt < 2 && (!category || !poster); attempt++) { try { const sr = await searchSite(result.title); if (sr && Array.isArray(sr.items) && sr.items.length) { const hit = sr.items.find(it => it.id === id) || sr.items.find(it => it.title === result.title) || sr.items[0]; if (hit) { if (!category && typeof hit.meta === 'string') { const m = hit.meta.match(/(๋“œ๋ผ๋งˆ|์˜ˆ๋Šฅ|์˜ํ™”|์• ๋‹ˆ|์‹œ์‚ฌ๊ต์–‘|๋‹คํ|ํ‚ค์ฆˆ|์Šคํฌ์ธ )/); if (m) category = m[1]; } if (!poster && hit.poster) poster = hit.poster; } } } catch (e) { console.warn(`[ep ${id}] search fallback attempt ${attempt + 1} failed:`, e.message); } if ((!category || !poster) && attempt === 0) await new Promise(r => setTimeout(r, 500)); } } // tvchak placeholder๋ฟ์ด๊ณ  ๊ฒ€์ƒ‰ fallback๋„ ์—†์œผ๋ฉด ์™ธ๋ถ€ ๋ฉ”ํƒ€ ์†Œ์Šค๋กœ ๋ณด๊ฐ•. // 1) ๋‚˜๋ฌด์œ„ํ‚ค โ€” ์‹œ์ฆŒ๋ณ„ ํฌ์Šคํ„ฐ ๋“ฑ ๋” ์ •ํ™•. i.namu.wiki ์ฐจ๋‹จ ํ™˜๊ฒฝ(์˜ˆ: PC)์—์„œ๋Š” // ํด๋ผ์ด์–ธํŠธ๊ฐ€ viaProxy(/img-proxy) ๊ฑฐ์ณ ๊ฐ€์ ธ์˜ด. if (!poster && result.title) { try { poster = await fetchNamuPoster(result.title); } catch (e) { console.warn(`[ep ${id}] namu poster failed:`, e.message); } } // 2) TMDb ํด๋ฐฑ โ€” namu์—์„œ ๋ชป ์ฐพ์€ ์ž‘ํ’ˆ์šฉ. image.tmdb.org๋Š” hotlink ์ž์œ . if (!poster && result.title) { try { poster = await fetchTmdbPoster(result.title); } catch (e) { console.warn(`[ep ${id}] tmdb poster failed:`, e.message); } } // ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ํ†ต๊ณผ๋งŒ category๋กœ ์ธ์ • โ€” ์‚ฌ์ดํŠธ๊ฐ€ "๊ธˆ์š”์ผ" ๊ฐ™์€ ์š”์ผ์„ vod_class๋กœ ์ฃผ๋Š” ์ผ€์ด์Šค ์ฐจ๋‹จ. if (category) { const m = String(category).match(/(๋“œ๋ผ๋งˆ|์˜ˆ๋Šฅ|์˜ํ™”|์• ๋‹ˆ|์‹œ์‚ฌ๊ต์–‘|๋‹คํ|ํ‚ค์ฆˆ|์Šคํฌ์ธ )/); category = m ? m[1] : null; } const out = { id, title: result.title, category, poster, count: normEps.length, episodes: normEps, domain: d.domain, checked_at: new Date().toISOString(), }; writeCache(`ep_${id}.json`, out); return out; } // โ”€โ”€โ”€โ”€โ”€ ๋‚˜๋ฌด์œ„ํ‚ค ํฌ์Šคํ„ฐ ์ถ”์ถœ โ”€โ”€โ”€โ”€โ”€ // title์„ ๊ทธ๋Œ€๋กœ /w/{title}์— ๋ถ™์—ฌ og:image ๊ฐ€์ ธ์˜ด. ์˜๊ตฌ ์บ์‹œ. // ๋‚˜๋ฌด์œ„ํ‚ค ๊ธฐ๋ณธ ๋กœ๊ณ /anonymous ํŒจํ„ด์€ ์ œ์™ธ. ๋™์Œ์ด์˜์–ด ํŽ˜์ด์ง€๋ฉด og:image๊ฐ€ ์ผ๋ฐ˜ ๋กœ๊ณ ์ผ ์ˆ˜ ์žˆ์Œ. const NAMU_DEFAULT_RE = /\/(anonymous|logo|namuwiki|namu_logo|default)\b|i\.namu\.wiki\/i\/[A-Za-z0-9_-]{0,20}\./i; // ์ œ๋ชฉ ๋ณ€ํ˜• โ€” ๋‚˜๋ฌด์œ„ํ‚ค์— ์ •ํ™•ํžˆ ์ผ์น˜ํ•˜๋Š” ํŽ˜์ด์ง€ ์—†์„ ๋•Œ ์‹œ๋„ํ•  ํ›„๋ณด ์ƒ์„ฑ. // ๋™์Œ์ด์˜์–ด ์ฒ˜๋ฆฌ: "ํ—ˆ์ˆ˜์•„๋น„"๋Š” ์ผ๋ฐ˜๋ช…์‚ฌ ํŽ˜์ด์ง€์™€ ๋“œ๋ผ๋งˆ ํŽ˜์ด์ง€(ํ—ˆ์ˆ˜์•„๋น„(๋“œ๋ผ๋งˆ))๊ฐ€ ๋ถ„๋ฆฌ. // suffix ํ›„๋ณด๋ฅผ ์›์ œ๋ชฉ๋ณด๋‹ค ๋จผ์ € ์‹œ๋„ โ€” ๋น„์šฉ์€ ์บ์‹œ๋‹น 1ํšŒ๋ฟ์ด๋ผ ์ •ํ™•๋„ ์šฐ์„ . const NAMU_DISAMBIG_SUFFIXES = ['๋“œ๋ผ๋งˆ', '์˜ํ™”', '์˜ˆ๋Šฅ', '์• ๋‹ˆ๋ฉ”์ด์…˜', '๋งŒํ™”', 'TV์‡ผ', '์‹œ๋ฆฌ์ฆˆ']; function namuTitleCandidates(title) { const out = []; const seen = new Set(); const push = (t) => { t = String(t || '').trim(); if (t && !seen.has(t)) { seen.add(t); out.push(t); } }; const base = String(title).trim(); // 1์ˆœ์œ„: ์›์ œ๋ชฉ + disambiguation suffix (๋“œ๋ผ๋งˆ ํŽ˜์ด์ง€ ์šฐ์„ ) if (!/\([^)]+\)$/.test(base)) { for (const sfx of NAMU_DISAMBIG_SUFFIXES) push(`${base}(${sfx})`); } // 2์ˆœ์œ„: ์›์ œ๋ชฉ push(base); // ๊ด„ํ˜ธ ์•ˆ ์ค„์ž„๋ง ์ถ”์ถœ: "...(๋‚˜์†”์‚ฌ๊ณ„)" โ†’ "๋‚˜์†”์‚ฌ๊ณ„" const parenAll = base.match(/\(([^)]+)\)/g) || []; for (const p of parenAll) push(p.slice(1, -1).trim()); // ๊ด„ํ˜ธ ๋ถ€๋ถ„ ์ œ๊ฑฐ: "๋‚˜๋Š” SOLO ๊ทธํ›„ ์‚ฌ๋ž‘์€ ๊ณ„์†๋œ๋‹ค(๋‚˜์†”์‚ฌ๊ณ„)" โ†’ "๋‚˜๋Š” SOLO ๊ทธํ›„ ์‚ฌ๋ž‘์€ ๊ณ„์†๋œ๋‹ค" const bareNoParen = base.replace(/\s*\([^)]*\)\s*/g, ' ').trim(); push(bareNoParen); // ์‹œ์ฆŒ ํ‘œ๊ธฐ ์ œ๊ฑฐ: "ํžˆ๋“ ์‹ฑ์–ด8" โ†’ "ํžˆ๋“ ์‹ฑ์–ด" push(base.replace(/\s*\d+\s*$/, '').trim()); // ์‹œ๋ฆฌ์ฆˆ ์ด๋ฆ„๋งŒ (์ฒซ ์–ด์ ˆ): "๋‚˜๋Š” SOLO ๊ทธํ›„ ์‚ฌ๋ž‘์€ ๊ณ„์†๋œ๋‹ค" โ†’ "๋‚˜๋Š” SOLO" const words = base.split(/\s+/); if (words.length >= 2) push(words.slice(0, 2).join(' ')); // ๋„์–ด์“ฐ๊ธฐ ๋ณ€ํ˜• โ€” ์‚ฌ์ดํŠธ๋Š” "๋‚˜ํ˜ผ์ž ์‚ฐ๋‹ค"๋กœ, ๋‚˜๋ฌด์œ„ํ‚ค๋Š” "๋‚˜ ํ˜ผ์ž ์‚ฐ๋‹ค"๋กœ ํ‘œ๊ธฐ๋˜๋Š” ์ผ€์ด์Šค. // - ๊ณต๋ฐฑ ๋ชจ๋‘ ์ œ๊ฑฐ: "๋‚˜ํ˜ผ์ž ์‚ฐ๋‹ค" โ†’ "๋‚˜ํ˜ผ์ž์‚ฐ๋‹ค" // - ์ฒซ ํ•œ๊ธ€ 1๊ธ€์ž ๋’ค ๊ณต๋ฐฑ ์‚ฝ์ž…: "๋‚˜ํ˜ผ์ž ์‚ฐ๋‹ค" โ†’ "๋‚˜ ํ˜ผ์ž ์‚ฐ๋‹ค" const noSpace = base.replace(/\s+/g, ''); push(noSpace); const m1 = base.match(/^([๊ฐ€-ํžฃ])([๊ฐ€-ํžฃ].*)/); if (m1) { push(`${m1[1]} ${m1[2]}`); // disambiguation suffix๋„ ๋™์ผ ๋ณ€ํ˜•์œผ๋กœ if (!/\([^)]+\)$/.test(base)) { for (const sfx of NAMU_DISAMBIG_SUFFIXES) push(`${m1[1]} ${m1[2]}(${sfx})`); } } return out.filter(t => t.length >= 2); } // TMDb ๊ฒ€์ƒ‰ ํ›„๋ณด ์ƒ์„ฑ โ€” ์›์ œ๋ชฉ + ์ผ๋ฐ˜์  ๋ณ€ํ˜•. // ์˜ˆ: "ํžˆ๋“ ์‹ฑ์–ด8" โ†’ ["ํžˆ๋“ ์‹ฑ์–ด8","ํžˆ๋“ ์‹ฑ์–ด"], "...(๋‚˜์†”์‚ฌ๊ณ„)" โ†’ ["...(๋‚˜์†”์‚ฌ๊ณ„)","..."] function tmdbTitleCandidates(title) { const base = String(title).trim(); const out = []; const seen = new Set(); const push = (t) => { t = String(t || '').trim(); if (t && !seen.has(t)) { seen.add(t); out.push(t); } }; push(base); // ๋์— ์‹œ์ฆŒ ์ˆซ์ž ์ œ๊ฑฐ: "ํžˆ๋“ ์‹ฑ์–ด8" โ†’ "ํžˆ๋“ ์‹ฑ์–ด" push(base.replace(/\s*\d+\s*$/, '').trim()); // ๋์— ์‹œ์ฆŒ ํ‘œ๊ธฐ ์ œ๊ฑฐ: "...์‹œ์ฆŒ2" / "...S2" push(base.replace(/\s*(์‹œ์ฆŒ\s*\d+|S\d+)\s*$/, '').trim()); // ๊ด„ํ˜ธ ์•ˆ ์ค„์ž„๋ง ์ œ๊ฑฐ: "๋‚˜๋Š” SOLO ...(๋‚˜์†”์‚ฌ๊ณ„)" โ†’ "๋‚˜๋Š” SOLO ..." push(base.replace(/\s*\([^)]*\)\s*/g, ' ').trim()); // SOLO โ†” ์†”๋กœ (ํ•œ์˜ ํ˜ผ์šฉ) if (/SOLO/i.test(base)) push(base.replace(/SOLO/gi, '์†”๋กœ')); if (/์†”๋กœ/.test(base)) push(base.replace(/์†”๋กœ/g, 'SOLO')); return out.filter(t => t.length >= 2); } // TMDb (themoviedb.org) ํฌ์Šคํ„ฐ ๊ฒ€์ƒ‰ โ€” namu ์ฐจ๋‹จ ์šฐํšŒ์šฉ. TMDB_API_KEY ํ™˜๊ฒฝ๋ณ€์ˆ˜ ํ•„์š”. // image.tmdb.org๋Š” hotlink ํ—ˆ์šฉ์ด๋ผ ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์ง์ ‘ src๋กœ ์‚ฌ์šฉ ๊ฐ€๋Šฅ. // /search/multi๋กœ ์˜ํ™”ยทTV ํ•œ ๋ฒˆ์— ๊ฒ€์ƒ‰, ์ฒซ ๊ฒฐ๊ณผ์˜ poster_path ์‚ฌ์šฉ. async function fetchTmdbPoster(title) { title = String(title || '').trim(); if (!title) return null; const apiKey = process.env.TMDB_API_KEY; if (!apiKey) return null; const cacheFile = `tmdb_poster_${Buffer.from(title).toString('base64').slice(0, 80).replace(/[+/=]/g, '_')}.json`; const cached = readCachePermanent(cacheFile); if (cached) return cached.poster || null; const candidates = tmdbTitleCandidates(title); try { const headers = apiKey.startsWith('eyJ') ? { 'Authorization': `Bearer ${apiKey}`, 'Accept': 'application/json' } // v4 Read Token (JWT) : null; let poster = null; for (const cand of candidates) { const url = `https://api.themoviedb.org/3/search/multi?query=${encodeURIComponent(cand)}&language=ko-KR&include_adult=false`; const finalUrl = headers ? url : `${url}&api_key=${encodeURIComponent(apiKey)}`; const resp = await fetch(finalUrl, { headers: headers || {} }); if (!resp.ok) { console.warn(`[tmdb] "${cand}" โ†’ HTTP ${resp.status}`); continue; } const data = await resp.json(); const hit = (data.results || []).find(r => r.poster_path && (r.media_type === 'tv' || r.media_type === 'movie')); if (hit?.poster_path) { poster = `https://image.tmdb.org/t/p/w500${hit.poster_path}`; console.log(`[tmdb] "${title}" via "${cand}" โ†’ ${hit.media_type}/${hit.id} โ†’ ${poster.slice(0, 70)}`); break; } } if (!poster) console.warn(`[tmdb] "${title}" no result (tried ${candidates.length})`); writeCache(cacheFile, { poster, checked_at: new Date().toISOString() }); return poster; } catch (e) { console.warn(`[tmdb] "${title}" error:`, e.message); return null; } } async function fetchNamuPoster(title) { title = String(title || '').trim(); if (!title) return null; // v2: disambiguation suffix ์šฐ์„  + og:title ๊ฒ€์ฆ (2026-05-24). v1 ์บ์‹œ๋Š” ์ž๋™ ๋ฌดํšจ. const cacheFile = `namu_poster_v2_${Buffer.from(title).toString('base64').slice(0, 80).replace(/[+/=]/g, '_')}.json`; const cached = readCachePermanent(cacheFile); if (cached) return cached.poster || null; // ๋‚˜๋ฌด์œ„ํ‚ค๋Š” datacenter IP๋ฅผ Cloudflare๋กœ 403ํ•˜๋ฏ€๋กœ, SOCKS5_PROXY ์žˆ์œผ๋ฉด NAS ๊ฒฝ์œ . // Node 22+ fetch๋Š” dispatcher ์˜ต์…˜์„ ๋ฐ›์ง€ ์•Š์œผ๋ฏ€๋กœ _socksAgent๋ฅผ ์“ฐ๋ ค๋ฉด raw https.request. // ๊ฐ„๋‹จํ•˜๊ฒŒ๋Š” page.evaluate(๊ฐ™์€ origin)๋กœ ์šฐํšŒ โ€” anilife ์ปจํ…์ŠคํŠธ(์ด๋ฏธ SOCKS5 ํ™œ์„ฑ)๋ฅผ ๋นŒ๋ ค๋„ ๋˜์ง€๋งŒ // ๋ณ„๋„ ์ปจํ…์ŠคํŠธ ๋งŒ๋“ค์–ด ๊น”๋”ํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ•˜๊ณ  ์ฆ‰์‹œ ๋‹ซ๋Š”๋‹ค. try { if (!_browser) await getContext(); const ctx = await _browser.newContext({ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', locale: 'ko-KR', }); let poster = null; const candidates = namuTitleCandidates(title); try { const page = await ctx.newPage(); for (const cand of candidates) { try { const resp = await withTimeout(page.goto(`https://namu.wiki/w/${encodeURIComponent(cand)}`, { waitUntil: 'domcontentloaded', timeout: 15000 }), 16000, `namu ${cand}`); const status = resp?.status() || 0; if (status < 200 || status >= 400) { console.warn(`[namu] "${cand}" status=${status}`); continue; } // og:image์™€ og:title์„ ํ•จ๊ป˜ ์ถ”์ถœ โ€” title๋กœ ๋™์Œ์ด์˜์–ด ๊ฒ€์ฆ const meta = await page.evaluate(() => { const img = document.querySelector('meta[property="og:image"]')?.getAttribute('content') || null; const ttl = document.querySelector('meta[property="og:title"]')?.getAttribute('content') || null; return { img, ttl }; }); let p = meta.img; if (p && p.startsWith('//')) p = 'https:' + p; if (p && /\.svg$/i.test(p)) p = null; if (p && NAMU_DEFAULT_RE.test(p)) p = null; if (!p) continue; // ํ›„๋ณด๊ฐ€ disambiguation suffix๋ฅผ ๊ฐ€์กŒ์œผ๋ฉด (์˜ˆ: "ํ—ˆ์ˆ˜์•„๋น„(๋“œ๋ผ๋งˆ)") og:title๋„ ๊ฐ™์€ ํ˜•ํƒœ์—ฌ์•ผ ์ •์ƒ. // ๋‚˜๋ฌด์œ„ํ‚ค๋Š” ์กด์žฌํ•˜์ง€ ์•Š๋Š” ํŽ˜์ด์ง€๋กœ ๊ฐ€๋„ 200 + ํŽธ์ง‘์ฐฝ์„ ๋ณด์—ฌ์ฃผ๋ฏ€๋กœ og:title ์ผ์น˜ ๊ฒ€์ฆ ํ•„์š”. const candHasSfx = /\([^)]+\)$/.test(cand); const ttl = meta.ttl || ''; if (candHasSfx) { // og:title์ด ์ •ํ™•ํžˆ ํ›„๋ณด์™€ ์ผ์น˜ (๋˜๋Š” ํ›„๋ณด๋กœ ์‹œ์ž‘) ํ•ด์•ผ ์ฑ„ํƒ if (!ttl || !ttl.startsWith(cand)) { console.warn(`[namu] "${cand}" og:title mismatch ("${ttl.slice(0,40)}") โ€” skip`); continue; } } poster = p; console.log(`[namu] "${title}" โ†’ "${cand}" (og:title="${ttl.slice(0,30)}") โ†’ ${p.slice(0, 60)}`); break; } catch (e) { console.warn(`[namu] "${cand}" goto failed:`, e.message); } } await page.close().catch(() => {}); } finally { await ctx.close().catch(() => {}); } writeCache(cacheFile, { poster, checked_at: new Date().toISOString() }); return poster; } catch (e) { console.warn(`[namu] ${title} error:`, e.message); return null; } } // โ”€โ”€โ”€โ”€โ”€ ์žฌ์ƒ ์ •๋ณด (player_aaaa) โ”€โ”€โ”€โ”€โ”€ function parsePlayerAaaa(html) { const idx = html.indexOf('player_aaaa'); if (idx < 0) return null; const eqIdx = html.indexOf('=', idx); if (eqIdx < 0) return null; // tvchak204๋Š” ๋‘ ๊ฐ€์ง€ ์ธ์ฝ”๋”ฉ์„ ๋ฒˆ๊ฐˆ์•„ ์คŒ: // (A) ์ •์ƒ: player_aaaa={"flag":"play",...} // (B) ์ด์Šค์ผ€์ดํ”„: player_aaaa={\"flag\":\"play\",...} โ† JS ๋ฌธ์ž์—ด๋กœ ํ•œ ๋ฒˆ ๋” ๊ฐ์‹ธ์ง„ ํ˜•ํƒœ // (B)๋Š” ์ค‘๊ด„ํ˜ธ ์นด์šดํŒ…์ด \" ์•ˆ์˜ ๊ด„ํ˜ธ๊นŒ์ง€ ์„ธ์„œ ๊นจ์ง€๋ฏ€๋กœ, ๋จผ์ € ์ด์Šค์ผ€์ดํ”„ ์—ฌ๋ถ€๋ฅผ ํŒ์ •ํ•ด ์–ธ์ด์Šค์ผ€์ดํ”„ ํ›„ ํŒŒ์‹ฑ. const after = html.slice(eqIdx + 1, eqIdx + 40); const isEscaped = /^\s*\{\s*\\+"/.test(after) || after.includes('\\"flag\\"'); // ๊ฐ’์˜ ๋(}) ์ฐพ๊ธฐ โ€” ์ด์Šค์ผ€์ดํ”„ ์—ฌ๋ถ€์™€ ๋ฌด๊ด€ํ•˜๊ฒŒ ๊ท ํ˜• ์นด์šดํŒ…ํ•˜๋˜, escaped๋ฉด \" ๋ฅผ ๋ฌด์‹œ. let depth = 0, start = -1, end = -1, inStr = false; for (let i = eqIdx; i < html.length; i++) { const c = html[i]; const prev = html[i - 1]; if (c === '"' && prev !== '\\') inStr = !inStr; if (inStr) continue; if (c === '{') { if (depth === 0) start = i; depth++; } else if (c === '}') { depth--; if (depth === 0) { end = i + 1; break; } } } if (start < 0 || end < 0) return null; let raw = html.slice(start, end); // 1์ฐจ: ๊ทธ๋Œ€๋กœ (์ •์ƒ 22267 ๋ณ€์ข…) try { return JSON.parse(raw); } catch {} // 2์ฐจ: 24650 ๋ณ€์ข… โ€” ์ „์ฒด๊ฐ€ JSON ๋ฌธ์ž์—ด๋กœ ํ•œ ๋ฒˆ ๋” ์ธ์ฝ”๋”ฉ๋จ. // `{\"flag\":...}` โ†’ ๊ฐ€์šด๋ฐ๋ฅผ ๋”ฐ์˜ดํ‘œ๋กœ ๊ฐ์‹ธ JSON.parse๋กœ unescape โ†’ ๋‹ค์‹œ JSON.parse. try { const inner = JSON.parse('"' + raw.slice(1, -1) + '"'); return JSON.parse('{' + inner + '}'); } catch {} return null; } async function fetchPlay(id, sid, nid) { id = parseInt(id, 10); sid = parseInt(sid, 10) || 1; nid = parseInt(nid, 10) || 1; if (!id) return { error: 'bad id' }; // ์žฌ์ƒ URL์€ ์ผ๋ถ€ ํšŒ์ฐจ์—์„œ ๋‹จ๊ธฐ ํ† ํฐ ํ˜•ํƒœ๋กœ ๋ฐœ๊ธ‰๋˜๋ฏ€๋กœ ์บ์‹œํ•˜์ง€ ์•Š๋Š”๋‹ค. // (์บ์‹œํ•˜๋ฉด ๋งŒ๋ฃŒ๋œ URL์ด ๊ณ„์† ๋ฐ˜ํ™˜๋˜์–ด 404 โ†’ ๋น„๋””์˜ค 'Format error') const d = await findLiveDomain(); if (!d.domain) return { error: 'no live domain' }; // tvchak fetch๋Š” NAS zapret desync๊ฐ€ ํฐ ClientHello์—์„œ ๊ฐ„ํ— ์‹คํŒจ(KT SNI ์ฐจ๋‹จ ์žฌ๋…ธ์ถœ)ํ•  ์ˆ˜ ์žˆ๋‹ค. // ๋งค ์—ฐ๊ฒฐ์€ ์ƒˆ TLS ํ•ธ๋“œ์…ฐ์ดํฌ๋ผ ์žฌ์‹œ๋„ํ•˜๋ฉด ๋Œ€๋ถ€๋ถ„ ์„ฑ๊ณต โ†’ ์ตœ๋Œ€ 4ํšŒ ์žฌ์‹œ๋„๋กœ ํก์ˆ˜. const playPath = `/index.php/vod/play/id/${id}/sid/${sid}/nid/${nid}.html`; let cfg = null; let lastErr = ''; for (let attempt = 0; attempt < 3; attempt++) { const r = await tvFetch(d.domain, playPath); if (!r.ok) console.warn(`[play] id=${id} attempt ${attempt} fail: status=${r.status||''} ${r.error||''} ${r.code||''}`); if (r.ok && r.status === 200) { const parsed = parsePlayerAaaa(r.body); if (parsed) { cfg = parsed; break; } lastErr = 'player_aaaa not found'; } else { // ํ†ต๊ณผ ํƒญ ํ† ํฐ ๋งŒ๋ฃŒ/๋ฏธํ†ต๊ณผ โ†’ ์žฌ์‹œ๋„ํ•ด๋„ ์†Œ์šฉ์—†์Œ. ์ฆ‰์‹œ code ์ „ํŒŒํ•ด ํ”„๋ก ํŠธ๊ฐ€ ์•ˆ๋‚ดํ•˜๊ฒŒ. if (r.code === 'CF_PASS_NEEDED') return { error: r.error, code: 'CF_PASS_NEEDED' }; lastErr = `fetch failed: ${r.status || r.error}`; } } if (!cfg) return { error: lastErr || 'player_aaaa not found' }; if (cfg.id != null && +cfg.id !== id) { return { error: `id mismatch: requested ${id}, got ${cfg.id}` }; } if (cfg.nid != null && +cfg.nid !== nid) { return { error: `nid mismatch: requested ${nid}, got ${cfg.nid}` }; } // tvchak๊ฐ€ ์ผ๋ถ€ ํšŒ์ฐจ์—์„œ url์— ๋งŒ๋ฃŒ๋œ ๋‹จ๊ธฐํ† ํฐ์„, url_next์— ์‹ค์ œ ํŒŒ์ผ์„ ๋„ฃ๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋‹ค. // HEAD๋กœ ์‚ด์•„์žˆ๋Š” URL์„ ์„ ํƒ. const referer = `https://${d.domain}/`; let chosenUrl = cfg.url || null; let fallback = false; if (chosenUrl) { const ok = await checkUrlAlive(chosenUrl, referer); if (!ok && cfg.url_next) { const ok2 = await checkUrlAlive(cfg.url_next, referer); if (ok2) { chosenUrl = cfg.url_next; fallback = true; } } } else if (cfg.url_next) { chosenUrl = cfg.url_next; fallback = true; } return { id, sid, nid, url: chosenUrl, url_raw: cfg.url || null, url_next: cfg.url_next || null, fallback, link_next: cfg.link_next || null, link_pre: cfg.link_pre || null, vod_data: cfg.vod_data || null, encrypt: cfg.encrypt, from: cfg.from, domain: d.domain, referer, checked_at: new Date().toISOString(), }; } function checkUrlAlive(target, referer) { return new Promise((resolve) => { try { const t = new URL(target); const req = https.request({ hostname: t.hostname, port: t.port || 443, path: t.pathname + t.search, method: 'HEAD', headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', 'Referer': referer, }, rejectUnauthorized: false, }, (res) => { resolve(res.statusCode >= 200 && res.statusCode < 400); res.resume(); }); req.on('error', () => resolve(false)); req.setTimeout(5000, () => { req.destroy(); resolve(false); }); req.end(); } catch { resolve(false); } }); } // โ”€โ”€โ”€โ”€โ”€ ํ‚ค๋…ธ๋ผ์ด์ธ  ๋žญํ‚น โ”€โ”€โ”€โ”€โ”€ // period: daily|weekly|monthly // opts.fetchIfMissing: true๋ฉด ์บ์‹œ ์—†๊ฑฐ๋‚˜ ๋งŒ๋ฃŒ์ผ ๋•Œ ์ƒˆ๋กœ ๊ฐ€์ ธ์˜ด (prefetch ์ „์šฉ). // ๊ธฐ๋ณธ์€ false โ€” ์‚ฌ์šฉ์ž ์š”์ฒญ์€ ์บ์‹œ๋งŒ ์‚ฌ์šฉ (๋А๋ ค์ง€์ง€ ์•Š๊ฒŒ). async function fetchKinoRanking(period, opts = {}) { period = period || 'daily'; const cacheFile = `kino_${period}.json`; // ์ผ๊ฐ„=ํ•˜๋ฃจ 1ํšŒ, ์ฃผ๊ฐ„=์ฃผ 1ํšŒ(์›”~์ผ), ์›”๊ฐ„=์›” 1ํšŒ. ํ•œ๋ฒˆ ๊ฐฑ์‹ ๋˜๋ฉด ํ•ด๋‹น ๊ตฌ๊ฐ„ ์•ˆ์—์„œ๋Š” ์บ์‹œ ์‚ฌ์šฉ. const bucket = period === 'weekly' ? 'week' : period === 'monthly' ? 'month' : 'day'; // force=1์ด๋ฉด ์บ์‹œ ๋ฌด์‹œํ•˜๊ณ  ๊ฐ•์ œ ์žฌ์กฐํšŒ if (!opts.force) { const cached = readCacheSameBucket(cacheFile, bucket); // ๋นˆ items๊ฐ€ ์บ์‹œ๋˜์–ด ์žˆ๋‹ค๋ฉด ๋ฌดํšจ๋กœ ๊ฐ„์ฃผํ•˜๊ณ  ๋‹ค์‹œ ๊ฐ€์ ธ์˜ด (์Šคํฌ๋ž˜ํ•‘ ์‹คํŒจ ์‹œ ๋นˆ ๊ฒฐ๊ณผ๊ฐ€ ์บ์‹ฑ๋˜๋Š” ์‚ฌ๊ณ  ๋ฐฉ์ง€) if (cached && cached.items && cached.items.length > 0) return cached; // ์‚ฌ์šฉ์ž ์š”์ฒญ ๊ฒฝ๋กœ: ๋งŒ๋ฃŒ๋œ ์บ์‹œ๋ผ๋„ stale๋กœ ๋ฐ˜ํ™˜, ์ƒˆ๋กœ ๊ฐ€์ ธ์˜ค์ง€ ์•Š์Œ. if (!opts.fetchIfMissing) { const stale = readCachePermanent(cacheFile); if (stale && stale.items && stale.items.length > 0) return { ...stale, stale: true }; return { period, items: [], pending: true }; } } // ์ผ๊ฐ„/์ฃผ๊ฐ„/์›”๊ฐ„ ๋ชจ๋‘ ๋™์ผํ•˜๊ฒŒ ?period= ์ฟผ๋ฆฌ ์‚ฌ์šฉ (์˜ˆ์ „์—” daily๋งŒ path-only์˜€๋Š”๋ฐ ๋™์ž‘์€ ๊ฐ™์Œ) const url = `https://m.kinolights.com/ranking/kino?period=${period}`; // ํ‚ค๋…ธ๋ผ์ด์ธ ์šฉ ๋ณ„๋„ context (tvchak ๋ผ์šฐํŠธ ์ฐจ๋‹จ ์˜ํ–ฅ X) if (!_browser) await getContext(); const ctx = await _browser.newContext({ userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1', locale: 'ko-KR', viewport: { width: 390, height: 2400 }, // 100์œ„๊นŒ์ง€ ๋‹ค ๋ณด์ด๊ฒŒ ๊ธธ๊ฒŒ }); const page = await ctx.newPage(); try { // ํฐํŠธ/๋ฏธ๋””์–ด๋งŒ ์ฐจ๋‹จ (์ด๋ฏธ์ง€๋Š” lazy-load ํŠธ๋ฆฌ๊ฑฐ์— ํ•„์š”) await page.route('**/*', (route) => { const t = route.request().resourceType(); if (t === 'font' || t === 'media') return route.abort(); return route.continue(); }); await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 25000 }); // ์Šคํฌ๋กค๋กœ ๋ชจ๋“  ์นด๋“œ ๋ Œ๋” ํŠธ๋ฆฌ๊ฑฐ await page.evaluate(async () => { await new Promise(r => setTimeout(r, 500)); window.scrollTo(0, document.body.scrollHeight); await new Promise(r => setTimeout(r, 500)); window.scrollTo(0, 0); }); // 2026-07: ํ‚ค๋…ธ๋ผ์ด์ธ  Tailwind ๋ฆฌ๋‰ด์–ผ โ€” ul.content-ranking-list>li ๊ตฌ์กฐ๊ฐ€ ์‚ฌ๋ผ์ง€๊ณ  // ๋žญํ‚น ์นด๋“œ๊ฐ€ a[href^="/season/{id}"] (๋‚ด๋ถ€ <article>) ๋กœ ๋ฐ”๋€œ. // ์ œ๋ชฉ์€ ์นด๋“œ innerText๊ฐ€ ์•„๋‹ˆ๋ผ a[aria-label="์ œ๋ชฉ, ๋žญํ‚น ์นด๋“œ"] / img[alt] ์— ์žˆ์Œ. const CARD_SEL = 'a[href^="/season/"]'; await page.waitForSelector(CARD_SEL, { timeout: 15000 }).catch(() => null); let status = await page.evaluate((sel) => ({ cardCount: document.querySelectorAll(sel).length, bodyLen: document.body.innerText.length, title: document.title, bodyHead: document.body.innerText.slice(0, 200), }), CARD_SEL).catch(() => ({ err: 'evaluate failed' })); console.log('[kino]', period, status); // SPA ๋ Œ๋” ํƒ€์ด๋ฐ ์ด์Šˆ๋กœ ์นด๋“œ๊ฐ€ 0์ด๋ฉด ํ•œ ๋ฒˆ ๋” ์Šคํฌ๋กค + ๋Œ€๊ธฐ ํ›„ ์žฌ์‹œ๋„ โ€” ๋นˆ ๊ฒฐ๊ณผ ์บ์‹ฑ ์‚ฌ๊ณ  ๋ฐฉ์ง€ if (!status.cardCount) { console.warn(`[kino] ${period} cards=0, retrying with extra scroll`); await page.evaluate(async () => { for (let i = 0; i < 3; i++) { window.scrollTo(0, document.body.scrollHeight); await new Promise(r => setTimeout(r, 700)); } window.scrollTo(0, 0); }); await page.waitForSelector(CARD_SEL, { timeout: 10000 }).catch(() => null); status = await page.evaluate((sel) => ({ cardCount: document.querySelectorAll(sel).length, }), CARD_SEL).catch(() => ({})); console.log('[kino]', period, 'retry status:', status); } const items = await page.evaluate((sel) => { const cards = [...document.querySelectorAll(sel)]; const out = []; const seen = new Set(); for (const a of cards) { const href = a.getAttribute('href') || ''; const id = a.getAttribute('id') || (href.match(/\/season\/(\d+)/) || [])[1]; if (!id || seen.has(id)) continue; // ์ƒ๋‹จ ์บ๋Ÿฌ์…€/์ค‘๋ณต ์นด๋“œ ์ œ๊ฑฐ // ์ œ๋ชฉ: aria-label("์ œ๋ชฉ, ๋žญํ‚น ์นด๋“œ")์—์„œ, ์—†์œผ๋ฉด img alt let title = (a.getAttribute('aria-label') || '').replace(/,?\s*๋žญํ‚น\s*์นด๋“œ\s*$/, '').trim(); if (!title) { const im = a.querySelector('img[alt]'); title = im ? (im.getAttribute('alt') || '').trim() : ''; } if (!title) continue; // ํฌ์Šคํ„ฐ: ์นด๋“œ ๋‚ด file.kinolights.com ์ฒซ img let poster = null; for (const img of a.querySelectorAll('img')) { const src = img.getAttribute('src') || img.getAttribute('data-src') || ''; if (/file\.kinolights\.com/.test(src)) { poster = src; break; } } if (poster && poster.startsWith('//')) poster = 'https:' + poster; seen.add(id); // href๋Š” ํ”„๋ก ํŠธ/์ƒ์„ธ API ํ˜ธํ™˜์„ ์œ„ํ•ด /title/{id} ๋กœ ์ •๊ทœํ™” (ํ”„๋ก ํŠธ๊ฐ€ /title/(\d+) ์ถ”์ถœ) // rank๋Š” ์นด๋“œ์— ์‹ ๋ขฐํ•  ์ˆซ์ž๊ฐ€ ์—†์–ด DOM ๋…ธ์ถœ ์ˆœ์„œ๋กœ ๋งค๊น€ (ํ”„๋ก ํŠธ๋„ i+1 ์‚ฌ์šฉ). out.push({ rank: out.length + 1, title, category: null, year: null, href: `/title/${id}`, poster }); if (out.length >= 10) break; } return out; }, CARD_SEL); const result = { period, items, checked_at: new Date().toISOString() }; // ๋นˆ items๋Š” ์บ์‹œํ•˜์ง€ ์•Š์Œ โ€” ์Šคํฌ๋ž˜ํ•‘ ์‹คํŒจ๊ฐ€ day ๋ฒ„ํ‚ท ๋™์•ˆ ๊ตณ์–ด๋ฒ„๋ฆฌ๋Š” ๊ฒƒ ๋ฐฉ์ง€ if (items && items.length > 0) writeCache(cacheFile, result); else console.warn(`[kino] ${period} empty items โ€” not caching`); return result; } catch (e) { return { error: String(e.message || e), period }; } finally { await page.close().catch(() => {}); await ctx.close().catch(() => {}); } } // โ”€โ”€โ”€โ”€โ”€ ํ‚ค๋…ธ๋ผ์ด์ธ  ์ž‘ํ’ˆ ์ƒ์„ธ โ”€โ”€โ”€โ”€โ”€ async function fetchKinoDetail(titleId, opts = {}) { titleId = parseInt(titleId, 10); if (!titleId) return { error: 'bad id' }; const cacheFile = `kino_detail_${titleId}.json`; // ์ž‘ํ’ˆ ์ƒ์„ธ ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ๋Š” ๊ฑฐ์˜ ์•ˆ ๋ฐ”๋€Œ๋ฏ€๋กœ ํ•œ๋ฒˆ ๊ฐ€์ ธ์˜ค๋ฉด ์˜๊ตฌ ์‚ฌ์šฉ. const cached = readCachePermanent(cacheFile); if (cached) return cached; // ์‚ฌ์šฉ์ž ์š”์ฒญ์€ ์บ์‹œ ๋ฏธ์Šค์—ฌ๋„ ์ƒˆ๋กœ ๊ฐ€์ ธ์˜ค์ง€ ์•Š์Œ. if (!opts.fetchIfMissing) return { id: titleId, pending: true }; const url = `https://m.kinolights.com/title/${titleId}`; if (!_browser) await getContext(); const ctx = await _browser.newContext({ userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1', locale: 'ko-KR', viewport: { width: 390, height: 2400 }, }); const page = await ctx.newPage(); try { await page.route('**/*', (route) => { const t = route.request().resourceType(); if (t === 'font' || t === 'media') return route.abort(); return route.continue(); }); await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 25000 }); await page.waitForSelector('.synopsis, h2, [class*="title"]', { timeout: 10000 }).catch(() => {}); await page.evaluate(() => new Promise(r => setTimeout(r, 400))); // "๋”๋ณด๊ธฐ" ๋ฒ„ํŠผ ์žˆ์œผ๋ฉด ํด๋ฆญํ•ด์„œ ์ „์ฒด ์‹œ๋†‰์‹œ์Šค ํŽผ์น˜๊ธฐ await page.evaluate(() => { const btns = [...document.querySelectorAll('button, p, span, a')]; const more = btns.find(el => el.children.length === 0 && el.textContent.trim() === '๋”๋ณด๊ธฐ' && el.closest('.synopsis, [class*="synopsis"]')); if (more) (more.closest('button') || more).click(); }).catch(() => {}); await page.evaluate(() => new Promise(r => setTimeout(r, 200))); const data = await page.evaluate(() => { const txt = document.body.innerText; const m = (re) => { const x = txt.match(re); return x ? x[1].trim() : null; }; // ์‹œ๋†‰์‹œ์Šค: .synopsis__text-wrap ๋˜๋Š” .synopsis ์•ˆ ํ…์ŠคํŠธ, "๋”๋ณด๊ธฐ/์ ‘๊ธฐ" ๊ผฌ๋ฆฌํ‘œ ์ œ๊ฑฐ let synopsis = null; const synEl = document.querySelector('.synopsis__text-wrap, .synopsis'); if (synEl) { synopsis = synEl.innerText.trim() .replace(/\s*\.\.\.\s*๋”๋ณด๊ธฐ\s*$/u, '') .replace(/\s*\.\.\.\s*์ ‘๊ธฐ\s*$/u, '') .replace(/\s*๋”๋ณด๊ธฐ\s*$/u, '') .replace(/\s*์ ‘๊ธฐ\s*$/u, '') .trim(); } const genre = m(/์žฅ๋ฅด\s*\n\s*(.+)/); const airDate = m(/๋ฐฉ์˜์ผ\s*\n\s*(.+)/); const episodes = m(/ํšŒ์ฐจ\s*\n\s*(.+)/); const rating = m(/์—ฐ๋ น๋“ฑ๊ธ‰\s*\n\s*(.+)/); const country = m(/์ œ์ž‘๊ตญ๊ฐ€\s*\n\s*(.+)/); const year = m(/์ œ์ž‘์—ฐ๋„\s*\n\s*(.+)/); // ํ‰์  โ€” "90.7%" ๊ฐ™์€ ํŒจํ„ด ์ฒซ ๋“ฑ์žฅ const score = m(/(\d{1,3}(?:\.\d)?%)/); // ์ถœ์—ฐ์ง„ โ€” img alt ๊ธฐ๋ฐ˜(์žˆ๋‹ค๋ฉด) ๋˜๋Š” ํ…์ŠคํŠธ ํŒจํ„ด const cast = []; const castSection = txt.match(/์ถœ์—ฐ์ง„\/์ œ์ž‘์ง„([\s\S]+?)(์ถœ์—ฐ์ง„\/์ œ์ž‘์ง„ ๋”๋ณด๊ธฐ|์˜์ƒ|์ด๋ฏธ์ง€|์ปฌ๋ ‰์…˜)/); if (castSection) { const sec = castSection[1].split('\n').map(s => s.trim()).filter(Boolean); // "์ด๋ฆ„\n์—ญํ• \n์ฃผ์—ฐ" ํŒจํ„ด์ด ๋ฐ˜๋ณต๋จ โ€” ์ด๋ฆ„๋งŒ ์ถ”๋ฆฌ๊ธฐ for (let i = 0; i < sec.length; i++) { if (/^(์ฃผ์—ฐ|์กฐ์—ฐ|๊ฐ๋…|์ถœ์—ฐ)$/.test(sec[i])) { if (i >= 2) cast.push(sec[i-2]); // ์ด๋ฆ„ } } } // ๋ณด๋Ÿฌ๊ฐ€๊ธฐ OTT const ottMatch = txt.match(/(?:์ •์•ก์ œ|๋ฌด๋ฃŒ|๋Œ€์—ฌ|๊ตฌ๋งค)[\d\s]*\n([^\n]+)\n์ •์•ก์ œ/); const ott = ottMatch ? ottMatch[1].trim() : null; return { synopsis, genre, airDate, episodes, rating, country, year, score, cast: [...new Set(cast)].slice(0, 12), ott }; }); const result = { id: titleId, url, ...data, checked_at: new Date().toISOString() }; writeCache(cacheFile, result); return result; } catch (e) { return { error: String(e.message || e), id: titleId }; } finally { await page.close().catch(() => {}); await ctx.close().catch(() => {}); } } // โ”€โ”€โ”€โ”€โ”€ ์œ ํŠœ๋ธŒ ์˜ˆ๊ณ ํŽธ ๊ฒ€์ƒ‰ โ”€โ”€โ”€โ”€โ”€ async function fetchYoutubeTrailer(query, opts = {}) { query = (query || '').trim(); if (!query) return { error: 'empty query' }; const cacheFile = `yt_${Buffer.from(query).toString('base64').slice(0, 60)}.json`; // ์˜ˆ๊ณ ํŽธ ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ(videoId)๋Š” ํ•œ๋ฒˆ ์ฐพ์œผ๋ฉด ๋ฐ”๋€Œ์ง€ ์•Š์œผ๋ฏ€๋กœ ์˜๊ตฌ ์‚ฌ์šฉ. const cached = readCachePermanent(cacheFile); if (cached) return cached; // ์‚ฌ์šฉ์ž ์š”์ฒญ์€ ์บ์‹œ ๋ฏธ์Šค์—ฌ๋„ ์ƒˆ๋กœ ๊ฐ€์ ธ์˜ค์ง€ ์•Š์Œ. if (!opts.fetchIfMissing) return { query, pending: true }; if (!_browser) await getContext(); const ctx = await _browser.newContext({ userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1', locale: 'ko-KR', viewport: { width: 390, height: 1200 }, }); const page = await ctx.newPage(); try { await page.route('**/*', (route) => { const t = route.request().resourceType(); if (t === 'image' || t === 'font' || t === 'media') return route.abort(); return route.continue(); }); const url = `https://www.youtube.com/results?search_query=${encodeURIComponent(query + ' ๋ฉ”์ธ ์˜ˆ๊ณ ํŽธ')}`; await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 25000 }); await page.waitForSelector('a[href*="/watch?v="]', { timeout: 10000 }).catch(() => {}); const videoId = await page.evaluate(() => { const a = document.querySelector('a[href*="/watch?v="]'); const m = a?.getAttribute('href').match(/[?&]v=([\w-]{11})/); return m ? m[1] : null; }); const result = { query, videoId, embed: videoId ? `https://www.youtube.com/embed/${videoId}` : null, checked_at: new Date().toISOString() }; if (videoId) writeCache(cacheFile, result); return result; } catch (e) { return { error: String(e.message || e), query }; } finally { await page.close().catch(() => {}); await ctx.close().catch(() => {}); } } // โ”€โ”€โ”€โ”€โ”€ ๊ฒ€์ƒ‰ โ”€โ”€โ”€โ”€โ”€ // ๊ฒ€์ƒ‰ ํŽ˜์ด์ง€์˜ .vod-search-list .box ์นด๋“œ ๊ตฌ์กฐ์—์„œ ์ง์ ‘ ์ถ”์ถœ. // ๊ฐ™์€ origin์ด๋ผ page.evaluate์—์„œ DOM์„ ์ง์ ‘ ๋‹ค๋ฃฐ ์ˆ˜ ์žˆ๋„๋ก ๋ณ„๋„ fetch+parse ํŽ˜์ด์ง€๋กœ ์ฒ˜๋ฆฌ. // ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ HTML์„ ์„œ๋ฒ„์ธก ์ •๊ทœ์‹์œผ๋กœ ํŒŒ์‹ฑ (DOMParser ๋Œ€์ฒด โ€” raw CDP WS fetch๋Š” body ๋ฌธ์ž์—ด๋งŒ ์คŒ, 2026-07-01). // .vod-search-list .box ์•ˆ์˜ ๊ฐ ํ•ญ๋ชฉ: detail ๋งํฌ(id), ์ œ๋ชฉ, meta(๋ถ„๋ฅ˜/์—ฐ๋„ ๋“ฑ), ํฌ์Šคํ„ฐ. function parseSearchHtml(html, domain) { const out = []; const seen = new Set(); // ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ์˜์—ญ๋งŒ ํ•œ์ •. const listIdx = html.indexOf('vod-search-list'); const scope = listIdx >= 0 ? html.slice(listIdx) : html; // box ๋‹จ์œ„๋กœ ๋ถ„ํ•  (<div class="box flex"> ... ๋‹ค์Œ box ์ง์ „). const boxStarts = []; const startRe = /<div\s+class="box flex">/gi; let sm; while ((sm = startRe.exec(scope))) boxStarts.push(sm.index); for (let i = 0; i < boxStarts.length; i++) { const box = scope.slice(boxStarts[i], i + 1 < boxStarts.length ? boxStarts[i + 1] : boxStarts[i] + 2000); const idM = box.match(/\/vod\/detail\/id\/(\d+)/); if (!idM) continue; const id = +idM[1]; if (seen.has(id)) continue; seen.add(id); const href = `/index.php/vod/detail/id/${id}.html`; // ์ œ๋ชฉ: <div class="movie-title ..." title="...">...</div> โ€” title ์†์„ฑ ์šฐ์„ . let title = ''; const tM = box.match(/class="[^"]*movie-title[^"]*"[^>]*title="([^"]*)"/i) || box.match(/class="[^"]*movie-title[^"]*"[^>]*>([\s\S]*?)<\//i); if (tM) title = tM[1].replace(/<[^>]+>/g, '').replace(/&amp;/g, '&').replace(/&nbsp;/g, ' ').trim(); // meta: ์ฒซ <div class="meta getop ...">๋ถ„๋ฅ˜ / ์—ฐ๋„ / ...</div> let meta = ''; const mM = box.match(/class="meta getop[^"]*"[^>]*>([\s\S]*?)<\/div>/i) || box.match(/class="meta[^"]*"[^>]*>([\s\S]*?)<\/div>/i); if (mM) meta = mM[1].replace(/<[^>]+>/g, ' ').replace(/&amp;/g, '&').replace(/\s+/g, ' ').trim(); // ํฌ์Šคํ„ฐ: data-original (lazy) ์šฐ์„ , style background-image๋Š” placeholder๋ผ ์ œ์™ธ. let poster = null; const pM = box.match(/data-original="([^"]+)"/i) || box.match(/data-src="([^"]+)"/i); if (pM) poster = pM[1]; if (poster && /\/template\//.test(poster)) poster = null; if (poster && poster.startsWith('//')) poster = 'https:' + poster; if (poster && poster.startsWith('/')) poster = `https://${domain}${poster}`; out.push({ id, title, meta, href, poster }); } return out; } async function searchSite(wd) { if (!wd || !wd.trim()) return { error: 'empty query' }; const d = await findLiveDomain(); if (!d.domain) return { error: 'no live domain' }; // raw CDP WS fetch(ํ†ต๊ณผ ํƒญ)๋กœ ๊ฒ€์ƒ‰ HTML์„ ๋ฐ›์•„ ์„œ๋ฒ„์ธก ์ •๊ทœ์‹ ํŒŒ์‹ฑ (2026-07-01). const searchPath = `/index.php/vod/search.html?wd=${encodeURIComponent(wd)}`; let items = null; let lastErr = ''; for (let attempt = 0; attempt < 3; attempt++) { const r = await tvFetch(d.domain, searchPath); if (r.ok && r.status === 200) { items = parseSearchHtml(r.body, d.domain); break; } if (r.code === 'CF_PASS_NEEDED') return { error: r.error, code: 'CF_PASS_NEEDED' }; lastErr = `fetch failed: ${r.status || r.error}`; } if (items == null) return { error: lastErr || 'searchSite failed' }; return { wd, count: items.length, items, domain: d.domain }; } // โ”€โ”€โ”€โ”€โ”€ CDN ํ”„๋ก์‹œ (mp4 Range + HLS .m3u8 URL ์žฌ์ž‘์„ฑ) โ”€โ”€โ”€โ”€โ”€ // ์ฟผ๋ฆฌ: u=๋Œ€์ƒURL(b64 ๋˜๋Š” plain), r=Referer ๊ฐ•์ œ ์ง€์ •, t=m3u8|mp4 (์˜ต์…˜, content-type์œผ๋กœ๋„ ์ž๋™ ํŒ๋ณ„) // gcdn.app(anilife HLS) ํ˜ธ์ถœ์€ manifest๋ฅผ ๋ฐœ๊ธ‰๋ฐ›์€ IP์—์„œ๋งŒ ์œ ํšจ โ†’ SOCKS5 ํ†ตํ•ด์•ผ ํ•จ. // SOCKS5_PROXY ํ™˜๊ฒฝ๋ณ€์ˆ˜ ์žˆ์„ ๋•Œ๋งŒ agent ์ƒ์„ฑ. let _socksAgent = null; try { if (process.env.SOCKS5_PROXY) { const { SocksProxyAgent } = require('socks-proxy-agent'); _socksAgent = new SocksProxyAgent(process.env.SOCKS5_PROXY); console.log(`[cdn] SOCKS5 agent ready for anilife/gcdn calls (${process.env.SOCKS5_PROXY})`); } } catch (e) { console.warn('[cdn] socks-proxy-agent unavailable:', e.message); } function proxyCdn(req, res) { const u = url.parse(req.url, true); let target = u.query.u; if (!target) { res.writeHead(400); return res.end('missing u'); } if (u.query.b64 === '1') { try { target = Buffer.from(target, 'base64').toString('utf-8'); } catch { res.writeHead(400); return res.end('bad b64'); } } const cachedDomain = readCache('domain.json', 1e9); const isAniLikeHost = /anilife|gcdn\.app/.test(target); const isLinkkfHost = /ssku\d*\.top|play\.sub\d*\.top|linkkf\.tv/.test(target); const referer = u.query.r || (isAniLikeHost ? 'https://anilife.app/' : isLinkkfHost ? 'https://play.sub3.top/' : `https://${(cachedDomain && cachedDomain.domain) || 'tvchak.org'}/`); const t = new URL(target); const reqHeaders = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', 'Accept': '*/*', 'Referer': referer, 'Origin': new URL(referer).origin, }; if (req.headers.range) reqHeaders['Range'] = req.headers.range; const reqOpts = { hostname: t.hostname, port: t.port || 443, path: t.pathname + t.search, method: 'GET', headers: reqHeaders, rejectUnauthorized: false, }; // anilife/gcdn ์€ manifest ๋ฐœ๊ธ‰ IP์—์„œ๋งŒ ์œ ํšจ โ†’ SOCKS5(NAS residential) ๊ฒฝ์œ  ํ•„์ˆ˜. // linkkf์˜ m3u8/์„ธ๊ทธ๋จผํŠธ๋„ ํ•œ๊ตญ IP์—์„œ๋งŒ ๋ฐ›์„ ๊ฐ€๋Šฅ์„ฑ โ†’ SOCKS5 ๊ฒฝ์œ . // BunnyCDN ๋“ฑ์€ datacenter OK์ด๋ฏ€๋กœ ์ง์ ‘ ํ˜ธ์ถœ. if ((isAniLikeHost || isLinkkfHost) && _socksAgent) reqOpts.agent = _socksAgent; const upstream = https.request(reqOpts, (up) => { const ct = up.headers['content-type'] || ''; const isHls = /mpegurl/i.test(ct) || /\.m3u8(\?|$)/i.test(target); if (isHls) { // m3u8 ๋ณธ๋ฌธ์„ ํ•œ ๋ฒˆ์— ์ฝ์–ด์„œ URL ์žฌ์ž‘์„ฑ ํ›„ ์‘๋‹ต const chunks = []; up.on('data', (c) => chunks.push(c)); up.on('end', () => { let body = Buffer.concat(chunks).toString('utf-8'); const baseUrl = new URL(target); // anilife์˜ EXT-X-KEY๋Š” ํŽ˜์ดํฌ(enc.bin์ด 404) โ€” ์„ธ๊ทธ๋จผํŠธ๋Š” ์‹ค์ œ๋กœ๋Š” ํ‰๋ฌธ MPEG-TS. // anilife ๋„๋ฉ”์ธ์˜ m3u8์ผ ๋•Œ๋งŒ EXT-X-KEY ๋ผ์ธ ์ œ๊ฑฐ. if (/gcdn\.app/.test(target)) { body = body.split(/\r?\n/).filter(l => !l.startsWith('#EXT-X-KEY')).join('\n'); } // ๋ผ์ธ ๋‹จ์œ„๋กœ ์ฒ˜๋ฆฌ: ์ ˆ๋Œ€ URL์ด๊ฑฐ๋‚˜ ์ƒ๋Œ€ ๊ฒฝ๋กœ๋ฉด ์šฐ๋ฆฌ /cdn ์œผ๋กœ ์žฌ์ž‘์„ฑ body = body.split(/\r?\n/).map(line => { if (!line || line.startsWith('#')) return line; // ์ ˆ๋Œ€ URL if (/^https?:\/\//i.test(line)) { return `/cdn?b64=1&u=${encodeURIComponent(Buffer.from(line).toString('base64'))}&r=${encodeURIComponent(referer)}`; } // ์ƒ๋Œ€ ๊ฒฝ๋กœ โ†’ baseUrl ๊ธฐ์ค€ ์ ˆ๋Œ€ ๋ณ€ํ™˜ ํ›„ ํ”„๋ก์‹œ ํ†ต๊ณผ try { const abs = new URL(line, baseUrl).toString(); return `/cdn?b64=1&u=${encodeURIComponent(Buffer.from(abs).toString('base64'))}&r=${encodeURIComponent(referer)}`; } catch { return line; } }).join('\n'); // m3u8 #EXT-X-MAP ๋“ฑ ํƒœ๊ทธ ์•ˆ์˜ URI๋„ ์ฒ˜๋ฆฌ (EXT-X-KEY๋Š” ์œ„์—์„œ ์ œ๊ฑฐ๋จ) body = body.replace(/URI="([^"]+)"/g, (full, link) => { try { const abs = /^https?:\/\//i.test(link) ? link : new URL(link, baseUrl).toString(); const wrapped = `/cdn?b64=1&u=${encodeURIComponent(Buffer.from(abs).toString('base64'))}&r=${encodeURIComponent(referer)}`; return `URI="${wrapped}"`; } catch { return full; } }); const buf = Buffer.from(body, 'utf-8'); res.writeHead(up.statusCode, { 'Content-Type': 'application/vnd.apple.mpegurl', 'Content-Length': buf.length, 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store', }); res.end(buf); }); up.on('error', (e) => { try { res.writeHead(502); res.end('upstream error: ' + e.message); } catch {} }); return; } // ์ผ๋ฐ˜ ๋ฐ”์ด๋„ˆ๋ฆฌ (mp4 / m4s / ts) โ€” ๊ทธ๋Œ€๋กœ stream const passHeaders = {}; for (const k of ['content-type', 'content-length', 'content-range', 'accept-ranges', 'cache-control', 'last-modified']) { if (up.headers[k]) passHeaders[k] = up.headers[k]; } passHeaders['Access-Control-Allow-Origin'] = '*'; // ๋‹ค์šด๋กœ๋“œ ๋ชจ๋“œ: ?dl=ํŒŒ์ผ๋ช… ์œผ๋กœ Content-Disposition ๊ฐ•์ œ ์ถ”๊ฐ€ if (u.query.dl) { const fname = String(u.query.dl).replace(/[\r\n"\\]/g, '_').slice(0, 120); passHeaders['Content-Disposition'] = `attachment; filename*=UTF-8''${encodeURIComponent(fname)}`; } res.writeHead(up.statusCode, passHeaders); up.pipe(res); }); upstream.on('error', (e) => { try { res.writeHead(502); res.end('upstream error: ' + e.message); } catch {} }); req.on('close', () => upstream.destroy()); upstream.end(); } // โ”€โ”€โ”€โ”€โ”€ ์ •์  ํŒŒ์ผ โ”€โ”€โ”€โ”€โ”€ const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'application/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.png': 'image/png', '.svg': 'image/svg+xml', '.webmanifest': 'application/manifest+json; charset=utf-8', }; // gzip ์••์ถ• ๋Œ€์ƒ MIME โ€” ํ…์ŠคํŠธ๋ฅ˜๋งŒ. ์ด๋ฏธ์ง€/ํฐํŠธ๋Š” ์ด๋ฏธ ์••์ถ• ํ˜•์‹. const GZIP_TYPES = new Set([ 'text/html; charset=utf-8', 'text/css; charset=utf-8', 'application/javascript; charset=utf-8', 'application/json; charset=utf-8', 'application/manifest+json; charset=utf-8', 'image/svg+xml', ]); function serveStatic(req, res) { let p = decodeURIComponent(url.parse(req.url).pathname); if (p === '/' || p === '') p = '/index.html'; if (p.includes('..')) { res.writeHead(400); return res.end('bad'); } const fp = path.join(ROOT, p); if (!fp.startsWith(ROOT) || !fs.existsSync(fp) || fs.statSync(fp).isDirectory()) { res.writeHead(404); return res.end('not found'); } const type = MIME[path.extname(fp)] || 'application/octet-stream'; const acceptEnc = String(req.headers['accept-encoding'] || ''); const wantsGzip = /\bgzip\b/.test(acceptEnc) && GZIP_TYPES.has(type); const headers = { 'Content-Type': type, Vary: 'Accept-Encoding' }; if (wantsGzip) { headers['Content-Encoding'] = 'gzip'; res.writeHead(200, headers); fs.createReadStream(fp).pipe(zlib.createGzip({ level: 6 })).pipe(res); } else { res.writeHead(200, headers); fs.createReadStream(fp).pipe(res); } } // โ”€โ”€โ”€โ”€โ”€ ์„œ๋ฒ„ โ”€โ”€โ”€โ”€โ”€ function readBody(req, maxBytes = 5_000_000) { return new Promise((resolve, reject) => { let chunks = [], total = 0; req.on('data', (c) => { total += c.length; if (total > maxBytes) { req.destroy(); reject(new Error('body too large')); return; } chunks.push(c); }); req.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8'))); req.on('error', reject); }); } async function handleApi(req, res, parsed) { res.setHeader('Content-Type', 'application/json; charset=utf-8'); res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Cache-Control', 'no-store'); try { let out; const p = parsed.pathname; const q = parsed.query; if (p === '/api/auth-token') { // ์ธ์ฆ ํ†ต๊ณผํ•œ ํด๋ผ์ด์–ธํŠธ์— ์˜๊ตฌ ํ† ํฐ ๋ฐœ๊ธ‰ โ†’ localStorage์— ์ €์žฅํ•˜๋ฉด ์ฟ ํ‚ค ๋งŒ๋ฃŒ ํ›„์—๋„ ์ž๋™ ๋ณต๊ตฌ out = BASIC_AUTH ? { token: authCookieSign() } : { token: '' }; } else if (p === '/api/domain') { const d = await findLiveDomain(); // ํด๋ผ์ด์–ธํŠธ ํ—ค๋” ๋ฐฐ์ง€์šฉ ๋ชจ๋“œ ์ •๋ณด. cdp = USE_LOCAL_CDP=1๋กœ ์‚ฌ์šฉ์ž Chrome attach. local = NAS/Playwright ๊ฒฝ๋กœ. hf = Hugging Face Space. // HF๋Š” SPACE_ID ํ™˜๊ฒฝ๋ณ€์ˆ˜๋กœ ์ž๋™ ํŒ๋ณ„ (HF Space ๋Ÿฐํƒ€์ž„์ด ์ฃผ์ž…). const mode = process.env.SPACE_ID ? 'hf' : (USE_LOCAL_CDP ? 'cdp' : 'local'); // override ์ƒํƒœ๋„ ํ•จ๊ป˜ ๋‚ด๋ ค ํด๋ผ์ด์–ธํŠธ๊ฐ€ '์ž๋™/์ˆ˜๋™'์„ ๊ตฌ๋ถ„ํ•ด ๋ฐฐ์ง€ยทํŒ์—…์— ํ‘œ์‹œ. const ov = readCachePermanent('domain-override.json'); out = { ...d, mode, override: ov && ov.domain ? ov.domain : null, forced: !!FORCE_DOMAIN }; } else if (p === '/api/domain-override') { // ์‚ฌ์šฉ์ž๊ฐ€ ํ—ค๋” ๋ฐฐ์ง€์—์„œ ๋„๋ฉ”์ธ์„ ๊ณจ๋ผ ์ €์žฅ/ํ•ด์ œ. announce ์ž๋™์ถ”์ข…๋ณด๋‹ค ์šฐ์„ . // POST {domain:'tvchak209.com'|'tvchak.live'} โ†’ ์ €์žฅ / POST {domain:null|''} โ†’ ํ•ด์ œ(์ž๋™ ๋ณต๊ท€). // FORCE_DOMAIN(๋ถ€ํŒ… ๊ณ ์ •)์ด ์žˆ์œผ๋ฉด ๊ทธ๊ฒŒ ์ตœ์šฐ์„ ์ด๋ผ ์˜ค๋ฒ„๋ผ์ด๋“œ๋Š” ๋ฌด์‹œ๋จ์„ ์•Œ๋ ค์ค€๋‹ค. if (req.method !== 'POST' && req.method !== 'PUT') { // GET: ํ˜„์žฌ ์˜ค๋ฒ„๋ผ์ด๋“œ ์ƒํƒœ ์กฐํšŒ const ov = readCachePermanent('domain-override.json'); out = { domain: ov && ov.domain ? ov.domain : null, forced: !!FORCE_DOMAIN }; } else { const body = await readBody(req); let incoming = {}; try { incoming = JSON.parse(body || '{}'); } catch { throw new Error('invalid json'); } let dom = (typeof incoming.domain === 'string') ? incoming.domain.trim().toLowerCase() : ''; // ์•ž์— ๋ถ™์€ https:// ๋‚˜ ๊ฒฝ๋กœ ์ œ๊ฑฐ โ†’ ์ˆœ์ˆ˜ host๋งŒ. dom = dom.replace(/^https?:\/\//, '').replace(/\/.*$/, ''); if (!dom) { // ํ•ด์ œ โ†’ ํŒŒ์ผ ์‚ญ์ œ โ†’ announce ์ž๋™์ถ”์ข… ๋ณต๊ท€ try { fs.unlinkSync(path.join(CACHE_DIR, 'domain-override.json')); } catch {} try { fs.unlinkSync(path.join(CACHE_DIR, 'domain.json')); } catch {} // ์บ์‹œ๋„ ๋น„์›Œ ์ฆ‰์‹œ ์žฌํƒ์ง€ out = { ok: true, domain: null, source: 'auto' }; } else { // ๊ฒ€์ฆ: tvchakNNN.com (๋ฒˆํ˜ธ) ๋˜๋Š” tvchak.<flat> (live/net/cc/me/tv/io) ๋งŒ ํ—ˆ์šฉ. const okNumbered = /^tvchak\d+\.com$/.test(dom); const okFlat = /^tvchak\.(live|net|cc|me|tv|io|org)$/.test(dom); if (!okNumbered && !okFlat) { throw new Error('ํ—ˆ์šฉ๋˜์ง€ ์•Š๋Š” ๋„๋ฉ”์ธ ํ˜•์‹: ' + dom.slice(0, 40)); } const rec = { domain: dom, checked_at: new Date().toISOString() }; writeCache('domain-override.json', rec); // ๊ธฐ์กด domain.json ์บ์‹œ๋ฅผ ๋ฎ์–ด์จ ์ฆ‰์‹œ ๋ฐ˜์˜(10๋ถ„ ์บ์‹œ ๋ฌด์‹œ). writeCache('domain.json', { domain: dom, announced: dom, source: 'override', checked_at: rec.checked_at }); out = { ok: true, domain: dom, source: 'override', forced: !!FORCE_DOMAIN }; } } } else if (p === '/api/episodes') { if (q.source === 'anilife') { out = await aniEpisodes(q.id, { nocache: !!q.nocache }); // ํด๋ฐฑ ํŠธ๋ฆฌ๊ฑฐ: error ์žˆ๊ฑฐ๋‚˜ episodes ๋น„์–ด์žˆ์„ ๋•Œ. title ํ•„์š” (ํด๋ผ์ด์–ธํŠธ๊ฐ€ q.title๋กœ ์ „๋‹ฌ) const needFallback = !!(out && (out.error || !out.episodes || out.episodes.length === 0)); if (needFallback && q.title) { const reason = out?.error ? out.error.slice(0, 40) : 'empty episodes'; console.log(`[linkkf-fb] anilife ${q.id} "${q.title}" failed (${reason}) โ€” trying linkkf`); const fb = await aniEpisodesFallback(q.id, q.title, { targetCount: q.count ? parseInt(q.count, 10) : 0, fallbackId: q.fallbackId ? parseInt(q.fallbackId, 10) : 0, }); if (!fb.error && fb.episodes && fb.episodes.length) { console.log(`[linkkf-fb] success: ${fb.episodes.length} episodes (linkkf ${fb._fallbackLinkkfId || '?'})`); out = fb; } } } else out = await fetchEpisodes(q.id, { nocache: !!q.nocache }); } else if (p === '/api/latest-labels') { // ๋ณด๊ด€ํ•จ NEW ๊ฐ์ง€์šฉ ๊ฒฝ๋Ÿ‰ ์—”๋“œํฌ์ธํŠธ. // ids=1,2,3 + sources=tvchak,anilife,tvchak (์œ„์น˜ ๋งค์นญ). ๊ฐ๊ฐ์˜ ์ตœ์‹  ๋ผ๋ฒจ + count๋งŒ ๋ฐ˜ํ™˜. // ์บ์‹œ hit์ด๋ฉด ์ฆ‰์‹œ ๋ฐ˜ํ™˜. miss๋ฉด ๋ฐฑ๊ทธ๋ผ์šด๋“œ๋กœ fetchEpisodes ํŠธ๋ฆฌ๊ฑฐ (๋‹ค์Œ ํ˜ธ์ถœ ๋•Œ hit๋˜๋„๋ก). // ์‘๋‹ต: { items: [{id, source, latestLabel, count, fresh: true|false}], pending: [{id, source}] } const ids = String(q.ids || '').split(',').map(s => parseInt(s, 10)).filter(Boolean); const sources = String(q.sources || '').split(','); const items = []; const pending = []; for (let i = 0; i < ids.length; i++) { const id = ids[i]; const source = sources[i] === 'anilife' ? 'anilife' : 'tvchak'; const cacheFile = source === 'anilife' ? `ani_ep_${id}.json` : `ep_${id}.json`; // 2๋ถ„ fresh ์บ์‹œ โ€” ์ƒˆ ํšŒ์ฐจ ๋น ๋ฅด๊ฒŒ ๊ฐ์ง€ํ•˜๋ฉด์„œ๋„ ๋ถ€ํ•˜ ์ ์ • let cached = readCache(cacheFile, 120); let fresh = !!cached; // fresh ์—†์œผ๋ฉด stale์ด๋ผ๋„ ์‚ฌ์šฉ (์‘๋‹ต์€ ๋น ๋ฅด๊ฒŒ) if (!cached) cached = readCachePermanent(cacheFile); if (cached && cached.episodes && cached.episodes.length) { // ์ตœ์‹  ํšŒ์ฐจ ์ถ”์ถœ โ€” ์–‘์ชฝ ๋ชจ๋‘ nid=1์ด ์ตœ์‹  (tvchak sid=1, anilife sid=0) const latest = cached.episodes.find(e => e.nid === 1) || cached.episodes[0]; items.push({ id, source, latestLabel: latest?.label || null, count: cached.count || cached.episodes.length, fresh, }); // stale์ด๋ฉด ๋ฐฑ๊ทธ๋ผ์šด๋“œ ๊ฐฑ์‹  (์‘๋‹ต์—” ์˜ํ–ฅ ์—†์Œ) if (!fresh) pending.push({ id, source }); } else { // ์บ์‹œ ์ž์ฒด ์—†์Œ โ€” ๋ฐฑ๊ทธ๋ผ์šด๋“œ๋กœ ๊ฐ€์ ธ์™€ ๋‹ค์Œ ํ˜ธ์ถœ ๋•Œ hit๋˜๊ฒŒ pending.push({ id, source }); } } // ๋ฐฑ๊ทธ๋ผ์šด๋“œ ๊ฐฑ์‹  ํŠธ๋ฆฌ๊ฑฐ (await ์•ˆ ํ•จ, ์‘๋‹ต ์ฆ‰์‹œ ๋ฐ˜ํ™˜) // in-flight Set์œผ๋กœ ์ค‘๋ณต ํ˜ธ์ถœ ์ฐจ๋‹จ โ€” ๊ฐ™์€ ep๊ฐ€ ์ด๋ฏธ ์ฒ˜๋ฆฌ ์ค‘์ด๋ฉด skip. const toFetch = pending.filter(({ id, source }) => { const key = `${source}:${id}`; if (_latestLabelsInFlight.has(key)) return false; _latestLabelsInFlight.add(key); return true; }); if (toFetch.length) { setImmediate(async () => { for (const { id, source } of toFetch) { const key = `${source}:${id}`; try { if (source === 'anilife') await aniEpisodes(id); else await fetchEpisodes(id); } catch (e) { console.warn(`[latest-labels] bg ${source} ${id} failed:`, e.message); } finally { _latestLabelsInFlight.delete(key); } } }); } out = { items, pending: pending.map(p => p.id) }; } else if (p === '/api/play') { if (q.source === 'anilife') { const uniqueId = q.uniqueId || q.uid; // uniqueId๊ฐ€ "linkkf:..."๋ฉด ํด๋ฐฑ ์žฌ์ƒ (episodes ํด๋ฐฑ ํ›„ ํด๋ฆญํ•œ ์ผ€์ด์Šค) const fbPlay = await aniPlayMaybeFallback(uniqueId); if (fbPlay) out = fbPlay; else out = await aniPlay(uniqueId); } else { // ์ •๋ฐฉํ–ฅ nid ์ž‘ํ’ˆ(์™„๊ฒฐ ๊ณผ๊ฑฐ์ž‘) ๋Œ€์‘: episodes ๋งคํ•‘์— siteNid ๋ณด์กด๋ผ ์žˆ์œผ๋ฉด ๊ทธ๊ฑธ๋กœ ์‚ฌ์ดํŠธ์— ์ „๋‹ฌ. // ์บ์‹œ ๋งŒ๋ฃŒ(10๋ถ„) ์‹œ ๋งคํ•‘์ด ์‚ฌ๋ผ์ ธ ์ž˜๋ชป๋œ ํšŒ์ฐจ ์žฌ์ƒ๋˜๋˜ ์‚ฌ๊ณ ๊ฐ€ ์žˆ์–ด, ์บ์‹œ ๋งŒ๋ฃŒ ๋ฌด์‹œํ•˜๊ณ  ํŒŒ์ผ๋งŒ ์žˆ์œผ๋ฉด ๋งคํ•‘๋งŒ ์ถ”์ถœ. // ์บ์‹œ ํŒŒ์ผ ์ž์ฒด๊ฐ€ ์—†์œผ๋ฉด fetchEpisodes๋กœ ์ƒˆ๋กœ ์ƒ์„ฑ. let realNid = q.nid; try { const sidInt = parseInt(q.sid, 10); const nidInt = parseInt(q.nid, 10); let cached = readCachePermanent(`ep_${parseInt(q.id, 10)}.json`); if (!cached) { const ep = await fetchEpisodes(q.id); if (!ep?.error) cached = ep; } const hit = cached?.episodes?.find(e => e.sid === sidInt && e.nid === nidInt); if (hit && hit.siteNid && hit.siteNid !== nidInt) realNid = hit.siteNid; } catch {} out = await fetchPlay(q.id, q.sid, realNid); } } else if (p === '/api/search') { const source = q.source || 'all'; if (source === 'anilife') out = await aniSearch(q.wd); else if (source === 'tvchak') out = await searchSite(q.wd); else { // 'all' โ€” ์–‘์ชฝ ๋™์‹œ ๊ฒ€์ƒ‰ํ•ด์„œ ํ•ฉ์ณ์„œ ๋ฐ˜ํ™˜ (๊ฐ source๋Š” ๋ณ„๋„ ํ‚ค๋กœ) const [tv, ani] = await Promise.all([ searchSite(q.wd).catch(e => ({ error: String(e.message || e), items: [] })), aniSearch(q.wd).catch(e => ({ error: String(e.message || e), items: [] })), ]); // ํ†ต์ผ ํฌ๋งท์œผ๋กœ ๋ณ€ํ™˜ (tvchak์˜ ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ์—๋Š” source ํ•„๋“œ ์ถ”๊ฐ€) const tvItems = (tv.items || []).map(it => ({ ...it, source: 'tvchak' })); const aniItems = ani.items || []; out = { wd: q.wd, tvchak: { count: tvItems.length, items: tvItems, error: tv.error || null, domain: tv.domain }, anilife: { count: aniItems.length, items: aniItems, error: ani.error || null }, }; } } else if (p === '/api/ranking') out = await fetchKinoRanking(q.period, { fetchIfMissing: true, force: !!q.force }); else if (p === '/api/ranking-detail') out = await fetchKinoDetail(q.id, { fetchIfMissing: true }); else if (p === '/api/yt-trailer') out = await fetchYoutubeTrailer(q.title, { fetchIfMissing: true }); else if (p === '/api/favs') { const profile = q.profile || '1'; if (req.method === 'GET') { out = readFavs(profile); } else if (req.method === 'PUT' || req.method === 'POST') { const body = await readBody(req); const incoming = JSON.parse(body); if (!Array.isArray(incoming.favs)) throw new Error('invalid payload'); // ๊ธฐ์กด nickname ๋ณด์กด โ€” ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์•ˆ ๋ณด๋‚ด๊ฑฐ๋‚˜ ๋นˆ ๋ฌธ์ž์—ด์ด๋ฉด ์„œ๋ฒ„ ๊ฐ’ ์œ ์ง€. const existing = readFavs(profile); const incNick = (typeof incoming.nickname === 'string') ? incoming.nickname.slice(0, 30).trim() : null; const existingNick = (typeof existing.nickname === 'string') ? existing.nickname : null; // ๋‘˜ ๋‹ค ๋น„์—ˆ์œผ๋ฉด nickname ํ•„๋“œ ์ž์ฒด๋ฅผ ์•ˆ ๋„ฃ์Œ โ€” ๋‹ค์Œ NAS pull์ด ์ฑ„์šธ ์ˆ˜ ์žˆ๋„๋ก. // (๋นˆ ๋ฌธ์ž์—ด ""์„ ์ €์žฅํ•˜๋ฉด NAS๋กœ push๋˜์–ด ๋‹ค๋ฅธ ๋””๋ฐ”์ด์Šค ๋‹‰๋„ค์ž„๊นŒ์ง€ ๋ง๊ฐ€์ง. root cause: ๋ถ€ํŒ… ์‹œ NAS pull race.) const payload = { favs: incoming.favs, lastFavId: incoming.lastFavId || null, }; const chosen = incNick || existingNick; if (chosen) payload.nickname = chosen; out = writeFavs(profile, payload); } else { res.writeHead(405); return res.end(JSON.stringify({ error: 'method not allowed' })); } } else if (p === '/api/profile-labels') { // 5๊ฐœ ํ”„๋กœํ•„์˜ nickname ์ผ๊ด„ ์กฐํšŒ const labels = {}; for (let i = 1; i <= 5; i++) { try { labels[i] = readFavs(String(i)).nickname || ''; } catch { labels[i] = ''; } } out = { labels }; } else if (p === '/api/nas-status') { out = { enabled: NAS_SYNC_ENABLED, reachable: _nasReachable, // true/false/null (๋ฏธํ™•์ธ) pendingPush: [..._failedPush].sort(), }; } else if (p === '/api/flush') { for (const f of fs.readdirSync(CACHE_DIR)) if (f.endsWith('.json')) fs.unlinkSync(path.join(CACHE_DIR, f)); out = { ok: true }; } else if (p === '/api/poster-refresh') { // namu CDN URL ๋งŒ๋ฃŒ ์‹œ ์ •์กฐ์ค€ ์บ์‹œ ์‚ญ์ œ. titles=A,B ๊ทธ๋ฆฌ๊ณ /๋˜๋Š” ids=1,2 (ep ์บ์‹œ๊นŒ์ง€ ํ•จ๊ป˜) const titles = String(q.titles || '').split(',').map(s => s.trim()).filter(Boolean); const ids = String(q.ids || '').split(',').map(s => parseInt(s, 10)).filter(Boolean); const removed = []; for (const t of titles) { const fn = `namu_poster_v2_${Buffer.from(t).toString('base64').slice(0, 80).replace(/[+/=]/g, '_')}.json`; const fp = path.join(CACHE_DIR, fn); if (fs.existsSync(fp)) { try { fs.unlinkSync(fp); removed.push(fn); } catch {} } } for (const id of ids) { for (const fn of [`ep_${id}.json`, `ani_ep_${id}.json`]) { const fp = path.join(CACHE_DIR, fn); if (fs.existsSync(fp)) { try { fs.unlinkSync(fp); removed.push(fn); } catch {} } } } out = { ok: true, removed }; } else if (p === '/api/diag/proxy') { // NAS fetch ํ”„๋ก์‹œ(127.0.0.1:18080) ์—ฐ๊ฒฐ ์ง„๋‹จ const out2 = { proxyUrl: NAS_FETCH_PROXY }; // health const health = await new Promise((resolve) => { const t0 = Date.now(); const req = http.get(`${NAS_FETCH_PROXY}/health`, { timeout: 6000 }, (res) => { let b = ''; res.on('data', d => b += d); res.on('end', () => resolve({ status: res.statusCode, body: b.slice(0, 80), ms: Date.now() - t0 })); }); req.on('error', e => resolve({ error: String(e.message || e).slice(0, 120), ms: Date.now() - t0 })); req.on('timeout', () => { req.destroy(); resolve({ error: 'timeout', ms: Date.now() - t0 }); }); }); out2.health = health; // ์‹ค์ œ fetch 1ํšŒ // 5ํšŒ ๋ฐ˜๋ณตํ•ด์„œ body ๊ธธ์ด + parsePlayerAaaa ์„ฑ๊ณต ์—ฌ๋ถ€ ์ผ๊ด€์„ฑ ํ™•์ธ (๊ฐ„ํ— player_aaaa not found ์ง„๋‹จ) out2.fetches = []; for (let k = 0; k < 5; k++) { const t1 = Date.now(); const fr = await nasFetch('https://tvchak204.com/index.php/vod/play/id/122862/sid/1/nid/1.html', 12000); const body = typeof fr.body === 'string' ? fr.body : ''; const idx = body.indexOf('player_aaaa'); const parsed = idx >= 0 ? parsePlayerAaaa(body) : null; out2.fetches.push({ ok: fr.ok, status: fr.status, len: body.length, playerIdx: idx, parsedOk: !!parsed, hasUrl: !!(parsed && (parsed.url || parsed.url_next)), err: fr.error, ms: Date.now() - t1, }); } out = out2; } else if (p === '/api/diag/tvchak') { // SNI ์ฐจ๋‹จ ๊ฐ€์„ค ๊ฒ€์ฆ: HF Space ์•ˆ์—์„œ โ‘ Node native https, โ‘กPlaywright context.request, โ‘ขChromium page.goto๊ฐ€ ๊ฐ๊ฐ ์–ด๋–ป๊ฒŒ ์‘๋‹ตํ•˜๋Š”์ง€. const target = q.host || 'tvchak204.com'; const url = `https://${target}/`; const results = {}; // โ‘  Node native https try { const t0 = Date.now(); const got = await new Promise((resolve, reject) => { const req = https.request(url, { method: 'GET', timeout: 8000 }, (res) => { let buf = ''; res.on('data', (d) => { buf += d.toString('utf8').slice(0, 200); }); res.on('end', () => resolve({ status: res.statusCode, snippet: buf.slice(0, 200) })); }); req.on('error', (e) => reject(e)); req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); }); req.end(); }); results.node = { ms: Date.now() - t0, ...got }; } catch (e) { results.node = { error: String(e.message || e) }; } // โ‘ก Playwright context.request โ€” tvchak ์ „์šฉ ctx (SOCKS5 ๋ฏธ์‚ฌ์šฉ) try { const t0 = Date.now(); const ctx = await getTvContext(); const resp = await ctx.request.get(url, { timeout: 8000, maxRedirects: 0, failOnStatusCode: false }); const body = (await resp.text()).slice(0, 600); results.ctxRequest = { ms: Date.now() - t0, status: resp.status(), snippet: body }; } catch (e) { results.ctxRequest = { error: String(e.message || e).slice(0, 200) }; } // โ‘ข Chromium page.goto โ€” tvchak ์ „์šฉ ctx (SOCKS5 ๋ฏธ์‚ฌ์šฉ). ์ฑŒ๋ฆฐ์ง€ ํ†ต๊ณผ ์‹œ๋„๋ฅผ ์œ„ํ•ด 15์ดˆ ๋Œ€๊ธฐ ํ›„ ์ตœ์ข… ์ƒํƒœ ํ™•์ธ. try { const t0 = Date.now(); const ctx = await getTvContext(); const page = await ctx.newPage(); try { const resp = await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 15000 }); // Cloudflare JS challenge๊ฐ€ ์ž๋™ ํ†ต๊ณผ๋˜๋Š”์ง€ ์ž ์‹œ ๋Œ€๊ธฐ await page.waitForTimeout(8000); const finalUrl = page.url(); const body = (await page.content()).slice(0, 600); results.chromiumGoto = { ms: Date.now() - t0, status: resp ? resp.status() : null, finalUrl, snippet: body }; } finally { await page.close().catch(() => {}); } } catch (e) { results.chromiumGoto = { error: String(e.message || e).slice(0, 200) }; } // proxy ์ •๋ณด๋„ ๊ฐ™์ด ๋…ธ์ถœ results.proxyServer = process.env.SOCKS5_PROXY || null; results.target = target; out = results; } else if (p === '/api/breaker') { // ๋””๋ฒ„๊ทธ/๊ด€๋ฆฌ์šฉ: anilife circuit breaker ์ƒํƒœ ํ™•์ธ + ๊ฐ•์ œ ๋ฆฌ์…‹ if (q.reset === '1') { ANI_BREAKER.failures = 0; ANI_BREAKER.openUntil = 0; out = { ok: true, reset: true }; } else { out = { anilife: { failures: ANI_BREAKER.failures, failuresMax: ANI_BREAKER.failuresMax, isOpen: aniBreakerIsOpen(), openUntil: ANI_BREAKER.openUntil ? new Date(ANI_BREAKER.openUntil).toISOString() : null, cooldownMs: ANI_BREAKER.cooldownMs, }, }; } } else if (p === '/api/diag/cf-monitor') { // ๋””๋ฒ„๊ทธ/๊ด€๋ฆฌ์šฉ: ํ˜„์žฌ announce ๋„๋ฉ”์ธ์œผ๋กœ play ๊ฒฝ๋กœ fetch ๊ฒฐ๊ณผ ํ™•์ธ. (์ฐฝ ๋„์šฐ๊ธฐ ๋กœ์ง์€ ์ œ๊ฑฐ๋จ 2026-06-30) if (!USE_LOCAL_CDP) { out = { ok: false, error: 'CDP ๋ชจ๋“œ ์•„๋‹˜ (USE_LOCAL_CDP=1 ํ•„์š”)' }; } else { const cached = readCachePermanent('domain.json'); const dom = cached && (cached.announced || cached.domain); if (!dom) { out = { ok: false, error: 'no announce domain' }; } else { const r = await tvFetchCDP(dom, '/index.php/vod/play/id/122862/sid/1/nid/1.html'); const isCf = /challenge-platform|cf-chl|turnstile|cf_chl_/i.test(r.body || ''); out = { ok: true, domain: dom, fetchOk: !!r.ok, status: r.status, isCfChallenge: isCf }; } } } else { res.writeHead(400); return res.end(JSON.stringify({ error: 'unknown api' })); } res.end(JSON.stringify(out)); } catch (e) { // tvchak์ด ์ข€๋น„๋ผ queue ํฌํ™” โ€” 503์œผ๋กœ ์ฆ‰์‹œ ์‘๋‹ตํ•ด ํด๋ผ์ด์–ธํŠธ๊ฐ€ retry/๋Œ€์ฒด ํ๋ฆ„ ํƒ€๋„๋ก. // 500์œผ๋กœ ์ฃผ๋ฉด ํด๋ผ์ด์–ธํŠธ๊ฐ€ SW cachingยทbreaker ๊ฐ™์€ ์˜๊ตฌ ์‹คํŒจ ์ฒ˜๋ฆฌ๋กœ ์˜ค์ธํ•  ์ˆ˜ ์žˆ์Œ. if (e && e.code === 'TV_MUTEX_BUSY') { res.writeHead(503, { 'Retry-After': '20' }); return res.end(JSON.stringify({ error: 'tvchak busy, retry in a moment', code: 'TV_MUTEX_BUSY' })); } res.writeHead(500); res.end(JSON.stringify({ error: String(e.message || e) })); } } // HTTP Basic Auth ๊ฒŒ์ดํŠธ (HF Spaces ๊ฐ™์€ ๊ณต๊ฐœ ํ˜ธ์ŠคํŒ…์šฉ). // ํ™˜๊ฒฝ๋ณ€์ˆ˜ BASIC_AUTH="user:pass" ๊ฐ€ ์žˆ์„ ๋•Œ๋งŒ ํ™œ์„ฑํ™”. ๋กœ์ปฌ์—์„œ๋Š” ์ž๋™ ๋น„ํ™œ์„ฑ. // ํ•œ ๋ฒˆ Basic Auth ํ†ต๊ณผํ•˜๋ฉด HMAC ์„œ๋ช… ์žฅ๊ธฐ ์ฟ ํ‚ค(AUTH_COOKIE_DAYS) ๋ฐœ๊ธ‰ โ†’ // ์ปจํ…Œ์ด๋„ˆ ์žฌ์‹œ์ž‘/HF Space sleep ํ›„์—๋„ ์ฟ ํ‚ค๋งŒ ์žˆ์œผ๋ฉด ํ†ต๊ณผ (์„œ๋ช… ์‹œํฌ๋ฆฟ์ด BASIC_AUTH ์ž์ฒด๋ผ ๋™์ผ ์œ ์ง€) const BASIC_AUTH = process.env.BASIC_AUTH || ''; const AUTH_COOKIE_NAME = 'tvchak_auth'; const AUTH_COOKIE_DAYS = 180; const crypto = require('crypto'); function authCookieSign() { // BASIC_AUTH ๊ฐ’ ์ž์ฒด๋ฅผ ์‹œํฌ๋ฆฟ์œผ๋กœ HMAC. ๋น„๋ฒˆ ๋ฐ”๋€Œ๋ฉด ๋ชจ๋“  ์ฟ ํ‚ค ์ž๋™ ๋ฌดํšจ. return crypto.createHmac('sha256', BASIC_AUTH).update('v1').digest('hex').slice(0, 32); } function parseCookie(req, name) { const raw = req.headers['cookie'] || ''; for (const part of raw.split(';')) { const [k, ...v] = part.trim().split('='); if (k === name) return v.join('='); } return ''; } function setAuthCookie(res) { const maxAge = AUTH_COOKIE_DAYS * 24 * 60 * 60; const val = authCookieSign(); // SameSite=Lax: ๋™์ผ origin ์ผ๋ฐ˜ ์š”์ฒญ์— ๋‹ค ๋ถ™์Œ. Secure๋Š” HF๊ฐ€ https๋‹ˆ๊นŒ OK, ๋กœ์ปฌ http์—์„œ๋„ ๋ฌด๋ฆฌ ์—†์Œ(๋ธŒ๋ผ์šฐ์ €๋Š” https์—์„œ๋งŒ ์ „์†ก). res.setHeader('Set-Cookie', `${AUTH_COOKIE_NAME}=${val}; Path=/; Max-Age=${maxAge}; HttpOnly; SameSite=Lax; Secure`); } function checkBasicAuth(req, res) { if (!BASIC_AUTH) return true; // ํ™˜๊ฒฝ๋ณ€์ˆ˜ ์—†์œผ๋ฉด ํ†ต๊ณผ // PWA์šฉ (Service Worker, manifest)์€ ์ธ์ฆ ์—†์ด๋„ ๋ฐ›์„ ์ˆ˜ ์žˆ์–ด์•ผ ํ•จ. // SW๋Š” ์ฒซ ์ง„์ž… ์‹œ ์ธ์ฆ ํ†ต๊ณผํ•œ ์ปจํ…์ŠคํŠธ์—์„œ register๋˜์ง€๋งŒ, ๋“ฑ๋ก ์ž์ฒด์— ๋ณ„๋„ fetch๊ฐ€ ํ•„์š”. const p = req.url.split('?')[0]; if (p === '/sw.js' || p === '/manifest.webmanifest') return true; // PWA ์•„์ด์ฝ˜์€ manifest์—์„œ ์ฐธ์กฐ๋˜๋ฏ€๋กœ ์ธ์ฆ ์—†์ด ๋ฐ›์„ ์ˆ˜ ์žˆ์–ด์•ผ ํ•จ (TWA ์„ค์น˜ ์‹œ์—๋„ ๋™์ผ) if (p === '/favicon.svg' || p.startsWith('/icons/')) return true; // TWA Digital Asset Links โ€” ์•ˆ๋“œ๋กœ์ด๋“œ OS๊ฐ€ ์ธ์ฆ ์—†์ด ์ ‘๊ทผํ•ด์•ผ ์•ฑ ๊ฒ€์ฆ ํ†ต๊ณผ if (p === '/.well-known/assetlinks.json') return true; const sig = authCookieSign(); // 1) ์ฟ ํ‚ค ์šฐ์„  ๊ฒ€์‚ฌ โ€” ํ•œ ๋ฒˆ ์ธ์ฆํ•œ ๋ธŒ๋ผ์šฐ์ €๋Š” ์ปจํ…Œ์ด๋„ˆ ์žฌ์‹œ์ž‘/sleep ๋ฌด๊ด€ํ•˜๊ฒŒ ํ†ต๊ณผ const cookieVal = parseCookie(req, AUTH_COOKIE_NAME); if (cookieVal && cookieVal === sig) return true; // 2) X-Auth-Token ํ—ค๋” ๊ฒ€์‚ฌ โ€” localStorage์— ์ €์žฅ๋œ ์˜๊ตฌ ํ† ํฐ(์ฟ ํ‚ค๊ฐ€ ITP ๋“ฑ์œผ๋กœ ๋งŒ๋ฃŒ๋ผ๋„ ๋ณต๊ตฌ) const tokHdr = req.headers['x-auth-token'] || ''; if (tokHdr && tokHdr === sig) { setAuthCookie(res); // ์ฟ ํ‚ค ์žฌ๋ฐœ๊ธ‰ return true; } // 2-b) URL ์ฟผ๋ฆฌ ?auth=<token> ๊ฒ€์‚ฌ โ€” TWA(Android Bubblewrap APK) ์ง„์ž…์šฉ. ์ฒซ ์ง„์ž…์— ์ฟ ํ‚ค ๋ฐ•๊ณ  ํ†ต๊ณผ. try { const qIdx = req.url.indexOf('?'); if (qIdx >= 0) { const qs = new URLSearchParams(req.url.slice(qIdx + 1)); const qAuth = qs.get('auth') || ''; if (qAuth && qAuth === sig) { setAuthCookie(res); return true; } } } catch {} // 3) Basic Auth ํ—ค๋” ๊ฒ€์‚ฌ โ€” ํ†ต๊ณผ ์‹œ ์žฅ๊ธฐ ์ฟ ํ‚ค ๋ฐœ๊ธ‰ const h = req.headers['authorization'] || ''; if (h.startsWith('Basic ')) { try { const decoded = Buffer.from(h.slice(6), 'base64').toString('utf-8'); if (decoded === BASIC_AUTH) { setAuthCookie(res); return true; } } catch {} } res.writeHead(401, { 'WWW-Authenticate': 'Basic realm="OTT Player"', 'Content-Type': 'text/plain; charset=utf-8', }); res.end('Auth required'); return false; } // playwright ์ปจํ…์ŠคํŠธ๋กœ namu ์ด๋ฏธ์ง€ fetch โ€” i.namu.wiki๊ฐ€ ์ง์ ‘ GET์„ 403 ์ฐจ๋‹จํ•ด๋„ // namu.wiki origin ๋‚ด๋ถ€์—์„œ fetchํ•˜๋ฉด ํ†ต๊ณผํ•  ๊ฐ€๋Šฅ์„ฑ. ๋ฌด๊ฒ์ง€๋งŒ ํ•œ ๋ฒˆ ์บ์‹œ๋˜๋ฉด ์˜๊ตฌ. async function fetchNamuImageViaPlaywright(imgUrl) { if (!_browser) await getContext(); const ctx = await _browser.newContext({ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', locale: 'ko-KR', }); try { const page = await ctx.newPage(); try { // namu.wiki ๋ฉ”์ธ ํŽ˜์ด์ง€๋ฅผ origin์œผ๋กœ ์‚ฌ์šฉ (์–ด๋–ค ํ‘œ์ œ์–ด๋ผ๋„ OK) await withTimeout(page.goto('https://namu.wiki/', { waitUntil: 'domcontentloaded', timeout: 15000 }), 16000, 'namu origin'); // ํŽ˜์ด์ง€ ์•ˆ์—์„œ fetch โ€” origin์ด namu.wiki๋ผ Cloudflare ํ†ต๊ณผ ๊ธฐ๋Œ€ const result = await page.evaluate(async (url) => { try { const r = await fetch(url); if (!r.ok) return { error: 'HTTP ' + r.status }; const buf = await r.arrayBuffer(); const bytes = new Uint8Array(buf); let bin = ''; for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]); return { b64: btoa(bin), ct: r.headers.get('content-type') || 'image/webp' }; } catch (e) { return { error: String(e.message || e) }; } }, imgUrl); if (result.error) return { error: result.error }; return { buf: Buffer.from(result.b64, 'base64'), ct: result.ct }; } finally { await page.close().catch(() => {}); } } finally { await ctx.close().catch(() => {}); } } // ์ด๋ฏธ์ง€ ํ”„๋ก์‹œ โ€” namu CDN(i.namu.wiki) ์ฐจ๋‹จ ์šฐํšŒ. // 1์ฐจ: ์ง์ ‘ GET (NAS SOCKS5 ๊ฒฝ์œ , ๊ฐ€๋ฒผ์›€) // 2์ฐจ: 1์ฐจ๊ฐ€ 403/์‹คํŒจ๋ฉด playwright๋กœ namu.wiki origin ๋‚ด๋ถ€์—์„œ fetch // ์˜๊ตฌ ๋””์Šคํฌ ์บ์‹œ + immutable ์‘๋‹ต์œผ๋กœ ๋ธŒ๋ผ์šฐ์ € ์บ์‹œ. async function proxyImg(req, res) { const parsed = url.parse(req.url, true); const target = String(parsed.query.url || ''); if (!target) { res.writeHead(400); return res.end('missing url'); } // ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ: i.namu.wiki๋งŒ ํ—ˆ์šฉ. SSRF ๋ฐฉ์ง€. let t; try { t = new URL(target); } catch { res.writeHead(400); return res.end('bad url'); } if (t.hostname !== 'i.namu.wiki') { res.writeHead(403); return res.end('host not allowed'); } // ๋””์Šคํฌ ์บ์‹œ (์˜๊ตฌ). const cacheKey = `img_${Buffer.from(t.pathname).toString('base64').slice(0, 80).replace(/[+/=]/g, '_')}`; const cachePath = path.join(CACHE_DIR, cacheKey); if (fs.existsSync(cachePath)) { res.writeHead(200, { 'Content-Type': 'image/webp', 'Cache-Control': 'public, max-age=2592000, immutable', }); return fs.createReadStream(cachePath).pipe(res); } // 1์ฐจ: ์ง์ ‘ GET (NAS SOCKS5 ๊ฒฝ์œ ). ๋น ๋ฅด์ง€๋งŒ ์ฐจ๋‹จ๋˜๋ฉด 403. const direct = await new Promise((resolve) => { const reqOpts = { hostname: t.hostname, port: 443, path: t.pathname + (t.search || ''), method: 'GET', headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', 'Referer': 'https://namu.wiki/', 'Accept': 'image/avif,image/webp,image/*,*/*;q=0.8', }, }; if (_socksAgent) reqOpts.agent = _socksAgent; const upstream = https.request(reqOpts, (up) => { if (up.statusCode !== 200) { up.resume(); return resolve({ status: up.statusCode }); } const chunks = []; up.on('data', (c) => chunks.push(c)); up.on('end', () => resolve({ status: 200, buf: Buffer.concat(chunks), ct: up.headers['content-type'] || 'image/webp', })); up.on('error', () => resolve({ status: 500 })); }); upstream.on('error', () => resolve({ status: 502 })); upstream.end(); }); let final = direct; // 2์ฐจ: ์ง์ ‘ GET ์‹คํŒจํ•˜๋ฉด playwright origin ์šฐํšŒ (๋ฌด๊ฑฐ์šฐ๋‹ˆ ์บ์‹œ ์—†์„ ๋•Œ๋งŒ) if (!direct.buf) { console.warn(`[img-proxy] ${t.pathname.slice(0,40)} direct=${direct.status}, trying playwright origin`); try { const pw = await fetchNamuImageViaPlaywright(target); if (pw.buf) final = { status: 200, buf: pw.buf, ct: pw.ct }; else console.warn(`[img-proxy] ${t.pathname.slice(0,40)} playwright also failed: ${pw.error}`); } catch (e) { console.warn(`[img-proxy] playwright error:`, e.message); } } if (!final.buf) { res.writeHead(final.status || 502); return res.end('upstream failed'); } // ๋””์Šคํฌ ์บ์‹œ ์ €์žฅ + ์‘๋‹ต try { fs.writeFileSync(cachePath, final.buf); } catch {} res.writeHead(200, { 'Content-Type': final.ct, 'Cache-Control': 'public, max-age=2592000, immutable', }); res.end(final.buf); } const server = http.createServer(async (req, res) => { if (!checkBasicAuth(req, res)) return; const parsed = url.parse(req.url, true); if (parsed.pathname.startsWith('/api/')) return handleApi(req, res, parsed); if (parsed.pathname === '/cdn') return proxyCdn(req, res); if (parsed.pathname === '/img-proxy') return proxyImg(req, res); serveStatic(req, res); }); server.listen(PORT, () => { console.log(`tvchak local server: http://localhost:${PORT}/`); // NAS ๋™๊ธฐํ™” ํ™˜๊ฒฝ์ด๋ฉด ์‹œ์ž‘ ์‹œ favs pull (๋กœ์ปฌ PC ์„œ๋ฒ„์šฉ โ€” entrypoint.sh๊ฐ€ ๋„๋Š” HF๋Š” ๊ฑฐ๊ธฐ์„œ ๋ฏธ๋ฆฌ pull๋จ) // ๋‹จ entrypoint pull์ด ์ผ๋ถ€ ์‹คํŒจํ•œ ๊ฒฝ์šฐ(NAS_FAVS_ENABLED ๋ฏธ์„ค์ •)์—๋„ ๋™์ž‘. if (NAS_SYNC_ENABLED && !process.env.NAS_FAVS_ENABLED) { pullFavsFromNas().catch(e => console.warn('[nas-favs] startup pull failed:', e.message)); } // (NAS_FAVS_ENABLED=1 ์ผ€์ด์Šค๋ผ๋„ ํ•œ ๋ฒˆ ๋” ํ™•์ธ: ์–ด๋–ค ํ”„๋กœํ•„์—๋“  favs ํŒŒ์ผ์ด ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด // PUT race๋กœ nickname ์žƒ๋Š” ์‚ฌ๊ณ ๊ฐ€ ๋‚ฌ์œผ๋ฏ€๋กœ pull๋กœ ๋ณด์ถฉ.) if (NAS_SYNC_ENABLED && process.env.NAS_FAVS_ENABLED) { let anyMissing = false; for (let p = 1; p <= 5; p++) { if (!fs.existsSync(profileFile(String(p)))) { anyMissing = true; break; } } if (anyMissing) { console.log('[nas-favs] some profile files missing despite NAS_FAVS_ENABLED โ€” retry pull'); pullFavsFromNas().catch(e => console.warn('[nas-favs] retry pull failed:', e.message)); } } if (NAS_SYNC_ENABLED) { // 30์ดˆ๋งˆ๋‹ค NAS ํ—ฌ์Šค์ฒดํฌ โ€” ๋‹ค์šด โ†’ ํšŒ๋ณต ์ „ํ™˜ ๊ฐ์ง€ ์‹œ ๋ˆ„๋ฝ push ์ผ๊ด„ ์žฌ์‹œ๋„ setInterval(() => { pingNas().catch(() => {}); }, 30 * 1000); // 30๋ถ„๋งˆ๋‹ค NAS์—์„œ favs ์žฌpull โ€” ๋‹ค๋ฅธ ๋””๋ฐ”์ด์Šค ๋ณ€๊ฒฝ(์˜ˆ: nickname) ๊ฐ€์ ธ์˜ด. setInterval(() => { if (_pushTimers.size > 0 || _failedPush.size > 0) return; pullFavsFromNas().catch(e => console.warn('[nas-favs] periodic pull failed:', e.message)); }, 30 * 60 * 1000); } // ๋ถ€ํŒ… ์งํ›„ ์›Œ๋ฐ์—… โ†’ prefetch ์ˆœ์„œ๋กœ ์‹คํ–‰ (๋น„๋ธ”๋กœํ‚น). // ์›Œ๋ฐ์—…: Playwright ์ปจํ…์ŠคํŠธ + tvchak live domain ์บ์‹œ. cold start ์ฒซ ์‚ฌ์šฉ์ž์˜ 'no live domain' ๋ฐฉ์ง€. // SOCKS5 ์‚ฌ์šฉ ํ™˜๊ฒฝ(HF)์—์„œ๋Š” ํ„ฐ๋„ ์•ˆ์ •ํ™” ํ›„ ์›Œ๋ฐ์—… โ€” autossh๊ฐ€ "ready" ์ถœ๋ ฅ ์งํ›„์—” // ์ฒซ TLS handshake๊ฐ€ ์ž์ฃผ ERR_CONNECTION_CLOSED ๋จ. ์‹ค์ œ outbound ํ˜ธ์ถœ๋กœ ๊ฒ€์ฆ ํ›„ ์ง„ํ–‰. (async () => { if (process.env.SOCKS5_PROXY) { console.log('[boot] SOCKS5 ready ๊ฒ€์ฆ ์‹œ์ž‘...'); const verified = await verifySocks5Ready(); console.log(`[boot] SOCKS5 ready ๊ฒ€์ฆ: ${verified ? 'โœ“' : 'โœ— (skip, warmup ์ง„ํ–‰)'}`); } warmup().catch((e) => console.warn('[warmup] failed:', e.message)); })(); // 30๋ถ„๋งˆ๋‹ค ์žฌ์›Œ๋ฐ์—… โ€” domain ์บ์‹œ TTL์ด 1์‹œ๊ฐ„์ด๋ผ ๋งŒ๋ฃŒ ์ „์— ๊ฐฑ์‹ ํ•ด ์‚ฌ์šฉ์ž ์š”์ฒญ์— ๋งŒ๋ฃŒ hit์ด ์—†๊ฒŒ. setInterval(() => { warmup().catch((e) => console.warn('[warmup] failed:', e.message)); }, 30 * 60 * 1000); // ํ†ต๊ณผ ํƒญ keep-alive (2026-07-03, ์ฃผ๊ธฐ ๋‹จ์ถ• 2026-07-09) โ€” cf/WAF ํ† ํฐ ๋งŒ๋ฃŒ๋กœ // "์˜ค๋ž˜ ๋†”๋‘๋ฉด 202/challenge โ†’ ์žฌ์ƒ ์‹คํŒจ"๋˜๋˜ ๋ฌธ์ œ ๋Œ€์‘. // 4๋ถ„๋งˆ๋‹ค ํ˜„์žฌ ๋„๋ฉ”์ธ ํ†ต๊ณผ ํƒญ์„ ํ™”๋ฉด ๋ฐ– ๊ทธ๋Œ€๋กœ ์กฐ์šฉํžˆ reload โ†’ ํ† ํฐ ์„ ์ œ ๊ฐฑ์‹ . ํ†ต๊ณผ ํƒญ ์—†์œผ๋ฉด no-op. // ๊ธฐ์กด 10๋ถ„ ์ฃผ๊ธฐ๋กœ๋Š” ์œ ํœด ํ›„ ์ฒซ ์žฌ์ƒ์—์„œ ์ด๋ฏธ ํ† ํฐ์ด ๋งŒ๋ฃŒ๋ผ 202๊ฐ€ ๋‚˜๋˜ ์‚ฌ๋ก€๊ฐ€ ์žˆ์–ด 4๋ถ„์œผ๋กœ ๋‹น๊น€. // ๋ถ€ํŒ… ์งํ›„ 1ํšŒ๋Š” 2๋ถ„ ๋’ค(์ดˆ๊ธฐ ํ†ต๊ณผยท์›Œ๋ฐ์—…์ด ์ž๋ฆฌ์žก์€ ๋’ค)๋ถ€ํ„ฐ. if (USE_LOCAL_CDP) { // CDP ์ฐฝ ํ™”๋ฉด ์œ ์ง€ ์›Œ์ฒ˜ ์‹œ์ž‘ (2026-07-08) โ€” navigate/ํƒญ์ •๋ฆฌ๊ฐ€ ์ฐฝ์„ ํ™”๋ฉด ๋ฐ–/์ตœ์†Œํ™”๋กœ ๋ณด๋‚ด๋ฉด // 2์ดˆ๋งˆ๋‹ค ํ™”๋ฉด ์•ˆ์œผ๋กœ ๋˜๋Œ๋ฆผ. ํฌ์ปค์Šค๋Š” ์•ˆ ๋บ์Œ(SW_SHOWNOACTIVATE). ์‚ฌ์šฉ์ž๊ฐ€ ์ฐฝ ์ง์ ‘ ์ปจํŠธ๋กค. startCdpWindowWatcher(); setTimeout(() => { keepAlivePassedTab().catch(() => {}); setInterval(() => { keepAlivePassedTab().catch(() => {}); }, 4 * 60 * 1000); }, 2 * 60 * 1000); } // (์ œ๊ฑฐ๋จ 2026-06-30) cfClearanceMonitor(2๋ถ„ ์ฃผ๊ธฐ ์ฐฝ ๋„์šฐ๊ธฐ) + announceFollower(5๋ถ„ ์ฃผ๊ธฐ ์„ ์ œ ์žฌํƒ์ƒ‰). // ์šด์˜์ž๊ฐ€ ๋„๋ฉ”์ธ ๋ฒˆํ˜ธ๋ฅผ 208โ†’...โ†’213โ†’.live๋กœ ์ˆ˜์‹œ ๋ณ€๊ฒฝ โ†’ ์ถ”์ข… ๋ฃจํ”„๊ฐ€ ๋งค๋ฒˆ ์žฌํƒ์ƒ‰ + ์ƒˆ robots ํƒญ ์ƒ์„ฑ // โ†’ ํƒญ ํญ์ฆ + cf ์ฐฝ ํ™œ์„ฑํ™”โ†”์ตœ์†Œํ™” ๋ฌดํ•œ ๊นœ๋นก์ž„ ์‚ฌ๊ณ . ์ถ”์ข…/์ฐฝ ๋„์šฐ๊ธฐ๋ฅผ ์ „๋ถ€ ๊ฑท์–ด๋‚ด๊ณ , // findLiveDomain์ด tvchak.org announce๋ฅผ ๊ทธ๋•Œ๊ทธ๋•Œ ์ฝ์–ด ๊ทธ ๋„๋ฉ”์ธ์œผ๋กœ CDP ์—ฐ๊ฒฐํ•˜๋Š” ๋‹จ์ˆœ ๋ชจ๋ธ๋กœ ํšŒ๊ท€. // 1์‹œ๊ฐ„๋งˆ๋‹ค ๋žญํ‚น prefetch ์žฌ์‹œ๋„ โ€” ๋‚ ์งœ/์ฃผ/์›”์ด ๋„˜์–ด๊ฐ€๋ฉด ์ž๋™์œผ๋กœ ์ƒˆ ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ด. setInterval(() => { prefetchRankings().catch((e) => console.warn('[prefetch] failed:', e.message)); }, 60 * 60 * 1000); // SOCKS5 ๋ถ€ํ™œ ๊ฐ์ง€ โ†’ Playwright ์ปจํ…์ŠคํŠธ + ANI_BREAKER ๊ฐ•์ œ ๋ฆฌ์…‹. // entrypoint ์›Œ์น˜๋…์ด autossh ์žฌ๊ธฐ๋™ ํ›„ /tmp/socks5-respawned ํŒŒ์ผ์„ touchํ•จ. // server.js๊ฐ€ 30์ดˆ๋งˆ๋‹ค mtime ์ฒดํฌ โ†’ ์ƒˆ๋กœ ๊ฐฑ์‹ ๋์œผ๋ฉด ์˜› proxy ์—ฐ๊ฒฐ ์žก๊ณ  ์žˆ๋Š” ์ปจํ…์ŠคํŠธ ํ†ต์งธ๋กœ ํ๊ธฐ. const SIGNAL_FILE = '/tmp/socks5-respawned'; let _lastSignalMtime = 0; try { _lastSignalMtime = fs.statSync(SIGNAL_FILE).mtimeMs; } catch {} setInterval(() => { try { const mtime = fs.statSync(SIGNAL_FILE).mtimeMs; if (mtime > _lastSignalMtime) { _lastSignalMtime = mtime; console.warn(`[socks5-signal] SOCKS5 respawned โ€” recycling Playwright contexts + resetting breaker`); // tvchak ๋ธŒ๋ผ์šฐ์ € ํ๊ธฐ (๋‹ค์Œ ํ˜ธ์ถœ์—์„œ ์žฌ์ƒ์„ฑ๋จ) try { if (_tvPage) _tvPage.close().catch(() => {}); } catch {} _tvPage = null; _tvDomain = null; _tvFetchPage = null; _tvFetchPageDomain = null; try { if (_context) _context.close().catch(() => {}); } catch {} _context = null; try { if (_browser) _browser.close().catch(() => {}); } catch {} _browser = null; // tvchak ์ „์šฉ ์ปจํ…์ŠคํŠธ๋„ SOCKS5 ๊ฒฝ์œ ์ด๋ฏ€๋กœ ๊ฐ™์ด ํ๊ธฐ try { if (_tvContext) _tvContext.close().catch(() => {}); } catch {} _tvContext = null; try { if (_tvBrowser) _tvBrowser.close().catch(() => {}); } catch {} _tvBrowser = null; // anilife ๋ธŒ๋ผ์šฐ์ €(๋ณ„๊ฐœ)๋„ ํ๊ธฐ resetAniIsolated().catch(() => {}); // ์ฐจ๋‹จ๊ธฐ ์ฆ‰์‹œ ํ•ด์ œ โ€” ์ธํ”„๋ผ ํšŒ๋ณตํ–ˆ์œผ๋‹ˆ cooldown ํ๊ธฐ aniBreakerRecordSuccess(); } } catch { /* ์‹ ํ˜ธ ํŒŒ์ผ ์—†์œผ๋ฉด ๋ฌด์‹œ */ } }, 30 * 1000); console.log(`[socks5-signal] listening on ${SIGNAL_FILE}`); // self-heal ์›Œ์น˜๋…: ์ข€๋น„ ๊ฐ์ง€ ์‹œ ๊ฐ€๋ฒผ์šด ๋ณต๊ตฌ โ†’ ๋ฌด๊ฑฐ์šด ๋ณต๊ตฌ ๋‹จ๊ณ„์  ์ง„ํ–‰. // 1๋‹จ๊ณ„(๊ฐ€๋ฒผ์›€): Playwright tvchak context ๋ฆฌ์…‹ (mutex ์šฐํšŒ). ์ข€๋น„ evaluate๊ฐ€ ๋งค๋‹ฌ๋ ค ์žˆ์–ด๋„ ์ƒˆ context๋กœ ์‹œ์ž‘. // 2๋‹จ๊ณ„(์ค‘๊ฐ„): mutex ๊ฐ•์ œ ๋ฆฌ์…‹ + queue ๋น„์›€. ์ค„์„  ์š”์ฒญ ํ•œ๊บผ๋ฒˆ์— reject. // 3๋‹จ๊ณ„(๋ฌด๊ฑฐ์›€): HF Space restart. ์œ„ ๋‘˜ ๋‹ค ์•ˆ ํ†ตํ•  ๋•Œ. // // ์ข€๋น„์˜ ์ •์˜(2026-05-28 ๊ฐœ์ •): "์‹ค์ œ ํ˜ธ์ถœ์ด ์ง„ํ–‰ ์ค‘์ด๊ฑฐ๋‚˜ ์ค„์„œ ์žˆ๋Š”๋ฐ ์„ฑ๊ณต์ด ์•ˆ ๋‚˜์˜ค๋Š” ์ƒํƒœ". // ๊ธฐ์กด ๋กœ์ง์€ 5๋ถ„ ๋‚ด ํ™œ๋™์ด ์žˆ์œผ๋ฉด idle ์ƒํƒœ์—์„œ๋„ ์ข€๋น„ ํŒ์ • โ†’ ๋ฉ€์ฉกํ•œ ์ปจํ…์ŠคํŠธ๋ฅผ ์ž๊พธ ์ฃฝ์ด๊ณ  // ์‚ฌ์šฉ์ž ์ž…์žฅ์—์„  ๋Š๊น€ ๋ฐœ์ƒ. (in-flight ์นด์šดํ„ฐ๋กœ ์ •ํ™•ํ•œ ํŒ์ •) let zombieTicks = 0; const ZOMBIE_TICK_INTERVAL = 30 * 1000; // 30์ดˆ๋งˆ๋‹ค ์ ๊ฒ€ const ZOMBIE_STALE_MS = 180 * 1000; // ๋งˆ์ง€๋ง‰ ์„ฑ๊ณต 180์ดˆ ๋„˜์œผ๋ฉด ์ข€๋น„ ์˜์‹ฌ (idle vs ์ง„์งœ hang ๊ตฌ๋ถ„ ๊ฐ•ํ™”) let lightResetCooldown = 0; let hardResetCooldown = 0; let restartCooldown = 0; setInterval(async () => { // ์ข€๋น„์˜ ํ•ต์‹ฌ ์กฐ๊ฑด: ์ง€๊ธˆ in-flight ๋˜๋Š” queue ๋Œ€๊ธฐ๊ฐ€ ์žˆ๋Š”๋ฐ ์„ฑ๊ณต์ด ์˜ค๋ž˜๋˜๊ฑฐ๋‚˜, queue๊ฐ€ saturate๋œ ์ƒํƒœ. // idle(์•„๋ฌด ํ˜ธ์ถœ ์—†์Œ + ์ตœ๊ทผ ์„ฑ๊ณต๋„ ์—†์Œ)์€ ์ข€๋น„๊ฐ€ ์•„๋‹ˆ๋ผ ๊ทธ๋ƒฅ ํŠธ๋ž˜ํ”ฝ์ด ์—†๋Š” ๊ฒƒ โ€” skip. const queueBusy = _tvMutexQueueLen >= TV_MUTEX_QUEUE_MAX; const stale = (Date.now() - _tvLastSuccessAt) > ZOMBIE_STALE_MS; const hasPending = _tvInFlight > 0 || _tvMutexQueueLen > 0; // ์ข€๋น„ ์‹ ํ˜ธ: (a) queue ๊ฐ€๋“(=๋ช…๋ฐฑํ•œ ์ •์ฒด), ๋˜๋Š” (b) ์ง„ํ–‰ ์ค‘์ธ ํ˜ธ์ถœ์ด ์žˆ๋Š”๋ฐ stale. const zombieSignal = queueBusy || (stale && hasPending); if (!zombieSignal) { if (zombieTicks > 0) console.log(`[self-heal] tvchak recovered (was ${zombieTicks} ticks)`); zombieTicks = 0; return; } zombieTicks++; const ageSec = Math.round((Date.now() - _tvLastSuccessAt) / 1000); console.warn(`[self-heal] zombie signal #${zombieTicks} โ€” queueLen=${_tvMutexQueueLen} inFlight=${_tvInFlight} lastSuccess=${ageSec}s ago`); // 1ํ‹ฑ(30์ดˆ): ๊ฐ€๋ฒผ์šด ๋ณต๊ตฌ โ€” context ๋ฆฌ์…‹ if (zombieTicks === 1 && Date.now() > lightResetCooldown) { lightResetCooldown = Date.now() + 5 * 60 * 1000; console.warn(`[self-heal] LIGHT reset โ€” closing tvPage + tvContext (mutex bypass)`); try { if (_tvPage) _tvPage.close().catch(() => {}); } catch {} _tvPage = null; _tvDomain = null; _tvFetchPage = null; _tvFetchPageDomain = null; try { if (_tvContext) _tvContext.close().catch(() => {}); } catch {} _tvContext = null; try { if (_tvBrowser) _tvBrowser.close().catch(() => {}); } catch {} _tvBrowser = null; return; } // 2ํ‹ฑ(60์ดˆ): ์ค‘๊ฐ„ ๋ณต๊ตฌ โ€” mutex queue ๊ฐ•์ œ ๋น„์šฐ๊ธฐ if (zombieTicks === 2 && Date.now() > hardResetCooldown) { hardResetCooldown = Date.now() + 5 * 60 * 1000; console.warn(`[self-heal] HARD reset โ€” resetting mutex + clearing queue (${_tvMutexQueueLen} pending)`); _tvPageMutex = Promise.resolve(); _tvMutexQueueLen = 0; _tvLastSuccessAt = Date.now(); // ๋‹ค์Œ ์‚ฌ์ดํด์— ๋‹ค์‹œ ํŒ์ •ํ•˜๋„๋ก return; } // 3ํ‹ฑ(90์ดˆ): ๋ฌด๊ฑฐ์šด ๋ณต๊ตฌ โ€” HF Space ์žฌ์‹œ์ž‘ if (zombieTicks >= 3 && process.env.HF_SPACE_ID && process.env.HF_TOKEN && Date.now() > restartCooldown) { restartCooldown = Date.now() + 15 * 60 * 1000; zombieTicks = 0; console.warn(`[self-heal] FULL restart โ€” triggering HF Space restart`); try { const restartUrl = `https://huggingface.co/api/spaces/${process.env.HF_SPACE_ID}/restart`; const resp = await fetch(restartUrl, { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.HF_TOKEN}` }, }); console.warn(`[self-heal] restart API responded ${resp.status}`); } catch (err) { console.error(`[self-heal] restart API call failed:`, err.message); } } }, ZOMBIE_TICK_INTERVAL); console.log(`[self-heal] zombie watchdog armed (tick ${ZOMBIE_TICK_INTERVAL/1000}s, stale ${ZOMBIE_STALE_MS/1000}s)`); }); // ๋ถ€ํŒ… ์งํ›„ ๋˜๋Š” ์ฃผ๊ธฐ์ ์œผ๋กœ ํ˜ธ์ถœ๋˜๋Š” ์›Œ๋ฐ์—…: // 1) Playwright ๋ธŒ๋ผ์šฐ์ €/์ปจํ…์ŠคํŠธ๋ฅผ ๋ฏธ๋ฆฌ ๋„์›Œ cold init ๋น„์šฉ ์ œ๊ฑฐ // 2) findLiveDomain()์œผ๋กœ .cache/domain.json ๋ฏธ๋ฆฌ ์ฑ„์›€ (์บ์‹œ ์‹ ์„ ํ•˜๋ฉด ์™ธ๋ถ€ ํ˜ธ์ถœ ์•ˆ ํ•จ) // 3) ๋งˆ์ง€๋ง‰์— prefetchRankings() ํŠธ๋ฆฌ๊ฑฐ // HF Space cold start ํ›„ ์ฒซ ์‚ฌ์šฉ์ž๊ฐ€ /api/episodes ํ˜ธ์ถœํ–ˆ์„ ๋•Œ Playwright init + tvchak.org ํŽ˜์น˜๊ฐ€ // ๊ฐ™์€ 15์ดˆ timeout ์•ˆ์—์„œ ๋™์‹œ์— ์ผ์–ด๋‚˜ 'no live domain' 500์ด ๋œจ๋˜ ๋ฌธ์ œ ๋ฐฉ์ง€์šฉ. // SOCKS5 ํ„ฐ๋„์ด ์ง„์งœ outbound ํŠธ๋ž˜ํ”ฝ์„ ์ „๋‹ฌํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ๊ฒ€์ฆ. // entrypoint.sh์˜ "SOCKS5 tunnel ready"๋Š” TCP ํฌํŠธ๋งŒ ์—ด๋ฆฐ ์‹œ์ ์ด๋ผ // ์‹ค์ œ SSH ์ธ์ฆยท์•”ํ˜ธํ™” ์ฑ„๋„์ด ์•ˆ์ •ํ™”๋˜๊ธฐ ์ „์— ํ˜ธ์ถœํ•˜๋ฉด ์ฒซ TLS handshake๊ฐ€ ๋Š๊น€. // ๊ฐ€๋ฒผ์šด HTTPS HEAD๋ฅผ SOCKS5 ํ†ตํ•ด ์‹œ๋„ โ†’ ์„ฑ๊ณตํ•˜๋ฉด ready. ์ตœ๋Œ€ 6ํšŒ(์•ฝ 18์ดˆ) ์žฌ์‹œ๋„. async function verifySocks5Ready() { if (!process.env.SOCKS5_PROXY) return true; let agent; try { const { SocksProxyAgent } = require('socks-proxy-agent'); agent = new SocksProxyAgent(process.env.SOCKS5_PROXY); } catch (e) { console.warn('[boot] SOCKS5 verify: agent ์ƒ์„ฑ ์‹คํŒจ:', e.message); return false; } // ๊ฐ€๋ฒผ์šด HTTPS ์—”๋“œํฌ์ธํŠธ๋กœ ํ•ธ๋“œ์…ฐ์ดํฌ ํ™•์ธ. Cloudflare/๋ด‡ ์ฐจ๋‹จ ์˜ํ–ฅ ์—†๋Š” ํ‰๋ฒ”ํ•œ ํ˜ธ์ŠคํŠธ. const targets = ['https://api.ipify.org', 'https://1.1.1.1/']; for (let attempt = 0; attempt < 6; attempt++) { for (const url of targets) { const ok = await new Promise(resolve => { const u = new URL(url); const req = https.request({ hostname: u.hostname, port: 443, path: u.pathname || '/', method: 'HEAD', agent, timeout: 5000, rejectUnauthorized: false, }, (res) => { resolve(res.statusCode >= 200 && res.statusCode < 500); res.resume(); }); req.on('error', () => resolve(false)); req.on('timeout', () => { req.destroy(); resolve(false); }); req.end(); }); if (ok) return true; } // ์‹คํŒจ โ€” 3์ดˆ ํ›„ ์žฌ์‹œ๋„ await new Promise(r => setTimeout(r, 3000)); } return false; } async function warmup() { console.log('[warmup] start'); const t0 = Date.now(); try { await getContext(); console.log(`[warmup] playwright context ready (${Date.now() - t0}ms)`); } catch (e) { console.warn('[warmup] playwright context failed:', e.message); } let liveDomain = null; try { const d = await findLiveDomain(); liveDomain = d.domain; console.log(`[warmup] live domain: ${d.domain || 'NONE'} (${Date.now() - t0}ms total)`); } catch (e) { console.warn('[warmup] findLiveDomain failed:', e.message); } // tvPage ๋ฏธ๋ฆฌ ๋„์šฐ๊ธฐ โ€” ์‚ฌ์šฉ์ž ์ฒซ /api/play ํ˜ธ์ถœ์ด cold start ๋น„์šฉ(๋ฉ”์ธ ํŽ˜์ด์ง€ goto + Cloudflare ์ฑŒ๋ฆฐ์ง€) ์•ˆ ์น˜๋ฅด๋„๋ก. // ์‹คํŒจํ•ด๋„ ๋ฌด์‹œ: ์šด์˜ ์ค‘ ์‹ค ํ˜ธ์ถœ์—์„œ ensureTvPage๊ฐ€ ๋‹ค์‹œ ์‹œ๋„ํ•จ. if (liveDomain) { try { const t1 = Date.now(); await ensureTvPage(liveDomain); console.log(`[warmup] tvPage ready @ ${liveDomain} (${Date.now() - t1}ms)`); } catch (e) { console.warn('[warmup] ensureTvPage failed:', e.message); } } // ๋žญํ‚น prefetch๋„ ์›Œ๋ฐ์—…์˜ ์ผ๋ถ€๋กœ ์—ฐ์‡„ ํ˜ธ์ถœ (๊ฐ ์บ์‹œ ์ •์ฑ…์— ๋”ฐ๋ผ ์ด๋ฏธ ์‹ ์„ ํ•˜๋ฉด no-op) try { await prefetchRankings(); } catch (e) { console.warn('[warmup] prefetchRankings failed:', e.message); } console.log(`[warmup] done (${Date.now() - t0}ms)`); } async function prefetchRankings() { console.log('[prefetch] start'); const periods = ['daily', 'weekly', 'monthly']; // 1) ๋žญํ‚น 3๊ฐœ๋ฅผ ์ˆœ์ฐจ๋กœ ๊ฐ€์ ธ์˜ด (๋ธŒ๋ผ์šฐ์ € ์ปจํ…์ŠคํŠธ ๋™์‹œ ์‚ฌ์šฉ ๋ถ€๋‹ด ์ค„์ด๊ธฐ) const allItems = []; for (const period of periods) { try { const r = await fetchKinoRanking(period, { fetchIfMissing: true }); if (r && Array.isArray(r.items)) allItems.push(...r.items); console.log(`[prefetch] ranking ${period}: ${r?.items?.length ?? 0} items`); } catch (e) { console.warn(`[prefetch] ranking ${period} failed:`, e.message); } } // 2) TOP 10์— ๋“ฑ์žฅํ•œ ์ž‘ํ’ˆ์˜ ํ‚ค๋…ธ๋ผ์ด์ธ  ์ƒ์„ธ + ์œ ํŠœ๋ธŒ ์˜ˆ๊ณ ํŽธ prefetch. // href์—์„œ title id ์ถ”์ถœ, ์ œ๋ชฉ์œผ๋กœ ์˜ˆ๊ณ ํŽธ ๊ฒ€์ƒ‰. ์ค‘๋ณต ์ œ๊ฑฐ. const detailIds = new Set(); const titles = new Set(); for (const it of allItems) { if (it?.href) { const m = String(it.href).match(/\/title\/(\d+)/); if (m) detailIds.add(parseInt(m[1], 10)); } if (it?.title) titles.add(it.title); } for (const id of detailIds) { try { await fetchKinoDetail(id, { fetchIfMissing: true }); } catch (e) { console.warn(`[prefetch] detail ${id} failed:`, e.message); } } console.log(`[prefetch] details: ${detailIds.size}`); for (const t of titles) { try { await fetchYoutubeTrailer(t, { fetchIfMissing: true }); } catch (e) { console.warn(`[prefetch] trailer "${t}" failed:`, e.message); } } console.log(`[prefetch] trailers: ${titles.size}`); console.log('[prefetch] done'); } process.on('SIGINT', async () => { console.log('shutting down...'); try { if (_browser) await _browser.close(); } catch {} try { if (_aniBrowser) await _aniBrowser.close(); } catch {} process.exit(0); });
// ๋กœ์ปฌ ๋ฐฑ์—”๋“œ (Playwright ํ—ค๋“œ๋ฆฌ์Šค๋กœ tvchak Cloudflare ๋ด‡์ฐจ๋‹จ ์šฐํšŒ)
// GET / -> index.html
// GET /api/domain -> ํ˜„์žฌ ๊ณต์‹ ๋„๋ฉ”์ธ
// GET /api/episodes?id=ID -> ์‹œ๋ฆฌ์ฆˆ ํšŒ์ฐจ ๋ชฉ๋ก + ์ œ๋ชฉ
// GET /api/play?id&sid&nid -> { url, url_next, link_next, link_pre, vod_data }
// GET /api/search?wd=... -> ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ์นด๋“œ ๋ชฉ๋ก
// GET /api/flush -> ์บ์‹œ ๋น„์šฐ๊ธฐ
// GET /api/cdn?u=ENCODED -> mp4 CDN ํ”„๋ก์‹œ (Referer ํ—ค๋” ์ž๋™ ์ถ”๊ฐ€)
//
// ์‹คํ–‰: node server.js (ํฌํŠธ 8787)
const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const url = require('url');
const { chromium } = require('playwright');
const PORT = process.env.PORT || 8787;
const ROOT = __dirname;
// ์บ์‹œ/๋ฐ์ดํ„ฐ ๋””๋ ‰ํ† ๋ฆฌ. HF Spaces ๊ฐ™์€ read-only FS ํ™˜๊ฒฝ ๋Œ€์‘์„ ์œ„ํ•ด ํ™˜๊ฒฝ๋ณ€์ˆ˜๋กœ override ๊ฐ€๋Šฅ.
// CACHE_DIR=/tmp/.cache DATA_DIR=/tmp/.data
const CACHE_DIR = process.env.CACHE_DIR || path.join(ROOT, '.cache');
// ๋ถ€ํŒ… ์‹œ ๋นˆ๊ฐ’ ์บ์‹œ๋œ namu ํฌ์Šคํ„ฐ ํŒŒ์ผ ์ •๋ฆฌ โ€” ์ฝ”๋“œ ๊ฐœ์„ ์œผ๋กœ ์ด์ œ ์ฐพ์„ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ ๋Œ€๋น„
try {
if (fs.existsSync(CACHE_DIR)) {
for (const f of fs.readdirSync(CACHE_DIR)) {
if (!f.startsWith('namu_poster_')) continue;
try {
const j = JSON.parse(fs.readFileSync(path.join(CACHE_DIR, f), 'utf-8'));
if (!j || !j.poster) fs.unlinkSync(path.join(CACHE_DIR, f));
} catch { try { fs.unlinkSync(path.join(CACHE_DIR, f)); } catch {} }
}
}
} catch (e) { console.warn('[namu] cleanup empty cache failed:', e.message); }
if (!fs.existsSync(CACHE_DIR)) fs.mkdirSync(CACHE_DIR, { recursive: true });
const DATA_DIR = process.env.DATA_DIR || path.join(ROOT, '.data');
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
const LEGACY_FAVS_FILE = path.join(DATA_DIR, 'favs.json');
function profileFile(profile) {
const p = Math.max(1, Math.min(5, parseInt(profile, 10) || 1));
return path.join(DATA_DIR, `favs_p${p}.json`);
}
function readFavs(profile) {
// ๋งˆ์ด๊ทธ๋ ˆ์ด์…˜: profile=1์ด๊ณ  ๊ทธ์ชฝ ํŒŒ์ผ ์—†์œผ๋ฉด legacy favs.json์„ ์‚ฌ์šฉ
const fp = profileFile(profile);
if (!fs.existsSync(fp)) {
if ((parseInt(profile, 10) || 1) === 1 && fs.existsSync(LEGACY_FAVS_FILE)) {
try {
const legacy = JSON.parse(fs.readFileSync(LEGACY_FAVS_FILE, 'utf-8'));
fs.writeFileSync(fp, JSON.stringify(legacy, null, 2));
return legacy;
} catch {}
}
return { favs: [], lastFavId: null, updatedAt: 0 };
}
try { return JSON.parse(fs.readFileSync(fp, 'utf-8')); }
catch { return { favs: [], lastFavId: null, updatedAt: 0 }; }
}
const { spawn, spawnSync } = require('child_process');
// NAS ๋™๊ธฐํ™” ์ž๋™ ํ™œ์„ฑ โ€” ํ•„์š”ํ•œ env๊ฐ€ ๋ชจ๋‘ ์žˆ์œผ๋ฉด ON
const NAS_SYNC_ENABLED = !!(
process.env.NAS_SSH_HOST &&
process.env.NAS_SSH_USER &&
fs.existsSync(`${process.env.KEY_DIR || '/tmp/ssh-key-dir'}/nas-key`)
);
if (NAS_SYNC_ENABLED) console.log(`[nas-favs] sync enabled (host=${process.env.NAS_SSH_HOST})`);
function writeFavs(profile, obj) {
obj.updatedAt = Date.now();
fs.writeFileSync(profileFile(profile), JSON.stringify(obj, null, 2));
if (NAS_SYNC_ENABLED) schedulePushToNas(profile);
return obj;
}
// latest-labels ๋ฐฑ๊ทธ๋ผ์šด๋“œ fetchEpisodes ์ค‘๋ณต ํ˜ธ์ถœ ๋ฐฉ์ง€.
// ๊ฐ™์€ id+source๊ฐ€ in-flight๋ฉด ์ƒˆ ํ˜ธ์ถœ skip โ€” ํด๋ผ์ด์–ธํŠธ๊ฐ€ pending ๋ณด๊ณ  ์žฌํ˜ธ์ถœํ•˜๊ฑฐ๋‚˜
// ์—ฌ๋Ÿฌ ๋””๋ฐ”์ด์Šค/ํƒญ์ด ๋™์‹œ ํด๋งํ•ด๋„ ๊ฐ™์€ ep๋กœ ํ๊ฐ€ ๊ณฑ์…ˆ ํญ์ฃผํ•˜์ง€ ์•Š๊ฒŒ.
const _latestLabelsInFlight = new Set();
// NAS ์ƒํƒœ โ€” ๋‹ค์šด ์‹œ ๋กœ์ปฌ ์บ์‹œ๋งŒ์œผ๋กœ ๋™์ž‘. ํšŒ๋ณต ์‹œ ๋ˆ„๋ฝ push ์ผ๊ด„ ์žฌ์‹œ๋„.
const _failedPush = new Set(); // ๋งˆ์ง€๋ง‰ push๊ฐ€ ์‹คํŒจํ•œ ํ”„๋กœํ•„ ๋ฒˆํ˜ธ๋“ค
let _nasReachable = null; // true=์ •์ƒ, false=๋‹ค์šด, null=๋ฏธํ™•์ธ. ์ƒํƒœ ์ „ํ™˜ ์‹œ์—๋งŒ ๋กœ๊ทธ
function markNasStatus(reachable) {
if (_nasReachable === reachable) return;
_nasReachable = reachable;
if (reachable) {
console.log(`[nas-favs] ONLINE${_failedPush.size ? ` โ€” flushing ${_failedPush.size} pending push(es)` : ''}`);
// ํšŒ๋ณต ์‹œ ๋ˆ„๋ฝ push ์ผ๊ด„ ์žฌ์‹œ๋„
if (_failedPush.size) {
const ps = [..._failedPush];
_failedPush.clear();
for (const p of ps) doPushToNas(p);
}
} else {
console.warn('[nas-favs] OFFLINE โ€” using local cache only (changes will sync when NAS recovers)');
}