hanbinsite commited on
Commit
9d66536
·
1 Parent(s): 32ddb29

feat: implement full API - all admin/user routes, RBAC, sync service, collector, MySQL config, superadmin hanbin credentials

Browse files
.env.example CHANGED
@@ -1,11 +1,15 @@
1
- # 环境
2
- DATABASE_URL=postgresql+asyncpg://postgres:password@localhost:5432/binv
3
- SECRET_KEY=change-me-to-a-random-secret-key
 
 
 
 
4
  ACCESS_TOKEN_EXPIRE_MINUTES=1440
5
 
6
  # CORS
7
- CORS_ORIGINS=http://localhost:3000,http://localhost:5555
8
 
9
  # 同步
10
  SYNC_CRON_HOUR=1
11
- SYNC_MAX_CONCURRENT=3
 
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
.gitignore CHANGED
@@ -15,3 +15,6 @@ alembic/versions/__pycache__/
15
  .idea/
16
  .vscode/
17
  *.sqlite3
 
 
 
 
15
  .idea/
16
  .vscode/
17
  *.sqlite3
18
+ binv.db
19
+ source_categories.txt
20
+ scripts/fetch_categories.py
app/config.py CHANGED
@@ -2,14 +2,16 @@ from pydantic_settings import BaseSettings
2
 
3
 
4
  class Settings(BaseSettings):
5
- DATABASE_URL: str = "postgresql+asyncpg://postgres:password@localhost:5432/binv"
6
- SECRET_KEY: str = "change-me-to-a-random-secret-key"
 
7
  ACCESS_TOKEN_EXPIRE_MINUTES: int = 1440
8
- CORS_ORIGINS: str = "http://localhost:3000,http://localhost:5555"
9
  SYNC_CRON_HOUR: int = 1
10
  SYNC_MAX_CONCURRENT: int = 3
 
11
 
12
  model_config = {"env_file": ".env", "extra": "ignore"}
13
 
14
 
15
- settings = Settings()
 
2
 
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
 
17
+ settings = Settings()
app/database.py CHANGED
@@ -5,7 +5,7 @@ from sqlalchemy.orm import DeclarativeBase
5
 
6
  from app.config import settings
7
 
8
- engine = create_async_engine(settings.DATABASE_URL, echo=False)
9
  async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
10
 
11
 
 
5
 
6
  from app.config import settings
7
 
8
+ engine = create_async_engine(settings.DATABASE_URL, echo=False, connect_args={"check_same_thread": False} if "sqlite" in settings.DATABASE_URL else {})
9
  async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
10
 
11
 
app/main.py CHANGED
@@ -4,12 +4,16 @@ 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, user_router
 
 
8
 
9
 
10
  @asynccontextmanager
11
  async def lifespan(app: FastAPI):
 
12
  yield
 
13
 
14
 
15
  app = FastAPI(
@@ -33,4 +37,4 @@ app.include_router(user_router, prefix="/user")
33
 
34
  @app.get("/health")
35
  async def health_check():
36
- return {"status": "ok"}
 
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
10
 
11
 
12
  @asynccontextmanager
13
  async def lifespan(app: FastAPI):
14
+ start_scheduler()
15
  yield
16
+ stop_scheduler()
17
 
18
 
19
  app = FastAPI(
 
37
 
38
  @app.get("/health")
39
  async def health_check():
40
+ return {"status": "ok"}
app/models/category.py CHANGED
@@ -1,6 +1,6 @@
1
  from datetime import datetime
2
 
3
- from sqlalchemy import Boolean, Integer, String, func
4
  from sqlalchemy.orm import Mapped, mapped_column
5
 
6
  from app.database import Base
 
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
app/models/vod.py CHANGED
@@ -1,6 +1,6 @@
1
  from datetime import datetime
2
 
3
- from sqlalchemy import Boolean, Float, Integer, String, Text, func
4
  from sqlalchemy.orm import Mapped, mapped_column
5
 
6
  from app.database import Base
 
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
app/routers/admin/admin_mgmt.py CHANGED
@@ -1,33 +1,141 @@
1
- from fastapi import APIRouter
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  router = APIRouter()
4
 
5
 
6
- @router.get("")
7
- async def list_admins():
8
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- @router.post("")
12
- async def create_admin():
13
- pass
 
 
14
 
15
 
16
- @router.put("/{admin_id}")
17
- async def update_admin(admin_id: int):
18
- pass
 
 
 
 
 
 
 
19
 
 
 
 
20
 
21
- @router.delete("/{admin_id}")
22
- async def delete_admin(admin_id: int):
23
- pass
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- @router.put("/{admin_id}/reset-password")
27
- async def reset_password(admin_id: int):
28
- pass
29
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
- @router.put("/{admin_id}/assign-roles")
32
- async def assign_roles(admin_id: int):
33
- pass
 
 
1
+ from datetime import datetime, timezone
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.role import AdminRole, Role
11
+ from app.schemas.common import ApiResponse, PaginatedData
12
+ from app.utils.auth import hash_password
13
 
14
  router = APIRouter()
15
 
16
 
17
+ @router.get("", response_model=ApiResponse)
18
+ async def list_admins(
19
+ page: int = Query(1, ge=1),
20
+ page_size: int = Query(20, ge=1, le=100),
21
+ admin: Admin = Depends(require_permission("admin:list")),
22
+ db: AsyncSession = Depends(get_db),
23
+ ):
24
+ count_result = await db.execute(select(func.count(Admin.id)))
25
+ total = count_result.scalar() or 0
26
+
27
+ result = await db.execute(
28
+ select(Admin).order_by(Admin.id).offset((page - 1) * page_size).limit(page_size)
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
+ })
44
+
45
+ return ApiResponse.ok(
46
+ PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
47
+ )
48
+
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()
72
+ return ApiResponse.ok({"id": new_admin.id})
73
+
74
 
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
+ ):
82
+ result = await db.execute(select(Admin).where(Admin.id == admin_id))
83
+ target = result.scalar_one_or_none()
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
 
94
+ @router.delete("/{admin_id}", response_model=ApiResponse)
95
+ async def delete_admin(
96
+ admin_id: int,
97
+ admin: Admin = Depends(require_permission("admin:delete")),
98
+ db: AsyncSession = Depends(get_db),
99
+ ):
100
+ result = await db.execute(select(Admin).where(Admin.id == admin_id))
101
+ target = result.scalar_one_or_none()
102
+ if not target:
103
+ return ApiResponse.fail(40401, "管理员不存在")
104
 
105
+ await db.execute(AdminRole.__table__.delete().where(AdminRole.admin_id == admin_id))
106
+ await db.delete(target)
107
+ return ApiResponse.ok()
108
 
 
 
 
109
 
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()
app/routers/admin/auth.py CHANGED
@@ -1,33 +1,69 @@
1
- from fastapi import APIRouter
 
 
 
 
 
 
 
 
2
 
3
  router = APIRouter()
4
 
5
 
6
- @router.post("/login")
7
- async def login():
8
- pass
 
 
 
 
9
 
10
 
11
- @router.post("/logout")
12
- async def logout():
13
- pass
14
 
15
 
16
- @router.get("/user-info")
17
- async def get_user_info():
18
- pass
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
 
21
- @router.get("/codes")
22
- async def get_access_codes():
23
- pass
 
 
 
 
24
 
25
 
26
- @router.get("/menus")
27
- async def get_menus():
28
- pass
 
 
 
 
29
 
30
 
31
- @router.get("/permissions")
32
- async def get_permissions():
33
- pass
 
 
 
 
 
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
9
+ from app.utils.auth import create_access_token, verify_password
10
 
11
  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, "用户名或密码错误")
19
+ token = create_access_token(str(admin.id), "admin")
20
+ return ApiResponse.ok(LoginResponse(accessToken=token, expires_in=1440).model_dump())
21
 
22
 
23
+ @router.post("/logout", response_model=ApiResponse)
24
+ async def logout(admin=Depends(get_current_admin)):
25
+ return ApiResponse.ok()
26
 
27
 
28
+ @router.get("/user-info", response_model=ApiResponse)
29
+ async def get_user_info(
30
+ admin=Depends(get_current_admin),
31
+ db: AsyncSession = Depends(get_db),
32
+ ):
33
+ roles = await auth_admin.get_admin_roles(db, admin.id)
34
+ return ApiResponse.ok(
35
+ UserInfoResponse(
36
+ userId=str(admin.id),
37
+ username=admin.username,
38
+ realName=admin.nickname,
39
+ roles=roles,
40
+ avatar=admin.avatar,
41
+ ).model_dump()
42
+ )
43
 
44
 
45
+ @router.get("/codes", response_model=ApiResponse)
46
+ async def get_access_codes(
47
+ admin=Depends(get_current_admin),
48
+ db: AsyncSession = Depends(get_db),
49
+ ):
50
+ codes = await auth_admin.get_admin_permissions(db, admin.id)
51
+ return ApiResponse.ok(codes)
52
 
53
 
54
+ @router.get("/menus", response_model=ApiResponse)
55
+ async def get_menus(
56
+ admin=Depends(get_current_admin),
57
+ db: AsyncSession = Depends(get_db),
58
+ ):
59
+ menus = await auth_admin.get_menu_tree(db, admin.id)
60
+ return ApiResponse.ok(menus)
61
 
62
 
63
+ @router.get("/permissions", response_model=ApiResponse)
64
+ async def get_permissions(
65
+ admin=Depends(get_current_admin),
66
+ db: AsyncSession = Depends(get_db),
67
+ ):
68
+ tree = await auth_admin.get_permission_tree(db)
69
+ return ApiResponse.ok(tree)
app/routers/admin/category.py CHANGED
@@ -1,18 +1,172 @@
1
- from fastapi import APIRouter
 
 
 
 
 
 
 
 
 
2
 
3
  router = APIRouter()
4
 
5
 
6
- @router.get("")
7
- async def list_categories():
8
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
 
 
 
10
 
11
- @router.put("/{category_id}")
12
- async def update_category(category_id: int):
13
- pass
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- @router.put("/mapping")
17
- async def update_mapping():
18
- pass
 
1
+ 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()
13
 
14
 
15
+ @router.get("", response_model=ApiResponse)
16
+ async def list_categories(
17
+ admin: Admin = Depends(require_permission("category:list")),
18
+ db: AsyncSession = Depends(get_db),
19
+ ):
20
+ result = await db.execute(select(Category).order_by(Category.sort_order))
21
+ all_cats = result.scalars().all()
22
+
23
+ items = []
24
+ for c in all_cats:
25
+ items.append({
26
+ "id": c.id,
27
+ "name": c.name,
28
+ "parent_id": c.parent_id,
29
+ "sort_order": c.sort_order,
30
+ "is_active": c.is_active,
31
+ })
32
+
33
+ return ApiResponse.ok(items)
34
+
35
+
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
+ ):
43
+ result = await db.execute(select(Category).where(Category.id == category_id))
44
+ cat = result.scalar_one_or_none()
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
+
57
+ @router.get("/mapping", response_model=ApiResponse)
58
+ async def list_mappings(
59
+ source_id: int | None = Query(None),
60
+ admin: Admin = Depends(require_permission("category:list")),
61
+ db: AsyncSession = Depends(get_db),
62
+ ):
63
+ query = select(CategoryMapping)
64
+ if source_id:
65
+ query = query.where(CategoryMapping.source_id == source_id)
66
+
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
+ })
86
+
87
+ return ApiResponse.ok(items)
88
+
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
+
122
+ await db.flush()
123
+ return ApiResponse.ok()
124
+
125
+
126
+ @router.post("/mapping/auto", response_model=ApiResponse)
127
+ async def auto_map_categories(
128
+ source_id: int,
129
+ admin: Admin = Depends(require_permission("category:btn:map")),
130
+ db: AsyncSession = Depends(get_db),
131
+ ):
132
+ source_result = await db.execute(select(SourceSite).where(SourceSite.id == source_id))
133
+ source = source_result.scalar_one_or_none()
134
+ if not source:
135
+ return ApiResponse.fail(40401, "源站不存在")
136
+
137
+ import httpx
138
+ try:
139
+ async with httpx.AsyncClient(timeout=15, follow_redirects=True) as client:
140
+ resp = await client.get(source.base_url, params={"ac": "list"})
141
+ data = resp.json()
142
+ classes = data.get("class", [])
143
+ except Exception as e:
144
+ return ApiResponse.fail(40005, f"获取源站分类失败: {e}")
145
 
