# -*- coding: utf-8 -*-
# xjai3 (https://xjai3.com/) - TVBox py 源
# 结构实测（2026-10-27，只读实测，未登录、未注册、未支付、未下载视频）：
#   首页：收录 8089 部（文案值，两次加载时总数有 8089 与 8088 之差，故不把总数写死）。
#   剧场列表：/theater，第 1 页约 42 条，第 2 页约 39 条，下一页 href 为 /theater/page/2，
#             完整地址 https://xjai3.com/theater/page/2，末页链接为 /theater/page/208；
#             注意：分页并非严格无重叠，第 1 页尾部与第 2 页首部出现过同一条目，
#             故跨页零重叠不能当已验证，见 v6.91 分页实测要求。
#   题材筛选：不是 /theater?genre= 形式，而是标签路由 /tags/<slug>；
#             已核实：仙侠修真 /tags/xianxiaxiuzhen（52 部、2 页、本页 40 部），
#             穿越重生 /tags/chuanyuechongsheng（82 部、3 页、本页 40 部）；
#             两者下一页分别为 /tags/<slug>/page/2，与剧场相同的 /page/<n> 后缀。
#   卡片：详情链接 /dramas/<uuid>，卡片文本含标题、“更新至 N 集”与题材标签；
#         详情封面在文本抓取中为 mediacms.xonyok.cn 的图片地址，
#         但实时视图未再暴露其 img src，故封面地址形态列为文本抓取所见、实时未再核实。
#   详情：/dramas/<uuid>，含题材、“更新至 N 集”/“可看 N 集”与选集；
#         选集链接模式 /dramas/<uuid>/episodes/<n>，直接打开为独立播放页，
#         详情页内点击选集则不跳转、只在页内切换“正在播放第 N 集”。
#   播放（未验证直链形态）：独立播放页与详情页均有 <video> 元素与自定义控件，
#         未登录时免费示例的两集可开始播放，播放前有可跳过贴片；
#         但实时视图不暴露 <video>/<source> 的 src，也不暴露网络请求，
#         故是 mp4、m3u8、内嵌 JSON 还是后续 API 调用均未验证，是否签名/时效、
#         是否每次播放需重新获取也未验证；金币/VIP 剧集未测试，不作结论。
#         故 playerContent 先全量扫直链、探活通过才 parse=0，扫不到回 parse=1 嗅探。
#   搜索：/search?q=<UTF-8 编码关键词>，结果数文案如“10 个相关结果”；
#         更宽泛的词显示“200 个相关结果”但初始仅加载 30 条，页内未见下一页链接，
#         手动访问 &page=2 仍显示首批 30 条，故搜索翻页方式未验证，
#         本源搜索只回第 1 页，第 2 页起回空，不伪造分页。
#   拦截：未遇到登录墙、年龄验证门、验证码或机器人挑战；
#         仅有页脚年龄文字说明、播放前贴片广告、首页可关闭广告弹窗，
#         首次点剧场下一页时另开过一个外部广告标签页，原标签页仍正常进入第 2 页。
# 修正（2026-10-28）：卡片按 article+链接内解析，分类用核实的 26 个标签静态表；
#         上一版链接后窗口解析与全页标签解析已废弃，见 _parse_cards 与 homeContent。
# 未验证：详情封面实时 src、
#         播放直链形态与签名、搜索翻页、金币/VIP 剧集播放、分页严格无重叠。
import re
import time
import ssl
import urllib.request
import urllib.parse
import html as html_mod
from http.cookiejar import CookieJar
try:
    from base.spider import Spider as BaseSpider
except Exception:
    class BaseSpider(object):
        def __init__(self):
            pass


