This repository has been archived on 2026-10-02. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
NeteaseUrl/core/utils.py
T
snowy-yang c2a8da3e43 refactor(core): 抽出框架无关核心层 core/,为 FastAPI 迁移铺路
第一步模块拆分(纯搬运,零行为变化):
- 新增 core/ 包:config(常量/配置) + state(运行时状态) + utils(纯函数) + security(音频签名)
- main.py 改为从 core 导入并以原下划线名再导出,250+ 既有调用点零改动

关键设计:
- 状态全部原地修改,import 即共享同一对象(21 项身份断言 + 10 项冒烟全绿)
- 音频签名密钥由启动时 _init_audio_secret(app.secret_key) 注入,
  解除 core.security 对 Flask app 的依赖,新老应用可互认 token

验证:py_compile 通过;冒烟 10/10 PASS;对象身份 22/22 PASS;
waitress 真实启动 /health 200 version=2.4.0。main.py 减 229 行。
2026-09-26 00:16:04 +08:00

121 lines
4.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""纯函数工具(框架无关,无 Flask/FastAPI 依赖)。
自 main.py 原样迁出:安全整数解析、控制台输出兜底、SRT 时间轴、
LRC→SRT 转换、字段参数解析、163cn.tv 短链展开(含私有缓存)。
"""
import re
import sys
import threading
from typing import Any, Dict, List, Optional
def safe_int(value, default: int) -> int:
"""用户输入的安全整数解析:垃圾值回退默认值(而非 500)"""
try:
return int(value)
except (TypeError, ValueError):
return default
def safe_console_print(text: str) -> None:
"""控制台输出兜底:stdout 被重定向到文件且系统编码非 UTF-8 时
(典型:NSSM 服务日志 + 中文 Windows GBK 控制台),emoji 等字符会触发
UnicodeEncodeError 中断启动流程——实测崩溃循环。此处降级为可编码字符。"""
try:
print(text)
except UnicodeEncodeError:
enc = getattr(sys.stdout, 'encoding', None) or 'ascii'
print(text.encode(enc, errors='replace').decode(enc, errors='replace'))
def srt_time(t: float) -> str:
"""秒 → SRT 时间格式 HH:MM:SS,mmm"""
h = int(t // 3600)
m = int((t % 3600) // 60)
s = int(t % 60)
ms = int(round((t - int(t)) * 1000))
if ms >= 1000:
ms = 999
return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
def format_lyric(lrc: str, lyric_format: str) -> str:
"""将 LRC 歌词转换为指定格式(lrc / srt)
F37:时间轴先规范化再转 SRT——支持一行多时间标签(同句多时段各自成条)、
分钟超两位([100:00])、乱序行(排序后区间不再倒挂)、纯文本行(无时间戳则原样保留)。"""
if lyric_format != 'srt':
return lrc
tag_re = re.compile(r'\[(\d{1,3}):(\d{1,2}(?:[.:]\d+)?)\]')
parsed = []
for line in lrc.split('\n'):
tags = tag_re.findall(line)
text = tag_re.sub('', line).strip()
if not tags:
# 无时间戳的纯文本:保留为 0 时长行不合适,直接附在输出尾部
if text:
parsed.append((None, text))
continue
if not text:
continue
for m, s in tags:
try:
secs = int(m) * 60 + float(s.replace(':', '.'))
except ValueError:
continue
parsed.append((secs, text))
timed = [(t, x) for t, x in parsed if t is not None]
untimed = [x for t, x in parsed if t is None]
if not timed:
return lrc
timed.sort(key=lambda p: p[0])
out = []
for i, (t, text) in enumerate(timed):
end = timed[i + 1][0] if i + 1 < len(timed) else t + 5
if end <= t:
end = t + 1 # 同时间多行:给 1 秒最小区间,不再生成倒挂区间
out.append(f"{i + 1}\n{srt_time(t)} --> {srt_time(end)}\n{text}\n")
if untimed:
out.append('\n'.join(untimed))
return '\n'.join(out)
def parse_meta_fields(raw) -> Optional[List[str]]:
"""解析写入字段参数,空返回 None(表示全部写入)"""
if raw is None or raw == '':
return None
if isinstance(raw, str):
return [f.strip() for f in raw.split(',') if f.strip()] or None
try:
return list(raw) or None
except Exception:
return None
# 短链展开结果缓存:用户反复解析同一分享链接不再重复请求 163cn.tv(有界防膨胀)
_SHORTLINK_CACHE: Dict[str, str] = {}
_SHORTLINK_CACHE_LOCK = threading.Lock()
def expand_shortlink(url: str) -> str:
"""展开 163cn.tv 短链(带进程内缓存;失败原样返回)"""
with _SHORTLINK_CACHE_LOCK:
hit = _SHORTLINK_CACHE.get(url)
if hit is not None:
return hit
expanded = url
try:
import requests
response = requests.get(url, allow_redirects=False, timeout=10)
expanded = response.headers.get('Location', url)
except Exception:
expanded = url
# 第 97 条(P3):展开失败(Location 缺失/网络异常,expanded 原样等于 url)不写
# 缓存——旧口径一次网络抖动会让该分享链接在整个缓存存续期内必然解析失败
if expanded != url:
with _SHORTLINK_CACHE_LOCK:
if len(_SHORTLINK_CACHE) > 500:
_SHORTLINK_CACHE.clear()
_SHORTLINK_CACHE[url] = expanded
return expanded