# coding=utf-8
# !/usr/bin/python

"""

作者 丢丢喵 🚓 内容均从互联网收集而来 仅供交流学习使用 版权归原创者所有 如侵犯了您的权益 请通知作者 将及时删除侵权内容
                    ====================Diudiumiao====================

"""

from Crypto.Util.Padding import unpad
from Crypto.Util.Padding import pad
from urllib.parse import unquote
from Crypto.Cipher import ARC4
from urllib.parse import quote
from base.spider import Spider
from Crypto.Cipher import AES
from datetime import datetime

# --- embedded bs4-compatible shim (pyquery/lxml based) for Yingxia adaptation ---
# Used only when real `bs4` is unavailable; covers find/find_all/select/
# select_one/get_text/text/get/[]/name/parent/find_previous used by this spider.
class _BS4Tag(object):
    def __init__(self, el):
        self._el = el

    @property
    def name(self):
        t = self._el.tag
        return t if isinstance(t, str) else None

    @property
    def attrs(self):
        return dict(self._el.attrib)

    @property
    def parent(self):
        p = self._el.getparent()
        return _BS4Tag(p) if p is not None else None

    @property
    def text(self):
        return self.get_text()

    def get_text(self, separator="", strip=False):
        parts = list(self._el.itertext())
        if strip:
            parts = [p.strip() for p in parts if p and p.strip()]
        return separator.join(parts)

    def get(self, attr, default=None):
        v = self._el.get(attr)
        return default if v is None else v

    def has_attr(self, attr):
        return attr in self._el.attrib

    def __getitem__(self, attr):
        return self._el.attrib[attr]

    def __bool__(self):
        return True

    __nonzero__ = __bool__

    def __str__(self):
        try:
            from lxml import html as _lh
            return _lh.tostring(self._el, encoding="unicode")
        except Exception:
            return self.get_text()

    def _css(self, name, attrs, class_, kwargs):
        names = []
        if name:
            names = list(name) if isinstance(name, (list, tuple)) else [name]
        classes = []
        if class_:
            classes = str(class_).split()
        all_attrs = {}
        if attrs:
            all_attrs.update(attrs)
        for k, v in (kwargs or {}).items():
            if k == "recursive":
                continue
            kk = "class" if k == "class_" else ("id" if k == "id_" else k)
            all_attrs[kk] = v
        if "class" in all_attrs:
            classes += str(all_attrs.pop("class")).split()
        attr_sels = []
        for k, v in all_attrs.items():
            if v is True:
                attr_sels.append("[%s]" % k)
            elif v is False or v is None:
                continue
            else:
                attr_sels.append('[%s="%s"]' % (k, str(v).replace('"', "\\\"")))
        cls = "".join("." + c for c in classes)
        at = "".join(attr_sels)
        if names:
            return ", ".join("%s%s%s" % (n, cls, at) for n in names)
        return "*%s%s" % (cls, at) if (cls or at) else "*"

    def _select(self, css, recursive=True):
        from pyquery import PyQuery as _pq
        q = _pq(self._el)
        res = q(css) if recursive else q.children(css)
        return [_BS4Tag(e) for e in res]

    def select(self, css):
        try:
            return self._select(css, True)
        except Exception:
            return []

    def select_one(self, css):
        r = self.select(css)
        return r[0] if r else None

    def find_all(self, name=None, attrs=None, recursive=True, class_=None, **kwargs):
        return self._select(self._css(name, attrs, class_, kwargs), recursive)

    def find(self, name=None, attrs=None, recursive=True, class_=None, **kwargs):
        r = self.find_all(name, attrs, recursive, class_, **kwargs)
        return r[0] if r else None

    def find_previous(self, name=None, attrs=None, class_=None, **kwargs):
        try:
            from pyquery import PyQuery as _pq
            root = self._el.getroottree().getroot()
            css = self._css(name, attrs, class_, kwargs)
            matches = list(_pq(root)(css))
            last = None
            for e in _pq(root)("*"):
                if e is self._el:
                    break
                if any(e is m for m in matches):
                    last = e
            return _BS4Tag(last) if last is not None else None
        except Exception:
            return None


def _BS4_parse(markup):
    from lxml import html as _lh
    if markup is None:
        markup = ""
    if isinstance(markup, bytes):
        markup = markup.decode("utf-8", "ignore")
    markup = str(markup)
    if not markup.strip():
        return _lh.fromstring("<html><body></body></html>")
    try:
        return _lh.fromstring(markup)
    except Exception:
        try:
            return _lh.fromstring("<html><body>%s</body></html>" % markup)
        except Exception:
            return _lh.fromstring("<html><body></body></html>")


class _BeautifulSoupShim(_BS4Tag):
    def __init__(self, markup="", parser=None, *a, **kw):
        _BS4Tag.__init__(self, _BS4_parse(markup))
# --- end embedded bs4 shim ---
try:
    from bs4 import BeautifulSoup