class Spider(BaseSpider):
    def __init__(self):
        self.site_url = "https://xjai3.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,*/*;q=0.8",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Referer": "https://xjai3.com/",
        }
        self._cj = CookieJar()
        self._last = 0.0

    def init(self, extend=""):
        return None

    def getName(self):
        return "xjai3"

    def _fetch(self, url, timeout=12, extra_headers=None):
        gap = time.time() - self._last
        if gap < 0.5:
            time.sleep(0.5 - gap)
        self._last = time.time()
        try:
            ctx = ssl._create_unverified_context()
        except Exception:
            ctx = None
        try:
            headers = dict(self.headers)
            if extra_headers:
                headers.update(extra_headers)
            req = urllib.request.Request(url, headers=headers)
            opener = urllib.request.build_opener(
                urllib.request.HTTPSHandler(context=ctx),
                urllib.request.HTTPCookieProcessor(self._cj))
            with opener.open(req, timeout=timeout) as resp:
                raw = resp.read()
                enc = (resp.headers.get("Content-Encoding", "") or "").lower()
                if "gzip" in enc or raw[:2] == b"\x1f\x8b":
                    import gzip
                    raw = gzip.decompress(raw)
                return raw.decode("utf-8", errors="ignore")
        except Exception:
            return ""

    def _fetch_bytes(self, url, timeout=12):
        try:
            ctx = ssl._create_unverified_context()
        except Exception:
            ctx = None
        try:
            req = urllib.request.Request(url, headers=self.headers)
            opener = urllib.request.build_opener(
                urllib.request.HTTPSHandler(context=ctx),
                urllib.request.HTTPCookieProcessor(self._cj))
            with opener.open(req, timeout=timeout) as resp:
                raw = resp.read()
                enc = (resp.headers.get("Content-Encoding", "") or "").lower()
                if "gzip" in enc or raw[:2] == b"\x1f\x8b":
                    import gzip
                    raw = gzip.decompress(raw)
                return raw
        except Exception:
            return b""

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

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

    def _probe_media(self, url):
        try:
            gap = time.time() - self._last
            if gap < 0.5:
                time.sleep(0.5 - gap)
            self._last = time.time()
            ctx = ssl._create_unverified_context()
        except Exception:
            ctx = None
        try:
            req = urllib.request.Request(url, headers=self.headers)
            opener = urllib.request.build_opener(
                urllib.request.HTTPSHandler(context=ctx),
                urllib.request.HTTPCookieProcessor(self._cj))
            with opener.open(req, timeout=10) as resp:
                head = resp.read(4096)
            low = (url or "").lower()
            if ".m3u8" in low:
                return b"#EXTM3U" in head
            if ".mp4" in low:
                return b"ftyp" in head
            return False
        except Exception:
            return False

    def _parse_cards(self, html_data):
        # 修正（2026-10-28，复核后）：卡片标题在链接内部，不在链接之后。
        # 上一版按“链接后窗口取标题”会取到下一张卡，造成封面、名称重复/错位。
        # 正确做法：以 article 为单位，取其内部唯一的 /dramas/ 链接，
        # 只在该链接内部取图与标题，不向后取下一卡内容补位。
        # 链接内顺序分两种，均已核实：
        #   剧场：角标 -> 封面图 -> 标题 -> 更新至N集（无空格）-> 可选题材；
        #   标签页：封面图 -> 更新至 N 集（带空格）-> 标题 -> 全 N 集·标签名。
        # 字面 div/span/h3 标签名未证实，故不依赖具体标签名，只按 article 切块
        # 与 <a> 内文解析；article 切不到时回落到 <a> 内文解析，绝不向后取窗口。
        cards, seen = [], set()
        if not html_data:
            return cards
        blocks = re.findall(r"<article[^>]*>(.*?)</article>", html_data, re.S | re.I)
        hrefs = [None] * len(blocks) if blocks else []
        if not blocks:
            pairs = re.findall(
                r'<a[^>]+href="(/dramas/[A-Za-z0-9][A-Za-z0-9_-]*)"[^>]*>(.*?)</a>',
                html_data, re.S | re.I)
            if not pairs:
                pairs = re.findall(
                    r"<a[^>]+href='(/dramas/[A-Za-z0-9][A-Za-z0-9_-]*)'[^>]*>(.*?)</a>",
                    html_data, re.S | re.I)
            blocks = [inner for _href, inner in pairs]
            hrefs = [href for href, _inner in pairs]
        for idx, blk in enumerate(blocks):
            if hrefs[idx]:
                did = hrefs[idx].split("/dramas/", 1)[-1]
            else:
                lm = re.search(r"/dramas/([A-Za-z0-9][A-Za-z0-9_-]*)", blk)
                if not lm:
                    continue
                did = lm.group(1)
            if did in seen:
                continue
            seen.add(did)
            pic = ""
            cm = re.search(r"(https?://[^\"'<> ]+mediacms[^\"'<> ]+\.(?:jpg|jpeg|png|webp)[^\"'<> ]*)", blk, re.I)
            if cm:
                pic = cm.group(1)
            else:
                for im in re.finditer(r"<img[^>]+>", blk, re.I):
                    tag = im.group(0)
                    for attr in ("data-original", "data-src", "src", "srcset"):
                        mm = re.search(r'%s\s*=\s*"([^" ]+)"' % attr, tag, re.I)
                        if not mm:
                            mm = re.search(r"%s\s*=\s*'([^' ]+)'" % attr, tag, re.I)
                        if mm and mm.group(1) and not mm.group(1).startswith(("data:", "blob:")):
                            cand = mm.group(1).split(",")[0].split()[0]
                            if re.search(r"\.(?:webp|jpg|jpeg|png)(?:\?|$)", cand, re.I):
                                pic = self._abs(cand)
                                break
                    if pic:
                        break
            text = re.sub(r"\s+", " ", self._clean(re.sub(r"<[^>]+>", " ", blk))).strip()
            title, remarks = "", ""
            vm = re.match(r"查看《(.+?)》详情", text)
            if vm:
                title = vm.group(1).strip()
                um = re.search(r"更新至\s*(\d+)\s*集", text)
                if um:
                    remarks = "更新至%d集" % int(um.group(1))
            elif text.startswith("更新至"):
                tm = re.match(r"更新至\s*(\d+)\s*集\s*(.+?)\s*全\s*\d+\s*集", text)
                if tm:
                    remarks = "更新至%d集" % int(tm.group(1))
                    title = tm.group(2).strip()
            else:
                tm = re.match(r"^(?:免费|金币|VIP)?\s*(.+?)\s*更新至\s*(\d+)\s*集\b", text)
                if tm:
                    title = tm.group(1).strip()
                    remarks = "更新至%d集" % int(tm.group(2))
            if not title:
                am = re.search(r'alt\s*=\s*"短剧《(.+?)》封面"', blk, re.I)
                if am:
                    title = am.group(1).strip()
            if not title:
                continue
            cards.append({"vod_id": "/dramas/%s" % did, "vod_name": title,
                          "vod_pic": pic, "vod_remarks": remarks})
        return cards

    def _list_url(self, base, pg):
        base = base if base.startswith("/") else "/" + base
        if pg <= 1:
            return self.site_url + base
        return "%s%s/page/%d" % (self.site_url, base.rstrip("/"), pg)

    def homeContent(self, filter):
        # 分类静态表（2026-10-28 复核，剧场筛选栏“分类”组内顺序，共 26 个）：
        # 上一版动态解析全页 /tags/ 链接会混入页脚热门专题与标签页侧栏相关标签，
        # 导致分类名字不对；首页题材导航只有 22 个且不全，也不能代替本表。
        # “全部”是按钮、无 href，对应剧场列表 /theater。
        tags = [
            ("明星换脸", "mingxinghuanlian"), ("影视魔改", "yingshimogai"),
            ("动漫游戏", "dongmanyouxi"), ("家庭乱伦", "jiatingluanlun"),
            ("穿越重生", "chuanyuechongsheng"), ("系统异能", "xitongyineng"),
            ("仙侠修真", "xianxiaxiuzhen"), ("古装权谋", "guzhuangquanmou"),
            ("灵异奇幻", "lingyiqihuan"), ("同性题材", "tongxingticai"),
            ("性转伪娘", "xingzhuanweiniang"), ("婚姻背叛", "hunyinbeipan"),
            ("支配调教", "zhipeidiaojiao"), ("偷拍偷窥", "toupaitoukui"),
            ("公共露出", "gonggongluchu"), ("悬疑冒险", "xuanyimaoxian"),
            ("乡村艳情", "xiangcunyanqing"), ("校园青春", "xiaoyuanqingchun"),
            ("都市职场", "dushizhichang"), ("医疗情色", "yiliaoqingse"),
            ("科幻末世", "kehuanmoshi"), ("人妻熟女", "renqishunv"),
            ("多人派对", "duorenpaidui"), ("情色写真", "qingsexiezhen"),
            ("日常艳遇", "richangyanyu"), ("原创短剧", "yuanchuangduanju"),
        ]
        cats = [{"type_id": "/theater", "type_name": "全部"}]
        for name, slug in tags:
            cats.append({"type_id": "/tags/%s" % slug, "type_name": name})
        return {"class": cats, "filters": {}}

    def homeVideoContent(self):
        html_data = self._fetch("%s/theater" % self.site_url)
        return {"list": self._parse_cards(html_data)}

    def categoryContent(self, tid, pg, filter, extend):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        base = str(tid or "/theater")
        if not base.startswith("/"):
            base = "/" + base
        html_data = self._fetch(self._list_url(base, pg))
        cards = self._parse_cards(html_data)
        # 总数两次加载不一致（8089 与 8088），故不写死总数与末页，
        # 用“有卡就下一页”的满页继续翻写法，total 留 0 表示未知。
        return {"list": cards, "page": pg,
                "pagecount": pg + 1 if cards else pg,
                "limit": len(cards), "total": 0}

    def detailContent(self, ids):
        vid = str(ids[0]).strip() if ids else ""
        shell = {"vod_id": vid, "vod_name": "", "vod_pic": "",
                 "vod_remarks": "", "vod_play_from": "", "vod_play_url": ""}
        if not vid:
            return {"list": [shell]}
        if vid.startswith("http"):
            url = vid
            did = re.search(r"/dramas/([A-Za-z0-9][A-Za-z0-9_-]*)", vid)
            did = did.group(1) if did else ""
        elif vid.startswith("/dramas/"):
            url = self.site_url + vid
            did = vid.split("/")[2] if len(vid.split("/")) > 2 else ""
        else:
            url = "%s/dramas/%s" % (self.site_url, vid)
            did = vid
        html_data = self._fetch(url)
        if not html_data:
            return {"list": [shell]}
        tm = re.search(r"<title[^>]*>(.*?)</title>", html_data, re.S | re.I)
        if tm:
            title = self._clean(tm.group(1))
            title = re.split(r"[｜|]", title)[0].strip()
            title = re.sub(r"（更新至\s*\d+\s*集）.*$", "", title).strip()
            shell["vod_name"] = title
        cm = re.search(r'''(https?://[^"'<> ]+mediacms[^"'<> ]+\.(?:jpg|jpeg|png|webp)[^"'<> ]*)''', html_data, re.I)
        if cm:
            shell["vod_pic"] = cm.group(1)
        else:
            for im in re.finditer(r"<img[^>]+>", html_data, re.I):
                for attr in ("data-original", "data-src", "src"):
                    mm = re.search(r'''%s\s*=\s*["\']([^"\']+)["\']''' % attr, im.group(0), re.I)
                    if mm and re.search(r"\.(?:webp|jpg|jpeg|png)(?:\?|$)", mm.group(1), re.I):
                        shell["vod_pic"] = self._abs(mm.group(1))
                        break
                if shell["vod_pic"]:
                    break
        # 集数：选集链接优先，其次“更新至 N 集”/“可看 N 集”/“共 N 集”。
        eps = sorted({int(x) for x in re.findall(
            r"/dramas/%s/episodes/(\d+)" % re.escape(did), html_data)} if did else [])
        total = 0
        um = re.search(r"更新至\s*(\d+)\s*集", html_data)
        if um:
            total = int(um.group(1))
        else:
            km = re.search(r"可看\s*(\d+)\s*集", html_data)
            if km:
                total = int(km.group(1))
        if total:
            shell["vod_remarks"] = "更新至%d集" % total
        if eps:
            shell["vod_play_from"] = "在线播放"
            shell["vod_play_url"] = "#".join(
                "第%d集$%s/dramas/%s/episodes/%d" % (n, self.site_url, did, n) for n in eps)
        elif total and did:
            # 选集链接未扫到时，按已核实的选集链接模式拼集数，不编其他播放页。
            shell["vod_play_from"] = "在线播放"
            shell["vod_play_url"] = "#".join(
                "第%d集$%s/dramas/%s/episodes/%d" % (n, self.site_url, did, n)
                for n in range(1, total + 1))
        else:
            shell["vod_play_from"] = "在线播放"
            shell["vod_play_url"] = "正片$%s" % url
        return {"list": [shell]}

    def playerContent(self, flag, id, vipFlags):
        raw = str(id or "").strip()
        if "$" in raw:
            raw = raw.rsplit("$", 1)[-1].strip()
        header = {"User-Agent": self.headers["User-Agent"],
                  "Referer": self.site_url + "/"}
        if raw.lower().startswith("http") and (".m3u8" in raw.lower() or ".mp4" in raw.lower()):
            if self._probe_media(raw):
                return {"parse": 0, "playUrl": "", "url": raw, "header": header}
            return {"parse": 1, "playUrl": "", "url": raw, "header": header}
        url = raw if raw.startswith("http") else self._abs(raw)
        html_data = self._fetch(url)
        # v6.83 模板：全量扫 <source>/<video> 与全文 m3u8/mp4，探活通过才 parse=0。
        cands = []
        for pat in (r'<source[^>]+src="([^"]+)"', r'<video[^>]+src="([^"]+)"'):
            cands += re.findall(pat, html_data, re.I)
        cands += re.findall(r'"(https?://[^"]+\.(?:m3u8|mp4)[^"]*)"', html_data, re.I)
        cands += re.findall(r"'(https?://[^']+\.(?:m3u8|mp4)[^']*)'", html_data, re.I)
        seen = set()
        for cand in cands:
            cand = cand.strip().replace("\\/", "/")
            low = cand.lower()
            if cand in seen or any(k in low for k in ("preview", "sample", "trailer", "thumb")):
                continue
            seen.add(cand)
            cand_url = self._abs(cand)
            if self._probe_media(cand_url):
                return {"parse": 0, "playUrl": "", "url": cand_url, "header": header}
        # 扫不到直链：交壳内嗅探；直链形态未验证，不把播放页地址当直链下发。
        return {"parse": 1, "playUrl": "", "url": url, "header": header}

    def searchContent(self, key, quick, pg="1"):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        # 搜索翻页未验证（&page=2 仍显示首批），只回第 1 页，第 2 页起回空。
        if pg > 1:
            return {"list": [], "page": pg, "pagecount": 1, "limit": 0, "total": 0}
        url = "%s/search?q=%s" % (self.site_url, urllib.parse.quote(str(key)))
        html_data = self._fetch(url)
        cards = self._parse_cards(html_data)
        total = 0
        tm = re.search(r"(\d+)\s*个相关结果", html_data)
        if tm:
            total = int(tm.group(1))
        return {"list": cards, "page": pg, "pagecount": 1,
                "limit": len(cards), "total": total}

    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 localProxy(self, params):
        try:
            if isinstance(params, str):
                import json as _json
                try:
                    params = _json.loads(params)
                except Exception:
                    params = {}
            if not isinstance(params, dict):
                params = {}
            url = (params.get("url") or params.get("pic") or "").strip()
            if url.startswith("http://127.0.0.1"):
                return [400, "text/plain", b""]
            if url:
                body = self._fetch_bytes(url)
                if body[:3] == b"\xff\xd8\xff":
                    return [200, "image/jpeg", body]
                if body[:8] == b"\x89PNG\r\n\x1a\n":
                    return [200, "image/png", body]
                if body[:4] == b"RIFF" and body[8:12] == b"WEBP":
                    return [200, "image/webp", body]
                if body[:3] == b"GIF":
                    return [200, "image/gif", body]
            return [404, "text/plain", b""]
        except Exception:
            return [404, "text/plain", b""]

    def action(self, action):
        return None

    def liveContent(self):
        return {}


if __name__ == "__main__":
    sp = Spider()
    html_data = ('<a href="/dramas/abc-123"><img src="https://mediacms.xonyok.cn/img/x.jpg">'
                 '示例剧 更新至3集 示例剧 成人动漫</a>')
    print(sp._parse_cards(html_data))
    print(sp._list_url("/theater", 2))
    print(sp._list_url("/tags/xianxiaxiuzhen", 2))
    print(sp.searchContent("test", False, "2"))
