Archived
refactor: 拆分 4 个巨石模块为包,清理过时注释并删除作废文档
为什么:单文件 1100~1900 行的巨石模块让「改一处要通读全文」;同时注释里残留 大量已删台账的编号,以及「Flask/FastAPI 双栈迁移期」这类已失实的架构描述, 会误导后来者按不复存在的架构去改代码。 拆分(对外导入路径不变,行为零变更): - music_downloader.py -> music_downloader/(models/downloader/cover/_http/_log/_concurrency) - auth_system.py -> auth_system/(db/security/users/credits/ledger/mail/cards/backup...) - music_api.py -> music_api/(api/client/crypto/qr/cookies/compat/constants/errors) - services/runtime.py -> services/(api_service/_shared/_taskcore/downloads/batch/podcast/ streaming/tasks);services/runtime.py 保留为兼容门面 兼容性做法:各包用 __init__.py 以 __all__ 原样再导出全部符号,既有调用点 (auth_system.xxx / services.xxx / from music_api import Y)零改动;路径常量改为经包属性 动态读取(auth_system.DB_PATH),否则测试的 monkeypatch 会静默失效并写到生产库。 修复 9 处代码损伤(上一轮注释清理把 `()` 当「空括号残留」删掉所致;用「与拆分前逐字 等价」校验逐一定位,静态检查只会报出其中 4 处): - core/config.py ).strip() or '*' - core/state.py threading.Lock() x2 - qr_login.py datetime.now() / .strip() - music_downloader/downloader.py .lower() - services/podcast.py set() / time.time() x2 清理与删除: - 删除 部署文档.md / 功能介绍.md / README_私有包警告.txt - 清理指向已删台账与文档的过时编号注释;把「迁移期 / 两栈 / 双框架 / 已迁移」等 失实描述改写为现状描述(保留 `<-> Flask /path` 映射表等仍有价值的契约来源说明) - _mkpkg.py:公开包剔除清单去掉已不存在的文档名;私有包警告改为自包含 - pyproject.toml:补 pythonpath = ["."],使裸跑 pytest 不再 import core 失败 验证:ruff 全通过;pyright 0 errors / 0 warnings(102 文件);pytest 144 passed; 真实 uvicorn 冒烟 6 条路由符合预期且生产 data/ 指纹未变;忽略注释的逐字等价性校验通过。
This commit is contained in:
1 parent
838d635bc5
commit
6288a98ecc
89 files changed
+5806
-5112
No files matched your search
@@ -0,0 +1,150 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""次数卡密生成 / 兑换 / 管理。
|
||||
|
||||
(自 auth_system.py 拆出,行为与原实现一致。)
|
||||
"""
|
||||
|
||||
import secrets
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from .db import (
|
||||
_DB_LOCK,
|
||||
_q,
|
||||
get_conn,
|
||||
)
|
||||
|
||||
# ============ 卡密 ============
|
||||
|
||||
|
||||
def generate_cards(count: int, credits: int, created_by: str = '',
|
||||
prefix: str = '', note: str = '', valid_days: int = 0) -> list[str]:
|
||||
"""生成次数卡密(credits = 每张卡可下载次数)
|
||||
prefix: 自定义卡密前缀(默认 VIP-)
|
||||
note: 备注信息
|
||||
valid_days: 有效天数(0 = 永久有效,过期后不可兑换)
|
||||
"""
|
||||
count = max(1, min(int(count), 500))
|
||||
prefix = ''.join(ch for ch in (prefix or 'VIP') if ch.isalnum()).upper()[:10] or 'VIP'
|
||||
expire_at = int(time.time()) + int(valid_days) * 86400 if valid_days and int(valid_days) > 0 else 0
|
||||
codes = []
|
||||
with _DB_LOCK:
|
||||
conn = get_conn()
|
||||
try:
|
||||
for _ in range(count):
|
||||
code = prefix + '-' + secrets.token_hex(5).upper()
|
||||
conn.execute(
|
||||
'INSERT INTO cards (code, minutes, created_by, created_at, note, expire_at) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?)',
|
||||
(code, int(credits), created_by, int(time.time()), note or '', expire_at))
|
||||
codes.append(code)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return codes
|
||||
|
||||
|
||||
def list_cards(limit: int = 100, offset: int = 0) -> tuple[list[dict[str, Any]], int]:
|
||||
"""卡密列表(支持分页 limit/offset,管理路由透传)
|
||||
返回 (当页卡密列表, 卡密总数)——总数供前端分页控件用,调用方按元组解包"""
|
||||
limit = max(1, min(int(limit), 500))
|
||||
offset = max(0, int(offset))
|
||||
rows = _q('SELECT * FROM cards ORDER BY id DESC LIMIT ? OFFSET ?', (limit, offset))
|
||||
total_row = _q('SELECT COUNT(*) AS c FROM cards')
|
||||
total = int(total_row[0]['c']) if total_row else 0
|
||||
now = time.time()
|
||||
cards = []
|
||||
for r in rows:
|
||||
d = dict(r)
|
||||
# 过期判定以服务端时钟为准(前端时钟偏差会误标已过期/未使用)
|
||||
d['expired'] = bool(d.get('expire_at') and d['expire_at'] < now)
|
||||
cards.append(d)
|
||||
return cards, total
|
||||
|
||||
|
||||
def set_card_disabled(code: str, disabled: bool) -> None:
|
||||
"""禁用/恢复未使用卡密(已使用卡密无禁用意义,拒绝操作)"""
|
||||
code = (code or '').strip().upper()
|
||||
with _DB_LOCK:
|
||||
conn = get_conn()
|
||||
try:
|
||||
row = conn.execute('SELECT used_by, disabled FROM cards WHERE code = ?', (code,)).fetchone()
|
||||
if not row:
|
||||
raise ValueError('卡密不存在')
|
||||
if row['used_by']:
|
||||
raise ValueError('卡密已被使用,无需禁用')
|
||||
if bool(row['disabled']) == bool(disabled):
|
||||
raise ValueError('卡密已处于该状态')
|
||||
conn.execute('UPDATE cards SET disabled = ? WHERE code = ?',
|
||||
(1 if disabled else 0, code))
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def delete_card(code: str) -> None:
|
||||
"""删除未使用卡密(已使用卡密含兑换凭证:使用者/时间,按 owner 规则不可删)"""
|
||||
code = (code or '').strip().upper()
|
||||
with _DB_LOCK:
|
||||
conn = get_conn()
|
||||
try:
|
||||
row = conn.execute('SELECT used_by FROM cards WHERE code = ?', (code,)).fetchone()
|
||||
if not row:
|
||||
raise ValueError('卡密不存在')
|
||||
if row['used_by']:
|
||||
raise ValueError('已使用的卡密不可删除(保留兑换凭证)')
|
||||
conn.execute('DELETE FROM cards WHERE code = ?', (code,))
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def redeem_card(code: str, username: str) -> tuple[int, int]:
|
||||
"""兑换卡密,返回 (卡密次数, 新剩余次数)(标记已用与加余额同事务,失败整体回滚不吞卡)"""
|
||||
code = (code or '').strip().upper()
|
||||
with _DB_LOCK:
|
||||
conn = get_conn()
|
||||
try:
|
||||
row = conn.execute('SELECT * FROM cards WHERE code = ?', (code,)).fetchone()
|
||||
if not row:
|
||||
raise ValueError('卡密不存在')
|
||||
if row['used_by']:
|
||||
raise ValueError('卡密已被使用')
|
||||
if row['disabled']:
|
||||
raise ValueError('卡密已被禁用,请联系管理员')
|
||||
if row['expire_at'] and row['expire_at'] < time.time():
|
||||
raise ValueError('卡密已过期')
|
||||
# 卡密标记 + 余额增加同事务:任一失败整体回滚,卡密可重试兑换。
|
||||
# WHERE 带 used_by=""/disabled=0 防重标记 + rowcount 校验:命中 0 行
|
||||
# (跨进程并发抢卡)立即回滚报错,绝不出现"未标记已用却加了余额"
|
||||
cur = conn.execute(
|
||||
'UPDATE cards SET used_by = ?, used_at = ? '
|
||||
'WHERE code = ? AND used_by = "" AND disabled = 0',
|
||||
(username, int(time.time()), code))
|
||||
if cur.rowcount != 1:
|
||||
raise ValueError('卡密已被使用')
|
||||
urow = conn.execute('SELECT role, duration_seconds FROM users WHERE username = ?',
|
||||
(username,)).fetchone()
|
||||
if not urow:
|
||||
raise ValueError('用户不存在')
|
||||
minutes = int(row['minutes'])
|
||||
remaining = int(urow['duration_seconds'] or 0)
|
||||
if urow['role'] == 'admin' or remaining == -1:
|
||||
remaining = -1
|
||||
else:
|
||||
remaining = remaining + minutes
|
||||
conn.execute('UPDATE users SET duration_seconds = ? WHERE username = ?',
|
||||
(remaining, username))
|
||||
conn.commit()
|
||||
return minutes, remaining
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
Reference in new issue
Block a user