# -*- coding: utf-8 -*-
# TG交流群 https://t.me/hshsjk9

import sys, re, json, html as H, http.client, ssl
from urllib.parse import quote, urljoin
sys.path.append('..')
try:
    from base.spider import Spider
except ImportError:
    class Spider:
        def fetch(self, url, headers=None, timeout=10): return ''

CATS = [
    ['jinriheiliao', '今日黑料'], ['bichiregua', '必吃热瓜'], ['shenghuoheiliao', '生活黑料'],
    ['zhutidasai', '主题大赛'], ['wanghongheiliao', '网红黑料'], ['bilujingping', '必撸精品'],
    ['jingxuanheji', '精选合集'], ['xiaoyuanyinluan', '校园淫乱'], ['AIfuli', '51动漫'],
    ['luanlunshequ', '乱伦社区'], ['mingxingheiliao', '明星黑料'], ['gouxueduanju', '狗血短剧'],
    ['lieqizhongkou', '猎奇重口'],
]

HOSTS = [
    'https://jgecz1.laskxwwk.cc',
    'https://jgecz2.laskxwwk.cc',
    'https://jgecz3.laskxwwk.cc',
    'https://d1csx7olm8mwg9.cloudfront.net',
    'https://51hlws.com',
]

def _mirror(pic):
    if not pic:
        return ''
    return re.sub(r'^https?://pic\.[^/]+', 'https://imgpublic.ycomesc.live', pic)

class Spider(Spider):
    def init(self, extend=''):
        self.base = HOSTS[0]
        self.ua = 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36'
        self._conn = {}
        for host in HOSTS:
            h = self._get(host + '/')
            if h and '51黑料网' in h and 'post-card' in h and len(h) > 20000:
                self.base = host
                break
        return ''

    def _get(self, url, ref=None):
        for attempt in range(2):
            try:
                p = url.split('://', 1)[1]
                host, path = p.split('/', 1)
                path = '/' + path
                key = host
                if key not in self._conn:
                    self._conn[key] = http.client.HTTPSConnection(host, timeout=15, context=ssl.create_default_context())
                conn = self._conn[key]
                hd = {'User-Agent': self.ua, 'Accept-Language': 'zh-CN,zh;q=0.9', 'Connection': 'keep-alive', 'Accept-Encoding': 'identity'}
                if ref:
                    hd['Referer'] = ref
                conn.request('GET', path, headers=hd)
                r = conn.getresponse()
                b = r.read()
                return b.decode('utf-8', 'replace') if b else ''
            except Exception:
                try:
                    del self._conn[url.split('://', 1)[1].split('/', 1)[0]]
                except Exception:
                    pass
        return ''

    def _cards(self, html):
        out = []
        for m in re.finditer(r'<div class="post-card" id="post-card-(\d+)"', html):
            start = m.start()
            nxt = html.find('<div class="post-card" id="post-card-', start + 10)
            block = html[start:nxt if nxt > 0 else start + 3000]
            t = re.search(r'post-card-title[^>]*>\s*([^<]+)<', block)
            img = re.search(r'z-image-loader-url="([^"]+)"', block)
            if t:
                pic = _mirror(img.group(1)) if img else ''
                out.append({'id': '/archives/%s/' % m.group(1), 'name': H.unescape(t.group(1)).strip(), 'pic': pic})
        return out

    def homeContent(self, filter=False):
        return {'class': [{'type_id': c[0], 'type_name': c[1]} for c in CATS], 'list': self.homeVideoContent()['list']}

    def homeVideoContent(self):
        h = self._get(self.base + '/')
        ls = []
        for it in self._cards(h)[:30]:
            ls.append({'vod_id': it['id'], 'vod_name': it['name'], 'vod_pic': it['pic'], 'vod_remarks': ''})
        return {'list': ls}

    def categoryContent(self, tid, pg, filter=False, extend=''):
        try:
            p = int(pg)
        except Exception:
            p = 1
        url = '%s/category/%s/' % (self.base, tid) if p <= 1 else '%s/category/%s/%d/' % (self.base, tid, p)
        h = self._get(url)
        ls = []
        for it in self._cards(h):
            ls.append({'vod_id': it['id'], 'vod_name': it['name'], 'vod_pic': it['pic'], 'vod_remarks': ''})
        return {'list': ls, 'page': p, 'pagecount': 30, 'total': 99999}

    def detailContent(self, ids, quick='1'):
        vid = ids[0] if isinstance(ids, (list, tuple)) and ids else ids
        self._last_vid = str(vid)
        url = urljoin(self.base, str(vid))
        h = self._get(url)
        if not h:
            return {'list': []}
        t = re.search(r'<h1[^>]*>([^<]+)</h1>', h)
        name = H.unescape(t.group(1)).strip() if t else vid
        m = re.search(r"data-config='(.*?)'", h, re.S)
        play = ''
        pic = ''
        if m:
            try:
                cfg = json.loads(H.unescape(m.group(1)))
                v = (cfg.get('video') or {})
                play = v.get('url') or ''
                pic = re.sub(r'^https?://[^/]+', 'https://imgpublic.ycomesc.live', v.get('pic') or '')
            except Exception:
                pass
        if not pic:
            im = re.search(r'z-image-loader-url="([^"]+)"', h)
            pic = _mirror(im.group(1)) if im else ''
        vod = {'vod_id': vid, 'vod_name': name, 'vod_pic': pic, 'vod_remarks': '51黑料'}
        if play:
            vod['vod_play_from'] = '正片'
            vod['vod_play_url'] = '正片$' + play
        else:
            vod['vod_play_from'] = ''
            vod['vod_play_url'] = ''
        return {'list': [vod]}

    def searchContent(self, key, quick=False, pg='1'):
        if not key:
            return {'list': []}
        h = self._get(self.base + '/search/' + quote(key) + '/')
        ls = []
        for it in self._cards(h)[:30]:
            ls.append({'vod_id': it['id'], 'vod_name': it['name'], 'vod_pic': it['pic'], 'vod_remarks': ''})
        return {'list': ls, 'page': 1}

    def playerContent(self, flag, id, vipFlags=None):
        u = id if id.startswith('http') else ''
        if not u:
            return {'parse': 0, 'url': '', 'msg': '无播放地址'}
        return {'parse': 0, 'url': u, 'header': {'User-Agent': self.ua, 'Referer': self.base + '/'}}