# -*- coding: utf-8 -*-
# TVBox Python 影视源：997热线（say-mesh-82828.migdyjoa62.top）v1.0
# ============================================================
# 站点结构（2026-10-08 实测）：
#  分类：/t/{id}/，翻页 /t/{id}-{pg}/
#  详情：/voddetail/{id}/，播放按钮 -> /v/{id}/
#  播放页：/v/{id}/，player_aaaa.url = m3u8 明文（encrypt:0）
#  搜索：/s/wd/{kw}/
#  卡片：<a href="/voddetail/{id}/" title="..."><img src="封面">
import sys
import ssl
import time
import json
import re
import urllib.request
import urllib.parse
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://say-mesh-82828.migdyjoa62.top"
        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": self.site_url + "/",
        }
        self.cookie_jar = CookieJar()
        self.opener = self._build_opener()
        self.cats = [
            ("234", "自拍/偷拍"), ("233", "主播大秀"), ("232", "网曝黑料"),
            ("163", "国产视频"), ("17", "国产精品"), ("235", "国产自拍"),
            ("2", "国产传媒"), ("241", "网红头条"), ("239", "探花系列"),
            ("238", "AV解说"), ("38", "麻豆合集"), ("109", "葫芦影业"),
            ("1", "日本有码"), ("5", "日本无码"),
            ("13", "中文字幕"), ("30", "欧美"), ("240", "萝莉少女"),
            ("7", "日本巨乳"), ("9", "制服诱惑"), ("86", "女优"),
            ("225", "综合番号"),
        ]
        self._throttle = 0.3
        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 _decode_body(self, raw):
        if not raw:
            return ""
        if isinstance(raw, str):
            return raw
        import gzip, zlib
        try:
            # 尝试 gzip
            return gzip.decompress(raw).decode("utf-8", errors="ignore")
        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)
                with self.opener.open(req, timeout=timeout) as resp:
                    raw = resp.read()
                    return {"success": True, "html": self._decode_body(raw)}
            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, referer=None):
        html_data = ""
        for _ in range(3):
            res = self._fetch(url, 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 ""
        import html as html_mod
        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):
        import http.client
        req = urllib.request.Request(url, headers={
            "User-Agent": self.headers["User-Agent"],
            "Referer": self.site_url + "/"})
        best = b""
        for _ in range(3):
            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 localProxy(self, params):
        try:
            if params.get("type") == "pic":
                url = params.get("url", "")
                if url:
                    raw = self._fetch_bytes(url)
                    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
        for m in re.finditer(
                r'<a\s+href="/voddetail/(\d+)/"[^>]*?title="([^"]+)"[^>]*?>\s*<img\s+src="([^"]+)"',
                html_data, re.S):
            vid, title, pic = m.group(1), m.group(2).strip(), m.group(3)
            if vid in seen:
                continue
            seen.add(vid)
            cards.append({
                "vod_id": vid,
                "vod_name": self._clean(title) or vid,
                "vod_pic": self._abs_url(pic),
                "vod_remarks": "",
            })
        if not cards:
            for m in re.finditer(
                    r'href="/voddetail/(\d+)/"[^>]*title="([^"]+)"', html_data):
                vid, title = m.group(1), m.group(2).strip()
                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 JSON
        m = re.search(r'var\s+player_aaaa\s*=\s*(\{.*?\})\s*</script>',
                      html_data, re.S)
        if m:
            try:
                pd = json.loads(m.group(1))
                u = str(pd.get("url", "")).strip().replace("\\/", "/")
                if u and self.isVideoFormat(u):
                    return u
            except Exception:
                pass
        # 直接正则
        m = re.search(r'"url"\s*:\s*"(https?:[^"]+\.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
        return ""

    def init(self, extend=""):
        try:
            cfg = json.loads(extend) if extend and extend.strip() else {}
            host = str(cfg.get("host", "")).strip().rstrip("/")
            if host:
                self.site_url = host
                self.headers["Referer"] = host + "/"
        except Exception:
            pass

    def getName(self):
        return "997热线"

    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("%s/t/234/" % self.site_url,
                                     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)
        # 总页数
        pagecount = pg
        m = re.search(r'/t/%s-(\d+)/"\s+class="laypage_last"' % tid, html_data)
        if m:
            pagecount = int(m.group(1))
        elif len(cards) >= 20:
            pagecount = pg + 1
        return {"list": cards, "page": pg, "pagecount": pagecount,
                "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:
            durl = "%s/voddetail/%s/" % (self.site_url, vid)
            html_data = self._fetch_html(durl, must_contain="voddetail")
            tm = re.search(r'<a[^>]*class="tx-btn[^"]*"[^>]*>([^<>]+)</a>',
                           html_data)
            # 标题
            m = re.search(r'<title>(.*?)</title>', html_data, re.S | re.I)
            if m:
                t = self._clean(m.group(1)).split("|")[0].strip()
                t = re.sub(r'^在线播放', '', t).strip()
                if t:
                    vod["vod_name"] = t
            # 封面
            pm = re.search(r'<img[^>]+src="([^"]+\.(?:jpg|jpeg|png|webp)[^"]*)"',
                           html_data)
            if pm:
                vod["vod_pic"] = self._abs_url(pm.group(1))
            # 播放页直链
            pm2 = re.search(r'href="(/v/%s/)"' % vid, html_data)
            play_page = pm2.group(1) if pm2 else "/v/%s/" % vid
            vp_html = self._fetch_html(self.site_url + play_page,
                                       referer=durl)
            play_url = self._extract_play_url(vp_html)
            if play_url:
                vod["vod_play_url"] = "正片$%s" % play_url
            else:
                vod["vod_play_url"] = "正片$%s" % play_page
        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/%d/" % (self.site_url, kw, 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 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"]) >= 20, "%d分类" % len(hc["class"]))

    r = sp.categoryContent("234", "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("234", "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 not v["vod_name"].isdigit()
              and has_m3u8 and v["vod_pic"].startswith("http"),
              "%s | 封面%s" % (v["vod_name"][:30],
                               "有" if v["vod_pic"] 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")
