# -*- coding: utf-8 -*-
# TVBox Python 影视源：หีหี69 (xn--69-6tia3cb.net) v1.0
# ============================================================
# 站点结构（2026-10-10 实测）：
#  WordPress 站，9 个分类：/category/{slug}/，翻页 /category/{slug}/page/{pg}/
#  首页翻页：/page/{pg}/
#  卡片：<a href="/{slug}/{id}/"> 内含 div.post-thumbnail（img data-src 封面，
#        data-src 懒加载，alt 标题）+ div.post-views span 播放量 + h3 标题
#  详情：/{slug}/{id}/，og:title 标题（后缀" - หีหี69"需去掉），og:image 封面
#  播放链（三步）：
#    1. 详情页 iframe -> https://lumierecore.com/{uuid}?ref=...
#    2. GET https://lumierecore.com/player-config/v2/{uuid}.js
#       取 window.PLAYER_PROXY_SELECTION_URL（p2p 参数可省略）
#    3. POST {} 到该 API（Referer/Origin: https://lumierecore.com）
#       -> JSON.masterUrl 即 m3u8 直链（实测可直连）
#  搜索：/?s={kw}，翻页 /page/{pg}/?s={kw}
import sys
import ssl
import time
import json
import re
import urllib.request
import urllib.parse
from http.cookiejar import CookieJar

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


