#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 悦色TV - T4 Python Spider
# 站点：https://1.yuese5587.cc:88/
# 整站 HTML 包在 document.write(decodeURIComponent("...")) 里，先解码再解析
# 卡片：div.vod-item a-link[to="/play/{id}"]，封面 img[data-original]，标题 .rank-title（HTML实体）
# 播放页直接含 m3u8 直链
# 2026-10-31

import re
import ssl
import html as html_lib
import urllib.request
import urllib.parse

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


class Spider(BaseSpider):

    def getName(self):
        return "悦色TV"

    def init(self, extend=""):
        self.site = "https://1.yuese5587.cc:88"
        self.ua = "Mozilla/5.0 (Linux; Android 12) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
        self.ctx = ssl.create_default_context()
        self.ctx.check_hostname = False
        self.ctx.verify_mode = ssl.CERT_NONE
        self.cats = [
            {"type_id": "6", "type_name": "国产传媒"},
            {"type_id": "7", "type_name": "偷拍自拍"},
            {"type_id": "10", "type_name": "日韩无码"},
            {"type_id": "11", "type_name": "中文字幕"},
            {"type_id": "12", "type_name": "日韩杂类"},
            {"type_id": "19", "type_name": "欧美无码"},
            {"type_id": "20", "type_name": "黑白专区"},
            {"type_id": "23", "type_name": "少女动漫"},
            {"type_id": "28", "type_name": "其他综艺"},
            {"type_id": "29", "type_name": "成人游戏"},
            {"type_id": "30", "type_name": "网曝黑料"},
            {"type_id": "31", "type_name": "AI脱衣"},
            {"type_id": "35", "type_name": "绿帽偷情"},
            {"type_id": "36", "type_name": "JK萝莉"},
            {"type_id": "37", "type_name": "强奸迷奸"},
        ]

    # ---------- 基础 ----------
    def _fetch(self, url, timeout=12):
        req = urllib.request.Request(url, headers={
            "User-Agent": self.ua,
            "Accept": "text/html,application/xhtml+xml",
            "Referer": self.site + "/",
        })
        with urllib.request.urlopen(req, timeout=timeout, context=self.ctx) as r:
            raw = r.read().decode("utf-8", errors="replace")
        # 解开 document.write(decodeURIComponent("..."))
        m = re.search(r'document\.write\(decodeURIComponent\("(.+?)"\)\)', raw, re.S)
        if m:
            try:
                return urllib.parse.unquote(m.group(1))
            except Exception:
                pass
        return raw

    def _cards(self, html):
        out = []
        seen = set()
        # div.vod-item a-link[to="/play/{id}"]，按起始定位+定长窗口提取
        for m in re.finditer(r'<div class="vod-item a-link" to="(/play/[a-f0-9]+)">', html):
            href = m.group(1)
            if href in seen:
                continue
            seen.add(href)
            seg = html[m.start():m.start() + 2000]
            title_m = re.search(r'class="rank-title"[^>]*>(.*?)</div>', seg, re.S)
            title = ""
            if title_m:
                title = html_lib.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip()
            img_m = re.search(r'data-original="([^"]+)"', seg)
            pic = img_m.group(1) if img_m else ""
            if pic.startswith("//"):
                pic = "https:" + pic
            # .dat 是 base64 编码的 WebP，走 localProxy 解码
            if pic.endswith(".dat"):
                pic = self._pic_proxy(pic)
            dur_m = re.search(r'secondsToHMS\((\d+)\)', seg)
            remarks = ""
            if dur_m:
                s = int(dur_m.group(1))
                remarks = "%d:%02d:%02d" % (s // 3600, (s % 3600) // 60, s % 60) if s >= 3600 else "%d:%02d" % (s // 60, s % 60)
            if title:
                out.append({"vod_id": href, "vod_name": title, "vod_pic": pic, "vod_remarks": remarks})
        return out

    # ---------- 接口 ----------
    def _pic_proxy(self, url):
        """封面走 localProxy（.dat 是 base64 编码图）"""
        from urllib.parse import quote
        # 直接拼标准代理地址，带上源名
        return ("http://127.0.0.1:9978/proxy?do=py&from=%s&type=pic&url=%s"
                % (quote(self.getName()), quote(url, safe="")))

    def homeContent(self, filter):
        return {"class": self.cats, "filters": {}, "list": []}

    def homeVideoContent(self):
        try:
            lst = self._cards(self._fetch(self.site + "/"))
            return {"list": lst[:21]}
        except Exception:
            return {"list": []}

    def categoryContent(self, tid, pg, filter, extend):
        try:
            pg = max(1, int(pg or 1))
        except Exception:
            pg = 1
        tid = str(tid or "").strip()
        url = "%s/type/%s" % (self.site, tid) if pg <= 1 else "%s/type/%s/%d" % (self.site, tid, pg)
        try:
            lst = self._cards(self._fetch(url))
        except Exception:
            lst = []
        return {"page": pg, "pagecount": pg + 1 if lst else pg, "limit": 24,
                "total": 0, "list": lst}

    def detailContent(self, ids):
        raw = ids[0] if isinstance(ids, (list, tuple)) else ids
        href = str(raw or "").strip()
        if not href.startswith("/"):
            href = "/" + href
        try:
            html = self._fetch(self.site + href)
        except Exception:
            html = ""
        # 标题
        title = ""
        tm = re.search(r'<h1[^>]*>(.*?)</h1>', html, re.S)
        if tm:
            title = html_lib.unescape(re.sub(r'<[^>]+>', '', tm.group(1))).strip()
        if not title:
            tm = re.search(r'class="[^"]*video-title[^"]*"[^>]*>([^<]{3,80})<', html)
            title = html_lib.unescape(tm.group(1).strip()) if tm else "悦色TV"
        # 封面
        pic = ""
        pm = re.search(r'data-original="([^"]+)"', html)
        if pm:
            pic = pm.group(1)
        # 播放地址：页内 m3u8 直链，优先带 sign 的 res 域名
        m3u8s = re.findall(r'"(https?://[^"]+\.m3u8[^"]*)"', html)
        # 去重保序
        urls = []
        for u in m3u8s:
            u = u.replace("\\/", "/")
            if u not in urls:
                urls.append(u)
        # 带 sign 的放前面
        urls.sort(key=lambda u: 0 if "sign=" in u else 1)
        v = {"vod_id": href, "vod_name": title, "vod_pic": pic,
             "vod_content": title, "vod_play_from": "悦色TV",
             "vod_play_url": "正片$%s" % (urls[0] if urls else href)}
        return {"list": [v]}

    def searchContent(self, key, quick, page="1"):
        try:
            pg = max(1, int(page or 1))
        except Exception:
            pg = 1
        url = "%s/search/%s" % (self.site, urllib.parse.quote(key))
        try:
            lst = self._cards(self._fetch(url))
        except Exception:
            lst = []
        return {"page": pg, "pagecount": pg + 1 if lst else pg, "limit": 24,
                "total": 0, "list": lst}

    def playerContent(self, flag, id, vipFlags):
        url = str(id or "").strip()
        if url.startswith("http") and ".m3u8" in url:
            return {"parse": 0, "playUrl": "", "url": url,
                    "header": {"User-Agent": self.ua, "Referer": self.site + "/"}}
        if not url.startswith("/"):
            url = "/" + url
        # id 是 /play/xxx 时重新抓页取 m3u8
        try:
            html = self._fetch(self.site + url)
            m3u8s = re.findall(r'"(https?://[^"]+\.m3u8[^"]*)"', html)
            urls = []
            for u in m3u8s:
                u = u.replace("\\/", "/")
                if u not in urls:
                    urls.append(u)
            urls.sort(key=lambda u: 0 if "sign=" in u else 1)
            if urls:
                return {"parse": 0, "playUrl": "", "url": urls[0],
                        "header": {"User-Agent": self.ua, "Referer": self.site + "/"}}
        except Exception:
            pass
        return {"parse": 1, "playUrl": "", "url": self.site + url,
                "header": {"User-Agent": self.ua}}

    def isVideoFormat(self, url):
        u = str(url or "").lower()
        return any(k in u for k in (".m3u8", ".mp4", "mpegurl"))

    def localProxy(self, param):
        # 4 元组顺序：[code, mime, body, headers]，body 必须是原始字节
        try:
            import base64
            from urllib.parse import unquote
            if not isinstance(param, dict):
                param = {}
            url = unquote(param.get("url", "") or param.get("p", ""))
            if not url:
                return [404, "text/plain", b"no url", {}]
            req = urllib.request.Request(url, headers={"User-Agent": self.ua})
            with urllib.request.urlopen(req, timeout=15, context=self.ctx) as r:
                data = r.read()
            try:
                img = base64.b64decode("".join(data.decode().split()))
            except:
                img = data
            return [200, "image/webp", img, {}]
        except Exception as e:
            return [404, "text/plain", str(e).encode()[:100], {}]

    def destroy(self):
        pass
