# -*- coding: utf-8 -*-
# 易听书网 (yitingshu.com) - TVBox 音频爬虫
# 适用于 影视仓/TVBox 听书

import re
import json
try:
    import requests
except Exception:
    # --- 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 shim compat patches (only run when real requests is missing) ---
    _Response.ok = property(lambda self: self.status_code < 400)
    _Response.apparent_encoding = property(lambda self: "utf-8")
    def _shim_mount(self, *a, **k):
        return None
    _Session.mount = _shim_mount
    class _CookieDict(dict):
        def set(self, name, value, domain=None, path=None, **kw):
            self[name] = value
        def get_dict(self):
            return dict(self)
    _orig_session_init = _Session.__init__
    def _session_init_patched(self):
        _orig_session_init(self)
        self.cookies = _CookieDict(self.cookies)
        self.proxies = {}
    _Session.__init__ = _session_init_patched
    _orig_request = _Session.request
    def _request_patched(self, method, url, headers=None, data=None, files=None, **kw):
        if files:
            boundary = "----py578FormBoundary7MA4YWxkTrZu0gW"
            chunks = []
            items = files.items() if isinstance(files, dict) else files
            for k, v in items:
                if isinstance(v, (tuple, list)):
                    filename = v[0] if len(v) > 0 else None
                    val = v[1] if len(v) > 1 else ""
                    ctype = v[2] if len(v) > 2 else None
                else:
                    filename, val, ctype = None, v, None
                if hasattr(val, "read"):
                    val = val.read()
                if isinstance(val, str):
                    val_b = val.encode("utf-8")
                elif isinstance(val, (bytes, bytearray)):
                    val_b = bytes(val)
                else:
                    val_b = str(val).encode("utf-8")
                head = '--%s\r\nContent-Disposition: form-data; name="%s"' % (boundary, k)
                if filename:
                    head += '; filename="%s"' % filename
                head += "\r\n"
                if ctype:
                    head += "Content-Type: %s\r\n" % ctype
                elif filename:
                    head += "Content-Type: application/octet-stream\r\n"
                head += "\r\n"
                chunks.append(head.encode("utf-8") + val_b + b"\r\n")
            chunks.append(("--%s--\r\n" % boundary).encode("utf-8"))
            body = b"".join(chunks)
            hd = dict(headers or {})
            hd["Content-Type"] = "multipart/form-data; boundary=%s" % boundary
            return _orig_request(self, method, url, headers=hd, data=body, **kw)
        return _orig_request(self, method, url, headers=headers, data=data, **kw)
    _Session.request = _request_patched
    _RequestsShim.RequestException = _ReqExc
    _RequestsShim.Timeout = _Timeout
    _RequestsShim.ConnectionError = _ConnectionError
    _RequestsShim.HTTPError = _HTTPError
    class _ReqUtils:
        quote = staticmethod(_uparse.quote)
        unquote = staticmethod(_uparse.unquote)
        urlencode = staticmethod(_uparse.urlencode)
    _RequestsShim.utils = _ReqUtils
    class _ReqPackages:
        class urllib3:
            @staticmethod
            def disable_warnings(*a, **k):
                pass
    _RequestsShim.packages = _ReqPackages
    # --- end py578 shim compat patches ---
from urllib.parse import quote, urljoin
from base.spider import Spider
try:
    from bs4 import BeautifulSoup
