# coding=utf-8
# !/usr/bin/python
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 base64
import json
import time
import sys
import re
import os

sys.path.append('..')

xurl = "https://nnyy.la"

headerx = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36'
          }

class Spider(Spider):
    global xurl
    global headerx

    def getName(self):
        return "首页"

    def init(self, extend):
        pass

    def isVideoFormat(self, url):
        pass

    def manualVideoCheck(self):
        pass

    def split_id_by_at(self, id):
        return id.split("@")

    def split_first_part_by_comma(self, first_part):
        return first_part.split(",")

    def parse_url_dictionary(self, response_text):
        pattern = r'urlDictionary\[(\d+)\]\[(\d+)\]\s*=\s*"([^"]+)"'
        matches = re.findall(pattern, response_text)
        url_dictionary = {}
        for key1, key2, value in matches:
            key1_int = int(key1)
            key2_int = int(key2)
            if key1_int not in url_dictionary:
                url_dictionary[key1_int] = {}
            url_dictionary[key1_int][key2_int] = value
        return url_dictionary

    def get_url_from_dictionary(self, url_dictionary, indices):
        primary_index = int(indices[0].strip())
        secondary_index = int(indices[1].strip())
        return url_dictionary[primary_index][secondary_index]

    def decrypt_url(self, encrypted_hex, key="i_love_you"):
        encrypted_bytes = bytes.fromhex(encrypted_hex)
        s = list(range(256))
        j = 0
        key_bytes = key.encode('utf-8')
        key_length = len(key_bytes)
        for i in range(256):
            j = (j + s[i] + key_bytes[i % key_length]) % 256
            s[i], s[j] = s[j], s[i]
        i = 0
        j = 0
        decrypted_bytes = bytearray(len(encrypted_bytes))
        for k in range(len(encrypted_bytes)):
            i = (i + 1) % 256
            j = (j + s[i]) % 256
            s[i], s[j] = s[j], s[i]
            keystream_byte = s[(s[i] + s[j]) % 256]
            decrypted_bytes[k] = encrypted_bytes[k] ^ keystream_byte
        return decrypted_bytes.decode('utf-8')

    def _extract_play_sources(self, soups):
        xianlu = ''
        for item in soups:
            vods = item.find_all('dt')
            for sou in vods:
                name = sou.text.strip()
                xianlu = xianlu + name + '$$$'
            xianlu = xianlu[:-3]
        return xianlu

    def _extract_play_urls(self, soups1, did):
        bofang = ''
        for item in soups1:
            vods1 = item.find_all('a')
            for sou1 in vods1:
                id1 = sou1['onclick']
                numbers = re.findall(r'\((.*?)\)', id1)[0] if re.findall(r'\((.*?)\)', id1) else ""
                id = f"{numbers}@{did}"
                name = sou1.text.strip()
                bofang = bofang + name + '$' + id + '#'
            bofang = bofang[:-1] + '$$$'
        bofang = bofang[:-3]
        return bofang

    def _extract_content(self, res):
        content_raw = self.extract_middle_text(res, '剧情简介：<span>', '<', 0).replace('\n', '')
        return '😸丢丢为您介绍剧情📢' + (content_raw if content_raw is not None else "暂无剧情介绍")

    def _extract_director(self, res):
        director_raw = self.extract_middle_text(res, '导演：', '</div>', 1, 'href=".*?">(.*?)</a>')
        return director_raw if director_raw is not None and director_raw.strip() != "" else "暂无导演介绍"

    def _extract_actor(self, res):
        actor_raw = self.extract_middle_text(res, '主演：', '</div>', 1, 'href=".*?">(.*?)</a>')
        return actor_raw if actor_raw is not None and actor_raw.strip() != "" else "暂无主演介绍"

    def _extract_remarks(self, res):
        remarks_raw = self.extract_middle_text(res, '类型：', '</div>', 1, 'href=".*?">(.*?)</a>')
        return remarks_raw if remarks_raw is not None and remarks_raw.strip() != "" else "暂无类型介绍"

    def _extract_area(self, res):
        area_raw = self.extract_middle_text(res, '制片国家/地区：', '</div>', 1, 'href=".*?">(.*?)</a>')
        return area_raw if area_raw is not None and area_raw.strip() != "" else "暂无国家/地区介绍"

    def _extract_year(self, doc):
        years = doc.find('h1', class_="product-title")
        year = years.text.strip() if years else '暂无年份介绍'
        return year.replace('\n', '打分：')

    def _extract_video_items(self, vods):
        videos = []
        for vod in vods:
            name = vod.find('img')['alt']
            ids = vod.find('a', class_="thumbnail")
            id = ids['href']
            pic = vod.find('img')['data-src']
            remarks = vod.find('div', class_="note")
            remark = remarks.text.strip()
            video = {
                "vod_id": id,
                "vod_name": name,
                "vod_pic": pic,
                "vod_remarks": remark
                    }
            videos.append(video)
        return videos

    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 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('div', class_="nav")

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

            for vod in vods:

                name = vod.text.strip()

                skip_names = ["首页"]
                if name in skip_names:
                    continue

                id = vod['href'].replace('/', '')

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

        result["class"].append({"type_id": "duanju", "type_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")

        soups = doc.find('div', class_="bd")

        vods = soups.find_all('li')

        videos = self._extract_video_items(vods)

        result = {'list': videos}
        return result

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

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

        url = f'{xurl}/{cid}/?page={str(page)}'
        detail = requests.get(url=url, headers=headerx)
        detail.encoding = "utf-8"
        res = detail.text
        doc = BeautifulSoup(res, "lxml")

        soups = doc.find_all('div', class_="lists-content")

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

            videos = self._extract_video_items(vods)

        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 = []

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

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

        content = self._extract_content(res)

        director = self._extract_director(res)

        actor = self._extract_actor(res)

        remarks = self._extract_remarks(res)

        area = self._extract_area(res)

        year = self._extract_year(doc)

        soups = doc.find_all('div', class_="playlists")
        xianlu = self._extract_play_sources(soups)

        soups1 = doc.find_all('ul', class_="sort-list")
        bofang = self._extract_play_urls(soups1, did)

        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):

        fenge = self.split_id_by_at(id)

        fenge1 = self.split_first_part_by_comma(fenge[0])

        detail = requests.get(url=fenge[1], headers=headerx)
        detail.encoding = "utf-8"
        res = detail.text

        url_dictionary = self.parse_url_dictionary(res)

        result = self.get_url_from_dictionary(url_dictionary, fenge1)

        url = self.decrypt_url(result)

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

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

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

        soups = doc.find_all('div', class_="lists-content")

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

            videos = self._extract_video_items(vods)

        result['list'] = videos
        result['page'] = pg
        result['pagecount'] = 1
        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
