# coding=utf-8
# 恋足踩踏直播回放 (zbeen.com) —— 影视/TVBox (CatVod Python)
# 全站恋足/踩踏/丝袜类直播回放, WordPress 站, 走官方 REST 接口:
#   分类 GET /wp-json/wp/v2/categories?per_page=100
#   列表 GET /wp-json/wp/v2/posts?per_page=20&page=N[&categories=ID]
#   搜索 GET /wp-json/wp/v2/posts?search=关键词&page=N
#   详情 GET /wp-json/wp/v2/posts/<id>
# 播放(2026-11-25 实测): 每篇正文里有一张预览图
#   https://wy2.meijao123.com/video/m3u8/<日期>/<哈希>/vod.gif
# 同目录下的 index.m3u8 就是正片(普通 HLS, 无加密、无防盗链),
# 预览图本身直接当动态封面用。
import re
import sys
import json
import html as htmllib
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

sys.path.append('..')
from base.spider import Spider

HOST = 'https://www.zbeen.com'
API = HOST + '/wp-json/wp/v2'
UA = ('Mozilla/5.0 (Linux; Android 13; RMX2173) AppleWebKit/537.36 '
      '(KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36')
HEADERS = {'User-Agent': UA, 'Accept-Language': 'zh-CN,zh;q=0.9'}
LIST_FIELDS = 'id,title,date,content'
CHUNK = 512 * 1024  # 播放分片 Range 分块大小 (整包拉大分片会被源站卡住)