146
+ cat_result = await db.execute(select(Category))
147
+ all_cats = cat_result.scalars().all()
148
+ cat_name_map = {c.name: c.id for c in all_cats}
149
 
150
+ await db.execute(sa_delete(CategoryMapping).where(CategoryMapping.source_id == source_id))
151
+ await db.flush()
 
152
 
153
+ mapped = 0
154
+ unmapped = 0
155
+ for c in classes:
156
+ source_type_id = c.get("type_id")
157
+ source_type_name = c.get("type_name")
158
+ cat_id = cat_name_map.get(source_type_name)
159
+ if cat_id:
160
+ mapping = CategoryMapping(
161
+ category_id=cat_id,
162
+ source_id=source_id,
163
+ source_type_id=source_type_id,
164
+ source_type_name=source_type_name,
165
+ )
166
+ db.add(mapping)
167
+ mapped += 1
168
+ else:
169
+ unmapped += 1
170
 
171
+ await db.flush()
172
+ return ApiResponse.ok({"mapped": mapped, "unmapped": unmapped, "total_classes": len(classes)})
 
app/routers/admin/role_mgmt.py CHANGED
@@ -1,28 +1,114 @@
1
- from fastapi import APIRouter
 
 
 
 
 
 
 
 
 
2
 
3
  router = APIRouter()
4
 
5
 
6
- @router.get("")
7
- async def list_roles():
8
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- @router.post("")
12
- async def create_role():
13
- pass
 
 
 
 
14
 
15
 
16
- @router.put("/{role_id}")
17
- async def update_role(role_id: int):
18
- pass
 
 
 
 
 
 
 
 
 
19
 
 
 
 
 
20
 
21
- @router.delete("/{role_id}")
22
- async def delete_role(role_id: int):
23
- pass
24
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- @router.put("/{role_id}/permissions")
27
- async def assign_permissions(role_id: int):
28
- pass
 
 
1
+ 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 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()
13
 
14
 
15
+ @router.get("", response_model=ApiResponse)
16
+ async def list_roles(
17
+ admin: Admin = Depends(require_permission("role:list")),
18
+ db: AsyncSession = Depends(get_db),
19
+ ):
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)
36
+
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})
57
+
58
 
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
+ ):
66
+ result = await db.execute(select(Role).where(Role.id == role_id))
67
+ role = result.scalar_one_or_none()
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
 
80
+ @router.delete("/{role_id}", response_model=ApiResponse)
81
+ async def delete_role(
82
+ role_id: int,
83
+ admin: Admin = Depends(require_permission("role:delete")),
84
+ db: AsyncSession = Depends(get_db),
85
+ ):
86
+ result = await db.execute(select(Role).where(Role.id == role_id))
87
+ role = result.scalar_one_or_none()
88
+ if not role:
89
+ return ApiResponse.fail(40401, "角色不存在")
90
+ if role.is_builtin:
91
+ return ApiResponse.fail(40003, "内置角色不可删除")
92
 
93
+ await db.execute(RolePermission.__table__.delete().where(RolePermission.role_id == role_id))
94
+ await db.execute(AdminRole.__table__.delete().where(AdminRole.role_id == role_id))
95
+ await db.delete(role)
96
+ return ApiResponse.ok()
97
 
 
 
 
98
 
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()
app/routers/admin/source.py CHANGED
@@ -1,43 +1,153 @@
1
- from fastapi import APIRouter
2
 
3
- router = APIRouter()
4
-
5
-
6
- @router.get("")
7
- async def list_sources():
8
- pass
9
-
10
-
11
- @router.post("")
12
- async def create_source():
13
- pass
14
-
15
-
16
- @router.get("/{source_id}")
17
- async def get_source(source_id: int):
18
- pass
19
 
 
 
 
 
 
20
 
21
- @router.put("/{source_id}")
22
- async def update_source(source_id: int):
23
- pass
24
-
25
-
26
- @router.delete("/{source_id}")
27
- async def delete_source(source_id: int):
28
- pass
29
-
30
-
31
- @router.post("/{source_id}/test")
32
- async def test_source(source_id: int):
33
- pass
34
-
35
-
36
- @router.post("/{source_id}/sync")
37
- async def sync_source(source_id: int):
38
- pass
39
 
40
 
41
- @router.put("/{source_id}/enable")
42
- async def enable_source(source_id: int):
43
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
 
15
 
16
+ @router.get("", response_model=ApiResponse)
17
+ async def list_sources(
18
+ page: int = Query(1, ge=1),
19
+ page_size: int = Query(20, ge=1, le=100),
20
+ admin: Admin = Depends(require_permission("source:list")),
21
+ db: AsyncSession = Depends(get_db),
22
+ ):
23
+ count_result = await db.execute(select(func.count(SourceSite.id)))
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,
36
+ "code": s.code,
37
+ "base_url": s.base_url,
38
+ "site_url": s.site_url,
39
+ "play_from_m3u8": s.play_from_m3u8,
40
+ "play_from_yun": s.play_from_yun,
41
+ "parse_url": s.parse_url,
42
+ "is_active": s.is_active,
43
+ "sync_interval": s.sync_interval,
44
+ "last_sync_at": str(s.last_sync_at) if s.last_sync_at else None,
45
+ "last_sync_status": s.last_sync_status,
46
+ "last_sync_count": s.last_sync_count,
47
+ "total_count": s.total_count,
48
+ "sort_order": s.sort_order,
49
+ "remark": s.remark,
50
+ })
51
+
52
+ return ApiResponse.ok(
53
+ PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
54
+ )
55
+
56
+
57
+ @router.get("/{source_id}", response_model=ApiResponse)
58
+ async def get_source(
59
+ source_id: int,
60
+ admin: Admin = Depends(require_permission("source:detail")),
61
+ db: AsyncSession = Depends(get_db),
62
+ ):
63
+ result = await db.execute(select(SourceSite).where(SourceSite.id == source_id))
64
+ source = result.scalar_one_or_none()
65
+ if not source:
66
+ return ApiResponse.fail(40401, "源站不存在")
67
+
68
+ return ApiResponse.ok({
69
+ "id": source.id,
70
+ "name": source.name,
71
+ "code": source.code,
72
+ "base_url": source.base_url,
73
+ "site_url": source.site_url,
74
+ "play_from_m3u8": source.play_from_m3u8,
75
+ "play_from_yun": source.play_from_yun,
76
+ "parse_url": source.parse_url,
77
+ "is_active": source.is_active,
78
+ "sync_interval": source.sync_interval,
79
+ "last_sync_at": str(source.last_sync_at) if source.last_sync_at else None,
80
+ "last_sync_status": source.last_sync_status,
81
+ "last_sync_count": source.last_sync_count,
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
+ ):
95
+ result = await db.execute(select(SourceSite).where(SourceSite.id == source_id))
96
+ source = result.scalar_one_or_none()
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,
116
+ admin: Admin = Depends(require_permission("source:btn:test")),
117
+ db: AsyncSession = Depends(get_db),
118
+ ):
119
+ result = await db.execute(select(SourceSite).where(SourceSite.id == source_id))
120
+ source = result.scalar_one_or_none()
121
+ if not source:
122
+ return ApiResponse.fail(40401, "源站不存在")
123
+
124
+ try:
125
+ async with httpx.AsyncClient(timeout=15, follow_redirects=True) as client:
126
+ resp = await client.get(source.base_url, params={"ac": "list", "pg": "1"})
127
+ data = resp.json()
128
+ total = data.get("total", 0)
129
+ classes = data.get("class", [])
130
+ return ApiResponse.ok({
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)})
138
+
139
+
140
+ @router.put("/{source_id}/enable", response_model=ApiResponse)
141
+ async def enable_source(
142
+ source_id: int,
143
+ admin: Admin = Depends(require_permission("source:btn:enable")),
144
+ db: AsyncSession = Depends(get_db),
145
+ ):
146
+ result = await db.execute(select(SourceSite).where(SourceSite.id == source_id))
147
+ source = result.scalar_one_or_none()
148
+ if not source:
149
+ return ApiResponse.fail(40401, "源站不存在")
150
+
151
+ source.is_active = not source.is_active
152
+ await db.flush()
153
+ return ApiResponse.ok({"is_active": source.is_active})
app/routers/admin/sync.py CHANGED
@@ -1,13 +1,100 @@
1
- from fastapi import APIRouter
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  router = APIRouter()
4
 
5
 
6
- @router.get("/log")
7
- async def list_sync_logs():
8
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
 
11
- @router.post("/trigger")
12
- async def trigger_sync():
13
- pass
 
 
 
 
 
1
+ import asyncio
2
+
3
+ from fastapi import APIRouter, Depends, Query
4
+ from sqlalchemy import select, func
5
+ from sqlalchemy.ext.asyncio import AsyncSession
6
+
7
+ from app.database import async_session, get_db
8
+ from app.dependencies import get_current_admin, require_permission
9
+ from app.models.admin import Admin
10
+ 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
 
17
 
18
+ @router.get("/log", response_model=ApiResponse)
19
+ async def list_sync_logs(
20
+ page: int = Query(1, ge=1),
21
+ page_size: int = Query(20, ge=1, le=100),
22
+ source_id: int | None = Query(None),
23
+ status: str | None = Query(None),
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,
52
+ "source_name": source.name if source else "Unknown",
53
+ "range_type": l.range_type,
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
+ })
62
+
63
+ return ApiResponse.ok(
64
+ PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
65
+ )
66
+
67
+
68
+ @router.post("/trigger", response_model=ApiResponse)
69
+ async def trigger_sync(
70
+ range_type: str = Query("daily", pattern="^(all|monthly|weekly|daily)$"),
71
+ source_id: int | None = Query(None),
72
+ admin: Admin = Depends(require_permission("sync:btn:trigger")),
73
+ ):
74
+ if collector.is_running:
75
+ return ApiResponse.fail(40003, "同步任务正在执行中,请稍后再试")
76
+
77
+ if source_id:
78
+ async with async_session() as db:
79
+ result = await db.execute(select(SourceSite).where(SourceSite.id == source_id))
80
+ source = result.scalar_one_or_none()
81
+ if not source:
82
+ return ApiResponse.fail(40401, "源站不存在")
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 {}
90
+
91
+ return ApiResponse.ok(result)
92
 
93
 
94
+ @router.get("/status", response_model=ApiResponse)
95
+ async def sync_status(
96
+ admin: Admin = Depends(require_permission("sync:list")),
97
+ ):
98
+ return ApiResponse.ok({
99
+ "is_running": collector.is_running,
100
+ })
app/routers/admin/system.py CHANGED
@@ -1,13 +1,44 @@
1
- from fastapi import APIRouter
 
 
 
 
 
 
 
2
 
3
  router = APIRouter()
4
 
5
 
6
- @router.get("/config")
7
- async def get_config():
8
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
 
 
10
 
11
- @router.put("/config")
12
- async def update_config():
13
- pass
 
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 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()
11
 
12
 
13
+ @router.get("/config", response_model=ApiResponse)
14
+ async def get_config(
15
+ admin: Admin = Depends(require_permission("system:config")),
16
+ ):
17
+ return ApiResponse.ok({
18
+ "sync_cron_hour": settings.SYNC_CRON_HOUR,
19
+ "sync_max_concurrent": settings.SYNC_MAX_CONCURRENT,
20
+ "access_token_expire_minutes": settings.ACCESS_TOKEN_EXPIRE_MINUTES,
21
+ })
22
+
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()
 
 
app/routers/admin/user_mgmt.py CHANGED
@@ -1,23 +1,96 @@
1
- from fastapi import APIRouter
 
 
 
 
 
 
 
 
2
 
