# coding=utf-8
# ============================================================
#  书音FM（m.dakuwo.com / 爱书音）—— OK影视 5.x / TVBox / CatVod  py 接口
#
#  · 内容：有声小说 / 广播剧 / 评书 / 戏曲 / 相声小品 / 儿童 等 7 万+ 部
#  · 播放：官方签名接口直出音频（mp3 / m4a），无需登录、无需解析
#  · 无 VIP 墙：标记需要权限的章节，服务端照样签发播放地址，全部可播
# ============================================================
import sys
import json
import time
import hashlib
import urllib.parse
import urllib.request
import email.utils
from concurrent.futures import ThreadPoolExecutor

try:
    import requests
    from requests.adapters import HTTPAdapter
except Exception:
    requests = None

sys.path.append('..')
try:
    from base.spider import Spider as _BaseSpider
except Exception:
    class _BaseSpider(object):
        pass

HOST = 'https://weixin.aikeu.com'
API = HOST + '/ecmsapi/index.php'
SIGN_SALT = 'ecmsapitoken'
UA = ('Mozilla/5.0 (Linux; Android 13; SM-G991B) AppleWebKit/537.36 '
      '(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36')

HDRS = {
    'User-Agent': UA,
    'Referer': 'https://m.dakuwo.com/',
    'Accept': 'application/json, text/plain, */*',
}

# ---------- 分类（classid, 名称） ----------
CLASSES = [
    ('0', '全部'),
    ('28', '有声小说'),
    ('1', '有声小说·言情'),
    ('2', '有声小说·玄幻'),
    ('5', '有声小说·恐怖'),
    ('7', '有声小说·穿越'),
    ('8', '有声小说·都市'),
    ('16', '有声小说·历史'),
    ('33', '有声小说·悬疑'),
    ('38', '有声小说·文学'),
    ('39', '有声小说·推理'),
    ('40', '有声小说·军事'),
    ('41', '有声小说·职场'),
    ('56', '有声小说·反腐'),
    ('58', '有声小说·人物'),
    ('60', '有声小说·修真'),
    ('63', '有声小说·网游'),
    ('92', '有声小说·武侠'),
    ('29', '广播剧'),
    ('10', '广播剧·耽美'),
    ('12', '广播剧·爱情'),
    ('51', '广播剧·古风'),
    ('54', '广播剧·现代'),
    ('30', '评书'),
    ('42', '评书·单田芳'),
    ('43', '评书·刘兰芳'),
    ('44', '评书·田连元'),
    ('45', '评书·袁阔成'),
    ('46', '评书·连丽如'),
    ('47', '评书·张少佐'),
    ('48', '评书·田战义'),
    ('49', '评书·孙一'),
    ('53', '评书·袁田'),
    ('55', '评书·王玥波'),
    ('57', '评书·郭德纲'),
    ('62', '评书·关勇超'),
    ('65', '评书·王传林'),
    ('105', '评书·石连君'),
    ('50', '评书·其他'),
    ('31', '百家讲坛'),
    ('34', '养生'),
    ('35', '娱乐'),
    ('59', '粤语'),
    ('66', '车载专区'),
    ('67', '车载·资讯'),
    ('68', '车载·短剧'),
    ('69', '车载·娱乐'),
    ('70', '车载·音乐'),
    ('71', '车载·情感'),
    ('72', '车载·搞笑'),
    ('73', '车载·相声小品'),
    ('74', '车载·汽车'),
    ('75', '车载·公开课'),
    ('76', '车载·生活'),
    ('77', '车载·旅游'),
    ('81', '戏曲'),
    ('82', '戏曲·越剧'),
    ('83', '戏曲·京剧'),
    ('84', '戏曲·黄梅戏'),
    ('85', '戏曲·昆曲'),
    ('86', '戏曲·秦腔'),
    ('87', '戏曲·越剧(二)'),
    ('88', '戏曲·蒲剧'),
    ('89', '戏曲·评弹'),
    ('90', '戏曲·晋剧'),
    ('97', '戏曲·大鼓'),
    ('91', '相声小品'),
    ('98', '音乐'),
    ('99', '音乐·古风'),
    ('100', '儿童'),
    ('101', '儿童·知识'),
    ('102', '儿童·故事'),
    ('103', '儿童·儿歌'),
    ('104', '儿童·家长课堂'),
]

CLASS_NAME = dict(CLASSES)

# ---------- 首页只显示 6 个大类，原细分类放进「筛选-类型」 ----------


