From 558f91c7c3e85d7679d8df9570a94e65c6a1eba9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=99=93=E4=B8=B6=E6=A2=A6=E4=B8=B6=E4=BB=81?= <74444214+Daydreamer114@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:21:12 +0800 Subject: [PATCH] =?UTF-8?q?feat(garrison):=20=E5=8D=AB=E6=88=8D=E5=8D=8F?= =?UTF-8?q?=E8=AE=AE=E9=80=9F=E5=88=B7=EF=BC=88=E6=A0=B8=E5=BF=83=E8=A1=A5?= =?UTF-8?q?=E4=B8=81=20+=20=E5=85=8D=E8=B4=B9=E9=A2=86=E5=8F=96=E6=A0=B8?= =?UTF-8?q?=E5=AF=B9=E6=94=BE=E5=AE=BD=EF=BC=89(#113)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增卫戍协议(三合一勋章速刷)自动化:下载校验第三方核心、一账号一宿主进程、MaaFramework 截图点击。 修复两处卡流程:点「准备就绪」后弹出的确认框不被识别(核心落 unknown 空转 90 秒),改为核心文本补丁机制认出该弹窗并点「确认」;免费领取时名字 OCR 核对过严导致三合一赠送高星干员领丢,放宽短名与拉丁名容差,并在详情标题可读时信任详情。 --- README.md | 1 + backend/core/api.py | 56 +++- backend/core/garrison.py | 479 ++++++++++++++++++++++++++++++++ backend/core/garrisondl.py | 399 ++++++++++++++++++++++++++ backend/core/settings.py | 5 + backend/main.py | 5 + docs/backend.md | 42 +++ frontend/app.js | 307 +++++++++++++++++++- frontend/index.html | 105 ++++++- frontend/style.css | 111 ++++++++ resources/garrison/host.mjs | 202 ++++++++++++++ resources/garrison/patches.json | 24 ++ tools/smoketest/smoke_test.py | 181 ++++++++++++ 13 files changed, 1909 insertions(+), 8 deletions(-) create mode 100644 backend/core/garrison.py create mode 100644 backend/core/garrisondl.py create mode 100644 resources/garrison/host.mjs create mode 100644 resources/garrison/patches.json diff --git a/README.md b/README.md index bcc5344..ec1b605 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ MAA-PRTS\ | 抽卡统计 | 「抽卡统计」模块:总抽数、六星数/出率、平均出六星、距上次六星,按卡池分开列(每池挂出自己的六星与第几抽)、星级分布、最近记录;终末地分「角色寻访 / 武器申领」两个 tab(两套保底不能混算)。记录只增不减地存在本地,没网也能看 | | 终末地抽卡 | 角色寻访(5 类池子全翻页)+ 武器申领分开统计:角色看抽数/六星/出率/保底,武器单独两张卡;记录接口只给最近一段窗口,本地只增不减,滑走的旧记录不会丢 | | 森空岛签到 | 「森空岛签到」模块:左「全局签到」一键签列表里所有账号(明日方舟 + 终末地),右「单号签到」只签当前账号;两边各一块日志,跑完给「成功 / 已签到 / 失败 / 跳过」汇总。先查状态再签,今天签过的直接说已签到,不会重复打接口 | +| 卫戍协议 | 「卫戍协议」模块:策略刻章速刷(极速模拟自动打满 31 个策略目标)。连接参数从当前账号绑定的 MAA 配置里抄(MuMu 自动用快速截图 Extras、雷电→ldplayer、PC 官方客户端→pc;默认极速 / 1.5× / 3 胜),每个账号一个独立速刷后端、自己的检查点,可多账号同时跑。核心包(约 61MB)不随本程序分发:首次打开该页自动从小黑盒官方 CDN 下载并逐文件校验(装过小黑盒的用本机记录拿最新版),断点续传;另需 Node.js 20+ | | 练度统计 | 干员数 / 精二 / 满级 / 六星 / 专三 / 模组 / 潜能 / 信赖 | | 缺卡清单 | 点顶部「缺卡」,按星级列出还没有的干员名字 | | 作业匹配 | 输入关卡代号(`TL-10`)、章节号(`2` 返回整章:主线 + S 支线 + TR 教学)、活动(`act55side`)、系列(`TR-`)或中文名,逐份比对干员与练度 | diff --git a/backend/core/api.py b/backend/core/api.py index 192e0ea..a30df4e 100644 --- a/backend/core/api.py +++ b/backend/core/api.py @@ -7,8 +7,8 @@ import traceback import urllib.parse -from . import (accounts, agent, appupdate, asstlog, copilot, gacha, maa, - maaplan, multiacct, operbox, packsync, paradox, resources, +from . import (accounts, agent, appupdate, asstlog, copilot, gacha, garrison, + maa, maaplan, multiacct, operbox, packsync, paradox, resources, settings, signin, skills, sklogin, tasks, updater, version, watch) WEB = settings.static_dir() @@ -581,6 +581,51 @@ def _mut(snap): return {'file': file, 'imported': len(imp)} +# ---------------------------------------------------------------- 卫戍协议 +def api_garrison_status(q, _body): + """速刷面板状态:环境(Node/核心)+ 从 MAA 配置抄的默认值 + 运行态 + + 会懒启动该账号的速刷后端(首次打开面板慢几秒是正常的)。 + 核心缺失时附带下载进度(needsDownload / download),前端自动开始下载。 + """ + return garrison.status(_account_for(q.get('file'))) + + +def api_garrison_download(_q, _body): + """开始/继续核心包下载(幂等),返回当前下载状态""" + return garrison.start_download() + + +def _garrison_options(q, body): + """test/start/resume 共用:账号 + 前端提交的连接选项""" + body = body or {} + file = _account_for(q.get('file') or body.get('file')) + return file, body.get('options') or {} + + +def api_garrison_test(q, body): + """测试连接(截图 + OCR + 活动页自检,只读不点击)""" + file, opts = _garrison_options(q, body) + return garrison.test(file, opts) + + +def api_garrison_start(q, body): + """开始速刷(游戏先停在卫戍协议活动主界面)""" + file, opts = _garrison_options(q, body) + return garrison.start(file, opts) + + +def api_garrison_resume(q, body): + """从该账号的上次检查点恢复""" + file, opts = _garrison_options(q, body) + return garrison.resume(file, opts) + + +def api_garrison_stop(q, body): + body = body or {} + return garrison.stop(_account_for(q.get('file') or body.get('file'))) + + def api_task(q, _body): tid = q.get('id') t = tasks.get(tid, int(q.get('since') or 0)) @@ -842,6 +887,13 @@ def api_export(_q, body): '/api/gacha': api_gacha, '/api/gacha/sync': api_gacha_sync, '/api/signin/run': api_signin_run, + # 卫戍协议·策略刻章速刷 + '/api/garrison/status': api_garrison_status, + '/api/garrison/download/start': api_garrison_download, + '/api/garrison/test': api_garrison_test, + '/api/garrison/start': api_garrison_start, + '/api/garrison/resume': api_garrison_resume, + '/api/garrison/stop': api_garrison_stop, # 观测层(M2/M3) '/api/watch/status': api_watch_status, '/api/watch/start': api_watch_start, diff --git a/backend/core/garrison.py b/backend/core/garrison.py new file mode 100644 index 0000000..201c3d5 --- /dev/null +++ b/backend/core/garrison.py @@ -0,0 +1,479 @@ +# -*- coding: utf-8 -*- +"""卫戍协议·策略刻章速刷:Node 宿主进程管理 + HTTP 转发 + +移植自独立版 ``garrison-standalone``(小黑盒扩展分离产物)。核心 +``service.mjs``(GPL-3.0-or-later,含 MaaFramework 原生模块,~114MB) +**不进仓库、不进安装包**——它是被 ``node host.mjs`` 以子进程方式加载的 +独立程序,Python 这边只做进程编排与代理转发。核心目录按优先级检测: + +1. ``settings.garrisonCoreDir``(用户手动指定) +2. ``<运行根>/garrison/core``(把 ``medal-farm-v1.1.4/core`` 拷到这里即可) +3. ``<运行根>/garrison/medal-farm-v1.1.4/core``(整个独立包解压进 garrison/) +4. ``<运行根>/garrison-standalone/medal-farm-v1.1.4/core``(解压即用) + +多账号:每个账号一个 Node 宿主进程(懒启动、随机端口 + token 握手), +各自连各自 MAA 配置里的模拟器地址,互不干扰;检查点按账号存 +``config/garrison/<账号文件名>.checkpoint.json``。宿主带 --parent-pid +看门狗,Python 崩溃后它们会自己退出,不会变成孤儿继续点游戏。 + +连接默认值从**当前账号绑定 MAA** 的 gui.new.json 解析(ConnectSettings): +MuMu → 设备 mumu + MuMu Extras 快速截图;雷电 → ldplayer;PC 官方客户端 +→ pc;模拟模式默认极速、操作速度 1.5、目标 3 胜。 +""" +from __future__ import annotations + +import io +import json +import os +import queue +import shutil +import subprocess +import threading +import time +import urllib.error +import urllib.request +import uuid + +from . import applog, garrisondl, maa, settings + +CREATE_NO_WINDOW = 0x08000000 if os.name == 'nt' else 0 + +HOST_JS = os.path.join(settings.RES, 'resources', 'garrison', 'host.mjs') +PATCH_FILE = os.path.join(settings.RES, 'resources', 'garrison', 'patches.json') + +DEVICES = ('mumu', 'ldplayer', 'pc') +SHOT_METHODS = ('auto', 'fast', 'adb') +BUSY = ('running', 'starting', 'stopping') + +# MAA ConnectSettings.Config(模拟器类型)→ 核心的 device / 截图方式。 +# MuMu(含 ARM 版)走 MuMu Extras(快速截图);雷电的 Extras 需 9.1.32+ +# 且实例由核心自找,稳妥起见 auto;其余 ADB 类一律当 mumu(核心的默认)。 +_KIND_MAP = { + 'MuMuEmulator12': ('mumu', 'fast'), + 'MuMuArm': ('mumu', 'fast'), + 'LDPlayer': ('ldplayer', 'auto'), + 'PC': ('pc', 'auto'), +} + + +# ---------------------------------------------------------------- 环境 +def node_exe() -> str: + """Node.js 可执行文件(核心是 ESM + 原生模块,需要 Node ≥ 20)""" + try: + return shutil.which('node') or '' + except Exception: + return '' + + +def core_dir() -> str: + """按约定位置找卫戍协议核心(含 service.mjs 的目录),找不到返回 ''""" + cands = [] + try: + cands.append(settings.norm_dir(settings.load().get('garrisonCoreDir') or '')) + except Exception: + pass + root = settings.project_root() + cands += [ + os.path.join(root, 'garrison', 'core'), + os.path.join(root, 'garrison', 'medal-farm-v1.1.4', 'core'), + os.path.join(root, 'garrison-standalone', 'medal-farm-v1.1.4', 'core'), + ] + for d in cands: + if d and os.path.isfile(os.path.join(d, 'service.mjs')): + return d + return '' + + +def _patch_rules(): + try: + with io.open(PATCH_FILE, encoding='utf-8') as f: + return (json.load(f) or {}).get('patches') or [] + except (OSError, ValueError): + return [] + + +def apply_core_patches(core: str) -> dict: + """给核心 service.mjs 打最小文本补丁(幂等,失败不影响启动) + + 核心是第三方 GPL 混淆包,不进仓库、由 garrisondl.py 下载;它偶尔认不出 + 游戏新弹窗(如「确认准备就绪吗?当前仍处于临时整备区…」),落进 unknown + 空转 90 秒后报错。补这种缺口走规则文件里的纯文本替换,比在 MAA-PRTS 侧 + 再挂一个 adb 看门狗去跟核心抢截图/输入安全得多:点哪儿仍由核心自己按 + OCR 文本算,分辨率与缩放天然自适应。 + + 首次改动前留 ``service.mjs.orig`` 备份;核心升级后规则脱靶(find 找不到) + 只记日志跳过,绝不动文件。返回 ``{applied, skipped, miss, error}``。 + """ + rules = _patch_rules() + out = {'applied': 0, 'skipped': 0, 'miss': 0, 'error': ''} + if not rules: + return out + path = os.path.join(core, 'service.mjs') + try: + with io.open(path, encoding='utf-8') as f: + src = f.read() + except OSError as e: + out['error'] = str(e) + return out + text = src + for r in rules: + find = r.get('find') or '' + repl = r.get('replace') or '' + if not find or not repl: + continue + if repl in text: # 已经打过了 + out['skipped'] += 1 + continue + if find not in text: # 核心换了写法:不硬来 + out['miss'] += 1 + applog.log('[卫戍协议] 核心补丁「%s」未命中,跳过(核心版本可能变了)' + % (r.get('id') or '?')) + continue + text = text.replace(find, repl, 1) + out['applied'] += 1 + if text == src: + return out + try: + bak = path + '.orig' + if not os.path.isfile(bak): + shutil.copy2(path, bak) + tmp = path + '.tmp' + with io.open(tmp, 'w', encoding='utf-8', newline='') as f: + f.write(text) + os.replace(tmp, path) + except OSError as e: + out['error'] = str(e) + applog.log('[卫戍协议] 核心补丁写入失败:%s' % e) + return out + applog.log('[卫戍协议] 核心补丁已应用 %d 条(已在位 %d,未命中 %d)' + % (out['applied'], out['skipped'], out['miss'])) + return out + + +def _maa_dir_for(file: str) -> str: + """账号绑定的 MAA 根目录,没有就回退全局默认(与 api._maa_dir_for 同口径, + 这里不能 import api——api 反过来要 import 本模块)""" + if file: + try: + from . import accounts + snap = accounts.get_account(file) + d = settings.norm_dir((snap.get('maa') or {}).get('dir') or '') + if d: + return d + except Exception: + pass + return settings.load()['maaDir'] + + +def defaults(file: str): + """速刷默认参数:从账号绑定 MAA 的连接配置里抄。 + + 返回 ``(options, 来源)``;MAA 配置读不到时给核心自己的兜底值 + (mumu + 16384),前端会展示来源让用户知道这份默认值从哪来。 + """ + opts = { + 'device': 'mumu', 'mode': 'quick', 'speed': 1.5, 'medalWins': 3, + 'adbAddress': '127.0.0.1:16384', 'adbPath': '', + 'screenshotMethod': 'auto', 'pcUiScale': 90, + } + src = {'kind': '', 'profile': '', 'maaDir': ''} + try: + d = _maa_dir_for(file) + if d: + cfg = maa._load_cfg(d) + configs = cfg.get('Configurations') or {} + name = cfg.get('Current') or '' + c = (configs.get(name) + or (next(iter(configs.values())) if configs else {}) or {}) + cs = ((c.get('Gui') or {}).get('ConnectSettings') or {}) + kind = str(cs.get('Config') or '') + dev, shot = _KIND_MAP.get(kind, ('mumu', 'auto')) + opts['device'] = dev + opts['screenshotMethod'] = shot + addr = str(cs.get('Address') or '').strip() + if addr: + opts['adbAddress'] = addr + opts['adbPath'] = str(cs.get('AdbPath') or '').strip() + src = {'kind': kind, 'profile': name, 'maaDir': d} + except Exception: + pass + return opts, src + + +def sanitize(body: dict) -> dict: + """前端提交的选项清洗:只放行核心认识的枚举与范围,其余回默认""" + body = body or {} + dft, _src = defaults('') # 兜底基底(读不到 MAA 配置时的那套) + device = body.get('device') if body.get('device') in DEVICES else dft['device'] + try: + speed = min(5.0, max(0.5, float(body.get('speed') or 1.5))) + except (TypeError, ValueError): + speed = 1.5 + return { + 'device': device, + 'mode': body.get('mode') if body.get('mode') in ('quick', 'standard') else 'quick', + 'medalWins': 6 if str(body.get('medalWins')) == '6' else 3, + 'speed': speed, + 'adbAddress': str(body.get('adbAddress') or dft['adbAddress']).strip() or dft['adbAddress'], + 'adbPath': str(body.get('adbPath') or '').strip(), + 'screenshotMethod': (body.get('screenshotMethod') + if body.get('screenshotMethod') in SHOT_METHODS + else dft['screenshotMethod']), + 'pcUiScale': 100 if str(body.get('pcUiScale')) == '100' else 90, + } + + +# ---------------------------------------------------------------- 宿主进程 +# file → {'proc', 'port', 'token', 'core', 'started', 'logPath'} +_HOSTS: dict[str, dict] = {} +_lock = threading.Lock() +_SPAWN_LOCK = threading.Lock() # 同一账号并发首启只放一个进去 + + +def _stem(file: str) -> str: + return os.path.splitext(os.path.basename(file or 'account'))[0] + + +def _checkpoint_path(file: str) -> str: + return os.path.join(settings.CONFIG_DIR, 'garrison', + '%s.checkpoint.json' % _stem(file)) + + +def _log_path(file: str) -> str: + return os.path.join(settings.DEBUG_DIR, 'garrison-%s.log' % _stem(file)) + + +def _alive(h) -> bool: + try: + return bool(h) and h['proc'].poll() is None + except Exception: + return False + + +def host_of(file: str): + """该账号的宿主进程信息(可能为 None,不启动)""" + with _lock: + return _HOSTS.get(file) + + +def _reap(file, h): + with _lock: + if _HOSTS.get(file) is h: + _HOSTS.pop(file, None) + try: + if _alive(h): + h['proc'].terminate() + except Exception: + pass + + +def ensure_host(file: str) -> dict: + """拿到该账号的宿主(没有就启动一个);起不来抛 RuntimeError""" + with _SPAWN_LOCK: + h = host_of(file) + if _alive(h): + return h + if h: + _reap(file, h) + return _spawn(file) + + +def _spawn(file: str) -> dict: + node = node_exe() + if not node: + raise RuntimeError('找不到 Node.js:卫戍协议核心需要 Node.js 20 以上,' + '装好后再来(https://nodejs.org)') + core = core_dir() + if not core: + raise RuntimeError('核心包还没下载好:打开卫戍协议页会自动下载安装') + apply_core_patches(core) + if not os.path.isfile(HOST_JS): + raise RuntimeError('缺少宿主脚本:%s' % HOST_JS) + + ckpt = _checkpoint_path(file) + os.makedirs(os.path.dirname(ckpt), exist_ok=True) + os.makedirs(settings.DEBUG_DIR, exist_ok=True) + token = uuid.uuid4().hex + argv = [node, HOST_JS, + '--core', core, '--checkpoint', ckpt, + '--token', token, '--parent-pid', str(os.getpid()), '--port', '0'] + logp = _log_path(file) + try: + logf = io.open(logp, 'ab', buffering=0) + except OSError: + logf = subprocess.DEVNULL + try: + proc = subprocess.Popen( + argv, cwd=core, stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=logf, + creationflags=CREATE_NO_WINDOW) + except OSError as e: + raise RuntimeError('速刷后端起不来:%s' % e) + + # stdout 只等一行握手:READY 。加载原生模块(sharp/onnx) + # 首次可能要几秒,给 45 秒;放队列里等,超时按行读余量防止卡死。 + q: queue.Queue = queue.Queue() + + def reader(): + try: + for line in proc.stdout: # type: ignore[union-attr] + q.put(line.decode('utf-8', 'ignore').strip()) + except Exception: + pass + finally: + q.put(None) # 流关闭(进程退出) + + threading.Thread(target=reader, daemon=True, + name='garrison-%s' % _stem(file)).start() + deadline = time.time() + 45 + ready = None + while time.time() < deadline: + try: + line = q.get(timeout=1.0) + except queue.Empty: + if not _alive({'proc': proc}): + break + continue + if line is None: + break + if line.startswith('READY '): + ready = line.split() + break + if not ready or len(ready) < 2: + rc = proc.poll() + _reap(file, {'proc': proc}) + raise RuntimeError('速刷后端没就绪(%s)。排查:%s' + % ('退出码 %s' % rc if rc is not None else '45 秒内没握手', + logp)) + try: + port = int(ready[1]) + except (IndexError, ValueError): + _reap(file, {'proc': proc}) + raise RuntimeError('速刷后端握手行不认识:%r' % ' '.join(ready)) + + h = {'proc': proc, 'port': port, 'token': token, 'core': core, + 'started': time.time(), 'logPath': logp} + with _lock: + _HOSTS[file] = h + applog.log('[卫戍协议] %s 的速刷后端已启动(端口 %d,核心 %s)' + % (_stem(file), port, core)) + return h + + +def _call(h: dict, method: str, path: str, body=None, timeout=30.0) -> dict: + url = 'http://127.0.0.1:%d%s' % (h['port'], path) + data = json.dumps(body).encode('utf-8') if body is not None else None + headers = {'x-garrison-token': h['token']} + if data is not None: + headers['Content-Type'] = 'application/json' + req = urllib.request.Request(url, data=data, method=method, headers=headers) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.loads(r.read().decode('utf-8')) + except urllib.error.HTTPError as e: + try: + msg = json.loads(e.read().decode('utf-8')).get('error') or '' + except Exception: + msg = '' + raise RuntimeError(msg or ('速刷后端返回 %d' % e.code)) + except (urllib.error.URLError, OSError, ValueError) as e: + raise RuntimeError('速刷后端没响应(%s),详情见 %s' + % (getattr(e, 'reason', e), h.get('logPath', ''))) + + +def _state_of(h: dict) -> dict: + return _call(h, 'GET', '/api/state', timeout=10) or {} + + +# ---------------------------------------------------------------- 对外(api 层调) +def status(file: str) -> dict: + """卫戍协议面板的一揽子状态:环境 + 默认值 + 当前运行态(懒启动宿主)。 + + 核心缺失时带 ``needsDownload`` + 下载进度(garrisondl 的状态机), + 前端据此自动开始下载并显示进度条;下载是全局一份(不分账号)。 + """ + node = node_exe() + core = core_dir() + dft, src = defaults(file) + out = { + 'nodeOk': bool(node), 'coreOk': bool(core), 'coreDir': core, + 'defaults': dft, 'fromMaa': src, + 'ready': False, 'running': False, 'state': None, + 'hasCheckpoint': os.path.isfile(_checkpoint_path(file)), + 'needsDownload': not core, + 'download': garrisondl.state(), + } + if node and core: + try: + h = ensure_host(file) + st = _state_of(h) + out['state'] = st.get('state') + out['hasCheckpoint'] = bool(st.get('hasCheckpoint', out['hasCheckpoint'])) + status_ = (out['state'] or {}).get('status') + out['running'] = status_ in BUSY + out['ready'] = True + except Exception as e: + out['error'] = str(e) + return out + + +def start_download() -> dict: + """开始(或继续)核心包下载;幂等,返回当前下载状态""" + return garrisondl.start() + + +def test(file: str, options: dict) -> dict: + h = ensure_host(file) + return _call(h, 'POST', '/api/test', sanitize(options), timeout=120) + + +def start(file: str, options: dict) -> dict: + h = ensure_host(file) + return _call(h, 'POST', '/api/start', sanitize(options), timeout=30) + + +def resume(file: str, options: dict) -> dict: + h = ensure_host(file) + return _call(h, 'POST', '/api/resume', sanitize(options), timeout=30) + + +def stop(file: str) -> dict: + h = host_of(file) + if not _alive(h): + raise ValueError('当前没有速刷任务在跑') + return _call(h, 'POST', '/api/stop', {}, timeout=15) # type: ignore[arg-type] + + +def stop_all(timeout=6.0): + """程序退出前收尾:通知各宿主自行 stop+dispose,等不及再硬杀。 + + 正在跑的对局点掉就停(核心的 stop 是可恢复的,检查点已落盘), + 所以这里不做长等待——用户关窗口的耐心比一局速刷宝贵。 + """ + with _lock: + hosts = list(_HOSTS.items()) + if not hosts: + return [] + for _file, h in hosts: + try: + _call(h, 'POST', '/api/shutdown', {}, timeout=3) + except Exception: + pass + deadline = time.time() + timeout + for _file, h in hosts: + left = max(0.1, deadline - time.time()) + try: + h['proc'].wait(timeout=left) + except subprocess.TimeoutExpired: + try: + h['proc'].terminate() + except Exception: + pass + except Exception: + pass + applog.log('[卫戍协议] 已停止 %d 个速刷后端' % len(hosts)) + with _lock: + for file, h in hosts: + if _HOSTS.get(file) is h: + _HOSTS.pop(file, None) + return [f for f, _h in hosts] diff --git a/backend/core/garrisondl.py b/backend/core/garrisondl.py new file mode 100644 index 0000000..c762e08 --- /dev/null +++ b/backend/core/garrisondl.py @@ -0,0 +1,399 @@ +# -*- coding: utf-8 -*- +"""卫戍协议核心包下载引擎:records → 回退直链,断点续传 + 逐文件校验 + 原子落盘 + +核心包(约 61MB 的 .hbext = zip,解压 ~114MB)不随本程序分发,首次使用 +卫戍协议模块时从这里下载(前端面板自动触发,全程进度可见): + + 1. 首选:本机小黑盒扩展记录 + %APPDATA%\\HeyboxDesktop\\desktop\\extension-artifacts\\v1\\records\\*.catalog.json + 里 package_id == ai-desktop.arknights-medal-farm 的记录(多条取版本最大), + 带 target.cdn_url(官方 CDN 直链,匿名可下)与 integrity.files 逐文件清单。 + 2. 回退:硬编码的 v1.1.4 已验证直链(整包 sha256 已锚定;无逐文件清单时 + 退化为 zip 可解压 + core/service.mjs 存在 + 体量下限)。 + +落盘到 ``<运行根>/garrison/medal-farm-v<版本>/``(garrison.core_dir 的约定 +位置之一,装好即被发现)。下载在后台线程跑,进度/阶段记在模块级 _DL, +``/api/garrison/status`` 顺路带给前端轮询;``.part`` 断点续传,失败可重试。 + +版本锚定:落盘前检查包内 README 仍含原许可声明(引导下载的依据);新版 +若缺失则停在需人工确认,不自动安装,回退用已验证的 v1.1.4。 +""" +from __future__ import annotations + +import hashlib +import json +import os +import re +import shutil +import threading +import time +import urllib.error +import urllib.request +import zipfile + +from . import applog, settings + +PKG_ID = 'ai-desktop.arknights-medal-farm' +PKG_DIR_RE = re.compile(r'^medal-farm-v(\d+(?:\.\d+)*)$') + +FALLBACK = { + 'version': '1.1.4', + 'url': ('https://static.max-c.com/heybox/desktop/extension/' + 'ai-desktop.arknights-medal-farm/version/1.1.4/' + '970f8e97e13fd427abf63289c53c8a68765d4ac870f745c5f3c58250a25829ff-' + '20261118T140851382Z/ai-desktop.arknights-medal-farm-1.1.4.hbext'), + 'sha256': '970f8e97e13fd427abf63289c53c8a68765d4ac870f745c5f3c58250a25829ff', + 'bytes': 61071704, + 'files': None, + 'source': '官方直链(回退)', +} + +MIN_TOTAL_BYTES = 50 * 1024 * 1024 +MIN_FILE_COUNT = 100 + +_LOCK = threading.Lock() +_RUNNING = [False] +_DL = { + 'stage': 'idle', # idle / connecting / downloading / verifying / done / error + 'done': 0, 'total': 0, # 下载字节 + 'files': 0, 'filesTotal': 0, + 'source': '', 'version': '', 'error': '', + 'startedAt': None, 'endedAt': None, +} + + +class NeedConfirmError(Exception): + """包内容校验未过(原许可声明缺失):停在需人工确认,不自动落盘""" + + +# ---------------------------------------------------------------- 路径与版本 +def garrison_dir() -> str: + return os.path.join(settings.project_root(), 'garrison') + + +def download_dir() -> str: + return os.path.join(garrison_dir(), '.medal-farm-download') + + +def ver_key(v): + parts = [] + for x in re.findall(r'\d+', str(v or '')): + try: + parts.append(int(x)) + except ValueError: + break + return tuple(parts or (0,)) + + +def _installed_pkg_dir() -> str: + """garrison/ 下已装的最高版本目录(空串 = 没装)""" + best = None + try: + names = os.listdir(garrison_dir()) + except OSError: + return '' + for name in names: + m = PKG_DIR_RE.match(name) + if not m or not os.path.isfile(os.path.join(garrison_dir(), name, 'core', 'service.mjs')): + continue + if best is None or ver_key(m.group(1)) > ver_key(best[0]): + best = (m.group(1), name) + return best[1] if best else '' + + +# ---------------------------------------------------------------- 下载源 +def record_candidates(): + base = os.environ.get('APPDATA') or '' + rdir = os.path.join(base, 'HeyboxDesktop', 'desktop', + 'extension-artifacts', 'v1', 'records') + out, seen = [], set() + try: + names = os.listdir(rdir) + except OSError: + return out + for name in names: + if not name.endswith('.catalog.json'): + continue + try: + with open(os.path.join(rdir, name), encoding='utf-8') as f: + d = json.load(f) + except Exception: + continue + t = d.get('target') or {} + if t.get('package_id') != PKG_ID: + continue + ver = str(t.get('version') or '') + url = str(t.get('cdn_url') or '') + if not ver or not url or ver in seen: + continue + try: + bytes_ = int(t.get('bytes') or 0) or None + except (TypeError, ValueError): + bytes_ = None + seen.add(ver) + out.append({'version': ver, 'url': url, + 'sha256': str(t.get('artifact_sha256') or '').strip().lower() or None, + 'bytes': bytes_, + 'files': ((d.get('integrity') or {}).get('files')) or None, + 'source': '小黑盒扩展记录'}) + out.sort(key=lambda r: ver_key(r['version']), reverse=True) + return out + + +def candidates(): + return record_candidates() + [dict(FALLBACK)] + + +# ---------------------------------------------------------------- 引擎 +def _set(**kw): + with _LOCK: + _DL.update(kw) + + +def _sha256_file(path): + h = hashlib.sha256() + with open(path, 'rb') as f: + while True: + chunk = f.read(1 << 20) + if not chunk: + break + h.update(chunk) + return h.hexdigest() + + +def _download(url, dest, expected_bytes=None, expected_sha256=None, + timeout=30, attempts=3): + """流式下载(Range 断点续传 + 重试);校验失败删 .part 重抛。""" + part = dest + '.part' + last_err = None + for attempt in range(1, attempts + 1): + try: + have = os.path.getsize(part) if os.path.isfile(part) else 0 + headers = {'User-Agent': 'MAA-PRTS-garrison/1.0'} + if have: + headers['Range'] = 'bytes=%d-' % have + req = urllib.request.Request(url, headers=headers) + with urllib.request.urlopen(req, timeout=timeout) as r: + code = getattr(r, 'status', 200) or 200 + resume = code == 206 + if not resume and have: + have = 0 + total = expected_bytes + if not total: + cl = r.headers.get('Content-Length') + total = (have + int(cl)) if (resume and cl and cl.isdigit()) \ + else (int(cl) if cl and cl.isdigit() else None) + done = have + with open(part, 'ab' if resume else 'wb') as f: + while True: + chunk = r.read(1 << 20) + if not chunk: + break + f.write(chunk) + done += len(chunk) + _set(done=done, total=total or done) + size = os.path.getsize(part) + if expected_bytes and size != expected_bytes: + os.remove(part) + raise RuntimeError('下载大小不符:期望 %d,实得 %d' % (expected_bytes, size)) + if expected_sha256 and _sha256_file(part) != expected_sha256.lower(): + os.remove(part) + raise RuntimeError('整包校验失败,下载可能不完整,请重试') + os.replace(part, dest) + return dest + except RuntimeError: + raise + except Exception as e: # noqa: BLE001 网络/中断:保留 .part 续传 + last_err = e + if attempt >= attempts: + break + time.sleep(1.5 * attempt) + raise RuntimeError('下载失败(重试 %d 次):%s' % (attempts, last_err)) + + +def _license_ok(extract_dir) -> bool: + """落盘前置校验:包内 README 仍含原许可声明才继续(引导下载的依据)""" + for rel in ('README.md', 'core/README.md', 'extension.manifest.json'): + p = os.path.join(extract_dir, *rel.split('/')) + try: + with open(p, encoding='utf-8', errors='ignore') as f: + if 'GPL-3.0' in f.read().upper(): + return True + except OSError: + continue + return False + + +def _extract_verify(hbext, out_dir, manifest=None): + """解压 + 逐文件校验(大小+sha256,清单全覆盖);无清单退化校验体量。""" + want = {} + for f in manifest or []: + rel = str(f.get('relativePath') or '').replace('\\', '/') + if rel: + want[rel] = (int(f.get('bytes') or 0), str(f.get('sha256') or '').lower()) + root_real = os.path.realpath(out_dir) + os.makedirs(out_dir, exist_ok=True) + got, total_bytes = {}, 0 + with zipfile.ZipFile(hbext) as zf: + names = [n.replace('\\', '/') for n in zf.namelist() if not n.endswith('/')] + _set(files=0, filesTotal=len(names)) + for i, name in enumerate(names): + dest = os.path.realpath(os.path.join(out_dir, *name.split('/'))) + try: + inside = os.path.commonpath([root_real, dest]) == root_real + except ValueError: + inside = False + if not inside or os.path.basename(name) in ('', '.', '..'): + raise RuntimeError('包内路径异常,拒收:%s' % name) + info = zf.getinfo(name) + os.makedirs(os.path.dirname(dest) or dest, exist_ok=True) + h = hashlib.sha256() + with open(dest, 'wb') as f_out, zf.open(info) as src: + while True: + chunk = src.read(1 << 20) + if not chunk: + break + f_out.write(chunk) + h.update(chunk) + total_bytes += len(chunk) + got[name] = (info.file_size, h.hexdigest()) + _set(files=i + 1) + if 'core/service.mjs' not in got: + raise RuntimeError('包里没有 core/service.mjs,不是速刷核心包') + if want: + missing = [k for k in want if k not in got] + if missing: + raise RuntimeError('清单里的文件包里没有(%d 个),如 %s' % (len(missing), missing[0])) + bad = [rel for rel, (size, dig) in want.items() + if got[rel][0] != size or (dig and got[rel][1] != dig)] + if bad: + raise RuntimeError('%d 个文件校验失败,如 %s' % (len(bad), bad[0])) + # 清单外的额外文件允许(签名信封等本就不进清单),完整性由整包校验兜住 + elif len(got) < MIN_FILE_COUNT or total_bytes < MIN_TOTAL_BYTES: + raise RuntimeError('包体量异常(%d 个文件 / %d 字节),拒收' % (len(got), total_bytes)) + return len(got) + + +def _install(hbext, version, manifest=None): + """解压校验 → 前置校验 → 原子落位 garrison/medal-farm-v<版本>;失败不伤旧版。""" + pkg = os.path.join(garrison_dir(), 'medal-farm-v%s' % version) + stage = os.path.join(download_dir(), 'stage') + shutil.rmtree(stage, ignore_errors=True) + os.makedirs(stage, exist_ok=True) + try: + _extract_verify(hbext, stage, manifest) + if not _license_ok(stage): + raise NeedConfirmError( + '新版本 v%s 内容校验未通过,已停止自动安装。可点重试改用已验证的 v%s。' + % (version, FALLBACK['version'])) + had_old = os.path.exists(pkg) + bak = pkg + '.replacing' + if had_old: + os.replace(pkg, bak) + try: + os.replace(stage, pkg) + except OSError: + if had_old: + os.replace(bak, pkg) + raise + if had_old: + shutil.rmtree(bak, ignore_errors=True) + # 新版已就位:清掉其它旧版本(删不掉的留着不影响) + for name in os.listdir(garrison_dir()): + m = PKG_DIR_RE.match(name) + if m and m.group(1) != version: + shutil.rmtree(os.path.join(garrison_dir(), name), ignore_errors=True) + return pkg + finally: + shutil.rmtree(stage, ignore_errors=True) + + +def _cleanup(keep_part=True): + d = download_dir() + if not os.path.isdir(d): + return + shutil.rmtree(os.path.join(d, 'stage'), ignore_errors=True) + for name in os.listdir(d): + if name == 'lock' or (keep_part and name.endswith('.part')): + continue + if name.endswith('.hbext') or name.endswith('.part'): + try: + os.remove(os.path.join(d, name)) + except OSError: + pass + + +# ---------------------------------------------------------------- 对外 +def state() -> dict: + with _LOCK: + return dict(_DL) + + +def start() -> dict: + """启动(或继续)下载;已在跑/已完成时原样返回。返回 state 快照。""" + with _LOCK: + running = _RUNNING[0] + if running: + return state() + if _installed_pkg_dir(): + _set(stage='done', error='', endedAt=time.time()) + return state() + threading.Thread(target=_run, daemon=True, name='garrison-dl').start() + return state() + + +def _run(): + with _LOCK: + if _RUNNING[0]: + return + _RUNNING[0] = True + _set(stage='connecting', error='', done=0, total=0, files=0, filesTotal=0, + startedAt=time.time(), endedAt=None) + lock_dir = '' + tried = [] + try: + os.makedirs(download_dir(), exist_ok=True) + lock_dir = os.path.join(download_dir(), 'lock') + if os.path.isdir(lock_dir): + try: + stale = time.time() - os.path.getmtime(lock_dir) > 15 * 60 + except OSError: + stale = True + if not stale: + raise RuntimeError('另一个实例正在下载核心包,稍候再试') + shutil.rmtree(lock_dir, ignore_errors=True) + os.mkdir(lock_dir) + + for rec in candidates(): + label = 'v%s(%s)' % (rec['version'], rec['source']) + try: + _set(stage='connecting', source=rec['source'], version=rec['version'], + done=0, total=rec.get('bytes') or 0) + hbext = os.path.join(download_dir(), 'medal-farm-%s.hbext' % rec['version']) + _download(rec['url'], hbext, + expected_bytes=rec.get('bytes'), + expected_sha256=rec.get('sha256')) + _set(stage='verifying', files=0, filesTotal=0) + _install(hbext, rec['version'], manifest=rec.get('files')) + try: + os.remove(hbext) + except OSError: + pass + _set(stage='done', error='', endedAt=time.time()) + applog.log('[卫戍协议] 核心包 v%s 下载安装完成(%s)' % (rec['version'], label)) + return + except NeedConfirmError as e: + # 校验门禁:不落盘;换下一个源(回退直链是已验证版本) + tried.append('%s:%s' % (label, e)) + except Exception as e: # noqa: BLE001 + tried.append('%s:%s' % (label, e)) + raise RuntimeError('所有下载源都失败了:\n' + '\n'.join('· ' + t for t in tried)) + except Exception as e: # noqa: BLE001 + _set(stage='error', error=str(e), endedAt=time.time()) + applog.log('[卫戍协议] 核心包下载失败:%s' % e) + finally: + if lock_dir: + shutil.rmtree(lock_dir, ignore_errors=True) + _cleanup() + with _LOCK: + _RUNNING[0] = False diff --git a/backend/core/settings.py b/backend/core/settings.py index 2d7631d..c628a1d 100644 --- a/backend/core/settings.py +++ b/backend/core/settings.py @@ -196,6 +196,9 @@ def ensure_dirs(): # 这里只在用户手动指定时覆盖(比如 MAA 里没配、或者想指向另一个实例) 'emulatorPath': '', 'emulatorAutoStart': True, # 任务开跑前发现模拟器没启动,替用户启动 + # 卫戍协议速刷核心(service.mjs 所在目录,GPL,不随本程序分发); + # 空时按约定位置找:<运行根>/garrison/core 等,见 garrison.core_dir + 'garrisonCoreDir': '', # 内置助手:只存连接参数,apiKey 走 DPAPI 单独存 config/agent.key 'agent': { 'baseUrl': 'https://api.deepseek.com/v1', @@ -410,6 +413,8 @@ def save(patch: dict) -> dict: v = [str(x) for x in (v or []) if str(x).endswith('.json')][:200] elif k == 'emulatorPath': v = _norm_dir(v) if v else '' + elif k == 'garrisonCoreDir': + v = _norm_dir(v) if v else '' elif k == 'emulatorAutoStart': # 前端可能传 "false" / 0 / 空串,别让字符串 "false" 变成真 v = bool(v) and str(v).strip().lower() not in ('0', 'false', 'no', '') diff --git a/backend/main.py b/backend/main.py index b35ad42..cc267e0 100644 --- a/backend/main.py +++ b/backend/main.py @@ -358,6 +358,11 @@ def _quit(code=0, reason='退出'): _watch.stop_all() # 观测线程是 daemon,但主动停能让它把最后一条日志写完 except Exception: pass + try: + from core import garrison as _garrison + _garrison.stop_all() # 卫戍协议的 Node 宿主:通知收尾,等不及硬杀 + except Exception: + pass try: left = tasks.wait_all(5) if left: diff --git a/docs/backend.md b/docs/backend.md index bddc8f2..18ef388 100644 --- a/docs/backend.md +++ b/docs/backend.md @@ -1216,3 +1216,45 @@ MaaCore 只会报 `adb 连不上`,用户第一反应是程序坏了。放一 `181****5505` / 全角与带横线的写法;官服只拦「填了昵称」(MAA 拿昵称去 账号列表里子串匹配,死找几十次后超时,整轮挂机废掉)。**空串放行**—— 「还没填」和「填错了」是两件事,用 `check()` 原文会把清空输入框也拦下。 + +## 卫戍协议速刷(`garrison.py` / `garrisondl.py` / `resources/garrison/`,2026-11-20) + +**核心不在仓库里**。真正干活的 `service.mjs` 是第三方插件 +(`ai-desktop.arknights-medal-farm`,GPL-3.0-or-later,约 114MB,带 MaaFramework +原生模块),不进 git、不进安装包。首次打开卫戍协议页时 `garrisondl.py` 从小黑盒 +扩展记录(`%APPDATA%\HeyboxDesktop\...\records\*.catalog.json`)拿 CDN 直链, +拿不到就用锚定过 sha256 的 v1.1.4 回退直链,逐文件校验后落到 +`<运行根>/garrison/medal-farm-v<版本>/`。 + +**一个账号一个宿主进程**:`host.mjs` 用 Node 把核心包成 HTTP 服务(随机端口 + +`x-garrison-token` 握手),Python 只做进程编排和转发。`--parent-pid` 看门狗保证 +MAA-PRTS 崩了宿主自己退出,不会变成孤儿继续点游戏。设备与截图方式从账号绑定 +MAA 的 `gui.new.json` 里 `ConnectSettings` 抄(MuMu→`mumu`+Extras 快速截图、 +雷电→`ldplayer`、PC 客户端→`pc`)。 + +### 核心文本补丁(`resources/garrison/patches.json`) + +核心是混淆过的单文件,页面识别遇到游戏新弹窗就会卡住。改它(而不是在 MAA-PRTS +侧另挂一个 adb 看门狗去抢截图和点击)是因为**点哪儿仍由核心自己按 OCR 文本算**, +分辨率、UI 缩放、主题全都天然自适应;看门狗得把坐标写死,还会跟核心抢输入。 + +`apply_core_patches(core)` 在每次 spawn 宿主前跑一遍: + +| 情形 | 行为 | +|------|------| +| 规则里的 `replace` 已在文件里 | 记 `skipped`,不重复替换(幂等) | +| `find` 能找到 | 替换一次,首次改动前把原文件备份成 `service.mjs.orig` | +| `find` 找不到(核心升级换了写法) | 记 `miss` + 日志,**一个字节都不动** | + +**2026-11-20 实证**:点「准备就绪」后游戏弹出「确认准备就绪吗?当前仍处于临时 +整备区的干员和装备,将在进入战斗后自动销毁(召唤物仍会在下个休整期出现)」, +`garrison-<账号>.log` 里是 `[t] r9 prep.ready 115998ms` 紧跟 +`[trace] prep -> unknown`,然后空转 90 秒报「画面持续无法识别」。原因是核心把 +`confirm-ready` 页判定成「`确认准备` **且** `剩余资金|未使用的|指令`」,这个弹窗 +没有后三个词,落到 `unknown`。补丁把条件放宽为再认 `临时整备区|召唤物|自动销毁`, +就走进核心自带的 confirm 分支:`Ma()` 找不到「本局不再提示」返回 null(跳过勾选), +`wt(state, /^确认$/)` 点 OCR 到的「确认」,然后 `Z(1200)` 继续战斗流程。 + +核心升级(v1.1.5+)后若 `find` 脱靶,补丁只会在 app.log 里留一行 miss,核心照常 +跑、但这个弹窗问题会复发 —— 那时更新 `patches.json` 里的 `find` 就行,逻辑不用改。 + diff --git a/frontend/app.js b/frontend/app.js index a0f7a65..b62a229 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -11,8 +11,10 @@ const S = { appUpdate: null, updateBusy: false, paradoxPending: [], authorNames: {}, // 作业站作者 id → 昵称(搜索时顺手学,黑名单弹窗显示用) - module: 'copilot', // 当前模块:copilot / gacha / signin(配置修改按需求去掉了) + module: 'copilot', // 当前模块:copilot / gacha / signin / garrison(配置修改按需求去掉了) signBusy: '', // 正在跑哪一块签到:''/all/one——同一 token 并发签到会被风控,只能一个一个来 + gar: null, // /api/garrison/status 的最近一次响应(当前账号那份) + garOpts: {}, // file → 用户改过的速刷连接选项(没改过的账号用后端从 MAA 抄的默认值) gacha: null, // /api/gacha 的最近一次响应(当前账号那份) gachaOf: {}, // file → 已加载过的抽卡视图:切账号/切菜单回来直接复用,不再转圈 lastOfGame: { arknights: '', endfield: '' }, // 每栏上次看的是哪个号(切回这一栏时还原) @@ -3880,9 +3882,9 @@ function currentGame() { function applyModuleAvailability() { const ef = currentGame() === 'endfield'; - // 终末地账号只留助手与抽卡统计:作业获取、森空岛签到两枚 tab 都不显示 + // 终末地账号只留助手与抽卡统计:作业获取、森空岛签到、卫戍协议三枚 tab 都不显示 // (签到本身支持终末地,全局签到照样会签,只是不给终末地账号开这块界面) - ['copilot', 'signin'].forEach(m => { + ['copilot', 'signin', 'garrison'].forEach(m => { const b = $('.modtab[data-mod="' + m + '"]'); if (b) b.hidden = ef; }); @@ -3898,6 +3900,9 @@ function applyModuleAvailability() { renderGacha(); } else if (S.module === 'signin') { renderSignin(); // 签到面板上的「当前账号」跟着换 + } else if (S.module === 'garrison') { + resetGarView(); // 卫戍协议:换号重描面板(轮询不用重开) + renderGarrison(); } else if (S.module === 'chat') { chatInit(); // 换号后助手面板里的上下文提示要跟着变 } @@ -3915,15 +3920,19 @@ function setModule(mod, byGame) { }); const cp = $('#mod-copilot'), gg = $('#mod-gacha'), sg = $('#mod-signin'); const ct = $('#mod-chat'); + const ga = $('#mod-garrison'); if (cp) cp.hidden = mod !== 'copilot'; if (gg) gg.hidden = mod !== 'gacha'; if (sg) sg.hidden = mod !== 'signin'; if (ct) ct.hidden = mod !== 'chat'; - // 抽卡统计/签到/助手都用不到右栏作业集:收掉第三列,主区拿满宽度 + if (ga) ga.hidden = mod !== 'garrison'; + // 抽卡统计/签到/助手/卫戍协议都用不到右栏作业集:收掉第三列,主区拿满宽度 $('#app').classList.toggle('no-basket', mod !== 'copilot'); if (mod !== 'copilot') toggleBasket(false); if (mod === 'gacha') renderGacha(); if (mod === 'signin') renderSignin(); + if (mod === 'garrison') { resetGarView(); renderGarrison(); garStartPolling(); } + else garStopPolling(); if (mod === 'chat') enterChat(); else leaveChat(); } @@ -3989,6 +3998,288 @@ async function signinRun(scope) { } } +/* ------------------------------------------------------------ 卫戍协议 + 策略刻章速刷:每个账号一个速刷后端(Node 子进程,后端懒启动),面板轮询 + /api/garrison/status 拿状态。连接默认值由后端从该账号绑定 MAA 的连接配置 + 里抄(MuMu → 快速截图,雷电 → ldplayer,PC → pc;极速 / 1.5× / 3 胜), + 用户改过的选项按账号记在 S.garOpts 里,切回来还在。 */ +const GAR_STATUS_CN = { + idle: '空闲', starting: '启动中', running: '运行中', stopping: '停止中', + failed: '失败', completed: '已完成', done: '已完成', +}; +const GAR_KIND_CN = { + MuMuEmulator12: 'MuMu 模拟器 12', MuMuArm: 'MuMu ARM 版', LDPlayer: '雷电模拟器', + PC: '明日方舟 PC 版', BlueStacks: '蓝叠', Nox: '夜神', XYAZ: '逍遥', +}; +const GAR_BUSY = ['running', 'starting', 'stopping']; + +let _garTimer = null; // 面板轮询句柄:只在卫戍协议 tab 激活时跑 +let _garSeq = 0; // 请求代次:切账号/离开面板后丢弃旧响应 +let _garLogSeq = {}; // file → 核心日志已追加到哪条 seq(按 seq 去重) + +function resetGarView() { + const box = $('#gar-log'); + if (box) box.innerHTML = '点「开始速刷」后这里显示进度日志。'; + _garLogSeq[S.current] = 0; +} + +function garCurrentOpts() { + const d = (S.gar && S.gar.file === S.current) ? (S.gar.defaults || null) : null; + return S.garOpts[S.current] || (d ? { ...d } : null); +} + +/* 把选项描进表单:用户改过用改过的,否则用后端从 MAA 抄的默认值 */ +function paintGarInputs() { + const o = garCurrentOpts(); + if (!o) return; + const set = (id, v) => { const el = $(id); if (el && v !== undefined && v !== null) el.value = String(v); }; + set('#gar-device', o.device); + set('#gar-mode', o.mode); + set('#gar-adb', o.adbAddress); + set('#gar-wins', o.medalWins); + set('#gar-speed', o.speed); + set('#gar-scale', o.pcUiScale); + set('#gar-shot', o.screenshotMethod); +} + +function collectGarOpts() { + const v = id => $(id) ? $(id).value : ''; + const o = { + device: v('#gar-device'), mode: v('#gar-mode'), adbAddress: v('#gar-adb').trim(), + medalWins: Number(v('#gar-wins')) || 3, speed: Number(v('#gar-speed')) || 1.5, + pcUiScale: Number(v('#gar-scale')) || 90, screenshotMethod: v('#gar-shot'), + }; + S.garOpts[S.current] = o; // 记住用户的改动,切号再回来还在 + return o; +} + +function garAppendLog(items) { + const box = $('#gar-log'); + if (!box || !Array.isArray(items)) return; + const idle = box.querySelector('.sign-idle'); + if (idle) idle.remove(); + let max = _garLogSeq[S.current] || 0; + for (const it of items) { + const seq = (it && it.seq) || 0; + const text = (typeof it === 'string') ? it : (it.text ?? it.message ?? it.msg ?? JSON.stringify(it)); + if (!text) continue; + if (seq && seq <= max) continue; + if (seq) max = seq; + const div = document.createElement('div'); + if ((it && it.err) || /失败|错误|error|停止|超时/.test(text)) div.className = 'err'; + div.textContent = seq ? `[${String(seq).padStart(4)}] ${text}` : text; + box.appendChild(div); + } + while (box.childNodes.length > 400) box.removeChild(box.firstChild); + box.scrollTop = box.scrollHeight; + _garLogSeq[S.current] = max; +} + +function paintGarState(d) { + const st = d.state || {}; + const busy = GAR_BUSY.includes(st.status); + S.garBusy = busy; + const badge = $('#gar-badge'); + if (badge) { + badge.className = 'gar-badge ' + (st.status || 'idle'); + badge.textContent = GAR_STATUS_CN[st.status] || st.status || '空闲'; + } + const msg = $('#gar-msg'); + if (msg) msg.textContent = st.message || ''; + const set = (id, v, dash) => { const el = $(id); if (el) el.textContent = (v === undefined || v === null || v === '') ? (dash || '–') : v; }; + set('#gar-strategy', st.strategy); + set('#gar-round', st.round); + set('#gar-level', st.level); + set('#gar-matches', st.matches, 0); + const total = st.total || 31, done = st.completed || 0; + const bar = $('#gar-progress'); + if (bar) bar.style.width = (total ? (done / total) * 100 : 0) + '%'; + const pt = $('#gar-prog-text'); + if (pt) pt.textContent = `进度 ${done} / ${total}` + (st.lastMatch ? ` · 上局:${st.lastMatch}` : ''); + garAppendLog(st.log); + const tip = $('#gar-tip'); + if (tip) tip.textContent = busy ? '速刷运行中…' : ''; + const bt = $('#gar-test'), bs = $('#gar-start'), br = $('#gar-resume'), bp = $('#gar-stop'); + if (bt) bt.disabled = busy; + if (bs) bs.disabled = busy; + if (br) br.disabled = busy || !d.hasCheckpoint; + if (bp) bp.disabled = !busy; + ['#gar-device', '#gar-mode', '#gar-adb', '#gar-wins', '#gar-speed', '#gar-scale', '#gar-shot'] + .forEach(id => { const el = $(id); if (el) el.disabled = busy; }); + // 来源标注:让用户知道这份默认值是从哪个 MAA 配置抄的 + const src = $('#gar-src'); + if (src) { + const fm = d.fromMaa || {}; + src.textContent = fm.kind + ? `默认值抄自 MAA${fm.profile ? `「${fm.profile}」` : ''} · ${GAR_KIND_CN[fm.kind] || fm.kind}` + : '默认值(没读到 MAA 连接配置)'; + src.title = (fm.maaDir || '') + (d.defaults && d.defaults.adbPath ? '\nadb:' + d.defaults.adbPath : ''); + } +} + +/* 环境不齐(缺 Node / 后端起不来)时的指引空态(核心缺失走下载视图,不在这) */ +function showGarEmpty(d, title) { + const box = $('#gar-empty'), grid = $('#gar-grid'), logCard = $('#gar-log-card'); + if (!box) return; + if (grid) grid.hidden = true; + if (logCard) logCard.hidden = true; + let html = ''; + if (d && !d.nodeOk) { + html = `

还缺 Node.js

速刷核心是一个 Node 程序(需要 Node.js 20 以上)。 + 装好 Node 后回来点「重试」。

`; + } else { + html = `

${esc(title || '速刷后端起不来')}

${esc((d && d.error) || '未知原因')}

`; + } + box.innerHTML = html + ''; + box.hidden = false; + const r = $('#gar-retry'); + if (r) r.addEventListener('click', () => renderGarrison(true)); + const link = box.querySelector('.link-btn'); + if (link) link.addEventListener('click', () => openUrl(link.dataset.url)); +} + +/* 核心包下载视图:自动开始(records → 官方直链),进度随面板轮询刷新 */ +async function garStartDownload() { + try { await api('/api/garrison/download/start', {}); } + catch (e) { /* 失败原因下一轮轮询会带出来 */ } +} + +function showGarDownload(d) { + const box = $('#gar-empty'), grid = $('#gar-grid'), logCard = $('#gar-log-card'); + if (!box) return; + if (grid) grid.hidden = true; + if (logCard) logCard.hidden = true; + const dl = d.download || {}; + let pct = 0, text = '准备下载…'; + if (dl.stage === 'connecting') { + text = `连接下载源(${dl.version ? 'v' + dl.version + ' · ' : ''}${dl.source || '官方源'})…`; + } else if (dl.stage === 'downloading') { + pct = dl.total ? 100 * dl.done / dl.total : 0; + text = `下载中 ${pct.toFixed(1)}%(${dl.done >> 20} / ${(dl.total || dl.done) >> 20} MB)`; + } else if (dl.stage === 'verifying') { + pct = dl.filesTotal ? 100 * dl.files / dl.filesTotal : 0; + text = `校验解压中 ${dl.files} / ${dl.filesTotal || '…'} 个文件`; + } else if (dl.stage === 'done') { + pct = 100; + text = '核心就绪,正在启动…'; + } else if (dl.stage === 'error') { + text = ''; + } + const err = dl.stage === 'error' + ? `

${esc(dl.error || '下载失败')}

` + : ''; + box.innerHTML = ` +

首次使用:下载核心包

+

约 61MB,来自小黑盒官方 CDN(装过小黑盒会自动用你本机的最新版记录)。 + 下载后逐文件校验再安装,中断了会断点续传,不用手动管。

+
+
${esc(text)}
+ ${err}`; + box.hidden = false; + const r = $('#gar-dl-retry'); + if (r) r.addEventListener('click', garStartDownload); +} + +function hideGarEmpty() { + const box = $('#gar-empty'); + if (box) box.hidden = true; + const grid = $('#gar-grid'), logCard = $('#gar-log-card'); + if (grid) grid.hidden = false; + if (logCard) logCard.hidden = false; +} + +async function renderGarrison(force) { + const sub = $('#gar-sub'); + const acc = currentAccount(); + if (sub) sub.textContent = acc ? `${acc.nickName} · 明日方舟` : '未选择账号'; + const an = $('#gar-account'); + if (an) an.textContent = acc ? acc.nickName : '未选择账号'; + if (!S.current) { + showGarEmpty({ error: '先在左侧选一个明日方舟账号,再回来开速刷。' }, '还没有账号'); + return; + } + const seq = ++_garSeq; + if (force) hideGarEmpty(); + paintGarInputs(); // 先用缓存/旧默认值描一遍,不闪空表单 + try { + const d = await api('/api/garrison/status?file=' + encodeURIComponent(S.current)); + if (seq !== _garSeq || S.module !== 'garrison') return; + d.file = S.current; + S.gar = d; + if (d.needsDownload) { + showGarDownload(d); + const st = (d.download || {}).stage; + if (st === 'idle' || st === 'done') garStartDownload(); // 全自动:打开即开始(done=装好的核心又没了,重下) + return; + } + if (!d.nodeOk || !d.ready) { showGarEmpty(d); return; } + hideGarEmpty(); + paintGarInputs(); + paintGarState(d); + } catch (e) { + if (seq !== _garSeq) return; + showGarEmpty({ error: e.message }); + } +} + +/* 面板激活期间的状态轮询(后端本身就是转发,本地往返很便宜) */ +function garStartPolling() { + garStopPolling(); + _garTimer = setInterval(garTick, 1400); + garTick(); +} +function garStopPolling() { + if (_garTimer) { clearInterval(_garTimer); _garTimer = null; } +} +async function garTick() { + if (S.module !== 'garrison' || !S.current) return; + if (!S.gar || S.gar.file !== S.current) return; // 首份状态还没拿到,等 renderGarrison + const seq = _garSeq; + try { + const d = await api('/api/garrison/status?file=' + encodeURIComponent(S.current)); + if (seq !== _garSeq || S.module !== 'garrison') return; + d.file = S.current; + const wasDownloading = !!S.gar.needsDownload; + S.gar = d; + if (d.needsDownload) { + showGarDownload(d); + const st = (d.download || {}).stage; + if (st === 'idle' || st === 'done') garStartDownload(); + return; + } + if (wasDownloading) { renderGarrison(true); return; } // 刚下载完:重建整面板 + if (!d.ready) return; + paintGarState(d); + } catch (e) { /* 断线别刷屏:下一轮再试 */ } +} + +async function garAction(kind) { + if (!S.current) { toast('先在左侧选一个账号', 'err'); return; } + const opts = collectGarOpts(); + const body = { file: S.current, options: opts }; + const tip = $('#gar-tip'); + try { + if (kind === 'stop') { + await api('/api/garrison/stop', body); + toast('已发送停止指令'); + } else if (kind === 'test') { + if (tip) tip.textContent = '正在测试连接…'; + const r = await api('/api/garrison/test', body); + toast('✓ ' + (r.message || '连接成功'), 'ok', 4200); + garAppendLog([{ text: '[测试] ' + (r.message || '连接成功') }]); + } else { + const r = await api('/api/garrison/' + kind, body); + toast(kind === 'resume' ? '已从检查点恢复' : '已开始速刷'); + garAppendLog([{ text: `=== ${kind === 'resume' ? '恢复' : '开始'}速刷 ${r.taskId || ''} ===` }]); + } + garTick(); + } catch (e) { + toast('✗ ' + e.message, 'err', 5000); + garAppendLog([{ text: '✗ ' + e.message, err: true }]); + if (tip) tip.textContent = ''; + } +} + /* ------------------------------------------------------------ 抽卡统计 */ let _gachaSeq = 0; let _gachaBusy = false; @@ -4262,6 +4553,14 @@ function bindGlobal() { $('#btn-sign-all').addEventListener('click', () => signinRun('all')); $('#btn-sign-one').addEventListener('click', () => signinRun('one')); + + // 卫戍协议:四个动作 + 表单改动随手记(不提交就切号也不丢) + $('#gar-test').addEventListener('click', () => garAction('test')); + $('#gar-start').addEventListener('click', () => garAction('start')); + $('#gar-resume').addEventListener('click', () => garAction('resume')); + $('#gar-stop').addEventListener('click', () => garAction('stop')); + const garForm = $('.gar-form'); + if (garForm) garForm.addEventListener('change', collectGarOpts); $('#btn-add-account').addEventListener('click', openAddAccount); $('#btn-import-maa').addEventListener('click', importFromMaa); $('#btn-settings').addEventListener('click', openSettings); diff --git a/frontend/index.html b/frontend/index.html index af5c51b..b64879a 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -80,7 +80,7 @@
- +
@@ -253,6 +259,101 @@

搜一个关卡开始

+ + + diff --git a/frontend/style.css b/frontend/style.css index d4b3c70..96b89b4 100644 --- a/frontend/style.css +++ b/frontend/style.css @@ -767,6 +767,117 @@ input:focus, select:focus, button:focus-visible { outline: none; } .log-box.sign-log { flex: 1 1 auto; margin-top: 12px; height: auto; min-height: 258px; max-height: none; } .sign-log .sign-idle { color: var(--text-3); } +/* ============================================================ 卫戍协议 */ +/* 环境不齐(缺 Node / 缺核心)的指引空态 */ +.gar-empty { + padding: 46px 20px; + text-align: center; + color: var(--text-2); + border-radius: 16px; + border: 1px dashed var(--line-strong); + background: rgba(255, 255, 255, 0.015); +} +.gar-empty h3 { font-size: 15px; color: var(--text); margin-bottom: 8px; } +/* 显式盖掉 grid/flex 布局:UA 的 [hidden] 挡不住设了 display 的类 */ +.gar-empty[hidden], .sign-grid[hidden], .gar-log-card[hidden] { display: none; } +/* 核心包下载视图(缺核心时自动开始,进度随轮询刷新) */ +.gar-empty .gar-dl-bar { + margin: 18px auto 0; max-width: 460px; height: 8px; + border-radius: 6px; overflow: hidden; + border: 1px solid var(--line); + background: #070a0f; +} +.gar-empty .gar-dl-bar i { + display: block; height: 100%; + background: linear-gradient(90deg, var(--mint), var(--indigo)); + transition: width .4s ease; +} +.gar-empty .gar-dl-text { margin-top: 9px; font-size: 12px; color: var(--text-2); min-height: 18px; } +.gar-empty .gar-dl-err { + margin: 12px auto 0; max-width: 560px; + font-size: 11.5px; line-height: 1.7; color: var(--rose); + white-space: pre-wrap; word-break: break-all; +} +.gar-empty .gar-dl-err + .ghost-btn { margin-top: 12px; } +.gar-empty p { font-size: 12.5px; color: var(--text-3); line-height: 1.85; max-width: 520px; margin: 0 auto; } +.gar-empty p b { color: var(--text-2); font-weight: 600; } +.gar-empty code { font-family: var(--mono); font-size: 11px; color: var(--mint); word-break: break-all; } +.gar-empty .ghost-btn { margin-top: 16px; } + +.gar-badge-row { margin-top: 12px; display: flex; align-items: center; gap: 10px; min-width: 0; } +.gar-badge { + flex: 0 0 auto; + padding: 3px 12px; + border-radius: 20px; + font-size: 11.5px; font-weight: 650; letter-spacing: .3px; + border: 1px solid var(--line-strong); + color: var(--text-2); + background: rgba(255, 255, 255, 0.045); +} +.gar-badge.running, .gar-badge.starting { color: #7fd6ff; border-color: rgba(127, 214, 255, 0.4); background: rgba(127, 214, 255, 0.08); } +.gar-badge.stopping { color: var(--amber); border-color: rgba(245, 185, 85, 0.4); background: rgba(245, 185, 85, 0.08); } +.gar-badge.failed { color: var(--rose); border-color: rgba(255, 122, 138, 0.4); background: rgba(255, 122, 138, 0.08); } +.gar-badge.completed, .gar-badge.done { color: var(--mint); border-color: rgba(94, 234, 212, 0.4); background: rgba(94, 234, 212, 0.08); } +.gar-msg { + flex: 1 1 auto; min-width: 0; + font-size: 12px; color: var(--text-2); line-height: 1.6; + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; +} + +.gar-stats { + margin-top: 14px; + display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; +} +.gar-stat { + padding: 9px 8px; + border-radius: 10px; + border: 1px solid var(--line); + background: rgba(255, 255, 255, 0.025); + text-align: center; + min-width: 0; +} +.gar-stat .v { + font-size: 17px; font-weight: 700; color: var(--mint); + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; +} +.gar-stat .k { margin-top: 2px; font-size: 10.5px; color: var(--text-3); letter-spacing: .5px; } + +.gar-bar { + margin-top: 14px; height: 8px; + border-radius: 6px; overflow: hidden; + border: 1px solid var(--line); + background: #070a0f; +} +.gar-bar i { + display: block; height: 100%; width: 0; + background: linear-gradient(90deg, var(--mint), var(--indigo)); + transition: width .5s ease; +} +.gar-prog-text { margin-top: 7px; font-size: 11px; color: var(--text-3); } + +.gar-form { margin-top: 12px; display: flex; flex-direction: column; gap: 8px; } +.gar-form .field-row { flex: 0 0 auto; } +.gar-form input[type=text] { + flex: 1; max-width: 190px; + height: 30px; padding: 0 9px; + border-radius: 8px; + border: 1px solid var(--line-strong); + background: rgba(10, 13, 20, 0.9); + font-size: 12px; + font-family: var(--mono); +} +.gar-form input:disabled, .gar-form select:disabled { opacity: .45; cursor: not-allowed; } +.gar-actions { flex-wrap: wrap; } +.gar-actions .ghost-btn, .gar-actions .primary-btn.sm { flex: 1 1 auto; min-width: 96px; } +.ghost-btn.stop { border-color: rgba(255, 122, 138, 0.4); color: var(--rose); } +.ghost-btn.stop:hover { border-color: rgba(255, 122, 138, 0.55); color: var(--rose); background: rgba(255, 122, 138, 0.06); } +.gar-hint { margin: 12px 0 0; font-size: 11px; line-height: 1.8; color: var(--text-3); } +.gar-hint b { color: var(--text-2); font-weight: 600; } + +/* 日志卡:面板最下面一整行;日志框定长,新日志在框内滚动(.log-box 自带 overflow:auto) */ +.gar-log-card { margin-top: 14px; } +.log-box.gar-log { margin-top: 12px; height: 260px; max-height: 260px; } + @media (max-width: 1400px) { .app.no-basket { grid-template-columns: 252px minmax(0, 1fr); } } diff --git a/resources/garrison/host.mjs b/resources/garrison/host.mjs new file mode 100644 index 0000000..0b242b8 --- /dev/null +++ b/resources/garrison/host.mjs @@ -0,0 +1,202 @@ +#!/usr/bin/env node +// 卫戍协议·策略刻章速刷 —— MAA-PRTS 子进程宿主 +// +// 由 backend/core/garrison.py 按账号懒启动(一个账号一个进程,多账号天然并行): +// node host.mjs --core <核心目录> --checkpoint <检查点文件> --token <随机串> \ +// [--parent-pid ] [--port 0] +// +// 与独立版 farm-ui.mjs 的区别:没有网页(前端就是 MAA-PRTS 自己的界面), +// 端口由 OS 分配(--port 0),启动后往 stdout 打一行 `READY ` +// 作为握手;所有 /api/* 请求必须带 x-garrison-token 头,防止误连/串台。 +// 另有 /api/shutdown 供 Python 退出时优雅收尾(stop → dispose → exit)。 +// +// 核心目录(service.mjs,GPL-3.0-or-later)不在本仓库、不进安装包, +// 由 garrison.py 在运行根 garrison/core 等约定位置检测。 + +import http from 'node:http'; +import { pathToFileURL } from 'node:url'; +import { readFile, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import fs from 'node:fs'; + +const argv = process.argv.slice(2); +function flagVal(name) { + const i = argv.indexOf(name); + return i >= 0 ? argv[i + 1] : undefined; +} +const coreDir = path.resolve(flagVal('--core') || ''); +const CHECKPOINT_FILE = path.resolve(flagVal('--checkpoint') || path.join(coreDir, '..', 'checkpoint-last.json')); +const TOKEN = flagVal('--token') || null; +const PARENT_PID = Number(flagVal('--parent-pid')) || 0; +const PORT = Number(flagVal('--port') || 0); + +function log(...args) { + // 运行轨迹走 stderr:stdout 只留 READY 握手行,Python 按行解析 + console.error('[host]', new Date().toISOString().slice(11, 19), ...args); +} + +if (!fs.existsSync(path.join(coreDir, 'service.mjs'))) { + console.error(`找不到核心: ${path.join(coreDir, 'service.mjs')}`); + process.exit(1); +} + +// ---------- 加载核心 ---------- +const core = await import(pathToFileURL(path.join(coreDir, 'service.mjs')).href); + +const diagBuffer = []; // 最近诊断 {t, name, data} +function pushDiag(name, data) { + diagBuffer.push({ t: Date.now(), name, data }); + if (diagBuffer.length > 400) diagBuffer.splice(0, diagBuffer.length - 400); +} + +let service; +service = await core.create({ + emit(event, data) { + if (event === 'diagnostic') pushDiag(data?.note ?? data?.name ?? JSON.stringify(data).slice(0, 80), data); + else if (event === 'checkpoint') { + writeFile(CHECKPOINT_FILE, JSON.stringify(data, null, 2)) + .catch(() => {}) + .finally(() => + service + .confirmCheckpoint({ taskId: data.taskId, seq: data.seq }) + .catch(() => {}) + ); + pushDiag('checkpoint.saved', { seq: data.seq }); + } + // "state" 事件无需处理:前端轮询 service.state() 即可 + }, +}); +log('核心已加载:', coreDir); + +const BUSY = ['running', 'stopping', 'starting']; +async function busy() { + const s = await service.state(); + return BUSY.includes(s.status); +} + +// ---------- HTTP 服务 ---------- +const server = http.createServer(async (req, res) => { + const url = new URL(req.url, 'http://x'); + const authed = !TOKEN || req.headers['x-garrison-token'] === TOKEN; + try { + if (!authed) { + sendJson(res, 403, { error: 'token 不对(不是拉给自己的后端)' }); + } else if (req.method === 'GET' && url.pathname === '/api/state') { + const [state, checkpoint] = await Promise.all([ + service.state(), + fs.existsSync(CHECKPOINT_FILE) + ? readFile(CHECKPOINT_FILE, 'utf8').then((t) => JSON.parse(t)).catch(() => null) + : null, + ]); + sendJson(res, 200, { state, diag: diagBuffer.slice(-80), hasCheckpoint: !!checkpoint }); + } else if (req.method === 'POST' && url.pathname === '/api/test') { + if (await busy()) return sendJson(res, 409, { error: '速刷运行中,请先停止' }); + const body = await readBody(req); + const { device, options } = buildOptions(body); + const r = await service.testConnection({ device, options }); + sendJson(res, 200, { message: r?.message ?? '连接成功' }); + } else if (req.method === 'POST' && url.pathname === '/api/start') { + if (await busy()) return sendJson(res, 409, { error: '速刷任务已在运行' }); + const body = await readBody(req); + const { device, options } = buildOptions(body); + const taskId = `prts-${Date.now()}`; + service + .start({ taskId, device, options }) + .then((r) => { pushDiag('farm.finished', r ?? {}); log('速刷结束:', JSON.stringify(r ?? {}).slice(0, 300)); }) + .catch((e) => { pushDiag('farm.error', { error: String(e?.message ?? e) }); log('速刷出错:', e?.message ?? e); }); + sendJson(res, 200, { ok: true, taskId }); + } else if (req.method === 'POST' && url.pathname === '/api/resume') { + if (await busy()) return sendJson(res, 409, { error: '速刷任务已在运行' }); + if (!fs.existsSync(CHECKPOINT_FILE)) return sendJson(res, 404, { error: '没有已保存的检查点' }); + const checkpoint = JSON.parse(await readFile(CHECKPOINT_FILE, 'utf8')); + const body = await readBody(req); + const { device, options } = buildOptions(body); + const taskId = `prts-${Date.now()}`; + service + .start({ taskId, device, options, resume: checkpoint.checkpoint ?? checkpoint }) + .then((r) => { pushDiag('farm.finished', r ?? {}); log('从检查点恢复后结束:', JSON.stringify(r ?? {}).slice(0, 300)); }) + .catch((e) => { pushDiag('farm.error', { error: String(e?.message ?? e) }); log('恢复出错:', e?.message ?? e); }); + sendJson(res, 200, { ok: true, taskId }); + } else if (req.method === 'POST' && url.pathname === '/api/stop') { + if (!(await busy())) return sendJson(res, 409, { error: '当前没有运行中的任务' }); + service.stop().catch(() => {}); + sendJson(res, 200, { ok: true }); + } else if (req.method === 'POST' && url.pathname === '/api/shutdown') { + // Python 退出/回收时调用:先回执再异步收尾,别让调用方等 dispose。 + // 稍等一拍再退出,确保回执的 TCP 段先发出去(立即 exit 会掐掉响应) + sendJson(res, 200, { ok: true }); + setTimeout(() => shutdown(0), 100); + } else { + sendJson(res, 404, { error: 'not found' }); + } + } catch (e) { + sendJson(res, 500, { error: String(e?.message ?? e) }); + } +}); + +function sendJson(res, code, obj) { + res.writeHead(code, { 'content-type': 'application/json; charset=utf-8' }); + res.end(JSON.stringify(obj)); +} +function readBody(req) { + return new Promise((resolve, reject) => { + let buf = ''; + req.on('data', (c) => (buf += c)); + req.on('end', () => { + try { resolve(buf ? JSON.parse(buf) : {}); } catch (e) { reject(e); } + }); + req.on('error', reject); + }); +} +function buildOptions(body = {}) { + const device = body.device ?? 'mumu'; + const options = { + goal: 'medal', + medalWins: Number(body.medalWins) === 6 ? 6 : 3, + mode: body.mode === 'standard' ? 'standard' : 'quick', + debug: Boolean(body.debug), + verifyUpgrade: true, identifyUnknown: true, fullBoard: true, useEquipment: true, + speed: Math.min(5, Math.max(0.5, Number(body.speed) || 1.5)), + device, + adbAddress: String(body.adbAddress ?? '127.0.0.1:16384').trim(), + adbPath: String(body.adbPath ?? '').trim(), + screenshotMethod: ['auto', 'fast', 'adb'].includes(body.screenshotMethod) ? body.screenshotMethod : 'auto', + inputMethod: 'auto', + pcInputMethod: ['cursor', 'message'].includes(body.pcInputMethod) ? body.pcInputMethod : 'cursor', + pcUiScale: Number(body.pcUiScale) === 100 ? 100 : 90, + }; + return { device, options }; +} + +server.on('error', (e) => { + console.error(`HTTP 服务出错: ${e?.message ?? e}`); + process.exit(1); +}); + +server.listen(PORT, '127.0.0.1', () => { + const port = server.address().port; + // 握手行:Python 从 stdout 读到它才认为后端就绪(token 一并带回) + process.stdout.write(`READY ${port} ${TOKEN ?? '-'}\n`); + log(`已监听 127.0.0.1:${port},检查点 ${CHECKPOINT_FILE}`); +}); + +// ---------- 存活与退出 ---------- +// Python 主进程不在了(崩溃/被杀)就自己收尾,别变成孤儿继续点游戏 +if (PARENT_PID > 0) { + setInterval(() => { + try { process.kill(PARENT_PID, 0); } catch { log('父进程已退出,跟随退出'); shutdown(0); } + }, 5000).unref(); +} + +let exiting = false; +async function shutdown(code) { + if (exiting) return; + exiting = true; + log('正在停止…'); + try { if (await busy()) { log('有任务在跑,先停任务…'); await service.stop(); } } catch {} + try { await core.dispose(service); } catch {} + process.exit(code); +} +process.on('SIGINT', () => shutdown(0)); +process.on('SIGTERM', () => shutdown(0)); +process.on('exit', () => { try { server.close(); } catch {} }); diff --git a/resources/garrison/patches.json b/resources/garrison/patches.json new file mode 100644 index 0000000..54d8269 --- /dev/null +++ b/resources/garrison/patches.json @@ -0,0 +1,24 @@ +{ + "coreVersion": "1.1.4", + "note": "对第三方核心 service.mjs 的最小文本补丁。核心是 GPL-3.0-or-later 的报混淆包,不进仓库、由 garrisondl.py 按版本下载;这里只存纯文本替换规则,启动前幂等应用(首次改动前留 service.mjs.orig 备份)。规则脱靶(核心升级换了写法)只记日志跳过,不影响启动。", + "patches": [ + { + "id": "confirm-ready-temp-zone", + "why": "点「准备就绪」后游戏弹出「确认准备就绪吗?当前仍处于临时整备区的干员和装备,将在进入战斗后自动销毁(召唤物仍会在下个休整期出现)」。核心原本把 confirm-ready 页判定为「确认准备」且同时出现「剩余资金/未使用的/指令」,这个弹窗没有那些词,于是落进 unknown 空转 90 秒后报「画面持续无法识别」。补上该弹窗的特征词后,走核心自带的 confirm-ready 分支:跳过不存在的「本局不再提示」复选框,点 OCR 到的「确认」。", + "find": "c(/确认准备/)&&c(/剩余资金|未使用的|指令/)?f=\"confirm-ready\"", + "replace": "c(/确认准备/)&&(c(/剩余资金|未使用的|指令/)||c(/临时整备区|召唤物|自动销毁/))?f=\"confirm-ready\"" + }, + { + "id": "name-match-short-latin-tolerance", + "why": "三合一(精锐免费选择)赠送高星干员时,核心点开候选卡后按详情标题 OCR 与卡片名互相核对(Zr)。原规则对期望名 <4 字零容错(必须原样包含)、拉丁名只容 1 个字符差:蕾缪安(3 字)OCR 错一个形近字、拉丁名(Miss.Christine,以及核心赛季数据里根本没有的新预备干员 Mist 系小字拉丁名)常错 2 字以上,即核对失败 → 点右上角关闭 → 抛「免费奖励领取未确认」→ 赠送干员没领到。放宽为:≥3 字享受与 ≥4 字相同的 1 字容差(2 字名保持原样零容错防误买),≥6 字的拉丁/数字名容 2 字差(核心数据里的拉丁名两两编辑距离远大于 2,无混淆风险)。", + "find": "if(A.includes(M))return!0;if(M.length<4)return!1;for(let q=0;q+M.length<=A.length;q++){let W=0;for(let L=0;L=6?2:1;for(let q=0;q+M.length<=A.length;q++){let W=0;for(let L=0;L/garrison 约定位置;都没有 = '' + assert garrison.core_dir() == '' + conv = os.path.join(settings.project_root(), 'garrison', 'core') + os.makedirs(conv, exist_ok=True) + open(os.path.join(conv, 'service.mjs'), 'w', encoding='utf-8').close() + assert os.path.normcase(garrison.core_dir()) == os.path.normcase(conv) + manual = os.path.join(tmp, 'my-core') + os.makedirs(manual, exist_ok=True) + open(os.path.join(manual, 'service.mjs'), 'w', encoding='utf-8').close() + settings.save({'garrisonCoreDir': manual}) + assert os.path.normcase(garrison.core_dir()) == os.path.normcase(manual) + settings.save({'garrisonCoreDir': ''}) + # 检测断言完就把假核心删掉:不然下面 status() 会拿假 service.mjs + # 真去拉一个宿主进程(有 Node 的机器上白等 45 秒握手超时) + shutil.rmtree(os.path.join(settings.project_root(), 'garrison'), ignore_errors=True) + shutil.rmtree(manual, ignore_errors=True) + assert garrison.core_dir() == '' + + # 3) 默认值从账号绑定的 MAA 配置抄:MuMu → mumu+快速截图(Extras) + maa_dir = os.path.join(tmp, 'maa') + os.makedirs(os.path.join(maa_dir, 'config'), exist_ok=True) + def _write_maa(kind, addr, adb=''): + with open(os.path.join(maa_dir, 'config', 'gui.new.json'), 'w', + encoding='utf-8') as f: + json.dump({'Current': 'P1', 'Configurations': {'P1': {'Gui': { + 'ConnectSettings': {'Config': kind, 'Address': addr, + 'AdbPath': adb}}}}}, f) + acc = os.path.join(tmp, 'config', 'g-acc.json') + with open(acc, 'w', encoding='utf-8') as f: + json.dump({'account': {'uid': '7', 'game': 'arknights'}, + 'maa': {'dir': maa_dir}}, f, ensure_ascii=False) + + _write_maa('MuMuEmulator12', '127.0.0.1:16416', r'C:\MuMu\adb.exe') + o, src = garrison.defaults('g-acc.json') + assert o == {'device': 'mumu', 'mode': 'quick', 'speed': 1.5, 'medalWins': 3, + 'adbAddress': '127.0.0.1:16416', 'adbPath': r'C:\MuMu\adb.exe', + 'screenshotMethod': 'fast', 'pcUiScale': 90}, o + assert src['kind'] == 'MuMuEmulator12' and src['profile'] == 'P1', src + + _write_maa('LDPlayer', 'emulator-5554') + o, _src = garrison.defaults('g-acc.json') + assert o['device'] == 'ldplayer' and o['screenshotMethod'] == 'auto', o + _write_maa('PC', '') + o, _src = garrison.defaults('g-acc.json') + assert o['device'] == 'pc' and o['adbAddress'] == '127.0.0.1:16384', o + # 没绑 MAA / 配置读不到:兜底值不炸 + o, src = garrison.defaults('ghost.json') + assert o['device'] == 'mumu' and o['mode'] == 'quick' and o['speed'] == 1.5, o + assert src['kind'] == '' and src['maaDir'] == '', src + + # 4) sanitize:越界值全部收进合法枚举/范围 + bad = garrison.sanitize({'device': 'hack', 'mode': 'zzz', 'medalWins': '6', + 'speed': '99', 'screenshotMethod': 'x', + 'adbAddress': ' ', 'pcUiScale': '120'}) + assert bad == {'device': 'mumu', 'mode': 'quick', 'medalWins': 6, + 'speed': 5.0, 'adbAddress': '127.0.0.1:16384', + 'adbPath': '', 'screenshotMethod': 'auto', + 'pcUiScale': 90}, bad + + # 5) 空环境 status:缺核心 → ready=False + needsDownload + 下载状态机初值; + # 路由也挂上了 + st = api.api_garrison_status({'file': 'g-acc.json'}, {}) + assert st['coreOk'] is False and st['ready'] is False and not st['running'], st + assert st['needsDownload'] is True, st + assert st['download']['stage'] == 'idle', st + assert st['defaults']['adbAddress'] == '127.0.0.1:16384', st # core 被清掉不影响默认值 + for path in ('/api/garrison/status', '/api/garrison/download/start', + '/api/garrison/test', '/api/garrison/start', + '/api/garrison/resume', '/api/garrison/stop'): + assert path in api.ROUTES, path + + # 6) 没宿主时的 stop:人话报错;stop_all:空列表不炸 + try: + garrison.stop('g-acc.json') + raise AssertionError('没任务却停成功了') + except (ValueError, RuntimeError) as e: + assert '没有' in str(e), e + assert garrison.stop_all() == [] + + # 7) 下载引擎(不起网络):回退候选常在、坏 URL 报错、坏包拒收、 + # 前置校验不过拒装(不伤旧版)、已装短路 + import zipfile + from core import garrisondl + cands = garrisondl.candidates() + assert cands and cands[-1]['version'] == garrisondl.FALLBACK['version'], cands + assert garrisondl.FALLBACK['sha256'] and garrisondl.FALLBACK['bytes'] > 0 + try: + garrisondl._download('https://static.max-c.com/heybox/desktop/nonexistent.hbext', + os.path.join(tmp, 'x.hbext'), attempts=1, timeout=10) + raise AssertionError('坏 URL 居然下载成功了') + except RuntimeError as e: + assert '下载失败' in str(e), e + + dl_tmp = os.path.join(tmp, 'dl-unit') + os.makedirs(dl_tmp, exist_ok=True) + bad_zip = os.path.join(dl_tmp, 'bad.hbext') + with zipfile.ZipFile(bad_zip, 'w') as z: + z.writestr('core/service.mjs', 'TINY') # 无清单 → 体量下限拒收 + z.writestr('README.md', 'x') + try: + garrisondl._install(bad_zip, '1.2.0') + raise AssertionError('坏包居然装上了') + except RuntimeError as e: + assert '体量异常' in str(e), e + + import hashlib as _hl + gate_zip = os.path.join(dl_tmp, 'gate.hbext') + entries = {} + with zipfile.ZipFile(gate_zip, 'w') as z: + for i in range(120): + z.writestr('core/data/f%d.json' % i, 'x' * 100000) + z.writestr('core/service.mjs', 'S' * 100000) + z.writestr('README.md', 'no license statement here') + with zipfile.ZipFile(gate_zip) as z: + for n in z.namelist(): + if not n.endswith('/'): + entries[n] = {'relativePath': n, 'bytes': z.getinfo(n).file_size, + 'sha256': _hl.sha256(z.read(n)).hexdigest()} + try: + garrisondl._install(gate_zip, '1.2.0', manifest=list(entries.values())) + raise AssertionError('前置校验没拦住') + except garrisondl.NeedConfirmError: + pass + assert not os.path.exists(os.path.join(garrisondl.garrison_dir(), + 'medal-farm-v1.2.0')), '拒装后不能留目录' + + # 已装短路:start() 直接 done,不起线程不下载(用 core_dir 断言即可, + # 别走 api_garrison_status——coreOk+nodeOk 会真去拉宿主进程) + os.makedirs(os.path.join(garrisondl.garrison_dir(), 'medal-farm-v1.1.4', 'core')) + open(os.path.join(garrisondl.garrison_dir(), 'medal-farm-v1.1.4', 'core', + 'service.mjs'), 'w').close() + snap = garrisondl.start() + assert snap['stage'] == 'done', snap + assert garrison.core_dir().endswith('medal-farm-v1.1.4' + os.sep + 'core'), garrison.core_dir() + shutil.rmtree(garrisondl.garrison_dir(), ignore_errors=True) + + # 8) 核心文本补丁:规则随包分发、能打上、幂等、脱靶不动文件 + # (核心 service.mjs 是第三方混淆包:认不出「确认准备就绪吗」弹窗、 + # 免费领取对短名/拉丁名的核对零容错——补丁只做纯文本替换,不改其它逻辑) + assert os.path.isfile(garrison.PATCH_FILE), garrison.PATCH_FILE + rules = garrison._patch_rules() + assert rules and all(r.get('find') and r.get('replace') for r in rules), rules + fake_core = os.path.join(tmp, 'patch-core') + os.makedirs(fake_core, exist_ok=True) + svc = os.path.join(fake_core, 'service.mjs') + with open(svc, 'w', encoding='utf-8') as f: + f.write('x=1;' + ''.join(r['find'] for r in rules) + ';y=2;') + got = garrison.apply_core_patches(fake_core) + assert got['applied'] == len(rules) and not got['miss'], got + with open(svc, encoding='utf-8') as f: + body = f.read() + for r in rules: + assert r['replace'] in body and r['find'] not in body, r['id'] + assert os.path.isfile(svc + '.orig'), '打补丁前必须先留 .orig 备份' + again = garrison.apply_core_patches(fake_core) # 幂等:第二次不重复替换 + assert again['applied'] == 0 and again['skipped'] == len(rules), again + with open(svc, 'w', encoding='utf-8') as f: + f.write('untouched core') # 核心换写法:find 找不到 + miss = garrison.apply_core_patches(fake_core) + assert miss['applied'] == 0 and miss['miss'] == len(rules), miss + with open(svc, encoding='utf-8') as f: + assert f.read() == 'untouched core', '脱靶时一个字节都不能动' + + # ---------------------------------------------------------------- 入口 @@ -4577,6 +4757,7 @@ def main(): r.check('B44 当期活动导航(有效期/指代/模板/点结算页/名单核对)', lambda: check_event_nav(tmp)) r.check('B45 资源包缺分区(EX/S 推断/默认不补前置/突袭不降级)', lambda: check_stage_infer(tmp)) r.check('B46 牛杂小工具(小游戏/活动商店/黑名单位置/卡教程提示)', lambda: check_maa_tool(tmp)) + r.check('B47 卫戍协议(核心检测/MAA 连接默认值/选项清洗/空环境口径/核心补丁)', lambda: check_garrison(tmp)) finally: shutil.rmtree(tmp, ignore_errors=True)