3
  router = APIRouter()
4
 
5
 
6
- @router.get("")
7
- async def list_users():
8
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
 
11
- @router.get("/{user_id}")
12
- async def get_user(user_id: int):
13
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
 
16
- @router.put("/{user_id}/ban")
17
- async def ban_user(user_id: int):
18
- pass
 
 
 
 
 
 
 
 
 
19
 
20
 
21
- @router.delete("/{user_id}")
22
- async def delete_user(user_id: int):
23
- pass
 
 
 
 
 
 
1
+ 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 require_permission
7
+ from app.models.admin import Admin
8
+ from app.models.user import User
9
+ from app.schemas.common import ApiResponse, PaginatedData
10
 
11
  router = APIRouter()
12
 
13
 
14
+ @router.get("", response_model=ApiResponse)
15
+ async def list_users(
16
+ page: int = Query(1, ge=1),
17
+ page_size: int = Query(20, ge=1, le=100),
18
+ keyword: str | None = Query(None),
19
+ admin: Admin = Depends(require_permission("user:list")),
20
+ db: AsyncSession = Depends(get_db),
21
+ ):
22
+ query = select(User)
23
+ count_query = select(func.count(User.id))
24
+
25
+ if keyword:
26
+ pattern = f"%{keyword}%"
27
+ q = User.username.ilike(pattern) | User.nickname.ilike(pattern) | User.email.ilike(pattern)
28
+ query = query.where(q)
29
+ count_query = count_query.where(q)
30
+
31
+ total_result = await db.execute(count_query)
32
+ total = total_result.scalar() or 0
33
+
34
+ result = await db.execute(
35
+ query.order_by(User.created_at.desc())
36
+ .offset((page - 1) * page_size)
37
+ .limit(page_size)
38
+ )
39
+ users = result.scalars().all()
40
+
41
+ items = []
42
+ for u in users:
43
+ items.append({
44
+ "id": u.id, "username": u.username, "email": u.email,
45
+ "nickname": u.nickname, "avatar": u.avatar,
46
+ "is_active": u.is_active,
47
+ "last_login_at": str(u.last_login_at) if u.last_login_at else None,
48
+ "created_at": str(u.created_at) if u.created_at else None,
49
+ })
50
+
51
+ return ApiResponse.ok(
52
+ PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
53
+ )
54
 
55
 
56
+ @router.get("/{user_id}", response_model=ApiResponse)
57
+ async def get_user(
58
+ user_id: int,
59
+ admin: Admin = Depends(require_permission("user:detail")),
60
+ db: AsyncSession = Depends(get_db),
61
+ ):
62
+ result = await db.execute(select(User).where(User.id == user_id))
63
+ user = result.scalar_one_or_none()
64
+ if not user:
65
+ return ApiResponse.fail(40401, "用户不存在")
66
+ return ApiResponse.ok({
67
+ "id": user.id, "username": user.username, "email": user.email,
68
+ "nickname": user.nickname, "avatar": user.avatar,
69
+ "is_active": user.is_active,
70
+ "last_login_at": str(user.last_login_at) if user.last_login_at else None,
71
+ "created_at": str(user.created_at) if user.created_at else None,
72
+ })
73
 
74
 
75
+ @router.put("/{user_id}/ban", response_model=ApiResponse)
76
+ async def ban_user(
77
+ user_id: int,
78
+ admin: Admin = Depends(require_permission("user:btn:ban")),
79
+ db: AsyncSession = Depends(get_db),
80
+ ):
81
+ result = await db.execute(select(User).where(User.id == user_id))
82
+ user = result.scalar_one_or_none()
83
+ if not user:
84
+ return ApiResponse.fail(40401, "用户不存在")
85
+ user.is_active = not user.is_active
86
+ return ApiResponse.ok({"is_active": user.is_active})
87
 
88
 
89
+ @router.delete("/{user_id}", response_model=ApiResponse)
90
+ async def delete_user(
91
+ user_id: int,
92
+ admin: Admin = Depends(require_permission("user:btn:delete")),
93
+ db: AsyncSession = Depends(get_db),
94
+ ):
95
+ await db.execute(sa_delete(User).where(User.id == user_id))
96
+ return ApiResponse.ok()
app/routers/admin/vod.py CHANGED
@@ -1,33 +1,153 @@
1
- from fastapi import APIRouter
 
 
 
 
 
 
 
 
 
2
 
3
  router = APIRouter()
4
 
5
 
6
- @router.get("")
7
- async def list_vods():
8
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- @router.get("/{vod_id}")
12
- async def get_vod(vod_id: int):
13
- pass
14
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- @router.put("/{vod_id}")
17
- async def update_vod(vod_id: int):
18
- pass
 
 
 
19
 
20
 
21
- @router.delete("/{vod_id}")
22
- async def delete_vod(vod_id: int):
23
- pass
 
 
 
 
 
 
24
 
25
 
26
- @router.put("/{vod_id}/hide")
27
- async def toggle_hide(vod_id: int):
28
- pass
 
 
 
 
 
 
 
 
 
29
 
30
 
31
- @router.put("/{vod_id}/recommend")
32
- async def toggle_recommend(vod_id: int):
33
- pass
 
 
 
 
 
 
 
 
 
 
1
+ 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()
13
 
14
 
15
+ @router.get("", response_model=ApiResponse)
16
+ async def list_vods(
17
+ page: int = Query(1, ge=1),
18
+ page_size: int = Query(20, ge=1, le=100),
19
+ category_id: int | None = Query(None),
20
+ keyword: str | None = Query(None),
21
+ is_hidden: bool | None = Query(None),
22
+ is_recommended: bool | None = Query(None),
23
+ admin: Admin = Depends(require_permission("vod:list")),
24
+ db: AsyncSession = Depends(get_db),
25
+ ):
26
+ query = select(Vod)
27
+ count_query = select(func.count(Vod.id))
28
+
29
+ if category_id:
30
+ query = query.where(Vod.category_id == category_id)
31
+ count_query = count_query.where(Vod.category_id == category_id)
32
+ if keyword:
33
+ pattern = f"%{keyword}%"
34
+ q = Vod.name.ilike(pattern)
35
+ query = query.where(q)
36
+ count_query = count_query.where(q)
37
+ if is_hidden is not None:
38
+ query = query.where(Vod.is_hidden == is_hidden)
39
+ count_query = count_query.where(Vod.is_hidden == is_hidden)
40
+ if is_recommended is not None:
41
+ query = query.where(Vod.is_recommended == is_recommended)
42
+ count_query = count_query.where(Vod.is_recommended == is_recommended)
43
+
44
+ total_result = await db.execute(count_query)
45
+ total = total_result.scalar() or 0
46
+
47
+ result = await db.execute(
48
+ query.order_by(Vod.updated_at.desc())
49
+ .offset((page - 1) * page_size)
50
+ .limit(page_size)
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
+
69
+ return ApiResponse.ok(
70
+ PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
71
+ )
72
+
73
 
74
+ @router.get("/{vod_id}", response_model=ApiResponse)
75
+ async def get_vod(
76
+ vod_id: int,
77
+ admin: Admin = Depends(require_permission("vod:detail")),
78
+ db: AsyncSession = Depends(get_db),
79
+ ):
80
+ result = await db.execute(select(Vod).where(Vod.id == vod_id))
81
+ vod = result.scalar_one_or_none()
82
+ if not vod:
83
+ return ApiResponse.fail(40401, "影片不存在")
84
+ return ApiResponse.ok({
85
+ "id": vod.id, "name": vod.name, "sub_name": vod.sub_name,
86
+ "en_name": vod.en_name, "category_id": vod.category_id,
87
+ "cover": vod.cover, "actor": vod.actor, "director": vod.director,
88
+ "area": vod.area, "lang": vod.lang, "year": vod.year,
89
+ "duration": vod.duration, "score": vod.score,
90
+ "douban_id": vod.douban_id, "blurb": vod.blurb,
91
+ "content": vod.content, "remarks": vod.remarks,
92
+ "is_end": vod.is_end, "is_hidden": vod.is_hidden,
93
+ "is_recommended": vod.is_recommended, "view_count": vod.view_count,
94
+ })
95
 
 
 
 
96
 
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
+ ):
104
+ result = await db.execute(select(Vod).where(Vod.id == vod_id))
105
+ vod = result.scalar_one_or_none()
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
 
117
+ @router.delete("/{vod_id}", response_model=ApiResponse)
118
+ async def delete_vod(
119
+ vod_id: int,
120
+ admin: Admin = Depends(require_permission("vod:btn:delete")),
121
+ db: AsyncSession = Depends(get_db),
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
 
128
+ @router.put("/{vod_id}/hide", response_model=ApiResponse)
129
+ async def toggle_hide(
130
+ vod_id: int,
131
+ admin: Admin = Depends(require_permission("vod:btn:hide")),
132
+ db: AsyncSession = Depends(get_db),
133
+ ):
134
+ result = await db.execute(select(Vod).where(Vod.id == vod_id))
135
+ vod = result.scalar_one_or_none()
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
 
142
+ @router.put("/{vod_id}/recommend", response_model=ApiResponse)
143
+ async def toggle_recommend(
144
+ vod_id: int,
145
+ admin: Admin = Depends(require_permission("vod:btn:recommend")),
146
+ db: AsyncSession = Depends(get_db),
147
+ ):
148
+ result = await db.execute(select(Vod).where(Vod.id == vod_id))
149
+ vod = result.scalar_one_or_none()
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})
app/routers/user/auth.py CHANGED
@@ -1,18 +1,81 @@
1
- from fastapi import APIRouter
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  router = APIRouter()
4
 
5
 
6
- @router.post("/register")
7
- async def register():
8
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
 
 
10
 
11
- @router.post("/login")
12
- async def login():
13
- pass
 
14
 
15
 
16
- @router.get("/profile")
17
- async def get_profile():
18
- pass
 
 
 
 
 
 
 
 
 
 
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
12
+ from app.schemas.user.auth import (
13
+ UserRegisterRequest,
14
+ UserLoginRequest,
15
+ UserLoginResponse,
16
+ UserProfileResponse,
17
+ )
18
+ from app.schemas.user.category import CategoryUserNode
19
+ from app.utils.auth import hash_password, verify_password, create_access_token
20
 
21
  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_(
29
+ User.username == req.username,
30
+ User.email == req.email if req.email else False,
31
+ )
32
+ )
33
+ )
34
+ if result.scalar_one_or_none():
35
+ return ApiResponse.fail(40001, "用户名或邮箱已存在")
36
+
37
+ user = User(
38
+ username=req.username,
39
+ email=req.email,
40
+ nickname=req.nickname or req.username,
41
+ password_hash=hash_password(req.password),
42
+ )
43
+ db.add(user)
44
+ await db.flush()
45
+
46
+ token = create_access_token(str(user.id), "user")
47
+ return ApiResponse.ok(
48
+ UserLoginResponse(accessToken=token, expires_in=1440).model_dump()
49
+ )
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(
57
+ req.password, user.password_hash
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")
65
+ return ApiResponse.ok(
66
+ UserLoginResponse(accessToken=token, expires_in=1440).model_dump()
67
+ )
68
 
69
 
70
+ @router.get("/profile", response_model=ApiResponse)
71
+ async def get_profile(user: User = Depends(get_current_user)):
72
+ return ApiResponse.ok(
73
+ UserProfileResponse(
74
+ id=user.id,
75
+ username=user.username,
76
+ email=user.email,
77
+ nickname=user.nickname,
78
+ avatar=user.avatar,
79
+ created_at=user.created_at,
80
+ ).model_dump()
81
+ )
app/routers/user/category.py CHANGED
@@ -1,8 +1,48 @@
1
- from fastapi import APIRouter
 
 
 
 
 
 
 
2
 
3
  router = APIRouter()
4
 
5
 
6
- @router.get("")
7
- async def list_categories():
8
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
8
+ from app.schemas.user.category import CategoryUserNode
9
 
10
  router = APIRouter()
11
 
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)
18
+ .order_by(Category.sort_order)
19
+ )
20
+ all_cats = result.scalars().all()
21
+
22
+ cat_map: dict[int, CategoryUserNode] = {}
23
+ for c in all_cats:
24
+ cat_map[c.id] = CategoryUserNode(id=c.id, name=c.name, children=[])
25
+
26
+ roots: list[CategoryUserNode] = []
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
+ parent = cat_map[c.parent_id]
31
+ if parent.children is None:
32
+ parent.children = []
33
+ parent.children.append(node)
34
+ else:
35
+ roots.append(node)
36
+
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):
44
+ if node.children is not None:
45
+ for child in node.children:
46
+ _clean_empty_children(child)
47
+ if len(node.children) == 0:
48
+ node.children = None
app/routers/user/favorite.py CHANGED
@@ -1,18 +1,88 @@
1
- from fastapi import APIRouter
 
 
 
 
 
 
 
 
 
 
2
 
