# -*- coding: utf-8 -*-
# TVBox Python 影视源：BadNews（bad.news）v1.0
# ============================================================
# 成人视频内容平台：短视频 / 长视频 / H动漫
# 主列表（tag/porn、tag/long-porn、sort-*）：
#   卡片 <div class="link show" data-tid="{id}">
#   视频 <video class="my-videos" data-source="直链" poster="封面">
#   标题 <h3 class="title"><a class="title">标题</a>
#   翻页 /tag/porn/page-N、/sort-new/page-N
# H动漫（/dm）：卡片 <article> -> /dm/play/id-{id}，封面 data-echo，MP4直链
# 注意：Twitter CDN 会拦 bad.news 的 Referer，播放头不带 Referer
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://bad.news"
        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()
        self.cats = [
            ("tag/porn", "短视频"),
            ("tag/long-porn", "长视频"),
            ("dm", "H动漫"),
            ("sort-hot", "热门"),
            ("sort-new", "最新"),
            ("sort-score", "得分"),
            ("sort-better", "精选"),
        ]
        self._throttle = 0.5
        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()
        import http.client
        for i in range(retry + 1):
            try:
                req = urllib.request.Request(url, headers=headers)
                with self.opener.open(req, timeout=12) as resp:
                    raw = resp.read()
                    try:
                        return {"success": True, "data": raw,
                                "html": raw.decode("utf-8", errors="ignore")}
                    except Exception:
                        return {"success": True, "data": raw, "html": ""}
            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(0.5)
        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 ""
        import html as html_mod
        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, tag_html):
        """封面提取：优先懒加载属性，过滤占位图"""
        if not tag_html:
            return ""
        for im in re.finditer(r'<img[^>]+>', tag_html, re.I):
            tag = im.group(0)
            for attr in ('data-echo', 'data-src', 'data-original',
                         'data-lazy-src', '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 ('lightbox-blank', 'loading.gif',
                                          'placeholder', 'blank.', 'pixel.',
                                          'default_avatar')):
                    continue
                return self._abs_url(cand)
        # video 标签的 poster
        pm = re.search(r'poster="([^"]+)"', tag_html, re.I)
        if pm:
            return self._abs_url(pm.group(1))
        return ""

    def _cat_url(self, tid, pg):
        if pg <= 1:
            return "%s/%s" % (self.site_url, tid)
        return "%s/%s/page-%d" % (self.site_url, tid, pg)

    def _parse_main_list(self, html_data):
        """主列表解析（tag/porn、sort-*）：video 标签直带播放地址"""
        cards, seen = [], set()
        if not html_data:
            return cards
        blocks = re.split(r'<div class="link show\s*" data-tid="', 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)
            # 只收录视频帖
            vm = re.search(
                r'<video[^>]*class="my-videos"[^>]*>', blk, re.I)
            if not vm:
                continue
            vtag = vm.group(0)
            src = ""
            sm = re.search(r'data-source="([^"]+)"', vtag, re.I)
            if sm:
                src = sm.group(1).strip()
            if not src:
                continue
            pic = ""
            pm = re.search(r'poster="([^"]+)"', vtag, re.I)
            if pm:
                pic = self._abs_url(pm.group(1))
            title = ""
            tm = re.search(
                r'<h3 class="title">.*?<a[^>]*class="title"[^>]*>(.*?)</a>',
                blk, re.S | re.I)
            if tm:
                title = self._clean(tm.group(1))
            if not title:
                title = "视频 %s" % vid
            cards.append({
                "vod_id": "t%s" % vid,
                "vod_name": title,
                "vod_pic": pic,
                "vod_remarks": "",
                "_play": src,
            })
        return cards

    def _parse_dm_list(self, html_data):
        """H动漫列表解析"""
        cards, seen = [], set()
        if not html_data:
            return cards
        # 按 article 切块
        blocks = re.split(r'<article[^>]*>', html_data, flags=re.I)
        for blk in blocks[1:]:
            m = re.search(r'href="(/dm/play/id-(\d+))"', blk, re.I)
            if not m:
                continue
            href, vid = m.group(1), m.group(2)
            if vid in seen:
                continue
            seen.add(vid)
            title = ""
            tm = re.search(
                r'<a[^>]*class="title"[^>]*title="([^"]+)"', blk, re.I)
            if tm:
                title = tm.group(1)
            if not title:
                tm2 = re.search(r'alt="([^"]{2,120})"', blk, re.I)
                if tm2:
                    title = tm2.group(1)
            title = self._clean(title) or ("动漫 %s" % vid)
            pic = self._extract_cover(blk)
            cards.append({
                "vod_id": "dm%s" % vid,
                "vod_name": title,
                "vod_pic": pic,
                "vod_remarks": "",
                "_href": href,
            })
        return cards

    def _max_page(self, html_data, pg):
        max_pg = pg
        for pm in re.finditer(r'/page-(\d+)', html_data):
            try:
                max_pg = max(max_pg, int(pm.group(1)))
            except Exception:
                pass
        return max_pg if max_pg > pg else (pg + 1)

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

    def getName(self):
        return "BadNews"

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

    def homeVideoContent(self):
        r = self.categoryContent("sort-new", "1", None, None)
        return {"list": r["list"][:20]}

    def categoryContent(self, tid, pg, filter, extend):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        url = self._cat_url(tid, pg)
        if tid == "dm":
            html_data = self._fetch_html(url, must_contain="dm/play/id-")
            cards = self._parse_dm_list(html_data)
        else:
            html_data = self._fetch_html(url, must_contain="my-videos")
            cards = self._parse_main_list(html_data)
        pagecount = self._max_page(html_data, pg) if cards else pg
        for c in cards:
            c.pop("_play", None)
            c.pop("_href", None)
        return {"list": cards, "page": pg, "pagecount": pagecount,
                "limit": len(cards), "total": 0}

    def detailContent(self, ids):
        vid = str(ids[0]).strip() if ids else ""
        vod = {"vod_id": vid, "vod_name": vid, "vod_pic": "",
               "vod_remarks": "", "vod_content": "",
               "vod_play_from": "在线播放", "vod_play_url": ""}
        play_url, title, pic = "", "", ""
        try:
            if vid.startswith("dm"):
                did = re.sub(r"\D", "", vid)
                html_data = self._fetch_html(
                    "%s/dm/play/id-%s" % (self.site_url, did),
                    must_contain=".mp4")
                tm = re.search(r'<title>(.*?)</title>', html_data, re.S)
                if tm:
                    title = self._clean(tm.group(1)).strip()
                for pat in (r'"(https?://[^"]+\.mp4[^"]*)"',
                            r"'(https?://[^']+\.mp4[^']*)'"):
                    mm = re.search(pat, html_data)
                    if mm:
                        play_url = mm.group(1)
                        break
            else:
                tid = re.sub(r"\D", "", vid)
                html_data = self._fetch_html(
                    "%s/t/%s" % (self.site_url, tid),
                    must_contain="data-source")
                vm = re.search(
                    r'<video[^>]*class="my-videos"[^>]*>', html_data, re.I)
                if vm:
                    vtag = vm.group(0)
                    sm = re.search(r'data-source="([^"]+)"', vtag)
                    if sm:
                        play_url = sm.group(1).strip()
                    pm = re.search(r'poster="([^"]+)"', vtag)
                    if pm:
                        pic = self._abs_url(pm.group(1))
                tm = re.search(r'<title>(.*?)</title>', html_data, re.S)
                if tm:
                    title = self._clean(tm.group(1)).strip()
                    # 去掉站名后缀
                    title = re.sub(r'\s*[|｜-]\s*bad\.news.*$', '',
                                   title, flags=re.I).strip()
        except Exception:
            pass
        if title:
            vod["vod_name"] = title
        if pic:
            vod["vod_pic"] = pic
        if play_url and self.isVideoFormat(play_url):
            vod["vod_play_url"] = "正片$%s" % play_url
        else:
            vod["vod_play_url"] = "正片$%s" % vid
        return {"list": [vod]}

    def _extract_play_url(self, html_data):
        """四层兜底提取播放地址"""
        if not html_data:
            return ""
        # 1. video 标签 data-source
        m = re.search(
            r'<video[^>]*class="my-videos"[^>]*data-source="([^"]+)"',
            html_data, re.I)
        if m and self._ok_url(m.group(1)):
            return m.group(1).strip()
        # 2. data-source 通用
        m = re.search(r'data-source="([^"]+)"', html_data, re.I)
        if m and self._ok_url(m.group(1)):
            return m.group(1).strip()
        # 3. 直扫 m3u8/mp4
        for pat in (r'"(https?://[^"]+?\.m3u8[^"]*)"',
                    r"'(https?://[^']+?\.m3u8[^']*)'",
                    r'"(https?://[^"]+?\.mp4[^"]*)"',
                    r"'(https?://[^']+?\.mp4[^']*)'"):
            for mm in re.finditer(pat, html_data, re.I):
                u = mm.group(1)
                if self._ok_url(u):
                    return u
        # 4. 裸 m3u8
        m = re.search(r'(https?://\S+?\.m3u8\S*)', html_data, re.I)
        if m and self._ok_url(m.group(1)):
            return m.group(1).strip('"\'' )
        return ""

    @staticmethod
    def _ok_url(u):
        if not u or not u.startswith("http"):
            return False
        low = u.lower()
        if any(k in low for k in ("sample", "test", "advert", "ads.")):
            return False
        return True

    def playerContent(self, flag, id, vipFlags):
        raw_id = str(id).strip()
        # Twitter CDN 拦 bad.news 的 Referer，播放头不带 Referer
        header = {"User-Agent": self.headers["User-Agent"]}
        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/q-%s" % (self.site_url, kw)
        else:
            url = "%s/search/q-%s/page-%d" % (self.site_url, kw, pg)
        html_data = self._fetch_html(url, must_contain="my-videos")
        cards = self._parse_main_list(html_data)
        pagecount = self._max_page(html_data, pg) if cards else pg
        for c in cards:
            c.pop("_play", None)
            c.pop("_href", None)
        return {"list": cards, "page": pg, "pagecount": pagecount,
                "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


if __name__ == "__main__":
    sp = Spider()
    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

    # ---- mock ----
    mock_main = '''<div class="link show " data-tid="111">
    <video class="my-videos" data-source="https://video.twimg.com/x/pl/a.m3u8?tag=14"
      poster="https://pbs.twimg.com/x.jpg"></video>
    <div class="entry"><h3 class="title"><a class="title" href="/t/111">测试标题</a></h3></div>
    </div>'''
    cards = sp._parse_main_list(mock_main)
    check("parse_main", len(cards) == 1 and cards[0]["vod_pic"].endswith("x.jpg"),
          "%d条" % len(cards))

    mock_dm = '''<article><div class="thumbr"><a class="afterglow post-thumb" href="/dm/play/id-1875">
    <img class="lazy" data-echo="https://v.hersav.me/images/dm/a.jpg" alt="动漫标题"></a></div>
    <div class="infor"><h4><a class="title" href="/dm/play/id-1875" title="动漫标题">动漫标题</a></h4></div></article>'''
    cards2 = sp._parse_dm_list(mock_dm)
    check("parse_dm", len(cards2) == 1 and cards2[0]["vod_name"] == "动漫标题",
          "%d条" % len(cards2))

    # ---- 真实网络 ----
    hc = sp.homeContent(True)
    check("homeContent", len(hc["class"]) == 7,
          "%d分类" % len(hc["class"]))

    r = sp.categoryContent("tag/porn", "1", None, None)
    n1 = len(r["list"])
    check("category", n1 > 0, "%d条 pagecount=%s" % (n1, r["pagecount"]))
    cov = sum(1 for c in r["list"] if c.get("vod_pic", "").startswith("http"))
    check("covers", cov == n1 and n1 > 0, "%d/%d" % (cov, n1))
    tit = sum(1 for c in r["list"] if c.get("vod_name"))
    check("titles", tit == n1, "%d/%d" % (tit, n1))

    r2 = sp.categoryContent("tag/porn", "2", None, None)
    s1 = set(c["vod_id"] for c in r["list"])
    s2 = set(c["vod_id"] for c in r2["list"])
    check("page_no_overlap", len(r2["list"]) > 0 and not (s1 & s2),
          "p2=%d条" % len(r2["list"]))

    rd = sp.categoryContent("dm", "1", None, None)
    check("dm_category", len(rd["list"]) > 0, "%d条" % len(rd["list"]))

    rs = sp.searchContent("美女", True, "1")
    check("search", len(rs["list"]) > 0, "%d条" % len(rs["list"]))

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

    if r["list"]:
        d = sp.detailContent([r["list"][0]["vod_id"]])
        v = d["list"][0]
        has_play = "$" in v["vod_play_url"] and v["vod_play_url"].split("$", 1)[1].startswith("http")
        check("detail", bool(v["vod_name"]) and has_play,
              v["vod_name"][:30])
        p = sp.playerContent("", r["list"][0]["vod_id"], "")
        is_p0 = p.get("parse") == 0 and p.get("url", "").startswith("http")
        check("player", is_p0 and "playUrl" not in p,
              "parse=%s" % p.get("parse"))
        # m3u8 可达性（不带 Referer）
        if is_p0:
            import urllib.request as _rq
            try:
                _req = _rq.Request(p["url"], headers={"User-Agent": sp.headers["User-Agent"]})
                with _rq.urlopen(_req, timeout=12) as _resp:
                    _code = _resp.getcode()
                    _head = _resp.read(200).decode("utf-8", errors="ignore")
                check("m3u8_http", _code == 200 and "#EXTM3U" in _head,
                      "code=%s" % _code)
            except Exception as e:
                check("m3u8_http", False, str(e)[:60])

    print("ALL PASS" if ok else "SOME FAILED")
