212 lines
9.8 KiB
Python
212 lines
9.8 KiB
Python
"""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("不支持此操作")
|