3
  router = APIRouter()
4
 
5
 
6
- @router.get("")
7
- async def list_favorites():
8
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
 
10
 
11
- @router.post("")
12
- async def add_favorite():
13
- pass
14
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- @router.delete("/{vod_id}")
17
- async def remove_favorite(vod_id: int):
18
- pass
 
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
6
+ from app.dependencies import get_current_user
7
+ from app.models.favorite import Favorite
8
+ from app.models.user import User
9
+ from app.models.vod import Vod
10
+ from app.schemas.common import ApiResponse, PaginatedData
11
+ from app.schemas.user.favorite import FavoriteItem, AddFavoriteRequest
12
 
13
  router = APIRouter()
14
 
15
 
16
+ @router.get("", response_model=ApiResponse)
17
+ async def list_favorites(
18
+ page: int = Query(1, ge=1),
19
+ page_size: int = Query(24, ge=1, le=100),
20
+ user: User = Depends(get_current_user),
21
+ db: AsyncSession = Depends(get_db),
22
+ ):
23
+ count_result = await db.execute(
24
+ select(func.count(Favorite.id)).where(Favorite.user_id == user.id)
25
+ )
26
+ total = count_result.scalar() or 0
27
+
28
+ result = await db.execute(
29
+ select(Favorite)
30
+ .where(Favorite.user_id == user.id)
31
+ .order_by(Favorite.created_at.desc())
32
+ .offset((page - 1) * page_size)
33
+ .limit(page_size)
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
+ )
51
+
52
+ return ApiResponse.ok(
53
+ PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
54
+ )
55
+
56
+
57
+ @router.post("", response_model=ApiResponse)
58
+ async def add_favorite(
59
+ req: AddFavoriteRequest,
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(
78
+ vod_id: int,
79
+ user: User = Depends(get_current_user),
80
+ db: AsyncSession = Depends(get_db),
81
+ ):
82
+ result = await db.execute(
83
+ sa_delete(Favorite).where(Favorite.user_id == user.id, Favorite.vod_id == vod_id)
84
+ )
85
+ if result.rowcount == 0:
86
+ return ApiResponse.fail(40401, "收藏记录不存在")
87
 
88
+ return ApiResponse.ok()
 
 
app/routers/user/history.py CHANGED
@@ -1,18 +1,111 @@
1
- from fastapi import APIRouter
 
 
 
 
 
 
 
 
 
 
2
 
3
  router = APIRouter()
4
 
5
 
6
- @router.get("")
7
- async def list_history():
8
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
 
 
10
 
11
- @router.post("")
12
- async def record_history():
13
- pass
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- @router.delete("/{history_id}")
17
- async def delete_history(history_id: int):
18
- pass
 
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
6
+ from app.dependencies import get_current_user
7
+ from app.models.play_history import PlayHistory
8
+ from app.models.user import User
9
+ from app.models.vod import Vod
10
+ from app.schemas.common import ApiResponse, PaginatedData
11
+ from app.schemas.user.history import HistoryItem, RecordHistoryRequest
12
 
13
  router = APIRouter()
14
 
15
 
16
+ @router.get("", response_model=ApiResponse)
17
+ async def list_history(
18
+ page: int = Query(1, ge=1),
19
+ page_size: int = Query(24, ge=1, le=100),
20
+ user: User = Depends(get_current_user),
21
+ db: AsyncSession = Depends(get_db),
22
+ ):
23
+ count_result = await db.execute(
24
+ select(func.count(PlayHistory.id)).where(PlayHistory.user_id == user.id)
25
+ )
26
+ total = count_result.scalar() or 0
27
+
28
+ result = await db.execute(
29
+ select(PlayHistory)
30
+ .where(PlayHistory.user_id == user.id)
31
+ .order_by(PlayHistory.updated_at.desc())
32
+ .offset((page - 1) * page_size)
33
+ .limit(page_size)
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,
50
+ progress=h.progress,
51
+ duration=h.duration,
52
+ updated_at=h.updated_at,
53
+ ).model_dump()
54
+ )
55
+
56
+ return ApiResponse.ok(
57
+ PaginatedData(list=items, total=total, page=page, page_size=page_size).model_dump()
58
+ )
59
+
60
+
61
+ @router.post("", response_model=ApiResponse)
62
+ async def record_history(
63
+ req: RecordHistoryRequest,
64
+ user: User = Depends(get_current_user),
65
+ db: AsyncSession = Depends(get_db),
66
+ ):
67
+ existing = await db.execute(
68
+ select(PlayHistory).where(
69
+ PlayHistory.user_id == user.id,
70
+ PlayHistory.vod_id == req.vod_id,
71
+ PlayHistory.source_id == req.source_id,
72
+ )
73
+ )
74
+ history = existing.scalar_one_or_none()
75
+
76
+ if history:
77
+ history.episode = req.episode
78
+ history.play_url = req.play_url
79
+ history.progress = req.progress
80
+ history.duration = req.duration
81
+ else:
82
+ history = PlayHistory(
83
+ user_id=user.id,
84
+ vod_id=req.vod_id,
85
+ source_id=req.source_id,
86
+ episode=req.episode,
87
+ play_url=req.play_url,
88
+ progress=req.progress,
89
+ duration=req.duration,
90
+ )
91
+ db.add(history)
92
 
93
+ await db.flush()
94
+ return ApiResponse.ok()
95
 
 
 
 
96
 
97
+ @router.delete("/{history_id}", response_model=ApiResponse)
98
+ async def delete_history(
99
+ history_id: int,
100
+ user: User = Depends(get_current_user),
101
+ db: AsyncSession = Depends(get_db),
102
+ ):
103
+ result = await db.execute(
104
+ sa_delete(PlayHistory).where(
105
+ PlayHistory.id == history_id, PlayHistory.user_id == user.id
106
+ )
107
+ )
108
+ if result.rowcount == 0:
109
+ return ApiResponse.fail(40401, "记录不存在")
110
 
111
+ return ApiResponse.ok()
 
 
app/routers/user/vod.py CHANGED
@@ -1,28 +1,323 @@
1
- from fastapi import APIRouter
 
 
 
 
 
 
 
 
 
 
2
 
3
  router = APIRouter()
4
 
5
 
6
- @router.get("")
7
- async def list_vods():
8
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
 
11
- @router.get("/search")
12
- async def search_vods():
13
- pass
14
 
15
 
16
- @router.get("/recommended")
17
- async def recommended_vods():
18
- pass
 
 
 
 
19
 
20
 
21
- @router.get("/latest")
22
- async def latest_vods():
23
- pass
 
24
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- @router.get("/{vod_id}")
27
- async def get_vod(vod_id: int):
28
- pass
 
