# -*- coding: utf-8 -*-
# TVBox Python 影视源：5x5x影院（jwy35r2.vip）v2.0 融合版
# ============================================================
# 融合 16 个成熟源的写法：
#  [学1-10] localProxy 返回 [200,mime,data,""]；playerContent 极简无playUrl；
#           isVideoFormat 只判m3u8；详情页预抓直链；block切块解析；
#           must_contain 内容校验；3次重试+IncompleteRead恢复
#  [学11-16] 分类筛选器结构（子分类+排序）；播放地址四层兜底；
#           sample/test预览过滤；封面URL推导m3u8；total:9999
# 站点结构（2026-10-08 实测）：
#  首页推荐：/json/recommend/rmd_{1-200}.json
#  分类：/category/{id}/，p2+ /category/{id}/{pg}/（1=大陆 2=日韩 3=欧美 4=动画 5=三级）
#  卡片：<a href=/vd/{id}/ class="card group">，data-src封面，alt/标题
#  详情：/vd/{id}/，data-m3u8=直链，data-poster=封面，<title>=标题
#  搜索：/api/search/video?keyword={kw}&page={pg}
import re
import time
import ssl
import json
import random
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 = "5x5x影院"
DEFAULT_HOST = "https://www.jwy35r2.vip"
IMG_CDN = "https://jhfduadgiyhas.com:1443/"

CATS = [
    ("1", "大陆"),
    ("2", "日韩"),
    ("3", "欧美"),
    ("4", "动画"),
    ("5", "三级"),
]

# 筛选器（站点暂无排序接口，结构预留，通用模板用）
SORT_VALUES = [
    {"n": "最近更新", "v": "time"},
    {"n": "最多播放", "v": "hits"},
]
FILTERS = {
    "1": [{"key": "by", "name": "排序", "value": SORT_VALUES}],
    "2": [{"key": "by", "name": "排序", "value": SORT_VALUES}],
    "3": [{"key": "by", "name": "排序", "value": SORT_VALUES}],
    "4": [{"key": "by", "name": "排序", "value": SORT_VALUES}],
    "5": [{"key": "by", "name": "排序", "value": SORT_VALUES}],
}

