feat: 接入 DramaBox 并按语言地区切换清单
This commit is contained in:
@@ -0,0 +1,248 @@
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
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]
|
||||
|
||||
|
||||
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-{client.language}.json"
|
||||
|
||||
|
||||
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():
|
||||
home = await asyncio.to_thread(api.home_index)
|
||||
first = await asyncio.to_thread(api.browse, 1, 0)
|
||||
types = [item for item in (first.get("types") or []) if isinstance(item, dict)]
|
||||
jobs: list[tuple[str, str, str, object]] = []
|
||||
sections = []
|
||||
for column in home:
|
||||
if not isinstance(column, dict):
|
||||
continue
|
||||
name = str(column.get("name") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
key = f"home-{column.get('id') or name}"
|
||||
sections.append({"key": key, "name": name, "note": "", "loading": True})
|
||||
jobs.append((key, name, "home", column))
|
||||
sections.append({"key": "browse-0", "name": "全部", "note": "", "loading": True})
|
||||
jobs.append(("browse-0", "全部", "browse", {"id": 0, "seed": first}))
|
||||
for item in types:
|
||||
type_id = _int(item.get("id"))
|
||||
name = str(item.get("name") or "").strip()
|
||||
if type_id <= 0 or not name:
|
||||
continue
|
||||
key = f"browse-{type_id}"
|
||||
sections.append({"key": key, "name": name, "note": "", "loading": True})
|
||||
jobs.append((key, name, "browse", {"id": type_id}))
|
||||
if not sections:
|
||||
raise RuntimeError("没有获取到分类")
|
||||
yield {"type": "outline", "sections": sections}
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
queue: asyncio.Queue = asyncio.Queue()
|
||||
limit = asyncio.Semaphore(6)
|
||||
|
||||
async def run(job):
|
||||
key, name, kind, payload = job
|
||||
|
||||
def work():
|
||||
try:
|
||||
if kind == "home":
|
||||
items = _home_items(payload)
|
||||
else:
|
||||
items = _browse_items(payload)
|
||||
loop.call_soon_threadsafe(queue.put_nowait, _page(key, name, items, done=True))
|
||||
except Exception as exc:
|
||||
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:
|
||||
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()
|
||||
if not text:
|
||||
return []
|
||||
items = []
|
||||
seen: set[str] = set()
|
||||
for page in range(1, 4):
|
||||
payload = api.search_books(text, page=page, page_size=20)
|
||||
rows = payload.get("records") if isinstance(payload, dict) else None
|
||||
if not isinstance(rows, list) or not rows:
|
||||
break
|
||||
for item in rows:
|
||||
drama = _drama(item)
|
||||
if not drama or drama["id"] in seen:
|
||||
continue
|
||||
seen.add(drama["id"])
|
||||
items.append(drama)
|
||||
if len(rows) < 20:
|
||||
break
|
||||
return items
|
||||
|
||||
|
||||
def _home_items(column: dict) -> list[dict]:
|
||||
items = []
|
||||
seen: set[str] = set()
|
||||
for item in column.get("items") or []:
|
||||
drama = _drama(item)
|
||||
if not drama or drama["id"] in seen:
|
||||
continue
|
||||
seen.add(drama["id"])
|
||||
items.append(drama)
|
||||
name = str(column.get("name") or "").strip()
|
||||
if name:
|
||||
for page in range(1, 3):
|
||||
payload = api.home_more(name, page=page, page_size=18)
|
||||
block = payload.get("data") if isinstance(payload, dict) else None
|
||||
rows = block.get("items") if isinstance(block, dict) else None
|
||||
if not isinstance(rows, list) or not rows:
|
||||
break
|
||||
for item in rows:
|
||||
drama = _drama(item)
|
||||
if not drama or drama["id"] in seen:
|
||||
continue
|
||||
seen.add(drama["id"])
|
||||
items.append(drama)
|
||||
pages = _int(payload.get("pages")) if isinstance(payload, dict) else 0
|
||||
if page >= pages:
|
||||
break
|
||||
return items
|
||||
|
||||
|
||||
def _browse_items(payload: dict) -> list[dict]:
|
||||
type_id = _int(payload.get("id"))
|
||||
items = []
|
||||
seen: set[str] = set()
|
||||
seed = payload.get("seed") if isinstance(payload.get("seed"), dict) else None
|
||||
pages = 3 if type_id == 0 else 1
|
||||
for page in range(1, pages + 1):
|
||||
if page == 1 and seed is not None:
|
||||
data = seed
|
||||
else:
|
||||
data = api.browse(page, type_id)
|
||||
rows = data.get("bookList") if isinstance(data, dict) else None
|
||||
if not isinstance(rows, list) or not rows:
|
||||
break
|
||||
for item in rows:
|
||||
drama = _drama(item)
|
||||
if not drama or drama["id"] in seen:
|
||||
continue
|
||||
seen.add(drama["id"])
|
||||
items.append(drama)
|
||||
total_pages = _int(data.get("pages")) if isinstance(data, dict) else 0
|
||||
if page >= total_pages:
|
||||
break
|
||||
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("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) -> dict:
|
||||
event = {"type": "page", "key": key, "name": name, "note": note, "items": items, "done": done}
|
||||
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
|
||||
Reference in New Issue
Block a user