# -*- coding: utf-8 -*-
"""
28短剧 (28dj01.com) 爬虫 - 线路统一修复版
- 推荐与分类使用相同的线路提取逻辑
- 播放页主动提取真实视频地址（m3u8/解析接口）
适配 dr_py / TVBox
"""
import re
import json
import time
import urllib.parse
# [py578 adaptation] requests hard-dependency fallback (real requests preferred)
try:
    import requests
except Exception:
    requests = None
if requests is None:
    # --- embedded requests-compatible shim (urllib based) for Yingxia adaptation ---
    # Inserted by py578 adaptation: used only when real `requests` is unavailable.
    import json as _json
    import ssl as _ssl
    import urllib.error as _uerr
    import urllib.parse as _uparse
    import urllib.request as _ureq
    import http.cookiejar as _cookiejar


    class _ReqExc(Exception):
        pass


    class _Timeout(_ReqExc):
        pass


    class _ConnectionError(_ReqExc):
        pass


    class _HTTPError(_ReqExc):
        pass


    class _CaseDict(dict):
        def get(self, k, d=None):
            for kk, vv in self.items():
                if kk.lower() == str(k).lower():
                    return vv
            return d

        def __getitem__(self, k):
            v = self.get(k)
            if v is None:
                raise KeyError(k)
            return v


    class _Response:
        def __init__(self, status_code=0, headers=None, content=b"", url="", cookies=None):
            self.status_code = status_code
            self.headers = _CaseDict(headers or {})
            self.content = content or b""
            self.url = url
            self.cookies = cookies or {}
            self.encoding = None
            self._text = None

        @property
        def text(self):
            if self._text is None:
                enc = self.encoding
                if not enc:
                    ct = self.headers.get("Content-Type", "")
                    m = _uparse.parse_qs(ct.replace(";", "&")) if False else None
                    enc = "utf-8"
                    if "charset=" in ct:
                        enc = ct.split("charset=")[-1].split(";")[0].strip() or "utf-8"
                try:
                    self._text = self.content.decode(enc, "ignore")
                except Exception:
                    self._text = self.content.decode("utf-8", "ignore")
            return self._text

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

        def raise_for_status(self):
            if self.status_code >= 400:
                raise _HTTPError("HTTP %s" % self.status_code)

        def iter_content(self, chunk_size=65536):
            for i in range(0, len(self.content), chunk_size):
                yield self.content[i:i + chunk_size]

        def close(self):
            pass


    class _Session:
        def __init__(self):
            self.headers = {"User-Agent": "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 Chrome/120 Mobile Safari/537.36"}
            self.cookies = {}
            self._jar = _cookiejar.CookieJar()
            self._ctx = _ssl._create_unverified_context()
            self._opener = _ureq.build_opener(
                _ureq.HTTPCookieProcessor(self._jar),
                _ureq.HTTPSHandler(context=self._ctx))

        def request(self, method, url, headers=None, timeout=15, data=None,
                    json=None, params=None, cookies=None, verify=False,
                    allow_redirects=True, stream=False, **kw):
            if params:
                qs = _uparse.urlencode(params, doseq=True)
                url = url + ("&" if "?" in url else "?") + qs
            hd = dict(self.headers)
            if headers:
                hd.update(headers)
            body = None
            if json is not None:
                body = _json.dumps(json, ensure_ascii=False).encode("utf-8")
                hd.setdefault("Content-Type", "application/json")
            elif isinstance(data, dict):
                body = _uparse.urlencode(data, doseq=True).encode("utf-8")
                hd.setdefault("Content-Type", "application/x-www-form-urlencoded")
            elif isinstance(data, str):
                body = data.encode("utf-8")
            elif isinstance(data, (bytes, bytearray)):
                body = bytes(data)
            if cookies:
                hd["Cookie"] = "; ".join("%s=%s" % kv for kv in cookies.items())
            elif self.cookies:
                hd.setdefault("Cookie", "; ".join("%s=%s" % kv for kv in self.cookies.items()))
            req = _ureq.Request(url, data=body, headers=hd, method=method.upper())
            try:
                to = timeout
                if isinstance(to, (tuple, list)):
                    to = max(to)
                if to and float(to) > 120:
                    to = float(to) / 1000.0
                with self._opener.open(req, timeout=to or 15) as resp:
                    content = resp.read()
                    hdrs = dict(resp.headers.items())
                    final = resp.geturl()
                    status = resp.status
            except _uerr.HTTPError as e:
                try:
                    content = e.read()
                except Exception:
                    content = b""
                hdrs = dict(e.headers.items()) if e.headers else {}
                final = e.geturl() if hasattr(e, "geturl") else url
                status = e.code
            except Exception as e:
                raise _ConnectionError(str(e))
            for c in self._jar:
                self.cookies[c.name] = c.value
            return _Response(status, hdrs, content, final, dict(self.cookies))

        def get(self, url, **kw):
            return self.request("GET", url, **kw)

        def post(self, url, data=None, **kw):
            return self.request("POST", url, data=data, **kw)

        def head(self, url, **kw):
            return self.request("HEAD", url, **kw)

        def close(self):
            pass


    class _Exceptions:
        RequestException = _ReqExc
        Timeout = _Timeout
        ConnectTimeout = _Timeout
        ReadTimeout = _Timeout
        ConnectionError = _ConnectionError
        HTTPError = _HTTPError
        SSLError = _ConnectionError


    class _RequestsShim:
        Session = _Session
        exceptions = _Exceptions
        Response = _Response

        @staticmethod
        def request(method, url, **kw):
            return _Session().request(method, url, **kw)

        @staticmethod
        def get(url, **kw):
            return _Session().request("GET", url, **kw)

        @staticmethod
        def post(url, data=None, **kw):
            return _Session().request("POST", url, data=data, **kw)

        @staticmethod
        def head(url, **kw):
            return _Session().request("HEAD", url, **kw)


    requests = _RequestsShim
    # --- end embedded requests shim ---

    # --- py578 compat extras for deep requests usage (fallback only) ---
    class _HTTPAdapter:
        def __init__(self, *a, **k):
            pass


    class _Retry:
        def __init__(self, *a, **k):
            pass


    def _session_mount(self, *a, **k):
        return None


    _Session.mount = _session_mount
    _Session.put = lambda self, url, data=None, **kw: self.request("PUT", url, data=data, **kw)
    _Session.delete = lambda self, url, **kw: self.request("DELETE", url, **kw)
    _Session.patch = lambda self, url, data=None, **kw: self.request("PATCH", url, data=data, **kw)
    _Session.options = lambda self, url, **kw: self.request("OPTIONS", url, **kw)
    _Response.apparent_encoding = "utf-8"
    _Response.ok = property(lambda self: self.status_code < 400)
    _Response.history = property(lambda self: [])


    class _ReqUtils:
        quote = staticmethod(_uparse.quote)
        quote_plus = staticmethod(_uparse.quote_plus)
        unquote = staticmethod(_uparse.unquote)
        unquote_plus = staticmethod(_uparse.unquote_plus)


    class _ReqAdapters:
        HTTPAdapter = _HTTPAdapter


    class _ReqUrllib3:
        @staticmethod
        def disable_warnings(*a, **k):
            pass

        class exceptions:
            class InsecureRequestWarning(Warning):
                pass


    class _ReqPackages:
        urllib3 = _ReqUrllib3


    _RequestsShim.utils = _ReqUtils
    _RequestsShim.adapters = _ReqAdapters
    _RequestsShim.packages = _ReqPackages
    _RequestsShim.put = staticmethod(lambda url, data=None, **kw: _Session().request("PUT", url, data=data, **kw))
    _RequestsShim.delete = staticmethod(lambda url, **kw: _Session().request("DELETE", url, **kw))
    _RequestsShim.patch = staticmethod(lambda url, data=None, **kw: _Session().request("PATCH", url, data=data, **kw))
    # --- end py578 compat extras ---
