557 lines
17 KiB
Python
557 lines
17 KiB
Python
import asyncio
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import threading
|
|
import time
|
|
from pathlib import Path
|
|
|
|
from server.services.dramabox.client import client
|
|
from server.services.dramabox.covers import covers
|
|
|
|
ROOT = Path(__file__).resolve().parents[3]
|
|
DEFAULT_MAX_PAGES = 99
|
|
MAX_MAX_PAGES = 999
|
|
|
|
|
|
def enabled_cache() -> bool:
|
|
flag = os.environ.get("RAPTD_CATALOG_CACHE", "1").strip().lower()
|
|
return flag not in ("0", "false", "no")
|
|
|
|
|
|
def cache_path() -> Path:
|
|
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):
|
|
path = cache_path()
|
|
if enabled_cache():
|
|
if refresh:
|
|
path.unlink(missing_ok=True)
|
|
else:
|
|
cached = _read_cache(path)
|
|
if cached:
|
|
for event in cached:
|
|
yield event
|
|
return
|
|
collected: list[dict] = []
|
|
failed = False
|
|
async for event in _fetch():
|
|
if event.get("failed"):
|
|
failed = True
|
|
collected.append(event)
|
|
yield event
|
|
if enabled_cache() and not failed and collected and collected[-1].get("type") == "done":
|
|
_write_cache(path, collected)
|
|
|
|
|
|
async def _fetch():
|
|
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 = job[0], job[1]
|
|
|
|
def work():
|
|
try:
|
|
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:
|
|
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)
|
|
|
|
async with limit:
|
|
await asyncio.to_thread(work)
|
|
|
|
tasks = [asyncio.create_task(run(job)) for job in jobs]
|
|
finished = 0
|
|
try:
|
|
while finished < len(tasks):
|
|
event = await queue.get()
|
|
if event is None:
|
|
finished += 1
|
|
continue
|
|
yield event
|
|
yield {"type": "done"}
|
|
finally:
|
|
stop.set()
|
|
for task in tasks:
|
|
if not task.done():
|
|
task.cancel()
|
|
await asyncio.gather(*tasks, return_exceptions=True)
|
|
|
|
|
|
def search(keyword: str) -> list[dict]:
|
|
text = (keyword or "").strip()[:80]
|
|
if not text:
|
|
return []
|
|
_require_app()
|
|
session = _rec_session()
|
|
found = []
|
|
seen: set[str] = set()
|
|
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
|
|
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
|
|
seen.update(item["id"] for item in fresh)
|
|
found.extend(fresh)
|
|
if not _more(payload):
|
|
break
|
|
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 _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()
|
|
|
|
def fresh(rows: list[dict]) -> list[dict]:
|
|
page = []
|
|
for drama in rows:
|
|
if drama["id"] in seen:
|
|
continue
|
|
seen.add(drama["id"])
|
|
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
|
|
|
|
|
|
def _drama(item: dict) -> dict | None:
|
|
if not isinstance(item, dict):
|
|
return None
|
|
drama_id = str(item.get("bookId") or item.get("action") or "").strip()
|
|
title = str(item.get("bookName") or item.get("name") or "").strip()
|
|
if not drama_id or not title:
|
|
return None
|
|
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()
|
|
free = item.get("free")
|
|
return {
|
|
"id": drama_id,
|
|
"title": title,
|
|
"image": covers.local_url(image) if image else "",
|
|
"payType": "" if free in (1, "1", True, None) else str(free or ""),
|
|
"episodeCount": str(count or ""),
|
|
"corner": corner,
|
|
"limitedFree": False,
|
|
"locked": False,
|
|
"kind": corner,
|
|
}
|
|
|
|
|
|
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
|
|
|
|
|
|
def _read_cache(path: Path) -> list[dict] | None:
|
|
if not path.is_file():
|
|
return None
|
|
try:
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
except (OSError, json.JSONDecodeError):
|
|
return None
|
|
events = data.get("events") if isinstance(data, dict) else None
|
|
if not isinstance(events, list) or not events:
|
|
return None
|
|
return events
|
|
|
|
|
|
def _write_cache(path: Path, events: list[dict]) -> None:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
temporary = path.with_suffix(".json.tmp")
|
|
temporary.write_text(json.dumps({"events": events}, ensure_ascii=False), encoding="utf-8")
|
|
temporary.replace(path)
|
|
|
|
|
|
def _int(value) -> int:
|
|
try:
|
|
return int(float(str(value)))
|
|
except (TypeError, ValueError):
|
|
return 0
|