def _subs(*parents):
    """按名称前缀挑出子分类：[(classid, 短名)]"""
    return [(c, n.split('·', 1)[1]) for p in parents
            for c, n in CLASSES if n.startswith(p + '·')]


def _group(tid, name, subs):
    return (tid, name, [(tid, '全部')] + subs)


GROUPS = [
    _group('28', '有声小说', _subs('有声小说')),
    _group('29', '广播剧', _subs('广播剧')),
    _group('30', '评书', _subs('评书')),
    _group('81', '戏曲', _subs('戏曲')),
    _group('100', '儿童', _subs('儿童')),
    ('91', '综艺其他', [(c, CLASS_NAME[c]) for c in
                      ('91', '31', '34', '35', '59', '98', '99', '66')]
                     + [(c, '车载·' + n) for c, n in _subs('车载')]),
]

# ---------- 排序 ----------
SORTS = [
    {'n': '最新更新', 'v': 'newstime desc'},
    {'n': '最多播放', 'v': 'onclick desc'},
    {'n': '最多评论', 'v': 'plnum desc'},
    {'n': '最新入库', 'v': 'id desc'},
]


# 复用连接：省掉每次请求的 TCP/TLS 握手
SESSION = None
if requests is not None:
    SESSION = requests.Session()
    SESSION.headers.update(HDRS)
    _ad = HTTPAdapter(pool_connections=4, pool_maxsize=8)
    SESSION.mount('https://', _ad)
    SESSION.mount('http://', _ad)

_CACHE = {}          # key -> (过期时间, 数据)
CACHE_MAX = 60
_CLOCK = [0]         # 服务器时间 - 本机时间（秒）


def log(msg):
    print('[书音FM] %s' % msg)


def cache_get(key):
    item = _CACHE.get(key)
    if item and item[0] > time.time():
        return item[1]
    return None


def cache_set(key, value, ttl):
    if len(_CACHE) >= CACHE_MAX:
        _CACHE.clear()
    _CACHE[key] = (time.time() + ttl, value)


def _sync_clock(date_header):
    try:
        server = email.utils.parsedate_to_datetime(date_header).timestamp()
        _CLOCK[0] = int(server - time.time())
    except Exception:
        pass


def http_get(url, timeout=10):
    if SESSION is not None:
        r = SESSION.get(url, timeout=(5, timeout))
        _sync_clock(r.headers.get('Date'))
        r.raise_for_status()
        return r.content.decode('utf-8-sig', 'ignore')
    req = urllib.request.Request(url, headers=HDRS)
    with urllib.request.urlopen(req, timeout=timeout) as r:
        _sync_clock(r.headers.get('Date'))
        return r.read().decode('utf-8-sig', 'ignore')


def api(_tries=2, _timeout=10, **params):
    url = API + '?' + urllib.parse.urlencode(params)
    for i in range(_tries):
        try:
            return json.loads(http_get(url, _timeout))
        except Exception as ex:
            log('请求失败(%d/%d) %s: %s' % (i + 1, _tries, params.get('act'), ex))
            if i + 1 >= _tries:
                raise
            time.sleep(0.3)


def cached_api(ttl, **params):
    """只缓存有内容的结果，空结果/报错下次重新请求"""
    key = urllib.parse.urlencode(sorted(params.items()))
    d = cache_get(key)
    if d is None:
        d = api(**params)
        data = d.get('data') or {}
        if data.get('list') or data.get('detail'):
            cache_set(key, d, ttl)
    return d


# 短于这个秒数视为“失败时返回的短音频”
MIN_SECONDS = 25
HEAD_BYTES = 65536


def fetch_range(url, start):
    """读取 start 起的一小段，返回 (状态码, 类型, 文件总大小, 数据)"""
    h = {'User-Agent': UA, 'Referer': 'https://m.dakuwo.com/', 'Accept': '*/*',
         'Accept-Encoding': 'identity',
         'Range': 'bytes=%d-%d' % (start, start + HEAD_BYTES - 1)}
    if SESSION is not None:
        r = SESSION.get(url, headers=h, stream=True, timeout=(3, 4))
        try:
            code, rh = r.status_code, r.headers
            body = b''
            for chunk in r.iter_content(8192):
                body += chunk
                if len(body) >= HEAD_BYTES:
                    break
        finally:
            r.close()
    else:
        req = urllib.request.Request(url, headers=h)
        with urllib.request.urlopen(req, timeout=4) as r:
            code, rh, body = r.getcode(), r.headers, r.read(HEAD_BYTES)
    total = 0
    try:
        if code == 206:
            total = int(rh.get('Content-Range').split('/')[-1])
        elif code == 200:
            total = int(rh.get('Content-Length'))
    except Exception:
        pass
    return code, (rh.get('Content-Type') or '').lower(), total, body[:HEAD_BYTES]


