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。
170 lines
6.5 KiB
Python
170 lines
6.5 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""播客端点(FastAPI 栈)——与 Flask 侧同名端点响应契约逐字段对齐。
|
|
|
|
已迁移(免费解析类,需登录,不扣次数):
|
|
- POST/GET /api/v1/podcast/parse ↔ Flask /podcast/parse
|
|
- POST/GET /api/v1/podcast/programs ↔ Flask /podcast/programs
|
|
- POST/GET /api/v1/podcast/search ↔ Flask /podcast/search
|
|
- POST/GET /api/v1/podcast/hot ↔ Flask /podcast/hot
|
|
|
|
说明:podcast_api 仍是同步模块(requests),此处以 asyncio.to_thread 包装,
|
|
让阻塞的上游调用不占用事件循环——行为与 Flask 侧一致,且不阻塞其它请求。
|
|
"""
|
|
import asyncio
|
|
from typing import Annotated
|
|
|
|
from fastapi import APIRouter, Depends, Request
|
|
|
|
import podcast_api
|
|
from core import media
|
|
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()
|
|
|
|
LoginUser = Annotated[SiteUser, Depends(require_login)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.api_route('/podcast/parse', methods=['GET', 'POST'])
|
|
async def podcast_parse(_user: LoginUser, request: Request):
|
|
"""播客解析:电台 → 详情+单集列表;单集 → 详情+音频直链。"""
|
|
await ratelimit.guard(request, bucket='free', limit=30, window=60)
|
|
data = await _request_data(request)
|
|
raw = data.get('id') or data.get('url')
|
|
if not raw:
|
|
return error("参数 'id' 不能为空", 400)
|
|
page_size = max(1, min(_safe_int(data.get('page_size'), 30), 100))
|
|
quality = str(data.get('quality') or 'auto')
|
|
|
|
cookies = _cookies()
|
|
try:
|
|
result = await asyncio.to_thread(
|
|
podcast_api.parse_podcast_ref, raw, cookies, page_size=page_size)
|
|
except APIException as e:
|
|
return error(str(e), 404)
|
|
except Exception:
|
|
return error('服务暂时不可用,请稍后再试', 500)
|
|
|
|
if result.get('kind') == 'program':
|
|
program = result['program']
|
|
song_id = program.get('main_song_id')
|
|
url_info = None
|
|
if song_id:
|
|
try:
|
|
url_info = await asyncio.to_thread(
|
|
podcast_api.resolve_episode_url, song_id, cookies, quality)
|
|
except Exception:
|
|
url_info = None
|
|
if url_info:
|
|
program['audio'] = {
|
|
'url': url_info['url'],
|
|
'level': url_info['level'],
|
|
'level_name': media.quality_display_name(url_info['level']),
|
|
'type': url_info['type'],
|
|
'size': url_info['size'],
|
|
'size_formatted': media.format_file_size(url_info['size']),
|
|
'br': url_info['br'],
|
|
}
|
|
else:
|
|
program['audio'] = None
|
|
try:
|
|
_record_log('解析', ratelimit.client_ip(request), program.get('name') or str(raw))
|
|
except Exception:
|
|
pass
|
|
else:
|
|
try:
|
|
_record_log('解析', ratelimit.client_ip(request),
|
|
(result.get('radio') or {}).get('name') or str(raw))
|
|
except Exception:
|
|
pass
|
|
|
|
return success(result, '播客解析成功')
|
|
|
|
|
|
@router.api_route('/podcast/programs', methods=['GET', 'POST'])
|
|
async def podcast_programs(_user: LoginUser, request: Request):
|
|
"""播客单集列表(分页加载)。"""
|
|
await ratelimit.guard(request, bucket='free', limit=30, window=60)
|
|
data = await _request_data(request)
|
|
radio_id = data.get('radio_id') or data.get('id')
|
|
if not radio_id:
|
|
return error("参数 'radio_id' 不能为空", 400)
|
|
limit = max(1, min(_safe_int(data.get('limit'), 30), 100))
|
|
offset = max(0, _safe_int(data.get('offset'), 0))
|
|
asc = str(data.get('asc', 'true')).lower() in ('1', 'true', 'yes')
|
|
|
|
radio_id = _extract_id(str(radio_id))
|
|
if not str(radio_id).isdigit():
|
|
return error('无效的电台 ID')
|
|
try:
|
|
result = await asyncio.to_thread(
|
|
podcast_api.get_radio_programs, radio_id, _cookies(),
|
|
limit=limit, offset=offset, asc=asc)
|
|
return success(result, '获取单集列表成功')
|
|
except APIException as e:
|
|
return error(str(e), 404)
|
|
except Exception:
|
|
return error('服务暂时不可用,请稍后再试', 500)
|
|
|
|
|
|
@router.api_route('/podcast/search', methods=['GET', 'POST'])
|
|
async def podcast_search(_user: LoginUser, request: Request):
|
|
"""播客搜索(电台 / 单集声音)。"""
|
|
await ratelimit.guard(request, bucket='free', limit=30, window=60)
|
|
data = await _request_data(request)
|
|
keyword = data.get('keyword') or data.get('q')
|
|
if not keyword:
|
|
return error("参数 'keyword' 不能为空", 400)
|
|
limit = max(1, min(_safe_int(data.get('limit'), 20), 50))
|
|
offset = max(0, _safe_int(data.get('offset'), 0))
|
|
search_type = data.get('type', 'all')
|
|
if search_type not in ('all', 'radio', 'voice'):
|
|
search_type = 'all'
|
|
try:
|
|
result = await asyncio.to_thread(
|
|
podcast_api.search_podcast, keyword, _cookies(),
|
|
limit=limit, offset=offset, search_type=search_type)
|
|
return success(result, '播客搜索完成')
|
|
except APIException as e:
|
|
return error(str(e), 404)
|
|
except Exception:
|
|
return error('服务暂时不可用,请稍后再试', 500)
|
|
|
|
|
|
@router.api_route('/podcast/hot', methods=['GET', 'POST'])
|
|
async def podcast_hot(_user: LoginUser, request: Request):
|
|
"""热门播客 + 播客分类列表。"""
|
|
await ratelimit.guard(request, bucket='free', limit=30, window=60)
|
|
data = await _request_data(request)
|
|
limit = max(1, min(_safe_int(data.get('limit'), 30), 100))
|
|
offset = max(0, _safe_int(data.get('offset'), 0))
|
|
cate_id = data.get('cate_id') or None
|
|
try:
|
|
radios = await asyncio.to_thread(
|
|
podcast_api.get_hot_radios, _cookies(), limit=limit, offset=offset, cate_id=cate_id)
|
|
except APIException as e:
|
|
return error(str(e), 404)
|
|
except Exception:
|
|
return error('服务暂时不可用,请稍后再试', 500)
|
|
try:
|
|
categories = await asyncio.to_thread(podcast_api.get_categories)
|
|
except APIException:
|
|
categories = []
|
|
# 满页视为可能还有更多(与 Flask 同口径)
|
|
return success({'radios': radios, 'categories': categories,
|
|
'has_more': len(radios) >= limit}, '获取热门播客成功')
|