# -*- coding: utf-8 -*-
# 听友听书（新 API listening-api 重写，2026-12-06）
import json
import urllib.parse
import urllib.request

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


class Spider(BaseSpider):
    def getName(self):
        return "听友听书"

    def init(self, extend=""):
        self.base = "https://tingyou.fm"
        self.api = self.base + "/listening-api"
        self.ua = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"
        self.classes = [
            {"type_id": "46", "type_name": "玄幻奇幻"},
            {"type_id": "11", "type_name": "武侠小说"},
            {"type_id": "19", "type_name": "言情通俗"},
            {"type_id": "21", "type_name": "相声小品"},
            {"type_id": "14", "type_name": "恐怖惊悚"},
            {"type_id": "17", "type_name": "官场商战"},
            {"type_id": "15", "type_name": "历史军事"},
            {"type_id": "9", "type_name": "百家讲坛"},
            {"type_id": "16", "type_name": "刑侦反腐"},
        ]

    def _headers(self):
        return {"User-Agent": self.ua, "Referer": self.base + "/listening",
                "Accept": "application/json,text/html,*/*;q=0.8"}

    def _get_json(self, url):
        try:
            r = BaseSpider.fetch(self, url, headers=self._headers(), timeout=15)
            txt = getattr(r, "text", "") or ""
            if txt:
                return json.loads(txt)
        except Exception:
            pass
        try:
            req = urllib.request.Request(url, headers=self._headers())
            return json.loads(urllib.request.urlopen(req, timeout=15).read().decode("utf-8", "ignore"))
        except Exception:
            return {}

    def _post_json(self, url, obj):
        data = json.dumps(obj).encode("utf-8")
        hdrs = dict(self._headers(), **{"Content-Type": "application/json"})
        try:
            r = BaseSpider.post(self, url, data=data, headers=hdrs, timeout=20)
            txt = getattr(r, "text", "") or ""
            if txt:
                return json.loads(txt)
        except Exception:
            pass
        try:
            req = urllib.request.Request(url, data=data, headers=hdrs, method="POST")
            return json.loads(urllib.request.urlopen(req, timeout=20).read().decode("utf-8", "ignore"))
        except Exception:
            return {}

    def _album(self, it):
        if not isinstance(it, dict) or not it.get("id"):
            return None
        remarks = []
        if it.get("count"):
            remarks.append("%s期" % it["count"])
        if it.get("teller"):
            remarks.append(str(it["teller"]))
        return {"vod_id": str(it["id"]), "vod_name": str(it.get("title") or ""),
                "vod_pic": str(it.get("cover_url") or ""), "vod_remarks": " · ".join(remarks)}

    def homeContent(self, filter):
        d = self._get_json(self.api + "/rank?section=latest&page=1")
        lst = [a for a in (self._album(x) for x in (d.get("items") or [])) if a]
        return {"class": self.classes, "list": lst}

    def homeVideoContent(self):
        return {"list": self.homeContent(False).get("list", [])}

    def categoryContent(self, tid, pg, filter, extend):
        pg = int(pg or 1)
        d = self._get_json("%s/category?type=%s&page=%d" % (self.api, tid, pg))
        lst = [a for a in (self._album(x) for x in (d.get("data") or [])) if a]
        return {"list": lst, "page": pg, "pagecount": int(d.get("pages") or pg),
                "limit": len(lst), "total": 999999}

    def detailContent(self, ids):
        vid = str(ids[0] if isinstance(ids, list) else ids)
        d = self._get_json("%s/chapters/%s" % (self.api, vid))
        chs = d.get("chapters") or []
        title = ""
        if chs:
            title = str(chs[0].get("title") or "").split(" 0")[0]
        play_url = "#".join("%s$%s@@%s" % (c.get("title") or ("第%s集" % c.get("index", 1)), vid, c.get("index", 1)) for c in chs[:200])
        vod = {"vod_id": vid, "vod_name": title or vid, "vod_pic": "",
               "vod_content": "", "vod_play_from": "听友听书",
               "vod_play_url": play_url or ("播放$%s@@1" % vid)}
        return {"list": [vod]}

    def searchContent(self, key, quick=False, pg="1"):
        pg = int(pg or 1)
        d = self._post_json(self.api + "/search", {"keyword": str(key), "page": pg})
        items = d.get("results") or d.get("items") or []
        lst = [a for a in (self._album(x) for x in items) if a]
        return {"list": lst, "page": pg}

    def playerContent(self, flag, id, vipFlags):
        raw = str(id).rsplit("$", 1)[-1]
        parts = raw.split("@@")
        vid = parts[0]
        idx = int(parts[1]) if len(parts) > 1 and str(parts[1]).isdigit() else 1
        d = self._post_json(self.api + "/play", {"album_id": str(vid), "chapter_idx": idx})
        url = d.get("play_url") or ""
        if url:
            return {"parse": 0, "url": url, "header": {"User-Agent": self.ua, "Referer": self.base + "/listening"}}
        return {"parse": 1, "url": self.base + "/listening", "header": {"User-Agent": self.ua}}

    def isVideoFormat(self, url):
        u = str(url or "").lower()
        return any(k in u for k in (".m3u8", ".mp4", ".mp3", ".m4a", "stream"))

    def destroy(self):
        pass
