Files
live-hub-py/web/backend/main.py
T
yml ec05d66f61 fix(supply): 有效 CK 即可用并修复自动化页空注册表
- 供给覆盖/候选取消 24h CK 新鲜度硬门槛,有效 CK 直接可用
- Web/API 进程登记作业注册表,修复作业配置/运行记录空白
- 补充有效 CK、空注册表回归测试
- 文档记录 CK 获取/首次登录缺口
2026-11-24 14:07:39 +08:00

247 lines
7.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""FastAPI 入口"""
import os
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any, cast
import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from utils import setup_logger
from .database import init_db
from .errors import ApiError, api_error_handler
from .routers import (
account_check,
accounts,
admin_users,
audit,
auth,
automation,
cookies,
dashboard,
dcauth,
douyu,
douyu_collab,
files,
huya,
login,
platform_fulfillment,
platform_fulfillment_integration,
proxy,
users,
weibo,
weibo_collab,
yyb,
)
from .schemas import AppInfo
from .session import SessionRenewalMiddleware
from .version import get_app_version
@asynccontextmanager
async def lifespan(app: FastAPI):
# 本地 dev.sh 和 Docker 均显式设置 LOG_DIR;直接运行时回退到项目 logs/。
_log_level = os.getenv("LOG_LEVEL", "INFO")
_log_dir = Path(
os.getenv("LOG_DIR", str(Path(__file__).resolve().parents[2] / "logs"))
)
setup_logger(level=_log_level, log_dir=str(_log_dir))
init_db()
# Web/API 进程也必须登记作业注册表:生产把调度器放在独立进程
# (RUNTIME_ROLE=web/background),API 进程如果不登记,
# /automation/jobs 和 /automation/runs 会按空注册表过滤,页面全空白。
from .services.automation import register_default_jobs
register_default_jobs()
from .background_runtime import (
recover_orphaned_work,
start_background_services,
stop_background_services,
)
from .database import dispose_engines
from .services.task_runtime import shutdown as shutdown_task_runtime
role = os.getenv("RUNTIME_ROLE", "all").strip().lower()
background_in_process = role in {"all", "background"}
if background_in_process:
recover_orphaned_work()
start_background_services()
try:
yield
finally:
if background_in_process:
stop_background_services()
shutdown_task_runtime(wait=False)
dispose_engines()
app = FastAPI(
title="直播运营后台",
version=get_app_version(),
lifespan=lifespan,
)
# 业务异常统一带 errorCode,前端据此区分手机号未绑定 / 设备不一致等场景。
app.add_exception_handler(ApiError, cast(Any, api_error_handler))
# CORS(支持通过环境变量配置,逗号分隔;默认开发环境)
_cors_env = os.getenv("CORS_ORIGINS", "")
if _cors_env:
_cors_origins = [o.strip() for o in _cors_env.split(",") if o.strip()]
else:
_cors_origins = [
"http://localhost:5174",
"http://localhost:5173",
"http://localhost:3000",
]
app.add_middleware(
CORSMiddleware,
allow_origins=_cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 压缩 JSON 和静态资源响应,避免任务列表轮询反复传输大体积文本。
app.add_middleware(GZipMiddleware, minimum_size=1024)
# 安全响应头中间件
class SecurityHeadersMiddleware:
def __init__(self, app: Any):
self.app = app
async def __call__(self, scope: Any, receive: Any, send: Any):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
path = str(scope.get("path") or "")
is_asset = path.startswith("/assets/")
async def send_wrapper(message: Any):
if message["type"] == "http.response.start":
replaced_headers = {
b"x-content-type-options",
b"x-frame-options",
b"referrer-policy",
}
if is_asset:
replaced_headers.add(b"cache-control")
headers = [
(key, value)
for key, value in message.get("headers", [])
if key not in replaced_headers
]
if not is_asset and not any(
key == b"cache-control" for key, _value in headers
):
headers.append((b"cache-control", b"no-store, max-age=0"))
headers.extend(
[
(b"x-content-type-options", b"nosniff"),
(b"x-frame-options", b"DENY"),
(
b"referrer-policy",
b"strict-origin-when-cross-origin",
),
]
)
if is_asset:
headers.append(
(
b"cache-control",
b"public, max-age=31536000, immutable",
)
)
message["headers"] = headers
await send(message)
await self.app(scope, receive, send_wrapper)
app.add_middleware(SecurityHeadersMiddleware)
# 后台登录滑动续期:24h 空闲过期,7d 绝对上限。
app.add_middleware(SessionRenewalMiddleware)
# 注册路由
app.include_router(auth.router)
app.include_router(users.router)
app.include_router(admin_users.router)
app.include_router(dcauth.router)
app.include_router(accounts.router)
app.include_router(account_check.router)
app.include_router(dashboard.router)
app.include_router(login.router)
app.include_router(proxy.router)
app.include_router(cookies.router)
app.include_router(huya.router)
app.include_router(weibo.router)
app.include_router(weibo_collab.router)
app.include_router(douyu.router)
app.include_router(douyu_collab.router)
app.include_router(platform_fulfillment.router)
app.include_router(platform_fulfillment_integration.router)
app.include_router(yyb.router)
app.include_router(audit.router)
app.include_router(automation.router)
app.include_router(files.router)
@app.get("/api/health")
async def health():
return {"status": "ok"}
@app.get("/api/app-info", response_model=AppInfo)
def app_info():
return AppInfo(version=get_app_version())
# ---- 生产环境:serve 前端静态文件 ----
# Docker 部署时前端构建产物会被复制到 web/frontend/dist
_FRONTEND_DIST = Path(__file__).resolve().parents[2] / "web" / "frontend" / "dist"
_INDEX_HTML = _FRONTEND_DIST / "index.html"
if _INDEX_HTML.exists():
# 挂载静态资源目录(js/css/图片等)
_ASSETS_DIR = _FRONTEND_DIST / "assets"
if _ASSETS_DIR.exists():
app.mount("/assets", StaticFiles(directory=str(_ASSETS_DIR)), name="assets")
@app.get("/{full_path:path}")
async def serve_spa(full_path: str, request: Request):
"""SPA fallback:非 /api 路径返回 index.html"""
# 排除 API 路径
if full_path.startswith("api"):
return {"detail": "Not Found"}
# 尝试返回静态文件(防护路径遍历)
file_path = (_FRONTEND_DIST / full_path).resolve()
try:
file_path.relative_to(_FRONTEND_DIST.resolve())
except ValueError:
# 路径逃逸出 dist 目录,拒绝访问
return {"detail": "Not Found"}
if file_path.is_file():
return FileResponse(str(file_path))
# SPA fallback 到 index.html
return FileResponse(str(_INDEX_HTML))
def run():
_reload = os.getenv("UVICORN_RELOAD", "false").lower() == "true"
_port = int(os.getenv("BACKEND_PORT", "8800"))
uvicorn.run("web.backend.main:app", host="0.0.0.0", port=_port, reload=_reload)
if __name__ == "__main__":
run()