# -*- coding: utf-8 -*-
"""
EVOJAV（evojav.pro）· TVBox Python 采集源 · 中文版

站点形态：WordPress 主题 supjav2 + qTranslate-XT 多语言，日语为默认站点，
          中文版全部走 /zh/ 前缀（标题、分类名、女优名、类别均为简体中文）。

    首页      /zh/                                 每页 24 条卡片
    分类      /zh/{栏目}/page/{页码}/                栏目见 CATS
    搜索      /zh/?s={关键词}  → 第 N 页 /zh/page/{N}/?s={关键词}
    详情      /zh/video/{slug}/
    播放      /zh 详情页内 5 个播放服务器（EVS/VAS/ST/VOE/LUC）各自带 data-link 令牌
              取流：lk1.supremejav.com/evojav.php?c={令牌倒序}
              → 页面内 eval(function(p,a,c,k,e,d){…}) 打包脚本，Python 侧解包
              → var links={hls4,hls3,hls2}，取 hls2 的 master.m3u8（实测 HTTP 200）

说明：EVS 一路可解出 m3u8 直链；VAS/ST/VOE/LUC 是第三方播放器壳页，本脚本按同一
      链路逐个尝试，全部失败时回落到详情页地址交给 TVBox 嗅探，不做任何绕过限制的处理。

导入：TVBox「配置中心 → 数据源 → 添加」选 Python，粘贴本文件，extend 留空即可；
      可选 {"ua":"...","interval":0.3,"attempts":2,"timeout":8,"budget":12}

命令行：
    python evojav.py check | categories | category 有码 1 | search 东美香 1 | detail <slug> | play <slug>
"""

import base64
import json
import os
import re
import socket
import sys
import threading
import time
import urllib.parse

try:
    import requests
except Exception:
    requests = None

try:
    from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
except Exception:
    BaseHTTPRequestHandler = ThreadingHTTPServer = None

try:
    from base.spider import Spider as _BaseSpider
except Exception:
    _BaseSpider = object


BASE = "https://evojav.pro"
ZH = BASE + "/zh"
LK = "https://lk1.supremejav.com"
DOH_ENDPOINTS = ("https://doh.pub/dns-query", "https://1.12.12.12/resolve")

UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")

PER_PAGE = 24
TIMEOUT = 8.0
ATTEMPTS = 2
BUDGET = 12.0
INTERVAL = 0.3
HOME_BUDGET = 6.0
CACHE_TTL = 60.0

# (slug, 中文栏目名, 首页路径前缀)
CATS = [
    ("latest", "最新上市", "/zh/"),
    ("popular", "热门推荐", "/zh/popular/"),
    ("censored-jav", "有码", "/zh/censored-jav/"),
    ("uncensored-jav", "无码", "/zh/uncensored-jav/"),
    ("amateur", "素人", "/zh/amateur/"),
    ("chinese-subtitles", "中文字幕", "/zh/chinese-subtitles/"),
    ("reducing-mosaic", "无码破解", "/zh/reducing-mosaic/"),
    ("english-subtitles", "英文字幕", "/zh/english-subtitles/"),
]
CAT_PATH = {slug: path for slug, _name, path in CATS}

def m3u8_expired(url, margin=120):
    """CDN 签名是否临近过期（hls2 链接带 s=起始秒、e=有效秒）。"""
    if not url:
        return True
    try:
        qs = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)
        s0 = float((qs.get("s") or ["0"])[0])
        e0 = float((qs.get("e") or ["0"])[0])
        if s0 and e0:
            return time.time() > s0 + e0 - margin
    except Exception:
        pass
    return False


_CFG = {"ua": UA, "interval": INTERVAL, "attempts": ATTEMPTS,
        "timeout": TIMEOUT, "budget": BUDGET, "local_img": True,
        "net": "auto", "proxy": "", "relay": True, "pin": "lazy",
        "mirror": "", "mirror_style": "path", "mirror_token": "",
        "mirror_direct": False, "mirror_page": True, "relay_all": False}

_session = None
_sess_lock = threading.Lock()
_cache = {}
_cache_lock = threading.Lock()
_last_call = [0.0]
_home_cache = {"videos": [], "classes": [], "ts": 0.0}
_home_lock = threading.Lock()


def _warm_home(spider):
    """后台预热一次首页：TVBox 首次调用若超时，用户下拉刷新就能直接命中缓存。"""
    if not _CFG.get("warm", True):
        return
    def run():
        try:
            time.sleep(0.3)
            spider.homeContent(False)
        except Exception:
            pass
    try:
        threading.Thread(target=run, daemon=True).start()
    except Exception:
        pass
_pins = {}
_pin_lock = threading.Lock()
_pin_orig = [None]
_pin_applied = [False]

_net = {"mode": "", "ts": 0.0}
_net_lock = threading.Lock()
_sessions = {}


def _env_proxy():
    """读 TVBox / 系统注入的代理环境变量（只认 http/https 代理，socks 交给系统）。"""
    for key in ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy",
                "ALL_PROXY", "all_proxy"):
        val = (os.environ.get(key) or "").strip()
        if not val:
            continue
        if "://" not in val:
            val = "http://" + val
        if val.startswith(("http://", "https://")):
            return val
    return ""


_proxy_cache = {"url": "", "ts": 0.0, "src": ""}
_proxy_lock = threading.Lock()
_dirty_hosts = set()
_LOCAL_PORTS = (7890, 7891, 7897, 1080, 10808, 10809)


def _probe_via_proxy(pu, timeout=2.5):
    """用给定代理探一次外网，判断它到底能不能用。"""
    if requests is None:
        return False
    urls = [_CFG.get("base") or "", "https://evojav.pro/zh/"]
    for u in [x for x in urls if x]:
        try:
            r = requests.get(u, timeout=timeout, proxies={"http": pu, "https": pu},
                             headers={"User-Agent": _CFG["ua"]})
            if 200 <= r.status_code < 400:
                return True
        except Exception:
            continue
    return False


def _local_proxy():
    """扫本机常见代理端口（Clash / v2ray / SS / V2rayN …）。

    TVBox 跑在 Android 上，系统的代理设置不会写进 Python 进程的环境变量，
    所以不能只认 HTTP_PROXY，得自己把本机监听端口找出来。
    """
    with _proxy_lock:
        if _proxy_cache["url"] and time.time() - _proxy_cache["ts"] < 300:
            return _proxy_cache["url"]
    if requests is None:
        return ""
    found = []
    try:
        from concurrent.futures import ThreadPoolExecutor
        ports = list(_LOCAL_PORTS)
        with ThreadPoolExecutor(max_workers=min(8, len(ports))) as ex:
            hits = list(ex.map(
                lambda p: ("http://127.0.0.1:%d" % p,
                           _probe_via_proxy("http://127.0.0.1:%d" % p, 0.8)), ports))
        found = [u for u, ok in hits if ok]
    except Exception:
        found = []
    url = found[0] if found else ""
    with _proxy_lock:
        _proxy_cache["url"], _proxy_cache["ts"] = url, time.time()
    return url


