- backend-site/cms.py(新):账号(scrypt 加盐哈希)、服务端会话(只存哈希,30 天滑动,可撤销)、 admin/admin 首次登录强制改密(改密前其它接口一律 403)、CSRF / 来源 / https / 登录冷却、 内容校验、发布写 content/ 与 prices.json / payinfo.json、版本与回滚、传图核验 + 去元数据 + ffmpeg 缩略图 - server.py 把 /api/cms/* 交给 cms.py;admin.py 加 user list/add/passwd/reset/disable/enable/sessions - portal/admin/(新):内容后台页面;门户顶栏加不带字的淡色铅笔入口 - 门户 / 下单页读 content/site.js、order/content/order.js(代码里的数据降级为兜底);?preview=1 预览草稿 - portal/assets/universe/layout.js(新):新点亮的世界线自动排到中圈不挤的位置、补给线接附近的星、已有的都不动 - planets.js:加 10 种卡通预设(类地 / 海洋 / 丛林 / 荒漠 / 冻原 / 熔岩 / 毒雾 / 荒芜岩球 / 冰巨星 / 带环巨星) - galaxy.js:名牌 / 档案卡文字一律转义 - tests/内容后台测试.py(75 条);回归 27 + 数据库 38 照旧全过;端到端浏览器 36 条 - 文档:交接文档-2026-10.md(变更 / 接口 / 部署 7.1b / 测试 / 第 10 节)、内容后台设计.md(实现对照)、星系图交接说明、nginx 片段 ④ Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
636 lines
30 KiB
Python
636 lines
30 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
金钻工坊 · 渲染下单 —— 管理工具(**只在本机跑**,不开公网入口)
|
||
|
||
python3 admin.py gen 50 --batch 2026-09-30 --value 6 批量生成 50 个码(导出 CSV)
|
||
python3 admin.py gen 1 --tpl wheat --n-fix 3 张数卡密:这张码只能出 3 张
|
||
python3 admin.py edit <卡密> --n-fix 5 / --unlimited / --lock-tpl / --off
|
||
改一张还没用掉的卡密(张数/锁模板/停用)
|
||
python3 admin.py codes [--used|--unused] 看码库
|
||
python3 admin.py ls [waiting|working|done|failed] 看订单
|
||
python3 admin.py show <订单号> 看单详情
|
||
python3 admin.py retry <订单号> 把单子退回队列重渲
|
||
python3 admin.py calls 看「呼叫金钻」记录
|
||
python3 admin.py sweep 清理超过保留期的成品
|
||
python3 admin.py stat 概览
|
||
python3 admin.py db [check|backup|export [目录]] 数据库:体检 / 热备份 / 导回旧版 JSON
|
||
python3 admin.py user list 内容后台:有哪些账号、最近登录
|
||
python3 admin.py user add <用户名> [--email 邮箱] [--temp] 建账号(密码隐藏输入两遍;--temp = 发临时密码、首次登录必须改)
|
||
python3 admin.py user passwd <账号> 直接设新密码(这个账号所有会话作废)
|
||
python3 admin.py user reset <账号> [--to-admin] 忘了密码:会话全作废 → 临时密码 → 下次登录必须改
|
||
python3 admin.py user disable|enable <账号> 停用 / 启用(停用时会话全作废)
|
||
python3 admin.py user sessions <账号> [--revoke-all] 在哪些设备登录着 / 全部踢掉
|
||
python3 admin.py audit [行数] 看兑换码失败/被拒记录
|
||
"""
|
||
import csv, json, os, shutil, sys, time
|
||
from datetime import datetime, timedelta
|
||
|
||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||
import server as S # noqa: E402
|
||
|
||
|
||
def cmd_gen(argv):
|
||
# ⚠️ 2026-10-01 实踩:`gen --help` 会被当成普通参数 → **直接生成 10 张真码**。
|
||
# 管理工具绝不能"看个帮助就产生副作用"。
|
||
if any(a in ("-h", "--help") for a in argv):
|
||
print("""gen 用法:
|
||
gen 50 生成 50 张(一张码一张图)
|
||
gen 20 --platform 爱发电 打平台标记(买家填码时会显示来源并预选模板)
|
||
gen 20 --n-fix 1 固定张数:这张码只能出 1 张
|
||
gen 5 --n-free 不限张数
|
||
gen 20 --unlimited --direct 不限张数 + 直发(不用确认收货,直接给原图)
|
||
gen 10 --tpl wheat 预选模板(买家填码自动勾上)
|
||
gen 20 --platform 爱发电 --n-fix 1 --export payplatform.txt
|
||
★ 顺手导出「一行一码」纯文本,直接贴进爱发电的自动发货卡池""")
|
||
return 0
|
||
n = int(argv[0]) if argv and argv[0].isdigit() else 10
|
||
batch, value, platform, tpl, is_set, direct = "", 6, "", "", False, False
|
||
n_fix, n_max, lock_tpl, n_free, export = 0, 0, False, False, ""
|
||
for i, a in enumerate(argv):
|
||
if a == "--batch" and i + 1 < len(argv):
|
||
batch = argv[i + 1]
|
||
if a == "--value" and i + 1 < len(argv):
|
||
value = argv[i + 1]
|
||
# 第三方平台的标记:闲鱼 / B站工坊 …(金钻 2026-09-30)
|
||
# 买家填码时页面会显示「来自闲鱼 · 麦田萤火」并自动预选模板,不用他自己挑
|
||
if a == "--platform" and i + 1 < len(argv):
|
||
platform = argv[i + 1]
|
||
# --export 文件名:导出一份「一行一码」的纯文本。
|
||
# 金钻 2026-10-01(P4):爱发电的「自动发货」= 你填一池子卡密,买家付款它自己发一张。
|
||
# 这里直接产出能整段粘进去的文本,省掉手工挑码。
|
||
if a in ("--export", "--dlv") and i + 1 < len(argv):
|
||
export = argv[i + 1]
|
||
if a == "--tpl" and i + 1 < len(argv):
|
||
tpl = argv[i + 1]
|
||
# --set = 套装卡密:一张码管一整套(全部皮肤 × 全部模板)
|
||
if a == "--set":
|
||
is_set = True
|
||
# --direct = 金钻自己发的码(个人收款卖的):不用等确认收货,看完预览直接下
|
||
if a == "--direct":
|
||
direct = True
|
||
# 张数卡密(金钻 2026-09-30 晚):
|
||
# --n-fix 3 → 这张码**只能出 3 张**(模板随便改,张数不能多也不能少)
|
||
# --n-max 10 → 最多 10 张(不限张数也可以封个顶)
|
||
# --lock-tpl → 码里带的模板锁死,买家不能改
|
||
if a in ("--n-fix", "--n-max") and i + 1 < len(argv):
|
||
try:
|
||
if a == "--n-fix":
|
||
n_fix = int(argv[i + 1])
|
||
else:
|
||
n_max = int(argv[i + 1])
|
||
except ValueError:
|
||
print("❌ %s 要跟一个整数" % a)
|
||
return
|
||
if a == "--lock-tpl":
|
||
lock_tpl = True
|
||
# --unlimited → 不限张数(买家想出几张出几张;老规矩「一张码一张图」也解除)
|
||
if a == "--unlimited":
|
||
n_free = True
|
||
# --tpl 支持逗号分隔多个(套装卡密:一张码预选一组模板)
|
||
tpl_list = [x.strip() for x in tpl.split(",") if x.strip()]
|
||
bad = [x for x in tpl_list if x not in S.TPL_KEYS]
|
||
if bad:
|
||
print("❌ 模板 key 不认识:%s\n 可选:%s" % (",".join(bad), " / ".join(S.TPL_KEYS)))
|
||
return
|
||
tpl = ",".join(tpl_list)
|
||
if lock_tpl and not tpl:
|
||
print("❌ --lock-tpl 要跟 --tpl 一起用(没有模板,锁什么?)")
|
||
return
|
||
if n_free and n_fix:
|
||
print("❌「不限张数」和「固定张数」只能选一个")
|
||
return
|
||
made = S.gen_codes(n, batch, value, platform, tpl, is_set=is_set, direct=direct,
|
||
n_fix=n_fix, n_max=n_max, lock_tpl=lock_tpl, n_free=n_free)
|
||
stamp = S.now().strftime("%Y%m%d-%H%M%S")
|
||
out = os.path.join(S.ROOT, "exports", "codes-%s.csv" % stamp)
|
||
os.makedirs(os.path.dirname(out), exist_ok=True)
|
||
# ⚠️ 同一秒连开两批会撞名互相覆盖(2026-09-30 实踩)→ 撞了就在后面加 -2/-3
|
||
n_dup = 1
|
||
while os.path.exists(out):
|
||
n_dup += 1
|
||
out = os.path.join(S.ROOT, "exports", "codes-%s-%d.csv" % (stamp, n_dup))
|
||
with open(out, "w", newline="", encoding="utf-8-sig") as f:
|
||
w = csv.writer(f)
|
||
w.writerow(["兑换码", "面额", "批次", "平台", "模板", "固定张数", "不限张数",
|
||
"最多张数", "锁定模板"])
|
||
for c in made:
|
||
w.writerow([c, value, batch, platform, tpl, n_fix or "",
|
||
"是" if n_free else "", n_max or "", "是" if lock_tpl else ""])
|
||
print("已生成 %d 个兑换码(面额 ¥%s,批次 %s,平台 %s,模板 %s%s%s%s%s)"
|
||
% (len(made), value, batch or "-", platform or "-", tpl or "-",
|
||
",★套装(一张管一整套)" if is_set else "",
|
||
",◆直发(不用等收货)" if direct else "",
|
||
(",张数固定 %d 张" % n_fix) if n_fix
|
||
else ((",不限张数" if n_free else ",最多 %d 张" % n_max) if (n_free or n_max) else ",一张码一张图"),
|
||
",🔒模板锁定不能改" if lock_tpl else ""))
|
||
for c in made:
|
||
print(" " + c)
|
||
print("\nCSV: %s" % out)
|
||
|
||
# ---- 发卡文本(金钻 2026-10-01 P4:爱发电/闲鱼「自动发货」直接整段粘)----
|
||
if export:
|
||
ex_dir = os.path.join(S.ROOT, "exports")
|
||
os.makedirs(ex_dir, exist_ok=True)
|
||
p = export if os.path.isabs(export) else os.path.join(ex_dir, export)
|
||
with open(p, "w", encoding="utf-8") as f:
|
||
f.write("\n".join(made) + "\n")
|
||
os.chmod(p, 0o640)
|
||
print("""
|
||
发卡文本: %s (%d 行,一行一码,可直接整段粘贴)
|
||
▸ 爱发电:创作中心 → 商品 → 编辑 → 发货方式「自动发货」→ 把那几行粘进去 → 保存
|
||
买家付款后爱发电自动发一张给他,他到 shop.example.com/order/ 点「卡密下单」填码就行
|
||
▸ 闲鱼/B站工坊:发货时复制一行发给买家
|
||
⚠️ 这份文本等于钱,别发群里、别进公开仓库(已设 640 权限)""" % (p, len(made)))
|
||
return 0
|
||
|
||
|
||
def cmd_codes(argv):
|
||
codes = S.load_codes()
|
||
flt = argv[0] if argv else ""
|
||
for c, v in sorted(codes.items()):
|
||
if flt == "--used" and not v.get("used"):
|
||
continue
|
||
if flt == "--unused" and v.get("used"):
|
||
continue
|
||
q = ("固定 %d 张" % v["n_fix"]) if v.get("n_fix") else \
|
||
("不限张数" if v.get("n_free") else (("最多 %d 张" % v["n_max"]) if v.get("n_max") else "1 码 1 张"))
|
||
stt = {"active": "可用", "bound": "已激活", "used": "已核销",
|
||
"inactive": "停用"}.get(S.code_state(v), "?")
|
||
tags = "%s%s%s%s" % (
|
||
("【%s】" % v["platform"]) if v.get("platform") else "",
|
||
("【%s】" % v["tpl"]) if v.get("tpl") else "",
|
||
"🔒" if v.get("lock_tpl") else "",
|
||
"◆直发" if v.get("direct") else "")
|
||
print("%s %-6s 张数=%-8s %s 订单=%s %s" % (
|
||
c, stt, q, tags, v.get("order") or "-",
|
||
v.get("ts") or v.get("bound_at") or ""))
|
||
stc = [S.code_state(v) for v in codes.values()]
|
||
print("\n合计 %d 张:可用 %d / 已激活 %d / 已核销 %d / 停用 %d"
|
||
% (len(codes), stc.count("active"), stc.count("bound"),
|
||
stc.count("used"), stc.count("inactive")))
|
||
|
||
|
||
def cmd_edit(argv):
|
||
"""改一张还没用掉的卡密(张数 / 锁定模板 / 直发 / 停用…)。
|
||
|
||
金钻 2026-09-30 晚:「这个也给你开 api,方便我管理和你介入」
|
||
用法:
|
||
admin.py edit <卡密> --n-fix 5 固定出 5 张(不能多也不能少)
|
||
admin.py edit <卡密> --unlimited 改成不限张数
|
||
admin.py edit <卡密> --n-max 20 封顶 20 张
|
||
admin.py edit <卡密> --lock-tpl 模板锁死(要码里已有模板)
|
||
admin.py edit <卡密> --unlock-tpl 解锁模板
|
||
admin.py edit <卡密> --tpl wheat,sakura 换一组模板
|
||
admin.py edit <卡密> --off / --on 停用 / 启用
|
||
"""
|
||
if not argv:
|
||
print(cmd_edit.__doc__)
|
||
return
|
||
code, p = argv[0], {}
|
||
for i, a in enumerate(argv):
|
||
nxt = argv[i + 1] if i + 1 < len(argv) else None
|
||
if a == "--n-fix" and nxt:
|
||
p["n_fix"] = nxt
|
||
elif a == "--n-max" and nxt:
|
||
p["n_max"] = nxt
|
||
elif a == "--unlimited":
|
||
p["unlimited"] = True
|
||
elif a == "--tpl" and nxt:
|
||
p["tpls"] = [x.strip() for x in nxt.split(",") if x.strip()]
|
||
elif a == "--lock-tpl":
|
||
p["lock_tpl"] = True
|
||
elif a == "--unlock-tpl":
|
||
p["lock_tpl"] = False
|
||
elif a == "--direct":
|
||
p["direct"] = True
|
||
elif a == "--no-direct":
|
||
p["direct"] = False
|
||
elif a == "--set":
|
||
p["set"] = True
|
||
elif a == "--no-set":
|
||
p["set"] = False
|
||
elif a == "--off":
|
||
p["state"] = "inactive"
|
||
elif a == "--on":
|
||
p["state"] = "active"
|
||
elif a == "--platform" and nxt:
|
||
p["platform"] = nxt
|
||
if not p:
|
||
print("没给要改什么 —— 看用法:")
|
||
print(cmd_edit.__doc__)
|
||
return
|
||
ok, e, info = S.edit_code(code, p)
|
||
if not ok:
|
||
print("❌ " + e)
|
||
return
|
||
print("✅ %s 改好了:张数 %s | 模板 %s%s | 直发 %s | 状态 %s"
|
||
% (info["code"],
|
||
(("固定 %d 张" % info["n_fix"]) if info["n_fix"]
|
||
else (("最多 %d 张" % info["n_max"]) if info["n_max"] else "不限")),
|
||
",".join(info["tpls"]) or "自由选",
|
||
"(🔒锁定)" if info["lock_tpl"] else "",
|
||
"是" if info["direct"] else "否", info["state"]))
|
||
|
||
|
||
def cmd_ls(argv):
|
||
st = argv[0] if argv else None
|
||
rows = S.list_orders((st,) if st else None)
|
||
if not rows:
|
||
print("(没有订单)")
|
||
return
|
||
for m in sorted(rows, key=lambda x: x.get("created") or ""):
|
||
print("%-10s %-8s %-19s %d 张 %s %s" % (
|
||
m["oid"], m.get("state"), m.get("created", ""),
|
||
len(m.get("templates") or []), m.get("arm"),
|
||
",".join(m.get("templates") or [])))
|
||
print("\n共 %d 单" % len(rows))
|
||
|
||
|
||
def cmd_show(argv):
|
||
if not argv:
|
||
sys.exit("用法: admin.py show <订单号>")
|
||
m = S.read_meta(argv[0])
|
||
if not m:
|
||
sys.exit("没有这个订单")
|
||
m2 = dict(m)
|
||
m2.pop("token", None)
|
||
print(json.dumps(m2, ensure_ascii=False, indent=1))
|
||
|
||
|
||
def cmd_retry(argv):
|
||
if not argv:
|
||
sys.exit("用法: admin.py retry <订单号>")
|
||
oid = argv[0]
|
||
m = S.read_meta(oid)
|
||
if not m:
|
||
sys.exit("没有这个订单")
|
||
with S.LOCK: # 跟服务器进程抢同一个 meta.json(2026-10-05 外部复查:原来不加锁)
|
||
m = S.read_meta(oid) or m
|
||
m["state"] = "waiting"
|
||
m["note"] = "管理员退回重渲"
|
||
m["started"] = m["finished"] = None
|
||
S.write_meta(oid, m)
|
||
print("%s 已退回队列" % oid)
|
||
|
||
|
||
def cmd_db(argv):
|
||
"""数据库(<DATA_DIR>/ys.db,2026-10-05 起)。服务器不用停。"""
|
||
sub = (argv or ["check"])[0]
|
||
if sub == "check":
|
||
ok, n, imp = S.STORE.check()
|
||
print("库文件:%s" % S.STORE.path)
|
||
print("完整性:%s" % ok)
|
||
for k, v in n.items():
|
||
print(" %-10s %d 行" % (k, v))
|
||
print("订单(按状态):%s" % (S.STORE.order_counts() or "无"))
|
||
print("卡密(按状态):%s" % (S.STORE.code_counts() or "无"))
|
||
print("旧数据导入:%s" % (imp or "(没导过)"))
|
||
elif sub == "backup":
|
||
print("备份好了:%s" % S.STORE.backup())
|
||
elif sub == "export":
|
||
print("已导出到 %s" % S.STORE.export_legacy(argv[1] if len(argv) > 1 else None))
|
||
else:
|
||
print("用法:admin.py db [check|backup|export [目录]]")
|
||
|
||
|
||
def cmd_user(argv):
|
||
"""内容后台的账号(2026-10-05)。账号只能在服务器上用命令行建 —— 网页上没有注册入口。"""
|
||
import getpass
|
||
from datetime import datetime as _dt
|
||
sub, rest = (argv[0] if argv else "list"), argv[1:]
|
||
C = S.CMS
|
||
fmt = lambda ts: _dt.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M") if ts else "从没登录过"
|
||
|
||
def ask_pw():
|
||
a = getpass.getpass("新密码(至少 %d 位):" % S.cms.MIN_PW)
|
||
if getpass.getpass("再输一遍:") != a:
|
||
sys.exit("两次输的不一样")
|
||
p = S.cms.pw_problem(a)
|
||
if p:
|
||
sys.exit(p)
|
||
return a
|
||
try:
|
||
if sub == "list":
|
||
for u in C.users():
|
||
print("%-16s %-28s %s%s 最近登录 %s(%s) 登录着 %d 台" % (
|
||
u["user"], u["email"] or "-", "【待改密】" if u["must_change"] else "", "【已停用】" if u["disabled"] else "",
|
||
fmt(u["last_login"]), u["last_ip"] or "-", u["sessions"]))
|
||
elif sub == "add" and rest:
|
||
email = rest[rest.index("--email") + 1] if "--email" in rest else None
|
||
import re as _re # 先校验,再问密码(不然填了半天密码才告诉你用户名不行)
|
||
if not _re.match(r"^[A-Za-z0-9_.-]{2,32}$", rest[0]):
|
||
sys.exit("用户名只能是 2–32 位字母、数字、点、横线、下划线")
|
||
if C.user_row(rest[0]) or (email and C.user_row(email)):
|
||
sys.exit("用户名或邮箱已经有人用了")
|
||
if "--temp" in rest:
|
||
import secrets as _sec
|
||
pw = _sec.token_urlsafe(9)
|
||
C.user_add(rest[0], pw, email, must_change=True)
|
||
print("建好了。临时密码:%s\n(只显示这一次;他第一次登录必须改密码)" % pw)
|
||
else:
|
||
C.user_add(rest[0], ask_pw(), email)
|
||
print("建好了:%s" % rest[0])
|
||
elif sub == "passwd" and rest:
|
||
name = C.user_set_password(rest[0], ask_pw())
|
||
C.audit("命令行", "-", "设了 %s 的新密码(所有会话已作废)" % name)
|
||
print("改好了;%s 所有登录着的设备都已退出" % name)
|
||
elif sub == "reset" and rest:
|
||
tmp = C.user_reset(rest[0], to_admin="--to-admin" in rest)
|
||
print("重置好了。临时密码:%s\n所有会话已作废;下次登录必须改密码。(临时密码只显示这一次)" % tmp)
|
||
elif sub in ("disable", "enable") and rest:
|
||
C.user_disable(rest[0], off=(sub == "disable"))
|
||
print("已%s:%s" % ("停用" if sub == "disable" else "启用", rest[0]))
|
||
elif sub == "sessions" and rest:
|
||
if "--revoke-all" in rest:
|
||
print("踢掉了 %d 个会话" % C.revoke_all(rest[0]))
|
||
else:
|
||
r = C.user_row(rest[0])
|
||
if not r:
|
||
sys.exit("没有这个账号")
|
||
rows = C.sessions_of(r[0])
|
||
if not rows:
|
||
print("(没有登录着的设备)")
|
||
for s in rows:
|
||
print("%s 最近 %s %s %s%s" % (s["id"], fmt(s["last"]), s["ip"], (s["ua"] or "")[:50], " 记住我" if s["remember"] else ""))
|
||
else:
|
||
print(__doc__)
|
||
except S.cms.Bad as e:
|
||
sys.exit(str(e))
|
||
|
||
|
||
def cmd_calls(argv):
|
||
rows = S.STORE.calls() # 数据库 calls 表(2026-10-05 起;calls.jsonl 只是给手机通知的副本)
|
||
if not rows:
|
||
print("(没有呼叫记录)")
|
||
for r in rows:
|
||
print("%s 订单=%s IP=%s %s %s" % (r.get("ts"), r.get("order") or "-", r.get("ip"),
|
||
"已通知" if r.get("notified") else "未通知", r.get("kind") or "呼叫"))
|
||
|
||
|
||
def cmd_sweep(argv):
|
||
"""清过期成品 + **核销卡密**(金钻 2026-09-30 晚:「核销要等开放下载后 72 小时」)。
|
||
|
||
到期口径改用 S.expire_at():确认收货/直发出图之后 72 小时(没开放下载的用创建时间兜底)。
|
||
⚠️ 删文件之前先把卡密核销 —— 否则文件没了、码还挂在「已激活」,账永远对不上。
|
||
"""
|
||
n = freed = settled = 0
|
||
for oid in S.STORE.order_ids():
|
||
d = S.order_dir(oid)
|
||
m = S.read_meta(oid)
|
||
if not m:
|
||
continue
|
||
# ⚠️ 2026-10-05(外部复查):**还在流水线上的单绝不删**。
|
||
# expire_at() 对没开放下载的单用「创建时间 + 72h」兜底 —— 渲染机关了三天(出差 / 断网),
|
||
# 排队中的单、买家报了付款等确认的单,都会在这里被整目录删掉,码还被记成「已核销」:
|
||
# 钱收了、皮肤没了、图也没出。只清已经走完(done / failed / void)或一直没付款(unpaid)的。
|
||
if m.get("state") in ("waiting", "working", "paid"):
|
||
continue
|
||
exp = S.expire_at(m)
|
||
if exp is None or exp > datetime.now(S.CST):
|
||
continue
|
||
settled += S.settle_codes(oid, "订单到期清理(开放下载满 %dh)" % S.KEEP_HOURS)
|
||
for root, _, files in os.walk(d):
|
||
for f in files:
|
||
try:
|
||
freed += os.path.getsize(os.path.join(root, f))
|
||
except OSError:
|
||
pass
|
||
S.purge_order(oid) # 删文件;库里那一行留着记账(之后当它不存在)
|
||
n += 1
|
||
# 文件还在、但开放下载已满 72 小时的,也一起核销
|
||
settled += sum(x[1] for x in S.settle_due())
|
||
print("清理 %d 单,释放 %.1f MB,核销卡密 %d 张" % (n, freed / 1048576, settled))
|
||
|
||
|
||
def cmd_audit(argv):
|
||
n = int(argv[0]) if argv and argv[0].isdigit() else 40
|
||
try:
|
||
lines = [l for l in open(S.LOG_FILE, encoding="utf-8").read().splitlines()
|
||
if ("兑换码失败" in l or "拒绝" in l)]
|
||
except OSError:
|
||
lines = []
|
||
for l in lines[-n:]:
|
||
print(l)
|
||
print("\n共 %d 条异常记录" % len(lines))
|
||
|
||
|
||
def cmd_activate(argv):
|
||
"""网页下单:买家付了款,激活这一单 → 进队列开渲。"""
|
||
oid = (argv[0] if argv else "").strip().upper()
|
||
if not oid:
|
||
print("用法: activate <订单号>")
|
||
return
|
||
m = S.read_meta(oid)
|
||
if not m:
|
||
print("没有这个订单:%s" % oid)
|
||
return
|
||
st = m.get("state")
|
||
if st not in ("unpaid", "paid"):
|
||
print("订单 %s 现在是「%s」,不是待付款,没动它" % (oid, st))
|
||
return
|
||
m["state"] = "waiting"
|
||
m["paid_at"] = S.now().isoformat(timespec="seconds")
|
||
with S.LOCK:
|
||
S.write_meta(oid, m)
|
||
print("✅ 订单 %s 已激活 → 进入排队" % oid)
|
||
print(" 模板:%s | 分辨率:%s | 码:%s"
|
||
% (",".join(m.get("templates") or []), m.get("res"), ",".join(m.get("codes") or [])))
|
||
|
||
|
||
def cmd_pending(argv):
|
||
"""列出待付款的网页单(等你收钱激活的)"""
|
||
rows = S.list_orders(("unpaid", "paid"))
|
||
if not rows:
|
||
print("没有待付款 / 待激活的网页单")
|
||
return
|
||
for m in rows:
|
||
tag = "★买家已报付款" if m.get("state") == "paid" else "还没付款"
|
||
print("%s %-12s ¥%-5s %s 张 %s 码 %s"
|
||
% (m["oid"], tag, m.get("amount") or (S.PRICE_UNIT * len(m.get("templates") or [] or [1])),
|
||
len(m.get("templates") or []), ",".join(m.get("templates") or []),
|
||
",".join(m.get("codes") or [])))
|
||
print("\n共 %d 单 —— 确认到账后跑:python3 admin.py activate <订单号>" % len(rows))
|
||
|
||
|
||
def cmd_stat(argv):
|
||
codes = S.load_codes()
|
||
st = [S.code_state(v) for v in codes.values()]
|
||
print("卡密 %d 张(可用 %d / 已激活 %d / 已核销 %d / 停用 %d)"
|
||
% (len(codes), st.count("active"), st.count("bound"),
|
||
st.count("used"), st.count("inactive")))
|
||
hb = S.heartbeat()
|
||
print("渲染机 %s 最后心跳 %s" % ("在线" if hb["online"] else "离线", hb["last_seen"]))
|
||
for st in ("unpaid", "paid", "waiting", "working", "done", "failed"):
|
||
print("订单 %-8s %d" % (st, len(S.list_orders((st,)))))
|
||
total = 0
|
||
for root, _, files in os.walk(S.ROOT):
|
||
for f in files:
|
||
try:
|
||
total += os.path.getsize(os.path.join(root, f))
|
||
except OSError:
|
||
pass
|
||
print("数据占用 %.1f MB" % (total / 1048576))
|
||
|
||
|
||
def cmd_price(argv):
|
||
"""价格档位(金钻 2026-10-01:「按张数和优惠设置专属购买价格链接」)
|
||
|
||
看: python3 admin.py price
|
||
设: python3 admin.py price set 3 15 http<WIN-PATH>
|
||
(第 3 档 = 买 3 张 ¥15,付款按钮就跳这个商品链接;链接可省 = 用总链接)
|
||
删: python3 admin.py price rm 3
|
||
单价: python3 admin.py price per 6 (没配档位的张数按这个算)
|
||
"""
|
||
d = S.price_tiers()
|
||
tiers = d.get("tiers") or {}
|
||
if not argv:
|
||
print("单价(没配档位时):¥%g/张" % d["per"])
|
||
print("%-6s %-8s %s" % ("张数", "价格", "专属商品链接"))
|
||
for k in sorted(tiers, key=lambda x: int(x) if x.isdigit() else 99):
|
||
t = tiers[k] or {}
|
||
print("%-6s ¥%-7s %s" % (k, t.get("price"), t.get("payplatform") or "(用总链接)"))
|
||
if not tiers:
|
||
print("(还没配任何档位)")
|
||
print("\n设一档:python3 admin.py price set 3 15 http<WIN-PATH>")
|
||
return
|
||
sub = argv[0]
|
||
if sub == "per" and len(argv) > 1:
|
||
d["per"] = float(argv[1])
|
||
elif sub == "set" and len(argv) > 2:
|
||
n, price = argv[1], argv[2]
|
||
if not n.isdigit() or int(n) < 1:
|
||
raise SystemExit("张数要正整数")
|
||
tiers[n] = {"price": float(price), "payplatform": (argv[3] if len(argv) > 3 else "").strip()}
|
||
elif sub == "rm" and len(argv) > 1:
|
||
tiers.pop(argv[1], None)
|
||
else:
|
||
raise SystemExit("用法:price / price per N / price set N 价格 [链接] / price rm N")
|
||
d["tiers"] = tiers
|
||
S.jsave(S.PRICES_FILE, d)
|
||
try:
|
||
os.chmod(S.PRICES_FILE, 0o644)
|
||
except OSError:
|
||
pass
|
||
print("改好了 —— 现在:")
|
||
cmd_price([])
|
||
|
||
|
||
def cmd_gift(argv):
|
||
"""福利券(金钻 2026-10-01「赛博鸡蛋」):一批**免费、免付费、只限张数**的码,买家自取。
|
||
|
||
看: python3 admin.py gift
|
||
开一批:python3 admin.py gift new 赛博鸡蛋 --count 50 --n-fix 1
|
||
加 --tpl sakura --lock → 只让领的人试这个新模板(试玩券)
|
||
加 --days 7 → 7 天后自动收摊
|
||
加 --no-direct → 领到的券也要走「确认收货」才给原图(默认直发)
|
||
补货:python3 admin.py gift add <批次id> --count 20
|
||
收摊:python3 admin.py gift off <批次id> (已领到手的券不受影响)
|
||
|
||
⚠️ 建/补/收的逻辑全在 server.py(gift_batch_new / gift_batch_add / gift_batch_off)——
|
||
金钻电脑上那块**面板**(ys_admin.py 的「免费码」区块)调的是同一批函数。
|
||
**改规则只改 server.py 那一处**,别在这儿再写一遍(两边必漂移)。
|
||
"""
|
||
|
||
def show_all():
|
||
rows = S.gift_batches()["batches"] # 每次现读:刚建/补完的批次要立刻看见
|
||
if not rows:
|
||
print("(还没有福利券批次)")
|
||
return
|
||
print("%-16s %-16s %-6s %-6s %-8s %s" % ("批次", "名字", "总数", "已领", "还剩", "限制"))
|
||
for b in rows:
|
||
st = S.gift_stat(b["id"])
|
||
lim = "%d 张/人" % int(b.get("each") or 1)
|
||
lim += ",锁模板 %s" % b["tpl"] if b.get("lock_tpl") else ""
|
||
lim += ",%s 到期" % b["expire"] if b.get("expire") else ""
|
||
if not b.get("enabled", True):
|
||
lim += "(已收摊)"
|
||
print("%-16s %-16s %-6d %-6d %-8d %s"
|
||
% (b["id"], b.get("name") or "", st["total"], st["claimed"], st["left"], lim))
|
||
|
||
if not argv:
|
||
show_all()
|
||
return
|
||
sub = argv[0]
|
||
if sub == "new" and len(argv) > 1:
|
||
name = argv[1]
|
||
op = {"count": 20, "n-fix": 1, "each": 1, "tpl": "", "lock": False,
|
||
"days": 0, "note": "", "direct": True, "kind": "render", "free": False}
|
||
i = 2
|
||
while i < len(argv):
|
||
a = argv[i]
|
||
if a == "--count" and i + 1 < len(argv):
|
||
op["count"] = int(argv[i + 1]); i += 2
|
||
elif a == "--n-fix" and i + 1 < len(argv):
|
||
op["n-fix"] = int(argv[i + 1]); i += 2
|
||
elif a == "--each" and i + 1 < len(argv):
|
||
op["each"] = int(argv[i + 1]); i += 2
|
||
elif a == "--tpl" and i + 1 < len(argv):
|
||
op["tpl"] = argv[i + 1]; i += 2
|
||
elif a == "--days" and i + 1 < len(argv):
|
||
op["days"] = int(argv[i + 1]); i += 2
|
||
elif a == "--note" and i + 1 < len(argv):
|
||
op["note"] = argv[i + 1]; i += 2
|
||
elif a == "--lock":
|
||
op["lock"] = True; i += 1
|
||
elif a == "--kind" and i + 1 < len(argv):
|
||
op["kind"] = argv[i + 1]; i += 2 # render/standee/keychain/poster…
|
||
elif a == "--n-free":
|
||
op["free"] = True; i += 1 # 不限张数
|
||
elif a == "--no-direct":
|
||
op["direct"] = False; i += 1
|
||
else:
|
||
i += 1
|
||
try:
|
||
bid, codes = S.gift_batch_new(
|
||
name, count=op["count"], n_fix=op["n-fix"], n_free=op["free"],
|
||
tpl=op["tpl"], lock_tpl=op["lock"], days=op["days"],
|
||
note=op["note"], kind=op["kind"], direct=op["direct"], each=op["each"])
|
||
except ValueError as e:
|
||
raise SystemExit(str(e))
|
||
print("批次 id:%s(把这个贴给别人也行:福利页会自动列出来)" % bid)
|
||
print("生了 %d 张券。" % len(codes))
|
||
show_all()
|
||
elif sub == "add" and len(argv) > 1:
|
||
bid = argv[1]
|
||
n, direct = 20, None
|
||
i = 2
|
||
while i < len(argv):
|
||
if argv[i] == "--count" and i + 1 < len(argv):
|
||
n = int(argv[i + 1]); i += 2
|
||
elif argv[i] == "--no-direct":
|
||
direct = False; i += 1
|
||
elif argv[i] == "--direct":
|
||
direct = True; i += 1
|
||
else:
|
||
i += 1
|
||
try:
|
||
got = S.gift_batch_add(bid, n, direct=direct)
|
||
except ValueError as e:
|
||
raise SystemExit(str(e))
|
||
print("补了 %d 张(批次 %s)" % (len(got), bid))
|
||
show_all()
|
||
elif sub == "off" and len(argv) > 1:
|
||
try:
|
||
S.gift_batch_off(argv[1])
|
||
except ValueError as e:
|
||
raise SystemExit(str(e))
|
||
print("已收摊(已领到手的券照常用):%s" % argv[1])
|
||
show_all()
|
||
else:
|
||
raise SystemExit("用法见文件头注释")
|
||
|
||
|
||
CMDS = {"gen": cmd_gen, "codes": cmd_codes, "ls": cmd_ls, "show": cmd_show,
|
||
"gift": cmd_gift,
|
||
"price": cmd_price,
|
||
"retry": cmd_retry, "calls": cmd_calls, "db": cmd_db, "user": cmd_user, "sweep": cmd_sweep, "stat": cmd_stat,
|
||
"audit": cmd_audit, "activate": cmd_activate, "pending": cmd_pending,
|
||
"edit": cmd_edit}
|
||
|
||
if __name__ == "__main__":
|
||
if len(sys.argv) < 2 or sys.argv[1] not in CMDS:
|
||
print(__doc__)
|
||
sys.exit(1)
|
||
CMDS[sys.argv[1]](sys.argv[2:])
|