Add Web 2 workspace and controlled deployment updates
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
# Only runtime source and the shipped static catalog enter the build context.
|
||||
*
|
||||
!Dockerfile
|
||||
!ranch_assistant/
|
||||
!ranch_assistant/**
|
||||
!ranch_web/
|
||||
!ranch_web/**
|
||||
**/__pycache__/
|
||||
**/*.pyc
|
||||
**/*.pyo
|
||||
**/tests/
|
||||
**/.impeccable/
|
||||
.impeccable/
|
||||
test-artifacts/
|
||||
local_state/
|
||||
logs/
|
||||
.git/
|
||||
.env
|
||||
.env.*
|
||||
.image.env
|
||||
**/*.db
|
||||
**/*.sqlite*
|
||||
**/*.key
|
||||
**/*.pem
|
||||
**/*.jsonl
|
||||
**/*.zip
|
||||
!ranch_assistant/data/progression_battles.zip
|
||||
ranch_assistant/*_gui.py
|
||||
ranch_assistant/gui.py
|
||||
ranch_assistant/native_widgets.py
|
||||
ranch_assistant/table_widgets.py
|
||||
ranch_assistant/README.md
|
||||
ranch_web/README.md
|
||||
ranch_web/DESIGN.md
|
||||
ranch_web/PRODUCT.md
|
||||
@@ -0,0 +1,101 @@
|
||||
name: Web image
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ["v2.*"]
|
||||
pull_request:
|
||||
paths:
|
||||
- ranch_web/**
|
||||
- ranch_assistant/**
|
||||
- deploy/web/**
|
||||
- Dockerfile
|
||||
- .dockerignore
|
||||
- compose.yaml
|
||||
- .github/workflows/web-image.yml
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: web-image-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
image:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- name: Validate source version and publish tag
|
||||
id: version
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
REF_TYPE: ${{ github.ref_type }}
|
||||
REF_NAME: ${{ github.ref_name }}
|
||||
REPOSITORY: ${{ github.repository }}
|
||||
run: |
|
||||
python - <<'PY'
|
||||
import os
|
||||
from ranch_web import __version__
|
||||
from ranch_web.updates import current_version_key, validate_image_release
|
||||
current_version_key(__version__)
|
||||
publish = os.environ["EVENT_NAME"] == "push" and os.environ["REF_TYPE"] == "tag"
|
||||
tag = os.environ["REF_NAME"]
|
||||
if publish:
|
||||
validate_image_release(os.environ["REPOSITORY"], tag, __version__)
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output:
|
||||
print(f"version={__version__}", file=output)
|
||||
print(f"publish={'true' if publish else 'false'}", file=output)
|
||||
print(f"tag={tag if publish else ''}", file=output)
|
||||
PY
|
||||
- name: Install Web dependencies only
|
||||
run: python -m pip install -r ranch_web/requirements.txt
|
||||
- name: Offline updater regression
|
||||
run: python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater -v
|
||||
- name: Build image
|
||||
env:
|
||||
WEB_VERSION: ${{ steps.version.outputs.version }}
|
||||
VCS_REF: ${{ github.sha }}
|
||||
run: docker build --build-arg "WEB_VERSION=$WEB_VERSION" --build-arg "VCS_REF=$VCS_REF" --tag ranch-web-smoke .
|
||||
- name: Offline container health, persistence permissions, and graceful stop
|
||||
run: |
|
||||
docker run --detach --name ranch-web-smoke --network none --read-only \
|
||||
--cap-drop ALL --security-opt no-new-privileges \
|
||||
--tmpfs /tmp:rw,noexec,nosuid,size=64m,mode=1777 \
|
||||
--tmpfs /data:rw,uid=10001,gid=10001,mode=0700 \
|
||||
--env RANCH_WEB_PASSWORD=ephemeral-offline-ci-only ranch-web-smoke
|
||||
for attempt in $(seq 1 35); do
|
||||
health=$(docker inspect --format '{{.State.Health.Status}}' ranch-web-smoke)
|
||||
if [ "$health" = healthy ]; then break; fi
|
||||
if [ "$health" = unhealthy ]; then exit 1; fi
|
||||
sleep 2
|
||||
done
|
||||
test "$health" = healthy
|
||||
docker exec ranch-web-smoke python -c "import importlib.util,os,pathlib; assert os.getuid()==10001; assert importlib.util.find_spec('PySide6') is None; p=pathlib.Path('/data/.permission-check'); p.write_text('ok'); assert p.read_text()=='ok'; p.unlink()"
|
||||
docker stop --time 120 ranch-web-smoke
|
||||
test "$(docker inspect --format '{{.State.ExitCode}}' ranch-web-smoke)" = 0
|
||||
- name: Remove smoke container
|
||||
if: always()
|
||||
run: docker rm --force ranch-web-smoke 2>/dev/null || true
|
||||
- name: Log in to GHCR
|
||||
if: steps.version.outputs.publish == 'true'
|
||||
uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Publish only the exact stable 2.x tag
|
||||
if: steps.version.outputs.publish == 'true'
|
||||
env:
|
||||
PUBLISH_TAG: ${{ steps.version.outputs.tag }}
|
||||
run: |
|
||||
python -c "import os; from ranch_web.updates import stable_version; stable_version(os.environ['PUBLISH_TAG'])"
|
||||
docker tag ranch-web-smoke "ghcr.io/attilanet/myrzx_bot-web:$PUBLISH_TAG"
|
||||
docker push "ghcr.io/attilanet/myrzx_bot-web:$PUBLISH_TAG"
|
||||
@@ -48,6 +48,13 @@ logs/
|
||||
*.pyc
|
||||
*.pyo
|
||||
**/__pycache__/
|
||||
.venv-web/
|
||||
.impeccable/
|
||||
.image.env
|
||||
/updater-control/
|
||||
/backups/
|
||||
/failed-data/
|
||||
/.web-updater.lock
|
||||
/tools/ffdec/
|
||||
/flashlib/
|
||||
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
FROM python:3.12-slim-bookworm
|
||||
|
||||
ARG WEB_VERSION=2.0.0.dev1
|
||||
ARG VCS_REF=unknown
|
||||
LABEL org.opencontainers.image.source="https://github.com/attilanet/myrzx_bot" \
|
||||
org.opencontainers.image.title="myrzx_bot Web" \
|
||||
org.opencontainers.image.version="${WEB_VERSION}" \
|
||||
org.opencontainers.image.revision="${VCS_REF}"
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
WEB_CONCURRENCY=1 \
|
||||
RANCH_WEB_HOST=0.0.0.0 \
|
||||
RANCH_WEB_PORT=8765 \
|
||||
RANCH_WEB_DATA_DIR=/data \
|
||||
RANCH_WEB_UPDATER_DIR=/run/ranch-updater
|
||||
|
||||
WORKDIR /app
|
||||
COPY ranch_web/requirements.txt /tmp/web-requirements.txt
|
||||
RUN python -m pip install --no-cache-dir -r /tmp/web-requirements.txt \
|
||||
&& groupadd --gid 10001 ranch \
|
||||
&& useradd --uid 10001 --gid 10001 --no-create-home --shell /usr/sbin/nologin ranch \
|
||||
&& mkdir -p /data /run/ranch-updater \
|
||||
&& chown 10001:10001 /data
|
||||
|
||||
COPY ranch_assistant/ /app/ranch_assistant/
|
||||
COPY ranch_web/ /app/ranch_web/
|
||||
|
||||
USER 10001:10001
|
||||
EXPOSE 8765
|
||||
STOPSIGNAL SIGTERM
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD ["python", "-c", "import urllib.request; r=urllib.request.urlopen('http://127.0.0.1:8765/api/health', timeout=3); assert r.status == 200"]
|
||||
CMD ["python", "-m", "ranch_web", "--no-browser"]
|
||||
@@ -14,6 +14,18 @@
|
||||
也可以在项目目录运行 `python -m ranch_assistant` 启动。
|
||||
首次使用可先查看各页面数据、配置规则,再开启策略;重启、恢复会话或导入配置后,策略开关默认关闭。
|
||||
|
||||
## Web 2 开发运行与部署入口
|
||||
|
||||
`develop/v2.0.0` 提供 **2.0.0.dev1** 开发工作台,保留原15页导航、多账号页签、顶部玩家数值与统一启停、可调整日志区,复用现有 Engine 和策略。尚未合并 main 或发布正式版,桌面入口继续可用。
|
||||
|
||||
- Windows:Python 3.12+,安装 `ranch_web/requirements.txt` 后运行 `Start_Ranch_Web.cmd`,访问 `http://127.0.0.1:8765`。
|
||||
- Web 使用原生 HTML/CSS/ES 模块与 FastAPI,无需 Node/npm 或 PySide6;数据独立保存在 `local_state/ranch_web`。
|
||||
- Linux:提供单服务 Docker、`/data` 持久化及宿主机受控更新;只接官方稳定 `v2.x.y`,默认只通知,未配置执行器时仅检查。
|
||||
|
||||
本地虚拟环境、离线演示与环境配置见 [Web 开发运行说明](ranch_web/README.md);Linux 单服务 Docker、`/data` 持久化、GHCR 镜像与宿主机备份/回滚更新见 [Web 部署更新入口](deploy/web/README.md)。更新仅接受官方稳定 `v2.x.y`,没有 Web 2 正式版时不会安装旧桌面版;Windows 未配置执行器时仅检查更新。本轮不代表真实游戏 API 或 Linux Docker 实机验收通过。
|
||||
|
||||
最终离线后端验证 **185项:184通过、1跳过(Windows符号链接权限),0失败/错误**;浏览器 **13项通过,JS/CSP错误为0**,另以新 Edge 进程验证15页及主线/孵蛋子页。完整非浏览器测试命令见 [Web 验证说明](ranch_web/README.md#离线验证)。这些结果不代表真实游戏服务器或 Linux Docker 验收通过。
|
||||
|
||||
## 当前功能
|
||||
|
||||
| 模块 | 1.2.0 当前实现(战斗能力范围见下文) |
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
@echo off
|
||||
setlocal
|
||||
cd /d "%~dp0"
|
||||
if exist ".venv-web\Scripts\python.exe" (
|
||||
".venv-web\Scripts\python.exe" -B -m ranch_web %*
|
||||
) else (
|
||||
python -B -m ranch_web %*
|
||||
)
|
||||
if errorlevel 1 (
|
||||
echo.
|
||||
echo Web startup failed. Use Python 3.12+ and install ranch_web/requirements.txt.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
@@ -0,0 +1,245 @@
|
||||
# Web 2.0.0.dev1 协作契约
|
||||
|
||||
基线:`main` / `v1.2.0` / `7fe4c0f`。工作分支:`develop/v2.0.0`。
|
||||
不合并 main、不发布正式版本;本轮 API owner 不提交、不推送,验证后由 Main 按既有授权
|
||||
决定推送 `develop/v2.0.0` 供用户测试。保留桌面兼容;Web 导入链不得包含
|
||||
`PySide6`、`gui` 或 `*_gui`。现有功能按原页面 1:1 迁移,未知业务给出具体原因。
|
||||
Windows 本地验证后部署 Linux Docker;所有验证使用 temporary + fake / 离线演示,
|
||||
不测试真实游戏 API,不读取或修改私有 `local_state` 账户。
|
||||
|
||||
## 文件归属
|
||||
|
||||
| Owner | 文件 / 范围 |
|
||||
| --- | --- |
|
||||
| API | `ranch_web/__init__.py`、`__main__.py`、`app.py`、`config.py`、`requirements.txt`、`tests/__init__.py`、`tests/test_api.py`、`tests/test_auth.py`、本契约 |
|
||||
| Runtime | `service.py`、账户线程 / 调度 / 凭据 / 运行时测试 |
|
||||
| Views / actions | `policies.py`、`views.py`、`actions.py`、相关离线测试 |
|
||||
| Frontend | `static/` 原生 ES modules、HTML、CSS,无 npm 编译 |
|
||||
| Deploy | `updates.py`、Docker / host updater / Windows launcher、部署测试及文档 |
|
||||
| Main | 协调最终契约、代码审核、离线集成和浏览器实测 |
|
||||
|
||||
协作 agent IDs:runtime `01a1c454-a71b-7fb2-bffd-590ca032c00e`;views
|
||||
`01a1c454-a76c-7901-8d67-f05fb95cb172`;api `01a1c454-a7d5-71c2-96d8-ffcb2831d520`;
|
||||
frontend `01a1c454-a828-7f01-83f7-8a657ccc9211`;deploy
|
||||
`01a1c454-a872-7702-8ec3-01651883b0f2`。接口有变化立即同步相关 owner 和 Main,
|
||||
小 patch 协作,不覆盖其他 owner 文件。
|
||||
|
||||
## Python 接口
|
||||
|
||||
```python
|
||||
create_app(data_dir=None, manager=None, config=None, updates=None) # ranch_web.app
|
||||
|
||||
WebManager(root, *, start_scheduler=True, catalog=None,
|
||||
engine_factory=None, login_factory=None) # ranch_web.service
|
||||
manager.list_accounts() -> list[summary]
|
||||
manager.create_account(label="", demo=True) -> summary
|
||||
manager.remove_account(account_id)
|
||||
manager.status(account_id) -> summary
|
||||
manager.get_config(account_id) -> {"config": ..., "revision": ...}
|
||||
manager.set_config(account_id, config, revision=None) -> {"config": ..., "revision": ...}
|
||||
manager.view(account_id, page, query=None) -> {"data": ..., "loading": bool,
|
||||
"job_id": str | None, "revision": ...}
|
||||
manager.submit(account_id, operation, payload=None) -> job
|
||||
manager.job(account_id, job_id) -> job
|
||||
manager.logs(account_id, after=0, debug=False) -> {"entries": [...], "next": ...}
|
||||
manager.log_detail(account_id, entry_id) -> publicJSON # 单条懒加载脱敏网络详情
|
||||
manager.close()
|
||||
|
||||
default_config(), validate_config(config), apply_config(engine, config)
|
||||
export_config(config, snapshot=None), import_config(value, snapshot=None) # ranch_web.policies
|
||||
build_view(engine, page, config, query=None), schema(catalog) # ranch_web.views
|
||||
execute_action(worker, operation, payload) # ranch_web.actions
|
||||
|
||||
UpdateService(root, current_version) # ranch_web.updates;root 为 Web 数据根
|
||||
updates.status() -> publicJSON
|
||||
updates.check() -> publicJSON
|
||||
updates.request_update(version=None) -> publicJSON
|
||||
```
|
||||
|
||||
FastAPI 使用 lifespan;只 close 自己创建的 manager / updates,对注入对象不取得所有权。
|
||||
同步服务调用在线程池执行,游戏操作仅提交队列,HTTP 202 + job 轮询;GET 视图立即
|
||||
返回缓存,首访 `loading=true`,不得等待战斗。状态、日志、健康和 meta 不被长任务阻塞。
|
||||
单账号一个线程串行,多账号并行;停止立即取消未发请求和可取消等待。配置串行生效并
|
||||
自动保存;重启、恢复会话、导入配置均保持策略关闭。导入导出及批量资料处理也经 job。
|
||||
Runtime 已说明 `set_config` 忙时返回 `{config,revision,pending:true,job_id,job}`,其中
|
||||
config/revision 是当前已生效值;API 对此返回 202,frontend 必须轮询 job 后再读新 revision,
|
||||
不得当作已经应用。非 pending 的响应仍为 200。
|
||||
|
||||
账户 summary:
|
||||
```json
|
||||
{"id":"opaque-account-id","label":"账号1","connected":false,"demo":true,
|
||||
"running":false,"busy":false,"player":{"name":"","level":0,"exp":0,
|
||||
"next_exp":0,"money":0,"ke":0,"ti":0},"revision":0,"error":null}
|
||||
```
|
||||
|
||||
job:`{id,status,operation,result,error}`;status 只允许
|
||||
`queued/running/succeeded/failed/cancelled`,result 仅 publicJSON。外发禁止
|
||||
token、key、reqid、password、原始快照、服务器文件路径。错误使用中文,禁止堆栈。
|
||||
`has_saved_password` 是允许的布尔元数据;游戏会话展示仅使用不含秘密的 session 元数据。
|
||||
|
||||
## 页面与控件
|
||||
|
||||
页面 key 固定:`login,incubator,bag,ranch,daily,hatching,mainline,battles,gifts,
|
||||
commissions,exploration,maps,statistics,plans,yields`。
|
||||
保持菜单、账号 tabs、顶部玩家数值 / 随机刷新 / 绿开启红停止、底部可调隐藏日志。
|
||||
背包分类:蛋 / 可用 / 消耗 / 材料 / 其他 / 装备。牧场支持平铺与分组;主线默认当前主线;
|
||||
地图默认折叠,保留矿洞、难度、次数、工具库存;统计使用真实统计数据绘 SVG。
|
||||
|
||||
统一视图 DTO:
|
||||
```json
|
||||
{"page":"bag","title":"背包","columns":[{"key":"enabled","label":"启用",
|
||||
"type":"boolean","edit":{"path":["policy","egg_rules","100","enabled"],
|
||||
"type":"boolean"}}],"rows":[{"id":"100","enabled":true}],"summary":{},
|
||||
"filters":[],"form":[],"details":{}}
|
||||
```
|
||||
|
||||
`summary/filters/form/details` 按页可选。路径示例仅说明 shape,真实路径取 views schema。
|
||||
`schema(catalog)` 包含中文 label、类型、options、config path;渲染真实控件,所有控件
|
||||
经相同配置路径 PUT 并自动保存,不使用纯 JSON 编辑器替代原功能。具体样例由 views
|
||||
owner 同步 frontend,API 只传递已脱敏公共 DTO。
|
||||
|
||||
## REST
|
||||
|
||||
| 方法 | 路径 | 返回 |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/health` | `{status:"ok",version}`,无游戏副作用 |
|
||||
| GET | `/api/meta` | version、gameVersion、access、features、updates |
|
||||
| GET | `/api/schema` | `views.schema(catalog)` |
|
||||
| GET / POST | `/api/accounts` | GET 为 summary 数组;POST `{label?,demo?}`,201 summary |
|
||||
| DELETE | `/api/accounts/{id}` | 204 |
|
||||
| GET | `/api/accounts/{id}/status` | summary |
|
||||
| GET / PUT | `/api/accounts/{id}/config` | PUT `{config,revision?}`;返回 `{config,revision}` |
|
||||
| GET | `/api/accounts/{id}/views/{page}` | `{data,loading,job_id,revision}` |
|
||||
| POST | `/api/accounts/{id}/actions/{operation}` | payload 对象,202 job |
|
||||
| GET | `/api/accounts/{id}/jobs/{job_id}` | job |
|
||||
| GET | `/api/accounts/{id}/logs?after=0&debug=false` | `{entries,next}` |
|
||||
| GET | `/api/accounts/{id}/logs/{entry_id}` | 选中单条后取脱敏网络详情;不随普通日志轮询发送大 body |
|
||||
| GET | `/api/accounts/{id}/debug/{entry_id}` | 相同详情兼容路径,frontend 可用;manager.log_detail / debug_entry 等价 |
|
||||
| GET | `/api/accounts/{id}/config/export` | 提交 `export_config`,202 job |
|
||||
| POST | `/api/accounts/{id}/config/import` | 上传 portable document(兼容 `{config:document}`),API 包装为 action 的 `{config:document}`,202 job |
|
||||
| GET | `/api/system/updates` | updates.status(),不联网检查 |
|
||||
| POST | `/api/system/updates/check` | 在线程池 check(),仅检查 GitHub 正式版本 |
|
||||
| POST | `/api/system/updates/apply` | `{version?}`,202,提交受控更新请求 |
|
||||
| GET | `/api/auth/status` | `{required,authenticated,access_mode}` |
|
||||
| POST | `/api/auth/login` | `{password}`,设置 HttpOnly / SameSite=Strict cookie |
|
||||
| POST | `/api/auth/logout` | 撤销管理会话并清除 cookie |
|
||||
|
||||
视图 query:推荐 `?query=<JSON object>`;同时支持简单 query 参数;两种形式不可混用。
|
||||
不允许客户端指定任意磁盘文件路径;资料导入使用内存内容 / 已有业务 schema。
|
||||
API 默认 JSON body 上限 1 MiB;唯一例外是严格匹配账户 ID 的
|
||||
`POST /api/accounts/{id}/actions/import_yields`,其 JSON body 上限为 12 MiB,容纳 8 MiB
|
||||
文件的 base64 与 JSON 开销。声明长度与流式读取均执行相同上限;其他方法 / 路径仍使用
|
||||
默认 1 MiB(或显式配置的普通 body 上限)。action 按解码后字节数严格限制 8 MiB。
|
||||
账户与 job ID 为 1–80 位 ASCII 字母、数字、`_`、`-`。
|
||||
API 错误统一 `{error:{code,message},detail:message}`,不回显请求 body 或验证错误值。
|
||||
|
||||
手动 action allowlist:`refresh,refresh_maps,refresh_tasks,claim_daily,lock,unlock,sell,
|
||||
feed,quote_expansion,expand,export_config,import_config,import_yields,reset_map_pending`。
|
||||
`login,enter_server,restore_session,logout,forget_login,start,stop` 由 service 实现。
|
||||
如原业务迁移需要其他 action,先同步 API owner 加入 allowlist。
|
||||
|
||||
游戏 login payload:`{account,password,remember}`,result 含
|
||||
`servers:[{id,name,role_name}]` 和布尔 `has_saved_password`。
|
||||
`enter_server:{server_id}`;`restore_session:{session_id}`。凭据只在服务器内存或加密
|
||||
存储,严禁浏览器 localStorage、cookie 或 DTO 含游戏秘密。
|
||||
|
||||
## 认证、部署与更新边界
|
||||
|
||||
默认 `127.0.0.1:8765`,数据根 `local_state/ranch_web`,独立于桌面;Docker 显式 `/data`。
|
||||
CLI:`python -m ranch_web [--host ...] [--port ...] [--data-dir ...] [--demo] [--no-browser]`。
|
||||
默认启动不自动创建 demo;`--demo` 仅显式创建离线演示账号。
|
||||
Web 依赖仅 fastapi、uvicorn、requests、cryptography、openpyxl,不含 Qt。
|
||||
|
||||
非 loopback 绑定必须配置 `RANCH_WEB_PASSWORD` 或 `RANCH_WEB_PASSWORD_HASH`;
|
||||
loopback 无密码模式只允许 loopback 客户端。每个请求严格校验 Host;写 API 校验 Origin
|
||||
与 Sec-Fetch-Site,禁止 wildcard CORS、DNS rebinding 与跨站登录 / 账户操作。
|
||||
未带 Origin 的本机 CLI 可调用;携带 Origin 时必须同源或是明确配置的允许源。
|
||||
反代域名通过 `RANCH_WEB_ALLOWED_HOSTS` 指定,外部源通过 `RANCH_WEB_ALLOWED_ORIGINS`
|
||||
指定;不信任客户端 X-Forwarded-Host。HTTPS 反代设置 `RANCH_WEB_SECURE_COOKIE=1`。
|
||||
管理会话仅内存,随机 opaque token,12 小时 TTL;重启后失效。
|
||||
管理登录每个来源在 60 秒内最多保留 10 个失败 / 在途校验名额;锁内原子预留,PBKDF
|
||||
在锁外并行运行,成功仅撤销自身名额。来源记录最多 1024 条,不串行阻塞其他来源或已有会话。
|
||||
密码 hash 格式:`pbkdf2_sha256$600000$salt$base64_digest`,salt 为 UTF-8 文本。
|
||||
可用 `ranch_web.config.hash_password()` 生成;明文配置使用常量时间比较。
|
||||
|
||||
`updates.status()` 与 meta 不触发 GitHub 请求;check 显式 / 定时调用,不能访问游戏 API。
|
||||
apply 仅向部署 owner 管理的 host updater 提交规范 `v2.x.y` 稳定版本号请求(不接受前导零、
|
||||
开发版、其他主版本或裸版本号,与 UpdateService 一致);Web 容器不得持有
|
||||
Docker socket,不执行任意 git / shell。未配置部署器要明确解释,不能宣称更新成功。
|
||||
host 目录的具体协议由 deploy owner 维护,API 只调用 `request_update(version)`,frontend
|
||||
只读取公开状态,不直接使用目录路径;需与 deploy / frontend 同步具体 DTO。
|
||||
更新 DTO 与 `deploy/web/UPDATE_PROTOCOL.md` 完全同名:API 显式选择公开更新字段并保留
|
||||
经过协议校验的 `request={request_id,version,requested_at,status}` 和
|
||||
`host_status={request_id,status,version,updated_at,error}`。此例外仅适用于更新接口及
|
||||
meta.updates,不放宽普通游戏数据的 request / reqid / request_id / key / token 脱敏。
|
||||
|
||||
## API owner 集成记录
|
||||
|
||||
- 首次检查:仓库为 `7fe4c0f`,尚无 `ranch_web`;API 创建包初始化文件。
|
||||
- 当前 API owner 工具列表没有 `send_input` / agent 通信工具,已在会话告知;暂以本文件
|
||||
共享接口,在工具可用时立即直接同步相关 owner。
|
||||
- 按 Main 调试 1:1 要求,API 添加 `GET logs/{entry_id}` 对接
|
||||
`manager.log_detail(account_id, entry_id)`。正常轮询只发摘要,详情仅点击后加载;
|
||||
详情保留请求 / 响应 / body 结构并递归遮罩秘密,普通响应禁止原始快照。
|
||||
请 runtime / frontend 采用此方法名和路径;运行时未实现时 API 明确返回 501。
|
||||
- CLI / Docker / launcher 统一环境变量:`RANCH_WEB_HOST`、`RANCH_WEB_PORT`、
|
||||
`RANCH_WEB_DATA_DIR`;API 不使用 `RANCH_WEB_ROOT`。CLI 参数覆盖环境变量。
|
||||
- 可运行骨架及离线验证结果完成后追加在此,不改写其他 owner 文件。
|
||||
|
||||
## API owner 冻结交接(2026-11-10)
|
||||
|
||||
状态:分配范围实现完成,API owner freeze,未提交 / 推送。Main 可进行独立审核、浏览器
|
||||
实测及按既有授权安排 develop 测试分支。后续只响应集成缺陷修复,不扩展本轮范围。
|
||||
|
||||
交付文件:`ranch_web/{__init__,__main__,app,config}.py`、`requirements.txt`、
|
||||
`ranch_web/tests/{__init__,test_api,test_auth}.py`、本共享契约。其他 owner 的文件未修改。
|
||||
|
||||
已验证:Windows Python 3.13.15、FastAPI 0.162.2、uvicorn 0.54.0、httpx 0.28.1。
|
||||
|
||||
```text
|
||||
python -m unittest ranch_web.tests.test_api ranch_web.tests.test_auth -q
|
||||
Ran 40 tests ... OK
|
||||
python -m compileall -q ranch_web/app.py ranch_web/config.py ranch_web/__main__.py ranch_web/tests/test_api.py ranch_web/tests/test_auth.py
|
||||
git diff --check
|
||||
```
|
||||
|
||||
测试覆盖:生命周期仅释放自建对象 / 启动失败清理 / 全部对象清理尝试,HTTP 202 job、
|
||||
缓存视图、配置 revision / pending、portable 导入导出、中文错误 / 堆栈 / 路径脱敏,
|
||||
摘要与延迟调试详情,输入与路径 allowlist、body 大小 / 流式正文限制,Host / Origin / DNS
|
||||
rebinding,免密仅限本机,明文与 PBKDF2 密码,HttpOnly / SameSite Strict / Secure cookie,
|
||||
退出后的 cookie 重放、管理会话实例隔离、登录限流、后台检查不阻塞 event loop。
|
||||
测试均使用临时目录与 fake / demo,requests 网络 guard 实测调用次数为 0。
|
||||
|
||||
真实 WebManager + 原 Engine 的临时 demo 集成:15 个页面都成功返回 DTO(收益 749 行),
|
||||
columns / filters / schema.pages 的 key 保留;配置队列保存 interval、导出后以 portable
|
||||
文档重新导入成功,策略仍关闭。独立进程验证导入无 PySide6 / *_gui。
|
||||
CLI `--help`、`--data-dir --demo --no-browser` 生命周期验证通过,不打开浏览器。
|
||||
|
||||
Main 需知的接口细节:
|
||||
|
||||
- set_config pending 返回 202;轮询 job 后读取最新 config / revision。
|
||||
- 日志详情同时支持 `/logs/{entry_id}` 与 frontend 已使用的 `/debug/{entry_id}`;
|
||||
对接 manager.log_detail,兼容 manager.debug_entry,只有选中条目才加载 body。
|
||||
- `config/import` 接受 portable document 或 `{config:document}`;提交 action 时统一包装。
|
||||
- apply 版本号只接受部署模块的规范 `v2.x.y`;未配置部署器返回真实 unavailable 状态。
|
||||
- 环境变量统一 HOST / PORT / DATA_DIR;HTTPS 反代要显式设置允许的 Host、Origin 和
|
||||
`RANCH_WEB_SECURE_COOKIE=1`。CLI 不信任任意 forwarded header,关闭访问日志避免查询泄密。
|
||||
|
||||
验证边界:未调用真实游戏 API 或真实 GitHub 检查;未读取 / 修改桌面账户数据;
|
||||
Linux Python 3.12 / Docker、浏览器交互与生产 updater 由 Main / deploy 继续验证。
|
||||
本轮没有宣称线上业务成功、容器更新完成或正式发布。
|
||||
|
||||
Main 最终集成修复补记:仅修改 API owner 的 app.py、test_api.py、本契约。
|
||||
新增 4 项测试覆盖专用 12 MiB body 的 Content-Length 边界、真实多块 ASGI 流式边界、
|
||||
其他路由仍为 1 MiB,以及原 action 恰好 8 MiB CSV 成功 / 多 1 字节失败且保留原配置。
|
||||
真实 UpdateService + 临时 executor 心跳 / 固定 GitHub release 替身验证 check → pending →
|
||||
applying,HTTP 与 meta 的 request / request_id / version / status 均完整;游戏 DTO 仍
|
||||
过滤这些秘密键。DTO 未改名,frontend 无需适配。39 项 API / auth 测试通过后再次 freeze。
|
||||
|
||||
Independent review 2 修复补记:API 的 metadata 上下文补齐 tabs,仅保留这类控件的合法
|
||||
key;真实 manager 的隔离 demo API 回归断言主线 `status/policy` 两个 tab 与孵蛋策略
|
||||
三个 tab 的 key 完整,主线策略表单可用。登录限流改为锁内检查并预留、锁外 PBKDF,
|
||||
失败不再回写旧计数,成功仅释放自身预留。确定性事件门控测试验证 12 个并发错误请求
|
||||
恰好得到 10 个 401 + 2 个 429,随后仍限流;同时已有会话查询、另一来源正确登录均
|
||||
及时完成。以上两项均先复现再修复。40 项 API / auth 测试、编译、diff 检查通过,再次 freeze。
|
||||
本次仅修改 API owner 的 app.py、test_api.py、test_auth.py、本契约;未提交 / 推送。
|
||||
@@ -0,0 +1,104 @@
|
||||
# Web 2.0 页面/策略/操作契约与对照
|
||||
|
||||
Owner: views。状态:已freeze,26项focused tests通过,交Main审核。此文件是 frontend / API / runtime 的共享契约;当前会话无 send_input 工具,以共享文件和会话进度同步。
|
||||
|
||||
## 固定 Python 接口
|
||||
|
||||
- `default_config() -> dict`:桌面六组策略 + interval / overrides / yield_stars / log_visible / log_sizes;所有运行状态由 runtime 管理。
|
||||
- `validate_config(config) -> dict`:补默认值,严格校验每层字段和动态规则,不接受凭据或未知字段。
|
||||
- `apply_config(engine, config) -> dict`:原子验证后应用六组 core 策略和收益 overrides;不启动运行。
|
||||
- `export_config(config, snapshot=None) -> dict` / `import_config(value, snapshot=None) -> dict`:复用纯 Python `policy_io` 可移植 schema 1 / 2,按 species 重映射实例 ID。
|
||||
- `build_view(engine, page, config, query=None) -> dict`、`schema(catalog) -> dict`;纯读取 DTO 在账号 worker 队列执行;绝不 import GUI。
|
||||
- `execute_action(worker, operation, payload=None) -> publicJSON`:worker 要有 engine、config、profile_root;运行状态/持久化由 runtime 统一处理。
|
||||
|
||||
## DTO 与编辑协议(前端可立即接入)
|
||||
|
||||
所有页面:`{page,title,columns:[{key,label,type?,edit?:{path,type,options?}}],rows:[{id,...}],summary,filters,form,details,actions}`。
|
||||
`form` 为字段列表,字段至少 `{label,type,path,value}`,可带 `options:[{value,label,disabled?,reason?}]` / `min,max,step,group,help`。
|
||||
行中 `edits` 可覆盖该行列编辑定义;静态列 path 中 `"{id}"` 替换为行 ID。前端把 path 定位的值写回同一份 config,再 PUT;数组/字典由专用列表控件编辑。
|
||||
例如蛋规则列 `{"key":"keep_count","label":"牧场保留","type":"integer","edit":{"path":["policy","egg_rules","{id}","keep_count"],"type":"integer","min":0,"max":1000}}`,含义是最低保留数量。
|
||||
动态行规则不存在时 DTO 提供该行 `rule_defaults`;编辑第一格时先把 defaults 合并入对应规则,避免创建不完整规则。
|
||||
探索队员是完整三选控件:`type:"members"`,path `["explore_policy","teams","{id}","monsters"]`,value 为 `[]`(自动)或三个整数 ID;允许前端保留未完成草稿,仅三人齐全后 PUT。
|
||||
`filters` 是可用筛选控件列表,字段包含 `key,label,type,value,options`,query 同名;`search` 通用文本筛选。`details` 为按 row.id 索引的安全展示数据。
|
||||
牧场目标开关的 edit.type=`target`:勾选写整数优先级(default=100),取消删除对应路径,不能把布尔值写进 targets 字典;优先级列使用同一 config path。探索 `members` 提供三个人员选项,只提交完整3人数组或[]。`add_rule` 用选择器添加species规则,不是文本输入。`id_counts` 用逐项编号/数量控件。
|
||||
|
||||
支持 page keys:login / incubator / bag / ranch / daily / hatching / mainline / battles / gifts / commissions / exploration / maps / statistics / plans / yields。
|
||||
bag query.category:eggs / usable / consumables / materials / other / equipment。ranch query.grouped 默认 false,query.room_id 可选。mainline query.category 默认 mainline、query.state 默认 current。maps query.category all / ordinary / resource,query.only_unlocked 默认 true;地区 groups 默认 collapsed。
|
||||
statistics query:stage_id(兼容stage别名)、level(1/2/3)、source(all/sweep/event;event=奖励事件)、metric(rate/per_stamina;probability 为 rate 别名);chart.series[].value 的rate为0~1比例,frontend乘100绘制百分比;charts 是同一chart的列表形式。
|
||||
|
||||
## 手动操作 payload(POST actions/{operation})
|
||||
|
||||
| operation | payload | 结果/约束 |
|
||||
| --- | --- | --- |
|
||||
| refresh | `{page?:string}` | Engine.poll(自动关闭)或相应本地刷新;不自动执行计划 |
|
||||
| refresh_maps | `{}` | Engine.refresh_stages |
|
||||
| refresh_tasks | `{}` | Engine.refresh_progression |
|
||||
| claim_daily | `{}` | Engine.claim_daily;按 daily_policy.selected 领取 |
|
||||
| lock / unlock | `{monster_ids:[int]}` | Engine.set_monster_lock |
|
||||
| sell | `{monster_ids:[int],confirm:true}` | Engine.manage_monsters('sell',...);必须明确确认 |
|
||||
| feed | `{monster_ids:[int],target_id:int,confirm:true}` | Engine.manage_monsters('feed',...);复用原保护与等级验证 |
|
||||
| quote_expansion | `{kind:'stack'|'room',currency:'money'|'ke',position?:int}` | 返回 `{quote_id,kind,currency,position,cost,description}`;quote_id 只在该 worker 有效 |
|
||||
| expand | `{quote_id:string,confirm:true}` | 消费一次性服务器报价;Engine.expand 再核对当前费用与次数 |
|
||||
| export_config | `{}` | 可移植 dict,不含秘密 |
|
||||
| import_config | `{config:object}` | 返回 `{config}`;runtime 验证串行应用、保存并停止运行 |
|
||||
| import_yields | `{filename:string,content_base64:string}` | 只接受上传 CSV/XLSX 的内存内容,不接受客户端磁盘路径;经worker.save_config应用和保存后返回 `{overrides,count,message}` |
|
||||
| reset_map_pending | `{confirm:true}`(兼容server_verified但不信任) | 仅复用原sweeper.recover_reward_event核对账号/请求/关卡/难度及成功响应,缺证据保留pending;绝不清battle journal |
|
||||
|
||||
游戏登录、恢复、开启、停止仍归 runtime;此层不新增构造游戏请求的手动动作。自动赠礼、突破、探险、主线和刷图使用原 Engine 策略调度。
|
||||
|
||||
## 对照与验证
|
||||
|
||||
所有测试仅 temporary+fake 或显式离线 demo;不读取私有账号目录,不连接真实游戏 API,不修改 ranch_assistant core。
|
||||
|
||||
### 已确认的集成约定
|
||||
|
||||
- runtime / API:`build_view(...).tabs[].key` 与columns/filters/pages一样保留;两层已修复,主线和孵蛋子页经真实WebManager HTTP与浏览器复核。
|
||||
- frontend:`members` 三选控件保留未完成浏览器草稿,只提交[]或完整3个ID;自动按钮清空[]。
|
||||
- frontend:hatching.details.preset是原绿色史莱姆预设;应用patch并整体替换policy.egg_rules为preset.egg_rules后PUT,不开启运行。
|
||||
- frontend:statistics兼容stage/stage_id;level对象含id/level/value;chart.series[].value为比例(rate)或每体力数量,无样本为null/无series,不当作0%成功。
|
||||
- 所有合法旧battle_mode(original)先通过core校验再归一experimental,与当前desktop保持一致;未知值仍拒绝。
|
||||
- API:收益上传action支持8MiB原文件,仅`/api/accounts/{id}/actions/import_yields`路由使用12MiB JSON body上限,其他路由维持原限制;frontend发送filename+content_base64。
|
||||
|
||||
### 页面逐项对照
|
||||
|
||||
| Web page | 原GUI / 纯核心证据 | DTO / 真实操作 |
|
||||
| --- | --- | --- |
|
||||
| login | gui.connection_tab;运行时login_view | 仅登录页公共元数据骨架;密码/区服/恢复由runtime填充,不读取游戏凭据 |
|
||||
| incubator | gui.render;Snapshot.phase_text/remaining;management.expansion_quote | 11个坑位含未开/VIP、真实成长阶段/资质/剩余时间;选普通坑位money/ke报价,Engine.expand复核并检查新增记录 |
|
||||
| bag | egg_rules_gui.EggTable;inventory_gui.InventoryTable;Catalog.item_type | 蛋/可用/消耗/材料/其他/装备,同种库存聚合;蛋启用/优先级/去向/补货下限/目标/市场/牧场保留;允许无库存规则;礼物开关和保留数量按资格禁用装备及蛋 |
|
||||
| ranch | ranch_gui.RanchView;presentation.monster_rows | 平铺/分组/按牧场过滤、容量空位、详情;喂养/赠礼/突破目标开关和1~999优先级真绑定;手动锁/解锁/派遣/指定目标喂养;新建牧场报价 |
|
||||
| daily | activity_gui.daily_tab/render_daily;daily.entries | 每日礼包/七日/累计/VIP/邮件状态和奖励、选择列表;Engine.claim_daily按选项处理,ledger防重,刷新只预览 |
|
||||
| hatching | gui.automation_tab/policy_tab/read_policy/gold_preset | 孵蛋/牧场/喂养三个子策略;保留星级/资质/同种更好保护、收取牧场、保留物种/蛋、买蛋预算等现UI字段;原绿色史莱姆预设DTO,应用只保存配置 |
|
||||
| mainline | progression_gui.prepare_progression_views/render_progression/read_progression_policy | 默认当前主线,类别+生命周期+搜索,任务步骤/NPC/对话/位置/下一步/阻塞;完整现UI策略;旧original先验证再归一experimental,不暴露旧隐藏selector |
|
||||
| battles | progression_gui.prepare_progression_views | 战斗/扫荡/奖励事件分类、北京时间、中文胜败和阻塞、模式/伤害说明和奖励详情;不公开raw response或journal内部路径 |
|
||||
| gifts | gui.gifting_tab;GiftPlanner;CultivationSelector | 自动代表、喜欢物品开关、代表/目标名单、好感上限/资质/喜欢物品/冷却;执行继续走原Engine调度 |
|
||||
| commissions | gui.quests_tab/render_quests;TaskPlanner;progression_rows | 委托金币/氪金奖励、接取/进行中状态、原诊断覆盖原因;交付物品/1级魔物/金币上限/库存保留/战斗限制,按氪金优先 |
|
||||
| exploration | exploration_gui.prepare_exploration_rows/prepare_exploration_members;ExplorePlanner | 已有队伍/地区/解锁/费用/状态/倒计时;三队员选择含自动排除原因,手动仍允许战斗/培养目标;占用/等级等由原planner检查;领奖与再出发沿原策略 |
|
||||
| maps | activity_gui.render_maps/resource_cost_text;StageCache;Engine.map_stage_reason | 全部/普通/资源、只解锁、搜索、默认地区折叠;难度选择/勾选/日次数、普通扫荡/挑战诊断;矿洞/门票仅入口难度1,体力及每种工具单次/可用/保留成本 |
|
||||
| statistics | statistics_gui.render_detail;SweepStatistics.snapshot;drop_statistics.analyze | 原名称“数据分析”;all/sweep/event,关卡难度/次数/奖励,出现率/平均数量/每体力/95%区间/配置与实测;SVG series用真实统计,未知体力样本不算效率 |
|
||||
| plans | gui.render;Engine.plans | 原名称“执行计划”;仅公开动作kind/description和原planner等待原因,不暴露path/payload或自行执行 |
|
||||
| yields | gui.yield_tab/render_catalog;Catalog.import_prices | 原749种魔物,星级和搜索、培育时间/金币/经验/每小时/金币经验比;CSV/XLSX通过临时文件调用原导入器,完整验证后才保存overrides |
|
||||
|
||||
### 文件与检查记录
|
||||
|
||||
仅本owner文件:`ranch_web/policies.py`、`views.py`、`actions.py`、`tests/test_web_policies.py`、`tests/test_web_views_actions.py`、本报告。未修改ranch_assistant core、其他owner文件或私有local_state。
|
||||
|
||||
定向测试命令:
|
||||
|
||||
```powershell
|
||||
python -m unittest ranch_web.tests.test_web_policies ranch_web.tests.test_web_views_actions -v
|
||||
```
|
||||
|
||||
- 26项通过:8项策略验证/原子应用/跨账号重映射、18项页面/操作/原始Engine验证。
|
||||
- 所有15页在temporary demo中JSON序列化成功;非demo Engine +拒绝所有call的fake transport构建15页未触网;独立子进程阻断PySide6与GUI import通过。
|
||||
- 真实WebManager(temporary、start_scheduler=False)15页异步队列构建成功;quote_expansion→expand、lock/unlock、export/import、refresh_tasks job均succeeded;导入后running=False。
|
||||
- 扩建测试覆盖费用变化拒绝、一次性报价、错误/未知响应不能重复支付;派遣/喂养沿原保护;每日ledger防重。
|
||||
- 实际SweepStatistics记录合并验证all/event/sweep与未知体力样本排除;pending测试包含缺证据、错误账号、正确服务器响应、已有battle journal四种情况。
|
||||
- 没有运行真实游戏API验证,没有打开/更改私有账户;未commit/push。
|
||||
|
||||
### 已知边界与Main接手项
|
||||
|
||||
- 登录、安全、调度、缓存、前端控件及API请求体/脱敏接口已对齐并冻结。最终测试计数与验证边界以[Web验证说明](../ranch_web/README.md#离线验证)为准。
|
||||
- 未新增原业务未支持的委托孵蛋联动、未知战斗机制、花钱开探险队或召回;DTO保留核心具体原因。
|
||||
- pending不提供无证据强制清除;普通挑战/任务journal完全归Engine自动核对。
|
||||
- 源码核对与验证均为本地离线;未把demo或fake结果当成在线成功。
|
||||
@@ -0,0 +1,47 @@
|
||||
name: ranch-web
|
||||
services:
|
||||
web:
|
||||
image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:dev}
|
||||
build:
|
||||
context: .
|
||||
args:
|
||||
WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.0.dev1}
|
||||
user: "10001:10001"
|
||||
init: true
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 120s
|
||||
environment:
|
||||
RANCH_WEB_HOST: "0.0.0.0"
|
||||
RANCH_WEB_PORT: "8765"
|
||||
RANCH_WEB_DATA_DIR: /data
|
||||
RANCH_WEB_UPDATER_DIR: /run/ranch-updater
|
||||
RANCH_WEB_PASSWORD: ${RANCH_WEB_PASSWORD:?Set RANCH_WEB_PASSWORD in the private .env file}
|
||||
RANCH_WEB_ALLOWED_HOSTS: ${RANCH_WEB_ALLOWED_HOSTS:-localhost,127.0.0.1}
|
||||
RANCH_WEB_ALLOWED_ORIGINS: ${RANCH_WEB_ALLOWED_ORIGINS:-}
|
||||
RANCH_WEB_SECURE_COOKIE: ${RANCH_WEB_SECURE_COOKIE:-false}
|
||||
ports:
|
||||
- "${RANCH_WEB_BIND:-127.0.0.1}:${RANCH_WEB_PUBLISH_PORT:-8765}:8765"
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${RANCH_WEB_DATA_DIR:-./local_state/ranch_web}
|
||||
target: /data
|
||||
bind:
|
||||
create_host_path: false
|
||||
- type: bind
|
||||
source: ${RANCH_WEB_UPDATER_CONTROL_DIR:-./local_state/ranch_web_updater}
|
||||
target: /run/ranch-updater
|
||||
read_only: true
|
||||
bind:
|
||||
create_host_path: false
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:rw,noexec,nosuid,size=64m,mode=1777
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
@@ -0,0 +1,91 @@
|
||||
# Web 2 Linux Docker 部署与更新
|
||||
|
||||
本目录对应 `develop/v2.0.0`、`2.0.0.dev1`,当前仍是开发版本。以下正式镜像命令仅在官方发布对应稳定 `v2.x.y` 后可用;没有 Web 2 正式发布时,更新检查明确返回“暂无正式版”,不会安装旧桌面 1.2.0。开发分支不发布稳定镜像,不自动更新服务器。
|
||||
|
||||
## 容器与持久化
|
||||
|
||||
需要 Linux、Docker Engine、带 `up --wait --wait-timeout` 和 `pull --policy` 的 Docker Compose v2。宿主机更新器另需 Python 3.12+(仅标准库)。镜像使用 Python 3.12,无 PySide6、Node 或 npm,单服务、单 Uvicorn worker;账号由应用内独立线程并行。
|
||||
|
||||
将审核后的项目源码放在 `/opt/ranch-web`,项目、Python 源码、Compose 及部署配置由 root 持有,且禁止其他用户写入。以下路径适用于全新部署,持久化账号目录使用单独的 UID/GID 10001:
|
||||
|
||||
```sh
|
||||
cd /opt/ranch-web
|
||||
sudo install -d -m 0700 -o 10001 -g 10001 /opt/ranch-web/data
|
||||
sudo install -d -m 0755 -o root -g root /opt/ranch-web/updater-control
|
||||
sudo install -m 0600 -o root -g root deploy/web/web.env.example .env
|
||||
sudo install -m 0600 -o root -g root deploy/web/image.env.example .image.env
|
||||
sudoedit .env .image.env
|
||||
```
|
||||
|
||||
在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 填入已正式发布的完整镜像,例如 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.0`。Compose 默认只发布到宿主机 `127.0.0.1:8765`,容器内监听 `0.0.0.0:8765` 并强制管理密码。使用域名反代时,同时配置 `RANCH_WEB_ALLOWED_HOSTS` 与 `RANCH_WEB_ALLOWED_ORIGINS`;TLS 入口设置 `RANCH_WEB_SECURE_COOKIE=true`。代理保留正确的 Host,写请求依赖来源校验。
|
||||
|
||||
`/opt/ranch-web/data` 挂到容器 `/data`,包括账号、加密会话与密钥、配置、SQLite 统计和更新请求;独立于桌面数据。心跳控制目录独立只读挂到 `/run/ranch-updater`。使用 bind mount 的目录必须预先创建,Compose 不会悄悄创建 root 所有、容器无法写入的目录。默认容器用户 `10001:10001`,根文件系统只读,临时文件写到 `/tmp`。不要对现有账号目录重新初始化密钥。
|
||||
|
||||
正式版本启动:
|
||||
|
||||
```sh
|
||||
sudo sh deploy/web/compose.sh pull --policy always web
|
||||
sudo sh deploy/web/compose.sh up -d --no-build --wait --wait-timeout 180 web
|
||||
sudo sh deploy/web/compose.sh ps
|
||||
curl --fail http://127.0.0.1:8765/api/health
|
||||
```
|
||||
|
||||
脚本固定读取 `.env` 与 `.image.env`,相当于 `docker compose --project-name ranch-web --env-file .env --env-file .image.env --file compose.yaml ...`。更新器会持久化已选镜像到 `.image.env`,之后也应通过此脚本启动,以免误用默认开发镜像。
|
||||
|
||||
GitHub 首次创建 GHCR 包可能为私有;仓库管理员可将 `myrzx_bot-web` 包设为 Public。私有包部署需操作者先在宿主机执行 `sudo docker login ghcr.io`,使用具备 `read:packages` 的凭据;不要把 registry 凭据交给 Web 容器。[GHCR 官方文档](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)
|
||||
|
||||
若目前只在 Linux 上验证开发分支,将 `.image.env` 保持 `:dev`,本地构建后启动;这不会发布镜像:
|
||||
|
||||
```sh
|
||||
sudo sh deploy/web/compose.sh build web
|
||||
sudo sh deploy/web/compose.sh up -d --no-build --pull never --wait --wait-timeout 180 web
|
||||
```
|
||||
|
||||
停止使用 `sudo sh deploy/web/compose.sh stop --timeout 120 web`。容器 SIGTERM 经应用 lifespan 关闭账号队列;Compose 给出 120 秒退出时间。保持单实例,不要用多个 worker、replica 或 `--scale web=...` 共享同一 `/data`。
|
||||
|
||||
## 手动检查与更新
|
||||
|
||||
Web 只读检查官方 GitHub Releases;默认只接受 `v2.MINOR.PATCH`,跳过草稿、预发布、1.x、3.x 和非法标签。数字不含前导零。`2.0.0.dev1 → v2.0.0` 可升级,`2.0.0 → v2.0.0` 不升级,拒绝降级。网络失败会明确显示检查失败,不使用虚构版本或下载脚本。
|
||||
|
||||
先安装 root 持有的配置(示例的所有自动化开关默认关闭):
|
||||
|
||||
```sh
|
||||
sudo install -m 0600 -o root -g root deploy/web/updater.example.toml /etc/ranch-web-updater.toml
|
||||
sudo python3 -B deploy/web/updater.py --config /etc/ranch-web-updater.toml --check
|
||||
sudo python3 -B deploy/web/updater.py --config /etc/ranch-web-updater.toml --apply v2.0.0
|
||||
```
|
||||
|
||||
`--apply` 不传版本时选比运行中版本更新的最新稳定 2.x。手动操作和定时任务共享排他锁。执行器固定官方仓库及镜像地址,重新查询 Releases 验证来源;Web 即使伪造 `update-request.json` 也不能指定命令、下载地址、路径或第三方镜像。
|
||||
|
||||
执行顺序:旧容器运行期间先 `compose pull --policy always web`;拉取失败则保持旧服务。然后停服,确认所有容器写入停止,为完整数据目录创建一致的快照(包含 SQLite 文件及 WAL、加密密钥);最后用新镜像 `compose up -d --no-build --pull never --wait --wait-timeout 180 web`。镜像已有 `/api/health` healthcheck,检查成功后才记录更新完成。
|
||||
|
||||
新服务健康失败时,更新器停止失败容器、恢复更新前数据、用旧镜像的准确本地 image ID 启动并检查健康。失败版本数据移入 `failed-data/`,快照保存在 `backups/`,均不自动删除。快照文件权限为 0600、备份目录 0700;不会打印账号数据、密钥、Compose 环境或容器日志。回滚也失败时保留恢复事务,下一次更新器运行会先恢复,需操作者检查服务状态。镜像拉取和停机发生在宿主机;Web 容器没有 Docker socket。
|
||||
|
||||
## 定时检查、Web 按钮与自动更新
|
||||
|
||||
```sh
|
||||
sudo install -m 0644 deploy/web/ranch-web-updater.service /etc/systemd/system/
|
||||
sudo install -m 0644 deploy/web/ranch-web-updater.timer /etc/systemd/system/
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now ranch-web-updater.timer
|
||||
sudo systemctl start ranch-web-updater.service
|
||||
```
|
||||
|
||||
定时器每五分钟维护一次心跳;官方版本默认每小时检查一次。`auto_apply=false` 只显示可用更新,不主动更新。页面更新按钮还需操作者在 `/etc/ranch-web-updater.toml` 设置 `accept_web_requests=true`,再启动一次 service 刷新心跳;只有此时 Web 的 `can_apply` 才为 true。Web 点击后返回 `pending`,定时器独立验证并消费请求;这属于用户手动请求,不依赖 `auto_apply`。
|
||||
|
||||
若希望检测到新稳定版便自动安装,操作者显式设置 `auto_apply=true`;这可能在下次运行时开始升级。停用 Web 按钮或自动更新后,同样启动一次 service 刷新状态。停止 timer 后,15 分钟有效期到期的心跳会让 Web 显示执行器失效。可以用 `systemctl status ranch-web-updater.timer` 与 `journalctl -u ranch-web-updater.service` 查看脱敏状态。
|
||||
|
||||
Windows 或未安装执行器的 Docker 部署仍能检查版本,但按钮会显示“仅可检查更新”,不会伪装更新完成。公共 DTO、心跳、去重与请求字段见 [UPDATE_PROTOCOL.md](UPDATE_PROTOCOL.md)。
|
||||
|
||||
## CI 与验证范围
|
||||
|
||||
[web-image.yml](../../.github/workflows/web-image.yml) 仅对官方仓库的严格稳定 `v2.x.y` tag 推送 `ghcr.io/attilanet/myrzx_bot-web:v2.x.y`;校验 `ranch_web.__version__` 必须与 tag 一致,不能只改变镜像 label。PR 与手动运行只测试、构建,不推送。开发分支 push 不触发正式镜像发布,也没有 `latest` 滚动升级通道。CI 规划在无外网容器中检查 healthcheck、非 root 数据写权限、无 Qt 和正常停止;本轮没有触发 CI 或发布。
|
||||
|
||||
本机 Windows 没有 Docker,已能执行的验证是离线单元测试、临时数据的备份/回滚测试、启动脚本语法与配置静态核对、更新器 dry-run;不代表 Linux/Docker 实机验证通过。可在无 Docker 的机器上只打印计划(不联网、不写文件):
|
||||
|
||||
```sh
|
||||
python -B deploy/web/updater.py --config deploy/web/updater.example.toml --apply v2.0.0 --dry-run
|
||||
python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater -v
|
||||
```
|
||||
|
||||
命令参数依据 [Compose up](https://docs.docker.com/reference/cli/docker/compose/up/)、[Compose pull](https://docs.docker.com/reference/cli/docker/compose/pull/);发布权限与 GHCR 认证依据 [GitHub 镜像发布流程](https://docs.github.com/en/actions/tutorials/publish-packages/publish-docker-images)。检查使用 [GitHub Releases 列表 API](https://docs.github.com/en/rest/releases/releases#list-releases),不依赖可能指向桌面版的 `/latest`。
|
||||
@@ -0,0 +1,45 @@
|
||||
# Web 2 更新接口(协议 1)
|
||||
|
||||
供 API、前端、宿主机更新器与 Main 集成。`ranch_web.updates.UpdateService(root, current_version)` 只依赖 Python 标准库;构造和 `status()` 不联网,`check()` 才访问固定官方 GitHub Releases,`request_update(version=None)` 仅提交文件请求。API 可在线程池中调用检查,不能在事件循环里等待网络。
|
||||
|
||||
- 固定仓库:`attilanet/myrzx_bot`;固定镜像:`ghcr.io/attilanet/myrzx_bot-web`。
|
||||
- 唯一可选发布 tag:`v2.MINOR.PATCH`(十进制、不许前导零、无任何后缀)。草稿、预发布、1.x、3.x、dev 分支全部跳过;按版本数值比较,不信任 GitHub latest 排序。
|
||||
- `root` 为 Web 数据根(Docker `/data`),文件为 `update-check.json`、`update-request.json`、`updater-status.json`。账号数据与这些控制文件隔离。
|
||||
- `RANCH_WEB_UPDATER_DIR` 指向宿主机心跳目录,Docker 固定 `/run/ranch-updater`,只读挂载,与 `/data` 分离。没有有效 `capability.json` 时 `can_apply=false`,仅检查可用;Windows 默认如此。
|
||||
- 心跳由宿主机定时任务写入,含 `protocol=1, executor_id, enabled, auto_apply, heartbeat_at, expires_at`。执行器配置默认 `accept_web_requests=false, auto_apply=false`,操作者必须显式启用 Web 请求。心跳有效期 15 分钟、timer 每 5 分钟运行。
|
||||
- `update-request.json` 仅含 `protocol=1, request_id`(32 位小写十六进制)、`executor_id`、`version`(官方 tag)、`requested_at`(UTC ISO 8601)。禁止镜像地址、命令、下载地址或路径。宿主机再次联网验证 tag、版本单调递增并去重;Web 写文件不等于部署成功。
|
||||
|
||||
三个方法返回同一公共 DTO,示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"current_version": "2.0.0.dev1",
|
||||
"latest_version": "v2.0.0",
|
||||
"available": true,
|
||||
"checked_at": "2026-11-10T00:00:00Z",
|
||||
"release_url": "https://github.com/attilanet/myrzx_bot/releases/tag/v2.0.0",
|
||||
"channel": "stable-2.x",
|
||||
"repository": "attilanet/myrzx_bot",
|
||||
"status": "available",
|
||||
"message": "发现稳定 Web 2 更新。",
|
||||
"error": null,
|
||||
"can_apply": false,
|
||||
"executor": {
|
||||
"configured": false,
|
||||
"enabled": false,
|
||||
"auto_apply": false,
|
||||
"state": "unconfigured",
|
||||
"heartbeat_at": null
|
||||
},
|
||||
"request": null,
|
||||
"host_status": null
|
||||
}
|
||||
```
|
||||
|
||||
`status`:`unchecked / no_release / up_to_date / available / check_failed / unavailable / pending / applying / succeeded / rolled_back / failed`。无 2.x 正式版时 `latest_version=null, available=false, status=no_release`,不可退到桌面 1.2。
|
||||
|
||||
提交成功返回 `status=pending`,`request={request_id,version,requested_at,status:"pending"}`;前端应显示“等待宿主机”,定时 GET 状态。宿主机结果 `host_status={request_id,status,version,updated_at,error}`,错误是固定脱敏说明,不含原始异常、文件路径或子进程输出。`request_update` 在缺少执行器时返回 `status=unavailable` 和具体 `message`;非法/非官方/倒退版本抛 `ValueError`,API 映射 400。API `/apply` 的 HTTP 接受响应不应宣称已经升级;更新完成由宿主机健康检查决定。
|
||||
|
||||
启动约定(对齐 API owner 已落地的 config.py):`python -m ranch_web`,读取 `RANCH_WEB_HOST`(默认 `127.0.0.1`)、`RANCH_WEB_PORT`(默认 `8765`)、`RANCH_WEB_DATA_DIR`(默认 `local_state/ranch_web`)、`RANCH_WEB_PASSWORD`。Docker 设置 `HOST=0.0.0.0, DATA_DIR=/data`,只运行一个 Uvicorn worker,正常 SIGTERM 经 lifespan 关闭 manager。
|
||||
|
||||
API 已在更新 DTO 专用上下文按以上限定字段保留公共 `request`、`request_id`;全局游戏凭据脱敏保持有效。按钮传 `latest_version` 的完整 `v2.x.y`,无 `v` 的版本不会作为镜像标签接受。
|
||||
@@ -0,0 +1,53 @@
|
||||
# Deploy owner 交接与冻结记录
|
||||
|
||||
分支 `develop/v2.0.0`,基线 `main v1.2.0 (7fe4c0f)`,Web 源码版本 `2.0.0.dev1`。本 owner 完成部署与更新范围,未 commit、push、合并、发布镜像或触发线上部署;未读取或修改桌面私有账户,未调用真实游戏 API 或真实 GitHub Releases。
|
||||
|
||||
## 文件
|
||||
|
||||
- 根目录:`Dockerfile`、`compose.yaml`、`.dockerignore`、`Start_Ranch_Web.cmd`、`start-web.sh`;`.gitignore` 仅追加 Web 虚拟环境、设计缓存与部署运行产物排除;根 `README.md` 仅增加 Web 开发/部署入口。
|
||||
- `ranch_web/updates.py`:标准库发布检查、严格稳定 2.x 比较、只读宿主机心跳授权、原子 pending 请求与脱敏公共状态;包含 CI 的固定仓库/源码版本发布校验函数。
|
||||
- `ranch_web/tests/test_updates.py` 与 `test_web_updater.py`:本 owner 独立测试文件。
|
||||
- `ranch_web/README.md`:Windows/Linux Python 开发启动、数据隔离、环境设置与更新限制。
|
||||
- `.github/workflows/web-image.yml`:PR/手动只测试与构建,官方严格 `v2.x.y` tag 且源码版本完全一致时才推固定 GHCR 镜像。仓库名称比较忽略大小写,覆盖 `AttilaNet/myrzx_bot`。
|
||||
- `deploy/web/`:更新器、Compose 包装脚本、systemd service/timer、环境及 TOML 示例、部署文档与 [精确更新协议](UPDATE_PROTOCOL.md)。
|
||||
|
||||
## 已执行验证(部署专项)
|
||||
|
||||
Windows Python **3.13.15**:
|
||||
|
||||
```console
|
||||
python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater -q
|
||||
```
|
||||
|
||||
**41 项通过,无跳过。** GitHub 和 Docker 为 mock,数据全部在独立 `TemporaryDirectory`。覆盖:
|
||||
|
||||
- 仅稳定 `v2.x.y`,过滤 1.x、3.x、草稿、预发布、前导零、命令/换行注入;数字版本排序;`2.0.0.dev1 → v2.0.0` 可升级,同版正式版本/降级拒绝。
|
||||
- 未配置、过期、禁用、错误实例、未来时间的能力证明;Web 数据目录不能自行开启执行器;pending 去重;公共错误不泄露原始异常或私有数据。
|
||||
- 宿主机独立从 fake 官方 Releases 复验,不信 Web 标签;operator opt-in;过期/额外命令字段/跨实例请求拒绝;自动安装默认关闭。
|
||||
- 旧服务运行时 pull、停服后才快照;拉取失败不停止;备份失败恢复旧镜像;健康失败恢复 SQLite、密钥和准确旧镜像,保留失败版本数据;回滚失败保存事务,恢复可重试。
|
||||
- 实际 `WebManager` 在全网络 connect 禁止条件下,以内置离线 demo 开启策略,然后关闭、快照、重启及还原:保留勾选偏好与相同加密密钥,但 `running=false`,不会自动恢复执行。
|
||||
- 正式镜像 label 仍是 dev 或健康失败时不能宣告更新成功;官方仓库名称大小写、fork 拒绝、源码版本/tag 不一致拒绝。
|
||||
- `--dry-run` 对 Windows 与随附 Linux 路径示例均有效,不联网、不执行 Docker、不创建文件。
|
||||
|
||||
另外已执行:
|
||||
|
||||
- `Start_Ranch_Web.cmd --version` 返回 `2.0.0.dev1`。
|
||||
- 实际 Windows `python -m ranch_web --demo --no-browser` HTTP 启动烟测:临时数据、动态本地端口;导入钩子禁止 PySide6/桌面 GUI,禁止外部 DNS/connect;健康、离线账号与更新禁用状态正常,触发 SIGINT 后正常 lifespan 退出,exit 0。该测试不含页面浏览器验收。
|
||||
- `start-web.sh` 与 `deploy/web/compose.sh` 通过 Git Bash `bash -n`;两个 YAML 解析通过;静态核对单服务、UID/GID 10001、`/data`、独立只读心跳挂载、无 Docker socket、120 秒停止宽限;`git diff --check` 通过。
|
||||
- 官方 Docker/GitHub 文档已核对并在 [部署说明](README.md) 链接。必要的 `ranch_assistant/data/progression_battles.zip` 在 `.dockerignore` 中显式保留。
|
||||
|
||||
## Main/API/前端集成注意与未执行范围
|
||||
|
||||
1. 所有文档、容器与当前 API config 统一 `RANCH_WEB_DATA_DIR`、`RANCH_WEB_HOST`、`RANCH_WEB_PORT`;Docker `WEB_CONCURRENCY=1`,CLI 不打开浏览器。
|
||||
2. API 已使用更新 DTO 专用序列化保留合法 `request` / `request_id`,游戏凭据脱敏保持有效;HTTP 与 meta 的 pending/applying 信息已对接。前端从 `latest_version` 原样传完整 `v2.x.y`。
|
||||
3. `request_update()` 在无执行器时返回 `unavailable`,成功提交仅是 `pending`;不能把 HTTP 202 文案写成“已更新”。心跳目录只读,协议 1,timer 每五分钟;`accept_web_requests=false` 与 `auto_apply=false` 均为默认值。
|
||||
4. 本机无 Docker 可执行程序;**没有**验证 Linux/Docker 构建、Compose 真实解析/拉取、UID bind mount 实机权限、systemd 或真实健康回滚,也未执行 CI。静态配置与 mock 测试不能替代上述实机验收。CI 已编写隔离网络的容器健康/权限/停止检查,等待父代理审核后在授权发布流程执行。
|
||||
5. GHCR 首次包为私有的处理已记录:公共发布需设包 Public;私有部署由操作者 `docker login`,Web 无 registry 凭据或 Docker socket。更新器 systemd 允许只读访问 root 的 registry 登录配置。
|
||||
|
||||
## 最终集成与复核
|
||||
|
||||
Main 确认最终非浏览器后端 **185项:184通过、1跳过(Windows符号链接权限),0失败/错误,用时26.878秒**;执行前后69份源文件哈希一致,无外发尝试。浏览器 **13项通过,JS/CSP错误为0**,另以新 Edge 进程验证15页与主线/孵蛋子页。上述部署专项41项、定向复核与全量测试有重叠,不相加。
|
||||
|
||||
本 owner 对此前五项问题复核完成:编码后与 requests 发送前的停止检查有效;修改配置不误关运行开关;120个筛选后视图缓存32项、已完成任务索引归零;主线/孵蛋标签 key 完整;12个并发错误登录得到10个401和2个429。六项定向回归与原始复现均通过,未扩大审查或重跑整套测试。
|
||||
|
||||
完整后端及浏览器命令见 [Web 验证说明](../../ranch_web/README.md#离线验证)。未进行真实游戏 API、Linux Docker、systemd 或生产更新器实机验收,未发布镜像或触发部署。生产代码保持冻结,仅更新最终文档,交 Main 提交。
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd -- "$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)"
|
||||
exec docker compose --project-name ranch-web --env-file .env --env-file .image.env --file compose.yaml "$@"
|
||||
@@ -0,0 +1,2 @@
|
||||
# Development builds are local only. Set a real published v2.x.y for production.
|
||||
RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:dev
|
||||
@@ -0,0 +1,25 @@
|
||||
[Unit]
|
||||
Description=Check or apply official stable Ranch Web 2 updates
|
||||
Requires=docker.service
|
||||
After=docker.service network-online.target
|
||||
Wants=network-online.target
|
||||
ConditionPathExists=/etc/ranch-web-updater.toml
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=root
|
||||
Group=root
|
||||
WorkingDirectory=/opt/ranch-web
|
||||
ExecStart=/usr/bin/python3 -B /opt/ranch-web/deploy/web/updater.py --config /etc/ranch-web-updater.toml --run
|
||||
TimeoutStartSec=30min
|
||||
TimeoutStopSec=180s
|
||||
UMask=0077
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
# Allow read-only access to root's registry credentials for private GHCR pulls.
|
||||
ProtectHome=read-only
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=/opt/ranch-web
|
||||
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
@@ -0,0 +1,12 @@
|
||||
[Unit]
|
||||
Description=Ranch Web updater heartbeat and scheduled release checks
|
||||
|
||||
[Timer]
|
||||
OnBootSec=2min
|
||||
OnUnitInactiveSec=5min
|
||||
AccuracySec=15s
|
||||
Persistent=true
|
||||
Unit=ranch-web-updater.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,12 @@
|
||||
# Root-owned operator configuration. Never put this file in /data.
|
||||
project_dir = "/opt/ranch-web"
|
||||
data_dir = "/opt/ranch-web/data"
|
||||
control_dir = "/opt/ranch-web/updater-control"
|
||||
backup_dir = "/opt/ranch-web/backups"
|
||||
failed_data_dir = "/opt/ranch-web/failed-data"
|
||||
compose_project = "ranch-web"
|
||||
accept_web_requests = false
|
||||
auto_apply = false
|
||||
check_interval_seconds = 3600
|
||||
wait_timeout_seconds = 180
|
||||
shutdown_timeout_seconds = 120
|
||||
@@ -0,0 +1,491 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Root-owned Linux host updater; no shell, Docker socket, or code in Web.
|
||||
|
||||
Use --check for notification, --apply [v2.x.y] for an operator update, or
|
||||
--run from the timer. --dry-run never contacts GitHub or Docker or writes files.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, fields
|
||||
from datetime import timedelta
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import tomllib
|
||||
import uuid
|
||||
|
||||
# This import is standard-library-only; no FastAPI/Qt installation on the host.
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
from ranch_web import updates # noqa: E402
|
||||
|
||||
_DIGEST = re.compile(r"sha256:[0-9a-f]{64}", re.ASCII)
|
||||
_CONTAINER = re.compile(r"[0-9a-f]{12,64}", re.ASCII)
|
||||
_CONTROL_FILES = {"update-check.json", "update-request.json", "updater-status.json"}
|
||||
|
||||
|
||||
class UpdaterError(RuntimeError):
|
||||
"""Only a fixed public error is printed by the CLI."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Config:
|
||||
project_dir: Path = Path("/opt/ranch-web")
|
||||
data_dir: Path = Path("/opt/ranch-web/data")
|
||||
control_dir: Path = Path("/opt/ranch-web/updater-control")
|
||||
backup_dir: Path = Path("/opt/ranch-web/backups")
|
||||
failed_data_dir: Path = Path("/opt/ranch-web/failed-data")
|
||||
compose_project: str = "ranch-web"
|
||||
accept_web_requests: bool = False
|
||||
auto_apply: bool = False
|
||||
check_interval_seconds: int = 3600
|
||||
wait_timeout_seconds: int = 180
|
||||
shutdown_timeout_seconds: int = 120
|
||||
|
||||
@classmethod
|
||||
def load(cls, path, *, dry_run=False):
|
||||
with open(path, "rb") as stream:
|
||||
value = tomllib.load(stream)
|
||||
if set(value) - {field.name for field in fields(cls)}:
|
||||
raise UpdaterError("执行器配置包含未知字段。")
|
||||
for key in ("project_dir", "data_dir", "control_dir", "backup_dir", "failed_data_dir"):
|
||||
if key in value:
|
||||
item = Path(value[key])
|
||||
if not item.is_absolute() and not (dry_run and PurePosixPath(value[key]).is_absolute()):
|
||||
raise UpdaterError("执行器目录必须为绝对路径。")
|
||||
value[key] = item.resolve()
|
||||
result = cls(**value)
|
||||
if not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,62}", result.compose_project):
|
||||
raise UpdaterError("Compose 项目名称无效。")
|
||||
if type(result.accept_web_requests) is not bool or type(result.auto_apply) is not bool:
|
||||
raise UpdaterError("执行器开关必须为布尔值。")
|
||||
for key, lower, upper in (("check_interval_seconds", 300, 604800),
|
||||
("wait_timeout_seconds", 30, 600),
|
||||
("shutdown_timeout_seconds", 30, 600)):
|
||||
if type(getattr(result, key)) is not int or not lower <= getattr(result, key) <= upper:
|
||||
raise UpdaterError("执行器时间配置超出允许范围。")
|
||||
directories = [result.data_dir, result.control_dir, result.backup_dir, result.failed_data_dir]
|
||||
for index, directory in enumerate(directories):
|
||||
if directory == result.project_dir or directory in result.project_dir.parents:
|
||||
raise UpdaterError("数据与控制目录不能覆盖项目目录。")
|
||||
for other in directories[index + 1:]:
|
||||
if directory == other or directory in other.parents or other in directory.parents:
|
||||
raise UpdaterError("数据、控制、备份及失败数据目录必须相互独立。")
|
||||
return result
|
||||
|
||||
|
||||
class Docker:
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
|
||||
def run(self, arguments, *, image=None, timeout=120):
|
||||
environment = {key: value for key, value in os.environ.items()
|
||||
if not key.startswith("COMPOSE_") and key not in {
|
||||
"DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH",
|
||||
}}
|
||||
if image:
|
||||
environment["RANCH_WEB_IMAGE"] = image
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
["docker", "--context", "default", *arguments], cwd=self.config.project_dir,
|
||||
env=environment, stdin=subprocess.DEVNULL, capture_output=True,
|
||||
text=True, timeout=timeout, check=False,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
raise UpdaterError("Docker 命令不可用或超时。") from None
|
||||
if completed.returncode:
|
||||
# Never print compose config, environment, or container logs.
|
||||
raise UpdaterError("Docker 操作失败;请在宿主机检查服务状态。")
|
||||
return completed.stdout.strip()
|
||||
|
||||
def compose(self, arguments, *, image=None, timeout=120):
|
||||
cfg = self.config
|
||||
return self.run([
|
||||
"compose", "--project-name", cfg.compose_project,
|
||||
"--project-directory", str(cfg.project_dir),
|
||||
"--env-file", str(cfg.project_dir / ".env"),
|
||||
"--env-file", str(cfg.project_dir / ".image.env"),
|
||||
"--file", str(cfg.project_dir / "compose.yaml"), *arguments,
|
||||
], image=image, timeout=timeout)
|
||||
|
||||
def inspect_service(self, *, allow_missing=False):
|
||||
identity = self.compose(["ps", "--all", "--quiet", "web"])
|
||||
if not identity and allow_missing:
|
||||
return None
|
||||
if not _CONTAINER.fullmatch(identity):
|
||||
raise UpdaterError("必须先部署且只运行一个 web 容器。")
|
||||
try:
|
||||
values = json.loads(self.run(["container", "inspect", identity]))
|
||||
container = values[0] if len(values) == 1 else None
|
||||
image = container["Image"]
|
||||
version = container["Config"]["Labels"]["org.opencontainers.image.version"]
|
||||
updates.current_version_key(version)
|
||||
except (KeyError, ValueError, TypeError, IndexError):
|
||||
raise UpdaterError("现有容器缺少有效的 Web 2 版本标记。") from None
|
||||
if not _DIGEST.fullmatch(image):
|
||||
raise UpdaterError("无法固定旧镜像用于回滚。")
|
||||
mounts = {mount["Destination"]: mount for mount in container.get("Mounts", [])}
|
||||
if Path(mounts.get("/data", {}).get("Source", "")).resolve() != self.config.data_dir:
|
||||
raise UpdaterError("现有容器的数据挂载与更新器配置不一致。")
|
||||
capability = mounts.get("/run/ranch-updater", {})
|
||||
if Path(capability.get("Source", "")).resolve() != self.config.control_dir or capability.get("RW") is not False:
|
||||
raise UpdaterError("执行器心跳必须使用独立的只读挂载。")
|
||||
return {"image": image, "version": version, "running": container["State"]["Running"],
|
||||
"health": container["State"].get("Health", {}).get("Status")}
|
||||
|
||||
def validate(self, image):
|
||||
try:
|
||||
config = json.loads(self.compose(["config", "--format", "json"], image=image))
|
||||
services = config["services"]
|
||||
service = services["web"]
|
||||
volumes = {mount["target"]: mount for mount in service["volumes"]}
|
||||
valid = (set(services) == {"web"} and service["image"] == image
|
||||
and service.get("user") == "10001:10001" and not service.get("privileged")
|
||||
and set(volumes) == {"/data", "/run/ranch-updater"}
|
||||
and volumes["/data"].get("type") == "bind"
|
||||
and Path(volumes["/data"]["source"]).resolve() == self.config.data_dir
|
||||
and Path(volumes["/run/ranch-updater"]["source"]).resolve() == self.config.control_dir
|
||||
and volumes["/run/ranch-updater"].get("read_only") is True)
|
||||
except (KeyError, ValueError, TypeError):
|
||||
valid = False
|
||||
if not valid:
|
||||
raise UpdaterError("Compose 必须是固定 web 单服务、非 root 用户和指定挂载。")
|
||||
|
||||
def pull(self, image):
|
||||
self.compose(["pull", "--policy", "always", "web"], image=image, timeout=900)
|
||||
|
||||
def stop(self):
|
||||
self.compose(["stop", "--timeout", str(self.config.shutdown_timeout_seconds), "web"],
|
||||
timeout=self.config.shutdown_timeout_seconds + 30)
|
||||
remaining = self.inspect_service(allow_missing=True)
|
||||
if remaining and remaining["running"]:
|
||||
raise UpdaterError("旧服务未停止,拒绝创建不一致的备份。")
|
||||
|
||||
def up(self, image):
|
||||
self.compose(["up", "-d", "--no-build", "--pull", "never", "--wait", "--wait-timeout",
|
||||
str(self.config.wait_timeout_seconds), "web"], image=image,
|
||||
timeout=self.config.wait_timeout_seconds + self.config.shutdown_timeout_seconds + 60)
|
||||
running = self.inspect_service()
|
||||
if not running["running"] or running["health"] != "healthy":
|
||||
raise UpdaterError("容器未通过 /api/health 健康检查。")
|
||||
if image.startswith(f"{updates.IMAGE}:") and running["version"] != image[len(updates.IMAGE) + 2:]:
|
||||
raise UpdaterError("新镜像版本标记与正式发布标签不一致。")
|
||||
|
||||
|
||||
def snapshot_data(config, request_id):
|
||||
"""Create a complete directory snapshot only while all app writers are stopped."""
|
||||
config.backup_dir.mkdir(parents=True, mode=0o700, exist_ok=True)
|
||||
destination = config.backup_dir / f"{request_id}.tar.gz"
|
||||
if destination.exists():
|
||||
raise UpdaterError("备份标识冲突,已停止更新。")
|
||||
descriptor, temporary = tempfile.mkstemp(prefix=".snapshot-", dir=config.backup_dir)
|
||||
try:
|
||||
with os.fdopen(descriptor, "wb") as stream:
|
||||
os.chmod(temporary, 0o600)
|
||||
with tarfile.open(fileobj=stream, mode="w:gz", dereference=False) as archive:
|
||||
for directory, subdirs, filenames in os.walk(config.data_dir, followlinks=False):
|
||||
for name in sorted(subdirs + filenames):
|
||||
path = Path(directory) / name
|
||||
info = path.lstat()
|
||||
if stat.S_ISLNK(info.st_mode) or not (stat.S_ISREG(info.st_mode) or stat.S_ISDIR(info.st_mode)):
|
||||
raise UpdaterError("数据目录存在非普通文件,已中止备份并恢复旧服务。")
|
||||
if stat.S_ISREG(info.st_mode) and info.st_nlink != 1:
|
||||
raise UpdaterError("数据目录存在硬链接,已中止备份并恢复旧服务。")
|
||||
# Control status is preserved live; application data and keys are backed up.
|
||||
relative = path.relative_to(config.data_dir)
|
||||
if len(relative.parts) == 1 and name in _CONTROL_FILES:
|
||||
continue
|
||||
archive.add(path, arcname=str(relative), recursive=False)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, destination)
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
return destination
|
||||
|
||||
|
||||
def restore_data(config, backup, request_id):
|
||||
"""Swap in the snapshot, retaining failed-version data for operator inspection."""
|
||||
if backup.parent != config.backup_dir or backup.name != f"{request_id}.tar.gz":
|
||||
raise UpdaterError("回滚备份标识无效。")
|
||||
temporary = Path(tempfile.mkdtemp(prefix=".restore-", dir=config.data_dir.parent))
|
||||
try:
|
||||
with tarfile.open(backup, "r:gz") as archive:
|
||||
for member in archive.getmembers():
|
||||
relative = Path(member.name)
|
||||
if relative.is_absolute() or ".." in relative.parts or not (member.isfile() or member.isdir()):
|
||||
raise UpdaterError("备份包含不安全路径,拒绝回滚。")
|
||||
archive.extractall(temporary, filter="data")
|
||||
for name in _CONTROL_FILES:
|
||||
value = updates.read_json(config.data_dir / name)
|
||||
if value is not None:
|
||||
updates.atomic_json(temporary / name, value, mode=0o600 if name == "update-request.json" else 0o644)
|
||||
# The runtime image always uses this UID/GID. Restore encrypted keys with it.
|
||||
if hasattr(os, "chown"):
|
||||
for directory, subdirs, filenames in os.walk(temporary):
|
||||
for name in subdirs + filenames:
|
||||
os.chown(Path(directory) / name, 10001, 10001)
|
||||
os.chown(temporary, 10001, 10001)
|
||||
config.failed_data_dir.mkdir(parents=True, mode=0o700, exist_ok=True)
|
||||
failed = config.failed_data_dir / request_id
|
||||
if failed.exists():
|
||||
raise UpdaterError("失败数据隔离目录已存在,拒绝覆盖。")
|
||||
os.replace(config.data_dir, failed)
|
||||
try:
|
||||
os.replace(temporary, config.data_dir)
|
||||
except BaseException:
|
||||
os.replace(failed, config.data_dir)
|
||||
raise
|
||||
finally:
|
||||
if temporary.exists():
|
||||
shutil.rmtree(temporary)
|
||||
|
||||
|
||||
class HostUpdater:
|
||||
def __init__(self, config, docker=None):
|
||||
self.config = config
|
||||
self.docker = docker or Docker(config)
|
||||
self.journal = config.control_dir / "transaction.json"
|
||||
|
||||
def capability(self):
|
||||
old = updates.read_json(self.config.control_dir / "capability.json")
|
||||
old = old if isinstance(old, dict) else {}
|
||||
identity = old.get("executor_id")
|
||||
if not updates.valid_id(identity):
|
||||
identity = uuid.uuid4().hex
|
||||
now = updates.utc_now()
|
||||
value = {"protocol": updates.PROTOCOL, "executor_id": identity,
|
||||
"enabled": self.config.accept_web_requests, "auto_apply": self.config.auto_apply,
|
||||
"heartbeat_at": updates.timestamp(now),
|
||||
"expires_at": updates.timestamp(now + timedelta(minutes=15))}
|
||||
updates.atomic_json(self.config.control_dir / "capability.json", value)
|
||||
return value
|
||||
|
||||
def publish(self, request_id, version, status):
|
||||
value = {"protocol": updates.PROTOCOL, "request_id": request_id, "version": version,
|
||||
"status": status, "updated_at": updates.timestamp(), "error": None}
|
||||
updates.atomic_json(self.config.data_dir / "updater-status.json", value)
|
||||
return value
|
||||
|
||||
def check(self, current_version):
|
||||
return updates.UpdateService(self.config.data_dir, current_version).check()
|
||||
|
||||
def persist_image(self, image):
|
||||
if not (_DIGEST.fullmatch(image) or image.startswith(f"{updates.IMAGE}:")):
|
||||
raise UpdaterError("只能保存官方镜像或已固定的本地回滚镜像。")
|
||||
if not _DIGEST.fullmatch(image):
|
||||
updates.stable_version(image[len(updates.IMAGE) + 1:])
|
||||
descriptor, temporary = tempfile.mkstemp(prefix=".image-env-", dir=self.config.project_dir)
|
||||
try:
|
||||
with os.fdopen(descriptor, "w", encoding="ascii", newline="\n") as stream:
|
||||
stream.write(f"RANCH_WEB_IMAGE={image}\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, self.config.project_dir / ".image.env")
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
|
||||
def rollback(self, transaction):
|
||||
request_id, version = transaction["request_id"], transaction["version"]
|
||||
old_image = transaction["old_image"]
|
||||
if not _DIGEST.fullmatch(old_image) or not updates.valid_id(request_id):
|
||||
raise UpdaterError("回滚事务记录无效。")
|
||||
if transaction.get("backup_ready") and transaction.get("new_started"):
|
||||
self.docker.stop()
|
||||
restore_data(self.config, self.config.backup_dir / f"{request_id}.tar.gz", request_id)
|
||||
transaction["new_started"] = False
|
||||
updates.atomic_json(self.journal, transaction, mode=0o600)
|
||||
self.persist_image(old_image)
|
||||
self.docker.up(old_image)
|
||||
self.journal.unlink(missing_ok=True)
|
||||
return self.publish(request_id, version, "rolled_back")
|
||||
|
||||
def recover(self):
|
||||
transaction = updates.read_json(self.journal)
|
||||
if transaction is not None:
|
||||
return self.rollback(transaction)
|
||||
return None
|
||||
|
||||
def apply(self, version=None, *, request_id=None):
|
||||
# Source and monotonicity are rechecked here, including Web requests.
|
||||
old = self.docker.inspect_service()
|
||||
if not old["running"]:
|
||||
raise UpdaterError("现有服务未运行,请先由操作者处理。")
|
||||
try:
|
||||
tags = updates.official_tags(updates.github_releases())
|
||||
except Exception:
|
||||
raise UpdaterError("无法独立验证官方 GitHub 正式发布,保留现有服务。") from None
|
||||
target = version or (max(tags, key=updates.stable_version) if tags else None)
|
||||
if target is None:
|
||||
return {"status": "no_release", "message": "官方尚无稳定 Web 2 正式版。"}
|
||||
if target not in tags or updates.stable_version(target) <= updates.current_version_key(old["version"]):
|
||||
raise UpdaterError("目标必须是官方已发布且比现有容器更新的稳定 v2.x.y。")
|
||||
image = f"{updates.IMAGE}:{target}"
|
||||
request_id = request_id or uuid.uuid4().hex
|
||||
if not updates.valid_id(request_id):
|
||||
raise UpdaterError("更新请求标识无效。")
|
||||
self.docker.validate(image)
|
||||
self.docker.pull(image) # Pull failure leaves the old container running.
|
||||
transaction = {"protocol": 1, "request_id": request_id, "version": target,
|
||||
"old_image": old["image"], "backup_ready": False, "new_started": False}
|
||||
updates.atomic_json(self.journal, transaction, mode=0o600)
|
||||
self.publish(request_id, target, "applying")
|
||||
try:
|
||||
self.docker.stop()
|
||||
snapshot_data(self.config, request_id)
|
||||
transaction["backup_ready"] = True
|
||||
updates.atomic_json(self.journal, transaction, mode=0o600)
|
||||
# Mark before startup, since failed startups can already migrate data.
|
||||
transaction["new_started"] = True
|
||||
updates.atomic_json(self.journal, transaction, mode=0o600)
|
||||
self.docker.up(image)
|
||||
self.persist_image(image)
|
||||
except (Exception, KeyboardInterrupt):
|
||||
try:
|
||||
return self.rollback(transaction)
|
||||
except Exception:
|
||||
self.publish(request_id, target, "failed")
|
||||
raise UpdaterError("更新及自动回滚失败;已保留备份、失败数据和恢复事务。") from None
|
||||
self.journal.unlink(missing_ok=True)
|
||||
return self.publish(request_id, target, "succeeded")
|
||||
|
||||
def run(self):
|
||||
capability = self.capability()
|
||||
recovery = self.recover()
|
||||
if recovery:
|
||||
return recovery
|
||||
request = updates.read_json(self.config.data_dir / "update-request.json")
|
||||
if self.config.accept_web_requests and request is not None:
|
||||
if not isinstance(request, dict):
|
||||
return {"status": "failed", "message": "更新请求无效,未执行。"}
|
||||
previous = updates.read_json(self.config.data_dir / "updater-status.json")
|
||||
previous = previous if isinstance(previous, dict) else {}
|
||||
if previous.get("request_id") != request.get("request_id") or previous.get("status") not in {"succeeded", "failed", "rolled_back"}:
|
||||
identity, target = request.get("request_id"), request.get("version")
|
||||
try:
|
||||
if set(request) != {"protocol", "request_id", "executor_id", "version", "requested_at"}:
|
||||
raise ValueError
|
||||
issued = updates.parse_time(request.get("requested_at"))
|
||||
now = updates.utc_now()
|
||||
if (request["protocol"] != updates.PROTOCOL or not updates.valid_id(identity)
|
||||
or request["executor_id"] != capability["executor_id"] or issued is None
|
||||
or not now - timedelta(hours=24) <= issued <= now + timedelta(seconds=60)):
|
||||
raise ValueError
|
||||
updates.stable_version(target)
|
||||
return self.apply(target, request_id=identity)
|
||||
except (ValueError, UpdaterError):
|
||||
if updates.valid_id(identity):
|
||||
try:
|
||||
updates.stable_version(target)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
return self.publish(identity, target, "failed")
|
||||
return {"status": "failed", "message": "更新请求无效,未执行。"}
|
||||
current = self.docker.inspect_service()["version"]
|
||||
cached = updates.read_json(self.config.data_dir / "update-check.json")
|
||||
cached = cached if isinstance(cached, dict) else {}
|
||||
checked = updates.parse_time(cached.get("checked_at"))
|
||||
state = updates.UpdateService(self.config.data_dir, current).status()
|
||||
if checked is None or updates.utc_now() - checked >= timedelta(seconds=self.config.check_interval_seconds):
|
||||
state = self.check(current)
|
||||
if self.config.auto_apply and state["available"]:
|
||||
return self.apply(state["latest_version"])
|
||||
return state
|
||||
|
||||
|
||||
@contextmanager
|
||||
def exclusive(config):
|
||||
import fcntl
|
||||
path = config.project_dir / ".web-updater.lock"
|
||||
descriptor = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
||||
try:
|
||||
try:
|
||||
fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
raise UpdaterError("已有宿主机更新任务正在执行。") from None
|
||||
yield
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
|
||||
|
||||
def dry_run(config, mode, version):
|
||||
if version:
|
||||
updates.stable_version(version)
|
||||
return {"dry_run": True, "mode": mode, "repository": updates.REPOSITORY,
|
||||
"image": f"{updates.IMAGE}:{version or '<official-newer-v2.x.y>'}",
|
||||
"auto_apply": config.auto_apply, "accept_web_requests": config.accept_web_requests,
|
||||
"steps": ["verify official stable release and running version", "validate single-service mounts",
|
||||
"compose pull while old service runs", "stop; snapshot all data and encrypted keys",
|
||||
"compose up -d --no-build --pull never --wait --wait-timeout",
|
||||
"on failure: stop, restore snapshot, start pinned old image"]}
|
||||
|
||||
|
||||
def interrupt_update(signum, frame):
|
||||
raise InterruptedError("宿主机正在停止更新任务。")
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", default="/etc/ranch-web-updater.toml")
|
||||
mode = parser.add_mutually_exclusive_group(required=True)
|
||||
mode.add_argument("--check", action="store_true")
|
||||
mode.add_argument("--apply", nargs="?", const="", metavar="v2.x.y")
|
||||
mode.add_argument("--run", action="store_true")
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
config = Config.load(args.config, dry_run=args.dry_run)
|
||||
if args.dry_run:
|
||||
result = dry_run(config, "check" if args.check else "run" if args.run else "apply", args.apply)
|
||||
else:
|
||||
if sys.platform != "linux" or os.geteuid() != 0:
|
||||
raise UpdaterError("执行更新需要 Linux 宿主机上的受控 root 服务;Windows 仅支持 dry-run。")
|
||||
operator_config = Path(args.config)
|
||||
if (not operator_config.is_file() or operator_config.is_symlink()
|
||||
or operator_config.stat().st_uid != 0 or operator_config.stat().st_mode & 0o022):
|
||||
raise UpdaterError("执行器配置必须由 root 持有,且不能被其他用户写入。")
|
||||
if config.project_dir.stat().st_uid != 0 or config.project_dir.stat().st_mode & 0o022:
|
||||
raise UpdaterError("部署项目目录必须由 root 持有且禁止其他用户写入。")
|
||||
for path in (config.project_dir / "compose.yaml", config.project_dir / ".env", config.project_dir / ".image.env"):
|
||||
if not path.is_file() or path.is_symlink() or path.stat().st_uid != 0 or path.stat().st_mode & 0o022:
|
||||
raise UpdaterError("部署配置必须由 root 持有,且不能被其他用户写入。")
|
||||
if not config.data_dir.is_dir() or config.data_dir.is_symlink() or config.data_dir.stat().st_uid != 10001:
|
||||
raise UpdaterError("请先建立 UID 10001 可读写的独立 Web 数据目录。")
|
||||
if not config.control_dir.is_dir() or config.control_dir.is_symlink() or config.control_dir.stat().st_uid != 0 or config.control_dir.stat().st_mode & 0o022:
|
||||
raise UpdaterError("执行器控制目录必须由 root 持有且禁止其他用户写入。")
|
||||
signal.signal(signal.SIGTERM, interrupt_update)
|
||||
with exclusive(config):
|
||||
updater = HostUpdater(config)
|
||||
recovery = updater.recover()
|
||||
if recovery:
|
||||
result = recovery
|
||||
elif args.check:
|
||||
result = updater.check(updater.docker.inspect_service()["version"])
|
||||
elif args.run:
|
||||
result = updater.run()
|
||||
else:
|
||||
result = updater.apply(args.apply or None)
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
return int(result.get("status") in {"failed", "check_failed", "rolled_back"})
|
||||
except UpdaterError as error:
|
||||
print(json.dumps({"status": "failed", "message": str(error)}, ensure_ascii=False))
|
||||
return 1
|
||||
except (OSError, ValueError, TypeError):
|
||||
print(json.dumps({"status": "failed", "message": "执行器配置、发布验证或 Docker 操作失败;未输出凭据或私有路径。"}, ensure_ascii=False))
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,12 @@
|
||||
# Copy to /opt/ranch-web/.env, chmod 600, set a unique management password.
|
||||
RANCH_WEB_PASSWORD=
|
||||
RANCH_WEB_DATA_DIR=/opt/ranch-web/data
|
||||
RANCH_WEB_UPDATER_CONTROL_DIR=/opt/ranch-web/updater-control
|
||||
RANCH_WEB_BIND=127.0.0.1
|
||||
RANCH_WEB_PUBLISH_PORT=8765
|
||||
# Include the actual reverse-proxy hostname, without a scheme or path.
|
||||
RANCH_WEB_ALLOWED_HOSTS=localhost,127.0.0.1
|
||||
# Example behind TLS: https://ranch.example.com
|
||||
RANCH_WEB_ALLOWED_ORIGINS=
|
||||
# Set true when a TLS reverse proxy is configured.
|
||||
RANCH_WEB_SECURE_COOKIE=false
|
||||
@@ -0,0 +1,34 @@
|
||||
# Web 工作台设计
|
||||
|
||||
## 方向与依据
|
||||
|
||||
按明确需求采用 Impeccable 的 code-led Operate 路径。现有 `ranch_assistant/gui.py`、`accounts_gui.py` 及各功能 `*_gui.py` 是视觉与交互依据;不增加营销封面或装饰卡片,不改变十五页的顺序。
|
||||
|
||||
页面是一张紧凑的浅色操作台。顶层是菜单、账号页签和运行工具栏,中层是功能页与可横向滚动表格,底层是可调日志。功能名称、绿色开启与红色停止对应现有桌面。页签选中使用细蓝边和浅蓝背景,状态文字与颜色一起说明结果。
|
||||
|
||||
## 基础规格
|
||||
|
||||
- 字体:系统 UI,Windows 优先 Microsoft YaHei UI/Segoe UI,其他系统采用可用系统中文字体;不从网络下载。
|
||||
- 正文字号 13px,辅助文字 12px,页内标题 14px;表格紧凑、数字使用等宽数字。
|
||||
- 空间基准 4px,控件高 26–28px,表格行约 28px。表头置顶,长掉落文本省略并保留 tooltip。
|
||||
- 界面背景 `#f1f3f5`,内容白色,分隔 `#cbd1d8`,正文 `#202832`,次要文字 `#55616e`,强调 `#245d9b`。
|
||||
- 运行开启 `#20743a`,停止 `#b3261e`,警告 `#805300`。键盘焦点有 2px 可见轮廓,状态不会只靠颜色传达。
|
||||
- 菜单和上下文菜单使用独立浮层,确认使用原生 dialog,避免被滚动表格裁切。
|
||||
|
||||
## 交互要求
|
||||
|
||||
各账号独立保存内存中的页签、筛选、选中行、视图缓存和待保存配置。轮询期间不重建正在编辑的控件,不覆盖焦点所在输入。输入经 debounce 自动保存,执行策略前先完成待保存内容;冲突或校验错误保留用户输入并给出可重试状态。
|
||||
|
||||
表格提供排序、行选择、多选、原生 checkbox、number 与 select。普通浏览不改变 number 数值;只有输入获得焦点时滚轮才可作用。地图地区默认收起;筛选本身只请求 GET 视图。主线默认当前任务。表单由中文 schema、路径、类型与选项驱动,不以 JSON 文本框代替业务控件。
|
||||
|
||||
长任务保留任务状态并轮询;状态栏、账号切换和日志仍可使用。停止按钮提交即时停止操作,不等待前一任务完成。费用、消耗魔物和移除账号使用明确的二次确认。扩建先取服务端报价,确认后回传报价与批准字段。
|
||||
|
||||
日志只渲染文本,保留自动滚动开关;用户向上查看时不会被强行拉到底部。分隔条支持拖拽、方向键、Home/End。隐藏日志后内容区利用剩余高度。
|
||||
|
||||
## 响应式与可访问性
|
||||
|
||||
1280/1600 宽使用相同层级。工具栏可换行,导航和宽表格独立横向滚动;小屏保留原字段而不压缩成卡片。页签与菜单支持键盘,原生表单有 label,错误和状态使用可访问 live region。遵从减少动效偏好,界面无装饰动画。
|
||||
|
||||
## 技术默认假设
|
||||
|
||||
静态 ES modules 由 FastAPI 同源提供;路径为 `/static/`,入口 `/`。安全逻辑以服务端认证、Origin 校验、公开 DTO 与脱敏日志为边界,前端使用 `textContent`/DOM API,不执行来自游戏的 HTML。浏览器不保存密码、token、key、会话原文。截图、E2E 只使用离线演示或显式 fixture;无样本图表不产生虚构柱形。
|
||||
@@ -0,0 +1,65 @@
|
||||
# Web 前端交接
|
||||
|
||||
状态:实现与针对性浏览器检查完成,frontend owner freeze。无 commit / push;未修改其他 owner 的 Python 文件。现有桌面 GUI 是结构与语义依据,未导入 Qt,未增加构建或网络字体依赖。
|
||||
|
||||
## 文件
|
||||
|
||||
- `static/index.html`:菜单、账号页签、玩家工具栏、15 页导航、可调日志与管理登录入口。
|
||||
- `static/app.js`:同源 API 接线、账号隔离、队列任务轮询、debounce 自动保存、修订冲突保留输入、开始/即时停止、菜单与手动操作、导入导出、更新面板、日志懒加载详情。
|
||||
- `static/api.js`:公共 REST 客户端;JSON query 与同源 cookie;无凭据持久化。
|
||||
- `static/pages.js`:原页面顺序和名称、登录/区服/恢复、schema 表单、子页、过滤、地图/牧场分组、统计地区→关卡→难度树、真实 DTO SVG 图表。
|
||||
- `static/forms.js`:原生控件、编号/数量编辑、添加无库存蛋规则;聚焦输入不被轮询重建。
|
||||
- `static/table.js`:稳定行/单元格节点、排序/选择/上下文菜单、逐行 edit path、目标勾选、完整探险三人队伍草稿;地图按展开懒建表格。
|
||||
- `static/dom.js`、`static/ui.js`:纯文本 DOM、安全 CSV、下载、对话框、浮层和文件选择。
|
||||
- `static/styles.css`:浅色紧凑工作台、1280/1600/窄屏滚动布局、原生焦点/状态、无 inline-style 依赖。
|
||||
- `PRODUCT.md` / `DESIGN.md`:按 explicit brief 写入,标明技术默认假设。
|
||||
- `tests/browser/test_workbench_browser.py`:13 个可重复运行的 Python Playwright 检查;系统 Edge 或 `RANCH_WEB_BROWSER`,不下载浏览器。
|
||||
|
||||
## 已对齐的接口
|
||||
|
||||
- 读取实际 `views.py` / `analysis/WEB_V2_PARITY.md`,未修改其 schema。逐行以 `columns[].edit + rows[].edits` 合并定义;`{id}` 展开后使用同一个 config path。
|
||||
- 首次编辑把 `row.rule_defaults` 按字段作为“仅当缺失时补齐”记录,用户实际修改独立记录;修订冲突重读时默认字段不能覆盖另一个浏览器已有的值。牧场目标写整数优先级,取消删除键,勾选状态只读取配置当前路径,不回退到过期 DTO。蛋 `keep_count` 显示“牧场保留”。新增规则使用 `field.defaults_by_id[typeId]` 的完整规则和市场,保留通用 defaults fallback。
|
||||
- 探险队员只写 `[]`(自动)或完整三人 ID 数组;1/2 人在浏览器保留草稿,重复或等级不合规则不提交。自动按钮清空手动配置,由原核心选人。
|
||||
- `set_config` 返回 `pending/job_id/job` 时先轮询任务,再更新 applied revision;保留保存期间新增的输入。409 合并保留本机修改字段,提示手动重试。停止绕过配置等待。
|
||||
- 主线默认 `category=mainline,state=current`。统计使用 `stage_id/level/source/metric`;`chart.series` 直接绘制,rate 为 0–1,固定 0–100% 刻度,无样本不补数。
|
||||
- 调试摘要只展示 `message`;有 `details_available` 的条目点击后 GET `/api/accounts/{id}/debug/{entry_id}`,JSON 用 `textContent` 展示。兼容同源 `detail_url`。日志时间显示 Asia/Shanghai 的 HH:mm:ss,原完整时间保留在 title。
|
||||
- 扩建先取 `quote_expansion`,二次确认后只发 `{quote_id,confirm:true}`。批量派遣/喂养传 `monster_ids`、`target_id` 和显式 `confirm`。
|
||||
- 策略导入导出处理 HTTP 202 job。收益导入 `filename+content_base64`,支持 CSV/XLSX;下载 CSV 使用原导入器识别的“编号 / 派遣金币 / 强化经验 / 孵化秒数”列,可往返导入。
|
||||
- 绿色史莱姆预设使用 DTO `details.preset.patch/egg_rules`,点击即应用并保存,不额外确认、不开启运行。按所属子页展示 `details.feed_status/last_draw`,赠礼展示 `next_ready_at`。每体力数量在图表、tooltip 和表格保留六位有效数字,0.001 不显示为 0。
|
||||
- 更新弹窗每 3 秒 GET 公开状态,单次请求有超时且不重叠;关闭时清理定时器并取消请求。临时断连会核对 health 并重试;所有状态使用中文,仅服务端回报 succeeded 才显示完成,同时显示安全的宿主机回报。前端不操作 host 目录。
|
||||
|
||||
## 验证
|
||||
|
||||
真实临时 WebManager + ASGI + 系统 Edge headless:
|
||||
|
||||
```powershell
|
||||
python -m unittest ranch_web.tests.browser.test_workbench_browser -v
|
||||
```
|
||||
|
||||
最终同一次完整运行:`Ran 13 tests in 71.863s — OK`。服务使用最新 API 进程,13 个用例均通过:
|
||||
|
||||
1. 15 页全载入;切换只 GET,不提交动作/配置;1280、1600、390 宽可操作,页面无额外横向溢出;浏览器 JS / CSP error 为 0。真实 HTTP 的孵蛋三个子页与主线“任务状态 / 推进策略”均验证。
|
||||
2. 逐蛋规则补齐默认值并保存;轮询后节点与焦点不变;账号配置隔离;开启/停止成功。
|
||||
3. 探险半成品不 PUT,三人完整后才保存;自动清空;恶意 HTML 名称为纯文本。
|
||||
4. 统计地区/关卡默认收起,按展开建难度按钮;切换来源请求匹配,50%→25% 文案及柱宽同步。
|
||||
5. 调试摘要轮询不取详情,点击后只请求对应脱敏 JSON。
|
||||
6. fake 登录返回区服,密码提交后清空,不进 localStorage / sessionStorage / URL。
|
||||
7. 策略/收益下载,收益 CSV 被原 Catalog 导入器读回;报价取消无扩建,确认后真实离线扩建。
|
||||
8. 喂养、赠礼、突破三个目标取消后立即保持未勾选,配置键删除,过期 DTO 不会复勾。
|
||||
9. 新增无库存蛋使用真实 HTTP DTO 的逐 species 默认规则,市场非空且回显匹配。
|
||||
10. 两个浏览器页签并发编辑,真实 409 后重试:A 勾选,保留 B 新设的难度2 / 上限5,不回退为默认1 / 3。
|
||||
11. 0.001 每点体力收益在 SVG 标签、tooltip、表格与表格 tooltip 均正确显示。
|
||||
12. 喂养/抽蛋/下次赠礼状态可见;预设无确认弹窗,保存后运行保持关闭。
|
||||
13. fake 更新 pending→applying→服务503→succeeded,弹窗轮询自动恢复并显示中文宿主机状态;关闭后停止 GET。409/503 是用例明确注入的预期 HTTP 报告,不是 JS/CSP 错误。
|
||||
|
||||
所有七个 ES modules 经 `node --check`;无 `innerHTML`、浏览器持久存储、CDN、inline style attribute。测试全过程只 temporary + fake / 明确 demo,未测试真实游戏登录/API,未读取或修改私人账户。
|
||||
|
||||
## Main 复核与验证边界
|
||||
|
||||
Main 已独立检查离线演示的背包/孵蛋截图及浏览器 JS/CSP 状态。截图写入 `%TEMP%/ranch-web-render-*/`,不把本机账号路径、临时服务地址或进程号写入公共仓库。后续树懒加载与图表刻度修正以浏览器测试断言为准。
|
||||
|
||||
Main 已运行 Impeccable detector。`summary-line` / dialog 的紧凑间距与 `#172a40` 阴影提示已对照真实浅色截图审核;前者遵循明确的紧凑工作台需求,dialog 子元素已有 padding,阴影不是暗色发光界面。按 brief 例外保留,不扩大布局。
|
||||
|
||||
最终清理:已核验启动命令确属 frontend 的独立临时离线演示,随后停止该进程,并确认进程与监听均已释放。最终源码 freeze,未 commit / push。
|
||||
|
||||
验证边界:demo 原数据不包含已建立探险队或实测掉落;对应丰富状态由显式路由 fixture 验证。实际游戏登录/区服/领奖与 Linux host updater 的真实运行留给用户授权后的环境验证;前端不宣称这些已在线成功。收益下载为可往返导入的 CSV,XLSX 沿原功能用于导入。
|
||||
@@ -0,0 +1,33 @@
|
||||
# 牧羊人之心牧场助手 · Web
|
||||
|
||||
## 产品约束
|
||||
|
||||
把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。版本为 `2.0.0.dev1`,游戏数据版本 `1.9.68`;本次不合并 main、不发布正式版本。
|
||||
|
||||
使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。
|
||||
|
||||
## 固定工作台结构
|
||||
|
||||
1. 顶部原生风格菜单:账号、策略、配置、帮助。
|
||||
2. 多账号页签,支持新增、切换、移除。
|
||||
3. 当前角色昵称、等级、经验、金币、氪金、体力;随机刷新间隔、绿色开启/红色停止、刷新/预览、调试、日志显隐。
|
||||
4. 同桌面顺序的功能页:登录、培育室、背包、牧场、每日事务、自动孵蛋、自动主线、战斗记录、自动赠礼、自动委托、自动探险、自动扫荡、数据分析、执行计划、收益资料。
|
||||
5. 可拖动高度、可隐藏的底部日志和常驻状态栏。
|
||||
|
||||
## 核心操作
|
||||
|
||||
- 账号密码登录后选择区服进入;恢复已保存会话;退出与清除登录记录。游戏凭据仅交给同源服务端,不进入浏览器持久存储或 URL。
|
||||
- 配置通过中文 schema 生成原生控件;逐蛋孵化/补货规则、物品赠礼保留量、逐魔物培养目标、关卡规则等直接在对应页面编辑。自动保存显示待保存、保存中、失败与已保存状态。
|
||||
- 培育室扩建、牧场锁定/解锁、批量派遣/喂养、上下文菜单和费用二次确认沿用核心行为。切换功能页只读取视图,不触发游戏写操作。
|
||||
- 主线默认当前主线,可切换筛选。地图按地区默认折叠,展示普通关卡、矿洞、难度、次数和工具库存。探险支持队员手选/自动与完成后自动领奖说明。
|
||||
- 数据分析用真实 DTO 绘制 SVG 条形图,保留来源筛选、体力效率、样本和不确定性说明。没有样本时明确说明。
|
||||
- 策略统一导入导出;收益 CSV/XLSX 导入与可用数据下载。错误展示具体原因,不把不支持的任务伪装成可执行任务。
|
||||
- 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。
|
||||
|
||||
## 安全与验证
|
||||
|
||||
不发真实游戏 API 测试,不读取或更改私人 `local_state` 账号。浏览器测试仅使用临时目录、fake 后端或服务端离线演示。所有游戏文本用 `textContent` 呈现;日志使用服务端脱敏数据。管理登录、同源校验与 cookie 由 API 负责。
|
||||
|
||||
## 技术默认假设
|
||||
|
||||
原生 HTML/CSS/ES modules,无 React、npm 构建、CDN 或网络字体。FastAPI 同源提供静态资源和 `/api`。以共享 WebManager/API/视图 DTO 契约为准,前端不构造游戏在线成功数据。桌面/服务端拥有业务规则,前端拥有展示与交互。1280 和 1600 宽桌面均可操作,小屏允许横向滚动。非业务的布局偏好可以存本机,凭据不可持久化。
|
||||
@@ -0,0 +1,77 @@
|
||||
# Web 2 开发运行
|
||||
|
||||
Web 包版本 **2.0.0.dev1**,游戏资料基线 **1.9.68**,开发分支 `develop/v2.0.0`。当前正式桌面版仍为 1.2.0;Web 未合并 main、未发布正式版本。桌面入口 `python -m ranch_assistant` 保留,Web 使用独立依赖与数据根。
|
||||
|
||||
Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或前端编译步骤,不安装 PySide6。页面和策略能力沿用现有核心,详细业务范围与原有限制见 [桌面使用说明](../ranch_assistant/README.md)。多浏览器连接同一个管理员工作台;一个服务实例内,各账号独立线程并行,同一账号操作串行。
|
||||
|
||||
## 迁移清单
|
||||
|
||||
- [x] 原15页:登录、培育室、背包、牧场、每日事务、自动孵蛋、自动主线、战斗记录、自动赠礼、自动委托、自动探险、自动扫荡、数据分析、执行计划、收益资料。
|
||||
- [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,重启、恢复会话及导入策略后保持停止。
|
||||
- [x] Windows Python 启动与离线演示;Web 导入链和依赖不使用 Qt,无 Node 构建步骤。
|
||||
- [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;Linux Docker 尚未实机验收。
|
||||
- [x] 开发版本为 `2.0.0.dev1`,保留桌面兼容,不等同正式发布或真实游戏 API 验收。
|
||||
|
||||
## Windows 本地开发
|
||||
|
||||
使用 Python 3.12+,在项目根目录执行(本机已安装 3.13):
|
||||
|
||||
```powershell
|
||||
py -3 -m venv .venv-web
|
||||
.\.venv-web\Scripts\python.exe -m pip install -r ranch_web\requirements.txt
|
||||
.\Start_Ranch_Web.cmd
|
||||
```
|
||||
|
||||
默认地址 `http://127.0.0.1:8765`,本机无需管理密码。启动脚本优先使用 `.venv-web`,否则使用 PATH 中的 `python`。也可直接运行 `python -B -m ranch_web`;安装依赖时务必选择同一解释器。首启不自动创建或登录游戏账号。
|
||||
|
||||
离线演示请指定全新目录,仅使用 fake / 内置演示,不连接真实游戏 API,也不要指向桌面私有目录:
|
||||
|
||||
```powershell
|
||||
.\Start_Ranch_Web.cmd --demo --data-dir "$env:TEMP\ranch-web-demo-new" --no-browser
|
||||
```
|
||||
|
||||
健康检查 `GET /api/health` 不访问游戏 API。关闭终端时使用 Ctrl+C,让应用正常关闭账号队列。重启、恢复会话或导入策略后仍需手动开启运行。
|
||||
|
||||
## Linux Python 与环境变量
|
||||
|
||||
```sh
|
||||
python3 -m venv .venv-web
|
||||
.venv-web/bin/python -m pip install -r ranch_web/requirements.txt
|
||||
sh start-web.sh --no-browser
|
||||
```
|
||||
|
||||
| 设置 | 默认 / 用途 |
|
||||
| --- | --- |
|
||||
| `RANCH_WEB_HOST` | `127.0.0.1`;非 loopback 必须设置管理密码 |
|
||||
| `RANCH_WEB_PORT` | `8765` |
|
||||
| `RANCH_WEB_DATA_DIR` | 项目下 `local_state/ranch_web`;Docker 固定 `/data` |
|
||||
| `RANCH_WEB_PASSWORD` | 独立的 Web 管理密码,不是游戏密码 |
|
||||
| `RANCH_WEB_PASSWORD_HASH` | 可替代明文管理密码,格式与生成函数见 `config.py` |
|
||||
| `RANCH_WEB_ALLOWED_HOSTS` | 明确的额外域名/IP,无通配符 |
|
||||
| `RANCH_WEB_ALLOWED_ORIGINS` | 明确的额外 http(s) 来源,逗号分隔 |
|
||||
| `RANCH_WEB_SECURE_COOKIE` | HTTPS 反代时设 `true` |
|
||||
| `RANCH_WEB_UPDATER_DIR` | 受控宿主机心跳目录;本地默认不设置 |
|
||||
|
||||
账号密钥、加密凭据、会话、配置和统计保留在服务端数据目录,不写入浏览器 localStorage。管理登录使用 HttpOnly / SameSite cookie,写请求校验 Origin。不要启动多个 Uvicorn worker 或多个服务实例共享同一数据根。
|
||||
|
||||
## Docker 与在线更新
|
||||
|
||||
完整步骤见 [Linux Docker 部署与受控更新](../deploy/web/README.md)。镜像使用 UID/GID 10001,持久化 `/data`,内置 `/api/health` healthcheck,正常退出宽限 120 秒,不挂载 Docker socket。
|
||||
|
||||
Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、未来 3.x、草稿和预发布。开发版本 `2.0.0.dev1` 可升级至同数字的正式 `v2.0.0`;没有正式 Web 2 发布时明确显示暂无更新。Windows 默认仅检查;Web “更新”按钮仅在宿主机显式启用并有有效只读心跳时可提交 `pending` 请求,安装、备份和回滚由宿主机执行。默认定时检查只通知,自动安装需操作者 opt-in。
|
||||
|
||||
## 离线验证
|
||||
|
||||
最终非浏览器后端验证 **185项:184通过、1跳过(Windows符号链接权限),0失败/错误**。以下完整命令显式列出后端模块,避免发现并混入浏览器测试:
|
||||
|
||||
```console
|
||||
python -B -m unittest ranch_web.tests.test_api ranch_web.tests.test_auth ranch_web.tests.test_scheduler ranch_web.tests.test_service ranch_web.tests.test_store ranch_web.tests.test_updates ranch_web.tests.test_web_integration ranch_web.tests.test_web_policies ranch_web.tests.test_web_updater ranch_web.tests.test_web_views_actions -v
|
||||
```
|
||||
|
||||
浏览器 **13项通过,JS/CSP错误为0**;另在新 Edge 进程验证15页、主线策略与孵蛋子页切换、未配置执行器时禁用更新按钮。浏览器测试需要 Python Playwright 和可用的 Edge,属于验证依赖:
|
||||
|
||||
```console
|
||||
python -B -m unittest ranch_web.tests.browser.test_workbench_browser -v
|
||||
```
|
||||
|
||||
全部验证使用临时目录、fake transport / GitHub / Docker 或内置离线演示,不读取私有账户,不访问真实游戏 API。停止取消、配置并发保存、视图索引清理、子页字段保留和并发认证限流的已报问题均已修复并复核。当前 Windows 无 Docker;上述结果不代表 Linux Docker、生产更新器或真实游戏服务器实机验收通过。
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Headless Web workspace for the ranch assistant."""
|
||||
|
||||
__version__ = "2.0.0.dev1"
|
||||
GAME_VERSION = "1.9.68"
|
||||
|
||||
__all__ = ["__version__", "GAME_VERSION"]
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Run the local Web workspace: python -m ranch_web --demo --no-browser."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from contextlib import asynccontextmanager
|
||||
import threading
|
||||
import webbrowser
|
||||
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
import uvicorn
|
||||
|
||||
from . import __version__
|
||||
from .app import create_app
|
||||
from .config import WebConfig
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
parser = argparse.ArgumentParser(description="牧羊人之心 Web 工作台(Windows / Linux,无需 Qt)")
|
||||
parser.add_argument("--host", help="监听地址,默认 127.0.0.1;远程绑定必须配置管理密码")
|
||||
parser.add_argument("--port", type=int, help="监听端口,默认 8765")
|
||||
parser.add_argument("--data-dir", help="独立 Web 数据目录,默认 local_state/ranch_web")
|
||||
parser.add_argument("--demo", action="store_true", help="添加一个离线演示账号,不访问游戏服务器")
|
||||
parser.add_argument("--no-browser", action="store_true", help="启动后不自动打开浏览器")
|
||||
parser.add_argument("--version", action="version", version=__version__)
|
||||
args = parser.parse_args(argv)
|
||||
overrides = {key: value for key, value in {"host": args.host, "port": args.port, "data_dir": args.data_dir}.items() if value is not None}
|
||||
try:
|
||||
settings = WebConfig.from_env(**overrides)
|
||||
except (ValueError, TypeError):
|
||||
parser.error("Web 设置无效;请检查监听地址、端口及 RANCH_WEB_PASSWORD 等环境变量")
|
||||
app = create_app(config=settings)
|
||||
application_lifespan = app.router.lifespan_context
|
||||
browser_timer = None
|
||||
|
||||
@asynccontextmanager
|
||||
async def cli_lifespan(application):
|
||||
nonlocal browser_timer
|
||||
async with application_lifespan(application):
|
||||
if args.demo:
|
||||
accounts = await run_in_threadpool(application.state.manager.list_accounts)
|
||||
if not any(item.get("demo") for item in accounts):
|
||||
await run_in_threadpool(application.state.manager.create_account, label="离线演示", demo=True)
|
||||
if not args.no_browser:
|
||||
browser_host = settings.host
|
||||
if browser_host == "0.0.0.0":
|
||||
browser_host = "127.0.0.1"
|
||||
elif browser_host == "::":
|
||||
browser_host = "::1"
|
||||
authority = f"[{browser_host}]" if ":" in browser_host else browser_host
|
||||
browser_timer = threading.Timer(1, webbrowser.open, args=(f"http://{authority}:{settings.port}/",))
|
||||
browser_timer.daemon = True
|
||||
browser_timer.start()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if browser_timer is not None:
|
||||
browser_timer.cancel()
|
||||
|
||||
app.router.lifespan_context = cli_lifespan
|
||||
# Request bodies, credentials and arbitrary query strings do not belong in access logs.
|
||||
uvicorn.run(app, host=settings.host, port=settings.port, access_log=False, proxy_headers=False)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Account-queue actions backed by the existing Engine, without GUI imports."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
from copy import copy, deepcopy
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import tempfile
|
||||
import time
|
||||
from zipfile import BadZipFile
|
||||
from xml.etree.ElementTree import ParseError
|
||||
|
||||
from ranch_assistant.management import expansion_quote
|
||||
from .policies import export_config, import_config, validate_config
|
||||
|
||||
|
||||
OPERATIONS = frozenset({"refresh", "refresh_maps", "refresh_tasks", "claim_daily", "lock", "unlock",
|
||||
"sell", "feed", "quote_expansion", "expand", "export_config", "import_config", "import_yields", "reset_map_pending"})
|
||||
|
||||
|
||||
def _payload(value, allowed):
|
||||
if value is None:
|
||||
value = {}
|
||||
if not isinstance(value, dict) or set(value) - set(allowed):
|
||||
raise ValueError("操作参数包含未知或不允许的字段")
|
||||
return value
|
||||
|
||||
|
||||
def _ids(value):
|
||||
if not isinstance(value, list) or not value or any(type(mid) is not int or mid <= 0 for mid in value):
|
||||
raise ValueError("请选择魔物(编号须为正整数列表)")
|
||||
return list(dict.fromkeys(value))
|
||||
|
||||
|
||||
def _stop(worker):
|
||||
stop = getattr(worker, "stop", None)
|
||||
if callable(stop):
|
||||
stop()
|
||||
worker.engine.auto = False
|
||||
|
||||
|
||||
def _consume(worker, value):
|
||||
"""Never serialize an Engine triple: its first element is a private snapshot."""
|
||||
if not isinstance(value, tuple) or len(value) != 3:
|
||||
raise ValueError("引擎未返回可确认的操作结果")
|
||||
consume = getattr(worker, "result", None)
|
||||
if callable(consume):
|
||||
consume(*value)
|
||||
return {"message": str(value[2]), "demo": bool(worker.engine.demo)}
|
||||
|
||||
|
||||
def _save(worker, config):
|
||||
value = validate_config(config)
|
||||
saver = getattr(worker, "save_config", None) or getattr(worker, "replace_config", None)
|
||||
if not callable(saver):
|
||||
raise ValueError("当前账号运行时尚未提供配置保存接口")
|
||||
result = saver(value)
|
||||
return result if isinstance(result, dict) and "config" in result else {"config": value}
|
||||
|
||||
|
||||
def _snapshot(engine):
|
||||
if not engine.demo:
|
||||
engine.read_snapshot()
|
||||
if engine.snapshot is None:
|
||||
raise ValueError("请先登录或打开离线演示")
|
||||
|
||||
|
||||
def _refresh(worker, page):
|
||||
engine = worker.engine
|
||||
if page in ("yields", "statistics", "plans"):
|
||||
return {"message": "已刷新本地资料 / 预览", "demo": bool(engine.demo)}
|
||||
previous = engine.auto
|
||||
engine.auto = False
|
||||
try:
|
||||
if page == "maps":
|
||||
value = engine.refresh_stages()
|
||||
elif page in ("mainline", "battles", "commissions"):
|
||||
value = engine.refresh_progression()
|
||||
else:
|
||||
value = engine.poll()
|
||||
return _consume(worker, value)
|
||||
finally:
|
||||
# A user stop during a long refresh must win. Runtime owns this flag.
|
||||
running = getattr(worker, "running", previous)
|
||||
engine.auto = bool(previous and running)
|
||||
|
||||
|
||||
def _import_yields(worker, payload):
|
||||
filename = payload.get("filename", "")
|
||||
if not isinstance(filename, str) or Path(filename).suffix.lower() not in (".csv", ".xlsx"):
|
||||
raise ValueError("收益资料仅支持CSV或XLSX文件")
|
||||
encoded = payload.get("content_base64")
|
||||
if not isinstance(encoded, str) or len(encoded) > 12_000_000:
|
||||
raise ValueError("请上传有效的收益资料文件(最大8MiB)")
|
||||
try:
|
||||
content = base64.b64decode(encoded, validate=True)
|
||||
except (binascii.Error, ValueError) as exc:
|
||||
raise ValueError("收益资料编码无效") from exc
|
||||
if not content or len(content) > 8 * 1024 * 1024:
|
||||
raise ValueError("收益资料文件为空或超过8MiB")
|
||||
catalog = copy(worker.engine.catalog)
|
||||
catalog.overrides = deepcopy(catalog.overrides)
|
||||
# The supplied name is never used as a local path. All parser writes stay
|
||||
# in a disposable directory; invalid imports cannot alter live overrides.
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(prefix="ranch-web-yields-") as folder:
|
||||
path = Path(folder) / ("uploaded" + Path(filename).suffix.lower())
|
||||
path.write_bytes(content)
|
||||
count = catalog.import_prices(path)
|
||||
except ImportError as exc:
|
||||
raise ValueError("读取XLSX需要安装openpyxl") from exc
|
||||
except (OSError, KeyError, TypeError, ValueError, StopIteration, BadZipFile, ParseError) as exc:
|
||||
raise ValueError("收益资料格式错误:需含typeId/编号及派遣金币、强化经验或孵化秒数字段") from exc
|
||||
updated = deepcopy(worker.config)
|
||||
updated["overrides"] = catalog.overrides
|
||||
saved = _save(worker, updated)
|
||||
return {"count": count, "overrides": deepcopy(saved["config"]["overrides"]), "message": f"已导入{count}条收益资料"}
|
||||
|
||||
|
||||
def _reset_map_pending(worker, payload):
|
||||
if payload.get("confirm") is not True:
|
||||
raise ValueError("请先确认核对未完成记录")
|
||||
engine = worker.engine
|
||||
_stop(worker)
|
||||
_snapshot(engine)
|
||||
journal = getattr(engine, "battle_journal", None)
|
||||
battle = journal.pending(engine.snapshot) if journal else None
|
||||
if battle:
|
||||
raise ValueError("任务 / 普通挑战记录由引擎按服务器证据自动核对,不能手动清除;请查看战斗记录")
|
||||
sweeper = engine.sweeper
|
||||
if not sweeper.state.get("pending"):
|
||||
return {"cleared": False, "message": "没有未完成的扫荡记录"}
|
||||
trace = getattr(getattr(engine, "client", None), "trace", None) or getattr(worker, "trace", None)
|
||||
trace_path = getattr(trace, "path", None)
|
||||
# Only the core's role/request/response-matched evidence can repair the old
|
||||
# reward-event block. A browser's server_verified checkbox is not evidence.
|
||||
sweeper.recovery_checked = False
|
||||
if sweeper.recover_reward_event(engine.snapshot, trace_path):
|
||||
return {"cleared": True, "message": "已按当前账号的服务器成功响应核对奖励事件,解除旧版阻塞"}
|
||||
raise ValueError("缺少当前账号、关卡和难度匹配的服务器结算证据,已保留待核对记录;请在游戏内核对后刷新")
|
||||
|
||||
|
||||
def execute_action(worker, operation, payload=None):
|
||||
if operation not in OPERATIONS:
|
||||
raise ValueError("不支持此操作")
|
||||
engine = worker.engine
|
||||
if operation == "refresh":
|
||||
p = _payload(payload, {"page"})
|
||||
from .views import PAGES
|
||||
if p.get("page", "incubator") not in dict(PAGES):
|
||||
raise ValueError("未知页面")
|
||||
return _refresh(worker, p.get("page", "incubator"))
|
||||
if operation in ("refresh_maps", "refresh_tasks"):
|
||||
_payload(payload, set())
|
||||
return _refresh(worker, "maps" if operation == "refresh_maps" else "mainline")
|
||||
if operation == "claim_daily":
|
||||
_payload(payload, set())
|
||||
_stop(worker)
|
||||
return _consume(worker, engine.claim_daily())
|
||||
if operation in ("lock", "unlock", "sell", "feed"):
|
||||
allowed = {"monster_ids"} if operation in ("lock", "unlock") else {"monster_ids", "confirm"}
|
||||
if operation == "feed":
|
||||
allowed.add("target_id")
|
||||
p = _payload(payload, allowed)
|
||||
ids = _ids(p.get("monster_ids"))
|
||||
if operation in ("sell", "feed") and p.get("confirm") is not True:
|
||||
raise ValueError("派遣 / 喂养会消耗选中魔物,请明确确认")
|
||||
if operation == "feed" and (type(p.get("target_id")) is not int or p["target_id"] <= 0):
|
||||
raise ValueError("请选择牧场中的喂养目标")
|
||||
_stop(worker)
|
||||
value = engine.set_monster_lock(ids, operation == "lock") if operation in ("lock", "unlock") else engine.manage_monsters(operation, ids, p.get("target_id", 0))
|
||||
return _consume(worker, value)
|
||||
if operation == "quote_expansion":
|
||||
p = _payload(payload, {"kind", "currency", "position"})
|
||||
position = p.get("position", -1)
|
||||
if type(position) is not int:
|
||||
raise ValueError("坑位位置须为整数(从0开始)")
|
||||
_stop(worker)
|
||||
_snapshot(engine)
|
||||
if p.get("kind") == "stack" and "position" not in p:
|
||||
opened = {int(row.get("position", -1)) for row in engine.snapshot.raw["stacks"]}
|
||||
position = next((i for i in range(int(engine.catalog.data["stack_meta"]["total"])) if i not in opened and i != 3), -1)
|
||||
quote = expansion_quote(engine.catalog, engine.snapshot, p.get("kind"), p.get("currency"), position)
|
||||
quote_id = secrets.token_urlsafe(24)
|
||||
worker._web_expansion_quotes = {quote_id: (time.monotonic(), quote)}
|
||||
return {"quote_id": quote_id, "kind": quote.kind, "currency": quote.currency, "position": quote.position,
|
||||
"cost": quote.cost, "level": quote.level, "description": quote.description}
|
||||
if operation == "expand":
|
||||
p = _payload(payload, {"quote_id", "confirm"})
|
||||
if p.get("confirm") is not True or not isinstance(p.get("quote_id"), str):
|
||||
raise ValueError("请先读取扩建报价并明确确认费用")
|
||||
record = getattr(worker, "_web_expansion_quotes", {}).pop(p["quote_id"], None)
|
||||
if record is None or time.monotonic() - record[0] > 120:
|
||||
raise ValueError("扩建报价已失效,请重新读取并确认")
|
||||
_stop(worker)
|
||||
return _consume(worker, engine.expand(record[1]))
|
||||
if operation == "export_config":
|
||||
_payload(payload, set())
|
||||
return export_config(worker.config, engine.snapshot)
|
||||
if operation == "import_config":
|
||||
p = _payload(payload, {"config"})
|
||||
imported = import_config(p.get("config"), engine.snapshot)
|
||||
_stop(worker)
|
||||
# Import is configuration only. Saving never calls Engine.poll.
|
||||
return _save(worker, imported)
|
||||
if operation == "import_yields":
|
||||
return _import_yields(worker, _payload(payload, {"filename", "content_base64"}))
|
||||
if operation == "reset_map_pending":
|
||||
return _reset_map_pending(worker, _payload(payload, {"confirm", "server_verified"}))
|
||||
raise ValueError("不支持此操作")
|
||||
@@ -0,0 +1,669 @@
|
||||
"""FastAPI transport and administrator boundary for the headless workspace."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import OrderedDict
|
||||
from contextlib import asynccontextmanager
|
||||
from dataclasses import replace
|
||||
import hashlib
|
||||
import inspect
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path as FilePath
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from typing import Annotated, Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Path, Query, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from starlette.responses import FileResponse, JSONResponse, Response
|
||||
from starlette.staticfiles import StaticFiles
|
||||
|
||||
from . import GAME_VERSION, __version__
|
||||
from .config import COOKIE_NAME, WebConfig, is_loopback, normalize_host, normalize_origin, verify_password
|
||||
|
||||
|
||||
PAGES = tuple("login incubator bag ranch daily hatching mainline battles gifts commissions exploration maps statistics plans yields".split())
|
||||
ACTIONS = frozenset("refresh refresh_maps refresh_tasks claim_daily lock unlock sell feed quote_expansion expand export_config import_config import_yields reset_map_pending login enter_server restore_session logout forget_login start stop".split())
|
||||
Identifier = Annotated[str, Path(pattern=r"^[A-Za-z0-9_-]{1,80}$")]
|
||||
_PUBLIC_PATHS = frozenset({"/api/health", "/api/meta", "/api/auth/status", "/api/auth/login", "/api/auth/logout"})
|
||||
_WRITES = frozenset({"POST", "PUT", "PATCH", "DELETE"})
|
||||
_JOB_STATUSES = frozenset({"queued", "running", "succeeded", "failed", "cancelled"})
|
||||
_PRIVATE_KEYS = frozenset({"key", "reqid", "reqsid", "requestid", "password", "passwordhash", "passwd", "pwd", "userpwd", "newpass", "secret", "credentials", "protected", "authorization", "cookie", "setcookie", "raw", "snapshot", "rawsnapshot", "profileroot", "stateroot", "dataroot", "datadir", "filepath", "budgetpath", "private", "headers", "body", "request", "response"})
|
||||
_METADATA_CONTEXTS = frozenset({"columns", "fields", "filters", "form", "pages", "options", "tabs"})
|
||||
_FILE_KEYS = frozenset({"path", "filepath", "fileroot", "root", "profileroot", "stateroot", "datadir", "budgetpath"})
|
||||
_YIELDS_IMPORT_PATH = re.compile(r"/api/accounts/[A-Za-z0-9_-]{1,80}/actions/import_yields")
|
||||
_YIELDS_IMPORT_BODY_BYTES = 12 * 1024 * 1024
|
||||
|
||||
|
||||
def _error(status: int, code: str, message: str) -> JSONResponse:
|
||||
return JSONResponse({"error": {"code": code, "message": message}, "detail": message}, status_code=status)
|
||||
|
||||
|
||||
class _Redactor:
|
||||
def __init__(self, settings: WebConfig):
|
||||
self.lock = threading.Lock()
|
||||
self.secrets: set[str] = set()
|
||||
self.paths = {str(settings.data_dir), settings.data_dir.as_posix()}
|
||||
|
||||
def remember(self, value: Any) -> None:
|
||||
if isinstance(value, dict):
|
||||
for key, item in value.items():
|
||||
name = str(key).lower().replace("_", "").replace("-", "")
|
||||
if name in _PRIVATE_KEYS or "token" in name or "password" in name or name.endswith(("key", "secret")):
|
||||
if isinstance(item, str) and item:
|
||||
with self.lock:
|
||||
if len(self.secrets) < 4096:
|
||||
self.secrets.add(item)
|
||||
elif isinstance(item, (list, dict)):
|
||||
self.remember(item)
|
||||
elif isinstance(value, list):
|
||||
for item in value:
|
||||
self.remember(item)
|
||||
|
||||
def text(self, value: str) -> str:
|
||||
with self.lock:
|
||||
known = sorted(self.secrets, key=len, reverse=True)
|
||||
for secret in known:
|
||||
value = value.replace(secret, "<隐藏>")
|
||||
for path in sorted(self.paths, key=len, reverse=True):
|
||||
value = value.replace(path, "<本地目录>")
|
||||
value = re.sub(
|
||||
r'''(?i)(["']?(?:password|passwd|pwd|[\w-]*token|secret|authorization|cookie|reqsid|reqid|key)["']?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;&}\r\n]+)''',
|
||||
lambda m: m[1] + "<隐藏>", value,
|
||||
)
|
||||
value = re.sub(r"(?i)\b(?:Bearer|Basic)\s+[A-Za-z0-9+/=_\-.]+", "<隐藏>", value)
|
||||
value = re.sub(r"[A-Za-z]:[\\/][^\s\"'<>]*", "<本地路径>", value)
|
||||
value = re.sub(r"(?<![\w:/])/[^/\s\"'<>][^\s\"'<>]*", "<本地路径>", value)
|
||||
value = re.sub(r"\\\\[^\s\"'<>]+", "<本地路径>", value)
|
||||
return value[:32_000]
|
||||
|
||||
def public(self, value: Any, *, context: str = "", trace: bool = False, depth: int = 0) -> Any:
|
||||
if depth > 32:
|
||||
return None
|
||||
if value is None or type(value) in (bool, int):
|
||||
return value
|
||||
if type(value) is float:
|
||||
return value if math.isfinite(value) else None
|
||||
if isinstance(value, str):
|
||||
return self.text(value)
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [self.public(item, context=context, trace=trace, depth=depth + 1) for item in value]
|
||||
if isinstance(value, dict):
|
||||
result = {}
|
||||
for field, item in value.items():
|
||||
if not isinstance(field, str):
|
||||
field = str(field)
|
||||
name = field.lower().replace("_", "").replace("-", "")
|
||||
if name == "hassavedpassword":
|
||||
if type(item) is bool:
|
||||
result[field] = item
|
||||
continue
|
||||
metadata_key = name == "key" and context in _METADATA_CONTEXTS and not trace
|
||||
envelope = trace and name in {"headers", "body", "request", "response"}
|
||||
private = name in _PRIVATE_KEYS or "token" in name or "password" in name or name.endswith(("key", "secret"))
|
||||
if private and not (metadata_key or envelope):
|
||||
if trace:
|
||||
result[field] = "<隐藏>"
|
||||
continue
|
||||
result[field] = self.public(item, context=field, trace=trace, depth=depth + 1)
|
||||
return result
|
||||
# Never serialize arbitrary Engine / Session / Snapshot / Path objects.
|
||||
return None
|
||||
|
||||
|
||||
class _Sessions:
|
||||
def __init__(self, settings: WebConfig):
|
||||
self.settings = settings
|
||||
self.lock = threading.Lock()
|
||||
self.sessions: OrderedDict[str, float] = OrderedDict()
|
||||
self.failures: OrderedDict[str, list[tuple[float, object]]] = OrderedDict()
|
||||
|
||||
def authenticated(self, request: Request) -> bool:
|
||||
if not self.settings.credential:
|
||||
return bool(request.client and is_loopback(request.client.host))
|
||||
token = request.cookies.get(COOKIE_NAME, "")
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{43}", token):
|
||||
return False
|
||||
digest = hashlib.sha256(token.encode()).hexdigest()
|
||||
with self.lock:
|
||||
expiry = self.sessions.get(digest)
|
||||
if expiry is not None and expiry > time.monotonic():
|
||||
return True
|
||||
self.sessions.pop(digest, None)
|
||||
return False
|
||||
|
||||
def login(self, request: Request, password: str) -> str:
|
||||
peer = request.client.host if request.client else "unknown"
|
||||
now = time.monotonic()
|
||||
reservation = object()
|
||||
with self.lock:
|
||||
failures = [entry for entry in self.failures.get(peer, []) if entry[0] > now - 60]
|
||||
if len(failures) >= 10:
|
||||
raise HTTPException(429, "尝试过于频繁,请稍后再试")
|
||||
# Pending verifications count against the same bounded per-peer budget.
|
||||
self.failures[peer] = failures + [(now, reservation)]
|
||||
self.failures.move_to_end(peer)
|
||||
while len(self.failures) > 1024:
|
||||
self.failures.popitem(last=False)
|
||||
# PBKDF work runs outside the session lock, independently for each request.
|
||||
if not verify_password(password, self.settings.credential):
|
||||
raise HTTPException(401, "管理密码错误")
|
||||
token = secrets.token_urlsafe(32)
|
||||
digest = hashlib.sha256(token.encode()).hexdigest()
|
||||
now = time.monotonic()
|
||||
with self.lock:
|
||||
failures = [entry for entry in self.failures.get(peer, [])
|
||||
if entry[1] is not reservation and entry[0] > now - 60]
|
||||
if failures:
|
||||
self.failures[peer] = failures
|
||||
else:
|
||||
self.failures.pop(peer, None)
|
||||
expired = [key for key, expiry in self.sessions.items() if expiry <= now]
|
||||
for key in expired:
|
||||
del self.sessions[key]
|
||||
while len(self.sessions) >= 256:
|
||||
self.sessions.popitem(last=False)
|
||||
self.sessions[digest] = now + self.settings.session_ttl
|
||||
self.logout(request)
|
||||
return token
|
||||
|
||||
def logout(self, request: Request) -> None:
|
||||
token = request.cookies.get(COOKIE_NAME, "")
|
||||
with self.lock:
|
||||
self.sessions.pop(hashlib.sha256(token.encode()).hexdigest(), None)
|
||||
|
||||
|
||||
class _Boundary:
|
||||
"""Bounded ASGI body buffering and checks before any API handler runs."""
|
||||
|
||||
def __init__(self, app, *, settings: WebConfig, sessions: _Sessions):
|
||||
self.app, self.settings, self.sessions = app, settings, sessions
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
request = Request(scope)
|
||||
|
||||
async def deny(status, code, message):
|
||||
await _error(status, code, message)(scope, receive, secure_send)
|
||||
|
||||
async def secure_send(message):
|
||||
if message["type"] == "http.response.start":
|
||||
headers = list(message.get("headers", []))
|
||||
headers.extend([
|
||||
(b"x-content-type-options", b"nosniff"),
|
||||
(b"referrer-policy", b"same-origin"),
|
||||
(b"x-frame-options", b"DENY"),
|
||||
(b"content-security-policy", b"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"),
|
||||
])
|
||||
if scope["path"].startswith("/api/"):
|
||||
headers.append((b"cache-control", b"no-store"))
|
||||
message = {**message, "headers": headers}
|
||||
await send(message)
|
||||
|
||||
hosts = request.headers.getlist("host")
|
||||
try:
|
||||
if len(hosts) != 1 or any(c in hosts[0] for c in "@/\\?# \t\r\n,"):
|
||||
raise ValueError
|
||||
parsed = urlsplit("http://" + hosts[0])
|
||||
host = normalize_host(parsed.hostname or "")
|
||||
if parsed.port is not None and not 1 <= parsed.port <= 65535:
|
||||
raise ValueError
|
||||
if host not in self.settings.trusted_hosts:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
await deny(400, "invalid_host", "请求主机不受信任")
|
||||
return
|
||||
|
||||
is_api = scope["path"] == "/api" or scope["path"].startswith("/api/")
|
||||
if is_api and request.method in _WRITES:
|
||||
origins = request.headers.getlist("origin")
|
||||
fetch_site = request.headers.get("sec-fetch-site", "")
|
||||
try:
|
||||
if fetch_site == "cross-site" or len(origins) > 1:
|
||||
raise ValueError
|
||||
if origins:
|
||||
origin = normalize_origin(origins[0])
|
||||
same_origin = normalize_origin(f"{scope['scheme']}://{hosts[0]}")
|
||||
if origin not in {same_origin, *self.settings.allowed_origins}:
|
||||
raise ValueError
|
||||
elif fetch_site not in {"", "none", "same-origin"}:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
await deny(403, "invalid_origin", "禁止跨站操作,请从当前工作台发起请求")
|
||||
return
|
||||
if is_api and scope["path"] not in _PUBLIC_PATHS and not self.sessions.authenticated(request):
|
||||
status = 401 if self.settings.credential else 403
|
||||
await deny(status, "authentication_required", "请先登录管理工作台" if status == 401 else "本机免密模式只允许本机访问")
|
||||
return
|
||||
if not is_api:
|
||||
await self.app(scope, receive, secure_send)
|
||||
return
|
||||
if len(scope.get("query_string", b"")) > 16_384:
|
||||
await deny(414, "query_too_large", "查询条件过长")
|
||||
return
|
||||
body_limit = self.settings.max_body_bytes
|
||||
if request.method == "POST" and _YIELDS_IMPORT_PATH.fullmatch(scope["path"]):
|
||||
# An 8 MiB file expands to about 10.7 MiB in base64, plus JSON metadata.
|
||||
body_limit = _YIELDS_IMPORT_BODY_BYTES
|
||||
lengths = request.headers.getlist("content-length")
|
||||
try:
|
||||
if len(lengths) > 1 or (lengths and (not lengths[0].isascii() or not lengths[0].isdecimal())):
|
||||
raise ValueError
|
||||
declared = int(lengths[0]) if lengths else None
|
||||
except ValueError:
|
||||
await deny(400, "invalid_length", "请求正文长度无效")
|
||||
return
|
||||
if declared is not None and declared > body_limit:
|
||||
await deny(413, "body_too_large", "请求正文超过允许大小")
|
||||
return
|
||||
if request.headers.get("content-encoding", "identity").lower() != "identity":
|
||||
await deny(415, "unsupported_encoding", "请求正文不支持压缩编码")
|
||||
return
|
||||
chunks, size = [], 0
|
||||
while True:
|
||||
part = await receive()
|
||||
if part["type"] == "http.disconnect":
|
||||
return
|
||||
chunk = part.get("body", b"")
|
||||
size += len(chunk)
|
||||
if size > body_limit:
|
||||
await deny(413, "body_too_large", "请求正文超过允许大小")
|
||||
return
|
||||
chunks.append(chunk)
|
||||
if not part.get("more_body", False):
|
||||
break
|
||||
if declared is not None and size != declared:
|
||||
await deny(400, "invalid_length", "请求正文长度与声明不符")
|
||||
return
|
||||
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||
if size and request.method in _WRITES and content_type != "application/json":
|
||||
await deny(415, "unsupported_media_type", "请使用 application/json 提交请求")
|
||||
return
|
||||
buffered = b"".join(chunks)
|
||||
delivered = False
|
||||
|
||||
async def replay():
|
||||
nonlocal delivered
|
||||
if not delivered:
|
||||
delivered = True
|
||||
return {"type": "http.request", "body": buffered, "more_body": False}
|
||||
return await receive()
|
||||
|
||||
await self.app(scope, replay, secure_send)
|
||||
|
||||
|
||||
class _Input(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class AccountInput(_Input):
|
||||
label: Annotated[StrictStr, Field(max_length=200)] = ""
|
||||
demo: StrictBool = True
|
||||
|
||||
|
||||
class ConfigInput(_Input):
|
||||
config: dict[str, Any]
|
||||
revision: Annotated[StrictInt, Field(ge=0)] | None = None
|
||||
|
||||
|
||||
class LoginInput(_Input):
|
||||
password: Annotated[StrictStr, Field(min_length=1, max_length=1024)]
|
||||
|
||||
|
||||
class UpdateInput(_Input):
|
||||
version: Annotated[StrictStr, Field(max_length=64)] | None = None
|
||||
|
||||
|
||||
def _no_file_paths(value: Any, depth: int = 0) -> None:
|
||||
if depth > 32:
|
||||
raise HTTPException(400, "请求内容嵌套过深")
|
||||
if isinstance(value, dict):
|
||||
for field, item in value.items():
|
||||
name = str(field).lower().replace("_", "").replace("-", "")
|
||||
if name in _FILE_KEYS:
|
||||
raise HTTPException(400, "不允许通过 API 指定服务器文件路径")
|
||||
if name == "filename" and (not isinstance(item, str) or re.search(r"[\\/:\x00]", item) or item.startswith(".")):
|
||||
raise HTTPException(400, "导入文件名必须是不含路径的名称")
|
||||
_no_file_paths(item, depth + 1)
|
||||
elif isinstance(value, list):
|
||||
for item in value:
|
||||
_no_file_paths(item, depth + 1)
|
||||
|
||||
|
||||
class _Assets(StaticFiles):
|
||||
async def get_response(self, path, scope):
|
||||
allowed = {".html", ".js", ".mjs", ".css", ".svg", ".png", ".jpg", ".jpeg", ".webp", ".ico", ".woff", ".woff2"}
|
||||
parts = path.replace("\\", "/").split("/")
|
||||
if any(part.startswith(".") for part in parts) or FilePath(path).suffix.lower() not in allowed:
|
||||
raise HTTPException(404, "静态资源不存在")
|
||||
return await super().get_response(path, scope)
|
||||
|
||||
|
||||
def create_app(data_dir=None, manager=None, config=None, updates=None) -> FastAPI:
|
||||
"""Create an application; injected collaborators retain their ownership."""
|
||||
if config is None:
|
||||
settings = WebConfig.from_env(**({"data_dir": data_dir} if data_dir is not None else {}))
|
||||
elif isinstance(config, WebConfig):
|
||||
settings = replace(config, data_dir=data_dir) if data_dir is not None else config
|
||||
elif isinstance(config, dict):
|
||||
values = dict(config)
|
||||
if data_dir is not None:
|
||||
values["data_dir"] = data_dir
|
||||
settings = WebConfig.from_env(**values)
|
||||
else:
|
||||
raise TypeError("config 必须是 WebConfig 或字典")
|
||||
sessions, redactor = _Sessions(settings), _Redactor(settings)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
owned = []
|
||||
try:
|
||||
if app.state.manager is None:
|
||||
from .service import WebManager
|
||||
settings.data_dir.mkdir(parents=True, exist_ok=True)
|
||||
app.state.manager = await run_in_threadpool(WebManager, settings.data_dir)
|
||||
owned.append(app.state.manager)
|
||||
if app.state.updates is None:
|
||||
from .updates import UpdateService
|
||||
app.state.updates = await run_in_threadpool(UpdateService, settings.data_dir, __version__)
|
||||
owned.append(app.state.updates)
|
||||
yield
|
||||
finally:
|
||||
failures = []
|
||||
try:
|
||||
for item in reversed(owned):
|
||||
close = getattr(item, "close", None)
|
||||
if close:
|
||||
try:
|
||||
if inspect.iscoroutinefunction(close):
|
||||
await close()
|
||||
else:
|
||||
await run_in_threadpool(close)
|
||||
except Exception:
|
||||
failures.append(True)
|
||||
finally:
|
||||
if manager is None:
|
||||
app.state.manager = None
|
||||
if updates is None:
|
||||
app.state.updates = None
|
||||
with sessions.lock:
|
||||
sessions.sessions.clear()
|
||||
sessions.failures.clear()
|
||||
with redactor.lock:
|
||||
redactor.secrets.clear()
|
||||
if failures:
|
||||
raise RuntimeError("Web 服务关闭未完成,请查看已脱敏日志") from None
|
||||
|
||||
app = FastAPI(title="牧羊人之心 Web 工作台", version=__version__, lifespan=lifespan,
|
||||
docs_url=None, redoc_url=None, openapi_url=None)
|
||||
app.state.manager, app.state.updates, app.state.config = manager, updates, settings
|
||||
app.add_middleware(_Boundary, settings=settings, sessions=sessions)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error(request, exc):
|
||||
return _error(422, "invalid_request", "请求字段或格式不正确,请检查输入")
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_error(request, exc):
|
||||
messages = {404: "请求的资源不存在", 405: "不支持此请求方法"}
|
||||
message = messages.get(exc.status_code, redactor.text(str(exc.detail)))
|
||||
return _error(exc.status_code, "request_rejected", message)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def internal_error(request, exc):
|
||||
return _error(500, "internal_error", "操作未完成,请查看已脱敏日志后重试")
|
||||
|
||||
def invoke(target, method, *args, **kwargs):
|
||||
if target is None:
|
||||
raise HTTPException(503, "服务尚未启动")
|
||||
try:
|
||||
return getattr(target, method)(*args, **kwargs)
|
||||
except HTTPException:
|
||||
raise
|
||||
except KeyError:
|
||||
raise HTTPException(404, "账号、任务或记录不存在") from None
|
||||
except NotImplementedError:
|
||||
raise HTTPException(501, "当前部署尚未支持此操作") from None
|
||||
except ValueError as exc:
|
||||
status = 409 if type(exc).__name__ == "RevisionConflict" else 400
|
||||
text = redactor.text(str(exc))
|
||||
message = text if re.search(r"[\u3400-\u9fff]", text) else "请求参数无效,请检查后重试"
|
||||
raise HTTPException(status, message) from None
|
||||
except RuntimeError as exc:
|
||||
text = redactor.text(str(exc))
|
||||
message = text if re.search(r"[\u3400-\u9fff]", text) else "当前状态无法执行此操作"
|
||||
raise HTTPException(409, message) from None
|
||||
except Exception:
|
||||
# Catch at the transport boundary so server access/error logs do not print secrets.
|
||||
raise HTTPException(500, "操作未完成,请查看已脱敏日志后重试") from None
|
||||
|
||||
def public(value, **kwargs):
|
||||
return redactor.public(value, **kwargs)
|
||||
|
||||
def public_error(value):
|
||||
if not value:
|
||||
return value
|
||||
if not isinstance(value, str) or "Traceback" in value or re.search(r"\n\s*File\s+[\"']", value):
|
||||
return "操作未完成,请查看已脱敏日志后重试"
|
||||
text = redactor.text(value)
|
||||
return text if re.search(r"[\u3400-\u9fff]", text) else "操作未完成,请查看已脱敏日志后重试"
|
||||
|
||||
def public_updates(value):
|
||||
from .updates import HOST_STATES, current_version_key, stable_version, valid_id
|
||||
if not isinstance(value, dict):
|
||||
raise HTTPException(500, "更新服务返回格式不正确")
|
||||
fields = ("current_version", "latest_version", "available", "checked_at", "release_url", "channel",
|
||||
"repository", "status", "message", "error", "can_apply")
|
||||
result = public({field: value[field] for field in fields if field in value})
|
||||
states = {"unchecked", "no_release", "up_to_date", "available", "check_failed", "unavailable", *HOST_STATES}
|
||||
if value.get("status") in states:
|
||||
result["status"] = value["status"]
|
||||
for field, validator in (("current_version", current_version_key), ("latest_version", stable_version)):
|
||||
if field in value:
|
||||
try:
|
||||
validator(value[field])
|
||||
except (ValueError, TypeError):
|
||||
result[field] = None
|
||||
else:
|
||||
result[field] = value[field]
|
||||
executor = value.get("executor")
|
||||
result["executor"] = public({field: executor[field] for field in
|
||||
("configured", "enabled", "auto_apply", "state", "heartbeat_at") if field in executor}) if isinstance(executor, dict) else None
|
||||
for field, allowed in (("request", ("version", "requested_at", "status")),
|
||||
("host_status", ("version", "status", "updated_at", "error"))):
|
||||
record = value.get(field)
|
||||
result[field] = None
|
||||
if not isinstance(record, dict) or not valid_id(record.get("request_id")) or record.get("status") not in HOST_STATES:
|
||||
continue
|
||||
try:
|
||||
stable_version(record.get("version"))
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
mapped = public({key: record[key] for key in allowed if key in record})
|
||||
# These validated control-plane fields are public updater metadata.
|
||||
mapped.update(request_id=record["request_id"], version=record["version"], status=record["status"])
|
||||
result[field] = mapped
|
||||
return result
|
||||
|
||||
def submit(account_id, operation, payload):
|
||||
if operation not in ACTIONS:
|
||||
raise HTTPException(404, "不支持此操作")
|
||||
_no_file_paths(payload)
|
||||
redactor.remember(payload)
|
||||
value = invoke(app.state.manager, "submit", account_id, operation, payload)
|
||||
return public_job(value)
|
||||
|
||||
def public_job(value):
|
||||
if not isinstance(value, dict) or value.get("status") not in _JOB_STATUSES:
|
||||
raise HTTPException(500, "后台任务返回格式不正确")
|
||||
result = {field: value.get(field) for field in ("id", "status", "operation", "result", "error")}
|
||||
result["error"] = public_error(result["error"])
|
||||
return public(result)
|
||||
|
||||
def public_summary(value):
|
||||
if not isinstance(value, dict):
|
||||
raise HTTPException(500, "账号状态返回格式不正确")
|
||||
result = {field: value.get(field) for field in ("id", "label", "connected", "demo", "running", "busy", "revision", "error")}
|
||||
result["error"] = public_error(result["error"])
|
||||
player = value.get("player")
|
||||
result["player"] = {field: player.get(field) for field in ("name", "level", "exp", "next_exp", "money", "ke", "ti")} if isinstance(player, dict) else None
|
||||
return public(result)
|
||||
|
||||
@app.get("/api/health")
|
||||
def health():
|
||||
return {"status": "ok", "version": __version__}
|
||||
|
||||
@app.get("/api/meta")
|
||||
def meta():
|
||||
update_status = invoke(app.state.updates, "status")
|
||||
result = public({"version": __version__, "gameVersion": GAME_VERSION,
|
||||
"access": {"mode": settings.access_mode, "password_required": bool(settings.credential)},
|
||||
"features": [*PAGES, "multi_account", "jobs", "config_autosave", "updates"]})
|
||||
result["updates"] = public_updates(update_status)
|
||||
return result
|
||||
|
||||
@app.get("/api/auth/status")
|
||||
def auth_status(request: Request):
|
||||
return {"required": bool(settings.credential), "authenticated": sessions.authenticated(request), "access_mode": settings.access_mode}
|
||||
|
||||
@app.post("/api/auth/login")
|
||||
def admin_login(request: Request, body: LoginInput):
|
||||
if not settings.credential:
|
||||
if not sessions.authenticated(request):
|
||||
raise HTTPException(403, "本机免密模式只允许本机访问")
|
||||
return {"required": False, "authenticated": True, "access_mode": "local"}
|
||||
token = sessions.login(request, body.password)
|
||||
response = JSONResponse({"required": True, "authenticated": True, "access_mode": "password"})
|
||||
response.set_cookie(COOKIE_NAME, token, max_age=settings.session_ttl, httponly=True,
|
||||
secure=settings.secure_cookie, samesite="strict", path="/api")
|
||||
return response
|
||||
|
||||
@app.post("/api/auth/logout")
|
||||
def admin_logout(request: Request):
|
||||
sessions.logout(request)
|
||||
response = JSONResponse({"authenticated": False})
|
||||
response.delete_cookie(COOKIE_NAME, path="/api", httponly=True, secure=settings.secure_cookie, samesite="strict")
|
||||
return response
|
||||
|
||||
@app.get("/api/schema")
|
||||
def get_schema():
|
||||
from .views import schema
|
||||
catalog = getattr(app.state.manager, "catalog", None)
|
||||
if catalog is None:
|
||||
from ranch_assistant.model import Catalog
|
||||
catalog = Catalog()
|
||||
return public(schema(catalog))
|
||||
|
||||
@app.get("/api/accounts")
|
||||
def list_accounts():
|
||||
return [public_summary(item) for item in invoke(app.state.manager, "list_accounts")]
|
||||
|
||||
@app.post("/api/accounts", status_code=201)
|
||||
def create_account(body: AccountInput):
|
||||
return public_summary(invoke(app.state.manager, "create_account", label=body.label, demo=body.demo))
|
||||
|
||||
@app.delete("/api/accounts/{account_id}", status_code=204)
|
||||
def remove_account(account_id: Identifier):
|
||||
invoke(app.state.manager, "remove_account", account_id)
|
||||
return Response(status_code=204)
|
||||
|
||||
@app.get("/api/accounts/{account_id}/status")
|
||||
def status(account_id: Identifier):
|
||||
return public_summary(invoke(app.state.manager, "status", account_id))
|
||||
|
||||
@app.get("/api/accounts/{account_id}/config")
|
||||
def get_config(account_id: Identifier):
|
||||
return public(invoke(app.state.manager, "get_config", account_id))
|
||||
|
||||
@app.put("/api/accounts/{account_id}/config")
|
||||
def set_config(account_id: Identifier, body: ConfigInput, response: Response):
|
||||
_no_file_paths(body.config)
|
||||
result = invoke(app.state.manager, "set_config", account_id, body.config, revision=body.revision)
|
||||
if isinstance(result, dict) and result.get("pending"):
|
||||
response.status_code = 202
|
||||
return public(result)
|
||||
|
||||
@app.get("/api/accounts/{account_id}/views/{page}")
|
||||
def view(account_id: Identifier, page: str, request: Request):
|
||||
if page not in PAGES:
|
||||
raise HTTPException(404, "页面不存在")
|
||||
params = dict(request.query_params)
|
||||
if "query" in params:
|
||||
if len(params) > 1:
|
||||
raise HTTPException(400, "JSON 查询条件不能与简单参数混用")
|
||||
try:
|
||||
query = json.loads(params["query"])
|
||||
except (ValueError, RecursionError):
|
||||
raise HTTPException(400, "页面查询条件不是有效 JSON") from None
|
||||
if not isinstance(query, dict):
|
||||
raise HTTPException(400, "页面查询条件必须是对象")
|
||||
else:
|
||||
query = params or None
|
||||
_no_file_paths(query)
|
||||
return public(invoke(app.state.manager, "view", account_id, page, query=query))
|
||||
|
||||
@app.post("/api/accounts/{account_id}/actions/{operation}", status_code=202)
|
||||
def action(account_id: Identifier, operation: str, payload: dict[str, Any] | None = None):
|
||||
return submit(account_id, operation, payload or {})
|
||||
|
||||
@app.get("/api/accounts/{account_id}/jobs/{job_id}")
|
||||
def job(account_id: Identifier, job_id: Identifier):
|
||||
return public_job(invoke(app.state.manager, "job", account_id, job_id))
|
||||
|
||||
@app.get("/api/accounts/{account_id}/logs")
|
||||
def logs(account_id: Identifier, after: Annotated[int, Query(ge=0)] = 0, debug: bool = False):
|
||||
return public(invoke(app.state.manager, "logs", account_id, after=after, debug=debug))
|
||||
|
||||
@app.get("/api/accounts/{account_id}/logs/{entry_id}")
|
||||
@app.get("/api/accounts/{account_id}/debug/{entry_id}")
|
||||
def log_detail(account_id: Identifier, entry_id: Annotated[int, Path(ge=1)]):
|
||||
method = "log_detail" if hasattr(app.state.manager, "log_detail") else "debug_entry"
|
||||
if not hasattr(app.state.manager, method):
|
||||
raise HTTPException(501, "当前运行时尚未提供单条调试详情")
|
||||
return public(invoke(app.state.manager, method, account_id, entry_id), trace=True)
|
||||
|
||||
@app.get("/api/accounts/{account_id}/config/export", status_code=202)
|
||||
def config_export(account_id: Identifier):
|
||||
return submit(account_id, "export_config", {})
|
||||
|
||||
@app.post("/api/accounts/{account_id}/config/import", status_code=202)
|
||||
def config_import(account_id: Identifier, payload: dict[str, Any]):
|
||||
# The REST upload accepts a portable document; the action layer uses {config: document}.
|
||||
wrapped = payload if "config" in payload else {"config": payload}
|
||||
return submit(account_id, "import_config", wrapped)
|
||||
|
||||
@app.get("/api/system/updates")
|
||||
def update_status():
|
||||
return public_updates(invoke(app.state.updates, "status"))
|
||||
|
||||
@app.post("/api/system/updates/check")
|
||||
def update_check():
|
||||
return public_updates(invoke(app.state.updates, "check"))
|
||||
|
||||
@app.post("/api/system/updates/apply", status_code=202)
|
||||
def update_apply(body: UpdateInput | None = None):
|
||||
version = body.version if body else None
|
||||
if version is not None and not re.fullmatch(r"v2\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)", version):
|
||||
raise HTTPException(400, "更新版本必须是正式的 v2.x.y 版本号,例如 v2.0.1")
|
||||
return public_updates(invoke(app.state.updates, "request_update", version))
|
||||
|
||||
static_dir = FilePath(__file__).resolve().parent / "static"
|
||||
|
||||
@app.get("/", include_in_schema=False)
|
||||
def index():
|
||||
index_path = static_dir / "index.html"
|
||||
if not index_path.is_file():
|
||||
raise HTTPException(503, "前端资源尚未准备完成")
|
||||
return FileResponse(index_path, media_type="text/html", headers={"Cache-Control": "no-cache"})
|
||||
|
||||
app.mount("/static", _Assets(directory=static_dir, check_dir=False, follow_symlink=False), name="static")
|
||||
return app
|
||||
@@ -0,0 +1,194 @@
|
||||
"""Web settings and password verification, without desktop imports or disk reads."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from dataclasses import dataclass, field
|
||||
import hashlib
|
||||
import hmac
|
||||
import ipaddress
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
from typing import Mapping
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
DEFAULT_DATA_DIR = Path(__file__).resolve().parents[1] / "local_state" / "ranch_web"
|
||||
DEFAULT_HOST = "127.0.0.1"
|
||||
DEFAULT_PORT = 8765
|
||||
COOKIE_NAME = "ranch_web_session"
|
||||
_HASH_PREFIX = "pbkdf2_sha256$"
|
||||
|
||||
|
||||
def is_loopback(host: str) -> bool:
|
||||
if host.lower() == "localhost":
|
||||
return True
|
||||
try:
|
||||
address = ipaddress.ip_address(host)
|
||||
if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped:
|
||||
return address.ipv4_mapped.is_loopback
|
||||
return address.is_loopback
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def normalize_host(value: str) -> str:
|
||||
"""Accept a hostname / IP literal, never URLs, ports or wildcard patterns."""
|
||||
candidate = value.strip().lower()
|
||||
if candidate.startswith("[") and candidate.endswith("]"):
|
||||
candidate = candidate[1:-1]
|
||||
try:
|
||||
return str(ipaddress.ip_address(candidate))
|
||||
except ValueError:
|
||||
pass
|
||||
if len(candidate) > 253 or not re.fullmatch(
|
||||
r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*",
|
||||
candidate,
|
||||
):
|
||||
raise ValueError("允许的主机必须是明确的域名或 IP 地址,不能包含通配符或端口")
|
||||
return candidate
|
||||
|
||||
|
||||
def normalize_origin(value: str) -> str:
|
||||
parsed = urlsplit(value)
|
||||
if (
|
||||
parsed.scheme not in {"http", "https"}
|
||||
or not parsed.hostname
|
||||
or parsed.username is not None
|
||||
or parsed.password is not None
|
||||
or parsed.path not in {"", "/"}
|
||||
or parsed.query
|
||||
or parsed.fragment
|
||||
):
|
||||
raise ValueError("允许的来源必须是明确的 http 或 https 来源")
|
||||
host = normalize_host(parsed.hostname)
|
||||
try:
|
||||
port = parsed.port
|
||||
except ValueError:
|
||||
raise ValueError("允许的来源端口无效") from None
|
||||
if port is not None and not 1 <= port <= 65535:
|
||||
raise ValueError("允许的来源端口无效")
|
||||
authority = f"[{host}]" if ":" in host else host
|
||||
if port is not None and port != (443 if parsed.scheme == "https" else 80):
|
||||
authority += f":{port}"
|
||||
return f"{parsed.scheme}://{authority}"
|
||||
|
||||
|
||||
def _hash_parts(encoded: str) -> tuple[int, bytes, bytes]:
|
||||
try:
|
||||
algorithm, raw_iterations, salt, digest = encoded.split("$")
|
||||
iterations = int(raw_iterations)
|
||||
expected = base64.b64decode(digest, validate=True)
|
||||
if (
|
||||
algorithm != "pbkdf2_sha256"
|
||||
or not 100_000 <= iterations <= 2_000_000
|
||||
or not 8 <= len(salt) <= 128
|
||||
or len(expected) != 32
|
||||
):
|
||||
raise ValueError
|
||||
return iterations, salt.encode("utf-8"), expected
|
||||
except (ValueError, TypeError):
|
||||
raise ValueError("管理密码哈希格式无效") from None
|
||||
|
||||
|
||||
def hash_password(password: str, *, iterations: int = 600_000) -> str:
|
||||
if not password or len(password) > 1024 or not 100_000 <= iterations <= 2_000_000:
|
||||
raise ValueError("密码或哈希迭代次数无效")
|
||||
salt = secrets.token_hex(16)
|
||||
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt.encode(), iterations)
|
||||
return f"{_HASH_PREFIX}{iterations}${salt}${base64.b64encode(digest).decode('ascii')}"
|
||||
|
||||
|
||||
def verify_password(password: str, configured: str) -> bool:
|
||||
if configured.startswith(_HASH_PREFIX):
|
||||
iterations, salt, expected = _hash_parts(configured)
|
||||
candidate = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
|
||||
return hmac.compare_digest(candidate, expected)
|
||||
# Equal-length digests also permit non-ASCII passwords with compare_digest.
|
||||
return hmac.compare_digest(
|
||||
hashlib.sha256(password.encode("utf-8")).digest(),
|
||||
hashlib.sha256(configured.encode("utf-8")).digest(),
|
||||
)
|
||||
|
||||
|
||||
def _env_bool(value: str, name: str) -> bool:
|
||||
normalized = value.strip().lower()
|
||||
if normalized in {"1", "true", "yes", "on"}:
|
||||
return True
|
||||
if normalized in {"0", "false", "no", "off", ""}:
|
||||
return False
|
||||
raise ValueError(f"{name} 必须是布尔值")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WebConfig:
|
||||
host: str = DEFAULT_HOST
|
||||
port: int = DEFAULT_PORT
|
||||
data_dir: Path = DEFAULT_DATA_DIR
|
||||
password: str = field(default="", repr=False)
|
||||
password_hash: str = field(default="", repr=False)
|
||||
allowed_hosts: tuple[str, ...] = ()
|
||||
allowed_origins: tuple[str, ...] = ()
|
||||
secure_cookie: bool = False
|
||||
session_ttl: int = 43_200
|
||||
max_body_bytes: int = 1_048_576
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "host", normalize_host(self.host))
|
||||
object.__setattr__(self, "data_dir", Path(self.data_dir).expanduser().absolute())
|
||||
object.__setattr__(self, "allowed_hosts", tuple(normalize_host(h) for h in self.allowed_hosts))
|
||||
object.__setattr__(self, "allowed_origins", tuple(normalize_origin(o) for o in self.allowed_origins))
|
||||
if type(self.port) is not int or not 1 <= self.port <= 65535:
|
||||
raise ValueError("监听端口必须在 1–65535 之间")
|
||||
if type(self.session_ttl) is not int or not 60 <= self.session_ttl <= 2_592_000:
|
||||
raise ValueError("管理会话有效期必须在 60–2592000 秒之间")
|
||||
if type(self.max_body_bytes) is not int or not 1024 <= self.max_body_bytes <= 16_777_216:
|
||||
raise ValueError("请求正文上限必须在 1 KiB–16 MiB 之间")
|
||||
if self.password and self.password_hash:
|
||||
raise ValueError("管理密码和管理密码哈希只能配置一个")
|
||||
if self.password_hash:
|
||||
_hash_parts(self.password_hash)
|
||||
elif self.password.startswith(_HASH_PREFIX):
|
||||
_hash_parts(self.password)
|
||||
if not is_loopback(self.host) and not self.credential:
|
||||
raise ValueError("非本机绑定必须设置 RANCH_WEB_PASSWORD 或 RANCH_WEB_PASSWORD_HASH")
|
||||
# Public proxy hostnames must never silently enable the local password bypass.
|
||||
if not self.credential and any(not is_loopback(h) for h in self.allowed_hosts):
|
||||
raise ValueError("允许远程域名访问时必须设置 RANCH_WEB_PASSWORD 或 RANCH_WEB_PASSWORD_HASH")
|
||||
if not self.credential and any(not is_loopback(urlsplit(o).hostname or "") for o in self.allowed_origins):
|
||||
raise ValueError("允许远程来源访问时必须设置管理密码")
|
||||
|
||||
@property
|
||||
def credential(self) -> str:
|
||||
return self.password_hash or self.password
|
||||
|
||||
@property
|
||||
def access_mode(self) -> str:
|
||||
return "password" if self.credential else "local"
|
||||
|
||||
@property
|
||||
def trusted_hosts(self) -> frozenset[str]:
|
||||
hosts = {"localhost", "127.0.0.1", "::1", *self.allowed_hosts}
|
||||
if self.host not in {"0.0.0.0", "::"}:
|
||||
hosts.add(self.host)
|
||||
return frozenset(hosts)
|
||||
|
||||
@classmethod
|
||||
def from_env(cls, env: Mapping[str, str] | None = None, **overrides) -> WebConfig:
|
||||
values = os.environ if env is None else env
|
||||
settings = {
|
||||
"host": values.get("RANCH_WEB_HOST", DEFAULT_HOST),
|
||||
"port": int(values.get("RANCH_WEB_PORT", DEFAULT_PORT)),
|
||||
"data_dir": values.get("RANCH_WEB_DATA_DIR", DEFAULT_DATA_DIR),
|
||||
"password": values.get("RANCH_WEB_PASSWORD", ""),
|
||||
"password_hash": values.get("RANCH_WEB_PASSWORD_HASH", ""),
|
||||
"allowed_hosts": tuple(h.strip() for h in values.get("RANCH_WEB_ALLOWED_HOSTS", "").split(",") if h.strip()),
|
||||
"allowed_origins": tuple(o.strip() for o in values.get("RANCH_WEB_ALLOWED_ORIGINS", "").split(",") if o.strip()),
|
||||
"secure_cookie": _env_bool(values.get("RANCH_WEB_SECURE_COOKIE", ""), "RANCH_WEB_SECURE_COOKIE"),
|
||||
"session_ttl": int(values.get("RANCH_WEB_SESSION_TTL", 43_200)),
|
||||
"max_body_bytes": int(values.get("RANCH_WEB_MAX_BODY_BYTES", 1_048_576)),
|
||||
}
|
||||
settings.update(overrides)
|
||||
return cls(**settings)
|
||||
@@ -0,0 +1,255 @@
|
||||
"""Validated, portable strategy configuration shared by Web controls and workers.
|
||||
|
||||
No running switch or account/session information belongs in this document.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from dataclasses import asdict
|
||||
import math
|
||||
import re
|
||||
|
||||
from ranch_assistant.model import EggRule, Policy
|
||||
from ranch_assistant.daily import DailyPolicy
|
||||
from ranch_assistant.quests import QuestPolicy
|
||||
from ranch_assistant.sweeping import SweepPolicy
|
||||
from ranch_assistant.progression import ProgressionPolicy
|
||||
from ranch_assistant.exploration import ExplorePolicy
|
||||
from ranch_assistant import policy_io
|
||||
|
||||
|
||||
POLICY_CLASSES = {
|
||||
"policy": Policy, "quest_policy": QuestPolicy, "daily_policy": DailyPolicy,
|
||||
"sweep_policy": SweepPolicy, "progression_policy": ProgressionPolicy,
|
||||
"explore_policy": ExplorePolicy,
|
||||
}
|
||||
DAILY_CHOICES = ("gift", "check", "loop", "vip", "mail")
|
||||
MAX_COUNT = 1_000_000_000
|
||||
IDENTIFIER = re.compile(r"[A-Za-z0-9_]{1,64}\Z")
|
||||
|
||||
|
||||
def default_config():
|
||||
value = {key: asdict(cls()) for key, cls in POLICY_CLASSES.items()}
|
||||
# The current desktop configures individual eggs and always uses its
|
||||
# experimental battle simulator. Keep those defaults, not legacy widgets.
|
||||
value["policy"]["manual_eggs"] = True
|
||||
value["progression_policy"]["battle_mode"] = "experimental"
|
||||
return value | {"interval": 30, "overrides": {}, "yield_stars": [1, 2, 3, 4, 5],
|
||||
"log_visible": True, "log_sizes": [420, 140]}
|
||||
|
||||
|
||||
def _object(value, label, allowed=None):
|
||||
if not isinstance(value, dict) or any(type(key) is not str for key in value):
|
||||
raise ValueError(label + "必须是对象,字段名必须是字符串")
|
||||
if allowed is not None and set(value) - set(allowed):
|
||||
raise ValueError(label + "含未知或不允许的字段")
|
||||
return value
|
||||
|
||||
|
||||
def _int(value, label, low=0, high=MAX_COUNT):
|
||||
if type(value) is not int or not low <= value <= high:
|
||||
raise ValueError(f"{label}须为 {low} 至 {high} 的整数")
|
||||
return value
|
||||
|
||||
|
||||
def _number(value, label, high=MAX_COUNT):
|
||||
if type(value) not in (int, float) or not math.isfinite(value) or not 0 <= value <= high:
|
||||
raise ValueError(label + "须为范围内的非负有限数值")
|
||||
|
||||
|
||||
def _id(key, label):
|
||||
if type(key) is not str or not key.isascii() or not key.isdigit() or int(key) <= 0:
|
||||
raise ValueError(label + "须使用正整数编号")
|
||||
|
||||
|
||||
def _counts(value, label, *, priority=False):
|
||||
_object(value, label)
|
||||
result = {}
|
||||
for key, count in value.items():
|
||||
_id(key, label)
|
||||
_int(count, label, 1 if priority else 0, 999 if priority else MAX_COUNT)
|
||||
result[str(int(key))] = count
|
||||
return result
|
||||
|
||||
|
||||
def _choice(value, options, label):
|
||||
if value not in options:
|
||||
raise ValueError(label + "选项无效")
|
||||
|
||||
|
||||
def _section(value, defaults, label):
|
||||
_object(value, label, defaults)
|
||||
result = deepcopy(defaults)
|
||||
result.update(deepcopy(value))
|
||||
for key, default in defaults.items():
|
||||
actual = result[key]
|
||||
if type(default) is bool:
|
||||
if type(actual) is not bool:
|
||||
raise ValueError(label + "." + key + "须为布尔值")
|
||||
elif label == "policy" and key in ("coins_per_exp", "min_gold_per_hour", "min_exp_per_hour"):
|
||||
_number(actual, label + "." + key)
|
||||
elif type(default) is int:
|
||||
_int(actual, label + "." + key)
|
||||
elif type(default) is float:
|
||||
_number(actual, label + "." + key)
|
||||
elif type(actual) is not type(default):
|
||||
raise ValueError(label + "." + key + "类型错误")
|
||||
return result
|
||||
|
||||
|
||||
def validate_config(config):
|
||||
"""Fill absent defaults and reject unknown paths *before* core coercion.
|
||||
|
||||
A partial HTTP PUT is merged with the saved config by the account worker;
|
||||
passing a partial document here fills from defaults, not previous state.
|
||||
"""
|
||||
defaults = default_config()
|
||||
_object(config, "配置", defaults)
|
||||
result = deepcopy(defaults)
|
||||
for key, cls in POLICY_CLASSES.items():
|
||||
result[key] = _section(config.get(key, {}), defaults[key], key)
|
||||
p = result["policy"]
|
||||
# read_policy() in the current desktop always enables per-species rules.
|
||||
# Normalize a validated legacy False so importing hidden old settings can
|
||||
# never authorize incubation of eggs left unchecked in the Web controls.
|
||||
p["manual_eggs"] = True
|
||||
_choice(p["strategy"], ("wiki", "gold", "experience", "keep"), "培育策略")
|
||||
_choice(p["egg_order"], ("shortest", "longest", "gold", "experience"), "蛋排序")
|
||||
for key, low, high in (("protect_star", 1, 6), ("protect_quality", 1, 6),
|
||||
("hatch_max_star", 1, 5), ("buy_batch", 1, 100),
|
||||
("egg_stock", 1, 1000), ("target_level", 1, 999)):
|
||||
_int(p[key], key, low, high)
|
||||
_number(p["coins_per_exp"], "金币经验比", 10000)
|
||||
for key in ("min_gold_per_hour", "min_exp_per_hour"):
|
||||
_number(p[key], key, 1_000_000)
|
||||
if not IDENTIFIER.fullmatch(p["market_id"]):
|
||||
raise ValueError("默认市场编号无效")
|
||||
if any(type(key) is not int or key <= 0 for key in p["reserved_types"]):
|
||||
raise ValueError("额外保留魔物须为正整数编号列表")
|
||||
p["reserved_types"] = list(dict.fromkeys(p["reserved_types"]))
|
||||
for key in ("reserved_eggs", "feed_targets", "gift_targets", "breakthrough_targets"):
|
||||
p[key] = _counts(p[key], key, priority=key.endswith("targets"))
|
||||
_object(p["egg_rules"], "魔物蛋规则")
|
||||
egg_defaults = asdict(EggRule())
|
||||
for key, raw in p["egg_rules"].items():
|
||||
_id(key, "魔物蛋")
|
||||
rule = _section(raw, egg_defaults, "魔物蛋规则")
|
||||
if rule["market_id"] and not IDENTIFIER.fullmatch(rule["market_id"]):
|
||||
raise ValueError("补货市场编号无效")
|
||||
p["egg_rules"][key] = asdict(EggRule(**rule))
|
||||
_object(p["gift_items"], "赠礼物品")
|
||||
for key, raw in p["gift_items"].items():
|
||||
_id(key, "赠礼物品")
|
||||
p["gift_items"][key] = _section(raw, {"enabled": False, "reserve": 0}, "赠礼物品")
|
||||
for section in ("quest_policy", "progression_policy"):
|
||||
result[section]["item_reserves"] = _counts(result[section]["item_reserves"], "交付保留物品")
|
||||
q = result["quest_policy"]
|
||||
_int(q["city"], "委托城市", 0, 999)
|
||||
daily = result["daily_policy"]
|
||||
if any(type(key) is not str or key not in DAILY_CHOICES for key in daily["selected"]):
|
||||
raise ValueError("每日领取项目无效")
|
||||
daily["selected"] = list(dict.fromkeys(daily["selected"]))
|
||||
sweep = result["sweep_policy"]
|
||||
_object(sweep["rules"], "刷图规则")
|
||||
for key, raw in sweep["rules"].items():
|
||||
if not IDENTIFIER.fullmatch(key):
|
||||
raise ValueError("关卡编号无效")
|
||||
rule = _section(raw, {"enabled": False, "level": "3", "limit": 3}, "刷图规则")
|
||||
_choice(rule["level"], ("1", "2", "3"), "难度")
|
||||
_int(rule["limit"], "本日上限", 0, 999)
|
||||
sweep["rules"][key] = rule
|
||||
for section in ("sweep_policy", "progression_policy"):
|
||||
_choice(result[section]["team"], ("teamA", "teamB", "teamC"), "战队")
|
||||
_int(result["progression_policy"]["stop_after_loss"], "连续失败停止次数", 1, 999)
|
||||
_object(result["explore_policy"]["teams"], "探险队伍")
|
||||
for key, raw in result["explore_policy"]["teams"].items():
|
||||
_id(key, "探险队伍")
|
||||
rule = _section(raw, {"enabled": False, "area": "", "monsters": []}, "探险队伍")
|
||||
for mid in rule["monsters"]:
|
||||
_int(mid, "探险魔物编号", 1)
|
||||
result["explore_policy"]["teams"][key] = rule
|
||||
for key, cls in POLICY_CLASSES.items():
|
||||
try:
|
||||
result[key] = asdict(cls(**result[key]))
|
||||
except (TypeError, AttributeError, KeyError) as exc:
|
||||
raise ValueError(key + "配置格式错误") from exc
|
||||
# Current desktop forces the hidden legacy selector to its simulator.
|
||||
# Validate the supplied mode first so unknown values are still rejected.
|
||||
result["progression_policy"]["battle_mode"] = "experimental"
|
||||
interval = config.get("interval", defaults["interval"])
|
||||
if type(interval) is not int or interval not in (30, 60, 120, 300):
|
||||
raise ValueError("随机刷新间隔须为30、60、120或300秒")
|
||||
result["interval"] = interval
|
||||
stars = config.get("yield_stars", defaults["yield_stars"])
|
||||
if not isinstance(stars, list) or any(type(star) is not int or star not in range(1, 6) for star in stars):
|
||||
raise ValueError("收益星级筛选无效")
|
||||
result["yield_stars"] = list(dict.fromkeys(stars))
|
||||
overrides = _object(config.get("overrides", {}), "收益资料")
|
||||
result["overrides"] = deepcopy(overrides)
|
||||
for key, row in overrides.items():
|
||||
_id(key, "收益魔物")
|
||||
_object(row, "收益资料", ("sell_money", "sell_exp", "time_total"))
|
||||
for field, number in row.items():
|
||||
_number(number, "收益资料." + field)
|
||||
visible = config.get("log_visible", True)
|
||||
if type(visible) is not bool:
|
||||
raise ValueError("日志显示开关须为布尔值")
|
||||
result["log_visible"] = visible
|
||||
sizes = config.get("log_sizes", defaults["log_sizes"])
|
||||
if not isinstance(sizes, list) or len(sizes) != 2:
|
||||
raise ValueError("日志分隔高度须为两个整数")
|
||||
for size in sizes:
|
||||
_int(size, "日志高度", 0, 100000)
|
||||
if not sum(sizes):
|
||||
raise ValueError("日志分隔高度不能同时为0")
|
||||
result["log_sizes"] = list(sizes)
|
||||
return result
|
||||
|
||||
|
||||
def apply_config(engine, config):
|
||||
value = validate_config(config)
|
||||
policies = {key: cls(**deepcopy(value[key])) for key, cls in POLICY_CLASSES.items()}
|
||||
for key, policy in policies.items():
|
||||
setattr(engine, key, policy)
|
||||
engine.catalog.overrides = deepcopy(value["overrides"])
|
||||
return value
|
||||
|
||||
|
||||
def export_config(config, snapshot=None):
|
||||
value = policy_io.portable_config(validate_config(config), snapshot)
|
||||
value["assistantVersion"] = "2.0.0.dev1"
|
||||
return value
|
||||
|
||||
|
||||
def import_config(value, snapshot=None):
|
||||
allowed = {"format", "schema", "assistantVersion", "gameVersion", "policy", "targetSpecies",
|
||||
"quest_policy", "daily_policy", "sweep_policy", "progression_policy", "explore_policy",
|
||||
"interval", "overrides", "yield_stars"}
|
||||
_object(value, "策略导入文件", allowed)
|
||||
value = deepcopy(value)
|
||||
# Legacy desktop bundles sometimes stored difficulty as an integer.
|
||||
rules = (value.get("sweep_policy") or {}).get("rules", {}) if isinstance(value.get("sweep_policy", {}), dict) else {}
|
||||
if isinstance(rules, dict):
|
||||
for rule in rules.values():
|
||||
if isinstance(rule, dict) and type(rule.get("level")) is int and rule["level"] in (1, 2, 3):
|
||||
rule["level"] = str(rule["level"])
|
||||
# Validate source policy too: core's legacy loader intentionally coerces
|
||||
# several values. Web imports must reject ambiguous booleans and secrets.
|
||||
validate_config({key: raw for key, raw in value.items()
|
||||
if key in default_config() and key != "explore_policy"})
|
||||
targets = _object(value.get("targetSpecies", {}), "培养种类", ("feed", "gift", "breakthrough"))
|
||||
for rules in targets.values():
|
||||
if not isinstance(rules, list):
|
||||
raise ValueError("培养种类必须是列表")
|
||||
for rule in rules:
|
||||
_object(rule, "培养种类规则", ("typeId", "priority"))
|
||||
if not isinstance(rule.get("typeId"), str):
|
||||
raise ValueError("培养种类编号无效")
|
||||
if rule["typeId"]:
|
||||
_id(rule["typeId"], "培养种类")
|
||||
_int(rule.get("priority"), "培养优先级", 1, 999)
|
||||
try:
|
||||
loaded = policy_io.import_config(deepcopy(value), snapshot)
|
||||
except (TypeError, KeyError, AttributeError) as exc:
|
||||
raise ValueError("策略文件格式错误") from exc
|
||||
return validate_config(loaded)
|
||||
@@ -0,0 +1,5 @@
|
||||
fastapi>=0.162.2,<1
|
||||
uvicorn>=0.54.0,<1
|
||||
requests>=2.32,<3
|
||||
cryptography>=43
|
||||
openpyxl>=3.1,<4
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Desktop scheduling semantics without Qt timers or concurrent Engine access."""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
FAST_KINDS = ("hatch", "gift", "explore", "breakthrough")
|
||||
|
||||
|
||||
class AccountSchedule:
|
||||
"""Deadlines belong to one worker and are inspected only on its thread."""
|
||||
|
||||
def __init__(self, *, clock=time.monotonic, uniform=random.uniform):
|
||||
self.clock, self.uniform = clock, uniform
|
||||
self.next_poll = math.inf
|
||||
self.next_fast = {kind: math.inf for kind in FAST_KINDS}
|
||||
self.monitoring = False
|
||||
self.last_maintenance_error = {}
|
||||
|
||||
def monitor(self, enabled=True):
|
||||
self.monitoring = bool(enabled)
|
||||
self.next_poll = self.clock() if enabled else math.inf
|
||||
|
||||
def stop(self):
|
||||
for kind in FAST_KINDS:
|
||||
self.next_fast[kind] = math.inf
|
||||
|
||||
def poll_finished(self, config):
|
||||
self.next_poll = self.clock() + self.uniform(0, config.get("interval", 30))
|
||||
|
||||
def maintenance_failed(self, kind):
|
||||
self.last_maintenance_error[kind] = self.clock()
|
||||
|
||||
def arm(self, engine, config, running, plans=(), *, completed=None):
|
||||
if completed in self.next_fast:
|
||||
self.next_fast[completed] = math.inf
|
||||
snapshot = engine.snapshot
|
||||
if not self.monitoring or not running or snapshot is None:
|
||||
self.stop()
|
||||
return
|
||||
now = self.clock()
|
||||
policy = config.get("policy", {})
|
||||
pending = bool(engine._progression_pending() or engine.explore_planner.pending(snapshot) or engine._breakthrough_pending)
|
||||
delays = {}
|
||||
if not pending:
|
||||
if policy.get("enabled") and policy.get("fill") and engine.pending_hatches:
|
||||
delays["hatch"] = self.uniform(1, 2)
|
||||
ready_at = engine.gift_planner.next_ready_at
|
||||
if policy.get("gift_enabled") and ready_at is not None:
|
||||
delays["gift"] = max(0, ready_at - snapshot.now)
|
||||
if any(action.path and (action.kind == "explore_finish" or action.kind == "explore_start"
|
||||
and config.get("explore_policy", {}).get("enabled")) for action in plans):
|
||||
delays["explore"] = 1.0
|
||||
for team in snapshot.raw.get("exploreTeams") or []:
|
||||
if isinstance(team, dict) and team.get("status") in (1, "1"):
|
||||
remaining = engine.explore_planner.remaining(snapshot, team)
|
||||
if remaining is not None:
|
||||
delays["explore"] = min(delays.get("explore", math.inf), max(1.0, remaining + 1))
|
||||
if policy.get("breakthrough_targets") and any(action.path and action.kind in ("potential", "breakthrough") for action in plans):
|
||||
delays["breakthrough"] = 1.0
|
||||
for kind in FAST_KINDS:
|
||||
if kind not in delays:
|
||||
self.next_fast[kind] = math.inf
|
||||
elif self.next_fast[kind] == math.inf:
|
||||
self.next_fast[kind] = now + delays[kind]
|
||||
|
||||
def due(self, engine, config, running):
|
||||
now = self.clock()
|
||||
|
||||
def allowed(kind):
|
||||
return now - self.last_maintenance_error.get(kind, -math.inf) >= 30
|
||||
|
||||
connected = not engine.demo and engine.client is not None and engine.snapshot is not None
|
||||
if connected and engine.heartbeat_enabled and now - engine.last_heartbeat >= 240 and allowed("heartbeat"):
|
||||
return "heartbeat"
|
||||
if connected and self.monitoring and engine.pending_recovery_due() and allowed("reconcile"):
|
||||
return "reconcile"
|
||||
if connected and engine.heartbeat_enabled and engine.master_sync_due() and allowed("master_sync"):
|
||||
return "master_sync"
|
||||
if connected and engine.heartbeat_enabled and engine.growth_sync_due() and allowed("growth_sync"):
|
||||
return "growth_sync"
|
||||
if self.monitoring and running and now >= self.next_fast["hatch"]:
|
||||
return "hatch"
|
||||
if self.monitoring and now >= self.next_poll:
|
||||
return "poll"
|
||||
if self.monitoring and running:
|
||||
for kind in ("gift", "explore", "breakthrough"):
|
||||
if now >= self.next_fast[kind]:
|
||||
return kind
|
||||
return None
|
||||
|
||||
|
||||
class Scheduler:
|
||||
"""Ask idle account queues to tick; never call an Engine from this thread."""
|
||||
|
||||
def __init__(self, workers, *, interval=0.2):
|
||||
self.workers = workers
|
||||
self.interval = interval
|
||||
self.closed = threading.Event()
|
||||
self.thread = threading.Thread(target=self._run, name="ranch-web-scheduler", daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
def _run(self):
|
||||
while not self.closed.wait(self.interval):
|
||||
for worker in self.workers():
|
||||
worker.request_tick()
|
||||
|
||||
def close(self):
|
||||
self.closed.set()
|
||||
if threading.current_thread() is not self.thread:
|
||||
self.thread.join(timeout=2)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,63 @@
|
||||
export class ApiError extends Error {
|
||||
constructor(message, status, detail) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.detail = detail;
|
||||
}
|
||||
}
|
||||
|
||||
function errorMessage(data, status) {
|
||||
if (typeof data?.detail === 'string') return data.detail;
|
||||
if (typeof data?.error === 'string') return data.error;
|
||||
if (typeof data?.message === 'string') return data.message;
|
||||
if (Array.isArray(data?.detail)) return data.detail.map(item => `${(item.loc || []).slice(1).join('.')}: ${item.msg}`).join(';');
|
||||
return `请求未完成(HTTP ${status})`;
|
||||
}
|
||||
|
||||
export async function request(path, {method = 'GET', body, signal, blob = false} = {}) {
|
||||
const headers = {Accept: blob ? '*/*' : 'application/json'};
|
||||
if (body !== undefined && !(body instanceof FormData)) headers['Content-Type'] = 'application/json';
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(path, {method, credentials: 'same-origin', cache: 'no-store', headers, signal,
|
||||
body: body === undefined ? undefined : body instanceof FormData ? body : JSON.stringify(body)});
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') throw error;
|
||||
throw new ApiError('无法连接 Web 服务,请检查服务是否仍在运行。', 0);
|
||||
}
|
||||
if (response.status === 401 && !path.startsWith('/api/auth/')) window.dispatchEvent(new CustomEvent('auth-required'));
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null);
|
||||
throw new ApiError(errorMessage(data, response.status), response.status, data);
|
||||
}
|
||||
if (blob) return response.blob();
|
||||
if (response.status === 204) return null;
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export const accountURL = id => `/api/accounts/${encodeURIComponent(id)}`;
|
||||
export const api = {
|
||||
auth: () => request('/api/auth/status'),
|
||||
login: password => request('/api/auth/login', {method: 'POST', body: {password}}),
|
||||
logout: () => request('/api/auth/logout', {method: 'POST', body: {}}),
|
||||
meta: () => request('/api/meta'),
|
||||
schema: () => request('/api/schema'),
|
||||
accounts: () => request('/api/accounts'),
|
||||
create: (label, demo) => request('/api/accounts', {method: 'POST', body: {label, demo}}),
|
||||
remove: id => request(accountURL(id), {method: 'DELETE'}),
|
||||
status: id => request(`${accountURL(id)}/status`),
|
||||
config: id => request(`${accountURL(id)}/config`),
|
||||
save: (id, config, revision) => request(`${accountURL(id)}/config`, {method: 'PUT', body: {config, revision}}),
|
||||
view: (id, page, query = {}) => request(`${accountURL(id)}/views/${encodeURIComponent(page)}?query=${encodeURIComponent(JSON.stringify(query))}`),
|
||||
action: (id, operation, payload = {}) => request(`${accountURL(id)}/actions/${encodeURIComponent(operation)}`, {method: 'POST', body: payload}),
|
||||
job: (id, job) => request(`${accountURL(id)}/jobs/${encodeURIComponent(job)}`),
|
||||
logs: (id, after, debug) => request(`${accountURL(id)}/logs?after=${encodeURIComponent(after)}&debug=${debug}`),
|
||||
debugEntry: (id, entry) => request(`${accountURL(id)}/debug/${encodeURIComponent(entry)}`),
|
||||
exportConfig: id => request(`${accountURL(id)}/config/export`),
|
||||
importConfig: (id, config) => request(`${accountURL(id)}/config/import`, {method: 'POST', body: config}),
|
||||
health: options => request('/api/health', options),
|
||||
updates: options => request('/api/system/updates', options),
|
||||
checkUpdates: options => request('/api/system/updates/check', {...options, method: 'POST', body: {}}),
|
||||
applyUpdate: (version, options) => request('/api/system/updates/apply', {...options, method: 'POST', body: version ? {version} : {}}),
|
||||
};
|
||||
@@ -0,0 +1,511 @@
|
||||
import {api, request} from './api.js';
|
||||
import {el, $, $$, clone, getPath, setPath, pathKey, textValue, number, chinaTime, download, csvBlob, optionsList, detailsList, tabKeys} from './dom.js';
|
||||
import {PageView, PAGES} from './pages.js';
|
||||
import {notice, dialog, confirm, filePicker, fileBase64} from './ui.js';
|
||||
|
||||
const state = {accounts:new Map(),active:null,schema:null,meta:null,ready:false,polling:false,seq:0};
|
||||
const current = () => state.accounts.get(state.active);
|
||||
const currentPage = () => { const account=current(); return account?.pages.get(account.page); };
|
||||
const terminal = new Set(['succeeded','failed','cancelled']);
|
||||
const jobLabels = {queued:'排队中',running:'执行中',succeeded:'已完成',failed:'失败',cancelled:'已取消'};
|
||||
const operationLabels = {login:'登录',enter_server:'进入区服',restore_session:'恢复会话',refresh:'刷新 / 预览',start:'开启策略',stop:'停止策略',set_config:'保存配置',import_config:'导入策略',import_yields:'导入收益',claim_daily:'领取每日奖励',quote_expansion:'读取扩建费用',expand:'扩建',sell:'派遣',feed:'喂养',lock:'锁定',unlock:'解锁'};
|
||||
|
||||
function makeAccount(summary) {
|
||||
return {id:summary.id,summary,config:null,revision:null,edits:new Map(),pages:new Map(),page:'login',jobs:new Map(),savePromise:null,saveError:null,
|
||||
logs:{entries:[],next:0,debug:false,loading:false},loadingConfig:false};
|
||||
}
|
||||
|
||||
function setStatus(message) { $('#status-text').textContent=message; $('#status-text').title=message; }
|
||||
function error(error) { notice(error.message || String(error),true); setStatus(error.message || String(error)); }
|
||||
|
||||
function renderAccountTabs() {
|
||||
const root=$('#account-tabs');
|
||||
for (const child of [...root.children]) if (!state.accounts.has(child.dataset.account)) child.remove();
|
||||
state.accounts.forEach(account=>{
|
||||
let button=[...root.children].find(child=>child.dataset.account===account.id);
|
||||
if (!button) {
|
||||
button=el('button',{type:'button',class:'account-tab',role:'tab','data-account':account.id,onClick:()=>selectAccount(account.id)},el('span',{class:'account-dot'}),el('span',{class:'account-label'}));
|
||||
root.append(button);
|
||||
}
|
||||
const summary=account.summary, selected=state.active===account.id;
|
||||
$('.account-label',button).textContent=summary.label || summary.player?.name || '账号';
|
||||
$('.account-dot',button).className=`account-dot${summary.error?' error':summary.running?' running':''}`;
|
||||
button.setAttribute('aria-selected',String(selected));button.tabIndex=selected?0:-1;
|
||||
button.title=`${summary.label || '账号'}${summary.demo?' · 离线演示':''}${summary.running?' · 策略运行中':''}${summary.error?' · '+summary.error:''}`;
|
||||
});
|
||||
}
|
||||
|
||||
function syncSaveStatus(account=current()) {
|
||||
if (!account || account.id!==state.active) return;
|
||||
const node=$('#save-status');
|
||||
const message=account.saveError?'保存失败 · 点击重试':account.savePromise?'保存中…':account.edits.size?'修改待保存…':account.config?'策略已自动保存':'配置载入中…';
|
||||
node.textContent=message;node.title=account.saveError || message;node.className=account.saveError?'failed':account.edits.size||account.savePromise?'pending':'';
|
||||
}
|
||||
|
||||
function renderSummary() {
|
||||
const account=current(),summary=account?.summary,player=summary?.player || {};
|
||||
const connected=summary?.connected,demo=summary?.demo;
|
||||
$('#connection').textContent=demo?'离线演示':connected?'已登录':'未登录';
|
||||
$('#connection').className=`connection${demo?' demo':connected?' online':''}`;
|
||||
$('#player-name').textContent=player.name || '—';$('#player-name').title=player.name || '';
|
||||
for (const [id,key] of [['player-level','level'],['player-money','money'],['player-ke','ke'],['player-ti','ti']]) $('#'+id).textContent=number(player[key]);
|
||||
$('#player-exp').textContent=player.exp==null?'—':`${number(player.exp)} / ${number(player.next_exp)}`;
|
||||
$('#experience-progress').max=Math.max(1,Number(player.next_exp)||1);$('#experience-progress').value=Number(player.exp)||0;
|
||||
const run=$('#strategy-toggle');run.textContent=summary?.running?'停止':'开启';run.classList.toggle('running',Boolean(summary?.running));run.disabled=!account || !account.config || !connected && !demo;
|
||||
run.setAttribute('aria-pressed',String(Boolean(summary?.running)));
|
||||
run.title=summary?.running?'停止自动执行已勾选功能;取消尚未发送的请求':'开启后自动执行各页面已勾选功能';
|
||||
if (account?.config && document.activeElement!==$('#refresh-interval')) $('#refresh-interval').value=String(account.config.interval);
|
||||
$('#refresh-interval').disabled=!account?.config;
|
||||
$('#refresh').disabled=!account;
|
||||
const task=account?[...account.jobs.values()].at(-1)?.job:null;
|
||||
$('#job-status').textContent=task?`${operationLabels[task.operation] || task.operation} · ${jobLabels[task.status]}`:summary?.busy?'后台任务执行中':'';
|
||||
$('#data-summary').textContent=summary?.error || (demo?'当前为离线演示,不连接游戏服务器。':connected?'角色状态自动刷新;配置功能后开启策略。':'请在登录页输入账号密码,或恢复已保存会话。');
|
||||
syncSaveStatus(account);
|
||||
}
|
||||
|
||||
async function refreshConfig(account) {
|
||||
if (account.loadingConfig) return;
|
||||
account.loadingConfig=true;
|
||||
try {
|
||||
const response=await api.config(account.id);
|
||||
account.config=clone(response.config);account.revision=response.revision;
|
||||
account.edits.forEach(edit=>applyEdit(account.config,edit));
|
||||
account.pages.forEach(page=>page.data&&page.render(page.data));
|
||||
if (account.id===state.active) {renderSummary();applyLogLayout(account);}
|
||||
} finally {account.loadingConfig=false;}
|
||||
}
|
||||
|
||||
function applyEdit(config,edit) {
|
||||
if(!edit.ifMissing || getPath(config,edit.path)===undefined)setPath(config,edit.path,edit.value);
|
||||
}
|
||||
|
||||
function writeEdit(account,path,value,{ifMissing=false}={}) {
|
||||
if(ifMissing && (getPath(account.config,path)!==undefined || account.edits.get(pathKey(path))?.ifMissing===false))return;
|
||||
setPath(account.config,path,value);
|
||||
account.edits.set(pathKey(path),{path:[...path],value:clone(value),seq:++state.seq,ifMissing});
|
||||
}
|
||||
|
||||
function editConfig(account,path,value,field={},row) {
|
||||
if (!account.config) throw new Error('配置尚未载入,请稍后再试。');
|
||||
if (row?.rule_path && row.rule_defaults)Object.entries(row.rule_defaults).forEach(([key,value])=>writeEdit(account,[...row.rule_path,key],value,{ifMissing:true}));
|
||||
writeEdit(account,path,value);
|
||||
// Preserve the desktop's linked switches when enabling an individual rule.
|
||||
if (path[0]==='policy') {
|
||||
const section=path[1];
|
||||
if (section==='egg_rules') {
|
||||
const rule=getPath(account.config,path.slice(0,3),{});
|
||||
if (rule.enabled && ['enabled','action'].includes(path[3])) {
|
||||
if (rule.action==='sell') writeEdit(account,['policy','dispatch'],true);
|
||||
else {writeEdit(account,['policy','collect'],true);if(rule.action==='feed')writeEdit(account,['policy','feed'],true);}
|
||||
}
|
||||
}
|
||||
if (section==='gift_items'&&value===true) writeEdit(account,['policy','gift_enabled'],true);
|
||||
if (section==='feed_targets'&&value!==undefined) {writeEdit(account,['policy','feed'],true);writeEdit(account,['policy','collect'],true);}
|
||||
if (section==='gift_targets'&&value!==undefined) writeEdit(account,['policy','gift_enabled'],true);
|
||||
}
|
||||
account.saveError=null;clearTimeout(account.saveTimer);
|
||||
account.saveTimer=setTimeout(()=>flushConfig(account).catch(error),500);
|
||||
syncSaveStatus(account);
|
||||
// Update other controls, while every control protects its own focused input.
|
||||
account.pages.forEach(page=>page.data&&page.render(page.data));
|
||||
if (path[0]==='log_visible'||path[0]==='log_sizes') applyLogLayout(account);
|
||||
}
|
||||
|
||||
async function flushConfig(account=current()) {
|
||||
if (!account) return;
|
||||
clearTimeout(account.saveTimer);
|
||||
if (account.savePromise) {await account.savePromise;if(account.edits.size)return flushConfig(account);return;}
|
||||
if (!account.edits.size) return;
|
||||
const invalid=account.pages.get(account.page)?.root.querySelector(':invalid');
|
||||
if (invalid) {invalid.reportValidity();throw new Error('请先补全当前输入,再保存或开启策略。');}
|
||||
const sent=[...account.edits.values()].map(clone),config=clone(account.config);
|
||||
account.saveError=null;
|
||||
account.savePromise=(async()=>{
|
||||
try {
|
||||
let response=await api.save(account.id,config,account.revision);
|
||||
if (response.pending && response.job_id) {
|
||||
const result=await trackJob(account,response.job || {id:response.job_id,status:'queued',operation:'set_config'});
|
||||
response=result?.config?result:await api.config(account.id);
|
||||
}
|
||||
if (!response?.config) response=await api.config(account.id);
|
||||
sent.forEach(edit=>{if(account.edits.get(pathKey(edit.path))?.seq===edit.seq)account.edits.delete(pathKey(edit.path));});
|
||||
account.config=clone(response.config);account.revision=response.revision;
|
||||
account.edits.forEach(edit=>applyEdit(account.config,edit));
|
||||
account.saveError=null;
|
||||
} catch(failure) {
|
||||
if(failure.status===409){
|
||||
const latest=await api.config(account.id);account.config=clone(latest.config);account.revision=latest.revision;
|
||||
account.edits.forEach(edit=>applyEdit(account.config,edit));
|
||||
account.saveError='配置已被另一浏览器更新。已保留你修改的字段,请点击保存状态重试。';
|
||||
} else account.saveError=failure.message;
|
||||
throw new Error(account.saveError);
|
||||
} finally {account.savePromise=null;syncSaveStatus(account);renderSummary();}
|
||||
})();
|
||||
syncSaveStatus(account);
|
||||
await account.savePromise;
|
||||
if(account.edits.size)return flushConfig(account);
|
||||
account.pages.forEach(page=>page.data&&page.render(page.data));
|
||||
const page=account.pages.get(account.page);if(page)loadPage(page,true);
|
||||
}
|
||||
|
||||
function trackJob(account,job) {
|
||||
if (!job?.id || !job.status) return Promise.resolve(job);
|
||||
if (terminal.has(job.status)) return job.status==='succeeded'?Promise.resolve(job.result):Promise.reject(new Error(job.error || jobLabels[job.status]));
|
||||
if(account.jobs.has(job.id))return account.jobs.get(job.id).promise;
|
||||
let resolve,reject;
|
||||
const promise=new Promise((yes,no)=>{resolve=yes;reject=no;});
|
||||
const record={job,promise,resolve,reject,polling:false};account.jobs.set(job.id,record);
|
||||
pollJob(account,record);renderSummary();
|
||||
return promise;
|
||||
}
|
||||
|
||||
async function pollJob(account,record) {
|
||||
if(record.polling)return;record.polling=true;
|
||||
try {
|
||||
const job=await api.job(account.id,record.job.id);record.job=job;
|
||||
if(terminal.has(job.status)){
|
||||
account.jobs.delete(job.id);
|
||||
if(job.status==='succeeded')record.resolve(job.result);
|
||||
else record.reject(new Error(job.error || '任务已取消'));
|
||||
}
|
||||
}catch(failure){if([400,401,403,404].includes(failure.status)){account.jobs.delete(record.job.id);record.reject(failure);}}
|
||||
finally{record.polling=false;renderSummary();}
|
||||
}
|
||||
|
||||
async function perform(account,operation,payload={},options={}) {
|
||||
if(!account)throw new Error('请先新增或选择一个账号。');
|
||||
if(operation==='start'){
|
||||
const invalid=account.pages.get(account.page)?.root.querySelector(':invalid');
|
||||
if(invalid){invalid.reportValidity();throw new Error('请先完成当前输入,再开启策略。');}
|
||||
}
|
||||
if(operation!=='stop')await flushConfig(account);
|
||||
const job=await api.action(account.id,operation,payload);
|
||||
setStatus(`${operationLabels[operation] || '操作'}:${jobLabels[job.status] || '已提交'}`);
|
||||
const result=await trackJob(account,job);
|
||||
if(!state.accounts.has(account.id))return result;
|
||||
if(result?.config){account.config=clone(result.config);account.revision=result.revision;}
|
||||
if(['enter_server','restore_session','logout','forget_login','import_config','import_yields'].includes(operation))await refreshConfig(account);
|
||||
account.summary=await api.status(account.id);
|
||||
renderAccountTabs();renderSummary();
|
||||
const page=options.page || account.pages.get(account.page);if(page)await loadPage(page,true);
|
||||
if(operation==='login'&&result)account.pages.get('login')?.login?.update(result);
|
||||
if(operation==='enter_server'||operation==='restore_session')notice('已读取角色。策略保持关闭,请配置功能后开启。');
|
||||
else if(result?.message)notice(result.message);
|
||||
setStatus(result?.message || `${operationLabels[operation] || '操作'}已完成`);
|
||||
return result;
|
||||
}
|
||||
|
||||
function getPage(account,key) {
|
||||
if(!account.pages.has(key)){
|
||||
const page=new PageView(account,key,{edit:editConfig,perform,load:loadPage,action:pageAction,command,
|
||||
schema:pageKey=>state.schema?.pages?.find(page=>page.key===pageKey)?.form || []});
|
||||
account.pages.set(key,page);$('#page-host').append(page.root);
|
||||
}
|
||||
return account.pages.get(key);
|
||||
}
|
||||
|
||||
async function loadPage(page,force=false) {
|
||||
if(page.fetching){if(force)page.reload=true;return;}
|
||||
page.fetching=true;const generation=page.generation || 0;
|
||||
try {
|
||||
const response=await api.view(page.account.id,page.key,page.query);
|
||||
if(generation!==(page.generation||0))return;
|
||||
page.clearError();page.render(response.data,response.loading);page.lastLoad=Date.now();
|
||||
if(response.loading){clearTimeout(page.loadTimer);page.loadTimer=setTimeout(()=>loadPage(page),650);}
|
||||
}catch(failure){page.showError(failure.message);}
|
||||
finally{page.fetching=false;if(page.reload){page.reload=false;loadPage(page);}}
|
||||
}
|
||||
|
||||
function selectPage(key) {
|
||||
const account=current();if(!account)return;
|
||||
if(account.page!==key)account.pages.get(account.page)?.login?.clearPassword();
|
||||
account.page=key;
|
||||
state.accounts.forEach(other=>other.pages.forEach(page=>{page.root.hidden=other.id!==account.id||page.key!==key;}));
|
||||
const page=getPage(account,key);page.root.hidden=false;
|
||||
$$('.page-tab').forEach(tab=>{const selected=tab.dataset.page===key;tab.setAttribute('aria-selected',String(selected));tab.tabIndex=selected?0:-1;});
|
||||
loadPage(page,true);
|
||||
}
|
||||
|
||||
async function selectAccount(id) {
|
||||
const previous=current();previous?.pages.get('login')?.login?.clearPassword();
|
||||
if(previous?.edits.size)flushConfig(previous).catch(error);
|
||||
state.active=id;const account=current();if(!account)return;
|
||||
$('#page-host').querySelector('.initial-state')?.remove();
|
||||
renderAccountTabs();renderSummary();renderLogs(true);applyLogLayout(account);selectPage(account.page);
|
||||
if(!account.config)try{await refreshConfig(account);}catch(failure){error(failure);}
|
||||
fetchLogs(account);
|
||||
}
|
||||
|
||||
async function addAccount(demo=false) {
|
||||
const label=el('input',{type:'text','aria-label':'账号页签名称',placeholder:demo?'离线演示':'账号名称(可留空)',maxlength:80});
|
||||
const result=await dialog(demo?'新增离线演示账号':'新增账号',el('div',{},el('label',{class:'field'},el('span',{class:'field-label',text:'账号名称'}),label),el('p',{class:'info-note',text:demo?'使用服务端离线演示状态,不连接游戏服务器。':'创建独立账号工作区,然后在登录页连接游戏角色。'})),{confirm:'新增',read:()=>({label:label.value.trim()})});
|
||||
if(!result)return;
|
||||
const summary=await api.create(result.label,demo);state.accounts.set(summary.id,makeAccount(summary));await selectAccount(summary.id);notice(demo?'离线演示账号已创建':'账号已创建,请在登录页登录。');
|
||||
}
|
||||
|
||||
async function pageAction(page,action,currency) {
|
||||
const account=page.account,operation=action.operation;
|
||||
if(operation==='configure_bag'||operation==='configure_ranch'){selectPage(operation==='configure_bag'?'bag':'ranch');return;}
|
||||
if(operation==='reveal_breakthrough'){page.root.querySelector('th[data-column=breakthrough_selected]')?.scrollIntoView({block:'nearest',inline:'center'});return;}
|
||||
if(operation==='apply_preset'){
|
||||
const preset=page.data.details.preset;
|
||||
if(account.summary.running)await perform(account,'stop');
|
||||
Object.entries(preset.patch || {}).forEach(([section,fields])=>Object.entries(fields).forEach(([key,value])=>editConfig(account,[section,key],value)));
|
||||
editConfig(account,['policy','egg_rules'],preset.egg_rules);
|
||||
await flushConfig(account);notice('预设已保存。开启顶部策略后运行。');return;
|
||||
}
|
||||
if(operation==='expand_regions'||operation==='collapse_regions'){page.table?.expand(operation==='expand_regions');return;}
|
||||
if(operation==='import_yields'){return importYields(account);}
|
||||
if(operation==='download_yields'){return exportYields(account);}
|
||||
const payload=clone(action.payload || {}),selected=page.selectedRows();
|
||||
if(action.selection==='monster_ids'){
|
||||
if(!selected.length)throw new Error('请先选择一只或多只魔物。');
|
||||
payload.monster_ids=selected.map(row=>Number(row.id));
|
||||
}
|
||||
if(operation==='quote_expansion'){
|
||||
payload.currency=currency || 'money';
|
||||
if(payload.kind==='stack'&&selected.length)payload.position=Number(selected[0].position ?? selected[0].id);
|
||||
const quote=await perform(account,'quote_expansion',payload,{page});
|
||||
if(await confirm(payload.kind==='stack'?'确认开启坑位':'确认新建牧场',`${quote.description}\n确认消费并开通?`,{confirm:'确认消费',danger:true}))return perform(account,'expand',{quote_id:quote.quote_id,confirm:true},{page});
|
||||
return;
|
||||
}
|
||||
if(operation==='feed'){
|
||||
const options=optionsList(action.target_options || page.data.feed_targets).filter(option=>!payload.monster_ids.includes(Number(option.value)));
|
||||
if(!options.length)throw new Error('没有可接收经验的目标魔物,请检查当前突破上限。');
|
||||
const select=el('select',{'aria-label':'喂养目标'},...options.map(option=>el('option',{value:option.value,text:option.label})));
|
||||
const result=await dialog('确认喂养',el('div',{},el('p',{text:`将选中 ${selected.length} 只魔物作为经验素材,无法撤销。`}),el('label',{class:'field'},el('span',{class:'field-label',text:'喂养目标'}),select)),{confirm:'确认喂养',danger:true,read:()=>({target_id:Number(select.value)})});
|
||||
if(!result)return;payload.target_id=result.target_id;payload.confirm=true;
|
||||
}else if(action.confirm || operation==='reset_map_pending'){
|
||||
if(!await confirm(action.label,`${action.confirm || '仅在游戏内核对后处理未完成记录;缺少服务器结算证据时将保留记录。'}${selected.length?'\n已选择 '+selected.length+' 项':''}`,{confirm:'确认',danger:true}))return;
|
||||
payload.confirm=true;
|
||||
}
|
||||
return perform(account,operation,payload,{page});
|
||||
}
|
||||
|
||||
async function importYields(account=current()) {
|
||||
const file=await filePicker('.csv,.xlsx');if(!file)return;
|
||||
if(file.size>8*1024*1024)throw new Error('收益资料文件最大为 8 MiB。');
|
||||
const result=await perform(account,'import_yields',{filename:file.name,content_base64:await fileBase64(file)});
|
||||
notice(result?.message || '收益资料已导入并保存。');
|
||||
}
|
||||
|
||||
async function exportYields(account=current()) {
|
||||
if(!account)throw new Error('请先选择账号。');
|
||||
const page=getPage(account,'yields');await loadPage(page,true);
|
||||
const deadline=Date.now()+30000;
|
||||
while(!page.data?.columns?.length&&Date.now()<deadline){await new Promise(resolve=>setTimeout(resolve,250));await loadPage(page);}
|
||||
if(!page.data?.columns?.length)throw new Error('收益资料尚未载入,请稍后重试。');
|
||||
const columns=[{key:'type_id',label:'编号'},{key:'name',label:'名称'},{key:'star',label:'星'},{key:'time_total',label:'孵化秒数'},{key:'sell_money',label:'派遣金币'},{key:'sell_exp',label:'强化经验'},{key:'gold_per_hour',label:'金币/小时'},{key:'exp_per_hour',label:'经验/小时'}];
|
||||
download(csvBlob(columns,page.data.rows || []),'牧场收益资料.csv');
|
||||
}
|
||||
|
||||
async function command(name,account=current()) {
|
||||
try {
|
||||
if(name==='add-account'||name==='add-demo')return await addAccount(name==='add-demo');
|
||||
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.0.dev1'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`}),el('p',{class:'info-note',text:'与桌面助手共用核心策略。配置在服务端自动保存;运行开关在重启和恢复会话后保持关闭。'})),{info:true});
|
||||
if(name==='updates')return await showUpdates();
|
||||
if(name==='admin-logout'){await api.logout();state.ready=false;location.reload();return;}
|
||||
if(!account)throw new Error('请先新增或选择账号。');
|
||||
if(name==='debug'){account.logs.debug=!account.logs.debug;account.logs.entries=[];account.logs.next=0;account.logs.generation=(account.logs.generation || 0)+1;$('#debug-log').checked=account.logs.debug;setLogVisible(true);renderLogs(true);await fetchLogs(account);return;}
|
||||
if(name==='save'){await flushConfig(account);notice('策略已保存。');return;}
|
||||
if(name==='stop'||name==='start')return await perform(account,name);
|
||||
if(name==='start-all'||name==='stop-all'){await Promise.all([...state.accounts.values()].map(item=>perform(item,name==='start-all'?'start':'stop')));return;}
|
||||
if(name==='logout')return await perform(account,'logout');
|
||||
if(name==='forget-login'){
|
||||
if(await confirm('退出并清除登录记录','将退出当前角色,删除当前账号保存的登录会话和账号密码。培养策略和其他账号不受影响。',{confirm:'清除登录记录',danger:true}))await perform(account,'forget_login');return;
|
||||
}
|
||||
if(name==='remove-account'){
|
||||
if(!await confirm('移除当前账号',`移除“${account.summary.label || '当前账号'}”及其保存的会话和策略?此操作无法撤销。`,{confirm:'移除账号',danger:true}))return;
|
||||
await api.remove(account.id);account.jobs.forEach(record=>record.reject(new Error('账号已移除')));account.pages.forEach(page=>{clearTimeout(page.loadTimer);page.root.remove();});clearTimeout(account.saveTimer);state.accounts.delete(account.id);state.active=null;
|
||||
if(state.accounts.size)await selectAccount(state.accounts.keys().next().value);else showNoAccounts();renderAccountTabs();renderSummary();return;
|
||||
}
|
||||
if(name==='export-config'){
|
||||
await flushConfig(account);const result=await trackJob(account,await api.exportConfig(account.id));
|
||||
download(new Blob([JSON.stringify(result,null,2)],{type:'application/json'}),'牧场策略.json');return;
|
||||
}
|
||||
if(name==='import-config'){
|
||||
const file=await filePicker('.json');if(!file)return;if(file.size>1024*1024)throw new Error('策略文件过大。');
|
||||
let config;try{config=JSON.parse(await file.text());}catch{throw new Error('策略文件不是有效的 JSON。');}
|
||||
if(!await confirm('导入当前账号策略','将替换当前账号策略,策略运行保持关闭。',{confirm:'导入策略'}))return;
|
||||
await flushConfig(account);const result=await trackJob(account,await api.importConfig(account.id,config));await refreshConfig(account);notice('策略已导入,运行保持关闭。');await loadPage(getPage(account,account.page),true);return result;
|
||||
}
|
||||
if(name==='import-yields')return await importYields(account);
|
||||
if(name==='export-yields')return await exportYields(account);
|
||||
}catch(failure){error(failure);}
|
||||
}
|
||||
|
||||
async function showUpdates() {
|
||||
const content=el('div',{class:'detail-sections'}),values=el('div'),message=el('p'),check=el('button',{type:'button',text:'检查 GitHub 正式版本'}),apply=el('button',{type:'button',text:'提交更新请求…',disabled:true});
|
||||
const labels={unchecked:'尚未检查',no_release:'尚无正式版本',up_to_date:'已是最新版本',available:'发现新版本',check_failed:'版本检查失败',unavailable:'更新器未就绪',pending:'等待宿主机处理',applying:'正在更新并检查健康',succeeded:'更新完成,健康检查通过',rolled_back:'更新失败,已回滚',failed:'更新失败'};
|
||||
const lifetime=new AbortController();
|
||||
let status,timer,closed=false,busy=false;
|
||||
const active=()=>!closed && content.isConnected && $('#action-dialog').open;
|
||||
const bounded=async callback=>{
|
||||
const controller=new AbortController(),abort=()=>controller.abort();
|
||||
lifetime.signal.addEventListener('abort',abort,{once:true});
|
||||
const deadline=setTimeout(abort,5000);
|
||||
try{return await callback(controller.signal);}
|
||||
finally{clearTimeout(deadline);lifetime.signal.removeEventListener('abort',abort);}
|
||||
};
|
||||
const render=data=>{
|
||||
if(!active())return;
|
||||
status=data;
|
||||
const host=data.host_status;
|
||||
values.replaceChildren(detailsList({current:data.current_version || state.meta?.version,latest:data.latest_version,checked:data.checked_at,executor:data.executor?.enabled?'已就绪':'未配置或未启用',automatic:data.executor?.auto_apply?'已启用':'未启用',status:labels[data.status] || '状态未确认',...(host?{host:labels[host.status] || '状态未确认',hostVersion:host.version,hostUpdated:host.updated_at}:{})},{current:'当前版本',latest:'最新正式版本',checked:'上次检查',executor:'宿主机更新器',automatic:'定时更新',status:'更新状态',host:'宿主机回报',hostVersion:'宿主机版本',hostUpdated:'回报时间'}));
|
||||
message.textContent=[...new Set([data.message,data.error,host?.message,host?.error].filter(Boolean))].join('\n');apply.disabled=!data.can_apply;
|
||||
if(!data.executor?.enabled)message.textContent+=' 当前仅可检查版本;部署器未配置或未启用,无法执行更新。';
|
||||
};
|
||||
const schedule=()=>{clearTimeout(timer);if(active())timer=setTimeout(poll,3000);};
|
||||
const disconnected=async failure=>{
|
||||
if(!active())return;
|
||||
message.textContent=failure.status===401?'服务已重新要求管理登录,请登录后继续查看更新状态。':'服务暂时断开,正在等待恢复;每 3 秒重新读取更新状态。';
|
||||
apply.disabled=true;
|
||||
try{await bounded(signal=>api.health({signal}));}catch{}
|
||||
};
|
||||
async function poll(){
|
||||
if(!active())return;
|
||||
if(busy){schedule();return;}
|
||||
busy=true;
|
||||
try{render(await bounded(signal=>api.updates({signal})));}
|
||||
catch(failure){await disconnected(failure);}
|
||||
finally{busy=false;schedule();}
|
||||
}
|
||||
check.addEventListener('click',async()=>{
|
||||
if(busy)return;busy=true;clearTimeout(timer);check.disabled=true;check.textContent='正在检查…';
|
||||
try{render(await bounded(signal=>api.checkUpdates({signal})));}
|
||||
catch(failure){if(active())message.textContent=failure.name==='AbortError'?'版本检查暂未返回,稍后将自动读取最新状态。':failure.message;}
|
||||
finally{busy=false;check.disabled=false;check.textContent='检查 GitHub 正式版本';schedule();}
|
||||
});
|
||||
apply.addEventListener('click',async()=>{
|
||||
if(busy || !status?.can_apply)return;
|
||||
const version=status.latest_version;
|
||||
if(!window.confirm(`提交 ${version} 更新请求?执行器将处理请求并可能重启服务。`))return;
|
||||
busy=true;clearTimeout(timer);apply.disabled=true;
|
||||
try{render(await bounded(signal=>api.applyUpdate(version,{signal})));}
|
||||
catch(failure){await disconnected(failure);}
|
||||
finally{busy=false;schedule();}
|
||||
});
|
||||
content.append(values,message,el('div',{class:'page-toolbar'},check,apply),el('p',{class:'info-note',text:'仅检查 GitHub 正式版本。窗口打开时每 3 秒读取宿主机状态;提交请求后由受控更新器处理,服务恢复且健康检查通过后才显示完成。'}));
|
||||
const open=dialog('版本与更新',content,{info:true});
|
||||
poll();
|
||||
try{await open;}
|
||||
finally{closed=true;clearTimeout(timer);lifetime.abort();}
|
||||
}
|
||||
|
||||
function setLogVisible(visible) {
|
||||
const account=current();if(account?.config)editConfig(account,['log_visible'],visible);
|
||||
else applyLogLayout(null,visible);
|
||||
}
|
||||
|
||||
function applyLogLayout(account=current(),visibleOverride) {
|
||||
if(account&&account.id!==state.active)return;
|
||||
const visible=visibleOverride ?? account?.config?.log_visible ?? true;
|
||||
$('#log-panel').hidden=!visible;$('#log-resizer').hidden=!visible;$('#log-toggle').textContent=visible?'隐藏日志':'显示日志';$('#log-toggle').setAttribute('aria-expanded',String(visible));
|
||||
const size=account?.config?.log_sizes?.[1];if(size)setLogHeight(size);
|
||||
}
|
||||
|
||||
function setLogHeight(height) {
|
||||
height=Math.max(64,Math.min(Math.min(480,innerHeight*.5),Math.round(height)));
|
||||
document.documentElement.style.setProperty('--log-height',`${height}px`);$('#log-resizer').setAttribute('aria-valuenow',String(height));return height;
|
||||
}
|
||||
|
||||
function renderLogs(reset=false) {
|
||||
const account=current(),root=$('#log-lines');if(!account){root.replaceChildren();return;}
|
||||
const log=account.logs;
|
||||
if(reset){root.replaceChildren();log.rendered=0;}
|
||||
const follow=$('#log-follow').checked&& (reset || root.scrollHeight-root.scrollTop-root.clientHeight<45);
|
||||
for(const entry of log.entries.slice(log.rendered || 0)){
|
||||
const line=el('div',{class:`log-entry ${entry.level || entry.kind || ''}`,'data-entry-id':entry.id});
|
||||
const stamp=entry.time || entry.timestamp || entry.at || '';
|
||||
line.append(el('span',{class:'log-time',text:chinaTime(stamp),title:String(stamp)}),document.createTextNode(entry.message || entry.operation || textValue(entry)));
|
||||
if(entry.details_available || entry.detail_url){line.classList.add('inspectable');line.tabIndex=0;line.setAttribute('role','button');line.title='查看脱敏请求 / 响应 JSON';line.addEventListener('click',()=>showDebugEntry(account,entry));line.addEventListener('keydown',event=>{if(event.key==='Enter'||event.key===' '){event.preventDefault();showDebugEntry(account,entry);}});}
|
||||
root.append(line);
|
||||
}
|
||||
log.rendered=log.entries.length;
|
||||
while(root.childElementCount>600)root.firstElementChild.remove();
|
||||
$('#log-count').textContent=`${Math.min(600,log.entries.length)} 条`;$('#debug-log').checked=log.debug;$('#log-heading').textContent=log.debug?'调试日志(已脱敏)':'运行日志';
|
||||
if(follow)root.scrollTop=root.scrollHeight;
|
||||
}
|
||||
|
||||
async function fetchLogs(account) {
|
||||
if(account.logs.loading)return;account.logs.loading=true;const generation=account.logs.generation || 0;
|
||||
try{const response=await api.logs(account.id,account.logs.next,account.logs.debug);if(generation!==(account.logs.generation || 0))return;
|
||||
const seen=new Set(account.logs.entries.map(entry=>entry.id));
|
||||
account.logs.entries.push(...(response.entries || []).filter(entry=>entry.id==null||!seen.has(entry.id)));account.logs.next=response.next;
|
||||
if(account.id===state.active)renderLogs();
|
||||
if(account.logs.entries.length>1200){account.logs.entries=account.logs.entries.slice(-600);if(account.id===state.active)renderLogs(true);}
|
||||
}catch(failure){if(failure.status!==401)setStatus(failure.message);}finally{account.logs.loading=false;}
|
||||
}
|
||||
|
||||
async function showDebugEntry(account,entry) {
|
||||
const pre=el('pre',{class:'debug-json',text:'正在读取所选条目的脱敏详情…'});const open=dialog('请求 / 响应详情(已脱敏)',pre,{info:true});
|
||||
try{let detail;if(entry.detail_url&&new URL(entry.detail_url,location.href).origin===location.origin)detail=await request(entry.detail_url);else detail=await api.debugEntry(account.id,entry.id);pre.textContent=JSON.stringify(detail.details ?? detail,null,2);}catch(failure){pre.textContent=failure.message;}
|
||||
await open;
|
||||
}
|
||||
|
||||
function showNoAccounts() {
|
||||
state.active=null;$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:'尚未添加账号。新增账号后登录游戏,或使用离线演示查看工作台。'}),el('div',{class:'page-toolbar'},el('button',{text:'新增账号…',onClick:()=>command('add-account')}),el('button',{text:'新增离线演示账号',onClick:()=>command('add-demo')}))));
|
||||
renderAccountTabs();renderSummary();renderLogs(true);setStatus('等待新增账号');
|
||||
}
|
||||
|
||||
async function syncAccounts() {
|
||||
const response=await api.accounts(),summaries=Array.isArray(response)?response:response.accounts || [];
|
||||
const ids=new Set(summaries.map(summary=>summary.id));
|
||||
for(const [id,account]of state.accounts)if(!ids.has(id)){account.pages.forEach(page=>{clearTimeout(page.loadTimer);page.root.remove();});state.accounts.delete(id);}
|
||||
summaries.forEach(summary=>{
|
||||
const account=state.accounts.get(summary.id);if(account){account.summary=summary;if(account.config&&account.revision!==summary.revision&&!account.edits.size&&!account.savePromise)refreshConfig(account).catch(error);}
|
||||
else state.accounts.set(summary.id,makeAccount(summary));
|
||||
});
|
||||
renderAccountTabs();renderSummary();
|
||||
if(!state.accounts.size)showNoAccounts();else if(!state.accounts.has(state.active))await selectAccount(state.accounts.keys().next().value);
|
||||
}
|
||||
|
||||
async function tick() {
|
||||
if(!state.ready||state.polling)return;state.polling=true;
|
||||
try{
|
||||
const account=current();await Promise.allSettled([syncAccounts(),...([...state.accounts.values()].flatMap(item=>[...item.jobs.values()].map(job=>pollJob(item,job))))]);
|
||||
if(account&&state.accounts.has(account.id)){fetchLogs(account);const page=account.pages.get(account.page);if(page&&Date.now()-(page.lastLoad||0)>4000)loadPage(page);}
|
||||
}finally{state.polling=false;}
|
||||
}
|
||||
|
||||
async function requireAuth() {
|
||||
state.ready=false;const root=$('#auth-dialog');if(!root.open)root.showModal();$('#admin-password').focus();
|
||||
}
|
||||
|
||||
async function bootstrap() {
|
||||
try{
|
||||
const auth=await api.auth();if(auth.required&&!auth.authenticated){requireAuth();return;}
|
||||
const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema;
|
||||
$('#app-version').textContent=meta.version || '2.0.0.dev1';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
|
||||
await syncAccounts();state.ready=true;setStatus('工作台已连接');
|
||||
}catch(failure){setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));}
|
||||
}
|
||||
|
||||
PAGES.forEach(([key,label])=>$('#page-tabs').append(el('button',{type:'button',class:'page-tab',role:'tab','data-page':key,'aria-selected':String(key==='login'),tabindex:key==='login'?0:-1,text:label,onClick:()=>selectPage(key)})));
|
||||
tabKeys($('#account-tabs'),'.account-tab');tabKeys($('#page-tabs'),'.page-tab');
|
||||
$('#menu-bar').addEventListener('click',event=>{const button=event.target.closest('[data-command]');if(button){$$('.menu[open]').forEach(menu=>menu.open=false);command(button.dataset.command);}});
|
||||
document.addEventListener('click',event=>{if(!event.target.closest('.menu'))$$('.menu[open]').forEach(menu=>menu.open=false);});
|
||||
document.addEventListener('keydown',event=>{if(event.key==='Escape')$$('.menu[open]').forEach(menu=>menu.open=false);});
|
||||
$$('.menu').forEach(menu=>menu.addEventListener('toggle',()=>{if(menu.open)$$('.menu').filter(other=>other!==menu).forEach(other=>other.open=false);}));
|
||||
$('#add-account').addEventListener('click',()=>command('add-account'));
|
||||
$('#strategy-toggle').addEventListener('click',()=>command(current()?.summary.running?'stop':'start'));
|
||||
$('#refresh').addEventListener('click',()=>{const account=current();if(account)perform(account,'refresh',{page:account.page}).catch(error);});
|
||||
$('#refresh-interval').addEventListener('change',event=>{if(current())editConfig(current(),['interval'],Number(event.target.value));});
|
||||
$('#save-status').tabIndex=0;$('#save-status').addEventListener('click',()=>command('save'));$('#save-status').addEventListener('keydown',event=>{if(event.key==='Enter')command('save');});
|
||||
$('#debug-toggle').addEventListener('click',()=>command('debug'));$('#debug-log').addEventListener('change',()=>command('debug'));
|
||||
$('#log-toggle').addEventListener('click',()=>setLogVisible($('#log-panel').hidden));
|
||||
$('#clear-log').addEventListener('click',()=>{if(current()){current().logs.entries=[];current().logs.rendered=0;renderLogs(true);}});
|
||||
$('#download-log').addEventListener('click',()=>{const account=current();if(account)download(new Blob([account.logs.entries.map(entry=>[entry.time || entry.timestamp || '',entry.message || entry.operation || ''].join(' ')).join('\n')],{type:'text/plain;charset=utf-8'}),'牧场日志.txt');});
|
||||
$('#log-lines').addEventListener('scroll',()=>{const node=$('#log-lines');if(node.scrollHeight-node.scrollTop-node.clientHeight>55)$('#log-follow').checked=false;});
|
||||
$('#log-follow').addEventListener('change',()=>{if($('#log-follow').checked)$('#log-lines').scrollTop=$('#log-lines').scrollHeight;});
|
||||
let resize;
|
||||
$('#log-resizer').addEventListener('pointerdown',event=>{resize={y:event.clientY,height:$('#log-panel').getBoundingClientRect().height};event.currentTarget.setPointerCapture(event.pointerId);event.preventDefault();});
|
||||
$('#log-resizer').addEventListener('pointermove',event=>{if(resize)setLogHeight(resize.height+resize.y-event.clientY);});
|
||||
$('#log-resizer').addEventListener('pointerup',()=>{if(!resize)return;resize=null;const account=current();if(account?.config)editConfig(account,['log_sizes'],[$('#workspace').clientHeight,Number($('#log-resizer').getAttribute('aria-valuenow'))]);});
|
||||
$('#log-resizer').addEventListener('keydown',event=>{if(!['ArrowUp','ArrowDown','Home','End'].includes(event.key))return;event.preventDefault();const height=Number(event.currentTarget.getAttribute('aria-valuenow'));const next=setLogHeight(event.key==='Home'?64:event.key==='End'?480:height+(event.key==='ArrowUp'?16:-16));if(current()?.config)editConfig(current(),['log_sizes'],[$('#workspace').clientHeight,next]);});
|
||||
$('#auth-form').addEventListener('submit',async event=>{event.preventDefault();const input=$('#admin-password');const password=input.value;input.value='';const button=$('button',event.currentTarget);button.disabled=true;try{await api.login(password);$('#auth-dialog').close();$('#auth-error').hidden=true;await bootstrap();}catch(failure){$('#auth-error').textContent=failure.message;$('#auth-error').hidden=false;input.focus();}finally{button.disabled=false;}});
|
||||
$('#auth-dialog').addEventListener('cancel',event=>event.preventDefault());window.addEventListener('auth-required',requireAuth);
|
||||
window.addEventListener('beforeunload',event=>{if([...state.accounts.values()].some(account=>account.edits.size||account.savePromise)){event.preventDefault();event.returnValue='';}});
|
||||
setInterval(()=>{$('#clock').textContent=new Date().toLocaleTimeString('zh-CN',{hour12:false});},1000);
|
||||
setInterval(tick,1000);
|
||||
bootstrap();
|
||||
@@ -0,0 +1,116 @@
|
||||
// Every supplied string is rendered as text, including names, errors and logs.
|
||||
export function el(tag, attributes = {}, ...children) {
|
||||
const node = document.createElement(tag);
|
||||
for (const [key, value] of Object.entries(attributes)) {
|
||||
if (value === undefined || value === null || value === false) continue;
|
||||
if (key === 'class') node.className = value;
|
||||
else if (key === 'text') node.textContent = String(value);
|
||||
else if (key.startsWith('on') && typeof value === 'function') node.addEventListener(key.slice(2).toLowerCase(), value);
|
||||
else if (['checked', 'disabled', 'hidden', 'value', 'multiple', 'required', 'open'].includes(key)) node[key] = value;
|
||||
else node.setAttribute(key, value === true ? '' : String(value));
|
||||
}
|
||||
for (const child of children.flat(Infinity)) {
|
||||
if (child !== null && child !== undefined && child !== false) node.append(child instanceof Node ? child : document.createTextNode(String(child)));
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
export const $ = (selector, root = document) => root.querySelector(selector);
|
||||
export const $$ = (selector, root = document) => [...root.querySelectorAll(selector)];
|
||||
export const clone = value => structuredClone(value);
|
||||
export const pathKey = path => JSON.stringify(path);
|
||||
const blockedKeys = new Set(['__proto__', 'prototype', 'constructor']);
|
||||
|
||||
export function getPath(object, path, fallback) {
|
||||
let value = object;
|
||||
for (const key of path || []) {
|
||||
if (blockedKeys.has(String(key)) || value == null || !Object.hasOwn(value, key)) return fallback;
|
||||
value = value[key];
|
||||
}
|
||||
return value === undefined ? fallback : value;
|
||||
}
|
||||
|
||||
export function setPath(object, path, value) {
|
||||
if (!Array.isArray(path) || !path.length || path.some(key => blockedKeys.has(String(key)))) throw new Error('配置字段路径无效');
|
||||
let current = object;
|
||||
path.slice(0, -1).forEach((key, index) => {
|
||||
if (!current[key] || typeof current[key] !== 'object') current[key] = typeof path[index + 1] === 'number' ? [] : {};
|
||||
current = current[key];
|
||||
});
|
||||
if (value === undefined) delete current[path.at(-1)];
|
||||
else current[path.at(-1)] = clone(value);
|
||||
}
|
||||
|
||||
export function textValue(value) {
|
||||
if (value === null || value === undefined || value === '') return '—';
|
||||
if (typeof value === 'boolean') return value ? '是' : '否';
|
||||
if (Array.isArray(value)) return value.map(textValue).join(' / ');
|
||||
if (typeof value === 'object') return Object.entries(value).map(([key, item]) => `${key}: ${textValue(item)}`).join(';');
|
||||
return String(value);
|
||||
}
|
||||
|
||||
export function number(value) {
|
||||
if (value === null || value === undefined) return '—';
|
||||
const numeric=Number(value);
|
||||
if(!Number.isFinite(numeric))return textValue(value);
|
||||
return numeric.toLocaleString('zh-CN',Number.isInteger(numeric)?{}:{maximumSignificantDigits:6});
|
||||
}
|
||||
|
||||
export function chinaTime(value, {date=false} = {}) {
|
||||
if(value===null || value===undefined || value==='')return '';
|
||||
const parsed=typeof value==='number'?new Date(value<1e12?value*1000:value):new Date(value);
|
||||
if(!Number.isFinite(parsed.getTime()))return String(value);
|
||||
return new Intl.DateTimeFormat('zh-CN',{timeZone:'Asia/Shanghai',hour12:false,hour:'2-digit',minute:'2-digit',second:'2-digit',
|
||||
...(date?{year:'numeric',month:'2-digit',day:'2-digit'}:{})}).format(parsed);
|
||||
}
|
||||
|
||||
export function optionsList(options) {
|
||||
if (!options) return [];
|
||||
if (!Array.isArray(options)) return Object.entries(options).map(([value, label]) => ({value, label}));
|
||||
return options.map(option => Array.isArray(option) ? {value: option[0], label: option[1]} : typeof option === 'object' ? {value: option.value ?? option.id ?? option.key, label: option.label ?? option.name ?? String(option.value ?? option.id), ...option} : {value: option, label: String(option)});
|
||||
}
|
||||
|
||||
export function download(blob, filename) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = el('a', {href: url, download: filename});
|
||||
document.body.append(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
export function csvBlob(columns, rows) {
|
||||
// Spreadsheet text must not become a formula when a nickname starts with '='.
|
||||
const escape = value => {
|
||||
let text = value == null ? '' : textValue(value);
|
||||
if (/^[\s]*[=+@\-]/u.test(text) && !/^-?\d+(\.\d+)?$/u.test(text)) text = "'" + text;
|
||||
return '"' + text.replaceAll('"', '""') + '"';
|
||||
};
|
||||
const lines = [columns.map(column => escape(column.label)).join(','), ...rows.map(row => columns.map(column => escape(row[column.key])).join(','))];
|
||||
return new Blob(['\ufeff', lines.join('\r\n')], {type: 'text/csv;charset=utf-8'});
|
||||
}
|
||||
|
||||
export function empty(message) {
|
||||
return el('div', {class: 'empty-state'}, el('p', {text: message}));
|
||||
}
|
||||
|
||||
export function detailsList(value, labels = {}) {
|
||||
const list = el('dl', {class: 'detail-list'});
|
||||
for (const [key, item] of Object.entries(value || {})) {
|
||||
list.append(el('dt', {text: labels[key] || key}), el('dd', {text: textValue(item)}));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
export function tabKeys(container, selector) {
|
||||
container.addEventListener('keydown', event => {
|
||||
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
|
||||
const tabs = $$(selector, container).filter(tab => !tab.disabled);
|
||||
const index = tabs.indexOf(document.activeElement);
|
||||
if (index < 0) return;
|
||||
const next = event.key === 'Home' ? 0 : event.key === 'End' ? tabs.length - 1 : (index + (event.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length;
|
||||
event.preventDefault();
|
||||
tabs[next]?.focus();
|
||||
tabs[next]?.click();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import {el, $, optionsList, pathKey} from './dom.js';
|
||||
|
||||
function readNumber(input, integer = true) {
|
||||
if (input.value.trim() === '' || !input.checkValidity()) return undefined;
|
||||
const value = Number(input.value);
|
||||
return Number.isFinite(value) && (!integer || Number.isInteger(value)) ? value : undefined;
|
||||
}
|
||||
|
||||
// A control is created once, then synchronized without replacing its input node.
|
||||
export function control(field, {get, set, onError = () => {}}) {
|
||||
const type = field.type || 'text';
|
||||
const path = field.path || [];
|
||||
const label = field.label || path.at(-1) || '设置';
|
||||
let root, sync;
|
||||
const commit = value => {
|
||||
try { set(path, value, field); } catch (error) { onError(error); }
|
||||
};
|
||||
const value = () => get(path, field.value);
|
||||
if (type === 'add_rule') {
|
||||
const select = el('select', {'aria-label': label}, el('option', {value: '', text: '选择魔物蛋(含无库存)'}), ...optionsList(field.options).map(option => el('option', {value: option.value, text: `${option.label} [${option.value}]`})));
|
||||
const add = el('button', {type: 'button', text: '添加无库存蛋规则'});
|
||||
add.addEventListener('click', () => {
|
||||
if (!select.value) { select.focus(); return; }
|
||||
const defaults=field.defaults_by_id?.[select.value] || field.defaults || {};
|
||||
set([...path, select.value], get([...path, select.value], defaults), field);
|
||||
});
|
||||
root = el('div', {class: 'inline-editor'}, select, add);
|
||||
sync = () => {};
|
||||
} else if (['boolean', 'bool', 'checkbox'].includes(type)) {
|
||||
root = el('input', {type: 'checkbox', 'aria-label': label});
|
||||
root.addEventListener('change', () => commit(root.checked));
|
||||
sync = () => { root.checked = Boolean(value()); };
|
||||
} else if (['select', 'enum'].includes(type)) {
|
||||
root = el('select', {'aria-label': label});
|
||||
let optionsSignature;
|
||||
const fill = () => {
|
||||
const options = optionsList(typeof field.options === 'function' ? field.options() : field.options);
|
||||
const signature = JSON.stringify(options);
|
||||
if (signature !== optionsSignature && document.activeElement !== root) {
|
||||
root.replaceChildren(...options.map(option => el('option', {value: String(option.value), text: option.label, disabled: option.disabled})));
|
||||
optionsSignature = signature;
|
||||
}
|
||||
return options;
|
||||
};
|
||||
root.addEventListener('change', () => {
|
||||
const selected = fill().find(option => String(option.value) === root.value);
|
||||
if (selected) commit(selected.value);
|
||||
});
|
||||
sync = () => {
|
||||
fill();
|
||||
if (document.activeElement !== root) root.value = String(value() ?? '');
|
||||
};
|
||||
} else if (['multiselect', 'multi_select'].includes(type)) {
|
||||
root = el('div', {class: 'multi-select', role: 'group', 'aria-label': label});
|
||||
const items = optionsList(field.options).map(option => {
|
||||
const check = el('input', {type: 'checkbox', 'aria-label': option.label});
|
||||
check.addEventListener('change', () => commit(items.filter(item => item.check.checked).map(item => item.option.value)));
|
||||
root.append(el('label', {}, check, option.label));
|
||||
return {check, option};
|
||||
});
|
||||
sync = () => items.forEach(({check, option}) => { check.checked = (value() || []).includes(option.value); });
|
||||
} else if (['id_counts', 'counts', 'reserves'].includes(type)) {
|
||||
root = el('div', {class: 'counts-editor', role: 'group', 'aria-label': label});
|
||||
const lines = el('div', {class: 'counts-lines'});
|
||||
const add = el('button', {type: 'button', class: 'small', text: '添加编号 / 数量'});
|
||||
root.append(lines, add);
|
||||
let signature;
|
||||
const save = () => {
|
||||
const result = {};
|
||||
for (const line of [...lines.children]) {
|
||||
const id = $('input[data-part=id]', line), count = $('input[data-part=count]', line);
|
||||
if (!id.value.trim() && count.value === '') continue;
|
||||
const number = readNumber(count);
|
||||
if (!/^[1-9]\d*$/.test(id.value.trim()) || number === undefined || result[id.value.trim()] !== undefined) {
|
||||
id.setCustomValidity('请输入不重复的正整数编号和有效数量');
|
||||
return;
|
||||
}
|
||||
id.setCustomValidity('');
|
||||
result[id.value.trim()] = number;
|
||||
}
|
||||
signature = JSON.stringify(result);
|
||||
commit(result);
|
||||
};
|
||||
const addLine = (id = '', count = '') => {
|
||||
const idInput = el('input', {type: 'text', inputmode: 'numeric', value: id, placeholder: '编号', 'aria-label': `${label}物品编号`, 'data-part': 'id', class: 'count-id'});
|
||||
const countInput = el('input', {type: 'number', min: 0, max: 1000000000, step: 1, value: count, placeholder: '数量', 'aria-label': `${label}数量`, 'data-part': 'count'});
|
||||
const line = el('div', {class: 'inline-editor'}, idInput, countInput);
|
||||
line.append(el('button', {type: 'button', class: 'small', text: '移除', onClick: () => { line.remove(); save(); }}));
|
||||
idInput.addEventListener('input', () => { idInput.setCustomValidity(''); save(); });
|
||||
countInput.addEventListener('input', save);
|
||||
lines.append(line);
|
||||
return idInput;
|
||||
};
|
||||
add.addEventListener('click', () => addLine().focus());
|
||||
sync = () => {
|
||||
if (root.contains(document.activeElement)) return;
|
||||
const next = value() || {};
|
||||
if (JSON.stringify(next) === signature) return;
|
||||
lines.replaceChildren();
|
||||
Object.entries(next).forEach(([id, count]) => addLine(id, count));
|
||||
signature = JSON.stringify(next);
|
||||
};
|
||||
} else {
|
||||
const numeric = ['integer', 'int', 'number', 'float', 'priority'].includes(type);
|
||||
root = el('input', {type: numeric ? 'number' : 'text', 'aria-label': label, min: field.min ?? (numeric ? 0 : undefined), max: field.max,
|
||||
step: field.step ?? (['number', 'float'].includes(type) ? 'any' : numeric ? 1 : undefined), placeholder: field.placeholder});
|
||||
root.addEventListener('input', () => {
|
||||
if (numeric) {
|
||||
const next = readNumber(root, !['number', 'float'].includes(type));
|
||||
if (next !== undefined) commit(next);
|
||||
} else if (['id_list', 'ids'].includes(type)) {
|
||||
const parts = root.value.split(/[,,;;\s]+/).filter(Boolean);
|
||||
if (parts.some(part => !/^[1-9]\d*$/.test(part))) { root.setCustomValidity('编号须为正整数,多个编号用逗号分隔'); return; }
|
||||
root.setCustomValidity('');
|
||||
commit([...new Set(parts.map(Number))]);
|
||||
} else commit(root.value);
|
||||
});
|
||||
sync = () => {
|
||||
if (document.activeElement === root) return;
|
||||
const next = value();
|
||||
root.value = ['id_list', 'ids'].includes(type) ? (next || []).join(', ') : next ?? '';
|
||||
};
|
||||
}
|
||||
root.dataset.configPath = pathKey(path);
|
||||
root.title = field.help || field.description || label;
|
||||
root.disabled = Boolean(field.disabled || field.readonly);
|
||||
sync();
|
||||
return {root, sync, field};
|
||||
}
|
||||
|
||||
export class PolicyForm {
|
||||
constructor(host, context) {
|
||||
this.host = host;
|
||||
this.context = context;
|
||||
this.controls = [];
|
||||
this.signature = '';
|
||||
}
|
||||
|
||||
update(fields = []) {
|
||||
if (!Array.isArray(fields)) fields = fields.fields || [];
|
||||
const signature = JSON.stringify(fields.map(({value, ...field}) => field));
|
||||
if (signature !== this.signature && !this.host.contains(document.activeElement)) {
|
||||
this.host.replaceChildren();
|
||||
this.controls = [];
|
||||
const groups = new Map();
|
||||
fields.forEach(field => {
|
||||
if (!Array.isArray(field.path) || field.hidden) return;
|
||||
const group = field.group || '';
|
||||
if (!groups.has(group)) {
|
||||
const grid = el('div', {class: 'form-grid'});
|
||||
const section = group ? el('fieldset', {class: 'form-section'}, el('legend', {text: group}), grid) : grid;
|
||||
this.host.append(section);
|
||||
groups.set(group, grid);
|
||||
}
|
||||
const entry = control(field, this.context);
|
||||
entry.root.classList.add('field-input');
|
||||
const boolean = ['boolean', 'bool', 'checkbox'].includes(field.type);
|
||||
const wide = ['id_counts', 'counts', 'reserves', 'multiselect'].includes(field.type);
|
||||
const row = el('label', {class: `field${boolean ? ' checkbox-field' : ''}${wide ? ' field-wide' : ''}`, title: field.help || field.description || ''});
|
||||
if (entry.root.tagName === 'DIV') {
|
||||
const fieldRow = el('div', {class: `field${wide ? ' field-wide' : ''}`}, el('span', {class: 'field-label', text: field.label}), entry.root);
|
||||
groups.get(group).append(fieldRow);
|
||||
entry.row = fieldRow;
|
||||
} else {
|
||||
row.append(el('span', {class: 'field-label', text: field.label}), entry.root);
|
||||
groups.get(group).append(row);
|
||||
entry.row = row;
|
||||
}
|
||||
if (field.help || field.description) groups.get(group).append(el('span', {class: 'field-help', text: field.help || field.description}));
|
||||
this.controls.push(entry);
|
||||
});
|
||||
this.signature = signature;
|
||||
}
|
||||
this.host.hidden = !fields.length;
|
||||
this.controls.forEach(entry => {
|
||||
const latest = fields.find(field => pathKey(field.path) === pathKey(entry.field.path));
|
||||
if (latest) Object.assign(entry.field, latest);
|
||||
entry.sync();
|
||||
entry.row.dataset.dirty = String(Boolean(this.context.dirty?.(entry.field.path)));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Keep native number behavior only for the number field the user is editing.
|
||||
document.addEventListener('wheel', event => {
|
||||
const input = event.target.closest?.('input[type=number]');
|
||||
if (input && document.activeElement !== input) event.preventDefault();
|
||||
}, {passive: false});
|
||||
@@ -0,0 +1,50 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light">
|
||||
<title>牧羊人之心牧场助手 · Web</title>
|
||||
<link rel="icon" href="data:,">
|
||||
<link rel="stylesheet" href="/static/styles.css">
|
||||
<script type="module" src="/static/app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app" class="workbench" aria-label="牧羊人之心牧场助手">
|
||||
<header class="window-header">
|
||||
<nav id="menu-bar" class="menu-bar" aria-label="主菜单">
|
||||
<details class="menu"><summary accesskey="a">账号<span class="access-key">(A)</span></summary><div class="menu-popup">
|
||||
<button data-command="add-account">新增账号…</button><button data-command="add-demo">新增离线演示账号</button>
|
||||
<button data-command="remove-account">移除当前账号…</button><hr><button data-command="logout">退出游戏登录</button><button data-command="forget-login">退出并清除登录记录…</button><hr><button data-command="admin-logout">退出管理工作台</button>
|
||||
</div></details>
|
||||
<details class="menu"><summary accesskey="r">策略<span class="access-key">(R)</span></summary><div class="menu-popup">
|
||||
<button data-command="start">开启当前账号策略</button><button data-command="stop">停止当前账号策略</button><hr><button data-command="start-all">开启全部账号策略</button><button data-command="stop-all">停止全部账号策略</button>
|
||||
</div></details>
|
||||
<details class="menu"><summary accesskey="s">配置<span class="access-key">(S)</span></summary><div class="menu-popup">
|
||||
<button data-command="save">保存当前账号策略</button><button data-command="import-config">导入当前账号策略…</button><button data-command="export-config">导出当前账号策略</button><hr><button data-command="import-yields">导入收益 CSV / XLSX…</button><button data-command="export-yields">下载收益 CSV</button>
|
||||
</div></details>
|
||||
<details class="menu"><summary accesskey="h">帮助<span class="access-key">(H)</span></summary><div class="menu-popup"><button data-command="updates">检查版本更新…</button><button data-command="debug">调试日志</button><button data-command="about">关于…</button></div></details>
|
||||
</nav>
|
||||
<span class="window-title">牧羊人之心牧场助手 <span id="app-version">2.0.0.dev1</span></span>
|
||||
<span id="access-mode" class="muted">正在连接本地服务</span>
|
||||
</header>
|
||||
<div class="account-bar"><div id="account-tabs" class="account-tabs" role="tablist" aria-label="账号"></div><button id="add-account" class="compact" title="新增账号">+ 新增账号</button></div>
|
||||
<div class="toolbar" aria-label="角色状态和运行控制">
|
||||
<div class="player-line"><span id="connection" class="connection">未登录</span><strong id="player-name">—</strong><span>等级 <b id="player-level">—</b></span><span class="experience">经验 <b id="player-exp">—</b><progress id="experience-progress" max="1" value="0" aria-label="角色经验"></progress></span><span>金币 <b id="player-money">—</b></span><span>氪金 <b id="player-ke">—</b></span><span>体力 <b id="player-ti">—</b></span></div>
|
||||
<div class="run-controls"><label>刷新 <select id="refresh-interval" aria-label="随机刷新间隔" title="整体刷新完成后,从 0 到所选上限随机等待;空坑装填与到期同步独立执行"><option value="30">随机30秒</option><option value="60">随机60秒</option><option value="120">随机2分钟</option><option value="300">随机5分钟</option></select></label><button id="strategy-toggle" class="run-button" disabled>开启</button><button id="refresh">刷新 / 预览策略</button><button id="debug-toggle">调试日志</button><button id="log-toggle" aria-expanded="true" aria-controls="log-panel">隐藏日志</button></div>
|
||||
</div>
|
||||
<div class="summary-line"><span id="data-summary">等待连接服务</span><span id="save-status" role="status">配置未载入</span></div>
|
||||
<main id="workspace" class="workspace">
|
||||
<nav id="page-tabs" class="page-tabs" role="tablist" aria-label="功能页面"></nav>
|
||||
<div id="page-host" class="page-host"><div class="initial-state" role="status">正在载入工作台…</div></div>
|
||||
</main>
|
||||
<div id="log-resizer" class="log-resizer" role="separator" tabindex="0" aria-label="调整日志高度" aria-orientation="horizontal" aria-valuemin="64" aria-valuemax="480" aria-valuenow="150" title="上下拖动调整日志高度;也可使用方向键"></div>
|
||||
<section id="log-panel" class="log-panel" aria-label="运行日志"><div class="log-toolbar"><strong id="log-heading">运行日志</strong><label><input id="debug-log" type="checkbox">调试 / 脱敏</label><label><input id="log-follow" type="checkbox" checked>自动滚动</label><span id="log-count" class="muted"></span><span class="spacer"></span><button id="download-log" class="small">下载日志</button><button id="clear-log" class="small">清空显示</button></div><div id="log-lines" class="log-lines" tabindex="0" role="log" aria-live="off" aria-label="日志内容"></div></section>
|
||||
<footer class="status-bar"><span id="status-text" role="status">连接中</span><span id="job-status" class="muted"></span><span class="spacer"></span><span>游戏 <span id="game-version">1.9.68</span></span><span id="clock"></span></footer>
|
||||
</div>
|
||||
<div id="notice" class="notice" role="status" hidden></div>
|
||||
<dialog id="action-dialog" aria-labelledby="dialog-title"><form id="dialog-form"><header class="dialog-header"><h1 id="dialog-title"></h1><button type="button" class="dialog-close" aria-label="关闭对话框">×</button></header><div id="dialog-content" class="dialog-content"></div><p id="dialog-error" class="error-text" role="alert" hidden></p><footer class="dialog-footer"><button type="button" id="dialog-cancel">取消</button><button type="submit" id="dialog-confirm" class="primary">确认</button></footer></form></dialog>
|
||||
<dialog id="auth-dialog" aria-labelledby="auth-title"><form id="auth-form"><h1 id="auth-title">登录管理工作台</h1><p>请输入此 Web 工作台的管理密码。</p><label class="field">管理密码<input id="admin-password" type="password" autocomplete="current-password" required></label><p id="auth-error" class="error-text" role="alert" hidden></p><div class="dialog-footer"><button type="submit" class="primary">登录</button></div></form></dialog>
|
||||
<noscript>此工作台需要启用 JavaScript 才能连接本地服务。</noscript>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,357 @@
|
||||
import {el, $, $$, textValue, number, chinaTime, getPath, pathKey, optionsList, detailsList, tabKeys, empty} from './dom.js';
|
||||
import {PolicyForm, control} from './forms.js';
|
||||
import {DataTable, GroupedTables} from './table.js';
|
||||
import {dialog, contextMenu, notice} from './ui.js';
|
||||
|
||||
export const PAGES = [
|
||||
['login', '登录'], ['incubator', '培育室'], ['bag', '背包'], ['ranch', '牧场'], ['daily', '每日事务'],
|
||||
['hatching', '自动孵蛋'], ['mainline', '自动主线'], ['battles', '战斗记录'], ['gifts', '自动赠礼'],
|
||||
['commissions', '自动委托'], ['exploration', '自动探险'], ['maps', '自动扫荡'], ['statistics', '数据分析'], ['plans', '执行计划'], ['yields', '收益资料'],
|
||||
];
|
||||
|
||||
export const initialQuery = page => page === 'bag' ? {category: 'eggs'} : page === 'mainline' ? {category: 'mainline', state: 'current'} : page === 'ranch' ? {grouped: false} : page === 'maps' ? {category: 'all', only_unlocked: true} : {};
|
||||
|
||||
class LoginPage {
|
||||
constructor(host, page) {
|
||||
this.page = page;
|
||||
this.root = el('div', {class: 'login-layout'});
|
||||
this.account = el('input', {type: 'text', name: 'game-account', autocomplete: 'username', 'aria-label': '游戏账号'});
|
||||
this.password = el('input', {type: 'password', name: 'game-password', autocomplete: 'current-password', 'aria-label': '游戏密码'});
|
||||
this.remember = el('input', {type: 'checkbox', checked: true});
|
||||
const show = el('input', {type: 'checkbox'});
|
||||
this.showPassword = show;
|
||||
show.addEventListener('change', () => { this.password.type = show.checked ? 'text' : 'password'; });
|
||||
const field = (label, input) => el('label', {class: 'field'}, el('span', {class: 'field-label', text: label}), input);
|
||||
const login = el('button', {type: 'submit', text: '账号密码登录 / 获取区服', class: 'primary'});
|
||||
this.loginButton = login;
|
||||
const form = el('form', {class: 'policy-form'}, field('第一步:游戏账号', this.account), field('密码', this.password),
|
||||
el('div', {class: 'login-options'}, el('label', {}, this.remember, '记住账号和密码'), el('label', {}, show, '显示密码')),
|
||||
el('div', {class: 'login-actions'}, login));
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
if (!this.account.value.trim()) { this.account.focus(); return; }
|
||||
const payload = {account: this.account.value.trim(), password: this.password.value, remember: this.remember.checked};
|
||||
this.password.value = '';
|
||||
login.disabled = true;
|
||||
try { const result = await page.perform('login', payload); if (result) this.update(result); }
|
||||
catch (error) { page.error(error); }
|
||||
finally { login.disabled = false; }
|
||||
});
|
||||
this.servers = el('select', {'aria-label': '区服 / 角色'}, el('option', {value: '', text: '请先获取区服'}));
|
||||
this.enter = el('button', {type: 'button', text: '进入选中区服', disabled: true, onClick: () => page.perform('enter_server', {server_id: this.servers.value}).catch(page.error)});
|
||||
this.saved = el('select', {'aria-label': '已保存的账号 / 区服 / 角色'}, el('option', {value: '', text: '成功读取角色后自动保存会话'}));
|
||||
this.restore = el('button', {type: 'button', text: '恢复选中会话(无需重新输密码)', disabled: true, onClick: () => page.perform('restore_session', {session_id: this.saved.value}).catch(page.error)});
|
||||
this.root.append(form,
|
||||
field('第二步:区服 / 角色', el('div', {class: 'server-row'}, this.servers, this.enter)),
|
||||
el('p', {class: 'info-note', text: '账号验证 → 获取官方区服 → 选择区服 → 进入区服 → 读取角色。登录后自动刷新状态,配置功能后开启顶部策略。'}),
|
||||
el('div', {class: 'session-block policy-form'}, field('已保存账号 / 区服 / 角色', this.saved), el('div', {class: 'login-actions'}, this.restore)),
|
||||
el('div', {class: 'page-toolbar'}, el('button', {type: 'button', text: '退出登录', onClick: () => page.perform('logout').catch(page.error)}),
|
||||
el('button', {type: 'button', text: '退出并清除登录记录…', onClick: () => page.options.command('forget-login', page.account)})),
|
||||
el('p', {class: 'info-note', text: '记住的账号密码和登录会话由服务端加密保存。浏览器不会保存游戏凭据。退出或恢复会话后,策略保持关闭。'}));
|
||||
host.append(this.root);
|
||||
}
|
||||
|
||||
update(data) {
|
||||
const login = data.login || data.details?.login || data;
|
||||
if (login.account && !this.account.value && document.activeElement !== this.account) this.account.value = login.account;
|
||||
if (login.has_saved_password !== undefined) this.password.placeholder = login.has_saved_password ? '已在服务端加密保存;留空使用已保存密码' : '输入游戏密码';
|
||||
if (Array.isArray(login.servers)) this.updateOptions(this.servers, login.servers.map(server => ({value: server.id ?? server.server_id, label: `${server.name}${server.role_name ? ` · ${server.role_name}` : ''}`})), '请先获取区服');
|
||||
if (Array.isArray(login.saved_sessions)) this.updateOptions(this.saved, login.saved_sessions.map(session => ({value: session.id ?? session.session_id, label: session.label || [session.account, session.server_name || session.server, session.role_name || session.name].filter(Boolean).join(' · ')})), '暂无已保存会话');
|
||||
this.enter.disabled = !this.servers.value;
|
||||
this.restore.disabled = !this.saved.value;
|
||||
}
|
||||
|
||||
updateOptions(select, options, placeholder) {
|
||||
const signature = JSON.stringify(options);
|
||||
if (select.dataset.signature === signature) return;
|
||||
const previous = select.value;
|
||||
select.replaceChildren(...options.map(option => el('option', {value: option.value, text: option.label})));
|
||||
if (!options.length) select.append(el('option', {value: '', text: placeholder}));
|
||||
if (options.some(option => String(option.value) === previous)) select.value = previous;
|
||||
select.dataset.signature = signature;
|
||||
}
|
||||
|
||||
clearPassword() { this.password.value = ''; this.password.type = 'password'; this.showPassword.checked = false; }
|
||||
}
|
||||
|
||||
export class PageView {
|
||||
constructor(account, key, options) {
|
||||
this.account = account;
|
||||
this.key = key;
|
||||
this.options = options;
|
||||
this.query = initialQuery(key);
|
||||
this.filters = new Map();
|
||||
this.data = null;
|
||||
this.root = el('section', {class: 'page-panel', role: 'tabpanel', 'aria-label': PAGES.find(page => page[0] === key)[1], 'data-page': key, hidden: true});
|
||||
this.header = el('div', {class: 'page-header'});
|
||||
this.title = el('h2', {text: PAGES.find(page => page[0] === key)[1]});
|
||||
this.loading = el('span', {class: 'page-loading', role: 'status', text: '正在读取…', 'data-loading': 'true'});
|
||||
this.header.append(this.title, this.loading);
|
||||
this.errorBox = el('div', {class: 'page-error', role: 'alert', hidden: true});
|
||||
this.error = error => { this.showError(error.message || String(error)); notice(error.message || String(error), true); };
|
||||
this.subtabs = el('div', {class: 'subtabs', role: 'tablist', 'aria-label': '子页面', hidden: true});
|
||||
this.filterHost = el('div', {class: 'filter-bar'});
|
||||
this.summary = el('p', {class: 'page-summary'});
|
||||
this.runtimeStatus=el('div',{class:'page-summary',hidden:true});
|
||||
this.formHost = el('div', {class: 'policy-form'});
|
||||
this.actionsHost = el('div', {class: 'page-toolbar'});
|
||||
this.content = el('div', {class: 'page-content'});
|
||||
this.notes = el('div', {class: 'info-note'});
|
||||
this.context = {get: (path, fallback) => getPath(account.config, path, fallback), set: (path, value, field, row) => options.edit(account, path, value, field, row),
|
||||
dirty: path => account.edits.has(pathKey(path)), onError: this.error, onSelection: () => this.syncActions(),
|
||||
onContext: (event, selected, row) => this.openContext(event, selected, row), onDetail: row => this.showDetail(row)};
|
||||
this.form = new PolicyForm(this.formHost, this.context);
|
||||
this.root.append(this.header, this.errorBox, this.subtabs, this.filterHost, this.summary, this.runtimeStatus, this.formHost, this.actionsHost, this.content, this.notes);
|
||||
if (key === 'login') this.login = new LoginPage(this.content, this);
|
||||
tabKeys(this.subtabs, '.subtab');
|
||||
}
|
||||
|
||||
perform(operation, payload = {}) { return this.options.perform(this.account, operation, payload, {page: this}); }
|
||||
showError(message) { this.errorBox.replaceChildren(el('span', {text: message}), el('button', {text: '重新读取', type: 'button', onClick: () => this.options.load(this, true)})); this.errorBox.hidden = false; }
|
||||
clearError() { this.errorBox.hidden = true; }
|
||||
|
||||
setQuery(key, value) {
|
||||
if (this.query[key] === value) return;
|
||||
this.query[key] = value;
|
||||
this.generation = (this.generation || 0) + 1;
|
||||
clearTimeout(this.queryTimer);
|
||||
this.queryTimer = setTimeout(() => this.options.load(this, true), key === 'search' ? 220 : 0);
|
||||
}
|
||||
|
||||
updateFilters(filters) {
|
||||
const included = new Set();
|
||||
filters.forEach(field => {
|
||||
if (this.key === 'bag' && field.key === 'category') return;
|
||||
included.add(field.key);
|
||||
if (!Object.hasOwn(this.query, field.key)) this.query[field.key] = field.value;
|
||||
let item = this.filters.get(field.key);
|
||||
const signature = JSON.stringify({...field, value: undefined});
|
||||
if (!item || item.signature !== signature && !item.root.contains(document.activeElement)) {
|
||||
const entry = control({...field, type: field.type === 'text' ? 'text' : field.type, path: [field.key]}, {
|
||||
get: () => this.query[field.key] ?? field.value,
|
||||
set: (_, value) => this.setQuery(field.key, value), onError: this.error,
|
||||
});
|
||||
if (field.key === 'search') { entry.root.type = 'search'; entry.root.placeholder = this.key === 'maps' ? '关卡、名称或掉落物品' : '按名称或编号筛选'; }
|
||||
const root = el('label', {}, el('span', {text: field.label}), entry.root);
|
||||
item?.root.remove();
|
||||
item = {root, entry, signature};
|
||||
this.filters.set(field.key, item);
|
||||
this.filterHost.append(root);
|
||||
}
|
||||
item.entry.sync();
|
||||
});
|
||||
for (const [key, item] of this.filters) if (!included.has(key)) { item.root.remove(); this.filters.delete(key); }
|
||||
this.filterHost.hidden = !included.size;
|
||||
}
|
||||
|
||||
updateSubtabs(data) {
|
||||
let tabs = data.tabs || [];
|
||||
if (this.key === 'bag') tabs = [{key:'eggs',title:'魔物蛋'}, {key:'usable',title:'可使用'}, {key:'consumables',title:'消耗品'}, {key:'materials',title:'材料'}, {key:'other',title:'其他'}, {key:'equipment',title:'装备'}];
|
||||
if (!tabs.length && this.key === 'hatching') tabs = ['孵蛋策略','牧场策略','喂养策略'].map(title => ({key:title,title}));
|
||||
if (!tabs.length && this.key === 'mainline') tabs = [{key:'tasks',title:'任务状态'}, {key:'policy',title:'推进策略'}];
|
||||
const signature = JSON.stringify(tabs);
|
||||
if (this.tabSignature !== signature) {
|
||||
if (!this.activeSubtab || !tabs.some(tab => tab.key === this.activeSubtab)) this.activeSubtab = this.key === 'bag' ? this.query.category || tabs[0]?.key : tabs[0]?.key;
|
||||
this.subtabs.replaceChildren(...tabs.map(tab => el('button', {type: 'button', class: 'subtab', role: 'tab', 'data-key': tab.key, text: tab.title || tab.label,
|
||||
onClick: () => { this.activeSubtab = tab.key; if (this.key === 'bag') this.setQuery('category', tab.key); this.render(this.data || data); }})));
|
||||
this.tabSignature = signature;
|
||||
}
|
||||
$$('.subtab', this.subtabs).forEach(button => { const selected = button.dataset.key === this.activeSubtab; button.setAttribute('aria-selected', selected); button.tabIndex = selected ? 0 : -1; });
|
||||
this.subtabs.hidden = !tabs.length;
|
||||
}
|
||||
|
||||
selectedRows() { return this.table?.selectedRows() || []; }
|
||||
|
||||
updateActions(actions) {
|
||||
const operations = [...actions];
|
||||
if(this.key==='hatching'){
|
||||
if(this.data?.details?.preset)operations.push({operation:'apply_preset',label:this.data.details.preset.label});
|
||||
operations.push({operation:'configure_bag',label:'去背包配置孵蛋规则'});
|
||||
}
|
||||
if(this.key==='gifts')operations.push({operation:'configure_bag',label:'去背包选择物品'},{operation:'configure_ranch',label:'去牧场选择目标'});
|
||||
if(this.key==='ranch')operations.push({operation:'reveal_breakthrough',label:'潜能突破设置'});
|
||||
if (this.key === 'yields') {
|
||||
if (!operations.some(action => action.operation === 'import_yields')) operations.push({operation: 'import_yields', label: '导入自定义 CSV / XLSX'});
|
||||
operations.push({operation: 'download_yields', label: '下载收益 CSV'});
|
||||
}
|
||||
if (this.key === 'maps') operations.push({operation: 'expand_regions', label: '展开地区'}, {operation: 'collapse_regions', label: '折叠地区'});
|
||||
const signature = JSON.stringify(operations);
|
||||
if (signature !== this.actionSignature) {
|
||||
this.actionsHost.replaceChildren();
|
||||
operations.filter(action => !['login', 'enter_server', 'restore_session', 'logout', 'forget_login'].includes(action.operation)).forEach(action => {
|
||||
const currencies = action.currencies ? optionsList(action.currencies) : [null];
|
||||
currencies.forEach(currency => {
|
||||
const button = el('button', {type: 'button', text: `${action.label}${currency ? `(${currency.label})` : ''}`, 'data-operation': action.operation,
|
||||
'data-selection': action.selection, onClick: () => this.options.action(this, action, currency?.value).catch(this.error)});
|
||||
this.actionsHost.append(button);
|
||||
});
|
||||
});
|
||||
this.actionSignature = signature;
|
||||
}
|
||||
this.syncActions();
|
||||
}
|
||||
|
||||
syncActions() {
|
||||
const selected = this.selectedRows().length > 0;
|
||||
$$('button[data-selection]', this.actionsHost).forEach(button => { button.disabled = !selected; });
|
||||
}
|
||||
|
||||
render(data, loading = false) {
|
||||
if (!data) { this.loading.textContent = '正在读取…'; this.loading.dataset.loading = 'true'; return; }
|
||||
this.data = data;
|
||||
this.loading.dataset.loading = String(loading);
|
||||
this.loading.textContent = loading ? '后台更新中…' : '已载入';
|
||||
this.updateSubtabs(data);
|
||||
this.updateFilters(data.filters || []);
|
||||
this.summary.textContent = typeof data.summary === 'string' ? data.summary : textValue(data.summary || '');
|
||||
this.updateRuntimeStatus(data.details || {});
|
||||
let fields = data.form || this.options.schema(this.key);
|
||||
fields=fields.map(field=>field.path?.[0]==='policy'&&field.path[1]==='buy_ten'?{...field,disabled:!this.account.config?.policy?.allow_single_draw}:field);
|
||||
if (this.key === 'hatching' && this.activeSubtab) fields = fields.filter(field => !field.group || field.group === this.activeSubtab);
|
||||
const policyTab = this.key === 'mainline' && ['policy', 'settings', '推进策略'].includes(this.activeSubtab);
|
||||
this.form.update(this.key === 'mainline' && !policyTab ? [] : fields);
|
||||
this.updateActions(data.actions || []);
|
||||
if (this.login) { this.login.update(data); return; }
|
||||
this.content.hidden = policyTab;
|
||||
if (policyTab) return;
|
||||
const notes = data.notes || data.details?.note || data.details?.notes || data.details?.help || data.hint || '';
|
||||
const noteText=Array.isArray(notes)?notes.join('\n'):typeof notes==='string'?notes:textValue(notes);
|
||||
this.notes.textContent=[noteText,...(data.battle_mode?[data.battle_mode.label,data.battle_mode.damage_rule]:[])].filter(Boolean).join('\n');
|
||||
this.notes.style.whiteSpace = 'pre-wrap';
|
||||
this.notes.hidden = !this.notes.textContent;
|
||||
const groups = data.groups || [];
|
||||
const grouped = this.key === 'maps' || this.key === 'ranch' && (this.query.grouped === true || this.query.grouped === 'true');
|
||||
const mode = this.key === 'statistics' ? 'statistics' : grouped ? 'grouped' : 'table';
|
||||
if (this.contentMode !== mode) {
|
||||
if (this.content.contains(document.activeElement)) return;
|
||||
this.content.replaceChildren();
|
||||
this.contentMode = mode;
|
||||
this.table = mode === 'grouped' ? new GroupedTables(this.content, this.context, {collapsed: this.key === 'maps'}) : mode === 'table' ? new DataTable(this.content, this.context, {emptyMessage: this.key === 'plans' ? '当前没有执行计划。请配置策略并刷新 / 预览,查看下一步或等待原因。' : '当前筛选下没有条目。可调整筛选,或登录后刷新状态。'}) : null;
|
||||
if (mode === 'statistics') this.buildStatistics();
|
||||
}
|
||||
if (mode === 'statistics') this.renderStatistics(data);
|
||||
else if (grouped) {
|
||||
const labels = Object.fromEntries(groups.map(group => [String(group.id), group.label || group.name]));
|
||||
this.table.update(data.columns || [], data.rows || [], row => row.group ?? row.region ?? row.city_name ?? row.city ?? '其他', labels, Object.fromEntries(groups.map(group=>[String(group.id),group])));
|
||||
} else this.table.update(data.columns || [], data.rows || []);
|
||||
}
|
||||
|
||||
updateRuntimeStatus(details) {
|
||||
const lines=[];
|
||||
if(this.key==='hatching'){
|
||||
if(this.activeSubtab==='喂养策略' && Array.isArray(details.feed_status))lines.push(['feed_status','当前喂养状态:'+textValue(details.feed_status[1])]);
|
||||
if(this.activeSubtab==='孵蛋策略' && details.last_draw!==undefined)lines.push(['last_draw','最近抽蛋:'+textValue(details.last_draw)]);
|
||||
}
|
||||
if(this.key==='gifts' && Object.hasOwn(details,'next_ready_at')){
|
||||
const ready=details.next_ready_at;
|
||||
lines.push(['next_ready_at',ready===null?'下次赠礼:当前没有符合条件的目标或物品,等待状态更新':'下次可赠礼:'+chinaTime(ready,{date:true})+'(北京时间)']);
|
||||
}
|
||||
this.runtimeStatus.replaceChildren(...lines.map(([key,text])=>el('p',{'data-view-status':key,text})));
|
||||
this.runtimeStatus.hidden=!lines.length;
|
||||
}
|
||||
|
||||
showDetail(row) {
|
||||
const data = this.data.details?.[row.id] || row.details;
|
||||
if (!data) return;
|
||||
const labels = {name:'名称',species:'种类',id:'魔物ID',level:'等级 / 当前上限',quality:'资质 攻/防/血/敏',reference_stats:'参考攻击 / 防御 / 生命 / 敏捷',growth:'成长数值',likes:'喜欢的物品',feel:'好感 / 上限',feed_exp:'喂养经验',scope:'管理范围'};
|
||||
const title=this.key==='ranch'?'魔物详情':this.key==='mainline'?'任务详情':this.key==='battles'?'战斗详情':'详情';
|
||||
dialog(title, el('div', {class:'detail-sections'}, detailsList(data, labels), this.key==='ranch'?el('p', {class:'info-note',text:'参考属性不含装备、羁绊或全局加成。'}):null), {info:true});
|
||||
}
|
||||
|
||||
openContext(event, selected, row) {
|
||||
const items = [{label:'刷新本页',run:()=>this.perform('refresh',{page:this.key})}];
|
||||
if (this.key === 'ranch') {
|
||||
items.push({label:'查看魔物详情',run:()=>this.showDetail(row)});
|
||||
(this.data.actions || []).filter(action => ['lock','unlock','sell','feed'].includes(action.operation)).forEach(action => items.push({label:action.label,disabled:!selected.length,run:()=>this.options.action(this,action)}));
|
||||
}
|
||||
(this.data.actions || []).filter(action => action.operation === 'quote_expansion').forEach(action => optionsList(action.currencies).forEach(currency => items.push({label:`${action.label}(${currency.label})…`,run:()=>this.options.action(this,action,currency.value)})));
|
||||
contextMenu(event,items);
|
||||
}
|
||||
|
||||
buildStatistics() {
|
||||
this.statisticsPicker = el('div', {class:'statistics-picker',role:'listbox','aria-label':'关卡 / 难度'});
|
||||
this.chart = el('div',{class:'chart-scroll','aria-label':'掉落统计图'});
|
||||
this.statisticsTableHost = el('div',{class:'statistics-table-host'});
|
||||
this.statisticsTable = new DataTable(this.statisticsTableHost,this.context,{selection:false,emptyMessage:'所选关卡尚无已确认样本;完成扫荡后将显示实际统计。'});
|
||||
this.statisticsSummary = el('p',{class:'page-summary'});
|
||||
this.content.append(el('div',{class:'statistics-layout'},this.statisticsPicker,el('div',{class:'statistics-main'},this.statisticsSummary,this.chart,this.statisticsTableHost)));
|
||||
}
|
||||
|
||||
renderStatistics(data) {
|
||||
const stages = data.stages || data.details?.stages || data.details?.tree || [];
|
||||
const signature = JSON.stringify(stages);
|
||||
if (signature !== this.statisticsSignature) {
|
||||
const openCities=new Set($$('.statistics-city[open]',this.statisticsPicker).map(node=>node.dataset.city));
|
||||
const openStages=new Set($$('.statistics-stage[open]',this.statisticsPicker).map(node=>node.dataset.stage));
|
||||
this.statisticsPicker.replaceChildren();
|
||||
const cities = new Map();
|
||||
stages.forEach(stage => {
|
||||
const id=String(stage.city_id || '0');
|
||||
if(!cities.has(id))cities.set(id,{name:stage.city_name || `地区 ${id}`,stages:[]});
|
||||
cities.get(id).stages.push(stage);
|
||||
});
|
||||
cities.forEach((city,id)=>{
|
||||
const children=el('div',{class:'statistics-city-children'});
|
||||
const cityRoot=el('details',{class:'statistics-city','data-city':id},el('summary',{text:`${city.name}(${city.stages.length})`}),children);
|
||||
const buildCity=()=>{
|
||||
if(children.childElementCount)return;
|
||||
city.stages.forEach(stage=>{
|
||||
const levelsHost=el('div',{class:'statistics-levels'});
|
||||
const stageRoot=el('details',{class:'statistics-stage','data-stage':stage.id},el('summary',{text:`${stage.label || stage.name || stage.id} ${stage.sweep || 0} / ${stage.event || 0}`}),levelsHost);
|
||||
const buildLevels=()=>{
|
||||
if(levelsHost.childElementCount)return;
|
||||
(stage.levels || []).forEach(level=>levelsHost.append(el('button',{type:'button',role:'option','data-stat-stage':stage.id,'data-stat-level':level.level || level.id,
|
||||
text:`难度 ${level.level || level.id} 扫荡 ${level.sweep || 0} / 事件 ${level.event || 0}`,onClick:()=>{
|
||||
this.query.stage_id=stage.id;delete this.query.stage;this.query.level=level.level || level.id || '3';
|
||||
this.generation=(this.generation || 0)+1;this.options.load(this,true);
|
||||
}})));
|
||||
};
|
||||
stageRoot.addEventListener('toggle',()=>{if(stageRoot.open)buildLevels();});
|
||||
if(openStages.has(stage.id)||(this.query.stage_id || this.query.stage)===stage.id){stageRoot.open=true;buildLevels();}
|
||||
children.append(stageRoot);
|
||||
});
|
||||
};
|
||||
cityRoot.addEventListener('toggle',()=>{if(cityRoot.open)buildCity();});
|
||||
if(openCities.has(id)||city.stages.some(stage=>(this.query.stage_id || this.query.stage)===stage.id)){cityRoot.open=true;buildCity();}
|
||||
this.statisticsPicker.append(cityRoot);
|
||||
});
|
||||
this.statisticsSignature = signature;
|
||||
}
|
||||
$$('[data-stat-stage]',this.statisticsPicker).forEach(button=>button.setAttribute('aria-selected',String(button.dataset.statStage===(this.query.stage_id || this.query.stage)&&button.dataset.statLevel===String(this.query.level || '3'))));
|
||||
this.statisticsPicker.hidden = !stages.length;
|
||||
this.statisticsSummary.textContent = data.details?.summary ? textValue(data.details.summary) : '';
|
||||
const rows = data.rows || [];
|
||||
this.statisticsTable.update(data.columns || [],rows);
|
||||
const metric = this.query.metric || this.query.chart_metric || 'rate';
|
||||
const series = data.chart?.series || data.chart || data.details?.chart;
|
||||
const bars = Array.isArray(series) ? series.map(item=>({label:item.label || item.name,value:item.value})) : rows.map(row=>({label:row.name || row.item_name || row.item || row.id,value:metric === 'per_stamina' ? row.per_stamina ?? row.per_ti : row.rate ?? row.drop_rate}));
|
||||
this.drawChart(bars,metric,data.chart?.max,data.chart?.empty_reason);
|
||||
}
|
||||
|
||||
drawChart(bars,metric,axisMax,emptyReason) {
|
||||
bars = bars.filter(item=>typeof item.value === 'number' && Number.isFinite(item.value));
|
||||
const signature = JSON.stringify([bars,metric,axisMax,emptyReason]);
|
||||
if (this.chartSignature === signature) return;
|
||||
this.chartSignature = signature;
|
||||
this.chart.replaceChildren();
|
||||
if (!bars.length) { this.chart.append(empty(emptyReason || '暂无已确认的统计样本。图表将随实际扫荡记录生成。')); return; }
|
||||
const ns='http://www.w3.org/2000/svg', width=760, height=Math.max(120,bars.length*29+50), labelWidth=175;
|
||||
const svg=document.createElementNS(ns,'svg');
|
||||
svg.setAttribute('viewBox',`0 0 ${width} ${height}`);svg.setAttribute('class','drop-chart');svg.setAttribute('role','img');svg.setAttribute('aria-label',metric==='per_stamina'?'每点体力掉落数量':'实测掉落率');
|
||||
const title=document.createElementNS(ns,'title');title.textContent=metric==='per_stamina'?'每点体力掉落数量':'实测掉落率';svg.append(title);
|
||||
const max=typeof axisMax==='number'&&axisMax>0?axisMax:metric==='rate'?1:Math.max(...bars.map(item=>item.value),.0001)*1.15, plotWidth=width-labelWidth-85;
|
||||
for(let tick=0;tick<=4;tick++){
|
||||
const x=labelWidth+tick/4*plotWidth;
|
||||
const line=document.createElementNS(ns,'line');line.setAttribute('x1',String(x));line.setAttribute('x2',String(x));line.setAttribute('y1','24');line.setAttribute('y2',String(height-12));line.setAttribute('class','chart-grid');svg.append(line);
|
||||
const label=document.createElementNS(ns,'text');label.setAttribute('x',String(x));label.setAttribute('y','15');label.setAttribute('text-anchor','middle');label.setAttribute('class','chart-axis');label.textContent=metric==='rate'?`${Math.round(tick/4*max*100)}%`:number(tick/4*max);svg.append(label);
|
||||
}
|
||||
bars.forEach((item,index)=>{
|
||||
const y=index*29+33;
|
||||
const text=document.createElementNS(ns,'text');text.setAttribute('x',String(labelWidth-10));text.setAttribute('y',String(y+13));text.setAttribute('text-anchor','end');text.setAttribute('class','chart-label');text.textContent=String(item.label);svg.append(text);
|
||||
const rect=document.createElementNS(ns,'rect');rect.setAttribute('x',String(labelWidth));rect.setAttribute('y',String(y));rect.setAttribute('width',String(item.value/max*plotWidth));rect.setAttribute('height','19');rect.setAttribute('class','chart-bar');
|
||||
const tip=document.createElementNS(ns,'title');tip.textContent=`${item.label}:${metric==='per_stamina'?number(item.value):(item.value*100).toFixed(2)+'%'}`;rect.append(tip);svg.append(rect);
|
||||
const value=document.createElementNS(ns,'text');value.setAttribute('x',String(labelWidth+item.value/max*plotWidth+7));value.setAttribute('y',String(y+13));value.setAttribute('class','chart-value');value.textContent=metric==='per_stamina'?number(item.value):(item.value*100).toFixed(2)+'%';svg.append(value);
|
||||
});
|
||||
this.chart.append(svg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
:root{font-family:"Segoe UI","Microsoft YaHei UI","Microsoft YaHei",system-ui,sans-serif;font-size:13px;color:#202832;background:#f1f3f5;font-synthesis:none;color-scheme:light;--border:#cbd1d8;--muted:#55616e;--accent:#245d9b;--tint:#e8f0f9;--log-height:150px;--danger:#b3261e;--green:#20743a}
|
||||
*{box-sizing:border-box}body{margin:0}button,input,select,textarea{font:inherit;color:inherit}button,select,input[type=number],input[type=text],input[type=password],input[type=search],textarea{border:1px solid #afb8c2;border-radius:3px;background:#fff;min-height:27px}button{padding:3px 10px;cursor:pointer;white-space:nowrap;background:#f8f9fb}button:hover{background:#e9edf2;border-color:#8291a1}button:active{background:#dce4ed}button:disabled,input:disabled,select:disabled{cursor:default;opacity:.58}input,select{padding:2px 6px}input[type=checkbox]{width:14px;height:14px;min-height:0;margin:0 4px 0 0;accent-color:var(--accent);vertical-align:middle;flex-shrink:0}input[type=number]{font-variant-numeric:tabular-nums;min-width:62px;width:88px}input[type=search]{min-width:170px}select{max-width:100%}textarea{padding:6px;resize:vertical;min-height:60px}button:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible,[tabindex]:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:2px}::selection{background:#c5dbf5;color:#142b46}input,textarea{caret-color:var(--accent)}[hidden]{display:none!important}h1,h2,h3,p{margin:0}h1{font-size:16px;font-weight:600}h2,h3{font-size:14px;font-weight:600}p{line-height:1.65}a{color:var(--accent);text-underline-offset:3px}.muted{color:var(--muted);font-size:12px}.spacer{flex:1}.primary{background:#245d9b;color:#fff;border-color:#245d9b}.primary:hover{background:#1c4d83;color:#fff}.danger{color:#94231d;border-color:#c39c99}.error-text{color:#99251e;white-space:pre-wrap;overflow-wrap:anywhere}.small,.compact{min-height:24px;padding:2px 8px;font-size:12px}
|
||||
.workbench{height:100dvh;min-height:420px;display:flex;flex-direction:column;overflow:hidden}.window-header{display:flex;align-items:center;min-height:29px;gap:16px;padding:0 10px 0 4px;border-bottom:1px solid var(--border);background:#f6f7f9}.window-title{font-size:12px;color:#404c59}.window-title #app-version{margin-left:5px;color:var(--muted)}#access-mode{margin-left:auto}.menu-bar{display:flex;gap:1px}.menu{position:relative}.menu>summary{list-style:none;padding:5px 9px;cursor:pointer;border-radius:2px}.menu>summary::-webkit-details-marker{display:none}.menu[open]>summary,.menu>summary:hover{background:#dfe8f3}.access-key{font-size:11px;margin-left:3px;color:var(--muted)}.menu-popup{position:absolute;top:100%;left:0;z-index:30;min-width:220px;padding:4px;background:#fff;border:1px solid #acb6c1;box-shadow:0 5px 14px #172a4026}.menu-popup button{display:block;width:100%;border:0;border-radius:0;text-align:left;background:transparent;padding:6px 12px}.menu-popup button:hover{background:var(--tint)}.menu-popup hr{border:0;border-top:1px solid var(--border);margin:4px 2px}
|
||||
.account-bar{display:flex;gap:6px;align-items:center;padding:5px 6px 0;min-height:36px;background:#e7ebef;border-bottom:1px solid var(--border)}.account-tabs{display:flex;overflow-x:auto;gap:3px;align-self:stretch;min-width:0;scrollbar-width:thin}.account-tab{border-radius:4px 4px 0 0;border:1px solid var(--border);border-bottom:0;display:flex;gap:6px;align-items:center;max-width:230px;background:#f1f3f5;min-height:30px;padding:4px 13px}.account-tab[aria-selected=true]{background:#fff;box-shadow:inset 0 2px 0 var(--accent)}.account-tab .account-label{overflow:hidden;text-overflow:ellipsis}.account-dot{width:6px;height:6px;border-radius:50%;background:#7b8490;flex-shrink:0}.account-dot.running{background:var(--green)}.account-dot.error{background:var(--danger)}#add-account{margin:0 0 5px;flex-shrink:0}.toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:8px 18px;padding:8px 8px 5px;background:#fff}.player-line{display:flex;align-items:center;flex-wrap:wrap;gap:12px;min-height:27px;flex:1 1 auto}.player-line>span{white-space:nowrap}.player-line b{font-weight:600;font-variant-numeric:tabular-nums}.player-line>strong{max-width:180px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.connection{font-size:12px;color:var(--muted)}.connection.online{color:#176331}.connection.demo{color:#805300}.experience{display:inline-flex;gap:5px;align-items:center}progress{width:58px;height:6px;accent-color:var(--accent)}progress::-webkit-progress-bar{background:#e2e7ee;border-radius:2px}progress::-webkit-progress-value{background:#467aa9;border-radius:2px}.run-controls{display:flex;align-items:center;gap:5px;flex-wrap:wrap}.run-controls>label{display:flex;align-items:center;gap:5px}.run-button{min-width:76px;font-weight:600;background:var(--green);border-color:#185b2d;color:#fff}.run-button:hover{background:#1b6332;color:#fff;border-color:#185b2d}.run-button.running{background:var(--danger);border-color:#8f1e18}.run-button.running:hover{background:#992019}.run-button:disabled{opacity:1;background:#727b82;border-color:#727b82}.summary-line{display:flex;gap:10px;align-items:center;min-height:25px;padding:2px 8px 5px;background:#fff;font-size:12px;color:var(--muted)}#data-summary{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;flex:1}#save-status{flex-shrink:0}#save-status.pending{color:#805300}#save-status.failed{color:#99251e}
|
||||
.workspace{display:flex;flex-direction:column;flex:1;min-height:155px;padding:0 6px;overflow:hidden;background:#fff}.page-tabs{display:flex;flex-shrink:0;overflow-x:auto;gap:0;border-bottom:1px solid #9eabb9;scrollbar-width:thin}.page-tab{border-radius:3px 3px 0 0;border:1px solid transparent;background:#f1f3f5;padding:6px 10px;min-height:30px;margin-right:1px;font-size:12px}.page-tab[aria-selected=true]{background:#fff;border-color:#9eabb9;border-bottom-color:#fff;color:#174d83;box-shadow:inset 0 2px 0 #245d9b;font-weight:600}.page-tab:hover{background:#e8f0f9}.page-host{flex:1;min-height:0;overflow:hidden;position:relative}.page-panel{height:100%;display:flex;flex-direction:column;overflow:auto;padding:7px 2px 4px;gap:7px;scrollbar-gutter:stable}.page-header{display:flex;gap:8px;align-items:center;flex-wrap:wrap;min-height:25px}.page-header h2{margin-right:7px}.page-summary{color:var(--muted);font-size:12px;line-height:1.6;white-space:pre-wrap;overflow-wrap:anywhere}.page-toolbar,.filter-bar{display:flex;flex-wrap:wrap;gap:5px 9px;align-items:center}.filter-bar label{display:inline-flex;gap:5px;align-items:center}.page-loading{font-size:12px;color:var(--muted);margin-left:auto}.page-loading[data-loading=true]::before{content:"";display:inline-block;width:7px;height:7px;background:#688aaf;border-radius:50%;margin-right:5px}.subtabs{display:flex;gap:2px;border-bottom:1px solid var(--border);flex-shrink:0}.subtab{background:#f0f2f5;border:1px solid var(--border);border-bottom:0;border-radius:3px 3px 0 0;font-size:12px;padding:4px 10px}.subtab[aria-selected=true]{background:#e8f0f9;color:#174d83;border-color:#94adc7}.initial-state,.empty-state{padding:24px 18px;color:var(--muted);line-height:1.8}.empty-state p{max-width:65ch}.empty-state button{margin-top:12px}.page-error{padding:8px 10px;background:#fff4f3;border:1px solid #ddbbb7;color:#8e251f;display:flex;align-items:center;gap:10px;white-space:pre-wrap}.info-note{font-size:12px;color:var(--muted);line-height:1.65;padding:5px 0;max-width:115ch}.inline-note{color:var(--muted);font-size:12px}
|
||||
.table-scroll{overflow:auto;min-height:80px;flex:1;border:1px solid var(--border);background:#fff;position:relative}.data-table{border-collapse:separate;border-spacing:0;width:100%;font-size:12px;white-space:nowrap;text-align:left;font-variant-numeric:tabular-nums}.data-table th{position:sticky;top:0;z-index:2;background:#eef1f5;color:#303d4c;font-weight:500;border-bottom:1px solid #bac4cf;border-right:1px solid #d5dbe2;height:28px;padding:3px 8px;white-space:nowrap}.data-table th button{font:inherit;border:0;background:transparent;padding:0;min-height:20px;display:flex;align-items:center;gap:6px;width:100%;text-align:left}.data-table th .sort-mark{color:#506a85;font-size:10px;min-width:8px}.data-table td{border-bottom:1px solid #e4e8ed;border-right:1px solid #eef0f3;padding:2px 7px;height:29px;max-width:300px;overflow:hidden;text-overflow:ellipsis}.data-table tr:nth-child(even)>td{background:#fafbfc}.data-table tr:hover>td{background:#f0f5fa}.data-table tr[aria-selected=true]>td{background:#dfecfa}.data-table td.number{text-align:right}.data-table td.cell-edit{padding:2px 4px;overflow:visible}.data-table td.cell-edit input[type=number]{min-height:24px;height:24px;width:76px;font-size:12px}.data-table td.cell-edit select{min-height:24px;height:24px;font-size:12px;max-width:220px}.data-table td.cell-edit input[type=text]{min-height:24px;width:140px;font-size:12px}.data-table .selection-cell{width:29px;min-width:29px;text-align:center;padding:0 5px;position:sticky;left:0;z-index:1}.data-table th.selection-cell{z-index:3}.data-table .cell-wrap{white-space:normal;min-width:190px;line-height:1.5}.data-table .cell-ellipsis{max-width:260px}.data-table .cell-boolean{color:#176331}.table-footer{display:flex;gap:12px;align-items:center;min-height:20px;font-size:12px;color:var(--muted)}.table-footer>button{margin-left:auto}.grouped-tables{display:flex;flex-direction:column;gap:5px;overflow:auto;flex:1;min-height:100px}.table-group{border:1px solid var(--border);background:#fff}.table-group>summary{cursor:pointer;font-weight:600;font-size:12px;padding:7px 9px;background:#eef1f5;position:sticky;top:0;z-index:3}.table-group>summary small{font-weight:400;color:var(--muted);margin-left:10px}.table-group .table-scroll{border:0;max-height:410px}.table-group .data-table th{top:0}.table-group .table-footer{padding:3px 8px}
|
||||
.policy-form{display:flex;flex-direction:column;gap:9px;flex-shrink:0}.form-section{margin:0;border:1px solid #d6dce3;padding:7px 10px 10px;min-width:0}.form-section legend{font-size:12px;font-weight:600;padding:0 5px;color:#344458}.form-grid{display:grid;grid-template-columns:repeat(2,minmax(270px,1fr));gap:7px 22px;max-width:1100px}.field{display:flex;align-items:center;gap:8px;min-width:0;font-size:12px}.field>.field-label{min-width:135px;flex:0 1 195px;line-height:1.5}.field>.field-input{flex:1;min-width:0;max-width:310px}.field input[type=number].field-input{max-width:130px}.field.checkbox-field{min-height:27px}.field-help{font-size:12px;color:var(--muted);line-height:1.5;display:block;grid-column:1/-1}.field-wide{grid-column:1/-1}.field.invalid input{border-color:var(--danger)}.field[data-dirty=true] .field-label::after{content:" ·";color:#805300}.inline-editor{display:inline-flex;align-items:center;gap:3px}.multi-select{display:flex;flex-wrap:wrap;gap:4px 12px;padding:4px 0;min-width:0}.multi-select label{display:inline-flex;align-items:center;gap:2px}.member-selects{display:flex;gap:3px;flex-wrap:wrap;align-items:center}.member-selects select{width:165px}.member-selects button{min-height:24px}.login-layout{max-width:790px;display:flex;flex-direction:column;gap:10px;padding:4px 8px}.login-layout .form-grid{grid-template-columns:1fr}.login-layout input[type=text],.login-layout input[type=password]{width:320px;max-width:100%}.login-layout .field>.field-label{flex-basis:145px;min-width:145px}.login-layout .field>.field-input{max-width:none}.login-options{display:flex;gap:14px;margin-left:153px;font-size:12px}.login-actions{display:flex;gap:6px;margin-left:153px;flex-wrap:wrap}.server-row{display:flex;gap:6px;flex:1;min-width:0}.server-row select{min-width:180px;flex:1}.session-block{margin-top:4px;padding-top:14px;border-top:1px solid var(--border)}.demo-note{font-size:12px;color:#805300;background:#fff9ea;border:1px solid #e1d0a7;padding:6px 9px;line-height:1.6}.detail-list{display:grid;grid-template-columns:max-content 1fr;gap:6px 18px;font-size:12px}.detail-list dt{color:var(--muted)}.detail-list dd{margin:0;white-space:pre-wrap;overflow-wrap:anywhere}.detail-sections{display:flex;flex-direction:column;gap:12px}.statistics-layout{display:flex;gap:9px;min-height:180px;flex:1}.statistics-picker{width:260px;flex-shrink:0;overflow:auto;border:1px solid var(--border)}.statistics-picker button{display:block;border:0;border-radius:0;width:100%;text-align:left;overflow:hidden;text-overflow:ellipsis;font-size:12px}.statistics-picker button[aria-selected=true]{background:var(--tint);color:#174d83}.statistics-main{min-width:0;flex:1;display:flex;flex-direction:column;gap:8px}.chart-scroll{min-height:120px;max-height:310px;overflow:auto;border:1px solid var(--border);padding:8px}.drop-chart{display:block;min-width:450px;width:100%;height:auto}.chart-label{font-size:12px;fill:#344458}.chart-value{font-size:11px;fill:#344458;font-variant-numeric:tabular-nums}.chart-bar{fill:#4979a4}.chart-grid{stroke:#e3e7ed;stroke-width:1}
|
||||
.log-resizer{height:7px;min-height:7px;cursor:row-resize;background:#e3e7ec;position:relative;border-top:1px solid #b8c1cb;border-bottom:1px solid #c8d0d9}.log-resizer::after{content:"";position:absolute;width:34px;height:2px;background:#8f9ba8;left:calc(50% - 17px);top:2px}.log-resizer:hover{background:#cedbe9}.log-panel{height:var(--log-height);min-height:64px;max-height:55vh;display:flex;flex-direction:column;background:#fff}.log-toolbar{display:flex;gap:13px;align-items:center;padding:3px 8px;background:#f1f3f5;border-bottom:1px solid var(--border);min-height:29px;font-size:12px}.log-toolbar strong{font-weight:600}.log-toolbar label{display:flex;align-items:center;gap:2px}.log-lines{padding:4px 9px;overflow:auto;flex:1;font:12px/1.65 Consolas,"Microsoft YaHei UI",monospace;white-space:pre-wrap;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.log-entry{min-height:19px}.log-entry .log-time{color:#6a7480;margin-right:8px}.log-entry.error{color:#99251e}.log-entry.warning{color:#805300}.log-entry.debug{color:#55616e}.status-bar{min-height:24px;display:flex;align-items:center;gap:14px;padding:3px 8px;border-top:1px solid var(--border);background:#f1f3f5;font-size:12px;overflow:hidden;white-space:nowrap}.status-bar #status-text{overflow:hidden;text-overflow:ellipsis;max-width:50vw}.status-bar #job-status{overflow:hidden;text-overflow:ellipsis}.notice{position:fixed;right:16px;bottom:35px;max-width:min(540px,calc(100vw - 32px));background:#eef5fc;color:#1d456d;border:1px solid #99b5d1;padding:10px 14px;z-index:80;box-shadow:0 4px 14px #1b2d4326;font-size:13px;line-height:1.5;white-space:pre-wrap}.notice.error{background:#fff2f0;border-color:#d2aaa5;color:#99251e}dialog{border:1px solid #a4afbb;border-radius:5px;padding:0;max-width:min(740px,calc(100vw - 28px));width:560px;max-height:88dvh;background:#fff;color:#202832;box-shadow:0 12px 44px #172a4040}dialog::backdrop{background:#152d493d}dialog>form{display:flex;flex-direction:column;max-height:85dvh}.dialog-header{display:flex;align-items:center;gap:12px;padding:10px 14px;border-bottom:1px solid var(--border);background:#f4f6f8}.dialog-close{margin-left:auto;border:0;background:transparent;padding:0 5px;font-size:22px;line-height:1}.dialog-content{padding:14px;overflow:auto;display:flex;flex-direction:column;gap:12px;min-height:40px}.dialog-content p{font-size:13px;white-space:pre-wrap;overflow-wrap:anywhere}.dialog-content .field{align-items:flex-start}.dialog-content .field input{flex:1;min-width:0}.dialog-content .form-grid{grid-template-columns:1fr}.dialog-footer{display:flex;justify-content:flex-end;gap:7px;padding:10px 14px;border-top:1px solid var(--border);background:#f6f7f9}#dialog-error{padding:0 14px 10px}#auth-dialog{width:370px;padding:18px}#auth-dialog form{gap:13px}#auth-dialog .dialog-footer{margin:0 -18px -18px}#auth-dialog .field{display:flex;flex-direction:column;align-items:stretch;gap:6px}.context-menu{position:fixed;z-index:50;background:#fff;border:1px solid #acb6c1;box-shadow:0 5px 14px #172a4026;padding:4px;min-width:190px}.context-menu button{display:block;width:100%;text-align:left;background:transparent;border:0;border-radius:0;padding:5px 10px}.context-menu button:hover{background:var(--tint)}
|
||||
@media(min-width:1450px){.toolbar{gap:22px}.player-line{gap:18px}.page-tab{padding-left:13px;padding-right:13px}.form-grid{grid-template-columns:repeat(3,minmax(240px,1fr));max-width:1450px}.login-layout .form-grid{grid-template-columns:1fr}}
|
||||
@media(max-width:1000px){.window-title{display:none}.toolbar{gap:5px}.run-controls{width:100%}.player-line{gap:10px}.page-tab{padding-left:8px;padding-right:8px}.form-grid{grid-template-columns:repeat(2,minmax(240px,1fr))}.statistics-picker{width:220px}}
|
||||
@media(max-width:650px){:root{--log-height:120px}.workbench{min-width:340px}.window-header{gap:5px}.menu>summary{padding:5px 7px}.access-key{display:none}#access-mode{font-size:11px}.toolbar{padding:6px}.player-line{gap:7px 10px}.player-line>strong{max-width:135px}.experience progress{display:none}.run-controls{gap:4px}.run-controls>button{padding-left:7px;padding-right:7px;font-size:12px}.form-grid{grid-template-columns:1fr}.field>.field-label{min-width:120px}.field-wide{grid-column:auto}.login-layout{padding:3px}.login-layout .field{align-items:stretch;flex-direction:column;gap:4px}.login-layout .field>.field-label{flex-basis:auto;min-width:0}.login-layout input[type=text],.login-layout input[type=password]{width:100%}.login-options,.login-actions{margin-left:0}.server-row{flex-wrap:wrap}.statistics-layout{flex-direction:column}.statistics-picker{width:100%;max-height:130px}.log-toolbar{gap:7px}#download-log{display:none}.status-bar{gap:8px}.status-bar #game-version{display:none}dialog .field{flex-direction:column;align-items:stretch}dialog .field-label{flex-basis:auto}#save-status{max-width:160px;overflow:hidden;text-overflow:ellipsis}}
|
||||
@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important}}
|
||||
.page-content{display:flex;flex-direction:column;gap:7px;flex:1;min-height:0}.statistics-table-host{display:flex;flex-direction:column;flex:1;min-height:100px}.count-id{width:100px}.statistics-city>summary,.statistics-stage>summary{cursor:pointer;font-size:12px;padding:6px 7px;line-height:1.5;overflow-wrap:anywhere}.statistics-city>summary{background:#eef1f5;border-bottom:1px solid #d8dee6;font-weight:600}.statistics-stage{margin-left:10px}.statistics-stage>summary:hover{background:#edf3fa}.statistics-levels{padding-left:12px}.statistics-levels button{padding:5px 8px}.debug-json{margin:0;font:12px/1.6 Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere}.log-entry.inspectable{cursor:pointer}.log-entry.inspectable:hover{background:#e8f0f9}.member-draft-note{font-size:11px;color:#805300}.counts-lines{display:flex;flex-direction:column;gap:3px;margin-bottom:4px}
|
||||
.chart-axis{font-size:11px;fill:#55616e;font-variant-numeric:tabular-nums}
|
||||
@@ -0,0 +1,292 @@
|
||||
import {el, $, optionsList, pathKey, textValue, number} from './dom.js';
|
||||
import {control} from './forms.js';
|
||||
|
||||
export function editPath(template, row) {
|
||||
return (template || []).map(part => {
|
||||
if (typeof part !== 'string') return part;
|
||||
if (['*', '{id}', '$id', ':id'].includes(part)) return String(row.id);
|
||||
const match = part.match(/^\{(?:row\.)?([^}]+)\}$|^\$row\.(.+)$/);
|
||||
if (match) return String(row[match[1] || match[2]] ?? row.id);
|
||||
return part;
|
||||
});
|
||||
}
|
||||
|
||||
function editableSpec(column, row) {
|
||||
const edit = column.edit || row.edits?.[column.key] ? {...column.edit, ...row.edits?.[column.key]} : null;
|
||||
if (!edit) return null;
|
||||
return {...edit, path: editPath(edit.path, row), label: `${column.label} · ${row.name || row.label || row.id}`,
|
||||
options: row[edit.options_key] || row[`${column.key}_options`] || edit.options,
|
||||
disabled: edit.disabled || row[`${column.key}_disabled`] || row.editable === false};
|
||||
}
|
||||
|
||||
function createCellControl(spec, row, context, key) {
|
||||
const get = (path, fallback) => context.get(path, fallback ?? row[key]);
|
||||
const set = (path, value, field) => context.set(path, value, field, row);
|
||||
const target = ['target', 'priority_target', 'target_priority'].includes(spec.type);
|
||||
if (target) {
|
||||
const checkbox = el('input', {type: 'checkbox', 'aria-label': spec.label});
|
||||
const root = el('div', {class: 'inline-editor'}, checkbox);
|
||||
root.dataset.configPath = pathKey(spec.path);
|
||||
checkbox.addEventListener('change', () => set(spec.path, checkbox.checked ? spec.default || 100 : undefined, spec));
|
||||
const sync = () => {
|
||||
const current = context.get(spec.path);
|
||||
checkbox.checked = current !== undefined && current !== null && current !== false && current !== 0;
|
||||
checkbox.disabled = Boolean(spec.disabled);
|
||||
};
|
||||
sync();
|
||||
return {root, sync, field: spec};
|
||||
}
|
||||
if (['members', 'monster_list', 'team_members'].includes(spec.type)) {
|
||||
const root = el('div', {class: 'member-selects', 'data-config-path': pathKey(spec.path)});
|
||||
const options = optionsList(spec.options || row.member_options || row.members_options || []);
|
||||
let drafting=false;
|
||||
const hint=el('span',{class:'member-draft-note',hidden:true});
|
||||
const selects = Array.from({length: spec.count || 3}, (_, index) => {
|
||||
const select = el('select', {'aria-label': `${spec.label}${index === 0 ? '队长' : `队员${index}`}`, disabled: spec.disabled},
|
||||
el('option', {value: '', text: index === 0 ? '自动选择队长' : '自动选择队员'}),
|
||||
...options.map(option => el('option', {value: option.value, text: option.label, disabled: option.disabled})));
|
||||
select.addEventListener('change', () => {
|
||||
selects.forEach(item=>item.setCustomValidity(''));
|
||||
const slots=selects.map(item=>item.value), selected=slots.filter(Boolean).map(Number);
|
||||
if(!select.value){drafting=false;selects.forEach(item=>item.value='');hint.hidden=true;set(spec.path,[],spec);return;}
|
||||
drafting=true;
|
||||
const invalid=message=>{hint.textContent=message;hint.hidden=false;select.setCustomValidity(message);};
|
||||
if (new Set(selected).size !== selected.length) {invalid('探险队员不可重复');return;}
|
||||
if(selected.length!==3){invalid(`已选择 ${selected.length}/3 只;选满队长和两名队员后保存`);return;}
|
||||
const leader=options.find(option=>Number(option.value)===selected[0]);
|
||||
if(leader&&selected.slice(1).some(id=>(options.find(option=>Number(option.value)===id)?.level || 0)>leader.level)){invalid('队员等级不可高于队长');return;}
|
||||
drafting=false;hint.hidden=true;set(spec.path, selected, spec);
|
||||
});
|
||||
root.append(select);
|
||||
return select;
|
||||
});
|
||||
const auto = el('button', {type: 'button', class: 'small', text: '自动选三只', disabled: spec.disabled,
|
||||
title: '清除手动指定,由核心选择未被战斗队和培养目标占用的空闲魔物', onClick: () => {drafting=false;selects.forEach(item=>{item.value='';item.setCustomValidity('');});hint.hidden=true;set(spec.path, [], spec);}});
|
||||
root.append(auto,hint);
|
||||
const sync = () => {
|
||||
if(drafting)return;
|
||||
const selected = get(spec.path, []) || [];
|
||||
selects.forEach((select, index) => { if (document.activeElement !== select) select.value = String(selected[index] ?? ''); });
|
||||
};
|
||||
sync();
|
||||
return {root, sync, field: spec};
|
||||
}
|
||||
return control(spec, {get, set, onError: context.onError});
|
||||
}
|
||||
|
||||
export class DataTable {
|
||||
constructor(host, context, {selection = true, emptyMessage = '当前筛选下没有条目。'} = {}) {
|
||||
this.host = host;
|
||||
this.context = context;
|
||||
this.selection = selection;
|
||||
this.emptyMessage = emptyMessage;
|
||||
this.rows = [];
|
||||
this.nodes = new Map();
|
||||
this.selected = new Set();
|
||||
this.sort = null;
|
||||
this.table = el('table', {class: 'data-table'});
|
||||
this.head = el('thead');
|
||||
this.body = el('tbody');
|
||||
this.table.append(this.head, this.body);
|
||||
this.empty = el('div', {class: 'empty-state', text: emptyMessage});
|
||||
this.scroller = el('div', {class: 'table-scroll'}, this.table, this.empty);
|
||||
this.footer = el('div', {class: 'table-footer'});
|
||||
this.count = el('span');
|
||||
this.selectionCount = el('span');
|
||||
this.footer.append(this.count, this.selectionCount);
|
||||
host.append(this.scroller, this.footer);
|
||||
this.table.addEventListener('contextmenu', event => {
|
||||
const tr = event.target.closest('tr[data-row-id]');
|
||||
if (!tr) return;
|
||||
event.preventDefault();
|
||||
const id = tr.dataset.rowId;
|
||||
if (!this.selected.has(id)) {
|
||||
this.selected.clear();
|
||||
this.selected.add(id);
|
||||
this.syncSelection();
|
||||
}
|
||||
context.onContext?.(event, this.selectedRows(), this.rows.find(row => String(row.id) === id));
|
||||
});
|
||||
}
|
||||
|
||||
selectedRows() { return this.rows.filter(row => this.selected.has(String(row.id))); }
|
||||
|
||||
syncSelection() {
|
||||
for (const [id, item] of this.nodes) {
|
||||
item.tr.setAttribute('aria-selected', String(this.selected.has(id)));
|
||||
if (item.check) item.check.checked = this.selected.has(id);
|
||||
}
|
||||
this.selectionCount.textContent = this.selected.size ? `已选择 ${this.selected.size} 项` : '';
|
||||
if (this.allCheck) {
|
||||
const selected = this.rows.filter(row => this.selected.has(String(row.id))).length;
|
||||
this.allCheck.checked = selected > 0 && selected === this.rows.length;
|
||||
this.allCheck.indeterminate = selected > 0 && selected < this.rows.length;
|
||||
}
|
||||
this.context.onSelection?.(this.selectedRows());
|
||||
}
|
||||
|
||||
buildHead(columns) {
|
||||
this.head.replaceChildren();
|
||||
this.nodes.clear();
|
||||
this.body.replaceChildren();
|
||||
const row = el('tr');
|
||||
if (this.selection) {
|
||||
this.allCheck = el('input', {type: 'checkbox', 'aria-label': '选择当前表格全部条目'});
|
||||
this.allCheck.addEventListener('change', () => {
|
||||
this.selected.clear();
|
||||
if (this.allCheck.checked) this.rows.forEach(item => this.selected.add(String(item.id)));
|
||||
this.syncSelection();
|
||||
});
|
||||
row.append(el('th', {scope: 'col', class: 'selection-cell'}, this.allCheck));
|
||||
}
|
||||
columns.forEach(column => {
|
||||
const mark = el('span', {class: 'sort-mark', 'aria-hidden': 'true'});
|
||||
const label = column.key === 'keep_count' ? '牧场保留' : column.label;
|
||||
const button = el('button', {type: 'button', title: `按${label}排序`}, label, mark);
|
||||
const th = el('th', {scope: 'col', 'data-column': column.key}, button);
|
||||
if (column.width) th.style.minWidth = `${Number(column.width)}px`;
|
||||
button.addEventListener('click', () => {
|
||||
this.sort = {key: column.key, direction: this.sort?.key === column.key && this.sort.direction === 1 ? -1 : 1};
|
||||
this.update(this.columns, this.rows);
|
||||
});
|
||||
row.append(th);
|
||||
});
|
||||
this.head.append(row);
|
||||
}
|
||||
|
||||
update(columns = [], rows = []) {
|
||||
const signature = JSON.stringify(columns);
|
||||
if (this.signature !== signature) {
|
||||
if (this.host.contains(document.activeElement) && this.signature) return;
|
||||
this.columns = columns;
|
||||
this.signature = signature;
|
||||
this.buildHead(columns);
|
||||
}
|
||||
this.rows = rows;
|
||||
const active = new Set(rows.map(row => String(row.id)));
|
||||
for (const [id, node] of this.nodes) {
|
||||
if (!active.has(id) && !node.tr.contains(document.activeElement)) { node.tr.remove(); this.nodes.delete(id); this.selected.delete(id); }
|
||||
}
|
||||
const sorted = [...rows];
|
||||
if (this.sort) {
|
||||
const {key, direction} = this.sort;
|
||||
sorted.sort((a, b) => {
|
||||
const aValue = a[key], bValue = b[key];
|
||||
if (typeof aValue === 'number' && typeof bValue === 'number') return (aValue - bValue) * direction;
|
||||
return textValue(aValue).localeCompare(textValue(bValue), 'zh-CN', {numeric: true}) * direction;
|
||||
});
|
||||
}
|
||||
sorted.forEach((row, index) => {
|
||||
const id = String(row.id ?? index);
|
||||
let node = this.nodes.get(id);
|
||||
if (!node) {
|
||||
const tr = el('tr', {'data-row-id': id, 'aria-selected': 'false', tabindex: -1});
|
||||
const check = this.selection ? el('input', {type: 'checkbox', 'aria-label': `选择 ${row.name || row.label || id}`}) : null;
|
||||
if (check) {
|
||||
check.addEventListener('change', () => { check.checked ? this.selected.add(id) : this.selected.delete(id); this.syncSelection(); });
|
||||
tr.append(el('td', {class: 'selection-cell'}, check));
|
||||
}
|
||||
tr.addEventListener('click', event => {
|
||||
if (event.target.closest('input,select,button,a,label')) return;
|
||||
if (!event.ctrlKey && !event.metaKey && !event.shiftKey) this.selected.clear();
|
||||
this.selected.add(id);
|
||||
this.syncSelection();
|
||||
});
|
||||
tr.addEventListener('dblclick', event => {
|
||||
if (!event.target.closest('input,select,button,a,label')) this.context.onDetail?.(node.row);
|
||||
});
|
||||
node = {tr, check, cells: new Map(), row};
|
||||
this.nodes.set(id, node);
|
||||
}
|
||||
node.row = row;
|
||||
columns.forEach(column => {
|
||||
let cell = node.cells.get(column.key);
|
||||
if (!cell) {
|
||||
const td = el('td', {'data-column': column.key});
|
||||
cell = {td};
|
||||
node.cells.set(column.key, cell);
|
||||
node.tr.append(td);
|
||||
}
|
||||
const spec = editableSpec(column, row);
|
||||
if (spec) {
|
||||
const controlSignature = JSON.stringify(spec);
|
||||
if (!cell.control || cell.controlSignature !== controlSignature && !cell.td.contains(document.activeElement)) {
|
||||
cell.control = createCellControl(spec, row, this.context, column.key);
|
||||
cell.controlSignature = controlSignature;
|
||||
cell.td.replaceChildren(cell.control.root);
|
||||
cell.td.className = 'cell-edit';
|
||||
}
|
||||
cell.control?.sync();
|
||||
} else {
|
||||
const value = row[column.key];
|
||||
const text = typeof value==='number'?number(value):textValue(value);
|
||||
if (cell.td.textContent !== text) cell.td.textContent = text;
|
||||
cell.td.title = row.tooltips?.[column.key] || text;
|
||||
cell.td.className = `${typeof value === 'number' || ['number', 'integer'].includes(column.type) ? 'number ' : ''}${column.type === 'wrap' ? 'cell-wrap' : 'cell-ellipsis'}`;
|
||||
}
|
||||
});
|
||||
// Inserting a node unnecessarily can blur a focused native number input.
|
||||
const existing = this.body.children[index];
|
||||
if (existing !== node.tr && !node.tr.contains(document.activeElement)) this.body.insertBefore(node.tr, existing || null);
|
||||
});
|
||||
this.empty.hidden = Boolean(rows.length);
|
||||
this.table.hidden = !columns.length;
|
||||
this.count.textContent = `共 ${rows.length} 项`;
|
||||
for (const th of this.head.querySelectorAll('[data-column]')) {
|
||||
const activeSort = this.sort?.key === th.dataset.column;
|
||||
th.setAttribute('aria-sort', activeSort ? this.sort.direction === 1 ? 'ascending' : 'descending' : 'none');
|
||||
$('.sort-mark', th).textContent = activeSort ? this.sort.direction === 1 ? '▲' : '▼' : '';
|
||||
}
|
||||
this.syncSelection();
|
||||
}
|
||||
}
|
||||
|
||||
export class GroupedTables {
|
||||
constructor(host, context, {collapsed = true} = {}) {
|
||||
this.host = host;
|
||||
this.context = context;
|
||||
this.collapsed = collapsed;
|
||||
this.groups = new Map();
|
||||
this.host.classList.add('grouped-tables');
|
||||
}
|
||||
|
||||
update(columns, rows, groupBy, labels = {}, metadata = {}) {
|
||||
const grouped = new Map();
|
||||
rows.forEach(row => {
|
||||
const key = String(typeof groupBy === 'function' ? groupBy(row) : row[groupBy] ?? '其他');
|
||||
if (!grouped.has(key)) grouped.set(key, []);
|
||||
grouped.get(key).push(row);
|
||||
});
|
||||
for (const [key, group] of this.groups) if (!grouped.has(key)) { group.root.remove(); this.groups.delete(key); }
|
||||
grouped.forEach((items, key) => {
|
||||
let group = this.groups.get(key);
|
||||
if (!group) {
|
||||
const summary = el('summary');
|
||||
const container = el('div', {class: 'group-table'});
|
||||
const root = el('details', {class: 'table-group', open: metadata[key]?.collapsed === false || !this.collapsed}, summary, container);
|
||||
container.style.display = 'flex';
|
||||
container.style.flexDirection = 'column';
|
||||
group = {root, summary, container, table:null};
|
||||
const item=group;
|
||||
root.addEventListener('toggle',()=>{if(root.open)this.renderGroup(item);});
|
||||
this.groups.set(key, group);
|
||||
this.host.append(root);
|
||||
}
|
||||
group.summary.replaceChildren(document.createTextNode(labels[key] || key), el('small', {text: `${items.length} 项`}));
|
||||
group.columns=columns;group.items=items;
|
||||
if(group.root.open)this.renderGroup(group);
|
||||
});
|
||||
if (!grouped.size) {
|
||||
if (!this.empty) { this.empty = el('div', {class: 'empty-state', text: '当前筛选下没有条目。'}); this.host.append(this.empty); }
|
||||
}
|
||||
if (this.empty) this.empty.hidden = Boolean(grouped.size);
|
||||
}
|
||||
|
||||
renderGroup(group) {
|
||||
if(!group.table)group.table=new DataTable(group.container,this.context);
|
||||
group.table.update(group.columns || [],group.items || []);
|
||||
}
|
||||
|
||||
expand(open) { this.groups.forEach(group => { group.root.open = open; }); }
|
||||
selectedRows() { return [...this.groups.values()].flatMap(group => group.table?.selectedRows() || []); }
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import {el, $, $$} from './dom.js';
|
||||
|
||||
let noticeTimer;
|
||||
export function notice(message, error = false) {
|
||||
const node = $('#notice');
|
||||
node.textContent = message;
|
||||
node.classList.toggle('error', error);
|
||||
node.hidden = false;
|
||||
clearTimeout(noticeTimer);
|
||||
noticeTimer = setTimeout(() => { node.hidden = true; }, error ? 10000 : 4500);
|
||||
}
|
||||
|
||||
let closeCurrent;
|
||||
export function dialog(title, content, {confirm = '确认', cancel = '取消', read = () => true, danger = false, info = false} = {}) {
|
||||
closeCurrent?.();
|
||||
const root = $('#action-dialog');
|
||||
const form = $('#dialog-form');
|
||||
const confirmButton = $('#dialog-confirm');
|
||||
$('#dialog-title').textContent = title;
|
||||
$('#dialog-content').replaceChildren(content);
|
||||
$('#dialog-error').hidden = true;
|
||||
confirmButton.textContent = confirm;
|
||||
confirmButton.hidden = info;
|
||||
confirmButton.disabled = false;
|
||||
confirmButton.className = danger ? 'danger' : 'primary';
|
||||
$('#dialog-cancel').textContent = info ? '关闭' : cancel;
|
||||
const previous = document.activeElement;
|
||||
root.showModal();
|
||||
return new Promise(resolve => {
|
||||
const abort = new AbortController();
|
||||
const done = value => {
|
||||
abort.abort();
|
||||
closeCurrent = null;
|
||||
root.close();
|
||||
$('#dialog-content').replaceChildren();
|
||||
previous?.isConnected && previous.focus();
|
||||
resolve(value);
|
||||
};
|
||||
closeCurrent = () => done(null);
|
||||
root.addEventListener('cancel', event => { event.preventDefault(); done(null); }, {signal: abort.signal});
|
||||
$('#dialog-cancel').addEventListener('click', () => done(null), {signal: abort.signal});
|
||||
$('.dialog-close', root).addEventListener('click', () => done(null), {signal: abort.signal});
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
if (!form.reportValidity()) return;
|
||||
confirmButton.disabled = true;
|
||||
try { const value = await read(); if (value !== undefined) done(value); }
|
||||
catch (error) { $('#dialog-error').textContent = error.message; $('#dialog-error').hidden = false; }
|
||||
finally { confirmButton.disabled = false; }
|
||||
}, {signal: abort.signal});
|
||||
const focus = $('input:not([type=checkbox]),select,textarea', content);
|
||||
(focus || (danger ? $('#dialog-cancel') : confirmButton.hidden ? $('#dialog-cancel') : confirmButton)).focus();
|
||||
});
|
||||
}
|
||||
|
||||
export async function confirm(title, message, options = {}) {
|
||||
return Boolean(await dialog(title, el('p', {text: message}), options));
|
||||
}
|
||||
|
||||
export function contextMenu(event, items) {
|
||||
document.querySelector('.context-menu')?.remove();
|
||||
const menu = el('div', {class: 'context-menu', role: 'menu', 'aria-label': '条目操作'});
|
||||
const abort = new AbortController();
|
||||
const close = () => { menu.remove(); abort.abort(); };
|
||||
items.forEach(item => menu.append(el('button', {type: 'button', role: 'menuitem', disabled: item.disabled, text: item.label,
|
||||
onClick: () => { close(); Promise.resolve(item.run()).catch(error => notice(error.message, true)); }})));
|
||||
document.body.append(menu);
|
||||
const rect = menu.getBoundingClientRect();
|
||||
menu.style.left = `${Math.max(4, Math.min(event.clientX, innerWidth - rect.width - 5))}px`;
|
||||
menu.style.top = `${Math.max(4, Math.min(event.clientY, innerHeight - rect.height - 5))}px`;
|
||||
document.addEventListener('pointerdown', action => { if (!menu.contains(action.target)) close(); }, {capture: true, signal: abort.signal});
|
||||
document.addEventListener('keydown', action => {
|
||||
if (action.key === 'Escape') close();
|
||||
if (['ArrowDown', 'ArrowUp'].includes(action.key)) {
|
||||
const buttons = $$('button:not(:disabled)', menu), index = buttons.indexOf(document.activeElement);
|
||||
buttons[(index + (action.key === 'ArrowDown' ? 1 : -1) + buttons.length) % buttons.length]?.focus();
|
||||
action.preventDefault();
|
||||
}
|
||||
}, {signal: abort.signal});
|
||||
document.addEventListener('scroll', close, {capture: true, once: true, signal: abort.signal});
|
||||
$('button:not(:disabled)', menu)?.focus();
|
||||
}
|
||||
|
||||
export function filePicker(accept) {
|
||||
return new Promise(resolve => {
|
||||
const input = el('input', {type: 'file', accept});
|
||||
input.addEventListener('change', () => resolve(input.files[0] || null), {once: true});
|
||||
input.addEventListener('cancel', () => resolve(null), {once: true});
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
export async function fileBase64(file) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.addEventListener('load', () => resolve(String(reader.result).split(',', 2)[1]));
|
||||
reader.addEventListener('error', () => reject(new Error('无法读取所选文件,请重新选择。')));
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
"""Web-only atomic storage, portable encrypted credentials and role sessions.
|
||||
|
||||
Nothing here reads the desktop workspace or its DPAPI records. The key and
|
||||
encrypted records must be backed up together. Losing a key is an error, never an
|
||||
excuse to replace it and silently discard remembered sessions.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
|
||||
from ranch_assistant.api import Session
|
||||
|
||||
|
||||
def _identifier(value, length=32):
|
||||
if not isinstance(value, str) or not re.fullmatch(r"[a-f0-9]{%d}" % length, value):
|
||||
raise ValueError("无效的账号或会话编号")
|
||||
return value
|
||||
|
||||
|
||||
def _unlinked(path):
|
||||
path = Path(path)
|
||||
if path.is_symlink() or getattr(path, "is_junction", lambda: False)():
|
||||
raise ValueError("Web 状态目录含链接路径,已停止操作")
|
||||
return path
|
||||
|
||||
|
||||
def atomic_json(path, value):
|
||||
"""Write a complete JSON record with owner-only permissions and replacement."""
|
||||
path = _unlinked(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_name(path.name + "." + uuid.uuid4().hex + ".tmp")
|
||||
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
try:
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
|
||||
json.dump(value, stream, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
temporary.replace(path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def session_identity(session):
|
||||
owner = session.account_id or session.server_url.rstrip("/")
|
||||
raw = json.dumps([owner, session.channel, session.platform, session.server_id, session.role_id], separators=(",", ":"))
|
||||
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
class WorkspaceLock:
|
||||
"""Hold the Web data root exclusively, on Windows as well as Linux."""
|
||||
|
||||
def __init__(self, root):
|
||||
self.path = _unlinked(Path(root) / "workspace.lock")
|
||||
self.stream = self.path.open("a+b")
|
||||
self.stream.seek(0)
|
||||
if self.path.stat().st_size == 0:
|
||||
self.stream.write(b"\0")
|
||||
self.stream.flush()
|
||||
self.stream.seek(0)
|
||||
try:
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
msvcrt.locking(self.stream.fileno(), msvcrt.LK_NBLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
fcntl.flock(self.stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except OSError:
|
||||
self.stream.close()
|
||||
raise RuntimeError("Web 数据目录已由另一个服务实例使用") from None
|
||||
|
||||
def close(self):
|
||||
if self.stream.closed:
|
||||
return
|
||||
try:
|
||||
self.stream.seek(0)
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
msvcrt.locking(self.stream.fileno(), msvcrt.LK_UNLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
fcntl.flock(self.stream.fileno(), fcntl.LOCK_UN)
|
||||
finally:
|
||||
self.stream.close()
|
||||
|
||||
|
||||
class WebStore:
|
||||
def __init__(self, root):
|
||||
candidate = Path(root).absolute()
|
||||
for parent in (candidate, *candidate.parents):
|
||||
_unlinked(parent)
|
||||
self.root = candidate.resolve()
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
self.lock = threading.RLock()
|
||||
self.workspace_lock = WorkspaceLock(self.root)
|
||||
try:
|
||||
self.profiles = _unlinked(self.root / "profiles")
|
||||
self.profiles.mkdir(exist_ok=True)
|
||||
self.fernet = Fernet(self._key())
|
||||
except Exception:
|
||||
self.workspace_lock.close()
|
||||
raise
|
||||
|
||||
def _key(self):
|
||||
path = _unlinked(self.root / "web.key")
|
||||
if not path.exists():
|
||||
if next(self.profiles.glob("*/credentials.fernet"), None) or next(self.profiles.glob("*/sessions/*.fernet"), None):
|
||||
raise ValueError("缺少 Web 加密密钥,无法恢复已保存登录;请恢复原密钥")
|
||||
try:
|
||||
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
except FileExistsError:
|
||||
pass
|
||||
else:
|
||||
with os.fdopen(descriptor, "wb") as stream:
|
||||
stream.write(Fernet.generate_key())
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.chmod(path, 0o600)
|
||||
try:
|
||||
raw = path.read_bytes()
|
||||
Fernet(raw)
|
||||
except (OSError, ValueError):
|
||||
raise ValueError("Web 加密密钥无法读取,请恢复原密钥") from None
|
||||
return raw
|
||||
|
||||
def profile(self, identifier):
|
||||
folder = _unlinked(self.profiles / _identifier(identifier))
|
||||
if folder.resolve() != folder or self.profiles.resolve() != self.profiles:
|
||||
raise ValueError("账号工作区路径不合法")
|
||||
return folder
|
||||
|
||||
def accounts(self):
|
||||
with self.lock:
|
||||
path = _unlinked(self.root / "accounts.json")
|
||||
if not path.exists():
|
||||
return []
|
||||
value = json.loads(path.read_text(encoding="utf-8"))
|
||||
if not isinstance(value, dict) or value.get("schema") != 1 or not isinstance(value.get("accounts"), list):
|
||||
raise ValueError("Web 账号目录格式错误")
|
||||
entries, seen = [], set()
|
||||
for row in value["accounts"]:
|
||||
if not isinstance(row, dict) or set(row) != {"id", "label", "demo"}:
|
||||
raise ValueError("Web 账号目录格式错误")
|
||||
identifier = _identifier(row["id"])
|
||||
if identifier in seen or not isinstance(row["label"], str) or type(row["demo"]) is not bool:
|
||||
raise ValueError("Web 账号目录格式错误")
|
||||
self.profile(identifier)
|
||||
seen.add(identifier)
|
||||
entries.append(dict(row))
|
||||
return entries
|
||||
|
||||
def save_accounts(self, entries):
|
||||
with self.lock:
|
||||
atomic_json(self.root / "accounts.json", {"schema": 1, "accounts": entries})
|
||||
|
||||
def secure(self, identifier):
|
||||
return SecureStore(self, identifier)
|
||||
|
||||
def role_root(self, identifier, identity=None, *, demo=False):
|
||||
folder = self.profile(identifier)
|
||||
if identity is not None:
|
||||
roles = _unlinked(folder / "roles")
|
||||
result = _unlinked(roles / _identifier(identity, 64))
|
||||
else:
|
||||
result = _unlinked(folder / ("demo" if demo else "disconnected"))
|
||||
if not result.resolve().is_relative_to(folder):
|
||||
raise ValueError("角色工作区路径不合法")
|
||||
result.mkdir(parents=True, exist_ok=True)
|
||||
return result
|
||||
|
||||
def load_config(self, folder):
|
||||
path = _unlinked(Path(folder) / "settings.json")
|
||||
if not path.exists():
|
||||
return None
|
||||
value = json.loads(path.read_text(encoding="utf-8"))
|
||||
if not isinstance(value, dict) or value.get("schema") != 1 or type(value.get("revision")) is not int or not isinstance(value.get("config"), dict):
|
||||
raise ValueError("Web 策略文件格式错误")
|
||||
return value
|
||||
|
||||
def save_config(self, folder, config, revision):
|
||||
atomic_json(Path(folder) / "settings.json", {"schema": 1, "revision": revision, "config": config})
|
||||
|
||||
def remove_profile(self, identifier):
|
||||
"""Validate the whole tree before deleting only this UUID profile."""
|
||||
folder = self.profile(identifier)
|
||||
if not folder.exists():
|
||||
return
|
||||
for current, directories, files in os.walk(folder, followlinks=False):
|
||||
for name in (*directories, *files):
|
||||
target = _unlinked(Path(current) / name)
|
||||
if not target.resolve().is_relative_to(folder):
|
||||
raise ValueError("账号工作区含越界路径,已停止删除")
|
||||
shutil.rmtree(folder)
|
||||
|
||||
def close(self):
|
||||
self.workspace_lock.close()
|
||||
|
||||
|
||||
class SecureStore:
|
||||
"""Account-scoped Fernet records; public session entries are explicit fields."""
|
||||
|
||||
def __init__(self, workspace, identifier):
|
||||
self.workspace = workspace
|
||||
self.profile_root = workspace.profile(identifier)
|
||||
self.profile_root.mkdir(exist_ok=True)
|
||||
self.folder = _unlinked(self.profile_root / "sessions")
|
||||
self.lock = threading.RLock()
|
||||
|
||||
def _write(self, path, value):
|
||||
encrypted = self.workspace.fernet.encrypt(json.dumps(value, ensure_ascii=False, allow_nan=False).encode("utf-8"))
|
||||
atomic_json(path, {"schema": 1, "scheme": "fernet", "protected": encrypted.decode("ascii")})
|
||||
|
||||
def _read(self, path):
|
||||
try:
|
||||
record = json.loads(_unlinked(path).read_text(encoding="utf-8"))
|
||||
if record.get("schema") != 1 or record.get("scheme") != "fernet":
|
||||
raise ValueError
|
||||
return json.loads(self.workspace.fernet.decrypt(record["protected"].encode("ascii")))
|
||||
except (InvalidToken, KeyError, ValueError, TypeError, AttributeError, UnicodeError):
|
||||
raise ValueError("Web 加密记录无法读取,请恢复正确密钥或重新登录") from None
|
||||
|
||||
def save_credentials(self, account, password, remember=True):
|
||||
with self.lock:
|
||||
self._write(self.profile_root / "credentials.fernet", {"remember": bool(remember),
|
||||
"account": str(account) if remember else "", "password": str(password) if remember else ""})
|
||||
|
||||
def load_credentials(self):
|
||||
with self.lock:
|
||||
path = self.profile_root / "credentials.fernet"
|
||||
if not path.exists():
|
||||
return False, "", ""
|
||||
value = self._read(path)
|
||||
if type(value.get("remember")) is not bool or not isinstance(value.get("account"), str) or not isinstance(value.get("password"), str):
|
||||
raise ValueError("Web 登录记录格式错误")
|
||||
return value["remember"], value["account"], value["password"]
|
||||
|
||||
def device(self):
|
||||
with self.lock:
|
||||
path = self.profile_root / "device.fernet"
|
||||
if path.exists():
|
||||
return self._read(path)["device_id"]
|
||||
device = str(uuid.uuid4())
|
||||
self._write(path, {"device_id": device})
|
||||
return device
|
||||
|
||||
def set_active(self, identity):
|
||||
with self.lock:
|
||||
path = self.profile_root / "active.fernet"
|
||||
if identity is None:
|
||||
_unlinked(path).unlink(missing_ok=True)
|
||||
else:
|
||||
self._write(path, {"session_id": _identifier(identity, 64)})
|
||||
|
||||
def active(self):
|
||||
with self.lock:
|
||||
path = self.profile_root / "active.fernet"
|
||||
if not path.exists():
|
||||
return None
|
||||
return _identifier(self._read(path)["session_id"], 64)
|
||||
|
||||
def save(self, session, label):
|
||||
if not session.token or not session.server_url or not session.role_id:
|
||||
return None
|
||||
identity = session_identity(session)
|
||||
with self.lock:
|
||||
self.folder.mkdir(exist_ok=True)
|
||||
path = self.folder / (identity + ".fernet")
|
||||
value = asdict(session)
|
||||
if path.exists():
|
||||
previous = self._read(path)["session"]
|
||||
# Counters are never rolled back, including by an imported/stale object.
|
||||
for field in ("reqid", "reqsid"):
|
||||
value[field] = max(int(value[field]), int(previous.get(field, 0)))
|
||||
setattr(session, field, value[field])
|
||||
self._write(path, {"session_id": identity, "label": str(label),
|
||||
"saved_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "session": value})
|
||||
return identity
|
||||
|
||||
def entries(self):
|
||||
with self.lock:
|
||||
_unlinked(self.folder)
|
||||
result = []
|
||||
for path in self.folder.glob("*.fernet"):
|
||||
_identifier(path.stem, 64)
|
||||
value = self._read(path)
|
||||
if value.get("session_id") != path.stem:
|
||||
raise ValueError("Web 会话编号不一致")
|
||||
result.append({field: value[field] for field in ("session_id", "label", "saved_at")})
|
||||
return sorted(result, key=lambda row: row["saved_at"], reverse=True)
|
||||
|
||||
def load(self, identifier):
|
||||
identifier = _identifier(identifier, 64)
|
||||
with self.lock:
|
||||
value = self._read(_unlinked(self.folder) / (identifier + ".fernet"))
|
||||
session = Session(**value["session"])
|
||||
if session_identity(session) != identifier or not session.token or not session.role_id:
|
||||
raise ValueError("保存的账号、区服或角色信息不一致")
|
||||
return session
|
||||
|
||||
def remove(self, identifier):
|
||||
with self.lock:
|
||||
self.load(identifier)
|
||||
(self.folder / (identifier + ".fernet")).unlink()
|
||||
|
||||
def forget(self):
|
||||
with self.lock:
|
||||
_unlinked(self.folder)
|
||||
for path in self.folder.glob("*.fernet"):
|
||||
_identifier(path.stem, 64)
|
||||
_unlinked(path)
|
||||
for path in self.folder.glob("*.fernet"):
|
||||
path.unlink()
|
||||
_unlinked(self.profile_root / "credentials.fernet").unlink(missing_ok=True)
|
||||
_unlinked(self.profile_root / "active.fernet").unlink(missing_ok=True)
|
||||
@@ -0,0 +1 @@
|
||||
"""Offline tests; fixtures must use temporary storage and fake game clients."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Optional system-browser checks; all state is temporary and offline."""
|
||||
@@ -0,0 +1,479 @@
|
||||
"""Run with: python -m unittest ranch_web.tests.browser.test_workbench_browser -v.
|
||||
|
||||
Uses a temporary WebManager with explicit demo accounts and a local ASGI server.
|
||||
Login, populated exploration and measured statistics use browser route fixtures;
|
||||
no test contacts a game server or reads the user's account directories.
|
||||
Set RANCH_WEB_BROWSER to a Chromium executable when Edge is not installed.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import csv
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
|
||||
EDGE = Path(os.environ.get("RANCH_WEB_BROWSER", "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"))
|
||||
AVAILABLE = importlib.util.find_spec("playwright") is not None and EDGE.is_file()
|
||||
if AVAILABLE:
|
||||
from playwright.sync_api import expect
|
||||
|
||||
|
||||
class OfflineUpdates:
|
||||
def status(self):
|
||||
return {"current_version": "2.0.0.dev1", "latest_version": None, "status": "unchecked",
|
||||
"message": "尚未检查正式版本", "can_apply": False,
|
||||
"executor": {"enabled": False, "configured": False}}
|
||||
|
||||
|
||||
@unittest.skipUnless(AVAILABLE, "Install Python Playwright and set RANCH_WEB_BROWSER to a system Chromium browser")
|
||||
class WorkbenchBrowserTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
import uvicorn
|
||||
from playwright.sync_api import sync_playwright
|
||||
from ranch_web.app import create_app
|
||||
from ranch_web.config import WebConfig
|
||||
from ranch_web.service import WebManager
|
||||
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix="ranch-web-browser-test-")
|
||||
cls.manager = WebManager(cls.temp.name, start_scheduler=False)
|
||||
cls.first = cls.manager.create_account("浏览器离线演示", demo=True)["id"]
|
||||
cls.second = cls.manager.create_account("账号二", demo=True)["id"]
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
cls.base = f"http://127.0.0.1:{port}"
|
||||
settings = WebConfig(port=port, data_dir=Path(cls.temp.name))
|
||||
app = create_app(manager=cls.manager, config=settings, updates=OfflineUpdates())
|
||||
cls.server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error"))
|
||||
cls.thread = threading.Thread(target=cls.server.run, daemon=True)
|
||||
cls.thread.start()
|
||||
deadline = time.monotonic() + 15
|
||||
while not cls.server.started and time.monotonic() < deadline:
|
||||
time.sleep(.02)
|
||||
if not cls.server.started:
|
||||
raise RuntimeError("Temporary offline browser server failed to start")
|
||||
cls.playwright = sync_playwright().start()
|
||||
cls.browser = cls.playwright.chromium.launch(executable_path=str(EDGE), headless=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.browser.close()
|
||||
cls.playwright.stop()
|
||||
cls.server.should_exit = True
|
||||
cls.thread.join(timeout=10)
|
||||
cls.manager.close()
|
||||
cls.temp.cleanup()
|
||||
|
||||
def setUp(self):
|
||||
from ranch_web.policies import default_config
|
||||
|
||||
for identifier in (self.first, self.second):
|
||||
self.manager.submit(identifier, "stop")
|
||||
response = self.manager.set_config(identifier, default_config())
|
||||
self.await_job(identifier, response["job_id"])
|
||||
self.context = self.browser.new_context(viewport={"width": 1280, "height": 800}, accept_downloads=True)
|
||||
self.page = self.context.new_page()
|
||||
self.errors = []
|
||||
self.page.on("pageerror", lambda failure: self.errors.append(str(failure)))
|
||||
self.page.on("console", lambda message: self.errors.append(message.text) if message.type == "error" else None)
|
||||
self.context.route("https://**", lambda route: route.abort())
|
||||
|
||||
def tearDown(self):
|
||||
self.context.close()
|
||||
|
||||
def await_job(self, identifier, job_id):
|
||||
deadline = time.monotonic() + 10
|
||||
while time.monotonic() < deadline:
|
||||
job = self.manager.job(identifier, job_id)
|
||||
if job["status"] in ("succeeded", "failed", "cancelled"):
|
||||
self.assertEqual(job["status"], "succeeded", job.get("error"))
|
||||
return job.get("result")
|
||||
time.sleep(.01)
|
||||
self.fail("Offline job did not complete")
|
||||
|
||||
def open(self, page=None):
|
||||
page=page or self.page
|
||||
page.goto(self.base, wait_until="networkidle")
|
||||
page.locator(f'.account-tab[data-account="{self.first}"]').click()
|
||||
expect(page.locator('#save-status')).to_have_text('策略已自动保存')
|
||||
|
||||
def go(self, key, page=None):
|
||||
page=page or self.page
|
||||
page.locator(f'.page-tab[data-page="{key}"]').click()
|
||||
page.wait_for_selector(f'.page-panel[data-page="{key}"]:not([hidden]) .page-loading[data-loading="false"]')
|
||||
return page.locator(f'.page-panel[data-page="{key}"]:not([hidden])')
|
||||
|
||||
@staticmethod
|
||||
def field(root,path):
|
||||
return root.locator("[data-config-path='"+json.dumps(path,separators=(',',':'))+"']")
|
||||
|
||||
def wait_saved(self):
|
||||
expect(self.page.locator('#save-status')).to_have_text('策略已自动保存')
|
||||
|
||||
@staticmethod
|
||||
def fulfill(route, data):
|
||||
route.fulfill(status=200, content_type="application/json", body=json.dumps(data, ensure_ascii=False))
|
||||
|
||||
def test_all_pages_are_read_only_csp_clean_and_responsive(self):
|
||||
self.open()
|
||||
writes = []
|
||||
self.page.on("request", lambda request: writes.append(request.url) if request.method in ("POST", "PUT", "DELETE") else None)
|
||||
keys = ["login", "incubator", "bag", "ranch", "daily", "hatching", "mainline", "battles", "gifts", "commissions", "exploration", "maps", "statistics", "plans", "yields"]
|
||||
for key in keys:
|
||||
panel = self.go(key)
|
||||
self.assertEqual(panel.locator(".page-error:not([hidden])").count(), 0)
|
||||
if key=='hatching':
|
||||
expect(panel.locator('.subtab')).to_have_count(3)
|
||||
expect(panel.locator('.form-section')).to_have_count(1)
|
||||
expect(panel.locator('.form-section legend')).to_have_text('孵蛋策略')
|
||||
panel.locator('.subtab[data-key="喂养策略"]').click()
|
||||
expect(panel.locator('.form-section legend')).to_have_text('喂养策略')
|
||||
expect(panel.locator('[data-view-status="feed_status"]')).to_be_visible()
|
||||
if key=='mainline':
|
||||
expect(panel.locator('.subtab[data-key="policy"]')).to_be_visible()
|
||||
panel.locator('.subtab[data-key="policy"]').click()
|
||||
expect(self.field(panel,['progression_policy','enabled'])).to_be_visible()
|
||||
panel.locator('.subtab[data-key="status"]').click()
|
||||
expect(self.field(panel,['progression_policy','enabled'])).to_have_count(0)
|
||||
self.assertEqual(writes, [], "Switching pages must not submit game or configuration actions")
|
||||
self.assertEqual(self.page.locator('.page-tab[data-page="statistics"]').inner_text(), "数据分析")
|
||||
self.assertEqual(self.page.locator('.page-tab[data-page="plans"]').inner_text(), "执行计划")
|
||||
self.go("bag")
|
||||
for width, height in ((1280, 800), (1600, 900), (390, 844)):
|
||||
self.page.set_viewport_size({"width": width, "height": height})
|
||||
self.assertTrue(self.page.locator("#strategy-toggle").is_visible())
|
||||
self.assertTrue(self.page.locator("#page-tabs").is_visible())
|
||||
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width)
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_rule_defaults_autosave_focus_account_isolation_and_start_stop(self):
|
||||
self.open()
|
||||
panel = self.go("bag")
|
||||
row = panel.locator("tbody tr").first
|
||||
species = row.get_attribute("data-row-id")
|
||||
priority = row.locator('td[data-column="priority"] input')
|
||||
priority.fill("17")
|
||||
original = priority.element_handle()
|
||||
self.page.wait_for_timeout(2100)
|
||||
self.wait_saved()
|
||||
self.assertTrue(priority.evaluate("(node, original) => node === original", original))
|
||||
self.assertTrue(priority.evaluate("node => node === document.activeElement"))
|
||||
saved = self.manager.get_config(self.first)["config"]["policy"]["egg_rules"][species]
|
||||
self.assertEqual(saved["priority"], 17)
|
||||
self.assertIn("refill_target", saved)
|
||||
self.assertIn("keep_count", saved)
|
||||
row.locator('td[data-column="enabled"] input').check()
|
||||
self.page.wait_for_timeout(1800)
|
||||
self.wait_saved()
|
||||
self.page.locator("#strategy-toggle").click()
|
||||
expect(self.page.locator('#strategy-toggle')).to_have_text('停止')
|
||||
self.page.locator("#strategy-toggle").click()
|
||||
expect(self.page.locator('#strategy-toggle')).to_have_text('开启')
|
||||
self.page.locator(f'.account-tab[data-account="{self.second}"]').click()
|
||||
expect(self.page.locator('#save-status')).to_have_text('策略已自动保存')
|
||||
self.assertEqual(self.manager.get_config(self.second)["config"]["policy"]["egg_rules"], {})
|
||||
self.page.locator(f'.account-tab[data-account="{self.first}"]').click()
|
||||
self.assertEqual(self.go("bag").locator(f'tr[data-row-id="{species}"] td[data-column="priority"] input').input_value(), "17")
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_exploration_keeps_partial_drafts_and_saves_only_three_or_auto(self):
|
||||
from ranch_web.policies import default_config
|
||||
|
||||
fixture_config = default_config()
|
||||
revision = 500
|
||||
writes = []
|
||||
candidates = [{"value": 101, "label": "队长", "level": 30}, {"value": 102, "label": "队员一", "level": 20}, {"value": 103, "label": "队员二", "level": 10}]
|
||||
def route_config(route):
|
||||
nonlocal fixture_config, revision
|
||||
if route.request.method == "PUT":
|
||||
fixture_config = route.request.post_data_json["config"]
|
||||
writes.append(copy.deepcopy(fixture_config))
|
||||
revision += 1
|
||||
self.fulfill(route, {"config": fixture_config, "revision": revision})
|
||||
def route_view(route):
|
||||
row = {"id": "1", "name": '<img src=x onerror="alert(1)">', "enabled": False, "monsters": [], "rule_path": ["explore_policy", "teams", "1"],
|
||||
"rule_defaults": {"enabled": False, "area": "area1", "monsters": []}, "member_options": candidates}
|
||||
self.fulfill(route, {"loading": False, "revision": revision, "data": {"page": "exploration", "title": "自动探险", "summary": "完成后自动领奖", "form": [], "filters": [], "actions": [],
|
||||
"columns": [{"key": "name", "label": "队伍"}, {"key": "monsters", "label": "队员", "edit": {"path": ["explore_policy", "teams", "{id}", "monsters"], "type": "members", "options": candidates}}], "rows": [row]}})
|
||||
self.page.route(f"**/api/accounts/{self.first}/config", route_config)
|
||||
self.page.route(f"**/api/accounts/{self.first}/views/exploration?*", route_view)
|
||||
self.open()
|
||||
panel = self.go("exploration")
|
||||
selects = panel.locator(".member-selects select")
|
||||
selects.nth(0).select_option("101")
|
||||
selects.nth(1).select_option("102")
|
||||
self.page.wait_for_timeout(750)
|
||||
self.assertEqual(writes, [], "An incomplete team must remain a browser draft")
|
||||
self.assertEqual(panel.locator("img").count(), 0, "Game names must be text, never HTML")
|
||||
selects.nth(2).select_option("103")
|
||||
self.page.wait_for_timeout(1400)
|
||||
self.assertEqual(writes[-1]["explore_policy"]["teams"]["1"]["monsters"], [101, 102, 103])
|
||||
panel.get_by_role("button", name="自动选三只", exact=True).click()
|
||||
self.page.wait_for_timeout(1400)
|
||||
self.assertEqual(writes[-1]["explore_policy"]["teams"]["1"]["monsters"], [])
|
||||
self.assertTrue(all(len(config["explore_policy"]["teams"]["1"]["monsters"]) in (0, 3) for config in writes))
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_statistics_tree_is_lazy_and_chart_uses_requested_source(self):
|
||||
requests = []
|
||||
def route_view(route):
|
||||
query = json.loads(parse_qs(urlsplit(route.request.url).query)["query"][0])
|
||||
requests.append(query)
|
||||
source = query.get("source", "all")
|
||||
stages = [{"id": f"stage{i}", "label": f"关卡{i}", "city_id": str(i // 30), "city_name": f"地区{i // 30}", "levels": [{"id": str(level), "level": str(level), "sweep": 2, "event": 1} for level in (1, 2, 3)]} for i in range(120)]
|
||||
self.fulfill(route, {"loading": False, "data": {"page": "statistics", "title": "数据分析", "summary": "真实测量 fixture", "stages": stages,
|
||||
"filters": [{"key": "source", "label": "统计范围", "type": "select", "value": source, "options": [{"value": "all", "label": "扫荡+奖励事件"}, {"value": "event", "label": "奖励事件"}]}], "form": [], "actions": [], "columns": [{"key": "name", "label": "掉落物"}], "rows": [],
|
||||
"chart": {"series": [{"label": "测量样本", "value": .25 if source == "event" else .5}]}}})
|
||||
self.page.route(f"**/api/accounts/{self.first}/views/statistics?*", route_view)
|
||||
self.open()
|
||||
panel = self.go("statistics")
|
||||
original_width=float(panel.locator('.chart-bar').get_attribute('width'))
|
||||
self.assertEqual(panel.locator(".statistics-city").count(), 4)
|
||||
self.assertEqual(panel.locator(".statistics-levels button").count(), 0)
|
||||
panel.locator(".statistics-city > summary").first.click()
|
||||
expect(panel.locator('.statistics-stage')).to_have_count(30)
|
||||
self.assertEqual(panel.locator(".statistics-levels button").count(), 0)
|
||||
panel.locator(".statistics-stage > summary").first.click()
|
||||
expect(panel.locator('.statistics-levels button')).to_have_count(3)
|
||||
panel.locator('[data-config-path=\'["source"]\']').select_option("event")
|
||||
expect(panel.locator('.chart-value')).to_have_text('25.00%')
|
||||
self.assertAlmostEqual(float(panel.locator('.chart-bar').get_attribute('width')), original_width / 2)
|
||||
self.assertEqual(requests[-1]["source"], "event")
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_network_debug_details_are_loaded_only_when_selected(self):
|
||||
detail_requests = []
|
||||
def route_logs(route):
|
||||
query = parse_qs(urlsplit(route.request.url).query)
|
||||
debug = query.get("debug") == ["true"]
|
||||
self.fulfill(route, {"entries": [{"id": 51, "seq": 51, "time":"2026-11-10T07:08:09Z", "message": "离线请求响应", "details_available": debug}], "next": 51})
|
||||
def route_detail(route):
|
||||
detail_requests.append(route.request.url)
|
||||
self.fulfill(route, {"id": 51, "details": {"operation": "离线测试", "body": {"master": {"name": "演示"}, "token": "<隐藏>"}}})
|
||||
self.page.route(f"**/api/accounts/{self.first}/logs?*", route_logs)
|
||||
self.page.route(f"**/api/accounts/{self.first}/debug/51", route_detail)
|
||||
self.open()
|
||||
self.page.locator("#debug-toggle").click()
|
||||
self.page.wait_for_selector(".log-entry.inspectable")
|
||||
expect(self.page.locator('.log-entry.inspectable .log-time')).to_have_text('15:08:09')
|
||||
expect(self.page.locator('.log-entry.inspectable .log-time')).to_have_attribute('title','2026-11-10T07:08:09Z')
|
||||
self.assertEqual(detail_requests, [])
|
||||
self.page.locator(".log-entry.inspectable").first.click()
|
||||
expect(self.page.locator('.debug-json')).to_contain_text('<隐藏>')
|
||||
self.assertEqual(len(detail_requests), 1)
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_fake_login_uses_servers_without_persisting_password(self):
|
||||
payloads = []
|
||||
def route_login(route):
|
||||
payloads.append(route.request.post_data_json)
|
||||
self.fulfill(route, {"id": "fake_login", "status": "succeeded", "operation": "login", "result": {"servers": [{"id": 7, "name": "测试区", "role_name": "测试角色"}], "has_saved_password": True}, "error": None})
|
||||
self.page.route(f"**/api/accounts/{self.first}/actions/login", route_login)
|
||||
self.open()
|
||||
panel = self.go("login")
|
||||
panel.get_by_label("游戏账号", exact=True).fill("offline-test")
|
||||
panel.get_by_label("游戏密码", exact=True).fill("test-password-never-persist")
|
||||
panel.get_by_role("button", name="账号密码登录 / 获取区服", exact=True).click()
|
||||
expect(panel.get_by_label('区服 / 角色',exact=True)).to_contain_text('测试区')
|
||||
self.assertEqual(payloads[0], {"account": "offline-test", "password": "test-password-never-persist", "remember": True})
|
||||
self.assertEqual(panel.get_by_label("游戏密码", exact=True).input_value(), "")
|
||||
self.assertEqual(self.page.evaluate("Object.keys(localStorage).length + Object.keys(sessionStorage).length"), 0)
|
||||
self.assertNotIn("test-password", self.page.url)
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_exports_round_trip_and_expansion_requires_confirmation(self):
|
||||
from ranch_assistant.model import Catalog
|
||||
|
||||
self.open()
|
||||
self.page.locator('.menu > summary').nth(2).click()
|
||||
with self.page.expect_download() as pending:
|
||||
self.page.locator('[data-command="export-config"]').click()
|
||||
exported = json.loads(Path(pending.value.path()).read_text(encoding='utf-8'))
|
||||
self.assertIn('policy', exported)
|
||||
self.assertNotIn('password', exported)
|
||||
self.page.locator('.menu > summary').nth(2).click()
|
||||
with self.page.expect_download() as pending:
|
||||
self.page.locator('[data-command="export-yields"]').click()
|
||||
content = Path(pending.value.path()).read_bytes()
|
||||
raw = content.decode('utf-8-sig')
|
||||
rows = list(csv.DictReader(raw.splitlines()))
|
||||
self.assertGreater(len(rows), 100)
|
||||
self.assertIn('孵化秒数', rows[0])
|
||||
path = Path(self.temp.name) / 'round-trip.csv'
|
||||
path.write_bytes(content)
|
||||
catalog = Catalog()
|
||||
self.assertEqual(catalog.import_prices(path), len(rows))
|
||||
|
||||
panel = self.go('incubator')
|
||||
data = self.manager.view(self.first, 'incubator', {})['data']
|
||||
position = next(row['id'] for row in data['rows'] if row['can_expand'])
|
||||
panel.locator(f'tr[data-row-id="{position}"] .selection-cell input').check()
|
||||
writes = []
|
||||
self.page.on('request', lambda request: writes.append(request.url) if request.method == 'POST' and request.url.endswith('/actions/expand') else None)
|
||||
panel.locator('button[data-operation="quote_expansion"]').first.click()
|
||||
expect(self.page.locator('#dialog-title')).to_have_text('确认开启坑位')
|
||||
self.page.locator('#dialog-cancel').click()
|
||||
self.assertEqual(writes, [], 'Reading or cancelling a quote must not expand')
|
||||
panel.locator('button[data-operation="quote_expansion"]').first.click()
|
||||
expect(self.page.locator('#dialog-title')).to_have_text('确认开启坑位')
|
||||
self.page.locator('#dialog-confirm').click()
|
||||
expect(panel.locator(f'tr[data-row-id="{position}"] td[data-column="status"]')).to_have_text('已开启', timeout=10000)
|
||||
self.assertEqual(len(writes), 1)
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_target_deletion_never_rechecks_from_stale_view(self):
|
||||
self.open()
|
||||
panel=self.go('ranch')
|
||||
data=self.manager.view(self.first,'ranch',{'grouped':False})['data']
|
||||
identifier=next(row['id'] for row in data['rows'] if row['process']==3)
|
||||
value=self.manager.get_config(self.first)['config']
|
||||
for mapping in ('feed_targets','gift_targets','breakthrough_targets'):
|
||||
value['policy'][mapping]={identifier:100}
|
||||
pending=self.manager.set_config(self.first,value)
|
||||
self.await_job(self.first,pending['job_id'])
|
||||
self.page.reload(wait_until='networkidle')
|
||||
panel=self.go('ranch')
|
||||
for prefix,mapping in [('feed','feed_targets'),('gift','gift_targets'),('breakthrough','breakthrough_targets')]:
|
||||
checkbox=panel.locator(f'tr[data-row-id="{identifier}"] td[data-column="{prefix}_selected"] input')
|
||||
expect(checkbox).to_be_checked()
|
||||
checkbox.uncheck()
|
||||
expect(checkbox).not_to_be_checked()
|
||||
self.page.wait_for_timeout(1200)
|
||||
self.wait_saved()
|
||||
expect(checkbox).not_to_be_checked()
|
||||
self.assertEqual(self.manager.get_config(self.first)['config']['policy'][mapping],{})
|
||||
self.assertEqual(self.errors,[])
|
||||
|
||||
def test_add_rule_uses_species_market_defaults(self):
|
||||
self.open()
|
||||
panel=self.go('bag')
|
||||
data=self.manager.view(self.first,'bag',{'category':'eggs'})['data']
|
||||
field=next(field for field in data['form'] if field['type']=='add_rule')
|
||||
existing={row['id'] for row in data['rows']}
|
||||
identifier,defaults=next((key,value) for key,value in field['defaults_by_id'].items() if key not in existing and value['market_id'])
|
||||
panel.get_by_label('添加魔物蛋规则',exact=True).select_option(identifier)
|
||||
panel.get_by_role('button',name='添加无库存蛋规则',exact=True).click()
|
||||
self.page.wait_for_timeout(1600)
|
||||
self.wait_saved()
|
||||
saved=self.manager.get_config(self.first)['config']['policy']['egg_rules'][identifier]
|
||||
self.assertEqual(saved,defaults)
|
||||
expect(panel.locator(f'tr[data-row-id="{identifier}"] td[data-column="market_id"] select')).to_have_value(defaults['market_id'])
|
||||
self.assertEqual(self.errors,[])
|
||||
|
||||
def test_conflict_between_two_tabs_preserves_new_row_fields(self):
|
||||
# Keep tab A on an earlier revision so it exercises the actual HTTP 409.
|
||||
initial=self.manager.list_accounts()
|
||||
self.page.route('**/api/accounts',lambda route:self.fulfill(route,initial))
|
||||
def map_view(route):
|
||||
config=self.manager.get_config(self.first)
|
||||
defaults={'enabled':False,'level':'1','limit':3}
|
||||
rule=defaults | config['config']['sweep_policy']['rules'].get('stage1',{})
|
||||
data={'page':'maps','title':'自动扫荡','summary':'离线冲突回归','filters':[],'form':[],'actions':[],
|
||||
'groups':[{'id':'1','label':'测试地区','collapsed':False}],
|
||||
'columns':[{'key':'enabled','label':'刷图','edit':{'path':['sweep_policy','rules','{id}','enabled'],'type':'boolean'}},
|
||||
{'key':'level','label':'难度','edit':{'path':['sweep_policy','rules','{id}','level'],'type':'select','options':[{'value':str(i),'label':str(i)} for i in (1,2,3)]}},
|
||||
{'key':'limit','label':'本日上限','edit':{'path':['sweep_policy','rules','{id}','limit'],'type':'integer','min':0,'max':999}}],
|
||||
'rows':[{'id':'stage1','group':'1',**rule,'rule_path':['sweep_policy','rules','stage1'],'rule_defaults':defaults}]}
|
||||
self.fulfill(route,{'data':data,'loading':False,'revision':config['revision']})
|
||||
self.page.route(f'**/api/accounts/{self.first}/views/maps?*',map_view)
|
||||
self.open()
|
||||
panel_a=self.go('maps')
|
||||
second=self.context.new_page()
|
||||
second.route(f'**/api/accounts/{self.first}/views/maps?*',map_view)
|
||||
self.open(second)
|
||||
panel_b=self.go('maps',second)
|
||||
panel_b.locator('td[data-column="level"] select').select_option('2')
|
||||
panel_b.locator('td[data-column="limit"] input').fill('5')
|
||||
second.wait_for_timeout(1400)
|
||||
expect(second.locator('#save-status')).to_have_text('策略已自动保存')
|
||||
self.assertEqual(self.manager.get_config(self.first)['config']['sweep_policy']['rules']['stage1']['limit'],5)
|
||||
panel_a.locator('td[data-column="enabled"] input').check()
|
||||
expect(self.page.locator('#save-status')).to_have_text('保存失败 · 点击重试',timeout=10000)
|
||||
self.page.locator('#save-status').click()
|
||||
expect(self.page.locator('#save-status')).to_have_text('策略已自动保存',timeout=10000)
|
||||
self.assertEqual(self.manager.get_config(self.first)['config']['sweep_policy']['rules']['stage1'],{'enabled':True,'level':'2','limit':5})
|
||||
self.assertFalse([message for message in self.errors if '409' not in message],self.errors)
|
||||
|
||||
def test_small_stamina_efficiency_is_visible_in_chart_and_table(self):
|
||||
# The metric is a GET filter; no configuration changes are submitted.
|
||||
data={'page':'statistics','title':'数据分析','summary':'精度回归','filters':[{'key':'metric','label':'图表指标','type':'select','value':'per_stamina','options':[{'value':'per_stamina','label':'每点体力数量'}]}],
|
||||
'form':[],'actions':[],'columns':[{'key':'name','label':'掉落物'},{'key':'per_stamina','label':'每点体力数量'}],
|
||||
'rows':[{'id':'rare','name':'稀有材料','per_stamina':.001}],'chart':{'max':.002,'series':[{'label':'稀有材料','value':.001}]}}
|
||||
self.page.route(f'**/api/accounts/{self.first}/views/statistics?*',lambda route:self.fulfill(route,{'data':data,'loading':False}))
|
||||
self.open()
|
||||
panel=self.go('statistics')
|
||||
expect(panel.locator('.chart-value')).to_have_text('0.001')
|
||||
expect(panel.locator('.chart-bar title')).to_have_text('稀有材料:0.001')
|
||||
expect(panel.locator('td[data-column="per_stamina"]')).to_have_text('0.001')
|
||||
expect(panel.locator('td[data-column="per_stamina"]')).to_have_attribute('title','0.001')
|
||||
self.assertEqual(self.errors,[])
|
||||
|
||||
def test_runtime_statuses_and_preset_without_confirmation(self):
|
||||
def gifts_view(route):
|
||||
self.fulfill(route,{'data':{'page':'gifts','title':'自动赠礼','summary':'离线状态','form':[],'filters':[],'columns':[],'rows':[],'actions':[],
|
||||
'details':{'next_ready_at':1794294489}},'loading':False})
|
||||
self.page.route(f'**/api/accounts/{self.first}/views/gifts?*',gifts_view)
|
||||
self.open()
|
||||
panel=self.go('hatching')
|
||||
expect(panel.locator('[data-view-status="last_draw"]')).to_contain_text('最近抽蛋:')
|
||||
panel.locator('.subtab[data-key="喂养策略"]').click()
|
||||
data=self.manager.view(self.first,'hatching',{})['data']
|
||||
expect(panel.locator('[data-view-status="feed_status"]')).to_contain_text(data['details']['feed_status'][1])
|
||||
panel.locator('button[data-operation="apply_preset"]').click()
|
||||
expect(self.page.locator('#action-dialog')).not_to_be_visible()
|
||||
self.page.wait_for_timeout(1400)
|
||||
self.wait_saved()
|
||||
self.assertTrue(self.manager.get_config(self.first)['config']['policy']['egg_rules']['1001010']['enabled'])
|
||||
self.assertFalse(self.manager.status(self.first)['running'])
|
||||
panel=self.go('gifts')
|
||||
expect(panel.locator('[data-view-status="next_ready_at"]')).to_contain_text('北京时间')
|
||||
self.assertEqual(self.errors,[])
|
||||
|
||||
def test_update_dialog_polls_host_progress_recovers_and_stops_on_close(self):
|
||||
calls=[]
|
||||
applied=False
|
||||
progress=iter(['applying','disconnected','succeeded'])
|
||||
def status_value(status):
|
||||
return {'current_version':'2.0.0.dev1','latest_version':'v2.0.0','status':status,'message':{'available':'发现正式版本','pending':'等待宿主机','applying':'正在执行更新','succeeded':'宿主机健康检查通过'}[status],
|
||||
'can_apply':status=='available','executor':{'enabled':True},'host_status':{'status':status,'version':'v2.0.0'}}
|
||||
def updates(route):
|
||||
calls.append(route.request.url)
|
||||
stage=next(progress,'succeeded') if applied else 'available'
|
||||
if stage=='disconnected':
|
||||
route.fulfill(status=503,content_type='application/json',body='{"detail":"离线模拟服务重启"}')
|
||||
else:self.fulfill(route,status_value(stage))
|
||||
def apply(route):
|
||||
nonlocal applied
|
||||
applied=True
|
||||
self.fulfill(route,status_value('pending'))
|
||||
self.page.route('**/api/system/updates',updates)
|
||||
self.page.route('**/api/system/updates/apply',apply)
|
||||
self.open()
|
||||
self.page.locator('.menu > summary').nth(3).click()
|
||||
self.page.locator('[data-command="updates"]').click()
|
||||
expect(self.page.get_by_text('发现新版本',exact=True).first).to_be_visible()
|
||||
self.page.once('dialog',lambda prompt:prompt.accept())
|
||||
self.page.get_by_role('button',name='提交更新请求…',exact=True).click()
|
||||
expect(self.page.get_by_text('等待宿主机处理',exact=True).first).to_be_visible()
|
||||
expect(self.page.get_by_text('正在更新并检查健康',exact=True).first).to_be_visible(timeout=7000)
|
||||
expect(self.page.get_by_text('更新完成,健康检查通过',exact=True).first).to_be_visible(timeout=13000)
|
||||
expect(self.page.locator('#dialog-content')).to_contain_text('宿主机健康检查通过')
|
||||
self.page.locator('#dialog-cancel').click()
|
||||
completed=len(calls)
|
||||
self.page.wait_for_timeout(3300)
|
||||
self.assertEqual(len(calls),completed)
|
||||
self.assertFalse([message for message in self.errors if '503' not in message],self.errors)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,560 @@
|
||||
"""Exercise HTTP behavior with temporary state and fake, offline collaborators."""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import httpx
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from ranch_web.app import create_app
|
||||
from ranch_web.config import WebConfig
|
||||
|
||||
|
||||
class FakeUpdates:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
self.closed = False
|
||||
|
||||
def status(self):
|
||||
self.calls.append("status")
|
||||
return {"current_version": "2.0.0.dev1", "status": "unchecked", "can_apply": False,
|
||||
"message": "尚未配置部署器", "path": "C:/private/updater-state"}
|
||||
|
||||
def check(self):
|
||||
self.calls.append("check")
|
||||
return {"status": "no_release", "message": "没有可用的正式版本"}
|
||||
|
||||
def request_update(self, version=None):
|
||||
self.calls.append(("apply", version))
|
||||
return {"status": "unavailable", "message": "尚未配置部署器", "can_apply": False}
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
class FakeManager:
|
||||
def __init__(self):
|
||||
self.accounts = {}
|
||||
self.jobs = {}
|
||||
self.calls = []
|
||||
self.closed = False
|
||||
self.pending_config = False
|
||||
|
||||
def list_accounts(self):
|
||||
self.calls.append("list")
|
||||
return deepcopy(list(self.accounts.values()))
|
||||
|
||||
def create_account(self, label="", demo=True):
|
||||
identifier = f"account_{len(self.accounts) + 1}"
|
||||
summary = {"id": identifier, "label": label, "demo": demo, "connected": False,
|
||||
"running": False, "busy": False, "revision": 0, "error": None,
|
||||
"player": {"name": "离线演示", "level": 1, "exp": 5, "next_exp": 10,
|
||||
"money": 100, "ke": 0, "ti": 20, "token": "PLAYER_PRIVATE"},
|
||||
"password": "SUMMARY_PRIVATE", "raw": {"private": "RAW_PRIVATE"}}
|
||||
self.accounts[identifier] = summary
|
||||
self.calls.append(("create", demo))
|
||||
return deepcopy(summary)
|
||||
|
||||
def status(self, account_id):
|
||||
return deepcopy(self.accounts[account_id])
|
||||
|
||||
def remove_account(self, account_id):
|
||||
del self.accounts[account_id]
|
||||
|
||||
def get_config(self, account_id):
|
||||
self.status(account_id)
|
||||
return {"config": {"policy": {"fill": False}}, "revision": 3}
|
||||
|
||||
def set_config(self, account_id, config, revision=None):
|
||||
self.status(account_id)
|
||||
self.calls.append(("config", deepcopy(config), revision))
|
||||
result = {"config": config, "revision": 4}
|
||||
if self.pending_config:
|
||||
result.update(pending=True, job_id="config_job")
|
||||
return result
|
||||
|
||||
def view(self, account_id, page, query=None):
|
||||
self.status(account_id)
|
||||
self.calls.append(("view", page, query))
|
||||
return {"data": {"page": page, "title": "背包", "columns": [{"key": "name", "label": "名称"}],
|
||||
"filters": [{"key": "category", "label": "分类"}], "rows": [{"id": "100", "name": "测试蛋"}],
|
||||
"raw": {"password": "VIEW_PRIVATE"}},
|
||||
"loading": True, "job_id": "view_job", "revision": 3}
|
||||
|
||||
def submit(self, account_id, operation, payload=None):
|
||||
self.status(account_id)
|
||||
self.calls.append(("submit", operation, deepcopy(payload)))
|
||||
result = {"id": "job_1", "status": "queued", "operation": operation, "result": None, "error": None}
|
||||
self.jobs[(account_id, "job_1")] = result
|
||||
return deepcopy(result)
|
||||
|
||||
def job(self, account_id, job_id):
|
||||
return deepcopy(self.jobs[(account_id, job_id)])
|
||||
|
||||
def logs(self, account_id, after=0, debug=False):
|
||||
self.status(account_id)
|
||||
self.calls.append(("logs", after, debug))
|
||||
return {"entries": [{"id": 1, "message": "password=LOG_SECRET token=TOKEN_SECRET reqid=REQ_SECRET C:/private/file.log /data/profiles/a"}], "next": 1}
|
||||
|
||||
def log_detail(self, account_id, entry_id):
|
||||
self.status(account_id)
|
||||
self.calls.append(("detail", entry_id))
|
||||
return {"id": entry_id, "request": {"body": {"operation": "refresh", "key": "GAME_KEY"}},
|
||||
"response": {"body": {"player": {"name": "演示角色"}, "token": "GAME_TOKEN"}},
|
||||
"headers": {"Authorization": "Bearer PRIVATE_BEARER"}}
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
class ApiTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix="ranch-web-api-")
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name)
|
||||
self.manager, self.updates = FakeManager(), FakeUpdates()
|
||||
self.account_id = self.manager.create_account("离线账号")["id"]
|
||||
self.settings = WebConfig(data_dir=self.root)
|
||||
self.app = create_app(manager=self.manager, updates=self.updates, config=self.settings)
|
||||
self.client = self.enterContext(TestClient(self.app, base_url="http://localhost", client=("127.0.0.1", 50000)))
|
||||
self.network = self.enterContext(patch("requests.sessions.Session.request", side_effect=AssertionError("禁止真实游戏 API")))
|
||||
self.url = f"/api/accounts/{self.account_id}"
|
||||
|
||||
def test_health_meta_and_updates_have_no_game_side_effects(self):
|
||||
self.manager.calls.clear()
|
||||
self.assertEqual(self.client.get("/api/health").json(), {"status": "ok", "version": "2.0.0.dev1"})
|
||||
meta = self.client.get("/api/meta")
|
||||
self.assertEqual(meta.status_code, 200)
|
||||
self.assertEqual(meta.json()["gameVersion"], "1.9.68")
|
||||
self.assertEqual(meta.json()["access"]["mode"], "local")
|
||||
self.assertEqual(self.client.get("/api/system/updates").status_code, 200)
|
||||
self.assertEqual(self.manager.calls, [])
|
||||
self.assertEqual(self.updates.calls, ["status", "status"])
|
||||
self.assertNotIn("C:/private", meta.text)
|
||||
self.network.assert_not_called()
|
||||
|
||||
def test_injected_objects_are_not_closed_by_lifespan(self):
|
||||
app = create_app(manager=self.manager, updates=self.updates, config=self.settings)
|
||||
with TestClient(app, base_url="http://localhost", client=("127.0.0.1", 50001)) as client:
|
||||
self.assertEqual(client.get("/api/health").status_code, 200)
|
||||
self.assertFalse(self.manager.closed)
|
||||
self.assertFalse(self.updates.closed)
|
||||
|
||||
def test_owned_objects_closed_even_when_lifespan_fails(self):
|
||||
with patch("ranch_web.service.WebManager", return_value=self.manager), patch("ranch_web.updates.UpdateService", side_effect=RuntimeError("injected startup failure")):
|
||||
app = create_app(config=self.settings)
|
||||
with self.assertRaises(RuntimeError):
|
||||
with TestClient(app):
|
||||
pass
|
||||
self.assertTrue(self.manager.closed)
|
||||
|
||||
def test_only_owned_objects_close(self):
|
||||
with patch("ranch_web.service.WebManager", return_value=self.manager), patch("ranch_web.updates.UpdateService", return_value=self.updates):
|
||||
with TestClient(create_app(config=self.settings)):
|
||||
pass
|
||||
self.assertTrue(self.manager.closed)
|
||||
self.assertTrue(self.updates.closed)
|
||||
|
||||
def test_shutdown_attempts_all_owned_cleanup_when_one_close_fails(self):
|
||||
with patch("ranch_web.service.WebManager", return_value=self.manager), patch("ranch_web.updates.UpdateService", return_value=self.updates), patch.object(self.updates, "close", side_effect=OSError("private shutdown detail")):
|
||||
with self.assertRaisesRegex(RuntimeError, "关闭未完成"):
|
||||
with TestClient(create_app(config=self.settings)):
|
||||
pass
|
||||
self.assertTrue(self.manager.closed)
|
||||
|
||||
def test_accounts_are_public_and_creation_does_not_start_strategy(self):
|
||||
response = self.client.post("/api/accounts", json={"label": "另一个离线账号", "demo": True})
|
||||
self.assertEqual(response.status_code, 201)
|
||||
self.assertFalse(response.json()["running"])
|
||||
self.assertNotIn("PRIVATE", response.text)
|
||||
accounts = self.client.get("/api/accounts").json()
|
||||
self.assertEqual(len(accounts), 2)
|
||||
self.assertEqual(accounts[1]["player"]["money"], 100)
|
||||
self.assertEqual(self.client.delete(f"/api/accounts/{response.json()['id']}").status_code, 204)
|
||||
self.assertEqual(self.client.get(f"/api/accounts/{response.json()['id']}/status").status_code, 404)
|
||||
|
||||
def test_game_login_is_queued_and_credentials_stay_server_side(self):
|
||||
response = self.client.post(self.url + "/actions/login", json={"account": "fake-account", "password": "GAME_PASSWORD", "remember": True})
|
||||
self.assertEqual(response.status_code, 202)
|
||||
self.assertEqual(response.json()["status"], "queued")
|
||||
self.assertEqual(self.manager.calls[-1][1], "login")
|
||||
job_id = response.json()["id"]
|
||||
self.manager.jobs[(self.account_id, job_id)].update(
|
||||
status="succeeded", result={"servers": [{"id": 1, "name": "一区", "role_name": "角色"}],
|
||||
"has_saved_password": True, "key": "GAME_KEY", "token": "GAME_TOKEN",
|
||||
"message": "GAME_PASSWORD", "raw": {"account": "private"}})
|
||||
result = self.client.get(self.url + f"/jobs/{job_id}")
|
||||
self.assertEqual(result.json()["result"]["servers"][0]["name"], "一区")
|
||||
self.assertTrue(result.json()["result"]["has_saved_password"])
|
||||
for secret in ("GAME_PASSWORD", "GAME_TOKEN", "GAME_KEY", "private"):
|
||||
self.assertNotIn(secret, result.text)
|
||||
|
||||
def test_views_keep_column_and_filter_keys_and_return_loading(self):
|
||||
response = self.client.get(self.url + "/views/bag", params={"query": json.dumps({"category": "eggs", "search": "蛋"})})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
value = response.json()
|
||||
self.assertTrue(value["loading"])
|
||||
self.assertEqual(value["data"]["columns"][0]["key"], "name")
|
||||
self.assertEqual(value["data"]["filters"][0]["key"], "category")
|
||||
self.assertEqual(self.manager.calls[-1], ("view", "bag", {"category": "eggs", "search": "蛋"}))
|
||||
self.assertNotIn("VIEW_PRIVATE", response.text)
|
||||
|
||||
def test_schema_page_keys_survive_public_redaction(self):
|
||||
value = {"pages": [{"key": "login", "title": "登录", "form": []}], "columns": [{"key": "name", "label": "名称"}]}
|
||||
with patch("ranch_web.views.schema", return_value=value):
|
||||
response = self.client.get("/api/schema")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json(), value)
|
||||
|
||||
def test_real_demo_pipeline_uses_only_temporary_state_and_offline_core(self):
|
||||
root = self.root / "real-demo"
|
||||
with TestClient(create_app(config=WebConfig(data_dir=root)), base_url="http://localhost", client=("127.0.0.1", 50001)) as client:
|
||||
self.assertEqual(client.get("/api/accounts").json(), [])
|
||||
created = client.post("/api/accounts", json={"label": "隔离演示", "demo": True})
|
||||
self.assertEqual(created.status_code, 201)
|
||||
prefix = "/api/accounts/" + created.json()["id"]
|
||||
|
||||
def poll(job_id):
|
||||
deadline = time.monotonic() + 5
|
||||
while time.monotonic() < deadline:
|
||||
response = client.get(prefix + "/jobs/" + job_id)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
value = response.json()
|
||||
if value["status"] in {"succeeded", "failed", "cancelled"}:
|
||||
self.assertEqual(value["status"], "succeeded", value)
|
||||
return value
|
||||
time.sleep(.01)
|
||||
self.fail("离线任务未在时限内完成")
|
||||
|
||||
pages = client.get("/api/schema").json()["pages"]
|
||||
self.assertEqual(len(pages), 15)
|
||||
for page in pages:
|
||||
value = client.get(prefix + "/views/" + page["key"]).json()
|
||||
if value["loading"] and value.get("job_id"):
|
||||
poll(value["job_id"])
|
||||
value = client.get(prefix + "/views/" + page["key"]).json()
|
||||
self.assertEqual(value["data"]["page"], page["key"])
|
||||
self.assertTrue(all("key" in column for column in value["data"]["columns"]))
|
||||
if page["key"] == "mainline":
|
||||
self.assertEqual(value["data"]["tabs"], [
|
||||
{"key": "status", "title": "任务状态"},
|
||||
{"key": "policy", "title": "推进策略"},
|
||||
])
|
||||
self.assertTrue(value["data"]["form"])
|
||||
elif page["key"] == "hatching":
|
||||
self.assertEqual([tab["key"] for tab in value["data"]["tabs"]], ["孵蛋策略", "牧场策略", "喂养策略"])
|
||||
config = client.get(prefix + "/config").json()
|
||||
config["config"]["interval"] = 60
|
||||
saved = client.put(prefix + "/config", json=config)
|
||||
self.assertEqual(saved.status_code, 202)
|
||||
poll(saved.json()["job_id"])
|
||||
self.assertEqual(client.get(prefix + "/config").json()["config"]["interval"], 60)
|
||||
exported = client.get(prefix + "/config/export")
|
||||
document = poll(exported.json()["id"])["result"]
|
||||
self.assertEqual(document["assistantVersion"], "2.0.0.dev1")
|
||||
imported = client.post(prefix + "/config/import", json=document)
|
||||
self.assertEqual(imported.status_code, 202)
|
||||
poll(imported.json()["id"])
|
||||
self.assertFalse(client.get(prefix + "/status").json()["running"])
|
||||
self.network.assert_not_called()
|
||||
|
||||
def test_simple_view_query_is_supported_and_mixed_query_rejected(self):
|
||||
self.assertEqual(self.client.get(self.url + "/views/maps?search=abc").status_code, 200)
|
||||
self.assertEqual(self.manager.calls[-1], ("view", "maps", {"search": "abc"}))
|
||||
for params in ({"query": "[1]"}, {"query": "{"}, {"query": "{}", "search": "abc"}):
|
||||
with self.subTest(params=params):
|
||||
self.assertEqual(self.client.get(self.url + "/views/maps", params=params).status_code, 400)
|
||||
|
||||
def test_configuration_revision_and_deferred_application(self):
|
||||
self.assertEqual(self.client.get(self.url + "/config").json()["revision"], 3)
|
||||
response = self.client.put(self.url + "/config", json={"config": {"policy": {"fill": True}}, "revision": 3})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(self.manager.calls[-1], ("config", {"policy": {"fill": True}}, 3))
|
||||
self.manager.pending_config = True
|
||||
response = self.client.put(self.url + "/config", json={"config": {}, "revision": 4})
|
||||
self.assertEqual(response.status_code, 202)
|
||||
self.assertTrue(response.json()["pending"])
|
||||
self.assertEqual(response.json()["job_id"], "config_job")
|
||||
|
||||
def test_import_and_export_use_jobs_and_never_accept_server_paths(self):
|
||||
self.assertEqual(self.client.get(self.url + "/config/export").status_code, 202)
|
||||
self.assertEqual(self.manager.calls[-1], ("submit", "export_config", {}))
|
||||
self.assertEqual(self.client.post(self.url + "/config/import", json={"config": {"format": "offline"}}).status_code, 202)
|
||||
self.assertEqual(self.manager.calls[-1][1], "import_config")
|
||||
self.assertEqual(self.client.post(self.url + "/config/import", json={"format": "portable", "schema": 2}).status_code, 202)
|
||||
self.assertEqual(self.manager.calls[-1], ("submit", "import_config", {"config": {"format": "portable", "schema": 2}}))
|
||||
for payload in ({"path": "C:/private/file.csv"}, {"filename": "../file.csv"}, {"config": {"file_path": "/data/private"}}):
|
||||
with self.subTest(payload=payload):
|
||||
self.assertEqual(self.client.post(self.url + "/actions/import_yields", json=payload).status_code, 400)
|
||||
|
||||
def test_debug_detail_is_lazy_and_preserves_structured_redacted_body(self):
|
||||
response = self.client.get(self.url + "/logs?after=7&debug=true")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(self.manager.calls[-1], ("logs", 7, True))
|
||||
for secret in ("LOG_SECRET", "TOKEN_SECRET", "REQ_SECRET", "C:/private", "/data/profiles"):
|
||||
self.assertNotIn(secret, response.text)
|
||||
self.assertNotIn(("detail", 1), self.manager.calls)
|
||||
detail = self.client.get(self.url + "/logs/1")
|
||||
self.assertEqual(detail.status_code, 200)
|
||||
self.assertEqual(detail.json()["response"]["body"]["player"]["name"], "演示角色")
|
||||
self.assertEqual(detail.json()["request"]["body"]["operation"], "refresh")
|
||||
self.assertEqual(self.manager.calls[-1], ("detail", 1))
|
||||
for secret in ("GAME_KEY", "GAME_TOKEN", "PRIVATE_BEARER"):
|
||||
self.assertNotIn(secret, detail.text)
|
||||
alias = self.client.get(self.url + "/debug/1")
|
||||
self.assertEqual(alias.status_code, 200)
|
||||
self.assertEqual(alias.json(), detail.json())
|
||||
|
||||
def test_updates_check_and_apply_are_explicit_and_invalid_versions_never_dispatched(self):
|
||||
self.assertEqual(self.client.post("/api/system/updates/check").json()["status"], "no_release")
|
||||
self.assertEqual(self.updates.calls[-1], "check")
|
||||
for version in ("main", "v2.0.0.dev1", "2.0.0;whoami", "../v2.0.0", "v2.0.0\n", "v1.2.0", "2.0.1", "v2.01.0"):
|
||||
with self.subTest(version=version):
|
||||
response = self.client.post("/api/system/updates/apply", json={"version": version})
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertFalse(any(isinstance(call, tuple) for call in self.updates.calls))
|
||||
response = self.client.post("/api/system/updates/apply", json={"version": "v2.0.1"})
|
||||
self.assertEqual(response.status_code, 202)
|
||||
self.assertEqual(response.json()["status"], "unavailable")
|
||||
self.assertEqual(self.updates.calls[-1], ("apply", "v2.0.1"))
|
||||
|
||||
def test_identifiers_allowlists_and_validation_do_not_echo_input(self):
|
||||
self.manager.calls.clear()
|
||||
self.assertEqual(self.client.get("/api/accounts/账户/status").status_code, 422)
|
||||
self.assertEqual(self.client.get(self.url + "/jobs/a.b").status_code, 422)
|
||||
self.assertEqual(self.client.get(self.url + "/views/unknown").status_code, 404)
|
||||
self.assertEqual(self.client.post(self.url + "/actions/run_shell", json={}).status_code, 404)
|
||||
response = self.client.post("/api/accounts", json={"label": {"password": "MUST_NOT_ECHO"}, "demo": "true"})
|
||||
self.assertEqual(response.status_code, 422)
|
||||
self.assertNotIn("MUST_NOT_ECHO", response.text)
|
||||
self.assertEqual(self.manager.calls, [])
|
||||
|
||||
def test_body_limit_handles_declared_and_streamed_bodies(self):
|
||||
app = create_app(manager=self.manager, updates=self.updates, config=WebConfig(data_dir=self.root, max_body_bytes=1024))
|
||||
with TestClient(app, base_url="http://localhost", client=("127.0.0.1", 50001)) as client:
|
||||
for body in (b"x" * 1025, iter([b"x" * 800, b"x" * 800])):
|
||||
self.assertEqual(client.post(self.url + "/actions/refresh", content=body, headers={"Content-Type": "application/json"}).status_code, 413)
|
||||
self.assertEqual(client.post(self.url + "/actions/refresh", content=b"{}", headers={"Content-Type": "text/plain"}).status_code, 415)
|
||||
self.assertEqual(client.post(self.url + "/actions/refresh", content=b"{}", headers={"Content-Type": "application/json", "Content-Length": "3"}).status_code, 400)
|
||||
|
||||
def test_yield_import_declared_body_limit_is_12mib_for_exact_post_route(self):
|
||||
limit = 12 * 1024 * 1024
|
||||
prefix = b'{"filename":"data.csv","content_base64":""}'
|
||||
body = prefix + b" " * (limit - len(prefix))
|
||||
response = self.client.post(self.url + "/actions/import_yields", content=body, headers={"Content-Type": "application/json"})
|
||||
self.assertEqual(response.status_code, 202)
|
||||
self.assertEqual(self.manager.calls[-1], ("submit", "import_yields", {"filename": "data.csv", "content_base64": ""}))
|
||||
before = len(self.manager.calls)
|
||||
response = self.client.post(self.url + "/actions/import_yields", content=b"{}", headers={"Content-Type": "application/json", "Content-Length": str(limit + 1)})
|
||||
self.assertEqual(response.status_code, 413)
|
||||
ordinary = prefix + b" " * (1024 * 1024 + 1 - len(prefix))
|
||||
for method, endpoint in (("POST", self.url + "/actions/refresh"),
|
||||
("POST", self.url + "/actions/import_config"),
|
||||
("POST", self.url + "/config/import"),
|
||||
("POST", self.url + "/actions/import_yields_extra"),
|
||||
("PUT", self.url + "/actions/import_yields"),
|
||||
("POST", "/api/accounts/invalid.id/actions/import_yields")):
|
||||
with self.subTest(method=method, endpoint=endpoint):
|
||||
response = self.client.request(method, endpoint, content=ordinary, headers={"Content-Type": "application/json"})
|
||||
self.assertEqual(response.status_code, 413)
|
||||
self.assertEqual(len(self.manager.calls), before)
|
||||
|
||||
def test_yield_import_streamed_body_limit_is_12mib_and_other_routes_keep_1mib(self):
|
||||
async def stream(size):
|
||||
prefix = b'{"filename":"data.csv","content_base64":""}'
|
||||
yield prefix
|
||||
remaining = size - len(prefix)
|
||||
chunk = b" " * (256 * 1024)
|
||||
while remaining:
|
||||
count = min(remaining, len(chunk))
|
||||
yield chunk[:count]
|
||||
remaining -= count
|
||||
|
||||
async def scenario():
|
||||
transport = httpx.ASGITransport(app=self.app, client=("127.0.0.1", 50001))
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as client:
|
||||
response = await client.post(self.url + "/actions/import_yields", content=stream(12 * 1024 * 1024), headers={"Content-Type": "application/json"})
|
||||
self.assertNotIn("content-length", response.request.headers)
|
||||
self.assertEqual(response.status_code, 202)
|
||||
before = len(self.manager.calls)
|
||||
for endpoint, size in ((self.url + "/actions/import_yields", 12 * 1024 * 1024 + 1),
|
||||
(self.url + "/actions/refresh", 1024 * 1024 + 1)):
|
||||
response = await client.post(endpoint, content=stream(size), headers={"Content-Type": "application/json"})
|
||||
self.assertEqual(response.status_code, 413)
|
||||
self.assertEqual(len(self.manager.calls), before)
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_real_yield_action_accepts_exact_8mib_and_rejects_one_extra_byte(self):
|
||||
header = b"typeId,sell_money,note\n"
|
||||
row = b"1001010,7777," + b"x" * 4096 + b"\n"
|
||||
count, remainder = divmod(8 * 1024 * 1024 - len(header), len(row))
|
||||
content = header + row * count + b"\n" * remainder
|
||||
self.assertEqual(len(content), 8 * 1024 * 1024)
|
||||
with TestClient(create_app(config=WebConfig(data_dir=self.root / "large-yields")), base_url="http://localhost", client=("127.0.0.1", 50001)) as client:
|
||||
created = client.post("/api/accounts", json={"demo": True}).json()
|
||||
prefix = "/api/accounts/" + created["id"]
|
||||
for suffix, expected_status in ((b"", "succeeded"), (b"\n", "failed")):
|
||||
with self.subTest(decoded_bytes=len(content) + len(suffix)):
|
||||
response = client.post(prefix + "/actions/import_yields", json={"filename": "data.csv", "content_base64": base64.b64encode(content + suffix).decode("ascii")})
|
||||
self.assertEqual(response.status_code, 202, response.text)
|
||||
job_id = response.json()["id"]
|
||||
deadline = time.monotonic() + 5
|
||||
job = None
|
||||
while time.monotonic() < deadline:
|
||||
job = client.get(prefix + "/jobs/" + job_id).json()
|
||||
if job["status"] in {"succeeded", "failed", "cancelled"}:
|
||||
break
|
||||
time.sleep(.01)
|
||||
self.assertEqual(job["status"], expected_status, job)
|
||||
if expected_status == "succeeded":
|
||||
self.assertEqual(job["result"]["count"], 1)
|
||||
self.assertEqual(job["result"]["overrides"]["1001010"]["sell_money"], 7777)
|
||||
else:
|
||||
self.assertIn("8MiB", job["error"])
|
||||
self.assertEqual(client.get(prefix + "/config").json()["config"]["overrides"]["1001010"]["sell_money"], 7777)
|
||||
self.network.assert_not_called()
|
||||
|
||||
def test_real_update_service_request_metadata_survives_only_in_update_dtos(self):
|
||||
from ranch_web.updates import UpdateService
|
||||
data = self.root / "updater-data"
|
||||
control = self.root / "updater-control"
|
||||
control.mkdir()
|
||||
now = datetime.now(timezone.utc)
|
||||
capability = {"protocol": 1, "executor_id": "a" * 32, "enabled": True, "auto_apply": False,
|
||||
"heartbeat_at": now.isoformat(), "expires_at": (now + timedelta(minutes=15)).isoformat()}
|
||||
(control / "capability.json").write_text(json.dumps(capability), encoding="utf-8")
|
||||
service = UpdateService(data, "2.0.0.dev1")
|
||||
releases = [{"tag_name": "v2.1.0", "draft": False, "prerelease": False}]
|
||||
with patch.dict(os.environ, {"RANCH_WEB_UPDATER_DIR": str(control)}), patch("ranch_web.updates.github_releases", return_value=releases) as github:
|
||||
with TestClient(create_app(manager=self.manager, updates=service, config=self.settings), base_url="http://localhost", client=("127.0.0.1", 50001)) as client:
|
||||
checked = client.post("/api/system/updates/check").json()
|
||||
self.assertEqual(checked["latest_version"], "v2.1.0")
|
||||
self.assertTrue(checked["can_apply"])
|
||||
applied = client.post("/api/system/updates/apply", json={"version": "v2.1.0"})
|
||||
self.assertEqual(applied.status_code, 202)
|
||||
pending = applied.json()
|
||||
self.assertEqual(pending["status"], "pending")
|
||||
request = pending["request"]
|
||||
self.assertRegex(request["request_id"], r"^[0-9a-f]{32}$")
|
||||
self.assertEqual(request["version"], "v2.1.0")
|
||||
self.assertEqual(request["status"], "pending")
|
||||
self.assertEqual(client.get("/api/system/updates").json()["request"], request)
|
||||
self.assertEqual(client.get("/api/meta").json()["updates"]["request"], request)
|
||||
host = {"protocol": 1, "request_id": request["request_id"], "version": "v2.1.0", "status": "applying",
|
||||
"updated_at": now.isoformat(), "password": "HOST_PRIVATE", "key": "HOST_KEY", "path": "C:/private/updater"}
|
||||
(data / "updater-status.json").write_text(json.dumps(host), encoding="utf-8")
|
||||
for state in (client.get("/api/system/updates").json(), client.get("/api/meta").json()["updates"]):
|
||||
self.assertEqual(state["status"], "applying")
|
||||
self.assertEqual(state["request"]["status"], "applying")
|
||||
self.assertEqual(state["host_status"]["request_id"], request["request_id"])
|
||||
self.assertEqual(state["host_status"]["version"], "v2.1.0")
|
||||
for private in ("HOST_PRIVATE", "HOST_KEY", "C:/private", "executor_id"):
|
||||
self.assertNotIn(private, json.dumps(state))
|
||||
job = client.post(self.url + "/actions/refresh", json={}).json()
|
||||
self.manager.jobs[(self.account_id, job["id"])].update(status="succeeded", result={
|
||||
"request": {"request_id": request["request_id"], "key": "GAME_KEY"},
|
||||
"request_id": request["request_id"], "reqid": "GAME_REQID", "token": "GAME_TOKEN"})
|
||||
game = client.get(self.url + "/jobs/" + job["id"]).json()["result"]
|
||||
self.assertEqual(game, {})
|
||||
self.assertEqual(github.call_count, 2)
|
||||
self.network.assert_not_called()
|
||||
|
||||
def test_errors_hide_stack_traces_and_local_paths(self):
|
||||
errors = [ValueError("参数无效 C:/private/key.json password=VALUE_PRIVATE"), RuntimeError("状态不可用 /home/private token=RUNTIME_PRIVATE"), OSError("OSError: C:/private/INTERNAL_PRIVATE")]
|
||||
for error in errors:
|
||||
with self.subTest(error=type(error).__name__), patch.object(self.manager, "status", side_effect=error):
|
||||
response = self.client.get(self.url + "/status")
|
||||
self.assertIn(response.status_code, (400, 409, 500))
|
||||
for secret in ("C:/private", "/home/private", "VALUE_PRIVATE", "RUNTIME_PRIVATE", "INTERNAL_PRIVATE", "Traceback", "OSError"):
|
||||
self.assertNotIn(secret, response.text)
|
||||
|
||||
def test_job_errors_are_chinese_and_never_return_tracebacks(self):
|
||||
job = self.client.post(self.url + "/actions/refresh", json={}).json()
|
||||
self.manager.jobs[(self.account_id, job["id"])].update(status="failed", error='Traceback (most recent call last):\n File "C:/private/server.py", line 5\nsecret()')
|
||||
response = self.client.get(self.url + "/jobs/" + job["id"])
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json()["error"], "操作未完成,请查看已脱敏日志后重试")
|
||||
self.assertNotIn("Traceback", response.text)
|
||||
|
||||
def test_cli_demo_uses_explicit_temporary_root_and_no_browser(self):
|
||||
from ranch_web.__main__ import main
|
||||
root = self.root / "cli"
|
||||
|
||||
def run(application, **kwargs):
|
||||
self.assertEqual(application.state.config.data_dir, root)
|
||||
self.assertFalse(kwargs["access_log"])
|
||||
with TestClient(application, base_url="http://localhost", client=("127.0.0.1", 50001)) as client:
|
||||
accounts = client.get("/api/accounts").json()
|
||||
self.assertEqual(len(accounts), 1)
|
||||
self.assertTrue(accounts[0]["demo"])
|
||||
self.assertFalse(accounts[0]["running"])
|
||||
|
||||
with patch("ranch_web.__main__.uvicorn.run", side_effect=run) as runner, patch("ranch_web.__main__.webbrowser.open") as browser:
|
||||
result = main(["--host", "127.0.0.1", "--port", "8765", "--data-dir", str(root), "--demo", "--no-browser"])
|
||||
self.assertEqual(result, 0)
|
||||
runner.assert_called_once()
|
||||
browser.assert_not_called()
|
||||
self.network.assert_not_called()
|
||||
|
||||
def test_static_files_are_restricted_to_frontend_assets(self):
|
||||
for url in ("/static/.env", "/static/config.py", "/static/../app.py", "/static/%2e%2e/requirements.txt"):
|
||||
with self.subTest(url=url):
|
||||
self.assertEqual(self.client.get(url).status_code, 404)
|
||||
response = self.client.get("/")
|
||||
self.assertIn(response.status_code, (200, 503))
|
||||
if response.status_code == 200:
|
||||
self.assertIn("text/html", response.headers["content-type"])
|
||||
self.assertEqual(response.headers["x-content-type-options"], "nosniff")
|
||||
self.assertIn("frame-ancestors 'none'", response.headers["content-security-policy"])
|
||||
|
||||
def test_cli_help_and_factory_do_not_import_qt_or_open_private_state(self):
|
||||
project = Path(__file__).resolve().parents[2]
|
||||
script = "from ranch_web.app import create_app; import sys; assert not any(k.startswith('PySide6') or k.endswith('_gui') for k in sys.modules)"
|
||||
result = subprocess.run([sys.executable, "-c", script], cwd=project, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr.decode(errors="replace"))
|
||||
result = subprocess.run([sys.executable, "-m", "ranch_web", "--help"], cwd=project, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0)
|
||||
self.assertIn(b"--no-browser", result.stdout)
|
||||
self.assertIn(b"--data-dir", result.stdout)
|
||||
|
||||
def test_blocking_update_work_does_not_block_event_loop(self):
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
|
||||
def blocking_check():
|
||||
entered.set()
|
||||
if not release.wait(5):
|
||||
raise RuntimeError("offline synchronization timed out")
|
||||
return {"status": "no_release"}
|
||||
|
||||
async def scenario():
|
||||
transport = httpx.ASGITransport(app=self.app, client=("127.0.0.1", 50001))
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as client:
|
||||
task = asyncio.create_task(client.post("/api/system/updates/check"))
|
||||
try:
|
||||
self.assertTrue(await asyncio.to_thread(entered.wait, 2))
|
||||
response = await asyncio.wait_for(client.get("/api/health"), 1)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertFalse(task.done())
|
||||
finally:
|
||||
release.set()
|
||||
self.assertEqual((await task).status_code, 200)
|
||||
|
||||
with patch.object(self.updates, "check", side_effect=blocking_check):
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,197 @@
|
||||
"""Administrator sessions and browser boundary checks, entirely offline."""
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import httpx
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from ranch_web.app import create_app
|
||||
from ranch_web.config import COOKIE_NAME, WebConfig, hash_password, verify_password
|
||||
from ranch_web.tests.test_api import FakeManager, FakeUpdates
|
||||
|
||||
|
||||
class AuthTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix="ranch-web-auth-")
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name)
|
||||
self.manager, self.updates = FakeManager(), FakeUpdates()
|
||||
|
||||
def client(self, settings=None, **kwargs):
|
||||
settings = settings or WebConfig(data_dir=self.root)
|
||||
app = create_app(manager=self.manager, updates=self.updates, config=settings)
|
||||
return self.enterContext(TestClient(app, base_url="http://localhost", client=("127.0.0.1", 50000), **kwargs))
|
||||
|
||||
def test_loopback_bypass_is_local_and_has_no_password_cookie(self):
|
||||
client = self.client()
|
||||
self.assertEqual(client.get("/api/auth/status").json(), {"required": False, "authenticated": True, "access_mode": "local"})
|
||||
response = client.post("/api/accounts", json={"demo": True}, headers={"Origin": "http://localhost"})
|
||||
self.assertEqual(response.status_code, 201)
|
||||
self.assertNotIn("set-cookie", response.headers)
|
||||
remote = self.enterContext(TestClient(create_app(manager=self.manager, updates=self.updates, config=WebConfig(data_dir=self.root)), base_url="http://localhost", client=("192.0.2.1", 50001)))
|
||||
self.assertEqual(remote.get("/api/accounts").status_code, 403)
|
||||
self.assertFalse(remote.get("/api/auth/status").json()["authenticated"])
|
||||
|
||||
def test_remote_bind_and_public_proxy_names_require_password(self):
|
||||
for values in ({"host": "0.0.0.0"}, {"host": "::"}, {"host": "192.0.2.10"}, {"allowed_hosts": ("ranch.example",)}, {"allowed_origins": ("https://ranch.example",)}):
|
||||
with self.subTest(values=values), self.assertRaises(ValueError):
|
||||
WebConfig(data_dir=self.root, **values)
|
||||
|
||||
def test_plain_password_cookie_login_logout_and_replay(self):
|
||||
client = self.client(WebConfig(data_dir=self.root, password="离线管理密码"))
|
||||
self.assertEqual(client.get("/api/accounts").status_code, 401)
|
||||
self.assertFalse(client.get("/api/auth/status").json()["authenticated"])
|
||||
self.assertEqual(client.post("/api/auth/login", json={"password": "错误"}).status_code, 401)
|
||||
response = client.post("/api/auth/login", json={"password": "离线管理密码"})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertNotIn("离线管理密码", response.text)
|
||||
cookie = response.headers["set-cookie"].lower()
|
||||
self.assertIn("httponly", cookie)
|
||||
self.assertIn("samesite=strict", cookie)
|
||||
self.assertIn("path=/api", cookie)
|
||||
self.assertEqual(client.get("/api/accounts").status_code, 200)
|
||||
token = client.cookies.get(COOKIE_NAME)
|
||||
self.assertEqual(len(token), 43)
|
||||
self.assertEqual(client.post("/api/auth/logout").status_code, 200)
|
||||
self.assertEqual(client.get("/api/accounts", headers={"Cookie": f"{COOKIE_NAME}={token}"}).status_code, 401)
|
||||
|
||||
def test_hash_password_authentication_and_secure_proxy_cookie(self):
|
||||
encoded = hash_password("offline-password", iterations=100_000)
|
||||
settings = WebConfig(data_dir=self.root, host="0.0.0.0", password_hash=encoded, secure_cookie=True,
|
||||
allowed_hosts=("ranch.example",), allowed_origins=("https://ranch.example",))
|
||||
app = create_app(manager=self.manager, updates=self.updates, config=settings)
|
||||
client = self.enterContext(TestClient(app, base_url="https://ranch.example", client=("192.0.2.1", 50000)))
|
||||
response = client.post("/api/auth/login", json={"password": "offline-password"}, headers={"Origin": "https://ranch.example"})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertIn("Secure", response.headers["set-cookie"])
|
||||
self.assertEqual(client.get("/api/accounts").status_code, 200)
|
||||
self.assertNotIn(encoded, repr(settings))
|
||||
|
||||
def test_wrong_password_is_rate_limited_without_changing_accounts(self):
|
||||
client = self.client(WebConfig(data_dir=self.root, password="correct"))
|
||||
for _ in range(10):
|
||||
self.assertEqual(client.post("/api/auth/login", json={"password": "wrong"}).status_code, 401)
|
||||
response = client.post("/api/auth/login", json={"password": "wrong"})
|
||||
self.assertEqual(response.status_code, 429)
|
||||
self.assertEqual(self.manager.calls, [])
|
||||
|
||||
def test_concurrent_wrong_passwords_reserve_slots_without_serializing_other_peers(self):
|
||||
client = self.client(WebConfig(data_dir=self.root, password_hash=hash_password("correct", iterations=100_000)))
|
||||
self.assertEqual(client.post("/api/auth/login", json={"password": "correct"}).status_code, 200)
|
||||
cookie = client.cookies.get(COOKIE_NAME)
|
||||
entered, release, counter_lock = threading.Event(), threading.Event(), threading.Lock()
|
||||
verifying = 0
|
||||
|
||||
def blocked_verification(password, configured):
|
||||
nonlocal verifying
|
||||
if password == "wrong":
|
||||
with counter_lock:
|
||||
verifying += 1
|
||||
if verifying >= 10:
|
||||
entered.set()
|
||||
if not release.wait(5):
|
||||
raise AssertionError("password verification gate timed out")
|
||||
return verify_password(password, configured)
|
||||
|
||||
async def scenario():
|
||||
transport = httpx.ASGITransport(app=client.app, client=("127.0.0.1", 50001))
|
||||
other_transport = httpx.ASGITransport(app=client.app, client=("127.0.0.2", 50002))
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as http, httpx.AsyncClient(transport=other_transport, base_url="http://localhost") as other:
|
||||
rejected = 0
|
||||
rejected_two = asyncio.Event()
|
||||
|
||||
async def attempt():
|
||||
nonlocal rejected
|
||||
response = await http.post("/api/auth/login", json={"password": "wrong"})
|
||||
if response.status_code == 429:
|
||||
rejected += 1
|
||||
if rejected == 2:
|
||||
rejected_two.set()
|
||||
return response.status_code
|
||||
|
||||
tasks = [asyncio.create_task(attempt()) for _ in range(12)]
|
||||
try:
|
||||
self.assertTrue(await asyncio.to_thread(entered.wait, 2), "ten verifications must run concurrently")
|
||||
await asyncio.wait_for(rejected_two.wait(), 2)
|
||||
with counter_lock:
|
||||
self.assertEqual(verifying, 10)
|
||||
authenticated = await asyncio.wait_for(http.get("/api/accounts", headers={"Cookie": f"{COOKIE_NAME}={cookie}"}), 2)
|
||||
self.assertEqual(authenticated.status_code, 200)
|
||||
unrelated = await asyncio.wait_for(other.post("/api/auth/login", json={"password": "correct"}), 2)
|
||||
self.assertEqual(unrelated.status_code, 200)
|
||||
finally:
|
||||
release.set()
|
||||
outcomes = await asyncio.gather(*tasks)
|
||||
self.assertEqual(outcomes.count(401), 10)
|
||||
self.assertEqual(outcomes.count(429), 2)
|
||||
self.assertEqual((await http.post("/api/auth/login", json={"password": "wrong"})).status_code, 429)
|
||||
with counter_lock:
|
||||
self.assertEqual(verifying, 10)
|
||||
|
||||
with patch("ranch_web.app.verify_password", side_effect=blocked_verification):
|
||||
asyncio.run(scenario())
|
||||
self.assertEqual(self.manager.calls, ["list"])
|
||||
|
||||
def test_admin_password_does_not_corrupt_public_identifiers_or_versions(self):
|
||||
client = self.client(WebConfig(data_dir=self.root, password="1"))
|
||||
self.assertEqual(client.post("/api/auth/login", json={"password": "1"}).status_code, 200)
|
||||
self.assertEqual(client.get("/api/meta").json()["version"], "2.0.0.dev1")
|
||||
account = client.post("/api/accounts", json={"demo": True}).json()
|
||||
self.assertEqual(account["id"], "account_1")
|
||||
self.assertEqual(client.get("/api/accounts/account_1/status").status_code, 200)
|
||||
|
||||
def test_dns_rebinding_and_forwarded_host_cannot_bypass_host_allowlist(self):
|
||||
client = self.client()
|
||||
for hostname in ("attacker.example", "localhost.attacker.example", "127.0.0.1.attacker.example", "attacker.example:8765", "localhost@attacker.example", "localhost/evil", "localhost:bad"):
|
||||
with self.subTest(hostname=hostname):
|
||||
response = client.post("/api/accounts", headers={"Host": hostname, "X-Forwarded-Host": "localhost"}, json={"demo": True})
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(self.manager.calls, [])
|
||||
|
||||
def test_cross_site_writes_including_auth_are_blocked_before_dispatch(self):
|
||||
client = self.client(WebConfig(data_dir=self.root, password="correct"))
|
||||
for endpoint, payload in (("/api/auth/login", {"password": "correct"}), ("/api/auth/logout", {}), ("/api/accounts", {"demo": True}), ("/api/system/updates/apply", {})):
|
||||
for origin in ("https://attacker.example", "http://localhost.attacker.example", "null", "file://"):
|
||||
with self.subTest(endpoint=endpoint, origin=origin):
|
||||
self.assertEqual(client.post(endpoint, json=payload, headers={"Origin": origin}).status_code, 403)
|
||||
self.assertEqual(client.post("/api/auth/login", json={"password": "correct"}, headers={"Sec-Fetch-Site": "cross-site"}).status_code, 403)
|
||||
self.assertEqual(self.manager.calls, [])
|
||||
|
||||
def test_origin_includes_port_and_never_uses_forwarded_header(self):
|
||||
client = self.client()
|
||||
self.assertEqual(client.post("/api/accounts", json={}, headers={"Origin": "http://localhost:8765"}).status_code, 403)
|
||||
self.assertEqual(client.post("/api/accounts", json={}, headers={"Origin": "https://localhost", "X-Forwarded-Proto": "https"}).status_code, 403)
|
||||
self.assertEqual(client.post("/api/accounts", json={}, headers={"Origin": "http://localhost:80"}).status_code, 201)
|
||||
|
||||
def test_no_wildcard_cors_and_errors_do_not_echo_password(self):
|
||||
client = self.client(WebConfig(data_dir=self.root, password="correct"))
|
||||
response = client.options("/api/accounts", headers={"Origin": "https://attacker.example", "Access-Control-Request-Method": "POST"})
|
||||
self.assertNotIn("access-control-allow-origin", response.headers)
|
||||
response = client.post("/api/auth/login", json={"password": "SENSITIVE" * 1000})
|
||||
self.assertEqual(response.status_code, 422)
|
||||
self.assertNotIn("SENSITIVE", response.text)
|
||||
|
||||
def test_cookie_from_another_application_instance_is_invalid(self):
|
||||
settings = WebConfig(data_dir=self.root, password="correct")
|
||||
client = self.client(settings)
|
||||
client.post("/api/auth/login", json={"password": "correct"})
|
||||
token = client.cookies.get(COOKIE_NAME)
|
||||
another = self.client(settings)
|
||||
self.assertEqual(another.get("/api/accounts", headers={"Cookie": f"{COOKIE_NAME}={token}"}).status_code, 401)
|
||||
|
||||
def test_environment_and_cli_overrides_use_same_names(self):
|
||||
settings = WebConfig.from_env({"RANCH_WEB_HOST": "0.0.0.0", "RANCH_WEB_PORT": "8766", "RANCH_WEB_DATA_DIR": str(self.root / "env"), "RANCH_WEB_PASSWORD": "offline", "RANCH_WEB_SECURE_COOKIE": "1"}, port=8767, data_dir=self.root / "override")
|
||||
self.assertEqual(settings.host, "0.0.0.0")
|
||||
self.assertEqual(settings.port, 8767)
|
||||
self.assertEqual(settings.data_dir, self.root / "override")
|
||||
self.assertTrue(settings.secure_cookie)
|
||||
self.assertNotIn("offline", repr(settings))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Deterministic timing checks: no waits, no game clients and no Qt."""
|
||||
import math
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
|
||||
from ranch_assistant.model import Action
|
||||
from ranch_web.policies import default_config
|
||||
from ranch_web.scheduler import AccountSchedule
|
||||
|
||||
|
||||
class SchedulerTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.now = 1000.0
|
||||
self.draws = []
|
||||
|
||||
def uniform(low, high):
|
||||
self.draws.append((low, high))
|
||||
return (low + high) / 2
|
||||
|
||||
self.schedule = AccountSchedule(clock=lambda: self.now, uniform=uniform)
|
||||
self.config = default_config()
|
||||
self.config["policy"].update(enabled=True, fill=True, gift_enabled=True, breakthrough_targets={"101": 1})
|
||||
self.config["explore_policy"]["enabled"] = True
|
||||
self.pending = False
|
||||
self.snapshot = SimpleNamespace(now=1000, raw={"exploreTeams": []})
|
||||
self.engine = SimpleNamespace(snapshot=self.snapshot, demo=True, client=None,
|
||||
heartbeat_enabled=True, last_heartbeat=1000, pending_recovery_due=lambda: False,
|
||||
master_sync_due=lambda: False, growth_sync_due=lambda: False,
|
||||
_progression_pending=lambda: self.pending, _breakthrough_pending=None,
|
||||
explore_planner=SimpleNamespace(pending=lambda snapshot: None, remaining=lambda snapshot, team: 8),
|
||||
gift_planner=SimpleNamespace(next_ready_at=1003),
|
||||
pending_hatches=[Action("hatch", "hatch", "offline/hatch", {})])
|
||||
self.plans = [Action(kind, kind, "offline/" + kind, {}) for kind in ("progression", "explore_start", "breakthrough", "gift")]
|
||||
self.schedule.monitor()
|
||||
self.schedule.next_poll = math.inf
|
||||
|
||||
def test_hatch_uses_one_to_two_seconds_and_kind_isolation(self):
|
||||
self.schedule.arm(self.engine, self.config, True, self.plans)
|
||||
self.assertEqual(self.schedule.next_fast["hatch"], 1001.5)
|
||||
self.assertIn((1, 2), self.draws)
|
||||
self.now = 1002
|
||||
self.assertEqual(self.schedule.due(self.engine, self.config, True), "hatch")
|
||||
self.assertNotEqual(self.schedule.due(self.engine, self.config, True), "poll")
|
||||
|
||||
def test_completing_one_kind_preserves_other_deadlines(self):
|
||||
self.schedule.arm(self.engine, self.config, True, self.plans)
|
||||
self.schedule.next_fast["breakthrough"] = 999
|
||||
self.schedule.next_fast["hatch"] = 999
|
||||
self.now += 3
|
||||
self.snapshot.now = self.now
|
||||
self.schedule.arm(self.engine, self.config, True, self.plans, completed="gift")
|
||||
self.assertEqual(self.schedule.next_fast["breakthrough"], 999)
|
||||
self.assertEqual(self.schedule.next_fast["hatch"], 999)
|
||||
self.assertEqual(self.schedule.next_fast["gift"], 1003)
|
||||
|
||||
def test_stop_keeps_monitoring_and_clears_fast_deadlines(self):
|
||||
self.schedule.arm(self.engine, self.config, True, self.plans)
|
||||
self.schedule.stop()
|
||||
self.assertTrue(self.schedule.monitoring)
|
||||
self.assertTrue(all(math.isinf(value) for value in self.schedule.next_fast.values()))
|
||||
self.schedule.next_poll = self.now
|
||||
self.assertEqual(self.schedule.due(self.engine, self.config, False), "poll")
|
||||
|
||||
def test_unknown_pending_suppresses_all_fast_retries(self):
|
||||
self.pending = True
|
||||
self.schedule.arm(self.engine, self.config, True, self.plans)
|
||||
self.assertTrue(all(math.isinf(value) for value in self.schedule.next_fast.values()))
|
||||
|
||||
def test_priority_heartbeat_reconciliation_master_growth_then_monitor(self):
|
||||
self.engine.demo, self.engine.client = False, object()
|
||||
self.engine.last_heartbeat = 0
|
||||
self.engine.pending_recovery_due = lambda: True
|
||||
self.engine.master_sync_due = lambda: True
|
||||
self.engine.growth_sync_due = lambda: True
|
||||
self.assertEqual(self.schedule.due(self.engine, self.config, False), "heartbeat")
|
||||
self.engine.last_heartbeat = self.now
|
||||
self.assertEqual(self.schedule.due(self.engine, self.config, False), "reconcile")
|
||||
self.engine.pending_recovery_due = lambda: False
|
||||
self.assertEqual(self.schedule.due(self.engine, self.config, False), "master_sync")
|
||||
self.engine.master_sync_due = lambda: False
|
||||
self.assertEqual(self.schedule.due(self.engine, self.config, False), "growth_sync")
|
||||
|
||||
def test_random_monitor_interval_is_redrawn_each_time(self):
|
||||
self.config["interval"] = 120
|
||||
self.schedule.poll_finished(self.config)
|
||||
self.now += 1
|
||||
self.schedule.poll_finished(self.config)
|
||||
self.assertEqual(self.draws, [(0, 120), (0, 120)])
|
||||
self.assertEqual(self.schedule.next_poll, 1061)
|
||||
|
||||
def test_running_exploration_arms_its_completion_deadline(self):
|
||||
self.snapshot.raw["exploreTeams"] = [{"id": 1, "status": 1}]
|
||||
self.schedule.arm(self.engine, self.config, True, [])
|
||||
self.assertEqual(self.schedule.next_fast["explore"], 1009)
|
||||
|
||||
def test_maintenance_errors_back_off_instead_of_busy_looping(self):
|
||||
self.engine.demo, self.engine.client = False, object()
|
||||
self.engine.last_heartbeat = 0
|
||||
self.schedule.maintenance_failed("heartbeat")
|
||||
self.assertIsNone(self.schedule.due(self.engine, self.config, False))
|
||||
self.now += 30
|
||||
self.assertEqual(self.schedule.due(self.engine, self.config, False), "heartbeat")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,595 @@
|
||||
"""Account lifecycle/concurrency with temporary state and offline HTTP fakes."""
|
||||
from copy import deepcopy
|
||||
from dataclasses import replace
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from requests import Response
|
||||
from requests.sessions import Session as HttpSession
|
||||
|
||||
from ranch_assistant.api import Client, Session, decode, encode
|
||||
from ranch_assistant.engine import Engine, demo_snapshot
|
||||
from ranch_assistant.model import Catalog
|
||||
from ranch_web.service import RevisionConflict, WebManager
|
||||
from ranch_web.store import session_identity
|
||||
|
||||
|
||||
class FakeClient(Client):
|
||||
catalog = Catalog()
|
||||
calls = []
|
||||
|
||||
def __init__(self, session, trace=None):
|
||||
super().__init__(session, trace=trace)
|
||||
self.raw = deepcopy(demo_snapshot(self.catalog).raw)
|
||||
role = session.role_id or 100 + (session.server_id or 1)
|
||||
self.raw["master"].update(id=role, roleName="离线角色 " + str(role), level=1, exp=0, timeTi=int(time.time() * 1000))
|
||||
for monster in self.raw["monsters"]:
|
||||
monster.update(process=3, mode=2)
|
||||
self.http.post = self._post
|
||||
self.closed = False
|
||||
|
||||
def _post(self, url, data, **kwargs):
|
||||
payload = decode(data, self.session.key)
|
||||
self.calls.append((self.session.account_id, url, payload))
|
||||
if url.endswith("masterService/masterQueryDetail"):
|
||||
role = self.session.role_id or 100 + self.session.server_id
|
||||
self.raw["master"].update(id=role, roleName="离线角色 " + str(role))
|
||||
if url.endswith("monsterService/monsterLock"):
|
||||
for monster in self.raw["monsters"]:
|
||||
if monster["id"] == payload["monsterId"]:
|
||||
monster["lock"] = payload["lock"]
|
||||
return SimpleNamespace(status_code=200, content=encode(self.raw | {"resCode": 0}, self.session.key), headers={})
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
super().close()
|
||||
|
||||
|
||||
class FakeLogin:
|
||||
client_factory = FakeClient
|
||||
|
||||
def __init__(self, catalog, device, *, trace=None):
|
||||
self.catalog, self.device, self.trace = catalog, device, trace
|
||||
|
||||
def authenticate(self, account, password):
|
||||
client = FakeClient(Session(token="synthetic-center-token", account_id=account,
|
||||
account_name=account), trace=self.trace)
|
||||
response = {"servers": [{"id": identifier, "serverName": "测试区 " + str(identifier),
|
||||
"gameServerAddress": "https://offline.invalid/game/", "platform": "ANDROID"} for identifier in (1, 2)],
|
||||
"masterInfos": [{"serverId": 1, "masterName": "离线角色 101"}],
|
||||
"playerInfo": {"token": "synthetic-center-token"}}
|
||||
return client, response, {"uid": account, "center_url": "https://offline.invalid/center/",
|
||||
"channel": "DYD", "device_id": self.device}
|
||||
|
||||
|
||||
class ServiceTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = self.enterContext(tempfile.TemporaryDirectory(prefix="ranch-web-runtime-test-"))
|
||||
self.root = Path(self.temp) / "web"
|
||||
# Any unmocked requests call is an immediate test failure, never traffic.
|
||||
self._http_request = HttpSession.request
|
||||
self.enterContext(patch("requests.sessions.Session.request", side_effect=AssertionError("Live HTTP is forbidden")))
|
||||
FakeClient.calls = []
|
||||
self.manager = WebManager(self.root, start_scheduler=False, login_factory=FakeLogin)
|
||||
self.addCleanup(self.manager.close)
|
||||
|
||||
def account(self, demo=True):
|
||||
identifier = self.manager.create_account("测试页签", demo)["id"]
|
||||
self.idle(identifier)
|
||||
self.assertEqual(self.manager.status(identifier)["error"], "")
|
||||
return identifier
|
||||
|
||||
def idle(self, identifier, timeout=10):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if not self.manager.status(identifier)["busy"]:
|
||||
return
|
||||
time.sleep(.005)
|
||||
self.fail("Account did not become idle")
|
||||
|
||||
def job(self, identifier, job, *, status="succeeded"):
|
||||
deadline = time.monotonic() + 10
|
||||
while time.monotonic() < deadline:
|
||||
result = self.manager.job(identifier, job["id"])
|
||||
if result["status"] in {"succeeded", "failed", "cancelled"}:
|
||||
self.assertEqual(result["status"], status, result)
|
||||
self.idle(identifier)
|
||||
return result
|
||||
time.sleep(.005)
|
||||
self.fail("Job did not complete")
|
||||
|
||||
def login(self, identifier, account="synthetic-owner", server=1):
|
||||
login = self.job(identifier, self.manager.submit(identifier, "login",
|
||||
{"account": account, "password": "synthetic-password", "remember": True}))
|
||||
self.job(identifier, self.manager.submit(identifier, "enter_server", {"server_id": server}))
|
||||
return login
|
||||
|
||||
def enable(self, identifier):
|
||||
config = self.manager.get_config(identifier)
|
||||
config["config"]["daily_policy"].update(enabled=True, selected=["gift"])
|
||||
pending = self.manager.set_config(identifier, config["config"], config["revision"])
|
||||
self.assertTrue(pending["pending"])
|
||||
self.job(identifier, pending["job"])
|
||||
|
||||
def test_real_engine_demo_config_autosave_and_revision_conflict(self):
|
||||
identifier = self.account()
|
||||
self.assertIsInstance(self.manager._worker(identifier).engine, Engine)
|
||||
self.assertEqual(self.manager.status(identifier)["player"]["name"], demo_snapshot(self.manager.catalog).raw["master"]["roleName"])
|
||||
config = self.manager.get_config(identifier)
|
||||
config["config"]["policy"]["keep_money"] = 2345
|
||||
result = self.manager.set_config(identifier, config["config"], config["revision"])
|
||||
self.assertEqual(result["revision"], 0)
|
||||
self.job(identifier, result["job"])
|
||||
self.assertEqual(self.manager.get_config(identifier)["config"]["policy"]["keep_money"], 2345)
|
||||
self.assertEqual(self.manager._worker(identifier).engine.policy.keep_money, 2345)
|
||||
with self.assertRaises(RevisionConflict):
|
||||
self.manager.set_config(identifier, config["config"], 0)
|
||||
|
||||
def test_login_select_server_public_metadata_and_restart_restore(self):
|
||||
identifier = self.account(False)
|
||||
result = self.login(identifier)
|
||||
public = json.dumps(result)
|
||||
for secret in ("synthetic-password", "synthetic-center-token", "gameServerAddress", "center_url", "reqid"):
|
||||
self.assertNotIn(secret, public)
|
||||
self.assertEqual(result["result"]["servers"][0]["role_name"], "离线角色 101")
|
||||
status = self.manager.status(identifier)
|
||||
self.assertTrue(status["connected"])
|
||||
self.assertFalse(status["demo"])
|
||||
self.assertFalse(status["running"])
|
||||
worker = self.manager._worker(identifier)
|
||||
identity = worker.active_identity
|
||||
before = worker.securestore.load(identity).reqid
|
||||
self.enable(identifier)
|
||||
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||
self.manager.close()
|
||||
count = len(FakeClient.calls)
|
||||
self.manager = WebManager(self.root, start_scheduler=False, login_factory=FakeLogin)
|
||||
self.addCleanup(self.manager.close)
|
||||
self.idle(identifier)
|
||||
self.assertEqual(len(FakeClient.calls), count, "Restart issued an unsolicited request")
|
||||
self.assertFalse(self.manager.status(identifier)["running"])
|
||||
self.assertFalse(self.manager.status(identifier)["connected"])
|
||||
self.assertTrue(self.manager.get_config(identifier)["config"]["daily_policy"]["enabled"])
|
||||
self.job(identifier, self.manager.submit(identifier, "restore_session", {"session_id": identity}))
|
||||
restored = self.manager._worker(identifier).securestore.load(identity)
|
||||
self.assertGreater(restored.reqid, before)
|
||||
self.assertFalse(self.manager.status(identifier)["running"])
|
||||
|
||||
def test_role_workspaces_do_not_copy_targets_or_other_profiles_overrides(self):
|
||||
first, other = self.account(False), self.account()
|
||||
self.login(first)
|
||||
worker = self.manager._worker(first)
|
||||
role_one = worker.state_root
|
||||
config = self.manager.get_config(first)
|
||||
config["config"]["policy"]["keep_money"] = 9876
|
||||
config["config"]["overrides"] = {next(iter(worker.catalog.monsters)): {"sell_money": 123}}
|
||||
self.job(first, self.manager.set_config(first, config["config"])["job"])
|
||||
self.assertEqual(self.manager._worker(other).catalog.overrides, {})
|
||||
self.manager.view(first, "incubator")
|
||||
self.idle(first)
|
||||
self.assertIsNotNone(self.manager.view(first, "incubator")["data"])
|
||||
self.login(first, server=2)
|
||||
self.assertNotEqual(worker.state_root, role_one)
|
||||
self.assertIsNone(self.manager.view(first, "incubator")["data"], "Previous role view escaped the cache")
|
||||
self.idle(first)
|
||||
self.assertNotEqual(self.manager.get_config(first)["config"]["policy"]["keep_money"], 9876)
|
||||
self.assertEqual(worker.catalog.overrides, {})
|
||||
saved = next(row["session_id"] for row in worker.securestore.entries() if row["session_id"] != worker.active_identity)
|
||||
self.job(first, self.manager.submit(first, "restore_session", {"session_id": saved}))
|
||||
self.assertEqual(worker.state_root, role_one)
|
||||
self.assertEqual(self.manager.get_config(first)["config"]["policy"]["keep_money"], 9876)
|
||||
|
||||
def test_duplicate_account_server_role_connection_is_refused(self):
|
||||
first, second = self.account(False), self.account(False)
|
||||
self.login(first)
|
||||
self.job(second, self.manager.submit(second, "login", {"account": "synthetic-owner", "password": "synthetic-password"}))
|
||||
result = self.job(second, self.manager.submit(second, "enter_server", {"server_id": 1}), status="failed")
|
||||
self.assertIn("另一个", result["error"])
|
||||
self.assertTrue(self.manager.status(first)["connected"])
|
||||
self.assertFalse(self.manager.status(second)["connected"])
|
||||
|
||||
def test_stop_cancels_queued_start_and_consumer_but_not_read_only_jobs(self):
|
||||
identifier = self.account()
|
||||
self.enable(identifier)
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
self.addCleanup(release.set)
|
||||
calls = []
|
||||
|
||||
def action(worker, operation, payload):
|
||||
calls.append(operation)
|
||||
if payload.get("hold"):
|
||||
entered.set()
|
||||
release.wait(5)
|
||||
return {"message": operation}
|
||||
|
||||
with patch("ranch_web.actions.execute_action", side_effect=action):
|
||||
held = self.manager.submit(identifier, "refresh", {"hold": True})
|
||||
self.assertTrue(entered.wait(2))
|
||||
start = self.manager.submit(identifier, "start")
|
||||
consumer = self.manager.submit(identifier, "consume_probe")
|
||||
reader = self.manager.submit(identifier, "refresh")
|
||||
stopped = self.manager.submit(identifier, "stop")
|
||||
self.assertEqual(stopped["status"], "succeeded")
|
||||
self.assertFalse(self.manager.status(identifier)["running"])
|
||||
release.set()
|
||||
self.job(identifier, held)
|
||||
self.job(identifier, start, status="cancelled")
|
||||
self.job(identifier, consumer, status="cancelled")
|
||||
self.job(identifier, reader)
|
||||
self.assertEqual(calls, ["refresh", "refresh"])
|
||||
self.assertFalse(self.manager._worker(identifier).engine.auto)
|
||||
self.assertTrue(self.manager._worker(identifier).engine._progression_cancel.is_set())
|
||||
|
||||
def test_policy_queued_before_stop_saves_without_reactivating(self):
|
||||
identifier = self.account()
|
||||
self.enable(identifier)
|
||||
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
self.addCleanup(release.set)
|
||||
|
||||
def hold(worker, operation, payload):
|
||||
entered.set()
|
||||
release.wait(5)
|
||||
return {}
|
||||
|
||||
with patch("ranch_web.actions.execute_action", side_effect=hold):
|
||||
held = self.manager.submit(identifier, "refresh")
|
||||
self.assertTrue(entered.wait(2))
|
||||
config = self.manager.get_config(identifier)["config"]
|
||||
config["policy"]["keep_money"] = 4567
|
||||
pending = self.manager.set_config(identifier, config)
|
||||
self.manager.submit(identifier, "stop")
|
||||
release.set()
|
||||
self.job(identifier, held)
|
||||
self.job(identifier, pending["job"])
|
||||
worker = self.manager._worker(identifier)
|
||||
self.assertEqual(worker.engine.policy.keep_money, 4567)
|
||||
self.assertFalse(worker.engine.auto)
|
||||
self.assertTrue(worker.engine._progression_cancel.is_set())
|
||||
self.assertFalse(worker.running)
|
||||
|
||||
def test_slow_account_does_not_block_other_account_status_or_cached_view(self):
|
||||
first, second = self.account(), self.account()
|
||||
self.manager.view(first, "incubator")
|
||||
self.idle(first)
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
self.addCleanup(release.set)
|
||||
|
||||
def action(worker, operation, payload):
|
||||
if worker.id == first:
|
||||
entered.set()
|
||||
release.wait(5)
|
||||
return {"message": "read"}
|
||||
|
||||
with patch("ranch_web.actions.execute_action", side_effect=action):
|
||||
held = self.manager.submit(first, "refresh")
|
||||
self.assertTrue(entered.wait(2))
|
||||
started = time.monotonic()
|
||||
self.assertTrue(self.manager.status(first)["busy"])
|
||||
view = self.manager.view(first, "incubator")
|
||||
self.assertIsNotNone(view["data"])
|
||||
self.manager.logs(first)
|
||||
self.assertLess(time.monotonic() - started, .2)
|
||||
self.job(second, self.manager.submit(second, "refresh"))
|
||||
self.assertTrue(self.manager.status(first)["busy"])
|
||||
release.set()
|
||||
self.job(first, held)
|
||||
|
||||
def test_worker_owned_manual_stop_preserves_confirmed_request(self):
|
||||
identifier = self.account(False)
|
||||
self.login(identifier)
|
||||
worker = self.manager._worker(identifier)
|
||||
monster = next(row for row in worker.engine.snapshot.raw["monsters"] if not row.get("lock"))
|
||||
result = self.job(identifier, self.manager.submit(identifier, "lock", {"monster_ids": [monster["id"]]}))
|
||||
self.assertTrue(worker.engine.snapshot.monsters[monster["id"]]["lock"])
|
||||
self.assertIn("message", result["result"])
|
||||
self.assertFalse(worker.running)
|
||||
|
||||
def test_enter_job_is_not_terminal_until_persistence_and_summary_are_published(self):
|
||||
identifier = self.account(False)
|
||||
self.job(identifier, self.manager.submit(identifier, "login", {"account": "synthetic-owner", "password": "synthetic-password"}))
|
||||
worker = self.manager._worker(identifier)
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
self.addCleanup(release.set)
|
||||
original = worker._persist_session
|
||||
|
||||
def persist():
|
||||
if worker.engine.client is not None:
|
||||
entered.set()
|
||||
release.wait(5)
|
||||
return original()
|
||||
|
||||
with patch.object(worker, "_persist_session", side_effect=persist):
|
||||
selected = self.manager.submit(identifier, "enter_server", {"server_id": 1})
|
||||
self.assertTrue(entered.wait(2))
|
||||
self.assertEqual(self.manager.job(identifier, selected["id"])["status"], "running")
|
||||
release.set()
|
||||
self.job(identifier, selected)
|
||||
self.assertTrue(self.manager.status(identifier)["connected"])
|
||||
|
||||
def test_stop_between_manual_requests_prevents_remaining_dispatches(self):
|
||||
identifier = self.account(False)
|
||||
self.login(identifier)
|
||||
worker = self.manager._worker(identifier)
|
||||
client = worker.engine.client
|
||||
ids = [row["id"] for row in worker.engine.snapshot.raw["monsters"] if not row.get("lock")][:2]
|
||||
self.assertEqual(len(ids), 2)
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
self.addCleanup(release.set)
|
||||
original = client.http.post
|
||||
|
||||
def post(url, data, **kwargs):
|
||||
value = original(url, data, **kwargs)
|
||||
if url.endswith("monsterService/monsterLock"):
|
||||
entered.set()
|
||||
release.wait(5)
|
||||
return value
|
||||
|
||||
with patch.object(client.http, "post", side_effect=post):
|
||||
job = self.manager.submit(identifier, "lock", {"monster_ids": ids})
|
||||
self.assertTrue(entered.wait(2))
|
||||
self.manager.submit(identifier, "stop")
|
||||
release.set()
|
||||
self.job(identifier, job, status="cancelled")
|
||||
locks = [call for call in FakeClient.calls if call[1].endswith("monsterService/monsterLock")]
|
||||
self.assertEqual(len(locks), 1)
|
||||
self.assertTrue(any(event["kind"] == "response" and event["operation"] == "monsterService/monsterLock"
|
||||
for event in worker.trace.events), "Already-sent response evidence was discarded")
|
||||
|
||||
def test_stop_during_encoding_prevents_the_encoded_write_reaching_http(self):
|
||||
identifier = self.account(False)
|
||||
self.login(identifier)
|
||||
worker = self.manager._worker(identifier)
|
||||
monster = next(row for row in worker.engine.snapshot.raw["monsters"] if not row.get("lock"))
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
self.addCleanup(release.set)
|
||||
before = len(FakeClient.calls)
|
||||
high_water = worker.securestore.load(worker.active_identity).reqid
|
||||
|
||||
def paused_encode(value, key):
|
||||
encoded = encode(value, key)
|
||||
if "monsterId" in value and "lock" in value:
|
||||
entered.set()
|
||||
if not release.wait(5):
|
||||
raise AssertionError("Encoding gate was not released")
|
||||
return encoded
|
||||
|
||||
with patch("ranch_assistant.api.encode", side_effect=paused_encode):
|
||||
job = self.manager.submit(identifier, "lock", {"monster_ids": [monster["id"]]})
|
||||
self.assertTrue(entered.wait(2))
|
||||
stopped = self.manager.submit(identifier, "stop")
|
||||
self.assertEqual(stopped["status"], "succeeded")
|
||||
self.assertFalse(release.is_set())
|
||||
release.set()
|
||||
self.job(identifier, job, status="cancelled")
|
||||
writes = sum(call[1].endswith("monsterService/monsterLock") for call in FakeClient.calls[before:])
|
||||
self.assertEqual(writes, 0, "An encoded cancelled write reached HTTP")
|
||||
self.assertGreater(worker.securestore.load(worker.active_identity).reqid, high_water)
|
||||
|
||||
def test_stop_during_requests_preparation_prevents_adapter_dispatch(self):
|
||||
identifier = self.account(False)
|
||||
self.login(identifier)
|
||||
worker = self.manager._worker(identifier)
|
||||
client = worker.engine.client
|
||||
http = client.http
|
||||
monster = next(row for row in worker.engine.snapshot.raw["monsters"] if not row.get("lock"))
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
self.addCleanup(release.set)
|
||||
original_prepare = http.prepare_request
|
||||
before = len(FakeClient.calls)
|
||||
|
||||
def paused_prepare(request):
|
||||
prepared = original_prepare(request)
|
||||
if request.url.endswith("monsterService/monsterLock"):
|
||||
entered.set()
|
||||
if not release.wait(5):
|
||||
raise AssertionError("Prepared-request gate was not released")
|
||||
return prepared
|
||||
|
||||
def offline_send(request, **kwargs):
|
||||
value = client._post(request.url, request.body)
|
||||
response = Response()
|
||||
response.status_code, response._content, response.headers = value.status_code, value.content, value.headers
|
||||
response.url, response.request = request.url, request
|
||||
return response
|
||||
|
||||
adapter = http.get_adapter("https://offline.invalid/")
|
||||
# Exercise requests' real post -> request -> prepare -> send pipeline.
|
||||
# The adapter stays fake; the class-wide live-HTTP prohibition stays on.
|
||||
with patch.object(http, "post", HttpSession.post.__get__(http, HttpSession)), \
|
||||
patch.object(http, "request", self._http_request.__get__(http, HttpSession)), \
|
||||
patch.object(http, "prepare_request", side_effect=paused_prepare), \
|
||||
patch.object(adapter, "send", side_effect=offline_send):
|
||||
job = self.manager.submit(identifier, "lock", {"monster_ids": [monster["id"]]})
|
||||
self.assertTrue(entered.wait(2))
|
||||
started = time.monotonic()
|
||||
self.manager.submit(identifier, "stop")
|
||||
self.assertLess(time.monotonic() - started, .2)
|
||||
release.set()
|
||||
self.job(identifier, job, status="cancelled")
|
||||
writes = sum(call[1].endswith("monsterService/monsterLock") for call in FakeClient.calls[before:])
|
||||
self.assertEqual(writes, 0, "A prepared cancelled request reached the adapter")
|
||||
|
||||
def test_config_change_during_automatic_poll_keeps_execution_enabled(self):
|
||||
identifier = self.account(False)
|
||||
self.login(identifier)
|
||||
self.enable(identifier)
|
||||
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||
worker = self.manager._worker(identifier)
|
||||
client = worker.engine.client
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
self.addCleanup(release.set)
|
||||
original = client.http.post
|
||||
|
||||
def paused_response(url, data, **kwargs):
|
||||
response = original(url, data, **kwargs)
|
||||
if url.endswith("masterService/masterQueryDetail"):
|
||||
entered.set()
|
||||
if not release.wait(5):
|
||||
raise AssertionError("Snapshot response gate was not released")
|
||||
return response
|
||||
|
||||
worker.engine.last_heartbeat = time.monotonic()
|
||||
worker.schedule.next_poll = 0
|
||||
with patch.object(client.http, "post", side_effect=paused_response):
|
||||
worker.request_tick()
|
||||
self.assertTrue(entered.wait(2))
|
||||
self.assertTrue(worker.running)
|
||||
config = self.manager.get_config(identifier)["config"]
|
||||
config["policy"]["keep_money"] += 100
|
||||
pending = self.manager.set_config(identifier, config)
|
||||
self.assertTrue(worker.running)
|
||||
release.set()
|
||||
self.job(identifier, pending["job"])
|
||||
self.assertTrue(self.manager.status(identifier)["running"], "Config cancellation disabled the execution switch")
|
||||
self.assertTrue(worker.engine.auto)
|
||||
self.assertEqual(worker.engine.policy.keep_money, config["policy"]["keep_money"])
|
||||
|
||||
def test_engine_pause_in_current_generation_still_disables_execution(self):
|
||||
identifier = self.account()
|
||||
self.enable(identifier)
|
||||
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||
worker = self.manager._worker(identifier)
|
||||
worker.schedule.next_poll = 0
|
||||
|
||||
def stopped_poll(**kwargs):
|
||||
worker.engine.auto = False
|
||||
return worker.engine.snapshot, [], "Engine paused after validation"
|
||||
|
||||
with patch.object(worker.engine, "poll", side_effect=stopped_poll):
|
||||
worker.request_tick()
|
||||
self.idle(identifier)
|
||||
self.assertFalse(self.manager.status(identifier)["running"])
|
||||
self.assertFalse(worker.engine.auto)
|
||||
|
||||
def test_view_task_indices_stay_bounded_after_many_filters_and_failure(self):
|
||||
identifier = self.account()
|
||||
worker = self.manager._worker(identifier)
|
||||
for index in range(120):
|
||||
view = self.manager.view(identifier, "incubator", {"search": str(index)})
|
||||
self.job(identifier, {"id": view["job_id"]})
|
||||
self.assertLessEqual(len(worker._views), 32)
|
||||
self.assertLessEqual(len(worker._view_jobs), 32, "Completed view task indices grow with every filter")
|
||||
self.assertFalse(self.manager.view(identifier, "incubator", {"search": "119"})["loading"])
|
||||
with patch("ranch_web.views.build_view", side_effect=ValueError("synthetic view failure")):
|
||||
view = self.manager.view(identifier, "incubator", {"search": "failed"})
|
||||
self.job(identifier, {"id": view["job_id"]}, status="failed")
|
||||
self.assertNotIn(("incubator", '{"search": "failed"}'), worker._view_jobs)
|
||||
retry = self.manager.view(identifier, "incubator", {"search": "failed"})
|
||||
self.job(identifier, {"id": retry["job_id"]})
|
||||
self.assertFalse(self.manager.view(identifier, "incubator", {"search": "failed"})["loading"])
|
||||
|
||||
def test_failed_counter_save_blocks_http_and_a_repaired_store_can_retry(self):
|
||||
identifier = self.account(False)
|
||||
self.login(identifier)
|
||||
worker = self.manager._worker(identifier)
|
||||
before = len(FakeClient.calls)
|
||||
with patch.object(worker.securestore, "save", side_effect=OSError("synthetic persistence failure")):
|
||||
result = self.job(identifier, self.manager.submit(identifier, "refresh"), status="failed")
|
||||
self.assertTrue(result["error"])
|
||||
self.assertEqual(len(FakeClient.calls), before)
|
||||
self.job(identifier, self.manager.submit(identifier, "refresh"))
|
||||
self.assertGreater(len(FakeClient.calls), before)
|
||||
|
||||
def test_account_registry_failure_closes_worker_without_holding_manager_lock(self):
|
||||
started = time.monotonic()
|
||||
with patch.object(self.manager.store, "save_accounts", side_effect=OSError("registry unavailable")):
|
||||
with self.assertRaisesRegex(OSError, "registry unavailable"):
|
||||
self.manager.create_account()
|
||||
self.assertLess(time.monotonic() - started, 2)
|
||||
self.assertEqual(self.manager.list_accounts(), [])
|
||||
|
||||
def test_public_structural_keys_survive_but_real_secret_key_is_removed(self):
|
||||
worker = self.manager._worker(self.account())
|
||||
value = {name: [{"key": "binding", "label": "选项", "details": {"key": "secret-nested"}}]
|
||||
for name in ("columns", "filters", "pages", "tabs", "form")}
|
||||
value.update(key="secret-protocol", token="secret-token", reqid=17, raw={"hidden": True})
|
||||
result = worker.public_json(value)
|
||||
for name in ("columns", "filters", "pages", "tabs", "form"):
|
||||
self.assertEqual(result[name][0]["key"], "binding")
|
||||
self.assertNotIn("key", result[name][0]["details"])
|
||||
self.assertNotIn("key", result)
|
||||
self.assertNotIn("token", result)
|
||||
self.assertNotIn("reqid", result)
|
||||
self.assertNotIn("raw", result)
|
||||
with self.assertRaises(ValueError):
|
||||
worker.public_json(Session())
|
||||
|
||||
def test_debug_summaries_are_small_and_details_keep_redacted_body_headers(self):
|
||||
identifier = self.account()
|
||||
worker = self.manager._worker(identifier)
|
||||
worker.trace.emit("response", "离线请求", headers={"Content-Type": "application/json", "Set-Cookie": "private-cookie"},
|
||||
body={"monsters": [{"id": index, "name": "测试"} for index in range(80)],
|
||||
"token": "private-token", "password": "private-password", "key": "private-key", "reqid": 187,
|
||||
"file_path": str(worker.profile_root / "private.json")})
|
||||
logs = self.manager.logs(identifier, debug=True)
|
||||
entry = next(row for row in logs["entries"] if row["details_available"])
|
||||
self.assertNotIn("body", entry)
|
||||
self.assertLess(len(json.dumps(entry)), 1000)
|
||||
details = self.manager.log_detail(identifier, entry["id"])["details"]
|
||||
self.assertEqual(len(details["body"]["monsters"]), 80)
|
||||
self.assertEqual(details["headers"]["Content-Type"], "application/json")
|
||||
for field in ("token", "password", "key", "reqid"):
|
||||
self.assertEqual(details["body"][field], "<隐藏>")
|
||||
serialized = json.dumps(details)
|
||||
for secret in ("private-cookie", "private-token", "private-password", "private-key", str(worker.profile_root)):
|
||||
self.assertNotIn(secret, serialized)
|
||||
for index in range(70):
|
||||
worker.trace.emit("info", "entry", value=index)
|
||||
with self.assertRaises(KeyError):
|
||||
self.manager.debug_entry(identifier, entry["id"])
|
||||
|
||||
def test_shutdown_cancels_simulation_before_waiting_and_keeps_pending_evidence(self):
|
||||
first, second = self.account(), self.account()
|
||||
entered = threading.Event()
|
||||
worker = self.manager._worker(first)
|
||||
pending = worker.state_root / "uncertain-evidence.json"
|
||||
pending.write_text('{"status":"unknown"}', encoding="utf-8")
|
||||
|
||||
def simulate(runtime, operation, payload):
|
||||
entered.set()
|
||||
runtime.engine._progression_cancel.wait(5)
|
||||
runtime.check_intent()
|
||||
return {}
|
||||
|
||||
with patch("ranch_web.actions.execute_action", side_effect=simulate):
|
||||
job = self.manager.submit(first, "simulate_probe")
|
||||
self.assertTrue(entered.wait(2))
|
||||
started = time.monotonic()
|
||||
self.manager.close()
|
||||
self.assertLess(time.monotonic() - started, 1)
|
||||
self.assertTrue(pending.exists())
|
||||
self.assertEqual(self.manager.job(first, job["id"])["status"], "cancelled")
|
||||
self.assertTrue(self.manager._worker(second)._closed.is_set())
|
||||
|
||||
def test_no_pyside_or_gui_import_is_required(self):
|
||||
code = '''
|
||||
import importlib.abc, sys, tempfile
|
||||
class NoGui(importlib.abc.MetaPathFinder):
|
||||
def find_spec(self, fullname, path=None, target=None):
|
||||
if fullname.startswith("PySide6") or fullname.endswith("_gui") or fullname == "ranch_assistant.gui":
|
||||
raise ImportError("GUI forbidden")
|
||||
sys.meta_path.insert(0, NoGui())
|
||||
from ranch_web.service import WebManager
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
manager = WebManager(root, start_scheduler=False)
|
||||
manager.create_account(demo=True)
|
||||
manager.close()
|
||||
print("headless-ok")
|
||||
'''
|
||||
result = subprocess.run([sys.executable, "-c", code], cwd=Path(__file__).resolve().parents[2],
|
||||
capture_output=True, text=True, timeout=15)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("headless-ok", result.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Web persistence tests use disposable roots and synthetic sessions only."""
|
||||
from dataclasses import replace
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from ranch_assistant.api import Session
|
||||
from ranch_web.store import WebStore, session_identity
|
||||
|
||||
|
||||
class StoreTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = self.enterContext(tempfile.TemporaryDirectory(prefix="ranch-web-store-test-"))
|
||||
self.root = Path(self.temp) / "web"
|
||||
self.store = WebStore(self.root)
|
||||
self.addCleanup(self.store.close)
|
||||
self.secure = self.store.secure("a" * 32)
|
||||
|
||||
def session(self):
|
||||
return Session("https://offline.invalid/game/", "synthetic-private-token", account_id="fake-owner",
|
||||
server_id=1, role_id=101, reqid=5, reqsid=9)
|
||||
|
||||
def test_fernet_credentials_and_session_survive_restart_without_plaintext(self):
|
||||
self.secure.save_credentials("synthetic-account", "synthetic-password", True)
|
||||
session = self.session()
|
||||
identifier = self.secure.save(session, "测试角色")
|
||||
self.secure.set_active(identifier)
|
||||
self.store.close()
|
||||
reopened = WebStore(self.root)
|
||||
self.addCleanup(reopened.close)
|
||||
secure = reopened.secure("a" * 32)
|
||||
self.assertEqual(secure.load_credentials(), (True, "synthetic-account", "synthetic-password"))
|
||||
self.assertEqual(secure.load(identifier), session)
|
||||
self.assertEqual(secure.active(), identifier)
|
||||
for path in self.root.rglob("*.fernet"):
|
||||
raw = path.read_text(encoding="utf-8")
|
||||
for secret in ("synthetic-account", "synthetic-password", session.token, session.key):
|
||||
self.assertNotIn(secret, raw)
|
||||
if os.name != "nt":
|
||||
self.assertEqual(stat.S_IMODE((self.root / "web.key").stat().st_mode), 0o600)
|
||||
|
||||
def test_high_water_marks_never_regress(self):
|
||||
session = self.session()
|
||||
identifier = self.secure.save(session, "first")
|
||||
stale = replace(session, reqid=0, reqsid=1)
|
||||
self.secure.save(stale, "stale")
|
||||
loaded = self.secure.load(identifier)
|
||||
self.assertEqual((loaded.reqid, loaded.reqsid), (5, 9))
|
||||
self.assertEqual((stale.reqid, stale.reqsid), (5, 9))
|
||||
|
||||
def test_sessions_are_separated_by_account_region_role_and_profile(self):
|
||||
first = self.session()
|
||||
sessions = [first, replace(first, account_id="other"), replace(first, server_id=2), replace(first, role_id=102)]
|
||||
ids = [self.secure.save(value, "角色") for value in sessions]
|
||||
self.assertEqual(len(set(ids)), 4)
|
||||
other = self.store.secure("b" * 32)
|
||||
self.assertEqual(other.entries(), [])
|
||||
self.assertEqual(len(self.secure.entries()), 4)
|
||||
self.assertEqual(set(self.secure.entries()[0]), {"session_id", "label", "saved_at"})
|
||||
self.assertEqual(session_identity(first), ids[0])
|
||||
|
||||
def test_missing_or_different_key_is_reported_without_replacing_ciphertext(self):
|
||||
self.secure.save(self.session(), "角色")
|
||||
self.store.close()
|
||||
original = next(self.secure.folder.glob("*.fernet")).read_bytes()
|
||||
(self.root / "web.key").unlink()
|
||||
with self.assertRaisesRegex(ValueError, "密钥"):
|
||||
WebStore(self.root)
|
||||
self.assertEqual(next(self.secure.folder.glob("*.fernet")).read_bytes(), original)
|
||||
|
||||
def test_tamper_and_path_traversal_are_rejected(self):
|
||||
identifier = self.secure.save(self.session(), "角色")
|
||||
path = self.secure.folder / (identifier + ".fernet")
|
||||
record = json.loads(path.read_text(encoding="utf-8"))
|
||||
record["protected"] = record["protected"][:-8] + "invalid!"
|
||||
path.write_text(json.dumps(record), encoding="utf-8")
|
||||
with self.assertRaisesRegex(ValueError, "加密"):
|
||||
self.secure.load(identifier)
|
||||
for bad in ("../other", "A" * 32, "", None):
|
||||
with self.assertRaises(ValueError):
|
||||
self.store.remove_profile(bad)
|
||||
with self.assertRaises(ValueError):
|
||||
self.secure.load("../credentials")
|
||||
|
||||
def test_only_one_instance_owns_the_root(self):
|
||||
with self.assertRaisesRegex(RuntimeError, "另一个"):
|
||||
WebStore(self.root)
|
||||
|
||||
def test_removal_preserves_siblings_and_shared_files(self):
|
||||
sibling = self.store.secure("b" * 32)
|
||||
sibling.save_credentials("b", "password-b")
|
||||
shared = self.root / "shared-catalog.json"
|
||||
shared.write_text("shared", encoding="utf-8")
|
||||
self.secure.save(self.session(), "A")
|
||||
self.store.remove_profile("a" * 32)
|
||||
self.assertFalse(self.secure.profile_root.exists())
|
||||
self.assertEqual(sibling.load_credentials(), (True, "b", "password-b"))
|
||||
self.assertEqual(shared.read_text(encoding="utf-8"), "shared")
|
||||
|
||||
def test_link_inside_profile_blocks_entire_removal(self):
|
||||
sibling = self.store.secure("b" * 32).profile_root
|
||||
link = self.secure.profile_root / "sibling-link"
|
||||
try:
|
||||
link.symlink_to(sibling, target_is_directory=True)
|
||||
except (OSError, NotImplementedError):
|
||||
self.skipTest("Creating symlinks requires Windows privileges")
|
||||
self.addCleanup(lambda: link.unlink(missing_ok=True))
|
||||
ordinary = self.secure.profile_root / "keep.txt"
|
||||
ordinary.write_text("keep", encoding="utf-8")
|
||||
with self.assertRaisesRegex(ValueError, "链接"):
|
||||
self.store.remove_profile("a" * 32)
|
||||
self.assertTrue(ordinary.exists())
|
||||
self.assertTrue(sibling.exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,216 @@
|
||||
"""Offline update protocol checks; no game API, Docker, or live GitHub."""
|
||||
from datetime import timedelta
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from ranch_web import updates
|
||||
|
||||
|
||||
def release(tag, **extra):
|
||||
return {"tag_name": tag, "draft": False, "prerelease": False, **extra}
|
||||
|
||||
|
||||
class UpdateTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix="ranch-updates-")
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.folder = Path(self.temporary.name)
|
||||
self.root = self.folder / "data"
|
||||
self.control = self.folder / "host-control"
|
||||
self.environment = patch.dict(os.environ, {"RANCH_WEB_UPDATER_DIR": ""})
|
||||
self.environment.start()
|
||||
self.addCleanup(self.environment.stop)
|
||||
self.github = patch.object(updates, "github_releases", return_value=[])
|
||||
self.releases = self.github.start()
|
||||
self.addCleanup(self.github.stop)
|
||||
self.service = updates.UpdateService(self.root, "2.0.0.dev1")
|
||||
|
||||
def enable(self, **overrides):
|
||||
now = updates.utc_now()
|
||||
value = {"protocol": 1, "executor_id": "a" * 32, "enabled": True, "auto_apply": False,
|
||||
"heartbeat_at": updates.timestamp(now), "expires_at": updates.timestamp(now + timedelta(minutes=15)),
|
||||
**overrides}
|
||||
updates.atomic_json(self.control / "capability.json", value)
|
||||
os.environ["RANCH_WEB_UPDATER_DIR"] = str(self.control)
|
||||
|
||||
def test_status_does_not_create_data_or_use_network(self):
|
||||
result = self.service.status()
|
||||
self.assertEqual(result["status"], "unchecked")
|
||||
self.assertFalse(self.root.exists())
|
||||
self.releases.assert_not_called()
|
||||
|
||||
def test_release_gate_accepts_official_repository_case_and_exact_source_version(self):
|
||||
for repository in ("AttilaNet/myrzx_bot", "attilanet/myrzx_bot", "ATTILANET/MYRZX_BOT"):
|
||||
with self.subTest(repository=repository):
|
||||
self.assertEqual(updates.validate_image_release(repository, "v2.0.0", "2.0.0"), "v2.0.0")
|
||||
|
||||
def test_release_gate_rejects_forks_dev_source_and_unstable_tags(self):
|
||||
variants = [("someone/myrzx_bot", "v2.0.0", "2.0.0"),
|
||||
("AttilaNet/myrzx_bot", "v2.0.0", "2.0.0.dev1"),
|
||||
("AttilaNet/myrzx_bot", "v2.0.1", "2.0.0"),
|
||||
("AttilaNet/myrzx_bot", "v3.0.0", "3.0.0"),
|
||||
("AttilaNet/myrzx_bot", "v2.0.0-rc1", "2.0.0-rc1")]
|
||||
for values in variants:
|
||||
with self.subTest(values=values), self.assertRaises(ValueError):
|
||||
updates.validate_image_release(*values)
|
||||
|
||||
def test_only_desktop_or_no_releases_means_no_web_update(self):
|
||||
self.releases.return_value = [release("v1.2.0"), release("v3.0.0")]
|
||||
result = self.service.check()
|
||||
self.assertEqual(result["status"], "no_release")
|
||||
self.assertIsNone(result["latest_version"])
|
||||
self.assertFalse(result["available"])
|
||||
self.assertIn("桌面", result["message"])
|
||||
|
||||
def test_dev_can_upgrade_to_same_number_stable(self):
|
||||
self.releases.return_value = [release("v2.0.0")]
|
||||
self.assertTrue(self.service.check()["available"])
|
||||
|
||||
def test_same_stable_and_downgrade_are_not_updates(self):
|
||||
self.releases.return_value = [release("v2.0.0")]
|
||||
for current in ("2.0.0", "2.1.0", "v2.0.0"):
|
||||
with self.subTest(current=current):
|
||||
state = updates.UpdateService(self.root, current).check()
|
||||
self.assertEqual(state["status"], "up_to_date")
|
||||
self.assertFalse(state["available"])
|
||||
|
||||
def test_numeric_order_and_untrusted_release_url(self):
|
||||
self.releases.return_value = [release("v2.9.9"), release("v2.10.0", html_url="https://evil.invalid")]
|
||||
result = self.service.check()
|
||||
self.assertEqual(result["latest_version"], "v2.10.0")
|
||||
self.assertEqual(result["release_url"], "https://github.com/attilanet/myrzx_bot/releases/tag/v2.10.0")
|
||||
|
||||
def test_draft_prerelease_and_noncanonical_tags_skipped(self):
|
||||
tags = ["v2.01.0", "v2.1.00", "2.1.0", "v2.1.0-rc1", "v2.1.0+build", "v2.1.0.dev1",
|
||||
"v2.1.0\n", "v2.1.0;id", "v2.1.0", "v1.99.99", "v3.0.0"]
|
||||
self.releases.return_value = [release(tag) for tag in tags] + [release("v2.1.0", draft=True),
|
||||
release("v2.2.0", prerelease=True)]
|
||||
self.assertEqual(self.service.check()["status"], "no_release")
|
||||
|
||||
def test_network_failure_has_no_exception_or_secret_text(self):
|
||||
self.releases.side_effect = RuntimeError("token=secret C:/private/account")
|
||||
state = self.service.check()
|
||||
encoded = json.dumps(state)
|
||||
self.assertEqual(state["status"], "check_failed")
|
||||
self.assertFalse(state["available"])
|
||||
self.assertNotIn("secret", encoded)
|
||||
self.assertNotIn("private", encoded)
|
||||
|
||||
def test_unconfigured_windows_can_only_check(self):
|
||||
self.releases.return_value = [release("v2.0.0")]
|
||||
self.service.check()
|
||||
state = self.service.request_update()
|
||||
self.assertEqual(state["status"], "unavailable")
|
||||
self.assertFalse(state["can_apply"])
|
||||
self.assertFalse((self.root / "update-request.json").exists())
|
||||
|
||||
def test_data_cannot_self_enable_host_executor(self):
|
||||
updates.atomic_json(self.root / "capability.json", {"protocol": 1, "enabled": True})
|
||||
self.assertFalse(self.service.status()["executor"]["enabled"])
|
||||
|
||||
def test_disabled_expired_future_and_malformed_proof_refuse_apply(self):
|
||||
now = updates.utc_now()
|
||||
variants = [dict(enabled=False), dict(expires_at=updates.timestamp(now - timedelta(seconds=1))),
|
||||
dict(heartbeat_at=updates.timestamp(now + timedelta(hours=1))),
|
||||
dict(expires_at=updates.timestamp(now + timedelta(hours=1))), dict(executor_id="bad"),
|
||||
dict(protocol=2)]
|
||||
for variant in variants:
|
||||
with self.subTest(variant=variant):
|
||||
self.enable(**variant)
|
||||
self.assertEqual(self.service.request_update()["status"], "unavailable")
|
||||
self.assertFalse((self.root / "update-request.json").exists())
|
||||
|
||||
def test_apply_creates_only_strict_pending_request(self):
|
||||
self.enable()
|
||||
self.releases.return_value = [release("v2.0.0")]
|
||||
state = self.service.request_update()
|
||||
self.assertEqual(state["status"], "pending")
|
||||
self.assertFalse(state["can_apply"])
|
||||
value = updates.read_json(self.root / "update-request.json")
|
||||
self.assertEqual(set(value), {"protocol", "request_id", "executor_id", "version", "requested_at"})
|
||||
self.assertEqual(value["version"], "v2.0.0")
|
||||
self.assertEqual(value["executor_id"], "a" * 32)
|
||||
self.assertTrue(updates.valid_id(value["request_id"]))
|
||||
self.assertIsNone(state["host_status"])
|
||||
|
||||
def test_duplicate_request_is_idempotent(self):
|
||||
self.enable()
|
||||
self.releases.return_value = [release("v2.0.0")]
|
||||
first = self.service.request_update()
|
||||
second = self.service.request_update()
|
||||
self.assertEqual(first["request"], second["request"])
|
||||
self.assertEqual(self.releases.call_count, 1)
|
||||
|
||||
def test_tampered_cached_release_is_not_enough_for_apply(self):
|
||||
self.enable()
|
||||
updates.atomic_json(self.root / "update-check.json", {"status": "available", "latest_version": "v2.9.9"})
|
||||
with self.assertRaises(ValueError):
|
||||
self.service.request_update("v2.9.9")
|
||||
self.assertFalse((self.root / "update-request.json").exists())
|
||||
|
||||
def test_apply_rejects_unsafe_tag_before_network(self):
|
||||
self.enable()
|
||||
for tag in ("v1.2.0", "v3.0.0", "v2.1.0;rm", "v2.1.0\n", "latest", "v2.1.0-rc1"):
|
||||
with self.subTest(tag=tag), self.assertRaises(ValueError):
|
||||
self.service.request_update(tag)
|
||||
self.releases.assert_not_called()
|
||||
|
||||
def test_request_rejects_equal_or_older_official_version(self):
|
||||
self.enable()
|
||||
self.releases.return_value = [release("v2.0.0")]
|
||||
for current in ("2.0.0", "2.1.0"):
|
||||
with self.subTest(current=current), self.assertRaises(ValueError):
|
||||
updates.UpdateService(self.root, current).request_update("v2.0.0")
|
||||
|
||||
def test_public_host_state_uses_allowlist_and_fixed_error(self):
|
||||
self.enable()
|
||||
self.releases.return_value = [release("v2.0.0")]
|
||||
request = self.service.request_update()["request"]
|
||||
updates.atomic_json(self.root / "updater-status.json", {
|
||||
"protocol": 1, "request_id": request["request_id"], "version": "v2.0.0",
|
||||
"status": "rolled_back", "updated_at": updates.timestamp(),
|
||||
"error": "private token", "path": "C:/account", "password": "do-not-send",
|
||||
})
|
||||
state = self.service.status()
|
||||
self.assertEqual(state["status"], "rolled_back")
|
||||
self.assertEqual(state["request"]["status"], "rolled_back")
|
||||
encoded = json.dumps(state)
|
||||
for value in ("private token", "C:/account", "do-not-send", "executor_id"):
|
||||
self.assertNotIn(value, encoded)
|
||||
|
||||
def test_corrupt_large_or_wrong_type_control_files_are_ignored(self):
|
||||
self.root.mkdir()
|
||||
for content in ("not json", "[]", '"wrong type"', "x" * 65537):
|
||||
with self.subTest(content=content[:20]):
|
||||
(self.root / "update-check.json").write_text(content, encoding="utf-8")
|
||||
(self.root / "update-request.json").write_text(content, encoding="utf-8")
|
||||
(self.root / "updater-status.json").write_text(content, encoding="utf-8")
|
||||
self.assertEqual(self.service.status()["status"], "unchecked")
|
||||
|
||||
def test_official_fetch_uses_fixed_url_bounded_body_no_redirects(self):
|
||||
class Reply:
|
||||
def __enter__(self):
|
||||
return self
|
||||
def __exit__(self, *args):
|
||||
pass
|
||||
def read(self, size):
|
||||
self_size.append(size)
|
||||
return b'[{"tag_name":"v1.2.0","draft":false,"prerelease":false}]'
|
||||
self_size = []
|
||||
self.github.stop()
|
||||
with patch.object(updates, "build_opener") as build:
|
||||
build.return_value.open.return_value = Reply()
|
||||
result = updates.github_releases()
|
||||
self.assertEqual(result[0]["tag_name"], "v1.2.0")
|
||||
request = build.return_value.open.call_args.args[0]
|
||||
self.assertEqual(request.full_url, updates.RELEASES_API + "?per_page=100&page=1")
|
||||
self.assertIsInstance(build.call_args.args[0], updates._NoRedirect)
|
||||
self.assertEqual(self_size, [2 * 1024 * 1024 + 1])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,820 @@
|
||||
"""Independent HTTP -> WebManager -> existing Engine offline integration checks.
|
||||
|
||||
Run: python -m unittest ranch_web.tests.test_web_integration -v
|
||||
Only the game Client/login boundary and release source are fakes. Each test owns
|
||||
a new temporary root, disables the scheduler, and blocks external socket I/O.
|
||||
Fixtures stay in this file to avoid other agents' test/fixture ownership.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from contextlib import ExitStack
|
||||
from copy import deepcopy
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import textwrap
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
PAGES = "login incubator bag ranch daily hatching mainline battles gifts commissions exploration maps statistics plans yields".split()
|
||||
TERMINAL = {"succeeded", "failed", "cancelled"}
|
||||
TOKEN = "web-integration-synthetic-token-82719"
|
||||
KEY = "web-integration-synthetic-key-49281"
|
||||
PASSWORD = "web-integration-synthetic-password-18374"
|
||||
REQID = 98271948
|
||||
REQSID = 91283741
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class NoExternalSockets:
|
||||
"""Allow Windows asyncio's loopback socketpair, reject external addresses."""
|
||||
|
||||
def __init__(self):
|
||||
self.stack = ExitStack()
|
||||
self.attempts = []
|
||||
|
||||
def check(self, address):
|
||||
host = address[0] if isinstance(address, tuple) else address
|
||||
if host == "localhost":
|
||||
return
|
||||
try:
|
||||
value = ipaddress.ip_address(host)
|
||||
if value.is_loopback or (getattr(value, "ipv4_mapped", None) and value.ipv4_mapped.is_loopback):
|
||||
return
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
self.attempts.append(str(host))
|
||||
raise AssertionError("External socket blocked by Web integration fixture")
|
||||
|
||||
def __enter__(self):
|
||||
for name in ("connect", "connect_ex", "sendto"):
|
||||
original = getattr(socket.socket, name)
|
||||
|
||||
def guarded(sock, *args, _original=original, _name=name, **kwargs):
|
||||
address = args[-1] if _name == "sendto" else args[0]
|
||||
self.check(address)
|
||||
return _original(sock, *args, **kwargs)
|
||||
|
||||
self.stack.enter_context(patch.object(socket.socket, name, guarded))
|
||||
original_dns = socket.getaddrinfo
|
||||
|
||||
def dns(host, *args, **kwargs):
|
||||
self.check(host)
|
||||
return original_dns(host, *args, **kwargs)
|
||||
|
||||
self.stack.enter_context(patch.object(socket, "getaddrinfo", dns))
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
return self.stack.__exit__(*args)
|
||||
|
||||
|
||||
class SnapshotGate:
|
||||
def __init__(self):
|
||||
self.entered = threading.Event()
|
||||
self.release = threading.Event()
|
||||
|
||||
def wait(self):
|
||||
self.entered.set()
|
||||
if not self.release.wait(8):
|
||||
raise AssertionError("Integration snapshot gate was not released")
|
||||
|
||||
|
||||
def seeded_snapshot(catalog, role_id=1):
|
||||
from ranch_assistant.engine import demo_snapshot
|
||||
from ranch_assistant.resource_stages import item_requirements, with_resource_data
|
||||
|
||||
snapshot = demo_snapshot(catalog)
|
||||
snapshot.raw["master"]["id"] = role_id
|
||||
snapshot.raw["master"]["roleName"] = "Integration offline role"
|
||||
snapshot.raw["teams"][0]["teamName"] = "teamA"
|
||||
for index, monster in enumerate(snapshot.raw["monsters"][:4]):
|
||||
monster.update(process=3, mode=2, roomId=1, level=20 - index * 4)
|
||||
for slot in snapshot.raw["stacks"]:
|
||||
slot["monsterId"] = 0
|
||||
snapshot.raw["history"].update(
|
||||
unlockStage={"0101": [1, 2, 3], "0109": [1, 2, 3]},
|
||||
passStage={"0101": {"1": True, "2": True, "3": True}, "0109": {"1": True}},
|
||||
passTask={"1001008": True}, unlockTask={"1001004": True}, openHardMode=True,
|
||||
)
|
||||
snapshot.raw["currentTasks"] = [{"id": 711, "typeId": "1001004", "curStep": 1, "stepValue": None}]
|
||||
snapshot.raw["exploreTeams"] = [{"id": 1, "status": 0, "area": "", "monsters": ""}]
|
||||
for code in range(1, 6):
|
||||
item_id = next(key for key in catalog.data["item_info"] if catalog.item_type(key) == code)
|
||||
snapshot.raw["items"].extend({"id": 11000 + code * 10 + index, "typeId": item_id, "num": count}
|
||||
for index, count in enumerate((3, 4)))
|
||||
required_items = {}
|
||||
for stage in with_resource_data(catalog).data["stage_info"].values():
|
||||
for item_id, count in item_requirements((stage.get("cost") or {}).get("items") or []).items():
|
||||
required_items[item_id] = max(required_items.get(item_id, 0), count * 3)
|
||||
snapshot.raw["items"].extend({"id": 12000 + index, "typeId": item_id, "num": count}
|
||||
for index, (item_id, count) in enumerate(sorted(required_items.items())))
|
||||
return snapshot
|
||||
|
||||
|
||||
def real_engine_factory(catalog, client=None, budget_path=None):
|
||||
from ranch_assistant.engine import Engine
|
||||
|
||||
engine = Engine(catalog, client, budget_path)
|
||||
if client is None:
|
||||
engine.snapshot = seeded_snapshot(catalog)
|
||||
role_id = client.session.role_id if client else 1
|
||||
# Persist through the real SQLite statistics service; no DTOs are injected.
|
||||
statistics = engine.sweeper.statistics
|
||||
for source, operation, reward, spent in (
|
||||
("sweep", "integration-sweep-hit", {"items": [{"typeId": 30005, "num": 2}]}, 10),
|
||||
("sweep", "integration-sweep-miss", {"items": []}, 10),
|
||||
("event", "integration-event-hit", {"items": [{"typeId": 30005, "num": 3}]}, 5),
|
||||
):
|
||||
statistics.record(role_id, "0101", "3", source, operation, 1, reward, spent=spent)
|
||||
return engine
|
||||
|
||||
|
||||
class OfflineClient:
|
||||
def __init__(self, catalog, account="fixture", **kwargs):
|
||||
from ranch_assistant.api import Session
|
||||
|
||||
role_id = 100 + int(hashlib.sha256(account.encode()).hexdigest()[:6], 16)
|
||||
self.catalog = catalog
|
||||
self.session = Session(server_url="https://game.invalid/", token=TOKEN, key=KEY,
|
||||
reqid=REQID, reqsid=REQSID, account_id=account,
|
||||
server_id=7, role_id=role_id, account_name=account)
|
||||
self.raw = seeded_snapshot(catalog, role_id).raw
|
||||
self.trace = kwargs.get("trace")
|
||||
self.on_session_change = kwargs.get("on_session_change")
|
||||
self.gate = None
|
||||
self.fail_snapshot = False
|
||||
self.reads = 0
|
||||
self.writes = []
|
||||
self.closed = False
|
||||
|
||||
def enter_server(self, *args, **kwargs):
|
||||
return {"resCode": 0}
|
||||
|
||||
def snapshot(self):
|
||||
from ranch_assistant.model import Snapshot
|
||||
|
||||
self.reads += 1
|
||||
if self.gate:
|
||||
self.gate.wait()
|
||||
if self.fail_snapshot:
|
||||
raise ValueError("离线读取失败 " + PASSWORD + " token=" + TOKEN + " key=" + KEY)
|
||||
if self.trace:
|
||||
self.trace.emit("response", "masterService/masterQueryDetail", http_status=200,
|
||||
body={"safe_marker": "integration-readable-detail", "token": TOKEN,
|
||||
"nested": {"password": PASSWORD, "key": KEY, "reqid": REQID}},
|
||||
message="离线响应 password=" + PASSWORD)
|
||||
return Snapshot(deepcopy(self.raw))
|
||||
|
||||
def call(self, path, payload=None, **kwargs):
|
||||
self.writes.append((path, deepcopy(payload)))
|
||||
raise AssertionError("Unexpected game write in integration fixture: " + path)
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
class OfflineLoginFactory:
|
||||
def __init__(self):
|
||||
self.clients = []
|
||||
|
||||
def __call__(self, catalog, device, trace=None):
|
||||
owner = self
|
||||
|
||||
class Flow:
|
||||
def authenticate(self, account, password):
|
||||
client = OfflineClient(catalog, account, trace=trace)
|
||||
owner.clients.append(client)
|
||||
return client, {"token": TOKEN, "key": KEY,
|
||||
"servers": [{"id": 7, "serverName": "Offline server", "gameServerAddress": "https://game.invalid/"}],
|
||||
"masterInfos": [{"serverId": 7, "masterName": "Offline role"}]}, {
|
||||
"center_url": "https://center.invalid/", "uid": account,
|
||||
"channel": "DYD", "device_id": "integration-device"}
|
||||
|
||||
return Flow()
|
||||
|
||||
|
||||
class WebIntegrationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
from fastapi.testclient import TestClient
|
||||
from ranch_web.app import create_app
|
||||
from ranch_web.config import WebConfig
|
||||
from ranch_web.service import WebManager
|
||||
from ranch_web.updates import UpdateService
|
||||
|
||||
self.stack = ExitStack()
|
||||
self.addCleanup(self.stack.close)
|
||||
self.network = self.stack.enter_context(NoExternalSockets())
|
||||
self.folder = Path(self.stack.enter_context(tempfile.TemporaryDirectory(prefix="web-integration-")))
|
||||
self.root = self.folder / "new-web-root"
|
||||
self.stack.enter_context(patch.dict(os.environ, {"RANCH_WEB_UPDATER_DIR": ""}))
|
||||
self.source = self.stack.enter_context(patch("ranch_web.updates.github_releases", return_value=[]))
|
||||
self.login = OfflineLoginFactory()
|
||||
self.manager = WebManager(self.root, start_scheduler=False,
|
||||
engine_factory=real_engine_factory, login_factory=self.login)
|
||||
self.stack.callback(lambda: self.manager.close())
|
||||
self.updates = UpdateService(self.root, "2.0.0.dev1")
|
||||
self.app = create_app(manager=self.manager, updates=self.updates,
|
||||
config=WebConfig(data_dir=self.root))
|
||||
self.http = self.stack.enter_context(TestClient(self.app, base_url="http://127.0.0.1:8765",
|
||||
client=("127.0.0.1", 50000)))
|
||||
self.account = self.create_account()
|
||||
|
||||
def tearDown(self):
|
||||
self.assertEqual(self.network.attempts, [], "An external socket was attempted")
|
||||
|
||||
def response(self, response, status=200):
|
||||
self.assertEqual(response.status_code, status, response.text[:3000])
|
||||
return response.json()
|
||||
|
||||
def create_account(self, demo=True, label="integration"):
|
||||
value = self.response(self.http.post("/api/accounts", json={"label": label, "demo": demo}), 201)
|
||||
self.wait_idle(value["id"])
|
||||
return value["id"]
|
||||
|
||||
def path(self, suffix, account=None):
|
||||
return "/api/accounts/" + (account or self.account) + "/" + suffix
|
||||
|
||||
def wait_idle(self, account=None):
|
||||
deadline = time.monotonic() + 8
|
||||
while time.monotonic() < deadline:
|
||||
status = self.manager.status(account or self.account)
|
||||
if not status["busy"]:
|
||||
self.assertFalse(status["error"], status)
|
||||
return status
|
||||
time.sleep(.005)
|
||||
self.fail("Account worker did not become idle")
|
||||
|
||||
def job(self, value, account=None, expected="succeeded"):
|
||||
deadline = time.monotonic() + 8
|
||||
while time.monotonic() < deadline:
|
||||
current = self.response(self.http.get(self.path("jobs/" + value["id"], account)))
|
||||
self.assertIn(current["status"], TERMINAL | {"queued", "running"})
|
||||
if current["status"] in TERMINAL:
|
||||
self.assertEqual(current["status"], expected, current)
|
||||
return current
|
||||
time.sleep(.005)
|
||||
self.fail("Job did not finish: " + str(value))
|
||||
|
||||
def action(self, operation, payload=None, account=None, expected="succeeded"):
|
||||
value = self.response(self.http.post(self.path("actions/" + operation, account), json=payload or {}), 202)
|
||||
return self.job(value, account, expected)
|
||||
|
||||
def config(self, account=None):
|
||||
return self.response(self.http.get(self.path("config", account)))
|
||||
|
||||
def save(self, value, account=None):
|
||||
current = self.config(account)
|
||||
response = self.http.put(self.path("config", account), json={"config": value, "revision": current["revision"]})
|
||||
self.assertIn(response.status_code, (200, 202), response.text)
|
||||
pending = response.json()
|
||||
if pending.get("pending"):
|
||||
self.job(pending["job"], account)
|
||||
applied = self.config(account)
|
||||
self.assertGreater(applied["revision"], current["revision"])
|
||||
return applied
|
||||
|
||||
def view(self, page, query=None, account=None, simple=False):
|
||||
params = query if simple else {"query": json.dumps(query)} if query is not None else None
|
||||
value = self.response(self.http.get(self.path("views/" + page, account), params=params))
|
||||
if value["loading"]:
|
||||
self.assertIsInstance(value["job_id"], str)
|
||||
self.job({"id": value["job_id"]}, account)
|
||||
value = self.response(self.http.get(self.path("views/" + page, account), params=params))
|
||||
self.assertFalse(value["loading"], value)
|
||||
self.assertIsInstance(value["revision"], int)
|
||||
self.assertIsInstance(value["data"], dict)
|
||||
return value["data"]
|
||||
|
||||
def hatch_config(self, account=None, enabled=True, priority=13):
|
||||
row = self.view("bag", account=account)["rows"][0]
|
||||
config = deepcopy(self.config(account)["config"])
|
||||
config["policy"].update(enabled=True, fill=True, buy=False, collect=False, dispatch=False, feed=False,
|
||||
manual_eggs=True, egg_rules={row["id"]: row["rule_defaults"] | {
|
||||
"enabled": enabled, "priority": priority, "action": "keep", "keep_count": 2}})
|
||||
return config, row
|
||||
|
||||
def logged_account(self):
|
||||
account = self.create_account(False, "fake login")
|
||||
result = self.action("login", {"account": "fixture-account", "password": PASSWORD, "remember": True}, account)
|
||||
self.assertEqual(result["result"]["servers"][0]["id"], 7)
|
||||
self.assertTrue(result["result"]["has_saved_password"])
|
||||
self.action("enter_server", {"server_id": 7}, account)
|
||||
self.assertTrue(self.manager.status(account)["connected"])
|
||||
return account, self.login.clients[-1]
|
||||
|
||||
def assert_dto(self, page):
|
||||
from ranch_assistant.engine import Engine
|
||||
|
||||
self.assertIs(type(self.manager._worker(self.account).engine), Engine)
|
||||
dto = self.view(page)
|
||||
self.assertEqual(dto["page"], page)
|
||||
self.assertTrue(dto["title"])
|
||||
for field in ("rows", "columns", "filters", "form"):
|
||||
self.assertIsInstance(dto[field], list, (page, field))
|
||||
if page != "login":
|
||||
self.assertTrue(dto["columns"], page)
|
||||
for column in dto["columns"]:
|
||||
self.assertTrue(column["key"], (page, column))
|
||||
self.assertTrue(column["label"], (page, column))
|
||||
if "edit" in column:
|
||||
self.assertIsInstance(column["edit"]["path"], list)
|
||||
for row in dto["rows"]:
|
||||
self.assertIn("id", row, (page, row))
|
||||
for field in dto["form"]:
|
||||
self.assertTrue({"path", "type", "label", "value"} <= field.keys(), (page, field))
|
||||
|
||||
def test_default_queries_schema_and_all_six_bag_categories(self):
|
||||
schema = self.response(self.http.get("/api/schema"))
|
||||
self.assertEqual([p["key"] for p in schema["pages"]], PAGES)
|
||||
self.assertTrue(schema["settings"])
|
||||
defaults = {"bag": {"category": "eggs"}, "ranch": {"grouped": False},
|
||||
"mainline": {"category": "mainline", "state": "current"},
|
||||
"maps": {"category": "all", "only_unlocked": True},
|
||||
"statistics": {"source": "all", "metric": "rate"}}
|
||||
for page, filters in defaults.items():
|
||||
with self.subTest(page=page):
|
||||
implicit, explicit = self.view(page), self.view(page, filters)
|
||||
self.assertEqual([r["id"] for r in implicit["rows"]], [r["id"] for r in explicit["rows"]])
|
||||
values = {f["key"]: f["value"] for f in implicit["filters"]}
|
||||
for key, value in filters.items():
|
||||
self.assertEqual(values[key], value)
|
||||
maps = self.view("maps")
|
||||
self.assertTrue(maps["groups"])
|
||||
self.assertTrue(all(group["collapsed"] for group in maps["groups"]))
|
||||
for category in ("eggs", "usable", "consumables", "materials", "other", "equipment"):
|
||||
dto = self.view("bag", {"category": category}, simple=True)
|
||||
self.assertEqual(dto["filters"][0]["value"], category)
|
||||
self.assertTrue(dto["rows"], category)
|
||||
if category != "eggs":
|
||||
self.assertTrue(any(len(row["inventory_ids"]) >= 2 and row["count"] >= 7 for row in dto["rows"]), category)
|
||||
mixed = self.http.get(self.path("views/bag"), params={"query": "{}", "category": "eggs"})
|
||||
self.response(mixed, 400)
|
||||
|
||||
def test_seeded_maps_tasks_and_exploration_have_business_data(self):
|
||||
maps = self.view("maps")
|
||||
stage = next(row for row in maps["rows"] if row["id"] == "0101")
|
||||
self.assertTrue(stage["unlocked"])
|
||||
self.assertEqual(len(stage["edits"]["level"]["options"]), 3)
|
||||
self.assertTrue(stage["costs"])
|
||||
resource = self.view("maps", {"category": "resource", "only_unlocked": False})
|
||||
self.assertTrue(resource["rows"])
|
||||
self.assertTrue(all(row["category"] in ("mine", "ticket") for row in resource["rows"]))
|
||||
self.assertTrue(any(any(cost["kind"] == "item" for cost in row["costs"]) for row in resource["rows"]))
|
||||
self.assertTrue(any(any(cost["kind"] == "item" and cost["available"] > 0 for cost in row["costs"]) for row in resource["rows"]))
|
||||
# Engine deliberately gates full-table task planning until the user
|
||||
# refreshes tasks or enables that feature. Exercise its real HTTP action.
|
||||
self.assertEqual(self.manager._worker(self.account).engine.snapshot.raw["currentTasks"][0]["typeId"], "1001004")
|
||||
self.action("refresh_tasks")
|
||||
mainline = self.view("mainline")
|
||||
self.assertTrue(mainline["rows"])
|
||||
self.assertTrue(any(str(row.get("task_type_id")) == "1001004" for row in mainline["rows"]))
|
||||
config = self.config()["config"]
|
||||
config["explore_policy"].update(enabled=True, teams={"1": {"enabled": True, "area": "1", "monsters": [101, 102, 103]}})
|
||||
self.save(config)
|
||||
explore = self.view("exploration")
|
||||
self.assertTrue(explore["rows"])
|
||||
team = next(row for row in explore["rows"] if str(row["id"]) == "1")
|
||||
self.assertEqual(team["rule_path"], ["explore_policy", "teams", "1"])
|
||||
self.assertTrue(team["edits"]["monsters"]["options"])
|
||||
self.assertEqual(self.manager._worker(self.account).engine.explore_policy.teams["1"].monsters, [101, 102, 103])
|
||||
self.assertEqual(team["monsters"], [101, 102, 103])
|
||||
self.assertGreater(team["cost_ti"], 0)
|
||||
self.assertTrue(any(action.kind == "explore_start" for action in self.manager._worker(self.account).engine.plans()))
|
||||
self.assertFalse(self.manager.status(self.account)["running"])
|
||||
|
||||
def test_job_stays_running_until_persistence_and_status_summary_are_published(self):
|
||||
account = self.create_account(False, "publication barrier")
|
||||
self.action("login", {"account": "barrier-account", "password": PASSWORD, "remember": False}, account)
|
||||
worker = self.manager._worker(account)
|
||||
gate = SnapshotGate()
|
||||
self.stack.callback(gate.release.set)
|
||||
persist = worker._persist_session
|
||||
|
||||
def blocked_persist():
|
||||
if worker.engine.client is not None:
|
||||
gate.wait()
|
||||
persist()
|
||||
|
||||
with patch.object(worker, "_persist_session", blocked_persist):
|
||||
value = self.response(self.http.post(self.path("actions/enter_server", account), json={"server_id": 7}), 202)
|
||||
self.assertTrue(gate.entered.wait(3))
|
||||
try:
|
||||
current = self.response(self.http.get(self.path("jobs/" + value["id"], account)))
|
||||
self.assertEqual(current["status"], "running", "A terminal job must not precede persisted/public status")
|
||||
finally:
|
||||
gate.release.set()
|
||||
self.job(value, account)
|
||||
self.assertTrue(self.response(self.http.get(self.path("status", account)))["connected"])
|
||||
|
||||
def test_seeded_sqlite_statistics_compute_rates_sources_and_stamina(self):
|
||||
for source, samples, units, rate, efficiency in (("sweep", 2, 2, .5, .1), ("event", 1, 3, 1, .6), ("all", 3, 5, 2/3, .2)):
|
||||
with self.subTest(source=source):
|
||||
dto = self.view("statistics", {"stage_id": "0101", "level": "3", "source": source})
|
||||
row = next(row for row in dto["rows"] if row["id"] == "item:30005")
|
||||
self.assertEqual((row["samples"], row["units"]), (samples, units))
|
||||
self.assertAlmostEqual(row["rate"], rate)
|
||||
self.assertAlmostEqual(row["per_stamina"], efficiency)
|
||||
self.assertTrue(row["interval"])
|
||||
point = next(point for point in dto["charts"][0]["series"] if point["id"] == row["id"])
|
||||
self.assertAlmostEqual(point["value"], rate)
|
||||
dto = self.view("statistics", {"stage_id": "0101", "level": "3", "metric": "per_stamina"})
|
||||
point = next(point for point in dto["chart"]["series"] if point["id"] == "item:30005")
|
||||
self.assertAlmostEqual(point["value"], .2)
|
||||
|
||||
def test_dto_egg_edit_autosaves_into_real_engine_plan_and_restart_stays_stopped(self):
|
||||
config, row = self.hatch_config()
|
||||
column = next(column for column in self.view("bag")["columns"] if column["key"] == "enabled")
|
||||
self.assertEqual([row["id"] if part == "{id}" else part for part in column["edit"]["path"]], row["rule_path"] + ["enabled"])
|
||||
applied = self.save(config)
|
||||
engine = self.manager._worker(self.account).engine
|
||||
self.assertEqual(engine.policy.egg_rules[row["id"]]["priority"], 13)
|
||||
plans = engine.plans()
|
||||
self.assertTrue(plans)
|
||||
self.assertTrue(all(plan.kind == "hatch" for plan in plans))
|
||||
self.assertTrue(all(plan.payload["eggs"][0]["itemId"] in row["inventory_ids"] for plan in plans))
|
||||
preview = self.view("plans")
|
||||
self.assertTrue(preview["rows"])
|
||||
self.assertFalse(engine.auto)
|
||||
self.action("start")
|
||||
self.assertTrue(self.manager.status(self.account)["running"])
|
||||
self.manager.close()
|
||||
from ranch_web.service import WebManager
|
||||
self.manager = WebManager(self.root, start_scheduler=False, engine_factory=real_engine_factory, login_factory=self.login)
|
||||
self.app.state.manager = self.manager
|
||||
self.wait_idle()
|
||||
self.assertEqual(self.config(), applied)
|
||||
self.assertFalse(self.manager.status(self.account)["running"])
|
||||
self.assertFalse(self.manager._worker(self.account).engine.auto)
|
||||
|
||||
def test_same_species_config_and_catalog_overrides_are_independent_between_accounts(self):
|
||||
other = self.create_account(label="account B")
|
||||
first, row = self.hatch_config()
|
||||
second, other_row = self.hatch_config(other, enabled=False, priority=91)
|
||||
self.assertEqual(row["id"], other_row["id"])
|
||||
first["overrides"] = {row["id"]: {"sell_money": 123456}}
|
||||
self.save(first)
|
||||
self.save(second, other)
|
||||
engine_a, engine_b = (self.manager._worker(a).engine for a in (self.account, other))
|
||||
self.assertIsNot(engine_a.catalog, engine_b.catalog)
|
||||
self.assertEqual(engine_a.catalog.monster(row["id"])["sell_money"], 123456)
|
||||
self.assertNotEqual(engine_b.catalog.monster(row["id"])["sell_money"], 123456)
|
||||
self.assertTrue(engine_a.plans())
|
||||
self.assertEqual(engine_b.plans(), [])
|
||||
self.assertEqual(next(r for r in self.view("bag", account=other)["rows"] if r["id"] == row["id"])["priority"], 91)
|
||||
|
||||
def test_http_reads_with_running_real_engine_do_not_dispatch_game_writes(self):
|
||||
account, client = self.logged_account()
|
||||
config, _ = self.hatch_config(account)
|
||||
self.save(config, account)
|
||||
self.action("start", account=account)
|
||||
reads = client.reads
|
||||
before = deepcopy(client.raw)
|
||||
for page in PAGES:
|
||||
self.view(page, account=account)
|
||||
self.response(self.http.get(self.path("status", account)))
|
||||
self.assertEqual(client.writes, [])
|
||||
self.assertEqual(client.reads, reads)
|
||||
self.assertEqual(client.raw, before)
|
||||
self.assertTrue(self.manager.status(account)["running"])
|
||||
|
||||
def test_blocked_game_job_keeps_http_cached_views_and_other_account_available(self):
|
||||
account, client = self.logged_account()
|
||||
cached = self.view("bag", account=account)
|
||||
gate = client.gate = SnapshotGate()
|
||||
self.stack.callback(gate.release.set)
|
||||
refresh = self.response(self.http.post(self.path("actions/refresh", account), json={"page": "incubator"}), 202)
|
||||
self.assertTrue(gate.entered.wait(3))
|
||||
for endpoint in ("/api/health", "/api/meta", self.path("status", account), self.path("logs", account), self.path("config", account), self.path("views/bag", account), self.path("views/mainline", account)):
|
||||
with self.subTest(endpoint=endpoint):
|
||||
start = time.monotonic()
|
||||
result = self.response(self.http.get(endpoint))
|
||||
self.assertLess(time.monotonic() - start, 1.5, endpoint)
|
||||
self.assertFalse(gate.release.is_set())
|
||||
if endpoint.endswith("views/bag"):
|
||||
self.assertEqual(result["data"], cached)
|
||||
self.assertEqual(self.manager.job(account, refresh["id"])["status"], "running")
|
||||
self.assertTrue(self.view("bag")["rows"])
|
||||
old = self.config(account)
|
||||
config = deepcopy(old["config"])
|
||||
config["interval"] = 60
|
||||
pending = self.response(self.http.put(self.path("config", account), json={"config": config, "revision": old["revision"]}), 202)
|
||||
self.assertTrue(pending["pending"])
|
||||
self.assertEqual(pending["revision"], old["revision"])
|
||||
self.assertEqual(self.config(account), old)
|
||||
gate.release.set()
|
||||
self.job(refresh, account)
|
||||
self.job(pending["job"], account)
|
||||
self.assertEqual(self.config(account)["config"]["interval"], 60)
|
||||
|
||||
def test_stop_cancels_queued_start_without_later_resurrection(self):
|
||||
account, client = self.logged_account()
|
||||
config, _ = self.hatch_config(account)
|
||||
self.save(config, account)
|
||||
gate = client.gate = SnapshotGate()
|
||||
self.stack.callback(gate.release.set)
|
||||
refresh = self.response(self.http.post(self.path("actions/refresh", account), json={}), 202)
|
||||
self.assertTrue(gate.entered.wait(3))
|
||||
start = self.response(self.http.post(self.path("actions/start", account), json={}), 202)
|
||||
self.assertEqual(self.manager.job(account, start["id"])["status"], "queued")
|
||||
begin = time.monotonic()
|
||||
stop = self.response(self.http.post(self.path("actions/stop", account), json={}), 202)
|
||||
self.assertLess(time.monotonic() - begin, 1.5)
|
||||
self.assertEqual(stop["status"], "succeeded")
|
||||
self.assertFalse(self.manager.status(account)["running"])
|
||||
self.assertFalse(self.manager._worker(account).engine.auto)
|
||||
self.job(start, account, "cancelled")
|
||||
gate.release.set()
|
||||
self.job(refresh, account)
|
||||
self.wait_idle(account)
|
||||
self.assertFalse(self.manager.status(account)["running"])
|
||||
self.assertFalse(self.manager._worker(account).engine.auto)
|
||||
self.assertEqual(client.writes, [])
|
||||
|
||||
def test_legacy_schema_one_import_is_a_job_and_never_starts_engine(self):
|
||||
from ranch_assistant.model import Policy
|
||||
from ranch_assistant.policy_io import portable_policy
|
||||
|
||||
config, row = self.hatch_config()
|
||||
self.save(config)
|
||||
self.action("start")
|
||||
engine = self.manager._worker(self.account).engine
|
||||
bundle = portable_policy(Policy(**config["policy"]), engine.snapshot)
|
||||
self.assertEqual((bundle["schema"], bundle["assistantVersion"]), (1, "1.2.0"))
|
||||
bundle["policy"].update(enabled=True, fill=True)
|
||||
before = deepcopy(engine.snapshot.raw)
|
||||
value = self.response(self.http.post(self.path("config/import"), json={"config": bundle}), 202)
|
||||
self.job(value)
|
||||
self.assertFalse(self.manager.status(self.account)["running"])
|
||||
self.assertFalse(engine.auto)
|
||||
self.assertEqual(engine.snapshot.raw, before)
|
||||
self.assertTrue(self.config()["config"]["policy"]["egg_rules"][row["id"]]["enabled"])
|
||||
exported = self.job(self.response(self.http.get(self.path("config/export")), 202))["result"]
|
||||
self.assertEqual(exported["schema"], 2)
|
||||
self.assertEqual(exported["format"], "ranch-helper-policies")
|
||||
|
||||
def test_yield_csv_import_is_saved_and_changes_real_view(self):
|
||||
row = self.view("bag")["rows"][0]
|
||||
content = f"typeId,sell_money,sell_exp,time_total\n{row['id']},7777,123,600\n".encode()
|
||||
result = self.action("import_yields", {"filename": "uploaded.csv", "content_base64": base64.b64encode(content).decode()})["result"]
|
||||
self.assertEqual(result["count"], 1)
|
||||
self.assertEqual(self.config()["config"]["overrides"][row["id"]]["sell_money"], 7777)
|
||||
view = self.view("yields", {"search": row["id"]})
|
||||
self.assertEqual(next(r for r in view["rows"] if r["id"] == row["id"])["sell_money"], 7777)
|
||||
|
||||
def test_http_manual_lock_sell_and_feed_confirmations_reach_real_engine(self):
|
||||
engine = self.manager._worker(self.account).engine
|
||||
self.action("lock", {"monster_ids": [101]})
|
||||
self.assertTrue(engine.snapshot.monsters[101]["lock"])
|
||||
self.action("unlock", {"monster_ids": [101]})
|
||||
self.assertFalse(engine.snapshot.monsters[101]["lock"])
|
||||
before = deepcopy(engine.snapshot.raw)
|
||||
self.action("sell", {"monster_ids": [101]}, expected="failed")
|
||||
self.assertEqual(engine.snapshot.raw, before)
|
||||
self.action("sell", {"monster_ids": [101], "confirm": True})
|
||||
self.assertNotIn(101, engine.snapshot.monsters)
|
||||
self.action("feed", {"monster_ids": [102], "target_id": 900}, expected="failed")
|
||||
self.assertIn(102, engine.snapshot.monsters)
|
||||
self.action("feed", {"monster_ids": [102], "target_id": 900, "confirm": True})
|
||||
self.assertNotIn(102, engine.snapshot.monsters)
|
||||
self.assertIn(900, engine.snapshot.monsters)
|
||||
self.action("sell", {"monster_ids": [900], "confirm": True}, expected="failed")
|
||||
self.assertIn(900, engine.snapshot.monsters)
|
||||
self.assertFalse(self.manager.status(self.account)["running"])
|
||||
|
||||
def test_http_expansion_quote_is_confirmed_once_and_bound_to_account(self):
|
||||
other = self.create_account(label="quote scope")
|
||||
quote = self.action("quote_expansion", {"kind": "stack", "currency": "money", "position": 6})["result"]
|
||||
self.assertGreater(quote["cost"], 0)
|
||||
before = self.manager._worker(self.account).engine.snapshot.raw["master"]["money"]
|
||||
self.action("expand", {"quote_id": quote["quote_id"], "confirm": True}, other, expected="failed")
|
||||
self.action("expand", {"quote_id": quote["quote_id"]}, expected="failed")
|
||||
self.assertEqual(self.manager._worker(self.account).engine.snapshot.raw["master"]["money"], before)
|
||||
self.action("expand", {"quote_id": quote["quote_id"], "confirm": True})
|
||||
engine = self.manager._worker(self.account).engine
|
||||
self.assertEqual(engine.snapshot.raw["master"]["money"], before - quote["cost"])
|
||||
self.assertTrue(any(row["position"] == 6 for row in engine.snapshot.raw["stacks"]))
|
||||
self.assertEqual(self.response(self.http.get(self.path("status")))["player"]["money"], before - quote["cost"])
|
||||
self.action("expand", {"quote_id": quote["quote_id"], "confirm": True}, expected="failed")
|
||||
self.assertEqual(engine.snapshot.raw["master"]["money"], before - quote["cost"])
|
||||
|
||||
def test_local_auth_host_csrf_and_remote_client_boundary(self):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
before = self.response(self.http.get("/api/accounts"))
|
||||
invalid_host = self.response(self.http.post("/api/accounts", json={"demo": True}, headers={"Host": "rebind.invalid"}), 400)
|
||||
self.assertEqual(invalid_host["error"]["code"], "invalid_host")
|
||||
for headers in ({"Origin": "https://cross-site.invalid"}, {"Sec-Fetch-Site": "cross-site"}):
|
||||
self.response(self.http.post("/api/accounts", json={"demo": True}, headers=headers), 403)
|
||||
self.assertEqual(self.response(self.http.get("/api/accounts")), before)
|
||||
self.response(self.http.post("/api/accounts", json={"demo": True}, headers={"Origin": "http://127.0.0.1:8765", "Sec-Fetch-Site": "same-origin"}), 201)
|
||||
with TestClient(self.app, base_url="http://127.0.0.1:8765", client=("203.0.113.2", 51234)) as remote:
|
||||
self.response(remote.get("/api/accounts", headers={"X-Forwarded-For": "127.0.0.1", "X-Forwarded-Host": "localhost"}), 403)
|
||||
|
||||
def test_password_auth_cookie_revocation_and_cross_site_login(self):
|
||||
from fastapi.testclient import TestClient
|
||||
from ranch_web.app import create_app
|
||||
from ranch_web.config import COOKIE_NAME, WebConfig
|
||||
|
||||
app = create_app(manager=self.manager, updates=self.updates,
|
||||
config=WebConfig(data_dir=self.root, password="integration-admin-password"))
|
||||
with TestClient(app, base_url="http://127.0.0.1:8765", client=("127.0.0.1", 50001)) as http:
|
||||
self.response(http.get("/api/accounts"), 401)
|
||||
self.response(http.post("/api/auth/login", json={"password": "wrong"}), 401)
|
||||
self.response(http.post("/api/auth/login", json={"password": "integration-admin-password"}, headers={"Origin": "https://cross-site.invalid"}), 403)
|
||||
response = http.post("/api/auth/login", json={"password": "integration-admin-password"})
|
||||
self.response(response)
|
||||
self.assertIn("httponly", response.headers["set-cookie"].lower())
|
||||
self.assertIn("samesite=strict", response.headers["set-cookie"].lower())
|
||||
token = http.cookies.get(COOKIE_NAME)
|
||||
self.assertTrue(token)
|
||||
self.assertNotIn("integration-admin-password", token)
|
||||
self.response(http.get("/api/accounts"))
|
||||
self.response(http.post("/api/auth/logout"))
|
||||
self.response(http.get("/api/accounts", headers={"Cookie": COOKIE_NAME + "=" + token}), 401)
|
||||
|
||||
def assert_no_secrets(self, value):
|
||||
encoded = json.dumps(value, ensure_ascii=False)
|
||||
for secret in (TOKEN, KEY, PASSWORD, str(REQID), str(REQSID), str(self.root), self.root.as_posix()):
|
||||
self.assertNotIn(secret, encoded)
|
||||
self.assertNotIn("Traceback (most recent call last)", encoded)
|
||||
|
||||
def test_game_credentials_are_absent_from_http_views_config_jobs_and_logs(self):
|
||||
account, client = self.logged_account()
|
||||
for page in PAGES:
|
||||
self.assert_no_secrets(self.view(page, account=account))
|
||||
for suffix in ("status", "config", "logs", "logs?debug=true"):
|
||||
self.assert_no_secrets(self.response(self.http.get(self.path(suffix, account))))
|
||||
self.assert_no_secrets(self.action("export_config", account=account))
|
||||
client.fail_snapshot = True
|
||||
failed = self.action("refresh", account=account, expected="failed")
|
||||
self.assert_no_secrets(failed)
|
||||
self.assert_no_secrets(self.response(self.http.get(self.path("logs?debug=true", account))))
|
||||
self.assert_no_secrets(self.response(self.http.get(self.path("status", account))))
|
||||
|
||||
def test_lazy_log_detail_is_available_and_keeps_structure_with_secrets_masked(self):
|
||||
account, _ = self.logged_account()
|
||||
logs = self.response(self.http.get(self.path("logs?debug=true", account)))
|
||||
entries = [entry for entry in logs["entries"] if entry.get("details_available")]
|
||||
self.assertTrue(entries, logs)
|
||||
self.assertTrue(all("body" not in entry and "details" not in entry for entry in logs["entries"]))
|
||||
detail = self.response(self.http.get(self.path("logs/" + str(entries[-1]["id"]), account)))
|
||||
self.assert_no_secrets(detail)
|
||||
self.assertIn("integration-readable-detail", json.dumps(detail))
|
||||
self.assertIn("body", json.dumps(detail))
|
||||
|
||||
def test_updates_use_fake_source_and_no_stable_v2_means_no_upgrade(self):
|
||||
self.response(self.http.get("/api/meta"))
|
||||
self.response(self.http.get("/api/system/updates"))
|
||||
self.source.assert_not_called()
|
||||
for releases in ([], [{"tag_name": "v1.2.0", "draft": False, "prerelease": False}],
|
||||
[{"tag_name": "v2.0.0.dev1", "draft": False, "prerelease": True},
|
||||
{"tag_name": "v2.0.0", "draft": True, "prerelease": False},
|
||||
{"tag_name": "v3.0.0", "draft": False, "prerelease": False}]):
|
||||
self.source.return_value = releases
|
||||
result = self.response(self.http.post("/api/system/updates/check"))
|
||||
self.assertFalse(result["available"])
|
||||
self.assertIsNone(result["latest_version"])
|
||||
self.assertEqual(result["status"], "no_release")
|
||||
self.assertEqual(self.source.call_count, 3)
|
||||
result = self.response(self.http.post("/api/system/updates/apply", json={}), 202)
|
||||
self.assertEqual(result["status"], "unavailable")
|
||||
self.assertFalse((self.root / "update-request.json").exists())
|
||||
|
||||
def test_config_revisions_and_invalid_input_are_atomic(self):
|
||||
old = self.config()
|
||||
value = deepcopy(old["config"])
|
||||
value["interval"] = 60
|
||||
applied = self.save(value)
|
||||
self.response(self.http.put(self.path("config"), json={"config": old["config"], "revision": old["revision"]}), 409)
|
||||
bad = deepcopy(value)
|
||||
bad["policy"]["egg_rules"] = {"1001010": {"enabled": "false"}}
|
||||
self.response(self.http.put(self.path("config"), json={"config": bad, "revision": applied["revision"]}), 400)
|
||||
self.assertEqual(self.config(), applied)
|
||||
self.response(self.http.post(self.path("actions/import_yields"), json={"path": "C:/private/account.csv"}), 400)
|
||||
|
||||
|
||||
def _page_test(page):
|
||||
def check(self):
|
||||
self.assert_dto(page)
|
||||
check.__name__ = "test_page_" + page
|
||||
return check
|
||||
|
||||
|
||||
for _page in PAGES:
|
||||
setattr(WebIntegrationTests, "test_page_" + _page, _page_test(_page))
|
||||
|
||||
|
||||
class FreshProcessIntegrationTests(unittest.TestCase):
|
||||
def child(self, program):
|
||||
env = {key: value for key, value in os.environ.items() if not key.startswith("RANCH_WEB_")}
|
||||
env["PYTHONIOENCODING"] = "utf-8"
|
||||
result = subprocess.run([sys.executable, "-X", "utf8", "-c", textwrap.dedent(program)],
|
||||
cwd=ROOT, env=env, capture_output=True, text=True, encoding="utf-8", timeout=35,
|
||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
return json.loads(result.stdout.strip().splitlines()[-1])
|
||||
|
||||
def test_fresh_web_process_blocks_gui_imports_and_serves_demo_strategy(self):
|
||||
result = self.child('''
|
||||
import importlib.abc, json, sys, tempfile, time
|
||||
from pathlib import Path
|
||||
attempted = []
|
||||
class BlockGUI(importlib.abc.MetaPathFinder):
|
||||
def find_spec(self, fullname, path=None, target=None):
|
||||
if fullname.startswith('PySide6') or fullname.endswith('_gui') or fullname == 'ranch_assistant.gui':
|
||||
attempted.append(fullname)
|
||||
raise ImportError('GUI import blocked in fresh Web integration process')
|
||||
sys.meta_path.insert(0, BlockGUI())
|
||||
from ranch_web.tests.test_web_integration import NoExternalSockets, real_engine_factory
|
||||
from ranch_web.app import create_app
|
||||
from ranch_web.config import WebConfig
|
||||
from ranch_web.service import WebManager
|
||||
from fastapi.testclient import TestClient
|
||||
with NoExternalSockets() as network, tempfile.TemporaryDirectory(prefix='web-fresh-process-') as temporary:
|
||||
manager = WebManager(Path(temporary) / 'new-root', start_scheduler=False, engine_factory=real_engine_factory)
|
||||
try:
|
||||
app = create_app(manager=manager, config=WebConfig(data_dir=Path(temporary) / 'new-root'))
|
||||
with TestClient(app, base_url='http://127.0.0.1', client=('127.0.0.1', 50000)) as http:
|
||||
assert http.get('/api/health').json()['status'] == 'ok'
|
||||
account = http.post('/api/accounts', json={'demo': True}).json()['id']
|
||||
value = http.get('/api/accounts/' + account + '/config').json()
|
||||
value['config']['interval'] = 60
|
||||
saved = http.put('/api/accounts/' + account + '/config', json=value)
|
||||
assert saved.status_code in (200, 202), saved.text
|
||||
deadline = time.monotonic() + 8
|
||||
while manager.status(account)['busy'] and time.monotonic() < deadline:
|
||||
time.sleep(.005)
|
||||
assert http.get('/api/accounts/' + account + '/config').json()['config']['interval'] == 60
|
||||
assert http.get('/api/schema').status_code == 200
|
||||
view = http.get('/api/accounts/' + account + '/views/bag').json()
|
||||
if view['loading']:
|
||||
deadline = time.monotonic() + 8
|
||||
while manager.job(account, view['job_id'])['status'] not in ('succeeded', 'failed') and time.monotonic() < deadline:
|
||||
time.sleep(.005)
|
||||
bag = http.get('/api/accounts/' + account + '/views/bag').json()['data']
|
||||
assert bag['rows'] and bag['columns'][0]['key']
|
||||
assert not network.attempts
|
||||
finally:
|
||||
manager.close()
|
||||
assert not attempted, attempted
|
||||
assert not any(n.startswith('PySide6') for n in sys.modules)
|
||||
print(json.dumps({'health': 'ok', 'demo_rows': len(bag['rows']), 'interval': 60, 'blocked_import_attempts': attempted}))
|
||||
''')
|
||||
self.assertEqual(result["blocked_import_attempts"], [])
|
||||
self.assertGreater(result["demo_rows"], 0)
|
||||
|
||||
def test_real_engine_battle_worker_subprocess_still_runs_after_web_imports(self):
|
||||
result = self.child('''
|
||||
import json, tempfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
import subprocess
|
||||
from ranch_web.app import create_app
|
||||
from ranch_web.service import WebManager
|
||||
from ranch_web.tests.test_web_integration import NoExternalSockets, real_engine_factory
|
||||
from ranch_assistant.battle_simulator import combat_tables, simulate
|
||||
row = combat_tables()['monster_info']['1001010']
|
||||
mon = {'id': 101, 'typeId': 1001010, 'level': 20, 'mode': 2, 'tpLevel': 0, 'feel': 0, 'upStar': 0, 'pAtk': 0, 'pDef': 0, 'pHp': 0, 'pDex': 0}
|
||||
for name in ('Atk', 'Def', 'Hp', 'Dex'):
|
||||
mon['g' + name] = (row[name.lower() + '_grow_min'] + row[name.lower() + '_grow_max']) / 2
|
||||
enemy = {'type': '1001010', 'team': 2, 'mode': 2, 'level': 1, 'atk': 16, 'def': 20, 'hp': 101, 'dex': 4, 'spd_mov': .92, 'spd_atk': 1595, 'atk_dis': 100, 'skill_1': 0, 'skill_2': 0, 'joinTime': -1, 'wave': 1, 'teamPos': 1, 'ai': 0, 'joinPoint': 'point_team2_fore2', 'controller': []}
|
||||
request = {'context': 'ordinary_stage', 'seed': 0, 'team': 'teamA',
|
||||
'battle_position': {'battleType': 'stage', 'stageId': 'fixture', 'stageLevel': '1'},
|
||||
'roster': {'master': {'level': 43}, 'monsters': [mon], 'teams': [{'teamName': 'teamA', 'monsters': [101]}], 'monsterAttributes': []},
|
||||
'original_data': {'battle': {'time': 30, 'winType': ['1'], 'loseType': ['1', '2'], 'controller': [], 'triggers': [],
|
||||
'teams': [{'team': 2, 'numMax': 2, 'ap': 80, 'mons': [enemy]}],
|
||||
'battleField': {'fieldMode': True, 'fieldName': 'default', 'mapAreas': [], 'mapObjects': []}}}}
|
||||
with NoExternalSockets() as network, tempfile.TemporaryDirectory(prefix='web-battle-process-') as temporary:
|
||||
manager = WebManager(Path(temporary) / 'new-root', start_scheduler=False, engine_factory=real_engine_factory)
|
||||
try:
|
||||
account = manager.create_account(demo=True)['id']
|
||||
engine = manager._worker(account).engine
|
||||
engine._select_battle_runtime('experimental')
|
||||
with patch('subprocess.Popen', wraps=subprocess.Popen) as launch:
|
||||
result = engine.battles.runtime.run(request, timeout=15)
|
||||
assert launch.call_count == 1
|
||||
assert 'ranch_assistant.battle_simulator' in launch.call_args.args[0]
|
||||
assert result == simulate(request), result
|
||||
assert result['outcome'] == 'win', result
|
||||
assert not network.attempts
|
||||
print(json.dumps({'outcome': result['outcome'], 'execution_mode': result['execution_mode'], 'real_worker_processes': launch.call_count}))
|
||||
finally:
|
||||
manager.close()
|
||||
''')
|
||||
self.assertEqual(result["real_worker_processes"], 1)
|
||||
self.assertEqual(result["outcome"], "win")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Focused pure-policy tests; no desktop imports or private account files."""
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from ranch_assistant.engine import Engine, demo_snapshot
|
||||
from ranch_assistant.model import Catalog, Policy
|
||||
from ranch_assistant.policy_io import portable_policy
|
||||
from ranch_web.policies import apply_config, default_config, export_config, import_config, validate_config
|
||||
|
||||
|
||||
class WebPolicyTests(unittest.TestCase):
|
||||
def test_defaults_are_independent_and_match_current_desktop(self):
|
||||
first, second = default_config(), default_config()
|
||||
first["policy"]["gift_targets"]["900"] = 3
|
||||
self.assertEqual(second["policy"]["gift_targets"], {})
|
||||
self.assertTrue(second["policy"]["manual_eggs"])
|
||||
self.assertEqual(second["progression_policy"]["battle_mode"], "experimental")
|
||||
|
||||
def test_validate_original_mode_before_normalizing_for_linux(self):
|
||||
for source in ("original", "experimental"):
|
||||
with self.subTest(source=source):
|
||||
value = validate_config({"progression_policy": {"battle_mode": source}})
|
||||
self.assertEqual(value["progression_policy"]["battle_mode"], "experimental")
|
||||
with self.assertRaises(ValueError):
|
||||
validate_config({"progression_policy": {"battle_mode": "unknown"}})
|
||||
|
||||
def test_validate_legacy_egg_mode_before_enforcing_current_desktop(self):
|
||||
for flag in (False, True):
|
||||
with self.subTest(flag=flag):
|
||||
source = {"policy": {"manual_eggs": flag}}
|
||||
value = validate_config(source)
|
||||
self.assertTrue(value["policy"]["manual_eggs"])
|
||||
self.assertIs(source["policy"]["manual_eggs"], flag)
|
||||
for flag in (0, 1, "false", "true", None, [], {}):
|
||||
with self.subTest(flag=flag), self.assertRaises(ValueError):
|
||||
validate_config({"policy": {"manual_eggs": flag}})
|
||||
|
||||
def test_apply_legacy_mode_never_plans_unchecked_eggs(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
engine = Engine(Catalog(), budget_path=Path(folder) / "budget.json")
|
||||
engine.snapshot = demo_snapshot(engine.catalog)
|
||||
config = default_config()
|
||||
config["policy"]["manual_eggs"] = False
|
||||
applied = apply_config(engine, config)
|
||||
self.assertTrue(applied["policy"]["manual_eggs"])
|
||||
self.assertTrue(engine.policy.manual_eggs)
|
||||
self.assertEqual(engine.planner.available_eggs(engine.snapshot, engine.policy), [])
|
||||
self.assertEqual(engine.planner.hatch_actions(engine.snapshot, engine.policy), [])
|
||||
egg = engine.snapshot.eggs(engine.catalog)[0]
|
||||
config["policy"]["egg_rules"] = {str(egg["typeId"]): {"enabled": True}}
|
||||
apply_config(engine, config)
|
||||
eligible = engine.planner.available_eggs(engine.snapshot, engine.policy)
|
||||
self.assertEqual([str(row["typeId"]) for row, _ in eligible], [str(egg["typeId"])])
|
||||
actions = engine.planner.hatch_actions(engine.snapshot, engine.policy)
|
||||
self.assertTrue(actions)
|
||||
self.assertTrue(all(action.payload["eggs"][0]["itemId"] == egg["id"] for action in actions))
|
||||
self.assertFalse(engine.auto)
|
||||
|
||||
def test_old_portable_both_schemas_enforce_selected_eggs_without_starting(self):
|
||||
legacy = portable_policy(Policy(manual_eggs=False))
|
||||
bundle = export_config(default_config())
|
||||
bundle["policy"]["manual_eggs"] = False
|
||||
for document in (legacy, bundle):
|
||||
with self.subTest(schema=document["schema"]):
|
||||
imported = import_config(document)
|
||||
self.assertTrue(imported["policy"]["manual_eggs"])
|
||||
self.assertTrue(export_config(imported)["policy"]["manual_eggs"])
|
||||
for document in (legacy, bundle):
|
||||
malformed = deepcopy(document)
|
||||
malformed["policy"]["manual_eggs"] = "false"
|
||||
with self.subTest(schema=document["schema"]), self.assertRaises(ValueError):
|
||||
import_config(malformed)
|
||||
|
||||
def test_reject_unknown_secret_and_invalid_dynamic_paths(self):
|
||||
bad = [
|
||||
{"password": "synthetic"}, {"policy": {"token": "synthetic"}},
|
||||
{"policy": {"gift_items": {"30001": {"enabled": True, "password": "synthetic"}}}},
|
||||
{"policy": {"egg_rules": {"1001010": {"enabled": 1}}}},
|
||||
{"policy": {"feed_targets": {"900": True}}},
|
||||
{"policy": {"gift_targets": {"../../settings": 1}}},
|
||||
{"policy": {"reserved_types": [True]}}, {"policy": {"protect_star": 0}},
|
||||
{"policy": {"gift_items": {"30001": {"reserve": -1}}}},
|
||||
{"policy": {"egg_rules": {"1001010": {"keep_count": 1001}}}},
|
||||
{"policy": {"egg_rules": {"1001010": {"refill_below": 11, "refill_target": 10}}}},
|
||||
{"sweep_policy": {"rules": {"0101": {"enabled": True, "limit": -1}}}},
|
||||
{"sweep_policy": {"rules": {"0101": {"level": "4"}}}},
|
||||
{"explore_policy": {"teams": {"1": {"monsters": [1, 2]}}}},
|
||||
{"explore_policy": {"teams": {"1": {"monsters": [1, 2, 2]}}}},
|
||||
{"explore_policy": {"teams": {"1": {"monsters": [True, 2, 3]}}}},
|
||||
{"daily_policy": {"selected": ["all"]}}, {"interval": True},
|
||||
{"overrides": {"1001010": {"sell_money": float("nan")}}},
|
||||
{"overrides": {"1001010": {"time_total": -1}}},
|
||||
{"overrides": {"1001010": {"path": "private"}}},
|
||||
{"log_sizes": [0, 0]}, {"yield_stars": [True]},
|
||||
]
|
||||
for value in bad:
|
||||
with self.subTest(value=value), self.assertRaises(ValueError):
|
||||
validate_config(value)
|
||||
|
||||
def test_nested_defaults_and_fractional_thresholds_are_preserved(self):
|
||||
value = validate_config({"policy": {"min_gold_per_hour": .5, "coins_per_exp": 2.75,
|
||||
"egg_rules": {"1001010": {"keep_count": 7}}}})
|
||||
self.assertEqual(value["policy"]["min_gold_per_hour"], .5)
|
||||
self.assertEqual(value["policy"]["egg_rules"]["1001010"]["keep_count"], 7)
|
||||
self.assertEqual(value["policy"]["egg_rules"]["1001010"]["action"], "sell")
|
||||
|
||||
def test_apply_is_atomic_and_never_starts_automation(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
engine = Engine(Catalog(), budget_path=Path(folder) / "budget.json")
|
||||
original = engine.policy
|
||||
with self.assertRaises(ValueError):
|
||||
apply_config(engine, {"policy": {"protect_star": 6}, "quest_policy": {"enabled": "yes"}})
|
||||
self.assertIs(engine.policy, original)
|
||||
cfg = default_config()
|
||||
cfg["progression_policy"]["battle_mode"] = "original"
|
||||
cfg["policy"]["gift_targets"] = {"900": 2}
|
||||
cfg["overrides"] = {"1001010": {"sell_money": 12.5}}
|
||||
apply_config(engine, cfg)
|
||||
self.assertFalse(engine.auto)
|
||||
self.assertEqual(engine.progression_policy.battle_mode, "experimental")
|
||||
self.assertEqual(engine.policy.gift_targets, {"900": 2})
|
||||
self.assertEqual(engine.catalog.monster(1001010)["sell_money"], 12.5)
|
||||
|
||||
def test_portable_schema_two_remaps_species_and_normalizes_legacy_mode(self):
|
||||
snapshot = demo_snapshot(Catalog())
|
||||
config = default_config()
|
||||
config["policy"].update(feed_targets={"900": 1}, gift_targets={"900": 2}, breakthrough_targets={"900": 3}, room_id=123456789)
|
||||
config["sweep_policy"]["rules"] = {"0101": {"enabled": True, "level": "3", "limit": 4}}
|
||||
exported = export_config(config, snapshot)
|
||||
self.assertNotIn("feed_targets", exported["policy"])
|
||||
self.assertNotIn("gift_targets", exported["policy"])
|
||||
self.assertEqual(exported["policy"]["room_id"], 0)
|
||||
self.assertNotIn("log_sizes", exported)
|
||||
exported["progression_policy"]["battle_mode"] = "original"
|
||||
exported["sweep_policy"]["rules"]["0101"]["level"] = 3
|
||||
snapshot.monsters[900]["id"] = 999
|
||||
imported = import_config(exported, snapshot)
|
||||
for field, priority in (("feed_targets", 1), ("gift_targets", 2), ("breakthrough_targets", 3)):
|
||||
self.assertEqual(imported["policy"][field], {"999": priority})
|
||||
self.assertEqual(imported["progression_policy"]["battle_mode"], "experimental")
|
||||
self.assertEqual(imported["sweep_policy"]["rules"]["0101"]["level"], "3")
|
||||
self.assertEqual(import_config(exported)["policy"]["feed_targets"], {})
|
||||
|
||||
def test_schema_one_and_explore_import_never_copy_instance_ids(self):
|
||||
snapshot = demo_snapshot(Catalog())
|
||||
legacy = portable_policy(Policy(feed_targets={"900": 3}, protect_quality=6), snapshot)
|
||||
snapshot.monsters[900]["id"] = 999
|
||||
imported = import_config(legacy, snapshot)
|
||||
self.assertEqual(imported["policy"]["feed_targets"], {"999": 3})
|
||||
self.assertFalse(imported["policy"]["enabled"])
|
||||
snapshot = demo_snapshot(Catalog())
|
||||
for mid in (101, 102):
|
||||
snapshot.monsters[mid].update(process=3, typeId=snapshot.monsters[900]["typeId"])
|
||||
snapshot.raw["exploreTeams"] = [{"id": 800, "status": 0}]
|
||||
config = default_config()
|
||||
config["explore_policy"] = {"enabled": True, "reserve_ti": 9,
|
||||
"teams": {"800": {"enabled": True, "area": "1", "monsters": [900, 101, 102]}}}
|
||||
exported = export_config(config, snapshot)
|
||||
snapshot.raw["exploreTeams"][0]["id"] = 50
|
||||
for mon in snapshot.raw["monsters"]:
|
||||
mon["id"] += 1000
|
||||
imported = import_config(exported, snapshot)
|
||||
self.assertNotIn("800", imported["explore_policy"]["teams"])
|
||||
self.assertEqual(imported["explore_policy"]["teams"]["50"]["monsters"], [1101, 1102, 1900])
|
||||
self.assertFalse(imported["explore_policy"]["enabled"])
|
||||
|
||||
def test_import_rejects_unknown_fields_instead_of_silently_dropping_them(self):
|
||||
exported = export_config(default_config())
|
||||
for value in (exported | {"token": "synthetic"},
|
||||
exported | {"targetSpecies": {"feed": [{"typeId": "1001010", "priority": 2, "password": "synthetic"}]}},
|
||||
exported | {"policy": exported["policy"] | {"feed_targets": {"900": True}}}):
|
||||
with self.subTest(value=value), self.assertRaises(ValueError):
|
||||
import_config(value)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,349 @@
|
||||
"""Temporary filesystem and fake Docker/GitHub transaction tests."""
|
||||
from contextlib import closing, redirect_stdout
|
||||
from dataclasses import replace
|
||||
from datetime import timedelta
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from deploy.web import updater
|
||||
from ranch_web import updates
|
||||
|
||||
|
||||
def release(tag):
|
||||
return {"tag_name": tag, "draft": False, "prerelease": False}
|
||||
|
||||
|
||||
class FakeDocker:
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
self.events = []
|
||||
self.version = "2.0.0.dev1"
|
||||
self.old_version = self.version
|
||||
self.image = "sha256:" + "a" * 64
|
||||
self.old_image = self.image
|
||||
self.running = True
|
||||
self.fail_pull = self.fail_start = self.fail_rollback = False
|
||||
|
||||
def inspect_service(self, **kwargs):
|
||||
return {"image": self.image, "version": self.version, "running": self.running, "health": "healthy"}
|
||||
|
||||
def validate(self, image):
|
||||
self.events.append(("validate", image))
|
||||
|
||||
def pull(self, image):
|
||||
self.events.append(("pull", image))
|
||||
if not self.running:
|
||||
raise AssertionError("pull must happen while the old app is running")
|
||||
if self.fail_pull:
|
||||
raise updater.UpdaterError("fake registry failure")
|
||||
|
||||
def stop(self):
|
||||
self.events.append(("stop", None))
|
||||
self.running = False
|
||||
|
||||
def up(self, image):
|
||||
self.events.append(("up", image))
|
||||
self.running = True
|
||||
if image == self.old_image:
|
||||
if self.fail_rollback:
|
||||
raise updater.UpdaterError("fake rollback failure")
|
||||
self.image = image
|
||||
self.version = self.old_version
|
||||
else:
|
||||
self.image = "sha256:" + "b" * 64
|
||||
self.version = image.rsplit(":", 1)[1][1:]
|
||||
(self.config.data_dir / "key.bin").write_bytes(b"changed-key")
|
||||
with closing(sqlite3.connect(self.config.data_dir / "samples.sqlite3")) as connection, connection:
|
||||
connection.execute("insert into samples values (2)")
|
||||
if self.fail_start:
|
||||
raise updater.UpdaterError("fake health failure")
|
||||
|
||||
|
||||
class HostUpdaterTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix="ranch-host-updater-")
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name).resolve()
|
||||
self.config = updater.Config(
|
||||
project_dir=self.root, data_dir=self.root / "data", control_dir=self.root / "control",
|
||||
backup_dir=self.root / "backups", failed_data_dir=self.root / "failed-data",
|
||||
)
|
||||
self.config.data_dir.mkdir()
|
||||
self.config.control_dir.mkdir()
|
||||
(self.config.data_dir / "key.bin").write_bytes(b"original-encrypted-test-key")
|
||||
with closing(sqlite3.connect(self.config.data_dir / "samples.sqlite3")) as connection, connection:
|
||||
connection.execute("create table samples (n integer)")
|
||||
connection.execute("insert into samples values (1)")
|
||||
self.docker = FakeDocker(self.config)
|
||||
self.host = updater.HostUpdater(self.config, self.docker)
|
||||
self.github = patch.object(updates, "github_releases", return_value=[release("v2.0.0")])
|
||||
self.releases = self.github.start()
|
||||
self.addCleanup(self.github.stop)
|
||||
# Linux CI runs unprivileged; real chown is a host deployment check.
|
||||
self.chown = patch.object(updater.os, "chown", create=True)
|
||||
self.chown.start()
|
||||
self.addCleanup(self.chown.stop)
|
||||
self.environment = patch.dict(os.environ, {"RANCH_WEB_UPDATER_DIR": str(self.config.control_dir)})
|
||||
self.environment.start()
|
||||
self.addCleanup(self.environment.stop)
|
||||
|
||||
def samples(self, directory=None):
|
||||
with closing(sqlite3.connect((directory or self.config.data_dir) / "samples.sqlite3")) as connection:
|
||||
return connection.execute("select n from samples order by n").fetchall()
|
||||
|
||||
def enable(self):
|
||||
self.config = replace(self.config, accept_web_requests=True)
|
||||
self.host = updater.HostUpdater(self.config, self.docker)
|
||||
return self.host.capability()
|
||||
|
||||
def request(self, capability, **overrides):
|
||||
value = {"protocol": 1, "request_id": "c" * 32, "executor_id": capability["executor_id"],
|
||||
"version": "v2.0.0", "requested_at": updates.timestamp(), **overrides}
|
||||
updates.atomic_json(self.config.data_dir / "update-request.json", value)
|
||||
return value
|
||||
|
||||
def test_pull_failure_does_not_stop_or_backup(self):
|
||||
self.docker.fail_pull = True
|
||||
with self.assertRaises(updater.UpdaterError):
|
||||
self.host.apply()
|
||||
self.assertTrue(self.docker.running)
|
||||
self.assertNotIn("stop", [event[0] for event in self.docker.events])
|
||||
self.assertFalse(self.config.backup_dir.exists())
|
||||
self.assertFalse(self.host.journal.exists())
|
||||
|
||||
def test_update_stops_before_snapshot_and_persists_image_only_after_health(self):
|
||||
original_snapshot = updater.snapshot_data
|
||||
def snapshot(config, identity):
|
||||
self.assertFalse(self.docker.running)
|
||||
self.docker.events.append(("snapshot", None))
|
||||
return original_snapshot(config, identity)
|
||||
with patch.object(updater, "snapshot_data", side_effect=snapshot):
|
||||
result = self.host.apply()
|
||||
self.assertEqual(result["status"], "succeeded")
|
||||
self.assertEqual([event[0] for event in self.docker.events], ["validate", "pull", "stop", "snapshot", "up"])
|
||||
self.assertEqual((self.root / ".image.env").read_text(), f"RANCH_WEB_IMAGE={updates.IMAGE}:v2.0.0\n")
|
||||
self.assertFalse(self.host.journal.exists())
|
||||
self.assertEqual(len(list(self.config.backup_dir.glob("*.tar.gz"))), 1)
|
||||
|
||||
def test_health_failure_restores_sqlite_key_and_keeps_failed_data(self):
|
||||
self.docker.fail_start = True
|
||||
result = self.host.apply(request_id="d" * 32)
|
||||
self.assertEqual(result["status"], "rolled_back")
|
||||
self.assertTrue(self.docker.running)
|
||||
self.assertEqual(self.docker.image, self.docker.old_image)
|
||||
self.assertEqual(self.samples(), [(1,)])
|
||||
self.assertEqual((self.config.data_dir / "key.bin").read_bytes(), b"original-encrypted-test-key")
|
||||
failed = self.config.failed_data_dir / ("d" * 32)
|
||||
self.assertEqual(self.samples(failed), [(1,), (2,)])
|
||||
self.assertEqual((failed / "key.bin").read_bytes(), b"changed-key")
|
||||
self.assertIn(self.docker.old_image, (self.root / ".image.env").read_text())
|
||||
|
||||
def test_restart_and_snapshot_restore_preserve_preferences_but_never_start_strategies(self):
|
||||
from ranch_web.service import WebManager
|
||||
def complete(manager, account_id, job):
|
||||
until = time.monotonic() + 5
|
||||
while time.monotonic() < until:
|
||||
result = manager.job(account_id, job["id"])
|
||||
if result["status"] in {"succeeded", "failed", "cancelled"}:
|
||||
self.assertEqual(result["status"], "succeeded", result.get("error"))
|
||||
return
|
||||
time.sleep(0.01)
|
||||
self.fail("offline worker did not finish")
|
||||
with patch("socket.socket.connect", side_effect=AssertionError("Network forbidden in deployment restart test")):
|
||||
manager = WebManager(self.config.data_dir, start_scheduler=False)
|
||||
try:
|
||||
account_id = manager.create_account(demo=True)["id"]
|
||||
config = manager.get_config(account_id)["config"]
|
||||
config["daily_policy"]["enabled"] = True
|
||||
pending = manager.set_config(account_id, config)
|
||||
complete(manager, account_id, pending["job"])
|
||||
complete(manager, account_id, manager.submit(account_id, "start"))
|
||||
self.assertTrue(manager.status(account_id)["running"])
|
||||
finally:
|
||||
manager.close()
|
||||
key = (self.config.data_dir / "web.key").read_bytes()
|
||||
identity = "f" * 32
|
||||
backup = updater.snapshot_data(self.config, identity)
|
||||
for restore in (False, True):
|
||||
if restore:
|
||||
updater.restore_data(self.config, backup, identity)
|
||||
restarted = WebManager(self.config.data_dir, start_scheduler=False)
|
||||
try:
|
||||
self.assertFalse(restarted.status(account_id)["running"])
|
||||
self.assertTrue(restarted.get_config(account_id)["config"]["daily_policy"]["enabled"])
|
||||
self.assertEqual((self.config.data_dir / "web.key").read_bytes(), key)
|
||||
finally:
|
||||
restarted.close()
|
||||
|
||||
def test_backup_failure_resumes_pinned_old_image_without_new_image(self):
|
||||
with patch.object(updater, "snapshot_data", side_effect=OSError("fake disk full")):
|
||||
result = self.host.apply()
|
||||
self.assertEqual(result["status"], "rolled_back")
|
||||
starts = [image for event, image in self.docker.events if event == "up"]
|
||||
self.assertEqual(starts, [self.docker.old_image])
|
||||
self.assertEqual(self.samples(), [(1,)])
|
||||
|
||||
def test_failed_rollback_retains_journal_and_backup(self):
|
||||
self.docker.fail_start = self.docker.fail_rollback = True
|
||||
with self.assertRaises(updater.UpdaterError):
|
||||
self.host.apply()
|
||||
self.assertTrue(self.host.journal.exists())
|
||||
self.assertEqual(updates.read_json(self.config.data_dir / "updater-status.json")["status"], "failed")
|
||||
self.assertTrue(list(self.config.backup_dir.glob("*.tar.gz")))
|
||||
|
||||
def test_recovery_can_retry_old_start_after_data_was_already_restored(self):
|
||||
self.docker.fail_start = self.docker.fail_rollback = True
|
||||
with self.assertRaises(updater.UpdaterError):
|
||||
self.host.apply()
|
||||
self.docker.fail_rollback = False
|
||||
result = self.host.recover()
|
||||
self.assertEqual(result["status"], "rolled_back")
|
||||
self.assertEqual(self.samples(), [(1,)])
|
||||
self.assertFalse(self.host.journal.exists())
|
||||
|
||||
def test_interrupted_transaction_recovery_resumes_old_service(self):
|
||||
identity = "e" * 32
|
||||
self.docker.stop()
|
||||
updater.snapshot_data(self.config, identity)
|
||||
self.docker.up(f"{updates.IMAGE}:v2.0.0")
|
||||
updates.atomic_json(self.host.journal, {"request_id": identity, "version": "v2.0.0",
|
||||
"old_image": self.docker.old_image, "backup_ready": True, "new_started": True})
|
||||
result = self.host.recover()
|
||||
self.assertEqual(result["status"], "rolled_back")
|
||||
self.assertEqual(self.samples(), [(1,)])
|
||||
self.assertFalse(self.host.journal.exists())
|
||||
|
||||
def test_only_old_desktop_release_leaves_service_untouched(self):
|
||||
self.releases.return_value = [release("v1.2.0"), release("v3.0.0")]
|
||||
result = self.host.apply()
|
||||
self.assertEqual(result["status"], "no_release")
|
||||
self.assertEqual(self.docker.events, [])
|
||||
|
||||
def test_same_stable_version_or_downgrade_never_pulls(self):
|
||||
for current in ("2.0.0", "2.1.0"):
|
||||
with self.subTest(current=current):
|
||||
self.docker.version = current
|
||||
with self.assertRaises(updater.UpdaterError):
|
||||
self.host.apply("v2.0.0")
|
||||
self.assertEqual(self.docker.events, [])
|
||||
|
||||
def test_host_independently_rejects_not_official_request_tag(self):
|
||||
capability = self.enable()
|
||||
self.request(capability, version="v2.99.99")
|
||||
self.releases.return_value = [release("v2.0.0")]
|
||||
result = self.host.run()
|
||||
self.assertEqual(result["status"], "failed")
|
||||
self.assertTrue(self.docker.running)
|
||||
self.assertEqual(self.docker.events, [])
|
||||
self.releases.assert_called_once()
|
||||
|
||||
def test_web_request_requires_operator_opt_in(self):
|
||||
capability = self.host.capability()
|
||||
self.assertFalse(capability["enabled"])
|
||||
self.request(capability)
|
||||
self.host.run()
|
||||
self.assertTrue(self.docker.running)
|
||||
self.assertEqual(self.docker.events, [])
|
||||
|
||||
def test_web_request_success_and_replay_deduplication(self):
|
||||
capability = self.enable()
|
||||
request = self.request(capability)
|
||||
result = self.host.run()
|
||||
self.assertEqual(result["status"], "succeeded")
|
||||
self.assertEqual(result["request_id"], request["request_id"])
|
||||
events = list(self.docker.events)
|
||||
self.host.run()
|
||||
self.assertEqual(events, self.docker.events)
|
||||
|
||||
def test_stale_other_executor_and_injected_command_are_rejected(self):
|
||||
capability = self.enable()
|
||||
variants = [dict(executor_id="a" * 32), dict(command="rm anything"),
|
||||
dict(requested_at=updates.timestamp(updates.utc_now() - timedelta(days=2))),
|
||||
dict(requested_at=updates.timestamp(updates.utc_now() + timedelta(hours=1)))]
|
||||
for index, variant in enumerate(variants):
|
||||
with self.subTest(variant=variant):
|
||||
self.request(capability, request_id=f"{index:032x}", **variant)
|
||||
self.assertEqual(self.host.run()["status"], "failed")
|
||||
self.assertEqual(self.docker.events, [])
|
||||
self.releases.assert_not_called()
|
||||
|
||||
def test_auto_apply_is_explicit_opt_in(self):
|
||||
result = self.host.run()
|
||||
self.assertTrue(result["available"])
|
||||
self.assertEqual(self.docker.events, [])
|
||||
config = replace(self.config, auto_apply=True)
|
||||
result = updater.HostUpdater(config, self.docker).run()
|
||||
self.assertEqual(result["status"], "succeeded")
|
||||
|
||||
def test_malformed_request_fails_without_network_or_docker(self):
|
||||
self.enable()
|
||||
updates.atomic_json(self.config.data_dir / "update-request.json", ["invalid"])
|
||||
self.assertEqual(self.host.run()["status"], "failed")
|
||||
self.assertEqual(self.docker.events, [])
|
||||
self.releases.assert_not_called()
|
||||
|
||||
def test_dry_run_is_read_only_and_network_free(self):
|
||||
document = self.root / "updater.toml"
|
||||
text = "\n".join(f"{key} = {json.dumps(str(getattr(self.config, key)))}" for key in (
|
||||
"project_dir", "data_dir", "control_dir", "backup_dir", "failed_data_dir"))
|
||||
document.write_text(text, encoding="utf-8")
|
||||
before = sorted(str(item.relative_to(self.root)) for item in self.root.rglob("*"))
|
||||
with patch.object(updater.Docker, "run", side_effect=AssertionError("Docker not allowed")), redirect_stdout(io.StringIO()) as output:
|
||||
code = updater.main(["--config", str(document), "--apply", "v2.1.0", "--dry-run"])
|
||||
self.assertEqual(code, 0)
|
||||
self.assertTrue(json.loads(output.getvalue())["dry_run"])
|
||||
self.assertEqual(before, sorted(str(item.relative_to(self.root)) for item in self.root.rglob("*")))
|
||||
self.releases.assert_not_called()
|
||||
|
||||
def test_shipped_linux_config_supports_windows_dry_run(self):
|
||||
source = Path(updater.__file__).with_name("updater.example.toml")
|
||||
with patch.object(updater.Docker, "run", side_effect=AssertionError("Docker not allowed")), redirect_stdout(io.StringIO()) as output:
|
||||
code = updater.main(["--config", str(source), "--apply", "v2.0.0", "--dry-run"])
|
||||
self.assertEqual(code, 0)
|
||||
self.assertTrue(json.loads(output.getvalue())["dry_run"])
|
||||
self.releases.assert_not_called()
|
||||
|
||||
def test_config_rejects_unknown_fields_and_nested_control_paths(self):
|
||||
document = self.root / "bad.toml"
|
||||
for text in ("download_url = 'https://evil.invalid'", f"control_dir = {json.dumps(str(self.config.data_dir / 'control'))}\ndata_dir = {json.dumps(str(self.config.data_dir))}"):
|
||||
document.write_text(text, encoding="utf-8")
|
||||
with self.assertRaises(updater.UpdaterError):
|
||||
updater.Config.load(document)
|
||||
|
||||
def test_real_docker_runner_uses_arguments_not_shell_and_never_echoes_output(self):
|
||||
docker = updater.Docker(self.config)
|
||||
with patch.object(updater.subprocess, "run") as run:
|
||||
run.return_value.returncode = 1
|
||||
run.return_value.stdout = "password=secret"
|
||||
run.return_value.stderr = "token=secret"
|
||||
with self.assertRaises(updater.UpdaterError) as error:
|
||||
docker.pull(f"{updates.IMAGE}:v2.0.0")
|
||||
args, kwargs = run.call_args
|
||||
self.assertIsInstance(args[0], list)
|
||||
self.assertNotIn("shell", kwargs)
|
||||
self.assertIn("pull", args[0])
|
||||
self.assertNotIn("secret", str(error.exception))
|
||||
|
||||
def test_healthy_container_with_dev_label_is_not_a_completed_stable_update(self):
|
||||
docker = updater.Docker(self.config)
|
||||
target = f"{updates.IMAGE}:v2.0.0"
|
||||
with patch.object(docker, "compose"), patch.object(docker, "inspect_service") as inspect:
|
||||
inspect.return_value = {"running": True, "health": "healthy", "version": "2.0.0.dev1"}
|
||||
with self.assertRaises(updater.UpdaterError):
|
||||
docker.up(target)
|
||||
inspect.return_value = {"running": True, "health": "unhealthy", "version": "2.0.0"}
|
||||
with self.assertRaises(updater.UpdaterError):
|
||||
docker.up(target)
|
||||
inspect.return_value = {"running": True, "health": "healthy", "version": "2.0.0"}
|
||||
docker.up(target)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,398 @@
|
||||
"""Parity checks with disposable offline Engines, fake transports and evidence."""
|
||||
from copy import deepcopy
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from ranch_assistant.engine import Engine, demo_snapshot
|
||||
from ranch_assistant.exploration import ExplorePlanner
|
||||
from ranch_assistant.maps import Stage
|
||||
from ranch_assistant.model import Catalog
|
||||
from ranch_web.actions import execute_action
|
||||
from ranch_web.policies import apply_config, default_config, export_config
|
||||
from ranch_web.views import build_view, PAGES, schema
|
||||
|
||||
|
||||
class OfflineWorker:
|
||||
def __init__(self, folder):
|
||||
self.profile_root = Path(folder)
|
||||
self.engine = Engine(Catalog(), budget_path=self.profile_root / "budget.json")
|
||||
self.engine.snapshot = demo_snapshot(self.engine.catalog)
|
||||
self.config = apply_config(self.engine, default_config())
|
||||
self.running, self.revision = False, 1
|
||||
self.messages = []
|
||||
self.trace = SimpleNamespace(path=self.profile_root / "network_debug.jsonl")
|
||||
|
||||
def stop(self):
|
||||
self.running = self.engine.auto = False
|
||||
|
||||
def result(self, snapshot, plans, message):
|
||||
self.engine.snapshot = snapshot
|
||||
self.messages.append(message)
|
||||
|
||||
def save_config(self, config):
|
||||
self.config = apply_config(self.engine, config)
|
||||
self.revision += 1
|
||||
return {"config": deepcopy(self.config), "revision": self.revision}
|
||||
|
||||
|
||||
class WebViewActionTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(prefix="ranch-web-parity-test-")
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.worker = OfflineWorker(self.temp.name)
|
||||
self.engine = self.worker.engine
|
||||
|
||||
def view(self, page, query=None):
|
||||
return build_view(self.engine, page, self.worker.config, query)
|
||||
|
||||
def action(self, operation, **payload):
|
||||
return execute_action(self.worker, operation, payload)
|
||||
|
||||
def test_all_pages_are_public_json_without_qt_imports_or_network(self):
|
||||
self.engine.client = SimpleNamespace(call=Mock(side_effect=AssertionError("offline-only")))
|
||||
self.engine.demo = False
|
||||
for page, title in PAGES:
|
||||
with self.subTest(page=page):
|
||||
dto = self.view(page)
|
||||
self.assertEqual(dto["title"], title)
|
||||
json.dumps(dto, ensure_ascii=False, allow_nan=False)
|
||||
self.assertNotIn('"raw"', json.dumps(dto))
|
||||
self.engine.client.call.assert_not_called()
|
||||
script = """import sys, importlib.abc
|
||||
class BlockGUI(importlib.abc.MetaPathFinder):
|
||||
def find_spec(self,fullname,path=None,target=None):
|
||||
if fullname.startswith('PySide6') or fullname.endswith('_gui') or fullname == 'ranch_assistant.gui':
|
||||
raise AssertionError(fullname)
|
||||
sys.meta_path.insert(0,BlockGUI())
|
||||
import ranch_web.policies,ranch_web.views,ranch_web.actions
|
||||
"""
|
||||
result = subprocess.run([sys.executable, "-c", script], cwd=Path(__file__).resolve().parents[2], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_schema_exposes_only_current_gui_fields_and_chinese_labels(self):
|
||||
value = schema(self.engine.catalog)
|
||||
fields = [field for page in value["pages"] for field in page["form"]]
|
||||
self.assertTrue(all(field["label"] and isinstance(field["path"], list) for field in fields))
|
||||
self.assertNotIn(["policy", "feed_target"], [field["path"] for field in fields])
|
||||
self.assertNotIn(["progression_policy", "battle_mode"], [field["path"] for field in fields])
|
||||
self.assertEqual(dict(PAGES)["statistics"], "数据分析")
|
||||
self.assertEqual(dict(PAGES)["plans"], "执行计划")
|
||||
self.assertEqual(len(self.view("yields")["rows"]), 749)
|
||||
self.assertEqual([tab["title"] for tab in self.view("hatching")["tabs"]], ["孵蛋策略", "牧场策略", "喂养策略"])
|
||||
|
||||
def test_incubator_includes_closed_slots_and_vip_never_expandable(self):
|
||||
dto = self.view("incubator")
|
||||
self.assertEqual(len(dto["rows"]), 11)
|
||||
self.assertFalse(dto["rows"][3]["can_expand"])
|
||||
self.assertTrue(dto["rows"][6]["can_expand"])
|
||||
self.assertEqual(dto["rows"][0]["monster_id"], 101)
|
||||
|
||||
def test_bag_uses_real_category_and_groups_inventory_ids(self):
|
||||
catalog = self.engine.catalog
|
||||
categories = {"usable": 1, "consumables": 2, "materials": 3, "other": 4, "equipment": 5}
|
||||
items = []
|
||||
for category, code in categories.items():
|
||||
key = next(key for key in catalog.data["item_info"] if catalog.item_type(key) == code)
|
||||
items += [{"id": len(items) + 10000, "typeId": key, "num": number} for number in (3, 4)]
|
||||
self.engine.snapshot.raw["items"] += items
|
||||
for category, code in categories.items():
|
||||
with self.subTest(category=category):
|
||||
dto = self.view("bag", {"category": category})
|
||||
self.assertTrue(dto["rows"])
|
||||
self.assertTrue(all(catalog.item_type(row["id"]) == code for row in dto["rows"]))
|
||||
row = next(row for row in dto["rows"] if len(row["inventory_ids"]) == 2)
|
||||
self.assertEqual(row["count"], 7)
|
||||
self.assertEqual(row["rule_path"], ["policy", "gift_items", row["id"]])
|
||||
if code == 5:
|
||||
self.assertTrue(row["edits"]["enabled"]["disabled"])
|
||||
|
||||
def test_egg_keep_count_and_missing_stock_rule_bind_real_config(self):
|
||||
config = deepcopy(self.worker.config)
|
||||
config["policy"]["egg_rules"]["1001010"] = {"enabled": True, "keep_count": 5, "priority": 1, "market_id": "sc_city1"}
|
||||
self.worker.save_config(config)
|
||||
dto = self.view("bag", {"category": "eggs"})
|
||||
row = next(row for row in dto["rows"] if row["id"] == "1001010")
|
||||
column = next(column for column in dto["columns"] if column["key"] == "keep_count")
|
||||
self.assertEqual(column["label"], "牧场保留")
|
||||
self.assertEqual(row["keep_count"], 5)
|
||||
self.assertEqual(column["edit"]["path"], ["policy", "egg_rules", "{id}", "keep_count"])
|
||||
self.assertTrue(row["edits"]["market_id"]["options"])
|
||||
|
||||
def test_add_rule_species_defaults_follow_current_market_and_desktop_fallback(self):
|
||||
catalog = self.engine.catalog
|
||||
self.engine.snapshot.raw["items"] = []
|
||||
config = deepcopy(self.worker.config)
|
||||
config["policy"]["market_id"] = "sc_city10"
|
||||
self.worker.save_config(config)
|
||||
dto = self.view("bag", {"category": "eggs"})
|
||||
field = next(field for field in dto["form"] if field["type"] == "add_rule")
|
||||
defaults = field["defaults_by_id"]
|
||||
self.assertEqual(set(defaults), set(catalog.monsters))
|
||||
self.assertEqual(dto["rows"], [])
|
||||
self.assertEqual(defaults["1001010"]["market_id"], "sc_city10")
|
||||
fallback = next(key for key in catalog.monsters if catalog.markets_for(key) and "sc_city10" not in catalog.markets_for(key))
|
||||
self.assertEqual(defaults[fallback]["market_id"], catalog.markets_for(fallback)[0])
|
||||
unavailable = next(key for key in catalog.monsters if not catalog.markets_for(key))
|
||||
self.assertEqual(defaults[unavailable]["market_id"], "")
|
||||
config = deepcopy(self.worker.config)
|
||||
for key in ("1001010", fallback, unavailable):
|
||||
config["policy"]["egg_rules"][key] = deepcopy(defaults[key])
|
||||
self.worker.save_config(config)
|
||||
rows = {row["id"]: row for row in self.view("bag", {"category": "eggs"})["rows"]}
|
||||
for key in ("1001010", fallback, unavailable):
|
||||
with self.subTest(species=key):
|
||||
self.assertEqual(rows[key]["market_id"], defaults[key]["market_id"])
|
||||
self.assertEqual(rows[key]["rule_defaults"], defaults[key])
|
||||
self.assertFalse(rows[key]["enabled"])
|
||||
self.assertEqual(self.engine.policy.egg_rules[key], defaults[key])
|
||||
self.assertFalse(self.engine.auto)
|
||||
|
||||
def test_status_fields_expose_core_feed_draw_and_gift_timing(self):
|
||||
snapshot, catalog = self.engine.snapshot, self.engine.catalog
|
||||
config = deepcopy(self.worker.config)
|
||||
config["policy"]["feed_targets"] = {"900": 1}
|
||||
self.engine.last_draw = "offline draw: 3 eggs"
|
||||
self.worker.save_config(config)
|
||||
details = self.view("hatching")["details"]
|
||||
self.assertEqual(details["feed_status"], self.engine.planner.feed_status(snapshot, self.engine.policy))
|
||||
self.assertTrue(details["feed_status"][0])
|
||||
self.assertIsInstance(details["feed_status"][1], str)
|
||||
self.assertEqual(details["last_draw"], "offline draw: 3 eggs")
|
||||
self.assertIsNone(self.view("gifts")["details"]["next_ready_at"])
|
||||
likes = catalog.monster(snapshot.monsters[900]["typeId"]).get("like") or {}
|
||||
gift_id = next(str(key) for key, feel in likes.items() if feel > 0 and catalog.item_type(key) not in (5, 6) and catalog.item(key).get("sellable"))
|
||||
gifted_at = snapshot.now
|
||||
snapshot.monsters[900]["giftTime"] = gifted_at * 1000
|
||||
snapshot.raw["items"].append({"id": 8000, "typeId": int(gift_id), "num": 2})
|
||||
config["policy"].update(gift_enabled=True, gift_targets={"900": 1}, gift_items={gift_id: {"enabled": True, "reserve": 0}})
|
||||
self.worker.save_config(config)
|
||||
deadline = self.view("gifts")["details"]["next_ready_at"]
|
||||
self.assertEqual(deadline, gifted_at + int(catalog.data["game_setting"].get("monGiftTime", 7200)))
|
||||
|
||||
def test_ranch_targets_are_real_priorities_and_details_are_whitelisted(self):
|
||||
config = deepcopy(self.worker.config)
|
||||
for field, priority in (("feed_targets", 1), ("gift_targets", 2), ("breakthrough_targets", 3)):
|
||||
config["policy"][field] = {"900": priority}
|
||||
self.worker.save_config(config)
|
||||
self.engine.snapshot.monsters[900].update(password="synthetic-secret", raw={"token": "synthetic-secret"})
|
||||
dto = self.view("ranch", {"grouped": True})
|
||||
row = next(row for row in dto["rows"] if row["id"] == "900")
|
||||
self.assertTrue(row["feed_selected"])
|
||||
self.assertEqual(row["feed_priority"], 1)
|
||||
self.assertEqual(row["edits"]["feed_selected"]["path"], ["policy", "feed_targets", "900"])
|
||||
self.assertEqual(row["edits"]["feed_selected"]["type"], "target")
|
||||
self.assertEqual(self.engine.planner.feeding_target(self.engine.snapshot, self.engine.policy)[0]["id"], 900)
|
||||
self.assertTrue(dto["groups"])
|
||||
self.assertTrue(dto["feed_targets"])
|
||||
self.assertNotIn("synthetic-secret", json.dumps(dto))
|
||||
|
||||
def test_mainline_default_current_and_filters_with_chinese_record_messages(self):
|
||||
self.engine._progression_rows = [
|
||||
{"task_type_id": "a", "category": "main", "state": "active", "name": "当前主线", "dialogue": "对话", "supported": True},
|
||||
{"task_type_id": "b", "category": "mainline", "state": "completed", "name": "历史主线"},
|
||||
{"task_type_id": "c", "category": "sidequest", "state": "received", "name": "支线"}]
|
||||
self.assertEqual([row["name"] for row in self.view("mainline")["rows"]], ["当前主线"])
|
||||
dto = self.view("mainline", {"category": "", "state": "", "search": "历史"})
|
||||
self.assertEqual(dto["rows"][0]["state_label"], "已完成")
|
||||
self.engine._progression_records = [{"battle_kind": "ordinary_stage", "outcome": "loss", "started_at": 0,
|
||||
"battle_mode": "experimental", "damage_profile": "client_v4_x10", "message": "Unsupported monster controller: test", "response": {"token": "synthetic-secret"}}]
|
||||
record = self.view("battles")
|
||||
self.assertIn("打不过", record["rows"][0]["outcome_label"])
|
||||
self.assertIn("尚未支持", record["rows"][0]["message"])
|
||||
self.assertNotIn("synthetic-secret", json.dumps(record))
|
||||
|
||||
def test_exploration_three_members_options_and_diagnoses_use_planner(self):
|
||||
snapshot = self.engine.snapshot
|
||||
snapshot.raw["history"].update(passTask={"1001008": True}, passStage={"0101": {"1": True}})
|
||||
snapshot.raw["exploreTeams"] = [{"id": 1, "status": 0}]
|
||||
for mid, level in ((101, 30), (102, 10), (900, 20)):
|
||||
snapshot.monsters[mid].update(process=3, level=level, mode=2)
|
||||
self.engine.explore_planner = ExplorePlanner(self.engine.catalog, areas={"1": {"id": "1", "name": "测试地区", "passStage": "0101", "costTi": 10, "costTime": 3600, "level": [4, 1, 1], "team": "normal"}})
|
||||
config = deepcopy(self.worker.config)
|
||||
config["explore_policy"] = {"enabled": True, "reserve_ti": 2, "teams": {"1": {"enabled": True, "area": "1", "monsters": [101, 900, 102]}}}
|
||||
self.worker.save_config(config)
|
||||
dto = self.view("exploration")
|
||||
row = dto["rows"][0]
|
||||
self.assertEqual(row["monsters"], [101, 900, 102])
|
||||
self.assertEqual(row["state"], "可出发")
|
||||
self.assertEqual(row["edits"]["monsters"]["path"], ["explore_policy", "teams", "1", "monsters"])
|
||||
protected = next(option for option in row["member_options"] if option["value"] == 900)
|
||||
self.assertFalse(protected["automatic"])
|
||||
self.assertFalse(protected["disabled"])
|
||||
|
||||
def test_maps_resources_show_ticket_cost_and_filter_difficulty_one(self):
|
||||
snapshot = self.engine.snapshot
|
||||
snapshot.raw["items"] += [{"id": 7000, "typeId": 20009, "num": 5}, {"id": 7001, "typeId": 20009, "num": 100, "lock": True}]
|
||||
stages = [Stage("m101", str(level), "测试矿洞", 1, True, False, True, 10, "矿镐×2", city_name="测试地区", category="mine", battle_available=True) for level in (1, 2)]
|
||||
self.engine.stage_cache.get = Mock(return_value=stages)
|
||||
self.engine.stage_cache.catalog.data["stage_info"]["m101"] = {"cost": {"items": [{"typeId": 20009, "num": 2}]}}
|
||||
self.engine.map_stage_reason = Mock(return_value="")
|
||||
dto = self.view("maps", {"category": "resource"})
|
||||
self.assertEqual(len(dto["rows"]), 1)
|
||||
row = dto["rows"][0]
|
||||
self.assertEqual(row["level"], "1")
|
||||
self.assertEqual(row["costs"][1]["available"], 5)
|
||||
self.assertEqual(row["costs"][1]["required"], 2)
|
||||
self.assertIn("资源关开关", row["status"])
|
||||
self.assertTrue(dto["groups"][0]["collapsed"])
|
||||
self.assertEqual([option["value"] for option in row["edits"]["level"]["options"]], ["1"])
|
||||
|
||||
def test_statistics_all_event_and_known_stamina_follow_real_store(self):
|
||||
store = self.engine.sweeper.statistics
|
||||
owner = self.engine.snapshot.raw["master"]["id"]
|
||||
for index, kind, amount, spent in ((1, "sweep", 2, 10), (2, "event", 3, 20), (3, "event", 7, None)):
|
||||
store.record(owner, "0101", "3", kind, f"offline:{index}", index, {"money": 10, "items": [{"typeId": 30005, "num": amount}]}, spent)
|
||||
dto = self.view("statistics", {"stage_id": "0101", "level": "3", "source": "all"})
|
||||
row = next(row for row in dto["rows"] if row["typeId"] == "30005")
|
||||
self.assertEqual(dto["totals"]["n"], 3)
|
||||
self.assertEqual(dto["totals"]["spent"], 30)
|
||||
self.assertEqual(row["rate"], 1)
|
||||
self.assertAlmostEqual(row["per_stamina"], 5 / 30)
|
||||
self.assertEqual(next(point for point in dto["chart"]["series"] if point["id"] == row["id"])["value"], 1)
|
||||
self.assertEqual(self.view("statistics", {"stage": "0101", "source": "event"})["totals"]["n"], 2)
|
||||
self.assertEqual(self.view("statistics", {"stage_id": "0101", "source": "sweep"})["totals"]["n"], 1)
|
||||
with self.assertRaises(ValueError):
|
||||
self.view("statistics", {"source": "challenge"})
|
||||
|
||||
def test_lock_sell_feed_are_core_operations_and_require_confirmation(self):
|
||||
self.action("lock", monster_ids=[101])
|
||||
self.assertTrue(self.engine.snapshot.monsters[101]["lock"])
|
||||
self.action("unlock", monster_ids=[101])
|
||||
self.assertFalse(self.engine.snapshot.monsters[101]["lock"])
|
||||
with self.assertRaises(ValueError):
|
||||
self.action("sell", monster_ids=[101])
|
||||
self.action("sell", monster_ids=[101], confirm=True)
|
||||
self.assertNotIn(101, self.engine.snapshot.monsters)
|
||||
self.engine.snapshot.monsters[102].update(process=3, roomId=1, mode=2)
|
||||
self.action("feed", monster_ids=[102], target_id=900, confirm=True)
|
||||
self.assertNotIn(102, self.engine.snapshot.monsters)
|
||||
with self.assertRaises(ValueError):
|
||||
self.action("sell", monster_ids=[900], confirm=True)
|
||||
|
||||
def test_daily_refresh_is_preview_and_manual_selected_claims_use_ledger(self):
|
||||
snapshot = self.engine.snapshot
|
||||
yesterday = snapshot.now - 86400
|
||||
snapshot.raw["activityHistory"] = {"dailyGift": {"dailyGiftCheckTime": yesterday * 1000,
|
||||
"dailyGiftLevel": 1, "dailyGiftCount": 1}, "dailyCheck": {"checkDay": 1, "checkTime": yesterday * 1000}}
|
||||
snapshot.raw["mails"] = [{"id": 12, "title": "离线测试", "createTime": snapshot.now * 1000,
|
||||
"isGetReward": 0, "reward": {"money": 10}}]
|
||||
config = deepcopy(self.worker.config)
|
||||
config["daily_policy"]["selected"] = ["gift", "mail"]
|
||||
self.worker.save_config(config)
|
||||
self.action("refresh", page="daily")
|
||||
self.assertFalse(self.engine.daily_ledger.state)
|
||||
result = self.action("claim_daily")
|
||||
self.assertIn("2 项", result["message"])
|
||||
self.assertTrue(self.engine.daily_ledger.seen(snapshot, "gift"))
|
||||
self.assertFalse(self.engine.daily_ledger.seen(snapshot, "check"))
|
||||
self.assertTrue(self.engine.daily_ledger.seen(snapshot, "mail:12"))
|
||||
self.assertIn("0 项", self.action("claim_daily")["message"])
|
||||
|
||||
def test_commission_rewards_restrictions_and_gift_representatives_are_real(self):
|
||||
snapshot, catalog = self.engine.snapshot, self.engine.catalog
|
||||
key = next(key for key, row in catalog.data["task_info"].items() if row.get("type") == 4 and row.get("steps"))
|
||||
snapshot.raw["currentTasks"] = [{"id": 10000, "typeId": key, "curStep": 999}]
|
||||
dto = self.view("commissions")
|
||||
self.assertEqual(dto["rows"][0]["reward_ke"], catalog.data["task_info"][key]["reward"]["ke"])
|
||||
self.assertEqual(dto["rows"][0]["reason"], "可领取奖励")
|
||||
config = deepcopy(self.worker.config)
|
||||
config["policy"].update(gift_enabled=True, gift_auto_representative=True)
|
||||
self.worker.save_config(config)
|
||||
dto = self.view("gifts")
|
||||
self.assertEqual(dto["rows"][0]["monster_id"], 900)
|
||||
self.assertEqual(dto["rows"][0]["likes"], catalog.likes_text(snapshot.monsters[900]["typeId"]))
|
||||
|
||||
def test_engine_failure_does_not_return_success_or_reuse_paid_quote(self):
|
||||
quote = self.action("quote_expansion", kind="stack", currency="money", position=6)
|
||||
self.engine.expand = Mock(side_effect=TimeoutError("offline unknown response"))
|
||||
with self.assertRaises(TimeoutError):
|
||||
self.action("expand", quote_id=quote["quote_id"], confirm=True)
|
||||
with self.assertRaisesRegex(ValueError, "报价已失效"):
|
||||
self.action("expand", quote_id=quote["quote_id"], confirm=True)
|
||||
self.engine.expand.assert_called_once()
|
||||
|
||||
def test_expansion_quote_is_bound_one_use_and_cost_is_rechecked(self):
|
||||
quote = self.action("quote_expansion", kind="stack", currency="money", position=6)
|
||||
money = self.engine.snapshot.raw["master"]["money"]
|
||||
with self.assertRaises(ValueError):
|
||||
self.action("expand", quote_id=quote["quote_id"])
|
||||
self.action("expand", quote_id=quote["quote_id"], confirm=True)
|
||||
self.assertEqual(self.engine.snapshot.raw["master"]["money"], money - quote["cost"])
|
||||
self.assertTrue(any(row["position"] == 6 for row in self.engine.snapshot.raw["stacks"]))
|
||||
with self.assertRaises(ValueError):
|
||||
self.action("expand", quote_id=quote["quote_id"], confirm=True)
|
||||
quote = self.action("quote_expansion", kind="room", currency="money")
|
||||
record = self.worker._web_expansion_quotes[quote["quote_id"]][1]
|
||||
price = self.engine.catalog.data["room_price"][str(record.index)]
|
||||
price["money"] = int(price["money"]) + 1
|
||||
with self.assertRaisesRegex(ValueError, "费用或次数已变化"):
|
||||
self.action("expand", quote_id=quote["quote_id"], confirm=True)
|
||||
|
||||
def test_import_csv_xlsx_is_transactional_and_never_accepts_disk_paths(self):
|
||||
data = "编号,派遣金币,强化经验,孵化秒数\n1001010,999,18,120\n".encode("utf-8-sig")
|
||||
result = self.action("import_yields", filename="data.csv", content_base64=base64.b64encode(data).decode())
|
||||
self.assertEqual(result["count"], 1)
|
||||
self.assertEqual(self.engine.catalog.monster(1001010)["sell_money"], 999)
|
||||
old = deepcopy(self.worker.config)
|
||||
data = b"typeId,sell_money\n1001010,nan\n"
|
||||
with self.assertRaises(ValueError):
|
||||
self.action("import_yields", filename="data.csv", content_base64=base64.b64encode(data).decode())
|
||||
self.assertEqual(self.worker.config, old)
|
||||
with self.assertRaises(ValueError):
|
||||
self.action("import_yields", path="private-file.csv")
|
||||
import openpyxl
|
||||
workbook = openpyxl.Workbook()
|
||||
workbook.active.append(["typeId", "sell_money"])
|
||||
workbook.active.append([1001010, 123])
|
||||
stream = io.BytesIO()
|
||||
workbook.save(stream)
|
||||
workbook.close()
|
||||
result = self.action("import_yields", filename="data.xlsx", content_base64=base64.b64encode(stream.getvalue()).decode())
|
||||
self.assertEqual(result["overrides"]["1001010"]["sell_money"], 123)
|
||||
|
||||
def test_import_only_saves_and_never_executes_a_plan(self):
|
||||
self.worker.running = self.engine.auto = True
|
||||
document = export_config(self.worker.config, self.engine.snapshot)
|
||||
self.engine.poll = Mock(side_effect=AssertionError("import must not run"))
|
||||
result = self.action("import_config", config=document)
|
||||
self.assertIn("config", result)
|
||||
self.assertFalse(self.engine.auto)
|
||||
self.assertFalse(self.worker.running)
|
||||
self.engine.poll.assert_not_called()
|
||||
|
||||
def test_reset_pending_requires_real_role_matched_evidence_and_keeps_journal(self):
|
||||
pending = {"stage": "0101", "level": "3", "phase": "遇到事件或响应缺少事件状态,请在游戏内处理"}
|
||||
self.engine.sweeper.state["pending"] = pending
|
||||
with self.assertRaises(ValueError):
|
||||
self.action("reset_map_pending", confirm=True, server_verified=True)
|
||||
self.assertIs(self.engine.sweeper.state["pending"], pending)
|
||||
trace = [
|
||||
{"operation": "读取角色", "kind": "response", "body": {"master": {"id": 2}}},
|
||||
{"operation": "stageService/stageStart", "kind": "request", "request_id": "offline:1", "body": {"stageTypeId": "0101", "stageLevel": "3"}},
|
||||
{"operation": "stageService/stageStart", "kind": "response", "request_id": "offline:1", "http_status": 200,
|
||||
"body": {"resCode": 0, "triggerEvent": True, "stageEvent": {"resCode": 0, "result": {"money": 10}}}},
|
||||
]
|
||||
self.worker.trace.path.write_text("\n".join(json.dumps(event) for event in trace), encoding="utf-8")
|
||||
with self.assertRaises(ValueError):
|
||||
self.action("reset_map_pending", confirm=True, server_verified=True)
|
||||
trace[0]["body"]["master"]["id"] = 1
|
||||
self.worker.trace.path.write_text("\n".join(json.dumps(event) for event in trace), encoding="utf-8")
|
||||
result = self.action("reset_map_pending", confirm=True)
|
||||
self.assertTrue(result["cleared"])
|
||||
self.engine.sweeper.state["pending"] = pending
|
||||
self.engine.battle_journal.pending = Mock(return_value={"kind": "map_battle", "phase": "unknown"})
|
||||
with self.assertRaisesRegex(ValueError, "不能手动清除"):
|
||||
self.action("reset_map_pending", confirm=True, server_verified=True)
|
||||
self.assertIs(self.engine.sweeper.state["pending"], pending)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,317 @@
|
||||
"""Official stable Web 2 releases and a file-only host updater handshake.
|
||||
|
||||
This module is also used by the Linux host, so it imports no application, Qt,
|
||||
HTTP framework, or third-party library. It never executes an update itself.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import tempfile
|
||||
import threading
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
import uuid
|
||||
|
||||
REPOSITORY = "attilanet/myrzx_bot"
|
||||
IMAGE = "ghcr.io/attilanet/myrzx_bot-web"
|
||||
RELEASES_API = f"https://api.github.com/repos/{REPOSITORY}/releases"
|
||||
PROTOCOL = 1
|
||||
_TAG = re.compile(r"v2\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})", re.ASCII)
|
||||
_CURRENT = re.compile(r"v?2\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})(\.dev[0-9]+)?", re.ASCII)
|
||||
_ID = re.compile(r"[0-9a-f]{32}", re.ASCII)
|
||||
HOST_STATES = frozenset({"pending", "applying", "succeeded", "rolled_back", "failed"})
|
||||
_MESSAGES = {
|
||||
"unchecked": "尚未检查官方 Web 2 正式版本。",
|
||||
"no_release": "官方尚无稳定 Web 2 正式版;不会安装旧版桌面程序。",
|
||||
"up_to_date": "当前已是最新稳定 Web 2 版本。",
|
||||
"available": "发现稳定 Web 2 更新。",
|
||||
"check_failed": "GitHub 发布检查失败,请稍后重试。",
|
||||
"unavailable": "未启用有效的 Linux 宿主机执行器;当前仅可检查更新。",
|
||||
"pending": "更新请求已提交,等待宿主机处理。",
|
||||
"applying": "宿主机正在备份、更新并检查服务健康。",
|
||||
"succeeded": "宿主机已确认更新后服务健康。",
|
||||
"rolled_back": "更新未通过健康检查,宿主机已恢复旧镜像及更新前数据。",
|
||||
"failed": "宿主机更新失败,请操作者检查部署状态。",
|
||||
}
|
||||
|
||||
|
||||
def utc_now():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def timestamp(value=None):
|
||||
return (value or utc_now()).isoformat(timespec="seconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def parse_time(value):
|
||||
if not isinstance(value, str) or len(value) > 40:
|
||||
return None
|
||||
try:
|
||||
result = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return None
|
||||
return result.astimezone(timezone.utc) if result.tzinfo is not None else None
|
||||
|
||||
|
||||
def stable_version(tag):
|
||||
"""Accept only canonical official image tags in the stable 2.x channel."""
|
||||
match = _TAG.fullmatch(tag) if isinstance(tag, str) else None
|
||||
if match is None:
|
||||
raise ValueError("更新版本必须是稳定的 v2.x.y,且数字不含前导零。")
|
||||
return 2, int(match[1]), int(match[2]), 1
|
||||
|
||||
|
||||
def current_version_key(version):
|
||||
match = _CURRENT.fullmatch(version) if isinstance(version, str) else None
|
||||
if match is None:
|
||||
raise ValueError("当前 Web 版本必须是 2.x.y 或 2.x.y.devN。")
|
||||
return 2, int(match[1]), int(match[2]), int(match[3] is None)
|
||||
|
||||
|
||||
def validate_image_release(repository, tag, source_version):
|
||||
"""Gate publishing on the official repository and the actual source version."""
|
||||
if not isinstance(repository, str) or repository.lower() != REPOSITORY:
|
||||
raise ValueError("只有官方仓库可发布此镜像。")
|
||||
stable_version(tag)
|
||||
if source_version != tag[1:]:
|
||||
raise ValueError("源码版本必须与稳定发布标签完全一致。")
|
||||
return tag
|
||||
|
||||
|
||||
def valid_id(value):
|
||||
return isinstance(value, str) and _ID.fullmatch(value) is not None
|
||||
|
||||
|
||||
def read_json(path, *, limit=65536):
|
||||
"""Read a small regular control file without following Linux symlinks."""
|
||||
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
|
||||
try:
|
||||
if Path(path).is_symlink():
|
||||
return None
|
||||
descriptor = os.open(path, flags)
|
||||
with os.fdopen(descriptor, "rb") as stream:
|
||||
info = os.fstat(stream.fileno())
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_size > limit:
|
||||
return None
|
||||
payload = stream.read(limit + 1)
|
||||
if len(payload) > limit:
|
||||
return None
|
||||
return json.loads(payload)
|
||||
except (OSError, ValueError, UnicodeError):
|
||||
return None
|
||||
|
||||
|
||||
def atomic_json(path, value, *, mode=0o644):
|
||||
"""Replace a complete control file; never write through a destination link."""
|
||||
path = Path(path)
|
||||
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream:
|
||||
os.chmod(temporary, mode)
|
||||
json.dump(value, stream, ensure_ascii=False, indent=2)
|
||||
stream.write("\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
|
||||
|
||||
class _NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def github_releases():
|
||||
"""Fetch only the fixed public repository. No tokens or asset downloads."""
|
||||
opener = build_opener(_NoRedirect())
|
||||
releases = []
|
||||
for page in range(1, 11):
|
||||
request = Request(f"{RELEASES_API}?per_page=100&page={page}", headers={
|
||||
"Accept": "application/vnd.github+json",
|
||||
"User-Agent": "ranch-web-release-checker/2",
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
})
|
||||
try:
|
||||
with opener.open(request, timeout=8) as response:
|
||||
payload = response.read(2 * 1024 * 1024 + 1)
|
||||
except HTTPError as error:
|
||||
if error.code == 404: # A repository without public releases.
|
||||
return []
|
||||
raise
|
||||
if len(payload) > 2 * 1024 * 1024:
|
||||
raise ValueError("发布列表超出大小限制。")
|
||||
items = json.loads(payload)
|
||||
if not isinstance(items, list) or len(items) > 100:
|
||||
raise ValueError("发布列表格式无效。")
|
||||
releases.extend(items)
|
||||
if len(items) < 100:
|
||||
return releases
|
||||
raise ValueError("发布列表超出页数限制,请稍后重试。")
|
||||
|
||||
|
||||
def official_tags(releases):
|
||||
tags = set()
|
||||
for release in releases:
|
||||
if not isinstance(release, dict):
|
||||
continue
|
||||
if release.get("draft") is not False or release.get("prerelease") is not False:
|
||||
continue
|
||||
tag = release.get("tag_name")
|
||||
try:
|
||||
stable_version(tag)
|
||||
except ValueError:
|
||||
continue
|
||||
tags.add(tag)
|
||||
return tags
|
||||
|
||||
|
||||
class UpdateService:
|
||||
def __init__(self, root, current_version):
|
||||
self.root = Path(root)
|
||||
self.current_version = current_version
|
||||
self._current = current_version_key(current_version)
|
||||
self._lock = threading.RLock()
|
||||
|
||||
def _executor(self):
|
||||
directory = os.environ.get("RANCH_WEB_UPDATER_DIR", "")
|
||||
result = {"configured": False, "enabled": False, "auto_apply": False,
|
||||
"state": "unconfigured", "heartbeat_at": None}
|
||||
if not directory:
|
||||
return result, None
|
||||
value = read_json(Path(directory) / "capability.json")
|
||||
if not isinstance(value, dict) or value.get("protocol") != PROTOCOL:
|
||||
return result, None
|
||||
if not valid_id(value.get("executor_id")):
|
||||
return result, None
|
||||
seen, expiry = parse_time(value.get("heartbeat_at")), parse_time(value.get("expires_at"))
|
||||
if seen is None or expiry is None:
|
||||
return result, None
|
||||
now = utc_now()
|
||||
result.update(configured=True, heartbeat_at=timestamp(seen),
|
||||
auto_apply=value.get("auto_apply") is True)
|
||||
if seen > now + timedelta(seconds=60) or expiry <= now or expiry > seen + timedelta(minutes=16):
|
||||
result["state"] = "expired"
|
||||
return result, None
|
||||
result["enabled"] = value.get("enabled") is True
|
||||
result["state"] = "ready" if result["enabled"] else "disabled"
|
||||
return result, value["executor_id"] if result["enabled"] else None
|
||||
|
||||
def _request(self):
|
||||
value = read_json(self.root / "update-request.json")
|
||||
if not isinstance(value, dict) or value.get("protocol") != PROTOCOL:
|
||||
return None
|
||||
if not valid_id(value.get("request_id")) or parse_time(value.get("requested_at")) is None:
|
||||
return None
|
||||
try:
|
||||
stable_version(value.get("version"))
|
||||
except ValueError:
|
||||
return None
|
||||
return {key: value[key] for key in ("request_id", "version", "requested_at")}
|
||||
|
||||
def _host_status(self):
|
||||
value = read_json(self.root / "updater-status.json")
|
||||
if not isinstance(value, dict) or value.get("protocol") != PROTOCOL:
|
||||
return None
|
||||
if value.get("status") not in HOST_STATES or not valid_id(value.get("request_id")):
|
||||
return None
|
||||
if parse_time(value.get("updated_at")) is None:
|
||||
return None
|
||||
try:
|
||||
stable_version(value.get("version"))
|
||||
except ValueError:
|
||||
return None
|
||||
# Advisory files in /data are not trusted to supply public free text.
|
||||
result = {key: value[key] for key in ("request_id", "status", "version", "updated_at")}
|
||||
result["error"] = _MESSAGES[value["status"]] if value["status"] in {"failed", "rolled_back"} else None
|
||||
return result
|
||||
|
||||
def status(self):
|
||||
with self._lock:
|
||||
cache = read_json(self.root / "update-check.json")
|
||||
cache = cache if isinstance(cache, dict) else {}
|
||||
state = cache.get("status", "unchecked")
|
||||
if state not in {"unchecked", "no_release", "up_to_date", "available", "check_failed"}:
|
||||
state = "unchecked"
|
||||
checked = parse_time(cache.get("checked_at"))
|
||||
latest = cache.get("latest_version")
|
||||
try:
|
||||
key = stable_version(latest)
|
||||
except ValueError:
|
||||
latest, key = None, None
|
||||
available = key is not None and key > self._current and state != "check_failed"
|
||||
if latest and state != "check_failed":
|
||||
state = "available" if available else "up_to_date"
|
||||
elif state in {"available", "up_to_date"}:
|
||||
state = "unchecked"
|
||||
executor, _ = self._executor()
|
||||
request, host = self._request(), self._host_status()
|
||||
if request:
|
||||
request["status"] = "pending"
|
||||
if host and host["request_id"] == request["request_id"]:
|
||||
request["status"] = host["status"]
|
||||
state = request["status"]
|
||||
elif host:
|
||||
state = host["status"]
|
||||
result = {
|
||||
"current_version": self.current_version, "latest_version": latest,
|
||||
"available": available, "checked_at": timestamp(checked) if checked else None,
|
||||
"release_url": f"https://github.com/{REPOSITORY}/releases/tag/{latest}" if latest else None,
|
||||
"channel": "stable-2.x", "repository": REPOSITORY,
|
||||
"status": state, "message": _MESSAGES[state],
|
||||
"error": _MESSAGES[state] if state in {"check_failed", "failed", "rolled_back"} else None,
|
||||
"can_apply": available and executor["enabled"] and state not in {"pending", "applying"},
|
||||
"executor": executor, "request": request, "host_status": host,
|
||||
}
|
||||
return result
|
||||
|
||||
def check(self):
|
||||
with self._lock:
|
||||
try:
|
||||
tags = official_tags(github_releases())
|
||||
latest = max(tags, key=stable_version) if tags else None
|
||||
state = "no_release" if latest is None else "available" if stable_version(latest) > self._current else "up_to_date"
|
||||
cache = {"status": state, "latest_version": latest, "checked_at": timestamp()}
|
||||
except Exception:
|
||||
# Never expose response bodies, proxy addresses, tokens, or paths.
|
||||
cache = {"status": "check_failed", "latest_version": None, "checked_at": timestamp()}
|
||||
atomic_json(self.root / "update-check.json", cache)
|
||||
return self.status()
|
||||
|
||||
def request_update(self, version=None):
|
||||
with self._lock:
|
||||
if version is not None:
|
||||
stable_version(version)
|
||||
executor, executor_id = self._executor()
|
||||
if not executor["enabled"]:
|
||||
result = self.status()
|
||||
result.update(status="unavailable", message=_MESSAGES["unavailable"], can_apply=False)
|
||||
return result
|
||||
state = self.status()
|
||||
if state["status"] in {"pending", "applying"}:
|
||||
return state
|
||||
# Revalidate against live official releases, never just a local cache.
|
||||
try:
|
||||
tags = official_tags(github_releases())
|
||||
except Exception:
|
||||
raise ValueError(_MESSAGES["check_failed"]) from None
|
||||
target = version or (max(tags, key=stable_version) if tags else None)
|
||||
if target is None or target not in tags:
|
||||
raise ValueError("指定版本不是官方已发布的稳定 Web 2 正式版。")
|
||||
if stable_version(target) <= self._current:
|
||||
raise ValueError("仅允许升级到比当前版本更新的稳定 Web 2 正式版。")
|
||||
atomic_json(self.root / "update-check.json", {
|
||||
"status": "available", "latest_version": max(tags, key=stable_version), "checked_at": timestamp(),
|
||||
})
|
||||
atomic_json(self.root / "update-request.json", {
|
||||
"protocol": PROTOCOL, "request_id": uuid.uuid4().hex, "executor_id": executor_id,
|
||||
"version": target, "requested_at": timestamp(),
|
||||
}, mode=0o600)
|
||||
return self.status()
|
||||
@@ -0,0 +1,770 @@
|
||||
"""Plain-data desktop parity views. Called only on an account worker thread."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from copy import deepcopy
|
||||
from dataclasses import asdict
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from ranch_assistant.model import EggRule, duration, seconds
|
||||
from ranch_assistant.maps import reward_summary
|
||||
from ranch_assistant.daily import entries
|
||||
from ranch_assistant.drop_statistics import analyze
|
||||
from ranch_assistant.presentation import monster_rows
|
||||
from ranch_assistant.battle_messages import battle_message
|
||||
from ranch_assistant.resource_stages import available_item_count, item_requirements, with_resource_data
|
||||
from .policies import default_config, validate_config
|
||||
|
||||
|
||||
PAGES = [
|
||||
("login", "登录"), ("incubator", "培育室"), ("bag", "背包"), ("ranch", "牧场"),
|
||||
("daily", "每日事务"), ("hatching", "自动孵蛋"), ("mainline", "自动主线"),
|
||||
("battles", "战斗记录"), ("gifts", "自动赠礼"), ("commissions", "自动委托"),
|
||||
("exploration", "自动探险"), ("maps", "自动扫荡"), ("statistics", "数据分析"),
|
||||
("plans", "执行计划"), ("yields", "收益资料"),
|
||||
]
|
||||
ITEM_TYPES = {0: "全部物品", 6: "魔物蛋", 1: "可使用", 2: "消耗品", 3: "材料", 4: "其他", 5: "装备"}
|
||||
BAG_CATEGORIES = [("eggs", "魔物蛋"), ("usable", "可使用"), ("consumables", "消耗品"),
|
||||
("materials", "材料"), ("other", "其他"), ("equipment", "装备")]
|
||||
|
||||
|
||||
def _options(pairs):
|
||||
return [{"value": value, "label": label} for value, label in pairs]
|
||||
|
||||
|
||||
def _field(path, label, kind="boolean", **extra):
|
||||
return {"path": list(path), "label": label, "type": kind, **extra}
|
||||
|
||||
|
||||
def _policy_field(key, label, kind="boolean", **extra):
|
||||
return _field(["policy", key], label, kind, **extra)
|
||||
|
||||
|
||||
def _strategy_fields(catalog):
|
||||
"""Only controls retained by the current GUI; legacy Policy fields stay hidden."""
|
||||
markets = _options([(key, row.get("name", key) + "市场") for key, row in catalog.data.get("markets", {}).items()])
|
||||
team_options = _options([(key, key) for key in ("teamA", "teamB", "teamC")])
|
||||
hatch = [_policy_field(key, label, group="孵蛋策略") for key, label in (
|
||||
("enabled", "启用培育室自动管理"), ("buy", "自动从金币市场购蛋 / 抽蛋"),
|
||||
("allow_single_draw", "允许单抽"), ("buy_ten", "优先十连"), ("fill", "自动填充空坑位"),
|
||||
("dispatch", "成熟后按策略自动派遣"), ("collect", "自动收取到牧场"))]
|
||||
hatch += [_policy_field("market_id", "新增规则默认市场", "select", options=markets, group="孵蛋策略")]
|
||||
hatch += [_policy_field(key, label, "integer", min=low, max=high, group="孵蛋策略") for key, label, low, high in (
|
||||
("buy_batch", "单抽时每批上限", 1, 100), ("keep_money", "至少保留金币", 0, 1_000_000_000),
|
||||
("daily_buy_money", "每日购蛋金币额度(0=不购买)", 0, 1_000_000_000))]
|
||||
hatch += [_policy_field("protect_star", "保留此星级及以上", "integer", min=1, max=6, group="牧场策略"),
|
||||
_policy_field("protect_quality", "资质保留条件", "select", group="牧场策略", options=_options([
|
||||
(4, "S及以上"), (3, "A及以上"), (2, "B及以上"), (1, "全部资质"), (5, "不按资质保留"), (6, "四项全S(4S)才保留")])),
|
||||
_policy_field("keep_better_quality", "保留资质高于牧场同种培养代表的新魔物", group="牧场策略"),
|
||||
_policy_field("room_id", "收取到牧场", "select", options=_options([(0, "自动选择有空位的牧场")]), group="牧场策略"),
|
||||
_policy_field("reserved_types", "额外保留魔物编号", "id_list", group="牧场策略"),
|
||||
_policy_field("reserved_eggs", "保留蛋数量", "id_counts", group="牧场策略"),
|
||||
_policy_field("feed", "按策略喂养选定目标(受当前突破上限限制)", group="喂养策略")]
|
||||
gift = [_policy_field(key, label) for key, label in (
|
||||
("gift_enabled", "启用自动赠礼"), ("gift_auto_representative", "每种魔物只培养一只,自动选择培养代表"),
|
||||
("gift_liked_only", "仅赠送目标喜欢的物品"))]
|
||||
quest = [_field(["quest_policy", key], label) for key, label in (
|
||||
("enabled", "启用委托自动接取 / 推进 / 领奖"), ("accept", "按氪金奖励优先接取(20 → 15 → 10)"), ("allow_items", "允许提交道具(遵守保留数量)"),
|
||||
("allow_monsters", "允许提交1级魔物(遵守锁定、星级和资质保留)"), ("battle_tasks", "也接取需要实战的委托"))]
|
||||
quest += [_field(["quest_policy", "city"], "城市编号(0=所有已解锁城市)", "integer", min=0, max=99),
|
||||
_field(["quest_policy", "max_money"], "单次最多提交金币", "integer", min=0, max=10_000_000),
|
||||
_field(["quest_policy", "item_reserves"], "保留道具", "id_counts")]
|
||||
progression_labels = [("enabled", "启用自动主线策略"), ("mainline", "主线"), ("sidequests", "支线"),
|
||||
("commissions", "委托(仅诊断)"), ("accept", "接取已确认的任务"), ("auto_dialogue", "自动推进已支持的对话"),
|
||||
("repair_chain", "补全已确认的任务链"), ("allow_items", "允许提交物品"), ("allow_monsters", "允许提交魔物"),
|
||||
("allow_sweep", "允许用扫荡完成已通关目标"), ("auto_farm", "自动收集任务材料 / 击杀目标")]
|
||||
progression = [_field(["progression_policy", key], label) for key, label in progression_labels]
|
||||
progression += [_field(["progression_policy", "team"], "推进战斗队伍", "select", options=team_options)]
|
||||
progression += [_field(["progression_policy", key], label, "integer", min=low, max=high) for key, label, low, high in (
|
||||
("reserve_ti", "保留体力", 0, 1_000_000_000), ("max_money", "单次交付金币上限(0=不交金币)", 0, 1_000_000_000),
|
||||
("stop_after_loss", "连续失败后停止次数", 1, 999))]
|
||||
progression += [_field(["progression_policy", "item_reserves"], "交付后至少保留物品", "id_counts")]
|
||||
maps = [_field(["sweep_policy", key], label) for key, label in (
|
||||
("enabled", "启用勾选关卡自动刷图"), ("allow_challenge", "未满星时自动挑战"), ("allow_special", "允许矿洞 / 门票关卡"))]
|
||||
maps += [_field(["sweep_policy", "team"], "使用战队", "select", options=team_options)]
|
||||
maps += [_field(["sweep_policy", key], label, "integer", min=0, max=1_000_000_000) for key, label in (
|
||||
("keep_stamina", "保留体力"), ("keep_tickets", "每种门票 / 工具保留"))]
|
||||
return {"hatching": hatch, "gifts": gift, "commissions": quest, "mainline": progression, "maps": maps,
|
||||
"daily": [_field(["daily_policy", "enabled"], "启用每日奖励领取"),
|
||||
_field(["daily_policy", "selected"], "领取项目", "multiselect", options=_options([
|
||||
("gift", "每日签到礼包"), ("check", "七日签到"), ("loop", "累计奖励"), ("vip", "VIP日奖"), ("mail", "邮件附件")]))],
|
||||
"exploration": [_field(["explore_policy", "enabled"], "自动安排再次探险(完成后自动领奖)"),
|
||||
_field(["explore_policy", "reserve_ti"], "保留体力", "integer", min=0, max=1_000_000_000)],
|
||||
"yields": [_field(["yield_stars"], "星级", "multiselect", options=_options([(i, f"{i}星") for i in range(1, 6)]))],
|
||||
"login": [], "incubator": [], "bag": [], "ranch": [], "battles": [], "statistics": [], "plans": []}
|
||||
|
||||
|
||||
def schema(catalog):
|
||||
fields = _strategy_fields(catalog)
|
||||
return {"version": 1, "pages": [{"key": key, "title": title, "form": fields[key]} for key, title in PAGES],
|
||||
"settings": [_field(["interval"], "随机刷新间隔", "select", options=_options([
|
||||
(30, "0~30秒"), (60, "0~60秒"), (120, "0~120秒"), (300, "0~300秒")])),
|
||||
_field(["log_visible"], "显示日志"), _field(["log_sizes"], "页面 / 日志高度", "sizes")],
|
||||
"defaults": default_config()}
|
||||
|
||||
|
||||
def _value(config, path):
|
||||
value = config
|
||||
for key in path:
|
||||
value = value[key]
|
||||
return deepcopy(value)
|
||||
|
||||
|
||||
def _column(key, label, kind=None, edit=None):
|
||||
return {"key": key, "label": label, **({"type": kind} if kind else {}), **({"edit": edit} if edit else {})}
|
||||
|
||||
|
||||
def build_view(engine, page, config, query=None):
|
||||
if page not in dict(PAGES):
|
||||
raise ValueError("未知页面")
|
||||
config = validate_config(config)
|
||||
fields = _strategy_fields(engine.catalog)[page]
|
||||
dto = {"page": page, "title": dict(PAGES)[page], "columns": [], "rows": [], "summary": "",
|
||||
"form": [field | {"value": _value(config, field["path"])} for field in fields],
|
||||
"filters": [], "details": {}, "actions": [{"operation": "refresh", "label": "刷新本页", "payload": {"page": page}}]}
|
||||
builder = _BUILDERS.get(page)
|
||||
if engine.snapshot is None and page not in ("login", "yields", "statistics"):
|
||||
dto["summary"] = "请先登录或打开离线演示"
|
||||
return dto
|
||||
if builder is not None:
|
||||
builder(dto, engine, config, query or {})
|
||||
elif engine.snapshot is None:
|
||||
dto["summary"] = "请先登录或打开离线演示"
|
||||
return dto
|
||||
|
||||
|
||||
_BUILDERS = {}
|
||||
|
||||
|
||||
def _filter(key, label, value, pairs=None, kind="select"):
|
||||
return {"key": key, "label": label, "type": kind, "value": value,
|
||||
**({"options": _options(pairs)} if pairs is not None else {})}
|
||||
|
||||
|
||||
def _search(dto, query):
|
||||
search = str(query.get("search", "")).strip().casefold()
|
||||
dto["filters"].append(_filter("search", "搜索", query.get("search", ""), kind="text"))
|
||||
return search
|
||||
|
||||
|
||||
def _boolean(value, default=False):
|
||||
return value if type(value) is bool else str(value).lower() in ("true", "1", "yes") if value is not None else default
|
||||
|
||||
|
||||
def _edit(path, kind, **extra):
|
||||
return {"path": list(path), "type": kind, **extra}
|
||||
|
||||
|
||||
def _row_column(key, label, section, *, kind="integer", **extra):
|
||||
return _column(key, label, kind, _edit([*section, "{id}", key], kind, **extra))
|
||||
|
||||
|
||||
def _login(dto, engine, config, query):
|
||||
dto["columns"] = [_column("name", "服务器"), _column("role_name", "角色")]
|
||||
dto["summary"] = "离线演示,无游戏网络连接" if engine.demo else "请在此账号登录或恢复已保存的角色"
|
||||
# Runtime adds only public saved-session/server metadata via login_view().
|
||||
dto["servers"], dto["saved_sessions"], dto["has_saved_password"] = [], [], False
|
||||
dto["actions"] = [{"operation": "login", "label": "账号密码登录"},
|
||||
{"operation": "restore_session", "label": "恢复保存角色"},
|
||||
{"operation": "logout", "label": "退出当前角色"},
|
||||
{"operation": "forget_login", "label": "忘记登录信息"}]
|
||||
|
||||
|
||||
def _plans(engine):
|
||||
# Only kind and description are public. Action paths/payloads may contain
|
||||
# instance IDs, protocol evidence or non-JSON progression intents.
|
||||
return [{"id": str(i), "kind": action.kind, "description": action.description}
|
||||
for i, action in enumerate(engine.plans())]
|
||||
|
||||
|
||||
def _incubator(dto, engine, config, query):
|
||||
snapshot, catalog = engine.snapshot, engine.catalog
|
||||
dto["columns"] = [_column(k, label) for k, label in (
|
||||
("position_label", "坑位"), ("stack_id", "坑位ID"), ("status", "开启状态"), ("name", "魔物"),
|
||||
("star", "星"), ("phase", "阶段"), ("remaining_text", "剩余时间"), ("quality", "资质 攻/防/血/敏"), ("decision", "策略预览"))]
|
||||
opened = {int(row.get("position", -1)): row for row in snapshot.raw["stacks"]}
|
||||
total = max(int(catalog.data.get("stack_meta", {}).get("total", 0)), max(opened, default=-1) + 1)
|
||||
vip = seconds((snapshot.raw.get("activityHistory", {}).get("vipInfo") or {}).get("vipTime")) > snapshot.now
|
||||
engine.plans() # Refresh core disposition/status calculations without executing.
|
||||
for position in range(total):
|
||||
slot = opened.get(position)
|
||||
mon = snapshot.monsters.get(int(slot.get("monsterId") or 0)) if slot else None
|
||||
info = catalog.monster(mon.get("typeId")) if mon else {}
|
||||
remaining = snapshot.remaining(mon, catalog) if mon else None
|
||||
dto["rows"].append({"id": str(position), "position": position, "position_label": position + 1,
|
||||
"stack_id": slot.get("id", "") if slot else "", "opened": bool(slot), "vip": position == 3,
|
||||
"status": ("VIP已激活" if vip else "VIP未激活") if slot and position == 3 else "已开启" if slot else "VIP专用" if position == 3 else "未开启",
|
||||
"name": info.get("name", "未知") if mon else "空位" if slot else "", "star": info.get("star", ""),
|
||||
"monster_id": int(mon["id"]) if mon else None, "phase": snapshot.phase_text(mon, catalog) if mon else "",
|
||||
"remaining": remaining, "remaining_text": duration(remaining) if mon else "", "quality": catalog.quality_text(mon) if mon else "",
|
||||
"decision": engine.planner.statuses.get(int(mon["id"]), "等待成长 / 预览规则") if mon else "",
|
||||
"can_expand": slot is None and position != 3})
|
||||
dto["summary"] = f"已开启 {len(opened)} / {total} 个坑位;第4坑为VIP专用({'已激活' if vip else '未激活'})"
|
||||
dto["actions"] += [{"operation": "quote_expansion", "label": "开启选中普通坑位", "selection": "position",
|
||||
"payload": {"kind": "stack"}, "currencies": _options([("money", "金币"), ("ke", "氪金")])}]
|
||||
|
||||
|
||||
def _default_egg_rule(catalog, type_id, preferred_market):
|
||||
markets = catalog.markets_for(type_id)
|
||||
market = preferred_market if preferred_market in markets else markets[0] if markets else ""
|
||||
return asdict(EggRule(market_id=market))
|
||||
|
||||
|
||||
def _egg_rows(dto, engine, config, query):
|
||||
catalog, snapshot = engine.catalog, engine.snapshot
|
||||
groups = {}
|
||||
for egg in snapshot.eggs(catalog):
|
||||
key = str(egg["typeId"])
|
||||
group = groups.setdefault(key, {"count": 0, "inventory_ids": []})
|
||||
group["count"] += int(egg.get("num") or 0)
|
||||
group["inventory_ids"].append(int(egg["id"]))
|
||||
rules = config["policy"]["egg_rules"]
|
||||
search = str(query.get("search", "")).strip().casefold()
|
||||
dto["columns"] = [_column(k, label) for k, label in (("name", "魔物蛋"), ("star", "星"), ("count", "数量"))]
|
||||
for key, label, kind, extra in (
|
||||
("enabled", "孵化", "boolean", {}), ("priority", "优先级", "integer", {"min": 1, "max": 999}),
|
||||
("action", "孵出后", "select", {"options": _options([("sell", "派遣"), ("feed", "喂养"), ("keep", "保留")])}),
|
||||
("refill_below", "低于补货", "integer", {"min": 0, "max": 1000}),
|
||||
("refill_target", "补至", "integer", {"min": 1, "max": 1000}), ("market_id", "补货市场", "select", {})):
|
||||
dto["columns"].append(_row_column(key, label, ["policy", "egg_rules"], kind=kind, **extra))
|
||||
dto["columns"] += [_column(k, label) for k, label in (
|
||||
("time_text", "培育时间"), ("sell_money", "派遣金币"), ("sell_exp", "基础经验"),
|
||||
("gold_per_hour", "金币/小时"), ("exp_per_hour", "经验/小时"), ("inventory_text", "物品ID"))]
|
||||
dto["columns"].append(_row_column("keep_count", "牧场保留", ["policy", "egg_rules"], min=0, max=1000,
|
||||
help="已启用规则跨牧场至少保留此数量;0不保留名额,硬保护仍有效"))
|
||||
for key in dict.fromkeys([*groups, *rules]):
|
||||
info = catalog.monster(key)
|
||||
if not info or search and search not in (key + str(info.get("name", ""))).casefold():
|
||||
continue
|
||||
markets = catalog.markets_for(key)
|
||||
defaults = _default_egg_rule(catalog, key, config["policy"]["market_id"])
|
||||
rule = defaults | rules.get(key, {})
|
||||
total = max(1, catalog.total_time(key))
|
||||
money, exp = info.get("sell_money", 0), info.get("sell_exp", 0)
|
||||
options = _options([(market, catalog.data["markets"][market]["name"] + "市场") for market in markets])
|
||||
dto["rows"].append({"id": key, "type_id": key, "name": info.get("name", key), "star": info.get("star", "?"),
|
||||
**groups.get(key, {"count": 0, "inventory_ids": []}), **rule, "time_total": total, "time_text": duration(total),
|
||||
"sell_money": money, "sell_exp": exp, "gold_per_hour": round(money * 3600 / total, 2), "exp_per_hour": round(exp * 3600 / total, 2),
|
||||
"inventory_text": ", ".join(map(str, groups.get(key, {}).get("inventory_ids", []))),
|
||||
"rule_defaults": defaults, "rule_path": ["policy", "egg_rules", key],
|
||||
"edits": {"market_id": _edit(["policy", "egg_rules", key, "market_id"], "select", options=options or _options([("", "金币市场无此蛋")]))}})
|
||||
dto["summary"] = f"{len(dto['rows'])} 种魔物蛋规则;已启用 {sum(row['enabled'] for row in dto['rows'])} 种"
|
||||
dto["form"].append(_field(["policy", "egg_rules"], "添加魔物蛋规则", "add_rule", value=None,
|
||||
options=_options([(key, row.get("name", key)) for key, row in catalog.monsters.items()]), defaults=asdict(EggRule()),
|
||||
defaults_by_id={key: _default_egg_rule(catalog, key, config["policy"]["market_id"]) for key in catalog.monsters},
|
||||
help="可配置背包当前没有的蛋;按孵化优先级、去向、补货和牧场保留规则自动执行"))
|
||||
|
||||
|
||||
def _bag(dto, engine, config, query):
|
||||
category = str(query.get("category", "eggs"))
|
||||
if category not in dict(BAG_CATEGORIES) and category != "all":
|
||||
raise ValueError("背包分类无效")
|
||||
dto["filters"].append(_filter("category", "背包分类", category, BAG_CATEGORIES))
|
||||
search = _search(dto, query)
|
||||
if category == "eggs":
|
||||
_egg_rows(dto, engine, config, query)
|
||||
return
|
||||
category_code = {"all": 0, "usable": 1, "consumables": 2, "materials": 3, "other": 4, "equipment": 5}[category]
|
||||
catalog = engine.catalog
|
||||
groups = {}
|
||||
for item in engine.snapshot.raw["items"]:
|
||||
key = str(item.get("typeId"))
|
||||
if int(item.get("num") or 0) <= 0 or category_code and catalog.item_type(key) != category_code:
|
||||
continue
|
||||
if search and search not in (key + catalog.item_name(key)).casefold():
|
||||
continue
|
||||
group = groups.setdefault(key, {"count": 0, "inventory_ids": []})
|
||||
group["count"] += int(item["num"])
|
||||
group["inventory_ids"].append(int(item["id"]))
|
||||
dto["columns"] = [_column(k, label) for k, label in (("inventory_text", "物品ID"), ("name", "名称"), ("category", "分类"),
|
||||
("quality", "品质"), ("count", "数量"), ("sell_money", "售价"))]
|
||||
dto["columns"] += [_row_column("enabled", "允许赠礼", ["policy", "gift_items"], kind="boolean"),
|
||||
_row_column("reserve", "至少保留", ["policy", "gift_items"], min=0, max=1_000_000_000)]
|
||||
for key, group in groups.items():
|
||||
info = catalog.item(key)
|
||||
code = catalog.item_type(key)
|
||||
eligible = code not in (5, 6) and bool(info.get("sellable"))
|
||||
rule = {"enabled": False, "reserve": 0} | config["policy"]["gift_items"].get(key, {})
|
||||
dto["rows"].append({"id": key, "type_id": key, "name": catalog.item_name(key), "category": ITEM_TYPES.get(code, "其他"),
|
||||
"quality": info.get("quality", ""), **group, "inventory_text": ", ".join(map(str, group["inventory_ids"])),
|
||||
"sell_money": info.get("sellMoney", ""), **rule, "gift_eligible": eligible,
|
||||
"rule_defaults": {"enabled": False, "reserve": 0}, "rule_path": ["policy", "gift_items", key],
|
||||
"edits": {field: _edit(["policy", "gift_items", key, field], kind, disabled=not eligible,
|
||||
reason="此类物品不进入自动赠礼" if not eligible else "") for field, kind in (("enabled", "boolean"), ("reserve", "integer"))}})
|
||||
dto["summary"] = f"{len(groups)} 类物品 / {sum(row['count'] for row in groups.values())} 件;同种库存合并显示"
|
||||
|
||||
|
||||
def _ranch(dto, engine, config, query):
|
||||
snapshot, catalog = engine.snapshot, engine.catalog
|
||||
grouped = _boolean(query.get("grouped"), False)
|
||||
try:
|
||||
room_id = int(query.get("room_id") or 0)
|
||||
except (ValueError, TypeError) as exc:
|
||||
raise ValueError("牧场编号无效") from exc
|
||||
dto["filters"] = [_filter("grouped", "按牧场分组", grouped, kind="boolean"),
|
||||
_filter("room_id", "牧场", room_id, [(0, "全部牧场")] + [(int(room["id"]), f"{room.get('name') or '牧场'} #{room['id']}") for room in snapshot.raw["rooms"]])]
|
||||
search = _search(dto, query)
|
||||
keys = ["monster_id", "name", "star", "level_text", "quality", "location", "locked", "scope",
|
||||
"feed_selected", "feed_priority", "potential_level", "attack", "defense", "health", "dexterity", "feel_text", "likes",
|
||||
"gift_selected", "gift_priority", "breakthrough_selected", "breakthrough_priority", "tp_level_text", "tp_exp_text"]
|
||||
labels = ["牧场 / 魔物ID", "名称", "星", "等级 / 当前上限", "资质 攻/防/血/敏", "位置", "锁定", "管理范围",
|
||||
"喂养目标", "喂养优先级", "潜能阶段", "参考攻击", "参考防御", "参考生命", "参考敏捷", "好感 / 当前上限", "喜欢的物品",
|
||||
"赠礼", "赠礼优先级", "自动突破目标", "突破优先级", "同种突破", "突破经验"]
|
||||
dto["columns"] = [_column(key, label) for key, label in zip(keys, labels)]
|
||||
for prefix, mapping in (("feed", "feed_targets"), ("gift", "gift_targets"), ("breakthrough", "breakthrough_targets")):
|
||||
for column in dto["columns"]:
|
||||
if column["key"] == prefix + "_selected":
|
||||
column.update(type="boolean", edit=_edit(["policy", mapping, "{id}"], "target", default=100, unchecked="delete"))
|
||||
elif column["key"] == prefix + "_priority":
|
||||
column.update(type="integer", edit=_edit(["policy", mapping, "{id}"], "integer", min=1, max=999, optional=True))
|
||||
managed = engine.planner.managed
|
||||
rows = monster_rows(catalog, snapshot, managed)
|
||||
counts = Counter("incubator" if mon.get("process") == 2 else f"room:{int(mon.get('roomId') or 0)}" for mon in snapshot.raw["monsters"])
|
||||
dto["groups"] = []
|
||||
if grouped:
|
||||
for room in snapshot.raw["rooms"]:
|
||||
rid = int(room["id"])
|
||||
if room_id and rid != room_id:
|
||||
continue
|
||||
info = catalog.data.get("room_info", {}).get(str(room.get("typeId")), {})
|
||||
group_key = f"room:{rid}"
|
||||
capacity = info.get("maxNum")
|
||||
dto["groups"].append({"id": group_key, "label": f"{room.get('name') or info.get('name') or '牧场'} #{rid}",
|
||||
"count": counts[group_key], "capacity": capacity, "free": max(0, int(capacity) - counts[group_key]) if capacity is not None else None, "collapsed": False})
|
||||
for mon, values in zip(snapshot.raw["monsters"], rows):
|
||||
if room_id and (mon.get("process") != 3 or int(mon.get("roomId") or 0) != room_id):
|
||||
continue
|
||||
if search and search not in " ".join(map(str, values)).casefold():
|
||||
continue
|
||||
key = str(int(mon["id"]))
|
||||
row = dict(zip(keys, values)) | {"id": key, "type_id": str(mon["typeId"]), "level": int(mon.get("level") or 1), "max_level": catalog.max_level(mon),
|
||||
"process": mon.get("process"), "room_id": int(mon.get("roomId") or 0), "group": "incubator" if mon.get("process") == 2 else f"room:{int(mon.get('roomId') or 0)}", "edits": {}}
|
||||
for prefix, mapping in (("feed", "feed_targets"), ("gift", "gift_targets"), ("breakthrough", "breakthrough_targets")):
|
||||
targets = config["policy"][mapping]
|
||||
selected = key in targets
|
||||
row[prefix + "_selected"], row[prefix + "_priority"] = selected, targets.get(key, 100)
|
||||
row["edits"][prefix + "_selected"] = _edit(["policy", mapping, key], "target", default=100, unchecked="delete", disabled=mon.get("process") != 3)
|
||||
row["edits"][prefix + "_priority"] = _edit(["policy", mapping, key], "integer", min=1, max=999, optional=True, disabled=not selected or mon.get("process") != 3)
|
||||
dto["rows"].append(row)
|
||||
dto["details"][key] = {"name": row["name"], "species": catalog.monster(mon["typeId"]).get("name", "未知"), "id": int(mon["id"]),
|
||||
"level": row["level_text"], "quality": row["quality"], "reference_stats": catalog.reference_stats(mon),
|
||||
"growth": {name: mon.get("g" + name.capitalize()) for name in ("atk", "def", "hp", "dex")},
|
||||
"likes": row["likes"], "feel": row["feel_text"], "feed_exp": catalog.feed_exp(mon), "scope": row["scope"]}
|
||||
if grouped:
|
||||
known = {group["id"] for group in dto["groups"]}
|
||||
for row in dto["rows"]:
|
||||
if row["group"] not in known:
|
||||
known.add(row["group"])
|
||||
dto["groups"].append({"id": row["group"], "label": "培育室" if row["group"] == "incubator" else "未归属牧场", "count": counts[row["group"]], "collapsed": False})
|
||||
dto["summary"] = f"{len(snapshot.raw['rooms'])} 座牧场;显示 {len(dto['rows'])} 只魔物;勾选目标按较小优先级先执行"
|
||||
targets = [{"value": int(mon["id"]), "label": f"{catalog.monster_label(mon)} Lv.{mon.get('level', 1)}/{catalog.max_level(mon)}"}
|
||||
for mon in snapshot.raw["monsters"] if mon.get("process") == 3 and catalog.max_level(mon) is not None and int(mon.get("level", 1)) < catalog.max_level(mon)]
|
||||
dto["feed_targets"] = targets
|
||||
dto["actions"] += [{"operation": operation, "label": label, "selection": "monster_ids", **extra} for operation, label, extra in (
|
||||
("lock", "锁定选中魔物", {}), ("unlock", "解锁选中魔物", {}),
|
||||
("sell", "派遣选中魔物", {"confirm": "将消耗选中魔物,无法撤销"}),
|
||||
("feed", "喂给指定魔物", {"confirm": "将消耗选中魔物作为经验素材,无法撤销", "target_options": targets}))]
|
||||
dto["actions"].append({"operation": "quote_expansion", "label": "新建牧场", "payload": {"kind": "room"},
|
||||
"currencies": _options([("money", "金币"), ("ke", "氪金")])})
|
||||
|
||||
|
||||
def _daily(dto, engine, config, query):
|
||||
dto["columns"] = [_column(k, label) for k, label in (("name", "项目 / 邮件"), ("status", "状态"), ("reward", "奖励 / 附件"))]
|
||||
for row in entries(engine.catalog, engine.snapshot, engine.daily_ledger):
|
||||
dto["rows"].append({"id": row.key, "name": row.name, "status": row.status, "reward": row.reward, "claimable": row.action is not None})
|
||||
dto["summary"] = "刷新只更新状态;领取勾选项目立即处理可领奖励;自动领取需要开启顶部策略"
|
||||
dto["actions"].append({"operation": "claim_daily", "label": "领取勾选项目", "payload": {}})
|
||||
|
||||
|
||||
def _hatching(dto, engine, config, query):
|
||||
for field in dto["form"]:
|
||||
if field["path"] == ["policy", "room_id"]:
|
||||
field["options"] += _options([(int(room["id"]), f"{room.get('name') or '牧场'} #{room['id']}") for room in engine.snapshot.raw["rooms"]])
|
||||
dto["tabs"] = [{"key": label, "title": label} for label in ("孵蛋策略", "牧场策略", "喂养策略")]
|
||||
dto["columns"] = [_column("kind", "类型"), _column("description", "下一步 / 等待条件")]
|
||||
dto["rows"] = _plans(engine)
|
||||
policy = engine.policy
|
||||
dto["summary"] = "先在背包魔物蛋配置规则,再开启顶部策略;空坑按优先级随机1~2秒装填"
|
||||
dto["details"] = {"feed_status": engine.planner.feed_status(engine.snapshot, policy),
|
||||
"last_draw": engine.last_draw or "尚无记录", "notes": list(dict.fromkeys(engine.planner.notes)),
|
||||
"preset": {"label": "绿色史莱姆金币预设(仅孵此蛋)", "patch": {
|
||||
"policy": {"enabled": True, "buy": True, "fill": True, "dispatch": True, "collect": True, "buy_ten": True,
|
||||
"allow_single_draw": False, "feed": False, "strategy": "gold", "market_id": "sc_city1", "egg_order": "shortest",
|
||||
"protect_quality": 3, "protect_star": 4, "hatch_max_star": 3, "min_gold_per_hour": 0, "min_exp_per_hour": 0}},
|
||||
"egg_rules": {key: rule | {"enabled": False} for key, rule in config["policy"]["egg_rules"].items()} | {
|
||||
"1001010": asdict(EggRule(enabled=True, priority=1, action="sell", refill_below=1, refill_target=10, market_id="sc_city1"))},
|
||||
"help": "只更改策略并保存;开启顶部策略后运行"}}
|
||||
|
||||
|
||||
def _gifts(dto, engine, config, query):
|
||||
catalog, snapshot = engine.catalog, engine.snapshot
|
||||
dto["columns"] = [_column(k, label) for k, label in (("species", "魔物种类"), ("monster_id", "培养对象 ID"),
|
||||
("level", "等级"), ("feel_text", "好感 / 上限"), ("quality", "资质 攻/防/血/敏"), ("likes", "喜欢的物品"), ("cooldown", "赠礼冷却"))]
|
||||
representatives = engine.cultivation.select(snapshot) if engine.policy.gift_auto_representative else {}
|
||||
candidates = list(representatives.values()) if representatives else engine.gift_planner.candidates(snapshot, engine.policy)
|
||||
cooldown = int(catalog.data["game_setting"].get("monGiftTime", 7200))
|
||||
for mon in candidates:
|
||||
remaining = max(0, seconds(mon.get("giftTime")) + cooldown - snapshot.now)
|
||||
dto["rows"].append({"id": str(mon["id"]), "species": catalog.monster(mon["typeId"]).get("name", "未知"),
|
||||
"monster_id": int(mon["id"]), "level": mon.get("level", 1), "feel_text": f"{mon.get('feel', 0)} / {catalog.max_feel(mon)}",
|
||||
"quality": catalog.quality_text(mon), "likes": catalog.likes_text(mon["typeId"]), "remaining": remaining,
|
||||
"cooldown": duration(remaining) if remaining else "可赠礼"})
|
||||
engine.gift_planner.plan(snapshot, engine.policy, engine.quest_policy)
|
||||
dto["summary"] = "自动代表按等级 → 好感 → 综合成长资质选择并记住;满好感或冷却时不换喂同种另一只"
|
||||
dto["details"] = {"notes": list(engine.gift_planner.notes), "next_ready_at": engine.gift_planner.next_ready_at,
|
||||
"inventory_page": "bag", "targets_page": "ranch"}
|
||||
|
||||
|
||||
CATEGORIES = {"mainline": "主线", "sidequest": "支线", "commission": "委托", "event": "活动(暂不自动)", "bond": "羁绊(暂不自动)", "unknown": "其他 / 未知"}
|
||||
BATTLE_KINDS = {"mainline": "主线战斗", "sidequest": "支线战斗", "commission": "委托战斗", "battle": "普通战斗", "map_battle": "地图战斗",
|
||||
"sweep": "扫荡", "map_reward_event": "地图奖励事件", "ordinary_stage": "普通关卡战斗", "resource_stage": "资源关卡战斗", "task_battle": "任务战斗", "task_pass_stage": "任务通关战斗", "unknown": "其他 / 未知"}
|
||||
BATTLE_ALIASES = {"task": "task_battle", "passStage": "task_pass_stage", "event": "map_reward_event", "reward_event": "map_reward_event", "normal": "battle"}
|
||||
STATES = {"available": "可接取", "unaccepted": "未接取", "active": "进行中", "in_progress": "进行中", "ready": "待交付", "completed": "已完成", "complete": "已完成",
|
||||
"claimed": "已领奖", "received": "进行中", "unlocked": "已解锁 / 待接取", "offered": "待接取", "locked": "未解锁", "finished": "已完成", "ready_to_reward": "待领取任务奖励",
|
||||
"blocked": "受阻", "unsupported": "暂不支持", "unknown": "未知"}
|
||||
STATE_ALIASES = {"active": "received", "in_progress": "received", "available": "unlocked", "unaccepted": "unlocked", "offered": "unlocked", "ready": "ready_to_reward",
|
||||
"completed": "finished", "complete": "finished", "claimed": "finished", "blocked": "received"}
|
||||
STATE_FILTERS = [("current", "当前(进行中 + 待接取 + 待领奖)"), ("received", "进行中"), ("unlocked", "待接取"), ("ready_to_reward", "待领奖"), ("finished", "已完成"), ("locked", "未解锁"), ("", "全部状态")]
|
||||
OUTCOMES = {"win": "胜利", "loss": "打不过", "unsupported": "暂不支持", "event": "地图奖励事件", "completed": "已完成", "cancelled": "已取消", "timeout": "超时", "unknown": "结果待核对"}
|
||||
CHINA_TIME = timezone(timedelta(hours=8))
|
||||
|
||||
|
||||
def _text(value, empty="—"):
|
||||
# Display only scalars. Arbitrary raw structures must never reach a detail
|
||||
# drawer through json.dumps (battle records may contain responses/secrets).
|
||||
return str(value) if isinstance(value, (str, int, float, bool)) and value != "" else empty
|
||||
|
||||
|
||||
def _category(value):
|
||||
value = {"main": "mainline", "side": "sidequest", "sidequests": "sidequest", "commissions": "commission", "主线": "mainline", "支线": "sidequest", "委托": "commission"}.get(value, value) if isinstance(value, str) else "unknown"
|
||||
return value if value in CATEGORIES else "unknown"
|
||||
|
||||
|
||||
def _mainline(dto, engine, config, query):
|
||||
selected, state = str(query.get("category", "mainline")), str(query.get("state", "current"))
|
||||
dto["filters"] = [_filter("category", "任务类别", selected, [("", "全部类别"), *CATEGORIES.items()]),
|
||||
_filter("state", "任务状态", state, STATE_FILTERS)]
|
||||
search = _search(dto, query)
|
||||
dto["columns"] = [_column(key, label) for key, label in (("task_type_id", "编号"), ("category_label", "类别"), ("name", "任务"), ("state_label", "状态"),
|
||||
("step", "步骤"), ("location", "目标 / 位置"), ("requirement", "需求"), ("next_action", "下一步"), ("battle", "战斗类型"), ("support", "支持状态 / 阻塞原因"))]
|
||||
sources = engine.progression_rows()
|
||||
for index, source in enumerate(sources):
|
||||
category = _category(source.get("category"))
|
||||
raw_state = _text(source.get("state"), "unknown")
|
||||
lifecycle = STATE_ALIASES.get(raw_state, raw_state)
|
||||
if selected and category != selected or state == "current" and lifecycle not in ("received", "unlocked", "ready_to_reward") or state not in ("", "current") and lifecycle != state:
|
||||
continue
|
||||
reason = battle_message(source.get("blocked_reason") or source.get("block_reason") or source.get("reason") or "")
|
||||
support = "受阻:" + reason if reason else "已支持" if source.get("supported") is True else "暂不支持" if source.get("supported") is False else "支持状态未确认"
|
||||
battle = _text(source.get("battle_kind"), "未确认")
|
||||
battle = BATTLE_ALIASES.get(battle, battle)
|
||||
row = {"id": str(source.get("task_id") or source.get("task_type_id") or index), "task_type_id": _text(source.get("task_type_id")), "category": category,
|
||||
"category_label": CATEGORIES[category], "name": _text(source.get("name")), "state": raw_state, "lifecycle_state": lifecycle,
|
||||
"state_label": STATES.get(raw_state, raw_state), "step": _text(source.get("step_number")) + " / " + _text(source.get("total_steps")),
|
||||
"location": _text(source.get("location_text") or source.get("location") or source.get("position")), "requirement": _text(source.get("requirement")),
|
||||
"next_action": _text(source.get("next_action")), "battle": BATTLE_KINDS.get(battle, battle), "support": support}
|
||||
detail = {"任务": row["name"], "类别": row["category_label"], "状态": row["state_label"], "步骤": row["step"],
|
||||
"目标 / 位置": row["location"], "NPC": _text(source.get("npc_name")), "需求": row["requirement"],
|
||||
"对话": _text(source.get("dialogue") or source.get("dialogue_text") or source.get("dialogue_status"), "当前未提供对话内容"),
|
||||
"下一步": row["next_action"], "战斗": row["battle"], "运行状态": _text(source.get("status"), row["state_label"]), "支持状态 / 阻塞原因": support}
|
||||
if search and search not in " ".join(map(str, [*row.values(), *detail.values()])).casefold():
|
||||
continue
|
||||
dto["rows"].append(row)
|
||||
dto["details"][row["id"]] = detail
|
||||
dto["summary"] = f"显示 {len(dto['rows'])} / {len(sources)} 条任务;未支持的步骤显示原因" if sources else "尚未读取任务,请刷新任务 / 预览"
|
||||
dto["tabs"] = [{"key": "status", "title": "任务状态"}, {"key": "policy", "title": "推进策略"}]
|
||||
dto["actions"] = [{"operation": "refresh_tasks", "label": "刷新任务 / 预览", "payload": {}}]
|
||||
dto["battle_mode"] = {"mode": "experimental", "label": "实验模拟(近似,未完整验证)", "damage_rule": "保持原始属性;我方对敌最终伤害10倍,单次最高50000"}
|
||||
|
||||
|
||||
def _battles(dto, engine, config, query):
|
||||
selected = str(query.get("category", ""))
|
||||
dto["filters"] = [_filter("category", "战斗类型", selected, [("", "全部类型"), *BATTLE_KINDS.items()])]
|
||||
search = _search(dto, query)
|
||||
dto["columns"] = [_column(key, label) for key, label in (("time", "时间(北京时间)"), ("kind_label", "上下文 / 类型"),
|
||||
("name", "任务 / 地图"), ("team", "队伍"), ("outcome_label", "结果"), ("message", "详情 / 阻塞原因"))]
|
||||
records = engine.progression_records()
|
||||
for index, source in enumerate(records):
|
||||
raw_kind = source.get("battle_kind") or source.get("kind") or source.get("context") or "unknown"
|
||||
kind = BATTLE_ALIASES.get(raw_kind, raw_kind) if isinstance(raw_kind, str) else "unknown"
|
||||
if source.get("outcome") == "event":
|
||||
kind = "map_reward_event"
|
||||
elif source.get("task_id") and kind == "battle":
|
||||
kind = "task_battle"
|
||||
elif source.get("kind") == "sweep":
|
||||
kind = "sweep"
|
||||
if selected and selected != kind:
|
||||
continue
|
||||
stamp = source.get("finished_at") or source.get("started_at") or source.get("timestamp", source.get("time", source.get("at")))
|
||||
if type(stamp) in (int, float) and 0 <= stamp <= 253402271999:
|
||||
stamp = datetime.fromtimestamp(stamp, CHINA_TIME).strftime("%Y-%m-%d %H:%M:%S")
|
||||
outcome = source.get("outcome") or source.get("status") or source.get("phase") or source.get("result")
|
||||
if isinstance(outcome, dict):
|
||||
outcome = outcome.get("outcome") or outcome.get("status")
|
||||
outcome = _text(outcome, "unknown")
|
||||
mode = source.get("battle_mode") or source.get("execution_mode")
|
||||
row = {"id": str(index), "time": _text(stamp), "category": kind, "kind_label": BATTLE_KINDS.get(kind, "其他 / 未知"),
|
||||
"name": _text(source.get("name") or source.get("task_type_id") or source.get("stage_id") or source.get("stage") or source.get("description")),
|
||||
"team": _text(source.get("team")), "outcome": outcome, "outcome_label": OUTCOMES.get(outcome, outcome) + ("(实验近似)" if mode == "experimental" else ""),
|
||||
"message": battle_message(_text(source.get("blocked_reason") or source.get("block_reason") or source.get("message") or source.get("reason")))}
|
||||
if search and search not in " ".join(map(str, row.values())).casefold():
|
||||
continue
|
||||
dto["rows"].append(row)
|
||||
damage = {"client_v4_x10": "我方对敌最终伤害10倍,单次最高50000;角色属性保持原值", "original_1x": "原始1倍;角色属性保持原值"}.get(source.get("damage_profile"), "旧记录未标明伤害倍率")
|
||||
reward = source.get("reward")
|
||||
if isinstance(reward, dict):
|
||||
# Both wire-shaped and already normalized journal rewards occur.
|
||||
shown_reward = reward_summary(engine.catalog, reward)
|
||||
normalized_drops = reward.get("drops")
|
||||
if isinstance(normalized_drops, list):
|
||||
drop_text = [f"{_text(drop.get('name'))} ×{_text(drop.get('num'), '0')}" for drop in normalized_drops if isinstance(drop, dict)]
|
||||
shown_reward += (";" if shown_reward and drop_text else "") + ";".join(drop_text)
|
||||
else:
|
||||
shown_reward = "当前未提供奖励数据"
|
||||
dto["details"][row["id"]] = {"时间(北京时间)": row["time"], "上下文": row["kind_label"], "任务 / 地图": row["name"],
|
||||
"战斗模式": "实验模拟(近似,未完整验证)" if mode == "experimental" else "原版运行时" if mode == "original" else "记录未标明",
|
||||
"队伍": row["team"], "结果": row["outcome_label"], "详情 / 阻塞原因": row["message"], "奖励": shown_reward, "伤害规则": damage}
|
||||
dto["summary"] = f"已读取 {len(records)} 条记录,显示 {len(dto['rows'])} 条" if records else "尚无已读取的战斗记录;未记录结果不代表战斗成功"
|
||||
dto["actions"] = [{"operation": "refresh_tasks", "label": "刷新战斗记录", "payload": {}}]
|
||||
|
||||
|
||||
def _commissions(dto, engine, config, query):
|
||||
snapshot, catalog = engine.snapshot, engine.catalog
|
||||
search = _search(dto, query)
|
||||
dto["columns"] = [_column(key, label) for key, label in (("task_type_id", "编号"), ("name", "委托"), ("status", "状态"),
|
||||
("reward_money", "金币奖励"), ("reward_ke", "氪金奖励"), ("reason", "需求 / 下一步 / 阻塞原因"))]
|
||||
diagnostics = {str(row.get("task_type_id")): row for row in engine.progression_rows() if _category(row.get("category")) == "commission"}
|
||||
source = engine.tasks.rows(snapshot, engine.quest_policy, engine.policy)
|
||||
for index, (key, name, status, text, meta) in enumerate(source):
|
||||
diagnostic = diagnostics.get(str(key), {})
|
||||
reason = diagnostic.get("block_reason") or diagnostic.get("blocked_reason")
|
||||
if reason:
|
||||
status = "暂不接取" if "city" in meta else "等待条件"
|
||||
text = reason
|
||||
elif diagnostic.get("next_action"):
|
||||
text = diagnostic["next_action"]
|
||||
info = catalog.data.get("task_info", {}).get(str(key), {})
|
||||
reward = info.get("reward") or {}
|
||||
row = {"id": f"{key}:{index}", "task_type_id": str(key), "name": name, "status": status,
|
||||
"reward_money": reward.get("money", 0), "reward_ke": reward.get("ke", 0), "reason": battle_message(text),
|
||||
"city": meta.get("city"), "active": "city" not in meta}
|
||||
if search and search not in " ".join(map(str, row.values())).casefold():
|
||||
continue
|
||||
dto["rows"].append(row)
|
||||
dto["details"][row["id"]] = {"描述": info.get("des", ""), "需求 / 下一步": row["reason"],
|
||||
"交付限制": {"允许物品": engine.quest_policy.allow_items, "允许魔物": engine.quest_policy.allow_monsters,
|
||||
"单次金币上限": engine.quest_policy.max_money, "允许已支持战斗": engine.quest_policy.battle_tasks},
|
||||
"接取优先级": "氪金奖励较高的委托优先;仅接取原规划器确认可支持的委托"}
|
||||
dto["summary"] = f"今日剩余可接次数:{snapshot.raw.get('history', {}).get('loopTaskNum', '未知')};当前委托:{len(engine.tasks.current(snapshot))};按氪金奖励优先"
|
||||
|
||||
|
||||
def _exploration(dto, engine, config, query):
|
||||
planner, snapshot = engine.explore_planner, engine.snapshot
|
||||
policy = engine.explore_policy
|
||||
rows = planner.rows(snapshot, policy, engine.policy)
|
||||
area_options = [{"value": key, "label": f"{area.get('name') or key}({key})", "disabled": not planner.area_unlocked(snapshot, area),
|
||||
"reason": "" if planner.area_unlocked(snapshot, area) else f"需通关 {area.get('passStage') or '指定关卡'} 难度1"} for key, area in planner.areas.items()]
|
||||
dto["columns"] = [_row_column("enabled", "启用", ["explore_policy", "teams"], kind="boolean"), _column("team_id", "队伍"),
|
||||
_row_column("area", "地区", ["explore_policy", "teams"], kind="select", options=_options([("", "请选择地区")]) + area_options),
|
||||
_column("state_text", "状态 / 剩余"), _column("monsters", "队长 / 队员 / 队员", "members",
|
||||
_edit(["explore_policy", "teams", "{id}", "monsters"], "members", slots=["队长", "队员(等级不可高于队长)", "队员(等级不可高于队长)"])),
|
||||
_column("cost_text", "体力 / 时间"), _column("reason", "原因 / 选择规则")]
|
||||
for source in rows:
|
||||
key = str(source["team_id"])
|
||||
rule = {"enabled": False, "area": "", "monsters": []} | config["explore_policy"]["teams"].get(key, {})
|
||||
disabled = source["state"] in ("探索中", "可领取", "待核对")
|
||||
candidates = planner.member_options(snapshot, int(key), policy, engine.policy)
|
||||
options = []
|
||||
for candidate in candidates:
|
||||
mon = snapshot.monsters.get(candidate["id"])
|
||||
manual_reason = planner.monster_exclusion(snapshot, mon, engine.policy, automatic=False) if mon else "快照中不存在"
|
||||
if candidate["reason"] == "正在其他探险队":
|
||||
manual_reason = candidate["reason"]
|
||||
options.append({"value": candidate["id"], "label": f"{candidate['label']} Lv.{candidate['level']}" + (f";{candidate['reason']}" if candidate["reason"] else ""),
|
||||
"level": candidate["level"], "automatic": candidate["automatic"], "automatic_reason": candidate["reason"],
|
||||
"disabled": bool(manual_reason), "reason": manual_reason})
|
||||
for mid in rule["monsters"]:
|
||||
if not any(option["value"] == mid for option in options):
|
||||
options.append({"value": mid, "label": f"#{mid}(当前快照不存在)", "disabled": True,
|
||||
"reason": "当前快照不存在", "automatic": False, "automatic_reason": "当前快照不存在"})
|
||||
members_edit = _edit(["explore_policy", "teams", key, "monsters"], "members", options=options, disabled=disabled,
|
||||
slots=["队长", "队员(等级不可高于队长)", "队员(等级不可高于队长)"])
|
||||
dto["rows"].append({"id": key, "team_id": source["team_id"], **rule, "state": source["state"],
|
||||
"remaining": source["remaining"], "state_text": source["state"] + " / " + (duration(source["remaining"]) if source["remaining"] is not None else "—"),
|
||||
"monster_ids": source["monster_ids"], "monster_labels": [engine.catalog.monster_label(snapshot.monsters[mid]) if mid in snapshot.monsters else f"#{mid}" for mid in source["monster_ids"]],
|
||||
"member_options": options, "cost_ti": source["cost_ti"], "cost_time": source["cost_time"], "cost_text": f"{source['cost_ti']} / {duration(source['cost_time'])}",
|
||||
"manual": source["manual"], "can_auto": source["can_auto"], "reason": source["reason"] or ("手动指定;允许锁定 / 装备" if source["manual"] else "自动选空闲魔物"),
|
||||
"rule_defaults": {"enabled": False, "area": "", "monsters": []}, "rule_path": ["explore_policy", "teams", key],
|
||||
"edits": {"enabled": _edit(["explore_policy", "teams", key, "enabled"], "boolean", disabled=disabled),
|
||||
"area": _edit(["explore_policy", "teams", key, "area"], "select", options=_options([("", "请选择地区")]) + area_options, disabled=disabled),
|
||||
"monsters": members_edit}})
|
||||
dto["summary"] = f"已有 {len(rows)} 支探险队;配置 {len(policy.teams)} 支;启用 {sum(rule.enabled for rule in policy.teams.values())} 支。完成时自动领奖,再次出发由开关控制。"
|
||||
dto["details"] = {"help": "留空任一槽位恢复自动选人;手动队员必须三只不同魔物,队员等级不可高于队长;不自动花钱开队或召回"}
|
||||
|
||||
|
||||
def _maps(dto, engine, config, query):
|
||||
snapshot = engine.snapshot
|
||||
all_rows = engine.stage_cache.get(snapshot)
|
||||
resource_catalog = engine.stage_cache.catalog
|
||||
category = str(query.get("category", "all"))
|
||||
only_unlocked = _boolean(query.get("only_unlocked"), True)
|
||||
if category not in ("all", "ordinary", "resource"):
|
||||
raise ValueError("地图分类无效")
|
||||
dto["filters"] = [_filter("category", "关卡分类", category, [("all", "全部关卡"), ("ordinary", "普通关卡"), ("resource", "矿洞与门票")]),
|
||||
_filter("only_unlocked", "只看账号已解锁", only_unlocked, kind="boolean")]
|
||||
search = _search(dto, query)
|
||||
policy = engine.sweep_policy
|
||||
team_ids = engine.sweeper.team_ids(snapshot, policy)
|
||||
dto["columns"] = [_row_column("enabled", "刷图", ["sweep_policy", "rules"], kind="boolean"), _column("number", "关卡"), _column("name", "名称"),
|
||||
_row_column("level", "难度", ["sweep_policy", "rules"], kind="select", options=_options([(str(i), f"难度{i}") for i in (1, 2, 3)])),
|
||||
_column("stars_text", "星级"), _column("status", "扫荡 / 挑战状态"), _column("cost_text", "体力 / 门票:单次 / 可用 / 保留"),
|
||||
_column("drops", "可能掉落"), _row_column("limit", "本日上限", ["sweep_policy", "rules"], min=0, max=999), _column("used", "本日已开始")]
|
||||
grouped = {}
|
||||
for stage in all_rows:
|
||||
if stage.category in ("mine", "ticket") and stage.level != "1":
|
||||
continue
|
||||
grouped.setdefault(stage.stage_id, []).append(stage)
|
||||
dto["groups"] = []
|
||||
cities = set()
|
||||
for key, stages in sorted(grouped.items(), key=lambda pair: (pair[1][0].city, pair[1][0].number, pair[0])):
|
||||
first = stages[0]
|
||||
resource = first.category in ("mine", "ticket")
|
||||
if category == "ordinary" and first.category != "ordinary" or category == "resource" and not resource:
|
||||
continue
|
||||
if only_unlocked and not any(stage.unlocked for stage in stages):
|
||||
continue
|
||||
if search and search not in (first.city_name + key + first.number + first.name + " ".join(stage.drops for stage in stages)).casefold():
|
||||
continue
|
||||
saved = config["sweep_policy"]["rules"].get(key, {})
|
||||
chosen = next((stage for stage in stages if stage.level == saved.get("level")), None)
|
||||
chosen = chosen or next((stage for stage in reversed(stages) if stage.unlocked), first)
|
||||
defaults = {"enabled": False, "level": chosen.level, "limit": 3}
|
||||
rule = defaults | saved
|
||||
reason = engine.map_stage_reason(snapshot, chosen, policy, team_ids=team_ids)
|
||||
costs = [{"kind": "stamina", "label": "体力", "required": chosen.stamina,
|
||||
"available": int(snapshot.raw["master"].get("ti") or 0), "reserve": policy.keep_stamina}]
|
||||
base = resource_catalog.data.get("stage_info", {}).get(key, {}).get("cost") or {}
|
||||
if resource:
|
||||
for item_id, count in item_requirements(base.get("items") or []).items():
|
||||
costs.append({"kind": "item", "type_id": item_id, "label": resource_catalog.data.get("item_names", {}).get(item_id, item_id),
|
||||
"required": count, "available": available_item_count(snapshot, item_id), "reserve": policy.keep_tickets})
|
||||
if not chosen.battle_available:
|
||||
reason = "该资源关卡缺少已提取的战斗配置,未启用"
|
||||
elif not policy.allow_special:
|
||||
reason = "尚未开启“允许矿洞 / 门票关卡”资源关开关"
|
||||
else:
|
||||
insufficient = next((cost for cost in costs if cost["available"] - cost["required"] < cost["reserve"]), None)
|
||||
if insufficient:
|
||||
reason = f"{insufficient['label']}不足:单次需 {insufficient['required']},可用 {insufficient['available']},保留 {insufficient['reserve']}"
|
||||
reason = reason or "将按实际模拟结果挑战;不是扫荡"
|
||||
cost_text = "\n".join(f"{cost['label']} 单次 {cost['required']} / 可用 {cost['available']} / 保留 {cost['reserve']}" for cost in costs)
|
||||
levels = [{"value": stage.level, "label": f"难度 {stage.level}" + ("(已通关)" if stage.passed else ""), "disabled": not (stage.unlocked and stage.open)} for stage in stages]
|
||||
dto["rows"].append({"id": key, "number": first.number, "name": first.name, "group": str(first.city), "city_name": first.city_name, "category": first.category,
|
||||
**rule, "stars": first.stars, "stars_text": "★" * first.stars + "☆" * max(0, 3 - first.stars), "status": reason or ("可扫荡" if chosen.sweep else "将模拟挑战"),
|
||||
"unlocked": chosen.unlocked, "open": chosen.open, "sweep": chosen.sweep, "costs": costs, "cost_text": cost_text, "drops": chosen.drops,
|
||||
"used": engine.sweeper.used(snapshot, chosen), "rule_defaults": defaults, "rule_path": ["sweep_policy", "rules", key],
|
||||
"edits": {"enabled": _edit(["sweep_policy", "rules", key, "enabled"], "boolean", disabled=not any(stage.unlocked and stage.open for stage in stages)),
|
||||
"level": _edit(["sweep_policy", "rules", key, "level"], "select", options=levels)}})
|
||||
if first.city not in cities:
|
||||
cities.add(first.city)
|
||||
dto["groups"].append({"id": str(first.city), "label": first.city_name, "collapsed": not bool(search)})
|
||||
pending = engine.sweeper.state.get("pending")
|
||||
dto["summary"] = f"已解锁 {sum(stage.unlocked for stage in all_rows)} 个难度;显示 {len(dto['rows'])} 关;勾选 {sum(bool(rule.get('enabled')) for rule in policy.rules.values())} 关"
|
||||
dto["details"] = {"pending": {"stage": _text(pending.get("stage")), "phase": _text(pending.get("phase"))} if pending else None,
|
||||
"help": "普通关卡三个难度全部通关可扫荡;资源关卡需单独开启并逐关勾选,仅原入口难度1;未支持内容保留具体原因,随机掉落并非必得"}
|
||||
dto["actions"] = [{"operation": "refresh_maps", "label": "刷新关卡", "payload": {}},
|
||||
{"operation": "reset_map_pending", "label": "核对未完成记录", "payload": {"confirm": True}, "confirm": "按服务器证据核对;证据不完整时会保留记录"}]
|
||||
|
||||
|
||||
def _statistics(dto, engine, config, query):
|
||||
catalog = engine.stage_cache.catalog
|
||||
source = str(query.get("source", "all"))
|
||||
metric = str(query.get("metric", "rate"))
|
||||
if metric == "probability":
|
||||
metric = "rate"
|
||||
if source not in ("all", "sweep", "event") or metric not in ("rate", "per_stamina"):
|
||||
raise ValueError("数据分析来源或指标无效")
|
||||
stage_id, level = str(query.get("stage_id") or query.get("stage") or ""), str(query.get("level", "3"))
|
||||
data = engine.sweeper.statistics.snapshot(engine.snapshot.raw["master"]["id"]) if engine.snapshot else {"totals": {}, "drops": {}}
|
||||
dto["filters"] = [_filter("source", "统计范围", source, [("all", "扫荡+奖励事件"), ("sweep", "普通扫荡"), ("event", "奖励事件")]),
|
||||
_filter("metric", "图表指标", metric, [("rate", "实测掉落率"), ("per_stamina", "每点体力数量")])]
|
||||
search = _search(dto, query)
|
||||
stages, choices = [], []
|
||||
for key, stage in sorted(catalog.data.get("stage_info", {}).items(), key=lambda pair: (int(pair[1].get("city") or 0), pair[1].get("tagname") or pair[0])):
|
||||
label = f"{stage.get('tagname') or key} {stage.get('name') or key}"
|
||||
if search and search not in (key + label).casefold():
|
||||
continue
|
||||
levels = [{"id": str(number), "level": str(number), "value": str(number), "label": f"{label} / 难度 {number}",
|
||||
"sweep": data["totals"].get(f"{key}:{number}:sweep", {}).get("n", 0),
|
||||
"event": data["totals"].get(f"{key}:{number}:event", {}).get("n", 0)} for number in sorted(stage.get("level", {}), key=int)]
|
||||
city_id = str(int(stage.get("city") or 0))
|
||||
city = catalog.data["game_setting"].get("cityInfo", {}).get(city_id, {}).get("name", f"地区 {city_id}")
|
||||
stages.append({"id": key, "label": label, "city_id": city_id, "city_name": city, "levels": levels,
|
||||
"sweep": sum(row["sweep"] for row in levels), "event": sum(row["event"] for row in levels)})
|
||||
choices.append((key, label))
|
||||
dto["stages"] = stages
|
||||
dto["filters"] += [_filter("stage_id", "关卡", stage_id, [("", "请选择关卡"), *choices])]
|
||||
stage = catalog.data.get("stage_info", {}).get(stage_id)
|
||||
levels = [(str(number), f"难度 {number}") for number in sorted(stage.get("level", {}), key=int)] if stage else [(str(i), f"难度{i}") for i in (1, 2, 3)]
|
||||
dto["filters"].append(_filter("level", "难度", level, levels))
|
||||
dto["columns"] = [_column(key, label) for key, label in (("name", "掉落物"), ("kind_label", "类别"), ("hits", "出现次数"), ("units", "总数量"),
|
||||
("samples", "样本数"), ("rate_text", "实测掉落率"), ("average", "平均数量/次"), ("per_stamina", "每点体力数量"), ("interval_text", "95%区间"), ("configured_text", "静态配置"))]
|
||||
dto["chart"] = {"type": "horizontal_bar", "metric": metric, "label": "实测掉落率" if metric == "rate" else "每点体力数量", "series": [], "max": 1 if metric == "rate" else None,
|
||||
"unit": "ratio" if metric == "rate" else "个 / 体力", "empty_reason": "请选择关卡和难度"}
|
||||
dto["charts"] = [dto["chart"]]
|
||||
if not stage_id:
|
||||
dto["summary"] = "请选择关卡和难度;关卡来自本地配置,统计按当前账号读取"
|
||||
return
|
||||
if stage is None or level not in stage.get("level", {}):
|
||||
raise ValueError("数据分析的关卡或难度无效")
|
||||
totals, rows = analyze(catalog, data, stage_id, level, source)
|
||||
counts = {kind: data["totals"].get(f"{stage_id}:{level}:{kind}", {}).get("n", 0) for kind in ("sweep", "event")}
|
||||
dto["totals"] = totals | counts | {"source": source, "stage_id": stage_id, "level": level}
|
||||
for row in rows:
|
||||
interval = row["interval"]
|
||||
dto["rows"].append({"id": row["key"], **row, "kind_label": {"item": "物品", "egg": "魔物蛋", "monster": "魔物"}.get(row["kind"], "未知"),
|
||||
"rate_text": f"{row['rate'] * 100:.2f}%" if row["rate"] is not None else "—", "interval_text": f"{interval[0] * 100:.1f}%~{interval[1] * 100:.1f}%" if interval else "—",
|
||||
"configured_text": "可能掉落" if row["configured"] else "实际观测"})
|
||||
dto["chart"]["series"] = [{"id": row["key"], "label": row["name"], "value": row[metric], "hits": row["hits"], "samples": row["samples"]}
|
||||
for row in rows if row[metric] is not None]
|
||||
dto["chart"]["empty_reason"] = "尚无此范围的已确认样本" if not totals["n"] else "没有已知的非零体力消耗,暂不计算体力效率" if metric == "per_stamina" and not totals["spent"] else ""
|
||||
if metric == "per_stamina":
|
||||
dto["chart"]["max"] = max([point["value"] for point in dto["chart"]["series"]] + [0]) * 1.15 or 1
|
||||
dto["summary"] = f"{stage.get('tagname') or stage_id} {stage.get('name') or stage_id} / 难度 {level};扫荡 {counts['sweep']} / 奖励事件 {counts['event']};当前范围 {totals['n']} 个已确认样本;累计金币 {totals['money']}、经验 {totals['exp']};已知体力消耗样本 {totals['known']}/{totals['n']},消耗体力 {totals['spent']},返还体力 {totals['ti']}"
|
||||
dto["details"] = {"help": "掉落率=出现次数/已确认样本数;每点体力数量只计已知消耗样本,不扣减奖励返还体力;实测值不是官方掉率;95%区间反映样本不确定性",
|
||||
"statistics_error": "本地统计读取失败,请查看服务器日志" if data.get("error") else ""}
|
||||
|
||||
|
||||
def _execution_plans(dto, engine, config, query):
|
||||
dto["columns"] = [_column("kind", "类型"), _column("description", "计划动作")]
|
||||
dto["rows"] = _plans(engine)
|
||||
dto["summary"] = f"{len(dto['rows'])} 项计划;仅预览,开启顶部策略后由原引擎执行"
|
||||
dto["details"] = {"notes": list(dict.fromkeys(engine.planner.notes))}
|
||||
|
||||
|
||||
def _yields(dto, engine, config, query):
|
||||
search = _search(dto, query)
|
||||
dto["columns"] = [_column(key, label) for key, label in (("type_id", "魔物编号"), ("name", "名称"), ("star", "星"), ("time_text", "培育时间"),
|
||||
("sell_money", "派遣金币"), ("sell_exp", "基础经验"), ("gold_per_hour", "金币/小时"), ("exp_per_hour", "经验/小时"), ("ratio", "金币/经验"), ("recommendation", "建议(未计保留条件)"))]
|
||||
threshold = config["policy"]["coins_per_exp"]
|
||||
for type_id in engine.catalog.monsters:
|
||||
info = engine.catalog.monster(type_id)
|
||||
if int(info.get("star", 0)) not in config["yield_stars"] or search and search not in (type_id + str(info.get("name", ""))).casefold():
|
||||
continue
|
||||
total = engine.catalog.total_time(type_id)
|
||||
if not total:
|
||||
continue
|
||||
money, exp = info.get("sell_money", 0), info.get("sell_exp", 0)
|
||||
ratio = money / exp if exp else None
|
||||
dto["rows"].append({"id": type_id, "type_id": int(type_id), "name": info.get("name", "未知"), "star": info.get("star", "?"), "time_total": total, "time_text": duration(total),
|
||||
"sell_money": money, "sell_exp": exp, "gold_per_hour": round(money * 3600 / total, 2), "exp_per_hour": round(exp * 3600 / total, 2),
|
||||
"ratio": round(ratio, 3) if ratio is not None else "无经验", "recommendation": "适合喂养" if ratio is not None and ratio < threshold else "适合派遣"})
|
||||
dto["summary"] = f"本地资料共 {len(engine.catalog.monsters)} 种魔物,当前显示 {len(dto['rows'])} 种;CSV/XLSX覆盖值仅影响收益计算"
|
||||
dto["actions"].append({"operation": "import_yields", "label": "导入CSV / XLSX收益资料", "accept": ".csv,.xlsx"})
|
||||
dto["details"] = {"import_columns": ["typeId / 编号 / 魔物ID", "sell_money / 派遣金币", "sell_exp / 强化经验", "time_total / 孵化秒数"]}
|
||||
|
||||
|
||||
_BUILDERS.update({"login": _login, "incubator": _incubator, "bag": _bag, "ranch": _ranch,
|
||||
"daily": _daily, "hatching": _hatching, "mainline": _mainline, "battles": _battles,
|
||||
"gifts": _gifts, "commissions": _commissions, "exploration": _exploration, "maps": _maps,
|
||||
"statistics": _statistics, "plans": _execution_plans, "yields": _yields})
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd -- "$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
|
||||
if [ -x .venv-web/bin/python ]; then
|
||||
exec .venv-web/bin/python -B -m ranch_web "$@"
|
||||
fi
|
||||
exec python3 -B -m ranch_web "$@"
|
||||
Reference in New Issue
Block a user