1
+ 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
8
+ 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),
19
+ page: int = Query(1, ge=1),
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
+
26
+ if category_id:
27
+ query = query.where(Vod.category_id == category_id)
28
+ count_query = count_query.where(Vod.category_id == category_id)
29
+
30
+ total_result = await db.execute(count_query)
31
+ total = total_result.scalar() or 0
32
+
33
+ result = await db.execute(
34
+ query.order_by(Vod.updated_at.desc())
35
+ .offset((page - 1) * page_size)
36
+ .limit(page_size)
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)
67
+ async def search_vods(
68
+ keyword: str = Query(..., min_length=1),
69
+ page: int = Query(1, ge=1),
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
+
76
+ count_result = await db.execute(
77
+ select(func.count(Vod.id)).where(Vod.is_hidden == False, name_match)
78
+ )
79
+ total = count_result.scalar() or 0
80
+
81
+ result = await db.execute(
82
+ select(Vod)
83
+ .where(Vod.is_hidden == False, name_match)
84
+ .order_by(Vod.updated_at.desc())
85
+ .offset((page - 1) * page_size)
86
+ .limit(page_size)
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)
117
+ async def recommended_vods(
118
+ page: int = Query(1, ge=1),
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
+
129
+ result = await db.execute(
130
+ select(Vod)
131
+ .where(Vod.is_hidden == False, Vod.is_recommended == True)
132
+ .order_by(Vod.score.desc().nullslast(), Vod.updated_at.desc())
133
+ .offset((page - 1) * page_size)
134
+ .limit(page_size)
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)
165
+ async def latest_vods(
166
+ hours: int = Query(72, ge=1),
167
+ page: int = Query(1, ge=1),
168
+ page_size: int = Query(24, ge=1, le=100),
169
+ db: AsyncSession = Depends(get_db),
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)
176
+ )
177
+ total = count_result.scalar() or 0
178
+
179
+ result = await db.execute(
180
+ select(Vod)
181
+ .where(Vod.is_hidden == False, Vod.updated_at >= cutoff)
182
+ .order_by(Vod.updated_at.desc())
183
+ .offset((page - 1) * page_size)
184
+ .limit(page_size)
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
+
239
+ episodes = _parse_play_url(vs.play_url)
240
+ play_from_label = vs.play_from
241
+ if site.play_from_m3u8 and vs.play_from == site.play_from_m3u8:
242
+ play_from_label = f"{site.name}-M3U8"
243
+ elif site.play_from_yun and vs.play_from == site.play_from_yun:
244
+ play_from_label = f"{site.name}-云播"
245
+
246
+ parse_url = site.parse_url if site.play_from_m3u8 and vs.play_from == site.play_from_m3u8 else None
247
+
248
+ sources.append(
249
+ VodPlaySource(
250
+ source_id=site.id,
251
+ source_name=site.name,
252
+ play_from=vs.play_from,
253
+ play_from_label=play_from_label,
254
+ episodes=[
255
+ EpisodeItem(
256
+ name=ep["name"],
257
+ url=ep["url"],
258
+ parse_url=parse_url,
259
+ )
260
+ for ep in episodes
261
+ ],
262
+ ).model_dump()
263
+ )
264
+
265
+ source_count = len(vod_sources)
266
+
267
+ detail = VodUserDetail(
268
+ id=vod.id,
269
+ name=vod.name,
270
+ sub_name=vod.sub_name,
271
+ cover=vod.cover,
272
+ category_id=vod.category_id,
273
+ category_name=cat_name,
274
+ score=vod.score,
275
+ year=vod.year,
276
+ area=vod.area,
277
+ actor=vod.actor,
278
+ director=vod.director,
279
+ lang=vod.lang,
280
+ duration=vod.duration,
281
+ is_end=vod.is_end,
282
+ remarks=vod.remarks,
283
+ blurb=vod.blurb,
284
+ content=vod.content,
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]:
308
+ episodes = []
309
+ if not play_url:
310
+ return episodes
311
 
312
+ parts = play_url.split("#")
313
+ for part in parts:
314
+ part = part.strip()
315
+ if not part:
316
+ continue
317
+ if "$" in part:
318
+ name, url = part.split("$", 1)
319
+ episodes.append({"name": name.strip(), "url": url.strip()})
320
+ else:
321
+ episodes.append({"name": f"第{len(episodes)+1}集", "url": part.strip()})
322
 
323
+ return episodes
 
 
app/schemas/admin/auth.py CHANGED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class LoginRequest(BaseModel):
5
+ username: str
6
+ password: str
7
+
8
+
9
+ class LoginResponse(BaseModel):
10
+ accessToken: str
11
+ expires_in: int
12
+
13
+
14
+ class UserInfoResponse(BaseModel):
15
+ userId: str
16
+ username: str
17
+ realName: str | None
18
+ roles: list[str]
19
+ avatar: str | None
20
+ desc: str = ""
21
+ homePath: str = "/source"
app/schemas/common.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class ApiResponse(BaseModel):
5
+ code: int = 0
6
+ msg: str = "success"
7
+ data: object = None
8
+
9
+ @classmethod
10
+ def ok(cls, data=None, msg: str = "success"):
11
+ return cls(code=0, msg=msg, data=data)
12
+
13
+ @classmethod
14
+ def fail(cls, code: int, msg: str, data=None):
15
+ return cls(code=code, msg=msg, data=data)
16
+
17
+
18
+ class PaginatedData(BaseModel):
19
+ list: list
20
+ total: int
21
+ page: int
22
+ page_size: int
app/schemas/user/auth.py CHANGED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+
3
+ from pydantic import BaseModel, Field
4
+
5
+
6
+ class UserRegisterRequest(BaseModel):
7
+ username: str = Field(..., min_length=3, max_length=30)
8
+ password: str = Field(..., min_length=6, max_length=50)
9
+ email: str | None = None
10
+ nickname: str | None = None
11
+
12
+
13
+ class UserLoginRequest(BaseModel):
14
+ username: str
15
+ password: str
16
+
17
+
18
+ class UserLoginResponse(BaseModel):
19
+ accessToken: str
20
+ expires_in: int = 1440
21
+
22
+
23
+ class UserProfileResponse(BaseModel):
24
+ id: int
25
+ username: str | None
26
+ email: str | None
27
+ nickname: str | None
28
+ avatar: str | None
29
+ created_at: datetime
app/schemas/user/category.py CHANGED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class CategoryUserNode(BaseModel):
5
+ id: int
6
+ name: str
7
+ children: list["CategoryUserNode"] | None = None
app/schemas/user/favorite.py CHANGED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+
3
+ from pydantic import BaseModel
4
+
5
+
6
+ class FavoriteItem(BaseModel):
7
+ id: int
8
+ vod_id: int
9
+ vod_name: str
10
+ vod_cover: str | None = None
11
+ vod_remarks: str | None = None
12
+ created_at: datetime
13
+
14
+
15
+ class AddFavoriteRequest(BaseModel):
16
+ vod_id: int
app/schemas/user/history.py CHANGED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+
3
+ from pydantic import BaseModel
4
+
5
+
6
+ class HistoryItem(BaseModel):
7
+ id: int
8
+ vod_id: int
9
+ vod_name: str
10
+ vod_cover: str | None = None
11
+ source_id: int
12
+ episode: str | None = None
13
+ play_url: str
14
+ progress: int = 0
15
+ duration: int = 0
16
+ updated_at: datetime
17
+
18
+
19
+ class RecordHistoryRequest(BaseModel):
20
+ vod_id: int
21
+ source_id: int
22
+ episode: str | None = None
23
+ play_url: str
24
+ progress: int = 0
25
+ duration: int = 0
app/schemas/user/vod.py CHANGED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+
3
+ from pydantic import BaseModel
4
+
5
+
6
+ class EpisodeItem(BaseModel):
7
+ name: str
8
+ url: str
9
+ parse_url: str | None = None
10
+
11
+
12
+ class VodPlaySource(BaseModel):
13
+ source_id: int
14
+ source_name: str
15
+ play_from: str
16
+ play_from_label: str
17
+ episodes: list[EpisodeItem]
18
+
19
+
20
+ class VodUserItem(BaseModel):
21
+ id: int
22
+ name: str
23
+ cover: str | None = None
24
+ category_id: int
25
+ category_name: str | None = None
26
+ score: float | None = None
27
+ year: str | None = None
28
+ area: str | None = None
29
+ is_end: bool = False
30
+ remarks: str | None = None
31
+ source_count: int = 0
32
+ updated_at: datetime
33
+
34
+
35
+ class VodUserDetail(VodUserItem):
36
+ sub_name: str | None = None
37
+ actor: str | None = None
38
+ director: str | None = None
39
+ lang: str | None = None
40
+ duration: str | None = None
41
+ blurb: str | None = None
42
+ content: str | None = None
43
+ sources: list[VodPlaySource] = []
app/services/auth_admin.py CHANGED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy import select
2
+ from sqlalchemy.ext.asyncio import AsyncSession
3
+
4
+ from app.models.admin import Admin
5
+ from app.models.role import Role, AdminRole
6
+ from app.models.permission import Permission, RolePermission
7
+ from app.utils.auth import hash_password, verify_password, create_access_token
8
+
9
+
10
+ async def authenticate_admin(db: AsyncSession, username: str, password: str) -> Admin | None:
11
+ result = await db.execute(select(Admin).where(Admin.username == username))
12
+ admin = result.scalar_one_or_none()
13
+ if not admin or not admin.is_active or not verify_password(password, admin.password_hash):
14
+ return None
15
+ return admin
16
+
17
+
18
+ async def get_admin_roles(db: AsyncSession, admin_id: int) -> list[str]:
19
+ result = await db.execute(
20
+ select(Role.code)
21
+ .join(AdminRole, AdminRole.role_id == Role.id)
22
+ .where(AdminRole.admin_id == admin_id, Role.status == 1)
23
+ )
24
+ return [r[0] for r in result.all()]
25
+
26
+
27
+ async def get_admin_permissions(db: AsyncSession, admin_id: int) -> list[str]:
28
+ result = await db.execute(
29
+ select(Permission.code)
30
+ .join(RolePermission, RolePermission.permission_id == Permission.id)
31
+ .join(AdminRole, AdminRole.role_id == RolePermission.role_id)
32
+ .where(AdminRole.admin_id == admin_id, Permission.status == 1)
33
+ .distinct()
34
+ )
35
+ return [p[0] for p in result.all()]
36
+
37
+
38
+ async def get_menu_tree(db: AsyncSession, admin_id: int) -> list[dict]:
39
+ perm_codes = await get_admin_permissions(db, admin_id)
40
+ roles = await get_admin_roles(db, admin_id)
41
+
42
+ is_super = "super_admin" in roles
43
+
44
+ result = await db.execute(
45
+ select(Permission)
46
+ .where(Permission.type == "menu", Permission.status == 1)
47
+ .order_by(Permission.sort_order)
48
+ )
49
+ all_menus = result.scalars().all()
50
+
51
+ menus = []
52
+ for m in all_menus:
53
+ if not is_super:
54
+ menu_page_codes = [
55
+ c.code for c in await _get_menu_pages(db, m.id)
56
+ if c.code in perm_codes
57
+ ]
58
+ if not menu_page_codes:
59
+ continue
60
+
61
+ menus.append({
62
+ "name": code_to_route_name(m.code),
63
+ "path": m.path,
64
+ "component": "BasicLayout",
65
+ "redirect": m.path,
66
+ "meta": {
67
+ "title": m.name,
68
+ "icon": m.icon,
69
+ "order": m.sort_order,
70
+ },
71
+ "children": [
72
+ {
73
+ "name": code_to_route_name(m.code) + "Index",
74
+ "path": m.path,
75
+ "component": m.component,
76
+ "meta": {
77
+ "title": m.name,
78
+ "icon": m.icon,
79
+ "hideInMenu": True,
80
+ "keepAlive": False,
81
+ "menuVisibleWithForbidden": True,
82
+ },
83
+ }
84
+ ],
85
+ })
86
+
87
+ return menus
88
+
89
+
90
+ async def get_permission_tree(db: AsyncSession) -> list[dict]:
91
+ result = await db.execute(
92
+ select(Permission).order_by(Permission.sort_order)
93
+ )
94
+ all_perms = result.scalars().all()
95
+
96
+ perm_map: dict[int, dict] = {}
97
+ roots = []
98
+ for p in all_perms:
99
+ node = build_perm_node(p)
100
+ perm_map[p.id] = node
101
+ for p in all_perms:
102
+ if p.parent_id and p.parent_id in perm_map:
103
+ if "children" not in perm_map[p.parent_id]:
104
+ perm_map[p.parent_id]["children"] = []
105
+ perm_map[p.parent_id]["children"].append(perm_map[p.id])
106
+ elif not p.parent_id:
107
+ roots.append(perm_map[p.id])
108
+ return roots
109
+
110
+
111
+ async def _get_menu_pages(db: AsyncSession, menu_id: int) -> list[Permission]:
112
+ result = await db.execute(
113
+ select(Permission)
114
+ .where(Permission.parent_id == menu_id, Permission.type == "page", Permission.status == 1)
115
+ )
116
+ return list(result.scalars().all())
117
+
118
+
119
+ def build_menu_node(p: Permission) -> dict:
120
+ return {
121
+ "name": code_to_route_name(p.code),
122
+ "path": p.path or "",
123
+ "component": p.component,
124
+ "redirect": p.redirect,
125
+ "meta": {
126
+ "title": p.name,
127
+ "icon": p.icon,
128
+ "order": p.sort_order,
129
+ "hideInMenu": False,
130
+ "keepAlive": False,
131
+ },
132
+ }
133
+
134
+
135
+ def build_perm_node(p: Permission) -> dict:
136
+ return {
137
+ "id": p.id,
138
+ "code": p.code,
139
+ "name": p.name,
140
+ "type": p.type,
141
+ }
142
+
143
+
144
+ def code_to_route_name(code: str) -> str:
145
+ parts = code.replace(":", "_").split("_")
146
+ return "".join(p.capitalize() for p in parts)
app/services/collector.py CHANGED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ import time
4
+ from datetime import datetime, timedelta, timezone
5
+
6
+ import httpx
7
+ from sqlalchemy import select, update
8
+ from sqlalchemy.ext.asyncio import AsyncSession
9
+
10
+ from app.database import async_session
11
+ from app.models.category import CategoryMapping
12
+ from app.models.source_site import SourceSite
13
+ from app.models.sync_log import SyncLog
14
+ from app.models.vod import Vod
15
+ from app.models.vod_source import VodSource
16
+
17
+ logger = logging.getLogger("collector")
18
+
19
+ SYNC_RANGES = {
20
+ "all": None,
21
+ "monthly": 720,
22
+ "weekly": 168,
23
+ "daily": 24,
24
+ }
25
+
26
+
27
+ class Collector:
28
+ def __init__(self):
29
+ self._running = False
30
+
31
+ @property
32
+ def is_running(self) -> bool:
33
+ return self._running
34
+
35
+ async def sync_source(
36
+ self,
37
+ source: SourceSite,
38
+ range_type: str = "daily",
39
+ db: AsyncSession | None = None,
40
+ ) -> dict:
41
+ hours = SYNC_RANGES.get(range_type, 24)
42
+ result = {
43
+ "source_id": source.id,
44
+ "source_name": source.name,
45
+ "status": "running",
46
+ "total_fetched": 0,
47
+ "new_vods": 0,
48
+ "updated_vods": 0,
49
+ "new_sources": 0,
50
+ "updated_sources": 0,
51
+ "skipped_no_mapping": 0,
52
+ "error": None,
53
+ }
54
+
55
+ close_db = False
56
+ if db is None:
57
+ db = async_session()
58
+ close_db = True
59
+
60
+ try:
61
+ mappings = await self._get_mappings(db, source.id)
62
+ if not mappings:
63
+ result["status"] = "skipped"
64
+ result["error"] = "No category mappings configured"
65
+ return result
66
+
67
+ total_fetched = 0
68
+ new_vods = 0
69
+ updated_vods = 0
70
+ new_sources = 0
71
+ updated_sources = 0
72
+ skipped = 0
73
+
74
+ page = 1
75
+ while True:
76
+ vods_data = await self._fetch_page(source, hours, page)
77
+ if not vods_data:
78
+ break
79
+
80
+ total_fetched += len(vods_data)
81
+ for vod_data in vods_data:
82
+ source_type_id = vod_data.get("type_id")
83
+ cat_mapping = mappings.get(source_type_id)
84
+ if not cat_mapping:
85
+ skipped += 1
86
+ continue
87
+
88
+ unified_cat_id = cat_mapping["category_id"]
89
+
90
+ n, u = await self._process_vod(db, vod_data, source, unified_cat_id)
91
+ new_vods += n
92
+ updated_vods += u
93
+
94
+ ns, us = await self._process_play_urls(db, vod_data, source)
95
+ new_sources += ns
96
+ updated_sources += us
97
+
98
+ page += 1
99
+ pagecount = vods_data[0].get("_pagecount", 1) if vods_data else 1
100
+ if page > pagecount or total_fetched >= 5000:
101
+ break
102
+ await asyncio.sleep(0.5)
103
+
104
+ result["total_fetched"] = total_fetched
105
+ result["new_vods"] = new_vods
106
+ result["updated_vods"] = updated_vods
107
+ result["new_sources"] = new_sources
108
+ result["updated_sources"] = updated_sources
109
+ result["skipped_no_mapping"] = skipped
110
+ result["status"] = "success"
111
+
112
+ await db.execute(
113
+ update(SourceSite)
114
+ .where(SourceSite.id == source.id)
115
+ .values(
116
+ last_sync_at=datetime.now(timezone.utc),
117
+ last_sync_status="success",
118
+ last_sync_count=new_vods,
119
+ )
120
+ )
121
+ await db.commit()
122
+
123
+ except Exception as e:
124
+ logger.exception(f"Sync failed for {source.name}: {e}")
125
+ result["status"] = "failed"
126
+ result["error"] = str(e)
127
+ try:
128
+ await db.execute(
129
+ update(SourceSite)
130
+ .where(SourceSite.id == source.id)
131
+ .values(last_sync_status="failed")
132
+ )
133
+ await db.commit()
134
+ except Exception:
135
+ await db.rollback()
136
+ finally:
137
+ if close_db:
138
+ await db.close()
139
+
140
+ return result
141
+
142
+ async def sync_all(self, range_type: str = "daily") -> list[dict]:
143
+ if self._running:
144
+ raise RuntimeError("Sync already running")
145
+
146
+ self._running = True
147
+ results = []
148
+
149
+ try:
150
+ async with async_session() as db:
151
+ result = await db.execute(
152
+ select(SourceSite).where(SourceSite.is_active == True).order_by(SourceSite.sort_order)
153
+ )
154
+ sources = result.scalars().all()
155
+
156
+ for source in sources:
157
+ log = SyncLog(
158
+ source_id=source.id,
159
+ range_type=range_type,
160
+ status="running",
161
+ started_at=datetime.now(timezone.utc),
162
+ )
163
+ async with async_session() as db:
164
+ db.add(log)
165
+ await db.commit()
166
+ log_id = log.id
167
+
168
+ r = await self.sync_source(source, range_type)
169
+
170
+ async with async_session() as db:
171
+ await db.execute(
172
+ update(SyncLog)
173
+ .where(SyncLog.id == log_id)
174
+ .values(
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
+ )
183
+ await db.commit()
184
+
185
+ results.append(r)
186
+ await asyncio.sleep(1)
187
+
188
+ finally:
189
+ self._running = False
190
+
191
+ return results
192
+
193
+ async def _get_mappings(self, db: AsyncSession, source_id: int) -> dict:
194
+ result = await db.execute(
195
+ select(CategoryMapping).where(CategoryMapping.source_id == source_id)
196
+ )
197
+ mappings = result.scalars().all()
198
+ return {m.source_type_id: {"category_id": m.category_id, "name": m.source_type_name} for m in mappings}
199
+
200
+ async def _fetch_page(self, source: SourceSite, hours: int | None, page: int) -> list[dict] | None:
201
+ params = {"ac": "detail", "pg": str(page)}
202
+ if hours:
203
+ params["h"] = str(hours)
204
+
205
+ url = source.base_url.rstrip("/")
206
+ try:
207
+ async with httpx.AsyncClient(timeout=30, follow_redirects=True) as client:
208
+ resp = await client.get(url, params=params)
209
+ data = resp.json()
210
+ except Exception as e:
211
+ logger.error(f"Fetch failed for {source.name} page {page}: {e}")
212
+ return None
213
+
214
+ vod_list = data.get("list", [])
215
+ if not vod_list:
216
+ return None
217
+
218
+ pagecount = data.get("pagecount", 1)
219
+ for v in vod_list:
220
+ v["_pagecount"] = pagecount
221
+
222
+ return vod_list
223
+
224
+ async def _process_vod(
225
+ self, db: AsyncSession, vod_data: dict, source: SourceSite, category_id: int
226
+ ) -> tuple[int, int]:
227
+ source_vod_id = vod_data.get("vod_id")
228
+ name = vod_data.get("vod_name", "")
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
253
+ vod.actor = vod_data.get("vod_actor") or vod.actor
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,
272
+ sub_name=vod_data.get("vod_sub") or vod_data.get("vod_en"),
273
+ en_name=vod_data.get("vod_en"),
274
+ category_id=category_id,
275
+ cover=vod_data.get("vod_pic"),
276
+ actor=vod_data.get("vod_actor"),
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,
284
+ blurb=vod_data.get("vod_blurb"),
285
+ content=vod_data.get("vod_content"),
286
+ remarks=vod_data.get("vod_remarks"),
287
+ )
288
+ db.add(vod)
289
+ await db.flush()
290
+ return 1, 0
291
+
292
+ async def _process_play_urls(
293
+ self, db: AsyncSession, vod_data: dict, source: SourceSite
294
+ ) -> tuple[int, int]:
295
+ name = vod_data.get("vod_name", "")
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
+
304
+ play_from_raw = vod_data.get("vod_play_from", "")
305
+ play_url_raw = vod_data.get("vod_play_url", "")
306
+
307
+ from_list = [f.strip() for f in play_from_raw.split("$$$") if f.strip()]
308
+ url_list = [u.strip() for u in play_url_raw.split("$$$") if u.strip()]
309
+
310
+ new_count = 0
311
+ update_count = 0
312
+
313
+ for i, play_from in enumerate(from_list):
314
+ play_url = url_list[i] if i < len(url_list) else ""
315
+ source_vod_id = vod_data.get("vod_id")
316
+
317
+ existing = await db.execute(
318
+ select(VodSource).where(
319
+ VodSource.vod_id == vod.id,
320
+ VodSource.source_id == source.id,
321
+ VodSource.play_from == play_from,
322
+ )
323
+ )
324
+ existing_vs = existing.scalar_one_or_none()
325
+
326
+ if existing_vs:
327
+ existing_vs.play_url = play_url
328
+ existing_vs.source_vod_id = source_vod_id
329
+ update_count += 1
330
+ else:
331
+ vs = VodSource(
332
+ vod_id=vod.id,
333
+ source_id=source.id,
334
+ source_vod_id=source_vod_id,
335
+ play_from=play_from,
336
+ play_url=play_url,
337
+ )
338
+ db.add(vs)
339
+ await db.flush()
340
+ new_count += 1
341
+
342
+ return new_count, update_count
343
+
344
+
345
+ collector = Collector()
app/services/scheduler.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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")
9
+
10
+ scheduler = AsyncIOScheduler()
11
+
12
+
13
+ def start_scheduler():
14
+ sync_hour = 1
15
+
16
+ scheduler.add_job(
17
+ collector.sync_all,
18
+ trigger=CronTrigger(hour=sync_hour, minute=0),
19
+ id="sync_daily",
20
+ name="每日增量同步(24h)",
21
+ kwargs={"range_type": "daily"},
22
+ misfire_grace_time=3600,
23
+ )
24
+
25
+ scheduler.add_job(
26
+ collector.sync_all,
27
+ trigger=CronTrigger(day_of_week="mon", hour=sync_hour, minute=30),
28
+ id="sync_weekly",
29
+ name="每周增量同步(168h)",
30
+ kwargs={"range_type": "weekly"},
31
+ misfire_grace_time=7200,
32
+ )
33
+
34
+ scheduler.add_job(
35
+ collector.sync_all,
36
+ trigger=CronTrigger(day=1, hour=sync_hour, minute=45),
37
+ id="sync_monthly",
38
+ name="每月增量同步(720h)",
39
+ kwargs={"range_type": "monthly"},
40
+ misfire_grace_time=14400,
41
+ )
42
+
43
+ scheduler.start()
44
+ logger.info(f"Scheduler started with sync_hour={sync_hour}")
45
+
46
+
47
+ def stop_scheduler():
48
+ if scheduler.running:
49
+ scheduler.shutdown(wait=False)
50
+ logger.info("Scheduler stopped")
app/utils/auth.py CHANGED
@@ -1,19 +1,17 @@
1
  from datetime import datetime, timedelta, timezone
2
 
 
3
  from jose import jwt
4
- from passlib.context import CryptContext
5
 
6
  from app.config import settings
7
 
8
- pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
9
-
10
 
11
  def hash_password(password: str) -> str:
12
- return pwd_context.hash(password)
13
 
14
 
15
  def verify_password(plain_password: str, hashed_password: str) -> bool:
16
- return pwd_context.verify(plain_password, hashed_password)
17
 
18
 
19
  def create_access_token(subject: str, token_type: str = "admin", expires_delta: timedelta | None = None) -> str:
@@ -21,4 +19,4 @@ def create_access_token(subject: str, token_type: str = "admin", expires_delta:
21
  expires_delta = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
22
  expire = datetime.now(timezone.utc) + expires_delta
23
  to_encode = {"sub": subject, "type": token_type, "exp": expire}
24
- return jwt.encode(to_encode, settings.SECRET_KEY, algorithm="HS256")
 
1
  from datetime import datetime, timedelta, timezone
2
 
3
+ import bcrypt
4
  from jose import jwt
 
5
 
6
  from app.config import settings
7
 
 
 
8
 
9
  def hash_password(password: str) -> str:
10
+ return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
11
 
12
 
13
  def verify_password(plain_password: str, hashed_password: str) -> bool:
14
+ return bcrypt.checkpw(plain_password.encode("utf-8"), hashed_password.encode("utf-8"))
15
 
16
 
17
  def create_access_token(subject: str, token_type: str = "admin", expires_delta: timedelta | None = None) -> str:
 
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")
requirements.txt CHANGED
@@ -1,12 +1,13 @@
1
  fastapi==0.115.*
2
  uvicorn[standard]==0.34.*
3
  sqlalchemy[asyncio]==2.0.*
4
- asyncpg==0.30.*
 
5
  alembic==1.14.*
6
  pydantic==2.10.*
7
  pydantic-settings==2.7.*
8
  python-jose[cryptography]==3.3.*
9
- passlib[bcrypt]==1.7.*
10
  httpx==0.28.*
11
  apscheduler==3.11.*
12
  python-multipart==0.0.*
 
1
  fastapi==0.115.*
2
  uvicorn[standard]==0.34.*
3
  sqlalchemy[asyncio]==2.0.*
4
+ aiosqlite==0.20.*
5
+ 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.*
scripts/create_superadmin.py CHANGED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
6
+
7
+ from sqlalchemy import select
8
+
9
+ from app.database import async_session
10
+ from app.models.admin import Admin
11
+ from app.models.role import Role, AdminRole
12
+ from app.utils.auth import hash_password
13
+
14
+
15
+ async def create_superadmin():
16
+ username = "hanbin"
17
+ password = "Han147258!"
18
+ async with async_session() as db:
19
+ existing = await db.execute(select(Admin).where(Admin.username == username))
20
+ if existing.scalar_one_or_none():
21
+ print(f"Admin '{username}' already exists, skipping.")
22
+ return
23
+
24
+ super_admin_role = await db.execute(
25
+ select(Role).where(Role.code == "super_admin")
26
+ )
27
+ role = super_admin_role.scalar_one_or_none()
28
+ if not role:
29
+ print("super_admin role not found. Run seed_roles.py first.")
30
+ return
31
+
32
+ admin = Admin(
33
+ username=username,
34
+ password_hash=hash_password(password),
35
+ nickname="韩彬",
36
+ is_active=True,
37
+ )
38
+ db.add(admin)
39
+ await db.flush()
40
+
41
+ db.add(AdminRole(admin_id=admin.id, role_id=role.id))
42
+ await db.commit()
43
+ print(f"Super admin '{username}' created with password '{password}'.")
44
+
45
+
46
+ if __name__ == "__main__":
47
+ asyncio.run(create_superadmin())
scripts/init_db.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import importlib
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
7
+
8
+ from app.database import engine, Base, async_session
9
+
10
+
11
+ async def init():
12
+ import app.models
13
+ from scripts.seed_categories_sources import seed as seed_categories
14
+ from scripts.seed_permissions import seed as seed_permissions
15
+ from scripts.seed_roles import seed as seed_roles
16
+ from scripts.create_superadmin import create_superadmin
17
+
18
+ async with engine.begin() as conn:
19
+ await conn.run_sync(Base.metadata.create_all)
20
+ print("Tables created.")
21
+
22
+ await seed_categories()
23
+ await seed_permissions()
24
+ await seed_roles()
25
+ await create_superadmin()
26
+ print("Database initialization complete!")
27
+
28
+
29
+ if __name__ == "__main__":
30
+ asyncio.run(init())
scripts/seed_categories_sources.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
6
+
7
+ from sqlalchemy import select
8
+
9
+ from app.database import async_session
10
+ from app.models.category import Category, CategoryMapping
11
+ from app.models.source_site import SourceSite
12
+
13
+ CATEGORIES = [
14
+ ("电影", None, 1),
15
+ ("动作片", "电影", 10),
16
+ ("爱情片", "电影", 11),
17
+ ("喜剧片", "电影", 12),
18
+ ("科幻片", "电影", 13),
19
+ ("恐怖片", "电影", 14),
20
+ ("剧情片", "电影", 15),
21
+ ("战争片", "电影", 16),
22
+ ("纪录片", "电影", 17),
23
+ ("灾难片", "电影", 18),
24
+ ("悬疑片", "电影", 19),
25
+ ("犯罪片", "电影", 20),
26
+ ("奇幻片", "电影", 21),
27
+ ("动画电影", "电影", 22),
28
+ ("4K电影", "电影", 23),
29
+
30
+ ("连续剧", None, 2),
31
+ ("国产剧", "连续剧", 30),
32
+ ("欧美剧", "连续剧", 31),
33
+ ("韩剧", "连续剧", 32),
34
+ ("日剧", "连续剧", 33),
35
+ ("港剧", "连续剧", 34),
36
+ ("台剧", "连续剧", 35),
37
+ ("泰剧", "连续剧", 36),
38
+ ("海外剧", "连续剧", 37),
39
+ ("短剧", "连续剧", 38),
40
+
41
+ ("综艺", None, 3),
42
+ ("大陆综艺", "综艺", 40),
43
+ ("日韩综艺", "综艺", 41),
44
+ ("港台综艺", "综艺", 42),
45
+ ("欧美综艺", "综艺", 43),
46
+ ("演唱会", "综艺", 44),
47
+
48
+ ("动漫", None, 4),
49
+ ("国产动漫", "动漫", 50),
50
+ ("日本动漫", "动漫", 51),
51
+ ("欧美动漫", "动漫", 52),
52
+ ("海外动漫", "动漫", 53),
53
+ ("有声动漫", "动漫", 54),
54
+ ]
55
+
56
+ SOURCE_SITES = [
57
+ ("极速资源", "jszy", "https://jszyapi.com/api.php/provide/vod/", "https://jszy333.com/", "jsm3u8", "jsyun", None, True, 1),
58
+ ("豆瓣资源", "dbzy", "https://dbzy.tv/api.php/provide/vod/", "https://dbzy.tv", "dbm3u8", "dbyun", None, True, 2),
59
+ ("索尼资源", "snzy", "https://suoniapi.com/api.php/provide/vod/", "https://suonizy.net/", "snm3u8", None, "https://dxfbk.com/?url=", True, 3),
60
+ ("OK资源", "okzy", "https://okzyw.cc/api.php/provide/vod/", "https://okzyw.cc/", "okm3u8", None, None, True, 4),
61
+ ("红牛资源", "hnzy", "https://www.hongniuzy2.com/api.php/provide/vod/", "https://www.hongniuzy.com/", "hnm3u8", "hnyun", "https://www.hnjiexi.com/m3u8/?url=", True, 5),
62
+ ("金鹰资源", "jyzy", "https://jyzyapi.com/provide/vod/", "https://jinyingzy.com/", "jinyingm3u8", "jinyingyun", "https://hd.iapijy.com/play?url=", True, 6),
63
+ ("快车资源", "kczy", "http://kuaichezy.com/api.php/provide/vod/", "http://kuaichezy.com/", "kcm3u8", None, None, True, 7),
64
+ ("CK资源", "ckzy", "http://www.ckzy1.com/api.php/provide/vod/", "http://www.ckzy1.com/", "ckm3u8", None, None, False, 8),
65
+ ("新浪资源", "xlzy", "https://www.xinlangzy.com/api.php/provide/vod/", "https://www.xinlangzy.com/", "xlm3u8", "xlyun", None, False, 9),
66
+ ]
67
+
68
+ CATEGORY_MAPPINGS = {
69
+ "jszy": {
70
+ 1: "连续剧", 2: "电影", 3: "欧美剧", 4: "港剧", 5: "韩剧", 6: "日剧",
71
+ 7: "泰剧", 8: "剧情片", 9: "动作片", 10: "爱情片", 11: "喜剧片",
72
+ 12: "科幻片", 13: "恐怖片", 14: "剧情片", 15: "战争片", 16: "纪录片",
73
+ 17: "动漫", 20: "国产剧", 23: "动画电影", 24: "国产动漫", 25: "日本动漫",
74
+ 26: "欧美动漫", 27: "综艺", 28: "台剧", 29: "演唱会",
75
+ 30: "大陆综艺", 31: "日韩综艺", 32: "港台综艺", 33: "欧美综艺",
76
+ 34: "灾难片", 35: "悬疑片", 36: "犯罪片", 37: "奇幻片", 38: "短剧",
77
+ },
78
+ "jyzy": {
79
+ 1: "连续剧", 2: "电影", 3: "欧美剧", 4: "港剧", 5: "韩剧", 6: "日剧",
80
+ 7: "泰剧", 8: "剧情片", 9: "动作片", 10: "爱情片", 11: "喜剧片",
81
+ 12: "科幻片", 13: "恐怖片", 14: "剧情片", 15: "战争片", 16: "纪录片",
82
+ 17: "动漫", 20: "国产剧", 23: "动画电影", 24: "国产动漫", 25: "日本动漫",
83
+ 26: "欧美动漫", 27: "综艺", 28: "台剧", 29: "演唱会",
84
+ 30: "大陆综艺", 31: "日韩综艺", 32: "港台综艺", 33: "欧美综艺",
85
+ 34: "灾难片", 35: "悬疑片", 36: "犯罪片", 37: "奇幻片", 38: "短剧",
86
+ },
87
+ "dbzy": {
88
+ 1: "电影", 2: "连续剧", 3: "综艺", 4: "动漫", 5: "纪录片",
89
+ 6: "动作片", 7: "爱情片", 8: "喜剧片", 9: "科幻片", 10: "恐怖片",
90
+ 11: "剧情片", 12: "战争片", 13: "国产剧", 14: "港剧", 15: "欧美剧",
91
+ 16: "韩剧", 20: "动画电影", 21: "泰剧", 22: "日剧", 23: "台剧",
92
+ 24: "海外剧", 25: "大陆综艺", 26: "日韩综艺", 27: "港台综艺",
93
+ 28: "欧美综艺", 29: "演唱会", 30: "国产动漫", 31: "日本动漫",
94
+ 32: "欧美动漫", 33: "海外动漫", 34: "剧情片", 35: "综艺",
95
+ 36: "演唱会", 37: "短剧",
96
+ },
97
+ "snzy": {
98
+ 1: "电影", 2: "连续剧", 3: "综艺", 4: "动漫", 6: "动作片",
99
+ 7: "喜剧片", 8: "爱情片", 9: "科幻片", 10: "恐怖片", 11: "剧情片",
100
+ 12: "战争片", 13: "国产剧", 14: "欧美剧", 15: "韩剧", 16: "日剧",
101
+ 17: "港剧", 18: "台剧", 19: "泰剧", 20: "纪录片", 23: "海外剧",
102
+ 25: "大陆综艺", 26: "日韩综艺", 27: "港台综艺", 28: "欧美综艺",
103
+ 29: "国产动漫", 30: "日本动漫", 31: "欧美动漫", 39: "动画电影",
104
+ 44: "港台综艺", 45: "海外动漫", 47: "演唱会",
105
+ },
106
+ "okzy": {
107
+ 1: "电影", 2: "连续剧", 3: "综艺", 4: "动漫", 6: "动作片",
108
+ 7: "喜剧片", 8: "爱情片", 9: "科幻片", 10: "恐怖片", 11: "剧情片",
109
+ 12: "战争片", 13: "国产剧", 14: "欧美剧", 15: "韩剧", 16: "日剧",
110
+ 17: "港剧", 18: "台剧", 19: "泰剧", 20: "纪录片", 23: "海外剧",
111
+ 25: "大陆综艺", 26: "日韩综艺", 27: "港台综艺", 28: "欧美综艺",
112
+ 29: "国产动漫", 30: "日本动漫", 31: "欧美动漫", 39: "动画电影",
113
+ 44: "港台综艺", 45: "海外动漫", 47: "演唱会",
114
+ },
115
+ "hnzy": {
116
+ 1: "电影", 2: "连续剧", 3: "综艺", 4: "动漫", 5: "动作片",
117
+ 6: "喜剧片", 7: "爱情片", 8: "科幻片", 9: "恐怖片", 10: "剧情片",
118
+ 11: "战争片", 12: "国产剧", 13: "港剧", 14: "日剧", 15: "欧美剧",
119
+ 16: "台剧", 17: "泰剧", 18: "韩剧", 19: "纪录片", 20: "动画电影",
120
+ 29: "演唱会", 30: "短剧", 36: "国产动漫", 37: "日本动漫", 38: "欧美动漫",
121
+ },
122
+ "kczy": {
123
+ 1: "电影", 2: "连续剧", 3: "综艺", 4: "动漫", 6: "动作片",
124
+ 7: "喜剧片", 8: "爱情片", 9: "科幻片", 10: "恐怖片", 11: "剧情片",
125
+ 12: "战争片", 13: "国产剧", 14: "欧美剧", 15: "韩剧", 16: "日剧",
126
+ 17: "港剧", 18: "台剧", 19: "泰剧", 20: "纪录片", 23: "海外剧",
127
+ 25: "大陆综艺", 26: "日韩综艺", 27: "港台综艺", 28: "欧美综艺",
128
+ 29: "国产动漫", 30: "日本动漫", 31: "欧美动漫", 39: "动画电影",
129
+ 44: "港台综艺", 45: "海外动漫", 47: "演唱会",
130
+ },
131
+ "ckzy": {
132
+ 20: "剧情片", 21: "综艺",
133
+ },
134
+ }
135
+
136
+ CATEGORY_NAME_TO_ID = {
137
+ "电影": None, "动作片": None, "爱情片": None, "喜剧片": None,
138
+ "科幻片": None, "恐怖片": None, "剧情片": None, "战争片": None,
139
+ "纪录片": None, "灾难片": None, "悬疑片": None, "犯罪片": None,
140
+ "奇幻片": None, "动画电影": None, "4K电影": None,
141
+ "连续剧": None, "国产剧": None, "欧美剧": None, "韩剧": None,
142
+ "日剧": None, "港剧": None, "台剧": None, "泰剧": None,
143
+ "海外剧": None, "短剧": None,
144
+ "综艺": None, "大陆综艺": None, "日韩综艺": None,
145
+ "港台综艺": None, "欧美综艺": None, "演唱会": None,
146
+ "动漫": None, "国产动漫": None, "日本动漫": None,
147
+ "欧美动漫": None, "海外动漫": None, "有声动漫": None,
148
+ }
149
+
150
+
151
+ async def seed():
152
+ async with async_session() as db:
153
+ existing = await db.execute(select(Category))
154
+ if existing.scalars().first():
155
+ print("Categories already seeded, skipping.")
156
+ return
157
+
158
+ for name, parent_name, order in CATEGORIES:
159
+ c = Category(name=name, sort_order=order)
160
+ db.add(c)
161
+ await db.flush()
162
+ CATEGORY_NAME_TO_ID[name] = c.id
163
+ if parent_name:
164
+ c.parent_id = CATEGORY_NAME_TO_ID[parent_name]
165
+
166
+ await db.flush()
167
+
168
+ site_id_map = {}
169
+ for name, code, base_url, site_url, m3u8, yun, parse_url, active, order in SOURCE_SITES:
170
+ s = SourceSite(
171
+ name=name, code=code, base_url=base_url, site_url=site_url,
172
+ play_from_m3u8=m3u8, play_from_yun=yun, parse_url=parse_url,
173
+ is_active=active, sort_order=order,
174
+ )
175
+ db.add(s)
176
+ await db.flush()
177
+ site_id_map[code] = s.id
178
+
179
+ mapping_count = 0
180
+ for site_code, mappings in CATEGORY_MAPPINGS.items():
181
+ if site_code not in site_id_map:
182
+ continue
183
+ source_id = site_id_map[site_code]
184
+ for source_type_id, cat_name in mappings.items():
185
+ cat_id = CATEGORY_NAME_TO_ID.get(cat_name)
186
+ if cat_id is None:
187
+ print(f" WARNING: no unified category for '{cat_name}' from {site_code}:{source_type_id}")
188
+ continue
189
+ m = CategoryMapping(
190
+ category_id=cat_id,
191
+ source_id=source_id,
192
+ source_type_id=source_type_id,
193
+ source_type_name=cat_name,
194
+ )
195
+ db.add(m)
196
+ mapping_count += 1
197
+
198
+ await db.commit()
199
+ print(f"Seeded {len(CATEGORIES)} categories, {len(SOURCE_SITES)} source sites, {mapping_count} category mappings.")
200
+
201
+
202
+ if __name__ == "__main__":
203
+ asyncio.run(seed())
scripts/seed_permissions.py CHANGED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
6
+
7
+ from sqlalchemy import select
8
+
9
+ from app.database import async_session
10
+ from app.models.permission import Permission
11
+
12
+ PERMISSIONS = [
13
+ ("source:menu", "资源站管理", "menu", None, "/source", "/source/index", None, "lucide:database", 1),
14
+ ("source:list", "查看", "page", None, None, None, None, None, 2),
15
+ ("source:detail", "详情", "page", None, None, None, None, None, 3),
16
+ ("source:create", "新增", "page", None, None, None, None, None, 4),
17
+ ("source:update", "编辑", "page", None, None, None, None, None, 5),
18
+ ("source:btn:sync", "同步", "btn", None, None, None, None, None, 6),
19
+ ("source:btn:enable", "启用/禁用", "btn", None, None, None, None, None, 7),
20
+ ("source:btn:delete", "删除", "btn", None, None, None, None, None, 8),
21
+ ("source:btn:test", "测试连通", "btn", None, None, None, None, None, 9),
22
+
23
+ ("vod:menu", "影片管理", "menu", None, "/vod", "/vod/index", None, "lucide:film", 10),
24
+ ("vod:list", "查看", "page", None, None, None, None, None, 11),
25
+ ("vod:detail", "详情", "page", None, None, None, None, None, 12),
26
+ ("vod:create", "新增", "page", None, None, None, None, None, 13),
27
+ ("vod:update", "编辑", "page", None, None, None, None, None, 14),
28
+ ("vod:btn:hide", "隐藏", "btn", None, None, None, None, None, 15),
29
+ ("vod:btn:recommend", "推荐", "btn", None, None, None, None, None, 16),
30
+ ("vod:btn:delete", "删除", "btn", None, None, None, None, None, 17),
31
+ ("vod:btn:audit", "审核", "btn", None, None, None, None, None, 18),
32
+
33
+ ("category:menu", "分类管理", "menu", None, "/category", "/category/index", None, "lucide:tags", 19),
34
+ ("category:list", "查看", "page", None, None, None, None, None, 20),
35
+ ("category:update", "编辑", "page", None, None, None, None, None, 21),
36
+ ("category:btn:map", "映射管理", "btn", None, None, None, None, None, 22),
37
+
38
+ ("user:menu", "用户管理", "menu", None, "/user", "/user/index", None, "lucide:users", 23),
39
+ ("user:list", "查看", "page", None, None, None, None, None, 24),
40
+ ("user:detail", "详情", "page", None, None, None, None, None, 25),
41
+ ("user:btn:ban", "封禁", "btn", None, None, None, None, None, 26),
42
+ ("user:btn:delete", "删除", "btn", None, None, None, None, None, 27),
43
+
44
+ ("admin:menu", "管理员管理", "menu", None, "/admin", "/admin/index", None, "lucide:shield", 28),
45
+ ("admin:list", "查看", "page", None, None, None, None, None, 29),
46
+ ("admin:create", "新增", "page", None, None, None, None, None, 30),
47
+ ("admin:update", "编辑", "page", None, None, None, None, None, 31),
48
+ ("admin:delete", "删除", "page", None, None, None, None, None, 32),
49
+ ("admin:btn:assign_role", "分配角色", "btn", None, None, None, None, None, 33),
50
+ ("admin:btn:reset_pwd", "重置密码", "btn", None, None, None, None, None, 34),
51
+
52
+ ("role:menu", "角色管理", "menu", None, "/role", "/role/index", None, "lucide:key", 35),
53
+ ("role:list", "查看", "page", None, None, None, None, None, 36),
54
+ ("role:create", "新增", "page", None, None, None, None, None, 37),
55
+ ("role:update", "编辑", "page", None, None, None, None, None, 38),
56
+ ("role:delete", "删除", "page", None, None, None, None, None, 39),
57
+ ("role:btn:assign_perm", "分配权限", "btn", None, None, None, None, None, 40),
58
+
59
+ ("sync:menu", "同步管理", "menu", None, "/sync", "/sync/index", None, "lucide:refresh-cw", 41),
60
+ ("sync:list", "查看", "page", None, None, None, None, None, 42),
61
+ ("sync:btn:trigger", "触发同步", "btn", None, None, None, None, None, 43),
62
+ ("sync:btn:cancel", "取消同步", "btn", None, None, None, None, None, 44),
63
+
64
+ ("system:menu", "系统配置", "menu", None, "/system", "/system/index", None, "lucide:settings", 45),
65
+ ("system:config", "查看", "page", None, None, None, None, None, 46),
66
+ ("system:btn:save", "保存配置", "btn", None, None, None, None, None, 47),
67
+ ]
68
+
69
+
70
+ async def seed():
71
+ async with async_session() as db:
72
+ existing = await db.execute(select(Permission))
73
+ if existing.scalars().first():
74
+ print("Permissions already seeded, skipping.")
75
+ return
76
+
77
+ parent_ids: dict[str, int] = {}
78
+ for item in PERMISSIONS:
79
+ code, name, ptype, _, path, component, redirect, icon, order = item
80
+ p = Permission(
81
+ code=code,
82
+ name=name,
83
+ type=ptype,
84
+ path=path,
85
+ component=component,
86
+ redirect=redirect,
87
+ icon=icon,
88
+ sort_order=order,
89
+ )
90
+ db.add(p)
91
+ await db.flush()
92
+ if ptype == "menu":
93
+ parent_ids[code] = p.id
94
+
95
+ for item in PERMISSIONS:
96
+ code, name, ptype, _, _, _, _, _, _ = item
97
+ if ptype in ("page", "btn"):
98
+ prefix = code.split(":")[0]
99
+ menu_code = f"{prefix}:menu"
100
+ if menu_code in parent_ids:
101
+ result = await db.execute(
102
+ select(Permission).where(Permission.code == code)
103
+ )
104
+ perm = result.scalar_one_or_none()
105
+ if perm:
106
+ perm.parent_id = parent_ids[menu_code]
107
+
108
+ await db.commit()
109
+ print(f"Seeded {len(PERMISSIONS)} permissions.")
110
+
111
+
112
+ if __name__ == "__main__":
113
+ asyncio.run(seed())
scripts/seed_roles.py CHANGED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
6
+
7
+ from sqlalchemy import select
8
+
9
+ from app.database import async_session
10
+ from app.models.role import Role, AdminRole
11
+ from app.models.permission import Permission, RolePermission
12
+
13
+ ROLES = [
14
+ {
15
+ "name": "超级管理员",
16
+ "code": "super_admin",
17
+ "description": "全部权限,含角色管理",
18
+ "all_permissions": True,
19
+ },
20
+ {
21
+ "name": "管理员",
22
+ "code": "admin",
23
+ "description": "除角色管理外的所有权限",
24
+ "exclude_codes": [
25
+ "role:menu", "role:list", "role:create", "role:update", "role:delete",
26
+ "role:btn:assign_perm",
27
+ ],
28
+ },
29
+ {
30
+ "name": "编辑",
31
+ "code": "editor",
32
+ "description": "内容管理,不能动系统配置",
33
+ "include_codes": [
34
+ "vod:menu", "vod:list", "vod:detail", "vod:create", "vod:update",
35
+ "vod:btn:hide", "vod:btn:recommend", "vod:btn:delete", "vod:btn:audit",
36
+ "category:menu", "category:list", "category:update", "category:btn:map",
37
+ "sync:menu", "sync:list", "sync:btn:trigger", "sync:btn:cancel",
38
+ ],
39
+ },
40
+ {
41
+ "name": "查看者",
42
+ "code": "viewer",
43
+ "description": "只读所有页面",
44
+ "include_patterns": [":list", ":detail", ":config", ":menu"],
45
+ },
46
+ ]
47
+
48
+
49
+ async def seed():
50
+ async with async_session() as db:
51
+ existing = await db.execute(select(Role))
52
+ if existing.scalars().first():
53
+ print("Roles already seeded, skipping.")
54
+ return
55
+
56
+ all_perm_result = await db.execute(select(Permission))
57
+ all_perms = {p.code: p.id for p in all_perm_result.scalars().all()}
58
+
59
+ for role_data in ROLES:
60
+ role = Role(
61
+ name=role_data["name"],
62
+ code=role_data["code"],
63
+ description=role_data["description"],
64
+ is_builtin=True,
65
+ status=1,
66
+ )
67
+ db.add(role)
68
+ await db.flush()
69
+
70
+ if role_data.get("all_permissions"):
71
+ perm_ids = list(all_perms.values())
72
+ elif "exclude_codes" in role_data:
73
+ perm_ids = [
74
+ pid for code, pid in all_perms.items()
75
+ if code not in role_data["exclude_codes"]
76
+ ]
77
+ elif "include_codes" in role_data:
78
+ perm_ids = [
79
+ all_perms[c] for c in role_data["include_codes"]
80
+ if c in all_perms
81
+ ]
82
+ elif "include_patterns" in role_data:
83
+ perm_ids = []
84
+ for code, pid in all_perms.items():
85
+ if any(pat in code for pat in role_data["include_patterns"]):
86
+ perm_ids.append(pid)
87
+ else:
88
+ perm_ids = []
89
+
90
+ for pid in perm_ids:
91
+ db.add(RolePermission(role_id=role.id, permission_id=pid))
92
+
93
+ await db.commit()
94
+ print(f"Seeded {len(ROLES)} roles with permissions.")
95
+
96
+
97
+ if __name__ == "__main__":
98
+ asyncio.run(seed())