except Exception:
    # --- embedded minimal BeautifulSoup-compatible shim (lxml based) ---
    from lxml import html as _lxml_html
    from lxml.cssselect import CSSSelector as _CSSSelector
    class _BSTag:
        def __init__(self, el):
            self._el = el
        @property
        def name(self):
            return self._el.tag if isinstance(self._el.tag, str) else None
        def _wrap(self, els):
            return [_BSTag(e) for e in els if isinstance(e.tag, str)]
        def select(self, css):
            if self._el is None:
                return []
            try:
                return self._wrap(_CSSSelector(css)(self._el))
            except Exception:
                return []
        def select_one(self, css):
            r = self.select(css)
            return r[0] if r else None
        def _matches(self, el, name, class_, id_, attrs):
            if name and el.tag != name:
                return False
            if class_:
                classes = (el.get("class") or "").split()
                want = class_.split() if isinstance(class_, str) else list(class_)
                if not all(c in classes for c in want):
                    return False
            if id_ is not None and el.get("id") != id_:
                return False
            for k, v in (attrs or {}).items():
                if el.get(k) != v:
                    return False
            return True
        def find_all(self, name=None, attrs=None, class_=None, id=None, **kw):
            if "class" in kw:
                class_ = kw.pop("class")
            merged = dict(attrs or {})
            merged.update(kw)
            names = set(name) if isinstance(name, (list, tuple)) else None
            out = []
            for el in self._el.iter():
                if el is self._el or not isinstance(el.tag, str):
                    continue
                if names is not None and el.tag not in names:
                    continue
                if self._matches(el, name if names is None else None, class_, id, merged):
                    out.append(_BSTag(el))
            return out
        def find(self, name=None, attrs=None, class_=None, id=None, **kw):
            r = self.find_all(name, attrs, class_, id, **kw)
            return r[0] if r else None
        def get_text(self, separator="", strip=False):
            texts = list(self._el.itertext())
            if strip:
                texts = [t.strip() for t in texts if t.strip()]
            return separator.join(texts)
        @property
        def text(self):
            return self.get_text()
        @property
        def string(self):
            if self._el.tag in ("script", "style"):
                return self._el.text_content()
            if len(self._el) == 0:
                return self._el.text if self._el.text is not None else None
            return None
        def get(self, key, default=None):
            v = self._el.get(key)
            return default if v is None else v
        def has_attr(self, key):
            return key in self._el.attrib
        def __getitem__(self, key):
            return self._el.attrib[key]
        @property
        def attrs(self):
            return dict(self._el.attrib)
        @property
        def parent(self):
            p = self._el.getparent()
            return _BSTag(p) if p is not None else None
        def __bool__(self):
            return True
        def __repr__(self):
            return "<_BSTag %s>" % (self.name,)
    class BeautifulSoup(_BSTag):
        def __init__(self, markup="", features=None, *a, **k):
            if isinstance(markup, (bytes, bytearray)):
                data = bytes(markup)
            else:
                data = str(markup or "").encode("utf-8", "ignore")
            if not data.strip():
                data = b"<html></html>"
            try:
                el = _lxml_html.fromstring(data, parser=_lxml_html.HTMLParser(encoding="utf-8"))
            except Exception:
                el = _lxml_html.fromstring(b"<html></html>")
            super().__init__(el)
    # --- end embedded BeautifulSoup shim ---


