# -*- coding: utf-8 -*-
# TVBox 影视源：黑料网曝（lede-parc-hexi.xxxxxxav-108.com）v1.0
import sys
import ssl
import time
import json
import re
import gzip
import zlib
import html as html_mod
import urllib.request
import urllib.parse
import urllib.error
from http.cookiejar import CookieJar

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

class Spider(BaseSpider):
    def __init__(self):
        self.site_url = "https://lede-parc-hexi.xxxxxxav-108.com"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.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",
            "Referer": "https://lede-parc-hexi.xxxxxxav-108.com/",
            "Connection": "keep-alive",
        }
        self.cats = [
            ("163", "国产视频"), ("232", "网曝黑料"), ("236", "主播大秀"),
            ("233", "AV解说"), ("48", "国产自拍"), ("231", "抖阴视频"),
            ("2", "国产传媒"), ("227", "综合传媒"), ("38", "麻豆合集"),
            ("109", "葫芦影业"), ("111", "天美传媒"),
            ("131", "91制片厂"),
            ("17", "国产精品"),
            ("18", "国产剧情"), ("114", "精东影业"),
            ("116", "SWAG"), ("120", "兔子先生"),
        ]
        self.cookie_jar = CookieJar()
        self.opener = self._build_opener()
        self._throttle = 0.4
        self._last_req = 0.0

    def _build_opener(self):
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        https_handler = urllib.request.HTTPSHandler(context=ctx)
        cookie_handler = urllib.request.HTTPCookieProcessor(self.cookie_jar)
        return urllib.request.build_opener(https_handler, cookie_handler)

    def getName(self):
        return "黑料网曝"

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

    # ============ 网络层 ============
    def _decode_body(self, raw, enc=""):
        if not raw:
            return ""
        if isinstance(raw, str):
            return raw
        if "gzip" in enc:
            try: raw = gzip.decompress(raw)
            except Exception: pass
        elif "deflate" in enc:
            try: raw = zlib.decompress(raw)
            except Exception: pass
        for cs in ("utf-8", "gbk", "gb2312"):
            try: return raw.decode(cs)
            except Exception: continue
        return raw.decode("utf-8", errors="ignore")

    def _fetch(self, url, retry=2, referer=None, timeout=12):
        import http.client
        gap = time.time() - self._last_req
        if gap < self._throttle:
            time.sleep(self._throttle - gap)
        self._last_req = time.time()
        headers = dict(self.headers)
        if referer:
            headers["Referer"] = referer
        last_err = ""
        for i in range(retry + 1):
            try:
                req = urllib.request.Request(url, headers=headers, method="GET")
                with self.opener.open(req, timeout=timeout) as resp:
                    raw = resp.read()
                    enc = resp.headers.get("Content-Encoding", "").lower()
                    return {"success": True, "html": self._decode_body(raw, enc)}
            except http.client.IncompleteRead as e:
                if e.partial:
                    return {"success": True, "html": self._decode_body(e.partial)}
                last_err = str(e)
            except Exception as e:
                last_err = str(e)
                if i < retry:
                    time.sleep(0.4)
        return {"success": False, "html": "", "error": last_err}

    def _fetch_html(self, url, must_contain=None, timeout=12, referer=None):
        html_data = ""
        for _ in range(3):
            res = self._fetch(url, timeout=timeout, referer=referer)
            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 _abs_url(self, url):
        if not url: return ""
        url = url.strip()
        if url.startswith("http"): return url
        if url.startswith("//"): return "https:" + url
        return urllib.parse.urljoin(self.site_url, url)

    @staticmethod
    def _clean(text):
        if not text: return ""
        text = html_mod.unescape(text)
        return re.sub(r"<[^>]+>", "", text).strip()

    # ============ 封面代理 ============
    @staticmethod
    def _img_mime(data):
        if not data or len(data) < 12: return ""
        if data[:2] == b"\xff\xd8": return "image/jpeg"
        if data[:8] == b"\x89PNG\r\n\x1a\n": return "image/png"
        if data[:4] == b"RIFF" and data[8:12] == b"WEBP": return "image/webp"
        return ""

    def _fetch_bytes(self, url, timeout=15, retries=3):
        import http.client
        req = urllib.request.Request(url, headers={
            "User-Agent": self.headers["User-Agent"],
            "Referer": self.site_url + "/"})
        best = b""
        for _ in range(max(1, retries)):
            try:
                with self.opener.open(req, timeout=timeout) as resp:
                    return resp.read()
            except http.client.IncompleteRead as e:
                if e.partial and len(e.partial) > len(best):
                    best = e.partial
            except Exception:
                pass
        return best

    def _pic_url(self, pic):
        return pic or ""

    def localProxy(self, params):
        try:
            if params.get("type") == "pic":
                url = params.get("url", "")
                if url:
                    raw = self._fetch_bytes(url, timeout=15)
                    mime = self._img_mime(raw)
                    if mime:
                        return [200, mime, raw, ""]
                    if raw[:2] == b"\xff\xd8":
                        return [200, "image/jpeg", raw, ""]
        except Exception:
            pass
        return [200, "text/plain; charset=utf-8", ""]

    # ============ 列表解析 ============
    def _parse_vod_list(self, html_data):
        cards, seen = [], set()
        if not html_data:
            return cards
        # <a href="/voddetail/ID/" title="标题"><img src="封面">
        for m in re.finditer(
                r'<a\s+href="(/voddetail/(\d+)/)"[^>]*?title="([^"]+)"[^>]*>.*?'
                r'<img[^>]+src="([^"]+\.(?:jpg|jpeg|png|webp)[^"]*)"',
                html_data, re.S):
            url, vid, title, pic = m.group(1), m.group(2), m.group(3), m.group(4)
            if vid in seen:
                continue
            seen.add(vid)
            # 去掉 ?t= 时间戳
            pic = pic.split("?")[0]
            cards.append({
                "vod_id": vid,
                "vod_name": self._clean(title) or vid,
                "vod_pic": self._pic_url(self._abs_url(pic)),
                "vod_remarks": "",
            })
        # 兜底
        if not cards:
            for m in re.finditer(
                    r'href="(/voddetail/(\d+)/)"[^>]*title="([^"]{4,80})"',
                    html_data):
                vid, title = m.group(2), m.group(3)
                if vid not in seen:
                    seen.add(vid)
                    cards.append({"vod_id": vid,
                                  "vod_name": self._clean(title) or vid,
                                  "vod_pic": "", "vod_remarks": ""})
        return cards

    # ============ 播放地址提取 ============
    def _extract_play_url(self, html_data):
        if not html_data:
            return ""
        # player_aaaa.url
        m = re.search(r'"url"\s*:\s*"((?:[^"\\]|\\.)*?\.m3u8(?:[^"\\]|\\.)*?)"', html_data)
        if m:
            u = m.group(1).replace("\\/", "/")
            if "sample" not in u and "test" not in u:
                return u
        for mm in re.finditer(r'"(https?://[^"]+\.m3u8[^"]*)"', html_data, re.I):
            u = mm.group(1).replace("\\/", "/")
            if "sample" not in u and "test" not in u:
                return u
        for mm in re.finditer(r'"(https?://[^"]+\.mp4[^"]*)"', html_data, re.I):
            u = mm.group(1).replace("\\/", "/")
            if "sample" not in u and "test" not in u:
                return u
        return ""

    # ============ 标准接口 ============
    def homeContent(self, filter):
        return {"class": [{"type_id": tid, "type_name": name}
                          for tid, name in self.cats],
                "filters": {}}

    def homeVideoContent(self):
        html_data = self._fetch_html(self.site_url + "/t/232/",
                                     must_contain="voddetail")
        return {"list": self._parse_vod_list(html_data)[:20]}

    def categoryContent(self, tid, pg, filter, extend):
        try: pg = int(pg)
        except Exception: pg = 1
        if pg < 1: pg = 1
        tid = str(tid).strip()
        if pg <= 1:
            url = "%s/t/%s/" % (self.site_url, tid)
        else:
            url = "%s/t/%s-%d/" % (self.site_url, tid, pg)
        html_data = self._fetch_html(url, must_contain="voddetail")
        cards = self._parse_vod_list(html_data)
        return {"list": cards, "page": pg,
                "pagecount": pg + 1 if len(cards) >= 20 else pg,
                "limit": len(cards), "total": 0}

    def detailContent(self, ids):
        vid = str(ids[0]).strip() if ids else ""
        if not vid:
            return {"list": []}
        vod = {"vod_id": vid, "vod_name": vid, "vod_pic": "",
               "vod_remarks": "", "vod_content": "",
               "vod_play_from": "在线播放",
               "vod_play_url": "正片$/v/%s/" % vid}
        try:
            html_data = self._fetch_html(
                "%s/voddetail/%s/" % (self.site_url, vid),
                must_contain="voddetail")
            tm = re.search(r"<title>(.*?)</title>", html_data, re.S | re.I)
            if tm:
                t = self._clean(tm.group(1)).split("|")[0].strip()
                t = re.sub(r"^在线播放", "", t).strip()
                if t:
                    vod["vod_name"] = t
            pm = re.search(
                r'<img[^>]+src="(https?://[^"]+\.(?:jpg|jpeg|png|webp)[^"]*)"',
                html_data)
            if pm:
                vod["vod_pic"] = self._pic_url(pm.group(1).split("?")[0])
            # 播放页拿直链
            vp_html = self._fetch_html(
                "%s/v/%s/" % (self.site_url, vid),
                referer="%s/voddetail/%s/" % (self.site_url, vid))
            play_url = self._extract_play_url(vp_html)
            if play_url:
                vod["vod_play_url"] = "正片$%s" % play_url
        except Exception:
            pass
        return {"list": [vod]}

    def playerContent(self, flag, id, vipFlags):
        raw_id = str(id).strip()
        header = {"User-Agent": self.headers["User-Agent"],
                  "Referer": self.site_url + "/"}
        if raw_id.startswith("http") and self.isVideoFormat(raw_id):
            return {"parse": 0, "url": raw_id, "header": header}
        try:
            url = raw_id if raw_id.startswith("http") else \
                self.site_url + (raw_id if raw_id.startswith("/")
                                  else "/v/%s/" % re.sub(r"\D", "", raw_id))
            vp_html = self._fetch_html(url)
            play_url = self._extract_play_url(vp_html)
            if play_url:
                return {"parse": 0, "url": play_url, "header": header}
        except Exception:
            pass
        return {"parse": 1, "url": raw_id, "header": header}

    def searchContent(self, key, quick, pg="1"):
        try: pg = int(pg)
        except Exception: pg = 1
        if pg < 1: pg = 1
        kw = urllib.parse.quote(str(key).strip())
        if pg <= 1:
            url = "%s/s/wd/%s/" % (self.site_url, kw)
        else:
            url = "%s/s/wd/%s/page/%d/" % (self.site_url, kw, pg)
        html_data = self._fetch_html(url)
        cards = self._parse_vod_list(html_data)
        return {"list": cards, "page": pg,
                "pagecount": pg + 1 if len(cards) >= 20 else pg,
                "limit": len(cards), "total": 0}

    def action(self, action):
        return None

    def liveContent(self):
        return {}

    def isVideoFormat(self, url):
        u = (url or "").lower()
        return u.endswith(".m3u8") or ".m3u8?" in u

    def manualVideoCheck(self):
        return False

    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

    hc = sp.homeContent(True)
    check("homeContent", len(hc["class"]) > 0, "%d分类" % len(hc["class"]))

    r = sp.categoryContent("232", "1", None, None)
    check("category", len(r["list"]) > 0, "%d条" % len(r["list"]))
    pics = sum(1 for v in r["list"] if v["vod_pic"].startswith("http"))
    check("covers", pics == len(r["list"]) and pics > 0,
          "%d/%d" % (pics, len(r["list"])))
    titles = sum(1 for v in r["list"] if v["vod_name"] and not v["vod_name"].isdigit())
    check("titles", titles == len(r["list"]), "%d/%d" % (titles, len(r["list"])))

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

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

    h = sp.homeVideoContent()
    check("home", len(h["list"]) > 0, "%d条" % len(h["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 v["vod_name"] != vid
              and v["vod_pic"].startswith("http"),
              "%s | 封面%s | m3u8=%s" % (v["vod_name"][:25],
                                         "有" if v["vod_pic"] else "无",
                                         "有" if has_m3u8 else "无"))
        if has_m3u8:
            ep = v["vod_play_url"].split("$", 1)[1]
            p = sp.playerContent("在线播放", ep, [])
            check("player", p["parse"] == 0 and ".m3u8" in p["url"]
                  and isinstance(p.get("header"), dict)
                  and "playUrl" not in p, p["url"][:70])
    else:
        check("detail", False, "无列表跳过")

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