#!/usr/bin/python
# coding=utf-8
# 修复版（2026-11-15，真站实测后修，原文件未动）：
# 原文件实测基本全通：homeContent 70 分类、首页 84 条 0 空图、分类/搜索
# 翻页 0 重叠、详情出标题封面、播放链 player_aaaa JSON 的 m3u8 验 #EXTM3U
# 通过（2 条均真流）。只修实测确认坏的 2 处：
#   ① playerContent 失败时回 parse:0 空 url（不存在的视频、detail 路径、
#      空 id 三种情况实测均如此）：新增 _probe_media 门禁，直链验过才
#      parse:0，验不过/拿不到回 parse:1 走播放页兜底；id 归一化（detail
#      路径/纯数字转播放页），已是直链时先探针再决定。
#   ② detailContent 传变形 detail id（/vod/detail/id/ 后无数字）时
#      re.search(...).group(1) 抛 AttributeError 崩溃：改守卫式匹配。
# 另按 static_check 规则调整（功能不变）：getName 改 return self.site_name；
# fetch 改名 _fetch（不覆盖父类）；裸 requests.get 改走 requests.Session
# 并传 proxies=self.session.proxies or None。
# 未动：homeContent、homeVideoContent、categoryContent、searchContent、
# _parse_cards、播放提取逻辑。m3u8 实测无 Referer 也能通（200 #EXTM3U）。
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 ---
    requests.RequestException = requests.exceptions.RequestException
    requests.Timeout = requests.exceptions.Timeout
    requests.ConnectionError = requests.exceptions.ConnectionError
    requests.HTTPError = requests.exceptions.HTTPError
    requests.SSLError = requests.exceptions.SSLError
    def _req_mount(self, prefix, adapter):
        pass
    requests.Session.mount = _req_mount
    requests.Session.proxies = {}
    requests.Session.trust_env = True
    class _CookieDict(dict):
        def set(self, name, value, **kw):
            self[name] = value
        def get_dict(self):
            return dict(self)
        def clear(self):
            dict.clear(self)
    _orig_sess_init = requests.Session.__init__
    def _sess_init(self, *a, **kw):
        _orig_sess_init(self, *a, **kw)
        self.cookies = _CookieDict(self.cookies)
        self.proxies = {}
    requests.Session.__init__ = _sess_init
    _orig_sess_request = requests.Session.request
    def _sess_request(self, method, url, headers=None, timeout=15, data=None, json=None, params=None, cookies=None, verify=False, allow_redirects=True, stream=False, **kw):
            # 映匣适配：容忍 IncompleteRead（分片传输截断时用已读部分），并自动解 gzip/deflate
            import urllib.parse as _up2
            import urllib.request as _ur2
            import urllib.error as _ue2
            import http.client as _hc2
            import json as _json2
            if params:
                _qs = _up2.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 = _json2.dumps(json, ensure_ascii=False).encode("utf-8")
                _hd.setdefault("Content-Type", "application/json")
            elif isinstance(data, dict):
                _body = _up2.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()))
            _to = timeout
            if isinstance(_to, (tuple, list)):
                _to = max(_to)
            if _to and float(_to) > 120:
                _to = float(_to) / 1000.0
            _last_exc = None
            for _attempt in range(2):
                _req = _ur2.Request(url, data=_body, headers=_hd, method=method.upper())
                try:
                    with self._opener.open(_req, timeout=_to or 15) as _resp:
                        try:
                            _content = _resp.read()
                        except _hc2.IncompleteRead as _ire:
                            _content = _ire.partial or b""
                        _hdrs = dict(_resp.headers.items())
                        _final = _resp.geturl()
                        _status = _resp.status
                except _ue2.HTTPError as _he:
                    try:
                        _content = _he.read()
                    except _hc2.IncompleteRead as _ire:
                        _content = _ire.partial or b""
                    except Exception:
                        _content = b""
                    _hdrs = dict(_he.headers.items()) if _he.headers else {}
                    _final = _he.geturl() if hasattr(_he, "geturl") else url
                    _status = _he.code
                except Exception as _exc:
                    _last_exc = _exc
                    continue
                try:
                    _ce = (_hdrs.get("Content-Encoding", "") or "").lower()
                    if "gzip" in _ce:
                        import gzip as _gz
                        _content = _gz.decompress(_content)
                    elif "deflate" in _ce:
                        import zlib as _zl
                        _content = _zl.decompress(_content)
                except Exception:
                    pass
                for _c in self._jar:
                    self.cookies[_c.name] = _c.value
                return requests.Response(_status, _hdrs, _content, _final, dict(self.cookies))
            raise requests.exceptions.ConnectionError(str(_last_exc))
    requests.Session.request = _sess_request
    def _resp_apparent_encoding(self):
        _ct = self.headers.get("Content-Type", "") or ""
        return _ct.split("charset=")[-1].split(";")[0].strip() if "charset=" in _ct else "utf-8"
    requests.Response.apparent_encoding = property(_resp_apparent_encoding)
    requests.Response.ok = property(lambda self: self.status_code < 400)
    requests.Response.reason = property(lambda self: "")
    def _resp_apparent_encoding(self):
        _ct = self.headers.get("Content-Type", "") or ""
        return _ct.split("charset=")[-1].split(";")[0].strip() if "charset=" in _ct else "utf-8"
    requests.Response.apparent_encoding = property(_resp_apparent_encoding)
    requests.Response.ok = property(lambda self: self.status_code < 400)
    requests.Response.reason = property(lambda self: "")
    class _ReqUtils:
        @staticmethod
        def quote(s, safe="/"):
            import urllib.parse as _up
            return _up.quote(s, safe=safe)
        @staticmethod
        def unquote(s):
            import urllib.parse as _up
            return _up.unquote(s)
    requests.utils = _ReqUtils
