# -*- coding: utf-8 -*-
# TVBox Python 影视源：YouPorn（www.youporn.com）融合风格版
# ============================================================
# 站点结构（2026-10-22 抓原始 HTML 实证，站方自有系统，非CMS）：
#  分类：/category/{slug}/，共 82 个（/categories/ 页全量），翻页
#  ?page={页}；每页 39 条。无总数文本，pagecount 用满页推断
#  列表卡片：<article class="video-box" data-video-id data-…>，
#  标题在 aria-label，封面在卡片 img 的 data-poster（明图 CDN），
#  时长在 .video-duration 里
#  播放页：/watch/{id}/，页内 JSON 有 mediaDefinitions，其 hls 项
#  的 videoUrl 是站内端点 /media/hls/?s={令牌}，请求它返回 JSON
#  数组，每项是带签名的 CDN master.m3u8（约 2 小时有效），取
#  defaultQuality 或最高画质那条——detail 必须现抓现拼
#  搜索：/search/?query={关键词}，翻页 &page={页}
import re
import time
import ssl
import json
import urllib.request
import urllib.parse
import urllib.error
import gzip
import zlib

try:
    from base.spider import Spider as BaseSpider
except Exception:
    class BaseSpider(object):
        pass

SITE_NAME = "YouPorn"
DEFAULT_HOST = "https://www.youporn.com"

CATS = [("home", "Recommended"),
        ("amateur", "Amateur"), ("anal", "Anal"), ("arab", "Arab"),
        ("asian", "Asian"), ("bbw", "BBW"), ("bigass", "Big Ass"),
        ("bigdick", "Big Dick"), ("bigtits", "Big Tits"), ("bisexual", "Bisexual"),
        ("blonde", "Blonde"), ("blowjob", "Blowjob"), ("bondage", "Bondage"),
        ("brazilian", "Brazilian"), ("brunette", "Brunette"), ("bts", "BTS"),
        ("bukkake", "Bukkake"), ("cartoon", "Cartoon"), ("casting", "Casting"),
        ("celebrity", "Celebrity"), ("college", "College (18+)"), ("compilation", "Compilation"),
        ("cosplay", "Cosplay"), ("creampie", "Creampie"), ("cuckold", "Cuckold"),
        ("cumshot", "Cumshot"), ("doublepenetration", "Double Penetration"), ("ebony", "Ebony"),
        ("european", "European"), ("facials", "Facials"), ("feet", "Feet"),
        ("femaleorgasm", "Female Orgasm"), ("fetish", "Fetish"), ("fingering", "Fingering"),
        ("fisting", "Fisting"), ("french", "French"), ("funny", "Funny"),
        ("gangbang", "Gangbang"), ("german", "German"), ("group", "Group"),
        ("handjob", "Handjob"), ("hardcore", "Hardcore"), ("hd", "HD"),
        ("hentai", "Hentai"), ("indian", "Indian"), ("interracial", "Interracial"),
        ("japanese", "Japanese"), ("latina", "Latina"), ("lesbian", "Lesbian"),
        ("lingerie", "Lingerie"), ("massage", "Massage"), ("masturbation", "Masturbation"),
        ("mature", "Mature"), ("milf", "MILF"), ("muscle", "Muscle"),
        ("orgy", "Orgy"), ("parody", "Parody"), ("party", "Party"),
        ("pissing", "Pissing"), ("popular-with-women", "Popular With Women"), ("pov", "POV"),
        ("public", "Public"), ("pussy-licking", "Pussy Licking"), ("reality", "Reality"),
        ("redhead", "Redhead"), ("romantic", "Romantic"), ("rough", "Rough"),
        ("small-tits", "Small Tits"), ("solo-girl", "Solo girl"), ("solomale", "Solo Male"),
        ("squirting", "Squirting"), ("stepfantasy", "Step Fantasy"), ("striptease", "Striptease"),
        ("tattoos", "Tattoos"), ("teens", "18-25"), ("threesome", "Threesome"),
        ("toys", "Toys"), ("transgender", "Transgender"), ("verifiedamateurs", "Verified Amateurs"),
        ("vintage", "Vintage"), ("virtualreality", "Virtual Reality"), ("webcam", "Webcam"),
        ("youngandold", "Young (18+) and Old"),
]

PAGE_FULL = 30
THROTTLE = 0.3


