Archived
refactor: 迁移收尾(管理员2FA)+ 抽取公共工具层,消除 router 间重复
补齐最后缺口: - POST /api/v1/auth/admin_login/email、/auth/admin_login/verify(管理员 2FA Step2/3), 复用 auth_routes 的票据表与尝试上限(跨栈共享),签发会话 Cookie 重构(消除约 200 行重复,11 个 router 受益): - web/request_utils.py:request_data / safe_int / extract_id / cookies / dedup_ids 原在各 router 各复制一份,现集中 - web/serializers.py:format_credits / user_public / record_req_log - 各 router 改为导入别名,行为逐字不变 覆盖率:Flask 90 条业务路由全部有 FastAPI 等价端点(含 5 个向后兼容别名)。 验证:pytest 69/69;ruff All checks passed;pyright 0 errors;奇偶 36/36;冒烟 10/10。
This commit is contained in:
1 parent
9df0028195
commit
cd0f1f78a3
13 files changed
+274
-339
No files matched your search
+6
-56
@@ -17,7 +17,6 @@
|
||||
import asyncio
|
||||
import hmac
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from typing import Annotated, Any
|
||||
|
||||
@@ -26,11 +25,16 @@ from fastapi import APIRouter, Depends, Request
|
||||
import music_api
|
||||
from core import media, repo
|
||||
from core.config import VALID_QUALITY_LEVELS
|
||||
from core.state import GLOBAL_MUSIC_U_CACHE, REQ_LOG, SERVER_NICK_CACHE
|
||||
from core.state import GLOBAL_MUSIC_U_CACHE, SERVER_NICK_CACHE
|
||||
from music_api import APIException
|
||||
from web import ratelimit
|
||||
from web.deps import SiteUser, require_login
|
||||
from web.request_utils import cookies as _cookies
|
||||
from web.request_utils import extract_id as _extract_id
|
||||
from web.request_utils import request_data as _request_data
|
||||
from web.request_utils import safe_int as _safe_int
|
||||
from web.response import error, success
|
||||
from web.serializers import record_req_log as _record_log
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -50,56 +54,12 @@ def _nick_lock() -> asyncio.Lock:
|
||||
return _SERVER_NICK_LOCK
|
||||
|
||||
|
||||
async def _request_data(request: Request) -> dict[str, Any]:
|
||||
"""三路兼容取参:GET query 优先,其次 POST JSON,最后表单。"""
|
||||
data: dict[str, Any] = {}
|
||||
if request.method == 'GET':
|
||||
data.update(dict(request.query_params))
|
||||
return data
|
||||
try:
|
||||
body = await request.json()
|
||||
if isinstance(body, dict):
|
||||
data.update(body)
|
||||
except Exception:
|
||||
pass
|
||||
if not data:
|
||||
try:
|
||||
form = await request.form()
|
||||
data.update(dict(form.items()))
|
||||
except Exception:
|
||||
pass
|
||||
return data
|
||||
|
||||
|
||||
def _safe_int(value: Any, default: int) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _extract_id(raw: Any) -> str:
|
||||
"""URL/纯数字 → ID(与 Flask _extract_music_id 的查询参数口径一致)。"""
|
||||
s = str(raw or '').strip()
|
||||
if 'music.163.com' in s:
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
try:
|
||||
q = parse_qs(urlsplit(s).query)
|
||||
for key in ('id', 'songid'):
|
||||
if q.get(key):
|
||||
return str(q[key][0]).strip()
|
||||
except Exception:
|
||||
pass
|
||||
m = re.search(r'[?&#]id=(\d+)', s)
|
||||
if m:
|
||||
return m.group(1)
|
||||
return s
|
||||
|
||||
|
||||
def _cookies() -> dict[str, str]:
|
||||
"""全局账号 Cookie(管理员 cookie.txt)。"""
|
||||
return music_api.load_cookies()
|
||||
|
||||
|
||||
async def mask_server_nickname(nick: str, user: SiteUser) -> str:
|
||||
"""非管理员响应中把服务器账号昵称替换为站点名(与 Flask _mask_server_nickname 同口径)。
|
||||
@@ -269,16 +229,6 @@ async def _resolve_user_cookies(
|
||||
return ck
|
||||
|
||||
|
||||
def _record_log(action: str, ip: str, song: str) -> None:
|
||||
"""用户解析/下载操作记录(IP)——写入共享 REQ_LOG(与 Flask _record_log 同口径)。"""
|
||||
REQ_LOG.append({
|
||||
'action': action,
|
||||
'ip': ip,
|
||||
'song': str(song or '')[:100],
|
||||
'time': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
})
|
||||
if len(REQ_LOG) > 2000:
|
||||
del REQ_LOG[:len(REQ_LOG) - 2000]
|
||||
|
||||
|
||||
# ============ 迁移端:专辑 / 歌单 / 歌曲 ============
|
||||
|
||||
Reference in new issue
Block a user