hanbinsite commited on
Commit
bf34e9d
ยท
1 Parent(s): 9d66536

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

This view is limited to 50 files because it contains too many changes. ย  See raw diff
Files changed (50) hide show
  1. .env.example +30 -7
  2. .gitignore +2 -0
  3. alembic.ini +1 -1
  4. alembic/env.py +4 -0
  5. alembic/versions/8126d022fb75_initial_schema.py +268 -0
  6. app/cache.py +153 -0
  7. app/config.py +12 -2
  8. app/dependencies.py +8 -6
  9. app/limiter.py +4 -0
  10. app/main.py +39 -1
  11. app/models/category.py +12 -1
  12. app/models/favorite.py +6 -1
  13. app/models/play_history.py +8 -1
  14. app/models/source_health.py +6 -1
  15. app/models/sync_log.py +8 -2
  16. app/models/vod.py +14 -1
  17. app/models/vod_source.py +8 -1
  18. app/routers/admin/admin_mgmt.py +35 -26
  19. app/routers/admin/auth.py +4 -2
  20. app/routers/admin/category.py +33 -30
  21. app/routers/admin/role_mgmt.py +21 -22
  22. app/routers/admin/source.py +115 -14
  23. app/routers/admin/sync.py +27 -20
  24. app/routers/admin/system.py +12 -13
  25. app/routers/admin/vod.py +23 -10
  26. app/routers/user/auth.py +8 -5
  27. app/routers/user/category.py +11 -1
  28. app/routers/user/favorite.py +21 -15
  29. app/routers/user/history.py +10 -4
  30. app/routers/user/vod.py +123 -117
  31. app/schemas/admin/admin_mgmt.py +20 -0
  32. app/schemas/admin/category.py +18 -0
  33. app/schemas/admin/role_mgmt.py +17 -0
  34. app/schemas/admin/source.py +26 -0
  35. app/schemas/admin/system.py +6 -0
  36. app/schemas/admin/vod.py +16 -0
  37. app/services/auth_user.py +28 -0
  38. app/services/category.py +45 -0
  39. app/services/collector.py +56 -21
  40. app/services/health.py +128 -0
  41. app/services/scheduler.py +18 -1
  42. app/services/sync.py +63 -0
  43. app/services/vod.py +40 -0
  44. app/utils/auth.py +7 -2
  45. docs/่ต„ๆบ็ซ™.txt +23 -0
  46. docs/่ต„ๆบ็ซ™APIๆŽฅๅฃๆ–‡ๆกฃ.md +534 -0
  47. requirements.txt +7 -1
  48. tests/conftest.py +108 -0
  49. tests/test_admin_auth.py +82 -0
  50. tests/test_admin_mgmt.py +261 -0
.env.example CHANGED
@@ -1,15 +1,38 @@
1
- # ๅผ€ๅ‘็Žฏๅขƒ(้ป˜่ฎคSQLite)
 
 
 
 
 
 
2
  DATABASE_URL=sqlite+aiosqlite:///./binv.db
3
 
4
- # ็”Ÿไบง็Žฏๅขƒ(MySQL)
5
- # DATABASE_URL=mysql+aiomysql://bin_v:Han147258%2B-@124.221.224.204:7104/bin_v
 
 
 
 
 
6
 
7
- SECRET_KEY=binv-secret-key-2026-change-in-prod
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
- SYNC_MAX_CONCURRENT=3
 
 
 
 
 
 
 
 
 
 
 
 
 
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
.gitignore CHANGED
@@ -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
alembic.ini CHANGED
@@ -1,6 +1,6 @@
1
  [alembic]
2
  script_location = alembic
3
- sqlalchemy.url = postgresql+asyncpg://postgres:password@localhost:5432/binv
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
alembic/env.py CHANGED
@@ -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
 