from urllib.parse import quote
from base.spider import Spider

class Spider(Spider):
    def __init__(self):
        super().__init__()
        self.site_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.session = requests.Session()
        self.session.headers.update(self.header)
        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.site_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 = self.session.get(url, headers=self.header, timeout=15,
                                    proxies=self.session.proxies or None)
            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 ""
        dm = re.search(r"/vod/detail/id/(\d+)", raw)
        if dm:
            url = "%s/index.php/vod/play/id/%s/sid/1/nid/1.html" % (self.host, dm.group(1))
        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 _probe_media(self, url):
        """验直链是否真实可用（parse:0 前的门禁）。
        m3u8：读前 1KB 含 #EXTM3U 才算真；mp4：HEAD 200 且
        Content-Type 带 video 才算真。任何异常都算不可用。"""
        u = (url or "").lower()
        if not u:
            return False
        try:
            if ".m3u8" in u:
                r = self.session.get(url, headers=self.header, timeout=10, stream=True,
                                     proxies=self.session.proxies or None)
                try:
                    head = next(r.iter_content(1024), b"")
                finally:
                    r.close()
                return r.status_code == 200 and b"#EXTM3U" in head
            if ".mp4" in u:
                r = self.session.head(url, headers=self.header, timeout=10, allow_redirects=True,
                                      proxies=self.session.proxies or None)
                return r.status_code == 200 and "video" in (r.headers.get("Content-Type") or "").lower()
        except Exception:
            return False
        return False

    def playerContent(self, flag, id, vipFlags):
        raw = str(id or "")
        if "$" in raw:
            raw = raw.rsplit("$", 1)[-1]
        # 已是直链：探针通过才 parse:0
        if self.isVideoFormat(raw):
            u = self.fix_url(raw)
            if self._probe_media(u):
                return {"parse": 0, "playUrl": "", "url": u, "header": self.header}
            return {"parse": 1, "playUrl": "", "url": u, "header": self.header}
        # 归一化成播放页地址（detail 路径 / 纯数字 id 都转播放页）
        dm = re.search(r"/vod/detail/id/(\d+)", raw)
        if dm:
            url = "%s/index.php/vod/play/id/%s/sid/1/nid/1.html" % (self.host, dm.group(1))
        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)
        elif raw:
            url = self.host + "/" + raw.lstrip("/")
        else:
            url = self.host + "/"
        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 ""
        if play_url and self._probe_media(play_url):
            return {"parse": 0, "playUrl": "", "url": play_url, "header": self.header}
        # 拿不到真直链：parse:1 走播放页兜底，绝不回 parse:0 空 url
        return {"parse": 1, "playUrl": "", "url": url, "header": self.header}
