223 lines
7.2 KiB
Python
223 lines
7.2 KiB
Python
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-browse-{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)
|
|
|
|
|
|
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("没有获取到分类")
|
|
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, type_id = job
|
|
|
|
def work():
|
|
try:
|
|
items = _browse_items(type_id)
|
|
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()
|
|
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:
|
|
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:
|
|
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):
|
|
break
|
|
page += 1
|
|
return items
|
|
|
|
|
|
def _browse_items(type_id: int) -> list[dict]:
|
|
items = []
|
|
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:
|
|
continue
|
|
seen.add(drama["id"])
|
|
items.append(drama)
|
|
if len(rows) < PAGE_SIZE or page >= total_pages:
|
|
break
|
|
page += 1
|
|
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
|