def _proxy_url():
    """代理来源优先级：显式参数 > 环境变量 > 本机端口探测。"""
    explicit = (_CFG.get("proxy") or "").strip()
    if explicit:
        _proxy_cache["src"] = "param"
        return explicit
    env = _env_proxy()
    if env:
        _proxy_cache["src"] = "env"
        return env
    local = _local_proxy()
    _proxy_cache["src"] = "local" if local else ""
    return local




def _net_demote():
    """代理连不上站点时立刻降级直连，避免整页请求都卡在代理上。"""
    if (_CFG.get("net") or "auto") != "auto":
        return
    with _net_lock:
        if _net.get("mode") == "proxy":
            _net["mode"], _net["ts"] = "direct", time.time()


def _net_promote():
    """直连被墙时升级到代理（auto 模式，60s 内保持代理）。"""
    if (_CFG.get("net") or "auto") != "auto":
        return False
    if not _proxy_url():
        return False
    with _net_lock:
        if _net.get("mode") != "proxy":
            _net["mode"], _net["ts"] = "proxy", time.time()
    return True


def _net_mode():
    """auto：默认走直连，直连被墙才自动切代理；选择结果缓存 60s。

    默认直连而不是先试代理，是因为很多代理软件对未匹配域名按规则直连，
    先探代理会白花 2 秒还可能把请求绕进一条走不通的链路。
    """
    mode = (_CFG.get("net") or "auto").strip().lower()
    if mode in ("proxy", "direct"):
        return mode
    with _net_lock:
        if _net.get("mode") and time.time() - _net["ts"] < 60:
            return _net["mode"]
        _net["mode"], _net["ts"] = "direct", time.time()
        return "direct"


def _session_for(use_proxy):
    key = "proxy" if use_proxy else "direct"
    with _sess_lock:
        sess = _sessions.get(key)
        if sess is None:
            sess = requests.Session()
            sess.trust_env = False
            sess.headers.update({
                "User-Agent": _CFG["ua"],
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                "Accept-Language": "zh-CN,zh;q=0.9",
                "Connection": "keep-alive",
                "Referer": ZH + "/",
            })
            if use_proxy:
                pu = _proxy_url()
                sess.proxies = {"http": pu, "https": pu}
            _sessions[key] = sess
        return sess




# ---------------------------------------------------------------- 网络

def _doh_all(host):
    if requests is None:
        return []
    sd = requests.Session()
    sd.trust_env = False
    sd.headers.update({"accept": "application/dns-json"})
    for url in DOH_ENDPOINTS:
        try:
            r = sd.get(url, params={"name": host, "type": "A"}, timeout=6)
            ips = [a["data"] for a in r.json().get("Answer", []) if a.get("type") == 1]
            if ips:
                return ips
        except Exception:
            continue
    return []


def _apply_pin():
    if _pin_applied[0]:
        return
    _pin_orig[0] = socket.getaddrinfo
    orig = _pin_orig[0]

    def gai(host, port, *args, **kwargs):
        if _net.get("mode") != "proxy":
            ip = _pins.get(host)
            if ip:
                return orig(ip, port, *args, **kwargs)
        return orig(host, port, *args, **kwargs)

    socket.getaddrinfo = gai
    _pin_applied[0] = True


def pin_host(host, force=False):
    """给域名钉 DoH IP。

    代理模式完全跳过（交给代理解析）；pin=lazy（默认）时只有该域直连失败过才钉，
    否则钉到“真实 IP”反而会破坏 TUN/透明代理的分流。
    """
    if _net_mode() == "proxy":
        return ""
    if (_CFG.get("pin") or "lazy") == "lazy" and host not in _dirty_hosts and not force:
        return ""
    with _pin_lock:
        if host in _pins:
            return _pins[host]
    ips = _doh_all(host)
    ip = ips[0] if ips else ""
    if ip:
        with _pin_lock:
            _pins[host] = ip
        _apply_pin()
    return ip


def configure(extend):
    if not extend:
        return
    try:
        cfg = json.loads(extend) if isinstance(extend, str) else dict(extend or {})
    except Exception:
        return
    if not isinstance(cfg, dict):
        return
    if "local_img" in cfg:
        _CFG["local_img"] = bool(cfg.get("local_img"))
    if "relay" in cfg:
        _CFG["relay"] = bool(cfg.get("relay"))
    if "relay_all" in cfg:
        _CFG["relay_all"] = bool(cfg.get("relay_all"))
    if "mirror" in cfg:
        mv = cfg.get("mirror")
        _CFG["mirror"] = mv.strip() if isinstance(mv, str) else ""
    mstyle = (cfg.get("mirror_style") or "").strip().lower()
    if mstyle in ("path", "pathq", "query", "prefix"):
        _CFG["mirror_style"] = mstyle
    if "mirror_token" in cfg:
        _CFG["mirror_token"] = str(cfg.get("mirror_token") or "").strip()
    if "mirror_direct" in cfg:
        _CFG["mirror_direct"] = bool(cfg.get("mirror_direct"))
    if "mirror_page" in cfg:
        _CFG["mirror_page"] = bool(cfg.get("mirror_page"))
    pin_mode = (cfg.get("pin") or "").strip().lower()
    if pin_mode in ("lazy", "always"):
        _CFG["pin"] = pin_mode
    net = (cfg.get("net") or "").strip().lower()
    if net in ("auto", "proxy", "direct"):
        _CFG["net"] = net
    if "proxy" in cfg:
        px = cfg.get("proxy")
        px = px.strip() if isinstance(px, str) else ""
        if px and "://" not in px:
            px = "http://" + px
        _CFG["proxy"] = px          # 传空字符串即可清掉之前设过的代理
    ua = cfg.get("ua")
    if isinstance(ua, str) and ua.strip():
        _CFG["ua"] = ua.strip()
    for key, low, high in (("interval", 0.0, 5.0), ("timeout", 1.0, 20.0),
                           ("budget", 2.0, 25.0)):
        try:
            _CFG[key] = max(low, min(high, float(cfg.get(key))))
        except Exception:
            pass
    try:
        _CFG["attempts"] = max(1, min(3, int(cfg.get("attempts", ATTEMPTS))))
    except Exception:
        pass
    global _session
    with _sess_lock:
        _session = None
        _sessions.clear()
    with _net_lock:
        _net["mode"], _net["ts"] = "", 0.0
    with _proxy_lock:
        _proxy_cache["url"], _proxy_cache["ts"] = "", 0.0


def _get_session():
    """按当前网络模式返回会话：走代理时用代理会话，否则用直连 + DoH 钉址会话。"""
    return _session_for(_net_mode() == "proxy")


def _throttle():
    gap = _CFG["interval"] - (time.time() - _last_call[0])
    if gap > 0:
        time.sleep(gap)
    _last_call[0] = time.time()


