# -*- coding: utf-8 -*-
"""
黄瓜视频 (9wkx145bm.209018.xyz) - py影视 Spider v2
v2 (2026-10-08) 修复清单:
  1. playerContent header 改为 dict (原来是 json.dumps 字符串, APP 无法设置请求头)
  2. isVideoFormat 按 .m3u8 判断 (原来永远 False, 播放器可能误判嗅探)
  3. _fetch 加 3 次重试 + _fetch_html 内容校验 (must_contain), 根治偶发残缺页面
  4. _deobfuscate 改为处理所有 atob 块 (原来只解第一个)
  5. 去掉 vod_remarks / vod_content / type_name 硬编码 "黄瓜视频"
  6. 详情标题加 og:title / img alt 兜底, 不再死赌 parts[1]
  7. 选集按 mark 的 id 分线路 (单线路保持"黄瓜线路"兼容)
  8. 自带测试断言改为 > 0, 不再硬编码条数
实测(2026-10-08): 站点当前直接返回 HTML, 已无混淆, _deobfuscate 保留作保险
- 列表: <article><a href="/vodplay/{id}-1-1.html" class="video_link">
        <figure><img class="lazyload" data-src="{pic}"></figure><cite>{title}</cite></a></article>
- 分类: /vodtype/{tid}.html, p2+ /vodtype/{tid}-{pg}.html, 8条/页
- 搜索: p1 /vod/search.html?wd={key}, p2+ /vod/search/page/{pg}/wd/{key}.html
- 详情: /voddetail/{id}.html, <mark id="bfz" data-user-name="第1集$直链m3u8">
- 播放: mark 里就是直链 m3u8, playerContent 直接返回 parse:0
- 注意: 侧栏广告也是 <li><a><img><p> 结构, 但 href 指向 gotome.vip, 用 /vodplay/ 正则天然过滤
"""
import re
import ssl
import gzip
import zlib
import json
import base64
import urllib.request
import urllib.parse
import html

try:
    from base.spider import Spider as BaseSpider
except Exception:
    class BaseSpider(object):
        pass