except Exception:
    BeautifulSoup = _BeautifulSoupShim
from base64 import b64decode
import urllib.request
import urllib.parse
import datetime
import binascii
# --- 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
import random
import base64
import html
import json
import time
import sys
import re
import os

sys.path.append('..')

headerz = {
    'sec-ch-ua': '"Microsoft Edge";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-User': '?1',
    'Sec-Fetch-Dest': 'document',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Accept-Encoding': 'gzip, deflate'
          }

xurl = "https://rb.huaduys.org"

try:
    response = requests.get(xurl, headers=headerz, timeout=10)
    cookie_dict = {}
    for cookie in response.cookies:
        cookie_dict[cookie.name] = cookie.value
except Exception:
    cookie_dict = {}
first_cookie_key = None
first_cookie_value = None
server_session_value = cookie_dict.get('server_name_session')
for key, value in cookie_dict.items():
    if key != 'server_name_session':
        first_cookie_key = key
        first_cookie_value = value
        break

headerx = {
    "Host": "rb.huaduys.org",
    "Connection": "keep-alive",
    "sec-ch-ua": '"Microsoft Edge";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"Windows"',
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-Mode": "navigate",
    "Sec-Fetch-Dest": "document",
    "Referer": "https://rb.huaduys.org/",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Cookie": f"{first_cookie_key}={first_cookie_value}; server_name_session={server_session_value}",
    "Accept-Encoding": "gzip, deflate"
          }

headers = {
    'User-Agent': 'Linux; Android 12; Pixel 3 XL) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.101 Mobile Safari/537.36'
          }

