# -*- coding: utf-8 -*-
# TVBox Python 影视源：海角社区（nit.naiduoduo0917.buzz）v1.1
# ============================================================
# 站点结构（2026-10-08 实测，苹果CMS系）：
#  首页：/love/
#  分类：/vodtype/{id}/，翻页 /vodtype/{id}/page/{pg}/
#  详情：/voddetail/{id}/（标题在 a.title，封面 data-src 绝对URL）
#  播放页：/vodplay/{id}-1-1/（player_data.url = m3u8直链，\/转义）
#  搜索：GET /vodsearch/-------------.html?wd={kw}
# 注意：需 Windows UA + Referer + CookieJar，否则播放页403
import re
import time
import ssl
import http.cookiejar
import urllib.request
import urllib.parse
import urllib.error
import gzip
import zlib
import html as html_mod

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

SITE_NAME = "久久瑟瑟"
DEFAULT_HOST = "https://mvu-hfxk-ym3.hscwang8s10m1.cc"

CATS = [
    ("202", "麻豆传媒"),
    ("205", "天美传媒"),
    ("206", "果冻传媒"),
    ("207", "91制片厂"),
    ("208", "蜜桃传媒"),
    ("209", "精东影业"),
    ("210", "皇家华人"),
    ("223", "星空传媒"),
    ("301", "200GANA"),
    ("302", "300MIUM"),
    ("308", "300MAAN"),
    ("309", "300NTK"),
    ("313", "336KNB"),
    ("326", "MUDR"),
    ("329", "AARM"),
    ("345", "DVAJ"),
    ("401", "夢乃愛華"),
    ("402", "波多野结衣"),
    ("404", "河北彩花"),
    ("409", "桃乃木香奈"),
    ("412", "相澤南"),
    ("414", "Miru"),
    ("419", "木下日葵"),
    ("429", "明里紬"),
    ("501", "91沈先生"),
    ("502", "文轩探花"),
    ("503", "千人斩"),
    ("509", "李寻欢探花"),
    ("513", "酒店"),
    ("514", "小宝寻花"),
    ("515", "午夜寻花"),
    ("516", "91系列"),
]

PIC_MODE = "direct"
THROTTLE = 0.4
LOCAL_PROXY_BASE = "http://127.0.0.1:9978/proxy"


