File size: 12,885 Bytes
9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 | 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() |