def _cache_get(key):
    with _cache_lock:
        item = _cache.get(key)
        if item and time.time() - item[0] < CACHE_TTL:
            return item[1]
        if item:
            _cache.pop(key, None)
    return None


def _cache_put(key, value):
    with _cache_lock:
        _cache[key] = (time.time(), value)
        if len(_cache) > 200:
            for k in sorted(_cache, key=lambda k: _cache[k][0])[:80]:
                _cache.pop(k, None)


def fetch(url, referer=None, use_cache=True, budget=None):
    url = url if url.startswith("http") else BASE + url
    if use_cache:
        hit = _cache_get(url)
        if hit is not None:
            return hit
    if requests is None:
        return ""
    host = urllib.parse.urlparse(url).hostname or ""
    if host:
        pin_host(host)
    deadline = time.time() + (budget or _CFG["budget"])
    text = ""
    headers = {"Referer": referer} if referer else None
    for attempt in range(_CFG["attempts"]):
        remain = deadline - time.time()
        if remain <= 0.4:
            break
        _throttle()
        try:
            use_proxy = (_net_mode() == "proxy")
            if attempt and (_CFG.get("net") or "auto") == "auto":
                use_proxy = not use_proxy          # 首轮失败就换另一条通道
            r = _session_for(use_proxy).get(url, timeout=min(_CFG["timeout"], remain),
                                   headers=headers, allow_redirects=True)
            if r.status_code == 200 and len(r.text) > 300:
                text = r.text
                break
            if r.status_code in (403, 429, 503):
                time.sleep(0.6 * (attempt + 1))
            elif r.status_code >= 500:
                time.sleep(0.4 * (attempt + 1))
            else:
                break
        except Exception:
            if use_proxy:
                _net_demote()
            else:
                _net_promote()
            time.sleep(0.4 * (attempt + 1))
    if text:
        _cache_put(url, text)
    if not text and host:
        # 直连这次被 DNS 污染挡住了：记下这个域，改用 DoH 钉址再取一次
        _dirty_hosts.add(host)
        if pin_host(host, force=True):
            try:
                r = _session_for(False).get(url, timeout=min(_CFG["timeout"], 8.0),
                                            headers=headers or None, allow_redirects=True)
                if r.status_code < 400 and len(r.text) > 300:
                    text = r.text
                    _cache_put(url, text)
            except Exception:
                pass
    return text


# ---------------------------------------------------------------- HTML 工具

_TAG_RE = re.compile(r"<[^>]+>")


def clean(text):
    if not text:
        return ""
    try:
        import html as _h
        text = _h.unescape(text)
    except Exception:
        pass
    text = _TAG_RE.sub(" ", str(text))
    return re.sub(r"\s+", " ", text.replace("\u200b", "").replace("\xa0", " ")).strip()


def _pic(url):
    url = (url or "").strip()
    if url.startswith("//"):
        url = "https:" + url
    if url.startswith("data:"):
        return ""
    return url


_CARD_RE = re.compile(
    r'<div class="post">\s*<a[^>]+href="(https://evojav\.pro/zh/video/[^"]+)"[^>]*class="img"[^>]*title="([^"]*)"(.*?)</div>\s*</div>',
    re.S)
_SLUG_RE = re.compile(r"/zh/video/([^/]+)/?")


def parse_cards(html_text):
    items, seen = [], set()
    for m in _CARD_RE.finditer(html_text or ""):
        url, title, body = m.group(1), m.group(2), m.group(3)
        ms = _SLUG_RE.search(url)
        if not ms:
            continue
        slug = ms.group(1)
        if slug in seen:
            continue
        pic = ""
        mp = re.search(r'data-original="([^"]+)"', body) or re.search(r'<img[^>]+src="(https?://[^"]+)"', body)
        if mp:
            pic = _pic(mp.group(1))
        # 卡片信息：时长、番号等（主题在 .con 内给 <span class="duration"> / 番号标签）
        dur, serial = "", ""
        md = re.search(r'class="duration"[^>]*>(.*?)</span>', body, re.S)
        if md:
            dur = clean(md.group(1))
        mcode = re.search(r'class="code"[^>]*>(.*?)</span>', body, re.S)
        if mcode:
            serial = clean(mcode.group(1))
        seen.add(slug)
        items.append({
            "vod_id": slug,
            "vod_name": clean(title) or slug,
            "vod_pic": img_url(pic),
            "vod_remarks": dur or serial,
            "vod_year": "",
        })
    if not items:            # 兜底：主题偶尔换排版，按 a.img 标题抓
        for m in re.finditer(r'<a[^>]+href="(https://evojav\.pro/zh/video/[^"]+)"[^>]*class="img"[^>]*title="([^"]*)"', html_text or ""):
            ms = _SLUG_RE.search(m.group(1))
            if not ms or ms.group(1) in seen:
                continue
            seen.add(ms.group(1))
            items.append({"vod_id": ms.group(1), "vod_name": clean(m.group(2)) or ms.group(1),
                          "vod_pic": "", "vod_remarks": "", "vod_year": ""})
    return items


