# -*- coding: utf-8 -*-
# TVBox Python 影视源：少妇AV（wap.sfav8.cc）v1.0
# ============================================================
# 站点结构（2026-10-08 实测，苹果CMS index.php路由）：
#  首页：/rukou/（移动端模板）
#  分类：/rukou/index.php/vod/type/id/{id}.html
#  翻页：/rukou/index.php/vod/type/id/{id}/page/{pg}.html
#  卡片：div.vod > .vod-img a[href=/detail/] img[data-original] + .vod-txt a（标题）
#  详情：/rukou/index.php/vod/detail/id/{id}.html
#  播放页：/rukou/index.php/vod/play/id/{id}/sid/1/nid/1.html
#  直链：player_aaaa.url（encrypt:0，明文m3u8）
#  搜索：/rukou/index.php/vod/search/wd/{kw}.html
import sys
import ssl
import time
import json
import re
import urllib.request
import urllib.parse
from http.cookiejar import CookieJar
import gzip
import zlib
import html as html_mod

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


class Spider(BaseSpider):
    def __init__(self):
        self.site_url = "https://wap.sfav8.cc"
        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://wap.sfav8.cc/rukou/",
        }
        self.cookie_jar = CookieJar()
        self.opener = self._build_opener()
        self.cats = [
            ("119", "斯卡资源"), ("302", "玉兔资源"), ("328", "黄瓜资源"),
            ("206", "冷库资源"), ("244", "老5资源"), ("267", "少妇资源"),
            ("332", "AI短剧"), ("124", "日本无码"), ("273", "网曝黑料"),
        ]
        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 "少妇AV"

    def init(self, extend=""):
        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, referer=None):
        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
        req = urllib.request.Request(url, headers=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, 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 + "/rukou/"})
        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 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
        # 主模式：div.vod 切块
        for m in re.finditer(
                r'<div class="vod">(.*?)</div>\s*</div>', html_data, re.S):
            body = m.group(1)
            vm = re.search(
                r'href="(/rukou/index\.php/vod/detail/id/(\d+)\.html)"', body)
            if not vm:
                continue
            vid = vm.group(2)
            if vid in seen:
                continue
            seen.add(vid)
            # 封面：data-original > src（过滤占位图）
            pic = ""
            for pat in (r'data-original="([^"]+)"', r'src="([^"]+)"'):
                pm = re.search(pat, body)
                if pm:
                    cand = pm.group(1).strip()
                    if cand and "load_x1" not in cand \
                            and not cand.startswith("data:"):
                        pic = cand
                        break
            # 标题：.vod-txt a
            title = ""
            tm = re.search(
                r'class="vod-txt"[^>]*>\s*<a[^>]*>([^<]+)</a>', body)
            if tm:
                title = tm.group(1).strip()
            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="(/rukou/index\.php/vod/detail/id/(\d+)\.html)"[^>]*>([^<>]{4,80})</a>',
                    html_data):
                vid, title = m.group(2), m.group(3).strip()
                if vid not in seen and title:
                    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):
        """player_aaaa.url > m3u8 > mp4 > JS url:；过滤 sample/test"""
        if not html_data:
            return ""
        # 1) player_aaaa.url（本站主方式）
        m = re.search(r'var\s+player_aaaa\s*=\s*(\{.*?\});?\s*</script>',
                      html_data, re.S)
        if m:
            try:
                d = json.loads(m.group(1))
                u = str(d.get("url", "")).strip()
                if u and self.isVideoFormat(u):
                    return u
            except Exception:
                pass
        # 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
        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 + "/rukou/index.php/label/new.html",
            must_contain="vod/detail")
        if not html_data or "vod/detail" not in html_data:
            html_data = self._fetch_html(
                self.site_url + "/rukou/", must_contain="vod/detail")
        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()
        base = "%s/rukou/index.php/vod/type/id/%s" % (self.site_url, tid)
        if pg <= 1:
            url = base + ".html"
        else:
            url = "%s/page/%d.html" % (base, pg)
        html_data = self._fetch_html(url, must_contain="vod/detail")
        cards = self._parse_vod_list(html_data)
        return {"list": cards, "page": pg,
                "pagecount": pg + 1 if len(cards) >= 10 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": "正片$%s" % vid}
        try:
            durl = "%s/rukou/index.php/vod/detail/id/%s.html" % (
                self.site_url, vid)
            html_data = self._fetch_html(durl, must_contain="vod/play")
            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-original="([^"]+)"', html_data)
            if pm:
                vod["vod_pic"] = self._abs_url(pm.group(1))
            # 播放页链接
            pm2 = re.search(
                r'href="(/rukou/index\.php/vod/play/id/%s/sid/1/nid/1\.html)"'
                % re.escape(vid), html_data)
            if not pm2:
                pm2 = re.search(
                    r'href="(/rukou/index\.php/vod/play/id/\d+/sid/\d+/nid/\d+\.html)"',
                    html_data)
            play_page = pm2.group(1) if pm2 else \
                "/rukou/index.php/vod/play/id/%s/sid/1/nid/1.html" % 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 + "/rukou/"}
        if raw_id.startswith("http") and self.isVideoFormat(raw_id):
            return {"parse": 0, "url": raw_id, "header": header}
        # 播放页地址 -> 抓直链
        try:
            if raw_id.startswith("/"):
                url = self.site_url + raw_id
            elif raw_id.startswith("http"):
                url = raw_id
            else:
                url = "%s/rukou/index.php/vod/play/id/%s/sid/1/nid/1.html" % (
                    self.site_url, 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())
        base = "%s/rukou/index.php/vod/search/wd/%s" % (self.site_url, kw)
        if pg <= 1:
            url = base + ".html"
        else:
            url = "%s/page/%d.html" % (base, 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) >= 10 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"]) == 9, "%d分类" % len(hc["class"]))

    r = sp.categoryContent("302", "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 v["vod_name"] != v["vod_id"])
    check("titles", titles == len(r["list"]),
          "%d/%d" % (titles, len(r["list"])))

    r2 = sp.categoryContent("302", "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 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])
            # m3u8 有效性
            import urllib.request as _ur
            try:
                rq = _ur.Request(p["url"], headers={
                    "User-Agent": "Mozilla/5.0"})
                with _ur.urlopen(rq, timeout=10) as rp:
                    head = rp.read(100).decode("utf-8", errors="ignore")
                check("m3u8_live", head.startswith("#EXTM3U"),
                      head.split("\n")[0])
            except Exception as e:
                check("m3u8_live", False, str(e)[:60])
    else:
        check("detail", False, "无列表跳过")

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