From 9e8b4aff4646844a4b98dc8dc3d3963bd0849f8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=8D=A1=E6=8B=89=E5=B8=95=E9=B2=81=E7=81=B0?= <939671113@qq.com> Date: Sat, 28 Nov 2026 01:17:05 +0800 Subject: [PATCH 1/3] =?UTF-8?q?fix(ui):=20=E8=AE=BE=E7=BD=AE=E9=A1=B5?= =?UTF-8?q?=E6=8F=90=E7=A4=BA=E6=96=87=E6=A1=88=E5=8E=BB=E6=8E=89=20AI=20?= =?UTF-8?q?=E8=85=94=EF=BC=88=E7=A0=B4=E6=8A=98=E5=8F=B7=E6=8E=A5=E8=A7=A3?= =?UTF-8?q?=E9=87=8A=E3=80=81=E6=8B=AC=E5=8F=B7=E5=A1=9E=E7=BB=86=E8=8A=82?= =?UTF-8?q?=E3=80=81=E6=8B=9F=E4=BA=BA=E5=8C=96=E5=8F=A3=E8=AF=AD=EF=BC=89?= =?UTF-8?q?=20(#165)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 常规设置:第三方主题说明拆成直述句,删掉「exe 不会越做越大」这类推理过程 - 主题提示 / 开机自启:去掉「只有你在这里勾上」「就立刻删掉」的口语表达 - MAA 路径:切号名规则改为陈述句,保留官服后 4 位与脱敏形式示例; 「一个字都不动」「死找」改成「不会改动任何字段」「反复查找」 - 版本更新 / 网络代理:两条链、代理适用范围与回退行为分句说明 事实要素全部保留,仅换表达方式。 Co-authored-by: HuiParu <171644868+HuiParu@users.noreply.github.com> --- frontend/app.js | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/frontend/app.js b/frontend/app.js index 378a59a..8f4b9e8 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -3102,16 +3102,15 @@ function openSettings() {

常规设置

-

界面主题和开机启动。主题只影响外观:深色 / 白色随程序自带; - 卫戍协议这类第三方主题要在这里点一次「下载」,从我们的资源分支 - 拉到本机(config/themes),不塞进程序包里——这样 exe 不会 - 越做越大,不想要的主题也能随时删掉。

+

界面主题和开机启动。深色和白色主题随程序自带;像卫戍协议这样的第三方主题 + 不打包进程序,第一次使用要先点一次「下载」,文件存到本机 config/themes + 目录,不再需要时可以删掉。

界面主题
${themeCards()}
-
第三方主题第一次用要先下载(含配色、字体和桌宠动画), - 下载完点「使用」立即切换;不适配的主题随时可以删掉。
+
第三方主题包含配色、字体和桌宠动画,首次使用需先下载, + 下载完成后点「使用」即可切换。
正在读状态…
-
默认关闭。只有你在这里勾上,才会往当前用户的 - 启动项里写一条(任务管理器 → 启动 里能看见「MAA-PRTS」,随时可关); - 取消勾选就立刻删掉。
+
默认关闭。勾选后会在当前用户的启动项里登记一条, + 任务管理器的「启动」页可以看到「MAA-PRTS」,随时可以关闭;取消勾选会立即移除。
@@ -3149,13 +3147,13 @@ function openSettings() {

MAA 路径

-

每个账号可以绑自己的 MAA(包含 MAA.exe 的目录),没绑就用下面的默认目录。 - 第二行选一个 配置文件(MAA 里那份档案,如 Default / moren), - 程序会从它的「开始唤醒」里读出切号名——官服是手机号(后 4 位 - 5505,或前 3 位 + 后 4 位 157****3635, - bilibili服是游戏内用户名),读出来还能手改。 - 只读不写:MAA 里那份档案我们一个字段都不动。填错的代价是 MAA - 在账号列表里死找、4 分钟超时后整轮挂机作废。

+

每个账号可以绑定独立的 MAA 目录(包含 MAA.exe 的文件夹), + 未绑定时使用下方的默认目录。在 配置文件 中选择 MAA 里的档案 + (如 Default / moren),程序会从该档案的「开始唤醒」任务里 + 读取切号名:官服填手机号后 4 位(如 5505),或「前 3 位 + 后 4 位」 + 的脱敏形式(如 157****3635);bilibili服 + 填游戏内用户名。读取后仍可手动修改。该档案只读,程序不会改动 MAA 中的任何字段。 + 切号名填错时,MAA 会在账号列表中反复查找,4 分钟超时后本轮任务作废。

${gameTabs()}
@@ -3243,8 +3241,9 @@ function openSettings() {

版本更新

-

两条链各自独立:游戏资源是关卡 / 干员 / 活动数据(几百 KB,随程序发版更新), - 程序本体是 MAA-PRTS 自己(国内源 / 海外源都能取,有新版本只提醒,装不装你说了算)。

+

游戏资源和程序本体分开更新。游戏资源包含关卡、干员和活动数据, + 体积只有几百 KB,随程序发版同步;程序本体是 MAA-PRTS,国内源和海外源都可以获取。 + 检测到新版本时只做提示,是否安装由你决定。

@@ -3299,8 +3298,8 @@ function openSettings() {
网络代理
-
只在连不上 GitHub 时才需要。仅用于上面两条检查 / 下载链路; - 端口留空 = 直连。改完点「保存并测试」,不可用也会保存(更新时会自动直连回退)。
+
仅在无法连接 GitHub 时需要。该代理只作用于上面两条检查与下载链路, + 端口留空表示直连。填写后点「保存并测试」;代理不可用时配置仍会保存,更新时会自动退回直连。
Date: Sat, 28 Nov 2026 01:28:52 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix(update):=20=E8=A3=85=E5=AE=8C=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E4=B8=BB=E5=8A=A8=E5=88=B7=E5=9B=BE=E6=A0=87=E7=BC=93?= =?UTF-8?q?=E5=AD=98=EF=BC=8C=E6=A1=8C=E9=9D=A2=E4=B8=8D=E5=86=8D=E5=81=9C?= =?UTF-8?q?=E5=9C=A8=E6=97=A7=E5=9B=BE=E6=A0=87=20(#166)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit install.ps1 换完 exe 直接起新进程,全程没通知 shell;iconcache_*.db 不会 因为 exe 被替换而失效——本机缓存停在 11-25 02:49,系统 11-26 12:23 重启过 也没重建,用户看到的还是上一版的图标。 - appupdate.refresh_icon_cache():SHChangeNotify(SHCNE_ASSOCCHANGED), 失败只返回 False,不连累启动结算 - on_start() 在「pending.to == 当前版本」的成功分支补调一次;没装成功不刷 - 不放进 install.ps1:无窗口跑 Add-Type 可能被安全软件拦,且新版本启动时 exe 已经是新的,这时扫出来才是新图 - 冒烟 B83(86 项全绿):成功补刷 / 失败不白刷 / Windows 上 API 可调 Co-authored-by: HuiParu <171644868+HuiParu@users.noreply.github.com> --- backend/core/appupdate.py | 22 ++++++++++++++ docs/backend.md | 2 +- docs/tools-smoketest.md | 16 +++++++++++ tools/smoketest/smoke_test.py | 54 +++++++++++++++++++++++++++++++++++ 4 files changed, 93 insertions(+), 1 deletion(-) diff --git a/backend/core/appupdate.py b/backend/core/appupdate.py index c68fa3a..f4c54bb 100644 --- a/backend/core/appupdate.py +++ b/backend/core/appupdate.py @@ -1108,6 +1108,25 @@ def run(): threading.Thread(target=run, daemon=True, name='install-quit').start() +# ---------------------------------------------------------------- 图标缓存 +def refresh_icon_cache() -> bool: + """通知资源管理器重建图标缓存(SHCNE_ASSOCCHANGED) + + 换了 exe 以后 shell 不会自己失效:2026-11-28 实测 iconcache_*.db 的 + 时间戳停在 11-25 02:49,中间 11-26 12:23 重启过电脑也没重建,桌面快捷 + 方式一直显示旧图标,只能手动清缓存。安装脚本收尾时顾不上(无窗口、 + Add-Type 还可能被拦),所以新版本第一次启动、确认替换成功时补一次。 + """ + if os.name != 'nt': + return False + try: + import ctypes + ctypes.windll.shell32.SHChangeNotify(0x08000000, 0, None, None) + return True + except Exception: + return False + + # ---------------------------------------------------------------- 启动自检 def on_start() -> dict: """启动时结算上一次安装:替换成功就把 pending 清掉,失败则留痕 @@ -1147,6 +1166,9 @@ def on_start() -> dict: os.remove(os.path.join(update_dir(), 'install-ok.txt')) except Exception: pass + # exe 换了新图,但 shell 手里还是旧缓存:重启电脑也不重建, + # 不主动发一次通知,用户的桌面图标会一直停在上一版的图案上 + refresh_icon_cache() return info diff --git a/docs/backend.md b/docs/backend.md index df96015..82b355b 100644 --- a/docs/backend.md +++ b/docs/backend.md @@ -201,7 +201,7 @@ pywebview 窗口与浏览器直开都是同源,不受影响。 | 预检 | `precheck()`:MAA.exe 在跑直接拒绝(它会把 `_internal/VCRUNTIME140*.dll` 加载进自己进程,镜像必失败)。不逐个试开 `_internal`——MAA-PRTS 自己就锁着二十多个 DLL,那样判定恒误报 | | 替换 | 程序退出后由 `update/install.ps1` 执行:按 PID 等进程退出 → 备份 exe → `robocopy /MIR` 镜像 `_internal`(失败重试 4 次,仍失败把点名的文件写进 `install-error.txt`)→ 覆盖根级文件 → 校验版本号 → 重启,失败则整体回滚并重新拉起旧版 | | 不动的东西 | `config/`、`debug/`、`resources/`——那是用户数据,脚本里一个字都不出现 | -| 结算 | 写 `update/pending.json`;新版本启动时版本号对上才算成功,否则日志留警告,并把 `install-error.txt` 的原因带进 `/api/app/status.lastInstall.error` | +| 结算 | 写 `update/pending.json`;新版本启动时版本号对上才算成功,否则日志留警告,并把 `install-error.txt` 的原因带进 `/api/app/status.lastInstall.error`;成功时顺手调 `SHChangeNotify(SHCNE_ASSOCCHANGED)` 让 shell 重建图标缓存(`iconcache_*.db` 不会因为 exe 被替换而失效,实测重启电脑也不重建) | `install()` 需要让整个进程退出,而 api 层不能 import main,所以 main 启动时 把退出函数注册进 `appupdate.set_quit_hook()`。源码模式一律拒绝自动替换。 diff --git a/docs/tools-smoketest.md b/docs/tools-smoketest.md index 59171d7..31ec8de 100644 --- a/docs/tools-smoketest.md +++ b/docs/tools-smoketest.md @@ -885,3 +885,19 @@ MAA 牛杂里那两个常驻商店接进助手。和前三项(活动里的小 点名这两个工具,前端第一条引导是「帮我使用推荐设置一键长草刷左侧所有账号」。 全程打桩(假 candidates / 假 `_load_cfg` / 假 `run_core`),不连模拟器、不读真配置。 + +### B83 换完 exe 刷图标缓存(2026-11-28) + +v2.8.7 装好后桌面快捷方式还是旧图。`install.ps1` 换完文件直接起新进程,全程 +没通知 shell;本机 `iconcache_*.db` 时间戳停在 11-25 02:49,而系统 11-26 12:23 +重启过——**重启电脑不会重建图标缓存**,只能主动发 `SHCNE_ASSOCCHANGED`。 + +- **时机**:`on_start()` 里「`pending.to` 等于当前版本」那条分支,`refresh_icon_cache()` + 紧跟着清理备份执行;版本对不上(没装成功)一律不刷,免得白扫一遍缓存目录。 +- **实现**:`ctypes.windll.shell32.SHChangeNotify(0x08000000, 0, None, None)`, + 失败只吞掉异常返回 False,不许连累启动结算。 +- **不在安装脚本里做**:`install.ps1` 无窗口跑,`Add-Type` 编译 C# 还可能被安全 + 软件拦;放进新版本启动路径更稳,而且这时候 exe 已经是新的,扫出来就是新图。 + +打桩 `update_dir/_current/_state/_save_state`,只在临时目录写 `pending.json`, +不碰真实 `update/` 和 `config/appupdate.json`;最后真调一次函数验 API 可用。 diff --git a/tools/smoketest/smoke_test.py b/tools/smoketest/smoke_test.py index f00a77f..1fde8ab 100644 --- a/tools/smoketest/smoke_test.py +++ b/tools/smoketest/smoke_test.py @@ -8956,6 +8956,8 @@ def main(): lambda: check_daily_longgrass(tmp)) r.check('B82 程序图标(美术源 → 七档 ICO / 美术源缺失退回占位图)', lambda: check_app_icon(tmp)) + r.check('B83 换完 exe 刷图标缓存(不刷重启也不管用 / 装失败不白刷)', + lambda: check_icon_cache_refresh(tmp)) finally: shutil.rmtree(tmp, ignore_errors=True) @@ -9698,5 +9700,57 @@ def check_app_icon(tmp): assert 'assets/icon.png' in doc, 'docs/resources.md 没写美术源在哪' +def check_icon_cache_refresh(tmp): + """B83 换完 exe 主动刷图标缓存(不刷的话重启电脑也不管用) + + 2026-11-28 现场:v2.8.7 装好了,桌面快捷方式还是 v2.8.6 的旧图。 + `install.ps1` 换完文件直接 Start-Process,全程没通知 shell;本机 + `iconcache_*.db` 时间戳停在 11-25 02:49,而系统 11-26 12:23 重启过 + —— 说明**重启不会重建缓存**,只能主动发 SHCNE_ASSOCCHANGED。 + + 这里不去碰真实缓存目录(也碰不到):on_start 打桩到临时 update 目录, + 验的是「替换成功补一次、没装成功不白刷」,最后真调一次函数本身。 + """ + from core import appupdate + + keep = (appupdate.update_dir, appupdate._current, appupdate._state, + appupdate._save_state, appupdate.refresh_icon_cache) + try: + upd = os.path.join(tmp, 'update-icon') + os.makedirs(upd, exist_ok=True) + appupdate.update_dir = lambda: upd + appupdate._current = lambda: '2.8.8' + appupdate._state = lambda: {} + appupdate._save_state = lambda st: None + + hits = [] + appupdate.refresh_icon_cache = lambda: (hits.append(1), True)[1] + + # 1) 替换成功(pending.to == 当前版本)→ 必须补一次刷新 + appupdate._write_json(os.path.join(upd, 'pending.json'), + {'from': '2.8.7', 'to': '2.8.8', 'tag': 'v2.8.8'}) + st = appupdate.on_start() + assert st.get('ok') is True, st + assert len(hits) == 1, '替换成功后没刷新图标缓存,用户会一直看旧图标' + + # 2) 没装成功(还是旧版本号)→ 不许白刷,还要带出失败原因 + appupdate._current = lambda: '2.8.7' + appupdate._write_json(os.path.join(upd, 'pending.json'), + {'from': '2.8.7', 'to': '2.8.8', 'tag': 'v2.8.8'}) + with io.open(os.path.join(upd, 'install-error.txt'), 'w', encoding='utf-8') as f: + f.write('替换 _internal 失败 rc=9') + st = appupdate.on_start() + assert st.get('ok') is False and 'rc=9' in (st.get('error') or ''), st + assert len(hits) == 1, '没装成功却去刷了图标缓存' + + # 3) 函数本身:Windows 上必须能调通(无副作用,只让 shell 重扫) + appupdate.refresh_icon_cache = keep[4] + if os.name == 'nt': + assert appupdate.refresh_icon_cache() is True, 'SHChangeNotify 调用失败' + finally: + (appupdate.update_dir, appupdate._current, appupdate._state, + appupdate._save_state, appupdate.refresh_icon_cache) = keep + + if __name__ == '__main__': sys.exit(main()) \ No newline at end of file From eae328ea3b806a0515874f8e5cfbb7063a1b13b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=8D=A1=E6=8B=89=E5=B8=95=E9=B2=81=E7=81=B0?= <939671113@qq.com> Date: Sat, 28 Nov 2026 02:31:16 +0800 Subject: [PATCH 3/3] =?UTF-8?q?feat:=20=E5=B9=B2=E5=91=98=E5=A4=B4?= =?UTF-8?q?=E5=83=8F=E6=8C=89=E9=9C=80=E4=B8=8B=E8=BD=BD=E3=80=81=E6=8A=BD?= =?UTF-8?q?=E5=8D=A1=E7=BB=9F=E8=AE=A1=E4=B8=89=E5=88=86=E8=A7=86=E5=9B=BE?= =?UTF-8?q?=E3=80=81=E8=B5=84=E6=BA=90=E7=BB=9F=E4=B8=80=E5=88=B0=20pack-d?= =?UTF-8?q?ata=20(#167)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(gacha): 干员头像按需下载 + 抽卡统计三分视图与分页 头像不进安装包:469 张 96px WebP 约 2MB,全塞进去每个用户都要为几十张 看得见的图买单。改成用到哪张下哪张。 头像链路(backend/core/avatarcache.py + /api/avatar/): - 本地 config/cache/avatar 命中直返(长缓存,install.ps1 不碰 config/) - avatar-data 分支的 avatar-index.json 决定有没有成品:有才试三镜像 (raw → gh-proxy → jsDelivr),没有直接走 PRTS 兜底,省掉三次白等 - 兜底 torappu.prts.wiki 原图,服务端转 96px WebP;转不了存原 PNG - 同 id 并发合并、失败记 5 分钟负缓存、假图(HTML/RIFf 空壳)不落盘 - tools/sync_avatars.py 从 PRTS Wiki 的 MediaWiki API 拉「头像_*.png」 生成索引;数据放独立 avatar-data 分支(pack.yml 是 force push,混在 pack-data 会被下次资源同步冲掉) 抽卡统计: - 统计卡下分三个视图:按卡池 / 星级分布 / 抽卡记录(S.gachaView), 终末地的角色/武器口径改成右侧小分段,两层互不干扰 - 六星行、记录表都带头像;img 加载失败自己移除,露出 .op-av 首字母 - 星级分布补「实际出率 vs 官方公示」和「六星出在第几抽」柱状图,底部 加六星头像墙,不再半屏空白 - 抽卡记录 20 条/页,页码 + 上一页/下一页 + 「本页 N 个 new」,含 new 的 页码带红点;后端记录上限 200 → 2000 条 冒烟 B84(87 项全绿),docs/backend.md、docs/frontend.md、 docs/tools-smoketest.md 同步。 * feat: 头像资源并入 pack-data,账号头像改用看板娘 三件事一起改,都是围绕「头像」: 1) 资源统一到 pack-data 之前头像是被 pack.yml 逼出去的:那个流程每次 orphan + 强推,只放三个 JSON,themes/ 和 resources/avatars/ 会被整个冲掉。现在改成先 `git fetch --depth=1` + `git archive FETCH_HEAD | tar -x` 继承上一版整条 分支,再只覆盖自己负责的路径,然后 push -f。历史仍只有一条,但用户 下过的主题包(850KB)和头像(2.2MB)不会再被每天两次的同步冲成 404。 新 avatars.yml 每周一跑同一套逻辑写 resources/avatars/,两个流程共用 concurrency: pack-data-write(同时跑必然互相覆盖)。 packrepo 去掉 AVATAR_BRANCH / avatar_urls,avatarcache 改回 mirror_urls。 2) 卫戍协议主题的扫描线不再盖头像 body::after 原来 z-index:3 + multiply 压在整屏上,30~36px 的干员头像每 3px 被压一条 22% 黑线,脸完全看不清。试过给头像提 z-index:4——无效, .sidebar 的 backdrop-filter 把层叠上下文锁死了(实测有无规则像素差 0)。 改成 z-index:-1:背景仍留 CRT 纹理,文字/头像/卡片全部清楚。 主题升 1.1.1(顺带把 theme.json 里一直没对齐的版本号改对),重打包推 pack-data。 3) 账号头像 = 看板娘 森空岛同步时已经存了 account.secretary.charId,列表页直接拿来拼 /api/avatar/。新增 acctAvatar() 统一三处(侧栏、设置页、顶部), img 绝对定位盖在昵称首字上,onerror 自删就露出首字;没有 secretary 的 账号(MAA 导入的、终末地的)自然退回首字,前端不用判状态。 冒烟新增 B85(88 项全绿):secretary 透传 / 三处都走 acctAvatar / 无 secretary 退回首字 / packrepo 不再有第二条分支。文档同步。 --------- Co-authored-by: HuiParu <171644868+HuiParu@users.noreply.github.com> --- .github/workflows/avatars.yml | 146 +++++++++++++++++ .github/workflows/pack.yml | 65 +++++--- backend/core/api.py | 1 + backend/core/avatarcache.py | 246 +++++++++++++++++++++++++++++ backend/core/gacha.py | 6 +- backend/main.py | 25 ++- docs/backend.md | 18 +++ docs/frontend.md | 6 +- docs/tools-smoketest.md | 17 ++ frontend/app.js | 285 +++++++++++++++++++++++++--------- frontend/style.css | 103 ++++++++++++ tools/smoketest/smoke_test.py | 159 +++++++++++++++++++ tools/sync_avatars.py | 207 ++++++++++++++++++++++++ 13 files changed, 1190 insertions(+), 94 deletions(-) create mode 100644 .github/workflows/avatars.yml create mode 100644 backend/core/avatarcache.py create mode 100644 tools/sync_avatars.py diff --git a/.github/workflows/avatars.yml b/.github/workflows/avatars.yml new file mode 100644 index 0000000..6f6a487 --- /dev/null +++ b/.github/workflows/avatars.yml @@ -0,0 +1,146 @@ +# 干员头像同步:从 PRTS Wiki 抓「头像_*.png」,压成 96px WebP 推到 pack-data +# +# 触发:每周一 14:00(北京时间,UTC 06:00)+ 手动。头像只在出新干员时变, +# 没必要跟 pack.yml 一样一天两次——那样每次都要多传 2MB 的对象。 +# +# 做的事(tools/sync_avatars.py): +# 1. 先把 pack-data 上现有的头像取到 build/avatars,增量模式下只补缺的 +# 2. 拉 PRTS Wiki 的 MediaWiki 列表(list=allimages&aiprefix=头像) +# 3. 按干员表匹配、转 96px WebP q80,写 avatar-index.json(sha256 + 字节数) +# 4. 推到 pack-data 的 resources/avatars/:继承整条分支,只替换这一块 +# +# 为什么和 pack.yml 共用 concurrency:两个流程都强推同一条分支, +# 同时跑必然有一个被覆盖掉(后推的赢,前一个白干)。 +name: Avatar Sync + +on: + schedule: + - cron: '0 6 * * 1' # 周一 14:00(UTC+8) + workflow_dispatch: + inputs: + force: + description: '已有的头像也重新下载' + type: boolean + default: false + +permissions: + contents: write + +concurrency: + group: pack-data-write + cancel-in-progress: false + +env: + MAA_PRTS_PACK_BRANCH: pack-data + PYTHONUTF8: '1' + PYTHONIOENCODING: utf-8 + +jobs: + sync: + name: 同步干员头像 + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout main + uses: actions/checkout@v7 + with: + ref: main + fetch-depth: 1 + show-progress: false + + - name: Setup Python + uses: actions/setup-python@v7 + with: + python-version: '3.12' + + - name: Install Pillow + run: python -m pip install --quiet --disable-pip-version-check pillow + + # 增量基础:pack-data 上已有的图先落到 build/avatars,sync_avatars 默认 + # 跳过已存在的文件,所以常态下一次只下几张新干员的图。 + # 同时用数据分支的干员表覆盖 main 里那份——main 只在发版时更新, + # 新干员还没进表的话会被当成「没匹配到头像」直接跳过。 + - name: Seed previous avatars + shell: bash + run: | + mkdir -p build/avatars + if ! git fetch --depth=1 origin "$MAA_PRTS_PACK_BRANCH" 2>/dev/null; then + echo "pack-data 还不存在,本次按全量处理" + exit 0 + fi + if git show "FETCH_HEAD:resources/arknights.json" > resources/arknights.json.tmp 2>/dev/null; then + mv -f resources/arknights.json.tmp resources/arknights.json + fi + rm -f resources/arknights.json.tmp + if git cat-file -e "FETCH_HEAD:resources/avatars/avatar-index.json" 2>/dev/null; then + rm -rf "$RUNNER_TEMP/av"; mkdir -p "$RUNNER_TEMP/av" + git archive --format=tar FETCH_HEAD resources/avatars | tar -xf - -C "$RUNNER_TEMP/av" + cp -a "$RUNNER_TEMP/av/resources/avatars/." build/avatars/ + echo "已有 $(find build/avatars -name '*.webp' | wc -l) 张,本次只补缺的" + fi + + - name: Sync avatars from PRTS Wiki + run: | + if [ "${{ inputs.force }}" = "true" ]; then + python -u tools/sync_avatars.py --out build/avatars --force + else + python -u tools/sync_avatars.py --out build/avatars + fi + + - name: Validate + run: | + python - <<'PY' + import json, os + d = json.load(open('build/avatars/avatar-index.json', encoding='utf-8')) + n = d.get('count') or 0 + assert n > 300, '头像只有 %d 张,PRTS 接口多半挂了(别把残缺的索引推上去)' % n + files = set(f for f in os.listdir('build/avatars') if f.endswith('.webp')) + assert len(files) >= n * 0.98, '文件数 %d 与索引 %d 对不上' % (len(files), n) + print('索引 %d 条 | 文件 %d 个 | 合计 %.2f MB' + % (n, len(files), (d.get('bytes') or 0) / 1048576.0)) + PY + + - name: Publish to pack-data + shell: bash + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -e + # 只比 webp 文件集合(索引里的 generatedAt 每次都变,拿它比永远「有变化」) + hash_av() { + find "$1" -name '*.webp' -type f 2>/dev/null | sort | xargs -r sha256sum \ + | sha256sum | cut -d' ' -f1 + } + + D="$RUNNER_TEMP/pack-data" + rm -rf "$D"; mkdir -p "$D" + cd "$D" + git init -q -b "$MAA_PRTS_PACK_BRANCH" + git config user.name 'github-actions[bot]' + git config user.email '41898282+github-actions[bot]@users.noreply.github.com' + git remote add origin "https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" + + # 继承上一版(含 themes/ 与三个资源 JSON),只替换 resources/avatars/ + if git fetch -q --depth=1 origin "$MAA_PRTS_PACK_BRANCH" 2>/dev/null; then + git archive --format=tar FETCH_HEAD | tar -xf - -C . + fi + + OLD=$(hash_av resources/avatars) + rm -rf resources/avatars + mkdir -p resources + cp -a "$GITHUB_WORKSPACE/build/avatars" resources/avatars + NEW=$(hash_av resources/avatars) + + if [ -n "$OLD" ] && [ "$OLD" = "$NEW" ]; then + echo "头像没有变化,本次不推送" + echo "### 头像无变化" >> "$GITHUB_STEP_SUMMARY" + exit 0 + fi + + COUNT=$(python -c "import json;print(json.load(open('resources/avatars/avatar-index.json',encoding='utf-8'))['count'])") + MB=$(python -c "import json;d=json.load(open('resources/avatars/avatar-index.json',encoding='utf-8'));print(round((d.get('bytes') or 0)/1048576.0,2))") + git add -A + git commit -q -m "chore(avatar): 同步干员头像 ${COUNT} 张" + git push -q -f origin "HEAD:refs/heads/${MAA_PRTS_PACK_BRANCH}" + + echo "### 头像已更新:${COUNT} 张 / ${MB} MB" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/pack.yml b/.github/workflows/pack.yml index 2317b01..c039bd2 100644 --- a/.github/workflows/pack.yml +++ b/.github/workflows/pack.yml @@ -11,6 +11,9 @@ # 4. 条数只增不减才放行(arknights 各字段 + 悖论条数) # 5. 产物推到独立的 pack-data 分支(不碰 main) # +# 这个流程只负责 resources/ 下那三个 JSON;pack-data 上还有 themes/(主题包) +# 和 resources/avatars/(头像),发布前会把上一版整条分支继承过来,不会冲掉。 +# # 为什么不推 main:main 挂着规则集(强制走 PR、需审批、只允许 squash), # GitHub Actions 的 bot 不在绕过名单里,直推必被拒。数据也不该和代码抢同一条分支。 # pack-data 是纯数据分支,没有保护,客户端按固定分支名拼 raw / jsDelivr 地址。 @@ -33,7 +36,8 @@ permissions: contents: write concurrency: - group: pack-sync + # 与 avatars.yml 共用一把锁:两个流程都写 pack-data,同时跑必然互相覆盖 + group: pack-data-write cancel-in-progress: false env: @@ -133,6 +137,11 @@ jobs: # 推数据分支。每次都是独立的单提交(orphan)+ 强推: # 数据不保留历史,仓库体积不会越滚越大;manifest 里的 ?v=指纹 保证客户端不吃旧缓存。 + # + # 但「强推」只允许冲掉本工作流自己生成的东西。pack-data 上还住着 + # themes/(主题包,人工发布)和 resources/avatars/(头像,avatars.yml 生成), + # 所以先把上一版整条分支继承下来,再盖这三个 JSON——否则每天两次同步 + # 都会把用户已经下载过的主题包和头像冲成 404。 - name: Publish to pack-data shell: bash env: @@ -155,33 +164,53 @@ jobs: fi D="$RUNNER_TEMP/pack-data" - rm -rf "$D"; mkdir -p "$D/resources" - cp resources/arknights.json resources/paradox.json resources/pack-manifest.json "$D/resources/" + rm -rf "$D"; mkdir -p "$D" + cd "$D" + + git init -q -b "$MAA_PRTS_PACK_BRANCH" + git config user.name 'github-actions[bot]' + git config user.email '41898282+github-actions[bot]@users.noreply.github.com' + git remote add origin "https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" + + # 继承上一版(含 themes/ 与 resources/avatars/)。首次生成时 fetch 会失败, + # 此时就是一份干净的孤儿提交。 + if git fetch -q --depth=1 origin "$MAA_PRTS_PACK_BRANCH" 2>/dev/null; then + git archive --format=tar FETCH_HEAD | tar -xf - -C . + echo "继承上一版:$(ls -d themes resources/avatars 2>/dev/null | tr '\n' ' ')" + fi - cat > "$D/README.md" <<'EOF' + # 只覆盖本工作流负责的三个文件 + mkdir -p resources + cp "$GITHUB_WORKSPACE/resources/arknights.json" \ + "$GITHUB_WORKSPACE/resources/paradox.json" \ + "$GITHUB_WORKSPACE/resources/pack-manifest.json" resources/ + + cat > README.md <<'EOF' # pack-data - MAA-PRTS 的游戏资源数据分支,由 `.github/workflows/pack.yml` 自动生成, - **请勿手工编辑**。 + MAA-PRTS 的公共资源数据分支,**请勿手工编辑**。 - | 文件 | 说明 | - | --- | --- | - | `resources/arknights.json` | 干员 / 技能 / 模组 / 关卡 / 区域 / 活动 | - | `resources/paradox.json` | 悖论模拟清单与解锁条件 | - | `resources/pack-manifest.json` | 版本、指纹、sha256、下载地址(客户端读它) | + | 目录 / 文件 | 说明 | 谁在维护 | + | --- | --- | --- | + | `resources/arknights.json` | 干员 / 技能 / 模组 / 关卡 / 区域 / 活动 | `pack.yml`(每天 12:00 / 16:00) | + | `resources/paradox.json` | 悖论模拟清单与解锁条件 | `pack.yml` | + | `resources/pack-manifest.json` | 版本、指纹、sha256、下载地址(客户端读它) | `pack.yml` | + | `resources/avatars/` | 干员头像 96px WebP + `avatar-index.json` | `avatars.yml`(每周一) | + | `themes/` | 第三方主题包 + `manifest.json` | 人工发布 | - 只保留最新一份快照,每次同步都是单提交强制覆盖,不累积历史。 - 原始出处:`yuanyan3060/ArknightsGameResource`,源提交记在 manifest 的 `source.commit`。 + 每次同步都是单提交强制覆盖,不累积历史;但只会覆盖自己那一块, + 其余目录原样继承。原始出处:`yuanyan3060/ArknightsGameResource`, + 源提交记在 manifest 的 `source.commit`。 EOF - cd "$D" - git init -q -b "$MAA_PRTS_PACK_BRANCH" - git config user.name 'github-actions[bot]' - git config user.email '41898282+github-actions[bot]@users.noreply.github.com' git add -A + if git diff --cached --quiet; then + echo "内容没有变化,本次不推送" + exit 0 + fi + git commit -q -m "chore(pack): 同步游戏资源 ${VERSION}" \ -m "上游提交 ${SHA:0:12}" -m "指纹 ${FP}" - git remote add origin "https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" git push -q -f origin "HEAD:refs/heads/${MAA_PRTS_PACK_BRANCH}" echo "### 资源已更新到 ${VERSION}" >> "$GITHUB_STEP_SUMMARY" diff --git a/backend/core/api.py b/backend/core/api.py index c3478a2..e5050b3 100644 --- a/backend/core/api.py +++ b/backend/core/api.py @@ -20,6 +20,7 @@ '.js': 'application/javascript; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', + '.webp': 'image/webp', '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.webm': 'video/webm', diff --git a/backend/core/avatarcache.py b/backend/core/avatarcache.py new file mode 100644 index 0000000..910203e --- /dev/null +++ b/backend/core/avatarcache.py @@ -0,0 +1,246 @@ +# -*- coding: utf-8 -*- +"""干员头像:用到哪张下哪张,安装包不带图 + +为什么不在包里:350 个干员头像压到 96px WebP 约 1.8MB,全打进安装包等于 +给每个用户塞一份他只看得见几十张的图。这里按需下载、落到 +``config/cache/avatar/``——`install.ps1` 的 ``/XD`` 本来就排除 ``config/``, +更新程序不会覆盖;清缓存也只是删这一层目录。 + +来源顺序(前一个失败才走下一个): + + 1. 本机缓存 ``config/cache/avatar/.webp|png``,命中直接返回 + 2. 数据分支 pack-data 的 ``resources/avatars/.webp``(raw → gh-proxy → jsDelivr) + 3. PRTS 镜像 ``torappu.prts.wiki/assets/char_avatar/.png``,现场转 WebP + +第 2 条是主路(我们自己的包,可校验),第 3 条只兜「数据分支还没同步到这张」。 +两条都挂就抛 ``KeyError``,前端回落到首字母圆角块(``.avatar``),不影响阅读。 + +校验刻意做得简单:不认 sha 表(那要额外拉一份 index),只认「真的是图片」—— +文件头 + 大小区间,防的是 CDN 返回一段 HTML 错误页被当成图存下来。 +""" +from __future__ import annotations + +import io +import json +import os +import re +import threading +import time +import urllib.request + +from . import net, packrepo, settings + +_ID_RE = re.compile(r'^[A-Za-z0-9_]{1,64}$') +TIMEOUT_MIRROR = 4 # 自己那三个镜像,挂了就换 +TIMEOUT_FALLBACK = 8 # PRTS 镜像,慢一点但一般能等到 +MIN_BYTES = 512 +MAX_BYTES = 400 * 1024 +NEG_TTL = 300 # 下不到的 id 记 5 分钟,别让列表页每次刷新都重打一遍 + +_locks = {} +_guard = threading.Lock() +_neg = {} # cid -> 到期时间戳(只在内存里) +_index = {'at': 0.0, 'map': None} +INDEX_TTL = 3600 + + +def cache_dir() -> str: + return os.path.join(settings.CONFIG_DIR, 'cache', 'avatar') + + +def _safe(cid: str) -> str: + cid = str(cid or '').strip() + if not _ID_RE.match(cid): + raise KeyError('头像 id 不合法') + return cid + + +def _path_of(cid: str) -> tuple: + """本地已有的缓存文件:(路径, 扩展名);没有返回 ('', '')""" + base = os.path.join(cache_dir(), cid) + for ext in ('webp', 'png'): + p = base + '.' + ext + if os.path.isfile(p) and os.path.getsize(p) >= MIN_BYTES: + return p, ext + return '', '' + + +def _kind(data: bytes) -> str: + """认文件头:webp / png / 其它(空字符串)""" + if len(data) >= 12 and data[:4] == b'RIFF' and data[8:12] == b'WEBP': + return 'webp' + if data[:8] == b'\x89PNG\r\n\x1a\n': + return 'png' + return '' + + +def _ok(data: bytes) -> str: + if not data or len(data) < MIN_BYTES or len(data) > MAX_BYTES: + return '' + return _kind(data) + + +def _get(url: str, timeout: float) -> bytes: + from .version import app_version + req = urllib.request.Request(url, headers={ + 'User-Agent': 'MAA-PRTS/%s' % app_version(), + 'Accept': 'image/webp,image/png,*/*', + }) + with net.open(req, timeout=timeout) as r: + return r.read(MAX_BYTES + 1) + + +def _to_webp(raw: bytes) -> bytes: + """PNG → 96×96 WebP;Pillow 缺 webp 支持时返回空字节(调用方存原图)""" + try: + from PIL import Image + im = Image.open(io.BytesIO(raw)).convert('RGBA') + im = im.resize((96, 96), Image.LANCZOS) + out = io.BytesIO() + im.save(out, 'WEBP', quality=80, method=4) + data = out.getvalue() + return data if _kind(data) == 'webp' else b'' + except Exception: + return b'' + + +def _save(cid: str, data: bytes, ext: str) -> None: + d = cache_dir() + os.makedirs(d, exist_ok=True) + dst = os.path.join(d, '%s.%s' % (cid, ext)) + tmp = dst + '.tmp' + with open(tmp, 'wb') as f: + f.write(data) + os.replace(tmp, dst) + + +def avatar_index() -> dict: + """pack-data 上的头像索引:{charId: {sha256, bytes, name}} + + 拿它只为判断「这张到底有没有成品」:有才去试三个镜像,没有就直接走 + PRTS 兜底,省掉三次必然 404 / 超时的往返(实测能省 5 秒)。拉不到就 + 返回空表(1 小时后再试),此时全部走兜底,功能照常。 + """ + if _index['map'] is not None and time.time() - _index['at'] < INDEX_TTL: + return _index['map'] + got = {} + for url in packrepo.mirror_urls('resources/avatars/avatar-index.json'): + try: + d = json.loads(_get(url, TIMEOUT_MIRROR).decode('utf-8')) + got = d.get('chars') or {} + break + except Exception: + continue + _index['map'] = got + _index['at'] = time.time() + return got + + +def _from_mirrors(cid: str): + """第 2 条:数据分支上的成品 WebP""" + rel = 'resources/avatars/%s.webp' % cid + for url in packrepo.mirror_urls(rel): + try: + data = _get(url, TIMEOUT_MIRROR) + if _ok(data) == 'webp': + return data, 'webp' + except Exception: + continue + return None + + +def _from_prts(cid: str): + """第 3 条:PRTS 镜像上的原图,现场压成 96px WebP""" + url = 'https://torappu.prts.wiki/assets/char_avatar/%s.png' % cid + try: + raw = _get(url, TIMEOUT_FALLBACK) + except Exception: + return None + if _ok(raw) != 'png': + return None + webp = _to_webp(raw) + if webp: + return webp, 'webp' + return raw, 'png' # 转不了就存原图,别为了小 10 倍丢功能 + + +def fetch(cid: str) -> tuple: + """取一张头像:返回 (字节, 扩展名)。哪都拿不到就抛 KeyError + + 同一个 id 的并发请求只下一次:列表页一屏会同时发十几个 img 请求。 + """ + cid = _safe(cid) + p, ext = _path_of(cid) + if p: + return _read(p), ext + + with _guard: + lock = _locks.setdefault(cid, threading.Lock()) + + acquired = lock.acquire(timeout=20) + try: + p, ext = _path_of(cid) # 等锁期间别人可能已经下好了 + if p: + return _read(p), ext + until = _neg.get(cid) or 0 + if until > time.time(): + raise KeyError('头像暂时拿不到') + got = None + if cid in avatar_index(): + got = _from_mirrors(cid) + got = got or _from_prts(cid) + if not got: + _neg[cid] = time.time() + NEG_TTL + raise KeyError('头像拿不到') + data, ext = got + try: + _save(cid, data, ext) + except OSError: + pass # 落盘失败也先把这张发出去 + _neg.pop(cid, None) + return data, ext + finally: + if acquired: + lock.release() + + +def _read(path: str) -> bytes: + with open(path, 'rb') as f: + return f.read() + + +def stats() -> dict: + """缓存占用(设置页 / 以后做「清理头像缓存」用)""" + d = cache_dir() + files, size = 0, 0 + try: + for name in os.listdir(d): + if name.endswith('.tmp'): + continue + p = os.path.join(d, name) + if os.path.isfile(p): + files += 1 + size += os.path.getsize(p) + except OSError: + pass + return {'dir': d, 'files': files, 'bytes': size} + + +def clear() -> dict: + """清空缓存;返回删掉的数量(下次用到会重新下)""" + d = cache_dir() + n = 0 + try: + for name in os.listdir(d): + p = os.path.join(d, name) + try: + if os.path.isfile(p): + os.remove(p) + n += 1 + except OSError: + pass + except OSError: + pass + with _guard: + _neg.clear() + return {'removed': n} diff --git a/backend/core/gacha.py b/backend/core/gacha.py index 10ac853..2e77246 100644 --- a/backend/core/gacha.py +++ b/backend/core/gacha.py @@ -578,6 +578,7 @@ def _pools_of(rs: list) -> list: p['six'] += 1 p['sixItems'].append({ 'charName': r.get('charName') or '?', + 'charId': r.get('charId') or '', 'at': at, 'pity': counters[pid], 'isNew': bool(r.get('isNew')), @@ -596,9 +597,12 @@ def _slice_summary(rs: list) -> dict: """一个口径的完整汇总:卡片数字 + 星级分布 + 六星时间线 + 按卡池 + 最近记录""" t = _tally(rs) recent = [] - for r in reversed(rs[-200:]): + # 2000 条上限:够翻 100 页(前端 20 条/页),又不至于让极老玩家的一次响应 + # 塞进几 MB——官方接口本身也只留最近一段窗口 + for r in reversed(rs[-2000:]): recent.append({ 'charName': r.get('charName') or '?', + 'charId': r.get('charId') or '', 'rarity': int(r.get('rarity') or 0), 'kind': r.get('kind') or 'char', 'poolName': r.get('poolName') or '未知寻访', diff --git a/backend/main.py b/backend/main.py index 6b07b85..746b8d5 100644 --- a/backend/main.py +++ b/backend/main.py @@ -108,11 +108,12 @@ class Handler(BaseHTTPRequestHandler): def log_message(self, fmt, *args): pass - def _send(self, code, body: bytes, ctype='application/json; charset=utf-8'): + def _send(self, code, body: bytes, ctype='application/json; charset=utf-8', + cache='no-store'): 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') + self.send_header('Cache-Control', cache) self.end_headers() try: self.wfile.write(body) @@ -201,6 +202,23 @@ def _theme(self, path): ext = os.path.splitext(full)[1].lower() self._send(200, data, api.MIME.get(ext, 'application/octet-stream')) + def _avatar(self, path): + """干员头像:/api/avatar/ + + 拿不到就 404(前端 img onerror 回落首字母块),不要冒泡成 500—— + 列表页一屏十几张,一张失败刷一条红字会把日志淹掉。 + 命中后长缓存:头像跟 charId 绑定,一个版本内不会变。 + """ + from core import avatarcache + cid = path[len('/api/avatar/'):].strip('/') + try: + data, ext = avatarcache.fetch(cid) + except Exception: + self._send(404, b'not found', 'text/plain; charset=utf-8') + return + self._send(200, data, api.MIME.get('.' + ext, 'application/octet-stream'), + cache='public, max-age=604800') + def do_GET(self): if not trusted_request(self.headers, self.server.server_address): self._reject() @@ -209,6 +227,9 @@ def do_GET(self): if path.startswith('/themes/'): self._theme(path) return + if path.startswith('/api/avatar/'): + self._avatar(path) + return if path.startswith('/api/'): if path == '/api/ping': _last_ping[0] = time.time() diff --git a/docs/backend.md b/docs/backend.md index 82b355b..bc88c14 100644 --- a/docs/backend.md +++ b/docs/backend.md @@ -27,6 +27,7 @@ | `core/resources.py` | 读 `resources/arknights.json`:关卡索引(战斗关默认视图 / `include_story=True` 全量)、干员表、技能/模组名、活动正式名与代号前缀 | | `core/version.py` | 版本管理:程序版本、内置资源包版本、资源更新检测与提示 | | `core/packsync.py` | 资源包自动更新:读远端 manifest → 校验 sha256/条数 → 原子替换 | +| `core/avatarcache.py` | 干员头像按需下载:本地 `config/cache/avatar/` → `pack-data` 的 `resources/avatars/`(三镜像,先看索引里有没有这张)→ PRTS 镜像兜底并转 96px WebP。**安装包不带图**,拿不到抛 `KeyError` 让前端回落首字母;同 id 并发合并、失败记 5 分钟负缓存 | | `core/appupdate.py` | 程序本体自动更新(GitHub Releases):查版本 → 下载校验 → 退出后由 install.ps1 替换 | | `core/maa.py` | MAA 进程控制、`gui.new.json` 读写、作业文件下载 | | `core/envcheck.py` | 开跑前的环境闸:模拟器开着没有、adb 通不通。路径优先从 MAA 的 `gui.new.json` 抄(`Config` 类型 / `AdbPath` / `Extras.<类型>.EmulatorPath` / `InstanceIndex`),再退到 `settings.emulatorPath` 和 adb 反推。没启动就替用户启动(`settings.emulatorAutoStart`,默认开),起来才放行。**不进 `SKILLS`**,所以 `/api/skill/list` 和助手工具表里都看不到它——它是每个任务的前置闸,`skills.run_skill` 起任务时自动调一次,正常时零日志 | @@ -107,6 +108,7 @@ main() | POST | `/api/app/download` | 下载安装包并校验,**不替换**,等用户点「重启并安装」 | | POST | `/api/app/install` | 解压 + 拉起 install.ps1 + 退出程序(源码模式直接拒绝) | | POST | `/api/app/open` | 用系统浏览器打开 Release 页 | +| GET | `/api/avatar/` | 干员头像。**不走 `ROUTES`**:`main.py` 按前缀分发(`/api/avatar/`),命中缓存直接回(`Cache-Control: public, max-age=604800`),拿不到回 404 让 `img onerror` 自己消失 | | GET | `/api/op?id=` | 作业详情(干员与要求、动作数、`maa://` 代码) | | GET | `/api/maa/status` | MAA 是否运行、配置列表、当前配置 | | GET | `/api/maa/probe?dir=` | 检测目录是不是 MAA 根目录(引导/设置用);附干员识别数据 `operbox/operboxCount/operboxSyncTime` | @@ -185,6 +187,22 @@ pywebview 窗口与浏览器直开都是同源,不受影响。 重新生成 → 条数校验 → 推到 `pack-data` 分支(单提交强推)。 **不推 `main`**:`main` 的规则集强制 PR + 审批,bot 不在绕过名单里。 +`pack-data` 是一条**公共数据分支**,住着三户人家: + +| 目录 | 内容 | 谁写 | +|---|---|---| +| `resources/arknights.json`、`paradox.json`、`pack-manifest.json` | 游戏数据 | `pack.yml`,每天两次 | +| `resources/avatars/` | 干员头像 96px WebP + `avatar-index.json` | `avatars.yml`,每周一 | +| `themes/` | 第三方主题包 + `manifest.json` | 人工发布 | + +所以「单提交强推」不能真的把头砍掉:每个写分支的流程都是 +**先 `git fetch --depth=1` + `git archive FETCH_HEAD \| tar -x` 把上一版整条 +分支继承下来,再只覆盖自己负责的那几个路径**,然后提交、`push -f`。历史仍然 +只有一条(旧提交变 unreachable,GitHub 会 gc),用户下过的主题包和头像不会被 +每天两次的资源同步冲成 404。 + +两个流程共用 `concurrency: pack-data-write`:同时跑必然互相覆盖,后推的赢。 + ### 程序本体自动更新(`appupdate.py`) 和资源包是两条完全独立的链路:资源包 0.6 MB、静默换掉;程序 13 MB、 diff --git a/docs/frontend.md b/docs/frontend.md index aeedcb7..d1d4e91 100644 --- a/docs/frontend.md +++ b/docs/frontend.md @@ -55,7 +55,7 @@ api('/api/xxx', body) // 统一包成 {ok, data|error} | 函数 | 负责区块 | |---|---| -| `renderAccounts()` | 左侧账号列表:只渲染侧栏顶部标签选中的那一组(明日方舟 / 终末地),头像配色 + 「终末地」小标签二次区分;拖拽排序只在这一组内生效,另一组的顺序原样保留。渠道名单独上色(`.acct-ch`):B 站服粉、官服亮白,其它渠道不动 | +| `renderAccounts()` | 左侧账号列表:只渲染侧栏顶部标签选中的那一组(明日方舟 / 终末地),头像配色 + 「终末地」小标签二次区分;拖拽排序只在这一组内生效,另一组的顺序原样保留。渠道名单独上色(`.acct-ch`):B 站服粉、官服亮白,其它渠道不动。**账号头像走看板娘**:`acctAvatar(a, cls)` 读 `a.secretary.charId` 拼 `/api/avatar/`,img 加载失败 `onerror` 自删、露出昵称首字;没有 secretary 的账号(MAA 导入的、终末地的)直接是首字 | | `setSideGame()` | 侧栏顶部「明日方舟 / 终末地」分组标签(各带账号数)。切换时若当前账号不属于这一组,自动选中这组第一个;某组为空也保留标签,点了给空态说明 | | `renderHero()` | 顶部账号信息卡 + 统计块(「缺卡」是可点按钮);明日方舟里只有 MAA 建的号(无森空岛 token)显示「从 MAA 更新干员信息」,token 号不显示;终末地只显示等级/区服/抽卡数 | | `showMissing()` | 缺卡清单弹窗,按星级分组,只显示名字 | @@ -73,7 +73,7 @@ api('/api/xxx', body) // 统一包成 {ok, data|error} | `pollTask(tid, root, sel, onNew)` | 任务日志轮询(同步账号、写入 MAA、同步抽卡、签到、助手触发的后台任务共用)。日志容器默认 `#task-log`,签到面板两块日志各有 id,用 `sel` 指过去;第 4 参 `onNew(lines, kind, owners)` 给右栏分栏用(不传就只写弹窗)。承载日志的弹窗被关掉(`root.isConnected === false`)就停下——任务本身在后台跑,不需要前端继续问 | | `setModule(mod)` | 模块菜单切换(作业获取 / 助手 / 抽卡统计 / 森空岛签到),同时决定右栏作业集要不要收起来 | | `applyModuleAvailability()` | 按当前账号的游戏决定 tab 可见性:终末地账号**只留助手与抽卡统计**(隐藏「作业获取」和「森空岛签到」)并自动切过去;切回明日方舟时自动回作业获取(手动点过的模块不会被抢) | -| `renderGacha()` / `paintGacha()` / `paintGachaBody()` | 抽卡统计面板。终末地按「角色寻访 / 武器申领」两个 tab 分开(`S.gachaTab`),一个 tab 一套完整面板;两个游戏版式一致:按卡池 → 星级分布 → 最近记录。按卡池是一池一张卡片(按最近抽卡时间倒序,最新的在最上面),池子下面直接挂这个池出的六星(最多 8 个:名字 + 第几抽 + 时间 + new) | +| `renderGacha()` / `paintGacha()` / `paintGachaBody()` | 抽卡统计面板。统计卡常驻,下面是**视图三分**(`S.gachaView`):按卡池 / 星级分布 / 抽卡记录;终末地的「角色寻访 / 武器申领」是另一层口径开关(`S.gachaTab`,右侧小分段按钮),与视图互不影响。按卡池是一池一张卡片(按最近抽卡时间倒序),池下挂这个池出的六星(最多 8 个:头像 + 名字 + 第几抽 + 时间 + new)。星级分布除星级条,还并列「实际出率 vs 官方公示」(方舟单抽 2/8/50/40%)与「六星出在第几抽」柱状图,底部是六星头像墙。抽卡记录一页 20 条(`S.gachaPage`),翻页控件带页码 + new 红点 + 「本页 N 个 new」 | | `gachaSync()` | 「同步最新记录」:`POST /api/gacha/sync` → 轮询任务日志 → 重画面板 | | `renderSignin()` | 签到面板:标题写当前账号,「单号签到」卡上写它的游戏 / 区服,全局卡上写「几个号有 token」;两个按钮按「有 token 且没有正在跑」置灰 | | `signinRun(scope)` | 签到执行:`scope=all` 全部账号 / `one` 当前账号,`POST /api/signin/run` → 轮询任务日志写进各自那块 `.log-box.sign-log`。用 `S.signBusy` 挡并发(同 token 并发签到会被风控) | @@ -135,7 +135,7 @@ api('/api/xxx', body) // 统一包成 {ok, data|error} |---|---| | 作业获取 | 原有整块(搜索 + 结果),终末地账号不显示 | | 助手 | 内置聊天助手(见下面「内置助手」一节)。跟游戏无关,终末地账号也显示 | -| 抽卡统计 | 读 `/api/gacha` 的本地缓存渲染,点「同步最新记录」才联网。视图按账号留一份在 `S.gachaOf`,切账号 / 切菜单回来直接复用(不闪「读取中」);切换侧栏分组时还原 `S.lastOfGame` 记下的上次那个号。已同步过但确实 0 条的号显示「这个账号没有抽卡记录」,不再劝人反复拉 | +| 抽卡统计 | 读 `/api/gacha` 的本地缓存渲染,点「同步最新记录」才联网。头像走 `/api/avatar/`:``,加载失败自己移除,露出 `.op-av` 的首字母与星级渐变底(不需要前端判状态)。视图按账号留一份在 `S.gachaOf`,切账号 / 切菜单回来直接复用(不闪「读取中」);切换侧栏分组时还原 `S.lastOfGame` 记下的上次那个号。已同步过但确实 0 条的号显示「这个账号没有抽卡记录」,不再劝人反复拉 | | 森空岛签到 | 左右两块卡片:左「全局签到」一键签所有账号(方舟 + 终末地),右「单号签到」只签当前账号;各自一块日志,跑完底部给「成功 / 已签到 / 失败 / 跳过」汇总。终末地账号不显示这个 tab(签到本身支持终末地,全局里照样签) | | ~~配置修改~~ | 这一版不做,tab 已删(不留占位) | diff --git a/docs/tools-smoketest.md b/docs/tools-smoketest.md index 31ec8de..fbef22d 100644 --- a/docs/tools-smoketest.md +++ b/docs/tools-smoketest.md @@ -901,3 +901,20 @@ v2.8.7 装好后桌面快捷方式还是旧图。`install.ps1` 换完文件直 打桩 `update_dir/_current/_state/_save_state`,只在临时目录写 `pending.json`, 不碰真实 `update/` 和 `config/appupdate.json`;最后真调一次函数验 API 可用。 + +### B84 干员头像按需下载(2026-11-28) + +抽卡界面要显示干员头像,但 469 张 96px WebP 约 2MB,不能进安装包。做法是 +「用到哪张下哪张」,B84 钉的是这条链路的边界: + +- **id 校验**:只认 `[A-Za-z0-9_]`,`../x`、`a/b`、超长串一律当场 `KeyError`, + 别指望后面的路径拼接兜住穿越; +- **缓存优先**:命中 `config/cache/avatar/.webp` 就直接返回,不再发请求; +- **索引决定要不要走镜像**:`pack-data` 上 `resources/avatars/avatar-index.json` 里有这张才去试 + 三个镜像,没有就直接走 PRTS 兜底——否则每张都要白等三次 404/超时(实测首张 5.7s→0.7s); +- **兜底**:镜像全挂时从 `torappu.prts.wiki/assets/char_avatar/.png` 取原图, + 服务端转 96px WebP;转不了就存原 PNG,宁可大一点也别丢功能; +- **负缓存**:两条路都挂记 5 分钟,第二次请求不再打网络(列表页一屏十几张,不能每刷一次重打一遍); +- **不认假图**:空包、HTML 错误页、只有 `RIFF` 头的假 WebP 都不许落盘。 + +打桩 `settings.CONFIG_DIR`、`avatar_index`、`_from_mirrors`、`_from_prts`,不联网、不写真缓存。 diff --git a/frontend/app.js b/frontend/app.js index 8f4b9e8..6eb2ed2 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -19,6 +19,8 @@ const S = { gachaOf: {}, // file → 已加载过的抽卡视图:切账号/切菜单回来直接复用,不再转圈 lastOfGame: { arknights: '', endfield: '' }, // 每栏上次看的是哪个号(切回这一栏时还原) gachaTab: 'char', // 抽卡统计里看哪个池:char 角色寻访 / weapon 武器申领(终末地专用) + gachaView: 'pool', // 抽卡统计当前视图:pool 按卡池 / rarity 星级分布 / records 抽卡记录 + gachaPage: 1, // 抽卡记录分页(一页 20 条),切号 / 切口径时回第 1 页 sideGame: 'arknights', // 左侧账号列表当前看哪一栏:arknights / endfield gachaByGame: false, // 抽卡统计是因为选中终末地账号才打开的(切回方舟时自动回作业获取) }; @@ -325,6 +327,18 @@ function setSideGame(g) { renderAccounts(); } +/* 账号头像:有看板娘就用看板娘(snap.account.secretary.charId),没有就退回 + 昵称首字。img 绝对定位盖在首字上,onerror 自删——加载失败/接口 404 都会 + 自然露出首字,前端不用记状态。MAA 导入的账号没有 secretary,永远走首字。 */ +function acctAvatar(a, cls) { + const ch = (a.nickName || '?').replace(/[##].*$/, '').slice(0, 1); + const id = (a.secretary && a.secretary.charId) || ''; + const pic = id + ? `` + : ''; + return `${pic}${esc(ch)}`; +} + function renderAccounts() { const box = $('#account-list'); renderGameSwitch(); @@ -343,7 +357,6 @@ function renderAccounts() { const st = a.stats || {}; const ef = a.game === 'endfield'; // 终末地:没有练度数据,副标题换口径 const cls = ef ? 'ef' : (st.sixStarCount >= 120 ? 'r6' : (st.sixStarCount >= 60 ? 'r5' : '')); - const ch = (a.nickName || '?').replace(/[##].*$/, '').slice(0, 1); // 渠道名单独上色:B 站服粉、官服亮白,其它渠道不动(同 style.css .acct-ch) const chName = a.channelName || '官服'; const chCls = /bilibili/i.test(chName) ? ' bili' : (/^官服/.test(chName) ? ' official' : ''); @@ -354,7 +367,7 @@ function renderAccounts() { return ` `).join('')} -
` : ''; + const nums = pageWindow(page, pages).map(p => (p === '…' + ? '…' + : ``)).join(''); + + return `
+
抽卡记录最新在前 · 共 ${recs.length} 条${newTotal + ? ` · ${newTotal} new` : ''}
+ + + + ${rows || ''} +
${ef ? (tab === 'weapon' ? '武器' : '角色') : '干员'}星级卡池时间
没有记录
+
+ +
${nums}
+ + 第 ${page} / ${pages} 页${newHere ? ` · 本页 ${newHere} 个 new` : ''} +
+
`; +} + +function paintGachaBody() { + const d = S.gacha; + const body = $('#gacha-body'); + if (!d || !body) return; + const s = d.summary || {}; + const ef = d.game === 'endfield'; + const tab = ef ? S.gachaTab : 'char'; + // 终末地每个 tab 只在 summary.char / .weapon 里取;方舟就是顶层那份 + const cur = ef ? ((tab === 'weapon' ? s.weapon : s.char) || GACHA_BLANK) : s; + const view = GACHA_VIEWS.some(v => v[0] === S.gachaView) ? S.gachaView : 'pool'; const cards = `
${cur.total}${ef @@ -5806,39 +5947,29 @@ function paintGachaBody() {
${cur.avgPity || '—'}平均出六星(抽)
${cur.lastSixGap}距上次六星(抽)
`; - const poolSec = (cur.pools || []).length ? ` -
-
按卡池按最近抽卡时间排序${(cur.pools.length > 12) - ? `,只列最近 12 个(共 ${cur.pools.length} 个)` : ''}
-
${poolCards}
-
` : ''; - - const rarSec = ` -
-
星级分布${esc(cur.firstAt)} — ${esc(cur.lastAt)}
-
${bars}
-
`; + const views = `
+ ${GACHA_VIEWS.map(([k, label]) => { + const n = k === 'pool' ? (cur.pools || []).length : (k === 'records' ? (cur.total || 0) : ''); + return ``; + }).join('')} +
`; - const recSec = ` -
-
最近记录最新在前${cur.total > 60 ? `,只列最近 60 条(共 ${cur.total} 条)` : ''}
- - - ${recRows} -
${ef ? (tab === 'weapon' ? '武器' : '角色') : '干员'}星级卡池时间
-
`; + if (d.game === 'endfield' && S.gachaTab !== 'weapon') S.gachaTab = 'char'; + const scope = ef ? `
+ ${[['char', '角色'], ['weapon', '武器']].map(([k, label]) => + ``).join('')} +
` : ''; - // 两个游戏同一套版式:按卡池(六星挂在池下)→ 星级分布 → 最近记录 - const secs = [poolSec, rarSec, recSec]; + const content = view === 'pool' ? gachaPoolSec(cur) + : (view === 'rarity' ? gachaRaritySec(cur, ef) : gachaRecSec(cur, ef, tab)); body.innerHTML = ` - ${tabs}
${cards}
+
${views}${scope}
${ef ? `
官方记录接口只保留最近一段:角色 ${(s.char || {}).total || 0} 抽 · 武器 ${(s.weapon || {}).total || 0} 抽。 更早的记录接口不返回,所以这里比实际总抽数少(不是统计漏了)。
` : ''} - - ${secs.join('')} - + ${content}
! 保底按卡池连续计数(同池每抽 +1,出六星清零);抽卡记录只保留最近一段窗口, 最早几次六星的「第几抽」只是窗口内的下限,不是真实垫抽数。 @@ -5846,12 +5977,26 @@ function paintGachaBody() {
`; - $$('.gacha-tab', body).forEach(b => b.addEventListener('click', () => { + const backTop = () => { const sc = $('.gacha-scroll'); if (sc) sc.scrollTop = 0; }; + $$('[data-gview]', body).forEach(b => b.addEventListener('click', () => { + if (S.gachaView === b.dataset.gview) return; + S.gachaView = b.dataset.gview; + paintGachaBody(); + backTop(); + })); + $$('[data-gtab]', body).forEach(b => b.addEventListener('click', () => { if (S.gachaTab === b.dataset.gtab) return; S.gachaTab = b.dataset.gtab; + S.gachaPage = 1; + paintGachaBody(); + backTop(); + })); + $$('[data-page]', body).forEach(b => b.addEventListener('click', () => { + const p = Number(b.dataset.page); + if (!p || p === S.gachaPage) return; + S.gachaPage = p; paintGachaBody(); - const sc = $('.gacha-scroll'); - if (sc) sc.scrollTop = 0; + backTop(); })); } diff --git a/frontend/style.css b/frontend/style.css index fabe979..5bd3a3d 100644 --- a/frontend/style.css +++ b/frontend/style.css @@ -229,9 +229,18 @@ input:focus, select:focus, button:focus-visible { outline: none; } font-size: 14px; font-weight: 700; color: #061018; flex: 0 0 auto; + position: relative; + overflow: hidden; background: linear-gradient(150deg, #6ee7d7, #7f8cf5); letter-spacing: -.5px; } +/* 看板娘头像:绝对定位盖在昵称首字上。加载失败时 img 被 onerror 删掉, + 首字自然露出来——所以文字要一直留在 DOM 里,不能换掉 */ +.avatar img, .hero-avatar img, +.set-acct .avatar img { + position: absolute; inset: 0; width: 100%; height: 100%; + object-fit: cover; display: block; border-radius: inherit; +} .avatar.r6 { background: linear-gradient(150deg, #ffd479, #ff9a5c); } .avatar.r5 { background: linear-gradient(150deg, #e9d5a1, #c9a86a); color: #1a1305; } /* 终末地账号:紫青渐变,和明日方舟账号一眼分开 */ @@ -379,6 +388,8 @@ input:focus, select:focus, button:focus-visible { outline: none; } background: linear-gradient(145deg, rgba(94, 234, 212, 0.9), rgba(139, 147, 255, 0.9)); color: #05100f; font-weight: 800; font-size: 14px; flex: 0 0 auto; + position: relative; + overflow: hidden; } .hero-name { font-size: 15px; font-weight: 700; letter-spacing: .2px; @@ -702,6 +713,98 @@ input:focus, select:focus, button:focus-visible { outline: none; } .rec-table td:last-child { text-align: right; color: var(--text-3); font-variant-numeric: tabular-nums; } .rec-more { padding: 10px 4px 0; font-size: 11.5px; color: var(--text-3); text-align: center; } +/* ---- 抽卡统计:视图 tab(按卡池 / 星级分布 / 抽卡记录)+ 终末地口径 ---- */ +.gacha-bar { display: flex; align-items: center; gap: 10px; margin-top: 14px; flex-wrap: wrap; } +.gacha-views { display: inline-flex; gap: 2px; padding: 3px; border-radius: 11px; + border: 1px solid var(--line); background: rgba(var(--tint), 0.035); } +.gacha-view { appearance: none; border: 0; background: transparent; font: inherit; + display: inline-flex; align-items: center; gap: 7px; height: 30px; padding: 0 14px; + border-radius: 9px; font-size: 12.5px; font-weight: 600; letter-spacing: .2px; + color: var(--text-3); cursor: pointer; transition: .15s ease; } +.gacha-view i { font-style: normal; min-width: 16px; padding: 0 4px; border-radius: 5px; + font-size: 10.5px; line-height: 15px; text-align: center; color: var(--text-3); + background: rgba(var(--tint), 0.08); font-variant-numeric: tabular-nums; } +.gacha-view:hover { color: var(--text-2); background: rgba(var(--tint), 0.05); } +.gacha-view.active { color: #071410; background: linear-gradient(140deg, var(--mint), #4fd7c8); } +.gacha-view.active i { color: #071410; background: rgba(0, 0, 0, 0.16); } +.gacha-scope { display: inline-flex; gap: 2px; padding: 3px; border-radius: 11px; + border: 1px solid var(--line); background: rgba(var(--tint), 0.035); margin-left: auto; } +.gacha-scope-btn { appearance: none; border: 0; background: transparent; font: inherit; + height: 26px; padding: 0 12px; border-radius: 8px; font-size: 12px; font-weight: 600; + color: var(--text-3); cursor: pointer; } +.gacha-scope-btn:hover { color: var(--text-2); background: rgba(var(--tint), 0.05); } +.gacha-scope-btn.active { color: var(--text); background: rgba(var(--tint), 0.10); } + +/* ---- 干员头像:后端按需下载;加载失败 img 自己被移除,露出首字母 ---- */ +.op-av { position: relative; flex: 0 0 auto; width: 30px; height: 30px; border-radius: 7px; + overflow: hidden; display: inline-flex; align-items: center; justify-content: center; + font-size: 13px; font-weight: 650; color: var(--text-2); + background: rgba(var(--tint), 0.08); } +.op-av::before { content: attr(data-ch); } +.op-av img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; display: block; } +.op-av.r6 { background: linear-gradient(150deg, #ffd479, #ff9a5c); color: #1a1305; } +.op-av.r5 { background: linear-gradient(150deg, #e9d5a1, #c9a86a); color: #1a1305; } +.op-av.r4 { background: linear-gradient(150deg, #c084fc, #9333ea); color: #0b1020; } +.op-av.r3 { background: linear-gradient(150deg, #7dd3fc, #0ea5e9); color: #0b1020; } +.op-av.r2 { background: linear-gradient(150deg, #6ee7a8, #34d399); color: #062117; } + +/* ---- 星级分布补充:实际 vs 公示 / 六星落在第几抽 / 六星墙 ---- */ +.rar-extra { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.15fr); + gap: 12px; margin-top: 16px; } +@media (max-width: 900px) { .rar-extra { grid-template-columns: minmax(0, 1fr); } } +.rar-panel { padding: 12px 14px 14px; border-radius: 14px; border: 1px solid var(--line); + background: rgba(var(--tint), 0.022); } +.rar-panel h4, .wall-wrap h4 { display: flex; align-items: baseline; gap: 8px; + font-size: 12px; font-weight: 650; color: var(--text-2); margin: 0 0 10px; } +.rar-panel h4 small, .wall-wrap h4 small { font-size: 10.5px; font-weight: 400; color: var(--text-3); } +.vs-row { display: flex; align-items: center; gap: 10px; font-size: 11.5px; padding: 4px 0; } +.vs-row > i { flex: 0 0 30px; font-style: normal; font-weight: 600; } +.vs-row > i.r6 { color: var(--star); } +.vs-row > i.r5 { color: #e9d07a; } +.vs-row > i.r4 { color: #c084fc; } +.vs-row > i.r3 { color: #7dd3fc; } +.vs-row > b { flex: 0 0 62px; font-variant-numeric: tabular-nums; color: var(--text); } +.vs-row > span { flex: 1 1 auto; color: var(--text-3); } +.vs-row > em { font-style: normal; font-variant-numeric: tabular-nums; font-weight: 600; } +.vs-row > em.up { color: var(--mint); } +.vs-row > em.down { color: var(--rose); } +.vs-row > em.flat { color: var(--text-3); } + +.hist { display: flex; align-items: flex-end; gap: 6px; height: 96px; padding-top: 12px; } +.hist-col { flex: 1 1 0; height: 100%; display: flex; flex-direction: column; align-items: center; gap: 5px; min-width: 0; } +.hist-col > b { font-size: 10px; font-weight: 600; color: var(--text-3); font-variant-numeric: tabular-nums; } +.hist-track { flex: 1 1 auto; width: 100%; display: flex; align-items: flex-end; } +.hist-bar { width: 100%; min-height: 2px; border-radius: 5px 5px 3px 3px; + background: linear-gradient(180deg, var(--star), rgba(255, 154, 92, 0.55)); } +.hist-col > span { font-size: 9.5px; color: var(--text-3); white-space: nowrap; } + +.wall-wrap { margin-top: 16px; } +.six-wall { display: flex; flex-wrap: wrap; gap: 8px; } +.wall-item { display: flex; align-items: center; gap: 7px; padding: 5px 9px 5px 5px; + border-radius: 10px; border: 1px solid var(--line); background: rgba(var(--tint), 0.022); + font-size: 11.5px; color: var(--text-2); max-width: 158px; } +.wall-item > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.wall-item .op-av { width: 26px; height: 26px; border-radius: 6px; font-size: 11px; } + +/* ---- 抽卡记录分页 ---- */ +.rec-table .c-av { width: 40px; padding-right: 0; } +.rec-table tr.is-new td { background: rgba(94, 234, 212, 0.035); } +.rec-pager { display: flex; align-items: center; gap: 8px; margin-top: 12px; flex-wrap: wrap; } +.pg-step, .pg-btn { appearance: none; font: inherit; cursor: pointer; + border: 1px solid var(--line); background: rgba(var(--tint), 0.03); color: var(--text-2); + border-radius: 8px; height: 28px; padding: 0 10px; font-size: 11.5px; } +.pg-step:hover:not(:disabled), .pg-btn:hover { background: rgba(var(--tint), 0.07); color: var(--text); } +.pg-step:disabled { opacity: .38; cursor: default; } +.pg-nums { display: flex; align-items: center; gap: 4px; } +.pg-btn { position: relative; min-width: 28px; padding: 0 6px; font-variant-numeric: tabular-nums; } +.pg-btn.active { border-color: transparent; color: #071410; background: var(--mint); font-weight: 650; } +.pg-btn u { position: absolute; top: 3px; right: 3px; width: 4px; height: 4px; border-radius: 50%; + background: var(--rose); text-decoration: none; } +.pg-btn.active u { background: #071410; } +.pg-gap { color: var(--text-3); font-size: 11.5px; padding: 0 2px; } +.pg-info { margin-left: auto; font-size: 11.5px; color: var(--text-3); } +.pg-info b { color: var(--text-2); } + .gacha-empty { padding: 60px 20px; text-align: center; diff --git a/tools/smoketest/smoke_test.py b/tools/smoketest/smoke_test.py index 1fde8ab..6bfd321 100644 --- a/tools/smoketest/smoke_test.py +++ b/tools/smoketest/smoke_test.py @@ -8958,6 +8958,10 @@ def main(): lambda: check_app_icon(tmp)) r.check('B83 换完 exe 刷图标缓存(不刷重启也不管用 / 装失败不白刷)', lambda: check_icon_cache_refresh(tmp)) + r.check('B84 干员头像按需下载(缓存优先 / 索引决定走镜像 / 兜底 / 负缓存)', + lambda: check_avatar_cache(tmp)) + r.check('B85 账号头像走看板娘(无 secretary 退回首字 / 资源统一 pack-data)', + lambda: check_account_avatar(tmp)) finally: shutil.rmtree(tmp, ignore_errors=True) @@ -9752,5 +9756,160 @@ def check_icon_cache_refresh(tmp): appupdate._save_state, appupdate.refresh_icon_cache) = keep +def check_avatar_cache(tmp): + """B84 干员头像按需下载:安装包不带图,用到哪张下哪张 + + 2026-11-28 加。三条线被钉死: + + - **安装包不许变大**:350+ 张 96px WebP 约 2MB,只能落 ``config/cache/avatar``; + - **索引决定要不要走镜像**:数据分支没这张时还去挨个试三个镜像,等于每张 + 白等 5 秒(实测首张 5.7s → 0.7s); + - **拿不到就 404,前端回落首字母**:负缓存 5 分钟,别让列表页每次刷新 + 都把失败请求重打一遍。 + + 全程打桩,不联网、不写真 config(``settings.CONFIG_DIR`` 指到临时目录)。 + """ + from core import avatarcache, settings + + keep = (settings.CONFIG_DIR, avatarcache.avatar_index, + avatarcache._from_mirrors, avatarcache._from_prts, + dict(avatarcache._neg)) + try: + settings.CONFIG_DIR = os.path.join(tmp, 'cfg-avatar') + avatarcache._neg.clear() + + webp = b'RIFF' + b'\x00' * 4 + b'WEBP' + b'\x00' * 2000 + png = b'\x89PNG\r\n\x1a\n' + b'\x00' * 2000 + + # 1) id 只认 [A-Za-z0-9_],路径穿越必须当场拒绝 + for bad in ['../x', 'a/b', '', 'x' * 80, 'char_002.amiya', '..']: + try: + avatarcache.fetch(bad) + raise AssertionError('id 没校验住:%r' % (bad,)) + except KeyError: + pass + + # 2) 索引里有 → 走镜像;落盘后第二次不再下载 + avatarcache.avatar_index = lambda: {'char_002_amiya': {}} + calls = [] + avatarcache._from_mirrors = lambda cid: (calls.append('m'), (webp, 'webp'))[1] + avatarcache._from_prts = lambda cid: (calls.append('p'), None)[1] + data, ext = avatarcache.fetch('char_002_amiya') + assert ext == 'webp' and data[:4] == b'RIFF', (ext, data[:8]) + assert calls == ['m'], calls + assert os.path.isfile(os.path.join(avatarcache.cache_dir(), + 'char_002_amiya.webp')) + avatarcache.fetch('char_002_amiya') + assert calls == ['m'], '命中缓存后又去下载了:%r' % (calls,) + + # 3) 索引里没有 → 不许空跑三个镜像,直接兜底 PRTS + calls.clear() + avatarcache.avatar_index = lambda: {} + avatarcache._from_prts = lambda cid: (calls.append('p'), (png, 'png'))[1] + data, ext = avatarcache.fetch('char_1001_amiya2') + assert ext == 'png' and calls == ['p'], (ext, calls) + + # 4) 两条路都挂 → KeyError;5 分钟内不再重试(负缓存) + calls.clear() + avatarcache.avatar_index = lambda: {'char_999_none': {}} + avatarcache._from_mirrors = lambda cid: (calls.append('m'), None)[1] + avatarcache._from_prts = lambda cid: (calls.append('p'), None)[1] + for _ in range(2): + try: + avatarcache.fetch('char_999_none') + raise AssertionError('拿不到却返回了') + except KeyError: + pass + assert calls == ['m', 'p'], '负缓存没生效,重复打了网络:%r' % (calls,) + + # 5) 不是图片的字节(CDN 回一段 HTML / 空包)一律不认 + assert avatarcache._ok(b'404 not found' * 100) == '' + assert avatarcache._ok(b'') == '' + assert avatarcache._ok(b'RIFF' + b'\x00' * 4000) == '', '假的 RIFF 也认了' + + # 6) 占用统计与清理 + st = avatarcache.stats() + assert st['files'] >= 2, st + avatarcache.clear() + assert avatarcache.stats()['files'] == 0, '清缓存没清干净' + finally: + (settings.CONFIG_DIR, avatarcache.avatar_index, + avatarcache._from_mirrors, avatarcache._from_prts) = keep[:4] + avatarcache._neg.clear() + avatarcache._neg.update(keep[4]) + + +def check_account_avatar(tmp): + """B85 账号头像改成看板娘 + 资源统一到 pack-data + + 2026-11-28 加。用户提的三件事,各钉一条: + + - **账号头像不许再是首字**:森空岛同步时已经存了 ``account.secretary`` + (charId / 皮肤),列表页要拿它去 ``/api/avatar/`` 取图; + 没有 secretary 的账号(MAA 导入的、终末地的)才退回昵称首字; + - **头像资源只走 pack-data**:之前单独开了 ``avatar-data`` 分支,是因为 + pack.yml 强推会冲掉它。现在 pack.yml 改成「继承整条分支再覆盖自己那 + 三个文件」,头像和主题都住 pack-data,客户端不该再认别的分支名; + - **图片要有尺寸约束**:``object-fit: cover`` 缺失时 96px 的正方形会按 + 原尺寸撑破 36px 的圆角块。 + """ + import json + from core import accounts, packrepo, settings + + repo = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + js = open(os.path.join(repo, 'frontend', 'app.js'), encoding='utf-8').read() + css = open(os.path.join(repo, 'frontend', 'style.css'), encoding='utf-8').read() + + # 1) 后端把 secretary 带出来(列表页直接用,不用再请求详情) + keep_dir = settings.ACCOUNTS_DIR + d = os.path.join(tmp, 'cfg-acct') + os.makedirs(d, exist_ok=True) + snap = { + 'account': {'uid': '1', 'nickName': '测试#1234', 'channelName': '官服', + 'secretary': {'charId': 'char_4080_lin', 'name': '林', + 'skinId': 'char_4080_lin@summer#19'}}, + 'stats': {'charCount': 100, 'charTotal': 440}, + } + with open(os.path.join(d, '测试#1234 官服.json'), 'w', encoding='utf-8') as f: + json.dump(snap, f, ensure_ascii=False) + # 没有 secretary 的(MAA 导入的账号长这样) + with open(os.path.join(d, '纯导入.json'), 'w', encoding='utf-8') as f: + json.dump({'account': {'uid': '2', 'nickName': '纯导入'}, + 'stats': {}}, f, ensure_ascii=False) + try: + settings.ACCOUNTS_DIR = d + rows = {r['file']: r for r in accounts.list_accounts()} + assert rows['测试#1234 官服.json']['secretary']['charId'] == 'char_4080_lin', \ + rows['测试#1234 官服.json'].get('secretary') + assert rows['纯导入.json']['secretary'] == {}, rows['纯导入.json']['secretary'] + finally: + settings.ACCOUNTS_DIR = keep_dir + + # 2) 前端三处头像都走同一个 helper,不许再各自拼首字 + assert 'function acctAvatar(' in js, 'app.js 没有 acctAvatar' + assert "a.secretary && a.secretary.charId" in js, '没读 secretary' + assert "`\"\"`" in js, \ + 'acctAvatar 里的 img 不完整(要么缺 lazy,要么缺 onerror 自删)' + assert js.count('${acctAvatar(a, cls)}') == 2, \ + '侧栏/设置页应该都用 acctAvatar,实际 %d 处' % js.count('${acctAvatar(a, cls)}') + assert "hBox.classList.toggle('has-pic', !!hSec)" in js, '顶部头像没用看板娘' + assert "classList.remove('ef', 'has-pic')" in js, '删光账号后头像状态没清干净' + + # 3) 样式:图片铺满 + 裁边 + assert '.avatar img, .hero-avatar img' in css, 'style.css 缺头像图片规则' + assert 'object-fit: cover' in css, '头像没写 object-fit,会拉伸变形' + assert '.avatar {' in css and 'position: relative' in css, '.avatar 缺定位(img 绝对定位要靠它)' + + # 4) 头像资源统一走 pack-data(不再有 AVATAR_BRANCH 这条岔路) + assert not hasattr(packrepo, 'AVATAR_BRANCH'), 'packrepo 还留着 AVATAR_BRANCH' + assert not hasattr(packrepo, 'avatar_urls'), 'packrepo 还留着 avatar_urls' + for u in packrepo.mirror_urls('resources/avatars/char_002_amiya.webp'): + assert '/' + packrepo.PACK_BRANCH + '/' in u or '@' + packrepo.PACK_BRANCH + '/' in u, \ + '头像地址没指向 pack-data:%s' % u + from core import avatarcache + src = open(avatarcache.__file__, encoding='utf-8').read() + assert 'avatar_urls' not in src, 'avatarcache 还在用 avatar_urls' + + if __name__ == '__main__': sys.exit(main()) \ No newline at end of file diff --git a/tools/sync_avatars.py b/tools/sync_avatars.py new file mode 100644 index 0000000..f1212a6 --- /dev/null +++ b/tools/sync_avatars.py @@ -0,0 +1,207 @@ +# -*- coding: utf-8 -*- +"""把干员头像从 PRTS Wiki 抓下来,压成 96px WebP,推到 pack-data 分发 + +为什么走 PRTS Wiki 而不是官方 CDN: + - 官方资源没有稳定的公开索引,名字和 bundle 路径一一对应还要自己解包; + - PRTS Wiki 的 ``头像_<干员名>.png`` 是社区维护的现成索引,带 MediaWiki + API(``list=allimages&aiprefix=头像``),能分页拿全,不用爬 HTML; + - 产物只有几 KB 一张,350 个干员全量约 2.2MB——放 pack-data 的 resources/avatars/, + 客户端用到哪张下哪张,安装包一个字节都不加。 + +用法: + python tools/sync_avatars.py # 全量,写 build/avatars/ + python tools/sync_avatars.py --limit 30 # 先跑一小批看看 + python tools/sync_avatars.py --out D:\\tmp\\av + python tools/sync_avatars.py --check-only # 只报能不能连上、命中多少 + +产物: + /.webp + /avatar-index.json {count, chars: {id: {sha256, bytes, name}}} + +退出码:0 成功;2 有干员没匹配到头像(仍写出已拿到的);1 网络/环境错误。 +""" +from __future__ import annotations + +import argparse +import hashlib +import io +import json +import os +import sys +import time +import urllib.parse +import urllib.request +from concurrent.futures import ThreadPoolExecutor, as_completed + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +PACK = os.path.join(ROOT, 'resources', 'arknights.json') + +API = 'https://prts.wiki/api.php' +UA = 'MAA-PRTS-avatar-sync/1.0 (+https://github.com/OriginiumLab/MAA-PRTS)' +SIZE = 96 +QUALITY = 80 +THREADS = 8 + + +def _get(url: str, timeout: float = 25) -> bytes: + req = urllib.request.Request(url, headers={'User-Agent': UA}) + with urllib.request.urlopen(req, timeout=timeout) as r: + return r.read() + + +def list_avatars() -> dict: + """PRTS Wiki 上所有「头像_*.png」:{文件名: 原图地址}""" + out = {} + cont = {} + while True: + q = { + 'action': 'query', 'list': 'allimages', 'aiprefix': '头像', + 'ailimit': '500', 'format': 'json', + } + q.update(cont) + url = API + '?' + urllib.parse.urlencode(q) + d = json.loads(_get(url).decode('utf-8')) + for it in (d.get('query') or {}).get('allimages') or []: + out[it.get('name') or ''] = it.get('url') or '' + cont = d.get('continue') or {} + if not cont: + break + time.sleep(0.3) + return out + + +def pick(files: dict, name: str) -> str: + """按干员名找头像地址:先精确,再带消歧后缀(头像_X(卫戍协议).png)""" + exact = files.get('头像_%s.png' % name) + if exact: + return exact + prefix = '头像_%s(' % name + for fn, url in files.items(): + if fn.startswith(prefix) and fn.endswith(').png'): + return url + return '' + + +def to_webp(raw: bytes) -> bytes: + from PIL import Image + im = Image.open(io.BytesIO(raw)).convert('RGBA').resize((SIZE, SIZE), Image.LANCZOS) + buf = io.BytesIO() + im.save(buf, 'WEBP', quality=QUALITY, method=4) + return buf.getvalue() + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument('--out', default=os.path.join(ROOT, 'build', 'avatars')) + ap.add_argument('--limit', type=int, default=0) + ap.add_argument('--only', default='', help='逗号分隔的 charId,只处理这些') + ap.add_argument('--force', action='store_true', help='已存在的也重下') + ap.add_argument('--check-only', action='store_true') + args = ap.parse_args() + + try: + pack = json.load(open(PACK, encoding='utf-8')) + except Exception as e: + print('读不到 %s:%s' % (PACK, e)) + return 1 + chars = pack.get('chars') or {} + ids = list(chars.keys()) + if args.only: + want = {s.strip() for s in args.only.split(',') if s.strip()} + ids = [i for i in ids if i in want] + if args.limit: + ids = ids[:args.limit] + + try: + files = list_avatars() + except Exception as e: + print('拉 PRTS Wiki 列表失败:%s' % e) + return 1 + print('PRTS Wiki 上 %d 个头像文件;本地干员 %d 个' % (len(files), len(ids))) + + os.makedirs(args.out, exist_ok=True) + jobs = [] + missing = [] + for cid in ids: + name = (chars.get(cid) or {}).get('name') or '' + url = pick(files, name) + if not url: + missing.append('%s %s' % (cid, name)) + continue + dst = os.path.join(args.out, cid + '.webp') + if os.path.isfile(dst) and not args.force: + continue + jobs.append((cid, name, url)) + + print('要处理 %d 张,没匹配到 %d 个' % (len(jobs), len(missing))) + if args.check_only: + for m in missing[:20]: + print(' MISS', m) + return 0 if jobs else 2 + + index = {} + old = os.path.join(args.out, 'avatar-index.json') + if os.path.isfile(old): + try: + index = (json.load(open(old, encoding='utf-8')) or {}).get('chars') or {} + except Exception: + index = {} + + failed = [] + + def work(job): + cid, name, url = job + try: + raw = _get(url) + webp = to_webp(raw) + with open(os.path.join(args.out, cid + '.webp'), 'wb') as f: + f.write(webp) + return cid, name, webp + except Exception as e: # noqa: BLE001 + failed.append('%s %s: %s' % (cid, name, e)) + return None + + done = 0 + with ThreadPoolExecutor(max_workers=THREADS) as ex: + for fut in as_completed([ex.submit(work, j) for j in jobs]): + r = fut.result() + if not r: + continue + cid, name, webp = r + index[cid] = { + 'name': name, + 'bytes': len(webp), + 'sha256': hashlib.sha256(webp).hexdigest(), + } + done += 1 + if done % 25 == 0: + print(' ... %d/%d' % (done, len(jobs))) + + total = sum(v.get('bytes') or 0 for v in index.values()) + meta = { + 'schema': 1, + 'generatedAt': time.strftime('%Y-%m-%dT%H:%M:%S'), + 'size': SIZE, + 'count': len(index), + 'bytes': total, + 'chars': index, + } + with open(old, 'w', encoding='utf-8') as f: + json.dump(meta, f, ensure_ascii=False, indent=1) + f.write('\n') + + print('完成 %d 张,索引 %d 条,合计 %.1f MB' + % (done, len(index), total / 1048576.0)) + if failed: + print('失败 %d 个,前 10 个:' % len(failed)) + for f_ in failed[:10]: + print(' ', f_) + if missing: + print('没匹配到头像 %d 个,前 10 个:' % len(missing)) + for m in missing[:10]: + print(' ', m) + return 0 if not failed and not missing else 2 + + +if __name__ == '__main__': + sys.exit(main())