def _page_max(html_text, slug):
    nums = [int(x) for x in re.findall(r'href=["\']https://evojav\.pro/zh/(?:%s/)?page/(\d+)/' % re.escape(slug), html_text or "")]
    nums += [int(x) for x in re.findall(r"/zh/page/(\d+)/\?s=", html_text or "")]
    nums = [n for n in nums if 0 < n <= 100000]
    if nums:
        return max(nums)
    m = re.search(r"<h1[^>]*>.*?\((\d+)\)", html_text or "", re.S)
    if m:
        try:
            return max(1, (int(m.group(1)) + PER_PAGE - 1) // PER_PAGE)
        except Exception:
            pass
    return 1


# ---------------------------------------------------------------- 封面图代理
# img.supjav.com 在国内网络常被 DNS 污染（TVBox 自带 HTTP 客户端不认 DoH），
# 这里起一个只监听 127.0.0.1 的图片代理：进程内先用 DoH 把域名钉到真实 IP，
# 再带 Referer 取图并缓存在内存里。

_img_cache = {}
_img_lock = threading.Lock()
_img_server = {"srv": None, "port": 0}


def _image_bytes(url):
    if not url.startswith("http"):
        return b"", ""
    with _img_lock:
        hit = _img_cache.get(url)
    if hit:
        return hit
    host = urllib.parse.urlparse(url).hostname or ""
    if host:
        pin_host(host, force=True)
    try:
        r = _get_session().get(url, timeout=12, headers={"Referer": ZH + "/"})
        if r.status_code == 200 and r.content:
            data = (r.content, r.headers.get("Content-Type") or "image/jpeg")
            with _img_lock:
                _img_cache[url] = data
                if len(_img_cache) > 240:
                    for k in list(_img_cache)[:80]:
                        _img_cache.pop(k, None)
            return data
    except Exception:
        pass
    return b"", ""


class _ImageHandler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.0"

    def do_GET(self):
        qs = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
        u = (qs.get("u") or [""])[0]
        data, ctype = _image_bytes(u)
        if not data:
            self.send_error(404)
            return
        try:
            self.send_response(200)
            self.send_header("Content-Type", ctype or "image/jpeg")
            self.send_header("Content-Length", str(len(data)))
            self.send_header("Cache-Control", "max-age=86400")
            self.end_headers()
            self.wfile.write(data)
        except Exception:
            pass

    def log_message(self, *args):
        pass


def _start_img_server():
    if _img_server["srv"] is not None:
        return _img_server["port"]
    srv = ThreadingHTTPServer(("127.0.0.1", 0), _ImageHandler)
    srv.daemon_threads = True
    threading.Thread(target=srv.serve_forever, kwargs={"poll_interval": 0.3},
                     daemon=True).start()
    _img_server["srv"] = srv
    _img_server["port"] = srv.server_address[1]
    return _img_server["port"]


def img_url(url):
    url = (url or "").strip()
    if not url or not _CFG.get("local_img", True):
        return url
    if url.startswith("http://127.0.0.1"):
        return url
    try:
        port = _start_img_server()
        if not port:
            return url
        return "http://127.0.0.1:%d/?u=%s" % (port, urllib.parse.quote(url, safe=""))
    except Exception:
        return url


def _stop_img_server():
    srv = _img_server.get("srv")
    if srv is not None:
        try:
            srv.shutdown()
            srv.server_close()
        except Exception:
            pass
    _img_server["srv"] = None
    _img_server["port"] = 0
    with _img_lock:
        _img_cache.clear()


# ---------------------------------------------------------------- 流转发（需要代理的线路）
# 有些 CDN 域名直连不通、只有走代理才通，而播放器未必走代理。
# 这里起一个只监听 127.0.0.1 的转发口：播放器请求本机，本机按当前网络模式（代理/直连）出网，
# m3u8 的子清单与分片都会重写成同样的本机地址，Range 请求也原样透传。

_relay = {"srv": None, "port": 0}


def _b64e(text):
    return base64.urlsafe_b64encode((text or "").encode("utf-8")).decode("ascii").rstrip("=")


def _b64d(text):
    text = (text or "").strip()
    return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)).decode("utf-8", "replace")


def _need_proxy_relay(url):
    """直连打不通、但当前走代理时，才把地址交给本机转发。"""
    if not _CFG.get("relay", True):
        return False
    if _CFG.get("relay_all"):
        return _net_mode() == "proxy" or bool(_proxy_url())
    if _net_mode() != "proxy":
        return False
    host = urllib.parse.urlparse(url).hostname or ""
    if not host:
        return False
    key = "relay:" + host
    hit = _cache_get(key)
    if hit is not None:
        return hit == "1"
    ok = False
    try:
        r = _session_for(False).get("https://" + host + "/", timeout=2.2, stream=True)
        ok = r.status_code < 500
        try:
            r.close()
        except Exception:
            pass
    except Exception:
        ok = False
    _cache_put(key, "1" if not ok else "0")
    return not ok


def _relay_wrap(url, referer=""):
    if not url or not url.startswith("http") or url.startswith("http://127.0.0.1"):
        return url
    try:
        port = _start_relay_server()
        if not port:
            return url
        q = "u=" + urllib.parse.quote(_b64e(url), safe="")
        if referer:
            q += "&r=" + urllib.parse.quote(_b64e(referer), safe="")
        return "http://127.0.0.1:%d/p?%s" % (port, q)
    except Exception:
        return url


def _mirror_url(url, style=None):
    """按配置的 OCI 镜像代理包装地址；未配置原样返回。

    支持四种拼法：
      path   （默认）{base}/{原始完整地址}，如 https://m.example.com/https://cdn/x/master.m3u8
      pathq  {base}/{urlencode(原始地址)}，目标地址里的 ? & = 全部编码进 path ——
             GitHub 代理类实现常把 query 当成自己的参数而不转给目标，这种写法更稳
      query  {base}/?url={quote(原始地址)}
      prefix base 已带前缀，如 https://m.example.com/proxy?u=，直接接 quote(原始地址)
    """
    base = (_CFG.get("mirror") or "").strip().rstrip("/")
    if not base or not url or not url.startswith("http") or url.startswith("http://127.0.0.1"):
        return url
    style = (style or _CFG.get("mirror_style") or "path").strip().lower()
    token = (_CFG.get("mirror_token") or "").strip()
    if style == "pathq":
        out = base + "/" + urllib.parse.quote(url, safe=":/")
        if token:
            out += "?token=" + urllib.parse.quote(token, safe="")
        return out
    if style == "query":
        q = "url=" + urllib.parse.quote(url, safe="")
        if token:
            q += "&token=" + urllib.parse.quote(token, safe="")
        return base + "/?" + q
    if style == "prefix":
        out = base + urllib.parse.quote(url, safe="")
        if token:
            out += ("&" if "?" in out else "?") + "token=" + urllib.parse.quote(token, safe="")
        return out
    out = base + "/" + url
    if token:
        out += ("&" if "?" in out else "?") + "token=" + urllib.parse.quote(token, safe="")
    return out


def _unmirror(url):
    """把镜像地址还原成原始目标地址。

    镜像取回 m3u8 后，相对路径必须相对**原始** CDN 地址解析；若不还原，
    子清单会被拼成「镜像/原始地址/子清单」再被转发，形成双重包装后 502。
    """
    base = (_CFG.get("mirror") or "").strip().rstrip("/")
    if not base or not url.startswith(base):
        return url
    style = (_CFG.get("mirror_style") or "path").strip().lower()
    rest = url[len(base):]
    if style == "path":
        if rest.startswith("/http"):
            out = rest[1:]
            if "&token=" in out:
                out = out.split("&token=")[0]
            return out
    elif style == "pathq":
        out = urllib.parse.unquote(rest[1:] if rest.startswith("/") else rest)
        if "?token=" in out:
            out = out.split("?token=")[0]
        if out.startswith("http"):
            return out
    elif style == "query":
        qs = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)
        v = (qs.get("url") or [""])[0]
        if v.startswith("http"):
            return v
    elif style == "prefix":
        v = urllib.parse.unquote(rest[1:] if rest.startswith("/") else rest)
        if "&token=" in v:
            v = v.split("&token=")[0]
        if v.startswith("http"):
            return v
    return url


def _playable(url, referer=""):
    """所有线路的统一出口：配了 OCI 镜像就整条线路经镜像出网。

    默认把地址交给本机转发（127.0.0.1），转发进程用镜像地址取流，并把 m3u8
    的子清单与分片重写成同样的本地地址 —— 这样不指望镜像自己处理相对路径；
    想直接把镜像地址交给播放器时设 mirror_direct=true。
    """
    if not url or not url.startswith("http") or url.startswith("http://127.0.0.1"):
        return url
    if (_CFG.get("mirror") or "").strip():
        try:
            if _CFG.get("mirror_direct"):
                return _mirror_url(url)
            return _relay_wrap(url, referer)
        except Exception:
            return url
    try:
        if _need_proxy_relay(url):
            return _relay_wrap(url, referer)
    except Exception:
        pass
    return url


