# -*- coding: utf-8 -*-
# TVBox Python 影视源：SexAV（xbow-wouq-wisx.sexav-108.com）v1.0
# ============================================================
# 站点结构（2026-10-08 实测）：
#  首页：/ssss/?link=nbo-levr90.2026vvipmega.buzz
#  分类：/t/{id}/，p2+ /t/{id}-{pg}/
#  卡片：<a href="/voddetail/{id}/" title="..." class="img-box"><img src="封面">
#  详情：/voddetail/{id}/
#  播放页：/v/{id}/ -> "url":"https:\/\/cdn\/..\/index.m3u8"（转义斜杠）
#  搜索：/s/wd/{kw}/
# 注意：需 Windows UA + Referer
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 = "SexAV"
DEFAULT_HOST = "https://xbow-wouq-wisx.sexav-108.com"

CATS = [
    ("163", "国产视频"),
    ("232", "网曝黑料"),
    ("236", "主播大秀"),
    ("233", "AV解说"),
    ("48", "国产自拍"),
    ("231", "抖阴视频"),
    ("2", "国产传媒"),
    ("1", "日本有码"),
    ("5", "日本无码"),
    ("13", "中文字幕"),
]

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):
        cards, seen = [], set()
        if not html_data:
            return cards
        # 卡片：<a href="/voddetail/ID/" title="标题" class="img-box"><img src="封面">
        for m in re.finditer(
                r'<a\s+href="/voddetail/(\d+)/"[^>]*title="([^"]+)"',
                html_data):
            vid, title = m.group(1), m.group(2).strip()
            if vid in seen:
                continue
            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)
            seen.add(vid)
            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+)/"', html_data):
                vid = m.group(1)
                if vid not in seen:
                    seen.add(vid)
                    cards.append({"vod_id": vid, "vod_name": vid,
                                  "vod_pic": "", "vod_remarks": ""})
        return cards

    # ============ 播放地址提取 ============
    def _extract_play_url(self, html_data):
        """m3u8 > mp4 > JS url；处理转义斜杠；过滤 sample/test"""
        if not html_data:
            return ""
        html_data = html_data.replace("\\/", "/")
        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
        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
        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
        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 + "/t/163/",
                                     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")
            # 标题：h1
            tm = re.search(r"<h1[^>]*>([^<>]+)</h1>", html_data)
            if tm:
                vod["vod_name"] = self._clean(tm.group(1))
            else:
                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 and "详情" not in t:
                        vod["vod_name"] = t
            # 封面：detail-image-wrapper
            pic = ""
            pm = re.search(
                r'detail-image-wrapper[^>]*>\s*<img[^>]+src="([^"]+)"',
                html_data)
            if pm:
                pic = pm.group(1)
            if pic:
                vod["vod_pic"] = self._pic_url(self._abs_url(pic))
            # 播放页：/v/{id}/
            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)
            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}
        # 播放页地址 -> 抓直链（带cookie）
        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())
        url = "%s/s/wd/%s/" % (self.site_url, kw)
        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")
