Files
myrzx_bot/ranch_assistant/accounts_gui.py
T

216 lines
9.3 KiB
Python

"""One process with independent account workspaces and workers."""
import json
from pathlib import Path
import re
import uuid
from PySide6 import QtCore as C, QtWidgets as W
from . import gui
from .api import Session
from .sessions import identity
class AccountsWindow(W.QMainWindow):
def __init__(self, root=None):
super().__init__()
gui.use_native_scrollbars()
self.root = Path(root or gui.STATE).resolve()
self.root.mkdir(parents=True, exist_ok=True)
self.index_path = self.root / "accounts.json"
self.windows, self.locks, self.profiles = {}, {}, []
self.setWindowTitle("牧羊人之心牧场辅助 — 多账号")
font = self.font()
font.setPointSizeF(8.5)
self.setFont(font)
self.resize(1100, 740)
central = W.QWidget()
layout = W.QVBoxLayout(central)
self.setCentralWidget(central)
self.setup_menus()
note = W.QLabel("每个页签独立登录、保存 Token 和运行。切换页签不会停止其他账号;自动执行需在各账号里分别开启。")
note.setWordWrap(True)
layout.addWidget(note)
self.tabs = W.QTabWidget()
self.tabs.currentChanged.connect(self.activate_profile)
self.tabs.setTabsClosable(True)
self.tabs.tabCloseRequested.connect(self.close_profile)
layout.addWidget(self.tabs, 1)
try:
self.profiles = json.loads(self.index_path.read_text(encoding="utf-8"))["profiles"]
except (OSError, ValueError, KeyError, TypeError):
self.profiles = [{"id": "default", "label": "账号 1"}]
self.profiles = [p for p in self.profiles if isinstance(p, dict) and re.fullmatch(r"default|[a-f0-9]{32}", str(p.get("id", "")))]
for profile in list(self.profiles):
self.open_profile(profile)
if not self.profiles:
self.add_profile()
gui.compact_layouts(central)
def setup_menus(self):
accounts = self.menuBar().addMenu("账号(&A)")
for text, handler in (("新增账号页签", self.add_profile), ("打开已保存账号…", self.choose_profile),
("恢复各页签的保存会话", self.resume_all)):
accounts.addAction(text, handler)
accounts.addSeparator()
accounts.addAction("退出", self.close)
monitoring = self.menuBar().addMenu("监控(&M)")
monitoring.addAction("全部开始监控", self.monitor_all)
monitoring.addAction("全部停止", self.stop_all)
strategies = self.menuBar().addMenu("策略配置(&S)")
self.save_policy_action = strategies.addAction("保存当前账号策略", self.save_current_policies)
self.save_policy_action.setShortcut("Ctrl+S")
self.import_policy_action = strategies.addAction("导入当前账号策略…",
lambda: self.run_account_action("import_policies"))
self.export_policy_action = strategies.addAction("导出当前账号策略…",
lambda: self.run_account_action("export_policies"))
self.policy_actions = (self.save_policy_action, self.import_policy_action, self.export_policy_action)
strategies.aboutToShow.connect(self.update_account_actions)
help_menu = self.menuBar().addMenu("帮助(&H)")
self.about_action = help_menu.addAction("关于…", self.show_about)
def update_account_actions(self):
window = self.tabs.currentWidget()
for action in self.policy_actions:
action.setEnabled(window is not None and not window.closed)
def run_account_action(self, method):
window = self.tabs.currentWidget()
if window is not None and not window.closed:
return getattr(window, method)()
def save_current_policies(self):
value = self.run_account_action("persist_settings")
if value is not None:
label = self.tabs.tabText(self.tabs.currentIndex())
self.statusBar().showMessage(f"已保存账号“{label}”的策略", 5000)
else:
self.statusBar().showMessage("策略尚未保存,请检查当前账号的输入和提示", 5000)
def show_about(self):
W.QMessageBox.about(self, "关于牧羊人之心牧场辅助",
f"牧羊人之心牧场辅助\n\n辅助版本:{gui.APP_VERSION}(开发中)\n适配游戏版本:{gui.GAME_VERSION}")
def open_profile(self, profile):
identifier = profile["id"]
if identifier in self.windows:
self.tabs.setCurrentWidget(self.windows[identifier])
return
folder = self.root if identifier == "default" else self.root / "profiles" / identifier
folder.mkdir(parents=True, exist_ok=True)
lock = C.QLockFile(str(folder / "workspace.lock"))
if not lock.tryLock(0):
self.statusBar().showMessage("有账号工作区已在其他程序窗口打开,未重复运行")
return
window = gui.Window(folder)
window.connection_guard = lambda session: self.allow_connection(window, session)
window.login_guard = lambda account: self.allow_login(window, account)
window.profile_changed.connect(lambda label: self.rename_profile(identifier, label))
self.windows[identifier], self.locks[identifier] = window, lock
self.tabs.addTab(window, profile.get("label", "账号"))
self.tabs.setCurrentWidget(window)
def add_profile(self):
profile = {"id": uuid.uuid4().hex, "label": f"账号 {len(self.profiles) + 1}"}
self.profiles.append(profile)
self.open_profile(profile)
self.save_index()
def activate_profile(self, *args):
active = self.tabs.currentWidget()
for window in self.windows.values():
window.set_presentation_active(window is active)
self.update_account_actions()
def choose_profile(self):
if not self.profiles:
return
labels = [p.get("label", "账号") + " [" + p["id"][:6] + "]" for p in self.profiles]
label, accepted = W.QInputDialog.getItem(self, "打开账号页签", "保存的账号工作区", labels, 0, False)
if accepted:
self.open_profile(self.profiles[labels.index(label)])
def rename_profile(self, identifier, label):
for profile in self.profiles:
if profile["id"] == identifier:
profile["label"] = label
window = self.windows.get(identifier)
if window:
self.tabs.setTabText(self.tabs.indexOf(window), label)
self.save_index()
def save_index(self):
temporary = self.index_path.with_suffix(".tmp")
temporary.write_text(json.dumps({"profiles": self.profiles}, ensure_ascii=False, indent=2), encoding="utf-8")
temporary.replace(self.index_path)
def allow_login(self, requester, account):
for window in self.windows.values():
if window is not requester and not window.engine.demo and window.account.text().strip() == account:
self.tabs.setCurrentWidget(window)
return False
return True
def allow_connection(self, requester, session):
if not isinstance(session, Session):
return True
for window in self.windows.values():
other = window.engine.client
if window is not requester and other and isinstance(other.session, Session) and identity(other.session) == identity(session):
self.tabs.setCurrentWidget(window)
return False
return True
def resume_all(self):
for window in self.windows.values():
if window.engine.demo and not window.busy and window.saved_sessions.count():
window.resume_session()
def monitor_all(self):
for window in self.windows.values():
if not window.engine.demo:
window.start_monitor.setChecked(True)
def stop_all(self):
for window in self.windows.values():
window.start_monitor.setChecked(False)
window.execute.setChecked(False)
def close_profile(self, index):
window = self.tabs.widget(index)
if window is None:
return
window.start_monitor.setChecked(False)
window.timer.stop()
window.closed = True
window.pending_refresh = None
if window.busy:
C.QTimer.singleShot(250, lambda: self.close_profile(self.tabs.indexOf(window)))
return
identifier = next(k for k, value in self.windows.items() if value is window)
window.close()
self.tabs.removeTab(index)
del self.windows[identifier]
self.locks.pop(identifier).unlock()
# Workspaces and saved sessions remain on disk for the next launch.
window.deleteLater()
def closeEvent(self, event):
self.stop_all()
for window in self.windows.values():
window.timer.stop()
window.closed = True
window.pending_refresh = None
if any(window.busy for window in self.windows.values()):
self.setEnabled(False)
self.statusBar().showMessage("正在完成当前请求,完成后自动关闭并保存会话")
C.QTimer.singleShot(250, self.close)
event.ignore()
return
for window in self.windows.values():
window.close()
for lock in self.locks.values():
lock.unlock()
self.save_index()
event.accept()