class Spider(BaseSpider):
    def __init__(self):
        self.site_url = "https://xn--6969-4jo4c.com"
        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": self.site_url + "/",
        }
        self.cookie_jar = CookieJar()
        self.opener = self._build_opener()
        # type_id 用 URL 编码后的 slug（ASCII 安全），直拼即可
        self.cats = [
            ("%e0%b8%84%e0%b8%a5%e0%b8%b4%e0%b8%9b%e0%b8%ab%e0%b8%a5%e0%b8%b8%e0%b8%94", "คลิปหลุด"),
            ("onlyfans", "Onlyfans"),
            ("mlive", "Mlive"),
            ("thlive", "THLive"),
            ("jav", "JAV"),
            ("xxx", "xxx"),
            ("%e0%b8%ab%e0%b8%99%e0%b8%b1%e0%b8%87%e0%b9%82%e0%b8%9b%e0%b9%8a%e0%b9%84%e0%b8%97%e0%b8%a2", "หนังโป๊ไทย"),
            ("%e0%b9%80%e0%b8%ad%e0%b8%a7%e0%b8%b5%e0%b8%88%e0%b8%b5%e0%b8%99", "หนังเอวีจีน"),
            ("%e0%b8%ab%e0%b9%89%e0%b8%ad%e0%b8%87%e0%b9%80%e0%b8%8a%e0%b8%b7%e0%b8%ad%e0%b8%94", "ห้องเชือด"),
        ]
        self._throttle = 0.5
        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 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

    def getName(self):
        return "หีหี69"

    # ============ 网络层 ============
    def _decode(self, raw, enc=""):
        import gzip, zlib
        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=15, retries=2, referer=None, data=None, extra_headers=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
        if extra_headers:
            headers.update(extra_headers)
        last_err = ""
        for i in range(retries + 1):
            try:
                req = urllib.request.Request(url, data=data, headers=headers)
                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(raw, enc)}
            except http.client.IncompleteRead as e:
                if e.partial:
                    return {"success": True, "html": self._decode(e.partial)}
                last_err = str(e)
            except Exception as e:
                last_err = str(e)
                if i < retries:
                    time.sleep(0.5)
        return {"success": False, "html": "", "error": last_err}

    def _fetch_html(self, url, must_contain=None, referer=None):
        html_data = ""
        for _ in range(3):
            res = self._fetch(url, 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

    @staticmethod
    def _clean(t):
        import html as hm
        if not t:
            return ""
        return re.sub(r"<[^>]+>", "", hm.unescape(t)).strip()

    def _abs(self, u):
        if not u:
            return ""
        u = u.strip()
        if u.startswith("http"):
            return u
        if u.startswith("//"):
            return "https:" + u
        return urllib.parse.urljoin(self.site_url + "/", u)

    # ============ 封面代理（防盗链兜底） ============
    @staticmethod
    def _mime(d):
        if not d or len(d) < 12:
            return ""
        if d[:2] == b"\xff\xd8":
            return "image/jpeg"
        if d[:8] == b"\x89PNG\r\n\x1a\n":
            return "image/png"
        if d[:4] == b"RIFF" and d[8:12] == b"WEBP":
            return "image/webp"
        return ""

    def localProxy(self, params):
        try:
            if params.get("type") == "pic":
                url = params.get("url", "")
                if url:
                    req = urllib.request.Request(url, headers={
                        "User-Agent": self.headers["User-Agent"],
                        "Referer": self.site_url + "/"})
                    with self.opener.open(req, timeout=15) as r:
                        raw = r.read()
                    mime = self._mime(raw) or "image/jpeg"
                    return [200, mime, raw, ""]
        except Exception:
            pass
        return [200, "text/plain;charset=utf-8", ""]

    # ============ 列表解析 ============
    def _is_post_url(self, url):
        if not url or not url.startswith(self.site_url):
            return False
        if "/category/" in url or "/tag/" in url:
            return False
        return bool(re.match(r"https?://[^/]+/[^/]+/\d+/?$", url))

    def _parse_vod_list(self, html_data):
        cards, seen = [], set()
        if not html_data:
            return cards
        for m in re.finditer(
                r'<a[^>]*href="([^"]+)"[^>]*>(.*?)</a>',
                html_data, re.S):
            url, body = m.group(1), m.group(2)
            if "post-thumbnail" not in body or not self._is_post_url(url):
                continue
            vid = url.rstrip("/").rsplit("/", 1)[-1]
            if vid in seen:
                continue
            seen.add(vid)
            # 标题：h3 优先，img alt 兜底
            title = ""
            hm = re.search(r"<h3[^>]*>(.*?)</h3>", body, re.S)
            if hm:
                title = self._clean(hm.group(1))
            if not title:
                am = re.search(r'<img[^>]+alt="([^"]+)"', body)
                if am:
                    title = am.group(1).strip()
            # 封面：data-src 懒加载优先
            pic = ""
            pm = re.search(r'data-src="([^"]+)"', body)
            if not pm:
                pm = re.search(r'<img[^>]+src="(?!data:)([^"]+)"', body)
            if pm:
                pic = pm.group(1).strip()
            # 备注：播放量
            remark = ""
            rm = re.search(r'post-views.*?<span[^>]*>([^<]+)</span>', body, re.S)
            if rm:
                remark = rm.group(1).strip()
            cards.append({
                "vod_id": url,
                "vod_name": title or vid,
                "vod_pic": self._abs(pic),
                "vod_remarks": remark,
            })
        return cards

    # ============ 播放链：iframe -> config -> POST api -> m3u8 ============
    def _resolve_m3u8(self, post_url):
        """三步拿 m3u8，失败返回空串"""
        try:
            html_data = self._fetch_html(post_url, must_contain="lumierecore",
                                         referer=self.site_url + "/")
            if not html_data:
                return ""
            um = re.search(r"https?://lumierecore\.com/([0-9a-f-]{36})", html_data)
            if not um:
                return ""
            uuid = um.group(1)
            cfg_url = "https://lumierecore.com/player-config/v2/%s.js" % uuid
            res = self._fetch(cfg_url, referer="https://lumierecore.com/%s" % uuid)
            if not res.get("success"):
                return ""
            sm = re.search(r'PLAYER_PROXY_SELECTION_URL\s*=\s*"((?:[^"\\]|\\.)*)"',
                           res["html"])
            if not sm:
                return ""
            api_url = sm.group(1).replace("\\/", "/")
            res2 = self._fetch(api_url, data=b"{}",
                               extra_headers={
                                   "Referer": "https://lumierecore.com/",
                                   "Origin": "https://lumierecore.com",
                                   "Content-Type": "application/json"})
            if not res2.get("success"):
                return ""
            j = json.loads(res2["html"])
            return (j.get("masterUrl") or "").strip()
        except Exception:
            return ""

    @staticmethod
    def _post_title(html_data):
        m = re.search(r'property="og:title"[^>]*content="([^"]+)"', html_data)
        title = m.group(1).strip() if m else ""
        if not title:
            m = re.search(r"<title>(.*?)</title>", html_data, re.S | re.I)
            if m:
                title = m.group(1).strip()
        # 去掉 " - หีหี69..." 站名后缀
        title = re.sub(r"\s*[-–—]\s*หีหี69.*$", "", title).strip()
        return title

    # ============ 标准接口 ============
    def homeContent(self, filter):
        return {"class": [{"type_id": t, "type_name": n} for t, n in self.cats],
                "filters": {}}

    def homeVideoContent(self):
        html_data = self._fetch_html(self.site_url + "/", must_contain="post-thumbnail")
        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/category/%s/" % (self.site_url, tid)
        else:
            url = "%s/category/%s/page/%d/" % (self.site_url, tid, pg)
        html_data = self._fetch_html(url, must_contain="post-thumbnail")
        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):
        raw = ids[0] if isinstance(ids, list) and ids else str(ids)
        vod = {"vod_id": raw, "vod_name": raw, "vod_pic": "",
               "vod_remarks": "", "vod_content": "",
               "vod_play_from": "在线播放", "vod_play_url": ""}
        if not raw:
            return {"list": [vod]}
        post_url = raw if raw.startswith("http") else self._abs(raw)
        try:
            html_data = self._fetch_html(post_url, must_contain="lumierecore",
                                         referer=self.site_url + "/")
            if not html_data:
                return {"list": [vod]}
            title = self._post_title(html_data)
            if title:
                vod["vod_name"] = title
                vod["vod_content"] = title
            pm = re.search(r'property="og:image"[^>]*content="([^"]+)"', html_data)
            if pm:
                vod["vod_pic"] = self._abs(pm.group(1))
            m3u8 = self._resolve_m3u8(post_url)
            if m3u8:
                vod["vod_play_url"] = "正片$%s" % m3u8
            else:
                vod["vod_play_url"] = "正片$%s" % post_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": "https://lumierecore.com/"}
        if raw_id.startswith("http") and self.isVideoFormat(raw_id):
            return {"parse": 0, "url": raw_id, "header": header}
        # 帖子页：再走一遍解析链
        try:
            post_url = raw_id if raw_id.startswith("http") else self._abs(raw_id)
            m3u8 = self._resolve_m3u8(post_url)
            if m3u8:
                return {"parse": 0, "url": m3u8, "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())
        if pg <= 1:
            url = "%s/?s=%s" % (self.site_url, kw)
        else:
            url = "%s/page/%d/?s=%s" % (self.site_url, pg, kw)
        html_data = self._fetch_html(url, must_contain="post-thumbnail")
        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 or u.endswith(".mp4")

    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

    import ast as _ast
    _ast.parse(open(__file__, encoding="utf-8").read())
    check("syntax", True)

    hc = sp.homeContent(True)
    check("homeContent", len(hc["class"]) == 9, "%d分类" % len(hc["class"]))

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

    r2 = sp.categoryContent("onlyfans", "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条" % len(r2["list"]))

    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"]:
        post_url = r["list"][0]["vod_id"]
        d = sp.detailContent([post_url])
        v = d["list"][0]
        has_m3u8 = ".m3u8" in v["vod_play_url"]
        check("detail", bool(v["vod_name"]) and has_m3u8,
              "%s... m3u8=%s" % (v["vod_name"][:30], has_m3u8))
        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"][:80])

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