# -*- coding: utf-8 -*-
# 萌妻涩涩 (DGAV06 / AV Discovery 06) — TVBox py 源
# host: ow63.com（extend 可传 {"host": "https://其他域名"} 换前台域）
#
# 站点三层壳，源里各拆一层：
# 1) 门口是假验证页（纯前端滑块）：服务端只认 cookie
#    _slide_passed=1，请求带上即过，不用真过滑块。
# 2) 每个页面响应都是 document.write(外层(unescape(内层("HEX"))))
#    的整页编码壳（函数名每次响应随机换）：HEX 解码就是真 HTML，
#    _fetch 里透明脱壳。
# 3) 封面走 cache-*.sgvafw.com 缓存链（对部分出口直接 403）：
#    其路径 /base/<base64>.cache 里藏着源图地址，解出来直连源图。
#
# 列表：首页/板块走 /zh/{slug}、分类走 /zh/browse/{id}，翻页统一
# /page/{n}?order=latest（order 必须全程一致，混用会串序重叠）。
# 详情即播放页 /zh/screen/{id}，页内 window.videoConfig JSON
# 带签名的 m3u8 直链（url 字段），parse=0 下发。

import re
import json
import time
import base64
import gzip
import urllib.request
import urllib.parse
import urllib.error

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


class Spider(BaseSpider):

    SECTIONS = [
        ('new-release', '最近更新'), ('trending', '热门'),
        ('chinese-subtitle', '中文字幕'), ('uncensored-leak', '无码流出'),
        ('siro', '素人SIRO'), ('luxu', 'LUXU'), ('gana', 'GANA'),
        ('maan', 'PRESTIGE PREMIUM'), ('scute', 'S-CUTE'), ('ara', 'ARA'),
        ('fc2', 'FC2'), ('heyzo', 'HEYZO'), ('tokyohot', 'Tokyo Hot'),
        ('1pondo', '1Pondo'), ('caribbeancom', 'Caribbeancom'),
        ('caribbeancompr', 'Caribbeancompr'), ('10musume', '10musume'),
        ('pacopacomama', 'Pacopacomama'), ('gachinco', 'Gachinco'),
        ('xxxav', 'XXX-AV'), ('marriedslash', 'Married Slash'),
        ('naughty4610', 'Naughty 4610'), ('naughty0930', 'Naughty 0930'),
        ('madou', '亚洲传媒'), ('twav', 'TWAV'), ('furuke', 'Furuke'),
        ('klive', 'K-Live'), ('clive', 'C-Live'),
    ]
    # 首页导航现抓失败时的兜底分类（id 与站方一致）
    BROWSE_FALLBACK = [
        ('44090', '国产'), ('43997', '卡通动漫'), ('44002', '中文字幕'),
        ('44006', '三级伦理'), ('44011', '麻豆传媒'), ('44015', 'SM调教'),
        ('44315', '国产厂商'), ('44041', '日本无码'), ('44050', '日本有码'),
        ('44300', '水果派解说'), ('44091', '主播视讯'), ('44092', '蜜桃影像传媒'),
        ('44093', '其他传媒'), ('44094', '欧美性爱'), ('44095', '黑料事件'),
        ('44096', '91制片厂'), ('44097', '台湾swag'), ('44098', '精东影业'),
        ('44099', '天美传媒'), ('44100', '美女写真'), ('44101', '糖心Vlog'),
        ('44102', '星空无限传媒'), ('44103', '葫芦影业'), ('44104', '中字无码'),
        ('44106', '中字有码'), ('44107', '女同系列'),
    ]

    def __init__(self):
        self.host = 'https://ow63.com'
        self.ua = ('Mozilla/5.0 (Linux; Android 13; SM-G991B) '
                   'AppleWebKit/537.36 (KHTML, like Gecko) '
                   'Chrome/131.0.0.0 Mobile Safari/537.36')
        self._cats_cache = None

    def getName(self):
        return '萌妻涩涩'

    def init(self, extend=''):
        try:
            ex = json.loads(extend) if isinstance(extend, str) and extend else extend
            if isinstance(ex, dict) and ex.get('host'):
                self.host = str(ex['host']).rstrip('/')
        except Exception:
            pass
        return True

    def isVideoFormat(self, url):
        return bool(re.search(r'\.(m3u8|mp4|m4v|ts)(\?|$)', str(url or ''), re.I))

    def manualVideoCheck(self):
        return False

    # ---------- 网络层 ----------
    def _fetch(self, path, timeout=20):
        url = path if path.startswith('http') else self.host + path
        last = ''
        for attempt in range(3):
            try:
                rq = urllib.request.Request(url, headers={
                    'User-Agent': self.ua,
                    'Cookie': '_slide_passed=1',
                    'Accept': 'text/html,application/xhtml+xml,*/*',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                    'Accept-Encoding': 'gzip',
                    'Referer': self.host + '/zh/',
                })
                resp = urllib.request.urlopen(rq, timeout=timeout)
                body = resp.read()
                if resp.headers.get('Content-Encoding') == 'gzip':
                    body = gzip.decompress(body)
                return self._unshell(body.decode('utf-8', 'ignore'))
            except Exception as e:
                last = str(e)
                time.sleep(0.5 * (attempt + 1))
        return ''

    @staticmethod
    def _unshell(text):
        # 整页编码壳：document.write(fn(unescape(fn2("HEX", "%"))))
        # 内层 fn2 只是给 HEX 每两字符插分隔符，外层 fn 是 UTF-8
        # 解码——合起来等价于 hex 解码 + UTF-8 解码。函数名随机，
        # 只认「括号引号里的一整段超长 hex」。
        if not text or 'document.write(' not in text[:60]:
            return text
        m = re.search(r'\("([0-9a-f]{1000,})"', text)
        if not m:
            return text
        try:
            return bytes.fromhex(m.group(1)).decode('utf-8', 'ignore')
        except Exception:
            return text

    # ---------- 封面 ----------
    @staticmethod
    def _pic(url):
        # cache 链：/base/<base64>.cache 解出源图直连（cache 域对
        # 部分出口 403，源图域可达）；不合式的原样返回。
        url = (url or '').strip()
        m = re.match(r'https?://cache-[^/]+/base/([A-Za-z0-9+/=]+)\.cache$', url)
        if m:
            try:
                origin = base64.b64decode(m.group(1)).decode('utf-8', 'ignore')
                if origin.startswith('http'):
                    return origin
            except Exception:
                pass
        return url

    # ---------- 卡片 ----------
    def _cards(self, html):
        out = []
        seen = set()
        for m in re.finditer(
                r'<a href="(/zh/screen/([^"/]+))" title="([^"]*)">\s*'
                r'<img src="([^"]+)"', html or ''):
            vid = m.group(2)
            if vid in seen:
                continue
            seen.add(vid)
            tail = html[m.end():m.end() + 400]
            dm = re.search(r'video-duration">([^<]+)<', tail)
            out.append({
                'vod_id': vid,
                'vod_name': m.group(3).strip(),
                'vod_pic': self._pic(m.group(4)),
                'vod_remarks': dm.group(1).strip() if dm else '',
            })
        return out

    def _pagecount(self, html, page, got):
        # 页内有总数（共 N 项/部）时按每页 20 算真页数
        tm = re.search(r'共[:：]?\s*(?:<strong>)?(\d+)(?:</strong>)?\s*[项部]',
                       html or '')
        if tm:
            total = int(tm.group(1))
            return max(page, (total + 19) // 20)
        mx = page
        for pm in re.finditer(r'/page/(\d+)', html or ''):
            mx = max(mx, int(pm.group(1)))
        if mx > page:
            return mx
        return page + 1 if got >= 20 else page

    # ---------- 分类表 ----------
    def _classes(self):
        if self._cats_cache:
            return self._cats_cache
        classes = [{'type_id': 'sec:' + slug, 'type_name': name}
                   for slug, name in self.SECTIONS]
        classes += [
            {'type_id': 'ai:', 'type_name': 'AI短剧'},
            {'type_id': 'ai:duanju', 'type_name': 'AI成人短剧'},
            {'type_id': 'ai:manju', 'type_name': 'AI成人漫剧'},
            {'type_id': 'ai:shipin', 'type_name': 'AI成人视频'},
        ]
        browse = list(self.BROWSE_FALLBACK)
        try:
            html = self._fetch('/zh/')
            got = []
            seen = set()
            for m in re.finditer(
                    r'href="/zh/browse/(\d+)"[^>]*>(?:<span>)?([^<]{1,16})', html):
                if m.group(1) not in seen and m.group(2).strip():
                    seen.add(m.group(1))
                    got.append((m.group(1), m.group(2).strip()))
            if len(got) >= 10:
                browse = got
        except Exception:
            pass
        classes += [{'type_id': 'browse:' + bid, 'type_name': name}
                    for bid, name in browse]
        self._cats_cache = classes
        return classes

    # ---------- 首页 ----------
    def homeContent(self, filter=True):
        return {'class': self._classes(), 'filters': {}, 'list': []}

    def homeVideoContent(self):
        html = self._fetch('/zh/')
        return {'list': self._cards(html)[:24]}

    # ---------- 分类 ----------
    def _list_url(self, tid, page):
        kind, _, key = str(tid).partition(':')
        if kind == 'browse':
            base = '/zh/browse/%s' % key
        else:
            base = '/zh/%s' % key
        if page > 1:
            return '%s/page/%d?order=latest' % (base, page)
        return '%s?order=latest' % base

    def _cards_ai(self, html):
        out = []
        seen = set()
        for m in re.finditer(
                r'<a href="(/zh/ai-duanju/play/(\d+))">\s*'
                r'<img src="([^"]+)" alt="([^"]*)"', html or ''):
            aid = m.group(2)
            if aid in seen:
                continue
            seen.add(aid)
            out.append({
                'vod_id': 'ai:' + aid,
                'vod_name': m.group(4).strip(),
                'vod_pic': self._pic(m.group(3)),
                'vod_remarks': 'AI',
            })
        return out

    def categoryContent(self, tid, pg, filter=True, extend=None):
        page = int(pg) if str(pg).isdigit() else 1
        result = {'list': [], 'page': page, 'pagecount': 1, 'limit': 20,
                  'total': 0}
        if str(tid).startswith('ai'):
            key = str(tid).partition(':')[2]
            base = '/zh/ai-duanju/category/%s' % key if key else '/zh/ai-duanju'
            path = base if page <= 1 else '%s?page=%d' % (base, page)
            html = self._fetch(path)
            if not html:
                return result
            cards = self._cards_ai(html)
            result['list'] = cards
            result['pagecount'] = self._pagecount(html, page, len(cards))
            result['total'] = len(cards)
            return result
        html = self._fetch(self._list_url(tid, page))
        if not html:
            return result
        cards = self._cards(html)
        result['list'] = cards
        result['pagecount'] = self._pagecount(html, page, len(cards))
        result['total'] = len(cards)
        return result

    # ---------- 详情 / 播放 ----------
    def _video_config(self, html):
        i = (html or '').find('window.videoConfig')
        if i < 0:
            return {}
        j = html.find('{', i)
        if j < 0:
            return {}
        depth = 0
        in_str = False
        esc = False
        for k in range(j, len(html)):
            ch = html[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 == '{':
                depth += 1
            elif ch == '}':
                depth -= 1
                if depth == 0:
                    try:
                        cfg = json.loads(html[j:k + 1])
                        return cfg if isinstance(cfg, dict) else {}
                    except Exception:
                        return {}
        return {}

    def detailContent(self, ids):
        vid = ids[0] if isinstance(ids, (list, tuple)) and ids else ids
        vid = str(vid or '')
        if vid.startswith('ai:') or 'ai-duanju/play/' in vid:
            am = re.search(r'(\d+)', vid)
            if not am:
                return {'list': []}
            page = '/zh/ai-duanju/play/%s' % am.group(1)
            html = self._fetch(page)
            if not html:
                return {'list': []}
            tm = re.search(r'<title>([^<]+)</title>', html)
            name = ''
            if tm:
                name = re.sub(r'\s*-\s*AV Discovery 06\s*$', '', tm.group(1)).strip()
            pm = (re.search(r'property="og:image" content="([^"]+)"', html)
                  or re.search(r'<img src="(https://cache-[^"]+)"', html))
            return {'list': [{
                'vod_id': vid,
                'vod_name': name or vid,
                'vod_pic': self._pic(pm.group(1)) if pm else '',
                'vod_content': '',
                'vod_remarks': 'AI',
                'vod_play_from': 'DGAV',
                'vod_play_url': '播放$%s' % page,
            }]}
        m = re.search(r'screen/([^/?#]+)', vid)
        if m:
            vid = m.group(1)
        if not vid:
            return {'list': []}
        page = '/zh/screen/%s' % vid
        html = self._fetch(page)
        if not html:
            return {'list': []}
        cfg = self._video_config(html)
        name = (cfg.get('title') or '').strip()
        if not name:
            tm = re.search(r'<title>([^<]+)</title>', html)
            if tm:
                name = re.sub(r'\s*-\s*AV Discovery 06\s*$', '', tm.group(1)).strip()
        desc = ''
        dm = re.search(r'"description"\s*:\s*"((?:[^"\\]|\\.)*)"', html)
        if dm:
            try:
                desc = json.loads('"%s"' % dm.group(1))
            except Exception:
                desc = dm.group(1)
        return {'list': [{
            'vod_id': vid,
            'vod_name': name or vid,
            'vod_pic': self._pic(cfg.get('img') or ''),
            'vod_content': desc,
            'vod_remarks': str(cfg.get('fanhao') or '').upper(),
            'vod_play_from': 'DGAV',
            'vod_play_url': '播放$%s' % page,
        }]}

    def playerContent(self, flag, id, vipFlags=None):
        raw = str(id or '')
        m = (re.search(r'(/zh/screen/[^/?#\s]+)', raw)
             or re.search(r'(/zh/ai-duanju/play/[^/?#\s]+)', raw))
        page = m.group(1) if m else '/zh/screen/%s' % raw.strip('/')
        hdr = {'User-Agent': self.ua, 'Referer': self.host + '/'}
        html = self._fetch(page)
        cfg = self._video_config(html) if html else {}
        url = (cfg.get('url') or cfg.get('video_url') or '').strip()
        if not url and html:
            mm = re.search(r'https?://[^\s"\'<>\\]+\.m3u8[^\s"\'<>\\]*', html)
            if mm:
                url = mm.group(0)
        if url:
            return {'parse': 0, 'jx': 0, 'url': url, 'header': hdr}
        return {'parse': 1, 'jx': 0, 'url': self.host + page, 'header': hdr}

    # ---------- 搜索 ----------
    def searchContent(self, key, quick=None, pg='1'):
        page = int(pg) if str(pg).isdigit() else 1
        result = {'list': [], 'page': page, 'pagecount': 1, 'limit': 20,
                  'total': 0}
        if not key:
            return result
        kw = urllib.parse.quote(str(key), safe='')
        if page > 1:
            path = '/zh/lookup/page/%d?keyword=%s' % (page, kw)
        else:
            path = '/zh/lookup?keyword=%s' % kw
        html = self._fetch(path)
        if not html:
            return result
        cards = self._cards(html)
        result['list'] = cards
        result['pagecount'] = self._pagecount(html, page, len(cards))
        result['total'] = len(cards)
        return result

    def localProxy(self, params):
        return [404, 'text/plain', b'']
