diff --git a/.env.example b/.env.example index fd8bed3c2ec17176b946233b2ad0c3221c0f15dc..3fce6e14d48e1162aa76a42dd2a9039e3de57a44 100644 --- a/.env.example +++ b/.env.example @@ -1,15 +1,38 @@ -# 开发环境(默认SQLite) +# ============================================================ +# BinV API 环境变量配置示例 +# 复制此文件为 .env 并填写实际值,.env 不得提交到版本控制 +# ============================================================ + +# 数据库 +# 开发环境 (SQLite) DATABASE_URL=sqlite+aiosqlite:///./binv.db -# 生产环境(MySQL) -# DATABASE_URL=mysql+aiomysql://bin_v:Han147258%2B-@124.221.224.204:7104/bin_v +# 生产环境 (MySQL) - 取消注释并填写实际连接信息 +# DATABASE_URL=mysql+aiomysql://用户名:密码@主机:端口/数据库名 +# DATABASE_URL_PROD=mysql+aiomysql://用户名:密码@主机:端口/数据库名 + +# JWT 密钥 - 生产环境必须使用强随机字符串,至少 32 位 +# 生成命令: python -c "import secrets; print(secrets.token_hex(32))" +SECRET_KEY=dev-only-change-in-production -SECRET_KEY=binv-secret-key-2026-change-in-prod +# Token 过期时间(分钟),默认 24 小时 ACCESS_TOKEN_EXPIRE_MINUTES=1440 -# CORS +# CORS 允许的前端域名,逗号分隔 CORS_ORIGINS=http://localhost:3000,http://localhost:5777,http://localhost:5555 -# 同步 +# 定时同步触发小时(0-23,服务器本地时间) SYNC_CRON_HOUR=1 -SYNC_MAX_CONCURRENT=3 \ No newline at end of file + +# 同步并发数 +SYNC_MAX_CONCURRENT=3 + +# 单次同步最大页数 +SYNC_MAX_PAGES=100 + +# Redis 缓存(可选,不填则自动降级为无缓存模式) +REDIS_URL=redis://localhost:6379/0 +CACHE_ENABLED=true +CACHE_TTL_VOD_LIST=300 +CACHE_TTL_VOD_DETAIL=600 +CACHE_TTL_CATEGORY=3600 diff --git a/.gitignore b/.gitignore index b8a662b7dd31ed5fffac0e2b18cbe3eeb696dfe5..3339ed5cad19afca257391ce13b3ea0038b941a8 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,8 @@ alembic/versions/__pycache__/ .idea/ .vscode/ *.sqlite3 +*.db +*.db.bak binv.db source_categories.txt scripts/fetch_categories.py diff --git a/alembic.ini b/alembic.ini index 38e3dd203c412bc41480819181a7189bd5dc14cc..4aa889c2b77a6a5229611fc9d977b68485dac51a 100644 --- a/alembic.ini +++ b/alembic.ini @@ -1,6 +1,6 @@ [alembic] script_location = alembic -sqlalchemy.url = postgresql+asyncpg://postgres:password@localhost:5432/binv +sqlalchemy.url = sqlite+aiosqlite:///./binv.db [loggers] keys = root,sqlalchemy,alembic diff --git a/alembic/env.py b/alembic/env.py index 571e8a199bb79f98de60dd6755e7068294a4eaf7..8449c228fefdc59a991fda920416153368ad9ff0 100644 --- a/alembic/env.py +++ b/alembic/env.py @@ -5,6 +5,7 @@ from alembic import context from sqlalchemy import pool from sqlalchemy.ext.asyncio import async_engine_from_config +from app.config import settings from app.database import Base from app.models import * # noqa: F401,F403 @@ -12,6 +13,9 @@ config = context.config if config.config_file_name is not None: fileConfig(config.config_file_name) +# 优先使用 settings.DATABASE_URL,覆盖 alembic.ini 中的值 +config.set_main_option("sqlalchemy.url", settings.DATABASE_URL) + target_metadata = Base.metadata diff --git a/alembic/versions/8126d022fb75_initial_schema.py b/alembic/versions/8126d022fb75_initial_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..1a147025216f8b97b72ea6f62e81cb9239c9402d --- /dev/null +++ b/alembic/versions/8126d022fb75_initial_schema.py @@ -0,0 +1,268 @@ +"""initial_schema + +Revision ID: 8126d022fb75 +Revises: +Create Date: 2026-05-15 15:38:43.248659 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + +# MySQL ON UPDATE CURRENT_TIMESTAMP helper +# SQLite 会忽略 server_onupdate,MySQL 会生成 ON UPDATE CURRENT_TIMESTAMP +_OU = sa.text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP') + + +revision: str = '8126d022fb75' +down_revision: Union[str, None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.create_table( + 'source_site', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(length=50), nullable=False, comment='站点名称'), + sa.Column('code', sa.String(length=30), nullable=False, comment='站点编码'), + sa.Column('base_url', sa.String(length=500), nullable=False, comment='API基础地址'), + sa.Column('site_url', sa.String(length=500), nullable=True, comment='官网地址'), + sa.Column('play_from_m3u8', sa.String(length=30), nullable=True, comment='M3U8来源标识'), + sa.Column('play_from_yun', sa.String(length=30), nullable=True, comment='云播来源标识'), + sa.Column('parse_url', sa.String(length=500), nullable=True, comment='M3U8解析接口'), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('sync_interval', sa.Integer(), nullable=False), + sa.Column('last_sync_at', sa.DateTime(), nullable=True), + sa.Column('last_sync_status', sa.String(length=20), nullable=True), + sa.Column('last_sync_count', sa.Integer(), nullable=False), + sa.Column('total_count', sa.Integer(), nullable=False), + sa.Column('sort_order', sa.Integer(), nullable=False), + sa.Column('remark', sa.String(length=200), nullable=True), + sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), server_onupdate=_OU, nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('code'), + ) + op.create_table( + 'category', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(length=30), nullable=False, comment='分类名称'), + sa.Column('parent_id', sa.Integer(), nullable=True), + sa.Column('sort_order', sa.Integer(), nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.PrimaryKeyConstraint('id'), + ) + op.create_table( + 'category_mapping', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('category_id', sa.Integer(), nullable=False, comment='统一分类ID'), + sa.Column('source_id', sa.Integer(), nullable=False, comment='资源站ID'), + sa.Column('source_type_id', sa.Integer(), nullable=False, comment='源站分类ID'), + sa.Column('source_type_name', sa.String(length=30), nullable=False, comment='源站分类名称'), + sa.PrimaryKeyConstraint('id'), + ) + op.create_table( + 'admin', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('username', sa.String(length=30), nullable=False, comment='用户名'), + sa.Column('password_hash', sa.String(length=128), nullable=False, comment='bcrypt哈希'), + sa.Column('nickname', sa.String(length=30), nullable=True), + sa.Column('avatar', sa.String(length=500), nullable=True), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('last_login_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), server_onupdate=_OU, nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('username'), + ) + op.create_table( + 'role', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(length=30), nullable=False, comment='角色名称'), + sa.Column('code', sa.String(length=30), nullable=False, comment='角色编码'), + sa.Column('description', sa.String(length=200), nullable=True), + sa.Column('is_builtin', sa.Boolean(), nullable=False), + sa.Column('status', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), server_onupdate=_OU, nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('code'), + sa.UniqueConstraint('name'), + ) + op.create_table( + 'admin_role', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('admin_id', sa.Integer(), nullable=False), + sa.Column('role_id', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('id'), + ) + op.create_table( + 'permission', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('code', sa.String(length=60), nullable=False, comment='权限码'), + sa.Column('name', sa.String(length=50), nullable=False, comment='权限名称'), + sa.Column('type', sa.String(length=10), nullable=False, comment='menu/page/btn'), + sa.Column('parent_id', sa.Integer(), nullable=True), + sa.Column('path', sa.String(length=200), nullable=True), + sa.Column('component', sa.String(length=200), nullable=True), + sa.Column('redirect', sa.String(length=200), nullable=True), + sa.Column('icon', sa.String(length=50), nullable=True), + sa.Column('sort_order', sa.Integer(), nullable=False), + sa.Column('status', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('code'), + ) + op.create_table( + 'role_permission', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('role_id', sa.Integer(), nullable=False), + sa.Column('permission_id', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('id'), + ) + op.create_table( + 'user', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('username', sa.String(length=30), nullable=True, comment='用户名'), + sa.Column('email', sa.String(length=100), nullable=True, comment='邮箱'), + sa.Column('phone', sa.String(length=20), nullable=True, comment='手机号'), + sa.Column('password_hash', sa.String(length=128), nullable=False, comment='bcrypt哈希'), + sa.Column('nickname', sa.String(length=30), nullable=True), + sa.Column('avatar', sa.String(length=500), nullable=True), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('last_login_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), server_onupdate=_OU, nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('username'), + sa.UniqueConstraint('email'), + sa.UniqueConstraint('phone'), + ) + op.create_table( + 'vod', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(length=200), nullable=False), + sa.Column('sub_name', sa.String(length=500), nullable=True), + sa.Column('en_name', sa.String(length=200), nullable=True), + sa.Column('category_id', sa.Integer(), nullable=False), + sa.Column('cover', sa.String(length=500), nullable=True), + sa.Column('actor', sa.String(length=2000), nullable=True), + sa.Column('director', sa.String(length=200), nullable=True), + sa.Column('area', sa.String(length=50), nullable=True), + sa.Column('lang', sa.String(length=50), nullable=True), + sa.Column('year', sa.String(length=10), nullable=True), + sa.Column('duration', sa.String(length=20), nullable=True), + sa.Column('score', sa.Float(), nullable=True), + sa.Column('douban_id', sa.Integer(), nullable=True), + sa.Column('blurb', sa.Text(), nullable=True), + sa.Column('content', sa.Text(), nullable=True), + sa.Column('remarks', sa.String(length=100), nullable=True), + sa.Column('is_end', sa.Boolean(), nullable=False), + sa.Column('is_hidden', sa.Boolean(), nullable=False), + sa.Column('is_recommended', sa.Boolean(), nullable=False), + sa.Column('view_count', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), server_onupdate=_OU, nullable=False), + sa.PrimaryKeyConstraint('id'), + ) + op.create_table( + 'vod_source', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('vod_id', sa.Integer(), nullable=False), + sa.Column('source_id', sa.Integer(), nullable=False), + sa.Column('source_vod_id', sa.Integer(), nullable=False, comment='源站影片ID'), + sa.Column('play_from', sa.String(length=30), nullable=False, comment='播放来源'), + sa.Column('play_url', sa.String(), nullable=False, comment='播放地址'), + sa.Column('parse_url', sa.String(), nullable=True, comment='解析后URL'), + sa.Column('is_available', sa.Boolean(), nullable=False), + sa.Column('last_check_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), server_onupdate=_OU, nullable=False), + sa.PrimaryKeyConstraint('id'), + ) + op.create_table( + 'favorite', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('vod_id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.PrimaryKeyConstraint('id'), + ) + op.create_table( + 'play_history', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('vod_id', sa.Integer(), nullable=False), + sa.Column('source_id', sa.Integer(), nullable=False), + sa.Column('episode', sa.String(length=50), nullable=True), + sa.Column('play_url', sa.String(), nullable=False), + sa.Column('progress', sa.Integer(), nullable=False), + sa.Column('duration', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), server_onupdate=_OU, nullable=False), + sa.PrimaryKeyConstraint('id'), + ) + op.create_table( + 'sync_log', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('source_id', sa.Integer(), nullable=False), + sa.Column('range_type', sa.String(length=20), nullable=False), + sa.Column('status', sa.String(length=20), nullable=False), + sa.Column('started_at', sa.DateTime(), nullable=False), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.Column('total_fetched', sa.Integer(), nullable=False), + sa.Column('new_count', sa.Integer(), nullable=False), + sa.Column('update_count', sa.Integer(), nullable=False), + sa.Column('fail_count', sa.Integer(), nullable=False), + sa.Column('error_message', sa.String(), nullable=True), + sa.Column('duration_seconds', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id'), + ) + op.create_table( + 'source_health', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('source_id', sa.Integer(), nullable=False), + sa.Column('check_type', sa.String(length=20), nullable=False, comment='api/play'), + sa.Column('is_success', sa.Boolean(), nullable=False), + sa.Column('response_time_ms', sa.Integer(), nullable=True), + sa.Column('error_message', sa.String(), nullable=True), + sa.Column('checked_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.PrimaryKeyConstraint('id'), + ) + + # ── 索引 ────────────────────────────────────────────────────────────────── + op.create_index('ix_vod_category_updated', 'vod', ['category_id', 'updated_at'], unique=False) + op.create_index('ix_vod_hidden_updated', 'vod', ['is_hidden', 'updated_at'], unique=False) + op.create_index('ix_vod_recommended_score', 'vod', ['is_recommended', 'score'], unique=False) + op.create_index('ix_vod_name_year', 'vod', ['name', 'year'], unique=False) + op.create_index('ix_vod_douban_id', 'vod', ['douban_id'], unique=False) + op.create_index('ix_vod_source_vod_id', 'vod_source', ['vod_id'], unique=False) + op.create_index('ix_vod_source_source_vod', 'vod_source', ['source_id', 'source_vod_id'], unique=False) + op.create_index('uq_favorite_user_vod', 'favorite', ['user_id', 'vod_id'], unique=True) + op.create_index('ix_play_history_user_updated', 'play_history', ['user_id', 'updated_at'], unique=False) + op.create_index('ix_play_history_user_vod', 'play_history', ['user_id', 'vod_id'], unique=False) + op.create_index('ix_sync_log_source_started', 'sync_log', ['source_id', 'started_at'], unique=False) + op.create_index('ix_source_health_source_checked','source_health', ['source_id', 'checked_at'], unique=False) + op.create_index('ix_category_active_sort', 'category', ['is_active', 'sort_order'], unique=False) + op.create_index('ix_category_mapping_source_type','category_mapping',['source_id', 'source_type_id'], unique=False) + + +def downgrade() -> None: + op.drop_table('source_health') + op.drop_table('sync_log') + op.drop_table('play_history') + op.drop_table('favorite') + op.drop_table('vod_source') + op.drop_table('vod') + op.drop_table('user') + op.drop_table('role_permission') + op.drop_table('permission') + op.drop_table('admin_role') + op.drop_table('role') + op.drop_table('admin') + op.drop_table('category_mapping') + op.drop_table('category') + op.drop_table('source_site') diff --git a/app/cache.py b/app/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..026416d3e77553b200aecd51b03b4e9a89cbbb44 --- /dev/null +++ b/app/cache.py @@ -0,0 +1,153 @@ +""" +Redis 缓存工具模块 +- 支持降级:Redis 不可用时自动退出缓存模式,不影响业务 +- key 命名规范:binv:{namespace}:{具体参数hash} +""" +import hashlib +import json +import logging +from typing import Any + +import redis.asyncio as aioredis + +from app.config import settings + +logger = logging.getLogger("cache") + +# 全局 Redis 连接池(懒加载) +_redis: aioredis.Redis | None = None + + +async def get_redis() -> aioredis.Redis | None: + """获取 Redis 连接,连接失败返回 None(降级模式)""" + global _redis + if not settings.CACHE_ENABLED: + return None + if _redis is None: + try: + _redis = aioredis.from_url( + settings.REDIS_URL, + encoding="utf-8", + decode_responses=True, + socket_connect_timeout=2, + socket_timeout=2, + ) + await _redis.ping() + logger.info(f"Redis connected: {settings.REDIS_URL}") + except Exception as e: + logger.warning(f"Redis unavailable, cache disabled: {e}") + _redis = None + return _redis + + +async def close_redis(): + """关闭 Redis 连接(应用退出时调用)""" + global _redis + if _redis is not None: + await _redis.aclose() + _redis = None + + +def _make_key(namespace: str, **kwargs) -> str: + """生成缓存 key,参数超过 32 字符时用 md5 压缩""" + param_str = "&".join(f"{k}={v}" for k, v in sorted(kwargs.items()) if v is not None) + if len(param_str) > 32: + param_str = hashlib.md5(param_str.encode()).hexdigest() + return f"binv:{namespace}:{param_str}" + + +async def cache_get(key: str) -> Any | None: + """读取缓存,失败返回 None""" + r = await get_redis() + if r is None: + return None + try: + raw = await r.get(key) + return json.loads(raw) if raw else None + except Exception as e: + logger.debug(f"cache_get error [{key}]: {e}") + return None + + +async def cache_set(key: str, value: Any, ttl: int) -> None: + """写入缓存,失败静默忽略""" + r = await get_redis() + if r is None: + return + try: + await r.setex(key, ttl, json.dumps(value, ensure_ascii=False, default=str)) + except Exception as e: + logger.debug(f"cache_set error [{key}]: {e}") + + +async def cache_delete(key: str) -> None: + """删除单个缓存 key""" + r = await get_redis() + if r is None: + return + try: + await r.delete(key) + except Exception as e: + logger.debug(f"cache_delete error [{key}]: {e}") + + +async def cache_delete_pattern(pattern: str) -> int: + """按 pattern 批量删除缓存(使用 SCAN 避免阻塞)""" + r = await get_redis() + if r is None: + return 0 + try: + deleted = 0 + async for key in r.scan_iter(match=pattern, count=100): + await r.delete(key) + deleted += 1 + return deleted + except Exception as e: + logger.debug(f"cache_delete_pattern error [{pattern}]: {e}") + return 0 + + +# ── 业务层 Key 生成器 ────────────────────────────────────────────────────────── + +def vod_list_key(category_id: int | None, page: int, page_size: int) -> str: + return _make_key("vod:list", category_id=category_id, page=page, page_size=page_size) + + +def vod_search_key(keyword: str, category_id: int | None, page: int, page_size: int) -> str: + return _make_key("vod:search", keyword=keyword, category_id=category_id, page=page, page_size=page_size) + + +def vod_latest_key(page: int, page_size: int) -> str: + return _make_key("vod:latest", page=page, page_size=page_size) + + +def vod_recommended_key(page: int, page_size: int) -> str: + return _make_key("vod:recommended", page=page, page_size=page_size) + + +def vod_detail_key(vod_id: int) -> str: + return _make_key("vod:detail", vod_id=vod_id) + + +def category_tree_key() -> str: + return "binv:category:tree" + + +# ── 缓存失效辅助 ────────────────────────────────────────────────────────────── + +async def invalidate_vod_cache(vod_id: int | None = None) -> None: + """影片数据变更时清除相关缓存""" + if vod_id: + await cache_delete(vod_detail_key(vod_id)) + # 列表缓存全部清除(因为排序、数量都可能变化) + await cache_delete_pattern("binv:vod:list:*") + await cache_delete_pattern("binv:vod:search:*") + await cache_delete_pattern("binv:vod:latest:*") + await cache_delete_pattern("binv:vod:recommended:*") + + +async def invalidate_category_cache() -> None: + """分类变更时清除分类树缓存""" + await cache_delete(category_tree_key()) + # 分类变化也影响影片列表 + await cache_delete_pattern("binv:vod:list:*") diff --git a/app/config.py b/app/config.py index b9daffb5419c1e84521aadd2904d4a56f547fe09..7fadc4a6c26c8a53f0d80afae6b7ec4640e94445 100644 --- a/app/config.py +++ b/app/config.py @@ -3,14 +3,24 @@ from pydantic_settings import BaseSettings class Settings(BaseSettings): DATABASE_URL: str = "sqlite+aiosqlite:///./binv.db" - DATABASE_URL_PROD: str = "mysql+aiomysql://bin_v:Han147258%2B-@124.221.224.204:7104/bin_v" - SECRET_KEY: str = "binv-secret-key-2026-change-in-prod" + # 生产数据库 URL 必须通过环境变量注入,不在代码中提供默认值 + DATABASE_URL_PROD: str = "" + # JWT 密钥必须通过环境变量注入,生产环境不得使用默认值 + SECRET_KEY: str = "dev-only-change-in-production" ACCESS_TOKEN_EXPIRE_MINUTES: int = 1440 CORS_ORIGINS: str = "http://localhost:3000,http://localhost:5777,http://localhost:5555" SYNC_CRON_HOUR: int = 1 SYNC_MAX_CONCURRENT: int = 3 SYNC_MAX_PAGES: int = 100 + # Redis 配置(缓存层,可选,不配置则降级为无缓存模式) + REDIS_URL: str = "redis://localhost:6379/0" + CACHE_ENABLED: bool = True + # 各类缓存 TTL(秒) + CACHE_TTL_VOD_LIST: int = 300 # 影片列表缓存 5 分钟 + CACHE_TTL_VOD_DETAIL: int = 600 # 影片详情缓存 10 分钟 + CACHE_TTL_CATEGORY: int = 3600 # 分类树缓存 1 小时 + model_config = {"env_file": ".env", "extra": "ignore"} diff --git a/app/dependencies.py b/app/dependencies.py index 4c741bb34348b442121185367adcd0e8b74e2006..23009a6e4079624dd6c679bb9097961b678b9f5f 100644 --- a/app/dependencies.py +++ b/app/dependencies.py @@ -1,8 +1,8 @@ from collections.abc import AsyncGenerator +import jwt from fastapi import Depends, HTTPException, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer -from jose import JWTError, jwt from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession @@ -23,10 +23,11 @@ async def get_current_admin( token = credentials.credentials try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"]) - admin_id: int | None = payload.get("sub") - if admin_id is None: + admin_id: str | None = payload.get("sub") + token_type: str | None = payload.get("type") + if admin_id is None or token_type != "admin": raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") - except JWTError: + except jwt.PyJWTError: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") result = await db.execute(select(Admin).where(Admin.id == int(admin_id))) @@ -43,11 +44,11 @@ async def get_current_user( token = credentials.credentials try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"]) - user_id: int | None = payload.get("sub") + user_id: str | None = payload.get("sub") user_type: str | None = payload.get("type") if user_id is None or user_type != "user": raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") - except JWTError: + except jwt.PyJWTError: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") result = await db.execute(select(User).where(User.id == int(user_id))) @@ -94,3 +95,4 @@ def require_permission(permission_code: str): return admin return permission_checker + diff --git a/app/limiter.py b/app/limiter.py new file mode 100644 index 0000000000000000000000000000000000000000..38404a8a6d7dbaca01db045351560a102db07613 --- /dev/null +++ b/app/limiter.py @@ -0,0 +1,4 @@ +from slowapi import Limiter +from slowapi.util import get_remote_address + +limiter = Limiter(key_func=get_remote_address) diff --git a/app/main.py b/app/main.py index 4d59d91e32e960c194c48dc6c5dd033f76fe4b95..57fa8712905e2a6f4740790e00813418a6ae778c 100644 --- a/app/main.py +++ b/app/main.py @@ -2,8 +2,12 @@ from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware +from slowapi import _rate_limit_exceeded_handler +from slowapi.errors import RateLimitExceeded +from app.cache import get_redis, close_redis from app.config import settings +from app.limiter import limiter from app.routers import admin_router from app.routers.user import user_router from app.services.scheduler import start_scheduler, stop_scheduler @@ -11,9 +15,12 @@ from app.services.scheduler import start_scheduler, stop_scheduler @asynccontextmanager async def lifespan(app: FastAPI): + # 初始化 Redis 连接(失败会自动降级,不阻断启动) + await get_redis() start_scheduler() yield stop_scheduler() + await close_redis() app = FastAPI( @@ -23,6 +30,9 @@ app = FastAPI( lifespan=lifespan, ) +app.state.limiter = limiter +app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) + app.add_middleware( CORSMiddleware, allow_origins=[o.strip() for o in settings.CORS_ORIGINS.split(",")], @@ -37,4 +47,32 @@ app.include_router(user_router, prefix="/user") @app.get("/health") async def health_check(): - return {"status": "ok"} \ No newline at end of file + from sqlalchemy import text + from app.database import async_session + from app.cache import get_redis + + # 数据库检查 + try: + async with async_session() as db: + await db.execute(text("SELECT 1")) + db_status = "ok" + except Exception as e: + db_status = f"error: {e}" + + # Redis 检查 + try: + r = await get_redis() + if r: + await r.ping() + redis_status = "ok" + else: + redis_status = "disabled" + except Exception as e: + redis_status = f"error: {e}" + + overall = "ok" if db_status == "ok" else "degraded" + return { + "status": overall, + "db": db_status, + "redis": redis_status, + } diff --git a/app/models/category.py b/app/models/category.py index 5949cb2a770df0e867e5c0c57bd53537fc8b8608..f213de02de14c44a59cba94294171c61697d1f5c 100644 --- a/app/models/category.py +++ b/app/models/category.py @@ -1,6 +1,6 @@ from datetime import datetime -from sqlalchemy import Boolean, DateTime, Integer, String, func +from sqlalchemy import Boolean, DateTime, Index, Integer, String, func from sqlalchemy.orm import Mapped, mapped_column from app.database import Base @@ -16,6 +16,11 @@ class Category(Base): is_active: Mapped[bool] = mapped_column(Boolean, default=True, comment="是否启用") created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now()) + __table_args__ = ( + # 分类树查询:活跃 + 排序 + Index("ix_category_active_sort", "is_active", "sort_order"), + ) + class CategoryMapping(Base): __tablename__ = "category_mapping" @@ -25,3 +30,9 @@ class CategoryMapping(Base): source_id: Mapped[int] = mapped_column(Integer, nullable=False, comment="资源站ID") source_type_id: Mapped[int] = mapped_column(Integer, nullable=False, comment="源站分类ID") source_type_name: Mapped[str] = mapped_column(String(30), nullable=False, comment="源站分类名称") + + __table_args__ = ( + # 采集器分类映射查找:source_id + source_type_id 定位分类 + Index("ix_category_mapping_source_type", "source_id", "source_type_id"), + ) + diff --git a/app/models/favorite.py b/app/models/favorite.py index 8396e300a49907e047437339f6f072de1da1ea84..6856833226dc91769f548ef0886d394af216703a 100644 --- a/app/models/favorite.py +++ b/app/models/favorite.py @@ -1,6 +1,6 @@ from datetime import datetime -from sqlalchemy import DateTime, Integer, func +from sqlalchemy import DateTime, Index, Integer, func from sqlalchemy.orm import Mapped, mapped_column from app.database import Base @@ -13,3 +13,8 @@ class Favorite(Base): user_id: Mapped[int] = mapped_column(Integer, nullable=False, comment="用户ID") vod_id: Mapped[int] = mapped_column(Integer, nullable=False, comment="影片ID") created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now()) + + __table_args__ = ( + # 唯一复合索引:防止同一用户重复收藏同一影片,同时加速查询 + Index("uq_favorite_user_vod", "user_id", "vod_id", unique=True), + ) diff --git a/app/models/play_history.py b/app/models/play_history.py index b597ebf0f131de4e19113eee977610d392cfea76..9acf94d075da19a58c2da557809a3ad06a5cf0d4 100644 --- a/app/models/play_history.py +++ b/app/models/play_history.py @@ -1,6 +1,6 @@ from datetime import datetime -from sqlalchemy import DateTime, Integer, String, func +from sqlalchemy import DateTime, Index, Integer, String, func from sqlalchemy.orm import Mapped, mapped_column from app.database import Base @@ -19,3 +19,10 @@ class PlayHistory(Base): duration: Mapped[int] = mapped_column(Integer, default=0, comment="总时长(秒)") created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now()) updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now()) + + __table_args__ = ( + # 历史列表:按用户 + 时间倒序 + Index("ix_play_history_user_updated", "user_id", "updated_at"), + # 更新播放进度:user_id + vod_id 定位记录 + Index("ix_play_history_user_vod", "user_id", "vod_id"), + ) diff --git a/app/models/source_health.py b/app/models/source_health.py index 09ef51c7a308585d49d985ba13135328d69e922e..ec96ae3bebac266dc1522de272528985c233739c 100644 --- a/app/models/source_health.py +++ b/app/models/source_health.py @@ -1,6 +1,6 @@ from datetime import datetime -from sqlalchemy import Boolean, DateTime, Integer, String, func +from sqlalchemy import Boolean, DateTime, Index, Integer, String, func from sqlalchemy.orm import Mapped, mapped_column from app.database import Base @@ -16,3 +16,8 @@ class SourceHealth(Base): response_time_ms: Mapped[int | None] = mapped_column(Integer, comment="响应时间(ms)") error_message: Mapped[str | None] = mapped_column(String, comment="错误信息") checked_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now()) + + __table_args__ = ( + # 查询最新健康记录:source_id + checked_at 倒序 + Index("ix_source_health_source_checked", "source_id", "checked_at"), + ) diff --git a/app/models/sync_log.py b/app/models/sync_log.py index cb9467639fbbd1508bab7ad551124aa7db189148..770fa1190290e768df7fb05b0b2d7ab5cc0064a5 100644 --- a/app/models/sync_log.py +++ b/app/models/sync_log.py @@ -1,6 +1,6 @@ from datetime import datetime -from sqlalchemy import DateTime, Integer, String, func +from sqlalchemy import DateTime, Index, Integer, String, func from sqlalchemy.orm import Mapped, mapped_column from app.database import Base @@ -11,7 +11,8 @@ class SyncLog(Base): id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) source_id: Mapped[int] = mapped_column(Integer, nullable=False, comment="资源站ID") - status: Mapped[str] = mapped_column(String(20), nullable=False, comment="running/success/failed") + range_type: Mapped[str] = mapped_column(String(20), nullable=False, default="daily", comment="同步范围: all/monthly/weekly/daily") + status: Mapped[str] = mapped_column(String(20), nullable=False, comment="running/success/failed/skipped") started_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, comment="开始时间") finished_at: Mapped[datetime | None] = mapped_column(DateTime, comment="结束时间") total_fetched: Mapped[int] = mapped_column(Integer, default=0, comment="拉取总数") @@ -20,3 +21,8 @@ class SyncLog(Base): fail_count: Mapped[int] = mapped_column(Integer, default=0, comment="失败数") error_message: Mapped[str | None] = mapped_column(String, comment="错误信息") duration_seconds: Mapped[int | None] = mapped_column(Integer, comment="耗时秒数") + + __table_args__ = ( + # 同步日志列表:按 source_id 过滤 + 时间倒序 + Index("ix_sync_log_source_started", "source_id", "started_at"), + ) diff --git a/app/models/vod.py b/app/models/vod.py index 5ab03f98eda762cc089845ba382ec77f9dbcf93d..2a09cba5f1a08b883bd01b446cafb7355c3e65f4 100644 --- a/app/models/vod.py +++ b/app/models/vod.py @@ -1,6 +1,6 @@ from datetime import datetime -from sqlalchemy import Boolean, DateTime, Float, Integer, String, Text, func +from sqlalchemy import Boolean, DateTime, Float, Index, Integer, String, Text, func from sqlalchemy.orm import Mapped, mapped_column from app.database import Base @@ -32,3 +32,16 @@ class Vod(Base): view_count: Mapped[int] = mapped_column(Integer, default=0, comment="播放次数") created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now()) updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now()) + + __table_args__ = ( + # 影片列表:按分类过滤 + 时间排序(最常用查询) + Index("ix_vod_category_updated", "category_id", "updated_at"), + # 隐藏状态 + 时间排序(用户端列表 WHERE is_hidden=0 ORDER BY updated_at) + Index("ix_vod_hidden_updated", "is_hidden", "updated_at"), + # 推荐列表:is_recommended + score 排序 + Index("ix_vod_recommended_score", "is_recommended", "score"), + # 去重查询:按名称+年份 + Index("ix_vod_name_year", "name", "year"), + # 去重查询:按 douban_id(唯一性较高,单列即可) + Index("ix_vod_douban_id", "douban_id"), + ) diff --git a/app/models/vod_source.py b/app/models/vod_source.py index a07c70384e469c0a4814a9f0fd82f5efb7cf6b05..d524316b7733ec1a06e42a59168c686a5b680c46 100644 --- a/app/models/vod_source.py +++ b/app/models/vod_source.py @@ -1,6 +1,6 @@ from datetime import datetime -from sqlalchemy import Boolean, DateTime, Integer, String, func +from sqlalchemy import Boolean, DateTime, Index, Integer, String, func from sqlalchemy.orm import Mapped, mapped_column from app.database import Base @@ -20,3 +20,10 @@ class VodSource(Base): last_check_at: Mapped[datetime | None] = mapped_column(DateTime, comment="可用性检查时间") created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now()) updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now()) + + __table_args__ = ( + # 影片详情页加载播放源(最高频查询) + Index("ix_vod_source_vod_id", "vod_id"), + # 采集器去重:source_id + source_vod_id 定位已有记录 + Index("ix_vod_source_source_vod", "source_id", "source_vod_id"), + ) diff --git a/app/routers/admin/admin_mgmt.py b/app/routers/admin/admin_mgmt.py index 7f5f89b5506b154496b3496628789625a05b7685..8386220e65c314353c0597ab42f708d36985539e 100644 --- a/app/routers/admin/admin_mgmt.py +++ b/app/routers/admin/admin_mgmt.py @@ -8,6 +8,12 @@ from app.database import get_db from app.dependencies import require_permission from app.models.admin import Admin from app.models.role import AdminRole, Role +from app.schemas.admin.admin_mgmt import ( + AdminCreateRequest, + AdminUpdateRequest, + AdminResetPasswordRequest, + AdminAssignRolesRequest, +) from app.schemas.common import ApiResponse, PaginatedData from app.utils.auth import hash_password @@ -29,15 +35,27 @@ async def list_admins( ) admins = result.scalars().all() - items = [] - for a in admins: + if admins: + admin_ids = [a.id for a in admins] roles_result = await db.execute( - select(Role.code).join(AdminRole, AdminRole.role_id == Role.id).where(AdminRole.admin_id == a.id) + select(AdminRole.admin_id, Role.code) + .join(Role, Role.id == AdminRole.role_id) + .where(AdminRole.admin_id.in_(admin_ids)) ) - roles = [r[0] for r in roles_result.all()] + admin_roles_map: dict[int, list[str]] = {} + for admin_id, role_code in roles_result.all(): + if admin_id not in admin_roles_map: + admin_roles_map[admin_id] = [] + admin_roles_map[admin_id].append(role_code) + else: + admin_roles_map = {} + + items = [] + for a in admins: items.append({ "id": a.id, "username": a.username, "nickname": a.nickname, - "avatar": a.avatar, "is_active": a.is_active, "roles": roles, + "avatar": a.avatar, "is_active": a.is_active, + "roles": admin_roles_map.get(a.id, []), "last_login_at": str(a.last_login_at) if a.last_login_at else None, "created_at": str(a.created_at) if a.created_at else None, }) @@ -49,23 +67,18 @@ async def list_admins( @router.post("", response_model=ApiResponse) async def create_admin( - body: dict, + req: AdminCreateRequest, admin: Admin = Depends(require_permission("admin:create")), db: AsyncSession = Depends(get_db), ): - username = body.get("username") - password = body.get("password") - if not username or not password: - return ApiResponse.fail(40001, "用户名和密码必填") - - existing = await db.execute(select(Admin).where(Admin.username == username)) + existing = await db.execute(select(Admin).where(Admin.username == req.username)) if existing.scalar_one_or_none(): return ApiResponse.fail(40002, "用户名已存在") new_admin = Admin( - username=username, - password_hash=hash_password(password), - nickname=body.get("nickname"), + username=req.username, + password_hash=hash_password(req.password), + nickname=req.nickname, ) db.add(new_admin) await db.flush() @@ -75,7 +88,7 @@ async def create_admin( @router.put("/{admin_id}", response_model=ApiResponse) async def update_admin( admin_id: int, - body: dict, + req: AdminUpdateRequest, admin: Admin = Depends(require_permission("admin:update")), db: AsyncSession = Depends(get_db), ): @@ -84,10 +97,8 @@ async def update_admin( if not target: return ApiResponse.fail(40401, "管理员不存在") - if "nickname" in body: - target.nickname = body["nickname"] - if "is_active" in body: - target.is_active = body["is_active"] + for field, value in req.model_dump(exclude_unset=True).items(): + setattr(target, field, value) return ApiResponse.ok() @@ -110,32 +121,30 @@ async def delete_admin( @router.put("/{admin_id}/reset-password", response_model=ApiResponse) async def reset_password( admin_id: int, - body: dict, + req: AdminResetPasswordRequest, admin: Admin = Depends(require_permission("admin:btn:reset_pwd")), db: AsyncSession = Depends(get_db), ): - new_password = body.get("password", "123456") result = await db.execute(select(Admin).where(Admin.id == admin_id)) target = result.scalar_one_or_none() if not target: return ApiResponse.fail(40401, "管理员不存在") - target.password_hash = hash_password(new_password) + target.password_hash = hash_password(req.password) return ApiResponse.ok() @router.put("/{admin_id}/assign-roles", response_model=ApiResponse) async def assign_roles( admin_id: int, - body: dict, + req: AdminAssignRolesRequest, admin: Admin = Depends(require_permission("admin:btn:assign_role")), db: AsyncSession = Depends(get_db), ): - role_ids = body.get("role_ids", []) result = await db.execute(select(Admin).where(Admin.id == admin_id)) if not result.scalar_one_or_none(): return ApiResponse.fail(40401, "管理员不存在") await db.execute(AdminRole.__table__.delete().where(AdminRole.admin_id == admin_id)) - for rid in role_ids: + for rid in req.role_ids: db.add(AdminRole(admin_id=admin_id, role_id=rid)) return ApiResponse.ok() \ No newline at end of file diff --git a/app/routers/admin/auth.py b/app/routers/admin/auth.py index 465fab75c3fc05d55e823240cf28053dd326aff4..f6c6620df6d1a5f0c8a2379552af093bb2cc030d 100644 --- a/app/routers/admin/auth.py +++ b/app/routers/admin/auth.py @@ -1,8 +1,9 @@ -from fastapi import APIRouter, Depends +from fastapi import APIRouter, Depends, Request from sqlalchemy.ext.asyncio import AsyncSession from app.database import get_db from app.dependencies import get_current_admin +from app.limiter import limiter from app.schemas.admin.auth import LoginRequest, LoginResponse, UserInfoResponse from app.schemas.common import ApiResponse from app.services import auth_admin @@ -12,7 +13,8 @@ router = APIRouter() @router.post("/login", response_model=ApiResponse) -async def login(req: LoginRequest, db: AsyncSession = Depends(get_db)): +@limiter.limit("10/minute") +async def login(request: Request, req: LoginRequest, db: AsyncSession = Depends(get_db)): admin = await auth_admin.authenticate_admin(db, req.username, req.password) if not admin: return ApiResponse.fail(40001, "用户名或密码错误") diff --git a/app/routers/admin/category.py b/app/routers/admin/category.py index 36b096013e72f10a729fdbc3188854add3beee8b..47ade06a578bd43f06fe31bf6072d7bcbb078077 100644 --- a/app/routers/admin/category.py +++ b/app/routers/admin/category.py @@ -2,11 +2,13 @@ from fastapi import APIRouter, Depends, Query from sqlalchemy import delete as sa_delete, func, select from sqlalchemy.ext.asyncio import AsyncSession +from app.cache import invalidate_category_cache from app.database import get_db from app.dependencies import get_current_admin, require_permission from app.models.admin import Admin from app.models.category import Category, CategoryMapping from app.models.source_site import SourceSite +from app.schemas.admin.category import CategoryUpdateRequest, CategoryMappingUpdateRequest from app.schemas.common import ApiResponse, PaginatedData router = APIRouter() @@ -36,7 +38,7 @@ async def list_categories( @router.put("/{category_id}", response_model=ApiResponse) async def update_category( category_id: int, - body: dict, + req: CategoryUpdateRequest, admin: Admin = Depends(require_permission("category:update")), db: AsyncSession = Depends(get_db), ): @@ -45,12 +47,11 @@ async def update_category( if not cat: return ApiResponse.fail(40401, "分类不存在") - allowed = ["name", "sort_order", "is_active", "parent_id"] - for field in allowed: - if field in body: - setattr(cat, field, body[field]) + for field, value in req.model_dump(exclude_unset=True).items(): + setattr(cat, field, value) await db.flush() + await invalidate_category_cache() return ApiResponse.ok() @@ -67,19 +68,27 @@ async def list_mappings( result = await db.execute(query.order_by(CategoryMapping.source_id, CategoryMapping.source_type_id)) mappings = result.scalars().all() + if mappings: + cat_ids = list({m.category_id for m in mappings}) + source_ids = list({m.source_id for m in mappings}) + + cat_result = await db.execute(select(Category.id, Category.name).where(Category.id.in_(cat_ids))) + cat_map = {row[0]: row[1] for row in cat_result.all()} + + source_result = await db.execute(select(SourceSite.id, SourceSite.name).where(SourceSite.id.in_(source_ids))) + source_map = {row[0]: row[1] for row in source_result.all()} + else: + cat_map = {} + source_map = {} + items = [] for m in mappings: - cat_result = await db.execute(select(Category).where(Category.id == m.category_id)) - cat = cat_result.scalar_one_or_none() - source_result = await db.execute(select(SourceSite).where(SourceSite.id == m.source_id)) - source = source_result.scalar_one_or_none() - items.append({ "id": m.id, "category_id": m.category_id, - "category_name": cat.name if cat else None, + "category_name": cat_map.get(m.category_id), "source_id": m.source_id, - "source_name": source.name if source else None, + "source_name": source_map.get(m.source_id), "source_type_id": m.source_type_id, "source_type_name": m.source_type_name, }) @@ -89,33 +98,27 @@ async def list_mappings( @router.put("/mapping", response_model=ApiResponse) async def update_mappings( - body: dict, + req: CategoryMappingUpdateRequest, admin: Admin = Depends(require_permission("category:btn:map")), db: AsyncSession = Depends(get_db), ): - mappings_data = body.get("mappings", []) - if not mappings_data: - return ApiResponse.fail(40001, "mappings data is required") - - source_id = body.get("source_id") - if not source_id: - return ApiResponse.fail(40002, "source_id is required") - - source_result = await db.execute(select(SourceSite).where(SourceSite.id == source_id)) + source_result = await db.execute(select(SourceSite).where(SourceSite.id == req.source_id)) if not source_result.scalar_one_or_none(): return ApiResponse.fail(40401, "源站不存在") - await db.execute(sa_delete(CategoryMapping).where(CategoryMapping.source_id == source_id)) + await db.execute(sa_delete(CategoryMapping).where(CategoryMapping.source_id == req.source_id)) await db.flush() - for m in mappings_data: - cat_result = await db.execute(select(Category).where(Category.id == m["category_id"])) - cat = cat_result.scalar_one_or_none() + cat_ids = list({m.category_id for m in req.mappings}) + cat_result = await db.execute(select(Category.id, Category.name).where(Category.id.in_(cat_ids))) + cat_map = {row[0]: row[1] for row in cat_result.all()} + + for m in req.mappings: mapping = CategoryMapping( - category_id=m["category_id"], - source_id=source_id, - source_type_id=m["source_type_id"], - source_type_name=cat.name if cat else str(m["source_type_id"]), + category_id=m.category_id, + source_id=req.source_id, + source_type_id=m.source_type_id, + source_type_name=cat_map.get(m.category_id, str(m.source_type_id)), ) db.add(mapping) diff --git a/app/routers/admin/role_mgmt.py b/app/routers/admin/role_mgmt.py index 10c471706c1961a0f855b19bf5b1778cc6dc226c..f7052d3febbb57e756cdd6edcb38a474af92a254 100644 --- a/app/routers/admin/role_mgmt.py +++ b/app/routers/admin/role_mgmt.py @@ -7,6 +7,7 @@ from app.dependencies import require_permission from app.models.admin import Admin from app.models.permission import Permission, RolePermission from app.models.role import AdminRole, Role +from app.schemas.admin.role_mgmt import RoleCreateRequest, RoleUpdateRequest, RoleAssignPermissionsRequest from app.schemas.common import ApiResponse, PaginatedData router = APIRouter() @@ -20,16 +21,24 @@ async def list_roles( result = await db.execute(select(Role).order_by(Role.id)) roles = result.scalars().all() + if roles: + role_ids = [r.id for r in roles] + perm_count_result = await db.execute( + select(RolePermission.role_id, func.count(RolePermission.id)) + .where(RolePermission.role_id.in_(role_ids)) + .group_by(RolePermission.role_id) + ) + perm_count_map = {row[0]: row[1] for row in perm_count_result.all()} + else: + perm_count_map = {} + items = [] for r in roles: - perm_count = await db.execute( - select(func.count(RolePermission.id)).where(RolePermission.role_id == r.id) - ) items.append({ "id": r.id, "name": r.name, "code": r.code, "description": r.description, "is_builtin": r.is_builtin, "status": r.status, - "permission_count": perm_count.scalar() or 0, + "permission_count": perm_count_map.get(r.id, 0), }) return ApiResponse.ok(items) @@ -37,20 +46,15 @@ async def list_roles( @router.post("", response_model=ApiResponse) async def create_role( - body: dict, + req: RoleCreateRequest, admin: Admin = Depends(require_permission("role:create")), db: AsyncSession = Depends(get_db), ): - name = body.get("name") - code = body.get("code") - if not name or not code: - return ApiResponse.fail(40001, "名称和编码必填") - - existing = await db.execute(select(Role).where(Role.code == code)) + existing = await db.execute(select(Role).where(Role.code == req.code)) if existing.scalar_one_or_none(): return ApiResponse.fail(40002, "角色编码已存在") - role = Role(name=name, code=code, description=body.get("description")) + role = Role(name=req.name, code=req.code, description=req.description) db.add(role) await db.flush() return ApiResponse.ok({"id": role.id}) @@ -59,7 +63,7 @@ async def create_role( @router.put("/{role_id}", response_model=ApiResponse) async def update_role( role_id: int, - body: dict, + req: RoleUpdateRequest, admin: Admin = Depends(require_permission("role:update")), db: AsyncSession = Depends(get_db), ): @@ -68,12 +72,8 @@ async def update_role( if not role: return ApiResponse.fail(40401, "角色不存在") - if "name" in body: - role.name = body["name"] - if "description" in body: - role.description = body["description"] - if "status" in body: - role.status = body["status"] + for field, value in req.model_dump(exclude_unset=True).items(): + setattr(role, field, value) return ApiResponse.ok() @@ -99,16 +99,15 @@ async def delete_role( @router.put("/{role_id}/permissions", response_model=ApiResponse) async def assign_permissions( role_id: int, - body: dict, + req: RoleAssignPermissionsRequest, admin: Admin = Depends(require_permission("role:btn:assign_perm")), db: AsyncSession = Depends(get_db), ): - perm_ids = body.get("permission_ids", []) result = await db.execute(select(Role).where(Role.id == role_id)) if not result.scalar_one_or_none(): return ApiResponse.fail(40401, "角色不存在") await db.execute(RolePermission.__table__.delete().where(RolePermission.role_id == role_id)) - for pid in perm_ids: + for pid in req.permission_ids: db.add(RolePermission(role_id=role_id, permission_id=pid)) return ApiResponse.ok() \ No newline at end of file diff --git a/app/routers/admin/source.py b/app/routers/admin/source.py index 105480c41bb73e691369fd4adafa7ca38541ef21..8932457888c7e75684d7921f9473c75ca500aad0 100644 --- a/app/routers/admin/source.py +++ b/app/routers/admin/source.py @@ -1,14 +1,16 @@ import httpx from fastapi import APIRouter, Depends, Query -from sqlalchemy import func, select, update +from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession from app.database import get_db -from app.dependencies import get_current_admin, require_permission +from app.dependencies import require_permission from app.models.admin import Admin from app.models.source_site import SourceSite +from app.schemas.admin.source import SourceCreateRequest, SourceUpdateRequest from app.schemas.common import ApiResponse, PaginatedData +from app.services.health import get_latest_health, run_health_checks router = APIRouter() @@ -24,12 +26,22 @@ async def list_sources( total = count_result.scalar() or 0 result = await db.execute( - select(SourceSite).order_by(SourceSite.sort_order).offset((page - 1) * page_size).limit(page_size) + select(SourceSite) + .order_by(SourceSite.sort_order) + .offset((page - 1) * page_size) + .limit(page_size) ) sources = result.scalars().all() + if sources: + source_ids = [s.id for s in sources] + health_map = await get_latest_health(db, source_ids) + else: + health_map = {} + items = [] for s in sources: + health = health_map.get(s.id) items.append({ "id": s.id, "name": s.name, @@ -47,6 +59,7 @@ async def list_sources( "total_count": s.total_count, "sort_order": s.sort_order, "remark": s.remark, + "health": health, }) return ApiResponse.ok( @@ -54,6 +67,33 @@ async def list_sources( ) +@router.post("", response_model=ApiResponse) +async def create_source( + req: SourceCreateRequest, + admin: Admin = Depends(require_permission("source:create")), + db: AsyncSession = Depends(get_db), +): + existing = await db.execute(select(SourceSite).where(SourceSite.code == req.code)) + if existing.scalar_one_or_none(): + return ApiResponse.fail(40002, "站点编码已存在") + + source = SourceSite( + name=req.name, + code=req.code, + base_url=req.base_url, + site_url=req.site_url, + play_from_m3u8=req.play_from_m3u8, + play_from_yun=req.play_from_yun, + parse_url=req.parse_url, + sync_interval=req.sync_interval, + sort_order=req.sort_order, + remark=req.remark, + ) + db.add(source) + await db.flush() + return ApiResponse.ok({"id": source.id}) + + @router.get("/{source_id}", response_model=ApiResponse) async def get_source( source_id: int, @@ -65,6 +105,7 @@ async def get_source( if not source: return ApiResponse.fail(40401, "源站不存在") + health_map = await get_latest_health(db, [source_id]) return ApiResponse.ok({ "id": source.id, "name": source.name, @@ -82,13 +123,14 @@ async def get_source( "total_count": source.total_count, "sort_order": source.sort_order, "remark": source.remark, + "health": health_map.get(source_id), }) @router.put("/{source_id}", response_model=ApiResponse) async def update_source( source_id: int, - body: dict, + req: SourceUpdateRequest, admin: Admin = Depends(require_permission("source:update")), db: AsyncSession = Depends(get_db), ): @@ -97,19 +139,28 @@ async def update_source( if not source: return ApiResponse.fail(40401, "源站不存在") - allowed_fields = [ - "name", "base_url", "site_url", "play_from_m3u8", - "play_from_yun", "parse_url", "sync_interval", - "sort_order", "remark", - ] - for field in allowed_fields: - if field in body: - setattr(source, field, body[field]) + for field, value in req.model_dump(exclude_unset=True).items(): + setattr(source, field, value) await db.flush() return ApiResponse.ok() +@router.delete("/{source_id}", response_model=ApiResponse) +async def delete_source( + source_id: int, + admin: Admin = Depends(require_permission("source:delete")), + db: AsyncSession = Depends(get_db), +): + result = await db.execute(select(SourceSite).where(SourceSite.id == source_id)) + source = result.scalar_one_or_none() + if not source: + return ApiResponse.fail(40401, "源站不存在") + + await db.delete(source) + return ApiResponse.ok() + + @router.post("/{source_id}/test", response_model=ApiResponse) async def test_source( source_id: int, @@ -131,7 +182,10 @@ async def test_source( "status": "ok", "total": total, "category_count": len(classes), - "categories": [{"type_id": c.get("type_id"), "type_name": c.get("type_name")} for c in classes], + "categories": [ + {"type_id": c.get("type_id"), "type_name": c.get("type_name")} + for c in classes + ], }) except Exception as e: return ApiResponse.ok({"status": "failed", "error": str(e)}) @@ -150,4 +204,51 @@ async def enable_source( source.is_active = not source.is_active await db.flush() - return ApiResponse.ok({"is_active": source.is_active}) \ No newline at end of file + return ApiResponse.ok({"is_active": source.is_active}) + + +@router.post("/health-check", response_model=ApiResponse) +async def trigger_health_check( + admin: Admin = Depends(require_permission("source:btn:health")), +): + """手动触发所有源站健康检查""" + results = await run_health_checks() + healthy = sum(1 for r in results if r["is_success"]) + return ApiResponse.ok({ + "total": len(results), + "healthy": healthy, + "unhealthy": len(results) - healthy, + "results": results, + }) + + +@router.get("/{source_id}/health-history", response_model=ApiResponse) +async def get_health_history( + source_id: int, + limit: int = Query(20, ge=1, le=100), + admin: Admin = Depends(require_permission("source:list")), + db: AsyncSession = Depends(get_db), +): + """获取指定源站的健康检查历史""" + from app.models.source_health import SourceHealth + + result = await db.execute( + select(SourceHealth) + .where(SourceHealth.source_id == source_id) + .order_by(SourceHealth.checked_at.desc()) + .limit(limit) + ) + records = result.scalars().all() + + items = [ + { + "id": r.id, + "check_type": r.check_type, + "is_success": r.is_success, + "response_time_ms": r.response_time_ms, + "error_message": r.error_message, + "checked_at": str(r.checked_at) if r.checked_at else None, + } + for r in records + ] + return ApiResponse.ok({"list": items, "total": len(items)}) diff --git a/app/routers/admin/sync.py b/app/routers/admin/sync.py index 3a103901b94e9f0f0b10482d7305d3a37cf12299..2e94ea11cd6a8f1bc96bbdcb497777c4f4a741a6 100644 --- a/app/routers/admin/sync.py +++ b/app/routers/admin/sync.py @@ -11,6 +11,7 @@ from app.models.sync_log import SyncLog from app.models.source_site import SourceSite from app.schemas.common import ApiResponse, PaginatedData from app.services.collector import collector +from app.services.sync import get_sync_logs, create_sync_log, finish_sync_log router = APIRouter() @@ -24,28 +25,18 @@ async def list_sync_logs( admin: Admin = Depends(require_permission("sync:list")), db: AsyncSession = Depends(get_db), ): - query = select(SyncLog).order_by(SyncLog.started_at.desc()) - count_query = select(func.count(SyncLog.id)) + logs, total = await get_sync_logs(db, source_id=source_id, status=status, page=page, page_size=page_size) - if source_id: - query = query.where(SyncLog.source_id == source_id) - count_query = count_query.where(SyncLog.source_id == source_id) - if status: - query = query.where(SyncLog.status == status) - count_query = count_query.where(SyncLog.status == status) - - total_result = await db.execute(count_query) - total = total_result.scalar() or 0 - - result = await db.execute( - query.offset((page - 1) * page_size).limit(page_size) - ) - logs = result.scalars().all() + if logs: + source_ids = list({l.source_id for l in logs}) + source_result = await db.execute(select(SourceSite).where(SourceSite.id.in_(source_ids))) + source_map = {s.id: s for s in source_result.scalars().all()} + else: + source_map = {} items = [] for l in logs: - source_result = await db.execute(select(SourceSite).where(SourceSite.id == l.source_id)) - source = source_result.scalar_one_or_none() + source = source_map.get(l.source_id) items.append({ "id": l.id, "source_id": l.source_id, @@ -54,8 +45,8 @@ async def list_sync_logs( "status": l.status, "total_fetched": l.total_fetched, "new_count": l.new_count, - "updated_count": l.updated_count, - "error_msg": l.error_msg, + "update_count": l.update_count, + "error_message": l.error_message, "started_at": str(l.started_at) if l.started_at else None, "finished_at": str(l.finished_at) if l.finished_at else None, }) @@ -83,7 +74,23 @@ async def trigger_sync( if not source.is_active: return ApiResponse.fail(40004, "源站未启用") + from datetime import datetime, timezone + from app.models.sync_log import SyncLog + + 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 + result = await collector.sync_source(source, range_type) + + await finish_sync_log(log_id, result) else: results = await collector.sync_all(range_type) result = results[-1] if results else {} diff --git a/app/routers/admin/system.py b/app/routers/admin/system.py index e763f30f977e643ddb4ab5e8a56db2e221be1d91..b38806a7d72e3d2ca8434bd228dcdc55dbab2def 100644 --- a/app/routers/admin/system.py +++ b/app/routers/admin/system.py @@ -5,6 +5,7 @@ from app.database import get_db from app.dependencies import require_permission from app.config import settings from app.models.admin import Admin +from app.schemas.admin.system import SystemConfigUpdateRequest from app.schemas.common import ApiResponse router = APIRouter() @@ -23,22 +24,20 @@ async def get_config( @router.put("/config", response_model=ApiResponse) async def update_config( - body: dict, + req: SystemConfigUpdateRequest, admin: Admin = Depends(require_permission("system:btn:save")), ): from app.services.scheduler import start_scheduler, stop_scheduler - if "sync_cron_hour" in body: - hour = int(body["sync_cron_hour"]) - if 0 <= hour <= 23: - try: - stop_scheduler() - settings.SYNC_CRON_HOUR = hour - start_scheduler() - except Exception: - pass + if req.sync_cron_hour is not None: + try: + stop_scheduler() + settings.SYNC_CRON_HOUR = req.sync_cron_hour + start_scheduler() + except Exception: + pass - if "access_token_expire_minutes" in body: - settings.ACCESS_TOKEN_EXPIRE_MINUTES = int(body["access_token_expire_minutes"]) + if req.access_token_expire_minutes is not None: + settings.ACCESS_TOKEN_EXPIRE_MINUTES = req.access_token_expire_minutes - return ApiResponse.ok() \ No newline at end of file + return ApiResponse.ok() diff --git a/app/routers/admin/vod.py b/app/routers/admin/vod.py index 26b970bef3e9bd5bd8f2c81a220a7b7cbc8e4a19..f3dc22b40e84e38917c39afbe5963abed5e0ff65 100644 --- a/app/routers/admin/vod.py +++ b/app/routers/admin/vod.py @@ -2,11 +2,13 @@ from fastapi import APIRouter, Depends, Query from sqlalchemy import delete as sa_delete, func, select, update from sqlalchemy.ext.asyncio import AsyncSession +from app.cache import invalidate_vod_cache from app.database import get_db from app.dependencies import require_permission from app.models.admin import Admin from app.models.vod import Vod from app.models.vod_source import VodSource +from app.schemas.admin.vod import VodUpdateRequest from app.schemas.common import ApiResponse, PaginatedData router = APIRouter() @@ -51,18 +53,28 @@ async def list_vods( ) vods = result.scalars().all() + if not vods: + return ApiResponse.ok( + PaginatedData(list=[], total=total, page=page, page_size=page_size).model_dump() + ) + + vod_ids = [v.id for v in vods] + src_count_result = await db.execute( + select(VodSource.vod_id, func.count(VodSource.id)) + .where(VodSource.vod_id.in_(vod_ids)) + .group_by(VodSource.vod_id) + ) + src_count_map = {row[0]: row[1] for row in src_count_result.all()} + items = [] for v in vods: - src_count = await db.execute( - select(func.count(VodSource.id)).where(VodSource.vod_id == v.id) - ) items.append({ "id": v.id, "name": v.name, "cover": v.cover, "category_id": v.category_id, "score": v.score, "year": v.year, "area": v.area, "is_end": v.is_end, "is_hidden": v.is_hidden, "is_recommended": v.is_recommended, "remarks": v.remarks, "view_count": v.view_count, - "source_count": src_count.scalar() or 0, + "source_count": src_count_map.get(v.id, 0), "updated_at": str(v.updated_at) if v.updated_at else None, }) @@ -97,7 +109,7 @@ async def get_vod( @router.put("/{vod_id}", response_model=ApiResponse) async def update_vod( vod_id: int, - body: dict, + req: VodUpdateRequest, admin: Admin = Depends(require_permission("vod:update")), db: AsyncSession = Depends(get_db), ): @@ -106,11 +118,9 @@ async def update_vod( if not vod: return ApiResponse.fail(40401, "影片不存在") - allowed = ["name", "sub_name", "category_id", "score", "douban_id", - "blurb", "content", "is_end", "area", "year", "actor", "director"] - for field in allowed: - if field in body: - setattr(vod, field, body[field]) + for field, value in req.model_dump(exclude_unset=True).items(): + setattr(vod, field, value) + await invalidate_vod_cache(vod_id) return ApiResponse.ok() @@ -122,6 +132,7 @@ async def delete_vod( ): await db.execute(sa_delete(VodSource).where(VodSource.vod_id == vod_id)) await db.execute(sa_delete(Vod).where(Vod.id == vod_id)) + await invalidate_vod_cache(vod_id) return ApiResponse.ok() @@ -136,6 +147,7 @@ async def toggle_hide( if not vod: return ApiResponse.fail(40401, "影片不存在") vod.is_hidden = not vod.is_hidden + await invalidate_vod_cache(vod_id) return ApiResponse.ok({"is_hidden": vod.is_hidden}) @@ -150,4 +162,5 @@ async def toggle_recommend( if not vod: return ApiResponse.fail(40401, "影片不存在") vod.is_recommended = not vod.is_recommended + await invalidate_vod_cache(vod_id) return ApiResponse.ok({"is_recommended": vod.is_recommended}) \ No newline at end of file diff --git a/app/routers/user/auth.py b/app/routers/user/auth.py index ba9180229dd7bd507d012cac8be5e1a64f17835d..26d97334d76bad0972c00b604fe8c4b0ddf20a0a 100644 --- a/app/routers/user/auth.py +++ b/app/routers/user/auth.py @@ -1,11 +1,12 @@ -from datetime import datetime +from datetime import datetime, timezone -from fastapi import APIRouter, Depends +from fastapi import APIRouter, Depends, Request from sqlalchemy import select, or_ from sqlalchemy.ext.asyncio import AsyncSession from app.database import get_db from app.dependencies import get_current_user +from app.limiter import limiter from app.models.user import User from app.models.category import Category from app.schemas.common import ApiResponse @@ -22,7 +23,8 @@ router = APIRouter() @router.post("/register", response_model=ApiResponse) -async def register(req: UserRegisterRequest, db: AsyncSession = Depends(get_db)): +@limiter.limit("5/minute") +async def register(request: Request, req: UserRegisterRequest, db: AsyncSession = Depends(get_db)): result = await db.execute( select(User).where( or_( @@ -50,7 +52,8 @@ async def register(req: UserRegisterRequest, db: AsyncSession = Depends(get_db)) @router.post("/login", response_model=ApiResponse) -async def login(req: UserLoginRequest, db: AsyncSession = Depends(get_db)): +@limiter.limit("10/minute") +async def login(request: Request, req: UserLoginRequest, db: AsyncSession = Depends(get_db)): result = await db.execute(select(User).where(User.username == req.username)) user = result.scalar_one_or_none() if not user or not user.is_active or not verify_password( @@ -58,7 +61,7 @@ async def login(req: UserLoginRequest, db: AsyncSession = Depends(get_db)): ): return ApiResponse.fail(40001, "用户名或密码错误") - user.last_login_at = datetime.now() + user.last_login_at = datetime.now(timezone.utc) await db.flush() token = create_access_token(str(user.id), "user") diff --git a/app/routers/user/category.py b/app/routers/user/category.py index d61bdd0f3b411723a168bea5b46888a0821baa80..c0751ac327d7a0f8b93e3a3da5112d14e5b9d9ae 100644 --- a/app/routers/user/category.py +++ b/app/routers/user/category.py @@ -2,6 +2,8 @@ from fastapi import APIRouter, Depends from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession +from app.cache import cache_get, cache_set, category_tree_key +from app.config import settings from app.database import get_db from app.models.category import Category from app.schemas.common import ApiResponse @@ -12,6 +14,11 @@ router = APIRouter() @router.get("", response_model=ApiResponse) async def list_categories(db: AsyncSession = Depends(get_db)): + cache_key = category_tree_key() + cached = await cache_get(cache_key) + if cached is not None: + return ApiResponse.ok(cached) + result = await db.execute( select(Category) .where(Category.is_active == True) @@ -37,7 +44,9 @@ async def list_categories(db: AsyncSession = Depends(get_db)): for node in roots: _clean_empty_children(node) - return ApiResponse.ok([r.model_dump() for r in roots]) + data = [r.model_dump() for r in roots] + await cache_set(cache_key, data, settings.CACHE_TTL_CATEGORY) + return ApiResponse.ok(data) def _clean_empty_children(node: CategoryUserNode): @@ -46,3 +55,4 @@ def _clean_empty_children(node: CategoryUserNode): _clean_empty_children(child) if len(node.children) == 0: node.children = None + diff --git a/app/routers/user/favorite.py b/app/routers/user/favorite.py index a7aefdfed0dac37eb40e0e3e53425f71c1b714d4..39c8b677b044374e5e94f6da854f61e9aa72f114 100644 --- a/app/routers/user/favorite.py +++ b/app/routers/user/favorite.py @@ -1,5 +1,6 @@ from fastapi import APIRouter, Depends, Query from sqlalchemy import func, select, delete as sa_delete +from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession from app.database import get_db @@ -34,17 +35,23 @@ async def list_favorites( ) favs = result.scalars().all() + if favs: + vod_ids = [f.vod_id for f in favs] + vod_result = await db.execute(select(Vod.id, Vod.name, Vod.cover, Vod.remarks).where(Vod.id.in_(vod_ids))) + vod_map = {row[0]: row for row in vod_result.all()} + else: + vod_map = {} + items = [] for f in favs: - vod_result = await db.execute(select(Vod).where(Vod.id == f.vod_id)) - vod = vod_result.scalar_one_or_none() + vod = vod_map.get(f.vod_id) items.append( FavoriteItem( id=f.id, vod_id=f.vod_id, - vod_name=vod.name if vod else "未知", - vod_cover=vod.cover if vod else None, - vod_remarks=vod.remarks if vod else None, + vod_name=vod[1] if vod else "未知", + vod_cover=vod[2] if vod else None, + vod_remarks=vod[3] if vod else None, created_at=f.created_at, ).model_dump() ) @@ -60,18 +67,17 @@ async def add_favorite( user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): - existing = await db.execute( - select(Favorite).where(Favorite.user_id == user.id, Favorite.vod_id == req.vod_id) - ) - if existing.scalar_one_or_none(): + # 直接插入,由数据库唯一索引 uq_favorite_user_vod 保证幂等性 + # 捕获 IntegrityError 代替应用层的 SELECT 查重,消除竞态条件 + try: + fav = Favorite(user_id=user.id, vod_id=req.vod_id) + db.add(fav) + await db.flush() + return ApiResponse.ok() + except IntegrityError: + await db.rollback() return ApiResponse.fail(40002, "已收藏") - fav = Favorite(user_id=user.id, vod_id=req.vod_id) - db.add(fav) - await db.flush() - - return ApiResponse.ok() - @router.delete("/{vod_id}", response_model=ApiResponse) async def remove_favorite( diff --git a/app/routers/user/history.py b/app/routers/user/history.py index 38a1fbb560b3cbdb6ac467d6c3232dc26ea2ea9b..7aa5913e244ccb91d5b0a1fb7bdf91a60f7fef96 100644 --- a/app/routers/user/history.py +++ b/app/routers/user/history.py @@ -34,16 +34,22 @@ async def list_history( ) histories = result.scalars().all() + if histories: + vod_ids = [h.vod_id for h in histories] + vod_result = await db.execute(select(Vod.id, Vod.name, Vod.cover).where(Vod.id.in_(vod_ids))) + vod_map = {row[0]: row for row in vod_result.all()} + else: + vod_map = {} + items = [] for h in histories: - vod_result = await db.execute(select(Vod).where(Vod.id == h.vod_id)) - vod = vod_result.scalar_one_or_none() + vod = vod_map.get(h.vod_id) items.append( HistoryItem( id=h.id, vod_id=h.vod_id, - vod_name=vod.name if vod else "未知", - vod_cover=vod.cover if vod else None, + vod_name=vod[1] if vod else "未知", + vod_cover=vod[2] if vod else None, source_id=h.source_id, episode=h.episode, play_url=h.play_url, diff --git a/app/routers/user/vod.py b/app/routers/user/vod.py index 76b506d49d563de4960c85b3507b8430d8fe15ad..4a636b1619861d1ad647ece6db4625a22670bffc 100644 --- a/app/routers/user/vod.py +++ b/app/routers/user/vod.py @@ -2,6 +2,11 @@ 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 @@ -9,10 +14,41 @@ 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), @@ -20,6 +56,11 @@ async def list_vods( 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) @@ -37,30 +78,18 @@ async def list_vods( ) vods = result.scalars().all() - items = [] - for v in vods: - cat_name = await _get_category_name(db, v.category_id) - source_count = await _get_source_count(db, v.id) - items.append( - VodUserItem( - id=v.id, - name=v.name, - cover=v.cover, - category_id=v.category_id, - category_name=cat_name, - score=v.score, - year=v.year, - area=v.area, - is_end=v.is_end, - remarks=v.remarks, - source_count=source_count, - updated_at=v.updated_at, - ).model_dump() - ) + 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) - return ApiResponse.ok( - PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump() - ) + 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) @@ -70,6 +99,11 @@ async def search_vods( 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) @@ -87,30 +121,18 @@ async def search_vods( ) vods = result.scalars().all() - items = [] - for v in vods: - cat_name = await _get_category_name(db, v.category_id) - source_count = await _get_source_count(db, v.id) - items.append( - VodUserItem( - id=v.id, - name=v.name, - cover=v.cover, - category_id=v.category_id, - category_name=cat_name, - score=v.score, - year=v.year, - area=v.area, - is_end=v.is_end, - remarks=v.remarks, - source_count=source_count, - updated_at=v.updated_at, - ).model_dump() - ) + 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) - return ApiResponse.ok( - PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump() - ) + 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) @@ -119,10 +141,13 @@ async def recommended_vods( 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 - ) + select(func.count(Vod.id)).where(Vod.is_hidden == False, Vod.is_recommended == True) ) total = count_result.scalar() or 0 @@ -135,30 +160,18 @@ async def recommended_vods( ) vods = result.scalars().all() - items = [] - for v in vods: - cat_name = await _get_category_name(db, v.category_id) - source_count = await _get_source_count(db, v.id) - items.append( - VodUserItem( - id=v.id, - name=v.name, - cover=v.cover, - category_id=v.category_id, - category_name=cat_name, - score=v.score, - year=v.year, - area=v.area, - is_end=v.is_end, - remarks=v.remarks, - source_count=source_count, - updated_at=v.updated_at, - ).model_dump() - ) + 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) - return ApiResponse.ok( - PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump() - ) + 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) @@ -170,6 +183,11 @@ async def latest_vods( ): 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) @@ -185,54 +203,55 @@ async def latest_vods( ) vods = result.scalars().all() - items = [] - for v in vods: - cat_name = await _get_category_name(db, v.category_id) - source_count = await _get_source_count(db, v.id) - items.append( - VodUserItem( - id=v.id, - name=v.name, - cover=v.cover, - category_id=v.category_id, - category_name=cat_name, - score=v.score, - year=v.year, - area=v.area, - is_end=v.is_end, - remarks=v.remarks, - source_count=source_count, - updated_at=v.updated_at, - ).model_dump() - ) + 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) - return ApiResponse.ok( - PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump() - ) + 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(db, 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 db.execute( - Vod.__table__.update().where(Vod.id == vod_id).values(view_count=Vod.view_count + 1) - ) + await increment_view_count(db, vod_id) - cat_name = await _get_category_name(db, vod.category_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_result = await db.execute(select(SourceSite).where(SourceSite.id == vs.source_id)) - site = site_result.scalar_one_or_none() + site = site_map.get(vs.source_id) if not site: continue @@ -285,23 +304,10 @@ async def get_vod(vod_id: int, db: AsyncSession = Depends(get_db)): source_count=source_count, sources=sources, updated_at=vod.updated_at, - ) - - return ApiResponse.ok(detail.model_dump()) + ).model_dump() - -async def _get_category_name(db: AsyncSession, category_id: int) -> str | None: - result = await db.execute(select(Category.name).where(Category.id == category_id)) - return result.scalar_one_or_none() - - -async def _get_source_count(db: AsyncSession, vod_id: int) -> int: - result = await db.execute( - select(func.count(VodSource.id)).where( - VodSource.vod_id == vod_id, VodSource.is_available == True - ) - ) - return result.scalar() or 0 + await cache_set(cache_key, detail, settings.CACHE_TTL_VOD_DETAIL) + return ApiResponse.ok(detail) def _parse_play_url(play_url: str) -> list[dict]: diff --git a/app/schemas/admin/admin_mgmt.py b/app/schemas/admin/admin_mgmt.py index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..43460d4a7e7a091c53713d6628a647ba2b239801 100644 --- a/app/schemas/admin/admin_mgmt.py +++ b/app/schemas/admin/admin_mgmt.py @@ -0,0 +1,20 @@ +from pydantic import BaseModel, Field + + +class AdminCreateRequest(BaseModel): + username: str = Field(..., min_length=3, max_length=50) + password: str = Field(..., min_length=6, max_length=100) + nickname: str | None = Field(None, max_length=50) + + +class AdminUpdateRequest(BaseModel): + nickname: str | None = Field(None, max_length=50) + is_active: bool | None = None + + +class AdminResetPasswordRequest(BaseModel): + password: str = Field(..., min_length=6, max_length=100) + + +class AdminAssignRolesRequest(BaseModel): + role_ids: list[int] = Field(default_factory=list) diff --git a/app/schemas/admin/category.py b/app/schemas/admin/category.py index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..980293050a68f91230b2e3d4409598f5367d070b 100644 --- a/app/schemas/admin/category.py +++ b/app/schemas/admin/category.py @@ -0,0 +1,18 @@ +from pydantic import BaseModel, Field + + +class CategoryUpdateRequest(BaseModel): + name: str | None = Field(None, min_length=1, max_length=50) + sort_order: int | None = Field(None, ge=0) + is_active: bool | None = None + parent_id: int | None = None + + +class CategoryMappingItem(BaseModel): + category_id: int + source_type_id: int + + +class CategoryMappingUpdateRequest(BaseModel): + source_id: int + mappings: list[CategoryMappingItem] = Field(..., min_length=1) diff --git a/app/schemas/admin/role_mgmt.py b/app/schemas/admin/role_mgmt.py index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..3666c9aca2554784f2e9ab4a3000bc066754fdbc 100644 --- a/app/schemas/admin/role_mgmt.py +++ b/app/schemas/admin/role_mgmt.py @@ -0,0 +1,17 @@ +from pydantic import BaseModel, Field + + +class RoleCreateRequest(BaseModel): + name: str = Field(..., min_length=1, max_length=50) + code: str = Field(..., min_length=1, max_length=50, pattern=r"^[a-zA-Z0-9_]+$") + description: str | None = Field(None, max_length=200) + + +class RoleUpdateRequest(BaseModel): + name: str | None = Field(None, min_length=1, max_length=50) + description: str | None = Field(None, max_length=200) + status: int | None = Field(None, ge=0, le=1) + + +class RoleAssignPermissionsRequest(BaseModel): + permission_ids: list[int] = Field(default_factory=list) diff --git a/app/schemas/admin/source.py b/app/schemas/admin/source.py index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..ab221d487b8c9644acb02de91a2c99e7ffd6e632 100644 --- a/app/schemas/admin/source.py +++ b/app/schemas/admin/source.py @@ -0,0 +1,26 @@ +from pydantic import BaseModel, Field, HttpUrl + + +class SourceCreateRequest(BaseModel): + name: str = Field(..., min_length=1, max_length=50) + code: str = Field(..., min_length=1, max_length=30, pattern=r"^[a-zA-Z0-9_-]+$") + base_url: str = Field(..., min_length=1, max_length=500) + site_url: str | None = Field(None, max_length=500) + play_from_m3u8: str | None = Field(None, max_length=30) + play_from_yun: str | None = Field(None, max_length=30) + parse_url: str | None = Field(None, max_length=500) + sync_interval: int = Field(60, ge=1, le=10080) + sort_order: int = Field(0, ge=0) + remark: str | None = Field(None, max_length=200) + + +class SourceUpdateRequest(BaseModel): + name: str | None = Field(None, min_length=1, max_length=50) + base_url: str | None = Field(None, min_length=1, max_length=500) + site_url: str | None = Field(None, max_length=500) + play_from_m3u8: str | None = Field(None, max_length=30) + play_from_yun: str | None = Field(None, max_length=30) + parse_url: str | None = Field(None, max_length=500) + sync_interval: int | None = Field(None, ge=1, le=10080) + sort_order: int | None = Field(None, ge=0) + remark: str | None = Field(None, max_length=200) diff --git a/app/schemas/admin/system.py b/app/schemas/admin/system.py index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..18ef4d85b48cbaf92239089e96d908835f5fd595 100644 --- a/app/schemas/admin/system.py +++ b/app/schemas/admin/system.py @@ -0,0 +1,6 @@ +from pydantic import BaseModel, Field + + +class SystemConfigUpdateRequest(BaseModel): + sync_cron_hour: int | None = Field(None, ge=0, le=23) + access_token_expire_minutes: int | None = Field(None, ge=1, le=43200) diff --git a/app/schemas/admin/vod.py b/app/schemas/admin/vod.py index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..c6e2cd90a542064b3312994f64a944b5c24e1476 100644 --- a/app/schemas/admin/vod.py +++ b/app/schemas/admin/vod.py @@ -0,0 +1,16 @@ +from pydantic import BaseModel, Field + + +class VodUpdateRequest(BaseModel): + name: str | None = Field(None, min_length=1, max_length=200) + sub_name: str | None = Field(None, max_length=500) + category_id: int | None = None + score: float | None = Field(None, ge=0, le=10) + douban_id: int | None = None + blurb: str | None = None + content: str | None = None + is_end: bool | None = None + area: str | None = Field(None, max_length=50) + year: str | None = Field(None, max_length=10) + actor: str | None = Field(None, max_length=2000) + director: str | None = Field(None, max_length=200) diff --git a/app/services/auth_user.py b/app/services/auth_user.py index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..c92d6a92c7205ad5bf41f27ee019492413f8911c 100644 --- a/app/services/auth_user.py +++ b/app/services/auth_user.py @@ -0,0 +1,28 @@ +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models.user import User +from app.utils.auth import hash_password, verify_password, create_access_token + + +async def get_user_by_username(db: AsyncSession, username: str) -> User | None: + result = await db.execute(select(User).where(User.username == username)) + return result.scalar_one_or_none() + + +async def get_user_by_id(db: AsyncSession, user_id: int) -> User | None: + result = await db.execute(select(User).where(User.id == user_id)) + return result.scalar_one_or_none() + + +async def authenticate_user(db: AsyncSession, username: str, password: str) -> User | None: + user = await get_user_by_username(db, username) + if not user or not user.is_active: + return None + if not verify_password(password, user.password_hash): + return None + return user + + +def generate_user_token(user: User) -> str: + return create_access_token(str(user.id), "user") diff --git a/app/services/category.py b/app/services/category.py index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..7c109b1e522dd4da0ef94173c963058f4ebec7dd 100644 --- a/app/services/category.py +++ b/app/services/category.py @@ -0,0 +1,45 @@ +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models.category import Category, CategoryMapping + + +async def get_category_tree(db: AsyncSession, active_only: bool = True) -> list[dict]: + query = select(Category).order_by(Category.sort_order) + if active_only: + query = query.where(Category.is_active == True) + result = await db.execute(query) + all_cats = result.scalars().all() + + cat_map: dict[int, dict] = {} + roots: list[dict] = [] + + for c in all_cats: + node = { + "id": c.id, + "name": c.name, + "parent_id": c.parent_id, + "sort_order": c.sort_order, + "children": [], + } + cat_map[c.id] = node + + for c in all_cats: + node = cat_map[c.id] + if c.parent_id and c.parent_id in cat_map: + cat_map[c.parent_id]["children"].append(node) + elif not c.parent_id: + roots.append(node) + + return roots + + +async def get_source_mappings(db: AsyncSession, source_id: int) -> dict[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 + } diff --git a/app/services/collector.py b/app/services/collector.py index 7ba1004efc4c9a8bbe8e7c334c1d801149fc8ab7..90975132e873b3360038455d6e3ccabc558ac61d 100644 --- a/app/services/collector.py +++ b/app/services/collector.py @@ -175,8 +175,8 @@ class Collector: status=r["status"], total_fetched=r["total_fetched"], new_count=r["new_vods"], - updated_count=r["updated_vods"], - error_msg=r["error"], + update_count=r["updated_vods"], + error_message=r["error"], finished_at=datetime.now(timezone.utc), ) ) @@ -229,24 +229,42 @@ class Collector: if not name: return 0, 0 - existing = await db.execute( - select(Vod).where(Vod.name == name).limit(1) - ) - vod = existing.scalar_one_or_none() + 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 - douban_id = vod_data.get("vod_douban_id") - if douban_id and str(douban_id).isdigit(): - douban_id = int(douban_id) - else: - douban_id = vod.douban_id + + if douban_id: + vod.douban_id = douban_id vod.cover = cover vod.score = score - vod.douban_id = douban_id 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 @@ -254,18 +272,13 @@ class Collector: 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 = vod_data.get("vod_year") or vod.year + 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 - 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 vod = Vod( name=name, @@ -277,7 +290,7 @@ class Collector: director=vod_data.get("vod_director"), area=vod_data.get("vod_area"), lang=vod_data.get("vod_lang"), - year=vod_data.get("vod_year"), + year=year, duration=vod_data.get("vod_duration"), score=score, douban_id=douban_id, @@ -296,8 +309,30 @@ class Collector: if not name: return 0, 0 - vod_result = await db.execute(select(Vod).where(Vod.name == name).limit(1)) - vod = vod_result.scalar_one_or_none() + 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 diff --git a/app/services/health.py b/app/services/health.py index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..f60648d30ae605a5fd95dd7b68f5664b04800e36 100644 --- a/app/services/health.py +++ b/app/services/health.py @@ -0,0 +1,128 @@ +import asyncio +import logging +import time +from datetime import datetime, timezone + +import httpx +from sqlalchemy import select, update + +from app.database import async_session +from app.models.source_site import SourceSite +from app.models.source_health import SourceHealth + +logger = logging.getLogger("health") + + +async def check_source(source: SourceSite) -> dict: + """对单个源站发起健康检查,返回检查结果""" + start = time.monotonic() + error_msg = None + is_success = False + + try: + async with httpx.AsyncClient(timeout=10, follow_redirects=True) as client: + resp = await client.get(source.base_url, params={"ac": "list", "pg": "1"}) + resp.raise_for_status() + data = resp.json() + # 验证返回格式是否符合预期 + if "list" in data or "class" in data or "total" in data: + is_success = True + else: + error_msg = "响应格式不符合预期" + except httpx.TimeoutException: + error_msg = "连接超时" + except httpx.HTTPStatusError as e: + error_msg = f"HTTP {e.response.status_code}" + except Exception as e: + error_msg = str(e)[:200] + + response_time_ms = int((time.monotonic() - start) * 1000) + + return { + "source_id": source.id, + "is_success": is_success, + "response_time_ms": response_time_ms, + "error_message": error_msg, + } + + +async def run_health_checks() -> list[dict]: + """对所有启用的源站执行健康检查""" + 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() + + if not sources: + return [] + + # 并发检查,最多 5 个并发 + semaphore = asyncio.Semaphore(5) + + async def check_with_semaphore(source): + async with semaphore: + return await check_source(source) + + results = await asyncio.gather(*[check_with_semaphore(s) for s in sources]) + + # 批量写入检查结果 + async with async_session() as db: + now = datetime.now(timezone.utc) + for r in results: + record = SourceHealth( + source_id=r["source_id"], + check_type="api", + is_success=r["is_success"], + response_time_ms=r["response_time_ms"], + error_message=r["error_message"], + checked_at=now, + ) + db.add(record) + + # 同步更新 source_site 的最后健康状态 + await db.execute( + update(SourceSite) + .where(SourceSite.id == r["source_id"]) + .values(last_sync_status="healthy" if r["is_success"] else "unhealthy") + ) + + await db.commit() + + logger.info(f"Health check completed: {len(results)} sources checked, " + f"{sum(1 for r in results if r['is_success'])} healthy") + return list(results) + + +async def get_latest_health(db, source_ids: list[int] | None = None) -> dict[int, dict]: + """获取每个源站最新的健康检查记录""" + from sqlalchemy import func + + # 子查询:每个 source_id 的最新 checked_at + subq = ( + select(SourceHealth.source_id, func.max(SourceHealth.checked_at).label("latest")) + .group_by(SourceHealth.source_id) + .subquery() + ) + + query = ( + select(SourceHealth) + .join(subq, (SourceHealth.source_id == subq.c.source_id) & + (SourceHealth.checked_at == subq.c.latest)) + ) + + if source_ids: + query = query.where(SourceHealth.source_id.in_(source_ids)) + + result = await db.execute(query) + records = result.scalars().all() + + return { + r.source_id: { + "is_success": r.is_success, + "response_time_ms": r.response_time_ms, + "error_message": r.error_message, + "checked_at": str(r.checked_at) if r.checked_at else None, + } + for r in records + } diff --git a/app/services/scheduler.py b/app/services/scheduler.py index aa62783145245888e08edd10715bda47987be1f7..2cec2668c1a5a04f1adcd107d22c9bd70e30ad80 100644 --- a/app/services/scheduler.py +++ b/app/services/scheduler.py @@ -2,7 +2,9 @@ import logging from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.triggers.cron import CronTrigger +from apscheduler.triggers.interval import IntervalTrigger +from app.config import settings from app.services.collector import collector logger = logging.getLogger("scheduler") @@ -11,7 +13,12 @@ scheduler = AsyncIOScheduler() def start_scheduler(): - sync_hour = 1 + sync_hour = settings.SYNC_CRON_HOUR + + # 移除已存在的同名 job,避免重启时 ConflictingIdError + for job_id in ("sync_daily", "sync_weekly", "sync_monthly", "health_check"): + if scheduler.get_job(job_id): + scheduler.remove_job(job_id) scheduler.add_job( collector.sync_all, @@ -40,6 +47,16 @@ def start_scheduler(): misfire_grace_time=14400, ) + # 源站健康检查:每 30 分钟执行一次 + from app.services.health import run_health_checks + scheduler.add_job( + run_health_checks, + trigger=IntervalTrigger(minutes=30), + id="health_check", + name="源站健康检查", + misfire_grace_time=300, + ) + scheduler.start() logger.info(f"Scheduler started with sync_hour={sync_hour}") diff --git a/app/services/sync.py b/app/services/sync.py index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..149938f96f2a01a6002eaec3c73099b135f9f9d2 100644 --- a/app/services/sync.py +++ b/app/services/sync.py @@ -0,0 +1,63 @@ +from datetime import datetime, timezone + +from sqlalchemy import select, update +from sqlalchemy.ext.asyncio import AsyncSession + +from app.database import async_session +from app.models.sync_log import SyncLog +from app.models.source_site import SourceSite + + +async def create_sync_log(db: AsyncSession, source_id: int, range_type: str) -> int: + log = SyncLog( + source_id=source_id, + range_type=range_type, + status="running", + started_at=datetime.now(timezone.utc), + ) + db.add(log) + await db.flush() + return log.id + + +async def finish_sync_log(log_id: int, result: dict) -> None: + async with async_session() as db: + await db.execute( + update(SyncLog) + .where(SyncLog.id == log_id) + .values( + status=result["status"], + total_fetched=result.get("total_fetched", 0), + new_count=result.get("new_vods", 0), + update_count=result.get("updated_vods", 0), + error_message=result.get("error"), + finished_at=datetime.now(timezone.utc), + ) + ) + await db.commit() + + +async def get_sync_logs( + db: AsyncSession, + source_id: int | None = None, + status: str | None = None, + page: int = 1, + page_size: int = 20, +) -> tuple[list[SyncLog], int]: + from sqlalchemy import func + query = select(SyncLog).order_by(SyncLog.started_at.desc()) + count_query = select(func.count(SyncLog.id)) + + if source_id: + query = query.where(SyncLog.source_id == source_id) + count_query = count_query.where(SyncLog.source_id == source_id) + if status: + query = query.where(SyncLog.status == status) + count_query = count_query.where(SyncLog.status == status) + + total_result = await db.execute(count_query) + total = total_result.scalar() or 0 + + result = await db.execute(query.offset((page - 1) * page_size).limit(page_size)) + logs = result.scalars().all() + return list(logs), total diff --git a/app/services/vod.py b/app/services/vod.py index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..cb9e66b28205b4b00510b586f443112e0c57c569 100644 --- a/app/services/vod.py +++ b/app/services/vod.py @@ -0,0 +1,40 @@ +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models.category import Category +from app.models.vod import Vod +from app.models.vod_source import VodSource + + +async def get_vod_by_id(db: AsyncSession, vod_id: int, hidden_ok: bool = False) -> Vod | None: + query = select(Vod).where(Vod.id == vod_id) + if not hidden_ok: + query = query.where(Vod.is_hidden == False) + result = await db.execute(query) + return result.scalar_one_or_none() + + +async def batch_get_category_names(db: AsyncSession, category_ids: list[int]) -> dict[int, str]: + if not category_ids: + return {} + result = await db.execute( + select(Category.id, Category.name).where(Category.id.in_(category_ids)) + ) + return {row[0]: row[1] for row in result.all()} + + +async def batch_get_source_counts(db: AsyncSession, vod_ids: list[int]) -> dict[int, int]: + if not vod_ids: + return {} + result = await db.execute( + select(VodSource.vod_id, func.count(VodSource.id)) + .where(VodSource.vod_id.in_(vod_ids), VodSource.is_available == True) + .group_by(VodSource.vod_id) + ) + return {row[0]: row[1] for row in result.all()} + + +async def increment_view_count(db: AsyncSession, vod_id: int) -> None: + await db.execute( + Vod.__table__.update().where(Vod.id == vod_id).values(view_count=Vod.view_count + 1) + ) diff --git a/app/utils/auth.py b/app/utils/auth.py index 3bbf7dcefed1555d8ea1e9fcc651a734c569349c..b60a24ed0c3ba12b8873bfea8edd98d44ffbbaa7 100644 --- a/app/utils/auth.py +++ b/app/utils/auth.py @@ -1,7 +1,7 @@ from datetime import datetime, timedelta, timezone import bcrypt -from jose import jwt +import jwt from app.config import settings @@ -19,4 +19,9 @@ def create_access_token(subject: str, token_type: str = "admin", expires_delta: expires_delta = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) expire = datetime.now(timezone.utc) + expires_delta to_encode = {"sub": subject, "type": token_type, "exp": expire} - return jwt.encode(to_encode, settings.SECRET_KEY, algorithm="HS256") \ No newline at end of file + return jwt.encode(to_encode, settings.SECRET_KEY, algorithm="HS256") + + +def decode_access_token(token: str) -> dict: + """解码 JWT,失败抛出 jwt.PyJWTError""" + return jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"]) \ No newline at end of file diff --git "a/docs/\350\265\204\346\272\220\347\253\231.txt" "b/docs/\350\265\204\346\272\220\347\253\231.txt" new file mode 100644 index 0000000000000000000000000000000000000000..6211f28e3609c9804fb70ecf713ebcacdff44015 --- /dev/null +++ "b/docs/\350\265\204\346\272\220\347\253\231.txt" @@ -0,0 +1,23 @@ +m3u8 切片资源专区 +全部m3u8直链资源,可以用dplayer、ckplayer、xgplayer等播放器播放 + +2022-2026年推荐接口 +极速资源站 https://jszy333.com/ +豆瓣资源站 https://dbzy.tv + +索尼资源[速度不错, 禁国外] https://suonizy.net/ + +OK资源 [速度还行, 禁国外, 域名换几次了] https://okzyw.cc/ + +红牛资源站【速度一般, 不过是老牌资源】https://www.hongniuzy.com/ + +无尽资源站【速度一般】http://www.wujinzy.net/ + +光速资源站【速度一般】https://guangsuzy.com/ +U酷资源站【最新片源,商业CDN】https://ukuzy0.com/ +新浪资源站【HTTPS资源,m3u8直链】https://www.xinlangzy.com/ +快车资源站【HTTPS资源,m3u8直链】http://kuaichezy.com/ +金鹰资源站【国内CDN,秒拖秒播】http://jinyingzy.com/ +淘片资源站【HTTPS资源,m3u8直链】https://www.taopianzy.com/ +卧龙资源站【HTTPS资源,跑马灯广告】http://wolongzyw.com/ +CK资源站【HTTPS资源,跑马灯广告】http://www.ckzy1.com/ \ No newline at end of file diff --git "a/docs/\350\265\204\346\272\220\347\253\231API\346\216\245\345\217\243\346\226\207\346\241\243.md" "b/docs/\350\265\204\346\272\220\347\253\231API\346\216\245\345\217\243\346\226\207\346\241\243.md" new file mode 100644 index 0000000000000000000000000000000000000000..e7bc22f18d80cea1b14d9ff364fa53578bf8e33a --- /dev/null +++ "b/docs/\350\265\204\346\272\220\347\253\231API\346\216\245\345\217\243\346\226\207\346\241\243.md" @@ -0,0 +1,534 @@ +# 影视资源站 API 接口文档 + +> 更新时间:2026-05-12 +> 所有资源站均基于苹果CMS开放API标准,接口规范基本一致 + +--- + +## 目录 + +1. [通用API规范](#通用api规范) +2. [可用资源站一览](#可用资源站一览) +3. [各资源站详细接口](#各资源站详细接口) +4. [播放说明](#播放说明) + +--- + +## 通用API规范 + +所有资源站均遵循苹果CMS采集API标准,支持以下通用参数: + +### 请求参数 + +| 参数 | 类型 | 必填 | 说明 | 示例 | +|---|---|---|---|---| +| `ac` | string | 否 | 操作模式(见下表),为空=列表标准模式 | `ac=detail` | +| `ids` | string | 否 | 影片ID,多个用逗号隔开 | `ids=110602` | +| `t` | int | 否 | 按分类ID筛选 | `t=2` | +| `h` | int | 否 | 最近多少小时内更新的数据 | `h=24` | +| `pg` | int | 否 | 页码,默认1 | `pg=2` | +| `wd` | string | 否 | 搜索关键词(like模糊匹配) | `wd=庆余年` | +| `limit` | int | 否 | 每页条数,默认20 | `limit=50` | + +### ac 操作模式 + +| ac值 | 说明 | 返回字段 | +|---|---|---| +| (空) | 标准列表模式 | 基础字段 + class分类 | +| `list` | 列表模式 | 仅基础字段(id/名称/分类/更新时间/备注/播放来源) | +| `videolist` | 视频列表模式 | 基础字段 + 更多详情(图片/演员/地区/年份等,不含播放地址) | +| `detail` | 详情模式 | **全部字段**,含播放地址、简介、评分等 | + +### URL路径指定来源和格式 + +``` +/api.php/provide/vod/from/{来源标识}/at/{格式}/ +``` + +- **来源标识**:各站不同,如 `jinyingm3u8`、`hnm3u8`、`snm3u8` 等 +- **格式**:`xml`、`json`/`josn`(部分站拼写为josn)、`xmlsea`(海洋CMS专用) + +### 通用返回结构(JSON) + +```json +{ + "code": 1, + "msg": "数据列表", + "page": 1, + "pagecount": 5178, + "limit": "20", + "total": 103547, + "list": [ ... ], + "class": [ ... ] +} +``` + +### 通用字段说明 + +| 字段 | 说明 | 备注 | +|---|---|---| +| `vod_id` | 影片ID | 唯一标识 | +| `vod_name` | 影片名 | | +| `type_id` | 分类ID | | +| `type_id_1` | 一级分类ID | | +| `type_name` | 分类名称 | | +| `vod_en` | 英文拼音 | | +| `vod_pic` | 封面图 | CDN地址 | +| `vod_actor` | 演员 | 逗号分隔 | +| `vod_director` | 导演 | | +| `vod_area` | 地区 | | +| `vod_lang` | 语言 | | +| `vod_year` | 年份 | | +| `vod_remarks` | 备注 | 如"第39集"、"全集完结" | +| `vod_score` | 评分 | | +| `vod_content` | 简介 | HTML内容 | +| `vod_duration` | 时长 | 如"100分钟" | +| `vod_douban_id` | 豆瓣ID | 部分站有 | +| `vod_play_from` | 播放来源 | 多个用 `$$$` 分隔 | +| `vod_play_url` | 播放地址 | 多个来源用 `$$$` 分隔,集数用 `#` 分隔 | +| `vod_time` | 更新时间 | | + +### 播放地址格式 + +`vod_play_from` 和 `vod_play_url` 用 `$$$` 一一对应: + +``` +vod_play_from: "jinyingyun$$$jinyingm3u8" +vod_play_url: "全集完结$https://xxx/play/abc$$$全集完结$https://xxx/play/abc/index.m3u8" +``` + +单个来源内,多集用 `#` 分隔,每集格式为 `集名$播放地址`: + +``` +第01集$https://xxx/01/index.m3u8#第02集$https://xxx/02/index.m3u8 +``` + +--- + +## 可用资源站一览 + +| 站点 | 官网 | API基础地址 | 状态 | 资源总量 | 播放来源标识 | 速度 | +|---|---|---|---|---|---|---| +| 极速资源 | jszy333.com | `https://jszyapi.com/api.php/provide/vod/` | 可用 | 101,840 | `jsm3u8` | 快 | +| 豆瓣资源 | dbzy.tv | `https://dbzy.tv/api.php/provide/vod/` | 可用 | 126,890 | `dbm3u8` | 快 | +| 索尼资源 | suonizy.net | `https://suoniapi.com/api.php/provide/vod/` | 可用 | 135,704 | `snm3u8` | 快,禁国外 | +| OK资源 | okzyw.cc | `https://okzyw.cc/api.php/provide/vod/` | 可用 | - | `okm3u8` | 行,禁国外 | +| 红牛资源 | hongniuzy.com | `https://www.hongniuzy2.com/api.php/provide/vod/` | 可用 | 103,249 | `hnm3u8`、`hnyun` | 一般 | +| 金鹰资源 | jinyingzy.com | `https://jyzyapi.com/provide/vod/` | 可用 | 103,547 | `jinyingm3u8`、`jinyingyun` | 快 | +| 新浪资源 | xinlangzy.com | `https://www.xinlangzy.com/api.php/provide/vod/` | 可用 | - | `xlm3u8`、`xlyun` | - | +| 快车资源 | kuaichezy.com | `http://kuaichezy.com/api.php/provide/vod/` | 可用 | 119,079 | `kcm3u8` | - | +| CK资源 | ckzy1.com | `http://www.ckzy1.com/api.php/provide/vod/` | 可用 | - | `ckm3u8` | - | +| 卧龙资源 | wolongzyw.com | `http://wolongzyw.com/api.php/provide/vod/` | 不可用 | - | - | 网站可访问但API失效 | +| 光速资源 | guangsuzy.com | - | 不可用 | - | - | 网站及API均无法访问 | +| U酷资源 | ukuzy0.com | - | 不可用 | - | - | API返回closed/空 | +| 无尽资源 | wujinzy.net | - | 不可用 | - | - | 404 | +| 淘片资源 | taopianzy.com | - | 不可用 | - | - | 404 | + +--- + +## 各资源站详细接口 + +### 1. 极速资源站 + +- **官网**:https://jszy333.com/ +- **API基础**:`https://jszyapi.com/api.php/provide/vod/` +- **播放来源**:`jsm3u8` +- **总资源**:101,840 +- **推荐接口**: + +| 接口 | 地址 | +|---|---| +| 标准列表 | `https://jszyapi.com/api.php/provide/vod/` | +| 视频列表 | `https://jszyapi.com/api.php/provide/vod/?ac=videolist` | +| 详情模式 | `https://jszyapi.com/api.php/provide/vod/?ac=detail` | +| XML格式 | `https://jszyapi.com/api.php/provide/vod/at/xml/` | + +### 2. 豆瓣资源站 + +- **官网**:https://dbzy.tv +- **API基础**:`https://dbzy.tv/api.php/provide/vod/` +- **播放来源**:`dbm3u8` +- **总资源**:126,890 +- **图片CDN**:`dbzy5.com` +- **推荐接口**: + +| 接口 | 地址 | +|---|---| +| 视频列表 | `https://dbzy.tv/api.php/provide/vod/?ac=videolist` | +| 详情模式 | `https://dbzy.tv/api.php/provide/vod/?ac=detail` | + +### 3. 索尼资源站 + +- **官网**:https://suonizy.net/ (备用:suonizy.cc) +- **API基础**:`https://suoniapi.com/api.php/provide/vod/` +- **播放来源**:`snm3u8` +- **总资源**:135,704 +- **图片CDN**:`snzypic.vip` +- **M3U8解析**:`https://dxfbk.com/?url=` +- **推荐接口**: + +| 接口 | 地址 | +|---|---| +| 标准列表 | `https://suoniapi.com/api.php/provide/vod/` | +| M3U8 XML | `https://suoniapi.com/api.php/provide/vod/from/snm3u8/at/xml/` | +| JSON | `https://suoniapi.com/api.php/provide/vod/?ac=list` | +| 详情模式 | `https://suoniapi.com/api.php/provide/vod/?ac=detail` | + +### 4. OK资源站 + +- **官网**:https://okzyw.cc/ +- **API基础**:`https://okzyw.cc/api.php/provide/vod/` +- **播放来源**:`okm3u8` +- **注意**:域名换过几次,禁国外访问 +- **推荐接口**: + +| 接口 | 地址 | +|---|---| +| 标准列表 | `https://okzyw.cc/api.php/provide/vod/` | +| 详情模式 | `https://okzyw.cc/api.php/provide/vod/?ac=detail` | +| XML | `https://okzyw.cc/api.php/provide/vod/at/xml/` | + +### 5. 红牛资源站 + +- **官网**:https://www.hongniuzy.com/ +- **API基础**:`https://www.hongniuzy2.com/api.php/provide/vod/`(注意:API域名带2) +- **备用API**:`https://www.hongniuzy3.com/api.php/provide/vod/` +- **播放来源**:`hnm3u8`、`hnyun` +- **总资源**:103,249 +- **M3U8解析**:`https://www.hnjiexi.com/m3u8/?url=` +- **备用解析**:`https://www.hongniujiexi.com/m3u8/?url=` +- **备用域名**:hongniuziyuan.com/net/tv、hongniuzy.com/net/tv +- **推荐接口**: + +| 接口 | 地址 | +|---|---| +| XML综合 | `https://www.hongniuzy2.com/api.php/provide/vod/at/xml/` | +| JSON综合 | `https://www.hongniuzy2.com/api.php/provide/vod/at/josn/` | +| M3U8 XML | `https://www.hongniuzy2.com/api.php/provide/vod/from/hnm3u8/at/xml/` | +| M3U8 JSON | `https://www.hongniuzy2.com/api.php/provide/vod/from/hnm3u8/at/josn/` | +| 云播 XML | `https://www.hongniuzy2.com/api.php/provide/vod/from/hnyun/at/xml/` | +| 海洋CMS | `https://www.hongniuzy2.com/api.php/provide/vod/at/xmlsea/` | + +### 6. 金鹰资源站 + +- **官网**:https://jinyingzy.com/ (备用:jinyingzy.net) +- **API基础**:`https://jyzyapi.com/provide/vod/`(注意:不含api.php) +- **播放来源**:`jinyingm3u8`、`jinyingyun` +- **总资源**:103,547 +- **M3U8解析**:`https://hd.iapijy.com/play?url=` +- **备用域名**:jinyingziyuan.com、jyzy1/2/3.com +- **推荐接口**: + +| 接口 | 地址 | +|---|---| +| 标准采集 | `https://jyzyapi.com/provide/vod` | +| M3U8 XML | `https://jyzyapi.com/provide/vod/from/jinyingm3u8/at/xml/` | +| M3U8 JSON | `https://jyzyapi.com/provide/vod/from/jinyingm3u8/at/json` | +| 云播 XML | `https://jyzyapi.com/provide/vod/from/jinyingyun/at/xml/` | +| 云播 JSON | `https://jyzyapi.com/provide/vod/from/jinyingyun/at/json` | +| 海洋CMS | `https://jyzyapi.com/provide/vod/at/xmlsea/` | + +### 7. 新浪资源站 + +- **官网**:https://www.xinlangzy.com/ +- **API基础**:`https://www.xinlangzy.com/api.php/provide/vod/` +- **播放来源**:`xlm3u8`、`xlyun` +- **特点**:HTTPS资源,m3u8直链 +- **推荐接口**: + +| 接口 | 地址 | +|---|---| +| 标准列表 | `https://www.xinlangzy.com/api.php/provide/vod/` | +| 详情模式 | `https://www.xinlangzy.com/api.php/provide/vod/?ac=detail` | + +### 8. 快车资源站 + +- **官网**:http://kuaichezy.com/ +- **API基础**:`http://kuaichezy.com/api.php/provide/vod/` +- **播放来源**:`kcm3u8` +- **总资源**:119,079 +- **图片CDN**:`kuaichezyimg.com` +- **注意**:仅HTTP +- **推荐接口**: + +| 接口 | 地址 | +|---|---| +| 标准列表 | `http://kuaichezy.com/api.php/provide/vod/` | +| 详情模式 | `http://kuaichezy.com/api.php/provide/vod/?ac=detail` | + +### 9. CK资源站 + +- **官网**:http://www.ckzy1.com/ +- **API基础**:`http://www.ckzy1.com/api.php/provide/vod/` +- **播放来源**:`ckm3u8` +- **图片CDN**:`ckzyjpg.top` +- **注意**:HTTPS资源,有跑马灯广告,仅HTTP +- **推荐接口**: + +| 接口 | 地址 | +|---|---| +| 标准列表 | `http://www.ckzy1.com/api.php/provide/vod/` | +| 详情模式 | `http://www.ckzy1.com/api.php/provide/vod/?ac=detail` | + +--- + +## 不可用资源站 + +| 站点 | 官网 | 问题说明 | +|---|---|---| +| 卧龙资源 | wolongzyw.com | 网站可访问,API返回HTML页面而非数据,接口已失效 | +| 光速资源 | guangsuzy.com | 网站及API均无法访问 | +| U酷资源 | ukuzy0.com | API返回closed/空响应,疑似已关闭 | +| 无尽资源 | wujinzy.net | 返回404 | +| 淘片资源 | taopianzy.com | 返回404,API域名已失效 | + +--- + +## 播放说明 + +### 三种播放地址类型 + +通过API `ac=detail` 获取到的 `vod_play_url` 中,存在三种不同类型的播放地址: + +#### 类型一:M3U8直链 + +以 `/index.m3u8` 结尾的HLS切片地址,可直接用HLS播放器播放。 + +``` +https://vv.jisuzyv.com/play/bo2R17Aa/index.m3u8 +https://hd.ijycnd.com/play/eERR6RNa/index.m3u8 +https://v3.kuaichezym3u8.com/yyv3/202605/11/tVzZj7hcR927/video/index.m3u8 +https://ckzy3.com/20260428/zQEHfw8I/index.m3u8 +https://vodcnd13.oag7h.com/20260511/jjotR1L6/index.m3u8 +``` + +实测m3u8文件内容为HLS主播放列表(Master Playlist),包含多码率流: + +``` +#EXTM3U +#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=4096000,RESOLUTION=1920x1080 +/play/hls/eERR6RNa/index.m3u8 +``` + +或直接包含分片列表: + +``` +#EXTM3U +#EXT-X-STREAM-INF:BANDWIDTH=3902000,RESOLUTION=1920x1080 +/20260511/jjotR1L6/3902kb/hls/index.m3u8 +``` + +**M3U8直链可直接被 HLS.js / DPlayer 等播放器消费,无需解析接口。** + +#### 类型二:云播短链 + +不带 `/index.m3u8` 后缀的短链地址,访问后返回一个完整的HTML播放页面(含DPlayer + HLS.js)。 + +``` +https://hd.ijycnd.com/play/eERR6RNa +https://hn.bfvvs.com/play/b2kxBVWd +https://vv.jisuzyv.com/play/bo2R17Aa +https://vodcnd13.oag7h.com/share/AdBKIiZCCd +``` + +访问云播短链返回的HTML中,内嵌了播放器代码: + +```html +
+ +