def _playable_page(url):
    """parse=1 的线路页（第三方 embed 壳页）同样按镜像代理跳转。

    播放器/嗅探器直接打开这个地址，所以这里只改写地址；镜像只反代流、
    不反代页面时设 mirror_page=false 恢复原地址。
    """
    if not url or not url.startswith("http"):
        return url
    if (_CFG.get("mirror") or "").strip() and _CFG.get("mirror_page", True):
        try:
            return _mirror_url(url)
        except Exception:
            return url
    return url


def _relay_fetch(url, referer="", rng=""):
    headers = {"User-Agent": _CFG["ua"]}
    if referer:
        headers["Referer"] = referer
    if rng:
        headers["Range"] = rng
    mbase = (_CFG.get("mirror") or "").strip().rstrip("/")
    style = (_CFG.get("mirror_style") or "path").strip().lower()
    key = ""
    cands = []                                  # [(拼法, 地址)]
    if mbase and not url.startswith(mbase + "/"):
        host = urllib.parse.urlparse(url).hostname or ""
        root = ".".join(host.split(".")[-2:])   # CDN 常换随机子域，按主域记
        key = "mstyle:" + (root or host) + ":" + style
        pref = _cache_get(key) or ""
        if pref == "direct":                     # 这个域名镜像两种拼法都不通，别再试错
            cands = [("direct", url)]
        else:
            order = ["path", "pathq"] if style in ("path", "pathq") else [style]
            if pref == "pathq" and style in ("path", "pathq"):
                order = ["pathq", "path"]
            seen = []
            for st in order:
                u = _mirror_url(url, st)
                if u not in seen:
                    seen.append(u)
                    cands.append((st, u))
            cands.append(("direct", url))        # 镜像两种拼法都不通时回退直连
    else:
        cands.append(("mirror" if mbase else "direct", url))
    resp = None
    for idx, (st, target) in enumerate(cands):
        mhost = urllib.parse.urlparse(target).hostname or ""
        loop = mhost in ("127.0.0.1", "localhost", "::1")
        sess = _session_for(False if loop else _net_mode() == "proxy")
        try:
            r = sess.get(target, timeout=20, headers=headers, stream=True)
        except Exception:
            if idx + 1 >= len(cands):
                raise
            continue
        resp = r
        if 200 <= r.status_code < 400:
            if key:
                _cache_put(key, st)             # 记住这个主域可行的拼法（direct=镜像不通），后续不再试错
            return r
        if idx + 1 >= len(cands):
            return r
    return resp


def _rewrite_m3u8(text, base_url, referer):
    out = []
    for line in text.splitlines():
        s = line.strip()
        if not s:
            out.append(line)
            continue
        if s.startswith("#"):
            if 'URI="' in s:
                s = re.sub(r'URI="([^"]+)"',
                           lambda m: 'URI="%s"' % _relay_wrap(
                               urllib.parse.urljoin(base_url, m.group(1)), referer), s)
            out.append(s)
            continue
        out.append(_relay_wrap(urllib.parse.urljoin(base_url, s), referer))
    return "\n".join(out) + "\n"


class _RelayHandler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.0"

    def do_GET(self):
        qs = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
        try:
            u = _b64d((qs.get("u") or [""])[0])
            ref = _b64d((qs.get("r") or [""])[0])
        except Exception:
            self.send_error(400)
            return
        if not u.startswith("http"):
            self.send_error(400)
            return
        r = _relay_fetch(u, ref, self.headers.get("Range") or "")
        ctype = (r.headers.get("Content-Type") or "").lower()
        eff = _unmirror(getattr(r, "url", "") or u)   # 镜像/302 → 还原成原始目标
        look_pl = "mpegurl" in ctype or eff.split("?")[0].endswith(".m3u8") \
            or u.split("?")[0].endswith(".m3u8")
        raw = ""
        is_pl = False
        if look_pl and r.status_code < 300:
            raw = r.content.decode("utf-8", "replace")
            is_pl = "#EXTM3U" in raw[:2048]          # 403 错误页也常以 .m3u8 结尾，需验内容
        if is_pl:
            body = _rewrite_m3u8(raw, eff, ref).encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "application/vnd.apple.mpegurl")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return
        self.send_response(r.status_code or 502)   # 403/404 原样透传，别让播放器以为取到了流
        self.send_header("Content-Type", ctype or "application/octet-stream")
        if r.headers.get("Content-Range"):
            self.send_header("Content-Range", r.headers["Content-Range"])
        if r.headers.get("Content-Length"):
            self.send_header("Content-Length", r.headers["Content-Length"])
        self.end_headers()
        try:
            for chunk in r.iter_content(65536):
                if chunk:
                    self.wfile.write(chunk)
        except Exception:
            pass

    def log_message(self, *args):
        pass


def _start_relay_server():
    if _relay["srv"] is not None:
        return _relay["port"]
    srv = ThreadingHTTPServer(("127.0.0.1", 0), _RelayHandler)
    srv.daemon_threads = True
    threading.Thread(target=srv.serve_forever, kwargs={"poll_interval": 0.3},
                     daemon=True).start()
    _relay["srv"] = srv
    _relay["port"] = srv.server_address[1]
    return _relay["port"]


def _stop_relay_server():
    srv = _relay.get("srv")
    if srv is not None:
        try:
            srv.shutdown()
            srv.server_close()
        except Exception:
            pass
    _relay["srv"] = None
    _relay["port"] = 0





# ---------------------------------------------------------------- packer 解包

_PACKER_RE = re.compile(r"eval\(function\(p,a,c,k,e,d\)\{.*?\}\((.*)\)\)\s*</script>", re.S)
_PACKER_ARGS = re.compile(
    r"\s*'((?:[^'\\]|\\.)*)'\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*'((?:[^'\\]|\\.)*)'\.split\('\|'\)",
    re.S)


def unpack_packer(html_text):
    """还原 eval(function(p,a,c,k,e,d)) 打包的播放器脚本，返回明文 JS。"""
    m = _PACKER_RE.search(html_text or "")
    if not m:
        return ""
    pm = _PACKER_ARGS.match(m.group(1))
    if not pm:
        return ""

    def unesc(x):
        return (x.replace("\\'", "'").replace('\\"', '"')
                 .replace("\\\\", "\\").replace("\\n", "\n").replace("\\r", "\r"))

    payload = unesc(pm.group(1))
    base = int(pm.group(2)) or 36
    count = int(pm.group(3))
    words = unesc(pm.group(4)).split("|")
    alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"

    def code(n):
        if n == 0:
            return "0"
        out = ""
        while n:
            out = alphabet[n % base] + out
            n //= base
        return out

    for i in range(min(count, len(words)) - 1, -1, -1):
        if i < len(words) and words[i]:
            payload = re.sub(r"\b" + re.escape(code(i)) + r"\b",
                             lambda _m, r=words[i]: r, payload)
    return payload


