feat: DramaBox 全量走 App 接口,清单可停止并避免卡死
分类按 App 翻页,精选走推荐接口。清单顶部显示进度,停止后不再拉新剧,已拿到的封面继续加载。列表只绘制可见卡片,避免大量剧目占满主线程。
This commit is contained in:
@@ -1,13 +1,17 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from server.services.dramabox import api
|
||||
from server.services.dramabox.client import client
|
||||
from server.services.dramabox.covers import covers
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
DEFAULT_MAX_PAGES = 300
|
||||
MAX_MAX_PAGES = 999
|
||||
|
||||
|
||||
def enabled_cache() -> bool:
|
||||
@@ -16,7 +20,49 @@ def enabled_cache() -> bool:
|
||||
|
||||
|
||||
def cache_path() -> Path:
|
||||
return ROOT / "cache" / "dramabox" / f"catalog-browse-{client.language}.json"
|
||||
return ROOT / "cache" / "dramabox" / f"catalog-app-channels-{client.language}.json"
|
||||
|
||||
|
||||
def settings_path() -> Path:
|
||||
return ROOT / "cache" / "dramabox" / "catalog-settings.json"
|
||||
|
||||
|
||||
def page_limit() -> int:
|
||||
path = settings_path()
|
||||
if path.is_file():
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
data = None
|
||||
if isinstance(data, dict) and "max_pages" in data:
|
||||
return clamp_page_limit(data.get("max_pages"))
|
||||
return DEFAULT_MAX_PAGES
|
||||
|
||||
|
||||
def set_page_limit(value) -> int:
|
||||
pages = clamp_page_limit(value)
|
||||
path = settings_path()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(".json.tmp")
|
||||
temporary.write_text(json.dumps({"max_pages": pages}, ensure_ascii=False), encoding="utf-8")
|
||||
temporary.replace(path)
|
||||
_drop_catalog_cache()
|
||||
return pages
|
||||
|
||||
|
||||
def clamp_page_limit(value) -> int:
|
||||
number = _int(value)
|
||||
if number < 1:
|
||||
return DEFAULT_MAX_PAGES
|
||||
return min(number, MAX_MAX_PAGES)
|
||||
|
||||
|
||||
def _drop_catalog_cache() -> None:
|
||||
folder = ROOT / "cache" / "dramabox"
|
||||
if not folder.is_dir():
|
||||
return
|
||||
for path in folder.glob("catalog-app-channels-*.json"):
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
async def stream(refresh: bool = False):
|
||||
@@ -41,44 +87,56 @@ async def stream(refresh: bool = False):
|
||||
_write_cache(path, collected)
|
||||
|
||||
|
||||
PAGE_SIZE = 60
|
||||
|
||||
|
||||
async def _fetch():
|
||||
language = client.language
|
||||
first = await asyncio.to_thread(api.browse, 1, 0, language, PAGE_SIZE)
|
||||
all_name = await asyncio.to_thread(api.all_label, language)
|
||||
types = [item for item in (first.get("types") or []) if isinstance(item, dict)]
|
||||
jobs: list[tuple[str, str, int]] = [("browse-0", all_name, 0)]
|
||||
sections = [{"key": "browse-0", "name": all_name, "note": "", "loading": True}]
|
||||
for item in types:
|
||||
type_id = _int(item.get("id"))
|
||||
name = str(item.get("name") or "").strip()
|
||||
if type_id <= 0 or not name or name.lower() == "all":
|
||||
continue
|
||||
key = f"browse-{type_id}"
|
||||
sections.append({"key": key, "name": name, "note": "", "loading": True})
|
||||
jobs.append((key, name, type_id))
|
||||
if not sections:
|
||||
raise RuntimeError("没有获取到分类")
|
||||
session = _rec_session()
|
||||
home = await asyncio.to_thread(_home, session)
|
||||
channels = [item for item in (home.get("channelList") or []) if isinstance(item, dict) and str(item.get("channelName") or "").strip()]
|
||||
sections = []
|
||||
jobs: list[tuple] = []
|
||||
if channels:
|
||||
for index, channel in enumerate(channels):
|
||||
key = f"channel-{channel.get('channelId')}"
|
||||
name = str(channel.get("channelName") or "").strip()
|
||||
sections.append({"key": key, "name": name, "note": "", "loading": True})
|
||||
jobs.append((key, name, channel, index, home if index == 0 else None))
|
||||
else:
|
||||
books = _dramas_from_feed(home)
|
||||
if not books:
|
||||
raise RuntimeError("没有获取到剧目")
|
||||
sections.append({"key": "home", "name": "推荐", "note": "", "loading": True})
|
||||
jobs.append(("home", "推荐", None, 0, home))
|
||||
yield {"type": "outline", "sections": sections}
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
queue: asyncio.Queue = asyncio.Queue()
|
||||
limit = asyncio.Semaphore(6)
|
||||
stop = threading.Event()
|
||||
|
||||
async def run(job):
|
||||
key, name, type_id = job
|
||||
key, name = job[0], job[1]
|
||||
|
||||
def work():
|
||||
try:
|
||||
items = _browse_items(type_id)
|
||||
loop.call_soon_threadsafe(queue.put_nowait, _page(key, name, items, done=True))
|
||||
page_no = 0
|
||||
page_cap = page_limit()
|
||||
for items in _iter_channel_pages(job[2], job[3], job[4], session, stop):
|
||||
if stop.is_set():
|
||||
break
|
||||
if not items:
|
||||
continue
|
||||
page_no += 1
|
||||
loop.call_soon_threadsafe(
|
||||
queue.put_nowait,
|
||||
_page(key, name, items, done=False, page=page_no, pages=page_cap),
|
||||
)
|
||||
if not stop.is_set():
|
||||
loop.call_soon_threadsafe(queue.put_nowait, _page(key, name, [], done=True))
|
||||
except Exception as exc:
|
||||
loop.call_soon_threadsafe(
|
||||
queue.put_nowait,
|
||||
_page(key, name, [], str(exc) or "获取清单失败", done=True, failed=True),
|
||||
)
|
||||
if not stop.is_set():
|
||||
loop.call_soon_threadsafe(
|
||||
queue.put_nowait,
|
||||
_page(key, name, [], str(exc) or "获取清单失败", done=True, failed=True),
|
||||
)
|
||||
finally:
|
||||
loop.call_soon_threadsafe(queue.put_nowait, None)
|
||||
|
||||
@@ -96,6 +154,7 @@ async def _fetch():
|
||||
yield event
|
||||
yield {"type": "done"}
|
||||
finally:
|
||||
stop.set()
|
||||
for task in tasks:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
@@ -103,63 +162,326 @@ async def _fetch():
|
||||
|
||||
|
||||
def search(keyword: str) -> list[dict]:
|
||||
text = (keyword or "").strip()
|
||||
text = (keyword or "").strip()[:80]
|
||||
if not text:
|
||||
return []
|
||||
items = []
|
||||
_require_app()
|
||||
session = _rec_session()
|
||||
found = []
|
||||
seen: set[str] = set()
|
||||
page = 1
|
||||
page_size = 60
|
||||
previous: tuple[str, ...] | None = None
|
||||
while True:
|
||||
payload = api.search_books(text, page=page, page_size=page_size)
|
||||
rows = payload.get("records") if isinstance(payload, dict) else None
|
||||
if not isinstance(rows, list) or not rows:
|
||||
for page in range(1, 41):
|
||||
try:
|
||||
payload = _post("drama-box/search/search", _bind({
|
||||
"from": "search_sug",
|
||||
"keyword": text,
|
||||
"searchSource": "搜索按钮",
|
||||
"sortType": 1,
|
||||
"synSwitch": 0,
|
||||
"pageNo": page,
|
||||
"pageSize": 20,
|
||||
}, session))
|
||||
except RuntimeError:
|
||||
break
|
||||
signature = tuple(str(item.get("bookId") or "") for item in rows if isinstance(item, dict))
|
||||
if signature == previous:
|
||||
rows = payload.get("searchList") if isinstance(payload, dict) else None
|
||||
fresh = [item for item in _dramas(rows) if item["id"] not in seen]
|
||||
if not fresh:
|
||||
break
|
||||
previous = signature
|
||||
for item in rows:
|
||||
drama = _drama(item)
|
||||
if not drama or drama["id"] in seen:
|
||||
continue
|
||||
seen.add(drama["id"])
|
||||
items.append(drama)
|
||||
total = _int(payload.get("total")) if isinstance(payload, dict) else 0
|
||||
if len(rows) < page_size or (total and page * page_size >= total):
|
||||
seen.update(item["id"] for item in fresh)
|
||||
found.extend(fresh)
|
||||
if not _more(payload):
|
||||
break
|
||||
page += 1
|
||||
return items
|
||||
if found:
|
||||
return found
|
||||
payload = _post("drama-box/search/suggest", {"keyword": text})
|
||||
rows = payload.get("suggestList") if isinstance(payload, dict) else None
|
||||
return _dramas(rows)
|
||||
|
||||
|
||||
def _browse_items(type_id: int) -> list[dict]:
|
||||
items = []
|
||||
def _require_app() -> None:
|
||||
if not client.can_browse():
|
||||
raise RuntimeError("请先进入 DramaBox")
|
||||
|
||||
|
||||
def _post(path: str, payload: dict) -> dict:
|
||||
from server.services.dramabox.app_api import browse_app, _post as post
|
||||
|
||||
_require_app()
|
||||
return post(path, payload, browse_app())
|
||||
|
||||
|
||||
def _home(session: str = "") -> dict:
|
||||
return _post("drama-box/he001/theater", _bind({"type": 0, "isNeedNewChannel": 1, "isNeedRank": 1}, session))
|
||||
|
||||
|
||||
def _rec_session() -> str:
|
||||
from server.services.dramabox.app_api import browse_app
|
||||
|
||||
app = browse_app() or {}
|
||||
raw = f"{app.get('android_id') or ''}_{int(time.time() * 1000)}_{app.get('user_id') or ''}"
|
||||
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _bind(payload: dict, session: str) -> dict:
|
||||
if not session:
|
||||
return payload
|
||||
body = dict(payload)
|
||||
body["recSessionId"] = session
|
||||
return body
|
||||
|
||||
|
||||
def _halted(stop: threading.Event | None) -> bool:
|
||||
return bool(stop and stop.is_set())
|
||||
|
||||
|
||||
def _iter_channel_pages(channel: dict | None, index: int, home: dict | None, session: str = "", stop: threading.Event | None = None):
|
||||
seen: set[str] = set()
|
||||
page = 1
|
||||
total_pages = 1
|
||||
previous: tuple[str, ...] | None = None
|
||||
while page <= total_pages:
|
||||
data = api.browse(page, type_id, page_size=PAGE_SIZE)
|
||||
rows = data.get("bookList") if isinstance(data, dict) else None
|
||||
reported = _int(data.get("pages")) if isinstance(data, dict) else 0
|
||||
if reported > 0:
|
||||
total_pages = reported
|
||||
if not isinstance(rows, list) or not rows:
|
||||
break
|
||||
signature = tuple(str(item.get("bookId") or "") for item in rows if isinstance(item, dict))
|
||||
if signature == previous:
|
||||
break
|
||||
previous = signature
|
||||
for item in rows:
|
||||
drama = _drama(item)
|
||||
if not drama or drama["id"] in seen:
|
||||
|
||||
def fresh(rows: list[dict]) -> list[dict]:
|
||||
page = []
|
||||
for drama in rows:
|
||||
if drama["id"] in seen:
|
||||
continue
|
||||
seen.add(drama["id"])
|
||||
items.append(drama)
|
||||
if len(rows) < PAGE_SIZE or page >= total_pages:
|
||||
break
|
||||
page += 1
|
||||
page.append(drama)
|
||||
return page
|
||||
|
||||
if not isinstance(channel, dict):
|
||||
if isinstance(home, dict):
|
||||
first = fresh(_dramas_from_feed(home))
|
||||
if first:
|
||||
yield first
|
||||
return
|
||||
channel_type = _int(channel.get("channelType"))
|
||||
channel_id = _int(channel.get("channelId"))
|
||||
if channel_type == 2:
|
||||
yield from _new_theater_pages(channel_id, index, fresh, session, stop)
|
||||
return
|
||||
if channel_type == 3:
|
||||
yield from _rank_pages(fresh, session, stop)
|
||||
return
|
||||
if channel_type == 4:
|
||||
yield from _classify_pages(fresh, session, stop)
|
||||
return
|
||||
if channel_type in (5, 6, 7, 8):
|
||||
yield from _grid_pages(channel_id, index, fresh, session, stop)
|
||||
return
|
||||
first_payload = home if index == 0 and isinstance(home, dict) else None
|
||||
yield from _explore_pages(channel_id, index, channel_type, first_payload, fresh, session, stop)
|
||||
|
||||
|
||||
def _new_theater_pages(channel_id: int, index: int, fresh, session: str, stop: threading.Event | None = None):
|
||||
style = 1
|
||||
page_no = 1
|
||||
limit = page_limit()
|
||||
while page_no <= limit:
|
||||
if _halted(stop):
|
||||
return
|
||||
try:
|
||||
data = _post("drama-box/he001/theater", _bind({
|
||||
"channelId": channel_id,
|
||||
"index": index,
|
||||
"pageNo": page_no,
|
||||
"isNeedRank": 1,
|
||||
"newChannelStyle": style,
|
||||
}, session))
|
||||
except RuntimeError:
|
||||
return
|
||||
records = _records(data, "newTheaterList")
|
||||
if not records and page_no == 1 and style == 1:
|
||||
style = 0
|
||||
continue
|
||||
page = fresh(_dramas(records))
|
||||
if page:
|
||||
yield page
|
||||
if not records:
|
||||
return
|
||||
page_no += 1
|
||||
|
||||
|
||||
def _rank_pages(fresh, session: str, stop: threading.Event | None = None):
|
||||
if _halted(stop):
|
||||
return
|
||||
try:
|
||||
data = _post("drama-box/he001/rank", _bind({}, session))
|
||||
except RuntimeError:
|
||||
return
|
||||
page = fresh(_dramas(data.get("rankList") if isinstance(data, dict) else None))
|
||||
if page:
|
||||
yield page
|
||||
asked: set[int] = set()
|
||||
for item in (data.get("rankTypeVoList") if isinstance(data, dict) else None) or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
rank_type = _int(item.get("rankType"))
|
||||
if rank_type in asked:
|
||||
continue
|
||||
if _halted(stop):
|
||||
return
|
||||
asked.add(rank_type)
|
||||
try:
|
||||
ranked = _post("drama-box/he001/rank", _bind({"rankType": rank_type}, session))
|
||||
except RuntimeError:
|
||||
return
|
||||
page = fresh(_dramas(ranked.get("rankList") if isinstance(ranked, dict) else None))
|
||||
if page:
|
||||
yield page
|
||||
|
||||
|
||||
def _classify_pages(fresh, session: str, stop: threading.Event | None = None):
|
||||
filters: list[dict] = []
|
||||
show_labels = True
|
||||
for page_no in range(1, page_limit() + 1):
|
||||
if _halted(stop):
|
||||
return
|
||||
try:
|
||||
data = _post("drama-box/he001/classify", _bind({
|
||||
"typeList": filters,
|
||||
"showLabels": show_labels,
|
||||
"pageNo": page_no,
|
||||
"pageSize": 15,
|
||||
}, session))
|
||||
except RuntimeError:
|
||||
return
|
||||
if show_labels:
|
||||
filters = _classify_filters(data)
|
||||
show_labels = False
|
||||
block = data.get("classifyBookList") if isinstance(data, dict) else None
|
||||
records = block.get("records") if isinstance(block, dict) else None
|
||||
page = fresh(_dramas(records))
|
||||
if page:
|
||||
yield page
|
||||
if not isinstance(records, list) or not records:
|
||||
return
|
||||
if isinstance(block, dict) and "isMore" in block and not _more(block):
|
||||
return
|
||||
|
||||
|
||||
def _grid_pages(channel_id: int, index: int, fresh, session: str, stop: threading.Event | None = None):
|
||||
for page_no in range(1, page_limit() + 1):
|
||||
if _halted(stop):
|
||||
return
|
||||
try:
|
||||
data = _post("drama-box/he001/theater", _bind({
|
||||
"channelId": channel_id,
|
||||
"index": index,
|
||||
"pageNo": page_no,
|
||||
"pageSize": 10,
|
||||
}, session))
|
||||
except RuntimeError:
|
||||
return
|
||||
records = _records(data, "recommendList")
|
||||
rows = _dramas_from_feed(data) if page_no == 1 else _dramas(records)
|
||||
page = fresh(rows)
|
||||
if page:
|
||||
yield page
|
||||
if not records:
|
||||
return
|
||||
|
||||
|
||||
def _explore_pages(channel_id: int, index: int, channel_type: int, home: dict | None, fresh, session: str, stop: threading.Event | None = None):
|
||||
if isinstance(home, dict):
|
||||
data = home
|
||||
else:
|
||||
if _halted(stop):
|
||||
return
|
||||
try:
|
||||
data = _post("drama-box/he001/theater", _bind({
|
||||
"channelId": channel_id,
|
||||
"index": index,
|
||||
"type": channel_type,
|
||||
"isNeedRank": 1,
|
||||
}, session))
|
||||
except RuntimeError:
|
||||
return
|
||||
page = fresh(_dramas_from_feed(data))
|
||||
if page:
|
||||
yield page
|
||||
special = _int(data.get("specialColumnId") if isinstance(data, dict) else 0)
|
||||
for page_no in range(2, page_limit() + 1):
|
||||
if _halted(stop):
|
||||
return
|
||||
try:
|
||||
data = _post("drama-box/he001/recommendBook", _bind({
|
||||
"pageNo": page_no,
|
||||
"specialColumnId": special,
|
||||
"isNeedRank": 1,
|
||||
}, session))
|
||||
except RuntimeError:
|
||||
return
|
||||
records = _records(data, "recommendList")
|
||||
page = fresh(_dramas(records))
|
||||
if page:
|
||||
yield page
|
||||
if not records:
|
||||
return
|
||||
|
||||
|
||||
def _classify_filters(data: dict) -> list[dict]:
|
||||
filters = []
|
||||
if not isinstance(data, dict):
|
||||
return filters
|
||||
for item in data.get("classifyList") or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
tags = item.get("showList") or []
|
||||
if not tags or not isinstance(tags[0], dict):
|
||||
continue
|
||||
filters.append({"type": _int(item.get("type")), "value": tags[0].get("value")})
|
||||
return filters
|
||||
|
||||
|
||||
def _records(data: dict, key: str) -> list:
|
||||
block = data.get(key) if isinstance(data, dict) else None
|
||||
records = block.get("records") if isinstance(block, dict) else None
|
||||
return records if isinstance(records, list) else []
|
||||
|
||||
|
||||
def _more(block) -> bool:
|
||||
if not isinstance(block, dict) or "isMore" not in block:
|
||||
return False
|
||||
return _int(block.get("isMore")) != 0
|
||||
|
||||
|
||||
def _dramas_from_feed(data: dict) -> list[dict]:
|
||||
found = []
|
||||
if not isinstance(data, dict):
|
||||
return found
|
||||
for column in data.get("columnVoList") or []:
|
||||
if isinstance(column, dict):
|
||||
found.extend(_dramas(column.get("bookList")))
|
||||
for key in ("recommendList", "newTheaterList"):
|
||||
block = data.get(key)
|
||||
records = block.get("records") if isinstance(block, dict) else None
|
||||
found.extend(_dramas(records))
|
||||
if isinstance(records, list):
|
||||
for record in records:
|
||||
if not isinstance(record, dict):
|
||||
continue
|
||||
card = record.get("tagCardVo")
|
||||
if isinstance(card, dict):
|
||||
found.extend(_dramas(card.get("tagBooks")))
|
||||
found.extend(_dramas(data.get("bannerList")))
|
||||
seen: set[str] = set()
|
||||
unique = []
|
||||
for item in found:
|
||||
if item["id"] in seen:
|
||||
continue
|
||||
seen.add(item["id"])
|
||||
unique.append(item)
|
||||
return unique
|
||||
|
||||
|
||||
def _dramas(rows) -> list[dict]:
|
||||
items = []
|
||||
seen: set[str] = set()
|
||||
if not isinstance(rows, list):
|
||||
return items
|
||||
for item in rows:
|
||||
drama = _drama(item)
|
||||
if not drama or drama["id"] in seen:
|
||||
continue
|
||||
seen.add(drama["id"])
|
||||
items.append(drama)
|
||||
return items
|
||||
|
||||
|
||||
@@ -170,7 +492,7 @@ def _drama(item: dict) -> dict | None:
|
||||
title = str(item.get("bookName") or item.get("name") or "").strip()
|
||||
if not drama_id or not title:
|
||||
return None
|
||||
image = str(item.get("cover") or item.get("_originalCover") or "").strip()
|
||||
image = str(item.get("coverWap") or item.get("cover") or item.get("_originalCover") or "").strip()
|
||||
count = item.get("chapterCount")
|
||||
tags = item.get("typeTwoNames") if isinstance(item.get("typeTwoNames"), list) else []
|
||||
corner = str(item.get("typeTwoName") or (tags[0] if tags else "")).strip()
|
||||
@@ -188,8 +510,20 @@ def _drama(item: dict) -> dict | None:
|
||||
}
|
||||
|
||||
|
||||
def _page(key: str, name: str, items: list[dict], note: str = "", done: bool = False, failed: bool = False) -> dict:
|
||||
def _page(
|
||||
key: str,
|
||||
name: str,
|
||||
items: list[dict],
|
||||
note: str = "",
|
||||
done: bool = False,
|
||||
failed: bool = False,
|
||||
page: int = 0,
|
||||
pages: int = 0,
|
||||
) -> dict:
|
||||
event = {"type": "page", "key": key, "name": name, "note": note, "items": items, "done": done}
|
||||
if page:
|
||||
event["page"] = page
|
||||
event["pages"] = pages
|
||||
if failed:
|
||||
event["failed"] = True
|
||||
return event
|
||||
|
||||
Reference in New Issue
Block a user