Spaces:
Paused
feat: anilife → linkkf 자동 폴백 (장애 시 백업 소스)
Browse filesanilife 장애 시 linkkf.tv에서 같은 시리즈 자동 검색·재생.
사용자 보관함은 그대로 (source=anilife 유지), 서버가 내부에서 폴백 처리.
서버:
- linkkfSearch/Episodes/Play — tvchak과 동일한 player_aaaa 패턴, 토큰→m3u8 매핑
- scoreLinkkfCandidate — 제목 정규화 일치 + 회차 수 근접도(targetCount 기반)로
최적 후보 자동 선택. "나루토" 720화 → 본편 21707(693ep) 정확 매칭 확인.
- 매핑 캐시 linkkf_map_{anilifeId}.json — 한 번 매칭하면 영구, 실패는 7일 후 재시도
- /api/episodes&source=anilife 응답 비었으면(error 또는 episodes=[]) 자동 폴백
- /api/cdn proxy에 linkkf host(ssku*.top, play.sub*.top) 인식: Referer 자동
+ SOCKS5(NAS residential IP) 경유 (datacenter 차단 회피)
클라이언트:
- loadEpisodes에 &count, &fallbackId 쿼리 추가 — 서버가 검색 단계 스킵 가능
- fav.fallbackLinkkfId 자동 저장 (자동 백업 매핑)
- 폴백 사용 시 nowMeta 제목 옆에 작은 'linkkf' 배지 (.fb-badge)
알려진 한계:
- linkkf가 시즌별로 분리 등록한 작품(귀멸·진격 등)은 시즌 1만 매칭됨.
자동 매칭으로는 한계, 필요 시 수동 매핑.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- index.html +19 -4
- server.js +347 -4
|
@@ -368,6 +368,9 @@
|
|
| 368 |
vertical-align: middle; margin-right: 4px; font-weight: 700; letter-spacing: 0.5px; }
|
| 369 |
.src-badge.ani { background: #5b3df5; color: #fff; }
|
| 370 |
.src-badge.tv { background: #16a34a; color: #fff; } /* 드라마 */
|
|
|
|
|
|
|
|
|
|
| 371 |
.src-badge.tv.ent { background: #d97706; color: #fff; } /* 예능 */
|
| 372 |
.src-badge.tv.mov { background: #1865f2; color: #fff; } /* 영화 */
|
| 373 |
|
|
@@ -1467,13 +1470,20 @@ async function loadEpisodes(fav) {
|
|
| 1467 |
$('#epSection').style.display = 'none';
|
| 1468 |
try {
|
| 1469 |
const src = fav.source || 'tvchak';
|
| 1470 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1471 |
if (ep.error) {
|
| 1472 |
console.warn('episodes', ep.error);
|
| 1473 |
return;
|
| 1474 |
}
|
| 1475 |
if (ep.title && !fav.title) fav.title = ep.title;
|
| 1476 |
if (ep.category && !fav.category) fav.category = ep.category; // E2: tvchak 카테고리 (드라마/예능/영화 등)
|
|
|
|
|
|
|
|
|
|
| 1477 |
// E-2: 옛 placeholder URL 정리 + ep 응답의 poster 활용 + posterAlt (anilife용 fallback)
|
| 1478 |
if (fav.poster && /\/template\//.test(fav.poster)) fav.poster = null;
|
| 1479 |
if (ep.poster) fav.poster = ep.poster; // 항상 최신값으로 갱신 (서버가 namu fallback 거친 결과)
|
|
@@ -1747,6 +1757,9 @@ async function playEpisode(id, sid, nid, opts = {}) {
|
|
| 1747 |
const ep = currentEpList.find(e => e.sid === sid && e.nid === nid) || currentEpList.find(e => e.nid === nid);
|
| 1748 |
const epLabel = (ep && ep.label) || `${nid}화`;
|
| 1749 |
const sourceLabel = src === 'anilife' ? '<span class="src-badge ani">애니</span> ' : '';
|
|
|
|
|
|
|
|
|
|
| 1750 |
// 다운로드: tvchak은 직접 mp4 다운로드, anilife는 HLS라 아직 미지원
|
| 1751 |
const canDownload = src === 'tvchak' && p.url;
|
| 1752 |
const dlBtn = canDownload
|
|
@@ -1754,7 +1767,7 @@ async function playEpisode(id, sid, nid, opts = {}) {
|
|
| 1754 |
: '';
|
| 1755 |
$('#nowMeta').innerHTML = `
|
| 1756 |
<div class="title-row">
|
| 1757 |
-
<div class="title">${sourceLabel}${esc(title)}</div>
|
| 1758 |
${dlBtn}
|
| 1759 |
</div>
|
| 1760 |
<div class="sub">${esc(epLabel)}${ep?.subject ? ' · ' + esc(ep.subject) : ''} ${p.vod_data?.vod_class ? '· ' + esc(p.vod_data.vod_class) : ''} ${p.vod_data?.vod_actor ? '· ' + esc(p.vod_data.vod_actor) : ''}</div>
|
|
@@ -2386,7 +2399,8 @@ async function refreshAll() {
|
|
| 2386 |
for (const f of favs) {
|
| 2387 |
try {
|
| 2388 |
const src = f.source || 'tvchak';
|
| 2389 |
-
const
|
|
|
|
| 2390 |
if (ep.error || !ep.episodes) continue;
|
| 2391 |
if (!f.title) f.title = ep.title;
|
| 2392 |
f.knownCount = ep.count;
|
|
@@ -2416,7 +2430,8 @@ async function refreshAll() {
|
|
| 2416 |
: favs.find(f => f.id === currentFavId);
|
| 2417 |
if (fav) {
|
| 2418 |
const src = fav.source || 'tvchak';
|
| 2419 |
-
const
|
|
|
|
| 2420 |
if (!ep.error) {
|
| 2421 |
currentEpList = ep.episodes || [];
|
| 2422 |
if (fav.lastSid != null) {
|
|
|
|
| 368 |
vertical-align: middle; margin-right: 4px; font-weight: 700; letter-spacing: 0.5px; }
|
| 369 |
.src-badge.ani { background: #5b3df5; color: #fff; }
|
| 370 |
.src-badge.tv { background: #16a34a; color: #fff; } /* 드라마 */
|
| 371 |
+
.fb-badge { display: inline-block; font-size: 9px; padding: 1px 4px; border-radius: 3px;
|
| 372 |
+
background: #404555; color: #c5cad6; font-weight: 600; letter-spacing: 0.3px;
|
| 373 |
+
vertical-align: middle; margin-left: 4px; opacity: 0.8; }
|
| 374 |
.src-badge.tv.ent { background: #d97706; color: #fff; } /* 예능 */
|
| 375 |
.src-badge.tv.mov { background: #1865f2; color: #fff; } /* 영화 */
|
| 376 |
|
|
|
|
| 1470 |
$('#epSection').style.display = 'none';
|
| 1471 |
try {
|
| 1472 |
const src = fav.source || 'tvchak';
|
| 1473 |
+
const titleQ = fav.title ? `&title=${encodeURIComponent(fav.title)}` : '';
|
| 1474 |
+
// 폴백 매핑 힌트: 클라이언트가 알고 있는 linkkf id + anilife 회차 수 → 서버가 검색 단계 스킵 가능
|
| 1475 |
+
const fbQ = (src === 'anilife' && fav.fallbackLinkkfId) ? `&fallbackId=${fav.fallbackLinkkfId}` : '';
|
| 1476 |
+
const countQ = (src === 'anilife' && fav.knownCount) ? `&count=${fav.knownCount}` : '';
|
| 1477 |
+
const ep = await api(`/api/episodes?id=${fav.id}&source=${src}${titleQ}${fbQ}${countQ}`);
|
| 1478 |
if (ep.error) {
|
| 1479 |
console.warn('episodes', ep.error);
|
| 1480 |
return;
|
| 1481 |
}
|
| 1482 |
if (ep.title && !fav.title) fav.title = ep.title;
|
| 1483 |
if (ep.category && !fav.category) fav.category = ep.category; // E2: tvchak 카테고리 (드라마/예능/영화 등)
|
| 1484 |
+
// linkkf 폴백 사용 사실 저장 — 다음 호출에 fallbackId 직접 전달
|
| 1485 |
+
if (ep._fallbackLinkkfId) fav.fallbackLinkkfId = ep._fallbackLinkkfId;
|
| 1486 |
+
fav.usingFallback = ep._fallbackSource || null; // UI 배지용
|
| 1487 |
// E-2: 옛 placeholder URL 정리 + ep 응답의 poster 활용 + posterAlt (anilife용 fallback)
|
| 1488 |
if (fav.poster && /\/template\//.test(fav.poster)) fav.poster = null;
|
| 1489 |
if (ep.poster) fav.poster = ep.poster; // 항상 최신값으로 갱신 (서버가 namu fallback 거친 결과)
|
|
|
|
| 1757 |
const ep = currentEpList.find(e => e.sid === sid && e.nid === nid) || currentEpList.find(e => e.nid === nid);
|
| 1758 |
const epLabel = (ep && ep.label) || `${nid}화`;
|
| 1759 |
const sourceLabel = src === 'anilife' ? '<span class="src-badge ani">애니</span> ' : '';
|
| 1760 |
+
// 폴백 사용 시 작은 배지 — play 응답의 _fallbackSource(서버) 또는 fav.usingFallback(loadEpisodes에서 저장한 값)
|
| 1761 |
+
const fbSrc = p._fallbackSource || fav?.usingFallback;
|
| 1762 |
+
const fallbackBadge = fbSrc ? `<span class="fb-badge" title="원본(${src}) 차단·장애로 ${fbSrc}에서 재생 중">${esc(fbSrc)}</span> ` : '';
|
| 1763 |
// 다운로드: tvchak은 직접 mp4 다운로드, anilife는 HLS라 아직 미지원
|
| 1764 |
const canDownload = src === 'tvchak' && p.url;
|
| 1765 |
const dlBtn = canDownload
|
|
|
|
| 1767 |
: '';
|
| 1768 |
$('#nowMeta').innerHTML = `
|
| 1769 |
<div class="title-row">
|
| 1770 |
+
<div class="title">${sourceLabel}${esc(title)}${fallbackBadge}</div>
|
| 1771 |
${dlBtn}
|
| 1772 |
</div>
|
| 1773 |
<div class="sub">${esc(epLabel)}${ep?.subject ? ' · ' + esc(ep.subject) : ''} ${p.vod_data?.vod_class ? '· ' + esc(p.vod_data.vod_class) : ''} ${p.vod_data?.vod_actor ? '· ' + esc(p.vod_data.vod_actor) : ''}</div>
|
|
|
|
| 2399 |
for (const f of favs) {
|
| 2400 |
try {
|
| 2401 |
const src = f.source || 'tvchak';
|
| 2402 |
+
const titleQ = f.title ? `&title=${encodeURIComponent(f.title)}` : '';
|
| 2403 |
+
const ep = await api(`/api/episodes?id=${f.id}&nocache=1&source=${src}${titleQ}`);
|
| 2404 |
if (ep.error || !ep.episodes) continue;
|
| 2405 |
if (!f.title) f.title = ep.title;
|
| 2406 |
f.knownCount = ep.count;
|
|
|
|
| 2430 |
: favs.find(f => f.id === currentFavId);
|
| 2431 |
if (fav) {
|
| 2432 |
const src = fav.source || 'tvchak';
|
| 2433 |
+
const titleQ = fav.title ? `&title=${encodeURIComponent(fav.title)}` : '';
|
| 2434 |
+
const ep = await api(`/api/episodes?id=${fav.id}&nocache=1&source=${src}${titleQ}`);
|
| 2435 |
if (!ep.error) {
|
| 2436 |
currentEpList = ep.episodes || [];
|
| 2437 |
if (fav.lastSid != null) {
|
|
@@ -752,6 +752,323 @@ async function _aniPlayInternal(uniqueId) {
|
|
| 752 |
}
|
| 753 |
|
| 754 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 755 |
// ───── 도메인 탐지 ─────
|
| 756 |
async function findLiveDomain() {
|
| 757 |
// 살아있는 도메인 캐시는 1시간 유지. domain이 null인 캐시는 신뢰 X (재시도).
|
|
@@ -1489,8 +1806,11 @@ function proxyCdn(req, res) {
|
|
| 1489 |
|
| 1490 |
const cachedDomain = readCache('domain.json', 1e9);
|
| 1491 |
const isAniLikeHost = /anilife|gcdn\.app/.test(target);
|
|
|
|
| 1492 |
const referer = u.query.r
|
| 1493 |
-
|| (isAniLikeHost ? 'https://anilife.app/'
|
|
|
|
|
|
|
| 1494 |
|
| 1495 |
const t = new URL(target);
|
| 1496 |
const reqHeaders = {
|
|
@@ -1510,8 +1830,9 @@ function proxyCdn(req, res) {
|
|
| 1510 |
rejectUnauthorized: false,
|
| 1511 |
};
|
| 1512 |
// anilife/gcdn 은 manifest 발급 IP에서만 유효 → SOCKS5(NAS residential) 경유 필수.
|
|
|
|
| 1513 |
// BunnyCDN ��은 datacenter OK이므로 직접 호출.
|
| 1514 |
-
if (isAniLikeHost && _socksAgent) reqOpts.agent = _socksAgent;
|
| 1515 |
|
| 1516 |
const upstream = https.request(reqOpts, (up) => {
|
| 1517 |
const ct = up.headers['content-type'] || '';
|
|
@@ -1634,7 +1955,23 @@ async function handleApi(req, res, parsed) {
|
|
| 1634 |
}
|
| 1635 |
else if (p === '/api/domain') out = await findLiveDomain();
|
| 1636 |
else if (p === '/api/episodes') {
|
| 1637 |
-
if (q.source === 'anilife')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1638 |
else out = await fetchEpisodes(q.id, { nocache: !!q.nocache });
|
| 1639 |
}
|
| 1640 |
else if (p === '/api/latest-labels') {
|
|
@@ -1687,7 +2024,13 @@ async function handleApi(req, res, parsed) {
|
|
| 1687 |
out = { items, pending: pending.map(p => p.id) };
|
| 1688 |
}
|
| 1689 |
else if (p === '/api/play') {
|
| 1690 |
-
if (q.source === 'anilife')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1691 |
else out = await fetchPlay(q.id, q.sid, q.nid);
|
| 1692 |
}
|
| 1693 |
else if (p === '/api/search') {
|
|
|
|
| 752 |
}
|
| 753 |
|
| 754 |
|
| 755 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 756 |
+
// LINKKF — anilife 폴백 소스 (linkkf.tv)
|
| 757 |
+
// ═══════════════════════════════════════════════════════════════════════════
|
| 758 |
+
// 구조:
|
| 759 |
+
// /view/?wd=KEYWORD → 검색 (HTML)
|
| 760 |
+
// /ani/{id}/ → 시리즈 상세 + 회차 링크 (HTML)
|
| 761 |
+
// /watch/{id}/a{sid}/k{nid}/ → 재생 페이지 (player_aaaa.url 토큰)
|
| 762 |
+
// 토큰 21707m1 → https://pp5.ssku1.top/{token}/index.m3u8 (Referer: play.sub3.top)
|
| 763 |
+
// nid 컨벤션: linkkf 원본은 k1=1화(가장 옛). 우리 시스템은 nid=1이 최신 → 뒤집어 정규화.
|
| 764 |
+
// player m3u8은 Referer 필요 — /api/cdn 프록시에서 처리.
|
| 765 |
+
|
| 766 |
+
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';
|
| 767 |
+
|
| 768 |
+
// 가벼운 fetch 헬퍼 (linkkf는 Cloudflare 가벼운 보호라 직접 fetch OK. 단 SOCKS5 미사용 — datacenter IP면 차단 가능성).
|
| 769 |
+
// HF 환경에서 datacenter IP라 차단되면 Playwright 컨텍스트 빌려 우회. 일단 fetch 시도 → 실패 시 Playwright fallback.
|
| 770 |
+
async function linkkfFetchHtml(url, opts = {}) {
|
| 771 |
+
const timeout = opts.timeout || 12000;
|
| 772 |
+
try {
|
| 773 |
+
const ctrl = new AbortController();
|
| 774 |
+
const t = setTimeout(() => ctrl.abort(), timeout);
|
| 775 |
+
const r = await fetch(url, {
|
| 776 |
+
headers: { 'User-Agent': LINKKF_UA, 'Accept-Language': 'ko-KR,ko;q=0.9' },
|
| 777 |
+
signal: ctrl.signal,
|
| 778 |
+
});
|
| 779 |
+
clearTimeout(t);
|
| 780 |
+
if (r.status >= 200 && r.status < 400) {
|
| 781 |
+
const html = await r.text();
|
| 782 |
+
if (html && html.length > 1000) return html;
|
| 783 |
+
}
|
| 784 |
+
} catch (e) {
|
| 785 |
+
console.warn(`[linkkf] fetch failed (${url}), trying Playwright:`, e.message);
|
| 786 |
+
}
|
| 787 |
+
// Playwright fallback — anilife 컨텍스트 빌려서 (SOCKS5 경유 시 한국 IP 효과)
|
| 788 |
+
try {
|
| 789 |
+
if (!_browser) await getContext();
|
| 790 |
+
const ctx = await _browser.newContext({ userAgent: LINKKF_UA, locale: 'ko-KR' });
|
| 791 |
+
try {
|
| 792 |
+
const p = await ctx.newPage();
|
| 793 |
+
await p.goto(url, { waitUntil: 'domcontentloaded', timeout });
|
| 794 |
+
const html = await p.content();
|
| 795 |
+
await p.close().catch(() => {});
|
| 796 |
+
return html;
|
| 797 |
+
} finally { await ctx.close().catch(() => {}); }
|
| 798 |
+
} catch (e) {
|
| 799 |
+
console.warn(`[linkkf] Playwright fallback failed (${url}):`, e.message);
|
| 800 |
+
return null;
|
| 801 |
+
}
|
| 802 |
+
}
|
| 803 |
+
|
| 804 |
+
// 검색 — /view/?wd=...
|
| 805 |
+
async function linkkfSearch(wd) {
|
| 806 |
+
wd = (wd || '').trim();
|
| 807 |
+
if (!wd) return { items: [] };
|
| 808 |
+
const html = await linkkfFetchHtml(`https://linkkf.tv/view/?wd=${encodeURIComponent(wd)}`);
|
| 809 |
+
if (!html) return { items: [], error: 'fetch failed' };
|
| 810 |
+
// a 태그: <a href="/ani/{id}/">제목</a> — 검색 결과 카드
|
| 811 |
+
const re = /href="\/ani\/(\d+)\/"[^>]*>([^<]{1,80})</g;
|
| 812 |
+
const items = [];
|
| 813 |
+
const seen = new Set();
|
| 814 |
+
let m;
|
| 815 |
+
while ((m = re.exec(html))) {
|
| 816 |
+
const id = parseInt(m[1], 10);
|
| 817 |
+
const title = m[2].trim();
|
| 818 |
+
if (!id || seen.has(id) || !title) continue;
|
| 819 |
+
seen.add(id);
|
| 820 |
+
items.push({ id, title, source: 'linkkf' });
|
| 821 |
+
}
|
| 822 |
+
return { items };
|
| 823 |
+
}
|
| 824 |
+
|
| 825 |
+
// 회차 목록 + 시리즈 정보 — /ani/{id}/
|
| 826 |
+
async function linkkfEpisodes(id, opts = {}) {
|
| 827 |
+
id = parseInt(id, 10);
|
| 828 |
+
if (!id) return { error: 'bad id' };
|
| 829 |
+
const cacheFile = `linkkf_ep_${id}.json`;
|
| 830 |
+
if (!opts.nocache) {
|
| 831 |
+
const cached = readCache(cacheFile, 300);
|
| 832 |
+
if (cached) return cached;
|
| 833 |
+
}
|
| 834 |
+
const html = await linkkfFetchHtml(`https://linkkf.tv/ani/${id}/`);
|
| 835 |
+
if (!html) return { error: 'fetch failed' };
|
| 836 |
+
// 제목
|
| 837 |
+
const titleMatch = html.match(/<h1[^>]*class="detail-info-title[^"]*"[^>]*>([^<]+)</);
|
| 838 |
+
const title = titleMatch ? titleMatch[1].trim() : null;
|
| 839 |
+
// 포스터
|
| 840 |
+
const posterMatch = html.match(/<img[^>]+class="[^"]*detail-pic[^"]*"[^>]+src="([^"]+)"/) ||
|
| 841 |
+
html.match(/<meta[^>]+property="og:image"[^>]+content="([^"]+)"/);
|
| 842 |
+
const poster = posterMatch ? posterMatch[1] : null;
|
| 843 |
+
// 회차 링크 — /watch/{id}/a{sid}/k{nid}/ + 라벨
|
| 844 |
+
const epRe = new RegExp(`href="/watch/${id}/a(\\d+)/k(\\d+)/"[^>]*>([^<]*)<`, 'g');
|
| 845 |
+
const rawEps = [];
|
| 846 |
+
let m;
|
| 847 |
+
while ((m = epRe.exec(html))) {
|
| 848 |
+
const sid = parseInt(m[1], 10);
|
| 849 |
+
const linkkfNid = parseInt(m[2], 10);
|
| 850 |
+
let label = (m[3] || '').trim();
|
| 851 |
+
if (!label) continue; // 라벨 없는 ▶ 버튼 같은 항목 제외
|
| 852 |
+
// 라벨 정규화: 숫자만 있으면 "N화" 형태로 (linkkf는 "1", "720", "714-715" 같이 들어옴)
|
| 853 |
+
if (/^\d+(-\d+)?$/.test(label)) label = `${label}화`;
|
| 854 |
+
rawEps.push({ sid, linkkfNid, label });
|
| 855 |
+
}
|
| 856 |
+
if (!rawEps.length) {
|
| 857 |
+
return { id, title, poster, count: 0, episodes: [], source: 'linkkf', error: 'no episodes' };
|
| 858 |
+
}
|
| 859 |
+
// linkkf 원본: k1이 가장 옛, 큰 k가 최신. 우리 컨벤션은 nid=1이 최신.
|
| 860 |
+
// → linkkfNid 내림차순으로 정렬해서 nid=1,2,3... 할당
|
| 861 |
+
rawEps.sort((a, b) => b.linkkfNid - a.linkkfNid);
|
| 862 |
+
const eps = rawEps.map((e, i) => ({
|
| 863 |
+
sid: e.sid, nid: i + 1,
|
| 864 |
+
label: e.label,
|
| 865 |
+
linkkfNid: e.linkkfNid, // 재생 시 원본 nid 필요
|
| 866 |
+
}));
|
| 867 |
+
const out = {
|
| 868 |
+
id, title, poster,
|
| 869 |
+
count: eps.length,
|
| 870 |
+
episodes: eps,
|
| 871 |
+
source: 'linkkf',
|
| 872 |
+
checked_at: new Date().toISOString(),
|
| 873 |
+
};
|
| 874 |
+
writeCache(cacheFile, out);
|
| 875 |
+
return out;
|
| 876 |
+
}
|
| 877 |
+
|
| 878 |
+
// 재생 — watch 페이지에서 player_aaaa.url 토큰 추출 → m3u8 URL 조립
|
| 879 |
+
async function linkkfPlay(id, sid, linkkfNid) {
|
| 880 |
+
id = parseInt(id, 10);
|
| 881 |
+
sid = parseInt(sid, 10);
|
| 882 |
+
linkkfNid = parseInt(linkkfNid, 10);
|
| 883 |
+
if (!id || !sid || !linkkfNid) return { error: 'bad params' };
|
| 884 |
+
const html = await linkkfFetchHtml(`https://linkkf.tv/watch/${id}/a${sid}/k${linkkfNid}/`);
|
| 885 |
+
if (!html) return { error: 'fetch failed' };
|
| 886 |
+
// player_aaaa JSON 추출 (tvchak과 같은 구조)
|
| 887 |
+
const idx = html.indexOf('player_aaaa');
|
| 888 |
+
if (idx < 0) return { error: 'player_aaaa not found' };
|
| 889 |
+
const eqIdx = html.indexOf('=', idx);
|
| 890 |
+
const startIdx = html.indexOf('{', eqIdx);
|
| 891 |
+
if (startIdx < 0) return { error: 'player JSON start not found' };
|
| 892 |
+
// 균형 중괄호 파서
|
| 893 |
+
let depth = 0, endIdx = -1;
|
| 894 |
+
for (let i = startIdx; i < html.length; i++) {
|
| 895 |
+
const c = html[i];
|
| 896 |
+
if (c === '{') depth++;
|
| 897 |
+
else if (c === '}') { depth--; if (depth === 0) { endIdx = i; break; } }
|
| 898 |
+
}
|
| 899 |
+
if (endIdx < 0) return { error: 'player JSON end not found' };
|
| 900 |
+
let player;
|
| 901 |
+
try { player = JSON.parse(html.slice(startIdx, endIdx + 1)); }
|
| 902 |
+
catch (e) { return { error: 'player JSON parse: ' + e.message }; }
|
| 903 |
+
const token = player.url; // 예: "21707m1"
|
| 904 |
+
if (!token) return { error: 'no url token' };
|
| 905 |
+
// m3u8 패턴 조립. host는 actual_url에서 추출 시도 (변동 가능성 대응)
|
| 906 |
+
let host = 'pp5.ssku1.top';
|
| 907 |
+
if (player.actual_url) {
|
| 908 |
+
const am = player.actual_url.match(/id=(\w+)/);
|
| 909 |
+
if (am) host = `${am[1]}.ssku1.top`;
|
| 910 |
+
}
|
| 911 |
+
const m3u8 = `https://${host}/${token}/index.m3u8`;
|
| 912 |
+
return {
|
| 913 |
+
url: m3u8,
|
| 914 |
+
url_next: player.url_next ? `https://${host}/${player.url_next}/index.m3u8` : null,
|
| 915 |
+
link_next: player.link_next || null,
|
| 916 |
+
link_pre: player.link_pre || null,
|
| 917 |
+
vod_data: player.vod_data || null,
|
| 918 |
+
referer: 'https://play.sub3.top/',
|
| 919 |
+
source: 'linkkf',
|
| 920 |
+
_fallbackSource: 'linkkf',
|
| 921 |
+
};
|
| 922 |
+
}
|
| 923 |
+
|
| 924 |
+
// 제목 정규화 — 매칭 점수용. 공백/괄호/특수문자 제거, 소문자.
|
| 925 |
+
function normalizeTitle(s) {
|
| 926 |
+
return String(s || '')
|
| 927 |
+
.toLowerCase()
|
| 928 |
+
.replace(/\([^)]*\)/g, '') // 괄호 안 제거 "(2023)"
|
| 929 |
+
.replace(/[!?:·\-_,.\s]/g, '') // 구두점/공백
|
| 930 |
+
.replace(/시즌\d+|season\d+|s\d+|극장판|ova|tv판|tv시리즈|movie/g, '')
|
| 931 |
+
.trim();
|
| 932 |
+
}
|
| 933 |
+
// 매칭 점수 (0~100). 높을수록 좋음.
|
| 934 |
+
// +60: 정규화 제목 완전 일치
|
| 935 |
+
// +30: 한쪽이 다른 쪽을 포함 (예: "주술회전" ⊂ "주술회전2기")
|
| 936 |
+
// +0~30: 회차 수 근접도 (anilife knownCount와 ±20% 안이면 만점, 멀수록 감소)
|
| 937 |
+
// -50: 회차 0 (재생 불가)
|
| 938 |
+
// -10: 제목이 안 비슷한데 회차도 적음
|
| 939 |
+
function scoreLinkkfCandidate(targetTitle, targetCount, candTitle, candCount) {
|
| 940 |
+
const a = normalizeTitle(targetTitle);
|
| 941 |
+
const b = normalizeTitle(candTitle);
|
| 942 |
+
let score = 0;
|
| 943 |
+
if (!a || !b) return -10;
|
| 944 |
+
if (a === b) score += 60;
|
| 945 |
+
else if (a.includes(b) || b.includes(a)) score += 30;
|
| 946 |
+
else {
|
| 947 |
+
// 부분 토큰 매칭
|
| 948 |
+
const ta = a.length, tb = b.length;
|
| 949 |
+
const overlap = (() => {
|
| 950 |
+
let cnt = 0;
|
| 951 |
+
for (let i = 0; i < ta - 1; i++) {
|
| 952 |
+
const bigram = a.slice(i, i + 2);
|
| 953 |
+
if (b.includes(bigram)) cnt++;
|
| 954 |
+
}
|
| 955 |
+
return cnt / Math.max(1, ta - 1);
|
| 956 |
+
})();
|
| 957 |
+
score += Math.round(overlap * 25); // 0~25
|
| 958 |
+
}
|
| 959 |
+
if (candCount === 0) score -= 50;
|
| 960 |
+
else if (targetCount && targetCount > 0) {
|
| 961 |
+
const ratio = Math.min(candCount, targetCount) / Math.max(candCount, targetCount);
|
| 962 |
+
score += Math.round(ratio * 30); // 0~30
|
| 963 |
+
} else {
|
| 964 |
+
// targetCount 모르면 회차 많은 것 약간 우선
|
| 965 |
+
score += Math.min(15, candCount);
|
| 966 |
+
}
|
| 967 |
+
return score;
|
| 968 |
+
}
|
| 969 |
+
|
| 970 |
+
// anilife id → linkkf id 매핑 캐시 조회만 (영구). 신규 매칭은 점수 기반으로 aniEpisodesFallback에서 처리.
|
| 971 |
+
function getCachedLinkkfMap(anilifeId) {
|
| 972 |
+
if (!anilifeId) return undefined;
|
| 973 |
+
const cached = readCachePermanent(`linkkf_map_${anilifeId}.json`);
|
| 974 |
+
if (!cached) return undefined;
|
| 975 |
+
if (cached.linkkfId) return cached.linkkfId;
|
| 976 |
+
// 실패 캐시: 7일 안엔 재시도 안 함
|
| 977 |
+
if (cached.matchedAt && Date.now() - new Date(cached.matchedAt).getTime() < 7 * 24 * 3600 * 1000) {
|
| 978 |
+
return null; // 명시적 "최근 실패" — 재시도 안 함
|
| 979 |
+
}
|
| 980 |
+
return undefined; // 캐시 만료 → 새로 매칭
|
| 981 |
+
}
|
| 982 |
+
|
| 983 |
+
// fav.title을 받아 linkkf episodes 폴백.
|
| 984 |
+
// anilife 응답과 동일한 스키마로 정규화해서 클라이언트 코드 변경 없이 동���.
|
| 985 |
+
// opts.targetCount: anilife의 knownCount (있으면 회차 수 근접도로 점수 가산)
|
| 986 |
+
// opts.fallbackId: 클라이언트가 미리 알고 있는 linkkf id (검색 단계 스킵, 즉시 매핑)
|
| 987 |
+
async function aniEpisodesFallback(anilifeId, title, opts = {}) {
|
| 988 |
+
// 1. 클라이언트가 fallbackId를 보냈으면 그것 우선 (B 자동 백업 매핑)
|
| 989 |
+
if (opts.fallbackId) {
|
| 990 |
+
const ep = await linkkfEpisodes(opts.fallbackId);
|
| 991 |
+
if (!ep.error && ep.episodes && ep.episodes.length) {
|
| 992 |
+
return finalizeLinkkfFallback(anilifeId, title, opts.fallbackId, ep);
|
| 993 |
+
}
|
| 994 |
+
}
|
| 995 |
+
// 2. 매핑 캐시 — 점수 통과해서 저장된 매핑만 신뢰
|
| 996 |
+
const cachedId = getCachedLinkkfMap(anilifeId);
|
| 997 |
+
if (cachedId === null) return { error: 'recent linkkf match failure (cached)' };
|
| 998 |
+
if (cachedId !== undefined) {
|
| 999 |
+
const ep = await linkkfEpisodes(cachedId);
|
| 1000 |
+
if (!ep.error && ep.episodes && ep.episodes.length) {
|
| 1001 |
+
return finalizeLinkkfFallback(anilifeId, title, cachedId, ep);
|
| 1002 |
+
}
|
| 1003 |
+
}
|
| 1004 |
+
// 3. 신규 검색 — 점수 기반 best 매칭
|
| 1005 |
+
const result = await linkkfSearch(title);
|
| 1006 |
+
const candidates = (result.items || []).slice(0, 8);
|
| 1007 |
+
if (!candidates.length) return { error: 'no linkkf candidates' };
|
| 1008 |
+
// 각 후보의 회차 수 빠르게 확인 (병렬)
|
| 1009 |
+
const scored = await Promise.all(candidates.map(async cand => {
|
| 1010 |
+
const e = await linkkfEpisodes(cand.id);
|
| 1011 |
+
const count = (!e.error && e.episodes) ? e.episodes.length : 0;
|
| 1012 |
+
const score = scoreLinkkfCandidate(title, opts.targetCount || 0, cand.title, count);
|
| 1013 |
+
return { cand, ep: e, score, count };
|
| 1014 |
+
}));
|
| 1015 |
+
scored.sort((a, b) => b.score - a.score);
|
| 1016 |
+
console.log(`[linkkf-map] candidates for "${title}" (targetCount=${opts.targetCount || '?'}):`);
|
| 1017 |
+
for (const s of scored.slice(0, 5)) console.log(` score=${s.score} id=${s.cand.id} "${s.cand.title}" (${s.count}ep)`);
|
| 1018 |
+
const best = scored.find(s => s.count > 0 && s.score > 0);
|
| 1019 |
+
if (!best) return { error: 'no playable linkkf match' };
|
| 1020 |
+
writeCache(`linkkf_map_${anilifeId}.json`, { linkkfId: best.cand.id, title, matchedAt: new Date().toISOString(), score: best.score });
|
| 1021 |
+
return finalizeLinkkfFallback(anilifeId, title, best.cand.id, best.ep);
|
| 1022 |
+
}
|
| 1023 |
+
|
| 1024 |
+
// 공통: linkkf 회차를 anilife 스키마로 변환
|
| 1025 |
+
function finalizeLinkkfFallback(anilifeId, title, linkkfId, ep) {
|
| 1026 |
+
// anilife 스키마에 맞춤: episodes에 uniqueId 자리에 "linkkf:{id}:{sid}:{linkkfNid}" 같은 키 사용해서
|
| 1027 |
+
// aniPlay 호출 시 분기 가능하게.
|
| 1028 |
+
const eps = ep.episodes.map(e => ({
|
| 1029 |
+
sid: 0, // anilife 컨벤션
|
| 1030 |
+
nid: e.nid,
|
| 1031 |
+
uniqueId: `linkkf:${linkkfId}:${e.sid}:${e.linkkfNid}`,
|
| 1032 |
+
label: e.label,
|
| 1033 |
+
subject: '',
|
| 1034 |
+
thumbnail: null,
|
| 1035 |
+
duration: '',
|
| 1036 |
+
episodeNum: String(e.nid),
|
| 1037 |
+
}));
|
| 1038 |
+
return {
|
| 1039 |
+
id: anilifeId, // 클라이언트가 알고 있는 ID 유지
|
| 1040 |
+
title: ep.title || title,
|
| 1041 |
+
titles: null,
|
| 1042 |
+
poster: ep.poster || null,
|
| 1043 |
+
posterAlt: null,
|
| 1044 |
+
description: '',
|
| 1045 |
+
genre: [],
|
| 1046 |
+
format: '',
|
| 1047 |
+
rating: 0,
|
| 1048 |
+
ageRating: '',
|
| 1049 |
+
trailer: null,
|
| 1050 |
+
count: eps.length,
|
| 1051 |
+
episodes: eps,
|
| 1052 |
+
source: 'anilife', // 클라이언트엔 anilife로 보임 (폴백 사실 숨김)
|
| 1053 |
+
_fallbackSource: 'linkkf', // 클라이언트가 배지 표시용으로 사용
|
| 1054 |
+
_fallbackLinkkfId: linkkfId, // 클라이언트가 fav.fallbackLinkkfId로 저장해 다음 호출에 직접 전달
|
| 1055 |
+
checked_at: new Date().toISOString(),
|
| 1056 |
+
};
|
| 1057 |
+
}
|
| 1058 |
+
|
| 1059 |
+
// uniqueId가 "linkkf:..."로 시작하면 linkkf 재생.
|
| 1060 |
+
async function aniPlayMaybeFallback(uniqueId) {
|
| 1061 |
+
if (typeof uniqueId === 'string' && uniqueId.startsWith('linkkf:')) {
|
| 1062 |
+
const parts = uniqueId.split(':');
|
| 1063 |
+
// linkkf:{linkkfId}:{sid}:{linkkfNid}
|
| 1064 |
+
const linkkfId = parseInt(parts[1], 10);
|
| 1065 |
+
const sid = parseInt(parts[2], 10);
|
| 1066 |
+
const linkkfNid = parseInt(parts[3], 10);
|
| 1067 |
+
return await linkkfPlay(linkkfId, sid, linkkfNid);
|
| 1068 |
+
}
|
| 1069 |
+
return null; // 일반 anilife 경로로
|
| 1070 |
+
}
|
| 1071 |
+
|
| 1072 |
// ───── 도메인 탐지 ─────
|
| 1073 |
async function findLiveDomain() {
|
| 1074 |
// 살아있는 도메인 캐시는 1시간 유지. domain이 null인 캐시는 신뢰 X (재시도).
|
|
|
|
| 1806 |
|
| 1807 |
const cachedDomain = readCache('domain.json', 1e9);
|
| 1808 |
const isAniLikeHost = /anilife|gcdn\.app/.test(target);
|
| 1809 |
+
const isLinkkfHost = /ssku\d*\.top|play\.sub\d*\.top|linkkf\.tv/.test(target);
|
| 1810 |
const referer = u.query.r
|
| 1811 |
+
|| (isAniLikeHost ? 'https://anilife.app/'
|
| 1812 |
+
: isLinkkfHost ? 'https://play.sub3.top/'
|
| 1813 |
+
: `https://${(cachedDomain && cachedDomain.domain) || 'tvchak.org'}/`);
|
| 1814 |
|
| 1815 |
const t = new URL(target);
|
| 1816 |
const reqHeaders = {
|
|
|
|
| 1830 |
rejectUnauthorized: false,
|
| 1831 |
};
|
| 1832 |
// anilife/gcdn 은 manifest 발급 IP에서만 유효 → SOCKS5(NAS residential) 경유 필수.
|
| 1833 |
+
// linkkf의 m3u8/세그먼트도 한국 IP에서만 받을 가능성 → SOCKS5 경유.
|
| 1834 |
// BunnyCDN ��은 datacenter OK이므로 직접 호출.
|
| 1835 |
+
if ((isAniLikeHost || isLinkkfHost) && _socksAgent) reqOpts.agent = _socksAgent;
|
| 1836 |
|
| 1837 |
const upstream = https.request(reqOpts, (up) => {
|
| 1838 |
const ct = up.headers['content-type'] || '';
|
|
|
|
| 1955 |
}
|
| 1956 |
else if (p === '/api/domain') out = await findLiveDomain();
|
| 1957 |
else if (p === '/api/episodes') {
|
| 1958 |
+
if (q.source === 'anilife') {
|
| 1959 |
+
out = await aniEpisodes(q.id, { nocache: !!q.nocache });
|
| 1960 |
+
// 폴백 트리거: error 있거나 episodes 비어있을 때. title 필요 (클라이언트가 q.title로 전달)
|
| 1961 |
+
const needFallback = !!(out && (out.error || !out.episodes || out.episodes.length === 0));
|
| 1962 |
+
if (needFallback && q.title) {
|
| 1963 |
+
const reason = out?.error ? out.error.slice(0, 40) : 'empty episodes';
|
| 1964 |
+
console.log(`[linkkf-fb] anilife ${q.id} "${q.title}" failed (${reason}) — trying linkkf`);
|
| 1965 |
+
const fb = await aniEpisodesFallback(q.id, q.title, {
|
| 1966 |
+
targetCount: q.count ? parseInt(q.count, 10) : 0,
|
| 1967 |
+
fallbackId: q.fallbackId ? parseInt(q.fallbackId, 10) : 0,
|
| 1968 |
+
});
|
| 1969 |
+
if (!fb.error && fb.episodes && fb.episodes.length) {
|
| 1970 |
+
console.log(`[linkkf-fb] success: ${fb.episodes.length} episodes (linkkf ${fb._fallbackLinkkfId || '?'})`);
|
| 1971 |
+
out = fb;
|
| 1972 |
+
}
|
| 1973 |
+
}
|
| 1974 |
+
}
|
| 1975 |
else out = await fetchEpisodes(q.id, { nocache: !!q.nocache });
|
| 1976 |
}
|
| 1977 |
else if (p === '/api/latest-labels') {
|
|
|
|
| 2024 |
out = { items, pending: pending.map(p => p.id) };
|
| 2025 |
}
|
| 2026 |
else if (p === '/api/play') {
|
| 2027 |
+
if (q.source === 'anilife') {
|
| 2028 |
+
const uniqueId = q.uniqueId || q.uid;
|
| 2029 |
+
// uniqueId가 "linkkf:..."면 폴백 재생 (episodes 폴백 후 클릭한 케이스)
|
| 2030 |
+
const fbPlay = await aniPlayMaybeFallback(uniqueId);
|
| 2031 |
+
if (fbPlay) out = fbPlay;
|
| 2032 |
+
else out = await aniPlay(uniqueId);
|
| 2033 |
+
}
|
| 2034 |
else out = await fetchPlay(q.id, q.sid, q.nid);
|
| 2035 |
}
|
| 2036 |
else if (p === '/api/search') {
|