# -*- coding: utf-8 -*-
# Chaturbate 直播源 (T4 Python Spider)
# 站点结构(实测 2026-10-24):
#   列表: 官方公开接口 GET /api/public/affiliates/onlinerooms/
#         ?wm=<联盟码>&client_ip=<IP>&format=json&limit=60&offset=<偏移>
#         支持 gender=f/m/c/t 与 tag=<标签> 过滤, count 为在线总数,
#         limit/offset 真分页(实测相邻页零重叠)。
#         wm 与 client_ip：2026-10-27 曾改为只走 extend 注入，实测
#         导致无码时“有分类没内容”，已按用户反馈恢复原版默认值；
#         仍可用 extend {"wm": "你的联盟码", "client_ip": "你的出口 IP"} 覆盖。
#         分类为 2026-10-24 实测内置表，复测时确认是否为最新全集。
#   封面: 接口 image_url_360x270(thumb.live.mmcdn.com),
#         实测直出真 JPEG(ffd8ff), 无需代理。
#   详情: 免抓, vod_id 即房间名(username), 封面按
#         thumb.live.mmcdn.com/ri/<username>.jpg 拼(接口同款)。
#   播放: 房间页 https://chaturbate.com/<username>/ 内嵌
#         "hls_source"(整页 \\uXXXX 转义, 解转义后正则取),
#         为签名 LL-HLS 主清单(edge*.live.mmcdn.com, token 绑出口
#         IP, 必须现抓现解)。隐藏/私密/票房房页面无 hls_source,
#         退房间页 parse=1(站点行为, 非失败)。
#         注意: 签名令牌绑 IP, 我方探活断连是假阴性, 故解出
#         地址直接下发、不用探活否决。
#   搜索: 接口无用户名搜索参数; 拉大样本(500 条热门)按
#         用户名/显示名/标签本地过滤，只回第一页，非全站搜索。
import re
import ssl
import time
import json
import gzip
import http.client
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):

    API_PATH = "/api/public/affiliates/onlinerooms/"
    PAGE_SIZE = 60
    SHOW_LABEL = {
        "public": "直播中",
        "private": "私密秀",
        "group": "群组秀",
        "hidden": "隐藏秀",
        "away": "离开中",
        "ticket": "票房秀",
        "fanclub": "粉丝团秀",
    }

    def __init__(self):
        self.site_url = "https://chaturbate.com"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
            "Accept": "text/html,application/json,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "en-US,en;q=0.9,zh-CN;q=0.8",
            "Connection": "keep-alive",
        }
        self.cookie_jar = CookieJar()
        self.opener = self._build_opener()
        # 2026-10-27 修复：恢复原版默认值，保证不配 extend 也能出列表；
        # extend 传入 wm / client_ip 时仍优先覆盖（见 init）。
        self.wm = "tDEC8"
        self.client_ip = "1.2.3.4"
        self.cats = [
            ("all", "全部在线"),
            ("gender:f", "女性"),
            ("gender:m", "男性"),
            ("gender:c", "情侣"),
            ("gender:t", "跨性别"),
            ("tag:asian", "亚洲"),
            ("tag:latina", "拉丁"),
            ("tag:milf", "熟女"),
            ("tag:blonde", "金发"),
            ("tag:bigboobs", "巨乳"),
            ("tag:bigass", "美臀"),
            ("tag:smalltits", "小胸"),
            ("tag:petite", "娇小"),
            ("tag:natural", "天然"),
            ("tag:cute", "可爱"),
            ("tag:fit", "健身"),
            ("tag:skinny", "苗条"),
            ("tag:tease", "挑逗"),
            ("tag:feet", "美足"),
            ("tag:squirt", "潮吹"),
            ("tag:anal", "后庭"),
            ("tag:lovense", "互动玩具"),
            ("tag:fuckmachine", "炮机"),
            ("tag:new", "新人"),
        ]
        # 节流：接口限流保护，非全局无意义延时；命中限流时另走 _backoff 递增重试。
        self._throttle = 0.5
        self._last_req = 0.0
        self._retry = 2
        self._backoff = 0.5

    # ---------- 基础抓取(模板同款: 节流 + 重试 + gzip) ----------
    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 _decode_body(self, raw, resp=None):
        if not raw:
            return ""
        try:
            enc = ""
            if resp is not None:
                try:
                    enc = (resp.headers.get("Content-Encoding") or "").lower()
                except Exception:
                    enc = ""
            if "gzip" in enc or raw[:2] == b"\x1f\x8b":
                try:
                    raw = gzip.decompress(raw)
                except Exception:
                    pass
            return raw.decode("utf-8", errors="ignore")
        except Exception:
            return ""

    def _fetch(self, url, retry=None, referer=None):
        if retry is None:
            retry = getattr(self, "_retry", 2)
        headers = dict(self.headers)
        if referer:
            headers["Referer"] = referer
        gap = time.time() - self._last_req
        if gap < self._throttle:
            time.sleep(self._throttle - gap)
        self._last_req = time.time()
        for i in range(retry + 1):
            try:
                req = urllib.request.Request(url, headers=headers)
                with self.opener.open(req, timeout=15) as resp:
                    raw = resp.read()
                    if not raw:
                        raise IOError("empty response")
                    return {"success": True, "html": self._decode_body(raw, resp), "data": raw}
            except http.client.IncompleteRead as e:
                if e.partial:
                    return {"success": True, "html": self._decode_body(bytes(e.partial)), "data": bytes(e.partial)}
            except Exception:
                if i < retry:
                    time.sleep(getattr(self, "_backoff", 0.5) * (i + 1))
        return {"success": False, "html": "", "data": b""}

    def _fetch_bytes(self, url, timeout=15, referer=None):
        headers = dict(self.headers)
        if referer:
            headers["Referer"] = referer
        try:
            req = urllib.request.Request(url, headers=headers)
            with self.opener.open(req, timeout=timeout) as resp:
                raw = resp.read()
                enc = (resp.headers.get("Content-Encoding") or "").lower()
                if "gzip" in enc:
                    try:
                        raw = gzip.decompress(raw)
                    except Exception:
                        pass
                return raw
        except http.client.IncompleteRead as e:
            return bytes(e.partial or b"")
        except Exception:
            return b""

    # ---------- 接口层 ----------
    def _api_rooms(self, tid="", limit=60, offset=0):
        """拉一页在线房间, 返回 (results, count)。失败返回 ([], 0)。"""
        params = {
            "wm": self.wm,
            "client_ip": self.client_ip,
            "format": "json",
            "limit": int(limit),
            "offset": int(offset),
        }
        if tid and tid != "all":
            if tid.startswith("gender:"):
                params["gender"] = tid.split(":", 1)[1]
            elif tid.startswith("tag:"):
                params["tag"] = tid.split(":", 1)[1]
        url = self.site_url + self.API_PATH + "?" + urllib.parse.urlencode(params)
        # 出口链路偶发截断响应(半截 JSON), 解不出就整条重拉, 最多 3 次;
        # strict=False 容忍个别房间标题里的控制字符
        for attempt in range(3):
            res = self._fetch(url, retry=0)
            if res.get("success"):
                try:
                    data = json.loads(res["html"], strict=False)
                except Exception:
                    data = None
                if isinstance(data, dict) and not data.get("errors"):
                    return data.get("results") or [], int(data.get("count") or 0)
            if attempt < 2:
                time.sleep(0.8 * (attempt + 1))
        return [], 0

    def _room_to_vod(self, room):
        username = str(room.get("username") or "")
        if not username:
            return None
        show = str(room.get("current_show") or "public")
        label = self.SHOW_LABEL.get(show, show)
        users = room.get("num_users") or 0
        remarks = "%s · %s人" % (label, users)
        if room.get("is_hd"):
            remarks += " · HD"
        if room.get("is_new"):
            remarks += " · NEW"
        return {
            "vod_id": username,
            "vod_name": str(room.get("display_name") or username),
            "vod_pic": str(room.get("image_url_360x270") or room.get("image_url") or ""),
            "vod_remarks": remarks,
            "style": {"type": "rect", "ratio": 1.33},
        }

    # ---------- 壳接口 ----------
    def init(self, extend=""):
        cfg = {}
        if extend:
            try:
                cfg = json.loads(extend) if isinstance(extend, str) else dict(extend)
            except Exception:
                cfg = {}
        if isinstance(cfg, dict):
            if cfg.get("wm"):
                self.wm = str(cfg["wm"])
            if cfg.get("client_ip"):
                self.client_ip = str(cfg["client_ip"])
            if cfg.get("host"):
                self.site_url = str(cfg["host"]).rstrip("/")
        return ""

    def getName(self):
        return "Chaturbate"

    def homeContent(self, filter):
        return {
            "class": [{"type_id": tid, "type_name": name} for tid, name in self.cats],
            "filters": {},
        }

    def homeVideoContent(self):
        rooms, _ = self._api_rooms("all", limit=30, offset=0)
        return {"list": [v for v in (self._room_to_vod(r) for r in rooms) if v]}

    def categoryContent(self, tid, pg, filter, extend):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        offset = (pg - 1) * self.PAGE_SIZE
        rooms, count = self._api_rooms(str(tid or "all"), limit=self.PAGE_SIZE, offset=offset)
        cards = [v for v in (self._room_to_vod(r) for r in rooms) if v]
        pagecount = (count + self.PAGE_SIZE - 1) // self.PAGE_SIZE if count else pg
        if pagecount < pg:
            pagecount = pg
        return {
            "list": cards,
            "page": pg,
            "pagecount": pagecount,
            "limit": len(cards),
            "total": count,
        }

    def detailContent(self, ids):
        vid = str(ids[0]).strip() if ids else ""
        username = self._username_of(vid)
        if not username:
            return {"list": []}
        vod = {
            "vod_id": username,
            "vod_name": username,
            "vod_pic": "https://thumb.live.mmcdn.com/ri/%s.jpg" % username,
            "vod_remarks": "直播间",
            "vod_actor": "",
            "vod_director": "",
            "vod_content": "Chaturbate 直播间: %s" % username,
            "vod_play_from": "Chaturbate",
            "vod_play_url": "直播$%s" % username,
        }
        return {"list": [vod]}

    def playerContent(self, flag, id, vipFlags):
        username = self._username_of(str(id or ""))
        header = {
            "User-Agent": self.headers["User-Agent"],
            "Referer": self.site_url + "/",
        }
        room_url = "%s/%s/" % (self.site_url, username) if username else self.site_url + "/"
        if not username:
            return {"parse": 1, "url": room_url, "header": header}
        html = self._fetch(room_url, referer=self.site_url + "/").get("html", "")
        stream = self._extract_hls(html)
        if not stream and html:
            # 页面可能被链路截断(hls_source 在后半段), 整页重拉一次
            html = self._fetch(room_url, referer=self.site_url + "/").get("html", "")
            stream = self._extract_hls(html)
        if stream:
            # 签名流绑出口 IP: 解出即下发, 不拿探活结果否决(防假阴性误杀)
            return {"parse": 0, "url": stream, "header": header}
        # 隐藏/私密/票房房或已下播: 页面无公开流, 退房间页
        return {"parse": 1, "url": room_url, "header": header}

    def searchContent(self, key, quick, pg="1"):
        # 站方公开接口没有用户名搜索参数; 拉热门大样本(5 页 x 100)
        # 在本地按用户名/显示名/标签过滤。结果只回第一页，非全站搜索。
        kw = str(key or "").strip().lower()
        if not kw:
            return {"list": [], "page": 1, "pagecount": 1, "limit": 0, "total": 0}
        cards, seen = [], set()
        for off in (0, 100, 200, 300, 400):
            rooms, _ = self._api_rooms("all", limit=100, offset=off)
            if not rooms:
                break
            for r in rooms:
                uname = str(r.get("username") or "")
                if uname in seen:
                    continue
                seen.add(uname)
                hay = " ".join([
                    uname.lower(),
                    str(r.get("display_name") or "").lower(),
                    " ".join(str(t).lower() for t in (r.get("tags") or [])),
                ])
                if kw in hay:
                    v = self._room_to_vod(r)
                    if v:
                        cards.append(v)
        return {
            "list": cards,
            "page": 1,
            "pagecount": 1,
            "limit": len(cards),
            "total": len(cards),
        }

    # ---------- 播放解析 ----------
    @staticmethod
    def _username_of(raw):
        s = str(raw or "").strip()
        m = re.search(r"chaturbate\.com/([^/?#\s]+)", s)
        if m:
            return m.group(1)
        s = s.split("$")[-1].strip().strip("/")
        if re.fullmatch(r"[A-Za-z0-9_.\-]+", s or ""):
            return s
        return ""

    @staticmethod
    def _extract_hls(html):
        """房间页整页 \\uXXXX 转义: 先解转义再取 "hls_source"。"""
        if not html:
            return ""
        dec = html.replace("\\/", "/")
        try:
            dec = re.sub(r"\\u([0-9a-fA-F]{4})",
                         lambda m: chr(int(m.group(1), 16)), dec)
        except Exception:
            pass
        m = re.search(r'"hls_source"\s*:\s*"(https://[^"\\]+?\.m3u8[^"\\]*)"', dec)
        if m:
            return m.group(1)
        m = re.search(r'https://[^\s"\\]+?llhls\.m3u8[^\s"\\]*', dec)
        return m.group(0) if m else ""

    # ---------- 其他 ----------
    @staticmethod
    def _img_mime(raw):
        if not raw or len(raw) < 4:
            return ""
        if raw[:3] == b"\xff\xd8\xff":
            return "image/jpeg"
        if raw[:8] == b"\x89PNG\r\n\x1a\n":
            return "image/png"
        if raw[:6] in (b"GIF87a", b"GIF89a"):
            return "image/gif"
        if raw[:4] == b"RIFF" and raw[8:12] == b"WEBP":
            return "image/webp"
        return ""

    def localProxy(self, params):
        # 本站封面为直链真图, 一般用不上代理; 保留 pic 透传(3 段格式)
        try:
            p = params
            if isinstance(p, str):
                p = json.loads(p)
            if isinstance(p, dict) and p.get("type") == "pic" and p.get("url"):
                raw = self._fetch_bytes(str(p["url"]), timeout=15,
                                         referer=self.site_url + "/")
                if raw:
                    return [200, self._img_mime(raw) or "image/jpeg", raw]
        except Exception:
            pass
        return [404, "text/plain", b""]

    def isVideoFormat(self, url):
        u = (url or "").lower()
        return u.endswith(".m3u8") or ".m3u8?" in u or u.endswith(".mp4") or ".mp4?" in u

    def manualVideoCheck(self):
        return False

    def destroy(self):
        pass