class Spider(BaseSpider):
    def __init__(self):
        super(Spider, self).__init__()
        self.site_url = DEFAULT_HOST
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Linux; Android 13) "
                          "AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/120.0.0.0 Mobile Safari/537.36",
            "Accept": "text/html,application/xhtml+xml,application/xml;"
                      "q=0.9,*/*;q=0.8",
            "Accept-Language": "en-US,en;q=0.9,zh-CN;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            "Referer": self.site_url + "/",
            "Connection": "keep-alive",
        }
        self.ssl_ctx = ssl.create_default_context()
        self.ssl_ctx.check_hostname = False
        self.ssl_ctx.verify_mode = ssl.CERT_NONE
        self._throttle = THROTTLE
        self._last_req = 0.0
        self._opener = None
        try:
            import http.cookiejar
            jar = http.cookiejar.CookieJar()
            self._opener = urllib.request.build_opener(
                urllib.request.HTTPCookieProcessor(jar),
                urllib.request.HTTPSHandler(context=self.ssl_ctx))
        except Exception:
            self._opener = None

    def getName(self):
        return SITE_NAME

    def init(self, extend=""):
        try:
            host = ""
            if isinstance(extend, dict):
                host = str(extend.get("host", "")).strip()
            elif extend and str(extend).strip():
                ext = str(extend).strip()
                if ext.startswith("{"):
                    host = str(json.loads(ext).get("host", "")).strip()
                elif ext.startswith("http"):
                    host = ext
            host = host.rstrip("/")
            if host:
                self.site_url = host
                self.headers["Referer"] = host + "/"
        except Exception:
            pass

    def _open(self, req, timeout):
        if self._opener is not None:
            return self._opener.open(req, timeout=timeout)
        return urllib.request.urlopen(req, context=self.ssl_ctx,
                                      timeout=timeout)

    # ============ 网络层：重试+partial恢复+内容校验 ============
    @staticmethod
    def _decode_body(raw, enc=""):
        if not raw:
            return ""
        if isinstance(raw, str):
            return raw
        if raw[:2] == b"\x1f\x8b":
            try:
                raw = gzip.decompress(raw)
            except Exception:
                pass
        elif raw[:1] == b"\x78":
            try:
                raw = zlib.decompress(raw)
            except Exception:
                pass
        elif "gzip" in enc:
            try:
                raw = gzip.decompress(raw)
            except Exception:
                pass
        elif "deflate" in enc:
            try:
                raw = zlib.decompress(raw)
            except Exception:
                pass
        for cs in ("utf-8", "gbk", "gb2312"):
            try:
                return raw.decode(cs)
            except Exception:
                continue
        return raw.decode("utf-8", errors="ignore")

    def _fetch(self, url, timeout=20, retries=2, referer=None):
        import http.client
        gap = time.time() - self._last_req
        if gap < self._throttle:
            time.sleep(self._throttle - gap)
        self._last_req = time.time()
        headers = dict(self.headers)
        if referer:
            headers["Referer"] = referer
        req = urllib.request.Request(url, headers=headers, method="GET")
        last_err = ""
        for attempt in range(retries + 1):
            try:
                with self._open(req, timeout) as resp:
                    raw = resp.read()
                    enc = resp.headers.get("Content-Encoding", "").lower()
                    return {"success": True,
                            "html": self._decode_body(raw, enc)}
            except http.client.IncompleteRead as e:
                if e.partial:
                    return {"success": True,
                            "html": self._decode_body(e.partial)}
                last_err = str(e)
            except Exception as e:
                last_err = str(e)
                if attempt < retries:
                    time.sleep(0.5)
        return {"success": False, "html": "", "error": last_err}

    def _fetch_html(self, url, must_contain=None, timeout=20, referer=None):
        html_data = ""
        for _ in range(3):
            res = self._fetch(url, timeout=timeout, referer=referer)
            html_data = res.get("html", "")
            if res.get("success") and (not must_contain
                                       or must_contain in html_data):
                return html_data
        return html_data

    def _abs_url(self, url):
        if not url:
            return ""
        url = url.strip()
        if url.startswith("http"):
            return url
        if url.startswith("//"):
            return "https:" + url
        return urllib.parse.urljoin(self.site_url + "/", url.lstrip("/"))

    @staticmethod
    def _unescape(text):
        t = text.replace("&amp;", "&").replace("&lt;", "<") \
            .replace("&gt;", ">").replace("&quot;", '"') \
            .replace("&apos;", "'").replace("&#39;", "'") \
            .replace("&#039;", "'").replace("&nbsp;", " ")

        def _num(m):
            try:
                return chr(int(m.group(1)))
            except Exception:
                return m.group(0)

        def _hex(m):
            try:
                return chr(int(m.group(1), 16))
            except Exception:
                return m.group(0)

        t = re.sub(r"&#x([0-9a-fA-F]+);", _hex, t)
        t = re.sub(r"&#(\d+);", _num, t)
        return t

    @staticmethod
    def _clean(text):
        if not text:
            return ""
        text = Spider._unescape(text)
        return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", text)).strip()

    @staticmethod
    def _attr(tag, name):
        if not tag:
            return ""
        m = re.search(name + r'\s*=\s*"([^"]*)"', tag, re.I)
        if m:
            return m.group(1).strip()
        m = re.search(name + r"\s*=\s*'([^']*)'", tag, re.I)
        if m:
            return m.group(1).strip()
        m = re.search(name + r"\s*=\s*([^\s>]+)", tag, re.I)
        return m.group(1).strip() if m else ""

    # ============ localProxy（封面明图直连，一般用不上，保留兜底）====
    @staticmethod
    def _img_mime(data):
        if not data or len(data) < 12:
            return ""
        if data[:2] == b"\xff\xd8":
            return "image/jpeg"
        if data[:8] == b"\x89PNG\r\n\x1a\n":
            return "image/png"
        if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
            return "image/webp"
        return ""

    def localProxy(self, params):
        # 只返 3 段 [状态码, mime, bytes]
        try:
            if params.get("type") == "pic":
                url = params.get("url", "")
                if url:
                    req = urllib.request.Request(
                        url, headers={"User-Agent": self.headers["User-Agent"],
                                      "Referer": self.site_url + "/"})
                    with self._open(req, 15) as resp:
                        raw = resp.read()
                    mime = self._img_mime(raw)
                    if mime:
                        return [200, mime, raw]
        except Exception:
            pass
        return [404, "text/plain; charset=utf-8", b""]

    def _fix_pic(self, pic):
        # 封面地址两层坑（2026-10-22 实测）：① 属性里的 &amp; 必须还原
        # 成 &，否则 pix-cdn77 的签名参数被隔断、验签失败 403；
        # ② pix-cdn77 还查 Referer，无 Referer 直接 403——给签名图
        # 拼壳的图片代理后缀 @Referer=，让 App 加载时带上主站 Referer
        u = self._abs_url(self._unescape(pic))
        if "cdn77" in u or "hash=" in u:
            u += "@Referer=%s/" % self.site_url
        return u

    # ============ 列表解析：<article class="video-box"> 切块 ============
    def _parse_vod_list(self, html_data):
        cards, order, by_id = [], [], {}
        if not html_data:
            return cards
        pat = re.compile(
            r'<article\b[^>]*?data-video-id="(\d+)"[^>]*>(.*?)</article>',
            re.S | re.I)
        for m in pat.finditer(html_data):
            vid, body = m.group(1), m.group(2)
            if vid in by_id:
                continue
            opening = m.group(0)[:m.group(0).find(">") + 1]
            vod = {"vod_id": vid, "vod_name": "", "vod_pic": "",
                   "vod_remarks": ""}
            t = self._attr(opening, "aria-label")
            if t and self._clean(t):
                vod["vod_name"] = self._clean(t)
            if not vod["vod_name"]:
                im = re.search(r"<img\b[^>]*>", body, re.I | re.S)
                if im:
                    alt = self._attr(im.group(0), "alt")
                    if alt and self._clean(alt):
                        vod["vod_name"] = self._clean(alt)
            im = re.search(r"<img\b[^>]*>", body, re.I | re.S)
            if im:
                pic = self._attr(im.group(0), "data-poster")
                if not pic:
                    src = self._attr(im.group(0), "src")
                    if src.startswith("http"):
                        pic = src
                if pic:
                    vod["vod_pic"] = self._fix_pic(pic)
            dm = re.search(
                r'class="[^"]*video-duration[^"]*"[^>]*>\s*<span>\s*'
                r"([^<]+?)\s*</span>", body, re.S | re.I)
            if dm:
                vod["vod_remarks"] = dm.group(1).strip()
            by_id[vid] = vod
            order.append(vid)
        for vid in order:
            vod = by_id[vid]
            if not vod["vod_name"]:
                vod["vod_name"] = vid
            cards.append(vod)
        return cards

    # ============ 播放链：mediaDefinitions -> 端点 -> CDN m3u8 ============
    @staticmethod
    def _extract_json_after(text, marker, opener, closer):
        # 花括号/方括号配平提取 marker 后的第一个 JSON 结构
        i = text.find(marker)
        if i < 0:
            return None
        j = text.find(opener, i)
        if j < 0:
            return None
        depth, in_str, esc = 0, False, False
        for k in range(j, len(text)):
            ch = text[k]
            if in_str:
                if esc:
                    esc = False
                elif ch == "\\":
                    esc = True
                elif ch == '"':
                    in_str = False
                continue
            if ch == '"':
                in_str = True
            elif ch == opener:
                depth += 1
            elif ch == closer:
                depth -= 1
                if depth == 0:
                    try:
                        return json.loads(text[j:k + 1])
                    except Exception:
                        return None
        return None

    def _media_endpoint(self, html_data, fmt):
        arr = self._extract_json_after(html_data, "mediaDefinitions",
                                       "[", "]")
        if not arr:
            return ""
        for e in arr:
            if e.get("format") == fmt and e.get("videoUrl"):
                return str(e["videoUrl"])
        return ""

    def _resolve_hls(self, endpoint, referer):
        # 请求站内端点拿画质数组，取 default 或最高画质的 m3u8
        if not endpoint:
            return ""
        text = self._fetch_html(endpoint, timeout=15, referer=referer)
        if not text:
            return ""
        try:
            arr = json.loads(text)
        except Exception:
            arr = None
        if isinstance(arr, list) and arr:
            best, best_h = "", -1
            for e in arr:
                u = str(e.get("videoUrl", "") or "")
                if ".m3u8" not in u:
                    continue
                if e.get("defaultQuality"):
                    return u
                try:
                    hgt = int(e.get("height", 0) or 0)
                except Exception:
                    hgt = 0
                if hgt > best_h:
                    best, best_h = u, hgt
            return best
        m = re.search(r'https?://[^\s"\'\\]+?\.m3u8[^\s"\'\\]*', text)
        return m.group(0) if m else ""

    # ============ 标准接口 ============
    def homeContent(self, filter):
        return {"class": [{"type_id": tid, "type_name": name}
                          for tid, name in CATS]}

    def homeVideoContent(self):
        html_data = self._fetch_html(self.site_url + "/",
                                     must_contain="data-video-id")
        return {"list": self._parse_vod_list(html_data)[:30]}

    def _page_result(self, cards, pg):
        pagecount = pg + 1 if len(cards) >= PAGE_FULL else pg
        return {"list": cards, "page": pg, "pagecount": pagecount,
                "limit": len(cards), "total": len(cards)}

    def categoryContent(self, tid, pg, filter, extend):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        tid = str(tid).strip().strip("/")
        if tid == "home":
            url = self.site_url + "/"
        else:
            url = "%s/category/%s/" % (self.site_url, tid)
        if pg > 1:
            url += "?page=%d" % pg
        html_data = self._fetch_html(url, must_contain="data-video-id")
        return self._page_result(self._parse_vod_list(html_data), pg)

    def detailContent(self, ids):
        if not ids:
            return {"list": []}
        vid = re.search(r"(\d+)", str(ids[0]))
        vid = vid.group(1) if vid else str(ids[0]).strip()
        url = "%s/watch/%s/" % (self.site_url, vid)
        vod = {"vod_id": vid, "vod_name": vid, "vod_pic": "",
               "vod_remarks": "", "vod_content": "",
               "vod_play_from": "HLS",
               "vod_play_url": "正片$%s" % url}
        try:
            html_data = self._fetch_html(url, must_contain="mediaDefinitions")
            if not html_data:
                html_data = self._fetch_html(url)
            tm = re.search(r"<title>(.*?)</title>", html_data, re.S | re.I)
            if tm:
                t = self._clean(tm.group(1))
                t = re.split(r"\s+-\s+Free Porn Videos", t)[0].strip()
                if t:
                    vod["vod_name"] = t
            om = re.search(r'og:image[^>]*content="([^"]+)"', html_data)
            if om:
                vod["vod_pic"] = self._fix_pic(om.group(1))
            endpoint = self._media_endpoint(html_data, "hls")
            m3u8 = self._resolve_hls(endpoint, url) if endpoint else ""
            if not m3u8:
                mm = re.search(r'https?://[^\s"\'\\]+?\.m3u8[^\s"\'\\]*',
                               html_data)
                if mm:
                    m3u8 = mm.group(0).replace("\\/", "/")
            if m3u8:
                vod["vod_play_url"] = "正片$%s" % m3u8
        except Exception:
            pass
        return {"list": [vod]}

    def playerContent(self, flag, id, vipFlags):
        raw_id = str(id).strip()
        header = {"User-Agent": self.headers["User-Agent"],
                  "Referer": self.site_url + "/"}
        if raw_id.startswith("http") and self.isVideoFormat(raw_id):
            return {"parse": 0, "url": raw_id, "header": header}
        vid = re.search(r"(\d+)", raw_id)
        if vid:
            return {"parse": 1,
                    "url": "%s/watch/%s/" % (self.site_url, vid.group(1)),
                    "header": header}
        return {"parse": 1, "url": raw_id, "header": header}

    def searchContent(self, key, quick, pg="1"):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        kw = str(key).strip()
        if not kw:
            return {"list": [], "page": pg, "pagecount": pg,
                    "limit": 0, "total": 0}
        url = "%s/search/?query=%s" % (
            self.site_url, urllib.parse.quote_plus(kw))
        if pg > 1:
            url += "&page=%d" % pg
        html_data = self._fetch_html(url, must_contain="data-video-id")
        return self._page_result(self._parse_vod_list(html_data), pg)

    def action(self, action):
        return None

    def liveContent(self):
        return {}

    def isVideoFormat(self, url):
        u = (url or "").lower()
        return u.endswith(".m3u8") or ".m3u8?" in u or ".mp4" in u.split("?")[0]

    def manualVideoCheck(self):
        return False

    def destroy(self):
        pass