alembic/versions/8126d022fb75_initial_schema.py ADDED
@@ -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')
app/cache.py ADDED
@@ -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:*")
app/config.py CHANGED
@@ -3,14 +3,24 @@ from pydantic_settings import BaseSettings
3
 
4
  class Settings(BaseSettings):
5
  DATABASE_URL: str = "sqlite+aiosqlite:///./binv.db"
6
- DATABASE_URL_PROD: str = "mysql+aiomysql://bin_v:Han147258%2B-@124.221.224.204:7104/bin_v"
7
- SECRET_KEY: str = "binv-secret-key-2026-change-in-prod"
 
 
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
 
app/dependencies.py CHANGED
@@ -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: int | None = payload.get("sub")
27
- if admin_id is None:
 
28
  raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
29
- except JWTError:
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: int | None = payload.get("sub")
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 JWTError:
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
+
app/limiter.py ADDED
@@ -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)
app/main.py CHANGED
@@ -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
- return {"status": "ok"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ }
app/models/category.py CHANGED
@@ -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
+
app/models/favorite.py CHANGED
@@ -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
+ )
app/models/play_history.py CHANGED
@@ -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
+ )
app/models/source_health.py CHANGED
@@ -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
+ )
app/models/sync_log.py CHANGED
@@ -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
- status: Mapped[str] = mapped_column(String(20), nullable=False, comment="running/success/failed")
 
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
+ )
app/models/vod.py CHANGED
@@ -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
+ )
app/models/vod_source.py CHANGED
@@ -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
+ )
app/routers/admin/admin_mgmt.py CHANGED
@@ -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
- items = []
33
- for a in admins:
34
  roles_result = await db.execute(
35
- select(Role.code).join(AdminRole, AdminRole.role_id == Role.id).where(AdminRole.admin_id == a.id)
 
 
36
  )
37
- roles = [r[0] for r in roles_result.all()]
 
 
 
 
 
 
 
 
 
38
  items.append({
39
  "id": a.id, "username": a.username, "nickname": a.nickname,
40
- "avatar": a.avatar, "is_active": a.is_active, "roles": roles,
 
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
- body: dict,
53
  admin: Admin = Depends(require_permission("admin:create")),
54
  db: AsyncSession = Depends(get_db),
55
  ):
56
- username = body.get("username")
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=body.get("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
- body: dict,
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
- if "nickname" in body:
88
- target.nickname = body["nickname"]
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
- body: dict,
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(new_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
- body: dict,
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()
app/routers/admin/auth.py CHANGED
@@ -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
- async def login(req: LoginRequest, db: AsyncSession = Depends(get_db)):
 
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, "็”จๆˆทๅๆˆ–ๅฏ†็ ้”™่ฏฏ")
app/routers/admin/category.py CHANGED
@@ -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
- body: dict,
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
- allowed = ["name", "sort_order", "is_active", "parent_id"]
49
- for field in allowed:
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": cat.name if cat else None,
81
  "source_id": m.source_id,
82
- "source_name": source.name if source else None,
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
- body: dict,
93
  admin: Admin = Depends(require_permission("category:btn:map")),
94
  db: AsyncSession = Depends(get_db),
95
  ):
96
- mappings_data = body.get("mappings", [])
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 mappings_data:
112
- cat_result = await db.execute(select(Category).where(Category.id == m["category_id"]))
113
- cat = cat_result.scalar_one_or_none()
 
 
114
  mapping = CategoryMapping(
115
- category_id=m["category_id"],
116
- source_id=source_id,
117
- source_type_id=m["source_type_id"],
118
- source_type_name=cat.name if cat else str(m["source_type_id"]),
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
 
app/routers/admin/role_mgmt.py CHANGED
@@ -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": perm_count.scalar() or 0,
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
- body: dict,
41
  admin: Admin = Depends(require_permission("role:create")),
42
  db: AsyncSession = Depends(get_db),
43
  ):
44
- name = body.get("name")
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=body.get("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
- body: dict,
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
- if "name" in body:
72
- role.name = body["name"]
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
- body: dict,
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 perm_ids:
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()
app/routers/admin/source.py CHANGED
@@ -1,14 +1,16 @@
1
  import httpx
2
 
3
  from fastapi import APIRouter, Depends, Query
4
- from sqlalchemy import func, select, update
5
  from sqlalchemy.ext.asyncio import AsyncSession
6
 
7
  from app.database import get_db
8
- from app.dependencies import get_current_admin, require_permission
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).order_by(SourceSite.sort_order).offset((page - 1) * page_size).limit(page_size)
 
 
 
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
- body: dict,
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
- allowed_fields = [
101
- "name", "base_url", "site_url", "play_from_m3u8",
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": [{"type_id": c.get("type_id"), "type_name": c.get("type_name")} for c in classes],
 
 
 
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)})
app/routers/admin/sync.py CHANGED
@@ -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
- query = select(SyncLog).order_by(SyncLog.started_at.desc())
28
- count_query = select(func.count(SyncLog.id))
29
 
