File size: 11,579 Bytes
9d66536 bf34e9d 9d66536 bf34e9d 32ddb29 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d cea9127 bf34e9d 9d66536 cea9127 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 9d66536 bf34e9d 32ddb29 bf34e9d 32ddb29 9d66536 32ddb29 9d66536 32ddb29 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 | 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
|