if __name__ == "__main__":
    sp = Spider()
    sp.init()
    ok = True

    def check(name, cond, extra=""):
        global ok
        print(("PASS " if cond else "FAIL ") + name +
              (" | " + str(extra) if extra else ""))
        if not cond:
            ok = False

    hc = sp.homeContent(True)
    check("homeContent", len(hc["class"]) == len(CATS),
          "%d分类" % len(hc["class"]))

    r = sp.categoryContent("amateur", "1", None, None)
    check("category", len(r["list"]) > 0, "%d条" % len(r["list"]))
    pics = sum(1 for v in r["list"] if v["vod_pic"].startswith("http"))
    bad = sum(1 for v in r["list"] if "&amp;" in v["vod_pic"])
    check("covers", pics > 0 and bad == 0,
          "%d/%d 含&amp;残留%d" % (pics, len(r["list"]), bad))
    names = sum(1 for v in r["list"]
                if v["vod_name"] and v["vod_name"] != v["vod_id"])
    check("titles", names > 0, "%d/%d" % (names, len(r["list"])))

    r2 = sp.categoryContent("amateur", "2", None, None)
    ids1 = set(v["vod_id"] for v in r["list"])
    ids2 = set(v["vod_id"] for v in r2["list"])
    check("page2", len(r2["list"]) > 0 and not (ids1 & ids2),
          "%d条 与第1页重叠%d" % (len(r2["list"]), len(ids1 & ids2)))

    h = sp.homeVideoContent()
    check("home", len(h["list"]) > 0, "%d条" % len(h["list"]))

    if r["list"]:
        vid = r["list"][0]["vod_id"]
        s = sp.searchContent("asian", False, "1")
        check("search", len(s["list"]) > 0, "%d条" % len(s["list"]))

        d = sp.detailContent([vid])
        v = d["list"][0]
        has_m3u8 = ".m3u8" in v["vod_play_url"]
        check("detail", bool(v["vod_name"]) and v["vod_name"] != vid
              and has_m3u8 and bool(v["vod_pic"]),
              "%s | 封面%s" % (v["vod_name"][:30],
                               "有" if v["vod_pic"] else "无"))
        if has_m3u8:
            ep = v["vod_play_url"].split("$", 1)[1]
            p = sp.playerContent("HLS", ep, [])
            check("player", p["parse"] == 0 and ".m3u8" in p["url"]
                  and isinstance(p.get("header"), dict)
                  and "playUrl" not in p, p["url"][:70])
            # 真链探活：m3u8 必须以 #EXTM3U 开头
            probe = sp._fetch(ep, timeout=15,
                              referer=sp.site_url + "/")
            check("probe_media", probe["html"].startswith("#EXTM3U"),
                  probe["html"][:40].replace("\n", " "))
    else:
        check("detail", False, "无列表跳过")

    print("ALL PASS" if ok else "SOME FAILED（把 FAIL 行发回即可）")
