# coding=utf-8
"""
足控资源网 (zu45.com, 入口 www.zukong8.com) - TVBox/CatVod Python 源
- 全站足控的 WordPress 站, 与 zbeen 同属 MeiJiao 内容池 (meijao123.com)
- WP REST API 被关 (401), 走 HTML 解析: 列表卡片自带标题与预览 gif
- 播放: 帖子页里的 vod.gif 同目录 index.m3u8 即完整流 (与 zbeen 同一机制)
- 封面 gif 走 localProxy 代理 (手机端播放器不带浏览器头时原站会拒图)
- 黄金/圣水 为搜索型分类 (?s=), 与其他分类一样翻页
"""
import re
import sys
import json
# --- 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 additions (RequestException/utils/cookies/mount) ---
try:
    _RequestsShim.RequestException = _ReqExc
    _RequestsShim.Timeout = _Timeout
    _RequestsShim.ConnectionError = _ConnectionError
    _RequestsShim.HTTPError = _HTTPError
    _Response.apparent_encoding = property(lambda self: "utf-8")

    class _ReqUtils(object):
        @staticmethod
        def quote(s, safe="/"):
            return _uparse.quote(str(s), safe=safe)

        @staticmethod
        def unquote(s):
            return _uparse.unquote(str(s))

    _RequestsShim.utils = _ReqUtils

    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(self):
        _orig_session_init(self)
        self.cookies = _CookieDict(self.cookies)

    _Session.__init__ = _session_init
    if not hasattr(_Session, "mount"):
        _Session.mount = lambda self, prefix, adapter=None: None
except Exception:
    pass
# --- end py578 shim compat additions ---
try:
    import requests
except Exception:
    requests = _RequestsShim
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import quote, urljoin

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

UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
      '(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36')

HOST_CANDIDATES = [
    'https://zu45.com',
    'https://www.zukong8.com',
]
CHUNK = 512 * 1024  # 播放分片 Range 分块大小 (整包拉大分片会被源站卡住)

# (tid, name, slug)  slug 为空=首页; S: 前缀=搜索型分类
CLASSES = [
    ('new', '最新', ''),
    ('zhibo', '直播视频', 'zhiboshipin'),
    ('aicai', '艾彩系列', 'aicaixilie'),
    ('jigou', '机构系列', 'jigou'),
    ('shengyi', '绳艺精品', 'shengyijingpin'),
    ('tk', 'TK系列', 'tkxilie'),
    ('wangyou', '网友原创', 'wangyouyuanchuang'),
    ('manghe', '盲盒12V', 'suijitaocan'),
    ('S:黄金', '黄金', ''),
    ('S:圣水', '圣水', ''),
]
CLASS_MAP = {c[0]: c[2] for c in CLASSES}


class Spider(Spider):

    def getName(self):
        return '足控资源网'

    def init(self, extend=''):
        self.s = requests.Session()
        self.s.headers.update({
            'User-Agent': UA,
            'Accept-Language': 'zh-CN,zh;q=0.9',
        })
        self.host = self._probe()
        return self.host

    # ---------------- 基础 ----------------

    def _check(self, host):
        try:
            r = self.s.get(host + '/', timeout=8, verify=False)
            if r.status_code == 200 and '足控' in r.text:
                return str(r.url).rstrip('/')
        except Exception:
            pass
        return None

    def _probe(self):
        with ThreadPoolExecutor(max_workers=len(HOST_CANDIDATES)) as ex:
            for res in ex.map(self._check, HOST_CANDIDATES):
                if res:
                    return res
        return HOST_CANDIDATES[0]

    def get_text(self, url):
        # 偶尔会拿到空/拦截页, 失败重试一次
        for _ in range(2):
            try:
                r = self.s.get(url, timeout=25, verify=False)
                if r.status_code == 200 and len(r.text) > 3000:
                    r.encoding = 'utf-8'
                    return r.text
            except Exception:
                pass
        return ''

    def img_proxy(self, url):
        if not url:
            return ''
        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)]

    @staticmethod
    def norm_gif(url):
        return re.sub(r'(?<!:)//', '/', url or '')

    def parse_cards(self, htmltxt):
        out = []
        seen = set()
        for m in re.finditer(r'<a[^>]+href="[^"]*/archives/(\d+)\.html"[^>]*>',
                             htmltxt):
            tag = m.group(0)
            did = m.group(1)
            if did in seen:
                continue
            mt = re.search(r'title="([^"]+)"', tag)
            mg = re.search(r'data-bg="([^"]+)"', tag)
            if not mt:
                continue
            seen.add(did)
            gif = self.norm_gif(mg.group(1)) if mg else ''
            out.append({'vod_id': did, 'vod_name': mt.group(1),
                        'vod_pic': self.img_proxy(gif) if gif else '',
                        'vod_remarks': ''})
        return out

    def list_result(self, items, page):
        return {'list': items, 'page': int(page), 'pagecount': 9999,
                'limit': 24, 'total': 999999}

    # ---------------- 接口 ----------------

    def homeContent(self, filter):
        result = {'class': [{'type_id': c[0], 'type_name': c[1]} for c in CLASSES]}
        result['list'] = self.parse_cards(self.get_text(self.host + '/'))
        return result

    def homeVideoContent(self):
        return self.parse_cards(self.get_text(self.host + '/'))

    def categoryContent(self, tid, pg, filter, extend):
        pg = int(pg)
        if tid.startswith('S:'):
            url = self._search_url(tid[2:], pg)
        else:
            slug = CLASS_MAP.get(tid, '')
            url = self.host + ('/' + slug if slug else '/')
            if pg > 1:
                url = url.rstrip('/') + '/page/%d' % pg
        return self.list_result(self.parse_cards(self.get_text(url)), pg)

    def _search_url(self, key, pg):
        if pg > 1:
            return '%s/page/%d/?s=%s' % (self.host, pg, quote(key))
        return '%s/?s=%s' % (self.host, quote(key))

    def detailContent(self, ids):
        did = str(ids[0])
        htmltxt = self.get_text('%s/archives/%s.html' % (self.host, did))
        name, m3u8, gif = '', '', ''
        if htmltxt:
            mt = re.search(r'<title>([^<]+?)(?:-足控资源网)?</title>', htmltxt)
            if mt:
                name = mt.group(1)
            mg = re.search(r'https?://[^"\s]*?meijao123\.com/video/m3u8/[^"\s]*?/vod\.gif',
                           htmltxt)
            if mg:
                gif = self.norm_gif(mg.group(0))
                m3u8 = gif.replace('/vod.gif', '/index.m3u8')
        vod = {
            'vod_id': did,
            'vod_name': name,
            'vod_pic': self.img_proxy(gif) if gif else '',
            'vod_play_from': '分块#直连',
            'vod_play_url': ('正片$' + m3u8 + '#正片$' + m3u8) if m3u8 else '',
        }
        return {'list': [vod]}

    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 searchContent(self, key, quick, pg='1'):
        pg = int(pg)
        return self.list_result(
            self.parse_cards(self.get_text(self._search_url(key, pg))), pg)

    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
