Files
live-hub-py/web/backend/main.py
T

235 lines
7.0 KiB
Python

"""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()
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 "")
async def send_wrapper(message: Any):
if message["type"] == "http.response.start":
headers = [
(key, value)
for key, value in message.get("headers", [])
if key
not in {
b"x-content-type-options",
b"x-frame-options",
b"referrer-policy",
b"cache-control",
}
]
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 path.startswith("/assets/"):
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()