api / app /routers /user /vod.py
hanbinsite's picture
feat: view_count Redis incr, history upsert, pytest config
cea9127
Raw History Blame Contribute Delete
11.6 kB
from fastapi import APIRouter, Depends, Query
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.cache import (
cache_get, cache_set,
vod_list_key, vod_search_key, vod_latest_key, vod_recommended_key, vod_detail_key,
)
from app.config import settings
from app.database import get_db
from app.models.category import Category
from app.models.source_site import SourceSite
from app.models.vod import Vod
from app.models.vod_source import VodSource
from app.schemas.common import ApiResponse, PaginatedData
from app.schemas.user.vod import VodUserItem, VodUserDetail, VodPlaySource, EpisodeItem
from app.services.vod import batch_get_category_names, batch_get_source_counts, increment_view_count
router = APIRouter()
async def _batch_get_category_names(db: AsyncSession, category_ids: list[int]) -> dict[int, str]:
return await batch_get_category_names(db, category_ids)
async def _batch_get_source_counts(db: AsyncSession, vod_ids: list[int]) -> dict[int, int]:
return await batch_get_source_counts(db, vod_ids)
def _build_vod_items(vods, cat_map, source_count_map) -> list[dict]:
items = []
for v in vods:
items.append(
VodUserItem(
id=v.id,
name=v.name,
cover=v.cover,
category_id=v.category_id,
category_name=cat_map.get(v.category_id),
score=v.score,
year=v.year,
area=v.area,
is_end=v.is_end,
remarks=v.remarks,
source_count=source_count_map.get(v.id, 0),
updated_at=v.updated_at,
).model_dump()
)
return items
@router.get("", response_model=ApiResponse)
async def list_vods(
category_id: int | None = Query(None),
page: int = Query(1, ge=1),
page_size: int = Query(24, ge=1, le=100),
db: AsyncSession = Depends(get_db),
):
cache_key = vod_list_key(category_id, page, page_size)
cached = await cache_get(cache_key)
if cached is not None:
return ApiResponse.ok(cached)
query = select(Vod).where(Vod.is_hidden == False)
count_query = select(func.count(Vod.id)).where(Vod.is_hidden == False)
if category_id:
query = query.where(Vod.category_id == category_id)
count_query = count_query.where(Vod.category_id == category_id)
total_result = await db.execute(count_query)
total = total_result.scalar() or 0
result = await db.execute(
query.order_by(Vod.updated_at.desc())
.offset((page - 1) * page_size)
.limit(page_size)
)
vods = result.scalars().all()
if not vods:
data = PaginatedData(list=[], total=total, page=page, page_size=page_size).model_dump()
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
return ApiResponse.ok(data)
cat_map = await _batch_get_category_names(db, [v.category_id for v in vods])
source_count_map = await _batch_get_source_counts(db, [v.id for v in vods])
items = _build_vod_items(vods, cat_map, source_count_map)
data = PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
return ApiResponse.ok(data)
@router.get("/search", response_model=ApiResponse)
async def search_vods(
keyword: str = Query(..., min_length=1),
page: int = Query(1, ge=1),
page_size: int = Query(24, ge=1, le=100),
db: AsyncSession = Depends(get_db),
):
cache_key = vod_search_key(keyword, None, page, page_size)
cached = await cache_get(cache_key)
if cached is not None:
return ApiResponse.ok(cached)
pattern = f"%{keyword}%"
name_match = Vod.name.ilike(pattern) | Vod.sub_name.ilike(pattern) | Vod.actor.ilike(pattern)
count_result = await db.execute(
select(func.count(Vod.id)).where(Vod.is_hidden == False, name_match)
)
total = count_result.scalar() or 0
result = await db.execute(
select(Vod)
.where(Vod.is_hidden == False, name_match)
.order_by(Vod.updated_at.desc())
.offset((page - 1) * page_size)
.limit(page_size)
)
vods = result.scalars().all()
if not vods:
data = PaginatedData(list=[], total=total, page=page, page_size=page_size).model_dump()
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
return ApiResponse.ok(data)
cat_map = await _batch_get_category_names(db, [v.category_id for v in vods])
source_count_map = await _batch_get_source_counts(db, [v.id for v in vods])
items = _build_vod_items(vods, cat_map, source_count_map)
data = PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
return ApiResponse.ok(data)
@router.get("/recommended", response_model=ApiResponse)
async def recommended_vods(
page: int = Query(1, ge=1),
page_size: int = Query(12, ge=1, le=50),
db: AsyncSession = Depends(get_db),
):
cache_key = vod_recommended_key(page, page_size)
cached = await cache_get(cache_key)
if cached is not None:
return ApiResponse.ok(cached)
count_result = await db.execute(
select(func.count(Vod.id)).where(Vod.is_hidden == False, Vod.is_recommended == True)
)
total = count_result.scalar() or 0
result = await db.execute(
select(Vod)
.where(Vod.is_hidden == False, Vod.is_recommended == True)
.order_by(Vod.score.desc().nullslast(), Vod.updated_at.desc())
.offset((page - 1) * page_size)
.limit(page_size)
)
vods = result.scalars().all()
if not vods:
data = PaginatedData(list=[], total=total, page=page, page_size=page_size).model_dump()
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
return ApiResponse.ok(data)
cat_map = await _batch_get_category_names(db, [v.category_id for v in vods])
source_count_map = await _batch_get_source_counts(db, [v.id for v in vods])
items = _build_vod_items(vods, cat_map, source_count_map)
data = PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
return ApiResponse.ok(data)
@router.get("/latest", response_model=ApiResponse)
async def latest_vods(
hours: int = Query(72, ge=1),
page: int = Query(1, ge=1),
page_size: int = Query(24, ge=1, le=100),
db: AsyncSession = Depends(get_db),
):
from datetime import datetime, timedelta, timezone
cache_key = vod_latest_key(page, page_size)
cached = await cache_get(cache_key)
if cached is not None:
return ApiResponse.ok(cached)
cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
count_result = await db.execute(
select(func.count(Vod.id)).where(Vod.is_hidden == False, Vod.updated_at >= cutoff)
)
total = count_result.scalar() or 0
result = await db.execute(
select(Vod)
.where(Vod.is_hidden == False, Vod.updated_at >= cutoff)
.order_by(Vod.updated_at.desc())
.offset((page - 1) * page_size)
.limit(page_size)
)
vods = result.scalars().all()
if not vods:
data = PaginatedData(list=[], total=total, page=page, page_size=page_size).model_dump()
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
return ApiResponse.ok(data)
cat_map = await _batch_get_category_names(db, [v.category_id for v in vods])
source_count_map = await _batch_get_source_counts(db, [v.id for v in vods])
items = _build_vod_items(vods, cat_map, source_count_map)
data = PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
return ApiResponse.ok(data)
@router.get("/{vod_id}", response_model=ApiResponse)
async def get_vod(vod_id: int, db: AsyncSession = Depends(get_db)):
# 详情缓存(不缓存 view_count,每次仍递增,但结构信息缓存)
cache_key = vod_detail_key(vod_id)
cached = await cache_get(cache_key)
if cached is not None:
# 即使命中缓存仍递增播放次数
await increment_view_count(vod_id)
return ApiResponse.ok(cached)
result = await db.execute(select(Vod).where(Vod.id == vod_id, Vod.is_hidden == False))
vod = result.scalar_one_or_none()
if not vod:
return ApiResponse.fail(40401, "影片不存在")
await increment_view_count(vod_id)
cat_result = await db.execute(select(Category.name).where(Category.id == vod.category_id))
cat_name = cat_result.scalar_one_or_none()
source_result = await db.execute(
select(VodSource).where(VodSource.vod_id == vod_id, VodSource.is_available == True)
)
vod_sources = source_result.scalars().all()
if vod_sources:
source_ids = [vs.source_id for vs in vod_sources]
site_result = await db.execute(select(SourceSite).where(SourceSite.id.in_(source_ids)))
site_map = {s.id: s for s in site_result.scalars().all()}
else:
site_map = {}
sources = []
for vs in vod_sources:
site = site_map.get(vs.source_id)
if not site:
continue
episodes = _parse_play_url(vs.play_url)
play_from_label = vs.play_from
if site.play_from_m3u8 and vs.play_from == site.play_from_m3u8:
play_from_label = f"{site.name}-M3U8"
elif site.play_from_yun and vs.play_from == site.play_from_yun:
play_from_label = f"{site.name}-云播"
parse_url = site.parse_url if site.play_from_m3u8 and vs.play_from == site.play_from_m3u8 else None
sources.append(
VodPlaySource(
source_id=site.id,
source_name=site.name,
play_from=vs.play_from,
play_from_label=play_from_label,
episodes=[
EpisodeItem(
name=ep["name"],
url=ep["url"],
parse_url=parse_url,
)
for ep in episodes
],
).model_dump()
)
source_count = len(vod_sources)
detail = VodUserDetail(
id=vod.id,
name=vod.name,
sub_name=vod.sub_name,
cover=vod.cover,
category_id=vod.category_id,
category_name=cat_name,
score=vod.score,
year=vod.year,
area=vod.area,
actor=vod.actor,
director=vod.director,
lang=vod.lang,
duration=vod.duration,
is_end=vod.is_end,
remarks=vod.remarks,
blurb=vod.blurb,
content=vod.content,
source_count=source_count,
sources=sources,
updated_at=vod.updated_at,
).model_dump()
await cache_set(cache_key, detail, settings.CACHE_TTL_VOD_DETAIL)
return ApiResponse.ok(detail)
def _parse_play_url(play_url: str) -> list[dict]:
episodes = []
if not play_url:
return episodes
parts = play_url.split("#")
for part in parts:
part = part.strip()
if not part:
continue
if "$" in part:
name, url = part.split("$", 1)
episodes.append({"name": name.strip(), "url": url.strip()})
else:
episodes.append({"name": f"第{len(episodes)+1}集", "url": part.strip()})
return episodes