fix(backend): 复查修复(一码两单 / 回调重放 / 跨进程覆盖 / sweep 误删 等)+ 回执

Browse Source
- submit/activate:查码与绑码同锁(redeem_bind),防并发一码两单
- submit:卡密规则按 max(前端 nTotal, 实际模板数) 与模板并集校验;拒未知模板
- 爱发电回调:发码或激活过一律幂等原样回;回调与账本读写串行(HOOK_LOCK)
- LOCK 加跨进程 flock;jsave 唯一临时文件 + fsync + 沿用权限
- admin.py sweep 不删 waiting/working/paid;retry 加锁
- 卡密/订单号/取件码改用 secrets
- redo 换皮肤走 PNG 核验;feedback 限频 + 磁盘闸 + 只收图片
- 下载/取皮肤边读边发;zip 成品 STORED + 同时只打一个包
- H.finish 与 socketserver.finish 重名 → 改名 finish_upload(路径不变)
- 部分失败:记 plan_total/partial,通知金钻,页面说实话
- /claim 新增 terms_v 字段(只增,渲染机无需改)
- ys_local.py:只接受本机页面的 POST(Host/Origin 校验)
- 两份 回执-Claude.md + tests/回执复现测试.py(原版 13/27 失败,改后全过)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yws
2026-10-05 12:14:02 +00:00
co-authored by Claude Opus 5.5
parent 11eb16ccae
commit 651d21d882
6 changed files with 1164 additions and 116 deletions
+433 -112
View File
@@ -146,9 +146,63 @@ STALE_MIN = 45 # 渲染机领单后超过这么久没交
# zip 先落临时文件再边读边发,**不进内存**(这台机器只有 1.6G,MemoryMax=256M)。
MAX_ZIP_BYTES = 600 * 1024 * 1024 # 一单成品合计超过这个数就拒绝打包,让他分开下
ZIP_CHUNK = 64 * 1024
ZIP_SEM = threading.BoundedSemaphore(1) # 同一时间只打一个包(2026-10-05 外部复查)
CST = timezone(timedelta(hours=8))
LOCK = threading.Lock()
class _DataLock(object):
"""线程锁 + 跨进程文件锁(2026-10-05 外部复查加)。
⚠️ 原来的 LOCK 只是 threading.Lock —— 只管得住**本进程**里的线程。
admin.py(发码 / 核销 / sweep)是**另一个进程**,跟服务器同时改 codes.json 时会互相覆盖:
比如 CLI 发码那一刻刚好有买家提交,CLI 存回去的旧快照会把买家刚绑上的码改回「可用」。
所以在线程锁之外再加一把 flock(<DATA_DIR>/.lock)。用法不变:`with LOCK:`。
拿不到文件锁(非 Linux / 没权限)就只用线程锁,并且记一笔日志 —— 不让它把服务拖死。
"""
def __init__(self, path):
self._t = threading.Lock()
self._path = path
self._fh = None
self._warned = False
def __enter__(self):
self._t.acquire()
try:
import fcntl
if self._fh is None:
self._fh = open(self._path, "a+")
fcntl.flock(self._fh.fileno(), fcntl.LOCK_EX)
except Exception as e: # noqa: BLE001 —— 文件锁拿不到不能影响主流程
if self._fh is not None:
try:
self._fh.close()
except Exception:
pass
self._fh = None
if not self._warned:
self._warned = True
try:
print("⚠️ 跨进程文件锁不可用,只用线程锁:%r" % (e,), flush=True)
except Exception:
pass
return self
def __exit__(self, *exc):
try:
if self._fh is not None:
import fcntl
fcntl.flock(self._fh.fileno(), fcntl.LOCK_UN)
except Exception:
pass
finally:
self._t.release()
return False
LOCK = _DataLock(os.path.join(ROOT, ".lock"))
HOOK_LOCK = threading.Lock() # 爱发电回调 + 账本读写串行(回调很少,串行没有代价)
# 臂型中文名(小票/页面文案用,和前端 ARMTXT 保持一致)
ARMTXT = {"classic": "粗臂", "slim": "细臂", "auto": "自动判定"}
@@ -280,9 +334,12 @@ def gift_expire_text(iso_ts):
return "还有 %d 分钟" % max(1, m)
def coupon_status(c):
"""一张券现在什么状态(给"我的卡券"用)。返回 dict。"""
cs = load_codes()
def coupon_status(c, cs=None):
"""一张券现在什么状态(给"我的卡券"用)。返回 dict。
cs:调用方已经读好的 codes(批量查时只读一次文件,2026-10-05 外部复查)。"""
if cs is None:
cs = load_codes()
rec = cs.get(c)
if not rec:
return {"code": c, "status": "unknown", "text": "查不到这张券"}
@@ -349,7 +406,7 @@ def gift_claim(bid, token, ip):
if r.get("gift") == bid and not r.get("claim_token") and code_state(r) == "active"]
if not pool:
return False, "手慢了 —— 这批已经被领完啦"
pick = random.choice(pool)
pick = secrets.choice(pool)
cs[pick]["claim_token"] = tok
cs[pick]["claim_ip"] = ip
cs[pick]["claim_ts"] = now().isoformat(timespec="seconds")
@@ -417,19 +474,20 @@ def gift_batch_new(name, count=20, n_fix=1, n_free=False, tpl="", lock_tpl=False
days = 0
# ⚠️ 只按秒取 id 会撞车(同一秒建两批 → 同一个 id,券和批次全串了,2026-10-02 实踩)→ 补 3 个随机位
bid = "g" + time.strftime("%m%d%H%M%S") + "".join(
random.choice(GIFT_ID_ALPH) for _ in range(3))
d = gift_batches()
d["batches"].append({
"id": bid, "name": name, "note": (note or "").strip()[:200],
"n_fix": n_fix, "n_free": bool(n_free), "kind": kind,
"each": max(1, int(each or 1)), "tpl": ",".join(tpls),
"lock_tpl": bool(lock_tpl) and bool(tpls),
"expire": (time.strftime("%Y-%m-%d", time.localtime(time.time() + days * 86400))
if days else ""),
"enabled": True, "direct": bool(direct),
"created": now().isoformat(timespec="seconds"),
})
jsave(GIFTS_FILE, d)
secrets.choice(GIFT_ID_ALPH) for _ in range(3))
with LOCK:
d = gift_batches()
d["batches"].append({
"id": bid, "name": name, "note": (note or "").strip()[:200],
"n_fix": n_fix, "n_free": bool(n_free), "kind": kind,
"each": max(1, int(each or 1)), "tpl": ",".join(tpls),
"lock_tpl": bool(lock_tpl) and bool(tpls),
"expire": (time.strftime("%Y-%m-%d", time.localtime(time.time() + days * 86400))
if days else ""),
"enabled": True, "direct": bool(direct),
"created": now().isoformat(timespec="seconds"),
})
jsave(GIFTS_FILE, d)
codes = gift_batch_add(bid, count, direct=direct)
log("福利券批次建好 %s「%s」%d 张(%s)" % (
bid, name, len(codes), "不限张数" if n_free else "最多 %d 张" % n_fix))
@@ -461,22 +519,27 @@ def gift_batch_add(bid, count=20, direct=None):
n_max=0 if b.get("n_free") else int(b.get("n_fix") or 1),
n_free=bool(b.get("n_free")), direct=bool(direct),
lock_tpl=bool(b.get("lock_tpl")))
cs = load_codes()
for c in got:
cs[c]["gift"] = bid
jsave(CODES_FILE, cs)
# ⚠️ 2026-10-05(外部复查):原来这段在锁外读写 codes.json —— 恰好有人在下单 / 领券的话,
# 存回去的旧快照会把别人刚改的码冲掉。
with LOCK:
cs = load_codes()
for c in got:
if c in cs:
cs[c]["gift"] = bid
jsave(CODES_FILE, cs)
log("福利券批次 %s 补货 %d 张" % (bid, len(got)))
return got
def gift_batch_off(bid):
"""收摊(已领到手的券不受影响)。批次不存在 raise ValueError。"""
d = gift_batches()
b = next((x for x in d["batches"] if x.get("id") == bid), None)
if not b:
raise ValueError("没有这个批次:%s" % bid)
b["enabled"] = False
jsave(GIFTS_FILE, d)
with LOCK:
d = gift_batches()
b = next((x for x in d["batches"] if x.get("id") == bid), None)
if not b:
raise ValueError("没有这个批次:%s" % bid)
b["enabled"] = False
jsave(GIFTS_FILE, d)
log("福利券批次 %s 已收摊" % bid)
return b
@@ -589,6 +652,33 @@ def note_submit(ip):
IP_SUBS.setdefault(ip, []).append(time.time())
IP_FEEDBACK = {} # ip -> [反馈时间戳]
def feedback_allowed(ip):
"""反馈限流:10 分钟 5 条(正常买家够用;刷不爆盘、刷不爆通知)。"""
return len(_recent(IP_FEEDBACK, ip, SUB_WIN)) < 5
def note_feedback(ip):
IP_FEEDBACK.setdefault(ip, []).append(time.time())
def _img_ext(b):
"""看文件头认图片格式(png/jpg/webp/gif);认不出返回 None。"""
if not b:
return None
if b[:8] == b"\x89PNG\r\n\x1a\n":
return "png"
if b[:3] == b"\xff\xd8\xff":
return "jpg"
if b[:4] == b"RIFF" and b[8:12] == b"WEBP":
return "webp"
if b[:6] in (b"GIF87a", b"GIF89a"):
return "gif"
return None
def skin_allowed(ip):
"""追补皮肤单独限流:10 分钟 20 次(一个买家补十张皮肤也够用)。"""
return len(_recent(IP_SKINS, ip, SUB_WIN)) < 20
@@ -652,11 +742,38 @@ def jload(path, default):
return default
_UMASK = os.umask(0)
os.umask(_UMASK)
def jsave(path, obj):
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(obj, f, ensure_ascii=False, indent=1)
os.replace(tmp, path)
"""原子写 JSON。
⚠️ 2026-10-05(外部复查)两处加固,读写格式不变:
* 临时文件名**每次唯一**(原来固定是 path+".tmp":两个线程/进程同时写同一个文件时
会写进同一个 tmp,互相截断,replace 出一个半截文件);
* 写完 **fsync** 再 replace:只 replace 不 fsync,断电后可能留下一个 0 字节的 codes.json。
* 新文件的权限沿用原文件(没有原文件就按进程 umask),不会因为换了写法悄悄变成 600。
"""
d = os.path.dirname(path) or "."
try:
mode = os.stat(path).st_mode & 0o777
except OSError:
mode = 0o666 & ~_UMASK
fd, tmp = tempfile.mkstemp(prefix=os.path.basename(path) + ".", suffix=".tmp", dir=d)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(obj, f, ensure_ascii=False, indent=1)
f.flush()
os.fsync(f.fileno())
os.chmod(tmp, mode)
os.replace(tmp, path)
except BaseException:
try:
os.unlink(tmp)
except OSError:
pass
raise
def worker_token():
@@ -707,15 +824,21 @@ def note_home_ip(ip):
def admin_ip_ok(ip):
"""后门:本机回环永远放行(等于原来的 admin.py 本地 CLI)。"""
return ip in ("localhost", "::1", "localhost", "?") or ip in HOME_IPS
# ⚠️ 2026-10-05(外部复查):去掉了 "?"。ip_of() 取不到来源时返回 "?",
# 原来这样也算「本机」直接放行 —— 门是靠令牌 + IP 两道,不能让「不知道是谁」过 IP 这道。
# (另见回执:反代哪条 location 漏配 X-Real-IP,来源就会变成回环、被当成本机。)
return ip in ("localhost", "::1", "localhost") or ip in HOME_IPS
# ⚠️ 2026-10-05(外部复查):订单号 / 取件码 / 卡密必须用 secrets(操作系统级随机),不能用 random。
# random 是梅森旋转,看够它吐出来的值(比如反复领福利券、反复下网页单拿到的码和取件码)
# 就能反推内部状态,**预测之后要生成的卡密和别人的取件码**。字符表、长度、格式都没变。
def new_oid():
return "YS" + "".join(random.choice(OID_ALPH) for _ in range(6))
return "YS" + "".join(secrets.choice(OID_ALPH) for _ in range(6))
def new_owner_token():
return "".join(random.choice(OID_ALPH) for _ in range(14))
return "".join(secrets.choice(OID_ALPH) for _ in range(14))
# ----------------------------------------------------------------- 兑换码
@@ -739,7 +862,7 @@ def gen_codes(n, batch="", value=6, platform="", tpl="", state="active", is_set=
made = []
while len(made) < n:
c = "YS-" + "-".join(
"".join(random.choice(OID_ALPH) for _ in range(4)) for _ in range(3))
"".join(secrets.choice(OID_ALPH) for _ in range(4)) for _ in range(3))
if c in codes:
continue
# platform/tpl = 第三方平台的标记(闲鱼/B站工坊…)+ 预选模板;金钻 2026-09-30
@@ -944,40 +1067,87 @@ def activate_order_paid(oid, code=None, source=""):
def redeem(codes_in):
"""校验一批码;全部可用才通过。返回 (ok, err, codes_out)"""
"""校验一批码;全部可用才通过。返回 (ok, err, codes_out)
⚠️ 只是「查」,不占码 —— 真正占码用 redeem_bind()(查 + 绑在同一把锁里)。
"""
with LOCK:
return _redeem_check(load_codes(), codes_in)
def _redeem_check(codes, codes_in):
"""redeem / redeem_bind 共用的判断(不加锁,调用方负责)。"""
seen, good = set(), []
for raw in codes_in:
c = (raw or "").strip().upper()
if not CODE_RE.match(c):
return False, "卡密格式不对:%s" % c, None
if c in seen:
return False, "同一张卡密重复提交:%s" % c, None
seen.add(c)
rec = codes.get(c)
if rec is None:
return False, "卡密不存在:%s" % c, None
st = code_state(rec)
if st == "used":
return False, "这张卡密已经核销了(用过了):%s" % c, None
if st == "bound":
return False, ("这张卡密已经用来下过单了:%s —— 去「凭票取图」填卡密就能回到那一单"
% c), None
if st == "inactive":
return False, "这张卡密还没激活(网页下单的要等付款后激活):%s" % c, None
_exp = rec.get("claim_expire") or ""
if _exp and st == "active":
try:
overdue = datetime.fromisoformat(_exp) < now()
except (TypeError, ValueError):
overdue = False
if overdue:
return False, ("这张福利券过期了(领了没用掉)—— 找金钻要一张新的吧:%s" % c), None
good.append(c)
return True, None, good
def redeem_bind(codes_in, oid):
"""**校验 + 绑定**在同一把锁里做完(2026-10-05 外部复查加)。返回 (ok, err, codes_out)。
⚠️ 原来是 redeem()(锁里查)→ 落皮肤、做 PNG 核验、写订单 → burn_codes()(锁里绑),
中间有好几秒的空档:同一张码**同时提交两次**(连点、脚本、两个标签页),两次都查到「可用」,
就开出两单 —— 一码两用。现在绑定前在锁里**再查一遍**,查到不是 active 就整单不收。
校验规则和 redeem() 完全一样(直接复用它的判断,免得两份漂移)。
"""
with LOCK:
codes = load_codes()
seen, good = set(), []
for raw in codes_in:
c = (raw or "").strip().upper()
if not CODE_RE.match(c):
return False, "卡密格式不对:%s" % c, None
if c in seen:
return False, "同一张卡密重复提交:%s" % c, None
seen.add(c)
rec = codes.get(c)
if rec is None:
return False, "卡密不存在:%s" % c, None
st = code_state(rec)
if st == "used":
return False, "这张卡密已经核销了(用过了):%s" % c, None
if st == "bound":
return False, ("这张卡密已经用来下过单了:%s —— 去「凭票取图」填卡密就能回到那一单"
% c), None
if st == "inactive":
return False, "这张卡密还没激活(网页下单的要等付款后激活):%s" % c, None
_exp = rec.get("claim_expire") or ""
if _exp and st == "active":
try:
overdue = datetime.fromisoformat(_exp) < now()
except (TypeError, ValueError):
overdue = False
if overdue:
return False, ("这张福利券过期了(领了没用掉)—— 找金钻要一张新的吧:%s" % c), None
good.append(c)
ok, err, good = _redeem_check(codes, codes_in)
if not ok:
return False, err, None
ts = now().isoformat(timespec="seconds")
for c in good:
codes[c]["state"] = "bound"
codes[c]["used"] = False
codes[c]["order"] = oid
codes[c]["bound_at"] = ts
jsave(CODES_FILE, codes)
return True, None, good
def unbind_codes(codes_list, oid):
"""redeem_bind 之后订单没建成(写盘失败等)→ 把码放回 active,别让码白白占住。"""
with LOCK:
codes = load_codes()
hit = False
for c in codes_list or []:
r = codes.get(c)
if r and r.get("order") == oid and code_state(r) == "bound":
r["state"] = "active"
r["used"] = False
r["order"] = None
r.pop("bound_at", None)
hit = True
if hit:
jsave(CODES_FILE, codes)
def burn_codes(codes_list, oid):
"""把卡密绑到订单上 —— ⚠️ 这只算**激活**,不是核销(金钻 2026-09-30 晚:
「点击最后的提交才算激活;核销要等开放下载后 72 小时」)。
@@ -1257,18 +1427,32 @@ def edit_code(c, patch):
两边各写一遍迟早漂移(这是本项目的头号 bug 来源)。
"""
c = (c or "").strip().upper()
# ⚠️ 2026-10-05(外部复查):读 → 改 → 写 必须在**同一把锁**里。原来锁外读、锁里写:
# 读完到写之间要是有买家把另一张码绑上了,这里存回去的旧快照会把那张码改回 active(一码两用)。
with LOCK:
rec, err = _edit_code_locked(c, patch)
if not rec:
return False, err, None
log("改卡密 %s → %s" % (c, json.dumps({k: rec.get(k) for k in
("tpl", "set", "direct", "lock_tpl", "n_fix", "n_max", "state", "platform")},
ensure_ascii=False)))
return True, None, code_info(c)
def _edit_code_locked(c, patch):
"""edit_code 的主体(调用方持锁)。返回 (改后的记录 或 False, 错误文案)。"""
cs = load_codes()
if c not in cs:
return False, "没有这张卡密:%s" % c, None
return False, "没有这张卡密:%s" % c
if code_state(cs[c]) == "used":
return False, ("这张卡密已经用掉了(订单 %s),改不了 —— 要改请用 admin.py 直接动订单"
% (cs[c].get("order") or "")), None
% (cs[c].get("order") or ""))
r = cs[c]
p = patch or {}
if "tpls" in p:
bad = [t for t in (p.get("tpls") or []) if t not in TPL_KEYS]
if bad:
return False, "模板不认识:%s" % "、".join(bad), None
return False, "模板不认识:%s" % "、".join(bad)
r["tpl"] = ",".join(p["tpls"])
for k in ("set", "direct", "lock_tpl"):
if k in p:
@@ -1284,11 +1468,11 @@ def edit_code(c, patch):
n_fix = int(p["n_fix"]) if "n_fix" in p else (0 if p.get("free") else cur_fix)
n_max = int(p["n_max"]) if "n_max" in p else cur_max
except (TypeError, ValueError):
return False, "张数不合法", None
return False, "张数不合法"
if n_fix > MAX_IMAGES or n_max > 100:
return False, "张数不合法(固定张数最多 %d 张)" % MAX_IMAGES, None
return False, "张数不合法(固定张数最多 %d 张)" % MAX_IMAGES
if n_fix and n_max and n_max < n_fix:
return False, "封顶不能小于固定张数", None
return False, "封顶不能小于固定张数"
r["n_fix"], r["n_max"] = n_fix, n_max
if p.get("unlimited"):
r["n_free"] = True # 不限张数(老规矩「一张码一张图」也一并解除)
@@ -1302,13 +1486,9 @@ def edit_code(c, patch):
if k in p:
r[k] = str(p[k] or "")[:20]
if r.get("lock_tpl") and not (r.get("tpl") or "").strip():
return False, "要锁定模板,得先给这张码带模板", None
with LOCK:
jsave(CODES_FILE, cs)
log("改卡密 %s → %s" % (c, json.dumps({k: r.get(k) for k in
("tpl", "set", "direct", "lock_tpl", "n_fix", "n_max", "state", "platform")},
ensure_ascii=False)))
return True, None, code_info(c)
return False, "要锁定模板,得先给这张码带模板"
jsave(CODES_FILE, cs)
return r, None
# ----------------------------------------------------------------- HTTP
@@ -1395,6 +1575,28 @@ class H(BaseHTTPRequestHandler):
if body and self.command != "HEAD":
self.wfile.write(body)
def _send_file(self, path, ctype, extra=None):
"""把文件**边读边发**(不整块进内存)。头和 _send 一样:Content-Length + no-store。"""
try:
size = os.path.getsize(path)
fh = open(path, "rb")
except OSError:
return self.err("文件已过期或不存在", 404)
with fh:
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(size))
self.send_header("Cache-Control", "no-store")
for k, v in (extra or {}).items():
self.send_header(k, v)
self.end_headers()
if self.command == "HEAD":
return
try:
shutil.copyfileobj(fh, self.wfile, ZIP_CHUNK)
except (BrokenPipeError, ConnectionResetError):
self.close_connection = True
def js(self, obj, code=200):
self._send(code, json.dumps(obj, ensure_ascii=False).encode(), "application/json; charset=utf-8")
@@ -1533,7 +1735,7 @@ class H(BaseHTTPRequestHandler):
if p == "/api/progress":
return self.progress()
if p == "/api/finish":
return self.finish()
return self.finish_upload()
if p == "/api/fail":
return self.fail()
# ---- 管理接口(金钻电脑上的后台面板)----
@@ -1609,6 +1811,9 @@ class H(BaseHTTPRequestHandler):
return self.err("一单最多 %d 张" % MAX_IMAGES)
if len(templates) > MAX_IMAGES:
return self.err("一单最多 %d 个模板" % MAX_IMAGES)
_badt = [str(x) for x in templates if x not in TPL_KEYS]
if _badt:
return self.err("模板不认识:%s(刷新一下页面再试)" % "、".join(_badt[:3]))
if not prepay and not _loose and len(codes) != len(templates):
return self.err("卡密个数与出图张数不一致")
if arm not in ("classic", "slim"):
@@ -1632,8 +1837,18 @@ class H(BaseHTTPRequestHandler):
# ⚠️ 2026-10-04 修:第 1 次提交只带第 1 张皮肤,直接拿 len(templates) 当整单张数
# 会把多皮肤的单一律算少(实测:皮肤1 出 2 张 + 皮肤2 出 1 张 → 只算 2 张 →
# 「固定 3 张」的码被误拒)。前端现在会传 nTotal / tplUnion,优先用它。
_n1 = int(d.get("nTotal") or 0) or len(templates)
_u1 = [t for t in (d.get("tplUnion") or templates) if t in TPL_KEYS] or templates
# ⚠️ 2026-10-05(外部复查):nTotal / tplUnion 是**前端报的**,不能单独信 ——
# 原来报 nTotal=1、实际 templates 塞 7 个,「固定 1 张」的码就能出 7 张图;
# 报 tplUnion=锁定那组、实际 templates 是别的模板,锁模板就形同虚设。
# 现在:张数取「前端报的」和「这次真提交的」里**大的那个**,模板取两者的**并集**。
# 正常页面报的 nTotal 本来就 ≥ 第一张皮肤的模板数,所以对正常买家没有任何变化。
try:
_n_decl = int(d.get("nTotal") or 0)
except (TypeError, ValueError):
_n_decl = 0
_n1 = max(_n_decl, len(templates))
_u1 = list(dict.fromkeys([t for t in (d.get("tplUnion") or []) if t in TPL_KEYS]
+ [t for t in templates if t in TPL_KEYS])) or templates
e2 = check_rules(codes_rules(good), _n1, _u1)
if e2:
log("卡密规则不通过 %s:%s" % (ip, e2))
@@ -1711,8 +1926,24 @@ class H(BaseHTTPRequestHandler):
"note": "", "files": [], "started": None, "finished": None,
"expire": (now() + timedelta(hours=KEEP_HOURS)).isoformat(timespec="seconds"),
}
with LOCK:
write_meta(oid, meta)
if not prepay:
# ⚠️ 2026-10-05(外部复查):这里**再查一遍并当场绑定**(同一把锁里)——
# 上面 redeem() 只是查,从查到这里中间隔着解码 / PNG 核验 / 落盘好几秒,
# 同一张码并发提交两次的话两边都会查到「可用」。绑不上 = 被别的提交抢先了。
okb, eb, good = redeem_bind(good, oid)
if not okb:
shutil.rmtree(order_dir(oid), ignore_errors=True)
log("兑换码并发冲突 %s:%s" % (ip, eb))
return self.err(eb)
meta["codes"] = good
try:
with LOCK:
write_meta(oid, meta)
except Exception:
if not prepay:
unbind_codes(good, oid) # 单没建成,码放回去
shutil.rmtree(order_dir(oid), ignore_errors=True)
raise
note_submit(ip)
if prepay:
# 给网页单也发一个码:既是凭证,买家也能拿它在「凭票取图」页取件
@@ -1737,8 +1968,6 @@ class H(BaseHTTPRequestHandler):
meta["codes"] = [newc]
with LOCK:
write_meta(oid, meta)
else:
burn_codes(good, oid)
log("新订单 %s | %s | %s px | 码 %d 个 | 模板 %s | %s"
% (oid, arm, res, len(good), ",".join(templates), "待付款" if prepay else "已核销入队"))
return self.js({"ok": True, "order": oid, "token": tok, "expire": meta["expire"],
@@ -1790,7 +2019,8 @@ class H(BaseHTTPRequestHandler):
elif st == "waiting" and m.get("codes"):
# 卡密单(闲鱼/B站发来的码)本来就是付过款的,别再让买家以为要付款
pos = queue_pos(oid)
note = ("这单是用卡密下的,**已经付过款,不用再付款**。"
# 页面把 note 当纯文本显示 —— 别写 Markdown 的 **,买家会看到两对星号(2026-10-05 外部复查)
note = ("这单是用卡密下的,已经付过款,不用再付款。"
+ ("渲染机在线,正在排队(前面还有 %d 单)。" % (pos - 1) if hbs["online"]
else "渲染机当前离线,等金钻开机器后会自动开始渲染,着急可点「呼叫金钻」。"))
elif st == "waiting":
@@ -1806,6 +2036,10 @@ class H(BaseHTTPRequestHandler):
if accepted else
"渲染完成!先看下面的 512 预览图(带水印),确认没问题点「确认收货」,"
"就能下载原图(标准压缩 + 无压缩 16bit,两张都记得下载)。")
if m.get("partial"):
# 状态话术不许骗人:少交了就直说(金钻那边已经收到提醒)
note = ("有 %d 个文件没渲出来,已经自动通知金钻补。下面是已经出好的部分。"
% max(0, int(m["partial"].get("want") or 0) - int(m["partial"].get("got") or 0))) + note
elif st == "failed":
note = note or "渲染失败,已记录,可点「呼叫金钻」处理。"
return self.js({"ok": True, "oid": oid, "state": st, "created": m.get("created"),
@@ -2001,6 +2235,11 @@ class H(BaseHTTPRequestHandler):
except OSError:
pass
with HOOK_LOCK:
return self._payplatform_hook_locked(obj)
def _payplatform_hook_locked(self, obj):
"""回调主体(在 HOOK_LOCK 里跑:同一笔单并发重推、两笔回调同时写账本都不会互相冲掉)。"""
order = (((obj.get("data") or {}).get("order")) or {})
oid_af = str(order.get("out_trade_no") or "").strip()
title = "%s %s" % (order.get("plan_title") or "", order.get("title") or "")
@@ -2011,8 +2250,13 @@ class H(BaseHTTPRequestHandler):
log("爱发电回调:测试单(%s),只记账不发码" % title.strip())
return self.js({"ec": 200, "em": ""})
led = jload(PAYPLATFORM_LEDGER, {}) or {}
if oid_af in led and led[oid_af].get("code"):
log("爱发电回调:%s 已经发过码 %s(重推,原样回它)" % (oid_af, led[oid_af]["code"]))
# ⚠️ 2026-10-05(外部复查):幂等原来只认「发过码」。可「对上网页单、激活了」那条路记的是
# code=None + used_by=<单号> —— 同一笔单再推一次(爱发电自己会重试;这个地址又是公开的,
# 谁都能把报文原样再 POST 一遍)就不算处理过:第二次激活失败(单子已经在排队)→ 掉进
# 「按买码处理」→ **白送一张码**,还会写进返回体里。现在:发过码 **或** 激活过单,一律原样回。
if oid_af in led and (led[oid_af].get("code") or led[oid_af].get("used_by")):
log("爱发电回调:%s 已经处理过(%s),重推原样回它"
% (oid_af, led[oid_af].get("code") or ("激活了 %s" % led[oid_af].get("used_by"))))
return self.js({"ec": 200, "em": "", "data": {"content": led[oid_af].get("content") or ""}})
if int(order.get("status") or 0) != 2:
@@ -2193,6 +2437,13 @@ class H(BaseHTTPRequestHandler):
return self.err("这一单现在是「%s」,不用再激活了" % m.get("state"))
if len(ano) < 10:
return self.err("爱发电订单号看着不对(在爱发电「我的订单」里能复制到,一长串数字)")
ip = ip_of(self)
if too_many_fails(ip):
return self.err("尝试次数过多,请 15 分钟后再试", 429)
with HOOK_LOCK: # 账本和回调共用一把锁,免得两边同时写把对方的记录冲掉
return self._activate_payplatform_locked(oid, m, ano, ip)
def _activate_payplatform_locked(self, oid, m, ano, ip):
led = jload(PAYPLATFORM_LEDGER, {}) or {}
rec = None
for k, v in led.items():
@@ -2201,6 +2452,7 @@ class H(BaseHTTPRequestHandler):
rec["_key"] = k
break
if not rec:
note_fail(ip)
return self.err("没查到这笔爱发电订单 —— 确认一下订单号?刚付完可能要等几秒,"
"稍等再试;还不行就点「呼叫金钻」。")
if not rec.get("code"):
@@ -2244,8 +2496,12 @@ class H(BaseHTTPRequestHandler):
return self.err("这一单现在是「%s」,不用再激活了" % m.get("state"))
if not CODE_RE.match(code):
return self.err("卡密格式不对(形如 YS-XXXX-XXXX-XXXX)")
ip = ip_of(self)
if too_many_fails(ip): # 和下单共用一套「输错冷却」(2026-10-05 外部复查补)
return self.err("尝试次数过多,请 15 分钟后再试", 429)
rec = (load_codes() or {}).get(code)
if not rec:
note_fail(ip)
return self.err("没有这个卡密 —— 检查一下有没有输错")
# 填的是**自己这一单的凭证码**?金钻 2026-10-01 定的口径:「回来就用这个兑换码就行」。
# 那就把它当**报到付款**用:订单推到 paid(待激活),并告诉买家"等确认到账就开渲"。
@@ -2279,7 +2535,11 @@ class H(BaseHTTPRequestHandler):
if set(uni) - set(locked):
return self.err("这张卡密锁定了模板(%s),你这单选的是 %s —— 对不上。"
% ("、".join(locked), "、".join(uni)))
burn_codes([code], oid) # 绑码(= 激活,不是核销)
# 绑码(= 激活,不是核销)。⚠️ 查和绑必须在同一把锁里:同一张码同时激活两张单,
# 原来两边都会查到 active、都绑上(2026-10-05 外部复查)。
okb, eb, _g = redeem_bind([code], oid)
if not okb:
return self.err(eb)
m["codes"] = (m.get("codes") or []) + [code]
m["state"] = "waiting" # 进队列 —— 订单内容原封不动
m["paid_at"] = now().isoformat(timespec="seconds")
@@ -2336,12 +2596,12 @@ class H(BaseHTTPRequestHandler):
hit = [x for x in skins if (x.get("id") or "") == sid]
if not hit:
return self.err("这张皮肤不属于这一单")
try:
raw = base64.b64decode(new_skin.split(",", 1)[-1])
except Exception:
return self.err("新皮肤数据不合法")
if not raw or len(raw) > MAX_BODY:
return self.err("新皮肤太大或为空")
# ⚠️ 2026-10-05(外部复查):原来这里只 base64 解一下、看个大小就落盘 ——
# **绕过了 PNG 结构核验**(尾部夹带 / 未知关键块 / APNG 全都能进),
# 而且直接发给渲染机那台电脑。现在和下单 / 追补皮肤走同一个 _read_skin(核验 + 清洗)。
okr, er, raw, _sz, _notes = self._read_skin({"skin": new_skin})
if not okr:
return self.err("新皮肤不行:%s" % er)
sd = os.path.join(order_dir(oid), "skins")
os.makedirs(sd, exist_ok=True)
with open(os.path.join(sd, "%s.png" % sid), "wb") as f:
@@ -2414,17 +2674,24 @@ class H(BaseHTTPRequestHandler):
"""买家反馈(金钻 2026-10-02:「反馈问题要能上传图片」)。
为什么改走服务器:原来是 mailto —— **手机上点了没反应**(没配邮箱客户端就什么都不发生),
而且图片根本带不出去。现在存到 <DATA_DIR>/feedback/,并且走「呼叫金钻」同一套通知。"""
ip = ip_of(self)
# ⚠️ 2026-10-05(外部复查):这个接口原来**不限频、不看磁盘**,每次能存一张 4MB 的图,
# 还会往 calls.jsonl 塞一条「呼叫」→ 写个循环就能把盘写满、把金钻的手机通知刷爆。
if not feedback_allowed(ip):
return self.err("反馈太频繁了,稍后再试(着急可以点「呼叫金钻」)", 429)
if not disk_ok():
return self.err("服务器空间不足,请联系金钻处理", 503)
d = self.body_json() or {}
ip = self.headers.get("X-Real-IP") or self.client_address[0]
note = str(d.get("note") or "").strip()[:1500]
if not note and not d.get("image"):
return self.err("总得写点什么,或者传张图")
note_feedback(ip)
try:
os.makedirs(FEEDBACK_DIR, exist_ok=True)
except OSError:
return self.err("服务器忙,稍后再试", 503)
fid = now().strftime("%Y%m%d-%H%M%S") + "-" + "".join(
random.choice("abcdefghijkmnpqrstuvwxyz23456789") for _ in range(4))
secrets.choice("abcdefghijkmnpqrstuvwxyz23456789") for _ in range(4))
rec = {"id": fid, "ts": now().isoformat(timespec="seconds"), "ip": ip,
"order": str(d.get("order") or "")[:20], "note": note,
"contact": str(d.get("contact") or "")[:80],
@@ -2439,8 +2706,11 @@ class H(BaseHTTPRequestHandler):
raw = base64.b64decode(img.split(",", 1)[-1])
except Exception:
raw = b""
if raw and len(raw) <= 4 * 1024 * 1024:
fn = "%s.png" % fid
_ext = _img_ext(raw)
if raw and not _ext:
rec["image"] = "(不是常见图片格式,没收)"
elif raw and len(raw) <= 4 * 1024 * 1024:
fn = "%s.%s" % (fid, _ext)
with open(os.path.join(FEEDBACK_DIR, fn), "wb") as f:
f.write(raw)
rec["image"] = fn
@@ -2464,7 +2734,8 @@ class H(BaseHTTPRequestHandler):
d = self.body_json() or {}
codes = [re.sub(r"[^A-Za-z0-9-]", "", str(x)).upper()[:20]
for x in (d.get("codes") or [])][:60]
return self.js({"ok": True, "list": [coupon_status(c) for c in codes if c]})
cs = load_codes()
return self.js({"ok": True, "list": [coupon_status(c, cs) for c in codes if c]})
def gift_take(self):
"""领一张福利券 → 返回券码(拿去「卡密下单」用,免费)"""
@@ -2555,8 +2826,6 @@ class H(BaseHTTPRequestHandler):
path = os.path.join(order_dir(oid), rel)
if not os.path.exists(path):
return self.err("文件已过期或不存在", 404)
with open(path, "rb") as f:
data = f.read()
name = files[idx].get("name") or "out.png"
# ⚠️ HTTP 头只能是 latin-1:中文文件名直接写进 filename= 会 UnicodeEncodeError,
# 连接被掐断 → nginx 侧看到 502。必须给 ASCII 回退名 + RFC 5987 的 filename*=
@@ -2565,10 +2834,13 @@ class H(BaseHTTPRequestHandler):
% (ascii_name, quote(name, safe="")))
ctype = "image/jpeg" if rel.lower().endswith(".jpg") else "image/png"
# ⚠️ no-store:成品/预览是同名覆盖的,重渲后绝不能让浏览器拿缓存里的旧图
# ⚠️ 2026-10-05(外部复查):原来 `data = f.read()` 整张读进内存再发。4096 的无压缩 16bit
# 一张就是几十 MB,几个人同时下就顶到 MemoryMax=256M → 整个服务被 OOM 杀掉。
# 现在和 zip 一样边读边发(64KB 一块),响应头、内容一个字节都没变。
if (q.get("p") or [""])[0] == "1":
self._send(200, data, ctype, {"Cache-Control": "no-store"}) # 预览内联显示,不强制下载
self._send_file(path, ctype, {}) # 预览内联显示,不强制下载
else:
self._send(200, data, ctype, {"Content-Disposition": disp, "Cache-Control": "no-store"})
self._send_file(path, ctype, {"Content-Disposition": disp})
def skin(self, oid, sid="s1"):
m = read_meta(oid)
@@ -2584,9 +2856,7 @@ class H(BaseHTTPRequestHandler):
path = next((p for p in cand if os.path.exists(p)), cand[-1])
if not os.path.exists(path):
return self.err("not found", 404)
with open(path, "rb") as f:
data = f.read()
self._send(200, data, "image/png")
self._send_file(path, "image/png")
def hb(self):
if not self.is_worker():
@@ -2632,6 +2902,8 @@ class H(BaseHTTPRequestHandler):
# 「只重渲勾的那几张」时必须留着 —— 清了的话没重渲的成品就永远回不来了(金钻 2026-10-04)
if not m.get("redo_tpls"):
m["files"] = []
m.pop("plan_total", None) # 新的一轮,按渲染机这次报的 total 重新算
m.pop("partial", None)
write_meta(m["oid"], m)
log("派单 %s → 渲染机" % m["oid"])
return self.js({"ok": True, "order": {
@@ -2639,6 +2911,9 @@ class H(BaseHTTPRequestHandler):
"created": m["created"], "skin_size": m.get("skin_size"),
"res": int(m.get("res") or DEFAULT_RES),
"redo_tpls": (m.get("redo_tpls") or []), "keep_n": len(m.get("files") or []), "codes": m.get("codes"),
# 2026-10-05(外部复查,⚠️ 接口**新增**字段):渲染机留档里的「条款版本」原来读不到这一项,
# 一直写的是渲染机自己写死的旧版本号(2026-10-01.1)。带上订单真实同意的那一版。
"terms_v": m.get("terms_v") or "",
# 皮肤清单(金钻 2026-10-01):渲染机按「每张皮肤 × 每个模板」出图,
# 每张皮肤各自带臂型(A 可能粗臂、B 可能细臂)
"skins": [{"id": x.get("id"), "fileName": x.get("fileName"), "arm": x.get("arm"),
@@ -2691,7 +2966,12 @@ class H(BaseHTTPRequestHandler):
write_meta(oid, m)
return self.js({"ok": True})
def finish(self):
# ⚠️ 2026-10-05(外部复查):这个方法原来叫 finish() —— 和 socketserver 的 StreamRequestHandler.finish()
# **重名**。框架在**每个请求**处理完之后都会调 self.finish(),于是每个请求结束时都会把「回传成品」
# 的逻辑再跑一遍:普通请求 → 往已经回完的连接上再写一个 403;带渲染机令牌的请求 → 再去读一次请求体
# (读到连接关闭才返回)→ 再写一个「参数不合法」。日志里那些
# 「Exception occurred during processing of request … in finish」就是它。接口路径 /api/finish 不变。
def finish_upload(self):
"""渲染机交回成品(**一张一次**,避免单次请求过大):
{oid, total, results:[{tpl,name,png}], note}
收满 total 张才把单子标成 done。"""
@@ -2709,7 +2989,8 @@ class H(BaseHTTPRequestHandler):
# (2026-10-01:模板认错皮肤节点时,不用再去宿主翻渲染机日志)
if d.get("diag"):
m["skin_diag"] = [str(x)[:240] for x in (d.get("diag") or [])][:8]
write_meta(oid, m)
with LOCK:
write_meta(oid, m)
log("皮肤节点判定(%s):%s" % (oid, " | ".join(m["skin_diag"])))
outdir = os.path.join(order_dir(oid), "out")
os.makedirs(outdir, exist_ok=True)
@@ -2751,7 +3032,16 @@ class H(BaseHTTPRequestHandler):
# 重渲会把同名图重新交上来 —— 按名字替换,别在列表里堆两份(2026-10-02 加重渲时发现)
files = [f for f in files if (f.get("name") or "") != name]
files.append(entry)
total = int(d.get("total") or len(m.get("templates") or []) or 1)
# ⚠️ 2026-10-05(外部复查):渲染机收单(close)那一下**不带 total**,原来就退回按「模板数」算 ——
# 可渲染机的 total 是按**文件数**(每个模板两张)报的。于是 2 个模板只交回 2 个文件(缺两张无压缩)
# 也会被当成「收满了」。现在记住渲染机前面报过的 total(plan_total),收单时按它判断。
try:
_tot_in = int(d.get("total") or 0)
except (TypeError, ValueError):
_tot_in = 0
if _tot_in > 0:
m["plan_total"] = _tot_in
total = _tot_in or int(m.get("plan_total") or 0) or len(m.get("templates") or []) or 1
m["files"] = files
if d.get("note"):
m["note"] = str(d["note"])[:300]
@@ -2772,6 +3062,24 @@ class H(BaseHTTPRequestHandler):
m["state"] = "done"
m["finished"] = now().isoformat(timespec="seconds")
m.setdefault("accepted", False) # 收货闸:没确认只能看 512 预览
# ⚠️ 2026-10-05(外部复查):渲染机显式收单(close)但没收满 total 张 = 部分失败。
# 原来照样标「已完成」,失败原因只写进 note —— 而 done 状态的页面文案会把 note 盖掉,
# 买家看到「渲染完成」、金钻也收不到任何提醒(静默少交货)。
# 现在:记下缺了几张 + 往 calls.jsonl 写一条(走「呼叫金钻」同一套通知)+ 页面说实话。
if d.get("close") and len(files) < total:
m["partial"] = {"got": len(files), "want": total,
"why": str(d.get("note") or "")[:300],
"at": now().isoformat(timespec="seconds")}
try:
with open(CALLS_FILE, "a", encoding="utf-8") as f:
f.write(json.dumps({"ts": m["partial"]["at"], "ip": "渲染机", "order": oid,
"notified": False, "kind": "部分失败",
"note": ("收到 %d/%d 个文件:%s" % (len(files), total,
m["partial"]["why"]))[:300]},
ensure_ascii=False) + "\n")
except OSError:
pass
log("⚠️ %s 部分失败:收到 %d/%d 个文件(%s)" % (oid, len(files), total, m["partial"]["why"]))
if m.get("direct"):
# 直发单不用确认收货 —— 渲完就是「开放下载」,保留期/核销都从这一刻起算
self._extend_expire(m, m["finished"])
@@ -2869,6 +3177,16 @@ class H(BaseHTTPRequestHandler):
return self.err("文件已过期或不存在", 404)
if total > MAX_ZIP_BYTES:
return self.err("这一单合计太大(%.0f MB),请一张一张下载" % (total / 1048576.0), 413)
# ⚠️ 2026-10-05(外部复查):同一时间只打**一个**包。每个包最大 600MB 临时文件,
# 原来不限并发:同一个取件码连点 / 脚本并发几次,就能把盘和 CPU 一起占满。
if not ZIP_SEM.acquire(timeout=60):
return self.err("正在给别的订单打包,稍等一分钟再点", 503)
try:
return self._download_zip_locked(oid, m, files, base)
finally:
ZIP_SEM.release()
def _download_zip_locked(self, oid, m, files, base):
os.makedirs(TMP_DIR, exist_ok=True)
fd, zpath = tempfile.mkstemp(prefix="ys-", suffix=".zip", dir=TMP_DIR)
os.close(fd)
@@ -2876,8 +3194,11 @@ class H(BaseHTTPRequestHandler):
# 随包一份**收货凭证(小票)**:金钻 2026-10-01 —— 订单号/卡密/皮肤/逐张清单/
# 分辨率/时间/留档序号/条款版本/保存期限,闲鱼对账、留证都用它。
# ⚠️ 带 BOM(utf-8-sig):Windows 记事本打开中文才不乱码。
with zipfile.ZipFile(zpath, "w", zipfile.ZIP_DEFLATED, compresslevel=1) as z:
z.writestr("小票.txt", receipt_text(oid, m).encode("utf-8-sig"))
# PNG 本身已经压过,再 deflate 一遍几乎不变小、白烧 CPU(小机器上很明显)→ 成品直接 STORED;
# 小票是文本,单独用 DEFLATED。
with zipfile.ZipFile(zpath, "w", zipfile.ZIP_STORED) as z:
z.writestr("小票.txt", receipt_text(oid, m).encode("utf-8-sig"),
compress_type=zipfile.ZIP_DEFLATED)
for i, f in enumerate(files):
nm = re.sub(r'[\\/:*?"<>|]', "_", f.get("name") or ("out%d.png" % (i + 1)))
z.write(os.path.join(base, f["path"]), "%02d_%s" % (i + 1, nm))