def mp4_seconds(head):
    i = head.find(b'mvhd')
    if i < 0 or len(head) < i + 36:
        return None
    if head[i + 4] == 1:
        scale = int.from_bytes(head[i + 24:i + 28], 'big')
        dur = int.from_bytes(head[i + 28:i + 36], 'big')
    else:
        scale = int.from_bytes(head[i + 16:i + 20], 'big')
        dur = int.from_bytes(head[i + 20:i + 24], 'big')
    return dur / float(scale) if scale and dur else None


def mp3_seconds(data, size):
    """data 从音频数据开头算起，size 是音频部分的字节数"""
    for i in range(min(len(data) - 4, 4096)):
        b1, b2, b3, b4 = data[i:i + 4]
        if b1 != 0xFF or (b2 & 0xE6) != 0xE2:      # 只认 Layer III 帧头
            continue
        ver = (b2 >> 3) & 3
        br, sr = b3 >> 4, (b3 >> 2) & 3
        if ver == 1 or br in (0, 15) or sr == 3:
            continue
        if ver == 3:
            kbps = (32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320)[br - 1]
        else:
            kbps = (8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160)[br - 1]
        rate = (44100, 48000, 32000)[sr] // {3: 1, 2: 2, 0: 4}[ver]
        # 变长码率文件：用 Xing/Info 里记录的总帧数
        frame = data[i:i + 200]
        for tag in (b'Xing', b'Info'):
            j = frame.find(tag)
            if j >= 0 and len(frame) >= j + 12 and frame[j + 7] & 1:
                n = int.from_bytes(frame[j + 8:j + 12], 'big')
                return n * (1152 if ver == 3 else 576) / float(rate)
        return size * 8 / (kbps * 1000.0) if size > 0 else None
    return None


def clean(s):
    """播放列表名称里不能出现 $ 和 #"""
    if s is None:
        return ''
    return str(s).replace('$', '＄').replace('#', '＃').strip()


