Spaces:
Paused
Paused
Download server.js from myott/ott-player: direct link, hf CLI and curl.
- Browser
- Download file 196 kB
-
https://huggingface.co/spaces/myott/ott-player/resolve/main/server.js
- Command line
-
hf download hf://spaces/myott/ott-player/server.js
-
curl -L -o server.js https://huggingface.co/spaces/myott/ott-player/resolve/main/server.js
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(/&/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(/&/g, '&').replace(/ /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(/&/g, '&').replace(/ /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(/&/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)');
}