# -*- coding: utf-8 -*-
# 八度影院 h.sdgtrl.com | MacCMS v10魔改(拼音分类/films详情/vodlist播放) | 71us v7.3定制 | 必须安卓UA
import sys, re, json, hashlib, time
from urllib.parse import urljoin, quote, unquote
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 ---

try:
    requests.packages.urllib3.disable_warnings()
except:
    pass

sys.path.append('..')
try:
    from base.spider import Spider
except ImportError:
    class Spider:
        def fetch(self, url, headers=None, **kw):
            kw.pop('timeout', None)
            r = requests.get(url, headers=headers, timeout=15, **kw)
            r.encoding = 'utf-8'
            return r

HOSTS = ['https://h.sdgtrl.com']
UA = 'Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36'
CATEGORIES = {
    'dianying': '电影', 'dianshiju': '电视剧', 'zongyi': '综艺', 'dongman': '动漫',
    'fanzuipian': '犯罪片', 'xijupian': '喜剧片', 'dongzuopian': '动作片', 'aiqingpian': '爱情片',
    'kehuanpian': '科幻片', 'kongbupian': '恐怖片', 'juqingpian': '剧情片', 'zhanzhengpian': '战争片',
    'jingsongpian': '惊悚片', 'jiatingpian': '家庭片', 'guzhangpian': '古装片', 'lishipian': '历史片',
    'xianyipian': '悬疑片', 'zainanpian': '灾难片', 'jilupian': '纪录片', 'donghuapian': '动画片',
    'rihan': '日韩', 'guochanju': '国产剧', 'xianggangju': '香港剧', 'hanguoju': '韩国剧',
    'oumeiju': '欧美剧', 'taiwanju': '台湾剧', 'ribenju': '日本剧', 'haiwaiju': '海外剧',
    'taiguoju': '泰国剧', 'duanju': '短剧'}