30
- if source_id:
31
- query = query.where(SyncLog.source_id == source_id)
32
- count_query = count_query.where(SyncLog.source_id == source_id)
33
- if status:
34
- query = query.where(SyncLog.status == status)
35
- count_query = count_query.where(SyncLog.status == status)
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
- source_result = await db.execute(select(SourceSite).where(SourceSite.id == l.source_id))
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
- "updated_count": l.updated_count,
58
- "error_msg": l.error_msg,
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 {}
app/routers/admin/system.py CHANGED
@@ -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
- body: dict,
27
  admin: Admin = Depends(require_permission("system:btn:save")),
28
  ):
29
  from app.services.scheduler import start_scheduler, stop_scheduler
30
 
31
- if "sync_cron_hour" in body:
32
- hour = int(body["sync_cron_hour"])
33
- if 0 <= hour <= 23:
34
- try:
35
- stop_scheduler()
36
- settings.SYNC_CRON_HOUR = hour
37
- start_scheduler()
38
- except Exception:
39
- pass
40
 
41
- if "access_token_expire_minutes" in body:
42
- settings.ACCESS_TOKEN_EXPIRE_MINUTES = int(body["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()
app/routers/admin/vod.py CHANGED
@@ -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": src_count.scalar() or 0,
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
- body: dict,
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
- allowed = ["name", "sub_name", "category_id", "score", "douban_id",
110
- "blurb", "content", "is_end", "area", "year", "actor", "director"]
111
- for field in allowed:
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})
app/routers/user/auth.py CHANGED
@@ -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
- async def register(req: UserRegisterRequest, db: AsyncSession = Depends(get_db)):
 
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
- async def login(req: UserLoginRequest, db: AsyncSession = Depends(get_db)):
 
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")
app/routers/user/category.py CHANGED
@@ -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
- return ApiResponse.ok([r.model_dump() for r in roots])
 
 
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
+
app/routers/user/favorite.py CHANGED
@@ -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
- vod_result = await db.execute(select(Vod).where(Vod.id == f.vod_id))
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.name if vod else "ๆœช็Ÿฅ",
46
- vod_cover=vod.cover if vod else None,
47
- vod_remarks=vod.remarks if vod else None,
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
- existing = await db.execute(
64
- select(Favorite).where(Favorite.user_id == user.id, Favorite.vod_id == req.vod_id)
65
- )
66
- if existing.scalar_one_or_none():
 
 
 
 
 
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(
app/routers/user/history.py CHANGED
@@ -34,16 +34,22 @@ async def list_history(
34
  )
35
  histories = result.scalars().all()
36
 
 
 
 
 
 
 
 
37
  items = []
38
  for h in histories:
39
- vod_result = await db.execute(select(Vod).where(Vod.id == h.vod_id))
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.name if vod else "ๆœช็Ÿฅ",
46
- vod_cover=vod.cover if vod else None,
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,
app/routers/user/vod.py CHANGED
@@ -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
- items = []
41
- for v in vods:
42
- cat_name = await _get_category_name(db, v.category_id)
43
- source_count = await _get_source_count(db, v.id)
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
- return ApiResponse.ok(
62
- PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
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
- items = []
91
- for v in vods:
92
- cat_name = await _get_category_name(db, v.category_id)
93
- source_count = await _get_source_count(db, v.id)
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
- return ApiResponse.ok(
112
- PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
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
- items = []
139
- for v in vods:
140
- cat_name = await _get_category_name(db, v.category_id)
141
- source_count = await _get_source_count(db, v.id)
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
- return ApiResponse.ok(
160
- PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
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
- items = []
189
- for v in vods:
190
- cat_name = await _get_category_name(db, v.category_id)
191
- source_count = await _get_source_count(db, v.id)
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
- return ApiResponse.ok(
210
- PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
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 db.execute(
222
- Vod.__table__.update().where(Vod.id == vod_id).values(view_count=Vod.view_count + 1)
223
- )
224
 
225
- cat_name = await _get_category_name(db, vod.category_id)
 
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
- site_result = await db.execute(select(SourceSite).where(SourceSite.id == vs.source_id))
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
- async def _get_category_name(db: AsyncSession, category_id: int) -> str | None:
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]:
app/schemas/admin/admin_mgmt.py CHANGED
@@ -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)
app/schemas/admin/category.py CHANGED
@@ -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)
app/schemas/admin/role_mgmt.py CHANGED
@@ -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)
app/schemas/admin/source.py CHANGED
@@ -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)
app/schemas/admin/system.py CHANGED
@@ -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)
app/schemas/admin/vod.py CHANGED
@@ -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)
app/services/auth_user.py CHANGED
@@ -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")
app/services/category.py CHANGED
@@ -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
+ }
app/services/collector.py CHANGED
@@ -175,8 +175,8 @@ class Collector:
175
  status=r["status"],
