# -*- coding: utf-8 -*-
# TVBox Python 影视源：AV99AV（yco405.av99av.icu）v1.0
# ============================================================
# 站点：Nuxt SPA + JSON API + AES-128-CBC 加密
# API：/api/videos?page={pg}&limit=20&category_id={cid}
# 搜索：/api/videos?kw={kw}&page={pg}
# 详情：/api/movie?id={vid} → data.info.play_url（m3u8直链）
# 解密：AES-128-CBC，key=a9yX32LpQvUt7wBc，iv=N7cPk2Bv38hWqFzM，PKCS7（纯Python实现）
import sys
import ssl
import time
import json
import re
import base64
import urllib.request
import urllib.parse
import http.client
from http.cookiejar import CookieJar

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


class Spider(BaseSpider):
    # ============ AES-128-CBC 纯Python实现（静态方法，避免模块级函数） ============
    _AES_SBOX = [
        0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
        0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
        0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
        0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
        0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
        0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
        0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
        0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
        0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
        0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
        0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
        0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
        0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
        0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
        0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
        0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16]
    _AES_RCON = [0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36]

    @staticmethod
    def _xtime(a):
        return ((a << 1) ^ 0x1b) & 0xff if a & 0x80 else (a << 1) & 0xff

    @classmethod
    def _gmul(cls, a, b):
        r = 0
        for _ in range(8):
            if b & 1:
                r ^= a
            a = cls._xtime(a)
            b >>= 1
        return r

    @classmethod
    def _aes_key_expansion(cls, key):
        sb = cls._AES_SBOX
        w = [int.from_bytes(key[i*4:(i+1)*4], "big") for i in range(4)]
        for i in range(4, 44):
            t = w[i-1]
            if i % 4 == 0:
                t = (sb[(t >> 16) & 0xff] << 24 | sb[(t >> 8) & 0xff] << 16 |
                     sb[t & 0xff] << 8 | sb[(t >> 24) & 0xff]) ^ (cls._AES_RCON[i // 4 - 1] << 24)
            w.append(w[i-4] ^ t)
        return [b"".join(x.to_bytes(4, "big") for x in w[i:i+4]) for i in range(0, 44, 4)]

    @classmethod
    def _aes_decrypt_block(cls, rks, block):
        inv = [0] * 256
        for _i, _v in enumerate(cls._AES_SBOX):
            inv[_v] = _i
        s = [block[i] ^ rks[10][i] for i in range(16)]
        for rnd in range(9, 0, -1):
            s = [inv[b] for b in (s[0],s[13],s[10],s[7],s[4],s[1],s[14],s[11],
                                    s[8],s[5],s[2],s[15],s[12],s[9],s[6],s[3])]
            rk = rks[rnd]
            s = [s[i] ^ rk[i] for i in range(16)]
            for c in range(4):
                a0,a1,a2,a3 = s[4*c],s[4*c+1],s[4*c+2],s[4*c+3]
                s[4*c]   = cls._gmul(a0,0x0e)^cls._gmul(a1,0x0b)^cls._gmul(a2,0x0d)^cls._gmul(a3,0x09)
                s[4*c+1] = cls._gmul(a0,0x09)^cls._gmul(a1,0x0e)^cls._gmul(a2,0x0b)^cls._gmul(a3,0x0d)
                s[4*c+2] = cls._gmul(a0,0x0d)^cls._gmul(a1,0x09)^cls._gmul(a2,0x0e)^cls._gmul(a3,0x0b)
                s[4*c+3] = cls._gmul(a0,0x0b)^cls._gmul(a1,0x0d)^cls._gmul(a2,0x09)^cls._gmul(a3,0x0e)
        s = [inv[b] for b in (s[0],s[13],s[10],s[7],s[4],s[1],s[14],s[11],
                                s[8],s[5],s[2],s[15],s[12],s[9],s[6],s[3])]
        return bytes(s[i] ^ rks[0][i] for i in range(16))

    def _aes_cbc_decrypt(self, cipher_b64):
        raw = base64.b64decode(cipher_b64)
        rks = self._aes_key_expansion(self._aes_key)
        iv = self._aes_iv
        out = b""
        prev = iv
        for i in range(0, len(raw), 16):
            blk = self._aes_decrypt_block(rks, raw[i:i+16])
            out += bytes(blk[j] ^ prev[j] for j in range(16))
            prev = raw[i:i+16]
        pad = out[-1]
        if 1 <= pad <= 16 and out[-pad:] == bytes([pad]) * pad:
            out = out[:-pad]
        return out.decode("utf-8")

    # ============ 初始化（紧凑风格） ============
    def __init__(self):
        self.site_url = "https://yco405.av99av.icu"
        self.api_url = "https://yco405.av99av.icu/api"
        self._aes_key = b"a9yX32LpQvUt7wBc"
        self._aes_iv = b"N7cPk2Bv38hWqFzM"
        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": "application/json, text/plain, */*",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Referer": "https://yco405.av99av.icu/",
        }
        self.cookie_jar = CookieJar()
        self.opener = self._build_opener()
        self._throttle = 0.5
        self._last_req = 0.0
        # 分类：(id, name)，全部实测有内容
        self.cats = [
            ("1428", "精品推荐"), ("1429", "国产主播"), ("1430", "国产乱伦"),
            ("1431", "自拍偷拍"), ("1432", "制服丝袜"), ("1433", "网曝事件"),
            ("1434", "传媒探花"), ("1435", "清纯学生"), ("1436", "AV解说"),
            ("1437", "淫妻作乐"), ("1438", "港台辣妹"), ("1439", "足浴撩妹"),
            ("1440", "反差母狗"), ("1441", "AI换脸"), ("1442", "VR视角"),
            ("1443", "重口性癖"), ("1444", "制服诱惑"), ("1445", "丝袜美腿"),
            ("1446", "中文字幕"), ("1447", "人妻熟女"), ("1448", "无码流出"),
            ("1449", "多人群交"), ("1450", "凌辱快感"), ("1451", "角色剧情"),
            ("1452", "强奸乱伦"), ("1453", "韩国三级"), ("1454", "欧美激情"),
            ("1455", "主奴调教"), ("1456", "动漫卡通"), ("1457", "变性伪娘"),
            ("1458", "女同性恋"), ("1459", "野外露出"), ("486", "黑丝诱惑"),
            ("487", "SWAG"), ("488", "中文字幕"), ("489", "日本有码"),
            ("490", "日本无码"), ("491", "AV解说"), ("492", "cosplay"),
            ("493", "自拍偷拍"), ("494", "网红主播"), ("495", "激情动漫"),
            ("496", "探花系列"), ("497", "三级伦理"), ("498", "VR视角"),
            ("499", "国产传媒"), ("500", "素人搭讪"), ("501", "门事件"),
            ("502", "抖阴视频"),
        ]

    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 _fetch(self, url, retry=2, referer=None):
        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()
                    return {"success": True,
                            "html": raw.decode("utf-8", errors="ignore"),
                            "data": raw}
            except http.client.IncompleteRead as e:
                if e.partial:
                    try:
                        h = e.partial.decode("utf-8", errors="ignore")
                    except Exception:
                        h = ""
                    return {"success": True, "data": e.partial, "html": h}
            except Exception as e:
                if i == retry:
                    return {"success": False, "data": b"", "html": "",
                            "error": str(e)}
                time.sleep(1)
        return {"success": False, "data": b"", "html": ""}

    def _api(self, path):
        """调API并解密，返回 data"""
        res = self._fetch(self.api_url + path)
        if not res.get("success"):
            return {}
        try:
            j = json.loads(res["html"])
            cipher = j.get("cipher", "")
            if not cipher:
                return j.get("data", j)
            pt = self._aes_cbc_decrypt(cipher)
            pj = json.loads(pt)
            return pj.get("data", pj)
        except Exception:
            return {}

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

    def _to_vod(self, v):
        vid = str(v.get("id", ""))
        pic = str(v.get("cover_url", "") or "").strip()
        if pic.startswith("//"):
            pic = "https:" + pic
        # 封面 MIME 为 application/octet-stream，App 不认，走代理解决
        if pic.startswith("http"):
            try:
                base = self.getProxyUrl()
                sep = "&" if "?" in base else "?"
                pic = base + sep + "url=" + urllib.parse.quote(pic, safe="")
            except Exception:
                pass
        return {
            "vod_id": vid,
            "vod_name": self._clean(str(v.get("title", ""))) or vid,
            "vod_pic": pic,
            "vod_remarks": str(v.get("category", "") or ""),
        }

    # ============ 标准接口 ============
    def init(self, extend=""):
        pass

    def getName(self):
        return "AV99AV"

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

    def homeVideoContent(self):
        d = self._api("/videos?page=1&limit=20&category_id=1428")
        lst = d.get("list", []) if isinstance(d, dict) else []
        return {"list": [self._to_vod(v) for v in lst[:20]]}

    def categoryContent(self, tid, pg, filter, extend):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        d = self._api("/videos?page=%d&limit=20&category_id=%s" % (pg, tid))
        lst = d.get("list", []) if isinstance(d, dict) else []
        cards = [self._to_vod(v) for v in lst]
        # pagecount 从API真实页数取
        try:
            pages = int(d.get("pages", 0))
        except Exception:
            pages = 0
        pagecount = pages if pages > 0 else (pg + 1 if cards else pg)
        return {"list": cards, "page": pg, "pagecount": pagecount,
                "limit": len(cards), "total": d.get("total", 0)}

    def detailContent(self, ids):
        vid = str(ids[0]).strip() if ids else ""
        if not vid:
            return {"list": []}
        d = self._api("/movie?id=%s" % urllib.parse.quote(vid))
        info = d.get("info", {}) if isinstance(d, dict) else {}
        title = self._clean(str(info.get("title", ""))) or vid
        pic = str(info.get("cover_url", "") or "").strip()
        if pic.startswith("//"):
            pic = "https:" + pic
        if pic.startswith("http"):
            try:
                base = self.getProxyUrl()
                sep = "&" if "?" in base else "?"
                pic = base + sep + "url=" + urllib.parse.quote(pic, safe="")
            except Exception:
                pass
        play_url = str(info.get("play_url", "") or "").strip()
        vod_play_url = "正片$%s" % play_url if play_url else ""
        vod = {
            "vod_id": vid, "vod_name": title, "vod_pic": pic,
            "vod_remarks": str(info.get("category", "") or ""),
            "vod_content": title,
            "vod_play_from": "在线播放",
            "vod_play_url": vod_play_url,
        }
        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}
        try:
            vid = re.sub(r"\D", "", raw_id)
            if vid:
                d = self.detailContent([vid])
                ep = d["list"][0]["vod_play_url"]
                if "$" in ep:
                    u = ep.split("$", 1)[1]
                    if u.startswith("http") and self.isVideoFormat(u):
                        return {"parse": 0, "url": u, "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())
        d = self._api("/videos?kw=%s&page=%d&limit=20" % (kw, pg))
        lst = d.get("list", []) if isinstance(d, dict) else []
        cards = [self._to_vod(v) for v in lst]
        try:
            pages = int(d.get("pages", 0))
        except Exception:
            pages = 0
        pagecount = pages if pages > 0 else (pg + 1 if cards else pg)
        return {"list": cards, "page": pg, "pagecount": pagecount,
                "limit": len(cards), "total": d.get("total", 0)}

    def action(self, action):
        return None

    def liveContent(self):
        return {}

    def localProxy(self, params):
        # 封面代理：修正 MIME 类型（源站返回 application/octet-stream）
        try:
            if not isinstance(params, dict):
                params = {}
            url = (params.get("url") or "").strip()
            if url.startswith("http"):
                raw = None
                for _ in range(2):
                    try:
                        req = urllib.request.Request(url, headers={"User-Agent": self.headers["User-Agent"], "Referer": self.site_url + "/"})
                        raw = urllib.request.urlopen(req, timeout=20).read()
                        if raw and len(raw) > 100:
                            break
                    except Exception:
                        time.sleep(0.5)
                if not raw:
                    return [200, "text/plain; charset=utf-8", b""]
                if raw[:2] == b"\xff\xd8":
                    return [200, "image/jpeg", raw]
                elif raw[:4] == b"\x89PNG":
                    return [200, "image/png", raw]
                elif raw[:4] == b"RIFF":
                    return [200, "image/webp", raw]
                elif raw[:3] == b"GIF":
                    return [200, "image/gif", raw]
                return [200, "image/jpeg", raw]
        except Exception:
            pass
        return [200, "text/plain; charset=utf-8", b""]

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

    def manualVideoCheck(self):
        return False

    def destroy(self):
        pass


if __name__ == "__main__":
    sp = Spider()
    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
    ast.parse(open(__file__, encoding="utf-8").read())
    check("syntax", True)

    # AES 解密自测（用真实API数据）
    try:
        res = sp._fetch(sp.api_url + "/videos?page=1&limit=1")
        j = json.loads(res["html"])
        pt = sp._aes_cbc_decrypt(j["cipher"])
        pj = json.loads(pt)
        check("aes_decrypt", "list" in pj.get("data", {}),
              "解密出 %d 条" % len(pj["data"].get("list", [])))
    except Exception as e:
        check("aes_decrypt", False, str(e)[:80])

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

    # category
    r = sp.categoryContent("1428", "1", None, None)
    check("category", len(r["list"]) > 0, "%d条 pagecount=%s" % (len(r["list"]), r["pagecount"]))
    check("covers", all(c["vod_pic"].startswith("http") for c in r["list"]),
          "%d/%d" % (sum(1 for c in r["list"] if c["vod_pic"].startswith("http")), len(r["list"])))
    check("titles", all(c["vod_name"] for c in r["list"]))

    # 翻页零重叠
    r2 = sp.categoryContent("1428", "2", None, None)
    ids1 = {c["vod_id"] for c in r["list"]}
    ids2 = {c["vod_id"] for c in r2["list"]}
    check("page_no_overlap", len(r2["list"]) > 0 and not (ids1 & ids2),
          "p2=%d条 重叠=%d" % (len(r2["list"]), len(ids1 & ids2)))

    # search
    s = sp.searchContent("学生", True, "1")
    check("search", len(s["list"]) > 0, "%d条" % len(s["list"]))

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

    # detail
    vid = r["list"][0]["vod_id"]
    d = sp.detailContent([vid])
    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"][:20], has_m3u8))

    # player
    p = sp.playerContent("在线播放", v["vod_play_url"].split("$", 1)[1], "")
    check("player", p.get("parse") == 0 and "playUrl" not in p,
          "parse=%s" % p.get("parse"))

    # m3u8 可达性
    if has_m3u8:
        murl = v["vod_play_url"].split("$", 1)[1]
        try:
            import urllib.request as _rq
            req = _rq.Request(murl, headers={"User-Agent": sp.headers["User-Agent"],
                                             "Referer": sp.site_url + "/"})
            with sp.opener.open(req, timeout=15) as resp:
                code = resp.getcode()
                head = resp.read(200).decode("utf-8", errors="ignore")
            check("m3u8_http", code == 200 and "#EXTM3U" in head,
                  "HTTP %s" % code)
        except Exception as e:
            check("m3u8_http", False, str(e)[:60])

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