class Spider(Spider):
    global xurl
    global headerx
    global headers

    def getName(self):
        return "首页"

    def init(self, extend):
        pass

    def isVideoFormat(self, url):
        pass

    def manualVideoCheck(self):
        pass

    def extract_middle_text(self, text, start_str, end_str, pl, start_index1: str = '', end_index2: str = ''):
        if pl == 3:
            plx = []
            while True:
                start_index = text.find(start_str)
                if start_index == -1:
                    break
                end_index = text.find(end_str, start_index + len(start_str))
                if end_index == -1:
                    break
                middle_text = text[start_index + len(start_str):end_index]
                plx.append(middle_text)
                text = text.replace(start_str + middle_text + end_str, '')
            if len(plx) > 0:
                purl = ''
                for i in range(len(plx)):
                    matches = re.findall(start_index1, plx[i])
                    output = ""
                    for match in matches:
                        match3 = re.search(r'(?:^|[^0-9])(\d+)(?:[^0-9]|$)', match[1])
                        if match3:
                            number = match3.group(1)
                        else:
                            number = 0
                        if 'http' not in match[0]:
                            output += f"#{match[1]}${number}{xurl}{match[0]}"
                        else:
                            output += f"#{match[1]}${number}{match[0]}"
                    output = output[1:]
                    purl = purl + output + "$$$"
                purl = purl[:-3]
                return purl
            else:
                return ""
        else:
            start_index = text.find(start_str)
            if start_index == -1:
                return ""
            end_index = text.find(end_str, start_index + len(start_str))
            if end_index == -1:
                return ""

        if pl == 0:
            middle_text = text[start_index + len(start_str):end_index]
            return middle_text.replace("\\", "")

        if pl == 1:
            middle_text = text[start_index + len(start_str):end_index]
            matches = re.findall(start_index1, middle_text)
            if matches:
                jg = ' '.join(matches)
                return jg

        if pl == 2:
            middle_text = text[start_index + len(start_str):end_index]
            matches = re.findall(start_index1, middle_text)
            if matches:
                new_list = [f'{item}' for item in matches]
                jg = '$$$'.join(new_list)
                return jg

    def parse_videos_from_doc(self, doc, xurl):
        videos = []

        skip_names = ["广告点赞"]

        soups = doc.find_all('ul', class_="stui-vodlist clearfix")

        for soup in soups:
            vods = soup.find_all('li')

            for vod in vods:

                remarks = vod.find('a', class_="stui-vodlist__thumb picture w-thumb img-shadow")
                remark = remarks.text.strip() + "点赞"
                if remark in skip_names:
                    continue

                names = vod.find('h4', class_="title text-overflow")
                name = names.text.strip()

                id = names.find('a')['href']

                pic = vod.find('img')['data-original']
                if 'http' not in pic:
                    pic = xurl + pic

                video = {
                    "vod_id": id,
                    "vod_name": name,
                    "vod_pic": pic,
                    "vod_remarks": '集多▶️' + remark
                        }
                videos.append(video)

        return videos

    def homeContent(self, filter):
        result = {"class": []}

        detail = requests.get(url=xurl, headers=headerx)
        detail.encoding = "utf-8"
        res = detail.text
        doc = BeautifulSoup(res, "lxml")

        soups = doc.find_all('ul', class_="stui-header__menu type-slide")

        for soup in soups:
            vods = soup.find_all('li')

            for vod in vods:

                name = vod.text.strip()
                skip_names = ["首页", "发布页", "免费VPN下载"]
                if name in skip_names:
                    continue

                id1 = vod.find('a')['href']
                fenge = id1.split(".html")
                id = f"{fenge[0]}-----------.html"
                id = id.replace('vodtype', 'vodshow')

                result["class"].append({"type_id": id, "type_name": "集多🌠" + name})

        return result

    def homeVideoContent(self):
        videos = []

        detail = requests.get(url=xurl, headers=headerx)
        detail.encoding = "utf-8"
        res = detail.text
        doc = BeautifulSoup(res, "lxml")
        videos = self.parse_videos_from_doc(doc, xurl)

        result = {'list': videos}
        return result

    def categoryContent(self, cid, pg, filter, ext):
        result = {}
        videos = []

        if pg:
            page = int(pg)
        else:
            page = 1

        fenge = cid.split("---.html")
        url = f'{xurl}{fenge[0]}{str(page)}---.html'
        detail = requests.get(url=url, headers=headerx)
        detail.encoding = "utf-8"
        res = detail.text
        doc = BeautifulSoup(res, "lxml")
        videos = self.parse_videos_from_doc(doc, xurl)

        result = {'list': videos}
        result['page'] = pg
        result['pagecount'] = 9999
        result['limit'] = 90
        result['total'] = 999999
        return result

    def detailContent(self, ids):
        did = ids[0]
        result = {}
        videos = []
        xianlu = ''
        bofang = ''

        if 'http' not in did:
            did = xurl + did

        res = requests.get(url=did, headers=headerx)
        res.encoding = "utf-8"
        res = res.text
        res = html.unescape(res)

        url = 'http://rihou.cc:88/je.json'
        response = requests.get(url)
        response.encoding = 'utf-8'
        code = response.text
        name = self.extract_middle_text(code, "s1='", "'", 0)
        Jumps = self.extract_middle_text(code, "s2='", "'", 0)

        content = '集多🎉为您介绍剧情📢' + self.extract_middle_text(res, '标题：', '</span>', 1, 'alt="(.*?)">')

        director = self.extract_middle_text(res, '分类：', '</p>', 1, 'target=".*?">(.*?)</a>')

        actor = self.extract_middle_text(res, '演员：', '</span>', 1, 'target=".*?">(.*?)</a>')

        remarks = self.extract_middle_text(res, '类别：', '</li>', 1, 'target=".*?">(.*?)</a>')

        year = self.extract_middle_text(res, '日期：', 'p>', 1, '</strong>(.*?)<')

        area = self.extract_middle_text(res, '时长：', 'p>', 1, '</strong>(.*?)<')

        if name not in content:
            bofang = Jumps
            xianlu = '1'
        else:
            id = self.extract_middle_text(res, 'class="btn btn-primary" href="', '"', 0)
            if 'http' not in id:
                id = xurl + id

            name = "集多请您欣赏"

            bofang = name + '$' + id

            xianlu = '花都专线'

        videos.append({
            "vod_id": did,
            "vod_director": director,
            "vod_actor": actor,
            "vod_remarks": remarks,
            "vod_year": year,
            "vod_area": area,
            "vod_content": content,
            "vod_play_from": xianlu,
            "vod_play_url": bofang
                     })

        result['list'] = videos
        return result

    def playerContent(self, flag, id, vipFlags):

        detail = requests.get(url=id, headers=headerx)
        detail.encoding = "utf-8"
        res = detail.text

        url = self.extract_middle_text(res, '"","url":"', '"', 0).replace('\\', '')
        base64_decoded_bytes = base64.b64decode(url)
        base64_decoded_string = base64_decoded_bytes.decode('utf-8')
        url = unquote(base64_decoded_string)

        result = {}
        result["parse"] = 0
        result["playUrl"] = ''
        result["url"] = url
        result["header"] = headers
        return result

    def searchContentPage(self, key, quick, pg):
        result = {}
        videos = []

        url = f'{xurl}/vodsearch/-------------.html?wd={key}'
        detail = requests.get(url=url, headers=headerx)
        detail.encoding = "utf-8"
        res = detail.text
        doc = BeautifulSoup(res, "lxml")
        videos = self.parse_videos_from_doc(doc, xurl)

        result['list'] = videos
        result['page'] = pg
        result['pagecount'] = 9999
        result['limit'] = 90
        result['total'] = 999999
        return result

    def searchContent(self, key, quick, pg="1"):
        return self.searchContentPage(key, quick, '1')

    def localProxy(self, params):
        if params['type'] == "m3u8":
            return self.proxyM3u8(params)
        elif params['type'] == "media":
            return self.proxyMedia(params)
        elif params['type'] == "ts":
            return self.proxyTs(params)
        return None








