# -*- coding: utf-8 -*-
# 兼容 OK影视/影视仓   
# 其它影视壳自测

from base.spider import Spider
# [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 re
# [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 urllib.parse import quote


class Spider(Spider):
    def getName(self):
        return "DJ呦呦"

    def init(self, extend=""):
        pass

    def isVideoFormat(self, url):
        return False

    def manualVideoCheck(self):
        return False

    def homeContent(self, filter):
        result = {}
        result['filters'] = {}
        cateId = [
            {"type_name": "最近更新-专辑", "type_id": "ablum_i1"},
            {"type_name": "最新加入-专辑", "type_id": "ablum_i2"},
            {"type_name": "热门DJ-专辑", "type_id": "ablum_i3"},
            {"type_name": "独家舞曲", "type_id": "exclusive_115"},
            {"type_name": "迪高串烧", "type_id": "djlist_1"},
            {"type_name": "慢摇串烧", "type_id": "djlist_2"},
            {"type_name": "慢歌串烧", "type_id": "djlist_3"},
            {"type_name": "中文Remix", "type_id": "djlist_4"},
            {"type_name": "外文Remix", "type_id": "djlist_5"},
            {"type_name": "中文DISCO", "type_id": "djlist_9"},
            {"type_name": "外文DISCO", "type_id": "djlist_10"}
        ]
        result['class'] = cateId
        return result

    def homeVideoContent(self):
        return self.categoryContent("ablum_i1", 1, False, {})

    # ---------- 分类列表 ----------

    def categoryContent(self, tid, pg, filter, extend):
        result = {
            'list': [],
            'page': pg,
            'pagecount': 9999,
            'limit': 30,
            'total': 999999
        }
        path, cid = self._split_type(tid)

        try:
            if path == 'ablum':
                videos = self._category_ablum(cid, pg)
            elif path == 'exclusive':
                videos = self._category_songlist('exclusive', cid, pg)
            elif path == 'djlist':
                videos = self._category_songlist('djlist', cid, pg)
            else:
                videos = []

            result['list'] = videos
        except Exception:
            pass

        return result

    def _split_type(self, tid):
        # 格式: ablum_i1, exclusive_115, djlist_1
        if '_' in tid:
            path, cid = tid.split('_', 1)
            return path, cid
        return 'ablum', tid

    def _category_ablum(self, cid, pg):
        url = f"https://www.djuu.com/ablum/{cid}_{pg}.html"
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Referer': 'https://www.djuu.com/ablum/'
        }
        r = requests.get(url, headers=headers, timeout=10)
        r.encoding = 'utf-8'
        soup = BeautifulSoup(r.text, 'html.parser')

        videos = []
        container = soup.select_one('.djshow_contentlist')
        if container:
            for table in container.find_all('table', recursive=False):
                rows = table.find_all('tr')
                if not rows:
                    continue

                first_row = rows[0]
                img_a = first_row.find('a', href=re.compile(r'/ablum/\d+\.html'))
                if not img_a:
                    continue

                img = img_a.find('img')
                pic = (img.get('src') or '') if img else ''
                ablum_url = img_a.get('href', '')
                m = re.search(r'/ablum/(\d+)\.html', ablum_url)
                if not m:
                    continue

                name_a = table.find('a', class_='djshow_contentlist_name')
                name = name_a.get_text(strip=True) if name_a else '未知DJ'

                msgs = table.find_all('td', class_='djshow_contentlist_msg')
                area = msgs[0].get_text(strip=True) if len(msgs) > 0 else ''
                hot = msgs[2].get_text(strip=True) if len(msgs) > 2 else ''
                remarks = f"{area} | 热度:{hot}" if area and hot else (area or hot)

                videos.append({
                    "vod_id": m.group(1),
                    "vod_name": name,
                    "vod_pic": pic,
                    "vod_remarks": remarks
                })
        return videos

    def _category_songlist(self, path, cid, pg):
        url = f"https://www.djuu.com/{path}/{cid}_{pg}.html"
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Referer': f'https://www.djuu.com/{path}/'
        }
        r = requests.get(url, headers=headers, timeout=10)
        r.encoding = 'utf-8'
        soup = BeautifulSoup(r.text, 'html.parser')

        videos = []
        seen = set()
        for div in soup.find_all('div', class_='isgood_list'):
            img_a = div.find('a', href=re.compile(r'/play/\d+\.html'))
            title_a = div.find('p', class_='t1')
            if title_a:
                title_a = title_a.find('a', href=re.compile(r'/play/\d+\.html'))
            if not img_a or not title_a:
                continue

            m = re.search(r'/play/(\d+)\.html', img_a.get('href', ''))
            if not m:
                continue
            sid = m.group(1)
            if sid in seen:
                continue
            seen.add(sid)

            name = title_a.get('title') or title_a.get_text(strip=True)
            img = img_a.find('img')
            pic = (img.get('src') or '') if img else ''
            # 兼容懒加载
            if not pic:
                pic = (img.get('data-src') or '') if img else ''

            # 时长/大小作为备注
            spans = div.find_all('span')
            info = ' | '.join([s.get_text(strip=True) for s in spans[:3]])

            videos.append({
                "vod_id": f"song_{sid}",
                "vod_name": name,
                "vod_pic": pic,
                "vod_remarks": info
            })
        return videos

    # ---------- 详情 ----------

    def detailContent(self, ids):
        rid = ids[0] if isinstance(ids, (list, tuple)) else ids
        result = {}

        try:
            if isinstance(rid, str) and rid.startswith('song_'):
                sid = rid.replace('song_', '', 1)
                vod = self._song_detail(sid)
            else:
                vod = self._ablum_detail(rid)
            result['list'] = [vod]
        except Exception as e:
            result['list'] = [{
                "vod_id": rid,
                "vod_name": "加载失败",
                "vod_content": f"加载失败: {str(e)}",
                "vod_remarks": "加载失败",
                "vod_actor": "未知",
                "vod_play_from": "DJ呦呦",
                "vod_play_url": "",
                "vod_pic": ""
            }]

        return result

    def _ablum_detail(self, rid):
        vod_name, pic, content = self._ablum_info(rid)
        songs = self._ablum_songs(rid)

        play_arr = []
        for song in songs:
            name = re.sub(r'[$#]', '', song.get('name', '')).strip()
            sid = song.get('id', '')
            if name and sid:
                play_arr.append(f"{name}${sid}")

        return {
            "vod_id": rid,
            "vod_name": vod_name,
            "vod_pic": pic,
            "vod_content": content if content else "暂无简介",
            "vod_remarks": f"歌曲 : {len(songs)}首",
            "vod_actor": vod_name,
            "vod_play_from": "DJ呦呦",
            "vod_play_url": "#".join(play_arr)
        }

    def _song_detail(self, sid):
        # 单曲详情：直接进入播放页取信息
        url = f"https://www.djuu.com/play/{sid}.html"
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Referer': 'https://www.djuu.com/'
        }
        r = requests.get(url, headers=headers, timeout=10)
        r.encoding = 'utf-8'
        soup = BeautifulSoup(r.text, 'html.parser')

        # 歌曲名
        name = ''
        h1 = soup.find('h1')
        if h1:
            name = h1.get_text(strip=True)
        if not name:
            m = re.search(r"var music = \{[^}]*name:\s*'([^']+)'", r.text)
            name = m.group(1) if m else '未知歌曲'

        # 封面：优先取播放器区域 / 旋转封面 / 模糊背景，避免取到广告图
        pic = self._extract_play_pic(soup)

        # 简介：取播放页信息
        content = ''
        info = soup.select_one('.djshow_djmsg_content') or soup.select_one('.play_info')
        if info:
            content = info.get_text('\n', strip=True)

        return {
            "vod_id": f"song_{sid}",
            "vod_name": name,
            "vod_pic": pic,
            "vod_content": content if content else "暂无简介",
            "vod_remarks": "单曲",
            "vod_actor": name,
            "vod_play_from": "DJ呦呦",
            "vod_play_url": f"{name}${sid}"
        }

    def _ablum_info(self, rid):
        url = f"https://www.djuu.com/ablum/{rid}.html"
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Referer': 'https://www.djuu.com/ablum/'
        }
        r = requests.get(url, headers=headers, timeout=10)
        r.encoding = 'utf-8'
        soup = BeautifulSoup(r.text, 'html.parser')

        h1 = soup.find('h1')
        vod_name = h1.get_text(strip=True) if h1 else '未知DJ'
        vod_name = re.sub(r'<[^>]+>', '', vod_name)

        pic = ''
        for img in soup.find_all('img', src=re.compile(r'img\.djuu\.com')):
            src = img.get('src') or ''
            pic = src or pic
            if 'ablum' in pic or 'dj_album' in pic:
                break

        content = ''
        info_div = soup.select_one('.djshow_djmsg_content')
        if info_div:
            content = info_div.get_text('\n', strip=True)

        return vod_name, pic, content

    def _ablum_songs(self, rid, max_pages=10, max_songs=300):
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Referer': f'https://www.djuu.com/ablum/{rid}.html'
        }

        songs = []
        for pg in range(1, max_pages + 1):
            url = f"https://www.djuu.com/ablum/{rid}_1_{pg}.html"
            try:
                r = requests.get(url, headers=headers, timeout=10)
                r.encoding = 'utf-8'
                soup = BeautifulSoup(r.text, 'html.parser')

                page_songs = []
                seen = set(s['id'] for s in songs)
                for a in soup.find_all('a', href=re.compile(r'/play/(\d+)\.html')):
                    sid = re.search(r'/play/(\d+)\.html', a.get('href', ''))
                    if not sid:
                        continue
                    song_id = sid.group(1)
                    if song_id in seen:
                        continue
                    title = a.get('title') or a.get_text(strip=True)
                    if title:
                        page_songs.append({'id': song_id, 'name': title})
                        seen.add(song_id)

                if not page_songs:
                    break

                songs.extend(page_songs)
                if len(songs) >= max_songs:
                    songs = songs[:max_songs]
                    break

            except Exception:
                continue

        return songs

    # ---------- 播放 ----------

    def _extract_play_pic(self, soup):
        """从播放页提取歌曲封面，优先排除广告图"""
        pic = ''
        for selector in ['#mcover', 'img.blur', '.play_detail img', '.play_p2 img', '.play_ct img']:
            el = soup.select_one(selector)
            if el and el.name == 'img':
                pic = el.get('src') or ''
            elif el:
                img = el.find('img')
                pic = (img.get('src') or '') if img else ''
            if pic:
                break
        # fallback：取包含 cover 且非 advert 的第一张图
        if not pic:
            for img in soup.find_all('img', src=re.compile(r'img\.djuu\.com')):
                src = img.get('src') or ''
                if 'cover' in src and 'advert' not in src:
                    pic = src
                    break
        # 最后兜底
        if not pic:
            first = soup.find('img', src=re.compile(r'img\.djuu\.com'))
            pic = (first.get('src') or '') if first else ''
        return pic

    def playerContent(self, flag, id, vipFlags):
        result = {}
        rid = id
        if isinstance(rid, str) and rid.startswith('song_'):
            rid = rid.replace('song_', '', 1)

        url = f"https://www.djuu.com/play/{rid}.html"
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Referer': 'https://www.djuu.com/'
        }

        try:
            r = requests.get(url, headers=headers, timeout=10)
            r.encoding = 'utf-8'
            html = r.text
            soup = BeautifulSoup(html, 'html.parser')

            # 歌曲名
            name = ''
            h1 = soup.find('h1')
            if h1:
                name = h1.get_text(strip=True)
            if not name:
                m = re.search(r"var music = \{[^}]*name:\s*'([^']+)'", html)
                name = m.group(1) if m else ''

            # 封面
            pic = self._extract_play_pic(soup)

            m = re.search(r"var music = \{[^}]*file:\s*'([^']+)'", html)
            if m:
                file_path = m.group(1)
                if file_path.startswith('http'):
                    play_url = file_path
                else:
                    play_url = f"https://mp4.djuu.com/{file_path}.m4a"
                result["parse"] = 0
                result["jx"] = 0
                result["playUrl"] = ""
                result["url"] = play_url
                result["header"] = {
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
                    "Referer": "https://www.djuu.com/"
                }
                result["pic"] = pic
                result["name"] = name
                return result

        except Exception:
            pass

        result["parse"] = 0
        result["jx"] = 0
        result["playUrl"] = ""
        result["url"] = ""
        result["header"] = {}
        result["pic"] = ""
        result["name"] = ""
        return result

    # ---------- 搜索 ----------

    def searchContent(self, key, quick, pg=1):
        result = {
            'list': [],
            'page': pg,
            'pagecount': 9999,
            'limit': 30,
            'total': 999999
        }
        wd = quote(key)
        url = f"https://www.djuu.com/search?musicname={wd}&page={pg}"
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Referer': 'https://www.djuu.com/'
        }

        try:
            r = requests.get(url, headers=headers, timeout=10)
            r.encoding = 'utf-8'
            soup = BeautifulSoup(r.text, 'html.parser')

            videos = []
            seen = set()
            # 搜索结果为表格行，每行一个 isgood_list
            for tr in soup.find_all('tr', class_='sbg'):
                a = tr.find('a', href=re.compile(r'/play/\d+\.html'))
                if not a:
                    continue
                m = re.search(r'/play/(\d+)\.html', a.get('href', ''))
                if not m:
                    continue
                song_id = m.group(1)
                if song_id in seen:
                    continue
                seen.add(song_id)

                title = a.get('title') or a.get_text(strip=True)
                if not title:
                    continue

                pic = ''
                img = tr.find('img')
                if img:
                    pic = img.get('src') or ''
                    if not pic:
                        pic = img.get('data-src') or ''

                remarks = ''
                spans = tr.find_all('span', class_='sc_2')
                if spans:
                    remarks = ' | '.join([s.get_text(strip=True) for s in spans])

                videos.append({
                    "vod_id": f"song_{song_id}",
                    "vod_name": title,
                    "vod_pic": pic,
                    "vod_remarks": remarks
                })

            result['list'] = videos
        except Exception:
            pass

        return result

    def searchContentPage(self, key, quick, pg):
        return self.searchContent(key, quick, pg)

    def localProxy(self, param):
        return {}