class Spider(Spider):
    def init(self, extend=''):
        self.base = HOSTS[0].rstrip('/')
        self.ua = UA
        self.types = dict(CATEGORIES)
        try:
            h = self._get(self.base)
            if not h:
                return
            ts = {}
            for m in re.finditer(r'<a href="/vod/([a-z0-9]+)\.html"[^>]*>\s*<span[^>]*>([^<]+)</span>', h):
                name = m.group(2).strip()
                if name and name != '理论' and name != '伦理片':
                    ts.setdefault(m.group(1), name)
            if len(ts) >= 4:
                self.types = {k: v for k, v in self.types.items() if k in ts} or self.types
        except:
            pass

    def _get(self, url, headers=None, timeout=15000):
        last = ''
        for u in [url] + ([url.replace(self.base, h.rstrip('/'), 1) for h in HOSTS if h.rstrip('/') != self.base and url.startswith(self.base)]):
            try:
                hs = headers or {'User-Agent': self.ua, 'Referer': self.base}
                try:
                    r = self.fetch(u, headers=hs, timeout=timeout)
                except TypeError:
                    r = self.fetch(u, headers=hs)
                last = r.text if hasattr(r, 'text') else str(r)
                if last:
                    return last
            except:
                try:
                    rr = requests.get(u, headers=hs, timeout=max(timeout / 1000.0, 10), verify=False)
                    last = rr.text
                    if last:
                        return last
                except:
                    pass
        return last

    def _pic(self, u):
        if not u:
            return ''
        if u.startswith('//'):
            u = 'https:' + u
        elif u.startswith('/'):
            u = self.base + u
        return u

    def _pagecount(self, h, cur=1):
        mx = cur
        for m in re.finditer(r'page=(\d+)', h):
            try:
                n = int(m.group(1))
                if n > mx:
                    mx = n
            except:
                pass
        if re.search(r'下一页', h):
            mx = max(mx, cur + 1)
        return mx

    def _items(self, h, drop=False):
        items, seen = [], set()
        for m in re.finditer(r'<a[^>]*?href="/films/(\d+)\.html"[^>]*?>', h):
            tag = m.group(0)
            tm = re.search(r'title="([^"]+)"', tag)
            if not tm or m.group(1) in seen:
                continue
            pic = ''
            dm = re.search(r'data-original="([^"]+)"', tag)
            if dm:
                pic = dm.group(1)
            else:
                sm = re.search(r'style="([^"]*)"', tag)
                if sm:
                    pm = re.search(r'(/upload/[^"\')&\s]+\.(?:jpe?g|png|webp)|https?://[^"\')&\s]+\.(?:jpe?g|png|webp))', sm.group(1), re.I)
                    if pm:
                        pic = pm.group(1)
            if drop and not pic:
                continue
            remark = ''
            rm = re.search(r'<span[^>]*class="[^"]*(?:pic-text|pic-tag)[^"]*"[^>]*>([^<]+)<', h[m.end():m.end() + 300])
            if rm:
                remark = rm.group(1).strip()
            seen.add(m.group(1))
            items.append({'vod_id': m.group(1), 'vod_name': tm.group(1).strip()[:80], 'vod_pic': self._pic(pic), 'vod_remarks': remark})
        return items

    def homeContent(self, filter=False):
        r = {'class': [{'type_id': k, 'type_name': v} for k, v in self.types.items()]}
        r['list'] = self.homeVideoContent().get('list', [])
        return r

    def homeVideoContent(self):
        h = self._get(self.base)
        return {'list': self._items(h, True) if h else []}

    def categoryContent(self, tid, pg=1, filter=False, extend=''):
        try:
            pn = max(int(str(pg)), 1)
        except:
            pn = 1
        t2 = str(tid).split('|')[0].split('$')[0]
        url = f'{self.base}/stars/{t2}.html' if t2 == 'duanju' else f'{self.base}/vod/{t2}.html'
        h = self._get(f'{url}?page={pn}')
        if not h:
            return {'page': pn, 'pagecount': 1, 'limit': 42, 'total': 0, 'list': []}
        idx = h.find('stui-vodlist clearfix')
        if idx > 0:
            h = h[idx:]
        items = self._items(h)
        return {'page': pn, 'pagecount': self._pagecount(h, pn), 'limit': 42, 'total': len(items), 'list': items}

    def detailContent(self, ids, quick='1'):
        vid = str(ids[0] if isinstance(ids, list) else ids or '')
        m = re.search(r'(\d+)', vid)
        vid = m.group(1) if m else ''
        if not vid:
            return {'list': []}
        h = self._get(f'{self.base}/films/{vid}.html')
        if not h:
            return {'list': []}
        d = {'vod_id': vid, 'vod_name': '', 'vod_pic': '', 'vod_year': '', 'vod_area': '',
             'vod_class': '', 'vod_director': '', 'vod_actor': '', 'vod_content': '',
             'vod_remarks': '', 'vod_play_from': '', 'vod_play_url': ''}
        tn = re.search(r'<h1[^>]*>\s*<a[^>]*title="([^"]+)"', h) or re.search(r'<title>(.*?)</title>', h)
        if tn:
            d['vod_name'] = re.sub(r'[《》]', '', tn.group(1).split('-')[0]).replace('免费在线观看', '').replace('高清完整版', '').strip()
        pm = re.search(r'<div[^>]*class="[^"]*stui-content__thumb[^"]*"[^>]*>[\s\S]*?<img[^>]*src="([^"]+)"', h)
        if pm:
            d['vod_pic'] = self._pic(pm.group(1))
        for pm in re.finditer(r'<p[^>]*class="[^"]*\bdata\b[^"]*"[^>]*>([\s\S]*?)</p>', h):
            t = re.sub(r'<[^>]+>', '', pm.group(1)).replace('&nbsp;', '').replace('\xa0', '').strip(' ：:')
            for k, kk in (('vod_year', '年代'), ('vod_director', '导演'), ('vod_actor', '演员'), ('vod_area', '地区'), ('vod_remarks', '状态')):
                if not d[k] and t.startswith(kk):
                    d[k] = t[len(kk):].strip(' ：:').strip()
        dc = re.search(r'<span[^>]*class="[^"]*detail-sketch[^"]*"[^>]*>([\s\S]*?)</span>', h)
        if dc:
            d['vod_content'] = re.sub(r'\s+', ' ', re.sub(r'<[^>]+>', '', dc.group(1)).replace('&nbsp;', ' ')).strip()[:500]
        uls = re.findall(r'<ul[^>]*class="[^"]*stui-content__playlist[^"]*"[^>]*>([\s\S]*?)</ul>', h)
        pf, pu = [], []
        for i, uu in enumerate(uls):
            eps = re.findall(r'href="(/vodlist/[^"]+)"[^>]*>\s*([^<]+?)\s*</a>', uu)
            if eps:
                pf.append('wjm3u8' if i == 0 else f'线路{i + 1}')
                pu.append('#'.join(f'{t.strip().replace("#", "-").replace("$", "|")}${urljoin(self.base, u)}' for u, t in eps))
        if pf:
            d['vod_play_from'] = '$$$'.join(pf)
            d['vod_play_url'] = '$$$'.join(pu)
        return {'list': [d]}

    def searchContent(self, key, quick=False, pg='1'):
        try:
            pn = max(int(str(pg)), 1)
        except:
            pn = 1
        h = self._get(f'{self.base}/mosr?wd={quote(key)}&page={pn}', timeout=30000)
        if not h:
            return {'list': [], 'page': pn}
        idx = h.find('stui-vodlist__media')
        if idx > 0:
            end = h.find('</ul>', idx)
            if end > 0:
                h = h[idx:end]
        return {'list': self._items(h, True), 'page': pn}

    def playerContent(self, flag, id, vipFlags=None):
        url = str(id) if id else str(flag)
        if '://' in url and re.search(r'\.(m3u8|mp4|flv|mp3)(\?|$)', url, re.I):
            return {'parse': 0, 'url': url}
        full = url if url.startswith('http') else urljoin(self.base, url)
        h = self._get(full)
        if not h:
            return {'parse': 0, 'url': ''}
        return {'parse': 0, 'url': self._parse_play(h)}

    def _parse_play(self, h):
        for key in ('player_data', 'player_aaaa'):
            pd = re.search(r'var\s+%s\s*=\s*(\{[\s\S]*?\})\s*[;<]' % key, h)
            if pd:
                try:
                    u = json.loads(pd.group(1)).get('url', '')
                    if u:
                        u = u.replace('\\/', '/')
                        if re.search(r'\.(m3u8|mp4|flv)(\?|$)', u, re.I):
                            return u
                except:
                    pass
        m = re.search(r'var\s*(?:now|url)\s*=\s*["\']([^"\']+)["\']', h)
        if m and re.search(r'\.(m3u8|mp4|flv)(\?|$)', m.group(1), re.I):
            return m.group(1)
        fm = re.search(r'(https?://[^\s"\'<>]+\.(?:m3u8|mp4|flv))', h)
        if fm:
            return fm.group(1)
        iframe = re.search(r'<iframe[^>]+src="([^"]+)"', h, re.I)
        if iframe:
            u = iframe.group(1)
            if u.startswith('http'):
                h2 = self._get(u)
                if h2:
                    return self._parse_play(h2)
        return ''

    def localProxy(self, param):
        p = param.split('url=', 1)[-1] if 'url=' in param else param
        p = unquote(p) if '%' in p else p
        if re.search(r'\.(jpe?g|png|webp|gif)(\?|$)', p, re.I):
            try:
                r = requests.get(p, headers={'User-Agent': self.ua, 'Referer': self.base}, timeout=15)
                return {'code': r.status_code, 'content': r.content, 'headers': {'Content-Type': r.headers.get('Content-Type', 'image/jpeg')}}
            except:
                return {'code': 404, 'content': b'', 'headers': {}}
        if '.m3u8' in p:
            return self._rewrite_m3u8(p)
        try:
            try:
                r = self.fetch(p, headers={'User-Agent': self.ua, 'Referer': self.base}, timeout=20000)
            except TypeError:
                r = self.fetch(p, headers={'User-Agent': self.ua, 'Referer': self.base})
            if hasattr(r, 'status_code') and r.status_code != 200:
                return {'code': r.status_code, 'content': b'', 'headers': {}}
            return {'code': 200, 'content': r.content, 'headers': {'Content-Type': r.headers.get('Content-Type', 'application/octet-stream')}}
        except:
            return {'code': 404, 'content': b'', 'headers': {}}

    def _rewrite_m3u8(self, url):
        try:
            try:
                r = self.fetch(url, headers={'User-Agent': self.ua, 'Referer': self.base}, timeout=20000)
            except TypeError:
                r = self.fetch(url, headers={'User-Agent': self.ua, 'Referer': self.base})
            if hasattr(r, 'status_code') and r.status_code != 200:
                return {'code': r.status_code, 'content': b'', 'headers': {}}
            body = r.text if hasattr(r, 'text') else str(r)
        except:
            return {'code': 404, 'content': b'', 'headers': {}}
        base = url.rsplit('/', 1)[0] + '/'
        origin = re.match(r'https?://[^/]+', url)
        origin = origin.group(0) if origin else ''
        out = []
        for ln in body.splitlines():
            if ln.startswith('#EXT-X-KEY'):
                m = re.search(r'URI="([^"]+)"', ln)
                if m:
                    ku = m.group(1)
                    if ku.startswith('/'):
                        ku = origin + ku
                    elif not ku.startswith('http'):
                        ku = base + ku
                    ln = ln.replace('URI="%s"' % m.group(1), 'URI="%s"' % ('proxy?url=' + quote(ku, safe='')))
            elif ln.startswith('http'):
                ln = 'proxy?url=' + quote(ln, safe='')
            elif ln.startswith('/') and not ln.startswith('//'):
                ln = 'proxy?url=' + quote(origin + ln, safe='')
            out.append(ln)
        return {'code': 200, 'content': '\n'.join(out), 'headers': {'Content-Type': 'application/vnd.apple.mpegurl'}}