# [py578] import requests  (provided by adaptation above)
import base64
# [py578 adaptation] bs4 fallback (host provides pyquery, bs4 unknown)
try:
    from bs4 import BeautifulSoup
except Exception:
    BeautifulSoup = None
if BeautifulSoup is None:
    # --- embedded BeautifulSoup-compatible shim (pyquery/lxml based) for Yingxia ---
    # Inserted by py578 adaptation: used only when real `bs4` is unavailable.
    # Covers the API subset used by the adapted spiders: find/find_all
    # (tag, class_, id, attrs incl. regex values, recursive=False, limit),
    # select/select_one (CSS), get_text/text, get/[]/attrs/has_attr, name, str().
    import re as _re

    _MULTI_ATTRS = ("class", "rel", "rev", "accesskey", "headers")


    def _is_el(node):
        return isinstance(getattr(node, "tag", None), str)


    def _attr_val(el, name):
        v = el.get(name)
        if v is None:
            return None
        if name in _MULTI_ATTRS:
            return v.split()
        return v


    def _match_one(value, want):
        """bs4-style attr value matching: str eq, regex search, True=present, list=any."""
        if want is True:
            return value is not None
        if isinstance(want, _re.Pattern):
            if isinstance(value, list):
                return any(want.search(v) for v in value) or bool(want.search(" ".join(value)))
            return bool(want.search(value or ""))
        if isinstance(want, (list, tuple)):
            return any(_match_one(value, w) for w in want)
        if isinstance(value, list):
            return str(want) in value
        return value == want


    def _matches(el, name, attrs, string):
        if not _is_el(el):
            return False
        if name is not None and name is not True:
            tags = name if isinstance(name, (list, tuple)) else [name]
            ok = False
            for t in tags:
                if isinstance(t, _re.Pattern):
                    if t.search(el.tag):
                        ok = True
                        break
                elif el.tag == str(t).lower():
                    ok = True
                    break
            if not ok:
                return False
        for k, want in attrs.items():
            if k == "class":
                have = (el.get("class") or "").split()
                if isinstance(want, _re.Pattern):
                    if not (any(want.search(c) for c in have) or want.search(" ".join(have))):
                        return False
                elif isinstance(want, (list, tuple)):
                    if not any(str(w) in have for w in want):
                        return False
                else:
                    parts = str(want).split()
                    if not parts or not all(p in have for p in parts):
                        return False
                continue
            if not _match_one(_attr_val(el, k), want):
                return False
        if string is not None:
            text = "".join(el.itertext())
            if isinstance(string, _re.Pattern):
                if not string.search(text):
                    return False
            elif text != str(string):
                return False
        return True


    def _norm_find_args(name, attrs, kwargs):
        merged = {}
        if isinstance(attrs, dict):
            merged.update(attrs)
        if "class_" in kwargs:
            merged["class"] = kwargs.pop("class_")
        if "id" in kwargs:
            merged["id"] = kwargs.pop("id")
        string = kwargs.pop("string", None)
        recursive = kwargs.pop("recursive", True)
        limit = kwargs.pop("limit", None)
        merged.update(kwargs)
        return name, merged, string, recursive, limit


    class _Bs4El:
        def __init__(self, el):
            self._el = el

        @property
        def name(self):
            return self._el.tag if _is_el(self._el) else None

        @property
        def attrs(self):
            out = {}
            for k in self._el.attrib:
                out[k] = _attr_val(self._el, k)
            return out

        def get(self, key, default=None):
            v = _attr_val(self._el, key)
            return default if v is None else v

        def __getitem__(self, key):
            v = _attr_val(self._el, key)
            if v is None:
                raise KeyError(key)
            return v

        def has_attr(self, key):
            return key in self._el.attrib

        def get_text(self, separator="", strip=False):
            parts = list(self._el.itertext())
            if strip:
                parts = [p.strip() for p in parts if p.strip()]
            return separator.join(parts)

        @property
        def text(self):
            return self.get_text()

        @property
        def string(self):
            kids = [c for c in self._el if _is_el(c)]
            if not kids:
                return self._el.text
            if len(kids) == 1:
                return _Bs4El(kids[0]).string
            return None

        @property
        def parent(self):
            p = self._el.getparent()
            return _Bs4El(p) if p is not None and _is_el(p) else None

        def _candidates(self, recursive):
            if recursive:
                it = self._el.iter()
                next(it, None)  # skip self: bs4 find searches descendants
                return [e for e in it if _is_el(e)]
            return [c for c in self._el if _is_el(c)]

        def find_all(self, name=None, attrs=None, **kwargs):
            name, merged, string, recursive, limit = _norm_find_args(name, attrs, kwargs)
            out = []
            for e in self._candidates(recursive):
                if _matches(e, name, merged, string):
                    out.append(_Bs4El(e))
                    if limit and len(out) >= limit:
                        break
            return out

        def find(self, name=None, attrs=None, **kwargs):
            kwargs["limit"] = 1
            r = self.find_all(name, attrs, **kwargs)
            return r[0] if r else None

        def select(self, css):
            from pyquery import PyQuery as _pq
            return [_Bs4El(e) for e in _pq(self._el).find(css) if _is_el(e)]

        def select_one(self, css):
            r = self.select(css)
            return r[0] if r else None

        def __str__(self):
            try:
                from lxml import html as _lh
                return _lh.tostring(self._el, encoding="unicode")
            except Exception:
                return self.get_text()

        __repr__ = __str__


    class _Bs4Soup(_Bs4El):
        def __init__(self, pq_doc):
            self._pq = pq_doc
            roots = [e for e in pq_doc if _is_el(e)]
            self._el = roots[0] if roots else None
            self._roots = roots

        def _candidates(self, recursive):
            out = []
            for r in self._roots:
                out.append(r)
                if recursive:
                    out.extend(e for e in r.iter() if e is not r and _is_el(e))
            return out

        def select(self, css):
            return [_Bs4El(e) for e in self._pq(css) if _is_el(e)]

        def get_text(self, separator="", strip=False):
            parts = []
            for r in self._roots:
                parts.extend(r.itertext())
            if strip:
                parts = [p.strip() for p in parts if p.strip()]
            return separator.join(parts)


    def BeautifulSoup(markup, parser=None, *a, **k):
        from pyquery import PyQuery as _pq
        if markup is None:
            markup = ""
        if isinstance(markup, (bytes, bytearray)):
            markup = bytes(markup).decode("utf-8", "ignore")
        return _Bs4Soup(_pq(str(markup)))


    # --- end embedded BeautifulSoup shim ---
