# -*- coding: utf-8 -*-
# =============================================================================
# hd.rip.py — HD.Rip 全球电视频道直播 · 默影视 / TVBox Python 源
# 站点：https://hd.rip/  （IPTV 直播站，223 个在线频道，H.264 / HEVC）
#
# 实测接口（2026-11-25）：
#   频道清单  GET /api/config.php
#             -> {"channels":[{"id","name","codec","ok","logo","intro","epg","sub"}...],
#                 "offline_ids":[...], "stats":{"total","online","hidden"}, ...}
#             logo 是站内相对路径，前置 https://hd.rip 即原图（实测 200 image/png）。
#   播放地址  GET /api/play.php?id=<频道id>
#             -> {"id","name","codec","url":"https://hd.rip/stream/<流名>/playlist.m3u8?tid=..&ct=..&tsum=..&e=..&s=..","sig_ttl":3600}
#             必须先访问首页拿会话 Cookie hdrip_s，否则返回 {"error":"stream_denied"}。
#             m3u8 是签名地址，且签名绑定 Referer = 该频道页 /channel/<id>-<slug>；
#             Referer 用首页或裸 /channel/<id> 都 403 stream_denied（实测）。
#   节目表    GET /api/epg.php?id=<频道id>  -> 今明两天节目单（详情里附频道页链接）
#   搜索      站点没有服务端搜索接口（app.js 本地过滤频道名），本源同样本地过滤。
#   分类      站点没有题材分类接口，只有「全部 / H.264 / HEVC / 收藏 / 离线」筛选条；
#             本源按频道名与简介归入地区/题材桶，只作浏览用，不改动站点数据。
#
# 风控：play.php 有服务端频控（每分钟 60 次），本源单次取址、失败不重试。
# 起播只能进默影视壳实测；若报 stream_denied，属站点风控或地区限制。
#
# 排版（本次调整）：
#   - 分类级：homeContent 的 class 里带 type_flag="2"（网格）
#   - 卡片级：_item() 里带 style={"type":"rect","ratio":1.78}（16:9 横版大图）
#   - 两者叠加：一横排两个 16:9 大图
# =============================================================================
import json
import os
import re
import time
import urllib.parse
import http.cookiejar
import urllib.request

try:
    import requests
except Exception:
    requests = None

try:
    from base.spider import Spider as BaseSpider
except Exception:
    BaseSpider = object

UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36")
BASE = "https://hd.rip"


class _Resp(object):
    """统一 requests 与 urllib 的响应形态"""
    def __init__(self, code, data):
        self.status_code = code
        self.content = data
        try:
            self.text = data.decode("utf-8", "replace")
        except Exception:
            self.text = str(data)

    def json(self):
        return json.loads(self.text)


# ---------------------------------------------------------------------------
# 装载前扫描用的占位类：壳在 import 之前按纯文本扫类名/方法名，
# 真实实现是同名类（在后面重新定义并覆盖这里）。
# ---------------------------------------------------------------------------
class Spider(object):
    def __init__(self):
        pass

    def init(self, extend=""):
        pass

    def homeContent(self, filter):
        pass

    def homeVideoContent(self):
        pass

    def categoryContent(self, tid, pg, filter, extend):
        pass

    def detailContent(self, ids):
        pass

    def searchContent(self, key, quick, pg="1"):
        pass

    def playerContent(self, flag, id, vipFlags):
        pass

    def localProxy(self, param):
        pass

    def getDependence(self):
        return []


# ---------------------------------------------------------------------------
# 分类规则（按频道名 + 简介关键词归桶，一个频道可落多个桶）
# ---------------------------------------------------------------------------
CATS = [
    ("all", "全部频道"),
    ("hmt", "港澳台"),
    ("cn", "中国大陆"),
    ("jp", "日本"),
    ("kr", "韩国"),
    ("sea", "东南亚"),
    ("west", "欧美"),
    ("sport", "体育"),
    ("movie", "电影剧集"),
    ("news", "新闻资讯"),
    ("kids", "少儿动漫"),
    ("docu", "纪实生活"),
]