class Spider(BaseSpider):

    def getName(self):
        return "黄瓜视频"

    def init(self, extend=""):
        pass

    def __init__(self):
        super(Spider, self).__init__()
        self.site_url = "https://9wkx145bm.209018.xyz"
        self.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",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Connection": "keep-alive",
            "Referer": self.site_url + "/"
        }

    # ---------------- 抓取 + 去混淆 ----------------
    def _deobfuscate(self, text):
        """解开所有 atob(char-code数组) 混淆块 -> 真实HTML"""
        if "atob(" not in text:
            return text

        def _dec(m):
            try:
                codes = json.loads(base64.b64decode(m.group(1)).decode("ascii"))
                raw = "".join(chr(c) for c in codes)
                return raw.encode("latin1").decode("utf-8", errors="ignore")
            except Exception:
                return m.group(0)

        return re.sub(r'atob\("([^"]+)"\)', _dec, text)

    def _fetch(self, url, retries=3):
        last = {"success": False, "html": "", "error": ""}
        for _ in range(max(1, retries)):
            req = urllib.request.Request(url, headers=self.headers)
            try:
                ctx = ssl._create_unverified_context()
            except Exception:
                ctx = None
            try:
                if ctx:
                    resp = urllib.request.urlopen(req, context=ctx, timeout=12)
                else:
                    resp = urllib.request.urlopen(req, timeout=12)
                raw = resp.read()
                enc = resp.headers.get("Content-Encoding", "").lower()
                if "gzip" in enc:
                    raw = gzip.decompress(raw)
                elif "deflate" in enc:
                    raw = zlib.decompress(raw)
                text = ""
                for charset in ("utf-8", "gbk", "gb2312", "iso-8859-1"):
                    try:
                        text = raw.decode(charset)
                        break
                    except Exception:
                        continue
                return {"success": True, "html": self._deobfuscate(text),
                        "real_url": resp.geturl()}
            except Exception as e:
                last = {"success": False, "html": "", "error": str(e)}
        return last

    def _fetch_html(self, url, must_contain=None):
        """带内容校验的抓取: 成功但内容缺标记(残缺页/风控页)则重试"""
        html_data = ""
        for _ in range(3):
            res = self._fetch(url)
            html_data = res.get("html", "")
            if res.get("success") and (not must_contain
                                       or must_contain in html_data):
                return html_data
        return html_data

    def homeContent(self, filter):
        classes = [
            {"type_id": "21", "type_name": "视频②区"}, {"type_id": "40", "type_name": "国产视频"},
            {"type_id": "41", "type_name": "中文字幕"}, {"type_id": "42", "type_name": "国产传媒"},
            {"type_id": "43", "type_name": "日本有码"}, {"type_id": "44", "type_name": "日本无码"},
            {"type_id": "45", "type_name": "欧美无码"}, {"type_id": "46", "type_name": "美女主播"},
            {"type_id": "47", "type_name": "激情动漫"}, {"type_id": "48", "type_name": "明星换脸"},
            {"type_id": "50", "type_name": "女优明星"}, {"type_id": "51", "type_name": "SM调教"},
            {"type_id": "52", "type_name": "网红头条"}, {"type_id": "53", "type_name": "极品媚黑"},
            {"type_id": "54", "type_name": "人妖系列"}, {"type_id": "55", "type_name": "VR视角"},
            {"type_id": "56", "type_name": "伦理三级"}, {"type_id": "57", "type_name": "女同性恋"},
            {"type_id": "58", "type_name": "AV解说"}, {"type_id": "59", "type_name": "清纯素女"},
        ]
        return {"class": classes, "filters": {}}

    def homeVideoContent(self):
        html_data = self._fetch_html(self.site_url + "/vodtype/53.html",
                                     must_contain="/vodplay/")
        return {"list": self._parse_vod_list(html_data)}

    # ---------------- 统一列表解析 ----------------
    def _parse_vod_list(self, html_data):
        cards = []
        if not html_data:
            return cards
        blocks = re.findall(
            r'<article>\s*<a[^>]*href=["\'](/vodplay/(\d+)-\d+-\d+\.html)["\'][^>]*class=["\']video_link["\'][^>]*>(.*?)</a>\s*</article>',
            html_data, re.I | re.S)
        if not blocks:
            blocks = re.findall(
                r'<a[^>]*href=["\'](/vodplay/(\d+)-\d+-\d+\.html)["\'][^>]*>(.*?)</a>',
                html_data, re.I | re.S)
        seen = set()
        for href, vid, inner in blocks:
            if vid in seen:
                continue
            seen.add(vid)

            title = ""
            cm = re.search(r'<cite[^>]*>(.*?)</cite>', inner, re.I | re.S)
            if cm:
                title = re.sub(r'<[^>]+>', '', cm.group(1)).strip()
            if not title:
                tm = re.search(r'title=["\']([^"\']+)["\']', inner, re.I)
                if tm:
                    title = tm.group(1).strip()
            if not title:
                continue
            title = html.unescape(title)

            pic = ""
            for pat in (r'data-src=["\']([^"\']+)["\']', r'data-original=["\']([^"\']+)["\']',
                        r'src=["\']([^"\']+)["\']'):
                pm = re.search(pat, inner, re.I)
                if pm:
                    cand = pm.group(1).strip()
                    if cand and not cand.startswith("data:image"):
                        pic = cand
                        break
            if pic.startswith("//"):
                pic = "https:" + pic
            elif pic.startswith("/"):
                pic = urllib.parse.urljoin(self.site_url, pic)

            cards.append({
                "vod_id": vid,
                "vod_name": title,
                "vod_pic": pic,
                "vod_remarks": "",
                "style": {"type": "rect", "ratio": 1.78}
            })
        return cards

    def categoryContent(self, tid, pg, filter, extend):
        pg_int = int(pg) if str(pg).isdigit() else 1
        if pg_int <= 1:
            url = "%s/vodtype/%s.html" % (self.site_url, tid)
        else:
            url = "%s/vodtype/%s-%d.html" % (self.site_url, tid, pg_int)
        cards = self._parse_vod_list(
            self._fetch_html(url, must_contain="/vodplay/"))
        return {
            "list": cards,
            "page": pg_int,
            "pagecount": pg_int + 1 if len(cards) >= 8 else pg_int,
            "limit": len(cards),
            "total": 9999
        }

    def _extract_title(self, h):
        """详情标题: 站点名-片名-关键词, 多级兜底"""
        tm = re.search(r'<title>(.*?)</title>', h, re.I | re.S)
        if tm:
            raw = html.unescape(tm.group(1)).strip()
            parts = [p.strip() for p in raw.split("-") if p.strip()]
            if len(parts) > 1 and parts[0] == self.getName():
                return parts[1]
            if parts:
                t = parts[0]
                if t.startswith(self.getName()):
                    t = t[len(self.getName()):].lstrip("- ").strip()
                return t
        # 兜底: og:title / figure img alt
        og = re.search(
            r'<meta[^>]*property="og:title"[^>]*content="([^"]+)"', h, re.I)
        if og:
            return html.unescape(og.group(1)).strip()
        fa = re.search(r'<figure>.*?<img[^>]+alt=["\']([^"\']+)["\']',
                       h, re.I | re.S)
        if fa:
            return html.unescape(fa.group(1)).strip()
        return ""

    def detailContent(self, ids):
        vid = ids[0] if isinstance(ids, list) else ids
        h = self._fetch_html("%s/voddetail/%s.html" % (self.site_url, vid),
                             must_contain="data-user-name")

        title = self._extract_title(h)

        pic = ""
        fm = re.search(r'<figure>.*?<img[^>]+data-src=["\']([^"\']+)["\']',
                       h, re.I | re.S)
        if fm:
            pic = fm.group(1).strip()
        if pic.startswith("//"):
            pic = "https:" + pic
        elif pic.startswith("/"):
            pic = urllib.parse.urljoin(self.site_url, pic)

        # 按 mark 的 id 分线路 (单线路保持"黄瓜线路"兼容老版本)
        lines, order = {}, []
        for m in re.finditer(r'<mark[^>]*data-user-name="([^"]+)"[^>]*>',
                             h, re.I):
            ep = html.unescape(m.group(1)).strip()
            if "$http" not in ep:
                continue
            lid = re.search(r'id="([^"]+)"', m.group(0))
            key = lid.group(1) if lid else "default"
            if key not in lines:
                lines[key] = []
                order.append(key)
            lines[key].append(ep)
        if len(order) == 1:
            play_from = ["黄瓜线路"]
            play_url = ["#".join(lines[order[0]])]
        elif order:
            play_from = ["线路%d" % (i + 1) for i in range(len(order))]
            play_url = ["#".join(lines[k]) for k in order]
        else:
            play_from, play_url = [], []

        vod = {
            "vod_id": vid,
            "vod_name": title or "未知",
            "vod_pic": pic,
            "vod_content": "",
            "vod_play_from": "$$$".join(play_from),
            "vod_play_url": "$$$".join(play_url)
        }
        return {"list": [vod]}

    def playerContent(self, flag, id, vipFlags):
        url = id.strip()
        if not url.startswith("http"):
            url = self.site_url + url
        return {
            "parse": 0,
            "url": url,
            # 修: header 必须是 dict, 不能是 json.dumps 后的字符串
            "header": {
                "User-Agent": self.headers["User-Agent"],
                "Referer": self.site_url + "/"
            }
        }

    def searchContent(self, key, quick, pg="1"):
        pg_int = int(pg) if str(pg).isdigit() else 1
        ek = urllib.parse.quote(key)
        if pg_int <= 1:
            url = "%s/vod/search.html?wd=%s" % (self.site_url, ek)
        else:
            url = "%s/vod/search/page/%d/wd/%s.html" % (self.site_url, pg_int, ek)
        cards = self._parse_vod_list(
            self._fetch_html(url, must_contain="/vodplay/"))
        return {
            "list": cards,
            "page": pg_int,
            "pagecount": pg_int + 1 if len(cards) >= 8 else pg_int,
            "limit": len(cards),
            "total": 9999
        }

    def action(self, action):
        return {}

    def liveContent(self):
        return {}

    def localProxy(self, params):
        return [200, "text/plain; charset=utf-8", ""]

    def manualVideoCheck(self):
        return False

    def isVideoFormat(self, url):
        # 修: m3u8 直链应返回 True, 否则播放器可能误判去嗅探
        u = (url or "").lower()
        return u.endswith(".m3u8") or ".m3u8?" in u

    def destroy(self):
        pass