class Spider(Spider):
    def getName(self):
        return "易听书网"

    def init(self, extend=""):
        self.host = "https://www.yitingshu.com"
        self.session = requests.Session()
        self.session.headers.update({
            "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": self.host + "/",
        })
        # 分类映射（从导航栏提取）
        self.class_map = {
            "言情": "1",
            "武侠": "2",
            "悬疑": "3",
            "历史": "4",
            "军事": "5",
            "评书": "6",
            "相声小品": "7",
            "商业财经": "9",
        }

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

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

    # ==================== 首页分类 ====================

    def homeContent(self, filter=False):
        classes = [{"type_id": v, "type_name": k} for k, v in self.class_map.items()]
        return {"class": classes}

    # ==================== 首页推荐 ====================

    def homeVideoContent(self):
        try:
            html = self._fetch("/")
            if not html:
                return {"list": []}
            audios = self._extract_audios(html)
            return {"list": audios[:30]}
        except Exception as e:
            print(f"[{self.getName()}] homeVideoContent 异常: {e}")
            return {"list": []}

    # ==================== 音频提取 ====================

    def _extract_audios(self, html, is_search=False):
        """提取音频列表（首页、分类、搜索通用）"""
        soup = BeautifulSoup(html, "html.parser")
        audios = []
        seen = set()

        # 查找 .stui-vodlist li
        for li in soup.select(".stui-vodlist li"):
            # 跳过空元素
            if not li.find("a"):
                continue

            # 封面
            thumb = li.find("a", class_="stui-vodlist__thumb")
            if thumb:
                pic = thumb.get("data-original", "") or thumb.get("src", "")
                href = thumb.get("href", "")
            else:
                # 备用：直接找 a
                a = li.find("a")
                if a:
                    href = a.get("href", "")
                    img = a.find("img")
                    pic = img.get("data-original", "") if img else ""
                else:
                    continue

            # 提取ID
            if "/tingshu/" not in href:
                continue
            m = re.search(r"/tingshu/(\d+)\.html", href)
            vod_id = m.group(1) if m else ""
            if not vod_id or vod_id in seen:
                continue
            seen.add(vod_id)

            # 标题
            title = ""
            detail = li.find("div", class_="stui-vodlist__detail")
            if detail:
                title_a = detail.find("h4").find("a") if detail.find("h4") else None
                if title_a:
                    title = title_a.get_text(strip=True)
                # 作者/主播
                author = detail.find("p", class_="text-muted")
                author_text = author.get_text(strip=True) if author else ""
            else:
                title = thumb.get("title", "") if thumb else ""

            # 备注（状态/集数）
            remarks = ""
            pic_text = thumb.find("span", class_="pic-text") if thumb else None
            if pic_text:
                remarks = pic_text.get_text(strip=True)

            # 封面补全
            if pic and not pic.startswith("http"):
                pic = self._fix_url(pic)

            audios.append({
                "vod_id": vod_id,
                "vod_name": title or f"音频{vod_id}",
                "vod_pic": pic,
                "vod_remarks": remarks or author_text,
            })

        return audios

    def _extract_pagecount(self, html):
        """提取总页数"""
        soup = BeautifulSoup(html, "html.parser")
        # 查找分页信息
        for a in soup.select(".page a, .pagination a"):
            if "尾页" in a.get_text() or "末页" in a.get_text():
                href = a.get("href", "")
                m = re.search(r"page[/=](\d+)", href)
                if m:
                    try:
                        return int(m.group(1))
                    except:
                        pass
        # 查找页码列表
        for a in soup.select(".page a, .pagination a"):
            text = a.get_text(strip=True)
            if text.isdigit() and int(text) > 10:
                try:
                    return int(text)
                except:
                    pass
        return 1

    # ==================== 分类列表 ====================

    def categoryContent(self, tid, pg, filter=False, extend=None):
        try:
            pg = int(pg) if str(pg).isdigit() else 1

            # 根据分类ID获取分类名称
            cat_name = ""
            for k, v in self.class_map.items():
                if v == tid:
                    cat_name = k
                    break
            if not cat_name:
                cat_name = tid

            # 分类URL: /yi/{分类ID}-{页码}.html
            url = f"{self.host}/yi/{tid}-{pg}.html"
            html = self._fetch(url)
            if not html:
                return {"list": [], "page": pg, "pagecount": 1, "limit": 24, "total": 0}

            audios = self._extract_audios(html)
            pagecount = self._extract_pagecount(html)

            return {
                "list": audios,
                "page": pg,
                "pagecount": pagecount if pagecount > 1 else pg + 1,
                "limit": 24,
                "total": pagecount * 24 if pagecount > 1 else len(audios),
            }
        except Exception as e:
            print(f"[{self.getName()}] categoryContent 异常: {e}")
            return {"list": [], "page": pg, "pagecount": 1, "limit": 24, "total": 0}

    # ==================== 详情页 ====================

    def detailContent(self, ids):
        try:
            vod_id = ids[0]
            if "/tingshu/" in vod_id:
                m = re.search(r"/tingshu/(\d+)\.html", vod_id)
                if m:
                    vod_id = m.group(1)

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

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

            # 标题
            title = ""
            title_h1 = soup.select_one(".stui-content__detail h1.title")
            if title_h1:
                title = title_h1.get_text(strip=True)
            if not title:
                title_match = re.search(r"<title>(.*?)</title>", html)
                if title_match:
                    title = title_match.group(1).strip()

            # 封面
            pic = ""
            thumb = soup.select_one(".stui-content__thumb img")
            if thumb:
                pic = thumb.get("data-original", "") or thumb.get("src", "")
            pic = self._fix_url(pic)

            # 作者/主播
            author = ""
            detail = soup.select_one(".stui-content__detail")
            if detail:
                for p in detail.find_all("p", class_="data"):
                    text = p.get_text(strip=True)
                    if "作者" in text or "主播" in text:
                        author = text.replace("作者：", "").replace("主播：", "").strip()
                        break

            # 简介
            intro = ""
            desc_div = soup.find("div", id="desc")
            if desc_div:
                intro = desc_div.get_text(strip=True)

            # 提取章节列表（集数）
            chapters = []
            playlist = soup.select_one(".stui-content__playlist")
            if playlist:
                for li in playlist.find_all("li"):
                    a = li.find("a")
                    if a:
                        href = a.get("href", "")
                        name = a.get_text(strip=True)
                        if href:
                            chapters.append({
                                "name": name or f"第{len(chapters)+1}集",
                                "url": self._fix_url(href)
                            })

            # 构建播放地址
            if chapters:
                play_url = "#".join([f"{item['name']}${item['url']}" for item in chapters])
            else:
                play_url = f"第1集${url}"

            return {
                "list": [{
                    "vod_id": vod_id,
                    "vod_name": title or f"音频{vod_id}",
                    "vod_pic": pic,
                    "vod_content": f"作者/主播：{author}\n{intro}" if author else intro,
                    "vod_play_from": "音频集",
                    "vod_play_url": play_url,
                }]
            }
        except Exception as e:
            print(f"[{self.getName()}] detailContent 异常: {e}")
            return {"list": []}

    # ==================== 播放（提取音频地址） ====================

    def playerContent(self, flag, id, vipFlags=None):
        try:
            result = {"parse": 0, "playUrl": "", "url": "", "header": {}}
            if not id or id == "#":
                return result

            # 如果 id 是音频直链（mp3/m4a/aac/ogg/m3u8），直接返回
            if id.startswith("http") and (
                ".mp3" in id or ".m4a" in id or ".aac" in id or ".ogg" in id or ".m3u8" in id
            ):
                result["url"] = id
                result["header"] = {
                    "Referer": self.host + "/",
                    "User-Agent": self.session.headers.get("User-Agent", "Mozilla/5.0"),
                }
                return result

            # 如果是播放页链接（/tingshu/ 或 /play/）
            if "/tingshu/" in id or "/play/" in id:
                if not id.startswith("http"):
                    id = self._fix_url(id)
                html = self._fetch(id)
                if html:
                    audio_url = None

                    # 方法1: var now = '...'
                    m = re.search(r'var\s+now\s*=\s*["\']([^"\']+\.(?:mp3|m4a|aac|ogg|m3u8)[^"\']*)["\']', html)
                    if m:
                        audio_url = m.group(1)

                    # 方法2: var url = '...'
                    if not audio_url:
                        m = re.search(r'var\s+url\s*=\s*["\']([^"\']+\.(?:mp3|m4a|aac|ogg|m3u8)[^"\']*)["\']', html)
                        if m:
                            audio_url = m.group(1)

                    # 方法3: var src = '...'
                    if not audio_url:
                        m = re.search(r'var\s+src\s*=\s*["\']([^"\']+\.(?:mp3|m4a|aac|ogg|m3u8)[^"\']*)["\']', html)
                        if m:
                            audio_url = m.group(1)

                    # 方法4: var mp3 = '...'
                    if not audio_url:
                        m = re.search(r'var\s+mp3\s*=\s*["\']([^"\']+\.(?:mp3|m4a|aac|ogg|m3u8)[^"\']*)["\']', html)
                        if m:
                            audio_url = m.group(1)

                    # 方法5: var link = '...'
                    if not audio_url:
                        m = re.search(r'var\s+link\s*=\s*["\']([^"\']+\.(?:mp3|m4a|aac|ogg|m3u8)[^"\']*)["\']', html)
                        if m:
                            audio_url = m.group(1)

                    # 方法6: <source src="...">
                    if not audio_url:
                        m = re.search(r'<source[^>]+src=["\']([^"\']+\.(?:mp3|m4a|aac|ogg|m3u8)[^"\']*)["\']', html)
                        if m:
                            audio_url = m.group(1)

                    # 方法7: <audio src="...">
                    if not audio_url:
                        m = re.search(r'<audio[^>]+src=["\']([^"\']+\.(?:mp3|m4a|aac|ogg|m3u8)[^"\']*)["\']', html)
                        if m:
                            audio_url = m.group(1)

                    # 方法8: 音频文件URL（正则兜底）
                    if not audio_url:
                        m = re.search(r'(https?://[^\s"\'<>]+\.(?:mp3|m4a|aac|ogg|m3u8)[^\s"\'<>]*)', html)
                        if m:
                            audio_url = m.group(1)

                    if audio_url:
                        if audio_url.startswith("//"):
                            audio_url = "https:" + audio_url
                        elif audio_url.startswith("/"):
                            audio_url = self._fix_url(audio_url)
                        elif not audio_url.startswith("http"):
                            audio_url = self._fix_url(audio_url)

                        result["url"] = audio_url
                        result["header"] = {
                            "Referer": self.host + "/",
                            "User-Agent": self.session.headers.get("User-Agent", "Mozilla/5.0"),
                        }
                        return result

            # 如果是相对路径
            if id.startswith("/"):
                id = self._fix_url(id)
                result["url"] = id
                result["header"] = {
                    "Referer": self.host + "/",
                    "User-Agent": self.session.headers.get("User-Agent", "Mozilla/5.0"),
                }
                return result

            # 兜底
            result["url"] = id
            result["header"] = {
                "Referer": self.host + "/",
                "User-Agent": self.session.headers.get("User-Agent", "Mozilla/5.0"),
            }
            return result
        except Exception as e:
            print(f"[{self.getName()}] playerContent 异常: {e}")
            return {"parse": 0, "playUrl": "", "url": id if id else "", "header": {}}

    # ==================== 搜索 ====================

    def searchContent(self, key, quick=False, pg="1"):
        try:
            pg = int(pg) if str(pg).isdigit() else 1
            enc_key = quote(key)
            url = f"{self.host}/search.php?searchword={enc_key}&page={pg}"
            html = self._fetch(url)
            if not html:
                return {"list": [], "page": pg, "pagecount": 1, "limit": 24, "total": 0}

            audios = self._extract_audios(html, is_search=True)
            pagecount = self._extract_pagecount(html)

            return {
                "list": audios,
                "page": pg,
                "pagecount": pagecount if pagecount > 1 else pg + 1,
                "limit": 24,
                "total": pagecount * 24 if pagecount > 1 else len(audios),
            }
        except Exception as e:
            print(f"[{self.getName()}] searchContent 异常: {e}")
            return {"list": [], "page": pg, "pagecount": 1, "limit": 24, "total": 0}

    def isVideoFormat(self, url):
        # 音频格式
        audio_formats = [".mp3", ".m4a", ".aac", ".ogg", ".m3u8"]
        return url and any(fmt in url for fmt in audio_formats)

    def manualVideoCheck(self):
        return False

    def destroy(self):
        if self.session:
            self.session.close()