RULES = {
    "hmt": ["无线", "tvb", "凤凰", "viu", "rthk", "明珠", "翡翠", "香港", "中天", "东森",
            "民视", "台视", "华视", "中视", "三立", "八大", "龙华", "龙祥", "纬来", "爱尔达",
            "tvbs", "公视", "大爱", "非凡", "年代", "靖天", "华艺", "寰宇", "美亚", "天映",
            "好莱坞电影台", "catchplay", "axn台湾", "亚洲旅游台", "时尚台", "台湾"],
    "cn": ["中国", "卫视", "cctv", "大湾区", "深圳", "湖南", "江苏", "浙江", "广东", "四川",
           "湖北", "广西", "东南", "北京"],
    "jp": ["日本", "nhk", "纬来日本"],
    "kr": ["韩国", "kbs", "tvn", "阿里郎", "arirang", "mbc", "sbs", "daebak"],
    "sea": ["malaysia", "astro", "singapore", "indonesia", "thailand", "india", "zee",
            "asianet", "makkal", "tvri", "rcti", "trans", "metro", "mnc", "inews",
            "bernama", "suria", "vasantham", "tv3", "tv9", "tv2", "tv1", "tv8",
            "alhijrah", "arena", "supersport", "prima", "thrill", "nation", "pptv",
            "tnn", "tptv", "dmi", "galaxy", "muslim", "mdtv", "kids tv", "quran", "sunnah"],
    "west": ["bbc", "cnn", "cnbc", "bloomberg", "cbs", "abc", "fox", "france 24",
             "skysports", "dazn", "hbo", "cinemax", "discovery", "natgeo", "history",
             "tlc", "hgtv", "love nature", "cartoon network", "nickelodeon", "nick jr",
             "zoomoo", "animax", "axn", "studio universal", "fight sports",
             "global trekker", "cna", "cgtn", "crime investigation"],
    "sport": ["体育", "sport", "博斯", "dazn", "fight", "arena", "stadium", "高球", "网球"],
    "movie": ["电影", "戏剧", "剧", "hbo", "cinemax", "天映", "龙祥", "美亚", "tvn movies",
              "thrill", "drama", "洋片", "影"],
    "news": ["新闻", "news", "资讯", "cna", "cgtn", "财经", "bloomberg", "cnbc", "berita"],
    "kids": ["幼幼", "卡通", "kids", "cartoon", "zoomoo", "nick", "ceria", "boo", "animax"],
    "docu": ["discovery", "探索", "国家地理", "natgeo", "history", "tlc", "hgtv",
             "love nature", "旅游", "时尚", "生活", "global trekker", "动物星球"],
}


def _cat_of(ch):
    blob = ((ch.get("name") or "") + " " + (ch.get("intro") or "")).lower()
    out = ["all"]
    for tid, _ in CATS[1:]:
        for kw in RULES.get(tid, []):
            if kw in blob:
                out.append(tid)
                break
    return out


