Compare commits
31
Commits
1903daafc3
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c5eec6049 | ||
|
|
c8f3ae4fdb | ||
|
|
973afd7886 | ||
|
|
7c4a747ea9 | ||
|
|
56c1fa648a | ||
|
|
8fbffd8408 | ||
|
|
e453ebb0da | ||
|
|
7d2e65975b | ||
|
|
675e096675 | ||
|
|
bc8402ca67 | ||
|
|
cb7cd3649b | ||
|
|
9f2322e7ae | ||
|
|
09311aac5b | ||
|
|
6a7c7b267f | ||
|
|
4ce09ce173 | ||
|
|
daa78fc25d | ||
|
|
4f76ec4b11 | ||
|
|
f9f406f54b | ||
|
|
fd72f7192e | ||
|
|
b83511ff55 | ||
|
|
f6df52ce63 | ||
|
|
74bf490baa | ||
|
|
12e66badc6 | ||
|
|
6b05fc849a | ||
|
|
09b229deee | ||
|
|
3ae940d828 | ||
|
|
51212a07c0 | ||
|
|
651d21d882 | ||
|
|
11eb16ccae | ||
|
|
c6034e9acd | ||
|
|
1d67fda9d5 |
@@ -26,3 +26,7 @@ _shots/
|
||||
# 原始私有素材与原站导出(协作仓只保留脱敏副本)
|
||||
raw/
|
||||
backup/
|
||||
|
||||
# Python 缓存
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
@@ -1,3 +1,20 @@
|
||||
# jinzuan-werewolf
|
||||
|
||||
金钻狼人杀协作仓库(github/协作修改包经此流转)。
|
||||
|
||||
---
|
||||
|
||||
## 两批交付
|
||||
|
||||
| 目录 | 是什么 | 批次 |
|
||||
|---|---|---|
|
||||
| `portal/` `order/` | 门户与下单页(前端) | 上一批(视觉重设计) |
|
||||
| **`backend/`** | **网站后端 + 本地自助管理后台 + 测试用 Blender 工程 + 部署层片段** | **本批** |
|
||||
|
||||
> **总交接文档:`交接文档-2026-10.md`**(2026-10 这一轮前后端所有改动 / 功能增删 / 设计规范 / 业务逻辑 / 部署运维)。
|
||||
>
|
||||
> 看后端请从 **`backend/他应该知道的.md`** 开始读(生意背景 / 机器约束 / 数据边界 / 术语表),
|
||||
> 再进 `backend/README.md` 和两份交接说明。
|
||||
> 写回执照 **`backend/回执模板.md`** 填。
|
||||
|
||||
- **内容后台**(2026-10-05):网站展示内容在网页后台里改 —— 设计与安全规则见 `内容后台设计.md`,部署见 `交接文档-2026-10.md` 7.1b。
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
# 交付包 · 卡密 / 自助渲染下单(后端 + 工具)
|
||||
|
||||
> **交付方**:苏达(网站运维与技术提供)
|
||||
> **收件方**:外部协作者
|
||||
> **日期**:2026-10-05
|
||||
> **本次交付由店主拍板,范围就是他圈定的**:网站后端 + 工具后端,全部脱敏,各配交接文档。
|
||||
|
||||
---
|
||||
|
||||
## 怎么读这份包(建议顺序)
|
||||
|
||||
> 2026-10 这一轮(数据库、开单后台 / 本机开单重写、前端星系图)的总说明在仓库根目录 **`交接文档-2026-10.md`**。
|
||||
|
||||
| 顺序 | 读什么 | 为什么先读它 |
|
||||
|---|---|---|
|
||||
| 1 | **`他应该知道的.md`** | 生意怎么转、机器什么条件、哪些数据碰不得、术语表 —— **不读这个,代码里很多东西推不出来** |
|
||||
| 2 | 本文件 | 包里有什么、三条纪律、我们要你回什么 |
|
||||
| 3 | `backend-site/交接说明.md` 或 `backend-tools/交接说明.md` | 各含一节**《我们的思路与方法》**(比代码更值得看:坑都是"不报错但坏掉"那一类) |
|
||||
| 4 | 代码 | 到这儿再进代码 |
|
||||
| 5 | **`回执模板.md`** | 写回执时照它填,**不用另起格式** |
|
||||
|
||||
---
|
||||
|
||||
## 包里有什么(按店主划的交付范围)
|
||||
|
||||
| 店主说的 | 落在哪 | 里面是什么 | 交接文档 |
|
||||
|---|---|---|---|
|
||||
| **网页后端 / 自助后端** | `backend-site/` | 网站服务端全部逻辑:下单、卡密生命周期、队列、支付回调、打包下载、小票 + 管理 CLI + PNG 结构核验 | `backend-site/交接说明.md` |
|
||||
| **本地的自助管理后台** | `backend-tools/` | 局域网开单后台(带 PIN 锁)+ 纯本机开单工具 + 渲染机 + Blender 出图脚本 + 部署/启动脚本 | `backend-tools/交接说明.md` |
|
||||
| **用于测试的工程** | `模板/` | 三个 Blender 模板工程(已脱敏,可直接打开渲染) | `模板/说明.md` |
|
||||
| **其他需要的** | `deploy/` | 反向代理的路由与限流片段(部署层)+ 这一层的取舍说明 | `deploy/nginx-片段.md` |
|
||||
| **背景须知** | `他应该知道的.md` | 生意背景 / 机器约束 / 数据边界 / 术语表 / 我们这边的纪律 | — |
|
||||
| **回执模板** | `回执模板.md` | 直接照着填:问题分析 / 改正意见 / 你改了什么 + 我们拿不准的问题 + **运维个人想知道的** | — |
|
||||
|
||||
---
|
||||
|
||||
## ⭐ 我们要你回的东西(这次交付的主要目的)
|
||||
|
||||
请你读完代码后,**各回一份**回执(就放在对应目录下,文件名 `回执-<你的名字>.md`),
|
||||
每份包含三段:
|
||||
|
||||
1. **问题分析** —— 你看到的问题/风险/坏味道,**分轻重**(会丢钱/丢数据/能被人打的排前面),
|
||||
尽量**指到具体函数或行**,并说清**什么条件下会踩到**。
|
||||
2. **改正意见** —— 每条给出你建议的改法,以及**代价**(改起来多大、会不会影响别处)。
|
||||
3. **你改了什么** —— 如果你直接动手改了,逐条列:
|
||||
```
|
||||
文件 / 函数: 为什么改: 改成什么(一句话):
|
||||
⚠️ 有没有动接口路径 / 请求响应字段 / 数据格式: ← 这三样动了我们必须知道
|
||||
你怎么验证的:
|
||||
```
|
||||
|
||||
> 两份交接文档里各有两个**我们自己拿不准的具体问题**,也请顺手回答一下。
|
||||
|
||||
**"你改了什么"为什么单独要一段**:这套系统是**两台机器上各跑一份代码**
|
||||
(服务器一份、店里电脑一份),两边靠接口对齐。你只改了其中一份、
|
||||
或者改了字段名却没标出来,我们这边会**静默出不来图** —— 不报错、就是没图,
|
||||
这种最难查。所以请务必标清楚。
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 三条纪律
|
||||
|
||||
1. **私有交付**:请勿外传、勿公开、勿镜像(含截图和片段)。
|
||||
里面的**占位值**(域名、端口、路径、IP)请**保持原样**,不要替换成任何真实地址。
|
||||
2. **不要为了"跑起来"去补真实凭据**:这份代码**设计上就跑不起来**(见下),
|
||||
我们是给你**读**的,不是给你部署的。要看运行效果用 `模板/` 那三个工程。
|
||||
3. **有看不懂的先问再改**,别猜 —— 猜错的表现是"静默失效",不报错。
|
||||
|
||||
---
|
||||
|
||||
## 关于"跑不起来"这件事(不是疏漏,是刻意的)
|
||||
|
||||
出站纪律要求:**任何离开我们机器的代码,先脱敏**。所以:
|
||||
|
||||
- 站点/支付平台的**域名** → `example.com` 系列(RFC 2606 保留域,永远不会指向真站)
|
||||
- **端口** → 中性数字(不是真端口)
|
||||
- **目录、盘符路径** → `<DATA_DIR>` / `<WORKER_DIR>` / `<WIN-PATH>` 这类占位
|
||||
- **家里出口 IP、局域网 IP** → `<LOCAL-IP>` 这类占位
|
||||
- **密钥 / 令牌的值** → 代码里本来就**没有硬编码**(全走文件与环境变量),所以这一项是干净的
|
||||
|
||||
**保留未换的**(说明一下,免得你以为我们漏了):
|
||||
- `localhost` —— 回环地址,通用值,不指向任何真实主机
|
||||
- `1000 / 1024 / 2048 / 4096` —— 是**出图分辨率**,业务常量,不是端口
|
||||
- **品牌笔名** —— 属公开署名,按我们的署名口径保留
|
||||
|
||||
---
|
||||
|
||||
## 关于 `模板/` 里那三个工程
|
||||
|
||||
渲染是**拿 Blender 模板工程 + 买家的皮肤贴图**渲出来的。要真跑一遍看效果,
|
||||
你需要模板 —— 所以店主选了三个给你:
|
||||
|
||||
| 文件 | 用途 |
|
||||
|---|---|
|
||||
| `1站立正反.blend` | 最基础的一个(站立,正反两面),**先用它把链路跑通** |
|
||||
| `4海边自拍.blend` | 场景类的,带环境(测"场景重"的时候用) |
|
||||
| `5不看爆炸.blend` | **另一个场景**(动感类),用来验证"换一个场景是不是也对" |
|
||||
|
||||
> 三个合起来约 45MB。**名字前面那个数字就是模板编号**,
|
||||
> 代码里 `TEMPLATES` 那张表就是靠编号对应的(一一对应,别改文件名)。
|
||||
|
||||
**渲染环境**:Blender 4.x,命令行后台模式(`-b --factory-startup`),
|
||||
Windows 下用 `pythonw.exe` 起。具体参数看 `backend-tools/make_order.py` 顶部的用法说明。
|
||||
|
||||
---
|
||||
|
||||
## 我们的思路与方法(两份交接文档里各有一节详版)
|
||||
|
||||
代码能看出"做了什么",看不出"为什么这么做、踩过什么坑"。所以两份交接文档里
|
||||
各加了一节**《我们的思路与方法》**,把这几样都摊开了,**请你连做法本身一起评**:
|
||||
|
||||
- **给自己定的硬规矩** —— 例:正常买家一步都不许多加(防探测改动不能误伤付钱的人);
|
||||
收钱的数字一律以服务器为准;状态话术不许骗人;同一件事的逻辑只写一处。
|
||||
- **干活的方法** —— 例:改一处要顺着所有调用点核一遍;同一个东西存两处时,
|
||||
先问"读取方按哪个字段找";前端必须真在浏览器里点一遍(一批 bug 在接口层根本测不出来);
|
||||
部署完要核对"跑的是不是新代码"。
|
||||
- **付过学费的坑** —— 例:静默失败最贵(不报错、不崩、就是没效果);
|
||||
显示层会骗人(订单算对了但界面从另一个来源取数);"改完不生效"是这套系统最高频的坑。
|
||||
|
||||
每份最后还有**三个我们拿不准的"做法"**请你表态(要不要换技术栈、单机多单怎么设计、
|
||||
部署不生效有没有更稳的机制)。
|
||||
|
||||
> 我们更想要的是**对做法的批评**,不只是对某几行代码的。如果整套思路就是错的,请直说。
|
||||
|
||||
---
|
||||
|
||||
## 交付清单(自查用)
|
||||
|
||||
- [x] 网站后端:`server.py` / `admin.py` / `pngcheck.py` / `store.py`(数据库,2026-10-05 加),已脱敏
|
||||
- [x] 工具后端:19 个文件(含 `.bat` / `.ps1` / `.html` / 共用的 `skincheck.js` / Blender 脚本),已脱敏
|
||||
- [x] 两份交接文档(含《我们的思路与方法》)
|
||||
- [x] 三个模板工程,已脱敏(等长替换,文件字节数未变)
|
||||
- [x] 逐文件 SHA-256 清单(`交付清单.md`)
|
||||
- [x] 机器逐类扫描:**0 命中**(域名含大小写变体 / 端口 / 各类路径 / IP / 邮箱 / 密钥特征 /
|
||||
分享链里夹的群号与授权参数 / 第三方人名 / 长数字串)
|
||||
- [x] **独立第二双眼睛复查**(由另一个 agent 独立扫、不采信我们的自述结论)
|
||||
—— **它抓出了 3 处我们漏的**(Windows 账户名从路径与 SSH 用户名两处漏出、
|
||||
一处换过但仍像真路径的 `/srv`、一处把真端口换成了另一个像真端口的数)
|
||||
**以及 2 处"引用了却没带上"的缺件**(共用的质检脚本、打包脚本),全部已修并复扫 0 命中。
|
||||
- [ ] **故意没带的**(不是漏):运行期的数据文件(卡密池、订单、皮肤、成品、心跳、
|
||||
价格表、凭据文件等)—— 那些是**真实经营数据**,不在交付范围里。
|
||||
@@ -0,0 +1,636 @@
|
||||
#!/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)
|
||||
print("⚠️ 2026-10-05 起价格建议在内容后台改(「价格与付款」页):后台下次改价格并发布时,会以后台里的为准覆盖这里的改动。")
|
||||
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:])
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,133 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""PNG 结构核验 —— 防「夹带私货」:有人在文件尾部或元数据块里塞任意数据,
|
||||
改图看不出来,但能夹带任意字节(图片里藏文件 / 藏提示词 / 藏脚本)。
|
||||
|
||||
**只做结构判断,不解码像素** —— 零依赖、零成本、零误判。
|
||||
|
||||
判定分三档:
|
||||
拒(reject)
|
||||
* 签名不对 / 没有 IHDR / 块结构损坏或截断
|
||||
* **IEND 之后还有字节** ← 最常见的尾部夹带
|
||||
* 未知的「关键块」(首字母大写且不在白名单)→ 后面可能跟着必须解析的语义
|
||||
* **APNG(acTL)** → 多帧能藏额外画面,剥掉 acTL 会留下孤儿 fcTL
|
||||
剥(strip,不算错)
|
||||
* tEXt / zTXt / iTXt / eXIf / tIME → 元数据,很多编辑器会自动加,剥掉不影响成图
|
||||
过(pass)
|
||||
* IHDR / PLTE / IDAT / IEND / tRNS / gAMA / cHRM / sRGB / iCCP / bKGD / pHYs / sBIT
|
||||
|
||||
⚠️ 这份逻辑在前端也有一份镜像(`skincheck.js` 的 `checkPngBytes`)。
|
||||
两边必须一致 —— 前端负责**拦**(给人看的原因),后端负责**剥**(存下来的是干净字节)。
|
||||
改一边记得改另一边,`tests/png_struct_test.py` 里有共享用例。
|
||||
"""
|
||||
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
SIG = b"\x89PNG\r\n\x1a\n"
|
||||
|
||||
# 直接剥掉的辅助块(不报错)
|
||||
STRIP = {b"tEXt", b"zTXt", b"iTXt", b"eXIf", b"tIME", b"sPLT", b"hIST"}
|
||||
|
||||
# 允许出现的关键块
|
||||
CRITICAL_OK = {b"IHDR", b"PLTE", b"IDAT", b"IEND"}
|
||||
|
||||
MAX_CHUNKS = 4096 # 防"超多小块"这种结构型 DoS
|
||||
|
||||
|
||||
def scan(data):
|
||||
"""核验并清洗。
|
||||
|
||||
返回 (ok, reason, clean_bytes, notes)
|
||||
ok=False 时 clean 为 None
|
||||
"""
|
||||
notes = []
|
||||
|
||||
if not isinstance(data, (bytes, bytearray)):
|
||||
return False, "数据格式不对", None, notes
|
||||
data = bytes(data)
|
||||
if len(data) < 8 + 25 or data[:8] != SIG:
|
||||
return False, "不是 PNG 文件", None, notes
|
||||
|
||||
off = 8
|
||||
out = bytearray(SIG)
|
||||
n_chunks = 0
|
||||
seen_ihdr = False
|
||||
seen_idat = False
|
||||
seen_iend = False
|
||||
|
||||
while off < len(data):
|
||||
if n_chunks > MAX_CHUNKS:
|
||||
return False, "PNG 结构异常(块数量过多)", None, notes
|
||||
if off + 8 > len(data):
|
||||
return False, "PNG 文件损坏(块头不完整)", None, notes
|
||||
|
||||
(ln,) = struct.unpack(">I", data[off:off + 4])
|
||||
ctype = data[off + 4:off + 8]
|
||||
end = off + 12 + ln
|
||||
if ln > len(data) or end > len(data):
|
||||
return False, "PNG 文件损坏(块数据不完整)", None, notes
|
||||
|
||||
chunk = data[off:end]
|
||||
n_chunks += 1
|
||||
|
||||
# CRC 自检(不一致只记一笔,不拒 —— 目标是防夹带,不是查完整性)
|
||||
try:
|
||||
want = struct.unpack(">I", chunk[-4:])[0]
|
||||
got = zlib.crc32(chunk[4:-4]) & 0xFFFFFFFF
|
||||
if want != got:
|
||||
notes.append("块 %s 的 CRC 对不上" % ctype.decode("latin-1"))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if ctype == b"IHDR":
|
||||
if len(out) != 8:
|
||||
return False, "PNG 结构异常(IHDR 不在最前)", None, notes
|
||||
seen_ihdr = True
|
||||
out += chunk
|
||||
|
||||
elif ctype == b"IEND":
|
||||
seen_iend = True
|
||||
tail = len(data) - end # ← 尾部夹带就在这里露馅
|
||||
if tail > 0:
|
||||
return False, ("图片尾部夹带了 %d 字节额外数据(正常 PNG 到 IEND 就该结束)" % tail), None, notes
|
||||
out += chunk
|
||||
off = end
|
||||
break
|
||||
|
||||
elif ctype == b"acTL":
|
||||
return False, "这是动画 PNG(APNG),请用普通静态 PNG", None, notes
|
||||
|
||||
elif ctype == b"IDAT":
|
||||
seen_idat = True
|
||||
out += chunk
|
||||
|
||||
elif ctype in (b"PLTE", b"tRNS", b"gAMA", b"cHRM", b"sRGB", b"iCCP", b"bKGD", b"pHYs", b"sBIT"):
|
||||
out += chunk
|
||||
|
||||
elif ctype in STRIP:
|
||||
notes.append("已剥掉元数据块 %s" % ctype.decode("latin-1"))
|
||||
|
||||
else:
|
||||
critical = not (ctype[0] & 0x20) # PNG 规范:首字母大写 = 关键块
|
||||
if critical and ctype not in CRITICAL_OK:
|
||||
return False, ("图片里有无法识别的内容块 %s" % ctype.decode("latin-1", "replace")), None, notes
|
||||
notes.append("已剥掉附加块 %s" % ctype.decode("latin-1", "replace"))
|
||||
|
||||
off = end
|
||||
|
||||
if not seen_ihdr:
|
||||
return False, "PNG 缺少 IHDR(不是完整图片)", None, notes
|
||||
if not seen_idat:
|
||||
return False, "PNG 缺少图像数据(IDAT)", None, notes
|
||||
if not seen_iend:
|
||||
return False, "PNG 没有正常结束(缺 IEND)", None, notes
|
||||
|
||||
return True, "", bytes(out), notes
|
||||
|
||||
|
||||
def size_of(data):
|
||||
"""只读 IHDR 拿宽高(不解码像素)。"""
|
||||
if len(data) < 33 or data[:8] != SIG or data[12:16] != b"IHDR":
|
||||
return None
|
||||
w, h = struct.unpack(">II", data[16:24])
|
||||
return w, h
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,425 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""金钻工坊 · 数据层(SQLite,标准库自带,零依赖)
|
||||
|
||||
2026-10-05 起,原来散在 <DATA_DIR> 下的这些「拿 JSON 文件当数据库」的东西,统一进一个库:
|
||||
<DATA_DIR>/ys.db
|
||||
|
||||
| 表 | 原来在哪 | 里面是什么 |
|
||||
|-------------|-----------------------------------|------------|
|
||||
| codes | codes.json | 卡密池(一行一张码) |
|
||||
| orders | orders/<单号>/meta.json | 订单信息(一行一单;皮肤 / 成品**文件**还在 orders/<单号>/ 目录里) |
|
||||
| pay_orders | payplatform-orders.json | 爱发电回调账本(一行一笔,按平台单号幂等) |
|
||||
| calls | calls.jsonl | 「呼叫金钻」/ 反馈 / 部分失败 记录 |
|
||||
| kv | gifts.json / heartbeat.json / home_ips.json / tpl_times.json | 小块状态(一个键一份 JSON) |
|
||||
|
||||
**还是文件、没进库的**(都是人手改的配置或二进制):
|
||||
payplatform.json(凭据)、payplatform-map.json、prices.json、payinfo.json、
|
||||
worker_token / admin_token、皮肤与成品图片、feedback/ 里的反馈图、各种 .log
|
||||
|
||||
设计取舍(为什么这么做):
|
||||
* 每张表都是「几个能查的列 + 一列 data(整条记录的 JSON)」。上层代码拿到的还是原来的 dict,
|
||||
**字段想加就加,不用改表**;能查的列(state / order_id / batch …)是写入时从 data 里抽出来的。
|
||||
* 写整份 dict 的老写法(load → 改 → save)保留:save 时在**一个事务里**只改有变化的行。
|
||||
所以 server.py 里的路由逻辑一行都不用动,只是存取换了地方。
|
||||
* 并发:上层照旧 `with LOCK:`(线程锁 + 跨进程 flock);库本身开 WAL + busy_timeout,
|
||||
读不挡写、写不挡读,另一个进程(admin.py)在写也只是等一会儿,不会报 locked。
|
||||
* 断电:SQLite 事务要么全写进去、要么全没写,不会再有「半截 codes.json」。
|
||||
|
||||
第一次启动自动从旧 JSON 导入(只导一次,旧文件原样留着不删);要回退到旧版:
|
||||
python3 store.py export 把库里的数据导回成旧版的 JSON 文件
|
||||
python3 store.py check 完整性检查 + 每张表几行
|
||||
python3 store.py backup 在线热备份一份到 <DATA_DIR>/backup/ys-<时间>.db
|
||||
"""
|
||||
import json, os, sqlite3, sys, threading, time
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
# 哪些 kv 键原来是哪个文件(导入 / 导出用)
|
||||
KV_FILES = {
|
||||
"gifts": "gifts.json",
|
||||
"heartbeat": "heartbeat.json",
|
||||
"home_ips": "home_ips.json",
|
||||
"tpl_times": "tpl_times.json",
|
||||
}
|
||||
|
||||
_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS codes (
|
||||
code TEXT PRIMARY KEY,
|
||||
state TEXT NOT NULL DEFAULT 'active',
|
||||
order_id TEXT,
|
||||
batch TEXT,
|
||||
platform TEXT,
|
||||
gift TEXT,
|
||||
data TEXT NOT NULL,
|
||||
updated REAL NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS codes_state ON codes(state);
|
||||
CREATE INDEX IF NOT EXISTS codes_order ON codes(order_id);
|
||||
CREATE INDEX IF NOT EXISTS codes_batch ON codes(batch);
|
||||
CREATE INDEX IF NOT EXISTS codes_gift ON codes(gift);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS orders (
|
||||
oid TEXT PRIMARY KEY,
|
||||
state TEXT,
|
||||
created TEXT,
|
||||
data TEXT NOT NULL,
|
||||
updated REAL NOT NULL,
|
||||
purged REAL -- 文件已清理的时间;NULL = 还在。清掉的单留一行做账,不再当成「存在」
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS orders_state ON orders(state) WHERE purged IS NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS pay_orders (
|
||||
out_trade_no TEXT PRIMARY KEY,
|
||||
data TEXT NOT NULL,
|
||||
updated REAL NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS calls (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ts TEXT,
|
||||
ip TEXT,
|
||||
order_id TEXT,
|
||||
data TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS calls_ip ON calls(ip, ts);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS kv (
|
||||
k TEXT PRIMARY KEY,
|
||||
data TEXT NOT NULL,
|
||||
updated REAL NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS schema_info (k TEXT PRIMARY KEY, v TEXT);
|
||||
"""
|
||||
|
||||
|
||||
def _dump(obj):
|
||||
return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
|
||||
|
||||
def _code_cols(code, rec):
|
||||
st = rec.get("state")
|
||||
if st not in ("active", "inactive", "used", "bound"):
|
||||
st = "used" if rec.get("used") else "active"
|
||||
return (code, st, rec.get("order") or None, rec.get("batch") or None,
|
||||
rec.get("platform") or None, rec.get("gift") or None)
|
||||
|
||||
|
||||
class Store(object):
|
||||
"""一个库文件一个实例。每个线程自己一条连接(sqlite3 连接不能跨线程用)。"""
|
||||
|
||||
def __init__(self, root):
|
||||
self.root = root
|
||||
self.path = os.path.join(root, "ys.db")
|
||||
self._local = threading.local()
|
||||
os.makedirs(root, exist_ok=True)
|
||||
fresh = not os.path.exists(self.path)
|
||||
c = self.conn()
|
||||
c.executescript(_SCHEMA)
|
||||
if fresh:
|
||||
try:
|
||||
os.chmod(self.path, 0o640) # 和 codes.json 一样:别的账号读不到
|
||||
except OSError:
|
||||
pass
|
||||
if self._info("schema") is None:
|
||||
with self.tx() as c:
|
||||
c.execute("INSERT OR REPLACE INTO schema_info VALUES ('schema', ?)", (str(SCHEMA_VERSION),))
|
||||
if self._info("imported") is None:
|
||||
self.import_legacy()
|
||||
|
||||
# ------------------------------------------------------------ 连接 / 事务
|
||||
def conn(self):
|
||||
c = getattr(self._local, "c", None)
|
||||
if c is None:
|
||||
c = sqlite3.connect(self.path, timeout=30, isolation_level=None, check_same_thread=False)
|
||||
c.execute("PRAGMA journal_mode=WAL")
|
||||
c.execute("PRAGMA synchronous=NORMAL") # WAL 下 NORMAL:断电最多丢最后一个事务,不会写坏库
|
||||
c.execute("PRAGMA busy_timeout=30000")
|
||||
c.execute("PRAGMA foreign_keys=ON")
|
||||
self._local.c = c
|
||||
return c
|
||||
|
||||
class _Tx(object):
|
||||
def __init__(self, c):
|
||||
self.c = c
|
||||
|
||||
def __enter__(self):
|
||||
self.c.execute("BEGIN IMMEDIATE")
|
||||
return self.c
|
||||
|
||||
def __exit__(self, et, ev, tb):
|
||||
self.c.execute("COMMIT" if et is None else "ROLLBACK")
|
||||
return False
|
||||
|
||||
def tx(self):
|
||||
"""写事务:`with store.tx() as c:` 里的语句要么全成、要么全不成。"""
|
||||
return Store._Tx(self.conn())
|
||||
|
||||
def _info(self, k):
|
||||
r = self.conn().execute("SELECT v FROM schema_info WHERE k=?", (k,)).fetchone()
|
||||
return r[0] if r else None
|
||||
|
||||
# ------------------------------------------------------------ 卡密
|
||||
def codes_all(self):
|
||||
return {k: json.loads(d) for k, d in self.conn().execute("SELECT code, data FROM codes")}
|
||||
|
||||
def code_get(self, code):
|
||||
r = self.conn().execute("SELECT data FROM codes WHERE code=?", (code,)).fetchone()
|
||||
return json.loads(r[0]) if r else None
|
||||
|
||||
def codes_where(self, **cols):
|
||||
"""按列查:codes_where(order_id='YS…') / codes_where(gift='g1') / codes_where(state='active')"""
|
||||
ok = ("state", "order_id", "batch", "platform", "gift")
|
||||
ks = [k for k in cols if k in ok]
|
||||
sql = "SELECT code, data FROM codes" + (" WHERE " + " AND ".join("%s=?" % k for k in ks) if ks else "")
|
||||
return {k: json.loads(d) for k, d in self.conn().execute(sql, [cols[k] for k in ks])}
|
||||
|
||||
def codes_save(self, codes):
|
||||
"""整份写回(老写法 load → 改 → save 用)。一个事务里:变了的更新、没了的删掉、新的插入。"""
|
||||
now = time.time()
|
||||
with self.tx() as c:
|
||||
old = dict(c.execute("SELECT code, data FROM codes"))
|
||||
for k in set(old) - set(codes):
|
||||
c.execute("DELETE FROM codes WHERE code=?", (k,))
|
||||
for k, rec in codes.items():
|
||||
d = _dump(rec)
|
||||
if old.get(k) == d:
|
||||
continue
|
||||
c.execute("INSERT OR REPLACE INTO codes (code, state, order_id, batch, platform, gift, data, updated)"
|
||||
" VALUES (?,?,?,?,?,?,?,?)", _code_cols(k, rec) + (d, now))
|
||||
|
||||
def code_put(self, code, rec):
|
||||
with self.tx() as c:
|
||||
c.execute("INSERT OR REPLACE INTO codes (code, state, order_id, batch, platform, gift, data, updated)"
|
||||
" VALUES (?,?,?,?,?,?,?,?)", _code_cols(code, rec) + (_dump(rec), time.time()))
|
||||
|
||||
def code_counts(self):
|
||||
return dict(self.conn().execute("SELECT state, COUNT(*) FROM codes GROUP BY state"))
|
||||
|
||||
# ------------------------------------------------------------ 订单
|
||||
def order_get(self, oid):
|
||||
r = self.conn().execute("SELECT data FROM orders WHERE oid=? AND purged IS NULL", (oid,)).fetchone()
|
||||
return json.loads(r[0]) if r else None
|
||||
|
||||
def order_put(self, oid, meta):
|
||||
with self.tx() as c:
|
||||
c.execute("INSERT INTO orders (oid, state, created, data, updated, purged) VALUES (?,?,?,?,?,NULL)"
|
||||
" ON CONFLICT(oid) DO UPDATE SET state=excluded.state, created=excluded.created,"
|
||||
" data=excluded.data, updated=excluded.updated, purged=NULL",
|
||||
(oid, meta.get("state"), meta.get("created"), _dump(meta), time.time()))
|
||||
|
||||
def order_known(self, oid):
|
||||
"""这个单号用过没有(包括已清理的)—— 发新单号时防撞号。"""
|
||||
return self.conn().execute("SELECT 1 FROM orders WHERE oid=?", (oid,)).fetchone() is not None
|
||||
|
||||
def orders(self, states=None, include_purged=False):
|
||||
sql, args = "SELECT data FROM orders", []
|
||||
cond = [] if include_purged else ["purged IS NULL"]
|
||||
if states is not None:
|
||||
states = list(states)
|
||||
if not states:
|
||||
return []
|
||||
cond.append("state IN (%s)" % ",".join("?" * len(states)))
|
||||
args += states
|
||||
if cond:
|
||||
sql += " WHERE " + " AND ".join(cond)
|
||||
sql += " ORDER BY oid"
|
||||
return [json.loads(d) for (d,) in self.conn().execute(sql, args)]
|
||||
|
||||
def order_ids(self):
|
||||
return [r[0] for r in self.conn().execute("SELECT oid FROM orders WHERE purged IS NULL ORDER BY oid")]
|
||||
|
||||
def order_purge(self, oid):
|
||||
"""文件清掉了:行留着(记账 / 统计用),但之后 order_get 当它不存在。"""
|
||||
with self.tx() as c:
|
||||
c.execute("UPDATE orders SET purged=? WHERE oid=?", (time.time(), oid))
|
||||
|
||||
def order_drop(self, oid):
|
||||
"""单根本没建成(提交中途失败):连行一起删。"""
|
||||
with self.tx() as c:
|
||||
c.execute("DELETE FROM orders WHERE oid=?", (oid,))
|
||||
|
||||
def order_counts(self):
|
||||
return dict(self.conn().execute("SELECT state, COUNT(*) FROM orders WHERE purged IS NULL GROUP BY state"))
|
||||
|
||||
# ------------------------------------------------------------ 爱发电账本
|
||||
def ledger_all(self):
|
||||
return {k: json.loads(d) for k, d in self.conn().execute("SELECT out_trade_no, data FROM pay_orders")}
|
||||
|
||||
def ledger_get(self, no):
|
||||
r = self.conn().execute("SELECT data FROM pay_orders WHERE out_trade_no=?", (str(no),)).fetchone()
|
||||
return json.loads(r[0]) if r else None
|
||||
|
||||
def ledger_save(self, led):
|
||||
now = time.time()
|
||||
with self.tx() as c:
|
||||
old = dict(c.execute("SELECT out_trade_no, data FROM pay_orders"))
|
||||
for k in set(old) - set(led):
|
||||
c.execute("DELETE FROM pay_orders WHERE out_trade_no=?", (k,))
|
||||
for k, rec in led.items():
|
||||
d = _dump(rec)
|
||||
if old.get(k) != d:
|
||||
c.execute("INSERT OR REPLACE INTO pay_orders VALUES (?,?,?)", (str(k), d, now))
|
||||
|
||||
# ------------------------------------------------------------ 呼叫记录
|
||||
def call_add(self, rec):
|
||||
with self.tx() as c:
|
||||
cur = c.execute("INSERT INTO calls (ts, ip, order_id, data) VALUES (?,?,?,?)",
|
||||
(rec.get("ts"), rec.get("ip"), rec.get("order") or None, _dump(rec)))
|
||||
return cur.lastrowid
|
||||
|
||||
def calls(self, limit=None, ip=None, since=None):
|
||||
"""最近的在后。ip / since(ISO 时间串)可以筛。"""
|
||||
sql, cond, args = "SELECT id, data FROM calls", [], []
|
||||
if ip is not None:
|
||||
cond.append("ip=?"); args.append(ip)
|
||||
if since is not None:
|
||||
cond.append("ts>=?"); args.append(since)
|
||||
if cond:
|
||||
sql += " WHERE " + " AND ".join(cond)
|
||||
sql += " ORDER BY id DESC"
|
||||
if limit:
|
||||
sql += " LIMIT %d" % int(limit)
|
||||
out = []
|
||||
for i, d in self.conn().execute(sql, args):
|
||||
r = json.loads(d); r["id"] = i; out.append(r)
|
||||
return out[::-1]
|
||||
|
||||
def call_mark(self, cid, **fields):
|
||||
with self.tx() as c:
|
||||
r = c.execute("SELECT data FROM calls WHERE id=?", (cid,)).fetchone()
|
||||
if not r:
|
||||
return False
|
||||
d = json.loads(r[0]); d.update(fields)
|
||||
c.execute("UPDATE calls SET data=? WHERE id=?", (_dump(d), cid))
|
||||
return True
|
||||
|
||||
# ------------------------------------------------------------ 小块状态
|
||||
def kv_get(self, k, default=None):
|
||||
r = self.conn().execute("SELECT data FROM kv WHERE k=?", (k,)).fetchone()
|
||||
return json.loads(r[0]) if r else default
|
||||
|
||||
def kv_put(self, k, obj):
|
||||
with self.tx() as c:
|
||||
c.execute("INSERT OR REPLACE INTO kv VALUES (?,?,?)", (k, _dump(obj), time.time()))
|
||||
|
||||
# ------------------------------------------------------------ 导入 / 导出 / 体检
|
||||
def import_legacy(self):
|
||||
"""第一次启动:把旧 JSON 导进来(旧文件不动)。整个导入一个事务,失败就整体回滚、下次再试。"""
|
||||
R = self.root
|
||||
n = {"codes": 0, "orders": 0, "pay_orders": 0, "calls": 0, "kv": 0}
|
||||
|
||||
def jl(p, default):
|
||||
try:
|
||||
with open(p, encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return default
|
||||
now = time.time()
|
||||
with self.tx() as c:
|
||||
# 服务器和 admin.py 同时第一次启动时,两边都会走到这里:BEGIN IMMEDIATE 让它们排队,
|
||||
# 后进来的那个在事务里再看一眼,导过了就不再导(不然呼叫记录会导两份)
|
||||
if c.execute("SELECT 1 FROM schema_info WHERE k='imported'").fetchone():
|
||||
return None
|
||||
for k, rec in (jl(os.path.join(R, "codes.json"), {}) or {}).items():
|
||||
if isinstance(rec, dict):
|
||||
c.execute("INSERT OR IGNORE INTO codes (code, state, order_id, batch, platform, gift, data, updated)"
|
||||
" VALUES (?,?,?,?,?,?,?,?)", _code_cols(k, rec) + (_dump(rec), now))
|
||||
n["codes"] += 1
|
||||
od = os.path.join(R, "orders")
|
||||
if os.path.isdir(od):
|
||||
for oid in sorted(os.listdir(od)):
|
||||
m = jl(os.path.join(od, oid, "meta.json"), None)
|
||||
if isinstance(m, dict):
|
||||
c.execute("INSERT OR IGNORE INTO orders (oid, state, created, data, updated) VALUES (?,?,?,?,?)",
|
||||
(oid, m.get("state"), m.get("created"), _dump(m), now))
|
||||
n["orders"] += 1
|
||||
for k, rec in (jl(os.path.join(R, "payplatform-orders.json"), {}) or {}).items():
|
||||
c.execute("INSERT OR IGNORE INTO pay_orders VALUES (?,?,?)", (str(k), _dump(rec), now))
|
||||
n["pay_orders"] += 1
|
||||
try:
|
||||
with open(os.path.join(R, "calls.jsonl"), encoding="utf-8") as f:
|
||||
for line in f:
|
||||
try:
|
||||
r = json.loads(line)
|
||||
except ValueError:
|
||||
continue # 旧文件里写了半行的那条跳过
|
||||
if isinstance(r, dict):
|
||||
c.execute("INSERT INTO calls (ts, ip, order_id, data) VALUES (?,?,?,?)",
|
||||
(r.get("ts"), r.get("ip"), r.get("order") or None, _dump(r)))
|
||||
n["calls"] += 1
|
||||
except OSError:
|
||||
pass
|
||||
for k, fn in KV_FILES.items():
|
||||
v = jl(os.path.join(R, fn), None)
|
||||
if v is not None:
|
||||
c.execute("INSERT OR IGNORE INTO kv VALUES (?,?,?)", (k, _dump(v), now))
|
||||
n["kv"] += 1
|
||||
c.execute("INSERT OR REPLACE INTO schema_info VALUES ('imported', ?)",
|
||||
(json.dumps({"at": time.strftime("%Y-%m-%d %H:%M:%S"), "n": n}, ensure_ascii=False),))
|
||||
return n
|
||||
|
||||
def export_legacy(self, dest=None):
|
||||
"""把库导回旧版 JSON(回退用)。dest 不给 = 写回 <DATA_DIR>(会覆盖那几个旧文件)。"""
|
||||
D = dest or self.root
|
||||
os.makedirs(os.path.join(D, "orders"), exist_ok=True)
|
||||
|
||||
def js(p, obj):
|
||||
tmp = p + ".export.tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(obj, f, ensure_ascii=False, indent=1)
|
||||
os.replace(tmp, p)
|
||||
js(os.path.join(D, "codes.json"), self.codes_all())
|
||||
js(os.path.join(D, "payplatform-orders.json"), self.ledger_all())
|
||||
for m in self.orders():
|
||||
od = os.path.join(D, "orders", m["oid"])
|
||||
os.makedirs(od, exist_ok=True)
|
||||
js(os.path.join(od, "meta.json"), m)
|
||||
with open(os.path.join(D, "calls.jsonl"), "w", encoding="utf-8") as f:
|
||||
for r in self.calls():
|
||||
r.pop("id", None)
|
||||
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
||||
for k, fn in KV_FILES.items():
|
||||
v = self.kv_get(k)
|
||||
if v is not None:
|
||||
js(os.path.join(D, fn), v)
|
||||
return D
|
||||
|
||||
def check(self):
|
||||
c = self.conn()
|
||||
ok = c.execute("PRAGMA integrity_check").fetchone()[0]
|
||||
n = {t: c.execute("SELECT COUNT(*) FROM %s" % t).fetchone()[0]
|
||||
for t in ("codes", "orders", "pay_orders", "calls", "kv")}
|
||||
return ok, n, self._info("imported")
|
||||
|
||||
def backup(self, dest=None):
|
||||
"""在线热备份(服务器不用停)。"""
|
||||
d = dest or os.path.join(self.root, "backup")
|
||||
os.makedirs(d, exist_ok=True)
|
||||
p = os.path.join(d, "ys-%s.db" % time.strftime("%Y%m%d-%H%M%S"))
|
||||
b = sqlite3.connect(p)
|
||||
with b:
|
||||
self.conn().backup(b)
|
||||
b.close()
|
||||
os.chmod(p, 0o600)
|
||||
return p
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
root = os.environ.get("YS_ROOT", "<DATA_DIR>")
|
||||
cmd = (sys.argv[1:] or ["check"])[0]
|
||||
st = Store(root)
|
||||
if cmd == "check":
|
||||
ok, n, imp = st.check()
|
||||
print("完整性:%s" % ok)
|
||||
for k, v in n.items():
|
||||
print(" %-10s %d 行" % (k, v))
|
||||
print("旧数据导入:%s" % (imp or "(没导过)"))
|
||||
elif cmd == "export":
|
||||
print("已导出到 %s" % st.export_legacy(sys.argv[2] if len(sys.argv) > 2 else None))
|
||||
elif cmd == "backup":
|
||||
print("备份好了:%s" % st.backup())
|
||||
else:
|
||||
print(__doc__)
|
||||
sys.exit(2)
|
||||
@@ -0,0 +1,397 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""内容后台(cms.py)测试 —— 数据全是这里现编的,不碰任何真实环境。
|
||||
|
||||
用法:python3 tests/内容后台测试.py <server.py 所在目录> [仓库根目录]
|
||||
· 交付副本里三个 URL 格式串被脱敏弄坏了(http<WIN-PATH>),跑之前先换成能格式化的占位(同另外两份测试);
|
||||
· 会在临时目录建数据目录 + 门户 / 下单页目录(从仓库拷 content/ 当初始内容),起一份 server,从 HTTP 层打接口;
|
||||
· 需要 ffmpeg 才测得到「缩略图生成」那一条(没有就测「退回用原图」)。
|
||||
"""
|
||||
import base64, json, os, re, shutil, sqlite3, struct, subprocess, sys, tempfile, threading, time, urllib.request, urllib.error, zlib
|
||||
|
||||
SRC = os.path.abspath(sys.argv[1])
|
||||
REPO = os.path.abspath(sys.argv[2]) if len(sys.argv) > 2 else os.path.abspath(os.path.join(SRC, "..", ".."))
|
||||
TMP = tempfile.mkdtemp(prefix="ys-cms-")
|
||||
ROOT, PORTAL, ORDER = os.path.join(TMP, "data"), os.path.join(TMP, "www"), os.path.join(TMP, "www", "order")
|
||||
os.makedirs(ROOT); os.makedirs(PORTAL); os.makedirs(ORDER)
|
||||
shutil.copytree(os.path.join(REPO, "portal", "content"), os.path.join(PORTAL, "content"))
|
||||
shutil.copytree(os.path.join(REPO, "order", "content"), os.path.join(ORDER, "content"))
|
||||
os.environ.update(YS_ROOT=ROOT, YS_PORTAL_DIR=PORTAL, YS_ORDER_DIR=ORDER)
|
||||
sys.path.insert(0, SRC)
|
||||
import server as S # noqa: E402
|
||||
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
RESULTS.append((name, bool(cond), detail))
|
||||
print(("PASS " if cond else "FAIL ") + name + ((" —— " + str(detail)[:160]) if detail else ""), flush=True)
|
||||
|
||||
|
||||
srv = S.ThreadingHTTPServer(("127.0.0.1", 0), S.H)
|
||||
srv.daemon_threads = True
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
BASE = "http://127.0.0.1:%d/api/cms/" % srv.server_address[1]
|
||||
|
||||
|
||||
class C(object):
|
||||
"""一个「浏览器」:自己记 Cookie 和 CSRF。默认走「反代 + https」的请求头。"""
|
||||
def __init__(self, ip="203.0.113.10", proto="https", origin=None):
|
||||
self.cookie, self.csrf, self.ip, self.proto, self.origin = None, "", ip, proto, origin
|
||||
|
||||
def req(self, ep, body=None, headers=None, raw=None):
|
||||
data = raw if raw is not None else (json.dumps(body).encode() if body is not None else None)
|
||||
r = urllib.request.Request(BASE + ep, data=data, method="POST" if data is not None else "GET")
|
||||
r.add_header("Content-Type", "application/json")
|
||||
r.add_header("Host", "shop.example.com")
|
||||
if self.ip:
|
||||
r.add_header("X-Real-IP", self.ip)
|
||||
if self.proto:
|
||||
r.add_header("X-Forwarded-Proto", self.proto)
|
||||
if self.origin:
|
||||
r.add_header("Origin", self.origin)
|
||||
if self.cookie:
|
||||
r.add_header("Cookie", "jz_cms=" + self.cookie)
|
||||
if data is not None and self.csrf:
|
||||
r.add_header("X-CSRF", self.csrf)
|
||||
for k, v in (headers or {}).items():
|
||||
r.add_header(k, v)
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=60) as resp:
|
||||
st, hd, b = resp.status, resp.headers, resp.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
st, hd, b = e.code, e.headers, e.read()
|
||||
for sc in hd.get_all("Set-Cookie") or []:
|
||||
m = re.match(r"jz_cms=([^;]*)", sc)
|
||||
if m:
|
||||
self.cookie = m.group(1) or None
|
||||
self.last_cookie = sc
|
||||
try:
|
||||
j = json.loads(b.decode("utf-8"))
|
||||
except ValueError:
|
||||
j = {"_raw": b.decode("utf-8", "replace")}
|
||||
if isinstance(j, dict) and j.get("csrf"):
|
||||
self.csrf = j["csrf"]
|
||||
return st, j
|
||||
|
||||
def login(self, user, pw, remember=True):
|
||||
return self.req("login", {"user": user, "password": pw, "remember": remember})
|
||||
|
||||
|
||||
def db():
|
||||
return sqlite3.connect(os.path.join(ROOT, "ys.db"))
|
||||
|
||||
|
||||
NEWPW = "Jz-内容后台-2026!"
|
||||
# ================================================================== 1. 首次启动 / 初始账号
|
||||
rows = db().execute("SELECT username, must_change, pw FROM cms_users").fetchall()
|
||||
check("首次启动:自动建了唯一一个初始账号 admin,标了必须改密", len(rows) == 1 and rows[0][0] == "admin" and rows[0][1] == 1, rows and rows[0][:2])
|
||||
check("初始密码存的是 scrypt 哈希,不是明文", rows and rows[0][2].startswith(("scrypt$", "pbkdf2$")) and rows[0][2] != "admin", rows and rows[0][2][:10])
|
||||
|
||||
# ================================================================== 2. 登录
|
||||
a = C()
|
||||
st, j = a.login("admin", "wrong-pass")
|
||||
check("错密码 → 401「账号或密码不对」", st == 401 and j.get("error") == "账号或密码不对", j)
|
||||
st, j = C(ip="203.0.113.11").login("nobody", "whatever")
|
||||
check("不存在的账号 → 同样的提示(不透露账号在不在)", st == 401 and j.get("error") == "账号或密码不对", j)
|
||||
st, j = a.login("admin", "admin")
|
||||
check("admin / admin 能登录,回 must_change", st == 200 and j.get("must_change") is True, j)
|
||||
ck = getattr(a, "last_cookie", "")
|
||||
check("Cookie:HttpOnly + SameSite=Strict + https 下 Secure + 记住我 30 天", all(x in ck for x in ("HttpOnly", "SameSite=Strict", "Secure", "Max-Age=2592000")), ck)
|
||||
|
||||
# ================================================================== 3. 强制改密前:服务端只放行 me / password / logout
|
||||
blocked = []
|
||||
for ep, body in (("content", None), ("versions", None), ("audit", None), ("sessions", None), ("draft.js", None), ("draft", {"doc": {}}),
|
||||
("publish", {}), ("rollback", {"no": 1}), ("upload", {"data": "x"}), ("discard", {}), ("sessions/revoke", {"others": True})):
|
||||
st, j = a.req(ep, body)
|
||||
if not (st == 403 and j.get("must_change")):
|
||||
blocked.append((ep, st))
|
||||
check("改密前:其它 11 个接口一律 403「请先修改初始密码」", not blocked, blocked)
|
||||
st, j = a.req("me")
|
||||
check("改密前:me 照常能用", st == 200 and j.get("must_change") is True)
|
||||
st, j = a.req("password", {"old": "admin", "new": "12345678"})
|
||||
check("新密码太常见 → 拒", st == 400 and "常见" in j.get("error", ""), j)
|
||||
st, j = a.req("password", {"old": "admin", "new": "short"})
|
||||
check("新密码太短 → 拒", st == 400 and "8" in j.get("error", ""), j)
|
||||
st, j = a.req("password", {"old": "admin", "new": "admin"})
|
||||
check("新密码是 admin → 拒", st == 400, j)
|
||||
st, j = a.req("password", {"old": "bad", "new": NEWPW})
|
||||
check("旧密码不对 → 拒", st == 400 and "现在的密码" in j.get("error", ""), j)
|
||||
old_cookie = a.cookie
|
||||
st, j = a.req("password", {"old": "admin", "new": NEWPW})
|
||||
check("首次改密成功 → 要求重新登录", st == 200 and j.get("relogin") is True, j)
|
||||
a2 = C(); a2.cookie = old_cookie
|
||||
st, _ = a2.req("me")
|
||||
check("首次改密后:原来那个会话立即作废", st == 401)
|
||||
# ⚠️ 不能在本进程里 open() 库文件:POSIX 规定关掉任何一个句柄会释放本进程对这个文件的所有锁,SQLite 的锁会被顺带清掉。
|
||||
# 所以用另一个进程(cat)去读。
|
||||
raw_db = subprocess.run(["cat", os.path.join(ROOT, "ys.db")] + ([os.path.join(ROOT, "ys.db-wal")] if os.path.exists(os.path.join(ROOT, "ys.db-wal")) else []), capture_output=True).stdout
|
||||
check("库文件(含 WAL)里找不到新密码明文", NEWPW.encode("utf-8") not in raw_db)
|
||||
st, j = a.login("admin", NEWPW)
|
||||
check("新密码登录 → 不再要求改密", st == 200 and j.get("must_change") is False, j)
|
||||
|
||||
# ================================================================== 4. 安全闸:https / CSRF / 来源 / 爆破
|
||||
st, j = C(ip="203.0.113.20", proto="http").login("admin", NEWPW)
|
||||
check("经反代但不是 https → 403,不收密码", st == 403 and "https" in j.get("error", ""), j)
|
||||
st, j = C(ip="203.0.113.21", proto=None).login("admin", NEWPW)
|
||||
check("经反代但没带 X-Forwarded-Proto → 也当成不是 https 拒掉", st == 403, j)
|
||||
loc = C(ip=None, proto=None)
|
||||
st, j = loc.login("admin", NEWPW)
|
||||
check("服务器本机直连(调试)可以 http;这时 Cookie 不带 Secure", st == 200 and "Secure" not in getattr(loc, "last_cookie", ""), getattr(loc, "last_cookie", ""))
|
||||
csrf = a.csrf; a.csrf = ""
|
||||
st, j = a.req("draft", {"doc": {}})
|
||||
check("修改类请求不带 X-CSRF → 403", st == 403, j)
|
||||
a.csrf = "forged"
|
||||
st, j = a.req("draft", {"doc": {}})
|
||||
check("X-CSRF 不对 → 403", st == 403, j)
|
||||
a.csrf = csrf
|
||||
a.origin = "https://evil.example"
|
||||
st, j = a.req("discard", {})
|
||||
check("跨站来源(Origin 不是本站)→ 403", st == 403 and "来源" in j.get("error", ""), j)
|
||||
a.origin = "https://shop.example.com"
|
||||
st, j = a.req("discard", {})
|
||||
check("同站来源照常", st == 200, j)
|
||||
a.origin = None
|
||||
bf = C(ip="198.51.100.66")
|
||||
codes = [bf.login("admin", "guess%d" % k)[0] for k in range(7)]
|
||||
check("同一 IP 连错 5 次后开始冷却 → 429", codes[:5] == [401] * 5 and 429 in codes[5:], codes)
|
||||
st, j = C(ip="198.51.100.77").login("admin", NEWPW)
|
||||
check("别的 IP 乱试几次,店主从自己的网络用对密码照常能登(不能一键把人锁在门外)", st == 200, st)
|
||||
codes = [C(ip="192.0.2.%d" % k).login("admin", "spread%d" % k)[0] for k in range(22)]
|
||||
check("分散在很多 IP 上慢慢试:同一账号合计错满 20 次也冷却", 429 in codes[20:], codes[-4:])
|
||||
for k in list(S.CMS.fails): # 清掉冷却记录,后面的用例要正常登录
|
||||
S.CMS.fails.pop(k, None)
|
||||
|
||||
# ================================================================== 5. 内容:读 / 存草稿 / 校验
|
||||
st, j = a.req("content")
|
||||
check("读内容:第 1 版 = 从网站现有内容文件导入", st == 200 and j.get("version") == 1 and j["published"]["site"]["links"], j.get("version"))
|
||||
doc = j["draft"]
|
||||
bad = json.loads(json.dumps(doc)); bad["site"]["links"][0]["url"] = "http://example.com/x"
|
||||
st, j = a.req("draft", {"doc": bad, "base": 1})
|
||||
check("校验:平台链接用 http:// → 拒,并说清是哪一个", st == 400 and "https" in j.get("error", "") and "平台入口第 1 个" in j.get("error", ""), j)
|
||||
bad = json.loads(json.dumps(doc)); bad["site"]["links"][0]["url"] = "javascript:alert(1)"
|
||||
st, j = a.req("draft", {"doc": bad, "base": 1})
|
||||
check("校验:javascript: 链接 → 拒", st == 400, j)
|
||||
bad = json.loads(json.dumps(doc)); bad["site"]["gallery"][0]["src"] = "../../etc/passwd"
|
||||
st, j = a.req("draft", {"doc": bad, "base": 1})
|
||||
check("校验:图片路径想往上跳目录 → 拒", st == 400, j)
|
||||
bad = json.loads(json.dumps(doc)); bad["order"]["templates"] = [dict(t, on=False) for t in bad["order"]["templates"]]
|
||||
st, j = a.req("draft", {"doc": bad, "base": 1})
|
||||
check("校验:模板全部下架 → 拒(至少留一个)", st == 400 and "至少" in j.get("error", ""), j)
|
||||
bad = json.loads(json.dumps(doc)); bad["order"]["templates"].append({"k": "notatpl", "n": "x", "s": "", "on": True})
|
||||
st, j = a.req("draft", {"doc": bad, "base": 1})
|
||||
check("校验:不认识的模板 key → 拒(后台不能新增模板)", st == 400, j)
|
||||
bad = json.loads(json.dumps(doc)); bad["site"]["universe"]["items"][1]["look"]["style"] = "unknownstyle"
|
||||
st, j = a.req("draft", {"doc": bad, "base": 1})
|
||||
check("校验:不认识的星球风格 → 拒", st == 400, j)
|
||||
bad = json.loads(json.dumps(doc)); bad["site"]["hero"]["tagline"] = "长" * 200
|
||||
st, j = a.req("draft", {"doc": bad, "base": 1})
|
||||
check("校验:超长 → 拒,并说清多长", st == 400 and "最多 160" in j.get("error", ""), j)
|
||||
|
||||
# 真实画展的样子(2026-10-06 线上恢复时踩到):文件名带空格、本站 mp4 视频 + 网页版副本、作品外链、离线缩略图索引、世界线主色
|
||||
real = json.loads(json.dumps(doc))
|
||||
real["site"]["gallery"] = [
|
||||
{"id": "r1", "type": "image", "date": "2024-10-20", "title": "定制 (1)", "owner": "own", "src": "exhibition/渲染与动画/20241020/星野 渲染-定制 (1).webp", "r": 1.7778,
|
||||
"links": ["https://example.com/workshop/1", "https://example.com/cgmodel/2"], "link": "https://example.com/a"},
|
||||
{"id": "r2", "type": "video", "date": "2022-10-23", "title": "本站视频", "owner": "gift", "src": "exhibition/他人赠或合照带我/20221023/忘了谁做的了 (1).mp4",
|
||||
"web": "exhibition_web/他人赠或合照带我/20221023/忘了谁做的了 (1).mp4", "r": 2.3636}]
|
||||
real["site"]["media"] = {"exhibition/渲染与动画/20241020/星野 渲染-定制 (1).webp": {"t": "thumbs/abc123.png", "r": 1.7778},
|
||||
"exhibition/他人赠或合照带我/20221023/忘了谁做的了 (1).mp4": {"t": "thumbs/def456.png", "r": 2.3636}}
|
||||
real["site"]["universe"]["items"][0]["tone"] = "#e6e1d6"
|
||||
tk = tuple(t["k"] for t in doc["order"]["templates"])
|
||||
try:
|
||||
n = S.cms.normalize(real, tk)
|
||||
ok = (n["site"]["gallery"][0]["src"] == real["site"]["gallery"][0]["src"] and n["site"]["gallery"][0]["links"] == real["site"]["gallery"][0]["links"]
|
||||
and n["site"]["gallery"][0]["link"] == "https://example.com/a" and n["site"]["gallery"][1]["web"] == real["site"]["gallery"][1]["web"]
|
||||
and n["site"]["media"] == real["site"]["media"] and n["site"]["universe"]["items"][0]["tone"] == "#e6e1d6")
|
||||
pay = S.cms.site_payload(n["site"])
|
||||
check("真实画展:带空格的文件名、本站 mp4 视频(不填 B 站链接)、网页版副本、外链、缩略图索引、世界线主色全部原样保留",
|
||||
ok and S.cms.normalize(n, tk) == n, n["site"]["gallery"])
|
||||
check("真实画展:网站内容文件里缩略图索引还在(不然画展会直接拉几百张原图)",
|
||||
pay["media"]["exhibition/他人赠或合照带我/20221023/忘了谁做的了 (1).mp4"].get("t") == "thumbs/def456.png" and pay["universe"]["UNIVERSES"][0].get("tone") == "#e6e1d6", pay["media"])
|
||||
except S.cms.Bad as e:
|
||||
check("真实画展:带空格的文件名、本站 mp4 视频、网页版副本、外链、缩略图索引全部原样保留", False, e)
|
||||
for badp in ["exhibition/a\tb.webp", "exhibition/a\"b.webp", "exhibition/a?b.webp", "thumbs/../x.png", "other/a.webp"]:
|
||||
bad = json.loads(json.dumps(real)); bad["site"]["gallery"][0]["src"] = badp
|
||||
try:
|
||||
S.cms.normalize(bad, tk); rej = False
|
||||
except S.cms.Bad:
|
||||
rej = True
|
||||
check("校验:站内路径 %r → 拒" % badp, rej)
|
||||
bad = json.loads(json.dumps(real)); bad["site"]["gallery"][1]["src"] = "exhibition/x/a.webp"
|
||||
try:
|
||||
S.cms.normalize(bad, tk); rej = False
|
||||
except S.cms.Bad as e:
|
||||
rej = "B 站" in str(e)
|
||||
check("校验:视频既没有 B 站链接、也不是本站 mp4 → 拒", rej)
|
||||
|
||||
XSS = '</script><script>alert(1)</script><img src=x onerror=alert(2)>'
|
||||
good = json.loads(json.dumps(doc))
|
||||
good["site"]["hero"]["tagline"] = "首页改一句 " + XSS[:40]
|
||||
good["site"]["hero"]["notice"] = {"on": True, "text": "国庆照常营业", "from": "", "to": ""}
|
||||
good["site"]["links"][0]["name"] = "哔哩哔哩" + "<b>x</b>"
|
||||
good["site"]["universe"]["items"].append({"no": "0005", "name": "新地球", "kind": "原创", "tag": "卡通地球", "desc": XSS, "tags": ["新"], "look": {"style": "earth", "accent": "#7FE0A8", "enter": "push"}})
|
||||
good["order"]["templates"][-1]["on"] = False
|
||||
good["order"]["prices"] = {"per": 6, "tiers": [{"n": 3, "price": 15, "url": "https://example.com/afdian/3"}]}
|
||||
good["order"]["pay"]["note"] = "付款时留言写订单号"
|
||||
st, j = a.req("draft", {"doc": good, "base": 1})
|
||||
check("存草稿:合格的内容存上,返回改了哪些板块", st == 200 and any(c[0] == "金钻宇宙" for c in j.get("changes", [])), j.get("changes"))
|
||||
st, j = a.req("content")
|
||||
check("草稿存在库里,网站上(已发布)还是原样", j.get("has_draft") and j["published"]["site"]["hero"]["tagline"] != good["site"]["hero"]["tagline"])
|
||||
|
||||
# ================================================================== 6. 预览草稿(要登录)
|
||||
st, j = C(ip="203.0.113.30").req("draft.js")
|
||||
check("预览草稿:没登录 → 401", st == 401)
|
||||
st, j = a.req("draft.js")
|
||||
body = j.get("_raw", "")
|
||||
check("预览草稿:登录了 → 拿到草稿内容 + JZ_PREVIEW", st == 200 and "window.JZ_PREVIEW = true" in body and "新地球" in body)
|
||||
check("预览草稿:</script> 被转义,塞不进脚本", "</script>" not in body.split("window.JZ_CONTENT = ", 1)[1].split("window.JZ_PREVIEW")[0], body[:80])
|
||||
|
||||
# ================================================================== 7. 发布 / 冲突 / 回滚
|
||||
st, j = a.req("publish", {"note": "测试发布", "base": 1})
|
||||
check("发布 → v2", st == 200 and j.get("version") == 2, j)
|
||||
site_js = open(os.path.join(PORTAL, "content", "site.js"), encoding="utf-8").read()
|
||||
order_js = open(os.path.join(ORDER, "content", "order.js"), encoding="utf-8").read()
|
||||
check("发布写出门户 site.js:有新世界线、</script> 被转义", "新地球" in site_js and "</script>" not in site_js.split("=", 1)[1], site_js[:120])
|
||||
check("发布写出 site.json(正本)", json.load(open(os.path.join(PORTAL, "content", "site.json"), encoding="utf-8"))["hero"]["notice"]["on"] is True)
|
||||
check("发布写出下单页 order.js:最后一个模板已下架", '"on":false' in order_js)
|
||||
pr = json.load(open(S.PRICES_FILE, encoding="utf-8")); pay = json.load(open(S.PAYINFO_FILE, encoding="utf-8"))
|
||||
check("价格档位写回 prices.json(server.py 原来的格式)", pr.get("per") == 6 and pr.get("tiers", {}).get("3", {}).get("price") == 15, pr)
|
||||
check("付款方式写回 payinfo.json", pay.get("note") == "付款时留言写订单号", pay)
|
||||
check("下单页的价格接口立刻反映新档位", S.price_for(3) == 15)
|
||||
lit = [x for x in json.loads(site_js.split("window.JZ_CONTENT = ", 1)[1].rsplit(";", 1)[0])["universe"]["UNIVERSES"] if not x.get("empty")]
|
||||
check("星系图数据:新世界线没写位置(交给 layout.js 自动排)", any(x["no"] == "0005" for x in lit))
|
||||
# 命令行改了价格之后,后台发布别的内容不能把它改回去
|
||||
pr = json.load(open(S.PRICES_FILE, encoding="utf-8")); pr["tiers"]["5"] = {"price": 22, "payplatform": ""}
|
||||
S.jsave(S.PRICES_FILE, pr)
|
||||
b = C(ip="203.0.113.40"); b.login("admin", NEWPW)
|
||||
st, j = b.req("content")
|
||||
d2 = j["draft"]; d2["site"]["hero"]["cta1"] = "看看画"
|
||||
st, j = b.req("draft", {"doc": d2, "base": 1}) # 故意拿旧底稿
|
||||
st, j = b.req("publish", {"base": 1})
|
||||
check("别人已经发布过(底稿是旧版)→ 409 冲突,不静默覆盖", st == 409 and j.get("conflict"), j)
|
||||
st, j = b.req("publish", {"base": 2})
|
||||
check("刷新到新底稿再发 → v3", st == 200 and j.get("version") == 3, j)
|
||||
check("后台发布没动价格时,不覆盖命令行改过的 prices.json", json.load(open(S.PRICES_FILE, encoding="utf-8")).get("tiers", {}).get("5", {}).get("price") == 22)
|
||||
st, j = a.req("rollback", {"no": 1})
|
||||
check("回到 v1 → 记为 v4", st == 200 and j.get("version") == 4, j)
|
||||
v1 = json.loads(db().execute("SELECT data FROM cms_versions WHERE no=1").fetchone()[0])
|
||||
v4 = json.loads(db().execute("SELECT data FROM cms_versions WHERE no=4").fetchone()[0])
|
||||
check("回滚后内容和 v1 一模一样", v1 == v4)
|
||||
check("回滚后网站文件也回去了(没有新地球)", "新地球" not in open(os.path.join(PORTAL, "content", "site.js"), encoding="utf-8").read())
|
||||
st, j = a.req("versions")
|
||||
check("发布记录 4 条,带改动摘要", st == 200 and len(j.get("versions", [])) == 4 and j["versions"][0]["chg"], j.get("versions", [{}])[0])
|
||||
|
||||
# ================================================================== 8. 传图
|
||||
def png(w=64, h=48, tail=b""):
|
||||
raw = b"".join(b"\x00" + b"".join(bytes(((x * 3) % 256, (y * 5) % 256, 120, 255)) for x in range(w)) for y in range(h))
|
||||
ch = lambda t, d: struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
|
||||
return b"\x89PNG\r\n\x1a\n" + ch(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + ch(b"tEXt", b"Comment\x00secret") + ch(b"IDAT", zlib.compress(raw)) + ch(b"IEND", b"") + tail
|
||||
du = lambda b, t="png": "data:image/%s;base64,%s" % (t, base64.b64encode(b).decode())
|
||||
st, j = a.req("upload", {"name": "测试.png", "data": du(png())})
|
||||
ok_up = st == 200 and j.get("src", "").startswith("uploads/") and os.path.exists(os.path.join(PORTAL, j.get("src", "x")))
|
||||
check("传 PNG:存进 uploads/,量好宽高比", ok_up and abs(j.get("r", 0) - 64 / 48) < 0.01, j)
|
||||
if ok_up:
|
||||
saved = open(os.path.join(PORTAL, j["src"]), "rb").read()
|
||||
check("PNG 的文字元数据块被剥掉", b"secret" not in saved)
|
||||
has_ff = shutil.which("ffmpeg") is not None
|
||||
check("缩略图:有 ffmpeg 就生成 .t.jpg,没有就退回原图", (j["thumb"].endswith(".t.jpg") and os.path.exists(os.path.join(PORTAL, j["thumb"]))) if has_ff else j["thumb"] == j["src"], j.get("thumb"))
|
||||
st, j = a.req("upload", {"name": "x.png", "data": du(png(tail=b"hidden-payload"))})
|
||||
check("传图:PNG 尾部夹带数据 → 拒", st == 400 and "核验" in j.get("error", ""), j)
|
||||
jpeg = b"\xff\xd8" + b"\xff\xe1" + struct.pack(">H", 2 + 20) + b"Exif\x00\x00GPS-LOCATION" + b"\x00" * 2 \
|
||||
+ b"\xff\xc0" + struct.pack(">HBHHB", 11, 8, 40, 60, 1) + b"\x01\x11\x00" \
|
||||
+ b"\xff\xda" + struct.pack(">HB", 8, 1) + b"\x01\x00\x00\x3f\x00" + b"\x12\x34\x56" + b"\xff\xd9"
|
||||
st, j = a.req("upload", {"name": "p.jpg", "data": du(jpeg, "jpeg")})
|
||||
saved = open(os.path.join(PORTAL, j["src"]), "rb").read() if st == 200 else b""
|
||||
check("传 JPEG:EXIF(含拍摄地点)被剥掉,尺寸读对", st == 200 and b"GPS-LOCATION" not in saved and j.get("w") == 60 and j.get("h") == 40, j)
|
||||
st, j = a.req("upload", {"name": "p.jpg", "data": du(jpeg + b"tail", "jpeg")})
|
||||
check("传 JPEG:结尾后夹带数据 → 拒", st == 400, j)
|
||||
st, j = a.req("upload", {"name": "a.txt", "data": "data:text/plain;base64,aGVsbG8="})
|
||||
check("传图:不是图片 → 拒", st == 400, j)
|
||||
st, j = a.req("upload", {"name": "big.png", "data": du(b"\x89PNG\r\n\x1a\n" + b"0" * (10 * 1024 * 1024 + 10))})
|
||||
check("传图:超过 10MB → 拒", st == 400 and "太大" in j.get("error", ""), j)
|
||||
|
||||
# ================================================================== 9. 会话管理
|
||||
c1, c2 = C(ip="203.0.113.51"), C(ip="203.0.113.52")
|
||||
c1.login("admin", NEWPW); c2.login("admin", NEWPW)
|
||||
st, j = c1.req("sessions")
|
||||
check("设备列表能看到多台,标出这台", st == 200 and len(j.get("sessions", [])) >= 3 and sum(1 for s in j["sessions"] if s.get("cur")) == 1, len(j.get("sessions", [])))
|
||||
st, j = c1.req("sessions/revoke", {"others": True})
|
||||
st2, _ = c2.req("me"); st3, _ = c1.req("me")
|
||||
check("「退出所有其它设备」:别的当场失效,这台还在", st == 200 and st2 == 401 and st3 == 200)
|
||||
st, j = c1.req("logout", {})
|
||||
st2, _ = c1.req("me")
|
||||
check("退出:服务端会话删掉,同一个 Cookie 再用 → 401", st == 200 and st2 == 401)
|
||||
c3 = C(ip="203.0.113.53"); c3.login("admin", NEWPW)
|
||||
with db() as con:
|
||||
con.execute("UPDATE cms_sessions SET expires=? WHERE th=?", (time.time() - 1, S.cms._th(c3.cookie)))
|
||||
st, _ = c3.req("me")
|
||||
check("会话过期 → 401", st == 401)
|
||||
|
||||
# ================================================================== 10. 命令行
|
||||
env = dict(os.environ, YS_ROOT=ROOT, YS_PORTAL_DIR=PORTAL, YS_ORDER_DIR=ORDER)
|
||||
run = lambda *args: subprocess.run([sys.executable, os.path.join(SRC, "admin.py"), "user"] + list(args), capture_output=True, text=True, env=env, cwd=SRC, timeout=120)
|
||||
keep = C(ip="203.0.113.60"); keep.login("admin", NEWPW)
|
||||
r = run("reset", "admin")
|
||||
m = re.search(r"临时密码:(\S+)", r.stdout)
|
||||
st, _ = keep.req("me")
|
||||
check("命令行 user reset:打印临时密码,原来的会话全部作废", m and st == 401, (r.stdout + r.stderr)[-120:])
|
||||
tmp_pw = m.group(1) if m else ""
|
||||
st, j = C(ip="203.0.113.61").login("admin", tmp_pw)
|
||||
check("用临时密码登录 → 必须改密", st == 200 and j.get("must_change") is True, j)
|
||||
check("临时密码没写进日志", tmp_pw and tmp_pw not in (open(S.LOG_FILE, encoding="utf-8").read() if os.path.exists(S.LOG_FILE) else ""))
|
||||
r = run("reset", "admin", "--to-admin")
|
||||
st, j = C(ip="203.0.113.62").login("admin", "admin")
|
||||
check("user reset --to-admin:退回 admin / admin 且必须改密", st == 200 and j.get("must_change") is True, j)
|
||||
r = run("add", "editor2", "--email", "ed@example.com", "--temp")
|
||||
m = re.search(r"临时密码:(\S+)", r.stdout)
|
||||
st, j = C(ip="203.0.113.63").login("ed@example.com", m.group(1) if m else "")
|
||||
check("user add --temp:用邮箱也能登,首次必须改密", st == 200 and j.get("must_change") is True and j.get("user") == "editor2", (r.stdout + r.stderr)[-120:])
|
||||
r = run("disable", "editor2")
|
||||
st, j = C(ip="203.0.113.64").login("editor2", m.group(1) if m else "")
|
||||
check("user disable:停用后登不上", st == 401, j)
|
||||
r = run("list")
|
||||
check("user list 能跑,列出两个账号", r.returncode == 0 and "admin" in r.stdout and "editor2" in r.stdout and "已停用" in r.stdout, r.stdout[-200:])
|
||||
r = run("add", "x y")
|
||||
check("user add:非法用户名 → 报错退出", r.returncode != 0, (r.stdout + r.stderr)[-80:])
|
||||
|
||||
# ================================================================== 11. 多个进程同时首次启动:只建一个初始账号
|
||||
R2 = tempfile.mkdtemp(prefix="ys-cms-race-")
|
||||
probe = "import sys,os;sys.path.insert(0,%r);os.environ['YS_ROOT']=%r;import server" % (SRC, R2)
|
||||
ps = [subprocess.Popen([sys.executable, "-c", probe], env=dict(os.environ, YS_ROOT=R2), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) for _ in range(3)]
|
||||
[p.wait(timeout=120) for p in ps]
|
||||
n = sqlite3.connect(os.path.join(R2, "ys.db")).execute("SELECT COUNT(*) FROM cms_users").fetchone()[0]
|
||||
check("三个进程同时首次启动:只建了一个初始账号", n == 1, n)
|
||||
|
||||
# ================================================================== 11b. 部署漏配:目录不对 / 缺内容文件 → 不建第一版、不写文件
|
||||
import store as ST
|
||||
R3 = tempfile.mkdtemp(prefix="ys-cms-dirs-")
|
||||
c3 = S.cms.CMS(ST.Store(R3), R3, log=lambda *a: None, prices_file=os.path.join(R3, "prices.json"), payinfo_file=os.path.join(R3, "payinfo.json"), tpl_keys=S.TPL_KEYS, pngcheck=S.pngcheck)
|
||||
old_p = S.cms.PORTAL_DIR
|
||||
for bad_dir, why in (("<PORTAL_DIR>", "没配环境变量"), (os.path.join(R3, "empty-www"), "目录里没有 content/site.json")):
|
||||
if not bad_dir.startswith("<"):
|
||||
os.makedirs(bad_dir, exist_ok=True)
|
||||
S.cms.PORTAL_DIR = bad_dir
|
||||
try:
|
||||
c3.current(); refused = False
|
||||
except S.cms.Bad as e:
|
||||
refused = True; msg = str(e)
|
||||
n = sqlite3.connect(os.path.join(R3, "ys.db")).execute("SELECT COUNT(*) FROM cms_versions").fetchone()[0]
|
||||
check("部署漏配(%s):内容后台拒绝工作、不建空的第一版" % why, refused and n == 0 and not os.path.exists("<PORTAL_DIR>"), msg if refused else "没拒")
|
||||
S.cms.PORTAL_DIR = old_p
|
||||
shutil.rmtree(R3, ignore_errors=True)
|
||||
|
||||
# ================================================================== 12. 原有接口不受影响
|
||||
try:
|
||||
with urllib.request.urlopen("http://127.0.0.1:%d/api/status" % srv.server_address[1], timeout=10) as r:
|
||||
stj = json.loads(r.read())
|
||||
except Exception as e:
|
||||
stj = {"err": repr(e)}
|
||||
check("下单那边的接口照常(/api/status)", stj.get("ok") is True, stj)
|
||||
|
||||
srv.shutdown()
|
||||
shutil.rmtree(TMP, ignore_errors=True); shutil.rmtree(R2, ignore_errors=True)
|
||||
bad = [n for n, ok, _ in RESULTS if not ok]
|
||||
print("\n%d 条,失败 %d 条" % (len(RESULTS), len(bad)))
|
||||
for n in bad:
|
||||
print(" ✗ " + n)
|
||||
sys.exit(1 if bad else 0)
|
||||
@@ -0,0 +1,326 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""网站后端回归 + 漏洞复现测试(自己造的假皮肤,不碰任何真实数据)。
|
||||
|
||||
用法:python3 tests/回执复现测试.py <server.py 所在目录>
|
||||
(交付副本里三个 URL 格式串被脱敏弄坏了,跑之前要先把它们换成能格式化的占位;线上原版可以直接跑)
|
||||
· 会在系统临时目录建一份独立数据目录,不碰 <DATA_DIR>;测试机上没有水印字体,预览那一步用「拷一份」代替。
|
||||
· 在临时目录里起一份 server(随机端口),从 HTTP 层打接口;
|
||||
· 每条用例各用一份新数据(不复用,免得"第一条就把码用掉");
|
||||
· 输出每条 PASS / FAIL;对原版跑一遍能看到哪些洞真实存在。
|
||||
"""
|
||||
import base64, io, json, os, struct, subprocess, sys, tempfile, threading, time, urllib.request, urllib.error, zipfile, zlib
|
||||
|
||||
SRC = os.path.abspath(sys.argv[1])
|
||||
ROOT = tempfile.mkdtemp(prefix="ys-test-")
|
||||
os.environ["YS_ROOT"] = ROOT
|
||||
sys.path.insert(0, SRC)
|
||||
import server as S # noqa: E402
|
||||
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
RESULTS.append((name, bool(cond), detail))
|
||||
print(("PASS " if cond else "FAIL ") + name + ((" —— " + detail) if detail else ""), flush=True)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 假皮肤
|
||||
def png(w=64, h=64, tail=b"", extra_chunk=None, seed=0):
|
||||
raw = b"".join(b"\x00" + b"".join(bytes(((x * 7 + y * 3 + seed) % 256, (x + seed) % 256, y % 256, 255))
|
||||
for x in range(w)) for y in range(h))
|
||||
|
||||
def chunk(t, d):
|
||||
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
|
||||
out = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0))
|
||||
if extra_chunk:
|
||||
out += chunk(*extra_chunk)
|
||||
out += chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
|
||||
return out + tail
|
||||
|
||||
|
||||
def durl(b):
|
||||
return "data:image/png;base64," + base64.b64encode(b).decode()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 起服务
|
||||
srv = S.ThreadingHTTPServer(("127.0.0.1", 0), S.H)
|
||||
srv.daemon_threads = True
|
||||
PORT = srv.server_address[1]
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
BASE = "http://127.0.0.1:%d" % PORT
|
||||
|
||||
|
||||
def req(method, path, obj=None, headers=None, raw=False, timeout=30):
|
||||
data = json.dumps(obj).encode() if obj is not None else None
|
||||
r = urllib.request.Request(BASE + path, data=data, method=method)
|
||||
r.add_header("Content-Type", "application/json")
|
||||
for k, v in (headers or {}).items():
|
||||
r.add_header(k, v)
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=timeout) as resp:
|
||||
body = resp.read()
|
||||
return resp.status, (body if raw else json.loads(body)), dict(resp.headers)
|
||||
except urllib.error.HTTPError as e:
|
||||
body = e.read()
|
||||
try:
|
||||
return e.code, (body if raw else json.loads(body)), dict(e.headers)
|
||||
except ValueError:
|
||||
return e.code, body, dict(e.headers)
|
||||
|
||||
|
||||
WK = {"X-Worker-Token": S.WT}
|
||||
TERMS = {"v": S.TERMS_VERSION, "agreed": True}
|
||||
_ip_n = [0]
|
||||
|
||||
|
||||
def new_ip():
|
||||
"""每条用例换一个来源 IP(X-Real-IP),免得被「同 IP 10 分钟 6 单」的限流串了用例。"""
|
||||
_ip_n[0] += 1
|
||||
return {"X-Real-IP": "198.51.100.%d" % _ip_n[0]}
|
||||
|
||||
|
||||
def submit(codes, templates, ip=None, **kw):
|
||||
body = {"skin": durl(png(seed=len(codes) + len(templates))), "fileName": "test.png", "arm": "classic",
|
||||
"templates": templates, "res": 1000, "codes": codes, "terms": TERMS}
|
||||
body.update(kw)
|
||||
return req("POST", "/api/submit", body, ip or new_ip())
|
||||
|
||||
|
||||
def fake_preview(oid, png_path, out_name, idx=0):
|
||||
"""测试机没有水印字体 / ffmpeg:预览直接拷一份,只为让「水印闸门」放行。"""
|
||||
rel = "out/prev_%02d.jpg" % int(idx)
|
||||
with open(png_path, "rb") as a, open(os.path.join(S.order_dir(oid), rel), "wb") as b:
|
||||
b.write(a.read())
|
||||
return rel
|
||||
|
||||
|
||||
S.make_preview = fake_preview
|
||||
|
||||
# ================================================================== 1. 正常链路(回归)
|
||||
code = S.gen_codes(1)[0]
|
||||
st, j, _ = submit([code], ["stand"])
|
||||
check("回归:卡密单提交成功", st == 200 and j.get("ok"), str(j)[:120])
|
||||
oid, tok = j.get("order"), j.get("token")
|
||||
st, j, _ = req("POST", "/api/claim", {}, WK)
|
||||
check("回归:渲染机领到这一单", st == 200 and (j.get("order") or {}).get("oid") == oid, str(j)[:120])
|
||||
claimed = j.get("order") or {}
|
||||
check("新增字段:claim 带 terms_v(订单同意的条款版本)", claimed.get("terms_v") == S.TERMS_VERSION,
|
||||
"terms_v=%r" % claimed.get("terms_v"))
|
||||
st, b, h = req("GET", "/api/skin/%s/s1" % oid, headers=WK, raw=True)
|
||||
check("回归:渲染机取得到皮肤(流式发送后内容不变)", st == 200 and b[:8] == b"\x89PNG\r\n\x1a\n"
|
||||
and int(h.get("Content-Length", -1)) == len(b))
|
||||
big = png(256, 256) + b"" # 成品
|
||||
for name in ("站立正反.png", "站立正反无压缩.png"):
|
||||
st, j, _ = req("POST", "/api/finish", {"oid": oid, "total": 2,
|
||||
"results": [{"tpl": "stand", "name": name, "png": base64.b64encode(big).decode(),
|
||||
"skin": "s1", "sec": 30}]}, WK)
|
||||
check("回归:回传两张后订单完成", j.get("done") is True, str(j)[:120])
|
||||
st, j, _ = req("GET", "/api/order/%s?t=%s" % (oid, tok))
|
||||
check("回归:订单详情可读、两张文件", st == 200 and len(j.get("files") or []) == 2, str(j.get("state")))
|
||||
st, j, _ = req("POST", "/api/accept", {"oid": oid, "token": tok})
|
||||
check("回归:确认收货", j.get("accepted") is True)
|
||||
st, b, h = req("GET", "/api/dl/%s/0?t=%s" % (oid, tok), raw=True)
|
||||
check("回归:下载原图(流式)字节一致、带附件头", st == 200 and b == big and "attachment" in h.get("Content-Disposition", ""),
|
||||
"len=%d" % len(b))
|
||||
st, b, h = req("GET", "/api/zip/%s?t=%s" % (oid, tok), raw=True)
|
||||
zok = False
|
||||
if st == 200:
|
||||
z = zipfile.ZipFile(io.BytesIO(b))
|
||||
names = z.namelist()
|
||||
zok = "小票.txt" in names and len(names) == 3 and z.read(names[1]) == big
|
||||
check("回归:整单打包 zip 内容完整", zok, "status=%s" % st)
|
||||
|
||||
# 网页单(先填后付)→ 用平台卡密激活
|
||||
st, j, _ = submit([], ["wheat"], pay="prepay")
|
||||
check("回归:网页下单(待付款)", st == 200 and j.get("prepay") is True, str(j)[:100])
|
||||
p_oid, p_tok = j.get("order"), j.get("token")
|
||||
c2 = S.gen_codes(1)[0]
|
||||
st, j, _ = req("POST", "/api/activate", {"oid": p_oid, "token": p_tok, "code": c2}, new_ip())
|
||||
check("回归:网页单用卡密激活进队列", j.get("state") == "waiting", str(j)[:100])
|
||||
|
||||
# ================================================================== 2. 一码两单(并发提交同一张码)
|
||||
dup = S.gen_codes(1)[0]
|
||||
outs = []
|
||||
|
||||
|
||||
def _go():
|
||||
outs.append(submit([dup], ["stand"]))
|
||||
|
||||
|
||||
ths = [threading.Thread(target=_go) for _ in range(6)]
|
||||
[t.start() for t in ths]
|
||||
[t.join() for t in ths]
|
||||
okn = sum(1 for st, j, _ in outs if st == 200 and j.get("ok"))
|
||||
check("洞:同一张码并发提交 6 次,只能成 1 单", okn == 1, "成功了 %d 单" % okn)
|
||||
|
||||
# ================================================================== 3. 张数 / 锁模板 绕过
|
||||
c1 = S.gen_codes(1, n_fix=1)[0]
|
||||
st, j, _ = submit([c1], ["stand", "standb", "wheat", "beach", "boom", "sakura", "airship"], nTotal=1, tplUnion=["stand"])
|
||||
check("洞:「固定 1 张」的码报 nTotal=1、实际塞 7 个模板 → 必须拒", not (st == 200 and j.get("ok")),
|
||||
"server 说:%s" % (j.get("error") if isinstance(j, dict) else j))
|
||||
cl = S.gen_codes(1, tpl="stand", lock_tpl=True, n_max=5)[0]
|
||||
st, j, _ = submit([cl], ["airship"], nTotal=1, tplUnion=["stand"])
|
||||
check("洞:锁定「站立正反」的码,报 tplUnion=stand、实际出空艇 → 必须拒", not (st == 200 and j.get("ok")),
|
||||
"server 说:%s" % (j.get("error") if isinstance(j, dict) else j))
|
||||
cn = S.gen_codes(1, n_fix=3)[0]
|
||||
st, j, _ = submit([cn], ["stand", "wheat"], nTotal=3, tplUnion=["stand", "wheat", "beach"])
|
||||
check("回归:多皮肤单(第 1 张 2 个模板,整单报 3 张)照常能交", st == 200 and j.get("ok"), str(j)[:100])
|
||||
st, j, _ = submit([S.gen_codes(1)[0]], ["notatpl"])
|
||||
check("加固:不认识的模板 key 在提交时就拒(不等渲染机报错)", not (st == 200 and j.get("ok")), str(j)[:80])
|
||||
|
||||
# ================================================================== 4. 爱发电回调重放
|
||||
st, j, _ = submit([], ["stand"], pay="prepay")
|
||||
h_oid, h_tok = j.get("order"), j.get("token")
|
||||
real = {"out_trade_no": "202610050000000000000000001", "status": 2, "total_amount": "6.00", "show_amount": "6.00",
|
||||
"remark": "", "custom_order_id": h_oid, "user_id": "u1", "sku_detail": [{"name": "x", "count": 1}],
|
||||
"plan_title": "渲染", "title": ""}
|
||||
S.payplatform_find_order = lambda no, pages=3: dict(real) if no == real["out_trade_no"] else None
|
||||
hook_body = {"ec": 200, "em": "ok", "data": {"type": "order", "order": dict(real)}}
|
||||
n0 = len(S.load_codes())
|
||||
st, j1, _ = req("POST", "/api/payplatform-hook", hook_body)
|
||||
m = S.read_meta(h_oid)
|
||||
check("回归:回调对上网页单并激活", m and m.get("state") == "waiting", "state=%s" % (m or {}).get("state"))
|
||||
n1 = len(S.load_codes())
|
||||
st, j2, _ = req("POST", "/api/payplatform-hook", hook_body) # 原样重放(平台重试 / 别人照抄)
|
||||
n2 = len(S.load_codes())
|
||||
c2txt = ((j2 or {}).get("data") or {}).get("content") or ""
|
||||
check("洞:同一笔付款回调重放,不能再发码", n2 == n1 and "卡密" not in c2txt,
|
||||
"重放前 %d 张码、重放后 %d 张;返回:%s" % (n1, n2, c2txt[:40].replace("\n", " ")))
|
||||
# 第二张待付款单 + 用同一笔付款的报文、把 custom_order_id 改成它
|
||||
st, j, _ = submit([], ["stand"], pay="prepay")
|
||||
h2 = j.get("order")
|
||||
forged = json.loads(json.dumps(hook_body))
|
||||
forged["data"]["order"]["custom_order_id"] = h2
|
||||
real2 = dict(real)
|
||||
real2.pop("custom_order_id")
|
||||
S.payplatform_find_order = lambda no, pages=3: dict(real2) if no == real["out_trade_no"] else None
|
||||
req("POST", "/api/payplatform-hook", forged)
|
||||
m2 = S.read_meta(h2)
|
||||
check("洞:同一笔付款改报文里的订单号,不能再激活另一单", (m2 or {}).get("state") in ("unpaid", "paid"),
|
||||
"第二单状态=%s" % (m2 or {}).get("state"))
|
||||
|
||||
# 2026-10-06 安全加固:伪造的回调(没付款 / 开放接口查不到)不能写进账本,刷再多也只占 50 格待核对
|
||||
led0 = len(S.STORE.ledger_all())
|
||||
for k in range(60):
|
||||
fake = {"data": {"order": {"out_trade_no": "FAKE%04d" % k, "status": 1 if k % 2 else 2,
|
||||
"total_amount": "999", "title": "x" * 500}}}
|
||||
req("POST", "/api/payplatform-hook", fake)
|
||||
pend = S.STORE.kv_get("hook_unverified", []) or []
|
||||
check("洞:伪造回调刷 60 次 → 账本一条都不多,待核对清单封顶 50 条、字段截断",
|
||||
len(S.STORE.ledger_all()) == led0 and len(pend) == 50 and all(len(x.get("title", "")) <= 60 for x in pend),
|
||||
"账本 %d → %d,待核对 %d 条" % (led0, len(S.STORE.ledger_all()), len(pend)))
|
||||
logsz = os.path.getsize(S.PAYPLATFORM_LOG) if os.path.exists(S.PAYPLATFORM_LOG) else 0
|
||||
hook_big = {"data": {"order": {"out_trade_no": "BIG", "status": 1}}, "junk": "y" * 60000}
|
||||
req("POST", "/api/payplatform-hook", hook_big)
|
||||
grew = (os.path.getsize(S.PAYPLATFORM_LOG) if os.path.exists(S.PAYPLATFORM_LOG) else 0) - logsz
|
||||
check("加固:回调日志一条最多记 4KB 正文(60KB 的报文不会整包写盘)", 0 < grew < 6000, "这一条写了 %d 字节" % grew)
|
||||
|
||||
# ================================================================== 5. 重渲换皮肤绕过 PNG 核验
|
||||
st, j, _ = submit([S.gen_codes(1)[0]], ["stand"])
|
||||
r_oid, r_tok = j["order"], j["token"]
|
||||
S.write_meta(r_oid, dict(S.read_meta(r_oid), state="done"))
|
||||
evil = png(tail=b"<<hidden payload>>")
|
||||
st, j, _ = req("POST", "/api/redo", {"oid": r_oid, "token": r_tok, "skin": durl(evil), "skin_id": "s1", "all": 1})
|
||||
saved = b""
|
||||
try:
|
||||
saved = open(os.path.join(S.order_dir(r_oid), "skins", "s1.png"), "rb").read()
|
||||
except OSError:
|
||||
pass
|
||||
check("洞:重渲换皮肤夹带尾部数据 → 必须拒、不能落盘", not (st == 200 and j.get("ok")) and b"hidden" not in saved,
|
||||
"server 说:%s" % (j.get("error") if isinstance(j, dict) else j))
|
||||
st, j, _ = submit([S.gen_codes(1)[0]], ["stand"])
|
||||
r2, t2 = j["order"], j["token"]
|
||||
S.write_meta(r2, dict(S.read_meta(r2), state="done"))
|
||||
st, j, _ = req("POST", "/api/redo", {"oid": r2, "token": t2, "skin": durl(png(seed=9)), "skin_id": "s1", "all": 1})
|
||||
check("回归:重渲换一张正常皮肤照常可以", st == 200 and j.get("ok"), str(j)[:80])
|
||||
|
||||
# 2026-10-07:确认收货后不能再免费重渲(原图都拿走了还能白出一套)
|
||||
st, j, _ = submit([S.gen_codes(1)[0]], ["stand"])
|
||||
a_oid, a_tok = j["order"], j["token"]
|
||||
S.write_meta(a_oid, dict(S.read_meta(a_oid), state="done", accepted=True, accepted_at="2026-10-07T10:00:00"))
|
||||
st, j, _ = req("POST", "/api/redo", {"oid": a_oid, "token": a_tok, "files": [], "all": 1})
|
||||
check("洞:确认收货后还能点免费重渲 → 必须拒", not (st == 200 and j.get("ok"))
|
||||
and (S.read_meta(a_oid) or {}).get("state") == "done" and not (S.read_meta(a_oid) or {}).get("redo_used"),
|
||||
"server 说:%s" % (j.get("error") if isinstance(j, dict) else j))
|
||||
st, j, _ = submit([S.gen_codes(1)[0]], ["stand"])
|
||||
d_oid, d_tok = j["order"], j["token"]
|
||||
S.write_meta(d_oid, dict(S.read_meta(d_oid), state="done", direct=True))
|
||||
st, j, _ = req("POST", "/api/redo", {"oid": d_oid, "token": d_tok, "files": [], "all": 1})
|
||||
check("回归:直发单(没有收货这一步)照常能免费重渲", st == 200 and j.get("ok"), str(j)[:80])
|
||||
|
||||
# 2026-10-07:渲染失败的模板没有成品文件 —— 只报模板 key 也要能重渲,而且只重渲没出来的那几个
|
||||
st, j, _ = submit([S.gen_codes(1, n_fix=2)[0]], ["stand", "wheat"], nTotal=2)
|
||||
f_oid, f_tok = j["order"], j["token"]
|
||||
S.write_meta(f_oid, dict(S.read_meta(f_oid), state="failed",
|
||||
files=[{"name": "站立正反.png", "path": "x.png", "tpl": "stand"}]))
|
||||
st, j, _ = req("GET", "/api/order/%s?t=%s" % (f_oid, f_tok))
|
||||
check("状态接口:成品带模板 key、带 direct 标记(重渲弹窗靠它算哪张没出来)",
|
||||
st == 200 and (j.get("files") or [{}])[0].get("tpl") == "stand" and "direct" in j, str(j)[:120])
|
||||
st, j, _ = req("POST", "/api/redo", {"oid": f_oid, "token": f_tok, "files": [], "miss_tpls": ["wheat", "boom"]})
|
||||
mf = S.read_meta(f_oid) or {}
|
||||
check("修:失败单只勾「没出图」的模板也能重渲,只重出那一个(不认这单以外的模板)",
|
||||
st == 200 and j.get("ok") and mf.get("state") == "waiting" and mf.get("redo_tpls") == ["wheat"]
|
||||
and [x.get("name") for x in mf.get("files") or []] == ["站立正反.png"],
|
||||
"redo_tpls=%s files=%s err=%s" % (mf.get("redo_tpls"), mf.get("files"), j.get("error") if isinstance(j, dict) else j))
|
||||
|
||||
# ================================================================== 6. 反馈接口灌盘
|
||||
ip = new_ip()
|
||||
codes_ = []
|
||||
for i in range(7):
|
||||
st, j, _ = req("POST", "/api/feedback", {"note": "测试 %d" % i, "image": durl(png(seed=i))}, ip)
|
||||
codes_.append(st)
|
||||
check("洞:同一 IP 连发 7 条反馈要被限流", 429 in codes_, "状态码:%s" % codes_)
|
||||
st, j, _ = req("POST", "/api/feedback", {"note": "x", "image": "data:image/png;base64," + base64.b64encode(b"MZ\x90\x00not an image").decode()}, new_ip())
|
||||
fb = [f for f in os.listdir(os.path.join(ROOT, "feedback")) if not f.endswith(".json")]
|
||||
check("加固:反馈里的「图片」不是图片就不收", not any(open(os.path.join(ROOT, "feedback", f), "rb").read().startswith(b"MZ") for f in fb))
|
||||
|
||||
# ================================================================== 7. 部分失败要响亮
|
||||
st, j, _ = submit([S.gen_codes(1, n_fix=2)[0]], ["stand", "wheat"], nTotal=2)
|
||||
q_oid, q_tok = j["order"], j["token"]
|
||||
for _ in range(5):
|
||||
st, j, _ = req("POST", "/api/claim", {}, WK)
|
||||
if (j.get("order") or {}).get("oid") == q_oid:
|
||||
break
|
||||
req("POST", "/api/finish", {"oid": q_oid, "total": 4, "results": [{"tpl": "stand", "name": "站立正反.png",
|
||||
"png": base64.b64encode(big).decode(), "skin": "s1"}]}, WK)
|
||||
req("POST", "/api/finish", {"oid": q_oid, "close": True, "note": "部分失败:麦田萤火 渲染卡住", "results": []}, WK)
|
||||
st, j, _ = req("GET", "/api/order/%s?t=%s" % (q_oid, q_tok))
|
||||
calls = open(S.CALLS_FILE, encoding="utf-8").read() if os.path.exists(S.CALLS_FILE) else ""
|
||||
check("静默失败:4 个文件只交回 1 个 → 页面要说实话(缺 3 个)+ 呼叫金钻", "有 3 个文件没渲出来" in (j.get("note") or "") and q_oid in calls,
|
||||
"页面文案:%s" % (j.get("note") or "")[:40])
|
||||
|
||||
# ================================================================== 8. sweep 不许删流水线上的单
|
||||
st, j, _ = submit([S.gen_codes(1)[0]], ["stand"])
|
||||
w_oid = j["order"]
|
||||
mm = S.read_meta(w_oid)
|
||||
mm["created"] = (S.now() - S.timedelta(days=5)).isoformat(timespec="seconds")
|
||||
S.write_meta(w_oid, mm) # 排队中,但已经是 5 天前的单(渲染机关了几天)
|
||||
sw = subprocess.run([sys.executable, os.path.join(SRC, "admin.py"), "sweep"], capture_output=True, text=True,
|
||||
env=dict(os.environ, YS_ROOT=ROOT), cwd=SRC, timeout=60)
|
||||
check("洞:渲染机关了 5 天,排队中的单不能被 sweep 删掉", os.path.isdir(S.order_dir(w_oid)),
|
||||
(sw.stdout or sw.stderr).strip()[-80:])
|
||||
|
||||
# ================================================================== 9. 跨进程:CLI 发码 与 服务器绑码 同时进行
|
||||
before = set(S.load_codes())
|
||||
child = subprocess.Popen([sys.executable, "-c",
|
||||
"import sys;sys.path.insert(0,%r);import server as S\n"
|
||||
"for _ in range(40): S.gen_codes(5, batch='cli')" % SRC],
|
||||
env=dict(os.environ, YS_ROOT=ROOT), cwd=SRC)
|
||||
mine = S.gen_codes(30, batch="pre")
|
||||
bound_ok = 0
|
||||
for c in mine:
|
||||
st, j, _ = submit([c], ["stand"])
|
||||
bound_ok += 1 if (st == 200 and j.get("ok")) else 0
|
||||
child.wait(timeout=300)
|
||||
after = S.load_codes()
|
||||
cli_n = sum(1 for c, r in after.items() if r.get("batch") == "cli")
|
||||
still_active = [c for c in mine if (after.get(c) or {}).get("state") != "bound"]
|
||||
check("洞:CLI 一边发码、服务器一边下单 —— 发出去的码一张不少", cli_n == 200, "CLI 发了 200 张,文件里有 %d 张" % cli_n)
|
||||
check("洞:同时进行时,已下单的码不能被改回「可用」", not still_active, "被冲回去的码 %d 张(下单成功 %d 单)" % (len(still_active), bound_ok))
|
||||
|
||||
# ================================================================== 汇总
|
||||
srv.shutdown()
|
||||
bad = [n for n, ok, _ in RESULTS if not ok]
|
||||
print("\n%d 条,失败 %d 条" % (len(RESULTS), len(bad)))
|
||||
for n in bad:
|
||||
print(" ✗ " + n)
|
||||
@@ -0,0 +1,177 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""收款自动化测试(2026-10-07):精确反查、主动对账、买家自查、去掉金额猜单、付款配置键名、支付宝待开通。
|
||||
|
||||
用法:python3 tests/收款对账测试.py <server.py 所在目录>
|
||||
· 临时数据目录 + 进程内起一份 server;爱发电开放接口用假的(FAKE 列表),不连外网。
|
||||
"""
|
||||
import base64, json, os, struct, sys, tempfile, threading, urllib.error, urllib.request, zlib
|
||||
|
||||
SRC = os.path.abspath(sys.argv[1])
|
||||
ROOT = tempfile.mkdtemp(prefix="ys-pay-")
|
||||
os.environ["YS_ROOT"] = ROOT
|
||||
sys.path.insert(0, SRC)
|
||||
import server as S # noqa: E402
|
||||
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
RESULTS.append((name, bool(cond)))
|
||||
print(("PASS " if cond else "FAIL ") + name + ((" —— " + str(detail)[:200]) if detail != "" else ""), flush=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 假的爱发电开放接口
|
||||
FAKE, CALLS = [], []
|
||||
S.payplatform_creds = lambda: ("uid-test", "tok-test")
|
||||
|
||||
|
||||
def fake_api(path, params=None):
|
||||
params = params or {}
|
||||
CALLS.append(dict(params))
|
||||
if params.get("out_trade_no"):
|
||||
ids = str(params["out_trade_no"]).split(",")
|
||||
return {"ec": 200, "data": {"list": [o for o in FAKE if o["out_trade_no"] in ids], "total_page": 1}}
|
||||
pg = int(params.get("page") or 1)
|
||||
lst = list(reversed(FAKE))[(pg - 1) * 50: pg * 50]
|
||||
return {"ec": 200, "data": {"list": lst, "total_page": max(1, (len(FAKE) + 49) // 50)}}
|
||||
|
||||
|
||||
S.payplatform_api = fake_api
|
||||
_n = [0]
|
||||
|
||||
|
||||
def afd(custom="", amount="6.00", remark="", status=2):
|
||||
_n[0] += 1
|
||||
o = {"out_trade_no": "2026100712%010d" % _n[0], "custom_order_id": custom, "user_id": "buyer%d" % _n[0],
|
||||
"plan_id": "plan", "total_amount": amount, "show_amount": amount, "status": status, "remark": remark,
|
||||
"plan_title": "自选金额", "title": "", "sku_detail": [], "create_time": 0}
|
||||
FAKE.append(o)
|
||||
return o
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 起服务
|
||||
srv = S.ThreadingHTTPServer(("127.0.0.1", 0), S.H)
|
||||
srv.daemon_threads = True
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
BASE = "http://127.0.0.1:%d" % srv.server_address[1]
|
||||
|
||||
|
||||
def req(method, path, obj=None, headers=None):
|
||||
r = urllib.request.Request(BASE + path, data=json.dumps(obj).encode() if obj is not None else None, method=method)
|
||||
r.add_header("Content-Type", "application/json")
|
||||
for k, v in (headers or {}).items():
|
||||
r.add_header(k, v)
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=30) as resp:
|
||||
return resp.status, json.loads(resp.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read() or b"{}")
|
||||
|
||||
|
||||
def png(seed=0):
|
||||
raw = b"".join(b"\x00" + b"".join(bytes(((x * 7 + y * 3 + seed) % 256, x % 256, y % 256, 255)) for x in range(64))
|
||||
for y in range(64))
|
||||
ch = lambda t, d: struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
|
||||
return (b"\x89PNG\r\n\x1a\n" + ch(b"IHDR", struct.pack(">IIBBBBB", 64, 64, 8, 6, 0, 0, 0))
|
||||
+ ch(b"IDAT", zlib.compress(raw)) + ch(b"IEND", b""))
|
||||
|
||||
|
||||
_ip = [0]
|
||||
|
||||
|
||||
def prepay(templates=("stand",)):
|
||||
_ip[0] += 1
|
||||
body = {"skin": "data:image/png;base64," + base64.b64encode(png(_ip[0])).decode(), "fileName": "t.png",
|
||||
"arm": "classic", "templates": list(templates), "res": 1000, "codes": [], "pay": "prepay",
|
||||
"terms": {"v": S.TERMS_VERSION, "agreed": True}}
|
||||
st, j = req("POST", "/api/submit", body, {"X-Real-IP": "203.0.113.%d" % _ip[0]})
|
||||
assert j.get("ok"), j
|
||||
return j["order"], j["token"], S.read_meta(j["order"])["amount"]
|
||||
|
||||
|
||||
def state(oid):
|
||||
return (S.read_meta(oid) or {}).get("state")
|
||||
|
||||
|
||||
def hook(o):
|
||||
return req("POST", "/api/payplatform-hook", {"ec": 200, "em": "ok", "data": {"type": "order", "order": o}})
|
||||
|
||||
|
||||
# ================================================================ 1. 付款配置键名
|
||||
with open(os.path.join(ROOT, "payinfo.json"), "w", encoding="utf-8") as f:
|
||||
json.dump({"afdian": "https://example.com/fixed", "afdian_uid": "UID-REAL"}, f)
|
||||
st, j = req("GET", "/api/payinfo")
|
||||
check("付款配置写的是 afdian / afdian_uid → 接口两种键名都给到(页面能拼出专链)",
|
||||
j.get("afdian_uid") == "UID-REAL" and j.get("payplatform_uid") == "UID-REAL"
|
||||
and j.get("afdian") == "https://example.com/fixed", {k: j.get(k) for k in ("afdian", "afdian_uid", "payplatform_uid")})
|
||||
check("支付宝扫码:只预留入口,状态是「待开通」", (j.get("alipay") or {}).get("on") is False
|
||||
and (j.get("alipay") or {}).get("note") == "待开通", j.get("alipay"))
|
||||
|
||||
# ================================================================ 2. 回调:精确反查 + 激活
|
||||
oid, tok, amt = prepay(("stand", "wheat"))
|
||||
o = afd(custom=oid, amount="%.2f" % amt)
|
||||
CALLS.clear()
|
||||
st, j = hook(o)
|
||||
check("回调带回订单号 → 先按 out_trade_no 精确反查 → 激活", state(oid) == "waiting"
|
||||
and CALLS and CALLS[0].get("out_trade_no") == o["out_trade_no"], (state(oid), CALLS[:2]))
|
||||
check("回调应答是 JSON 且 ec=200", st == 200 and j.get("ec") == 200, j)
|
||||
st, j = hook(o)
|
||||
check("同一笔回调再推一次 → 不重复处理,仍回 ec=200", j.get("ec") == 200 and state(oid) == "waiting", j)
|
||||
|
||||
# ================================================================ 3. 主动对账:回调丢了也能激活
|
||||
oid2, tok2, amt2 = prepay()
|
||||
afd(custom=oid2, amount="%.2f" % amt2) # 只在爱发电那边有,回调没推过来
|
||||
before = state(oid2)
|
||||
got = S.payplatform_reconcile()
|
||||
check("回调丢了 → 定时对账发现并激活", before == "unpaid" and oid2 in got and state(oid2) == "waiting", (before, got))
|
||||
led_n = len(S.STORE.ledger_all())
|
||||
got2 = S.payplatform_reconcile()
|
||||
check("再对一次账 → 不会重复激活、账本不多记", got2 == [] and len(S.STORE.ledger_all()) == led_n, (got2, led_n))
|
||||
|
||||
# 留言里写了订单号(没走专链)也认
|
||||
oid3, tok3, amt3 = prepay()
|
||||
afd(custom="", amount="%.2f" % amt3, remark="我的订单 %s 谢谢" % oid3)
|
||||
got = S.payplatform_reconcile()
|
||||
check("没走专链、但留言里写了订单号 → 对账也能认出来", oid3 in got and state(oid3) == "waiting", got)
|
||||
|
||||
# ================================================================ 4. 金额不足不激活
|
||||
oid4, tok4, amt4 = prepay(("stand", "wheat", "beach"))
|
||||
afd(custom=oid4, amount="0.10")
|
||||
S.payplatform_reconcile()
|
||||
led = S.STORE.ledger_all()
|
||||
rec = [v for v in led.values() if v.get("want_order") == oid4]
|
||||
check("实付 ¥0.10 < 应付 → 不激活,记一笔待人工核对", state(oid4) == "unpaid" and rec and rec[0].get("need_human"), rec[:1])
|
||||
|
||||
# ================================================================ 5. 去掉「金额唯一匹配」猜单
|
||||
oid5, tok5, amt5 = prepay(("stand", "boom", "sakura", "airship"))
|
||||
o5 = afd(custom="", amount="%.2f" % amt5, remark="")
|
||||
hook(o5)
|
||||
check("没带订单号、留言也空 → 不再按「金额唯一」去猜,网页单保持待付款", state(oid5) == "unpaid", state(oid5))
|
||||
|
||||
# ================================================================ 6. 买家点「我付好了」→ 当场对账
|
||||
oid6, tok6, amt6 = prepay()
|
||||
afd(custom=oid6, amount="%.2f" % amt6)
|
||||
st, j = req("POST", "/api/paid", {"oid": oid6, "token": tok6})
|
||||
check("买家点「我付好了」→ 当场查到付款,直接开始排队", j.get("found") and state(oid6) == "waiting", j)
|
||||
oid7, tok7, amt7 = prepay()
|
||||
st, j = req("POST", "/api/paid", {"oid": oid7, "token": tok7})
|
||||
check("还没付就点「我付好了」→ 照旧登记成「待确认」,不会被激活", state(oid7) == "paid" and not j.get("found"), (state(oid7), j))
|
||||
afd(custom=oid7, amount="%.2f" % amt7)
|
||||
S.payplatform_reconcile()
|
||||
check("登记过「待确认」的单,钱到了 → 对账自动激活,不用人工", state(oid7) == "waiting", state(oid7))
|
||||
|
||||
# ================================================================ 7. 卡密单 / 不相关的单不受影响
|
||||
code = S.gen_codes(1)[0]
|
||||
_ip[0] += 1
|
||||
st, j = req("POST", "/api/submit", {"skin": "data:image/png;base64," + base64.b64encode(png(99)).decode(),
|
||||
"fileName": "c.png", "arm": "classic", "templates": ["stand"], "res": 1000,
|
||||
"codes": [code], "terms": {"v": S.TERMS_VERSION, "agreed": True}},
|
||||
{"X-Real-IP": "203.0.113.%d" % _ip[0]})
|
||||
check("回归:卡密下单照旧直接进队列", j.get("ok") and state(j["order"]) == "waiting", j)
|
||||
|
||||
srv.shutdown()
|
||||
bad = [n for n, ok in RESULTS if not ok]
|
||||
print("\n%d 条,失败 %d 条" % (len(RESULTS), len(bad)))
|
||||
for n in bad:
|
||||
print(" ✗ " + n)
|
||||
sys.exit(1 if bad else 0)
|
||||
@@ -0,0 +1,298 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据库(store.py / ys.db)测试 —— 数据全是这里现编的假数据,不碰任何真实环境。
|
||||
|
||||
用法:python3 tests/数据库测试.py <server.py 所在目录>
|
||||
(和 回执复现测试.py 一样:交付副本里三个 URL 格式串被脱敏弄坏了,第 9 节要起服务器,跑之前先换成能格式化的占位)
|
||||
|
||||
测的是:
|
||||
1. 全新安装:空目录第一次启动 → 自动建库,什么都不用配
|
||||
2. 老数据迁移:现编一套旧版 JSON(卡密 / 订单 meta / 爱发电账本 / 呼叫记录(含写坏的半行)/ 小块状态)→ 一次导全
|
||||
3. 重启不重复导入;旧文件原样不动
|
||||
4. 卡密整份写回 = 只改有变化的行;能查的列(state / order_id)跟着变
|
||||
5. 订单清理:行留着记账,但对外当它不存在;单号不会被重新发出去
|
||||
6. 事务:中途出错整体回滚,不留半截
|
||||
7. 导出旧版 JSON → 再导入新库,数据一模一样(回退路径能用)
|
||||
8. 热备份能打开、行数一致;完整性检查 ok
|
||||
9. 服务器直接在「迁移过来的老数据」上跑:老订单能查、老卡密能认、admin.py db / calls / ls 能用
|
||||
10. 并发:8 个线程同时记呼叫、两个进程同时写卡密,一条不丢;三个进程同时第一次启动只导一次
|
||||
11. 规模:5000 张码 + 2000 单,按状态列订单的耗时
|
||||
"""
|
||||
import json, os, random, shutil, sqlite3, subprocess, sys, tempfile, threading, time
|
||||
|
||||
SRC = os.path.abspath(sys.argv[1])
|
||||
sys.path.insert(0, SRC)
|
||||
import store # noqa: E402
|
||||
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
RESULTS.append((name, bool(cond), detail))
|
||||
print(("PASS " if cond else "FAIL ") + name + ((" —— " + detail) if detail else ""), flush=True)
|
||||
|
||||
|
||||
def jw(p, obj):
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
with open(p, "w", encoding="utf-8") as f:
|
||||
json.dump(obj, f, ensure_ascii=False, indent=1)
|
||||
|
||||
|
||||
ALPH = "23456789ABCDEFGHJKMNPQRSTUVWXYZ"
|
||||
rnd = random.Random(20261005)
|
||||
|
||||
|
||||
def fake_code():
|
||||
return "YS-" + "-".join("".join(rnd.choice(ALPH) for _ in range(4)) for _ in range(3))
|
||||
|
||||
|
||||
def fake_oid():
|
||||
return "YS" + "".join(rnd.choice(ALPH) for _ in range(6))
|
||||
|
||||
|
||||
def make_legacy(root, n_codes=40, n_orders=12):
|
||||
"""现编一套「旧版」数据目录(形状照 server.py 写出来的样子)。"""
|
||||
codes, orders = {}, {}
|
||||
states = ["waiting", "working", "done", "failed", "unpaid", "paid"]
|
||||
for i in range(n_orders):
|
||||
oid = fake_oid()
|
||||
orders[oid] = {"oid": oid, "state": states[i % len(states)], "token": "".join(rnd.choice(ALPH) for _ in range(14)),
|
||||
"created": "2026-10-0%dT1%d:00:00+08:00" % (1 + i % 4, i % 10), "arm": "classic",
|
||||
"templates": ["stand"], "res": 1000, "skins": [{"id": "s1", "path": "skin.png", "templates": ["stand"]}],
|
||||
"codes": [], "files": [], "note": "假单 %d" % i, "expire": "2026-10-09T00:00:00+08:00"}
|
||||
oids = list(orders)
|
||||
for i in range(n_codes):
|
||||
c = fake_code()
|
||||
st = ["active", "inactive", "bound", "used"][i % 4]
|
||||
rec = {"used": st == "used", "order": None, "ts": None, "batch": "测试批%d" % (i % 3), "value": 6,
|
||||
"platform": ["", "闲鱼", "爱发电"][i % 3], "tpl": "", "state": st, "set": False, "direct": False,
|
||||
"n_fix": 1, "n_max": 0, "lock_tpl": False, "n_free": False}
|
||||
if st in ("bound", "used"):
|
||||
o = oids[i % len(oids)]
|
||||
rec["order"] = o
|
||||
orders[o]["codes"].append(c)
|
||||
codes[c] = rec
|
||||
codes["YS-OLD0-OLD0-OLD0"] = {"used": True, "order": None, "batch": "最早一批"} # 老格式:只有 used 布尔
|
||||
jw(os.path.join(root, "codes.json"), codes)
|
||||
for oid, m in orders.items():
|
||||
jw(os.path.join(root, "orders", oid, "meta.json"), m)
|
||||
with open(os.path.join(root, "orders", oid, "skin.png"), "wb") as f:
|
||||
f.write(b"\x89PNG\r\n\x1a\nfake-skin")
|
||||
jw(os.path.join(root, "payplatform-orders.json"),
|
||||
{"2026100500000000000000000%02d" % i: {"ts": "2026-10-05T12:00:00+08:00", "code": fake_code(), "n_img": 1,
|
||||
"paid": "6.00", "notified": False} for i in range(5)})
|
||||
with open(os.path.join(root, "calls.jsonl"), "w", encoding="utf-8") as f:
|
||||
for i in range(6):
|
||||
f.write(json.dumps({"ts": "2026-10-05T1%d:00:00+08:00" % i, "ip": "10.0.0.%d" % i, "order": oids[i],
|
||||
"note": "等太久了 %d" % i, "notified": i % 2 == 0}, ensure_ascii=False) + "\n")
|
||||
f.write('{"ts": "2026-10-05T19:00:00+08:00", "ip": "10.0.0.9", "no') # 断电写了半行
|
||||
jw(os.path.join(root, "gifts.json"), {"batches": [{"id": "g1", "name": "国庆福利", "n_fix": 1, "enabled": True}]})
|
||||
jw(os.path.join(root, "heartbeat.json"), {"ts": "2026-10-05T12:00:00+08:00", "host": "render"})
|
||||
jw(os.path.join(root, "home_ips.json"), {"ips": ["198.51.100.7"]})
|
||||
jw(os.path.join(root, "tpl_times.json"), {"stand": [40.0, 42.5, 39.1]})
|
||||
return codes, orders
|
||||
|
||||
|
||||
def fingerprint(root):
|
||||
out = {}
|
||||
for dp, _, fs in os.walk(root):
|
||||
for f in fs:
|
||||
p = os.path.join(dp, f)
|
||||
out[os.path.relpath(p, root)] = open(p, "rb").read()
|
||||
return out
|
||||
|
||||
|
||||
# ================================================================== 1. 全新安装
|
||||
R1 = tempfile.mkdtemp(prefix="ys-db-fresh-")
|
||||
st = store.Store(R1)
|
||||
ok, n, imp = st.check()
|
||||
check("全新安装:空目录第一次启动自动建库", os.path.exists(os.path.join(R1, "ys.db")) and ok == "ok" and sum(n.values()) == 0,
|
||||
"完整性=%s 行数=%s" % (ok, n))
|
||||
check("全新安装:库文件权限不对外(640)", (os.stat(st.path).st_mode & 0o777) == 0o640, oct(os.stat(st.path).st_mode & 0o777))
|
||||
|
||||
# ================================================================== 2/3. 老数据迁移
|
||||
R2 = tempfile.mkdtemp(prefix="ys-db-legacy-")
|
||||
codes0, orders0 = make_legacy(R2)
|
||||
before = fingerprint(R2)
|
||||
st2 = store.Store(R2)
|
||||
check("迁移:卡密全部导入、内容一致", st2.codes_all() == codes0, "%d 张" % len(st2.codes_all()))
|
||||
check("迁移:订单全部导入、内容一致", {m["oid"]: m for m in st2.orders()} == orders0, "%d 单" % len(st2.orders()))
|
||||
check("迁移:爱发电账本导入", len(st2.ledger_all()) == 5)
|
||||
calls = st2.calls()
|
||||
check("迁移:呼叫记录导入(写坏的半行跳过,不影响别的)", len(calls) == 6 and calls[0]["note"] == "等太久了 0", "%d 条" % len(calls))
|
||||
check("迁移:小块状态(福利券 / 心跳 / 家里 IP / 模板耗时)导入",
|
||||
st2.kv_get("gifts")["batches"][0]["name"] == "国庆福利" and st2.kv_get("home_ips") == {"ips": ["198.51.100.7"]}
|
||||
and st2.kv_get("tpl_times")["stand"][1] == 42.5 and st2.kv_get("heartbeat")["host"] == "render")
|
||||
check("迁移:老格式卡密(只有 used 布尔)能查到、状态算成 used",
|
||||
st2.codes_where(state="used").get("YS-OLD0-OLD0-OLD0") is not None)
|
||||
bound = [c for c, r in codes0.items() if r.get("state") == "bound"]
|
||||
o1 = codes0[bound[0]]["order"]
|
||||
check("迁移:按订单号查它绑的卡密(走索引)", bound[0] in st2.codes_where(order_id=o1))
|
||||
after = {k: v for k, v in fingerprint(R2).items() if not k.startswith("ys.db")}
|
||||
check("迁移:旧文件原样不动(一个字节都没改)", after == before)
|
||||
st2b = store.Store(R2)
|
||||
check("重启:不会重复导入", len(st2b.codes_all()) == len(codes0) and len(st2b.calls()) == 6 and len(st2b.orders()) == len(orders0))
|
||||
|
||||
# ================================================================== 4. 整份写回 = 只改有变化的行
|
||||
cs = st2.codes_all()
|
||||
c_up, c_del = list(cs)[0], list(cs)[1]
|
||||
cs[c_up] = dict(cs[c_up], state="bound", order=o1)
|
||||
del cs[c_del]
|
||||
cs["YS-NEW1-NEW1-NEW1"] = {"state": "active", "batch": "新批"}
|
||||
stamp = dict(st2.conn().execute("SELECT code, updated FROM codes"))
|
||||
time.sleep(0.02)
|
||||
st2.codes_save(cs)
|
||||
stamp2 = dict(st2.conn().execute("SELECT code, updated FROM codes"))
|
||||
changed = {k for k in stamp2 if stamp2[k] != stamp.get(k)}
|
||||
check("写回:只动了改过 / 新加的两行,删掉的那行没了", changed == {c_up, "YS-NEW1-NEW1-NEW1"} and c_del not in stamp2,
|
||||
"变动的行:%s" % sorted(changed))
|
||||
check("写回:能查的列跟着变(state=bound / order_id)", c_up in st2.codes_where(state="bound", order_id=o1))
|
||||
|
||||
# ================================================================== 5. 订单清理
|
||||
victim = list(orders0)[0]
|
||||
st2.order_purge(victim)
|
||||
check("清理:清掉的单对外当它不存在", st2.order_get(victim) is None and victim not in st2.order_ids())
|
||||
check("清理:行还在(记账用),单号不会被再发出去", st2.order_known(victim)
|
||||
and any(m["oid"] == victim for m in st2.orders(include_purged=True)))
|
||||
st2.order_put(victim, orders0[victim])
|
||||
check("清理:同号重新写入会复活(恢复误删用)", st2.order_get(victim) is not None)
|
||||
st2.order_drop("YSNOPE00")
|
||||
check("清理:删不存在的单不报错", True)
|
||||
|
||||
# ================================================================== 6. 事务回滚
|
||||
n_before = len(st2.codes_all())
|
||||
try:
|
||||
with st2.tx() as c:
|
||||
c.execute("INSERT INTO codes (code, state, data, updated) VALUES ('YS-HALF-HALF-HALF','active','{}',0)")
|
||||
raise RuntimeError("中途出错(模拟断电 / 异常)")
|
||||
except RuntimeError:
|
||||
pass
|
||||
check("事务:中途出错整体回滚,不留半截", len(st2.codes_all()) == n_before and st2.code_get("YS-HALF-HALF-HALF") is None)
|
||||
|
||||
# ================================================================== 7. 导出 → 再导入,一模一样
|
||||
EXP = tempfile.mkdtemp(prefix="ys-db-export-")
|
||||
st2.export_legacy(EXP)
|
||||
st3 = store.Store(EXP)
|
||||
check("回退:导出的 JSON 再导入,卡密一模一样", st3.codes_all() == st2.codes_all())
|
||||
check("回退:订单 / 账本 / 小块状态一模一样",
|
||||
st3.orders() == st2.orders() and st3.ledger_all() == st2.ledger_all()
|
||||
and all(st3.kv_get(k) == st2.kv_get(k) for k in store.KV_FILES))
|
||||
check("回退:呼叫记录条数和内容一致", [dict(r, id=0) for r in st3.calls()] == [dict(r, id=0) for r in st2.calls()])
|
||||
|
||||
# ================================================================== 8. 备份 / 体检
|
||||
bp = st2.backup()
|
||||
b = sqlite3.connect(bp)
|
||||
bn = b.execute("SELECT COUNT(*) FROM codes").fetchone()[0]
|
||||
b.close()
|
||||
check("备份:热备份能打开、行数一致", bn == len(st2.codes_all()), bp)
|
||||
check("体检:integrity_check = ok", st2.check()[0] == "ok")
|
||||
|
||||
# ================================================================== 9. 服务器跑在迁移过来的老数据上
|
||||
R4 = tempfile.mkdtemp(prefix="ys-db-server-")
|
||||
codes4, orders4 = make_legacy(R4, n_codes=12, n_orders=6)
|
||||
o4 = [o for o, m in orders4.items() if m["state"] == "done"][0]
|
||||
b4 = [c for c, r in codes4.items() if r.get("state") == "bound"][0]
|
||||
probe = r"""
|
||||
import sys, json, threading, urllib.request
|
||||
sys.path.insert(0, %(src)r)
|
||||
import server as S
|
||||
srv = S.ThreadingHTTPServer(("127.0.0.1", 0), S.H); srv.daemon_threads = True
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
base = "http://127.0.0.1:%%d" %% srv.server_address[1]
|
||||
def get(p):
|
||||
try:
|
||||
with urllib.request.urlopen(base + p, timeout=20) as r: return r.status, json.loads(r.read())
|
||||
except urllib.error.HTTPError as e: return e.code, {}
|
||||
out = {}
|
||||
out["order"] = get("/api/order/%(oid)s?t=%(tok)s")
|
||||
out["badtok"] = get("/api/order/%(oid)s?t=WRONGTOKEN0000")
|
||||
out["code"] = S.code_info(%(code)r)
|
||||
out["status"] = get("/api/status")
|
||||
out["home_ips"] = S.HOME_IPS
|
||||
out["waiting"] = [m["oid"] for m in S.list_orders(("waiting",))]
|
||||
print(json.dumps(out, ensure_ascii=False))
|
||||
srv.shutdown()
|
||||
""" % {"src": SRC, "oid": o4, "tok": orders4[o4]["token"], "code": b4}
|
||||
env = dict(os.environ, YS_ROOT=R4)
|
||||
p = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, env=env, cwd=SRC, timeout=120)
|
||||
try:
|
||||
res = json.loads(p.stdout.strip().splitlines()[-1])
|
||||
except Exception:
|
||||
res = {}
|
||||
print(p.stdout[-800:], p.stderr[-1500:])
|
||||
check("服务器:老订单直接能查(口令对 → 200)", (res.get("order") or [0])[0] == 200, str(res.get("order"))[:100])
|
||||
check("服务器:口令错 → 404(和以前一样不承认这单)", (res.get("badtok") or [0])[0] == 404)
|
||||
check("服务器:老卡密能认,带出它绑的单", (res.get("code") or {}).get("oid") == codes4[b4]["order"])
|
||||
check("服务器:状态接口照常", (res.get("status") or [0])[0] == 200)
|
||||
check("服务器:重启后还记得家里的出口 IP(从 home_ips.json 迁过来)", res.get("home_ips") == ["198.51.100.7"])
|
||||
check("服务器:按状态列队列", sorted(res.get("waiting") or []) == sorted(o for o, m in orders4.items() if m["state"] == "waiting"))
|
||||
for args, want in ((["db", "check"], "完整性:ok"), (["calls"], "10.0.0.1"),
|
||||
(["ls", "waiting"], ""), (["stat"], "")):
|
||||
q = subprocess.run([sys.executable, os.path.join(SRC, "admin.py")] + args, capture_output=True, text=True,
|
||||
env=env, cwd=SRC, timeout=60)
|
||||
check("admin.py %s 能跑" % " ".join(args), q.returncode == 0 and want in q.stdout, (q.stdout + q.stderr).strip()[-120:])
|
||||
|
||||
# ================================================================== 10. 并发
|
||||
R5 = tempfile.mkdtemp(prefix="ys-db-conc-")
|
||||
st5 = store.Store(R5)
|
||||
|
||||
|
||||
def spam(k):
|
||||
for i in range(50):
|
||||
st5.call_add({"ts": "2026-10-05T12:00:%02d+08:00" % (i % 60), "ip": "t%d" % k, "order": "", "note": str(i)})
|
||||
|
||||
|
||||
ths = [threading.Thread(target=spam, args=(k,)) for k in range(8)]
|
||||
[t.start() for t in ths]
|
||||
[t.join() for t in ths]
|
||||
check("并发:8 个线程同时记呼叫,400 条一条不丢", len(st5.calls()) == 400, "%d 条" % len(st5.calls()))
|
||||
writer = r"""
|
||||
import sys; sys.path.insert(0, %r)
|
||||
import store
|
||||
s = store.Store(%r)
|
||||
for i in range(300):
|
||||
s.code_put("YS-P%%s-%%04d-AAAA" %% (sys.argv[1], i), {"state": "active", "batch": "proc" + sys.argv[1]})
|
||||
""" % (SRC, R5)
|
||||
ps = [subprocess.Popen([sys.executable, "-c", writer, x]) for x in ("A", "B")]
|
||||
[p.wait(timeout=120) for p in ps]
|
||||
check("并发:两个进程同时各写 300 张码,600 张一张不少", len(st5.codes_all()) == 600, "%d 张" % len(st5.codes_all()))
|
||||
R7 = tempfile.mkdtemp(prefix="ys-db-race-")
|
||||
make_legacy(R7, n_codes=20, n_orders=6)
|
||||
opener = "import sys; sys.path.insert(0, %r); import store; store.Store(%r)" % (SRC, R7)
|
||||
ps = [subprocess.Popen([sys.executable, "-c", opener]) for _ in range(3)]
|
||||
[p.wait(timeout=120) for p in ps]
|
||||
st7 = store.Store(R7)
|
||||
check("并发:三个进程同时第一次启动,旧数据只导一次(呼叫记录不翻倍)",
|
||||
len(st7.calls()) == 6 and len(st7.codes_all()) == 21, "呼叫 %d 条 · 卡密 %d 张" % (len(st7.calls()), len(st7.codes_all())))
|
||||
shutil.rmtree(R7, ignore_errors=True)
|
||||
|
||||
# ================================================================== 11. 规模
|
||||
R6 = tempfile.mkdtemp(prefix="ys-db-scale-")
|
||||
make_legacy(R6, n_codes=5000, n_orders=2000)
|
||||
t0 = time.time()
|
||||
st6 = store.Store(R6)
|
||||
t_imp = time.time() - t0
|
||||
t0 = time.time()
|
||||
for _ in range(20):
|
||||
w = st6.orders(("waiting",))
|
||||
t_q = (time.time() - t0) / 20
|
||||
t0 = time.time()
|
||||
for _ in range(20):
|
||||
old = []
|
||||
od = os.path.join(R6, "orders")
|
||||
for oid in sorted(os.listdir(od)):
|
||||
m = json.load(open(os.path.join(od, oid, "meta.json"), encoding="utf-8"))
|
||||
if m.get("state") == "waiting":
|
||||
old.append(m)
|
||||
t_old = (time.time() - t0) / 20
|
||||
check("规模:5000 张码 + 2000 单首次导入 < 10 秒", t_imp < 10, "%.2f 秒" % t_imp)
|
||||
check("规模:按状态列队列比旧版(一单一单读文件)快", t_q < t_old and len(w) == len(old),
|
||||
"数据库 %.1f ms / 旧版 %.1f ms(%d 单在排队)" % (t_q * 1000, t_old * 1000, len(w)))
|
||||
|
||||
# ================================================================== 汇总
|
||||
for d in (R1, R2, EXP, R4, R5, R6):
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
bad = [n for n, ok, _ in RESULTS if not ok]
|
||||
print("\n%d 条,失败 %d 条" % (len(RESULTS), len(bad)))
|
||||
for n in bad:
|
||||
print(" ✗ " + n)
|
||||
sys.exit(1 if bad else 0)
|
||||
@@ -0,0 +1,342 @@
|
||||
# 交接说明 · 网站后端(卡密 / 自助渲染下单)
|
||||
|
||||
> **交付方**:苏达(网站运维与技术提供)
|
||||
> **收件方**:外部协作者
|
||||
> **日期**:2026-10-05
|
||||
> **一句话**:这是一个**零依赖单进程**的下单/卡密/队列后端,跑在一台小机器上。
|
||||
> 请你重点看**安全与并发**,并给我们**问题分析 + 改正意见**(见最后一节)。
|
||||
|
||||
---
|
||||
|
||||
## 一、这一份是什么
|
||||
|
||||
「自助模板渲染」的**服务端**:买家在网页挑模板、传皮肤、填卡密下单;
|
||||
服务器登记订单、排队;家里那台渲染机上线后自动领单、出图、回传;
|
||||
买家再回来下载。**目标是无人值守** —— 不用人 24 小时盯着。
|
||||
|
||||
```
|
||||
买家 → 网页(本地质检→选模板→填卡密→核对)→ POST /api/submit
|
||||
↓ 核销卡密 + 落盘订单目录
|
||||
服务器 → 队列(订单 meta 里的一个 state 字段:waiting/working/done/failed)
|
||||
渲染机 → 每 20s:POST /hb → POST /claim → GET /skin/<单号>
|
||||
→ Blender 渲染 → POST /progress(进度)→ POST /finish(一张一次)
|
||||
买家 → GET /api/order/<单号>?t=<口令> → 下载 /api/dl/<单号>/<i>?t=<口令>
|
||||
```
|
||||
|
||||
**为什么"渲染机是主动出站"**:家里那台机器没有公网入口,所以**服务器从不连它**,
|
||||
全靠它自己定时来拉。心跳超过阈值没更新 → 页面显示「渲染机离线」。
|
||||
|
||||
---
|
||||
|
||||
## 二、技术栈与运行方式
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 语言 / 依赖 | **Python 3,纯标准库,零第三方依赖**(连 Web 框架都没用,`BaseHTTPRequestHandler`) |
|
||||
| 进程 | 单进程,由 systemd 托管;内存上限被 cgroup 卡住(小机器上防它吃爆) |
|
||||
| 监听 | **只绑回环**,公网由 nginx 反代过去(后端自己不对外开端口) |
|
||||
| 账号 | 跑在专用非 root 用户下 |
|
||||
| 数据 | **SQLite**(`<DATA_DIR>/ys.db`,标准库自带 `sqlite3`,无外部服务)+ 皮肤 / 成品图片文件。2026-10-05 接入,见第五节 |
|
||||
| 规模 | 单机单进程,日单量个位数到几十 |
|
||||
|
||||
**为什么不用框架**:这台机器很小(1G 多内存),装一个 Web 框架 + 一堆传递依赖不划算,
|
||||
而且这台机器**不允许跑重活**(视频转码这类会把它拖死)。纯标准库启动快、内存稳。
|
||||
|
||||
---
|
||||
|
||||
## 三、文件清单
|
||||
|
||||
| 文件 | 行数 | 干什么 |
|
||||
|---|---|---|
|
||||
| `server.py` | ~3100 | **全部服务端逻辑**:路由、订单状态机、卡密生命周期、限流、PNG 结构核验的调用方、爱发电回调、打包下载、小票生成 |
|
||||
| `admin.py` | ~540 | 命令行管理工具:发卡密 / 看队列 / 重渲 / 清过期 / 审计被拦记录 |
|
||||
| `pngcheck.py` | ~130 | PNG **结构**核验(不解码像素):防「夹带私货」——尾部塞字节、未知关键块、APNG |
|
||||
| `cms.py` | ~900 | **内容后台**(2026-10-05 晚):账号 / 会话 / 草稿 / 发布 / 回滚 / 传图;`server.py` 把 `/api/cms/*` 交给它。见仓库根目录 `内容后台设计.md` |
|
||||
| `store.py` | ~400 | **数据层**(2026-10-05 新增):SQLite 建库 / 第一次启动自动导入旧 JSON / 存取 / 导出回旧格式 / 体检 / 热备份 |
|
||||
| `tests/回执复现测试.py` | ~280 | 回归 + 漏洞复现(27 条,HTTP 层打接口) |
|
||||
| `tests/内容后台测试.py` | ~360 | 内容后台专项(78 条:强制改密、无明文、Cookie、https / CSRF / 来源 / 冷却、校验、发布、回滚、传图、会话、命令行) |
|
||||
| `tests/数据库测试.py` | ~290 | 数据库专项(38 条:全新安装、迁移、回退、事务、并发、规模),数据全是现编的 |
|
||||
|
||||
> 这几个文件是**自足**的:没有 import 本项目之外的模块。**部署时 `store.py`、`cms.py` 必须和 `server.py` 放在同一个目录**(`server.py` 直接 `import store` / `import cms`)。
|
||||
> 内容后台还要两个环境变量 `YS_PORTAL_DIR` / `YS_ORDER_DIR`、nginx 一节配置、首次部署马上改初始密码 —— 见 `交接文档-2026-10.md` 7.1b。
|
||||
|
||||
---
|
||||
|
||||
## 四、对外接口
|
||||
|
||||
全部挂在 `/order/api/` 下(nginx 反代);下面路径已按脱敏规则替换过前缀,**看形状别看字面**。
|
||||
|
||||
| 方法 | 路径 | 谁用 | 说明 |
|
||||
|---|---|---|---|
|
||||
| GET | `/api/status` | 页面轮询 | 渲染机在线?队列长度 |
|
||||
| POST | `/api/submit` | 页面 | 皮肤(base64) + 模板数组 + 卡密数组 + 臂型 → 返回 `{order, token}` |
|
||||
| POST | `/api/add-skin` | 页面 | 追补一张皮肤(多皮肤单) |
|
||||
| POST | `/api/set-templates` | 页面 | 改/补模板(可只改某一张皮肤的) |
|
||||
| GET | `/api/order/<单号>?t=<口令>` | 页面 | 状态 + 可下载文件清单 + 进度 + 预计耗时 |
|
||||
| GET | `/api/dl/<单号>/<i>?t=<口令>` | 买家 | 下载成品(未收货只能拿预览) |
|
||||
| GET | `/api/zip/<单号>?t=` | 买家 | 整单原图打 zip(先落临时文件再边读边发) |
|
||||
| GET | `/api/receipt/<单号>?t=` | 买家 | 小票纯文本(`&dl=1` 变附件) |
|
||||
| POST | `/api/accept` | 买家 | 确认收货 → 才放原图 |
|
||||
| POST | `/api/paid` | 买家 | 「我付好了」 |
|
||||
| POST | `/api/activate` | 买家 | 用卡密**激活自己那一单**(码认单,不开新单) |
|
||||
| POST | `/api/redo` | 买家 | 重渲(支持只重出勾中的那几张) |
|
||||
| POST | `/api/call` | 页面 | 呼叫店主(同 IP 限次) |
|
||||
| POST | `/api/feedback` | 页面 | 反馈(落盘 + 通知) |
|
||||
| GET | `/api/payinfo` | 页面 | 付款方式(链接/收款码) |
|
||||
| POST | `/api/payplatform-hook` | 支付平台回调 | **不验签,改成拿开放接口反查这笔单**(见下) |
|
||||
| POST | `/api/hb` `/api/claim` `/api/skin/<单号>` `/api/progress` `/api/finish` `/api/fail` | **渲染机** | 都要请求头里的 worker token |
|
||||
| GET/POST | `/api/admin/*` | **本机后台面板** | 头里带 admin token **且**来源 IP 必须是家里出口 IP |
|
||||
|
||||
**2026-10-05 管理接口新增四个**(都在上面那两道门后面;**老接口的路径和字段一个没动**):
|
||||
|
||||
| 方法 | 路径 | 干什么 |
|
||||
|---|---|---|
|
||||
| GET | `/api/admin/calls?limit=` | 「呼叫店主」/ 反馈 / 部分失败 记录,新的在前;`open` = 还没处理的条数 |
|
||||
| POST | `/api/admin/call-done` | `{id, undo?}` 把一条呼叫标成「处理过了」(只加 `handled` 字段,不碰 `notified`) |
|
||||
| POST | `/api/admin/retry` | `{oid}` 渲染失败的单退回队列(等于 `admin.py retry`,只收 `failed` 状态的单) |
|
||||
| GET | `/api/admin/codes?q=` | 原有接口**加了一个可选参数** `q`:按卡密 / 订单号 / 批次 / 平台模糊搜;不传和以前一样 |
|
||||
|
||||
### 支付回调的处理顺序(这段是重点,欢迎挑刺)
|
||||
|
||||
```
|
||||
① 标题含"测试" → 只记账
|
||||
② 幂等:同一平台单号重推 → 回同一张卡密
|
||||
③ 反查不到 / 未付款 → 只记账 + 标 need_human,**绝不发卡密**
|
||||
④ 金额比对:
|
||||
少付(paid + 0.005 < need)→ **闸门拦死**,不激活不发码,记 need_human
|
||||
多付 → 照样激活出图,但记 over 待人工看一眼
|
||||
⑤ 认单优先级:自定义订单号 > 留言里的卡密 > 留言里的订单号 > 「只有一笔待付款单金额对得上」
|
||||
(两笔及以上一律人工,绝不乱认)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 五、数据(2026-10-05 起:SQLite)
|
||||
|
||||
> ⚠️ **数据格式变了,按第八节的规矩单独标出来**:卡密 / 订单信息 / 爱发电账本 / 呼叫记录 / 几块小状态
|
||||
> 从 JSON 文件挪进了 `<DATA_DIR>/ys.db`。**接口路径、请求 / 响应字段都没变**,渲染机那份代码**不用动**。
|
||||
|
||||
### 5.1 装上就能用
|
||||
|
||||
1. 把 `store.py` 放到 `server.py` 旁边,照常重启服务。**什么都不用配、不用装**(`sqlite3` 是 Python 自带的)。
|
||||
2. 第一次启动时自动:建库 → 如果 `<DATA_DIR>` 里有旧的 `codes.json` / `orders/*/meta.json` / 账本等,**一次性导进来**。
|
||||
- 导入是一个事务:中途出错就整体回滚,下次启动再试。
|
||||
- **旧文件原样留着,一个字节都不改**(测试里逐字节比对过)。
|
||||
- 只导一次:库里记了「导过了」,以后重启不会重复导。
|
||||
3. 自检:`python3 admin.py db check`,看到「完整性:ok」和每张表的行数就对了。
|
||||
|
||||
⚠️ 跑 `admin.py` 的账号要对 `<DATA_DIR>` **目录**有写权限(不只是对 `ys.db`):SQLite 的 WAL 模式会在旁边建 `ys.db-wal` / `ys.db-shm` 两个文件。
|
||||
以前 `admin.py` 就要写 `codes.json`、`.lock`,权限照以前那样给就行。
|
||||
|
||||
### 5.2 库里有什么
|
||||
|
||||
| 表 | 原来在哪 | 一行是什么 | 能按什么查(有索引) |
|
||||
|---|---|---|---|
|
||||
| `codes` | `codes.json` | 一张卡密 | 状态、订单号、批次、平台、福利券批次 |
|
||||
| `orders` | `orders/<单号>/meta.json` | 一单的信息 | 状态(只算没清理的单) |
|
||||
| `pay_orders` | `payplatform-orders.json` | 一笔爱发电成交(按平台单号幂等) | 平台单号 |
|
||||
| `calls` | `calls.jsonl` | 一条呼叫 / 反馈 / 部分失败 | 来源 IP + 时间(限频用) |
|
||||
| `kv` | `gifts.json` / `heartbeat.json` / `home_ips.json` / `tpl_times.json` | 一块小状态 | 键名 |
|
||||
|
||||
每张表都是「几个能查的列 + 一列 `data`(整条记录的 JSON)」。上层代码拿到的**还是原来那个 dict**,加字段不用改表。
|
||||
|
||||
**还是文件、没进库的**:皮肤和成品图片(`orders/<单号>/` 目录还在)、`feedback/` 里的反馈图、
|
||||
两把令牌、人手改的配置(`payplatform.json`、`payplatform-map.json`、`prices.json`、`payinfo.json`)、各种 `.log`。
|
||||
|
||||
**`calls.jsonl` 还会继续追加**:库是正本,但「呼叫店主」的手机通知是盯这个文件的(那段不在这份代码里),所以每条记录**同时**照旧写一行进去,通知不会断。
|
||||
|
||||
**清理过期订单**(`admin.py sweep`):文件照旧删掉;库里那一行**留着做账**,但之后对外当它不存在(`read_meta` 返回空),单号也不会再被发出去。
|
||||
|
||||
### 5.3 为什么换、换了有什么用
|
||||
|
||||
上一轮回执里修的竞态(一码两单、CLI 和服务器互相覆盖、账本丢记录、半截 JSON),根子都是「拿 JSON 文件当数据库」。换成 SQLite 之后:
|
||||
|
||||
| | 以前(JSON 文件) | 现在(SQLite) |
|
||||
|---|---|---|
|
||||
| 断电 / 进程被杀 | 可能留下半截或 0 字节的 `codes.json`(后来加了 fsync 才堵上) | 事务要么全写进去、要么全没写 |
|
||||
| 改一张码 | 整个 `codes.json` 重写一遍 | 一个事务里只改有变化的那几行 |
|
||||
| 列出排队的单 | 把每一单的 `meta.json` 都读一遍 | 走索引:2000 单时 **38 ms,以前 1238 ms**(测试第 11 节实测) |
|
||||
| 两个进程同时写 | 靠 `.lock` 文件锁 | `.lock` 照旧保留,库本身再兜一层(WAL + 等锁 30 秒,不会报 locked) |
|
||||
| 查账 / 统计 | 只能自己写脚本扫文件 | 直接 SQL;`admin.py db check` 按状态出数 |
|
||||
| 备份 | 拷整个目录(拷的时候可能有半截写入) | `admin.py db backup` 在线热备份,服务不用停 |
|
||||
|
||||
代价:多一个 `store.py`;库文件不能直接用记事本改(要改用 `sqlite3` 命令行,或者先导出成 JSON 改完再导回)。
|
||||
|
||||
### 5.4 运维命令
|
||||
|
||||
| 命令 | 干什么 |
|
||||
|---|---|
|
||||
| `python3 admin.py db check` | 完整性检查 + 每张表几行 + 订单 / 卡密按状态的数 + 当初导入了多少 |
|
||||
| `python3 admin.py db backup` | 在线热备份到 `<DATA_DIR>/backup/ys-<时间>.db`(600 权限) |
|
||||
| `python3 admin.py db export [目录]` | 把库导回**旧版 JSON 格式**;不写目录 = 写回 `<DATA_DIR>`(会覆盖那几个旧文件) |
|
||||
| `python3 store.py check / backup / export` | 同上(不用 `admin.py` 也能跑,要先设 `YS_ROOT`) |
|
||||
|
||||
### 5.5 回退到旧版
|
||||
|
||||
1. 停服务 → `python3 admin.py db export`(把库里的最新数据写回 `codes.json` / `meta.json` / 账本 …)
|
||||
2. 换回旧版 `server.py` / `admin.py` → 启动。旧版只认 JSON 文件,`ys.db` 放着不碰也没关系。
|
||||
3. 以后要再切回来:先删掉(或挪走)`ys.db`,新版启动时会从 JSON 重新导入。
|
||||
|
||||
测试第 7 节验证过:导出 → 再导入,卡密 / 订单 / 账本 / 呼叫 / 小状态**一模一样**。
|
||||
|
||||
### 5.6 测试
|
||||
|
||||
```
|
||||
python3 tests/数据库测试.py <server.py 所在目录> # 38 条:数据库专项
|
||||
python3 tests/回执复现测试.py <server.py 所在目录> # 27 条:回归 + 漏洞复现(现在跑在数据库上)
|
||||
```
|
||||
|
||||
- 数据全是测试脚本**现编的**(假卡密、假订单、假呼叫,包括一行写坏的 `calls.jsonl`),建在系统临时目录,不碰 `<DATA_DIR>`。
|
||||
- 交付副本里三个 URL 格式串被脱敏弄坏了(`http<WIN-PATH>`),要起服务器的那几节跑之前先换成能格式化的占位;线上原版直接跑。
|
||||
- 2026-10-05 结果:**65 条全过**。另外用假数据把服务器 + 后台面板 + 浏览器整条链路点了一遍(见 `backend-tools/交接说明.md`)。
|
||||
|
||||
### 5.7 文件 / 目录(库以外的)
|
||||
|
||||
| 路径 | 内容 |
|
||||
|---|---|
|
||||
| `<DATA_DIR>/ys.db`(+ `-wal` / `-shm`) | 上面那个库(640 权限) |
|
||||
| `<DATA_DIR>/orders/<单号>/skins/` | 买家皮肤原图(落盘前已过 PNG 结构核验并剥掉元数据块) |
|
||||
| `<DATA_DIR>/orders/<单号>/out/` | 成品(标准压缩 + 无压缩 两个版本/张) |
|
||||
| `<DATA_DIR>/worker_token`、`admin_token` | 两把**互不通用**的令牌(文件权限 600) |
|
||||
| `<DATA_DIR>/calls.jsonl` | 呼叫记录的**副本**(给手机通知读,正本在库里) |
|
||||
| `<DATA_DIR>/upload.log` 等 | 审计留痕 |
|
||||
| `<DATA_DIR>/codes.json`、`orders/*/meta.json` … | **旧数据**:导入之后就不再读写,留着当回退的底 |
|
||||
|
||||
### 卡密生命周期(**激活 ≠ 核销**,这是刻意分开的)
|
||||
|
||||
```
|
||||
active 可用
|
||||
↓ 买家点提交
|
||||
bound **已激活** —— 被这一单占住,不能用于别的单;但还没核销
|
||||
↓ 成品开放下载满 72 小时(或直发单从渲完起算)
|
||||
used **已核销** —— 终态
|
||||
inactive 停用(网页单等付款 / 手动停用)
|
||||
```
|
||||
|
||||
⚠️ 触发核销的只有两处,**删文件之前必须先核销**,否则文件没了码还挂在"已激活"。
|
||||
|
||||
---
|
||||
|
||||
## 六、已经做了的防护(请你对着挑漏)
|
||||
|
||||
| 防护 | 做法 |
|
||||
|---|---|
|
||||
| 卡密暴力破解 | 31 字符取 12 位 ≈ 7.9e17 组合;**单 IP 连错 15 次 → 冷却 15 分钟** |
|
||||
| 灌单 | 单 IP 10 分钟最多开 6 单;提交接口在 nginx 上单独限流 |
|
||||
| 探测 | **「订单不存在」与「口令错」返回同一个 404**(不承认站上有这单) |
|
||||
| 占盘 | 磁盘剩余低于阈值**停止收单** |
|
||||
| 夹带私货 | PNG 结构核验:拒尾部追加 / 未知关键块 / APNG;剥掉文本与 EXIF 类元数据块 |
|
||||
| 取皮肤 | 必须带 worker token |
|
||||
| 管理接口 | **两道门**:token + 来源 IP 必须是家里出口 IP(公网别处扫到也是 403) |
|
||||
| 路径穿越 | slug 白名单 + realpath 前缀校验 |
|
||||
|
||||
---
|
||||
|
||||
## 七、⚠️ 脱敏说明(**重要:这份代码不能直接跑**)
|
||||
|
||||
按我们的出站纪律,**所有指向真实环境的值都换成了占位**:
|
||||
|
||||
| 类别 | 替换成 |
|
||||
|---|---|
|
||||
| 站点域名 / 支付平台域名 | `shop.example.com` / `pay-platform.example` |
|
||||
| 监听端口、面板端口 | 中性数字(`8080`/`8081`/`8082`…)—— **不是真值** |
|
||||
| 数据 / 程序 / 工作目录 | `<DATA_DIR>` / `<APP_DIR>` / `<WORKER_DIR>` |
|
||||
| Windows 盘符路径 | `<WIN-PATH>` / `<ARCHIVE_DIR>` / `<TOOLS_DIR>` |
|
||||
| 家里出口 IP / 局域网 IP | `<HOME-LAN-IP>` / `<LOCAL-IP>` |
|
||||
| 通配绑定地址 | `<ALL-INTERFACES>` |
|
||||
| 密钥 / 令牌**值** | 本来就没有硬编码——全走文件与环境变量,所以代码里是干净的 |
|
||||
|
||||
**保留未换的**:`localhost`(回环,通用值)、渲染分辨率 `1000/1024/2048/4096`(业务常量)、
|
||||
以及**品牌笔名**(属公开署名)。
|
||||
|
||||
**包里没有的**(⚠️ 别去找,是刻意不给):
|
||||
- 任何真实卡密、订单、买家皮肤与成品图
|
||||
- 两把令牌、任何密钥、任何账号凭据
|
||||
- 数据库/运行数据、备份
|
||||
- 私有仓库地址、内部文档
|
||||
|
||||
---
|
||||
|
||||
## 八、⭐ 我们要你交给我们的东西(**这一份的主要目的**)
|
||||
|
||||
请你读完之后**回一份文档**(放在同一个仓库里就行,文件名 `回执-<你的名字>.md`),至少包含三部分:
|
||||
|
||||
> 📋 **格式不用自己起** —— 仓库根目录有一份 `回执模板.md`,照着填就行。
|
||||
|
||||
1. **问题分析** —— 你看到的问题、风险、坏味道。分个轻重(会导致丢钱/丢数据/被人打的,排前面)。
|
||||
请**尽量指到具体函数/行**,并说清**触发条件**(什么输入、什么并发时序会踩到)。
|
||||
2. **改正意见** —— 每条给**你建议怎么改**(不一定要写代码,说清思路和代价也行)。
|
||||
如果有**更简单的整体方案**(比如"这段根本该换个做法"),也请直说,别客气。
|
||||
3. **你改了什么** —— 如果你直接动手改了,请逐条列:
|
||||
```
|
||||
文件 / 函数:
|
||||
为什么改:
|
||||
改成什么(一句话说清):
|
||||
有没有动到接口路径、请求/响应字段、数据格式(**这三样动了我们必须知道**):
|
||||
你怎么验证的(跑过什么、看到什么):
|
||||
```
|
||||
⚠️ **改了接口/数据格式一定要单独标出来** —— 渲染机那边是另一台机器上的另一份代码,
|
||||
两边不同步会**静默出不来图**。
|
||||
|
||||
**另外请你顺手回答两个具体问题**(我们自己拿不准):
|
||||
- 爱发电那条线**"不验签、改成拿开放接口反查"**,你认为够不够硬?有没有更好的做法?
|
||||
- 订单状态机(`unpaid → paid → waiting → working → done/failed`)在**部分失败**时
|
||||
(比如 3 张图渲出 2 张)你建议怎么收口?
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 九、我们的思路与方法(**请你连这套做法一起评**)
|
||||
|
||||
代码能看出的是一部分;**为什么这么做、踩过什么坑**,在代码里看不到。这一节补上,
|
||||
**并且希望你连"做法"本身一起挑** —— 如果我们整套思路就是错的,那比某个函数写错更要紧。
|
||||
|
||||
### 9.1 我们给自己定的几条硬规矩
|
||||
|
||||
| 规矩 | 为什么 |
|
||||
|---|---|
|
||||
| **无人值守优先**:机器的活不该让人 24 小时待命 | 这行的买家半夜下单是常态,靠人盯必然漏 |
|
||||
| **正常用户一步都不多加**:每加一道防探测,先问"正常买家会不会被误伤" | 防的是坏人,误伤的是给你钱的人。两者冲突时**先保买家** |
|
||||
| **收钱的数字一律以服务器订单为准**,本地状态只能当兜底 | 踩过:恢复订单时本地状态是空的,按本地算出错的金额去拼付款链接 → 买家少付 → 闸门拦死。**同一行显示两个来源的数,必然自相矛盾** |
|
||||
| **状态话术不许骗人** | 踩过:没付款的单子被兜底文案说成"正在排队"。宁可说"没取到订单信息",也不给假安心 |
|
||||
| **出错要说清是什么、下一步怎么办**,不引导用户猜 | 报错是给人看的,不是给日志看的 |
|
||||
| **同一件事的逻辑只写一处** | "CLI 一套、后台面板一套"必然漂移 —— 出现过面板和命令行生成出两种卡密 |
|
||||
|
||||
### 9.2 我们干活的方法(改这块代码时照着来)
|
||||
|
||||
1. **改一处 → 顺着所有调用点核一遍**。可见性逻辑被好几个入口调用,改了一处、
|
||||
别的入口还传旧参数 → 出现"导航正常、首页却说没有可见内容"这种**看着像站坏了**的现象。
|
||||
2. **同一个东西存在两处时,先问"读取方是按哪个字段找的"**。改写入方不改读取方 =
|
||||
写进去了、读的还是旧的(踩过:换了皮肤文件、但路径字段没跟着改,买家看到"重渲了还是旧图")。
|
||||
3. **前端必须真的在浏览器里点一遍**。有一批 bug 在 API 层**根本测不出来**
|
||||
(页面上某个渲染函数调了不存在的名字 → 每次进第 2 步就抛异常 → 页面看着"就是没反应")。
|
||||
4. **部署完要核对"跑的是不是新代码"**,不是"部署脚本说成功了"。
|
||||
踩过:脚本全程报成功、功能静默缺失 —— 旧进程还活着,计划任务的"运行"不会替换它。
|
||||
5. **自测的每一个负例各用一份新数据**。复用同一份的话,第一条成功就把它消耗了,
|
||||
后面几条测的其实是"已经用过了"—— **全绿,但什么都没测到**。
|
||||
6. **测完必须清场**。测试产生的记录不许留在管理员看得见的列表里。
|
||||
|
||||
### 9.3 我们付过学费的坑(这些是"不要重复踩"清单)
|
||||
|
||||
- **静默失败最贵**:不报错、不崩,就是没效果 —— 比抛异常难查十倍。
|
||||
所以我们宁可让它**响亮地失败**(比如离线就不显示预计时间、宁可说"没取到")。
|
||||
- **显示层会骗人**:订单本身算对了,但界面从另一个来源取数 → 用户看到的是错的。
|
||||
**凡是"从 A 推导出 B"的函数,在别处读 B 之前都要先调一次它**。
|
||||
- **文件重复投递**:渲染机与服务器之间"一张图一次"回传,是因为一次全传会撞体积上限。
|
||||
- **重试要有上限也能收敛**:部分失败必须显式收尾,否则订单会永远停在"渲染中"、被反复重渲。
|
||||
|
||||
### 9.4 我们最想要你评的三件"做法"
|
||||
|
||||
1. **"不验签、改成拿开放接口反查"**这个取舍,你认同吗?(我们手头没有对方的公钥,与其猜算法不如反查)
|
||||
2. **订单状态机在部分失败时怎么收口**(3 张渲出 2 张)—— 我们现在靠"显式收尾",你觉得够不够。
|
||||
3. **这套"单文件纯标准库"的写法**:好处是零依赖零安装、小机器跑得动;
|
||||
代价是路由/校验/序列化全得自己写。**换你,你会不会上框架?** 请直说。
|
||||
|
||||
---
|
||||
|
||||
## 十、边界
|
||||
|
||||
- 这份是**私有交付**,**请勿外传 / 勿镜像 / 勿公开**(含截图、片段)。
|
||||
- 里面是**占位值**,请不要替换成任何真实地址再提交回来。
|
||||
- 有看不懂的先问,别猜着改 —— 猜错了我们这边会静默坏掉。
|
||||
- 你可以自由重构,但**动了接口/数据格式要按第 8 节单独标出来**。
|
||||
@@ -0,0 +1,384 @@
|
||||
# 回执 · Claude(受 ywsabc2 委托)· 2026-10-05
|
||||
|
||||
> 范围:`backend-site/`(server.py / admin.py / pngcheck.py)+ `deploy/nginx-片段.md`,以及它和前端 `order/index.html` 的对接。
|
||||
> 渲染机 / 本机工具那边单独一份:`backend-tools/回执-Claude.md`。
|
||||
> 行号一律指**交付时的原版**(提交 `c6034e9`)。
|
||||
> 我改过的地方都在 `server.py` / `admin.py` 里标了「2026-10-05(外部复查)」,搜这几个字就能全部找到。
|
||||
|
||||
---
|
||||
|
||||
## 0. 一句话总结
|
||||
|
||||
整体思路是对的(无人值守、渲染机只出站、收钱以服务器为准、话术不骗人),工程习惯也好(决定留痕、踩坑写进注释)。
|
||||
**最该先修的是「钱」和「数据」上的并发 / 信任问题**:一码两单、前端报的张数被直接信、支付回调重放白送码、
|
||||
CLI 和服务器互相覆盖 `codes.json`、`sweep` 会删掉还在排队的已付款单。
|
||||
这些我**都已经改了,并且写了复现测试**:同一套 27 条用例,原版失败 13 条、改后全部通过(见第 3 节末尾)。
|
||||
**接口路径一条没动**;接口字段只**新增**了一个(`/claim` 返回里的 `terms_v`),渲染机那边不用改代码。
|
||||
|
||||
---
|
||||
|
||||
## 1. 问题分析
|
||||
|
||||
> 🔴 = 会丢钱 / 丢数据 / 能被人利用;🟡 = 静默失败、显示骗人、能把机器拖死;🟢 = 小问题 / 坏味道。
|
||||
> 「已修」= 这次直接改了;「建议」= 只给意见没动(多半是要你们拍板,或者动的是部署层)。
|
||||
|
||||
| # | 严重度 | 位置(原版) | 问题是什么 | 触发条件 | 影响 | 状态 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| 1 | 🔴 | server.py `submit` 1626 查码 → 1741 绑码 | 「查码」和「绑码」在**两次加锁**里,中间隔着 base64 解码、PNG 核验、落盘 | 同一张码**同时**提交两次(连点、两个标签页、脚本) | **一码两单**。实测:并发 6 次成了 2 单 | 已修 |
|
||||
| 2 | 🔴 | server.py `submit` 1635-1637 | 卡密规则用的张数 / 模板并集是**前端报的** `nTotal` / `tplUnion`,真提交的 `templates` 不受它约束 | 「固定 1 张」的码 + `templates` 塞 7 个 + `nTotal=1`;锁模板的码 + `tplUnion=锁定那组` + `templates=别的` | **花 1 张的钱出 7 张**;锁模板(试玩券)形同虚设。实测两条都能过 | 已修 |
|
||||
| 3 | 🔴 | server.py `payplatform_hook` 2014 | 幂等只认「发过码」。「对上网页单并激活」那条路记的是 `code=None` | 同一笔单再推一次:爱发电自己会重试;这个地址又是公开的,谁都能把报文原样再 POST 一次 | 第二次激活失败(单子已在排队)→ 掉进「按买码处理」→ **白送一张码,还写在返回体里**。实测:重放一次多出 1 张码 | 已修 |
|
||||
| 4 | 🔴 | server.py `LOCK = threading.Lock()` 151;admin.py 各命令 | 锁只管**本进程**的线程。admin.py 是另一个进程,同样读-改-写 `codes.json` / `meta.json` | CLI 发码 / 改码 / retry 的同时,网页上有人下单 | 互相覆盖。**实测:CLI 发 200 张,最后文件里只剩 15 张;还有已下单的码被改回「可用」** | 已修 |
|
||||
| 5 | 🔴 | admin.py `cmd_sweep` 279 + server.py `expire_at` | 没开放下载的单,到期按「创建 + 72h」算,**不看状态** | 渲染机关了三天(出差、断网、坏了),或者买家报了付款、金钻还没确认 | 排队中 / 待确认的单被**整目录删掉**,码还被记成「已核销」:钱收了、皮肤没了、图也没出。实测:5 天前的排队单被删 | 已修(只跳过 waiting/working/paid,见第 2 节 #5 的取舍) |
|
||||
| 6 | 🔴 | server.py `new_oid` 713 / `new_owner_token` / `gen_codes` 742 / 批次号 / 反馈号 | 卡密、订单号、**取件码**都用 `random`(梅森旋转,不是密码学随机) | 攻击者攒够输出(反复领福利券、反复下网页单都会拿到码和取件码)就能还原内部状态 | 能**预测之后要生成的卡密和别人的取件码**。7.9e17 的码空间只防「盲猜」,防不住「预测」 | 已修(换 `secrets`,格式不变) |
|
||||
| 7 | 🔴 | server.py `redo` 2340 | 重渲换皮肤:只 base64 解一下、看大小就落盘,**没走 PNG 结构核验** | 任何拿着自己取件码的人 | 「夹带私货」防护整个绕过,而且这个文件会直接发到家里那台电脑上给 Blender 读。实测:尾部夹带 18 字节照样落盘 | 已修 |
|
||||
| 8 | 🟡 | server.py `feedback` 2413 | 不限频、不看磁盘;每条能存一张 4MB 的「图」(不校验是不是图),还往 calls.jsonl 写一条「呼叫」 | 写个循环 | 把盘写满(盘满后所有 `jsave` 都会失败);金钻手机通知被刷爆 | 已修 |
|
||||
| 9 | 🟡 | server.py `download` 2559 | 下载原图是 `f.read()` 整张读进内存 | 4096 的无压缩 16bit 一张几十 MB,几个人同时下 | 服务 `MemoryMax=256M`,会被 OOM **整个杀掉**(你们说这是最值得报的一类) | 已修(边读边发,和 zip 一样) |
|
||||
| 10 | 🟡 | server.py `class H` 里的 `def finish` 2694 | 和 socketserver 的 `StreamRequestHandler.finish()` **重名**。框架在**每个请求**处理完都调一次 `self.finish()` | 任何请求 | 每个请求结束后都把「回传成品」再跑一遍:多写一个 403;带渲染机令牌的请求还会再去读一次请求体(读到连接关闭才返回)。日志里大量「Exception occurred during processing of request … in finish」就是它(测试里原版一轮 32 条,改后 0 条) | 已修(方法改名,路径不变) |
|
||||
| 11 | 🟡 | server.py `finish` 2754 / 2764;`order_detail` 1802-1808 | 渲染机收单(`close`)**不带 total**,服务器退回按「模板数」算;渲染机的 total 是按**文件数**(每模板 2 张)报的。另外部分失败照样标「已完成」,原因只写进 note,而 done 状态的页面文案会把 note 盖掉 | 有模板渲失败、或回传失败(见渲染机回执里的 16MB 上限问题) | **静默少交货**:买家看到「渲染完成」,金钻也收不到任何提醒 | 已修(见第 3 节) |
|
||||
| 12 | 🟡 | server.py `activate` 2229-2282 | 同 #1:查码和绑码不在同一把锁里;而且输错码**不计数** | 同一张码同时激活两张网页单;拿这个接口试码不触发冷却 | 一码两单;试码没有冷却 | 已修 |
|
||||
| 13 | 🟡 | server.py `edit_code` 1253(锁外读、锁里写)、`gift_batch_add` 464-467(锁外读写) | 读-改-写不在同一把锁里 | 面板改码 / 补福利券的同时有人下单或领券 | 存回去的旧快照把别人刚改的码冲掉(码被改回「可用」= 一码两用) | 已修 |
|
||||
| 14 | 🟡 | server.py `jsave` 655 | 临时文件名固定是 `path + ".tmp"`;写完不 fsync | 两个线程 / 进程同时写同一个文件;或者写完马上断电 | 互相截断出半截 JSON;断电后可能留一个 0 字节的 `codes.json`(`jload` 读坏了会**静默**当成空字典 → 整个码池「消失」) | 已修 |
|
||||
| 15 | 🟡 | deploy/nginx-片段.md | `/order/api/submit` 的 `client_max_body_size 4m`,但后端和页面都说皮肤最大 10MB(base64 后约 13.4MB);`add-skin` / `redo` / `feedback` 走通用 location,**没配大小 = nginx 默认 1MB** | 买家传一张 3MB 以上的皮肤;追补 / 重渲换一张 700KB 以上的皮肤;反馈带一张截图 | nginx 直接回 413 的 HTML,前端 `r.json()` 解析失败 → 买家只看到一句笼统的失败,不知道是图太大 | **建议**(部署层,见第 2 节;如果你们线上的值和片段一样的话) |
|
||||
| 16 | 🟡 | server.py `ip_of` + `admin_ip_ok` 708 | 管理接口的 IP 门靠 `X-Real-IP`;取不到就用连接来源 —— 经过 nginx 时连接来源**永远是回环**,而回环在白名单里。原版白名单里还有 `"?"` | 哪天某条 location 漏配 `proxy_set_header X-Real-IP` | 来源变成回环 → IP 这道门对公网失效,只剩令牌一道 | `"?"` 已去掉;其余**建议**(第 2 节) |
|
||||
| 17 | 🟡 | server.py `order_detail` 1793 | 文案里写了 Markdown 的 `**已经付过款,不用再付款**`,页面当纯文本显示 | 每一张卡密单 | 买家看到两对星号(我在浏览器里端到端点了一遍看到的) | 已修 |
|
||||
| 18 | 🟡 | `order/index.html` 条款全文 vs server.py `TERMS_VERSION` | 页面上条款全文标的是「版本 2026-10-01.1」,提交时记进订单的是 `2026-10-04.1` | 每一单 | 「订单里记版本号,日后争议时证明买家当时同意的是哪一版」—— 现在记的版本和买家看到的那份**对不上** | **没动**:不知道是只改了版本号、还是条款内容也改了,要你们定 |
|
||||
| 19 | 🟡 | server.py `claim` 2606 + ys_worker.py 26 / 438 | 派单不带订单的条款版本,渲染机留档时只能用自己写死的 `2026-10-01.1` | 每一单 | 永久留档里的「条款版本」全是错的 | 已修(`/claim` 新增 `terms_v`,渲染机本来就先读它,不用改) |
|
||||
| 20 | 🟡 | server.py `download_zip` 2879 | PNG 再 `ZIP_DEFLATED` 一遍几乎不变小、白烧 CPU;**不限并发**,每个包最大 600MB 临时文件 | 同一个取件码连点 / 并发几次 | 盘和 CPU 一起被占满 | 已修(成品 STORED + 同时只打一个包) |
|
||||
| 21 | 🟢 | server.py `my_coupons` 2462 / `coupon_status` | 一次查 60 张券 = 读 60 遍 `codes.json`;不限频 | 刷这个接口 | CPU;另外它和 `/api/code/<码>` 都能当「码是否存在」的查询口子,不计输错 | 读文件次数已修;查询口子在换成 `secrets` 之后风险可以忽略 |
|
||||
| 22 | 🟢 | server.py `activate_payplatform` 2176 | 按「订单号**后缀**匹配」(≥10 位)+ 输错不计数;账本读写不在锁里 | 猜别人订单号的后 10 位 | 理论上能把别人付的款激活到自己单上(概率很低);账本和回调同时写会丢记录 | 计数 + 加锁已修;后缀匹配**建议**改成全号匹配(要你们看买家实际怎么复制) |
|
||||
| 23 | 🟢 | server.py `ThreadingHTTPServer` | 线程数不设上限 | 慢请求堆积(ffmpeg 预览、打包、大下载) | 小机器上线程 + 内存一起涨 | **建议**:重活加信号量(zip 已加),或 nginx `limit_conn` |
|
||||
| 24 | 🟢 | server.py `queue_pos` 1169 / `heartbeat` 1230 / `claim` | 每次都把 `orders/` 下所有 `meta.json` 读一遍 | 订单目录攒多了(sweep 不常跑的话) | 现在几十单无所谓;几千单就慢 | **建议**:现在不用动 |
|
||||
| 25 | 🟢 | 脱敏误伤:server.py 53、2095、2150 | 脱敏把带 `%s` 的 URL 格式串整个换成了 `"http<WIN-PATH>"`,格式化时会 `TypeError` | 只影响你们给出来的这份 | 不是线上问题,但说明**脱敏规则会吃掉 URL 里的 `%s`**,下次出站可以留意 | 没动(占位值按要求保持原样) |
|
||||
| 26 | 🟢 | 前端没在用的接口 | 交给我的这份 `order/index.html` 里**没有调用** `/api/activate`、`/api/activate-payplatform`、`/api/set-templates` | — | 要么是死接口(多一份攻击面),要么是前端副本比线上旧 | **问你们**:线上页面还调不调这三个? |
|
||||
| 27 | 🟢 | 其它小问题 | `order_detail` 返回体里 `"amount"` 写了两遍;`IP_FAILS` 等计数字典对「只来一次的 IP」永不清理;`call()` 每次读整个 calls.jsonl;pngcheck 不检查 IHDR 长度 / 取值、IDAT 里 zlib 流结束后的多余字节 | — | 都很轻 | 没动 |
|
||||
|
||||
**我怀疑但没验证的**(没有真实环境):
|
||||
|
||||
- **ffmpeg 生成 4096 预览的内存**:解一张 4096×4096 的 8bit RGBA 要约 64MB,加上缩放缓冲,和 Python 进程本身共用 256M 的 cgroup。正常应该过得去,但几单同时完成时可能顶到。建议实测一次 4096 单的峰值内存。
|
||||
- **2048 / 4096 的无压缩 16bit 回传会超过 16MB 上限**:详见渲染机那份回执第 1 条。如果成立,这些单会静默少一张无压缩版。#11 的修改至少能让它**不再静默**。
|
||||
|
||||
---
|
||||
|
||||
## 2. 改正意见(只列我没改、或者改了但你们要知道取舍的)
|
||||
|
||||
| 对应 # | 建议改法 | 代价 / 风险 | 优先级 |
|
||||
|---|---|---|---|
|
||||
| 5 | 我只让 sweep **跳过** `waiting / working / paid`(还在流水线上的)。`unpaid`(一直没付款)和 `done` 还没收货的,照旧 72h 后清。**另外建议**:`done` 但没确认收货的单,到期从**完成时间**算,而不是创建时间 —— 不然渲染机晚上线两天,买家只剩一天能收货 | 一行,改 `expire_at`;这是业务口径,你们定 | 中 |
|
||||
| 15 | nginx:`/order/api/submit` 的 `client_max_body_size` 改成 **15m**(和后端 `MAX_BODY` 一致);给 `add-skin`、`redo` 单独配 15m,`feedback` 配 6m。再给它们加 `error_page 413 = @json413;` 回一段 `{"ok":false,"error":"图片太大"}`,前端不用改就能显示人话 | 改配置 + reload,不停机 | **高**(直接影响买家能不能下单) |
|
||||
| 16 | 最稳:管理接口单独监听一个端口(或者单独一条 nginx location 带 `allow <家里 IP>; deny all;`);后端看到「来源是回环但没带 X-Real-IP」就当成**未知**而不是**本机**。至少在 nginx 每条 location 都确认带了 `proxy_set_header X-Real-IP $remote_addr;`(片段里 `/finish` 那条被省略了,看不出有没有) | 小 | 中 |
|
||||
| 18 | 条款版本号和全文**放一处**(比如后端 `/api/payinfo` 顺带返回 `terms_v` + 全文,页面照着显示),改一处两边一起变 | 改前端要走前端那边的流程 | 中 |
|
||||
| 22 | 爱发电订单号改成**全号匹配**(或至少 ≥ 20 位);买家复制时多出的空格 / 换行前端已经洗掉了 | 一行 | 低 |
|
||||
| 23 | `submit` / `add-skin` 收的请求体一个约 15MB,解码 + 清洗 + 原串一共约 4~5 份拷贝 → 单个请求峰值 ~50MB;**5 个并发就顶到 256M**。建议 nginx `limit_conn`(每 IP 2 个)+ 应用层给「收图」接口加一个 `BoundedSemaphore(2)` | 小 | 中 |
|
||||
| 新 | **取件码在 URL 的 query 里**(`?t=`),所以它会进 nginx access log、浏览器历史,订单页上点外链时还会带进 `Referer`。建议:订单页加 `Referrer-Policy: no-referrer`;nginx 的 access log 用不带 `$args` 的 log_format(或把 `t=` map 掉);`payplatform-hook.log` 现在是**整包 headers 落盘**,注意别把平台带过来的鉴权头长期留着 | 改配置 | 中 |
|
||||
| 新 | **下载不留痕**:买家说「我的图被别人下了」,现在没法自证。建议 `/dl` `/zip` 各记一行审计(时间、单号、第几张、IP、UA,**不记取件码**) | 小 | 中 |
|
||||
| 中期 | `codes.json` + 各种 jsonl / 账本 → **SQLite**(标准库自带 `sqlite3`,零依赖)。这次修的竞态(#1 #4 #12 #13 #14 + 账本)本质都是「文件当数据库用」:拿事务一把就全解决了,不用到处想锁。交接说明里写了「数据全在本地文件 + 一个 SQLite」,但代码里没看到 SQLite —— 是不是另有东西没给? | 一次迁移脚本 + 改数据层;接口不用动 | 中(不急,锁已经补上了) |
|
||||
|
||||
---
|
||||
|
||||
## 3. 你改了什么
|
||||
|
||||
> 所有改动都在 `backend-site/server.py`、`backend-site/admin.py`(+ 渲染机那份回执里的 `backend-tools/ys_local.py`)。
|
||||
> **接口路径:一条都没动。** 下面每条都单独标了「接口路径 / 请求响应字段 / 数据格式」三样。
|
||||
|
||||
### 改动 1 · 校验 + 绑码同锁(一码两单)
|
||||
|
||||
```
|
||||
文件 / 函数:server.py 新增 redeem_bind() / unbind_codes() / _redeem_check();submit()、activate() 改用 redeem_bind()
|
||||
为什么改:问题 #1、#12
|
||||
改成什么:查码和绑码放进同一把锁;绑不上(被别的提交抢先了)就整单不收、删掉刚建的目录;
|
||||
订单写盘失败就把码放回 active。redeem() 保留,只查不占码,判断逻辑和 redeem_bind 共用一份。
|
||||
⚠️ 有没有动:接口路径 [否] 请求响应字段 [否] 数据格式 [否]
|
||||
(并发冲突时多一种报错文案,和原来「这张卡密已经用来下过单了」是同一句)
|
||||
怎么验证的:同一张码并发提交 6 次 → 原版成 2 单,改后成 1 单;正常卡密单、网页单 + 卡密激活回归通过
|
||||
有没有引入新的依赖:没有
|
||||
```
|
||||
|
||||
### 改动 2 · 卡密规则不再只信前端报的张数
|
||||
|
||||
```
|
||||
文件 / 函数:server.py submit()
|
||||
为什么改:问题 #2
|
||||
改成什么:张数取 max(前端报的 nTotal, 这次真提交的模板数);模板取两者并集;不认识的模板 key 提交时直接拒
|
||||
⚠️ 有没有动:接口路径 [否] 请求响应字段 [否] 数据格式 [否]
|
||||
正常页面报的 nTotal 本来就 ≥ 第一张皮肤的模板数,对正常买家没有变化
|
||||
怎么验证的:「固定 1 张」+7 模板+nTotal=1 → 拒;锁模板 + 伪造 tplUnion → 拒;
|
||||
多皮肤单(第 1 张 2 个模板、整单报 3 张)照常能交
|
||||
有没有引入新的依赖:没有
|
||||
```
|
||||
|
||||
### 改动 3 · 支付回调幂等 + 串行
|
||||
|
||||
```
|
||||
文件 / 函数:server.py payplatform_hook() → 拆成外层 + _payplatform_hook_locked();activate_payplatform() 同理;新增 HOOK_LOCK
|
||||
为什么改:问题 #3、#22(账本读写不在锁里)
|
||||
改成什么:同一个 out_trade_no「发过码」或「激活过单」都算处理过,再推一律原样回上次的 content;
|
||||
回调和「用爱发电订单号激活」共用一把锁,账本不会被同时写坏;后者输错计入冷却
|
||||
⚠️ 有没有动:接口路径 [否] 请求响应字段 [否] 数据格式 [否](账本结构不变)
|
||||
怎么验证的:用假的反查结果模拟一笔 ¥6 付款:首次对上网页单并激活 ✔;原样重放 → 码数不变、返回同一段内容 ✔
|
||||
(原版:重放一次多出 1 张码,返回体里写着「这是你的卡密」)
|
||||
有没有引入新的依赖:没有
|
||||
```
|
||||
|
||||
### 改动 4 · 跨进程锁 + 原子写加固
|
||||
|
||||
```
|
||||
文件 / 函数:server.py LOCK 换成 _DataLock(线程锁 + <DATA_DIR>/.lock 上的 flock);jsave();admin.py cmd_retry 加锁
|
||||
为什么改:问题 #4、#14
|
||||
改成什么:用法不变(还是 with LOCK:),admin.py import server 后自动用同一把文件锁;
|
||||
jsave 的临时文件名每次唯一 + 写完 fsync + 权限沿用原文件;拿不到文件锁就退回只用线程锁并打一行日志
|
||||
⚠️ 有没有动:接口路径 [否] 请求响应字段 [否] 数据格式 [否]
|
||||
⚠️ 但:<DATA_DIR> 下会多一个空文件 .lock;临时文件名从 xxx.tmp 变成 xxx.<随机>.tmp
|
||||
(如果你们有脚本按 *.tmp 清理或备份,留意一下)
|
||||
怎么验证的:另起一个进程连续发 200 张码,同时 HTTP 下 30 单 → 原版文件里只剩 15 张、还有 1 张已下单的码被改回可用;
|
||||
改后 200 张一张不少、30 张码全部是「已激活」
|
||||
有没有引入新的依赖:没有(fcntl 是标准库;Windows 上不会 import 到这里)
|
||||
```
|
||||
|
||||
### 改动 5 · sweep 不删流水线上的单
|
||||
|
||||
```
|
||||
文件 / 函数:admin.py cmd_sweep()
|
||||
为什么改:问题 #5
|
||||
改成什么:state 是 waiting / working / paid 的单跳过,不删、不核销;其它状态口径不变
|
||||
⚠️ 有没有动:接口路径 [否] 请求响应字段 [否] 数据格式 [否]
|
||||
怎么验证的:造一张 5 天前创建、还在排队的单,跑 admin.py sweep → 原版删掉并核销了码,改后保留
|
||||
有没有引入新的依赖:没有
|
||||
```
|
||||
|
||||
### 改动 6 · 卡密 / 订单号 / 取件码用 secrets
|
||||
|
||||
```
|
||||
文件 / 函数:server.py new_oid() / new_owner_token() / gen_codes() / gift_batch_new() / gift_claim() / feedback()
|
||||
为什么改:问题 #6
|
||||
改成什么:random.choice → secrets.choice,字符表、长度、格式一个没变
|
||||
⚠️ 有没有动:接口路径 [否] 请求响应字段 [否] 数据格式 [否]
|
||||
怎么验证的:回归里所有生成的码都过 CODE_RE;订单号 / 取件码格式不变
|
||||
有没有引入新的依赖:没有
|
||||
```
|
||||
|
||||
### 改动 7 · 重渲换皮肤走 PNG 核验
|
||||
|
||||
```
|
||||
文件 / 函数:server.py redo()
|
||||
为什么改:问题 #7
|
||||
改成什么:换皮肤改用 _read_skin()(和下单、追补皮肤同一个:尺寸 + 结构核验 + 剥元数据),落盘的是清洗后的字节
|
||||
⚠️ 有没有动:接口路径 [否] 请求响应字段 [否] 数据格式 [否](不合格时多一种报错文案)
|
||||
怎么验证的:尾部夹带 18 字节 → 拒、不落盘;正常皮肤换图照常可以
|
||||
有没有引入新的依赖:没有
|
||||
```
|
||||
|
||||
### 改动 8 · 反馈限频 + 磁盘闸 + 只收图片
|
||||
|
||||
```
|
||||
文件 / 函数:server.py feedback();新增 feedback_allowed() / note_feedback() / _img_ext()
|
||||
为什么改:问题 #8
|
||||
改成什么:每 IP 10 分钟 5 条(超了回 429);磁盘不够回 503;「图片」只认 png/jpg/webp/gif 文件头
|
||||
⚠️ 有没有动:接口路径 [否] 请求响应字段 [否]
|
||||
数据格式 [是,很小]:反馈图片的文件扩展名按真实格式存(原来一律 .png),feedback/<id>.json 的 image 字段跟着变
|
||||
怎么验证的:同 IP 连发 7 条 → 第 6、7 条 429;伪装成 PNG 的 exe 头不落盘
|
||||
有没有引入新的依赖:没有
|
||||
```
|
||||
|
||||
### 改动 9 · 下载 / 取皮肤边读边发
|
||||
|
||||
```
|
||||
文件 / 函数:server.py 新增 H._send_file();download()、skin() 改用它
|
||||
为什么改:问题 #9
|
||||
改成什么:64KB 一块往外写,不整张进内存;响应头(Content-Type / Content-Length / no-store / Content-Disposition)完全不变
|
||||
⚠️ 有没有动:接口路径 [否] 请求响应字段 [否] 数据格式 [否]
|
||||
怎么验证的:下载原图字节一致、带附件头;渲染机取皮肤内容一致、Content-Length 一致;端到端下单后订单页正常
|
||||
有没有引入新的依赖:没有
|
||||
```
|
||||
|
||||
### 改动 10 · finish 方法改名(框架重名)
|
||||
|
||||
```
|
||||
文件 / 函数:server.py H.finish → H.finish_upload(路由 /api/finish 指过去)
|
||||
为什么改:问题 #10
|
||||
改成什么:只是改名,逻辑见改动 11
|
||||
⚠️ 有没有动:接口路径 [否](还是 /api/finish) 请求响应字段 [否] 数据格式 [否]
|
||||
怎么验证的:同一套测试,原版一轮 32 条「Exception occurred during processing of request」,改后 0 条
|
||||
有没有引入新的依赖:没有
|
||||
```
|
||||
|
||||
### 改动 11 · 部分失败要响亮
|
||||
|
||||
```
|
||||
文件 / 函数:server.py finish_upload()、claim()、order_detail()
|
||||
为什么改:问题 #11(以及回执模板 Q2)
|
||||
改成什么:记住渲染机报过的 total(meta.plan_total),收单时按它判断收没收满;
|
||||
没收满 → meta.partial = {got, want, why, at} + 往 calls.jsonl 写一条(走「呼叫金钻」同一套通知)+ 页面文案直说「有 N 个文件没渲出来」;
|
||||
状态仍是 done(已经出好的部分照常能看、能收货);领单时清掉上一轮的 plan_total / partial
|
||||
⚠️ 有没有动:接口路径 [否] 请求响应字段 [否](note 文案多一句)
|
||||
数据格式 [是,只增]:订单 meta.json 新增 plan_total、partial 两个字段;calls.jsonl 多一种 kind="部分失败"
|
||||
—— 如果你们的通知脚本按 kind 过滤,记得把它加进去
|
||||
怎么验证的:计划 4 个文件只交回 1 个 → 页面「有 3 个文件没渲出来,已经自动通知金钻补」,calls.jsonl 里有这一单
|
||||
有没有引入新的依赖:没有
|
||||
```
|
||||
|
||||
### 改动 12 · 派单带上条款版本
|
||||
|
||||
```
|
||||
文件 / 函数:server.py claim()
|
||||
为什么改:问题 #19
|
||||
改成什么:/claim 返回的 order 里多一个 terms_v(订单真实同意的版本)
|
||||
⚠️ 有没有动:接口路径 [否] 请求响应字段 [是,只增]:/api/claim 响应的 order 新增 terms_v 数据格式 [否]
|
||||
渲染机 ys_worker.py 本来就是 order_meta.get("terms_v") or TERMS_VERSION,所以**渲染机不用改**:
|
||||
老渲染机连新服务器 → 留档写对;新服务器配老渲染机也完全兼容
|
||||
怎么验证的:领单返回里 terms_v = 2026-10-04.1
|
||||
有没有引入新的依赖:没有
|
||||
```
|
||||
|
||||
### 改动 13 · 其它几处小改
|
||||
|
||||
```
|
||||
文件 / 函数:server.py edit_code()(拆出 _edit_code_locked,整段进锁)、gift_batch_new/add/off(写文件进锁)、
|
||||
my_coupons()/coupon_status()(一次只读一遍 codes.json)、admin_ip_ok()(去掉 "?")、
|
||||
download_zip()(成品 STORED、同时只打一个包,忙时回 503「稍等一分钟再点」)、
|
||||
order_detail()(去掉文案里的 ** 星号)
|
||||
⚠️ 有没有动:接口路径 [否] 请求响应字段 [否](打包忙时多一种 503) 数据格式 [否](zip 还是标准 zip,只是成品不再二次压缩)
|
||||
怎么验证的:打包下载 zip 内容完整(小票 + 两张图,字节一致);其余随回归一起跑
|
||||
有没有引入新的依赖:没有
|
||||
```
|
||||
|
||||
### 验证方式汇总
|
||||
|
||||
- 测试脚本放在 `backend-site/tests/回执复现测试.py`:在临时目录起一份 server、从 HTTP 层打接口,**全部用脚本现画的假皮肤**,每条用例各用一份新数据。
|
||||
用法:`python3 tests/回执复现测试.py <server.py 所在目录>`。对原版跑能看到哪些洞真实存在。
|
||||
(你们给的这份因为脱敏弄坏了三个 URL 格式串跑不起来,我是在一份只替换了那三处的副本上跑的;线上原版可以直接跑。)
|
||||
- 结果:**原版 27 条失败 13 条,改后 27 条全部通过**。
|
||||
- 端到端:在测试机上用无头浏览器打开真实的 `order/index.html`,接到改过的后端,按买家的路径点了一遍:
|
||||
卡密下单 → 填码(`/code` ✔ 识别有效)→ 勾条款、传皮肤(本地质检 ✔)→ 选模板 → 提交(`/submit` ✔)→ 结果页显示订单号,
|
||||
`/status`、`/order`、`/tick` 都是 200,页面 0 个 JS 报错。上面 #17 的星号就是这时候看到的。
|
||||
|
||||
---
|
||||
|
||||
## 4. 我们这边拿不准的,请你表态
|
||||
|
||||
**Q1. 支付回调「不验签、改成拿开放接口反查」这个取舍,你认同吗?**
|
||||
认同。反查比「拿不到公钥去猜签名」硬得多 —— 前提是**反查结果是唯一可信来源**,推送报文只当一条「单号 X 有动静,去查一下」的通知。现在有两处还在信报文:
|
||||
- 幂等只认「发过码」(#3,已修);
|
||||
- `custom_order_id` 在反查结果里没有时,会退回用**推送报文里的**(2049 行)。幂等修好之后这个口子拿不到好处了(同一笔钱只能处理一次),但更干净的做法是金额、状态、订单号、留言**全部只从反查结果取**。
|
||||
|
||||
另外两点:反查只翻前 3 页,单子多了会查不到(会落进 need_human,不丢钱,但要人工);据我所知爱发电的 `query-order` 支持按 `out_trade_no` 精确查,请你们核对一下文档,能精确查就别翻页。
|
||||
如果哪天拿到平台公钥:**验签 + 反查两道都做**最好;拿不到的话,反查加上「每个单号只处理一次」已经够用。
|
||||
|
||||
**Q2. 订单状态机在「部分失败」时怎么收口?**
|
||||
「渲染机显式收尾」这个方向是对的:没有它就只能靠超时,会无限重渲。但原版收得**太安静**,而且收单时张数口径不一致(#11)。我改成:服务器记住计划张数,收单缺张就记 `partial` + 通知金钻 + 页面说实话,已经出好的部分照常能收货、能下载。
|
||||
再往前一步(没做,要你们定):缺的那几张**自动补渲一次**(上限 1 次),还不行再转人工;页面上把缺的是哪几张列出来。
|
||||
|
||||
**Q3. 「改完不生效」除了「先杀旧进程再起新的」,有没有更稳的机制?**
|
||||
有:**让进程自己报版本**。部署时把代码的 git 提交号或文件 sha256 写进一个常量;渲染机心跳里带上它,服务器存进 heartbeat.json、在 `/status` 和面板上显示;部署脚本**比对「期望版本 == 心跳报上来的版本」才算成功**。这样旧进程还活着会立刻看出来,不用猜。服务器那边同理:systemd 的 `ExecStartPost` 或部署脚本打一下 `/api/status` 看版本号。
|
||||
Windows 那边:用 NSSM / WinSW 把渲染机装成**服务**,「重启」的语义是确定的(停、等退出、再起),比计划任务的「运行」可靠。
|
||||
|
||||
**Q4. 单机多单:如果要同时渲多单,怎么才不会把机器顶满?**
|
||||
我会先**不加并发、先加吞吐**:现在每张图都要冷启动一次 Blender、加载一次工程,固定开销不小。同一个模板的多张皮肤放进**同一个 Blender 进程**里连着渲(换贴图、再渲),通常比开两个进程更快、峰值还更低。
|
||||
真要并发的话:瓶颈是**显存**不是 CPU。按模板估一个显存占用,用一个「显存预算」信号量决定同时开几个;Blender 进程设成低于正常优先级、限定 Cycles 线程数;白天只开一个槽,夜里再开第二个。服务器 `/claim` 不用改,渲染机开两个消费线程各领各的就行(领单本身是原子的)。
|
||||
|
||||
**Q5. 技术栈:换你会不会上框架?**
|
||||
不会换 Web 框架。这个规模下纯标准库完全够,换框架解决不了这次发现的任何一个问题。
|
||||
真正缺的是**数据层**:这次的大部分问题(一码两单、CLI 和服务器互相覆盖、账本丢记录、半截 JSON)本质都是「拿 JSON 文件当数据库」。标准库自带的 `sqlite3` 一个事务就全解决了,零依赖、零安装,小机器也跑得动。路由和校验可以保持现在这样。
|
||||
|
||||
**Q6. 前后端共用一个质检脚本,值不值?**
|
||||
值。前端拦是给人看的体验,后端剥是安全边界,规则来自同一份就不会出现「网页说能传、后端说不行」。
|
||||
但这次也说明了:**比「两边一致」更要紧的是「每个收皮肤的入口都过后端核验」** —— 重渲换皮肤那条路就漏了(#7)。现在所有入口都收敛到 `_read_skin()` 一个函数,以后新加入口也请走它。
|
||||
另外 `pngcheck.py` 里提到的 `tests/png_struct_test.py`(共享用例)这次没带过来,有的话请补一份,它是「两边一致」唯一的保证。
|
||||
|
||||
---
|
||||
|
||||
## 5. 苏达(运维)另外想知道的
|
||||
|
||||
- **3100 行的单文件该不该拆、先拆哪块?**
|
||||
该拆,但不急。先拆**数据层**(codes / orders / 账本的读写 + 锁,约 300 行)—— 这次的 bug 一大半在这里,拆出来才好单测;再拆**支付回调**(钱相关,最需要单测)。HTTP 路由放最后,它最不容易出事。
|
||||
|
||||
- **卡密和订单用 JSON 文件存,并发写和「写到一半崩了」风险多大?**
|
||||
实测给你一个数:CLI 一边发码、服务器一边下单,**原版 200 张码丢了 185 张**。这次的低成本加固已经做了(跨进程 flock + 唯一临时文件 + fsync),改后 0 丢失。中期还是建议换 SQLite(见 Q5)。
|
||||
|
||||
- **限流放两处(nginx + 应用),是重复还是互补?会不会打架?**
|
||||
互补:nginx 按**请求速率**挡刷接口,应用按**业务语义**挡(同 IP 开单数、输错冷却)。
|
||||
打架的地方有两个:① 请求体大小 nginx 4m / 1m 对上应用的 10MB(#15);② nginx 回 429 / 413 时给的是 **HTML**,前端按 JSON 解析会失败,买家只看到一句笼统的错。建议 nginx 的 413 / 429 都回一段 JSON(`error_page` + 一个返回 JSON 的 location)。
|
||||
|
||||
- **内存受限的前提下,还有哪些地方可能爆?**
|
||||
① 下载整张读进内存(已改);② 收图接口单个请求峰值约 50MB,5 个并发就到 256M(建议见第 2 节 #23);③ ffmpeg 做 4096 预览(未验证,建议实测);④ 线程不设上限。
|
||||
|
||||
- **日志与审计够不够追责?**
|
||||
不够自证「我的图被别人下了」:**下载根本不留记录**(建议见第 2 节)。反过来,有些地方又记得**太多**:nginx access log 里有取件码(URL 的 `?t=`),`payplatform-hook.log` 整包 headers 落盘。建议审计记「谁、什么时候、哪一单、哪一张」,但**不记凭证本身**。
|
||||
|
||||
- **有没有「完全没想到」的角度?**
|
||||
- **取件码放在 URL 里**:会进浏览器历史、服务器日志,订单页上点外链还会通过 `Referer` 带出去。订单页加 `Referrer-Policy: no-referrer` 成本最低。
|
||||
- **随机数**(#6):「码空间够大,暴力猜不中」这个论证只防盲猜,防不住预测。
|
||||
- **框架方法重名**(#10):继承标准库的类时,自己的方法名别和父类撞,`finish` / `handle` / `setup` 都是保留的。
|
||||
- **买家数据的保留期**:渲染机那边永久留档了买家皮肤和成品(你们已知缺口 2)。从隐私角度,建议给留档也定一个保留期,至少能按订单号删。
|
||||
|
||||
---
|
||||
|
||||
## 6. 你没验证的部分
|
||||
|
||||
- 真实 nginx 配置(只看了片段;`/finish` 那条省略了 headers,看不出有没有带 X-Real-IP)。
|
||||
- 爱发电真实的反查返回结构(`custom_order_id` 到底在不在反查结果里)—— 我是拿假的反查结果测的。
|
||||
- ffmpeg 预览:测试机没有水印字体,预览那一步我用「直接拷一份」顶替了,水印本身没测。
|
||||
- 2048 / 4096 的真实成品大小、ffmpeg 峰值内存(没有渲染机、没有真实成品)。
|
||||
- systemd / cgroup 配置、定时任务(sweep 多久跑一次)都没看到。
|
||||
|
||||
## 7. 你还需要什么材料
|
||||
|
||||
- 线上 nginx 里 `/order/` 相关的完整配置(脱敏)。
|
||||
- 一份 4096 单的成品文件大小(标准版 + 无压缩各多大)。
|
||||
- 爱发电 `query-order` 返回的一条样例(脱敏)。
|
||||
- `tests/png_struct_test.py`。
|
||||
- systemd unit(`MemoryMax` 等)和跑 `admin.py sweep` 的定时任务。
|
||||
|
||||
---
|
||||
|
||||
*以上改动都还只在工作区,等你们(和 ywsabc2)看过再决定要不要合。*
|
||||
|
||||
---
|
||||
|
||||
# 第二轮(2026-10-05 晚)· 接入数据库 + 管理接口补齐
|
||||
|
||||
> 上一轮第 2 节「中期:换 SQLite」这次做了。你们没给真实数据,所以测试全用现编的假数据;
|
||||
> 设计目标是**换上就能用**:放好 `store.py` 重启即可,第一次启动自动建库并导入旧 JSON。
|
||||
> 怎么装、怎么回退、怎么测,都写进了 `交接说明.md` 第五节。
|
||||
|
||||
### 改动 14 · 数据层换成 SQLite
|
||||
|
||||
```
|
||||
文件 / 函数:新增 store.py;server.py 的 load_codes / save_codes(新)/ read_meta / write_meta / list_orders /
|
||||
drop_order(新)/ purge_order(新)/ add_call(新)/ note_tpl_time / tpl_eta_sec / gift_batches /
|
||||
heartbeat / hb / call / feedback / finish_upload 里写呼叫的地方 / 爱发电账本读写;
|
||||
admin.py 的 calls / sweep,新增 db 子命令
|
||||
为什么改:上一轮修的竞态根子都是「拿 JSON 文件当数据库」;锁补上了,但断电半截、整文件重写、
|
||||
列队列要读遍所有 meta.json 这些还在
|
||||
改成什么:卡密 / 订单信息 / 爱发电账本 / 呼叫记录 / 小块状态进 <DATA_DIR>/ys.db;
|
||||
上层还是拿到原来的 dict,路由逻辑一行没动,原来的 LOCK 也照旧保留
|
||||
⚠️ 有没有动接口路径 / 请求响应字段 / 数据格式:
|
||||
接口路径、请求 / 响应字段:没动。
|
||||
数据格式:**动了**(存储从 JSON 文件换成 SQLite)。第一次启动自动导入、旧文件不动,
|
||||
`admin.py db export` 能原样导回旧格式。calls.jsonl 照旧追加(手机通知要读)。渲染机不用动。
|
||||
你怎么验证的:tests/数据库测试.py 38 条(全新安装 / 迁移 / 重启不重导 / 多进程同时首启只导一次 / 只改变化的行 / 清理 / 回滚 /
|
||||
导出再导入一致 / 热备份 / 服务器跑在迁移来的数据上 / 8 线程 + 2 进程并发 / 5000 码 2000 单规模);
|
||||
tests/回执复现测试.py 27 条照旧全过(现在跑在库上)
|
||||
```
|
||||
|
||||
### 改动 15 · 管理接口补四个(给新面板用)
|
||||
|
||||
```
|
||||
文件 / 函数:server.py 的 admin_calls / admin_call_done / admin_retry(新);admin_codes 加可选参数 q
|
||||
为什么改:面板上「渲染失败」只能写「喊苏达用 admin.py retry」;呼叫记录只能 ssh 上去看
|
||||
改成什么:GET /api/admin/calls、POST /api/admin/call-done、POST /api/admin/retry(只收 failed 的单)、
|
||||
GET /api/admin/codes?q=(不传 q 和以前一样)
|
||||
⚠️ 有没有动接口:**新增**四个,老的路径 / 字段没改;都在原来的两道门(令牌 + 家里 IP)后面
|
||||
你怎么验证的:假数据起真服务器 + 真面板逐个打:退回重渲成功、对非 failed 单拒绝;
|
||||
不带令牌直接打 → 403;面板不带 PIN → 401
|
||||
```
|
||||
|
||||
### 这轮没验证的
|
||||
|
||||
- 没在你们的真机器(1.6G 内存 + systemd MemoryMax)上跑过;库很小(几千行级别),按测试的内存占用不会有压力,但请部署后跑一次 `admin.py db check`。
|
||||
- `admin.py` 用别的账号跑时的目录权限(WAL 要在 `<DATA_DIR>` 里建两个小文件),见交接说明 5.1。
|
||||
|
||||
### 第二轮自查修掉的三处(推送前审查)
|
||||
|
||||
- `add_call`:渲染机回传(`finish_upload`)的「部分失败」也调它;写库出错原来会把异常抛到回传接口 → 改成只记日志、`calls.jsonl` 照写。
|
||||
- `store.import_legacy`:服务器和 `admin.py` 同时第一次启动会各导一遍(呼叫记录翻倍)→ 在写事务里再判一次「导过没有」。测试加了一条(三个进程同时首启)。
|
||||
- `admin_call_done`:撤销「处理过了」时 `handled_at` 没清 → 一起清掉。
|
||||
@@ -0,0 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 核对渲染机进程:是不是这次部署之后起来的(光看"在线"不够 —— 旧进程也报在线)
|
||||
$ps = @(Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*ys_worker.py*' })
|
||||
Write-Host "渲染机进程数:$($ps.Count)"
|
||||
foreach ($p in $ps) {
|
||||
$age = [math]::Round(((Get-Date) - $p.CreationDate).TotalMinutes, 1)
|
||||
Write-Host (" PID {0} 启动于 {1} 已运行 {2} 分钟" -f $p.ProcessId, $p.CreationDate, $age)
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
把渲染机(worker)装到 Windows 宿主机上。
|
||||
链路:本机 → VM(ssh <跳板>) → Windows 宿主(<LOCAL-IP>)
|
||||
|
||||
用法:python3 <WORKER_DIR>/deploy.py
|
||||
前提:宿主那台开着、隧道通(ssh <跳板> 能 echo 出东西)
|
||||
"""
|
||||
import json, os, subprocess, sys, time
|
||||
|
||||
SRC = "<WORKER_DIR>"
|
||||
STAGE = "<TMP_OUT>"
|
||||
HOST_DIR = "<WIN-PATH>"
|
||||
KEY_HOST = "<SSH-KEY>"
|
||||
KEY_VM = "<SSH-KEY>"
|
||||
|
||||
|
||||
def sh(cmd, timeout=180):
|
||||
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
|
||||
return r.returncode, ((r.stdout or "") + (r.stderr or "")).strip()
|
||||
|
||||
|
||||
def step(title, cmd, timeout=180):
|
||||
print("\n=== %s ===" % title)
|
||||
rc, out = sh(cmd, timeout)
|
||||
print(out[-2500:] if out else "(无输出)")
|
||||
return rc, out
|
||||
|
||||
|
||||
def main():
|
||||
# 0) 先确认隧道
|
||||
rc, out = sh("ssh -o ConnectTimeout=10 -o BatchMode=yes <跳板> 'echo vm-ok'", 40)
|
||||
if "vm-ok" not in out:
|
||||
sys.exit("隧道不通:先确认 VM 和宿主机都开着(%s)" % out[:200])
|
||||
|
||||
# 1) 组装 staging
|
||||
os.makedirs(STAGE, exist_ok=True)
|
||||
for f in ("ys_worker.py", "ys_local.py", "local.html", "ys_admin.py",
|
||||
"run_worker.bat", "open_local.bat", "run_admin.bat", "stop_admin.bat",
|
||||
"stop_worker.bat", "show_log.bat", "install_worker.ps1",
|
||||
"pack_archive.bat", "pack_archive.ps1", "chk_worker.ps1"):
|
||||
data = open(os.path.join(SRC, f), "rb").read()
|
||||
if f.endswith(".ps1") and not data.startswith(b"\xef\xbb\xbf"):
|
||||
data = b"\xef\xbb\xbf" + data # BOM:让 PowerShell 正确读中文
|
||||
# ⚠️ 幂等:源文件已带 BOM 就不要再加,加两次 PowerShell 开头会多出乱码字符
|
||||
open(os.path.join(STAGE, f), "wb").write(data)
|
||||
token = open("<DATA_DIR>/worker_token", encoding="utf-8").read().strip()
|
||||
# 开单后台的令牌(金钻电脑上那块面板用)—— 和渲染机 token 是两把,互不通用
|
||||
atok = open("<DATA_DIR>/admin_token", encoding="utf-8").read().strip()
|
||||
with open(os.path.join(STAGE, "config.json"), "w", encoding="utf-8") as f:
|
||||
json.dump({"server": "http<WIN-PATH>", "token": token,
|
||||
"admin_token": atok,
|
||||
# 模板已统一收进「头图\模板\」(2026-09-30)
|
||||
"tpl_root": r"<ARCHIVE_DIR>",
|
||||
# 在线检查 10 分钟一次(金钻 9-30);领单仍 20 秒,别改大
|
||||
"hb_every": 600,
|
||||
"poll": 20,
|
||||
"blender": r"<PROJECT_DIR>"},
|
||||
f, ensure_ascii=False, indent=1)
|
||||
mk = "<MAKE_ORDER_DIR>/make_order.py"
|
||||
open(os.path.join(STAGE, "make_order.py"), "wb").write(open(mk, "rb").read())
|
||||
# 质检代码必须是同一份 —— 从网页那边取,绝不手工复制
|
||||
open(os.path.join(STAGE, "skincheck.js"), "wb").write(
|
||||
open("<SITE_DIR>/skincheck.js", "rb").read())
|
||||
|
||||
sizes = {f: os.path.getsize(os.path.join(STAGE, f)) for f in sorted(os.listdir(STAGE))}
|
||||
print("待传文件:")
|
||||
for k, v in sizes.items():
|
||||
print(" %-22s %6d 字节" % (k, v))
|
||||
|
||||
# 2) 本机 → VM
|
||||
step("本机 → VM", "scp -i %s -P <SSH-PORT> -o StrictHostKeyChecking=accept-new -r %s shopowner@localhos<WIN-PATH>" % (KEY_VM, STAGE))
|
||||
|
||||
# 3) VM 上跑一段脚本,把文件推到宿主并核对(引号地狱 → 用脚本文件)
|
||||
vm_sh = r'''#!/bin/sh
|
||||
set -e
|
||||
rm -rf <TMP_WORK> && mkdir -p <TMP_WORK>
|
||||
cp <TMP_OUT>/* <TMP_WORK>/
|
||||
SSH="ssh -i KEY -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 user0@<LOCAL-IP>"
|
||||
SCP="scp -i KEY -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10"
|
||||
$SSH "if not exist <WORKER_DIR> mkdir <WORKER_DIR>" || true
|
||||
$SSH "if not exist <TOOLS_DIR> mkdir <TOOLS_DIR>" || true
|
||||
# ⚠️ 以前这里是**写死的文件名清单** —— 结果新加的 pack_archive.* 传不上去,
|
||||
# 本地打印"待传文件"看着传了,宿主上根本没有(2026-09-30 实踩第 3 次"改 A 忘 B")。
|
||||
# 改成自动带上 staging 里除 make_order.py 之外的全部文件。
|
||||
WLIST=""
|
||||
for f in <TMP_WORK>/*; do
|
||||
case "$f" in */make_order.py) continue;; esac
|
||||
WLIST="$WLIST $f"
|
||||
done
|
||||
$SCP $WLIST "user0@<LOCAL-IP>:<WIN-PATH>"
|
||||
$SCP <TMP_WORK>/make_order.py "user0@<LOCAL-IP>:<WIN-PATH>"
|
||||
echo "--- <WORKER_DIR> ---"
|
||||
$SSH "dir <WORKER_DIR>"
|
||||
echo "--- <TOOLS_DIR>\\make_order.py ---"
|
||||
$SSH "dir <TOOLS_DIR>\\make_order.py"
|
||||
'''.replace("KEY", KEY_HOST)
|
||||
open("<TMP_SCRIPT>", "w", newline="\n").write(vm_sh)
|
||||
step("本机 → VM(推送脚本)", "scp -i %s -P <SSH-PORT> <TMP_SCRIPT> shopowner@localhost:<TMP_SCRIPT>" % KEY_VM)
|
||||
step("VM → 宿主 推送", "ssh <跳板> 'sh <TMP_SCRIPT>'", 300)
|
||||
|
||||
# 4) 跑安装脚本
|
||||
step("宿主上执行安装",
|
||||
"ssh <跳板> \"ssh -i %s -o StrictHostKeyChecking=accept-new user0@<LOCAL-IP> "
|
||||
"'powershell -ExecutionPolicy Bypass -File <WIN-PATH>'\"" % KEY_HOST, 300)
|
||||
|
||||
# 5) 服务器侧复核心跳
|
||||
time.sleep(20)
|
||||
step("核对渲染机进程是不是新的",
|
||||
"ssh <跳板> \"ssh -i %s -o StrictHostKeyChecking=accept-new user0@<LOCAL-IP> "
|
||||
"'powershell -NoProfile -ExecutionPolicy Bypass -File <WORKER_DIR>\\chk_worker.ps1'\"" % KEY_HOST, 120)
|
||||
|
||||
rc, out = sh("curl -s http<WIN-PATH>", 30)
|
||||
print("\n=== 服务器看到的渲染机状态 ===")
|
||||
print(out)
|
||||
if '"online":true' in out.replace(" ", ""): # 先去空格再比;之前比的是带空格的串,永远为假
|
||||
print("✅ 渲染机已上线")
|
||||
else:
|
||||
print("⚠️ 还没看到心跳,看宿主 <WORKER_DIR>\\worker.log")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,170 @@
|
||||
# YS render worker installer —— 在 Windows 宿主机上跑(金钻工坊·渲染下单)
|
||||
# 做四件事:找 pythonw → 修好 run_worker.bat → 注册开机自启 → 桌面放开关 → 立刻启动
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$DIR = '<WORKER_DIR>'
|
||||
Write-Host "=== YS 渲染机 安装 ==="
|
||||
|
||||
# 1) 找 pythonw.exe
|
||||
$pw = (Get-Command pythonw.exe -ErrorAction SilentlyContinue).Source
|
||||
if (-not $pw) {
|
||||
$c = Get-ChildItem -Path "$env:LOCALAPPDATA\Programs\Python", "<WIN_DIR>*", "<PROGRAM_DIR>" `
|
||||
-Filter pythonw.exe -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if ($c) { $pw = $c.FullName }
|
||||
}
|
||||
if (-not $pw) { Write-Host "ERROR: 找不到 pythonw.exe,先把 Python 装上"; exit 1 }
|
||||
Write-Host "pythonw = $pw"
|
||||
|
||||
# 2) 把两个 .bat 里的占位符换成真实路径
|
||||
$bat = Join-Path $DIR 'run_worker.bat'
|
||||
if (Test-Path $bat) {
|
||||
$t = Get-Content $bat -Raw
|
||||
$t = $t -replace '__PYTHONW__', $pw
|
||||
[IO.File]::WriteAllText($bat, $t, [Text.Encoding]::ASCII)
|
||||
Write-Host "run_worker.bat 已修好"
|
||||
} else { Write-Host "ERROR: 缺 run_worker.bat"; exit 1 }
|
||||
|
||||
# 本机开单工具用 python.exe(要留个黑框,崩了能看见)
|
||||
$py = (Get-Command python.exe -ErrorAction SilentlyContinue).Source
|
||||
if (-not $py) { $py = $pw -replace 'pythonw\.exe$', 'python.exe' }
|
||||
$bat2 = Join-Path $DIR 'open_local.bat'
|
||||
if (Test-Path $bat2) {
|
||||
$t2 = Get-Content $bat2 -Raw
|
||||
$t2 = $t2 -replace '__PYTHON__', $py
|
||||
[IO.File]::WriteAllText($bat2, $t2, [Text.Encoding]::ASCII)
|
||||
Write-Host "open_local.bat 已修好 (python=$py)"
|
||||
} else { Write-Host "!! 缺 open_local.bat,本机开单工具没法一键启动" }
|
||||
|
||||
# 开单后台(金钻 2026-09-30:家里电脑上点着用的,局域网 8081)
|
||||
# 用 pythonw(不留黑框);⚠️ 两个占位符都要替,只替一个会留个 __PYTHONW__ 在文件里
|
||||
$bat3 = Join-Path $DIR 'run_admin.bat'
|
||||
if (Test-Path $bat3) {
|
||||
$t3 = Get-Content $bat3 -Raw
|
||||
$t3 = $t3 -replace '__PYTHONW__', $pw
|
||||
$t3 = $t3 -replace '__PYTHON__', $py
|
||||
[IO.File]::WriteAllText($bat3, $t3, [Text.Encoding]::ASCII)
|
||||
Write-Host "run_admin.bat 已修好 (pythonw=$pw)"
|
||||
} else { Write-Host "!! 缺 run_admin.bat,开单后台没法一键启动" }
|
||||
|
||||
# 3) 开机自启(登录时启动,不需要管理员)
|
||||
schtasks /Delete /TN "YS-Render-Worker" /F 2>$null | Out-Null
|
||||
schtasks /Create /TN "YS-Render-Worker" /TR "`"$bat`"" /SC ONLOGON /RL LIMITED /F | Out-Null
|
||||
if ($LASTEXITCODE -eq 0) { Write-Host "已注册开机自启:YS-Render-Worker" }
|
||||
else { Write-Host "!! 注册开机自启失败(可手动跑 run_worker.bat)" }
|
||||
|
||||
# 开单后台也随登录自启(局域网服务,手机同 WiFi 直接开;不需要就删掉这个计划任务)
|
||||
if (Test-Path $bat3) {
|
||||
schtasks /Delete /TN "YS-Admin-Panel" /F 2>$null | Out-Null
|
||||
# ⚠️ 计划任务**直接调 pythonw 且不带 --open** —— 走 bat 的话会带 --open,开机就弹一个网页出来
|
||||
schtasks /Create /TN "YS-Admin-Panel" /TR "`"$pw`" `"$DIR\ys_admin.py`"" /SC ONLOGON /RL LIMITED /F | Out-Null
|
||||
if ($LASTEXITCODE -eq 0) { Write-Host "已注册开机自启:YS-Admin-Panel(开单后台)" }
|
||||
else { Write-Host "!! 开单后台自启注册失败(点开始菜单「开单后台」也能起)" }
|
||||
}
|
||||
|
||||
# 4) 桌面放三个开关
|
||||
$desk = [Environment]::GetFolderPath('Desktop')
|
||||
$sh = New-Object -ComObject WScript.Shell
|
||||
function MkLink([string]$name, [string]$target, [string]$desc) {
|
||||
$p = Join-Path $desk $name
|
||||
$l = $sh.CreateShortcut($p)
|
||||
$l.TargetPath = $target
|
||||
$l.WorkingDirectory = $DIR
|
||||
$l.Description = $desc
|
||||
$l.Save()
|
||||
if (Test-Path $p) { Write-Host "桌面快捷方式:$name" }
|
||||
}
|
||||
# ⚠️ 金钻 2026-09-30:桌面别撒一地 —— 全部进开始菜单「金钻工坊」,桌面只留一个入口。
|
||||
# 以前是往桌面逐个放 5 个快捷方式,桌面就花了。
|
||||
$GROUP = '金钻工坊'
|
||||
$start = Join-Path ([Environment]::GetFolderPath('Programs')) $GROUP
|
||||
New-Item -ItemType Directory -Force -Path $start | Out-Null
|
||||
function MkIn([string]$folder, [string]$name, [string]$target, [string]$desc) {
|
||||
$p = Join-Path $folder $name
|
||||
$l = $sh.CreateShortcut($p)
|
||||
$l.TargetPath = $target
|
||||
$l.WorkingDirectory = $DIR
|
||||
$l.Description = $desc
|
||||
$l.Save()
|
||||
if (Test-Path $p) { Write-Host "快捷方式:$folder\$name" }
|
||||
}
|
||||
$shortcutItems = @(
|
||||
@('本机开单', 'open_local.bat', '平台单:本机出图,不联网、不用卡密'),
|
||||
@('开单后台', 'run_admin.bat', '生成卡密 / 激活订单(局域网,手机同 WiFi 也能开)'),
|
||||
@('开单后台-停止', 'stop_admin.bat', '关掉开单后台'),
|
||||
@('打包留档', 'pack_archive.bat', '把在线订单压成一个 zip,方便整个拖网盘'),
|
||||
@('渲染机-启动', 'run_worker.bat', '启动影塑渲染机'),
|
||||
@('渲染机-停止', 'stop_worker.bat', '停止影塑渲染机'),
|
||||
@('渲染机-看日志', 'show_log.bat', '查看渲染机日志与服务器队列')
|
||||
)
|
||||
foreach ($it in $shortcutItems) {
|
||||
MkIn $start ($it[0] + '.lnk') (Join-Path $DIR $it[1]) $it[2]
|
||||
# 顺手把以前撒在桌面上的清掉(只删苏达建的这几个名字)
|
||||
$dp = Join-Path $desk ($it[0] + '.lnk')
|
||||
if (Test-Path $dp) { Remove-Item $dp -Force }
|
||||
}
|
||||
$dg = Join-Path $desk "$GROUP.lnk"
|
||||
if (Test-Path $dg) { Remove-Item $dg -Force }
|
||||
MkIn $desk "$GROUP.lnk" $start "金钻工坊:本机开单 / 渲染机开关 / 打包留档"
|
||||
|
||||
# 5) 立刻启动
|
||||
# ⚠️ 不能用 Start-Process —— 通过 SSH 起的进程会随会话结束被带走(2026-09-30 实踩:
|
||||
# 安装时显示"已运行",session 一断 worker 就没了,订单干等在队列里没人领)。
|
||||
# 走计划任务启动,由 Task Scheduler 持有,跟 SSH 会话无关。
|
||||
# ⚠️⚠️ 必须先停掉正在跑的旧进程再起新的!
|
||||
# 2026-09-30 实踩:部署脚本从头到尾都"成功",但渲染机进程是早上 09:19 起的,
|
||||
# 跑了一整天旧代码 —— 序号登记、条款留证、看门狗全都没生效,
|
||||
# 而且现象极具迷惑性(能出图、不报错,只是新功能静默缺失)。
|
||||
# 计划任务 /Run 对已在运行的实例不会替换,所以必须显式杀。
|
||||
$old = Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*ys_worker.py*' }
|
||||
if ($old) {
|
||||
foreach ($p in $old) {
|
||||
Write-Host "停掉旧渲染机进程 PID $($p.ProcessId)(启动于 $($p.CreationDate))"
|
||||
Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
Start-Sleep -Seconds 3
|
||||
}
|
||||
schtasks /Run /TN "YS-Render-Worker" 2>$null | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { Start-Process -FilePath $bat -WindowStyle Hidden }
|
||||
|
||||
# 开单后台:同一套「先杀旧、再起新」——不然跑着的还是昨天的代码(这个坑在渲染机上踩过)
|
||||
if (Test-Path $bat3) {
|
||||
$oldA = Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*ys_admin.py*' }
|
||||
foreach ($p in $oldA) {
|
||||
Write-Host "停掉旧开单后台进程 PID $($p.ProcessId)(启动于 $($p.CreationDate))"
|
||||
Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
if ($oldA) { Start-Sleep -Seconds 2 }
|
||||
schtasks /Run /TN "YS-Admin-Panel" 2>$null | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { Start-Process -FilePath $bat3 -WindowStyle Hidden }
|
||||
# ⚠️ 进程要几秒才出现、接口要十几秒才通 —— 检查**放在这个重试循环里**,
|
||||
# 放在循环外面会误报「没起来 / 接口不通」(2026-09-30 一晚踩了三次)
|
||||
$pa = $null
|
||||
for ($i = 1; $i -le 6; $i++) {
|
||||
Start-Sleep -Seconds 3
|
||||
$pa = Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*ys_admin.py*' }
|
||||
if ($pa) {
|
||||
try {
|
||||
# ⚠️ 2026-10-01 起面板有 PIN 锁:自检只能打免锁的 /api/health(state 会 401 → 自检误报"没起来")
|
||||
$code = (Invoke-WebRequest -UseBasicParsing 'htt<WIN-PATH>' -TimeoutSec 25).Content
|
||||
Write-Host "开单后台:已运行 (PID $($pa.ProcessId -join ','))(局域网 htt<WIN-PATH>"
|
||||
Write-Host "开单后台自检:$($code.Substring(0, [Math]::Min(200, $code.Length)))"
|
||||
break
|
||||
} catch { }
|
||||
}
|
||||
}
|
||||
if (-not $pa) { Write-Host "!! 开单后台没起来,看 <WORKER_DIR>\admin.log" }
|
||||
}
|
||||
Start-Sleep -Seconds 10
|
||||
|
||||
# 6) 自检:进程 + 服务器心跳
|
||||
$proc = Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*ys_worker.py*' }
|
||||
if ($proc) { Write-Host "进程:已运行 (PID $($proc.ProcessId -join ','))" }
|
||||
else { Write-Host "!! 进程没起来,去 <WORKER_DIR>\worker.log 看原因" }
|
||||
try {
|
||||
$s = (Invoke-WebRequest -UseBasicParsing 'http<WIN-PATH>' -TimeoutSec 20).Content
|
||||
Write-Host "服务器状态:$s"
|
||||
} catch { Write-Host "!! 连不上服务器:$_" }
|
||||
if (Test-Path (Join-Path $DIR 'worker.log')) {
|
||||
Write-Host "--- worker.log 末尾 ---"
|
||||
Get-Content (Join-Path $DIR 'worker.log') -Tail 15
|
||||
}
|
||||
Write-Host "=== 安装完成 ==="
|
||||
@@ -0,0 +1,500 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>本机开单 · 金钻工坊(平台单)</title>
|
||||
<style>
|
||||
/* 本机开单(2026-10-05 重写:跟 2026 版网站 / 开单后台同一套样子 —— 白光 + 毛玻璃卡片 + MC 方块按钮)
|
||||
本页跑在家里电脑上,引不到网站的 css / 字体,颜色值照网站复制一份(改值要两边一起改)。
|
||||
布局:电脑上左边「皮肤 + 质检」、右边「模板 + 分辨率 + 开始」;出图结果在下面整行。手机上从上往下排。 */
|
||||
:root{--bg:#F5F7FB;--txt:#1E2440;--txt-2:#454B6B;--txt-3:#5E6482;--dim:#7E849C;
|
||||
--line:rgba(30,36,64,.13);--line-soft:rgba(30,36,64,.08);
|
||||
--glass:linear-gradient(160deg,rgba(255,255,255,.9),rgba(255,255,255,.7));
|
||||
--panel-shadow:inset 0 1px 0 #fff,0 22px 44px -28px rgba(100,110,190,.38);
|
||||
--mc:#3C8527;--mc-hi:#5BAA3C;--mc-lo:#1D4D13;--ok-t:#2F6E1F;
|
||||
--stone:#F3F4F6;--stone-lo:#B4B7BE;--stone-edge:#9EA2AA;
|
||||
--bad-t:#B33A2E;--warn-t:#9A6A0C;
|
||||
--ease:cubic-bezier(.23,1,.32,1);
|
||||
--font:'OPPO Sans',system-ui,-apple-system,"PingFang SC","Microsoft YaHei","Segoe UI",sans-serif;
|
||||
--mono:ui-monospace,Consolas,"SF Mono",Menlo,monospace;color-scheme:light}
|
||||
*{box-sizing:border-box}
|
||||
[hidden]{display:none!important}
|
||||
body{margin:0;min-height:100vh;background:var(--bg);color:var(--txt);font:14.5px/1.65 var(--font);-webkit-font-smoothing:antialiased}
|
||||
body::before{content:"";position:fixed;inset:0;z-index:-1;pointer-events:none;background:
|
||||
radial-gradient(40% 34% at 6% 0%,rgba(150,215,255,.30),transparent 70%),radial-gradient(36% 30% at 100% 8%,rgba(255,176,204,.22),transparent 70%),
|
||||
radial-gradient(48% 38% at 72% 100%,rgba(255,214,150,.22),transparent 70%),radial-gradient(42% 36% at 0% 72%,rgba(170,235,200,.22),transparent 70%)}
|
||||
button,input{font:inherit;color:inherit}
|
||||
a{color:var(--mc);font-weight:700;text-decoration:none}
|
||||
a:hover{text-decoration:underline}
|
||||
|
||||
/* ---------- 顶栏 ---------- */
|
||||
header{position:sticky;top:0;z-index:20;background:rgba(255,255,255,.74);border-bottom:1px solid rgba(255,255,255,.9);box-shadow:0 10px 30px -24px rgba(80,90,170,.45);
|
||||
-webkit-backdrop-filter:blur(14px) saturate(1.4);backdrop-filter:blur(14px) saturate(1.4)}
|
||||
.hd{max-width:1180px;margin:0 auto;padding:12px 20px;display:flex;align-items:center;gap:12px}
|
||||
.hd h1{margin:0;font-size:17px;letter-spacing:.02em}
|
||||
.hd .sub{font-size:12px;color:var(--dim)}
|
||||
.badge{margin-left:auto;display:inline-flex;align-items:center;height:30px;padding:0 11px;border-radius:4px;font-size:12.5px;font-weight:700;white-space:nowrap;
|
||||
background:rgba(255,255,255,.85);border:1px solid var(--line-soft);color:var(--txt-3)}
|
||||
.badge.ok{color:var(--ok-t);background:rgba(91,170,60,.1);border-color:rgba(60,133,39,.25)}
|
||||
.badge.bad{color:var(--bad-t);background:rgba(210,72,58,.08);border-color:rgba(210,72,58,.25)}
|
||||
|
||||
/* ---------- 骨架 ---------- */
|
||||
.wrap{max-width:1180px;margin:0 auto;padding:20px}
|
||||
.cols{display:grid;grid-template-columns:minmax(0,5fr) minmax(0,7fr);gap:18px;align-items:start}
|
||||
.card{background:var(--glass);border:2px solid rgba(255,255,255,.95);border-radius:8px;box-shadow:var(--panel-shadow);padding:20px;margin-bottom:18px}
|
||||
.step{display:flex;align-items:center;gap:10px;margin:0 0 4px}
|
||||
.step .num{display:inline-grid;place-items:center;width:30px;height:30px;flex:none;border-radius:4px;background:var(--stone);border:2px solid var(--stone-edge);
|
||||
font:800 14px/1 var(--mono);box-shadow:inset 0 2px 0 #fff,inset 0 -3px 0 var(--stone-lo)}
|
||||
.step.done .num{background:var(--mc);border-color:var(--mc-lo);color:#fff;box-shadow:inset 0 2px 0 var(--mc-hi),inset 0 -3px 0 var(--mc-lo)}
|
||||
.step h2{margin:0;font-size:17px}
|
||||
.hint{font-size:13px;color:var(--txt-3);margin:4px 0 16px;line-height:1.75}
|
||||
.hint b{color:var(--txt-2)}
|
||||
.lab{font-size:12.5px;font-weight:700;color:var(--txt-2);margin:18px 0 8px}
|
||||
.lab .h{font-weight:400;color:var(--dim)}
|
||||
|
||||
/* ---------- 按钮:绿 = 主,石头白 = 次 ---------- */
|
||||
.btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;height:42px;padding:0 16px 3px;border-radius:4px;cursor:pointer;white-space:nowrap;
|
||||
border:2px solid var(--stone-edge);background:var(--stone);color:var(--txt);font-weight:700;font-size:14px;
|
||||
box-shadow:inset 0 2px 0 #fff,inset 0 -4px 0 var(--stone-lo);transition:transform .08s linear,box-shadow .08s linear,background .12s}
|
||||
.btn:hover:not(:disabled){background:#fff}
|
||||
.btn:active:not(:disabled){transform:translateY(2px);box-shadow:inset 0 2px 0 #fff,inset 0 -2px 0 var(--stone-lo)}
|
||||
.btn.pri{border-color:var(--mc-lo);background:var(--mc);color:#fff;box-shadow:inset 0 2px 0 var(--mc-hi),inset 0 -4px 0 var(--mc-lo)}
|
||||
.btn.pri:hover:not(:disabled){background:#469A2E}
|
||||
.btn.pri:active:not(:disabled){box-shadow:inset 0 2px 0 var(--mc-hi),inset 0 -2px 0 var(--mc-lo)}
|
||||
.btn.big{height:48px;font-size:15.5px;flex:1;min-width:200px}
|
||||
.btn:disabled{opacity:.45;cursor:not-allowed;filter:saturate(.4)}
|
||||
.btn:focus-visible,.tpl:focus-visible,.seg button:focus-visible,.drop:focus-visible{outline:2px solid var(--mc-hi);outline-offset:2px}
|
||||
|
||||
/* ---------- 1 · 皮肤 ---------- */
|
||||
.drop{display:block;width:100%;border:2px dashed rgba(60,133,39,.35);border-radius:8px;padding:30px 16px;text-align:center;cursor:pointer;background:rgba(255,255,255,.6);
|
||||
transition:border-color .15s,background .15s}
|
||||
.drop:hover,.drop.over{border-color:var(--mc);background:rgba(91,170,60,.07)}
|
||||
.drop svg{display:block;margin:0 auto 10px;width:30px;height:30px;color:var(--mc)}
|
||||
.drop .big{font-size:15px;font-weight:700;color:var(--txt);margin-bottom:3px}
|
||||
.drop .small{font-size:12.5px;color:var(--dim)}
|
||||
.drop.has{padding:14px 16px}
|
||||
.drop.has svg{display:none}
|
||||
.skin{display:grid;grid-template-columns:132px minmax(0,1fr);gap:16px;align-items:start;margin-top:16px}
|
||||
.preview{padding:10px;border-radius:8px;background:#fff;border:1px solid var(--line-soft);text-align:center}
|
||||
.preview canvas{width:100%;display:block;image-rendering:pixelated;border-radius:4px;
|
||||
background:conic-gradient(#E9ECF2 25%,#fff 0 50%,#E9ECF2 0 75%,#fff 0) 0 0/12px 12px}
|
||||
.preview .fn{font-size:11.5px;color:var(--dim);margin-top:8px;word-break:break-all;line-height:1.5}
|
||||
#report{display:flex;flex-direction:column;gap:8px}
|
||||
.item{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border-radius:6px;background:rgba(255,255,255,.85);border:1px solid var(--line-soft);font-size:13.5px}
|
||||
.item.warn{background:rgba(255,248,230,.9);border-color:rgba(214,160,40,.3)}
|
||||
.item.bad{background:rgba(255,240,238,.92);border-color:rgba(210,72,58,.3)}
|
||||
.tag{flex:none;display:inline-flex;align-items:center;height:22px;padding:0 8px;border-radius:4px;font-size:12px;font-weight:700;white-space:nowrap;
|
||||
background:rgba(91,170,60,.12);color:var(--ok-t)}
|
||||
.item.warn .tag{background:rgba(214,160,40,.18);color:var(--warn-t)}
|
||||
.item.bad .tag{background:rgba(210,72,58,.12);color:var(--bad-t)}
|
||||
.bd{flex:1;min-width:0}
|
||||
.bd .t{font-weight:700;color:var(--txt)}
|
||||
.bd .d{font-size:12.5px;color:var(--txt-3);margin-top:2px;line-height:1.7}
|
||||
details.terms{margin-top:16px;font-size:12.5px;color:var(--txt-3)}
|
||||
details.terms summary{cursor:pointer;color:var(--mc);font-weight:700}
|
||||
details.terms pre{white-space:pre-wrap;font:12.5px/1.8 var(--font);margin:8px 0 0;padding:10px 12px;border-radius:6px;background:rgba(255,255,255,.8);border:1px solid var(--line-soft)}
|
||||
.copyterms{margin-top:8px}
|
||||
|
||||
/* ---------- 2 · 模板 ---------- */
|
||||
.tpls{display:grid;gap:10px;grid-template-columns:repeat(auto-fill,minmax(138px,1fr))}
|
||||
.tpl{position:relative;display:block;padding:0;text-align:left;border-radius:8px;border:2px solid rgba(255,255,255,.95);background:#fff;cursor:pointer;overflow:hidden;
|
||||
box-shadow:0 12px 24px -20px rgba(80,90,170,.55);transition:transform .15s var(--ease),border-color .15s,box-shadow .15s}
|
||||
.tpl:hover{transform:translateY(-2px)}
|
||||
.tpl.sel{border-color:var(--mc);box-shadow:0 0 0 3px rgba(91,170,60,.22),0 12px 24px -20px rgba(80,90,170,.55)}
|
||||
.tpl .thumb{position:relative;aspect-ratio:4/3;display:grid;place-items:center;background:#EEF1F7;
|
||||
background:radial-gradient(80% 90% at 30% 20%,#fff,transparent 70%),linear-gradient(150deg,color-mix(in srgb,var(--tone) 22%,#fff),color-mix(in srgb,var(--tone) 48%,#fff))}
|
||||
.tpl .thumb svg{width:40px;height:40px;color:var(--tone);opacity:.85}
|
||||
.tpl .meta{padding:9px 11px 10px}
|
||||
.tpl .n{font-size:13.5px;font-weight:700;color:var(--txt)}
|
||||
.tpl .s{font-size:11.5px;color:var(--dim);margin-top:1px}
|
||||
.tpl .pick{position:absolute;top:8px;right:8px;width:22px;height:22px;display:grid;place-items:center;border-radius:4px;border:2px solid rgba(30,36,64,.18);background:rgba(255,255,255,.9);color:transparent;font-size:13px;font-weight:800}
|
||||
.tpl.sel .pick{background:var(--mc);border-color:var(--mc-lo);color:#fff}
|
||||
.tpl .ord{position:absolute;top:8px;left:8px;min-width:22px;height:22px;padding:0 6px;border-radius:4px;background:var(--txt);color:#fff;font:700 12px/22px var(--mono);text-align:center}
|
||||
.tpl:not(.sel) .ord{display:none}
|
||||
.seg{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px}
|
||||
.seg button{min-height:52px;padding:6px 8px;border-radius:4px;border:2px solid var(--line);background:rgba(255,255,255,.75);cursor:pointer;text-align:center;
|
||||
font:800 15px/1.2 var(--mono);color:var(--txt-2);transition:border-color .12s,background .12s,color .12s}
|
||||
.seg button small{display:block;margin-top:3px;font:400 11.5px/1.3 var(--font);color:var(--dim)}
|
||||
.seg button:hover{background:#fff}
|
||||
.seg button.on{border-color:var(--mc);background:rgba(91,170,60,.1);color:var(--ok-t)}
|
||||
input.t{width:100%;height:42px;padding:0 12px;border-radius:4px;border:2px solid var(--line);background:#fff;outline:none;transition:border-color .12s}
|
||||
input.t:focus{border-color:var(--mc)}
|
||||
input.t::placeholder{color:#9AA0B4}
|
||||
.sum{margin-top:18px;padding:11px 13px;border-radius:6px;background:rgba(91,170,60,.08);border:1px solid rgba(60,133,39,.2);font-size:13px;color:var(--txt-2);line-height:1.7}
|
||||
.sum b{color:var(--ok-t)}
|
||||
.sum.idle{background:rgba(30,36,64,.04);border-color:var(--line-soft);color:var(--dim)}
|
||||
.btns{display:flex;gap:10px;margin-top:14px;flex-wrap:wrap}
|
||||
.prog{margin-top:16px}
|
||||
.bar{height:10px;border-radius:3px;background:rgba(30,36,64,.08);overflow:hidden;box-shadow:inset 0 1px 2px rgba(30,36,64,.12)}
|
||||
.bar i{display:block;height:100%;width:0;background:repeating-linear-gradient(90deg,var(--mc) 0 14px,var(--mc-hi) 14px 16px);transition:width .4s var(--ease)}
|
||||
.prog .hint{margin:8px 0 0}
|
||||
|
||||
/* ---------- 3 · 出图 ---------- */
|
||||
.res{display:grid;gap:14px;grid-template-columns:repeat(auto-fill,minmax(210px,1fr))}
|
||||
.res .one{border-radius:8px;overflow:hidden;background:#fff;border:2px solid rgba(255,255,255,.95);box-shadow:0 14px 28px -22px rgba(80,90,170,.55)}
|
||||
.res img{width:100%;display:block;aspect-ratio:1/1;object-fit:cover;background:#EEF1F6}
|
||||
.res .cap{padding:10px 12px 12px;font-size:12px;color:var(--dim)}
|
||||
.res .cap b{display:block;font-size:14px;color:var(--txt);margin-bottom:1px}
|
||||
.res .dls{display:flex;gap:6px;flex-wrap:wrap;margin-top:8px}
|
||||
.res .dls a{display:inline-flex;align-items:center;height:30px;padding:0 10px 2px;border-radius:4px;border:2px solid var(--stone-edge);background:var(--stone);color:var(--txt);font-size:12.5px;
|
||||
box-shadow:inset 0 2px 0 #fff,inset 0 -3px 0 var(--stone-lo);text-decoration:none}
|
||||
.res .dls a:hover{background:#fff}
|
||||
.warnbar,.errbar{padding:12px 14px;border-radius:6px;font-size:13.5px;line-height:1.75;margin-bottom:16px}
|
||||
.warnbar{background:rgba(255,248,230,.95);border:1px solid rgba(214,160,40,.35);color:var(--warn-t)}
|
||||
.errbar{background:rgba(255,240,238,.95);border:1px solid rgba(210,72,58,.3);color:var(--bad-t);white-space:pre-wrap;grid-column:1/-1}
|
||||
footer{text-align:center;font-size:12px;color:var(--dim);padding:10px 20px 36px;line-height:2}
|
||||
footer a{color:var(--txt-3);font-weight:400}
|
||||
.toast{position:fixed;left:50%;bottom:28px;z-index:90;max-width:min(92vw,520px);padding:10px 16px;border-radius:6px;background:#1E2440;color:#fff;font-size:13.5px;
|
||||
opacity:0;transform:translate(-50%,10px);pointer-events:none;transition:opacity .18s var(--ease),transform .18s var(--ease)}
|
||||
.toast.show{opacity:1;transform:translate(-50%,0)}
|
||||
|
||||
@media (max-width:900px){
|
||||
.cols{grid-template-columns:minmax(0,1fr)}
|
||||
.hd{padding:10px 14px}.hd .sub{display:none}
|
||||
.wrap{padding:14px 12px}
|
||||
.card{padding:16px 14px}
|
||||
.seg{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
.skin{grid-template-columns:minmax(0,1fr);gap:10px}
|
||||
.preview{display:flex;align-items:center;gap:12px;text-align:left}
|
||||
.preview canvas{width:72px;flex:none}
|
||||
.preview .fn{margin:0}
|
||||
}
|
||||
@media (prefers-reduced-motion:reduce){.toast{transition:none}.btn:active:not(:disabled){transform:none}.tpl:hover{transform:none}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header><div class="hd">
|
||||
<svg width="26" height="26" viewBox="0 0 24 24" aria-hidden="true"><path fill="#5BAA3C" d="M6 3h12l4 6-10 12L2 9z"/><path fill="#3C8527" d="M2 9h20L12 21z"/><path fill="#9FE07A" d="M6 3l3 6h6l3-6z"/></svg>
|
||||
<h1>本机开单</h1>
|
||||
<span class="sub">平台单 · 只在这台电脑上能打开 · 不联网、不要卡密</span>
|
||||
<span class="badge" id="health">体检中…</span>
|
||||
</div></header>
|
||||
|
||||
<div class="wrap">
|
||||
<div id="syswarn"></div>
|
||||
|
||||
<div class="cols">
|
||||
<div class="card" id="card1">
|
||||
<div class="step" id="st1"><span class="num">1</span><h2>皮肤</h2></div>
|
||||
<p class="hint">把买家发的皮肤图拖进来、点一下选,或者直接 Ctrl+V 粘贴。质检规则和网页版是同一份代码。</p>
|
||||
<button type="button" class="drop" id="drop">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 15V4"/><path d="M8 8l4-4 4 4"/><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/></svg>
|
||||
<div class="big" id="dropBig">点击选择皮肤文件</div>
|
||||
<div class="small">或把 .png 拖到这里 / 直接粘贴图片</div>
|
||||
</button>
|
||||
<input type="file" id="file" accept="image/png" hidden>
|
||||
<div id="pvwrap" hidden>
|
||||
<div class="skin">
|
||||
<div class="preview"><canvas id="pv" width="64" height="64"></canvas><div class="fn" id="pvName"></div></div>
|
||||
<div id="report"></div>
|
||||
</div>
|
||||
</div>
|
||||
<details class="terms">
|
||||
<summary>发给买家的说明(可直接复制)</summary>
|
||||
<pre id="termsTxt">只提供渲染服务,不对皮肤内容与渲染结果作合规担保。
|
||||
皮肤由买家自行提供,其内容合法性由提供者负责;
|
||||
因皮肤内容(含夹带数据、隐藏信息、违规图案)产生的任何后果,由提供者承担。
|
||||
模板质量问题由金钻负责维护修复,非质量问题不予重做。
|
||||
一经发现违法内容,将立即停止服务、删除相关文件、拒绝后续接单。</pre>
|
||||
<button type="button" class="btn copyterms" id="copyTerms" style="height:34px;font-size:13px">复制这段话</button>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<div class="card" id="card2">
|
||||
<div class="step" id="st2"><span class="num">2</span><h2>模板</h2></div>
|
||||
<p class="hint">勾几个就出几张,按勾的顺序出。一次渲一张,不会把机器顶满。</p>
|
||||
<div class="tpls" id="tpls"></div>
|
||||
<div class="lab">出图分辨率 <span class="h">默认 1000 = 网易我的世界头图标准,文件名不带数字;换别的才写进文件名(如 飞跃樱花林2048.png)</span></div>
|
||||
<div class="seg" id="resSeg"></div>
|
||||
<div class="lab">买家备注 <span class="h">(选填,记进留档,比如闲鱼订单号 / 昵称)</span></div>
|
||||
<input class="t" id="note" placeholder="例:闲鱼 3829… / 小明">
|
||||
<div class="sum idle" id="sum">先选皮肤、勾模板。</div>
|
||||
<div class="btns">
|
||||
<button type="button" class="btn pri big" id="go" disabled>开始渲染</button>
|
||||
<button type="button" class="btn" id="clear">清空</button>
|
||||
</div>
|
||||
<div class="prog" id="progWrap" hidden>
|
||||
<div class="bar"><i id="bar"></i></div>
|
||||
<div class="hint" id="progTxt"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" id="card3" hidden>
|
||||
<div class="step done"><span class="num">3</span><h2>出图</h2></div>
|
||||
<p class="hint"><span id="resHint"></span> 每张模板出<b>两张</b>:标准压缩(发预览 / 常规交付)+ 无压缩 16bit(客户要高清时给),两张都发过去。</p>
|
||||
<div class="res" id="res"></div>
|
||||
<div class="btns">
|
||||
<button type="button" class="btn pri" id="open">打开留档文件夹</button>
|
||||
<button type="button" class="btn" id="again">再开一单</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer>
|
||||
本工具只监听 localhost · 不联网 · 不上传 · 不需要兑换码 · 所有文件都留在你自己电脑上<br>
|
||||
<a href="#" id="quit">退出工具</a>
|
||||
</footer>
|
||||
</div>
|
||||
<div class="toast" id="toast" role="status" aria-live="polite"></div>
|
||||
|
||||
<script src="skincheck.js"></script>
|
||||
<script>
|
||||
const $=(s,r=document)=>r.querySelector(s), $$=(s,r=document)=>Array.from(r.querySelectorAll(s));
|
||||
function toast(m){const t=$('#toast');t.textContent=m;t.classList.add('show');
|
||||
clearTimeout(t._h);t._h=setTimeout(()=>t.classList.remove('show'),2600);}
|
||||
|
||||
const TEMPLATES=[
|
||||
{k:'stand', n:'站立正反', s:'正面站立 · 干净背景', c:'#6F7A90'},
|
||||
{k:'standb', n:'站立正反(虚化)', s:'同款 + 景深虚化', c:'#7C86A8'},
|
||||
{k:'wheat', n:'麦田萤火', s:'麦田 · 暖光 · 萤火', c:'#C08A2A'},
|
||||
{k:'beach', n:'海边自拍', s:'海面 · 天光', c:'#3D86C2'},
|
||||
{k:'boom', n:'不看爆炸', s:'身后爆炸 · 不回头', c:'#C9573A'},
|
||||
{k:'sakura', n:'飞跃樱花林', s:'樱花 · 动态', c:'#D0739A'},
|
||||
{k:'airship', n:'空艇巡游', s:'飞空艇 · 巡航', c:'#4E8C9C'}
|
||||
];
|
||||
/* 模板缩略图:还没有实拍预览图,先用每个模板自己的颜色 + 一个小图标顶着(以后换成真图:把 thumb 里的 svg 换成 <img>) */
|
||||
const ICON={
|
||||
stand:'<path d="M12 4a2 2 0 1 0 0 .01M9 8h6l-1 6h-4zM10 14l-1 6M14 14l1 6"/>',
|
||||
standb:'<circle cx="12" cy="12" r="8" stroke-dasharray="2 3"/><path d="M12 7a1.5 1.5 0 1 0 0 .01M10 10h4l-.7 4h-2.6zM11 14l-.6 3.5M13 14l.6 3.5"/>',
|
||||
wheat:'<path d="M12 21V8M12 8c-2-1-3-3-3-5 2 1 3 3 3 5zM12 8c2-1 3-3 3-5-2 1-3 3-3 5zM12 13c-2-1-3-3-3-5 2 1 3 3 3 5zM12 13c2-1 3-3 3-5-2 1-3 3-3 5zM18 6h.01M6 10h.01"/>',
|
||||
beach:'<circle cx="17" cy="7" r="3"/><path d="M2 16c2 0 2-1.5 4-1.5S8 16 10 16s2-1.5 4-1.5S16 16 18 16s2-1.5 4-1.5M2 20c2 0 2-1.5 4-1.5S8 20 10 20s2-1.5 4-1.5S16 20 18 20s2-1.5 4-1.5"/>',
|
||||
boom:'<path d="M12 2l2 5 5-2-2 5 5 2-5 2 2 5-5-2-2 5-2-5-5 2 2-5-5-2 5-2-2-5 5 2z"/>',
|
||||
sakura:'<path d="M12 12c-1.5-2-1.5-5 0-7 1.5 2 1.5 5 0 7zM12 12c2.4-.6 5 .9 5.8 3.1-2.4.6-5-.9-5.8-3.1zM12 12c-2.4-.6-5 .9-5.8 3.1 2.4.6 5-.9 5.8-3.1z"/><circle cx="12" cy="12" r="1"/>',
|
||||
airship:'<ellipse cx="12" cy="9" rx="9" ry="4"/><path d="M9 13l1 3h4l1-3M3 9h18M21 9l2-2M21 9l2 2"/>'
|
||||
};
|
||||
const S={skin:null,fileName:'',analysis:null,report:null,sel:[],job:null,timer:null,res:1000};
|
||||
|
||||
/* 分辨率:文件名就是它。耗时按像素数粗估(1000² ≈ 40 秒 GPU 打底) */
|
||||
const RES=[{v:1000,t:'头图标准 · 约 40 秒',sec:40},
|
||||
{v:1024,t:'约 45 秒',sec:45},
|
||||
{v:2048,t:'约 2.5 分钟',sec:150},
|
||||
{v:4096,t:'约 10 分钟',sec:600}];
|
||||
RES.forEach(r=>{
|
||||
const b=document.createElement('button'); b.type='button';
|
||||
b.innerHTML=r.v+'<small>'+r.t+'</small>';
|
||||
if(r.v===S.res) b.classList.add('on');
|
||||
b.onclick=()=>{ S.res=r.v; $$('#resSeg button').forEach(x=>x.classList.toggle('on',x===b)); syncGo(); };
|
||||
$('#resSeg').appendChild(b);
|
||||
});
|
||||
|
||||
/* ---------- 模板卡片 ---------- */
|
||||
TEMPLATES.forEach(t=>{
|
||||
const el=document.createElement('button');
|
||||
el.type='button'; el.className='tpl'; el.dataset.k=t.k; el.style.setProperty('--tone',t.c);
|
||||
el.setAttribute('aria-pressed','false');
|
||||
el.innerHTML='<div class="thumb"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">'
|
||||
+(ICON[t.k]||'')+'</svg></div><div class="meta"><div class="n"></div><div class="s"></div></div><span class="pick">✓</span><span class="ord"></span>';
|
||||
el.querySelector('.n').textContent=t.n; el.querySelector('.s').textContent=t.s;
|
||||
el.onclick=()=>{
|
||||
const i=S.sel.indexOf(t.k);
|
||||
if(i>=0) S.sel.splice(i,1); else { if(S.sel.length>=10) return toast('一次最多 10 张'); S.sel.push(t.k); }
|
||||
syncTpls(); syncGo();
|
||||
};
|
||||
$('#tpls').appendChild(el);
|
||||
});
|
||||
function syncTpls(){
|
||||
$$('#tpls .tpl').forEach(el=>{ const i=S.sel.indexOf(el.dataset.k);
|
||||
el.classList.toggle('sel',i>=0); el.setAttribute('aria-pressed',String(i>=0));
|
||||
el.querySelector('.ord').textContent=i>=0?String(i+1):''; });
|
||||
}
|
||||
|
||||
/* ---------- 皮肤上传 + 质检(复用 skincheck.js) ---------- */
|
||||
const drop=$('#drop'), fileIn=$('#file');
|
||||
drop.onclick=()=>fileIn.click();
|
||||
fileIn.onchange=e=>{ if(e.target.files[0]) loadFile(e.target.files[0]); fileIn.value=''; };
|
||||
['dragenter','dragover'].forEach(ev=>drop.addEventListener(ev,e=>{e.preventDefault();drop.classList.add('over');}));
|
||||
['dragleave','drop'].forEach(ev=>drop.addEventListener(ev,e=>{e.preventDefault();drop.classList.remove('over');}));
|
||||
drop.addEventListener('drop',e=>{ const f=e.dataTransfer.files[0]; if(f) loadFile(f); });
|
||||
/* 拖到页面别处也能收(不然浏览器会直接打开这张图、把页面换掉) */
|
||||
['dragover','drop'].forEach(ev=>window.addEventListener(ev,e=>{ if(!drop.contains(e.target)){ e.preventDefault();
|
||||
if(ev==='drop'&&e.dataTransfer.files[0]) loadFile(e.dataTransfer.files[0]); } }));
|
||||
window.addEventListener('paste',e=>{
|
||||
for(const it of (e.clipboardData||{}).items||[]){
|
||||
if(it.type.startsWith('image/')){ const f=it.getAsFile(); if(f) return loadFile(f); }
|
||||
}
|
||||
});
|
||||
|
||||
function loadFile(f){
|
||||
if(!/png$/i.test(f.name) && f.type!=='image/png') return toast('只支持 .png 皮肤文件');
|
||||
/* PNG 结构核验 —— 和网页那份是同一个 checkPngBytes(skincheck.js),防夹带 */
|
||||
const rb=new FileReader();
|
||||
rb.onload=()=>{
|
||||
let st; try{ st=checkPngBytes(new Uint8Array(rb.result)); }catch(e){ st={ok:true}; }
|
||||
if(st && st.ok===false) return toast('这张图没通过安全核验:'+st.reason);
|
||||
if(st && st.notes && st.notes.length) toast('提示:'+st.notes.join(';')+'(不影响出图)');
|
||||
const fr=new FileReader();
|
||||
fr.onload=()=>{ const im=new Image();
|
||||
im.onload=()=>runCheck(im,f.name||'粘贴的图片.png',im.width,im.height);
|
||||
im.onerror=()=>toast('这张图读不出来,换一张试试');
|
||||
im.src=fr.result; };
|
||||
fr.readAsDataURL(f);
|
||||
};
|
||||
rb.readAsArrayBuffer(f);
|
||||
}
|
||||
|
||||
function runCheck(img,name,w,h){
|
||||
const a=analyze(img,w,h);
|
||||
const rep=buildReport(a);
|
||||
S.skin=img; S.fileName=name; S.analysis=a; S.report=rep;
|
||||
|
||||
const c=$('#pv'); c.width=64; c.height=64;
|
||||
const g=c.getContext('2d'); g.imageSmoothingEnabled=false;
|
||||
g.clearRect(0,0,64,64); g.drawImage(img,0,0,64,64);
|
||||
$('#pvName').textContent=name+'('+a.origW+'×'+a.origH+')';
|
||||
$('#pvwrap').hidden=false;
|
||||
drop.classList.add('has'); $('#dropBig').textContent='换一张皮肤';
|
||||
|
||||
const box=$('#report'); box.innerHTML='';
|
||||
const row=(lv,tag,t,d)=>{
|
||||
const el=document.createElement('div'); el.className='item '+lv;
|
||||
const tg=document.createElement('span'); tg.className='tag'; tg.textContent=tag;
|
||||
const bd=document.createElement('div'); bd.className='bd';
|
||||
const tt=document.createElement('div'); tt.className='t'; tt.textContent=t;
|
||||
const dd=document.createElement('div'); dd.className='d'; dd.textContent=d;
|
||||
bd.appendChild(tt); if(d) bd.appendChild(dd); el.appendChild(tg); el.appendChild(bd); box.appendChild(el);
|
||||
};
|
||||
rep.items.forEach(it=>row(it.lv,it.tag,it.t,it.d));
|
||||
if(rep.hasBad) row('bad','不通过','这张皮肤不能直接渲','上面标了不通过的问题得先解决。请买家换一张标准皮肤。');
|
||||
syncGo();
|
||||
}
|
||||
|
||||
/* ---------- 提交 ---------- */
|
||||
function tplName(k){ const t=TEMPLATES.find(x=>x.k===k); return t?t.n:k; }
|
||||
function fmtSec(s){ return s<90 ? (Math.round(s)+' 秒') : (Math.round(s/60)+' 分钟'); }
|
||||
function syncGo(){
|
||||
const ready = !!(S.skin && S.sel.length && !(S.report&&S.report.hasBad));
|
||||
$('#go').disabled = !ready;
|
||||
$('#st1').classList.toggle('done', !!(S.skin && !(S.report&&S.report.hasBad)));
|
||||
$('#st2').classList.toggle('done', S.sel.length>0);
|
||||
const sum=$('#sum');
|
||||
if(!S.skin && !S.sel.length){ sum.className='sum idle'; sum.textContent='先选皮肤、勾模板。'; return; }
|
||||
if(S.report&&S.report.hasBad){ sum.className='sum idle'; sum.textContent='皮肤质检没通过,换一张再来。'; return; }
|
||||
if(!S.skin){ sum.className='sum idle'; sum.textContent='已勾 '+S.sel.length+' 个模板,还差皮肤。'; return; }
|
||||
if(!S.sel.length){ sum.className='sum idle'; sum.textContent='皮肤好了,再勾模板。'; return; }
|
||||
const r=RES.find(x=>x.v===S.res)||RES[0];
|
||||
sum.className='sum';
|
||||
sum.innerHTML='出 <b>'+S.sel.length+'</b> 张:'+S.sel.map(k=>tplName(k)).join('、')+' · <b>'+S.res+'px</b> · 大概 <b>'+fmtSec(r.sec*S.sel.length)+'</b>(每张另出一份无压缩)';
|
||||
}
|
||||
|
||||
$('#go').onclick=async()=>{
|
||||
if(!S.skin) return toast('先选皮肤');
|
||||
if(!S.sel.length) return toast('先勾模板');
|
||||
if(S.report&&S.report.hasBad) return toast('质检不通过,不能提交');
|
||||
$('#go').disabled=true;
|
||||
$('#progWrap').hidden=false; $('#card3').hidden=true;
|
||||
$('#bar').style.width='4%'; $('#progTxt').textContent='提交中…';
|
||||
// 皮肤转 base64 送本机接口
|
||||
const c=document.createElement('canvas');
|
||||
c.width=S.analysis.origW; c.height=S.analysis.origH;
|
||||
const g=c.getContext('2d'); g.imageSmoothingEnabled=false;
|
||||
g.drawImage(S.skin,0,0,S.analysis.origW,S.analysis.origH);
|
||||
const data=c.toDataURL('image/png');
|
||||
let st;
|
||||
try{
|
||||
st=await (await fetch('/api/render',{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({skin:data,fileName:S.fileName,templates:S.sel,res:S.res,
|
||||
arm:(S.analysis.arm&&S.analysis.arm.model)||'',note:$('#note').value.trim()})})).json();
|
||||
}catch(e){ st={ok:false,error:'连不上本机工具(是不是已经退出了?)'}; }
|
||||
if(!st.ok){ $('#go').disabled=false; $('#progWrap').hidden=true; return toast(st.error||'提交失败'); }
|
||||
S.job=st.job; poll();
|
||||
};
|
||||
|
||||
async function poll(){
|
||||
let j;
|
||||
try{ j=await (await fetch('/api/job/'+S.job)).json(); }
|
||||
catch(e){ S.timer=setTimeout(poll,3000); $('#progTxt').textContent='和本机工具断了一下,重连中…'; return; }
|
||||
const pct=Math.round(((j.current-1)/j.total)*100);
|
||||
$('#bar').style.width=Math.max(pct,j.state==='done'?100:4)+'%';
|
||||
const ahead = Math.max((j.queue_pos||1) - 1, 0);
|
||||
$('#progTxt').textContent =
|
||||
j.state==='queued' ? (ahead>0 ? ('排队中 · 前面还有 '+ahead+' 单(一张一张来,不并行)')
|
||||
: '马上开始…')
|
||||
: j.state==='running' ? ('正在渲染第 '+j.current+' / '+j.total+' 张 · '+(j.res||1000)+'px'
|
||||
+'(每张出标准 + 无压缩两张)')
|
||||
: j.state==='done' ? '全部完成' : '出错了';
|
||||
if(j.state==='running'||j.state==='queued'){ S.timer=setTimeout(poll,2000); return; }
|
||||
clearTimeout(S.timer); S.timer=null;
|
||||
$('#go').disabled=false;
|
||||
const box=$('#res'); box.innerHTML='';
|
||||
$('#card3').hidden=false;
|
||||
if(j.state==='error' && !j.results.length){
|
||||
$('#resHint').textContent='';
|
||||
const e=document.createElement('div'); e.className='errbar'; e.textContent=j.error||'渲染失败'; box.appendChild(e);
|
||||
$('#card3').scrollIntoView({behavior:'smooth',block:'start'}); return;
|
||||
}
|
||||
$('#resHint').textContent='共 '+j.results.length+' 个文件'+(j.errors&&j.errors.length?('(有 '+j.errors.length+' 张失败)'):'')+'。';
|
||||
// 按序号分组:一个模板 = 一张卡片,里面挂【标准压缩】+【无压缩 16bit】两个下载
|
||||
const groups=[];
|
||||
j.results.forEach((r,i)=>{ let g=groups.find(x=>x.seq===r.seq);
|
||||
if(!g){ g={seq:r.seq,tpl:r.tpl,sec:r.sec,tplName:tplName(r.tpl),items:[]}; groups.push(g); }
|
||||
g.items.push({i:i,r:r}); });
|
||||
groups.forEach(g=>{
|
||||
const d=document.createElement('div'); d.className='one';
|
||||
d.innerHTML='<img src="/api/file/'+S.job+'/'+g.items[0].i+'?t='+Date.now()+'" alt="" loading="lazy">'
|
||||
+'<div class="cap"><b></b><span></span><div class="dls"></div></div>';
|
||||
d.querySelector('b').textContent=g.tplName||g.tpl;
|
||||
d.querySelector('span').textContent='序号 '+g.seq+' · '+(g.items[0].r.res||1000)+'px · 渲染 '+g.sec+' 秒';
|
||||
const dl=d.querySelector('.dls');
|
||||
g.items.forEach(it=>{
|
||||
const a=document.createElement('a');
|
||||
a.href='/api/file/'+S.job+'/'+it.i; a.setAttribute('download',it.r.name);
|
||||
a.textContent='下载 '+it.r.kind; dl.appendChild(a);
|
||||
});
|
||||
box.appendChild(d);
|
||||
});
|
||||
if(j.errors&&j.errors.length){
|
||||
const e=document.createElement('div'); e.className='errbar'; e.textContent='失败:'+j.errors.join('\n');
|
||||
box.appendChild(e);
|
||||
}
|
||||
S.job=j.id; toast('出图完成');
|
||||
$('#card3').scrollIntoView({behavior:'smooth',block:'start'});
|
||||
}
|
||||
|
||||
$('#quit').onclick=async e=>{ e.preventDefault();
|
||||
if(!confirm('关闭本机开单工具?(渲染机不受影响,还会继续接网页的单)')) return;
|
||||
await fetch('/api/quit',{method:'POST'}).catch(()=>{});
|
||||
document.body.innerHTML='<div class="wrap" style="padding:80px 20px;text-align:center;color:var(--dim)">工具已关闭,可以关掉这个页面了。</div>';
|
||||
};
|
||||
$('#open').onclick=async()=>{
|
||||
const r=await (await fetch('/api/openfolder',{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({job:S.job})})).json();
|
||||
toast(r.ok?'已打开文件夹':(r.error||'打不开'));
|
||||
};
|
||||
/* 再开一单:模板和备注清掉,皮肤留着(同一个买家常常要再加几张) */
|
||||
$('#again').onclick=()=>{ S.sel=[]; syncTpls();
|
||||
$('#note').value=''; $('#card3').hidden=true; $('#progWrap').hidden=true; syncGo();
|
||||
window.scrollTo({top:0,behavior:'smooth'}); };
|
||||
/* 清空:皮肤、模板、备注全清 */
|
||||
$('#clear').onclick=()=>{ if(S.timer) return toast('正在渲染,等它出完再清');
|
||||
S.skin=null; S.fileName=''; S.analysis=null; S.report=null; S.sel=[]; syncTpls();
|
||||
$('#note').value=''; $('#pvwrap').hidden=true; $('#report').innerHTML='';
|
||||
drop.classList.remove('has'); $('#dropBig').textContent='点击选择皮肤文件';
|
||||
$('#progWrap').hidden=true; syncGo(); };
|
||||
$('#copyTerms').onclick=()=>{ const t=$('#termsTxt').textContent;
|
||||
if(navigator.clipboard&&window.isSecureContext) navigator.clipboard.writeText(t).then(()=>toast('说明已复制'),()=>toast('复制失败,手动选吧'));
|
||||
else { const a=document.createElement('textarea'); a.value=t; a.style.position='fixed'; a.style.opacity='0'; document.body.appendChild(a); a.select();
|
||||
try{ document.execCommand('copy'); toast('说明已复制'); }catch(e){ toast('复制失败,手动选吧'); } a.remove(); } };
|
||||
|
||||
/* ---------- 体检 ---------- */
|
||||
(async()=>{
|
||||
let a;
|
||||
try{ a=await (await fetch('/api/status')).json(); }
|
||||
catch(e){ $('#health').textContent='连不上'; $('#health').className='badge bad'; return; }
|
||||
const bad=[];
|
||||
if(!a.blender_ok) bad.push('没找到 blender.exe —— 请在 config.json 里填 blender 路径');
|
||||
if(!a.make_order_ok) bad.push('没找到渲染脚本 make_order.py('+a.make_order+')');
|
||||
if(a.missing.length) bad.push('缺 '+a.missing.length+' 个模板文件:'+a.missing.join('、'));
|
||||
const ok = a.blender_ok && !a.missing.length && a.make_order_ok;
|
||||
$('#health').textContent = ok ? '就绪' : '有问题';
|
||||
$('#health').className = 'badge '+(ok?'ok':'bad');
|
||||
if(bad.length){
|
||||
const w=document.createElement('div'); w.className='warnbar';
|
||||
w.innerHTML='<b>先看这里:</b><br>'+bad.map(x=>x.replace(/[&<>]/g,c=>({'&':'&','<':'<','>':'>'}[c]))).join('<br>');
|
||||
$('#syswarn').appendChild(w);
|
||||
}
|
||||
})();
|
||||
syncGo();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,651 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
商单渲染流程自动化(宿主 Windows 用)—— 跑起来 0 token
|
||||
|
||||
金钻 2026-09-19 原话:
|
||||
「如果方便的话可以直接写个脚本,到时候如果不需要修改的话,直接按流程,
|
||||
复制所需工程到商单文件夹往后补一个新的编号。皮肤也放进去。
|
||||
然后根据皮肤粗细臂去选择对应集合,渲染出图」
|
||||
|
||||
一条命令完成:
|
||||
1. 成品文件夹用成品名(`飞跃樱花林` / `飞跃樱花林1080`),重名自动加 -2
|
||||
2. 新建成品文件夹;工程复制到**临时目录**(原文件不动,渲完就删)
|
||||
3. 皮肤先放进成品文件夹
|
||||
4. 自动判定皮肤是【粗臂 classic 4px】还是【细臂 slim 3px】
|
||||
5. 按判定切换场景里的 粗臂 / 细臂 集合(view layer exclude)
|
||||
6. 换皮肤贴图(pack 打包)
|
||||
7. 渲染出图 → 017\\飞跃樱花林.png + 017\\飞跃樱花林无压缩版.png
|
||||
(默认 1000 不带数字;换分辨率才带,如 飞跃樱花林1080.png。越高越慢)
|
||||
8. 写 _CHANGES.md 与 _make_order.log
|
||||
|
||||
用法:
|
||||
blender.exe -b --factory-startup --python make_order.py -- ^
|
||||
--template "<ARCHIVE_DIR>" ^
|
||||
--skin "<WIN-PATH>" ^
|
||||
--orders-dir "<ARCHIVE_DIR>" ^
|
||||
[--block-texture "<WIN-PATH>"] [--num 017] [--out-name 麦田萤火] ^
|
||||
[--res 2048] [--out-dir "...\\商单\\麦田萤火"] [--keep-blend] ^
|
||||
[--no-uncompressed] [--no-render] [--dry-run]
|
||||
|
||||
要点(踩过的坑,别改回去):
|
||||
* 必须 `-b --factory-startup` —— 宿主 Blender 装了 MMD 系 addon,不 factory-startup
|
||||
时会重复注册崩(ValueError: register_class(...): already registered)。
|
||||
* 但 factory-startup 会丢掉用户的 Cycles GPU 偏好 → 掉回 CPU,**慢 10 倍**
|
||||
(实测 1000×1000 / 180 samples:GPU 37.4s vs CPU 378.9s)。
|
||||
所以脚本里 setup_render_device() 显式切 GPU,别删。
|
||||
* 判臂型用 bpy.data.images 读 alpha,不依赖 PIL;注意 img.pixels 是 **bottom-up**,
|
||||
取像素必须翻转 y。
|
||||
* 渲染耗时长(CPU 下 6 分钟+),从我这边跑要走后台 + 轮询日志,别用前台 timeout。
|
||||
* **工程文件不保留**(2026-09-30 金钻):一份 .blend 二十多兆,攒起来受不住。
|
||||
工程复制到 tempfile.mkdtemp() 的临时目录,渲完立刻删;`--keep-blend` 只在调试时用。
|
||||
成品文件夹里只有:皮肤 + 成图 + 订单信息.json。
|
||||
* **臂集合名/层级各模板都不一样**(实测三种):1~4 顶层 `粗臂`/`细臂`;
|
||||
5~6 嵌在 `Collection` 里叫 `Player Wide Rig`/`Player Slim Rig`;
|
||||
7 顶层 `01_角色_粗臂`/`02_角色_细臂`。
|
||||
→ find_layer() 递归整棵树 + 中英双认(WIDE_KEYS/SLIM_KEYS)。
|
||||
写死任一种都会让模板 exit 5 渲不出来(5/6/7 全中过)。
|
||||
* 皮肤 `img.pack()` 必须在改 filepath **之前** —— 工程现在在临时目录,
|
||||
先改路径的话 pack 会拿相对路径去 <WIN-PATH> 找源文件,报 not found。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import atexit
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import traceback
|
||||
|
||||
import bpy
|
||||
|
||||
LOGLINES = []
|
||||
|
||||
# ---- 成品命名(金钻 2026-09-30 定稿)----
|
||||
# 默认分辨率 1000 → <模板名>.png + <模板名>无压缩版.png
|
||||
# 其它分辨率 N → <模板名>N.png + <模板名>N无压缩版.png
|
||||
# 例:飞跃樱花林 在 1000 → 飞跃樱花林.png / 飞跃樱花林无压缩版.png
|
||||
# 飞跃樱花林 在 1080 → 飞跃樱花林1080.png / 飞跃樱花林1080无压缩版.png
|
||||
DEFAULT_RES = 1000
|
||||
UNC_SUFFIX = "无压缩"
|
||||
|
||||
|
||||
def out_base(out_name, res):
|
||||
"""模板名 + (非默认分辨率才带数字)"""
|
||||
res = int(res)
|
||||
return out_name if res == DEFAULT_RES else "%s%d" % (out_name, res)
|
||||
|
||||
|
||||
def make_out_dir(root, base):
|
||||
"""成品文件夹用成品名(金钻 2026-09-30):`飞跃樱花林` / `飞跃樱花林1080`。
|
||||
同名已存在就往后加 -2 / -3 —— 同一个模板被买两次不能互相覆盖。
|
||||
序号仍然记在文件夹里的 订单信息.json(好查账)。"""
|
||||
d = os.path.join(root, base)
|
||||
n = 2
|
||||
while os.path.exists(d):
|
||||
d = os.path.join(root, "%s-%d" % (base, n))
|
||||
n += 1
|
||||
os.makedirs(d, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def std_name(out_name, res):
|
||||
return out_base(out_name, res) + ".png"
|
||||
|
||||
|
||||
def unc_name(out_name, res):
|
||||
return out_base(out_name, res) + UNC_SUFFIX + ".png"
|
||||
|
||||
|
||||
def log(*a):
|
||||
s = " ".join(str(x) for x in a)
|
||||
LOGLINES.append(s)
|
||||
print("[MAKE-ORDER] " + s, flush=True)
|
||||
|
||||
|
||||
def parse_args():
|
||||
argv = sys.argv
|
||||
if "--" in argv:
|
||||
argv = argv[argv.index("--") + 1:]
|
||||
else:
|
||||
argv = []
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--template", required=True, help="干净模板 .blend 绝对路径")
|
||||
ap.add_argument("--skin", required=True, help="皮肤 png 绝对路径")
|
||||
ap.add_argument("--orders-dir", required=True, help="商单根目录绝对路径")
|
||||
ap.add_argument("--out-dir", default=None,
|
||||
help="直接指定成品文件夹(调用方用来做重名处理;给了就不再用 --num)")
|
||||
ap.add_argument("--keep-blend", action="store_true",
|
||||
help="调试用:保留临时工程文件(默认渲完就删)")
|
||||
ap.add_argument("--block-texture", default=None, help="可选:方块贴图 png")
|
||||
ap.add_argument("--num", default=None, help="手动指定商单编号(3 位)")
|
||||
ap.add_argument("--out-name", default=None, help="出图名,默认取模板名去编号前缀")
|
||||
ap.add_argument("--res", type=int, default=DEFAULT_RES,
|
||||
help="渲染分辨率。默认 1000(文件名不带数字);换别的值会写进文件名。"
|
||||
"越高越慢:1000≈40s、2048≈2.5min、4096≈10min")
|
||||
ap.add_argument("--skin-material", default=None, help="皮肤材质名(默认自动找)")
|
||||
# 金钻 2026-10-01:页面让买家手动改粗/细臂,但以前**根本没传进来** —— 永远按自动判定走,
|
||||
# 买家改了也白改。现在由渲染机按「这张皮肤」的臂型传进来(多皮肤单每张各自一个臂型)。
|
||||
ap.add_argument("--arm", default="auto", choices=["auto", "classic", "slim"],
|
||||
help="粗臂(classic)/细臂(slim);auto=按皮肤自动判定(默认)")
|
||||
ap.add_argument("--uncompressed", action=argparse.BooleanOptionalAction, default=True,
|
||||
help="输出 16bit 无压缩版(默认开;要关就 --no-uncompressed)")
|
||||
ap.add_argument("--no-render", action="store_true")
|
||||
ap.add_argument("--dry-run", action="store_true")
|
||||
return ap.parse_args(argv)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 编号 / 目录
|
||||
|
||||
def next_order_number(orders_dir, forced=None):
|
||||
if forced:
|
||||
return forced
|
||||
n = 0
|
||||
for name in os.listdir(orders_dir):
|
||||
m = re.fullmatch(r"(\d{3})", name)
|
||||
if m and os.path.isdir(os.path.join(orders_dir, name)):
|
||||
n = max(n, int(m.group(1)))
|
||||
return "%03d" % (n + 1)
|
||||
|
||||
|
||||
# ------------------------------------------------------- 皮肤臂型判定(核心)
|
||||
|
||||
def _px(img, x, y, w, h):
|
||||
"""取 (x,y) alpha,y 从左上往下数;bpy pixels 是左下起 → 翻转 y。"""
|
||||
yy = h - 1 - y
|
||||
return img.pixels[(yy * w + x) * 4 + 3]
|
||||
|
||||
|
||||
def detect_arm_model(skin_abs):
|
||||
"""读皮肤 alpha 判粗臂/细臂。返回 (model, score, notes)
|
||||
model: 'classic'(粗臂 4px) / 'slim'(细臂 3px) / 'unknown'
|
||||
依据:64x64 标准布局,右臂区 (40,16)-(55,31)。
|
||||
粗臂:每个 4x4 面填满 → 侧面行 y=25 在 x40..55 无透明列;top/bottom 面各占 4px
|
||||
细臂:每个 4x4 面只用 3x3 → 每 4px 段第 4 列透明
|
||||
"""
|
||||
notes = []
|
||||
img = bpy.data.images.load(skin_abs, check_existing=False)
|
||||
try:
|
||||
ow, oh = img.size
|
||||
# 皮肤分辨率不固定:64 是基准,128/256/512/1024…都是同一套 64 网格的整倍数放大,
|
||||
# 一律缩到 64×64 再判臂型(和下单页的判定保持完全一致)。
|
||||
if ow != oh:
|
||||
return "unknown", 0, "非正方形 %dx%d(旧版 2:1,无独立左右臂/腿)" % (ow, oh)
|
||||
if ow < 64:
|
||||
return "unknown", 0, "尺寸过小 %dx%d" % (ow, oh)
|
||||
if ow != 64:
|
||||
img.scale(64, 64)
|
||||
w, h = img.size
|
||||
classic = 0
|
||||
slim = 0
|
||||
|
||||
# 判据1:侧面行 y=25,x=40..55 的透明列数
|
||||
nt = sum(1 for x in range(40, 56) if _px(img, x, 25, w, h) == 0.0)
|
||||
if nt >= 2:
|
||||
slim += 1
|
||||
else:
|
||||
classic += 1
|
||||
notes.append("side-row(y25) transparent cols=%d" % nt)
|
||||
|
||||
# 判据2/3:top/bottom 面第 4 列是否存在(细臂该列为空)
|
||||
for (x, lab) in ((47, "top-face-4th"), (51, "bottom-face-4th")):
|
||||
if _px(img, x, 17, w, h) == 0.0:
|
||||
slim += 1
|
||||
notes.append("%s alpha=0" % lab)
|
||||
else:
|
||||
classic += 1
|
||||
notes.append("%s opaque" % lab)
|
||||
|
||||
# 判据4:y16..19 里 x44..51 的有效列数(粗臂 8,细臂 6)
|
||||
cols = sum(1 for x in range(44, 52)
|
||||
if any(_px(img, x, y, w, h) > 0 for y in range(16, 20)))
|
||||
if cols <= 6:
|
||||
slim += 1
|
||||
else:
|
||||
classic += 1
|
||||
notes.append("face-active cols=%d/8" % cols)
|
||||
|
||||
model = "slim" if slim > classic else "classic"
|
||||
return model, max(slim, classic), "; ".join(notes)
|
||||
finally:
|
||||
try:
|
||||
bpy.data.images.remove(img)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ------------------------------------------------------------- 场景操作
|
||||
|
||||
def find_skin_node(mat_name=None, skin_abs=None):
|
||||
"""找皮肤图像纹理节点。返回 (material, node) 或 (None, None)
|
||||
|
||||
⚠️ 2026-10-01 踩坑(金钻报:「空艇那张皮肤还是默认皮肤材质」):
|
||||
老逻辑是「名字里带 skin/皮肤 就选,否则**拿第一个贴图节点**」。
|
||||
空艇模板里第一个贴图节点不是角色皮肤(大概是环境/天空),于是换了个寂寞 ——
|
||||
角色身上还是模板自带的默认皮肤,而"站立正反"因为节点名带 skin 所以正常。
|
||||
新逻辑:**给每个候选节点打分挑最高的**,并把候选全打日志(下次出问题一眼看得出)。
|
||||
分:材质/图片名带 skin|皮肤 +3;图片尺寸 == 上传皮肤的尺寸 +2;≤128 的小图 +1
|
||||
都不沾(全是大背景图)→ 才退回第一个,并明确警告。
|
||||
"""
|
||||
pairs = []
|
||||
for m in bpy.data.materials:
|
||||
if not m.use_nodes or not m.node_tree:
|
||||
continue
|
||||
for n in m.node_tree.nodes:
|
||||
if n.type == "TEX_IMAGE" and n.image is not None:
|
||||
pairs.append((m, n))
|
||||
if not pairs:
|
||||
return None, None
|
||||
if mat_name:
|
||||
for m, n in pairs:
|
||||
if m.name == mat_name:
|
||||
log("皮肤节点 → 按参数指定材质 %s" % m.name)
|
||||
return m, n
|
||||
log("⚠️ 指定材质 %r 没找到,改走自动打分" % mat_name)
|
||||
|
||||
def size_of(img):
|
||||
try:
|
||||
return (int(img.size[0]), int(img.size[1]))
|
||||
except Exception:
|
||||
return (0, 0)
|
||||
|
||||
want = (0, 0)
|
||||
if skin_abs:
|
||||
try:
|
||||
tmp = bpy.data.images.load(skin_abs, check_existing=False)
|
||||
want = size_of(tmp)
|
||||
except Exception:
|
||||
want = (0, 0)
|
||||
|
||||
board = []
|
||||
for m, n in pairs:
|
||||
nm = (m.name or "") + " " + (n.image.name or "") + " " + (n.image.filepath or "")
|
||||
low = nm.lower()
|
||||
s = 0
|
||||
if "skin" in low or "皮肤" in nm:
|
||||
s += 3
|
||||
w, h = size_of(n.image)
|
||||
if want != (0, 0) and (w, h) == want:
|
||||
s += 2
|
||||
if 0 < w <= 128 and 0 < h <= 128:
|
||||
s += 1
|
||||
board.append((s, m, n, (w, h)))
|
||||
board.sort(key=lambda x: -x[0])
|
||||
log("贴图节点候选:%s" % ";".join(
|
||||
"%s/%s %sx%s 分=%d" % (mm.name, (nn.image.name or "?"), wh[0], wh[1], sc)
|
||||
for sc, mm, nn, wh in board))
|
||||
best = board[0]
|
||||
if best[0] == 0:
|
||||
log("⚠️ 没有节点沾『皮肤』特征(全是大图?) → 按第一个来,可能渲出默认皮肤")
|
||||
# ⭐ 2026-10-01:**同分的全都要换**。空艇模板里有「角色皮肤_粗臂 / 角色皮肤_细臂」
|
||||
# 两个皮肤材质(模板作者自己那套工作皮肤),只换排第一的那个 → 用细臂集合渲染时
|
||||
# 角色身上还是模板自带的深褐色皮肤(金钻报的"还是默认皮肤"就是这原因)。
|
||||
# 只认"最高分"这一档,是为了不误伤 64x64 的杂图(那张模板里还有床 blue/purple,
|
||||
# 同尺寸但名字不含 skin,分更低 → 不会被换)。
|
||||
picked = [x for x in board if x[0] == best[0]]
|
||||
log("皮肤节点 → 选中 %d 个(分=%d):%s"
|
||||
% (len(picked), best[0], "、".join(x[1].name + "/" + x[2].name for x in picked)))
|
||||
return picked
|
||||
|
||||
|
||||
def swap_image(node, new_abs, rel_to_blend):
|
||||
"""给图像纹理节点换图并打包。
|
||||
|
||||
⚠️ 顺序不能反:**必须先 pack() 再改 filepath**。
|
||||
先改 filepath 的话,Blender 会拿那个相对路径去找源文件;工程一旦不在
|
||||
皮肤旁边(现在工程走临时目录),就会报
|
||||
RuntimeError: Unable to pack file, source path '<WIN_DIR>' not found
|
||||
(2026-09-30 实踩:`//_assets/` 是相对 .blend 所在目录解析的,
|
||||
.blend 搬去 temp 后就不指向皮肤了。)
|
||||
"""
|
||||
old = node.image
|
||||
img = bpy.data.images.load(new_abs, check_existing=False)
|
||||
try:
|
||||
img.pack() # 此刻 filepath 还是绝对路径,找得到源文件
|
||||
except Exception as e:
|
||||
log("⚠️ pack 失败(皮肤仍能用于本次渲染,只是工程不自包含): %r" % e)
|
||||
img.filepath = rel_to_blend # 已打包,路径只剩记录意义
|
||||
node.image = img
|
||||
node.interpolation = "Closest"
|
||||
try:
|
||||
node.image.colorspace_settings.name = "sRGB"
|
||||
except Exception:
|
||||
pass
|
||||
if old is not None and old.users == 0:
|
||||
try:
|
||||
bpy.data.images.remove(old)
|
||||
except Exception:
|
||||
pass
|
||||
return img
|
||||
|
||||
|
||||
# 粗臂/细臂集合在各模板里叫什么,都不一定 —— 2026-09-30 实测三种:
|
||||
# 1~4 :顶层 `粗臂` / `细臂`
|
||||
# 5~6 :**嵌在 `Collection` 里**,叫 `Player Wide Rig` / `Player Slim Rig`(英文)
|
||||
# 7 :顶层 `01_角色_粗臂` / `02_角色_细臂`
|
||||
# 所以判定必须 ① 递归整棵树 ② 中英双认。写死任何一种都会漏。
|
||||
WIDE_KEYS = ("粗臂", "wide rig", "wide_rig", "wide-rig")
|
||||
SLIM_KEYS = ("细臂", "slim rig", "slim_rig", "slim-rig")
|
||||
|
||||
|
||||
def find_layer(root, keys):
|
||||
"""在**整棵**集合树里找名字命中 keys 的层(广度优先,先浅后深)。
|
||||
|
||||
广度优先很重要:1~4 的顶层 `粗臂` 里还嵌着一个 `Player Wide Rig`,
|
||||
先命中外层才是对的(切外层等于整体切换)。
|
||||
"""
|
||||
queue = [root]
|
||||
while queue:
|
||||
cur = queue.pop(0)
|
||||
for ch in cur.children:
|
||||
low = ch.name.lower()
|
||||
if any(k.lower() in low for k in keys):
|
||||
return ch
|
||||
queue.append(ch)
|
||||
return None
|
||||
|
||||
|
||||
def set_arm_rig(model):
|
||||
"""按臂型切换粗臂/细臂。返回 (ok, msg)。
|
||||
|
||||
⚠️ **找不到不是错误**:真遇到既没中文也没英文臂集合的模板,
|
||||
说明那套模板本来就只有一套角色、不需要切 —— 这种情况要放行继续渲染。
|
||||
(早先版本直接 return False,导致 5/6/7 三个模板全部 exit 5 渲不出来。)
|
||||
"""
|
||||
lc = bpy.context.view_layer.layer_collection
|
||||
wide = find_layer(lc, WIDE_KEYS)
|
||||
slim = find_layer(lc, SLIM_KEYS)
|
||||
if wide is None and slim is None:
|
||||
return True, "此模板没有粗臂/细臂集合,跳过切臂型(按单角色渲)"
|
||||
if wide is not None:
|
||||
wide.exclude = (model != "classic")
|
||||
if slim is not None:
|
||||
slim.exclude = (model != "slim")
|
||||
return True, "粗臂[%s].exclude=%s / 细臂[%s].exclude=%s" % (
|
||||
wide.name if wide else "缺", wide.exclude if wide else "-",
|
||||
slim.name if slim else "缺", slim.exclude if slim else "-")
|
||||
|
||||
|
||||
def visible_armatures():
|
||||
out = []
|
||||
for o in bpy.data.objects:
|
||||
if o.type == "ARMATURE":
|
||||
try:
|
||||
if o.visible_get():
|
||||
out.append(o.name)
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def setup_render_device():
|
||||
"""--factory-startup 不加载用户偏好 → Cycles 会掉回 CPU(慢 10 倍)。
|
||||
这里显式把渲染设备切到 GPU。返回描述串。"""
|
||||
sc = bpy.context.scene
|
||||
info = []
|
||||
try:
|
||||
if not hasattr(sc, "cycles"):
|
||||
return "no-cycles"
|
||||
sc.cycles.device = "GPU"
|
||||
addon = bpy.context.preferences.addons.get("cycles")
|
||||
if addon is None:
|
||||
return "GPU 已设但找不到 cycles 偏好面板(可能仍走 CPU)"
|
||||
cp = addon.preferences
|
||||
for dt in ("OPTIX", "CUDA", "HIP", "ONEAPI"):
|
||||
try:
|
||||
cp.compute_device_type = dt
|
||||
info.append("type=%s" % dt)
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
cp.get_devices()
|
||||
used = []
|
||||
for d in cp.devices:
|
||||
if d.type != "CPU":
|
||||
d.use = True
|
||||
used.append(d.name)
|
||||
if not used:
|
||||
for d in cp.devices:
|
||||
d.use = True
|
||||
info.append("devices=%s" % (", ".join(used) if used else "CPU-only"))
|
||||
except Exception as e:
|
||||
info.append("设置失败:%r" % e)
|
||||
return "; ".join(info)
|
||||
|
||||
|
||||
def render_to(out_dir, out_name, res, do_render=True, uncompressed=False):
|
||||
sc = bpy.context.scene
|
||||
sc.render.resolution_x = res
|
||||
sc.render.resolution_y = res
|
||||
sc.render.resolution_percentage = 100
|
||||
sc.render.image_settings.file_format = "PNG"
|
||||
dev = setup_render_device()
|
||||
log("渲染设备 %s" % dev)
|
||||
target = os.path.join(out_dir, out_name + ".png")
|
||||
sc.render.filepath = target
|
||||
if not do_render:
|
||||
return target, False
|
||||
t0 = time.time()
|
||||
bpy.ops.render.render(write_still=True)
|
||||
dt = time.time() - t0
|
||||
# compositor 若带 File Output,可能写到别处;兜底找最新 png
|
||||
if not os.path.exists(target):
|
||||
cands = [f for f in os.listdir(out_dir) if f.lower().endswith(".png")]
|
||||
if cands:
|
||||
newest = max(cands, key=lambda f: os.path.getmtime(os.path.join(out_dir, f)))
|
||||
target = os.path.join(out_dir, newest)
|
||||
unc = None
|
||||
if uncompressed:
|
||||
unc = os.path.join(out_dir, out_name + UNC_SUFFIX + ".png")
|
||||
ok = False
|
||||
# 先试「从已渲好的 Render Result 直接另存」—— 省掉一次完整渲染(一张约 37s)
|
||||
try:
|
||||
sc.render.image_settings.file_format = "PNG"
|
||||
sc.render.image_settings.color_depth = "16"
|
||||
sc.render.image_settings.compression = 0
|
||||
rr = bpy.data.images.get("Render Result")
|
||||
if rr is not None:
|
||||
rr.save_render(filepath=unc, scene=sc)
|
||||
ok = os.path.exists(unc) and os.path.getsize(unc) > 1024
|
||||
except Exception as e:
|
||||
log("无压缩版直接另存失败,回退到重渲: %r" % e)
|
||||
if not ok:
|
||||
# 兜底:老老实实再渲一遍(慢一倍,但保证有图)
|
||||
try:
|
||||
sc.render.filepath = unc
|
||||
bpy.ops.render.render(write_still=True)
|
||||
ok = os.path.exists(unc) and os.path.getsize(unc) > 1024
|
||||
except Exception as e:
|
||||
log("无压缩版重渲也失败: %r" % e)
|
||||
log("无压缩版 %s %s" % ("OK" if ok else "FAIL", unc))
|
||||
if not ok:
|
||||
unc = None
|
||||
return target, dt, unc
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- main
|
||||
|
||||
def main():
|
||||
a = parse_args()
|
||||
t_start = time.time()
|
||||
|
||||
for p, lab in ((a.template, "template"), (a.skin, "skin"), (a.orders_dir, "orders-dir")):
|
||||
if not os.path.exists(p):
|
||||
log("FATAL %s 不存在: %s" % (lab, p))
|
||||
return 2
|
||||
|
||||
tpl_name = os.path.basename(a.template)
|
||||
blend_name = re.sub(r"^\d+", "", os.path.splitext(tpl_name)[0]) or os.path.splitext(tpl_name)[0]
|
||||
out_name = a.out_name or blend_name
|
||||
base = out_base(out_name, a.res)
|
||||
|
||||
# 成品文件夹用成品名(模板名[+分辨率]);重名加 -2。
|
||||
# 工程文件不放这里 —— 走临时目录,渲完就删(金钻:不保留工程文件,避免累计拖慢)。
|
||||
if a.out_dir:
|
||||
order_dir = a.out_dir
|
||||
os.makedirs(order_dir, exist_ok=True)
|
||||
num = os.path.basename(order_dir)
|
||||
elif a.num:
|
||||
num = a.num
|
||||
order_dir = os.path.join(a.orders_dir, num)
|
||||
os.makedirs(order_dir, exist_ok=True)
|
||||
else:
|
||||
order_dir = make_out_dir(a.orders_dir, base)
|
||||
num = os.path.basename(order_dir)
|
||||
log("编号 %s" % num)
|
||||
log("成品目录 %s" % order_dir)
|
||||
log("模板 %s" % tpl_name)
|
||||
log("出图名 %s" % base)
|
||||
|
||||
if a.dry_run:
|
||||
log("DRY-RUN 只做目录/复制/判定,不改场景不渲染")
|
||||
|
||||
# --- 1) 临时工程目录(每次一份全新副本;渲完删掉)---
|
||||
work = tempfile.mkdtemp(prefix="ys_order_%s_" % re.sub(r"\W+", "_", base))
|
||||
if not a.keep_blend:
|
||||
# ⚠️ 工程文件不保留(金钻:一份 .blend 二十多兆,攒起来受不住)。
|
||||
# 任何返回路径都要清掉 —— atexit 兜底,正常结束前再显式删一次。
|
||||
atexit.register(shutil.rmtree, work, True)
|
||||
dst_blend = os.path.join(work, tpl_name)
|
||||
shutil.copy2(a.template, dst_blend)
|
||||
log("临时工程 %s(渲完删除)" % dst_blend)
|
||||
|
||||
# --- 2) 素材 ---
|
||||
# ⚠️ 皮肤**先放进成品文件夹**(金钻 2026-09-30):渲染失败也留得下素材
|
||||
skin_abs = os.path.join(order_dir, os.path.basename(a.skin))
|
||||
if not os.path.exists(skin_abs) or os.path.abspath(skin_abs) != os.path.abspath(a.skin):
|
||||
shutil.copy2(a.skin, skin_abs)
|
||||
log("皮肤 → %s" % skin_abs)
|
||||
block_abs = None
|
||||
if a.block_texture and os.path.exists(a.block_texture):
|
||||
block_abs = os.path.join(order_dir, os.path.basename(a.block_texture))
|
||||
if not os.path.exists(block_abs):
|
||||
shutil.copy2(a.block_texture, block_abs)
|
||||
log("方块贴图 → %s" % block_abs)
|
||||
|
||||
# --- 3) 臂型判定 ---
|
||||
model, score, notes = detect_arm_model(skin_abs)
|
||||
log("臂型判定 %s (票数 %d) | %s" % (model.upper(), score, notes))
|
||||
if a.arm != "auto" and a.arm != model:
|
||||
# 指定优先:买家/金钻在页面上手动改过就听他的(自动判定只写进日志备查)
|
||||
log("臂型指定 %s(自动判定是 %s)→ 按指定的走" % (a.arm.upper(), model.upper()))
|
||||
model = a.arm
|
||||
if model == "unknown":
|
||||
log("FATAL 皮肤尺寸不支持,无法判定臂型")
|
||||
return 3
|
||||
|
||||
if a.dry_run:
|
||||
log("DRY-RUN 结束,未开 Blender 场景。耗时 %.1fs" % (time.time() - t_start))
|
||||
_write_log(order_dir, num, model, notes, a, out_name, None)
|
||||
return 0
|
||||
|
||||
# --- 4) 打开副本,改场景 ---
|
||||
bpy.ops.wm.open_mainfile(filepath=dst_blend)
|
||||
log("已打开 %s" % dst_blend)
|
||||
|
||||
picked = find_skin_node(a.skin_material, skin_abs)
|
||||
if not picked:
|
||||
log("FATAL 场景里找不到可用的图像纹理节点")
|
||||
return 4
|
||||
rel = "//" + os.path.basename(skin_abs) # 图片已 pack,路径仅作记录
|
||||
# ⚠️ 2026-10-01 实踩:一开始写成"每个节点各 load+pack 一次",空艇这种双皮肤材质模板
|
||||
# 直接让 Blender 崩掉(退出码 9)。正确做法是**只加载打包一次**,多个节点共用同一张图。
|
||||
try:
|
||||
img = bpy.data.images.load(skin_abs, check_existing=False)
|
||||
try:
|
||||
img.pack() # 此刻 filepath 还是绝对路径,找得到源文件
|
||||
except Exception as e:
|
||||
log("⚠️ pack 失败(皮肤仍能用于本次渲染,只是工程不自包含): %r" % e)
|
||||
img.filepath = rel # 已打包,路径只剩记录意义
|
||||
# ⚠️ board 里每项是**四元组** (分数, 材质, 节点, 尺寸) ——
|
||||
# 写成 `for mat, node in picked` 会 ValueError: too many values to unpack
|
||||
# (2026-10-01 实踩:空艇+站立两个模板全因此渲染失败,退出码 4)
|
||||
for _sc, mat, node, _wh in picked:
|
||||
node.image = img
|
||||
log("换皮肤 材质=%s 节点=%s → %s(已打包)" % (mat.name, node.name, rel))
|
||||
except Exception as e:
|
||||
log("FATAL 换皮肤失败:%r" % e)
|
||||
return 4
|
||||
|
||||
ok, msg = set_arm_rig(model)
|
||||
log("选集合 %s | %s" % ("OK" if ok else "FAIL", msg))
|
||||
if not ok: # 现在只有"真找不到"才会走到这(正常模板不会)
|
||||
return 5
|
||||
log("可见骨架 %s" % ", ".join(visible_armatures()))
|
||||
|
||||
log("工程 不保存(渲完随临时目录一起删)")
|
||||
|
||||
# --- 5) 渲染 ---
|
||||
# 成品命名见文件顶部 out_base():默认 1000 不带数字,其它分辨率带数字。
|
||||
target, dt, unc = render_to(order_dir, base, a.res,
|
||||
do_render=not a.no_render,
|
||||
uncompressed=a.uncompressed)
|
||||
# 渲完立刻删工程:别把 20 多兆的 .blend 留在盘上
|
||||
if a.keep_blend:
|
||||
log("临时工程 保留(--keep-blend):%s" % work)
|
||||
else:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
log("临时工程 已删除(不保留 .blend)")
|
||||
if a.no_render:
|
||||
unc = None
|
||||
log("跳过渲染(--no-render)")
|
||||
else:
|
||||
log("渲染完成 %s (%.1fs)" % (target, dt if isinstance(dt, float) else 0))
|
||||
log("成品 %s + %s" % (std_name(out_name, a.res), unc_name(out_name, a.res)))
|
||||
|
||||
_write_log(order_dir, num, model, notes, a, out_name, target)
|
||||
log("全部完成 耗时 %.1fs" % (time.time() - t_start))
|
||||
return 0
|
||||
|
||||
|
||||
def _write_log(order_dir, num, model, notes, a, out_name, target):
|
||||
stamp = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
body = [
|
||||
"# 商单 %s —— 自动生成(make_order.py)" % num,
|
||||
"",
|
||||
"生成时间:%s" % stamp,
|
||||
"",
|
||||
"## 输入",
|
||||
"- 模板:`%s`" % a.template,
|
||||
"- 皮肤:`%s`" % os.path.basename(a.skin),
|
||||
"- 方块贴图:%s" % (os.path.basename(a.block_texture) if a.block_texture else "(无)"),
|
||||
"",
|
||||
"## 自动判定",
|
||||
"- **皮肤臂型:%s**(%s)" % (model.upper(), notes),
|
||||
"- 集合切换:%s" % ("粗臂" if model == "classic" else "细臂"),
|
||||
"",
|
||||
"## 输出",
|
||||
"- 工程:`%s`" % os.path.basename(a.template),
|
||||
"- 出图:`%s`%s" % (std_name(out_name, a.res),
|
||||
("、`%s`" % unc_name(out_name, a.res)) if target else ""),
|
||||
"",
|
||||
"## 说明",
|
||||
"皮肤臂型判定依据(64x64 标准布局,右臂区 40..55 / 16..31):",
|
||||
"- 侧面行 y=25 在 x40..55 的透明列数:细臂每 4px 段留 1 列空 → ≥2 列透明",
|
||||
"- top/bottom 面第 4 列(x=47 / x=51):细臂该列为空",
|
||||
"- y16..19 中 x44..51 的有效列数:粗臂 8 列,细臂 6 列",
|
||||
"四项投票多数决;票数接近时请人工复核。",
|
||||
"",
|
||||
"---",
|
||||
"",
|
||||
"### 运行日志",
|
||||
"",
|
||||
"```",
|
||||
] + LOGLINES + ["```", ""]
|
||||
try:
|
||||
with open(os.path.join(order_dir, "_CHANGES.md"), "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(body))
|
||||
with open(os.path.join(order_dir, "_make_order.log"), "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(LOGLINES) + "\n")
|
||||
except Exception as e:
|
||||
print("write log failed: %r" % e)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
log("FATAL 未捕获异常")
|
||||
sys.exit(9)
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
cd /d %~dp0
|
||||
start "ys_local" /min "__PYTHON__" "%~dp0ys_local.py"
|
||||
exit
|
||||
@@ -0,0 +1,2 @@
|
||||
@echo off
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0pack_archive.ps1"
|
||||
@@ -0,0 +1,53 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 打包留档 —— 一键把「在线订单」压成带日期的 zip,方便传网盘
|
||||
# ⚠️ 本文件含中文,必须存成 UTF-8 **带 BOM**(PowerShell 5.1 不认无 BOM 的 UTF-8)
|
||||
param([switch]$NoPause) # -NoPause:非交互场景(远程测试)用
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$ARCH = '<ARCHIVE_DIR>'
|
||||
$OUT = '<ARCHIVE_DIR>'
|
||||
$KEEP = 3 # 只留最近 3 个包,别把盘撑满
|
||||
|
||||
if (-not (Test-Path $ARCH)) { Write-Host "找不到留档目录:$ARCH"; exit 1 }
|
||||
New-Item -ItemType Directory -Force -Path $OUT | Out-Null
|
||||
|
||||
# 先算大小,让金钻心里有数
|
||||
$files = @(Get-ChildItem -Path $ARCH -Recurse -File -ErrorAction SilentlyContinue)
|
||||
if ($files.Count -eq 0) { Write-Host "留档目录还是空的,没有要打包的。"; exit 0 }
|
||||
$mb = [math]::Round((($files | Measure-Object -Property Length -Sum).Sum)/1MB, 1)
|
||||
|
||||
$stamp = Get-Date -Format 'yyyyMMdd_HHmmss'
|
||||
$zip = Join-Path $OUT ("在线订单_$stamp.zip")
|
||||
|
||||
Write-Host "准备打包:$($files.Count) 个文件 / $mb MB"
|
||||
Write-Host "输出:$zip"
|
||||
Write-Host ""
|
||||
|
||||
# ⚠️ PNG 本身已是压缩数据,再压省不了多少,用 Optimal 纯烧时间(实测 35MB 花了 4 分半)。
|
||||
# Fastest 快得多,体积几乎一样 —— 金钻 9-30:「压缩率不高的话就亏」。
|
||||
$t0 = Get-Date
|
||||
Compress-Archive -Path $ARCH -DestinationPath $zip -CompressionLevel Fastest -Force
|
||||
$sec = [math]::Round(((Get-Date) - $t0).TotalSeconds, 1)
|
||||
|
||||
$zmb = [math]::Round((Get-Item $zip).Length/1MB, 1)
|
||||
$ratio = if ($mb -gt 0) { [math]::Round(100*$zmb/$mb) } else { 0 }
|
||||
$saved = if ($mb -gt 0) { [math]::Round(100 - $ratio) } else { 0 }
|
||||
Write-Host "打包完成:$zmb MB(原 $mb MB,省 $saved%) 用了 $sec 秒"
|
||||
if ($saved -lt 15) {
|
||||
Write-Host " ⚠️ 这次省得不多 —— 图本来就是压缩过的。"
|
||||
Write-Host " 打包主要是为了**把一堆文件变成一个**,方便整个拖网盘。"
|
||||
}
|
||||
|
||||
# 清老包,只留最近 KEEP 个
|
||||
$old = @(Get-ChildItem -Path $OUT -Filter '在线订单_*.zip' |
|
||||
Sort-Object LastWriteTime -Descending | Select-Object -Skip $KEEP)
|
||||
foreach ($f in $old) { Write-Host "清掉旧包:$($f.Name)"; Remove-Item $f.FullName -Force }
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "把这个文件拖进网盘就行 —— 上面那行就是路径:"
|
||||
Write-Host $zip
|
||||
Write-Host ""
|
||||
if (-not $NoPause) {
|
||||
Write-Host "按任意键关闭…"
|
||||
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
@echo off
|
||||
cd /d %~dp0
|
||||
rem 金钻工坊 · 开单后台(局域网 8081)。用 pythonw 起,不留黑框;
|
||||
rem --open = 顺便把浏览器打开;要停就点「开单后台-停止」。
|
||||
rem ⚠️ 不要在这里加 timeout —— 通过 SSH 跑时 timeout.exe 会因为「输入重定向不支持」报错退出(2026-09-30 实踩)。
|
||||
start "ys_admin" /min "__PYTHONW__" "%~dp0ys_admin.py" --open
|
||||
exit /b 0
|
||||
@@ -0,0 +1,16 @@
|
||||
@echo off
|
||||
rem ============================================================
|
||||
rem 金钻工坊 · 一键面板 (2026-10-04)
|
||||
rem 渲染机 worker + 开单工具(8082) + 管理面板(8081) 一次拉起来,
|
||||
rem 只打开一个页面(8081),开单工具在页面里用标签页切换。
|
||||
rem 每个服务都有单实例保护:已经跑着的不会重复启动。
|
||||
rem 注意:ys_local 用 python.exe(它要 print 到控制台),
|
||||
rem worker/admin 用 pythonw.exe(不留黑框)。
|
||||
rem ============================================================
|
||||
cd /d %~dp0
|
||||
set PYEXE=<WIN_DIR>\user0\AppData\Local\Programs\Python\Python312\python.exe
|
||||
set PYW=<WIN_DIR>\user0\AppData\Local\Programs\Python\Python312\pythonw.exe
|
||||
start "ys_worker" /min "%PYW%" "%~dp0ys_worker.py"
|
||||
start "ys_local" /min "%PYEXE%" "%~dp0ys_local.py"
|
||||
start "ys_admin" /min "%PYW%" "%~dp0ys_admin.py" --open
|
||||
exit /b 0
|
||||
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
cd /d %~dp0
|
||||
echo Starting YS render worker (background)...
|
||||
start "ys_worker" /min "__PYTHONW__" "%~dp0ys_worker.py"
|
||||
timeout /t 2 >nul
|
||||
echo Done. Log: %~dp0worker.log
|
||||
@@ -0,0 +1,9 @@
|
||||
@echo off
|
||||
cd /d %~dp0
|
||||
echo ===== YS render worker log (last 40 lines) =====
|
||||
powershell -NoProfile -Command "if (Test-Path '%~dp0worker.log') { Get-Content '%~dp0worker.log' -Tail 40 } else { 'worker.log not found' }"
|
||||
echo.
|
||||
echo ===== Server queue status =====
|
||||
powershell -NoProfile -Command "try { (Invoke-WebRequest -UseBasicParsing 'http<WIN-PATH>' -TimeoutSec 15).Content } catch { 'cannot reach server' }"
|
||||
echo.
|
||||
pause
|
||||
@@ -0,0 +1,245 @@
|
||||
/* =========================================================
|
||||
皮肤质检(共用)—— 网页下单页 和 本机开单工具 共用这一份
|
||||
⚠️ 绝对不要复制成两份:两边判定一旦不一致,
|
||||
就会出现「网页说能渲、本地渲不出来」这种最难查的 bug。
|
||||
========================================================= */
|
||||
/* ---------------- 标准 64 网格分区(来自 MC 皮肤规范) ----------------
|
||||
⚠️ 手臂区粗臂(4px)/细臂(3px)分区不同,必须按判定结果取用。
|
||||
实测教训:细臂皮肤若用粗臂的 4px 框去统计,会有 2.94% 被当成「主体镂空」
|
||||
→ 直接被红牌拦下(其实是正常皮肤那一列本来就空着)。 */
|
||||
const BASE = {
|
||||
head:[[8,0,16,8],[16,0,24,8],[0,8,8,16],[8,8,16,16],[16,8,24,16],[24,8,32,16]],
|
||||
body:[[20,16,28,20],[28,16,36,20],[16,20,20,32],[20,20,28,32],[28,20,32,32],[32,20,40,32]],
|
||||
legR:[[4,16,8,20],[8,16,12,20],[0,20,4,32],[4,20,8,32],[8,20,12,32],[12,20,16,32]],
|
||||
legL:[[20,48,24,52],[24,48,28,52],[16,52,20,64],[20,52,24,64],[24,52,28,64],[28,52,32,64]]
|
||||
};
|
||||
const ARM = {
|
||||
classic:{
|
||||
armR:[[44,16,48,20],[48,16,52,20],[40,20,44,32],[44,20,48,32],[48,20,52,32],[52,20,56,32]],
|
||||
armL:[[36,48,40,52],[40,48,44,52],[32,52,36,64],[36,52,40,64],[40,52,44,64],[44,52,48,64]]
|
||||
},
|
||||
slim:{
|
||||
/* 细臂:手臂宽 3px,顶/底面也只用 3 列(第 4 列是空的)
|
||||
—— 这正是渲染端两条判据(x=47 / x=51 处 y=17 镂空)在测的特征。
|
||||
若这里按 4px 画,皮肤会被自己的质检判成「粗臂」(3粗/1细),自相矛盾。 */
|
||||
armR:[[44,16,47,20],[48,16,51,20],[40,20,44,32],[44,20,47,32],[47,20,50,32],[50,20,54,32]],
|
||||
armL:[[36,48,39,52],[40,48,43,52],[32,52,36,64],[36,52,39,64],[39,52,42,64],[42,52,46,64]]
|
||||
}
|
||||
};
|
||||
const OVL = {
|
||||
头外层:[[32,0,64,16]], 身外层:[[16,32,40,48]], 右臂外层:[[40,32,56,48]],
|
||||
左臂外层:[[48,48,64,64]], 右腿外层:[[0,32,16,48]], 左腿外层:[[16,48,32,64]]
|
||||
};
|
||||
const ARM_GROUPS = {右臂:'armR', 左臂:'armL'};
|
||||
|
||||
/* ---------------- 皮肤分析 ---------------- */
|
||||
function analyze(img, origW, origH){
|
||||
const c = document.createElement('canvas');
|
||||
c.width = 64; c.height = 64;
|
||||
const g = c.getContext('2d', {willReadFrequently:true});
|
||||
g.imageSmoothingEnabled = false;
|
||||
g.clearRect(0,0,64,64);
|
||||
g.drawImage(img, 0, 0, 64, 64);
|
||||
const D = g.getImageData(0,0,64,64).data;
|
||||
const A = (x,y) => D[((y*64)+x)*4+3];
|
||||
|
||||
/* --- 1. 尺寸 ---
|
||||
皮肤分辨率没有"标准值"这回事:64 是基准,往上 128/192/256/512/1024…都是同一个
|
||||
64 网格的整倍数放大,所以只要【正方形 + 64 的整倍数】就是标准皮肤。
|
||||
另外把 16/32 这类小图和其它正方形尺寸也识别出来(标注非常规、允许人工确认继续)。
|
||||
非正方形 = 旧版 2:1(64×32),没有独立左右臂/腿纹理,模板渲不了。 */
|
||||
const sq = (origW === origH);
|
||||
const mult64 = sq && origW >= 64 && origW % 64 === 0;
|
||||
const legacy = (origH * 2 === origW) || (!sq && origW > origH);
|
||||
const tooBig = (origW > 4096 || origH > 4096);
|
||||
const tooSmall = sq && origW < 16;
|
||||
|
||||
/* --- 2. 臂型(与 make_order.py 同算法:4 票制) --- */
|
||||
const arm = (function(){
|
||||
let slim=0, classic=0; const v=[];
|
||||
let nt=0; for(let x=40;x<56;x++) if(A(x,25)===0) nt++;
|
||||
const c1 = nt>=2 ? 'slim' : 'classic';
|
||||
c1==='slim'?slim++:classic++;
|
||||
v.push({n:'侧面行 y=25 透明列数', val:nt+' 列', r:c1==='slim'?'细臂':'粗臂'});
|
||||
|
||||
const pairs=[[47,'顶面第 4 列 x=47'],[51,'底面第 4 列 x=51']];
|
||||
for(const [x,lab] of pairs){
|
||||
const empty = A(x,17)===0;
|
||||
empty?slim++:classic++;
|
||||
v.push({n:lab, val:empty?'镂空':'已涂色', r:empty?'细臂':'粗臂'});
|
||||
}
|
||||
let cols=0; for(let x=44;x<52;x++){
|
||||
let has=false; for(let y=16;y<20;y++) if(A(x,y)>0){has=true;break;}
|
||||
if(has) cols++;
|
||||
}
|
||||
const c4 = cols<=6 ? 'slim' : 'classic';
|
||||
c4==='slim'?slim++:classic++;
|
||||
v.push({n:'y16-19 有效列数 x44-51', val:cols+'/8', r:c4==='slim'?'细臂':'粗臂'});
|
||||
|
||||
const model = slim>classic ? 'slim':'classic';
|
||||
const conf = Math.max(slim,classic);
|
||||
return {model, slim, classic, conf, certain: conf>=3, votes:v};
|
||||
})();
|
||||
|
||||
/* --- 3. 分层像素统计(手臂区按判定出的臂型取框,见上方教训) --- */
|
||||
function stat(rects){
|
||||
let total=0, clear=0, semi=0;
|
||||
for(const r of rects){
|
||||
for(let y=r[1];y<r[3];y++) for(let x=r[0];x<r[2];x++){
|
||||
const a=A(x,y); total++;
|
||||
if(a===0) clear++; else if(a<255) semi++;
|
||||
}
|
||||
}
|
||||
return {total, clear, semi, clearPct: total?clear/total*100:0, semiPct: total?semi/total*100:0};
|
||||
}
|
||||
const AR = arm.model==='slim' ? ARM.slim : ARM.classic;
|
||||
const baseAll=[], ovlAll=[], partStat={};
|
||||
const groups=[['头',BASE.head],['身体',BASE.body],['右臂',AR.armR],['左臂',AR.armL],
|
||||
['右腿',BASE.legR],['左腿',BASE.legL]];
|
||||
for(const [cn,rs] of groups){ baseAll.push(...rs); partStat[cn]=stat(rs); }
|
||||
for(const rs of Object.values(OVL)) ovlAll.push(...rs);
|
||||
const base = stat(baseAll), ovl = stat(ovlAll);
|
||||
|
||||
/* --- 4. 颜色数(判断是不是像素风皮肤) --- */
|
||||
const seen=new Set();
|
||||
for(let i=0;i<D.length;i+=4){
|
||||
if(D[i+3] < 8) continue;
|
||||
seen.add((D[i]>>3<<10)|(D[i+1]>>3<<5)|(D[i+2]>>3));
|
||||
if(seen.size>6000) break;
|
||||
}
|
||||
|
||||
return {sq, mult64, legacy, tooBig, tooSmall, origW, origH, arm, base, ovl, partStat, colors:seen.size};
|
||||
}
|
||||
|
||||
/* ---------------- 生成检测报告 ---------------- */
|
||||
function buildReport(a){
|
||||
const out=[]; let hasBad=false, hasWarn=false;
|
||||
const push=(lv,tag,t,d)=>{out.push({lv,tag,t,d});
|
||||
if(lv==='bad')hasBad=true; if(lv==='warn')hasWarn=true;};
|
||||
|
||||
/* 尺寸:只要正方形 + 64 的整倍数都算标准;放大倍数直接说出来 */
|
||||
const sz = a.origW+'×'+a.origH;
|
||||
const times = a.mult64 ? (a.origW/64) : 0;
|
||||
if(a.mult64){
|
||||
push('ok','通过','图片规格 '+sz,
|
||||
times===1 ? '标准皮肤尺寸(64 网格)'
|
||||
: times+" 倍高清皮肤("+times+"×"+times+" 像素块,会按 64 网格解析,出图精度不受影响)");
|
||||
} else if(a.tooBig){
|
||||
push('bad','不通过','图片规格 '+sz,'图太大了(上限 4096×4096)。请先缩到 1024 或 512 再传。');
|
||||
} else if(a.tooSmall){
|
||||
push('bad','不通过','图片规格 '+sz,'图太小了(最小 16×16),装不下一套皮肤的分区。');
|
||||
} else if(a.legacy){
|
||||
push('bad','不通过','图片规格 '+sz,'这是旧版 2:1 皮肤(没有独立的左臂/左腿纹路),模板无法正确渲染,需要的是正方形皮肤。');
|
||||
} else if(a.sq){
|
||||
push('warn','注意','图片规格 '+sz,
|
||||
'能识别,但不是 64 的整倍数(如 64 / 128 / 256 / 512 / 1024),也不是标准皮肤分区比例。'
|
||||
+'会按 64 网格缩放解析;如果皮肤本身是照标准画的,通常也能出图,但有错位风险 —— 你确认没问题就勾下面的「无视风险」。');
|
||||
} else {
|
||||
push('bad','不通过','图片规格 '+sz,'这不是皮肤比例(应为正方形,或旧版的 2:1)。请确认传的是皮肤图。');
|
||||
}
|
||||
|
||||
/* 是否像皮肤 */
|
||||
if(a.colors>3000) push('warn','注意','图片来源看着不像皮肤','画面颜色数异常多('+a.colors+'+ 色),像素风皮肤一般不到几百色。确认没有传错图(比如误传照片或渲染成品图)。');
|
||||
else push('ok','通过','像素风检查','颜色数 '+a.colors+',符合像素风皮肤特征');
|
||||
|
||||
/* 主体层镂空 */
|
||||
const bp=a.base.clearPct;
|
||||
const badParts=Object.entries(a.partStat).filter(([,s])=>s.clearPct>1.5).map(([n,s])=>n+'('+s.clearPct.toFixed(1)+'%)');
|
||||
if(bp>2){
|
||||
push('bad','不通过','主体层有大量镂空','皮肤本体共有 '+bp.toFixed(1)+'% 的像素是全透明的'
|
||||
+(badParts.length?',集中部位:'+badParts.join('、'):'')+'。渲染出来身体会「漏空」,请先把本体补实再提交。');
|
||||
}else if(bp>0.2){
|
||||
push('warn','注意','主体层有小面积镂空','本体有 '+bp.toFixed(1)+'% 的像素是透明的'
|
||||
+(badParts.length?',主要在:'+badParts.join('、'):'')+'。多数情况能正常出图,少数会在成图上看到细小的透光点。');
|
||||
}else{
|
||||
push('ok','通过','主体层完整','本体没有明显镂空');
|
||||
}
|
||||
|
||||
/* 半透明 */
|
||||
const semiN = a.base.semi + a.ovl.semi;
|
||||
if(a.base.semi>30){
|
||||
push('warn','注意','存在半透明像素','本体层有 '+a.base.semi+' 个半透明像素(alpha 不是全实心)。渲染边缘可能出现毛边或色差。');
|
||||
}else if(semiN>0){
|
||||
push('warn','注意','存在少量半透明像素','全图 '+semiN+' 个半透明像素,通常不影响出图,但边缘可能略有杂色。');
|
||||
}else{
|
||||
push('ok','通过','透明度正常','未发现半透明像素');
|
||||
}
|
||||
|
||||
/* 外层 */
|
||||
const op=a.ovl.clearPct;
|
||||
if(a.ovl.total && op>99.5){
|
||||
push('ok','通过','外层(第二层)未使用','这套皮肤没有用外套/帽子层,属正常情况');
|
||||
}else if(a.ovl.total && op<2){
|
||||
push('warn','注意','外层几乎铺满','外层(帽子/外套)几乎每一格都有颜色。如果本意是「只有部分外套」,可能是不小心整层涂满了。');
|
||||
}else{
|
||||
push('ok','通过','外层覆盖正常','外层(帽子/外套)有内容也有留白,符合常见皮肤画法');
|
||||
}
|
||||
|
||||
/* 臂型 */
|
||||
if(a.arm.certain){
|
||||
push('ok','通过','手臂规格 · '+(a.arm.model==='classic'?'粗臂(Steve 4px)':'细臂(Alex 3px)'),
|
||||
'判定明确(' + Math.max(a.arm.slim,a.arm.classic) + '/4 项)。渲染时会用' + (a.arm.model==='classic'?'粗臂':'细臂') + '模型。若你觉得不对,可在下面手动改。');
|
||||
}else{
|
||||
push('warn','注意','手臂规格判定不确定',
|
||||
'4 项检验只命中 '+Math.max(a.arm.slim,a.arm.classic)+' 项('+(a.arm.classic)+' 粗 / '+(a.arm.slim)+' 细),这类皮肤容易判错。'
|
||||
+'请自己在下面确认一下手臂是粗的还是细的——判错会导致皮肤整体错位。');
|
||||
}
|
||||
return {items:out, hasBad, hasWarn};
|
||||
}
|
||||
|
||||
|
||||
/* ---------------- PNG 结构核验(防夹带私货) ----------------
|
||||
⚠️ 这份是 /opt/order-app/pngcheck.py 的**镜像**,两边判定必须一致:
|
||||
前端负责「拦」(给人看明白的原因),后端负责「剥」(存下来的是干净字节)。
|
||||
改一边必须同步改另一边 —— 共享用例在 /opt/order-app/tests/png_struct_test.py。
|
||||
拦什么:尾部夹带 / 未知关键块 / APNG / 结构损坏 / 非 PNG
|
||||
只警告:tEXt 等元数据块(很多编辑器会加,后端会剥掉,不算错)
|
||||
u8: Uint8Array(整个文件字节)→ {ok, reason, notes}
|
||||
------------------------------------------------------------- */
|
||||
function checkPngBytes(u8){
|
||||
const notes=[];
|
||||
const bad=(why)=>({ok:false, reason:why, notes:notes});
|
||||
const SIG=[0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A];
|
||||
if(!u8 || u8.length < 33) return bad('不是 PNG 文件');
|
||||
for(let i=0;i<8;i++){ if(u8[i]!==SIG[i]) return bad('不是 PNG 文件'); }
|
||||
|
||||
const STRIP=['tEXt','zTXt','iTXt','eXIf','tIME','sPLT','hIST'];
|
||||
const OK_CRIT=['IHDR','PLTE','IDAT','IEND'];
|
||||
const OK_ANC=['PLTE','tRNS','gAMA','cHRM','sRGB','iCCP','bKGD','pHYs','sBIT'];
|
||||
const rd=(o)=>((u8[o]<<24)>>>0)+(u8[o+1]<<16)+(u8[o+2]<<8)+u8[o+3];
|
||||
const typ=(o)=>String.fromCharCode(u8[o],u8[o+1],u8[o+2],u8[o+3]);
|
||||
|
||||
let off=8, n=0, seenIhdr=false, seenIdat=false, seenIend=false;
|
||||
while(off < u8.length){
|
||||
if(++n > 4096) return bad('PNG 结构异常(块数量过多)');
|
||||
if(off+8 > u8.length) return bad('PNG 文件损坏(块头不完整)');
|
||||
const ln=rd(off), t=typ(off+4), end=off+12+ln;
|
||||
if(end > u8.length) return bad('PNG 文件损坏(块数据不完整)');
|
||||
if(t==='IHDR'){
|
||||
if(off!==8) return bad('PNG 结构异常(IHDR 不在最前)');
|
||||
seenIhdr=true;
|
||||
}else if(t==='IEND'){
|
||||
seenIend=true;
|
||||
const tail=u8.length-end;
|
||||
if(tail>0) return bad('图片尾部夹带了 '+tail+' 字节额外数据(正常 PNG 到 IEND 就该结束)');
|
||||
break;
|
||||
}else if(t==='acTL'){
|
||||
return bad('这是动画 PNG(APNG),请用普通静态 PNG');
|
||||
}else if(t==='IDAT'){
|
||||
seenIdat=true;
|
||||
}else if(OK_ANC.indexOf(t)>=0){
|
||||
/* 允许 */
|
||||
}else if(STRIP.indexOf(t)>=0){
|
||||
notes.push('已剥掉元数据块 '+t);
|
||||
}else{
|
||||
const critical = (u8[off+4] & 0x20) === 0; /* PNG 规范:首字母大写=关键块 */
|
||||
if(critical && OK_CRIT.indexOf(t)<0) return bad('图片里有无法识别的内容块 '+t);
|
||||
notes.push('已剥掉附加块 '+t);
|
||||
}
|
||||
off=end;
|
||||
}
|
||||
if(!seenIhdr) return bad('PNG 缺少 IHDR(不是完整图片)');
|
||||
if(!seenIdat) return bad('PNG 缺少图像数据(IDAT)');
|
||||
if(!seenIend) return bad('PNG 没有正常结束(缺 IEND)');
|
||||
return {ok:true, reason:'', notes:notes};
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
@echo off
|
||||
echo Stopping YS admin panel...
|
||||
powershell -NoProfile -Command "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*ys_admin.py*' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }"
|
||||
echo Stopped.
|
||||
timeout /t 3 >nul
|
||||
@@ -0,0 +1,5 @@
|
||||
@echo off
|
||||
echo Stopping YS render worker...
|
||||
powershell -NoProfile -Command "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*ys_worker.py*' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }"
|
||||
echo Stopped. (Server side will show the machine as offline.)
|
||||
timeout /t 3 >nul
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,431 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
金钻工坊 · 本机开单工具(平台单专用)
|
||||
|
||||
给「闲鱼 / B站工坊」这类聊天下单的买家出图用:
|
||||
|
||||
双击桌面「本机开单」→ 浏览器打开 htt<WIN-PATH>
|
||||
→ 拖皮肤进去(同样自动质检)→ 勾模板 → 点开始
|
||||
→ 本机 Blender 出图(标准压缩 + 16bit 无压缩,两张)→ 下载 / 打开文件夹 → 贴回闲鱼
|
||||
|
||||
安全设计(金钻 2026-09-30 提出「别人会暴力破解吧」):
|
||||
* 只监听 localhost —— 公网、局域网都连不进来,根本没有暴露面
|
||||
* 不联网、不上传、不要兑换码、不碰服务器
|
||||
|
||||
渲染队列(金钻 2026-09-30:「也是渲染队列,不要一口气并行,会卡炸的」):
|
||||
* **只有一个渲染线程**(qworker)→ 任何时刻至多一个 Blender 在跑
|
||||
* 多单进来排队 FIFO,页面显示「前面还有 N 单」
|
||||
* 一张图渲完才开下一张;串行是硬约束,不是性能优化
|
||||
"""
|
||||
import base64
|
||||
import collections
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
import urllib.parse
|
||||
import webbrowser
|
||||
from datetime import datetime
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import ys_worker as W # 复用:配置 / 模板表 / Blender 查找 / 日志
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
PORT = 8082
|
||||
# ⚠️ 2026-10-04:单实例锁必须用**独立端口** —— 以前它 bind 的是 PORT(8082),
|
||||
# 紧接着 ThreadingHTTPServer 又要 bind 8082,Windows 上会直接 WinError 10013
|
||||
# ("访问权限不允许的方式做套接字尝试")。ys_worker 用的 8083,这里用 8084。
|
||||
LOCK_PORT = 8084
|
||||
JOBS = {} # job_id -> dict
|
||||
JOB_LOCK = threading.Lock()
|
||||
|
||||
# ⚠️ 渲染队列:只有一个消费线程 → 至多一个 Blender 在跑
|
||||
JOBQ = collections.deque()
|
||||
QCOND = threading.Condition()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 队列
|
||||
def enqueue(job_id):
|
||||
with QCOND:
|
||||
JOBQ.append(job_id)
|
||||
_refresh_positions()
|
||||
QCOND.notify()
|
||||
|
||||
|
||||
def _refresh_positions():
|
||||
for i, jid in enumerate(JOBQ):
|
||||
j = JOBS.get(jid)
|
||||
if j is not None:
|
||||
j["queue_pos"] = i + 1
|
||||
|
||||
|
||||
_queue_started = False
|
||||
|
||||
|
||||
def start_queue():
|
||||
"""起唯一的渲染线程(幂等)。main() 会调;测试也直接调它。"""
|
||||
global _queue_started
|
||||
if _queue_started:
|
||||
return False
|
||||
_queue_started = True
|
||||
threading.Thread(target=qworker, daemon=True).start()
|
||||
return True
|
||||
|
||||
|
||||
def qworker():
|
||||
"""唯一干活的人。串行是硬要求,别改成并行。"""
|
||||
while True:
|
||||
with QCOND:
|
||||
while not JOBQ:
|
||||
QCOND.wait()
|
||||
jid = JOBQ.popleft()
|
||||
_refresh_positions()
|
||||
try:
|
||||
run_job(jid)
|
||||
except Exception:
|
||||
j = JOBS.get(jid)
|
||||
if j is not None:
|
||||
j.update(state="error", error=traceback.format_exc()[-400:])
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 工具
|
||||
def local_archive():
|
||||
"""本机单的留档根目录(和网页订单分开放,但共用同一套序号)"""
|
||||
return W.CFG.get("local_archive") or os.path.join(W.CFG["archive"], "本地")
|
||||
|
||||
|
||||
def now_s():
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def scan_assets():
|
||||
"""体检:Blender / 模板 / 渲染脚本 都在不在(页面进来就先告诉你,别等渲到一半才报错)"""
|
||||
blender = W.find_blender()
|
||||
tpl_root = W.CFG["tpl_root"]
|
||||
missing = []
|
||||
for k, fn in W.TEMPLATES.items():
|
||||
if not os.path.exists(os.path.join(tpl_root, fn)):
|
||||
missing.append(fn)
|
||||
return {
|
||||
"blender": blender,
|
||||
"blender_ok": bool(blender),
|
||||
"tpl_root": tpl_root,
|
||||
"make_order": W.CFG["make_order"],
|
||||
"make_order_ok": os.path.exists(W.CFG["make_order"]),
|
||||
"archive": local_archive(),
|
||||
"templates": {k: {"file": fn, "ok": os.path.exists(os.path.join(tpl_root, fn))}
|
||||
for k, fn in W.TEMPLATES.items()},
|
||||
"missing": missing,
|
||||
}
|
||||
|
||||
|
||||
def open_browser(url):
|
||||
"""只在 Windows 上自动开浏览器。
|
||||
服务器/无桌面环境调 xdg-open 会去连 D-Bus,起不来还刷错误,没必要。"""
|
||||
if os.name != "nt" and not os.environ.get("YS_OPEN_BROWSER"):
|
||||
return
|
||||
try:
|
||||
webbrowser.open(url)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 渲染
|
||||
def write_png(dataurl, dest):
|
||||
if "," in dataurl:
|
||||
dataurl = dataurl.split(",", 1)[1]
|
||||
with open(dest, "wb") as f:
|
||||
f.write(base64.b64decode(dataurl))
|
||||
|
||||
|
||||
def pick_outputs(d, tpl_key, res):
|
||||
"""挑出这一单的两张成品。命名规则(金钻 2026-09-30 定稿,见 ys_worker.deliver_names):
|
||||
默认 1000 → 飞跃樱花林.png + 飞跃樱花林无压缩版.png
|
||||
其它 N → 飞跃樱花林N.png + 飞跃樱花林N无压缩版.png
|
||||
找不到就退回"目录里有的",别让一次改名把成品弄丢。"""
|
||||
sn, un = W.deliver_names(tpl_key, res)
|
||||
std = os.path.join(d, sn)
|
||||
if not os.path.exists(std):
|
||||
cands = [f for f in sorted(os.listdir(d))
|
||||
if f.lower().endswith(".png") and W.UNC_SUFFIX not in f]
|
||||
std = os.path.join(d, cands[0]) if cands else None
|
||||
unc = os.path.join(d, un)
|
||||
if not os.path.exists(unc):
|
||||
cands = [f for f in sorted(os.listdir(d))
|
||||
if f.lower().endswith(".png") and W.UNC_SUFFIX in f]
|
||||
unc = os.path.join(d, cands[0]) if cands else None
|
||||
return std, unc
|
||||
|
||||
|
||||
def run_job(job_id):
|
||||
j = JOBS[job_id]
|
||||
j["state"] = "running"
|
||||
j["queue_pos"] = 0
|
||||
try:
|
||||
blender = W.find_blender()
|
||||
if not blender:
|
||||
j.update(state="error", error="找不到 blender.exe(把路径填进 config.json 的 blender 字段)")
|
||||
return
|
||||
work = os.path.join(HERE, "work")
|
||||
os.makedirs(work, exist_ok=True)
|
||||
# 用买家原始文件名建临时皮肤 —— 留档文件夹里要看到客户给的那张图叫什么
|
||||
safe = re.sub(r'[\\/:*?"<>|]+', "_", (j.get("fileName") or "skin.png")).strip() or "skin.png"
|
||||
if not safe.lower().endswith(".png"):
|
||||
safe += ".png"
|
||||
skin = os.path.join(work, safe)
|
||||
write_png(j["skin"], skin)
|
||||
j["skin"] = None # 立刻丢掉 base64,别占内存
|
||||
|
||||
root = local_archive()
|
||||
os.makedirs(root, exist_ok=True)
|
||||
|
||||
for idx, tk in enumerate(j["templates"]):
|
||||
j["current"] = idx + 1
|
||||
fname = W.TEMPLATES.get(tk)
|
||||
if not fname:
|
||||
j["errors"].append("未知模板:%s" % tk)
|
||||
continue
|
||||
tpl = os.path.join(W.CFG["tpl_root"], fname)
|
||||
if not os.path.exists(tpl):
|
||||
j["errors"].append("%s:模板文件不存在" % fname)
|
||||
continue
|
||||
|
||||
out_name = W.tpl_base(tk)
|
||||
res = int(j.get("res") or W.DEFAULT_RES)
|
||||
# 不加 --uncompressed:这个开关现在默认就是开的(金钻:两张都要发顾客)
|
||||
# 成品文件夹用成品名;皮肤先放进去;工程走临时目录,渲完删
|
||||
d, dbase = W.prepare_out_dir(root, tk, res, skin)
|
||||
cmd = [blender, "-b", "--factory-startup", "--python", W.CFG["make_order"], "--",
|
||||
"--template", tpl, "--skin", skin,
|
||||
"--orders-dir", root, "--out-dir", d, "--res", str(res)]
|
||||
W.log("[本机单] 渲染 %s → %s(%d px)" % (fname, os.path.basename(d), res))
|
||||
okr, tail, dt, note = W.run_blender(cmd, timeout=W.blender_timeout(res))
|
||||
if not okr:
|
||||
j["errors"].append("%s:%s" % (fname, note))
|
||||
continue
|
||||
seq = W.next_seq({"来源": "本机开单(平台单)", "模板": out_name,
|
||||
"成品文件夹": os.path.basename(d), "分辨率": res,
|
||||
"皮肤文件": os.path.basename(skin), "备注": j.get("note") or "",
|
||||
"耗时秒": round(dt, 1)})
|
||||
|
||||
std, unc = pick_outputs(d, tk, res)
|
||||
if not std:
|
||||
j["errors"].append("%s:渲染完成但没找到 png" % fname)
|
||||
continue
|
||||
if not unc:
|
||||
j["errors"].append("%s:无压缩版没生成(只出了标准版)" % fname)
|
||||
|
||||
info = {"序号": seq, "文件夹": os.path.basename(d),
|
||||
"来源": "本机开单(平台单)", "模板": out_name, "模板key": tk,
|
||||
"分辨率": res, "皮肤文件": os.path.basename(skin), "手臂规格": j.get("arm"),
|
||||
"条款版本": W.TERMS_VERSION,
|
||||
"条款说明": "仅提供渲染服务;皮肤内容合法性由提供者负责",
|
||||
"买家备注": j.get("note") or "", "渲染完成时间": now_s(),
|
||||
"渲染耗时秒": round(dt, 1),
|
||||
"交付件": [os.path.basename(x) for x in (std, unc) if x]}
|
||||
try:
|
||||
with open(os.path.join(d, "订单信息.json"), "w", encoding="utf-8") as f:
|
||||
json.dump(info, f, ensure_ascii=False, indent=1)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
sn, un = W.deliver_names(tk, res)
|
||||
j["results"].append({"seq": seq, "tpl": tk, "res": res, "kind": "标准压缩",
|
||||
"name": sn, "path": std, "dir": d, "sec": round(dt, 1)})
|
||||
if unc:
|
||||
j["results"].append({"seq": seq, "tpl": tk, "res": res, "kind": "无压缩(16bit)",
|
||||
"name": un, "path": unc, "dir": d, "sec": round(dt, 1)})
|
||||
W.log("[本机单] 完成 %s → %s(%.1fs,两张)" % (fname, std, dt))
|
||||
|
||||
j["state"] = "done" if j["results"] else "error"
|
||||
if not j["results"]:
|
||||
j["error"] = ";".join(j["errors"])[:400] or "没有产出任何图片"
|
||||
j["finished"] = now_s()
|
||||
except subprocess.TimeoutExpired:
|
||||
j.update(state="error", error="渲染超时(超过 1 小时)")
|
||||
except Exception:
|
||||
j.update(state="error", error=traceback.format_exc()[-400:])
|
||||
finally:
|
||||
try:
|
||||
if skin and os.path.exists(skin):
|
||||
os.remove(skin)
|
||||
except (OSError, NameError):
|
||||
pass
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ HTTP
|
||||
class H(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
server_version = "ys-local"
|
||||
|
||||
def log_message(self, fmt, *a): # 静音,别刷屏
|
||||
pass
|
||||
|
||||
def send(self, code, body, ctype="application/json; charset=utf-8", extra=None):
|
||||
if isinstance(body, str):
|
||||
body = body.encode("utf-8")
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
for k, v in (extra or {}).items():
|
||||
self.send_header(k, v)
|
||||
self.end_headers()
|
||||
try:
|
||||
self.wfile.write(body)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
pass
|
||||
|
||||
def js(self, obj, code=200):
|
||||
self.send(code, json.dumps(obj, ensure_ascii=False))
|
||||
|
||||
def static(self, name, ctype):
|
||||
p = os.path.join(HERE, name)
|
||||
if not os.path.exists(p):
|
||||
return self.send(404, "missing", "text/plain; charset=utf-8")
|
||||
with open(p, "rb") as f:
|
||||
self.send(200, f.read(), ctype)
|
||||
|
||||
def do_GET(self):
|
||||
u = urllib.parse.urlparse(self.path)
|
||||
p = u.path
|
||||
if p in ("/", "/index.html"):
|
||||
return self.static("local.html", "text/html; charset=utf-8")
|
||||
if p == "/skincheck.js":
|
||||
return self.static("skincheck.js", "application/javascript; charset=utf-8")
|
||||
if p == "/api/status":
|
||||
return self.js(scan_assets())
|
||||
|
||||
m = re.fullmatch(r"/api/job/([A-Za-z0-9]+)", p)
|
||||
if m:
|
||||
j = JOBS.get(m.group(1))
|
||||
if not j:
|
||||
return self.js({"ok": False, "error": "任务不存在"}, 404)
|
||||
return self.js({k: v for k, v in j.items() if k != "skin"})
|
||||
|
||||
m = re.fullmatch(r"/api/file/([A-Za-z0-9]+)/(\d+)", p)
|
||||
if m:
|
||||
j = JOBS.get(m.group(1))
|
||||
if not j:
|
||||
return self.send(404, "no job", "text/plain")
|
||||
i = int(m.group(2))
|
||||
if i >= len(j["results"]):
|
||||
return self.send(404, "no file", "text/plain")
|
||||
r = j["results"][i]
|
||||
with open(r["path"], "rb") as f:
|
||||
# ⚠️ HTTP 头只能是 latin-1,中文文件名直接扔 UnicodeEncodeError
|
||||
# → 连接被掐断(浏览器看就是「下载失败」)。必须 ASCII 回退名 + RFC 5987。
|
||||
ascii_name = r["name"].encode("ascii", "replace").decode("ascii").replace("?", "_")
|
||||
cd = ("inline; filename=\"%s\"; filename*=UTF-8''%s"
|
||||
% (ascii_name, urllib.parse.quote(r["name"], safe="")))
|
||||
return self.send(200, f.read(), "image/png", {"Content-Disposition": cd})
|
||||
return self.send(404, "not found", "text/plain; charset=utf-8")
|
||||
|
||||
def _same_site(self):
|
||||
"""只认本机页面发来的请求(2026-10-05 外部复查加)。
|
||||
|
||||
⚠️ 这个工具只监听回环,但**本机浏览器里打开的任何网页**都能往 localhost 发 POST ——
|
||||
text/plain 的跨站 POST 不需要预检,原来照单全收:一个恶意网页就能往队列里塞任意多个
|
||||
渲染(把机器顶满)、往留档目录里写没经过核验的「皮肤」、或者直接 /api/quit 把工具关掉。
|
||||
规则:Host 必须是本机地址(挡 DNS 重绑定);带了 Origin 就必须是本机这个端口。
|
||||
本机页面自己发的请求两条都满足,用法不变。
|
||||
"""
|
||||
host = (self.headers.get("Host") or "").strip().lower()
|
||||
ok_hosts = {"localhost:%d" % PORT, "127.0.0.1:%d" % PORT, "[::1]:%d" % PORT}
|
||||
if host not in ok_hosts:
|
||||
return False
|
||||
origin = (self.headers.get("Origin") or "").strip().lower()
|
||||
if origin and origin not in {"http://" + h for h in ok_hosts}:
|
||||
return False
|
||||
return True
|
||||
|
||||
def do_POST(self):
|
||||
u = urllib.parse.urlparse(self.path)
|
||||
if not self._same_site():
|
||||
return self.js({"ok": False, "error": "只接受本机页面的请求"}, 403)
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
if n > 64 * 1024 * 1024:
|
||||
return self.js({"ok": False, "error": "请求过大"}, 413)
|
||||
try:
|
||||
d = json.loads(self.rfile.read(n) or b"{}") if n else {}
|
||||
except ValueError:
|
||||
return self.js({"ok": False, "error": "请求体不合法"}, 400)
|
||||
|
||||
if u.path == "/api/render":
|
||||
tpls = [t for t in (d.get("templates") or []) if t in W.TEMPLATES][:10]
|
||||
if not d.get("skin") or not tpls:
|
||||
return self.js({"ok": False, "error": "缺皮肤或缺模板"}, 400)
|
||||
st = scan_assets()
|
||||
if not st["blender_ok"]:
|
||||
return self.js({"ok": False, "error": "没找到 blender.exe"}, 400)
|
||||
jid = "%s%04d" % (datetime.now().strftime("%H%M%S"), len(JOBS))
|
||||
JOBS[jid] = {"id": jid, "state": "queued", "queue_pos": 0, "created": now_s(),
|
||||
"skin": d["skin"], "fileName": d.get("fileName") or "skin.png",
|
||||
"templates": tpls, "arm": d.get("arm") or "",
|
||||
"res": int(d.get("res") or W.DEFAULT_RES),
|
||||
"note": (d.get("note") or "")[:200],
|
||||
"total": len(tpls), "current": 0, "results": [], "errors": []}
|
||||
enqueue(jid) # ← 进队列,由唯一的渲染线程串行处理
|
||||
return self.js({"ok": True, "job": jid})
|
||||
|
||||
if u.path == "/api/openfolder":
|
||||
j = JOBS.get(d.get("job") or "")
|
||||
if not j or not j.get("results"):
|
||||
return self.js({"ok": False, "error": "还没有产出"}, 400)
|
||||
folder = j["results"][0]["dir"]
|
||||
try:
|
||||
if hasattr(os, "startfile"): # Windows
|
||||
os.startfile(folder)
|
||||
else:
|
||||
subprocess.Popen(["xdg-open", folder])
|
||||
return self.js({"ok": True, "folder": folder})
|
||||
except Exception as e:
|
||||
return self.js({"ok": False, "error": "%s 目录:%s" % (e, folder)}, 500)
|
||||
|
||||
if u.path == "/api/quit":
|
||||
self.js({"ok": True})
|
||||
threading.Thread(target=lambda: (time.sleep(0.4), os._exit(0)), daemon=True).start()
|
||||
return
|
||||
|
||||
return self.js({"ok": False, "error": "not found"}, 404)
|
||||
|
||||
|
||||
def single_instance():
|
||||
"""只允许开一个:不然两个页面同时开两个 Blender 会把机器顶满"""
|
||||
s = socket.socket()
|
||||
try:
|
||||
s.bind(("localhost", LOCK_PORT))
|
||||
s.listen(1)
|
||||
return s
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
W.load_cfg()
|
||||
lock = single_instance()
|
||||
if not lock:
|
||||
print("本机开单工具已经在跑了,直接打开 htt<WIN-PATH>" % PORT)
|
||||
open_browser("htt<WIN-PATH>" % PORT)
|
||||
time.sleep(4)
|
||||
return
|
||||
start_queue() # 唯一的渲染线程
|
||||
a = scan_assets()
|
||||
print("=" * 56)
|
||||
print(" 金钻工坊 · 本机开单工具(平台单)")
|
||||
print(" 地址 htt<WIN-PATH> (只有这台电脑能开)" % PORT)
|
||||
print(" Blender %s" % (a["blender"] or "❌ 没找到"))
|
||||
print(" 模板 %s(缺 %d 个)" % (a["tpl_root"], len(a["missing"])))
|
||||
print(" 留档 %s" % a["archive"])
|
||||
print(" 队列 串行,一次只开一个 Blender")
|
||||
print("=" * 56, flush=True)
|
||||
open_browser("htt<WIN-PATH>" % PORT)
|
||||
ThreadingHTTPServer(("localhost", PORT), H).serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,698 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
金钻工坊 · 渲染下单 —— 宿主机渲染机(worker)
|
||||
|
||||
开机启动后自动干活:
|
||||
心跳上报 → 拉一单 → 下载皮肤 → 用 Blender 按模板出图 → 回传服务器 → 永久留档
|
||||
|
||||
留档(金钻要求:时间 / 序号 / 兑换码 / 皮肤 / 成图):
|
||||
<ARCHIVE_DIR>
|
||||
模板.blend、_assets\\skin.png、<模板名>.png、订单信息.json
|
||||
|
||||
只在需要时连服务器(出站),服务器从不主动连你。
|
||||
"""
|
||||
import base64, codecs, json, os, re, shutil, signal, socket, subprocess, sys, threading, time, traceback
|
||||
import urllib.request, urllib.error
|
||||
from datetime import datetime
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
# ---- 成品命名(金钻 2026-09-30 定稿,和 make_order.py 必须一致)----
|
||||
# 默认 1000 → <模板名>.png + <模板名>无压缩.png
|
||||
# 其它 N → <模板名>N.png + <模板名>N无压缩.png
|
||||
DEFAULT_RES = 1000
|
||||
UNC_SUFFIX = "无压缩"
|
||||
# 服务条款版本 —— 与网页 index.html / 后端 server.py 必须一致(2026-09-30 金钻定)
|
||||
TERMS_VERSION = "2026-10-01.1"
|
||||
|
||||
# ---------------------------------------------------------------- 配置
|
||||
CFG = {
|
||||
"server": "http<WIN-PATH>",
|
||||
"token": "",
|
||||
"tpl_root": r"<ARCHIVE_DIR>",
|
||||
"make_order": r"<TOOLS_DIR>\make_order.py",
|
||||
"archive": r"<ARCHIVE_DIR>",
|
||||
"blender": "", # 留空 = 自动查找
|
||||
"res": DEFAULT_RES, # 出图分辨率;文件名规则见上
|
||||
"poll": 20
|
||||
}
|
||||
TEMPLATES = { # key 必须和下单页一致
|
||||
"stand": "1站立正反.blend",
|
||||
"standb": "2站立正反加虚化.blend",
|
||||
"wheat": "3麦田萤火.blend",
|
||||
"beach": "4海边自拍.blend",
|
||||
"boom": "5不看爆炸.blend",
|
||||
"sakura": "6飞跃樱花林.blend",
|
||||
"airship": "7空艇巡游.blend",
|
||||
}
|
||||
def tpl_base(tpl_key):
|
||||
"""模板中文名(去掉文件名开头的序号):3麦田萤火.blend → 麦田萤火"""
|
||||
return re.sub(r"^\d+", "", os.path.splitext(TEMPLATES.get(tpl_key, tpl_key))[0])
|
||||
|
||||
|
||||
def out_base(tpl_key, res):
|
||||
res = int(res or DEFAULT_RES)
|
||||
b = tpl_base(tpl_key)
|
||||
return b if res == DEFAULT_RES else "%s%d" % (b, res)
|
||||
|
||||
|
||||
def deliver_names(tpl_key, res):
|
||||
b = out_base(tpl_key, res)
|
||||
return b + ".png", b + UNC_SUFFIX + ".png"
|
||||
|
||||
|
||||
def prepare_out_dir(root, tpl_key, res, skin_path):
|
||||
"""建成品文件夹并**先把皮肤放进去**(金钻 2026-09-30)。
|
||||
文件夹名 = 成品名(`飞跃樱花林` / `飞跃樱花林1080`);重名加 -2/-3,
|
||||
同一个模板被买两次不能互相覆盖。返回 (文件夹, 成品基名)。"""
|
||||
base = out_base(tpl_key, res)
|
||||
d = os.path.join(root, base)
|
||||
n = 2
|
||||
while os.path.exists(d):
|
||||
d = os.path.join(root, "%s-%d" % (base, n))
|
||||
n += 1
|
||||
os.makedirs(d, exist_ok=True)
|
||||
if skin_path and os.path.exists(skin_path):
|
||||
dst = os.path.join(d, os.path.basename(skin_path))
|
||||
if os.path.abspath(dst) != os.path.abspath(skin_path):
|
||||
shutil.copy2(skin_path, dst)
|
||||
return d, base
|
||||
|
||||
|
||||
LOCK_PORT = 8083 # 单实例锁
|
||||
LOG = os.path.join(HERE, "worker.log")
|
||||
|
||||
|
||||
def log(*a):
|
||||
line = "[%s] %s" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), " ".join(str(x) for x in a))
|
||||
print(line, flush=True)
|
||||
try:
|
||||
if os.path.exists(LOG) and os.path.getsize(LOG) > 2 * 1024 * 1024:
|
||||
shutil.move(LOG, LOG + ".old")
|
||||
with open(LOG, "a", encoding="utf-8") as f:
|
||||
f.write(line + "\n")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def load_cfg():
|
||||
p = os.path.join(HERE, "config.json")
|
||||
if os.path.exists(p):
|
||||
try:
|
||||
CFG.update(json.load(open(p, encoding="utf-8")))
|
||||
except Exception as e:
|
||||
log("config.json 读取失败:%r(用默认值继续)" % e)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- HTTP
|
||||
def http(path, obj=None, raw=False, timeout=120, tries=1, gap=5):
|
||||
"""调服务器。tries>1 时网络抖动会自己重试。
|
||||
|
||||
⚠️ 2026-09-30 晚实踩:原来只接 HTTPError,**网络层的异常直接抛出去**。
|
||||
那次是无压缩(约 10MB)回传时 TLS 断了一下(`EOF occurred in violation of protocol`),
|
||||
异常一路冒到轮询循环 → 这一单**剩下的模板全没渲**,还得等 45 分钟退回重来。
|
||||
所以:网络异常要么在重试里消化掉,要么返回「失败」让调用方按普通失败处理。
|
||||
"""
|
||||
url = CFG["server"].rstrip("/") + path
|
||||
data = json.dumps(obj).encode("utf-8") if obj is not None else None
|
||||
req = urllib.request.Request(url, data=data, method="POST" if data else "GET")
|
||||
req.add_header("Content-Type", "application/json")
|
||||
req.add_header("X-Worker-Token", CFG.get("token") or "")
|
||||
last = None
|
||||
for i in range(max(1, tries)):
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
body = r.read()
|
||||
return (r.status, body if raw else json.loads(body))
|
||||
except urllib.error.HTTPError as e:
|
||||
return (e.code, e.read() if raw else {"ok": False, "error": "HTTP %d" % e.code})
|
||||
except (urllib.error.URLError, OSError, ValueError) as e:
|
||||
last = e
|
||||
if i < tries - 1:
|
||||
log("网络异常,%ds 后重试(第 %d/%d 次):%r" % (gap, i + 1, tries, e))
|
||||
time.sleep(gap)
|
||||
return (0, {"ok": False, "error": "网络异常 %r" % last})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Blender
|
||||
def find_blender():
|
||||
if CFG.get("blender") and os.path.exists(CFG["blender"]):
|
||||
return CFG["blender"]
|
||||
cands = []
|
||||
for base in (r"<PROGRAM_DIR>", r"<PROGRAM_DIR>",
|
||||
r"<PROGRAM_DIR>", r"<WIN_DIR>", r"<WIN_DIR>"):
|
||||
if os.path.isdir(base):
|
||||
for d in sorted(os.listdir(base), reverse=True):
|
||||
p = os.path.join(base, d, "blender.exe")
|
||||
if os.path.exists(p):
|
||||
cands.append(p)
|
||||
cands.append(os.path.join(base, d, "blender-launcher.exe"))
|
||||
for p in cands:
|
||||
if p.lower().endswith("blender.exe") and os.path.exists(p):
|
||||
return p
|
||||
return ""
|
||||
|
||||
|
||||
# ===== 序号登记(金钻 2026-09-30:专门用一个文件存,不依赖文件夹)=====
|
||||
# ⚠️ 以前靠扫文件夹名推序号 —— 文件夹一改名/挪地方序号就乱。
|
||||
# 现在序号写在登记文件里,文件夹怎么动都不影响连续性。
|
||||
SEQ_FILE_NAME = "_序号登记.json"
|
||||
|
||||
|
||||
def seq_file():
|
||||
return os.path.join(CFG["archive"], SEQ_FILE_NAME)
|
||||
|
||||
|
||||
def _seed_seq_from_folders():
|
||||
"""登记文件第一次用(或丢了)时,从老文件夹名估个起点,别从 001 重来。"""
|
||||
n = 0
|
||||
try:
|
||||
for name in os.listdir(CFG["archive"]):
|
||||
m = re.fullmatch(r"(\d{3})", name)
|
||||
if m:
|
||||
n = max(n, int(m.group(1)))
|
||||
except OSError:
|
||||
pass
|
||||
return n
|
||||
|
||||
|
||||
def next_seq(rec=None):
|
||||
"""领一个新序号,写进登记文件。返回整数序号。
|
||||
|
||||
登记明细里记下:时间 / 来源 / 订单号 / 兑换码 / 模板 / 成品文件夹 / 分辨率 ——
|
||||
「看号就知道是第几单、谁的单、出的哪个模板」。
|
||||
写文件用 tmp + os.replace 原子替换,断电也不会写坏。
|
||||
"""
|
||||
os.makedirs(CFG["archive"], exist_ok=True)
|
||||
p = seq_file()
|
||||
d = {}
|
||||
if os.path.exists(p):
|
||||
try:
|
||||
with open(p, encoding="utf-8") as f:
|
||||
d = json.load(f) or {}
|
||||
except Exception as e:
|
||||
log("⚠️ 序号登记文件读不动(%r),按 0 起算" % e)
|
||||
d = {}
|
||||
if not isinstance(d.get("last"), int):
|
||||
d["last"] = _seed_seq_from_folders()
|
||||
d["_起点说明"] = "首次创建:按已有文件夹名估的起点"
|
||||
n = int(d["last"]) + 1
|
||||
d["last"] = n
|
||||
r = dict(rec or {})
|
||||
r.setdefault("序号", n)
|
||||
r.setdefault("时间", time.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
d.setdefault("明细", []).append(r)
|
||||
d["明细"] = d["明细"][-1000:] # 只留最近 1000 条,别把文件撑大
|
||||
tmp = p + ".tmp"
|
||||
try:
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(d, f, ensure_ascii=False, indent=1)
|
||||
os.replace(tmp, p)
|
||||
except OSError as e:
|
||||
log("⚠️ 序号登记写失败:%r" % e)
|
||||
return n
|
||||
|
||||
|
||||
# ===== Blender 看门狗(金钻 2026-09-30:卡到十分钟就关掉重开再渲)=====
|
||||
BLENDER_TIMEOUT = 600 # 1000 px 单张的总时长上限(10 分钟);更大的图按像素放宽,见 blender_timeout()
|
||||
BLENDER_STALL = 900 # 连续这么久 Blender **一个字都没吐** 才算真卡住(不分分辨率)
|
||||
BLENDER_RETRY = 1 # 卡住就杀掉重开一次;再卡就判失败,别死循环
|
||||
|
||||
|
||||
def blender_timeout(res):
|
||||
"""总时长上限随分辨率放宽:1000 → 600s,2048 → ~21 分钟,4096 → ~84 分钟。
|
||||
|
||||
⚠️ 2026-10-07:以前不分分辨率一律 600 秒。空艇 1000 px 要 70~130 秒,4096 像素多 16.8 倍,
|
||||
每次都在第 10 分钟被当成"卡住"杀掉、重开再杀 → 订单 YSPPVNXQ(空艇 4096)白白失败。
|
||||
真卡死靠 BLENDER_STALL 抓(渲染中 Blender 每隔几十秒就会刷一次 Sample 进度)。
|
||||
"""
|
||||
r = (int(res or DEFAULT_RES) / 1000.0) ** 2
|
||||
return int(BLENDER_TIMEOUT * max(1.0, r * 0.5))
|
||||
|
||||
|
||||
def _kill_tree(proc):
|
||||
"""连子进程一起杀。Blender 会开子进程,只杀父进程会留孤儿继续吃 GPU。
|
||||
|
||||
Windows 用 taskkill /T 杀整棵树;其它平台 fallback 到 proc.kill()
|
||||
—— 这样在 Linux 上也能跑测试。
|
||||
"""
|
||||
if os.name == "nt":
|
||||
try:
|
||||
subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)],
|
||||
capture_output=True, timeout=30)
|
||||
return
|
||||
except Exception as e:
|
||||
log("⚠️ taskkill 失败 pid=%s:%r(改用 proc.kill)" % (proc.pid, e))
|
||||
# POSIX:连**整个进程组**一起杀。
|
||||
# 只 kill 父进程的话,子进程还活着占着 stdout 管道 → communicate() 白等 30 秒(实测踩过)
|
||||
try:
|
||||
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
|
||||
except Exception:
|
||||
try:
|
||||
proc.kill()
|
||||
except Exception as e:
|
||||
log("⚠️ 杀进程失败 pid=%s:%r" % (proc.pid, e))
|
||||
|
||||
|
||||
SKIN_DIAG = [] # 最近几次渲染里"皮肤节点认了谁"的日志 —— 回传服务器,云端直接查
|
||||
# (2026-10-01:空艇模板渲染出默认皮肤,只能远程到宿主翻日志才知道它挑了谁)
|
||||
|
||||
|
||||
def note_skin_diag(tpl_key, out):
|
||||
"""从 Blender 输出里挑出与"皮肤节点判定"有关的几行,留着回传。"""
|
||||
for ln in (out or "").splitlines():
|
||||
s = ln.strip()
|
||||
if ("皮肤节点" in s) or ("贴图节点候选" in s) or s.startswith("皮肤 "):
|
||||
SKIN_DIAG.append("[%s] %s" % (tpl_key, s[:220]))
|
||||
if len(SKIN_DIAG) > 12:
|
||||
del SKIN_DIAG[:-12]
|
||||
|
||||
|
||||
# 从 Blender 的一行输出里抠进度:`Sample 12/128`、`Rendered 3/8 Tiles`… 抠不到就返回 None
|
||||
_PCT_RES = [
|
||||
re.compile(r"(?:Sample|Path Tracing Sample|Rendered|Rendering|Tiles)\D{0,20}?(\d+)\s*/\s*(\d+)"),
|
||||
re.compile(r"(\d+)\s*/\s*(\d+)\s*(?:tiles|samples)", re.I),
|
||||
]
|
||||
|
||||
|
||||
def blender_pct(line):
|
||||
"""Blender 那行输出 → 百分比;认不出来就 None(金钻 2026-10-04:进度要给买家看)。"""
|
||||
if not line or "/" not in line:
|
||||
return None
|
||||
for rx in _PCT_RES:
|
||||
m = rx.search(line)
|
||||
if not m:
|
||||
continue
|
||||
try:
|
||||
a, b = int(m.group(1)), int(m.group(2))
|
||||
except ValueError:
|
||||
continue
|
||||
if b > 0 and 0 <= a <= b:
|
||||
return int(a * 100.0 / b)
|
||||
return None
|
||||
|
||||
|
||||
def run_blender(cmd, timeout=None, retry=None, on_progress=None, stall=None):
|
||||
"""带超时看门狗的渲染。返回 (ok, 输出尾巴, 耗时秒, 说明)。
|
||||
|
||||
「关掉重新打开」= 直接重跑同一条命令 —— 工程每次都是**从干净模板新复制的副本**,
|
||||
所以重开等于全新开始,能救掉偶发卡死(GPU 驱动抽风、贴图读挂等)。
|
||||
|
||||
on_progress(pct):渲的过程中有进度就回调(金钻 2026-10-04)。它在**读输出的线程**上跑,
|
||||
所以:不许抛异常、不许阻塞太久(回调里已经有节流 + 超时)。
|
||||
"""
|
||||
timeout = timeout or BLENDER_TIMEOUT
|
||||
stall = stall or BLENDER_STALL
|
||||
retry =BLENDER_RETRY if retry is None else retry
|
||||
t_all = time.time()
|
||||
last = ""
|
||||
for attempt in range(retry + 1):
|
||||
try:
|
||||
kw = {}
|
||||
if os.name != "nt":
|
||||
kw["start_new_session"] = True # 自成进程组,超时能整组杀干净
|
||||
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
**kw)
|
||||
except OSError as e:
|
||||
return False, "", time.time() - t_all, "启动 Blender 失败:%r" % e
|
||||
# 输出交给**独立线程**读:一边攒全文,一边挑进度行回调,一边记"最后一次有输出"的时刻。
|
||||
# 主线程只负责等它结束 / 超时(总时长超限 或 太久没输出)。
|
||||
buf = []
|
||||
last_out = [time.time()]
|
||||
|
||||
def _pump():
|
||||
try:
|
||||
tail = ""
|
||||
# ⚠️ 按**字节**有多少读多少(read1)再增量解码:文本模式的 read(512) 会憋到凑满
|
||||
# 512 个字才返回,"最后一次有输出"就不准了(2026-10-07 测出来的)
|
||||
dec = codecs.getincrementaldecoder("utf-8")("replace")
|
||||
while True:
|
||||
raw = p.stdout.read1(4096)
|
||||
if not raw:
|
||||
break
|
||||
chunk = dec.decode(raw)
|
||||
last_out[0] = time.time()
|
||||
tail += chunk
|
||||
# ⚠️ Blender 的进度条是**回车原地刷新**的(`... Sample 4/128\r`),
|
||||
# 按"行"读(for line in stdout)压根读不到 —— 2026-10-04 金钻要
|
||||
# 「按 blender 的完成度」才发现。所以这里 \n 和 \r 都当分隔符切。
|
||||
while True:
|
||||
cuts = [i for i in (tail.find("\n"), tail.find("\r")) if i >= 0]
|
||||
if not cuts:
|
||||
break
|
||||
i = min(cuts)
|
||||
line, tail = tail[:i + 1], tail[i + 1:]
|
||||
buf.append(line)
|
||||
if on_progress:
|
||||
pct = blender_pct(line)
|
||||
if pct is not None:
|
||||
try:
|
||||
on_progress(pct)
|
||||
except Exception:
|
||||
pass
|
||||
if tail:
|
||||
buf.append(tail)
|
||||
except Exception:
|
||||
pass
|
||||
th = threading.Thread(target=_pump, daemon=True)
|
||||
th.start()
|
||||
t_run = time.time()
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
p.wait(timeout=5)
|
||||
break
|
||||
except subprocess.TimeoutExpired:
|
||||
now = time.time()
|
||||
if now - t_run > timeout:
|
||||
why = "总时长超过 %d 秒" % timeout
|
||||
elif now - last_out[0] > stall:
|
||||
why = "%d 秒没有任何输出" % stall
|
||||
else:
|
||||
continue
|
||||
raise subprocess.TimeoutExpired(cmd, timeout, output=why)
|
||||
th.join(timeout=15)
|
||||
out = "".join(buf)
|
||||
if p.returncode == 0:
|
||||
return True, out or "", time.time() - t_all, ""
|
||||
# ⚠️ 以前只留 400 字,结果失败时看不到自己打的 FATAL 行(2026-10-01 查空艇报错时踩到)
|
||||
_txt = (out or "").strip()
|
||||
_keys = [ln.strip() for ln in _txt.splitlines()
|
||||
if any(k in ln for k in ("FATAL", "MAKE-ORDER", "Error", "Traceback", "错误"))]
|
||||
last = "Blender 退出码 %s:%s" % (
|
||||
p.returncode,
|
||||
(" | ".join(_keys[-6:]) + " | " if _keys else "") + _txt[-1200:])
|
||||
log("渲染失败:%s" % last)
|
||||
except subprocess.TimeoutExpired as e:
|
||||
why = e.output or ("总时长超过 %d 秒" % timeout)
|
||||
# 卡在哪一步留个底(以前超时直接丢掉输出,事后完全查不到)
|
||||
_seen = [ln.strip() for ln in "".join(buf).replace("\r", "\n").splitlines() if ln.strip()]
|
||||
log("⚠️ 渲染卡住(%s)—— 杀掉,重新打开再渲|最后输出:%s" % (why, " | ".join(_seen[-3:])[-600:]))
|
||||
_kill_tree(p)
|
||||
try:
|
||||
p.wait(timeout=10) # 收尸;整组杀过就该立刻返回
|
||||
except Exception:
|
||||
pass
|
||||
last = "渲染卡住(%s,已杀掉重开)" % why
|
||||
if attempt < retry:
|
||||
log("↻ 重开渲染(第 %d 次尝试)" % (attempt + 2))
|
||||
return False, "", time.time() - t_all, last
|
||||
|
||||
|
||||
def render_one(tpl_key, skin_path, order_meta, res=DEFAULT_RES, arm="auto", on_progress=None):
|
||||
"""渲染一张,返回 (成功?, png路径 或 错误信息)
|
||||
|
||||
arm:这张皮肤的臂型(auto/classic/slim)。多皮肤单里**每张皮肤各自一个臂型**,
|
||||
由调用方从服务器给的皮肤清单里带下来(金钻 2026-10-01:以前压根没传,买家手改无效)。
|
||||
"""
|
||||
fname = TEMPLATES.get(tpl_key)
|
||||
if not fname:
|
||||
return False, "未知模板 key:%s" % tpl_key
|
||||
tpl = os.path.join(CFG["tpl_root"], fname)
|
||||
if not os.path.exists(tpl):
|
||||
return False, "模板文件不存在:%s" % tpl
|
||||
blender = find_blender()
|
||||
if not blender:
|
||||
return False, "找不到 blender.exe(请在 config.json 里指定 blender 路径)"
|
||||
if not os.path.exists(CFG["make_order"]):
|
||||
return False, "找不到 make_order.py:%s" % CFG["make_order"]
|
||||
|
||||
out_name = tpl_base(tpl_key)
|
||||
# 文件夹用成品名,皮肤先放进去;工程走临时目录,渲完删(金钻:不留 .blend)
|
||||
order_dir, base = prepare_out_dir(CFG["archive"], tpl_key, res, skin_path)
|
||||
cmd = [blender, "-b", "--factory-startup", "--python", CFG["make_order"], "--",
|
||||
"--template", tpl, "--skin", skin_path, "--arm", arm or "auto",
|
||||
"--orders-dir", CFG["archive"], "--out-dir", order_dir, "--res", str(int(res))]
|
||||
# 某个模板的皮肤材质名固定不下来时,可以在 config.json 里钉死:
|
||||
# "skin_materials": {"airship": "材质名"}
|
||||
# (2026-10-01:空艇模板自动找皮肤节点找错,先留好这个后门口子)
|
||||
_sm = (CFG.get("skin_materials") or {}).get(tpl_key)
|
||||
if _sm:
|
||||
cmd += ["--skin-material", _sm]
|
||||
log("渲染 %s(模板 %s,臂型 %s,%d px)" % (tpl_key, fname, arm or "auto", int(res)))
|
||||
okr, tail, dt, note = run_blender(cmd, timeout=blender_timeout(res), on_progress=on_progress)
|
||||
note_skin_diag(tpl_key, tail) # 不管成没成,先把"皮肤节点认了谁"记下来
|
||||
if not okr:
|
||||
return False, note
|
||||
|
||||
# 找成品:优先 <名称>.png(命名规则见 out_base),其次目录里最新的 png
|
||||
cand = os.path.join(order_dir, base + ".png")
|
||||
if not os.path.exists(cand):
|
||||
pngs = [f for f in os.listdir(order_dir) if f.lower().endswith(".png")]
|
||||
pngs = [f for f in pngs if "无压缩" not in f and f != "1000.png"] or pngs
|
||||
if not pngs:
|
||||
return False, "渲染完成但没找到 png(看 %s)" % order_dir
|
||||
cand = os.path.join(order_dir, sorted(pngs, key=lambda f: os.path.getmtime(
|
||||
os.path.join(order_dir, f)))[-1])
|
||||
|
||||
# 渲染成功才领序号(失败的图不占号),并登记进专门的文件
|
||||
seq = next_seq({
|
||||
"来源": "网页订单",
|
||||
"订单号": order_meta.get("oid"),
|
||||
"兑换码": order_meta.get("codes") or [],
|
||||
"模板": out_name,
|
||||
"成品文件夹": os.path.basename(order_dir),
|
||||
"分辨率": res,
|
||||
"耗时秒": round(dt, 1),
|
||||
})
|
||||
|
||||
# 金钻要的留档:时间 / 序号 / 兑换码
|
||||
info = {
|
||||
"序号": seq,
|
||||
"订单号": order_meta.get("oid"),
|
||||
"兑换码": order_meta.get("codes") or [],
|
||||
"模板": out_name,
|
||||
"模板key": tpl_key,
|
||||
"成品文件夹": os.path.basename(order_dir),
|
||||
"分辨率": res,
|
||||
"皮肤文件": "skin.png",
|
||||
"客户提交时间": order_meta.get("created"),
|
||||
"渲染完成时间": datetime.now().isoformat(timespec="seconds"),
|
||||
"渲染耗时秒": round(dt, 1),
|
||||
"手臂规格": (arm if arm and arm != "auto" else order_meta.get("arm")),
|
||||
"条款版本": order_meta.get("terms_v") or TERMS_VERSION,
|
||||
}
|
||||
try:
|
||||
with open(os.path.join(order_dir, "订单信息.json"), "w", encoding="utf-8") as f:
|
||||
json.dump(info, f, ensure_ascii=False, indent=1)
|
||||
except OSError as e:
|
||||
log("写 订单信息.json 失败:%r" % e)
|
||||
# 无压缩版(make_order 默认就会生成):<名称>无压缩版.png
|
||||
unc = os.path.join(order_dir, out_base(tpl_key, res) + UNC_SUFFIX + ".png")
|
||||
if not os.path.exists(unc):
|
||||
cands = [f for f in sorted(os.listdir(order_dir))
|
||||
if f.lower().endswith(".png") and UNC_SUFFIX in f]
|
||||
unc = os.path.join(order_dir, cands[0]) if cands else None
|
||||
if not unc or not os.path.exists(unc):
|
||||
unc = None
|
||||
log("⚠️ 无压缩版没生成,这次只交标准版")
|
||||
log("完成 %s → %s(序号 %03d,%.1fs,%s)" % (tpl_key, cand, seq, dt, "两张" if unc else "一张"))
|
||||
return True, {"std": cand, "unc": unc, "seq": seq, "sec": round(dt, 1)}
|
||||
# seq = 留档序号(小票/订单信息里印);sec = 这张渲了多久(服务器拿它估下一单的时间)
|
||||
|
||||
|
||||
def deliver_names_for(skin_i, tk, res, dedup=True):
|
||||
"""第 skin_i 张皮肤、模板 tk 的交付名。
|
||||
|
||||
⚠️ 只有**同一个模板被多张皮肤用到**时才需要加 -2/-3(不加会在服务器同一个目录里互相覆盖)。
|
||||
不同皮肤用不同模板(金钻的常见用法:A 出麦田、B 出樱花)就保持干净的名字。
|
||||
"""
|
||||
sn, un = deliver_names(tk, res)
|
||||
if skin_i <= 0 or not dedup:
|
||||
return sn, un
|
||||
k = "-%d" % (skin_i + 1)
|
||||
|
||||
def ins(n):
|
||||
return (n[:-4] + k + ".png") if n.lower().endswith(".png") else (n + k)
|
||||
return ins(sn), ins(un)
|
||||
|
||||
|
||||
def handle_order(o):
|
||||
oid = o["oid"]
|
||||
tpls = o.get("templates") or []
|
||||
order_res = int(o.get("res") or CFG.get("res") or DEFAULT_RES)
|
||||
log("领到订单 %s:%d 张 %s" % (oid, len(tpls), ",".join(tpls)))
|
||||
|
||||
# ---- 皮肤清单(金钻 2026-10-01:多皮肤单 = **每张皮肤 × 每个模板**出图)----
|
||||
# 服务器在 /claim 里把清单带下来:[{id,fileName,arm}]。老单没有就按 1 张算。
|
||||
skins = o.get("skins") or [{"id": "s1", "fileName": "skin.png", "arm": "auto"}]
|
||||
tpls = o.get("templates") or []
|
||||
order_res = int(o.get("res") or CFG.get("res") or DEFAULT_RES)
|
||||
# 只重渲勾选的那几张(金钻 2026-10-04:「不需要重渲的就不用再重渲了,费力不讨好」)
|
||||
# 服务器给了清单就只干这几个模板 —— 换皮肤时清单是空的,那就还是整单重出。
|
||||
redo_tpls = [t for t in (o.get("redo_tpls") or []) if t]
|
||||
if redo_tpls:
|
||||
for sk in skins:
|
||||
sk["tpls"] = [t for t in (sk.get("tpls") or tpls) if t in redo_tpls]
|
||||
log("这一单只重渲:%s" % "、".join(redo_tpls))
|
||||
# ⚠️ 张数 = **各皮肤自己挑的模板加起来**(金钻 2026-10-01:不是乘法)
|
||||
# ⚠️ 只重渲一部分时,total 要**加上保留下来的那几张** —— 服务器是按 total 判断"收满了"的,
|
||||
# 少了这个数就会在最后一张还没传完时提前标完成(2026-10-04 自测踩到,少了一张无压缩版)。
|
||||
_keep = int(o.get("keep_n") or 0) if redo_tpls else 0
|
||||
plan = _keep + sum(len(sk.get("tpls") or tpls) for sk in skins) * 2
|
||||
log("领到订单 %s:%d 张皮肤,共 %d 张图(%s)"
|
||||
% (oid, len(skins), plan // 2,
|
||||
"; ".join("%s→%s" % (sk.get("fileName") or "?", "、".join(sk.get("tpls") or tpls))
|
||||
for sk in skins)))
|
||||
|
||||
work = os.path.join(HERE, "work")
|
||||
os.makedirs(work, exist_ok=True)
|
||||
|
||||
# 同一个模板被多张皮肤用到 → 交付名才加 -2/-3(不同模板就保持干净名字)
|
||||
cnt = {}
|
||||
for _sk in skins:
|
||||
for _tk in (_sk.get("tpls") or tpls):
|
||||
cnt[_tk] = cnt.get(_tk, 0) + 1
|
||||
dup_tpls = set(k for k, n in cnt.items() if n > 1)
|
||||
|
||||
# ---- 进度上报(金钻 2026-10-04:买家要看得见渲到哪了)----
|
||||
# 报进度**绝不能影响出图**:节流 2 秒一次,失败一律吞掉。
|
||||
def report_progress(idx, total, pct, tpl=""):
|
||||
try:
|
||||
http("/progress", {"oid": oid, "idx": idx, "total": total,
|
||||
"pct": pct, "tpl": tpl}, timeout=20)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ok_n, errs = 0, []
|
||||
img_i = 0
|
||||
for si, sk in enumerate(skins):
|
||||
sid = sk.get("id") or ("s%d" % (si + 1))
|
||||
# 每张皮肤各自下载、各自臂型(A 可能粗臂、B 可能细臂)
|
||||
skin = os.path.join(work, "skin_%s_%s.png" % (oid, sid))
|
||||
st, data = http("/skin/%s/%s" % (oid, sid), raw=True, timeout=60)
|
||||
if st != 200 or not data:
|
||||
errs.append("皮肤 %s:服务器取皮肤失败 HTTP %s" % (sid, st))
|
||||
log("皮肤 %s 取不下来 HTTP %s" % (sid, st))
|
||||
continue
|
||||
with open(skin, "wb") as f:
|
||||
f.write(data)
|
||||
arm = (sk.get("arm") or "auto")
|
||||
|
||||
# 这张皮肤**只出它自己挑的模板**(没写就退回订单级那份,兼容老单)
|
||||
for tk in (sk.get("tpls") or tpls):
|
||||
img_i += 1
|
||||
_last = [0.0]
|
||||
|
||||
def _prog(pct, _tk=tk, _i=img_i, _last=_last):
|
||||
t = time.time()
|
||||
if pct < 100 and t - _last[0] < 2.0: # 节流:2 秒最多报一次
|
||||
return
|
||||
_last[0] = t
|
||||
report_progress(_i, plan // 2, pct, _tk)
|
||||
|
||||
report_progress(img_i, plan // 2, 0, tk) # 这张开始了
|
||||
try:
|
||||
ok, res = render_one(tk, skin, o, order_res, arm=arm, on_progress=_prog)
|
||||
except subprocess.TimeoutExpired:
|
||||
ok, res = False, "渲染超时(看门狗已重开过一次仍卡住)"
|
||||
except Exception as e:
|
||||
ok, res = False, "异常 %r" % e
|
||||
if not ok:
|
||||
errs.append("%s(皮肤%d):%s" % (tk, si + 1, res))
|
||||
log("失败 %s" % res)
|
||||
continue
|
||||
# 一张模板交两个文件:标准压缩 + 无压缩版(金钻:两张都发顾客)
|
||||
sn, un = deliver_names_for(si, tk, order_res, dedup=(tk in dup_tpls))
|
||||
files = [("标准压缩", sn, res.get("std")),
|
||||
("无压缩(16bit)", un, res.get("unc"))]
|
||||
for kind, name, path in files:
|
||||
if not path:
|
||||
continue
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
png = base64.b64encode(f.read()).decode()
|
||||
except OSError as e:
|
||||
errs.append("%s(%s):读图失败 %r" % (tk, kind, e))
|
||||
continue
|
||||
# 一次一个文件回传;total = 这一单最终会交回的文件总数
|
||||
# tries=3:图上一次上传要几 MB~十几 MB,网络抖一下很常见,别为这个白渲一遍
|
||||
st, j = http("/finish", {"oid": oid, "total": plan,
|
||||
"results": [{"tpl": tk, "name": name, "png": png,
|
||||
"kind": kind, "skin": sid,
|
||||
# 耗时只跟「标准压缩」报一次:两个文件报两遍会把样本记重
|
||||
"sec": (res.get("sec") if kind == "标准压缩" else None),
|
||||
"seq": res.get("seq")}]},
|
||||
timeout=300, tries=3, gap=8)
|
||||
if st == 200 and j.get("ok"):
|
||||
log("回传 %s 皮肤%s [%s](服务器已收 %s / 计划 %d)"
|
||||
% (tk, sid, kind, j.get("n"), plan))
|
||||
else:
|
||||
errs.append("%s-%s:回传失败 %s" % (tk, kind, (j or {}).get("error")))
|
||||
ok_n += 1
|
||||
|
||||
if ok_n == 0:
|
||||
http("/fail", {"oid": oid, "note": ("全部渲染失败:" + ";".join(errs))[:280],
|
||||
"diag": SKIN_DIAG[:8], "log_tail": "\n".join(errs)[-3800:]})
|
||||
log("订单 %s 全部失败" % oid)
|
||||
return
|
||||
# ⚠️ 有失败时必须有始有终:否则 files < total,单子会永远卡在 working,
|
||||
# 45 分钟后被当成"渲染机中断"退回队列 → 无限重试。这里显式收单。
|
||||
http("/finish", {"oid": oid, "close": True, "diag": SKIN_DIAG[:8],
|
||||
"note": ("部分失败:" + ";".join(errs))[:280] if errs else "",
|
||||
"results": []}, tries=3, gap=8)
|
||||
log("订单 %s 处理完毕:成功 %d/%d%s" % (oid, ok_n, len(tpls), "(有失败)" if errs else ""))
|
||||
|
||||
|
||||
def single_instance():
|
||||
s = socket.socket()
|
||||
try:
|
||||
s.bind(("localhost", LOCK_PORT))
|
||||
s.listen(1)
|
||||
return s
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
load_cfg()
|
||||
once = "--once" in sys.argv # 只跑一轮就退出(手动补单 / 测试用)
|
||||
if not once:
|
||||
lock = single_instance()
|
||||
if not lock:
|
||||
log("已经有一个 worker 在跑了,这次退出")
|
||||
return
|
||||
log("渲染机上线 | 服务器 %s | 模板目录 %s | 留档 %s"
|
||||
% (CFG["server"], CFG["tpl_root"], CFG["archive"]))
|
||||
host = socket.gethostname()
|
||||
# 心跳(在线检查)与领单**分开计时**:
|
||||
# 心跳 = 服务器判断"渲染机还在不在"的唯一依据,也是唯一会造成误判的地方;
|
||||
# 领单 = 买家体验,慢一分钟买家就多等一分钟。
|
||||
# 默认心跳 **600 秒(10 分钟)**(金钻 9-30:有人来了网页会立刻查一次,所以不用频繁上报)。
|
||||
# ⚠️ 代价:渲染机真的挂了,最长要 25 分钟才判定为离线(见服务器 OFFLINE_AFTER)。
|
||||
# 启动时会立刻发一次心跳,所以"金钻刚开机"这种情形是即时准的。
|
||||
hb_every = int(CFG.get("hb_every") or 600) # 在线检查 10 分钟一次(金钻 9-30 定)
|
||||
poll = int(CFG.get("poll") or 20)
|
||||
# ⚠️⚠️ 心跳必须**自己一个线程**(金钻 2026-10-01 反馈:「开着电脑还显示设备离线,刷几次才正常」)。
|
||||
# 原来心跳和领单/渲染挤在同一个循环里 —— 一渲就是几十秒到十几分钟(4096 要 10 分钟),
|
||||
# 这期间心跳发不出去;要是连着几单、或某次上传卡住,超过服务器 OFFLINE_AFTER(1500 秒)
|
||||
# 就被判「离线」,**电脑明明开着、还在干活**。
|
||||
def hb_loop():
|
||||
while True:
|
||||
try:
|
||||
st, j = http("/hb", {"host": host}, timeout=30)
|
||||
if st != 200:
|
||||
log("心跳失败 HTTP %s" % st)
|
||||
except Exception:
|
||||
log("心跳异常:\n" + traceback.format_exc()[-400:])
|
||||
time.sleep(hb_every)
|
||||
threading.Thread(target=hb_loop, daemon=True).start()
|
||||
while True:
|
||||
try:
|
||||
st, o = http("/claim", {}, timeout=60)
|
||||
if st == 403:
|
||||
log("令牌不对(config.json 里的 token 要跟服务器 worker_token 一致)")
|
||||
time.sleep(300)
|
||||
continue
|
||||
if st == 200 and o.get("order"):
|
||||
handle_order(o["order"])
|
||||
except Exception:
|
||||
log("轮询异常:\n" + traceback.format_exc()[-800:])
|
||||
if once:
|
||||
log("--once:跑完这一轮就退出")
|
||||
return
|
||||
time.sleep(poll)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,215 @@
|
||||
# 交接说明 · 工具后端(渲染机 + 本机开单工具 + 开单后台)
|
||||
|
||||
> **交付方**:苏达(网站运维与技术提供)
|
||||
> **收件方**:外部协作者
|
||||
> **日期**:2026-10-05
|
||||
> **一句话**:这是跑在**店主自己那台 Windows 电脑**上的一整套工具:渲染机、
|
||||
> 局域网开单后台、纯本机开单工具。请你重点看**健壮性与"静默失败"**,
|
||||
> 并给我们**问题分析 + 改正意见**(见最后一节)。
|
||||
|
||||
---
|
||||
|
||||
## 一、这一份是什么
|
||||
|
||||
跟「网站后端」配套的**本地侧**。因为店里那台电脑没有公网入口,所以它**只做出站**:
|
||||
主动来服务器领单、渲染、回传。
|
||||
|
||||
```
|
||||
<WORKER_DIR>\
|
||||
├─ ys_worker.py 渲染机主程序(开机自启的计划任务;轮询领单 → 调 Blender → 回传)
|
||||
├─ ys_admin.py 开单后台(局域网面板:待处理 / 订单 / 卡密 / 福利券 / 呼叫·反馈),自带 PIN 锁
|
||||
├─ ys_local.py 纯本机开单工具(不联网、不上传、不要卡密;拖皮肤→勾模板→出图)
|
||||
├─ local.html 本机开单工具的页面(ys_local.py 内嵌服务它)
|
||||
├─ make_order.py Blender 出图脚本(渲染机调用它;改模板/分辨率/臂型都在这)
|
||||
├─ install_worker.ps1 / chk_worker.ps1 / pack_archive.ps1
|
||||
└─ run_*.bat / stop_*.bat / open_local.bat / show_log.bat
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 二、技术栈与运行方式
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 语言 / 依赖 | **Python 3,纯标准库**(`ys_admin.py` 连 HTML 都内嵌在单文件里) |
|
||||
| 渲染 | Blender **命令行后台模式**(`-b --factory-startup --python make_order.py`) |
|
||||
| 进程托管 | Windows 计划任务(**开机自启**);面板另有独立计划任务 |
|
||||
| 网络 | **只做出站**(来服务器领单/回传);本机工具与面板只监听本机/局域网 |
|
||||
| 关键约束 | ⚠️ **任何时刻只允许一个 Blender 在跑** —— 同时跑两个会把机器顶满(渲染队列是硬约束,不是优化) |
|
||||
|
||||
---
|
||||
|
||||
## 三、三条链路
|
||||
|
||||
### ① 渲染机(`ys_worker.py`)
|
||||
```
|
||||
每 20s POST /hb(心跳) ← 心跳在**独立线程**里,不然一渲染就发不出去被判离线
|
||||
POST /claim(领单)
|
||||
GET /api/skin/<单号> ← 取买家皮肤(必须带 worker token)
|
||||
Blender 渲染(一张一次 POST /finish)
|
||||
中途每 2s POST /progress ← 抠 Blender 输出的百分比
|
||||
```
|
||||
|
||||
### ② 开单后台(`ys_admin.py`,局域网)
|
||||
**2026-10-05 页面重写**:样子跟 2026 版网站统一(白光 + 毛玻璃卡片 + MC 方块按钮),按「要干的事」分页:
|
||||
|
||||
| 页 | 干什么 | 新增 / 变化 |
|
||||
|---|---|---|
|
||||
| **待处理**(默认打开) | 渲染机在不在、队列、待激活、卡密数一眼看完;下面是**要你动手的**:买家说付好了的单(排最前)、渲染失败的单、没处理的呼叫 | 失败的单有「退回重渲」按钮(以前只能写「喊苏达用 admin.py」);呼叫直接在这里看、点「处理过了」 |
|
||||
| 订单 | 全部订单,按状态筛 + **搜索**(单号 / 卡密 / 模板 / 备注) | 每单能**写备注**(服务器早有接口,以前面板上没按钮) |
|
||||
| 卡密 | 左:生成(设置下面实时出一句「会生成什么」);右:卡密库,按状态筛 + **搜索**(码 / 订单号 / 批次 / 平台) | 能**停用 / 启用**、**改张数**(服务器早有 `code-edit`,以前面板上没按钮) |
|
||||
| 福利券 | 左:开一批;右:已开的批次(复制券码 / 补货 / 收摊 / 领取情况) | 只改了排版 |
|
||||
| 呼叫·反馈 | 买家「呼叫金钻」、反馈、渲染机报的「部分失败」 | **新页**:以前只能 ssh 上去 `admin.py calls` 看 |
|
||||
| 开单工具 | 本机开单工具(iframe,第一次点开才加载) | 不变 |
|
||||
|
||||
- 手机上导航放到底部;电脑上在左边。顶栏的状态、导航上的角标每 30 秒自动刷新(页面藏在后台时不刷)。
|
||||
- **自带 PIN 锁**:首次打开自己设 4~12 位数字,存**加盐 sha256**(不是明文),12 小时免输;校验在服务端,直接打接口也会 401。
|
||||
- 面板新增的本机接口(都要 PIN,都是原样转给服务器 `/api/admin/*`):
|
||||
`GET /api/codes`、`GET /api/calls`、`POST /api/retry`、`POST /api/note`、`POST /api/code-edit`、`POST /api/call-done`。
|
||||
老接口(`/api/state`、`/api/gen`、`/api/activate`、`/api/void`、`/api/orders`、`/api/gifts`、`/api/gift/*`、`/api/savecsv`、PIN 那三个)**一个没动**。
|
||||
- ⚠️ 用到了服务器这次新加的管理接口(`calls` / `call-done` / `retry` / `codes?q=`),所以**服务器要先升级**;
|
||||
面板先升、服务器没升的话,这几个按钮会提示「服务器回 404」,别的照常能用。
|
||||
- 怎么验证的:用现编的假数据(10 单覆盖全部状态、30 多张卡密、3 条呼叫、1 批福利券)起一份真服务器 + 真面板,
|
||||
浏览器里(电脑 1366 宽 + 手机 390 宽)把每一页点了一遍:生成卡密、搜订单、激活、退回重渲、停用卡密、标呼叫已处理都走通,
|
||||
没有报错、没有横向滚动;不带 PIN 打面板接口 → 401,不带令牌直接打服务器管理接口 → 403。
|
||||
|
||||
### ③ 纯本机开单(`ys_local.py` + `local.html`,只监听回环)
|
||||
给**平台单**(聊天里成交的买家)用:拖皮肤 → 同一套质检 → 勾模板 → 本机 Blender 出图 → 下载。
|
||||
**不联网、不上传、不要卡密**,所以网站上根本没有入口(避免卡密被暴力试)。
|
||||
|
||||
**2026-10-05 页面重写**(`local.html`;`ys_local.py` 和本机接口一个没动):
|
||||
- 样子跟网站 / 开单后台统一;电脑上左边「① 皮肤 + 质检」、右边「② 模板 + 分辨率 + 备注 + 开始」,出图结果在下面整行;手机上从上往下排。
|
||||
- 补上了原来没写样式的两处:**分辨率选择**(原来 `.seg` / `label.sel` 没有 CSS,看着像一行纯文字)、「清空」「再开一单」按钮(原来用的 `.ghost` 没定义)。
|
||||
- 模板卡片:按勾的顺序标 1 / 2 / 3(出图就是这个顺序);每个模板一个颜色 + 小图标(还没有实拍预览图,以后有了把 `thumb` 里的 svg 换成 `<img>`)。
|
||||
- 「开始」上面实时一句话:出几张、哪几个模板、多大、大概多久;勾完、皮肤过了质检,步骤号变绿。
|
||||
- 「清空」现在真的会清皮肤(原来这个按钮**没绑任何事件**,点了没反应);「再开一单」照旧只清模板和备注、留着皮肤(同一个买家常常再加几张)。
|
||||
- 拖到页面别处也能收皮肤(原来拖偏了浏览器会直接打开那张图、把工具页换掉);买家说明多了一个「复制这段话」按钮。
|
||||
- 质检结果去掉了每行前面的小圆点,改成「通过 / 注意 / 不通过」色块。
|
||||
- 怎么验证的:写了一个假的本机服务(假装渲染,每张 1.4 秒),浏览器在电脑宽 / 手机宽各走一遍:选皮肤 → 勾 3 个模板 → 选 2048 → 渲染 → 出 3 张卡片各两个下载,无报错、无横向滚动。**没在真 Blender 上跑**(页面发给本机接口的字段和原来一样)。
|
||||
|
||||
---
|
||||
|
||||
## 四、几个刻意做出的设计(欢迎质疑)
|
||||
|
||||
| 设计 | 为什么 |
|
||||
|---|---|
|
||||
| 渲染串行(一个队列一个消费线程) | 两个 Blender 同时跑会把机器顶满 |
|
||||
| Blender 超时 600s,卡住就**连整个进程组一起杀**再重跑 | 只杀父进程的话子进程还占着管道,`communicate()` 会白等 30 秒 |
|
||||
| 命名逻辑**只写两处且必须一致**(`make_order.py` 与 `ys_worker.py`) | 散落硬编码过,判过一次 bug |
|
||||
| 未压缩版**不重渲**:从已渲好的渲染结果直接另存 | 省一次完整渲染(一张约 37 秒);失败再回退重渲 |
|
||||
| 质检代码只有一份(前后端共用同一个 js) | 两边判定一旦漂移,会出现「网页说能渲、本机渲不出来」这种最难查的 bug |
|
||||
| 部署脚本**先显式杀旧进程再起新的** | 计划任务的"运行"对已在跑的实例不替换 → 新代码静默不生效 |
|
||||
| 成品不保留 `.blend` 工程 | 太大,磁盘受不住;工程渲完立刻删 |
|
||||
|
||||
---
|
||||
|
||||
## 五、⚠️ 脱敏说明(**这份也不能直接跑**)
|
||||
|
||||
| 类别 | 替换成 |
|
||||
|---|---|
|
||||
| 站点域名 / 支付平台域名 | `shop.example.com` / `pay-platform.example` |
|
||||
| 端口 | 中性数字(**不是真值**) |
|
||||
| 程序 / 数据 / 工作目录 | `<WORKER_DIR>` / `<DATA_DIR>` / `<APP_DIR>` |
|
||||
| Windows 盘符路径 | `<WIN-PATH>` / `<ARCHIVE_DIR>` / `<TOOLS_DIR>` / `<PROGRAM_DIR>` |
|
||||
| 局域网与出口 IP | `<LOCAL-IP>` / `<HOME-LAN-IP>` |
|
||||
| 通配绑定 | `<ALL-INTERFACES>` |
|
||||
| 跳板与密钥文件名 | `<SSH-KEY>` / `<跳板>` |
|
||||
|
||||
**保留未换的**:`localhost`、分辨率常量 `1000/1024/2048/4096`、品牌笔名。
|
||||
|
||||
**包里没有的**:真实卡密/订单/皮肤/成品、两把令牌、模板工程(**模板单独给**,见包根目录说明)、
|
||||
任何密钥凭据、私有仓库地址。
|
||||
|
||||
---
|
||||
|
||||
## 六、⚠️ 已知缺口(我们知道的,不用你重复发现)
|
||||
|
||||
1. **没有内容审核** —— 结构合法的 PNG 但内容违规照样能过(技术拦不住,靠人)。
|
||||
2. **留档只增不减** —— 成品的永久留档目录会慢慢攒满盘。
|
||||
3. **预览水印是"防君子"** —— 512 宽 + 平铺水印,拦不住认真截图去水印的人。
|
||||
4. **渲染机真挂了,最长要 25 分钟才判定离线**(心跳周期 × 容错次数的代价)。
|
||||
|
||||
---
|
||||
|
||||
## 七、⭐ 我们要你交给我们的东西(**这一份的主要目的**)
|
||||
|
||||
同样请回一份 `回执-<你的名字>.md`,含三部分:
|
||||
|
||||
> 📋 **格式不用自己起** —— 仓库根目录有一份 `回执模板.md`,照着填就行。
|
||||
|
||||
1. **问题分析** —— 你看到的 bug、健壮性问题、坏味道。**特别欢迎**指这几类:
|
||||
- **静默失败**:出错了但看着"一切正常"的地方(我们被这个坑过好几次)
|
||||
- **状态不一致**:显示与真实不一致(比如界面说排队中、实际没领单)
|
||||
- **部署/重启类**:改了不生效、旧进程没替换、两边版本漂移
|
||||
- **并发/时序**:心跳与渲染抢资源、超时与重试互相打架
|
||||
2. **改正意见** —— 每条说清**怎么改 + 代价**。
|
||||
3. **你改了什么** —— 逐条列(同网站后端那份的格式):
|
||||
```
|
||||
文件 / 函数: 为什么改: 改成什么:
|
||||
⚠️ 有没有动接口路径 / 请求响应字段 / 数据格式(动了必须单独标):
|
||||
怎么验证的:
|
||||
```
|
||||
|
||||
**另外请你顺手回答两个具体问题**:
|
||||
- `ys_worker.py` 的**部署不生效**(旧进程还在跑)这类问题,除了"先杀再起",有没有更稳的办法?
|
||||
- 渲染队列现在是**单线程串行**。如果要在一台机器上同时支持多单,
|
||||
你觉得该怎么做才**不会把机器顶满**?(先说方案,不用实现)
|
||||
|
||||
---
|
||||
|
||||
## 八、我们的思路与方法(**请你连这套做法一起评**)
|
||||
|
||||
代码能看出一部分;**为什么这么做、踩过什么坑**,代码里看不到。这一节补上,
|
||||
**希望你连"做法"本身一起挑** —— 整套思路要是错的,比某个函数写错更要紧。
|
||||
|
||||
### 8.1 我们给自己定的硬规矩
|
||||
|
||||
| 规矩 | 为什么 |
|
||||
|---|---|
|
||||
| **机器只做出站**:店里那台没有公网入口,所以服务器从不连它,全靠它自己定时来拉 | 不给家用网络开任何入站口子;代价是"渲染机真挂了,最长要过一会儿才判离线" |
|
||||
| **任何时刻只允许一个渲染在跑** | 两个同时跑会把机器顶满 —— 这是**硬约束不是优化**,所以做成 FIFO 队列 |
|
||||
| **渲染串行、队列单消费者** | 同上;宁可让买家多等,也不让机器崩 |
|
||||
| **命名/路径这类"两边都要知道"的规则只写两处且必须一致** | 散落硬编码过一次,修的时候漏了地方 |
|
||||
| **质检逻辑只有一份,前后端共用** | 两边判定一旦漂移,会出现"网页说能渲、本机渲不出来"这种最难查的 bug |
|
||||
| **不保留巨大的中间产物** | 工程文件渲完立刻删(磁盘受不住);需要保留的从已渲结果直接另存,不重渲一遍 |
|
||||
|
||||
### 8.2 我们干活的方法(改这套工具时照着来)
|
||||
|
||||
1. **长驻进程必须交给任务计划/系统托管**,不能用"临时起一个"。
|
||||
踩过:从远程会话里起的进程,**会话一断就被系统回收** —— 装完看着"已运行",
|
||||
几十秒后就没了,订单干等在队列里没人领。表现是"看起来一切正常"。
|
||||
2. **部署 = 先明确杀掉旧进程,再起新的**。多数"重启/运行"命令对**已在运行的实例不会替换**,
|
||||
于是新代码静默不生效。部署后必须核对**进程的启动时间**,光看"在线"没用(旧进程也报在线)。
|
||||
3. **判断"活没活"要看真实产物**,不看脚本自述。`Set-Content` 类写入要回读、看字节数;
|
||||
端口要真连一次;图要真存在。
|
||||
4. **卡死要连整个进程组一起杀**。只杀父进程的话子进程还占着输出管道,读取方会白等很久
|
||||
(实测:只杀父 → 64 秒才返回;连组杀 → 4 秒)。
|
||||
5. **进度要自己吐日志,并且按 `\r` 和 `\n` 都切**。渲染器的进度条是**原地回车刷新**的,
|
||||
按 `\n` 逐行读会**一条都读不到**(看着像"没有进度",其实进度一直在刷)。
|
||||
6. **每台机器的配置里不放凭据**,凭据由部署流程单独推(密钥与规则分离)。
|
||||
7. **中文不要进 `.bat`**,中文一律放带 BOM 的 `.ps1` 里;编码错了会**连累后面的行**一起崩。
|
||||
|
||||
### 8.3 我们付过学费的坑("不要重复踩"清单)
|
||||
|
||||
- **"改完不生效"是这套系统最高频的坑**,而且从不报错:旧进程在跑、计划任务不替换、
|
||||
两边版本漂移 —— 三种都会表现成"功能没反应"。
|
||||
- **静默半死**:某一步抛异常 → 后面的渲染链全断 → 页面看着"就是没反应",
|
||||
只有开发者控制台才有线索。所以我们加了"出错要能看到原因"的要求。
|
||||
- **从 A 推导出 B 的函数,在别处读 B 之前必须先调一次**(同一个形状我们踩了两次)。
|
||||
- **同名文件被覆盖 + 地址不变 = 用户以为没更新**(缓存/同名双杀)。
|
||||
|
||||
### 8.4 我们最想要你评的三件"做法"
|
||||
|
||||
1. **部署不生效**这类问题,除了"先杀再起",**有没有更稳的机制**?
|
||||
2. **单机多单**:现在是严格串行。如果要在同一台机器上支持多单,你会怎么设计才**不会把机器顶满**?
|
||||
3. **"纯标准库单文件"**这套(零依赖零安装、小机器跑得动)换你你会不会换技术栈?请直说。
|
||||
|
||||
---
|
||||
|
||||
## 九、边界
|
||||
|
||||
- **私有交付,请勿外传 / 勿公开 / 勿镜像**。
|
||||
- 占位值保持原样,**不要**替换成真实地址再交回来。
|
||||
- 你可以自由重构,但**动了接口/数据格式要按第 7 节单独标出来** ——
|
||||
这套工具跟服务器那份代码是**两台机器上各一份**,不同步会静默坏掉。
|
||||
- 有看不懂的先问再改,别猜。
|
||||
@@ -0,0 +1,114 @@
|
||||
# 回执 · Claude(受 ywsabc2 委托)· 2026-10-05 · 工具后端
|
||||
|
||||
> 范围:`backend-tools/`(ys_worker.py / ys_admin.py / ys_local.py / deploy.py,make_order.py 只扫了命名部分)。
|
||||
> 网站后端那份更长、问题更多:`backend-site/回执-Claude.md`。两份里对 Q3/Q4/Q5 的回答是同一套,这里只写结论。
|
||||
> 行号指交付时的原版(提交 `c6034e9`)。
|
||||
|
||||
## 0. 一句话总结
|
||||
|
||||
渲染机这边**健壮性做得比服务器那边好**:心跳独立线程、看门狗连进程组一起杀、网络重试、进度按 `\r` 切,这些坑都踩明白了。
|
||||
最该修的是两处**静默少交货**(大图回传超上限、收单时张数口径不一致),以及本机工具能被任意网页远程操纵(`ys_local.py`)。
|
||||
前一处我在**服务器端**修好了(渲染机不用动),后一处直接改了 `ys_local.py`。
|
||||
|
||||
## 1. 问题分析
|
||||
|
||||
| # | 严重度 | 位置(原版) | 问题是什么 | 触发条件 | 影响 | 状态 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| 1 | 🟡(怀疑,强烈建议实测) | ys_worker.py `handle_order` 575 + 服务器 `MAX_BODY_WK=16MB` + nginx `/finish` 16m | 每个文件 base64 后整包 POST。4096×4096 的 16bit RGBA 原始数据是 128MB,PNG 压一半也还有几十 MB;2048 的无压缩也很可能超 12MB(base64 前) | 出 2048 / 4096 的单 | 服务器 / nginx 拒收 → 渲染机只记一条 errs 继续往下 → 最后 close → **订单「已完成」但少了无压缩版**,买家和金钻都不知道 | 「不再静默」已在服务器端修(见网站回执改动 11);**传输本身建议**改分块上传 |
|
||||
| 2 | 🟡 | ys_worker.py 596 收单不带 `total`;服务器按模板数算 | 渲染机的 total 是**文件数**(每模板 2 张),收单那一下服务器却按**模板数**判断收没收满 | 有模板失败或回传失败 | 少交的单被当成收满 → 静默 | 已修(服务器记住渲染机报过的 total) |
|
||||
| 3 | 🟡 | ys_worker.py 26 / 438 | 渲染机写死 `TERMS_VERSION = "2026-10-01.1"`,服务器派单又不给订单的版本 | 每一单 | 永久留档里的「条款版本」全是错的 | 已修(服务器 `/claim` 新增 `terms_v`,渲染机本来就先读它,**不用改渲染机**) |
|
||||
| 4 | 🟡 | ys_local.py `do_POST` 328 | 只监听回环,但**本机浏览器里任何网页**都能往 `localhost` 发 POST(text/plain 跨站 POST 不需要预检),原来照单全收 | 金钻开着本机工具时逛到一个恶意网页 | 往队列里塞任意多个渲染(**把机器顶满**)、往留档写没核验过的「皮肤」(本机工具不跑 pngcheck)、`/api/quit` 把工具关掉 | 已修 |
|
||||
| 5 | 🟡 | deploy.py `step()` / `main()` | 每一步的返回码都**没人检查**:scp 失败、安装脚本失败,后面照样往下走,最后打印一行状态 | 隧道抖一下、宿主没开、某个文件没传上 | 正是你们说的「脚本全程报成功、功能静默缺失」 | **建议**:任何一步 rc≠0 立刻退出并打印哪一步 |
|
||||
| 6 | 🟡 | deploy.py staging | `config.json`(**两把令牌明文**)留在本机 `<TMP_OUT>` 和 VM `<TMP_WORK>` 里,部署完不删 | 每次部署 | 令牌在两台机器的临时目录里长期躺着 | **建议**:推完就删 staging(VM 上那份也删) |
|
||||
| 7 | 🟡 | ys_worker.py `--once` | `--once` 不拿单实例锁;服务器 `claim` 会把开渲超过 45 分钟的单退回队列 | 计划任务那个 worker 正在渲一张大单(4096 × 多张超过 45 分钟),有人手动又跑了一次 `--once` | 退回的单被第二个进程又领走:**两个 Blender 同时跑** + 同一单重渲两遍 | **建议**:`--once` 也要拿锁(拿不到就提示「已经有一个在跑」) |
|
||||
| 8 | 🟢 | ys_admin.py PIN | 4~12 位数字 PIN 用「加盐 sha256」存:在线有冷却没问题,但 `pin.json` 一旦被拷走,离线几秒钟就能穷举完 | `pin.json` 泄露 | PIN 失效 | **建议**换 `hashlib.pbkdf2_hmac`(标准库,一行) |
|
||||
| 9 | 🟢 | ys_admin.py `/api/pinset` | 还没设过 PIN 时,**局域网里谁先打开谁就能设** | 新装 / 删了 pin.json 之后的空窗 | 别人设了 PIN、金钻反而进不去 | **建议**:首次设置只允许本机回环来源 |
|
||||
| 10 | 🟢 | ys_admin.py 绑定 `<ALL-INTERFACES>` | 面板监听所有网卡 | 那台电脑接到公共 Wi-Fi / 开了热点 | 面板暴露在别的网络里(还有 PIN 一道) | **建议**:只绑家里那张网卡的地址,或者 Windows 防火墙限定「专用网络」 |
|
||||
| 11 | 🟢 | ys_worker.py `http()` | `HTTPError` 一律不重试(包括 502 / 503 / 504 这类网关临时错误) | 服务器重启、nginx 偶发 502 | 那一张直接算回传失败 | **建议**:5xx 也按网络抖动重试 |
|
||||
|
||||
ys_admin.py 的「令牌 + PIN + 自定义请求头」做法本身是对的:敏感接口都要求 `X-Pin` 头,跨站页面发不出来(需要预检,服务器又不响应 OPTIONS),所以它没有 ys_local.py 那个问题。
|
||||
|
||||
## 2. 改正意见
|
||||
|
||||
| 对应 # | 建议改法 | 代价 / 风险 | 优先级 |
|
||||
|---|---|---|---|
|
||||
| 1 | **分块上传**:`/finish` 支持 `{oid, name, part, parts, data}` 一块 2~4MB,服务器按块追加到 `out/<name>.part`,收齐再改名 + 校验 sha256。这样不受请求体上限限制,断了也只重传一块。**⚠️ 这是接口改动,两边要一起上线**(服务器先上、兼容老格式,渲染机后上) | 中(两边各几十行) | 高(如果实测证实大图超限) |
|
||||
| 1(临时) | 先量一下 2048 / 4096 的无压缩版实际多大;如果只是略超,可以把 nginx 和 `MAX_BODY_WK` 一起调到 64MB 先顶着(服务器内存要算:单个请求峰值约为体积的 3~4 倍) | 小,但吃内存 | 中 |
|
||||
| 5、6 | deploy.py:`step()` 返回非 0 就 `sys.exit`;最后 `finally` 里删掉本机和 VM 的 staging;部署成功的判定改成「心跳报上来的版本号 == 这次部署的版本号」(见网站回执 Q3) | 小 | 中 |
|
||||
| 7 | `--once` 也走 `single_instance()`;服务器那边 45 分钟的「中断回退」改成看**进度最后一次上报的时间**(`progress.at`),而不是开渲时间 —— 大单只要还在报进度就不会被误退 | 小 | 中 |
|
||||
| 8、9、10 | 见上表 | 都很小 | 低 |
|
||||
|
||||
## 3. 你改了什么
|
||||
|
||||
### 改动 1 · 本机开单工具只认本机页面
|
||||
|
||||
```
|
||||
文件 / 函数:ys_local.py 新增 H._same_site();do_POST() 开头调用
|
||||
为什么改:问题 #4
|
||||
改成什么:Host 必须是 localhost / 127.0.0.1 / [::1] 加本工具端口(挡 DNS 重绑定);
|
||||
请求带了 Origin 就必须是本机这个端口;不满足回 403「只接受本机页面的请求」。GET(看页面、查进度、取图)不受影响。
|
||||
⚠️ 有没有动:接口路径 [否] 请求响应字段 [否] 数据格式 [否]
|
||||
本机页面 local.html 自己发的请求(render / openfolder / quit)两条都满足,用法不变
|
||||
怎么验证的:单测 5 种请求头组合:本机 Host ✔、本机 Host+本机 Origin ✔、本机 Host+外站 Origin ✘、
|
||||
外站 Host(重绑定)✘、Origin=null ✘,全部符合预期
|
||||
有没有引入新的依赖:没有
|
||||
```
|
||||
|
||||
### 改动 2、3(在服务器那份代码里,渲染机不用动)
|
||||
|
||||
- 收单张数口径(#2)、部分失败通知 + 页面说实话(#1 的「不再静默」)、`/claim` 带 `terms_v`(#3)。
|
||||
- 详见 `backend-site/回执-Claude.md` 第 3 节改动 11、12。**渲染机代码一行没改**;新服务器配老渲染机完全兼容。
|
||||
|
||||
## 4. 你们拿不准的两件事
|
||||
|
||||
- **部署不生效(旧进程还在跑),除了先杀再起有没有更稳的?**
|
||||
有:**让进程自己报版本**。部署时把版本号(git 提交号或文件 sha256)写进代码常量,心跳带上它,服务器存进 heartbeat.json、在 `/status` 和面板上显示;部署脚本**比对「期望版本 == 心跳报上来的版本」才算成功**。旧进程还活着会立刻看出来。
|
||||
Windows 上用 NSSM / WinSW 把渲染机和面板装成**服务**,「重启」的语义是确定的(停、等它退出、再起),比计划任务的「运行」可靠。
|
||||
|
||||
- **单线程串行,要支持多单怎么不顶满机器?**
|
||||
先**不加并发、先加吞吐**:同一个模板的多张皮肤放进**同一个 Blender 进程**连着渲(换贴图、再渲),省掉每张冷启动 + 加载工程的固定开销,峰值还不涨。
|
||||
真要并发,瓶颈是**显存**:按模板估一个显存占用,用「显存预算」信号量决定同时开几个;Blender 设低于正常的优先级、限定 Cycles 线程数;白天一个槽、夜里两个槽。服务器的 `/claim` 本身是原子的,渲染机开两个消费线程各领各的就行,**服务器不用改**。
|
||||
|
||||
## 5. 没验证的部分
|
||||
|
||||
- 没有 Windows + Blender 环境:ys_worker.py / ys_admin.py 没有实机跑,只做了代码阅读;ys_local.py 只单测了改动的那个函数。
|
||||
- `make_order.py`、`.ps1` / `.bat` 只扫了命名和调用参数,没有逐行审。
|
||||
- 大图回传超上限(#1)是按像素数和常见压缩比推算的,**没有真实成品验证**。
|
||||
|
||||
## 6. 需要的材料
|
||||
|
||||
- 一份 2048、一份 4096 单的成品文件大小(标准版 + 无压缩)。
|
||||
- 渲染机的 `worker.log` 里一次「部分失败」的片段(脱敏),用来核对收单流程。
|
||||
|
||||
---
|
||||
|
||||
*以上改动都还只在工作区,等你们(和 ywsabc2)看过再决定要不要合。*
|
||||
|
||||
---
|
||||
|
||||
# 第二轮(2026-10-05 晚)· 开单后台页面重写
|
||||
|
||||
### 改动 4 · ys_admin.py 页面按功能重排 + 补按钮
|
||||
|
||||
```
|
||||
文件 / 函数:ys_admin.py 的 PAGE(整页 HTML / CSS / JS 重写);do_GET / do_POST 加了 6 个转发
|
||||
为什么改:老页面一长条五张卡,要处理的事(待激活、失败、呼叫)跟生成表单混在一起;
|
||||
服务器早有的「写备注」「改卡密 / 停用」在面板上没有按钮;失败的单和呼叫记录在面板上处理不了
|
||||
改成什么:待处理(默认)/ 订单 / 卡密 / 福利券 / 呼叫·反馈 / 开单工具 六页;样子跟 2026 版网站一致;
|
||||
订单、卡密能搜;失败的单能退回重渲;呼叫能标「处理过了」;卡密能停用 / 启用 / 改张数
|
||||
⚠️ 有没有动接口:面板本机接口**新增** /api/codes /api/calls /api/retry /api/note /api/code-edit /api/call-done,
|
||||
老接口和 PIN 锁逻辑一个没动;新按钮用到服务器这次新加的管理接口,**服务器要先升级**
|
||||
你怎么验证的:现编假数据起真服务器 + 真面板,headless 浏览器在电脑宽 / 手机宽各点一遍全部页面和主要操作,
|
||||
无报错、无横向滚动(详见 交接说明.md 第三节 ②)
|
||||
```
|
||||
|
||||
### 改动 5 · 本机开单页面(local.html)重写
|
||||
|
||||
```
|
||||
文件 / 函数:local.html(整页);ys_local.py 没动
|
||||
为什么改:暗色老样子;分辨率选择和次按钮没写样式;「清空」按钮没绑事件(点了没反应);
|
||||
拖偏了浏览器会把工具页换成那张图
|
||||
改成什么:跟网站 / 开单后台同一套样子,左皮肤右模板;补上分辨率样式、清空、整页接收拖拽、出图顺序标号、预计耗时
|
||||
⚠️ 有没有动接口:没有。/api/status /api/render /api/job /api/file /api/openfolder /api/quit 的请求和字段照旧
|
||||
你怎么验证的:假本机服务 + headless 浏览器(电脑宽 / 手机宽)走完整流程;没在真 Blender 上跑
|
||||
```
|
||||
@@ -0,0 +1,188 @@
|
||||
# 部署层 · 反向代理片段(脱敏版)
|
||||
|
||||
> 后端**只绑本机回环**,对外全部由 nginx 反代。这一份是跟 `/order/` 相关的路由与限流,
|
||||
> 给你看**路由是怎么接的、限额是怎么设的**。值已按脱敏规则替换,**照形状看,别照字面抄**。
|
||||
|
||||
---
|
||||
|
||||
## 一、限流区(定义在 nginx 的 http 层)
|
||||
|
||||
```nginx
|
||||
# 下单相关:一般接口 90 次/分钟,提交接口单独收紧到 10 次/分钟
|
||||
limit_req_zone $binary_remote_addr zone=<ZONE_ORDER>:1m rate=90r/m;
|
||||
limit_req_zone $binary_remote_addr zone=<ZONE_SUBMIT>:1m rate=10r/m;
|
||||
```
|
||||
|
||||
**为什么给提交接口单独一条**:它是唯一会**收上传**的入口,也是最值得刷的入口。
|
||||
别的接口刷快一点无所谓(就是查状态),提交接口必须压住。
|
||||
|
||||
---
|
||||
|
||||
## 二、`/order/api/` 的路由
|
||||
|
||||
```nginx
|
||||
# ① 提交接口:单独限流 + 单独放宽请求体
|
||||
location = /order/api/submit {
|
||||
limit_req zone=<ZONE_SUBMIT> burst=5 nodelay;
|
||||
limit_req_status 429;
|
||||
client_max_body_size 4m; # 皮肤是 base64 进来的
|
||||
proxy_pass http://localhost:<PORT>/api/submit;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr; # 后端要拿它做「单 IP 限单」
|
||||
proxy_read_timeout 120s;
|
||||
add_header Cache-Control "no-store" always;
|
||||
}
|
||||
|
||||
# ② 回传接口:**单独一条**,因为成品一张 1~3MB(base64 后更大)
|
||||
# ⚠️ nginx 的 `location =` 精确匹配**优先于**前缀匹配 ——
|
||||
# 想只给这一个路径放宽体积,不能靠下面那条前缀规则
|
||||
location = /order/api/finish {
|
||||
limit_req zone=<ZONE_ORDER> burst=40 nodelay;
|
||||
limit_req_status 429;
|
||||
client_max_body_size 16m;
|
||||
proxy_pass http://localhost:<PORT>/api/finish;
|
||||
# ...
|
||||
}
|
||||
|
||||
# ③ 其余接口
|
||||
location /order/api/ {
|
||||
limit_req zone=<ZONE_ORDER> burst=40 nodelay;
|
||||
limit_req_status 429;
|
||||
proxy_pass http://localhost:<PORT>/api/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
# ...
|
||||
}
|
||||
```
|
||||
|
||||
### ④ 内容后台(2026-10-05 加)
|
||||
|
||||
```nginx
|
||||
# 登录 / 内容接口。⚠️ 必须带 X-Forwarded-Proto —— 后端看它判断是不是 https,不带一律拒绝(内容后台只走 https)
|
||||
location /order/api/cms/ {
|
||||
limit_req zone=<ZONE_ORDER> burst=20 nodelay;
|
||||
limit_req_status 429;
|
||||
client_max_body_size 16m; # 画展传图:单张 10MB,base64 后约 13.4MB
|
||||
proxy_pass http://localhost:<PORT>/api/cms/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# 后台发布出来的内容文件:文件名不变、内容会变 → 让浏览器每次都问一下有没有新的
|
||||
location /content/ { add_header Cache-Control "no-cache"; }
|
||||
location /order/content/ { add_header Cache-Control "no-cache"; }
|
||||
# 页面本身(2026-10-06 起门户是多页:index / gallery / tools / universe / links / about.html)不缓存:改版后手机浏览器别老吃旧副本
|
||||
location ~ \.html$ { add_header Cache-Control "no-cache"; }
|
||||
# 站点固定信息(群号 / 备案号 / 邮箱):正式服务器上的这份是真实值,部署别用仓库里的占位覆盖
|
||||
location = /assets/site-info.js { add_header Cache-Control "no-cache"; }
|
||||
# 后台页面本身不缓存(改版后别人拿到旧页面会调错接口)
|
||||
location /admin/ { add_header Cache-Control "no-store"; }
|
||||
# 画展上传的图(文件名是随机的,可以长缓存)
|
||||
location /uploads/ { add_header Cache-Control "public, max-age=2592000"; }
|
||||
|
||||
# 整站 http → https,并加 HSTS(登录页绝不能走 http)
|
||||
server { listen 80; server_name shop.example.com; return 301 https://$host$request_uri; }
|
||||
# 在 443 的 server 块里加:
|
||||
# add_header Strict-Transport-Security "max-age=31536000" always;
|
||||
```
|
||||
|
||||
> 没配好证书之前**不要开放内容后台**:后端会拒绝所有非 https 的请求(返回 403「内容后台只能用 https 打开」)。
|
||||
|
||||
⚠️ **打包下载(zip)那条要另外配**:`proxy_buffering off` + 更长的 `proxy_read_timeout`,
|
||||
因为它是**先落临时文件再边读边发**的,不能在 nginx 这层再缓存一份(小机器内存受不住)。
|
||||
|
||||
---
|
||||
|
||||
## 三、买家那边的路由(订单链接)
|
||||
|
||||
```nginx
|
||||
location ~ "^/order/[A-Za-z0-9]{6,16}$" {
|
||||
try_files /order/index.html =404;
|
||||
add_header Cache-Control "no-store" always;
|
||||
add_header X-Robots-Tag "noindex, nofollow, noarchive" always;
|
||||
}
|
||||
|
||||
# 兜底:/order/ 下面找不到的路径一律给下单页,**绝不给 404**
|
||||
location /order/ {
|
||||
try_files $uri $uri/ /order/index.html;
|
||||
add_header Cache-Control "no-store" always;
|
||||
add_header X-Robots-Tag "noindex, nofollow, noarchive" always;
|
||||
}
|
||||
```
|
||||
|
||||
**这两条的用意,请你连做法一起评**:
|
||||
|
||||
1. **`^/order/<6~16位>` 这条必须有**。买家拿到的是 `/order/<订单号>?t=<取件码>`,
|
||||
没有这条路由会掉到主站规则**直接 404** —— 而买家一关页面就**再也找不回订单**。
|
||||
(页面文案还写着"请记下订单号用于查询下载",那就成了骗人。)
|
||||
2. **兜底那条绝不能返回 404**。买家从聊天软件复制链接**常夹进不可见字符**
|
||||
(实测踩到:路径里多了个零宽空格 → 404),看着就像**网站坏了**。
|
||||
给下单页最差只是"没找到那一单",页面自己会提示。
|
||||
3. **正则里的 `{6,16}` 必须用引号包住**,否则 nginx 会把花括号当配置块起始,
|
||||
报 `unknown directive`(实测踩到)。
|
||||
4. **`no-store` + `noindex`**:订单页带取件码,不该被缓存也不该被搜索引擎收录
|
||||
(一是降曝光,二是链接本身就是凭证)。
|
||||
|
||||
---
|
||||
|
||||
## 四、这一层我们没做的事(也算"做法",欢迎质疑)
|
||||
|
||||
- **没上 WAF / 没有额外防护层**:这台机器很小,装不下重的东西;
|
||||
防护全在后端自己的限流 + 两把令牌 + 来源 IP 门上。
|
||||
- **没做多机/负载均衡**:单机单进程,够用。
|
||||
- **HTTPS 用自动签发的证书**,续期自动化,没有额外动作。
|
||||
|
||||
|
||||
## ⑤ 安全加固(2026-10-06,线上已加)
|
||||
|
||||
```nginx
|
||||
# 文件:/etc/nginx/snippets/jz-sec-base.conf
|
||||
add_header Strict-Transport-Security "max-age=31536000" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=()" always;
|
||||
|
||||
# 文件:/etc/nginx/snippets/jz-sec-csp.conf(只给本站页面)
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; media-src 'self' blob:; font-src 'self' data:; connect-src 'self'; frame-src https://player.bilibili.com; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'" always;
|
||||
|
||||
# server 块里:
|
||||
include snippets/jz-sec-base.conf;
|
||||
include snippets/jz-sec-csp.conf;
|
||||
location ~* (\.bak[^/]*|\.maint[^/]*|\.old[^/]*|\.orig|\.swp|~|\.v[0-9]+-(live|new)[^/]*)$ { return 404; }
|
||||
location ~* ^/(order/)?preview-[^/]*\.html$ { return 404; }
|
||||
location ~ /\.(?!well-known/) { return 404; }
|
||||
location = /content/site.json { return 404; }
|
||||
location = /order/content/order.json { return 404; }
|
||||
# 回调单独限流(http 级:limit_req_zone $binary_remote_addr zone=jzhook:1m rate=20r/m;)
|
||||
location ~ ^/order/api/(payplatform|afdian)-hook$ {
|
||||
limit_req zone=jzhook burst=10 nodelay; limit_req_status 429; client_max_body_size 64k;
|
||||
rewrite ^/order/api/(.*)$ /api/$1 break; proxy_pass http://localhost:<PORT>;
|
||||
proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr;
|
||||
add_header Cache-Control "no-store" always; include snippets/jz-sec-base.conf;
|
||||
}
|
||||
# ⚠️ 每个自己写了 add_header 的 location 里都要再 include 上面两个文件(nginx 不继承 server 级的 add_header)
|
||||
# nginx.conf 的 http 块:server_tokens off;
|
||||
```
|
||||
|
||||
## ⑥ 维护页开关(2026-10-07 加)
|
||||
|
||||
放在 `jinzuan.work` 的 server 块里(两个安全头 include 之后)。**开关不用 reload**:
|
||||
|
||||
- 开:`sudo touch /var/www/jinzuan/.maintenance && sudo chown www-data:www-data /var/www/jinzuan/.maintenance`
|
||||
- 关:`sudo rm -f /var/www/jinzuan/.maintenance`
|
||||
|
||||
只拦金钻客栈的页面(返回 503 + `/maintenance.html`);`/order/api/`(爱发电回调、渲染机、内容后台)、同域其它应用、
|
||||
`/assets/` `/fonts/` 一律放行。带请求头 `X-Jz-Bypass: <BYPASS_SECRET>` 可以绕过维护页验证新页面(密钥只在服务器配置里)。
|
||||
|
||||
```nginx
|
||||
set $jz_maint 0;
|
||||
if (-f /var/www/jinzuan/.maintenance) { set $jz_maint 1; }
|
||||
if ($uri ~ "^/(order/api/|api/|ws$|todo|gw|hit$|admin|uploads/|assets/|fonts/|maintenance\.html$|\.well-known/)") { set $jz_maint 0; }
|
||||
if ($http_x_jz_bypass = "<BYPASS_SECRET>") { set $jz_maint 0; }
|
||||
if ($jz_maint = 1) { rewrite ^ /__jz_maint last; }
|
||||
location = /__jz_maint { internal; error_page 503 /maintenance.html; return 503; }
|
||||
location = /maintenance.html { add_header Cache-Control "no-store" always; add_header Retry-After "900" always;
|
||||
include snippets/jz-sec-base.conf; include snippets/jz-sec-csp.conf; }
|
||||
```
|
||||
@@ -0,0 +1,2 @@
|
||||
data/
|
||||
__pycache__/
|
||||
@@ -0,0 +1,41 @@
|
||||
# 收款原型(pay-proto)
|
||||
|
||||
设计文档里「渠道抽象层 + 爱发电主通道 + 当面付辅助通道」的可运行原型。
|
||||
标准库 + SQLite + `cryptography`,只绑 127.0.0.1,由 nginx 反代。
|
||||
|
||||
## 占位符
|
||||
|
||||
`config.py` 里所有账号 / 密钥都是 `<占位符>`。值还是占位符的渠道,自动接到内置的**模拟网关**(`mockgw.py`):
|
||||
签名、验签、HTTP 调用都是真实代码,只是对面换成模拟的爱发电 / 支付宝。填上真实值(环境变量)即切到真渠道。
|
||||
|
||||
| 环境变量 | 说明 |
|
||||
|---|---|
|
||||
| `AFDIAN_USER_ID` / `AFDIAN_TOKEN` | 爱发电开放接口(query-order 的 md5 签名) |
|
||||
| `AFDIAN_PUBKEY_FILE` | 爱发电 Webhook 验签公钥(PEM) |
|
||||
| `AFDIAN_PLAN_ID` | 承载 `custom_price` 的「自选金额」方案 |
|
||||
| `ALIPAY_APP_ID` | 当面付应用 AppID |
|
||||
| `ALIPAY_APP_PRIVATE_KEY_FILE` | 应用私钥(PEM,权限 600,只放服务器) |
|
||||
| `ALIPAY_PUBLIC_KEY_FILE` | 支付宝公钥(验响应 / 异步通知) |
|
||||
| `PAY_ADMIN_TOKEN` | 后台口令;占位符时首次启动自动生成到 `data/admin_token` |
|
||||
| `PAY_BASE_URL` / `PAY_PORT` / `PAY_DATA_DIR` | 对外地址 / 端口 / 数据目录 |
|
||||
|
||||
## 结构
|
||||
|
||||
- `core.py`:数据库、演示时钟、统一到账入口 `settle_payment()`、定时任务(爱发电对账 / 当面付补查 / 支付单过期 / 订单超时 / 迟到扫描)
|
||||
- `channels.py`:渠道抽象层,`Afdian`、`AlipayF2F`(create / verify_notify / query / close / refund)
|
||||
- `mockgw.py`:模拟网关(只在占位符时用)
|
||||
- `app.py`:HTTP 服务(只有接口和模拟网关,页面都在站点里)
|
||||
- `preview/`:并进预览站的页面 —— `order.html`(下单表单 + 我的订单)、`pay.html`(收银台 / 订单页)、
|
||||
`cms/pay.html`(收款后台)、`assets/pay.css`、`assets/pay.js`(含演示控制台)、`assets/vendor/qrcode.min.js`(qrcode-generator 1.4.4,MIT)。
|
||||
另外 `cms/index.html` 的「下单页」分组里加了一个「收款与对账」链接(预览站上直接改的,三行)。
|
||||
|
||||
## 测试
|
||||
|
||||
`python3 tests/test_proto.py`:临时目录起一份服务,从 HTTP 层打 26 个场景。
|
||||
|
||||
## 预览部署(甲骨文 ARM)
|
||||
|
||||
`/opt/jz-pay-proto` + systemd `jz-pay-proto`(DynamicUser,数据 `/var/lib/jz-pay-proto`,
|
||||
`PAY_BASE_URL=http://161.33.11.66/svc`、`PAY_SITE_URL=http://161.33.11.66`),
|
||||
nginx `jz-preview.conf` 里 `/svc/` 反代到 `127.0.0.1:18100`;旧的 `/pay-proto/` 301 到 `/order.html`。
|
||||
页面:`/order.html` → `/pay.html?o=…&t=…`;后台 `/cms/pay.html`。**只在预览机,不碰生产。**
|
||||
@@ -0,0 +1,351 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""支付原型 HTTP 服务(标准库,只绑 127.0.0.1,由 nginx 反代到 /pay-proto/)。
|
||||
|
||||
买家: POST api/order · GET api/order · POST api/pay · GET api/pay · POST api/check
|
||||
回调: POST api/notify/afdian · POST api/notify/alipay
|
||||
后台: api/admin/*(请求头 X-Admin-Token)
|
||||
演示: api/demo/*(快进时钟、立即跑定时任务、模拟场景 —— 只在原型里有)
|
||||
模拟网关:mock/afdian/* · mock/alipay/*
|
||||
"""
|
||||
import json, os, secrets, sys, urllib.parse
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import config as C # noqa: E402
|
||||
import core # noqa: E402
|
||||
import channels # noqa: E402
|
||||
import mockgw # noqa: E402
|
||||
|
||||
STATE_TEXT = {"unpaid": "待付款", "waiting": "已付款 · 排队中", "working": "渲染中", "done": "已完成",
|
||||
"failed": "渲染失败", "closed": "已关闭", "void": "已注销"}
|
||||
PAY_TEXT = {"created": "等待付款", "paid": "已到账", "mismatch": "金额不足", "closed": "已关闭", "refunded": "已退款"}
|
||||
|
||||
|
||||
def admin_token():
|
||||
if not C.is_placeholder(C.ADMIN_TOKEN):
|
||||
return C.ADMIN_TOKEN
|
||||
p = os.path.join(C.DATA_DIR, "admin_token")
|
||||
if not os.path.exists(p):
|
||||
os.makedirs(C.DATA_DIR, exist_ok=True)
|
||||
with open(p, "w") as f:
|
||||
f.write(secrets.token_urlsafe(18))
|
||||
os.chmod(p, 0o600)
|
||||
return open(p).read().strip()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 视图
|
||||
def pay_view(p, with_display=True):
|
||||
d = {k: p[k] for k in ("pay_id", "channel", "state", "amount_due", "amount_paid", "trade_no",
|
||||
"created_at", "expire_at", "paid_at", "note")}
|
||||
d["state_text"] = PAY_TEXT.get(p["state"], p["state"])
|
||||
d["display"] = json.loads(p["display"] or "{}") if (with_display and p["state"] == "created") else {}
|
||||
return d
|
||||
|
||||
|
||||
def order_view(o):
|
||||
pays = core.order_payments(o["oid"])
|
||||
chans = []
|
||||
for ch in channels.all_channels():
|
||||
ok, why = ch.available(o)
|
||||
chans.append({"name": ch.name, "label": ch.label, "ok": ok, "reason": why, "mock": ch.mock})
|
||||
ev = core.q("SELECT ts,channel,kind,pay_id,result FROM pay_events WHERE oid=? OR pay_id LIKE ? "
|
||||
"ORDER BY id DESC LIMIT 40", (o["oid"], o["oid"] + "P%"))
|
||||
return {"ok": True, "now": core.now(), "order": {
|
||||
"oid": o["oid"], "state": o["state"], "state_text": STATE_TEXT.get(o["state"], o["state"]),
|
||||
"n_img": o["n_img"], "amount": o["amount"], "created_at": o["created_at"], "paid_at": o["paid_at"],
|
||||
"closed_at": o["closed_at"], "expire_at": o["created_at"] + C.ORDER_TTL,
|
||||
"templates": [{"k": k, "n": C.TEMPLATES.get(k, k)} for k in json.loads(o.get("templates") or "[]")],
|
||||
"res": o.get("res") or 1000, "skin_name": o.get("skin_name") or "", "price_unit": C.PRICE_UNIT},
|
||||
"payments": [pay_view(p) for p in pays], "channels": chans, "events": ev,
|
||||
"params": {"qr_ttl": C.QR_TTL, "order_ttl": C.ORDER_TTL, "late_grace": C.LATE_GRACE,
|
||||
"ali_max": C.ALI_MAX_AMOUNT}}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 动作
|
||||
def create_payment(o, chname):
|
||||
if o["state"] != "unpaid":
|
||||
return {"ok": False, "error": "订单现在是「%s」,不能再付款" % STATE_TEXT.get(o["state"], o["state"])}
|
||||
ch = channels.get(chname)
|
||||
ok, why = ch.available(o)
|
||||
if not ok:
|
||||
return {"ok": False, "error": why}
|
||||
for p in core.order_payments(o["oid"]): # 同渠道还有没过期的支付单 → 直接复用
|
||||
if p["channel"] == chname and p["state"] == "created" and p["expire_at"] > core.now() + 30:
|
||||
return {"ok": True, "payment": pay_view(p)}
|
||||
p = core.new_payment(o, chname, ch.ttl())
|
||||
try:
|
||||
disp = ch.create(o, p)
|
||||
except Exception as e:
|
||||
core.x("UPDATE payments SET state='closed',note=? WHERE pay_id=?", ("创建失败:%s" % e, p["pay_id"]))
|
||||
core.event(chname, "create_failed", p["pay_id"], o["oid"], "error", repr(e))
|
||||
return {"ok": False, "error": "%s暂时不可用,请换爱发电付款" % ch.label}
|
||||
core.set_display(p["pay_id"], disp)
|
||||
return {"ok": True, "payment": pay_view(core.get_payment(p["pay_id"]))}
|
||||
|
||||
|
||||
def buyer_check(o):
|
||||
"""买家点「付好了没反应?」→ 立刻把这单所有没到账的支付单查一遍。"""
|
||||
core.x("UPDATE orders SET buyer_claim_at=? WHERE oid=?", (core.now(), o["oid"]))
|
||||
core.event("", "buyer_check", "", o["oid"], "requested")
|
||||
found = []
|
||||
for p in core.order_payments(o["oid"]):
|
||||
if p["state"] in ("created", "closed"):
|
||||
try:
|
||||
r = core.poll_payment(channels.get(p["channel"]), p, "buyer_check")
|
||||
found.append(r["result"])
|
||||
except Exception as e:
|
||||
core.event(p["channel"], "query_failed", p["pay_id"], o["oid"], "error", repr(e))
|
||||
o2 = core.get_order(o["oid"])
|
||||
if o2["state"] == "waiting":
|
||||
return {"ok": True, "found": True, "msg": "找到了,已到账 —— 正在排队出图"}
|
||||
if "short" in found:
|
||||
return {"ok": True, "found": True, "msg": "收到了付款,但金额不足,已通知金钻核对"}
|
||||
return {"ok": True, "found": False, "msg": "暂时还没查到到账。刚付完可能要等几十秒;超过几分钟还没有,请点「呼叫金钻」。"}
|
||||
|
||||
|
||||
def handle_notify(chname, body, ctype):
|
||||
ch = channels.get(chname)
|
||||
try:
|
||||
facts, why, resp = ch.verify_notify(body, ctype)
|
||||
except Exception as e:
|
||||
core.event(chname, "notify", "", "", "error", repr(e))
|
||||
return resp_default(chname)
|
||||
core.event(chname, "notify", (facts or {}).get("pay_id", ""), "", why,
|
||||
body.decode("utf-8", "replace") if isinstance(body, bytes) else str(body))
|
||||
if facts:
|
||||
if not facts["pay_id"]:
|
||||
# 没带 custom_order_id:买家直接在爱发电店铺下的单 → 按「买卡密」处理(正式版沿用现有发码逻辑)
|
||||
core.event(chname, "card_purchase", "", "", "(原型)会按实付金额发一张卡密",
|
||||
{"trade_no": facts["trade_no"], "amount": facts["amount"]})
|
||||
else:
|
||||
core.settle_payment(chname, facts["pay_id"], facts["trade_no"], facts["amount"], "notify", facts["raw"])
|
||||
return resp
|
||||
|
||||
|
||||
def resp_default(chname):
|
||||
return json.dumps({"ec": 200, "em": ""}) if chname == "afdian" else "fail"
|
||||
|
||||
|
||||
def admin_overview():
|
||||
return {"ok": True, "now": core.now(), "clock_offset": core.kv_get("clock_offset", 0),
|
||||
"todo": core.q("SELECT * FROM pay_todo ORDER BY state='done', id DESC LIMIT 100"),
|
||||
"payments": [dict(pay_view(p, False), oid=p["oid"]) for p in
|
||||
core.q("SELECT * FROM payments ORDER BY created_at DESC LIMIT 60")],
|
||||
"orders": core.q("SELECT oid,state,amount,created_at,paid_at,closed_at,buyer_claim_at FROM orders "
|
||||
"ORDER BY created_at DESC LIMIT 40"),
|
||||
"events": core.q("SELECT * FROM pay_events ORDER BY id DESC LIMIT 80"),
|
||||
"breaker": channels.get("alipay").breaker(),
|
||||
"channels": [{"name": c.name, "label": c.label, "mock": c.mock} for c in channels.all_channels()],
|
||||
"mock_alipay_risk": bool(core.kv_get("mock_alipay_risk"))}
|
||||
|
||||
|
||||
def admin_todo(d):
|
||||
t = core.q1("SELECT * FROM pay_todo WHERE id=?", (int(d.get("id") or 0),))
|
||||
if not t:
|
||||
return {"ok": False, "error": "没有这条待办"}
|
||||
act, note = d.get("action"), str(d.get("note") or "")[:200]
|
||||
p = core.get_payment(t["pay_id"]) if t["pay_id"] else None
|
||||
msg = ""
|
||||
if act == "confirm": # 金额不足 → 人工确认补齐,按到账处理
|
||||
if not p:
|
||||
return {"ok": False, "error": "这条待办没有关联支付单"}
|
||||
core.x("UPDATE payments SET state='paid',note='人工确认补齐' WHERE pay_id=?", (p["pay_id"],))
|
||||
core.x("UPDATE orders SET state='waiting',paid_at=? WHERE oid=? AND state IN ('unpaid','closed')",
|
||||
(core.now(), p["oid"]))
|
||||
msg = "已确认,订单激活"
|
||||
elif act == "activate":
|
||||
core.x("UPDATE orders SET state='waiting',paid_at=? WHERE oid=? AND state IN ('unpaid','closed','void')",
|
||||
(core.now(), t["oid"]))
|
||||
msg = "订单已手动激活"
|
||||
elif act == "refund":
|
||||
if not p:
|
||||
return {"ok": False, "error": "这条待办没有关联支付单"}
|
||||
amt = float(t["amount_paid"] or p["amount_paid"] or 0)
|
||||
try:
|
||||
ch = channels.get(p["channel"])
|
||||
if t["kind"] == "duplicate" and t["trade_no"] and t["trade_no"] != p["trade_no"]:
|
||||
return {"ok": False, "error": "重复付款的第二笔不在本地支付单上:请到%s后台按交易号 %s 退款" % (ch.label, t["trade_no"])}
|
||||
ch.refund(p, amt)
|
||||
core.x("UPDATE payments SET state='refunded',note='已退款 ¥%.2f' WHERE pay_id=?" % amt, (p["pay_id"],))
|
||||
msg = "已退款 ¥%.2f" % amt
|
||||
except Exception as e:
|
||||
return {"ok": False, "error": str(e)}
|
||||
elif act != "ignore":
|
||||
return {"ok": False, "error": "不认识的操作"}
|
||||
core.x("UPDATE pay_todo SET state='done',resolution=?,resolved_at=? WHERE id=?",
|
||||
("%s:%s %s" % (act, msg, note), core.now(), t["id"]))
|
||||
core.event(t["channel"] or "", "todo_resolved", t["pay_id"] or "", t["oid"] or "", act, note)
|
||||
return {"ok": True, "msg": msg or "已处理"}
|
||||
|
||||
|
||||
def admin_claim(d):
|
||||
"""按爱发电订单号认领到某张订单(买家没走专链、或 custom_order_id 丢了)。"""
|
||||
o = core.get_order(str(d.get("oid") or "").upper())
|
||||
if not o:
|
||||
return {"ok": False, "error": "没有这张订单"}
|
||||
ch = channels.get("afdian")
|
||||
real = ch.query_trade(str(d.get("trade_no") or "").strip())
|
||||
if not real:
|
||||
return {"ok": False, "error": "爱发电查不到这个订单号"}
|
||||
f = ch.facts(real)
|
||||
if not f["paid"]:
|
||||
return {"ok": False, "error": "这笔爱发电订单还没付款"}
|
||||
p = core.new_payment(o, "afdian", ch.ttl())
|
||||
r = core.settle_payment("afdian", p["pay_id"], f["trade_no"], f["amount"], "admin_claim", f["raw"])
|
||||
return {"ok": True, "msg": "认领结果:%s" % r["result"]}
|
||||
|
||||
|
||||
def demo(d):
|
||||
k = d.get("kind")
|
||||
if k == "clock":
|
||||
core.advance_clock(float(d.get("seconds") or 0))
|
||||
return {"ok": True, "jobs": core.run_jobs()}
|
||||
if k == "jobs":
|
||||
return {"ok": True, "jobs": core.run_jobs()}
|
||||
if k == "alipay_risk":
|
||||
core.kv_set("mock_alipay_risk", bool(d.get("on")))
|
||||
return {"ok": True}
|
||||
if k == "breaker_reset":
|
||||
core.kv_set("alipay_breaker", {"fails": 0, "open_until": 0, "reason": ""})
|
||||
return {"ok": True}
|
||||
if k == "afdian_direct":
|
||||
o = mockgw.afd_create_order("", d.get("amount") or 12, "直接在爱发电店铺下单(没带订单号)")
|
||||
return {"ok": True, "trade_no": o["out_trade_no"]}
|
||||
if k == "afdian_forge":
|
||||
fake = {"out_trade_no": "FORGED" + secrets.token_hex(4), "custom_order_id": str(d.get("pay_id") or ""),
|
||||
"user_id": "evil", "plan_id": "mock-plan", "total_amount": "999.00", "status": 2,
|
||||
"remark": "", "create_time": int(core.now())}
|
||||
return {"ok": True, "result": mockgw.afd_push(fake, forge=True)}
|
||||
return {"ok": False, "error": "unknown"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- HTTP
|
||||
class H(BaseHTTPRequestHandler):
|
||||
server_version = "jz-pay-proto"
|
||||
|
||||
def log_message(self, fmt, *a):
|
||||
pass
|
||||
|
||||
def send(self, code, ctype, body, extra=None):
|
||||
if isinstance(body, str):
|
||||
body = body.encode("utf-8")
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
for k, v in (extra or {}).items():
|
||||
self.send_header(k, v)
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def js(self, obj, code=200):
|
||||
self.send(code, "application/json; charset=utf-8", json.dumps(obj, ensure_ascii=False))
|
||||
|
||||
def body(self):
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
return self.rfile.read(min(n, 65536)) if n > 0 else b""
|
||||
|
||||
def jbody(self):
|
||||
try:
|
||||
return json.loads(self.body() or b"{}")
|
||||
except ValueError:
|
||||
return {}
|
||||
|
||||
def order_auth(self, oid, tok):
|
||||
o = core.get_order(str(oid or "").upper())
|
||||
if not o or not secrets.compare_digest(o["token"], str(tok or "")):
|
||||
return None
|
||||
return o
|
||||
|
||||
def is_admin(self):
|
||||
return secrets.compare_digest(self.headers.get("X-Admin-Token") or "", admin_token())
|
||||
|
||||
def do_GET(self):
|
||||
u = urllib.parse.urlparse(self.path)
|
||||
p, qs = u.path, urllib.parse.parse_qs(u.query)
|
||||
g = lambda k: (qs.get(k) or [""])[0]
|
||||
try:
|
||||
if p in ("/", "/index.html", "/admin", "/admin.html"): # 页面都在站点里,这里只有接口
|
||||
return self.send(302, "text/plain", "", {"Location": C.SITE_URL + ("/cms/pay.html" if "admin" in p else "/order.html")})
|
||||
if p == "/api/order":
|
||||
o = self.order_auth(g("oid"), g("t"))
|
||||
return self.js(order_view(o)) if o else self.js({"ok": False, "error": "订单不存在"}, 404)
|
||||
if p == "/api/pay":
|
||||
pay = core.get_payment(g("pay_id"))
|
||||
o = self.order_auth(pay["oid"] if pay else "", g("t"))
|
||||
if not (pay and o):
|
||||
return self.js({"ok": False, "error": "支付单不存在"}, 404)
|
||||
gap = C.QUERY_MIN_GAP if pay["channel"] == "alipay" else 15
|
||||
if pay["state"] == "created" and core.now() - (pay["last_query_at"] or 0) >= gap:
|
||||
try:
|
||||
core.poll_payment(channels.get(pay["channel"]), pay, "page_poll")
|
||||
except Exception as e:
|
||||
core.event(pay["channel"], "query_failed", pay["pay_id"], o["oid"], "error", repr(e))
|
||||
return self.js(order_view(core.get_order(o["oid"])))
|
||||
if p == "/api/admin/overview":
|
||||
return self.js(admin_overview()) if self.is_admin() else self.js({"ok": False, "error": "口令不对"}, 403)
|
||||
if p == "/mock/afdian/order/create":
|
||||
return self.send(*mockgw.afd_checkout(qs))
|
||||
if p.startswith("/mock/alipay/scan/"):
|
||||
return self.send(*mockgw.ali_scan(p.rsplit("/", 1)[-1]))
|
||||
return self.send(404, "text/plain; charset=utf-8", "not found")
|
||||
except Exception as e:
|
||||
core.event("", "http_error", "", "", p, repr(e))
|
||||
return self.js({"ok": False, "error": "服务器出错了"}, 500)
|
||||
|
||||
def do_POST(self):
|
||||
p = urllib.parse.urlparse(self.path).path
|
||||
try:
|
||||
if p == "/api/order":
|
||||
d = self.jbody()
|
||||
o = core.new_order(d.get("templates"), d.get("res"), d.get("skin_name"), d.get("n_img"))
|
||||
return self.js(dict(order_view(o), token=o["token"]))
|
||||
if p in ("/api/pay", "/api/check"):
|
||||
d = self.jbody()
|
||||
o = self.order_auth(d.get("oid"), d.get("t"))
|
||||
if not o:
|
||||
return self.js({"ok": False, "error": "订单不存在"}, 404)
|
||||
return self.js(create_payment(o, d.get("channel")) if p == "/api/pay" else buyer_check(o))
|
||||
if p == "/api/notify/afdian":
|
||||
return self.send(200, "application/json", handle_notify("afdian", self.body(), self.headers.get("Content-Type")))
|
||||
if p == "/api/notify/alipay":
|
||||
return self.send(200, "text/plain", handle_notify("alipay", self.body(), self.headers.get("Content-Type")))
|
||||
if p.startswith("/api/admin/"):
|
||||
if not self.is_admin():
|
||||
return self.js({"ok": False, "error": "口令不对"}, 403)
|
||||
d = self.jbody()
|
||||
if p == "/api/admin/todo":
|
||||
return self.js(admin_todo(d))
|
||||
if p == "/api/admin/claim":
|
||||
return self.js(admin_claim(d))
|
||||
return self.js({"ok": False, "error": "unknown"}, 404)
|
||||
if p == "/api/demo":
|
||||
return self.js(demo(self.jbody()))
|
||||
if p == "/mock/afdian/order/pay":
|
||||
return self.send(*mockgw.afd_pay(urllib.parse.parse_qs(self.body().decode())))
|
||||
if p.startswith("/mock/afdian/api/open/"):
|
||||
return self.send(*mockgw.afd_api(p, self.body()))
|
||||
if p == "/mock/alipay/gateway.do":
|
||||
return self.send(*mockgw.ali_gateway(self.body()))
|
||||
if p == "/mock/alipay/scanpay":
|
||||
return self.send(*mockgw.ali_scanpay(urllib.parse.parse_qs(self.body().decode())))
|
||||
return self.js({"ok": False, "error": "not found"}, 404)
|
||||
except Exception as e:
|
||||
core.event("", "http_error", "", "", p, repr(e))
|
||||
return self.js({"ok": False, "error": "服务器出错了"}, 500)
|
||||
|
||||
|
||||
def main():
|
||||
core.db()
|
||||
mockgw.init()
|
||||
channels.init()
|
||||
admin_token() # 首次启动就生成后台口令(data/admin_token,600)
|
||||
core.start_scheduler()
|
||||
print("支付原型启动 :%d 对外 %s 爱发电=%s 当面付=%s" % (
|
||||
C.PORT, C.BASE_URL, "模拟" if channels.get("afdian").mock else "真实",
|
||||
"模拟" if channels.get("alipay").mock else "真实"), flush=True)
|
||||
ThreadingHTTPServer(("127.0.0.1", C.PORT), H).serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,373 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""支付渠道抽象层。
|
||||
|
||||
每个渠道只做五件事:生成付款方式 create / 验证回调 verify_notify / 主动查单 query / 关单 close / 退款 refund。
|
||||
到账一律交给 core.settle_payment(),渠道自己不改订单。
|
||||
|
||||
「事实」facts = {"pay_id", "trade_no", "amount", "paid", "raw"},只来自验过真的数据。
|
||||
"""
|
||||
import base64, hashlib, json, os, re, time, urllib.parse, urllib.request
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
from cryptography.exceptions import InvalidSignature
|
||||
|
||||
import config as C
|
||||
import core
|
||||
|
||||
CST = timezone(timedelta(hours=8))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- RSA 小工具(签名 / 验签分开两把钥匙)
|
||||
def load_pub(path):
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
if b"BEGIN" not in data: # 支付宝后台给的常是不带头尾的一行 base64
|
||||
data = b"-----BEGIN PUBLIC KEY-----\n" + data.strip() + b"\n-----END PUBLIC KEY-----\n"
|
||||
return serialization.load_pem_public_key(data)
|
||||
|
||||
|
||||
def load_priv(path):
|
||||
with open(path, "rb") as f:
|
||||
return serialization.load_pem_private_key(f.read(), password=None)
|
||||
|
||||
|
||||
def rsa_sign(priv, text):
|
||||
return base64.b64encode(priv.sign(text.encode("utf-8"), padding.PKCS1v15(), hashes.SHA256())).decode()
|
||||
|
||||
|
||||
def rsa_verify(pub, text, sig_b64):
|
||||
try:
|
||||
pub.verify(base64.b64decode(sig_b64 or ""), text.encode("utf-8"), padding.PKCS1v15(), hashes.SHA256())
|
||||
return True
|
||||
except (InvalidSignature, ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def http_post(url, body, ctype, timeout=10):
|
||||
req = urllib.request.Request(url, data=body, method="POST", headers={"Content-Type": ctype})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return r.read().decode("utf-8")
|
||||
|
||||
|
||||
def fmt_cst(ts):
|
||||
return datetime.fromtimestamp(ts, CST).strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 基类
|
||||
class Channel:
|
||||
name = ""
|
||||
label = ""
|
||||
mock = False
|
||||
|
||||
def available(self, order):
|
||||
return True, ""
|
||||
|
||||
def ttl(self):
|
||||
return 3600
|
||||
|
||||
def create(self, order, pay):
|
||||
raise NotImplementedError
|
||||
|
||||
def verify_notify(self, body, ctype):
|
||||
"""返回 (facts 或 None, 说明, 给渠道的应答文本)"""
|
||||
raise NotImplementedError
|
||||
|
||||
def query(self, pay):
|
||||
return None
|
||||
|
||||
def close(self, pay):
|
||||
return True
|
||||
|
||||
def refund(self, pay, amount):
|
||||
raise RuntimeError("这个渠道不支持接口退款")
|
||||
|
||||
|
||||
# ================================================================ 爱发电
|
||||
class Afdian(Channel):
|
||||
name, label = "afdian", "爱发电"
|
||||
|
||||
def __init__(self):
|
||||
cfg = dict(C.AFDIAN)
|
||||
self.mock = any(C.is_placeholder(v) for v in cfg.values())
|
||||
if self.mock:
|
||||
import mockgw
|
||||
cfg.update(user_id="mock-user", token="mock-token", plan_id="mock-plan",
|
||||
pubkey_file=mockgw.key_path("afdian_platform", public=True),
|
||||
api=C.INTERNAL_URL + "/mock/afdian/api/open",
|
||||
checkout=C.BASE_URL + "/mock/afdian/order/create")
|
||||
self.cfg = cfg
|
||||
self.pub = load_pub(cfg["pubkey_file"]) if os.path.exists(cfg["pubkey_file"]) else None
|
||||
|
||||
def ttl(self):
|
||||
return C.AFD_TTL
|
||||
|
||||
def create(self, order, pay):
|
||||
qs = urllib.parse.urlencode({"user_id": self.cfg["user_id"], "plan_id": self.cfg["plan_id"],
|
||||
"product_type": 0, "custom_price": pay["amount_due"],
|
||||
"custom_order_id": pay["pay_id"], "remark": order["oid"]})
|
||||
url = self.cfg["checkout"] + "?" + qs
|
||||
return {"type": "redirect", "url": url, "qr": url}
|
||||
|
||||
# ---- OpenAPI:sign = md5(token + "params" + params + "ts" + ts + "user_id" + user_id)
|
||||
def api(self, path, params):
|
||||
p = json.dumps(params, separators=(",", ":"))
|
||||
ts = int(time.time())
|
||||
sign = hashlib.md5(("%sparams%sts%duser_id%s" % (self.cfg["token"], p, ts, self.cfg["user_id"]))
|
||||
.encode()).hexdigest()
|
||||
body = json.dumps({"user_id": self.cfg["user_id"], "params": p, "ts": ts, "sign": sign}).encode()
|
||||
r = json.loads(http_post(self.cfg["api"] + "/" + path, body, "application/json"))
|
||||
if r.get("ec") != 200:
|
||||
raise RuntimeError("爱发电接口错误:%s %s" % (r.get("ec"), r.get("em")))
|
||||
return r.get("data") or {}
|
||||
|
||||
@staticmethod
|
||||
def facts(o):
|
||||
return {"pay_id": str(o.get("custom_order_id") or ""), "trade_no": str(o.get("out_trade_no") or ""),
|
||||
"amount": float(o.get("total_amount") or 0), "paid": int(o.get("status") or 0) == 2,
|
||||
"raw": json.dumps(o, ensure_ascii=False)[:2000]}
|
||||
|
||||
def query_trade(self, out_trade_no):
|
||||
lst = (self.api("query-order", {"out_trade_no": out_trade_no}).get("list") or [])
|
||||
return lst[0] if lst else None
|
||||
|
||||
def list_paid_since(self, since_ts, max_pages=10):
|
||||
"""从最新往前翻,翻到早于 since_ts 为止;只返回已付款的。"""
|
||||
out = []
|
||||
for page in range(1, max_pages + 1):
|
||||
d = self.api("query-order", {"page": page})
|
||||
lst = d.get("list") or []
|
||||
for o in lst:
|
||||
if int(o.get("status") or 0) == 2:
|
||||
out.append(self.facts(o))
|
||||
if not lst or page >= int(d.get("total_page") or 1) or \
|
||||
min(float(o.get("create_time") or 0) for o in lst) < since_ts:
|
||||
break
|
||||
return out
|
||||
|
||||
def verify_notify(self, body, ctype):
|
||||
ok_resp = json.dumps({"ec": 200, "em": ""})
|
||||
try:
|
||||
obj = json.loads(body or b"{}")
|
||||
except ValueError:
|
||||
return None, "报文不是 JSON", ok_resp
|
||||
data = obj.get("data") or {}
|
||||
o = data.get("order") or {}
|
||||
otn = str(o.get("out_trade_no") or "")
|
||||
if not otn:
|
||||
return None, "缺 out_trade_no", ok_resp
|
||||
# ① 验签:out_trade_no + user_id + plan_id + total_amount,平台公钥,SHA256,Base64
|
||||
if self.pub is not None:
|
||||
content = "%s%s%s%s" % (otn, o.get("user_id") or "", o.get("plan_id") or "", o.get("total_amount") or "")
|
||||
if not rsa_verify(self.pub, content, data.get("sign")):
|
||||
return None, "验签失败", ok_resp
|
||||
# ② 用开放接口按订单号精确反查,之后只认反查结果
|
||||
real = self.query_trade(otn)
|
||||
if not real:
|
||||
return None, "接口反查不到这笔单", ok_resp
|
||||
f = self.facts(real)
|
||||
if not f["paid"]:
|
||||
return None, "反查结果未付款", ok_resp
|
||||
return f, "ok", ok_resp
|
||||
|
||||
def query(self, pay):
|
||||
for f in self.list_paid_since(pay["created_at"] - 600, max_pages=5):
|
||||
if f["pay_id"] == pay["pay_id"]:
|
||||
return f
|
||||
return None
|
||||
|
||||
def close(self, pay):
|
||||
return True # 爱发电无法远程关单,只在本地标记
|
||||
|
||||
def refund(self, pay, amount):
|
||||
raise RuntimeError("爱发电没有退款接口:请到爱发电后台对订单 %s 手动退款" % pay.get("trade_no"))
|
||||
|
||||
|
||||
# ================================================================ 支付宝当面付
|
||||
RISK_CODES = ("ACQ.ACCESS_FORBIDDEN", "ACQ.SELLER_BEEN_BLOCKED", "ACQ.RISK_CONTROL", "isv.insufficient-isv-permissions",
|
||||
"ACQ.MERCHANT_STATUS_NOT_NORMAL", "ACQ.PAYMENT_AUTH_CODE_INVALID")
|
||||
|
||||
|
||||
class AlipayF2F(Channel):
|
||||
name, label = "alipay", "支付宝扫码"
|
||||
|
||||
def __init__(self):
|
||||
cfg = dict(C.ALIPAY)
|
||||
self.mock = any(C.is_placeholder(cfg[k]) for k in ("app_id", "app_private_key_file", "alipay_public_key_file"))
|
||||
if self.mock:
|
||||
import mockgw
|
||||
cfg.update(app_id="mock-app", app_private_key_file=mockgw.key_path("alipay_app"),
|
||||
alipay_public_key_file=mockgw.key_path("alipay_platform", public=True),
|
||||
gateway=C.INTERNAL_URL + "/mock/alipay/gateway.do")
|
||||
self.cfg = cfg
|
||||
self.priv = load_priv(cfg["app_private_key_file"])
|
||||
self.pub = load_pub(cfg["alipay_public_key_file"])
|
||||
|
||||
def ttl(self):
|
||||
return C.QR_TTL
|
||||
|
||||
# ---- 熔断(连续失败 / 风控类错误码 → 关 6 小时)
|
||||
def breaker(self):
|
||||
return core.kv_get("alipay_breaker", {"fails": 0, "open_until": 0, "reason": ""})
|
||||
|
||||
def _ok(self):
|
||||
b = self.breaker()
|
||||
if b["fails"]:
|
||||
b["fails"] = 0
|
||||
core.kv_set("alipay_breaker", b)
|
||||
|
||||
def _fail(self, reason, risk=False):
|
||||
b = self.breaker()
|
||||
b["fails"] += 1
|
||||
b["reason"] = reason
|
||||
if risk or b["fails"] >= C.BREAKER_FAILS:
|
||||
b["open_until"] = core.now() + C.BREAKER_COOL
|
||||
core.event("alipay", "breaker_open", "", "", reason, b)
|
||||
core.kv_set("alipay_breaker", b)
|
||||
|
||||
def available(self, order):
|
||||
b = self.breaker()
|
||||
if b["open_until"] > core.now():
|
||||
return False, "支付宝扫码暂时不可用"
|
||||
if order["amount"] > C.ALI_MAX_AMOUNT:
|
||||
return False, "金额超过 ¥%d,请用爱发电" % C.ALI_MAX_AMOUNT
|
||||
t = core.now()
|
||||
n_order = core.q1("SELECT COUNT(*) AS c FROM payments WHERE oid=? AND channel='alipay' AND created_at>?",
|
||||
(order["oid"], t - 600))["c"]
|
||||
if n_order >= C.ALI_PER_ORDER_10MIN:
|
||||
return False, "二维码生成太频繁,稍后再试或用爱发电"
|
||||
n_all = core.q1("SELECT COUNT(*) AS c FROM payments WHERE channel='alipay' AND state='created'")["c"]
|
||||
if n_all >= C.ALI_GLOBAL_PENDING:
|
||||
return False, "当前扫码人数较多,请用爱发电"
|
||||
return True, ""
|
||||
|
||||
# ---- 网关调用:请求用应用私钥签,响应用支付宝公钥验
|
||||
def call(self, method, biz, notify=False):
|
||||
params = {"app_id": self.cfg["app_id"], "method": method, "format": "JSON", "charset": "utf-8",
|
||||
"sign_type": "RSA2", "timestamp": fmt_cst(time.time()), "version": "1.0",
|
||||
"biz_content": json.dumps(biz, ensure_ascii=False, separators=(",", ":"))}
|
||||
if notify:
|
||||
params["notify_url"] = C.BASE_URL + "/api/notify/alipay"
|
||||
params["sign"] = rsa_sign(self.priv, "&".join("%s=%s" % (k, params[k]) for k in sorted(params)))
|
||||
try:
|
||||
text = http_post(self.cfg["gateway"], urllib.parse.urlencode(params).encode(),
|
||||
"application/x-www-form-urlencoded;charset=utf-8")
|
||||
except Exception as e:
|
||||
self._fail("网关不通:%r" % e)
|
||||
raise
|
||||
node = method.replace(".", "_") + "_response"
|
||||
raw_node = extract_json_node(text, node)
|
||||
sign = json.loads(text).get("sign")
|
||||
if raw_node is None or not rsa_verify(self.pub, raw_node, sign):
|
||||
self._fail("响应验签失败")
|
||||
raise RuntimeError("支付宝响应验签失败")
|
||||
r = json.loads(raw_node)
|
||||
code, sub = str(r.get("code")), str(r.get("sub_code") or "")
|
||||
if code != "10000" and sub in RISK_CODES:
|
||||
self._fail("风控/权限:%s %s" % (sub, r.get("sub_msg")), risk=True)
|
||||
elif code in ("10000", "40004"):
|
||||
self._ok()
|
||||
else:
|
||||
self._fail("%s %s" % (code, sub))
|
||||
return r
|
||||
|
||||
def create(self, order, pay):
|
||||
r = self.call("alipay.trade.precreate", {
|
||||
"out_trade_no": pay["pay_id"], "total_amount": "%.2f" % pay["amount_due"],
|
||||
"subject": "%s %s" % (self.cfg["subject"], order["oid"]),
|
||||
"time_expire": fmt_cst(core.now() + C.QR_TTL)}, notify=True)
|
||||
if str(r.get("code")) != "10000":
|
||||
raise RuntimeError("预下单失败:%s %s" % (r.get("sub_code") or r.get("code"), r.get("sub_msg") or r.get("msg")))
|
||||
return {"type": "qr", "qr": r["qr_code"], "expire_at": pay["expire_at"]}
|
||||
|
||||
def query(self, pay):
|
||||
r = self.call("alipay.trade.query", {"out_trade_no": pay["pay_id"]})
|
||||
if str(r.get("code")) != "10000":
|
||||
return None
|
||||
st = r.get("trade_status")
|
||||
return {"pay_id": pay["pay_id"], "trade_no": str(r.get("trade_no") or ""),
|
||||
"amount": float(r.get("total_amount") or 0), "paid": st in ("TRADE_SUCCESS", "TRADE_FINISHED"),
|
||||
"raw": json.dumps(r, ensure_ascii=False)}
|
||||
|
||||
def close(self, pay):
|
||||
r = self.call("alipay.trade.close", {"out_trade_no": pay["pay_id"]})
|
||||
return str(r.get("code")) == "10000" or r.get("sub_code") == "ACQ.TRADE_NOT_EXIST"
|
||||
|
||||
def refund(self, pay, amount):
|
||||
r = self.call("alipay.trade.refund", {"out_trade_no": pay["pay_id"], "refund_amount": "%.2f" % amount,
|
||||
"out_request_no": "%sR%d" % (pay["pay_id"], int(time.time()))})
|
||||
if str(r.get("code")) != "10000":
|
||||
raise RuntimeError("退款失败:%s %s" % (r.get("sub_code"), r.get("sub_msg")))
|
||||
return r
|
||||
|
||||
def verify_notify(self, body, ctype):
|
||||
form = dict(urllib.parse.parse_qsl((body or b"").decode("utf-8"), keep_blank_values=True))
|
||||
sign = form.pop("sign", "")
|
||||
form.pop("sign_type", None)
|
||||
content = "&".join("%s=%s" % (k, form[k]) for k in sorted(form) if form[k] != "")
|
||||
if not rsa_verify(self.pub, content, sign):
|
||||
return None, "验签失败", "fail"
|
||||
if form.get("app_id") != self.cfg["app_id"]:
|
||||
return None, "app_id 不符", "fail"
|
||||
f = {"pay_id": form.get("out_trade_no", ""), "trade_no": form.get("trade_no", ""),
|
||||
"amount": float(form.get("total_amount") or 0),
|
||||
"paid": form.get("trade_status") in ("TRADE_SUCCESS", "TRADE_FINISHED"),
|
||||
"raw": json.dumps(form, ensure_ascii=False)}
|
||||
if not f["paid"]:
|
||||
return None, "状态 %s,不是到账" % form.get("trade_status"), "success"
|
||||
return f, "ok", "success"
|
||||
|
||||
|
||||
def extract_json_node(text, key):
|
||||
"""取出响应里某个节点的**原始 JSON 文本**(支付宝对原文签名,不能先解析再序列化)。"""
|
||||
m = re.search(r'"%s"\s*:\s*' % re.escape(key), text)
|
||||
if not m:
|
||||
return None
|
||||
i = m.end()
|
||||
if i >= len(text) or text[i] != "{":
|
||||
return None
|
||||
depth, in_str, esc = 0, False, False
|
||||
for j in range(i, len(text)):
|
||||
ch = text[j]
|
||||
if in_str:
|
||||
if esc:
|
||||
esc = False
|
||||
elif ch == "\\":
|
||||
esc = True
|
||||
elif ch == '"':
|
||||
in_str = False
|
||||
elif ch == '"':
|
||||
in_str = True
|
||||
elif ch == "{":
|
||||
depth += 1
|
||||
elif ch == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return text[i:j + 1]
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 注册表
|
||||
_CH = {}
|
||||
|
||||
|
||||
def init():
|
||||
_CH["afdian"] = Afdian()
|
||||
_CH["alipay"] = AlipayF2F()
|
||||
|
||||
|
||||
def get(name):
|
||||
return _CH[name]
|
||||
|
||||
|
||||
def all_channels():
|
||||
return [_CH["afdian"], _CH["alipay"]]
|
||||
|
||||
|
||||
def safe_close(pay):
|
||||
try:
|
||||
get(pay["channel"]).close(pay)
|
||||
core.event(pay["channel"], "close", pay["pay_id"], pay["oid"], "ok")
|
||||
except Exception as e:
|
||||
core.event(pay["channel"], "close", pay["pay_id"], pay["oid"], "error", repr(e))
|
||||
@@ -0,0 +1,71 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""支付原型的配置。
|
||||
|
||||
所有账号 / 密钥都是 <占位符>。值是占位符的渠道自动接到原型内置的「模拟网关」
|
||||
(mockgw.py:模拟爱发电收银台 + 查单接口、模拟支付宝网关 + 扫码页),
|
||||
签名、验签、HTTP 调用走的都是真实代码,只是对面换成了模拟器。
|
||||
填上真实值(环境变量或直接改这里)就切到真渠道。
|
||||
"""
|
||||
import os
|
||||
|
||||
|
||||
def env(k, d=""):
|
||||
return os.environ.get(k, d)
|
||||
|
||||
|
||||
def is_placeholder(v):
|
||||
return isinstance(v, str) and v.startswith("<") and v.endswith(">")
|
||||
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
DATA_DIR = env("PAY_DATA_DIR", os.path.join(HERE, "data"))
|
||||
PORT = int(env("PAY_PORT", "18100"))
|
||||
# 对外地址:拼回调地址、专链、二维码页用(原型挂在预览站 /pay-proto/ 下)
|
||||
BASE_URL = env("PAY_BASE_URL", "http://127.0.0.1:%d" % PORT).rstrip("/")
|
||||
# 服务器自己调自己(模拟网关)用的内网地址
|
||||
INTERNAL_URL = "http://127.0.0.1:%d" % PORT
|
||||
# 站点地址:模拟收银台付完「回到订单页」用(预览站根)
|
||||
SITE_URL = env("PAY_SITE_URL", BASE_URL).rstrip("/")
|
||||
ADMIN_TOKEN = env("PAY_ADMIN_TOKEN", "<PAY_ADMIN_TOKEN>")
|
||||
|
||||
# ---------------- 爱发电(主通道) ----------------
|
||||
AFDIAN = {
|
||||
"user_id": env("AFDIAN_USER_ID", "<AFDIAN_USER_ID>"),
|
||||
"token": env("AFDIAN_TOKEN", "<AFDIAN_TOKEN>"),
|
||||
# 爱发电开发者后台给的 Webhook 验签公钥(PEM 文件路径)
|
||||
"pubkey_file": env("AFDIAN_PUBKEY_FILE", "<AFDIAN_PUBKEY_FILE>"),
|
||||
# 承载 custom_price 的「自选金额」方案
|
||||
"plan_id": env("AFDIAN_PLAN_ID", "<AFDIAN_PLAN_ID>"),
|
||||
"api": "https://afdian.com/api/open",
|
||||
"checkout": "https://afdian.com/order/create",
|
||||
}
|
||||
|
||||
# ---------------- 支付宝当面付(辅助通道) ----------------
|
||||
ALIPAY = {
|
||||
"app_id": env("ALIPAY_APP_ID", "<ALIPAY_APP_ID>"),
|
||||
"app_private_key_file": env("ALIPAY_APP_PRIVATE_KEY_FILE", "<ALIPAY_APP_PRIVATE_KEY_FILE>"),
|
||||
"alipay_public_key_file": env("ALIPAY_PUBLIC_KEY_FILE", "<ALIPAY_PUBLIC_KEY_FILE>"),
|
||||
"gateway": "https://openapi.alipay.com/gateway.do",
|
||||
"subject": "金钻工坊 渲染服务", # 商品名:中性、真实
|
||||
}
|
||||
|
||||
PRICE_UNIT = 6 # 每张图 ¥
|
||||
# 模板 key → 名字(和下单页一致);分辨率可选值
|
||||
TEMPLATES = {"stand": "站立正反", "standb": "站立正反(虚化)", "wheat": "麦田萤火", "beach": "海边自拍",
|
||||
"boom": "不看爆炸", "sakura": "飞跃樱花林", "airship": "空艇巡游"}
|
||||
RESOLUTIONS = (1000, 1024, 2048, 4096)
|
||||
|
||||
# ---------------- 时间参数(秒) ----------------
|
||||
QR_TTL = 15 * 60 # 当面付二维码有效期
|
||||
AFD_TTL = 2 * 3600 # 爱发电支付单本地有效期(过期后付款仍能被对账收回)
|
||||
ORDER_TTL = 24 * 3600 # 订单待付款保留
|
||||
LATE_GRACE = 72 * 3600 # 订单关闭后,迟到付款自动恢复的宽限
|
||||
QUERY_MIN_GAP = 5 # 同一张当面付支付单两次查单的最小间隔
|
||||
JOB_TICK = 60 # 定时任务一轮的间隔
|
||||
|
||||
# ---------------- 当面付降风险 ----------------
|
||||
ALI_MAX_AMOUNT = 500 # 单笔上限,超过只给爱发电
|
||||
ALI_PER_ORDER_10MIN = 3 # 同一订单 10 分钟内最多生成几个二维码
|
||||
ALI_GLOBAL_PENDING = 20 # 全站同时未付的当面付二维码上限
|
||||
BREAKER_FAILS = 3 # 连续失败几次熔断
|
||||
BREAKER_COOL = 6 * 3600 # 熔断多久
|
||||
@@ -0,0 +1,331 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""支付原型核心:数据库、时钟、统一到账入口 settle_payment()、订单状态机、定时任务。
|
||||
|
||||
订单状态:unpaid → waiting(到账)/ closed(超时)/ void(注销);closed → waiting(宽限期内迟到付款)
|
||||
支付单状态:created → paid / mismatch / closed;closed → paid(迟到);paid / mismatch → refunded
|
||||
"""
|
||||
import json, os, secrets, sqlite3, threading, time
|
||||
|
||||
import config as C
|
||||
|
||||
LOCK = threading.RLock()
|
||||
_DB = None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 时钟(原型可快进,方便演示超时)
|
||||
def now():
|
||||
return time.time() + float(kv_get("clock_offset", 0) or 0)
|
||||
|
||||
|
||||
def advance_clock(seconds):
|
||||
kv_set("clock_offset", float(kv_get("clock_offset", 0) or 0) + seconds)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 数据库
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS orders(
|
||||
oid TEXT PRIMARY KEY, token TEXT, state TEXT, n_img INTEGER, amount INTEGER,
|
||||
created_at REAL, paid_at REAL, closed_at REAL, buyer_claim_at REAL, note TEXT DEFAULT '',
|
||||
templates TEXT DEFAULT '[]', res INTEGER DEFAULT 1000, skin_name TEXT DEFAULT '');
|
||||
CREATE TABLE IF NOT EXISTS payments(
|
||||
pay_id TEXT PRIMARY KEY, oid TEXT, channel TEXT, amount_due INTEGER, state TEXT,
|
||||
created_at REAL, expire_at REAL, trade_no TEXT UNIQUE, amount_paid REAL, paid_at REAL,
|
||||
last_query_at REAL DEFAULT 0, display TEXT DEFAULT '{}', note TEXT DEFAULT '');
|
||||
CREATE INDEX IF NOT EXISTS pay_oid ON payments(oid);
|
||||
CREATE TABLE IF NOT EXISTS pay_events(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, ts REAL, channel TEXT, kind TEXT,
|
||||
pay_id TEXT, oid TEXT, result TEXT, raw TEXT);
|
||||
CREATE TABLE IF NOT EXISTS pay_todo(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, ts REAL, kind TEXT, oid TEXT, pay_id TEXT, channel TEXT,
|
||||
trade_no TEXT, amount_due REAL, amount_paid REAL, detail TEXT, state TEXT DEFAULT 'open',
|
||||
resolution TEXT DEFAULT '', resolved_at REAL);
|
||||
CREATE TABLE IF NOT EXISTS kv(k TEXT PRIMARY KEY, v TEXT);
|
||||
"""
|
||||
|
||||
|
||||
def db():
|
||||
global _DB
|
||||
if _DB is None:
|
||||
os.makedirs(C.DATA_DIR, exist_ok=True)
|
||||
_DB = sqlite3.connect(os.path.join(C.DATA_DIR, "pay.db"), check_same_thread=False,
|
||||
isolation_level=None)
|
||||
_DB.row_factory = sqlite3.Row
|
||||
_DB.execute("PRAGMA journal_mode=WAL")
|
||||
_DB.executescript(SCHEMA)
|
||||
for col, decl in (("templates", "TEXT DEFAULT '[]'"), ("res", "INTEGER DEFAULT 1000"),
|
||||
("skin_name", "TEXT DEFAULT ''")):
|
||||
try: # 老库补列
|
||||
_DB.execute("ALTER TABLE orders ADD COLUMN %s %s" % (col, decl))
|
||||
except sqlite3.OperationalError:
|
||||
pass
|
||||
return _DB
|
||||
|
||||
|
||||
def q(sql, args=()):
|
||||
with LOCK:
|
||||
return [dict(r) for r in db().execute(sql, args).fetchall()]
|
||||
|
||||
|
||||
def q1(sql, args=()):
|
||||
r = q(sql, args)
|
||||
return r[0] if r else None
|
||||
|
||||
|
||||
def x(sql, args=()):
|
||||
with LOCK:
|
||||
return db().execute(sql, args)
|
||||
|
||||
|
||||
def kv_get(k, d=None):
|
||||
with LOCK:
|
||||
r = db().execute("SELECT v FROM kv WHERE k=?", (k,)).fetchone()
|
||||
if not r:
|
||||
return d
|
||||
try:
|
||||
return json.loads(r[0])
|
||||
except ValueError:
|
||||
return d
|
||||
|
||||
|
||||
def kv_set(k, v):
|
||||
x("INSERT INTO kv(k,v) VALUES(?,?) ON CONFLICT(k) DO UPDATE SET v=excluded.v", (k, json.dumps(v)))
|
||||
|
||||
|
||||
def event(channel, kind, pay_id="", oid="", result="", raw=""):
|
||||
raw = raw if isinstance(raw, str) else json.dumps(raw, ensure_ascii=False)
|
||||
x("INSERT INTO pay_events(ts,channel,kind,pay_id,oid,result,raw) VALUES(?,?,?,?,?,?,?)",
|
||||
(now(), channel, kind, pay_id, oid, result, raw[:4096]))
|
||||
|
||||
|
||||
def todo(kind, detail, oid="", pay_id="", channel="", trade_no="", amount_due=None, amount_paid=None):
|
||||
# 同一笔渠道流水只进一次待办(回调 + 对账可能各报一次)
|
||||
if trade_no and q1("SELECT id FROM pay_todo WHERE trade_no=? AND kind=?", (trade_no, kind)):
|
||||
return
|
||||
x("INSERT INTO pay_todo(ts,kind,oid,pay_id,channel,trade_no,amount_due,amount_paid,detail) "
|
||||
"VALUES(?,?,?,?,?,?,?,?,?)", (now(), kind, oid, pay_id, channel, trade_no, amount_due, amount_paid, detail))
|
||||
event(channel, "todo", pay_id, oid, kind, detail)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 订单 / 支付单
|
||||
def new_order(templates=None, res=1000, skin_name="", n_img=None):
|
||||
"""下单。templates = 模板 key 列表(一张皮肤 × 每个模板出一张);老调用只给 n_img 也行。"""
|
||||
tpls = [t for t in (templates or []) if t in C.TEMPLATES]
|
||||
tpls = list(dict.fromkeys(tpls))
|
||||
if tpls:
|
||||
n = len(tpls)
|
||||
else:
|
||||
n = max(1, min(int(n_img or 1), 20))
|
||||
res = int(res or 1000) if int(res or 1000) in C.RESOLUTIONS else 1000
|
||||
oid = "YS" + "".join(secrets.choice("ABCDEFGHJKLMNPQRSTUVWXYZ23456789") for _ in range(6))
|
||||
tok = "".join(secrets.choice("ABCDEFGHJKLMNPQRSTUVWXYZ23456789") for _ in range(10)) # 取件码:好抄、不混淆
|
||||
x("INSERT INTO orders(oid,token,state,n_img,amount,created_at,templates,res,skin_name) VALUES(?,?,?,?,?,?,?,?,?)",
|
||||
(oid, tok, "unpaid", n, n * C.PRICE_UNIT, now(), json.dumps(tpls), res, str(skin_name or "")[:80]))
|
||||
event("", "order_created", "", oid, "unpaid", {"templates": tpls, "res": res, "amount": n * C.PRICE_UNIT})
|
||||
return get_order(oid)
|
||||
|
||||
|
||||
def get_order(oid):
|
||||
return q1("SELECT * FROM orders WHERE oid=?", (oid,))
|
||||
|
||||
|
||||
def order_payments(oid):
|
||||
return q("SELECT * FROM payments WHERE oid=? ORDER BY created_at", (oid,))
|
||||
|
||||
|
||||
def get_payment(pay_id):
|
||||
return q1("SELECT * FROM payments WHERE pay_id=?", (pay_id,))
|
||||
|
||||
|
||||
def new_payment(order, channel, ttl):
|
||||
with LOCK:
|
||||
seq = (q1("SELECT COUNT(*) AS c FROM payments WHERE oid=?", (order["oid"],)) or {}).get("c", 0) + 1
|
||||
pay_id = "%sP%d" % (order["oid"], seq)
|
||||
t = now()
|
||||
x("INSERT INTO payments(pay_id,oid,channel,amount_due,state,created_at,expire_at) VALUES(?,?,?,?,?,?,?)",
|
||||
(pay_id, order["oid"], channel, order["amount"], "created", t, t + ttl))
|
||||
event(channel, "payment_created", pay_id, order["oid"], "created", {"amount_due": order["amount"]})
|
||||
return get_payment(pay_id)
|
||||
|
||||
|
||||
def set_display(pay_id, display):
|
||||
x("UPDATE payments SET display=? WHERE pay_id=?", (json.dumps(display, ensure_ascii=False), pay_id))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 统一到账入口
|
||||
def settle_payment(channel, pay_id, trade_no, amount_paid, source, raw=""):
|
||||
"""所有「钱到了」都只走这里。回调、对账、轮询、买家自查、后台认领都调它。
|
||||
|
||||
返回 {"result": ...}:
|
||||
activated 首次到账,订单激活
|
||||
reopened 订单已超时关闭,但在宽限期内 → 恢复并激活
|
||||
dup_trade 这笔渠道流水已经处理过(幂等,什么都不做)
|
||||
already 这张支付单早就到账了,这次是另一笔钱 → 待办「重复付款」
|
||||
short 金额不足 → 待办
|
||||
late 超过宽限才付 / 订单已注销 → 待办
|
||||
duplicate 订单已经被别的支付单激活过 → 待办「重复付款」
|
||||
unknown 对不上本地支付单 → 待办
|
||||
"""
|
||||
trade_no = str(trade_no or "")
|
||||
to_close = []
|
||||
with LOCK:
|
||||
conn = db()
|
||||
conn.execute("BEGIN IMMEDIATE")
|
||||
try:
|
||||
if trade_no and conn.execute("SELECT 1 FROM payments WHERE trade_no=?", (trade_no,)).fetchone():
|
||||
conn.execute("COMMIT")
|
||||
event(channel, "settle", pay_id, "", "dup_trade", {"trade_no": trade_no, "source": source})
|
||||
return {"result": "dup_trade"}
|
||||
p = conn.execute("SELECT * FROM payments WHERE pay_id=?", (pay_id,)).fetchone()
|
||||
if not p:
|
||||
conn.execute("COMMIT")
|
||||
todo("unknown", "渠道报了一笔对不上本地支付单的到账(%s)" % pay_id, "", pay_id, channel,
|
||||
trade_no, None, amount_paid)
|
||||
return {"result": "unknown"}
|
||||
p = dict(p)
|
||||
oid = p["oid"]
|
||||
if p["state"] in ("paid", "refunded"):
|
||||
conn.execute("COMMIT")
|
||||
todo("duplicate", "同一张支付单又来了一笔钱(第一笔 %s)" % p["trade_no"], oid, pay_id, channel,
|
||||
trade_no, p["amount_due"], amount_paid)
|
||||
return {"result": "already"}
|
||||
if float(amount_paid or 0) + 0.005 < float(p["amount_due"]):
|
||||
conn.execute("UPDATE payments SET state='mismatch',trade_no=?,amount_paid=?,paid_at=?,note=? "
|
||||
"WHERE pay_id=?", (trade_no or None, amount_paid, now(), "金额不足", pay_id))
|
||||
conn.execute("COMMIT")
|
||||
todo("short", "实付 ¥%s,应付 ¥%s,未激活" % (amount_paid, p["amount_due"]), oid, pay_id,
|
||||
channel, trade_no, p["amount_due"], amount_paid)
|
||||
return {"result": "short"}
|
||||
conn.execute("UPDATE payments SET state='paid',trade_no=?,amount_paid=?,paid_at=?,note=? WHERE pay_id=?",
|
||||
(trade_no or None, amount_paid, now(), "到账(%s)" % source, pay_id))
|
||||
o = dict(conn.execute("SELECT * FROM orders WHERE oid=?", (oid,)).fetchone())
|
||||
if o["state"] == "unpaid":
|
||||
res = "activated"
|
||||
elif o["state"] == "closed" and now() - float(o["closed_at"] or 0) <= C.LATE_GRACE:
|
||||
res = "reopened"
|
||||
elif o["state"] in ("closed", "void"):
|
||||
res = "late"
|
||||
else:
|
||||
res = "duplicate"
|
||||
if res in ("activated", "reopened"):
|
||||
conn.execute("UPDATE orders SET state='waiting',paid_at=? WHERE oid=?", (now(), oid))
|
||||
to_close = [dict(r) for r in conn.execute(
|
||||
"SELECT * FROM payments WHERE oid=? AND state='created' AND pay_id<>?", (oid, pay_id))]
|
||||
conn.execute("UPDATE payments SET state='closed',note='订单已在别的支付单付过' "
|
||||
"WHERE oid=? AND state='created' AND pay_id<>?", (oid, pay_id))
|
||||
conn.execute("COMMIT")
|
||||
except Exception:
|
||||
conn.execute("ROLLBACK")
|
||||
raise
|
||||
event(channel, "settle", pay_id, oid, res, {"trade_no": trade_no, "amount": amount_paid, "source": source})
|
||||
if res == "late":
|
||||
todo("late", "订单已%s,超过宽限才到账" % ("注销" if o["state"] == "void" else "关闭"), oid, pay_id,
|
||||
channel, trade_no, p["amount_due"], amount_paid)
|
||||
elif res == "duplicate":
|
||||
todo("duplicate", "订单已经付过(状态 %s),这笔是重复付款" % o["state"], oid, pay_id, channel,
|
||||
trade_no, p["amount_due"], amount_paid)
|
||||
if to_close:
|
||||
import channels
|
||||
for op in to_close:
|
||||
channels.safe_close(op)
|
||||
return {"result": res}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 定时任务
|
||||
def job_afdian_reconcile():
|
||||
import channels
|
||||
ch = channels.get("afdian")
|
||||
oldest = q1("SELECT MIN(created_at) AS t FROM payments WHERE channel='afdian' AND "
|
||||
"(state='created' OR (state='closed' AND created_at>?))", (now() - C.LATE_GRACE,))
|
||||
if not oldest or not oldest.get("t"):
|
||||
return 0
|
||||
n = 0
|
||||
for f in ch.list_paid_since(oldest["t"] - 600):
|
||||
if f.get("pay_id"):
|
||||
p = get_payment(f["pay_id"])
|
||||
if p and p["state"] in ("created", "closed"):
|
||||
r = settle_payment("afdian", f["pay_id"], f["trade_no"], f["amount"], "reconcile", f.get("raw", ""))
|
||||
n += r["result"] in ("activated", "reopened")
|
||||
return n
|
||||
|
||||
|
||||
def job_alipay_poll():
|
||||
import channels
|
||||
ch = channels.get("alipay")
|
||||
t = now()
|
||||
rows = q("SELECT * FROM payments WHERE channel='alipay' AND state='created' AND created_at<? AND last_query_at<?",
|
||||
(t - 60, t - 30))
|
||||
for p in rows:
|
||||
poll_payment(ch, p, "poll")
|
||||
return len(rows)
|
||||
|
||||
|
||||
def poll_payment(ch, p, source):
|
||||
x("UPDATE payments SET last_query_at=? WHERE pay_id=?", (now(), p["pay_id"]))
|
||||
f = ch.query(p)
|
||||
if f and f.get("paid"):
|
||||
return settle_payment(ch.name, p["pay_id"], f["trade_no"], f["amount"], source, f.get("raw", ""))
|
||||
return {"result": "unpaid"}
|
||||
|
||||
|
||||
def job_expire_payments():
|
||||
import channels
|
||||
rows = q("SELECT * FROM payments WHERE state='created' AND expire_at<=?", (now(),))
|
||||
for p in rows:
|
||||
ch = channels.get(p["channel"])
|
||||
f = ch.query(p) # 关单前最后查一次,防止「刚付就被关」
|
||||
if f and f.get("paid"):
|
||||
settle_payment(ch.name, p["pay_id"], f["trade_no"], f["amount"], "expire_check", f.get("raw", ""))
|
||||
continue
|
||||
x("UPDATE payments SET state='closed',note='过期' WHERE pay_id=? AND state='created'", (p["pay_id"],))
|
||||
channels.safe_close(p)
|
||||
event(ch.name, "payment_expired", p["pay_id"], p["oid"], "closed")
|
||||
return len(rows)
|
||||
|
||||
|
||||
def job_close_orders():
|
||||
t = now()
|
||||
rows = q("SELECT * FROM orders WHERE state='unpaid' AND created_at<=?", (t - C.ORDER_TTL,))
|
||||
n = 0
|
||||
for o in rows:
|
||||
if q1("SELECT 1 AS y FROM payments WHERE oid=? AND state='created'", (o["oid"],)):
|
||||
continue
|
||||
x("UPDATE orders SET state='closed',closed_at=? WHERE oid=? AND state='unpaid'", (t, o["oid"]))
|
||||
event("", "order_closed", "", o["oid"], "closed", "超过 %d 小时未付款" % (C.ORDER_TTL // 3600))
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
def job_late_scan():
|
||||
"""最近宽限期内关闭的当面付支付单再查一次,抓迟到付款(爱发电的由对账覆盖)。"""
|
||||
import channels
|
||||
ch = channels.get("alipay")
|
||||
rows = q("SELECT * FROM payments WHERE channel='alipay' AND state='closed' AND created_at>? AND last_query_at<?",
|
||||
(now() - C.LATE_GRACE, now() - 600))
|
||||
for p in rows:
|
||||
poll_payment(ch, p, "late_scan")
|
||||
return len(rows)
|
||||
|
||||
|
||||
JOBS = [("爱发电对账", job_afdian_reconcile), ("当面付补查", job_alipay_poll),
|
||||
("支付单过期", job_expire_payments), ("订单超时关闭", job_close_orders), ("迟到付款扫描", job_late_scan)]
|
||||
|
||||
|
||||
def run_jobs():
|
||||
out = {}
|
||||
for name, fn in JOBS:
|
||||
try:
|
||||
out[name] = fn()
|
||||
except Exception as e: # 单个任务失败不影响其他任务
|
||||
out[name] = "错误:%r" % e
|
||||
event("", "job_error", "", "", name, repr(e))
|
||||
return out
|
||||
|
||||
|
||||
def scheduler():
|
||||
while True:
|
||||
time.sleep(C.JOB_TICK)
|
||||
run_jobs()
|
||||
|
||||
|
||||
def start_scheduler():
|
||||
threading.Thread(target=scheduler, daemon=True).start()
|
||||
@@ -0,0 +1,285 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""模拟网关:配置还是占位符时,渠道代码连的是这里。
|
||||
|
||||
模拟爱发电:收银台页面(金额可改、可模拟回调丢失)+ query-order 接口(校验 md5 签名)+ Webhook 推送(RSA 签名)。
|
||||
模拟支付宝:gateway.do(校验应用签名,响应用「支付宝」私钥签名)+ 手机扫码付款页 + 异步通知。
|
||||
密钥首次启动时生成在 data/mock_keys/,只用于模拟,和真实渠道无关。
|
||||
"""
|
||||
import hashlib, html, json, os, secrets, threading, time, urllib.parse
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
|
||||
import config as C
|
||||
import core
|
||||
|
||||
KEY_DIR = os.path.join(C.DATA_DIR, "mock_keys")
|
||||
|
||||
|
||||
def key_path(name, public=False):
|
||||
os.makedirs(KEY_DIR, exist_ok=True)
|
||||
priv = os.path.join(KEY_DIR, name + ".pem")
|
||||
pub = os.path.join(KEY_DIR, name + ".pub.pem")
|
||||
if not os.path.exists(priv):
|
||||
k = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
with open(priv, "wb") as f:
|
||||
f.write(k.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption()))
|
||||
os.chmod(priv, 0o600)
|
||||
with open(pub, "wb") as f:
|
||||
f.write(k.public_key().public_bytes(serialization.Encoding.PEM,
|
||||
serialization.PublicFormat.SubjectPublicKeyInfo))
|
||||
return pub if public else priv
|
||||
|
||||
|
||||
def init():
|
||||
core.db().executescript("""
|
||||
CREATE TABLE IF NOT EXISTS mock_afd(out_trade_no TEXT PRIMARY KEY, custom_order_id TEXT, user_id TEXT,
|
||||
plan_id TEXT, total_amount TEXT, status INTEGER, remark TEXT, create_time INTEGER);
|
||||
CREATE TABLE IF NOT EXISTS mock_ali(out_trade_no TEXT PRIMARY KEY, trade_no TEXT, total_amount TEXT, subject TEXT,
|
||||
status TEXT, notify_url TEXT, expire_ts REAL, qr TEXT, created REAL, paid_at REAL, refunded TEXT DEFAULT '0');
|
||||
""")
|
||||
for n in ("afdian_platform", "alipay_platform", "alipay_app"):
|
||||
key_path(n)
|
||||
|
||||
|
||||
def _priv(name):
|
||||
from channels import load_priv
|
||||
return load_priv(key_path(name))
|
||||
|
||||
|
||||
def _pub(name):
|
||||
from channels import load_pub
|
||||
return load_pub(key_path(name, public=True))
|
||||
|
||||
|
||||
def _later(fn, delay=0.6):
|
||||
threading.Timer(delay, fn).start()
|
||||
|
||||
|
||||
def _post(url, body, ctype):
|
||||
from channels import http_post
|
||||
try:
|
||||
return http_post(url, body, ctype)
|
||||
except Exception as e:
|
||||
return "ERR %r" % e
|
||||
|
||||
|
||||
def _trade_no():
|
||||
return time.strftime("%Y%m%d%H%M%S") + "".join(secrets.choice("0123456789") for _ in range(10))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 页面外壳
|
||||
def page(title, body):
|
||||
return ("""<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1"><title>%s</title>
|
||||
<style>
|
||||
body{margin:0;font:15px/1.7 system-ui,"PingFang SC","Microsoft YaHei",sans-serif;background:#f3f4f6;color:#1f2329}
|
||||
.top{padding:12px 16px;color:#fff;font-weight:600}
|
||||
.box{max-width:420px;margin:18px auto;background:#fff;border-radius:12px;padding:20px 18px;box-shadow:0 8px 24px -16px rgba(0,0,0,.3)}
|
||||
.amt{font-size:34px;font-weight:700;margin:6px 0}
|
||||
.mute{color:#6b7280;font-size:13px}
|
||||
label{display:flex;gap:8px;align-items:center;margin:10px 0;font-size:14px}
|
||||
input[type=number]{font-size:20px;width:120px;padding:6px 8px;border:1px solid #d1d5db;border-radius:8px}
|
||||
button{width:100%%;margin-top:12px;padding:12px;border:0;border-radius:10px;font-size:16px;font-weight:600;color:#fff;cursor:pointer}
|
||||
.warn{background:#fff7e6;border-radius:8px;padding:8px 10px;font-size:13px;color:#8a5a00;margin-top:10px}
|
||||
code{background:#f3f4f6;padding:1px 5px;border-radius:4px;font-size:12.5px}
|
||||
</style></head><body>%s</body></html>""" % (html.escape(title), body)).encode("utf-8")
|
||||
|
||||
|
||||
# ================================================================ 模拟爱发电
|
||||
def afd_checkout(qs):
|
||||
g = lambda k: (qs.get(k) or [""])[0]
|
||||
price = g("custom_price") or "0"
|
||||
body = """<div class="top" style="background:#946ce6">爱发电(模拟收银台)</div>
|
||||
<div class="box"><div class="mute">自选金额发电 · 方案 <code>%s</code></div>
|
||||
<div class="amt">¥<span id="a">%s</span></div>
|
||||
<div class="mute">订单留言:%s<br>custom_order_id:<code>%s</code></div>
|
||||
<form method="post" action="pay">
|
||||
<input type="hidden" name="custom_order_id" value="%s"><input type="hidden" name="remark" value="%s">
|
||||
<label>实付金额(可改,模拟买家改价)<input type="number" step="0.01" min="0" name="amount" value="%s"></label>
|
||||
<label><input type="checkbox" name="drop"> 模拟 Webhook 丢失(靠对账补)</label>
|
||||
<button style="background:#946ce6">确认付款</button></form>
|
||||
<div class="warn">这是原型里的模拟页面,不会真的扣钱。</div></div>""" % tuple(html.escape(x) for x in (
|
||||
g("plan_id"), price, g("remark") or "(无)", g("custom_order_id") or "(无)",
|
||||
g("custom_order_id"), g("remark"), price))
|
||||
return 200, "text/html; charset=utf-8", page("爱发电 · 模拟收银台", body)
|
||||
|
||||
|
||||
def afd_create_order(custom_order_id, amount, remark, drop=False):
|
||||
otn = _trade_no()
|
||||
o = {"out_trade_no": otn, "custom_order_id": custom_order_id, "user_id": "buyer" + secrets.token_hex(4),
|
||||
"plan_id": "mock-plan", "total_amount": "%.2f" % float(amount or 0), "status": 2, "remark": remark,
|
||||
"create_time": int(core.now())}
|
||||
core.x("INSERT INTO mock_afd VALUES(?,?,?,?,?,?,?,?)", tuple(o[k] for k in (
|
||||
"out_trade_no", "custom_order_id", "user_id", "plan_id", "total_amount", "status", "remark", "create_time")))
|
||||
core.event("mock-afdian", "mock_paid", custom_order_id, "", "drop_webhook" if drop else "webhook_soon", o)
|
||||
if not drop:
|
||||
_later(lambda: afd_push(o))
|
||||
return o
|
||||
|
||||
|
||||
def afd_push(o, forge=False):
|
||||
from channels import rsa_sign
|
||||
content = "%s%s%s%s" % (o["out_trade_no"], o["user_id"], o["plan_id"], o["total_amount"])
|
||||
sign = rsa_sign(_priv("afdian_platform"), content)
|
||||
if forge:
|
||||
sign = sign[::-1]
|
||||
body = json.dumps({"ec": 200, "em": "ok", "data": {"type": "order", "order": o, "sign": sign}}).encode()
|
||||
return _post(C.INTERNAL_URL + "/api/notify/afdian", body, "application/json")
|
||||
|
||||
|
||||
def afd_pay(form):
|
||||
g = lambda k: (form.get(k) or [""])[0]
|
||||
o = afd_create_order(g("custom_order_id"), g("amount"), g("remark"), drop=bool(g("drop")))
|
||||
back = C.SITE_URL + "/pay.html?o=" + urllib.parse.quote(g("remark") or "")
|
||||
body = """<div class="top" style="background:#946ce6">爱发电(模拟)</div><div class="box">
|
||||
<div class="amt">付款成功</div><div class="mute">爱发电订单号 <code>%s</code><br>实付 ¥%s%s</div>
|
||||
<p><a href="%s">回到订单页</a>(订单页会自动发现到账)</p></div>""" % (
|
||||
o["out_trade_no"], o["total_amount"], "<br><b>已模拟 Webhook 丢失</b>,等对账补上" if g("drop") else "", back)
|
||||
return 200, "text/html; charset=utf-8", page("付款成功", body)
|
||||
|
||||
|
||||
def afd_api(path, raw):
|
||||
try:
|
||||
req = json.loads(raw or b"{}")
|
||||
except ValueError:
|
||||
return _json({"ec": 400, "em": "bad json"})
|
||||
want = hashlib.md5(("mock-tokenparams%sts%suser_id%s" % (req.get("params"), req.get("ts"), req.get("user_id")))
|
||||
.encode()).hexdigest()
|
||||
if req.get("user_id") != "mock-user" or req.get("sign") != want:
|
||||
return _json({"ec": 400005, "em": "sign error"})
|
||||
if not path.endswith("query-order"):
|
||||
return _json({"ec": 404, "em": "unknown api"})
|
||||
p = json.loads(req.get("params") or "{}")
|
||||
cols = ("out_trade_no", "custom_order_id", "user_id", "plan_id", "total_amount", "status", "remark", "create_time")
|
||||
if p.get("out_trade_no"):
|
||||
ids = [s for s in str(p["out_trade_no"]).split(",") if s]
|
||||
rows = core.q("SELECT * FROM mock_afd WHERE out_trade_no IN (%s)" % ",".join("?" * len(ids)), ids)
|
||||
return _json({"ec": 200, "data": {"list": [{k: r[k] for k in cols} for r in rows], "total_page": 1}})
|
||||
page_no = max(1, int(p.get("page") or 1))
|
||||
total = core.q1("SELECT COUNT(*) AS c FROM mock_afd")["c"]
|
||||
rows = core.q("SELECT * FROM mock_afd ORDER BY create_time DESC LIMIT 50 OFFSET ?", ((page_no - 1) * 50,))
|
||||
return _json({"ec": 200, "data": {"list": [{k: r[k] for k in cols} for r in rows],
|
||||
"total_count": total, "total_page": max(1, (total + 49) // 50)}})
|
||||
|
||||
|
||||
# ================================================================ 模拟支付宝
|
||||
def _ali_resp(method, node):
|
||||
from channels import rsa_sign
|
||||
key = method.replace(".", "_") + "_response"
|
||||
raw = json.dumps(node, ensure_ascii=False, separators=(",", ":"))
|
||||
sign = rsa_sign(_priv("alipay_platform"), raw)
|
||||
return 200, "application/json; charset=utf-8", ('{"%s":%s,"sign":"%s"}' % (key, raw, sign)).encode()
|
||||
|
||||
|
||||
def ali_gateway(raw):
|
||||
from channels import rsa_verify
|
||||
form = dict(urllib.parse.parse_qsl(raw.decode("utf-8"), keep_blank_values=True))
|
||||
sign = form.pop("sign", "")
|
||||
content = "&".join("%s=%s" % (k, form[k]) for k in sorted(form))
|
||||
method = form.get("method", "")
|
||||
if not rsa_verify(_pub("alipay_app"), content, sign):
|
||||
return _ali_resp(method, {"code": "40002", "msg": "Invalid Arguments", "sub_code": "isv.invalid-signature"})
|
||||
biz = json.loads(form.get("biz_content") or "{}")
|
||||
otn = biz.get("out_trade_no", "")
|
||||
t = core.q1("SELECT * FROM mock_ali WHERE out_trade_no=?", (otn,))
|
||||
if t and t["status"] in ("NEW", "WAIT_BUYER_PAY") and core.now() > t["expire_ts"]:
|
||||
core.x("UPDATE mock_ali SET status='TRADE_CLOSED' WHERE out_trade_no=?", (otn,))
|
||||
t["status"] = "TRADE_CLOSED"
|
||||
if method == "alipay.trade.precreate":
|
||||
if core.kv_get("mock_alipay_risk"):
|
||||
return _ali_resp(method, {"code": "40004", "msg": "Business Failed", "sub_code": "ACQ.ACCESS_FORBIDDEN",
|
||||
"sub_msg": "(模拟)商户收款功能被限制"})
|
||||
if t:
|
||||
return _ali_resp(method, {"code": "10000", "msg": "Success", "out_trade_no": otn,
|
||||
"qr_code": C.BASE_URL + "/mock/alipay/scan/" + t["qr"]})
|
||||
from datetime import datetime
|
||||
from channels import CST
|
||||
exp = datetime.strptime(biz["time_expire"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=CST).timestamp()
|
||||
qr = secrets.token_urlsafe(10)
|
||||
core.x("INSERT INTO mock_ali(out_trade_no,total_amount,subject,status,notify_url,expire_ts,qr,created) "
|
||||
"VALUES(?,?,?,?,?,?,?,?)", (otn, biz["total_amount"], biz.get("subject", ""), "NEW",
|
||||
form.get("notify_url", ""), exp, qr, core.now()))
|
||||
return _ali_resp(method, {"code": "10000", "msg": "Success", "out_trade_no": otn,
|
||||
"qr_code": C.BASE_URL + "/mock/alipay/scan/" + qr})
|
||||
if method == "alipay.trade.query":
|
||||
if not t or t["status"] == "NEW":
|
||||
return _ali_resp(method, {"code": "40004", "msg": "Business Failed", "sub_code": "ACQ.TRADE_NOT_EXIST",
|
||||
"sub_msg": "交易不存在"})
|
||||
return _ali_resp(method, {"code": "10000", "msg": "Success", "out_trade_no": otn,
|
||||
"trade_no": t["trade_no"] or "", "trade_status": t["status"],
|
||||
"total_amount": t["total_amount"]})
|
||||
if method == "alipay.trade.close":
|
||||
if not t or t["status"] == "NEW":
|
||||
if t:
|
||||
core.x("UPDATE mock_ali SET status='TRADE_CLOSED' WHERE out_trade_no=?", (otn,))
|
||||
return _ali_resp(method, {"code": "40004", "msg": "Business Failed", "sub_code": "ACQ.TRADE_NOT_EXIST"})
|
||||
if t["status"] == "WAIT_BUYER_PAY":
|
||||
core.x("UPDATE mock_ali SET status='TRADE_CLOSED' WHERE out_trade_no=?", (otn,))
|
||||
return _ali_resp(method, {"code": "10000", "msg": "Success", "out_trade_no": otn})
|
||||
return _ali_resp(method, {"code": "40004", "msg": "Business Failed", "sub_code": "ACQ.TRADE_STATUS_ERROR"})
|
||||
if method == "alipay.trade.refund":
|
||||
if not t or t["status"] not in ("TRADE_SUCCESS",):
|
||||
return _ali_resp(method, {"code": "40004", "msg": "Business Failed", "sub_code": "ACQ.TRADE_STATUS_ERROR"})
|
||||
core.x("UPDATE mock_ali SET refunded=? WHERE out_trade_no=?", (biz.get("refund_amount"), otn))
|
||||
return _ali_resp(method, {"code": "10000", "msg": "Success", "out_trade_no": otn, "trade_no": t["trade_no"],
|
||||
"refund_fee": biz.get("refund_amount"), "fund_change": "Y"})
|
||||
return _ali_resp(method, {"code": "40004", "msg": "Business Failed", "sub_code": "ACQ.METHOD_NOT_SUPPORTED"})
|
||||
|
||||
|
||||
def ali_scan(qr):
|
||||
t = core.q1("SELECT * FROM mock_ali WHERE qr=?", (qr,))
|
||||
if not t:
|
||||
return 404, "text/plain; charset=utf-8", "二维码无效".encode()
|
||||
if t["status"] in ("NEW", "WAIT_BUYER_PAY") and core.now() > t["expire_ts"]:
|
||||
core.x("UPDATE mock_ali SET status='TRADE_CLOSED' WHERE qr=?", (qr,))
|
||||
t["status"] = "TRADE_CLOSED"
|
||||
if t["status"] == "NEW":
|
||||
core.x("UPDATE mock_ali SET status='WAIT_BUYER_PAY' WHERE qr=?", (qr,))
|
||||
t["status"] = "WAIT_BUYER_PAY"
|
||||
if t["status"] != "WAIT_BUYER_PAY":
|
||||
msg = {"TRADE_SUCCESS": "这笔已经付过了", "TRADE_CLOSED": "二维码已失效,请回到订单页重新生成"}.get(t["status"], t["status"])
|
||||
body = '<div class="top" style="background:#1677ff">支付宝(模拟)</div><div class="box"><div class="amt" style="font-size:22px">%s</div></div>' % msg
|
||||
return 200, "text/html; charset=utf-8", page("支付宝", body)
|
||||
body = """<div class="top" style="background:#1677ff">支付宝(模拟扫码付款)</div>
|
||||
<div class="box"><div class="mute">%s</div><div class="amt">¥%s</div>
|
||||
<form method="post" action="../scanpay"><input type="hidden" name="qr" value="%s">
|
||||
<label><input type="checkbox" name="drop"> 模拟异步通知丢失(靠页面轮询 / 补查发现)</label>
|
||||
<button style="background:#1677ff">确认付款</button></form>
|
||||
<div class="warn">这是原型里的模拟页面,不会真的扣钱。</div></div>""" % (
|
||||
html.escape(t["subject"]), html.escape(t["total_amount"]), html.escape(qr))
|
||||
return 200, "text/html; charset=utf-8", page("支付宝 · 模拟扫码", body)
|
||||
|
||||
|
||||
def ali_scanpay(form):
|
||||
from channels import rsa_sign, fmt_cst
|
||||
g = lambda k: (form.get(k) or [""])[0]
|
||||
t = core.q1("SELECT * FROM mock_ali WHERE qr=?", (g("qr"),))
|
||||
if not t or t["status"] != "WAIT_BUYER_PAY" or core.now() > t["expire_ts"]:
|
||||
return 200, "text/html; charset=utf-8", page("支付宝", '<div class="box">二维码已失效</div>')
|
||||
tn = _trade_no()
|
||||
core.x("UPDATE mock_ali SET status='TRADE_SUCCESS',trade_no=?,paid_at=? WHERE qr=?", (tn, core.now(), g("qr")))
|
||||
core.event("mock-alipay", "mock_paid", t["out_trade_no"], "", "drop_notify" if g("drop") else "notify_soon",
|
||||
{"trade_no": tn, "amount": t["total_amount"]})
|
||||
if not g("drop") and t["notify_url"]:
|
||||
p = {"notify_time": fmt_cst(core.now()), "notify_type": "trade_status_sync", "notify_id": secrets.token_hex(8),
|
||||
"app_id": "mock-app", "charset": "utf-8", "version": "1.0", "trade_no": tn,
|
||||
"out_trade_no": t["out_trade_no"], "trade_status": "TRADE_SUCCESS", "total_amount": t["total_amount"],
|
||||
"receipt_amount": t["total_amount"], "buyer_pay_amount": t["total_amount"], "subject": t["subject"],
|
||||
"gmt_payment": fmt_cst(core.now())}
|
||||
p["sign"] = rsa_sign(_priv("alipay_platform"), "&".join("%s=%s" % (k, p[k]) for k in sorted(p)))
|
||||
p["sign_type"] = "RSA2"
|
||||
url = C.INTERNAL_URL + "/api/notify/alipay"
|
||||
_later(lambda: _post(url, urllib.parse.urlencode(p).encode(), "application/x-www-form-urlencoded"))
|
||||
body = """<div class="top" style="background:#1677ff">支付宝(模拟)</div><div class="box">
|
||||
<div class="amt">支付成功</div><div class="mute">¥%s · 交易号 <code>%s</code>%s</div>
|
||||
<p class="mute">回到电脑上的订单页,它会自动变成「已到账」。</p>
|
||||
<p><a href="%s/pay.html?o=%s">在这台设备看订单</a></p></div>""" % (
|
||||
t["total_amount"], tn, "<br><b>已模拟异步通知丢失</b>" if g("drop") else "",
|
||||
C.SITE_URL, urllib.parse.quote(t["out_trade_no"].rsplit("P", 1)[0]))
|
||||
return 200, "text/html; charset=utf-8", page("支付成功", body)
|
||||
|
||||
|
||||
def _json(obj):
|
||||
return 200, "application/json; charset=utf-8", json.dumps(obj, ensure_ascii=False).encode()
|
||||
@@ -0,0 +1,183 @@
|
||||
/* 自助渲染 · 下单与收银台(预览)—— 只放新组件,站点通用样式仍在 site.css */
|
||||
|
||||
/* ---------- 下单表单 ---------- */
|
||||
.buy-step{margin-top:26px}
|
||||
.buy-step>h3{margin:0 0 4px;font-size:18px}
|
||||
.buy-step>p{margin:0 0 14px;font-size:14px;color:var(--ink-3)}
|
||||
.tpl-grid .tpl{cursor:pointer;text-align:left;font:inherit;color:inherit;border:2px solid rgba(255,255,255,.95);transition:border-color .15s var(--ease),box-shadow .15s var(--ease)}
|
||||
.tpl .pick{position:absolute;top:18px;right:18px;width:24px;height:24px;border-radius:4px;background:rgba(255,255,255,.92);border:2px solid rgba(30,36,64,.18);display:grid;place-items:center;color:#fff;font-size:15px;font-weight:700;line-height:1}
|
||||
.tpl[aria-pressed=true]{border-color:var(--mc-green)!important;box-shadow:0 0 0 3px rgba(91,170,60,.22),0 18px 30px -22px rgba(29,77,19,.45)!important}
|
||||
.tpl[aria-pressed=true] .pick{background:var(--mc-green);border-color:var(--mc-green-lo)}
|
||||
.tpl:focus-visible{outline:3px solid var(--mc-green-hi);outline-offset:2px}
|
||||
|
||||
.skin{display:grid;grid-template-columns:132px minmax(0,1fr);gap:18px;align-items:start;padding:18px;border-radius:var(--r)}
|
||||
@media (max-width:560px){.skin{grid-template-columns:1fr}}
|
||||
.skin-drop{position:relative;display:grid;place-items:center;aspect-ratio:1/1;border-radius:12px;border:2px dashed rgba(140,150,200,.45);background:rgba(255,255,255,.7);cursor:pointer;text-align:center;font-size:13px;color:var(--ink-3);padding:8px;overflow:hidden}
|
||||
.skin-drop:hover{border-color:var(--mc-green-hi)}
|
||||
.skin-drop canvas{width:100%;height:100%;image-rendering:pixelated;display:block}
|
||||
.skin-drop input{position:absolute;inset:0;opacity:0;cursor:pointer}
|
||||
.skin-rep{display:flex;flex-direction:column;gap:8px}
|
||||
.lamp{display:flex;gap:10px;align-items:flex-start;padding:9px 12px;border-radius:10px;font-size:13.5px;color:var(--ink-2);background:rgba(255,255,255,.6)}
|
||||
.lamp::before{content:"";flex:none;width:8px;height:8px;margin-top:7px;border-radius:2px;background:#3CC985}
|
||||
.lamp.warn{background:rgba(245,178,62,.055)} .lamp.warn::before{background:#F5B23E}
|
||||
.lamp.bad{background:rgba(224,83,61,.055)} .lamp.bad::before{background:#E0533D}
|
||||
.lamp b{color:var(--ink)}
|
||||
.lamp label{display:flex;gap:6px;align-items:center;margin-top:4px;cursor:pointer}
|
||||
|
||||
.sumbar{position:sticky;bottom:12px;z-index:4;margin-top:26px;display:flex;flex-wrap:wrap;align-items:center;gap:12px 18px;padding:14px 18px;border-radius:var(--r);background:rgba(255,255,255,.96)!important;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}
|
||||
.sumbar .sum{display:flex;flex-direction:column;gap:2px;min-width:0}
|
||||
.sumbar .sum b{font-size:24px;font-variant-numeric:tabular-nums}
|
||||
.sumbar .sum span{font-size:13px;color:var(--ink-3);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.sumbar .sp{flex:1}
|
||||
.sumbar .btn{min-width:150px}
|
||||
.sumbar .why{font-size:13px;color:#B4412F}
|
||||
|
||||
/* ---------- 我的订单(这台浏览器里下过的单) ---------- */
|
||||
.mine{display:flex;flex-direction:column;gap:10px}
|
||||
.mine a.mrow{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:6px 16px;align-items:center;padding:14px 18px;border-radius:var(--r-sm);text-decoration:none;color:inherit}
|
||||
.mine a.mrow:hover{border-color:var(--mc-green-hi)}
|
||||
.mrow .code{font-weight:700;letter-spacing:.05em;font-variant-numeric:tabular-nums}
|
||||
.mrow .what{font-size:13.5px;color:var(--ink-3);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.lookup{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-top:14px}
|
||||
.lookup input{height:44px;padding:0 14px;border-radius:4px;border:2px solid var(--stone-edge,#C9CED8);background:#fff;font:inherit;font-size:15px;min-width:0;flex:1 1 160px;letter-spacing:.04em;text-transform:uppercase}
|
||||
.lookup input:focus{outline:none;border-color:var(--mc-green)}
|
||||
|
||||
/* ---------- 状态 ---------- */
|
||||
.state.unpaid{background:#FFF4D9;color:#8A5A00}
|
||||
.state.waiting,.state.working{background:#E5F3DF;color:#2E6A1D}
|
||||
.state.done{background:#E5F3DF;color:#2E6A1D}
|
||||
.state.closed,.state.void,.state.failed{background:#FBE8E4;color:#A33A2A}
|
||||
|
||||
/* ---------- 收银台 ---------- */
|
||||
.pay .amt{font-size:34px;font-weight:700;font-variant-numeric:tabular-nums;line-height:1.1}
|
||||
.pay .items{display:flex;flex-wrap:wrap;gap:6px}
|
||||
.pay .items .chip{height:26px}
|
||||
.chs{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}
|
||||
@media (max-width:560px){.chs{grid-template-columns:1fr}}
|
||||
.chx{position:relative;display:flex;flex-direction:column;gap:4px;padding:14px 16px;border-radius:var(--r-sm);cursor:pointer;text-align:left;font:inherit;color:inherit;border:2px solid rgba(255,255,255,.95)}
|
||||
.chx b{font-size:16px;display:flex;align-items:center;gap:8px}
|
||||
.chx b i{width:22px;height:22px;border-radius:5px;display:grid;place-items:center;color:#fff;font-style:normal;font-size:12px;font-weight:700}
|
||||
.chx.afd b i{background:#946CE6} .chx.ali b i{background:#1677FF}
|
||||
.chx span{font-size:13px;color:var(--ink-3)}
|
||||
.chx .rec{position:absolute;top:12px;right:12px;font-size:11.5px;font-weight:700;color:#2E6A1D;background:#E5F3DF;padding:1px 8px;border-radius:4px}
|
||||
.chx[aria-pressed=true]{border-color:var(--mc-green)!important;box-shadow:0 0 0 3px rgba(91,170,60,.2)!important}
|
||||
.chx:disabled{cursor:not-allowed;opacity:.55}
|
||||
.chx .why{color:#A33A2A}
|
||||
.qrbox{display:grid;grid-template-columns:184px minmax(0,1fr);gap:20px;align-items:start;padding-top:16px;border-top:1px dashed rgba(140,150,200,.35)}
|
||||
@media (max-width:560px){.qrbox{grid-template-columns:1fr;justify-items:start}}
|
||||
.qr{width:184px;height:184px;padding:10px;border-radius:12px;background:#fff;box-shadow:inset 0 0 0 1px rgba(30,36,64,.08),0 12px 24px -18px rgba(30,36,64,.4)}
|
||||
.qr svg{display:block;width:100%;height:100%}
|
||||
.qrbox h4{margin:0 0 6px;font-size:16px}
|
||||
.qrbox p{margin:0 0 10px;font-size:13.5px;color:var(--ink-3);line-height:1.7}
|
||||
.cd{display:flex;align-items:baseline;gap:8px;margin:4px 0 12px;font-size:13px;color:var(--ink-3)}
|
||||
.cd b{font:700 26px/1 var(--pixel,inherit);color:var(--ink);font-variant-numeric:tabular-nums}
|
||||
.cd.low b{color:#C2410C}
|
||||
.waitline{display:flex;align-items:center;gap:8px;font-size:13.5px;color:var(--ink-2)}
|
||||
.waitline::before{content:"";width:8px;height:8px;border-radius:2px;background:var(--mc-green-hi);animation:blink 1.2s steps(2) infinite}
|
||||
@keyframes blink{50%{opacity:.25}}
|
||||
.paid-hero{display:flex;gap:16px;align-items:center}
|
||||
.paid-hero .ok{flex:none;width:52px;height:52px;border-radius:6px;display:grid;place-items:center;font-size:28px;color:#fff;background:var(--mc-green);box-shadow:inset 0 2px 0 var(--mc-green-hi),inset 0 -4px 0 var(--mc-green-lo)}
|
||||
.paid-hero b{font-size:20px}
|
||||
.paid-hero p{margin:2px 0 0;font-size:14px;color:var(--ink-3)}
|
||||
.pmsg{font-size:13.5px;padding:10px 14px;border-radius:10px;background:rgba(255,255,255,.7);color:var(--ink-2)}
|
||||
.pmsg.bad{background:rgba(224,83,61,.07);color:#A33A2A}
|
||||
.plog{width:100%;border-collapse:collapse;font-size:13px}
|
||||
.plog td{padding:7px 4px;border-top:1px solid var(--line);color:var(--ink-2)}
|
||||
.plog code{font-size:12px}
|
||||
.pass .stub .code{font-size:20px;word-break:break-all}
|
||||
|
||||
#tpl,#pass{scroll-margin-top:76px}
|
||||
.sum-h,.sum-list,.sum-note{display:none}
|
||||
|
||||
/* 平板(761–1023px):模板每行 4 张,两行排齐 */
|
||||
@media (min-width:761px) and (max-width:1023px){#tplGrid.tpl-grid{grid-template-columns:repeat(4,minmax(0,1fr))}}
|
||||
|
||||
/* ================= 电脑(≥1024px):左边表单,右边跟随滚动的「你的订单」 ================= */
|
||||
@media (min-width:1024px){
|
||||
.buy{display:grid;grid-template-columns:minmax(0,1fr) 320px;gap:28px;align-items:start;margin-top:26px}
|
||||
.buy-form>.buy-step:first-child{margin-top:0}
|
||||
#tplGrid.tpl-grid{grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}
|
||||
#tplGrid .tpl .sw{height:64px}
|
||||
.skin{grid-template-columns:120px minmax(0,1fr)}
|
||||
.sumbar{position:sticky;top:92px;bottom:auto;margin-top:0;flex-direction:column;flex-wrap:nowrap;align-items:stretch;gap:12px;padding:20px 20px 18px}
|
||||
.sumbar .sum{gap:10px}
|
||||
.sum-h{display:block;font-size:13px;font-weight:700;letter-spacing:.12em;color:var(--ink-3)}
|
||||
.sum-list{display:flex;flex-direction:column;list-style:none;margin:0;padding:0;font-size:14px}
|
||||
.sum-list li{display:flex;justify-content:space-between;gap:10px;padding:7px 0;border-top:1px solid var(--line)}
|
||||
.sum-list li:first-child{border-top:0}
|
||||
.sum-list li.meta{color:var(--ink-3);font-size:13px}
|
||||
.sum-list li.meta:first-of-type{border-top:1px dashed rgba(140,150,200,.4);margin-top:4px}
|
||||
.sumbar .sum b{font-size:30px;padding-top:10px;border-top:2px solid var(--line)}
|
||||
.sumbar .sum span#sumTxt{display:none}
|
||||
.sumbar .sp{display:none}
|
||||
.sumbar .why{min-height:0}
|
||||
.sumbar .why:empty{display:none}
|
||||
.sumbar .btn{width:100%;min-width:0;height:50px;font-size:15.5px}
|
||||
.sum-note{display:block;margin:0;font-size:12.5px;line-height:1.7;color:var(--ink-3)}
|
||||
}
|
||||
.qrfold{margin-top:14px}
|
||||
.qrfold summary{cursor:pointer;font-size:13.5px;color:var(--ink-2);list-style:none;display:inline-flex;align-items:center;gap:6px}
|
||||
.qrfold summary::-webkit-details-marker{display:none}
|
||||
.qrfold summary::before{content:"▸";font-size:11px;transition:transform .15s}
|
||||
.qrfold[open] summary::before{transform:rotate(90deg)}
|
||||
.qrfold .qr{margin-top:10px}
|
||||
.btn-wide{width:100%}
|
||||
|
||||
/* ================= 手机(≤760px) ================= */
|
||||
@media (max-width:760px){
|
||||
/* 模板:两列网格,全部 7 个一眼看完(不再横向滑) */
|
||||
#tplGrid.tpl-grid{grid-auto-flow:row;grid-template-columns:repeat(2,minmax(0,1fr));grid-auto-columns:auto;overflow:visible;margin:0;padding:0;gap:10px;scroll-snap-type:none}
|
||||
#tplGrid .tpl{padding:10px;gap:3px}
|
||||
#tplGrid .tpl .sw{height:46px}
|
||||
#tplGrid .tpl b{font-size:14px;line-height:1.35}
|
||||
#tplGrid .tpl span{font-size:12px;line-height:1.5}
|
||||
#tplGrid .tpl .pick{top:15px;right:15px;width:22px;height:22px;font-size:13px}
|
||||
/* 分辨率:2×2 方格,档位和时间各占一行 */
|
||||
#resSeg.seg{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:6px;width:100%;padding:6px}
|
||||
#resSeg.seg button{height:auto;min-height:52px;padding:6px 8px 8px;line-height:1.3;display:flex;flex-direction:column;align-items:center;justify-content:center}
|
||||
#resSeg.seg button em{display:block;margin:2px 0 0;font-size:12px}
|
||||
/* 皮肤:预览缩小放左边,质检结果在右边 */
|
||||
.skin{grid-template-columns:96px minmax(0,1fr);gap:12px;padding:12px}
|
||||
.skin-drop{font-size:11.5px;border-radius:10px}
|
||||
.lamp{font-size:12.5px;padding:7px 9px;gap:7px}
|
||||
.lamp::before{margin-top:6px}
|
||||
/* 吸底条:一行,金额在左、按钮在右;挡不住的原因写进说明行 */
|
||||
.sumbar{flex-wrap:nowrap;gap:10px;padding:10px 12px;margin-top:20px;bottom:calc(86px + env(safe-area-inset-bottom,0px))}
|
||||
.sumbar .sum{flex:1;min-width:0}
|
||||
.sumbar .sum b{font-size:20px;line-height:1.2}
|
||||
.sumbar .sum span{font-size:12px}
|
||||
.sumbar .sp,.sumbar .why{display:none}
|
||||
.sumbar .sum span.blocked{color:#B4412F}
|
||||
.sumbar .btn{min-width:0;flex:none;height:44px;padding:0 16px 3px}
|
||||
/* 查单:上下排,按钮整行 */
|
||||
.lookup input{flex-basis:100%}
|
||||
.lookup .btn{width:100%}
|
||||
.mine a.mrow{grid-template-columns:minmax(0,1fr) auto;padding:12px 14px}
|
||||
.mine a.mrow .what{grid-column:1/-1;grid-row:2}
|
||||
/* 收银台 */
|
||||
.pay .amt{font-size:30px}
|
||||
.qrbox{grid-template-columns:1fr;gap:6px}
|
||||
.chx{padding:12px 14px}
|
||||
.chx .rec{top:10px;right:10px}
|
||||
.pass .main{padding:20px 18px}
|
||||
.pass .stub{padding:20px 18px}
|
||||
}
|
||||
|
||||
/* ---------- 演示控制台(只在预览站) ---------- */
|
||||
.demo-fab{margin-left:4px;height:24px;padding:0 9px;border-radius:4px;border:1.5px solid #8A5A00;background:#FFF4D9;color:#8A5A00;font:700 12px/1 inherit;cursor:pointer;vertical-align:middle}
|
||||
.demo-fab[aria-expanded=true]{background:#8A5A00;color:#FFF4D9}
|
||||
.demo{position:fixed;right:16px;top:calc(46px + env(safe-area-inset-top,0px));z-index:31;width:min(380px,calc(100vw - 32px));max-height:min(70vh,640px);overflow:auto;padding:16px;border-radius:var(--r);background:rgba(255,255,255,.97);box-shadow:0 30px 60px -30px rgba(30,36,64,.55),inset 0 0 0 1px rgba(30,36,64,.08)}
|
||||
.demo h4{margin:0 0 2px;font-size:15px}
|
||||
.demo .mut{font-size:12.5px;color:var(--ink-3)}
|
||||
.demo .grp{display:flex;flex-wrap:wrap;gap:6px;margin:8px 0 12px}
|
||||
.demo button.d{height:32px;padding:0 10px;border-radius:4px;border:2px solid var(--stone-edge,#C9CED8);background:#fff;font:600 12.5px/1 inherit;color:var(--ink);cursor:pointer}
|
||||
.demo button.d:hover{border-color:var(--mc-green)}
|
||||
.demo .clock{font:700 15px/1.4 ui-monospace,Menlo,Consolas,monospace}
|
||||
.demo .out{font-size:12.5px;padding:8px 10px;border-radius:8px;background:#F4F6FB;color:var(--ink-2);margin-bottom:10px}
|
||||
.demo ul{list-style:none;margin:0;padding:0;font-size:12.5px}
|
||||
.demo li{display:grid;grid-template-columns:56px 1fr;gap:6px;padding:5px 0;border-top:1px solid var(--line)}
|
||||
.demo li time{font-family:ui-monospace,Menlo,Consolas,monospace;color:var(--ink-3);font-size:11.5px}
|
||||
.demo li .c{font-size:11px;font-weight:700;margin-right:4px}
|
||||
.demo li .c.afdian{color:#7A55D8} .demo li .c.alipay{color:#1677FF}
|
||||
|
||||
@media (prefers-reduced-motion:reduce){.waitline::before{animation:none}}
|
||||
@@ -0,0 +1,118 @@
|
||||
/* 自助渲染 · 下单与收银台共用(预览站)
|
||||
- 接口:/svc/api/*(预览机上的收款服务,全模拟渠道)
|
||||
- 本机订单:照独角数卡「浏览器缓存查单」—— 这台浏览器下过的单记在 localStorage,换设备用「订单号 + 取件码」查
|
||||
- 演示控制台:快进时钟 / 立即跑定时任务 / 模拟风控等,只在预览站有 */
|
||||
(function () {
|
||||
'use strict';
|
||||
var API = 'svc/api';
|
||||
var KEY = 'jz_orders_v1';
|
||||
var TPLS = [
|
||||
{k: 'stand', n: '站立正反', s: '正面站着,背景干净', c: '#8a8f98'},
|
||||
{k: 'standb', n: '站立正反(虚化)', s: '同上,背景虚化', c: '#6f7680'},
|
||||
{k: 'wheat', n: '麦田萤火', s: '麦田、暖光、萤火虫', c: '#a8863a'},
|
||||
{k: 'beach', n: '海边自拍', s: '海边,天光', c: '#4a7fa5'},
|
||||
{k: 'boom', n: '不看爆炸', s: '身后爆炸,头也不回', c: '#a2563f'},
|
||||
{k: 'sakura', n: '飞跃樱花林', s: '樱花林,动态', c: '#b07a92'},
|
||||
{k: 'airship', n: '空艇巡游', s: '坐飞空艇巡航', c: '#5e7f8f'}
|
||||
];
|
||||
var STATE = {unpaid: '待付款', waiting: '已付款 · 排队中', working: '渲染中', done: '已完成', failed: '渲染失败',
|
||||
closed: '已关闭', void: '已注销'};
|
||||
|
||||
function api(method, path, body) {
|
||||
return fetch(API + path, {method: method, cache: 'no-store',
|
||||
headers: body ? {'Content-Type': 'application/json'} : {}, body: body ? JSON.stringify(body) : undefined})
|
||||
.then(function (r) { return r.json().catch(function () { return {ok: false, error: '服务器没回应'}; }); })
|
||||
.catch(function () { return {ok: false, error: '网络不通,稍后再试'}; });
|
||||
}
|
||||
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
|
||||
return {'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[c]; }); }
|
||||
function left(sec) {
|
||||
sec = Math.max(0, Math.round(sec));
|
||||
var h = Math.floor(sec / 3600), m = Math.floor(sec % 3600 / 60), s = sec % 60;
|
||||
return h ? (h + ' 小时 ' + m + ' 分') : ((m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s);
|
||||
}
|
||||
function hm(ts) { return new Date(ts * 1000).toLocaleTimeString('zh-CN', {hour12: false, timeZone: 'Asia/Shanghai'}); }
|
||||
function full(ts) { return new Date(ts * 1000).toLocaleString('zh-CN', {hour12: false, timeZone: 'Asia/Shanghai'}); }
|
||||
function qrSvg(text) {
|
||||
try { var q = qrcode(0, 'M'); q.addData(text); q.make(); return q.createSvgTag({cellSize: 4, margin: 0, scalable: true}); }
|
||||
catch (e) { return ''; }
|
||||
}
|
||||
function orders() { try { return JSON.parse(localStorage.getItem(KEY) || '[]') || []; } catch (e) { return []; } }
|
||||
function saveOrder(o) {
|
||||
try {
|
||||
var l = orders().filter(function (x) { return x.oid !== o.oid; });
|
||||
l.unshift(o); localStorage.setItem(KEY, JSON.stringify(l.slice(0, 30)));
|
||||
} catch (e) {}
|
||||
}
|
||||
function tokenOf(oid) { var o = orders().filter(function (x) { return x.oid === oid; })[0]; return o ? o.t : ''; }
|
||||
|
||||
/* ---------------- 演示控制台 ---------------- */
|
||||
var KIND = {order_created: '下单', payment_created: '建支付单', notify: '收到回调', settle: '到账处理', close: '关单',
|
||||
payment_expired: '支付单过期', order_closed: '订单超时关闭', buyer_check: '买家点「付好了没反应」', todo: '进待办',
|
||||
mock_paid: '(模拟)买家付款', card_purchase: '按买卡密处理', breaker_open: '支付宝熔断', create_failed: '生成付款失败',
|
||||
query_failed: '查单失败', todo_resolved: '待办已处理'};
|
||||
var RES = {activated: '激活订单', reopened: '恢复并激活', dup_trade: '重复,忽略', short: '金额不足', duplicate: '重复付款',
|
||||
late: '迟到付款', ok: '验证通过', webhook_soon: '稍后推送回调', drop_webhook: '回调丢失(模拟)',
|
||||
notify_soon: '稍后推送通知', drop_notify: '通知丢失(模拟)', '验签失败': '验签失败,丢弃'};
|
||||
var CH = {afdian: '爱发电', alipay: '支付宝', 'mock-afdian': '爱发电', 'mock-alipay': '支付宝'};
|
||||
var demo = {view: null, onChange: null};
|
||||
|
||||
function demoUI() {
|
||||
var fab = document.createElement('button');
|
||||
fab.className = 'demo-fab'; fab.type = 'button'; fab.textContent = '演示控制台';
|
||||
fab.setAttribute('aria-expanded', 'false');
|
||||
var box = document.createElement('div'); box.className = 'demo'; box.hidden = true;
|
||||
box.innerHTML = '<h4>演示控制台</h4><div class="mut">只在预览站有:付款全部走模拟的爱发电 / 支付宝,不会扣钱。</div>'
|
||||
+ '<div class="mut" style="margin-top:10px">演示时钟(快进用来看超时关单)</div><div class="clock" id="dClock">—</div>'
|
||||
+ '<div class="grp"><button class="d" data-ff="900">快进 15 分钟</button><button class="d" data-ff="7200">快进 2 小时</button>'
|
||||
+ '<button class="d" data-ff="86400">快进 1 天</button><button class="d" data-k="jobs">立即跑一轮定时任务</button></div>'
|
||||
+ '<div class="mut">场景</div><div class="grp">'
|
||||
+ '<button class="d" data-k="risk_on">支付宝被风控</button><button class="d" data-k="risk_off">恢复支付宝</button>'
|
||||
+ '<button class="d" data-k="direct">有人直接在爱发电店铺下单</button><button class="d" data-k="forge">伪造一条爱发电回调</button>'
|
||||
+ '<a class="d" href="cms/pay.html" style="display:inline-flex;align-items:center;height:32px;padding:0 10px;border-radius:4px;border:2px solid #C9CED8;font:600 12.5px/1 inherit;color:inherit;text-decoration:none">打开收款后台</a></div>'
|
||||
+ '<div class="out" id="dOut" hidden></div><div class="mut">这张单的流水(新的在上)</div><ul id="dEv"><li><span></span><span class="mut">还没有</span></li></ul>';
|
||||
document.body.appendChild(box);
|
||||
var rib = document.querySelector('.ribbon'); /* 放进顶部「设计预览版」横幅,不压页面内容 */
|
||||
if (rib) rib.appendChild(fab); else { fab.style.cssText = 'position:fixed;right:16px;top:16px;z-index:30'; document.body.appendChild(fab); }
|
||||
fab.onclick = function () { box.hidden = !box.hidden; fab.setAttribute('aria-expanded', String(!box.hidden)); };
|
||||
function out(t) { var o = document.getElementById('dOut'); o.hidden = false; o.textContent = t; }
|
||||
function run(body, msg) {
|
||||
out('执行中…');
|
||||
return api('POST', '/demo', body).then(function (j) {
|
||||
var jobs = j.jobs ? ' 定时任务:' + Object.keys(j.jobs).map(function (k) { return k + ' ' + j.jobs[k]; }).join(',') : '';
|
||||
out((j.ok ? (msg || '完成。') : ('没成功:' + (j.error || ''))) + jobs);
|
||||
if (demo.onChange) demo.onChange();
|
||||
});
|
||||
}
|
||||
[].forEach.call(box.querySelectorAll('[data-ff]'), function (b) {
|
||||
b.onclick = function () { run({kind: 'clock', seconds: +b.dataset.ff}, '时钟已快进,并跑了一轮定时任务。'); };
|
||||
});
|
||||
box.querySelector('[data-k=jobs]').onclick = function () { run({kind: 'jobs'}, '已跑一轮。'); };
|
||||
box.querySelector('[data-k=risk_on]').onclick = function () {
|
||||
run({kind: 'alipay_risk', on: true}, '支付宝网关会返回风控错误码:现在点「支付宝扫码」会触发熔断,这个选项随即变灰。'); };
|
||||
box.querySelector('[data-k=risk_off]').onclick = function () {
|
||||
api('POST', '/demo', {kind: 'alipay_risk', on: false}).then(function () { run({kind: 'breaker_reset'}, '风控已解除,支付宝恢复可用。'); }); };
|
||||
box.querySelector('[data-k=direct]').onclick = function () {
|
||||
run({kind: 'afdian_direct', amount: 12}, '模拟了一笔没带订单号的爱发电成交:系统按「买卡密」处理,不去猜是哪张单;后台可以按爱发电订单号认领。'); };
|
||||
box.querySelector('[data-k=forge]').onclick = function () {
|
||||
var p = demo.view && demo.view.payments.filter(function (x) { return x.channel === 'afdian' && x.state === 'created'; })[0];
|
||||
if (!p) { out('先在收银台选「爱发电」生成一张支付单,再伪造它的回调。'); return; }
|
||||
run({kind: 'afdian_forge', pay_id: p.pay_id}, '发出了一条签名不对、金额 ¥999 的回调。看流水:验签失败,被丢弃。');
|
||||
};
|
||||
}
|
||||
function demoUpdate(v) {
|
||||
demo.view = v;
|
||||
var c = document.getElementById('dClock'); if (c && v) c.textContent = full(v.now);
|
||||
var ul = document.getElementById('dEv'); if (!ul || !v) return;
|
||||
ul.innerHTML = (v.events || []).map(function (e) {
|
||||
var r = RES.hasOwnProperty(e.result) ? RES[e.result] : e.result;
|
||||
return '<li><time>' + hm(e.ts) + '</time><span>' + (e.channel ? '<span class="c ' + esc(String(e.channel).replace('mock-', '')) + '">'
|
||||
+ esc(CH[e.channel] || e.channel) + '</span>' : '') + esc(KIND[e.kind] || e.kind)
|
||||
+ (r && r !== 'created' && r !== 'unpaid' && r !== 'closed' ? ' · <span class="mut">' + esc(r) + '</span>' : '') + '</span></li>';
|
||||
}).join('') || '<li><span></span><span class="mut">还没有</span></li>';
|
||||
}
|
||||
|
||||
window.JZPay = {api: api, esc: esc, left: left, full: full, qrSvg: qrSvg, orders: orders, saveOrder: saveOrder,
|
||||
tokenOf: tokenOf, TPLS: TPLS, STATE: STATE, demo: demo, demoUpdate: demoUpdate};
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', demoUI); else demoUI();
|
||||
})();
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,129 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<meta name="robots" content="noindex,nofollow">
|
||||
<title>收款后台 · 金钻客栈(设计预览)</title>
|
||||
<link rel="stylesheet" href="../assets/site.css?v=33">
|
||||
<link rel="stylesheet" href="../assets/pay.css?v=2">
|
||||
<style>
|
||||
.adm{padding:18px 20px;border-radius:var(--r);margin-top:16px}
|
||||
.adm h2{margin:0 0 4px;font-size:18px}
|
||||
.adm>p{margin:0 0 12px;font-size:13.5px;color:var(--ink-3)}
|
||||
.tw{overflow-x:auto}
|
||||
.tb{border-collapse:collapse;width:100%;font-size:13px;min-width:640px}
|
||||
.tb th,.tb td{text-align:left;padding:8px 8px;border-top:1px solid var(--line);vertical-align:top}
|
||||
.tb th{color:var(--ink-3);font-weight:700;border-top:0;white-space:nowrap}
|
||||
.tb td{font-variant-numeric:tabular-nums}
|
||||
.tb code{font-size:12px;word-break:break-all}
|
||||
.tb tr.done td{opacity:.5}
|
||||
.tb .btn{height:30px;padding:0 10px 2px;font-size:12.5px}
|
||||
.kd{display:inline-block;font-size:12px;font-weight:700;padding:1px 8px;border-radius:4px;white-space:nowrap}
|
||||
.kd.short,.kd.late{background:#FFF4D9;color:#8A5A00}.kd.duplicate,.kd.unknown{background:#FBE8E4;color:#A33A2A}
|
||||
.st{font-size:12px;font-weight:700;padding:1px 8px;border-radius:4px;background:#EEF1F8;white-space:nowrap}
|
||||
.st.paid,.st.waiting{background:#E5F3DF;color:#2E6A1D}.st.closed,.st.mismatch,.st.void{background:#FBE8E4;color:#A33A2A}.st.unpaid,.st.created{background:#FFF4D9;color:#8A5A00}
|
||||
.cha{font-weight:700}.cha.afdian{color:#7A55D8}.cha.alipay{color:#1677FF}
|
||||
.two{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:16px}
|
||||
.two .adm{margin-top:16px}
|
||||
.back-links{display:none;gap:8px;margin-top:8px}
|
||||
@media (max-width:760px){
|
||||
.back-links{display:flex}
|
||||
.adm{padding:14px}
|
||||
/* 表格 → 一行一张卡片:表头藏起来,单元格顺着排 */
|
||||
.tb{min-width:0}
|
||||
.tb tr:first-child{display:none}
|
||||
.tb tr{display:flex;flex-wrap:wrap;gap:4px 10px;padding:10px 0;border-top:1px solid var(--line)}
|
||||
.tb td{border:0;padding:0;font-size:12.5px}
|
||||
.tb td:empty{display:none}
|
||||
.tb .btn{height:34px}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="orbs" aria-hidden="true"><i class="o1"></i><i class="o2"></i><i class="o3"></i></div>
|
||||
<div class="ribbon"><span><b>设计预览版</b>,收款全部走模拟渠道</span></div>
|
||||
<header class="top"><div class="wrap top-in">
|
||||
<a class="brand" href="../index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a>
|
||||
<nav class="nav" aria-label="后台"><a href="index.html">内容管理</a><a href="pay.html" aria-current="page">收款</a></nav>
|
||||
</div></header>
|
||||
<main class="wrap" style="padding-bottom:60px">
|
||||
<div class="room-head svc-head"><div class="svc-ic" aria-hidden="true"><i class="gem-img"></i></div>
|
||||
<div><h1>收款后台</h1><p>到账、关单、对账都是自动的。这里只处理系统判断不了的情况。</p><p class="svc-line" id="clock">演示时钟 —</p><div class="back-links"><a class="btn btn-crystal btn-sm" href="index.html">内容管理</a><a class="btn btn-crystal btn-sm" href="../order.html">回自助渲染</a></div></div></div>
|
||||
|
||||
<section class="adm crystal" id="login">
|
||||
<h2>后台口令</h2><p>预览机 <code>/var/lib/jz-pay-proto/admin_token</code> 里的那串。</p>
|
||||
<form class="lookup" id="fTok" style="margin-top:0"><input id="tok" type="password" placeholder="后台口令" autocomplete="off" style="text-transform:none" aria-label="后台口令"><button class="btn btn-prism" type="submit">进入</button></form>
|
||||
<div class="pmsg bad" id="loginMsg" hidden style="margin-top:10px"></div>
|
||||
</section>
|
||||
|
||||
<div id="main" hidden>
|
||||
<section class="adm crystal">
|
||||
<h2>支付待办</h2><p>金额不足、重复付款、迟到太久的付款、对不上的到账。</p>
|
||||
<div class="tw"><table class="tb" id="todo"></table></div>
|
||||
<div class="pmsg" id="todoMsg" hidden style="margin-top:10px"></div>
|
||||
</section>
|
||||
<div class="two">
|
||||
<section class="adm crystal">
|
||||
<h2>按爱发电订单号认领</h2><p>买家没走专链、或者回调里没带订单号时,把那笔成交指定到某张订单。会先向爱发电反查确认已付款。</p>
|
||||
<form class="lookup" id="fClaim" style="margin-top:0"><input id="cOid" placeholder="订单号" maxlength="8" aria-label="订单号"><input id="cTn" placeholder="爱发电订单号" style="text-transform:none" aria-label="爱发电订单号"><button class="btn btn-prism" type="submit">认领</button></form>
|
||||
<div class="pmsg" id="claimMsg" hidden style="margin-top:10px"></div>
|
||||
</section>
|
||||
<section class="adm crystal"><h2>渠道</h2><p>当面付熔断后会自动隐藏,恢复用付款页左下角的演示控制台。</p><div id="chs"></div></section>
|
||||
</div>
|
||||
<section class="adm crystal"><h2>订单</h2><div class="tw"><table class="tb" id="orders"></table></div></section>
|
||||
<section class="adm crystal"><h2>支付单</h2><div class="tw"><table class="tb" id="pays"></table></div></section>
|
||||
<section class="adm crystal"><h2>流水</h2><p>最近 80 条。</p><div class="tw"><table class="tb" id="evs"></table></div></section>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
(function(){
|
||||
'use strict';
|
||||
var API='../svc/api', $=function(i){return document.getElementById(i);}, TOK='';
|
||||
try{ TOK=localStorage.getItem('jz_pay_admin')||''; }catch(e){}
|
||||
var KIND={short:'金额不足',duplicate:'重复付款',late:'迟到付款',unknown:'对不上'};
|
||||
var ACTS={short:[['confirm','确认补齐'],['refund','退款'],['ignore','忽略']],duplicate:[['refund','退款'],['ignore','忽略']],
|
||||
late:[['activate','手动激活'],['refund','退款'],['ignore','忽略']],unknown:[['ignore','忽略']]};
|
||||
var ST={unpaid:'待付款',waiting:'已付款',closed:'已关闭',void:'已注销',created:'等待付款',paid:'已到账',mismatch:'金额不足',refunded:'已退款'};
|
||||
function esc(s){return String(s==null?'':s).replace(/[&<>"']/g,function(c){return {'&':'&','<':'<','>':'>','"':'"',"'":'''}[c];});}
|
||||
function t(ts){return ts?new Date(ts*1000).toLocaleString('zh-CN',{hour12:false,timeZone:'Asia/Shanghai'}):'—';}
|
||||
function api(m,p,b){return fetch(API+p,{method:m,cache:'no-store',headers:Object.assign({'X-Admin-Token':TOK},b?{'Content-Type':'application/json'}:{}),
|
||||
body:b?JSON.stringify(b):undefined}).then(function(r){return r.json();}).catch(function(){return {ok:false,error:'网络不通'};});}
|
||||
function st(s){return '<span class="st '+esc(s)+'">'+esc(ST[s]||s)+'</span>';}
|
||||
function ch(c){return '<span class="cha '+esc(c)+'">'+esc(c==='afdian'?'爱发电':c==='alipay'?'支付宝':c)+'</span>';}
|
||||
function note(id,txt){var m=$(id);m.hidden=false;m.textContent=txt;}
|
||||
function load(){
|
||||
return api('GET','/admin/overview').then(function(j){
|
||||
if(!j.ok){ $('main').hidden=true; $('login').hidden=false; if(TOK) note('loginMsg',j.error||'口令不对'); return; }
|
||||
$('login').hidden=true; $('main').hidden=false; $('clock').textContent='演示时钟 '+t(j.now);
|
||||
$('todo').innerHTML='<tr><th>时间</th><th>类型</th><th>订单 / 支付单</th><th>渠道流水</th><th>应付 / 实付</th><th>说明</th><th>处理</th></tr>'
|
||||
+(j.todo.map(function(x){
|
||||
var acts=x.state==='done'?esc(x.resolution):(ACTS[x.kind]||[['ignore','忽略']]).map(function(a){
|
||||
return '<button class="btn '+(a[0]==='ignore'?'btn-crystal':'btn-prism')+'" data-id="'+x.id+'" data-a="'+a[0]+'">'+a[1]+'</button>';}).join(' ');
|
||||
return '<tr class="'+(x.state==='done'?'done':'')+'"><td>'+t(x.ts)+'</td><td><span class="kd '+esc(x.kind)+'">'+esc(KIND[x.kind]||x.kind)+'</span></td><td><code>'+esc(x.oid)
|
||||
+'</code><br><code>'+esc(x.pay_id)+'</code></td><td>'+ch(x.channel)+'<br><code>'+esc(x.trade_no)+'</code></td><td>¥'+esc(x.amount_due)+' / ¥'+esc(x.amount_paid)
|
||||
+'</td><td>'+esc(x.detail)+'</td><td>'+acts+'</td></tr>';}).join('')||'<tr><td colspan="7" style="color:var(--ink-3)">没有待办 —— 全都自动处理了</td></tr>');
|
||||
[].forEach.call($('todo').querySelectorAll('button[data-id]'),function(b){ b.onclick=function(){
|
||||
b.disabled=true; api('POST','/admin/todo',{id:+b.dataset.id,action:b.dataset.a}).then(function(r){ note('todoMsg',r.ok?r.msg:('没成功:'+r.error)); load(); }); }; });
|
||||
var br=j.breaker, open=br.open_until>j.now;
|
||||
$('chs').innerHTML=j.channels.map(function(c){ return '<div style="padding:8px 0;border-top:1px solid var(--line)">'+ch(c.name)+' · '+(c.mock?'模拟网关':'真实渠道')
|
||||
+(c.name==='alipay'?' · '+(open?'<span class="st closed">熔断中,至 '+t(br.open_until)+'</span>':'<span class="st paid">正常</span>')
|
||||
+(br.reason?'<div style="font-size:12.5px;color:var(--ink-3)">最近一次问题:'+esc(br.reason)+'</div>':''):' · <span class="st paid">正常</span>')+'</div>'; }).join('');
|
||||
$('orders').innerHTML='<tr><th>订单</th><th>状态</th><th>金额</th><th>下单</th><th>到账</th><th>关闭</th><th>买家点过「没反应」</th></tr>'
|
||||
+j.orders.map(function(o){ return '<tr><td><code>'+esc(o.oid)+'</code></td><td>'+st(o.state)+'</td><td>¥'+o.amount+'</td><td>'+t(o.created_at)+'</td><td>'+t(o.paid_at)
|
||||
+'</td><td>'+t(o.closed_at)+'</td><td>'+t(o.buyer_claim_at)+'</td></tr>'; }).join('');
|
||||
$('pays').innerHTML='<tr><th>支付单</th><th>渠道</th><th>状态</th><th>应付 / 实付</th><th>渠道流水</th><th>创建</th><th>过期</th><th>备注</th></tr>'
|
||||
+j.payments.map(function(p){ return '<tr><td><code>'+esc(p.pay_id)+'</code></td><td>'+ch(p.channel)+'</td><td>'+st(p.state)+'</td><td>¥'+p.amount_due+' / '
|
||||
+(p.amount_paid!=null?'¥'+p.amount_paid:'—')+'</td><td><code>'+esc(p.trade_no||'')+'</code></td><td>'+t(p.created_at)+'</td><td>'+t(p.expire_at)+'</td><td>'+esc(p.note)+'</td></tr>'; }).join('');
|
||||
$('evs').innerHTML='<tr><th>时间</th><th>渠道</th><th>事件</th><th>支付单 / 订单</th><th>结果</th></tr>'
|
||||
+j.events.slice(0,matchMedia('(max-width:760px)').matches?30:80).map(function(e){ return '<tr><td>'+t(e.ts)+'</td><td>'+ch(e.channel)+'</td><td>'+esc(e.kind)+'</td><td><code>'+esc(e.pay_id||e.oid)+'</code></td><td>'+esc(e.result)+'</td></tr>'; }).join('');
|
||||
});
|
||||
}
|
||||
$('fTok').onsubmit=function(e){ e.preventDefault(); TOK=$('tok').value.trim(); try{ localStorage.setItem('jz_pay_admin',TOK); }catch(e2){} load(); };
|
||||
$('fClaim').onsubmit=function(e){ e.preventDefault(); api('POST','/admin/claim',{oid:$('cOid').value.trim().toUpperCase(),trade_no:$('cTn').value.trim()}).then(function(r){
|
||||
note('claimMsg',r.ok?r.msg:('没成功:'+r.error)); load(); }); };
|
||||
load(); setInterval(function(){ if(!document.hidden&&TOK) load(); },5000);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,147 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<meta name="robots" content="noindex,nofollow">
|
||||
<title>自助渲染 · 金钻客栈(设计预览)</title>
|
||||
<meta name="theme-color" content="#FAFBFE">
|
||||
<link rel="preload" href="assets/OPPOSans-B.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="stylesheet" href="assets/site.css?v=33">
|
||||
<link rel="stylesheet" href="assets/pay.css?v=2">
|
||||
</head>
|
||||
<body>
|
||||
<div class="orbs" aria-hidden="true"><i class="o1"></i><i class="o2"></i><i class="o3"></i><i class="o4"></i><i class="o5"></i></div>
|
||||
<div class="ribbon"><span><b>设计预览版</b>,方括号里的是占位内容</span></div>
|
||||
<header class="top"><div class="wrap top-in"><a class="brand" href="index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a><nav class="nav" aria-label="导航"><a href="index.html">首页</a><a href="gallery.html">画展</a><a href="tools.html">工具与开源</a><a href="universe.html">金钻宇宙</a><a href="links.html">平台入口</a><a href="about.html">关于</a></nav><div class="desk-btn"><a class="btn-pill" href="order.html" aria-current="page"><span class="ic" aria-hidden="true"></span>自助渲染<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></svg></a></div><a class="cms-ent" href="cms/" aria-label="内容管理" title="内容管理"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg></a></div></header>
|
||||
<main class="wrap">
|
||||
<div class="room-head svc-head"><div class="svc-ic" aria-hidden="true"><i class="gem-img"></i></div><div><h1>自助模板渲染</h1><p>传一张皮肤,选个模板,等一会儿就能拿到渲染图。</p><p class="svc-line">渲染机在线 · 每张 6 元起</p></div></div>
|
||||
<section aria-labelledby="go-h"><div class="sec-h"><div><h2 id="go-h">怎么下单?</h2></div></div><div class="paths"><a class="path crystal" href="#tpl"><span class="pi"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="9" cy="20" r="1.5"/><circle cx="18" cy="20" r="1.5"/><path d="M3 4h2l2.4 11.2a2 2 0 0 0 2 1.6h7.7a2 2 0 0 0 2-1.5L21 8H6"/></svg></span><h3>网页下单</h3><p style="margin:0;font-size:14.5px;color:var(--ink-2);line-height:1.75">选好模板,在收银台用爱发电或支付宝扫码付款,到账自动开始渲染。</p><div class="hint"><span></span><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></svg></div></a><a class="path code crystal" href="#tpl"><span class="pi"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="15" r="4"/><path d="m10.85 12.15 7.65-7.65"/><path d="m15 6 3 3"/><path d="m17.5 3.5 3 3"/></svg></span><h3>用卡密</h3><p style="margin:0;font-size:14.5px;color:var(--ink-2);line-height:1.75">在闲鱼、B站工坊或爱发电买了卡密?填进来就行,模板会自动选好。</p><div class="hint"><span></span><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></svg></div></a></div><div class="pickup"><span>下过单了?</span><span class="sp"></span><a class="btn btn-crystal btn-sm" href="#pass">取图</a><a class="btn btn-crystal btn-sm" href="#pass">我的订单</a></div></section>
|
||||
<section class="sec" id="tpl" aria-labelledby="tpl-h">
|
||||
<div class="sec-h"><div><h2 id="tpl-h">网页下单</h2><p>每个模板出两张:一张压缩过的,一张无压缩 16bit 的。一张 ¥6。</p></div></div>
|
||||
<div class="buy"><div class="buy-form">
|
||||
<div class="buy-step"><h3>选模板</h3><p>可以多选,选几个出几张。</p><div class="tpl-grid" id="tplGrid"></div></div>
|
||||
<div class="buy-step"><h3>分辨率</h3><p>默认 1000px 就是网易我的世界头图的标准尺寸,出图最快。</p>
|
||||
<div class="seg crystal" id="resSeg" role="group" aria-label="分辨率">
|
||||
<button type="button" data-r="1000" aria-pressed="true">1000px<em>约 40 秒</em></button><button type="button" data-r="1024" aria-pressed="false">1024px<em>约 45 秒</em></button><button type="button" data-r="2048" aria-pressed="false">2048px<em>约 2.5 分钟</em></button><button type="button" data-r="4096" aria-pressed="false">4096px<em>约 10 分钟</em></button>
|
||||
</div></div>
|
||||
<div class="buy-step"><h3>皮肤</h3><p>.png 文件,64×64 的标准皮肤最稳。质检在你自己的浏览器里完成。</p>
|
||||
<div class="skin crystal">
|
||||
<label class="skin-drop" id="skinDrop"><span id="skinPh">点这里选皮肤<br>或把 .png 拖进来</span><canvas id="skinCv" width="64" height="64" hidden></canvas><input type="file" id="skinFile" accept="image/png" aria-label="选择皮肤文件"></label>
|
||||
<div class="skin-rep" id="skinRep"><div class="lamp warn">还没选皮肤</div></div>
|
||||
</div></div>
|
||||
</div>
|
||||
<aside class="sumbar crystal" aria-label="你的订单"><div class="sum"><span class="sum-h">你的订单</span><ul class="sum-list" id="sumList"></ul><b id="sumAmt">¥0</b><span id="sumTxt">还没选模板</span></div><span class="sp"></span><span class="why" id="sumWhy"></span><button type="button" class="btn btn-prism" id="btnBuy" disabled>去付款</button><p class="sum-note">付款方式:爱发电或支付宝扫码。到账后自动开始渲染,不用再操作。</p></aside>
|
||||
</div>
|
||||
</section>
|
||||
<section class="sec" id="pass" aria-labelledby="pass-h">
|
||||
<div class="sec-h"><div><h2 id="pass-h">我的订单</h2><p>这台浏览器下过的单都在这里。换了设备,用订单号和取件码查。</p></div></div>
|
||||
<div class="mine" id="mine"></div>
|
||||
<form class="lookup" id="lookup"><input id="lkOid" placeholder="订单号,如 YSAB12CD" maxlength="8" autocomplete="off" aria-label="订单号"><input id="lkTok" placeholder="取件码" maxlength="12" autocomplete="off" aria-label="取件码"><button class="btn btn-crystal" type="submit">查订单</button></form>
|
||||
<div class="pmsg bad" id="lkMsg" hidden style="margin-top:10px"></div>
|
||||
</section>
|
||||
<p class="note" style="margin-top:28px;line-height:1.9">非官方 Minecraft 产品,与 Mojang 无关<br>有问题来 QQ 群找金钻:123456789</p>
|
||||
</main>
|
||||
<nav class="tabbar" aria-label="导航"><a href="index.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/><path d="M10 21v-6h4v6"/></svg><span>首页</span></a><a href="gallery.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/></svg><span>画展</span></a><a class="mid" href="order.html" aria-current="page"><i aria-hidden="true"></i><span>渲染</span></a><a href="universe.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="5"/><path d="M4.2 15.6c-1.6 2.5 4.2 2.4 9.6-.2s9-6.6 7.5-8.6c-.8-1-2.9-.9-5.4 0"/></svg><span>宇宙</span></a><button type="button" data-sheet="more" aria-expanded="false" aria-controls="more"><i class="ic-a"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3.5" y="3.5" width="7" height="7" rx="2"/><rect x="13.5" y="3.5" width="7" height="7" rx="2"/><rect x="3.5" y="13.5" width="7" height="7" rx="2"/><rect x="13.5" y="13.5" width="7" height="7" rx="2"/></svg></i><i class="ic-b"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="M6 6l12 12"/></svg></i><span class="lb-a">更多</span><span class="lb-b">收起</span></button></nav>
|
||||
<div class="sheet" id="more" hidden><div class="panel"><nav class="more-grid" aria-label="更多"><a href="tools.html" style="--zc:#4F86E8;--zc2:#2E5BD8"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg></i><span>工具与开源</span></a><a href="links.html" style="--zc:#22B573;--zc2:#3C8527"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg></i><span>平台入口</span></a><a href="about.html" style="--zc:#E0533D;--zc2:#E8913A"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg></i><span>关于</span></a></nav><p class="more-qq">QQ 群:屑钻小窝 123456789</p></div></div>
|
||||
<footer class="foot-site"><div class="wrap foot-in"><a class="brand" href="index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a><span>© 2026 example.com</span><span>QQ 群:屑钻小窝 123456789</span><span class="sp"></span><span>备案号(已移除)</span></div></footer>
|
||||
<script src="assets/pay.js?v=2"></script>
|
||||
<script>
|
||||
(function(){
|
||||
'use strict';
|
||||
var P=window.JZPay, $=function(i){return document.getElementById(i);};
|
||||
var S={tpls:[], res:1000, skin:null};
|
||||
/* 模板 */
|
||||
var g=$('tplGrid');
|
||||
P.TPLS.forEach(function(t){
|
||||
var b=document.createElement('button'); b.type='button'; b.className='tpl crystal'; b.setAttribute('aria-pressed','false'); b.dataset.k=t.k;
|
||||
b.innerHTML='<span class="sw" style="--c:'+t.c+'" aria-hidden="true"></span><span class="pick" aria-hidden="true">✓</span><b>'+P.esc(t.n)+'</b><span>'+P.esc(t.s)+'</span><span class="num">¥6</span>';
|
||||
b.onclick=function(){ var on=S.tpls.indexOf(t.k)<0; S.tpls=on?S.tpls.concat([t.k]):S.tpls.filter(function(x){return x!==t.k;});
|
||||
b.setAttribute('aria-pressed',String(on)); sum(); };
|
||||
g.appendChild(b);
|
||||
});
|
||||
/* 分辨率 */
|
||||
[].forEach.call(document.querySelectorAll('#resSeg button'),function(b){ b.onclick=function(){ S.res=+b.dataset.r;
|
||||
[].forEach.call(document.querySelectorAll('#resSeg button'),function(x){ x.setAttribute('aria-pressed',String(x===b)); }); sum(); }; });
|
||||
/* 皮肤:三色灯(绿放行 / 黄勾了「无视风险」才放行 / 红拦住) */
|
||||
function lamps(list){ $('skinRep').innerHTML=list.map(function(l){ return '<div class="lamp '+l[0]+'">'+l[1]+'</div>'; }).join(''); }
|
||||
function checkSkin(f){
|
||||
S.skin=null; sum();
|
||||
if(!f) return;
|
||||
if(!/\.png$/i.test(f.name)||(f.type&&f.type!=='image/png')){ lamps([['bad','<span><b>不是 PNG 图片</b>,模板只认 .png 皮肤</span>']]); return; }
|
||||
if(f.size>10*1024*1024){ lamps([['bad','<span><b>文件太大</b>(上限 10MB)</span>']]); return; }
|
||||
var img=new Image(), url=URL.createObjectURL(f);
|
||||
img.onload=function(){
|
||||
var w=img.naturalWidth,h=img.naturalHeight,cv=$('skinCv'); cv.width=w; cv.height=h;
|
||||
var cx=cv.getContext('2d'); cx.imageSmoothingEnabled=false; cx.clearRect(0,0,w,h); cx.drawImage(img,0,0);
|
||||
cv.hidden=false; $('skinPh').hidden=true; URL.revokeObjectURL(url);
|
||||
var L=[], lv='ok';
|
||||
if(w===h*2){ L.push(['bad','<span><b>旧版 2:1 皮肤('+w+'×'+h+')</b>:没有左手左腿和外层,模板渲染不了。换一张新版 64×64 的。</span>']); lv='bad'; }
|
||||
else if(w!==h){ L.push(['bad','<span><b>不是皮肤比例('+w+'×'+h+')</b>:皮肤应该是正方形的。</span>']); lv='bad'; }
|
||||
else if(w%64){ L.push(['warn','<span><b>尺寸 '+w+'×'+h+' 不是 64 的倍数</b>:能渲,但手臂和外层可能错位。<label><input type="checkbox" id="riskOk"> 我知道,无视风险继续</label></span>']); lv='warn'; }
|
||||
else if(w>1024){ L.push(['warn','<span><b>超大皮肤 '+w+'×'+h+'</b>:能渲,出图会慢一些。<label><input type="checkbox" id="riskOk"> 我知道,继续</label></span>']); lv='warn'; }
|
||||
else L.push(['ok','<span><b>标准皮肤 '+w+'×'+h+'</b>:可以直接渲染。</span>']);
|
||||
L.push(['ok','<span>文件 '+P.esc(f.name)+' · '+Math.round(f.size/1024)+' KB</span>']);
|
||||
lamps(L); S.skin={name:f.name,lv:lv,ack:false};
|
||||
var r=$('riskOk'); if(r) r.onchange=function(){ S.skin.ack=r.checked; sum(); };
|
||||
sum();
|
||||
};
|
||||
img.onerror=function(){ lamps([['bad','<span><b>这张图读不出来</b>,换一个文件试试</span>']]); };
|
||||
img.src=url;
|
||||
}
|
||||
$('skinFile').onchange=function(e){ checkSkin(e.target.files[0]); };
|
||||
var drop=$('skinDrop');
|
||||
drop.addEventListener('dragover',function(e){ e.preventDefault(); });
|
||||
drop.addEventListener('drop',function(e){ e.preventDefault(); checkSkin(e.dataTransfer.files[0]); });
|
||||
/* 汇总 */
|
||||
function why(){
|
||||
if(!S.tpls.length) return '先选至少一个模板';
|
||||
if(!S.skin) return '还没选皮肤';
|
||||
if(S.skin.lv==='bad') return '这张皮肤渲染不了';
|
||||
if(S.skin.lv==='warn'&&!S.skin.ack) return '勾一下「无视风险」才能继续';
|
||||
return '';
|
||||
}
|
||||
function sum(){
|
||||
var n=S.tpls.length, w=why();
|
||||
$('sumAmt').textContent='¥'+(n*6);
|
||||
$('sumTxt').textContent=n?(n+' 张 · '+S.res+'px · '+P.TPLS.filter(function(t){return S.tpls.indexOf(t.k)>=0;}).map(function(t){return t.n;}).join('、')):'还没选模板';
|
||||
var L=P.TPLS.filter(function(t){return S.tpls.indexOf(t.k)>=0;}).map(function(t){ return '<li><span>'+P.esc(t.n)+'</span><span class="num">¥6</span></li>'; });
|
||||
L.push('<li class="meta"><span>分辨率</span><span class="num">'+S.res+'px</span></li>');
|
||||
L.push('<li class="meta"><span>皮肤</span><span>'+(S.skin?(S.skin.lv==='bad'?'不能渲染':(S.skin.lv==='warn'?(S.skin.ack?'已确认风险':'待确认风险'):'已通过质检')):'还没选')+'</span></li>');
|
||||
$('sumList').innerHTML=L.join('');
|
||||
$('sumWhy').textContent=w; $('btnBuy').disabled=!!w;
|
||||
if(matchMedia('(max-width:760px)').matches && w){ $('sumTxt').textContent=w; $('sumTxt').className='blocked'; } else $('sumTxt').className='';
|
||||
}
|
||||
$('btnBuy').onclick=function(){
|
||||
var b=this; b.disabled=true; b.textContent='正在下单…';
|
||||
P.api('POST','/order',{templates:S.tpls,res:S.res,skin_name:S.skin&&S.skin.name}).then(function(j){
|
||||
if(!j.ok){ $('sumWhy').textContent=j.error||'下单失败'; b.disabled=false; b.textContent='去付款'; return; }
|
||||
P.saveOrder({oid:j.order.oid,t:j.token,ts:Date.now(),amount:j.order.amount,n:j.order.n_img});
|
||||
location.href='pay.html?o='+encodeURIComponent(j.order.oid)+'&t='+encodeURIComponent(j.token);
|
||||
});
|
||||
};
|
||||
sum();
|
||||
/* 我的订单 */
|
||||
function mine(){
|
||||
var l=P.orders().slice(0,10), box=$('mine');
|
||||
if(!l.length){ box.innerHTML='<div class="note">这台浏览器还没下过单。</div>'; return; }
|
||||
box.innerHTML=l.map(function(o){ return '<a class="mrow crystal" id="m_'+o.oid+'" href="pay.html?o='+encodeURIComponent(o.oid)+'&t='+encodeURIComponent(o.t)+'">'
|
||||
+'<span class="code">'+P.esc(o.oid)+'</span><span class="what">'+o.n+' 张 · ¥'+o.amount+' · '+new Date(o.ts).toLocaleString('zh-CN',{hour12:false})+'</span><span class="state">…</span></a>'; }).join('');
|
||||
l.forEach(function(o){ P.api('GET','/order?oid='+encodeURIComponent(o.oid)+'&t='+encodeURIComponent(o.t)).then(function(j){
|
||||
var el=document.querySelector('#m_'+o.oid+' .state'); if(!el) return;
|
||||
if(j.ok){ el.textContent=P.STATE[j.order.state]||j.order.state_text; el.className='state '+j.order.state; } else el.textContent='查不到'; }); });
|
||||
}
|
||||
mine(); P.demo.onChange=mine;
|
||||
$('lookup').onsubmit=function(e){ e.preventDefault();
|
||||
var oid=$('lkOid').value.trim().toUpperCase(), t=$('lkTok').value.trim().toUpperCase(), m=$('lkMsg');
|
||||
if(!oid||!t){ m.hidden=false; m.textContent='订单号和取件码都要填'; return; }
|
||||
P.api('GET','/order?oid='+encodeURIComponent(oid)+'&t='+encodeURIComponent(t)).then(function(j){
|
||||
if(!j.ok){ m.hidden=false; m.textContent='没查到:订单号或取件码不对'; return; }
|
||||
P.saveOrder({oid:oid,t:t,ts:j.order.created_at*1000,amount:j.order.amount,n:j.order.n_img});
|
||||
location.href='pay.html?o='+encodeURIComponent(oid)+'&t='+encodeURIComponent(t); });
|
||||
};
|
||||
})();
|
||||
</script>
|
||||
<script src="assets/site.js?v=32"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,189 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<meta name="robots" content="noindex,nofollow">
|
||||
<title>收银台 · 金钻客栈(设计预览)</title>
|
||||
<meta name="theme-color" content="#FAFBFE">
|
||||
<link rel="preload" href="assets/OPPOSans-B.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="stylesheet" href="assets/site.css?v=33">
|
||||
<link rel="stylesheet" href="assets/pay.css?v=2">
|
||||
</head>
|
||||
<body>
|
||||
<div class="orbs" aria-hidden="true"><i class="o1"></i><i class="o2"></i><i class="o3"></i><i class="o4"></i><i class="o5"></i></div>
|
||||
<div class="ribbon"><span><b>设计预览版</b>,方括号里的是占位内容</span></div>
|
||||
<header class="top"><div class="wrap top-in"><a class="brand" href="index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a><nav class="nav" aria-label="导航"><a href="index.html">首页</a><a href="gallery.html">画展</a><a href="tools.html">工具与开源</a><a href="universe.html">金钻宇宙</a><a href="links.html">平台入口</a><a href="about.html">关于</a></nav><div class="desk-btn"><a class="btn-pill" href="order.html" aria-current="page"><span class="ic" aria-hidden="true"></span>自助渲染<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></svg></a></div><a class="cms-ent" href="cms/" aria-label="内容管理" title="内容管理"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg></a></div></header>
|
||||
<main class="wrap">
|
||||
<div class="room-head svc-head"><div class="svc-ic" aria-hidden="true"><i class="gem-img"></i></div>
|
||||
<div><h1 id="pTitle">收银台</h1><p id="pSub">选一种方式付款,到账后自动开始渲染。</p><p class="svc-line"><a href="order.html" style="color:inherit">← 回到自助渲染</a></p></div></div>
|
||||
<section class="sec" style="padding-top:6px" aria-label="订单">
|
||||
<div class="pass crystal pay" id="passCard">
|
||||
<div class="main">
|
||||
<div class="row"><div><div class="lbl">订单号</div><div class="code" id="pOid">—</div></div><span class="state" id="pState">读取中</span></div>
|
||||
<div class="row" style="align-items:flex-end"><div><div class="lbl">应付</div><div class="amt" id="pAmt">—</div></div><div class="items" id="pItems"></div></div>
|
||||
<div id="unpaidBox" hidden>
|
||||
<div class="lbl" style="margin-bottom:8px">付款方式</div>
|
||||
<div class="chs" id="chs"></div>
|
||||
<div class="qrbox" id="qrbox" hidden style="margin-top:16px"><div class="qr" id="qr"></div><div id="qrInfo"></div></div>
|
||||
<div class="row" style="justify-content:flex-start;gap:10px 14px;margin-top:16px">
|
||||
<button type="button" class="btn btn-crystal btn-sm" id="btnCheck">付好了没反应?</button>
|
||||
<span class="note" id="keep" style="margin:0"></span></div>
|
||||
<div class="pmsg" id="pMsg" hidden style="margin-top:10px"></div>
|
||||
</div>
|
||||
<div id="paidBox" hidden>
|
||||
<div class="paid-hero"><div class="ok" aria-hidden="true">✓</div><div><b>已付款,正在排队出图</b><p>不用再做任何操作。出图后在这一页看预览、确认收货、下载原图。</p></div></div>
|
||||
<div class="prog" id="pProg" aria-hidden="true" style="margin-top:14px"></div>
|
||||
<div class="note" id="paidAt"></div>
|
||||
</div>
|
||||
<div id="closedBox" hidden>
|
||||
<div class="pmsg bad">这张订单超过 24 小时没付款,已经自动关闭。如果其实付过了,系统会在 72 小时内自动认回来;也可以点下面立即查一次。</div>
|
||||
<div class="row" style="justify-content:flex-start;gap:10px;margin-top:12px"><a class="btn btn-prism btn-sm" href="order.html#tpl">重新下单</a><button type="button" class="btn btn-crystal btn-sm" id="btnCheck2">付好了没反应?</button></div>
|
||||
<div class="pmsg" id="pMsg2" hidden style="margin-top:10px"></div>
|
||||
</div>
|
||||
<div id="missBox" hidden><div class="pmsg bad">没找到这张订单:链接里缺了取件码,或者取件码不对。去「我的订单」用订单号和取件码查。</div>
|
||||
<a class="btn btn-crystal btn-sm" href="order.html#pass" style="margin-top:12px">我的订单</a></div>
|
||||
<details id="logBox" hidden><summary class="note" style="cursor:pointer">付款记录</summary><table class="plog" id="plog"></table></details>
|
||||
</div>
|
||||
<div class="stub">
|
||||
<div><div class="lbl">取件码</div><div class="code" id="pTok">—</div></div>
|
||||
<div class="barcode" aria-hidden="true"></div>
|
||||
<div style="font-size:13px;color:var(--ink-3);line-height:1.7">记好订单号和取件码,换了手机也能查单、取图。</div>
|
||||
<button type="button" class="btn btn-crystal btn-sm" id="btnCopy">复制订单链接</button>
|
||||
<a class="btn btn-crystal btn-sm" href="order.html#pass">我的订单</a>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<p class="note" style="margin-top:28px;line-height:1.9">非官方 Minecraft 产品,与 Mojang 无关<br>有问题来 QQ 群找金钻:123456789</p>
|
||||
</main>
|
||||
<nav class="tabbar" aria-label="导航"><a href="index.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/><path d="M10 21v-6h4v6"/></svg><span>首页</span></a><a href="gallery.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/></svg><span>画展</span></a><a class="mid" href="order.html" aria-current="page"><i aria-hidden="true"></i><span>渲染</span></a><a href="universe.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="5"/><path d="M4.2 15.6c-1.6 2.5 4.2 2.4 9.6-.2s9-6.6 7.5-8.6c-.8-1-2.9-.9-5.4 0"/></svg><span>宇宙</span></a><button type="button" data-sheet="more" aria-expanded="false" aria-controls="more"><i class="ic-a"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3.5" y="3.5" width="7" height="7" rx="2"/><rect x="13.5" y="3.5" width="7" height="7" rx="2"/><rect x="3.5" y="13.5" width="7" height="7" rx="2"/><rect x="13.5" y="13.5" width="7" height="7" rx="2"/></svg></i><i class="ic-b"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="M6 6l12 12"/></svg></i><span class="lb-a">更多</span><span class="lb-b">收起</span></button></nav>
|
||||
<div class="sheet" id="more" hidden><div class="panel"><nav class="more-grid" aria-label="更多"><a href="tools.html" style="--zc:#4F86E8;--zc2:#2E5BD8"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg></i><span>工具与开源</span></a><a href="links.html" style="--zc:#22B573;--zc2:#3C8527"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg></i><span>平台入口</span></a><a href="about.html" style="--zc:#E0533D;--zc2:#E8913A"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg></i><span>关于</span></a></nav><p class="more-qq">QQ 群:屑钻小窝 123456789</p></div></div>
|
||||
<footer class="foot-site"><div class="wrap foot-in"><a class="brand" href="index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a><span>© 2026 example.com</span><span>QQ 群:屑钻小窝 123456789</span><span class="sp"></span><span>备案号(已移除)</span></div></footer>
|
||||
<script src="assets/vendor/qrcode.min.js"></script>
|
||||
<script src="assets/pay.js?v=2"></script>
|
||||
<script>
|
||||
(function(){
|
||||
'use strict';
|
||||
var P=window.JZPay, $=function(i){return document.getElementById(i);};
|
||||
var q=new URLSearchParams(location.search);
|
||||
var S={oid:(q.get('o')||'').toUpperCase(), t:(q.get('t')||'').toUpperCase(), v:null, pay:null, timer:0, skew:0};
|
||||
if(!S.t) S.t=P.tokenOf(S.oid);
|
||||
var mobile=matchMedia('(max-width:760px), (pointer:coarse)').matches;
|
||||
var PST={created:'等待付款',paid:'已到账',mismatch:'金额不足',closed:'已关闭',refunded:'已退款'};
|
||||
|
||||
function show(id,on){ $(id).hidden=!on; }
|
||||
function nowSec(){ return Date.now()/1000+S.skew; } /* 服务器(演示)时钟 */
|
||||
function render(v){
|
||||
S.v=v; S.skew=v.now-Date.now()/1000; P.demoUpdate(v);
|
||||
var o=v.order;
|
||||
P.saveOrder({oid:o.oid,t:S.t,ts:o.created_at*1000,amount:o.amount,n:o.n_img});
|
||||
$('pOid').textContent=o.oid; $('pTok').textContent=S.t;
|
||||
var st=$('pState'); st.textContent=P.STATE[o.state]||o.state_text; st.className='state '+o.state;
|
||||
$('pAmt').textContent='¥'+o.amount;
|
||||
$('pItems').innerHTML=o.templates.map(function(t){ return '<span class="chip">'+P.esc(t.n)+'</span>'; }).join('')
|
||||
+'<span class="chip num">'+o.res+'px</span>'+(o.skin_name?'<span class="chip">'+P.esc(o.skin_name)+'</span>':'');
|
||||
var unpaid=o.state==='unpaid';
|
||||
$('pTitle').textContent=unpaid?'收银台':'订单';
|
||||
$('pSub').textContent=unpaid?'选一种方式付款,到账后自动开始渲染。':(o.state==='closed'?'这张订单已关闭。':'进度都在这一页看。');
|
||||
show('unpaidBox',unpaid); show('paidBox',o.state==='waiting'||o.state==='working'||o.state==='done'); show('closedBox',o.state==='closed'); show('missBox',false);
|
||||
if(o.state==='waiting'){
|
||||
$('pProg').style.gridTemplateColumns='repeat('+o.n_img+',minmax(0,1fr))';
|
||||
$('pProg').innerHTML=new Array(o.n_img+1).join('<i></i>');
|
||||
$('paidAt').textContent=o.paid_at?('到账时间 '+P.full(o.paid_at)+' · 一共 '+o.n_img+' 张,排队中'):'';
|
||||
}
|
||||
/* 渠道 */
|
||||
var box=$('chs'); box.innerHTML='';
|
||||
v.channels.forEach(function(c){
|
||||
var b=document.createElement('button'); b.type='button'; b.className='chx crystal '+(c.name==='afdian'?'afd':'ali'); b.disabled=!c.ok;
|
||||
b.innerHTML=(c.name==='afdian'?'<span class="rec">推荐</span>':'')
|
||||
+'<b><i aria-hidden="true">'+(c.name==='afdian'?'爱':'支')+'</i>'+(c.name==='afdian'?'爱发电':'支付宝扫码')+'</b>'
|
||||
+'<span>'+(c.name==='afdian'?'跳到爱发电付款,到账自动确认':'在这一页扫码付款,秒级到账')+'</span>'
|
||||
+(c.ok?'':'<span class="why">'+P.esc(c.reason)+'</span>');
|
||||
b.setAttribute('aria-pressed',String(!!(S.pay&&S.pay.channel===c.name)));
|
||||
b.onclick=function(){ choose(c.name); };
|
||||
box.appendChild(b);
|
||||
});
|
||||
/* 当前支付单:还在用的那张优先;没有就取最新一张待付款的 */
|
||||
var created=v.payments.filter(function(p){ return p.state==='created'; });
|
||||
var keep=S.pay&&created.filter(function(p){ return p.pay_id===S.pay.pay_id; })[0];
|
||||
S.pay=keep||created[created.length-1]||null;
|
||||
[].forEach.call(box.children,function(b,i){ b.setAttribute('aria-pressed',String(!!(S.pay&&S.pay.channel===v.channels[i].name))); });
|
||||
paintQR();
|
||||
/* 记录 */
|
||||
show('logBox',v.payments.length>0);
|
||||
$('plog').innerHTML=v.payments.map(function(p){ return '<tr><td><code>'+P.esc(p.pay_id)+'</code></td><td>'+(p.channel==='afdian'?'爱发电':'支付宝')
|
||||
+'</td><td>¥'+p.amount_due+(p.amount_paid!=null?' · 实付 ¥'+p.amount_paid:'')+'</td><td>'+P.esc(PST[p.state]||p.state)+'</td></tr>'; }).join('');
|
||||
$('keep').textContent=unpaid?('订单保留 '+P.left(o.expire_at-nowSec())+',超时自动关闭'):'';
|
||||
}
|
||||
function paintQR(){
|
||||
var p=S.pay, box=$('qrbox');
|
||||
if(!p||!S.v||S.v.order.state!=='unpaid'){ box.hidden=true; return; }
|
||||
box.hidden=false;
|
||||
var d=p.display||{}, link=p.channel==='afdian'?(d.url||''):(d.qr||''), wait='<div class="waitline" style="margin-top:14px">正在等待到账,不用刷新页面</div>';
|
||||
if(mobile){
|
||||
/* 手机:买家就在这台手机上付,自己扫不了自己的屏幕 → 按钮优先,二维码收起来留给「另一台设备」 */
|
||||
$('qr').innerHTML=''; $('qr').style.display='none'; box.style.display='block';
|
||||
$('qrInfo').innerHTML=(p.channel==='afdian'
|
||||
? '<h4>爱发电付款 ¥'+p.amount_due+'</h4><p>点下面的按钮去爱发电付款,付完回到这一页,会自动变成「已付款」。</p>'
|
||||
+'<a class="btn btn-prism btn-wide" href="'+P.esc(link)+'" target="_blank" rel="noopener">去爱发电付款</a>'
|
||||
: '<h4>支付宝付款 ¥'+p.amount_due+'</h4><div class="cd" id="cd">付款码有效 <b id="cdv">--:--</b></div>'
|
||||
+'<a class="btn btn-prism btn-wide" href="'+P.esc(link)+'" target="_blank" rel="noopener">打开支付宝付款</a>')
|
||||
+wait+'<details class="qrfold"><summary>用另一台设备扫码付款</summary><div class="qr">'+P.qrSvg(link)+'</div></details>';
|
||||
}else{
|
||||
box.style.display=''; $('qr').style.display='';
|
||||
$('qr').innerHTML=P.qrSvg(link);
|
||||
$('qrInfo').innerHTML=(p.channel==='afdian'
|
||||
? '<h4>爱发电付款 ¥'+p.amount_due+'</h4><p>用手机扫左边的码,在爱发电付款;用这台电脑付就点下面的按钮。付完回到这一页,会自动变成「已付款」。</p>'
|
||||
+'<a class="btn btn-prism btn-sm" href="'+P.esc(link)+'" target="_blank" rel="noopener">去爱发电付款</a>'
|
||||
: '<h4>支付宝扫码 ¥'+p.amount_due+'</h4><p>打开手机支付宝「扫一扫」,扫左边的二维码付款。</p>'
|
||||
+'<div class="cd" id="cd">二维码有效 <b id="cdv">--:--</b></div>'
|
||||
+'<a href="'+P.esc(link)+'" target="_blank" rel="noopener" style="font-size:13px">预览站:在这台设备打开模拟扫码页</a>')
|
||||
+wait;
|
||||
}
|
||||
tick();
|
||||
}
|
||||
function tick(){
|
||||
var e=$('cdv'); if(!e||!S.pay) return;
|
||||
var r=S.pay.expire_at-nowSec(); e.textContent=P.left(r); $('cd').classList.toggle('low',r<120);
|
||||
if(r<=0){ e.textContent='已过期'; var w=$('qrInfo').querySelector('.waitline'); if(w) w.textContent='付款码已过期:点上面的「支付宝扫码」重新生成一张。'; }
|
||||
}
|
||||
setInterval(function(){ tick(); if(S.v&&S.v.order.state==='unpaid') $('keep').textContent='订单保留 '+P.left(S.v.order.expire_at-nowSec())+',超时自动关闭'; },1000);
|
||||
|
||||
function choose(ch){
|
||||
$('pMsg').hidden=true;
|
||||
P.api('POST','/pay',{oid:S.oid,t:S.t,channel:ch}).then(function(j){
|
||||
if(!j.ok){ msg('pMsg',j.error,true); return refresh(); }
|
||||
S.pay=j.payment; refresh();
|
||||
});
|
||||
}
|
||||
function msg(id,t,bad){ var m=$(id); m.hidden=false; m.textContent=t; m.className='pmsg'+(bad?' bad':''); }
|
||||
function check(id){
|
||||
msg(id,'正在向支付渠道查询…');
|
||||
P.api('POST','/check',{oid:S.oid,t:S.t}).then(function(j){ msg(id,j.msg||j.error||'',!j.found); refresh(); });
|
||||
}
|
||||
$('btnCheck').onclick=function(){ check('pMsg'); };
|
||||
$('btnCheck2').onclick=function(){ check('pMsg2'); };
|
||||
$('btnCopy').onclick=function(){
|
||||
var u=location.origin+location.pathname+'?o='+S.oid+'&t='+S.t, b=this;
|
||||
(navigator.clipboard?navigator.clipboard.writeText(u):Promise.reject()).then(function(){ b.textContent='已复制'; },function(){ prompt('复制这个链接',u); });
|
||||
setTimeout(function(){ b.textContent='复制订单链接'; },1600);
|
||||
};
|
||||
|
||||
function refresh(){
|
||||
if(!S.oid||!S.t){ miss(); return Promise.resolve(); }
|
||||
var url=(S.pay&&S.pay.state==='created'&&S.v&&S.v.order.state==='unpaid')
|
||||
? '/pay?pay_id='+encodeURIComponent(S.pay.pay_id)+'&t='+encodeURIComponent(S.t)
|
||||
: '/order?oid='+encodeURIComponent(S.oid)+'&t='+encodeURIComponent(S.t);
|
||||
return P.api('GET',url).then(function(j){ if(j.ok) render(j); else if(!S.v) miss(); });
|
||||
}
|
||||
function miss(){ show('missBox',true); show('unpaidBox',false); $('pOid').textContent=S.oid||'—'; $('pState').textContent='查不到'; $('pTitle').textContent='订单'; }
|
||||
function loop(){ clearTimeout(S.timer); if(document.visibilityState!=='visible') return;
|
||||
refresh().then(function(){ S.timer=setTimeout(loop,(S.v&&S.v.order.state==='unpaid')?3000:8000); }); }
|
||||
document.addEventListener('visibilitychange',function(){ if(document.visibilityState==='visible') loop(); });
|
||||
P.demo.onChange=refresh;
|
||||
loop();
|
||||
})();
|
||||
</script>
|
||||
<script src="assets/site.js?v=32"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,269 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""支付原型场景测试:临时目录起一份服务(全模拟渠道),从 HTTP 层打。
|
||||
|
||||
用法:python3 tests/test_proto.py
|
||||
"""
|
||||
import base64, json, os, re, shutil, socket, subprocess, sys, tempfile, time, urllib.parse, urllib.request
|
||||
|
||||
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def check(name, ok, detail=""):
|
||||
RESULTS.append((name, bool(ok)))
|
||||
print(("PASS " if ok else "FAIL ") + name + ((" —— " + str(detail)[:200]) if detail != "" else ""))
|
||||
|
||||
|
||||
def free_port():
|
||||
s = socket.socket()
|
||||
s.bind(("127.0.0.1", 0))
|
||||
p = s.getsockname()[1]
|
||||
s.close()
|
||||
return p
|
||||
|
||||
|
||||
PORT = free_port()
|
||||
BASE = "http://127.0.0.1:%d" % PORT
|
||||
DATA = tempfile.mkdtemp(prefix="payproto_")
|
||||
env = dict(os.environ, PAY_PORT=str(PORT), PAY_DATA_DIR=DATA, PAY_BASE_URL=BASE)
|
||||
srv = subprocess.Popen([sys.executable, os.path.join(HERE, "app.py")], env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
||||
|
||||
|
||||
def req(method, path, obj=None, form=None, headers=None, raw=False):
|
||||
data, h = None, dict(headers or {})
|
||||
if obj is not None:
|
||||
data = json.dumps(obj).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
if form is not None:
|
||||
data = urllib.parse.urlencode(form).encode()
|
||||
h["Content-Type"] = "application/x-www-form-urlencoded"
|
||||
r = urllib.request.Request(BASE + path, data=data, method=method, headers=h)
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=20) as resp:
|
||||
body = resp.read().decode()
|
||||
return resp.status, (body if raw else json.loads(body))
|
||||
except urllib.error.HTTPError as e:
|
||||
body = e.read().decode()
|
||||
return e.code, (body if raw else json.loads(body or "{}"))
|
||||
|
||||
|
||||
for _ in range(300):
|
||||
try:
|
||||
urllib.request.urlopen(BASE + "/", timeout=1)
|
||||
break
|
||||
except Exception:
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def new_order(n=2):
|
||||
st, j = req("POST", "/api/order", {"n_img": n})
|
||||
return j["order"]["oid"], j["token"], j
|
||||
|
||||
|
||||
def view(oid, tok):
|
||||
return req("GET", "/api/order?oid=%s&t=%s" % (oid, tok))[1]
|
||||
|
||||
|
||||
def pay(oid, tok, ch):
|
||||
return req("POST", "/api/pay", {"oid": oid, "t": tok, "channel": ch})[1]
|
||||
|
||||
|
||||
def afd_pay_link(url, amount=None, drop=False):
|
||||
qs = dict(urllib.parse.parse_qsl(urllib.parse.urlparse(url).query))
|
||||
form = {"custom_order_id": qs["custom_order_id"], "remark": qs["remark"],
|
||||
"amount": amount if amount is not None else qs["custom_price"]}
|
||||
if drop:
|
||||
form["drop"] = "on"
|
||||
req("POST", "/mock/afdian/order/pay", form=form, raw=True)
|
||||
return qs
|
||||
|
||||
|
||||
def ali_scan_pay(qr_url, drop=False):
|
||||
path = urllib.parse.urlparse(qr_url).path
|
||||
req("GET", path, raw=True) # 扫码 → WAIT_BUYER_PAY
|
||||
form = {"qr": path.rsplit("/", 1)[-1]}
|
||||
if drop:
|
||||
form["drop"] = "on"
|
||||
return req("POST", "/mock/alipay/scanpay", form=form, raw=True)[1]
|
||||
|
||||
|
||||
def demo(**kw):
|
||||
return req("POST", "/api/demo", kw)[1]
|
||||
|
||||
|
||||
def todos():
|
||||
tok = open(os.path.join(DATA, "admin_token")).read().strip()
|
||||
return req("GET", "/api/admin/overview", headers={"X-Admin-Token": tok})[1]["todo"]
|
||||
|
||||
|
||||
def admin(path, obj):
|
||||
tok = open(os.path.join(DATA, "admin_token")).read().strip()
|
||||
return req("POST", path, obj, headers={"X-Admin-Token": tok})[1]
|
||||
|
||||
|
||||
try:
|
||||
# 1. 爱发电正常到账(Webhook)
|
||||
oid, tok, j = new_order(2)
|
||||
check("下单:应付 ¥12、状态 unpaid、两个渠道可选", j["order"]["amount"] == 12 and j["order"]["state"] == "unpaid"
|
||||
and [c["name"] for c in j["channels"] if c["ok"]] == ["afdian", "alipay"])
|
||||
r = pay(oid, tok, "afdian")
|
||||
url = r["payment"]["display"]["url"]
|
||||
check("爱发电专链带 custom_order_id=支付单号、custom_price=应付", "custom_order_id=%sP1" % oid in url
|
||||
and "custom_price=12" in url, url)
|
||||
afd_pay_link(url)
|
||||
time.sleep(3)
|
||||
v = view(oid, tok)
|
||||
check("爱发电付款 → Webhook 验签 + 精确反查 → 订单 waiting", v["order"]["state"] == "waiting",
|
||||
[e["kind"] + ":" + e["result"] for e in v["events"][:4]])
|
||||
|
||||
# 1b. 按真实下单内容建单:模板 × 1 张皮肤,金额按模板数算,非法模板/分辨率被过滤
|
||||
st, jt = req("POST", "/api/order", {"templates": ["stand", "sakura", "nope", "stand"], "res": 2048, "skin_name": "a.png"})
|
||||
o = jt["order"]
|
||||
check("下单带模板:去重、丢掉不认识的模板,2 个模板 = ¥12,分辨率 2048,皮肤名带回",
|
||||
o["amount"] == 12 and [t["n"] for t in o["templates"]] == ["站立正反", "飞跃樱花林"] and o["res"] == 2048
|
||||
and o["skin_name"] == "a.png" and len(jt["token"]) == 10, o)
|
||||
st, jt = req("POST", "/api/order", {"templates": ["wheat"], "res": 777})
|
||||
check("不支持的分辨率 → 回落 1000", jt["order"]["res"] == 1000, jt["order"]["res"])
|
||||
|
||||
# 2. 同一笔 Webhook 重复推送 → 幂等
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
import sqlite3
|
||||
con = sqlite3.connect(os.path.join(DATA, "pay.db"))
|
||||
con.row_factory = sqlite3.Row
|
||||
mo = dict(con.execute("SELECT * FROM mock_afd ORDER BY create_time DESC LIMIT 1").fetchone())
|
||||
pk = serialization.load_pem_private_key(open(os.path.join(DATA, "mock_keys", "afdian_platform.pem"), "rb").read(), None)
|
||||
content = "%s%s%s%s" % (mo["out_trade_no"], mo["user_id"], mo["plan_id"], mo["total_amount"])
|
||||
sig = base64.b64encode(pk.sign(content.encode(), padding.PKCS1v15(), hashes.SHA256())).decode()
|
||||
body = {"ec": 200, "data": {"type": "order", "order": mo, "sign": sig}}
|
||||
st, resp = req("POST", "/api/notify/afdian", body)
|
||||
n_settle = con.execute("SELECT COUNT(*) FROM pay_events WHERE kind='settle' AND pay_id=? AND result='activated'",
|
||||
(oid + "P1",)).fetchone()[0]
|
||||
dup = con.execute("SELECT COUNT(*) FROM pay_events WHERE kind='settle' AND pay_id=? AND result='dup_trade'",
|
||||
(oid + "P1",)).fetchone()[0]
|
||||
check("同一笔 Webhook 再推一次 → 只激活一次(dup_trade),仍回 ec=200", n_settle == 1 and dup >= 1 and resp.get("ec") == 200,
|
||||
(n_settle, dup, resp))
|
||||
|
||||
# 3. 伪造回调(签名不对)→ 丢弃
|
||||
oid3, tok3, _ = new_order(1)
|
||||
p3 = pay(oid3, tok3, "afdian")["payment"]["pay_id"]
|
||||
demo(kind="afdian_forge", pay_id=p3)
|
||||
time.sleep(0.3)
|
||||
check("伪造 Webhook(签名不对)→ 不激活", view(oid3, tok3)["order"]["state"] == "unpaid")
|
||||
|
||||
# 4. Webhook 丢失 → 对账补上
|
||||
oid4, tok4, _ = new_order(1)
|
||||
afd_pay_link(pay(oid4, tok4, "afdian")["payment"]["display"]["url"], drop=True)
|
||||
time.sleep(2)
|
||||
before = view(oid4, tok4)["order"]["state"]
|
||||
demo(kind="jobs")
|
||||
check("Webhook 丢了 → 定时对账发现并激活", before == "unpaid" and view(oid4, tok4)["order"]["state"] == "waiting", before)
|
||||
|
||||
# 5. 买家把金额改小 → 不激活,进待办
|
||||
oid5, tok5, _ = new_order(3)
|
||||
afd_pay_link(pay(oid5, tok5, "afdian")["payment"]["display"]["url"], amount="0.10")
|
||||
time.sleep(3)
|
||||
td = [t for t in todos() if t["oid"] == oid5]
|
||||
check("实付 ¥0.10 < 应付 ¥18 → 不激活,待办「金额不足」", view(oid5, tok5)["order"]["state"] == "unpaid"
|
||||
and td and td[0]["kind"] == "short", td[:1])
|
||||
r = admin("/api/admin/todo", {"id": td[0]["id"], "action": "confirm", "note": "买家补了差价"})
|
||||
check("后台「确认补齐」→ 订单激活", r.get("ok") and view(oid5, tok5)["order"]["state"] == "waiting", r)
|
||||
|
||||
# 6. 当面付正常:预下单 → 扫码 → 异步通知
|
||||
oid6, tok6, _ = new_order(2)
|
||||
r = pay(oid6, tok6, "alipay")
|
||||
qr = r["payment"]["display"]["qr"]
|
||||
check("当面付预下单 → 返回二维码内容和过期时间", r["ok"] and "/mock/alipay/scan/" in qr
|
||||
and r["payment"]["expire_at"] > 0, r)
|
||||
ali_scan_pay(qr)
|
||||
time.sleep(3)
|
||||
check("当面付付款 → 异步通知验签 → 订单 waiting", view(oid6, tok6)["order"]["state"] == "waiting")
|
||||
|
||||
# 7. 当面付异步通知丢失 → 页面轮询查单发现
|
||||
oid7, tok7, _ = new_order(1)
|
||||
r = pay(oid7, tok7, "alipay")
|
||||
ali_scan_pay(r["payment"]["display"]["qr"], drop=True)
|
||||
time.sleep(2)
|
||||
st, v = req("GET", "/api/pay?pay_id=%s&t=%s" % (r["payment"]["pay_id"], tok7))
|
||||
check("当面付通知丢了 → 页面轮询 trade.query 发现到账", v["order"]["state"] == "waiting")
|
||||
|
||||
# 8. 二维码过期 → 关单;订单超时 → closed;宽限内迟到付款 → 恢复
|
||||
oid8, tok8, _ = new_order(1)
|
||||
p8 = pay(oid8, tok8, "alipay")["payment"]
|
||||
a8 = pay(oid8, tok8, "afdian")["payment"]
|
||||
demo(kind="clock", seconds=16 * 60)
|
||||
pays = {p["pay_id"]: p["state"] for p in view(oid8, tok8)["payments"]}
|
||||
check("二维码 15 分钟没付 → 支付单关闭;爱发电支付单还在", pays[p8["pay_id"]] == "closed"
|
||||
and pays[a8["pay_id"]] == "created", pays)
|
||||
demo(kind="clock", seconds=25 * 3600)
|
||||
check("超过 24 小时没付 → 订单 closed", view(oid8, tok8)["order"]["state"] == "closed")
|
||||
afd_pay_link(a8["display"]["url"])
|
||||
time.sleep(3)
|
||||
check("关闭后宽限期内付了爱发电 → 订单自动恢复为 waiting", view(oid8, tok8)["order"]["state"] == "waiting",
|
||||
[e["kind"] + ":" + e["result"] for e in view(oid8, tok8)["events"][:3]])
|
||||
|
||||
# 9. 两个渠道都付了 → 只激活一次,第二笔进待办
|
||||
oid9, tok9, _ = new_order(1)
|
||||
a9 = pay(oid9, tok9, "afdian")["payment"]
|
||||
q9 = pay(oid9, tok9, "alipay")["payment"]
|
||||
ali_scan_pay(q9["display"]["qr"])
|
||||
time.sleep(3)
|
||||
afd_pay_link(a9["display"]["url"])
|
||||
time.sleep(3)
|
||||
td = [t for t in todos() if t["oid"] == oid9]
|
||||
check("先付支付宝、又付爱发电 → 订单只激活一次,爱发电那笔进待办「重复付款」",
|
||||
view(oid9, tok9)["order"]["state"] == "waiting" and td and td[0]["kind"] == "duplicate", td[:1])
|
||||
r = admin("/api/admin/todo", {"id": td[0]["id"], "action": "refund"})
|
||||
check("爱发电重复付款点退款 → 提示去爱发电后台(没有退款接口)", not r.get("ok") and "爱发电" in r.get("error", ""), r)
|
||||
|
||||
# 10. 风控熔断
|
||||
demo(kind="alipay_risk", on=True)
|
||||
oid10, tok10, _ = new_order(1)
|
||||
r = pay(oid10, tok10, "alipay")
|
||||
v = view(oid10, tok10)
|
||||
ali = [c for c in v["channels"] if c["name"] == "alipay"][0]
|
||||
check("当面付返回风控错误码 → 熔断,页面不再提供支付宝,只剩爱发电", not r["ok"] and not ali["ok"], (r, ali))
|
||||
demo(kind="alipay_risk", on=False)
|
||||
demo(kind="breaker_reset")
|
||||
check("后台恢复熔断后 → 支付宝重新可用",
|
||||
[c for c in view(oid10, tok10)["channels"] if c["name"] == "alipay"][0]["ok"])
|
||||
|
||||
# 11. 买家直接在爱发电店铺下单(没带订单号)→ 按买卡密处理;后台按爱发电订单号认领
|
||||
r = demo(kind="afdian_direct", amount=6)
|
||||
time.sleep(3)
|
||||
ev = con.execute("SELECT COUNT(*) FROM pay_events WHERE kind='card_purchase'").fetchone()[0]
|
||||
check("没带订单号的爱发电成交 → 走「按实付发卡密」,不去猜是哪张单", ev >= 1)
|
||||
oid11, tok11, _ = new_order(1)
|
||||
r2 = admin("/api/admin/claim", {"oid": oid11, "trade_no": r["trade_no"]})
|
||||
check("后台按爱发电订单号认领 → 订单激活", r2.get("ok") and view(oid11, tok11)["order"]["state"] == "waiting", r2)
|
||||
|
||||
# 12. 「付好了没反应?」→ 立即对账
|
||||
oid12, tok12, _ = new_order(1)
|
||||
afd_pay_link(pay(oid12, tok12, "afdian")["payment"]["display"]["url"], drop=True)
|
||||
time.sleep(1.5)
|
||||
st, r = req("POST", "/api/check", {"oid": oid12, "t": tok12})
|
||||
check("买家点「付好了没反应?」→ 当场查到并激活", r.get("found") and view(oid12, tok12)["order"]["state"] == "waiting", r)
|
||||
|
||||
# 13. 鉴权
|
||||
st, _ = req("GET", "/api/admin/overview")
|
||||
check("后台接口没口令 → 403", st == 403)
|
||||
st, _ = req("GET", "/api/order?oid=%s&t=wrong" % oid)
|
||||
check("取件码不对 → 查不到订单", st == 404)
|
||||
st, r = req("POST", "/api/pay", {"oid": oid, "t": tok, "channel": "afdian"})
|
||||
check("已到账的订单不能再建支付单", not r.get("ok"), r)
|
||||
finally:
|
||||
srv.terminate()
|
||||
try:
|
||||
out = srv.communicate(timeout=5)[0].decode()
|
||||
except Exception:
|
||||
out = ""
|
||||
shutil.rmtree(DATA, ignore_errors=True)
|
||||
|
||||
bad = [n for n, ok in RESULTS if not ok]
|
||||
print("\n%d 条,失败 %d 条" % (len(RESULTS), len(bad)))
|
||||
for n in bad:
|
||||
print(" ✗ " + n)
|
||||
if bad and out:
|
||||
print(out[-2000:])
|
||||
sys.exit(1 if bad else 0)
|
||||
@@ -0,0 +1,46 @@
|
||||
# 交付清单(自查用)
|
||||
|
||||
> 生成:2026-10-05 21:54 共 38 个文件 合计 44.9 MB(2026-10-05 晚:内容后台 cms.py + 推送后全量细审的修复)
|
||||
|
||||
| 文件 | 字节 | SHA-256 |
|
||||
|---|---|---|
|
||||
| `README.md` | 8,696 | `5cef368dbf5916def012dbfcf7fdfb35d1f435faf5a7b42b65f6ad683343b1c2` |
|
||||
| `backend-site/admin.py` | 30,382 | `9b4069444b4c1716a6abef22dfada6bcb3171d78c896579457c926a468d734ec` |
|
||||
| `backend-site/cms.py` | 61,942 | `3d5ea3869427f94fbc9a71e464e10b2c275450e617fbc42c9feb68a66b45fde3` |
|
||||
| `backend-site/pngcheck.py` | 4,945 | `ccec7ab21b0399da651029ffa5781bad498e0905b31a1102f6ba3e3f01e8594d` |
|
||||
| `backend-site/server.py` | 181,993 | `05c0aaa93f5adf39beecb9042313da8233099cee6060013d8f7cbf7fd142788a` |
|
||||
| `backend-site/store.py` | 19,303 | `9d22007b43188225d4254f8c9710c310d9d55635d0d67496ec99e91fe47bcd2d` |
|
||||
| `backend-site/tests/内容后台测试.py` | 24,099 | `9fd44d4aff00c32270fde4347e365781b3fb4b7aca89e024b5b3b252416b9f87` |
|
||||
| `backend-site/tests/回执复现测试.py` | 15,355 | `4529f6076abdfce89bf4406c7fbd0789482deaa595383749580bdc3e08ddc327` |
|
||||
| `backend-site/tests/数据库测试.py` | 16,045 | `9838f32bf213cd3c727625a50b5e0cbff7da98ded8b7452cacd187c448bde04f` |
|
||||
| `backend-site/交接说明.md` | 22,394 | `d226d6613f48343a867e2b5961b3290c3bd8238f3941eeca36b1efc5dd01ac48` |
|
||||
| `backend-site/回执-Claude.md` | 37,690 | `de1648832fe8bcd004c32ed538d4a90c6c29a0d72b8c70f448fdbe5332d8b5d9` |
|
||||
| `backend-tools/chk_worker.ps1` | 486 | `939a42cafa0954347f28d69e75b8af407ed1dab870cc3956fa8b7c5eb55e372f` |
|
||||
| `backend-tools/deploy.py` | 5,694 | `bf2cf47e715a3663faba5f1125ca9dee57596fd59664e2898515985924a0cc8c` |
|
||||
| `backend-tools/install_worker.ps1` | 8,902 | `95c339f2a69359fd1c980fb649217bb18371d9ba0b06eadce049b58537c11c1e` |
|
||||
| `backend-tools/local.html` | 32,184 | `7c31ed3419946b2ab10065a8b9007a5a18c57aba1a1eaa645856af7be46181b2` |
|
||||
| `backend-tools/make_order.py` | 28,388 | `e8e2ebb473501a0b914b9c2941d9e8505e9b92f0880190cf7f588d5fe27f233e` |
|
||||
| `backend-tools/open_local.bat` | 81 | `cf91a0f9bbf18db6b082874131aacb8bc04924bf68d355481a9445b26c46ab30` |
|
||||
| `backend-tools/pack_archive.bat` | 86 | `e2c6683d0b353ae8f68d9f9c0430c486aa733c57c6d2f4e7802bdd5e53783c00` |
|
||||
| `backend-tools/pack_archive.ps1` | 2,467 | `9fa2956e1d3718876fea3ad2b5576fab94087a0b73d00f43c5b443c821e1c06a` |
|
||||
| `backend-tools/run_admin.bat` | 417 | `49bab3f66e3f1419f2aab4e8d1835a5bc2f64395d6575605ec000d78c635c1c2` |
|
||||
| `backend-tools/run_panel.bat` | 911 | `c34eb6fb6d4808026c5432727de59e726632eadf2da49ee581477938c0194b0a` |
|
||||
| `backend-tools/run_worker.bat` | 176 | `3148827f6bd6967a9fb93f0ec9ba98e85cf8a26ac5160a6e6bab6369b2a3792a` |
|
||||
| `backend-tools/show_log.bat` | 422 | `fde479d7e8383863a3054b44d267d568a7c9c48df98a59175e03810e51156202` |
|
||||
| `backend-tools/skincheck.js` | 13,011 | `dc9c65ac8b8551aaa42ca7399517bb1d6c28956c4c80997132f16862e1239b8d` |
|
||||
| `backend-tools/stop_admin.bat` | 281 | `9b38682234f2e07b58c478c939f4f1d58cefe9624b13d0af2656d5522fd5509d` |
|
||||
| `backend-tools/stop_worker.bat` | 332 | `f7c8ab10d1d03d7a75c2fcb3343bec0c6d52409ef5cc6dd68c0f9e342e0077b4` |
|
||||
| `backend-tools/ys_admin.py` | 74,901 | `69f7938cb7f4fb96ec16fecb2272b1d1b6688dafbc28a4d72dc7b1ea53853f35` |
|
||||
| `backend-tools/ys_local.py` | 18,243 | `ea0b3208ec34ba4817b4513feb64d47eb7746cb5d1536191f295eb830107d15d` |
|
||||
| `backend-tools/ys_worker.py` | 30,465 | `ab6cdff13ce16ed15363c28cf016628b378a1ec255d2b8eeb62566cf38631eb9` |
|
||||
| `backend-tools/交接说明.md` | 15,276 | `5468d47b9f51bb6cca6172db6a61bed209a181814ac662093345d02445305dea` |
|
||||
| `backend-tools/回执-Claude.md` | 11,578 | `d1151810199f0dc585872027870666963e528f7027f12ce146334c5f36f761e4` |
|
||||
| `deploy/nginx-片段.md` | 5,696 | `7ec0cc36e69d62025b240312bb604cb088c77a0a40337623e01f9bc0e5dbdca7` |
|
||||
| `他应该知道的.md` | 6,988 | `177f08cb455bf5cf4b299abda5b227ff530c1da634c69f81c8ca7498ccc00cbe` |
|
||||
| `回执模板.md` | 5,049 | `0e38a6c19dff7b55767b8998d294b0252aa6024053dad0c63956ddd58b56a07a` |
|
||||
| `模板/1站立正反.blend` | 16,486,783 | `985dc61aeaa6eaaf5dc87ccbba6dfd4e1c5eb95468f7d0a9610d47aff14cb9dc` |
|
||||
| `模板/4海边自拍.blend` | 18,101,431 | `629df363d00e73e18820bddb6b7b92d7dbdd55d0f5c98de5378c76a48b705183` |
|
||||
| `模板/5不看爆炸.blend` | 11,849,599 | `3bb67516632e206c89fe44e2cf04667f5e34e1eab70e395c00830555e033e223` |
|
||||
| `模板/说明.md` | 2,775 | `491fa0587a9ff662a8e8893d0657eb412d87af8161de19abeba993e5a8ff4675` |
|
||||
|
||||
> 用途:对方收到后可以逐文件核哈希,确认传输没损坏 / 没被改动。
|
||||
@@ -0,0 +1,119 @@
|
||||
# 他应该知道的(背景须知 · 请先读这份再看代码)
|
||||
|
||||
> 你手上的是一份**脱敏过的真实生产代码**。光看代码有很多东西推不出来 ——
|
||||
> 这门生意怎么转、机器什么条件、哪些能动能不能动、哪些数据碰不得。这份补齐。
|
||||
> **看完这份再看 `README.md`,然后挑一份交接说明进代码。**
|
||||
|
||||
---
|
||||
|
||||
## 一、这门生意是什么
|
||||
|
||||
一个**个人的自助渲染小店**:卖**我的世界(Minecraft)角色的场景渲染图**。
|
||||
|
||||
```
|
||||
买家(闲鱼 / B站工房 / 爱发电)下单
|
||||
→ 自己上网页:挑模板 → 传自己的皮肤图 → 填卡密 → 提交
|
||||
→ 服务器登记排队
|
||||
→ 店主家里那台电脑(渲染机)自动领单、用 Blender 出图、回传
|
||||
→ 买家回来下载(标准压缩版 + 无压缩版,每张两个文件)
|
||||
```
|
||||
|
||||
**单价很低**(一张几块钱),**单量也不大**(一天几单到几十单)。
|
||||
所以整套系统的设计目标**不是吞吐,是"不用人盯着"** —— 店主白天还有别的事,
|
||||
不能为了接一单就守在电脑前。
|
||||
|
||||
**这就是为什么代码里到处是"无人值守"的痕迹**:队列、离线提示、自动发货、
|
||||
"呼叫店主"、过期自动清理。**评这块的时候请拿这个目标当尺子。**
|
||||
|
||||
---
|
||||
|
||||
## 二、这台机器什么条件(很多设计是它逼出来的)
|
||||
|
||||
| 约束 | 逼出来的做法 |
|
||||
|---|---|
|
||||
| 服务器**内存很小**(1G 多) | 不用框架、纯标准库;zip **先落临时文件再边读边发**(不能整块读进内存);用 cgroup 卡住进程内存上限 |
|
||||
| 服务器**不允许跑重活**(视频转码会把整机拖死) | 渲染全部在**店主家里那台电脑**上做,服务器只做登记/排队/转发 |
|
||||
| 家里那台**没有公网入口** | 它**只做出站**:自己定时来服务器领单。**服务器从不主动连它** |
|
||||
| 家里那台是**一台电脑**(还要玩游戏/干活) | 渲染**严格串行**,任何时刻只允许一个 Blender 在跑 |
|
||||
| 家用上传带宽一般 | 成品**一张一次**回传(也顺便避开请求体上限);打包下载走流式 |
|
||||
|
||||
⚠️ **"小机器 + 别拖死它"是硬前提**。如果你觉得我们某处写得太抠,很可能是这个前提逼的;
|
||||
反过来,**如果你发现某处会把机器拖死,那是最值得报的问题**。
|
||||
|
||||
---
|
||||
|
||||
## 三、边界(哪些是公开的、哪些碰不得)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **公开** | 门户首页、画展、模板缩略图(给买家看样图用的) |
|
||||
| **私有** | 下单页、订单页、所有接口、管理后台、本机工具 —— **"私有网站,请勿外传"** |
|
||||
| **绝对碰不得** | **买家的皮肤图和成品图、订单数据、卡密**。那是**第三方(买家)的个人数据**,不是店主的 |
|
||||
| **不要外传** | 这份代码本身(含片段、截图)。你要讨论就脱敏着讨论 |
|
||||
|
||||
**关于买家数据再多说一句**:买家的皮肤是**别人的作品**,成品里也带着他的皮肤。
|
||||
我们这边只做"渲染服务",**不对内容做合规担保**(服务条款里写明了)。
|
||||
**你如果要写测试,请用你自己画的假皮肤,别拿真实订单里的图。**
|
||||
|
||||
---
|
||||
|
||||
## 四、术语表(代码里到处是这些词)
|
||||
|
||||
| 词 | 意思 |
|
||||
|---|---|
|
||||
| **卡密 / 兑换码** | 买家凭它下单的凭证。**一枚码默认 = 一张图**,也可以设成"固定 N 张 / 不限张数 / 锁定模板" |
|
||||
| **单号** | 订单编号(短、大写字母数字) |
|
||||
| **取件码** | 订单链接里的 `?t=` 那一串。**它本身就是凭证**(所以链接不能外流、页面不许被搜索引擎收录) |
|
||||
| **模板** | Blender 工程(场景);买家的皮肤贴到模板上的角色模型上渲出来 |
|
||||
| **皮肤** | 买家的 MC 角色图(正方形 PNG,64 的整倍数) |
|
||||
| **臂型** | 角色是粗臂还是细臂(由皮肤决定,影响模型) |
|
||||
| **收货闸** | 买家点了"确认收货"才放**原图**;没点只能看 512 宽的水印预览 |
|
||||
| **直发单** | 不走"网页下单→付款→激活",后台直接推进队列的单 |
|
||||
| **福利券** | 免费码批次,放在福利页让买家自取(每设备+每网络限领一张) |
|
||||
| **渲染机** | 店主家里那台 Windows 电脑上跑的后台程序 |
|
||||
| **解冻 / 核销** | 卡密的终态(成品开放下载满 72 小时后)。**注意:激活 ≠ 核销** |
|
||||
|
||||
---
|
||||
|
||||
## 五、这份代码是脱敏过的,**不能直接跑**
|
||||
|
||||
所有指向真实环境的值都换成了占位(域名 / 端口 / 路径 / IP / 账户名)。
|
||||
**代码里本来就没有硬编码凭据**(令牌走文件与环境变量),所以这一项是干净的。
|
||||
|
||||
**你要真跑一遍看效果,用 `模板/` 里那三个 Blender 工程** —— 那三个能直接在 Blender 里打开渲染。
|
||||
|
||||
---
|
||||
|
||||
## 六、谁在维护 / 上一批交付了什么
|
||||
|
||||
- **店主**:做模板、出方案、拍板。
|
||||
- **苏达**:网站运维与技术提供(这台服务器、这套系统、这份文档都是它整理的)。
|
||||
- **你**:这次被请来看**后端**。
|
||||
|
||||
上一批交付给你的是**前端**(`portal/` 门户 + `order/` 下单页,视觉重设计那批),
|
||||
在同一个仓库里。**这次是后端和本地工具,两边是靠接口对齐的**,所以:
|
||||
|
||||
> ⚠️ **你改任何东西,只要动到"接口路径 / 请求响应字段 / 数据格式"这三样,
|
||||
> 必须单独标出来。** 这套系统是**两台机器上各跑一份代码**(服务器一份、店里电脑一份),
|
||||
> 两边不同步会**静默出不来图** —— 不报错、就是没图,这种最难查。
|
||||
|
||||
---
|
||||
|
||||
## 七、我们这边的几条纪律(不是给你立的,是让你理解我们为什么这么做)
|
||||
|
||||
1. **出站必脱敏**:任何离开这台机器的文字,先过机检 + 一个独立的第二双眼睛。
|
||||
(这次那份包就是这么出来的,**而且独立复查真抓出了 3 处漏网 + 2 处缺件**。)
|
||||
2. **不替对方做决定**:涉及别人的钱、别人的数据、别人的账号,一律问过本人再做。
|
||||
3. **宁可响亮地失败,不要静默成功**:出错了要看得见,不要"看着正常但其实没生效"。
|
||||
4. **改动要说清代价**:不只是"能改",还要说"改起来多大、会不会影响别处"。
|
||||
|
||||
---
|
||||
|
||||
## 八、你可能也想知道(我们主动交代)
|
||||
|
||||
- **这套系统踩过不少坑**,坑都写在两份交接文档的《我们的思路与方法》里了 ——
|
||||
**那节比代码更值得看**,因为坑是"不报错但坏掉"的那一类。
|
||||
- **代码里大量注释带了日期和决定人**(例如「某日:为什么要这么改」)。
|
||||
那是我们的决定留痕习惯,**不是为了甩锅**,是怕以后有人不知道为什么这么写。
|
||||
- **有几处"看起来多余"的防护**(比如订单不存在和口令错返回同一个 404),
|
||||
都是被真实压力逼出来的,不是过度设计 —— 但也**欢迎你说"这处没必要"**。
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
# 回执模板 · 直接照着填就行
|
||||
|
||||
> 你**不用另起格式**,把下面每节填掉、删掉提示语即可。
|
||||
> 文件名建议 `回执-<你的名字>.md`,放在仓库根目录。
|
||||
> **填不满不要紧,写"没看/没测/没意见"比空着好** —— 空着我们不知道是漏了还是没问题。
|
||||
|
||||
---
|
||||
|
||||
# 回执 · <你的名字> · <日期>
|
||||
|
||||
## 0. 一句话总结
|
||||
|
||||
<这套代码整体你怎么看?哪里最值得先修?>
|
||||
|
||||
---
|
||||
|
||||
## 1. 问题分析
|
||||
|
||||
> 请**分轻重**:会丢钱 / 丢数据 / 能被别人利用的排前面,风格问题排后面。
|
||||
> 尽量**指到具体位置**,并说清**什么条件下会踩到**(什么输入、什么并发时序、什么状态组合)。
|
||||
|
||||
| # | 严重度 | 位置(文件 : 函数 : 行) | 问题是什么 | 触发条件 | 影响 |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | 🔴高 / 🟡中 / 🟢低 | | | | |
|
||||
| 2 | | | | | |
|
||||
| 3 | | | | | |
|
||||
|
||||
<如果某条你自己也拿不准,就写"我怀疑但没验证" —— 那也很有用。>
|
||||
|
||||
---
|
||||
|
||||
## 2. 改正意见
|
||||
|
||||
> 每条说清**怎么改** + **代价**(改起来多大、会不会动到别处、要不要停机)。
|
||||
> 如果某处你觉得**整体就该换个做法**,直接说,不用迁就现在的结构。
|
||||
|
||||
| 对应 # | 建议改法 | 代价 / 风险 | 优先级 |
|
||||
|---|---|---|---|
|
||||
| 1 | | | |
|
||||
| 2 | | | |
|
||||
|
||||
---
|
||||
|
||||
## 3. 你改了什么(**改了就必须填**)
|
||||
|
||||
> 每条抄一份下面这个小块。**接口路径 / 请求响应字段 / 数据格式**这三样
|
||||
> **动了必须单独标出来** —— 这套系统是两台机器上各跑一份代码,不同步会**静默出不来图**。
|
||||
|
||||
### 改动 1
|
||||
|
||||
```
|
||||
文件 / 函数:
|
||||
为什么改:
|
||||
改成什么(一句话):
|
||||
⚠️ 有没有动:接口路径 [ 是 / 否 ] 请求响应字段 [ 是 / 否 ] 数据格式 [ 是 / 否 ]
|
||||
若"是",具体动了什么:
|
||||
怎么验证的(跑了什么、看到什么):
|
||||
有没有引入新的依赖:
|
||||
```
|
||||
|
||||
### 改动 2
|
||||
|
||||
```
|
||||
(同上)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 我们这边拿不准的,请你表态(逐条答,哪怕一句"现在这样够用"也行)
|
||||
|
||||
**Q1. 支付回调"不验签、改成拿开放接口反查"这个取舍,你认同吗?**
|
||||
我们手头没有对方的公钥,与其猜算法不如收到回调后反查这笔单是否真实存在且已付款。
|
||||
你怎么看?有没有更好的做法?
|
||||
|
||||
**Q2. 订单状态机在"部分失败"时怎么收口?**
|
||||
比如一单要出 3 张,第 2 张渲染失败。我们现在靠渲染机**显式发一个"收尾"信号**才判完成,
|
||||
否则订单会永远停在"渲染中"、被反复重渲。你觉得这个收口方式够不够?
|
||||
|
||||
**Q3. "改完不生效"这类问题,除了"先杀旧进程再起新的",有没有更稳的机制?**
|
||||
|
||||
**Q4. 单机多单:现在渲染是严格串行。** 如果要在同一台机器上支持多单同时渲染,
|
||||
你会怎么设计才**不会把机器顶满**?(先说方案,不用实现)
|
||||
|
||||
**Q5. 技术栈:我们现在是"单文件、纯标准库、零依赖"**(路由/校验/序列化全自己写)。
|
||||
好处是小机器跑得动、零安装;代价是自己写的这些一定有漏。
|
||||
**换你,你会不会上框架?** 请直说。
|
||||
|
||||
**Q6. 前后端共用一个质检脚本**(前端负责"拦"给用户看原因,后端负责"剥"元数据块)。
|
||||
这个设计省了逻辑漂移,但**两边判定必须一致**,不一致就会"网页说能传、后端说不行"。
|
||||
你觉得值不值?还是应该只留一边?
|
||||
|
||||
---
|
||||
|
||||
## 5. 苏达(运维)另外想知道的
|
||||
|
||||
> 这几条是我个人拿不准的,不属于"必须答",但你要是顺手能指一句,我少走很多弯路。
|
||||
|
||||
- **3100 行的单文件该不该拆、怎么拆?** 拆的话你最想先拆出哪一块?
|
||||
- **卡密和订单用 JSON 文件存,而不是数据库**:并发写和"写到一半崩了"这两点,
|
||||
在你看来风险有多大?有没有低成本的加固办法?
|
||||
- **限流现在放在两个地方**(反向代理一层、应用自己一层)。这是重复还是互补?
|
||||
有没有可能一边松一边紧、互相打架?
|
||||
- **内存受限制的前提下**,你扫一眼觉得**还有哪些地方可能爆**?
|
||||
- **日志与审计**:现在留痕比较散(几个 jsonl + 文件),你觉得够不够追责?
|
||||
真要出事(比如买家投诉"我的图被别人下了"),现在这套记录能不能自证?
|
||||
- **有没有你觉得"我们完全没想到"的角度?** 什么方向都行。
|
||||
|
||||
---
|
||||
|
||||
## 6. 你没验证的部分(说明原因就行)
|
||||
|
||||
> 比如"需要真机 / 需要凭据 / 需要买家皮肤 / 时间不够"。**写出来比假装测过好。**
|
||||
|
||||
- <例:渲染链路的真实耗时我没法复现,因为没有渲染机环境>
|
||||
|
||||
---
|
||||
|
||||
## 7. 你还需要什么材料
|
||||
|
||||
> 如果你觉得"要是有 XX 我就能判断得更准",列出来,我们补。
|
||||
|
||||
- <例:一份真实的订单 meta.json 样例(脱敏)>
|
||||
|
||||
---
|
||||
|
||||
*(感谢。你写的每一条我们都会看,也会回你"采纳 / 不采纳 + 为什么"。)*
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,50 @@
|
||||
# 三个 Blender 模板工程(给你跑测试用)
|
||||
|
||||
> 渲染 = **模板工程** + 买家的皮肤贴图。要真跑一遍看效果,你需要模板,
|
||||
> 所以店主挑了三个给你。**名字前面的数字就是模板编号**,代码里的 `TEMPLATES` 表靠它对应。
|
||||
|
||||
| 文件 | 编号 | 为什么给你这个 |
|
||||
|---|---|---|
|
||||
| `1站立正反.blend` | 1 | **最基础**:站立、正反两面。**先用它把链路跑通** |
|
||||
| `4海边自拍.blend` | 4 | **场景类的**(带环境),测"场景重"的情况 |
|
||||
| `5不看爆炸.blend` | 5 | **另一个场景**(爆炸/动感类),测"跟站立那个不一样的行为" |
|
||||
|
||||
**渲染环境**:Blender **4.x**,命令行后台模式:
|
||||
```
|
||||
blender -b --factory-startup --python make_order.py -- --skin <皮肤.png> --num <序号> --out <输出目录> --res 1000
|
||||
```
|
||||
完整参数看 `backend-tools/make_order.py` 顶部的用法说明。
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 这三个文件也**脱敏过**,说明一下动了什么
|
||||
|
||||
Blender 会把**绝对路径**写进工程文件里,所以直接给会把店主的机器信息一起带出去。
|
||||
我们做了**等长替换**(`.blend` 靠长度前缀存字符串,**长度一变文件就废**,
|
||||
所以只能等长换,不能删不能加):
|
||||
|
||||
| 原本 | 换成 | 处数 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `C:\Users\<账户名>` | `C:\Users\user0` | 1 / 6983 / 0 | 抹掉 Windows 账户名 |
|
||||
| `<盘符>:\<习惯用的工程目录>` | `<盘符>:\assets0` | 136 / 14 / 12 | 抹掉习惯用的工程盘路径 |
|
||||
|
||||
(`4海边自拍` 那个数字大,是因为它引用了一批 Blender 插件的资源清单,每一条都带完整路径。)
|
||||
|
||||
**已核对**:
|
||||
- 替换后**文件字节数一个没变**(`1站立正反` 16,486,783 / `4海边自拍` 18,101,431 / `5不看爆炸` 11,849,599)—— 结构没被破坏
|
||||
- 里面**没有**中文目录名的长路径(也就是说不会泄露工程目录的命名)
|
||||
- 里面**没有**邮箱、域名、密钥
|
||||
|
||||
**请你帮我们确认一件事**:这三个工程在你那边**能正常打开并且能渲出图**吗?
|
||||
(我们改的是路径字符串,理论上不影响渲染,但只有你真跑一遍才算数 ——
|
||||
如果打不开或渲出来是灰的,说明我们动坏了,请立刻告诉我们,我们给没动过的版本。)
|
||||
|
||||
---
|
||||
|
||||
## 用它们做什么
|
||||
|
||||
1. **跑通**:用 `1站立正反` 走一遍完整链路(皮肤 → 渲染 → 出图,标准压缩 + 无压缩两张)。
|
||||
2. **测场景**:用 `4海边自拍` 看有没有跟 `1站立正反` 不一样的行为。
|
||||
3. **测场景差异**:用 `5不看爆炸`(动感场景),看有没有跟 `1站立正反` 不一样的行为。
|
||||
|
||||
跑的过程中如果发现**代码**的问题,按那份交接文档最后两节的要求写回执就行。
|
||||
+365
@@ -0,0 +1,365 @@
|
||||
# 收款流程重构:从「半自动」到全自助
|
||||
|
||||
> 金钻工坊 · 自助模板渲染 · 设计文档
|
||||
> 版本 v1 · 2026-10-07 · 状态:设计稿(正式站代码未改动) · 范围:网页下单的付款与履约
|
||||
> 在线版(页面,内容相同):https://claude.ai/artifact/ErKjgvjU9fBipacGpuURuQ
|
||||
|
||||
## 目录
|
||||
|
||||
- [00 概要与决策](#00-概要与决策)
|
||||
- [01 总体架构](#01-总体架构)
|
||||
- [02 ① 支付渠道抽象层](#02--支付渠道抽象层)
|
||||
- [03 ② 爱发电主通道:全自动流程](#03--爱发电主通道全自动流程)
|
||||
- [04 ③ 当面付辅助通道](#04--当面付辅助通道)
|
||||
- [05 ④ 订单状态机](#05--订单状态机)
|
||||
- [06 ⑤ 对账与超时关单](#06--对账与超时关单)
|
||||
- [07 ⑥ 异常与人工兜底](#07--异常与人工兜底)
|
||||
- [08 付款区交互](#08-付款区交互)
|
||||
- [09 迁移与删除项](#09-迁移与删除项)
|
||||
- [10 分阶段实施](#10-分阶段实施)
|
||||
- [11 待金钻确认](#11-待金钻确认)
|
||||
- [附 原型(测试环境)](#附-原型测试环境)
|
||||
|
||||
---
|
||||
|
||||
## 00 概要与决策
|
||||
|
||||
**目标**:买家下单、付款、开始渲染,全程不需要金钻动手。人工只处理系统判断不了的异常,比如金额不对、重复付款、迟到很久的付款。
|
||||
|
||||
| 通道 | 说明 |
|
||||
|---|---|
|
||||
| **主通道 · 爱发电专链** | 合规、已开通。买家跳到爱发电付款;系统靠回调 + 主动对账自动确认到账。手续费约 6%。 |
|
||||
| **辅助通道 · 支付宝当面付** | 页面内直接显示二维码,扫码即付,到账秒级确认。手续费 0.6%。线上使用属于场景错配,有风控风险(见第 04 节)。 |
|
||||
|
||||
> **决策记录**:支付宝当面付官方定位是线下面对面收银,用在网站上可能被风控限额或关闭支付权限。金钻已知悉此风险,决定作为辅助通道使用,风险自担。设计上的应对:爱发电始终可用;当面付出现异常自动熔断、隐藏,不影响下单。
|
||||
|
||||
### 五条设计原则
|
||||
|
||||
- **到账只有一个入口。** 不管哪个渠道、回调还是对账,确认到账都调用同一个 `settle_payment()`,由它负责核对金额、去重、激活订单。
|
||||
- **先验真,再履约。** 回调内容一律不直接信:爱发电要验签并用接口精确反查;当面付要验 RSA2 签名并核对金额和应用号。
|
||||
- **天然幂等。** 同一笔渠道流水号只能入账一次;重复回调、回调和对账同时到达,都不会激活两次。
|
||||
- **回调会丢,所以要主动对账。** 后台定时查渠道,把漏掉的到账补上。
|
||||
- **订单内容和付款分开。** 订单记录买家要什么,支付单记录钱的往来。一张订单可以有多次付款尝试,比如换了渠道或二维码过期重来。
|
||||
|
||||
---
|
||||
|
||||
## 01 总体架构
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
B[买家·订单页] -->|1 提交订单| O[订单服务]
|
||||
O -->|2 选渠道 建支付单| G[渠道抽象层]
|
||||
G --> A[爱发电渠道]
|
||||
G --> Z[当面付渠道]
|
||||
A -->|专链 / 专链二维码| B
|
||||
Z -->|收款二维码| B
|
||||
A -.回调.-> N[回调入口]
|
||||
Z -.异步通知.-> N
|
||||
R[定时对账] -->|主动查单| A
|
||||
R -->|主动查单| Z
|
||||
B -->|轮询 / 付好了没反应| P[查单接口]
|
||||
P --> Z
|
||||
P --> A
|
||||
N --> S{{settle_payment 统一到账}}
|
||||
R --> S
|
||||
P --> S
|
||||
S -->|金额够·首次| ACT[激活订单 进渲染队列]
|
||||
S -->|金额不足·重复·迟到太久| TODO[后台待办 人工]
|
||||
```
|
||||
|
||||
下单内容(皮肤、模板、分辨率)、渲染机、确认收货、卡密下单这条路都**不变**。卡密本身就是已付款凭证,它的订单直接进入 `waiting`,不经过本设计的付款环节。
|
||||
|
||||
---
|
||||
|
||||
## 02 ① 支付渠道抽象层
|
||||
|
||||
每个渠道是一个独立模块,实现同一组接口。下单流程、状态机、对账任务只认这组接口,不关心具体是哪个渠道。以后加微信、个体户的官方网站支付、或者聚合支付,只需要新写一个模块。
|
||||
|
||||
| 接口 | 作用 | 爱发电实现 | 当面付实现 |
|
||||
|---|---|---|---|
|
||||
| `create(order, pay)` | 生成付款方式 | 拼专链:`order/create?user_id&custom_price&custom_order_id=pay_id&remark`,返回跳转链接 + 同一链接的二维码 | 调 `alipay.trade.precreate`,带 `out_trade_no=pay_id`、金额、`time_expire`、`notify_url`,返回 `qr_code` |
|
||||
| `verify_notify(req)` | 把回调变成「可信的到账事实」或拒绝 | 验 `data.sign`(官方公钥)→ 用 `out_trade_no` 调 `query-order` 精确反查 → 以反查结果为准 | 验 RSA2 签名(支付宝公钥)→ 核对 `app_id`、`out_trade_no` 存在、`trade_status` |
|
||||
| `query(pay)` | 主动查一笔支付单 | 扫最近的订单页,按 `custom_order_id` 找 | `alipay.trade.query` |
|
||||
| `close(pay)` | 关闭过期支付单 | 无法远程关闭,只在本地标记过期(迟到付款靠对账收回) | `alipay.trade.close`(未扫码的单可能返回「交易不存在」,视为已关) |
|
||||
| `refund(pay, amt)` | 退款(只在后台人工触发) | 不支持接口退款,提示去爱发电后台操作 | `alipay.trade.refund` |
|
||||
| `health()` | 渠道是否可用 | 配置齐全即可用 | 配置齐全且未熔断 |
|
||||
|
||||
### 统一到账入口 settle_payment()
|
||||
|
||||
```text
|
||||
settle_payment(channel, pay_id, trade_no, amount_paid, source)
|
||||
1. 在一个数据库事务里锁住这条支付单
|
||||
2. trade_no 已入账过 → 直接返回「已处理」(幂等)
|
||||
3. 支付单状态是 paid → 记为「重复付款」,进待办,返回
|
||||
4. amount_paid < amount_due → 支付单记 mismatch,进待办「金额不足」,返回
|
||||
5. 支付单记 paid(写 trade_no、实付、时间、来源)
|
||||
6. 看订单状态:
|
||||
unpaid → 激活:订单转 waiting,进渲染队列
|
||||
closed 且在宽限期内 → 恢复并激活(内容还在)
|
||||
closed 超过宽限期 → 进待办「迟到付款」,人工补单或退款
|
||||
已经是 waiting 之后 → 进待办「重复付款」(另一渠道已付过)
|
||||
7. 其他同一订单的未付支付单 → 关闭(当面付调 close)
|
||||
```
|
||||
|
||||
`source` 只用于留痕:`notify` / `reconcile` / `poll` / `buyer_check` / `admin`。
|
||||
|
||||
### 新增数据
|
||||
|
||||
| 表 | 字段 | 说明 |
|
||||
|---|---|---|
|
||||
| `payments` 支付单 | `pay_id`(主键,如 `YS7ZBZW6P1`)、`oid`、`channel`、`amount_due`、`state`、`created_at`、`expire_at`、`trade_no`(唯一)、`amount_paid`、`paid_at`、`last_query_at`、`note` | 一张订单可以有多条;`trade_no` 加唯一约束,是幂等的最后防线 |
|
||||
| `pay_events` 流水 | 时间、渠道、类型(notify/query/close/refund)、关联 pay_id、结果、原文摘要(截断 4KB) | 只追加不修改,用于对账和申诉 |
|
||||
| `pay_todo` 待办 | 类型、pay_id / 渠道流水号、金额、说明、处理人、处理结果 | 开单后台的「支付待办」列表 |
|
||||
|
||||
密钥(爱发电 token 与公钥、支付宝应用私钥与支付宝公钥)只放服务器配置文件,权限 600,不进仓库、不进前端。
|
||||
|
||||
---
|
||||
|
||||
## 03 ② 爱发电主通道:全自动流程
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant B as 买家
|
||||
participant S as 我方服务器
|
||||
participant F as 爱发电
|
||||
B->>S: 选「爱发电」付款
|
||||
S->>S: 建支付单 pay_id,应付金额锁定
|
||||
S-->>B: 专链(手机直接跳;电脑显示专链二维码)
|
||||
B->>F: 打开专链付款(custom_order_id = pay_id)
|
||||
F-->>S: Webhook 推送(可能延迟或丢失)
|
||||
S->>S: 验签 data.sign
|
||||
S->>F: query-order 按 out_trade_no 精确反查
|
||||
F-->>S: 订单详情(status、金额、custom_order_id)
|
||||
S->>S: settle_payment → 激活订单
|
||||
S-->>F: 回应 ec=200
|
||||
loop 页面可见时每 3 秒
|
||||
B->>S: 查订单状态
|
||||
end
|
||||
S-->>B: 已到账 · 排队中
|
||||
```
|
||||
|
||||
1. **生成专链。** 链接带 `custom_price`(本单应付)、`custom_order_id`(支付单号 pay_id)、`remark`(订单号,给买家和金钻看)。需要一个「自选金额」方案承载 `custom_price`。
|
||||
2. **展示。** 手机端直接跳转;电脑端显示专链二维码(本地生成,不用第三方二维码服务),手机扫码打开爱发电付款。买家回到订单页时页面开始轮询。
|
||||
3. **回调先落流水、马上回 200。** 收到推送后先写 `pay_events`,然后返回 `{"ec":200,"em":""}`。后续处理失败不影响这次应答,由对账补救。
|
||||
4. **验签。** 用爱发电官方公钥验 `data.sign`(2025 年 7 月起提供;待签字符串为 `out_trade_no + user_id + plan_id + total_amount`,SHA256,Base64)。验签失败直接丢弃,记流水。暂时拿不到公钥时,跳过这一步,以下一步为准。
|
||||
5. **精确反查。** 调用 `query-order` 并带 `out_trade_no`(接口支持按订单号查,不再翻页找)。之后**只用反查结果**里的状态、金额、`custom_order_id`。
|
||||
6. **认单。** `status == 2` 且 `custom_order_id` 对应得上本地支付单,调用 `settle_payment()`。
|
||||
没有 `custom_order_id`(买家直接在爱发电店铺下单,或用了旧链接),按现有逻辑当作购买卡密:按实付金额发码,通过爱发电自动回复给买家。**不再**用留言或金额唯一匹配去猜是哪张网页单。
|
||||
7. **金额闸门。** 买家可以在爱发电页面手动改金额,所以实付必须 ≥ 应付,否则支付单记为 mismatch,进待办。
|
||||
|
||||
---
|
||||
|
||||
## 04 ③ 当面付辅助通道
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant B as 买家
|
||||
participant S as 我方服务器
|
||||
participant A as 支付宝
|
||||
B->>S: 选「支付宝扫码」
|
||||
S->>S: 熔断检查 · 金额上限检查 · 建支付单
|
||||
S->>A: alipay.trade.precreate(out_trade_no=pay_id,time_expire=+15分钟)
|
||||
A-->>S: qr_code
|
||||
S-->>B: 页面显示二维码 + 15 分钟倒计时
|
||||
B->>A: 支付宝扫码付款
|
||||
par 异步通知
|
||||
A-->>S: notify(RSA2 签名)
|
||||
S->>S: 验签 → settle_payment → 回 "success"
|
||||
and 页面轮询
|
||||
loop 每 3 秒
|
||||
B->>S: 查支付单
|
||||
S->>A: trade.query(每单最多 5 秒查一次)
|
||||
end
|
||||
end
|
||||
S-->>B: 已到账 · 排队中
|
||||
```
|
||||
|
||||
1. **预下单。** 先检查熔断状态和金额上限(个人基础版单笔 ≤1000 元,建议再保守一点设 500 元,超过的只给爱发电)。调 `alipay.trade.precreate`,商品名统一写成中性文案,如「金钻工坊 渲染服务」,加订单号。
|
||||
2. **出码。** `qr_code` 在前端本地画成二维码,配 15 分钟倒计时;过期后显示「重新生成」,生成新支付单并关闭旧的。手机端加一个「打开支付宝付款」按钮,跳到支付宝扫这个码(不保证所有浏览器都能拉起,按钮仅作方便)。
|
||||
3. **异步通知。** 验 RSA2 签名 → 核对 `app_id`、`out_trade_no` 是本地支付单、`total_amount` 等于应付 → `trade_status` 为 `TRADE_SUCCESS` 或 `TRADE_FINISHED` 时调 `settle_payment()` → 回纯文本 `success`。验签失败回其他内容,支付宝会重试。
|
||||
4. **轮询查单。** 页面可见时每 3 秒问一次服务器;服务器对同一笔支付单最多每 5 秒调一次 `trade.query`,查到成功同样走 `settle_payment()`。页面切到后台就停轮询,回来立刻查一次。
|
||||
5. **过期关单。** 到期后先最后查一次,确认没付再 `trade.close`,本地记 closed。
|
||||
|
||||
### 线上使用的风控注意事项
|
||||
|
||||
- **场景错配。** 当面付是线下收银产品,签约时也按线下门店审核。线上使用可能被判场景不符,表现为:交易被拦、限额下调、要求补充材料,严重的关闭当面付权限,甚至影响支付宝账户。
|
||||
- **额度。** 无营业执照的基础版单笔 ≤1000 元、单日 ≤5 万元。
|
||||
- **资金。** 被风控时可能冻结一段时间的收款,要有心理准备,不能把它当唯一收款方式。
|
||||
|
||||
### 降低风险的做法
|
||||
|
||||
- **爱发电永远在。** 付款区默认推荐爱发电,当面付作为「也可以用支付宝扫码」的备选。
|
||||
- **自动熔断。** 预下单或查单连续失败 3 次,或返回风控、权限类错误码(如 `ACQ.ACCESS_FORBIDDEN`、`ACQ.SELLER_BEEN_BLOCKED` 一类),自动关闭当面付 6 小时,页面隐藏这个选项并通知金钻;之后由后台手动恢复。
|
||||
- **控制节奏。** 同一买家(同一 IP 或同一订单)10 分钟内最多生成 3 个二维码;全站同时未付款的当面付二维码不超过 20 个,超过就只给爱发电。
|
||||
- **控制金额。** 设单笔上限(建议 500 元),大单只走爱发电。
|
||||
- **交易信息真实一致。** 商品名、金额、订单号都是真实的,不伪装成线下消费;不使用营销类字眼。
|
||||
- **留证。** 每笔交易保留订单号、皮肤、成品和小票,被要求补材料或申诉时拿得出交易真实性证明。
|
||||
- **定期提现。** 当面付的钱实时进入支付宝余额,定期转出,降低冻结时的损失。
|
||||
|
||||
---
|
||||
|
||||
## 05 ④ 订单状态机
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> unpaid: 网页下单提交
|
||||
[*] --> waiting: 卡密下单提交
|
||||
unpaid --> waiting: 到账(settle_payment)
|
||||
unpaid --> closed: 超过 24 小时未付
|
||||
unpaid --> void: 后台注销
|
||||
closed --> waiting: 宽限期内迟到付款
|
||||
waiting --> working: 渲染机领单
|
||||
working --> done: 全部出图
|
||||
working --> failed: 渲染失败
|
||||
working --> waiting: 渲染机掉线回收
|
||||
failed --> waiting: 免费重渲 / 后台重试
|
||||
done --> waiting: 免费重渲(确认收货前)
|
||||
done --> [*]: 开放下载满 72 小时,卡密核销
|
||||
```
|
||||
|
||||
| 状态 | 含义 | 买家看到 | 变化 |
|
||||
|---|---|---|---|
|
||||
| `unpaid` | 已提交,等付款 | 付款区:渠道选择 / 二维码 / 倒计时 | 不变 |
|
||||
| `closed` | 超时未付,自动关闭;内容保留到清理期 | 「订单已关闭,重新下单」;宽限期内付款仍会自动恢复 | **新增** |
|
||||
| `void` | 后台人工注销 | 「订单已注销」 | 不变 |
|
||||
| `waiting` | 已付款(或卡密),排队 | 排队位置 | 不变 |
|
||||
| `working` / `done` / `failed` | 渲染流水线 | 同现在 | 不变 |
|
||||
| `paid` | 旧:买家申报「已付」等人工确认 | — | **删除**,改为订单上的标记 `buyer_claim_at`,只用于触发立即对账和提醒金钻 |
|
||||
|
||||
确认收货(`accepted`)、直发(`direct`)、免费重渲已用(`redo_used`)仍然是订单上的标记,不是状态。
|
||||
|
||||
### 支付单状态
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> created: 建单
|
||||
created --> paid: 到账且金额够
|
||||
created --> mismatch: 到账但金额不足
|
||||
created --> closed: 过期 / 订单已在别的渠道付过
|
||||
closed --> paid: 迟到付款(对账发现)
|
||||
paid --> refunded: 后台退款
|
||||
mismatch --> paid: 人工确认补齐
|
||||
mismatch --> refunded: 人工退款
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 06 ⑤ 对账与超时关单
|
||||
|
||||
服务器内一个后台调度线程(或 systemd 定时器调用 `admin.py`),每分钟运行一轮。每个任务各自加锁,同一时间只跑一个实例。
|
||||
|
||||
| 任务 | 频率 | 做什么 |
|
||||
|---|---|---|
|
||||
| 爱发电对账 | 有未结爱发电支付单时每 60 秒 | 从第一页往后拉 `query-order`,直到早于最老的未结支付单;按 `custom_order_id` 匹配,命中就 `settle_payment(source=reconcile)` |
|
||||
| 当面付补查 | 每 60 秒 | 对创建超过 1 分钟、30 秒内没查过的未结支付单调 `trade.query` |
|
||||
| 支付单过期 | 每 60 秒 | 到期的支付单最后查一次 → 没付就 `close`,记 closed |
|
||||
| 订单超时关闭 | 每 5 分钟 | `unpaid` 超过 24 小时且没有活跃支付单 → 订单转 `closed` |
|
||||
| 迟到付款扫描 | 每 10 分钟 | 对最近 72 小时内关闭的支付单再做一次对账,抓迟到付款 |
|
||||
| 日对账 | 每天 04:00 | 前一天两个渠道的成交笔数和金额 vs 本地 paid 支付单,有差异进待办 |
|
||||
|
||||
### 时间参数(可配置)
|
||||
|
||||
| 参数 | 建议值 | 说明 |
|
||||
|---|---|---|
|
||||
| 当面付二维码有效期 | 15 分钟 | 写进 `time_expire`,到期关单 |
|
||||
| 爱发电支付单有效期 | 2 小时 | 本地标记;过期后付款仍能被对账收回 |
|
||||
| 订单待付款保留 | 24 小时 | 之后转 `closed` |
|
||||
| 迟到付款宽限 | 关闭后 72 小时 | 宽限内到账自动恢复并激活;超过进待办 |
|
||||
| 页面轮询 | 3 秒,页面可见时 | 当面付二维码页最长 15 分钟;爱发电回到页面后最长 10 分钟 |
|
||||
|
||||
---
|
||||
|
||||
## 07 ⑥ 异常与人工兜底
|
||||
|
||||
所有需要人工的情况都进开单后台的「支付待办」,带上订单号、渠道流水号、应付和实付金额,以及推荐操作。
|
||||
|
||||
| 场景 | 系统自动做 | 人工做 |
|
||||
|---|---|---|
|
||||
| 回调丢失或延迟 | 【自动】对账补上 | 无 |
|
||||
| 伪造回调 | 【自动】验签失败或反查不到,丢弃并记流水 | 无 |
|
||||
| 买家点「付好了没反应」 | 【自动】立即对账一次;仍未找到,提示稍等并显示「呼叫金钻」 | 收到呼叫后在待办里核对 |
|
||||
| 金额不足(买家改了金额) | 【自动】不激活,支付单记 mismatch,页面提示差额 | 【人工】补差价后确认,或退款 |
|
||||
| 重复付款(两个渠道都付了 / 付了两次) | 【自动】只激活一次,第二笔进待办 | 【人工】退款:当面付后台一键退;爱发电去爱发电后台退 |
|
||||
| 订单关闭后付款(宽限内) | 【自动】恢复订单并激活 | 无 |
|
||||
| 订单关闭后付款(超过宽限) | 进待办 | 【人工】内容还在就手动激活,否则退款或联系买家 |
|
||||
| 爱发电成交没有 custom_order_id | 【自动】按购买卡密处理:按实付发码 | 实付不足一张时人工处理 |
|
||||
| 当面付被风控 / 接口连续失败 | 【自动】熔断 6 小时,页面隐藏,只剩爱发电 | 【人工】查看支付宝通知,处理后在后台恢复 |
|
||||
| 日对账有差异 | 进待办,列出差异明细 | 【人工】逐笔核对 |
|
||||
|
||||
### 开单后台新增
|
||||
|
||||
- 「支付待办」列表:确认补齐、退款(当面付)、手动激活、忽略并备注。
|
||||
- 「按渠道流水号认领」:输入爱发电订单号或支付宝交易号,指定到某张订单(取代现在买家自己填爱发电订单号的旧入口)。
|
||||
- 渠道开关:当面付熔断状态、手动关闭 / 恢复。
|
||||
- 保留现有「手动激活」,作为最后手段。
|
||||
|
||||
---
|
||||
|
||||
## 08 付款区交互
|
||||
|
||||
1. 提交订单后,付款区显示应付金额,以及两个选项:「爱发电付款(推荐)」和「支付宝扫码」。当面付熔断或金额超限时,只显示爱发电。
|
||||
2. 选爱发电:手机直接跳转;电脑显示专链二维码,并附「在本机打开」的链接。
|
||||
3. 选支付宝:显示二维码和倒计时;过期后显示「重新生成」。
|
||||
4. 付款期间页面自动轮询,到账后直接切到「已到账 · 排队中」,不需要买家点任何按钮。
|
||||
5. 「我已经付好了」改成「付好了没反应?」:点了立即对账,找不到再给「呼叫金钻」。
|
||||
6. 订单页始终能看到订单号和取件链接;不再附送未激活的卡密。
|
||||
|
||||
---
|
||||
|
||||
## 09 迁移与删除项
|
||||
|
||||
### 迁移
|
||||
|
||||
- 上线时现存的 `unpaid` 订单:为每单补建一条爱发电支付单,`pay_id` 就用订单号本身(旧专链里的 `custom_order_id` 本来就是订单号),老链接付款照样能对上。
|
||||
- 现存的 `paid` 订单(买家申报过):全部列进待办,人工逐笔核对后激活或关闭。
|
||||
- 已有的爱发电账本(`payplatform-orders`)保留只读,作为历史对账依据。
|
||||
|
||||
### 删除
|
||||
|
||||
- 回调里的「留言含兑换码」「留言含订单号」「金额唯一匹配」三层猜测。
|
||||
- 网页单提交时生成的未激活卡密(凭证统一为订单号 + 取件码)。
|
||||
- 没有页面在用的旧接口 `/api/activate`、`/api/activate-payplatform`。
|
||||
- 订单状态 `paid`。
|
||||
|
||||
---
|
||||
|
||||
## 10 分阶段实施
|
||||
|
||||
| 阶段 | 内容 | 上线标准 |
|
||||
|---|---|---|
|
||||
| 一 · 骨架 + 爱发电全自动 | 支付单与流水表、渠道接口、`settle_payment()`、爱发电验签和精确反查、对账任务、超时关单、`closed` 状态、页面轮询、迁移脚本 | 测试覆盖:重复回调、回调丢失、伪造回调、金额不足、重复付款、迟到付款、并发到账;在测试环境用真实小额爱发电订单跑通一次 |
|
||||
| 二 · 当面付 | 当面付渠道、二维码页、异步通知、轮询查单、关单、熔断、节奏和金额限制 | 先用支付宝沙箱跑通全部用例,再用正式应用付 0.01 元验证一次后开放 |
|
||||
| 三 · 后台与清理 | 支付待办、按流水号认领、退款按钮、渠道开关、日对账报告;删除旧逻辑和旧接口 | 后台各操作都有确认步骤和操作记录 |
|
||||
|
||||
每个阶段沿用现在的上线方式:先备份,队列为空时重启;前端单独上线,可随时回滚。
|
||||
|
||||
---
|
||||
|
||||
## 11 待金钻确认
|
||||
|
||||
1. 爱发电开发者后台的签名公钥(验签用),并确认有一个「自选金额」方案可承载 `custom_price`。
|
||||
2. 支付宝开放平台当面付应用:AppID、应用私钥(服务器生成后由他上传公钥)、支付宝公钥、异步通知地址。
|
||||
3. 时间参数是否按建议值:二维码 15 分钟、订单保留 24 小时、迟到宽限 72 小时。
|
||||
4. 当面付单笔上限:建议 500 元。
|
||||
5. 付款区默认推荐哪个渠道:建议爱发电。
|
||||
6. 现存的「已申报付款」订单由谁、何时核对。
|
||||
|
||||
---
|
||||
|
||||
## 附 原型(测试环境)
|
||||
|
||||
为验证上面的流程,按本设计做了一个可运行原型。**它只是测试环境,和正式站完全隔离:**
|
||||
|
||||
- 部署在甲骨文预览机(161.33.11.66),不在正式服务器上;正式站的下单、付款代码和数据都没有改动。
|
||||
- 爱发电、支付宝的账号与密钥全部是占位符,所有付款请求都发往原型内置的模拟网关,不连真实渠道、不会产生真实交易。
|
||||
- 原型有自己独立的 SQLite 数据库,不读写正式站的订单和卡密。
|
||||
- 后续开发也只在预览机上进行,不碰生产。
|
||||
|
||||
| 项 | 位置 |
|
||||
|---|---|
|
||||
| 付款页 | http://161.33.11.66/pay-proto/ |
|
||||
| 后台 | http://161.33.11.66/pay-proto/admin(口令在预览机 `/var/lib/jz-pay-proto/admin_token`) |
|
||||
| 代码 | 仓库 `backend/pay-proto/`(说明见其中 `README.md`) |
|
||||
| 测试 | `python3 backend/pay-proto/tests/test_proto.py`,24 个场景 |
|
||||
|
||||
依据:爱发电开发者文档(Webhook 无保证送达、需幂等并配合 query-order;2025-07 起 `data.sign` 可用官方公钥验签;下单链接支持 `custom_order_id` / `custom_price` / `remark`);支付宝开放平台当面付文档(precreate / query / close / 异步通知 RSA2 验签;产品定位为线下收银)。
|
||||
@@ -0,0 +1,96 @@
|
||||
Fusion Pixel Font
|
||||
https://github.com/TakWolf/fusion-pixel-font
|
||||
|
||||
Copyright (c) 2022, TakWolf (https://takwolf.com).
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,2 @@
|
||||
/* 内容文件:由内容后台发布时生成(这是第一版:从网站原有内容导入)。别手改:下次发布会被覆盖。改内容请用内容后台。 */
|
||||
window.JZ_ORDER = {"v":1,"head":"传一张皮肤,选个模板,等一会儿就能拿到渲染图。","notice":{"on":false,"text":""},"templates":[{"k":"stand","n":"站立正反","s":"正面站立 · 干净背景","on":true},{"k":"standb","n":"站立正反(虚化)","s":"同款 + 景深虚化","on":true},{"k":"wheat","n":"麦田萤火","s":"麦田 · 暖光 · 萤火","on":true},{"k":"beach","n":"海边自拍","s":"海面 · 天光","on":true},{"k":"boom","n":"不看爆炸","s":"身后爆炸 · 不回头","on":true},{"k":"sakura","n":"飞跃樱花林","s":"樱花 · 动态","on":true},{"k":"airship","n":"空艇巡游","s":"飞空艇 · 巡航","on":true}]};
|
||||
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"v": 1,
|
||||
"head": "传一张皮肤,选个模板,等一会儿就能拿到渲染图。",
|
||||
"notice": {
|
||||
"on": false,
|
||||
"text": ""
|
||||
},
|
||||
"templates": [
|
||||
{
|
||||
"k": "stand",
|
||||
"n": "站立正反",
|
||||
"s": "正面站立 · 干净背景",
|
||||
"on": true
|
||||
},
|
||||
{
|
||||
"k": "standb",
|
||||
"n": "站立正反(虚化)",
|
||||
"s": "同款 + 景深虚化",
|
||||
"on": true
|
||||
},
|
||||
{
|
||||
"k": "wheat",
|
||||
"n": "麦田萤火",
|
||||
"s": "麦田 · 暖光 · 萤火",
|
||||
"on": true
|
||||
},
|
||||
{
|
||||
"k": "beach",
|
||||
"n": "海边自拍",
|
||||
"s": "海面 · 天光",
|
||||
"on": true
|
||||
},
|
||||
{
|
||||
"k": "boom",
|
||||
"n": "不看爆炸",
|
||||
"s": "身后爆炸 · 不回头",
|
||||
"on": true
|
||||
},
|
||||
{
|
||||
"k": "sakura",
|
||||
"n": "飞跃樱花林",
|
||||
"s": "樱花 · 动态",
|
||||
"on": true
|
||||
},
|
||||
{
|
||||
"k": "airship",
|
||||
"n": "空艇巡游",
|
||||
"s": "飞空艇 · 巡航",
|
||||
"on": true
|
||||
}
|
||||
],
|
||||
"prices": {
|
||||
"per": 6.0,
|
||||
"tiers": []
|
||||
},
|
||||
"pay": {
|
||||
"payplatform": "",
|
||||
"payplatform_uid": "",
|
||||
"qr_img": "",
|
||||
"note": ""
|
||||
}
|
||||
}
|
||||
+872
-635
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,41 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>关于 · 金钻客栈</title>
|
||||
<meta name="description" content="金钻客栈是谁做的,用了哪些开源的东西。">
|
||||
<meta name="theme-color" content="#FAFBFE">
|
||||
<meta name="theme-color" content="#0D1020" media="(max-width: 760px) and (prefers-color-scheme: dark)">
|
||||
<link rel="icon" href="assets/gem.webp" type="image/webp">
|
||||
<link rel="preload" href="fonts/OPPOSans-B.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="preload" href="fonts/fusion-pixel-12.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="stylesheet" href="assets/site.css?v=6">
|
||||
</head>
|
||||
<body data-page="about">
|
||||
<div class="jz-boot" id="jzBoot" aria-hidden="true"><div class="jz-boot-in"><canvas class="jz-boot-gem" width="168" height="168"></canvas><b class="jz-boot-name">金钻客栈</b><i class="jz-boot-bar"><i></i></i></div></div>
|
||||
<script>/* 加载动画:同一个标签页里只在第一次打开时放;系统要求「减少动效」就不放 */
|
||||
try{if(sessionStorage.getItem('jz-boot')||matchMedia('(prefers-reduced-motion: reduce)').matches){document.getElementById('jzBoot').remove()}else{document.documentElement.classList.add('booting')}}catch(e){document.getElementById('jzBoot').remove()}</script>
|
||||
<div class="orbs" aria-hidden="true"><i class="o1"></i><i class="o2"></i><i class="o3"></i><i class="o4"></i><i class="o5"></i></div>
|
||||
<header class="top"><div class="wrap top-in"><a class="brand" href="index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a><nav class="nav" aria-label="导航"><a href="index.html">首页</a><a href="gallery.html">画展</a><a href="tools.html">工具与开源</a><a href="universe.html">金钻宇宙</a><a href="links.html">平台入口</a><a href="about.html" aria-current="page">关于</a></nav><div class="desk-btn"><a class="btn-pill" href="/order/"><span class="ic" aria-hidden="true"></span>自助渲染<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></svg></a></div><a class="cms-ent" href="admin/" aria-label="内容管理" title="内容管理"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg></a></div></header>
|
||||
<main class="wrap">
|
||||
<div class="room-head"><div class="zone num" aria-hidden="true" style="--zc:#E0533D;--zc2:#E8913A">05</div><div><h1>关于</h1><p>这个站是谁做的,用了哪些开源的东西。</p></div><div class="meta"><b>v3</b></div></div>
|
||||
<div class="about-grid">
|
||||
<article class="letter crystal"><h2>名字的由来</h2><div id="aStory"></div><div class="sign"><i class="gem-img" aria-hidden="true"></i>金钻</div></article>
|
||||
<div class="credits" id="aCredits"></div>
|
||||
</div>
|
||||
<p class="note" id="aFoot" style="margin-top:22px"></p>
|
||||
</main>
|
||||
<nav class="tabbar" aria-label="导航"><a href="index.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/><path d="M10 21v-6h4v6"/></svg><span>首页</span></a><a href="gallery.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/></svg><span>画展</span></a><a class="mid" href="/order/"><i aria-hidden="true"></i><span>渲染</span></a><a href="universe.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="5"/><path d="M4.2 15.6c-1.6 2.5 4.2 2.4 9.6-.2s9-6.6 7.5-8.6c-.8-1-2.9-.9-5.4 0"/></svg><span>宇宙</span></a><button type="button" data-sheet="more" aria-expanded="false" aria-controls="more"><i class="ic-a"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3.5" y="3.5" width="7" height="7" rx="2"/><rect x="13.5" y="3.5" width="7" height="7" rx="2"/><rect x="3.5" y="13.5" width="7" height="7" rx="2"/><rect x="13.5" y="13.5" width="7" height="7" rx="2"/></svg></i><i class="ic-b"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="M6 6l12 12"/></svg></i><span class="lb-a">更多</span><span class="lb-b">收起</span></button></nav>
|
||||
<div class="sheet" id="more" hidden><div class="panel"><nav class="more-grid" aria-label="更多"><a href="tools.html" style="--zc:#4F86E8;--zc2:#2E5BD8"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg></i><span>工具与开源</span></a><a href="links.html" style="--zc:#22B573;--zc2:#3C8527"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg></i><span>平台入口</span></a><a href="about.html" aria-current="page" style="--zc:#E0533D;--zc2:#E8913A"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg></i><span>关于</span></a></nav><p class="more-qq">QQ 群:屑钻小窝 123456789</p></div></div>
|
||||
<footer class="foot-site"><div class="wrap foot-in"><a class="brand" href="index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a></div></footer>
|
||||
<script src="assets/site-info.js?v=5"></script>
|
||||
<!-- 网站内容:内容后台发布时生成 content/site.js(window.JZ_CONTENT) -->
|
||||
<script src="content/site.js"></script>
|
||||
<script>/* 预览草稿:内容后台点「预览」会带 ?preview=1 打开;只有登录了内容后台的浏览器拿得到草稿(拿不到就还是正式内容) */
|
||||
if(/[?&]preview=1(&|$)/.test(location.search)) document.write('<script src="/order/api/cms/draft.js"><\/script>');</script>
|
||||
<script src="assets/pages.js?v=5"></script>
|
||||
<script src="assets/site.js?v=5"></script>
|
||||
<script src="assets/boot.js?v=5"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,999 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN"><head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<meta name="robots" content="noindex,nofollow">
|
||||
<meta name="referrer" content="same-origin">
|
||||
<title>金钻客栈 · 内容后台</title>
|
||||
<style>
|
||||
/* 金钻客栈 · 内容后台(2026-10-05)
|
||||
网站上所有展示内容在这里改:改动先存草稿(网站上看不到)→ 预览 → 发布。每次发布留一版,能一键回滚。
|
||||
接口:/order/api/cms/*(server.py → cms.py)。样子跟网站 / 开单后台同一套:白光 + 毛玻璃卡片 + MC 方块按钮 + 像素标题。 */
|
||||
@font-face{font-family:'JZ Pixel';src:url('pixel.woff2') format('woff2');font-display:swap}
|
||||
:root{--bg:#F5F7FB;--txt:#1E2440;--txt-2:#454B6B;--txt-3:#5E6482;--dim:#7E849C;
|
||||
--line:rgba(30,36,64,.13);--line-soft:rgba(30,36,64,.08);
|
||||
--glass:linear-gradient(160deg,rgba(255,255,255,.9),rgba(255,255,255,.7));
|
||||
--panel-shadow:inset 0 1px 0 #fff,0 22px 44px -28px rgba(100,110,190,.38);
|
||||
--mc:#3C8527;--mc-hi:#5BAA3C;--mc-lo:#1D4D13;--ok-t:#2F6E1F;
|
||||
--stone:#F3F4F6;--stone-lo:#B4B7BE;--stone-edge:#9EA2AA;
|
||||
--bad:#D2483A;--bad-t:#B33A2E;--warn-t:#9A6A0C;--info-t:#2D5BB8;
|
||||
--ease:cubic-bezier(.23,1,.32,1);
|
||||
--font:system-ui,-apple-system,"PingFang SC","Microsoft YaHei","Segoe UI",sans-serif;
|
||||
--pixel:'JZ Pixel',var(--font);
|
||||
--mono:ui-monospace,Consolas,"SF Mono",Menlo,monospace;color-scheme:light}
|
||||
*{box-sizing:border-box}
|
||||
[hidden]{display:none!important}
|
||||
html{-webkit-text-size-adjust:100%}
|
||||
body{margin:0;min-height:100vh;background:var(--bg);color:var(--txt);font:14px/1.6 var(--font);-webkit-font-smoothing:antialiased}
|
||||
body::before{content:"";position:fixed;inset:0;z-index:-1;pointer-events:none;background:
|
||||
radial-gradient(40% 34% at 6% 0%,rgba(150,215,255,.30),transparent 70%),radial-gradient(36% 30% at 100% 8%,rgba(255,176,204,.22),transparent 70%),
|
||||
radial-gradient(48% 38% at 72% 100%,rgba(255,214,150,.22),transparent 70%),radial-gradient(42% 36% at 0% 72%,rgba(170,235,200,.22),transparent 70%)}
|
||||
button,input,select,textarea{font:inherit;color:inherit}
|
||||
svg.i{width:18px;height:18px;flex:none;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
|
||||
.gem{display:inline-block;width:30px;height:30px;flex:none;background:url("data:image/webp;base64,UklGRlANAABXRUJQVlA4WAoAAAAQAAAAxwAAxwAAQUxQSDoCAAABkOv/kyIp1T3DXYQ7xOchb6EZhETruzgp5O6PQLiOPcTJWoR7aNHJ9HRVNDV314LuZyNiAsCOIdxWK8rIFXUHQvDIEO5STEbGdM8/lBlqmJgMuOPBPXPuB+MBV7oo7XVzboDz7zUbzeRW4w2hGUhvG61mcqN530XvyMrvXbQURzFXm4MxN4o7LuqRJutq6g9FEWHKvp0GYUphp9RLduqA/QXsKJaKJWbxC6F9kL4WS8xiqbgThH0kzJKD50DaaDJSkeKinVBxIxVN2WkKCcmpSDg98t8/CQATLpoEKwZwatAZMPsvycGv+gNmZ3AaAjNCKJNnViA0JafXNNtFmr2m8+bkSZFHKiqM/PdbSwbc8aDocWnPeJuAI8eOHks+efQRxZ4WwAvy2E1Wjddirva4OsXkrcOEimKLYHtcFjat91zZc2BP8u49W72NaPkn99vPxxB4W9q2xyFbYd3j+DE1Rv4b8aCqI81F30DNjXRtY56RRz/fCAl3uovd5F7nM6FPIH3u9LrJi927INcvrYAsKZ9QlAMBRoaQ940ChCP//bWXVSuKG7soVtwVlTPnHHnmeVMkzOQzueR89ioSugUJr2XzueRMfhakGekPuOggWFKG3LFw1kVz4VjIlebwJUy5aBokWHcYxGSkIsVFO6HiRiqastMMOXjWRgIOVWvVGrP6k9A+SD9r3GqtehiEfdZxibR9NHXAiUHKvp0GQUphqbQ9O/XBwcOD+oT2QRq4aH51edW6y6sLBgFWUDgg8AoAAFBBAJ0BKsgAyAA+SR6MQ6Qhoxj89OxABISm7EwDx/hykX3/nOvLkf07+B/J3p4+iPDXyDY8uM/OZ4+/1f9Y/ar/TfNL+7/6P2T/6H1Bf8D/Mv8x1S/299Qf87/qX/R/xHvKf6L/l/2T3LegB/av6n6yX/U9mD+ef7L2AP4B/gP/N63H7CfC//X/+V+7Hs8/+rWNPQ/+e9e/QevO7pm8pPk8CrxhX9D9ADQ+zAEy7vut0+WL2jM7Bha+MYD2aOc5YhbsJABg57wPkCxqolVYOcpQF9LOnhFoDMTGFNb8XsZR1QuidGMH9rxELBPVFwDvaGTq1v2S3ganOlSXWhe4wAzrD0ZY13INjOzT2Nc5DYKVELo9f9I2sTeoLOtlMQnxxst+p3PX1BeWTuSFP20/Mhali6vIn5Vs2eCODZQ/fvb1A+l14CHYbMl0VY4/BeiWbXkTwfaHnDeph+PQvqP+Zv6OlW+KhwmyDqg/q62ZKqGeOutwActE9S8v8MwhRnNqj9rGBORE+0L0mVvGt6tm4q3XM9nam+/dumpfHXzhCK9jb+0BTpW8UQP9nvYHZ08lcHnD0ZxvPxerOuMhtvzzsleCfWutDMMiHduoZGYWdOv+YgFaFzq7Ef7T0Ofl9QcNUsvWlcVAz42y+c/ExsX8Js5MZgx5Qc5Y3WqbqDINSAoc5cgcsyYAZlLYCOF8rOR+WVGkQAD+/nyUQNMcDsKWY60EpsmdOrbkKGNmia2purWHJ0vmqHe/BkLJxUpHR+7juBJx2iZQxxdq1zwoStodPc75obDoZXqp7ZP/v0lQBYIQgndf5SQij6zQvIX9dGjGDd/imlYTF9Wlt/npmmkp56ISJW/kHUoXRXO3pfAsXysAD8MUqPhEJiQgPCQVir0g7EncdPv8KNirfpiLZ84u+fMo//HW35PvTp0koSewcP9TzrydyEtb1T29z/6WEJxC3fpySjEzpmkb13uRFXTjfqf5wifnpw1HS+r43ARxmkB1u832qhVohMFm7vKOX7/2xEsuMDEbjT8ULaBZb3fhstJpT/1nhpVe2l0VBnHCATpjvJNIbjWp4BzX2knTQebRF/6VQqCYjHuFDdXlBWfgAKGld1Qi1C18ycb9stQBsNyz7BDrHOg+a75d+//InufwSQ/2m4vpW1eqWBkBQS9niGKlAh+xzjfXO3HZLH//rmlm46+jRJdjiSEJrkr53/jUPgULeIuuSjVgl76sDZMyJ14NlKUPC5dFEJaF5E8BiPDAwAGo7SnKMczk76uDo4K5r2OeNoIm2pARSWj0F6m5y33eH/9oObOf/tmd0TiTzdJABh1X+HG+on0CtWb+oHsC/ZUy0R864Ph/pV9K0Ew9hxtDdun6gPhFl5xzCD0ywQd1kItQXUIzxT+1Blv5YSQqVJAdqgaH8Y6RvyBc+Re4Q14sif8cbwdmrrfKB0fXHedPAYugpiDWr5qrFncwGOxPIs02X0OZqj3+oJVjUIBkdf5Xw6AsOhqZfTL6UnZNUoTebXPy83DN9i2hT0sume3+Gxywrvgw3oWUn6yH1JXBfniiYuWmKMKNFRks4g7AYOgBHuIaQXZrNi1W2knYOw8p3LAm7AgFMwYGkW5EZ0sHq3ZZsnnve59BvnDfE7PWNIGlTSPrAKNgT88EG66gYgjzmJiVuBQPKo3GneKRrhnURA2h22Si4Ekf2yvmD//nfRBPkqThpVPgDfS8/j74RqP643+K1dNPWitHT6+VSfSU2/UFKGtDEUR70Q77CpWYzgvBT3hI1SSCAfdmRlPaJ/D9t38ujaJToPB+bDobN4TjQafzW9V66v/EwzQX/XmEjEXRP7So0yep+U869pYstdTrcOjwqP4mp0weGyZFYHHuogVxnxx2aOaLDlQwM4Oz1qHHXgvBX7sXUvUgvdB9G+K1pT5CYgSWMu18Or5kLW39Z2M2kEZXGHsAkQMiil+c1p5ebuU6y6/7roOxw8py5lPVyIXz2FZsDJVrjMR8AdGTtXJd+vHfaULvJGjNEDC00io2i6divF52Abpv4jzEl7mTauagA+iQtoevO7q2wfcl8gm/wOu994zq0kxiFYC9JqTPYz3QNFb0w/AIEC0pXLKWhslvQjFj3R64nlgFRrncXFaNJgcBfOOomKjlpbcZj/KtYjwGf30CatVYEftNb1Tj7sQftX3Ws5/7gztKrPweq2UgGzS3Wi6a5R3p2ruB5iOy9ytckR4MGd5pGX2zlzw8rAMdVzO1RwXHLnonYoiPoC59lYxrJ7fxt+cXg8vJdWl/yuuYoGe6Fcdzwk2g//zIeutbs2LS9xOO0NKCwAo0oWbbLCFli0OzgxxcK6pcPpSXykulZ2xqMukMJu8D+1qAX7gaW9v09fJrw0W3MgS8UIJbmoF1tz+LwtVPOrkd3VENK7nxJzDbKpCQ3KkEL+4KHEWpt18tNOwfFMU4+OB5YwDlw77Y2aw6RPUWZc4vqmsGRuSGl75KiaC6zzT9/F0wpCivVWx9vY9Qgl1gc2Po+wOvUqrQ4aDGgMahYoAW6gARpJ7j3xcvkI9XX9FxDM9Huh0/ZVA/uT1eeCa6UNUHBWf2Y89+wRHnang85AaOxl05UXP47FSfmR1TCa9OhrTO2aAtoafklBVuKTba2Ke2re5y7HHMhdEWxOef/WhN46DpvRIjr8h/yKv7NqkIxZKGpDNxUuhyo66fabimGxxhdOV4TxUHl+Kt2jCffg6qj0lLeEAsQ+IDTLe3f+sx53nv+N1trtOCJhSjfUaOqoK5b0Ep62tlPGUum0tvFZ9gxgofRAdzz8TzRM6DOpivt8C4jkSAnqroejgYnZRnC3i5U76dHcO4XkTgqf7vza5pxtuogH+bS73/4E0TLSItybu3z2BSAvtQBtcRJGz2AO2diaWJynBFU8YqaJW0qO7sdycAe5MFaJ8N8P+VLLxK1QlZzHEkQzhx9smACj0WpMhtAz1lAM4dzRFAMX19gRekfA1rKZbIQJFmsTJDLIn8qd5V/jjqEC0GSYexXE8M9I8BeMW6X+s17Kq6gMXn6+Bl41LfG+kkH7RH39JbLael+yBf4RZpWHTB4SxXZ2Z0SsAcKR2ng5kTgNlNEpvvwzNXfdu379QA/OYu2UbQl/L1nZfv/Ye55QzCAApJdDwWVgx5LZ9JAepjG4s614zvjuu8UURzoebCOVMJD84ABp0Tr9h5LQycoEM3G4UTRNVlg2WMM0BqyOTktvZzF2Nl3/5HRrNZj6fQO7oVhnt84+GWUWFlL1SL96XQv2UddBX/NyhDHtuwwBi6sxdNAjgE0u/71CbMzoraYbyM54yQfGFmgg7Owq4LWMab++ix44NDh8hmeBD291vV1KP2S0eOIL2T819Vgk068LoU4lLMhCGIBVckMvlcpoK06QCkOMbAqYJKaZyfnwHzLeCYooyzec29+j1EeBVr918YImIm6AT1i1fOmMoc9G//9f657Bugh1ehZQowlm9MBHiHeBhoKb8S0pkkLW0jkjdnPzX1vwAa8u+BZfinC2NL8YqJUPZBgUIs/rtk+twHUTRPAi/NrHcuDGti9vuS0Zw0QeJXzjy4Z/kqZl5dZb/bKnwu3iHt3aP+l1z7XzUjspXIyw/TAFXxiqmu8kttkTkG1fUcqUSyZaxgEFXshEJTrj/qdeSdliYqE4t3yF6tEtZ8axetYc1pTd3VXLE5AERYoAAHNepoxPYBAAg5PvWz/R+QRhnmJYAAAAA=") center/contain no-repeat;image-rendering:pixelated}
|
||||
.px{font-family:var(--pixel);font-weight:400;-webkit-font-smoothing:none;letter-spacing:.02em}
|
||||
code{font-family:var(--mono);font-size:.92em;background:rgba(30,36,64,.06);padding:0 4px;border-radius:3px}
|
||||
|
||||
/* ---------- 按钮 ---------- */
|
||||
.btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;height:38px;padding:0 14px 3px;border-radius:4px;cursor:pointer;white-space:nowrap;text-decoration:none;
|
||||
border:2px solid var(--stone-edge);background:var(--stone);color:var(--txt);font-weight:700;font-size:13.5px;
|
||||
box-shadow:inset 0 2px 0 #fff,inset 0 -4px 0 var(--stone-lo);transition:transform .08s linear,box-shadow .08s linear,background .12s}
|
||||
.btn:hover:not(:disabled){background:#fff}
|
||||
.btn:active:not(:disabled){transform:translateY(2px);box-shadow:inset 0 2px 0 #fff,inset 0 -2px 0 var(--stone-lo)}
|
||||
.btn.pri{border-color:var(--mc-lo);background:var(--mc);color:#fff;box-shadow:inset 0 2px 0 var(--mc-hi),inset 0 -4px 0 var(--mc-lo)}
|
||||
.btn.pri:hover:not(:disabled){background:#469A2E}
|
||||
.btn.pri:active:not(:disabled){box-shadow:inset 0 2px 0 var(--mc-hi),inset 0 -2px 0 var(--mc-lo)}
|
||||
.btn.sm{height:32px;padding:0 10px 2px;font-size:12.5px}
|
||||
.btn.bad{color:var(--bad-t)}
|
||||
.btn.wide{width:100%;height:44px;font-size:15px}
|
||||
.btn:disabled{opacity:.45;cursor:not-allowed;filter:saturate(.4)}
|
||||
.btn:focus-visible,.nav button:focus-visible,.seg button:focus-visible,.tile:focus-visible{outline:2px solid var(--mc-hi);outline-offset:2px}
|
||||
.link{border:0;background:none;padding:0;color:var(--mc);font-weight:700;cursor:pointer}
|
||||
.pubn{display:inline-grid;place-items:center;min-width:19px;height:19px;margin-left:2px;padding:0 5px;border-radius:4px;background:#FFD36E;color:#1E2440;font-size:11.5px;font-weight:800;line-height:1}
|
||||
|
||||
/* ---------- 登录 / 首次改密 ---------- */
|
||||
.gate{min-height:100vh;display:grid;place-items:center;padding:24px 16px}
|
||||
.gbox{width:100%;max-width:380px;padding:28px 26px 24px;border-radius:10px;background:var(--glass);border:2px solid #fff;box-shadow:var(--panel-shadow)}
|
||||
.gbox .gem{width:64px;height:64px;display:block;margin:0 auto 12px;border-radius:8px;background-color:#fff;background-size:38px;border:2px solid #fff;
|
||||
box-shadow:-5px 10px 18px -12px rgba(255,110,140,.4),5px 10px 18px -12px rgba(70,140,255,.4)}
|
||||
.gbox h1{margin:0;text-align:center;font-size:24px}
|
||||
.gbox .sub{margin:4px 0 20px;text-align:center;color:var(--txt-3);font-size:13px;line-height:1.7}
|
||||
.gmsg{min-height:20px;margin-top:12px;font-size:13px;color:var(--bad-t);text-align:center}
|
||||
.chk{display:flex;align-items:center;gap:8px;margin:2px 0 18px;font-size:13px;color:var(--txt-2);cursor:pointer;user-select:none}
|
||||
.chk input{width:18px;height:18px;accent-color:var(--mc)}
|
||||
.lockbar{display:flex;gap:10px;align-items:flex-start;padding:11px 12px;margin-bottom:18px;border-radius:6px;background:rgba(255,248,230,.95);border:1px solid rgba(214,160,40,.35);color:var(--warn-t);font-size:12.5px;line-height:1.7}
|
||||
.back{display:block;margin-top:16px;text-align:center;font-size:12.5px;color:var(--dim);text-decoration:none}
|
||||
.back:hover{color:var(--txt)}
|
||||
|
||||
/* ---------- 表单 ---------- */
|
||||
.fld{display:block;margin-bottom:14px}
|
||||
.fld>span{display:block;margin-bottom:6px;font-size:12.5px;font-weight:700;color:var(--txt-2)}
|
||||
.fld>span .h{font-weight:400;color:var(--dim)}
|
||||
.in{width:100%;height:40px;padding:0 11px;border-radius:4px;border:2px solid var(--line);background:#fff;outline:none;transition:border-color .12s}
|
||||
textarea.in{height:auto;min-height:84px;padding:9px 11px;line-height:1.7;resize:vertical}
|
||||
select.in{padding-right:28px}
|
||||
.in:focus{border-color:var(--mc)}
|
||||
.in.err{border-color:var(--bad)}
|
||||
.pw{position:relative}
|
||||
.pw .in{padding-right:44px}
|
||||
.pw button{position:absolute;right:4px;top:4px;height:32px;width:36px;border:0;background:none;color:var(--dim);cursor:pointer;border-radius:4px}
|
||||
.pw button:hover{color:var(--txt);background:rgba(30,36,64,.05)}
|
||||
|
||||
/* ---------- 顶栏 ---------- */
|
||||
.top{position:sticky;top:0;z-index:30;background:rgba(255,255,255,.74);border-bottom:1px solid rgba(255,255,255,.9);box-shadow:0 10px 30px -24px rgba(80,90,170,.45);
|
||||
-webkit-backdrop-filter:blur(14px) saturate(1.4);backdrop-filter:blur(14px) saturate(1.4)}
|
||||
.top-in{max-width:1320px;margin:0 auto;padding:10px 20px;display:flex;align-items:center;gap:12px}
|
||||
.brand{display:flex;align-items:center;gap:10px;margin-right:auto;min-width:0;color:inherit;text-decoration:none}
|
||||
.brand b{font-size:19px;white-space:nowrap}
|
||||
.brand small{display:block;font-size:11.5px;color:var(--dim);font-weight:400;white-space:nowrap}
|
||||
.saving{font-size:12px;color:var(--dim);white-space:nowrap}
|
||||
.saving.bad{color:var(--bad-t)}
|
||||
|
||||
/* ---------- 骨架 ---------- */
|
||||
.shell{max-width:1320px;margin:0 auto;padding:20px;display:grid;grid-template-columns:212px minmax(0,1fr);gap:22px;align-items:start}
|
||||
.nav{position:sticky;top:78px;display:flex;flex-direction:column;gap:2px;padding:8px;border-radius:8px;background:var(--glass);border:2px solid rgba(255,255,255,.95);box-shadow:var(--panel-shadow)}
|
||||
.nav .grp{margin:10px 10px 4px;font-size:11px;font-weight:700;letter-spacing:.12em;color:var(--dim)}
|
||||
.nav .grp:first-child{margin-top:4px}
|
||||
.nav button{display:flex;align-items:center;gap:10px;height:38px;padding:0 12px;border:0;border-radius:4px;background:none;cursor:pointer;color:var(--txt-2);font-size:14px;text-align:left}
|
||||
.nav button:hover{background:rgba(255,255,255,.9);color:var(--txt)}
|
||||
.nav button[aria-current=true]{background:#fff;color:var(--txt);font-weight:700;box-shadow:inset 3px 0 0 var(--mc),0 6px 16px -12px rgba(80,90,170,.5)}
|
||||
.nav .n{margin-left:auto;min-width:20px;height:19px;padding:0 6px;border-radius:4px;background:#C88A12;color:#fff;font-size:11px;font-weight:700;line-height:19px;text-align:center}
|
||||
.nav .n:empty{display:none}
|
||||
main{min-width:0}
|
||||
.pane{display:none}
|
||||
.pane.on{display:block;animation:paneIn .26s var(--ease)}
|
||||
@keyframes paneIn{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
|
||||
.ph{display:flex;align-items:flex-end;justify-content:space-between;gap:12px;flex-wrap:wrap;margin:0 0 14px}
|
||||
.ph h1{margin:0;font-size:26px}
|
||||
.ph p{margin:2px 0 0;color:var(--txt-3);font-size:13px}
|
||||
.card{background:var(--glass);border:2px solid rgba(255,255,255,.95);border-radius:8px;box-shadow:var(--panel-shadow);padding:18px;margin-bottom:18px}
|
||||
.card>h2{display:flex;align-items:center;gap:8px;margin:0 0 12px;font-size:15.5px;flex-wrap:wrap}
|
||||
.card>h2 .sub{font-weight:400;font-size:12.5px;color:var(--dim)}
|
||||
.grid2{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:18px;align-items:start}
|
||||
.fgrid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:0 14px}
|
||||
.stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-bottom:18px}
|
||||
.stat{padding:14px 16px;border-radius:8px;background:var(--glass);border:2px solid rgba(255,255,255,.95);box-shadow:var(--panel-shadow)}
|
||||
.stat .k{font-size:12px;color:var(--txt-3)}
|
||||
.stat .v{font-size:26px;font-weight:800;line-height:1.25;font-variant-numeric:tabular-nums}
|
||||
.stat .s{font-size:12px;color:var(--dim)}
|
||||
.stat.warn .v{color:var(--warn-t)}
|
||||
.row{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
|
||||
.bar{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-bottom:14px}
|
||||
.search{position:relative;flex:1;min-width:180px}
|
||||
.search .in{padding-left:34px}
|
||||
.search svg{position:absolute;left:10px;top:11px;color:var(--dim)}
|
||||
.seg{display:flex;gap:6px;flex-wrap:wrap}
|
||||
.seg button{min-height:34px;padding:4px 12px;border-radius:4px;border:2px solid var(--line);background:rgba(255,255,255,.7);cursor:pointer;font-size:13px;color:var(--txt-2)}
|
||||
.seg button.on{border-color:var(--mc);background:rgba(91,170,60,.1);color:var(--ok-t);font-weight:700}
|
||||
.list{display:flex;flex-direction:column;gap:8px}
|
||||
.item{display:flex;align-items:center;gap:12px;padding:11px 14px;border-radius:6px;background:rgba(255,255,255,.85);border:1px solid var(--line-soft);transition:border-color .15s}
|
||||
.item:hover{border-color:var(--line)}
|
||||
.item.dirty{border-color:rgba(214,160,40,.45);background:linear-gradient(90deg,rgba(255,240,200,.5),rgba(255,255,255,.85) 30%)}
|
||||
.item.off{opacity:.55}
|
||||
.item .body{flex:1;min-width:0}
|
||||
.item .t{font-weight:700;display:flex;align-items:center;gap:8px;flex-wrap:wrap}
|
||||
.item .m{font-size:12.5px;color:var(--txt-3);margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.item .acts{display:flex;gap:6px;flex:none}
|
||||
.tag{display:inline-flex;align-items:center;height:21px;padding:0 7px;border-radius:4px;font-size:11.5px;font-weight:700;background:rgba(30,36,64,.06);color:var(--txt-2);white-space:nowrap}
|
||||
.tag.g{background:rgba(91,170,60,.12);color:var(--ok-t)}
|
||||
.tag.y{background:rgba(214,160,40,.16);color:var(--warn-t)}
|
||||
.tag.r{background:rgba(210,72,58,.1);color:var(--bad-t)}
|
||||
.tag.b{background:rgba(70,110,220,.1);color:var(--info-t)}
|
||||
.sw{width:30px;height:30px;border-radius:6px;flex:none;box-shadow:inset 0 0 0 1px rgba(30,36,64,.1)}
|
||||
.sw.img{background:#0B1028 center/118% no-repeat}
|
||||
.empty{padding:24px 10px;text-align:center;color:var(--dim);font-size:13px}
|
||||
.h{font-size:12px;color:var(--dim);line-height:1.7}
|
||||
.errtxt{display:block;margin-top:4px;font-size:12px;color:var(--bad-t)}
|
||||
/* 画展网格 */
|
||||
.tiles{display:grid;grid-template-columns:repeat(auto-fill,minmax(172px,1fr));gap:12px}
|
||||
.tile{position:relative;display:block;padding:0;text-align:left;border-radius:8px;overflow:hidden;background:#fff;border:2px solid rgba(255,255,255,.95);cursor:pointer;
|
||||
box-shadow:0 12px 24px -20px rgba(80,90,170,.55);transition:transform .15s var(--ease),border-color .15s}
|
||||
.tile:hover{transform:translateY(-2px)}
|
||||
.tile.dirty{border-color:rgba(214,160,40,.6)}
|
||||
.tile.off .th{filter:grayscale(1);opacity:.5}
|
||||
.tile .th{aspect-ratio:4/3;background:#EEF1F6 center/cover no-repeat}
|
||||
.tile .cap{padding:8px 10px 10px}
|
||||
.tile .cap b{display:block;font-size:13.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.tile .cap span{font-size:11.5px;color:var(--dim)}
|
||||
.tile .flags{position:absolute;left:8px;top:8px;display:flex;gap:4px}
|
||||
.tile .flags .tag{background:rgba(255,255,255,.94);box-shadow:0 2px 6px -2px rgba(30,36,64,.35)}
|
||||
.drop{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px;min-height:100%;border:2px dashed rgba(60,133,39,.35);border-radius:8px;background:rgba(255,255,255,.55);color:var(--mc);cursor:pointer;text-align:center;padding:16px;font-size:13px;font-weight:700}
|
||||
.drop:hover,.drop.over{border-color:var(--mc);background:rgba(91,170,60,.07)}
|
||||
.drop small{display:block;font-weight:400;color:var(--dim);margin-top:4px}
|
||||
.prog{height:6px;border-radius:3px;background:rgba(30,36,64,.08);overflow:hidden;margin-top:6px}
|
||||
.prog i{display:block;height:100%;background:var(--mc);width:0;transition:width .3s}
|
||||
/* 抽屉 */
|
||||
.scrim{position:fixed;inset:0;z-index:50;background:rgba(236,240,248,.55);-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);opacity:0;pointer-events:none;transition:opacity .2s}
|
||||
.scrim.on{opacity:1;pointer-events:auto}
|
||||
.drawer{position:fixed;top:0;right:0;bottom:0;z-index:51;width:min(520px,100vw);display:flex;flex-direction:column;background:#fff;box-shadow:-30px 0 60px -30px rgba(40,50,110,.45);
|
||||
transform:translateX(104%);transition:transform .28s var(--ease)}
|
||||
.drawer.on{transform:none}
|
||||
.dh{display:flex;align-items:center;gap:10px;padding:16px 18px;border-bottom:1px solid var(--line-soft)}
|
||||
.dh h3{margin:0;font-size:17px;flex:1;min-width:0}
|
||||
.db{flex:1;overflow:auto;padding:18px}
|
||||
.df{display:flex;gap:10px;padding:14px 18px calc(14px + env(safe-area-inset-bottom));border-top:1px solid var(--line-soft)}
|
||||
.df .sp{flex:1}
|
||||
.x{width:36px;height:36px;border:0;border-radius:4px;background:none;cursor:pointer;color:var(--dim)}
|
||||
.x:hover{background:rgba(30,36,64,.06);color:var(--txt)}
|
||||
.dimg{aspect-ratio:16/10;border-radius:6px;background:#EEF1F6 center/contain no-repeat;margin-bottom:14px;border:1px solid var(--line-soft)}
|
||||
.swatches{display:flex;gap:8px;flex-wrap:wrap}
|
||||
.swatches button{width:30px;height:30px;border-radius:6px;border:2px solid #fff;cursor:pointer;box-shadow:0 0 0 1px rgba(30,36,64,.15)}
|
||||
.swatches button.on{box-shadow:0 0 0 2px var(--mc)}
|
||||
.stage-mini{border-radius:8px;padding:14px 12px 12px;background:radial-gradient(70% 70% at 50% 40%,#1A2350,#070B1C);text-align:center;color:#C9D0F2;font-size:12px;margin-bottom:14px}
|
||||
.stage-mini canvas{width:150px;height:150px;display:block;margin:0 auto}
|
||||
.stage-mini b{display:block;color:#fff;font-size:16px;margin-top:6px}
|
||||
/* 外观预设 */
|
||||
.presets{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:10px}
|
||||
.pre{display:flex;flex-direction:column;align-items:center;gap:2px;padding:10px 8px 10px;border-radius:8px;background:radial-gradient(80% 70% at 50% 35%,#1A2350,#070B1C);color:#E8EBFA;text-align:center}
|
||||
.pre canvas{width:100%;max-width:150px;aspect-ratio:1/1}
|
||||
.pre b{font-size:13.5px}
|
||||
.pre code{font-size:11px;color:#8A92BE;background:none}
|
||||
.pre .btn{margin-top:6px;height:30px;font-size:12px}
|
||||
/* 弹窗 */
|
||||
.modal{position:fixed;inset:0;z-index:60;display:grid;place-items:center;padding:16px;background:rgba(236,240,248,.6);-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);opacity:0;pointer-events:none;transition:opacity .18s}
|
||||
.modal.on{opacity:1;pointer-events:auto}
|
||||
.mbox{width:100%;max-width:520px;max-height:calc(100vh - 32px);overflow:auto;padding:22px;border-radius:10px;background:#fff;box-shadow:0 40px 80px -40px rgba(40,50,110,.6);transform:translateY(8px);transition:transform .2s var(--ease)}
|
||||
.modal.on .mbox{transform:none}
|
||||
.mbox h3{margin:0 0 6px;font-size:19px}
|
||||
.mbox p{margin:0 0 14px;color:var(--txt-3);font-size:13px;line-height:1.75}
|
||||
.chg{list-style:none;margin:0 0 14px;padding:0;border-radius:6px;border:1px solid var(--line-soft);overflow:hidden}
|
||||
.chg li{display:flex;justify-content:space-between;gap:10px;padding:9px 12px;font-size:13px;border-top:1px solid var(--line-soft)}
|
||||
.chg li:first-child{border-top:0}
|
||||
.chg li span{color:var(--dim)}
|
||||
.mf{display:flex;gap:10px;justify-content:flex-end;margin-top:16px;flex-wrap:wrap}
|
||||
/* 时间线 */
|
||||
.ver{display:flex;gap:14px;padding:12px 0;border-top:1px solid var(--line-soft);align-items:center}
|
||||
.ver:first-child{border-top:0}
|
||||
.ver .dotc{flex:none;width:40px;height:34px;border-radius:6px;display:grid;place-items:center;background:var(--stone);border:2px solid var(--stone-edge);font:800 12px/1 var(--mono);box-shadow:inset 0 -3px 0 var(--stone-lo)}
|
||||
.ver.cur .dotc{background:var(--mc);border-color:var(--mc-lo);color:#fff;box-shadow:inset 0 -3px 0 var(--mc-lo)}
|
||||
.ver .body{flex:1;min-width:0}
|
||||
.ver .t{font-weight:700}
|
||||
.ver .m{font-size:12.5px;color:var(--txt-3)}
|
||||
/* 首页预览小窗 */
|
||||
.mini{border-radius:10px;padding:22px 20px;border:3px solid rgba(255,255,255,.95);box-shadow:0 20px 40px -26px rgba(80,100,170,.45);
|
||||
background:radial-gradient(60% 80% at 0% 0%,rgba(255,196,214,.55),transparent 70%),radial-gradient(60% 80% at 100% 10%,rgba(176,214,255,.6),transparent 70%),linear-gradient(160deg,#fff,#F6F8FE)}
|
||||
.mini h4{margin:0;font-size:34px}
|
||||
.mini p{margin:8px 0 14px;color:var(--txt-2);font-size:13.5px;line-height:1.8}
|
||||
.mini .notice{display:inline-block;margin-bottom:12px;padding:7px 10px;border-radius:4px;background:rgba(214,160,40,.14);color:var(--warn-t);font-size:12.5px;font-weight:700}
|
||||
.switch{position:relative;display:inline-flex;align-items:center;gap:10px;cursor:pointer;font-size:13px;color:var(--txt-2);user-select:none}
|
||||
.switch input{position:absolute;opacity:0}
|
||||
.switch i{width:40px;height:22px;border-radius:11px;background:rgba(30,36,64,.18);position:relative;transition:background .15s;flex:none}
|
||||
.switch i::after{content:"";position:absolute;left:3px;top:3px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .15s var(--ease);box-shadow:0 1px 3px rgba(0,0,0,.2)}
|
||||
.switch input:checked+i{background:var(--mc)}
|
||||
.switch input:checked+i::after{transform:translateX(18px)}
|
||||
.switch input:focus-visible+i{outline:2px solid var(--mc-hi);outline-offset:2px}
|
||||
.tbl{width:100%;border-collapse:collapse;font-size:13.5px}
|
||||
.tbl th{text-align:left;font-size:12px;color:var(--dim);font-weight:700;padding:0 8px 8px}
|
||||
.tbl td{padding:6px 8px;border-top:1px solid var(--line-soft);vertical-align:middle}
|
||||
.tbl .in{height:34px}
|
||||
#toast{position:fixed;left:50%;bottom:28px;z-index:80;max-width:min(92vw,560px);padding:10px 16px;border-radius:6px;background:#1E2440;color:#fff;font-size:13px;
|
||||
opacity:0;transform:translate(-50%,10px);pointer-events:none;transition:opacity .18s var(--ease),transform .18s var(--ease)}
|
||||
#toast.on{opacity:1;transform:translate(-50%,0)}
|
||||
#toast.bad{background:#8E2A20}
|
||||
.menu-btn{display:none}
|
||||
@media (max-width:1080px){.grid2{grid-template-columns:minmax(0,1fr)}}
|
||||
@media (max-width:880px){
|
||||
.top-in{padding:8px 12px;gap:8px}
|
||||
.top .bt,.saving{display:none}
|
||||
.brand b{font-size:17px}.brand small{font-size:10.5px}
|
||||
.menu-btn{display:inline-flex}
|
||||
.shell{grid-template-columns:minmax(0,1fr);padding:14px 12px 40px}
|
||||
.nav{position:fixed;left:0;top:0;bottom:0;z-index:55;width:248px;border-radius:0;transform:translateX(-104%);transition:transform .25s var(--ease);overflow:auto;background:#fff}
|
||||
.nav.open{transform:none}
|
||||
.stats{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
.fgrid{grid-template-columns:minmax(0,1fr)}
|
||||
.card{padding:15px 13px}
|
||||
.ph h1{font-size:22px}
|
||||
.item{flex-wrap:wrap}
|
||||
.item .acts{width:100%;justify-content:flex-end}
|
||||
}
|
||||
@media (prefers-reduced-motion:reduce){.pane.on{animation:none}.drawer,.nav,.modal,.mbox,#toast{transition:none}}
|
||||
</style></head><body>
|
||||
|
||||
<!-- ============ 登录 ============ -->
|
||||
<section class="gate" id="gLogin" hidden>
|
||||
<form class="gbox" id="loginForm" autocomplete="on">
|
||||
<i class="gem" aria-hidden="true"></i>
|
||||
<h1 class="px">内容后台</h1>
|
||||
<p class="sub">金钻客栈的网页内容都在这里改。<br>只给有账号的人用。</p>
|
||||
<label class="fld"><span>用户名或邮箱</span><input class="in" id="lgUser" autocomplete="username" required></label>
|
||||
<label class="fld"><span>密码</span><div class="pw"><input class="in" id="lgPw" type="password" autocomplete="current-password" required>
|
||||
<button type="button" class="eye" aria-label="显示密码"><svg class="i" viewBox="0 0 24 24"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg></button></div></label>
|
||||
<label class="chk"><input type="checkbox" id="lgRemember" checked>记住我(30 天内这台设备不用再输密码)</label>
|
||||
<button class="btn pri wide" type="submit" id="lgGo">登录</button>
|
||||
<div class="gmsg" id="lgMsg" role="alert"></div>
|
||||
<a class="back" href="../">← 回门户主页</a>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<!-- ============ 首次改密(初始账号必须先改,服务端也只放行改密 / 退出) ============ -->
|
||||
<section class="gate" id="gFirst" hidden>
|
||||
<form class="gbox" id="firstForm">
|
||||
<i class="gem" aria-hidden="true"></i>
|
||||
<h1 class="px">先改个密码</h1>
|
||||
<p class="sub">这是第一次用初始密码登录。<br>改完之前,后台别的功能都打不开。</p>
|
||||
<div class="lockbar"><svg class="i" viewBox="0 0 24 24"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
|
||||
<div>新密码至少 8 位,不能是 admin,也不能是 12345678 这类常见密码。改完要用新密码重新登录一次。</div></div>
|
||||
<label class="fld"><span>现在的密码</span><input class="in" id="fpOld" type="password" autocomplete="current-password"></label>
|
||||
<label class="fld"><span>新密码</span><input class="in" id="fpNew" type="password" autocomplete="new-password"></label>
|
||||
<label class="fld"><span>再输一遍</span><input class="in" id="fpAgain" type="password" autocomplete="new-password"></label>
|
||||
<button class="btn pri wide" type="submit">改好了</button>
|
||||
<div class="gmsg" id="fpMsg" role="alert"></div>
|
||||
<a class="back" href="#" id="fpOut">先退出</a>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<!-- ============ 后台 ============ -->
|
||||
<div id="app" hidden>
|
||||
<header class="top"><div class="top-in">
|
||||
<button class="btn sm menu-btn" id="menuBtn" type="button" aria-label="打开菜单"><svg class="i" viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h16"/></svg></button>
|
||||
<a class="brand" href="../" title="回到门户主页"><i class="gem" aria-hidden="true"></i><div><b class="px">内容后台</b><small>点这里回门户主页</small></div></a>
|
||||
<span class="saving" id="saving" aria-live="polite"></span>
|
||||
<button class="btn sm" id="prevBtn" type="button" title="用草稿打开网站看看(只有你看得到)"><svg class="i" viewBox="0 0 24 24"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg><span class="bt">预览</span></button>
|
||||
<button class="btn sm pri" id="pubBtn" type="button" disabled><svg class="i" viewBox="0 0 24 24"><path d="M12 19V5M5 12l7-7 7 7"/></svg><span class="bt">发布</span><span class="pubn" id="pubN" hidden></span></button>
|
||||
</div></header>
|
||||
|
||||
<div class="shell">
|
||||
<nav class="nav" id="nav" aria-label="后台分区">
|
||||
<div class="grp">总览</div>
|
||||
<button type="button" data-p="home"><svg class="i" viewBox="0 0 24 24"><rect x="3" y="3" width="7" height="9" rx="1"/><rect x="14" y="3" width="7" height="5" rx="1"/><rect x="14" y="12" width="7" height="9" rx="1"/><rect x="3" y="16" width="7" height="5" rx="1"/></svg>概览</button>
|
||||
<div class="grp">门户</div>
|
||||
<button type="button" data-p="hero"><svg class="i" viewBox="0 0 24 24"><path d="M3 10.5 12 3l9 7.5V21H3z"/></svg>首页文案<span class="n" data-n="hero"></span></button>
|
||||
<button type="button" data-p="gallery"><svg class="i" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/></svg>画展<span class="n" data-n="gallery"></span></button>
|
||||
<button type="button" data-p="apps"><svg class="i" viewBox="0 0 24 24"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.8-3.8a6 6 0 0 1-7.9 7.9l-6.9 6.9a2.1 2.1 0 0 1-3-3l6.9-6.9a6 6 0 0 1 7.9-7.9z"/></svg>工具与开源<span class="n" data-n="apps"></span></button>
|
||||
<button type="button" data-p="universe"><svg class="i" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4"/><ellipse cx="12" cy="12" rx="10" ry="4" transform="rotate(-20 12 12)"/></svg>金钻宇宙<span class="n" data-n="universe"></span></button>
|
||||
<button type="button" data-p="links"><svg class="i" viewBox="0 0 24 24"><path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7"/><path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7"/></svg>平台入口<span class="n" data-n="links"></span></button>
|
||||
<button type="button" data-p="about"><svg class="i" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>关于<span class="n" data-n="about"></span></button>
|
||||
<div class="grp">下单页</div>
|
||||
<button type="button" data-p="tpl"><svg class="i" viewBox="0 0 24 24"><path d="M12 2.6 21 7.3v9.4L12 21.4 3 16.7V7.3z"/><path d="M3 7.3l9 4.7 9-4.7M12 12v9.4"/></svg>模板与文字<span class="n" data-n="tpl"></span></button>
|
||||
<button type="button" data-p="price"><svg class="i" viewBox="0 0 24 24"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>价格与付款<span class="n" data-n="price"></span></button>
|
||||
<div class="grp">系统</div>
|
||||
<button type="button" data-p="versions"><svg class="i" viewBox="0 0 24 24"><path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 3v5h5M12 7v5l3 3"/></svg>发布记录</button>
|
||||
<button type="button" data-p="account"><svg class="i" viewBox="0 0 24 24"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg>账号与设备</button>
|
||||
</nav>
|
||||
|
||||
<main id="main">
|
||||
<!-- 概览 -->
|
||||
<section class="pane" id="p-home">
|
||||
<div class="ph"><div><h1 class="px">概览</h1><p>改动会自动存成草稿,网站上看不到;点右上角「发布」才会上线。</p></div></div>
|
||||
<div class="stats" id="stats"></div>
|
||||
<div class="grid2">
|
||||
<div class="card"><h2>还没发布的改动</h2><div class="list" id="dirtyList"></div></div>
|
||||
<div class="card"><h2>最近操作 <span class="sub">谁、什么时候、做了什么</span></h2><div class="list" id="auditList"></div></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 首页文案 -->
|
||||
<section class="pane" id="p-hero">
|
||||
<div class="ph"><div><h1 class="px">首页文案</h1><p>门户首屏那几句话、公告条,还有首页上各板块卡片的说明。</p></div></div>
|
||||
<div class="grid2">
|
||||
<div class="card">
|
||||
<label class="fld"><span>首屏一句话</span><textarea class="in" data-bind="site.hero.tagline" rows="3" maxlength="160"></textarea></label>
|
||||
<div class="fgrid">
|
||||
<label class="fld"><span>主按钮文字</span><input class="in" data-bind="site.hero.cta1" maxlength="12"></label>
|
||||
<label class="fld"><span>次按钮文字</span><input class="in" data-bind="site.hero.cta2" maxlength="12"></label>
|
||||
</div>
|
||||
<div class="fld"><span>公告条 <span class="h">(比如放假、涨价、新模板上线)</span></span>
|
||||
<label class="switch"><input type="checkbox" data-bind="site.hero.notice.on"><i></i>显示公告</label></div>
|
||||
<label class="fld"><span>公告内容</span><input class="in" data-bind="site.hero.notice.text" maxlength="80"></label>
|
||||
<div class="fgrid">
|
||||
<label class="fld"><span>从哪天开始 <span class="h">(空 = 马上)</span></span><input class="in" type="date" data-bind="site.hero.notice.from"></label>
|
||||
<label class="fld"><span>到哪天结束 <span class="h">(空 = 一直显示)</span></span><input class="in" type="date" data-bind="site.hero.notice.to"></label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card"><h2>门户首页上的样子</h2>
|
||||
<div class="mini" id="heroMini"></div>
|
||||
<p class="h" style="margin:12px 0 0">只是示意,正式效果点右上角「预览」。</p></div>
|
||||
</div>
|
||||
<div class="card"><h2>板块说明 <span class="sub">首页上各板块卡片里那段小字</span></h2>
|
||||
<div class="fgrid" id="boardFields"></div></div>
|
||||
</section>
|
||||
|
||||
<!-- 画展 -->
|
||||
<section class="pane" id="p-gallery">
|
||||
<div class="ph"><div><h1 class="px">画展</h1><p>拖图进来就能上传:服务器会核验图片、去掉照片里的隐私信息(拍摄地点等)、自动做缩略图。</p></div></div>
|
||||
<div class="card">
|
||||
<div class="bar">
|
||||
<label class="search"><svg class="i" viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg><input class="in" type="search" id="gSearch" placeholder="搜标题 / 说明 / 年份" aria-label="搜画展"></label>
|
||||
<div class="seg" id="gFilter"><button type="button" data-v="all" class="on">全部</button><button type="button" data-v="image">图片</button><button type="button" data-v="video">视频</button><button type="button" data-v="special">全景 / 壁纸</button><button type="button" data-v="hidden">已隐藏</button></div>
|
||||
<button class="btn sm" type="button" id="gVideo">加一个 B 站视频</button>
|
||||
</div>
|
||||
<div class="tiles" id="gTiles"></div>
|
||||
<input type="file" id="gFile" accept="image/png,image/jpeg,image/webp" multiple hidden>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 工具与开源 -->
|
||||
<section class="pane" id="p-apps">
|
||||
<div class="ph"><div><h1 class="px">工具与开源</h1><p>开源的和闭源的分两行显示;没填链接的会显示「待上架」。</p></div><button class="btn pri" type="button" id="appAdd">加一个</button></div>
|
||||
<div class="card"><div class="list" id="appList"></div></div>
|
||||
</section>
|
||||
|
||||
<!-- 金钻宇宙 -->
|
||||
<section class="pane" id="p-universe">
|
||||
<div class="ph"><div><h1 class="px">金钻宇宙</h1><p>每条世界线是星系图上的一颗星。档案写文字;外观在下拉里选。新点亮的会自动排到不挤的位置,连线接到附近的星上,已有的都不动。</p></div><button class="btn pri" type="button" id="uniAdd">点亮一条</button></div>
|
||||
<div class="grid2">
|
||||
<div class="card"><h2>世界线 <span class="sub" id="uniCount"></span></h2><div class="list" id="uniList"></div></div>
|
||||
<div class="card"><h2>空槽</h2>
|
||||
<p class="h" style="margin:0 0 10px">星系图外圈还没点亮的位置。点亮一条不占空槽数;想少显示几个就把数字调小。</p>
|
||||
<label class="fld"><span>留几个空槽</span><input class="in" type="number" min="0" max="20" data-bind="site.universe.empty" style="width:120px"></label></div>
|
||||
</div>
|
||||
<div class="card"><h2>外观预设 <span class="sub">编辑世界线时「星球风格」下拉里就是这些;这里是星系图上真正的样子,挑一个能直接用它点亮一条</span></h2>
|
||||
<div class="presets" id="presetGrid"><div class="empty">星球预设载入中…</div></div></div>
|
||||
</section>
|
||||
|
||||
<!-- 平台入口 -->
|
||||
<section class="pane" id="p-links">
|
||||
<div class="ph"><div><h1 class="px">平台入口</h1><p>链接只收 https:// 开头的网址和 mailto: 邮箱,别的会被拦下。</p></div><button class="btn pri" type="button" id="linkAdd">加一个</button></div>
|
||||
<div id="linkGroups"></div>
|
||||
</section>
|
||||
|
||||
<!-- 关于 -->
|
||||
<section class="pane" id="p-about">
|
||||
<div class="ph"><div><h1 class="px">关于</h1><p>名字的由来和署名卡片。写链接用 <code>[文字](https://网址)</code>,写代码样式用 <code>`文字`</code>,空一行是新段落;别的 HTML 都会原样显示成文字。</p></div><button class="btn pri" type="button" id="cardAdd">加一张卡片</button></div>
|
||||
<div class="card">
|
||||
<label class="fld"><span>名字的由来</span><textarea class="in" data-bind="site.about.story" rows="7" maxlength="1200"></textarea></label>
|
||||
<label class="fld"><span>页脚那句话</span><input class="in" data-bind="site.about.foot" maxlength="200"></label>
|
||||
</div>
|
||||
<div class="card"><h2>署名卡片</h2><div class="list" id="aboutCards"></div></div>
|
||||
</section>
|
||||
|
||||
<!-- 模板与文字 -->
|
||||
<section class="pane" id="p-tpl">
|
||||
<div class="ph"><div><h1 class="px">模板与文字</h1><p>下单页能选哪些模板、怎么介绍它们。模板文件本身和英文 key 不在这里改(渲染机认 key)。</p></div></div>
|
||||
<div class="grid2">
|
||||
<div class="card"><h2>模板 <span class="sub">关掉 = 下单页上不给选,已下的单不受影响</span></h2><div class="list" id="tplList"></div></div>
|
||||
<div class="card"><h2>页面上的文字</h2>
|
||||
<label class="fld"><span>页头那句话</span><input class="in" data-bind="order.head" maxlength="80"></label>
|
||||
<div class="fld"><span>下单页公告</span><label class="switch"><input type="checkbox" data-bind="order.notice.on"><i></i>显示公告</label></div>
|
||||
<label class="fld"><span>公告内容</span><input class="in" data-bind="order.notice.text" maxlength="120"></label>
|
||||
<p class="h">服务条款不在这里改:它和渲染机要用同一个版本号,改错会静默出问题,请照交接文档手动改。</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 价格与付款 -->
|
||||
<section class="pane" id="p-price">
|
||||
<div class="ph"><div><h1 class="px">价格与付款</h1><p>没配档位的张数按单价 × 张数算。发布后下单页的「应付」和付款按钮跟着变。</p></div></div>
|
||||
<div class="grid2">
|
||||
<div class="card"><h2>价格档位</h2>
|
||||
<label class="fld"><span>单价(元 / 张)</span><input class="in" type="number" min="0.01" step="0.01" data-bind="order.prices.per" style="width:120px"></label>
|
||||
<table class="tbl"><thead><tr><th>张数</th><th>价格(元)</th><th>爱发电商品链接</th><th></th></tr></thead><tbody id="tierRows"></tbody></table>
|
||||
<div class="row" style="margin-top:10px"><button class="btn sm" type="button" id="tierAdd">加一档</button></div>
|
||||
</div>
|
||||
<div class="card"><h2>付款方式</h2>
|
||||
<label class="fld"><span>爱发电主页链接</span><input class="in" data-bind="order.pay.payplatform" data-url placeholder="https://…"></label>
|
||||
<label class="fld"><span>爱发电创作者 ID <span class="h">(填了就能按订单金额生成专属付款链接)</span></span><input class="in" data-bind="order.pay.payplatform_uid" maxlength="40"></label>
|
||||
<label class="fld"><span>付款说明</span><textarea class="in" data-bind="order.pay.note" rows="3" maxlength="200"></textarea></label>
|
||||
<label class="fld"><span>收款码图片 <span class="h">(服务器上数据目录里的文件名,比如 payme.png)</span></span><input class="in" data-bind="order.pay.qr_img" maxlength="120"></label>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 发布记录 -->
|
||||
<section class="pane" id="p-versions">
|
||||
<div class="ph"><div><h1 class="px">发布记录</h1><p>每次发布都留一份完整的版本,可以一键回到任何一版(回滚本身也算一次发布,还能再回来)。</p></div></div>
|
||||
<div class="card" id="verList"></div>
|
||||
</section>
|
||||
|
||||
<!-- 账号与设备 -->
|
||||
<section class="pane" id="p-account">
|
||||
<div class="ph"><div><h1 class="px">账号与设备</h1><p id="meLine"></p></div><button class="btn" type="button" id="logoutBtn">退出</button></div>
|
||||
<div class="grid2">
|
||||
<form class="card" id="pwForm"><h2>改密码</h2>
|
||||
<label class="fld"><span>现在的密码</span><input class="in" type="password" id="pwOld" autocomplete="current-password"></label>
|
||||
<label class="fld"><span>新密码 <span class="h">(至少 8 位)</span></span><input class="in" type="password" id="pwNew" autocomplete="new-password"></label>
|
||||
<label class="fld"><span>再输一遍</span><input class="in" type="password" id="pwAgain" autocomplete="new-password"></label>
|
||||
<button class="btn pri" type="submit">改密码</button>
|
||||
<p class="h" style="margin:10px 0 0">改完后,除了这台,别的设备都会退出。忘了密码:在服务器上跑 <code>python3 admin.py user reset 账号</code>。</p></form>
|
||||
<div class="card"><h2>登录着的设备 <span class="sub">30 天没用会自动退出</span></h2>
|
||||
<div class="list" id="sessList"></div>
|
||||
<div class="row" style="margin-top:12px"><button class="btn bad" type="button" id="killAll">退出所有其它设备</button></div></div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 抽屉 / 弹窗 -->
|
||||
<div class="scrim" id="scrim"></div>
|
||||
<aside class="drawer" id="drawer" aria-modal="true" role="dialog" aria-labelledby="dTitle">
|
||||
<div class="dh"><h3 id="dTitle">编辑</h3><button class="x" type="button" id="dClose" aria-label="关闭"><svg class="i" viewBox="0 0 24 24"><path d="M18 6 6 18M6 6l12 12"/></svg></button></div>
|
||||
<div class="db" id="dBody"></div>
|
||||
<div class="df" id="dFoot"></div>
|
||||
</aside>
|
||||
<div class="modal" id="modal" role="dialog" aria-modal="true"><div class="mbox" id="mBox"></div></div>
|
||||
<div id="toast" role="status" aria-live="polite"></div>
|
||||
|
||||
<script type="module">
|
||||
/* 星球真实渲染:和星系图同一份 planets.js;只开一个 WebGL,画好再拷到各个小画布(浏览器能同时开的 WebGL 有限)。
|
||||
three.js 只在打开「金钻宇宙」这页时才下载。 */
|
||||
let ready = null;
|
||||
function boot() {
|
||||
if (ready) return ready;
|
||||
ready = Promise.all([import('../assets/vendor/three.module.min.js'), import('../assets/universe/planets.js?v=2')]).then(([THREE, P]) => {
|
||||
const SZ = 300, R = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
|
||||
R.setPixelRatio(1); R.setSize(SZ, SZ, false); R.setClearColor(0x000000, 0);
|
||||
const cam = new THREE.PerspectiveCamera(30, 1, 0.1, 100), L = new THREE.Vector3(-1, 0.6, 0.6).normalize();
|
||||
const thumbs = {}, live = new Map();
|
||||
const make = (style, seed) => { const s = new THREE.Scene(), p = P.makePlanet(THREE, { style, r: 1, seed: seed ?? 4.2, spin: 0.25 }); s.add(p.group); return { s, p, ring: style === 'ringed' }; };
|
||||
const draw = (it, ctx) => { cam.position.set(0, it.ring ? 1.5 : 0.4, it.ring ? 9.8 : 4.6); cam.lookAt(0, 0, 0); R.render(it.s, cam);
|
||||
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.drawImage(R.domElement, 0, 0, ctx.canvas.width, ctx.canvas.height); };
|
||||
let last = performance.now();
|
||||
(function frame(now) {
|
||||
const dt = Math.min(0.05, (now - last) / 1000); last = now;
|
||||
for (const [cv, x] of live) { if (!cv.isConnected) { live.delete(cv); continue; } x.it.p.update(dt, now / 1000, L); if (cv.offsetParent) draw(x.it, x.ctx); }
|
||||
requestAnimationFrame(frame);
|
||||
})(last);
|
||||
return {
|
||||
labels: P.STYLE_LABELS,
|
||||
thumb(style) { if (!thumbs[style]) { const it = make(style), c = document.createElement('canvas'); c.width = c.height = 96; it.p.update(0, 1, L); draw(it, c.getContext('2d')); thumbs[style] = c.toDataURL(); } return thumbs[style]; },
|
||||
live(cv, style) { const old = live.get(cv); if (old && old.style === style) return; live.set(cv, { style, it: make(style), ctx: cv.getContext('2d') }); },
|
||||
stop(cv) { live.delete(cv); },
|
||||
};
|
||||
}).catch(e => { console.warn('[内容后台] 星球预览没起来:', e); return null; });
|
||||
return ready;
|
||||
}
|
||||
window.__pp = { boot };
|
||||
</script>
|
||||
<script>
|
||||
'use strict';
|
||||
const API = '/order/api/cms/'; /* nginx:/order/api/ → server.py 的 /api/ */
|
||||
const $ = s => document.querySelector(s), $$ = s => [...document.querySelectorAll(s)];
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const clone = o => JSON.parse(JSON.stringify(o));
|
||||
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
||||
function toast(t, bad) { const e = $('#toast'); e.textContent = t; e.classList.toggle('bad', !!bad); e.classList.add('on'); clearTimeout(e._t); e._t = setTimeout(() => e.classList.remove('on'), bad ? 5200 : 2600); }
|
||||
const fmt = ts => { if (!ts) return '—'; const d = new Date(ts * 1000); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0') + ' ' + d.toTimeString().slice(0, 5); };
|
||||
const today = () => { const d = new Date(); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); };
|
||||
const rid = p => p + Math.random().toString(36).slice(2, 10);
|
||||
|
||||
/* ------------------------------------------------ 接口 */
|
||||
let CSRF = '', ME = null;
|
||||
async function api(path, body) {
|
||||
const opt = body === undefined ? { credentials: 'same-origin' }
|
||||
: { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-CSRF': CSRF }, body: JSON.stringify(body) };
|
||||
let r, j = {};
|
||||
try { r = await fetch(API + path, opt); } catch (e) { return { ok: false, error: '连不上服务器(网络断了?)', status: 0 }; }
|
||||
try { j = await r.json(); } catch (e) { j = { ok: false, error: '服务器回了看不懂的东西(' + r.status + ')' }; }
|
||||
j.status = r.status;
|
||||
if (r.status === 401 && path !== 'login' && path !== 'me') { ME = null; gate(); }
|
||||
if (r.status === 403 && j.must_change) { ME && (ME.must_change = true); gate(); }
|
||||
return j;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------ 登录 / 首次改密 / 退出 */
|
||||
function gate() {
|
||||
const inApp = ME && !ME.must_change;
|
||||
$('#gLogin').hidden = !!ME; $('#gFirst').hidden = !(ME && ME.must_change); $('#app').hidden = !inApp;
|
||||
if (!ME) setTimeout(() => $('#lgUser').focus(), 50);
|
||||
else if (ME.must_change) setTimeout(() => $('#fpOld').focus(), 50);
|
||||
}
|
||||
$$('.eye').forEach(b => b.onclick = () => { const i = b.parentNode.querySelector('input'); i.type = i.type === 'password' ? 'text' : 'password'; b.setAttribute('aria-label', i.type === 'password' ? '显示密码' : '隐藏密码'); });
|
||||
$('#loginForm').onsubmit = async e => {
|
||||
e.preventDefault();
|
||||
const b = $('#lgGo'); b.disabled = true; $('#lgMsg').textContent = '';
|
||||
const j = await api('login', { user: $('#lgUser').value.trim(), password: $('#lgPw').value, remember: $('#lgRemember').checked });
|
||||
b.disabled = false; $('#lgPw').value = '';
|
||||
if (!j.ok) { $('#lgMsg').textContent = j.error || '登录不了'; $('#lgPw').focus(); return; }
|
||||
CSRF = j.csrf; ME = { user: j.user, email: j.email, must_change: j.must_change };
|
||||
gate(); if (!ME.must_change) start();
|
||||
};
|
||||
$('#firstForm').onsubmit = async e => {
|
||||
e.preventDefault();
|
||||
const n = $('#fpNew').value;
|
||||
if (n !== $('#fpAgain').value) { $('#fpMsg').textContent = '两次输的新密码不一样'; return; }
|
||||
const j = await api('password', { old: $('#fpOld').value, new: n });
|
||||
if (!j.ok) { $('#fpMsg').textContent = j.error || '改不了'; return; }
|
||||
['#fpOld', '#fpNew', '#fpAgain'].forEach(s => $(s).value = ''); $('#fpMsg').textContent = '';
|
||||
ME = null; CSRF = ''; gate(); toast('密码改好了。所有登录都已作废,用新密码再登录一次');
|
||||
};
|
||||
$('#fpOut').onclick = async e => { e.preventDefault(); await api('logout', {}); ME = null; gate(); };
|
||||
$('#logoutBtn').onclick = async () => { await flush(); await api('logout', {}); ME = null; gate(); toast('已退出'); };
|
||||
|
||||
/* ------------------------------------------------ 内容:草稿自动保存 */
|
||||
let DOC = null, PUB = null, VERSION = 0, BASE = 0, CHANGES = [], saveTimer = 0, saving = null, dirtyLocal = false, TPLKEYS = [];
|
||||
async function loadContent() {
|
||||
const j = await api('content');
|
||||
if (!j.ok) { toast(j.error || '内容取不到', true); return false; }
|
||||
PUB = j.published; DOC = j.draft; VERSION = j.version; BASE = j.has_draft ? (j.draft_base || j.version) : j.version; CHANGES = j.changes || []; TPLKEYS = j.tpl_keys || [];
|
||||
if (j.has_draft && j.draft_base && j.draft_base !== j.version) toast('提醒:别人在你上次编辑之后发布过 v' + j.version + ',你的草稿是基于 v' + j.draft_base + ' 改的,发布前先核对一下', true);
|
||||
return true;
|
||||
}
|
||||
function mark() { /* 本地改了:画面先更新,800ms 后存草稿 */
|
||||
dirtyLocal = true; setSaving('…'); refreshCounts();
|
||||
clearTimeout(saveTimer); saveTimer = setTimeout(save, 800);
|
||||
}
|
||||
async function save() {
|
||||
if (saving) { await saving; }
|
||||
if (!dirtyLocal) return;
|
||||
dirtyLocal = false; setSaving('保存中…');
|
||||
/* 还在上传的图(没 src)先不发;存好后**不替换本地 DOC**(开着的编辑抽屉、上传回调都拿着本地对象的引用) */
|
||||
const doc = clone(DOC); doc.site.gallery = doc.site.gallery.filter(g => !g._up);
|
||||
saving = api('draft', { doc, base: BASE }).then(j => {
|
||||
saving = null;
|
||||
if (!j.ok) { dirtyLocal = true; setSaving('没存上', true); toast('草稿没存上:' + (j.error || '未知原因'), true); return false; }
|
||||
CHANGES = j.changes || []; setSaving('草稿已保存'); refreshCounts(); return true;
|
||||
});
|
||||
return saving;
|
||||
}
|
||||
async function flush() { clearTimeout(saveTimer); if (dirtyLocal) await save(); else if (saving) await saving; }
|
||||
function setSaving(t, bad) { const e = $('#saving'); e.textContent = t; e.classList.toggle('bad', !!bad); }
|
||||
function refreshCounts() {
|
||||
const n = CHANGES.reduce((s, c) => s + c[1] + c[2] + c[3], 0);
|
||||
$('#pubN').hidden = !n; $('#pubN').textContent = n; $('#pubBtn').disabled = !n && !dirtyLocal;
|
||||
$('#pubBtn').title = n ? n + ' 处改动还没发布' : '没有要发布的改动';
|
||||
const map = { '首页文案': 'hero', '板块说明': 'hero', '画展': 'gallery', '工具与开源': 'apps', '金钻宇宙': 'universe', '金钻宇宙 · 空槽': 'universe', '平台分组': 'links', '平台入口': 'links',
|
||||
'关于': 'about', '下单页模板': 'tpl', '下单页文字': 'tpl', '价格档位': 'price', '付款方式': 'price' };
|
||||
const per = {}; CHANGES.forEach(c => { const k = map[c[0]]; if (k) per[k] = (per[k] || 0) + c[1] + c[2] + c[3]; });
|
||||
$$('.nav .n').forEach(e => e.textContent = per[e.dataset.n] || '');
|
||||
}
|
||||
|
||||
/* ------------------------------------------------ 导航 */
|
||||
let PANE = 'home';
|
||||
function go(p) {
|
||||
if (!document.getElementById('p-' + p)) p = 'home';
|
||||
PANE = p;
|
||||
$$('.pane').forEach(x => x.classList.toggle('on', x.id === 'p-' + p));
|
||||
$$('#nav button').forEach(b => b.setAttribute('aria-current', String(b.dataset.p === p)));
|
||||
try { history.replaceState(null, '', '#/' + p); } catch (e) {}
|
||||
$('#nav').classList.remove('open'); window.scrollTo({ top: 0 });
|
||||
if (p === 'home') renderHome();
|
||||
if (p === 'versions') renderVersions();
|
||||
if (p === 'account') renderAccount();
|
||||
if (p === 'universe') renderUni(true);
|
||||
}
|
||||
$('#nav').addEventListener('click', e => { const b = e.target.closest('button[data-p]'); if (b) go(b.dataset.p); });
|
||||
$('#menuBtn').onclick = e => { e.stopPropagation(); $('#nav').classList.toggle('open'); };
|
||||
document.addEventListener('click', e => { if (!e.target.closest('#nav') && !e.target.closest('#menuBtn')) $('#nav').classList.remove('open'); });
|
||||
|
||||
/* ------------------------------------------------ 简单字段绑定(data-bind="site.hero.tagline") */
|
||||
const getp = (o, p) => p.split('.').reduce((a, k) => a == null ? a : a[k], o);
|
||||
function setp(o, p, v) { const ks = p.split('.'); const last = ks.pop(); const t = ks.reduce((a, k) => (a[k] = a[k] || {}), o); t[last] = v; }
|
||||
const urlOk = u => /^https:\/\/[^\s<>"']+$/i.test(u) || /^mailto:[^\s@<>"']+@[^\s@<>"']+$/i.test(u);
|
||||
function bindFields() {
|
||||
$$('[data-bind]').forEach(el => {
|
||||
const p = el.dataset.bind, v = getp(DOC, p);
|
||||
if (el.type === 'checkbox') el.checked = !!v; else el.value = v == null ? '' : v;
|
||||
el.oninput = el.onchange = () => {
|
||||
let val = el.type === 'checkbox' ? el.checked : (el.type === 'number' ? (el.value === '' ? 0 : Number(el.value)) : el.value);
|
||||
if (el.hasAttribute('data-url')) { const ok = !val || /^https:\/\//i.test(val); el.classList.toggle('err', !ok); if (!ok) return; }
|
||||
setp(DOC, p, val); mark();
|
||||
if (p.startsWith('site.hero.')) renderHeroMini();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------------------------ 概览 */
|
||||
async function renderHome() {
|
||||
const n = CHANGES.reduce((s, c) => s + c[1] + c[2] + c[3], 0), S = DOC.site;
|
||||
$('#stats').innerHTML =
|
||||
'<div class="stat ' + (n ? 'warn' : '') + '"><div class="k">没发布的改动</div><div class="v">' + n + '</div><div class="s">' + (n ? '网站上还看不到' : '草稿和网站一致') + '</div></div>'
|
||||
+ '<div class="stat"><div class="k">网站上是</div><div class="v">v' + VERSION + '</div><div class="s">点「发布记录」看历史</div></div>'
|
||||
+ '<div class="stat"><div class="k">画展作品</div><div class="v">' + S.gallery.filter(g => !g.hidden).length + '</div><div class="s">隐藏 ' + S.gallery.filter(g => g.hidden).length + ' 件</div></div>'
|
||||
+ '<div class="stat"><div class="k">世界线</div><div class="v">' + S.universe.items.length + '</div><div class="s">空槽 ' + S.universe.empty + ' 个</div></div>';
|
||||
const map = { '首页文案': 'hero', '板块说明': 'hero', '画展': 'gallery', '工具与开源': 'apps', '金钻宇宙': 'universe', '金钻宇宙 · 空槽': 'universe', '平台分组': 'links', '平台入口': 'links', '关于': 'about', '下单页模板': 'tpl', '下单页文字': 'tpl', '价格档位': 'price', '付款方式': 'price' };
|
||||
$('#dirtyList').innerHTML = CHANGES.length ? CHANGES.map(c => '<div class="item dirty"><div class="body"><div class="t">' + esc(c[0]) + '</div><div class="m">' + esc(dtxt(c)) + '</div></div><div class="acts"><button class="btn sm" type="button" data-jump="' + (map[c[0]] || 'home') + '">去看</button></div></div>').join('')
|
||||
+ '<div class="row" style="margin-top:6px"><button class="btn pri" type="button" id="homePub">发布这些改动</button><button class="btn bad" type="button" id="homeDiscard">全部丢掉</button></div>'
|
||||
: '<div class="empty">没有没发布的改动。改任何东西都会先存成草稿。</div>';
|
||||
$$('[data-jump]').forEach(b => b.onclick = () => go(b.dataset.jump));
|
||||
if ($('#homePub')) $('#homePub').onclick = openPublish;
|
||||
if ($('#homeDiscard')) $('#homeDiscard').onclick = discardAll;
|
||||
const a = await api('audit');
|
||||
$('#auditList').innerHTML = (a.audit || []).slice(0, 10).map(x => '<div class="item"><div class="body"><div class="t">' + esc(x.what) + '</div><div class="m">' + esc(fmt(x.at)) + ' · ' + esc(x.who) + ' · ' + esc(x.ip) + '</div></div></div>').join('') || '<div class="empty">还没有记录。</div>';
|
||||
}
|
||||
const dtxt = c => [c[1] && '新增 ' + c[1], c[2] && '改了 ' + c[2], c[3] && '删了 ' + c[3]].filter(Boolean).join(' · ');
|
||||
async function discardAll() {
|
||||
if (!confirm('丢掉所有没发布的改动?网站上的内容不受影响。')) return;
|
||||
clearTimeout(saveTimer); dirtyLocal = false;
|
||||
const j = await api('discard', {}); if (!j.ok) return toast(j.error || '丢不掉', true);
|
||||
await loadContent(); renderAll(); go('home'); toast('草稿已丢掉,回到网站上现在的内容');
|
||||
}
|
||||
|
||||
/* ------------------------------------------------ 首页文案 */
|
||||
const BOARD_NAMES = { gallery: '画展', apps: '工具与开源', universe: '金钻宇宙', links: '平台入口', about: '关于' };
|
||||
function renderHeroMini() {
|
||||
const h = DOC.site.hero, N = h.notice || {}, on = N.on && N.text;
|
||||
$('#heroMini').innerHTML = (on ? '<div class="notice">' + esc(N.text) + '</div>' : '') + '<h4 class="px">金钻客栈</h4><p>' + esc(h.tagline) + '</p>'
|
||||
+ '<div class="row"><span class="btn pri sm">' + esc(h.cta1 || '逛画展') + '</span><span class="btn sm">' + esc(h.cta2 || '金钻宇宙') + '</span></div>';
|
||||
}
|
||||
function renderBoards() {
|
||||
DOC.site.boards = DOC.site.boards || {};
|
||||
$('#boardFields').innerHTML = Object.entries(BOARD_NAMES).map(([k, n]) => '<label class="fld"><span>' + esc(n) + '</span><textarea class="in" rows="2" maxlength="120" data-bind="site.boards.' + k + '"></textarea></label>').join('');
|
||||
}
|
||||
|
||||
/* ------------------------------------------------ 抽屉 / 弹窗 */
|
||||
function openDrawer(title, html, foot) { $('#dTitle').textContent = title; $('#dBody').innerHTML = html; $('#dFoot').innerHTML = ''; foot.forEach(f => $('#dFoot').appendChild(f)); $('#scrim').classList.add('on'); $('#drawer').classList.add('on'); setTimeout(() => { const f = $('#dBody input,#dBody textarea'); if (f) f.focus(); }, 120); }
|
||||
function closeDrawer() { $('#scrim').classList.remove('on'); $('#drawer').classList.remove('on'); const cv = document.getElementById('uPlanetCv'); if (cv && PP) PP.stop(cv); }
|
||||
$('#dClose').onclick = closeDrawer; $('#scrim').onclick = closeDrawer;
|
||||
addEventListener('keydown', e => { if (e.key === 'Escape') { closeDrawer(); closeModal(); } });
|
||||
function openModal(html) { $('#mBox').innerHTML = html; $('#modal').classList.add('on'); }
|
||||
function closeModal() { $('#modal').classList.remove('on'); }
|
||||
$('#modal').onclick = e => { if (e.target.id === 'modal') closeModal(); };
|
||||
function bt(txt, cls, fn) { const b = document.createElement('button'); b.type = 'button'; b.className = 'btn ' + (cls || ''); b.textContent = txt; b.onclick = fn; return b; }
|
||||
function sp() { const s = document.createElement('span'); s.className = 'sp'; return s; }
|
||||
const fld = (label, inner, hint) => '<label class="fld"><span>' + label + (hint ? ' <span class="h">' + hint + '</span>' : '') + '</span>' + inner + '</label>';
|
||||
const inp = (id, v, extra) => '<input class="in" id="' + id + '" value="' + esc(v) + '" ' + (extra || '') + '>';
|
||||
const ta = (id, v, rows, extra) => '<textarea class="in" id="' + id + '" rows="' + (rows || 3) + '" ' + (extra || '') + '>' + esc(v) + '</textarea>';
|
||||
const sel = (id, opts, v) => '<select class="in" id="' + id + '">' + opts.map(o => '<option value="' + esc(o[0]) + '"' + (o[0] === v ? ' selected' : '') + '>' + esc(o[1]) + '</option>').join('') + '</select>';
|
||||
const val = id => document.getElementById(id).value;
|
||||
const dirtyIn = (list, key, item) => { const p = (list || []).find(x => x[key] === item[key]); return !p || !same(p, item); };
|
||||
function bad(id, msg) { const el = document.getElementById(id); if (el) { el.classList.add('err'); el.focus(); } toast(msg, true); return false; }
|
||||
|
||||
/* ------------------------------------------------ 画展 */
|
||||
let gF = 'all';
|
||||
const GTYPE = { image: '图片', video: '视频', pano: '全景', wall: '动态壁纸' };
|
||||
$('#gFilter').onclick = e => { const b = e.target.closest('button'); if (!b) return; gF = b.dataset.v; $$('#gFilter button').forEach(x => x.classList.toggle('on', x === b)); renderGallery(); };
|
||||
$('#gSearch').oninput = renderGallery;
|
||||
const imgUrl = p => p ? '../' + p.split('/').map(encodeURIComponent).join('/') : '';
|
||||
function renderGallery() {
|
||||
const kw = $('#gSearch').value.trim();
|
||||
const G = DOC.site.gallery;
|
||||
const rows = G.filter(g => (gF === 'all' ? true : gF === 'hidden' ? g.hidden : gF === 'special' ? (g.type === 'pano' || g.type === 'wall') : g.type === gF) && (!kw || (g.title + g.desc + g.date).includes(kw)))
|
||||
.sort((a, b) => String(b.date).localeCompare(String(a.date)));
|
||||
$('#gTiles').innerHTML = '<button type="button" class="drop" id="gDrop">+ 上传图片<small>拖到这里,或点一下选<br>PNG / JPEG / WebP,单张 ≤ 10MB</small></button>'
|
||||
+ rows.map(g => { const th = thumbOf(g);
|
||||
return '<button type="button" class="tile' + (dirtyIn(PUB.site.gallery, 'id', g) ? ' dirty' : '') + (g.hidden ? ' off' : '') + '" data-id="' + esc(g.id) + '">'
|
||||
+ '<div class="th" style="background-image:url("' + esc(imgUrl(th)) + '")"></div><div class="flags">' + (g.hidden ? '<span class="tag">隐藏</span>' : '') + (g.type !== 'image' ? '<span class="tag b">' + GTYPE[g.type] + '</span>' : '') + (g.owner === 'gift' ? '<span class="tag y">他人制作</span>' : '') + (g._up ? '<span class="tag g">处理中</span>' : '') + '</div>'
|
||||
+ '<div class="cap"><b>' + esc(g.title) + '</b><span>' + esc(g.date) + '</span>' + (g._up ? '<div class="prog"><i style="width:' + g._up + '%"></i></div>' : '') + '</div></button>'; }).join('');
|
||||
$('#gDrop').onclick = () => $('#gFile').click();
|
||||
const dz = $('#gDrop');
|
||||
['dragenter', 'dragover'].forEach(ev => dz.addEventListener(ev, e => { e.preventDefault(); dz.classList.add('over'); }));
|
||||
['dragleave', 'drop'].forEach(ev => dz.addEventListener(ev, e => { e.preventDefault(); dz.classList.remove('over'); }));
|
||||
dz.addEventListener('drop', e => upload([...e.dataTransfer.files]));
|
||||
$$('#gTiles .tile').forEach(t => t.onclick = () => { const g = DOC.site.gallery.find(x => x.id === t.dataset.id); if (g && !g._up) editGallery(g); });
|
||||
}
|
||||
$('#gFile').onchange = e => { upload([...e.target.files]); e.target.value = ''; };
|
||||
async function upload(files) {
|
||||
files = files.filter(f => /^image\/(png|jpeg|webp)$/.test(f.type));
|
||||
if (!files.length) return toast('只收 PNG / JPEG / WebP 图片', true);
|
||||
for (const f of files) {
|
||||
if (f.size > 10 * 1024 * 1024) { toast('「' + f.name + '」超过 10MB,没传', true); continue; }
|
||||
const tmp = { id: rid('g'), title: f.name.replace(/\.\w+$/, '').slice(0, 60), date: today(), type: 'image', owner: 'own', desc: '', hidden: false, _up: 10 };
|
||||
DOC.site.gallery.push(tmp); renderGallery();
|
||||
const data = await new Promise(res => { const r = new FileReader(); r.onload = () => res(r.result); r.onerror = () => res(''); r.readAsDataURL(f); });
|
||||
tmp._up = 45; renderGallery();
|
||||
const j = await api('upload', { name: f.name, data });
|
||||
const g = DOC.site.gallery.find(x => x.id === tmp.id);
|
||||
if (!j.ok) { DOC.site.gallery = DOC.site.gallery.filter(x => x.id !== tmp.id); renderGallery(); toast('「' + f.name + '」没传上:' + (j.error || ''), true); continue; }
|
||||
if (g) { delete g._up; Object.assign(g, { src: j.src, thumb: j.thumb, r: j.r }); }
|
||||
renderGallery(); mark(); toast('「' + tmp.title + '」传好了:核验通过、去掉了照片信息、缩略图已生成(存在草稿里,发布后上线)');
|
||||
}
|
||||
}
|
||||
$('#gVideo').onclick = () => { const g = { id: rid('g'), title: '', date: today(), type: 'video', owner: 'own', desc: '', url: '', hidden: false }; editGallery(g, true); };
|
||||
/* 作品的预览图:作品自带缩略图 → 离线缩略图索引(content 的 media)→ 封面 / 第一帧 → 原图(本站 mp4 不能当图片用) */
|
||||
function thumbOf(g) {
|
||||
const M = DOC.site.media || {}, first = g.poster || (g.frames && g.frames[0] && g.frames[0].src) || '';
|
||||
const isVid = /\.(mp4|webm)$/i.test(g.src || '');
|
||||
return g.thumb || (g.src && M[g.src] && M[g.src].t) || (first && M[first] && M[first].t) || first || (isVid ? '' : g.src) || '';
|
||||
}
|
||||
const localVid = g => g.type === 'video' && /\.(mp4|webm)$/i.test(g.src || '');
|
||||
function editGallery(g, isNew) {
|
||||
const th = thumbOf(g);
|
||||
openDrawer(isNew ? '加一个视频' : '编辑作品',
|
||||
(th ? '<div class="dimg" style="background-image:url("' + esc(imgUrl(th)) + '")"></div>' : '')
|
||||
+ fld('标题', inp('fTitle', g.title, 'maxlength="60"'))
|
||||
+ '<div class="fgrid">' + fld('日期', inp('fDate', g.date, 'type="date"')) + fld('类型', sel('fType', localVid(g) ? [['video', '视频(本站文件)']] : g.type === 'video' ? [['video', '视频(B 站)']] : (g.frames ? [['wall', '动态壁纸'], ['image', '图片']] : [['image', '图片'], ['pano', '全景(能拖着转一圈)']]), g.type)) + '</div>'
|
||||
+ fld('归属', sel('fOwner', [['own', '金钻制作'], ['gift', '他人制作(需授权)']], g.owner))
|
||||
+ fld('说明', ta('fDesc', g.desc, 3, 'maxlength="300"'), '(可空)')
|
||||
+ '<div id="fUrlWrap"' + (g.type === 'video' ? '' : ' hidden') + '>' + fld('B 站链接', inp('fUrl', g.url || '', 'placeholder="https://www.bilibili.com/video/BV…"'), localVid(g) ? '(本站视频,可空;填了就多一个「去 B 站看」)' : '(视频不上传,只填链接)') + '</div>'
|
||||
+ '<label class="switch"><input type="checkbox" id="fHidden"' + (g.hidden ? ' checked' : '') + '><i></i>在网站上隐藏</label>',
|
||||
[isNew ? sp() : bt('删掉', 'bad', () => { if (!confirm('删掉「' + g.title + '」?发布后网站上就没了(发布记录里还能找回)。')) return; DOC.site.gallery = DOC.site.gallery.filter(x => x.id !== g.id); closeDrawer(); renderGallery(); mark(); }), sp(), bt('取消', '', closeDrawer),
|
||||
bt('存进草稿', 'pri', () => {
|
||||
const t = val('fType'), u = val('fUrl').trim();
|
||||
if (!val('fTitle').trim()) return bad('fTitle', '标题不能空');
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(val('fDate'))) return bad('fDate', '日期要填完整');
|
||||
if (t === 'video' && !localVid(g) && !/^https:\/\//i.test(u)) return bad('fUrl', '视频要填 https:// 开头的 B 站链接');
|
||||
if (u && !/^https:\/\//i.test(u)) return bad('fUrl', '链接要 https:// 开头');
|
||||
Object.assign(g, { title: val('fTitle').trim(), date: val('fDate'), type: t, owner: val('fOwner'), desc: val('fDesc'), hidden: document.getElementById('fHidden').checked });
|
||||
if (t === 'video') g.url = u; else delete g.url;
|
||||
if (isNew) DOC.site.gallery.push(g); closeDrawer(); renderGallery(); mark(); toast('存进草稿了(发布后上线)'); })]);
|
||||
document.getElementById('fType').onchange = e => { document.getElementById('fUrlWrap').hidden = e.target.value !== 'video'; };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------ 工具与开源 */
|
||||
function renderApps() {
|
||||
$('#appList').innerHTML = DOC.site.apps.map(a => '<div class="item' + (dirtyIn(PUB.site.apps, 'id', a) ? ' dirty' : '') + '"><div class="body"><div class="t">' + esc(a.name) + ' <span class="tag ' + (a.oss ? 'g' : 'b') + '">' + (a.oss ? '开源' : '闭源') + '</span>' + (a.type ? '<span class="tag">' + esc(a.type) + '</span>' : '') + (a.url ? '' : '<span class="tag y">待上架</span>') + '</div><div class="m">' + esc(a.desc) + '</div></div><div class="acts"><button class="btn sm" type="button" data-app="' + esc(a.id) + '">编辑</button></div></div>').join('') || '<div class="empty">还没有。</div>';
|
||||
$$('[data-app]').forEach(b => b.onclick = () => editApp(DOC.site.apps.find(a => a.id === b.dataset.app)));
|
||||
}
|
||||
$('#appAdd').onclick = () => editApp({ id: rid('a'), name: '', en: '', type: '小工具', oss: true, desc: '', ver: '', size: '', status: '待上架', url: '', repo: '' }, true);
|
||||
function editApp(a, isNew) {
|
||||
openDrawer(isNew ? '加一个工具' : '编辑工具',
|
||||
'<div class="fgrid">' + fld('名称', inp('aName', a.name, 'maxlength="30"')) + fld('英文名', inp('aEn', a.en, 'maxlength="40"'), '(标题旁的小字)') + '</div>'
|
||||
+ '<div class="fgrid">' + fld('类型', inp('aType', a.type, 'maxlength="12"')) + fld('开源 / 闭源', sel('aOss', [['1', '开源'], ['0', '闭源']], a.oss ? '1' : '0')) + '</div>'
|
||||
+ fld('一句话介绍', ta('aDesc', a.desc, 3, 'maxlength="300"'))
|
||||
+ '<div class="fgrid">' + fld('版本', inp('aVer', a.ver, 'maxlength="24"')) + fld('状态', inp('aStatus', a.status, 'maxlength="12"')) + '</div>'
|
||||
+ '<div class="fgrid">' + fld('大小', inp('aSize', a.size || '', 'maxlength="16"'), '(可空)') + fld('按钮文字', inp('aBtn', a.btn || '', 'maxlength="16" placeholder="下载 ↓"'), '(可空)') + '</div>'
|
||||
+ fld('打开链接', inp('aUrl', a.url, 'placeholder="https://… 或站内路径 /order/"'), '(空 = 待上架)')
|
||||
+ '<label class="switch" style="margin:-4px 0 14px"><input type="checkbox" id="aWeb"' + (a.web ? ' checked' : '') + '><i></i>是网页(按钮写「在线体验」,不是下载)</label>'
|
||||
+ fld('源码仓库', inp('aRepo', a.repo, 'placeholder="https://…"'), '(可空)'),
|
||||
[isNew ? sp() : bt('删掉', 'bad', () => { if (!confirm('删掉「' + a.name + '」?')) return; DOC.site.apps = DOC.site.apps.filter(x => x.id !== a.id); closeDrawer(); renderApps(); mark(); }), sp(), bt('取消', '', closeDrawer),
|
||||
bt('存进草稿', 'pri', () => {
|
||||
if (!val('aName').trim()) return bad('aName', '名称不能空');
|
||||
const u = val('aUrl').trim(), r = val('aRepo').trim();
|
||||
if (u && !/^https:\/\//i.test(u) && !/^\/[A-Za-z0-9_\-./]*$/.test(u)) return bad('aUrl', '链接要以 https:// 开头,或站内路径(/ 开头)');
|
||||
if (r && !/^https:\/\//i.test(r)) return bad('aRepo', '仓库链接要以 https:// 开头');
|
||||
Object.assign(a, { name: val('aName').trim(), en: val('aEn').trim(), type: val('aType').trim(), oss: val('aOss') === '1', desc: val('aDesc'), ver: val('aVer'), status: val('aStatus'), size: val('aSize'), url: u, repo: r, web: document.getElementById('aWeb').checked });
|
||||
const b = val('aBtn').trim(); if (b) a.btn = b; else delete a.btn;
|
||||
if (isNew) DOC.site.apps.push(a); closeDrawer(); renderApps(); mark(); toast('存进草稿了'); })]);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------ 金钻宇宙 */
|
||||
const STYLES = [['earth', '类地(卡通地球)'], ['ocean', '海洋'], ['jungle', '丛林'], ['desert', '荒漠'], ['tundra', '冻原'], ['ice', '冰封'], ['lava', '熔岩'], ['toxic', '毒雾'],
|
||||
['barren', '荒芜岩球'], ['gas', '气态巨星'], ['icegiant', '冰巨星'], ['ringed', '带环巨星'], ['crystal', '晶体'], ['paper', '铅笔纸面'], ['neon', '霓虹城'], ['duality', '善恶两半'], ['rock', '小行星']];
|
||||
const ENTERS = [['push', '推进'], ['zoom', '放大(长焦再推)'], ['rise', '升空俯冲'], ['warp', '跃迁'], ['orbit', '绕行']];
|
||||
const ACCENTS = ['#FFD36E', '#F6F1E4', '#9FE3FF', '#C9A6FF', '#FF9DB8', '#7FE0A8', '#FFB074', '#8E96C8'];
|
||||
let PP = null;
|
||||
async function ensurePP() { if (!PP && window.__pp) PP = await window.__pp.boot(); return PP; }
|
||||
async function renderUni(withPresets) {
|
||||
const U = DOC.site.universe;
|
||||
$('#uniCount').textContent = '已点亮 ' + U.items.length + ' 条';
|
||||
const pp = withPresets ? await ensurePP() : PP;
|
||||
$('#uniList').innerHTML = U.items.map(u => '<div class="item' + (dirtyIn(PUB.site.universe.items, 'no', u) ? ' dirty' : '') + '">'
|
||||
+ (pp ? '<span class="sw img" style="background-image:url(' + pp.thumb(u.look.style) + ')"></span>' : '<span class="sw" style="background:' + esc(u.look.accent) + '"></span>')
|
||||
+ '<div class="body"><div class="t"><span style="font-family:var(--mono);color:var(--dim);font-weight:600">' + esc(u.no) + '</span>' + esc(u.name) + '<span class="tag">' + esc(u.kind) + '</span></div><div class="m">' + esc(u.tag) + ' · ' + esc((STYLES.find(s => s[0] === u.look.style) || [, u.look.style])[1]) + (u.look.enter ? ' · 入场' + esc((ENTERS.find(s => s[0] === u.look.enter) || [, ''])[1]) : '') + '</div></div><div class="acts"><button class="btn sm" type="button" data-uni="' + esc(u.no) + '">编辑</button></div></div>').join('') || '<div class="empty">还没有点亮的世界线。</div>';
|
||||
$$('[data-uni]').forEach(b => b.onclick = () => editUni(DOC.site.universe.items.find(u => u.no === b.dataset.uni)));
|
||||
if (withPresets && pp && !$('#presetGrid canvas')) {
|
||||
const g = $('#presetGrid'); g.innerHTML = '';
|
||||
STYLES.forEach(([k, n]) => {
|
||||
const d = document.createElement('div'); d.className = 'pre';
|
||||
const cv = document.createElement('canvas'); cv.width = cv.height = 220; d.append(cv);
|
||||
d.insertAdjacentHTML('beforeend', '<b>' + esc(n) + '</b><code>' + esc(k) + '</code>');
|
||||
d.append(bt('用它点亮', 'sm', () => lightNew(k)));
|
||||
g.append(d); pp.live(cv, k);
|
||||
});
|
||||
} else if (withPresets && !pp) $('#presetGrid').innerHTML = '<div class="empty">这台设备打不开 3D 预览(下拉照样能选)。</div>';
|
||||
}
|
||||
function lightNew(style) {
|
||||
const nos = DOC.site.universe.items.map(u => +u.no);
|
||||
const no = String((nos.length ? Math.max(...nos) : -1) + 1).padStart(4, '0');
|
||||
editUni({ no, name: '', kind: '原创', tag: '', desc: '', tags: [], look: { style: style || 'earth', accent: '#7FE0A8', enter: 'push' } }, true);
|
||||
}
|
||||
$('#uniAdd').onclick = () => lightNew();
|
||||
async function editUni(u, isNew) {
|
||||
const L = u.look || {};
|
||||
openDrawer(isNew ? '点亮世界线 ' + u.no : '世界线 ' + u.no,
|
||||
(isNew ? '<p class="h" style="margin:0 0 10px">新点亮的会自动排到中圈一个不挤的位置,补给线接到附近的星上;已有的星系、卫星和连线都不动。</p>' : '')
|
||||
+ '<div class="stage-mini"><canvas id="uPlanetCv" width="300" height="300"></canvas>星系图上的样子<b id="uPName">' + esc(u.name || '未命名') + '</b></div>'
|
||||
+ '<div class="fgrid">' + fld('名字', inp('uName', u.name, 'maxlength="12"')) + fld('类型', sel('uKind', [['主宇宙', '主宇宙'], ['原创', '原创'], ['二创', '二创']], u.kind)) + '</div>'
|
||||
+ fld('一句话', inp('uTag', u.tag, 'maxlength="24"')) + fld('简介', ta('uDesc', u.desc, 4, 'maxlength="600"')) + fld('标签', inp('uTags', (u.tags || []).join(',')), '(用逗号隔开,最多 10 个)')
|
||||
+ '<div class="fgrid">' + fld('星球风格', sel('uStyle', STYLES, L.style)) + fld('入场运镜', sel('uEnter', ENTERS, L.enter || 'push'), '(点开这颗星时镜头怎么飞)') + '</div>'
|
||||
+ '<div class="fld"><span>主色 <span class="h">(名牌、档案卡左边那条线)</span></span><div class="swatches" id="uSw">' + ACCENTS.map(c => '<button type="button" data-c="' + c + '" style="background:' + c + '"' + (c === L.accent ? ' class="on"' : '') + ' aria-label="' + c + '"></button>').join('') + '</div></div>',
|
||||
[isNew ? sp() : bt('熄灭', 'bad', () => { if (!confirm('熄灭「' + u.name + '」?星系图上它会消失(发布记录里还能找回)。')) return; DOC.site.universe.items = DOC.site.universe.items.filter(x => x.no !== u.no); closeDrawer(); renderUni(); mark(); }), sp(), bt('取消', '', closeDrawer),
|
||||
bt('存进草稿', 'pri', () => {
|
||||
if (!val('uName').trim()) return bad('uName', '名字不能空');
|
||||
const tags = val('uTags').split(/[,,、]/).map(s => s.trim()).filter(Boolean);
|
||||
if (tags.length > 10) return bad('uTags', '标签最多 10 个');
|
||||
Object.assign(u, { name: val('uName').trim(), kind: val('uKind'), tag: val('uTag'), desc: val('uDesc'), tags });
|
||||
u.look = Object.assign({}, L, { style: val('uStyle'), enter: val('uEnter'), accent: pick });
|
||||
if (isNew) DOC.site.universe.items.push(u); closeDrawer(); renderUni(); mark(); toast('存进草稿了'); })]);
|
||||
let pick = L.accent || '#7FE0A8';
|
||||
const pp = await ensurePP();
|
||||
const paint = () => { const cv = document.getElementById('uPlanetCv'); if (cv && pp) pp.live(cv, val('uStyle'));
|
||||
const n = document.getElementById('uPName'); if (n) { n.textContent = val('uName') || '未命名'; n.style.color = pick; } };
|
||||
paint(); document.getElementById('uStyle').onchange = paint; document.getElementById('uName').oninput = paint;
|
||||
$('#uSw').onclick = e => { const b = e.target.closest('button'); if (!b) return; pick = b.dataset.c; $$('#uSw button').forEach(x => x.classList.toggle('on', x === b)); paint(); };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------ 平台入口 */
|
||||
const ICONS = [['bili', '哔哩哔哩'], ['douyin', '抖音'], ['kuaishou', '快手'], ['xiaohongshu', '小红书'], ['cgmodel', 'CG模型网'], ['codemao', '编程猫'], ['steam', 'Steam'], ['lang', '语言包'], ['github', 'GitHub'], ['workshop', 'B站工坊'], ['xianyu', '闲鱼'], ['mail', '邮箱']];
|
||||
function renderLinks() {
|
||||
const S = DOC.site;
|
||||
$('#linkGroups').innerHTML = S.linkGroups.map(gr => {
|
||||
const ls = S.links.filter(l => l.group === gr.id);
|
||||
return '<div class="card"><h2>' + esc(gr.name) + ' <span class="sub">' + esc(gr.en) + ' · ' + ls.length + ' 个</span></h2><div class="list">'
|
||||
+ (ls.length ? ls.map((l, i) => '<div class="item' + (dirtyIn(PUB.site.links, 'id', l) ? ' dirty' : '') + '"><div class="body"><div class="t">' + esc(l.name) + '</div><div class="m">' + esc(l.desc) + ' · ' + esc(l.url) + '</div></div><div class="acts">'
|
||||
+ '<button class="btn sm" type="button" data-up="' + esc(l.id) + '"' + (i ? '' : ' disabled') + ' aria-label="往上挪">↑</button><button class="btn sm" type="button" data-dn="' + esc(l.id) + '"' + (i < ls.length - 1 ? '' : ' disabled') + ' aria-label="往下挪">↓</button><button class="btn sm" type="button" data-link="' + esc(l.id) + '">编辑</button></div></div>').join('')
|
||||
: '<div class="empty">这一组还没有。</div>') + '</div></div>';
|
||||
}).join('');
|
||||
$$('[data-link]').forEach(b => b.onclick = () => editLink(DOC.site.links.find(l => l.id === b.dataset.link)));
|
||||
const move = (id, d) => { const L = DOC.site.links, i = L.findIndex(l => l.id === id), g = L[i].group; let j = i + d; while (j >= 0 && j < L.length && L[j].group !== g) j += d; if (j < 0 || j >= L.length) return; [L[i], L[j]] = [L[j], L[i]]; renderLinks(); mark(); };
|
||||
$$('[data-up]').forEach(b => b.onclick = () => move(b.dataset.up, -1)); $$('[data-dn]').forEach(b => b.onclick = () => move(b.dataset.dn, 1));
|
||||
}
|
||||
$('#linkAdd').onclick = () => editLink({ id: rid('l'), group: (DOC.site.linkGroups[0] || {}).id || '', key: 'bili', name: '', en: '', desc: '', url: '' }, true);
|
||||
function editLink(l, isNew) {
|
||||
openDrawer(isNew ? '加一个入口' : '编辑入口',
|
||||
'<div class="fgrid">' + fld('分组', sel('lGroup', DOC.site.linkGroups.map(g => [g.id, g.name]), l.group)) + fld('图标', sel('lKey', ICONS.some(x => x[0] === l.key) ? ICONS : ICONS.concat([[l.key, l.key]]), l.key)) + '</div>'
|
||||
+ '<div class="fgrid">' + fld('名称', inp('lName', l.name, 'maxlength="20"')) + fld('英文名', inp('lEn', l.en, 'maxlength="24"')) + '</div>'
|
||||
+ fld('说明', inp('lDesc', l.desc, 'maxlength="40"'))
|
||||
+ fld('链接', inp('lUrl', l.url, 'placeholder="https://… 或 mailto:…"'), '(只收 https:// 和 mailto:)') + '<span class="errtxt" id="lErr"></span>',
|
||||
[isNew ? sp() : bt('删掉', 'bad', () => { if (!confirm('删掉「' + l.name + '」?')) return; DOC.site.links = DOC.site.links.filter(x => x.id !== l.id); closeDrawer(); renderLinks(); mark(); }), sp(), bt('取消', '', closeDrawer),
|
||||
bt('存进草稿', 'pri', () => {
|
||||
const u = val('lUrl').trim();
|
||||
if (!urlOk(u)) { $('#lErr').textContent = u.toLowerCase().startsWith('http://') ? '要用 https://(http 不安全,网站会拦下)' : '链接格式不对:只收 https:// 开头的网址或 mailto: 邮箱'; return bad('lUrl', '链接格式不对'); }
|
||||
if (!val('lName').trim()) return bad('lName', '名称不能空');
|
||||
Object.assign(l, { group: val('lGroup'), key: val('lKey'), name: val('lName').trim(), en: val('lEn').trim(), desc: val('lDesc').trim(), url: u });
|
||||
if (isNew) DOC.site.links.push(l); closeDrawer(); renderLinks(); mark(); toast('存进草稿了'); })]);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------ 关于 */
|
||||
function renderAbout() {
|
||||
const C = DOC.site.about.cards;
|
||||
$('#aboutCards').innerHTML = C.map((c, i) => '<div class="item' + (same(PUB.site.about.cards[i], c) ? '' : ' dirty') + '"><div class="body"><div class="t"><span class="tag">' + esc(c.k) + '</span>' + esc(c.h) + '</div><div class="m">' + esc(c.p) + '</div></div><div class="acts">'
|
||||
+ '<button class="btn sm" type="button" data-cu="' + i + '"' + (i ? '' : ' disabled') + ' aria-label="往上挪">↑</button><button class="btn sm" type="button" data-cd="' + i + '"' + (i < C.length - 1 ? '' : ' disabled') + ' aria-label="往下挪">↓</button><button class="btn sm" type="button" data-ab="' + i + '">编辑</button></div></div>').join('') || '<div class="empty">还没有卡片。</div>';
|
||||
$$('[data-ab]').forEach(b => b.onclick = () => editCard(C[+b.dataset.ab]));
|
||||
const mv = (i, d) => { const j = i + d; if (j < 0 || j >= C.length) return; [C[i], C[j]] = [C[j], C[i]]; renderAbout(); mark(); };
|
||||
$$('[data-cu]').forEach(b => b.onclick = () => mv(+b.dataset.cu, -1)); $$('[data-cd]').forEach(b => b.onclick = () => mv(+b.dataset.cd, 1));
|
||||
}
|
||||
$('#cardAdd').onclick = () => editCard({ k: '', h: '', p: '' }, true);
|
||||
function editCard(c, isNew) {
|
||||
openDrawer(isNew ? '加一张卡片' : '署名卡片', fld('小标题', inp('cK', c.k, 'maxlength="16"')) + fld('名字', inp('cH', c.h, 'maxlength="30"')) + fld('内容', ta('cP', c.p, 6, 'maxlength="600"'), '([文字](https://网址) 是链接,`文字` 是代码样式,空一行是新段落)'),
|
||||
[isNew ? sp() : bt('删掉', 'bad', () => { if (!confirm('删掉这张卡片?')) return; DOC.site.about.cards = DOC.site.about.cards.filter(x => x !== c); closeDrawer(); renderAbout(); mark(); }), sp(), bt('取消', '', closeDrawer),
|
||||
bt('存进草稿', 'pri', () => { if (!val('cH').trim()) return bad('cH', '名字不能空');
|
||||
Object.assign(c, { k: val('cK').trim(), h: val('cH').trim(), p: val('cP') }); if (isNew) DOC.site.about.cards.push(c); closeDrawer(); renderAbout(); mark(); toast('存进草稿了'); })]);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------ 下单页 */
|
||||
function renderTpl() {
|
||||
const T = DOC.order.templates;
|
||||
$('#tplList').innerHTML = T.map((t, i) => '<div class="item' + (t.on ? '' : ' off') + (same((PUB.order.templates || []).find(x => x.k === t.k), t) ? '' : ' dirty') + '"><label class="switch" title="在下单页上给买家选"><input type="checkbox" data-ton="' + i + '"' + (t.on ? ' checked' : '') + '><i></i></label><div class="body"><div class="t">' + esc(t.n) + ' <span class="tag" style="font-family:var(--mono)">' + esc(t.k) + '</span></div><div class="m">' + esc(t.s) + '</div></div><div class="acts"><button class="btn sm" type="button" data-tp="' + i + '">编辑</button></div></div>').join('');
|
||||
$$('[data-ton]').forEach(c => c.onchange = () => { const t = T[+c.dataset.ton];
|
||||
if (!c.checked && T.filter(x => x.on).length <= 1) { c.checked = true; return toast('至少要留一个模板上架', true); }
|
||||
t.on = c.checked; renderTpl(); mark(); });
|
||||
$$('[data-tp]').forEach(b => b.onclick = () => { const t = T[+b.dataset.tp];
|
||||
openDrawer('模板 ' + t.k, '<p class="h" style="margin:0 0 14px">英文 key「' + esc(t.k) + '」渲染机要认,这里改不了;只改下单页上显示的名字和说明。缩略图在 <code>/order/tpl/' + esc(t.k) + '.jpg</code>。</p>' + fld('显示名字', inp('tN', t.n, 'maxlength="12"')) + fld('一句话说明', inp('tS', t.s, 'maxlength="24"')),
|
||||
[sp(), bt('取消', '', closeDrawer), bt('存进草稿', 'pri', () => { if (!val('tN').trim()) return bad('tN', '名字不能空'); Object.assign(t, { n: val('tN').trim(), s: val('tS').trim() }); closeDrawer(); renderTpl(); mark(); toast('存进草稿了'); })]); });
|
||||
}
|
||||
function renderTiers() {
|
||||
const T = DOC.order.prices.tiers;
|
||||
$('#tierRows').innerHTML = T.map((t, i) => '<tr><td><input class="in" type="number" min="1" max="10" value="' + esc(t.n) + '" data-ti="' + i + '" data-k="n" style="width:70px" aria-label="张数"></td><td><input class="in" type="number" min="0" step="0.01" value="' + esc(t.price) + '" data-ti="' + i + '" data-k="price" style="width:90px" aria-label="价格"></td><td><input class="in" value="' + esc(t.url) + '" data-ti="' + i + '" data-k="url" placeholder="https://…" aria-label="链接"></td><td><button class="btn sm bad" type="button" data-tdel="' + i + '" aria-label="删掉这一档">删</button></td></tr>').join('')
|
||||
|| '<tr><td colspan="4" class="h">还没配档位:全部按单价 × 张数算。</td></tr>';
|
||||
$$('[data-ti]').forEach(el => el.oninput = () => { const t = T[+el.dataset.ti], k = el.dataset.k;
|
||||
if (k === 'url') { const ok = !el.value || /^https:\/\//i.test(el.value); el.classList.toggle('err', !ok); if (!ok) return; t.url = el.value; } else t[k] = Number(el.value || 0); mark(); });
|
||||
$$('[data-tdel]').forEach(b => b.onclick = () => { T.splice(+b.dataset.tdel, 1); renderTiers(); mark(); });
|
||||
}
|
||||
$('#tierAdd').onclick = () => { const T = DOC.order.prices.tiers; let n = 2; while (T.some(t => t.n === n) && n < 10) n++; T.push({ n, price: Math.round(DOC.order.prices.per * n), url: '' }); renderTiers(); mark(); };
|
||||
|
||||
/* ------------------------------------------------ 预览 / 发布 / 回滚 */
|
||||
$('#prevBtn').onclick = async () => {
|
||||
await flush();
|
||||
openModal('<h3>预览草稿</h3><p>用草稿内容打开网站,只有登录了内容后台的你看得到;访客看到的还是已发布的内容。</p>'
|
||||
+ '<div class="list"><a class="item" href="../?preview=1" target="_blank" rel="noopener"><div class="body"><div class="t">门户(草稿)</div><div class="m">首页 / 画展 / 工具 / 宇宙 / 平台入口 / 关于</div></div></a>'
|
||||
+ '<a class="item" href="/order/?preview=1" target="_blank" rel="noopener"><div class="body"><div class="t">下单页(草稿)</div><div class="m">模板上下架 / 名字说明、页头、公告(价格要发布后才变)</div></div></a></div>'
|
||||
+ '<div class="mf"><button class="btn" type="button" onclick="closeModal()">知道了</button></div>');
|
||||
};
|
||||
async function openPublish() {
|
||||
if (DOC.site.gallery.some(g => g._up)) return toast('还有图在上传,等传完再发布', true);
|
||||
await flush();
|
||||
if (dirtyLocal) return toast('最新的改动没存上(看右上角的提示),先改好再发布 —— 不然发出去的是上一次存上的草稿', true);
|
||||
if (!CHANGES.length) return toast('没有要发布的改动');
|
||||
openModal('<h3>发布这些改动</h3><p>发布后马上出现在网站上。每次发布都留一份完整版本,随时能回到之前的版本。</p>'
|
||||
+ '<ul class="chg">' + CHANGES.map(c => '<li><b>' + esc(c[0]) + '</b><span>' + esc(dtxt(c)) + '</span></li>').join('') + '</ul>'
|
||||
+ '<label class="fld"><span>这次改了什么 <span class="h">(可空,写给以后的自己看)</span></span><input class="in" id="pubNote" maxlength="60" placeholder="例:画展补了三张 / 换了国庆公告"></label>'
|
||||
+ '<div class="mf"><button class="btn" type="button" onclick="closeModal()">再看看</button><button class="btn pri" type="button" id="pubGo">发布 v' + (VERSION + 1) + '</button></div>');
|
||||
$('#pubGo').onclick = async () => {
|
||||
$('#pubGo').disabled = true;
|
||||
const j = await api('publish', { note: $('#pubNote').value.trim(), base: BASE });
|
||||
if (!j.ok) { $('#pubGo').disabled = false;
|
||||
if (j.conflict) { closeModal(); conflictModal(j.error); return; }
|
||||
return toast(j.error || '发布失败', true); }
|
||||
closeModal(); await loadContent(); renderAll(); go(PANE); toast('v' + j.version + ' 已发布,网站上已经是新内容');
|
||||
};
|
||||
}
|
||||
$('#pubBtn').onclick = openPublish;
|
||||
/* 别人在你编辑期间发布过:二选一 —— 丢掉自己的草稿看网站上现在的,或者确认后用自己的草稿覆盖发布 */
|
||||
function conflictModal(msg) {
|
||||
openModal('<h3>别人刚发布过</h3><p>' + esc(msg) + '</p><p>可以先去「发布记录」看对方改了什么。然后:</p>'
|
||||
+ '<div class="mf"><button class="btn" type="button" onclick="closeModal()">先不发</button><button class="btn bad" type="button" id="cfDrop">丢掉我的草稿</button><button class="btn pri" type="button" id="cfMine">用我的草稿覆盖发布</button></div>');
|
||||
$('#cfDrop').onclick = async () => { closeModal(); clearTimeout(saveTimer); dirtyLocal = false; await api('discard', {}); await loadContent(); renderAll(); go('home'); toast('已丢掉你的草稿,现在显示的是网站上的内容'); };
|
||||
$('#cfMine').onclick = async () => {
|
||||
if (!confirm('确定用你的草稿覆盖?对方那次发布的改动会被你的版本盖掉(发布记录里还能找回)。')) return;
|
||||
closeModal();
|
||||
const mine = clone(DOC); await loadContent(); DOC = mine; BASE = VERSION; dirtyLocal = true;
|
||||
if (!(await save())) return;
|
||||
const j = await api('publish', { note: '覆盖发布(基于 v' + VERSION + ')', base: VERSION });
|
||||
if (!j.ok) return toast(j.error || '发布失败', true);
|
||||
await loadContent(); renderAll(); go(PANE); toast('v' + j.version + ' 已发布');
|
||||
};
|
||||
}
|
||||
async function renderVersions() {
|
||||
const j = await api('versions');
|
||||
const V = j.versions || [];
|
||||
$('#verList').innerHTML = V.map((v, i) => '<div class="ver' + (i ? '' : ' cur') + '"><span class="dotc">v' + v.no + '</span><div class="body"><div class="t">' + esc(v.note || '(没写说明)') + (i ? '' : ' <span class="tag g">网站上是这一版</span>') + '</div><div class="m">' + esc(fmt(v.at)) + ' · ' + esc(v.by) + ' · ' + esc(v.chg) + '</div></div>'
|
||||
+ (i ? '<div class="acts"><button class="btn sm" type="button" data-rb="' + v.no + '">回到这一版</button></div>' : '') + '</div>').join('') || '<div class="empty">还没有发布过。</div>';
|
||||
$$('[data-rb]').forEach(b => b.onclick = () => { const no = +b.dataset.rb;
|
||||
openModal('<h3>回到 v' + no + '?</h3><p>会把 v' + no + ' 的内容当成新的一版(v' + (VERSION + 1) + ')发布出去;现在这版不会丢,还在记录里,随时能再回来。</p>'
|
||||
+ (CHANGES.length ? '<p style="color:var(--warn-t)">你还有没发布的改动,回滚会把它们一起丢掉。</p>' : '')
|
||||
+ '<div class="mf"><button class="btn" type="button" onclick="closeModal()">算了</button><button class="btn pri" type="button" id="rbGo">回到 v' + no + '</button></div>');
|
||||
$('#rbGo').onclick = async () => { $('#rbGo').disabled = true; clearTimeout(saveTimer); dirtyLocal = false;
|
||||
const r = await api('rollback', { no }); if (!r.ok) { $('#rbGo').disabled = false; return toast(r.error || '回不去', true); }
|
||||
closeModal(); await loadContent(); renderAll(); renderVersions(); toast('已回到 v' + no + '(记为 v' + r.version + ')'); }; });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------ 账号与设备 */
|
||||
async function renderAccount() {
|
||||
$('#meLine').textContent = '登录账号:' + ME.user + (ME.email ? '(' + ME.email + ')' : '') + '。忘了密码在服务器上跑 admin.py user reset。';
|
||||
const j = await api('sessions');
|
||||
const S = j.sessions || [];
|
||||
$('#sessList').innerHTML = S.map(s => '<div class="item"><div class="body"><div class="t">' + esc(uaName(s.ua)) + (s.cur ? ' <span class="tag g">这台</span>' : '') + (s.remember ? ' <span class="tag">记住我</span>' : '') + '</div><div class="m">' + esc(s.ip) + ' · 最近 ' + esc(fmt(s.last)) + '</div></div>' + (s.cur ? '' : '<div class="acts"><button class="btn sm bad" type="button" data-kill="' + esc(s.id) + '">退出</button></div>') + '</div>').join('') || '<div class="empty">没有。</div>';
|
||||
$$('[data-kill]').forEach(b => b.onclick = async () => { const r = await api('sessions/revoke', { id: b.dataset.kill }); toast(r.ok ? '那台设备已退出' : (r.error || '退不掉'), !r.ok); renderAccount(); });
|
||||
$('#killAll').disabled = S.length < 2;
|
||||
}
|
||||
function uaName(ua) { ua = ua || ''; const os = /iPhone|iPad/.test(ua) ? 'iPhone / iPad' : /Android/.test(ua) ? '安卓' : /Mac OS/.test(ua) ? 'Mac' : /Windows/.test(ua) ? 'Windows' : /Linux/.test(ua) ? 'Linux' : '设备';
|
||||
const br = /Edg\//.test(ua) ? 'Edge' : /Chrome\//.test(ua) ? 'Chrome' : /Firefox\//.test(ua) ? 'Firefox' : /Safari\//.test(ua) ? 'Safari' : '浏览器'; return os + ' · ' + br; }
|
||||
$('#killAll').onclick = async () => { if (!confirm('退出除这台以外的所有设备?')) return; const r = await api('sessions/revoke', { others: true }); toast(r.ok ? '其它设备都已退出' : (r.error || '退不掉'), !r.ok); renderAccount(); };
|
||||
$('#pwForm').onsubmit = async e => {
|
||||
e.preventDefault();
|
||||
if ($('#pwNew').value !== $('#pwAgain').value) return toast('两次输的新密码不一样', true);
|
||||
const r = await api('password', { old: $('#pwOld').value, new: $('#pwNew').value });
|
||||
if (!r.ok) return toast(r.error || '改不了', true);
|
||||
e.target.reset(); renderAccount(); toast('密码改好了,其它设备都已退出');
|
||||
};
|
||||
|
||||
/* ------------------------------------------------ 启动 */
|
||||
function renderAll() { renderBoards(); bindFields(); renderHeroMini(); renderGallery(); renderApps(); renderUni(false); renderLinks(); renderAbout(); renderTpl(); renderTiers(); refreshCounts(); setSaving(''); }
|
||||
async function start() {
|
||||
if (!(await loadContent())) return;
|
||||
renderAll();
|
||||
let p = 'home'; try { p = (location.hash.match(/^#\/(\w+)/) || [])[1] || 'home'; } catch (e) {}
|
||||
go(p);
|
||||
}
|
||||
addEventListener('beforeunload', e => { if (dirtyLocal || saving) { e.preventDefault(); e.returnValue = ''; } });
|
||||
(async () => {
|
||||
const j = await api('me');
|
||||
if (j.ok) { CSRF = j.csrf; ME = { user: j.user, email: j.email, must_change: j.must_change }; gate(); if (!ME.must_change) start(); }
|
||||
else if (j.status === 403 && /https/.test(j.error || '')) { document.body.innerHTML = '<div class="gate"><div class="gbox"><h1>只能用 https 打开</h1><p class="sub">内容后台要输密码,必须走 https。请用 https:// 开头的地址重新打开。</p></div></div>'; }
|
||||
else { ME = null; gate(); }
|
||||
})();
|
||||
</script>
|
||||
</body></html>
|
||||
Binary file not shown.
@@ -0,0 +1,94 @@
|
||||
/* 金钻客栈 · 加载动画(2026-10-06 重做)
|
||||
---------------------------------------------------------------------------
|
||||
像素钻石一块一块从上面落下来、从底往上垒成形(像 MC 里堆方块)→ 一道白光扫过钻石 →「金钻客栈」逐字弹出
|
||||
→ 底下一条光谱色进度条跟着页面真实加载走 → 整块幕布往上收起,露出页面。
|
||||
· 只在这个标签页第一次打开网站时放(sessionStorage 记一下),之后站内换页不再放;
|
||||
· 系统设置了「减少动效」就完全不放(页面里那段内联脚本直接把幕布删掉);
|
||||
· 最少放 1.25 秒(垒完 + 白光扫过;太短一闪而过很怪),页面 3 秒还没加载完也照样收起,绝不卡人。 */
|
||||
(function () {
|
||||
'use strict';
|
||||
var boot = document.getElementById('jzBoot');
|
||||
if (!boot) return;
|
||||
var root = document.documentElement;
|
||||
var cv = boot.querySelector('canvas'), ctx = cv.getContext('2d'), bar = boot.querySelector('.jz-boot-bar i');
|
||||
var name = boot.querySelector('.jz-boot-name');
|
||||
var N = 14, CELL = cv.width / N, T0 = performance.now(), MIN = 1250, MAX = 3000, done = false, ready = false;
|
||||
var blocks = [];
|
||||
|
||||
/* 把每个字拆开,好一个个弹出来 */
|
||||
name.innerHTML = name.textContent.split('').map(function (c, i) { return '<span style="--i:' + i + '">' + c + '</span>'; }).join('');
|
||||
|
||||
/* 钻石原图是 14×14 的像素画:按格子中心取色,得到要垒的方块 */
|
||||
var src = new Image();
|
||||
src.onload = function () {
|
||||
var t = document.createElement('canvas'); t.width = t.height = N;
|
||||
var tc = t.getContext('2d'); tc.imageSmoothingEnabled = false; tc.drawImage(src, 0, 0, N, N);
|
||||
var d = tc.getImageData(0, 0, N, N).data;
|
||||
for (var y = 0; y < N; y++) for (var x = 0; x < N; x++) {
|
||||
var k = (y * N + x) * 4;
|
||||
if (d[k + 3] < 128) continue;
|
||||
/* 落下的先后:从底往上一层层垒,同一层里左右随机一点 */
|
||||
var order = (N - 1 - y) + Math.random() * 0.9;
|
||||
blocks.push({ x: x, y: y, c: 'rgb(' + d[k] + ',' + d[k + 1] + ',' + d[k + 2] + ')', t: order });
|
||||
}
|
||||
var maxT = 0; blocks.forEach(function (b) { if (b.t > maxT) maxT = b.t; });
|
||||
blocks.forEach(function (b) { b.t = b.t / maxT; }); // 0..1
|
||||
requestAnimationFrame(frame);
|
||||
};
|
||||
src.src = 'assets/gem.webp';
|
||||
|
||||
var BUILD = 620, FALL = 260; // 整颗垒完 620ms,每块落 260ms
|
||||
function frame(now) {
|
||||
var el = now - T0;
|
||||
ctx.clearRect(0, 0, cv.width, cv.height);
|
||||
var built = true;
|
||||
for (var i = 0; i < blocks.length; i++) {
|
||||
var b = blocks[i], start = b.t * BUILD, k = (el - start) / FALL;
|
||||
if (k <= 0) { built = false; continue; }
|
||||
if (k < 1) built = false;
|
||||
k = Math.min(1, k);
|
||||
var e = 1 - Math.pow(1 - k, 3); // 落地减速
|
||||
var y = (b.y - (1 - e) * (b.y + 3)) * CELL;
|
||||
ctx.globalAlpha = Math.min(1, k * 2.2);
|
||||
ctx.fillStyle = b.c; ctx.fillRect(b.x * CELL, y, CELL, CELL);
|
||||
/* 每块顶上一道亮边、底下一道暗边:方块感 */
|
||||
ctx.globalAlpha *= 0.28;
|
||||
ctx.fillStyle = '#fff'; ctx.fillRect(b.x * CELL, y, CELL, 2);
|
||||
ctx.fillStyle = '#000'; ctx.fillRect(b.x * CELL, y + CELL - 2, CELL, 2);
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
/* 垒完以后一道白光斜着扫过钻石 */
|
||||
var sw = (el - BUILD - FALL) / 520;
|
||||
if (sw > 0 && sw < 1) {
|
||||
ctx.save(); ctx.globalCompositeOperation = 'source-atop';
|
||||
var gx = -cv.width * 0.6 + sw * cv.width * 2.2;
|
||||
var g = ctx.createLinearGradient(gx, 0, gx + cv.width * 0.5, cv.height);
|
||||
g.addColorStop(0, 'rgba(255,255,255,0)'); g.addColorStop(0.5, 'rgba(255,255,255,.85)'); g.addColorStop(1, 'rgba(255,255,255,0)');
|
||||
ctx.fillStyle = g; ctx.fillRect(0, 0, cv.width, cv.height); ctx.restore();
|
||||
}
|
||||
if (built && !boot.classList.contains('built')) boot.classList.add('built'); // 字开始弹出
|
||||
/* 进度条:一半看时间(让动画走完),一半看页面真加载完没有 */
|
||||
var p = Math.min(1, el / (BUILD + FALL + 300)) * (ready ? 1 : 0.82);
|
||||
bar.style.transform = 'scaleX(' + Math.max(p, parseFloat(bar.dataset.p || 0)).toFixed(3) + ')';
|
||||
bar.dataset.p = p;
|
||||
if (boot.isConnected) requestAnimationFrame(frame);
|
||||
}
|
||||
|
||||
function finish() {
|
||||
if (done) return;
|
||||
var el = performance.now() - T0;
|
||||
if (el < MIN) { setTimeout(finish, MIN - el); return; }
|
||||
done = true;
|
||||
bar.style.transform = 'scaleX(1)';
|
||||
try { sessionStorage.setItem('jz-boot', '1'); } catch (e) {}
|
||||
setTimeout(function () {
|
||||
boot.classList.add('leave'); root.classList.remove('booting'); root.classList.add('booted');
|
||||
setTimeout(function () { boot.remove(); }, 700);
|
||||
}, 160);
|
||||
}
|
||||
function onReady() { ready = true; finish(); }
|
||||
if (document.readyState === 'complete') onReady(); else addEventListener('load', onReady, { once: true });
|
||||
setTimeout(function () { ready = true; finish(); }, MAX);
|
||||
/* 点一下就跳过 */
|
||||
boot.addEventListener('click', function () { ready = true; T0 -= MIN; finish(); });
|
||||
})();
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 285 B |
@@ -0,0 +1,362 @@
|
||||
/* 金钻客栈 · 画展(gallery.html)
|
||||
---------------------------------------------------------------------------
|
||||
样子按设计预览站:类型筛选条 + 左边年份 + 右边作品墙(.art 卡片)+ 白色毛玻璃大图层。
|
||||
功能沿用原来的单页版(一样都没少):
|
||||
· 筛选:类型(图片 / 视频 / 特殊 = 全景 + 动态壁纸)、谁做的、年份 → 月份;排序最新 / 最早;看过的放前 / 放后 / 不显示(记在本机)
|
||||
· 作品墙:按「当前最矮的一列」投放(时间顺序从左往右走,不会像 CSS 分栏那样竖着排);列表只放缩略图
|
||||
· 看作品:图片先铺缩略图,再换 hd_cache 轻量高清(2 秒没到就上原图);本站视频优先放网页版副本;B 站视频嵌播放器;
|
||||
全景 = 球面环视(拖动 / 双指缩放 / 滚轮缩放);动态壁纸 = 拖时间轴 / 左右拖画面 / 自动播放
|
||||
· 观展统计:点开一次打一个 /hit(服务器只记计数,IP 加盐哈希);view_stats.json 里有数就在卡片上显示「几人看过」
|
||||
要在 pages.js 之后、site.js 之前加载(site.js 会给这里画好的卡片挂倾斜 / 浮现动效)。 */
|
||||
(function () {
|
||||
'use strict';
|
||||
var P = window.JZP; if (!P) return;
|
||||
var esc = P.esc, fileUrl = P.fileUrl, thumbOf = P.thumbOf, ratioOf = P.ratioOf;
|
||||
var ALL = P.gallery || [];
|
||||
var $ = function (id) { return document.getElementById(id); };
|
||||
var wall = $('gWall'); if (!wall) return;
|
||||
var reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
var clamp = function (v, a, b) { return Math.min(b, Math.max(a, v)); };
|
||||
var store = { get: function (k) { try { return localStorage.getItem(k); } catch (e) { return null; } }, set: function (k, v) { try { localStorage.setItem(k, v); } catch (e) {} } };
|
||||
|
||||
var TYPE = { image: '图片', video: '视频', pano: '全景', wall: '动态壁纸' };
|
||||
var S = { type: 'all', owner: 'all', year: '', month: '', newest: true, seen: store.get('jz_gallery_seen') || 'off' };
|
||||
if (['off', 'first', 'last', 'hide'].indexOf(S.seen) < 0) S.seen = 'off';
|
||||
var view = [];
|
||||
|
||||
/* ---------- 看过的(本机记录:打开次数 / 最近打开) ---------- */
|
||||
var OPEN_KEY = 'jz_gallery_opens';
|
||||
var keyOf = function (g) { return g.src || (g.frames && g.frames[0] && g.frames[0].src) || g.title || ''; };
|
||||
function opens() { try { var o = JSON.parse(store.get(OPEN_KEY) || '{}'); return o && typeof o === 'object' ? o : {}; } catch (e) { return {}; } }
|
||||
function markOpen(g) {
|
||||
var k = keyOf(g); if (!k) return;
|
||||
var o = opens(), r = o[k] || { c: 0, t: 0 }; r.c = (r.c || 0) + 1; r.t = Date.now(); o[k] = r;
|
||||
var ks = Object.keys(o); if (ks.length > 400) { ks.sort(function (a, b) { return (o[a].t || 0) - (o[b].t || 0); }); ks.slice(0, ks.length - 400).forEach(function (x) { delete o[x]; }); }
|
||||
store.set(OPEN_KEY, JSON.stringify(o));
|
||||
}
|
||||
/* ---------- 观展统计 ---------- */
|
||||
var STATS = null;
|
||||
fetch('view_stats.json?_=' + Date.now(), { cache: 'no-store' }).then(function (r) { return r.ok ? r.json() : null; }).then(function (j) {
|
||||
if (!j) return; STATS = j;
|
||||
if (j.total && j.total.u) { $('gViewsU').textContent = j.total.u; $('gViews').hidden = false; }
|
||||
draw();
|
||||
}).catch(function () {});
|
||||
function hit(g) {
|
||||
var k = keyOf(g); if (!k) return;
|
||||
var u = 'hit?k=' + encodeURIComponent(k) + '&_=' + Date.now();
|
||||
try { if (navigator.sendBeacon) navigator.sendBeacon(u); else fetch(u, { keepalive: true, cache: 'no-store' }); } catch (e) {}
|
||||
}
|
||||
|
||||
/* ---------- 筛选 + 排序 ---------- */
|
||||
function isSp(g) { return g.type === 'pano' || g.type === 'wall'; }
|
||||
function match(g) {
|
||||
if (S.year && g.date.slice(0, 4) !== S.year) return false;
|
||||
if (S.month && g.date.slice(5, 7) !== S.month) return false;
|
||||
if (S.owner !== 'all' && (g.owner === 'gift' ? 'gift' : 'own') !== S.owner) return false;
|
||||
if (S.type === 'all') return true;
|
||||
if (S.type === 'special') return isSp(g);
|
||||
return g.type === S.type;
|
||||
}
|
||||
function sorted() {
|
||||
var arr = ALL.slice().sort(function (a, b) { return a.date < b.date ? -1 : a.date > b.date ? 1 : 0; });
|
||||
if (S.newest) arr.reverse();
|
||||
if (S.seen === 'off') return arr;
|
||||
var log = opens(), seen = function (g) { return !!log[keyOf(g)]; };
|
||||
if (S.seen === 'hide') return arr.filter(function (g) { return !seen(g); });
|
||||
var a = [], b = []; arr.forEach(function (g) { (seen(g) ? a : b).push(g); });
|
||||
return S.seen === 'first' ? a.concat(b) : b.concat(a);
|
||||
}
|
||||
|
||||
/* ---------- 卡片 ---------- */
|
||||
var PLAY = '<span class="art-play" aria-hidden="true"><svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5.5v13l11-6.5z"/></svg></span>';
|
||||
var PH_ICON = { video: '<svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2.5" y="5" width="19" height="14" rx="2"/><path d="m10 9.5 5 2.5-5 2.5z"/></svg>' };
|
||||
function stillOf(g) {
|
||||
if (g.type === 'video') return (g.src && /\.(mp4|webm)$/i.test(g.src)) ? (thumbOf(g.src) !== g.src ? thumbOf(g.src) : '') : (g.poster || '');
|
||||
return g.poster || (g.frames && g.frames[0] && g.frames[0].src) || g.src || '';
|
||||
}
|
||||
function card(g, i) {
|
||||
var t = g.type || 'image', still = stillOf(g), r = ratioOf(g.src) || ratioOf(still) || g.r || 0;
|
||||
var thumb = still ? (t === 'video' ? still : thumbOf(still)) : '';
|
||||
var media = thumb
|
||||
? '<img src="' + esc(fileUrl(thumb)) + '" alt="' + esc(g.title) + '" loading="lazy" decoding="async" draggable="false"' + (r ? ' style="aspect-ratio:' + (+r).toFixed(4) + '"' : '') + '>'
|
||||
: '<span class="ph" style="--ar:16/9">' + (PH_ICON[t] || '') + '<span>' + TYPE[t] + '</span></span>';
|
||||
var st = STATS && STATS.items && STATS.items[keyOf(g)];
|
||||
var o = opens()[keyOf(g)];
|
||||
var badge = (t === 'video' ? PLAY : '') + (isSp(g) ? '<span class="art-sp">' + (t === 'pano' ? '全景 · 可拖动' : '动态壁纸 · ' + ((g.frames || []).length || '') + ' 帧') + '</span>' : '')
|
||||
+ (g.owner === 'gift' ? '<span class="art-own">别人送的</span>' : '');
|
||||
var links = (g.links && g.links.length) ? g.links : (g.link ? [g.link] : []);
|
||||
return '<figure class="art crystal" data-type="' + (isSp(g) ? 'special' : t) + '">'
|
||||
+ '<button type="button" data-i="' + i + '" aria-label="看「' + esc(g.title) + '」">' + media + badge + '</button>'
|
||||
+ '<figcaption class="cap"><b>' + esc(g.title) + '</b>'
|
||||
+ (g.desc ? '<i class="art-desc">' + esc(g.desc) + '</i>' : '')
|
||||
+ '<span><span class="type">' + TYPE[t] + '</span><span class="num">' + esc(g.date) + '</span></span>'
|
||||
+ ((st && st.c) || o || links.length ? '<span class="art-meta">'
|
||||
+ (st && st.c ? '<em title="看过的人(同一个人多次只算一次)/ 点开总次数">' + (st.u || 0) + ' 人看过</em>' : '')
|
||||
+ (o ? '<em class="mine" title="你在这台设备上打开过的次数">你看过 ' + (o.c || 1) + ' 次</em>' : '')
|
||||
+ links.map(function (u) { return '<a href="' + esc(u) + '" target="_blank" rel="noopener noreferrer">' + esc(linkLabel(u, links.length)) + ' ↗</a>'; }).join('')
|
||||
+ '</span>' : '')
|
||||
+ '</figcaption></figure>';
|
||||
}
|
||||
function linkLabel(u, n) {
|
||||
if (/steamcommunity\.com|\/workshop/i.test(u)) return 'Steam 创意工坊';
|
||||
if (/cgmodel\.com|\/cgmodel/i.test(u)) return 'CG 模型网';
|
||||
if (/bilibili\.com|b23\.tv/i.test(u)) return 'B 站';
|
||||
return n > 1 ? '外链' : '原站';
|
||||
}
|
||||
|
||||
/* ---------- 作品墙:按最矮的一列投放(宽高比来自离线媒体索引,估得准) ---------- */
|
||||
function cols() {
|
||||
var w = wall.clientWidth || 900;
|
||||
if (innerWidth <= 760) return 2;
|
||||
return clamp(Math.floor((w + 16) / 276), 1, 3);
|
||||
}
|
||||
function draw() {
|
||||
var all = sorted();
|
||||
var cnt = function (f) { return all.filter(f).length; };
|
||||
$('gN').textContent = ALL.length;
|
||||
$('cAll').textContent = all.length; $('cImage').textContent = cnt(function (g) { return g.type === 'image'; });
|
||||
$('cVideo').textContent = cnt(function (g) { return g.type === 'video'; }); $('cSpecial').textContent = cnt(isSp);
|
||||
$('cOwn').textContent = cnt(function (g) { return g.owner !== 'gift'; }); $('cGift').textContent = cnt(function (g) { return g.owner === 'gift'; });
|
||||
view = all.filter(match);
|
||||
var n = cols(), colH = [], html = [];
|
||||
for (var c = 0; c < n; c++) { colH.push(0); html.push(''); }
|
||||
view.forEach(function (g, i) {
|
||||
var r = ratioOf(g.src) || ratioOf(stillOf(g)) || g.r || 1.4;
|
||||
var t = 0; for (var j = 1; j < n; j++) if (colH[j] < colH[t] - 1e-6) t = j;
|
||||
html[t] += card(g, i); colH[t] += 1 / r + 0.32;
|
||||
});
|
||||
wall.innerHTML = view.length ? html.map(function (h) { return '<div class="wall-col">' + h + '</div>'; }).join('')
|
||||
: '<p class="note" style="padding:30px 0">这个筛选下还没有作品。</p>';
|
||||
wall.style.setProperty('--cols', n);
|
||||
syncBar(); drawYears();
|
||||
}
|
||||
function syncBar() {
|
||||
[['gType', 'f', S.type], ['gOwner', 'o', S.owner], ['gSeen', 's', S.seen]].forEach(function (x) {
|
||||
var box = $(x[0]); if (!box) return;
|
||||
box.querySelectorAll('button').forEach(function (b) { b.setAttribute('aria-pressed', String(b.getAttribute('data-' + x[1]) === x[2])); });
|
||||
});
|
||||
var sb = $('gSort'); sb.querySelector('span').textContent = S.newest ? '最新的在前' : '最早的在前'; sb.setAttribute('aria-pressed', String(S.newest));
|
||||
$('gClear').hidden = !(S.type !== 'all' || S.owner !== 'all' || S.year || S.month);
|
||||
}
|
||||
function drawYears() {
|
||||
var years = {}, months = {};
|
||||
ALL.forEach(function (g) { var y = g.date.slice(0, 4); if (y) years[y] = (years[y] || 0) + 1; if (S.year && y === S.year) { var m = g.date.slice(5, 7); months[m] = (months[m] || 0) + 1; } });
|
||||
var ys = Object.keys(years).sort().reverse();
|
||||
var h = '<b>年份</b><a href="#" data-y=""' + (S.year ? '' : ' class="on"') + '>全部<em class="num">' + ALL.length + '</em></a>';
|
||||
ys.forEach(function (y) {
|
||||
h += '<a href="#" data-y="' + y + '"' + (S.year === y ? ' class="on"' : '') + '>' + y + '<em class="num">' + years[y] + '</em></a>';
|
||||
if (S.year === y) Object.keys(months).sort().reverse().forEach(function (m) {
|
||||
h += '<a href="#" class="mon' + (S.month === m ? ' on' : '') + '" data-y="' + y + '" data-m="' + m + '">' + (+m) + ' 月<em class="num">' + months[m] + '</em></a>';
|
||||
});
|
||||
});
|
||||
$('gYears').innerHTML = h;
|
||||
var hm = $('gYearsM');
|
||||
if (hm) hm.innerHTML = '<button type="button" data-y="" aria-pressed="' + !S.year + '">全部</button>' + ys.map(function (y) { return '<button type="button" data-y="' + y + '" aria-pressed="' + (S.year === y) + '">' + y + '</button>'; }).join('');
|
||||
}
|
||||
|
||||
/* ---------- 工具条 ---------- */
|
||||
function on(id, attr, fn) { var el = $(id); if (el) el.addEventListener('click', function (e) { var b = e.target.closest('[data-' + attr + ']'); if (b) { e.preventDefault(); fn(b.getAttribute('data-' + attr), b); draw(); } }); }
|
||||
on('gType', 'f', function (v) { S.type = v; });
|
||||
on('gOwner', 'o', function (v) { S.owner = v; });
|
||||
on('gSeen', 's', function (v) { S.seen = v; store.set('jz_gallery_seen', v); });
|
||||
on('gYears', 'y', function (v, b) { S.year = v; S.month = b.getAttribute('data-m') || ''; });
|
||||
on('gYearsM', 'y', function (v) { S.year = v; S.month = ''; });
|
||||
$('gSort').addEventListener('click', function () { S.newest = !S.newest; draw(); });
|
||||
$('gClear').addEventListener('click', function () { S.type = 'all'; S.owner = 'all'; S.year = ''; S.month = ''; draw(); });
|
||||
$('gMore').addEventListener('click', function () { var p = $('gMorePanel'), o = p.hidden; p.hidden = !o; this.setAttribute('aria-expanded', String(o)); });
|
||||
var rt = 0, lastCols = 0;
|
||||
addEventListener('resize', function () { clearTimeout(rt); rt = setTimeout(function () { if (cols() !== lastCols) { lastCols = cols(); draw(); } }, 160); }, { passive: true });
|
||||
|
||||
/* ================================================================ 看作品 */
|
||||
var box = $('gbox'), stage = $('gbStage'), img = $('gbImg'), vid = $('gbVid'), vwrap = $('gbVidWrap'), bf = $('gbBiliFrame'),
|
||||
pano = $('gbPano'), wimg = $('gbWall'), load = $('gbLoad'), lastBtn = null, ctl = null, blobUrl = '';
|
||||
function showOnly(el) { [img, vwrap, bf, pano, wimg].forEach(function (x) { x.hidden = x !== el; }); }
|
||||
function openBox(g) {
|
||||
$('gbT').textContent = g.title || ''; $('gbD').textContent = [TYPE[g.type || 'image'], g.date, g.owner === 'gift' ? '别人送的' : ''].filter(Boolean).join(' · ') + (g.desc ? ' — ' + g.desc : '');
|
||||
$('gbOrig').hidden = true; $('gbBili').hidden = true; $('gbWallBar').hidden = true; $('gbHint').textContent = ''; load.hidden = true;
|
||||
var links = (g.links && g.links.length) ? g.links : (g.link ? [g.link] : []);
|
||||
$('gbLinks').innerHTML = links.map(function (u) { return '<a class="btn btn-crystal btn-sm" href="' + esc(u) + '" target="_blank" rel="noopener noreferrer">' + esc(linkLabel(u, links.length)) + ' ↗</a>'; }).join('');
|
||||
box.hidden = false; box.classList.add('open'); document.documentElement.classList.add('gbox-on');
|
||||
$('gbClose').focus();
|
||||
}
|
||||
function closeBox() {
|
||||
if (box.hidden) return;
|
||||
if (ctl) { try { ctl.destroy(); } catch (e) {} ctl = null; }
|
||||
vid.pause(); vid.removeAttribute('src'); vid.load();
|
||||
bf.removeAttribute('src'); img.removeAttribute('src'); wimg.removeAttribute('src');
|
||||
if (blobUrl) { URL.revokeObjectURL(blobUrl); blobUrl = ''; }
|
||||
box.classList.remove('open'); box.hidden = true; document.documentElement.classList.remove('gbox-on');
|
||||
if (lastBtn) lastBtn.focus();
|
||||
}
|
||||
$('gbClose').addEventListener('click', closeBox);
|
||||
/* 点空白处关闭:按下和松手都得在空白处才算(拖全景 / 拖动态壁纸拖出画框松手,click 会落在空白处,不能把人关出去) */
|
||||
var downOnBlank = false;
|
||||
box.addEventListener('pointerdown', function (e) { downOnBlank = (e.target === box || e.target === stage); });
|
||||
box.addEventListener('click', function (e) { if (downOnBlank && (e.target === box || e.target === stage)) closeBox(); downOnBlank = false; });
|
||||
addEventListener('keydown', function (e) { if (e.key === 'Escape') closeBox(); });
|
||||
|
||||
/* ---------- 图片:缩略图秒显 → hd_cache 轻量高清(通常 0.2~0.5MB)→ 2 秒没到就上原图 ---------- */
|
||||
var HDC = null, hdcWait = [];
|
||||
(window.__hdcEarly || fetch('hd_cache/manifest.json', { cache: 'force-cache' }))
|
||||
.then(function (r) { return r && r.ok ? r.json() : null; })
|
||||
.then(function (m) { HDC = m || {}; }, function () { HDC = {}; })
|
||||
.then(function () { var q = hdcWait; hdcWait = []; q.forEach(function (f) { f(); }); });
|
||||
var whenHdc = function (f) { if (HDC) f(); else hdcWait.push(f); };
|
||||
var hdcOf = function (src) { return (HDC && HDC[src]) || ''; };
|
||||
var cache = {}; // 打开过 / 预取过的高清图(第二次秒开)
|
||||
function fetchImg(u, cb) {
|
||||
var im = cache[u];
|
||||
if (im && im.ok) { cb && cb(true); return; }
|
||||
if (im && im.bad) { cb && cb(false); return; } // 之前预取就失败了:直接走下一档,别干等
|
||||
if (!im) { im = cache[u] = new Image(); im.decoding = 'async'; }
|
||||
if (cb) { im.addEventListener('load', function () { cb(true); }, { once: true }); im.addEventListener('error', function () { cb(false); }, { once: true }); }
|
||||
if (!im.src) { im.onload = function () { im.ok = true; }; im.onerror = function () { im.bad = true; }; im.src = fileUrl(u); }
|
||||
}
|
||||
function openImage(g, btn) {
|
||||
openBox(g); showOnly(img);
|
||||
var thumbEl = btn && btn.querySelector('img'), src = g.src;
|
||||
var have = thumbEl && thumbEl.complete && thumbEl.naturalWidth > 0;
|
||||
img.alt = g.title || '';
|
||||
/* 先铺缩略图(列表里的还没下完也照样先铺它:几十 KB,比干等高清快得多),高清到了原地换 */
|
||||
if (have) img.src = thumbEl.currentSrc || thumbEl.src; else { img.src = fileUrl(thumbOf(src)); load.hidden = false; }
|
||||
$('gbOrig').href = fileUrl(src); $('gbOrig').hidden = false;
|
||||
var shown = false;
|
||||
var put = function (u) { if (box.hidden || shown) return; shown = true; img.src = fileUrl(u); load.hidden = true; };
|
||||
var orig = function () { fetchImg(src, function (ok) { if (ok) put(src); else load.hidden = true; }); };
|
||||
whenHdc(function () {
|
||||
var h = hdcOf(src);
|
||||
if (h && h !== src) { fetchImg(h, function (ok) { if (ok) put(h); else orig(); }); setTimeout(function () { if (!shown && !box.hidden) orig(); }, 2000); }
|
||||
else orig();
|
||||
});
|
||||
if (!HDC) setTimeout(function () { if (!HDC && !shown && !box.hidden) orig(); }, 900);
|
||||
}
|
||||
/* 鼠标停在卡片上就先悄悄拉高清,点开更快 */
|
||||
wall.addEventListener('pointerover', function (e) {
|
||||
var b = e.target.closest && e.target.closest('button[data-i]'); if (!b || b._pf) return; b._pf = 1;
|
||||
var g = view[+b.getAttribute('data-i')]; if (!g || g.type !== 'image' || !g.src) return;
|
||||
whenHdc(function () { fetchImg(hdcOf(g.src) || g.src); });
|
||||
});
|
||||
|
||||
/* ---------- 视频 ---------- */
|
||||
function biliId(g) { var m = String(g.bvid || g.url || '').match(/BV[0-9A-Za-z]{10}/); return m ? m[0] : ''; }
|
||||
function openVideo(g) {
|
||||
openBox(g);
|
||||
var bv = biliId(g), local = g.src && /\.(mp4|webm)$/i.test(g.src);
|
||||
if (local) {
|
||||
showOnly(vwrap); vid.src = fileUrl(g.web || g.src); // 网页版副本更小、手机也能放
|
||||
$('gbWm').textContent = g.owner === 'gift' ? '别人做的' : '金钻做的';
|
||||
try { vid.play().catch(function () {}); } catch (e) {}
|
||||
if (bv || g.url) { $('gbBili').href = g.url || ('https://www.bilibili.com/video/' + bv); $('gbBili').hidden = false; }
|
||||
} else if (bv) {
|
||||
showOnly(bf); bf.src = 'https://player.bilibili.com/player.html?bvid=' + bv + '&page=1&autoplay=0';
|
||||
$('gbBili').href = g.url || ('https://www.bilibili.com/video/' + bv); $('gbBili').hidden = false;
|
||||
} else if (g.url) { closeBox(); window.open(g.url, '_blank', 'noopener'); }
|
||||
}
|
||||
|
||||
/* ---------- 全景:等距柱状图贴到球面上环视(拖动看四周;滚轮 / 双指捏合缩放;往上拖 = 低头) ---------- */
|
||||
function openPano(g) {
|
||||
openBox(g); showOnly(pano);
|
||||
$('gbHint').textContent = '拖动看四周 · 往上拖是低头、往下拖是抬头 · 滚轮或双指缩放';
|
||||
var off = document.createElement('canvas'), octx = off.getContext('2d');
|
||||
var sample = document.createElement('canvas'), sctx = sample.getContext('2d', { willReadFrequently: true });
|
||||
var px = null, iw = 1, ih = 1, yaw = 0, pitch = 0, fov = 1.25, raf = 0, drag = false, lx = 0, ly = 0, pinch = 0, pf = 0, gotHD = false;
|
||||
function use(im, hd) {
|
||||
if (gotHD && !hd) return; if (hd) gotHD = true;
|
||||
iw = im.naturalWidth; ih = im.naturalHeight; if (!iw || !ih) return;
|
||||
sample.width = iw; sample.height = ih; sctx.drawImage(im, 0, 0);
|
||||
try { px = sctx.getImageData(0, 0, iw, ih).data; } catch (e) { px = null; }
|
||||
render();
|
||||
}
|
||||
function src(u, hd) { var im = new Image(); im.onload = function () { if (ctl === me) use(im, hd); }; im.src = fileUrl(u); }
|
||||
function render() {
|
||||
if (!px) return;
|
||||
var cw = Math.max(240, stage.clientWidth || 640), ch = Math.max(180, stage.clientHeight || 360);
|
||||
var rw = Math.round(clamp(cw / 2.4, 280, 560)), rh = Math.max(2, Math.round(rw * ch / cw));
|
||||
if (off.width !== rw || off.height !== rh) { off.width = rw; off.height = rh; pano.width = rw; pano.height = rh; }
|
||||
var out = octx.createImageData(rw, rh), d = out.data, asp = rw / rh, tf = Math.tan(fov / 2);
|
||||
var cy = Math.cos(yaw), sy = Math.sin(yaw), cp = Math.cos(pitch), sp = Math.sin(pitch), TAU = Math.PI * 2, p = 0;
|
||||
for (var y = 0; y < rh; y++) {
|
||||
var ny = -(((y + 0.5) / rh) * 2 - 1) * tf;
|
||||
for (var x = 0; x < rw; x++) {
|
||||
var nx = (((x + 0.5) / rw) * 2 - 1) * tf * asp;
|
||||
var x1 = nx * cy + ny * sp * sy + cp * sy, y1 = ny * cp - sp, z1 = -nx * sy + ny * sp * cy + cp * cy;
|
||||
var len = Math.sqrt(x1 * x1 + y1 * y1 + z1 * z1) || 1;
|
||||
var lat = Math.asin(clamp(y1 / len, -1, 1)), lon = Math.atan2(x1, z1) / TAU + 0.5; lon -= Math.floor(lon);
|
||||
var u = (lon * iw) | 0, v = clamp(Math.round((0.5 - lat / Math.PI) * ih), 0, ih - 1), si = (v * iw + (u >= iw ? iw - 1 : u)) * 4;
|
||||
d[p++] = px[si]; d[p++] = px[si + 1]; d[p++] = px[si + 2]; d[p++] = 255;
|
||||
}
|
||||
}
|
||||
octx.putImageData(out, 0, 0);
|
||||
var c = pano.getContext('2d'); c.imageSmoothingEnabled = true; c.imageSmoothingQuality = 'high'; c.drawImage(off, 0, 0, pano.width, pano.height);
|
||||
}
|
||||
var sched = function () { if (!raf) raf = requestAnimationFrame(function () { raf = 0; render(); }); };
|
||||
var dist = function (t) { return Math.hypot(t[0].clientX - t[1].clientX, t[0].clientY - t[1].clientY) || 1; };
|
||||
function down(e) { var t = e.touches; if (t && t.length > 1) { pinch = dist(t); pf = fov; drag = false; return; } drag = true; lx = t ? t[0].clientX : e.clientX; ly = t ? t[0].clientY : e.clientY; }
|
||||
function move(e) {
|
||||
var t = e.touches;
|
||||
if (t && t.length > 1) { if (!pinch) { pinch = dist(t); pf = fov; } fov = clamp(pf * pinch / dist(t), 0.6, 2); e.cancelable && e.preventDefault(); sched(); return; }
|
||||
if (!drag) return;
|
||||
var x = t ? t[0].clientX : e.clientX, y = t ? t[0].clientY : e.clientY;
|
||||
yaw -= (x - lx) * 0.0045; pitch = clamp(pitch - (y - ly) * 0.0038, -1.05, 1.05); lx = x; ly = y;
|
||||
e.cancelable && e.preventDefault(); sched();
|
||||
}
|
||||
function up(e) { var t = e.touches; if (t && t.length === 1) { pinch = 0; drag = true; lx = t[0].clientX; ly = t[0].clientY; return; } drag = false; pinch = 0; }
|
||||
function wheel(e) { fov = clamp(fov + (e.deltaY > 0 ? 0.12 : -0.12), 0.6, 2); e.preventDefault(); sched(); }
|
||||
function dbl() { yaw = 0; pitch = 0; fov = 1.25; sched(); }
|
||||
pano.addEventListener('mousedown', down); pano.addEventListener('touchstart', down, { passive: true });
|
||||
addEventListener('mousemove', move); pano.addEventListener('touchmove', move, { passive: false });
|
||||
addEventListener('mouseup', up); addEventListener('touchend', up); pano.addEventListener('wheel', wheel, { passive: false }); pano.addEventListener('dblclick', dbl);
|
||||
var me = ctl = { destroy: function () {
|
||||
cancelAnimationFrame(raf); px = null;
|
||||
pano.removeEventListener('mousedown', down); pano.removeEventListener('touchstart', down); removeEventListener('mousemove', move); pano.removeEventListener('touchmove', move);
|
||||
removeEventListener('mouseup', up); removeEventListener('touchend', up); pano.removeEventListener('wheel', wheel); pano.removeEventListener('dblclick', dbl);
|
||||
} };
|
||||
src(thumbOf(g.src), false);
|
||||
whenHdc(function () { src(hdcOf(g.src) || g.src, true); });
|
||||
}
|
||||
|
||||
/* ---------- 动态壁纸:拖时间轴 / 在画面上左右拖 / 自动播放 ---------- */
|
||||
function openWall(g) {
|
||||
var F = g.frames || []; if (!F.length) return;
|
||||
openBox(g); showOnly(wimg); $('gbWallBar').hidden = false;
|
||||
$('gbHint').textContent = '左右拖画面或拖时间轴换帧';
|
||||
var n = F.length, i = 0, tid = 0, range = $('gbRange'), lbl = $('gbLbl'), play = $('gbPlay'), pre = {};
|
||||
range.max = String(n - 1);
|
||||
function show(k) {
|
||||
i = ((k % n) + n) % n; var f = F[i];
|
||||
wimg.src = fileUrl(thumbOf(f.src)); wimg.alt = f.label || '';
|
||||
if (thumbOf(f.src) !== f.src) { var im = pre[f.src] || (pre[f.src] = new Image()); if (im.complete && im.naturalWidth) wimg.src = fileUrl(f.src); else { im.onload = function () { if (F[i] === f) wimg.src = fileUrl(f.src); }; if (!im.src) im.src = fileUrl(f.src); } }
|
||||
[1, 2].forEach(function (d) { var nx = F[(i + d) % n]; var p = new Image(); p.src = fileUrl(thumbOf(nx.src)); });
|
||||
range.value = String(i); lbl.textContent = (f.label || '#' + (i + 1)) + ' · ' + (i + 1) + '/' + n;
|
||||
}
|
||||
function stop() { clearInterval(tid); tid = 0; play.textContent = '▶'; }
|
||||
function start() { stop(); play.textContent = '❚❚'; tid = setInterval(function () { show(i + 1); }, 1600); }
|
||||
range.oninput = function () { stop(); show(+range.value || 0); };
|
||||
play.onclick = function () { tid ? stop() : start(); };
|
||||
var dragX = null, acc = 0;
|
||||
function d(e) { dragX = (e.touches ? e.touches[0] : e).clientX; acc = 0; stop(); }
|
||||
function m(e) { if (dragX == null) return; var x = (e.touches ? e.touches[0] : e).clientX, step = Math.max(52, stage.clientWidth * 0.075); acc += x - dragX; dragX = x; var s = Math.round(acc / step); if (s) { acc -= s * step; show(i + s); } e.cancelable && e.preventDefault(); }
|
||||
function u() { dragX = null; }
|
||||
wimg.addEventListener('mousedown', d); wimg.addEventListener('touchstart', d, { passive: true });
|
||||
addEventListener('mousemove', m); wimg.addEventListener('touchmove', m, { passive: false }); addEventListener('mouseup', u); addEventListener('touchend', u);
|
||||
show(0); if (!reduce) start();
|
||||
ctl = { destroy: function () { stop(); wimg.removeEventListener('mousedown', d); wimg.removeEventListener('touchstart', d); removeEventListener('mousemove', m); wimg.removeEventListener('touchmove', m); removeEventListener('mouseup', u); removeEventListener('touchend', u); } };
|
||||
}
|
||||
|
||||
/* ---------- 点卡片:按类型分发 ---------- */
|
||||
wall.addEventListener('click', function (e) {
|
||||
if (e.target.closest('a')) return; // 卡片里的外链自己跳
|
||||
var b = e.target.closest('button[data-i]'); if (!b) return;
|
||||
var g = view[+b.getAttribute('data-i')]; if (!g) return;
|
||||
lastBtn = b; markOpen(g); hit(g);
|
||||
if (g.type === 'video') openVideo(g);
|
||||
else if (g.type === 'pano') openPano(g);
|
||||
else if (g.type === 'wall') openWall(g);
|
||||
else if (g.src) openImage(g, b);
|
||||
});
|
||||
|
||||
/* 作品图别被右键另存 / 拖走(和原来一样,挡一下顺手党) */
|
||||
document.addEventListener('contextmenu', function (e) { if (e.target.closest && e.target.closest('.wall img,#gbox img,#gbox canvas,#gbox video')) e.preventDefault(); });
|
||||
|
||||
lastCols = cols(); draw();
|
||||
})();
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.3 KiB |
@@ -0,0 +1,255 @@
|
||||
/* 金钻客栈 · 各页内容渲染(2026-10-06 起以设计预览站为准)
|
||||
---------------------------------------------------------------------------
|
||||
内容来源:content/site.js(window.JZ_CONTENT,内容后台发布时生成);后台点「预览」带 ?preview=1 时换成草稿。
|
||||
站点固定信息:assets/site-info.js(window.JZ_SITE:域名 / QQ 群 / 备案号 / 邮箱)。
|
||||
这个文件只负责「把内容填进页面」,标记和预览站一模一样;动效 / 交互在 assets/site.js(预览站原版),
|
||||
画展的筛选 / 大图 / 视频 / 全景 / 动态壁纸在 assets/gallery.js。
|
||||
顺序很重要:本文件要在 site.js 之前跑完,site.js 才能给填好的卡片挂上倾斜 / 浮现 / 翻牌动效。 */
|
||||
(function () {
|
||||
'use strict';
|
||||
var C = window.JZ_CONTENT || {}, SITE = window.JZ_SITE || {};
|
||||
var page = document.body.getAttribute('data-page') || '';
|
||||
var $ = function (s, r) { return (r || document).querySelector(s); };
|
||||
var esc = function (s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); };
|
||||
var ARROW = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></svg>';
|
||||
var ARROW_SM = ARROW.replace(/width="16" height="16"/, 'width="14" height="14"');
|
||||
var DIAG = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17 17 7"/><path d="M8 7h9v9"/></svg>';
|
||||
/* 板块色:和各页大号数字同一套(预览站) */
|
||||
var ZC = { gallery: ['#F2C14D', '#E8913A'], tools: ['#4F86E8', '#2E5BD8'], universe: ['#9A6BE0', '#3FC9C4'], links: ['#22B573', '#3C8527'], about: ['#E0533D', '#E8913A'] };
|
||||
var zc = function (k) { return '--zc:' + ZC[k][0] + ';--zc2:' + ZC[k][1]; };
|
||||
window.JZP = { esc: esc, ARROW: ARROW, DIAG: DIAG, ZC: ZC };
|
||||
|
||||
/* 站内文件地址:路径里有空格 / 中文 / 括号,按段编码(# ? 之类也不会被当成网址的一部分) */
|
||||
function fileUrl(p) { return p ? String(p).split('/').map(encodeURIComponent).join('/') : ''; }
|
||||
var MEDIA = C.media || {};
|
||||
function thumbOf(src) { var m = src && MEDIA[src]; return (m && m.t) || src || ''; }
|
||||
function ratioOf(src) { var m = src && MEDIA[src]; return (m && m.r > 0) ? m.r : 0; }
|
||||
window.JZP.fileUrl = fileUrl; window.JZP.thumbOf = thumbOf; window.JZP.ratioOf = ratioOf;
|
||||
|
||||
/* 「关于」里的简易写法:只认 [文字](https://…) 链接 和 `代码`,其余一律纯文本;空行分段 */
|
||||
function mini(text) {
|
||||
return String(text || '').split(/\n{2,}/).map(function (para) {
|
||||
var out = '', re = /\[([^\]\n]{1,80})\]\((https:\/\/[^\s)]{1,800}|mailto:[^\s)]{1,120})\)|`([^`\n]{1,80})`/g, last = 0, m;
|
||||
while ((m = re.exec(para))) {
|
||||
out += esc(para.slice(last, m.index));
|
||||
out += m[3] != null ? '<code>' + esc(m[3]) + '</code>' : '<a href="' + esc(m[2]) + '" target="_blank" rel="noopener noreferrer">' + esc(m[1]) + '</a>';
|
||||
last = re.lastIndex;
|
||||
}
|
||||
return '<p>' + (out + esc(para.slice(last))).replace(/\n/g, '<br>') + '</p>';
|
||||
}).join('');
|
||||
}
|
||||
window.JZP.mini = mini;
|
||||
|
||||
/* ---------- 全站:页脚 / 「更多」面板 / 公告 / 预览草稿提示 ---------- */
|
||||
(function shell() {
|
||||
var dom = esc(SITE.domain || ''), qq = esc(SITE.qq || ''), qn = esc(SITE.qqName || 'QQ 群');
|
||||
var qqTxt = 'QQ 群:' + qn + ' ' + qq;
|
||||
var foot = $('.foot-in');
|
||||
if (foot) foot.innerHTML = '<a class="brand" href="index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a>'
|
||||
+ '<span>© ' + new Date().getFullYear() + ' ' + dom + '</span>'
|
||||
+ (SITE.qqUrl ? '<a class="foot-qq" href="' + esc(SITE.qqUrl) + '" target="_blank" rel="noopener noreferrer">' + qqTxt + '</a>' : '<span>' + qqTxt + '</span>')
|
||||
+ '<span class="sp"></span><a class="foot-icp" href="https://beian.miit.gov.cn/" target="_blank" rel="noopener noreferrer">' + esc(SITE.icp || '') + '</a>';
|
||||
var mq = $('.more-qq'); if (mq) mq.textContent = 'QQ 群:' + (SITE.qqName || '') + ' ' + (SITE.qq || '');
|
||||
/* 首页公告:后台「公告」打开且在日期范围内才出 */
|
||||
var n = C.hero && C.hero.notice, today = new Date(Date.now() + 8 * 3600e3).toISOString().slice(0, 10);
|
||||
if (n && n.on && n.text && (!n.from || n.from <= today) && (!n.to || n.to >= today) && page === 'home') {
|
||||
var r = document.createElement('div'); r.className = 'ribbon notice'; r.setAttribute('role', 'status');
|
||||
r.innerHTML = '<span><span class="bar" aria-hidden="true"></span>' + esc(n.text) + '</span>';
|
||||
document.body.insertBefore(r, $('header.top'));
|
||||
}
|
||||
if (window.JZ_PREVIEW) {
|
||||
var b = document.createElement('div'); b.className = 'ribbon preview-bar';
|
||||
b.innerHTML = '<span><b>预览草稿</b>:只有你看得到,访客看到的还是已发布的内容 · <a href="admin/">回内容后台</a></span>';
|
||||
document.body.insertBefore(b, document.body.firstChild);
|
||||
/* 站内跳转带上 ?preview=1,换页也继续看草稿 */
|
||||
document.addEventListener('click', function (e) {
|
||||
var a = e.target.closest && e.target.closest('a[href]'); if (!a) return;
|
||||
var h = a.getAttribute('href');
|
||||
if (/^[a-z]+\.html(#.*)?$/.test(h)) a.setAttribute('href', h.replace(/(#.*)?$/, function (x) { return '?preview=1' + x; }));
|
||||
}, true);
|
||||
}
|
||||
})();
|
||||
|
||||
/* ---------- 旧链接兼容:原来的单页版地址(#/gallery、#/universe、#0001 …)跳到对应的新页面 ---------- */
|
||||
function legacy() {
|
||||
var h = location.hash.replace(/^#\/?/, '').replace(/\/+$/, '');
|
||||
var map = { gallery: 'gallery.html', apps: 'tools.html', universe: 'universe.html', rack: 'universe.html', links: 'links.html', about: 'about.html' };
|
||||
if (map[h]) location.replace(map[h] + location.search);
|
||||
else if (/^\d{4}$/.test(h)) location.replace('universe.html' + location.search + '#' + h);
|
||||
}
|
||||
if (page === 'home') { if (location.hash) legacy(); addEventListener('hashchange', legacy); } // 在首页上改地址栏的 # 也要跳
|
||||
|
||||
/* ---------- 共用小件 ---------- */
|
||||
var GALLERY = (C.gallery || []).filter(function (g) { return !g.hidden; });
|
||||
function dateOf(g) { // 以「分类/日期子目录」为准(和原来一致),路径没日期就用 date
|
||||
var src = g.src || (g.frames && g.frames[0] && g.frames[0].src) || '';
|
||||
var m = /(\d{4})(\d{2})(\d{2})/.exec(src);
|
||||
if (m) { var d = new Date(Date.UTC(+m[1], Math.min(12, Math.max(1, +m[2])) - 1, 1)); d.setUTCDate(+m[3]); return d.toISOString().slice(0, 10); }
|
||||
return g.date || '';
|
||||
}
|
||||
GALLERY.forEach(function (g) { g.date = dateOf(g); });
|
||||
window.JZP.gallery = GALLERY;
|
||||
function latestStills(n) { // 最新的几张「能当封面」的作品(图片 / 全景 / 视频首帧)
|
||||
return GALLERY.slice().sort(function (a, b) { return a.date < b.date ? 1 : a.date > b.date ? -1 : 0; })
|
||||
.map(function (g) { var s = g.src || (g.frames && g.frames[0] && g.frames[0].src) || ''; return { g: g, img: thumbOf(s) }; })
|
||||
.filter(function (x) { return x.img && !/\.(mp4|webm)$/i.test(x.img); }).slice(0, n);
|
||||
}
|
||||
var U = window.JZ_UNIVERSE || {};
|
||||
function universes() {
|
||||
var list = (C.universe && C.universe.UNIVERSES) || U.UNIVERSES || [];
|
||||
var looks = (C.universe && C.universe.LOOKS) || U.LOOKS || {};
|
||||
return { lit: list.filter(function (u) { return !u.empty; }), empty: list.filter(function (u) { return u.empty; }), looks: looks };
|
||||
}
|
||||
window.JZP.universes = universes;
|
||||
function linkRow(l) {
|
||||
var mail = /^mailto:/i.test(l.url || '');
|
||||
return '<a class="board-row flip" href="' + esc(l.url) + '"' + (mail ? '' : ' target="_blank" rel="noopener noreferrer"') + '>'
|
||||
+ '<span class="dest"><b>' + esc(l.name) + '</b></span><span class="kind">' + esc(l.desc || '') + '</span><span></span>'
|
||||
+ '<span class="act">' + (mail ? '写信 ' + ARROW_SM : '打开 ' + DIAG) + '</span></a>';
|
||||
}
|
||||
function setText(sel, v) { var el = $(sel); if (el && v) el.textContent = v; }
|
||||
|
||||
/* ================================================================ 首页 */
|
||||
if (page === 'home') {
|
||||
var hero = C.hero || {};
|
||||
setText('#hTagline', hero.tagline); setText('#hCta1 .t', hero.cta1); setText('#hCta2', hero.cta2);
|
||||
|
||||
/* 手机:最新作品两张 */
|
||||
var duo = $('#homeDuo');
|
||||
if (duo) duo.innerHTML = latestStills(2).map(function (x) {
|
||||
return '<a class="crystal" href="gallery.html"><img src="' + esc(fileUrl(x.img)) + '" alt="' + esc(x.g.title) + '" loading="lazy" decoding="async">'
|
||||
+ '<span class="cap">' + esc(x.g.title) + '<small>' + esc(x.g.date) + '</small></span></a>';
|
||||
}).join('');
|
||||
|
||||
/* 桌面:「都有些什么」五间屋 */
|
||||
var dir = $('#homeDir');
|
||||
if (dir) {
|
||||
var st = latestStills(2), first = st[0] && st[0].g;
|
||||
var apps = C.apps || [];
|
||||
var uv = universes();
|
||||
var links = C.links || [];
|
||||
var story = (C.about && C.about.story) || '';
|
||||
var q = (story.match(/^[^。!?]*[。!?]?/) || [story])[0] || story; // 第一句(别用后行断言:老 iOS Safari 不认,整个脚本会挂)
|
||||
var rack = uv.lit.map(function (u) { var t = u.tone || ((uv.looks[u.no] || {}).accent) || '#E6E1D6'; return '<i class="lit" style="--t:' + esc(t) + '"></i>'; }).join('')
|
||||
+ uv.empty.map(function () { return '<i></i>'; }).join('');
|
||||
var cloud = links.slice(0, 6).map(function (l) { return '<span class="chip">' + esc(l.name) + '</span>'; }).join('')
|
||||
+ (links.length > 6 ? '<span class="chip">+' + (links.length - 6) + '</span>' : '');
|
||||
dir.innerHTML =
|
||||
'<a class="room big crystal" href="gallery.html" style="' + zc('gallery') + '"><span class="no num">01</span><h3>画展</h3>'
|
||||
+ '<p class="desc">' + esc((C.boards && C.boards.gallery) || '画的图、渲染图和视频,按时间排好了。') + '</p>'
|
||||
+ '<div class="peek">' + st.map(function (x) { return '<img src="' + esc(fileUrl(x.img)) + '" alt="作品:' + esc(x.g.title) + '" loading="lazy" decoding="async">'; }).join('') + '</div>'
|
||||
+ (first ? '<div class="peek-cap"><span>最新:' + esc(first.title) + '</span><span class="num">' + esc(first.date) + '</span></div>' : '')
|
||||
+ '<div class="foot"><span>' + GALLERY.length + ' 件</span><span class="go">去看看 ' + ARROW_SM + '</span></div></a>'
|
||||
+ '<a class="room crystal" href="tools.html" style="' + zc('tools') + '"><span class="no num">02</span><h3>工具与开源</h3><ul class="mini-list">'
|
||||
+ apps.slice(0, 4).map(function (a) { return '<li>' + esc(a.name) + '<span class="chip">' + esc(a.status || (a.oss ? '开源' : '')) + '</span></li>'; }).join('')
|
||||
+ '</ul><div class="foot"><span>' + apps.length + ' 个</span><span class="go">去看看 ' + ARROW_SM + '</span></div></a>'
|
||||
+ '<a class="room crystal" href="universe.html" style="' + zc('universe') + '"><span class="no num">03</span><h3>金钻宇宙</h3>'
|
||||
+ '<p class="desc">金钻自己编的平行世界,已经写了 ' + uv.lit.length + ' 个。</p><div class="mini-rack" aria-hidden="true">' + rack + '</div>'
|
||||
+ '<div class="foot"><span>' + (uv.empty.length ? '还空着 ' + uv.empty.length + ' 个' : '都写满了') + '</span><span class="go">去看看 ' + ARROW_SM + '</span></div></a>'
|
||||
+ '<a class="room crystal" href="links.html" style="' + zc('links') + '"><span class="no num">04</span><h3>平台入口</h3><div class="plat-cloud">' + cloud + '</div>'
|
||||
+ '<div class="foot"><span>' + links.length + ' 个平台</span><span class="go">去看看 ' + ARROW_SM + '</span></div></a>'
|
||||
+ '<a class="room crystal" href="about.html" style="' + zc('about') + '"><span class="no num">05</span><h3>关于</h3>'
|
||||
+ '<p class="quote">' + esc(q.length > 40 ? q.slice(0, 38) + '……' : q) + '</p>'
|
||||
+ '<div class="foot"><span>名字由来、交流群</span><span class="go">去看看 ' + ARROW_SM + '</span></div></a>';
|
||||
}
|
||||
|
||||
/* 在别的平台找金钻:挑几个常用的(没有就按顺序取前 6 个) */
|
||||
var hb = $('#homeBoard');
|
||||
if (hb) {
|
||||
var L = C.links || [], pick = ['bili', 'douyin', 'xiaohongshu', 'steam', 'github', 'workshop'];
|
||||
var rows = pick.map(function (k) { return L.filter(function (l) { return l.key === k; })[0]; }).filter(Boolean);
|
||||
if (rows.length < 4) rows = L.slice(0, 6);
|
||||
hb.innerHTML = rows.map(linkRow).join('');
|
||||
}
|
||||
|
||||
/* 自助渲染:渲染机在不在线、每张多少钱(读下单那边的接口 / 内容文件,拿不到就不写) */
|
||||
(function desk() {
|
||||
var s = $('#deskStatus'), p = $('#deskPrice');
|
||||
/* 价格读下单页公开的价格接口(内容后台的原始 order.json 不对外,2026-10-06 安全加固) */
|
||||
fetch('/order/api/payinfo', { cache: 'no-store' }).then(function (r) { return r.ok ? r.json() : null; }).then(function (o) {
|
||||
var per = o && o.per;
|
||||
if (p && per) p.textContent = '每张 ' + per + ' 元起,一般 40 秒左右出图';
|
||||
}).catch(function () {});
|
||||
fetch('/order/api/status', { cache: 'no-store' }).then(function (r) { return r.ok ? r.json() : null; }).then(function (j) {
|
||||
if (!s) return;
|
||||
if (!j) { s.hidden = true; return; }
|
||||
s.textContent = j.online ? '渲染机在线' : '渲染机暂时离线(下的单会排队,开机就做)';
|
||||
s.classList.toggle('off', !j.online);
|
||||
}).catch(function () { if (s) s.hidden = true; }); // 查不到就不说,别一直挂着「查询中」
|
||||
})();
|
||||
}
|
||||
|
||||
/* ================================================================ 工具与开源 */
|
||||
if (page === 'tools') {
|
||||
var A = C.apps || [];
|
||||
setText('#tN', String(A.length));
|
||||
var types = ['全部'].concat(A.map(function (a) { return a.type; }).filter(function (t, i, arr) { return t && arr.indexOf(t) === i; }));
|
||||
var seg = $('#tSeg'), box = $('#tRows'), cur = '全部';
|
||||
function toolCard(a) {
|
||||
var chips = [a.type, a.status].filter(Boolean).map(function (t) { return '<span class="chip">' + esc(t) + '</span>'; }).join('');
|
||||
var kv = (a.ver ? '<span>版本 <b class="num">' + esc(a.ver) + '</b></span>' : '') + (a.size && a.size !== '—' ? '<span>大小 <b class="num">' + esc(a.size) + '</b></span>' : '');
|
||||
var acts = '';
|
||||
if (a.url) {
|
||||
var ext = /^https?:/i.test(a.url);
|
||||
acts += '<a class="btn btn-prism btn-sm" href="' + esc(a.url) + '"' + (ext ? ' target="_blank" rel="noopener noreferrer"' : '') + (a.web || !ext ? '' : ' download') + '>' + esc((a.btn || (a.web ? '打开' : '下载')).replace(/\s*[→↓]\s*$/, '')) + ' ' + ARROW_SM + '</a>';
|
||||
}
|
||||
if (a.repo) acts += '<a class="btn btn-crystal btn-sm" href="' + esc(a.repo) + '" target="_blank" rel="noopener noreferrer">看代码 ' + DIAG + '</a>';
|
||||
if (!acts) acts = '<span class="btn btn-crystal btn-sm" aria-disabled="true" style="opacity:.55;cursor:default">还没上架</span>';
|
||||
return '<article class="tool crystal"><h3>' + esc(a.name) + '</h3><div class="chips">' + chips + '</div><p>' + esc(a.desc || '') + '</p>'
|
||||
+ (kv ? '<div class="kv">' + kv + '</div>' : '') + '<div class="acts">' + acts + '</div></article>';
|
||||
}
|
||||
function draw() {
|
||||
var pick = function (a) { return cur === '全部' || a.type === cur; };
|
||||
var groups = [['开源', function (a) { return a.oss; }], ['在线使用', function (a) { return !a.oss && a.web; }], ['闭源工具', function (a) { return !a.oss && !a.web; }]];
|
||||
box.innerHTML = groups.map(function (g) {
|
||||
var list = A.filter(function (a) { return g[1](a) && pick(a); });
|
||||
return list.length ? '<div class="row-title">' + g[0] + '</div><div class="shelf">' + list.map(toolCard).join('') + '</div>' : '';
|
||||
}).join('') || '<p class="note">这一类还没有东西。</p>';
|
||||
seg.querySelectorAll('button').forEach(function (b) { b.setAttribute('aria-pressed', String(b.getAttribute('data-t') === cur)); });
|
||||
}
|
||||
if (seg) {
|
||||
seg.innerHTML = types.map(function (t) { return '<button type="button" data-t="' + esc(t) + '" aria-pressed="false">' + esc(t) + '</button>'; }).join('');
|
||||
seg.addEventListener('click', function (e) { var b = e.target.closest('button'); if (!b) return; cur = b.getAttribute('data-t'); draw(); });
|
||||
}
|
||||
if (box) draw();
|
||||
}
|
||||
|
||||
/* ================================================================ 平台入口 */
|
||||
if (page === 'links') {
|
||||
var LL = C.links || [], G = C.linkGroups || [];
|
||||
setText('#lN', String(LL.length));
|
||||
var bd = $('#lBoard');
|
||||
if (bd) bd.innerHTML = G.map(function (g) {
|
||||
var items = LL.filter(function (l) { return l.group === g.id; });
|
||||
return items.length ? '<div class="board-group flip">' + esc(g.name) + '</div>' + items.map(linkRow).join('') : '';
|
||||
}).join('') + LL.filter(function (l) { return !G.some(function (g) { return g.id === l.group; }); }).map(linkRow).join('');
|
||||
}
|
||||
|
||||
/* ================================================================ 关于 */
|
||||
if (page === 'about') {
|
||||
var AB = C.about || {};
|
||||
var story = $('#aStory'); if (story && AB.story) story.innerHTML = mini(AB.story);
|
||||
var cr = $('#aCredits');
|
||||
if (cr && AB.cards && AB.cards.length) cr.innerHTML = AB.cards.map(function (c) {
|
||||
return '<section class="credit crystal"><span class="k">' + esc(c.k) + '</span><h3>' + esc(c.h) + '</h3>' + mini(c.p) + '</section>';
|
||||
}).join('');
|
||||
var ft = $('#aFoot'); if (ft && AB.foot) ft.innerHTML = mini(AB.foot).replace(/^<p>|<\/p>$/g, '');
|
||||
}
|
||||
|
||||
/* ================================================================ 金钻宇宙:下面的档案卡片(星系图在页面自己的模块脚本里) */
|
||||
if (page === 'universe') {
|
||||
var uv2 = universes();
|
||||
var meta = $('.room-head .meta'); if (meta) meta.innerHTML = '写好 <b>' + uv2.lit.length + '</b> 个<br>空着 ' + uv2.empty.length + ' 个';
|
||||
/* 卡片左上角的小色块:预览站按星球风格配的颜色;后来新加的风格就用这条世界线自己的主色 */
|
||||
var SW = { crystal: '#7FE7FF', paper: '#F6F1E4', ice: '#BFE4FF', neon: '#5A3FB0', duality: '#F2B84B' };
|
||||
var ul = $('#uniList');
|
||||
if (ul) ul.innerHTML = uv2.lit.map(function (u) {
|
||||
var lk = uv2.looks[u.no] || {};
|
||||
return '<button type="button" class="ucell" data-no="' + esc(u.no) + '" style="--sw:' + esc(SW[lk.style] || lk.accent || u.tone || '#9AA0B4') + '">'
|
||||
+ '<span class="sw" aria-hidden="true"></span><span class="no">' + esc(u.no) + ' · ' + esc(u.kind || '') + '</span><h3>' + esc(u.name) + '</h3>'
|
||||
+ '<span class="tg">' + esc(u.tag || '') + '</span><span class="go">在星图里看 →</span></button>';
|
||||
}).join('');
|
||||
var us = $('#uniSlots');
|
||||
if (us) { us.innerHTML = uv2.empty.map(function (u) { return '<button type="button" data-no="' + esc(u.no) + '"><b>' + esc(u.no) + '</b>空槽</button>'; }).join(''); us.hidden = !uv2.empty.length; }
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,10 @@
|
||||
/* 站点信息:全站页脚 / 「更多」面板 / 关于页用的几项固定信息,只在这一个文件里写。
|
||||
仓库里是占位;正式服务器上换成真实值的这一份(部署时只替换这个文件,别去改各个页面)。 */
|
||||
window.JZ_SITE = {
|
||||
domain: 'example.com', // 页脚 © 后面的域名
|
||||
qq: '123456789', // QQ 群号
|
||||
qqName: '屑钻小窝', // QQ 群名
|
||||
qqUrl: 'https://example.com/group-invite', // 加群链接(空 = 不给链接)
|
||||
icp: '备案号(已移除)', // 备案号(页脚链到 beian.miit.gov.cn)
|
||||
mail: 'feedback@example.com' // 反馈邮箱
|
||||
};
|
||||
@@ -0,0 +1,935 @@
|
||||
/* 金钻客栈 · 全站样式(2026-10-06 起以设计预览站为准)—— 白光藏色 × MC 方块。
|
||||
一眼看过去是白的;颜色只藏在亮部:晶体边缘的淡彩细边、扫过的高光、钻石折射出的光谱。
|
||||
按钮是一块三棱镜:白色晶体 + 棱角两端 + 底部折射光谱,投下的不是灰影,而是红蓝分开的淡彩焦散光。 */
|
||||
|
||||
@font-face{font-family:'OPPO Sans';src:url('../fonts/OPPOSans-R.woff2') format('woff2');font-weight:400;font-display:swap}
|
||||
@font-face{font-family:'OPPO Sans';src:url('../fonts/OPPOSans-B.woff2') format('woff2');font-weight:700;font-display:swap}
|
||||
|
||||
:root{
|
||||
--ink:#1E2440; --ink-2:#4A5070; --ink-3:#737891;
|
||||
--bg:#FAFBFE; --white:#FFFFFF;
|
||||
--line:rgba(30,36,64,.08); --line-2:rgba(30,36,64,.14);
|
||||
/* 藏起来的颜色:低饱和光谱 */
|
||||
--spec:linear-gradient(90deg,#FF9BB0 0%,#FFCC7A 25%,#94E3B4 50%,#8CC8FF 75%,#B9A2FF 100%);
|
||||
--edge:linear-gradient(125deg,rgba(255,150,172,.55) 0%,rgba(255,210,135,.5) 26%,rgba(150,228,186,.5) 50%,rgba(140,200,255,.58) 74%,rgba(190,165,255,.58) 100%);
|
||||
--edge-strong:linear-gradient(125deg,#FFB3C3 0%,#FFD99A 26%,#A9EBC6 50%,#A6D5FF 74%,#CDB9FF 100%);
|
||||
--lift:0 1px 0 rgba(255,255,255,1) inset,0 18px 36px -24px rgba(110,130,220,.38),0 12px 26px -22px rgba(255,140,120,.28);
|
||||
--lift-hi:0 1px 0 rgba(255,255,255,1) inset,0 26px 48px -26px rgba(110,130,220,.45),0 16px 32px -24px rgba(255,140,120,.34);
|
||||
--r-xl:30px; --r-lg:22px; --r:18px; --r-sm:12px;
|
||||
--ease:cubic-bezier(.23,1,.32,1);
|
||||
--font:'OPPO Sans',-apple-system,BlinkMacSystemFont,'PingFang SC','Hiragino Sans GB','Microsoft YaHei',sans-serif;
|
||||
--wrap:1200px;
|
||||
--sparks:#FFB3C3 #FFD99A #A9EBC6 #A6D5FF #CDB9FF #FFC2D0 #B5DCFF;
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
html{-webkit-text-size-adjust:100%;scroll-behavior:smooth}
|
||||
body{margin:0;min-height:100vh;color:var(--ink);font:16px/1.7 var(--font);-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility;
|
||||
background:
|
||||
radial-gradient(38% 30% at 4% 0%,rgba(150,215,255,.16) 0%,transparent 70%),
|
||||
radial-gradient(34% 28% at 100% 6%,rgba(255,170,200,.13) 0%,transparent 70%),
|
||||
radial-gradient(46% 36% at 70% 100%,rgba(255,215,150,.12) 0%,transparent 70%),
|
||||
radial-gradient(40% 34% at 0% 70%,rgba(170,235,200,.10) 0%,transparent 70%),
|
||||
var(--bg)}
|
||||
img{max-width:100%;display:block}
|
||||
a{color:inherit}
|
||||
button{font:inherit;color:inherit}
|
||||
.wrap{max-width:var(--wrap);margin:0 auto;padding:0 24px}
|
||||
.num{font-variant-numeric:tabular-nums}
|
||||
:focus-visible{outline:2px solid #8CC8FF;outline-offset:3px;border-radius:10px}
|
||||
.gem-img{background:url('gem.webp') center/contain no-repeat;image-rendering:pixelated}
|
||||
|
||||
/* ===== 晶体面板:白色主体 + 淡彩细边 + 带色的柔光(不是灰影) ===== */
|
||||
.crystal{position:relative;border:1px solid rgba(255,255,255,.78);
|
||||
background:linear-gradient(160deg,rgba(255,255,255,.80) 0%,rgba(255,255,255,.56) 100%);
|
||||
box-shadow:inset 0 1px 0 rgba(255,255,255,.95),inset 0 -1px 0 rgba(255,255,255,.35),0 22px 44px -28px rgba(100,110,190,.38)}
|
||||
|
||||
/* 毛玻璃后面的彩光:几团缓慢漂动的柔光,玻璃把它们模糊成淡淡的颜色 */
|
||||
.orbs{position:fixed;inset:-12%;z-index:-2;overflow:hidden;pointer-events:none;translate:calc(var(--mx,0) * -36px) calc(var(--my,0) * -28px)}
|
||||
.orbs i{position:absolute;border-radius:50%;will-change:transform;animation:var(--path) var(--t,22s) ease-in-out infinite alternate}
|
||||
.orbs .o1{width:62vmax;height:62vmax;left:-14vmax;top:-18vmax;background:radial-gradient(circle,rgba(255,182,204,.78) 0%,rgba(255,182,204,0) 66%);--path:p1;--t:19s}
|
||||
.orbs .o2{width:70vmax;height:70vmax;right:-22vmax;top:-6vmax;background:radial-gradient(circle,rgba(160,206,255,.78) 0%,rgba(160,206,255,0) 66%);--path:p2;--t:24s}
|
||||
.orbs .o3{width:56vmax;height:56vmax;left:-6vmax;top:42%;background:radial-gradient(circle,rgba(170,238,204,.72) 0%,rgba(170,238,204,0) 66%);--path:p3;--t:21s}
|
||||
.orbs .o4{width:64vmax;height:64vmax;right:-10vmax;bottom:-24vmax;background:radial-gradient(circle,rgba(255,214,160,.78) 0%,rgba(255,214,160,0) 66%);--path:p4;--t:27s}
|
||||
.orbs .o5{width:50vmax;height:50vmax;left:34%;top:18%;background:radial-gradient(circle,rgba(206,188,255,.72) 0%,rgba(206,188,255,0) 66%);--path:p5;--t:17s}
|
||||
@keyframes p1{0%{transform:translate3d(0,0,0) scale(1)}50%{transform:translate3d(18vw,10vh,0) scale(1.12)}100%{transform:translate3d(6vw,26vh,0) scale(.94)}}
|
||||
@keyframes p2{0%{transform:translate3d(0,0,0) scale(1)}50%{transform:translate3d(-20vw,14vh,0) scale(.9)}100%{transform:translate3d(-8vw,30vh,0) scale(1.1)}}
|
||||
@keyframes p3{0%{transform:translate3d(0,0,0) scale(1)}50%{transform:translate3d(24vw,-12vh,0) scale(1.1)}100%{transform:translate3d(36vw,6vh,0) scale(.92)}}
|
||||
@keyframes p4{0%{transform:translate3d(0,0,0) scale(1)}50%{transform:translate3d(-26vw,-16vh,0) scale(1.08)}100%{transform:translate3d(-12vw,-30vh,0) scale(.95)}}
|
||||
@keyframes p5{0%{transform:translate3d(0,0,0) scale(1)}50%{transform:translate3d(-14vw,20vh,0) scale(1.15)}100%{transform:translate3d(12vw,-10vh,0) scale(.9)}}
|
||||
/* ===== 灵动:卡片随鼠标轻微倾斜,玻璃上一块跟着鼠标走的柔光;滚动时依次浮现 ===== */
|
||||
.fx{transform:perspective(1000px) rotateX(var(--rx,0deg)) rotateY(var(--ry,0deg)) translateY(var(--ty,0px));transition:transform .55s var(--ease),box-shadow .3s var(--ease)}
|
||||
.fx.on{transition:transform .12s linear,box-shadow .3s var(--ease)}
|
||||
.fx::after{content:"";position:absolute;inset:0;border-radius:inherit;pointer-events:none;opacity:0;transition:opacity .35s var(--ease);
|
||||
background:radial-gradient(380px circle at var(--px,50%) var(--py,50%),rgba(255,255,255,.7) 0%,rgba(255,255,255,0) 46%)}
|
||||
.fx.on::after{opacity:.55}
|
||||
.js .rv{opacity:0;translate:0 22px}
|
||||
/* ⚠️ 2026-10-07:这条优先级比 .room/.tool/.art/.path 自己的 transition 高,原来只写了 opacity/translate ——
|
||||
卡片一浮现完,悬停上浮、跟鼠标倾斜、阴影、描边全都没了过渡(画展大卡最明显:进出都是"跳")。
|
||||
浮现那两项照旧带依次延迟;悬停相关的几项不带延迟,补回来。 */
|
||||
.js .rv.in{opacity:1;translate:0 0;transition:opacity .7s var(--ease) var(--d,0ms),translate .7s var(--ease) var(--d,0ms),transform .45s var(--ease),box-shadow .35s var(--ease),border-color .35s var(--ease)}
|
||||
|
||||
/* ---------- 预览提示条 ---------- */
|
||||
.ribbon{display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:6px 14px;padding:8px 16px;font-size:12.5px;color:var(--ink-2);background:rgba(255,255,255,.45);border-bottom:1px solid rgba(255,255,255,.7)}
|
||||
.ribbon b{color:var(--ink)}
|
||||
.ribbon .bar{display:inline-block;width:38px;height:3px;border-radius:2px;background:var(--spec);vertical-align:middle;margin-right:8px}
|
||||
|
||||
/* ---------- 顶栏 ---------- */
|
||||
.top{position:sticky;top:0;z-index:50;background:rgba(255,255,255,.48);-webkit-backdrop-filter:saturate(1.4) blur(10px);backdrop-filter:saturate(1.4) blur(10px);box-shadow:inset 0 -1px 0 rgba(255,255,255,.8)}
|
||||
.top::after{content:"";position:absolute;left:0;right:0;bottom:0;height:1px;background:rgba(30,36,64,.06)}
|
||||
.top-in{display:flex;align-items:center;gap:20px;min-height:66px}
|
||||
.brand{display:flex;align-items:center;gap:10px;text-decoration:none;flex:none}
|
||||
.brand i{width:30px;height:30px;filter:drop-shadow(-2px 3px 4px rgba(255,110,140,.25)) drop-shadow(2px 3px 4px rgba(70,140,255,.25))}
|
||||
.brand b{font-size:18px;letter-spacing:.04em}
|
||||
.nav{display:flex;gap:2px;flex:1;min-width:0;overflow-x:auto;scrollbar-width:none}
|
||||
.nav::-webkit-scrollbar{display:none}
|
||||
.nav a{position:relative;display:flex;align-items:center;gap:8px;height:40px;padding:0 13px;border-radius:999px;text-decoration:none;font-size:15px;color:var(--ink-2);white-space:nowrap;transition:background .18s var(--ease),color .18s var(--ease)}
|
||||
.nav a:hover{background:rgba(255,255,255,.95);color:var(--ink)}
|
||||
.nav a .dm{width:8px;height:8px;border-radius:2px;transform:rotate(45deg);background:linear-gradient(135deg,var(--zc),var(--zc2,var(--zc)));opacity:.8;flex:none}
|
||||
.nav a[aria-current=page]{color:var(--ink);font-weight:700;border:1px solid transparent;background:linear-gradient(#fff,#fff) padding-box,var(--edge) border-box;box-shadow:0 8px 18px -12px rgba(110,130,220,.45)}
|
||||
.nav a[aria-current=page]::after{content:"";position:absolute;left:16px;right:16px;bottom:4px;height:2px;border-radius:2px;background:var(--spec)}
|
||||
.desk-btn{flex:none}
|
||||
.btn-pill{display:inline-flex;align-items:center;gap:9px;height:44px;padding:0 18px 0 6px;border-radius:999px;text-decoration:none;font-size:14.5px;font-weight:700;color:var(--ink);
|
||||
background:rgba(255,255,255,.82);border:1px solid rgba(255,255,255,.95);
|
||||
box-shadow:inset 0 1px 0 #fff,0 12px 26px -16px rgba(120,110,230,.6),0 8px 18px -14px rgba(255,140,170,.55);transition:transform .2s var(--ease),box-shadow .2s var(--ease),background .2s var(--ease)}
|
||||
.btn-pill .ic{width:32px;height:32px;border-radius:50%;background:#fff url('gem.webp') center/19px no-repeat;image-rendering:pixelated;box-shadow:0 2px 8px -2px rgba(110,120,220,.45)}
|
||||
.btn-pill svg{opacity:.55;transition:transform .2s var(--ease),opacity .2s var(--ease)}
|
||||
.btn-pill:hover{background:rgba(255,255,255,.78);transform:translateY(-1px);box-shadow:inset 0 1px 0 #fff,0 16px 30px -16px rgba(120,110,230,.7),0 10px 22px -14px rgba(255,140,170,.6)}
|
||||
.btn-pill:hover svg{transform:translateX(2px);opacity:.9}
|
||||
.btn-pill:active{transform:translateY(1px)}
|
||||
|
||||
/* ===== 按钮:统一毛玻璃胶囊(和顶栏「自助渲染」同一套) ===== */
|
||||
.btn{position:relative;display:inline-flex;align-items:center;justify-content:center;gap:8px;height:46px;padding:0 22px;border-radius:999px;
|
||||
font-size:15px;font-weight:700;color:var(--ink);text-decoration:none;cursor:pointer;white-space:nowrap;
|
||||
border:1px solid rgba(255,255,255,.9);
|
||||
transition:transform .2s var(--ease),box-shadow .2s var(--ease),background .2s var(--ease)}
|
||||
.btn svg{flex:none;transition:transform .2s var(--ease)}
|
||||
.btn:hover svg{transform:translateX(2px)}
|
||||
.btn:active{transform:translateY(1px)}
|
||||
/* 主按钮:更实一点的白玻璃 + 淡彩投影 */
|
||||
.btn-prism{background:rgba(255,255,255,.8);
|
||||
box-shadow:inset 0 1px 0 #fff,0 12px 26px -16px rgba(120,110,230,.6),0 8px 18px -14px rgba(255,140,170,.55)}
|
||||
.btn-prism:hover{background:rgba(255,255,255,.95);transform:translateY(-1px);
|
||||
box-shadow:inset 0 1px 0 #fff,0 16px 30px -16px rgba(120,110,230,.7),0 10px 22px -14px rgba(255,140,170,.6)}
|
||||
/* 次按钮:更透一点 */
|
||||
.btn-crystal{background:rgba(255,255,255,.6);font-weight:600;
|
||||
box-shadow:inset 0 1px 0 rgba(255,255,255,.9),0 8px 20px -16px rgba(110,120,200,.45)}
|
||||
.btn-crystal:hover{background:rgba(255,255,255,.7);transform:translateY(-1px)}
|
||||
.btn-sm{height:40px;padding:0 16px;font-size:14px}
|
||||
.btn[disabled]{opacity:.55;cursor:not-allowed;transform:none;filter:none}
|
||||
|
||||
/* ---------- 小部件 ---------- */
|
||||
.chip{display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 11px;border-radius:999px;border:1px solid rgba(255,255,255,.85);background:rgba(255,255,255,.6);font-size:12.5px;color:var(--ink-2);white-space:nowrap}
|
||||
.chip::before{display:none}
|
||||
.chip.ok{--c:#3CC985} .chip.wait{--c:#F5B23E} .chip.oss{--c:#45B8E0} .chip.plain::before{display:none}
|
||||
.status{display:inline-flex;align-items:center;gap:8px;font-size:13.5px;color:var(--ink-2)}
|
||||
.status::before{display:none}
|
||||
.dm-big{display:inline-block;width:16px;height:16px;border-radius:4px;transform:rotate(45deg);background:var(--edge-strong);box-shadow:-3px 4px 8px -2px rgba(255,110,140,.35),3px 4px 8px -2px rgba(70,140,255,.35)}
|
||||
|
||||
/* ---------- 大堂首屏:白色观景窗,钻石把白光折射成光谱 ---------- */
|
||||
.hero{padding:28px 0 4px}
|
||||
.window{border-radius:var(--r-xl);padding:10px}
|
||||
.sky{position:relative;overflow:hidden;border-radius:22px;min-height:500px;display:grid;grid-template-columns:1.15fr .85fr;align-items:center;isolation:isolate;
|
||||
background:radial-gradient(60% 70% at 12% 18%,rgba(255,196,214,.34) 0%,transparent 70%),radial-gradient(55% 65% at 88% 26%,rgba(176,212,255,.38) 0%,transparent 70%),radial-gradient(50% 60% at 55% 105%,rgba(255,222,176,.32) 0%,transparent 70%),linear-gradient(165deg,rgba(255,255,255,.84) 0%,rgba(255,255,255,.70) 100%)}
|
||||
.sky canvas{position:absolute;inset:0;width:100%;height:100%;z-index:-1}
|
||||
.beam{position:absolute;z-index:-2;left:-12%;top:40%;width:86%;height:150px;transform:rotate(-14deg);transform-origin:100% 50%;
|
||||
background:linear-gradient(90deg,rgba(255,255,255,0) 0%,rgba(255,255,255,.95) 70%,rgba(255,255,255,.4) 100%);filter:blur(6px)}
|
||||
.fan{position:absolute;z-index:-1;left:72%;top:46%;width:1100px;height:1100px;transform:translate(-50%,-50%);
|
||||
background:conic-gradient(from 68deg at 50% 50%,transparent 0deg,rgba(255,120,150,.55) 7deg,rgba(255,196,95,.55) 15deg,rgba(110,214,150,.5) 23deg,rgba(95,175,255,.55) 31deg,rgba(165,125,255,.55) 39deg,transparent 48deg,transparent 360deg);
|
||||
-webkit-mask:radial-gradient(circle,rgba(0,0,0,.9) 8%,rgba(0,0,0,.45) 28%,transparent 50%);mask:radial-gradient(circle,rgba(0,0,0,.9) 8%,rgba(0,0,0,.45) 28%,transparent 50%);
|
||||
filter:blur(8px);opacity:.9;will-change:transform;animation:sway 9s ease-in-out infinite alternate}
|
||||
@keyframes sway{0%{rotate:-7deg;scale:.96}100%{rotate:6deg;scale:1.05}}
|
||||
.hero-copy{padding:56px 56px 76px;display:flex;flex-direction:column;gap:20px;align-items:flex-start;translate:calc(var(--mx,0) * -6px) calc(var(--my,0) * -4px);transition:translate .2s linear}
|
||||
.tag-l{display:inline-flex;align-items:center;gap:8px;height:32px;padding:0 14px;border-radius:999px;border:1px solid rgba(255,255,255,.85);background:rgba(255,255,255,.6);font-size:13px;font-weight:700;color:var(--ink-2)}
|
||||
.tag-l i{width:8px;height:8px;border-radius:2px;transform:rotate(45deg);background:var(--spec)}
|
||||
.hero h1{margin:0;font-size:clamp(52px,7.4vw,92px);line-height:1.02;letter-spacing:.03em}
|
||||
.hero p{margin:0;font-size:17.5px;line-height:1.8;color:var(--ink-2);max-width:27em;text-wrap:pretty}
|
||||
.hero .cta{display:flex;flex-wrap:wrap;gap:14px;padding-top:6px}
|
||||
.emblem{position:relative;justify-self:center;width:min(320px,74%);aspect-ratio:1;translate:calc(var(--mx,0) * 16px) calc(var(--my,0) * 12px);transition:translate .2s linear}
|
||||
.emblem .halo{position:absolute;inset:6%;border-radius:50%;background:radial-gradient(circle,#FFFFFF 0%,rgba(255,255,255,.85) 40%,rgba(255,255,255,0) 70%)}
|
||||
.emblem .ring{position:absolute;inset:0;border-radius:50%;padding:2px;background:var(--edge-strong);-webkit-mask:linear-gradient(#000 0 0) content-box,linear-gradient(#000 0 0);-webkit-mask-composite:xor;mask:linear-gradient(#000 0 0) content-box exclude,linear-gradient(#000 0 0);opacity:.95;animation:spin 48s linear infinite}
|
||||
.emblem .ring.r2{inset:13%;opacity:.55;padding:1.5px;animation-duration:70s;animation-direction:reverse}
|
||||
.emblem .ring.r3{inset:-9%;opacity:.35;padding:1px}
|
||||
.emblem .gem{position:absolute;inset:27%;filter:drop-shadow(-6px 12px 14px rgba(255,110,140,.28)) drop-shadow(6px 12px 14px rgba(70,140,255,.28));animation:float 7s ease-in-out infinite}
|
||||
.telemetry{position:absolute;left:56px;right:56px;bottom:22px;display:flex;flex-wrap:wrap;gap:6px 22px;font-size:12.5px;color:var(--ink-3)}
|
||||
.telemetry b{color:var(--ink);font-weight:700}
|
||||
@keyframes spin{to{transform:rotate(360deg)}}
|
||||
@keyframes float{50%{transform:translateY(-9px)}}
|
||||
|
||||
/* ---------- 区块标题 ---------- */
|
||||
.sec{padding:60px 0 6px}
|
||||
.sec-h{display:flex;align-items:flex-end;justify-content:space-between;gap:12px 24px;flex-wrap:wrap;margin-bottom:22px}
|
||||
.sec-h h2{margin:0;font-size:30px;line-height:1.2}
|
||||
.sec-h p{margin:6px 0 0;color:var(--ink-3);font-size:15px}
|
||||
.sec-h a{font-size:15px;font-weight:700;text-decoration:none;display:inline-flex;align-items:center;gap:6px}
|
||||
.sec-h a:hover{text-decoration:underline;text-decoration-color:#8CC8FF;text-underline-offset:4px}
|
||||
|
||||
/* ---------- 楼层导览 ---------- */
|
||||
.dir{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));grid-auto-rows:minmax(232px,auto);gap:16px}
|
||||
.room{display:flex;flex-direction:column;gap:10px;padding:24px;border-radius:var(--r-lg);text-decoration:none;overflow:hidden;transition:transform .22s var(--ease),box-shadow .22s var(--ease)}
|
||||
.room:hover{--ty:-4px;box-shadow:var(--lift-hi)}
|
||||
.room::before{content:"";position:absolute;right:-70px;top:-70px;width:200px;height:200px;border-radius:50%;background:radial-gradient(circle,var(--zc) 0%,transparent 68%);opacity:.16;pointer-events:none;transition:opacity .3s var(--ease)}
|
||||
.room:hover::before{opacity:.28}
|
||||
.room .no{font-size:13px;font-weight:700;color:var(--ink-3);letter-spacing:.1em}
|
||||
.room h3{margin:0;font-size:23px;line-height:1.25}
|
||||
.room .desc{margin:0;font-size:14.5px;line-height:1.7;color:var(--ink-2)}
|
||||
.room .foot{margin-top:auto;padding-top:8px;display:flex;justify-content:space-between;align-items:center;gap:8px;font-size:13px;color:var(--ink-3)}
|
||||
.room .go{display:inline-flex;align-items:center;gap:6px;font-weight:700;color:var(--ink);white-space:nowrap;transition:gap .2s var(--ease)}
|
||||
.room:hover .go{gap:10px}
|
||||
.room.big{grid-column:span 2;grid-row:span 2}
|
||||
.room.big .peek{flex:1;min-height:200px}
|
||||
.room.big .peek img{aspect-ratio:auto;height:100%}
|
||||
.peek{display:grid;grid-template-columns:1.25fr 1fr;gap:10px;margin:6px 0 2px}
|
||||
.peek img{width:100%;height:100%;aspect-ratio:4/3;object-fit:cover;border-radius:14px;border:3px solid #fff;box-shadow:-4px 10px 18px -12px rgba(255,110,140,.35),4px 10px 18px -12px rgba(70,140,255,.35)}
|
||||
.peek-cap{display:flex;flex-wrap:wrap;gap:8px;align-items:center;font-size:13px;color:var(--ink-3)}
|
||||
.mini-list{list-style:none;margin:2px 0 0;padding:0;display:flex;flex-direction:column;gap:8px}
|
||||
.mini-list li{display:flex;justify-content:space-between;align-items:center;gap:10px;font-size:14px;font-weight:700}
|
||||
.mini-rack{display:grid;grid-template-columns:repeat(11,minmax(0,1fr));gap:4px;margin-top:4px}
|
||||
.mini-rack i{height:34px;border-radius:5px;background:#fff;border:1px dashed var(--line-2)}
|
||||
.mini-rack i.lit{border:0;background:linear-gradient(180deg,#fff 0%,var(--t) 100%);box-shadow:0 8px 14px -8px var(--t)}
|
||||
.plat-cloud{display:flex;flex-wrap:wrap;gap:6px;margin-top:2px}
|
||||
.quote{margin:2px 0 0;font-size:14.5px;line-height:1.8;color:var(--ink-2)}
|
||||
|
||||
/* ---------- 服务台 ---------- */
|
||||
.desk{display:grid;grid-template-columns:auto 1fr auto;gap:24px;align-items:center;padding:26px 28px;border-radius:var(--r-lg);overflow:hidden}
|
||||
.desk-ic,.svc-ic,.uni-tile{position:relative;display:grid;place-items:center;border:1px solid transparent;background:linear-gradient(160deg,#fff,#F3F5FF) padding-box,var(--edge-strong) border-box;box-shadow:-5px 10px 18px -12px rgba(255,110,140,.4),5px 10px 18px -12px rgba(70,140,255,.4)}
|
||||
.desk-ic{width:66px;height:66px;border-radius:20px}
|
||||
.desk-ic i{width:38px;height:38px}
|
||||
.desk h3{margin:0 0 4px;font-size:21px}
|
||||
.desk p{margin:0;font-size:14.5px;color:var(--ink-2)}
|
||||
.desk .meta{display:flex;flex-wrap:wrap;gap:8px 18px;margin-top:10px;font-size:13.5px;color:var(--ink-3)}
|
||||
.desk .acts{display:flex;flex-wrap:wrap;gap:14px;justify-content:flex-end;align-items:center}
|
||||
|
||||
/* ---------- 出发信息屏(白色晶体版) ---------- */
|
||||
.board{border-radius:var(--r-lg);overflow:hidden}
|
||||
.board-title{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:18px 24px 14px;border-bottom:1px solid var(--line)}
|
||||
.board-title b{font-size:16px;letter-spacing:.06em}
|
||||
.board-title span{font-size:12.5px;color:var(--ink-3)}
|
||||
.board-head,.board-row{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(0,1.2fr) minmax(0,.8fr) auto;gap:16px;align-items:center;padding:0 24px}
|
||||
.board-head{height:40px;font-size:12px;color:var(--ink-3);letter-spacing:.12em;border-bottom:1px solid var(--line)}
|
||||
.board-row{position:relative;min-height:62px;border-bottom:1px solid var(--line);text-decoration:none;color:inherit;transition:background .18s var(--ease)}
|
||||
.board-row:hover{background:rgba(255,255,255,.55)}
|
||||
.board-row:last-child{border-bottom:0}
|
||||
.board-row .dest{display:flex;align-items:baseline;gap:10px;min-width:0}
|
||||
.board-row .dest b{font-size:18px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.board-row .dest small{font-size:11px;color:var(--ink-3);letter-spacing:.12em;white-space:nowrap}
|
||||
.board-row .kind{font-size:14px;color:var(--ink-2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.board-row .gate{justify-self:start;display:inline-flex;align-items:center;height:26px;padding:0 10px;border-radius:999px;font-size:12.5px;color:var(--ink-2);border:1px solid transparent;background:linear-gradient(#fff,#fff) padding-box,var(--edge) border-box}
|
||||
.board-row .act{display:inline-flex;align-items:center;gap:6px;height:34px;padding:0 14px;border-radius:999px;font-size:13px;font-weight:700;color:var(--ink);background:rgba(255,255,255,.7);border:1px solid rgba(255,255,255,.95);box-shadow:inset 0 1px 0 #fff,0 6px 14px -10px rgba(110,120,200,.5);transition:background .2s var(--ease),box-shadow .2s var(--ease)}
|
||||
.board-row:hover .act{background:#fff;box-shadow:inset 0 1px 0 #fff,0 10px 18px -10px rgba(120,110,230,.55)}
|
||||
.board-group{padding:12px 24px 8px;font-size:12px;font-weight:700;letter-spacing:.14em;color:var(--ink-3);border-bottom:1px solid var(--line);background:linear-gradient(90deg,rgba(255,240,245,.6),rgba(240,248,255,.6))}
|
||||
.flip{opacity:0}
|
||||
.flip.in{animation:flipIn .55s var(--ease) both}
|
||||
@keyframes flipIn{from{opacity:0;transform:perspective(700px) rotateX(-75deg);transform-origin:50% 0}to{opacity:1;transform:none}}
|
||||
|
||||
/* ---------- 页脚 ---------- */
|
||||
.foot-site{position:relative;margin-top:80px;background:rgba(255,255,255,.45)}
|
||||
.foot-site::before{content:"";position:absolute;left:0;right:0;top:0;height:1px;background:rgba(255,255,255,.85)}
|
||||
.foot-in{display:flex;flex-wrap:wrap;gap:14px 36px;align-items:center;padding:26px 24px 34px;font-size:13.5px;color:var(--ink-3)}
|
||||
.foot-in .brand b{font-size:16px;color:var(--ink)}
|
||||
.foot-in .brand i{width:24px;height:24px}
|
||||
.foot-in .sp{flex:1}
|
||||
|
||||
/* ---------- 屋子门头 ---------- */
|
||||
.room-head{position:relative;display:grid;grid-template-columns:auto 1fr auto;gap:28px;align-items:end;padding:44px 0 26px;margin-bottom:28px}
|
||||
.room-head::after{content:"";position:absolute;left:0;right:0;bottom:0;height:1px;background:var(--edge)}
|
||||
.zone{position:relative;justify-self:start;font-size:clamp(64px,8vw,108px);line-height:.9;font-weight:700;letter-spacing:-.02em;background:linear-gradient(135deg,var(--zc) 0%,var(--zc2,var(--zc)) 100%);-webkit-background-clip:text;background-clip:text;color:transparent;opacity:.78;filter:drop-shadow(-4px 8px 10px rgba(255,110,140,.18)) drop-shadow(4px 8px 10px rgba(70,140,255,.18))}
|
||||
.zone .dm-big{position:absolute;right:-12px;top:-8px}
|
||||
.room-head h1{margin:0;font-size:clamp(32px,4vw,46px);line-height:1.15}
|
||||
.room-head p{margin:8px 0 0;color:var(--ink-2);max-width:42em}
|
||||
.room-head .meta{text-align:right;font-size:13.5px;line-height:1.9;color:var(--ink-3)}
|
||||
.room-head .meta b{color:var(--ink);font-size:20px}
|
||||
|
||||
/* ---------- 画展 ---------- */
|
||||
.tools-bar{display:flex;flex-wrap:wrap;gap:12px 16px;align-items:center;margin-bottom:22px}
|
||||
.seg{display:inline-flex;flex-wrap:wrap;padding:4px;border-radius:999px}
|
||||
.seg button{position:relative;height:38px;padding:0 16px;border:0;background:transparent;border-radius:999px;font-size:14.5px;color:var(--ink-2);cursor:pointer;transition:background .16s var(--ease),color .16s var(--ease)}
|
||||
.seg button:hover{color:var(--ink)}
|
||||
.seg button[aria-pressed=true]{color:var(--ink);font-weight:700;background:linear-gradient(180deg,#fff,#F3F5FF);box-shadow:-3px 6px 12px -8px rgba(255,110,140,.45),3px 6px 12px -8px rgba(70,140,255,.45),inset 0 0 0 1px rgba(160,180,255,.35)}
|
||||
.seg button[aria-pressed=true]::after{content:"";position:absolute;left:14px;right:14px;bottom:5px;height:2px;border-radius:2px;background:var(--spec)}
|
||||
.seg button em{font-style:normal;opacity:.6;margin-left:4px;font-variant-numeric:tabular-nums}
|
||||
.gal{display:grid;grid-template-columns:150px minmax(0,1fr);gap:28px}
|
||||
.years{position:sticky;top:96px;align-self:start;display:flex;flex-direction:column;gap:6px}
|
||||
.years b{font-size:12px;letter-spacing:.14em;color:var(--ink-3);font-weight:700;margin-bottom:4px}
|
||||
.years a{display:flex;justify-content:space-between;align-items:center;height:40px;padding:0 14px;border-radius:12px;text-decoration:none;font-size:15px;color:var(--ink-2);border:1px solid transparent}
|
||||
.years a.on{background:linear-gradient(#fff,#fff) padding-box,var(--edge) border-box;color:var(--ink);font-weight:700;box-shadow:0 10px 20px -14px rgba(110,130,220,.5)}
|
||||
.years a em{font-style:normal;font-size:12px;color:var(--ink-3)}
|
||||
.wall{columns:3 260px;column-gap:16px}
|
||||
.art{break-inside:avoid;margin:0 0 16px;border-radius:var(--r);overflow:hidden;transition:transform .22s var(--ease),box-shadow .22s var(--ease)}
|
||||
.art:hover{--ty:-4px;box-shadow:var(--lift-hi)}
|
||||
.art button{display:block;width:100%;padding:0;border:0;background:none;cursor:zoom-in;text-align:left}
|
||||
.art img{width:100%;height:auto}
|
||||
.art .cap{padding:12px 14px 14px;display:flex;flex-direction:column;gap:8px}
|
||||
.art .cap b{font-size:15px}
|
||||
.art .cap span{display:flex;justify-content:space-between;align-items:center;font-size:12.5px;color:var(--ink-3)}
|
||||
.ph{position:relative;overflow:hidden;aspect-ratio:var(--ar,4/3);display:grid;place-items:center;align-content:center;gap:8px;background:linear-gradient(165deg,#F6F8FD,#FBFAFF);color:var(--ink-3);font-size:13px;isolation:isolate}
|
||||
.ph::after{content:"";position:absolute;z-index:-1;right:-30%;top:-40%;width:90%;height:160%;transform:rotate(24deg);background:linear-gradient(90deg,rgba(255,150,172,.16),rgba(255,210,135,.16),rgba(150,228,186,.16),rgba(140,200,255,.18),rgba(190,165,255,.18));filter:blur(14px)}
|
||||
.ph::before{content:"";position:absolute;inset:10px;border:1.5px dashed rgba(140,150,190,.35);border-radius:12px}
|
||||
.ph svg{color:var(--ink-3);opacity:.6}
|
||||
.type{display:inline-flex;align-items:center;height:24px;padding:0 9px;border-radius:999px;font-size:12px;font-weight:700;border:1px solid transparent;background:linear-gradient(#fff,#fff) padding-box,var(--edge) border-box;color:var(--ink-2)}
|
||||
.note{margin:6px 0 0;font-size:13.5px;color:var(--ink-3)}
|
||||
.lb{position:fixed;inset:0;z-index:100;display:none;place-items:center;padding:24px;background:rgba(250,251,255,.86);-webkit-backdrop-filter:blur(16px);backdrop-filter:blur(16px)}
|
||||
.lb.open{display:grid}
|
||||
.lb img{max-width:min(1100px,94vw);max-height:80vh;border-radius:18px;border:4px solid #fff;box-shadow:-10px 26px 50px -26px rgba(255,110,140,.5),10px 26px 50px -26px rgba(70,140,255,.5)}
|
||||
.lb .lb-cap{margin-top:14px;text-align:center;color:var(--ink-2);font-size:14px;font-weight:700}
|
||||
.lb button{position:absolute;top:18px;right:18px}
|
||||
|
||||
/* ---------- 工具与开源 ---------- */
|
||||
.row-title{display:flex;align-items:center;gap:10px;margin:8px 0 14px;font-size:15px;font-weight:700;color:var(--ink-2)}
|
||||
.row-title::after{content:"";flex:1;height:1px;background:var(--edge);opacity:.8}
|
||||
.shelf{display:grid;grid-template-columns:repeat(auto-fill,minmax(330px,1fr));gap:16px;margin-bottom:34px}
|
||||
.tool{display:flex;flex-direction:column;gap:12px;padding:24px;border-radius:var(--r-lg);overflow:hidden;transition:transform .22s var(--ease),box-shadow .22s var(--ease)}
|
||||
.tool:hover{--ty:-3px;box-shadow:var(--lift-hi)}
|
||||
.tool .en{font-size:12px;letter-spacing:.14em;color:var(--ink-3)}
|
||||
.tool h3{margin:0;font-size:23px}
|
||||
.tool p{margin:0;font-size:14.5px;line-height:1.75;color:var(--ink-2)}
|
||||
.tool .chips{display:flex;flex-wrap:wrap;gap:8px}
|
||||
.kv{display:flex;flex-wrap:wrap;gap:6px 22px;padding-top:12px;margin-top:auto;border-top:1px solid var(--line);font-size:13px;color:var(--ink-3)}
|
||||
.kv b{color:var(--ink)}
|
||||
.tool .acts{display:flex;gap:14px;flex-wrap:wrap;align-items:center}
|
||||
|
||||
/* ---------- 金钻宇宙(也是白光:星云只藏在亮部) ---------- */
|
||||
body.uni{background:
|
||||
radial-gradient(40% 34% at 10% 8%,rgba(185,160,255,.20) 0%,transparent 70%),
|
||||
radial-gradient(36% 30% at 92% 18%,rgba(140,205,255,.20) 0%,transparent 70%),
|
||||
radial-gradient(44% 36% at 60% 96%,rgba(255,175,205,.16) 0%,transparent 70%),
|
||||
#F8F9FF}
|
||||
.space-bg{position:fixed;inset:0;z-index:-1;width:100%;height:100%;pointer-events:none}
|
||||
.uni-intro{display:flex;gap:20px;align-items:center;margin-bottom:26px;padding:16px 20px;border-radius:var(--r)}
|
||||
.uni-intro p{margin:0;color:var(--ink-2);font-size:15.5px;line-height:1.85}
|
||||
.uni-tile{width:76px;height:76px;flex:none;border-radius:20px}
|
||||
.logo-ink{display:block;width:62%;height:62%;background:linear-gradient(140deg,#7C6CFF 0%,#4AA8FF 45%,#E46C9A 100%);-webkit-mask-position:center;mask-position:center;-webkit-mask-size:contain;mask-size:contain;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat}
|
||||
.rack{display:flex;flex-direction:column;gap:12px}
|
||||
.disk{border-radius:var(--r);overflow:hidden;transition:transform .2s var(--ease),box-shadow .2s var(--ease)}
|
||||
.disk:hover{box-shadow:var(--lift-hi)}
|
||||
.disk[open]::before{content:"";position:absolute;left:18px;right:18px;top:0;height:2px;border-radius:2px;background:var(--spec)}
|
||||
.disk summary{list-style:none;display:grid;grid-template-columns:64px minmax(0,1fr) auto;gap:18px;align-items:center;padding:16px 20px;cursor:pointer}
|
||||
.disk summary::-webkit-details-marker{display:none}
|
||||
.disk .emb{position:relative;display:grid;place-items:center;width:64px;height:64px;border-radius:18px;border:1px solid transparent;background:linear-gradient(160deg,#fff,#F3F5FF) padding-box,var(--edge-strong) border-box;box-shadow:-4px 8px 14px -10px rgba(255,110,140,.45),4px 8px 14px -10px rgba(70,140,255,.45)}
|
||||
.disk .dno{font-size:12px;letter-spacing:.16em;color:var(--ink-3)}
|
||||
.disk h3{margin:2px 0 0;font-size:20px}
|
||||
.disk .tagline{font-size:13.5px;color:var(--ink-2)}
|
||||
.disk .kind{display:inline-flex;align-items:center;height:28px;padding:0 12px;border-radius:999px;border:1px solid transparent;background:linear-gradient(#fff,#fff) padding-box,var(--edge) border-box;font-size:12.5px;color:var(--ink-2)}
|
||||
.disk .more{padding:0 20px 20px 102px;color:var(--ink-2);font-size:14.5px;line-height:1.9}
|
||||
.disk .tags{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}
|
||||
.disk .tags span{height:26px;display:inline-flex;align-items:center;padding:0 10px;border-radius:999px;background:#F5F7FD;border:1px solid var(--line);font-size:12px;color:var(--ink-2)}
|
||||
.slots{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:10px;margin-top:4px}
|
||||
.slot{height:58px;border-radius:14px;border:1.5px dashed rgba(140,150,200,.4);background:rgba(255,255,255,.6);display:flex;flex-direction:column;align-items:center;justify-content:center;font-size:12px;color:var(--ink-3)}
|
||||
.slot b{font-size:14px;color:var(--ink-2);font-variant-numeric:tabular-nums}
|
||||
|
||||
/* ---------- 关于 ---------- */
|
||||
.about-grid{display:grid;grid-template-columns:minmax(0,1.2fr) minmax(0,1fr);gap:20px;align-items:start}
|
||||
.letter{padding:36px 40px;border-radius:var(--r-lg);overflow:hidden}
|
||||
.letter .k{font-size:13px;letter-spacing:.14em;color:var(--ink-3);font-weight:700}
|
||||
.letter h2{margin:6px 0 16px;font-size:26px}
|
||||
.letter p{margin:0;font-size:16.5px;line-height:2.05;color:var(--ink-2)}
|
||||
.letter .sign{display:flex;justify-content:flex-end;align-items:center;gap:10px;margin-top:20px;font-weight:700}
|
||||
.letter .sign i{width:26px;height:26px}
|
||||
.credits{display:flex;flex-direction:column;gap:12px}
|
||||
.credit{padding:18px 22px;border-radius:var(--r);overflow:hidden}
|
||||
.credit::after{display:none}
|
||||
.credit .k{font-size:12px;letter-spacing:.12em;color:var(--ink-3)}
|
||||
.credit h3{margin:2px 0 6px;font-size:19px}
|
||||
.credit p{margin:0;font-size:14px;line-height:1.75;color:var(--ink-2)}
|
||||
.credit code{font-family:inherit;font-weight:700;background:#F5F7FD;border:1px solid var(--line);border-radius:6px;padding:1px 6px}
|
||||
|
||||
/* ---------- 服务台(自助模板渲染) ---------- */
|
||||
.back{display:inline-flex;align-items:center;gap:6px;font-size:14px;color:var(--ink-2);text-decoration:none;height:40px;padding:0 12px;border-radius:999px}
|
||||
.back:hover{background:#fff;color:var(--ink)}
|
||||
.svc-ic{width:84px;height:84px;border-radius:26px}
|
||||
.svc-ic i{width:48px;height:48px}
|
||||
.paths{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}
|
||||
.path{display:flex;flex-direction:column;gap:12px;padding:26px;border-radius:var(--r-lg);text-decoration:none;overflow:hidden;transition:transform .22s var(--ease),box-shadow .22s var(--ease)}
|
||||
.path:hover{--ty:-4px;box-shadow:var(--lift-hi)}
|
||||
.path .pi{width:50px;height:50px;border-radius:16px;display:grid;place-items:center;border:1px solid transparent;background:linear-gradient(160deg,#fff,#F3F5FF) padding-box,var(--edge-strong) border-box;color:var(--ink);box-shadow:-4px 8px 14px -10px rgba(255,110,140,.45),4px 8px 14px -10px rgba(70,140,255,.45)}
|
||||
.path h3{margin:0;font-size:22px}
|
||||
.path .flow{display:flex;flex-wrap:wrap;align-items:center;gap:6px;font-size:14px;color:var(--ink-2)}
|
||||
.path .flow span{display:inline-flex;align-items:center;height:28px;padding:0 10px;border-radius:10px;background:#F6F8FD;border:1px solid var(--line)}
|
||||
.path .flow i{font-style:normal;color:var(--ink-3)}
|
||||
.path .hint{margin-top:auto;display:flex;justify-content:space-between;align-items:center;font-size:14px;font-weight:700}
|
||||
.path .hint em{font-style:normal;color:#12804C}
|
||||
.path.code .hint em{color:#1D63C2}
|
||||
.pickup{display:flex;flex-wrap:wrap;align-items:center;gap:10px 16px;margin-top:16px;padding:16px 20px;border-radius:var(--r);border:1.5px dashed rgba(140,150,200,.4);background:rgba(255,255,255,.6);font-size:14.5px;color:var(--ink-2)}
|
||||
.pickup .sp{flex:1}
|
||||
.tpl-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(148px,1fr));gap:12px}
|
||||
.tpl{display:flex;flex-direction:column;gap:6px;padding:12px;border-radius:var(--r-sm)}
|
||||
.tpl .sw{height:70px;border-radius:10px;background:linear-gradient(180deg,rgba(255,255,255,.4),rgba(255,255,255,0)),var(--c);position:relative;overflow:hidden;opacity:.85}
|
||||
.tpl .sw::after{content:"";position:absolute;left:0;right:0;bottom:0;height:32%;background:rgba(0,0,0,.1)}
|
||||
.tpl b{font-size:15px}
|
||||
.tpl span{font-size:12.5px;color:var(--ink-3)}
|
||||
.res{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px}
|
||||
.pass{display:grid;grid-template-columns:minmax(0,1fr) 240px;border-radius:var(--r-lg)}
|
||||
.pass .main{padding:26px 28px;display:flex;flex-direction:column;gap:14px;min-width:0}
|
||||
.pass .row{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex-wrap:wrap}
|
||||
.pass .lbl{font-size:12px;letter-spacing:.12em;color:var(--ink-3)}
|
||||
.pass .code{font-size:24px;font-weight:700;letter-spacing:.06em;font-variant-numeric:tabular-nums}
|
||||
.state{display:inline-flex;align-items:center;gap:8px;height:32px;padding:0 14px;border-radius:999px;background:#EDF4FF;color:#1D58C2;font-size:13.5px;font-weight:700}
|
||||
.state::before{display:none}
|
||||
@keyframes pulse{50%{opacity:.3}}
|
||||
.prog{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px}
|
||||
.prog i{height:8px;border-radius:4px;background:#EEF1F8}
|
||||
.prog i.on{background:var(--spec)}
|
||||
.prog i.run{background:repeating-linear-gradient(90deg,rgba(255,255,255,.95) 0 8px,rgba(255,255,255,.35) 8px 16px),var(--spec);background-size:32px 100%,100% 100%;animation:run 1s linear infinite}
|
||||
@keyframes run{to{background-position:32px 0,0 0}}
|
||||
.pass .stub{position:relative;padding:26px 24px;border-left:2px dashed rgba(140,150,200,.35);background:linear-gradient(180deg,rgba(248,250,255,.9),rgba(252,249,255,.9));border-radius:0 var(--r-lg) var(--r-lg) 0;display:flex;flex-direction:column;gap:12px;align-items:flex-start}
|
||||
.pass .stub::before,.pass .stub::after{content:"";position:absolute;left:-13px;width:24px;height:24px;border-radius:50%;background:var(--bg);box-shadow:inset 0 2px 4px rgba(30,36,64,.08)}
|
||||
.pass .stub::before{top:-13px}.pass .stub::after{bottom:-13px}
|
||||
.barcode{align-self:stretch;height:54px;border-radius:6px;background:repeating-linear-gradient(90deg,#2B3256 0 2px,transparent 2px 5px,#2B3256 5px 6px,transparent 6px 9px,#2B3256 9px 12px,transparent 12px 14px,#2B3256 14px 15px,transparent 15px 19px);opacity:.75}
|
||||
.previews{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}
|
||||
.previews figure{margin:0;position:relative;border-radius:14px;overflow:hidden;border:3px solid #fff;aspect-ratio:1;box-shadow:-4px 10px 18px -12px rgba(255,110,140,.4),4px 10px 18px -12px rgba(70,140,255,.4)}
|
||||
.previews img{width:100%;height:100%;object-fit:cover}
|
||||
.previews .wait{display:grid;place-items:center;align-content:center;gap:6px;background:#F6F8FD;font-size:12.5px;color:var(--ink-3);border:2px dashed rgba(140,150,200,.35);box-shadow:none}
|
||||
.previews figcaption{position:absolute;left:8px;bottom:8px;height:24px;padding:0 9px;border-radius:999px;display:inline-flex;align-items:center;background:rgba(255,255,255,.92);color:var(--ink);font-size:12px;font-weight:700}
|
||||
.after{margin-top:14px;padding:14px 18px;border-radius:var(--r-sm);background:linear-gradient(90deg,rgba(255,244,214,.75),rgba(255,236,242,.65));border:1px solid rgba(255,214,140,.7);font-size:14px;line-height:1.75;color:#5A4410}
|
||||
|
||||
/* ---------- 响应式 ---------- */
|
||||
@media (max-width:980px){
|
||||
.dir{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
.gal{grid-template-columns:1fr}
|
||||
.years{position:static;flex-direction:row;flex-wrap:wrap}
|
||||
.years b{width:100%}
|
||||
.about-grid{grid-template-columns:1fr}
|
||||
}
|
||||
@media (max-width:860px){
|
||||
.sky{grid-template-columns:1fr;min-height:0}
|
||||
.hero-copy{padding:36px 24px 8px}
|
||||
.emblem{width:210px;margin:10px auto 70px}
|
||||
.fan{left:50%;top:auto;bottom:-430px}
|
||||
.telemetry{left:24px;right:24px}
|
||||
.desk{grid-template-columns:auto 1fr}
|
||||
.desk .acts{grid-column:1/-1;justify-content:flex-start}
|
||||
.slots{grid-template-columns:repeat(3,minmax(0,1fr))}
|
||||
}
|
||||
@media (max-width:760px){
|
||||
.top-in{flex-wrap:wrap;gap:6px 12px;padding-top:10px}
|
||||
.top .desk-btn{margin-left:auto}
|
||||
.btn-pill{height:40px;font-size:14px;padding-right:14px}
|
||||
.btn-pill .ic{width:28px;height:28px;background-size:16px}
|
||||
.nav{order:3;flex-basis:100%;margin:0 -24px;padding:0 20px 8px;-webkit-mask-image:linear-gradient(90deg,#000 88%,transparent);mask-image:linear-gradient(90deg,#000 88%,transparent)}
|
||||
.room-head{grid-template-columns:1fr;gap:10px;padding-top:30px}
|
||||
.room-head .meta{text-align:left}
|
||||
.zone{font-size:64px}
|
||||
.paths{grid-template-columns:1fr}
|
||||
.pass{grid-template-columns:1fr}
|
||||
.pass .stub{border-left:0;border-top:2px dashed rgba(140,150,200,.35);border-radius:0 0 var(--r-lg) var(--r-lg)}
|
||||
.pass .stub::before{top:-13px;left:-13px}
|
||||
.pass .stub::after{top:-13px;bottom:auto;left:auto;right:-13px}
|
||||
}
|
||||
@media (max-width:620px){
|
||||
.wrap{padding:0 16px}
|
||||
.ribbon > span:last-child{display:none}
|
||||
.svc-ic{width:64px;height:64px;border-radius:20px}
|
||||
.svc-ic i{width:36px;height:36px}
|
||||
.nav{margin:0 -16px;padding:0 12px 8px}
|
||||
.dir{grid-template-columns:1fr;grid-auto-rows:auto}
|
||||
.room.big{grid-column:auto;grid-row:auto}
|
||||
.room.big .peek{flex:none;min-height:0}
|
||||
.room.big .peek img{aspect-ratio:4/3;height:auto}
|
||||
.sec{padding-top:44px}
|
||||
.sec-h h2{font-size:25px}
|
||||
.board-head{display:none}
|
||||
.board-row{grid-template-columns:minmax(0,1fr) auto;gap:4px 12px;padding:12px 18px}
|
||||
.board-row .kind{grid-column:1;grid-row:2;font-size:13px}
|
||||
.board-row .gate{display:none}
|
||||
.board-row .act{grid-column:2;grid-row:1/3}
|
||||
.board-title,.board-group{padding-left:18px;padding-right:18px}
|
||||
.desk{padding:22px 20px}
|
||||
.letter{padding:28px 22px}
|
||||
.disk summary{grid-template-columns:52px minmax(0,1fr);gap:14px}
|
||||
.disk .emb{width:52px;height:52px}
|
||||
.disk .kind{display:none}
|
||||
.disk .more{padding:0 18px 18px}
|
||||
.uni-tile{width:60px;height:60px;border-radius:16px}
|
||||
.foot-in{padding:22px 16px 30px}
|
||||
}
|
||||
/* ===== 整页动态背景:WebGL 流动渐变(低分辨率渲染、30fps、看不见就暂停);不支持时退回彩光色团 ===== */
|
||||
.bg-gl{position:fixed;inset:0;width:100%;height:100%;z-index:-3;pointer-events:none;display:block}
|
||||
.has-gl .orbs{display:none}
|
||||
|
||||
/* ===== 手机端:底部悬浮导航 + 更多面板(桌面隐藏) ===== */
|
||||
.tabbar,.sheet,.m-only,.order-cta{display:none}
|
||||
@media (max-width:760px){
|
||||
.d-only{display:none !important}
|
||||
.m-only{display:block}
|
||||
/* 顶栏只留 logo,导航交给底部 */
|
||||
.top-in{min-height:56px;flex-wrap:nowrap;padding-top:0}
|
||||
.top .nav,.top .desk-btn{display:none}
|
||||
body{padding-bottom:calc(92px + env(safe-area-inset-bottom))}
|
||||
body.flow{padding-bottom:calc(96px + env(safe-area-inset-bottom))}
|
||||
.tabbar{position:fixed;left:12px;right:12px;bottom:calc(10px + env(safe-area-inset-bottom));z-index:60;display:grid;grid-template-columns:repeat(5,minmax(0,1fr));align-items:center;height:64px;padding:0 4px;border-radius:24px;
|
||||
background:rgba(255,255,255,.78);-webkit-backdrop-filter:blur(10px) saturate(1.4);backdrop-filter:blur(10px) saturate(1.4);border:1px solid rgba(255,255,255,.95);
|
||||
box-shadow:0 16px 34px -18px rgba(100,110,190,.55),0 2px 8px rgba(30,36,64,.06)}
|
||||
.tabbar a,.tabbar button{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:3px;height:64px;padding:0;border:0;background:none;font-family:inherit;font-size:11px;color:var(--ink-3);text-decoration:none;cursor:pointer;-webkit-tap-highlight-color:transparent;transition:color .2s var(--ease),transform .15s var(--ease)}
|
||||
.tabbar a:active,.tabbar button:active{transform:scale(.92)}
|
||||
.tabbar svg{width:23px;height:23px}
|
||||
.tabbar [aria-current=page]{color:var(--ink);font-weight:700}
|
||||
.tabbar .mid{position:relative;top:-14px;height:auto;gap:4px;color:var(--ink);font-weight:700}
|
||||
.tabbar .mid i{width:54px;height:54px;border-radius:50%;background:#fff url('gem.webp') center/28px no-repeat;image-rendering:pixelated;
|
||||
box-shadow:0 0 0 4px rgba(255,255,255,.85),0 12px 24px -10px rgba(120,110,230,.65),0 8px 18px -12px rgba(255,140,170,.6)}
|
||||
|
||||
/* 首页首屏:钻石在上,文字居中(背景不动) */
|
||||
.sky{display:flex;flex-direction:column;align-items:center;min-height:0}
|
||||
.emblem{order:-1;width:150px;margin:30px auto 0}
|
||||
.hero-copy{padding:18px 22px 28px;align-items:center;text-align:center;gap:14px}
|
||||
.hero h1{font-size:44px}
|
||||
.hero p{font-size:15px;line-height:1.75}
|
||||
.hero .cta{width:100%;gap:10px;padding-top:4px}
|
||||
.hero .cta .btn{flex:1}
|
||||
.fan{left:64%;top:104px;width:760px;height:760px}
|
||||
.tag-l{height:28px;font-size:12px}
|
||||
|
||||
/* 金刚区:5 个入口一排 */
|
||||
.kk{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:4px;margin-top:18px;padding:14px 6px 10px;border-radius:22px}
|
||||
.kk a{display:flex;flex-direction:column;align-items:center;gap:7px;text-decoration:none;font-size:12.5px;color:var(--ink-2);-webkit-tap-highlight-color:transparent}
|
||||
.kk a:active i{transform:scale(.92)}
|
||||
.kk i{width:48px;height:48px;border-radius:16px;display:grid;place-items:center;color:var(--ink);transition:transform .15s var(--ease);background:#EEF1FA;
|
||||
background:linear-gradient(140deg,color-mix(in srgb,var(--zc) 26%,#fff) 0%,color-mix(in srgb,var(--zc2) 22%,#fff) 100%);
|
||||
box-shadow:inset 0 1px 0 #fff,0 8px 16px -10px color-mix(in srgb,var(--zc) 70%,transparent)}
|
||||
.kk svg{width:23px;height:23px}
|
||||
|
||||
/* 首页:双列最新作品 */
|
||||
.m-sec{padding-top:30px}
|
||||
.m-sec .sec-h{margin-bottom:12px}
|
||||
.m-sec .sec-h h2{font-size:21px}
|
||||
.duo{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}
|
||||
.duo a{display:block;border-radius:16px;overflow:hidden;text-decoration:none}
|
||||
.duo img{width:100%;aspect-ratio:3/4;object-fit:cover}
|
||||
.duo .cap{display:block;padding:8px 10px 10px;font-size:13px;font-weight:700}
|
||||
.duo .cap small{display:block;font-size:11.5px;font-weight:400;color:var(--ink-3);margin-top:2px}
|
||||
.desk{grid-template-columns:auto 1fr;gap:14px;padding:18px}
|
||||
.desk-ic{width:52px;height:52px;border-radius:16px}
|
||||
.desk-ic i{width:30px;height:30px}
|
||||
.desk h3{font-size:18px}
|
||||
.desk p{font-size:13.5px}
|
||||
.desk .meta{margin-top:6px;font-size:12.5px}
|
||||
.desk .acts{grid-column:1/-1;display:grid;grid-template-columns:1fr 1fr;gap:10px}
|
||||
.desk .acts .btn{width:100%}
|
||||
|
||||
/* 各屋门头:编号和标题并排,紧凑 */
|
||||
.room-head{grid-template-columns:auto 1fr;gap:4px 14px;align-items:center;padding:22px 0 18px;margin-bottom:18px}
|
||||
.room-head .zone{font-size:46px !important}
|
||||
.room-head h1{font-size:28px}
|
||||
.room-head p{grid-column:1/-1;margin-top:6px;font-size:14.5px}
|
||||
.room-head .meta{display:none}
|
||||
.svc-ic{width:56px;height:56px;border-radius:18px}
|
||||
.svc-ic i{width:32px;height:32px}
|
||||
|
||||
/* 筛选条:横向滑动 + 吸顶 */
|
||||
.tools-bar{position:sticky;top:56px;z-index:20;flex-wrap:nowrap;overflow-x:auto;scrollbar-width:none;margin:0 -16px 14px;padding:8px 16px;background:linear-gradient(rgba(250,251,254,.92),rgba(250,251,254,.78))}
|
||||
.tools-bar::-webkit-scrollbar{display:none}
|
||||
.tools-bar > *{flex:none}
|
||||
.seg{flex-wrap:nowrap}
|
||||
.seg button{height:34px;padding:0 13px;font-size:14px}
|
||||
|
||||
/* 画展:小红书式双列瀑布流 */
|
||||
.years{display:none}
|
||||
.wall{columns:2;column-gap:10px}
|
||||
.art{margin-bottom:10px;border-radius:14px}
|
||||
.art .cap{padding:8px 10px 10px;gap:5px}
|
||||
.art .cap b{font-size:13px}
|
||||
.art .cap span{font-size:11px}
|
||||
.type{height:20px;padding:0 7px;font-size:11px}
|
||||
.ph{font-size:12px}
|
||||
.ph svg{width:24px;height:24px}
|
||||
|
||||
/* 其它 */
|
||||
.sec{padding-top:34px}
|
||||
.sec-h h2{font-size:21px}
|
||||
.row-title{margin:4px 0 10px}
|
||||
.shelf{gap:12px;margin-bottom:22px}
|
||||
.tool{padding:18px}
|
||||
.tool h3{font-size:20px}
|
||||
.foot-site{margin-top:44px}
|
||||
.foot-in{flex-direction:column;align-items:flex-start;gap:6px;padding:20px 16px 24px;font-size:12.5px}
|
||||
.foot-in .sp{display:none}
|
||||
|
||||
/* 下单页:不显示底部导航,底部固定两个大按钮 */
|
||||
.order-cta{position:fixed;left:12px;right:12px;bottom:calc(10px + env(safe-area-inset-bottom));z-index:60;display:grid;grid-template-columns:1.3fr 1fr;gap:10px;padding:8px;border-radius:24px;
|
||||
background:rgba(255,255,255,.82);-webkit-backdrop-filter:blur(10px) saturate(1.4);backdrop-filter:blur(10px) saturate(1.4);border:1px solid rgba(255,255,255,.95);box-shadow:0 16px 34px -18px rgba(100,110,190,.55)}
|
||||
.order-cta .btn{height:50px;width:100%;font-size:15.5px}
|
||||
.tpl-grid{grid-auto-flow:column;grid-template-columns:none;grid-auto-columns:40%;overflow-x:auto;scroll-snap-type:x mandatory;scrollbar-width:none;margin:0 -16px;padding:4px 16px 12px;scroll-padding:0 16px}
|
||||
.tpl-grid::-webkit-scrollbar{display:none}
|
||||
.tpl{scroll-snap-align:start}
|
||||
}
|
||||
/* ===== MC 风格层(参考 Minecraft Ore UI):方块按钮、像素标题、物品栏格子、矿石配色 ===== */
|
||||
@font-face{font-family:'Fusion Pixel';src:url('../fonts/fusion-pixel-12.woff2') format('woff2');font-display:swap}
|
||||
:root{
|
||||
--r-xl:14px; --r-lg:10px; --r:8px; --r-sm:6px;
|
||||
--mc-green:#3C8527; --mc-green-hi:#5BAA3C; --mc-green-lo:#1D4D13;
|
||||
--stone:#F3F4F6; --stone-lo:#B4B7BE; --stone-edge:#9EA2AA;
|
||||
--pixel:'Fusion Pixel',var(--font);
|
||||
--sparks:#4FD8D2 #5CC97B #F2C14D #6F9BFF #B48CF2 #9FE6F0;
|
||||
}
|
||||
/* 像素标题:12px 字形按整数倍放大,边缘才清楚 */
|
||||
.hero h1,.room-head h1,.sec-h h2,.zone,.room h3,.room .no,.desk h3,.tool h3,.disk h3,.disk .dno,.path h3,.letter h2,.credit h3,.brand b,.tabbar span,.kk a{
|
||||
font-family:var(--pixel);font-weight:400;letter-spacing:0;-webkit-font-smoothing:none}
|
||||
.hero h1{font-size:72px;line-height:1.1}
|
||||
.room-head h1{font-size:36px;line-height:1.2}
|
||||
.sec-h h2{font-size:24px}
|
||||
.zone{font-size:96px;line-height:1;filter:none}
|
||||
.room h3,.desk h3,.tool h3,.disk h3,.path h3,.letter h2,.credit h3{font-size:24px;line-height:1.25}
|
||||
.room .no,.disk .dno{font-size:12px;letter-spacing:.06em}
|
||||
.brand b{font-size:24px}
|
||||
|
||||
/* 面板:方一点,白色玻璃框;悬停像物品栏格子一样变绿 */
|
||||
.crystal{border:2px solid rgba(255,255,255,.95);box-shadow:inset 0 0 0 1px rgba(30,36,64,.05),0 18px 36px -26px rgba(60,80,120,.38)}
|
||||
.room:hover,.tool:hover,.path:hover,.art:hover,.disk:hover,.tpl:hover{border-color:var(--mc-green-hi);box-shadow:0 0 0 2px rgba(91,170,60,.25),0 22px 40px -26px rgba(60,80,120,.42)}
|
||||
.room::before{opacity:.12}
|
||||
|
||||
/* 按钮:Ore UI 方块按钮(主按钮绿、次按钮白石;底边有厚度,按下会沉) */
|
||||
.btn{border-radius:4px;border:2px solid;height:46px;padding:0 20px 3px;font-weight:700;transition:transform .08s linear,box-shadow .08s linear,background .15s var(--ease),filter .15s var(--ease)}
|
||||
.btn:hover{transform:none}
|
||||
.btn:active{transform:translateY(2px)}
|
||||
.btn-prism{background:var(--mc-green);color:#fff;border-color:var(--mc-green-lo);
|
||||
box-shadow:inset 0 2px 0 var(--mc-green-hi),inset 0 -4px 0 var(--mc-green-lo),0 8px 16px -10px rgba(29,77,19,.55)}
|
||||
.btn-prism:hover{background:#469A2E;transform:none;box-shadow:inset 0 2px 0 #74C455,inset 0 -4px 0 var(--mc-green-lo),0 10px 18px -10px rgba(29,77,19,.6)}
|
||||
.btn-prism:active{box-shadow:inset 0 2px 0 var(--mc-green-hi),inset 0 -2px 0 var(--mc-green-lo)}
|
||||
.btn-crystal{background:var(--stone);color:var(--ink);border-color:var(--stone-edge);font-weight:700;
|
||||
box-shadow:inset 0 2px 0 #fff,inset 0 -4px 0 var(--stone-lo),0 8px 16px -12px rgba(60,70,100,.45)}
|
||||
.btn-crystal:hover{background:#fff;transform:none}
|
||||
.btn-crystal:active{box-shadow:inset 0 2px 0 #fff,inset 0 -2px 0 var(--stone-lo)}
|
||||
.btn-sm{height:40px;padding:0 14px 3px}
|
||||
.btn[disabled]{opacity:.5}
|
||||
.btn-pill{border-radius:4px;height:44px;padding:0 14px 3px 6px;color:#fff;background:var(--mc-green);border:2px solid var(--mc-green-lo);
|
||||
box-shadow:inset 0 2px 0 var(--mc-green-hi),inset 0 -4px 0 var(--mc-green-lo),0 8px 16px -10px rgba(29,77,19,.55)}
|
||||
.btn-pill:hover{background:#469A2E;transform:none;box-shadow:inset 0 2px 0 #74C455,inset 0 -4px 0 var(--mc-green-lo),0 10px 18px -10px rgba(29,77,19,.6)}
|
||||
.btn-pill:active{transform:translateY(2px)}
|
||||
.btn-pill .ic{width:28px;height:28px;border-radius:3px;background-color:#fff;background-size:18px;box-shadow:inset 0 -2px 0 #C9CDD4}
|
||||
.btn-pill svg{opacity:.9}
|
||||
.board-row .act{border-radius:4px;height:34px;padding:0 12px 2px;background:var(--stone);border:2px solid var(--stone-edge);box-shadow:inset 0 2px 0 #fff,inset 0 -3px 0 var(--stone-lo)}
|
||||
.board-row:hover .act{background:var(--mc-green);color:#fff;border-color:var(--mc-green-lo);box-shadow:inset 0 2px 0 var(--mc-green-hi),inset 0 -3px 0 var(--mc-green-lo)}
|
||||
|
||||
/* 小部件:方角 */
|
||||
.chip,.type,.tag-l,.disk .kind,.board-row .gate{border-radius:4px}
|
||||
.nav a{border-radius:4px}
|
||||
.nav a[aria-current=page]{border:0;background:#fff;box-shadow:inset 0 -3px 0 var(--mc-green),0 6px 14px -10px rgba(60,70,100,.5)}
|
||||
.nav a[aria-current=page]::after{display:none}
|
||||
.seg{border-radius:8px}
|
||||
.seg button{border-radius:4px}
|
||||
.seg button[aria-pressed=true]{color:#fff;background:var(--mc-green);box-shadow:inset 0 2px 0 var(--mc-green-hi),inset 0 -3px 0 var(--mc-green-lo)}
|
||||
.seg button[aria-pressed=true]::after{display:none}
|
||||
.years a{border-radius:6px}
|
||||
.years a.on{box-shadow:inset 0 -3px 0 var(--mc-green),0 10px 20px -14px rgba(60,70,100,.5)}
|
||||
.prog i.on{background:var(--mc-green)}
|
||||
.prog i.run{background:repeating-linear-gradient(90deg,#8BCB6E 0 8px,#C9E8B9 8px 16px);background-size:32px 100%}
|
||||
.desk-ic,.svc-ic,.uni-tile,.disk .emb,.path .pi{border-radius:8px}
|
||||
.peek img,.previews figure{border-radius:6px}
|
||||
.state{border-radius:4px}
|
||||
|
||||
/* 背景:像素化的流动色块(矿石色),粒子是方形的 */
|
||||
.orbs .o1{background:radial-gradient(circle,rgba(120,220,150,.6) 0%,rgba(120,220,150,0) 66%)}
|
||||
.orbs .o2{background:radial-gradient(circle,rgba(110,220,225,.6) 0%,rgba(110,220,225,0) 66%)}
|
||||
.orbs .o3{background:radial-gradient(circle,rgba(245,205,95,.55) 0%,rgba(245,205,95,0) 66%)}
|
||||
.orbs .o4{background:radial-gradient(circle,rgba(120,160,255,.55) 0%,rgba(120,160,255,0) 66%)}
|
||||
.orbs .o5{background:radial-gradient(circle,rgba(185,150,240,.5) 0%,rgba(185,150,240,0) 66%)}
|
||||
|
||||
@media (max-width:760px){
|
||||
.hero h1{font-size:48px}
|
||||
.room-head h1{font-size:24px}
|
||||
.zone{font-size:48px !important}
|
||||
.room h3,.desk h3,.tool h3,.disk h3,.path h3,.letter h2,.credit h3{font-size:24px}
|
||||
.sec-h h2,.m-sec .sec-h h2{font-size:24px}
|
||||
/* 底部导航做成 MC 快捷栏:一格一个,当前格子高亮 */
|
||||
body{padding-bottom:calc(100px + env(safe-area-inset-bottom))}
|
||||
.tabbar{border-radius:8px;height:72px;padding:6px;gap:6px;border:2px solid rgba(255,255,255,.95);background:rgba(255,255,255,.86)}
|
||||
.tabbar a,.tabbar button{height:56px;border-radius:4px;background:rgba(30,36,64,.04);box-shadow:inset 0 0 0 2px rgba(30,36,64,.08)}
|
||||
.tabbar [aria-current=page]{background:#fff;color:var(--ink);box-shadow:inset 0 0 0 3px var(--mc-green)}
|
||||
.tabbar span{font-size:12px}
|
||||
.tabbar .mid{top:0;height:56px;gap:2px;color:#fff;background:var(--mc-green);box-shadow:inset 0 2px 0 var(--mc-green-hi),inset 0 -4px 0 var(--mc-green-lo)}
|
||||
.tabbar .mid i{width:28px;height:28px;border-radius:3px;background-color:#fff;background-size:20px;box-shadow:inset 0 -2px 0 #C9CDD4}
|
||||
.kk{border-radius:10px}
|
||||
.kk i{border-radius:6px;box-shadow:inset 0 2px 0 rgba(255,255,255,.9),inset 0 -3px 0 rgba(30,36,64,.14)}
|
||||
.kk a{font-size:12px}
|
||||
.order-cta{border-radius:8px}
|
||||
.duo a{border-radius:8px}
|
||||
}
|
||||
/* 首屏:桌面保留「观景窗」外框,内圆角跟外框对齐;手机只留一层,不做框里套框 */
|
||||
.sky{border-radius:8px}
|
||||
.hero .window{padding:4px;border-radius:12px}
|
||||
/* 桌面:首屏和首页各段跟顶栏同宽(之前 padding 简写把 .wrap 的左右留白清掉了) */
|
||||
@media (min-width:761px){.hero,.sec.wrap{padding-left:24px;padding-right:24px}}
|
||||
@media (max-width:760px){
|
||||
.hero{padding-top:14px}
|
||||
.hero .window{padding:0;border:0;background:none;box-shadow:none}
|
||||
.hero .sky{border-radius:var(--r-lg);border:2px solid rgba(255,255,255,.95);box-shadow:inset 0 0 0 1px rgba(30,36,64,.05),0 18px 36px -26px rgba(60,80,120,.38)}
|
||||
}
|
||||
/* ===== 下单页(手机):两条路改成图标 + 标题并排 ===== */
|
||||
@media (max-width:760px){
|
||||
.paths{gap:12px}
|
||||
.path{display:grid;grid-template-columns:auto minmax(0,1fr);gap:4px 12px;align-items:center;padding:16px}
|
||||
.path .pi{grid-row:1/3;width:44px;height:44px}
|
||||
.path h3{font-size:24px}
|
||||
.path p{grid-column:2;font-size:13.5px !important;line-height:1.6 !important}
|
||||
.path .hint{display:none}
|
||||
}
|
||||
.btn-pill[aria-current=page]{box-shadow:inset 0 2px 0 var(--mc-green-hi),inset 0 -4px 0 var(--mc-green-lo),0 0 0 3px rgba(91,170,60,.28)}
|
||||
.svc-head .svc-line{margin-top:4px;font-size:13.5px;color:var(--ink-3)}
|
||||
@media (max-width:760px){.svc-head .svc-line{grid-column:auto;margin-top:2px;font-size:12.5px}}
|
||||
/* ===== 手机「更多」:从底栏上方弹出一排格子,底栏一直在;再点一次「更多」/点空白/返回键都能收起 ===== */
|
||||
@media (max-width:760px){
|
||||
.sheet{position:fixed;inset:0;z-index:55;display:block;pointer-events:none;touch-action:none}
|
||||
.sheet::before{content:"";position:absolute;inset:0;background:rgba(30,36,64,.16);opacity:0;transition:opacity .22s var(--ease)}
|
||||
.sheet .panel{position:absolute;left:12px;right:12px;bottom:calc(90px + env(safe-area-inset-bottom));padding:6px;border-radius:8px;border:2px solid #fff;background:#fff;
|
||||
box-shadow:0 16px 34px -18px rgba(100,110,190,.55),0 2px 8px rgba(30,36,64,.06);opacity:0;transform:translateY(12px);transition:opacity .2s var(--ease),transform .22s var(--ease)}
|
||||
.sheet[hidden]{display:none !important}
|
||||
.sheet.open{pointer-events:auto}
|
||||
.sheet.open::before{opacity:1}
|
||||
.sheet.open .panel{opacity:1;transform:none}
|
||||
.more-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px}
|
||||
.more-grid a{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;height:84px;border-radius:4px;text-decoration:none;-webkit-tap-highlight-color:transparent;
|
||||
font-size:13.5px;font-weight:700;color:var(--ink);transition:transform .12s var(--ease);
|
||||
background:#F1F4FA;background:linear-gradient(160deg,color-mix(in srgb,var(--zc) 20%,#fff),color-mix(in srgb,var(--zc2) 10%,#fff));
|
||||
box-shadow:inset 0 0 0 2px color-mix(in srgb,var(--zc) 28%,transparent)}
|
||||
.more-grid a:active{transform:scale(.95)}
|
||||
.more-grid a[aria-current=page]{box-shadow:inset 0 0 0 3px var(--zc)}
|
||||
.more-grid i{display:grid;place-items:center;color:var(--ink)}
|
||||
.more-grid svg{width:24px;height:24px}
|
||||
.more-qq{margin:0;padding:10px 8px 4px;font-size:13px;color:var(--ink-3)}
|
||||
.tabbar button i{display:block;line-height:0}
|
||||
.tabbar .ic-b,.tabbar .lb-b,.tabbar [aria-expanded=true] .ic-a,.tabbar [aria-expanded=true] .lb-a{display:none}
|
||||
.tabbar [aria-expanded=true] .ic-b{display:block}
|
||||
.tabbar [aria-expanded=true] .lb-b{display:inline}
|
||||
.tabbar [aria-expanded=true]{background:#fff;color:var(--ink);font-weight:700;box-shadow:inset 0 0 0 3px var(--mc-green)}
|
||||
}
|
||||
@media (prefers-reduced-motion:reduce){
|
||||
*,*::before,*::after{animation-duration:1ms!important;animation-iteration-count:1!important;transition-duration:1ms!important;scroll-behavior:auto!important}
|
||||
.flip{opacity:1}
|
||||
.orbs i{animation:none}
|
||||
.orbs,.hero-copy,.emblem{translate:none}
|
||||
.fan{animation:none}
|
||||
.js .rv{opacity:1;translate:none}
|
||||
.fx{transform:none}
|
||||
.sheet .panel,.sheet::before{transition:none}
|
||||
}
|
||||
|
||||
/* ---------- 内容后台入口:顶栏最右边一个不带字的铅笔图标 —— 淡、虚,不抢眼;hover 才稍微亮一点(店主 2026-10-05) ---------- */
|
||||
.cms-ent{flex:none;display:inline-grid;place-items:center;width:36px;height:36px;border-radius:999px;color:var(--ink);text-decoration:none;
|
||||
opacity:.32;background:transparent;border:0;transition:opacity .18s,background .18s}
|
||||
.cms-ent:hover,.cms-ent:focus-visible{opacity:.72;background:rgba(255,255,255,.55)}
|
||||
.cms-ent:focus-visible{outline:2px solid #6FA8F0;outline-offset:3px}
|
||||
.desk-btn+.cms-ent{margin-left:-8px}
|
||||
@media (max-width:760px){
|
||||
.top .cms-ent{margin-left:auto}
|
||||
}
|
||||
|
||||
/* 「都有些什么」卡片编号:跟各单页大号数字同色(--zc → --zc2 渐变) */
|
||||
.room .no{background:linear-gradient(135deg,var(--zc,var(--ink-3)) 0%,var(--zc2,var(--zc,var(--ink-3))) 100%);-webkit-background-clip:text;background-clip:text;color:transparent;justify-self:start;align-self:flex-start;font-size:18px;letter-spacing:.04em}
|
||||
|
||||
/* PC 窄窗(单列堆叠时):钻石在上、标题文字居中,跟钻石对齐 */
|
||||
@media (min-width:761px) and (max-width:860px){
|
||||
.sky{display:flex;flex-direction:column;align-items:center}
|
||||
.emblem{order:-1;width:190px;margin:36px auto 0}
|
||||
.hero-copy{padding:20px 40px 52px;align-items:center;text-align:center}
|
||||
.hero .cta{justify-content:center}
|
||||
.fan{left:64%;top:120px;bottom:auto}
|
||||
}
|
||||
|
||||
/* =====================================================================================
|
||||
以下是正式站在预览站样式之上补的部分(2026-10-06):预览里只有样子、没有真功能的地方
|
||||
===================================================================================== */
|
||||
|
||||
/* ---------- 公告 / 预览草稿提示条(复用预览站的 .ribbon) ---------- */
|
||||
.ribbon.notice,.ribbon.preview-bar{position:relative;z-index:51}
|
||||
.ribbon.preview-bar{background:linear-gradient(90deg,rgba(255,244,214,.9),rgba(255,236,242,.85));color:#5A4410}
|
||||
.ribbon.preview-bar a{color:inherit;font-weight:700}
|
||||
@media (max-width:620px){.ribbon.notice > span,.ribbon.preview-bar > span{display:inline}}
|
||||
/* 页脚:QQ 群、备案号能点 */
|
||||
.foot-in a:not(.brand){color:inherit;text-decoration:none}
|
||||
.foot-in a:not(.brand):hover{color:var(--ink);text-decoration:underline;text-underline-offset:3px}
|
||||
/* 首页服务台:渲染机离线时颜色淡一点 */
|
||||
.status.off{color:#A0662A}
|
||||
|
||||
/* ---------- 加载动画:像素钻石垒成形 → 白光扫过 → 店名逐字弹出 → 幕布收起 ---------- */
|
||||
.jz-boot{position:fixed;inset:0;z-index:200;display:grid;place-items:center;cursor:pointer;
|
||||
background:radial-gradient(40% 34% at 30% 30%,rgba(255,196,214,.35) 0%,transparent 70%),radial-gradient(42% 36% at 72% 64%,rgba(166,213,255,.38) 0%,transparent 70%),radial-gradient(36% 30% at 50% 100%,rgba(255,222,176,.32) 0%,transparent 70%),#FAFBFE;
|
||||
transition:transform .62s cubic-bezier(.7,0,.2,1),opacity .5s ease .12s}
|
||||
.jz-boot-in{display:flex;flex-direction:column;align-items:center;gap:18px}
|
||||
.jz-boot-gem{width:168px;height:168px;image-rendering:pixelated;filter:drop-shadow(-8px 16px 18px rgba(255,110,140,.28)) drop-shadow(8px 16px 18px rgba(70,140,255,.28))}
|
||||
.jz-boot-name{font:400 36px/1 var(--pixel);letter-spacing:.06em;color:var(--ink);-webkit-font-smoothing:none;display:flex;gap:2px;min-height:36px}
|
||||
.jz-boot-name span{display:inline-block;opacity:0;transform:translateY(14px) scale(.6)}
|
||||
.jz-boot.built .jz-boot-name span{animation:jzPop .42s cubic-bezier(.34,1.56,.64,1) both;animation-delay:calc(var(--i) * 70ms)}
|
||||
@keyframes jzPop{to{opacity:1;transform:none}}
|
||||
.jz-boot-bar{position:relative;display:block;width:200px;height:6px;border-radius:2px;background:rgba(30,36,64,.07);overflow:hidden;box-shadow:inset 0 0 0 1px rgba(255,255,255,.8)}
|
||||
.jz-boot-bar i{position:absolute;inset:0;background:var(--spec);transform-origin:0 50%;transform:scaleX(0);transition:transform .25s linear}
|
||||
.jz-boot.leave{transform:translateY(-100%);opacity:0;pointer-events:none}
|
||||
.jz-boot.leave .jz-boot-in{transition:transform .5s cubic-bezier(.7,0,.2,1);transform:translateY(-30px) scale(.92)}
|
||||
html.booting body{overflow:hidden}
|
||||
/* 幕布收起时,页面主体跟着轻轻浮上来 */
|
||||
html.booted main,html.booted .hero{animation:jzRise .7s cubic-bezier(.23,1,.32,1) both}
|
||||
@keyframes jzRise{from{opacity:.001;transform:translateY(18px)}to{opacity:1;transform:none}}
|
||||
|
||||
/* ---------- 画展:作品墙按列投放(预览站是 CSS 分栏,顺序会竖着走;这里改成 JS 投列,样子不变) ---------- */
|
||||
.wall{columns:auto;display:grid;grid-template-columns:repeat(var(--cols,3),minmax(0,1fr));gap:16px;align-items:start}
|
||||
.wall-col{display:flex;flex-direction:column;gap:16px;min-width:0}
|
||||
.wall-col .art{margin:0}
|
||||
.art button{position:relative}
|
||||
.art img{background:linear-gradient(165deg,#F2F4FA,#FAF9FF)}
|
||||
.art-play{position:absolute;left:50%;top:50%;width:52px;height:52px;margin:-26px 0 0 -26px;display:grid;place-items:center;border-radius:6px;color:#fff;background:rgba(30,36,64,.42);-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);box-shadow:inset 0 0 0 2px rgba(255,255,255,.55);transition:transform .2s var(--ease),background .2s var(--ease)}
|
||||
.art:hover .art-play{transform:scale(1.08);background:var(--mc-green)}
|
||||
.art-play svg{margin-left:3px}
|
||||
.art-sp,.art-own{position:absolute;top:10px;height:24px;display:inline-flex;align-items:center;padding:0 8px;border-radius:4px;font-size:12px;font-weight:700;color:var(--ink);background:rgba(255,255,255,.9);box-shadow:0 4px 10px -6px rgba(30,36,64,.4)}
|
||||
.art-sp{left:10px}
|
||||
.art-own{right:10px;color:#8A5A12;background:rgba(255,246,224,.95)}
|
||||
.art .cap .art-desc{font-style:normal;font-size:13px;line-height:1.6;color:var(--ink-2)}
|
||||
.art .cap .art-meta{display:flex;flex-wrap:wrap;justify-content:flex-start;gap:6px 12px;font-size:12px}
|
||||
.art-meta em{font-style:normal;color:var(--ink-3)}
|
||||
.art-meta em.mine{color:#2E7D32}
|
||||
.art-meta a{color:var(--ink-2);font-weight:700;text-decoration:none;border-bottom:1px dotted currentColor}
|
||||
.art-meta a:hover{color:var(--ink)}
|
||||
.years a.mon{height:34px;margin-left:12px;font-size:14px}
|
||||
.years a.mon.on{box-shadow:inset 3px 0 0 var(--mc-green)}
|
||||
/* 更多筛选 */
|
||||
.g-more{display:flex;flex-direction:column;gap:10px;margin:-8px 0 22px;padding:14px 16px;border-radius:var(--r)}
|
||||
.g-more[hidden]{display:none}
|
||||
.g-more-row{display:flex;flex-wrap:wrap;align-items:center;gap:8px 14px}
|
||||
.g-more-row > b{min-width:4em;font-size:13px;color:var(--ink-3)}
|
||||
.g-more .seg{background:rgba(255,255,255,.55)}
|
||||
.g-more .seg button{height:34px;padding:0 12px;font-size:13.5px}
|
||||
.m-years{display:none}
|
||||
@media (max-width:760px){
|
||||
.wall{gap:10px}
|
||||
.wall-col{gap:10px}
|
||||
.m-years{display:flex}
|
||||
.art-play{width:40px;height:40px;margin:-20px 0 0 -20px}
|
||||
.art-sp,.art-own{top:6px;height:20px;font-size:11px;padding:0 6px}
|
||||
.art-sp{left:6px}.art-own{right:6px}
|
||||
.art .cap .art-desc{display:none}
|
||||
.g-more{margin:-4px 0 14px;padding:12px}
|
||||
}
|
||||
|
||||
/* ---------- 看作品:白色毛玻璃大图层(预览站 .lb 的样子,多了视频 / B 站 / 全景 / 动态壁纸) ---------- */
|
||||
.gbox{position:fixed;inset:0;z-index:100;display:flex;flex-direction:column;gap:12px;padding:18px 24px 20px;background:rgba(250,251,255,.9);-webkit-backdrop-filter:blur(16px);backdrop-filter:blur(16px);opacity:0;transition:opacity .2s var(--ease)}
|
||||
.gbox[hidden]{display:none}
|
||||
.gbox.open{opacity:1}
|
||||
html.gbox-on{overflow:hidden}
|
||||
.gbox-bar{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
|
||||
.gbox-t{flex:1;min-width:0;display:flex;flex-direction:column}
|
||||
.gbox-t b{font-size:17px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.gbox-t span{font-size:13px;color:var(--ink-3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.gbox-stage{position:relative;flex:1;min-height:0;display:grid;place-items:center;overflow:hidden}
|
||||
.gbox-stage > *{grid-area:1/1}
|
||||
.gbox-stage img,.gbox-vid,.gbox-stage iframe,.gbox-stage canvas{max-width:min(1400px,100%);max-height:100%;border-radius:8px;border:4px solid #fff;
|
||||
box-shadow:-10px 26px 50px -26px rgba(255,110,140,.5),10px 26px 50px -26px rgba(70,140,255,.5);background:#fff}
|
||||
/* 长图 / 宽图都整张放进窗口里(网格行高是 auto,百分比 max-height 不生效,所以按视口算:顶栏 + 底栏 + 边距约 170px) */
|
||||
.gbox-stage img{object-fit:contain;width:auto;height:auto;max-width:100%;max-height:calc(100vh - 170px);max-height:calc(100dvh - 170px)}
|
||||
.gbox-stage canvas{max-height:calc(100vh - 170px);max-height:calc(100dvh - 170px)}
|
||||
.gbox-vid{position:relative;display:flex;background:#0d1020;overflow:hidden}
|
||||
.gbox-vid[hidden]{display:none}
|
||||
.gbox-vid video{display:block;max-width:100%;max-height:calc(100vh - 170px)}
|
||||
.gbox .v-wm{position:absolute;right:12px;bottom:46px;padding:3px 8px;border-radius:4px;font-size:12px;font-weight:700;color:rgba(255,255,255,.82);background:rgba(0,0,0,.28);pointer-events:none}
|
||||
.gbox-stage iframe{width:min(1100px,100%);aspect-ratio:16/9;height:auto;background:#000}
|
||||
.gbox-stage canvas{width:min(1200px,100%);aspect-ratio:2/1;height:auto;cursor:grab;touch-action:none}
|
||||
.gbox-stage canvas:active{cursor:grabbing}
|
||||
#gbWall{cursor:ew-resize;touch-action:pan-y;user-select:none}
|
||||
.gbox-load{padding:10px 16px;border-radius:6px;background:#fff;font-size:14px;color:var(--ink-2);box-shadow:0 10px 24px -14px rgba(60,80,120,.5)}
|
||||
.gbox-load[hidden]{display:none}
|
||||
.gbox-foot{display:flex;align-items:center;justify-content:center;flex-wrap:wrap;gap:10px 18px;min-height:20px}
|
||||
.gbox-hint{font-size:13px;color:var(--ink-3)}
|
||||
.gbox-wallbar{display:flex;align-items:center;gap:12px;width:min(640px,100%)}
|
||||
.gbox-wallbar[hidden]{display:none}
|
||||
.gbox-wallbar input{flex:1;accent-color:var(--mc-green)}
|
||||
.gbox-wallbar span{font-size:13px;color:var(--ink-2);white-space:nowrap}
|
||||
.g-links{display:flex;flex-wrap:wrap;gap:8px}
|
||||
@media (max-width:760px){
|
||||
.gbox{padding:12px 10px calc(14px + env(safe-area-inset-bottom))}
|
||||
.gbox-bar .btn{height:36px;padding:0 10px 2px;font-size:13px}
|
||||
.gbox-stage img,.gbox-vid,.gbox-stage iframe,.gbox-stage canvas{border-width:2px}
|
||||
.gbox-stage img{max-height:calc(100vh - 150px);max-height:calc(100dvh - 150px)}
|
||||
.gbox-stage canvas{aspect-ratio:4/5}
|
||||
}
|
||||
|
||||
/* ---------- 工具卡:按钮里的小箭头 ---------- */
|
||||
.tool .acts .btn svg{margin-left:2px}
|
||||
.about-grid .letter p + p{margin-top:14px}
|
||||
.credit p + p{margin-top:6px}
|
||||
.credit a,.letter a{color:var(--ink);font-weight:700;text-decoration:underline;text-decoration-color:rgba(60,133,39,.5);text-underline-offset:3px}
|
||||
/* hidden 属性永远说了算(.btn / .seg 等自带 display 的不能把它顶掉) */
|
||||
[hidden]{display:none !important}
|
||||
|
||||
|
||||
/* =====================================================================================
|
||||
手机深色模式(2026-10-06):系统设成深色时,手机上整站换成「夜里的同一家店」——
|
||||
还是那套晶体面板 / MC 方块按钮 / 光谱藏色,只是底换成深蓝黑、面板换成深色玻璃、字换成浅色。
|
||||
只在手机宽度生效(店主要求);要让电脑也跟随,把下面的 (max-width:760px) and 去掉即可。
|
||||
流动背景的深色版在 site.js 的着色器里(uDark)。
|
||||
===================================================================================== */
|
||||
@media (max-width:760px) and (prefers-color-scheme:dark){
|
||||
:root{color-scheme:dark;
|
||||
--ink:#E9ECF7; --ink-2:#B8BED8; --ink-3:#8A91AE; --bg:#0D1020;
|
||||
--line:rgba(255,255,255,.08); --line-2:rgba(255,255,255,.14);
|
||||
--stone:#2A3046; --stone-lo:#161A2A; --stone-edge:#3D4462;
|
||||
--lift-hi:0 0 0 1px rgba(255,255,255,.06),0 22px 40px -24px rgba(0,0,0,.7);
|
||||
--dk-glass:linear-gradient(160deg,rgba(34,39,62,.86) 0%,rgba(24,28,46,.74) 100%);
|
||||
--dk-edge:rgba(255,255,255,.09);
|
||||
}
|
||||
body,body.uni{background:radial-gradient(40% 30% at 10% 0%,rgba(80,120,220,.22) 0%,transparent 70%),radial-gradient(36% 28% at 100% 10%,rgba(200,90,150,.16) 0%,transparent 70%),radial-gradient(44% 34% at 70% 100%,rgba(60,160,120,.14) 0%,transparent 70%),var(--bg)}
|
||||
::selection{background:rgba(91,170,60,.45);color:#fff}
|
||||
/* 面板:深色玻璃 */
|
||||
.crystal,body .ucell{border-color:var(--dk-edge) !important;background:var(--dk-glass);box-shadow:inset 0 1px 0 rgba(255,255,255,.05),0 18px 36px -24px rgba(0,0,0,.75)}
|
||||
.room::before{opacity:.2}
|
||||
/* 顶栏 / 底栏 / 更多面板 */
|
||||
.top{background:rgba(13,16,32,.72);box-shadow:inset 0 -1px 0 rgba(255,255,255,.06)}
|
||||
.top::after{background:rgba(255,255,255,.05)}
|
||||
.cms-ent{color:var(--ink);opacity:.4}
|
||||
.tabbar{background:rgba(20,24,42,.88);border-color:rgba(255,255,255,.08);box-shadow:0 16px 34px -14px rgba(0,0,0,.8)}
|
||||
.tabbar a,.tabbar button{background:rgba(255,255,255,.04);box-shadow:inset 0 0 0 2px rgba(255,255,255,.06);color:var(--ink-3)}
|
||||
.tabbar [aria-current=page],.tabbar [aria-expanded=true]{background:#1C2136;color:var(--ink)}
|
||||
.tabbar .mid i,.btn-pill .ic{background-color:#F3F5FA}
|
||||
.sheet::before{background:rgba(0,0,0,.45)}
|
||||
.sheet .panel{background:#161A2C;border-color:#232842}
|
||||
.more-grid a{color:var(--ink);background:linear-gradient(160deg,color-mix(in srgb,var(--zc) 22%,#161A2C),color-mix(in srgb,var(--zc2) 12%,#161A2C));box-shadow:inset 0 0 0 2px color-mix(in srgb,var(--zc) 40%,transparent)}
|
||||
.more-grid i{color:var(--ink)}
|
||||
/* 首屏 */
|
||||
.sky{background:radial-gradient(60% 70% at 12% 18%,rgba(255,120,160,.16) 0%,transparent 70%),radial-gradient(55% 65% at 88% 26%,rgba(90,140,255,.22) 0%,transparent 70%),radial-gradient(50% 60% at 55% 105%,rgba(255,190,110,.12) 0%,transparent 70%),linear-gradient(165deg,#181C31 0%,#12152A 100%) !important}
|
||||
.hero .sky{border-color:var(--dk-edge) !important}
|
||||
.beam{background:linear-gradient(90deg,rgba(255,255,255,0) 0%,rgba(180,200,255,.18) 70%,rgba(180,200,255,.05) 100%)}
|
||||
.fan{opacity:.55}
|
||||
.emblem .halo{background:radial-gradient(circle,rgba(160,190,255,.28) 0%,rgba(120,150,255,.12) 40%,rgba(0,0,0,0) 70%)}
|
||||
.tag-l,.chip,.type{background:rgba(255,255,255,.06);border-color:rgba(255,255,255,.1);color:var(--ink-2)}
|
||||
.type{background:linear-gradient(#1C2136,#1C2136) padding-box,var(--edge) border-box}
|
||||
.kk i{color:var(--ink);background:linear-gradient(140deg,color-mix(in srgb,var(--zc) 30%,#1A1F35) 0%,color-mix(in srgb,var(--zc2) 22%,#1A1F35) 100%);box-shadow:inset 0 2px 0 rgba(255,255,255,.08),inset 0 -3px 0 rgba(0,0,0,.3)}
|
||||
.kk a{color:var(--ink-2)}
|
||||
/* 按钮:白石头换深石头(绿按钮不变) */
|
||||
.btn-crystal{background:var(--stone);color:var(--ink);border-color:var(--stone-edge);box-shadow:inset 0 2px 0 rgba(255,255,255,.08),inset 0 -4px 0 var(--stone-lo),0 8px 16px -10px rgba(0,0,0,.6)}
|
||||
.btn-crystal:hover{background:#323953}
|
||||
.board-row .act{background:var(--stone);border-color:var(--stone-edge);color:var(--ink);box-shadow:inset 0 2px 0 rgba(255,255,255,.08),inset 0 -3px 0 var(--stone-lo)}
|
||||
.board-group{background:linear-gradient(90deg,rgba(255,110,150,.08),rgba(90,150,255,.08));color:var(--ink-3)}
|
||||
.board-row:hover{background:rgba(255,255,255,.03)}
|
||||
.desk-ic,.svc-ic,.uni-tile,.disk .emb,.path .pi{background:linear-gradient(160deg,#20253D,#181C30) padding-box,var(--edge-strong) border-box}
|
||||
/* 筛选条 / 年份 / 更多筛选 */
|
||||
.tools-bar{background:linear-gradient(rgba(13,16,32,.94),rgba(13,16,32,.8))}
|
||||
.g-more .seg{background:rgba(255,255,255,.04)}
|
||||
.seg button{color:var(--ink-2)}
|
||||
/* 画展卡片 / 占位 */
|
||||
.art img{background:linear-gradient(165deg,#1A1E33,#151829)}
|
||||
.ph{background:linear-gradient(165deg,#1A1E33,#161A2C);color:var(--ink-3)}
|
||||
.ph::before{border-color:rgba(160,170,220,.22)}
|
||||
.art-sp,.art-own{background:rgba(16,19,34,.85);color:var(--ink)}
|
||||
.art-own{color:#F2C97A}
|
||||
.art-meta em.mine{color:#7BD45A}
|
||||
/* 关于 / 工具 */
|
||||
.credit code{background:rgba(255,255,255,.06);border-color:rgba(255,255,255,.1)}
|
||||
.credit a,.letter a{color:var(--ink)}
|
||||
.kv{border-color:rgba(255,255,255,.08)}
|
||||
.row-title::after,.room-head::after{opacity:.5}
|
||||
/* 看作品 */
|
||||
.gbox{background:rgba(8,10,20,.92)}
|
||||
.gbox-stage img,.gbox-vid,.gbox-stage iframe,.gbox-stage canvas{border-color:#262B44;background:#111426;box-shadow:0 26px 50px -26px rgba(0,0,0,.9)}
|
||||
.gbox-load{background:#1C2136;color:var(--ink-2)}
|
||||
/* 页脚 / 提示条 */
|
||||
.foot-site{background:rgba(255,255,255,.03)}
|
||||
.foot-site::before{background:rgba(255,255,255,.06)}
|
||||
.ribbon{background:rgba(255,255,255,.04);border-color:rgba(255,255,255,.06);color:var(--ink-2)}
|
||||
.ribbon.preview-bar{background:linear-gradient(90deg,rgba(120,90,20,.45),rgba(120,40,70,.4));color:#FFE3A6}
|
||||
.status.off{color:#E3A85A}
|
||||
/* 加载动画的幕布 */
|
||||
.jz-boot{background:radial-gradient(40% 34% at 30% 30%,rgba(255,110,150,.16) 0%,transparent 70%),radial-gradient(42% 36% at 72% 64%,rgba(90,140,255,.2) 0%,transparent 70%),#0D1020}
|
||||
.jz-boot-bar{background:rgba(255,255,255,.08);box-shadow:inset 0 0 0 1px rgba(255,255,255,.06)}
|
||||
/* 金钻宇宙页:星图窗框、档案卡、空槽、开场星门 */
|
||||
body .skywin{background:rgba(30,34,56,.8);border-color:#262B44}
|
||||
body .skywin .panel .card{background:rgba(22,26,44,.97);border-color:#2A3050;color:var(--ink)}
|
||||
body .skywin .panel .card .tags span{background:rgba(255,255,255,.07)}
|
||||
body .uslots button{background:rgba(255,255,255,.04);border-color:rgba(160,170,220,.25);color:var(--ink-3)}
|
||||
body .ugate{background:radial-gradient(46% 52% at 50% 46%,rgba(26,30,52,.97) 0%,rgba(16,19,36,.95) 55%,rgba(10,12,26,.94) 100%)}
|
||||
body .ugate-slots i{background:rgba(255,255,255,.05);border-color:rgba(160,170,220,.3)}
|
||||
body .ugate-slots i.l{background:#20253D;box-shadow:inset 0 0 0 2px rgba(255,255,255,.06)}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
/* 金钻客栈 · 全站交互(设计预览站原版,2026-10-06 搬进仓库):流动背景、手机「更多」、视差、卡片倾斜、滚动浮现、星尘、翻牌 */
|
||||
(function () {
|
||||
'use strict';
|
||||
var reduce = window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
var finePointer = window.matchMedia && matchMedia('(hover: hover) and (pointer: fine)').matches;
|
||||
document.documentElement.classList.add('js');
|
||||
|
||||
/* ---------- 整页动态背景:WebGL 流动渐变(低分辨率、30fps、标签页不可见时浏览器自动暂停) ---------- */
|
||||
var mouseX = 0, mouseY = 0;
|
||||
(function glBackground() {
|
||||
var c = document.createElement('canvas');
|
||||
c.className = 'bg-gl'; c.setAttribute('aria-hidden', 'true');
|
||||
var gl = null;
|
||||
try { gl = c.getContext('webgl', { antialias: false, alpha: false, depth: false, stencil: false, powerPreference: 'low-power' }); } catch (e) {}
|
||||
if (!gl) return;
|
||||
var VS = 'attribute vec2 p;void main(){gl_Position=vec4(p,0.0,1.0);}';
|
||||
var FS = [
|
||||
'precision mediump float;uniform vec2 uRes;uniform float uTime;uniform vec2 uMouse;uniform float uUni;uniform float uDark;',
|
||||
'vec3 m289(vec3 x){return x-floor(x*(1.0/289.0))*289.0;}vec4 m289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}',
|
||||
'vec4 perm(vec4 x){return m289(((x*34.0)+1.0)*x);}vec4 tis(vec4 r){return 1.79284291400159-0.85373472095314*r;}',
|
||||
'float sn(vec3 v){const vec2 C=vec2(1.0/6.0,1.0/3.0);const vec4 D=vec4(0.0,0.5,1.0,2.0);',
|
||||
'vec3 i=floor(v+dot(v,C.yyy));vec3 x0=v-i+dot(i,C.xxx);vec3 g=step(x0.yzx,x0.xyz);vec3 l=1.0-g;',
|
||||
'vec3 i1=min(g.xyz,l.zxy);vec3 i2=max(g.xyz,l.zxy);vec3 x1=x0-i1+C.xxx;vec3 x2=x0-i2+C.yyy;vec3 x3=x0-D.yyy;',
|
||||
'i=m289(i);vec4 p=perm(perm(perm(i.z+vec4(0.0,i1.z,i2.z,1.0))+i.y+vec4(0.0,i1.y,i2.y,1.0))+i.x+vec4(0.0,i1.x,i2.x,1.0));',
|
||||
'float n_=0.142857142857;vec3 ns=n_*D.wyz-D.xzx;vec4 j=p-49.0*floor(p*ns.z*ns.z);vec4 x_=floor(j*ns.z);vec4 y_=floor(j-7.0*x_);',
|
||||
'vec4 x=x_*ns.x+ns.yyyy;vec4 y=y_*ns.x+ns.yyyy;vec4 h=1.0-abs(x)-abs(y);vec4 b0=vec4(x.xy,y.xy);vec4 b1=vec4(x.zw,y.zw);',
|
||||
'vec4 s0=floor(b0)*2.0+1.0;vec4 s1=floor(b1)*2.0+1.0;vec4 sh=-step(h,vec4(0.0));vec4 a0=b0.xzyw+s0.xzyw*sh.xxyy;vec4 a1=b1.xzyw+s1.xzyw*sh.zzww;',
|
||||
'vec3 p0=vec3(a0.xy,h.x);vec3 p1=vec3(a0.zw,h.y);vec3 p2=vec3(a1.xy,h.z);vec3 p3=vec3(a1.zw,h.w);',
|
||||
'vec4 nm=tis(vec4(dot(p0,p0),dot(p1,p1),dot(p2,p2),dot(p3,p3)));p0*=nm.x;p1*=nm.y;p2*=nm.z;p3*=nm.w;',
|
||||
'vec4 m=max(0.6-vec4(dot(x0,x0),dot(x1,x1),dot(x2,x2),dot(x3,x3)),0.0);m=m*m;',
|
||||
'return 42.0*dot(m*m,vec4(dot(p0,x0),dot(p1,x1),dot(p2,x2),dot(p3,x3)));}',
|
||||
'void main(){vec2 uv=gl_FragCoord.xy/uRes;vec2 q=vec2(uv.x*uRes.x/uRes.y,uv.y)*1.25+uMouse*0.09;float t=uTime*0.085;',
|
||||
'float n1=sn(vec3(q*0.85,t));float n2=sn(vec3(q*1.4+vec2(3.1,1.7),t*1.25));float n3=sn(vec3(q*0.6-vec2(5.2,2.3),t*0.8));float n4=sn(vec3(q*1.1+vec2(-2.7,4.4),t*1.1));',
|
||||
'vec3 pink=vec3(0.55,0.90,0.90);vec3 blue=vec3(0.58,0.72,1.0);vec3 mint=vec3(0.56,0.88,0.64);vec3 peach=vec3(1.0,0.86,0.48);vec3 lav=vec3(0.76,0.66,0.98);',
|
||||
'vec3 col=mix(pink,blue,smoothstep(-0.55,0.55,n1));col=mix(col,mint,smoothstep(0.05,0.85,n2)*0.85);',
|
||||
'col=mix(col,peach,smoothstep(0.15,0.9,n3)*0.75);col=mix(col,lav,smoothstep(0.2,0.95,n4)*0.7);col=mix(col,lav,0.28*uUni);',
|
||||
'float w=0.74+0.14*sn(vec3(q*0.45,t*0.6));vec3 lite=mix(col,vec3(0.975,0.98,0.985),clamp(w,0.6,0.9));',
|
||||
/* 手机深色模式:同一团流动的彩光,压暗后往深蓝黑里混(uDark 0 → 1) */
|
||||
'vec3 dark=mix(col*0.34,vec3(0.05,0.06,0.12),clamp(w,0.6,0.9)*0.9);gl_FragColor=vec4(mix(lite,dark,uDark),1.0);}'
|
||||
].join('');
|
||||
function sh(type, src) { var o = gl.createShader(type); gl.shaderSource(o, src); gl.compileShader(o); return gl.getShaderParameter(o, gl.COMPILE_STATUS) ? o : null; }
|
||||
var v = sh(gl.VERTEX_SHADER, VS), f = sh(gl.FRAGMENT_SHADER, FS);
|
||||
if (!v || !f) return;
|
||||
var prog = gl.createProgram(); gl.attachShader(prog, v); gl.attachShader(prog, f); gl.linkProgram(prog);
|
||||
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) return;
|
||||
gl.useProgram(prog);
|
||||
var buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buf);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
|
||||
var loc = gl.getAttribLocation(prog, 'p'); gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
|
||||
var uRes = gl.getUniformLocation(prog, 'uRes'), uTime = gl.getUniformLocation(prog, 'uTime'),
|
||||
uMouse = gl.getUniformLocation(prog, 'uMouse'), uUni = gl.getUniformLocation(prog, 'uUni'), uDark = gl.getUniformLocation(prog, 'uDark');
|
||||
/* 深色模式:只在手机宽度跟系统走(和 site.css 里那段一致);切换时实时换 */
|
||||
var mqDark = window.matchMedia ? matchMedia('(max-width: 760px) and (prefers-color-scheme: dark)') : null;
|
||||
function setDark() { gl.uniform1f(uDark, mqDark && mqDark.matches ? 1 : 0); }
|
||||
setDark();
|
||||
if (mqDark) { var onDark = function () { setDark(); draw(performance.now()); }; if (mqDark.addEventListener) mqDark.addEventListener('change', onDark); else if (mqDark.addListener) mqDark.addListener(onDark); }
|
||||
gl.uniform1f(uUni, document.body.classList.contains('uni') ? 1 : 0);
|
||||
document.body.insertBefore(c, document.body.firstChild);
|
||||
document.documentElement.classList.add('has-gl');
|
||||
var scale = window.innerWidth < 760 ? 0.25 : 0.18, t0 = performance.now(), last = 0;
|
||||
function resize() {
|
||||
var w = Math.max(16, Math.round(window.innerWidth * scale)), h = Math.max(16, Math.round(window.innerHeight * scale));
|
||||
c.width = w; c.height = h; gl.viewport(0, 0, w, h); gl.uniform2f(uRes, w, h); draw(performance.now());
|
||||
}
|
||||
function draw(now) {
|
||||
gl.uniform1f(uTime, (now - t0) / 1000 + 20);
|
||||
gl.uniform2f(uMouse, mouseX, -mouseY);
|
||||
gl.drawArrays(gl.TRIANGLES, 0, 3);
|
||||
}
|
||||
function loop(now) { requestAnimationFrame(loop); if (now - last < 33) return; last = now; draw(now); }
|
||||
resize();
|
||||
window.addEventListener('resize', function () { clearTimeout(c._rt); c._rt = setTimeout(resize, 150); });
|
||||
if (!reduce) requestAnimationFrame(loop);
|
||||
})();
|
||||
|
||||
/* ---------- 手机:「更多」——底栏按钮开/关,底栏保持可点;返回键、点空白、Esc 都能收起 ---------- */
|
||||
(function sheet() {
|
||||
var sh = document.getElementById('more'), btn = document.querySelector('[data-sheet="more"]'), bar = btn && btn.parentNode, pushed = false, timer;
|
||||
if (!sh || !btn) return;
|
||||
function isOpen() { return btn.getAttribute('aria-expanded') === 'true'; }
|
||||
function open(kb) {
|
||||
clearTimeout(timer); sh.hidden = false; btn.setAttribute('aria-expanded', 'true');
|
||||
requestAnimationFrame(function () { requestAnimationFrame(function () { sh.classList.add('open'); }); });
|
||||
if (kb) { var a = sh.querySelector('a'); if (a) a.focus(); }
|
||||
try { history.pushState({ jzMore: 1 }, ''); pushed = true; } catch (e) {}
|
||||
}
|
||||
function close(fromPop) {
|
||||
if (!isOpen()) return;
|
||||
sh.classList.remove('open'); btn.setAttribute('aria-expanded', 'false');
|
||||
timer = setTimeout(function () { sh.hidden = true; }, reduce ? 0 : 240);
|
||||
if (pushed) { pushed = false; if (!fromPop) history.back(); }
|
||||
}
|
||||
btn.addEventListener('click', function (e) { if (isOpen()) close(); else open(e.detail === 0); });
|
||||
sh.addEventListener('click', function (e) { if (e.target === sh) close(); });
|
||||
window.addEventListener('popstate', function () { if (pushed) { pushed = false; close(true); } });
|
||||
document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && isOpen()) { close(); btn.focus(); } });
|
||||
/* 开着面板时点链接跳走:替换掉多出来的那条历史,免得返回时要按两次 */
|
||||
document.addEventListener('click', function (e) {
|
||||
if (!pushed || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
||||
var a = e.target.closest('a[href]');
|
||||
if (!a || a.target === '_blank' || !(sh.contains(a) || bar.contains(a))) return;
|
||||
e.preventDefault(); location.replace(a.href);
|
||||
});
|
||||
window.addEventListener('pageshow', function (e) {
|
||||
if (e.persisted && isOpen()) { pushed = false; sh.classList.remove('open'); sh.hidden = true; btn.setAttribute('aria-expanded', 'false'); }
|
||||
});
|
||||
})();
|
||||
|
||||
/* ---------- 鼠标视差:背景彩光、首屏钻石跟着鼠标轻轻错位(只改 CSS 变量,GPU 合成) ---------- */
|
||||
if (!reduce && finePointer) {
|
||||
var tx = 0, ty = 0, cx = 0, cy = 0, pr = 0, docEl = document.documentElement;
|
||||
window.addEventListener('pointermove', function (e) {
|
||||
tx = (e.clientX / window.innerWidth) * 2 - 1;
|
||||
ty = (e.clientY / window.innerHeight) * 2 - 1;
|
||||
mouseX = tx; mouseY = ty;
|
||||
if (!pr) pr = requestAnimationFrame(follow);
|
||||
}, { passive: true });
|
||||
function follow() {
|
||||
cx += (tx - cx) * 0.08; cy += (ty - cy) * 0.08;
|
||||
docEl.style.setProperty('--mx', cx.toFixed(4));
|
||||
docEl.style.setProperty('--my', cy.toFixed(4));
|
||||
pr = (Math.abs(tx - cx) > 0.001 || Math.abs(ty - cy) > 0.001) ? requestAnimationFrame(follow) : 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- 卡片:随鼠标轻微倾斜 + 玻璃上跟着鼠标的柔光 ---------- */
|
||||
if (!reduce && finePointer) {
|
||||
Array.prototype.forEach.call(document.querySelectorAll('.room, .tool, .path, .tpl, .art'), function (el) {
|
||||
el.classList.add('fx');
|
||||
var raf = 0, lx = 0, ly = 0;
|
||||
el.addEventListener('pointermove', function (e) {
|
||||
var r = el.getBoundingClientRect();
|
||||
lx = (e.clientX - r.left) / r.width; ly = (e.clientY - r.top) / r.height;
|
||||
if (raf) return;
|
||||
raf = requestAnimationFrame(function () {
|
||||
raf = 0;
|
||||
var max = el.classList.contains('big') ? 3 : 5;
|
||||
el.style.setProperty('--px', (lx * 100).toFixed(1) + '%');
|
||||
el.style.setProperty('--py', (ly * 100).toFixed(1) + '%');
|
||||
el.style.setProperty('--ry', ((lx - 0.5) * max * 2).toFixed(2) + 'deg');
|
||||
el.style.setProperty('--rx', ((0.5 - ly) * max * 2).toFixed(2) + 'deg');
|
||||
});
|
||||
});
|
||||
el.addEventListener('pointerenter', function () { el.classList.add('on'); });
|
||||
el.addEventListener('pointerleave', function () {
|
||||
el.classList.remove('on');
|
||||
el.style.setProperty('--rx', '0deg'); el.style.setProperty('--ry', '0deg');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- 滚动时内容依次浮现 ---------- */
|
||||
if (!reduce && 'IntersectionObserver' in window) {
|
||||
var targets = document.querySelectorAll('.sec-h, .room, .desk, .board, .tool, .row-title, .disk, .uni-intro, .slots, .letter, .credit, .path, .pickup, .tpl, .pass, .art, .tools-bar');
|
||||
var groups = new Map();
|
||||
Array.prototype.forEach.call(targets, function (el) {
|
||||
var k = el.parentNode, n = groups.get(k) || 0; groups.set(k, n + 1);
|
||||
el.style.setProperty('--d', Math.min(n, 6) * 70 + 'ms');
|
||||
el.classList.add('rv');
|
||||
});
|
||||
var rio = new IntersectionObserver(function (es) {
|
||||
es.forEach(function (e) { if (e.isIntersecting) { e.target.classList.add('in'); rio.unobserve(e.target); } });
|
||||
}, { threshold: 0.08, rootMargin: '0px 0px -6% 0px' });
|
||||
Array.prototype.forEach.call(targets, function (el) { rio.observe(el); });
|
||||
}
|
||||
|
||||
/* ---------- 配色切换(记在本机浏览器里;也可用 ?theme=dawn 直接打开某套) ---------- */
|
||||
var root = document.documentElement;
|
||||
var listeners = [];
|
||||
function sparkPalette() {
|
||||
var v = getComputedStyle(root).getPropertyValue('--sparks').trim();
|
||||
return v ? v.split(/\s+/) : ['#FFFFFF'];
|
||||
}
|
||||
function markTheme() {
|
||||
var cur = root.getAttribute('data-theme') || 'navy';
|
||||
Array.prototype.forEach.call(document.querySelectorAll('[data-theme-btn]'), function (b) {
|
||||
b.setAttribute('aria-pressed', b.getAttribute('data-theme-btn') === cur ? 'true' : 'false');
|
||||
});
|
||||
}
|
||||
document.addEventListener('click', function (e) {
|
||||
var b = e.target.closest('[data-theme-btn]'); if (!b) return;
|
||||
var t = b.getAttribute('data-theme-btn');
|
||||
root.setAttribute('data-theme', t);
|
||||
try { localStorage.setItem('jz-theme', t); } catch (err) {}
|
||||
markTheme();
|
||||
listeners.forEach(function (fn) { fn(); });
|
||||
});
|
||||
markTheme();
|
||||
|
||||
/* ---------- 星尘:观景窗 / 宇宙背景里缓慢漂浮的光点 ---------- */
|
||||
function stars(canvas) {
|
||||
var ctx = canvas.getContext('2d');
|
||||
var dpr = Math.min(window.devicePixelRatio || 1, 2);
|
||||
var w = 0, h = 0, pts = [], raf = 0, visible = true;
|
||||
var density = +canvas.getAttribute('data-density') || 1;
|
||||
var PAL = sparkPalette();
|
||||
listeners.push(function () { PAL = sparkPalette(); pts.forEach(function (p) { p.c = PAL[(Math.random() * PAL.length) | 0]; }); draw(performance.now()); });
|
||||
function resize() {
|
||||
var r = canvas.getBoundingClientRect();
|
||||
w = r.width; h = r.height;
|
||||
canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr);
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
var n = Math.round((w * h) / 5200 * density * (w < 600 ? 0.6 : 1));
|
||||
pts = [];
|
||||
for (var i = 0; i < n; i++) {
|
||||
pts.push({
|
||||
x: Math.random() * w, y: Math.random() * h,
|
||||
r: Math.random() < 0.85 ? Math.random() * 1.3 + 0.5 : Math.random() * 2 + 1.6,
|
||||
c: PAL[(Math.random() * PAL.length) | 0],
|
||||
a: Math.random() * 0.6 + 0.25,
|
||||
vx: (Math.random() - 0.5) * 0.12, vy: -(Math.random() * 0.16 + 0.03),
|
||||
tw: Math.random() * Math.PI * 2
|
||||
});
|
||||
}
|
||||
draw(0);
|
||||
}
|
||||
function draw(t) {
|
||||
ctx.clearRect(0, 0, w, h);
|
||||
for (var i = 0; i < pts.length; i++) {
|
||||
var p = pts[i];
|
||||
if (!reduce) {
|
||||
p.x += p.vx; p.y += p.vy;
|
||||
if (p.y < -4) { p.y = h + 4; p.x = Math.random() * w; }
|
||||
if (p.x < -4) p.x = w + 4; else if (p.x > w + 4) p.x = -4;
|
||||
}
|
||||
var a = reduce ? p.a : p.a * (0.65 + 0.35 * Math.sin(t / 900 + p.tw));
|
||||
ctx.globalAlpha = a;
|
||||
ctx.fillStyle = p.c;
|
||||
var sz = p.r > 1.9 ? 4 : (p.r > 1.1 ? 3 : 2);
|
||||
ctx.fillRect(Math.round(p.x), Math.round(p.y), sz, sz);
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
}
|
||||
function loop(t) { raf = requestAnimationFrame(loop); if (visible) draw(t); }
|
||||
resize();
|
||||
window.addEventListener('resize', function () { clearTimeout(canvas._rt); canvas._rt = setTimeout(resize, 150); });
|
||||
if ('IntersectionObserver' in window) {
|
||||
new IntersectionObserver(function (es) { visible = es[0].isIntersecting; }).observe(canvas);
|
||||
}
|
||||
if (!reduce) raf = requestAnimationFrame(loop);
|
||||
}
|
||||
Array.prototype.forEach.call(document.querySelectorAll('canvas.stars'), stars);
|
||||
|
||||
/* ---------- 出发屏:进入视口时逐行翻牌 ---------- */
|
||||
var rows = document.querySelectorAll('.flip');
|
||||
function flipIn(list) {
|
||||
Array.prototype.forEach.call(list, function (el, i) {
|
||||
el.style.animationDelay = (i * 70) + 'ms';
|
||||
el.classList.add('in');
|
||||
});
|
||||
}
|
||||
if (rows.length) {
|
||||
if (reduce || !('IntersectionObserver' in window)) { flipIn(rows); }
|
||||
else {
|
||||
var boards = document.querySelectorAll('.board');
|
||||
var io = new IntersectionObserver(function (es) {
|
||||
es.forEach(function (e) {
|
||||
if (e.isIntersecting) { flipIn(e.target.querySelectorAll('.flip')); io.unobserve(e.target); }
|
||||
});
|
||||
}, { threshold: 0.15 });
|
||||
Array.prototype.forEach.call(boards, function (b) { io.observe(b); });
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- 画展:类型筛选 ---------- */
|
||||
var seg = document.querySelector('[data-filter-group]');
|
||||
if (seg) {
|
||||
seg.addEventListener('click', function (e) {
|
||||
var b = e.target.closest('button[data-f]'); if (!b) return;
|
||||
Array.prototype.forEach.call(seg.querySelectorAll('button'), function (x) { x.setAttribute('aria-pressed', x === b ? 'true' : 'false'); });
|
||||
var f = b.getAttribute('data-f');
|
||||
Array.prototype.forEach.call(document.querySelectorAll('.wall .art'), function (a) {
|
||||
a.hidden = !(f === 'all' || a.getAttribute('data-type') === f);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- 画展:看大图(切到深色,突出作品) ---------- */
|
||||
var lb = document.querySelector('.lb');
|
||||
if (lb) {
|
||||
var img = lb.querySelector('img'), cap = lb.querySelector('.lb-cap'), closeBtn = lb.querySelector('button');
|
||||
var last = null;
|
||||
document.addEventListener('click', function (e) {
|
||||
var t = e.target.closest('[data-full]'); if (!t) return;
|
||||
last = t;
|
||||
img.src = t.getAttribute('data-full'); img.alt = t.getAttribute('data-title') || '';
|
||||
cap.textContent = t.getAttribute('data-title') || '';
|
||||
lb.classList.add('open'); closeBtn.focus();
|
||||
});
|
||||
function close() { lb.classList.remove('open'); img.removeAttribute('src'); if (last) last.focus(); }
|
||||
closeBtn.addEventListener('click', close);
|
||||
lb.addEventListener('click', function (e) { if (e.target === lb) close(); });
|
||||
document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && lb.classList.contains('open')) close(); });
|
||||
}
|
||||
|
||||
/* ---------- 手机:当前屋子滚进导航可视区 ---------- */
|
||||
var cur = document.querySelector('.nav a[aria-current=page]');
|
||||
if (cur && cur.scrollIntoView) { try { cur.scrollIntoView({ block: 'nearest', inline: 'center' }); } catch (e) {} }
|
||||
})();
|
||||
@@ -0,0 +1,80 @@
|
||||
/* =============================================================================
|
||||
* 金钻宇宙 · 星系图配置(config.js)—— 日常改动只改这一个文件
|
||||
* -----------------------------------------------------------------------------
|
||||
* 1. UNIVERSES :世界线的「档案内容」(和门户页原来的 UNIVERSES 字段一模一样,可以直接拷过来)
|
||||
* 2. LOOKS :每条世界线在星系图上「长什么样」(星球风格、颜色、卫星、光环、在哪条旋臂上)
|
||||
* 3. GALAXY :整个星系的配色、旋臂、粒子数量、扇区名
|
||||
* 加一条新世界线 = UNIVERSES 里加一条 + LOOKS 里按编号加一条外观(不写外观就用「空槽」的样子)。
|
||||
* ============================================================================= */
|
||||
window.JZ_UNIVERSE = {
|
||||
|
||||
// ---------------------------------------------------------------- 1. 档案内容
|
||||
UNIVERSES: [
|
||||
{ no: '0000', name: '零号宇宙', kind: '主宇宙', tag: '晶钻超算主宇宙', tags: ['门户主宇宙', '晶钻超算', '多世界线演算'],
|
||||
desc: '门户主宇宙,也是晶钻超算本体:把平行宇宙压成盘符,逐条演算多世界线。其余编号都是它演算出的分支世界线,零号自身负责总调度与收束。' },
|
||||
{ no: '0001', name: '火柴人宇宙', kind: '原创', tag: '火柴人的冒险', tags: ['金钻原创', '小时候的课堂', '火柴人的冒险'],
|
||||
desc: '金钻小时候在课上天马行空画出来的世界线,《火柴人的冒险》就从这里开始。' },
|
||||
{ no: '0002', name: '极寒世界', kind: '原创', tag: '冰河时期', tags: ['金钻原创', '冰河时期', '那迦彗星', '五大深垒', '2056'],
|
||||
desc: '2030年代确认北大西洋环流(AMOC)减弱、气候转入长期寒冷;2040年高含水彗星「那迦」撞击北大西洋,水汽化为冰晶云遮蔽日照,冰河期开始。故事发生在2056年,冰河已持续16年,地表约-50℃(极端-90℃)。人类转入五大地下深垒。' },
|
||||
{ no: '0003', name: '没落赛博城', kind: '二创', tag: '史蒂夫的探险之旅', tags: ['二创', '史蒂夫的探险之旅', '赛博废墟'],
|
||||
desc: '金钻刚接触动画时随手做的二创世界线:史蒂夫穿过没落的赛博城,一路探险。' },
|
||||
{ no: '0004', name: '善恶等级', kind: '原创', tag: '设定待定', tags: ['金钻原创', '设定酝酿中'],
|
||||
desc: '这条世界线的设定还在酝酿中,先留好位置,等金钻想清楚再填。' },
|
||||
{ no: '0005', empty: true }, { no: '0006', empty: true }, { no: '0007', empty: true },
|
||||
{ no: '0008', empty: true }, { no: '0009', empty: true }, { no: '0010', empty: true },
|
||||
],
|
||||
|
||||
// ---------------------------------------------------------------- 2. 外观(按编号对应)
|
||||
// style:crystal 晶体 / paper 铅笔纸面 / ice 冰封 / neon 霓虹城 / duality 善恶两半 / gas 气态 / rock 岩石 / ghost 未点亮
|
||||
// orbit:[离星系中心多远, 第几条旋臂];moons:绕着它转的卫星(纯装饰,没有档案)
|
||||
// enter:点开这颗星时的运镜 —— push 推进 / zoom 放大(长焦再推)/ rise 升空俯冲 / warp 跃迁 / orbit 绕行;不写就按顺序轮流
|
||||
LOOKS: {
|
||||
'0000': { enter: 'zoom', style: 'crystal', r: 2.6, orbit: [0, 0], accent: '#FFD36E',
|
||||
why: '晶钻超算:多面体切面像钻石,内部有发光的演算脉络。',
|
||||
moons: [{ style: 'crystal', r: 0.45, d: 5.0, speed: 0.35, colors: ['#BFF4FF', '#8E7BFF', '#FFE59A', '#FFFFFF'] },
|
||||
{ style: 'rock', r: 0.32, d: 6.6, speed: 0.22 }] },
|
||||
'0001': { enter: 'push', style: 'paper', r: 1.25, orbit: [20, 0], accent: '#F6F1E4',
|
||||
why: '小时候课上画出来的:米白纸面、铅笔等高线、暗面排线、几个红笔圈。',
|
||||
moons: [{ style: 'paper', r: 0.36, d: 2.6, speed: 0.6, colors: ['#FFF8EC', '#2B2E45', '#E5544B', '#F2C14D'] }] },
|
||||
'0002': { enter: 'rise', style: 'ice', r: 1.35, orbit: [29, 1], accent: '#9FE3FF',
|
||||
why: '冰河期地球:纬向冰带、厚极冠、冰裂纹;旁边那颗小卫星是「那迦」彗星残骸。',
|
||||
moons: [{ style: 'rock', r: 0.3, d: 2.7, speed: 0.5, colors: ['#CFE6FF', '#8FB4E0', '#5C79B8', '#FFFFFF'] }] },
|
||||
'0003': { enter: 'warp', style: 'neon', r: 1.4, orbit: [38, 2], accent: '#C9A6FF',
|
||||
why: '没落的赛博城:深紫地表、霓虹街区网格、零星还亮着的窗灯。',
|
||||
moons: [{ style: 'rock', r: 0.28, d: 3.0, speed: 0.42, colors: ['#3A2F66', '#2A2350', '#1A1535', '#FF5FD2'] },
|
||||
{ style: 'neon', r: 0.22, d: 3.8, speed: 0.3 }] },
|
||||
'0004': { enter: 'orbit', style: 'duality', r: 1.3, orbit: [46, 3], accent: '#FFD36E',
|
||||
why: '设定还在酝酿,先按名字「善恶」做成两半:一半金色白昼,一半紫色夜空,交界一条发光的波浪线。设定定了再换。',
|
||||
moons: [{ style: 'gas', r: 0.34, d: 2.8, speed: 0.45, colors: ['#FFF0C8', '#F2B84B', '#2D1E57', '#FFFFFF'] }] },
|
||||
},
|
||||
EMPTY_LOOK: { style: 'ghost', r: 0.75, accent: '#8E96C8' }, // 空槽的样子(未点亮的星系)
|
||||
|
||||
// ---------------------------------------------------------------- 3. 星系整体
|
||||
GALAXY: {
|
||||
radius: 60, arms: 4, twist: 0.11,
|
||||
particles: { desktop: 42000, mobile: 36000 }, // 手机和桌面画面要一致:数量只略少一点
|
||||
nebulae: { desktop: 32, mobile: 28 },
|
||||
decorPlanets: { desktop: 14, mobile: 14 }, // 散落在旋臂上的无名星球(只是好看,不能点)
|
||||
// 配色:深海军蓝底 + 蓝紫星云 + 一点青色 + 暖金色核心。整张图只用这几种颜色。
|
||||
colors: {
|
||||
bg: '#070B1C', core: '#FFE2B0', armInner: '#9DB4FF', armOuter: '#7C6BFF', accentStar: '#6FE3D6',
|
||||
nebula: [['#2F4BD8', '#4FB8E8'], ['#4A35B8', '#7C6BFF'], ['#1C7A8C', '#4FD1C5'], ['#5B3FB8', '#9B8BFF']],
|
||||
coreNebula: ['#FFC97A', '#B98CFF'], line: '#7F8BC8', ui: '#FFD36E',
|
||||
},
|
||||
firstSlot: 5, // 空槽从几号开始按编号排到外圈固定槽位(排布规则见 layout.js)
|
||||
intro: 'random', // 开场运镜:sweep 盘旋落下 / dive 垂直坠入 / random 每次随机
|
||||
sectors: ['S-01 · 晨线', 'S-02 · 冰原', 'S-03 · 霓虹', 'S-04 · 衡天', 'S-05 · 未测绘', 'S-06 · 未测绘'],
|
||||
},
|
||||
};
|
||||
|
||||
/* -----------------------------------------------------------------------------
|
||||
* 内容后台发布的世界线(2026-10-05):门户先加载 content/site.js(window.JZ_CONTENT),
|
||||
* 里面有 universe.UNIVERSES / LOOKS 就用它的 —— 上面写死的两份只是兜底(内容文件读不到时用)。
|
||||
* 星系整体(GALAXY)和空槽外观(EMPTY_LOOK)不归后台管,还是改这个文件。
|
||||
* --------------------------------------------------------------------------- */
|
||||
(function () {
|
||||
var C = window.JZ_CONTENT && window.JZ_CONTENT.universe, U = window.JZ_UNIVERSE;
|
||||
if (!C || !U) return;
|
||||
if (Array.isArray(C.UNIVERSES)) U.UNIVERSES = C.UNIVERSES; // 后台把世界线删光了也照实显示(不退回兜底)
|
||||
if (C.LOOKS && typeof C.LOOKS === 'object') U.LOOKS = C.LOOKS;
|
||||
})();
|
||||
@@ -0,0 +1,311 @@
|
||||
/* =============================================================================
|
||||
* 金钻宇宙 · 星系图引擎(galaxy.js)
|
||||
* -----------------------------------------------------------------------------
|
||||
* 读 window.JZ_UNIVERSE(config.js)→ 画旋臂星系、星云、扇区、补给线、星系(卡通星球 + 卫星)、
|
||||
* 散落的无名星球;处理拖动 / 滚轮 / 双指缩放 / 点星系飞过去 / 档案卡。
|
||||
* 只依赖 three.js 和 planets.js。挂载:mountGalaxy({ stage, canvas, labels, panel, ... })
|
||||
* 嵌进普通页面时可选:
|
||||
* onFocus(u|null) 选中 / 取消选中某条世界线时回调(页面下方的列表可以跟着高亮)
|
||||
* layout() 返回 { x, y }:选中时星球往左 / 往上挪多少(屏宽 / 屏高的比例),给档案卡让位
|
||||
* wheelZoom() 返回 true 时滚轮直接缩放;false 时只有按住 Ctrl 才缩放(嵌在页面里别抢页面滚动)
|
||||
* 返回 { fly(no), home(), resize() }。画面滚出视口时自动暂停渲染。
|
||||
* ============================================================================= */
|
||||
import * as THREE from 'three';
|
||||
import { makePlanet } from './planets.js?v=2';
|
||||
import { layoutSystems } from './layout.js?v=3';
|
||||
|
||||
export function mountGalaxy(el) {
|
||||
const CFG = window.JZ_UNIVERSE, G = CFG.GALAXY, C = G.colors;
|
||||
const { stage, canvas, labels, panel, back, hud } = el;
|
||||
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
const isMob = () => stage.clientWidth < 760;
|
||||
const MOB = isMob();
|
||||
|
||||
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' });
|
||||
renderer.setPixelRatio(Math.min(devicePixelRatio, MOB ? 1.5 : 2));
|
||||
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
||||
renderer.setClearColor(C.bg, 1);
|
||||
const scene = new THREE.Scene(), camera = new THREE.PerspectiveCamera(42, 1, 0.1, 2000);
|
||||
const R = G.radius, ARMS = G.arms;
|
||||
const rnd = (a = 0, b = 1) => a + Math.random() * (b - a);
|
||||
const gauss = () => { let u = 0, v = 0; while (!u) u = Math.random(); while (!v) v = Math.random(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v); };
|
||||
const armAngle = (r, arm) => arm * Math.PI * 2 / ARMS + r * G.twist;
|
||||
// 名牌 / 档案卡里的文字一律转义(内容来自后台,不能当 HTML 拼)
|
||||
const esc = x => String(x == null ? '' : x).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const LIGHT = new THREE.Vector3(-1, 0.55, 0.6).normalize();
|
||||
|
||||
// ============================================================ 旋臂星系(粒子)—— 星点大小有上限,离镜头很近的也不会糊成大光斑
|
||||
const galaxy = (() => {
|
||||
const N = MOB ? G.particles.mobile : G.particles.desktop, pos = new Float32Array(N * 3), col = new Float32Array(N * 3), sz = new Float32Array(N);
|
||||
const cCore = new THREE.Color(C.core), cIn = new THREE.Color(C.armInner), cOut = new THREE.Color(C.armOuter), cAcc = new THREE.Color(C.accentStar), c = new THREE.Color();
|
||||
for (let i = 0; i < N; i++) {
|
||||
const r = Math.pow(Math.random(), 0.55) * R, arm = i % ARMS, spread = (0.6 + r * 0.09) * gauss();
|
||||
const a = armAngle(r, arm) + spread / Math.max(r, 3) + (Math.random() < 0.22 ? rnd(-Math.PI, Math.PI) : 0);
|
||||
pos.set([Math.cos(a) * r + gauss() * 0.8, gauss() * (2.2 * Math.exp(-r / 18) + 0.35), Math.sin(a) * r + gauss() * 0.8], i * 3);
|
||||
const t = r / R; c.copy(cCore).lerp(cIn, Math.min(1, t * 2.4)).lerp(cOut, Math.max(0, t * 1.5 - 0.5));
|
||||
if (Math.random() < 0.04) c.copy(cAcc);
|
||||
col.set([c.r, c.g, c.b], i * 3); sz[i] = Math.random() < 0.012 ? rnd(3, 5.5) : rnd(0.6, 2.0);
|
||||
}
|
||||
const g = new THREE.BufferGeometry();
|
||||
g.setAttribute('position', new THREE.BufferAttribute(pos, 3)); g.setAttribute('color', new THREE.BufferAttribute(col, 3)); g.setAttribute('size', new THREE.BufferAttribute(sz, 1));
|
||||
const m = new THREE.ShaderMaterial({ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, vertexColors: true,
|
||||
uniforms: { uPx: { value: renderer.getPixelRatio() }, uDim: { value: 1 }, uK: { value: 1 } },
|
||||
vertexShader: `attribute float size; varying vec3 vC; uniform float uPx; uniform float uK;
|
||||
void main(){ vC = color; vec4 mv = modelViewMatrix*vec4(position,1.0); gl_PointSize = clamp(size*uPx*uK*(150.0/-mv.z), 1.1, 7.0*uPx); gl_Position = projectionMatrix*mv; }`,
|
||||
fragmentShader: `varying vec3 vC; uniform float uDim; void main(){ vec2 p = gl_PointCoord-0.5; float d = length(p); if(d>0.5) discard;
|
||||
float a = smoothstep(0.5,0.0,d); gl_FragColor = vec4(vC*(0.55+a*1.1), a*0.85*uDim); }` });
|
||||
const pts = new THREE.Points(g, m); scene.add(pts); return pts;
|
||||
})();
|
||||
|
||||
// ============================================================ 星云(噪声云,沿旋臂;颜色只取 config 里那几组)
|
||||
const nebulaMat = (c1, c2, seed, alpha) => new THREE.ShaderMaterial({ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
|
||||
uniforms: { uT: { value: 0 }, uA: { value: new THREE.Color(c1) }, uB: { value: new THREE.Color(c2) }, uS: { value: seed }, uO: { value: alpha }, uDim: { value: 1 } },
|
||||
vertexShader: `varying vec2 vU; void main(){ vU = uv; gl_Position = projectionMatrix*modelViewMatrix*vec4(position,1.0); }`,
|
||||
fragmentShader: `uniform float uT; uniform vec3 uA; uniform vec3 uB; uniform float uS; uniform float uO; uniform float uDim; varying vec2 vU;
|
||||
float h(vec2 p){ return fract(sin(dot(p,vec2(127.1,311.7))+uS)*43758.5453); }
|
||||
float n(vec2 p){ vec2 i=floor(p), f=fract(p); f=f*f*(3.0-2.0*f); return mix(mix(h(i),h(i+vec2(1,0)),f.x),mix(h(i+vec2(0,1)),h(i+vec2(1,1)),f.x),f.y); }
|
||||
float fbm(vec2 p){ float v=0.0, a=0.5; for(int i=0;i<6;i++){ v+=a*n(p); p=p*2.03+vec2(1.7,9.2); a*=0.5; } return v; }
|
||||
void main(){ vec2 p = vU-0.5; float r = length(p)*2.0; if(r>1.0) discard;
|
||||
vec2 q = vU*3.0 + uS; float w = fbm(q + vec2(uT*0.02, -uT*0.015)); float d = fbm(q*1.7 + w*2.4 + vec2(-uT*0.01, uT*0.02));
|
||||
float shape = smoothstep(1.0, 0.15, r) * smoothstep(0.32, 0.85, d); float dust = smoothstep(0.55, 0.75, fbm(q*3.1 - w));
|
||||
gl_FragColor = vec4(mix(uA, uB, smoothstep(0.3, 0.9, d)) * (0.6 + d), shape * (1.0 - dust*0.6) * uO * uDim); }` });
|
||||
const nebulae = [];
|
||||
{ const n = MOB ? G.nebulae.mobile : G.nebulae.desktop;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const r = rnd(8, R * 0.95), a = armAngle(r, i % ARMS) + rnd(-0.35, 0.35), pal = C.nebula[i % C.nebula.length], s = rnd(14, 34) * (1.1 - r / R * 0.4);
|
||||
const m = new THREE.Mesh(new THREE.PlaneGeometry(s, s), nebulaMat(pal[0], pal[1], rnd(0, 100), rnd(0.32, 0.55)));
|
||||
m.position.set(Math.cos(a) * r, rnd(-1.5, 1.5), Math.sin(a) * r); m.rotation.set(-Math.PI / 2 + rnd(-0.25, 0.25), 0, rnd(0, Math.PI)); scene.add(m); nebulae.push(m);
|
||||
}
|
||||
const core = new THREE.Mesh(new THREE.PlaneGeometry(34, 34), nebulaMat(C.coreNebula[0], C.coreNebula[1], 7, 0.5)); core.rotation.x = -Math.PI / 2; scene.add(core); nebulae.push(core); }
|
||||
const glow = (color, size, op = 1) => { const c = document.createElement('canvas'); c.width = c.height = 128; const x = c.getContext('2d');
|
||||
const g = x.createRadialGradient(64, 64, 0, 64, 64, 64); g.addColorStop(0, 'rgba(255,255,255,1)'); g.addColorStop(0.22, color); g.addColorStop(1, 'rgba(0,0,0,0)'); x.fillStyle = g; x.fillRect(0, 0, 128, 128);
|
||||
const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(c), blending: THREE.AdditiveBlending, depthWrite: false, transparent: true, opacity: op })); s.scale.setScalar(size); return s; };
|
||||
scene.add(glow('rgba(255,215,150,.28)', 15, 0.7)); // 核心的柔光(收着点,之前太曝)
|
||||
{ const N = MOB ? 1100 : 2400, p = new Float32Array(N * 3); // 远处整球背景星
|
||||
for (let i = 0; i < N; i++) { const u = rnd(-1, 1), t = rnd(0, Math.PI * 2), s = Math.sqrt(1 - u * u), r = rnd(500, 900); p.set([Math.cos(t) * s * r, u * r, Math.sin(t) * s * r], i * 3); }
|
||||
const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.BufferAttribute(p, 3));
|
||||
scene.add(new THREE.Points(g, new THREE.PointsMaterial({ color: 0xC9D3FF, size: 1.2, sizeAttenuation: false, transparent: true, opacity: 0.6 }))); }
|
||||
|
||||
// ============================================================ 扇区:同心环 + 分隔虚线 + 扇区名
|
||||
const lineCol = new THREE.Color(C.line), guides = [];
|
||||
const addLine = (pts, dashed, op) => { const g = new THREE.BufferGeometry().setFromPoints(pts);
|
||||
const m = dashed ? new THREE.LineDashedMaterial({ color: lineCol, dashSize: 1.2, gapSize: 1.4, transparent: true, opacity: op, depthWrite: false })
|
||||
: new THREE.LineBasicMaterial({ color: lineCol, transparent: true, opacity: op, depthWrite: false });
|
||||
const l = new THREE.Line(g, m); if (dashed) l.computeLineDistances(); l.userData.op = op; scene.add(l); guides.push(l); return l; };
|
||||
for (const [rr, op] of [[16, 0.16], [32, 0.11], [48, 0.09], [R + 4, 0.16]]) { const pts = []; for (let k = 0; k <= 256; k++) { const a = k / 256 * Math.PI * 2; pts.push(new THREE.Vector3(Math.cos(a) * rr, 0, Math.sin(a) * rr)); } addLine(pts, false, op); }
|
||||
for (let k = 0; k < 6; k++) { const a = k / 6 * Math.PI * 2 + 0.3; addLine([new THREE.Vector3(Math.cos(a) * 16, 0, Math.sin(a) * 16), new THREE.Vector3(Math.cos(a) * (R + 4), 0, Math.sin(a) * (R + 4))], true, 0.12); }
|
||||
const sectorTags = G.sectors.map((name, k) => { const d = document.createElement('div'); d.className = 'sector'; d.textContent = name; labels.appendChild(d);
|
||||
const a = (k + 0.5) / 6 * Math.PI * 2 + 0.3; return { el: d, p: new THREE.Vector3(Math.cos(a) * (R + 9), 0, Math.sin(a) * (R + 9)) }; });
|
||||
|
||||
// ============================================================ 星系(每条世界线一颗卡通星球 + 卫星)
|
||||
const systems = [], planets = [];
|
||||
const lit = CFG.UNIVERSES.filter(u => !u.empty), empty = CFG.UNIVERSES.filter(u => u.empty);
|
||||
// 位置和补给线由 layout.js 算(写死的 / 空槽按编号 / 新点亮的自动排位,规则见那个文件开头)
|
||||
const LAY = layoutSystems(CFG), byNo = new Map();
|
||||
LAY.forEach((ly, i) => {
|
||||
const u = ly.u, L = ly.look;
|
||||
const g = new THREE.Group(); g.position.set(ly.x, 0, ly.z); scene.add(g);
|
||||
const p = makePlanet(THREE, Object.assign({ seed: i * 7.3 + 1 }, L)); g.add(p.group); planets.push(p);
|
||||
const moons = (L.moons || []).map((m, k) => { const piv = new THREE.Group(); piv.rotation.x = 0.35 - k * 0.2; piv.rotation.y = k * 2.1; g.add(piv);
|
||||
const mp = makePlanet(THREE, Object.assign({ seed: i * 13 + k * 3.1, spin: 0.4 }, m)); mp.group.position.x = m.d; piv.add(mp.group); planets.push(mp); return { piv, speed: Math.abs(m.speed || 0.3) }; }); // 卫星一律同一个方向转(和星系自转同向)
|
||||
const tag = document.createElement('button'); tag.type = 'button'; tag.className = 'tag' + (u.empty ? ' empty' : ''); tag.style.setProperty('--c', L.accent || C.ui);
|
||||
tag.innerHTML = '<span class="t"><b>' + esc(u.empty ? '空槽' : u.name) + '</b><em>' + esc(u.no) + (u.empty ? ' · 未点亮' : ' · ' + esc(u.kind)) + '</em></span>';
|
||||
labels.appendChild(tag);
|
||||
const s = { u, L, g, planet: p, moons, tag, parent: ly.parent }; p.body.userData.s = s; systems.push(s); byNo.set(u.no, s);
|
||||
tag.addEventListener('click', () => fly(s));
|
||||
});
|
||||
// 补给线:从「上一站」(核心或更靠里的那颗星)连过来,虚线往外流;空槽的线很淡
|
||||
const supply = [];
|
||||
for (const s of systems) { if (s.u.no === '0000' || !s.g.position.lengthSq()) continue;
|
||||
const a = s.parent && byNo.has(s.parent) ? byNo.get(s.parent).g.position.clone() : new THREE.Vector3();
|
||||
const b = s.g.position.clone(), mid = a.clone().add(b).multiplyScalar(0.5); mid.y += a.distanceTo(b) * 0.12;
|
||||
const l = new THREE.Line(new THREE.BufferGeometry().setFromPoints(new THREE.QuadraticBezierCurve3(a, mid, b).getPoints(80)),
|
||||
new THREE.LineDashedMaterial({ color: s.u.empty ? lineCol : new THREE.Color(C.ui), dashSize: 0.9, gapSize: 0.8, transparent: true, opacity: s.u.empty ? 0.14 : 0.42, depthWrite: false }));
|
||||
l.computeLineDistances(); l.userData.op = l.material.opacity; scene.add(l); supply.push(l); }
|
||||
// 散落的无名星球(只是让星系看起来有人住;不进档案、不能点)
|
||||
// 位置挑过:离核心、离每个星系(含它的卫星轨道)、彼此之间都留足距离,不会叠在一起
|
||||
{ const n = MOB ? G.decorPlanets.mobile : G.decorPlanets.desktop, styles = ['gas', 'rock', 'gas', 'rock', 'ice'];
|
||||
const pals = [['#F2D7A6', '#D99A6C', '#8E6BBF', '#FFF2D6'], ['#BFD0FF', '#7C8FD6', '#4A5BA8', '#FFFFFF'], ['#9FE3D6', '#4FB8A8', '#2F6F8C', '#E6FFF8'], ['#D6C2FF', '#9B8BFF', '#5B3FB8', '#FFFFFF']];
|
||||
const taken = systems.map(s => ({ p: s.g.position, r: s.L.r * 3 + Math.max(0, ...(s.L.moons || []).map(m => m.d + m.r)) + 3 }));
|
||||
taken.push({ p: new THREE.Vector3(), r: 14 });
|
||||
let made = 0;
|
||||
for (let tries = 0; made < n && tries < n * 60; tries++) {
|
||||
const r = rnd(16, R * 0.96), a = armAngle(r, Math.floor(rnd(0, ARMS))) + rnd(-0.45, 0.45), size = rnd(0.35, 0.8);
|
||||
const pos = new THREE.Vector3(Math.cos(a) * r, rnd(-0.8, 0.8), Math.sin(a) * r);
|
||||
if (taken.some(o => o.p.distanceTo(pos) < o.r + size + 2.5)) continue;
|
||||
const p = makePlanet(THREE, { style: styles[made % styles.length], r: size, colors: pals[made % pals.length], seed: made * 5.1, outline: '#141833', spin: rnd(0.05, 0.2) });
|
||||
p.group.position.copy(pos); scene.add(p.group); planets.push(p); taken.push({ p: pos, r: size + 2 }); made++;
|
||||
} }
|
||||
el.counts && el.counts(CFG.UNIVERSES.length, lit.length, empty.length);
|
||||
|
||||
// ============================================================ 相机 + 交互(拖动、滚轮、双指缩放)
|
||||
const HOME = () => ({ az: 0.7, el: isMob() ? 1.08 : 0.62, dist: isMob() ? 155 : 112 });
|
||||
// ============================================================ 运镜库(全部按时间走,和帧率无关)
|
||||
// 每个运镜 = 时长 + 一条路径函数 path(from, to, k):k 是 0→1 的进度,往 view 里写这一刻的相机状态。
|
||||
// 相机状态:az 方位角 / el 仰角 / dist 距离 / tx,ty,tz 看向哪 / fov 视角 / roll 滚转。
|
||||
// 加一种新运镜:往 MOVES 里加一项,然后在 config.js 的 LOOKS[编号].enter 里写它的名字。
|
||||
const FOV = 42;
|
||||
const lerp = (a, b, k) => a + (b - a) * k, clamp01 = k => Math.max(0, Math.min(1, k));
|
||||
const E = {
|
||||
io: k => k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2, // 缓入缓出
|
||||
out: k => 1 - Math.pow(1 - k, 3), // 先快后慢
|
||||
in: k => k * k * k,
|
||||
io5: k => k < 0.5 ? 16 * k ** 5 : 1 - Math.pow(-2 * k + 2, 5) / 2, // 更「沉」的缓入缓出
|
||||
expo: k => k === 0 ? 0 : k === 1 ? 1 : k < 0.5 ? Math.pow(2, 20 * k - 10) / 2 : (2 - Math.pow(2, -20 * k + 10)) / 2,
|
||||
};
|
||||
const KEYS = ['az', 'el', 'dist', 'tx', 'ty', 'tz', 'fov', 'roll'];
|
||||
const mix = (f, to, k, keys = KEYS) => { for (const key of keys) view[key] = lerp(f[key], to[key], k); };
|
||||
const MOVES = {
|
||||
// 绕行:边飞边绕过去,中途抬高拉远一点(原来那种)
|
||||
orbit: { dur: 1700, path(f, to, k) { const e = E.io(k); mix(f, to, e); view.el += Math.sin(Math.PI * e) * 0.28; view.dist *= 1 + Math.sin(Math.PI * e) * 0.22; } },
|
||||
// 推进:镜头先转过去对准(前 40%),再笔直推进去(不绕圈)
|
||||
push: { dur: 1600, path(f, to, k) { const look = E.out(clamp01(k / 0.45)), go = E.io5(k);
|
||||
mix(f, to, look, ['tx', 'ty', 'tz', 'az', 'el']); mix(f, to, go, ['dist']); view.fov = FOV; view.roll = 0; } },
|
||||
// 放大:先用「长焦」把它拉近(视角收窄),再一边推进一边把视角放回来 —— 有点希区柯克变焦的味道
|
||||
zoom: { dur: 2000, path(f, to, k) { const k1 = clamp01(k / 0.45), k2 = clamp01((k - 0.45) / 0.55);
|
||||
mix(f, to, E.out(clamp01(k / 0.35)), ['tx', 'ty', 'tz']); mix(f, to, E.io(k), ['az', 'el']);
|
||||
view.fov = k < 0.45 ? lerp(f.fov, 14, E.out(k1)) : lerp(14, to.fov, E.io(k2));
|
||||
view.dist = lerp(f.dist, to.dist, E.io(k2)); view.roll = 0; } },
|
||||
// 升空俯冲:先拉高到几乎俯视,再从上面扎下去
|
||||
rise: { dur: 2100, path(f, to, k) { const e = E.io(k); mix(f, to, e);
|
||||
const up = Math.sin(Math.PI * clamp01(k * 1.15)); view.el = lerp(view.el, 1.35, up * 0.85); view.dist *= 1 + up * 0.55; } },
|
||||
// 跃迁:慢起步、中段猛冲、末段刹住;冲的时候视角张开、镜头轻轻一滚
|
||||
warp: { dur: 1800, path(f, to, k) { const e = E.expo(k), s = Math.sin(Math.PI * k);
|
||||
mix(f, to, e); view.fov = to.fov + s * s * 34; view.roll = s * 0.18 * (f.az > to.az ? 1 : -1); } },
|
||||
// 拉远:回星系图用 —— 先往后退,再抬头看全景
|
||||
pull: { dur: 1700, path(f, to, k) { mix(f, to, E.io5(k), ['dist']); mix(f, to, E.out(clamp01((k - 0.15) / 0.85)), ['tx', 'ty', 'tz', 'el', 'az']);
|
||||
view.fov = lerp(f.fov, to.fov, E.io(k)); view.roll = lerp(f.roll, 0, E.io(k)); } },
|
||||
// 开场 A · 盘旋落下:从高空、更远处绕半圈落到正常视角
|
||||
introSweep: { dur: 3600, path(f, to, k) { mix(f, to, E.io(k)); } },
|
||||
// 开场 B · 垂直坠入:从正上方很远的地方直着往下落,最后才抬起镜头、星系转正
|
||||
introDive: { dur: 3400, path(f, to, k) { const d = E.io5(k); view.dist = lerp(f.dist, to.dist, d); view.el = lerp(f.el, to.el, E.in(clamp01((k - 0.35) / 0.65)));
|
||||
view.az = lerp(f.az, to.az, E.io(k)); view.fov = lerp(f.fov, to.fov, E.out(k)); view.tx = view.ty = view.tz = 0; view.roll = 0; } },
|
||||
};
|
||||
const h0 = HOME();
|
||||
const introKind = (G.intro === 'dive' || G.intro === 'sweep') ? G.intro : (Math.random() < 0.5 ? 'dive' : 'sweep');
|
||||
const START = introKind === 'dive' ? { az: h0.az + 0.6, el: 1.52, dist: h0.dist * 3.2, fov: 30 } : { az: h0.az - 1.5, el: 1.42, dist: h0.dist * 2.4, fov: FOV };
|
||||
const view = Object.assign({ tx: 0, ty: 0, tz: 0, roll: 0, fov: FOV }, reduce ? h0 : START);
|
||||
const want = Object.assign({ fov: FOV, roll: 0 }, h0);
|
||||
let anim = null, intro = !reduce;
|
||||
// 用户中途拖动 / 缩放:运镜立刻停在原地交还控制权,但没出来的档案卡要马上补上(不然卡就丢了)
|
||||
function cancelAnim() { if (!anim) return; const f = anim.onArrive; anim = null; f && f(); }
|
||||
// to 里没写的 fov / roll 默认回到正常;az 走最近的那一边转
|
||||
function animate(to, move = 'orbit', onArrive = null, arriveAt = 0.8) {
|
||||
to = Object.assign({ fov: FOV, roll: 0 }, to);
|
||||
if (reduce) { Object.assign(view, to); Object.assign(want, to); anim = null; onArrive && onArrive(); return; }
|
||||
const daz = ((to.az - view.az) % (Math.PI * 2) + Math.PI * 3) % (Math.PI * 2) - Math.PI;
|
||||
const M = MOVES[move] || MOVES.orbit;
|
||||
anim = { t0: performance.now(), M, from: Object.assign({}, view), to: Object.assign({}, to, { az: view.az + daz }), onArrive, arriveAt };
|
||||
}
|
||||
let focus = null, hover = null;
|
||||
function fit() { const w = stage.clientWidth, h = stage.clientHeight; renderer.setSize(w, h, false); camera.aspect = w / h; camera.updateProjectionMatrix(); }
|
||||
addEventListener('resize', fit); fit();
|
||||
const ptrs = new Map(); let drag = null, pinch = null;
|
||||
canvas.addEventListener('pointerdown', e => { canvas.setPointerCapture(e.pointerId); ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
||||
if (ptrs.size === 2) { const [a, b] = [...ptrs.values()]; pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), dist: want.dist }; drag = null; }
|
||||
else drag = { x: e.clientX, y: e.clientY, az: want.az, el: want.el, moved: false }; });
|
||||
canvas.addEventListener('pointermove', e => {
|
||||
if (ptrs.has(e.pointerId)) ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
||||
if (pinch && ptrs.size === 2) { const [a, b] = [...ptrs.values()]; zoomTo(pinch.dist * pinch.d / Math.max(20, Math.hypot(a.x - b.x, a.y - b.y))); return; }
|
||||
if (drag) { const dx = e.clientX - drag.x, dy = e.clientY - drag.y; if (Math.abs(dx) + Math.abs(dy) > 6) drag.moved = true;
|
||||
if (drag.moved) { if (anim) { cancelAnim(); Object.assign(want, view); drag.az = view.az + dx * 0.005; drag.el = view.el - dy * 0.004; } /* 从镜头现在的位置接着拖,不跳 */ want.az = drag.az - dx * 0.005; want.el = THREE.MathUtils.clamp(drag.el + dy * 0.004, 0.08, 1.45); } return; }
|
||||
if (e.pointerType === 'mouse') { hover = pick(e); canvas.style.cursor = hover ? 'pointer' : 'grab'; } });
|
||||
const end = e => { ptrs.delete(e.pointerId); if (ptrs.size < 2) pinch = null;
|
||||
const d = drag; drag = null; if (d && !d.moved && e.type === 'pointerup') { const s = pick(e); if (s) fly(s); else if (focus) home(); } };
|
||||
canvas.addEventListener('pointerup', end); canvas.addEventListener('pointercancel', end);
|
||||
const zoomTo = d => { if (anim) { cancelAnim(); Object.assign(want, view); } want.dist = THREE.MathUtils.clamp(d, focus ? focus.L.r * 2.6 : 32, focus ? focus.L.r * 16 : 230); };
|
||||
canvas.addEventListener('wheel', e => {
|
||||
if (el.wheelZoom && !el.wheelZoom() && !e.ctrlKey) return; // 嵌在页面里:普通滚轮留给页面滚动
|
||||
e.preventDefault(); zoomTo(want.dist * (1 + Math.sign(e.deltaY) * 0.1)); }, { passive: false });
|
||||
addEventListener('keydown', e => { if (e.key === 'Escape') home(); if (focus && e.key === 'ArrowRight') step(1); if (focus && e.key === 'ArrowLeft') step(-1); });
|
||||
back && (back.onclick = () => home());
|
||||
const ray = new THREE.Raycaster(), ptr = new THREE.Vector2(), tmp = new THREE.Vector3();
|
||||
function pick(e) {
|
||||
const r = canvas.getBoundingClientRect(); ptr.set((e.clientX - r.left) / r.width * 2 - 1, -(e.clientY - r.top) / r.height * 2 + 1);
|
||||
ray.setFromCamera(ptr, camera); const hit = ray.intersectObjects(systems.map(s => s.planet.body), false)[0]; if (hit) return hit.object.userData.s;
|
||||
let best = null, bd = isMob() ? 34 : 28;
|
||||
for (const s of systems) { s.g.getWorldPosition(tmp).project(camera); const d = Math.hypot((tmp.x - ptr.x) * r.width / 2, (tmp.y - ptr.y) * r.height / 2); if (d < bd && tmp.z < 1) { bd = d; best = s; } }
|
||||
return best;
|
||||
}
|
||||
function card(s) { const u = s.u, nav = '<div class="nav"><button class="btn" type="button" data-s="-1">上一个</button><button class="btn" type="button" data-s="1">下一个</button></div>';
|
||||
if (u.empty) return '<div class="card" style="--pc:' + esc(s.L.accent) + '"><div class="k">UNIVERSE ' + esc(u.no) + ' · 未点亮</div><h2>空槽</h2><div class="tg">这条世界线还没写出来,星系还没被点亮。</div><div class="acts">' + nav + '<button class="btn" type="button" data-home>回到星系图</button></div></div>';
|
||||
return '<div class="card" style="--pc:' + esc(s.L.accent) + '"><div class="k">UNIVERSE ' + esc(u.no) + ' · ' + esc(u.kind) + ' · 已点亮</div><h2>' + esc(u.name) + '</h2><div class="tg">' + esc(u.tag) + '</div>' +
|
||||
'<p class="ds">' + esc(u.desc) + '</p><div class="tags">' + (u.tags || []).map(t => '<span>' + esc(t) + '</span>').join('') + '</div><div class="acts">' + nav + '<button class="btn pri" type="button" data-home>回到星系图</button></div></div>'; }
|
||||
panel && panel.addEventListener('click', e => { const b = e.target.closest('[data-s]'); if (b) step(+b.dataset.s); if (e.target.closest('[data-home]')) home(); });
|
||||
function step(d) { const i = systems.indexOf(focus); fly(systems[(i + d + systems.length) % systems.length]); }
|
||||
// 飞过去:先把旧档案卡收起来 → 镜头按这颗星的「入场运镜」飞 → 快到(80%)的时候档案卡才滑出来,和星球落定同步
|
||||
const ENTER_CYCLE = ['push', 'zoom', 'rise', 'warp', 'orbit'];
|
||||
function fly(s) { const was = focus; focus = s; intro = false; stage.classList.add('ready'); stage.classList.add('focus');
|
||||
panel && panel.classList.remove('on'); el.onFocus && el.onFocus(s.u, 'start');
|
||||
const p = s.g.position, dist = s.L.r * (isMob() ? 9 : 5.6) + (s.moons.length ? s.L.r * 1.5 : 0);
|
||||
const i = systems.indexOf(s), move = s.L.enter || ENTER_CYCLE[i % ENTER_CYCLE.length];
|
||||
// 推进 / 放大:沿着现在的视线方向过去(不绕);其它运镜:落到「从星系中心那一侧看过去」的角度,背景是星系盘
|
||||
const az = (move === 'push' || move === 'zoom') ? view.az + 0.12 : Math.atan2(p.x, p.z) + 0.35;
|
||||
animate({ az, el: 0.24, dist, tx: p.x, ty: p.y, tz: p.z }, was && was !== s && move !== 'warp' ? 'orbit' : move, () => {
|
||||
if (focus !== s) return;
|
||||
panel && (panel.innerHTML = card(s), panel.classList.add('on')); el.onFocus && el.onFocus(s.u, 'arrive'); }, 0.78); }
|
||||
function home() { if (!focus) return; focus = null; panel && panel.classList.remove('on'); stage.classList.remove('focus'); el.onFocus && el.onFocus(null, 'start');
|
||||
animate(Object.assign(HOME(), { tx: 0, ty: 0, tz: 0, az: view.az - 0.3 }), 'pull'); }
|
||||
|
||||
// ============================================================ 循环
|
||||
const clock = new THREE.Clock(), tgt = new THREE.Vector3();
|
||||
let hudBottom = 0; const measureHud = () => { hudBottom = hud ? hud.getBoundingClientRect().bottom - stage.getBoundingClientRect().top : 0; }; measureHud(); addEventListener('resize', measureHud);
|
||||
let visible = true, started = false, tIntro = 0;
|
||||
if ('IntersectionObserver' in window) new IntersectionObserver(es => { visible = es[0].isIntersecting; }, { threshold: 0.05 }).observe(stage);
|
||||
function loop() {
|
||||
requestAnimationFrame(loop);
|
||||
if (!visible) { clock.getDelta(); return; } // 滚出视口:不渲染,省电
|
||||
if (!started) { started = true; tIntro = clock.elapsedTime; if (intro) animate(Object.assign({}, h0, { tx: 0, ty: 0, tz: 0 }), introKind === 'dive' ? 'introDive' : 'introSweep'); else stage.classList.add('ready'); }
|
||||
const dt = Math.min(clock.getDelta(), 0.05), t = clock.elapsedTime, mob = isMob();
|
||||
if (!reduce) { galaxy.rotation.y += dt * 0.004; for (const n of nebulae) n.material.uniforms.uT.value = t; }
|
||||
for (const l of supply) l.material.dashOffset -= dt * 2;
|
||||
for (const p of planets) p.update(reduce ? 0 : dt, t, LIGHT);
|
||||
// 星系在总览里放大一点(不然在手机上只是一个小点),飞近时恢复真实大小
|
||||
const sysK = focus ? 1 : (mob ? 1.9 : 1.35);
|
||||
for (const s of systems) { for (const m of s.moons) m.piv.rotation.y += (reduce ? 0 : dt) * m.speed;
|
||||
const sc = s.g.scale.x + (sysK - s.g.scale.x) * (reduce ? 1 : Math.min(1, dt * 3)); s.g.scale.setScalar(sc); }
|
||||
// 开场:星系从暗处亮起来(0 → 1,大约 2.4 秒);飞近一颗星时:星云、粒子、扇区线退后一点,别抢主角
|
||||
const introK = intro ? Math.min(1, (t - tIntro) / 2.4) : 1;
|
||||
const dimT = (focus ? 0.45 : 1) * introK;
|
||||
galaxy.material.uniforms.uDim.value += (dimT - galaxy.material.uniforms.uDim.value) * (intro ? 1 : Math.min(1, dt * 3));
|
||||
galaxy.material.uniforms.uK.value = 112 / HOME().dist;
|
||||
for (const n of nebulae) n.material.uniforms.uDim.value = galaxy.material.uniforms.uDim.value;
|
||||
for (const l of guides.concat(supply)) l.material.opacity += (l.userData.op * (focus ? 0.25 : 1) * introK - l.material.opacity) * Math.min(1, dt * 3);
|
||||
// 相机:有补间就按时间走补间(不受帧率影响,一条连贯的弧线);没有就柔和地跟着拖动 / 缩放
|
||||
if (anim) {
|
||||
const a = anim, kk = Math.min(1, (performance.now() - a.t0) / a.M.dur);
|
||||
a.M.path(a.from, a.to, kk);
|
||||
if (a.onArrive && kk >= a.arriveAt) { const f = a.onArrive; a.onArrive = null; f(); } // 档案卡和星球落定同步出现
|
||||
if (kk >= 1) { Object.assign(view, a.to); Object.assign(want, a.to); if (anim === a) anim = null; if (!focus) stage.classList.add('ready'); }
|
||||
} else {
|
||||
view.fov += (FOV - view.fov) * Math.min(1, dt * 4); view.roll += (0 - view.roll) * Math.min(1, dt * 4);
|
||||
if (focus) focus.g.getWorldPosition(tgt); else tgt.set(0, 0, 0);
|
||||
const k = 1 - Math.exp(-dt * 6);
|
||||
view.tx += (tgt.x - view.tx) * k; view.ty += (tgt.y - view.ty) * k; view.tz += (tgt.z - view.tz) * k;
|
||||
for (const key of ['az', 'el', 'dist']) view[key] += (want[key] - view[key]) * k;
|
||||
if (!drag && !pinch && !focus && !reduce) want.az += dt * 0.02;
|
||||
}
|
||||
camera.position.set(view.tx + Math.sin(view.az) * Math.cos(view.el) * view.dist, view.ty + Math.sin(view.el) * view.dist, view.tz + Math.cos(view.az) * Math.cos(view.el) * view.dist);
|
||||
camera.lookAt(view.tx, view.ty, view.tz);
|
||||
if (view.roll) camera.rotateZ(view.roll);
|
||||
if (Math.abs(camera.fov - view.fov) > 0.01) { camera.fov = view.fov; camera.updateProjectionMatrix(); }
|
||||
// 选中时把星球挪开,给档案卡让位:桌面往左挪,手机往上挪(档案卡在下半屏)
|
||||
const w = stage.clientWidth, h = stage.clientHeight;
|
||||
const lay = el.layout ? el.layout() : { x: mob ? 0 : 0.16, y: mob ? 0.22 : 0 };
|
||||
if (focus && (lay.x || lay.y)) camera.setViewOffset(w, h, w * lay.x, h * lay.y, w, h); else camera.clearViewOffset();
|
||||
// 名牌:跟着星系走;贴边夹住不出屏;手机上压到 HUD 下面的藏起来
|
||||
for (const s of systems) { s.g.getWorldPosition(tmp); tmp.project(camera);
|
||||
let x = (tmp.x + 1) / 2 * w + 10, y = (1 - tmp.y) / 2 * h - 12;
|
||||
const tw = s.tag.offsetWidth || 90; x = Math.min(Math.max(x, 6), w - tw - 6);
|
||||
const vis = tmp.z < 1 && Math.abs(tmp.x) < 1.05 && Math.abs(tmp.y) < 1.05 && !(mob && y < hudBottom + 4) && focus !== s;
|
||||
s.tag.style.transform = 'translate(' + x.toFixed(1) + 'px,' + y.toFixed(1) + 'px)';
|
||||
s.tag.classList.toggle('hot', s === hover); s.tag.classList.toggle('dim', !!focus); s.tag.style.visibility = vis ? '' : 'hidden'; }
|
||||
for (const st of sectorTags) { tmp.copy(st.p).project(camera); st.el.style.transform = 'translate(' + ((tmp.x + 1) / 2 * w) + 'px,' + ((1 - tmp.y) / 2 * h) + 'px) translate(-50%,-50%)'; st.el.style.opacity = (tmp.z < 1 && !focus) ? '' : 0; }
|
||||
renderer.render(scene, camera);
|
||||
if (firstFrame) { firstFrame = false; el.onReady && el.onReady(); } // 第一帧画好了,外面的「载入中」再淡出
|
||||
}
|
||||
// 开场:第一帧画出来再开始(外面的「载入中」此时淡出,镜头接着就开始动,中间不留空白)
|
||||
let firstFrame = true;
|
||||
loop();
|
||||
return { resize: fit, fly: no => { const s = systems.find(x => x.u.no === no); if (s) fly(s); }, home };
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/* 金钻宇宙 · 开场「星门」(2026-10-06 重做,替换原来的「星图载入中…」一行字)
|
||||
---------------------------------------------------------------------------
|
||||
three.js 在下载 / 星系在生成的这段时间,星图窗里是一道星门:
|
||||
· 中间像素钻石,外面三圈光环反向慢转;底下一排格子 = 全部世界线(写好的 + 空槽);
|
||||
· 一道光沿着格子来回扫,写好的世界线按编号一格一格点亮成它自己的颜色(空槽保持虚线);
|
||||
· 星系第一帧画好(galaxy.js 的 onReady)→ JZGate.open():光环向外炸开、格子散开、星门淡出,
|
||||
正好接上 galaxy.js 自己的镜头俯冲入场;
|
||||
· 打不开 3D(老设备 / 没 WebGL)→ JZGate.fail(说明):星门停住,换成说明文字,下面的档案照样能看;
|
||||
· 系统要求「减少动效」:不扫、不炸,直接淡出。 */
|
||||
(function () {
|
||||
'use strict';
|
||||
var gate = document.getElementById('uGate'); if (!gate) return;
|
||||
var reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
var msg = document.getElementById('uGateMsg'), slots = document.getElementById('uGateSlots');
|
||||
var uv = window.JZP && window.JZP.universes ? window.JZP.universes() : { lit: [], empty: [], looks: {} };
|
||||
var all = uv.lit.concat(uv.empty).sort(function (a, b) { return a.no < b.no ? -1 : 1; });
|
||||
slots.innerHTML = all.map(function (u, i) {
|
||||
var lk = uv.looks[u.no] || {}, c = u.empty ? '' : (lk.accent || u.tone || '#9A6BE0');
|
||||
var e = window.JZP ? window.JZP.esc : function (x) { return String(x).replace(/[&<>"']/g, ''); };
|
||||
return '<i class="' + (u.empty ? 'e' : 'l') + '" style="--i:' + i + (c ? ';--c:' + e(c) : '') + '" title="' + e(u.no) + '"></i>';
|
||||
}).join('');
|
||||
gate.style.setProperty('--n', all.length);
|
||||
gate.classList.add('scan');
|
||||
var t0 = performance.now(), opened = false;
|
||||
/* 下载慢的时候换几句话,别让人以为卡死了 */
|
||||
var lines = ['正在打开星门…', '正在装载星系引擎…', '正在排布 ' + all.length + ' 条世界线…', '马上就好…'];
|
||||
var li = 0, lt = setInterval(function () { if (!opened && li < lines.length - 1) msg.textContent = lines[++li]; }, 1400);
|
||||
window.JZGate = {
|
||||
open: function () {
|
||||
if (opened) return; opened = true; clearInterval(lt);
|
||||
/* 至少让扫描走完一轮(约 1.1 秒),太快打开反而像闪了一下 */
|
||||
var wait = reduce ? 0 : Math.max(0, 1100 - (performance.now() - t0));
|
||||
setTimeout(function () {
|
||||
msg.textContent = '已点亮 ' + uv.lit.length + ' 条世界线';
|
||||
gate.classList.add('open');
|
||||
setTimeout(function () { gate.remove(); }, reduce ? 300 : 1300);
|
||||
}, wait);
|
||||
},
|
||||
fail: function (text) {
|
||||
opened = true; clearInterval(lt);
|
||||
gate.classList.remove('scan'); gate.classList.add('failed'); msg.textContent = text;
|
||||
}
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,150 @@
|
||||
/* =============================================================================
|
||||
* 金钻宇宙 · 星系图排布(layout.js)—— 纯计算,不依赖 three.js,可以单独测试
|
||||
* -----------------------------------------------------------------------------
|
||||
* 决定每条世界线的星球放在哪、补给线从哪连过来。规则(2026-10-05):
|
||||
*
|
||||
* 1. 在 LOOKS 里写了 orbit: [离核心多远, 第几条旋臂] 的 —— 就放在那儿,补给线从核心连过去。(现在的 0000–0004)
|
||||
* 2. 空槽(empty: true)—— 按**编号**放在外圈的固定槽位(从 GALAXY.firstSlot 号起,轮流分到各条旋臂)。
|
||||
* 只看自己的编号,点亮其中一个,别的空槽不会挪。空槽的淡虚线接到离它最近、又不穿过别的星的那颗已点亮的星
|
||||
* (没有就接核心)—— 这条淡线会随着新点亮的星「找到更近的落脚点」,空槽本身不动。
|
||||
* 3. 已点亮、但没写 orbit 的(内容后台里「点亮一条」新加的)—— **自动排位**:
|
||||
* · 在中圈的旋臂上挑一个位置:跟核心、已有星系(连同它的卫星轨道)都留足距离,尽量让各条旋臂均匀;
|
||||
* · 补给线连到「比它更靠近核心、又离它最近」的那颗星(没有合适的就连核心),
|
||||
* 而且这条线不能从别的星系中间穿过;
|
||||
* · 按编号从小到大一颗一颗排,每一颗只看排在它前面的 —— 所以**新加一条,已有的星和线都不动**。
|
||||
* · 中圈排满(二十来条以后)才会去外圈空槽之间找位置;那一档要避开空槽,所以改「空槽数」可能让这几颗挪一挪。
|
||||
*
|
||||
* 用法:import { layoutSystems } from './layout.js';
|
||||
* const L = layoutSystems(window.JZ_UNIVERSE) → [{ u, look, x, z, kind, parent }]
|
||||
* kind = 'pinned' | 'slot' | 'auto';parent = 补给线起点的编号,null = 核心
|
||||
* ============================================================================= */
|
||||
|
||||
export const armAngle = (r, arm, G) => arm * Math.PI * 2 / G.arms + r * G.twist;
|
||||
|
||||
/** 一个星系「占的地方」半径:星球本身 + 最外面那颗卫星的轨道 */
|
||||
export function footprint(look) {
|
||||
const moons = (look.moons || []).map(m => (m.d || 0) + (m.r || 0));
|
||||
return (look.r || 1) * 2.2 + (moons.length ? Math.max(...moons) : 0);
|
||||
}
|
||||
|
||||
const dist = (a, b) => { const dx = a.x - b.x, dz = a.z - b.z; return Math.sqrt(dx * dx + dz * dz); }; // 别用 Math.hypot:V8 里慢好几倍
|
||||
/** 点到线段的距离(补给线按直线近似;实际画的是稍微拱起来的弧,水平投影还是这条线) */
|
||||
function segDist(p, a, b) {
|
||||
const vx = b.x - a.x, vz = b.z - a.z, L2 = vx * vx + vz * vz || 1;
|
||||
const t = Math.max(0, Math.min(1, ((p.x - a.x) * vx + (p.z - a.z) * vz) / L2));
|
||||
const dx = p.x - (a.x + vx * t), dz = p.z - (a.z + vz * t);
|
||||
return Math.sqrt(dx * dx + dz * dz);
|
||||
}
|
||||
|
||||
export function layoutSystems(CFG) {
|
||||
const G = CFG.GALAXY, R = G.radius, ARMS = G.arms, first = G.firstSlot ?? 5;
|
||||
const LOOKS = CFG.LOOKS || {};
|
||||
const lookOf = u => Object.assign({}, CFG.EMPTY_LOOK, LOOKS[u.no] || {});
|
||||
const num = u => parseInt(u.no, 10) || 0;
|
||||
const list = [...CFG.UNIVERSES].sort((a, b) => num(a) - num(b));
|
||||
const CORE = { x: 0, z: 0, fp: 12, no: null };
|
||||
const out = new Map();
|
||||
const put = (u, look, r, a, kind, parent) => {
|
||||
const s = { u, look, x: Math.cos(a) * r, z: Math.sin(a) * r, r, kind, parent, fp: footprint(look), no: u.no };
|
||||
out.set(u.no, s); return s;
|
||||
};
|
||||
|
||||
// 1) 写死位置的
|
||||
for (const u of list) {
|
||||
const o = (LOOKS[u.no] || {}).orbit;
|
||||
if (!o) continue;
|
||||
const [r, arm] = o;
|
||||
put(u, lookOf(u), r, r ? armAngle(r, arm, G) : 0, 'pinned', null);
|
||||
}
|
||||
// 2) 空槽:按编号固定在外圈
|
||||
for (const u of list) {
|
||||
if (!u.empty || out.has(u.no)) continue;
|
||||
const e = Math.max(0, num(u) - first);
|
||||
const r = R * (0.8 + 0.12 * (e % 2));
|
||||
put(u, lookOf(u), r, armAngle(r, e % ARMS, G) + 0.32 * Math.floor(e / ARMS), 'slot', null);
|
||||
}
|
||||
// 3) 自动排位:只避开「核心 + 写死的 + 排在前面的自动星」(空槽在外圈,自动星只用中圈,互不影响)
|
||||
const placed = [...out.values()].filter(s => s.kind === 'pinned' && s.r > 0);
|
||||
const armCount = new Array(ARMS).fill(0);
|
||||
for (const s of placed) {
|
||||
const a = Math.atan2(s.z, s.x);
|
||||
let best = 0, bd = Infinity;
|
||||
for (let k = 0; k < ARMS; k++) { const d = Math.abs(Math.atan2(Math.sin(a - armAngle(s.r, k, G)), Math.cos(a - armAngle(s.r, k, G)))); if (d < bd) { bd = d; best = k; } }
|
||||
armCount[best]++;
|
||||
}
|
||||
const rMin = 16, rMax = R * 0.68, mid = R * 0.5; // 自动星只用中圈:外圈(0.8R 往外)留给空槽,两圈之间留出空隙
|
||||
|
||||
// 给一个候选位置挑补给线起点:比它更靠近核心的星(或核心),线不能穿过别的星系
|
||||
function parentFor(c, others) {
|
||||
const cands = [CORE, ...others.filter(o => o.r < c.r - 4)];
|
||||
let best = null;
|
||||
for (const p of cands) {
|
||||
const len = dist(p, c);
|
||||
let clear = Infinity;
|
||||
for (const o of others) { if (o === p) continue; clear = Math.min(clear, segDist(o, p, c) - o.fp); }
|
||||
if (clear < 1.5) continue;
|
||||
// 同样不穿的情况下挑短的;连核心稍微加一点「距离」,让新星更愿意接在附近的星上,连线成网而不是全扎向中心
|
||||
const score = len + (p === CORE ? 6 : 0);
|
||||
if (!best || score < best.score) best = { p, score, clear };
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// 候选位置:按「够不够宽敞」先粗筛打分(便宜),再只给排在前面的几十个检查补给线会不会穿星(贵)—— 40 条世界线也很快。
|
||||
// 中圈排满了就分档放宽:到外圈空槽之间找位置(这时也要避开空槽)、间距要求逐步降低;最后兜底也保证不叠在别人身上。
|
||||
const slots = [...out.values()].filter(s => s.kind === 'slot');
|
||||
const PASSES = [
|
||||
{ rMax: R * 0.68, need: 4, offs: [-0.2, -0.1, 0, 0.1, 0.2], slots: false },
|
||||
{ rMax: R * 0.96, need: 3, offs: [-0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3], slots: true },
|
||||
{ rMax: R * 0.98, need: 1.2, offs: [-0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4], slots: true },
|
||||
];
|
||||
function place(fp, pass) {
|
||||
const others = pass.slots ? placed.concat(slots) : placed, cands = [];
|
||||
for (let arm = 0; arm < ARMS; arm++) {
|
||||
for (let r = rMin; r <= pass.rMax; r += 1.25) {
|
||||
for (const off of pass.offs) {
|
||||
const a = armAngle(r, arm, G) + off;
|
||||
const c = { x: Math.cos(a) * r, z: Math.sin(a) * r, r };
|
||||
let clear = r - CORE.fp - fp;
|
||||
for (const o of others) clear = Math.min(clear, dist(o, c) - o.fp - fp);
|
||||
if (clear < pass.need) continue;
|
||||
// 分数:够宽敞(封顶,不为了宽敞跑到边上)、靠近中圈、所在旋臂人少、在旋臂正中更好
|
||||
cands.push({ c, a, r, arm, clear, score: Math.min(clear, 12) - 0.08 * Math.abs(r - mid) - 2.2 * armCount[arm] - 3 * Math.abs(off) });
|
||||
}
|
||||
}
|
||||
}
|
||||
cands.sort((x, y) => y.score - x.score || x.r - y.r || x.a - y.a);
|
||||
let best = null;
|
||||
for (const k of cands.slice(0, 60)) {
|
||||
const par = parentFor(k.c, placed);
|
||||
if (!par) continue;
|
||||
const s = k.score + Math.min(par.clear, 6) * 0.3;
|
||||
if (!best || s > best.s + 1e-9) best = { s, k, parent: par.p };
|
||||
}
|
||||
if (best) return best;
|
||||
return cands.length ? { k: cands[0], parent: CORE } : null; // 线怎么都会擦到别的星:就近连核心,至少星不叠
|
||||
}
|
||||
|
||||
for (const u of list) {
|
||||
if (u.empty || out.has(u.no)) continue;
|
||||
const look = lookOf(u), fp = footprint(look);
|
||||
let got = null;
|
||||
for (const pass of PASSES) { got = place(fp, pass); if (got) break; }
|
||||
if (!got) { // 整张图都满了(几十条以后):退到最外圈,按编号错开
|
||||
const e = Math.max(0, num(u) - first), r = R * 1.02 + 2 * Math.floor(e / ARMS);
|
||||
placed.push(put(u, look, r, armAngle(r, e % ARMS, G) + 0.16, 'auto', null));
|
||||
continue;
|
||||
}
|
||||
const s = put(u, look, got.k.r, got.k.a, 'auto', got.parent.no);
|
||||
armCount[got.k.arm]++;
|
||||
placed.push(s);
|
||||
}
|
||||
// 4) 空槽的淡线:接到最近的、不穿星的已点亮星(或核心)
|
||||
const litNow = [...out.values()].filter(s => !s.u.empty && s.r > 0);
|
||||
for (const s of out.values()) {
|
||||
if (s.kind !== 'slot') continue;
|
||||
const par = parentFor(s, litNow);
|
||||
s.parent = par && par.p !== CORE ? par.p.no : null;
|
||||
}
|
||||
return list.map(u => out.get(u.no));
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
/* =============================================================================
|
||||
* 金钻宇宙 · 卡通星球材质库(planets.js)
|
||||
* -----------------------------------------------------------------------------
|
||||
* 每一种「风格」= 一段着色器(决定星球表面长什么样)+ 一组默认参数。
|
||||
* 全部是程序生成的卡通材质:分段明暗(toon)+ 墨线描边 + 轮廓光,不依赖任何贴图文件。
|
||||
*
|
||||
* 加一种新风格:在 STYLES 里加一项 { geo, frag, defaults },见交接说明「加一种星球风格」。
|
||||
* 用法:
|
||||
* import { makePlanet } from './planets.js';
|
||||
* const p = makePlanet(THREE, { style: 'ice', r: 1.2, colors: [...] });
|
||||
* scene.add(p.group); // p.update(dt, t, lightDirWorld) 每帧调一次
|
||||
* ============================================================================= */
|
||||
|
||||
// ---- 3D simplex 噪声(Ashima / Stefan Gustavson,MIT)—— 用物体空间坐标取样,球面上没有接缝
|
||||
const NOISE = `
|
||||
vec3 m289(vec3 x){return x-floor(x*(1.0/289.0))*289.0;} vec4 m289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}
|
||||
vec4 perm(vec4 x){return m289(((x*34.0)+1.0)*x);} vec4 tis(vec4 r){return 1.79284291400159-0.85373472095314*r;}
|
||||
float snoise(vec3 v){const vec2 C=vec2(1.0/6.0,1.0/3.0);const vec4 D=vec4(0.0,0.5,1.0,2.0);
|
||||
vec3 i=floor(v+dot(v,C.yyy));vec3 x0=v-i+dot(i,C.xxx);vec3 g=step(x0.yzx,x0.xyz);vec3 l=1.0-g;
|
||||
vec3 i1=min(g.xyz,l.zxy);vec3 i2=max(g.xyz,l.zxy);vec3 x1=x0-i1+C.xxx;vec3 x2=x0-i2+C.yyy;vec3 x3=x0-D.yyy;
|
||||
i=m289(i);vec4 p=perm(perm(perm(i.z+vec4(0.0,i1.z,i2.z,1.0))+i.y+vec4(0.0,i1.y,i2.y,1.0))+i.x+vec4(0.0,i1.x,i2.x,1.0));
|
||||
float n_=0.142857142857;vec3 ns=n_*D.wyz-D.xzx;vec4 j=p-49.0*floor(p*ns.z*ns.z);vec4 x_=floor(j*ns.z);vec4 y_=floor(j-7.0*x_);
|
||||
vec4 x=x_*ns.x+ns.yyyy;vec4 y=y_*ns.x+ns.yyyy;vec4 h=1.0-abs(x)-abs(y);vec4 b0=vec4(x.xy,y.xy);vec4 b1=vec4(x.zw,y.zw);
|
||||
vec4 s0=floor(b0)*2.0+1.0;vec4 s1=floor(b1)*2.0+1.0;vec4 sh=-step(h,vec4(0.0));vec4 a0=b0.xzyw+s0.xzyw*sh.xxyy;vec4 a1=b1.xzyw+s1.xzyw*sh.zzww;
|
||||
vec3 p0=vec3(a0.xy,h.x);vec3 p1=vec3(a0.zw,h.y);vec3 p2=vec3(a1.xy,h.z);vec3 p3=vec3(a1.zw,h.w);
|
||||
vec4 nm=tis(vec4(dot(p0,p0),dot(p1,p1),dot(p2,p2),dot(p3,p3)));p0*=nm.x;p1*=nm.y;p2*=nm.z;p3*=nm.w;
|
||||
vec4 m=max(0.6-vec4(dot(x0,x0),dot(x1,x1),dot(x2,x2),dot(x3,x3)),0.0);m=m*m;
|
||||
return 42.0*dot(m*m,vec4(dot(p0,x0),dot(p1,x1),dot(p2,x2),dot(p3,x3)));}
|
||||
float fbm(vec3 p){ float v=0.0,a=0.5; for(int i=0;i<4;i++){ v+=a*snoise(p); p=p*2.02+vec3(3.1,1.7,5.3); a*=0.5; } return v; }
|
||||
// 抗锯齿的细线:x 离 0 越近越黑,线宽 w(以屏幕像素为单位)
|
||||
float aline(float x, float w){ float f = fwidth(x); return 1.0 - smoothstep(0.0, f*w, abs(x)); }
|
||||
`;
|
||||
|
||||
// ---- 公共部分:分段明暗 + 冷色阴影 + 轮廓光
|
||||
const HEAD = `
|
||||
uniform vec3 uL; uniform float uT; uniform float uSeed; uniform vec3 uC0; uniform vec3 uC1; uniform vec3 uC2; uniform vec3 uC3;
|
||||
uniform vec3 uShadow; uniform vec3 uRim; uniform float uGlow; uniform float uAlpha;
|
||||
varying vec3 vP; varying vec3 vN; varying vec3 vW;
|
||||
${NOISE}
|
||||
// 卡通分段光照:亮 / 中 / 暗 三档,交界处一点点平滑防锯齿
|
||||
float toon(float d){ float a = smoothstep(0.30,0.34,d), b = smoothstep(-0.12,-0.08,d); return 0.38 + 0.32*b + 0.30*a; }
|
||||
vec3 shade(vec3 base, vec3 N, vec3 V){ float d = dot(N, normalize(uL)); float t = toon(d);
|
||||
vec3 c = mix(base*uShadow, base, t);
|
||||
float rim = pow(1.0 - max(dot(N, V), 0.0), 3.0); c += uRim * rim * 0.32 * smoothstep(-0.3, 0.4, d + 0.3);
|
||||
return c; }
|
||||
`;
|
||||
|
||||
const VERT = `
|
||||
varying vec3 vP; varying vec3 vN; varying vec3 vW;
|
||||
void main(){ vP = normalize(position); vN = normalize(mat3(modelMatrix)*normal); vec4 w = modelMatrix*vec4(position,1.0); vW = w.xyz; gl_Position = projectionMatrix*viewMatrix*w; }`;
|
||||
|
||||
// ---- 各风格的表面(main 里拿到 base 颜色 + 自发光 emi,最后统一上光)
|
||||
const STYLES = {
|
||||
/* 晶体:多面体切面,每个面颜色随朝向变化(像钻石折光),内部有发光的「演算脉络」 —— 给晶钻超算主宇宙 */
|
||||
crystal: {
|
||||
geo: (THREE, r) => new THREE.IcosahedronGeometry(r, 2),
|
||||
defaults: { colors: ['#7FE7FF', '#8E7BFF', '#FFE59A', '#FFFFFF'], shadow: '#5B5FA8', rim: '#BFF4FF', outline: '#141A3A', glow: 0.55 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW);
|
||||
vec3 N = normalize(cross(dFdx(vW), dFdy(vW))); // 平面法线 = 一个面一个颜色
|
||||
vec3 nO = normalize(vP);
|
||||
float k = 0.5 + 0.5*sin(dot(nO, vec3(5.1,3.7,4.3)) + uSeed);
|
||||
vec3 base = mix(mix(uC0, uC1, k), uC2, smoothstep(0.55, 1.0, sin(dot(nO, vec3(2.3,-4.1,1.7))*3.0 + uSeed)*0.5+0.5)*0.55);
|
||||
float vein = aline(snoise(vP*3.2 + vec3(0.0, uT*0.08, 0.0)), 2.2);
|
||||
vec3 c = shade(base, N, V);
|
||||
float spark = pow(max(dot(reflect(-normalize(uL), N), V), 0.0), 24.0);
|
||||
c += uC3 * step(0.5, spark) * 0.45 + uC0 * vein * 0.75 * uGlow;
|
||||
gl_FragColor = vec4(c, uAlpha); }`,
|
||||
},
|
||||
/* 铅笔纸面:米白纸色 + 等高线一样的铅笔线 + 暗面排线 + 几处红笔圈 —— 给「火柴人宇宙」(小时候课上画的) */
|
||||
paper: {
|
||||
defaults: { colors: ['#F6F1E4', '#2B2E45', '#E5544B', '#9DB7E8'], shadow: '#B9B4C8', rim: '#FFFFFF', outline: '#2B2E45', glow: 0 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
float n = fbm(vP*1.6 + uSeed);
|
||||
float contour = aline(fract(n*4.0 + 0.5) - 0.5, 1.4);
|
||||
float d = dot(N, normalize(uL));
|
||||
float h1 = aline(fract(dot(vP, vec3(0.7,0.7,0.1))*26.0) - 0.5, 1.2) * (1.0 - smoothstep(-0.1, 0.1, d)); // 暗面单向排线
|
||||
float h2 = aline(fract(dot(vP, vec3(-0.7,0.7,0.2))*26.0) - 0.5, 1.2) * (1.0 - smoothstep(-0.55, -0.4, d)); // 更暗处交叉排线
|
||||
float circ = aline(length(vP - normalize(vec3(0.6, 0.35, 0.7))) - 0.22, 1.6) + aline(length(vP - normalize(vec3(-0.5,-0.4,0.75))) - 0.14, 1.6);
|
||||
float blue = smoothstep(0.35, 0.6, fbm(vP*2.4 + 7.0 + uSeed)); // 几块淡蓝色铅笔涂色
|
||||
vec3 base = mix(uC0, mix(uC0, uC3, 0.45), blue);
|
||||
vec3 c = shade(base, N, V);
|
||||
c = mix(c, uC1, clamp(contour*0.85 + max(h1, h2)*0.6, 0.0, 1.0));
|
||||
c = mix(c, uC2, clamp(circ, 0.0, 1.0)*0.9);
|
||||
gl_FragColor = vec4(c, uAlpha); }`,
|
||||
},
|
||||
/* 冰封:纬向冰带 + 极冠 + 冰裂纹 —— 给「极寒世界」(冰河期、地表 -50℃) */
|
||||
ice: {
|
||||
defaults: { colors: ['#F2FAFF', '#BFE4FF', '#7CC3F0', '#FFFFFF'], shadow: '#6C80C9', rim: '#D6F3FF', outline: '#18305C', glow: 0.2 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
float band = snoise(vec3(vP.x*1.2, vP.y*7.0 + uSeed, vP.z*1.2));
|
||||
vec3 base = mix(uC0, uC1, smoothstep(-0.25, 0.35, band));
|
||||
base = mix(base, uC3, smoothstep(0.68, 0.74, abs(vP.y) + 0.05*snoise(vP*6.0))); // 极冠
|
||||
float crack = smoothstep(0.88, 0.95, 1.0 - abs(snoise(vP*4.5 + uSeed)));
|
||||
vec3 c = shade(base, N, V);
|
||||
c = mix(c, uC2, crack*0.85);
|
||||
c += uC3 * pow(max(dot(reflect(-normalize(uL), N), V), 0.0), 40.0) * 0.6;
|
||||
gl_FragColor = vec4(c, uAlpha); }`,
|
||||
},
|
||||
/* 霓虹城:深紫底色 + 经纬网格街区 + 闪烁的窗灯 —— 给「没落赛博城」 */
|
||||
neon: {
|
||||
defaults: { colors: ['#211A3D', '#5FF2FF', '#FF5FD2', '#FFD36E'], shadow: '#5E5A8F', rim: '#8A7BFF', outline: '#0B0820', glow: 1.0 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
float lon = atan(vP.z, vP.x) / 3.14159265, lat = asin(clamp(vP.y, -1.0, 1.0)) / 1.5707963;
|
||||
float dist = smoothstep(-0.05, 0.25, fbm(vP*2.2 + uSeed)); // 有城的街区
|
||||
float gx = aline(fract(lon*14.0) - 0.5, 1.6), gy = aline(fract(lat*9.0) - 0.5, 1.6);
|
||||
vec2 cell = floor(vec2(lon*56.0, lat*36.0));
|
||||
float win = step(0.72, fract(sin(dot(cell, vec2(12.9898, 78.233)) + uSeed)*43758.5453));
|
||||
float flick = 0.65 + 0.35*sin(uT*2.0 + cell.x*1.7 + cell.y*0.9);
|
||||
vec3 base = uC0 * (0.9 + 0.2*snoise(vP*3.0));
|
||||
vec3 c = shade(base, N, V);
|
||||
vec3 neon = mix(uC1, uC2, step(0.0, snoise(vP*1.3 + 11.0)));
|
||||
c += neon * max(gx, gy) * dist * 1.2 * uGlow + uC3 * win * dist * flick * 0.55 * uGlow;
|
||||
gl_FragColor = vec4(c, uAlpha); }`,
|
||||
},
|
||||
/* 善恶两半:一半金色白昼、一半紫色夜空,交界是一条发光的波浪线 —— 给「善恶等级」 */
|
||||
duality: {
|
||||
defaults: { colors: ['#FFF0C8', '#F2B84B', '#2D1E57', '#8F6BFF'], shadow: '#8C7AA8', rim: '#FFE7A8', outline: '#1A1235', glow: 0.8 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
float s = vP.x*0.9 + 0.22*snoise(vP*1.8 + uSeed) + 0.12*sin(vP.y*7.0 + uT*0.3);
|
||||
float side = smoothstep(-0.015, 0.015, s);
|
||||
float cloud = smoothstep(0.1, 0.5, fbm(vP*2.6 + uSeed));
|
||||
vec3 light = mix(uC0, uC1, cloud*0.6);
|
||||
float star = step(0.985, fract(sin(dot(floor(vP*60.0), vec3(12.9898,78.233,37.719)))*43758.5453));
|
||||
vec3 dark = mix(uC2, uC3, cloud*0.5) + vec3(star)*0.8;
|
||||
vec3 c = shade(mix(dark, light, side), N, V);
|
||||
c += uC1 * aline(s, 3.0) * 1.2 * uGlow;
|
||||
gl_FragColor = vec4(c, uAlpha); }`,
|
||||
},
|
||||
/* 气态巨星(点缀用):卡通条纹 + 一个风暴眼 */
|
||||
gas: {
|
||||
defaults: { colors: ['#F2D7A6', '#D99A6C', '#8E6BBF', '#FFF2D6'], shadow: '#7A6A9E', rim: '#FFE2B8', outline: '#1E1838', ring: false, glow: 0 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
float w = vP.y*5.0 + 0.6*snoise(vec3(vP.x*2.0, vP.y*4.0, vP.z*2.0) + uSeed);
|
||||
float b = 0.5 + 0.5*sin(w*3.14159);
|
||||
vec3 base = mix(mix(uC0, uC1, smoothstep(0.3, 0.7, b)), uC2, smoothstep(0.8, 0.95, b)*0.6);
|
||||
float storm = 1.0 - smoothstep(0.08, 0.13, length(vP - normalize(vec3(0.8, -0.25, 0.5))));
|
||||
base = mix(base, uC3, storm*0.85);
|
||||
gl_FragColor = vec4(shade(base, N, V), uAlpha); }`,
|
||||
},
|
||||
/* 岩石小行星(点缀用):卡通陨坑 */
|
||||
rock: {
|
||||
defaults: { colors: ['#A9AFC9', '#7D84A6', '#5B6288', '#D5D9EA'], shadow: '#5B5F8A', rim: '#C9D3FF', outline: '#141833', glow: 0 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
float n = fbm(vP*2.0 + uSeed);
|
||||
vec3 base = mix(uC0, uC1, smoothstep(-0.2, 0.3, n));
|
||||
float cr = smoothstep(0.42, 0.5, snoise(vP*5.0 + uSeed*2.0));
|
||||
base = mix(base, uC2, cr); base = mix(base, uC3, aline(snoise(vP*5.0 + uSeed*2.0) - 0.42, 1.5)*0.7);
|
||||
gl_FragColor = vec4(shade(base, N, V), uAlpha); }`,
|
||||
},
|
||||
/* ===== 2026-10-05 加的预设(游戏美术里最常见的几类卡通星球;画法同上:三档明暗 + 墨线 + 轮廓光) ===== */
|
||||
/* 类地(卡通地球):蓝海 + 绿色大陆 + 沙漠块 + 极冠 + 慢慢飘的白云,海岸一圈墨线 */
|
||||
earth: {
|
||||
defaults: { colors: ['#3E8EDB', '#5DBB63', '#E8C77A', '#FFFFFF'], shadow: '#4A55A0', rim: '#BFE6FF', outline: '#14284A', glow: 0 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
float h = fbm(vP*1.5 + uSeed) + 0.22*snoise(vP*4.0 + uSeed);
|
||||
float land = smoothstep(0.03, 0.05, h), shallow = smoothstep(-0.14, 0.03, h)*(1.0 - land);
|
||||
vec3 water = mix(uC0, mix(uC0, vec3(1.0), 0.32), shallow);
|
||||
float dry = smoothstep(0.1, 0.35, snoise(vP*2.2 + uSeed + 5.0)) * (1.0 - smoothstep(0.45, 0.75, abs(vP.y)));
|
||||
vec3 base = mix(water, mix(uC1, uC2, dry*0.85), land);
|
||||
base = mix(base, uC3, smoothstep(0.80, 0.84, abs(vP.y) + 0.06*snoise(vP*5.0)));
|
||||
vec3 c = shade(base, N, V);
|
||||
c = mix(c, uC1*0.35, aline(h - 0.04, 1.2)*0.7);
|
||||
float cl = smoothstep(0.32, 0.38, fbm(vP*2.2 + vec3(uT*0.015, 9.0, uSeed)));
|
||||
float lit = smoothstep(-0.1, 0.12, dot(N, normalize(uL)));
|
||||
c = mix(c, mix(uC3*0.72, uC3, lit), cl*0.85);
|
||||
gl_FragColor = vec4(c, uAlpha); }`,
|
||||
},
|
||||
/* 海洋:几乎全是水,深浅两色 + 零星小岛 + 一圈圈浪线 + 条状云 */
|
||||
ocean: {
|
||||
defaults: { colors: ['#1F5FB8', '#3FB5E6', '#F2D49B', '#FFFFFF'], shadow: '#3A4A9A', rim: '#B8EEFF', outline: '#0F2148', glow: 0 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
float h = fbm(vP*1.8 + uSeed);
|
||||
float isl = smoothstep(0.40, 0.43, h);
|
||||
vec3 base = mix(mix(uC0, uC1, smoothstep(0.05, 0.38, h)), uC2, isl);
|
||||
vec3 c = shade(base, N, V);
|
||||
c = mix(c, uC3, aline(h - 0.34 - 0.02*sin(uT*0.8), 1.2)*0.6*(1.0 - isl));
|
||||
float st = smoothstep(0.30, 0.36, snoise(vec3(vP.x*1.4, vP.y*6.0, vP.z*1.4) + vec3(uSeed, 0.0, uT*0.01)));
|
||||
c = mix(c, uC3, st*0.8*smoothstep(-0.2, 0.2, dot(N, normalize(uL))) + st*0.15);
|
||||
gl_FragColor = vec4(c, uAlpha); }`,
|
||||
},
|
||||
/* 丛林:深浅两层绿 + 一团团树冠 + 弯弯的河 + 飘着的雾 */
|
||||
jungle: {
|
||||
defaults: { colors: ['#2F7D4A', '#6CC46A', '#3FA7D6', '#E9F7E4'], shadow: '#355A6E', rim: '#CFFFD8', outline: '#11301E', glow: 0 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
float n = fbm(vP*2.4 + uSeed);
|
||||
vec3 base = mix(uC0, uC1, smoothstep(-0.1, 0.35, n));
|
||||
base = mix(base, uC1*1.12, smoothstep(0.5, 0.56, snoise(vP*4.0 + uSeed))*0.5);
|
||||
float rv = fbm(vP*1.1 + uSeed*1.3);
|
||||
base = mix(base, uC2, aline(rv, 1.5)*smoothstep(0.75, 0.3, abs(vP.y))*0.9);
|
||||
vec3 c = shade(base, N, V);
|
||||
c = mix(c, uC3, smoothstep(0.35, 0.5, fbm(vP*1.6 + vec3(0.0, uT*0.015, 20.0)))*0.5);
|
||||
gl_FragColor = vec4(c, uAlpha); }`,
|
||||
},
|
||||
/* 荒漠:弯曲的沙丘条纹 + 红色台地(带墨线轮廓)+ 一点点极冠 */
|
||||
desert: {
|
||||
defaults: { colors: ['#F2C38B', '#E09A5A', '#B5623E', '#FFF4E2'], shadow: '#8A5A7A', rim: '#FFE2BF', outline: '#3A1E24', glow: 0 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
float b = 0.5 + 0.5*sin((vP.y*6.0 + 1.2*fbm(vP*1.8 + uSeed))*3.14159);
|
||||
vec3 base = mix(uC0, uC1, smoothstep(0.35, 0.65, b));
|
||||
float m = snoise(vP*3.0 + uSeed + 3.0);
|
||||
base = mix(base, uC2, smoothstep(0.42, 0.46, m));
|
||||
base = mix(base, uC3, smoothstep(0.86, 0.9, abs(vP.y)));
|
||||
vec3 c = shade(base, N, V);
|
||||
c = mix(c, uC2*0.6, aline(m - 0.44, 1.2)*0.7);
|
||||
gl_FragColor = vec4(c, uAlpha); }`,
|
||||
},
|
||||
/* 冻原:霜白和青灰 + 一片片深色针叶林 + 结冰的湖 */
|
||||
tundra: {
|
||||
defaults: { colors: ['#E9F3F2', '#9CC9C1', '#4E7F7A', '#BFE8FF'], shadow: '#6A7FA8', rim: '#E4FBFF', outline: '#173233', glow: 0 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
vec3 base = mix(uC0, uC1, smoothstep(0.0, 0.4, fbm(vP*2.0 + uSeed)));
|
||||
base = mix(base, uC2, smoothstep(0.5, 0.56, snoise(vP*5.5 + uSeed))*smoothstep(0.75, 0.4, abs(vP.y)));
|
||||
float lk = snoise(vP*3.0 + uSeed + 9.0);
|
||||
base = mix(base, uC3, smoothstep(0.62, 0.66, lk));
|
||||
vec3 c = shade(base, N, V);
|
||||
c = mix(c, uC2, aline(lk - 0.64, 1.2)*0.6);
|
||||
c += uC3 * pow(max(dot(reflect(-normalize(uL), N), V), 0.0), 30.0) * 0.35;
|
||||
gl_FragColor = vec4(c, uAlpha); }`,
|
||||
},
|
||||
/* 熔岩:深色岩壳 + 发光的裂缝和岩浆池(慢慢呼吸) */
|
||||
lava: {
|
||||
defaults: { colors: ['#2A1E2E', '#4A3340', '#FF7A2F', '#FFD36E'], shadow: '#3A2A4A', rim: '#FF9A5A', outline: '#120A14', glow: 0.9 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
float n = snoise(vP*3.0 + uSeed), n2 = snoise(vP*7.0 + uSeed*2.0);
|
||||
float crack = max(1.0 - smoothstep(0.0, 0.07, abs(n)), (1.0 - smoothstep(0.0, 0.045, abs(n2)))*0.7);
|
||||
float pool = smoothstep(0.5, 0.55, fbm(vP*1.6 + uSeed + 4.0));
|
||||
vec3 c = shade(mix(uC0, uC1, smoothstep(-0.3, 0.4, fbm(vP*2.5 + uSeed))), N, V);
|
||||
vec3 hot = mix(uC2, uC3, 0.35 + 0.25*sin(uT*1.4 + n*6.0));
|
||||
c = mix(c, hot, max(crack, pool)*uGlow);
|
||||
gl_FragColor = vec4(c, uAlpha); }`,
|
||||
},
|
||||
/* 毒雾:酸绿和黄绿的扭曲气流 + 一点紫色 + 冒泡的亮点 */
|
||||
toxic: {
|
||||
defaults: { colors: ['#B8E04A', '#6FBF3A', '#5B3F8C', '#F4FF9E'], shadow: '#4E3F7A', rim: '#E6FF9A', outline: '#1A1A2E', glow: 0.5 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
float w = fbm(vP*2.0 + vec3(uT*0.02, 0.0, uSeed));
|
||||
float w2 = fbm(vP*2.0 + w*1.6 + uSeed);
|
||||
vec3 base = mix(uC0, uC1, smoothstep(-0.2, 0.3, w2));
|
||||
base = mix(base, uC2, smoothstep(0.35, 0.5, w2)*0.6);
|
||||
vec3 c = shade(base, N, V);
|
||||
vec3 cell = floor(vP*28.0);
|
||||
float bub = step(0.94, fract(sin(dot(cell, vec3(12.9898, 78.233, 37.719)) + uSeed)*43758.5453));
|
||||
c += uC3 * bub * (0.5 + 0.5*sin(uT*2.0 + cell.x)) * 0.4 * uGlow;
|
||||
gl_FragColor = vec4(c, uAlpha); }`,
|
||||
},
|
||||
/* 荒芜岩球(像月球):灰色岩面 + 大小两层陨坑,坑沿一圈墨线、坑底更暗 */
|
||||
barren: {
|
||||
defaults: { colors: ['#C9C6CF', '#9F9AA8', '#6E6878', '#ECEAF2'], shadow: '#5F5A78', rim: '#E6E2FF', outline: '#1C1A26', glow: 0 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
vec3 base = mix(uC0, uC1, smoothstep(-0.2, 0.35, fbm(vP*2.2 + uSeed)));
|
||||
float a = snoise(vP*3.6 + uSeed), b = snoise(vP*9.0 + uSeed*3.0);
|
||||
base = mix(base, uC2, smoothstep(0.46, 0.56, a));
|
||||
base = mix(base, uC2, smoothstep(0.58, 0.66, b)*0.8);
|
||||
vec3 c = shade(base, N, V);
|
||||
c = mix(c, uC3, max(aline(a - 0.46, 1.4), aline(b - 0.58, 1.1)*0.6)*0.55*smoothstep(-0.2, 0.3, dot(N, normalize(uL))));
|
||||
c = mix(c, uC2*0.6, max(aline(a - 0.47, 1.0), aline(b - 0.59, 0.8)*0.5)*0.5);
|
||||
gl_FragColor = vec4(c, uAlpha); }`,
|
||||
},
|
||||
/* 冰巨星(像海王星):蓝色细条纹 + 一个深色风暴眼 + 几道白色流云 */
|
||||
icegiant: {
|
||||
defaults: { colors: ['#8FD3FF', '#4E8FE8', '#2B3F9E', '#FFFFFF'], shadow: '#3C4C9E', rim: '#CFF0FF', outline: '#101C48', glow: 0 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
float w = vP.y*7.0 + 0.35*snoise(vec3(vP.x*2.0, vP.y*5.0, vP.z*2.0) + uSeed);
|
||||
float b = 0.5 + 0.5*sin(w*3.14159);
|
||||
vec3 base = mix(uC0, uC1, smoothstep(0.35, 0.65, b));
|
||||
float spot = 1.0 - smoothstep(0.1, 0.15, length((vP - normalize(vec3(0.7, -0.3, 0.62)))*vec3(1.0, 1.7, 1.0)));
|
||||
base = mix(base, uC2, spot*0.9);
|
||||
vec3 c = shade(base, N, V);
|
||||
float streak = smoothstep(0.55, 0.62, snoise(vec3(vP.x*1.2, vP.y*14.0, vP.z*1.2) + vec3(uT*0.02, 0.0, uSeed)));
|
||||
c = mix(c, uC3, streak*0.75);
|
||||
gl_FragColor = vec4(c, uAlpha); }`,
|
||||
},
|
||||
/* 未点亮:半透明全息线框球 —— 空槽 */
|
||||
ghost: {
|
||||
transparent: true,
|
||||
defaults: { colors: ['#7F8BC8', '#B9C4FF', '#7F8BC8', '#FFFFFF'], shadow: '#FFFFFF', rim: '#B9C4FF', outline: null, glow: 0, alpha: 1 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
float lon = atan(vP.z, vP.x) / 3.14159265, lat = asin(clamp(vP.y,-1.0,1.0)) / 1.5707963;
|
||||
float g = max(aline(fract(lon*8.0 + uT*0.02) - 0.5, 1.4), aline(fract(lat*5.0) - 0.5, 1.4));
|
||||
float f = pow(1.0 - max(dot(N, V), 0.0), 2.0);
|
||||
gl_FragColor = vec4(mix(uC0, uC1, f), (g*0.55 + f*0.45 + 0.04) * uAlpha); }`,
|
||||
},
|
||||
};
|
||||
|
||||
/* 带环巨星:气态巨星 + 一圈卡通扁环(光环默认不加,只有这个预设自带;颜色压低,不发光) */
|
||||
STYLES.ringed = {
|
||||
defaults: { colors: ['#F4E1B8', '#D9A26C', '#9C6B9E', '#FFF6DE'], shadow: '#7A6A9E', rim: '#FFE9C4', outline: '#241A36', glow: 0,
|
||||
ring: { inner: 1.45, outer: 2.05, color: '#F2E3C2', color2: '#C99E72' }, tilt: 0.42 },
|
||||
frag: STYLES.gas.frag,
|
||||
};
|
||||
|
||||
export const STYLE_NAMES = Object.keys(STYLES);
|
||||
/* 每种风格的中文名(内容后台的下拉、交接文档都用这一份) */
|
||||
export const STYLE_LABELS = {
|
||||
crystal: '晶体', paper: '铅笔纸面', ice: '冰封', neon: '霓虹城', duality: '善恶两半',
|
||||
earth: '类地(卡通地球)', ocean: '海洋', jungle: '丛林', desert: '荒漠', tundra: '冻原',
|
||||
lava: '熔岩', toxic: '毒雾', barren: '荒芜岩球', gas: '气态巨星', icegiant: '冰巨星', ringed: '带环巨星',
|
||||
rock: '小行星', ghost: '未点亮(空槽)',
|
||||
};
|
||||
|
||||
/**
|
||||
* 造一颗卡通星球。look 里能写:
|
||||
* style 风格名(见 STYLES)
|
||||
* r 半径
|
||||
* colors 四个颜色(覆盖风格默认) shadow / rim / outline 阴影色 / 轮廓光色 / 描边色(outline:null 不描边)
|
||||
* ring 要不要光环(默认没有;true / { inner, outer, color })
|
||||
* seed 随机种子(同一风格的两颗星球长得不一样)
|
||||
* tilt 自转轴倾角(弧度)
|
||||
* atm 大气辉光颜色(默认没有;写了才加一层很淡的辉光)
|
||||
*/
|
||||
export function makePlanet(THREE, look = {}) {
|
||||
const S = STYLES[look.style] || STYLES.rock;
|
||||
const o = Object.assign({}, S.defaults, look);
|
||||
const r = o.r || 1;
|
||||
const col = i => new THREE.Color((o.colors || S.defaults.colors)[i] || '#ffffff');
|
||||
const uniforms = {
|
||||
uL: { value: new THREE.Vector3(-1, 0.6, 0.5) }, uT: { value: 0 }, uSeed: { value: o.seed ?? Math.random() * 50 },
|
||||
uC0: { value: col(0) }, uC1: { value: col(1) }, uC2: { value: col(2) }, uC3: { value: col(3) },
|
||||
uShadow: { value: new THREE.Color(o.shadow) }, uRim: { value: new THREE.Color(o.rim) }, uGlow: { value: o.glow ?? 0 }, uAlpha: { value: o.alpha ?? 1 },
|
||||
};
|
||||
const mat = new THREE.ShaderMaterial({ uniforms, vertexShader: VERT, fragmentShader: HEAD + S.frag,
|
||||
transparent: !!S.transparent, depthWrite: !S.transparent, side: S.transparent ? THREE.DoubleSide : THREE.FrontSide });
|
||||
const geo = S.geo ? S.geo(THREE, r) : new THREE.SphereGeometry(r, 96, 64);
|
||||
const group = new THREE.Group(), body = new THREE.Mesh(geo, mat);
|
||||
body.rotation.z = o.tilt ?? 0.3; group.add(body);
|
||||
// 墨线描边:背面放大一点点的同形状,纯色 —— 卡通感的关键
|
||||
if (o.outline) { const ol = new THREE.Mesh(geo, new THREE.MeshBasicMaterial({ color: o.outline, side: THREE.BackSide }));
|
||||
ol.scale.setScalar(1.035); body.add(ol); }
|
||||
// 大气辉光:默认**不加**(用户反馈「每颗星球外边都有一个罩子」)。确实想要就在 look 里写 atm: '#颜色'
|
||||
let atm = null;
|
||||
if (o.atm) {
|
||||
atm = new THREE.Mesh(new THREE.SphereGeometry(r * 1.08, 48, 32), new THREE.ShaderMaterial({
|
||||
transparent: true, depthWrite: false, side: THREE.BackSide, blending: THREE.AdditiveBlending,
|
||||
uniforms: { uC: { value: new THREE.Color(o.atm) }, uS: { value: 0.25 } },
|
||||
vertexShader: `varying vec3 vN; varying vec3 vW; void main(){ vN = normalize(mat3(modelMatrix)*normal); vec4 w = modelMatrix*vec4(position,1.0); vW = w.xyz; gl_Position = projectionMatrix*viewMatrix*w; }`,
|
||||
fragmentShader: `uniform vec3 uC; uniform float uS; varying vec3 vN; varying vec3 vW; void main(){ vec3 v = normalize(cameraPosition - vW); float f = pow(1.0 - abs(dot(v, vN)), 4.0); gl_FragColor = vec4(uC, f*uS); }` }));
|
||||
group.add(atm);
|
||||
}
|
||||
// 光环(卡通扁环,两道颜色)
|
||||
let ring = null;
|
||||
if (o.ring) {
|
||||
const rc = typeof o.ring === 'object' ? o.ring : {};
|
||||
const inner = (rc.inner || 1.45) * r, outer = (rc.outer || 2.1) * r;
|
||||
ring = new THREE.Mesh(new THREE.RingGeometry(inner, outer, 128, 1), new THREE.ShaderMaterial({
|
||||
transparent: true, depthWrite: false, side: THREE.DoubleSide,
|
||||
uniforms: { uA: { value: new THREE.Color(rc.color || (o.colors || S.defaults.colors)[0]) }, uB: { value: new THREE.Color(rc.color2 || (o.colors || S.defaults.colors)[1]) }, uIn: { value: inner }, uOut: { value: outer } },
|
||||
vertexShader: `varying vec3 vP; void main(){ vP = position; gl_Position = projectionMatrix*modelViewMatrix*vec4(position,1.0); }`,
|
||||
fragmentShader: `uniform vec3 uA; uniform vec3 uB; uniform float uIn; uniform float uOut; varying vec3 vP;
|
||||
void main(){ float t = (length(vP.xy)-uIn)/(uOut-uIn); float b = step(0.5, fract(t*5.0));
|
||||
float a = (0.42 + 0.2*b) * smoothstep(0.0, 0.06, t) * smoothstep(1.0, 0.94, t); gl_FragColor = vec4(mix(uA, uB, b*0.6 + t*0.3), a); }` }));
|
||||
ring.rotation.x = -Math.PI / 2 + 0.38; ring.rotation.y = 0.12; group.add(ring);
|
||||
}
|
||||
const spin = o.spin ?? 0.15;
|
||||
return {
|
||||
group, body, mat, atm, ring, r, look: o,
|
||||
update(dt, t, lightDir) { body.rotation.y += dt * spin; uniforms.uT.value = t; if (lightDir) uniforms.uL.value.copy(lightDir); },
|
||||
setAlpha(a) { uniforms.uAlpha.value = a; },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/* 金钻宇宙页:白色客栈页面里开一扇「观星窗」,窗里是星系图;窗下是世界线档案列表(和星图联动) */
|
||||
.skywin{--sky:#070B1C;--ui:#FFD36E;--line:rgba(127,139,200,.35);--pixel:'Fusion Pixel','OPPO Sans',sans-serif;
|
||||
position:relative;margin:6px 0 26px;padding:6px;border-radius:12px;background:rgba(255,255,255,.75);border:2px solid #fff;
|
||||
box-shadow:0 30px 60px -36px rgba(40,50,110,.55)}
|
||||
.skywin .stage{position:relative;height:min(72vh,660px);min-height:440px;border-radius:8px;overflow:hidden;background:var(--sky);color:#E8EBFA;isolation:isolate}
|
||||
.skywin #uGl{position:absolute;inset:0;width:100%;height:100%;display:block;touch-action:none;outline:none}
|
||||
/* 窗内 HUD:只放读数,标题已经在页面上了 */
|
||||
.skywin .hud{position:absolute;left:18px;top:14px;pointer-events:none;display:flex;gap:16px;font:600 11px/1.4 ui-monospace,Menlo,monospace;letter-spacing:.12em;color:#7C84B4;
|
||||
animation:uHud 1s cubic-bezier(.23,1,.32,1) .4s both}
|
||||
.skywin .hud b{font:400 18px/1 var(--pixel);letter-spacing:0;color:var(--ui);margin-left:6px;-webkit-font-smoothing:none}
|
||||
@keyframes uHud{from{opacity:0;transform:translateY(-6px)}to{opacity:1;transform:none}}
|
||||
.skywin .labels{position:absolute;inset:0;pointer-events:none;transition:opacity .9s cubic-bezier(.23,1,.32,1)}
|
||||
.skywin .stage:not(.ready) .labels{opacity:0}
|
||||
.skywin .tag{position:absolute;left:0;top:0;display:flex;align-items:center;gap:7px;padding:3px 8px;border:0;border-radius:4px;background:none;cursor:pointer;white-space:nowrap;pointer-events:auto;font:inherit;text-align:left;will-change:transform;transition:opacity .3s}
|
||||
.skywin .tag .t b{display:block;font:400 15px/1.15 var(--pixel);-webkit-font-smoothing:none;color:#F4F6FF;text-shadow:0 0 8px rgba(5,8,25,.95)}
|
||||
.skywin .tag .t em{display:block;font:600 10px/1.3 ui-monospace,Menlo,monospace;letter-spacing:.12em;font-style:normal;color:#7C84B4}
|
||||
.skywin .tag:hover,.skywin .tag.hot{background:rgba(255,211,110,.1)} .skywin .tag:hover .t b,.skywin .tag.hot .t b{color:var(--ui)}
|
||||
.skywin .tag:focus-visible{outline:2px solid var(--ui);outline-offset:2px}
|
||||
.skywin .tag.empty .t b{color:#8A92BE;font-size:13px}
|
||||
.skywin .tag.dim{opacity:.15}
|
||||
.skywin .sector{position:absolute;left:0;top:0;font:600 10px/1 ui-monospace,Menlo,monospace;letter-spacing:.3em;color:rgba(169,176,214,.42);white-space:nowrap;transition:opacity .4s;pointer-events:none}
|
||||
/* 窗内档案卡(桌面 / 全屏时) */
|
||||
.skywin .panel{position:absolute;right:18px;top:50%;width:min(390px,40%);transform:translate(20px,-48%);opacity:0;pointer-events:none;transition:opacity .45s cubic-bezier(.23,1,.32,1),transform .6s cubic-bezier(.23,1,.32,1)}
|
||||
.skywin .panel.on{opacity:1;transform:translate(0,-50%);pointer-events:auto}
|
||||
.skywin .panel .card{position:relative;padding:20px 20px 16px 24px;border-radius:8px;background:rgba(255,255,255,.96);border:2px solid #fff;color:var(--ink);box-shadow:0 30px 70px -30px rgba(0,0,0,.6)}
|
||||
.skywin .panel .card::before{content:"";position:absolute;left:0;top:0;bottom:0;width:4px;border-radius:8px 0 0 8px;background:var(--pc,#FFD36E)}
|
||||
.skywin .panel .card .k{font:600 12px/1 var(--font,inherit);letter-spacing:.06em;color:var(--ink-3)}
|
||||
.skywin .panel .card h2{margin:8px 0 2px;font:400 28px/1.2 'Fusion Pixel','OPPO Sans',sans-serif;-webkit-font-smoothing:none}
|
||||
.skywin .panel .card .tg{color:var(--ink-2);font-size:14px}
|
||||
.skywin .panel .card .ds{margin:10px 0 0;font-size:14px;line-height:1.8;color:var(--ink-2)}
|
||||
.skywin .panel .card .tags{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}
|
||||
.skywin .panel .card .tags span{font-size:12px;padding:4px 8px;border-radius:4px;background:rgba(30,36,64,.05);color:var(--ink-2)}
|
||||
.skywin .panel .card .acts{display:flex;flex-wrap:wrap;gap:8px;margin-top:16px;justify-content:space-between}
|
||||
.skywin .panel .card .nav{display:flex;gap:8px}
|
||||
.skywin .panel .card .btn{height:38px;font-size:13.5px;padding:0 14px 3px}
|
||||
/* 窗角按钮 */
|
||||
.skywin .ctl{position:absolute;right:14px;top:12px;display:flex;gap:8px}
|
||||
.skywin .ctl .btn{height:34px;font-size:13px;padding:0 12px 3px}
|
||||
.skywin #uBack{display:none} .skywin .stage.focus #uBack{display:inline-flex}
|
||||
.skywin .tip{position:absolute;left:18px;bottom:14px;margin:0;font-size:12px;color:#7C84B4;pointer-events:none;transition:opacity .3s}
|
||||
.skywin .stage.focus .tip{opacity:0}
|
||||
.skywin .loading{position:absolute;inset:0;display:grid;place-items:center;font:400 18px var(--pixel);color:#A9B0D6;background:var(--sky);transition:opacity .6s;z-index:5}
|
||||
/* 全屏:窗户铺满屏幕,滚轮直接缩放 */
|
||||
.skywin.full .stage{position:fixed;inset:0;z-index:300;height:auto;min-height:0;border-radius:0}
|
||||
body.sky-full{overflow:hidden}
|
||||
/* 窗下:世界线列表 */
|
||||
.sky-hint{display:none}
|
||||
.uni-list{display:grid;grid-template-columns:repeat(auto-fill,minmax(230px,1fr));gap:12px;margin-bottom:14px}
|
||||
.ucell{position:relative;display:flex;flex-direction:column;gap:4px;padding:16px 16px 14px;border-radius:8px;border:2px solid rgba(255,255,255,.95);text-align:left;cursor:pointer;font:inherit;color:var(--ink);
|
||||
background:linear-gradient(160deg,rgba(255,255,255,.9),rgba(255,255,255,.65));box-shadow:0 18px 36px -26px rgba(80,90,170,.45);transition:transform .2s cubic-bezier(.23,1,.32,1),box-shadow .2s}
|
||||
.ucell:hover{transform:translateY(-2px)}
|
||||
.ucell[aria-current=true]{box-shadow:inset 0 0 0 3px var(--mc-green,#3C8527),0 18px 36px -26px rgba(80,90,170,.45)}
|
||||
.ucell .no{font:600 11px/1 ui-monospace,Menlo,monospace;letter-spacing:.14em;color:var(--ink-3)}
|
||||
.ucell h3{margin:2px 0 0;font:400 22px/1.25 'Fusion Pixel','OPPO Sans',sans-serif;-webkit-font-smoothing:none}
|
||||
.ucell .tg{font-size:13px;color:var(--ink-2)}
|
||||
.ucell .go{margin-top:6px;font-size:12.5px;font-weight:700;color:var(--mc-green,#3C8527)}
|
||||
.ucell .sw{position:absolute;right:14px;top:14px;width:26px;height:26px;border-radius:50%;background:var(--sw);box-shadow:inset -5px -5px 0 rgba(0,0,0,.18),0 0 0 2px #fff}
|
||||
.uslots{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:10px}
|
||||
.uslots button{height:54px;border-radius:8px;border:1.5px dashed rgba(140,150,200,.45);background:rgba(255,255,255,.6);font:inherit;font-size:12px;color:var(--ink-3);cursor:pointer}
|
||||
.uslots button b{display:block;font-size:14px;color:var(--ink-2);font-variant-numeric:tabular-nums}
|
||||
.uslots button[aria-current=true]{border-style:solid;border-color:var(--mc-green,#3C8527)}
|
||||
@media (max-width:760px){
|
||||
.skywin{margin:4px -4px 8px;padding:4px}
|
||||
/* 窗户不铺满屏:上下留出能滑页面的地方 */
|
||||
.skywin .stage{height:min(64svh,560px);min-height:400px}
|
||||
.skywin #uGl{touch-action:none} /* 在星图里的手势全归星图:单指转、双指缩放,不会带着页面滑 */
|
||||
.sky-hint{display:block;margin:0 2px 20px;font-size:12px;color:var(--ink-3);text-align:center}
|
||||
/* 档案卡:星图窗里的底部抽屉(只占下半个窗),星球被镜头挪到上半个窗 */
|
||||
.skywin .panel{left:8px;right:8px;top:47%;bottom:8px;width:auto;display:flex;flex-direction:column;justify-content:flex-end;transform:translateY(24px)}
|
||||
.skywin.full .panel{bottom:calc(8px + env(safe-area-inset-bottom))}
|
||||
.skywin .panel.on{transform:none}
|
||||
.skywin .panel .card{max-height:100%;overflow:auto;overscroll-behavior:contain;-webkit-overflow-scrolling:touch;padding:12px 14px 0 18px;touch-action:pan-y}
|
||||
.skywin .panel .card h2{margin-top:6px;font-size:21px}
|
||||
.skywin .panel .card .tg{font-size:13px}
|
||||
.skywin .panel .card .ds{margin-top:6px;font-size:13px;line-height:1.7}
|
||||
.skywin .panel .card .tags{margin-top:8px}
|
||||
.skywin .panel .card .tags span{font-size:11.5px;padding:3px 7px}
|
||||
/* 三个按钮一行,贴在抽屉底边,正文长了在中间滚 */
|
||||
.skywin .panel .card .acts{position:sticky;bottom:0;display:grid;grid-template-columns:1fr 1fr 1.25fr;gap:6px;margin:10px -14px 0 -18px;padding:8px 14px 12px 18px;background:linear-gradient(rgba(255,255,255,0),#fff 10px)}
|
||||
.skywin .panel .card .nav{display:contents}
|
||||
.skywin .panel .card .btn{height:36px;font-size:13px;padding:0 6px 3px}
|
||||
.skywin .tag .t b{font-size:13px} .skywin .tag .t em{display:none} .skywin .tag.empty{display:none}
|
||||
.skywin .sector,.skywin .tip{display:none}
|
||||
.skywin #uBack{display:none !important} /* 手机:返回按钮已经在档案卡里了 */
|
||||
.skywin .hud{gap:12px;transition:opacity .3s}
|
||||
.skywin .stage.focus .hud{animation:none;opacity:0} /* 看档案时把读数收起来,别和右上角按钮挤 */
|
||||
.uni-list{grid-template-columns:1fr 1fr;gap:10px}
|
||||
.ucell{padding:14px 12px 12px}.ucell h3{font-size:18px}.ucell .sw{width:20px;height:20px;right:10px;top:10px}
|
||||
.uslots{grid-template-columns:repeat(3,minmax(0,1fr))}
|
||||
}
|
||||
@media (prefers-reduced-motion:reduce){.skywin .panel,.skywin .labels,.skywin .hud,.ucell{transition:none;animation:none}}
|
||||
|
||||
/* ===== 开场星门(2026-10-06,替换「星图载入中…」):钻石 + 三圈光环 + 一排世界线格子,星系画好就向外炸开 ===== */
|
||||
.ugate{position:absolute;inset:0;z-index:6;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:22px;pointer-events:none;
|
||||
background:radial-gradient(46% 52% at 50% 46%,rgba(255,255,255,.96) 0%,rgba(246,247,255,.9) 55%,rgba(238,240,255,.86) 100%);transition:opacity .9s ease .25s}
|
||||
.ugate-core{position:relative;width:150px;height:150px;display:grid;place-items:center}
|
||||
.ugate-core i{width:62px;height:62px;filter:drop-shadow(-6px 12px 14px rgba(255,110,140,.3)) drop-shadow(6px 12px 14px rgba(70,140,255,.3));animation:ugFloat 2.6s ease-in-out infinite}
|
||||
.ugate-ring{position:absolute;inset:0;border-radius:50%;padding:2px;background:conic-gradient(from 0deg,#FFB3C3,#FFD99A,#A9EBC6,#A6D5FF,#CDB9FF,#FFB3C3);
|
||||
-webkit-mask:linear-gradient(#000 0 0) content-box,linear-gradient(#000 0 0);-webkit-mask-composite:xor;mask:linear-gradient(#000 0 0) content-box exclude,linear-gradient(#000 0 0);
|
||||
animation:ugSpin 6s linear infinite;transition:transform .9s cubic-bezier(.2,.7,.2,1),opacity .8s ease}
|
||||
.ugate-ring.r2{inset:16%;opacity:.7;animation-duration:4.2s;animation-direction:reverse}
|
||||
.ugate-ring.r3{inset:-18%;opacity:.4;padding:1px;animation-duration:9s;border-radius:50%}
|
||||
.ugate-txt{display:flex;flex-direction:column;align-items:center;gap:6px;transition:opacity .4s ease,transform .6s ease}
|
||||
.ugate-txt b{font:400 28px/1 var(--pixel,inherit);letter-spacing:.08em;color:var(--ink,#1E2440);-webkit-font-smoothing:none}
|
||||
.ugate-txt span{font-size:13px;color:var(--ink-3,#737891)}
|
||||
.ugate-slots{display:grid;grid-template-columns:repeat(var(--n,11),18px);gap:6px;transition:opacity .5s ease}
|
||||
.ugate-slots i{position:relative;height:28px;border-radius:3px;border:1.5px dashed rgba(140,150,200,.45);background:rgba(255,255,255,.6);transition:transform .7s cubic-bezier(.2,.7,.2,1),opacity .6s ease}
|
||||
.ugate-slots i.l{border:0;background:#fff;box-shadow:inset 0 0 0 2px rgba(30,36,64,.08)}
|
||||
.ugate.scan .ugate-slots i.l{animation:ugLight .5s ease both;animation-delay:calc(180ms + var(--i) * 90ms)}
|
||||
.ugate.scan .ugate-slots::after{content:"";grid-row:1;grid-column:1/-1;height:28px;border-radius:3px;pointer-events:none;
|
||||
background:linear-gradient(90deg,transparent 0%,rgba(255,255,255,.95) 50%,transparent 100%);background-size:40% 100%;background-repeat:no-repeat;mix-blend-mode:screen;animation:ugScan 1.4s ease-in-out infinite}
|
||||
@keyframes ugLight{to{background:linear-gradient(180deg,#fff 0%,var(--c) 100%);box-shadow:0 8px 14px -6px var(--c)}}
|
||||
@keyframes ugScan{0%{background-position:-40% 0}100%{background-position:140% 0}}
|
||||
@keyframes ugSpin{to{transform:rotate(360deg)}}
|
||||
@keyframes ugFloat{50%{transform:translateY(-6px)}}
|
||||
/* 打开:光环向外炸开、格子往两边散、钻石一亮,整块淡出 —— 正好接上星系图自己的镜头俯冲 */
|
||||
.ugate.open{opacity:0}
|
||||
.ugate.open .ugate-ring{opacity:0;animation-play-state:paused}
|
||||
.ugate.open .ugate-ring.r1{transform:scale(4.2)}
|
||||
.ugate.open .ugate-ring.r2{transform:scale(5.4)}
|
||||
.ugate.open .ugate-ring.r3{transform:scale(3.4)}
|
||||
.ugate.open .ugate-core i{animation:ugFlash .7s ease forwards}
|
||||
@keyframes ugFlash{30%{transform:scale(1.25);filter:brightness(1.6) drop-shadow(0 0 22px #fff)}100%{transform:scale(.4);opacity:0}}
|
||||
.ugate.open .ugate-txt{opacity:0;transform:translateY(12px)}
|
||||
.ugate.open .ugate-slots i{opacity:0;transform:translateX(calc((var(--i) - var(--n) / 2) * 26px)) translateY(-40px) scale(.6)}
|
||||
.ugate.failed .ugate-core i,.ugate.failed .ugate-ring{animation:none}
|
||||
.ugate.failed .ugate-txt span{max-width:30em;text-align:center;color:var(--ink-2,#4A5070)}
|
||||
@media (max-width:760px){
|
||||
.ugate{gap:16px}
|
||||
.ugate-core{width:110px;height:110px}
|
||||
.ugate-core i{width:46px;height:46px}
|
||||
.ugate-slots{grid-template-columns:repeat(var(--n,11),14px);gap:4px}
|
||||
.ugate-slots i{height:22px}
|
||||
}
|
||||
@media (prefers-reduced-motion:reduce){
|
||||
.ugate-ring,.ugate-core i,.ugate.scan .ugate-slots::after{animation:none}
|
||||
.ugate.scan .ugate-slots i.l{animation:none;background:linear-gradient(180deg,#fff 0%,var(--c) 100%)}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
# 交接说明 · 金钻宇宙星系图(`portal/assets/universe/`)
|
||||
|
||||
> 状态:**已接进门户**(2026-10-05);2026-10-06 起门户是多页,星系图在 `portal/universe.html`(样子按设计预览站),开场是 `gate.js` 的「星门」(星系第一帧画好才打开,接上下面的镜头俯冲)。
|
||||
> 风格参考:《绝地潜兵 2》银河战争地图 —— 旋臂星系 + 星云 + 扇区 + 补给线;每条世界线是一个星系,点进去是一颗卡通星球 + 档案卡。
|
||||
|
||||
---
|
||||
|
||||
## 1. 文件
|
||||
|
||||
| 文件 | 干什么 | 日常要不要改 |
|
||||
|---|---|---|
|
||||
| `assets/universe/config.js` | **全部内容和外观配置**:世界线档案、每颗星球的风格 / 颜色 / 卫星、星系配色、扇区名、粒子数量。门户主脚本的 `UNIVERSES` 也从这里读 | **改这个** |
|
||||
| `assets/universe/planets.js` | 卡通星球材质库(每种「风格」= 一段着色器 + 默认参数) | 加新风格时改 |
|
||||
| `assets/universe/galaxy.js` | 引擎:画星系、星云、补给线、名牌,处理拖动 / 缩放 / 点击 / 档案卡 / 运镜 | 一般不用动 |
|
||||
| `assets/universe/universe.css` | 观星窗、档案卡、窗下世界线卡片、手机布局的样式 | 改版式时改 |
|
||||
| `portal/universe.html`(`#skywin` + 底部那段 `<script type="module">`)+ `universe-page.css` + `gate.js` | 页面骨架(窗户 / 名牌层 / HUD / 档案卡 / 卡片列表)、接线代码、开场星门 | 改交互时改 |
|
||||
| `assets/vendor/three.module.min.js` | three.js r170(MIT,自托管,不连外网) | 不动 |
|
||||
|
||||
**没有任何贴图、模型文件**:星球、星云、星点全是着色器实时生成的,所以没有版权问题,也不用担心图片加载慢。
|
||||
|
||||
---
|
||||
|
||||
## 2. 常见改动
|
||||
|
||||
### 加一条新世界线
|
||||
|
||||
> **2026-10-05 起推荐用内容后台**(门户顶栏最右边的铅笔 →「金钻宇宙」→「点亮一条」):填档案、下拉选外观,预览、发布就上线。
|
||||
> 后台发布的内容写在 `portal/content/site.js`(`window.JZ_CONTENT.universe`),`config.js` 末尾会用它**覆盖**下面写死的
|
||||
> `UNIVERSES` / `LOOKS`;`config.js` 里那两份只是兜底(内容文件读不到时用)。`GALAXY`、`EMPTY_LOOK` 不归后台管,还是改这个文件。
|
||||
>
|
||||
> 不用后台、直接改文件的话(比如本地调试):
|
||||
|
||||
1. `config.js` → `UNIVERSES` 里把对应的空槽(比如 `{ no: '0005', empty: true }`)换成完整档案:
|
||||
```js
|
||||
{ no: '0005', name: '名字', kind: '原创', tag: '一句话副标题', tags: ['标签1', '标签2'], desc: '档案正文' },
|
||||
```
|
||||
字段和门户页原来的 `UNIVERSES` 一模一样(`no / name / kind / tag / tags / desc`),可以直接拷。
|
||||
2. `config.js` → `LOOKS` 里按编号加外观:
|
||||
```js
|
||||
'0005': { style: 'ice', r: 1.2, orbit: [34, 2], accent: '#9FE3FF',
|
||||
colors: ['#…', '#…', '#…', '#…'], // 可选:覆盖风格默认的四个颜色
|
||||
ring: true, // 可选:光环(默认没有;用户觉得突兀,现在一颗都没开)
|
||||
atm: '#9FE3FF', // 可选:大气辉光(默认没有;之前「每颗星外面一个罩子」就是它)
|
||||
moons: [{ style: 'rock', r: 0.3, d: 2.6, speed: 0.5 }], // 可选:卫星(纯装饰)
|
||||
why: '为什么长这样(写给后来的人看)' },
|
||||
```
|
||||
- `orbit: [离中心距离, 第几条旋臂]`:距离 0~60,旋臂 0~3。**可以不写** —— 不写就交给 `layout.js` 自动排位(见下)。
|
||||
- 不写 `LOOKS` 的世界线会自动用 `EMPTY_LOOK`(全息线框的「未点亮」样子),放在外圈。
|
||||
|
||||
### 位置和补给线是怎么排的(`layout.js`,纯计算,可单独测试)
|
||||
1. **写了 `orbit` 的**(现在的 0000–0004):就放在那儿,补给线从核心连过去。
|
||||
2. **空槽**:按**编号**放在外圈固定槽位(从 `GALAXY.firstSlot` 号起,轮流分到各条旋臂)。只看自己的编号,点亮一个,别的空槽不挪。
|
||||
空槽的淡虚线接到离它最近、又不穿过别的星的那颗已点亮的星(没有就接核心)。
|
||||
3. **已点亮但没写 `orbit` 的**(后台新点亮的):自动在中圈的旋臂上挑位置 —— 跟核心、已有星系(连同卫星轨道)留足距离,
|
||||
各条旋臂尽量均匀;补给线接到「比它更靠近核心、离它最近」的那颗星,而且不能从别的星中间穿过。
|
||||
按编号从小到大一颗颗排,每颗只看排在前面的,所以**新加一条,已有的星和线都不动**。
|
||||
实测:连续点亮 10 条,已有的一次都没动,两两不挤,线不穿星。
|
||||
3. 刷新页面即可。HUD 上的「世界线 / 已点亮 / 空槽」数字是自动数的。
|
||||
|
||||
### 只换一颗星球的颜色
|
||||
改它 `LOOKS` 里的 `colors`(四个颜色,含义见下表)。不写就用风格默认值。
|
||||
|
||||
### 改整张图的配色
|
||||
`config.js` → `GALAXY.colors`:底色、核心色、旋臂内外色、星云几组颜色、线条色、UI 强调色(名牌 / 数字的金色)。
|
||||
**建议整张图只用这几种颜色**,别给每颗星单独配一个刺眼的颜色 —— 上一版就是因为颜色太杂被说丑。
|
||||
|
||||
### 改扇区名 / 粒子数量 / 散落星球数量
|
||||
`GALAXY.sectors`(6 个扇区名)、`GALAXY.particles`、`GALAXY.nebulae`、`GALAXY.decorPlanets`(桌面 / 手机分开设)。
|
||||
手机卡的话先把 `particles.mobile` 降到 10000、`nebulae.mobile` 降到 10。
|
||||
|
||||
---
|
||||
|
||||
## 3. 现有的星球风格(`planets.js` → `STYLES`,中文名在 `STYLE_LABELS`)
|
||||
|
||||
内容后台「金钻宇宙」页的「星球风格」下拉、「外观预设」一览都来自这里(一览里是真实渲染)。2026-10-05 加了带「新」的 10 种。
|
||||
|
||||
| 风格 | 长什么样 | 现在给谁用 |
|
||||
|---|---|---|
|
||||
| `earth` 新 · 类地(卡通地球) | 蓝海 + 绿色大陆 + 沙漠块 + 极冠 + 慢慢飘的白云,海岸一圈墨线 | 后台新点亮的默认 |
|
||||
| `ocean` 新 · 海洋 | 几乎全是水,深浅两色 + 零星小岛 + 岛边浪线 + 条状云 | — |
|
||||
| `jungle` 新 · 丛林 | 深浅两层绿 + 一团团树冠 + 弯弯的河 + 雾 | — |
|
||||
| `desert` 新 · 荒漠 | 弯曲沙丘条纹 + 红色台地(墨线轮廓)+ 一点极冠 | — |
|
||||
| `tundra` 新 · 冻原 | 霜白和青灰 + 深色针叶林 + 结冰的湖 | — |
|
||||
| `ice` · 冰封 | 纬向冰带、极冠、冰裂纹、冰面高光 | 极寒世界 |
|
||||
| `lava` 新 · 熔岩 | 深色岩壳 + 发光裂缝和岩浆池(慢慢呼吸) | — |
|
||||
| `toxic` 新 · 毒雾 | 酸绿 / 黄绿扭曲气流 + 一点紫 + 冒泡亮点 | — |
|
||||
| `barren` 新 · 荒芜岩球 | 灰色岩面 + 大小两层陨坑(坑沿墨线、坑底更暗) | — |
|
||||
| `gas` · 气态巨星 | 卡通条纹 + 风暴眼 | 散落的无名星球、卫星 |
|
||||
| `icegiant` 新 · 冰巨星 | 蓝色细条纹 + 深色风暴眼 + 白色流云 | — |
|
||||
| `ringed` 新 · 带环巨星 | 气态巨星 + 一圈压低颜色的卡通扁环(**只有这个预设自带光环**) | — |
|
||||
| `crystal` · 晶体 | 多面体切面、每面颜色随朝向变、内部发光脉络 | 零号宇宙 |
|
||||
| `paper` · 铅笔纸面 | 米白纸面、铅笔等高线、暗面排线、红笔圈 | 火柴人宇宙 |
|
||||
| `neon` · 霓虹城 | 深紫地表、霓虹街区网格、闪烁窗灯 | 没落赛博城 |
|
||||
| `duality` · 善恶两半 | 一半白昼一半夜空,交界发光波浪线 | 善恶等级 |
|
||||
| `rock` · 小行星 | 卡通陨坑岩石 | 卫星、散落星球 |
|
||||
| `ghost` · 未点亮 | 半透明全息线框球 | 空槽 |
|
||||
|
||||
所有风格共用:三档卡通明暗(亮 / 中 / 暗)+ 冷色阴影(`shadow`)+ 很弱的轮廓光(`rim`)+ 墨线描边(`outline`,写 `null` 不描边)。
|
||||
大气辉光(`atm`)和光环(`ring`)都是**可选**的,默认关 —— 用户反馈过「罩子」「环」很突兀、辉光太曝。
|
||||
|
||||
### 加一种新风格
|
||||
在 `STYLES` 里加一项:
|
||||
```js
|
||||
myStyle: {
|
||||
defaults: { colors: ['#…','#…','#…','#…'], shadow: '#…', rim: '#…', outline: '#…', glow: 0 },
|
||||
frag: `void main(){ vec3 V = normalize(cameraPosition - vW); vec3 N = normalize(vN);
|
||||
vec3 base = mix(uC0, uC1, smoothstep(-0.2, 0.3, fbm(vP*2.0 + uSeed))); // vP = 球面上的点(单位向量)
|
||||
gl_FragColor = vec4(shade(base, N, V), uAlpha); }`,
|
||||
},
|
||||
```
|
||||
着色器里能用:`snoise(vec3)` 噪声、`fbm(vec3)` 分形噪声、`aline(x, 线宽)` 抗锯齿细线、`shade(颜色, N, V)` 统一上卡通光、
|
||||
`uC0~uC3` 四个颜色、`uT` 时间、`uSeed` 种子、`uGlow` 自发光强度。然后在 `LOOKS` 里 `style: 'myStyle'` 就能用。
|
||||
|
||||
---
|
||||
|
||||
## 4. 交互
|
||||
|
||||
### 开场 / 飞行动画(运镜库在 galaxy.js 的 MOVES 里)
|
||||
全部按时间走(和帧率无关),慢设备上也是同一条连贯的路线。
|
||||
|
||||
| 运镜 | 名字 | 怎么动 | 现在给谁 |
|
||||
|---|---|---|---|
|
||||
| 推进 | `push` | 先转过去对准(前 40%),再笔直推进去,不绕圈 | 火柴人宇宙 |
|
||||
| 放大 | `zoom` | 先用长焦把它拉近(视角收窄到 14°),再一边推进一边把视角放回来 | 零号宇宙 |
|
||||
| 升空俯冲 | `rise` | 先拉高到几乎俯视,再从上面扎下去 | 极寒世界 |
|
||||
| 跃迁 | `warp` | 慢起步、中段猛冲、末段刹住;冲的时候视角张开、镜头轻轻一滚 | 没落赛博城 |
|
||||
| 绕行 | `orbit` | 边飞边绕过去,中途抬高拉远一点 | 善恶等级;以及「上一个 / 下一个」在星系之间切换时 |
|
||||
| 拉远 | `pull` | 回星系图:先往后退,再抬头看全景 | 「回到星系图」 |
|
||||
| 开场 · 盘旋落下 | `introSweep` | 从高空、更远处绕半圈落到正常视角 | 开场(`GALAXY.intro`) |
|
||||
| 开场 · 垂直坠入 | `introDive` | 从正上方很远处直着落下来,最后才抬起镜头 | 开场(`GALAXY.intro`,默认随机二选一) |
|
||||
|
||||
- 每条世界线用哪个入场运镜:`config.js` → `LOOKS[编号].enter`;不写就按 push / zoom / rise / warp / orbit 轮流。
|
||||
- **档案卡和镜头同步**:点下去时旧档案先收起,镜头飞到 78% 的时候档案卡才滑出来(内容也那时才换),和星球落定同时到。
|
||||
嵌在页面里时 `onFocus(u, 'start')` 在起飞时回调(列表马上高亮),`onFocus(u, 'arrive')` 在快到时回调(这时再出正文)。
|
||||
- 飞的途中用户拖动 / 缩放:运镜立刻停在原地交还控制权,没出来的档案卡马上补出来,不会丢。
|
||||
- 加一种新运镜:往 `MOVES` 里加一项 `{ dur: 毫秒, path(from, to, k) { … 往 view 里写 az/el/dist/tx/ty/tz/fov/roll … } }`,再在 `enter` 里写它的名字。
|
||||
- 开场在画面第一次进入视口时开始;星系从暗处亮起来(约 2.4 秒),镜头落定后名牌才浮现。「载入中」在第一帧画出来时才淡出。
|
||||
- 总览时星系会放大一点(桌面 1.35 倍、手机 1.9 倍)好认,飞近时恢复真实大小。
|
||||
|
||||
|
||||
- 桌面:拖动转视角、滚轮缩放、点星球或名牌飞过去、`←` / `→` 切上一个 / 下一个、`Esc` 回到星系图。
|
||||
- 手机:单指拖动、**双指缩放**、点名牌或星球飞过去;飞过去后星球在上半屏、档案卡是底部抽屉,「回到星系图」在卡里。
|
||||
- 系统设置了「减少动态效果」:星系不自转、镜头直接切过去、星云不流动。
|
||||
- 名牌是真正的 `<button>`,键盘 Tab 能选中。
|
||||
|
||||
---
|
||||
|
||||
## 5. 手机端处理过的冲突(这次修的)
|
||||
|
||||
| 问题 | 怎么修的 |
|
||||
|---|---|
|
||||
| HUD 的说明文字和星系名牌叠在一起 | 手机只留标题 + 一行读数;落在 HUD 范围里的名牌自动藏起来 |
|
||||
| 名牌贴边被切掉 | 名牌位置夹在屏幕内(左右各留 6px) |
|
||||
| 档案卡挡住星球 | 选中后镜头把星球挪到上半屏,档案卡做成底部抽屉(最高 44% 屏高,内容多了卡里自己滚) |
|
||||
| 左下「回到星系图」被抽屉盖住 | 手机上隐藏它,按钮放进档案卡(整行宽,好点) |
|
||||
| 空槽名牌太多太挤 | 手机只显示已点亮的名牌,空槽只留星球本身 |
|
||||
| 不能缩放 | 加了双指缩放 |
|
||||
| 近处的星点糊成大光斑 | 星点像素大小设了上限 |
|
||||
| 手机画面比桌面稀、星系只是小点 | 手机和桌面用几乎一样的数量,星点大小按距离补偿,总览时星系放大 1.9 倍 |
|
||||
| 名牌前的小方块色点 | 去掉了(全站规矩:文字前不放色点) |
|
||||
| 散落的无名星球乱、互相重叠、卫星有的反着转 | 减到 14 颗;摆放时和核心、各星系(含卫星轨道)、彼此之间都留距离;卫星一律同向转 |
|
||||
|
||||
验证:无头浏览器 390×844 / 1440×900 各截一轮,五颗星球逐个飞进去截图,控制台 0 报错、无横向滚动、所有名牌都在屏幕内且不压 HUD。
|
||||
|
||||
---
|
||||
|
||||
## 6. 在门户里是怎么接的
|
||||
|
||||
- `<head>` 里:`assets/universe/universe.css` + 一段 `importmap`(把 `three` 指到 `assets/vendor/three.module.min.js`)。
|
||||
- 主脚本之前:`<script src="assets/universe/config.js">` —— 主脚本一解析就要读 `window.JZ_UNIVERSE`(首页总览的计数、`#0001` 深链都用它)。
|
||||
- 页面底部一段 `<script type="module">`:
|
||||
- 按 `config.js` 渲染窗下的世界线卡片和空槽;
|
||||
- 对外挂 `window.__jzUniverse = { show(), fly(编号) }`;
|
||||
- **第一次 `show()` 时才 `import('./assets/universe/galaxy.js')`**,three.js 跟着下载(约 690KB,gzip 后约 170KB)。首页、画展等别的板块不下载它。
|
||||
- 主脚本:`showBoard('universe')` 调 `__jzUniverse.show()`;`#0001` 这种旧深链调 `__jzUniverse.fly('0001')`;飞到哪条,地址栏就 `replaceState` 成 `#编号`,可以直接分享。
|
||||
|
||||
`mountGalaxy()` 的可选参数(门户都用上了):
|
||||
|
||||
| 参数 | 干什么 | 门户怎么用 |
|
||||
|---|---|---|
|
||||
| `onFocus(u, phase)` | 选中 / 取消选中时回调(`u` 是档案或 `null`;`phase` 是 `start` 起飞 / `arrive` 快到) | 窗下卡片跟着高亮;地址栏跟着改 |
|
||||
| `layout()` | 返回 `{x, y}`:选中时星球往左 / 往上挪多少 | 桌面 `{x:0.17}`(右边是窗内档案卡);手机 `{y:0.26}`(档案卡是窗里的底部抽屉) |
|
||||
| `wheelZoom()` | 返回 `false` 时普通滚轮留给页面滚动,按住 Ctrl 才缩放 | 不全屏时 `false`,全屏时 `true` |
|
||||
| `onReady()` | 第一帧画好 | 淡出「星图载入中」 |
|
||||
| 返回值 `api.fly(no)` / `api.home()` / `api.resize()` | 从外面控制 | 点卡片 → 先把窗户滚到眼前再 `fly`;切全屏 / 切回板块后 `resize` |
|
||||
|
||||
另外:画面滚出视口时自动暂停渲染(省电);手机上星图里的手势全归星图(`touch-action:none`:单指转、双指缩放,页面不会跟着滑),窗户只占屏幕约 64%,上下留了滑页面的地方,窗下有一句提示。
|
||||
星图起不来(没有 WebGL)时,窗里显示原因,下面的世界线卡片照常能看。
|
||||
|
||||
## 7. 改了什么(相对原门户)
|
||||
|
||||
删掉:启动仪式(逐字 / 权限扫描 / 欢迎)、宇宙首屏的晶体线框画布(CrystalView)、盘符机架(抽插 / 读盘舱 / 键盘翻页)、两枚只给插卡用的图标(`--icd-logo` 白标、`--icd-people` 火柴人)。
|
||||
保留:首页右侧的晶钻徽记、`#0001` / `#rack` 旧链接(分别飞到那条世界线 / 打开宇宙板块)。
|
||||
|
||||
---
|
||||
|
||||
## 8. 性能
|
||||
|
||||
- 桌面:4.2 万星点 + 32 片星云 + 14 颗散落星球 + 11 个星系(含卫星)。手机:3.6 万星点 + 28 片星云 + 14 颗(为了和桌面画面一致,只少一点点)。
|
||||
- ⚠️ **帧率还没在真机上测过**(只在无头浏览器的软件渲染里验证了画面和交互),上线前请用一台普通手机和一台集显笔记本各打开看一下。
|
||||
- 手机像素比上限 1.5;星点大小按镜头距离补偿,手机和桌面看起来一样密。
|
||||
- 每颗星球一个绘制调用(加描边、大气各一个),没有实时阴影、没有后处理。
|
||||
- 卡的话按第 2 节降粒子数;再不行把 `planets.js` 里球体的 `SphereGeometry(r, 96, 64)` 降到 `(r, 48, 32)`。
|
||||
|
||||
## 9. 版权
|
||||
|
||||
- three.js:MIT(`vendor/three-LICENSE.txt`)。
|
||||
- 噪声函数:Ashima Arts / Stefan Gustavson 的 3D simplex noise(MIT),写在 `planets.js` 里。
|
||||
- 星球、星云、星点:全部程序生成,无外部素材。
|
||||
- 上一版用过的 NASA 星球贴图已经全部撤掉(不再需要署名)。
|
||||
|
||||
## 10. 部署注意(踩过的坑)
|
||||
|
||||
- 静态文件可能被缓存。**改了 JS / CSS 一定要换版本号**,几处一起换:`portal/universe.html` 里的 `universe-page.css?v=`、`gate.js?v=`、`config.js?v=`、底部模块脚本里的 `galaxy.js?v=`,以及 `galaxy.js` 里的 `import './planets.js?v='` / `'./layout.js?v='`。
|
||||
2026-10-05 踩过:一个坏掉的 galaxy.js 被缓存住,修好之后打开还是「加载不出来」。
|
||||
- 检查语法要按 ES 模块检查(把文件拷成 `.mjs` 再 `node --check`),按普通脚本检查会漏掉「重复声明」这类错误。
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License
|
||||
|
||||
Copyright © 2010-2024 three.js authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+6
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,459 @@
|
||||
{
|
||||
"v": 1,
|
||||
"hero": {
|
||||
"tagline": "金钻的画、做的小工具、写的宇宙设定,还有各个平台的主页,都放在这儿了。随便逛逛。",
|
||||
"cta1": "逛画展",
|
||||
"cta2": "金钻宇宙",
|
||||
"notice": {
|
||||
"on": false,
|
||||
"text": "",
|
||||
"from": "",
|
||||
"to": ""
|
||||
}
|
||||
},
|
||||
"boards": {
|
||||
"home": "整个网站的大框架与内容总入口:板块总览、快捷切换。",
|
||||
"gallery": "金钻一路画下的画稿、渲染影像与特殊图片,随年份安静地排在一起,可自由翻看。",
|
||||
"apps": "开源的项目与闭源的工具分两行列出,并可按类型筛选。",
|
||||
"universe": "金钻编的平行世界,每一条是一个星系:点星系飞过去,看那条世界线的设定。",
|
||||
"links": "视频、图文、模型创作、开源、小店与邮箱;这些地方也能找到金钻。",
|
||||
"about": "网站制作者与所用开源组件鸣谢:金钻(内容 / 创作者)、苏达与大肥鱼(构建),以及 Lucide 图标库、OPPO Sans 字体。"
|
||||
},
|
||||
"gallery": [
|
||||
{
|
||||
"id": "g1",
|
||||
"type": "image",
|
||||
"date": "2024-02-29",
|
||||
"title": "(作品占位)",
|
||||
"desc": "素材已在交付版脱敏移除",
|
||||
"owner": "own",
|
||||
"hidden": false,
|
||||
"src": "exhibition/渲染与动画/20240229/没有图片.webp",
|
||||
"r": 1.5241
|
||||
}
|
||||
],
|
||||
"apps": [
|
||||
{
|
||||
"id": "a1",
|
||||
"name": "待会儿办",
|
||||
"en": "DO IT LATER",
|
||||
"type": "网页应用",
|
||||
"oss": true,
|
||||
"desc": "家庭共用的待办 / 提醒小应用:发布端一次录入,接收端点一下完成,两边实时同步;安卓端与网页面同源。",
|
||||
"ver": "v0.1",
|
||||
"size": "—",
|
||||
"status": "待上架",
|
||||
"url": "",
|
||||
"repo": "https://github.com/example-org/family-todo"
|
||||
},
|
||||
{
|
||||
"id": "a2",
|
||||
"name": "Juno 简中语言包",
|
||||
"en": "JUNO ZH-CN",
|
||||
"type": "游戏汉化",
|
||||
"oss": true,
|
||||
"desc": "《Juno: New Origins》非官方简体中文语言包:9,271 条全量译文 + 配套字体 + 可复现的校验工具链。译文由 DeepSeek 生成,仅对该游戏版本做过测试。",
|
||||
"ver": "1.4.105.0c",
|
||||
"size": "9.4 MB",
|
||||
"status": "开源仓库",
|
||||
"url": "https://github.com/example-org/juno-zh-cn",
|
||||
"repo": "",
|
||||
"btn": "前往仓库 →"
|
||||
},
|
||||
{
|
||||
"id": "a3",
|
||||
"name": "自助模板渲染",
|
||||
"en": "TEMPLATE RENDER",
|
||||
"type": "渲染出图",
|
||||
"oss": false,
|
||||
"desc": "传皮肤、挑模板,渲染出成品大图(标准压缩 + 无压缩)。支持卡密下单与在线支付,下完自动排队出图。",
|
||||
"ver": "v1",
|
||||
"size": "—",
|
||||
"status": "在线",
|
||||
"url": "/order/",
|
||||
"repo": "",
|
||||
"web": true
|
||||
}
|
||||
],
|
||||
"linkGroups": [
|
||||
{
|
||||
"id": "video",
|
||||
"name": "视频",
|
||||
"en": "VIDEO"
|
||||
},
|
||||
{
|
||||
"id": "feed",
|
||||
"name": "图文",
|
||||
"en": "FEED"
|
||||
},
|
||||
{
|
||||
"id": "create",
|
||||
"name": "模型 / 创作",
|
||||
"en": "CREATE"
|
||||
},
|
||||
{
|
||||
"id": "oss",
|
||||
"name": "开源",
|
||||
"en": "OPEN SOURCE"
|
||||
},
|
||||
{
|
||||
"id": "used",
|
||||
"name": "小店",
|
||||
"en": "SHOP"
|
||||
},
|
||||
{
|
||||
"id": "contact",
|
||||
"name": "联系 / 其他",
|
||||
"en": "CONTACT"
|
||||
}
|
||||
],
|
||||
"links": [
|
||||
{
|
||||
"id": "bili",
|
||||
"group": "video",
|
||||
"key": "bili",
|
||||
"name": "哔哩哔哩",
|
||||
"en": "BILIBILI",
|
||||
"desc": "长视频",
|
||||
"url": "https://example.com/space"
|
||||
},
|
||||
{
|
||||
"id": "douyin",
|
||||
"group": "video",
|
||||
"key": "douyin",
|
||||
"name": "抖音",
|
||||
"en": "DOUYIN",
|
||||
"desc": "短视频",
|
||||
"url": "https://example.com/douyin"
|
||||
},
|
||||
{
|
||||
"id": "kuaishou",
|
||||
"group": "video",
|
||||
"key": "kuaishou",
|
||||
"name": "快手",
|
||||
"en": "KUAISHOU",
|
||||
"desc": "短视频",
|
||||
"url": "https://example.com/kuaishoutw"
|
||||
},
|
||||
{
|
||||
"id": "xiaohongshu",
|
||||
"group": "feed",
|
||||
"key": "xiaohongshu",
|
||||
"name": "小红书",
|
||||
"en": "REDNOTE",
|
||||
"desc": "图文 · 记录",
|
||||
"url": "https://example.com/xhs"
|
||||
},
|
||||
{
|
||||
"id": "cgmodel",
|
||||
"group": "create",
|
||||
"key": "cgmodel",
|
||||
"name": "CG模型网",
|
||||
"en": "CGMODEL",
|
||||
"desc": "3D模型 · 展示",
|
||||
"url": "https://example.com/cgmodel"
|
||||
},
|
||||
{
|
||||
"id": "codemao",
|
||||
"group": "create",
|
||||
"key": "codemao",
|
||||
"name": "编程猫社区",
|
||||
"en": "CODEMAO",
|
||||
"desc": "编程 · 作品集",
|
||||
"url": "https://example.com/codemao"
|
||||
},
|
||||
{
|
||||
"id": "steam",
|
||||
"group": "create",
|
||||
"key": "steam",
|
||||
"name": "Steam",
|
||||
"en": "STEAM",
|
||||
"desc": "壁纸引擎工坊",
|
||||
"url": "https://example.com/steam/"
|
||||
},
|
||||
{
|
||||
"id": "lang",
|
||||
"group": "oss",
|
||||
"key": "lang",
|
||||
"name": "Juno 简中语言包",
|
||||
"en": "JUNO ZH-CN",
|
||||
"desc": "游戏汉化 · 开源",
|
||||
"url": "https://github.com/example-org/juno-zh-cn"
|
||||
},
|
||||
{
|
||||
"id": "github",
|
||||
"group": "oss",
|
||||
"key": "github",
|
||||
"name": "GitHub",
|
||||
"en": "GITHUB",
|
||||
"desc": "开源",
|
||||
"url": "https://github.com/example-org"
|
||||
},
|
||||
{
|
||||
"id": "workshop",
|
||||
"group": "used",
|
||||
"key": "workshop",
|
||||
"name": "B站工坊",
|
||||
"en": "WORKSHOP",
|
||||
"desc": "模板定制 · 创意工坊 · 模型壁纸",
|
||||
"url": "https://example.com/workshop"
|
||||
},
|
||||
{
|
||||
"id": "xianyu",
|
||||
"group": "used",
|
||||
"key": "xianyu",
|
||||
"name": "闲鱼",
|
||||
"en": "GOOFISH",
|
||||
"desc": "模板定制 · 小店 · 工坊小物",
|
||||
"url": "https://example.com/xianyu"
|
||||
},
|
||||
{
|
||||
"id": "mail",
|
||||
"group": "contact",
|
||||
"key": "mail",
|
||||
"name": "邮箱",
|
||||
"en": "EMAIL",
|
||||
"desc": "feedback@example.com",
|
||||
"url": "mailto:feedback@example.com"
|
||||
}
|
||||
],
|
||||
"about": {
|
||||
"story": "「金钻」这名字,其实是一场小时候的误会。那会儿在《我的世界》里,钻石又硬又稀有,是我眼里最好用的矿物;又觉着现实里的黄金稀罕、不好置换。就这么一拍脑袋,把「游戏里最宝贝」和「现实里稀有」捏成了一个词——金钻。(如今倒是不怎么用「最」这个词了。)图标那抹彩色,是光的三原色和色彩的三原色——红黄蓝绿,凑到一块儿;从定下那天起就一直没改过,像把当年的心思原样锁在里头。回头再看:游戏里最强的早换成了下界合金,现实里比黄金稀少的金属也一抓一大把,毕竟人外有人、天外有天,很多东西的情况都是权衡来的。可这名字,是小时候的我起的——那就一直留着,延用下去吧。",
|
||||
"foot": "版权 © EXAMPLE.COM · 保留所有权利。金钻客栈为个人作品展示站;站外链接内容归各自平台与作者所有。",
|
||||
"cards": [
|
||||
{
|
||||
"k": "制作者",
|
||||
"h": "金钻",
|
||||
"p": "网站创作者 / 内容作者。画展、金钻宇宙、工具与开源内容与各平台入口的内容与设定都出自金钻。"
|
||||
},
|
||||
{
|
||||
"k": "网站构建",
|
||||
"h": "苏达 · 大肥鱼",
|
||||
"p": "苏达(Hermes 智能体)负责实现与部署;大肥鱼(DeepSeek Harness)协助页面核验与修复。前端为原生 HTML / CSS / JS 单文件,无构建工具。\n\n主站、自助模板渲染、待会儿办、本地开单后台共用同一套设计语言与动效规范;动效规范参考 Emil Kowalski 的 [skills](https://github.com/emilkowalski/skills)(MIT)。"
|
||||
},
|
||||
{
|
||||
"k": "图标库鸣谢",
|
||||
"h": "Lucide",
|
||||
"p": "全站线性图标来自 [Lucide](https://lucide.dev)(ISC License),以 inline `<symbol>` 方式内联,保持单文件、无外网依赖、24×24 线性 currentColor。"
|
||||
},
|
||||
{
|
||||
"k": "字体",
|
||||
"h": "OPPO Sans",
|
||||
"p": "正文使用 OPPO Sans(OPPO 免费商用字体),自托管 GB2312 子集 woff2(Regular / Bold);等宽字仍取系统字体栈。"
|
||||
},
|
||||
{
|
||||
"k": "像素字体",
|
||||
"h": "缝合像素字体",
|
||||
"p": "标题用的像素字是 TakWolf 的[缝合像素字体](https://github.com/TakWolf/fusion-pixel-font)(SIL OFL 1.1),只打包了页面上用到的字,协议原文在 `fonts/jz-pixel-OFL.txt`。"
|
||||
},
|
||||
{
|
||||
"k": "交流群",
|
||||
"h": "屑钻小窝",
|
||||
"p": "官方 QQ 群,群号 `123456789`。做图、下单、售后、闲聊都在这儿,欢迎来玩 —— [点这里加入 →](https://example.com/group-invite)"
|
||||
}
|
||||
]
|
||||
},
|
||||
"universe": {
|
||||
"items": [
|
||||
{
|
||||
"no": "0000",
|
||||
"name": "零号宇宙",
|
||||
"kind": "主宇宙",
|
||||
"tag": "晶钻超算主宇宙",
|
||||
"desc": "门户主宇宙,也是晶钻超算本体:把平行宇宙压成盘符,逐条演算多世界线。其余编号都是它演算出的分支世界线,零号自身负责总调度与收束。",
|
||||
"tags": [
|
||||
"门户主宇宙",
|
||||
"晶钻超算",
|
||||
"多世界线演算"
|
||||
],
|
||||
"look": {
|
||||
"style": "crystal",
|
||||
"accent": "#FFD36E",
|
||||
"enter": "zoom",
|
||||
"r": 2.6,
|
||||
"orbit": [
|
||||
0.0,
|
||||
0
|
||||
],
|
||||
"why": "晶钻超算:多面体切面像钻石,内部有发光的演算脉络。",
|
||||
"moons": [
|
||||
{
|
||||
"style": "crystal",
|
||||
"r": 0.45,
|
||||
"d": 5.0,
|
||||
"speed": 0.35,
|
||||
"colors": [
|
||||
"#BFF4FF",
|
||||
"#8E7BFF",
|
||||
"#FFE59A",
|
||||
"#FFFFFF"
|
||||
]
|
||||
},
|
||||
{
|
||||
"style": "rock",
|
||||
"r": 0.32,
|
||||
"d": 6.6,
|
||||
"speed": 0.22
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"no": "0001",
|
||||
"name": "火柴人宇宙",
|
||||
"kind": "原创",
|
||||
"tag": "火柴人的冒险",
|
||||
"desc": "金钻小时候在课上天马行空画出来的世界线,《火柴人的冒险》就从这里开始。",
|
||||
"tags": [
|
||||
"金钻原创",
|
||||
"小时候的课堂",
|
||||
"火柴人的冒险"
|
||||
],
|
||||
"look": {
|
||||
"style": "paper",
|
||||
"accent": "#F6F1E4",
|
||||
"enter": "push",
|
||||
"r": 1.25,
|
||||
"orbit": [
|
||||
20.0,
|
||||
0
|
||||
],
|
||||
"why": "小时候课上画出来的:米白纸面、铅笔等高线、暗面排线、几个红笔圈。",
|
||||
"moons": [
|
||||
{
|
||||
"style": "paper",
|
||||
"r": 0.36,
|
||||
"d": 2.6,
|
||||
"speed": 0.6,
|
||||
"colors": [
|
||||
"#FFF8EC",
|
||||
"#2B2E45",
|
||||
"#E5544B",
|
||||
"#F2C14D"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"no": "0002",
|
||||
"name": "极寒世界",
|
||||
"kind": "原创",
|
||||
"tag": "冰河时期",
|
||||
"desc": "2030年代确认北大西洋环流(AMOC)减弱、气候转入长期寒冷;2040年高含水彗星「那迦」撞击北大西洋,水汽化为冰晶云遮蔽日照,冰河期开始。故事发生在2056年,冰河已持续16年,地表约-50℃(极端-90℃)。人类转入五大地下深垒。",
|
||||
"tags": [
|
||||
"金钻原创",
|
||||
"冰河时期",
|
||||
"那迦彗星",
|
||||
"五大深垒",
|
||||
"2056"
|
||||
],
|
||||
"look": {
|
||||
"style": "ice",
|
||||
"accent": "#9FE3FF",
|
||||
"enter": "rise",
|
||||
"r": 1.35,
|
||||
"orbit": [
|
||||
29.0,
|
||||
1
|
||||
],
|
||||
"why": "冰河期地球:纬向冰带、厚极冠、冰裂纹;旁边那颗小卫星是「那迦」彗星残骸。",
|
||||
"moons": [
|
||||
{
|
||||
"style": "rock",
|
||||
"r": 0.3,
|
||||
"d": 2.7,
|
||||
"speed": 0.5,
|
||||
"colors": [
|
||||
"#CFE6FF",
|
||||
"#8FB4E0",
|
||||
"#5C79B8",
|
||||
"#FFFFFF"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"no": "0003",
|
||||
"name": "没落赛博城",
|
||||
"kind": "二创",
|
||||
"tag": "史蒂夫的探险之旅",
|
||||
"desc": "金钻刚接触动画时随手做的二创世界线:史蒂夫穿过没落的赛博城,一路探险。",
|
||||
"tags": [
|
||||
"二创",
|
||||
"史蒂夫的探险之旅",
|
||||
"赛博废墟"
|
||||
],
|
||||
"look": {
|
||||
"style": "neon",
|
||||
"accent": "#C9A6FF",
|
||||
"enter": "warp",
|
||||
"r": 1.4,
|
||||
"orbit": [
|
||||
38.0,
|
||||
2
|
||||
],
|
||||
"why": "没落的赛博城:深紫地表、霓虹街区网格、零星还亮着的窗灯。",
|
||||
"moons": [
|
||||
{
|
||||
"style": "rock",
|
||||
"r": 0.28,
|
||||
"d": 3.0,
|
||||
"speed": 0.42,
|
||||
"colors": [
|
||||
"#3A2F66",
|
||||
"#2A2350",
|
||||
"#1A1535",
|
||||
"#FF5FD2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"style": "neon",
|
||||
"r": 0.22,
|
||||
"d": 3.8,
|
||||
"speed": 0.3
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"no": "0004",
|
||||
"name": "善恶等级",
|
||||
"kind": "原创",
|
||||
"tag": "设定待定",
|
||||
"desc": "这条世界线的设定还在酝酿中,先留好位置,等金钻想清楚再填。",
|
||||
"tags": [
|
||||
"金钻原创",
|
||||
"设定酝酿中"
|
||||
],
|
||||
"look": {
|
||||
"style": "duality",
|
||||
"accent": "#FFD36E",
|
||||
"enter": "orbit",
|
||||
"r": 1.3,
|
||||
"orbit": [
|
||||
46.0,
|
||||
3
|
||||
],
|
||||
"why": "设定还在酝酿,先按名字「善恶」做成两半:一半金色白昼,一半紫色夜空,交界一条发光的波浪线。设定定了再换。",
|
||||
"moons": [
|
||||
{
|
||||
"style": "gas",
|
||||
"r": 0.34,
|
||||
"d": 2.8,
|
||||
"speed": 0.45,
|
||||
"colors": [
|
||||
"#FFF0C8",
|
||||
"#F2B84B",
|
||||
"#2D1E57",
|
||||
"#FFFFFF"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"empty": 6
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,96 @@
|
||||
Fusion Pixel Font
|
||||
https://github.com/TakWolf/fusion-pixel-font
|
||||
|
||||
Copyright (c) 2022, TakWolf (https://takwolf.com).
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,96 @@
|
||||
Fusion Pixel Font
|
||||
https://github.com/TakWolf/fusion-pixel-font
|
||||
|
||||
Copyright (c) 2022, TakWolf (https://takwolf.com).
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,64 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>画展 · 金钻客栈</title>
|
||||
<meta name="description" content="金钻的画、渲染图和视频,按时间排。">
|
||||
<meta name="theme-color" content="#FAFBFE">
|
||||
<meta name="theme-color" content="#0D1020" media="(max-width: 760px) and (prefers-color-scheme: dark)">
|
||||
<link rel="icon" href="assets/gem.webp" type="image/webp">
|
||||
<link rel="preload" href="fonts/OPPOSans-B.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="preload" href="fonts/fusion-pixel-12.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="stylesheet" href="assets/site.css?v=6">
|
||||
</head>
|
||||
<body data-page="gallery">
|
||||
<div class="jz-boot" id="jzBoot" aria-hidden="true"><div class="jz-boot-in"><canvas class="jz-boot-gem" width="168" height="168"></canvas><b class="jz-boot-name">金钻客栈</b><i class="jz-boot-bar"><i></i></i></div></div>
|
||||
<script>/* 加载动画:同一个标签页里只在第一次打开时放;系统要求「减少动效」就不放 */
|
||||
try{if(sessionStorage.getItem('jz-boot')||matchMedia('(prefers-reduced-motion: reduce)').matches){document.getElementById('jzBoot').remove()}else{document.documentElement.classList.add('booting')}}catch(e){document.getElementById('jzBoot').remove()}</script>
|
||||
<div class="orbs" aria-hidden="true"><i class="o1"></i><i class="o2"></i><i class="o3"></i><i class="o4"></i><i class="o5"></i></div>
|
||||
<header class="top"><div class="wrap top-in"><a class="brand" href="index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a><nav class="nav" aria-label="导航"><a href="index.html">首页</a><a href="gallery.html" aria-current="page">画展</a><a href="tools.html">工具与开源</a><a href="universe.html">金钻宇宙</a><a href="links.html">平台入口</a><a href="about.html">关于</a></nav><div class="desk-btn"><a class="btn-pill" href="/order/"><span class="ic" aria-hidden="true"></span>自助渲染<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></svg></a></div><a class="cms-ent" href="admin/" aria-label="内容管理" title="内容管理"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg></a></div></header>
|
||||
<main class="wrap">
|
||||
<div class="room-head"><div class="zone num" aria-hidden="true" style="--zc:#F2C14D;--zc2:#E8913A">01</div><div><h1>画展</h1><p>画的图、渲染图和视频,按时间排。</p></div><div class="meta"><b id="gN">0</b> 件<span id="gViews" hidden><br>看过 <b id="gViewsU">0</b> 人</span></div></div>
|
||||
<div class="tools-bar">
|
||||
<div class="seg crystal" role="group" aria-label="按类型筛选" id="gType"><button type="button" data-f="all" aria-pressed="true">全部<em id="cAll"></em></button><button type="button" data-f="image" aria-pressed="false">图片<em id="cImage"></em></button><button type="button" data-f="video" aria-pressed="false">视频<em id="cVideo"></em></button><button type="button" data-f="special" aria-pressed="false">特殊<em id="cSpecial"></em></button></div>
|
||||
<button type="button" class="btn btn-crystal btn-sm" id="gMore" aria-expanded="false" aria-controls="gMorePanel"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 5h18"/><path d="M6 12h12"/><path d="M10 19h4"/></svg>更多筛选</button>
|
||||
<button type="button" class="btn btn-crystal btn-sm" id="gSort" aria-pressed="true"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 4v16"/><path d="m3 16 4 4 4-4"/><path d="M17 20V4"/><path d="m21 8-4-4-4 4"/></svg><span>最新的在前</span></button>
|
||||
<button type="button" class="btn btn-crystal btn-sm" id="gClear" hidden>清除筛选</button>
|
||||
</div>
|
||||
<div class="g-more crystal" id="gMorePanel" hidden>
|
||||
<div class="g-more-row"><b>谁做的</b><div class="seg" role="group" aria-label="按制作者筛选" id="gOwner"><button type="button" data-o="all" aria-pressed="true">都看</button><button type="button" data-o="own" aria-pressed="false">金钻做的<em id="cOwn"></em></button><button type="button" data-o="gift" aria-pressed="false">别人送的<em id="cGift"></em></button></div></div>
|
||||
<div class="g-more-row"><b>看过的</b><div class="seg" role="group" aria-label="看过的作品怎么排" id="gSeen"><button type="button" data-s="off" aria-pressed="true">不区分</button><button type="button" data-s="first" aria-pressed="false">放前面</button><button type="button" data-s="last" aria-pressed="false">放后面</button><button type="button" data-s="hide" aria-pressed="false">不显示</button></div></div>
|
||||
<div class="g-more-row m-years"><b>年份</b><div class="seg" role="group" aria-label="按年份筛选" id="gYearsM"></div></div>
|
||||
</div>
|
||||
<div class="gal">
|
||||
<nav class="years" aria-label="年份" id="gYears"><b>年份</b></nav>
|
||||
<div><div class="wall" id="gWall"></div><p class="note">点开看大图。全景图可以拖着转一圈,动态壁纸可以拖时间轴。</p></div>
|
||||
</div>
|
||||
</main>
|
||||
<div class="gbox" id="gbox" role="dialog" aria-modal="true" aria-label="看作品" hidden>
|
||||
<div class="gbox-bar"><div class="gbox-t"><b id="gbT"></b><span id="gbD"></span></div><a class="btn btn-crystal btn-sm" id="gbOrig" href="#" target="_blank" rel="noopener" hidden>原图</a><a class="btn btn-crystal btn-sm" id="gbBili" href="#" target="_blank" rel="noopener noreferrer" hidden>去 B 站看</a><button type="button" class="btn btn-crystal btn-sm" id="gbClose"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="M6 6l12 12"/></svg>关闭</button></div>
|
||||
<div class="gbox-stage" id="gbStage">
|
||||
<img id="gbImg" alt="" hidden><span class="gbox-load" id="gbLoad" hidden>正在加载高清图…</span>
|
||||
<div class="gbox-vid" id="gbVidWrap" hidden><video id="gbVid" controls playsinline preload="metadata" controlslist="nodownload"></video><span class="v-wm" id="gbWm"></span></div>
|
||||
<iframe id="gbBiliFrame" hidden allow="fullscreen; autoplay" referrerpolicy="no-referrer" loading="lazy" title="B 站视频"></iframe>
|
||||
<canvas id="gbPano" hidden></canvas>
|
||||
<img id="gbWall" alt="" hidden draggable="false">
|
||||
</div>
|
||||
<div class="gbox-foot"><span class="gbox-hint" id="gbHint"></span><div class="gbox-wallbar" id="gbWallBar" hidden><button type="button" class="btn btn-crystal btn-sm" id="gbPlay" aria-label="播放 / 暂停">❚❚</button><input type="range" id="gbRange" min="0" max="0" value="0" aria-label="时间轴"><span id="gbLbl" class="num"></span></div><div class="g-links" id="gbLinks"></div></div>
|
||||
</div>
|
||||
<nav class="tabbar" aria-label="导航"><a href="index.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/><path d="M10 21v-6h4v6"/></svg><span>首页</span></a><a href="gallery.html" aria-current="page"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/></svg><span>画展</span></a><a class="mid" href="/order/"><i aria-hidden="true"></i><span>渲染</span></a><a href="universe.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="5"/><path d="M4.2 15.6c-1.6 2.5 4.2 2.4 9.6-.2s9-6.6 7.5-8.6c-.8-1-2.9-.9-5.4 0"/></svg><span>宇宙</span></a><button type="button" data-sheet="more" aria-expanded="false" aria-controls="more"><i class="ic-a"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3.5" y="3.5" width="7" height="7" rx="2"/><rect x="13.5" y="3.5" width="7" height="7" rx="2"/><rect x="3.5" y="13.5" width="7" height="7" rx="2"/><rect x="13.5" y="13.5" width="7" height="7" rx="2"/></svg></i><i class="ic-b"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="M6 6l12 12"/></svg></i><span class="lb-a">更多</span><span class="lb-b">收起</span></button></nav>
|
||||
<div class="sheet" id="more" hidden><div class="panel"><nav class="more-grid" aria-label="更多"><a href="tools.html" style="--zc:#4F86E8;--zc2:#2E5BD8"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg></i><span>工具与开源</span></a><a href="links.html" style="--zc:#22B573;--zc2:#3C8527"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg></i><span>平台入口</span></a><a href="about.html" style="--zc:#E0533D;--zc2:#E8913A"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg></i><span>关于</span></a></nav><p class="more-qq">QQ 群:屑钻小窝 123456789</p></div></div>
|
||||
<footer class="foot-site"><div class="wrap foot-in"><a class="brand" href="index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a></div></footer>
|
||||
<script src="assets/site-info.js?v=5"></script>
|
||||
<!-- 网站内容:内容后台发布时生成 content/site.js(window.JZ_CONTENT) -->
|
||||
<script src="content/site.js"></script>
|
||||
<script>/* 预览草稿:内容后台点「预览」会带 ?preview=1 打开;只有登录了内容后台的浏览器拿得到草稿(拿不到就还是正式内容) */
|
||||
if(/[?&]preview=1(&|$)/.test(location.search)) document.write('<script src="/order/api/cms/draft.js"><\/script>');</script>
|
||||
<script>window.__hdcEarly=(function(){try{return fetch("hd_cache/manifest.json",{cache:"force-cache"})}catch(e){return Promise.resolve(null)}})();</script>
|
||||
<script src="assets/pages.js?v=5"></script>
|
||||
<script src="assets/gallery.js?v=5"></script>
|
||||
<script src="assets/site.js?v=5"></script>
|
||||
<script src="assets/boot.js?v=5"></script>
|
||||
</body>
|
||||
</html>
|
||||
+39
-6663
File diff suppressed because one or more lines are too long
@@ -0,0 +1,37 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>平台入口 · 金钻客栈</title>
|
||||
<meta name="description" content="金钻在各个平台的主页:视频、图文、模型、开源、小店和邮箱。">
|
||||
<meta name="theme-color" content="#FAFBFE">
|
||||
<meta name="theme-color" content="#0D1020" media="(max-width: 760px) and (prefers-color-scheme: dark)">
|
||||
<link rel="icon" href="assets/gem.webp" type="image/webp">
|
||||
<link rel="preload" href="fonts/OPPOSans-B.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="preload" href="fonts/fusion-pixel-12.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="stylesheet" href="assets/site.css?v=6">
|
||||
</head>
|
||||
<body data-page="links">
|
||||
<div class="jz-boot" id="jzBoot" aria-hidden="true"><div class="jz-boot-in"><canvas class="jz-boot-gem" width="168" height="168"></canvas><b class="jz-boot-name">金钻客栈</b><i class="jz-boot-bar"><i></i></i></div></div>
|
||||
<script>/* 加载动画:同一个标签页里只在第一次打开时放;系统要求「减少动效」就不放 */
|
||||
try{if(sessionStorage.getItem('jz-boot')||matchMedia('(prefers-reduced-motion: reduce)').matches){document.getElementById('jzBoot').remove()}else{document.documentElement.classList.add('booting')}}catch(e){document.getElementById('jzBoot').remove()}</script>
|
||||
<div class="orbs" aria-hidden="true"><i class="o1"></i><i class="o2"></i><i class="o3"></i><i class="o4"></i><i class="o5"></i></div>
|
||||
<header class="top"><div class="wrap top-in"><a class="brand" href="index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a><nav class="nav" aria-label="导航"><a href="index.html">首页</a><a href="gallery.html">画展</a><a href="tools.html">工具与开源</a><a href="universe.html">金钻宇宙</a><a href="links.html" aria-current="page">平台入口</a><a href="about.html">关于</a></nav><div class="desk-btn"><a class="btn-pill" href="/order/"><span class="ic" aria-hidden="true"></span>自助渲染<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></svg></a></div><a class="cms-ent" href="admin/" aria-label="内容管理" title="内容管理"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg></a></div></header>
|
||||
<main class="wrap">
|
||||
<div class="room-head"><div class="zone num" aria-hidden="true" style="--zc:#22B573;--zc2:#3C8527">04</div><div><h1>平台入口</h1><p>金钻在这些平台都有号,点一下就打开。</p></div><div class="meta"><b id="lN">0</b> 个</div></div>
|
||||
<div class="board crystal" id="lBoard"></div>
|
||||
</main>
|
||||
<nav class="tabbar" aria-label="导航"><a href="index.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/><path d="M10 21v-6h4v6"/></svg><span>首页</span></a><a href="gallery.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/></svg><span>画展</span></a><a class="mid" href="/order/"><i aria-hidden="true"></i><span>渲染</span></a><a href="universe.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="5"/><path d="M4.2 15.6c-1.6 2.5 4.2 2.4 9.6-.2s9-6.6 7.5-8.6c-.8-1-2.9-.9-5.4 0"/></svg><span>宇宙</span></a><button type="button" data-sheet="more" aria-expanded="false" aria-controls="more"><i class="ic-a"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3.5" y="3.5" width="7" height="7" rx="2"/><rect x="13.5" y="3.5" width="7" height="7" rx="2"/><rect x="3.5" y="13.5" width="7" height="7" rx="2"/><rect x="13.5" y="13.5" width="7" height="7" rx="2"/></svg></i><i class="ic-b"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="M6 6l12 12"/></svg></i><span class="lb-a">更多</span><span class="lb-b">收起</span></button></nav>
|
||||
<div class="sheet" id="more" hidden><div class="panel"><nav class="more-grid" aria-label="更多"><a href="tools.html" style="--zc:#4F86E8;--zc2:#2E5BD8"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg></i><span>工具与开源</span></a><a href="links.html" aria-current="page" style="--zc:#22B573;--zc2:#3C8527"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg></i><span>平台入口</span></a><a href="about.html" style="--zc:#E0533D;--zc2:#E8913A"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg></i><span>关于</span></a></nav><p class="more-qq">QQ 群:屑钻小窝 123456789</p></div></div>
|
||||
<footer class="foot-site"><div class="wrap foot-in"><a class="brand" href="index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a></div></footer>
|
||||
<script src="assets/site-info.js?v=5"></script>
|
||||
<!-- 网站内容:内容后台发布时生成 content/site.js(window.JZ_CONTENT) -->
|
||||
<script src="content/site.js"></script>
|
||||
<script>/* 预览草稿:内容后台点「预览」会带 ?preview=1 打开;只有登录了内容后台的浏览器拿得到草稿(拿不到就还是正式内容) */
|
||||
if(/[?&]preview=1(&|$)/.test(location.search)) document.write('<script src="/order/api/cms/draft.js"><\/script>');</script>
|
||||
<script src="assets/pages.js?v=5"></script>
|
||||
<script src="assets/site.js?v=5"></script>
|
||||
<script src="assets/boot.js?v=5"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,142 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<meta name="robots" content="noindex">
|
||||
<meta name="theme-color" content="#FAFBFE">
|
||||
<title>金钻客栈 · 维护中</title>
|
||||
<link rel="icon" href="/assets/gem.webp" type="image/webp">
|
||||
<style>
|
||||
/* 金钻客栈 · 维护页(2026-10-06):「钻石在打磨中」
|
||||
一把像素钻石镐抬起 → 敲一下钻石 → 钻石被敲得一扁一弹(Q 弹)→ 迸出几粒光谱色的像素火花 → 一道白光扫过;
|
||||
下面一排 MC 方块进度条,每敲一下多亮一格,满了闪一下光谱色再重来。点一下钻石也会自己敲一下。
|
||||
动画都是 CSS(一轮 2.4 秒);脚本只管进度条跟拍子、点钻石敲一下、读群号;系统要求「减少动效」就全部静止。 */
|
||||
@font-face{font-family:'Fusion Pixel';src:url('/fonts/fusion-pixel-12.woff2') format('woff2');font-display:swap}
|
||||
:root{--ink:#1E2440;--ink-2:#4A5070;--ink-3:#737891;--bg:#FAFBFE;--mc:#3C8527;--mc-hi:#5BAA3C;--mc-lo:#1D4D13;
|
||||
--spec:linear-gradient(90deg,#FF9BB0 0%,#FFCC7A 25%,#94E3B4 50%,#8CC8FF 75%,#B9A2FF 100%);
|
||||
--pixel:'Fusion Pixel','PingFang SC','Microsoft YaHei',sans-serif;--T:2.4s}
|
||||
*{box-sizing:border-box}
|
||||
html,body{height:100%;margin:0}
|
||||
body{min-height:100%;display:flex;align-items:center;justify-content:center;padding:24px 16px;overflow:hidden;color:var(--ink);
|
||||
font:15px/1.7 'OPPO Sans',-apple-system,'PingFang SC','Microsoft YaHei',sans-serif;-webkit-font-smoothing:antialiased;background:var(--bg)}
|
||||
/* 背后几团慢慢漂的彩光(白光藏色) */
|
||||
.orbs{position:fixed;inset:-20%;z-index:-1;pointer-events:none}
|
||||
.orbs i{position:absolute;width:60vmax;height:60vmax;border-radius:50%;opacity:.55;animation:drift 18s ease-in-out infinite alternate}
|
||||
.orbs i:nth-child(1){left:-10%;top:-10%;background:radial-gradient(circle,rgba(255,182,204,.8),transparent 65%)}
|
||||
.orbs i:nth-child(2){right:-15%;top:5%;background:radial-gradient(circle,rgba(160,206,255,.8),transparent 65%);animation-duration:22s}
|
||||
.orbs i:nth-child(3){left:20%;bottom:-25%;background:radial-gradient(circle,rgba(170,238,204,.75),transparent 65%);animation-duration:26s}
|
||||
@keyframes drift{to{transform:translate(8vw,6vh) scale(1.1)}}
|
||||
|
||||
.card{position:relative;width:100%;max-width:440px;padding:30px 28px 26px;text-align:center;border-radius:12px;
|
||||
border:2px solid rgba(255,255,255,.95);background:linear-gradient(160deg,rgba(255,255,255,.86),rgba(255,255,255,.62));
|
||||
box-shadow:inset 0 0 0 1px rgba(30,36,64,.05),0 26px 50px -30px rgba(80,100,170,.5);
|
||||
-webkit-backdrop-filter:blur(10px) saturate(1.3);backdrop-filter:blur(10px) saturate(1.3)}
|
||||
|
||||
/* ---------- 打磨台:钻石 + 镐 + 火花 ---------- */
|
||||
.forge{position:relative;width:180px;height:150px;margin:0 auto 6px;cursor:pointer;-webkit-tap-highlight-color:transparent;outline:none}
|
||||
.forge .halo{position:absolute;left:50%;top:58px;width:120px;height:120px;margin:-60px 0 0 -60px;border-radius:50%;
|
||||
background:radial-gradient(circle,rgba(255,255,255,.95) 0%,rgba(166,213,255,.45) 38%,rgba(205,185,255,.18) 58%,transparent 72%);animation:halo var(--T) ease-in-out infinite}
|
||||
.forge .ring{position:absolute;left:50%;top:58px;width:104px;height:104px;margin:-52px 0 0 -52px;border-radius:50%;padding:2px;
|
||||
background:conic-gradient(from 0deg,#FFB3C3,#FFD99A,#A9EBC6,#A6D5FF,#CDB9FF,#FFB3C3);
|
||||
-webkit-mask:linear-gradient(#000 0 0) content-box,linear-gradient(#000 0 0);-webkit-mask-composite:xor;mask:linear-gradient(#000 0 0) content-box exclude,linear-gradient(#000 0 0);
|
||||
opacity:.55;animation:spin 14s linear infinite}
|
||||
.forge .floor{position:absolute;left:50%;bottom:10px;width:70px;height:10px;margin-left:-35px;border-radius:50%;background:rgba(30,36,64,.14);filter:blur(2px);animation:floor var(--T) ease-in-out infinite}
|
||||
/* 钻石:平时轻轻漂浮;被敲那一下先扁后弹,最后落定 */
|
||||
.gem{position:absolute;left:50%;top:22px;width:72px;height:72px;margin-left:-36px;animation:float var(--T) ease-in-out infinite}
|
||||
.gem img{display:block;width:72px;height:72px;image-rendering:pixelated;transform-origin:50% 90%;animation:squash var(--T) cubic-bezier(.3,0,.3,1) infinite;
|
||||
filter:drop-shadow(-5px 9px 9px rgba(255,110,140,.25)) drop-shadow(5px 9px 9px rgba(70,140,255,.25))}
|
||||
/* 敲完一道白光斜着扫过钻石(只扫钻石的形状:用钻石图当遮罩) */
|
||||
.gem::after{content:"";position:absolute;inset:0;-webkit-mask:url('/assets/gem.webp') center/contain no-repeat;mask:url('/assets/gem.webp') center/contain no-repeat;
|
||||
background:linear-gradient(115deg,transparent 35%,rgba(255,255,255,.95) 50%,transparent 65%) no-repeat;background-size:260% 100%;background-position:120% 0;animation:glint var(--T) ease-out infinite}
|
||||
/* 像素钻石镐:绕握把末端转,抬起 → 猛地敲下 → 回弹 */
|
||||
/* 钻石镐:Minecraft 原版 16×16 物品图(assets/diamond-pickaxe.png),一格像素放大成 3px;
|
||||
平时就是原版图标的样子(0°、整像素对齐),只在挥的时候绕柄尾(左下角那格)转;顺时针转 = 往钻石那边砸 */
|
||||
.pick{position:absolute;left:22px;top:-17px;width:48px;height:48px;transform-origin:8px 43px;animation:swing var(--T) cubic-bezier(.5,0,.2,1) infinite}
|
||||
.pick img{display:block;width:48px;height:48px;image-rendering:pixelated;image-rendering:crisp-edges;filter:drop-shadow(1px 3px 2px rgba(30,36,64,.25))}
|
||||
/* 火花:五粒光谱色像素,敲中时迸出去、划个弧落下 */
|
||||
.spark{position:absolute;left:61px;top:23px;width:6px;height:6px;opacity:0;animation:spark var(--T) cubic-bezier(.2,.7,.4,1) infinite}
|
||||
.spark:nth-of-type(1){background:#FF8FAB;--dx:-30px;--dy:-26px}
|
||||
.spark:nth-of-type(2){background:#FFC24D;--dx:-6px;--dy:-44px;width:5px;height:5px}
|
||||
.spark:nth-of-type(3){background:#6FDB9A;--dx:22px;--dy:-36px}
|
||||
.spark:nth-of-type(4){background:#6FB8FF;--dx:-38px;--dy:-6px;width:4px;height:4px}
|
||||
.spark:nth-of-type(5){background:#B496FF;--dx:34px;--dy:-14px;width:4px;height:4px}
|
||||
|
||||
@keyframes spin{to{transform:rotate(360deg)}}
|
||||
@keyframes float{0%,100%{transform:translateY(0)}25%{transform:translateY(-6px)}}
|
||||
/* 一轮 2.4s:0% 原版图标的样子 → 28% 往后抡起 → 36–38% 砸下、镐尖碰到钻石顶(敲中)→ 弹开、落回 0° */
|
||||
@keyframes swing{0%{transform:rotate(0)}28%{transform:rotate(-38deg)}36%{transform:rotate(16deg)}38%{transform:rotate(14deg)}47%{transform:rotate(4deg)}56%,100%{transform:rotate(0)}}
|
||||
@keyframes squash{0%,37%{transform:scale(1,1)}40%{transform:scale(1.14,.82)}46%{transform:scale(.92,1.1)}53%{transform:scale(1.04,.97)}60%,100%{transform:scale(1,1)}}
|
||||
@keyframes spark{0%,37%{opacity:0;transform:translate(0,0)}39%{opacity:1;transform:translate(calc(var(--dx)*.25),calc(var(--dy)*.4))}58%{opacity:1;transform:translate(var(--dx),var(--dy))}74%{opacity:0;transform:translate(calc(var(--dx)*1.3),calc(var(--dy)*.2 + 26px))}100%{opacity:0}}
|
||||
@keyframes glint{0%,42%{background-position:120% 0}64%,100%{background-position:-20% 0}}
|
||||
@keyframes halo{0%,37%,100%{transform:scale(1);opacity:.9}42%{transform:scale(1.14);opacity:1}}
|
||||
@keyframes floor{0%,100%{transform:scale(1);opacity:1}25%{transform:scale(.82);opacity:.7}40%{transform:scale(1.12);opacity:1}}
|
||||
|
||||
/* ---------- 字 ---------- */
|
||||
h1{margin:4px 0 2px;font:400 36px/1.2 var(--pixel);letter-spacing:.04em;-webkit-font-smoothing:none}
|
||||
.tag{display:inline-flex;align-items:center;gap:8px;height:28px;padding:0 12px;border-radius:4px;background:rgba(255,255,255,.75);
|
||||
box-shadow:inset 0 0 0 1px rgba(30,36,64,.06);font-size:13px;font-weight:700;color:var(--ink-2);margin-bottom:14px}
|
||||
.dots i{font-style:normal;animation:dot 1.2s steps(1) infinite}
|
||||
.dots i:nth-child(2){animation-delay:.2s}.dots i:nth-child(3){animation-delay:.4s}
|
||||
@keyframes dot{0%,100%{opacity:.15}40%{opacity:1}}
|
||||
p{margin:0 0 4px;color:var(--ink-2)}
|
||||
|
||||
/* ---------- MC 方块进度条:每敲一下亮一格,满了闪一下光谱色再从头来 ---------- */
|
||||
.blocks{display:grid;grid-template-columns:repeat(8,1fr);gap:4px;margin:20px auto 18px;max-width:300px;padding:5px;border-radius:6px;
|
||||
background:rgba(30,36,64,.06);box-shadow:inset 0 2px 0 rgba(30,36,64,.08)}
|
||||
.blocks i{height:18px;border-radius:2px;background:#E9ECF4;box-shadow:inset 0 2px 0 #fff,inset 0 -3px 0 #C9CDD8;transition:background .12s,box-shadow .12s}
|
||||
.blocks i.on{background:var(--mc);box-shadow:inset 0 2px 0 var(--mc-hi),inset 0 -3px 0 var(--mc-lo);animation:pop .3s cubic-bezier(.34,1.56,.64,1)}
|
||||
@keyframes pop{0%{transform:scale(.6)}100%{transform:scale(1)}}
|
||||
.blocks.flash i{animation:rainbow .6s ease}
|
||||
.blocks.flash i:nth-child(8n+1){--c:#FF9BB0}.blocks.flash i:nth-child(8n+2){--c:#FFB98A}.blocks.flash i:nth-child(8n+3){--c:#FFCC7A}.blocks.flash i:nth-child(8n+4){--c:#94E3B4}
|
||||
.blocks.flash i:nth-child(8n+5){--c:#7FD6C8}.blocks.flash i:nth-child(8n+6){--c:#8CC8FF}.blocks.flash i:nth-child(8n+7){--c:#A6A9FF}.blocks.flash i:nth-child(8n+8){--c:#B9A2FF}
|
||||
@keyframes rainbow{0%,60%{background:var(--c);box-shadow:inset 0 2px 0 rgba(255,255,255,.7),inset 0 -3px 0 rgba(30,36,64,.15);transform:translateY(-3px)}100%{transform:none}}
|
||||
|
||||
small{display:block;margin-top:4px;color:var(--ink-3);font-size:12.5px}
|
||||
|
||||
@media (max-width:420px){.card{padding:26px 18px 22px}h1{font-size:30px}}
|
||||
@media (prefers-reduced-motion:reduce){*,*::before,*::after{animation:none !important}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="orbs" aria-hidden="true"><i></i><i></i><i></i></div>
|
||||
<main class="card">
|
||||
<div class="forge" id="forge" role="img" aria-label="金钻正在打磨钻石(点一下也能帮忙敲一下)" tabindex="0">
|
||||
<span class="halo"></span><span class="ring"></span><span class="floor"></span>
|
||||
<div class="gem"><img src="/assets/gem.webp" alt="" width="72" height="72"></div>
|
||||
<i class="spark"></i><i class="spark"></i><i class="spark"></i><i class="spark"></i><i class="spark"></i>
|
||||
<div class="pick" aria-hidden="true"><img src="/assets/diamond-pickaxe.png" alt="" width="48" height="48"></div>
|
||||
</div>
|
||||
<h1>金钻客栈</h1>
|
||||
<div class="tag">正在打磨中<span class="dots" aria-hidden="true"><i>.</i><i>.</i><i>.</i></span></div>
|
||||
<p>网站在升级,稍后就回来。</p>
|
||||
<p>你的订单和作品都不受影响。</p>
|
||||
<div class="blocks" id="blocks" aria-hidden="true"><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div>
|
||||
<small id="qq">如有急事,可通过平时联系我的渠道找到我</small>
|
||||
</main>
|
||||
<script src="/assets/site-info.js"></script>
|
||||
<script>
|
||||
(function () {
|
||||
/* 群号从站点信息读(有就写上) */
|
||||
var S = window.JZ_SITE; if (S && S.qq) document.getElementById('qq').textContent = '有急事来 QQ 群找金钻:' + (S.qqName || '') + ' ' + S.qq;
|
||||
/* 进度条:跟着镐的节奏走 —— 镐每转一轮(animationiteration)在敲中那一刻(第 38%)亮一格;第 9 下整排闪一下光谱色、清空重来 */
|
||||
var bl = document.getElementById('blocks'), cells = bl.querySelectorAll('i'), pick = document.querySelector('.pick'), n = 0, T = 2400;
|
||||
function hit() {
|
||||
if (n >= cells.length) { bl.classList.remove('flash'); void bl.offsetWidth; bl.classList.add('flash'); [].forEach.call(cells, function (c) { c.classList.remove('on'); }); n = 0; return; }
|
||||
cells[n++].classList.add('on');
|
||||
}
|
||||
function loop() { setTimeout(hit, T * .38); }
|
||||
loop(); pick.addEventListener('animationiteration', loop);
|
||||
/* 点一下钻石:它自己也被敲一下(重放一次扁 → 弹 + 火花) */
|
||||
var f = document.getElementById('forge'), img = f.querySelector('.gem img'), sp = f.querySelectorAll('.spark');
|
||||
function tap() {
|
||||
if (matchMedia('(prefers-reduced-motion: reduce)').matches) return;
|
||||
var a = img.animate([{ transform: 'scale(1,1)' }, { transform: 'scale(1.16,.8)', offset: .2 }, { transform: 'scale(.9,1.12)', offset: .5 }, { transform: 'scale(1.04,.97)', offset: .75 }, { transform: 'scale(1,1)' }], { duration: 480, easing: 'cubic-bezier(.3,0,.3,1)', composite: 'replace' });
|
||||
[].forEach.call(sp, function (s) { var cs = getComputedStyle(s); s.animate([{ opacity: 1, transform: 'translate(0,0)' }, { opacity: 1, transform: 'translate(calc(' + cs.getPropertyValue('--dx') + '),' + cs.getPropertyValue('--dy') + ')', offset: .55 }, { opacity: 0, transform: 'translate(calc(' + cs.getPropertyValue('--dx') + ' * 1.3),30px)' }], { duration: 620, easing: 'cubic-bezier(.2,.7,.4,1)' }); });
|
||||
}
|
||||
f.addEventListener('click', tap);
|
||||
f.addEventListener('keydown', function (e) { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); tap(); } });
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,38 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>工具与开源 · 金钻客栈</title>
|
||||
<meta name="description" content="金钻做的小工具和开源项目。">
|
||||
<meta name="theme-color" content="#FAFBFE">
|
||||
<meta name="theme-color" content="#0D1020" media="(max-width: 760px) and (prefers-color-scheme: dark)">
|
||||
<link rel="icon" href="assets/gem.webp" type="image/webp">
|
||||
<link rel="preload" href="fonts/OPPOSans-B.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="preload" href="fonts/fusion-pixel-12.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="stylesheet" href="assets/site.css?v=6">
|
||||
</head>
|
||||
<body data-page="tools">
|
||||
<div class="jz-boot" id="jzBoot" aria-hidden="true"><div class="jz-boot-in"><canvas class="jz-boot-gem" width="168" height="168"></canvas><b class="jz-boot-name">金钻客栈</b><i class="jz-boot-bar"><i></i></i></div></div>
|
||||
<script>/* 加载动画:同一个标签页里只在第一次打开时放;系统要求「减少动效」就不放 */
|
||||
try{if(sessionStorage.getItem('jz-boot')||matchMedia('(prefers-reduced-motion: reduce)').matches){document.getElementById('jzBoot').remove()}else{document.documentElement.classList.add('booting')}}catch(e){document.getElementById('jzBoot').remove()}</script>
|
||||
<div class="orbs" aria-hidden="true"><i class="o1"></i><i class="o2"></i><i class="o3"></i><i class="o4"></i><i class="o5"></i></div>
|
||||
<header class="top"><div class="wrap top-in"><a class="brand" href="index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a><nav class="nav" aria-label="导航"><a href="index.html">首页</a><a href="gallery.html">画展</a><a href="tools.html" aria-current="page">工具与开源</a><a href="universe.html">金钻宇宙</a><a href="links.html">平台入口</a><a href="about.html">关于</a></nav><div class="desk-btn"><a class="btn-pill" href="/order/"><span class="ic" aria-hidden="true"></span>自助渲染<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></svg></a></div><a class="cms-ent" href="admin/" aria-label="内容管理" title="内容管理"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg></a></div></header>
|
||||
<main class="wrap">
|
||||
<div class="room-head"><div class="zone num" aria-hidden="true" style="--zc:#4F86E8;--zc2:#2E5BD8">02</div><div><h1>工具与开源</h1><p>金钻做的小工具。开源的可以去看代码。</p></div><div class="meta"><b id="tN">0</b> 个</div></div>
|
||||
<div class="tools-bar"><div class="seg crystal" role="group" aria-label="按类型筛选" id="tSeg"></div></div>
|
||||
<div id="tRows"></div>
|
||||
</main>
|
||||
<nav class="tabbar" aria-label="导航"><a href="index.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/><path d="M10 21v-6h4v6"/></svg><span>首页</span></a><a href="gallery.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/></svg><span>画展</span></a><a class="mid" href="/order/"><i aria-hidden="true"></i><span>渲染</span></a><a href="universe.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="5"/><path d="M4.2 15.6c-1.6 2.5 4.2 2.4 9.6-.2s9-6.6 7.5-8.6c-.8-1-2.9-.9-5.4 0"/></svg><span>宇宙</span></a><button type="button" data-sheet="more" aria-expanded="false" aria-controls="more"><i class="ic-a"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3.5" y="3.5" width="7" height="7" rx="2"/><rect x="13.5" y="3.5" width="7" height="7" rx="2"/><rect x="3.5" y="13.5" width="7" height="7" rx="2"/><rect x="13.5" y="13.5" width="7" height="7" rx="2"/></svg></i><i class="ic-b"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="M6 6l12 12"/></svg></i><span class="lb-a">更多</span><span class="lb-b">收起</span></button></nav>
|
||||
<div class="sheet" id="more" hidden><div class="panel"><nav class="more-grid" aria-label="更多"><a href="tools.html" aria-current="page" style="--zc:#4F86E8;--zc2:#2E5BD8"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg></i><span>工具与开源</span></a><a href="links.html" style="--zc:#22B573;--zc2:#3C8527"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg></i><span>平台入口</span></a><a href="about.html" style="--zc:#E0533D;--zc2:#E8913A"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg></i><span>关于</span></a></nav><p class="more-qq">QQ 群:屑钻小窝 123456789</p></div></div>
|
||||
<footer class="foot-site"><div class="wrap foot-in"><a class="brand" href="index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a></div></footer>
|
||||
<script src="assets/site-info.js?v=5"></script>
|
||||
<!-- 网站内容:内容后台发布时生成 content/site.js(window.JZ_CONTENT) -->
|
||||
<script src="content/site.js"></script>
|
||||
<script>/* 预览草稿:内容后台点「预览」会带 ?preview=1 打开;只有登录了内容后台的浏览器拿得到草稿(拿不到就还是正式内容) */
|
||||
if(/[?&]preview=1(&|$)/.test(location.search)) document.write('<script src="/order/api/cms/draft.js"><\/script>');</script>
|
||||
<script src="assets/pages.js?v=5"></script>
|
||||
<script src="assets/site.js?v=5"></script>
|
||||
<script src="assets/boot.js?v=5"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,79 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>金钻宇宙 · 金钻客栈</title>
|
||||
<meta name="description" content="金钻编的平行世界:每一条世界线是一个星系,点开看设定。">
|
||||
<meta name="theme-color" content="#FAFBFE">
|
||||
<meta name="theme-color" content="#0D1020" media="(max-width: 760px) and (prefers-color-scheme: dark)">
|
||||
<link rel="icon" href="assets/gem.webp" type="image/webp">
|
||||
<link rel="preload" href="fonts/OPPOSans-B.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="preload" href="fonts/fusion-pixel-12.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="stylesheet" href="assets/site.css?v=6">
|
||||
<link rel="stylesheet" href="assets/universe/universe-page.css?v=5">
|
||||
<script type="importmap">{"imports":{"three":"./assets/vendor/three.module.min.js"}}</script>
|
||||
</head>
|
||||
<body data-page="universe" class="uni">
|
||||
<div class="jz-boot" id="jzBoot" aria-hidden="true"><div class="jz-boot-in"><canvas class="jz-boot-gem" width="168" height="168"></canvas><b class="jz-boot-name">金钻客栈</b><i class="jz-boot-bar"><i></i></i></div></div>
|
||||
<script>/* 加载动画:同一个标签页里只在第一次打开时放;系统要求「减少动效」就不放 */
|
||||
try{if(sessionStorage.getItem('jz-boot')||matchMedia('(prefers-reduced-motion: reduce)').matches){document.getElementById('jzBoot').remove()}else{document.documentElement.classList.add('booting')}}catch(e){document.getElementById('jzBoot').remove()}</script>
|
||||
<div class="orbs" aria-hidden="true"><i class="o1"></i><i class="o2"></i><i class="o3"></i><i class="o4"></i><i class="o5"></i></div>
|
||||
<header class="top"><div class="wrap top-in"><a class="brand" href="index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a><nav class="nav" aria-label="导航"><a href="index.html">首页</a><a href="gallery.html">画展</a><a href="tools.html">工具与开源</a><a href="universe.html" aria-current="page">金钻宇宙</a><a href="links.html">平台入口</a><a href="about.html">关于</a></nav><div class="desk-btn"><a class="btn-pill" href="/order/"><span class="ic" aria-hidden="true"></span>自助渲染<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></svg></a></div><a class="cms-ent" href="admin/" aria-label="内容管理" title="内容管理"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg></a></div></header>
|
||||
<main class="wrap">
|
||||
<div class="room-head"><div class="zone num" aria-hidden="true" style="--zc:#9A6BE0;--zc2:#3FC9C4">03</div><div><h1>金钻宇宙</h1><p>金钻编的平行世界,每一条是一个星系。点星系或者下面的卡片,飞过去看设定。</p></div><div class="meta"></div></div>
|
||||
<section class="skywin" id="skywin" aria-label="金钻宇宙星系图"><div class="stage" id="uStage"><canvas id="uGl" tabindex="0" aria-label="星系图:每条世界线是一个星系,点名牌或星球打开档案;下面的卡片可以做同样的事"></canvas><div class="labels" id="uLabels"></div><div class="hud" id="uHud"><span>世界线<b id="uAll">11</b></span><span>已点亮<b id="uLit">5</b></span><span>空槽<b id="uEmpty">6</b></span></div><aside class="panel" id="uPanel" aria-live="polite"></aside><div class="ctl"><button class="btn" id="uBack" type="button">回到星系图</button><button class="btn" id="uFull" type="button" aria-pressed="false">全屏</button></div><p class="tip">点星系看档案 · 拖动转视角 · Ctrl + 滚轮缩放</p><div class="ugate" id="uGate" aria-hidden="true"><div class="ugate-core"><span class="ugate-ring r1"></span><span class="ugate-ring r2"></span><span class="ugate-ring r3"></span><i class="gem-img"></i></div>
|
||||
<div class="ugate-txt"><b>金钻宇宙</b><span id="uGateMsg">正在打开星门…</span></div><div class="ugate-slots" id="uGateSlots"></div></div></div></section>
|
||||
<p class="sky-hint">在星图里拖动是转视角、双指缩放;要翻页,在星图外面滑</p>
|
||||
<h2 class="row-title">世界线档案</h2>
|
||||
<div class="uni-list" id="uniList"></div>
|
||||
<div class="uslots" aria-label="空槽" id="uniSlots"></div>
|
||||
</main>
|
||||
<nav class="tabbar" aria-label="导航"><a href="index.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/><path d="M10 21v-6h4v6"/></svg><span>首页</span></a><a href="gallery.html"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/></svg><span>画展</span></a><a class="mid" href="/order/"><i aria-hidden="true"></i><span>渲染</span></a><a href="universe.html" aria-current="page"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="5"/><path d="M4.2 15.6c-1.6 2.5 4.2 2.4 9.6-.2s9-6.6 7.5-8.6c-.8-1-2.9-.9-5.4 0"/></svg><span>宇宙</span></a><button type="button" data-sheet="more" aria-expanded="false" aria-controls="more"><i class="ic-a"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3.5" y="3.5" width="7" height="7" rx="2"/><rect x="13.5" y="3.5" width="7" height="7" rx="2"/><rect x="3.5" y="13.5" width="7" height="7" rx="2"/><rect x="13.5" y="13.5" width="7" height="7" rx="2"/></svg></i><i class="ic-b"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="M6 6l12 12"/></svg></i><span class="lb-a">更多</span><span class="lb-b">收起</span></button></nav>
|
||||
<div class="sheet" id="more" hidden><div class="panel"><nav class="more-grid" aria-label="更多"><a href="tools.html" style="--zc:#4F86E8;--zc2:#2E5BD8"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg></i><span>工具与开源</span></a><a href="links.html" style="--zc:#22B573;--zc2:#3C8527"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg></i><span>平台入口</span></a><a href="about.html" style="--zc:#E0533D;--zc2:#E8913A"><i><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg></i><span>关于</span></a></nav><p class="more-qq">QQ 群:屑钻小窝 123456789</p></div></div>
|
||||
<footer class="foot-site"><div class="wrap foot-in"><a class="brand" href="index.html"><i class="gem-img" aria-hidden="true"></i><b>金钻客栈</b></a></div></footer>
|
||||
<script src="assets/site-info.js?v=5"></script>
|
||||
<!-- 网站内容:内容后台发布时生成 content/site.js(window.JZ_CONTENT) -->
|
||||
<script src="content/site.js"></script>
|
||||
<script>/* 预览草稿:内容后台点「预览」会带 ?preview=1 打开;只有登录了内容后台的浏览器拿得到草稿(拿不到就还是正式内容) */
|
||||
if(/[?&]preview=1(&|$)/.test(location.search)) document.write('<script src="/order/api/cms/draft.js"><\/script>');</script>
|
||||
<script src="assets/universe/config.js?v=5"></script>
|
||||
<script src="assets/pages.js?v=5"></script>
|
||||
<script src="assets/site.js?v=5"></script>
|
||||
<script src="assets/boot.js?v=5"></script>
|
||||
<script src="assets/universe/gate.js?v=5"></script>
|
||||
<script type="module">
|
||||
import { mountGalaxy } from './assets/universe/galaxy.js?v=5';
|
||||
const $ = id => document.getElementById(id), CFG = window.JZ_UNIVERSE;
|
||||
const win = $('skywin'), stage = $('uStage');
|
||||
const mob = () => innerWidth < 760, full = () => win.classList.contains('full');
|
||||
let api, cur = null;
|
||||
// 手机上档案卡也在星图窗里(底部抽屉),星球挪到上半个窗:一眼同时看到星球和档案
|
||||
function mark(no) { document.querySelectorAll('.ucell,.uslots button').forEach(b => b.setAttribute('aria-current', String(b.dataset.no === no))); }
|
||||
try {
|
||||
api = mountGalaxy({ stage, canvas: $('uGl'), labels: $('uLabels'), panel: $('uPanel'), back: $('uBack'), hud: $('uHud'),
|
||||
layout: () => mob() ? { x: 0, y: 0.26 } : { x: 0.17, y: 0 },
|
||||
wheelZoom: () => full(),
|
||||
onReady: () => window.JZGate && window.JZGate.open(), // 第一帧画好:星门打开,镜头接着俯冲进来
|
||||
// start:开始飞(列表马上高亮、旧的档案先收起);arrive:镜头快到了(档案这时才出来,和星球落定同步)
|
||||
onFocus: u => { cur = u; mark(u ? u.no : null); },
|
||||
counts: (a, l, e) => { $('uAll').textContent = a; $('uLit').textContent = l; $('uEmpty').textContent = e; } });
|
||||
} catch (e) { window.JZGate && window.JZGate.fail('这台设备打不开 3D 星图(' + e.message + '),下面的档案照样能看'); }
|
||||
// 深链:universe.html#0001 → 星系图好了就飞过去(旧的单页地址 /#0001 也会跳到这里)
|
||||
const deep = (location.hash || '').replace(/^#/, '');
|
||||
if (api && /^\d{4}$/.test(deep)) setTimeout(() => api.fly(deep), 900);
|
||||
// 点下面的卡片:先把窗户滚到眼前,再飞过去
|
||||
document.querySelectorAll('.ucell,.uslots button').forEach(b => b.addEventListener('click', () => {
|
||||
if (!api) return;
|
||||
win.scrollIntoView({ block: 'center', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });
|
||||
setTimeout(() => api.fly(b.dataset.no), 350);
|
||||
}));
|
||||
// 全屏:窗户铺满屏幕(滚轮直接缩放;手机上档案卡变成底部抽屉)
|
||||
const fb = $('uFull');
|
||||
function setFull(on) { win.classList.toggle('full', on); document.body.classList.toggle('sky-full', on); fb.textContent = on ? '退出全屏' : '全屏';
|
||||
fb.setAttribute('aria-pressed', String(on)); api && api.resize(); }
|
||||
fb.addEventListener('click', () => setFull(!full()));
|
||||
addEventListener('keydown', e => { if (e.key === 'Escape' && full() && !cur) setFull(false); });
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+460
@@ -0,0 +1,460 @@
|
||||
# 金钻客栈 · 2026-10 总交接文档(前端 + 后端)
|
||||
|
||||
> 这一份把 2026-10-05 这一轮**前后端所有改动**、**功能增删**、**设计规范**、**业务逻辑**和**部署运维**写在一处。
|
||||
> 细节文档还在各自目录里(位置见第 1 节),这份是总目录 + 总说明。
|
||||
>
|
||||
> 占位值一律保持原样:`example.com` / `shop.example.com`、`123456789`、`备案号(已移除)`、`(本机路径)`、`<DATA_DIR>` / `<APP_DIR>` / `<WORKER_DIR>` / `<WIN-PATH>` 等。
|
||||
> 署名不动(「苏达 · 大肥鱼」)。本文不含任何密钥、真实地址或截图。
|
||||
|
||||
---
|
||||
|
||||
## 目录
|
||||
|
||||
1. [仓库里有什么](#1-仓库里有什么)
|
||||
2. [变更清单(按提交)](#2-变更清单按提交)
|
||||
3. [功能增加 / 删除一览](#3-功能增加--删除一览)
|
||||
4. [⚠️ 接口与数据格式变更(单独列)](#4-️-接口与数据格式变更单独列)
|
||||
5. [设计规范](#5-设计规范)
|
||||
6. [业务逻辑](#6-业务逻辑)
|
||||
7. [部署与运维](#7-部署与运维)
|
||||
8. [测试与验证](#8-测试与验证)
|
||||
9. [已知未验证 / 待确认](#9-已知未验证--待确认)
|
||||
10. [内容后台(2026-10-05 晚实现)](#10-内容后台2026-10-05-晚实现)
|
||||
|
||||
---
|
||||
|
||||
## 1. 仓库里有什么
|
||||
|
||||
| 目录 / 文件 | 是什么 | 细节文档 |
|
||||
|---|---|---|
|
||||
| `portal/` | 门户(整个网站):`index.html` 首页、`gallery.html` 画展、`tools.html` 工具与开源、`universe.html` 金钻宇宙、`links.html` 平台入口、`about.html` 关于(**2026-10-06 起是多页,样子以设计预览站为准**)+ `assets/` `fonts/` `content/` `admin/` | 本文第 2.7、5、6 节;`portal/assets/universe/交接说明.md`(星系图) |
|
||||
| `order/` | 自助模板渲染(下单页)`index.html` + `skincheck.js` | 本文第 6.2 节 |
|
||||
| `backend/backend-site/` | 网站后端:`server.py`(全部服务端逻辑)、`store.py`(数据库)、`admin.py`(命令行管理)、`pngcheck.py`(PNG 结构核验)、`tests/` | `backend/backend-site/交接说明.md`、`回执-Claude.md` |
|
||||
| `backend/backend-tools/` | 店主电脑上的一整套:渲染机 `ys_worker.py`、开单后台 `ys_admin.py`、本机开单 `ys_local.py` + `local.html`、Blender 出图脚本 `make_order.py`、各种启动脚本 | `backend/backend-tools/交接说明.md`、`回执-Claude.md` |
|
||||
| `backend/模板/` | 三个 Blender 模板工程(测试用) | `backend/模板/说明.md` |
|
||||
| `backend/deploy/` | 反向代理路由与限流片段 | `backend/deploy/nginx-片段.md` |
|
||||
| `backend/他应该知道的.md` | 生意背景 / 机器约束 / 数据边界 / 术语表 | — |
|
||||
| `交接说明.md`(根目录) | 11eb16c 那一轮视觉改版的说明(**部分已过时**,以本文为准) | — |
|
||||
|
||||
---
|
||||
|
||||
## 2. 变更清单(按提交)
|
||||
|
||||
时间顺序。哈希以 `git log` 为准。
|
||||
|
||||
### 2.1 `11eb16c` · 前端 2026 改版「白光藏色 × MC 方块」
|
||||
|
||||
- 删掉上一轮的暗色覆盖块 `redesign-2026`(反馈不好看)。
|
||||
- 两页 `</body>` 前新增 `<!-- jz-2026:start -->…<!-- jz-2026:end -->`:手机底栏 HTML + `<style id="jz-2026">` + `<script id="jz-2026-js">`;下单页 `<body>` 开头另加一段跟门户一样的顶栏。
|
||||
- 浅色配色、流动淡彩背景(WebGL,降级为静态渐变)、MC 方块按钮、像素标题字(缝合像素字体子集,OFL)。
|
||||
- 门户顶栏加「自助渲染」入口;手机端底部物品栏导航 + 「更多」面板(像开关一样再点就收)。
|
||||
- 下单页页头改版;四段进度条 `.prog` 用 CSS 隐藏(DOM 和逻辑都还在)。
|
||||
- 修了「工具与开源」卡片正文被挤成一指宽的问题。
|
||||
- 这一轮**没改**任何原有 `<script>` / `<style>` 块(逐块比对过)。详见根目录 `交接说明.md`。
|
||||
|
||||
### 2.2 `651d21d` · 后端复查修复 + 回执
|
||||
|
||||
外部复查找到的问题,按会丢钱 / 丢数据的先修:
|
||||
|
||||
| 问题 | 改法 |
|
||||
|---|---|
|
||||
| 同一张码并发提交能成两单 | 查码和绑码放进同一把锁(`redeem_bind`) |
|
||||
| 卡密规则只信前端报的张数 | 按 `max(前端张数, 实际模板数)` 和模板并集校验;不认识的模板 key 直接拒 |
|
||||
| 爱发电回调重放 / 改单号能多发码、多激活 | 处理过的平台单号一律原样回;回调和账本读写串行(`HOOK_LOCK`) |
|
||||
| `admin.py` 和服务器同时改 `codes.json` 互相覆盖(实测 200 张丢 185 张) | `LOCK` 加跨进程 `flock`;写文件用唯一临时名 + `fsync` |
|
||||
| `sweep` 会删掉还在排队 / 等确认的单 | 只清走完流程的单 |
|
||||
| 卡密 / 单号 / 取件码用 `random` 生成(可预测) | 改 `secrets` |
|
||||
| 重渲换皮肤不过 PNG 核验 | 走同一套核验 |
|
||||
| 反馈接口能灌爆磁盘和通知 | 限频 + 磁盘闸 + 只收图片 |
|
||||
| 下载整个读进内存 | 边读边发;zip 同一时间只打一个 |
|
||||
| 部分失败静默标「已完成」 | 记 `partial`,通知店主,页面说实话 |
|
||||
| `H.finish` 和框架方法重名 | 改名 `finish_upload`(接口路径不变) |
|
||||
| 本机开单工具接受任意来源的 POST | 只认本机页面(Host / Origin 校验) |
|
||||
|
||||
附 `tests/回执复现测试.py`(27 条;原版 13 条失败,改后全过)。
|
||||
|
||||
### 2.3 `51212a0` · 接入 SQLite + 开单后台重写
|
||||
|
||||
- 新增 `store.py`:卡密 / 订单信息 / 爱发电账本 / 呼叫记录 / 小块状态进 `<DATA_DIR>/ys.db`;第一次启动自动建库并导入旧 JSON(旧文件不动)。
|
||||
- `server.py` / `admin.py` 的存取换到库上,路由逻辑不变;`calls.jsonl` 照旧追加(手机通知读它)。
|
||||
- 管理接口新增 `calls` / `call-done` / `retry`,`codes` 加 `q` 搜索。
|
||||
- `admin.py db check / backup / export`。
|
||||
- `ys_admin.py`(开单后台)页面按功能重写:待处理 / 订单 / 卡密 / 福利券 / 呼叫·反馈 / 开单工具。
|
||||
- 新增 `tests/数据库测试.py`(现编假数据)。
|
||||
|
||||
### 2.4 `3ae940d` · 本机开单页面重写
|
||||
|
||||
`backend-tools/local.html` 换成跟网站 / 后台同一套样子;补上原来没写样式的分辨率选择、没绑事件的「清空」;整页接收拖拽;按勾选顺序标号;预计耗时。`ys_local.py` 没动。
|
||||
|
||||
### 2.5 `09b229d` · 金钻宇宙换成星系图 + 推送前审查
|
||||
|
||||
- 门户「金钻宇宙」板块:**删掉**启动仪式、宇宙首屏晶体、盘符机架、读盘舱;**换成**星系图(three.js,懒加载)+ 窗下世界线卡片。
|
||||
- 世界线数据只剩一份:`portal/assets/universe/config.js`(主脚本也读它)。
|
||||
- 像素字子集按新文字重做(并保留了原来所有字)。
|
||||
- 审查修掉的后端问题:`add_call` 写库失败会打断渲染机回传;多进程同时首启会重复导入呼叫记录;撤销「处理过了」没清时间。数据库测试加一条,共 38 条。
|
||||
- 本文档。
|
||||
|
||||
### 2.6 内容后台 + 新世界线自动排位 + 星球预设
|
||||
|
||||
- **内容后台**(第 10 节):网站上所有展示内容在网页后台里改 —— 账号密码登录(首次 `admin/admin` 强制改密)、草稿自动保存、预览、发布、回滚、画展传图。
|
||||
后端 `backend-site/cms.py`(挂在 `server.py` 的 `/api/cms/*`),页面 `portal/admin/`,命令行 `admin.py user …`。
|
||||
- **门户 / 下单页改成读内容文件**:`portal/content/site.js`(`window.JZ_CONTENT`)、`order/content/order.js`(`window.JZ_ORDER`),后台发布时生成;代码里写死的数据降级为兜底。
|
||||
- 门户顶栏最右边加内容后台入口:一个不带字的淡色铅笔图标(无边框,hover 稍亮)。
|
||||
- **星系图排布** `layout.js`:新点亮的世界线自动排到中圈不挤的位置,补给线接到附近更靠里的星(不穿星);空槽按编号固定在外圈;**新加一条,已有的星和线都不动**。
|
||||
- **星球预设**从 7 种加到 18 种:类地(卡通地球)/ 海洋 / 丛林 / 荒漠 / 冻原 / 熔岩 / 毒雾 / 荒芜岩球 / 冰巨星 / 带环巨星(光环只有这个预设才有)。
|
||||
- 星图名牌 / 档案卡的文字一律转义(内容来自后台,不能当 HTML 拼)。
|
||||
- 新增 `tests/内容后台测试.py`(78 条);端到端浏览器流程 36 条(第 8 节)。
|
||||
- 推送后全量细审又修了:部署漏配(没设 `YS_PORTAL_DIR` / 缺 `content/site.json`)时内容后台拒绝工作,不会建空的第一版、一发布清空网站;同时最多 2 个 scrypt 在算(内存上限 256M);登录冷却记录定期清理;发布冲突给「丢掉我的草稿 / 用我的覆盖」二选一(原来会卡死在冲突里);草稿没存上、还有图在上传时不让发布;价格 / 付款文件只在这次真改了才写(不覆盖 `admin.py price` 的改动);排位在世界线很多时分档放宽、40 条也不重叠;删掉门户里旧启动仪式留下的死数据。
|
||||
|
||||
### 2.7 2026-10-06 · 全站按设计预览站重做 + 加载动画 + 宇宙开场星门 + 内容后台接住真实画展
|
||||
|
||||
- **门户从单页(`#/板块` 切换)改成六个独立页面**,标记、样式、交互全部照设计预览站(http://161.33.11.66/):
|
||||
`index / gallery / tools / universe / links / about.html`,共用 `assets/site.css`(预览站原样式 + 末尾一段正式站补充)、`assets/site.js`(预览站原交互:流动背景、视差、卡片倾斜、滚动浮现、翻牌、手机「更多」)。
|
||||
内容照旧全部读 `content/site.js`(内容后台发布的),由 `assets/pages.js` 按预览站的标记填进去;画展的真功能在 `assets/gallery.js`。
|
||||
- **画展**(`gallery.js`):样子是预览站的作品墙 + 年份栏 + 白色毛玻璃大图层;原来的功能一样没少 ——
|
||||
类型 / 谁做的 / 年份→月份筛选、最新 / 最早排序、看过的放前 / 放后 / 不显示、hd_cache 先轻后重的高清、本站 mp4(优先网页版副本)、B 站播放器、全景球面环视、动态壁纸时间轴、观展统计 `/hit` + `view_stats.json`、作品外链。
|
||||
作品墙改成 JS 按「最矮的一列」投放(预览站用 CSS 分栏,330 件时顺序会竖着走)。
|
||||
- **旧地址兼容**:`/#/gallery`、`/#/apps`、`/#/universe`、`/#0001` 等会自动跳到新页面(`universe.html#0001` 打开就飞到那条世界线)。
|
||||
- **加载动画(新)** `assets/boot.js`:像素钻石一块块从底往上垒成形 → 白光扫过 →「金钻客栈」逐字弹出 → 光谱进度条跟真实加载走 → 幕布上收。只在同一个标签页第一次打开时放、最少 1.25 秒、最多等 3 秒、点一下可跳过、「减少动效」时不放。
|
||||
- **金钻宇宙开场(新)** `assets/universe/gate.js`:three.js 下载 / 星系生成期间,星图窗里是一道「星门」(钻石 + 三圈光谱环 + 一排世界线格子按编号点亮);星系第一帧画好就光环外炸、格子散开、淡出,接上星系图自己的镜头俯冲。打不开 3D 时停在说明文字上。
|
||||
- **站点固定信息只放一处**:`portal/assets/site-info.js`(`window.JZ_SITE`:域名 / QQ 群号 / 群名 / 加群链接 / 备案号 / 反馈邮箱)。门户六页、下单页、关于页都读它。
|
||||
**仓库里是占位;正式服务器上只替换这一个文件**(以前要在好几个页面里改,容易漏 —— 10-06 就漏过)。
|
||||
- **下单页**对齐预览站:全站同一个顶栏 / 底栏 / 页脚、宽版面、落地页改成「怎么下单?」两张路卡 + 「下过单了?」条 + 模板样图(用 400px 的 jpg)+ 分辨率;之后的步骤卡片照预览站的晶体面板。**按钮 id、下单逻辑、接口一个没动**(新样式在 `<style id="jz-site">`,放在 jz-2026 块后面)。
|
||||
- **像素字体换成更全的子集** `portal/fonts/fusion-pixel-12.woff2`(114KB:ASCII + 常用 3755 字 + 当前全部内容;下单页也用这一份),删了旧的 `jz-pixel-12.woff2`。
|
||||
- **内容后台能原样接住真实画展**(`cms.py`):文件名带空格、本站 mp4 视频(不填 B 站链接)+ `web` 网页版副本、作品外链 `link` / `links`、离线缩略图索引 `media`、世界线 `tone` / `sector` / `media` —— 以前校验时会报错或悄悄丢掉;`site_payload` 把 `media` 一起写进 `site.js`(以前一发布就丢缩略图,画展会直接拉几百张原图)。测试 +8(86 条)。
|
||||
|
||||
### 2.8 2026-10-06 晚 · 五个修复 + 点击光效回归 + 手机深色模式 + 维护页
|
||||
|
||||
- 下单页模板样图按原图 1:1 显示。
|
||||
- 全景 / 动态壁纸:拖着拖出画框外松手,不会再被当成「点空白处」把大图关掉(按下和松手都在空白处才关)。
|
||||
- 画展长图(宽高比 0.45 那种)在大图里整张放得下(按视口高度限,网格行高 auto 时百分比 max-height 不生效);列表缩略图还没下完时大图先铺缩略图。
|
||||
- 点击光效:门户各页不加点击光效;下单页用它原来那套(按下发光、面板染色、邻按钮照亮)。(10-06 晚加过一版全站「彩虹边缘光段 + Q 弹」`fx.js`,店主看了说不要,已删。)
|
||||
- **手机深色模式**:系统设成深色时,手机宽度(≤760px)整站换夜间版(门户六页、画展大图、宇宙页、加载动画、下单页、流动背景着色器 `uDark`);电脑宽度保持浅色。要让电脑也跟随,把 `site.css` / 下单页 `jz-site` 里那段媒体查询的 `(max-width:760px) and` 去掉,`site.js` 里 `mqDark` 同步改。
|
||||
- **维护页** `portal/maintenance.html`:「钻石在打磨中」—— 钻石镐用 Minecraft 原版 16×16 物品图(`portal/assets/diamond-pickaxe.png`,取自 Minecraft Wiki,版权归 Mojang;本站是非官方粉丝向站点,别拿它做商品图),平时就是原版图标的样子(0°、3px 一格),挥的时候抡起、镐尖敲钻石、钻石一扁一弹、光谱像素火花、白光扫过;MC 方块进度条每敲一下亮一格、满了闪光谱色重来;点钻石也会敲一下。上维护:服务器上 `cp /var/www/jinzuan/index.html /var/backups/jinzuan/index.html.<日期>` 备份,再 `cp /var/www/jinzuan/maintenance.html /var/www/jinzuan/index.html`;撤维护:把备份拷回来。**别把备份留在网站目录里**(见 2.9)。
|
||||
|
||||
### 2.9 2026-10-06 · 安全审计与加固
|
||||
|
||||
- **爱发电回调防投毒**:这个地址谁都能 POST。没经开放接口验证的报文(没付款 / 查不到)**不再写进账本** `pay_orders`,只进 kv `hook_unverified`(最近 50 条、字段截断)供人工核对;回调日志只记关键头 + 正文前 4KB,5MB 轮转。nginx 给两个回调地址单独限流(20 次/分)+ 报文上限 64KB。测试 +2。
|
||||
- **福利券领取令牌**改成定长比较;**本机开单后台** `ys_admin.py` 的转义连引号一起转;星门格子提示文字转义;首页价格改读公开接口 `/order/api/payinfo`。
|
||||
- **nginx**(`/etc/nginx/sites-available/family-todo`,备份 `.bak-20261006-pre-security`):
|
||||
- 安全头:`snippets/jz-sec-base.conf`(HSTS / nosniff / X-Frame-Options / Referrer-Policy / Permissions-Policy,全站含待会儿办、隧道入口)、`snippets/jz-sec-csp.conf`(CSP,只给门户 / 下单页 / 内容后台)。⚠️ nginx 的 `add_header` 不继承:**新加的 location 只要写了 add_header,就要在里面再 `include` 这两个**(隧道 / 待会儿办只 include base)。
|
||||
- 挡掉:`*.bak*` `*.maint*` `*.old*` `*.v3-live-*` 之类备份、`preview-*.html`、隐藏文件(`.well-known` 照常)、内容后台原始文件 `content/site.json` / `order/content/order.json`(含「隐藏」的作品、付款设置;页面读的是 site.js / order.js)。
|
||||
- `server_tokens off`(不再暴露 nginx 版本)。
|
||||
- **网站目录里的 35 个备份 / 旧版 / 预览稿**挪到 `/var/backups/jinzuan/webroot-old-20261006/`(没删)。以后备份一律放 `/var/backups/jinzuan/`。
|
||||
- 复查过没问题的:SQL 全参数化;订单号路由 `[A-Z0-9]+` 且先查库再拼路径;渲染机回传文件名过滤;下单 / 反馈 / 呼叫限频 + 长度上限 + 磁盘水位;内容后台 https-only、Cookie `HttpOnly; SameSite=Strict; Secure`、CSRF + 同源、首次强制改密、服务端校验所有字段;公网只开 22 / 80 / 443(阿里云安全组);SSH 只认密钥 + fail2ban;数据目录 750。
|
||||
- **待定**:内容后台还是初始 `admin/admin`(尽快改);主机防火墙没开(8018 待会儿办、1Panel、docker 等监听 0.0.0.0,只靠安全组挡)。
|
||||
|
||||
---
|
||||
|
||||
## 3. 功能增加 / 删除一览
|
||||
|
||||
### 增加
|
||||
|
||||
| 在哪 | 功能 |
|
||||
|---|---|
|
||||
| 门户 · 金钻宇宙 | 星系图:旋臂星系 + 星云 + 扇区 + 补给线;每条世界线一颗卡通星球(材质按设定:晶体 / 铅笔纸面 / 冰封 / 霓虹 / 善恶两半);点星系或下面卡片飞过去,档案卡和星球同时落定;五种运镜(推进 / 放大 / 升空俯冲 / 跃迁 / 绕行);全屏;`#0001` 深链可分享 |
|
||||
| 门户 · 全站 | 「自助渲染」入口;手机底部物品栏 + 「更多」面板;流动淡彩背景 |
|
||||
| 下单页 | 跟门户一致的顶栏 / 底栏 |
|
||||
| 后端 | SQLite 数据库(自动建库、自动导入、导出回退、热备份、体检) |
|
||||
| 后端 · 管理接口 | 呼叫记录列表、标「处理过了」、失败单退回重渲、卡密搜索 |
|
||||
| 开单后台 | 待处理首页(要动手的事集中在一页)、订单搜索、卡密搜索 / 停用 / 启用 / 改张数、订单备注、呼叫·反馈页、失败单「退回重渲」按钮 |
|
||||
| 本机开单 | 分辨率选择样式、清空、整页拖拽、出图顺序标号、预计耗时、复制买家说明 |
|
||||
| **内容后台**(新) | 账号密码登录、首次强制改密、草稿 / 预览 / 发布 / 回滚、发布记录、操作日志、登录设备管理;可改:首页文案与公告、板块说明、画展(含传图)、工具与开源、金钻宇宙(档案 + 外观)、平台入口、关于、下单页模板上下架 / 名字 / 说明、页头与公告、价格档位、付款方式 |
|
||||
| 门户 / 下单页 | 读后台发布的内容;首页公告条(可设起止日期);`?preview=1` 预览草稿(只有登录的人看得到) |
|
||||
| 金钻宇宙 | 新世界线自动排位与连线;星球预设 18 种 |
|
||||
|
||||
### 删除
|
||||
|
||||
| 在哪 | 删了什么 | 为什么 |
|
||||
|---|---|---|
|
||||
| 门户 · 金钻宇宙 | 启动仪式(逐字 / 权限扫描 / 欢迎)、宇宙首屏晶体线框(`CrystalView`)、盘符机架(抽插 / 拖拽 / 导轨)、读盘舱(特写弹窗 / 拆解 / 翻页)、两枚只给插卡用的图标(白标 `--icd-logo`、火柴人 `--icd-people`)、相关 CSS | 被星系图取代;店主说机架「丑死了」 |
|
||||
| 门户 · 装饰 | 英文 kicker、遥测数字条、时钟、`LINK // 已同步`(CSS 隐藏,DOM 还在) | 文案要说人话 |
|
||||
| 下单页 | 四段进度条(CSS 隐藏,逻辑还在) | 店主觉得难看 |
|
||||
| 前端 | 上一轮暗色覆盖块 `redesign-2026` | 不好看 |
|
||||
|
||||
保留:首页右侧晶钻徽记、`#0001` / `#rack` 旧链接(分别飞到那条世界线 / 打开宇宙板块)。
|
||||
|
||||
---
|
||||
|
||||
## 4. ⚠️ 接口与数据格式变更(单独列)
|
||||
|
||||
> 规矩:动了接口路径、请求 / 响应字段、数据格式的,必须单独标出来 —— 渲染机是另一台机器上的另一份代码,两边对不上会静默出不来图。
|
||||
|
||||
| 类别 | 变更 | 影响谁 |
|
||||
|---|---|---|
|
||||
| **数据格式** | 卡密 / 订单信息 / 爱发电账本 / 呼叫记录 / 小块状态从 JSON 文件挪进 `<DATA_DIR>/ys.db`。第一次启动自动导入,旧文件原样留着;`admin.py db export` 能导回旧格式 | 服务器、`admin.py`。**渲染机不受影响** |
|
||||
| 新增接口 | `GET /api/admin/calls`、`POST /api/admin/call-done`、`POST /api/admin/retry` | 开单后台(新按钮要它们:**服务器先升级**) |
|
||||
| 接口加参数 | `GET /api/admin/codes?q=`(可选,不传和以前一样) | 开单后台 |
|
||||
| 新增字段 | `/api/claim` 回的订单里多一个 `terms_v`(只增不减) | 渲染机可以不理 |
|
||||
| 开单后台本机接口 | 新增 `/api/codes` `/api/calls` `/api/retry` `/api/note` `/api/code-edit` `/api/call-done`(都要 PIN,原样转服务器) | 只有面板页面自己用 |
|
||||
| 前端 | 门户的 `#rack` / `#bay` DOM 与 `window.__icd.open/close/flip/tray` 调试钩子删了;新增 `window.__jzUniverse.show()/fly(no)` | 只有页面自己和自动化脚本 |
|
||||
| **新增接口** | `/api/cms/*`(登录 / 内容 / 草稿 / 发布 / 回滚 / 传图 / 预览),见 `cms.py` 开头;nginx 要加一节(`deploy/nginx-片段.md` ④) | 只有内容后台页面 |
|
||||
| **数据格式** | 库里新增 `cms_users` / `cms_sessions` / `cms_draft` / `cms_versions` / `cms_audit` 五张表(启动时自动建);新增内容文件 `portal/content/site.{json,js}`、`order/content/order.{json,js}`;画展上传的图在 `portal/uploads/` | 服务器、门户、下单页 |
|
||||
| 文件被谁写 | `prices.json` / `payinfo.json` 现在也由内容后台发布时写(**格式不变**,别的字段原样保留;只有这次发布真改了价格 / 付款才写)。`admin.py price` 还能用,但建议统一在后台改 | 服务器 |
|
||||
| 前端 | 门户读 `window.JZ_CONTENT`、下单页读 `window.JZ_ORDER`(读不到用内置兜底);下单页 `TEMPLATES` 拆成 `TEMPLATES_ALL`(全部,用于显示老订单)和 `TEMPLATES`(上架的) | 页面自己 |
|
||||
|
||||
**没变**:所有买家接口、渲染机接口的路径和字段;本机开单的本机接口。
|
||||
|
||||
---
|
||||
|
||||
## 5. 设计规范
|
||||
|
||||
### 5.1 一句话
|
||||
|
||||
**白光藏色 × Minecraft 方块**:一眼看过去是白的,颜色藏在亮部和缓慢流动的淡彩光里;按钮是 MC Ore UI 那种方块按钮;标题用像素字;正文用 OPPO Sans。
|
||||
|
||||
### 5.2 颜色 token(门户 / 下单页写在 `jz-2026` 块的 `:root`;后台 / 本机开单各自复制一份)
|
||||
|
||||
| 用途 | 变量 | 值 |
|
||||
|---|---|---|
|
||||
| 页面底色 | `--bg` | `#F5F7FB` |
|
||||
| 正文墨色(深→浅) | `--ink` / `--txt` · `--txt-2` · `--txt-3` · `--txt-4` | `#1E2440` · `#454B6B` · `#676D8A` · `#858AA2` |
|
||||
| 发丝线 | `--line` / `--line-soft` | `rgba(30,36,64,.12)` / `.08` |
|
||||
| 主色(草方块绿) | `--mc-green` / `-hi` / `-lo` | `#3C8527` / `#5BAA3C` / `#1D4D13` |
|
||||
| 次按钮(石头白) | `--stone` / `--stone-lo` / `--stone-edge` | `#F3F4F6` / `#B4B7BE` / `#9EA2AA` |
|
||||
| 面板 | `--panel-shadow` + 半透明白 | `inset 0 1px 0 #fff, 0 22px 44px -28px rgba(100,110,190,.38)`;底 `rgba(255,255,255,.74~.9)`,2px 白边 |
|
||||
| 警告 / 错误文字 | `--warn-t` / `--bad-t` | `#9A6A0C` / `#B33A2E` |
|
||||
| 首页板块卡的「矿石色」 | `--zc` | 画展金 `#F2C14D`、工具蓝 `#4F86E8`、宇宙紫 `#9A6BE0`、平台绿、关于红(只在悬停时从边缘亮出来) |
|
||||
| 背景彩光 | `body::before` 四团 radial-gradient | 天蓝 / 粉 / 杏 / 薄荷,透明度 .22~.30;有 WebGL 时换成 `#jzBg` 流动彩光 |
|
||||
| 星系图(唯一的深色区域) | `config.js → GALAXY.colors` | 深海军蓝 `#070B1C` + 蓝紫星云 + 一点青 + 暖金 `#FFD36E`(名牌 / 数字) |
|
||||
|
||||
### 5.3 字体
|
||||
|
||||
- **标题**:缝合像素字体 12px(TakWolf,SIL OFL 1.1),子集 `portal/fonts/fusion-pixel-12.woff2`(门户和下单页共用;ASCII + GB2312 一级常用 3755 字 + 当前全部内容,114KB),协议原文 `portal/fonts/fusion-pixel-OFL.txt`。12 的整数倍字号最清楚,`-webkit-font-smoothing:none`。
|
||||
- **正文**:OPPO Sans(可免费商用)。
|
||||
- 常用字都在子集里,一般不用管;**用到生僻字(不在 3755 常用字里)才要重做子集**,否则那几个字会掉回正文字体:
|
||||
```
|
||||
# 文本 = 旧子集里已有的字 ∪ 页面 + config.js + galaxy.js 里所有字(只加不减)
|
||||
python3 -m fontTools.subset fusion-pixel-12px-proportional-zh_hans.otf.woff2 \
|
||||
--text-file=字表.txt --flavor=woff2 --layout-features='*' --no-hinting --output-file=portal/fonts/fusion-pixel-12.woff2
|
||||
```
|
||||
源字体从 fusion-pixel-font 的 release 取(12px proportional zh_hans)。
|
||||
|
||||
### 5.4 组件
|
||||
|
||||
| 组件 | 规则 |
|
||||
|---|---|
|
||||
| 按钮 | **全站统一一种**:MC 方块,`border-radius:4px`,2px 边,上亮下暗的内阴影;按下下沉 2px。绿 = 主操作,石头白 = 次操作,红字 = 危险操作(注销 / 停用 / 收摊) |
|
||||
| 卡片 / 面板 | 半透明白 + 2px 白边 + `--panel-shadow`,圆角 8px(大块 12px)。**只有吸顶顶栏用 `backdrop-filter`**,面板不用(卡、而且显得死板) |
|
||||
| 标签 / 状态 | 色块小标签(4px 圆角、浅底深字):绿 = 通过 / 已完成,黄 = 注意,红 = 失败,蓝 = 进行中,灰 = 停用 |
|
||||
| 输入框 | 白底、2px 线、聚焦变绿 |
|
||||
| 动效 | 只动 `transform` / `opacity`;缓动 `cubic-bezier(.23,1,.32,1)`;尊重 `prefers-reduced-motion` 和页面上的「动效」开关 |
|
||||
|
||||
### 5.5 移动端规则
|
||||
|
||||
- 窄屏(≤760 / 860px):顶栏只留 logo 和开关;底部浮动物品栏(首页 / 画展 / 渲染〔中间钻石〕 / 宇宙 / 更多),「更多」从底栏上方弹出一排格子,再点同一个按钮 / 点空白 / 返回键 / Esc 收起。
|
||||
- 左右边距 16px 左右;**任何页面不许横向滚动**(每次改完都要在 390 宽度下检查)。
|
||||
- 星系图在手机上:星图里的手势全归星图(拖动转、双指缩放,页面不跟着滑),窗户只占屏幕约 64%,上下留出滑页面的地方;档案卡是窗里的底部抽屉,星球挪到上半个窗。
|
||||
|
||||
### 5.6 口味禁区(每条都是看过预览之后的直接反馈)
|
||||
|
||||
- **不要暗色面板**、不要黑白强对比(星系图窗户是唯一例外);不要复古风。
|
||||
- **文字 / 标题 / 名牌前面不要放小圆点、小方块色点**。
|
||||
- 不要按钮扫光动画;不要六边形「三棱镜」按钮;全站按钮一个样子。
|
||||
- 星系图:不要星球光环、不要每颗星外面一层大气「罩子」、辉光不能过曝;颜色只用那一套(深蓝 + 蓝紫 + 金),不要彩虹;装饰星球不能互相重叠、卫星不能反着转;开场 / 飞行运镜要连贯,档案卡要跟星球落定同时出来。
|
||||
- 流动大背景要平滑,不要像素化;像素风只留在字、按钮、粒子上。
|
||||
- **文案说人话**:不写「标签 · 解释」式的说明、不加英文小字装饰、不写解释界面怎么用的句子。
|
||||
- 改一块就只动那一块,不要顺手改邻居(比如改顶栏时别动头图);小步改。
|
||||
|
||||
---
|
||||
|
||||
## 6. 业务逻辑
|
||||
|
||||
### 6.1 网站全貌
|
||||
|
||||
金钻客栈 = 一个线上「客栈」:画展、工具与开源、金钻宇宙、各平台入口都在里面;**自助模板渲染只是其中一家店**。
|
||||
|
||||
| 页面 | 内容 | 数据在哪 |
|
||||
|---|---|---|
|
||||
| `index.html` 首页 | 首屏 +「都有些什么」五间屋(桌面)/ 金刚区 + 最新作品(手机)+ 自助渲染服务台(渲染机状态、价格实时读)+ 常用平台 | `content/site.js`(hero / boards / gallery / apps / universe / links / about) |
|
||||
| `gallery.html` 画展 | 图片 / 视频 / 全景 / 动态壁纸,按时间排、可筛选(脱敏版只有一张占位) | `content/site.js` 的 gallery + media,`hd_cache/manifest.json`,`view_stats.json` |
|
||||
| `tools.html` 工具与开源 | 开源 / 在线使用 / 闭源三行,按类型筛选 | apps |
|
||||
| `universe.html` 金钻宇宙 | 星门开场 → 星系图 + 世界线档案 | universe(兜底 `assets/universe/config.js`) |
|
||||
| `links.html` 平台入口 | 按分组列出,外链新窗口打开 | linkGroups + links |
|
||||
| `about.html` 关于 | 名字由来 + 署名卡片 | about |
|
||||
|
||||
各页之间是普通链接(整页跳转)。旧的单页地址 `/#/板块`、`/#0001` 会被首页自动跳到新页面。页脚、「更多」面板里的群号和备案号读 `assets/site-info.js`。
|
||||
|
||||
**加一条世界线**:`config.js` 里把空槽换成完整档案(`no / name / kind / tag / tags / desc`)+ 在 `LOOKS` 里给它一个外观(`style / r / orbit / accent / moons / enter`);名字里有新字记得重做像素字子集(5.3);改了 JS 要换版本号(7.2)。细节见 `portal/assets/universe/交接说明.md`。
|
||||
|
||||
### 6.2 下单页(`order/`)
|
||||
|
||||
两条路:
|
||||
|
||||
```
|
||||
网页下单:传皮肤(本地质检)→ 选模板 / 分辨率 → 出订单号(待付款)→ 去爱发电付款
|
||||
→ 爱发电回调确认 / 店主后台激活 → 排队 → 渲染机出图 → 买家看 512 预览 → 确认收货 → 下原图
|
||||
卡密下单:传皮肤 → 填卡密(自动认模板 / 张数)→ 直接排队 → 出图 → 同上
|
||||
凭票取图:拿单号 + 取件码(或卡密)回来看进度、下载
|
||||
```
|
||||
|
||||
皮肤质检(`skincheck.js`,前端和本机开单共用):尺寸是否 64 网格的正方形、像素风检查、主体层完整、半透明、外层铺满、手臂粗细判定;PNG 结构核验防夹带(尾部追加 / 未知关键块 / APNG)。服务器落盘前还会再核一遍(`pngcheck.py`)并剥掉元数据块。
|
||||
|
||||
### 6.3 订单状态机
|
||||
|
||||
```
|
||||
unpaid(待付款)──买家点「我付好了」──▶ paid(待激活)
|
||||
│ │
|
||||
└──── 爱发电回调确认 / 后台激活 / 买家用卡密激活 ───┘
|
||||
▼
|
||||
waiting(排队中)──渲染机 claim──▶ working(渲染中)
|
||||
▲ │
|
||||
后台「退回重渲」/ admin.py retry 一张一次 /finish 回传
|
||||
│ ▼
|
||||
failed(失败)◀── 水印没生成 ── done(已完成)
|
||||
unpaid / paid ──后台注销──▶ void(已注销,不占卡密)
|
||||
```
|
||||
|
||||
- 领单超过 45 分钟没交回 → 自动退回队列。4096 的「重单」高峰期给小单让路,最多让 30 分钟(防饿死)。
|
||||
- 收满张数才算完成;渲染机显式收单但没收满 = **部分失败**:记 `partial`、页面说实话、通知店主。
|
||||
- 预览水印没做出来的不许标完成(标 `failed`,等退回重渲)。
|
||||
- 成品保留 72 小时(从开放下载算);`admin.py sweep` 清理时**先核销卡密再删文件**,排队 / 渲染中 / 待激活的单绝不删。清理后库里那一行留着做账。
|
||||
|
||||
### 6.4 卡密生命周期(**激活 ≠ 核销**)
|
||||
|
||||
```
|
||||
active(可用)──买家提交──▶ bound(已激活:被这一单占住,还没核销)──开放下载满 72 小时──▶ used(已核销,终态)
|
||||
inactive(停用:网页单等付款 / 手动停用)
|
||||
```
|
||||
|
||||
卡密种类:固定 N 张 / 最多 N 张 / 不限张数;可锁模板;「直发」= 店主自己发的码,不用等确认收货。
|
||||
防暴破:码空间 31¹² ≈ 7.9e17;同 IP 连错 15 次冷却 15 分钟;单 IP 10 分钟最多开 6 单。
|
||||
|
||||
### 6.5 爱发电回调
|
||||
|
||||
不验签(没有对方公钥),改成**拿开放接口反查这笔单**。处理顺序:
|
||||
① 标题含「测试」只记账 → ② 同一平台单号重推:原样回上次结果(幂等)→ ③ 反查不到 / 没付款:只记账、标人工,**绝不发码** → ④ 金额:少付拦死、多付照常但记一笔 → ⑤ 认单:自定义订单号 > 留言里的卡密 > 留言里的单号 > 「只有一笔待付款单金额对得上」(两笔以上一律人工)。
|
||||
|
||||
### 6.6 渲染机(店主电脑,`ys_worker.py`)
|
||||
|
||||
只出站:定时 `claim`(领单)+ 独立线程 `hb`(心跳,默认 10 分钟一次,`hb_every`)→ 取皮肤 → Blender 后台渲染(**同一时刻只允许一个 Blender**)→ 中途 `progress` → 一张一次 `finish` 回传。心跳超过 1500 秒没更新 = 页面显示离线(所以 `OFFLINE_AFTER` 必须大于心跳间隔,两边一起改)。心跳顺带记下家里的出口 IP,管理接口只认这个 IP。
|
||||
|
||||
### 6.7 福利券
|
||||
|
||||
一批「免费、已激活」的码放在福利页让人自取:**每台设备 + 每个网络各限领 1 张**(服务器硬规则),领到后 N 天内要用;可锁模板、限张数、定种类(渲染图 / 立牌 / 钥匙扣 / 海报)、到期自动收摊;收摊后已领走的照常能用。
|
||||
|
||||
### 6.8 开单后台(`ys_admin.py`,店主电脑,局域网)
|
||||
|
||||
- PIN 锁(服务端校验,加盐 sha256,12 小时免输);调服务器管理接口要「令牌 + 家里出口 IP」两道门。
|
||||
- 六页:**待处理**(买家说付好了的单、渲染失败的单、没处理的呼叫)/ 订单 / 卡密(生成 + 库)/ 福利券 / 呼叫·反馈 / 开单工具。
|
||||
|
||||
### 6.9 本机开单(`ys_local.py` + `local.html`)
|
||||
|
||||
给聊天里成交的平台单用:拖皮肤 → 同一套质检 → 勾模板 → 本机 Blender 出图 → 下载 / 打开留档文件夹。**不联网、不上传、不要卡密**,只监听本机,只认本机页面。
|
||||
|
||||
### 6.10 数据库
|
||||
|
||||
见 `backend/backend-site/交接说明.md` 第五节。要点:`ys.db` 里 5 张表(codes / orders / pay_orders / calls / kv),每张「能查的列 + 一列整条 JSON」;上层代码拿到的还是原来的 dict;`.lock` 文件锁照旧;WAL 模式。
|
||||
|
||||
---
|
||||
|
||||
## 7. 部署与运维
|
||||
|
||||
### 7.1 文件放哪
|
||||
|
||||
| 文件 | 放到 | 备注 |
|
||||
|---|---|---|
|
||||
| `portal/**` | 网站根目录 | 星系图要 `assets/universe/` 和 `assets/vendor/` 一起上;**`assets/site-info.js` 换成正式服务器那份(真实群号 / 备案号),别用仓库里的占位覆盖**;`content/` 是线上数据,**别用仓库里的占位覆盖**(内容后台管它) |
|
||||
| `order/**` | 网站 `/order/` | |
|
||||
| `server.py` + **`store.py`** + `admin.py` + `pngcheck.py` | `<APP_DIR>`(同一目录) | `server.py` 直接 `import store`,**少了 `store.py` 服务起不来** |
|
||||
| `backend-tools/*` | 店主电脑 `<WORKER_DIR>` | `deploy.py` 推送;面板新按钮依赖服务器新接口,**先升服务器** |
|
||||
| **`cms.py`** | `<APP_DIR>`(和 `server.py` 同一目录) | `server.py` 直接 `import cms` |
|
||||
| `portal/admin/` | 网站 `/admin/` | 内容后台页面(静态) |
|
||||
| `portal/content/`、`order/content/` | 随页面一起 | 后台发布时**由服务器进程覆盖写**:这两个目录和 `portal/uploads/` 要给服务进程写权限 |
|
||||
|
||||
**环境变量**(systemd 单元里加):`YS_PORTAL_DIR=<门户网站根目录>`、`YS_ORDER_DIR=<下单页目录>`(内容后台写内容文件和上传图用;`YS_ROOT` 照旧)。
|
||||
|
||||
### 7.1b 内容后台首次部署(⚠️ 照顺序做)
|
||||
|
||||
1. nginx 按 `deploy/nginx-片段.md` 第 ④ 节加配置(**必须带 `X-Forwarded-Proto`**,整站 http → https)。**没配好证书之前不要开放**:后端会拒绝所有非 https 请求。
|
||||
2. 放好 `cms.py`、设好两个环境变量、给 `content/` `uploads/` 写权限,重启服务。第一次启动会自动建初始账号 `admin / admin`,日志里有一句提示。
|
||||
3. **马上**打开 `https://<站点>/admin/`,用 `admin / admin` 登录 → 强制改密(至少 8 位、不能是 admin / 常见密码)→ 用新密码重新登录。
|
||||
在改密之前,服务端只放行改密码和退出,其它接口一律 403;但这段空档里谁先登进去谁就能改密 —— 所以越快越好。
|
||||
4. 第一次打开内容页时,后台把网站现有的 `content/` 文件当成第 1 版。
|
||||
5. 账号管理(服务器上):
|
||||
```
|
||||
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]
|
||||
```
|
||||
|
||||
### 7.2 缓存与版本号
|
||||
|
||||
- 门户各页引用 `assets/*.js|css?v=1`:改了哪个就把六个页面里它的 `?v=` 一起加 1。HTML 本身要 `no-cache`(nginx 片段里给 `*.html` 加了)。
|
||||
- 门户星系图:改了 JS / CSS 要换版本号,**一起换**:`portal/universe.html` 里 `universe-page.css?v=`、`config.js?v=`、底部模块脚本里 `galaxy.js?v=`,`galaxy.js` 里 `import './planets.js?v='` 和 `'./layout.js?v='`,以及 `portal/admin/index.html` 里 `planets.js?v=`。踩过:坏文件被缓存住,修好了打开还是「加载不出来」。
|
||||
- 内容文件 `content/site.js` / `order.js` 文件名不变、内容会变:nginx 给 `/content/` `/order/content/` 加 `Cache-Control: no-cache`(片段里有)。
|
||||
- 检查 ES 模块语法要拷成 `.mjs` 再 `node --check`(按普通脚本查会漏「重复声明」)。
|
||||
- three.js 只在第一次打开「金钻宇宙」时下载(约 690KB,gzip 后约 170KB)。
|
||||
|
||||
### 7.3 数据库命令
|
||||
|
||||
```
|
||||
python3 admin.py db check # 完整性 + 每张表几行 + 按状态计数
|
||||
python3 admin.py db backup # 在线热备份到 <DATA_DIR>/backup/
|
||||
python3 admin.py db export [目录] # 导回旧版 JSON(回退用)
|
||||
```
|
||||
|
||||
回退:停服务 → `db export` → 换回旧版 `server.py` / `admin.py` → 启动。再切回来:挪走 `ys.db`,新版启动时从 JSON 重新导入。
|
||||
权限:跑 `admin.py` 的账号要对 `<DATA_DIR>` **目录**有写权限(WAL 会建 `ys.db-wal` / `-shm`)。
|
||||
|
||||
### 7.4 常用
|
||||
|
||||
```
|
||||
python3 admin.py ls waiting # 看排队
|
||||
python3 admin.py retry <单号> # 失败单退回(后台也有按钮)
|
||||
python3 admin.py calls # 呼叫记录(后台也有页面)
|
||||
python3 admin.py sweep # 清过期成品 + 核销(建议每天跑一次)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. 测试与验证
|
||||
|
||||
| 测试 | 怎么跑 | 结果(2026-10-05) |
|
||||
|---|---|---|
|
||||
| 后端回归 + 漏洞复现 | `python3 backend/backend-site/tests/回执复现测试.py <server.py 所在目录>` | 27 / 27 |
|
||||
| 数据库专项 | `python3 backend/backend-site/tests/数据库测试.py <server.py 所在目录>` | 38 / 38 |
|
||||
| 开单后台 | 假数据起真服务器 + 真面板,headless 浏览器电脑宽 / 手机宽点全部页面 | 无报错、无横滚;无 PIN → 401、无令牌 → 403 |
|
||||
| 本机开单 | 假本机服务(模拟渲染)+ headless 浏览器走完整流程 | 无报错、无横滚 |
|
||||
| 门户 | headless 浏览器 1366 / 390:六个板块都切一遍;宇宙:星图就绪、点卡片飞过去出档案、`#0002` 深链、全屏开关、手机上拖星图页面不滚;首页不下载 three.js | 全过;除星系图板块外,其余板块和改动前**逐像素一致** |
|
||||
| 下单页 | 打开截图 | 正常(本轮没改) |
|
||||
| **内容后台(后端)** | `python3 backend/backend-site/tests/内容后台测试.py <server.py 所在目录> <仓库根目录>` | 78 / 78:部署漏配时拒绝工作、后台发布不覆盖命令行改过的价格、初始账号与强制改密(改密前 11 个接口全 403)、库里无明文、Cookie 属性、https / CSRF / 跨站来源 / 爆破冷却(按 IP 5 次、按账号合计 20 次)、内容校验、XSS 转义、发布写文件、冲突 409、回滚一致、预览要登录、传图核验与去元数据、会话撤销与过期、命令行、三进程同时首启只建一个账号 |
|
||||
| **内容后台(端到端)** | 迷你反代模拟 nginx + 真服务器 + headless 浏览器 1366 / 390 | 36 / 36:门户入口 → 登录 → 强制改密 → 改文案 / 传图 / 点亮新地球 / 加入口 / 下架模板 / 加档位 → 预览(未登录看不到草稿)→ 发布 → 门户 / 星系图 / 下单页都变了 → 回滚复原 → 退出;无新增报错(只有交付副本本来就缺的 `view_stats.json` 和模板缩略图 404) |
|
||||
|
||||
后端测试数据全是测试脚本现编的,建在系统临时目录。⚠️ 交付副本里三个 URL 格式串被脱敏成 `http<WIN-PATH>`,要起服务器的测试得先在**测试副本**里换成能格式化的占位(这三处分别吃 1 / 2 / 0 个参数);线上原版直接跑。
|
||||
|
||||
---
|
||||
|
||||
## 9. 已知未验证 / 待确认
|
||||
|
||||
- **星系图帧率没在真机上测过**(只在无头浏览器的软件渲染里验证了画面和交互)。上线前用一台普通手机、一台集显笔记本各打开看一下;卡的话按 `universe/交接说明.md` 第 8 节降粒子数。
|
||||
- **数据库没在真机器上跑过**(1.6G 内存 + systemd 内存上限)。部署后先跑一次 `admin.py db check`。
|
||||
- 渲染机、真实 Blender、爱发电真实回调、手机通知脚本(读 `calls.jsonl` 的那段不在仓库里)都没有端到端测过。
|
||||
- 下单页里的链接是站点根路径(`/index.html`、`/order/`、`/assets/site-info.js`、`/fonts/…`),本地要从 `portal/` 起服务、再把 `order/` 放到 `/order/` 才完整。
|
||||
- 加载动画 / 宇宙星门只在无头浏览器里看过逐帧截图;真机(尤其低端安卓)上看一眼顺不顺。
|
||||
- 署名按要求没改(「苏达 · 大肥鱼」)。
|
||||
|
||||
---
|
||||
|
||||
## 10. 内容后台(2026-10-05 晚实现)
|
||||
|
||||
网站前端所有展示内容在网页后台里改,不用再改代码。设计和每条安全规则的来由见根目录 **`内容后台设计.md`**;实现在:
|
||||
|
||||
| 部分 | 文件 |
|
||||
|---|---|
|
||||
| 服务端(账号 / 会话 / 草稿 / 发布 / 传图) | `backend/backend-site/cms.py`(`server.py` 把 `/api/cms/*` 交给它) |
|
||||
| 后台页面 | `portal/admin/index.html`(入口:门户顶栏最右边的淡色铅笔) |
|
||||
| 内容文件 | `portal/content/site.{json,js}`、`order/content/order.{json,js}`(发布时生成;`.json` 是正本,`.js` 给页面读) |
|
||||
| 命令行 | `admin.py user …`(见 7.1b) |
|
||||
| 测试 | `tests/内容后台测试.py`(75 条) |
|
||||
|
||||
要点(店主定的安全底线,别放松):
|
||||
- 初始账号 `admin / admin`,**首次登录强制改密**;改密前服务端只放行改密码 / 退出,其它接口一律 403。
|
||||
- 密码 `hashlib.scrypt`(没有就 `pbkdf2_hmac`)加盐存哈希,任何地方都不存明文;至少 8 位。
|
||||
- 会话是服务端令牌(库里只存哈希),「记住我」30 天滑动过期;退出 / 改密 / 命令行重置 / 停用都会当场作废。
|
||||
- Cookie:HttpOnly + SameSite=Strict,https 下 Secure;修改类请求要带 CSRF 头;跨站来源拒绝。
|
||||
- 只走 https(反代没说 https 就拒);登录冷却:同一 IP 错 5 次 / 同一账号合计错 20 次开始冷却(账号那档放宽,免得别人故意输错把店主锁在门外)。
|
||||
- 内容后台碰不到卡密 / 订单。
|
||||
@@ -1,101 +1,84 @@
|
||||
# 交接说明 · 前端视觉重设计(redesign-2026)
|
||||
# 交接说明 · 金钻客栈 2026 视觉改版(白光藏色 × MC 方块)
|
||||
|
||||
> ⚠️ 这一份只讲 `11eb16c` 那一轮视觉改版。之后「金钻宇宙」板块换成了星系图(这次改了门户原有的 JS,下面「原有脚本一字未改」那句对门户已不成立),后端也接了数据库。
|
||||
> **完整的、最新的情况以根目录 `交接文档-2026-10.md` 为准。**
|
||||
|
||||
## 一句话
|
||||
|
||||
两个页面都**只在 `</body>` 前追加了一个 `<style id="redesign-2026">` 覆盖块**,相对 `origin/main`(d1e34b7)是**纯新增、零删除**;
|
||||
**没有改 JS 业务逻辑、没有改接口路径/请求参数、没有改 HTML 文本和结构**。功能用自动化脚本对比原版逐项点过,未发现回归;需要后端的流程未验证(见第 4 节)。
|
||||
两个页面换成了**浅色的「白光藏色」+ Minecraft 方块风**:整体一眼是白的,颜色藏在亮部和流动的淡彩背景里;按钮是 MC Ore UI 那种方块按钮;标题换成像素字;手机端换成底部物品栏导航。
|
||||
**原有的 `<style>` 和 `<script>` 一字未改**(逐块比对过,见第 3 节);新东西全部放在两段带标记的新增块里,外加少量静态文案。
|
||||
上一轮的暗色覆盖块 `redesign-2026` 已整块删掉(金钻那边反馈不好看)。
|
||||
|
||||
## 仓库信息
|
||||
|
||||
- 仓库:`https://git.lingll.icu/public/jinzuanwork.git`
|
||||
- 分支:`main`
|
||||
- 样式提交:`8ee505f` style: 门户与下单页视觉重设计(精致暗色 + 宝石色)
|
||||
- 本说明所在的提交:紧跟在 `8ee505f` 之后的一个 docs 提交(提交自身的哈希无法写进自身,以 `git log` 为准)
|
||||
- 推送后 `git status`:干净(无未提交改动、无未跟踪文件)
|
||||
- 基线:已先 rebase 到你方最新的 `d1e34b7`(相对路径修复),无冲突
|
||||
- 提交:本说明所在的那个提交(提交自身的哈希写不进自身,以 `git log` 为准)
|
||||
- 推送后 `git status`:干净
|
||||
|
||||
## 1. 改了哪些文件
|
||||
|
||||
| 文件 | 改动 |
|
||||
|---|---|
|
||||
| `portal/index.html` | 第 5549–6671 行新增 `<style id="redesign-2026">`(+1121 行,0 删除) |
|
||||
| `order/index.html` | 第 4178–4752 行新增 `<style id="redesign-2026">`(+573 行,0 删除) |
|
||||
| `交接说明.md` | 新增(本文件) |
|
||||
| `portal/index.html` | 删除上一轮的 `<style id="redesign-2026">`;`</body>` 前新增 `<!-- jz-2026:start -->…<!-- jz-2026:end -->`(手机底栏 HTML + `<style id="jz-2026">` + `<script id="jz-2026-js">`);顶栏加一个「自助渲染」链接;部分静态文案改写(见第 2 节) |
|
||||
| `order/index.html` | 删除上一轮的 `<style id="redesign-2026">`;`<body>` 开头新增 `<!-- jz-2026-top:start -->…<!-- jz-2026-top:end -->`(跟门户一样的顶栏);`</body>` 前新增 `jz-2026` 块(底栏 + 样式 + 脚本);页头副标题一句改写 |
|
||||
| `portal/fonts/jz-pixel-12.woff2` | 新增:像素标题字体(缝合像素字体 12px,按两个页面实际用到的 1373 个字做了子集,41 KB) |
|
||||
| `portal/fonts/jz-pixel-OFL.txt` | 新增:上面字体的 SIL OFL 1.1 协议原文 |
|
||||
| `order/assets/jz-pixel-12.woff2`、`order/assets/jz-pixel-OFL.txt` | 同上,下单页用的一份(下单页的相对路径在 `order/assets/` 下) |
|
||||
| `交接说明.md` | 重写(本文件) |
|
||||
|
||||
**没有改**:`portal/assets/tokens.css`、`order/assets/tokens.css`、`order/skincheck.js`、`portal/dev/*`、`fonts/`、`icons/`、`exhibition/`、两份原有说明文档。
|
||||
**没有改**:`portal/assets/tokens.css`、`order/assets/tokens.css`、`order/skincheck.js`、`portal/dev/*`、`icons/`、`exhibition/`、OPPO Sans 字体、两份原有说明文档。
|
||||
|
||||
## 2. 做了什么
|
||||
|
||||
方向:**精致暗色 + 宝石色**(参考 Linear / Vercel 一类克制暗色站;强调色取自 logo 像素钻石:翡翠绿 `#3ecf8e` 为主,钻石青 `#7dd3e0`、金 `#e9c46a` 只做点缀)。
|
||||
### 全站
|
||||
- **配色**:把页面原来的颜色变量(`--bg`、`--txt*`、`--line*`、`--acc`、门户的 `--paper*`/`--moss`/`--brass-soft` 等)在新样式块里重新赋成浅色值,原来引用这些变量的规则自动变浅;少数写死了深色的地方(顶栏、机架抽屉、弹层、启动仪式等)单独覆盖。强调色换成 MC 草方块绿 `#3C8527`。
|
||||
- **背景**:白底 + 几团淡彩光;支持 WebGL 时换成缓慢流动的淡彩(低分辨率、30fps、标签页不可见时浏览器自动暂停;开了「减少动效」或系统 reduced-motion 就不动)。原来的网点 / 春意环境层 / 网格层用 CSS 隐藏(DOM 和脚本都还在)。
|
||||
- **按钮**:统一成 MC 方块按钮——绿色是主按钮,石头白是次按钮,按下会下沉;所有按钮一个样子。
|
||||
- **标题**:像素字(缝合像素字体);正文仍是 OPPO Sans。
|
||||
- **面板**:半透明白 + 白边 + 带一点颜色的柔影,不再用深色玻璃。
|
||||
- **英文装饰**(`BOARDS //`、`GALLERY //` 这类 kicker、`EXAMPLE.COM` 小字、时钟、`LINK // 已同步`)用 CSS 隐藏。
|
||||
|
||||
### 门户 portal
|
||||
### 门户 `portal/index.html`
|
||||
- 顶栏:logo + 像素字「金钻客栈」+ 板块导航(当前板块白底绿下划线)+ 右侧绿色「自助渲染」按钮(新增的静态链接 `/order/`)。「动效」「音」两个开关保留。
|
||||
- 首页首屏:一块淡彩「观景窗」,左边文案和按钮,右边钻石 + 一圈淡淡的彩虹环;去掉了遥测数字条和角标。
|
||||
- 首页五个板块卡:每块藏一种矿石色(画展金、工具蓝、宇宙紫、平台绿、关于红),悬停时边缘亮出来。
|
||||
- 工具与开源:**修了原版卡片三栏挤在一起、正文只剩一指宽的问题**——现在图标在左,正文占满,按钮放在正文下面。
|
||||
- 金钻宇宙:机架抽屉、特写弹窗、启动仪式都换成白底。
|
||||
- 手机端:顶栏只留 logo 和两个开关;底部一条 MC 物品栏式导航(首页 / 画展 / 渲染 / 宇宙 / 更多)。「更多」从底栏上方弹出一排格子(工具与开源 / 平台入口 / 关于 + QQ 群号),底栏一直可点;再点「更多」、点空白、返回键、Esc 都能收起。
|
||||
- 文案(只改静态 HTML 里的字,JS 渲染出来的内容一个没动):
|
||||
- 首屏:「欢迎光临」/「金钻的画、做的小工具、写的宇宙设定,还有各个平台的主页,都放在这儿了。随便逛逛。」/ 按钮「逛画展」「金钻宇宙」
|
||||
- 版块标题:「都有些什么」「画展」「工具与开源」「平台入口」「关于」,副标题改成一句人话
|
||||
- 关于:卡片小标题去掉英文;**新增一张「像素字体」鸣谢卡**(字体协议要求随附协议,顺带署名)
|
||||
- **署名没动**:「苏达 · 大肥鱼」保持原样(按金钻这边的要求,暂不改成「苏达 · 空枝」)
|
||||
|
||||
- **去噪**:`.kicker` / `.eyebrow` / `.sec-meta` / `.ro dt` / `.core-tag` / 顶部导航等「等宽 + 全大写 + 大字距」标签,统一改为常规无衬线、小号、淡灰;隐藏 `.core-hint`、`.core-bracket`(瞄准框角)等纯装饰。
|
||||
- **首屏重心**:H1 放大并紧字距,「客栈 / 宇宙」二字青绿渐变;钻石徽记外加柔和宝石色光晕;四个统计数字从格子框弱化为一行轻量数据;收紧首屏与「板块总览」之间的大块空白。
|
||||
- **背景**:隐藏网格/点阵层(`body::after`、`#bgBlur`、`#blockgrid`、`#halftone`、`.boot-grid`、`.v-grid`),只保留一层极淡径向氛围光。
|
||||
- **卡片与网格**:实色卡面 `#111316` + 1px 发丝边,圆角 14–16px,hover 轻微上浮;首页板块 5 张卡改为 3+2(「画展」主卡跨两列),关于页 5 张卡同样 3+2,不再有单张掉行。
|
||||
- **按钮**:主按钮实心翡翠绿 + 深色字,次按钮透明底 + 细边。
|
||||
- **画展**:筛选栏、左侧年份时间轴、底部说明统一新风格。
|
||||
- **金钻宇宙**:盘符机架结构、抽插/拖拽/回弹动效**原样保留**,只跟随新配色与字体层级。
|
||||
- **页脚**:改为与新风格一致的常规小号淡灰。
|
||||
- **手机端**:顶部 6 个导航改为 3×2 网格(原来最后一项「关于」被截一半);按钮在窄屏自动整行。
|
||||
|
||||
### 下单页 order
|
||||
|
||||
- 与门户统一底色、卡片、圆角、按钮与字体层级。
|
||||
- 步骤编号 `.num` 做成小圆形徽章;顶部进度条 `.prog` 加粗、当前段高亮。
|
||||
- 两个入口 `.entry` 做成可 hover 上浮的大卡。
|
||||
- 状态色保持可辨:正常/成功 翡翠绿、不足/警告 暖金、超出/失败 红。
|
||||
|
||||
### 顺手修的两个**原有**样式问题(都只是 CSS,在 redesign-2026 块内)
|
||||
|
||||
1. **手机端画展「更多 ▾」按钮永远不显示**:原 CSS 中第 951 行(手机端 `@media` 内)设了 `#fltMoreBtn{display:inline-flex}`,但第 1201 行有一条无条件的 `#fltMoreBtn{display:none}` 写在它后面,把它盖掉了 → 手机上「看过的在前 / 金钻制作 / 瀑布流 / 时间轴倒序」等筛选全部点不到。已在覆盖块末尾补 `@media (max-width:719px){ #fltMoreBtn{display:inline-flex} }`,实测手机上可展开、可点。
|
||||
2. **手机端下单页页头贴屏幕边**:原 `.hd{padding:15px 0 12px}` 左右为 0,标题和「渲染机离线」胶囊紧贴屏幕边缘。覆盖块内改为左右 16px,与下方卡片对齐。
|
||||
|
||||
### 对《设计思路(仅供参考)》的取舍
|
||||
|
||||
- **保留**:「内容浮在背景上」「层级靠亮度差」「单一强调色(翡翠绿)」「动效是反馈不是装饰」「手机优先」「状态显眼但不吓人」「尊重 prefers-reduced-motion」。
|
||||
- **改掉**:「终端感」——大量等宽大写字距标签、仪器网格、瞄准框角在实际页面里噪音过多、主次不清,所以大幅弱化或隐藏;改用留白、字号字重和容器层级来分层。
|
||||
- **小幅突破**:原思路说「不出彩色光环」,这次在钻石徽记外加了一圈很淡的青绿光晕作为首屏视觉锚点,强度克制;不想要的话删掉 `.home-core` 相关光晕规则即可。
|
||||
### 下单页 `order/index.html`
|
||||
- 顶部加了跟门户一样的顶栏(链接回 `/#/home` 等板块,「自助渲染」高亮为当前页);手机端是同一条底栏(「渲染」是当前格)和同一个「更多」面板。
|
||||
- 页头:钻石方块 + 像素标题「自助模板渲染」+ 一句话「传一张皮肤,选个模板,等一会儿就能拿到渲染图。」+ 一行小灰字显示渲染机状态(还是原来的 `#machTxt`,脚本照常更新)。
|
||||
- **四段进度条 `.prog` 用 CSS 隐藏了**(金钻那边觉得「渲染机在线 + 四个步骤」那一块难看);DOM 和 `body[data-step]` 逻辑都还在,以后想要回来删一行 CSS 即可。
|
||||
- 卡片、两条路入口、上传区、模板卡、分辨率、核对表、弹窗、toast 全部换成白底 + 方块按钮。
|
||||
|
||||
## 3. 没有动什么
|
||||
|
||||
- **没有改 JS 业务逻辑**,没有改任何 `<script>` 内容。
|
||||
- **没有改接口路径和请求参数**(实测下单页仍按原路径请求 `/order/api/payinfo`、`/order/api/gift`、`/order/api/status`,与原版一致)。
|
||||
- **没有改 HTML 文本、id、class、data-* 属性,没有删除任何元素。**
|
||||
- 占位值(`example.com`、`123456789`、`备案号(已移除)`、`(本机路径)`)保持原样。
|
||||
- **没有改 JS 业务逻辑、没有改接口路径 / 请求参数。** 用脚本把两个页面里所有原有的 `<script>` 块和 `<style>` 块跟基线 `d1e34b7` 逐块比对:**完全一致**(门户 5/5 个脚本、下单页 6/6 个脚本)。
|
||||
- 新增的 `<script id="jz-2026-js">` 是独立的:只画背景、管底栏和「更多」面板;只**读** `location.hash` 来高亮当前板块,不调用、不修改页面原有的任何函数和接口。
|
||||
- 占位值保持原样:`example.com`、`备案号(已移除)`、`(本机路径)` 次数跟原版一致;`123456789` 多出现了一次,是「更多」面板里那行 QQ 群号(同一个占位值)。
|
||||
- 新增 HTML 只有:门户顶栏的「自助渲染」链接、两页的底栏 / 更多面板、下单页顶栏。原有元素的 id / class 一个没改。
|
||||
|
||||
## 4. 怎么验证的
|
||||
|
||||
环境:服务器上用 `python3 -m http.server` 分别托管「原版(origin/main)」和「改版」,Playwright + Chromium 无头浏览器,**1440px 桌面宽**和 **390px 手机宽**各跑一遍**同一套点击脚本**,逐行对比输出;每次点击前先检测目标元素是否可见、是否被别的层遮挡(elementFromPoint 命中测试)。
|
||||
在服务器上用 `python3 -m http.server` 从包根目录起服务,Playwright(Chromium headless)实际打开、点击:
|
||||
|
||||
**结果:与原版一致,无回归**(仅有的差异是:① 弹窗/提示条 z-index 数值调高,不影响行为;② 手机端「更多」筛选从不可用变为可用,即上面修的原有问题)。
|
||||
|
||||
实际点过并通过的:
|
||||
|
||||
- **门户**:6 个导航切换板块与 hash 正确;首页 5 张板块卡可点并跳转;首屏 3 个按钮可点;「动效 / 音」开关 aria-pressed 正确翻转;画展「全部/图片/视频/特殊」筛选、「更多」、瀑布流切换、时间轴倒序、看过排序、按制作者筛选,筛选后「清除筛选」按钮出现(列数 +/- 与清除筛选本身未点);作品卡点开大图弹窗(关闭弹窗未单独验证);金钻宇宙 11 个盘符渲染,点击可抽出(open 状态);启动仪式遮罩约 3–8 秒后正常让出点击(与原版相同);12 个站外链接可点;关于页 5 张卡与署名原样。
|
||||
- **下单页**:卡密框打开/取消;「凭票取图」弹窗打开、按钮可点、取消关闭;「浏览器历史订单」弹窗;页脚「反馈」弹窗;「网页下单」进入第 1 步;勾选条款;上传测试皮肤 → 本地质检报告正常出现;臂型三选一;继续到第 2 步、7 个模板渲染、模板可选中;退回第 1 步。**未解锁的第 2–4 步仍然点不到**(`pointer-events:none` 锁定有效)。
|
||||
- **两页**:控制台 **0 个 JS 报错**;390px 下 5 个页面**均无横向滚动**。
|
||||
|
||||
**未验证**(本地没有后端,`/order/api/*` 全部 404):提交订单、查卡密、付款回执、进度轮询、下载/打包、确认收货、重渲、加皮肤、呼叫站长、领券等**需要后端返回数据的流程与对应状态 UI**(排队中/渲染中/完成/失败的样式)。这些状态的配色在 CSS 里保留了,但没有实际看到渲染出来的样子。
|
||||
|
||||
另:只在 Chromium 下测过,**未在 Safari / iOS / 微信内置浏览器实测**。
|
||||
- 门户六个板块(首页 / 画展 / 工具与开源 / 金钻宇宙 / 平台入口 / 关于)× 桌面 1440 与手机 390:截图逐张看过;**无 JS 报错、无横向滚动**。
|
||||
- 画展:点作品打开大图弹层 ✅(本地没有高清原图,弹层里会一直显示「正在加载」——脱敏副本本来就没有原图,不是样式问题)。
|
||||
- 金钻宇宙:启动仪式出现并可跳过 ✅;点抽屉展开 ✅;「抽取特写」打开盘芯弹窗 ✅。
|
||||
- 手机底栏:首页 → 画展切换、高亮跟着变 ✅;「更多」打开 / 再点收起 / 返回键收起 ✅;从「更多」进平台入口后按一次返回就回到画展(不会多一条历史)✅;下单页底栏「渲染」高亮、「更多」里链接回门户板块 ✅。
|
||||
- 下单页:落地页、「网页下单」展开四步、「卡密下单」输入框、「凭票取图」弹窗,桌面和手机都截图看过,无 JS 报错。
|
||||
- **未验证**:需要后端的流程(真实提交订单、付款、轮询进度、下载成品、呼叫站长、福利券等)——本地没有后端,下单页停在「渲染机离线」状态,只看了这些状态的样子。
|
||||
|
||||
## 5. 待确认 / 风险
|
||||
|
||||
1. **署名未改**:《给协作者的说明》要求把「制作者/鸣谢」补成「苏达 · 空枝」。本次**按委托方要求暂不改署名**,关于页保持原文「苏达 · 大肥鱼」,请你方自行决定后再改。
|
||||
2. **背景流态效果被关掉**:为去掉背景网格,隐藏了 `#bgBlur`、`#blockgrid`、`#halftone` 三个背景层,原首屏提示的「移动鼠标 · 背景流态」跟随鼠标效果因此不再可见(只是用 CSS 隐藏,相关 JS 未改;是否仍在后台计算未核实)。如需保留,删掉覆盖块里对这三个 id 的 `display:none` 即可。
|
||||
3. **大量 `!important`**:覆盖块为压过原有多层样式(`portal-shell` / `jz-unified` / `jz-1014` 等)用了较多 `!important`。后续若在原样式里继续调视觉,可能被覆盖块压住;建议以后视觉改动直接改 redesign-2026 块,或等稳定后把它合并回原样式。
|
||||
4. **文案里的「XXX // 中文」**(如「BOARDS // 01-05 内容板块」)是写在 HTML 里的文字,按约定没改文本,所以 `//` 还在,只是变淡变小了。要彻底去掉需要改文案。
|
||||
5. **字体**:下单页 `@font-face` 仍引用 `/fonts/OPPOSans-*.woff2`(绝对路径,你方上一提交未改到这里),在包内本地打开时会回落到系统字体;不影响本次样式,但与你方「相对路径」修复不一致,提醒一下。
|
||||
|
||||
## 6. 交付方式
|
||||
|
||||
- 保留原目录结构;只改了上面两个 HTML 并新增本说明。
|
||||
- 没有带入备份、截图、调试脚本、构建缓存、账号信息或任何密钥(截图与测试脚本都放在仓库外)。
|
||||
- 只推送到上面指定的仓库,没有镜像到其它位置。
|
||||
|
||||
## 附:怎么回退
|
||||
|
||||
- 只想撤掉视觉改动:删掉两个文件里的整个 `<style id="redesign-2026">…</style>` 块即可,页面恢复原样。
|
||||
- 或:`git revert 8ee505f`。
|
||||
- 下单页里的链接是**站点根路径**(`/#/home`、`/order/`),跟门户原来指向下单页的 `/order/` 一个写法;线上(门户在根目录)没问题,本地按「从包根目录起服务」打开时,下单页顶栏点「首页」会去到包根目录而不是 `portal/`。
|
||||
- 隐藏了四段进度条、遥测数字条、时钟和连接状态这些装饰;如果哪个其实有人在看,删掉对应那行 CSS 就能回来。
|
||||
- WebGL 背景在很老的手机上可能多耗一点电;拿不到 WebGL 时自动退回静态淡彩渐变。
|
||||
- 「署名」按金钻这边的意思暂时没改,协作说明里要求的「苏达 · 空枝」还没加,需要你们确认。
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
# 内容后台 · 设计说明(2026-10-05 定稿,待实现)
|
||||
|
||||
> 目的:网站前端所有**展示内容**都能在网页后台里改,不用再改代码、再部署。
|
||||
> 状态:**2026-10-05 晚已实现**(四步都做了)。实现:`backend/backend-site/cms.py`、`portal/admin/`、`admin.py user …`;部署步骤见 `交接文档-2026-10.md` 7.1b。
|
||||
> 跟设计有出入的地方见文末「实现对照」。
|
||||
|
||||
---
|
||||
|
||||
## 1. 和现有两个后台的关系
|
||||
|
||||
| | **内容后台(本文)** | 开单后台(`backend-tools/ys_admin.py`) |
|
||||
|---|---|---|
|
||||
| 管什么 | 网站上所有展示内容 | 卡密、订单、福利券、激活:跟钱有关 |
|
||||
| 跑在哪 | 服务器上(和 `server.py` 同一个进程) | 店主家里电脑 |
|
||||
| 谁能打开 | 公网能打开登录页,**登录后才能进** | 只在家里局域网 |
|
||||
| 怎么登录 | 账号(用户名或邮箱)+ 密码 | PIN(不变) |
|
||||
| 入口 | 门户顶栏最右边一个**不带字的铅笔图标** | 家里电脑桌面 |
|
||||
|
||||
**内容账号碰不到卡密和订单**:内容后台的接口只读写「内容」那几张表,跟卡密 / 订单 / 账本是两套接口、两套权限。
|
||||
内容账号就算被盗,最坏也就是网页内容被改,而且能一键回到上一版(第 5 节)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 能改什么
|
||||
|
||||
| 页面 | 能改的 |
|
||||
|---|---|
|
||||
| 门户 · 首页 | 大标题下那句话、按钮文字、公告条(可开关、可设起止日期) |
|
||||
| 门户 · 画展 | 增删改作品:标题、日期、类型(图片 / 视频 / 全景 / 动态壁纸)、归属(金钻 / 他人)、说明、排序、隐藏;**上传图片**(第 7 节);视频填 B 站链接 |
|
||||
| 门户 · 工具与开源 | 增删改条目:名称、英文名、类型、开源 / 闭源、说明、版本、状态、链接、仓库 |
|
||||
| 门户 · 金钻宇宙 | 世界线档案(名字、类型、一句话、简介、标签);外观用**下拉选**(星球风格、主色、入场运镜);空槽数量 |
|
||||
| 门户 · 平台入口 | 分组、名称、说明、链接(只允许 `https://` 和 `mailto:`) |
|
||||
| 门户 · 关于 | 名字的由来、署名卡片、鸣谢 |
|
||||
| 下单页 | 模板的名称 / 说明 / 上下架 / 预览图;页面上的提示与说明文字;价格档位(原 `prices.json`);付款方式(原 `payinfo.json`) |
|
||||
|
||||
**刻意不放进来的**:
|
||||
- **条款版本号**:服务器、下单页、渲染机三处必须同时改,放进后台容易只改一处、静默出错;继续手改,见交接文档。
|
||||
- **`.blend` 模板文件本身**:继续在家里电脑上放。
|
||||
- 模板 key(`stand`、`airship` …):渲染机认这个,后台只能改显示名,不能改 key。
|
||||
|
||||
---
|
||||
|
||||
## 3. 账号与密码
|
||||
|
||||
- 登录:**用户名或邮箱 + 密码**。**不开放注册**,账号只能在服务器上用命令行建。
|
||||
- 存储:`hashlib.scrypt`(每个账号一份随机盐,≥16 字节),参数和盐一起存进 SQLite;
|
||||
机器上的 Python 不带 scrypt 时自动改用 `pbkdf2_hmac`(sha256,≥60 万次迭代)。
|
||||
以后加强参数,老账号在下次登录时自动升级。比对用 `hmac.compare_digest`。**任何地方都不存、不记明文**(含日志)。
|
||||
- 密码规则:**至少 8 位**,不能是 `admin`,拦掉一份常见弱密码表。
|
||||
- 防爆破:同一 IP、同一账号连错几次逐步加长冷却;提示统一说「账号或密码不对」,不透露账号是否存在。
|
||||
|
||||
### 3.1 首次部署:初始账号 `admin / admin` + 强制改密(安全底线)
|
||||
|
||||
1. 服务器第一次启动、库里一个账号都没有时,自动建 `admin`,密码 `admin`(入库的同样是哈希)。
|
||||
2. 这个账号带「必须改密码」标记。用它登录后拿到的是**受限会话**:
|
||||
**服务端在接口统一入口拦截,除了「改密码」和「退出」,其它所有内容后台接口一律 403「请先修改初始密码」**。不靠前端跳转。
|
||||
3. 新密码 ≥8 位、不能是 `admin`。改完:清掉标记 → 作废这个账号所有会话 → 用新密码重新登录。
|
||||
4. 初始密码**不设过期**(店主定)。
|
||||
|
||||
> ⚠️ 部署步骤里写死:**服务一启动就马上登录改密**。
|
||||
> 从部署完到改密之间,公网上谁先用 `admin/admin` 登进去谁就能改掉密码 —— 这段空档越短越好。
|
||||
|
||||
### 3.2 服务器命令行(`backend-site/admin.py`)
|
||||
|
||||
| 命令 | 干什么 |
|
||||
|---|---|
|
||||
| `python3 admin.py user add <用户名> [--email 邮箱]` | 建账号,密码在终端里隐藏输入、输两遍 |
|
||||
| `python3 admin.py user passwd <账号>` | 直接设新密码;**作废这个账号所有会话** |
|
||||
| `python3 admin.py user reset <账号>` | 忘了密码用:**作废所有会话** → 生成**随机临时密码**,只打印在执行命令的终端里(不写日志)→ **下次登录必须改密**。加 `--to-admin` 则退回 `admin` |
|
||||
| `python3 admin.py user disable / enable <账号>` | 停用 / 启用;停用时作废所有会话 |
|
||||
| `python3 admin.py user list` | 账号、邮箱、是否待改密、最近登录时间 / IP |
|
||||
| `python3 admin.py user sessions <账号> [--revoke-all]` | 看这个账号在哪些设备登录着;可一键全部踢掉 |
|
||||
|
||||
---
|
||||
|
||||
## 4. 登录态(会话)
|
||||
|
||||
- 登录成功 → 服务端生成随机令牌(`secrets.token_urlsafe(32)`),**库里只存令牌的哈希**,带过期时间。
|
||||
- Cookie:始终 **HttpOnly + SameSite=Strict**;请求是 https 时加 **Secure**(看反代传来的协议)。
|
||||
- 「记住我」(默认勾上):Cookie 保留 **30 天**,每次使用自动续期;不勾 = 关掉浏览器就失效(服务端同样 30 天兜底)。
|
||||
- **服务端主动撤销** = 删掉那一行,下一次请求立刻失效。触发:退出、「退出所有设备」、命令行 `passwd` / `reset` / `disable`、自己改密码(除当前这台)。
|
||||
- 每个修改请求还要带一个防伪造令牌(CSRF,存在会话里,页面拿到后放请求头)。
|
||||
- 后台「账号」页能看到自己在哪些设备登录着(浏览器、IP、最近使用时间),可以逐个退出。
|
||||
|
||||
---
|
||||
|
||||
## 5. 草稿 → 预览 → 发布 → 回滚
|
||||
|
||||
- 编辑只写**草稿**;草稿随时可丢弃。
|
||||
- 「预览」:用草稿数据渲染一份门户 / 下单页(只给登录的人看)。
|
||||
- 「发布」:弹窗列出这次改了哪些地方(按板块统计增 / 改 / 删),写一句说明(可空)后确认。
|
||||
- 每次发布存一个**完整版本**(谁、什么时候、说明、内容快照),「发布记录」里能看、能对比、能**一键回到某一版**(回滚本身也算一次发布,可以再回滚)。
|
||||
- 两个人同时编辑:发布时发现底稿已被别人发布过,提示先看对方改了什么再合并,不静默覆盖。
|
||||
|
||||
---
|
||||
|
||||
## 6. 数据怎么到页面上
|
||||
|
||||
- 数据库(`ys.db`)加表:`cms_users`、`cms_sessions`、`cms_draft`、`cms_versions`、`cms_audit`。
|
||||
- 发布时把内容写成静态文件 `portal/content/site.json`(下单页 `order/content/order.json`),**原子替换**(先写临时文件再 rename)。
|
||||
页面直接读静态 JSON:快、能被缓存、**后端挂了网站照样能看**。
|
||||
- 页面里保留一份内置兜底数据:JSON 读不到时用它,不白屏。
|
||||
- 价格档位 / 付款方式:发布时同时写回服务器原来那两个文件(`prices.json` / `payinfo.json`),下单逻辑不用改。
|
||||
|
||||
---
|
||||
|
||||
## 7. 画展传图
|
||||
|
||||
1. 后台里拖图上传(PNG / JPEG / WebP,单张 ≤ 20MB)。
|
||||
2. 服务器先做**结构核验**(沿用 `pngcheck.py` 的思路,补 JPEG / WebP):拒尾部夹带、拒不认识的块;剥掉 EXIF 等元数据。
|
||||
3. 用 ffmpeg **一次处理一张**生成缩略图和高清版,自动更新媒体清单(`MEDIA` / `hd_cache`)。
|
||||
单张图片处理是这台服务器允许的(下单预览图现在就这么做);视频不上传,只填 B 站链接。
|
||||
4. 上传的文件进草稿;发布了才出现在网站上。
|
||||
|
||||
---
|
||||
|
||||
## 8. 安全清单
|
||||
|
||||
- **登录页和内容后台接口只走 https**:nginx 把 http 一律 301 到 https 并加 HSTS;后端再兜一层,反代说不是 https 就拒绝,不收密码。
|
||||
**没配好证书之前不能开放这个登录页。** 仅服务器本机 http 调试时例外(此时 Cookie 不带 Secure)。
|
||||
- 所有输入在**服务端**校验:字段类型、长度、链接白名单(`https://`、`mailto:`)、颜色格式、枚举值(星球风格 / 运镜只能选列表里的)。
|
||||
- 所有文字在页面上**转义输出**,不允许 HTML(防 XSS);需要换行的字段只认换行符。
|
||||
- 登录、改密、发布、回滚、上传都记审计日志:谁、什么时候、哪个 IP、改了什么。
|
||||
- 登录接口和上传接口在 nginx 上单独限流。
|
||||
- 内容后台接口和卡密 / 订单接口分开,权限互不相通。
|
||||
|
||||
---
|
||||
|
||||
## 9. 分四步做
|
||||
|
||||
| 步 | 内容 | 估时 |
|
||||
|---|---|---|
|
||||
| 1 | 内容从代码里搬出来:门户 / 下单页改成读 `content/*.json`(带内置兜底) | 1–1.5 天 |
|
||||
| 2 | 账号与会话:建表、哈希、初始账号 + 强制改密、Cookie、撤销、CSRF、防爆破、命令行 | 1.5 天 |
|
||||
| 3 | 内容后台页面:各板块编辑、草稿 / 预览 / 发布 / 回滚、账号页、顶栏铅笔图标 | 2–3 天 |
|
||||
| 4 | 画展传图:核验、ffmpeg 转图、媒体清单 | 1–2 天 |
|
||||
|
||||
每步都配测试,至少覆盖:
|
||||
- 库里查不到明文;
|
||||
- 错密码登不进;
|
||||
- 初始账号改密前调其它接口一律 403;
|
||||
- 改密 / 重置 / 停用后旧会话立即失效;
|
||||
- 令牌过期;
|
||||
- http 请求被拒;
|
||||
- 爆破触发冷却;
|
||||
- CSRF 缺失被拒;
|
||||
- 非法链接 / 超长字段被拒;
|
||||
- 转义正确;
|
||||
- 发布原子写入;
|
||||
- 回滚还原一致。
|
||||
|
||||
---
|
||||
|
||||
## 10. 还没定的
|
||||
|
||||
- 署名(关于页「网站构建」那张卡片):后台放开给店主自己改,还是锁成只读?——没定之前按「可以改」做。
|
||||
|
||||
---
|
||||
|
||||
## 11. 实现对照(和上面设计有出入的地方)
|
||||
|
||||
| 设计里写的 | 实际做的 | 为什么 |
|
||||
|---|---|---|
|
||||
| 「同一 IP、同一账号连错几次逐步加长冷却」 | 同一 IP 错 5 次 / **同一账号合计错 20 次**才冷却(30s 起翻倍,最长 15 分钟) | 只按账号算的话,别人从外面故意输错几次就能把店主锁在门外;IP 那档仍然很紧 |
|
||||
| 发布写 `content/site.json` | 同时写 `site.json`(正本)和 `site.js`(`window.JZ_CONTENT = …`,页面同步读) | 页面用同步脚本读,不用改成异步加载,旧代码几乎不动;读不到就用页面内置兜底 |
|
||||
| 「预览」用草稿渲染一份 | 门户 / 下单页带 `?preview=1` 打开时,额外加载 `/order/api/cms/draft.js`(要登录)覆盖内容;页面底部有「预览草稿」提示条 | 不用另做一套预览页;没登录的人带同样的参数也只看到正式内容 |
|
||||
| 画展传图 ≤ 20MB | ≤ 10MB | server.py 请求体上限 15MB,base64 后 10MB 的图约 13.4MB |
|
||||
| 「关于」不允许 HTML | 只认两种简易写法:`[文字](https://网址)` 链接、`` `代码` ``;空一行分段 | 原来的署名卡片里本来就有链接和代码样式,要能保留 |
|
||||
| 下单页「页面上的提示文字」 | 只做了页头那句话 + 公告条 | 其它提示散在下单页逻辑里,动它风险大;以后要加再逐个接 |
|
||||
| 署名卡片是否锁定(待定) | 没锁,店主可以改 | 没定之前按「可以改」 |
|
||||
| 新点亮的世界线放哪 | 自动排位(`portal/assets/universe/layout.js`):中圈不挤的位置,补给线接附近的星,已有的都不动 | 店主要求「新星球的位置和连线要好看、不打架」 |
|
||||
| 「两个人同时编辑:提示先看对方改了什么再合并」 | 发布时底稿过期 → 409,弹窗二选一:丢掉我的草稿 / 确认后用我的草稿覆盖发布(覆盖前可先看发布记录) | 不做逐字段合并,简单可控 |
|
||||
| (设计没写) | 部署漏配(没设 `YS_PORTAL_DIR` / `YS_ORDER_DIR`,或门户目录里没有 `content/site.json`)时内容后台**拒绝工作**,不建第一版、不写任何文件 | 否则会从空骨架开始,店主一发布就把网站内容清空 |
|
||||
| (设计没写) | 价格档位 / 付款方式只有这次发布真改了才写回 `prices.json` / `payinfo.json` | 不覆盖有人用 `admin.py price` 在命令行改过的价格 |
|
||||
| (设计没写) | 同时最多 2 个密码哈希在算 | 一次 scrypt 要 16MB 内存,服务进程上限 256M |
|
||||
|
||||
Reference in New Issue
Block a user