#!/usr/bin/python
# coding=utf-8
import re, json
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
from base.spider import Spider

class Spider(Spider):
    def __init__(self):
        super().__init__()
        self.name = "黄色仓库"
        self.host = "https://yaseporn.com"
        self.header = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0.0.0 Safari/537.36",
            "Referer": self.host + "/",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "zh-CN,zh;q=0.9"
        }
        self.fallback_class = [
            ("21", "全部日韩"), ("20", "中文字幕"), ("44", "有码精品"), ("45", "童颜巨乳"),
            ("46", "制服丝袜"), ("47", "熟女人妻"), ("48", "强奸乱伦"), ("49", "女优明星"),
            ("50", "SM调教"), ("23", "无码破解"), ("43", "精品无码"), ("30", "素人中出无码FC2"),
            ("31", "巨乳少女无码HEYZO"), ("32", "重口强奸无码tokyohot"), ("33", "萝莉高颜值无码1pondo"),
            ("39", "美熟女无码xxxav"), ("34", "出轨乱伦无码Caribbeancom"), ("36", "素人面试无码10musume"),
            ("37", "人妻素人无码pacopacomama"), ("38", "重口素人无码gachinco"), ("40", "熟女无码C0930"),
            ("41", "重口熟女无码H0930"), ("42", "极熟女无码H4610"), ("51", "更多精品素人"),
            ("52", "面试约拍系列素人SIRO"), ("53", "高颜值美人259LUXU"), ("59", "恋爱风素人S-CUTE"),
            ("54", "街头搭讪200GANA"), ("55", "高颜值搭讪300MIUM"), ("56", "应募素人300MAAN"),
            ("57", "搭讪快速中出300NTK"), ("58", "面接素人230ORECO"), ("60", "真实初次素人261ARA"),
            ("61", "少女恋爱系列390JAC"), ("62", "人妻乱伦素人328HMDN"), ("85", "日本VR影片"),
            ("63", "水果派解说"), ("28", "韩国主播"), ("27", "全部国产"), ("65", "麻豆传媒"),
            ("66", "精品传媒"), ("67", "国产推荐"), ("68", "国产精品"), ("70", "自拍偷拍"),
            ("69", "国产主播"), ("71", "网红头条"), ("72", "黑料网曝门"), ("73", "家庭乱伦"),
            ("74", "国产丝袜"), ("75", "探花约炮"), ("77", "国产SM"), ("78", "国产人妻"),
            ("79", "cosplay"), ("81", "SWAG"), ("86", "学生激情"), ("83", "明星换脸"),
            ("80", "抖阴视频"), ("101", "全部欧美"), ("29", "欧美高清"), ("102", "全部动漫"),
            ("82", "激情动漫"), ("87", "全部新线路"), ("103", "有码破解"), ("104", "欧美高清"),
            ("105", "动漫剧情"), ("99", "国产系列"), ("98", "日本有码"), ("97", "日本无码"),
            ("96", "有码中文字幕"), ("95", "无码中文字幕")
        ]

    def getName(self):
        return self.name

    def init(self, extend=""):
        return True

    def isVideoFormat(self, url):
        formats = [".m3u8", ".mp4", ".flv", ".mkv", ".ts", ".avi"]
        return any(f in url.lower() for f in formats)

    def manualVideoCheck(self):
        return False

    def fix_url(self, url):
        if not url:
            return ""
        if url.startswith("//"):
            return "https:" + url
        if url.startswith("/"):
            return self.host + url
        return url

    def clean_text(self, text):
        if not text:
            return ""
        text = re.sub(r"<[^>]+>", "", text)
        return re.sub(r"\s+", " ", text).strip()

    def fetch(self, url):
        try:
            resp = requests.get(url, headers=self.header, timeout=15)
            resp.encoding = resp.apparent_encoding or "utf-8"
            return resp.text if resp.status_code == 200 else ""
        except Exception:
            return ""

    def _parse_cards(self, html):
        videos = []
        seen = set()
        for block in re.split(r'<div class="thumbnail">', html)[1:]:
            try:
                m = re.search(r'<a href="(/index\.php/vod/play/id/\d+/sid/1/nid/1\.html)"[^>]*?title="([^"]*)"', block)
                if not m:
                    continue
                vod_id = m.group(1)
                if vod_id in seen:
                    continue
                seen.add(vod_id)
                pic = re.search(r'data-src="([^"]+)"', block)
                pic = self.fix_url(pic.group(1)) if pic else ""
                if not pic:
                    picm = re.search(r'<img[^>]+src="(https?://[^"]+)"', block)
                    pic = picm.group(1) if picm else ""
                date = re.search(r'bottom-1 right-1[^>]*>([^<]+)<', block)
                videos.append({
                    "vod_id": vod_id,
                    "vod_name": self.clean_text(m.group(2)),
                    "vod_pic": pic,
                    "vod_remarks": self.clean_text(date.group(1)) if date else ""
                })
            except Exception:
                continue
        return videos

    def _pagecount(self, html, pat):
        pages = re.findall(pat, html)
        return max([int(p) for p in pages]) if pages else 1

    def homeContent(self, filter=False):
        html = self.fetch(self.host + "/")
        classes = []
        seen = set()
        for tid, name in re.findall(r'/index\.php/vod/type/id/(\d+)\.html[^>]*>([^<]+)<', html):
            if tid not in seen:
                seen.add(tid)
                classes.append({"type_id": tid, "type_name": self.clean_text(name)})
        if not classes:
            classes = [{"type_id": t, "type_name": n} for t, n in self.fallback_class]
        return {"class": classes}

    def homeVideoContent(self):
        html = self.fetch(self.host + "/")
        return {"list": self._parse_cards(html)}

    def categoryContent(self, tid, pg, filter, extend):
        url = "%s/index.php/vod/type/id/%s/page/%s.html" % (self.host, tid, pg)
        html = self.fetch(url)
        videos = self._parse_cards(html)
        pagecount = self._pagecount(html, r'/index\.php/vod/type/id/%s/page/(\d+)\.html' % tid)
        return {"list": videos, "page": int(pg), "pagecount": pagecount, "limit": len(videos), "total": pagecount * len(videos)}

    def detailContent(self, ids):
        raw = ids[0] if ids else ""
        if "/vod/detail/id/" in raw:
            vid = re.search(r"/vod/detail/id/(\d+)", raw).group(1)
            url = "%s/index.php/vod/play/id/%s/sid/1/nid/1.html" % (self.host, vid)
        elif raw.startswith("http"):
            url = raw
        elif raw.startswith("/"):
            url = self.host + raw
        elif re.match(r"^\d+$", raw):
            url = "%s/index.php/vod/play/id/%s/sid/1/nid/1.html" % (self.host, raw)
        else:
            url = self.host + "/" + raw.lstrip("/")
        html = self.fetch(url)
        play_path = re.sub(r"^https?://[^/]+", "", url)
        title = ""
        h1 = re.search(r"<h1[^>]*>(.*?)</h1>", html, re.S)
        if h1:
            title = self.clean_text(h1.group(1))
        pic = ""
        cover = re.search(r'data-src="([^"]+/1\.jpg)"', html)
        if cover:
            pic = self.fix_url(cover.group(1))
        if not pic:
            img = re.search(r'<img[^>]+data-src="(https?://[^"]+)"', html)
            pic = img.group(1) if img else ""
        return {"list": [{
            "vod_id": play_path,
            "vod_name": title,
            "vod_pic": pic,
            "vod_play_from": "黄色仓库",
            "vod_play_url": "正片$%s" % play_path
        }]}

    def searchContent(self, key, quick, pg="1"):
        url = "%s/index.php/vod/search/wd/%s/page/%s.html" % (self.host, quote(key), pg)
        html = self.fetch(url)
        videos = self._parse_cards(html)
        if not videos and pg == "1":
            html = self.fetch("%s/index.php/vod/search.html?wd=%s" % (self.host, quote(key)))
            videos = self._parse_cards(html)
        pagecount = self._pagecount(html, r'/index\.php/vod/search/page/(\d+)/wd/')
        return {"list": videos, "page": int(pg), "pagecount": pagecount, "limit": len(videos), "total": pagecount * len(videos)}

    def playerContent(self, flag, id, vipFlags):
        if id.startswith("http"):
            url = id
        elif id.startswith("/"):
            url = self.host + id
        else:
            url = self.host + "/" + id.lstrip("/")
        html = self.fetch(url)
        play_url = ""
        idx = html.find("player_aaaa=")
        if idx >= 0:
            start = html.find("{", idx)
            depth = 0
            end = -1
            for j in range(start, len(html)):
                if html[j] == "{":
                    depth += 1
                elif html[j] == "}":
                    depth -= 1
                    if depth == 0:
                        end = j
                        break
            if start >= 0 and end > start:
                try:
                    data = json.loads(html[start:end + 1])
                    play_url = (data.get("url") or "").replace("\\/", "/")
                except Exception:
                    play_url = ""
        if not play_url:
            m = re.search(r'(https?://[^"\'\s]+\.m3u8[^"\'\s]*)', html)
            play_url = m.group(1).replace("\\/", "/") if m else ""
        return {"parse": 0, "url": play_url, "header": ""}