def _links_from_js(js):
    m = re.search(r"var links\s*=\s*(\{.*?\});", js or "", re.S)
    if not m:
        return {}
    try:
        return json.loads(m.group(1))
    except Exception:
        return {}


def probe_stream(url, timeout=None):
    """校验 m3u8 是否真的可播（取前 256 字节判断 #EXTM3U）。"""
    if not url or not url.startswith("http"):
        return False
    try:
        r = _get_session().get(url, timeout=timeout or min(6.0, _CFG["timeout"]),
                               headers={"Referer": LK + "/"},
                               stream=True)
        ok = r.status_code in (200, 206)
        if ok:
            chunk = next(r.iter_content(256), b"") or b""
            ok = b"#EXTM3U" in chunk
        try:
            r.close()
        except Exception:
            pass
        return ok
    except Exception:
        return False


_valid_cache = {}
_valid_lock = threading.Lock()


def _cache_valid(url, ok):
    with _valid_lock:
        _valid_cache[url] = (time.time(), ok)


def _cached_valid(url, ttl=600):
    with _valid_lock:
        item = _valid_cache.get(url)
    if item and time.time() - item[0] < ttl:
        return item[1]
    return None


def probe_variant(url, timeout=None):
    """校验 master 里的第一个子清单能否取到（有些片源 master 通但子清单 404）。"""
    host = urllib.parse.urlparse(url).hostname or ""
    if host:
        pin_host(host)
    try:
        tmo = timeout or min(6.0, _CFG["timeout"])
        r = _get_session().get(url, timeout=tmo, headers={"Referer": LK + "/"})
        if r.status_code != 200 or b"#EXTM3U" not in r.content[:200]:
            return False
        subs = [ln.strip() for ln in r.text.splitlines() if ln.strip() and not ln.startswith("#")]
        if not subs:
            return False
        sub_url = urllib.parse.urljoin(url, subs[0])
        host2 = urllib.parse.urlparse(sub_url).hostname or ""
        if host2:
            pin_host(host2)
        r2 = _get_session().get(sub_url, timeout=tmo,
                               headers={"Referer": LK + "/", "Range": "bytes=0-4095"})
        ok = r2.status_code in (200, 206) and b"#EXTINF" in r2.content
        try:
            r.close(); r2.close()
        except Exception:
            pass
        return ok
    except Exception:
        return False


def _candidates_from_html(text):
    """第三方 embed 页 → 候选播放地址（打包脚本 links / file 直写 / 裸 m3u8 三种形态）。"""
    js = unpack_packer(text) or text
    out = []
    links = _links_from_js(js)
    if links:
        for key in ("hls2", "hls3", "hls1", "hls4"):
            u = (links.get(key) or "").strip()
            if u.startswith("http"):
                out.append(u)
    for m in re.finditer(r'file\s*:\s*["\'](https?://[^"\']+)["\']', js):
        out.append(m.group(1))
    for m in re.finditer(r'https?://[^\s"\'>\\]+?\.(?:m3u8|mp4)[^\s"\'>\\]*', js):
        out.append(m.group(0))
    seen, res = set(), []
    for u in out:
        u = (u or "").strip()
        if not u.startswith("http") or ".txt" in u.lower() or u in seen:
            continue
        seen.add(u)
        res.append(u)
    return res


def _vas_stream(final_url, page):
    """vidara 型播放器（playlist:[{sources:[{file:t.streaming_url}]}）：POST /api/stream 取流。"""
    if "api/stream" not in (page or "") or "streaming_url" not in (page or ""):
        return ""
    p = urllib.parse.urlparse(final_url or "")
    code = (p.path or "").strip("/").split("/")[-1]
    if not code or not p.netloc:
        return ""
    origin = "%s://%s" % (p.scheme or "https", p.netloc)
    body = {"filecode": code, "device": "web",
            "codecs": {"av1": "av01.0.09M.10", "h265": "hvc1.1.6.L123.B0"}}
    try:
        pin_host(p.hostname, force=True)
        _throttle()
        r = _get_session().post(origin + "/api/stream", json=body,
                                 timeout=min(6.0, _CFG["timeout"]),
                                 headers={"Referer": final_url, "Origin": origin,
                                          "Content-Type": "application/json"})
        if r.status_code != 200:
            return ""
        url = (r.json() or {}).get("streaming_url") or ""
        if url.startswith("http"):
            _cache_valid(url, True)      # 站点官方接口给的直链，实测 master 200，直接信任
            return url.strip()
        return ""
    except Exception:
        return ""


_line_cache = {}
_line_lock = threading.Lock()


def _remember_line(token, url):
    """记住某条线路解析出的直链，播放阶段命中缓存可省一次 302 + 接口请求。"""
    if not token or not url:
        return
    with _line_lock:
        _line_cache[token] = (url, time.time())
        if len(_line_cache) > 200:
            for k in sorted(_line_cache, key=lambda k: _line_cache[k][1])[:80]:
                _line_cache.pop(k, None)