if __name__ == "__main__":
    sp = Spider()
    sp.init()
    ok = True

    def check(name, cond, extra=""):
        global ok
        print(("PASS " if cond else "FAIL ") + name + (" | " + str(extra) if extra else ""))
        if not cond:
            ok = False

    r = sp.categoryContent("53", "1", True, {})
    check("category p1", len(r["list"]) > 0, "%d条 pagecount=%s" % (len(r["list"]), r["pagecount"]))
    pics = sum(1 for v in r["list"] if v["vod_pic"].startswith("http"))
    check("category 封面率", pics == len(r["list"]) and pics > 0, "%d/%d" % (pics, len(r["list"])))

    r2 = sp.categoryContent("53", "2", True, {})
    ids1 = {v["vod_id"] for v in r["list"]}
    ids2 = {v["vod_id"] for v in r2["list"]}
    check("category p2", len(r2["list"]) > 0 and not ids1 & ids2, "%d条 无重叠" % len(r2["list"]))

    s = sp.searchContent("媚黑", False, "1")
    check("search p1", len(s["list"]) > 0, "%d条" % len(s["list"]))

    if r["list"]:
        vid = r["list"][0]["vod_id"]
        d = sp.detailContent([vid])
        v = d["list"][0]
        has_m3u8 = ".m3u8" in v["vod_play_url"]
        check("detail", bool(v["vod_name"]) and has_m3u8, v["vod_name"][:24])
        if has_m3u8:
            ep_url = v["vod_play_url"].split("#")[0].split("$", 1)[1]
            p = sp.playerContent("黄瓜线路", ep_url, [])
            check("player", p["parse"] == 0 and p["url"].endswith(".m3u8")
                  and isinstance(p.get("header"), dict), p["url"][:70])
            check("isVideoFormat", sp.isVideoFormat(p["url"]) is True)
    else:
        check("detail", False, "无列表数据跳过")
        check("player", False, "无列表数据跳过")
        check("isVideoFormat", False, "无列表数据跳过")

    print("ALL PASS" if ok else "SOME FAILED")