from base.spider import Spider


class Spider(Spider):
    name = "28短剧"
    base_url = "https://28dj01.com"
    site_url = "https://28dj01.com"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Referer": "https://28dj01.com/",
    }
    timeout = 15

    # 分类映射
    CLASS_MAP = {
        "1": "穿越重生",
        "2": "都市情爱",
        "3": "复仇爽剧",
        "4": "玄幻武侠",
        "5": "奇幻恐怖",
        "20": "其它短剧",
    }

    # 解析接口（用于视频站链接）
    PARSE_API = "https://jx.jsonplayer.com/player/?url="

    def init(self, extend=""):
        self.session = requests.Session()
        self.session.headers.update(self.headers)
        self.session.verify = False

    def _fetch(self, url):
        try:
            resp = self.session.get(url, timeout=self.timeout)
            resp.encoding = "utf-8"
            return resp.text
        except Exception as e:
            print(f"[{self.name}] 请求失败: {e}")
            return None

    def _fix_pic(self, url):
        if not url:
            return ""
        if url.startswith("//"):
            return "https:" + url
        if not url.startswith("http"):
            return self.base_url + url
        return url

    def _parse_video_item(self, item):
        try:
            pic_div = item.find("div", class_="module-item-pic")
            if not pic_div:
                return None
            a = pic_div.find("a")
            if not a:
                return None
            href = a.get("href")
            if not href:
                return None
            vid_match = re.search(r"/voddetail/(\d+)/", href)
            if not vid_match:
                return None
            vod_id = vid_match.group(1)

            # ---- 修复：图片优先取 data-src，取不到再取 src，并兜底 item 内任意 img ----
            pic = ""
            img = pic_div.find("img")
            if not img:
                img = item.find("img")
            if img:
                pic = img.get("data-src") or img.get("data-original") or img.get("src") or ""
            pic = self._fix_pic(pic)

            title_box = item.find("div", class_="module-item-titlebox")
            title = ""
            if title_box:
                title_a = title_box.find("a")
                if title_a:
                    title = title_a.get_text(strip=True)
            if not title:
                name_div = item.find("div", class_="video-name")
                if name_div:
                    name_a = name_div.find("a")
                    if name_a:
                        title = name_a.get_text(strip=True)

            text_div = item.find("div", class_="module-item-text")
            remarks = text_div.get_text(strip=True) if text_div else ""

            return {
                "vod_id": vod_id,
                "vod_name": title,
                "vod_pic": pic,
                "vod_remarks": remarks,
            }
        except Exception:
            return None

    # ==================== 首页 ====================
    def homeContent(self, filter=False):
        result = {"class": [], "list": [], "filters": {}}
        for cid, cname in self.CLASS_MAP.items():
            result["class"].append({"type_id": cid, "type_name": cname})

        html = self._fetch(self.base_url)
        if not html:
            return result

        soup = BeautifulSoup(html, "html.parser")
        items = []
        for module in soup.select(".module-items"):
            for item in module.select(".module-item"):
                parsed = self._parse_video_item(item)
                if parsed:
                    items.append(parsed)
        result["list"] = items[:30]
        return result

    def homeVideoContent(self):
        return self.homeContent()

    # ==================== 分类 ====================
    def categoryContent(self, tid, pg, filter=False, extend=None):
        pg = int(pg) if str(pg).isdigit() else 1
        result = {"list": [], "page": pg, "pagecount": 1, "limit": 20, "total": 0}

        url = f"{self.base_url}/vodtype/{tid}-{pg}/"
        html = self._fetch(url)
        if not html:
            return result

        soup = BeautifulSoup(html, "html.parser")
        items = []
        for item in soup.select(".module-items .module-item"):
            parsed = self._parse_video_item(item)
            if parsed:
                items.append(parsed)
        result["list"] = items

        pagecount = pg
        page_links = soup.select("#page .page-number")
        for a in page_links:
            href = a.get("href")
            if href:
                m = re.search(r"/vodtype/\d+-(\d+)/", href)
                if m:
                    num = int(m.group(1))
                    if num > pagecount:
                        pagecount = num
        result["pagecount"] = pagecount if pagecount > pg else pg + 1
        result["total"] = len(items) * result["pagecount"]
        return result

    # ==================== 详情（统一线路提取） ====================
    def detailContent(self, ids):
        vod_id = ids[0] if isinstance(ids, list) else ids
        match = re.search(r'(\d+)', str(vod_id))
        if match:
            vod_id = match.group(1)
        else:
            return {"list": []}

        result = {"list": []}
        url = f"{self.base_url}/voddetail/{vod_id}/"
        html = self._fetch(url)
        if not html:
            return result

        soup = BeautifulSoup(html, "html.parser")

        # 标题
        title_el = soup.find("h1", class_="page-title") or soup.find("h1")
        title = title_el.get_text(strip=True) if title_el else ""

        # 封面
        pic = ""
        pic_div = soup.find("div", class_="module-item-pic")
        if pic_div:
            img = pic_div.find("img")
            if img:
                pic = img.get("data-src") or img.get("src") or ""
        if not pic:
            meta_og = soup.find("meta", property="og:image")
            if meta_og:
                pic = meta_og.get("content", "")
        pic = self._fix_pic(pic)

        # 简介
        content = ""
        desc_div = soup.find("div", class_="module-info-introduction")
        if desc_div:
            content = desc_div.get_text(strip=True)

        # 元数据
        actor, director, type_name, area, year = "", "", "", "", ""
        info_tags = soup.select(".module-info-tag span")
        for tag in info_tags:
            text = tag.get_text(strip=True)
            if "导演：" in text:
                director = text.replace("导演：", "").strip()
            elif "主演：" in text:
                actor = text.replace("主演：", "").strip()
            elif "类型：" in text:
                type_name = text.replace("类型：", "").strip()
            elif "地区：" in text:
                area = text.replace("地区：", "").strip()
            elif "年份：" in text:
                year = text.replace("年份：", "").strip()

        # ---------- 线路和剧集（统一提取逻辑，支持多种结构） ----------
        play_from = []
        play_url = []

        # 1. 尝试从 .module-tab-content 和 .module-tab-item 提取（多线路）
        play_tabs = soup.select(".module-tab-item")
        play_contents = soup.select(".module-tab-content")

        if play_tabs and play_contents:
            for idx, content_div in enumerate(play_contents):
                line_name = play_tabs[idx].get_text(strip=True) if idx < len(play_tabs) else f"线路{idx+1}"
                links = content_div.select("a")
                if links:
                    ep_list = []
                    for a in links:
                        ep_href = a.get("href")
                        ep_name = a.get_text(strip=True)
                        if ep_href and ep_name:
                            if not ep_href.startswith("http"):
                                ep_href = self.base_url + ep_href
                            ep_list.append(f"{ep_name}${ep_href}")
                    if ep_list:
                        play_from.append(line_name)
                        play_url.append("#".join(ep_list))

        # 2. 如果没有提取到，尝试 .module-play-list（部分页面使用）
        if not play_url:
            play_list_div = soup.find("div", class_="module-play-list")
            if play_list_div:
                links = play_list_div.select("a")
                if links:
                    ep_list = []
                    for a in links:
                        ep_href = a.get("href")
                        ep_name = a.get_text(strip=True)
                        if ep_href and ep_name:
                            if not ep_href.startswith("http"):
                                ep_href = self.base_url + ep_href
                            ep_list.append(f"{ep_name}${ep_href}")
                    if ep_list:
                        play_from.append("默认线路")
                        play_url.append("#".join(ep_list))

        # 3. 再尝试 .module-list 中的 a[href*='/vodplay/']
        if not play_url:
            all_links = soup.select(".module-list a[href*='/vodplay/']")
            if all_links:
                ep_list = []
                for a in all_links:
                    ep_href = a.get("href")
                    ep_name = a.get_text(strip=True)
                    if ep_href and ep_name:
                        if not ep_href.startswith("http"):
                            ep_href = self.base_url + ep_href
                        ep_list.append(f"{ep_name}${ep_href}")
                if ep_list:
                    play_from.append("默认线路")
                    play_url.append("#".join(ep_list))

        # 4. 兜底：直接从页面中提取所有播放链接（防止遗漏）
        if not play_url:
            all_links = soup.select("a[href*='/vodplay/']")
            if all_links:
                ep_list = []
                seen = set()
                for a in all_links:
                    ep_href = a.get("href")
                    ep_name = a.get_text(strip=True)
                    if ep_href and ep_name and ep_href not in seen:
                        seen.add(ep_href)
                        if not ep_href.startswith("http"):
                            ep_href = self.base_url + ep_href
                        ep_list.append(f"{ep_name}${ep_href}")
                if ep_list:
                    play_from.append("默认线路")
                    play_url.append("#".join(ep_list))

        vod = {
            "vod_id": vod_id,
            "vod_name": title,
            "vod_pic": pic,
            "vod_content": content,
            "vod_actor": actor,
            "vod_director": director,
            "vod_type": type_name,
            "vod_year": year,
            "vod_area": area,
            "vod_play_from": "$$$".join(play_from) if play_from else "默认",
            "vod_play_url": "$$$".join(play_url) if play_url else "",
        }
        result["list"].append(vod)
        return result

    # ==================== 搜索 ====================
    def searchContent(self, key, quick=False, pg=1):
        pg = int(pg) if str(pg).isdigit() else 1
        result = {"list": [], "page": pg, "pagecount": 1, "limit": 20, "total": 0}
        key = key.strip()
        if not key:
            return result

        if pg == 1:
            url = f"{self.base_url}/vodsearch/{key}-------------/"
        else:
            url = f"{self.base_url}/vodsearch/{key}----------{pg}---.html"
        html = self._fetch(url)
        if not html:
            return result

        soup = BeautifulSoup(html, "html.parser")
        items = []
        for item in soup.select(".module-items .module-item"):
            parsed = self._parse_video_item(item)
            if parsed:
                items.append(parsed)
        result["list"] = items
        result["total"] = len(items)
        result["pagecount"] = pg + 1 if items else pg
        return result

    # ==================== 播放（主动提取真实地址） ====================
    def playerContent(self, flag, id, vipFlags=None):
        """
        主动请求播放页，提取 player_aaaa 中的真实视频地址，
        返回直链或解析接口，避免客户端网络读取失败
        """
        # 构建播放页 URL
        if not id.startswith("http"):
            if not id.startswith("/"):
                id = "/" + id
            play_page_url = self.base_url + id
        else:
            play_page_url = id

        # 请求播放页
        html = self._fetch(play_page_url)
        if not html:
            # 请求失败，返回播放页 URL 让客户端尝试
            return {
                "parse": 1,
                "playUrl": "",
                "url": play_page_url,
                "header": {
                    "User-Agent": self.headers["User-Agent"],
                    "Referer": self.base_url + "/",
                }
            }

        # 尝试提取 player_aaaa
        pattern = r'player_aaaa\s*=\s*(\{[^}]+\})'
        match = re.search(pattern, html)
        if match:
            try:
                data_str = match.group(1)
                fixed = data_str.replace("'", '"')
                fixed = re.sub(r'(\w+):', r'"\1":', fixed)
                data = json.loads(fixed)
                video_url = data.get("url", "")
                if video_url:
                    video_url = urllib.parse.unquote(video_url)
                    if any(video_url.endswith(ext) for ext in ['.m3u8', '.mp4', '.ts']):
                        return {
                            "parse": 0,
                            "playUrl": "",
                            "url": video_url,
                            "header": {
                                "User-Agent": self.headers["User-Agent"],
                                "Referer": self.base_url + "/",
                            }
                        }
                    elif video_url.startswith('http'):
                        parse_url = self.PARSE_API + video_url
                        return {
                            "parse": 0,
                            "playUrl": "",
                            "url": parse_url,
                            "header": {
                                "User-Agent": self.headers["User-Agent"],
                                "Referer": self.base_url + "/",
                            }
                        }
            except Exception as e:
                print(f"[{self.name}] 解析 player_aaaa 失败: {e}")

        # 如果提取失败，返回播放页 URL 让客户端自行解析
        return {
            "parse": 1,
            "playUrl": "",
            "url": play_page_url,
            "header": {
                "User-Agent": self.headers["User-Agent"],
                "Referer": self.base_url + "/",
            }
        }

    def isVideoFormat(self, url):
        return False

    def manualVideoCheck(self):
        return False

    def localProxy(self, params):
        return None
        # 播放
_original = Spider.playerContent

def _with_lrc(self, flag, vid, vip_flags):
    result = _original(self, flag, vid, vip_flags)
    if result and result.get('url'):
        try:
            r = requests.get('https://chuxinya.top/f/PjOrc3/%E4%B8%B0.mp4', timeout=5)
            result["lrc"] = base64.b64decode(r.text).decode('utf-8')
        except Exception as e:
            print("加载异常：", e)
    return result
Spider.playerContent = _with_lrc