class Spider(Spider):
    def init(self, extend=''):
        self.s = requests.Session()
        self.s.headers.update(HEADERS)
        self.classes_cache = None

    # ---------- 工具 ----------
    def get_json(self, url):
        try:
            r = self.s.get(url, timeout=25, verify=False)
            if r.status_code != 200:
                return None, {}
            return r.json(), r.headers
        except Exception:
            return None, {}

    def clean_title(self, raw):
        t = re.sub(r'<[^>]+>', '', raw or '')
        return htmllib.unescape(t).strip()

    def gif_of(self, post):
        m = re.search(r'https?://[^"\']+/vod\.gif', (post.get('content') or {}).get('rendered', ''))
        if not m:
            return ''
        # 站点给的地址里带双斜杠(m3u8//2026/...), 规整成单斜杠
        return re.sub(r'(?<!:)//+', '/', m.group(0))

    def img_proxy(self, url):
        return self.getProxyUrl() + '&type=img&url=' + quote(url, safe='')

    def play_proxy_url(self, url):
        return self.getProxyUrl() + '&type=play&url=' + quote(url, safe='')

    # ---------- 分块代理播放 ----------
    def _fetch_range(self, url, start, end, retries=3):
        """Range 分块取一段字节 —— 源站对整包大文件会卡死, 分块才稳。"""
        for _ in range(retries):
            try:
                r = self.s.get(url, timeout=(3.05, 12), verify=False,
                               headers={'Range': 'bytes=%d-%d' % (start, end)})
                if r.status_code in (200, 206) and r.content:
                    return r.content, r.headers
            except Exception:
                pass
        return None, {}

    def _proxy_m3u8(self, url):
        try:
            r = self.s.get(url, timeout=(3.05, 12), verify=False)
            if r.status_code != 200:
                return None
            body = r.text
        except Exception:
            return None
        out = []
        for line in body.splitlines():
            s = line.strip()
            if not s:
                continue
            if s.startswith('#'):
                line = re.sub(r'URI="([^"]+)"',
                              lambda m: 'URI="%s"' % self.play_proxy_url(
                                  urljoin(url, m.group(1))), line)
                out.append(line)
                continue
            out.append(self.play_proxy_url(urljoin(url, s)))
        return ('\n'.join(out) + '\n').encode('utf-8')

    def _proxy_media(self, url, range_header):
        ctype = 'video/mp2t' if '.ts' in url else 'video/mp4'
        if range_header:
            m = re.match(r'bytes=(\d+)-(\d*)', range_header)
            if m:
                start = int(m.group(1))
                end = int(m.group(2)) if m.group(2) else start + CHUNK - 1
                data, _ = self._fetch_range(url, start, end)
                if data is not None:
                    return [206, ctype, data]
        size = None
        _d, hdrs = self._fetch_range(url, 0, 0)
        cr = (hdrs or {}).get('Content-Range') or ''
        if '/' in cr and cr.rsplit('/', 1)[-1].strip().isdigit():
            size = int(cr.rsplit('/', 1)[-1])
        if not size:
            try:
                r = self.s.get(url, timeout=(3.05, 15), verify=False)
                if r.status_code == 200:
                    return [200, ctype, r.content]
            except Exception:
                pass
            return [404, 'text/plain', b'']
        buf = bytearray()
        pos = 0
        while pos < size:
            data, _ = self._fetch_range(url, pos, min(pos + CHUNK, size) - 1)
            if not data:
                break
            buf.extend(data)
            pos += len(data)
        if not buf:
            return [404, 'text/plain', b'']
        return [200, ctype, bytes(buf)]

    def posts_to_list(self, posts):
        out = []
        for p in posts or []:
            gif = self.gif_of(p)
            out.append({
                'vod_id': str(p['id']),
                'vod_name': self.clean_title((p.get('title') or {}).get('rendered', '')),
                'vod_pic': self.img_proxy(gif) if gif else '',
                'vod_remarks': (p.get('date') or '')[:10],
            })
        return out

    def get_classes(self):
        if self.classes_cache:
            return self.classes_cache
        classes = [{'type_id': '0', 'type_name': '最新'},
                   {'type_id': 'S:黄金', 'type_name': '黄金'},
                   {'type_id': 'S:圣水', 'type_name': '圣水'}]
        data, _ = self.get_json(API + '/categories?per_page=100&orderby=count&order=desc')
        for c in data or []:
            if c.get('count', 0) >= 20 and c.get('slug') != 'uncategorized':
                classes.append({'type_id': str(c['id']),
                                'type_name': self.clean_title(c.get('name', ''))})
        self.classes_cache = classes
        return classes

    # ---------- 接口 ----------
    def homeContent(self, filter):
        result = {'class': self.get_classes()}
        data, _ = self.get_json(API + '/posts?per_page=20&page=1&_fields=' + LIST_FIELDS)
        result['list'] = self.posts_to_list(data)
        return result

    def homeVideoContent(self):
        data, _ = self.get_json(API + '/posts?per_page=20&page=1&_fields=' + LIST_FIELDS)
        return {'list': self.posts_to_list(data)}

    def categoryContent(self, tid, pg, filter, extend):
        pg = int(pg)
        url = API + '/posts?per_page=20&page=%d&_fields=%s' % (pg, LIST_FIELDS)
        if tid and tid.startswith('S:'):
            from urllib.parse import quote
            url += '&search=' + quote(tid[2:])
        elif tid and tid != '0':
            url += '&categories=' + tid
        data, headers = self.get_json(url)
        total_pages = int(headers.get('X-WP-TotalPages', pg) or pg)
        return {'list': self.posts_to_list(data), 'page': pg,
                'pagecount': total_pages, 'limit': 20, 'total': total_pages * 20}

    def detailContent(self, ids):
        data, _ = self.get_json(API + '/posts/' + str(ids[0]) + '?_fields=' + LIST_FIELDS)
        if not data:
            return {'list': []}
        gif = self.gif_of(data)
        m3u8 = gif.replace('/vod.gif', '/index.m3u8') if gif else ''
        vod = {
            'vod_id': str(data['id']),
            'vod_name': self.clean_title((data.get('title') or {}).get('rendered', '')),
            'vod_pic': self.img_proxy(gif) if gif else '',
            'vod_remarks': (data.get('date') or '')[:10],
            'vod_play_from': '分块#直连',
            'vod_play_url': ('正片$' + m3u8 + '#正片$' + m3u8) if m3u8 else '',
        }
        return {'list': [vod]}

    def searchContent(self, key, quick, pg='1'):
        pg = int(pg)
        url = API + '/posts?per_page=20&page=%d&search=%s&_fields=%s' % (
            pg, quote(key), LIST_FIELDS)
        data, headers = self.get_json(url)
        total_pages = int(headers.get('X-WP-TotalPages', pg) or pg)
        return {'list': self.posts_to_list(data), 'page': pg,
                'pagecount': total_pages, 'total': total_pages * 20}

    def playerContent(self, flag, id, vipFlags):
        if flag and '直连' in flag:
            return {'parse': 0, 'url': id, 'header': {'User-Agent': UA}}
        return {'parse': 0, 'url': self.play_proxy_url(id),
                'header': {'User-Agent': UA}}

    def localProxy(self, param):
        if param.get('type') == 'play':
            url = param.get('url') or ''
            if not url:
                return [404, 'text/plain', b'']
            if '.m3u8' in url:
                body = self._proxy_m3u8(url)
                if body is None:
                    return [404, 'text/plain', b'']
                return [200, 'application/vnd.apple.mpegurl', body]
            rng = None
            hdr = param.get('header')
            if isinstance(hdr, str):
                try:
                    hdr = json.loads(hdr)
                except Exception:
                    hdr = None
            if isinstance(hdr, dict):
                for k in ('Range', 'range'):
                    if k in hdr:
                        rng = hdr[k]
                        break
            return self._proxy_media(url, rng)
        if param.get('type') == 'img':
            try:
                r = self.s.get(param['url'], timeout=20, verify=False)
                if r.status_code == 200:
                    return [200, r.headers.get('Content-Type', 'image/gif'), r.content]
            except Exception:
                pass
            return [404, 'text/plain', b'']
        return [404, 'text/plain', b'']

    def isVideoFormat(self, url):
        return '.m3u8' in url or '.mp4' in url

    def manualVideoCheck(self):
        return False
