feat: complete core feature improvements
Browse files- Auth: replace python-jose with PyJWT, eliminate utcnow() deprecation warnings
- Auth: fix security bug - admin token now validates 'type' field
- DB: add Alembic migration (initial_schema) with 15 tables + 14 indexes
- DB: migration updated_at columns add MySQL ON UPDATE CURRENT_TIMESTAMP support
- Cache: add Redis cache layer (auto-downgrade) for vod list/detail/category tree
- Cache: write operations auto-invalidate related cache keys
- Health: add source health check service (30min scheduled + manual trigger API)
- Health: GET /admin/source now includes latest health status per source
- Models: add 14 indexes covering all high-frequency query patterns
- Models: uq_favorite_user_vod unique index prevents duplicate favorites at DB level
- Router: favorite add_favorite uses IntegrityError catch instead of SELECT+INSERT
- Router: fix duplicate route definitions in admin/source.py
- Router: admin/vod write ops now invalidate vod cache
- Router: admin/category write ops now invalidate category cache
- Collector: fix dedup bug - same name + different year now correctly creates new record
- Collector: extract _process_play_urls dedup logic consistent with vod dedup
- Scheduler: add health check job (every 30 minutes)
- Tests: expand from 17 to 44 tests (favorite, history, admin mgmt, RBAC, collector dedup)
- Tests: fix conftest session isolation - db_session and HTTP client now share session
- Config: add Redis config (REDIS_URL, CACHE_ENABLED, TTLs)
- Requirements: add PyJWT==2.9.*, redis==5.2.*, slowapi==0.1.9; remove python-jose
- .env.example +30 -7
- .gitignore +2 -0
- alembic.ini +1 -1
- alembic/env.py +4 -0
- alembic/versions/8126d022fb75_initial_schema.py +268 -0
- app/cache.py +153 -0
- app/config.py +12 -2
- app/dependencies.py +8 -6
- app/limiter.py +4 -0
- app/main.py +39 -1
- app/models/category.py +12 -1
- app/models/favorite.py +6 -1
- app/models/play_history.py +8 -1
- app/models/source_health.py +6 -1
- app/models/sync_log.py +8 -2
- app/models/vod.py +14 -1
- app/models/vod_source.py +8 -1
- app/routers/admin/admin_mgmt.py +35 -26
- app/routers/admin/auth.py +4 -2
- app/routers/admin/category.py +33 -30
- app/routers/admin/role_mgmt.py +21 -22
- app/routers/admin/source.py +115 -14
- app/routers/admin/sync.py +27 -20
- app/routers/admin/system.py +12 -13
- app/routers/admin/vod.py +23 -10
- app/routers/user/auth.py +8 -5
- app/routers/user/category.py +11 -1
- app/routers/user/favorite.py +21 -15
- app/routers/user/history.py +10 -4
- app/routers/user/vod.py +123 -117
- app/schemas/admin/admin_mgmt.py +20 -0
- app/schemas/admin/category.py +18 -0
- app/schemas/admin/role_mgmt.py +17 -0
- app/schemas/admin/source.py +26 -0
- app/schemas/admin/system.py +6 -0
- app/schemas/admin/vod.py +16 -0
- app/services/auth_user.py +28 -0
- app/services/category.py +45 -0
- app/services/collector.py +56 -21
- app/services/health.py +128 -0
- app/services/scheduler.py +18 -1
- app/services/sync.py +63 -0
- app/services/vod.py +40 -0
- app/utils/auth.py +7 -2
- docs/่ตๆบ็ซ.txt +23 -0
- docs/่ตๆบ็ซAPIๆฅๅฃๆๆกฃ.md +534 -0
- requirements.txt +7 -1
- tests/conftest.py +108 -0
- tests/test_admin_auth.py +82 -0
- tests/test_admin_mgmt.py +261 -0
|
@@ -1,15 +1,38 @@
|
|
| 1 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
DATABASE_URL=sqlite+aiosqlite:///./binv.db
|
| 3 |
|
| 4 |
-
# ็ไบง็ฏๅข(MySQL)
|
| 5 |
-
# DATABASE_URL=mysql+aiomysql://
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
|
| 8 |
ACCESS_TOKEN_EXPIRE_MINUTES=1440
|
| 9 |
|
| 10 |
-
# CORS
|
| 11 |
CORS_ORIGINS=http://localhost:3000,http://localhost:5777,http://localhost:5555
|
| 12 |
|
| 13 |
-
# ๅๆญฅ
|
| 14 |
SYNC_CRON_HOUR=1
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ============================================================
|
| 2 |
+
# BinV API ็ฏๅขๅ้้
็ฝฎ็คบไพ
|
| 3 |
+
# ๅคๅถๆญคๆไปถไธบ .env ๅนถๅกซๅๅฎ้
ๅผ๏ผ.env ไธๅพๆไบคๅฐ็ๆฌๆงๅถ
|
| 4 |
+
# ============================================================
|
| 5 |
+
|
| 6 |
+
# ๆฐๆฎๅบ
|
| 7 |
+
# ๅผๅ็ฏๅข (SQLite)
|
| 8 |
DATABASE_URL=sqlite+aiosqlite:///./binv.db
|
| 9 |
|
| 10 |
+
# ็ไบง็ฏๅข (MySQL) - ๅๆถๆณจ้ๅนถๅกซๅๅฎ้
่ฟๆฅไฟกๆฏ
|
| 11 |
+
# DATABASE_URL=mysql+aiomysql://็จๆทๅ:ๅฏ็ @ไธปๆบ:็ซฏๅฃ/ๆฐๆฎๅบๅ
|
| 12 |
+
# DATABASE_URL_PROD=mysql+aiomysql://็จๆทๅ:ๅฏ็ @ไธปๆบ:็ซฏๅฃ/ๆฐๆฎๅบๅ
|
| 13 |
+
|
| 14 |
+
# JWT ๅฏ้ฅ - ็ไบง็ฏๅขๅฟ
้กปไฝฟ็จๅผบ้ๆบๅญ็ฌฆไธฒ๏ผ่ณๅฐ 32 ไฝ
|
| 15 |
+
# ็ๆๅฝไปค: python -c "import secrets; print(secrets.token_hex(32))"
|
| 16 |
+
SECRET_KEY=dev-only-change-in-production
|
| 17 |
|
| 18 |
+
# Token ่ฟๆๆถ้ด๏ผๅ้๏ผ๏ผ้ป่ฎค 24 ๅฐๆถ
|
| 19 |
ACCESS_TOKEN_EXPIRE_MINUTES=1440
|
| 20 |
|
| 21 |
+
# CORS ๅ
่ฎธ็ๅ็ซฏๅๅ๏ผ้ๅทๅ้
|
| 22 |
CORS_ORIGINS=http://localhost:3000,http://localhost:5777,http://localhost:5555
|
| 23 |
|
| 24 |
+
# ๅฎๆถๅๆญฅ่งฆๅๅฐๆถ๏ผ0-23๏ผๆๅกๅจๆฌๅฐๆถ้ด๏ผ
|
| 25 |
SYNC_CRON_HOUR=1
|
| 26 |
+
|
| 27 |
+
# ๅๆญฅๅนถๅๆฐ
|
| 28 |
+
SYNC_MAX_CONCURRENT=3
|
| 29 |
+
|
| 30 |
+
# ๅๆฌกๅๆญฅๆๅคง้กตๆฐ
|
| 31 |
+
SYNC_MAX_PAGES=100
|
| 32 |
+
|
| 33 |
+
# Redis ็ผๅญ๏ผๅฏ้๏ผไธๅกซๅ่ชๅจ้็บงไธบๆ ็ผๅญๆจกๅผ๏ผ
|
| 34 |
+
REDIS_URL=redis://localhost:6379/0
|
| 35 |
+
CACHE_ENABLED=true
|
| 36 |
+
CACHE_TTL_VOD_LIST=300
|
| 37 |
+
CACHE_TTL_VOD_DETAIL=600
|
| 38 |
+
CACHE_TTL_CATEGORY=3600
|
|
@@ -15,6 +15,8 @@ alembic/versions/__pycache__/
|
|
| 15 |
.idea/
|
| 16 |
.vscode/
|
| 17 |
*.sqlite3
|
|
|
|
|
|
|
| 18 |
binv.db
|
| 19 |
source_categories.txt
|
| 20 |
scripts/fetch_categories.py
|
|
|
|
| 15 |
.idea/
|
| 16 |
.vscode/
|
| 17 |
*.sqlite3
|
| 18 |
+
*.db
|
| 19 |
+
*.db.bak
|
| 20 |
binv.db
|
| 21 |
source_categories.txt
|
| 22 |
scripts/fetch_categories.py
|
|
@@ -1,6 +1,6 @@
|
|
| 1 |
[alembic]
|
| 2 |
script_location = alembic
|
| 3 |
-
sqlalchemy.url =
|
| 4 |
|
| 5 |
[loggers]
|
| 6 |
keys = root,sqlalchemy,alembic
|
|
|
|
| 1 |
[alembic]
|
| 2 |
script_location = alembic
|
| 3 |
+
sqlalchemy.url = sqlite+aiosqlite:///./binv.db
|
| 4 |
|
| 5 |
[loggers]
|
| 6 |
keys = root,sqlalchemy,alembic
|
|
@@ -5,6 +5,7 @@ from alembic import context
|
|
| 5 |
from sqlalchemy import pool
|
| 6 |
from sqlalchemy.ext.asyncio import async_engine_from_config
|
| 7 |
|
|
|
|
| 8 |
from app.database import Base
|
| 9 |
from app.models import * # noqa: F401,F403
|
| 10 |
|
|
@@ -12,6 +13,9 @@ config = context.config
|
|
| 12 |
if config.config_file_name is not None:
|
| 13 |
fileConfig(config.config_file_name)
|
| 14 |
|
|
|
|
|
|
|
|
|
|
| 15 |
target_metadata = Base.metadata
|
| 16 |
|
| 17 |
|
|
|
|
| 5 |
from sqlalchemy import pool
|
| 6 |
from sqlalchemy.ext.asyncio import async_engine_from_config
|
| 7 |
|
| 8 |
+
from app.config import settings
|
| 9 |
from app.database import Base
|
| 10 |
from app.models import * # noqa: F401,F403
|
| 11 |
|
|
|
|
| 13 |
if config.config_file_name is not None:
|
| 14 |
fileConfig(config.config_file_name)
|
| 15 |
|
| 16 |
+
# ไผๅ
ไฝฟ็จ settings.DATABASE_URL๏ผ่ฆ็ alembic.ini ไธญ็ๅผ
|
| 17 |
+
config.set_main_option("sqlalchemy.url", settings.DATABASE_URL)
|
| 18 |
+
|
| 19 |
target_metadata = Base.metadata
|
| 20 |
|
| 21 |
|
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""initial_schema
|
| 2 |
+
|
| 3 |
+
Revision ID: 8126d022fb75
|
| 4 |
+
Revises:
|
| 5 |
+
Create Date: 2026-05-15 15:38:43.248659
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
from typing import Sequence, Union
|
| 9 |
+
|
| 10 |
+
from alembic import op
|
| 11 |
+
import sqlalchemy as sa
|
| 12 |
+
|
| 13 |
+
# MySQL ON UPDATE CURRENT_TIMESTAMP helper
|
| 14 |
+
# SQLite ไผๅฟฝ็ฅ server_onupdate๏ผMySQL ไผ็ๆ ON UPDATE CURRENT_TIMESTAMP
|
| 15 |
+
_OU = sa.text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
revision: str = '8126d022fb75'
|
| 19 |
+
down_revision: Union[str, None] = None
|
| 20 |
+
branch_labels: Union[str, Sequence[str], None] = None
|
| 21 |
+
depends_on: Union[str, Sequence[str], None] = None
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def upgrade() -> None:
|
| 25 |
+
op.create_table(
|
| 26 |
+
'source_site',
|
| 27 |
+
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
| 28 |
+
sa.Column('name', sa.String(length=50), nullable=False, comment='็ซ็นๅ็งฐ'),
|
| 29 |
+
sa.Column('code', sa.String(length=30), nullable=False, comment='็ซ็น็ผ็ '),
|
| 30 |
+
sa.Column('base_url', sa.String(length=500), nullable=False, comment='APIๅบ็กๅฐๅ'),
|
| 31 |
+
sa.Column('site_url', sa.String(length=500), nullable=True, comment='ๅฎ็ฝๅฐๅ'),
|
| 32 |
+
sa.Column('play_from_m3u8', sa.String(length=30), nullable=True, comment='M3U8ๆฅๆบๆ ่ฏ'),
|
| 33 |
+
sa.Column('play_from_yun', sa.String(length=30), nullable=True, comment='ไบๆญๆฅๆบๆ ่ฏ'),
|
| 34 |
+
sa.Column('parse_url', sa.String(length=500), nullable=True, comment='M3U8่งฃๆๆฅๅฃ'),
|
| 35 |
+
sa.Column('is_active', sa.Boolean(), nullable=False),
|
| 36 |
+
sa.Column('sync_interval', sa.Integer(), nullable=False),
|
| 37 |
+
sa.Column('last_sync_at', sa.DateTime(), nullable=True),
|
| 38 |
+
sa.Column('last_sync_status', sa.String(length=20), nullable=True),
|
| 39 |
+
sa.Column('last_sync_count', sa.Integer(), nullable=False),
|
| 40 |
+
sa.Column('total_count', sa.Integer(), nullable=False),
|
| 41 |
+
sa.Column('sort_order', sa.Integer(), nullable=False),
|
| 42 |
+
sa.Column('remark', sa.String(length=200), nullable=True),
|
| 43 |
+
sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),
|
| 44 |
+
sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), server_onupdate=_OU, nullable=False),
|
| 45 |
+
sa.PrimaryKeyConstraint('id'),
|
| 46 |
+
sa.UniqueConstraint('code'),
|
| 47 |
+
)
|
| 48 |
+
op.create_table(
|
| 49 |
+
'category',
|
| 50 |
+
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
| 51 |
+
sa.Column('name', sa.String(length=30), nullable=False, comment='ๅ็ฑปๅ็งฐ'),
|
| 52 |
+
sa.Column('parent_id', sa.Integer(), nullable=True),
|
| 53 |
+
sa.Column('sort_order', sa.Integer(), nullable=False),
|
| 54 |
+
sa.Column('is_active', sa.Boolean(), nullable=False),
|
| 55 |
+
sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),
|
| 56 |
+
sa.PrimaryKeyConstraint('id'),
|
| 57 |
+
)
|
| 58 |
+
op.create_table(
|
| 59 |
+
'category_mapping',
|
| 60 |
+
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
| 61 |
+
sa.Column('category_id', sa.Integer(), nullable=False, comment='็ปไธๅ็ฑปID'),
|
| 62 |
+
sa.Column('source_id', sa.Integer(), nullable=False, comment='่ตๆบ็ซID'),
|
| 63 |
+
sa.Column('source_type_id', sa.Integer(), nullable=False, comment='ๆบ็ซๅ็ฑปID'),
|
| 64 |
+
sa.Column('source_type_name', sa.String(length=30), nullable=False, comment='ๆบ็ซๅ็ฑปๅ็งฐ'),
|
| 65 |
+
sa.PrimaryKeyConstraint('id'),
|
| 66 |
+
)
|
| 67 |
+
op.create_table(
|
| 68 |
+
'admin',
|
| 69 |
+
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
| 70 |
+
sa.Column('username', sa.String(length=30), nullable=False, comment='็จๆทๅ'),
|
| 71 |
+
sa.Column('password_hash', sa.String(length=128), nullable=False, comment='bcryptๅๅธ'),
|
| 72 |
+
sa.Column('nickname', sa.String(length=30), nullable=True),
|
| 73 |
+
sa.Column('avatar', sa.String(length=500), nullable=True),
|
| 74 |
+
sa.Column('is_active', sa.Boolean(), nullable=False),
|
| 75 |
+
sa.Column('last_login_at', sa.DateTime(), nullable=True),
|
| 76 |
+
sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),
|
| 77 |
+
sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), server_onupdate=_OU, nullable=False),
|
| 78 |
+
sa.PrimaryKeyConstraint('id'),
|
| 79 |
+
sa.UniqueConstraint('username'),
|
| 80 |
+
)
|
| 81 |
+
op.create_table(
|
| 82 |
+
'role',
|
| 83 |
+
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
| 84 |
+
sa.Column('name', sa.String(length=30), nullable=False, comment='่ง่ฒๅ็งฐ'),
|
| 85 |
+
sa.Column('code', sa.String(length=30), nullable=False, comment='่ง่ฒ็ผ็ '),
|
| 86 |
+
sa.Column('description', sa.String(length=200), nullable=True),
|
| 87 |
+
sa.Column('is_builtin', sa.Boolean(), nullable=False),
|
| 88 |
+
sa.Column('status', sa.Integer(), nullable=False),
|
| 89 |
+
sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),
|
| 90 |
+
sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), server_onupdate=_OU, nullable=False),
|
| 91 |
+
sa.PrimaryKeyConstraint('id'),
|
| 92 |
+
sa.UniqueConstraint('code'),
|
| 93 |
+
sa.UniqueConstraint('name'),
|
| 94 |
+
)
|
| 95 |
+
op.create_table(
|
| 96 |
+
'admin_role',
|
| 97 |
+
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
| 98 |
+
sa.Column('admin_id', sa.Integer(), nullable=False),
|
| 99 |
+
sa.Column('role_id', sa.Integer(), nullable=False),
|
| 100 |
+
sa.PrimaryKeyConstraint('id'),
|
| 101 |
+
)
|
| 102 |
+
op.create_table(
|
| 103 |
+
'permission',
|
| 104 |
+
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
| 105 |
+
sa.Column('code', sa.String(length=60), nullable=False, comment='ๆ้็ '),
|
| 106 |
+
sa.Column('name', sa.String(length=50), nullable=False, comment='ๆ้ๅ็งฐ'),
|
| 107 |
+
sa.Column('type', sa.String(length=10), nullable=False, comment='menu/page/btn'),
|
| 108 |
+
sa.Column('parent_id', sa.Integer(), nullable=True),
|
| 109 |
+
sa.Column('path', sa.String(length=200), nullable=True),
|
| 110 |
+
sa.Column('component', sa.String(length=200), nullable=True),
|
| 111 |
+
sa.Column('redirect', sa.String(length=200), nullable=True),
|
| 112 |
+
sa.Column('icon', sa.String(length=50), nullable=True),
|
| 113 |
+
sa.Column('sort_order', sa.Integer(), nullable=False),
|
| 114 |
+
sa.Column('status', sa.Integer(), nullable=False),
|
| 115 |
+
sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),
|
| 116 |
+
sa.PrimaryKeyConstraint('id'),
|
| 117 |
+
sa.UniqueConstraint('code'),
|
| 118 |
+
)
|
| 119 |
+
op.create_table(
|
| 120 |
+
'role_permission',
|
| 121 |
+
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
| 122 |
+
sa.Column('role_id', sa.Integer(), nullable=False),
|
| 123 |
+
sa.Column('permission_id', sa.Integer(), nullable=False),
|
| 124 |
+
sa.PrimaryKeyConstraint('id'),
|
| 125 |
+
)
|
| 126 |
+
op.create_table(
|
| 127 |
+
'user',
|
| 128 |
+
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
| 129 |
+
sa.Column('username', sa.String(length=30), nullable=True, comment='็จๆทๅ'),
|
| 130 |
+
sa.Column('email', sa.String(length=100), nullable=True, comment='้ฎ็ฎฑ'),
|
| 131 |
+
sa.Column('phone', sa.String(length=20), nullable=True, comment='ๆๆบๅท'),
|
| 132 |
+
sa.Column('password_hash', sa.String(length=128), nullable=False, comment='bcryptๅๅธ'),
|
| 133 |
+
sa.Column('nickname', sa.String(length=30), nullable=True),
|
| 134 |
+
sa.Column('avatar', sa.String(length=500), nullable=True),
|
| 135 |
+
sa.Column('is_active', sa.Boolean(), nullable=False),
|
| 136 |
+
sa.Column('last_login_at', sa.DateTime(), nullable=True),
|
| 137 |
+
sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),
|
| 138 |
+
sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), server_onupdate=_OU, nullable=False),
|
| 139 |
+
sa.PrimaryKeyConstraint('id'),
|
| 140 |
+
sa.UniqueConstraint('username'),
|
| 141 |
+
sa.UniqueConstraint('email'),
|
| 142 |
+
sa.UniqueConstraint('phone'),
|
| 143 |
+
)
|
| 144 |
+
op.create_table(
|
| 145 |
+
'vod',
|
| 146 |
+
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
| 147 |
+
sa.Column('name', sa.String(length=200), nullable=False),
|
| 148 |
+
sa.Column('sub_name', sa.String(length=500), nullable=True),
|
| 149 |
+
sa.Column('en_name', sa.String(length=200), nullable=True),
|
| 150 |
+
sa.Column('category_id', sa.Integer(), nullable=False),
|
| 151 |
+
sa.Column('cover', sa.String(length=500), nullable=True),
|
| 152 |
+
sa.Column('actor', sa.String(length=2000), nullable=True),
|
| 153 |
+
sa.Column('director', sa.String(length=200), nullable=True),
|
| 154 |
+
sa.Column('area', sa.String(length=50), nullable=True),
|
| 155 |
+
sa.Column('lang', sa.String(length=50), nullable=True),
|
| 156 |
+
sa.Column('year', sa.String(length=10), nullable=True),
|
| 157 |
+
sa.Column('duration', sa.String(length=20), nullable=True),
|
| 158 |
+
sa.Column('score', sa.Float(), nullable=True),
|
| 159 |
+
sa.Column('douban_id', sa.Integer(), nullable=True),
|
| 160 |
+
sa.Column('blurb', sa.Text(), nullable=True),
|
| 161 |
+
sa.Column('content', sa.Text(), nullable=True),
|
| 162 |
+
sa.Column('remarks', sa.String(length=100), nullable=True),
|
| 163 |
+
sa.Column('is_end', sa.Boolean(), nullable=False),
|
| 164 |
+
sa.Column('is_hidden', sa.Boolean(), nullable=False),
|
| 165 |
+
sa.Column('is_recommended', sa.Boolean(), nullable=False),
|
| 166 |
+
sa.Column('view_count', sa.Integer(), nullable=False),
|
| 167 |
+
sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),
|
| 168 |
+
sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), server_onupdate=_OU, nullable=False),
|
| 169 |
+
sa.PrimaryKeyConstraint('id'),
|
| 170 |
+
)
|
| 171 |
+
op.create_table(
|
| 172 |
+
'vod_source',
|
| 173 |
+
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
| 174 |
+
sa.Column('vod_id', sa.Integer(), nullable=False),
|
| 175 |
+
sa.Column('source_id', sa.Integer(), nullable=False),
|
| 176 |
+
sa.Column('source_vod_id', sa.Integer(), nullable=False, comment='ๆบ็ซๅฝฑ็ID'),
|
| 177 |
+
sa.Column('play_from', sa.String(length=30), nullable=False, comment='ๆญๆพๆฅๆบ'),
|
| 178 |
+
sa.Column('play_url', sa.String(), nullable=False, comment='ๆญๆพๅฐๅ'),
|
| 179 |
+
sa.Column('parse_url', sa.String(), nullable=True, comment='่งฃๆๅURL'),
|
| 180 |
+
sa.Column('is_available', sa.Boolean(), nullable=False),
|
| 181 |
+
sa.Column('last_check_at', sa.DateTime(), nullable=True),
|
| 182 |
+
sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),
|
| 183 |
+
sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), server_onupdate=_OU, nullable=False),
|
| 184 |
+
sa.PrimaryKeyConstraint('id'),
|
| 185 |
+
)
|
| 186 |
+
op.create_table(
|
| 187 |
+
'favorite',
|
| 188 |
+
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
| 189 |
+
sa.Column('user_id', sa.Integer(), nullable=False),
|
| 190 |
+
sa.Column('vod_id', sa.Integer(), nullable=False),
|
| 191 |
+
sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),
|
| 192 |
+
sa.PrimaryKeyConstraint('id'),
|
| 193 |
+
)
|
| 194 |
+
op.create_table(
|
| 195 |
+
'play_history',
|
| 196 |
+
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
| 197 |
+
sa.Column('user_id', sa.Integer(), nullable=False),
|
| 198 |
+
sa.Column('vod_id', sa.Integer(), nullable=False),
|
| 199 |
+
sa.Column('source_id', sa.Integer(), nullable=False),
|
| 200 |
+
sa.Column('episode', sa.String(length=50), nullable=True),
|
| 201 |
+
sa.Column('play_url', sa.String(), nullable=False),
|
| 202 |
+
sa.Column('progress', sa.Integer(), nullable=False),
|
| 203 |
+
sa.Column('duration', sa.Integer(), nullable=False),
|
| 204 |
+
sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),
|
| 205 |
+
sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), server_onupdate=_OU, nullable=False),
|
| 206 |
+
sa.PrimaryKeyConstraint('id'),
|
| 207 |
+
)
|
| 208 |
+
op.create_table(
|
| 209 |
+
'sync_log',
|
| 210 |
+
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
| 211 |
+
sa.Column('source_id', sa.Integer(), nullable=False),
|
| 212 |
+
sa.Column('range_type', sa.String(length=20), nullable=False),
|
| 213 |
+
sa.Column('status', sa.String(length=20), nullable=False),
|
| 214 |
+
sa.Column('started_at', sa.DateTime(), nullable=False),
|
| 215 |
+
sa.Column('finished_at', sa.DateTime(), nullable=True),
|
| 216 |
+
sa.Column('total_fetched', sa.Integer(), nullable=False),
|
| 217 |
+
sa.Column('new_count', sa.Integer(), nullable=False),
|
| 218 |
+
sa.Column('update_count', sa.Integer(), nullable=False),
|
| 219 |
+
sa.Column('fail_count', sa.Integer(), nullable=False),
|
| 220 |
+
sa.Column('error_message', sa.String(), nullable=True),
|
| 221 |
+
sa.Column('duration_seconds', sa.Integer(), nullable=True),
|
| 222 |
+
sa.PrimaryKeyConstraint('id'),
|
| 223 |
+
)
|
| 224 |
+
op.create_table(
|
| 225 |
+
'source_health',
|
| 226 |
+
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
| 227 |
+
sa.Column('source_id', sa.Integer(), nullable=False),
|
| 228 |
+
sa.Column('check_type', sa.String(length=20), nullable=False, comment='api/play'),
|
| 229 |
+
sa.Column('is_success', sa.Boolean(), nullable=False),
|
| 230 |
+
sa.Column('response_time_ms', sa.Integer(), nullable=True),
|
| 231 |
+
sa.Column('error_message', sa.String(), nullable=True),
|
| 232 |
+
sa.Column('checked_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),
|
| 233 |
+
sa.PrimaryKeyConstraint('id'),
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
# โโ ็ดขๅผ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 237 |
+
op.create_index('ix_vod_category_updated', 'vod', ['category_id', 'updated_at'], unique=False)
|
| 238 |
+
op.create_index('ix_vod_hidden_updated', 'vod', ['is_hidden', 'updated_at'], unique=False)
|
| 239 |
+
op.create_index('ix_vod_recommended_score', 'vod', ['is_recommended', 'score'], unique=False)
|
| 240 |
+
op.create_index('ix_vod_name_year', 'vod', ['name', 'year'], unique=False)
|
| 241 |
+
op.create_index('ix_vod_douban_id', 'vod', ['douban_id'], unique=False)
|
| 242 |
+
op.create_index('ix_vod_source_vod_id', 'vod_source', ['vod_id'], unique=False)
|
| 243 |
+
op.create_index('ix_vod_source_source_vod', 'vod_source', ['source_id', 'source_vod_id'], unique=False)
|
| 244 |
+
op.create_index('uq_favorite_user_vod', 'favorite', ['user_id', 'vod_id'], unique=True)
|
| 245 |
+
op.create_index('ix_play_history_user_updated', 'play_history', ['user_id', 'updated_at'], unique=False)
|
| 246 |
+
op.create_index('ix_play_history_user_vod', 'play_history', ['user_id', 'vod_id'], unique=False)
|
| 247 |
+
op.create_index('ix_sync_log_source_started', 'sync_log', ['source_id', 'started_at'], unique=False)
|
| 248 |
+
op.create_index('ix_source_health_source_checked','source_health', ['source_id', 'checked_at'], unique=False)
|
| 249 |
+
op.create_index('ix_category_active_sort', 'category', ['is_active', 'sort_order'], unique=False)
|
| 250 |
+
op.create_index('ix_category_mapping_source_type','category_mapping',['source_id', 'source_type_id'], unique=False)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def downgrade() -> None:
|
| 254 |
+
op.drop_table('source_health')
|
| 255 |
+
op.drop_table('sync_log')
|
| 256 |
+
op.drop_table('play_history')
|
| 257 |
+
op.drop_table('favorite')
|
| 258 |
+
op.drop_table('vod_source')
|
| 259 |
+
op.drop_table('vod')
|
| 260 |
+
op.drop_table('user')
|
| 261 |
+
op.drop_table('role_permission')
|
| 262 |
+
op.drop_table('permission')
|
| 263 |
+
op.drop_table('admin_role')
|
| 264 |
+
op.drop_table('role')
|
| 265 |
+
op.drop_table('admin')
|
| 266 |
+
op.drop_table('category_mapping')
|
| 267 |
+
op.drop_table('category')
|
| 268 |
+
op.drop_table('source_site')
|
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Redis ็ผๅญๅทฅๅ
ทๆจกๅ
|
| 3 |
+
- ๆฏๆ้็บง๏ผRedis ไธๅฏ็จๆถ่ชๅจ้ๅบ็ผๅญๆจกๅผ๏ผไธๅฝฑๅไธๅก
|
| 4 |
+
- key ๅฝๅ่ง่๏ผbinv:{namespace}:{ๅ
ทไฝๅๆฐhash}
|
| 5 |
+
"""
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
import logging
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import redis.asyncio as aioredis
|
| 12 |
+
|
| 13 |
+
from app.config import settings
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger("cache")
|
| 16 |
+
|
| 17 |
+
# ๅ
จๅฑ Redis ่ฟๆฅๆฑ ๏ผๆๅ ่ฝฝ๏ผ
|
| 18 |
+
_redis: aioredis.Redis | None = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
async def get_redis() -> aioredis.Redis | None:
|
| 22 |
+
"""่ทๅ Redis ่ฟๆฅ๏ผ่ฟๆฅๅคฑ่ดฅ่ฟๅ None๏ผ้็บงๆจกๅผ๏ผ"""
|
| 23 |
+
global _redis
|
| 24 |
+
if not settings.CACHE_ENABLED:
|
| 25 |
+
return None
|
| 26 |
+
if _redis is None:
|
| 27 |
+
try:
|
| 28 |
+
_redis = aioredis.from_url(
|
| 29 |
+
settings.REDIS_URL,
|
| 30 |
+
encoding="utf-8",
|
| 31 |
+
decode_responses=True,
|
| 32 |
+
socket_connect_timeout=2,
|
| 33 |
+
socket_timeout=2,
|
| 34 |
+
)
|
| 35 |
+
await _redis.ping()
|
| 36 |
+
logger.info(f"Redis connected: {settings.REDIS_URL}")
|
| 37 |
+
except Exception as e:
|
| 38 |
+
logger.warning(f"Redis unavailable, cache disabled: {e}")
|
| 39 |
+
_redis = None
|
| 40 |
+
return _redis
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
async def close_redis():
|
| 44 |
+
"""ๅ
ณ้ญ Redis ่ฟๆฅ๏ผๅบ็จ้ๅบๆถ่ฐ็จ๏ผ"""
|
| 45 |
+
global _redis
|
| 46 |
+
if _redis is not None:
|
| 47 |
+
await _redis.aclose()
|
| 48 |
+
_redis = None
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _make_key(namespace: str, **kwargs) -> str:
|
| 52 |
+
"""็ๆ็ผๅญ key๏ผๅๆฐ่ถ
่ฟ 32 ๅญ็ฌฆๆถ็จ md5 ๅ็ผฉ"""
|
| 53 |
+
param_str = "&".join(f"{k}={v}" for k, v in sorted(kwargs.items()) if v is not None)
|
| 54 |
+
if len(param_str) > 32:
|
| 55 |
+
param_str = hashlib.md5(param_str.encode()).hexdigest()
|
| 56 |
+
return f"binv:{namespace}:{param_str}"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
async def cache_get(key: str) -> Any | None:
|
| 60 |
+
"""่ฏปๅ็ผๅญ๏ผๅคฑ่ดฅ่ฟๅ None"""
|
| 61 |
+
r = await get_redis()
|
| 62 |
+
if r is None:
|
| 63 |
+
return None
|
| 64 |
+
try:
|
| 65 |
+
raw = await r.get(key)
|
| 66 |
+
return json.loads(raw) if raw else None
|
| 67 |
+
except Exception as e:
|
| 68 |
+
logger.debug(f"cache_get error [{key}]: {e}")
|
| 69 |
+
return None
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
async def cache_set(key: str, value: Any, ttl: int) -> None:
|
| 73 |
+
"""ๅๅ
ฅ็ผๅญ๏ผๅคฑ่ดฅ้้ปๅฟฝ็ฅ"""
|
| 74 |
+
r = await get_redis()
|
| 75 |
+
if r is None:
|
| 76 |
+
return
|
| 77 |
+
try:
|
| 78 |
+
await r.setex(key, ttl, json.dumps(value, ensure_ascii=False, default=str))
|
| 79 |
+
except Exception as e:
|
| 80 |
+
logger.debug(f"cache_set error [{key}]: {e}")
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
async def cache_delete(key: str) -> None:
|
| 84 |
+
"""ๅ ้คๅไธช็ผๅญ key"""
|
| 85 |
+
r = await get_redis()
|
| 86 |
+
if r is None:
|
| 87 |
+
return
|
| 88 |
+
try:
|
| 89 |
+
await r.delete(key)
|
| 90 |
+
except Exception as e:
|
| 91 |
+
logger.debug(f"cache_delete error [{key}]: {e}")
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
async def cache_delete_pattern(pattern: str) -> int:
|
| 95 |
+
"""ๆ pattern ๆน้ๅ ้ค็ผๅญ๏ผไฝฟ็จ SCAN ้ฟๅ
้ปๅก๏ผ"""
|
| 96 |
+
r = await get_redis()
|
| 97 |
+
if r is None:
|
| 98 |
+
return 0
|
| 99 |
+
try:
|
| 100 |
+
deleted = 0
|
| 101 |
+
async for key in r.scan_iter(match=pattern, count=100):
|
| 102 |
+
await r.delete(key)
|
| 103 |
+
deleted += 1
|
| 104 |
+
return deleted
|
| 105 |
+
except Exception as e:
|
| 106 |
+
logger.debug(f"cache_delete_pattern error [{pattern}]: {e}")
|
| 107 |
+
return 0
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# โโ ไธๅกๅฑ Key ็ๆๅจ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 111 |
+
|
| 112 |
+
def vod_list_key(category_id: int | None, page: int, page_size: int) -> str:
|
| 113 |
+
return _make_key("vod:list", category_id=category_id, page=page, page_size=page_size)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def vod_search_key(keyword: str, category_id: int | None, page: int, page_size: int) -> str:
|
| 117 |
+
return _make_key("vod:search", keyword=keyword, category_id=category_id, page=page, page_size=page_size)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def vod_latest_key(page: int, page_size: int) -> str:
|
| 121 |
+
return _make_key("vod:latest", page=page, page_size=page_size)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def vod_recommended_key(page: int, page_size: int) -> str:
|
| 125 |
+
return _make_key("vod:recommended", page=page, page_size=page_size)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def vod_detail_key(vod_id: int) -> str:
|
| 129 |
+
return _make_key("vod:detail", vod_id=vod_id)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def category_tree_key() -> str:
|
| 133 |
+
return "binv:category:tree"
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# โโ ็ผๅญๅคฑๆ่พ
ๅฉ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 137 |
+
|
| 138 |
+
async def invalidate_vod_cache(vod_id: int | None = None) -> None:
|
| 139 |
+
"""ๅฝฑ็ๆฐๆฎๅๆดๆถๆธ
้ค็ธๅ
ณ็ผๅญ"""
|
| 140 |
+
if vod_id:
|
| 141 |
+
await cache_delete(vod_detail_key(vod_id))
|
| 142 |
+
# ๅ่กจ็ผๅญๅ
จ้จๆธ
้ค๏ผๅ ไธบๆๅบใๆฐ้้ฝๅฏ่ฝๅๅ๏ผ
|
| 143 |
+
await cache_delete_pattern("binv:vod:list:*")
|
| 144 |
+
await cache_delete_pattern("binv:vod:search:*")
|
| 145 |
+
await cache_delete_pattern("binv:vod:latest:*")
|
| 146 |
+
await cache_delete_pattern("binv:vod:recommended:*")
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
async def invalidate_category_cache() -> None:
|
| 150 |
+
"""ๅ็ฑปๅๆดๆถๆธ
้คๅ็ฑปๆ ็ผๅญ"""
|
| 151 |
+
await cache_delete(category_tree_key())
|
| 152 |
+
# ๅ็ฑปๅๅไนๅฝฑๅๅฝฑ็ๅ่กจ
|
| 153 |
+
await cache_delete_pattern("binv:vod:list:*")
|
|
@@ -3,14 +3,24 @@ from pydantic_settings import BaseSettings
|
|
| 3 |
|
| 4 |
class Settings(BaseSettings):
|
| 5 |
DATABASE_URL: str = "sqlite+aiosqlite:///./binv.db"
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
| 8 |
ACCESS_TOKEN_EXPIRE_MINUTES: int = 1440
|
| 9 |
CORS_ORIGINS: str = "http://localhost:3000,http://localhost:5777,http://localhost:5555"
|
| 10 |
SYNC_CRON_HOUR: int = 1
|
| 11 |
SYNC_MAX_CONCURRENT: int = 3
|
| 12 |
SYNC_MAX_PAGES: int = 100
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
model_config = {"env_file": ".env", "extra": "ignore"}
|
| 15 |
|
| 16 |
|
|
|
|
| 3 |
|
| 4 |
class Settings(BaseSettings):
|
| 5 |
DATABASE_URL: str = "sqlite+aiosqlite:///./binv.db"
|
| 6 |
+
# ็ไบงๆฐๆฎๅบ URL ๅฟ
้กป้่ฟ็ฏๅขๅ้ๆณจๅ
ฅ๏ผไธๅจไปฃ็ ไธญๆไพ้ป่ฎคๅผ
|
| 7 |
+
DATABASE_URL_PROD: str = ""
|
| 8 |
+
# JWT ๅฏ้ฅๅฟ
้กป้่ฟ็ฏๅขๅ้ๆณจๅ
ฅ๏ผ็ไบง็ฏๅขไธๅพไฝฟ็จ้ป่ฎคๅผ
|
| 9 |
+
SECRET_KEY: str = "dev-only-change-in-production"
|
| 10 |
ACCESS_TOKEN_EXPIRE_MINUTES: int = 1440
|
| 11 |
CORS_ORIGINS: str = "http://localhost:3000,http://localhost:5777,http://localhost:5555"
|
| 12 |
SYNC_CRON_HOUR: int = 1
|
| 13 |
SYNC_MAX_CONCURRENT: int = 3
|
| 14 |
SYNC_MAX_PAGES: int = 100
|
| 15 |
|
| 16 |
+
# Redis ้
็ฝฎ๏ผ็ผๅญๅฑ๏ผๅฏ้๏ผไธ้
็ฝฎๅ้็บงไธบๆ ็ผๅญๆจกๅผ๏ผ
|
| 17 |
+
REDIS_URL: str = "redis://localhost:6379/0"
|
| 18 |
+
CACHE_ENABLED: bool = True
|
| 19 |
+
# ๅ็ฑป็ผๅญ TTL๏ผ็ง๏ผ
|
| 20 |
+
CACHE_TTL_VOD_LIST: int = 300 # ๅฝฑ็ๅ่กจ็ผๅญ 5 ๅ้
|
| 21 |
+
CACHE_TTL_VOD_DETAIL: int = 600 # ๅฝฑ็่ฏฆๆ
็ผๅญ 10 ๅ้
|
| 22 |
+
CACHE_TTL_CATEGORY: int = 3600 # ๅ็ฑปๆ ็ผๅญ 1 ๅฐๆถ
|
| 23 |
+
|
| 24 |
model_config = {"env_file": ".env", "extra": "ignore"}
|
| 25 |
|
| 26 |
|
|
@@ -1,8 +1,8 @@
|
|
| 1 |
from collections.abc import AsyncGenerator
|
| 2 |
|
|
|
|
| 3 |
from fastapi import Depends, HTTPException, status
|
| 4 |
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
| 5 |
-
from jose import JWTError, jwt
|
| 6 |
from sqlalchemy import select
|
| 7 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 8 |
|
|
@@ -23,10 +23,11 @@ async def get_current_admin(
|
|
| 23 |
token = credentials.credentials
|
| 24 |
try:
|
| 25 |
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
|
| 26 |
-
admin_id:
|
| 27 |
-
|
|
|
|
| 28 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
| 29 |
-
except
|
| 30 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
| 31 |
|
| 32 |
result = await db.execute(select(Admin).where(Admin.id == int(admin_id)))
|
|
@@ -43,11 +44,11 @@ async def get_current_user(
|
|
| 43 |
token = credentials.credentials
|
| 44 |
try:
|
| 45 |
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
|
| 46 |
-
user_id:
|
| 47 |
user_type: str | None = payload.get("type")
|
| 48 |
if user_id is None or user_type != "user":
|
| 49 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
| 50 |
-
except
|
| 51 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
| 52 |
|
| 53 |
result = await db.execute(select(User).where(User.id == int(user_id)))
|
|
@@ -94,3 +95,4 @@ def require_permission(permission_code: str):
|
|
| 94 |
return admin
|
| 95 |
|
| 96 |
return permission_checker
|
|
|
|
|
|
| 1 |
from collections.abc import AsyncGenerator
|
| 2 |
|
| 3 |
+
import jwt
|
| 4 |
from fastapi import Depends, HTTPException, status
|
| 5 |
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
|
|
| 6 |
from sqlalchemy import select
|
| 7 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 8 |
|
|
|
|
| 23 |
token = credentials.credentials
|
| 24 |
try:
|
| 25 |
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
|
| 26 |
+
admin_id: str | None = payload.get("sub")
|
| 27 |
+
token_type: str | None = payload.get("type")
|
| 28 |
+
if admin_id is None or token_type != "admin":
|
| 29 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
| 30 |
+
except jwt.PyJWTError:
|
| 31 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
| 32 |
|
| 33 |
result = await db.execute(select(Admin).where(Admin.id == int(admin_id)))
|
|
|
|
| 44 |
token = credentials.credentials
|
| 45 |
try:
|
| 46 |
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
|
| 47 |
+
user_id: str | None = payload.get("sub")
|
| 48 |
user_type: str | None = payload.get("type")
|
| 49 |
if user_id is None or user_type != "user":
|
| 50 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
| 51 |
+
except jwt.PyJWTError:
|
| 52 |
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
| 53 |
|
| 54 |
result = await db.execute(select(User).where(User.id == int(user_id)))
|
|
|
|
| 95 |
return admin
|
| 96 |
|
| 97 |
return permission_checker
|
| 98 |
+
|
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from slowapi import Limiter
|
| 2 |
+
from slowapi.util import get_remote_address
|
| 3 |
+
|
| 4 |
+
limiter = Limiter(key_func=get_remote_address)
|
|
@@ -2,8 +2,12 @@ from contextlib import asynccontextmanager
|
|
| 2 |
|
| 3 |
from fastapi import FastAPI
|
| 4 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
|
|
|
| 5 |
|
|
|
|
| 6 |
from app.config import settings
|
|
|
|
| 7 |
from app.routers import admin_router
|
| 8 |
from app.routers.user import user_router
|
| 9 |
from app.services.scheduler import start_scheduler, stop_scheduler
|
|
@@ -11,9 +15,12 @@ from app.services.scheduler import start_scheduler, stop_scheduler
|
|
| 11 |
|
| 12 |
@asynccontextmanager
|
| 13 |
async def lifespan(app: FastAPI):
|
|
|
|
|
|
|
| 14 |
start_scheduler()
|
| 15 |
yield
|
| 16 |
stop_scheduler()
|
|
|
|
| 17 |
|
| 18 |
|
| 19 |
app = FastAPI(
|
|
@@ -23,6 +30,9 @@ app = FastAPI(
|
|
| 23 |
lifespan=lifespan,
|
| 24 |
)
|
| 25 |
|
|
|
|
|
|
|
|
|
|
| 26 |
app.add_middleware(
|
| 27 |
CORSMiddleware,
|
| 28 |
allow_origins=[o.strip() for o in settings.CORS_ORIGINS.split(",")],
|
|
@@ -37,4 +47,32 @@ app.include_router(user_router, prefix="/user")
|
|
| 37 |
|
| 38 |
@app.get("/health")
|
| 39 |
async def health_check():
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
from fastapi import FastAPI
|
| 4 |
from fastapi.middleware.cors import CORSMiddleware
|
| 5 |
+
from slowapi import _rate_limit_exceeded_handler
|
| 6 |
+
from slowapi.errors import RateLimitExceeded
|
| 7 |
|
| 8 |
+
from app.cache import get_redis, close_redis
|
| 9 |
from app.config import settings
|
| 10 |
+
from app.limiter import limiter
|
| 11 |
from app.routers import admin_router
|
| 12 |
from app.routers.user import user_router
|
| 13 |
from app.services.scheduler import start_scheduler, stop_scheduler
|
|
|
|
| 15 |
|
| 16 |
@asynccontextmanager
|
| 17 |
async def lifespan(app: FastAPI):
|
| 18 |
+
# ๅๅงๅ Redis ่ฟๆฅ๏ผๅคฑ่ดฅไผ่ชๅจ้็บง๏ผไธ้ปๆญๅฏๅจ๏ผ
|
| 19 |
+
await get_redis()
|
| 20 |
start_scheduler()
|
| 21 |
yield
|
| 22 |
stop_scheduler()
|
| 23 |
+
await close_redis()
|
| 24 |
|
| 25 |
|
| 26 |
app = FastAPI(
|
|
|
|
| 30 |
lifespan=lifespan,
|
| 31 |
)
|
| 32 |
|
| 33 |
+
app.state.limiter = limiter
|
| 34 |
+
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 35 |
+
|
| 36 |
app.add_middleware(
|
| 37 |
CORSMiddleware,
|
| 38 |
allow_origins=[o.strip() for o in settings.CORS_ORIGINS.split(",")],
|
|
|
|
| 47 |
|
| 48 |
@app.get("/health")
|
| 49 |
async def health_check():
|
| 50 |
+
from sqlalchemy import text
|
| 51 |
+
from app.database import async_session
|
| 52 |
+
from app.cache import get_redis
|
| 53 |
+
|
| 54 |
+
# ๆฐๆฎๅบๆฃๆฅ
|
| 55 |
+
try:
|
| 56 |
+
async with async_session() as db:
|
| 57 |
+
await db.execute(text("SELECT 1"))
|
| 58 |
+
db_status = "ok"
|
| 59 |
+
except Exception as e:
|
| 60 |
+
db_status = f"error: {e}"
|
| 61 |
+
|
| 62 |
+
# Redis ๆฃๆฅ
|
| 63 |
+
try:
|
| 64 |
+
r = await get_redis()
|
| 65 |
+
if r:
|
| 66 |
+
await r.ping()
|
| 67 |
+
redis_status = "ok"
|
| 68 |
+
else:
|
| 69 |
+
redis_status = "disabled"
|
| 70 |
+
except Exception as e:
|
| 71 |
+
redis_status = f"error: {e}"
|
| 72 |
+
|
| 73 |
+
overall = "ok" if db_status == "ok" else "degraded"
|
| 74 |
+
return {
|
| 75 |
+
"status": overall,
|
| 76 |
+
"db": db_status,
|
| 77 |
+
"redis": redis_status,
|
| 78 |
+
}
|
|
@@ -1,6 +1,6 @@
|
|
| 1 |
from datetime import datetime
|
| 2 |
|
| 3 |
-
from sqlalchemy import Boolean, DateTime, Integer, String, func
|
| 4 |
from sqlalchemy.orm import Mapped, mapped_column
|
| 5 |
|
| 6 |
from app.database import Base
|
|
@@ -16,6 +16,11 @@ class Category(Base):
|
|
| 16 |
is_active: Mapped[bool] = mapped_column(Boolean, default=True, comment="ๆฏๅฆๅฏ็จ")
|
| 17 |
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
class CategoryMapping(Base):
|
| 21 |
__tablename__ = "category_mapping"
|
|
@@ -25,3 +30,9 @@ class CategoryMapping(Base):
|
|
| 25 |
source_id: Mapped[int] = mapped_column(Integer, nullable=False, comment="่ตๆบ็ซID")
|
| 26 |
source_type_id: Mapped[int] = mapped_column(Integer, nullable=False, comment="ๆบ็ซๅ็ฑปID")
|
| 27 |
source_type_name: Mapped[str] = mapped_column(String(30), nullable=False, comment="ๆบ็ซๅ็ฑปๅ็งฐ")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from datetime import datetime
|
| 2 |
|
| 3 |
+
from sqlalchemy import Boolean, DateTime, Index, Integer, String, func
|
| 4 |
from sqlalchemy.orm import Mapped, mapped_column
|
| 5 |
|
| 6 |
from app.database import Base
|
|
|
|
| 16 |
is_active: Mapped[bool] = mapped_column(Boolean, default=True, comment="ๆฏๅฆๅฏ็จ")
|
| 17 |
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
|
| 18 |
|
| 19 |
+
__table_args__ = (
|
| 20 |
+
# ๅ็ฑปๆ ๆฅ่ฏข๏ผๆดป่ท + ๆๅบ
|
| 21 |
+
Index("ix_category_active_sort", "is_active", "sort_order"),
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
|
| 25 |
class CategoryMapping(Base):
|
| 26 |
__tablename__ = "category_mapping"
|
|
|
|
| 30 |
source_id: Mapped[int] = mapped_column(Integer, nullable=False, comment="่ตๆบ็ซID")
|
| 31 |
source_type_id: Mapped[int] = mapped_column(Integer, nullable=False, comment="ๆบ็ซๅ็ฑปID")
|
| 32 |
source_type_name: Mapped[str] = mapped_column(String(30), nullable=False, comment="ๆบ็ซๅ็ฑปๅ็งฐ")
|
| 33 |
+
|
| 34 |
+
__table_args__ = (
|
| 35 |
+
# ้้ๅจๅ็ฑปๆ ๅฐๆฅๆพ๏ผsource_id + source_type_id ๅฎไฝๅ็ฑป
|
| 36 |
+
Index("ix_category_mapping_source_type", "source_id", "source_type_id"),
|
| 37 |
+
)
|
| 38 |
+
|
|
@@ -1,6 +1,6 @@
|
|
| 1 |
from datetime import datetime
|
| 2 |
|
| 3 |
-
from sqlalchemy import DateTime, Integer, func
|
| 4 |
from sqlalchemy.orm import Mapped, mapped_column
|
| 5 |
|
| 6 |
from app.database import Base
|
|
@@ -13,3 +13,8 @@ class Favorite(Base):
|
|
| 13 |
user_id: Mapped[int] = mapped_column(Integer, nullable=False, comment="็จๆทID")
|
| 14 |
vod_id: Mapped[int] = mapped_column(Integer, nullable=False, comment="ๅฝฑ็ID")
|
| 15 |
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from datetime import datetime
|
| 2 |
|
| 3 |
+
from sqlalchemy import DateTime, Index, Integer, func
|
| 4 |
from sqlalchemy.orm import Mapped, mapped_column
|
| 5 |
|
| 6 |
from app.database import Base
|
|
|
|
| 13 |
user_id: Mapped[int] = mapped_column(Integer, nullable=False, comment="็จๆทID")
|
| 14 |
vod_id: Mapped[int] = mapped_column(Integer, nullable=False, comment="ๅฝฑ็ID")
|
| 15 |
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
|
| 16 |
+
|
| 17 |
+
__table_args__ = (
|
| 18 |
+
# ๅฏไธๅคๅ็ดขๅผ๏ผ้ฒๆญขๅไธ็จๆท้ๅคๆถ่ๅไธๅฝฑ็๏ผๅๆถๅ ้ๆฅ่ฏข
|
| 19 |
+
Index("uq_favorite_user_vod", "user_id", "vod_id", unique=True),
|
| 20 |
+
)
|
|
@@ -1,6 +1,6 @@
|
|
| 1 |
from datetime import datetime
|
| 2 |
|
| 3 |
-
from sqlalchemy import DateTime, Integer, String, func
|
| 4 |
from sqlalchemy.orm import Mapped, mapped_column
|
| 5 |
|
| 6 |
from app.database import Base
|
|
@@ -19,3 +19,10 @@ class PlayHistory(Base):
|
|
| 19 |
duration: Mapped[int] = mapped_column(Integer, default=0, comment="ๆปๆถ้ฟ(็ง)")
|
| 20 |
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
|
| 21 |
updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from datetime import datetime
|
| 2 |
|
| 3 |
+
from sqlalchemy import DateTime, Index, Integer, String, func
|
| 4 |
from sqlalchemy.orm import Mapped, mapped_column
|
| 5 |
|
| 6 |
from app.database import Base
|
|
|
|
| 19 |
duration: Mapped[int] = mapped_column(Integer, default=0, comment="ๆปๆถ้ฟ(็ง)")
|
| 20 |
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
|
| 21 |
updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())
|
| 22 |
+
|
| 23 |
+
__table_args__ = (
|
| 24 |
+
# ๅๅฒๅ่กจ๏ผๆ็จๆท + ๆถ้ดๅๅบ
|
| 25 |
+
Index("ix_play_history_user_updated", "user_id", "updated_at"),
|
| 26 |
+
# ๆดๆฐๆญๆพ่ฟๅบฆ๏ผuser_id + vod_id ๅฎไฝ่ฎฐๅฝ
|
| 27 |
+
Index("ix_play_history_user_vod", "user_id", "vod_id"),
|
| 28 |
+
)
|
|
@@ -1,6 +1,6 @@
|
|
| 1 |
from datetime import datetime
|
| 2 |
|
| 3 |
-
from sqlalchemy import Boolean, DateTime, Integer, String, func
|
| 4 |
from sqlalchemy.orm import Mapped, mapped_column
|
| 5 |
|
| 6 |
from app.database import Base
|
|
@@ -16,3 +16,8 @@ class SourceHealth(Base):
|
|
| 16 |
response_time_ms: Mapped[int | None] = mapped_column(Integer, comment="ๅๅบๆถ้ด(ms)")
|
| 17 |
error_message: Mapped[str | None] = mapped_column(String, comment="้่ฏฏไฟกๆฏ")
|
| 18 |
checked_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from datetime import datetime
|
| 2 |
|
| 3 |
+
from sqlalchemy import Boolean, DateTime, Index, Integer, String, func
|
| 4 |
from sqlalchemy.orm import Mapped, mapped_column
|
| 5 |
|
| 6 |
from app.database import Base
|
|
|
|
| 16 |
response_time_ms: Mapped[int | None] = mapped_column(Integer, comment="ๅๅบๆถ้ด(ms)")
|
| 17 |
error_message: Mapped[str | None] = mapped_column(String, comment="้่ฏฏไฟกๆฏ")
|
| 18 |
checked_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
|
| 19 |
+
|
| 20 |
+
__table_args__ = (
|
| 21 |
+
# ๆฅ่ฏขๆๆฐๅฅๅบท่ฎฐๅฝ๏ผsource_id + checked_at ๅๅบ
|
| 22 |
+
Index("ix_source_health_source_checked", "source_id", "checked_at"),
|
| 23 |
+
)
|
|
@@ -1,6 +1,6 @@
|
|
| 1 |
from datetime import datetime
|
| 2 |
|
| 3 |
-
from sqlalchemy import DateTime, Integer, String, func
|
| 4 |
from sqlalchemy.orm import Mapped, mapped_column
|
| 5 |
|
| 6 |
from app.database import Base
|
|
@@ -11,7 +11,8 @@ class SyncLog(Base):
|
|
| 11 |
|
| 12 |
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
| 13 |
source_id: Mapped[int] = mapped_column(Integer, nullable=False, comment="่ตๆบ็ซID")
|
| 14 |
-
|
|
|
|
| 15 |
started_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, comment="ๅผๅงๆถ้ด")
|
| 16 |
finished_at: Mapped[datetime | None] = mapped_column(DateTime, comment="็ปๆๆถ้ด")
|
| 17 |
total_fetched: Mapped[int] = mapped_column(Integer, default=0, comment="ๆๅๆปๆฐ")
|
|
@@ -20,3 +21,8 @@ class SyncLog(Base):
|
|
| 20 |
fail_count: Mapped[int] = mapped_column(Integer, default=0, comment="ๅคฑ่ดฅๆฐ")
|
| 21 |
error_message: Mapped[str | None] = mapped_column(String, comment="้่ฏฏไฟกๆฏ")
|
| 22 |
duration_seconds: Mapped[int | None] = mapped_column(Integer, comment="่ๆถ็งๆฐ")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from datetime import datetime
|
| 2 |
|
| 3 |
+
from sqlalchemy import DateTime, Index, Integer, String, func
|
| 4 |
from sqlalchemy.orm import Mapped, mapped_column
|
| 5 |
|
| 6 |
from app.database import Base
|
|
|
|
| 11 |
|
| 12 |
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
| 13 |
source_id: Mapped[int] = mapped_column(Integer, nullable=False, comment="่ตๆบ็ซID")
|
| 14 |
+
range_type: Mapped[str] = mapped_column(String(20), nullable=False, default="daily", comment="ๅๆญฅ่ๅด: all/monthly/weekly/daily")
|
| 15 |
+
status: Mapped[str] = mapped_column(String(20), nullable=False, comment="running/success/failed/skipped")
|
| 16 |
started_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, comment="ๅผๅงๆถ้ด")
|
| 17 |
finished_at: Mapped[datetime | None] = mapped_column(DateTime, comment="็ปๆๆถ้ด")
|
| 18 |
total_fetched: Mapped[int] = mapped_column(Integer, default=0, comment="ๆๅๆปๆฐ")
|
|
|
|
| 21 |
fail_count: Mapped[int] = mapped_column(Integer, default=0, comment="ๅคฑ่ดฅๆฐ")
|
| 22 |
error_message: Mapped[str | None] = mapped_column(String, comment="้่ฏฏไฟกๆฏ")
|
| 23 |
duration_seconds: Mapped[int | None] = mapped_column(Integer, comment="่ๆถ็งๆฐ")
|
| 24 |
+
|
| 25 |
+
__table_args__ = (
|
| 26 |
+
# ๅๆญฅๆฅๅฟๅ่กจ๏ผๆ source_id ่ฟๆปค + ๆถ้ดๅๅบ
|
| 27 |
+
Index("ix_sync_log_source_started", "source_id", "started_at"),
|
| 28 |
+
)
|
|
@@ -1,6 +1,6 @@
|
|
| 1 |
from datetime import datetime
|
| 2 |
|
| 3 |
-
from sqlalchemy import Boolean, DateTime, Float, Integer, String, Text, func
|
| 4 |
from sqlalchemy.orm import Mapped, mapped_column
|
| 5 |
|
| 6 |
from app.database import Base
|
|
@@ -32,3 +32,16 @@ class Vod(Base):
|
|
| 32 |
view_count: Mapped[int] = mapped_column(Integer, default=0, comment="ๆญๆพๆฌกๆฐ")
|
| 33 |
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
|
| 34 |
updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from datetime import datetime
|
| 2 |
|
| 3 |
+
from sqlalchemy import Boolean, DateTime, Float, Index, Integer, String, Text, func
|
| 4 |
from sqlalchemy.orm import Mapped, mapped_column
|
| 5 |
|
| 6 |
from app.database import Base
|
|
|
|
| 32 |
view_count: Mapped[int] = mapped_column(Integer, default=0, comment="ๆญๆพๆฌกๆฐ")
|
| 33 |
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
|
| 34 |
updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())
|
| 35 |
+
|
| 36 |
+
__table_args__ = (
|
| 37 |
+
# ๅฝฑ็ๅ่กจ๏ผๆๅ็ฑป่ฟๆปค + ๆถ้ดๆๅบ๏ผๆๅธธ็จๆฅ่ฏข๏ผ
|
| 38 |
+
Index("ix_vod_category_updated", "category_id", "updated_at"),
|
| 39 |
+
# ้่็ถๆ + ๆถ้ดๆๅบ๏ผ็จๆท็ซฏๅ่กจ WHERE is_hidden=0 ORDER BY updated_at๏ผ
|
| 40 |
+
Index("ix_vod_hidden_updated", "is_hidden", "updated_at"),
|
| 41 |
+
# ๆจ่ๅ่กจ๏ผis_recommended + score ๆๅบ
|
| 42 |
+
Index("ix_vod_recommended_score", "is_recommended", "score"),
|
| 43 |
+
# ๅป้ๆฅ่ฏข๏ผๆๅ็งฐ+ๅนดไปฝ
|
| 44 |
+
Index("ix_vod_name_year", "name", "year"),
|
| 45 |
+
# ๅป้ๆฅ่ฏข๏ผๆ douban_id๏ผๅฏไธๆง่พ้ซ๏ผๅๅๅณๅฏ๏ผ
|
| 46 |
+
Index("ix_vod_douban_id", "douban_id"),
|
| 47 |
+
)
|
|
@@ -1,6 +1,6 @@
|
|
| 1 |
from datetime import datetime
|
| 2 |
|
| 3 |
-
from sqlalchemy import Boolean, DateTime, Integer, String, func
|
| 4 |
from sqlalchemy.orm import Mapped, mapped_column
|
| 5 |
|
| 6 |
from app.database import Base
|
|
@@ -20,3 +20,10 @@ class VodSource(Base):
|
|
| 20 |
last_check_at: Mapped[datetime | None] = mapped_column(DateTime, comment="ๅฏ็จๆงๆฃๆฅๆถ้ด")
|
| 21 |
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
|
| 22 |
updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from datetime import datetime
|
| 2 |
|
| 3 |
+
from sqlalchemy import Boolean, DateTime, Index, Integer, String, func
|
| 4 |
from sqlalchemy.orm import Mapped, mapped_column
|
| 5 |
|
| 6 |
from app.database import Base
|
|
|
|
| 20 |
last_check_at: Mapped[datetime | None] = mapped_column(DateTime, comment="ๅฏ็จๆงๆฃๆฅๆถ้ด")
|
| 21 |
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
|
| 22 |
updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())
|
| 23 |
+
|
| 24 |
+
__table_args__ = (
|
| 25 |
+
# ๅฝฑ็่ฏฆๆ
้กตๅ ่ฝฝๆญๆพๆบ๏ผๆ้ซ้ขๆฅ่ฏข๏ผ
|
| 26 |
+
Index("ix_vod_source_vod_id", "vod_id"),
|
| 27 |
+
# ้้ๅจๅป้๏ผsource_id + source_vod_id ๅฎไฝๅทฒๆ่ฎฐๅฝ
|
| 28 |
+
Index("ix_vod_source_source_vod", "source_id", "source_vod_id"),
|
| 29 |
+
)
|
|
@@ -8,6 +8,12 @@ from app.database import get_db
|
|
| 8 |
from app.dependencies import require_permission
|
| 9 |
from app.models.admin import Admin
|
| 10 |
from app.models.role import AdminRole, Role
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
from app.schemas.common import ApiResponse, PaginatedData
|
| 12 |
from app.utils.auth import hash_password
|
| 13 |
|
|
@@ -29,15 +35,27 @@ async def list_admins(
|
|
| 29 |
)
|
| 30 |
admins = result.scalars().all()
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
roles_result = await db.execute(
|
| 35 |
-
select(
|
|
|
|
|
|
|
| 36 |
)
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
items.append({
|
| 39 |
"id": a.id, "username": a.username, "nickname": a.nickname,
|
| 40 |
-
"avatar": a.avatar, "is_active": a.is_active,
|
|
|
|
| 41 |
"last_login_at": str(a.last_login_at) if a.last_login_at else None,
|
| 42 |
"created_at": str(a.created_at) if a.created_at else None,
|
| 43 |
})
|
|
@@ -49,23 +67,18 @@ async def list_admins(
|
|
| 49 |
|
| 50 |
@router.post("", response_model=ApiResponse)
|
| 51 |
async def create_admin(
|
| 52 |
-
|
| 53 |
admin: Admin = Depends(require_permission("admin:create")),
|
| 54 |
db: AsyncSession = Depends(get_db),
|
| 55 |
):
|
| 56 |
-
|
| 57 |
-
password = body.get("password")
|
| 58 |
-
if not username or not password:
|
| 59 |
-
return ApiResponse.fail(40001, "็จๆทๅๅๅฏ็ ๅฟ
ๅกซ")
|
| 60 |
-
|
| 61 |
-
existing = await db.execute(select(Admin).where(Admin.username == username))
|
| 62 |
if existing.scalar_one_or_none():
|
| 63 |
return ApiResponse.fail(40002, "็จๆทๅๅทฒๅญๅจ")
|
| 64 |
|
| 65 |
new_admin = Admin(
|
| 66 |
-
username=username,
|
| 67 |
-
password_hash=hash_password(password),
|
| 68 |
-
nickname=
|
| 69 |
)
|
| 70 |
db.add(new_admin)
|
| 71 |
await db.flush()
|
|
@@ -75,7 +88,7 @@ async def create_admin(
|
|
| 75 |
@router.put("/{admin_id}", response_model=ApiResponse)
|
| 76 |
async def update_admin(
|
| 77 |
admin_id: int,
|
| 78 |
-
|
| 79 |
admin: Admin = Depends(require_permission("admin:update")),
|
| 80 |
db: AsyncSession = Depends(get_db),
|
| 81 |
):
|
|
@@ -84,10 +97,8 @@ async def update_admin(
|
|
| 84 |
if not target:
|
| 85 |
return ApiResponse.fail(40401, "็ฎก็ๅไธๅญๅจ")
|
| 86 |
|
| 87 |
-
|
| 88 |
-
target
|
| 89 |
-
if "is_active" in body:
|
| 90 |
-
target.is_active = body["is_active"]
|
| 91 |
return ApiResponse.ok()
|
| 92 |
|
| 93 |
|
|
@@ -110,32 +121,30 @@ async def delete_admin(
|
|
| 110 |
@router.put("/{admin_id}/reset-password", response_model=ApiResponse)
|
| 111 |
async def reset_password(
|
| 112 |
admin_id: int,
|
| 113 |
-
|
| 114 |
admin: Admin = Depends(require_permission("admin:btn:reset_pwd")),
|
| 115 |
db: AsyncSession = Depends(get_db),
|
| 116 |
):
|
| 117 |
-
new_password = body.get("password", "123456")
|
| 118 |
result = await db.execute(select(Admin).where(Admin.id == admin_id))
|
| 119 |
target = result.scalar_one_or_none()
|
| 120 |
if not target:
|
| 121 |
return ApiResponse.fail(40401, "็ฎก็ๅไธๅญๅจ")
|
| 122 |
-
target.password_hash = hash_password(
|
| 123 |
return ApiResponse.ok()
|
| 124 |
|
| 125 |
|
| 126 |
@router.put("/{admin_id}/assign-roles", response_model=ApiResponse)
|
| 127 |
async def assign_roles(
|
| 128 |
admin_id: int,
|
| 129 |
-
|
| 130 |
admin: Admin = Depends(require_permission("admin:btn:assign_role")),
|
| 131 |
db: AsyncSession = Depends(get_db),
|
| 132 |
):
|
| 133 |
-
role_ids = body.get("role_ids", [])
|
| 134 |
result = await db.execute(select(Admin).where(Admin.id == admin_id))
|
| 135 |
if not result.scalar_one_or_none():
|
| 136 |
return ApiResponse.fail(40401, "็ฎก็ๅไธๅญๅจ")
|
| 137 |
|
| 138 |
await db.execute(AdminRole.__table__.delete().where(AdminRole.admin_id == admin_id))
|
| 139 |
-
for rid in role_ids:
|
| 140 |
db.add(AdminRole(admin_id=admin_id, role_id=rid))
|
| 141 |
return ApiResponse.ok()
|
|
|
|
| 8 |
from app.dependencies import require_permission
|
| 9 |
from app.models.admin import Admin
|
| 10 |
from app.models.role import AdminRole, Role
|
| 11 |
+
from app.schemas.admin.admin_mgmt import (
|
| 12 |
+
AdminCreateRequest,
|
| 13 |
+
AdminUpdateRequest,
|
| 14 |
+
AdminResetPasswordRequest,
|
| 15 |
+
AdminAssignRolesRequest,
|
| 16 |
+
)
|
| 17 |
from app.schemas.common import ApiResponse, PaginatedData
|
| 18 |
from app.utils.auth import hash_password
|
| 19 |
|
|
|
|
| 35 |
)
|
| 36 |
admins = result.scalars().all()
|
| 37 |
|
| 38 |
+
if admins:
|
| 39 |
+
admin_ids = [a.id for a in admins]
|
| 40 |
roles_result = await db.execute(
|
| 41 |
+
select(AdminRole.admin_id, Role.code)
|
| 42 |
+
.join(Role, Role.id == AdminRole.role_id)
|
| 43 |
+
.where(AdminRole.admin_id.in_(admin_ids))
|
| 44 |
)
|
| 45 |
+
admin_roles_map: dict[int, list[str]] = {}
|
| 46 |
+
for admin_id, role_code in roles_result.all():
|
| 47 |
+
if admin_id not in admin_roles_map:
|
| 48 |
+
admin_roles_map[admin_id] = []
|
| 49 |
+
admin_roles_map[admin_id].append(role_code)
|
| 50 |
+
else:
|
| 51 |
+
admin_roles_map = {}
|
| 52 |
+
|
| 53 |
+
items = []
|
| 54 |
+
for a in admins:
|
| 55 |
items.append({
|
| 56 |
"id": a.id, "username": a.username, "nickname": a.nickname,
|
| 57 |
+
"avatar": a.avatar, "is_active": a.is_active,
|
| 58 |
+
"roles": admin_roles_map.get(a.id, []),
|
| 59 |
"last_login_at": str(a.last_login_at) if a.last_login_at else None,
|
| 60 |
"created_at": str(a.created_at) if a.created_at else None,
|
| 61 |
})
|
|
|
|
| 67 |
|
| 68 |
@router.post("", response_model=ApiResponse)
|
| 69 |
async def create_admin(
|
| 70 |
+
req: AdminCreateRequest,
|
| 71 |
admin: Admin = Depends(require_permission("admin:create")),
|
| 72 |
db: AsyncSession = Depends(get_db),
|
| 73 |
):
|
| 74 |
+
existing = await db.execute(select(Admin).where(Admin.username == req.username))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
if existing.scalar_one_or_none():
|
| 76 |
return ApiResponse.fail(40002, "็จๆทๅๅทฒๅญๅจ")
|
| 77 |
|
| 78 |
new_admin = Admin(
|
| 79 |
+
username=req.username,
|
| 80 |
+
password_hash=hash_password(req.password),
|
| 81 |
+
nickname=req.nickname,
|
| 82 |
)
|
| 83 |
db.add(new_admin)
|
| 84 |
await db.flush()
|
|
|
|
| 88 |
@router.put("/{admin_id}", response_model=ApiResponse)
|
| 89 |
async def update_admin(
|
| 90 |
admin_id: int,
|
| 91 |
+
req: AdminUpdateRequest,
|
| 92 |
admin: Admin = Depends(require_permission("admin:update")),
|
| 93 |
db: AsyncSession = Depends(get_db),
|
| 94 |
):
|
|
|
|
| 97 |
if not target:
|
| 98 |
return ApiResponse.fail(40401, "็ฎก็ๅไธๅญๅจ")
|
| 99 |
|
| 100 |
+
for field, value in req.model_dump(exclude_unset=True).items():
|
| 101 |
+
setattr(target, field, value)
|
|
|
|
|
|
|
| 102 |
return ApiResponse.ok()
|
| 103 |
|
| 104 |
|
|
|
|
| 121 |
@router.put("/{admin_id}/reset-password", response_model=ApiResponse)
|
| 122 |
async def reset_password(
|
| 123 |
admin_id: int,
|
| 124 |
+
req: AdminResetPasswordRequest,
|
| 125 |
admin: Admin = Depends(require_permission("admin:btn:reset_pwd")),
|
| 126 |
db: AsyncSession = Depends(get_db),
|
| 127 |
):
|
|
|
|
| 128 |
result = await db.execute(select(Admin).where(Admin.id == admin_id))
|
| 129 |
target = result.scalar_one_or_none()
|
| 130 |
if not target:
|
| 131 |
return ApiResponse.fail(40401, "็ฎก็ๅไธๅญๅจ")
|
| 132 |
+
target.password_hash = hash_password(req.password)
|
| 133 |
return ApiResponse.ok()
|
| 134 |
|
| 135 |
|
| 136 |
@router.put("/{admin_id}/assign-roles", response_model=ApiResponse)
|
| 137 |
async def assign_roles(
|
| 138 |
admin_id: int,
|
| 139 |
+
req: AdminAssignRolesRequest,
|
| 140 |
admin: Admin = Depends(require_permission("admin:btn:assign_role")),
|
| 141 |
db: AsyncSession = Depends(get_db),
|
| 142 |
):
|
|
|
|
| 143 |
result = await db.execute(select(Admin).where(Admin.id == admin_id))
|
| 144 |
if not result.scalar_one_or_none():
|
| 145 |
return ApiResponse.fail(40401, "็ฎก็ๅไธๅญๅจ")
|
| 146 |
|
| 147 |
await db.execute(AdminRole.__table__.delete().where(AdminRole.admin_id == admin_id))
|
| 148 |
+
for rid in req.role_ids:
|
| 149 |
db.add(AdminRole(admin_id=admin_id, role_id=rid))
|
| 150 |
return ApiResponse.ok()
|
|
@@ -1,8 +1,9 @@
|
|
| 1 |
-
from fastapi import APIRouter, Depends
|
| 2 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 3 |
|
| 4 |
from app.database import get_db
|
| 5 |
from app.dependencies import get_current_admin
|
|
|
|
| 6 |
from app.schemas.admin.auth import LoginRequest, LoginResponse, UserInfoResponse
|
| 7 |
from app.schemas.common import ApiResponse
|
| 8 |
from app.services import auth_admin
|
|
@@ -12,7 +13,8 @@ router = APIRouter()
|
|
| 12 |
|
| 13 |
|
| 14 |
@router.post("/login", response_model=ApiResponse)
|
| 15 |
-
|
|
|
|
| 16 |
admin = await auth_admin.authenticate_admin(db, req.username, req.password)
|
| 17 |
if not admin:
|
| 18 |
return ApiResponse.fail(40001, "็จๆทๅๆๅฏ็ ้่ฏฏ")
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, Request
|
| 2 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 3 |
|
| 4 |
from app.database import get_db
|
| 5 |
from app.dependencies import get_current_admin
|
| 6 |
+
from app.limiter import limiter
|
| 7 |
from app.schemas.admin.auth import LoginRequest, LoginResponse, UserInfoResponse
|
| 8 |
from app.schemas.common import ApiResponse
|
| 9 |
from app.services import auth_admin
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
@router.post("/login", response_model=ApiResponse)
|
| 16 |
+
@limiter.limit("10/minute")
|
| 17 |
+
async def login(request: Request, req: LoginRequest, db: AsyncSession = Depends(get_db)):
|
| 18 |
admin = await auth_admin.authenticate_admin(db, req.username, req.password)
|
| 19 |
if not admin:
|
| 20 |
return ApiResponse.fail(40001, "็จๆทๅๆๅฏ็ ้่ฏฏ")
|
|
@@ -2,11 +2,13 @@ from fastapi import APIRouter, Depends, Query
|
|
| 2 |
from sqlalchemy import delete as sa_delete, func, select
|
| 3 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 4 |
|
|
|
|
| 5 |
from app.database import get_db
|
| 6 |
from app.dependencies import get_current_admin, require_permission
|
| 7 |
from app.models.admin import Admin
|
| 8 |
from app.models.category import Category, CategoryMapping
|
| 9 |
from app.models.source_site import SourceSite
|
|
|
|
| 10 |
from app.schemas.common import ApiResponse, PaginatedData
|
| 11 |
|
| 12 |
router = APIRouter()
|
|
@@ -36,7 +38,7 @@ async def list_categories(
|
|
| 36 |
@router.put("/{category_id}", response_model=ApiResponse)
|
| 37 |
async def update_category(
|
| 38 |
category_id: int,
|
| 39 |
-
|
| 40 |
admin: Admin = Depends(require_permission("category:update")),
|
| 41 |
db: AsyncSession = Depends(get_db),
|
| 42 |
):
|
|
@@ -45,12 +47,11 @@ async def update_category(
|
|
| 45 |
if not cat:
|
| 46 |
return ApiResponse.fail(40401, "ๅ็ฑปไธๅญๅจ")
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
if field in body:
|
| 51 |
-
setattr(cat, field, body[field])
|
| 52 |
|
| 53 |
await db.flush()
|
|
|
|
| 54 |
return ApiResponse.ok()
|
| 55 |
|
| 56 |
|
|
@@ -67,19 +68,27 @@ async def list_mappings(
|
|
| 67 |
result = await db.execute(query.order_by(CategoryMapping.source_id, CategoryMapping.source_type_id))
|
| 68 |
mappings = result.scalars().all()
|
| 69 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
items = []
|
| 71 |
for m in mappings:
|
| 72 |
-
cat_result = await db.execute(select(Category).where(Category.id == m.category_id))
|
| 73 |
-
cat = cat_result.scalar_one_or_none()
|
| 74 |
-
source_result = await db.execute(select(SourceSite).where(SourceSite.id == m.source_id))
|
| 75 |
-
source = source_result.scalar_one_or_none()
|
| 76 |
-
|
| 77 |
items.append({
|
| 78 |
"id": m.id,
|
| 79 |
"category_id": m.category_id,
|
| 80 |
-
"category_name":
|
| 81 |
"source_id": m.source_id,
|
| 82 |
-
"source_name":
|
| 83 |
"source_type_id": m.source_type_id,
|
| 84 |
"source_type_name": m.source_type_name,
|
| 85 |
})
|
|
@@ -89,33 +98,27 @@ async def list_mappings(
|
|
| 89 |
|
| 90 |
@router.put("/mapping", response_model=ApiResponse)
|
| 91 |
async def update_mappings(
|
| 92 |
-
|
| 93 |
admin: Admin = Depends(require_permission("category:btn:map")),
|
| 94 |
db: AsyncSession = Depends(get_db),
|
| 95 |
):
|
| 96 |
-
|
| 97 |
-
if not mappings_data:
|
| 98 |
-
return ApiResponse.fail(40001, "mappings data is required")
|
| 99 |
-
|
| 100 |
-
source_id = body.get("source_id")
|
| 101 |
-
if not source_id:
|
| 102 |
-
return ApiResponse.fail(40002, "source_id is required")
|
| 103 |
-
|
| 104 |
-
source_result = await db.execute(select(SourceSite).where(SourceSite.id == source_id))
|
| 105 |
if not source_result.scalar_one_or_none():
|
| 106 |
return ApiResponse.fail(40401, "ๆบ็ซไธๅญๅจ")
|
| 107 |
|
| 108 |
-
await db.execute(sa_delete(CategoryMapping).where(CategoryMapping.source_id == source_id))
|
| 109 |
await db.flush()
|
| 110 |
|
| 111 |
-
for m in
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
| 114 |
mapping = CategoryMapping(
|
| 115 |
-
category_id=m
|
| 116 |
-
source_id=source_id,
|
| 117 |
-
source_type_id=m
|
| 118 |
-
source_type_name=
|
| 119 |
)
|
| 120 |
db.add(mapping)
|
| 121 |
|
|
|
|
| 2 |
from sqlalchemy import delete as sa_delete, func, select
|
| 3 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 4 |
|
| 5 |
+
from app.cache import invalidate_category_cache
|
| 6 |
from app.database import get_db
|
| 7 |
from app.dependencies import get_current_admin, require_permission
|
| 8 |
from app.models.admin import Admin
|
| 9 |
from app.models.category import Category, CategoryMapping
|
| 10 |
from app.models.source_site import SourceSite
|
| 11 |
+
from app.schemas.admin.category import CategoryUpdateRequest, CategoryMappingUpdateRequest
|
| 12 |
from app.schemas.common import ApiResponse, PaginatedData
|
| 13 |
|
| 14 |
router = APIRouter()
|
|
|
|
| 38 |
@router.put("/{category_id}", response_model=ApiResponse)
|
| 39 |
async def update_category(
|
| 40 |
category_id: int,
|
| 41 |
+
req: CategoryUpdateRequest,
|
| 42 |
admin: Admin = Depends(require_permission("category:update")),
|
| 43 |
db: AsyncSession = Depends(get_db),
|
| 44 |
):
|
|
|
|
| 47 |
if not cat:
|
| 48 |
return ApiResponse.fail(40401, "ๅ็ฑปไธๅญๅจ")
|
| 49 |
|
| 50 |
+
for field, value in req.model_dump(exclude_unset=True).items():
|
| 51 |
+
setattr(cat, field, value)
|
|
|
|
|
|
|
| 52 |
|
| 53 |
await db.flush()
|
| 54 |
+
await invalidate_category_cache()
|
| 55 |
return ApiResponse.ok()
|
| 56 |
|
| 57 |
|
|
|
|
| 68 |
result = await db.execute(query.order_by(CategoryMapping.source_id, CategoryMapping.source_type_id))
|
| 69 |
mappings = result.scalars().all()
|
| 70 |
|
| 71 |
+
if mappings:
|
| 72 |
+
cat_ids = list({m.category_id for m in mappings})
|
| 73 |
+
source_ids = list({m.source_id for m in mappings})
|
| 74 |
+
|
| 75 |
+
cat_result = await db.execute(select(Category.id, Category.name).where(Category.id.in_(cat_ids)))
|
| 76 |
+
cat_map = {row[0]: row[1] for row in cat_result.all()}
|
| 77 |
+
|
| 78 |
+
source_result = await db.execute(select(SourceSite.id, SourceSite.name).where(SourceSite.id.in_(source_ids)))
|
| 79 |
+
source_map = {row[0]: row[1] for row in source_result.all()}
|
| 80 |
+
else:
|
| 81 |
+
cat_map = {}
|
| 82 |
+
source_map = {}
|
| 83 |
+
|
| 84 |
items = []
|
| 85 |
for m in mappings:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
items.append({
|
| 87 |
"id": m.id,
|
| 88 |
"category_id": m.category_id,
|
| 89 |
+
"category_name": cat_map.get(m.category_id),
|
| 90 |
"source_id": m.source_id,
|
| 91 |
+
"source_name": source_map.get(m.source_id),
|
| 92 |
"source_type_id": m.source_type_id,
|
| 93 |
"source_type_name": m.source_type_name,
|
| 94 |
})
|
|
|
|
| 98 |
|
| 99 |
@router.put("/mapping", response_model=ApiResponse)
|
| 100 |
async def update_mappings(
|
| 101 |
+
req: CategoryMappingUpdateRequest,
|
| 102 |
admin: Admin = Depends(require_permission("category:btn:map")),
|
| 103 |
db: AsyncSession = Depends(get_db),
|
| 104 |
):
|
| 105 |
+
source_result = await db.execute(select(SourceSite).where(SourceSite.id == req.source_id))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
if not source_result.scalar_one_or_none():
|
| 107 |
return ApiResponse.fail(40401, "ๆบ็ซไธๅญๅจ")
|
| 108 |
|
| 109 |
+
await db.execute(sa_delete(CategoryMapping).where(CategoryMapping.source_id == req.source_id))
|
| 110 |
await db.flush()
|
| 111 |
|
| 112 |
+
cat_ids = list({m.category_id for m in req.mappings})
|
| 113 |
+
cat_result = await db.execute(select(Category.id, Category.name).where(Category.id.in_(cat_ids)))
|
| 114 |
+
cat_map = {row[0]: row[1] for row in cat_result.all()}
|
| 115 |
+
|
| 116 |
+
for m in req.mappings:
|
| 117 |
mapping = CategoryMapping(
|
| 118 |
+
category_id=m.category_id,
|
| 119 |
+
source_id=req.source_id,
|
| 120 |
+
source_type_id=m.source_type_id,
|
| 121 |
+
source_type_name=cat_map.get(m.category_id, str(m.source_type_id)),
|
| 122 |
)
|
| 123 |
db.add(mapping)
|
| 124 |
|
|
@@ -7,6 +7,7 @@ from app.dependencies import require_permission
|
|
| 7 |
from app.models.admin import Admin
|
| 8 |
from app.models.permission import Permission, RolePermission
|
| 9 |
from app.models.role import AdminRole, Role
|
|
|
|
| 10 |
from app.schemas.common import ApiResponse, PaginatedData
|
| 11 |
|
| 12 |
router = APIRouter()
|
|
@@ -20,16 +21,24 @@ async def list_roles(
|
|
| 20 |
result = await db.execute(select(Role).order_by(Role.id))
|
| 21 |
roles = result.scalars().all()
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
items = []
|
| 24 |
for r in roles:
|
| 25 |
-
perm_count = await db.execute(
|
| 26 |
-
select(func.count(RolePermission.id)).where(RolePermission.role_id == r.id)
|
| 27 |
-
)
|
| 28 |
items.append({
|
| 29 |
"id": r.id, "name": r.name, "code": r.code,
|
| 30 |
"description": r.description, "is_builtin": r.is_builtin,
|
| 31 |
"status": r.status,
|
| 32 |
-
"permission_count":
|
| 33 |
})
|
| 34 |
|
| 35 |
return ApiResponse.ok(items)
|
|
@@ -37,20 +46,15 @@ async def list_roles(
|
|
| 37 |
|
| 38 |
@router.post("", response_model=ApiResponse)
|
| 39 |
async def create_role(
|
| 40 |
-
|
| 41 |
admin: Admin = Depends(require_permission("role:create")),
|
| 42 |
db: AsyncSession = Depends(get_db),
|
| 43 |
):
|
| 44 |
-
|
| 45 |
-
code = body.get("code")
|
| 46 |
-
if not name or not code:
|
| 47 |
-
return ApiResponse.fail(40001, "ๅ็งฐๅ็ผ็ ๅฟ
ๅกซ")
|
| 48 |
-
|
| 49 |
-
existing = await db.execute(select(Role).where(Role.code == code))
|
| 50 |
if existing.scalar_one_or_none():
|
| 51 |
return ApiResponse.fail(40002, "่ง่ฒ็ผ็ ๅทฒๅญๅจ")
|
| 52 |
|
| 53 |
-
role = Role(name=name, code=code, description=
|
| 54 |
db.add(role)
|
| 55 |
await db.flush()
|
| 56 |
return ApiResponse.ok({"id": role.id})
|
|
@@ -59,7 +63,7 @@ async def create_role(
|
|
| 59 |
@router.put("/{role_id}", response_model=ApiResponse)
|
| 60 |
async def update_role(
|
| 61 |
role_id: int,
|
| 62 |
-
|
| 63 |
admin: Admin = Depends(require_permission("role:update")),
|
| 64 |
db: AsyncSession = Depends(get_db),
|
| 65 |
):
|
|
@@ -68,12 +72,8 @@ async def update_role(
|
|
| 68 |
if not role:
|
| 69 |
return ApiResponse.fail(40401, "่ง่ฒไธๅญๅจ")
|
| 70 |
|
| 71 |
-
|
| 72 |
-
role
|
| 73 |
-
if "description" in body:
|
| 74 |
-
role.description = body["description"]
|
| 75 |
-
if "status" in body:
|
| 76 |
-
role.status = body["status"]
|
| 77 |
return ApiResponse.ok()
|
| 78 |
|
| 79 |
|
|
@@ -99,16 +99,15 @@ async def delete_role(
|
|
| 99 |
@router.put("/{role_id}/permissions", response_model=ApiResponse)
|
| 100 |
async def assign_permissions(
|
| 101 |
role_id: int,
|
| 102 |
-
|
| 103 |
admin: Admin = Depends(require_permission("role:btn:assign_perm")),
|
| 104 |
db: AsyncSession = Depends(get_db),
|
| 105 |
):
|
| 106 |
-
perm_ids = body.get("permission_ids", [])
|
| 107 |
result = await db.execute(select(Role).where(Role.id == role_id))
|
| 108 |
if not result.scalar_one_or_none():
|
| 109 |
return ApiResponse.fail(40401, "่ง่ฒไธๅญๅจ")
|
| 110 |
|
| 111 |
await db.execute(RolePermission.__table__.delete().where(RolePermission.role_id == role_id))
|
| 112 |
-
for pid in
|
| 113 |
db.add(RolePermission(role_id=role_id, permission_id=pid))
|
| 114 |
return ApiResponse.ok()
|
|
|
|
| 7 |
from app.models.admin import Admin
|
| 8 |
from app.models.permission import Permission, RolePermission
|
| 9 |
from app.models.role import AdminRole, Role
|
| 10 |
+
from app.schemas.admin.role_mgmt import RoleCreateRequest, RoleUpdateRequest, RoleAssignPermissionsRequest
|
| 11 |
from app.schemas.common import ApiResponse, PaginatedData
|
| 12 |
|
| 13 |
router = APIRouter()
|
|
|
|
| 21 |
result = await db.execute(select(Role).order_by(Role.id))
|
| 22 |
roles = result.scalars().all()
|
| 23 |
|
| 24 |
+
if roles:
|
| 25 |
+
role_ids = [r.id for r in roles]
|
| 26 |
+
perm_count_result = await db.execute(
|
| 27 |
+
select(RolePermission.role_id, func.count(RolePermission.id))
|
| 28 |
+
.where(RolePermission.role_id.in_(role_ids))
|
| 29 |
+
.group_by(RolePermission.role_id)
|
| 30 |
+
)
|
| 31 |
+
perm_count_map = {row[0]: row[1] for row in perm_count_result.all()}
|
| 32 |
+
else:
|
| 33 |
+
perm_count_map = {}
|
| 34 |
+
|
| 35 |
items = []
|
| 36 |
for r in roles:
|
|
|
|
|
|
|
|
|
|
| 37 |
items.append({
|
| 38 |
"id": r.id, "name": r.name, "code": r.code,
|
| 39 |
"description": r.description, "is_builtin": r.is_builtin,
|
| 40 |
"status": r.status,
|
| 41 |
+
"permission_count": perm_count_map.get(r.id, 0),
|
| 42 |
})
|
| 43 |
|
| 44 |
return ApiResponse.ok(items)
|
|
|
|
| 46 |
|
| 47 |
@router.post("", response_model=ApiResponse)
|
| 48 |
async def create_role(
|
| 49 |
+
req: RoleCreateRequest,
|
| 50 |
admin: Admin = Depends(require_permission("role:create")),
|
| 51 |
db: AsyncSession = Depends(get_db),
|
| 52 |
):
|
| 53 |
+
existing = await db.execute(select(Role).where(Role.code == req.code))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
if existing.scalar_one_or_none():
|
| 55 |
return ApiResponse.fail(40002, "่ง่ฒ็ผ็ ๅทฒๅญๅจ")
|
| 56 |
|
| 57 |
+
role = Role(name=req.name, code=req.code, description=req.description)
|
| 58 |
db.add(role)
|
| 59 |
await db.flush()
|
| 60 |
return ApiResponse.ok({"id": role.id})
|
|
|
|
| 63 |
@router.put("/{role_id}", response_model=ApiResponse)
|
| 64 |
async def update_role(
|
| 65 |
role_id: int,
|
| 66 |
+
req: RoleUpdateRequest,
|
| 67 |
admin: Admin = Depends(require_permission("role:update")),
|
| 68 |
db: AsyncSession = Depends(get_db),
|
| 69 |
):
|
|
|
|
| 72 |
if not role:
|
| 73 |
return ApiResponse.fail(40401, "่ง่ฒไธๅญๅจ")
|
| 74 |
|
| 75 |
+
for field, value in req.model_dump(exclude_unset=True).items():
|
| 76 |
+
setattr(role, field, value)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
return ApiResponse.ok()
|
| 78 |
|
| 79 |
|
|
|
|
| 99 |
@router.put("/{role_id}/permissions", response_model=ApiResponse)
|
| 100 |
async def assign_permissions(
|
| 101 |
role_id: int,
|
| 102 |
+
req: RoleAssignPermissionsRequest,
|
| 103 |
admin: Admin = Depends(require_permission("role:btn:assign_perm")),
|
| 104 |
db: AsyncSession = Depends(get_db),
|
| 105 |
):
|
|
|
|
| 106 |
result = await db.execute(select(Role).where(Role.id == role_id))
|
| 107 |
if not result.scalar_one_or_none():
|
| 108 |
return ApiResponse.fail(40401, "่ง่ฒไธๅญๅจ")
|
| 109 |
|
| 110 |
await db.execute(RolePermission.__table__.delete().where(RolePermission.role_id == role_id))
|
| 111 |
+
for pid in req.permission_ids:
|
| 112 |
db.add(RolePermission(role_id=role_id, permission_id=pid))
|
| 113 |
return ApiResponse.ok()
|
|
@@ -1,14 +1,16 @@
|
|
| 1 |
import httpx
|
| 2 |
|
| 3 |
from fastapi import APIRouter, Depends, Query
|
| 4 |
-
from sqlalchemy import func, select
|
| 5 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 6 |
|
| 7 |
from app.database import get_db
|
| 8 |
-
from app.dependencies import
|
| 9 |
from app.models.admin import Admin
|
| 10 |
from app.models.source_site import SourceSite
|
|
|
|
| 11 |
from app.schemas.common import ApiResponse, PaginatedData
|
|
|
|
| 12 |
|
| 13 |
router = APIRouter()
|
| 14 |
|
|
@@ -24,12 +26,22 @@ async def list_sources(
|
|
| 24 |
total = count_result.scalar() or 0
|
| 25 |
|
| 26 |
result = await db.execute(
|
| 27 |
-
select(SourceSite)
|
|
|
|
|
|
|
|
|
|
| 28 |
)
|
| 29 |
sources = result.scalars().all()
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
items = []
|
| 32 |
for s in sources:
|
|
|
|
| 33 |
items.append({
|
| 34 |
"id": s.id,
|
| 35 |
"name": s.name,
|
|
@@ -47,6 +59,7 @@ async def list_sources(
|
|
| 47 |
"total_count": s.total_count,
|
| 48 |
"sort_order": s.sort_order,
|
| 49 |
"remark": s.remark,
|
|
|
|
| 50 |
})
|
| 51 |
|
| 52 |
return ApiResponse.ok(
|
|
@@ -54,6 +67,33 @@ async def list_sources(
|
|
| 54 |
)
|
| 55 |
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
@router.get("/{source_id}", response_model=ApiResponse)
|
| 58 |
async def get_source(
|
| 59 |
source_id: int,
|
|
@@ -65,6 +105,7 @@ async def get_source(
|
|
| 65 |
if not source:
|
| 66 |
return ApiResponse.fail(40401, "ๆบ็ซไธๅญๅจ")
|
| 67 |
|
|
|
|
| 68 |
return ApiResponse.ok({
|
| 69 |
"id": source.id,
|
| 70 |
"name": source.name,
|
|
@@ -82,13 +123,14 @@ async def get_source(
|
|
| 82 |
"total_count": source.total_count,
|
| 83 |
"sort_order": source.sort_order,
|
| 84 |
"remark": source.remark,
|
|
|
|
| 85 |
})
|
| 86 |
|
| 87 |
|
| 88 |
@router.put("/{source_id}", response_model=ApiResponse)
|
| 89 |
async def update_source(
|
| 90 |
source_id: int,
|
| 91 |
-
|
| 92 |
admin: Admin = Depends(require_permission("source:update")),
|
| 93 |
db: AsyncSession = Depends(get_db),
|
| 94 |
):
|
|
@@ -97,19 +139,28 @@ async def update_source(
|
|
| 97 |
if not source:
|
| 98 |
return ApiResponse.fail(40401, "ๆบ็ซไธๅญๅจ")
|
| 99 |
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
"play_from_yun", "parse_url", "sync_interval",
|
| 103 |
-
"sort_order", "remark",
|
| 104 |
-
]
|
| 105 |
-
for field in allowed_fields:
|
| 106 |
-
if field in body:
|
| 107 |
-
setattr(source, field, body[field])
|
| 108 |
|
| 109 |
await db.flush()
|
| 110 |
return ApiResponse.ok()
|
| 111 |
|
| 112 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
@router.post("/{source_id}/test", response_model=ApiResponse)
|
| 114 |
async def test_source(
|
| 115 |
source_id: int,
|
|
@@ -131,7 +182,10 @@ async def test_source(
|
|
| 131 |
"status": "ok",
|
| 132 |
"total": total,
|
| 133 |
"category_count": len(classes),
|
| 134 |
-
"categories": [
|
|
|
|
|
|
|
|
|
|
| 135 |
})
|
| 136 |
except Exception as e:
|
| 137 |
return ApiResponse.ok({"status": "failed", "error": str(e)})
|
|
@@ -150,4 +204,51 @@ async def enable_source(
|
|
| 150 |
|
| 151 |
source.is_active = not source.is_active
|
| 152 |
await db.flush()
|
| 153 |
-
return ApiResponse.ok({"is_active": source.is_active})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import httpx
|
| 2 |
|
| 3 |
from fastapi import APIRouter, Depends, Query
|
| 4 |
+
from sqlalchemy import func, select
|
| 5 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 6 |
|
| 7 |
from app.database import get_db
|
| 8 |
+
from app.dependencies import require_permission
|
| 9 |
from app.models.admin import Admin
|
| 10 |
from app.models.source_site import SourceSite
|
| 11 |
+
from app.schemas.admin.source import SourceCreateRequest, SourceUpdateRequest
|
| 12 |
from app.schemas.common import ApiResponse, PaginatedData
|
| 13 |
+
from app.services.health import get_latest_health, run_health_checks
|
| 14 |
|
| 15 |
router = APIRouter()
|
| 16 |
|
|
|
|
| 26 |
total = count_result.scalar() or 0
|
| 27 |
|
| 28 |
result = await db.execute(
|
| 29 |
+
select(SourceSite)
|
| 30 |
+
.order_by(SourceSite.sort_order)
|
| 31 |
+
.offset((page - 1) * page_size)
|
| 32 |
+
.limit(page_size)
|
| 33 |
)
|
| 34 |
sources = result.scalars().all()
|
| 35 |
|
| 36 |
+
if sources:
|
| 37 |
+
source_ids = [s.id for s in sources]
|
| 38 |
+
health_map = await get_latest_health(db, source_ids)
|
| 39 |
+
else:
|
| 40 |
+
health_map = {}
|
| 41 |
+
|
| 42 |
items = []
|
| 43 |
for s in sources:
|
| 44 |
+
health = health_map.get(s.id)
|
| 45 |
items.append({
|
| 46 |
"id": s.id,
|
| 47 |
"name": s.name,
|
|
|
|
| 59 |
"total_count": s.total_count,
|
| 60 |
"sort_order": s.sort_order,
|
| 61 |
"remark": s.remark,
|
| 62 |
+
"health": health,
|
| 63 |
})
|
| 64 |
|
| 65 |
return ApiResponse.ok(
|
|
|
|
| 67 |
)
|
| 68 |
|
| 69 |
|
| 70 |
+
@router.post("", response_model=ApiResponse)
|
| 71 |
+
async def create_source(
|
| 72 |
+
req: SourceCreateRequest,
|
| 73 |
+
admin: Admin = Depends(require_permission("source:create")),
|
| 74 |
+
db: AsyncSession = Depends(get_db),
|
| 75 |
+
):
|
| 76 |
+
existing = await db.execute(select(SourceSite).where(SourceSite.code == req.code))
|
| 77 |
+
if existing.scalar_one_or_none():
|
| 78 |
+
return ApiResponse.fail(40002, "็ซ็น็ผ็ ๅทฒๅญๅจ")
|
| 79 |
+
|
| 80 |
+
source = SourceSite(
|
| 81 |
+
name=req.name,
|
| 82 |
+
code=req.code,
|
| 83 |
+
base_url=req.base_url,
|
| 84 |
+
site_url=req.site_url,
|
| 85 |
+
play_from_m3u8=req.play_from_m3u8,
|
| 86 |
+
play_from_yun=req.play_from_yun,
|
| 87 |
+
parse_url=req.parse_url,
|
| 88 |
+
sync_interval=req.sync_interval,
|
| 89 |
+
sort_order=req.sort_order,
|
| 90 |
+
remark=req.remark,
|
| 91 |
+
)
|
| 92 |
+
db.add(source)
|
| 93 |
+
await db.flush()
|
| 94 |
+
return ApiResponse.ok({"id": source.id})
|
| 95 |
+
|
| 96 |
+
|
| 97 |
@router.get("/{source_id}", response_model=ApiResponse)
|
| 98 |
async def get_source(
|
| 99 |
source_id: int,
|
|
|
|
| 105 |
if not source:
|
| 106 |
return ApiResponse.fail(40401, "ๆบ็ซไธๅญๅจ")
|
| 107 |
|
| 108 |
+
health_map = await get_latest_health(db, [source_id])
|
| 109 |
return ApiResponse.ok({
|
| 110 |
"id": source.id,
|
| 111 |
"name": source.name,
|
|
|
|
| 123 |
"total_count": source.total_count,
|
| 124 |
"sort_order": source.sort_order,
|
| 125 |
"remark": source.remark,
|
| 126 |
+
"health": health_map.get(source_id),
|
| 127 |
})
|
| 128 |
|
| 129 |
|
| 130 |
@router.put("/{source_id}", response_model=ApiResponse)
|
| 131 |
async def update_source(
|
| 132 |
source_id: int,
|
| 133 |
+
req: SourceUpdateRequest,
|
| 134 |
admin: Admin = Depends(require_permission("source:update")),
|
| 135 |
db: AsyncSession = Depends(get_db),
|
| 136 |
):
|
|
|
|
| 139 |
if not source:
|
| 140 |
return ApiResponse.fail(40401, "ๆบ็ซไธๅญๅจ")
|
| 141 |
|
| 142 |
+
for field, value in req.model_dump(exclude_unset=True).items():
|
| 143 |
+
setattr(source, field, value)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
await db.flush()
|
| 146 |
return ApiResponse.ok()
|
| 147 |
|
| 148 |
|
| 149 |
+
@router.delete("/{source_id}", response_model=ApiResponse)
|
| 150 |
+
async def delete_source(
|
| 151 |
+
source_id: int,
|
| 152 |
+
admin: Admin = Depends(require_permission("source:delete")),
|
| 153 |
+
db: AsyncSession = Depends(get_db),
|
| 154 |
+
):
|
| 155 |
+
result = await db.execute(select(SourceSite).where(SourceSite.id == source_id))
|
| 156 |
+
source = result.scalar_one_or_none()
|
| 157 |
+
if not source:
|
| 158 |
+
return ApiResponse.fail(40401, "ๆบ็ซไธๅญๅจ")
|
| 159 |
+
|
| 160 |
+
await db.delete(source)
|
| 161 |
+
return ApiResponse.ok()
|
| 162 |
+
|
| 163 |
+
|
| 164 |
@router.post("/{source_id}/test", response_model=ApiResponse)
|
| 165 |
async def test_source(
|
| 166 |
source_id: int,
|
|
|
|
| 182 |
"status": "ok",
|
| 183 |
"total": total,
|
| 184 |
"category_count": len(classes),
|
| 185 |
+
"categories": [
|
| 186 |
+
{"type_id": c.get("type_id"), "type_name": c.get("type_name")}
|
| 187 |
+
for c in classes
|
| 188 |
+
],
|
| 189 |
})
|
| 190 |
except Exception as e:
|
| 191 |
return ApiResponse.ok({"status": "failed", "error": str(e)})
|
|
|
|
| 204 |
|
| 205 |
source.is_active = not source.is_active
|
| 206 |
await db.flush()
|
| 207 |
+
return ApiResponse.ok({"is_active": source.is_active})
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
@router.post("/health-check", response_model=ApiResponse)
|
| 211 |
+
async def trigger_health_check(
|
| 212 |
+
admin: Admin = Depends(require_permission("source:btn:health")),
|
| 213 |
+
):
|
| 214 |
+
"""ๆๅจ่งฆๅๆๆๆบ็ซๅฅๅบทๆฃๆฅ"""
|
| 215 |
+
results = await run_health_checks()
|
| 216 |
+
healthy = sum(1 for r in results if r["is_success"])
|
| 217 |
+
return ApiResponse.ok({
|
| 218 |
+
"total": len(results),
|
| 219 |
+
"healthy": healthy,
|
| 220 |
+
"unhealthy": len(results) - healthy,
|
| 221 |
+
"results": results,
|
| 222 |
+
})
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
@router.get("/{source_id}/health-history", response_model=ApiResponse)
|
| 226 |
+
async def get_health_history(
|
| 227 |
+
source_id: int,
|
| 228 |
+
limit: int = Query(20, ge=1, le=100),
|
| 229 |
+
admin: Admin = Depends(require_permission("source:list")),
|
| 230 |
+
db: AsyncSession = Depends(get_db),
|
| 231 |
+
):
|
| 232 |
+
"""่ทๅๆๅฎๆบ็ซ็ๅฅๅบทๆฃๆฅๅๅฒ"""
|
| 233 |
+
from app.models.source_health import SourceHealth
|
| 234 |
+
|
| 235 |
+
result = await db.execute(
|
| 236 |
+
select(SourceHealth)
|
| 237 |
+
.where(SourceHealth.source_id == source_id)
|
| 238 |
+
.order_by(SourceHealth.checked_at.desc())
|
| 239 |
+
.limit(limit)
|
| 240 |
+
)
|
| 241 |
+
records = result.scalars().all()
|
| 242 |
+
|
| 243 |
+
items = [
|
| 244 |
+
{
|
| 245 |
+
"id": r.id,
|
| 246 |
+
"check_type": r.check_type,
|
| 247 |
+
"is_success": r.is_success,
|
| 248 |
+
"response_time_ms": r.response_time_ms,
|
| 249 |
+
"error_message": r.error_message,
|
| 250 |
+
"checked_at": str(r.checked_at) if r.checked_at else None,
|
| 251 |
+
}
|
| 252 |
+
for r in records
|
| 253 |
+
]
|
| 254 |
+
return ApiResponse.ok({"list": items, "total": len(items)})
|
|
@@ -11,6 +11,7 @@ from app.models.sync_log import SyncLog
|
|
| 11 |
from app.models.source_site import SourceSite
|
| 12 |
from app.schemas.common import ApiResponse, PaginatedData
|
| 13 |
from app.services.collector import collector
|
|
|
|
| 14 |
|
| 15 |
router = APIRouter()
|
| 16 |
|
|
@@ -24,28 +25,18 @@ async def list_sync_logs(
|
|
| 24 |
admin: Admin = Depends(require_permission("sync:list")),
|
| 25 |
db: AsyncSession = Depends(get_db),
|
| 26 |
):
|
| 27 |
-
|
| 28 |
-
count_query = select(func.count(SyncLog.id))
|
| 29 |
|
| 30 |
-
if
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
total_result = await db.execute(count_query)
|
| 38 |
-
total = total_result.scalar() or 0
|
| 39 |
-
|
| 40 |
-
result = await db.execute(
|
| 41 |
-
query.offset((page - 1) * page_size).limit(page_size)
|
| 42 |
-
)
|
| 43 |
-
logs = result.scalars().all()
|
| 44 |
|
| 45 |
items = []
|
| 46 |
for l in logs:
|
| 47 |
-
|
| 48 |
-
source = source_result.scalar_one_or_none()
|
| 49 |
items.append({
|
| 50 |
"id": l.id,
|
| 51 |
"source_id": l.source_id,
|
|
@@ -54,8 +45,8 @@ async def list_sync_logs(
|
|
| 54 |
"status": l.status,
|
| 55 |
"total_fetched": l.total_fetched,
|
| 56 |
"new_count": l.new_count,
|
| 57 |
-
"
|
| 58 |
-
"
|
| 59 |
"started_at": str(l.started_at) if l.started_at else None,
|
| 60 |
"finished_at": str(l.finished_at) if l.finished_at else None,
|
| 61 |
})
|
|
@@ -83,7 +74,23 @@ async def trigger_sync(
|
|
| 83 |
if not source.is_active:
|
| 84 |
return ApiResponse.fail(40004, "ๆบ็ซๆชๅฏ็จ")
|
| 85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
result = await collector.sync_source(source, range_type)
|
|
|
|
|
|
|
| 87 |
else:
|
| 88 |
results = await collector.sync_all(range_type)
|
| 89 |
result = results[-1] if results else {}
|
|
|
|
| 11 |
from app.models.source_site import SourceSite
|
| 12 |
from app.schemas.common import ApiResponse, PaginatedData
|
| 13 |
from app.services.collector import collector
|
| 14 |
+
from app.services.sync import get_sync_logs, create_sync_log, finish_sync_log
|
| 15 |
|
| 16 |
router = APIRouter()
|
| 17 |
|
|
|
|
| 25 |
admin: Admin = Depends(require_permission("sync:list")),
|
| 26 |
db: AsyncSession = Depends(get_db),
|
| 27 |
):
|
| 28 |
+
logs, total = await get_sync_logs(db, source_id=source_id, status=status, page=page, page_size=page_size)
|
|
|
|
| 29 |
|
| 30 |
+
if logs:
|
| 31 |
+
source_ids = list({l.source_id for l in logs})
|
| 32 |
+
source_result = await db.execute(select(SourceSite).where(SourceSite.id.in_(source_ids)))
|
| 33 |
+
source_map = {s.id: s for s in source_result.scalars().all()}
|
| 34 |
+
else:
|
| 35 |
+
source_map = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
items = []
|
| 38 |
for l in logs:
|
| 39 |
+
source = source_map.get(l.source_id)
|
|
|
|
| 40 |
items.append({
|
| 41 |
"id": l.id,
|
| 42 |
"source_id": l.source_id,
|
|
|
|
| 45 |
"status": l.status,
|
| 46 |
"total_fetched": l.total_fetched,
|
| 47 |
"new_count": l.new_count,
|
| 48 |
+
"update_count": l.update_count,
|
| 49 |
+
"error_message": l.error_message,
|
| 50 |
"started_at": str(l.started_at) if l.started_at else None,
|
| 51 |
"finished_at": str(l.finished_at) if l.finished_at else None,
|
| 52 |
})
|
|
|
|
| 74 |
if not source.is_active:
|
| 75 |
return ApiResponse.fail(40004, "ๆบ็ซๆชๅฏ็จ")
|
| 76 |
|
| 77 |
+
from datetime import datetime, timezone
|
| 78 |
+
from app.models.sync_log import SyncLog
|
| 79 |
+
|
| 80 |
+
log = SyncLog(
|
| 81 |
+
source_id=source_id,
|
| 82 |
+
range_type=range_type,
|
| 83 |
+
status="running",
|
| 84 |
+
started_at=datetime.now(timezone.utc),
|
| 85 |
+
)
|
| 86 |
+
async with async_session() as db:
|
| 87 |
+
db.add(log)
|
| 88 |
+
await db.commit()
|
| 89 |
+
log_id = log.id
|
| 90 |
+
|
| 91 |
result = await collector.sync_source(source, range_type)
|
| 92 |
+
|
| 93 |
+
await finish_sync_log(log_id, result)
|
| 94 |
else:
|
| 95 |
results = await collector.sync_all(range_type)
|
| 96 |
result = results[-1] if results else {}
|
|
@@ -5,6 +5,7 @@ from app.database import get_db
|
|
| 5 |
from app.dependencies import require_permission
|
| 6 |
from app.config import settings
|
| 7 |
from app.models.admin import Admin
|
|
|
|
| 8 |
from app.schemas.common import ApiResponse
|
| 9 |
|
| 10 |
router = APIRouter()
|
|
@@ -23,22 +24,20 @@ async def get_config(
|
|
| 23 |
|
| 24 |
@router.put("/config", response_model=ApiResponse)
|
| 25 |
async def update_config(
|
| 26 |
-
|
| 27 |
admin: Admin = Depends(require_permission("system:btn:save")),
|
| 28 |
):
|
| 29 |
from app.services.scheduler import start_scheduler, stop_scheduler
|
| 30 |
|
| 31 |
-
if
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
except Exception:
|
| 39 |
-
pass
|
| 40 |
|
| 41 |
-
if
|
| 42 |
-
settings.ACCESS_TOKEN_EXPIRE_MINUTES =
|
| 43 |
|
| 44 |
-
return ApiResponse.ok()
|
|
|
|
| 5 |
from app.dependencies import require_permission
|
| 6 |
from app.config import settings
|
| 7 |
from app.models.admin import Admin
|
| 8 |
+
from app.schemas.admin.system import SystemConfigUpdateRequest
|
| 9 |
from app.schemas.common import ApiResponse
|
| 10 |
|
| 11 |
router = APIRouter()
|
|
|
|
| 24 |
|
| 25 |
@router.put("/config", response_model=ApiResponse)
|
| 26 |
async def update_config(
|
| 27 |
+
req: SystemConfigUpdateRequest,
|
| 28 |
admin: Admin = Depends(require_permission("system:btn:save")),
|
| 29 |
):
|
| 30 |
from app.services.scheduler import start_scheduler, stop_scheduler
|
| 31 |
|
| 32 |
+
if req.sync_cron_hour is not None:
|
| 33 |
+
try:
|
| 34 |
+
stop_scheduler()
|
| 35 |
+
settings.SYNC_CRON_HOUR = req.sync_cron_hour
|
| 36 |
+
start_scheduler()
|
| 37 |
+
except Exception:
|
| 38 |
+
pass
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
if req.access_token_expire_minutes is not None:
|
| 41 |
+
settings.ACCESS_TOKEN_EXPIRE_MINUTES = req.access_token_expire_minutes
|
| 42 |
|
| 43 |
+
return ApiResponse.ok()
|
|
@@ -2,11 +2,13 @@ from fastapi import APIRouter, Depends, Query
|
|
| 2 |
from sqlalchemy import delete as sa_delete, func, select, update
|
| 3 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 4 |
|
|
|
|
| 5 |
from app.database import get_db
|
| 6 |
from app.dependencies import require_permission
|
| 7 |
from app.models.admin import Admin
|
| 8 |
from app.models.vod import Vod
|
| 9 |
from app.models.vod_source import VodSource
|
|
|
|
| 10 |
from app.schemas.common import ApiResponse, PaginatedData
|
| 11 |
|
| 12 |
router = APIRouter()
|
|
@@ -51,18 +53,28 @@ async def list_vods(
|
|
| 51 |
)
|
| 52 |
vods = result.scalars().all()
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
items = []
|
| 55 |
for v in vods:
|
| 56 |
-
src_count = await db.execute(
|
| 57 |
-
select(func.count(VodSource.id)).where(VodSource.vod_id == v.id)
|
| 58 |
-
)
|
| 59 |
items.append({
|
| 60 |
"id": v.id, "name": v.name, "cover": v.cover,
|
| 61 |
"category_id": v.category_id, "score": v.score,
|
| 62 |
"year": v.year, "area": v.area, "is_end": v.is_end,
|
| 63 |
"is_hidden": v.is_hidden, "is_recommended": v.is_recommended,
|
| 64 |
"remarks": v.remarks, "view_count": v.view_count,
|
| 65 |
-
"source_count":
|
| 66 |
"updated_at": str(v.updated_at) if v.updated_at else None,
|
| 67 |
})
|
| 68 |
|
|
@@ -97,7 +109,7 @@ async def get_vod(
|
|
| 97 |
@router.put("/{vod_id}", response_model=ApiResponse)
|
| 98 |
async def update_vod(
|
| 99 |
vod_id: int,
|
| 100 |
-
|
| 101 |
admin: Admin = Depends(require_permission("vod:update")),
|
| 102 |
db: AsyncSession = Depends(get_db),
|
| 103 |
):
|
|
@@ -106,11 +118,9 @@ async def update_vod(
|
|
| 106 |
if not vod:
|
| 107 |
return ApiResponse.fail(40401, "ๅฝฑ็ไธๅญๅจ")
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
if field in body:
|
| 113 |
-
setattr(vod, field, body[field])
|
| 114 |
return ApiResponse.ok()
|
| 115 |
|
| 116 |
|
|
@@ -122,6 +132,7 @@ async def delete_vod(
|
|
| 122 |
):
|
| 123 |
await db.execute(sa_delete(VodSource).where(VodSource.vod_id == vod_id))
|
| 124 |
await db.execute(sa_delete(Vod).where(Vod.id == vod_id))
|
|
|
|
| 125 |
return ApiResponse.ok()
|
| 126 |
|
| 127 |
|
|
@@ -136,6 +147,7 @@ async def toggle_hide(
|
|
| 136 |
if not vod:
|
| 137 |
return ApiResponse.fail(40401, "ๅฝฑ็ไธๅญๅจ")
|
| 138 |
vod.is_hidden = not vod.is_hidden
|
|
|
|
| 139 |
return ApiResponse.ok({"is_hidden": vod.is_hidden})
|
| 140 |
|
| 141 |
|
|
@@ -150,4 +162,5 @@ async def toggle_recommend(
|
|
| 150 |
if not vod:
|
| 151 |
return ApiResponse.fail(40401, "ๅฝฑ็ไธๅญๅจ")
|
| 152 |
vod.is_recommended = not vod.is_recommended
|
|
|
|
| 153 |
return ApiResponse.ok({"is_recommended": vod.is_recommended})
|
|
|
|
| 2 |
from sqlalchemy import delete as sa_delete, func, select, update
|
| 3 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 4 |
|
| 5 |
+
from app.cache import invalidate_vod_cache
|
| 6 |
from app.database import get_db
|
| 7 |
from app.dependencies import require_permission
|
| 8 |
from app.models.admin import Admin
|
| 9 |
from app.models.vod import Vod
|
| 10 |
from app.models.vod_source import VodSource
|
| 11 |
+
from app.schemas.admin.vod import VodUpdateRequest
|
| 12 |
from app.schemas.common import ApiResponse, PaginatedData
|
| 13 |
|
| 14 |
router = APIRouter()
|
|
|
|
| 53 |
)
|
| 54 |
vods = result.scalars().all()
|
| 55 |
|
| 56 |
+
if not vods:
|
| 57 |
+
return ApiResponse.ok(
|
| 58 |
+
PaginatedData(list=[], total=total, page=page, page_size=page_size).model_dump()
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
vod_ids = [v.id for v in vods]
|
| 62 |
+
src_count_result = await db.execute(
|
| 63 |
+
select(VodSource.vod_id, func.count(VodSource.id))
|
| 64 |
+
.where(VodSource.vod_id.in_(vod_ids))
|
| 65 |
+
.group_by(VodSource.vod_id)
|
| 66 |
+
)
|
| 67 |
+
src_count_map = {row[0]: row[1] for row in src_count_result.all()}
|
| 68 |
+
|
| 69 |
items = []
|
| 70 |
for v in vods:
|
|
|
|
|
|
|
|
|
|
| 71 |
items.append({
|
| 72 |
"id": v.id, "name": v.name, "cover": v.cover,
|
| 73 |
"category_id": v.category_id, "score": v.score,
|
| 74 |
"year": v.year, "area": v.area, "is_end": v.is_end,
|
| 75 |
"is_hidden": v.is_hidden, "is_recommended": v.is_recommended,
|
| 76 |
"remarks": v.remarks, "view_count": v.view_count,
|
| 77 |
+
"source_count": src_count_map.get(v.id, 0),
|
| 78 |
"updated_at": str(v.updated_at) if v.updated_at else None,
|
| 79 |
})
|
| 80 |
|
|
|
|
| 109 |
@router.put("/{vod_id}", response_model=ApiResponse)
|
| 110 |
async def update_vod(
|
| 111 |
vod_id: int,
|
| 112 |
+
req: VodUpdateRequest,
|
| 113 |
admin: Admin = Depends(require_permission("vod:update")),
|
| 114 |
db: AsyncSession = Depends(get_db),
|
| 115 |
):
|
|
|
|
| 118 |
if not vod:
|
| 119 |
return ApiResponse.fail(40401, "ๅฝฑ็ไธๅญๅจ")
|
| 120 |
|
| 121 |
+
for field, value in req.model_dump(exclude_unset=True).items():
|
| 122 |
+
setattr(vod, field, value)
|
| 123 |
+
await invalidate_vod_cache(vod_id)
|
|
|
|
|
|
|
| 124 |
return ApiResponse.ok()
|
| 125 |
|
| 126 |
|
|
|
|
| 132 |
):
|
| 133 |
await db.execute(sa_delete(VodSource).where(VodSource.vod_id == vod_id))
|
| 134 |
await db.execute(sa_delete(Vod).where(Vod.id == vod_id))
|
| 135 |
+
await invalidate_vod_cache(vod_id)
|
| 136 |
return ApiResponse.ok()
|
| 137 |
|
| 138 |
|
|
|
|
| 147 |
if not vod:
|
| 148 |
return ApiResponse.fail(40401, "ๅฝฑ็ไธๅญๅจ")
|
| 149 |
vod.is_hidden = not vod.is_hidden
|
| 150 |
+
await invalidate_vod_cache(vod_id)
|
| 151 |
return ApiResponse.ok({"is_hidden": vod.is_hidden})
|
| 152 |
|
| 153 |
|
|
|
|
| 162 |
if not vod:
|
| 163 |
return ApiResponse.fail(40401, "ๅฝฑ็ไธๅญๅจ")
|
| 164 |
vod.is_recommended = not vod.is_recommended
|
| 165 |
+
await invalidate_vod_cache(vod_id)
|
| 166 |
return ApiResponse.ok({"is_recommended": vod.is_recommended})
|
|
@@ -1,11 +1,12 @@
|
|
| 1 |
-
from datetime import datetime
|
| 2 |
|
| 3 |
-
from fastapi import APIRouter, Depends
|
| 4 |
from sqlalchemy import select, or_
|
| 5 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 6 |
|
| 7 |
from app.database import get_db
|
| 8 |
from app.dependencies import get_current_user
|
|
|
|
| 9 |
from app.models.user import User
|
| 10 |
from app.models.category import Category
|
| 11 |
from app.schemas.common import ApiResponse
|
|
@@ -22,7 +23,8 @@ router = APIRouter()
|
|
| 22 |
|
| 23 |
|
| 24 |
@router.post("/register", response_model=ApiResponse)
|
| 25 |
-
|
|
|
|
| 26 |
result = await db.execute(
|
| 27 |
select(User).where(
|
| 28 |
or_(
|
|
@@ -50,7 +52,8 @@ async def register(req: UserRegisterRequest, db: AsyncSession = Depends(get_db))
|
|
| 50 |
|
| 51 |
|
| 52 |
@router.post("/login", response_model=ApiResponse)
|
| 53 |
-
|
|
|
|
| 54 |
result = await db.execute(select(User).where(User.username == req.username))
|
| 55 |
user = result.scalar_one_or_none()
|
| 56 |
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)):
|
|
| 58 |
):
|
| 59 |
return ApiResponse.fail(40001, "็จๆทๅๆๅฏ็ ้่ฏฏ")
|
| 60 |
|
| 61 |
-
user.last_login_at = datetime.now()
|
| 62 |
await db.flush()
|
| 63 |
|
| 64 |
token = create_access_token(str(user.id), "user")
|
|
|
|
| 1 |
+
from datetime import datetime, timezone
|
| 2 |
|
| 3 |
+
from fastapi import APIRouter, Depends, Request
|
| 4 |
from sqlalchemy import select, or_
|
| 5 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 6 |
|
| 7 |
from app.database import get_db
|
| 8 |
from app.dependencies import get_current_user
|
| 9 |
+
from app.limiter import limiter
|
| 10 |
from app.models.user import User
|
| 11 |
from app.models.category import Category
|
| 12 |
from app.schemas.common import ApiResponse
|
|
|
|
| 23 |
|
| 24 |
|
| 25 |
@router.post("/register", response_model=ApiResponse)
|
| 26 |
+
@limiter.limit("5/minute")
|
| 27 |
+
async def register(request: Request, req: UserRegisterRequest, db: AsyncSession = Depends(get_db)):
|
| 28 |
result = await db.execute(
|
| 29 |
select(User).where(
|
| 30 |
or_(
|
|
|
|
| 52 |
|
| 53 |
|
| 54 |
@router.post("/login", response_model=ApiResponse)
|
| 55 |
+
@limiter.limit("10/minute")
|
| 56 |
+
async def login(request: Request, req: UserLoginRequest, db: AsyncSession = Depends(get_db)):
|
| 57 |
result = await db.execute(select(User).where(User.username == req.username))
|
| 58 |
user = result.scalar_one_or_none()
|
| 59 |
if not user or not user.is_active or not verify_password(
|
|
|
|
| 61 |
):
|
| 62 |
return ApiResponse.fail(40001, "็จๆทๅๆๅฏ็ ้่ฏฏ")
|
| 63 |
|
| 64 |
+
user.last_login_at = datetime.now(timezone.utc)
|
| 65 |
await db.flush()
|
| 66 |
|
| 67 |
token = create_access_token(str(user.id), "user")
|
|
@@ -2,6 +2,8 @@ from fastapi import APIRouter, Depends
|
|
| 2 |
from sqlalchemy import select
|
| 3 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 4 |
|
|
|
|
|
|
|
| 5 |
from app.database import get_db
|
| 6 |
from app.models.category import Category
|
| 7 |
from app.schemas.common import ApiResponse
|
|
@@ -12,6 +14,11 @@ router = APIRouter()
|
|
| 12 |
|
| 13 |
@router.get("", response_model=ApiResponse)
|
| 14 |
async def list_categories(db: AsyncSession = Depends(get_db)):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
result = await db.execute(
|
| 16 |
select(Category)
|
| 17 |
.where(Category.is_active == True)
|
|
@@ -37,7 +44,9 @@ async def list_categories(db: AsyncSession = Depends(get_db)):
|
|
| 37 |
for node in roots:
|
| 38 |
_clean_empty_children(node)
|
| 39 |
|
| 40 |
-
|
|
|
|
|
|
|
| 41 |
|
| 42 |
|
| 43 |
def _clean_empty_children(node: CategoryUserNode):
|
|
@@ -46,3 +55,4 @@ def _clean_empty_children(node: CategoryUserNode):
|
|
| 46 |
_clean_empty_children(child)
|
| 47 |
if len(node.children) == 0:
|
| 48 |
node.children = None
|
|
|
|
|
|
| 2 |
from sqlalchemy import select
|
| 3 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 4 |
|
| 5 |
+
from app.cache import cache_get, cache_set, category_tree_key
|
| 6 |
+
from app.config import settings
|
| 7 |
from app.database import get_db
|
| 8 |
from app.models.category import Category
|
| 9 |
from app.schemas.common import ApiResponse
|
|
|
|
| 14 |
|
| 15 |
@router.get("", response_model=ApiResponse)
|
| 16 |
async def list_categories(db: AsyncSession = Depends(get_db)):
|
| 17 |
+
cache_key = category_tree_key()
|
| 18 |
+
cached = await cache_get(cache_key)
|
| 19 |
+
if cached is not None:
|
| 20 |
+
return ApiResponse.ok(cached)
|
| 21 |
+
|
| 22 |
result = await db.execute(
|
| 23 |
select(Category)
|
| 24 |
.where(Category.is_active == True)
|
|
|
|
| 44 |
for node in roots:
|
| 45 |
_clean_empty_children(node)
|
| 46 |
|
| 47 |
+
data = [r.model_dump() for r in roots]
|
| 48 |
+
await cache_set(cache_key, data, settings.CACHE_TTL_CATEGORY)
|
| 49 |
+
return ApiResponse.ok(data)
|
| 50 |
|
| 51 |
|
| 52 |
def _clean_empty_children(node: CategoryUserNode):
|
|
|
|
| 55 |
_clean_empty_children(child)
|
| 56 |
if len(node.children) == 0:
|
| 57 |
node.children = None
|
| 58 |
+
|
|
@@ -1,5 +1,6 @@
|
|
| 1 |
from fastapi import APIRouter, Depends, Query
|
| 2 |
from sqlalchemy import func, select, delete as sa_delete
|
|
|
|
| 3 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 4 |
|
| 5 |
from app.database import get_db
|
|
@@ -34,17 +35,23 @@ async def list_favorites(
|
|
| 34 |
)
|
| 35 |
favs = result.scalars().all()
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
items = []
|
| 38 |
for f in favs:
|
| 39 |
-
|
| 40 |
-
vod = vod_result.scalar_one_or_none()
|
| 41 |
items.append(
|
| 42 |
FavoriteItem(
|
| 43 |
id=f.id,
|
| 44 |
vod_id=f.vod_id,
|
| 45 |
-
vod_name=vod
|
| 46 |
-
vod_cover=vod
|
| 47 |
-
vod_remarks=vod
|
| 48 |
created_at=f.created_at,
|
| 49 |
).model_dump()
|
| 50 |
)
|
|
@@ -60,18 +67,17 @@ async def add_favorite(
|
|
| 60 |
user: User = Depends(get_current_user),
|
| 61 |
db: AsyncSession = Depends(get_db),
|
| 62 |
):
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
return ApiResponse.fail(40002, "ๅทฒๆถ่")
|
| 68 |
|
| 69 |
-
fav = Favorite(user_id=user.id, vod_id=req.vod_id)
|
| 70 |
-
db.add(fav)
|
| 71 |
-
await db.flush()
|
| 72 |
-
|
| 73 |
-
return ApiResponse.ok()
|
| 74 |
-
|
| 75 |
|
| 76 |
@router.delete("/{vod_id}", response_model=ApiResponse)
|
| 77 |
async def remove_favorite(
|
|
|
|
| 1 |
from fastapi import APIRouter, Depends, Query
|
| 2 |
from sqlalchemy import func, select, delete as sa_delete
|
| 3 |
+
from sqlalchemy.exc import IntegrityError
|
| 4 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 5 |
|
| 6 |
from app.database import get_db
|
|
|
|
| 35 |
)
|
| 36 |
favs = result.scalars().all()
|
| 37 |
|
| 38 |
+
if favs:
|
| 39 |
+
vod_ids = [f.vod_id for f in favs]
|
| 40 |
+
vod_result = await db.execute(select(Vod.id, Vod.name, Vod.cover, Vod.remarks).where(Vod.id.in_(vod_ids)))
|
| 41 |
+
vod_map = {row[0]: row for row in vod_result.all()}
|
| 42 |
+
else:
|
| 43 |
+
vod_map = {}
|
| 44 |
+
|
| 45 |
items = []
|
| 46 |
for f in favs:
|
| 47 |
+
vod = vod_map.get(f.vod_id)
|
|
|
|
| 48 |
items.append(
|
| 49 |
FavoriteItem(
|
| 50 |
id=f.id,
|
| 51 |
vod_id=f.vod_id,
|
| 52 |
+
vod_name=vod[1] if vod else "ๆช็ฅ",
|
| 53 |
+
vod_cover=vod[2] if vod else None,
|
| 54 |
+
vod_remarks=vod[3] if vod else None,
|
| 55 |
created_at=f.created_at,
|
| 56 |
).model_dump()
|
| 57 |
)
|
|
|
|
| 67 |
user: User = Depends(get_current_user),
|
| 68 |
db: AsyncSession = Depends(get_db),
|
| 69 |
):
|
| 70 |
+
# ็ดๆฅๆๅ
ฅ๏ผ็ฑๆฐๆฎๅบๅฏไธ็ดขๅผ uq_favorite_user_vod ไฟ่ฏๅน็ญๆง
|
| 71 |
+
# ๆ่ท IntegrityError ไปฃๆฟๅบ็จๅฑ็ SELECT ๆฅ้๏ผๆถ้ค็ซๆๆกไปถ
|
| 72 |
+
try:
|
| 73 |
+
fav = Favorite(user_id=user.id, vod_id=req.vod_id)
|
| 74 |
+
db.add(fav)
|
| 75 |
+
await db.flush()
|
| 76 |
+
return ApiResponse.ok()
|
| 77 |
+
except IntegrityError:
|
| 78 |
+
await db.rollback()
|
| 79 |
return ApiResponse.fail(40002, "ๅทฒๆถ่")
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
@router.delete("/{vod_id}", response_model=ApiResponse)
|
| 83 |
async def remove_favorite(
|
|
@@ -34,16 +34,22 @@ async def list_history(
|
|
| 34 |
)
|
| 35 |
histories = result.scalars().all()
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
items = []
|
| 38 |
for h in histories:
|
| 39 |
-
|
| 40 |
-
vod = vod_result.scalar_one_or_none()
|
| 41 |
items.append(
|
| 42 |
HistoryItem(
|
| 43 |
id=h.id,
|
| 44 |
vod_id=h.vod_id,
|
| 45 |
-
vod_name=vod
|
| 46 |
-
vod_cover=vod
|
| 47 |
source_id=h.source_id,
|
| 48 |
episode=h.episode,
|
| 49 |
play_url=h.play_url,
|
|
|
|
| 34 |
)
|
| 35 |
histories = result.scalars().all()
|
| 36 |
|
| 37 |
+
if histories:
|
| 38 |
+
vod_ids = [h.vod_id for h in histories]
|
| 39 |
+
vod_result = await db.execute(select(Vod.id, Vod.name, Vod.cover).where(Vod.id.in_(vod_ids)))
|
| 40 |
+
vod_map = {row[0]: row for row in vod_result.all()}
|
| 41 |
+
else:
|
| 42 |
+
vod_map = {}
|
| 43 |
+
|
| 44 |
items = []
|
| 45 |
for h in histories:
|
| 46 |
+
vod = vod_map.get(h.vod_id)
|
|
|
|
| 47 |
items.append(
|
| 48 |
HistoryItem(
|
| 49 |
id=h.id,
|
| 50 |
vod_id=h.vod_id,
|
| 51 |
+
vod_name=vod[1] if vod else "ๆช็ฅ",
|
| 52 |
+
vod_cover=vod[2] if vod else None,
|
| 53 |
source_id=h.source_id,
|
| 54 |
episode=h.episode,
|
| 55 |
play_url=h.play_url,
|
|
@@ -2,6 +2,11 @@ from fastapi import APIRouter, Depends, Query
|
|
| 2 |
from sqlalchemy import func, select
|
| 3 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from app.database import get_db
|
| 6 |
from app.models.category import Category
|
| 7 |
from app.models.source_site import SourceSite
|
|
@@ -9,10 +14,41 @@ from app.models.vod import Vod
|
|
| 9 |
from app.models.vod_source import VodSource
|
| 10 |
from app.schemas.common import ApiResponse, PaginatedData
|
| 11 |
from app.schemas.user.vod import VodUserItem, VodUserDetail, VodPlaySource, EpisodeItem
|
|
|
|
| 12 |
|
| 13 |
router = APIRouter()
|
| 14 |
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
@router.get("", response_model=ApiResponse)
|
| 17 |
async def list_vods(
|
| 18 |
category_id: int | None = Query(None),
|
|
@@ -20,6 +56,11 @@ async def list_vods(
|
|
| 20 |
page_size: int = Query(24, ge=1, le=100),
|
| 21 |
db: AsyncSession = Depends(get_db),
|
| 22 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
query = select(Vod).where(Vod.is_hidden == False)
|
| 24 |
count_query = select(func.count(Vod.id)).where(Vod.is_hidden == False)
|
| 25 |
|
|
@@ -37,30 +78,18 @@ async def list_vods(
|
|
| 37 |
)
|
| 38 |
vods = result.scalars().all()
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
items.append(
|
| 45 |
-
VodUserItem(
|
| 46 |
-
id=v.id,
|
| 47 |
-
name=v.name,
|
| 48 |
-
cover=v.cover,
|
| 49 |
-
category_id=v.category_id,
|
| 50 |
-
category_name=cat_name,
|
| 51 |
-
score=v.score,
|
| 52 |
-
year=v.year,
|
| 53 |
-
area=v.area,
|
| 54 |
-
is_end=v.is_end,
|
| 55 |
-
remarks=v.remarks,
|
| 56 |
-
source_count=source_count,
|
| 57 |
-
updated_at=v.updated_at,
|
| 58 |
-
).model_dump()
|
| 59 |
-
)
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
|
| 66 |
@router.get("/search", response_model=ApiResponse)
|
|
@@ -70,6 +99,11 @@ async def search_vods(
|
|
| 70 |
page_size: int = Query(24, ge=1, le=100),
|
| 71 |
db: AsyncSession = Depends(get_db),
|
| 72 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
pattern = f"%{keyword}%"
|
| 74 |
name_match = Vod.name.ilike(pattern) | Vod.sub_name.ilike(pattern) | Vod.actor.ilike(pattern)
|
| 75 |
|
|
@@ -87,30 +121,18 @@ async def search_vods(
|
|
| 87 |
)
|
| 88 |
vods = result.scalars().all()
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
items.append(
|
| 95 |
-
VodUserItem(
|
| 96 |
-
id=v.id,
|
| 97 |
-
name=v.name,
|
| 98 |
-
cover=v.cover,
|
| 99 |
-
category_id=v.category_id,
|
| 100 |
-
category_name=cat_name,
|
| 101 |
-
score=v.score,
|
| 102 |
-
year=v.year,
|
| 103 |
-
area=v.area,
|
| 104 |
-
is_end=v.is_end,
|
| 105 |
-
remarks=v.remarks,
|
| 106 |
-
source_count=source_count,
|
| 107 |
-
updated_at=v.updated_at,
|
| 108 |
-
).model_dump()
|
| 109 |
-
)
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
|
| 116 |
@router.get("/recommended", response_model=ApiResponse)
|
|
@@ -119,10 +141,13 @@ async def recommended_vods(
|
|
| 119 |
page_size: int = Query(12, ge=1, le=50),
|
| 120 |
db: AsyncSession = Depends(get_db),
|
| 121 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
count_result = await db.execute(
|
| 123 |
-
select(func.count(Vod.id)).where(
|
| 124 |
-
Vod.is_hidden == False, Vod.is_recommended == True
|
| 125 |
-
)
|
| 126 |
)
|
| 127 |
total = count_result.scalar() or 0
|
| 128 |
|
|
@@ -135,30 +160,18 @@ async def recommended_vods(
|
|
| 135 |
)
|
| 136 |
vods = result.scalars().all()
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
items.append(
|
| 143 |
-
VodUserItem(
|
| 144 |
-
id=v.id,
|
| 145 |
-
name=v.name,
|
| 146 |
-
cover=v.cover,
|
| 147 |
-
category_id=v.category_id,
|
| 148 |
-
category_name=cat_name,
|
| 149 |
-
score=v.score,
|
| 150 |
-
year=v.year,
|
| 151 |
-
area=v.area,
|
| 152 |
-
is_end=v.is_end,
|
| 153 |
-
remarks=v.remarks,
|
| 154 |
-
source_count=source_count,
|
| 155 |
-
updated_at=v.updated_at,
|
| 156 |
-
).model_dump()
|
| 157 |
-
)
|
| 158 |
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
|
| 164 |
@router.get("/latest", response_model=ApiResponse)
|
|
@@ -170,6 +183,11 @@ async def latest_vods(
|
|
| 170 |
):
|
| 171 |
from datetime import datetime, timedelta, timezone
|
| 172 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
|
| 174 |
count_result = await db.execute(
|
| 175 |
select(func.count(Vod.id)).where(Vod.is_hidden == False, Vod.updated_at >= cutoff)
|
|
@@ -185,54 +203,55 @@ async def latest_vods(
|
|
| 185 |
)
|
| 186 |
vods = result.scalars().all()
|
| 187 |
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
items.append(
|
| 193 |
-
VodUserItem(
|
| 194 |
-
id=v.id,
|
| 195 |
-
name=v.name,
|
| 196 |
-
cover=v.cover,
|
| 197 |
-
category_id=v.category_id,
|
| 198 |
-
category_name=cat_name,
|
| 199 |
-
score=v.score,
|
| 200 |
-
year=v.year,
|
| 201 |
-
area=v.area,
|
| 202 |
-
is_end=v.is_end,
|
| 203 |
-
remarks=v.remarks,
|
| 204 |
-
source_count=source_count,
|
| 205 |
-
updated_at=v.updated_at,
|
| 206 |
-
).model_dump()
|
| 207 |
-
)
|
| 208 |
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
|
| 213 |
|
| 214 |
@router.get("/{vod_id}", response_model=ApiResponse)
|
| 215 |
async def get_vod(vod_id: int, db: AsyncSession = Depends(get_db)):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
result = await db.execute(select(Vod).where(Vod.id == vod_id, Vod.is_hidden == False))
|
| 217 |
vod = result.scalar_one_or_none()
|
| 218 |
if not vod:
|
| 219 |
return ApiResponse.fail(40401, "ๅฝฑ็ไธๅญๅจ")
|
| 220 |
|
| 221 |
-
await
|
| 222 |
-
Vod.__table__.update().where(Vod.id == vod_id).values(view_count=Vod.view_count + 1)
|
| 223 |
-
)
|
| 224 |
|
| 225 |
-
|
|
|
|
| 226 |
|
| 227 |
source_result = await db.execute(
|
| 228 |
select(VodSource).where(VodSource.vod_id == vod_id, VodSource.is_available == True)
|
| 229 |
)
|
| 230 |
vod_sources = source_result.scalars().all()
|
| 231 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
sources = []
|
| 233 |
for vs in vod_sources:
|
| 234 |
-
|
| 235 |
-
site = site_result.scalar_one_or_none()
|
| 236 |
if not site:
|
| 237 |
continue
|
| 238 |
|
|
@@ -285,23 +304,10 @@ async def get_vod(vod_id: int, db: AsyncSession = Depends(get_db)):
|
|
| 285 |
source_count=source_count,
|
| 286 |
sources=sources,
|
| 287 |
updated_at=vod.updated_at,
|
| 288 |
-
)
|
| 289 |
-
|
| 290 |
-
return ApiResponse.ok(detail.model_dump())
|
| 291 |
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
result = await db.execute(select(Category.name).where(Category.id == category_id))
|
| 295 |
-
return result.scalar_one_or_none()
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
async def _get_source_count(db: AsyncSession, vod_id: int) -> int:
|
| 299 |
-
result = await db.execute(
|
| 300 |
-
select(func.count(VodSource.id)).where(
|
| 301 |
-
VodSource.vod_id == vod_id, VodSource.is_available == True
|
| 302 |
-
)
|
| 303 |
-
)
|
| 304 |
-
return result.scalar() or 0
|
| 305 |
|
| 306 |
|
| 307 |
def _parse_play_url(play_url: str) -> list[dict]:
|
|
|
|
| 2 |
from sqlalchemy import func, select
|
| 3 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 4 |
|
| 5 |
+
from app.cache import (
|
| 6 |
+
cache_get, cache_set,
|
| 7 |
+
vod_list_key, vod_search_key, vod_latest_key, vod_recommended_key, vod_detail_key,
|
| 8 |
+
)
|
| 9 |
+
from app.config import settings
|
| 10 |
from app.database import get_db
|
| 11 |
from app.models.category import Category
|
| 12 |
from app.models.source_site import SourceSite
|
|
|
|
| 14 |
from app.models.vod_source import VodSource
|
| 15 |
from app.schemas.common import ApiResponse, PaginatedData
|
| 16 |
from app.schemas.user.vod import VodUserItem, VodUserDetail, VodPlaySource, EpisodeItem
|
| 17 |
+
from app.services.vod import batch_get_category_names, batch_get_source_counts, increment_view_count
|
| 18 |
|
| 19 |
router = APIRouter()
|
| 20 |
|
| 21 |
|
| 22 |
+
async def _batch_get_category_names(db: AsyncSession, category_ids: list[int]) -> dict[int, str]:
|
| 23 |
+
return await batch_get_category_names(db, category_ids)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
async def _batch_get_source_counts(db: AsyncSession, vod_ids: list[int]) -> dict[int, int]:
|
| 27 |
+
return await batch_get_source_counts(db, vod_ids)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _build_vod_items(vods, cat_map, source_count_map) -> list[dict]:
|
| 31 |
+
items = []
|
| 32 |
+
for v in vods:
|
| 33 |
+
items.append(
|
| 34 |
+
VodUserItem(
|
| 35 |
+
id=v.id,
|
| 36 |
+
name=v.name,
|
| 37 |
+
cover=v.cover,
|
| 38 |
+
category_id=v.category_id,
|
| 39 |
+
category_name=cat_map.get(v.category_id),
|
| 40 |
+
score=v.score,
|
| 41 |
+
year=v.year,
|
| 42 |
+
area=v.area,
|
| 43 |
+
is_end=v.is_end,
|
| 44 |
+
remarks=v.remarks,
|
| 45 |
+
source_count=source_count_map.get(v.id, 0),
|
| 46 |
+
updated_at=v.updated_at,
|
| 47 |
+
).model_dump()
|
| 48 |
+
)
|
| 49 |
+
return items
|
| 50 |
+
|
| 51 |
+
|
| 52 |
@router.get("", response_model=ApiResponse)
|
| 53 |
async def list_vods(
|
| 54 |
category_id: int | None = Query(None),
|
|
|
|
| 56 |
page_size: int = Query(24, ge=1, le=100),
|
| 57 |
db: AsyncSession = Depends(get_db),
|
| 58 |
):
|
| 59 |
+
cache_key = vod_list_key(category_id, page, page_size)
|
| 60 |
+
cached = await cache_get(cache_key)
|
| 61 |
+
if cached is not None:
|
| 62 |
+
return ApiResponse.ok(cached)
|
| 63 |
+
|
| 64 |
query = select(Vod).where(Vod.is_hidden == False)
|
| 65 |
count_query = select(func.count(Vod.id)).where(Vod.is_hidden == False)
|
| 66 |
|
|
|
|
| 78 |
)
|
| 79 |
vods = result.scalars().all()
|
| 80 |
|
| 81 |
+
if not vods:
|
| 82 |
+
data = PaginatedData(list=[], total=total, page=page, page_size=page_size).model_dump()
|
| 83 |
+
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
|
| 84 |
+
return ApiResponse.ok(data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
cat_map = await _batch_get_category_names(db, [v.category_id for v in vods])
|
| 87 |
+
source_count_map = await _batch_get_source_counts(db, [v.id for v in vods])
|
| 88 |
+
items = _build_vod_items(vods, cat_map, source_count_map)
|
| 89 |
+
|
| 90 |
+
data = PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
|
| 91 |
+
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
|
| 92 |
+
return ApiResponse.ok(data)
|
| 93 |
|
| 94 |
|
| 95 |
@router.get("/search", response_model=ApiResponse)
|
|
|
|
| 99 |
page_size: int = Query(24, ge=1, le=100),
|
| 100 |
db: AsyncSession = Depends(get_db),
|
| 101 |
):
|
| 102 |
+
cache_key = vod_search_key(keyword, None, page, page_size)
|
| 103 |
+
cached = await cache_get(cache_key)
|
| 104 |
+
if cached is not None:
|
| 105 |
+
return ApiResponse.ok(cached)
|
| 106 |
+
|
| 107 |
pattern = f"%{keyword}%"
|
| 108 |
name_match = Vod.name.ilike(pattern) | Vod.sub_name.ilike(pattern) | Vod.actor.ilike(pattern)
|
| 109 |
|
|
|
|
| 121 |
)
|
| 122 |
vods = result.scalars().all()
|
| 123 |
|
| 124 |
+
if not vods:
|
| 125 |
+
data = PaginatedData(list=[], total=total, page=page, page_size=page_size).model_dump()
|
| 126 |
+
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
|
| 127 |
+
return ApiResponse.ok(data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
+
cat_map = await _batch_get_category_names(db, [v.category_id for v in vods])
|
| 130 |
+
source_count_map = await _batch_get_source_counts(db, [v.id for v in vods])
|
| 131 |
+
items = _build_vod_items(vods, cat_map, source_count_map)
|
| 132 |
+
|
| 133 |
+
data = PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
|
| 134 |
+
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
|
| 135 |
+
return ApiResponse.ok(data)
|
| 136 |
|
| 137 |
|
| 138 |
@router.get("/recommended", response_model=ApiResponse)
|
|
|
|
| 141 |
page_size: int = Query(12, ge=1, le=50),
|
| 142 |
db: AsyncSession = Depends(get_db),
|
| 143 |
):
|
| 144 |
+
cache_key = vod_recommended_key(page, page_size)
|
| 145 |
+
cached = await cache_get(cache_key)
|
| 146 |
+
if cached is not None:
|
| 147 |
+
return ApiResponse.ok(cached)
|
| 148 |
+
|
| 149 |
count_result = await db.execute(
|
| 150 |
+
select(func.count(Vod.id)).where(Vod.is_hidden == False, Vod.is_recommended == True)
|
|
|
|
|
|
|
| 151 |
)
|
| 152 |
total = count_result.scalar() or 0
|
| 153 |
|
|
|
|
| 160 |
)
|
| 161 |
vods = result.scalars().all()
|
| 162 |
|
| 163 |
+
if not vods:
|
| 164 |
+
data = PaginatedData(list=[], total=total, page=page, page_size=page_size).model_dump()
|
| 165 |
+
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
|
| 166 |
+
return ApiResponse.ok(data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
+
cat_map = await _batch_get_category_names(db, [v.category_id for v in vods])
|
| 169 |
+
source_count_map = await _batch_get_source_counts(db, [v.id for v in vods])
|
| 170 |
+
items = _build_vod_items(vods, cat_map, source_count_map)
|
| 171 |
+
|
| 172 |
+
data = PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
|
| 173 |
+
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
|
| 174 |
+
return ApiResponse.ok(data)
|
| 175 |
|
| 176 |
|
| 177 |
@router.get("/latest", response_model=ApiResponse)
|
|
|
|
| 183 |
):
|
| 184 |
from datetime import datetime, timedelta, timezone
|
| 185 |
|
| 186 |
+
cache_key = vod_latest_key(page, page_size)
|
| 187 |
+
cached = await cache_get(cache_key)
|
| 188 |
+
if cached is not None:
|
| 189 |
+
return ApiResponse.ok(cached)
|
| 190 |
+
|
| 191 |
cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
|
| 192 |
count_result = await db.execute(
|
| 193 |
select(func.count(Vod.id)).where(Vod.is_hidden == False, Vod.updated_at >= cutoff)
|
|
|
|
| 203 |
)
|
| 204 |
vods = result.scalars().all()
|
| 205 |
|
| 206 |
+
if not vods:
|
| 207 |
+
data = PaginatedData(list=[], total=total, page=page, page_size=page_size).model_dump()
|
| 208 |
+
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
|
| 209 |
+
return ApiResponse.ok(data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
+
cat_map = await _batch_get_category_names(db, [v.category_id for v in vods])
|
| 212 |
+
source_count_map = await _batch_get_source_counts(db, [v.id for v in vods])
|
| 213 |
+
items = _build_vod_items(vods, cat_map, source_count_map)
|
| 214 |
+
|
| 215 |
+
data = PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
|
| 216 |
+
await cache_set(cache_key, data, settings.CACHE_TTL_VOD_LIST)
|
| 217 |
+
return ApiResponse.ok(data)
|
| 218 |
|
| 219 |
|
| 220 |
@router.get("/{vod_id}", response_model=ApiResponse)
|
| 221 |
async def get_vod(vod_id: int, db: AsyncSession = Depends(get_db)):
|
| 222 |
+
# ่ฏฆๆ
็ผๅญ๏ผไธ็ผๅญ view_count๏ผๆฏๆฌกไป้ๅข๏ผไฝ็ปๆไฟกๆฏ็ผๅญ๏ผ
|
| 223 |
+
cache_key = vod_detail_key(vod_id)
|
| 224 |
+
cached = await cache_get(cache_key)
|
| 225 |
+
if cached is not None:
|
| 226 |
+
# ๅณไฝฟๅฝไธญ็ผๅญไป้ๅขๆญๆพๆฌกๆฐ
|
| 227 |
+
await increment_view_count(db, vod_id)
|
| 228 |
+
return ApiResponse.ok(cached)
|
| 229 |
+
|
| 230 |
result = await db.execute(select(Vod).where(Vod.id == vod_id, Vod.is_hidden == False))
|
| 231 |
vod = result.scalar_one_or_none()
|
| 232 |
if not vod:
|
| 233 |
return ApiResponse.fail(40401, "ๅฝฑ็ไธๅญๅจ")
|
| 234 |
|
| 235 |
+
await increment_view_count(db, vod_id)
|
|
|
|
|
|
|
| 236 |
|
| 237 |
+
cat_result = await db.execute(select(Category.name).where(Category.id == vod.category_id))
|
| 238 |
+
cat_name = cat_result.scalar_one_or_none()
|
| 239 |
|
| 240 |
source_result = await db.execute(
|
| 241 |
select(VodSource).where(VodSource.vod_id == vod_id, VodSource.is_available == True)
|
| 242 |
)
|
| 243 |
vod_sources = source_result.scalars().all()
|
| 244 |
|
| 245 |
+
if vod_sources:
|
| 246 |
+
source_ids = [vs.source_id for vs in vod_sources]
|
| 247 |
+
site_result = await db.execute(select(SourceSite).where(SourceSite.id.in_(source_ids)))
|
| 248 |
+
site_map = {s.id: s for s in site_result.scalars().all()}
|
| 249 |
+
else:
|
| 250 |
+
site_map = {}
|
| 251 |
+
|
| 252 |
sources = []
|
| 253 |
for vs in vod_sources:
|
| 254 |
+
site = site_map.get(vs.source_id)
|
|
|
|
| 255 |
if not site:
|
| 256 |
continue
|
| 257 |
|
|
|
|
| 304 |
source_count=source_count,
|
| 305 |
sources=sources,
|
| 306 |
updated_at=vod.updated_at,
|
| 307 |
+
).model_dump()
|
|
|
|
|
|
|
| 308 |
|
| 309 |
+
await cache_set(cache_key, detail, settings.CACHE_TTL_VOD_DETAIL)
|
| 310 |
+
return ApiResponse.ok(detail)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
|
| 312 |
|
| 313 |
def _parse_play_url(play_url: str) -> list[dict]:
|
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel, Field
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class AdminCreateRequest(BaseModel):
|
| 5 |
+
username: str = Field(..., min_length=3, max_length=50)
|
| 6 |
+
password: str = Field(..., min_length=6, max_length=100)
|
| 7 |
+
nickname: str | None = Field(None, max_length=50)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class AdminUpdateRequest(BaseModel):
|
| 11 |
+
nickname: str | None = Field(None, max_length=50)
|
| 12 |
+
is_active: bool | None = None
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class AdminResetPasswordRequest(BaseModel):
|
| 16 |
+
password: str = Field(..., min_length=6, max_length=100)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class AdminAssignRolesRequest(BaseModel):
|
| 20 |
+
role_ids: list[int] = Field(default_factory=list)
|
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel, Field
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class CategoryUpdateRequest(BaseModel):
|
| 5 |
+
name: str | None = Field(None, min_length=1, max_length=50)
|
| 6 |
+
sort_order: int | None = Field(None, ge=0)
|
| 7 |
+
is_active: bool | None = None
|
| 8 |
+
parent_id: int | None = None
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class CategoryMappingItem(BaseModel):
|
| 12 |
+
category_id: int
|
| 13 |
+
source_type_id: int
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class CategoryMappingUpdateRequest(BaseModel):
|
| 17 |
+
source_id: int
|
| 18 |
+
mappings: list[CategoryMappingItem] = Field(..., min_length=1)
|
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel, Field
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class RoleCreateRequest(BaseModel):
|
| 5 |
+
name: str = Field(..., min_length=1, max_length=50)
|
| 6 |
+
code: str = Field(..., min_length=1, max_length=50, pattern=r"^[a-zA-Z0-9_]+$")
|
| 7 |
+
description: str | None = Field(None, max_length=200)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class RoleUpdateRequest(BaseModel):
|
| 11 |
+
name: str | None = Field(None, min_length=1, max_length=50)
|
| 12 |
+
description: str | None = Field(None, max_length=200)
|
| 13 |
+
status: int | None = Field(None, ge=0, le=1)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class RoleAssignPermissionsRequest(BaseModel):
|
| 17 |
+
permission_ids: list[int] = Field(default_factory=list)
|
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel, Field, HttpUrl
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class SourceCreateRequest(BaseModel):
|
| 5 |
+
name: str = Field(..., min_length=1, max_length=50)
|
| 6 |
+
code: str = Field(..., min_length=1, max_length=30, pattern=r"^[a-zA-Z0-9_-]+$")
|
| 7 |
+
base_url: str = Field(..., min_length=1, max_length=500)
|
| 8 |
+
site_url: str | None = Field(None, max_length=500)
|
| 9 |
+
play_from_m3u8: str | None = Field(None, max_length=30)
|
| 10 |
+
play_from_yun: str | None = Field(None, max_length=30)
|
| 11 |
+
parse_url: str | None = Field(None, max_length=500)
|
| 12 |
+
sync_interval: int = Field(60, ge=1, le=10080)
|
| 13 |
+
sort_order: int = Field(0, ge=0)
|
| 14 |
+
remark: str | None = Field(None, max_length=200)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class SourceUpdateRequest(BaseModel):
|
| 18 |
+
name: str | None = Field(None, min_length=1, max_length=50)
|
| 19 |
+
base_url: str | None = Field(None, min_length=1, max_length=500)
|
| 20 |
+
site_url: str | None = Field(None, max_length=500)
|
| 21 |
+
play_from_m3u8: str | None = Field(None, max_length=30)
|
| 22 |
+
play_from_yun: str | None = Field(None, max_length=30)
|
| 23 |
+
parse_url: str | None = Field(None, max_length=500)
|
| 24 |
+
sync_interval: int | None = Field(None, ge=1, le=10080)
|
| 25 |
+
sort_order: int | None = Field(None, ge=0)
|
| 26 |
+
remark: str | None = Field(None, max_length=200)
|
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel, Field
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class SystemConfigUpdateRequest(BaseModel):
|
| 5 |
+
sync_cron_hour: int | None = Field(None, ge=0, le=23)
|
| 6 |
+
access_token_expire_minutes: int | None = Field(None, ge=1, le=43200)
|
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel, Field
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class VodUpdateRequest(BaseModel):
|
| 5 |
+
name: str | None = Field(None, min_length=1, max_length=200)
|
| 6 |
+
sub_name: str | None = Field(None, max_length=500)
|
| 7 |
+
category_id: int | None = None
|
| 8 |
+
score: float | None = Field(None, ge=0, le=10)
|
| 9 |
+
douban_id: int | None = None
|
| 10 |
+
blurb: str | None = None
|
| 11 |
+
content: str | None = None
|
| 12 |
+
is_end: bool | None = None
|
| 13 |
+
area: str | None = Field(None, max_length=50)
|
| 14 |
+
year: str | None = Field(None, max_length=10)
|
| 15 |
+
actor: str | None = Field(None, max_length=2000)
|
| 16 |
+
director: str | None = Field(None, max_length=200)
|
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy import select
|
| 2 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 3 |
+
|
| 4 |
+
from app.models.user import User
|
| 5 |
+
from app.utils.auth import hash_password, verify_password, create_access_token
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
async def get_user_by_username(db: AsyncSession, username: str) -> User | None:
|
| 9 |
+
result = await db.execute(select(User).where(User.username == username))
|
| 10 |
+
return result.scalar_one_or_none()
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
async def get_user_by_id(db: AsyncSession, user_id: int) -> User | None:
|
| 14 |
+
result = await db.execute(select(User).where(User.id == user_id))
|
| 15 |
+
return result.scalar_one_or_none()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
async def authenticate_user(db: AsyncSession, username: str, password: str) -> User | None:
|
| 19 |
+
user = await get_user_by_username(db, username)
|
| 20 |
+
if not user or not user.is_active:
|
| 21 |
+
return None
|
| 22 |
+
if not verify_password(password, user.password_hash):
|
| 23 |
+
return None
|
| 24 |
+
return user
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def generate_user_token(user: User) -> str:
|
| 28 |
+
return create_access_token(str(user.id), "user")
|
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy import select
|
| 2 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 3 |
+
|
| 4 |
+
from app.models.category import Category, CategoryMapping
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
async def get_category_tree(db: AsyncSession, active_only: bool = True) -> list[dict]:
|
| 8 |
+
query = select(Category).order_by(Category.sort_order)
|
| 9 |
+
if active_only:
|
| 10 |
+
query = query.where(Category.is_active == True)
|
| 11 |
+
result = await db.execute(query)
|
| 12 |
+
all_cats = result.scalars().all()
|
| 13 |
+
|
| 14 |
+
cat_map: dict[int, dict] = {}
|
| 15 |
+
roots: list[dict] = []
|
| 16 |
+
|
| 17 |
+
for c in all_cats:
|
| 18 |
+
node = {
|
| 19 |
+
"id": c.id,
|
| 20 |
+
"name": c.name,
|
| 21 |
+
"parent_id": c.parent_id,
|
| 22 |
+
"sort_order": c.sort_order,
|
| 23 |
+
"children": [],
|
| 24 |
+
}
|
| 25 |
+
cat_map[c.id] = node
|
| 26 |
+
|
| 27 |
+
for c in all_cats:
|
| 28 |
+
node = cat_map[c.id]
|
| 29 |
+
if c.parent_id and c.parent_id in cat_map:
|
| 30 |
+
cat_map[c.parent_id]["children"].append(node)
|
| 31 |
+
elif not c.parent_id:
|
| 32 |
+
roots.append(node)
|
| 33 |
+
|
| 34 |
+
return roots
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
async def get_source_mappings(db: AsyncSession, source_id: int) -> dict[int, dict]:
|
| 38 |
+
result = await db.execute(
|
| 39 |
+
select(CategoryMapping).where(CategoryMapping.source_id == source_id)
|
| 40 |
+
)
|
| 41 |
+
mappings = result.scalars().all()
|
| 42 |
+
return {
|
| 43 |
+
m.source_type_id: {"category_id": m.category_id, "name": m.source_type_name}
|
| 44 |
+
for m in mappings
|
| 45 |
+
}
|
|
@@ -175,8 +175,8 @@ class Collector:
|
|
| 175 |
status=r["status"],
|
| 176 |
total_fetched=r["total_fetched"],
|
| 177 |
new_count=r["new_vods"],
|
| 178 |
-
|
| 179 |
-
|
| 180 |
finished_at=datetime.now(timezone.utc),
|
| 181 |
)
|
| 182 |
)
|
|
@@ -229,24 +229,42 @@ class Collector:
|
|
| 229 |
if not name:
|
| 230 |
return 0, 0
|
| 231 |
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
|
| 237 |
if vod:
|
| 238 |
cover = vod_data.get("vod_pic") or vod.cover
|
| 239 |
score_raw = vod_data.get("vod_score", "0.0")
|
| 240 |
score = float(score_raw) if score_raw and float(score_raw) > 0 else vod.score
|
| 241 |
-
|
| 242 |
-
if douban_id
|
| 243 |
-
douban_id =
|
| 244 |
-
else:
|
| 245 |
-
douban_id = vod.douban_id
|
| 246 |
|
| 247 |
vod.cover = cover
|
| 248 |
vod.score = score
|
| 249 |
-
vod.douban_id = douban_id
|
| 250 |
vod.blurb = vod_data.get("vod_blurb") or vod.blurb
|
| 251 |
vod.content = vod_data.get("vod_content") or vod.content
|
| 252 |
vod.remarks = vod_data.get("vod_remarks") or vod.remarks
|
|
@@ -254,18 +272,13 @@ class Collector:
|
|
| 254 |
vod.director = vod_data.get("vod_director") or vod.director
|
| 255 |
vod.area = vod_data.get("vod_area") or vod.area
|
| 256 |
vod.lang = vod_data.get("vod_lang") or vod.lang
|
| 257 |
-
vod.year =
|
| 258 |
vod.sub_name = vod_data.get("vod_sub") or vod_data.get("vod_en") or vod.sub_name
|
| 259 |
vod.updated_at = datetime.now(timezone.utc)
|
| 260 |
return 0, 1
|
| 261 |
else:
|
| 262 |
score_raw = vod_data.get("vod_score", "0.0")
|
| 263 |
score = float(score_raw) if score_raw and float(score_raw) > 0 else None
|
| 264 |
-
douban_id = vod_data.get("vod_douban_id")
|
| 265 |
-
if douban_id and str(douban_id).isdigit():
|
| 266 |
-
douban_id = int(douban_id)
|
| 267 |
-
else:
|
| 268 |
-
douban_id = None
|
| 269 |
|
| 270 |
vod = Vod(
|
| 271 |
name=name,
|
|
@@ -277,7 +290,7 @@ class Collector:
|
|
| 277 |
director=vod_data.get("vod_director"),
|
| 278 |
area=vod_data.get("vod_area"),
|
| 279 |
lang=vod_data.get("vod_lang"),
|
| 280 |
-
year=
|
| 281 |
duration=vod_data.get("vod_duration"),
|
| 282 |
score=score,
|
| 283 |
douban_id=douban_id,
|
|
@@ -296,8 +309,30 @@ class Collector:
|
|
| 296 |
if not name:
|
| 297 |
return 0, 0
|
| 298 |
|
| 299 |
-
|
| 300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
if not vod:
|
| 302 |
return 0, 0
|
| 303 |
|
|
|
|
| 175 |
status=r["status"],
|
| 176 |
total_fetched=r["total_fetched"],
|
| 177 |
new_count=r["new_vods"],
|
| 178 |
+
update_count=r["updated_vods"],
|
| 179 |
+
error_message=r["error"],
|
| 180 |
finished_at=datetime.now(timezone.utc),
|
| 181 |
)
|
| 182 |
)
|
|
|
|
| 229 |
if not name:
|
| 230 |
return 0, 0
|
| 231 |
|
| 232 |
+
douban_id = vod_data.get("vod_douban_id")
|
| 233 |
+
if douban_id and str(douban_id).isdigit():
|
| 234 |
+
douban_id = int(douban_id)
|
| 235 |
+
else:
|
| 236 |
+
douban_id = None
|
| 237 |
+
|
| 238 |
+
year = vod_data.get("vod_year")
|
| 239 |
+
|
| 240 |
+
vod = None
|
| 241 |
+
|
| 242 |
+
if douban_id:
|
| 243 |
+
result = await db.execute(select(Vod).where(Vod.douban_id == douban_id).limit(1))
|
| 244 |
+
vod = result.scalar_one_or_none()
|
| 245 |
+
|
| 246 |
+
if not vod and year:
|
| 247 |
+
result = await db.execute(
|
| 248 |
+
select(Vod).where(Vod.name == name, Vod.year == year).limit(1)
|
| 249 |
+
)
|
| 250 |
+
vod = result.scalar_one_or_none()
|
| 251 |
+
|
| 252 |
+
# ๅ
ๅบๆๅ็งฐๅน้
๏ผไป
ๅจๆฅๆบๆฐๆฎๆฒกๆ year ๆถๆ็จ๏ผ
|
| 253 |
+
# ้ฟๅ
ๅๅไธๅๅนดไปฝ๏ผๅฆ"ๆตๆตชๅฐ็"2019 vs 2023๏ผ่ขซ่ฏฏๅคไธบๅไธ้จ
|
| 254 |
+
if not vod and not year:
|
| 255 |
+
result = await db.execute(select(Vod).where(Vod.name == name).limit(1))
|
| 256 |
+
vod = result.scalar_one_or_none()
|
| 257 |
|
| 258 |
if vod:
|
| 259 |
cover = vod_data.get("vod_pic") or vod.cover
|
| 260 |
score_raw = vod_data.get("vod_score", "0.0")
|
| 261 |
score = float(score_raw) if score_raw and float(score_raw) > 0 else vod.score
|
| 262 |
+
|
| 263 |
+
if douban_id:
|
| 264 |
+
vod.douban_id = douban_id
|
|
|
|
|
|
|
| 265 |
|
| 266 |
vod.cover = cover
|
| 267 |
vod.score = score
|
|
|
|
| 268 |
vod.blurb = vod_data.get("vod_blurb") or vod.blurb
|
| 269 |
vod.content = vod_data.get("vod_content") or vod.content
|
| 270 |
vod.remarks = vod_data.get("vod_remarks") or vod.remarks
|
|
|
|
| 272 |
vod.director = vod_data.get("vod_director") or vod.director
|
| 273 |
vod.area = vod_data.get("vod_area") or vod.area
|
| 274 |
vod.lang = vod_data.get("vod_lang") or vod.lang
|
| 275 |
+
vod.year = year or vod.year
|
| 276 |
vod.sub_name = vod_data.get("vod_sub") or vod_data.get("vod_en") or vod.sub_name
|
| 277 |
vod.updated_at = datetime.now(timezone.utc)
|
| 278 |
return 0, 1
|
| 279 |
else:
|
| 280 |
score_raw = vod_data.get("vod_score", "0.0")
|
| 281 |
score = float(score_raw) if score_raw and float(score_raw) > 0 else None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
|
| 283 |
vod = Vod(
|
| 284 |
name=name,
|
|
|
|
| 290 |
director=vod_data.get("vod_director"),
|
| 291 |
area=vod_data.get("vod_area"),
|
| 292 |
lang=vod_data.get("vod_lang"),
|
| 293 |
+
year=year,
|
| 294 |
duration=vod_data.get("vod_duration"),
|
| 295 |
score=score,
|
| 296 |
douban_id=douban_id,
|
|
|
|
| 309 |
if not name:
|
| 310 |
return 0, 0
|
| 311 |
|
| 312 |
+
douban_id = vod_data.get("vod_douban_id")
|
| 313 |
+
if douban_id and str(douban_id).isdigit():
|
| 314 |
+
douban_id = int(douban_id)
|
| 315 |
+
else:
|
| 316 |
+
douban_id = None
|
| 317 |
+
|
| 318 |
+
year = vod_data.get("vod_year")
|
| 319 |
+
|
| 320 |
+
vod = None
|
| 321 |
+
|
| 322 |
+
if douban_id:
|
| 323 |
+
result = await db.execute(select(Vod).where(Vod.douban_id == douban_id).limit(1))
|
| 324 |
+
vod = result.scalar_one_or_none()
|
| 325 |
+
|
| 326 |
+
if not vod and year:
|
| 327 |
+
result = await db.execute(
|
| 328 |
+
select(Vod).where(Vod.name == name, Vod.year == year).limit(1)
|
| 329 |
+
)
|
| 330 |
+
vod = result.scalar_one_or_none()
|
| 331 |
+
|
| 332 |
+
if not vod and not year:
|
| 333 |
+
result = await db.execute(select(Vod).where(Vod.name == name).limit(1))
|
| 334 |
+
vod = result.scalar_one_or_none()
|
| 335 |
+
|
| 336 |
if not vod:
|
| 337 |
return 0, 0
|
| 338 |
|
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import logging
|
| 3 |
+
import time
|
| 4 |
+
from datetime import datetime, timezone
|
| 5 |
+
|
| 6 |
+
import httpx
|
| 7 |
+
from sqlalchemy import select, update
|
| 8 |
+
|
| 9 |
+
from app.database import async_session
|
| 10 |
+
from app.models.source_site import SourceSite
|
| 11 |
+
from app.models.source_health import SourceHealth
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger("health")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
async def check_source(source: SourceSite) -> dict:
|
| 17 |
+
"""ๅฏนๅไธชๆบ็ซๅ่ตทๅฅๅบทๆฃๆฅ๏ผ่ฟๅๆฃๆฅ็ปๆ"""
|
| 18 |
+
start = time.monotonic()
|
| 19 |
+
error_msg = None
|
| 20 |
+
is_success = False
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
async with httpx.AsyncClient(timeout=10, follow_redirects=True) as client:
|
| 24 |
+
resp = await client.get(source.base_url, params={"ac": "list", "pg": "1"})
|
| 25 |
+
resp.raise_for_status()
|
| 26 |
+
data = resp.json()
|
| 27 |
+
# ้ช่ฏ่ฟๅๆ ผๅผๆฏๅฆ็ฌฆๅ้ขๆ
|
| 28 |
+
if "list" in data or "class" in data or "total" in data:
|
| 29 |
+
is_success = True
|
| 30 |
+
else:
|
| 31 |
+
error_msg = "ๅๅบๆ ผๅผไธ็ฌฆๅ้ขๆ"
|
| 32 |
+
except httpx.TimeoutException:
|
| 33 |
+
error_msg = "่ฟๆฅ่ถ
ๆถ"
|
| 34 |
+
except httpx.HTTPStatusError as e:
|
| 35 |
+
error_msg = f"HTTP {e.response.status_code}"
|
| 36 |
+
except Exception as e:
|
| 37 |
+
error_msg = str(e)[:200]
|
| 38 |
+
|
| 39 |
+
response_time_ms = int((time.monotonic() - start) * 1000)
|
| 40 |
+
|
| 41 |
+
return {
|
| 42 |
+
"source_id": source.id,
|
| 43 |
+
"is_success": is_success,
|
| 44 |
+
"response_time_ms": response_time_ms,
|
| 45 |
+
"error_message": error_msg,
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
async def run_health_checks() -> list[dict]:
|
| 50 |
+
"""ๅฏนๆๆๅฏ็จ็ๆบ็ซๆง่กๅฅๅบทๆฃๆฅ"""
|
| 51 |
+
async with async_session() as db:
|
| 52 |
+
result = await db.execute(
|
| 53 |
+
select(SourceSite).where(SourceSite.is_active == True).order_by(SourceSite.sort_order)
|
| 54 |
+
)
|
| 55 |
+
sources = result.scalars().all()
|
| 56 |
+
|
| 57 |
+
if not sources:
|
| 58 |
+
return []
|
| 59 |
+
|
| 60 |
+
# ๅนถๅๆฃๆฅ๏ผๆๅค 5 ไธชๅนถๅ
|
| 61 |
+
semaphore = asyncio.Semaphore(5)
|
| 62 |
+
|
| 63 |
+
async def check_with_semaphore(source):
|
| 64 |
+
async with semaphore:
|
| 65 |
+
return await check_source(source)
|
| 66 |
+
|
| 67 |
+
results = await asyncio.gather(*[check_with_semaphore(s) for s in sources])
|
| 68 |
+
|
| 69 |
+
# ๆน้ๅๅ
ฅๆฃๆฅ็ปๆ
|
| 70 |
+
async with async_session() as db:
|
| 71 |
+
now = datetime.now(timezone.utc)
|
| 72 |
+
for r in results:
|
| 73 |
+
record = SourceHealth(
|
| 74 |
+
source_id=r["source_id"],
|
| 75 |
+
check_type="api",
|
| 76 |
+
is_success=r["is_success"],
|
| 77 |
+
response_time_ms=r["response_time_ms"],
|
| 78 |
+
error_message=r["error_message"],
|
| 79 |
+
checked_at=now,
|
| 80 |
+
)
|
| 81 |
+
db.add(record)
|
| 82 |
+
|
| 83 |
+
# ๅๆญฅๆดๆฐ source_site ็ๆๅๅฅๅบท็ถๆ
|
| 84 |
+
await db.execute(
|
| 85 |
+
update(SourceSite)
|
| 86 |
+
.where(SourceSite.id == r["source_id"])
|
| 87 |
+
.values(last_sync_status="healthy" if r["is_success"] else "unhealthy")
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
await db.commit()
|
| 91 |
+
|
| 92 |
+
logger.info(f"Health check completed: {len(results)} sources checked, "
|
| 93 |
+
f"{sum(1 for r in results if r['is_success'])} healthy")
|
| 94 |
+
return list(results)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
async def get_latest_health(db, source_ids: list[int] | None = None) -> dict[int, dict]:
|
| 98 |
+
"""่ทๅๆฏไธชๆบ็ซๆๆฐ็ๅฅๅบทๆฃๆฅ่ฎฐๅฝ"""
|
| 99 |
+
from sqlalchemy import func
|
| 100 |
+
|
| 101 |
+
# ๅญๆฅ่ฏข๏ผๆฏไธช source_id ็ๆๆฐ checked_at
|
| 102 |
+
subq = (
|
| 103 |
+
select(SourceHealth.source_id, func.max(SourceHealth.checked_at).label("latest"))
|
| 104 |
+
.group_by(SourceHealth.source_id)
|
| 105 |
+
.subquery()
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
query = (
|
| 109 |
+
select(SourceHealth)
|
| 110 |
+
.join(subq, (SourceHealth.source_id == subq.c.source_id) &
|
| 111 |
+
(SourceHealth.checked_at == subq.c.latest))
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
if source_ids:
|
| 115 |
+
query = query.where(SourceHealth.source_id.in_(source_ids))
|
| 116 |
+
|
| 117 |
+
result = await db.execute(query)
|
| 118 |
+
records = result.scalars().all()
|
| 119 |
+
|
| 120 |
+
return {
|
| 121 |
+
r.source_id: {
|
| 122 |
+
"is_success": r.is_success,
|
| 123 |
+
"response_time_ms": r.response_time_ms,
|
| 124 |
+
"error_message": r.error_message,
|
| 125 |
+
"checked_at": str(r.checked_at) if r.checked_at else None,
|
| 126 |
+
}
|
| 127 |
+
for r in records
|
| 128 |
+
}
|
|
@@ -2,7 +2,9 @@ import logging
|
|
| 2 |
|
| 3 |
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
| 4 |
from apscheduler.triggers.cron import CronTrigger
|
|
|
|
| 5 |
|
|
|
|
| 6 |
from app.services.collector import collector
|
| 7 |
|
| 8 |
logger = logging.getLogger("scheduler")
|
|
@@ -11,7 +13,12 @@ scheduler = AsyncIOScheduler()
|
|
| 11 |
|
| 12 |
|
| 13 |
def start_scheduler():
|
| 14 |
-
sync_hour =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
scheduler.add_job(
|
| 17 |
collector.sync_all,
|
|
@@ -40,6 +47,16 @@ def start_scheduler():
|
|
| 40 |
misfire_grace_time=14400,
|
| 41 |
)
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
scheduler.start()
|
| 44 |
logger.info(f"Scheduler started with sync_hour={sync_hour}")
|
| 45 |
|
|
|
|
| 2 |
|
| 3 |
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
| 4 |
from apscheduler.triggers.cron import CronTrigger
|
| 5 |
+
from apscheduler.triggers.interval import IntervalTrigger
|
| 6 |
|
| 7 |
+
from app.config import settings
|
| 8 |
from app.services.collector import collector
|
| 9 |
|
| 10 |
logger = logging.getLogger("scheduler")
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
def start_scheduler():
|
| 16 |
+
sync_hour = settings.SYNC_CRON_HOUR
|
| 17 |
+
|
| 18 |
+
# ็งป้คๅทฒๅญๅจ็ๅๅ job๏ผ้ฟๅ
้ๅฏๆถ ConflictingIdError
|
| 19 |
+
for job_id in ("sync_daily", "sync_weekly", "sync_monthly", "health_check"):
|
| 20 |
+
if scheduler.get_job(job_id):
|
| 21 |
+
scheduler.remove_job(job_id)
|
| 22 |
|
| 23 |
scheduler.add_job(
|
| 24 |
collector.sync_all,
|
|
|
|
| 47 |
misfire_grace_time=14400,
|
| 48 |
)
|
| 49 |
|
| 50 |
+
# ๆบ็ซๅฅๅบทๆฃๆฅ๏ผๆฏ 30 ๅ้ๆง่กไธๆฌก
|
| 51 |
+
from app.services.health import run_health_checks
|
| 52 |
+
scheduler.add_job(
|
| 53 |
+
run_health_checks,
|
| 54 |
+
trigger=IntervalTrigger(minutes=30),
|
| 55 |
+
id="health_check",
|
| 56 |
+
name="ๆบ็ซๅฅๅบทๆฃๆฅ",
|
| 57 |
+
misfire_grace_time=300,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
scheduler.start()
|
| 61 |
logger.info(f"Scheduler started with sync_hour={sync_hour}")
|
| 62 |
|
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime, timezone
|
| 2 |
+
|
| 3 |
+
from sqlalchemy import select, update
|
| 4 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 5 |
+
|
| 6 |
+
from app.database import async_session
|
| 7 |
+
from app.models.sync_log import SyncLog
|
| 8 |
+
from app.models.source_site import SourceSite
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
async def create_sync_log(db: AsyncSession, source_id: int, range_type: str) -> int:
|
| 12 |
+
log = SyncLog(
|
| 13 |
+
source_id=source_id,
|
| 14 |
+
range_type=range_type,
|
| 15 |
+
status="running",
|
| 16 |
+
started_at=datetime.now(timezone.utc),
|
| 17 |
+
)
|
| 18 |
+
db.add(log)
|
| 19 |
+
await db.flush()
|
| 20 |
+
return log.id
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
async def finish_sync_log(log_id: int, result: dict) -> None:
|
| 24 |
+
async with async_session() as db:
|
| 25 |
+
await db.execute(
|
| 26 |
+
update(SyncLog)
|
| 27 |
+
.where(SyncLog.id == log_id)
|
| 28 |
+
.values(
|
| 29 |
+
status=result["status"],
|
| 30 |
+
total_fetched=result.get("total_fetched", 0),
|
| 31 |
+
new_count=result.get("new_vods", 0),
|
| 32 |
+
update_count=result.get("updated_vods", 0),
|
| 33 |
+
error_message=result.get("error"),
|
| 34 |
+
finished_at=datetime.now(timezone.utc),
|
| 35 |
+
)
|
| 36 |
+
)
|
| 37 |
+
await db.commit()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
async def get_sync_logs(
|
| 41 |
+
db: AsyncSession,
|
| 42 |
+
source_id: int | None = None,
|
| 43 |
+
status: str | None = None,
|
| 44 |
+
page: int = 1,
|
| 45 |
+
page_size: int = 20,
|
| 46 |
+
) -> tuple[list[SyncLog], int]:
|
| 47 |
+
from sqlalchemy import func
|
| 48 |
+
query = select(SyncLog).order_by(SyncLog.started_at.desc())
|
| 49 |
+
count_query = select(func.count(SyncLog.id))
|
| 50 |
+
|
| 51 |
+
if source_id:
|
| 52 |
+
query = query.where(SyncLog.source_id == source_id)
|
| 53 |
+
count_query = count_query.where(SyncLog.source_id == source_id)
|
| 54 |
+
if status:
|
| 55 |
+
query = query.where(SyncLog.status == status)
|
| 56 |
+
count_query = count_query.where(SyncLog.status == status)
|
| 57 |
+
|
| 58 |
+
total_result = await db.execute(count_query)
|
| 59 |
+
total = total_result.scalar() or 0
|
| 60 |
+
|
| 61 |
+
result = await db.execute(query.offset((page - 1) * page_size).limit(page_size))
|
| 62 |
+
logs = result.scalars().all()
|
| 63 |
+
return list(logs), total
|
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy import func, select
|
| 2 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 3 |
+
|
| 4 |
+
from app.models.category import Category
|
| 5 |
+
from app.models.vod import Vod
|
| 6 |
+
from app.models.vod_source import VodSource
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
async def get_vod_by_id(db: AsyncSession, vod_id: int, hidden_ok: bool = False) -> Vod | None:
|
| 10 |
+
query = select(Vod).where(Vod.id == vod_id)
|
| 11 |
+
if not hidden_ok:
|
| 12 |
+
query = query.where(Vod.is_hidden == False)
|
| 13 |
+
result = await db.execute(query)
|
| 14 |
+
return result.scalar_one_or_none()
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
async def batch_get_category_names(db: AsyncSession, category_ids: list[int]) -> dict[int, str]:
|
| 18 |
+
if not category_ids:
|
| 19 |
+
return {}
|
| 20 |
+
result = await db.execute(
|
| 21 |
+
select(Category.id, Category.name).where(Category.id.in_(category_ids))
|
| 22 |
+
)
|
| 23 |
+
return {row[0]: row[1] for row in result.all()}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
async def batch_get_source_counts(db: AsyncSession, vod_ids: list[int]) -> dict[int, int]:
|
| 27 |
+
if not vod_ids:
|
| 28 |
+
return {}
|
| 29 |
+
result = await db.execute(
|
| 30 |
+
select(VodSource.vod_id, func.count(VodSource.id))
|
| 31 |
+
.where(VodSource.vod_id.in_(vod_ids), VodSource.is_available == True)
|
| 32 |
+
.group_by(VodSource.vod_id)
|
| 33 |
+
)
|
| 34 |
+
return {row[0]: row[1] for row in result.all()}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
async def increment_view_count(db: AsyncSession, vod_id: int) -> None:
|
| 38 |
+
await db.execute(
|
| 39 |
+
Vod.__table__.update().where(Vod.id == vod_id).values(view_count=Vod.view_count + 1)
|
| 40 |
+
)
|
|
@@ -1,7 +1,7 @@
|
|
| 1 |
from datetime import datetime, timedelta, timezone
|
| 2 |
|
| 3 |
import bcrypt
|
| 4 |
-
|
| 5 |
|
| 6 |
from app.config import settings
|
| 7 |
|
|
@@ -19,4 +19,9 @@ def create_access_token(subject: str, token_type: str = "admin", expires_delta:
|
|
| 19 |
expires_delta = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
| 20 |
expire = datetime.now(timezone.utc) + expires_delta
|
| 21 |
to_encode = {"sub": subject, "type": token_type, "exp": expire}
|
| 22 |
-
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm="HS256")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from datetime import datetime, timedelta, timezone
|
| 2 |
|
| 3 |
import bcrypt
|
| 4 |
+
import jwt
|
| 5 |
|
| 6 |
from app.config import settings
|
| 7 |
|
|
|
|
| 19 |
expires_delta = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
| 20 |
expire = datetime.now(timezone.utc) + expires_delta
|
| 21 |
to_encode = {"sub": subject, "type": token_type, "exp": expire}
|
| 22 |
+
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm="HS256")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def decode_access_token(token: str) -> dict:
|
| 26 |
+
"""่งฃ็ JWT๏ผๅคฑ่ดฅๆๅบ jwt.PyJWTError"""
|
| 27 |
+
return jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
|
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
m3u8 ๅ็่ตๆบไธๅบ
|
| 2 |
+
ๅ
จ้จm3u8็ด้พ่ตๆบ๏ผๅฏไปฅ็จdplayerใckplayerใxgplayer็ญๆญๆพๅจๆญๆพ
|
| 3 |
+
|
| 4 |
+
2022-2026ๅนดๆจ่ๆฅๅฃ
|
| 5 |
+
ๆ้่ตๆบ็ซ https://jszy333.com/
|
| 6 |
+
่ฑ็ฃ่ตๆบ็ซ https://dbzy.tv
|
| 7 |
+
|
| 8 |
+
็ดขๅฐผ่ตๆบ[้ๅบฆไธ้, ็ฆๅฝๅค] https://suonizy.net/
|
| 9 |
+
|
| 10 |
+
OK่ตๆบ [้ๅบฆ่ฟ่ก, ็ฆๅฝๅค, ๅๅๆขๅ ๆฌกไบ] https://okzyw.cc/
|
| 11 |
+
|
| 12 |
+
็บข็่ตๆบ็ซใ้ๅบฆไธ่ฌ, ไธ่ฟๆฏ่็่ตๆบใhttps://www.hongniuzy.com/
|
| 13 |
+
|
| 14 |
+
ๆ ๅฐฝ่ตๆบ็ซใ้ๅบฆไธ่ฌใhttp://www.wujinzy.net/
|
| 15 |
+
|
| 16 |
+
ๅ
้่ตๆบ็ซใ้ๅบฆไธ่ฌใhttps://guangsuzy.com/
|
| 17 |
+
U้
ท่ตๆบ็ซใๆๆฐ็ๆบ,ๅไธCDNใhttps://ukuzy0.com/
|
| 18 |
+
ๆฐๆตช่ตๆบ็ซใHTTPS่ตๆบ,m3u8็ด้พใhttps://www.xinlangzy.com/
|
| 19 |
+
ๅฟซ่ฝฆ่ตๆบ็ซใHTTPS่ตๆบ,m3u8็ด้พใhttp://kuaichezy.com/
|
| 20 |
+
้้นฐ่ตๆบ็ซใๅฝๅ
CDN,็งๆ็งๆญใhttp://jinyingzy.com/
|
| 21 |
+
ๆท็่ตๆบ็ซใHTTPS่ตๆบ,m3u8็ด้พใhttps://www.taopianzy.com/
|
| 22 |
+
ๅง้พ่ตๆบ็ซใHTTPS่ตๆบ,่ท้ฉฌ็ฏๅนฟๅใhttp://wolongzyw.com/
|
| 23 |
+
CK่ตๆบ็ซใHTTPS่ตๆบ,่ท้ฉฌ็ฏๅนฟๅใhttp://www.ckzy1.com/
|
|
@@ -0,0 +1,534 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ๅฝฑ่ง่ตๆบ็ซ API ๆฅๅฃๆๆกฃ
|
| 2 |
+
|
| 3 |
+
> ๆดๆฐๆถ้ด๏ผ2026-05-12
|
| 4 |
+
> ๆๆ่ตๆบ็ซๅๅบไบ่นๆCMSๅผๆพAPIๆ ๅ๏ผๆฅๅฃ่ง่ๅบๆฌไธ่ด
|
| 5 |
+
|
| 6 |
+
---
|
| 7 |
+
|
| 8 |
+
## ็ฎๅฝ
|
| 9 |
+
|
| 10 |
+
1. [้็จAPI่ง่](#้็จapi่ง่)
|
| 11 |
+
2. [ๅฏ็จ่ตๆบ็ซไธ่ง](#ๅฏ็จ่ตๆบ็ซไธ่ง)
|
| 12 |
+
3. [ๅ่ตๆบ็ซ่ฏฆ็ปๆฅๅฃ](#ๅ่ตๆบ็ซ่ฏฆ็ปๆฅๅฃ)
|
| 13 |
+
4. [ๆญๆพ่ฏดๆ](#ๆญๆพ่ฏดๆ)
|
| 14 |
+
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
## ้็จAPI่ง่
|
| 18 |
+
|
| 19 |
+
ๆๆ่ตๆบ็ซๅ้ตๅพช่นๆCMS้้APIๆ ๅ๏ผๆฏๆไปฅไธ้็จๅๆฐ๏ผ
|
| 20 |
+
|
| 21 |
+
### ่ฏทๆฑๅๆฐ
|
| 22 |
+
|
| 23 |
+
| ๅๆฐ | ็ฑปๅ | ๅฟ
ๅกซ | ่ฏดๆ | ็คบไพ |
|
| 24 |
+
|---|---|---|---|---|
|
| 25 |
+
| `ac` | string | ๅฆ | ๆไฝๆจกๅผ๏ผ่งไธ่กจ๏ผ๏ผไธบ็ฉบ=ๅ่กจๆ ๅๆจกๅผ | `ac=detail` |
|
| 26 |
+
| `ids` | string | ๅฆ | ๅฝฑ็ID๏ผๅคไธช็จ้ๅท้ๅผ | `ids=110602` |
|
| 27 |
+
| `t` | int | ๅฆ | ๆๅ็ฑปID็ญ้ | `t=2` |
|
| 28 |
+
| `h` | int | ๅฆ | ๆ่ฟๅคๅฐๅฐๆถๅ
ๆดๆฐ็ๆฐๆฎ | `h=24` |
|
| 29 |
+
| `pg` | int | ๅฆ | ้กต็ ๏ผ้ป่ฎค1 | `pg=2` |
|
| 30 |
+
| `wd` | string | ๅฆ | ๆ็ดขๅ
ณ้ฎ่ฏ๏ผlikeๆจก็ณๅน้
๏ผ | `wd=ๅบไฝๅนด` |
|
| 31 |
+
| `limit` | int | ๅฆ | ๆฏ้กตๆกๆฐ๏ผ้ป่ฎค20 | `limit=50` |
|
| 32 |
+
|
| 33 |
+
### ac ๆไฝๆจกๅผ
|
| 34 |
+
|
| 35 |
+
| acๅผ | ่ฏดๆ | ่ฟๅๅญๆฎต |
|
| 36 |
+
|---|---|---|
|
| 37 |
+
| (็ฉบ) | ๆ ๅๅ่กจๆจกๅผ | ๅบ็กๅญๆฎต + classๅ็ฑป |
|
| 38 |
+
| `list` | ๅ่กจๆจกๅผ | ไป
ๅบ็กๅญๆฎต๏ผid/ๅ็งฐ/ๅ็ฑป/ๆดๆฐๆถ้ด/ๅคๆณจ/ๆญๆพๆฅๆบ๏ผ |
|
| 39 |
+
| `videolist` | ่ง้ขๅ่กจๆจกๅผ | ๅบ็กๅญๆฎต + ๆดๅค่ฏฆๆ
๏ผๅพ็/ๆผๅ/ๅฐๅบ/ๅนดไปฝ็ญ๏ผไธๅซๆญๆพๅฐๅ๏ผ |
|
| 40 |
+
| `detail` | ่ฏฆๆ
ๆจกๅผ | **ๅ
จ้จๅญๆฎต**๏ผๅซๆญๆพๅฐๅใ็ฎไปใ่ฏๅ็ญ |
|
| 41 |
+
|
| 42 |
+
### URL่ทฏๅพๆๅฎๆฅๆบๅๆ ผๅผ
|
| 43 |
+
|
| 44 |
+
```
|
| 45 |
+
/api.php/provide/vod/from/{ๆฅๆบๆ ่ฏ}/at/{ๆ ผๅผ}/
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
- **ๆฅๆบๆ ่ฏ**๏ผๅ็ซไธๅ๏ผๅฆ `jinyingm3u8`ใ`hnm3u8`ใ`snm3u8` ็ญ
|
| 49 |
+
- **ๆ ผๅผ**๏ผ`xml`ใ`json`/`josn`๏ผ้จๅ็ซๆผๅไธบjosn๏ผใ`xmlsea`๏ผๆตทๆดCMSไธ็จ๏ผ
|
| 50 |
+
|
| 51 |
+
### ้็จ่ฟๅ็ปๆ๏ผJSON๏ผ
|
| 52 |
+
|
| 53 |
+
```json
|
| 54 |
+
{
|
| 55 |
+
"code": 1,
|
| 56 |
+
"msg": "ๆฐๆฎๅ่กจ",
|
| 57 |
+
"page": 1,
|
| 58 |
+
"pagecount": 5178,
|
| 59 |
+
"limit": "20",
|
| 60 |
+
"total": 103547,
|
| 61 |
+
"list": [ ... ],
|
| 62 |
+
"class": [ ... ]
|
| 63 |
+
}
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
### ้็จๅญๆฎต่ฏดๆ
|
| 67 |
+
|
| 68 |
+
| ๅญๆฎต | ่ฏดๆ | ๅคๆณจ |
|
| 69 |
+
|---|---|---|
|
| 70 |
+
| `vod_id` | ๅฝฑ็ID | ๅฏไธๆ ่ฏ |
|
| 71 |
+
| `vod_name` | ๅฝฑ็ๅ | |
|
| 72 |
+
| `type_id` | ๅ็ฑปID | |
|
| 73 |
+
| `type_id_1` | ไธ็บงๅ็ฑปID | |
|
| 74 |
+
| `type_name` | ๅ็ฑปๅ็งฐ | |
|
| 75 |
+
| `vod_en` | ่ฑๆๆผ้ณ | |
|
| 76 |
+
| `vod_pic` | ๅฐ้ขๅพ | CDNๅฐๅ |
|
| 77 |
+
| `vod_actor` | ๆผๅ | ้ๅทๅ้ |
|
| 78 |
+
| `vod_director` | ๅฏผๆผ | |
|
| 79 |
+
| `vod_area` | ๅฐๅบ | |
|
| 80 |
+
| `vod_lang` | ่ฏญ่จ | |
|
| 81 |
+
| `vod_year` | ๅนดไปฝ | |
|
| 82 |
+
| `vod_remarks` | ๅคๆณจ | ๅฆ"็ฌฌ39้"ใ"ๅ
จ้ๅฎ็ป" |
|
| 83 |
+
| `vod_score` | ่ฏๅ | |
|
| 84 |
+
| `vod_content` | ็ฎไป | HTMLๅ
ๅฎน |
|
| 85 |
+
| `vod_duration` | ๆถ้ฟ | ๅฆ"100ๅ้" |
|
| 86 |
+
| `vod_douban_id` | ่ฑ็ฃID | ้จๅ็ซๆ |
|
| 87 |
+
| `vod_play_from` | ๆญๆพๆฅๆบ | ๅคไธช็จ `$$$` ๅ้ |
|
| 88 |
+
| `vod_play_url` | ๆญๆพๅฐๅ | ๅคไธชๆฅๆบ็จ `$$$` ๅ้๏ผ้ๆฐ็จ `#` ๅ้ |
|
| 89 |
+
| `vod_time` | ๆดๆฐๆถ้ด | |
|
| 90 |
+
|
| 91 |
+
### ๆญๆพๅฐๅๆ ผๅผ
|
| 92 |
+
|
| 93 |
+
`vod_play_from` ๅ `vod_play_url` ็จ `$$$` ไธไธๅฏนๅบ๏ผ
|
| 94 |
+
|
| 95 |
+
```
|
| 96 |
+
vod_play_from: "jinyingyun$$$jinyingm3u8"
|
| 97 |
+
vod_play_url: "ๅ
จ้ๅฎ็ป$https://xxx/play/abc$$$ๅ
จ้ๅฎ็ป$https://xxx/play/abc/index.m3u8"
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
ๅไธชๆฅๆบๅ
๏ผๅค้็จ `#` ๅ้๏ผๆฏ้ๆ ผๅผไธบ `้ๅ$ๆญๆพๅฐๅ`๏ผ
|
| 101 |
+
|
| 102 |
+
```
|
| 103 |
+
็ฌฌ01้$https://xxx/01/index.m3u8#็ฌฌ02้$https://xxx/02/index.m3u8
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
---
|
| 107 |
+
|
| 108 |
+
## ๅฏ็จ่ตๆบ็ซไธ่ง
|
| 109 |
+
|
| 110 |
+
| ็ซ็น | ๅฎ็ฝ | APIๅบ็กๅฐๅ | ็ถๆ | ่ตๆบๆป้ | ๆญๆพๆฅๆบๆ ่ฏ | ้ๅบฆ |
|
| 111 |
+
|---|---|---|---|---|---|---|
|
| 112 |
+
| ๆ้่ตๆบ | jszy333.com | `https://jszyapi.com/api.php/provide/vod/` | ๅฏ็จ | 101,840 | `jsm3u8` | ๅฟซ |
|
| 113 |
+
| ่ฑ็ฃ่ตๆบ | dbzy.tv | `https://dbzy.tv/api.php/provide/vod/` | ๅฏ็จ | 126,890 | `dbm3u8` | ๅฟซ |
|
| 114 |
+
| ็ดขๅฐผ่ตๆบ | suonizy.net | `https://suoniapi.com/api.php/provide/vod/` | ๅฏ็จ | 135,704 | `snm3u8` | ๅฟซ๏ผ็ฆๅฝๅค |
|
| 115 |
+
| OK่ตๆบ | okzyw.cc | `https://okzyw.cc/api.php/provide/vod/` | ๅฏ็จ | - | `okm3u8` | ่ก๏ผ็ฆๅฝๅค |
|
| 116 |
+
| ็บข็่ตๆบ | hongniuzy.com | `https://www.hongniuzy2.com/api.php/provide/vod/` | ๅฏ็จ | 103,249 | `hnm3u8`ใ`hnyun` | ไธ่ฌ |
|
| 117 |
+
| ้้นฐ่ตๆบ | jinyingzy.com | `https://jyzyapi.com/provide/vod/` | ๅฏ็จ | 103,547 | `jinyingm3u8`ใ`jinyingyun` | ๅฟซ |
|
| 118 |
+
| ๆฐๆตช่ตๆบ | xinlangzy.com | `https://www.xinlangzy.com/api.php/provide/vod/` | ๅฏ็จ | - | `xlm3u8`ใ`xlyun` | - |
|
| 119 |
+
| ๅฟซ่ฝฆ่ตๆบ | kuaichezy.com | `http://kuaichezy.com/api.php/provide/vod/` | ๅฏ็จ | 119,079 | `kcm3u8` | - |
|
| 120 |
+
| CK่ตๆบ | ckzy1.com | `http://www.ckzy1.com/api.php/provide/vod/` | ๅฏ็จ | - | `ckm3u8` | - |
|
| 121 |
+
| ๅง้พ่ตๆบ | wolongzyw.com | `http://wolongzyw.com/api.php/provide/vod/` | ไธๅฏ็จ | - | - | ็ฝ็ซๅฏ่ฎฟ้ฎไฝAPIๅคฑๆ |
|
| 122 |
+
| ๅ
้่ตๆบ | guangsuzy.com | - | ไธๅฏ็จ | - | - | ็ฝ็ซๅAPIๅๆ ๆณ่ฎฟ้ฎ |
|
| 123 |
+
| U้
ท่ตๆบ | ukuzy0.com | - | ไธๅฏ็จ | - | - | API่ฟๅclosed/็ฉบ |
|
| 124 |
+
| ๆ ๅฐฝ่ตๆบ | wujinzy.net | - | ไธๅฏ็จ | - | - | 404 |
|
| 125 |
+
| ๆท็่ตๆบ | taopianzy.com | - | ไธๅฏ็จ | - | - | 404 |
|
| 126 |
+
|
| 127 |
+
---
|
| 128 |
+
|
| 129 |
+
## ๅ่ตๆบ็ซ่ฏฆ็ปๆฅๅฃ
|
| 130 |
+
|
| 131 |
+
### 1. ๆ้่ตๆบ็ซ
|
| 132 |
+
|
| 133 |
+
- **ๅฎ็ฝ**๏ผhttps://jszy333.com/
|
| 134 |
+
- **APIๅบ็ก**๏ผ`https://jszyapi.com/api.php/provide/vod/`
|
| 135 |
+
- **ๆญๆพๆฅๆบ**๏ผ`jsm3u8`
|
| 136 |
+
- **ๆป่ตๆบ**๏ผ101,840
|
| 137 |
+
- **ๆจ่ๆฅๅฃ**๏ผ
|
| 138 |
+
|
| 139 |
+
| ๆฅๅฃ | ๅฐๅ |
|
| 140 |
+
|---|---|
|
| 141 |
+
| ๆ ๅๅ่กจ | `https://jszyapi.com/api.php/provide/vod/` |
|
| 142 |
+
| ่ง้ขๅ่กจ | `https://jszyapi.com/api.php/provide/vod/?ac=videolist` |
|
| 143 |
+
| ่ฏฆๆ
ๆจกๅผ | `https://jszyapi.com/api.php/provide/vod/?ac=detail` |
|
| 144 |
+
| XMLๆ ผๅผ | `https://jszyapi.com/api.php/provide/vod/at/xml/` |
|
| 145 |
+
|
| 146 |
+
### 2. ่ฑ็ฃ่ตๆบ็ซ
|
| 147 |
+
|
| 148 |
+
- **ๅฎ็ฝ**๏ผhttps://dbzy.tv
|
| 149 |
+
- **APIๅบ็ก**๏ผ`https://dbzy.tv/api.php/provide/vod/`
|
| 150 |
+
- **ๆญๆพๆฅๆบ**๏ผ`dbm3u8`
|
| 151 |
+
- **ๆป่ตๆบ**๏ผ126,890
|
| 152 |
+
- **ๅพ็CDN**๏ผ`dbzy5.com`
|
| 153 |
+
- **ๆจ่ๆฅๅฃ**๏ผ
|
| 154 |
+
|
| 155 |
+
| ๆฅๅฃ | ๅฐๅ |
|
| 156 |
+
|---|---|
|
| 157 |
+
| ่ง้ขๅ่กจ | `https://dbzy.tv/api.php/provide/vod/?ac=videolist` |
|
| 158 |
+
| ่ฏฆๆ
ๆจกๅผ | `https://dbzy.tv/api.php/provide/vod/?ac=detail` |
|
| 159 |
+
|
| 160 |
+
### 3. ็ดขๅฐผ่ตๆบ็ซ
|
| 161 |
+
|
| 162 |
+
- **ๅฎ็ฝ**๏ผhttps://suonizy.net/ ๏ผๅค็จ๏ผsuonizy.cc๏ผ
|
| 163 |
+
- **APIๅบ็ก**๏ผ`https://suoniapi.com/api.php/provide/vod/`
|
| 164 |
+
- **ๆญๆพๆฅๆบ**๏ผ`snm3u8`
|
| 165 |
+
- **ๆป่ตๆบ**๏ผ135,704
|
| 166 |
+
- **ๅพ็CDN**๏ผ`snzypic.vip`
|
| 167 |
+
- **M3U8่งฃๆ**๏ผ`https://dxfbk.com/?url=`
|
| 168 |
+
- **ๆจ่ๆฅๅฃ**๏ผ
|
| 169 |
+
|
| 170 |
+
| ๆฅๅฃ | ๅฐๅ |
|
| 171 |
+
|---|---|
|
| 172 |
+
| ๆ ๅๅ่กจ | `https://suoniapi.com/api.php/provide/vod/` |
|
| 173 |
+
| M3U8 XML | `https://suoniapi.com/api.php/provide/vod/from/snm3u8/at/xml/` |
|
| 174 |
+
| JSON | `https://suoniapi.com/api.php/provide/vod/?ac=list` |
|
| 175 |
+
| ่ฏฆๆ
ๆจกๅผ | `https://suoniapi.com/api.php/provide/vod/?ac=detail` |
|
| 176 |
+
|
| 177 |
+
### 4. OK่ตๆบ็ซ
|
| 178 |
+
|
| 179 |
+
- **ๅฎ็ฝ**๏ผhttps://okzyw.cc/
|
| 180 |
+
- **APIๅบ็ก**๏ผ`https://okzyw.cc/api.php/provide/vod/`
|
| 181 |
+
- **ๆญๆพๆฅๆบ**๏ผ`okm3u8`
|
| 182 |
+
- **ๆณจๆ**๏ผๅๅๆข่ฟๅ ๆฌก๏ผ็ฆๅฝๅค่ฎฟ้ฎ
|
| 183 |
+
- **ๆจ่ๆฅๅฃ**๏ผ
|
| 184 |
+
|
| 185 |
+
| ๆฅๅฃ | ๅฐๅ |
|
| 186 |
+
|---|---|
|
| 187 |
+
| ๆ ๅๅ่กจ | `https://okzyw.cc/api.php/provide/vod/` |
|
| 188 |
+
| ่ฏฆๆ
ๆจกๅผ | `https://okzyw.cc/api.php/provide/vod/?ac=detail` |
|
| 189 |
+
| XML | `https://okzyw.cc/api.php/provide/vod/at/xml/` |
|
| 190 |
+
|
| 191 |
+
### 5. ็บข็่ตๆบ็ซ
|
| 192 |
+
|
| 193 |
+
- **ๅฎ็ฝ**๏ผhttps://www.hongniuzy.com/
|
| 194 |
+
- **APIๅบ็ก**๏ผ`https://www.hongniuzy2.com/api.php/provide/vod/`๏ผๆณจๆ๏ผAPIๅๅๅธฆ2๏ผ
|
| 195 |
+
- **ๅค็จAPI**๏ผ`https://www.hongniuzy3.com/api.php/provide/vod/`
|
| 196 |
+
- **ๆญๆพๆฅๆบ**๏ผ`hnm3u8`ใ`hnyun`
|
| 197 |
+
- **ๆป่ตๆบ**๏ผ103,249
|
| 198 |
+
- **M3U8่งฃๆ**๏ผ`https://www.hnjiexi.com/m3u8/?url=`
|
| 199 |
+
- **ๅค็จ่งฃๆ**๏ผ`https://www.hongniujiexi.com/m3u8/?url=`
|
| 200 |
+
- **ๅค็จๅๅ**๏ผhongniuziyuan.com/net/tvใhongniuzy.com/net/tv
|
| 201 |
+
- **ๆจ่ๆฅๅฃ**๏ผ
|
| 202 |
+
|
| 203 |
+
| ๆฅๅฃ | ๅฐๅ |
|
| 204 |
+
|---|---|
|
| 205 |
+
| XML็ปผๅ | `https://www.hongniuzy2.com/api.php/provide/vod/at/xml/` |
|
| 206 |
+
| JSON็ปผๅ | `https://www.hongniuzy2.com/api.php/provide/vod/at/josn/` |
|
| 207 |
+
| M3U8 XML | `https://www.hongniuzy2.com/api.php/provide/vod/from/hnm3u8/at/xml/` |
|
| 208 |
+
| M3U8 JSON | `https://www.hongniuzy2.com/api.php/provide/vod/from/hnm3u8/at/josn/` |
|
| 209 |
+
| ไบๆญ XML | `https://www.hongniuzy2.com/api.php/provide/vod/from/hnyun/at/xml/` |
|
| 210 |
+
| ๆตทๆดCMS | `https://www.hongniuzy2.com/api.php/provide/vod/at/xmlsea/` |
|
| 211 |
+
|
| 212 |
+
### 6. ้้นฐ่ตๆบ็ซ
|
| 213 |
+
|
| 214 |
+
- **ๅฎ็ฝ**๏ผhttps://jinyingzy.com/ ๏ผๅค็จ๏ผjinyingzy.net๏ผ
|
| 215 |
+
- **APIๅบ็ก**๏ผ`https://jyzyapi.com/provide/vod/`๏ผๆณจๆ๏ผไธๅซapi.php๏ผ
|
| 216 |
+
- **ๆญๆพๆฅๆบ**๏ผ`jinyingm3u8`ใ`jinyingyun`
|
| 217 |
+
- **ๆป่ตๆบ**๏ผ103,547
|
| 218 |
+
- **M3U8่งฃๆ**๏ผ`https://hd.iapijy.com/play?url=`
|
| 219 |
+
- **ๅค็จๅๅ**๏ผjinyingziyuan.comใjyzy1/2/3.com
|
| 220 |
+
- **ๆจ่ๆฅๅฃ**๏ผ
|
| 221 |
+
|
| 222 |
+
| ๆฅๅฃ | ๅฐๅ |
|
| 223 |
+
|---|---|
|
| 224 |
+
| ๆ ๅ้้ | `https://jyzyapi.com/provide/vod` |
|
| 225 |
+
| M3U8 XML | `https://jyzyapi.com/provide/vod/from/jinyingm3u8/at/xml/` |
|
| 226 |
+
| M3U8 JSON | `https://jyzyapi.com/provide/vod/from/jinyingm3u8/at/json` |
|
| 227 |
+
| ไบๆญ XML | `https://jyzyapi.com/provide/vod/from/jinyingyun/at/xml/` |
|
| 228 |
+
| ไบๆญ JSON | `https://jyzyapi.com/provide/vod/from/jinyingyun/at/json` |
|
| 229 |
+
| ๆตทๆดCMS | `https://jyzyapi.com/provide/vod/at/xmlsea/` |
|
| 230 |
+
|
| 231 |
+
### 7. ๆฐๆตช่ตๆบ็ซ
|
| 232 |
+
|
| 233 |
+
- **ๅฎ็ฝ**๏ผhttps://www.xinlangzy.com/
|
| 234 |
+
- **APIๅบ็ก**๏ผ`https://www.xinlangzy.com/api.php/provide/vod/`
|
| 235 |
+
- **ๆญๆพๆฅๆบ**๏ผ`xlm3u8`ใ`xlyun`
|
| 236 |
+
- **็น็น**๏ผHTTPS่ตๆบ๏ผm3u8็ด้พ
|
| 237 |
+
- **ๆจ่ๆฅๅฃ**๏ผ
|
| 238 |
+
|
| 239 |
+
| ๆฅๅฃ | ๅฐๅ |
|
| 240 |
+
|---|---|
|
| 241 |
+
| ๆ ๅๅ่กจ | `https://www.xinlangzy.com/api.php/provide/vod/` |
|
| 242 |
+
| ่ฏฆๆ
ๆจกๅผ | `https://www.xinlangzy.com/api.php/provide/vod/?ac=detail` |
|
| 243 |
+
|
| 244 |
+
### 8. ๅฟซ่ฝฆ่ตๆบ็ซ
|
| 245 |
+
|
| 246 |
+
- **ๅฎ็ฝ**๏ผhttp://kuaichezy.com/
|
| 247 |
+
- **APIๅบ็ก**๏ผ`http://kuaichezy.com/api.php/provide/vod/`
|
| 248 |
+
- **ๆญๆพๆฅๆบ**๏ผ`kcm3u8`
|
| 249 |
+
- **ๆป่ตๆบ**๏ผ119,079
|
| 250 |
+
- **ๅพ็CDN**๏ผ`kuaichezyimg.com`
|
| 251 |
+
- **ๆณจๆ**๏ผไป
HTTP
|
| 252 |
+
- **ๆจ่ๆฅๅฃ**๏ผ
|
| 253 |
+
|
| 254 |
+
| ๆฅๅฃ | ๅฐๅ |
|
| 255 |
+
|---|---|
|
| 256 |
+
| ๆ ๅๅ่กจ | `http://kuaichezy.com/api.php/provide/vod/` |
|
| 257 |
+
| ่ฏฆๆ
ๆจกๅผ | `http://kuaichezy.com/api.php/provide/vod/?ac=detail` |
|
| 258 |
+
|
| 259 |
+
### 9. CK่ตๆบ็ซ
|
| 260 |
+
|
| 261 |
+
- **ๅฎ็ฝ**๏ผhttp://www.ckzy1.com/
|
| 262 |
+
- **APIๅบ็ก**๏ผ`http://www.ckzy1.com/api.php/provide/vod/`
|
| 263 |
+
- **ๆญๆพๆฅๆบ**๏ผ`ckm3u8`
|
| 264 |
+
- **ๅพ็CDN**๏ผ`ckzyjpg.top`
|
| 265 |
+
- **ๆณจๆ**๏ผHTTPS่ตๆบ๏ผๆ่ท้ฉฌ็ฏๅนฟๅ๏ผไป
HTTP
|
| 266 |
+
- **ๆจ่ๆฅๅฃ**๏ผ
|
| 267 |
+
|
| 268 |
+
| ๆฅๅฃ | ๅฐๅ |
|
| 269 |
+
|---|---|
|
| 270 |
+
| ๆ ๅๅ่กจ | `http://www.ckzy1.com/api.php/provide/vod/` |
|
| 271 |
+
| ่ฏฆๆ
ๆจกๅผ | `http://www.ckzy1.com/api.php/provide/vod/?ac=detail` |
|
| 272 |
+
|
| 273 |
+
---
|
| 274 |
+
|
| 275 |
+
## ไธๅฏ็จ่ตๆบ็ซ
|
| 276 |
+
|
| 277 |
+
| ็ซ็น | ๅฎ็ฝ | ้ฎ้ข่ฏดๆ |
|
| 278 |
+
|---|---|---|
|
| 279 |
+
| ๅง้พ่ตๆบ | wolongzyw.com | ็ฝ็ซๅฏ่ฎฟ้ฎ๏ผAPI่ฟๅHTML้กต้ข่้ๆฐๆฎ๏ผๆฅๅฃๅทฒๅคฑๆ |
|
| 280 |
+
| ๅ
้่ตๆบ | guangsuzy.com | ็ฝ็ซๅAPIๅๆ ๆณ่ฎฟ้ฎ |
|
| 281 |
+
| U้
ท่ตๆบ | ukuzy0.com | API่ฟๅclosed/็ฉบๅๅบ๏ผ็ไผผๅทฒๅ
ณ้ญ |
|
| 282 |
+
| ๆ ๅฐฝ่ตๆบ | wujinzy.net | ่ฟๅ404 |
|
| 283 |
+
| ๆท็่ตๆบ | taopianzy.com | ่ฟๅ404๏ผAPIๅๅๅทฒๅคฑๆ |
|
| 284 |
+
|
| 285 |
+
---
|
| 286 |
+
|
| 287 |
+
## ๆญๆพ่ฏดๆ
|
| 288 |
+
|
| 289 |
+
### ไธ็งๆญๆพๅฐๅ็ฑปๅ
|
| 290 |
+
|
| 291 |
+
้่ฟAPI `ac=detail` ่ทๅๅฐ็ `vod_play_url` ไธญ๏ผๅญๅจไธ็งไธๅ็ฑปๅ็ๆญๆพๅฐๅ๏ผ
|
| 292 |
+
|
| 293 |
+
#### ็ฑปๅไธ๏ผM3U8็ด้พ
|
| 294 |
+
|
| 295 |
+
ไปฅ `/index.m3u8` ็ปๅฐพ็HLSๅ็ๅฐๅ๏ผๅฏ็ดๆฅ็จHLSๆญๆพๅจๆญๆพใ
|
| 296 |
+
|
| 297 |
+
```
|
| 298 |
+
https://vv.jisuzyv.com/play/bo2R17Aa/index.m3u8
|
| 299 |
+
https://hd.ijycnd.com/play/eERR6RNa/index.m3u8
|
| 300 |
+
https://v3.kuaichezym3u8.com/yyv3/202605/11/tVzZj7hcR927/video/index.m3u8
|
| 301 |
+
https://ckzy3.com/20260428/zQEHfw8I/index.m3u8
|
| 302 |
+
https://vodcnd13.oag7h.com/20260511/jjotR1L6/index.m3u8
|
| 303 |
+
```
|
| 304 |
+
|
| 305 |
+
ๅฎๆตm3u8ๆไปถๅ
ๅฎนไธบHLSไธปๆญๆพๅ่กจ๏ผMaster Playlist๏ผ๏ผๅ
ๅซๅค็ ็ๆต๏ผ
|
| 306 |
+
|
| 307 |
+
```
|
| 308 |
+
#EXTM3U
|
| 309 |
+
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=4096000,RESOLUTION=1920x1080
|
| 310 |
+
/play/hls/eERR6RNa/index.m3u8
|
| 311 |
+
```
|
| 312 |
+
|
| 313 |
+
ๆ็ดๆฅๅ
ๅซๅ็ๅ่กจ๏ผ
|
| 314 |
+
|
| 315 |
+
```
|
| 316 |
+
#EXTM3U
|
| 317 |
+
#EXT-X-STREAM-INF:BANDWIDTH=3902000,RESOLUTION=1920x1080
|
| 318 |
+
/20260511/jjotR1L6/3902kb/hls/index.m3u8
|
| 319 |
+
```
|
| 320 |
+
|
| 321 |
+
**M3U8็ด้พๅฏ็ดๆฅ่ขซ HLS.js / DPlayer ็ญๆญๆพๅจๆถ่ดน๏ผๆ ้่งฃๆๆฅๅฃใ**
|
| 322 |
+
|
| 323 |
+
#### ็ฑปๅไบ๏ผไบๆญ็ญ้พ
|
| 324 |
+
|
| 325 |
+
ไธๅธฆ `/index.m3u8` ๅ็ผ็็ญ้พๅฐๅ๏ผ่ฎฟ้ฎๅ่ฟๅไธไธชๅฎๆด็HTMLๆญๆพ้กต้ข๏ผๅซDPlayer + HLS.js๏ผใ
|
| 326 |
+
|
| 327 |
+
```
|
| 328 |
+
https://hd.ijycnd.com/play/eERR6RNa
|
| 329 |
+
https://hn.bfvvs.com/play/b2kxBVWd
|
| 330 |
+
https://vv.jisuzyv.com/play/bo2R17Aa
|
| 331 |
+
https://vodcnd13.oag7h.com/share/AdBKIiZCCd
|
| 332 |
+
```
|
| 333 |
+
|
| 334 |
+
่ฎฟ้ฎไบๆญ็ญ้พ่ฟๅ็HTMLไธญ๏ผๅ
ๅตไบๆญๆพๅจไปฃ็ ๏ผ
|
| 335 |
+
|
| 336 |
+
```html
|
| 337 |
+
<head>
|
| 338 |
+
<meta charset="utf-8">
|
| 339 |
+
<title>้้นฐ่ตๆบ่งฃๆๆญๆพ</title>
|
| 340 |
+
<script src="https://s2.pstatp.com/cdn/expire-1-M/hls.js/1.1.5/hls.js"></script>
|
| 341 |
+
<script src="https://s2.pstatp.com/cdn/expire-1-M/dplayer/1.25.1/DPlayer.min.js"></script>
|
| 342 |
+
</head>
|
| 343 |
+
<body>
|
| 344 |
+
<div id="dplayer"></div>
|
| 345 |
+
<script>
|
| 346 |
+
new DPlayer({
|
| 347 |
+
container: document.getElementById('dplayer'),
|
| 348 |
+
autoplay: true,
|
| 349 |
+
video: { url: 'https://hd.ijycnd.com/play/eERR6RNa/index.m3u8', type: 'hls' }
|
| 350 |
+
});
|
| 351 |
+
</script>
|
| 352 |
+
</body>
|
| 353 |
+
```
|
| 354 |
+
|
| 355 |
+
**ไบๆญ็ญ้พๅฏ็ดๆฅ็จ `<iframe>` ๅตๅ
ฅๅฐไฝ ็็ฝ้กตไธญๆญๆพใ**
|
| 356 |
+
|
| 357 |
+
#### ็ฑปๅไธ๏ผ่งฃๆๆฅๅฃ
|
| 358 |
+
|
| 359 |
+
่งฃๆๆฅๅฃๆฏไธไธช้็จๆญๆพ้กต้ข๏ผๆฅๆถ `url` ๅๆฐ๏ผ่ชๅจๅ ่ฝฝHLSๆญๆพๅจใ
|
| 360 |
+
|
| 361 |
+
```
|
| 362 |
+
https://hd.iapijy.com/play?url={m3u8ๅฐๅ}
|
| 363 |
+
https://www.hnjiexi.com/m3u8/?url={m3u8ๅฐๅ}
|
| 364 |
+
https://www.hongniujiexi.com/m3u8/?url={m3u8ๅฐๅ}
|
| 365 |
+
https://dxfbk.com/?url={m3u8ๅฐๅ}
|
| 366 |
+
```
|
| 367 |
+
|
| 368 |
+
่ฎฟ้ฎ่งฃๆๆฅๅฃ่ฟๅ็HTMLๅๆ ทๅ
ๅตDPlayer + HLS.js๏ผ
|
| 369 |
+
|
| 370 |
+
```html
|
| 371 |
+
<!-- ้้นฐ่งฃๆ -->
|
| 372 |
+
<script src="hls.js"></script>
|
| 373 |
+
<script src="DPlayer.min.js"></script>
|
| 374 |
+
<script>
|
| 375 |
+
new DPlayer({ video: { url: getUrlParam('url'), type: 'hls' } });
|
| 376 |
+
</script>
|
| 377 |
+
```
|
| 378 |
+
|
| 379 |
+
```html
|
| 380 |
+
<!-- ็ดขๅฐผ่งฃๆ๏ผๅธฆP2Pๅ ้๏ผ -->
|
| 381 |
+
<script src="/js/hls.js"></script>
|
| 382 |
+
<script src="/js/DPlayer.js"></script>
|
| 383 |
+
<script type="module">
|
| 384 |
+
import { HlsJsP2PEngine } from "p2p-media-loader-hlsjs";
|
| 385 |
+
const HlsWithP2P = HlsJsP2PEngine.injectMixin(window.Hls);
|
| 386 |
+
const hls = new HlsWithP2P({ p2p: { ... }, hlsjsConfig: { ... } });
|
| 387 |
+
hls.loadSource(videoUrl);
|
| 388 |
+
</script>
|
| 389 |
+
```
|
| 390 |
+
|
| 391 |
+
**่งฃๆๆฅๅฃๅๆ ทๅฏ็จ `<iframe>` ๅตๅ
ฅ๏ผ้ๅไธๆณ่ชๅทฑๆญๅปบๆญๆพๅจ็ๅบๆฏใ**
|
| 392 |
+
|
| 393 |
+
---
|
| 394 |
+
|
| 395 |
+
### ๆญๆพๆนๆก้ๆฉ
|
| 396 |
+
|
| 397 |
+
ๆ นๆฎไฝ ็ๆๆฏๅบๆฏ๏ผ้ๆฉๅ้็ๆญๆพๆนๅผ๏ผ
|
| 398 |
+
|
| 399 |
+
#### ๆนๆกA๏ผiframeๅตๅ
ฅ๏ผๆ็ฎๅ๏ผ
|
| 400 |
+
|
| 401 |
+
้ๅ๏ผๅฟซ้้ๆใไธๆณ่ชๅทฑๅค็ๆญๆพ้ป่พ
|
| 402 |
+
|
| 403 |
+
**ไบๆญ็ญ้พ็ดๆฅๅตๅ
ฅ๏ผ**
|
| 404 |
+
```html
|
| 405 |
+
<iframe
|
| 406 |
+
src="https://hd.ijycnd.com/play/eERR6RNa"
|
| 407 |
+
width="100%" height="500"
|
| 408 |
+
allowfullscreen frameborder="0"
|
| 409 |
+
></iframe>
|
| 410 |
+
```
|
| 411 |
+
|
| 412 |
+
**M3U8็ด้พ้่ฟ่งฃๆๆฅๅฃๅตๅ
ฅ๏ผ**
|
| 413 |
+
```html
|
| 414 |
+
<iframe
|
| 415 |
+
src="https://hd.iapijy.com/play?url=https://hd.ijycnd.com/play/eERR6RNa/index.m3u8"
|
| 416 |
+
width="100%" height="500"
|
| 417 |
+
allowfullscreen frameborder="0"
|
| 418 |
+
></iframe>
|
| 419 |
+
```
|
| 420 |
+
|
| 421 |
+
#### ๆนๆกB๏ผDPlayer + HLS.js๏ผๆจ่๏ผ
|
| 422 |
+
|
| 423 |
+
้ๅ๏ผ้่ฆ่ชๅฎไนๆญๆพๅจUIใๆงๅถๆญๆพ้ป่พ
|
| 424 |
+
|
| 425 |
+
```html
|
| 426 |
+
<link href="https://s2.pstatp.com/cdn/expire-1-M/dplayer/1.25.1/DPlayer.min.css" rel="stylesheet">
|
| 427 |
+
<script src="https://s2.pstatp.com/cdn/expire-1-M/hls.js/1.1.5/hls.js"></script>
|
| 428 |
+
<script src="https://s2.pstatp.com/cdn/expire-1-M/dplayer/1.25.1/DPlayer.min.js"></script>
|
| 429 |
+
|
| 430 |
+
<div id="dplayer"></div>
|
| 431 |
+
<script>
|
| 432 |
+
const dp = new DPlayer({
|
| 433 |
+
container: document.getElementById('dplayer'),
|
| 434 |
+
autoplay: true,
|
| 435 |
+
screenshot: true,
|
| 436 |
+
video: {
|
| 437 |
+
url: 'https://hd.ijycnd.com/play/eERR6RNa/index.m3u8',
|
| 438 |
+
type: 'hls',
|
| 439 |
+
},
|
| 440 |
+
pluginOptions: {
|
| 441 |
+
hls: {
|
| 442 |
+
maxBufferLength: 120,
|
| 443 |
+
maxMaxBufferLength: 120,
|
| 444 |
+
},
|
| 445 |
+
},
|
| 446 |
+
});
|
| 447 |
+
</script>
|
| 448 |
+
```
|
| 449 |
+
|
| 450 |
+
#### ๆนๆกC๏ผVideo.js + HLS
|
| 451 |
+
|
| 452 |
+
้ๅ๏ผ้่ฆๆดไธไธ็บง็ๆญๆพๅจ
|
| 453 |
+
|
| 454 |
+
```html
|
| 455 |
+
<link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
|
| 456 |
+
<script src="https://unpkg.com/video.js/dist/video.js"></script>
|
| 457 |
+
<script src="https://unpkg.com/@videojs/http-streaming/dist/videojs-http-streaming.min.js"></script>
|
| 458 |
+
|
| 459 |
+
<video id="my-video" class="video-js" controls preload="auto" width="100%">
|
| 460 |
+
<source src="https://hd.ijycnd.com/play/eERR6RNa/index.m3u8" type="application/x-mpegURL">
|
| 461 |
+
</video>
|
| 462 |
+
<script>
|
| 463 |
+
videojs('my-video', { fluid: true });
|
| 464 |
+
</script>
|
| 465 |
+
```
|
| 466 |
+
|
| 467 |
+
#### ๆนๆกD๏ผCKPlayer๏ผๅฝไบงๆญๆพๅจ๏ผ
|
| 468 |
+
|
| 469 |
+
้ๅ๏ผไธญๆๆๆกฃๅๅฅฝใๅฝไบงCMSๆ ้
|
| 470 |
+
|
| 471 |
+
```html
|
| 472 |
+
<script src="https://cdn.ckplayer.com/ckplayer/ckplayer.js"></script>
|
| 473 |
+
<div id="video"></div>
|
| 474 |
+
<script>
|
| 475 |
+
var videoObject = {
|
| 476 |
+
container: '#video',
|
| 477 |
+
video: 'https://hd.ijycnd.com/play/eERR6RNa/index.m3u8'
|
| 478 |
+
};
|
| 479 |
+
new ckplayer(videoObject);
|
| 480 |
+
</script>
|
| 481 |
+
```
|
| 482 |
+
|
| 483 |
+
---
|
| 484 |
+
|
| 485 |
+
### ๅ็ซๆญๆพๅฐๅCDNๅๅๅฏน็
ง
|
| 486 |
+
|
| 487 |
+
| ็ซ็น | M3U8ๆญๆพๅๅ | ไบๆญๅๅ | ่งฃๆๆฅๅฃ |
|
| 488 |
+
|---|---|---|---|
|
| 489 |
+
| ๆ้่ตๆบ | `vv.jisuzyv.com` | `vv.jisuzyv.com`๏ผๅM3U8ๅปๆ/index.m3u8๏ผ | - |
|
| 490 |
+
| ่ฑ็ฃ่ตๆบ | `vodcnd*.oag7h.com` | `vodcnd*.oag7h.com/share/*` | - |
|
| 491 |
+
| ็ดขๅฐผ่ตๆบ | `v*.yuglf.com` | - | `https://dxfbk.com/?url=` |
|
| 492 |
+
| OK่ตๆบ | `v*.yaaabc.com` | - | - |
|
| 493 |
+
| ็บข็่ตๆบ | `hn.bfvvs.com`๏ผ/index.m3u8ๅ็ผ๏ผ | `hn.bfvvs.com`๏ผๆ ๅ็ผ๏ผ | `https://www.hnjiexi.com/m3u8/?url=` |
|
| 494 |
+
| ้้นฐ่ตๆบ | `hd.ijycnd.com`๏ผ/index.m3u8ๅ็ผ๏ผ | `hd.ijycnd.com`๏ผๆ ๅ็ผ๏ผ | `https://hd.iapijy.com/play?url=` |
|
| 495 |
+
| ๆฐๆตช่ตๆบ | - | - | - |
|
| 496 |
+
| ๅฟซ่ฝฆ่ตๆบ | `v*.kuaichezym3u8.com` | - | - |
|
| 497 |
+
| CK่ตๆบ | `ckzy3.com` | - | - |
|
| 498 |
+
|
| 499 |
+
---
|
| 500 |
+
|
| 501 |
+
### ๆญๆพๅจๆฅๆบๆ ่ฏๅฏน็
ง
|
| 502 |
+
|
| 503 |
+
| ็ซ็น | M3U8ๆฅๆบ | ไบๆญๆฅๆบ |
|
| 504 |
+
|---|---|---|
|
| 505 |
+
| ๆ้่ตๆบ | `jsm3u8` | `jsyun` |
|
| 506 |
+
| ่ฑ็ฃ่ตๆบ | `dbm3u8` | `dbyun` |
|
| 507 |
+
| ็ดขๅฐผ่ตๆบ | `snm3u8` | - |
|
| 508 |
+
| OK่ตๆบ | `okm3u8` | - |
|
| 509 |
+
| ็บข็่ตๆบ | `hnm3u8` | `hnyun` |
|
| 510 |
+
| ้้นฐ่ตๆบ | `jinyingm3u8` | `jinyingyun` |
|
| 511 |
+
| ๆฐๆตช่ตๆบ | `xlm3u8` | `xlyun` |
|
| 512 |
+
| ๅฟซ่ฝฆ่ตๆบ | `kcm3u8` | - |
|
| 513 |
+
| CK่ตๆบ | `ckm3u8` | - |
|
| 514 |
+
|
| 515 |
+
---
|
| 516 |
+
|
| 517 |
+
### ๆญๆพๆณจๆไบ้กน
|
| 518 |
+
|
| 519 |
+
1. **่ทจๅ้ฎ้ข**๏ผM3U8็ด้พๅHLSๅ็ๆไปถ้ๅธธๅ
่ฎธ่ทจๅ่ฎฟ้ฎ๏ผDPlayer/Video.jsๅฏ็ดๆฅๅ ่ฝฝ๏ผไบๆญ็ญ้พiframeๅตๅ
ฅๆถ้ๆณจๆ `X-Frame-Options` ้ๅถ
|
| 520 |
+
2. **็ ็่ช้ๅบ**๏ผๅคๆฐM3U8ไธปๆญๆพๅ่กจๅ
ๅซๅค็ ็๏ผๅฆ1080P/720P/480P๏ผ๏ผHLS.jsไผๆ นๆฎ็ฝ้่ชๅจๅๆข
|
| 521 |
+
3. **P2Pๅ ้**๏ผ็ดขๅฐผ่งฃๆๆฅๅฃๅ
็ฝฎP2Pๅ ้๏ผp2p-media-loader๏ผ๏ผๅฏ้ไฝCDNๅธฆๅฎฝๆๆฌ
|
| 522 |
+
4. **้ฒ็้พ**๏ผ้จๅ็ซ็น็m3u8ๅฐๅๅฏ่ฝๆๆถๆๆง๏ผๅปบ่ฎฎ่ทๅๅๅฐฝๅฟซๆญๆพ๏ผไธๅฎ้ฟๆ็ผๅญๆญๆพๅฐๅ
|
| 523 |
+
5. **Refererๆฃๆฅ**๏ผ้จๅCDNๅฏ่ฝๆฃๆฅReferer๏ผ้ๅจๆญๆพๅจ้กต้ข่ฎพ็ฝฎ `<meta name="referrer" content="never">`
|
| 524 |
+
|
| 525 |
+
---
|
| 526 |
+
|
| 527 |
+
## ้้ๆณจๆไบ้กน
|
| 528 |
+
|
| 529 |
+
1. **้ข็ๆงๅถ**๏ผ่ฏทๆฑ้ด้ๅปบ่ฎฎ โฅ1็ง๏ผ้ฟๅ
่ขซๅฐIP
|
| 530 |
+
2. **ๅพ็ๅค็**๏ผๆจ่ไธ่ฝฝๅฐๆฌๅฐ๏ผ้ฟๅ
CDNๅคฑๆๅๅพ็ไธขๅคฑ
|
| 531 |
+
3. **HTTPS้ฎ้ข**๏ผๅฆ้้ๅคฑ่ดฅ๏ผๅฐ่ฏๅปๆ `https` ็ `s` ๆน็จ `http`
|
| 532 |
+
4. **ๅ็ฑป็ปๅฎ**๏ผ้ฆๆฌก้้้ๅจCMSๅๅฐ็ปๅฎๅฏนๅบๅ็ฑป
|
| 533 |
+
5. **ๆญๆพๅจ้
็ฝฎ**๏ผ้้ๅๅฟ
้กปๅจCMSๅๅฐๆทปๅ ๅฏนๅบๆญๆพๅจๆ ๅฟ๏ผๅฆๅๆ ๆณๆญๆพ
|
| 534 |
+
6. **ๆฐๆฎๅๆญฅ**๏ผๅปบ่ฎฎๅฎๆถๅข้้้๏ผไฝฟ็จ `h` ๅๆฐ่ทๅๆ่ฟNๅฐๆถๆดๆฐๆฐๆฎ๏ผ
|
|
@@ -6,8 +6,14 @@ aiomysql==0.2.*
|
|
| 6 |
alembic==1.14.*
|
| 7 |
pydantic==2.10.*
|
| 8 |
pydantic-settings==2.7.*
|
| 9 |
-
|
| 10 |
bcrypt==4.2.*
|
| 11 |
httpx==0.28.*
|
| 12 |
apscheduler==3.11.*
|
| 13 |
python-multipart==0.0.*
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
alembic==1.14.*
|
| 7 |
pydantic==2.10.*
|
| 8 |
pydantic-settings==2.7.*
|
| 9 |
+
PyJWT==2.9.*
|
| 10 |
bcrypt==4.2.*
|
| 11 |
httpx==0.28.*
|
| 12 |
apscheduler==3.11.*
|
| 13 |
python-multipart==0.0.*
|
| 14 |
+
slowapi==0.1.9
|
| 15 |
+
redis==5.2.*
|
| 16 |
+
|
| 17 |
+
# ๆต่ฏไพ่ต
|
| 18 |
+
pytest==8.3.*
|
| 19 |
+
pytest-asyncio==0.24.*
|
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
import pytest_asyncio
|
| 3 |
+
from httpx import AsyncClient, ASGITransport
|
| 4 |
+
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
|
| 5 |
+
|
| 6 |
+
from app.database import Base, get_db
|
| 7 |
+
from app.utils.auth import hash_password
|
| 8 |
+
|
| 9 |
+
TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"
|
| 10 |
+
|
| 11 |
+
test_engine = create_async_engine(
|
| 12 |
+
TEST_DATABASE_URL,
|
| 13 |
+
connect_args={"check_same_thread": False},
|
| 14 |
+
)
|
| 15 |
+
TestSessionLocal = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
|
| 16 |
+
|
| 17 |
+
# ๅฝๅๆต่ฏ็จ็ session๏ผๆฏไธช test ็ฌ็ซ๏ผ
|
| 18 |
+
_current_session: AsyncSession | None = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
async def override_get_db():
|
| 22 |
+
"""
|
| 23 |
+
ไผๅ
ๅค็จๆต่ฏ session๏ผไฟ่ฏ db_session ๅๅ
ฅ็ๆฐๆฎๅฏน HTTP ่ฏทๆฑๅฏ่ง๏ผ๏ผ
|
| 24 |
+
ๆฒกๆๅ
ฑไบซ session ๆถ่ชๅทฑๅๅปบไธไธช๏ผ็จไบไธ้่ฆ้ข็ฝฎๆฐๆฎ็ๆต่ฏ๏ผ
|
| 25 |
+
"""
|
| 26 |
+
if _current_session is not None:
|
| 27 |
+
yield _current_session
|
| 28 |
+
else:
|
| 29 |
+
async with TestSessionLocal() as session:
|
| 30 |
+
try:
|
| 31 |
+
yield session
|
| 32 |
+
await session.commit()
|
| 33 |
+
except Exception:
|
| 34 |
+
await session.rollback()
|
| 35 |
+
raise
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@pytest_asyncio.fixture(autouse=True)
|
| 39 |
+
async def setup_db():
|
| 40 |
+
async with test_engine.begin() as conn:
|
| 41 |
+
await conn.run_sync(Base.metadata.create_all)
|
| 42 |
+
yield
|
| 43 |
+
async with test_engine.begin() as conn:
|
| 44 |
+
await conn.run_sync(Base.metadata.drop_all)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@pytest_asyncio.fixture
|
| 48 |
+
async def db_session(setup_db):
|
| 49 |
+
global _current_session
|
| 50 |
+
async with TestSessionLocal() as session:
|
| 51 |
+
_current_session = session
|
| 52 |
+
try:
|
| 53 |
+
yield session
|
| 54 |
+
finally:
|
| 55 |
+
_current_session = None
|
| 56 |
+
await session.rollback()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@pytest_asyncio.fixture
|
| 60 |
+
async def client(setup_db):
|
| 61 |
+
from app.main import app
|
| 62 |
+
from app.limiter import limiter
|
| 63 |
+
app.dependency_overrides[get_db] = override_get_db
|
| 64 |
+
limiter.enabled = False
|
| 65 |
+
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
|
| 66 |
+
yield ac
|
| 67 |
+
app.dependency_overrides.clear()
|
| 68 |
+
limiter.enabled = True
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@pytest_asyncio.fixture
|
| 72 |
+
async def superadmin_token(client, db_session):
|
| 73 |
+
"""ๅๅปบ่ถ
็บง็ฎก็ๅๅนถ่ฟๅ token"""
|
| 74 |
+
from app.models.admin import Admin
|
| 75 |
+
from app.models.role import Role, AdminRole
|
| 76 |
+
|
| 77 |
+
admin = Admin(
|
| 78 |
+
username="test_superadmin",
|
| 79 |
+
password_hash=hash_password("Test@123456"),
|
| 80 |
+
nickname="Test SuperAdmin",
|
| 81 |
+
is_active=True,
|
| 82 |
+
)
|
| 83 |
+
db_session.add(admin)
|
| 84 |
+
await db_session.flush()
|
| 85 |
+
|
| 86 |
+
role = Role(name="่ถ
็บง็ฎก็ๅ", code="super_admin", is_builtin=True, status=1)
|
| 87 |
+
db_session.add(role)
|
| 88 |
+
await db_session.flush()
|
| 89 |
+
|
| 90 |
+
db_session.add(AdminRole(admin_id=admin.id, role_id=role.id))
|
| 91 |
+
await db_session.commit()
|
| 92 |
+
|
| 93 |
+
resp = await client.post("/admin/auth/login", json={
|
| 94 |
+
"username": "test_superadmin",
|
| 95 |
+
"password": "Test@123456",
|
| 96 |
+
})
|
| 97 |
+
return resp.json()["data"]["accessToken"]
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@pytest_asyncio.fixture
|
| 101 |
+
async def user_token(client, db_session):
|
| 102 |
+
"""้่ฟ HTTP ๆณจๅๆฎ้็จๆทๅนถ่ฟๅ token๏ผๆฐๆฎๅๅ
ฅๅ
ฑไบซ session๏ผๅฏนๅ็ปญ่ฏทๆฑๅฏ่ง๏ผ"""
|
| 103 |
+
resp = await client.post("/user/auth/register", json={
|
| 104 |
+
"username": "testuser",
|
| 105 |
+
"password": "Test@123456",
|
| 106 |
+
})
|
| 107 |
+
assert resp.json()["code"] == 0, f"register failed: {resp.json()}"
|
| 108 |
+
return resp.json()["data"]["accessToken"]
|
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
@pytest.mark.asyncio
|
| 5 |
+
async def test_health(client):
|
| 6 |
+
resp = await client.get("/health")
|
| 7 |
+
assert resp.status_code == 200
|
| 8 |
+
data = resp.json()
|
| 9 |
+
assert data["status"] in ("ok", "degraded")
|
| 10 |
+
assert "db" in data
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@pytest.mark.asyncio
|
| 14 |
+
async def test_admin_login_success(client, db_session):
|
| 15 |
+
from app.models.admin import Admin
|
| 16 |
+
from app.utils.auth import hash_password
|
| 17 |
+
|
| 18 |
+
admin = Admin(
|
| 19 |
+
username="login_test_admin",
|
| 20 |
+
password_hash=hash_password("Admin@123"),
|
| 21 |
+
is_active=True,
|
| 22 |
+
)
|
| 23 |
+
db_session.add(admin)
|
| 24 |
+
await db_session.commit()
|
| 25 |
+
|
| 26 |
+
resp = await client.post("/admin/auth/login", json={
|
| 27 |
+
"username": "login_test_admin",
|
| 28 |
+
"password": "Admin@123",
|
| 29 |
+
})
|
| 30 |
+
assert resp.status_code == 200
|
| 31 |
+
body = resp.json()
|
| 32 |
+
assert body["code"] == 0
|
| 33 |
+
assert "accessToken" in body["data"]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@pytest.mark.asyncio
|
| 37 |
+
async def test_admin_login_wrong_password(client, db_session):
|
| 38 |
+
from app.models.admin import Admin
|
| 39 |
+
from app.utils.auth import hash_password
|
| 40 |
+
|
| 41 |
+
admin = Admin(
|
| 42 |
+
username="wrong_pwd_admin",
|
| 43 |
+
password_hash=hash_password("correct_password"),
|
| 44 |
+
is_active=True,
|
| 45 |
+
)
|
| 46 |
+
db_session.add(admin)
|
| 47 |
+
await db_session.commit()
|
| 48 |
+
|
| 49 |
+
resp = await client.post("/admin/auth/login", json={
|
| 50 |
+
"username": "wrong_pwd_admin",
|
| 51 |
+
"password": "wrong_password",
|
| 52 |
+
})
|
| 53 |
+
assert resp.status_code == 200
|
| 54 |
+
assert resp.json()["code"] == 40001
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@pytest.mark.asyncio
|
| 58 |
+
async def test_admin_get_user_info(client, superadmin_token):
|
| 59 |
+
resp = await client.get(
|
| 60 |
+
"/admin/auth/user-info",
|
| 61 |
+
headers={"Authorization": f"Bearer {superadmin_token}"},
|
| 62 |
+
)
|
| 63 |
+
assert resp.status_code == 200
|
| 64 |
+
body = resp.json()
|
| 65 |
+
assert body["code"] == 0
|
| 66 |
+
assert body["data"]["username"] == "test_superadmin"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@pytest.mark.asyncio
|
| 70 |
+
async def test_admin_unauthorized(client):
|
| 71 |
+
resp = await client.get("/admin/auth/user-info")
|
| 72 |
+
assert resp.status_code == 403
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@pytest.mark.asyncio
|
| 76 |
+
async def test_admin_get_menus(client, superadmin_token):
|
| 77 |
+
resp = await client.get(
|
| 78 |
+
"/admin/auth/menus",
|
| 79 |
+
headers={"Authorization": f"Bearer {superadmin_token}"},
|
| 80 |
+
)
|
| 81 |
+
assert resp.status_code == 200
|
| 82 |
+
assert resp.json()["code"] == 0
|
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ๆต่ฏ Admin ็ฎก็ๅ่ฝๅ RBAC ๆ้ๆฆๆช
|
| 3 |
+
"""
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# โโ ่พ
ๅฉ fixture โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 8 |
+
|
| 9 |
+
@pytest.fixture
|
| 10 |
+
def auth_header(superadmin_token):
|
| 11 |
+
return {"Authorization": f"Bearer {superadmin_token}"}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# โโ ๅฝฑ็็ฎก็ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 15 |
+
|
| 16 |
+
@pytest.mark.asyncio
|
| 17 |
+
async def test_admin_list_vods(client, superadmin_token, db_session):
|
| 18 |
+
from app.models.vod import Vod
|
| 19 |
+
from app.models.category import Category
|
| 20 |
+
|
| 21 |
+
cat = Category(name="็ตๅฝฑ", sort_order=1, is_active=True)
|
| 22 |
+
db_session.add(cat)
|
| 23 |
+
await db_session.flush()
|
| 24 |
+
db_session.add(Vod(name="็ฎก็ๅฝฑ็1", category_id=cat.id))
|
| 25 |
+
await db_session.commit()
|
| 26 |
+
|
| 27 |
+
resp = await client.get(
|
| 28 |
+
"/admin/vod",
|
| 29 |
+
headers={"Authorization": f"Bearer {superadmin_token}"},
|
| 30 |
+
)
|
| 31 |
+
assert resp.status_code == 200
|
| 32 |
+
assert resp.json()["code"] == 0
|
| 33 |
+
assert resp.json()["data"]["total"] >= 1
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@pytest.mark.asyncio
|
| 37 |
+
async def test_admin_toggle_hide(client, superadmin_token, db_session):
|
| 38 |
+
from app.models.vod import Vod
|
| 39 |
+
from app.models.category import Category
|
| 40 |
+
|
| 41 |
+
cat = Category(name="ๅง้", sort_order=2, is_active=True)
|
| 42 |
+
db_session.add(cat)
|
| 43 |
+
await db_session.flush()
|
| 44 |
+
vod = Vod(name="้่ๆต่ฏๅฝฑ็", category_id=cat.id, is_hidden=False)
|
| 45 |
+
db_session.add(vod)
|
| 46 |
+
await db_session.commit()
|
| 47 |
+
|
| 48 |
+
headers = {"Authorization": f"Bearer {superadmin_token}"}
|
| 49 |
+
resp = await client.put(f"/admin/vod/{vod.id}/hide", headers=headers)
|
| 50 |
+
assert resp.status_code == 200
|
| 51 |
+
assert resp.json()["data"]["is_hidden"] is True
|
| 52 |
+
|
| 53 |
+
resp2 = await client.put(f"/admin/vod/{vod.id}/hide", headers=headers)
|
| 54 |
+
assert resp2.json()["data"]["is_hidden"] is False
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@pytest.mark.asyncio
|
| 58 |
+
async def test_admin_toggle_recommend(client, superadmin_token, db_session):
|
| 59 |
+
from app.models.vod import Vod
|
| 60 |
+
from app.models.category import Category
|
| 61 |
+
|
| 62 |
+
cat = Category(name="็ปผ่บ", sort_order=3, is_active=True)
|
| 63 |
+
db_session.add(cat)
|
| 64 |
+
await db_session.flush()
|
| 65 |
+
vod = Vod(name="ๆจ่ๆต่ฏๅฝฑ็", category_id=cat.id, is_recommended=False)
|
| 66 |
+
db_session.add(vod)
|
| 67 |
+
await db_session.commit()
|
| 68 |
+
|
| 69 |
+
headers = {"Authorization": f"Bearer {superadmin_token}"}
|
| 70 |
+
resp = await client.put(f"/admin/vod/{vod.id}/recommend", headers=headers)
|
| 71 |
+
assert resp.json()["data"]["is_recommended"] is True
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@pytest.mark.asyncio
|
| 75 |
+
async def test_admin_update_vod(client, superadmin_token, db_session):
|
| 76 |
+
from app.models.vod import Vod
|
| 77 |
+
from app.models.category import Category
|
| 78 |
+
|
| 79 |
+
cat = Category(name="ๅจๆผซ", sort_order=4, is_active=True)
|
| 80 |
+
db_session.add(cat)
|
| 81 |
+
await db_session.flush()
|
| 82 |
+
vod = Vod(name="ๆดๆฐๆต่ฏๅฝฑ็", category_id=cat.id)
|
| 83 |
+
db_session.add(vod)
|
| 84 |
+
await db_session.commit()
|
| 85 |
+
|
| 86 |
+
resp = await client.put(
|
| 87 |
+
f"/admin/vod/{vod.id}",
|
| 88 |
+
json={"score": 9.5, "area": "ไธญๅฝๅคง้"},
|
| 89 |
+
headers={"Authorization": f"Bearer {superadmin_token}"},
|
| 90 |
+
)
|
| 91 |
+
assert resp.status_code == 200
|
| 92 |
+
assert resp.json()["code"] == 0
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@pytest.mark.asyncio
|
| 96 |
+
async def test_admin_delete_vod(client, superadmin_token, db_session):
|
| 97 |
+
from app.models.vod import Vod
|
| 98 |
+
from app.models.category import Category
|
| 99 |
+
|
| 100 |
+
cat = Category(name="็บชๅฝ็", sort_order=5, is_active=True)
|
| 101 |
+
db_session.add(cat)
|
| 102 |
+
await db_session.flush()
|
| 103 |
+
vod = Vod(name="ๅ ้คๆต่ฏๅฝฑ็", category_id=cat.id)
|
| 104 |
+
db_session.add(vod)
|
| 105 |
+
await db_session.commit()
|
| 106 |
+
|
| 107 |
+
resp = await client.delete(
|
| 108 |
+
f"/admin/vod/{vod.id}",
|
| 109 |
+
headers={"Authorization": f"Bearer {superadmin_token}"},
|
| 110 |
+
)
|
| 111 |
+
assert resp.status_code == 200
|
| 112 |
+
assert resp.json()["code"] == 0
|
| 113 |
+
|
| 114 |
+
# ็กฎ่ฎคๅทฒๅ ้ค
|
| 115 |
+
resp2 = await client.get(f"/user/vod/{vod.id}")
|
| 116 |
+
assert resp2.json()["code"] == 40401
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# โโ ๆบ็ซ็ฎก็ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 120 |
+
|
| 121 |
+
@pytest.mark.asyncio
|
| 122 |
+
async def test_admin_create_source(client, superadmin_token):
|
| 123 |
+
resp = await client.post(
|
| 124 |
+
"/admin/source",
|
| 125 |
+
json={
|
| 126 |
+
"name": "ๆต่ฏ่ตๆบ็ซ",
|
| 127 |
+
"code": "test_site_001",
|
| 128 |
+
"base_url": "http://api.testsite.com",
|
| 129 |
+
"sync_interval": 60,
|
| 130 |
+
},
|
| 131 |
+
headers={"Authorization": f"Bearer {superadmin_token}"},
|
| 132 |
+
)
|
| 133 |
+
assert resp.status_code == 200
|
| 134 |
+
body = resp.json()
|
| 135 |
+
assert body["code"] == 0
|
| 136 |
+
assert "id" in body["data"]
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@pytest.mark.asyncio
|
| 140 |
+
async def test_admin_create_source_duplicate_code(client, superadmin_token):
|
| 141 |
+
headers = {"Authorization": f"Bearer {superadmin_token}"}
|
| 142 |
+
await client.post("/admin/source", json={
|
| 143 |
+
"name": "็ซ็นA", "code": "dup_code", "base_url": "http://a.com", "sync_interval": 60,
|
| 144 |
+
}, headers=headers)
|
| 145 |
+
resp = await client.post("/admin/source", json={
|
| 146 |
+
"name": "็ซ็นB", "code": "dup_code", "base_url": "http://b.com", "sync_interval": 60,
|
| 147 |
+
}, headers=headers)
|
| 148 |
+
assert resp.json()["code"] == 40002
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@pytest.mark.asyncio
|
| 152 |
+
async def test_admin_list_sources(client, superadmin_token):
|
| 153 |
+
resp = await client.get(
|
| 154 |
+
"/admin/source",
|
| 155 |
+
headers={"Authorization": f"Bearer {superadmin_token}"},
|
| 156 |
+
)
|
| 157 |
+
assert resp.status_code == 200
|
| 158 |
+
assert resp.json()["code"] == 0
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
# โโ RBAC ๆ้ๆฆๆช โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 162 |
+
|
| 163 |
+
@pytest.mark.asyncio
|
| 164 |
+
async def test_rbac_no_token(client):
|
| 165 |
+
"""ๆ token ่ฎฟ้ฎ admin ๆฅๅฃๅบ่ฟๅ 403"""
|
| 166 |
+
resp = await client.get("/admin/vod")
|
| 167 |
+
assert resp.status_code == 403
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
@pytest.mark.asyncio
|
| 171 |
+
async def test_rbac_user_token_rejected_on_admin(client, user_token):
|
| 172 |
+
"""็จๆท token ไธ่ฝ่ฎฟ้ฎ admin ๆฅๅฃ"""
|
| 173 |
+
resp = await client.get(
|
| 174 |
+
"/admin/vod",
|
| 175 |
+
headers={"Authorization": f"Bearer {user_token}"},
|
| 176 |
+
)
|
| 177 |
+
assert resp.status_code == 401
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
@pytest.mark.asyncio
|
| 181 |
+
async def test_rbac_viewer_cannot_delete(client, db_session):
|
| 182 |
+
"""viewer ่ง่ฒไธ่ฝๅ ้คๅฝฑ็"""
|
| 183 |
+
from app.models.admin import Admin
|
| 184 |
+
from app.models.role import Role, AdminRole
|
| 185 |
+
from app.models.vod import Vod
|
| 186 |
+
from app.models.category import Category
|
| 187 |
+
from app.utils.auth import hash_password
|
| 188 |
+
|
| 189 |
+
# ๅๅปบ viewer ่ง่ฒ็ฎก็ๅ
|
| 190 |
+
admin = Admin(username="viewer_admin", password_hash=hash_password("Viewer@123"), is_active=True)
|
| 191 |
+
db_session.add(admin)
|
| 192 |
+
await db_session.flush()
|
| 193 |
+
role = Role(name="ๆฅ็่
", code="viewer", is_builtin=True, status=1)
|
| 194 |
+
db_session.add(role)
|
| 195 |
+
await db_session.flush()
|
| 196 |
+
db_session.add(AdminRole(admin_id=admin.id, role_id=role.id))
|
| 197 |
+
await db_session.commit()
|
| 198 |
+
|
| 199 |
+
login_resp = await client.post("/admin/auth/login", json={
|
| 200 |
+
"username": "viewer_admin", "password": "Viewer@123",
|
| 201 |
+
})
|
| 202 |
+
token = login_resp.json()["data"]["accessToken"]
|
| 203 |
+
|
| 204 |
+
cat = Category(name="็ญ็", sort_order=6, is_active=True)
|
| 205 |
+
db_session.add(cat)
|
| 206 |
+
await db_session.flush()
|
| 207 |
+
vod = Vod(name="ๆ้ๆต่ฏๅฝฑ็", category_id=cat.id)
|
| 208 |
+
db_session.add(vod)
|
| 209 |
+
await db_session.commit()
|
| 210 |
+
|
| 211 |
+
resp = await client.delete(
|
| 212 |
+
f"/admin/vod/{vod.id}",
|
| 213 |
+
headers={"Authorization": f"Bearer {token}"},
|
| 214 |
+
)
|
| 215 |
+
# viewer ๆฒกๆ vod:btn:delete ๆ้๏ผๅบ่ฟๅ 403
|
| 216 |
+
assert resp.status_code == 403
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
# โโ ็ฎก็ๅ็ฎก็ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 220 |
+
|
| 221 |
+
@pytest.mark.asyncio
|
| 222 |
+
async def test_admin_create_and_list_admin(client, superadmin_token):
|
| 223 |
+
headers = {"Authorization": f"Bearer {superadmin_token}"}
|
| 224 |
+
|
| 225 |
+
resp = await client.post("/admin/admin", json={
|
| 226 |
+
"username": "new_admin_01",
|
| 227 |
+
"password": "NewAdmin@123",
|
| 228 |
+
"nickname": "ๆฐ็ฎก็ๅ",
|
| 229 |
+
}, headers=headers)
|
| 230 |
+
assert resp.status_code == 200
|
| 231 |
+
assert resp.json()["code"] == 0
|
| 232 |
+
|
| 233 |
+
list_resp = await client.get("/admin/admin", headers=headers)
|
| 234 |
+
assert list_resp.json()["code"] == 0
|
| 235 |
+
usernames = [a["username"] for a in list_resp.json()["data"]["list"]]
|
| 236 |
+
assert "new_admin_01" in usernames
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@pytest.mark.asyncio
|
| 240 |
+
async def test_admin_reset_password(client, superadmin_token, db_session):
|
| 241 |
+
from app.models.admin import Admin
|
| 242 |
+
from app.utils.auth import hash_password
|
| 243 |
+
|
| 244 |
+
admin = Admin(username="reset_pwd_admin", password_hash=hash_password("OldPass@123"), is_active=True)
|
| 245 |
+
db_session.add(admin)
|
| 246 |
+
await db_session.commit()
|
| 247 |
+
|
| 248 |
+
headers = {"Authorization": f"Bearer {superadmin_token}"}
|
| 249 |
+
resp = await client.put(
|
| 250 |
+
f"/admin/admin/{admin.id}/reset-password",
|
| 251 |
+
json={"password": "NewPass@456"},
|
| 252 |
+
headers=headers,
|
| 253 |
+
)
|
| 254 |
+
assert resp.status_code == 200
|
| 255 |
+
assert resp.json()["code"] == 0
|
| 256 |
+
|
| 257 |
+
# ็จๆฐๅฏ็ ็ปๅฝ
|
| 258 |
+
login_resp = await client.post("/admin/auth/login", json={
|
| 259 |
+
"username": "reset_pwd_admin", "password": "NewPass@456",
|
| 260 |
+
})
|
| 261 |
+
assert login_resp.json()["code"] == 0
|