class Spider(BaseSpider):
    def __init__(self):
        self.base = BASE
        self.ua = UA
        self.sess = None
        self._cfg = None
        self._cfg_ts = 0
        self._map = None
        self._map_ts = 0
        self.extend = ""

    # ---------------- 基础 ----------------
    def _session(self):
        if self.sess is not None:
            return self.sess
        if requests is not None:
            s = requests.Session()
            s.headers.update({
                "User-Agent": self.ua,
                "Accept": "application/json, text/plain, */*",
                "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
                "Referer": self.base + "/",
            })
            try:
                s.get(self.base + "/", timeout=8)   # 取 hdrip_s 会话 Cookie
            except Exception:
                pass
            self.sess = s
            return s
        # 壳里没有 requests 时用标准库，同样带 Cookie 会话
        cj = http.cookiejar.CookieJar()
        op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
        op.addheaders = [("User-Agent", self.ua),
                         ("Accept", "application/json, text/plain, */*"),
                         ("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8"),
                         ("Referer", self.base + "/")]
        try:
            op.open(self.base + "/", timeout=8).read()
        except Exception:
            pass
        self.sess = op
        return op

    def _get(self, url, referer=None, timeout=8):
        s = self._session()
        if not s:
            return None
        h = {}
        if referer:
            h["Referer"] = referer
        for _ in range(2):
            try:
                if requests is not None and hasattr(s, "get"):
                    r = s.get(url, headers=h, timeout=timeout)
                    if r.status_code == 200:
                        return _Resp(200, r.content)
                    if r.status_code == 429:
                        time.sleep(2)
                else:
                    req = urllib.request.Request(url, headers=h)
                    resp = s.open(req, timeout=timeout)
                    data = resp.read()
                    if resp.status == 200:
                        return _Resp(200, data)
            except Exception:
                time.sleep(1)
        return None

    def _config(self, force=False):
        if self._cfg and not force and time.time() - self._cfg_ts < 600:
            return self._cfg
        r = self._get(self.base + "/api/config.php")
        if r is None:
            return self._cfg or {"channels": []}
        try:
            self._cfg = r.json()
            self._cfg_ts = time.time()
        except Exception:
            self._cfg = self._cfg or {"channels": []}
        return self._cfg

    def _channels(self):
        return [c for c in (self._config().get("channels") or []) if c.get("id")]

    def _paths(self, force=False):
        """id -> 频道页路径；播放签名绑定的 Referer 必须是这个路径。"""
        if self._map and not force and time.time() - self._map_ts < 3600:
            return self._map
        m = self._map or {}
        r = self._get(self.base + "/sitemap.xml", timeout=12)
        if r is not None:
            for cid, slug in re.findall(r"https://hd\.rip/channel/(\d+)-([^<]+)</loc>", r.text):
                if cid not in m:
                    m[cid] = "/channel/%s-%s" % (cid, slug)
        self._map = m
        self._map_ts = time.time()
        return m

    def _path(self, cid):
        cid = str(cid)
        p = self._paths().get(cid)
        if p:
            return p
        # 退路：用频道名拼 slug（与站点规则不完全一致，仅兜底）
        for c in self._channels():
            if str(c.get("id")) == cid:
                slug = re.sub(r"[\s_]+", "-", (c.get("name") or "").strip()).lower()
                return "/channel/%s-%s" % (cid, urllib.parse.quote(slug, safe="-._~"))
        return "/channel/%s" % cid

    def _pic(self, c):
        p = c.get("logo") or ""
        if not p:
            return ""
        if p.startswith("http"):
            return p
        return self.base + urllib.parse.quote(p, safe="/-._~")

    def _item(self, c):
        codec = (c.get("codec") or "").strip()
        return {
            "vod_id": "hdrip_%s" % c.get("id"),
            "vod_name": c.get("name") or "",
            "vod_pic": self._pic(c),
            "vod_remarks": codec if codec else "直播",
            # 卡片级排版：rect + 16:9 → 宽度撑大，网格自动从 3 列降为 2 列
            "style": {"type": "rect", "ratio": 1.78},
        }

    def _classes(self):
        # 分类级排版：type_flag="2" → 网格模式
        return [{"type_id": t, "type_name": n, "type_flag": "2"} for t, n in CATS]

    # ---------------- 对外接口 ----------------
    def init(self, extend=""):
        self.extend = extend or ""
        self._config(True)
        self._paths()
        return self

    def homeContent(self, filter):
        chs = self._channels()
        return {"class": self._classes(), "filters": {},
                "list": [self._item(c) for c in chs[:60]]}

    def homeVideoContent(self):
        return {"list": [self._item(c) for c in self._channels()[:60]]}

    def categoryContent(self, tid, pg, filter, extend):
        tid = str(tid or "all")
        try:
            pg = int(str(pg).strip() or 1)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        chs = self._channels()
        if tid not in ("all", ""):
            chs = [c for c in chs if tid in _cat_of(c)]
        limit = 60
        total = len(chs)
        pagecount = (total + limit - 1) // limit if total else 1
        if pagecount > 999:
            pagecount = 999
        start = (pg - 1) * limit
        return {"page": pg, "pagecount": pagecount, "limit": limit, "total": total,
                "list": [self._item(c) for c in chs[start:start + limit]]}

    def detailContent(self, ids):
        vid = ids[0] if isinstance(ids, (list, tuple)) else ids
        cid = str(vid).replace("hdrip_", "").strip()
        ch = None
        for c in self._channels():
            if str(c.get("id")) == cid:
                ch = c
                break
        if not ch:
            return {"list": []}
        page = self.base + self._path(cid)
        content = (ch.get("intro") or ch.get("name") or "").strip()
        content += "\n\n频道页（节目表）：%s" % page
        content += "\n播放地址由 /api/play.php 实时签发（有效期约 1 小时）；"
        content += "若提示 stream_denied，多为站点风控或地区限制，换网络后重试。"
        return {"list": [{
            "vod_id": "hdrip_%s" % cid,
            "vod_name": ch.get("name") or "",
            "vod_pic": self._pic(ch),
            "type_name": (ch.get("codec") or "直播"),
            "vod_remarks": "直播" if ch.get("ok", 1) else "已下线",
            "vod_content": content,
            "vod_play_from": "HD.Rip直播",
            "vod_play_url": "直播$%s" % cid,
        }]}

    def searchContent(self, key, quick, pg="1"):
        key = (key or "").strip().lower()
        try:
            pg = int(str(pg).strip() or 1)
        except Exception:
            pg = 1
        chs = self._channels()
        if key:
            chs = [c for c in chs
                   if key in (c.get("name") or "").lower()
                   or key in (c.get("intro") or "").lower()]
        limit = 48
        total = len(chs)
        pagecount = (total + limit - 1) // limit if total else 1
        start = (pg - 1) * limit
        return {"page": pg, "pagecount": min(pagecount, 999), "limit": limit,
                "total": total, "list": [self._item(c) for c in chs[start:start + limit]]}

    def playerContent(self, flag, id, vipFlags):
        cid = str(id).strip()
        if cid.startswith("hdrip_"):
            cid = cid[6:]
        page = self.base + self._path(cid)
        r = self._get(self.base + "/api/play.php?id=" + urllib.parse.quote(cid),
                      referer=page, timeout=10)
        url = ""
        if r is not None:
            try:
                url = (r.json() or {}).get("url") or ""
            except Exception:
                url = ""
        if not url:
            # 取不到签名地址：把频道页交给播放器（浏览器内核可直接看）
            return {"parse": 1, "jx": 0, "url": page,
                    "header": {"User-Agent": self.ua, "Referer": self.base + "/"}}
        return {"parse": 0, "url": url,
                "header": {"User-Agent": self.ua, "Referer": page}}

    def localProxy(self, param):
        try:
            p = json.loads(param)
            return [200, "application/vnd.apple.mpegurl", p.get("url", ""), p.get("header", {})]
        except Exception:
            return None

    def getDependence(self):
        return []