PIC_MODE = "direct"
THROTTLE = 0.3
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 (Linux; Android 12) AppleWebKit/537.36 "
                          "(KHTML, like Gecko) Chrome/120.0.0.0 Mobile "
                          "Safari/537.36",
            "Accept": "text/html,application/xhtml+xml,application/xml;"
                      "q=0.9,*/*;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
        self._throttle = THROTTLE
        self._last_req = 0.0

    def getName(self):
        return SITE_NAME

    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

    # ============ 网络层：重试+partial恢复+内容校验 ============
    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 urllib.request.urlopen(req, context=self.ssl_ctx,
                                            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 _fetch_json(self, url, timeout=12):
        try:
            return json.loads(self._fetch_html(url, timeout=timeout))
        except Exception:
            return None

    def _abs_img(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(IMG_CDN, url.lstrip("/"))

    @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 urllib.request.urlopen(req, context=self.ssl_ctx,
                                            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):
        cards, seen = [], set()
        if not html_data:
            return cards
        for m in re.finditer(
                r'<a\s+href=/vd/(\d+)/\s+class="card group">(.*?)</a>',
                html_data, re.S):
            vid, body = m.group(1), m.group(2)
            if vid in seen:
                continue
            seen.add(vid)
            # 标题：alt > card-title
            title = ""
            am = re.search(r'alt=([^>]*?)\s+decoding=', body)
            if am:
                title = am.group(1).strip().strip('"').strip("'")
            if not title:
                tm = re.search(r'class=card-title>([^<]+)<', body)
                if tm:
                    title = tm.group(1).strip()
            # 封面：data-src > src（过滤占位图）
            pic = ""
            for pat in (r'data-src=(\S+?)(?:\s|>)',
                        r'data-original=(\S+?)(?:\s|>)',
                        r'src="([^"]+)"'):
                pm = re.search(pat, body)
                if pm:
                    cand = pm.group(1).strip().strip('"').strip("'")
                    if cand and not cand.startswith("data:") \
                            and "placeholder" not in cand.lower() \
                            and "loading" not in cand.lower():
                        pic = cand
                        break
            cards.append({
                "vod_id": vid,
                "vod_name": self._clean(title) or vid,
                "vod_pic": self._pic_url(self._abs_img(pic)),
                "vod_remarks": "",
            })
        # 兜底：裸 <a> 扫描
        if not cards:
            for m in re.finditer(r'href=/vd/(\d+)/[^>]*>([^<>]{4,80})</a>',
                                 html_data, re.S):
                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 _parse_json_list(self, data):
        cards = []
        if not isinstance(data, dict):
            return cards
        for it in data.get("list", []):
            vid = str(it.get("id", "")).strip()
            if not vid:
                continue
            cards.append({
                "vod_id": vid,
                "vod_name": self._clean(str(it.get("title", ""))) or vid,
                "vod_pic": self._pic_url(self._abs_img(
                    str(it.get("litpic", "")))),
                "vod_remarks": str(it.get("typename", "")),
            })
        return cards

    # ============ 播放地址四层兜底 ============
    def _extract_play_url(self, html_data, pic=""):
        """m3u8 > mp4 > JS url: > 封面推导；过滤 sample/test 预览"""
        # 封面推导不依赖页面，先处理
        if not html_data:
            if pic:
                inferred = re.sub(r"poster\d*\.(?:webp|jpg|png|jpeg)",
                                  "index.m3u8", pic)
                if inferred != pic and self.isVideoFormat(inferred):
                    return inferred
            return ""
        # 1) data-m3u8 属性（本站主方式）
        m = re.search(r"data-m3u8=(\S+?)(?:\s|>)", html_data)
        if m:
            u = m.group(1).strip().strip('"').strip("'")
            if self.isVideoFormat(u):
                return u
        # 2) 页面内 m3u8
        for mm in re.finditer(
                r'["\'](https?://[^"\']+\.m3u8[^"\']*)["\']',
                html_data, re.I):
            u = mm.group(1)
            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)
            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).strip()
            if u.startswith("http") and "sample" not in u \
                    and "test" not in u:
                return u
        # 5) 封面推导：poster.jpg -> index.m3u8
        if pic:
            inferred = re.sub(r"poster\d*\.(?:webp|jpg|png|jpeg)",
                              "index.m3u8", pic)
            if inferred != pic and self.isVideoFormat(inferred):
                return inferred
        return ""

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

    def homeVideoContent(self):
        try:
            n = random.randint(1, 200)
            data = self._fetch_json(
                "%s/json/recommend/rmd_%d.json" % (self.site_url, n))
            cards = self._parse_json_list(data)
            if cards:
                return {"list": cards[:20]}
        except Exception:
            pass
        return {"list": []}

    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 isinstance(extend, dict) and extend.get("by"):
            pass
        if pg <= 1:
            url = "%s/category/%s/" % (self.site_url, tid)
        else:
            url = "%s/category/%s/%d/" % (self.site_url, tid, pg)
        html_data = self._fetch_html(url, must_contain="/vd/")
        cards = self._parse_vod_list(html_data)
        total, per_page = 0, len(cards) if cards else 20
        m = re.search(r"共\s*(\d+)\s*个视频", html_data)
        if m:
            total = int(m.group(1))
        pagecount = (total + per_page - 1) // per_page \
            if total and per_page else \
            (pg + 1 if len(cards) >= 20 else pg)
        return {"list": cards, "page": pg, "pagecount": pagecount,
                "limit": len(cards), "total": total}

    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": "正片$/vd/%s/" % vid}
        try:
            html_data = self._fetch_html(
                "%s/vd/%s/" % (self.site_url, vid),
                must_contain="player-wrap")
            tm = re.search(r"<title>(.*?)</title>", html_data, re.S | re.I)
            if tm:
                t = self._clean(tm.group(1)).split("-")[0].strip()
                if t:
                    vod["vod_name"] = t
            pm = re.search(r"data-poster=(\S+?)(?:\s|>)", html_data)
            pic = ""
            if pm:
                pic = pm.group(1).strip().strip('"').strip("'")
                vod["vod_pic"] = self._pic_url(self._abs_img(pic))
            # 四层兜底抓直链
            play_url = self._extract_play_url(html_data, pic)
            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}
        return {"parse": 1, "url": raw_id if raw_id.startswith("http")
                else self.site_url + "/vd/%s/" % re.sub(r"\D", "", 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/api/search/video?keyword=%s&page=%d" % (
            self.site_url, kw, pg)
        data = self._fetch_json(url)
        if not data or data.get("code") != 0:
            return {"list": [], "page": pg, "pagecount": pg,
                    "limit": 0, "total": 0}
        d = data.get("data", {})
        cards = self._parse_json_list(d)
        return {"list": cards, "page": pg,
                "pagecount": d.get("total_pages") or pg,
                "limit": len(cards), "total": d.get("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"]) == 5 and "filters" in hc
          and "1" in hc["filters"], "%d分类+筛选器" % len(hc["class"]))

    r = sp.categoryContent("1", "1", None, None)
    check("category", 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("covers_full", pics == len(r["list"]) and pics > 0,
          "%d/%d" % (pics, len(r["list"])))

    r2 = sp.categoryContent("1", "2", None, None)
    ids1 = {v["vod_id"] for v in r["list"]}
    check("page2", len(r2["list"]) > 0, "%d条" % len(r2["list"]))

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

    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 has_m3u8 and v["vod_pic"].startswith("http"),
              "%s | 封面%s" % (v["vod_name"][:25],
                               "有" 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 p["url"].endswith(".m3u8")
                  and isinstance(p.get("header"), dict)
                  and "playUrl" not in p, p["url"][:70])
        # 兜底链测试
        u = sp._extract_play_url('var x="https://a.com/v.mp4";', "")
        check("fallback_mp4", u.endswith(".mp4"), u[:40])
        u2 = sp._extract_play_url("", "https://cdn/p/poster.jpg")
        check("fallback_infer", u2.endswith("index.m3u8"), u2[:40])
        u3 = sp._extract_play_url('var x="https://a.com/sample.m3u8";', "")
        check("filter_sample", u3 == "", "已过滤预览")
    else:
        check("detail", False, "无列表跳过")

    # localProxy 格式
    sp._fetch_bytes = lambda url, timeout=15, retries=3: b"\xff\xd8" + b"\x00" * 20
    res = sp.localProxy({"do": "py", "type": "pic", "url": "https://x/1.jpg"})
    check("localProxy", res[0] == 200 and res[3] == "", "%s %s" % (res[1], type(res[3]).__name__))

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