# -*- coding: utf-8 -*-
# TVBox Python 影视源：VJAV（vjav.com）v1.0
# ============================================================
# 纯 JSON API 站（Vue SPA），无 Cloudflare
# 分类列表：/api/json/videos2/86400/str/latest-updates/{n}/categories.{dir}.{pg}.all...json
# 视频详情：/api/json/video/86400/0/{1000*取整}/{id}.json
# 播放文件：/api/videofile.php?video_id={id}&lifetime=864000
#   → video_url 为自定义 base64（字母表含西里尔字符）编码
#   → 解码得 /get_file/... → 跟 302 → CDN 最终 MP4
# 搜索：/api/videos2.php?params=86400/str/relevance/{n}/search..{pg}.all...&s={kw}
# 封面：videos[].scr
import sys
import ssl
import time
import json
import re
import urllib.request
import urllib.parse
from http.cookiejar import CookieJar

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


class Spider(BaseSpider):
    def __init__(self):
        self.site_url = "https://vjav.com"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
            "Accept": "application/json, text/plain, */*",
            "Accept-Language": "en-US,en;q=0.9",
            "Referer": "https://vjav.com/",
        }
        self.cookie_jar = CookieJar()
        self.opener = self._build_opener()
        # 20 个分类（dir, 中文名），全部 7000+ 视频
        self.cats = [
            ("japanese", "日本"),
            ("asian", "亚洲"),
            ("jav-uncensored", "无码"),
            ("jav-censored", "有码"),
            ("amateur", "素人"),
            ("big-tits", "巨乳"),
            ("milf", "熟女"),
            ("college2", "少女"),
            ("blowjob", "口交"),
            ("creampie", "中出"),
            ("pov", "POV"),
            ("hardcore", "硬核"),
            ("lesbian", "女同"),
            ("mature", "成熟"),
            ("anal", "肛交"),
            ("cosplay", "Cosplay"),
            ("threesomes", "3P"),
            ("fetish", "恋物"),
            ("squirting", "潮吹"),
            ("massage", "按摩"),
        ]
        self._throttle = 0.6
        self._last_req = 0.0
        # videofile 自定义 base64 字母表（含西里尔 АВЕСМ）
        self._b64alpha = "АВСDЕFGHIJKLМNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,~"

    def _build_opener(self):
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        https_handler = urllib.request.HTTPSHandler(context=ctx)
        cookie_handler = urllib.request.HTTPCookieProcessor(self.cookie_jar)
        return urllib.request.build_opener(https_handler, cookie_handler)

    def _fetch(self, url, retry=2, referer=None, follow_redirect=True):
        headers = dict(self.headers)
        if referer:
            headers["Referer"] = referer
        gap = time.time() - self._last_req
        if gap < self._throttle:
            time.sleep(self._throttle - gap)
        self._last_req = time.time()
        import http.client
        for i in range(retry + 1):
            try:
                req = urllib.request.Request(url, headers=headers)
                if not follow_redirect:
                    # 手动跟 302 取 Location
                    ctx = ssl.create_default_context()
                    ctx.check_hostname = False
                    ctx.verify_mode = ssl.CERT_NONE

                    class NoRedir(urllib.request.HTTPRedirectHandler):
                        def redirect_request(self, req, fp, code, msg,
                                             headers, newurl):
                            return None
                    op = urllib.request.build_opener(
                        urllib.request.HTTPSHandler(context=ctx),
                        urllib.request.HTTPCookieProcessor(self.cookie_jar),
                        NoRedir())
                    try:
                        with op.open(req, timeout=15) as resp:
                            return {"success": True, "code": resp.getcode(),
                                    "final": resp.geturl(), "html": "",
                                    "headers": dict(resp.headers)}
                    except urllib.error.HTTPError as e:
                        if e.code in (301, 302, 303, 307, 308):
                            return {"success": True, "code": e.code,
                                    "final": e.headers.get("Location", ""),
                                    "html": "", "headers": dict(e.headers)}
                        raise
                with self.opener.open(req, timeout=15) as resp:
                    raw = resp.read()
                    return {"success": True, "code": resp.getcode(),
                            "final": resp.geturl(),
                            "html": raw.decode("utf-8", errors="ignore"),
                            "headers": dict(resp.headers)}
            except http.client.IncompleteRead as e:
                if e.partial:
                    return {"success": True, "code": 200, "final": url,
                            "html": e.partial.decode("utf-8", errors="ignore"),
                            "headers": {}}
            except Exception as e:
                if i == retry:
                    return {"success": False, "code": 0, "final": url,
                            "html": "", "headers": {}, "error": str(e)}
                time.sleep(1)
        return {"success": False, "code": 0, "final": url, "html": "",
                "headers": {}}

    def _fetch_json(self, url, must_contain=None):
        for _ in range(3):
            res = self._fetch(url)
            html = res.get("html", "")
            if res.get("success") and html:
                if not must_contain or must_contain in html:
                    try:
                        return json.loads(html)
                    except Exception:
                        pass
        return {}

    @staticmethod
    def _clean(text):
        if not text:
            return ""
        import html as html_mod
        text = html_mod.unescape(text)
        return re.sub(r"<[^>]+>", "", text).strip()

    # ============ 自定义 base64 解码 ============
    def _decode_videofile_url(self, s):
        alpha = self._b64alpha
        s = re.sub(r"[^АВСЕМA-Za-z0-9\.\,\~]", "", s or "")
        out = bytearray()
        i = 0
        try:
            while i + 3 < len(s):
                o = alpha.index(s[i]); i += 1
                p = alpha.index(s[i]); i += 1
                q = alpha.index(s[i]); i += 1
                r = alpha.index(s[i]); i += 1
                out.append((o << 2) | (p >> 4))
                if q != 64:
                    out.append(((p & 15) << 4) | (q >> 2))
                if r != 64:
                    out.append(((q & 3) << 6) | r)
            return urllib.parse.unquote(bytes(out).decode("latin1"))
        except Exception:
            return ""

    def _resolve_play_url(self, video_id):
        """videofile → 解码 → 跟 302 → 最终 MP4"""
        try:
            api = "%s/api/videofile.php?video_id=%s&lifetime=864000" % (
                self.site_url, video_id)
            data = self._fetch_json(api)
            if not data or not isinstance(data, list):
                return ""
            # 选最高清（第一个通常是 _hq）
            enc = ""
            for item in data:
                if isinstance(item, dict) and item.get("video_url"):
                    enc = item["video_url"]
                    break
            if not enc:
                return ""
            path = self._decode_videofile_url(enc)
            if not path:
                return ""
            if path.startswith("http"):
                url = path
            else:
                url = self.site_url + path
            # 跟 302 到 CDN 最终地址
            for _ in range(4):
                res = self._fetch(url, follow_redirect=False)
                loc = res.get("final", "")
                code = res.get("code", 0)
                if code in (301, 302, 303, 307, 308) and loc:
                    if loc.startswith("/"):
                        loc = self.site_url + loc
                    url = loc
                    continue
                break
            if url.startswith("http") and self.isVideoFormat(url):
                return url
            return ""
        except Exception:
            return ""

    # ============ 列表解析 ============
    def _parse_vod_list(self, data):
        cards, seen = [], set()
        if not data:
            return cards
        videos = data.get("videos", []) if isinstance(data, dict) else []
        for v in videos:
            if not isinstance(v, dict):
                continue
            vid = str(v.get("video_id", ""))
            if not vid or vid in seen:
                continue
            if v.get("is_private") == "1":
                continue
            seen.add(vid)
            pic = str(v.get("scr", "") or "")
            if pic.startswith("//"):
                pic = "https:" + pic
            cards.append({
                "vod_id": vid,
                "vod_name": self._clean(str(v.get("title", ""))) or vid,
                "vod_pic": pic,
                "vod_remarks": str(v.get("duration", "")),
            })
        return cards

    def _list_url(self, cat_dir, pg, count=30):
        return ("%s/api/json/videos2/86400/str/latest-updates/%d/"
                "categories.%s.%d.all...json" % (
                    self.site_url, count, cat_dir, pg))

    # ============ 标准接口 ============
    def init(self, extend=""):
        pass

    def getName(self):
        return "VJAV"

    def homeContent(self, filter):
        return {"class": [{"type_id": d, "type_name": n}
                          for d, n in self.cats],
                "filters": {}}

    def homeVideoContent(self):
        url = ("%s/api/json/videos2/86400/str/latest-updates/20/"
               "..1.all...json" % self.site_url)
        data = self._fetch_json(url, must_contain="videos")
        return {"list": self._parse_vod_list(data)[:20]}

    def categoryContent(self, tid, pg, filter, extend):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        data = self._fetch_json(self._list_url(str(tid), pg),
                                must_contain="videos")
        cards = self._parse_vod_list(data)
        total = 0
        try:
            total = int(data.get("total_count", 0))
        except Exception:
            pass
        pages = 0
        try:
            pages = int(data.get("pages", 0))
        except Exception:
            pass
        return {"list": cards, "page": pg,
                "pagecount": pages or (pg + 1 if len(cards) >= 30 else pg),
                "limit": len(cards), "total": total}

    def detailContent(self, ids):
        vid = str(ids[0]).strip() if ids else ""
        if not vid:
            return {"list": []}
        vod = {"vod_id": vid, "vod_name": vid, "vod_pic": "",
               "vod_remarks": "", "vod_content": "",
               "vod_play_from": "在线播放",
               "vod_play_url": "正片$%s" % vid}
        try:
            vid_int = int(re.sub(r"\D", "", vid) or 0)
            bucket = 1000 * (vid_int // 1000)
            api = "%s/api/json/video/86400/0/%d/%d.json" % (
                self.site_url, bucket, vid_int)
            data = self._fetch_json(api, must_contain="video")
            v = data.get("video", {}) if isinstance(data, dict) else {}
            if isinstance(v, dict) and v:
                if v.get("title"):
                    vod["vod_name"] = self._clean(str(v["title"]))
                pic = str(v.get("thumb", "") or "")
                if pic.startswith("//"):
                    pic = "https:" + pic
                vod["vod_pic"] = pic
                vod["vod_content"] = self._clean(
                    str(v.get("description", "")))[:500]
                vod["vod_remarks"] = str(v.get("duration", ""))
            play_url = self._resolve_play_url(vid)
            if play_url:
                vod["vod_play_url"] = "正片$%s" % play_url
        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}
        try:
            vid = re.sub(r"\D", "", raw_id)
            if vid:
                play_url = self._resolve_play_url(vid)
                if play_url:
                    return {"parse": 0, "url": play_url, "header": header}
        except Exception:
            pass
        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 = urllib.parse.quote(str(key).strip())
        url = ("%s/api/videos2.php?params=86400/str/relevance/30/"
               "search..%d.all...&s=%s" % (self.site_url, pg, kw))
        data = self._fetch_json(url, must_contain="videos")
        cards = self._parse_vod_list(data)
        return {"list": cards, "page": pg,
                "pagecount": pg + 1 if len(cards) >= 30 else pg,
                "limit": len(cards), "total": 0}

    def action(self, action):
        return None

    def liveContent(self):
        return {}

    def localProxy(self, params):
        return [200, "text/plain;charset=utf-8", ""]

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

    def manualVideoCheck(self):
        return False

    def destroy(self):
        pass
