import asyncio import logging import time from datetime import datetime, timedelta, timezone import httpx from sqlalchemy import select, update from sqlalchemy.ext.asyncio import AsyncSession from app.database import async_session from app.models.category import CategoryMapping from app.models.source_site import SourceSite from app.models.sync_log import SyncLog from app.models.vod import Vod from app.models.vod_source import VodSource logger = logging.getLogger("collector") SYNC_RANGES = { "all": None, "monthly": 720, "weekly": 168, "daily": 24, } class Collector: def __init__(self): self._running = False @property def is_running(self) -> bool: return self._running async def sync_source( self, source: SourceSite, range_type: str = "daily", db: AsyncSession | None = None, ) -> dict: hours = SYNC_RANGES.get(range_type, 24) result = { "source_id": source.id, "source_name": source.name, "status": "running", "total_fetched": 0, "new_vods": 0, "updated_vods": 0, "new_sources": 0, "updated_sources": 0, "skipped_no_mapping": 0, "error": None, } close_db = False if db is None: db = async_session() close_db = True try: mappings = await self._get_mappings(db, source.id) if not mappings: result["status"] = "skipped" result["error"] = "No category mappings configured" return result total_fetched = 0 new_vods = 0 updated_vods = 0 new_sources = 0 updated_sources = 0 skipped = 0 page = 1 while True: vods_data = await self._fetch_page(source, hours, page) if not vods_data: break total_fetched += len(vods_data) for vod_data in vods_data: source_type_id = vod_data.get("type_id") cat_mapping = mappings.get(source_type_id) if not cat_mapping: skipped += 1 continue unified_cat_id = cat_mapping["category_id"] n, u = await self._process_vod(db, vod_data, source, unified_cat_id) new_vods += n updated_vods += u ns, us = await self._process_play_urls(db, vod_data, source) new_sources += ns updated_sources += us page += 1 pagecount = vods_data[0].get("_pagecount", 1) if vods_data else 1 if page > pagecount or total_fetched >= 5000: break await asyncio.sleep(0.5) result["total_fetched"] = total_fetched result["new_vods"] = new_vods result["updated_vods"] = updated_vods result["new_sources"] = new_sources result["updated_sources"] = updated_sources result["skipped_no_mapping"] = skipped result["status"] = "success" await db.execute( update(SourceSite) .where(SourceSite.id == source.id) .values( last_sync_at=datetime.now(timezone.utc), last_sync_status="success", last_sync_count=new_vods, ) ) await db.commit() except Exception as e: logger.exception(f"Sync failed for {source.name}: {e}") result["status"] = "failed" result["error"] = str(e) try: await db.execute( update(SourceSite) .where(SourceSite.id == source.id) .values(last_sync_status="failed") ) await db.commit() except Exception: await db.rollback() finally: if close_db: await db.close() return result async def sync_all(self, range_type: str = "daily") -> list[dict]: if self._running: raise RuntimeError("Sync already running") self._running = True results = [] try: async with async_session() as db: result = await db.execute( select(SourceSite).where(SourceSite.is_active == True).order_by(SourceSite.sort_order) ) sources = result.scalars().all() for source in sources: log = SyncLog( source_id=source.id, range_type=range_type, status="running", started_at=datetime.now(timezone.utc), ) async with async_session() as db: db.add(log) await db.commit() log_id = log.id r = await self.sync_source(source, range_type) async with async_session() as db: await db.execute( update(SyncLog) .where(SyncLog.id == log_id) .values( status=r["status"], total_fetched=r["total_fetched"], new_count=r["new_vods"], update_count=r["updated_vods"], error_message=r["error"], finished_at=datetime.now(timezone.utc), ) ) await db.commit() results.append(r) await asyncio.sleep(1) finally: self._running = False return results async def _get_mappings(self, db: AsyncSession, source_id: int) -> dict: result = await db.execute( select(CategoryMapping).where(CategoryMapping.source_id == source_id) ) mappings = result.scalars().all() return {m.source_type_id: {"category_id": m.category_id, "name": m.source_type_name} for m in mappings} async def _fetch_page(self, source: SourceSite, hours: int | None, page: int) -> list[dict] | None: params = {"ac": "detail", "pg": str(page)} if hours: params["h"] = str(hours) url = source.base_url.rstrip("/") try: async with httpx.AsyncClient(timeout=30, follow_redirects=True) as client: resp = await client.get(url, params=params) data = resp.json() except Exception as e: logger.error(f"Fetch failed for {source.name} page {page}: {e}") return None vod_list = data.get("list", []) if not vod_list: return None pagecount = data.get("pagecount", 1) for v in vod_list: v["_pagecount"] = pagecount return vod_list async def _process_vod( self, db: AsyncSession, vod_data: dict, source: SourceSite, category_id: int ) -> tuple[int, int]: source_vod_id = vod_data.get("vod_id") name = vod_data.get("vod_name", "") if not name: return 0, 0 douban_id = vod_data.get("vod_douban_id") if douban_id and str(douban_id).isdigit(): douban_id = int(douban_id) else: douban_id = None year = vod_data.get("vod_year") vod = None if douban_id: result = await db.execute(select(Vod).where(Vod.douban_id == douban_id).limit(1)) vod = result.scalar_one_or_none() if not vod and year: result = await db.execute( select(Vod).where(Vod.name == name, Vod.year == year).limit(1) ) vod = result.scalar_one_or_none() # 兜底按名称匹配:仅在来源数据没有 year 时才用, # 避免同名不同年份(如"流浪地球"2019 vs 2023)被误判为同一部 if not vod and not year: result = await db.execute(select(Vod).where(Vod.name == name).limit(1)) vod = result.scalar_one_or_none() if vod: cover = vod_data.get("vod_pic") or vod.cover score_raw = vod_data.get("vod_score", "0.0") score = float(score_raw) if score_raw and float(score_raw) > 0 else vod.score if douban_id: vod.douban_id = douban_id vod.cover = cover vod.score = score vod.blurb = vod_data.get("vod_blurb") or vod.blurb vod.content = vod_data.get("vod_content") or vod.content vod.remarks = vod_data.get("vod_remarks") or vod.remarks vod.actor = vod_data.get("vod_actor") or vod.actor vod.director = vod_data.get("vod_director") or vod.director vod.area = vod_data.get("vod_area") or vod.area vod.lang = vod_data.get("vod_lang") or vod.lang vod.year = year or vod.year vod.sub_name = vod_data.get("vod_sub") or vod_data.get("vod_en") or vod.sub_name vod.updated_at = datetime.now(timezone.utc) return 0, 1 else: score_raw = vod_data.get("vod_score", "0.0") score = float(score_raw) if score_raw and float(score_raw) > 0 else None vod = Vod( name=name, sub_name=vod_data.get("vod_sub") or vod_data.get("vod_en"), en_name=vod_data.get("vod_en"), category_id=category_id, cover=vod_data.get("vod_pic"), actor=vod_data.get("vod_actor"), director=vod_data.get("vod_director"), area=vod_data.get("vod_area"), lang=vod_data.get("vod_lang"), year=year, duration=vod_data.get("vod_duration"), score=score, douban_id=douban_id, blurb=vod_data.get("vod_blurb"), content=vod_data.get("vod_content"), remarks=vod_data.get("vod_remarks"), ) db.add(vod) await db.flush() return 1, 0 async def _process_play_urls( self, db: AsyncSession, vod_data: dict, source: SourceSite ) -> tuple[int, int]: name = vod_data.get("vod_name", "") if not name: return 0, 0 douban_id = vod_data.get("vod_douban_id") if douban_id and str(douban_id).isdigit(): douban_id = int(douban_id) else: douban_id = None year = vod_data.get("vod_year") vod = None if douban_id: result = await db.execute(select(Vod).where(Vod.douban_id == douban_id).limit(1)) vod = result.scalar_one_or_none() if not vod and year: result = await db.execute( select(Vod).where(Vod.name == name, Vod.year == year).limit(1) ) vod = result.scalar_one_or_none() if not vod and not year: result = await db.execute(select(Vod).where(Vod.name == name).limit(1)) vod = result.scalar_one_or_none() if not vod: return 0, 0 play_from_raw = vod_data.get("vod_play_from", "") play_url_raw = vod_data.get("vod_play_url", "") from_list = [f.strip() for f in play_from_raw.split("$$$") if f.strip()] url_list = [u.strip() for u in play_url_raw.split("$$$") if u.strip()] new_count = 0 update_count = 0 for i, play_from in enumerate(from_list): play_url = url_list[i] if i < len(url_list) else "" source_vod_id = vod_data.get("vod_id") existing = await db.execute( select(VodSource).where( VodSource.vod_id == vod.id, VodSource.source_id == source.id, VodSource.play_from == play_from, ) ) existing_vs = existing.scalar_one_or_none() if existing_vs: existing_vs.play_url = play_url existing_vs.source_vod_id = source_vod_id update_count += 1 else: vs = VodSource( vod_id=vod.id, source_id=source.id, source_vod_id=source_vod_id, play_from=play_from, play_url=play_url, ) db.add(vs) await db.flush() new_count += 1 return new_count, update_count collector = Collector()