class Spider(BaseSpider):
    def __init__(self):
        super(Spider, self).__init__()
        self.site_url = DEFAULT_HOST
        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",
            "Referer": self.site_url + "/",
            "Connection": "keep-alive",
        }
        self.ssl_ctx = ssl.create_default_context()
        self.ssl_ctx.check_hostname = False
        self.ssl_ctx.verify_mode = ssl.CERT_NONE
        # CookieJar：播放页需要详情页种下的cookie
        self._cj = http.cookiejar.CookieJar()
        self._opener = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(self._cj),
            urllib.request.HTTPSHandler(context=self.ssl_ctx))
        self._throttle = THROTTLE
        self._last_req = 0.0

    def getName(self):
        return SITE_NAME

    def init(self, extend=""):
        try:
            import json
            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

    # ============ 网络层（带CookieJar） ============
    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, timeout=12, retries=2):
        import http.client
        gap = time.time() - self._last_req
        if gap < self._throttle:
            time.sleep(self._throttle - gap)
        self._last_req = time.time()
        req = urllib.request.Request(url, headers=self.headers, method="GET")
        last_err = ""
        for attempt in range(retries + 1):
            try:
                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 attempt < retries:
                    time.sleep(0.4)
        return {"success": False, "html": "", "error": last_err}

    def _fetch_html(self, url, must_contain=None, timeout=12):
        html_data = ""
        for _ in range(3):
            res = self._fetch(url, timeout=timeout)
            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):
        if not pic:
            return ""
        if PIC_MODE == "direct" or pic.startswith("http://127.0.0.1"):
            return pic
        return "%s?do=py&type=pic&url=%s" % (
            LOCAL_PROXY_BASE, urllib.parse.quote(pic, safe=""))

    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):
        """卡片：<a class="thumbnail" href="/voddetail/ID/" title="&#x..;(实体编码标题)">
           <img class="loadi" src="封面">
           封面兜底：style="--bg:url('封面')" """
        cards, seen = [], set()
        if not html_data:
            return cards
        for m in re.finditer(
                r'<a\s+class="thumbnail"\s+href="/voddetail/(\d+)/"[^>]*>',
                html_data):
            vid = m.group(1)
            if vid in seen:
                continue
            seen.add(vid)
            tag = m.group(0)
            title = ""
            tm = re.search(r'title="([^"]*)"', tag)
            if tm:
                title = self._clean(tm.group(1))
            if not title:
                # 兜底：卡片内 img alt 或后续文字
                seg2 = html_data[m.start():m.start()+2000]
                am = re.search(r'alt="([^"]{4,100})"', seg2)
                if am:
                    title = self._clean(am.group(1))
            # 同卡片内找封面：img src > style --bg
            seg = html_data[m.start():m.start()+1200]
            pic = ""
            pm = re.search(r'<img[^>]+src="([^"]+\.(?:jpg|jpeg|png|webp)[^"]*)"',
                           seg)
            if pm:
                pic = pm.group(1)
            if not pic:
                pm2 = re.search(r"--bg:url\('([^']+)'\)", seg)
                if pm2:
                    pic = pm2.group(1)
            cards.append({
                "vod_id": vid,
                "vod_name": title or vid,
                "vod_pic": self._pic_url(self._abs_url(pic)),
                "vod_remarks": "",
            })
        return cards

    # ============ 播放地址提取 ============
    def _extract_play_url(self, html_data):
        """player_data.url（斜杠转义）> m3u8 > mp4 > JS url:；过滤sample/test"""
        if not html_data:
            return ""
        # 1) player_data 的 url（本站主方式，\/转义）
        m = re.search(r'player_aaaa\s*=\s*\{[^}]*?"url"\s*:\s*"([^"]+)"',
                      html_data)
        if m:
            u = m.group(1).replace("\\/", "/").strip()
            if u.startswith("http") and self.isVideoFormat(u):
                return u
        # 2) 页面内 m3u8
        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
        # 3) mp4
        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
        # 4) JS url:
        m = re.search(r'url\s*:\s*["\']([^"\']+)["\']', html_data, re.I)
        if m:
            u = m.group(1).replace("\\/", "/").strip()
            if u.startswith("http") and "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 CATS],
                "filters": {}}

    def homeVideoContent(self):
        html_data = self._fetch_html(self.site_url + "/vodtype/202/",
                                     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/vodtype/%s/" % (self.site_url, tid)
        else:
            url = "%s/vodtype/%s/page/%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": "正片$/vodplay/%s-1-1/" % vid}
        try:
            html_data = self._fetch_html(
                "%s/voddetail/%s/" % (self.site_url, vid),
                must_contain="voddetail")
            # 标题：h1 > title首段
            tm = re.search(r"<h1[^>]*>(.*?)</h1>", html_data, re.S)
            if tm:
                t = self._clean(tm.group(1))
                if t:
                    vod["vod_name"] = t
            if vod["vod_name"] == vid:
                tm2 = re.search(r"<title>(.*?)</title>", html_data,
                                re.S | re.I)
                if tm2:
                    t = self._clean(tm2.group(1)).split("_")[0].strip()
                    if t:
                        vod["vod_name"] = t
            # 封面：首个 upload/vod 图片
            pic = ""
            pm = re.search(
                r'<img[^>]+src="(https?://[^"]*upload/vod[^"]*\.(?:jpg|jpeg|png|webp)[^"]*)"',
                html_data)
            if pm:
                pic = pm.group(1)
            if pic:
                vod["vod_pic"] = self._pic_url(pic)
            # 播放页直链（CookieJar已带cookie）
            vp_html = self._fetch_html(
                "%s/vodplay/%s-1-1/" % (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}
        # 播放页地址 -> 抓直链（带cookie）
        try:
            url = raw_id if raw_id.startswith("http") else \
                self.site_url + (raw_id if raw_id.startswith("/")
                                  else "/vodplay/%s-1-1/" % 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())
        url = "%s/vodsearch/-------------.html?wd=%s" % (
            self.site_url, kw)
        if pg > 1:
            url += "&page=%d" % 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

    r = sp.categoryContent("424", "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_full", pics == len(r["list"]) and pics > 0,
          "%d/%d" % (pics, len(r["list"])))
    titled = sum(1 for v in r["list"] if v["vod_name"] != v["vod_id"])
    check("titles", titled == len(r["list"]) and titled > 0,
          "%d/%d有标题" % (titled, len(r["list"])))

    h = sp.homeVideoContent()
    check("home", len(h["list"]) > 0, "%d条" % len(h["list"]))

    s = sp.searchContent("学生", False, "1")
    check("search", 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", v["vod_name"] != vid and has_m3u8
              and v["vod_pic"].startswith("http"),
              "%s | 封面%s | %s" % (
                  v["vod_name"][:30],
                  "有" if v["vod_pic"] else "无",
                  "直链" if has_m3u8 else v["vod_play_url"][:40]))
        if has_m3u8:
            ep = v["vod_play_url"].split("$", 1)[1]
            # 验证m3u8可访问
            import urllib.request as _ur
            try:
                rq = _ur.Request(ep, headers={
                    "User-Agent": sp.headers["User-Agent"],
                    "Referer": sp.site_url + "/"})
                with _ur.urlopen(rq, context=sp.ssl_ctx,
                                 timeout=10) as rp:
                    ok200 = rp.getcode() == 200
                    body = rp.read(200).decode("utf-8", errors="ignore")
                    is_m3u8 = "#EXTM3U" in body
            except Exception:
                ok200, is_m3u8 = False, False
            check("m3u8_live", ok200 and is_m3u8,
                  "HTTP%s" % ("200" if ok200 else "失败"))
            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:
            # parse=1兜底
            p = sp.playerContent("在线播放", v["vod_play_url"].split("$", 1)[1], [])
            check("player_fallback", p["parse"] == 1, "parse=1兜底")
    else:
        check("detail", False, "无列表跳过")

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