Archived
为什么:podcast_api.py(560 行) 与 qr_login.py(397 行) 既不属于任何包、也不是 入口脚本,却同时被 services 层与 web 层引用——`services/downloads.py` 直接 `from qr_login import ...`、`services/podcast.py` 直接 `import podcast_api`, 业务层反向依赖顶层游离模块,是本次架构体检里唯一的无争议分层倒置。 两者本就依赖 music_api(前者取 url_v1/APIConstants/APIException,后者取 QRLoginManager),与 music_api 下已有的 qr.py / compat.py 是同一层的同类物。 迁移(git 保留重命名历史): - podcast_api.py -> music_api/podcast.py - qr_login.py -> music_api/qr_client.py **命名避让**:不叫 music_api/qr_login.py——music_api/__init__ 已经从 .compat 导出了一个**同名函数** qr_login,同名子模块会与之互相遮蔽。改叫 qr_client (其核心导出即 QRLoginClient),并在验证里专门确认 music_api.qr_login 仍是 可调用函数、music_api.podcast 是模块,两者不冲突。 内部导入顺带改为精确子模块,不再绕道包门面: - podcast.py:from music_api import APIConstants/APIException/url_v1 → from .compat import url_v1 / from .constants import ... / from .errors import ... - qr_client.py:删掉那层 try/except ImportError 包装(它给的是「请确保 music_api.py 文件存在」这类顶层脚本时代的提示,作为包内模块已无意义), 改 from .cookies/.errors/.qr 相对导入 - CLI 用法文本 python qr_login.py → python -m music_api.qr_client (相对导入后直接跑脚本会失败,必须走 -m;全仓确认无脚本/文档引用旧入口) - 路径安全性已核对:qr_client 用的是 CWD 相对的 cookie.txt,不是 __file__ 相对, 迁移不改其解析结果 引用点全部更新(AST 扫描确认覆盖全集,替换后残留 0): - podcast:services/podcast.py(1 + 5 处调用) · web/routers/podcast.py(1 + 6) · web/routers/download.py(2 处函数内 + 3),导入名统一为 `podcast` - qr_login:services/downloads.py · web/routers/admin.py · web/routers/user.py(×2) - services/__init__.py 依赖自检列表去掉这两个名字(已并入 music_api) - pyproject include 去掉两个顶层文件名(music_api 目录已覆盖) 验证: - 11 + 3 个符号在新位置全部 hasattr 通过;podcast_api / qr_login 已 ModuleNotFoundError;6 个调用方模块均可 import;services 依赖自检仍生效 - 门禁:ruff 0 · pyright 0 errors/0 warnings · pytest 184 passed - 真实 uvicorn 冒烟 10/10,含 /podcast/parse 与 /podcast/hot 返回 401 (模块导入失败会是 500,路由缺失会是 404,401 证明两者都正常) - 生产 data/ 指纹 before == after
169 lines
6.4 KiB
Python
169 lines
6.4 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""播客端点。
|
|
|
|
端点(免费解析类,需登录,不扣次数):
|
|
- 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
|
|
|
|
说明:music_api.podcast 是同步模块(底层 core.sync_http),此处以 asyncio.to_thread 包装,
|
|
让阻塞的上游调用不占用事件循环——行为不变,且不阻塞其它请求。
|
|
"""
|
|
import asyncio
|
|
from typing import Annotated
|
|
|
|
from fastapi import APIRouter, Depends, Request
|
|
|
|
from core import media
|
|
from music_api import APIException, podcast
|
|
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.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.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.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.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.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.get_categories)
|
|
except APIException:
|
|
categories = []
|
|
# 满页视为可能还有更多
|
|
return success({'radios': radios, 'categories': categories,
|
|
'has_more': len(radios) >= limit}, '获取热门播客成功')
|