class Spider(_BaseSpider):

    def getName(self):
        return '书音FM'

    def init(self, extend=''):
        self.extend = extend or ''
        self._sub = None

    def destroy(self):
        pass

    def isVideoFormat(self, url):
        return False

    def manualVideoCheck(self):
        return False

    # ---------------- 内部 ----------------

    def _to_vod(self, r):
        year = ''
        nt = str(r.get('newstime') or '')
        if len(nt) >= 4 and nt[:4].isdigit():
            year = nt[:4]
        ft = (r.get('filetype') or '').strip()
        remark = ft
        if not remark:
            remark = str(r.get('onclick') or '') + '播放'
        intro = (r.get('moviesay') or '').strip()
        player = (r.get('player') or '').strip()
        extra = []
        if player:
            extra.append('主播：' + player)
        if r.get('onclick'):
            extra.append('播放：%s' % r.get('onclick'))
        if extra:
            intro = (intro + '\n\n' if intro else '') + '\n'.join(extra)
        return {
            'vod_id': str(r.get('id') or ''),
            'vod_name': (r.get('title') or '').strip(),
            'vod_pic': r.get('titlepic') or '',
            'vod_remarks': remark,
            'vod_year': year,
            'type_name': CLASS_NAME.get(str(r.get('classid')), ''),
            'vod_content': intro,
        }

    def _page(self, data, pg, size):
        rows = data.get('list') or []
        try:
            total = int(data.get('total') or 0)
        except Exception:
            total = 0
        try:
            pagecount = int(data.get('totalpage') or 1)
        except Exception:
            pagecount = 1
        if pagecount < 1:
            pagecount = 1
        return {
            'list': [self._to_vod(r) for r in rows],
            'page': int(pg),
            'pagecount': pagecount,
            'limit': size,
            'total': total,
        }

    def _episode_page(self, aid, page):
        d = api(_tries=3, _timeout=15, mod='movie', act='movielist',
                id=aid, page=page, pagesize=1200)
        data = d.get('data') or {}
        try:
            tp = int(data.get('totalpage') or 1)
        except Exception:
            tp = 1
        return data.get('moielist') or [], tp

    def _episodes(self, aid):
        """拉全章节（站方单页最多给 1200 条，多页时并发拉取）"""
        rows, tp = self._episode_page(aid, 1)
        out = list(rows)
        pages = range(2, min(tp, 12) + 1)
        if rows and pages:
            with ThreadPoolExecutor(max_workers=4) as pool:
                for more, _ in pool.map(lambda p: self._episode_page(aid, p), pages):
                    out.extend(more)
        return out

    # ---------------- 首页 ----------------

    def homeContent(self, filter):
        cls = [{'type_id': t, 'type_name': n} for t, n, _ in GROUPS]
        filters = {}
        for t, _, subs in GROUPS:
            filters[t] = [
                {'key': 'cid', 'name': '类型',
                 'value': [{'n': n, 'v': c} for c, n in subs]},
                {'key': 'sort', 'name': '排序', 'value': SORTS},
            ]
        return {'class': cls, 'filters': filters}

    def homeVideoContent(self):
        try:
            d = cached_api(300, act='list', mod='movie', classid='28', page=1,
                           pagesize=30, sort='newstime desc')
            return {'list': [self._to_vod(r) for r in ((d.get('data') or {}).get('list') or [])]}
        except Exception:
            return {'list': []}

    # ---------------- 分类 ----------------

    def categoryContent(self, tid, pg, filter, extend):
        tid = str(tid or '0')
        try:
            pg = int(pg or 1)
        except Exception:
            pg = 1
        size = 30
        sort = 'newstime desc'
        if isinstance(extend, dict) and extend.get('cid'):
            tid = str(extend.get('cid'))
        if isinstance(extend, dict) and extend.get('sort'):
            sort = extend.get('sort')
        try:
            d = cached_api(300, act='list', mod='movie', classid=tid, page=pg, pagesize=size, sort=sort)
        except Exception:
            return {'list': [], 'page': pg, 'pagecount': 1, 'limit': size, 'total': 0}
        return self._page(d.get('data') or {}, pg, size)

    # ---------------- 详情 ----------------

    def detailContent(self, ids):
        if isinstance(ids, (list, tuple)):
            vid = str(ids[0])
        else:
            vid = str(ids)
        vid = vid.strip().split('?')[0]
        if vid.startswith('http'):
            vid = vid.rstrip('/').split('/')[-1].split('.')[0]

        hit = cache_get('vod:' + vid)
        if hit:
            return {'list': [hit]}

        # 详情和章节同时请求，不再排队
        with ThreadPoolExecutor(max_workers=2) as pool:
            f_det = pool.submit(cached_api, 600, mod='movie', act='detail', id=vid)
            f_eps = pool.submit(self._episodes, vid)
            try:
                d = f_det.result()
            except Exception:
                return {'list': []}
            try:
                eps = f_eps.result()
            except Exception as ex:
                log('章节获取失败: %s' % ex)
                eps = []
        det = (d.get('data') or {}).get('detail') or {}
        if not det:
            return {'list': []}

        plays = []
        for e in eps:
            eid = str(e.get('id') or '')
            if not eid:
                continue
            name = clean(e.get('title')) or ('第%s集' % eid)
            if str(e.get('control')) not in ('0', '', 'None'):
                name += ' [会员]'
            plays.append(name + '$' + vid + '|' + eid)

        intro = (det.get('moviesay') or '').strip()
        extra = []
        if det.get('player'):
            extra.append('主播：' + det.get('player').strip())
        if det.get('username'):
            extra.append('上传：' + det.get('username').strip())
        extra.append('集数：%d' % (len(eps) or int(det.get('plnum') or 0)))
        if det.get('filetype'):
            extra.append('状态：' + str(det.get('filetype')))
        if det.get('onclick'):
            extra.append('播放：%s' % det.get('onclick'))
        if intro:
            intro += '\n\n'
        intro += '\n'.join(extra)

        vod = {
            'vod_id': str(det.get('id') or vid),
            'vod_name': (det.get('title') or '').strip(),
            'vod_pic': det.get('titlepic') or '',
            'vod_year': '',
            'type_name': CLASS_NAME.get(str(det.get('classid')), ''),
            'vod_remarks': str(det.get('filetype') or ('%d集' % len(eps))),
            'vod_content': intro,
            'vod_play_from': '书音FM',
            'vod_play_url': '#'.join(plays),
        }
        if plays:
            cache_set('vod:' + vid, vod, 600)
        return {'list': [vod]}

    # ---------------- 搜索 ----------------

    def searchContent(self, key, quick, pg='1'):
        try:
            pg = int(pg or 1)
        except Exception:
            pg = 1
        size = 30
        keys = [key]
        # 站方搜索不认空格，带空格查不到时自动去空格 / 只取首词重试
        if key and (' ' in key or '\u3000' in key):
            k2 = key.replace(' ', '').replace('\u3000', '')
            if k2 and k2 not in keys:
                keys.append(k2)
            k3 = key.replace('\u3000', ' ').split(' ')[0]
            if k3 and k3 not in keys:
                keys.append(k3)
        data = {}
        for k in keys:
            try:
                d = cached_api(300, mod='movie', act='search', page=pg, pagesize=size,
                        keyword=k, sort='onclick desc')
            except Exception:
                continue
            data = d.get('data') or {}
            if data.get('list'):
                break
        return self._page(data, pg, size)

    searchContentAll = searchContent

    # ---------------- 播放 ----------------

    def _series_url(self, aid, eid):
        """取播放地址：失败或返回空时重新签名重试；每次点播都现取，不缓存"""
        for i in range(4):
            ts = int(time.time())
            # 第 2、4 次改用服务器时间签名，防止盒子/手机时钟不准
            if i % 2 == 1:
                ts += _CLOCK[0]
            raw = ('act=series&id=%s&mod=movie&movieId=%s&t=%s&token=%s'
                   % (aid, eid, ts, SIGN_SALT))
            token = hashlib.md5(raw.encode('utf-8')).hexdigest()
            try:
                d = api(_tries=1, _timeout=8, act='series', mod='movie',
                        id=aid, movieId=eid, t=ts, token=token)
                data = d.get('data') or {}
                url = (data.get('SeriesUrl') or '').strip()
                if url:
                    # 中文、空格转义；已转义的部分和签名参数保持原样
                    return urllib.parse.quote(url, safe=":/?&=%#+,;@!$'()*[]~")
                log('第%d次未拿到地址: %s' % (i + 1, json.dumps(d, ensure_ascii=False)[:200]))
            except Exception as ex:
                log('第%d次取地址异常: %s' % (i + 1, ex))
            if i < 3:
                time.sleep(0.5 * (i + 1))
        return ''

    def _probe(self, url):
        """地址能打开、且不是那种不到 20 秒的短音频，才返回 True"""
        try:
            code, ctype, total, head = fetch_range(url, 0)
            if code not in (200, 206) or ctype.startswith(
                    ('text/html', 'application/json', 'text/xml', 'application/xml')):
                log('音频地址异常: HTTP %s %s' % (code, ctype))
                return False
        except Exception as ex:
            log('音频地址打不开: %s' % ex)
            return False

        sec = None
        try:
            if head[4:8] == b'ftyp':                       # m4a
                sec = mp4_seconds(head)
            else:                                          # mp3
                skip, data = 0, head
                if head[:3] == b'ID3':
                    skip = 10 + ((head[6] << 21) | (head[7] << 14) | (head[8] << 7) | head[9])
                    if skip + 4096 <= len(head):
                        data = head[skip:]
                    else:                                  # 标签里带大封面图
                        c2, _, _, data = fetch_range(url, skip)
                        if c2 != 206:
                            data = b''
                sec = mp3_seconds(data, total - skip)
        except Exception as ex:
            log('时长解析失败: %s' % ex)

        if sec is not None:
            if sec < MIN_SECONDS:
                log('只有 %.1f 秒，判定为无效音频' % sec)
                return False
        elif 0 < total < 200 * 1024:                       # 算不出时长时看大小
            log('文件只有 %d 字节，判定为无效音频' % total)
            return False
        return True

    def _ready_url(self, aid, eid):
        """相当于自动帮你“刷新”：打不开或是短音频就重新取地址再试，最多 3 轮、约 12 秒"""
        deadline = time.time() + 12
        url = ''
        for i in range(3):
            new = self._series_url(aid, eid)
            url = new or url
            if new and self._probe(new):
                return new
            if time.time() >= deadline or i == 2:
                break
            time.sleep(1)
        # 检测一直不过也把地址交给播放器，避免检测误判导致不能播
        return url

    def playerContent(self, flag, id, vipFlags=None):
        did = str(id).strip()
        if '|' in did:
            aid, eid = did.split('|', 1)
        else:
            aid, eid = '', did

        url = self._ready_url(aid, eid) if aid and eid else ''

        return {
            'parse': 0,
            'playUrl': '',
            'url': url,
            'header': {
                'User-Agent': UA,
                'Referer': 'https://m.dakuwo.com/',
            },
        }

    def localProxy(self, param):
        return None