176
  total_fetched=r["total_fetched"],
177
  new_count=r["new_vods"],
178
- updated_count=r["updated_vods"],
179
- error_msg=r["error"],
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
- existing = await db.execute(
233
- select(Vod).where(Vod.name == name).limit(1)
234
- )
235
- vod = existing.scalar_one_or_none()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- douban_id = vod_data.get("vod_douban_id")
242
- if douban_id and str(douban_id).isdigit():
243
- douban_id = int(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 = vod_data.get("vod_year") or 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=vod_data.get("vod_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
- vod_result = await db.execute(select(Vod).where(Vod.name == name).limit(1))
300
- vod = vod_result.scalar_one_or_none()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
 
app/services/health.py CHANGED
@@ -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
+ }
app/services/scheduler.py CHANGED
@@ -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 = 1
 
 
 
 
 
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
 
app/services/sync.py CHANGED
@@ -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
app/services/vod.py CHANGED
@@ -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
+ )
app/utils/auth.py CHANGED
@@ -1,7 +1,7 @@
1
  from datetime import datetime, timedelta, timezone
2
 
3
  import bcrypt
4
- from jose import jwt
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"])
docs/่ต„ๆบ็ซ™.txt ADDED
@@ -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/
docs/่ต„ๆบ็ซ™APIๆŽฅๅฃๆ–‡ๆกฃ.md ADDED
@@ -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ๅฐๆ—ถๆ›ดๆ–ฐๆ•ฐๆฎ๏ผ‰
requirements.txt CHANGED
@@ -6,8 +6,14 @@ aiomysql==0.2.*
6
  alembic==1.14.*
7
  pydantic==2.10.*
8
  pydantic-settings==2.7.*
9
- python-jose[cryptography]==3.3.*
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.*
tests/conftest.py CHANGED
@@ -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"]
tests/test_admin_auth.py CHANGED
@@ -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
tests/test_admin_mgmt.py ADDED
@@ -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