diff --git a/app/config.py b/app/config.py index 9be1336..c5264e5 100644 --- a/app/config.py +++ b/app/config.py @@ -29,6 +29,7 @@ import sqlite3 import json import os import sys +from pathlib import Path from typing import Dict, Union @@ -36,17 +37,15 @@ class AppConfig: def __init__(self) -> None: - self.app_path = os.path.normpath( - os.path.dirname(os.path.realpath(sys.argv[0])) - ) # 获取软件自身的路径 + self.app_path = Path.cwd() # 获取软件根目录 self.app_path_sys = os.path.realpath(sys.argv[0]) # 获取软件自身的路径 self.app_name = os.path.basename(self.app_path) # 获取软件自身的名称 - self.database_path = os.path.normpath(f"{self.app_path}/data/data.db") - self.config_path = os.path.normpath(f"{self.app_path}/config/gui.json") - self.key_path = os.path.normpath(f"{self.app_path}/data/key") - self.gameid_path = os.path.normpath(f"{self.app_path}/data/gameid.txt") - self.version_path = os.path.normpath(f"{self.app_path}/resources/version.json") + self.database_path = self.app_path / "data/data.db" + self.config_path = self.app_path / "config/gui.json" + self.key_path = self.app_path / "data/key" + self.gameid_path = self.app_path / "data/gameid.txt" + self.version_path = self.app_path / "resources/version.json" # 检查文件完整性 self.initialize() @@ -57,40 +56,32 @@ class AppConfig: """初始化程序的配置文件""" # 检查目录 - os.makedirs(os.path.normpath(f"{self.app_path}/data"), exist_ok=True) - os.makedirs(os.path.normpath(f"{self.app_path}/config"), exist_ok=True) - os.makedirs( - os.path.normpath(f"{self.app_path}/data/MAAconfig/simple"), exist_ok=True - ) - os.makedirs( - os.path.normpath(f"{self.app_path}/data/MAAconfig/beta"), exist_ok=True - ) - os.makedirs( - os.path.normpath(f"{self.app_path}/data/MAAconfig/Default"), exist_ok=True - ) + (self.app_path / "config").mkdir(parents=True, exist_ok=True) + (self.app_path / "data/MAAconfig/simple").mkdir(parents=True, exist_ok=True) + (self.app_path / "data/MAAconfig/beta").mkdir(parents=True, exist_ok=True) + (self.app_path / "data/MAAconfig/Default").mkdir(parents=True, exist_ok=True) # 生成版本信息文件 - if not os.path.exists(self.version_path): + if not self.version_path.exists(): version = { "main_version": "0.0.0.0", "updater_version": "0.0.0.0", } - with open(self.version_path, "w", encoding="utf-8") as f: + with self.version_path.open(mode="w", encoding="utf-8") as f: json.dump(version, f, indent=4) # 生成配置文件 - if not os.path.exists(self.config_path): + if not self.config_path.exists(): config = {"Default": {}} - with open(self.config_path, "w", encoding="utf-8") as f: + with self.config_path.open(mode="w", encoding="utf-8") as f: json.dump(config, f, indent=4) # 生成预设gameid替换方案文件 - if not os.path.exists(self.gameid_path): - with open(self.gameid_path, "w", encoding="utf-8") as f: - print( - "龙门币:CE-6\n技能:CA-5\n红票:AP-5\n经验:LS-6\n剿灭模式:Annihilation", - file=f, - ) + if not self.gameid_path.exists(): + self.gameid_path.write_text( + "龙门币:CE-6\n技能:CA-5\n红票:AP-5\n经验:LS-6\n剿灭模式:Annihilation", + encoding="utf-8", + ) def check_config(self) -> None: """检查配置文件字段完整性并补全""" @@ -136,7 +127,7 @@ class AppConfig: ] # 导入配置文件 - with open(self.config_path, "r", encoding="utf-8") as f: + with self.config_path.open(mode="r", encoding="utf-8") as f: config = json.load(f) # 检查并补充缺失的字段 @@ -154,7 +145,7 @@ class AppConfig: """检查用户数据库文件并处理数据库版本更新""" # 生成用户数据库 - if not os.path.exists(self.database_path): + if not self.database_path.exists(): db = sqlite3.connect(self.database_path) cur = db.cursor() cur.execute( @@ -244,5 +235,5 @@ class AppConfig: def save_config(self) -> None: """保存配置文件""" - with open(self.config_path, "w", encoding="utf-8") as f: + with self.config_path.open(mode="w", encoding="utf-8") as f: json.dump(self.content, f, indent=4) diff --git a/app/models/MAA.py b/app/models/MAA.py index af9796f..e268645 100644 --- a/app/models/MAA.py +++ b/app/models/MAA.py @@ -32,6 +32,7 @@ import os import subprocess import shutil import time +from pathlib import Path from app import AppConfig @@ -59,16 +60,11 @@ class MaaManager(QtCore.QThread): def configure(self): """提取配置信息""" - self.set_path = os.path.normpath( - f"{self.config.content["Default"]["MaaSet.path"]}/config/gui.json" - ) - self.log_path = os.path.normpath( - f"{self.config.content["Default"]["MaaSet.path"]}/debug/gui.log" - ) - self.maa_path = os.path.normpath( - f"{self.config.content["Default"]["MaaSet.path"]}/MAA.exe" - ) - self.json_path = os.path.normpath(f"{self.config.app_path}/data/MAAconfig") + self.maa_root_path = Path(self.config.content["Default"]["MaaSet.path"]) + self.set_path = self.maa_root_path / "config/gui.json" + self.log_path = self.maa_root_path / "debug/gui.log" + self.maa_path = self.maa_root_path / "MAA.exe" + self.json_path = self.config.app_path / "data/MAAconfig" self.routine = self.config.content["Default"]["TimeLimit.routine"] self.annihilation = self.config.content["Default"]["TimeLimit.annihilation"] self.num = self.config.content["Default"]["TimesLimit.run"] @@ -500,33 +496,29 @@ class MaaManager(QtCore.QThread): # 保存运行日志 end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") - with open( - os.path.normpath(f"{self.config.app_path}/log.txt"), - "w", - encoding="utf-8", - ) as f: - print(f"任务开始时间:{begin_time},结束时间:{end_time}", file=f) - print( - f"已完成数:{len(over_index)},未完成数:{len(error_index) + len(wait_index)}\n", - file=f, + end_log = ( + f"任务开始时间:{begin_time},结束时间:{end_time}\n" + f"已完成数:{len(over_index)},未完成数:{len(error_index) + len(wait_index)}\n\n" + ) + + if len(error_index) != 0: + end_log += ( + f"{self.mode[2:4]}未成功的用户:\n" + f"{"\n".join([self.data[_][0] for _ in error_index])}\n" ) - if len(error_index) != 0: - print(f"{self.mode[2:4]}未成功的用户:", file=f) - print("\n".join([self.data[_][0] for _ in error_index]), file=f) - wait_index = [ - _ for _ in all_index if (not _ in over_index + error_index) - ] - if len(wait_index) != 0: - print(f"\n未开始{self.mode[2:4]}的用户:", file=f) - print("\n".join([self.data[_][0] for _ in wait_index]), file=f) + wait_index = [_ for _ in all_index if (not _ in over_index + error_index)] + if len(wait_index) != 0: + end_log += ( + f"\n未开始{self.mode[2:4]}的用户:\n" + f"{"\n".join([self.data[_][0] for _ in wait_index])}\n" + ) + + (self.config.app_path / "log.txt").write_text( + end_log, + encoding="utf-8", + ) # 恢复GUI运行面板 - with open( - os.path.normpath(f"{self.config.app_path}/log.txt"), - "r", - encoding="utf-8", - ) as f: - end_log = f.read() self.update_gui.emit("", "", "", "", end_log) # 推送代理结果通知 @@ -553,7 +545,7 @@ class MaaManager(QtCore.QThread): logs = [] if_log_start = False - with open(self.log_path, "r", encoding="utf-8") as f: + with self.log_path.open(mode="r", encoding="utf-8") as f: for entry in f: if not if_log_start: try: @@ -618,20 +610,18 @@ class MaaManager(QtCore.QThread): # 预导入MAA配置文件 if mode == "设置MAA_用户": set_book = ["simple", "beta"] - if os.path.exists( - os.path.normpath( - f"{self.json_path}/{set_book[self.get_json_path[0]]}/{self.get_json_path[1]}/{self.get_json_path[2]}/gui.json" - ) - ): + if ( + self.json_path + / f"{set_book[self.get_json_path[0]]}/{self.get_json_path[1]}/{self.get_json_path[2]}/gui.json" + ).exists(): shutil.copy( - os.path.normpath( - f"{self.json_path}/{set_book[self.get_json_path[0]]}/{self.get_json_path[1]}/{self.get_json_path[2]}/gui.json" - ), + self.json_path + / f"{set_book[self.get_json_path[0]]}/{self.get_json_path[1]}/{self.get_json_path[2]}/gui.json", self.set_path, ) else: shutil.copy( - os.path.normpath(f"{self.json_path}/Default/gui.json"), + self.json_path / "Default/gui.json", self.set_path, ) elif (mode == "设置MAA_全局") or ( @@ -639,32 +629,27 @@ class MaaManager(QtCore.QThread): and self.data[index][15] == "simple" ): shutil.copy( - os.path.normpath(f"{self.json_path}/Default/gui.json"), + self.json_path / "Default/gui.json", self.set_path, ) elif "日常代理" in mode and self.data[index][15] == "beta": if mode == "日常代理_剿灭": shutil.copy( - os.path.normpath( - f"{self.json_path}/beta/{self.data[index][16]}/annihilation/gui.json" - ), + self.json_path + / f"beta/{self.data[index][16]}/annihilation/gui.json", self.set_path, ) elif mode == "日常代理_日常": shutil.copy( - os.path.normpath( - f"{self.json_path}/beta/{self.data[index][16]}/routine/gui.json" - ), + self.json_path / f"beta/{self.data[index][16]}/routine/gui.json", self.set_path, ) elif "人工排查" in mode and self.data[index][15] == "beta": shutil.copy( - os.path.normpath( - f"{self.json_path}/beta/{self.data[index][16]}/routine/gui.json" - ), + self.json_path / f"beta/{self.data[index][16]}/routine/gui.json", self.set_path, ) - with open(self.set_path, "r", encoding="utf-8") as f: + with self.set_path.open(mode="r", encoding="utf-8") as f: data = json.load(f) # 日常代理配置 @@ -1000,7 +985,7 @@ class MaaManager(QtCore.QThread): ] = "False" # 生息演算 # 覆写配置文件 - with open(self.set_path, "w", encoding="utf-8") as f: + with self.set_path.open(mode="w", encoding="utf-8") as f: json.dump(data, f, indent=4) return True @@ -1009,12 +994,10 @@ class MaaManager(QtCore.QThread): """获取模拟器路径""" # 读取配置文件 - with open(self.set_path, "r", encoding="utf-8") as f: + with self.set_path.open(mode="r", encoding="utf-8") as f: set = json.load(f) - # 获取模拟器路径 - return os.path.normpath( - set["Configurations"]["Default"]["Start.EmulatorPath"] - ) + # 获取模拟器路径 + return Path(set["Configurations"]["Default"]["Start.EmulatorPath"]) def server_date(self): """获取当前的服务器日期""" diff --git a/app/services/notification.py b/app/services/notification.py index 2a56872..d8c45f8 100644 --- a/app/services/notification.py +++ b/app/services/notification.py @@ -48,9 +48,7 @@ class Notification: title=title, message=message, app_name="AUTO_MAA", - app_icon=os.path.normpath( - f"{self.config.app_path}/resources/icons/AUTO_MAA.ico" - ), + app_icon=self.config.app_path / "resources/icons/AUTO_MAA.ico", timeout=t, ticker=ticker, toast=True, diff --git a/app/services/security.py b/app/services/security.py index 4fbd3b1..b39dc00 100644 --- a/app/services/security.py +++ b/app/services/security.py @@ -47,32 +47,27 @@ class CryptoHandler: """配置管理密钥""" # 生成目录 - os.makedirs(os.path.normpath(f"{self.config.app_path}/data/key"), exist_ok=True) + self.config.key_path.mkdir(parents=True, exist_ok=True) # 生成RSA密钥对 key = RSA.generate(2048) public_key_local = key.publickey() private_key = key # 保存RSA公钥 - with open( - os.path.normpath(f"{self.config.app_path}/data/key/public_key.pem"), "wb" - ) as f: - f.write(public_key_local.exportKey()) + (self.config.app_path / "data/key/public_key.pem").write_bytes( + public_key_local.exportKey() + ) # 生成密钥转换与校验随机盐 PASSWORD_salt = secrets.token_hex(random.randint(32, 1024)) - with open( - os.path.normpath(f"{self.config.app_path}/data/key/PASSWORDsalt.txt"), - "w", + (self.config.app_path / "data/key/PASSWORDsalt.txt").write_text( + PASSWORD_salt, encoding="utf-8", - ) as f: - print(PASSWORD_salt, file=f) + ) verify_salt = secrets.token_hex(random.randint(32, 1024)) - with open( - os.path.normpath(f"{self.config.app_path}/data/key/verifysalt.txt"), - "w", + (self.config.app_path / "data/key/verifysalt.txt").write_text( + verify_salt, encoding="utf-8", - ) as f: - print(verify_salt, file=f) + ) # 将管理密钥转化为AES-256密钥 AES_password = hashlib.sha256( (PASSWORD + PASSWORD_salt).encode("utf-8") @@ -81,29 +76,23 @@ class CryptoHandler: AES_password_verify = hashlib.sha256( AES_password + verify_salt.encode("utf-8") ).digest() - with open( - os.path.normpath( - f"{self.config.app_path}/data/key/AES_password_verify.bin" - ), - "wb", - ) as f: - f.write(AES_password_verify) + (self.config.app_path / "data/key/AES_password_verify.bin").write_bytes( + AES_password_verify + ) # AES-256加密RSA私钥并保存密文 AES_key = AES.new(AES_password, AES.MODE_ECB) private_key_local = AES_key.encrypt(pad(private_key.exportKey(), 32)) - with open( - os.path.normpath(f"{self.config.app_path}/data/key/private_key.bin"), "wb" - ) as f: - f.write(private_key_local) + (self.config.app_path / "data/key/private_key.bin").write_bytes( + private_key_local + ) def encryptx(self, note: str) -> bytes: """加密数据""" # 读取RSA公钥 - with open( - os.path.normpath(f"{self.config.app_path}/data/key/public_key.pem"), "rb" - ) as f: - public_key_local = RSA.import_key(f.read()) + public_key_local = RSA.import_key( + (self.config.app_path / "data/key/public_key.pem").read_bytes() + ) # 使用RSA公钥对数据进行加密 cipher = PKCS1_OAEP.new(public_key_local) encrypted = cipher.encrypt(note.encode("utf-8")) @@ -113,29 +102,24 @@ class CryptoHandler: """解密数据""" # 读入RSA私钥密文、盐与校验哈希值 - with open( - os.path.normpath(f"{self.config.app_path}/data/key/private_key.bin"), "rb" - ) as f: - private_key_local = f.read().strip() - with open( - os.path.normpath(f"{self.config.app_path}/data/key/PASSWORDsalt.txt"), - "r", - encoding="utf-8", - ) as f: - PASSWORD_salt = f.read().strip() - with open( - os.path.normpath(f"{self.config.app_path}/data/key/verifysalt.txt"), - "r", - encoding="utf-8", - ) as f: - verify_salt = f.read().strip() - with open( - os.path.normpath( - f"{self.config.app_path}/data/key/AES_password_verify.bin" - ), - "rb", - ) as f: - AES_password_verify = f.read().strip() + private_key_local = ( + (self.config.app_path / "data/key/private_key.bin").read_bytes().strip() + ) + PASSWORD_salt = ( + (self.config.app_path / "data/key/PASSWORDsalt.txt") + .read_text(encoding="utf-8") + .strip() + ) + verify_salt = ( + (self.config.app_path / "data/key/verifysalt.txt") + .read_text(encoding="utf-8") + .strip() + ) + AES_password_verify = ( + (self.config.app_path / "data/key/AES_password_verify.bin") + .read_bytes() + .strip() + ) # 将管理密钥转化为AES-256密钥并验证 AES_password = hashlib.sha256( (PASSWORD + PASSWORD_salt).encode("utf-8") diff --git a/app/ui/gui.py b/app/ui/gui.py index 9cb7ef1..ea7fcc1 100644 --- a/app/ui/gui.py +++ b/app/ui/gui.py @@ -52,9 +52,9 @@ from PySide6.QtGui import QIcon, QCloseEvent from PySide6 import QtCore from functools import partial from typing import List, Tuple +from pathlib import Path import json import datetime -import os import ctypes import subprocess import shutil @@ -150,17 +150,13 @@ class Main(QWidget): ] # 导入ui配置 - self.ui = uiLoader.load( - os.path.normpath(f"{self.config.app_path}/resources/gui/main.ui") - ) + self.ui = uiLoader.load(self.config.app_path / "resources/gui/main.ui") self.ui.setWindowIcon( - QIcon( - os.path.normpath(f"{self.config.app_path}/resources/icons/AUTO_MAA.ico") - ) + QIcon(str(self.config.app_path / "resources/icons/AUTO_MAA.ico")) ) # 生成管理密钥 - if not os.path.exists(self.config.key_path): + if not self.config.key_path.exists(): while True: self.PASSWORD, ok_pressed = QInputDialog.getText( self.ui, @@ -608,9 +604,7 @@ class Main(QWidget): self.config.content["Default"]["SelfSet.MainIndex"] ) - self.maa_path.setText( - os.path.normpath(self.config.content["Default"]["MaaSet.path"]) - ) + self.maa_path.setText(str(Path(self.config.content["Default"]["MaaSet.path"]))) self.routine.setValue(self.config.content["Default"]["TimeLimit.routine"]) self.annihilation.setValue( self.config.content["Default"]["TimeLimit.annihilation"] @@ -688,7 +682,7 @@ class Main(QWidget): """添加一位新用户""" # 判断是否已设置管理密钥 - if not os.path.exists(self.config.key_path): + if not self.config.key_path.exists(): QMessageBox.critical( self.ui, "错误", @@ -752,15 +746,13 @@ class Main(QWidget): ), ) self.config.db.commit() - if os.path.exists( - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{row}" - ) - ): + if ( + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{row}" + ).exists(): shutil.rmtree( - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{row}" - ) + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{row}" ) # 后续用户补位 if self.user_set.currentIndex() == 0: @@ -773,18 +765,16 @@ class Main(QWidget): (i - 1, self.user_mode_list[self.user_set.currentIndex()], i), ) self.config.db.commit() - if os.path.exists( - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{i}" - ) - ): - os.rename( - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{i}" - ), - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{i - 1}" - ), + if ( + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{i}" + ).exists(): + ( + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{i}" + ).rename( + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{i - 1}", ) # 同步最终结果至GUI @@ -841,18 +831,15 @@ class Main(QWidget): ), ) self.config.db.commit() - if os.path.exists( - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{row}" - ) - ): + if ( + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{row}" + ).exists(): shutil.move( - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{row}" - ), - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[1 - self.user_set.currentIndex()]}/{other_numb}" - ), + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{row}", + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[1 - self.user_set.currentIndex()]}/{other_numb}", ) # 后续用户补位 for i in range(row + 1, current_numb): @@ -861,19 +848,18 @@ class Main(QWidget): (i - 1, self.user_mode_list[self.user_set.currentIndex()], i), ) self.config.db.commit(), - if os.path.exists( - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{i}" - ) - ): - os.rename( - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{i}" - ), - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{i - 1}" - ), + if ( + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{i}" + ).exists(): + ( + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{i}" + ).rename( + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{i - 1}" ) + self.update_user_info("normal") def get_maa_config(self, info): @@ -881,31 +867,22 @@ class Main(QWidget): # 获取全局MAA配置文件 if info == ["Default"]: - os.makedirs( - os.path.normpath(f"{self.config.app_path}/data/MAAconfig/Default"), - exist_ok=True, - ) shutil.copy( - os.path.normpath( - f"{self.config.content["Default"]["MaaSet.path"]}/config/gui.json" - ), - os.path.normpath(f"{self.config.app_path}/data/MAAconfig/Default"), + Path(self.config.content["Default"]["MaaSet.path"]) / "config/gui.json", + self.config.app_path / "data/MAAconfig/Default", ) # 获取基建配置文件 elif info[2] == "infrastructure": infrastructure_path = self.read("file_path_infrastructure") if infrastructure_path: - os.makedirs( - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[info[0]]}/{info[1]}/infrastructure" - ), - exist_ok=True, - ) + ( + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[info[0]]}/{info[1]}/infrastructure" + ).mkdir(parents=True, exist_ok=True) shutil.copy( infrastructure_path, - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[info[0]]}/{info[1]}/infrastructure/infrastructure.json" - ), + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[info[0]]}/{info[1]}/infrastructure/infrastructure.json", ) return True else: @@ -917,19 +894,14 @@ class Main(QWidget): return False # 获取高级用户MAA配置文件 elif info[2] in ["routine", "annihilation"]: - os.makedirs( - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[info[0]]}/{info[1]}/{info[2]}" - ), - exist_ok=True, - ) + ( + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[info[0]]}/{info[1]}/{info[2]}" + ).mkdir(parents=True, exist_ok=True) shutil.copy( - os.path.normpath( - f"{self.config.content["Default"]["MaaSet.path"]}/config/gui.json" - ), - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[info[0]]}/{info[1]}/{info[2]}" - ), + Path(self.config.content["Default"]["MaaSet.path"]) / "config/gui.json", + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[info[0]]}/{info[1]}/{info[2]}", ) def change_user_Item(self, item: QTableWidget, mode): @@ -952,7 +924,7 @@ class Main(QWidget): if item.column() in [6, 7, 8]: # 关卡号 # 导入与应用特殊关卡规则 games = {} - with open(self.config.gameid_path, encoding="utf-8") as f: + with self.config.gameid_path.open(mode="r", encoding="utf-8") as f: gameids = f.readlines() for line in gameids: if ":" in line: @@ -1006,11 +978,10 @@ class Main(QWidget): index == 2 or ( index == 0 - and not os.path.exists( - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{row}/infrastructure/infrastructure.json" - ), - ) + and not ( + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{row}/infrastructure/infrastructure.json" + ).exists() ) ) ): @@ -1026,11 +997,10 @@ class Main(QWidget): index == 2 or ( index == 0 - and not os.path.exists( - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{row}/{column}/gui.json" - ), - ) + and not ( + self.config.app_path + / f"data/MAAconfig/{self.user_mode_list[self.user_set.currentIndex()]}/{row}/{column}/gui.json" + ).exists() ) ) ): @@ -1097,16 +1067,14 @@ class Main(QWidget): return None # 验证MAA路径 - if os.path.normpath( - self.config.content["Default"]["MaaSet.path"] - ) != os.path.normpath(self.maa_path.text()): - if os.path.exists( - os.path.normpath(f"{self.maa_path.text()}/MAA.exe") - ) and os.path.exists( - os.path.normpath(f"{self.maa_path.text()}/config/gui.json") - ): - self.config.content["Default"]["MaaSet.path"] = os.path.normpath( - self.maa_path.text() + if Path(self.config.content["Default"]["MaaSet.path"]) != Path( + self.maa_path.text() + ): + if (Path(self.maa_path.text()) / "MAA.exe").exists() and ( + Path(self.maa_path.text()) / "config/gui.json" + ).exists(): + self.config.content["Default"]["MaaSet.path"] = str( + Path(self.maa_path.text()) ) self.get_maa_config(["Default"]) else: @@ -1358,17 +1326,13 @@ class Main(QWidget): """启动MaaManager线程运行任务""" # 检查MAA路径是否可用 - if not ( - os.path.exists( - os.path.normpath( - f"{self.config.content["Default"]["MaaSet.path"]}/MAA.exe" - ) - ) - and os.path.exists( - os.path.normpath( - f"{self.config.content["Default"]["MaaSet.path"]}/config/gui.json" - ) - ) + if ( + not ( + Path(self.config.content["Default"]["MaaSet.path"]) / "MAA.exe" + ).exists() + and ( + Path(self.config.content["Default"]["MaaSet.path"]) / "config/gui.json" + ).exists() ): QMessageBox.critical(self.ui, "错误", "您还未正确配置MAA路径!") return None @@ -1437,12 +1401,8 @@ class Main(QWidget): elif "结束" in mode: shutil.copy( - os.path.normpath( - f"{self.config.app_path}/data/MAAconfig/Default/gui.json" - ), - os.path.normpath( - f"{self.config.content["Default"]["MaaSet.path"]}/config" - ), + self.config.app_path / "data/MAAconfig/Default/gui.json", + Path(self.config.content["Default"]["MaaSet.path"]) / "config", ) self.user_add.setEnabled(True) self.user_del.setEnabled(True) @@ -1474,7 +1434,7 @@ class Main(QWidget): """检查版本更新,调起文件下载进程""" # 从本地版本信息文件获取当前版本信息 - with open(self.config.version_path, "r", encoding="utf-8") as f: + with self.config.version_path.open(mode="r", encoding="utf-8") as f: version_current = json.load(f) main_version_current = list( map(int, version_current["main_version"].split(".")) @@ -1483,7 +1443,7 @@ class Main(QWidget): map(int, version_current["updater_version"].split(".")) ) # 检查更新器是否存在 - if not os.path.exists(os.path.normpath(f"{self.config.app_path}/Updater.exe")): + if not (self.config.app_path / "Updater.exe").exists(): updater_version_current = [0, 0, 0, 0] # 从远程服务器获取最新版本信息 @@ -1565,7 +1525,7 @@ class Main(QWidget): """更新主程序""" subprocess.Popen( - os.path.normpath(f"{self.config.app_path}/Updater.exe"), + str(self.config.app_path / "Updater.exe"), shell=True, creationflags=subprocess.CREATE_NO_WINDOW, ) @@ -1597,17 +1557,13 @@ class AUTO_MAA(QMainWindow): self.main = Main(config=config, notify=notify, crypto=crypto) self.setCentralWidget(self.main.ui) self.setWindowIcon( - QIcon( - os.path.normpath(f"{self.config.app_path}/resources/icons/AUTO_MAA.ico") - ) + QIcon(str(self.config.app_path / "resources/icons/AUTO_MAA.ico")) ) self.setWindowTitle("AUTO_MAA") # 创建系统托盘及其菜单 self.tray = QSystemTrayIcon( - QIcon( - os.path.normpath(f"{self.config.app_path}/resources/icons/AUTO_MAA.ico") - ), + QIcon(str(self.config.app_path / "resources/icons/AUTO_MAA.ico")), self, ) self.tray.setToolTip("AUTO_MAA") diff --git a/app/utils/Updater.py b/app/utils/Updater.py index b846699..8f50f43 100644 --- a/app/utils/Updater.py +++ b/app/utils/Updater.py @@ -32,6 +32,7 @@ import zipfile import requests import subprocess import time +from pathlib import Path from PySide6.QtWidgets import ( QApplication, @@ -53,7 +54,7 @@ class UpdateProcess(QThread): accomplish = Signal() def __init__( - self, app_path: str, name: str, main_version: list, updater_version: list + self, app_path: Path, name: str, main_version: list, updater_version: list ) -> None: super(UpdateProcess, self).__init__() @@ -61,10 +62,8 @@ class UpdateProcess(QThread): self.name = name self.main_version = main_version self.updater_version = updater_version - self.download_path = os.path.normpath( - f"{app_path}/AUTO_MAA_Update.zip" - ) # 临时下载文件的路径 - self.version_path = os.path.normpath(f"{app_path}/resources/version.json") + self.download_path = app_path / "AUTO_MAA_Update.zip" # 临时下载文件的路径 + self.version_path = app_path / "resources/version.json" def run(self) -> None: @@ -185,7 +184,7 @@ class UpdateProcess(QThread): # 主程序更新完成后打开AUTO_MAA if self.name == "AUTO_MAA主程序": subprocess.Popen( - os.path.normpath(f"{self.app_path}/AUTO_MAA.exe"), + str(self.app_path / "AUTO_MAA.exe"), shell=True, creationflags=subprocess.CREATE_NO_WINDOW, ) @@ -252,7 +251,7 @@ class UpdateProcess(QThread): class Updater(QObject): def __init__( - self, app_path: str, name: str, main_version: list, updater_version: list + self, app_path: Path, name: str, main_version: list, updater_version: list ) -> None: super().__init__() @@ -260,7 +259,7 @@ class Updater(QObject): self.ui.setWindowTitle("AUTO_MAA更新器") self.ui.resize(700, 70) self.ui.setWindowIcon( - QIcon(os.path.normpath(f"{app_path}/resources/icons/AUTO_MAA_Updater.ico")) + QIcon(str(app_path / "resources/icons/AUTO_MAA_Updater.ico")) ) # 创建垂直布局 @@ -292,7 +291,7 @@ class Updater(QObject): class AUTO_MAA_Updater(QApplication): def __init__( - self, app_path: str, name: str, main_version: list, updater_version: list + self, app_path: Path, name: str, main_version: list, updater_version: list ) -> None: super().__init__() @@ -303,14 +302,12 @@ class AUTO_MAA_Updater(QApplication): if __name__ == "__main__": # 获取软件自身的路径 - app_path = os.path.normpath(os.path.dirname(os.path.realpath(sys.argv[0]))) + app_path = Path.cwd() # 从本地版本信息文件获取当前版本信息 - if os.path.exists(os.path.normpath(f"{app_path}/resources/version.json")): - with open( - os.path.normpath(f"{app_path}/resources/version.json"), - "r", - encoding="utf-8", + if (app_path / "resources/version.json").exists(): + with (app_path / "resources/version.json").open( + mode="r", encoding="utf-8" ) as f: version_current = json.load(f) main_version_current = list( diff --git a/app/utils/package.py b/app/utils/package.py index af54e99..5120980 100644 --- a/app/utils/package.py +++ b/app/utils/package.py @@ -29,13 +29,16 @@ import os import json import shutil import subprocess +from pathlib import Path from app import version_text if __name__ == "__main__": - with open("resources/version.json", "r", encoding="utf-8") as f: + root_path = Path.cwd() + + with (root_path / "resources/version.json").open(mode="r", encoding="utf-8") as f: version = json.load(f) main_version_numb = list(map(int, version["main_version"].split("."))) @@ -63,18 +66,17 @@ if __name__ == "__main__": print(result.stderr) print("AUTO_MAA main program packaging completed !") - shutil.copy(os.path.normpath("app/utils/Updater.py"), os.path.normpath(".")) + shutil.copy(root_path / "app/utils/Updater.py", root_path) - with open(os.path.normpath("Updater.py"), "r", encoding="utf-8") as f: - file_content = f.read() + file_content = (root_path / "Updater.py").read_text(encoding="utf-8") - file_content = file_content.replace( - "from .version import version_text", "from app import version_text" + (root_path / "Updater.py").write_text( + file_content.replace( + "from .version import version_text", "from app import version_text" + ), + encoding="utf-8", ) - with open(os.path.normpath("Updater.py"), "w", encoding="utf-8") as f: - f.write(file_content) - print("Packaging AUTO_MAA update program ...") result = subprocess.run( @@ -97,10 +99,9 @@ if __name__ == "__main__": print(result.stderr) print("AUTO_MAA update program packaging completed !") - os.remove(os.path.normpath("Updater.py")) + os.remove(root_path / "Updater.py") - with open("version_info.txt", "w", encoding="utf-8") as f: - print( - f"{version_text(main_version_numb)}\n{version_text(updater_version_numb)}{version["announcement"]}", - file=f, - ) + (root_path / "version_info.txt").write_text( + f"{version_text(main_version_numb)}\n{version_text(updater_version_numb)}{version["announcement"]}", + encoding="utf-8", + )