# -*- coding: utf-8 -*-
# TVBox Python 影视源：性爱十八式（d_tz_kk_e.xa18s3.sbs）融合风格版
# ============================================================
# 站点结构（2026-10-22 抓原始 HTML 实证，苹果CMS/MacCMS 模板）：
#  分类：/vodtype/{id}.html，翻页 /vodtype/{id}-{页}.html，每页16条，
#  页面有“共{N}条数据,当前{p}/{M}页”可算真实 total/pagecount
#  列表卡片：<li> 内缩略图链接 /vodplay/{id}-1-1.html + <img src>
#  明图封面（独立图床域名），标题在 <h5><a> 里，播放数在
#  span.video-grade 里
#  播放页与详情页同一页：/vodplay/{id}-1-1.html，页内脚本
#  player_aaaa JSON 的 url 字段即 m3u8 直链（encrypt=0），每次现抓
#  搜索：/vodsearch/{关键词}-------------.html（13个连字符），
#  第2页起为 {关键词}----------{页}---.html（10+页码+3）
#  站点有 cookie 验证墙：首次请求返 403 + Set-Cookie + JS 跳回本页，
#  带上 cookie 重发即放行——网络层手动存/带 cookie 并自动重发
import re
import time
import ssl
import json
import urllib.request
import urllib.parse
import urllib.error
import gzip
import zlib

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

SITE_NAME = "性爱十八式"
DEFAULT_HOST = "https://d_tz_kk_e.xa18s3.sbs"

CATS = [
    ("117", "视频一区"), ("121", "女同拉拉"), ("122", "网曝门"),
    ("123", "性感护士"), ("124", "瑜伽裤"), ("125", "经典视频"),
    ("126", "风情旗袍"), ("127", "小学妹"), ("128", "女优系列"),
    ("118", "视频二区"), ("129", "台湾辣妹"), ("132", "韩国女团"),
    ("133", "极品御姐"), ("134", "东南亚乱交"), ("135", "欺辱调教"),
    ("136", "剧情介绍"), ("137", "多人多P"), ("138", "91探花"),
    ("119", "视频三区"), ("139", "网红黑料"), ("140", "野外露出"),
    ("141", "欧美视频"), ("142", "萝莉少女"), ("143", "伦理影片"),
    ("144", "动漫精品"), ("145", "自拍偷拍"), ("146", "丝袜制服"),
    ("120", "视频四区"), ("147", "口交颜射"), ("148", "日本精品"),
    ("149", "Cosplay"), ("150", "精品视频"), ("151", "国产色情"),
    ("152", "美女主播"), ("153", "中文字幕"), ("154", "强奸乱伦"),
]

THROTTLE = 0.3