def resolve_line(token, verify="light"):
    """播放服务器令牌 → (可播直链, 播放器壳页)。

    每个服务器令牌会 302 到各自的第三方 embed 页（evsishere / lulustream /
    vidara / streamtape / voe.sx / fc2stream …），按页面形态取真实地址：
    打包脚本里的 links / file，或 vidara 的 /api/stream 接口。
    """
    token = str(token or "").strip()
    if not token:
        return "", ""
    play_page = "%s/evojav.php?l=%s&bg=" % (LK, token)
    with _line_lock:
        hit = _line_cache.get(token)
    if hit:
        cached_url, ts_c = hit
        if cached_url and time.time() - ts_c < 900 and not m3u8_expired(cached_url):
            if verify == "none":
                return cached_url, play_page
            ok = _cached_valid(cached_url)
            if ok is None:
                ok = probe_stream(cached_url) and (verify != "deep" or probe_variant(cached_url))
                _cache_valid(cached_url, ok)
            if ok:
                return cached_url, play_page
    page, final_url = "", ""
    try:
        pin_host(urllib.parse.urlparse(LK).hostname, force=True)
        _throttle()
        r = _get_session().get("%s/evojav.php?c=%s" % (LK, token[::-1]),
                               timeout=min(8.0, _CFG["timeout"]),
                               headers={"Referer": "%s/evojav.php?l=%s" % (LK, token)})
        page, final_url = (r.text or ""), (r.url or "")
        if final_url:
            # 拿不到直链时，把第三方 embed 页本身交出去（标准播放器页，比 lk1 壳页更容易被播放器嗅探/渲染）
            play_page = final_url.split("#")[0]
    except Exception:
        return "", play_page
    if page and len(page) < 4000:
        # voe.sx 这类中间页是 JS 跳转页，跟到真正的播放器域再解析
        m = re.search(r"window\.location(?:\.href)?\s*=\s*['\"](https?://[^'\"]+)['\"]", page)
        if m:
            try:
                r2 = _get_session().get(m.group(1), timeout=min(8.0, _CFG["timeout"]),
                                        headers={"Referer": final_url or play_page})
                if len(r2.text or "") > 4000:
                    page, final_url = r2.text, (r2.url or m.group(1))
                    play_page = final_url.split("#")[0]
            except Exception:
                pass
    if not page or len(page) < 4000:
        return "", play_page
    try:
        host = urllib.parse.urlparse(final_url).hostname or ""
        if host:
            pin_host(host, force=True)
        cands = _candidates_from_html(page)
        vas = _vas_stream(final_url, page)
        if vas:
            cands.insert(0, vas)
        best = ""
        for url in cands:
            h = urllib.parse.urlparse(url).hostname or ""
            if h:
                pin_host(h, force=True)
            if verify != "none" and _cached_valid(url):
                _remember_line(token, url)
                return url, play_page          # 已在别处校验过，直接用，省一次探测
            if verify == "none":
                _remember_line(token, url)
                return url, play_page
            if verify == "deep":
                # 深校验自带 master + 子清单两步，省掉一次单独的 master 探测
                if probe_variant(url):
                    _cache_valid(url, True)
                    _remember_line(token, url)
                    return url, play_page
                _cache_valid(url, False)
                continue
            if not probe_stream(url):
                _cache_valid(url, False)
                continue
            _cache_valid(url, True)
            _remember_line(token, url)
            return url, play_page
        _remember_line(token, best)
        return best, play_page
    except Exception:
        return "", play_page


def resolve_stream(token, verify=True):
    """播放服务器令牌 → 可播 m3u8（兼容旧调用，逻辑见 resolve_line）。"""
    return resolve_line(token, "light" if verify is True else ("deep" if verify == "deep" else verify))
# ---------------------------------------------------------------- 采集源

