Archived
补齐最后缺口: - 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。
419 lines
17 KiB
Python
419 lines
17 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""个人账号与公开播放端点(FastAPI 栈)——与 Flask 侧响应契约逐字段对齐。
|
||
|
||
已迁移:
|
||
- POST /api/v1/user/qr/create ↔ Flask /user/qr/create(扫码登录二维码 SVG)
|
||
- POST /api/v1/user/qr/check ↔ Flask /user/qr/check(轮询登录状态)
|
||
- POST /api/v1/user/status ↔ Flask /user/status
|
||
- POST /api/v1/user/logout ↔ Flask /user/logout
|
||
- POST /api/v1/user/playlists ↔ Flask /user/playlists
|
||
- POST /api/v1/user/playlist ↔ Flask /user/playlist
|
||
- POST /api/v1/user/collect ↔ Flask /user/collect(需站点登录)
|
||
- POST /api/v1/user/comment ↔ Flask /user/comment(需站点登录)
|
||
- POST/GET /api/v1/api/playlist/play ↔ Flask /api/playlist/play(需 API 密钥)
|
||
- POST/GET /api/v1/fe_error ↔ Flask /api/fe_error(前端错误上报)
|
||
|
||
说明:qrcode/QRLoginClient 属同步实现,经 asyncio.to_thread 执行;
|
||
公开播放 API 的逐曲直链解析由 ThreadPoolExecutor(4) 改为 asyncio.gather 并发
|
||
(并发度不变,但不再占用线程)。
|
||
"""
|
||
import asyncio
|
||
import hmac
|
||
import logging
|
||
from typing import Annotated, Any
|
||
|
||
from fastapi import APIRouter, Depends, Request
|
||
|
||
import music_api
|
||
from core import media
|
||
from core.config import VALID_QUALITY_LEVELS
|
||
from music_api import APIException
|
||
from web import ratelimit
|
||
from web.deps import SiteUser, current_user, 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
|
||
|
||
router = APIRouter()
|
||
|
||
LoginUser = Annotated[SiteUser, Depends(require_login)]
|
||
|
||
logger = logging.getLogger('web.user')
|
||
|
||
_MAX_PLAY_TRACKS = 500
|
||
_PLAY_CONCURRENCY = 4
|
||
|
||
|
||
|
||
|
||
|
||
async def _resolve_user_cookies(data: dict[str, Any], user: SiteUser | None, request: Request):
|
||
from web.routers.music import _resolve_user_cookies as _r
|
||
return await _r(data, user, request)
|
||
|
||
|
||
class _AnonUser:
|
||
"""未登录请求(个人解析路径)按非管理员处理。"""
|
||
id = 0
|
||
username = ''
|
||
role = 'user'
|
||
credits = 0
|
||
|
||
@property
|
||
def is_admin(self) -> bool:
|
||
return False
|
||
|
||
@property
|
||
def unlimited(self) -> bool:
|
||
return False
|
||
|
||
|
||
async def _mask(nick: str, user: SiteUser | None) -> str:
|
||
from web.routers.music import mask_server_nickname
|
||
return await mask_server_nickname(nick, user if user is not None else _AnonUser()) # type: ignore[arg-type]
|
||
|
||
|
||
# ============ 扫码登录 ============
|
||
|
||
@router.post('/user/qr/create')
|
||
async def user_qr_create(request: Request):
|
||
"""生成个人登录二维码(返回 SVG)。"""
|
||
await ratelimit.guard(request, bucket='free', limit=30, window=60)
|
||
from qr_login import QRLoginClient
|
||
|
||
try:
|
||
client = QRLoginClient('user_cookie.txt')
|
||
# QRLoginManager 已异步化:直接 await(不可再经 to_thread 包装协程)
|
||
unikey = await client.qr_manager.generate_qr_key()
|
||
if not unikey:
|
||
return error('生成二维码失败', 500)
|
||
|
||
def _render_svg(key: str) -> str:
|
||
import qrcode
|
||
from qrcode.image.svg import SvgPathImage
|
||
qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_M) # type: ignore[attr-defined]
|
||
qr.add_data(f'https://music.163.com/login?codekey={key}')
|
||
qr.make(fit=True)
|
||
svg = qr.make_image(image_factory=SvgPathImage).to_string()
|
||
return svg.decode('utf-8') if isinstance(svg, bytes) else svg
|
||
|
||
svg = await asyncio.to_thread(_render_svg, unikey)
|
||
except Exception:
|
||
return error('服务暂时不可用,请稍后再试', 500)
|
||
return success({'unikey': unikey, 'qr_svg': svg, 'expires_in': 180}, '二维码生成成功')
|
||
|
||
|
||
@router.post('/user/qr/check')
|
||
async def user_qr_check(
|
||
user: Annotated[SiteUser | None, Depends(current_user)],
|
||
request: Request,
|
||
):
|
||
"""轮询个人登录状态(不写服务器文件;站点登录时同步一份供后台查看)。"""
|
||
await ratelimit.guard(request, bucket='free', limit=30, window=60)
|
||
data = await _request_data(request)
|
||
unikey = data.get('unikey')
|
||
if not unikey:
|
||
return error('缺少 unikey 参数')
|
||
from qr_login import QRLoginClient
|
||
|
||
try:
|
||
client = QRLoginClient('user_cookie.txt')
|
||
# QRLoginManager.check_qr_login 已异步化:直接 await
|
||
code, cookie_dict = await client.qr_manager.check_qr_login(unikey)
|
||
except Exception:
|
||
return error('服务暂时不可用,请稍后再试', 500)
|
||
|
||
if code == 803:
|
||
musu_u = cookie_dict.get('MUSIC_U', '')
|
||
if not musu_u:
|
||
return error('登录成功但未获取到 Cookie', 500)
|
||
cookie = f'MUSIC_U={musu_u};os=pc;appver=8.9.70;'
|
||
if cookie_dict.get('__csrf'):
|
||
cookie += f"__csrf={cookie_dict['__csrf']};"
|
||
try:
|
||
if user is not None:
|
||
import auth_system
|
||
await asyncio.to_thread(auth_system.set_user_netease_cookie, user.username, cookie)
|
||
except Exception:
|
||
pass
|
||
logger.info('个人账号扫码登录成功(Cookie 已返回浏览器本地保存)')
|
||
return success({'status': 'success', 'cookie': cookie}, '登录成功,Cookie 已保存在本机浏览器')
|
||
if code == 801:
|
||
return success({'status': 'waiting'}, '等待扫码')
|
||
if code == 802:
|
||
return success({'status': 'scanned'}, '已扫码,请在手机上确认登录')
|
||
if code == 800:
|
||
return success({'status': 'expired'}, '二维码已过期')
|
||
return success({'status': 'failed', 'code': code}, '登录失败')
|
||
|
||
|
||
@router.post('/user/status')
|
||
async def user_status(
|
||
user: Annotated[SiteUser | None, Depends(current_user)],
|
||
request: Request,
|
||
):
|
||
"""个人用户登录状态与账号信息(Cookie 由浏览器本地保存并随请求传入)。"""
|
||
data = await _request_data(request)
|
||
cookies = await _resolve_user_cookies(data, user, request)
|
||
if not cookies:
|
||
return success({'cookie': {'is_valid': False}, 'user': None}, '个人账号未登录')
|
||
try:
|
||
info = await music_api.NeteaseAPI().get_account_info(cookies)
|
||
except Exception:
|
||
info = None
|
||
return success({'cookie': {'is_valid': info is not None}, 'user': info}, '获取个人登录状态成功')
|
||
|
||
|
||
@router.post('/user/logout')
|
||
async def user_logout():
|
||
"""退出个人账号登录(浏览器清除本地 Cookie 即可,服务器无可清除内容)。"""
|
||
return success({'is_valid': False}, '已退出登录')
|
||
|
||
|
||
@router.post('/user/playlists')
|
||
async def user_playlists(
|
||
user: Annotated[SiteUser | None, Depends(current_user)],
|
||
request: Request,
|
||
):
|
||
"""个人用户收藏/创建的歌单(含「我喜欢的音乐」)。"""
|
||
data = await _request_data(request)
|
||
cookies = await _resolve_user_cookies(data, user, request)
|
||
if not cookies:
|
||
return error('请先扫码登录你的网易云账号', 401)
|
||
api = music_api.NeteaseAPI()
|
||
try:
|
||
account = await api.get_account_info(cookies)
|
||
if not account or not account.get('userId'):
|
||
return error('获取账号信息失败,Cookie 可能已失效,请重新登录', 401)
|
||
playlists = await api.get_user_playlists(account['userId'], cookies)
|
||
except APIException:
|
||
return error('服务暂时不可用,请稍后再试', 500)
|
||
if isinstance(playlists, list):
|
||
for pl in playlists:
|
||
if isinstance(pl, dict):
|
||
if pl.get('name'):
|
||
pl['name'] = await _mask(pl['name'], user)
|
||
cr = pl.get('creator')
|
||
if isinstance(cr, dict) and cr.get('nickname'):
|
||
cr['nickname'] = await _mask(cr['nickname'], user)
|
||
return success({'user': account, 'playlists': playlists}, '获取个人歌单成功')
|
||
|
||
|
||
@router.post('/user/playlist')
|
||
async def user_playlist(
|
||
user: Annotated[SiteUser | None, Depends(current_user)],
|
||
request: Request,
|
||
):
|
||
"""个人歌单详情(个人 Cookie,支持「我喜欢的音乐」等私有歌单)。"""
|
||
data = await _request_data(request)
|
||
playlist_id = data.get('id')
|
||
if not playlist_id:
|
||
return error("参数 'playlist_id' 不能为空", 400)
|
||
cookies = await _resolve_user_cookies(data, user, request)
|
||
if not cookies:
|
||
return error('请先扫码登录你的网易云账号', 401)
|
||
playlist_id = _extract_id(playlist_id)
|
||
if not str(playlist_id).strip().isdigit():
|
||
return error('无效的歌单ID,请输入数字ID或分享链接')
|
||
try:
|
||
result = await music_api.NeteaseAPI().get_playlist_detail(int(playlist_id), cookies)
|
||
except APIException:
|
||
return error('服务暂时不可用,请稍后再试', 500)
|
||
if isinstance(result, dict):
|
||
pl = result.get('playlist')
|
||
if isinstance(pl, dict):
|
||
if pl.get('name'):
|
||
pl['name'] = await _mask(pl['name'], user)
|
||
cr = pl.get('creator')
|
||
if isinstance(cr, dict) and cr.get('nickname'):
|
||
cr['nickname'] = await _mask(cr['nickname'], user)
|
||
return success({'playlist': result}, '获取个人歌单详情成功')
|
||
|
||
|
||
@router.post('/user/collect')
|
||
async def user_collect(user: LoginUser, request: Request):
|
||
"""收藏/取消收藏歌单或专辑(真实收藏到个人账号)。"""
|
||
await ratelimit.guard(request, bucket='free', limit=30, window=60)
|
||
data = await _request_data(request)
|
||
cookies = await _resolve_user_cookies(data, user, request)
|
||
if not cookies:
|
||
return error('请先扫码登录你的网易云账号', 401)
|
||
collect_id = data.get('id')
|
||
collect_type = data.get('type', 'playlist')
|
||
action = _safe_int(data.get('action'), 1)
|
||
if not collect_id:
|
||
return error('缺少 id 参数')
|
||
if collect_type not in ('playlist', 'album'):
|
||
return error('type 仅支持 playlist/album')
|
||
if action not in (1, 2):
|
||
return error('action 仅支持 1(收藏)/2(取消)')
|
||
collect_id = _extract_id(collect_id)
|
||
if not str(collect_id).strip().isdigit():
|
||
return error('无效的ID,请输入数字ID或分享链接')
|
||
api = music_api.NeteaseAPI()
|
||
try:
|
||
if collect_type == 'album':
|
||
result = await api.subscribe_album(int(collect_id), cookies, action)
|
||
else:
|
||
result = await api.subscribe_playlist(int(collect_id), cookies, action)
|
||
except APIException:
|
||
return error('服务暂时不可用,请稍后再试', 500)
|
||
return success({'result': result}, '收藏成功' if action == 1 else '取消收藏成功')
|
||
|
||
|
||
@router.post('/user/comment')
|
||
async def user_comment(user: LoginUser, request: Request):
|
||
"""发送/回复歌曲评论(weapi,使用个人账号)。"""
|
||
await ratelimit.guard(request, bucket='free', limit=30, window=60)
|
||
data = await _request_data(request)
|
||
cookies = await _resolve_user_cookies(data, user, request)
|
||
if not cookies:
|
||
return error('请先扫码登录你的网易云账号', 401)
|
||
song_id = data.get('song_id') or data.get('id')
|
||
content = (data.get('content') or '').strip()
|
||
action = _safe_int(data.get('action'), 1)
|
||
comment_id = data.get('comment_id') or data.get('reply_to')
|
||
if not song_id:
|
||
return error('缺少歌曲 ID')
|
||
if not content:
|
||
return error('评论内容不能为空')
|
||
if len(content) > 140:
|
||
return error('评论内容不能超过 140 字')
|
||
if action not in (1, 2):
|
||
return error('action 仅支持 1(评论)/2(回复)')
|
||
if action == 2 and not comment_id:
|
||
return error('回复评论缺少目标评论 ID')
|
||
song_id = _extract_id(song_id)
|
||
if not str(song_id).isdigit():
|
||
return error('无效的歌曲 ID')
|
||
thread_id = f'R_SO_4_{song_id}'
|
||
reply_target = _safe_int(comment_id, 0) if comment_id else 0
|
||
if action == 2 and reply_target <= 0:
|
||
return error('回复评论的目标评论 ID 无效')
|
||
try:
|
||
result = await music_api.NeteaseAPI().post_comment(
|
||
thread_id, content, action, reply_target if reply_target > 0 else None, cookies)
|
||
except APIException:
|
||
return error('服务暂时不可用,请稍后再试', 500)
|
||
return success({'result': result}, '评论成功' if action == 1 else '回复成功')
|
||
|
||
|
||
# ============ 公开播放 API ============
|
||
|
||
@router.api_route('/api/playlist/play', methods=['GET', 'POST'])
|
||
async def playlist_play(request: Request):
|
||
"""公开歌单播放 API(需密钥;返回每首歌的可播放直链)。"""
|
||
await ratelimit.guard(request, bucket='free', limit=30, window=60)
|
||
data = await _request_data(request)
|
||
playlist_id = data.get('id')
|
||
level = data.get('level', 'lossless')
|
||
|
||
provided = str(data.get('key') or request.query_params.get('key') or '')
|
||
expected = await _get_setting('playlist_play_key', '')
|
||
if not expected or not provided or not hmac.compare_digest(provided, expected):
|
||
return error('需要有效的 API 密钥(请联系站点管理员获取)', 401)
|
||
|
||
if not playlist_id:
|
||
return error("参数 'playlist_id' 不能为空", 400)
|
||
if level not in VALID_QUALITY_LEVELS:
|
||
return error(f"无效的音质参数,支持: {', '.join(VALID_QUALITY_LEVELS)}")
|
||
limit = _safe_int(data.get('limit', 100), 100)
|
||
if limit < 0:
|
||
return error('limit 参数不能为负数')
|
||
limit = min(limit or _MAX_PLAY_TRACKS, _MAX_PLAY_TRACKS)
|
||
|
||
playlist_id = _extract_id(playlist_id)
|
||
if not str(playlist_id).strip().isdigit():
|
||
return error('无效的歌单ID,请输入数字ID或分享链接')
|
||
|
||
cookies = _cookies()
|
||
api = music_api.NeteaseAPI()
|
||
try:
|
||
detail = await api.get_playlist_detail(int(playlist_id), cookies)
|
||
except APIException:
|
||
return error('服务暂时不可用,请稍后再试', 500)
|
||
|
||
all_tracks = detail.get('tracks', [])
|
||
tracks = all_tracks[:limit]
|
||
|
||
sem = asyncio.Semaphore(_PLAY_CONCURRENCY)
|
||
|
||
async def _resolve(track):
|
||
async with sem:
|
||
try:
|
||
info = await api.get_song_url(track['id'], level, cookies)
|
||
arr = (info or {}).get('data') or []
|
||
if arr and arr[0] and arr[0].get('url'):
|
||
d = arr[0]
|
||
return {
|
||
'id': track['id'],
|
||
'name': track.get('name', ''),
|
||
'artists': track.get('artists', ''),
|
||
'album': track.get('album', ''),
|
||
'picUrl': track.get('picUrl', ''),
|
||
'url': d.get('url', ''),
|
||
'level': d.get('level', level),
|
||
'level_name': media.quality_display_name(d.get('level', level)),
|
||
'size': d.get('size', 0),
|
||
'size_formatted': media.format_file_size(d.get('size', 0)),
|
||
'type': d.get('type'),
|
||
'bitrate': d.get('br'),
|
||
}
|
||
except Exception:
|
||
pass
|
||
return None
|
||
|
||
resolved = await asyncio.gather(*[_resolve(t) for t in tracks])
|
||
playable = [r for r in resolved if r is not None]
|
||
skipped = len(resolved) - len(playable)
|
||
|
||
return success({
|
||
'playlist': {
|
||
'id': detail.get('id'),
|
||
'name': await _mask(detail.get('name', ''), None),
|
||
'coverImgUrl': detail.get('coverImgUrl', ''),
|
||
'creator': await _mask(detail.get('creator', ''), None),
|
||
'trackCount': detail.get('trackCount', len(all_tracks)),
|
||
},
|
||
'account': 'admin',
|
||
'level': level,
|
||
'level_name': media.quality_display_name(level),
|
||
'limit': limit or len(tracks),
|
||
'total': len(all_tracks),
|
||
'playable': len(playable),
|
||
'skipped': skipped,
|
||
'tracks': playable,
|
||
}, '获取歌单播放列表成功')
|
||
|
||
|
||
async def _get_setting(key: str, default: str = '') -> str:
|
||
from core import repo
|
||
return await repo.get_setting(key, default)
|
||
|
||
|
||
# ============ 前端错误上报 ============
|
||
|
||
@router.api_route('/fe_error', methods=['POST', 'GET'])
|
||
async def fe_error(request: Request):
|
||
"""前端错误日志上报(10 次/分/IP;字段截断清洗;仅写服务日志,不入库)。"""
|
||
if not ratelimit.rate_ok('fe:' + ratelimit.client_ip(request), 10, 60):
|
||
return error('上报过于频繁', 429)
|
||
data = await _request_data(request)
|
||
|
||
def _clean(key: str, n: int) -> str:
|
||
return str(data.get(key) or '')[:n].replace('\n', ' | ').replace('\r', '')
|
||
|
||
msg = _clean('msg', 200)
|
||
if not msg:
|
||
return error('缺少 msg 参数')
|
||
etype = _clean('type', 20) or 'error'
|
||
stack = _clean('stack', 800)
|
||
page = _clean('page', 120)
|
||
env = _clean('env', 200)
|
||
ip = ratelimit.client_ip(request)
|
||
logger.error('[前端错误] type=%s msg=%s page=%s ip=%s env=%s stack=%s',
|
||
etype, msg, page, ip, env, stack)
|
||
return success(None, '已记录')
|