# -*- coding: utf-8 -*-
# TVBox Python 影视源：XXX follow（www.xxxfollow.com）v1.0
# TikTok 短视频站；分类=/tag/{name}?page=N；卡片=data-x-post-id；
# 详情=/{user}/{id}-{slug}，mp4直链；搜索=/search/{kw}?page=N
import sys
import ssl
import time
import json
import re
import html as html_mod
import urllib.request
import urllib.parse
import http.client
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://www.xxxfollow.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": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        }
        self.cookie_jar = CookieJar()
        self.opener = self._build_opener()
        # (tag, 中文名)
        self.cats = [
            ("bigtits", "巨乳"),
            ("asian", "亚洲"),
            ("ebony", "黑妞"),
            ("masturbation", "自慰"),
            ("18yearsold", "18岁"),
            ("pov", "POV"),
            ("cosplaygirl", "Cosplay"),
            ("bigcock", "巨根"),
            ("hotwife", "人妻"),
            ("curvy", "曲线"),
            ("brunette", "深发"),
            ("latina", "拉丁"),
        ]
        self._throttle = 0.8
        self._last_req = 0.0

    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):
        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()
        for i in range(retry + 1):
            try:
                req = urllib.request.Request(url, headers=headers)
                with self.opener.open(req, timeout=15) as resp:
                    raw = resp.read()
                    try:
                        h = raw.decode("utf-8", errors="ignore")
                    except Exception:
                        h = ""
                    return {"success": True, "data": raw, "html": h}
            except http.client.IncompleteRead as e:
                if e.partial:
                    try:
                        h = e.partial.decode("utf-8", errors="ignore")
                    except Exception:
                        h = ""
                    return {"success": True, "data": e.partial, "html": h}
            except Exception as e:
                if i == retry:
                    return {"success": False, "data": b"", "html": "",
                            "error": str(e)}
                time.sleep(1)
        return {"success": False, "data": b"", "html": ""}

    def _fetch_html(self, url, must_contain=None, referer=None):
        html_data = ""
        for _ in range(3):
            res = self._fetch(url, 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

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

    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)

    def _extract_cover(self, inner):
        """封面提取：优先懒加载属性，过滤占位图"""
        if not inner:
            return ""
        for im in re.finditer(r"<img[^>]+>", inner, re.I):
            tag = im.group(0)
            for attr in ("data-src", "data-original", "data-lazy-src",
                         "data-echo", "srcset", "src"):
                am = re.search(r'%s\s*=\s*["\']([^"\']+)["\']' % attr,
                               tag, re.I)
                if not am:
                    continue
                cand = am.group(1).strip().split()[0]
                if not cand or cand.startswith("data:"):
                    continue
                low = cand.lower()
                if any(k in low for k in ("loading.gif", "placeholder",
                                          "blank.", "pixel.", "spinner")):
                    continue
                return self._abs_url(cand)
        return ""

    def _parse_vod_list(self, html_data):
        """切块解析：data-x-post-id 卡片"""
        cards, seen = [], set()
        if not html_data:
            return cards
        # 按卡片切块
        blocks = re.split(r'data-x-post-id="', html_data)
        for blk in blocks[1:]:
            m_id = re.match(r"(\d+)", blk)
            if not m_id:
                continue
            vid = m_id.group(1)
            if vid in seen:
                continue
            seen.add(vid)
            seg = blk[:4000]
            # 详情链接 /user/id-slug
            lm = re.search(r'href="((/[^"]+)?/%s-[^"]*)"' % vid, seg)
            detail_url = lm.group(1) if lm else ""
            # 标题：img alt
            title = ""
            tm = re.search(r'alt="([^"]{3,150})"', seg)
            if tm:
                title = self._clean(tm.group(1))
                # 去掉 " by xxx" 后缀
                title = re.sub(r"\s+by\s+\S+\s*$", "", title).strip()
            # 封面
            pic = self._extract_cover(seg)
            if not title:
                title = vid
            cards.append({
                "vod_id": vid,
                "vod_name": title,
                "vod_pic": pic,
                "vod_remarks": "",
                "_detail": self._abs_url(detail_url),
            })
        # 兜底：直扫视频链接
        if not cards:
            for m in re.finditer(r'href="(/[^"]+/(\d+)-[^"]*)"', html_data):
                vid = m.group(2)
                if vid in seen:
                    continue
                seen.add(vid)
                seg = html_data[max(0, m.start() - 500):m.end() + 2000]
                tm = re.search(r'alt="([^"]{3,150})"', seg)
                title = self._clean(tm.group(1)) if tm else vid
                title = re.sub(r"\s+by\s+\S+\s*$", "", title).strip()
                cards.append({
                    "vod_id": vid,
                    "vod_name": title or vid,
                    "vod_pic": self._extract_cover(seg),
                    "vod_remarks": "",
                    "_detail": self._abs_url(m.group(1)),
                })
        return cards

    def _extract_play_url(self, html_data):
        """四层兜底提直链，过滤 sample/test"""
        if not html_data:
            return ""
        cands = []

        def _ok(u):
            u = u.strip().replace("\\/", "/")
            if not u.startswith("http"):
                return False
            low = u.lower()
            if any(k in low for k in ("sample", "test", "preview", "thumb",
                                      "poster", "blank")):
                return False
            return True

        # 1. fhd/sd_url JSON
        for pat in (r'"fhd_url"\s*:\s*"([^"]+)"',
                    r'"sd_url"\s*:\s*"([^"]+)"'):
            for m in re.finditer(pat, html_data):
                u = m.group(1).strip()
                if u and u != "null" and _ok(u):
                    cands.append(u)
        # 2. mp4 直链
        for m in re.finditer(r'"(https?://[^"]+\.mp4[^"]*)"', html_data):
            u = m.group(1)
            if _ok(u):
                cands.append(u.split("#")[0])
        # 3. source 标签
        for m in re.finditer(r'<source[^>]+src="([^"]+)"', html_data, re.I):
            if _ok(m.group(1)):
                cands.append(m.group(1).split("#")[0])
        # 4. 裸 mp4
        for m in re.finditer(r'(https?://[^\s"\']+\.mp4)', html_data):
            if _ok(m.group(1)):
                cands.append(m.group(1).split("#")[0])
        # 去重保序
        seen, out = set(), []
        for u in cands:
            if u not in seen:
                seen.add(u)
                out.append(u)
        return out[0] if out else ""

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

    def getName(self):
        return "XXXfollow"

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

    def homeVideoContent(self):
        html_data = self._fetch_html(self.site_url + "/",
                                     must_contain="data-x-post-id")
        cards = self._parse_vod_list(html_data)[:20]
        for c in cards:
            c.pop("_detail", None)
        return {"list": cards}

    def _detail_url_for(self, card):
        if card.get("_detail"):
            return card["_detail"]
        return ""

    def categoryContent(self, tid, pg, filter, extend):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        if pg <= 1:
            url = "%s/tag/%s" % (self.site_url, tid)
        else:
            url = "%s/tag/%s?page=%d" % (self.site_url, tid, pg)
        html_data = self._fetch_html(url, must_contain="data-x-post-id")
        cards = self._parse_vod_list(html_data)
        for c in cards:
            c.pop("_detail", None)
        return {"list": cards, "page": pg,
                "pagecount": pg + 1 if len(cards) >= 20 else pg,
                "limit": len(cards), "total": 0}

    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}
        # /video/{id} 301 跳到完整详情页
        try:
            html_data = self._fetch_html(
                "%s/video/%s" % (self.site_url, vid),
                must_contain=".mp4")
            # og:title / og:image
            tm = re.search(
                r'og:title[^>]*content="([^"]+)"', html_data)
            if tm:
                name = self._clean(tm.group(1))
                name = re.sub(r"\s*Starring\s.*$", "", name,
                              flags=re.I).strip()
                name = re.sub(r"\s*-\s*XXX\s*follow.*$", "", name,
                              flags=re.I).strip()
                if name:
                    vod["vod_name"] = name
            pm = re.search(
                r'og:image[^>]*content="([^"]+)"', html_data)
            if pm:
                vod["vod_pic"] = self._abs_url(pm.group(1))
            play_url = self._extract_play_url(html_data)
            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:
            d = self.detailContent([raw_id])
            ep = d["list"][0]["vod_play_url"]
            if "$" in ep:
                u = ep.split("$", 1)[1]
                if u.startswith("http") and self.isVideoFormat(u):
                    return {"parse": 0, "url": u, "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())
        if pg <= 1:
            url = "%s/search/%s" % (self.site_url, kw)
        else:
            url = "%s/search/%s?page=%d" % (self.site_url, kw, pg)
        html_data = self._fetch_html(url, must_contain="data-x-post-id")
        cards = self._parse_vod_list(html_data)
        for c in cards:
            c.pop("_detail", None)
        return {"list": cards, "page": pg,
                "pagecount": pg + 1 if len(cards) >= 20 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 ".mp4" in u or ".m3u8" in u

    def manualVideoCheck(self):
        return False

    def destroy(self):
        pass