class Spider(BaseSpider):
    def __init__(self):
        super(Spider, self).__init__()
        self.site_url = DEFAULT_HOST
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Linux; Android 13) "
                          "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,en;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            "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
        self._cookies = {}

    def getName(self):
        return SITE_NAME

    def init(self, extend=""):
        # ext 兼容两种写法：纯网址字符串，或 {"host": "网址"} 的 JSON
        try:
            host = ""
            if isinstance(extend, dict):
                host = str(extend.get("host", "")).strip()
            elif extend and str(extend).strip():
                ext = str(extend).strip()
                if ext.startswith("{"):
                    host = str(json.loads(ext).get("host", "")).strip()
                elif ext.startswith("http"):
                    host = ext
            host = host.rstrip("/")
            if host:
                self.site_url = host
                self.headers["Referer"] = host + "/"
        except Exception:
            pass

    # ============ 网络层：手动cookie会话+验证墙重发+重试 ============
    def _store_cookies(self, hdrs):
        try:
            raw_list = []
            if hasattr(hdrs, "get_all"):
                raw_list = hdrs.get_all("Set-Cookie") or []
            else:
                one = hdrs.get("Set-Cookie")
                if one:
                    raw_list = [one]
            for raw in raw_list:
                pair = raw.split(";")[0].strip()
                if "=" in pair:
                    name, val = pair.split("=", 1)
                    self._cookies[name.strip()] = val.strip()
        except Exception:
            pass

    def _cookie_header(self):
        if not self._cookies:
            return ""
        return "; ".join("%s=%s" % kv for kv in self._cookies.items())

    @staticmethod
    def _decode_body(raw, enc=""):
        if not raw:
            return ""
        if isinstance(raw, str):
            return raw
        if raw[:2] == b"\x1f\x8b":
            try:
                raw = gzip.decompress(raw)
            except Exception:
                pass
        elif raw[:1] == b"\x78":
            try:
                raw = zlib.decompress(raw)
            except Exception:
                pass
        elif "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")

    @staticmethod
    def _is_challenge(status, text):
        # 验证墙特征：403 小页面 + JS 跳回本页
        if status == 403 and "window.location.href" in (text or ""):
            return True
        if status == 200 and len(text or "") < 300 \
                and "window.location.href" in (text or ""):
            return True
        return False

    def _fetch_once(self, url, timeout):
        headers = dict(self.headers)
        ck = self._cookie_header()
        if ck:
            headers["Cookie"] = ck
        req = urllib.request.Request(url, headers=headers, method="GET")
        try:
            with urllib.request.urlopen(req, context=self.ssl_ctx,
                                        timeout=timeout) as resp:
                self._store_cookies(resp.headers)
                raw = resp.read()
                enc = resp.headers.get("Content-Encoding", "").lower()
                return resp.status, self._decode_body(raw, enc)
        except urllib.error.HTTPError as e:
            try:
                self._store_cookies(e.headers)
                raw = e.read()
            except Exception:
                raw = b""
            return e.code, self._decode_body(raw)
        except Exception:
            return 0, ""

    def _fetch(self, url, timeout=12, retries=3):
        gap = time.time() - self._last_req
        if gap < self._throttle:
            time.sleep(self._throttle - gap)
        self._last_req = time.time()
        status, text = 0, ""
        for _ in range(retries + 1):
            status, text = self._fetch_once(url, timeout)
            if status == 200 and text and not self._is_challenge(status, text):
                return {"success": True, "html": text}
            if not self._is_challenge(status, text) and status not in (0, 403):
                break
            time.sleep(0.3)
        ok = status == 200 and bool(text) \
            and not self._is_challenge(status, text)
        return {"success": ok, "html": text if ok else ""}

    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.lstrip("/"))

    @staticmethod
    def _unescape(text):
        t = text.replace("&amp;", "&").replace("&lt;", "<") \
            .replace("&gt;", ">").replace("&quot;", '"') \
            .replace("&apos;", "'").replace("&#39;", "'") \
            .replace("&nbsp;", " ")

        def _num(m):
            try:
                return chr(int(m.group(1)))
            except Exception:
                return m.group(0)

        def _hex(m):
            try:
                return chr(int(m.group(1), 16))
            except Exception:
                return m.group(0)

        t = re.sub(r"&#x([0-9a-fA-F]+);", _hex, t)
        t = re.sub(r"&#(\d+);", _num, t)
        return t

    @staticmethod
    def _clean(text):
        if not text:
            return ""
        text = Spider._unescape(text)
        return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", text)).strip()

    @staticmethod
    def _attr(tag, name):
        if not tag:
            return ""
        m = re.search(name + r'\s*=\s*"([^"]*)"', tag, re.I)
        if m:
            return m.group(1).strip()
        m = re.search(name + r"\s*=\s*'([^']*)'", tag, re.I)
        if m:
            return m.group(1).strip()
        m = re.search(name + r"\s*=\s*([^\s>]+)", tag, re.I)
        return m.group(1).strip() if m else ""

    # ============ localProxy（封面为明图直连，一般用不上，保留兜底）====
    @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"
        if data[:6] in (b"GIF87a", b"GIF89a"):
            return "image/gif"
        return ""

    def localProxy(self, params):
        # 只返 3 段 [状态码, mime, bytes]
        try:
            if params.get("type") == "pic":
                url = params.get("url", "")
                if url:
                    headers = dict(self.headers)
                    ck = self._cookie_header()
                    if ck:
                        headers["Cookie"] = ck
                    req = urllib.request.Request(url, headers=headers)
                    with urllib.request.urlopen(
                            req, context=self.ssl_ctx, timeout=15) as resp:
                        raw = resp.read()
                    mime = self._img_mime(raw)
                    if mime:
                        return [200, mime, raw]
        except Exception:
            pass
        return [404, "text/plain; charset=utf-8", b""]

    # ============ 列表解析：按 <li> 切块，缩略图链接定位卡片 ============
    @staticmethod
    def _pic_ok(cand):
        if not cand:
            return False
        low = cand.lower()
        if low.startswith("data:") or low.startswith("blob:"):
            return False
        if "/upload/site/" in low or "/template/" in low:
            return False
        base = low.split("/")[-1].split("?")[0]
        for bad in ("logo", "favicon", "avatar", "loading",
                    "blank", "placeholder", "spinner"):
            if bad in base:
                return False
        return True

    def _pic_from_block(self, block):
        for m in re.finditer(r"<img\b[^>]*>", block, re.I | re.S):
            tag = m.group(0)
            for name in ("src", "data-src", "data-original",
                         "data-lazy-src", "srcset"):
                cand = self._attr(tag, name)
                if name == "srcset" and cand:
                    cand = cand.split(",")[0].strip().split(" ")[0]
                if cand and self._pic_ok(cand):
                    return self._abs_url(cand)
        return ""

    def _parse_vod_list(self, html_data):
        cards, order, by_id = [], [], {}
        if not html_data:
            return cards
        pat = re.compile(r"/vodplay/(\d+-\d+-\d+)\.html")
        chunks = re.split(r"<li\b", html_data)
        blocks = chunks if len(chunks) > 3 else [html_data]
        for block in blocks:
            m = pat.search(block)
            if not m:
                # 无 <li> 切块时退回整页逐链接扫描
                continue
            vid = m.group(1)
            if vid in by_id:
                continue
            vod = {"vod_id": vid, "vod_name": "", "vod_pic": "",
                   "vod_remarks": ""}
            tm = re.search(r"<h[45]\b[^>]*>\s*<a\b[^>]*>(.*?)</a>",
                           block, re.S | re.I)
            if tm and self._clean(tm.group(1)):
                vod["vod_name"] = self._clean(tm.group(1))
            if not vod["vod_name"]:
                am = re.search(
                    r'<a\b[^>]*href=["\'][^"\']*/vodplay/' + re.escape(vid)
                    + r'\.html["\'][^>]*>([^<]{2,120})</a>', block, re.S | re.I)
                if am and self._clean(am.group(1)):
                    vod["vod_name"] = self._clean(am.group(1))
            vod["vod_pic"] = self._pic_from_block(block)
            gm = re.search(r'class="[^"]*video-grade[^"]*"[^>]*>(.*?)</',
                           block, re.S | re.I)
            if gm and self._clean(gm.group(1)):
                vod["vod_remarks"] = self._clean(gm.group(1))
            else:
                dm = re.search(r"<p[^>]*>\s*(\d{4}-\d{2}-\d{2})\s*</p>",
                               block, re.I)
                if dm:
                    vod["vod_remarks"] = dm.group(1)
            by_id[vid] = vod
            order.append(vid)
        if not order:
            # 兜底：整页逐个链接取窗口解析
            for m in pat.finditer(html_data):
                vid = m.group(1)
                if vid in by_id:
                    continue
                seg = html_data[max(0, m.start() - 200):m.start() + 1200]
                by_id[vid] = {"vod_id": vid,
                              "vod_name": self._clean(
                                  self._title_fallback(seg)),
                              "vod_pic": self._pic_from_block(seg),
                              "vod_remarks": ""}
                order.append(vid)
        for vid in order:
            vod = by_id[vid]
            if not vod["vod_name"]:
                vod["vod_name"] = vid
            cards.append(vod)
        return cards

    @staticmethod
    def _title_fallback(seg):
        tm = re.search(r"<h[45]\b[^>]*>\s*<a\b[^>]*>(.*?)</a>",
                       seg, re.S | re.I)
        return tm.group(1) if tm else ""

    @staticmethod
    def _page_stats(html_data):
        total, pagecount = 0, 0
        tm = re.search(r"共\s*(\d+)\s*条数据", html_data or "")
        if tm:
            total = int(tm.group(1))
        pm = re.search(r"当前\s*\d+\s*/\s*(\d+)\s*页", html_data or "")
        if pm:
            pagecount = int(pm.group(1))
        return total, pagecount

    # ============ 播放地址：player_aaaa JSON ============
    def _player_data(self, html_data):
        if not html_data:
            return {}
        m = re.search(r"player_aaaa\s*=\s*(\{.*?\})\s*</script>",
                      html_data, re.S)
        if not m:
            m = re.search(r"player_aaaa\s*=\s*(\{.*?\})\s*;", html_data, re.S)
        if not m:
            return {}
        try:
            return json.loads(m.group(1))
        except Exception:
            return {}

    def _play_url_from(self, data):
        if not data:
            return ""
        url = str(data.get("url", "") or "").strip()
        if not url:
            return ""
        if str(data.get("encrypt", "0")) == "1":
            # MacCMS encrypt=1：url 经 escape/编码处理，还原一层
            try:
                dec = urllib.parse.unquote(url)
                if dec.startswith("http"):
                    url = dec
            except Exception:
                pass
        if url.startswith("http") and self.isVideoFormat(url):
            return url
        return url if url.startswith("http") else ""

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

    def homeVideoContent(self):
        html_data = self._fetch_html(self.site_url + "/",
                                     must_contain="/vodplay/")
        cards = self._parse_vod_list(html_data)
        return {"list": cards[: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().strip("/")
        if pg <= 1:
            url = "%s/vodtype/%s.html" % (self.site_url, tid)
        else:
            url = "%s/vodtype/%s-%d.html" % (self.site_url, tid, pg)
        html_data = self._fetch_html(url, must_contain="/vodplay/")
        cards = self._parse_vod_list(html_data)
        total, pagecount = self._page_stats(html_data)
        if not pagecount:
            pagecount = pg + 1 if len(cards) >= 16 else pg
        if not total:
            total = len(cards)
        return {"list": cards, "page": pg, "pagecount": pagecount,
                "limit": 16 if cards else 0, "total": total}

    def _play_id(self, vid):
        v = str(vid).strip()
        m = re.search(r"(\d+-\d+-\d+)", v)
        if m:
            return m.group(1)
        m = re.search(r"(\d+)", v)
        if m:
            return m.group(1) + "-1-1"
        return v

    def detailContent(self, ids):
        if not ids:
            return {"list": []}
        pid = self._play_id(ids[0])
        url = "%s/vodplay/%s.html" % (self.site_url, pid)
        vod = {"vod_id": pid, "vod_name": pid, "vod_pic": "",
               "vod_remarks": "", "vod_content": "",
               "vod_play_from": "在线播放",
               "vod_play_url": "正片$%s" % url}
        try:
            html_data = self._fetch_html(url, must_contain="player_aaaa")
            if not html_data:
                html_data = self._fetch_html(url)
            data = self._player_data(html_data)
            vdata = data.get("vod_data", {}) or {}
            name = self._clean(str(vdata.get("vod_name", "") or ""))
            if not name:
                tm = re.search(r"<title>(.*?)</title>", html_data,
                               re.S | re.I)
                if tm:
                    name = re.split(r"[-|_]", self._clean(tm.group(1)))[0].strip()
            if name:
                vod["vod_name"] = name
            for cv in self._parse_vod_list(html_data):
                if cv["vod_id"] == pid and cv["vod_pic"]:
                    vod["vod_pic"] = cv["vod_pic"]
                    break
            if not vod["vod_pic"]:
                vod["vod_pic"] = self._pic_from_block(html_data)
            play_url = self._play_url_from(data)
            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}
        pid = self._play_id(raw_id)
        return {"parse": 1,
                "url": "%s/vodplay/%s.html" % (self.site_url, pid),
                "header": header}

    def searchContent(self, key, quick, pg="1"):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        kw = str(key).strip()
        if not kw:
            return {"list": [], "page": pg, "pagecount": pg,
                    "limit": 0, "total": 0}
        kq = urllib.parse.quote(kw, safe="")
        if pg <= 1:
            suffix = "-" * 13
        else:
            suffix = "-" * 10 + str(pg) + "-" * 3
        url = "%s/vodsearch/%s%s.html" % (self.site_url, kq, suffix)
        html_data = self._fetch_html(url, must_contain="/vodplay/")
        cards = self._parse_vod_list(html_data)
        total, pagecount = self._page_stats(html_data)
        if not pagecount:
            pagecount = pg + 1 if len(cards) >= 16 else pg
        if not total:
            total = len(cards)
        return {"list": cards, "page": pg, "pagecount": pagecount,
                "limit": len(cards), "total": total}

    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 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"]) == len(CATS),
          "%d分类" % len(hc["class"]))

    r = sp.categoryContent("117", "1", None, None)
    check("category", len(r["list"]) > 0,
          "%d条 pagecount=%s total=%s" % (len(r["list"]), r["pagecount"],
                                          r["total"]))
    pics = sum(1 for v in r["list"] if v["vod_pic"].startswith("http"))
    check("covers", pics > 0, "%d/%d" % (pics, len(r["list"])))
    names = sum(1 for v in r["list"]
                if v["vod_name"] and v["vod_name"] != v["vod_id"])
    check("titles", names > 0, "%d/%d" % (names, len(r["list"])))

    r2 = sp.categoryContent("117", "2", None, None)
    ids1 = set(v["vod_id"] for v in r["list"])
    ids2 = set(v["vod_id"] for v in r2["list"])
    check("page2", len(r2["list"]) > 0 and not (ids1 & ids2),
          "%d条 与第1页重叠%d" % (len(r2["list"]), len(ids1 & ids2)))

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

    if r["list"]:
        vid = r["list"][0]["vod_id"]
        kw = "湿透"
        s = sp.searchContent(kw, False, "1")
        check("search", len(s["list"]) > 0,
              "关键词=%s %d条" % (kw, len(s["list"])))

        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 bool(v["vod_pic"]),
              "%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 ".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（把 FAIL 行发回即可）")