class Spider(_BaseSpider):
    def __init__(self):
        try:
            _BaseSpider.__init__(self)
        except Exception:
            pass
        self.extend = ""

    def init(self, extend=""):
        self.extend = extend or ""
        try:
            configure(self.extend)
        except Exception:
            pass
        try:
            _warm_home(self)
        except Exception:
            pass

    def getName(self):
        return "EVOJAV 中文字幕站"

    # ---- 首页
    def homeContent(self, filter=False):
        # 首页先保证有栏目，再在预算内补片单，避免弱网/代理下出现整页空白
        classes = [{"type_id": slug, "type_name": name} for slug, name, _p in CATS]
        videos = []
        deadline = time.time() + HOME_BUDGET
        try:
            videos = parse_cards(fetch("/zh/", budget=min(6.0, HOME_BUDGET)))
            if not videos:
                for slug in ("latest", "popular"):
                    if time.time() > deadline - 1.5:
                        break
                    videos = self._category(slug, 1, budget=deadline)["list"]
                    if videos:
                        break
        except Exception:
            videos = []
        if videos:
            with _home_lock:
                _home_cache["videos"] = videos
                _home_cache["classes"] = classes
                _home_cache["ts"] = time.time()
        else:
            with _home_lock:
                if _home_cache["videos"] and time.time() - _home_cache["ts"] < 1800:
                    videos = _home_cache["videos"]
                    classes = _home_cache["classes"] or classes
        return {"class": classes, "list": videos}

    def homeVideoContent(self):
        return {"list": self.homeContent().get("list") or []}

    # ---- 分类
    def _category(self, tid, pg, budget=None):
        tid = str(tid or "latest")
        base = CAT_PATH.get(tid) or CAT_PATH["latest"]
        path = base if pg <= 1 else base.rstrip("/") + "/page/%d/" % pg
        try:
            text = fetch(path, budget=min(6.0, budget - time.time()) if budget else None)
        except Exception:
            text = ""
        videos = parse_cards(text)
        if not videos and path.startswith("/zh/"):
            try:
                videos = parse_cards(fetch(path[3:], budget=min(4.0, budget - time.time()) if budget else None))
            except Exception:
                pass
        pages = _page_max(text, tid)
        if pages <= pg and len(videos) >= PER_PAGE:
            pages = pg + 1                     # 分页条缺失时按满页向后延一页
        return {
            "page": pg,
            "pagecount": max(pages, pg),
            "limit": PER_PAGE,
            "total": max(pages, pg) * PER_PAGE,
            "list": videos,
        }

    def categoryContent(self, tid, pg, filter=False, extend=None):
        try:
            pg = max(1, int(pg))
        except Exception:
            pg = 1
        return self._category(tid, pg)

    # ---- 搜索
    def searchContent(self, key, quick=False, pg="1"):
        try:
            pg = max(1, int(pg))
        except Exception:
            pg = 1
        key = (key or "").strip()
        if not key:
            return {"list": [], "page": 1, "pagecount": 1, "limit": PER_PAGE, "total": 0}
        kw = urllib.parse.quote(key)
        try:
            text, videos, pages = "", [], 1
            for prefix in ("/zh", ""):
                path = ("%s/?s=%s" % (prefix, kw)) if pg <= 1 else ("%s/page/%d/?s=%s" % (prefix, pg, kw))
                text = fetch(path)
                videos = parse_cards(text)
                if videos:
                    pages = _page_max(text, "")
                    if pages <= 1 and len(videos) >= PER_PAGE:
                        pages = pg + 1
                    break
        except Exception:
            text, videos, pages = "", [], pg
        return {"list": videos, "page": pg, "pagecount": max(pages, pg),
                "limit": PER_PAGE, "total": max(pages, pg) * PER_PAGE}

    # ---- 详情
    def detailContent(self, ids):
        slug = ids[0] if isinstance(ids, (list, tuple)) else ids
        slug = str(slug or "").strip().strip("/")
        m = _SLUG_RE.search(slug)
        if m:
            slug = m.group(1)
        if not slug:
            return {"list": []}
        text = fetch("%s/video/%s/" % (ZH, slug))
        if not text:
            return {"list": []}

        name = ""
        m = re.search(r"<h1[^>]*>(.*?)</h1>", text, re.S)
        if m:
            name = clean(m.group(1))
        if not name:
            m = re.search(r"<title>(.*?)</title>", text, re.S)
            name = clean(m.group(1)).split("-")[0] if m else slug

        pic = ""
        m = re.search(r'id="player-wrap"[^>]*background-image:\s*url\(([^)]+)\)', text)
        if not m:
            m = re.search(r'background-image:\s*url\((https?://[^)]+)\)', text)
        if m:
            pic = _pic(m.group(1))

        cast = [clean(x) for x in re.findall(r'/zh/cast/[^"]+"[^>]*>([^<]+)</a>', text)]
        maker = [clean(x) for x in re.findall(r'/zh/maker/[^"]+"[^>]*>([^<]+)</a>', text)]
        tags = [clean(x) for x in re.findall(r'rel="tag"[^>]*>([^<]+)</a>', text)]

        date = ""
        m = re.search(r'<div class="meta">\s*([0-9]{4}/[0-9]{2}/[0-9]{2})', text)
        if m:
            date = m.group(1)
        views = ""
        m = re.search(r'<span class="views">([^<]+)</span>', text)
        if m:
            views = clean(m.group(1))

        content_bits = []
        if cast:
            content_bits.append("女优：" + "、".join(dict.fromkeys(cast)))
        if maker:
            content_bits.append("制作商：" + "、".join(dict.fromkeys(maker)))
        if date:
            content_bits.append("发行日期：" + date)
        if tags:
            content_bits.append("类别：" + "、".join(dict.fromkeys(tags)))

        servers = re.findall(r'class="btn-server[^"]*"\s+data-link="([^"]+)"[^>]*>([^<]+)</a>', text)
        tokens = [tok for tok, _n in servers if tok]
        names = [clean(n) for _t, n in servers if clean(n)]
        if not tokens:
            return {"list": []}

        # 详情页有几个服务器就写几条线路（EVS / VAS / ST / VOE / LUC / TV / FST …）
        labels, seen_label = [], {}
        for idx, nm in enumerate(names):
            label = (nm or ("线路%d" % (idx + 1))).upper()
            if label in seen_label:
                seen_label[label] += 1
                label = "%s%d" % (label, seen_label[label])
            else:
                seen_label[label] = 1
            labels.append(label)
        while len(labels) < len(tokens):
            labels.append("线路%d" % (len(labels) + 1))

        directs = [""] * len(tokens)
        try:
            from concurrent.futures import ThreadPoolExecutor
            head = tokens[:3]
            with ThreadPoolExecutor(max_workers=min(3, len(head))) as ex:
                got = list(ex.map(lambda t: resolve_stream(t, verify="none")[0], head))
            for i, v in enumerate(got):
                directs[i] = v or ""
        except Exception:
            for i, tok in enumerate(tokens[:3]):
                directs[i] = resolve_stream(tok, verify="none")[0] or ""
        info = {
            "vod_id": slug,
            "vod_name": name,
            "vod_pic": img_url(pic),
            "vod_year": date[:4] if date else "",
            "vod_area": "日本",
            "vod_remarks": views or date,
            "vod_actor": "、".join(dict.fromkeys(cast)),
            "vod_director": "、".join(dict.fromkeys(maker)),
            "vod_content": " ｜ ".join(content_bits) or name,
            "vod_play_from": "$$$".join(labels),
            "vod_play_url": "$$$".join("正片$%s|%s|%s" % (slug, tok, directs[i] or "")
                                       for i, tok in enumerate(tokens)),
        }
        return {"list": [info]}

    # ---- 播放
    def playerContent(self, flag, pid, vipFlags=None):
        pid = str(pid or "").strip()
        header = {"User-Agent": _CFG["ua"], "Referer": BASE + "/"}
        if "|" not in pid and self.isVideoFormat(pid):
            return {"parse": 0, "playUrl": "",
                    "url": _playable(pid, header.get("Referer", "")), "header": header}
        if not pid:
            return {"parse": 1, "playUrl": "", "url": "", "header": header}

        parts = pid.split("|")
        direct = parts[2] if len(parts) > 2 else ""
        token_blob = parts[1] if len(parts) > 1 else parts[0]

        if direct.startswith("http") and not m3u8_expired(direct):
            good = _cached_valid(direct)
            if good is None:
                good = probe_variant(direct)
                _cache_valid(direct, good)
            if good:
                return {"parse": 0, "playUrl": "",
                        "url": _playable(direct, header.get("Referer", "")), "header": header}

        tokens = [t for t in re.split(r"[,|]", token_blob) if t]
        banner = ""
        for tok in tokens:
            url, page = resolve_stream(tok, verify="deep")
            if not banner:
                banner = page
            if url:
                return {"parse": 0, "playUrl": "",
                        "url": _playable(url, header.get("Referer", "")), "header": header}
        shell = banner or ("%s/evojav.php?l=%s&bg=" % (LK, tokens[0]) if tokens else "")
        if shell:
            return {"parse": 1, "playUrl": "", "url": _playable_page(shell), "header": header}
        return {"parse": 1, "playUrl": "", "url": "", "header": header}

    def isVideoFormat(self, url):
        return bool(re.search(r"\.(m3u8|mp4|flv)(\?|$)", url or "", re.I))

    def manualVideoCheck(self):
        return False

    def destroy(self):
        global _session
        with _sess_lock:
            _session = None
        _stop_img_server()
        _stop_relay_server()
        with _sess_lock:
            _sessions.clear()
        with _net_lock:
            _net["mode"], _net["ts"] = "", 0.0
        with _cache_lock:
            _cache.clear()


# ---------------------------------------------------------------- 命令行自测

def _print(obj):
    print(json.dumps(obj, ensure_ascii=False, indent=2)[:3000])


def main(argv):
    sp = Spider()
    sp.init("")
    args = argv[1:]
    cmd = args[0] if args else "check"

    if cmd == "check":
        t0 = time.time()
        home = sp.homeContent()
        print("首页: 分类 %d | 条目 %d | 耗时 %.2fs"
              % (len(home["class"]), len(home["list"]), time.time() - t0))
        _print(home["list"][:2])
    elif cmd == "categories":
        for c in sp.homeContent()["class"]:
            print("  %-20s %s" % (c["type_id"], c["type_name"]))
    elif cmd == "category":
        tid = args[1] if len(args) > 1 else "censored-jav"
        pg = args[2] if len(args) > 2 else "1"
        r = sp.categoryContent(tid, pg)
        print("栏目 %s 第 %s 页 | pagecount %s | 条目 %d" % (tid, pg, r["pagecount"], len(r["list"])))
        _print(r["list"][:2])
    elif cmd == "search":
        kw = args[1] if len(args) > 1 else "东美香"
        pg = args[2] if len(args) > 2 else "1"
        r = sp.searchContent(kw, False, pg)
        print("搜索 %r 第 %s 页 | pagecount %s | 条目 %d" % (kw, pg, r["pagecount"], len(r["list"])))
        _print(r["list"][:2])
    elif cmd == "detail":
        _print(sp.detailContent([args[1]]) if len(args) > 1 else "需要 slug")
    elif cmd == "play":
        if len(args) < 2:
            print("需要 slug")
            return
        det = sp.detailContent([args[1]])["list"]
        if not det:
            print("详情为空")
            return
        pid = det[0]["vod_play_url"].split("$", 1)[1]
        print(json.dumps(sp.playerContent(det[0]["vod_play_from"], pid), ensure_ascii=False))
    else:
        print(__doc__)


if __name__ == "__main__":
    main(sys.argv)