# ---------------------------------------------------------------------------
# 自检（默认关闭；只有显式设置 HDRIP_SELFTEST=1 才执行）
# 只做接口级自检，起播必须进默影视壳实测。
# ---------------------------------------------------------------------------
def _selftest():
    sp = Spider()
    sp.init("")
    chs = sp._channels()
    print("channels:", len(chs))
    if not chs:
        return
    print("cover:", sp._pic(chs[0]))
    p1 = sp.categoryContent("all", 1, False, {})
    p2 = sp.categoryContent("all", 2, False, {})
    p3 = sp.categoryContent("all", 3, False, {})
    print("pagecount:", p1["pagecount"], "total:", p1["total"])
    print("first ids:", [x["vod_id"] for x in (p1["list"][:1] + p2["list"][:1] + p3["list"][:1])])
    print("class[0]:", sp.homeContent(False)["class"][0])
    print("item style:", p1["list"][0].get("style"))
    det = sp.detailContent(["hdrip_%s" % chs[0]["id"]])
    print("detail play:", det["list"][0]["vod_play_url"], "| pic:", det["list"][0]["vod_pic"])
    sr = sp.searchContent(chs[0]["name"][:2], False, "1")
    print("search items:", len(sr["list"]))
    print("path:", sp._path(chs[0]["id"]))
    pl = sp.playerContent("HD.Rip直播", str(chs[0]["id"]), [])
    print("play:", json.dumps(pl, ensure_ascii=False)[:300])


if __name__ == "__main__":
    if os.environ.get("HDRIP_SELFTEST") == "1":
        _selftest()