feat(core): 集成日志记录功能以增强调试和错误处理

- 在多个模块中添加日志记录功能,替代原有的打印输出,提升调试信息的管理。
- 更新主窗口、下载管理器、离线模式管理器等,确保在关键操作中记录详细日志。
- 优化异常处理逻辑,确保在发生错误时能够记录相关信息,便于后续排查。
- 增强用户体验,通过日志记录提供更清晰的操作反馈和状态信息。
This commit is contained in:
hyb-oyqq
2025-08-06 17:16:21 +08:00
parent 7befe19f30
commit dfdeb54b43
15 changed files with 338 additions and 315 deletions

View File

@@ -6,6 +6,10 @@ from PySide6.QtGui import QIcon, QPixmap
from utils import msgbox_frame, resource_path
from workers import IpOptimizerThread
from utils.logger import setup_logger
# 初始化logger
logger = setup_logger("cloudflare_optimizer")
class CloudflareOptimizer:
@@ -77,7 +81,7 @@ class CloudflareOptimizer:
# 判断是否继续优选的逻辑
if existing_ips and self.has_optimized_in_session:
# 如果本次会话中已执行过优选且hosts中存在记录则跳过优选过程
print(f"发现hosts文件中已有域名 {hostname} 的优选IP记录且本次会话已优选过跳过优选过程")
logger.info(f"发现hosts文件中已有域名 {hostname} 的优选IP记录且本次会话已优选过跳过优选过程")
# 设置标记为已优选完成
self.optimization_done = True
@@ -92,12 +96,12 @@ class CloudflareOptimizer:
if ipv6_entries:
self.optimized_ipv6 = ipv6_entries[0]
print(f"使用已存在的优选IP - IPv4: {self.optimized_ip}, IPv6: {self.optimized_ipv6}")
logger.info(f"使用已存在的优选IP - IPv4: {self.optimized_ip}, IPv6: {self.optimized_ipv6}")
return True
else:
# 如果本次会话尚未优选过或hosts中没有记录则显示优选窗口
if existing_ips:
print(f"发现hosts文件中已有域名 {hostname} 的优选IP记录但本次会话尚未优选过")
logger.info(f"发现hosts文件中已有域名 {hostname} 的优选IP记录但本次会话尚未优选过")
# 清理已有的hosts记录准备重新优选
self.hosts_manager.clean_hostname_entries(hostname)
@@ -175,7 +179,7 @@ class CloudflareOptimizer:
# 如果启用IPv6同时启动IPv6优化线程
if use_ipv6:
print("IPv6已启用将同时优选IPv6地址")
logger.info("IPv6已启用将同时优选IPv6地址")
self.ipv6_optimizer_thread = IpOptimizerThread(url, use_ipv6=True)
self.ipv6_optimizer_thread.finished.connect(self.on_ipv6_optimization_finished)
self.ipv6_optimizer_thread.start()
@@ -225,11 +229,11 @@ class CloudflareOptimizer:
return
self.optimized_ip = ip
print(f"IPv4优选完成结果: {ip if ip else '未找到合适的IP'}")
logger.info(f"IPv4优选完成结果: {ip if ip else '未找到合适的IP'}")
# 检查是否还有IPv6优化正在运行
if hasattr(self, 'ipv6_optimizer_thread') and self.ipv6_optimizer_thread and self.ipv6_optimizer_thread.isRunning():
print("等待IPv6优选完成...")
logger.info("等待IPv6优选完成...")
return
# 所有优选都已完成,继续处理
@@ -256,11 +260,11 @@ class CloudflareOptimizer:
return
self.optimized_ipv6 = ipv6
print(f"IPv6优选完成结果: {ipv6 if ipv6 else '未找到合适的IPv6'}")
logger.info(f"IPv6优选完成结果: {ipv6 if ipv6 else '未找到合适的IPv6'}")
# 检查IPv4优化是否已完成
if hasattr(self, 'ip_optimizer_thread') and self.ip_optimizer_thread and self.ip_optimizer_thread.isRunning():
print("等待IPv4优选完成...")
logger.info("等待IPv4优选完成...")
return
# 所有优选都已完成,继续处理

View File

@@ -2,8 +2,12 @@ import os
import sys
from PySide6 import QtWidgets
from data.config import LOG_FILE
from utils.logger import setup_logger
from utils import Logger
# 初始化logger
logger = setup_logger("debug_manager")
class DebugManager:
def __init__(self, main_window):
"""初始化调试管理器
@@ -52,7 +56,7 @@ class DebugManager:
Args:
checked: 是否启用调试模式
"""
print(f"Toggle debug mode: {checked}")
logger.info(f"Toggle debug mode: {checked}")
self.main_window.config["debug_mode"] = checked
self.main_window.save_config(self.main_window.config)
@@ -70,7 +74,7 @@ class DebugManager:
# 如果配置中已设置离线模式,则在调试模式下强制启用
if offline_mode_enabled:
print("DEBUG: 调试模式下强制启用离线模式")
logger.debug("DEBUG: 调试模式下强制启用离线模式")
self.main_window.offline_mode_manager.set_offline_mode(True)
# 更新UI中的离线模式选项
@@ -79,7 +83,7 @@ class DebugManager:
self.ui_manager.online_mode_action.setChecked(False)
else:
self.stop_logging()
def start_logging(self):
"""启动日志记录"""
if self.logger is None:
@@ -93,7 +97,7 @@ class DebugManager:
self.logger = Logger(LOG_FILE, self.original_stdout)
sys.stdout = self.logger
sys.stderr = self.logger
print("--- Debug mode enabled ---")
logger.info("--- Debug mode enabled ---")
except (IOError, OSError) as e:
QtWidgets.QMessageBox.critical(self.main_window, "错误", f"无法创建日志文件: {e}")
self.logger = None
@@ -101,7 +105,7 @@ class DebugManager:
def stop_logging(self):
"""停止日志记录"""
if self.logger:
print("--- Debug mode disabled ---")
logger.info("--- Debug mode disabled ---")
sys.stdout = self.original_stdout
sys.stderr = self.original_stderr
self.logger.close()

View File

@@ -16,6 +16,10 @@ from workers import IpOptimizerThread
from core.cloudflare_optimizer import CloudflareOptimizer
from core.download_task_manager import DownloadTaskManager
from core.extraction_handler import ExtractionHandler
from utils.logger import setup_logger
# 初始化logger
logger = setup_logger("download_manager")
class DownloadManager:
def __init__(self, main_window):
@@ -67,8 +71,8 @@ class DownloadManager:
install_path = os.path.join(game_dir, os.path.basename(info["install_path"]))
install_paths[game] = install_path
if debug_mode:
print(f"DEBUG: 使用识别到的游戏目录 {game}: {game_dir}")
print(f"DEBUG: 安装路径设置为: {install_path}")
logger.debug(f"DEBUG: 使用识别到的游戏目录 {game}: {game_dir}")
logger.debug(f"DEBUG: 安装路径设置为: {install_path}")
return install_paths
@@ -88,7 +92,7 @@ class DownloadManager:
try:
if self.main_window.cloud_config:
if self.is_debug_mode():
print("--- Using pre-fetched cloud config ---")
logger.info("--- Using pre-fetched cloud config ---")
config_data = self.main_window.cloud_config
else:
headers = {"User-Agent": UA}
@@ -102,7 +106,7 @@ class DownloadManager:
if self.is_debug_mode():
# 创建安全版本的配置数据用于调试输出
safe_config = self._create_safe_config_for_logging(config_data)
print(f"DEBUG: Parsed JSON data: {json.dumps(safe_config, indent=2)}")
logger.debug(f"DEBUG: Parsed JSON data: {json.dumps(safe_config, indent=2)}")
urls = {}
for i in range(4):
@@ -138,8 +142,8 @@ class DownloadManager:
safe_urls[key] = f"{domain}/***隐藏URL路径***"
else:
safe_urls[key] = "***隐藏URL***"
print(f"DEBUG: Extracted URLs: {safe_urls}")
print("--- Finished getting download URL successfully ---")
logger.debug(f"DEBUG: Extracted URLs: {safe_urls}")
logger.info("--- Finished getting download URL successfully ---")
return urls
except requests.exceptions.RequestException as e:
@@ -153,7 +157,7 @@ class DownloadManager:
json_message = "配置文件异常,无法解析错误信息"
if self.is_debug_mode():
print(f"ERROR: Failed to get download config due to RequestException: {e}")
logger.error(f"ERROR: Failed to get download config due to RequestException: {e}")
QtWidgets.QMessageBox.critical(
self.main_window,
@@ -163,7 +167,7 @@ class DownloadManager:
return {}
except ValueError as e:
if self.is_debug_mode():
print(f"ERROR: Failed to parse download config due to ValueError: {e}")
logger.error(f"ERROR: Failed to parse download config due to ValueError: {e}")
QtWidgets.QMessageBox.critical(
self.main_window,
@@ -204,17 +208,17 @@ class DownloadManager:
if hasattr(self.main_window, 'game_detector') and hasattr(self.main_window.game_detector, 'clear_directory_cache'):
self.main_window.game_detector.clear_directory_cache()
if self.is_debug_mode():
print("DEBUG: 已清除游戏目录缓存,确保获取最新状态")
logger.debug("DEBUG: 已清除游戏目录缓存,确保获取最新状态")
game_dirs = self.main_window.game_detector.identify_game_directories_improved(self.selected_folder)
debug_mode = self.is_debug_mode()
if debug_mode:
print(f"DEBUG: 开始下载流程, 识别到 {len(game_dirs)} 个游戏目录")
logger.debug(f"DEBUG: 开始下载流程, 识别到 {len(game_dirs)} 个游戏目录")
if not game_dirs:
if debug_mode:
print("DEBUG: 未识别到任何游戏目录,设置目录未找到错误")
logger.warning("DEBUG: 未识别到任何游戏目录,设置目录未找到错误")
self.main_window.last_error_message = "directory_not_found"
QtWidgets.QMessageBox.warning(
self.main_window,
@@ -259,18 +263,18 @@ class DownloadManager:
# 检查游戏是否已安装补丁
if self.main_window.installed_status.get(game_version, False):
if debug_mode:
print(f"DEBUG: {game_version} 已安装补丁,不需要再次安装")
logger.info(f"DEBUG: {game_version} 已安装补丁,不需要再次安装")
already_installed_games.append(game_version)
else:
# 检查是否存在被禁用的补丁
is_disabled, disabled_path = self.main_window.patch_manager.check_patch_disabled(game_dir, game_version)
if is_disabled:
if debug_mode:
print(f"DEBUG: {game_version} 存在被禁用的补丁: {disabled_path}")
logger.info(f"DEBUG: {game_version} 存在被禁用的补丁: {disabled_path}")
disabled_patch_games.append(game_version)
else:
if debug_mode:
print(f"DEBUG: {game_version} 未安装补丁,可以安装")
logger.info(f"DEBUG: {game_version} 未安装补丁,可以安装")
installable_games.append(game_version)
status_message = ""
@@ -292,7 +296,7 @@ class DownloadManager:
if reply == QtWidgets.QMessageBox.StandardButton.Yes:
# 用户选择启用补丁
if debug_mode:
print(f"DEBUG: 用户选择启用被禁用的补丁")
logger.debug(f"DEBUG: 用户选择启用被禁用的补丁")
# 为每个禁用的游戏创建目录映射
disabled_game_dirs = {game: game_dirs[game] for game in disabled_patch_games}
@@ -315,7 +319,7 @@ class DownloadManager:
already_installed_games.append(game_version)
else:
if debug_mode:
print(f"DEBUG: 用户选择不启用被禁用的补丁,这些游戏将被添加到可安装列表")
logger.info(f"DEBUG: 用户选择不启用被禁用的补丁,这些游戏将被添加到可安装列表")
# 用户选择不启用,将这些游戏视为可以安装补丁
installable_games.extend(disabled_patch_games)
@@ -382,7 +386,7 @@ class DownloadManager:
selected_games = [item.text() for item in list_widget.selectedItems()]
if debug_mode:
print(f"DEBUG: 用户选择了以下游戏进行安装: {selected_games}")
logger.debug(f"DEBUG: 用户选择了以下游戏进行安装: {selected_games}")
selected_game_dirs = {game: game_dirs[game] for game in selected_games if game in game_dirs}
@@ -395,7 +399,7 @@ class DownloadManager:
if is_offline_mode:
if debug_mode:
print("DEBUG: 使用离线模式,跳过网络配置获取")
logger.info("DEBUG: 使用离线模式,跳过网络配置获取")
self._fill_offline_download_queue(selected_game_dirs)
else:
config = self.get_download_url()
@@ -416,7 +420,7 @@ class DownloadManager:
# 如果是离线模式,直接开始下一个下载任务
if is_offline_mode:
if debug_mode:
print("DEBUG: 离线模式跳过Cloudflare优化")
logger.info("DEBUG: 离线模式跳过Cloudflare优化")
self.next_download_task()
else:
self._show_cloudflare_option()
@@ -435,7 +439,7 @@ class DownloadManager:
debug_mode = self.is_debug_mode()
if debug_mode:
print(f"DEBUG: 填充下载队列, 游戏目录: {game_dirs}")
logger.debug(f"DEBUG: 填充下载队列, 游戏目录: {game_dirs}")
for i in range(1, 5):
game_version = f"NEKOPARA Vol.{i}"
@@ -445,7 +449,7 @@ class DownloadManager:
game_folder = game_dirs[game_version]
if debug_mode:
print(f"DEBUG: 使用识别到的游戏目录 {game_version}: {game_folder}")
logger.debug(f"DEBUG: 使用识别到的游戏目录 {game_version}: {game_folder}")
_7z_path = os.path.join(PLUGIN, f"vol.{i}.7z")
plugin_path = os.path.join(PLUGIN, GAME_INFO[game_version]["plugin_path"])
@@ -458,7 +462,7 @@ class DownloadManager:
if url:
game_folder = game_dirs[game_version]
if debug_mode:
print(f"DEBUG: 使用识别到的游戏目录 {game_version}: {game_folder}")
logger.debug(f"DEBUG: 使用识别到的游戏目录 {game_version}: {game_folder}")
_7z_path = os.path.join(PLUGIN, "after.7z")
plugin_path = os.path.join(PLUGIN, GAME_INFO[game_version]["plugin_path"])
@@ -478,12 +482,12 @@ class DownloadManager:
debug_mode = self.is_debug_mode()
if debug_mode:
print(f"DEBUG: 填充离线下载队列, 游戏目录: {game_dirs}")
logger.debug(f"DEBUG: 填充离线下载队列, 游戏目录: {game_dirs}")
# 检查是否有离线模式管理器
if not hasattr(self.main_window, 'offline_mode_manager'):
if debug_mode:
print("DEBUG: 离线模式管理器未初始化,无法使用离线模式")
logger.warning("DEBUG: 离线模式管理器未初始化,无法使用离线模式")
return
for i in range(1, 5):
@@ -493,13 +497,13 @@ class DownloadManager:
offline_patch_path = self.main_window.offline_mode_manager.get_offline_patch_path(game_version)
if not offline_patch_path:
if debug_mode:
print(f"DEBUG: 未找到 {game_version} 的离线补丁文件,跳过")
logger.warning(f"DEBUG: 未找到 {game_version} 的离线补丁文件,跳过")
continue
game_folder = game_dirs[game_version]
if debug_mode:
print(f"DEBUG: 使用识别到的游戏目录 {game_version}: {game_folder}")
print(f"DEBUG: 使用离线补丁文件: {offline_patch_path}")
logger.debug(f"DEBUG: 使用识别到的游戏目录 {game_version}: {game_folder}")
logger.debug(f"DEBUG: 使用离线补丁文件: {offline_patch_path}")
_7z_path = os.path.join(PLUGIN, f"vol.{i}.7z")
plugin_path = os.path.join(PLUGIN, GAME_INFO[game_version]["plugin_path"])
@@ -515,8 +519,8 @@ class DownloadManager:
if offline_patch_path:
game_folder = game_dirs[game_version]
if debug_mode:
print(f"DEBUG: 使用识别到的游戏目录 {game_version}: {game_folder}")
print(f"DEBUG: 使用离线补丁文件: {offline_patch_path}")
logger.debug(f"DEBUG: 使用识别到的游戏目录 {game_version}: {game_folder}")
logger.debug(f"DEBUG: 使用离线补丁文件: {offline_patch_path}")
_7z_path = os.path.join(PLUGIN, "after.7z")
plugin_path = os.path.join(PLUGIN, GAME_INFO[game_version]["plugin_path"])
@@ -525,7 +529,7 @@ class DownloadManager:
self.download_queue.append((offline_patch_path, game_folder, game_version, _7z_path, plugin_path))
self.main_window.download_queue_history.append(game_version)
elif debug_mode:
print(f"DEBUG: 未找到 {game_version} 的离线补丁文件,跳过")
logger.warning(f"DEBUG: 未找到 {game_version} 的离线补丁文件,跳过")
def _show_cloudflare_option(self):
"""显示Cloudflare加速选择对话框"""
@@ -537,7 +541,7 @@ class DownloadManager:
existing_ips = self.cloudflare_optimizer.hosts_manager.get_hostname_entries(hostname)
if existing_ips:
print(f"发现hosts文件中已有域名 {hostname} 的优选IP记录跳过询问直接使用")
logger.info(f"发现hosts文件中已有域名 {hostname} 的优选IP记录跳过询问直接使用")
self.cloudflare_optimizer.optimization_done = True
self.cloudflare_optimizer.countdown_finished = True
@@ -629,12 +633,12 @@ class DownloadManager:
debug_mode = self.is_debug_mode()
if debug_mode:
print(f"DEBUG: 准备下载游戏 {game_version}")
print(f"DEBUG: 游戏文件夹: {game_folder}")
logger.debug(f"DEBUG: 准备下载游戏 {game_version}")
logger.debug(f"DEBUG: 游戏文件夹: {game_folder}")
# 隐藏敏感URL
safe_url = "***URL protection***" # 完全隐藏URL
print(f"DEBUG: 下载URL: {safe_url}")
logger.debug(f"DEBUG: 下载URL: {safe_url}")
game_exe_exists = True
@@ -643,9 +647,9 @@ class DownloadManager:
or self.main_window.installed_status[game_version]
):
if debug_mode:
print(f"DEBUG: 跳过下载游戏 {game_version}")
print(f"DEBUG: 游戏存在: {game_exe_exists}")
print(f"DEBUG: 已安装补丁: {self.main_window.installed_status[game_version]}")
logger.debug(f"DEBUG: 跳过下载游戏 {game_version}")
logger.debug(f"DEBUG: 游戏存在: {game_exe_exists}")
logger.debug(f"DEBUG: 已安装补丁: {self.main_window.installed_status[game_version]}")
self.main_window.installed_status[game_version] = False if not game_exe_exists else True
self.next_download_task()
return
@@ -658,7 +662,7 @@ class DownloadManager:
# 如果是离线模式且URL是本地文件路径
if is_offline_mode and os.path.isfile(url):
if debug_mode:
print(f"DEBUG: 离线模式,复制本地补丁文件 {url}{_7z_path}")
logger.debug(f"DEBUG: 离线模式,复制本地补丁文件 {url}{_7z_path}")
try:
# 确保目标目录存在
@@ -672,24 +676,24 @@ class DownloadManager:
hash_valid = False
if hasattr(self.main_window, 'offline_mode_manager'):
if debug_mode:
print(f"DEBUG: 开始验证补丁文件哈希: {_7z_path}")
logger.debug(f"DEBUG: 开始验证补丁文件哈希: {_7z_path}")
hash_valid = self.main_window.offline_mode_manager.verify_patch_hash(game_version, _7z_path)
if debug_mode:
print(f"DEBUG: 补丁文件哈希验证结果: {'成功' if hash_valid else '失败'}")
logger.debug(f"DEBUG: 补丁文件哈希验证结果: {'成功' if hash_valid else '失败'}")
else:
if debug_mode:
print("DEBUG: 离线模式管理器不可用,跳过哈希验证")
logger.warning("DEBUG: 离线模式管理器不可用,跳过哈希验证")
hash_valid = True # 如果没有离线模式管理器,假设验证成功
if hash_valid:
if debug_mode:
print(f"DEBUG: 成功复制并验证补丁文件 {_7z_path}")
logger.info(f"DEBUG: 成功复制并验证补丁文件 {_7z_path}")
# 直接进入解压阶段
self.main_window.extraction_handler.start_extraction(_7z_path, game_folder, plugin_path, game_version)
self.main_window.extraction_handler.extraction_finished.connect(self.on_extraction_finished)
else:
if debug_mode:
print(f"DEBUG: 补丁文件哈希验证失败")
logger.warning(f"DEBUG: 补丁文件哈希验证失败")
# 显示错误消息
QtWidgets.QMessageBox.critical(
self.main_window,
@@ -700,7 +704,7 @@ class DownloadManager:
self.next_download_task()
except Exception as e:
if debug_mode:
print(f"DEBUG: 复制补丁文件失败: {e}")
logger.error(f"DEBUG: 复制补丁文件失败: {e}")
# 显示错误消息
QtWidgets.QMessageBox.critical(
self.main_window,
@@ -715,9 +719,9 @@ class DownloadManager:
self.optimized_ip = self.cloudflare_optimizer.get_optimized_ip()
if self.optimized_ip:
print(f"已为 {game_version} 获取到优选IP: {self.optimized_ip}")
logger.info(f"已为 {game_version} 获取到优选IP: {self.optimized_ip}")
else:
print(f"未能为 {game_version} 获取优选IP将使用默认线路。")
logger.info(f"未能为 {game_version} 获取优选IP将使用默认线路。")
self.download_task_manager.start_download(url, _7z_path, game_version, game_folder, plugin_path)
@@ -738,9 +742,9 @@ class DownloadManager:
self.main_window.progress_window = None
if not success:
print(f"--- Download Failed: {game_version} ---")
print(error)
print("------------------------------------")
logger.error(f"--- Download Failed: {game_version} ---")
logger.error(error)
logger.error("------------------------------------")
self.main_window.setEnabled(True)
@@ -793,7 +797,7 @@ class DownloadManager:
self.main_window.progress_window.reject()
self.main_window.progress_window = None
print("下载已全部停止。")
logger.info("下载已全部停止。")
self.main_window.setEnabled(True)
self.main_window.ui.start_install_text.setText("开始安装")

View File

@@ -3,10 +3,15 @@ import hashlib
import shutil
import tempfile
import py7zr
import traceback
from PySide6.QtWidgets import QMessageBox
from data.config import PLUGIN, PLUGIN_HASH, GAME_INFO
from utils import msgbox_frame
from utils.logger import setup_logger
# 初始化logger
logger = setup_logger("offline_mode_manager")
class OfflineModeManager:
"""离线模式管理器,用于管理离线模式下的补丁安装和检测"""
@@ -57,7 +62,7 @@ class OfflineModeManager:
debug_mode = self._is_debug_mode()
if debug_mode:
print(f"DEBUG: 扫描离线补丁文件,目录: {directory}")
logger.debug(f"DEBUG: 扫描离线补丁文件,目录: {directory}")
# 要查找的补丁文件名
patch_files = ["vol.1.7z", "vol.2.7z", "vol.3.7z", "vol.4.7z", "after.7z"]
@@ -72,7 +77,7 @@ class OfflineModeManager:
patch_name = file.lower()
found_patches[patch_name] = file_path
if debug_mode:
print(f"DEBUG: 找到离线补丁文件: {patch_name} 路径: {file_path}")
logger.debug(f"DEBUG: 找到离线补丁文件: {patch_name} 路径: {file_path}")
self.offline_patches = found_patches
return found_patches
@@ -110,7 +115,7 @@ class OfflineModeManager:
return False
if debug_mode:
print("DEBUG: 已启用离线模式(调试模式下允许强制启用)")
logger.debug("DEBUG: 已启用离线模式(调试模式下允许强制启用)")
self.is_offline_mode = enabled
@@ -125,7 +130,7 @@ class OfflineModeManager:
self.main_window.ui.title_label.setText(f"{APP_NAME} v{APP_VERSION} {mode_indicator}")
if debug_mode:
print(f"DEBUG: 离线模式已{'启用' if enabled else '禁用'}")
logger.debug(f"DEBUG: 离线模式已{'启用' if enabled else '禁用'}")
return True
@@ -187,12 +192,12 @@ class OfflineModeManager:
shutil.copy2(source_path, target_path)
if debug_mode:
print(f"DEBUG: 已复制离线补丁文件 {source_path}{target_path}")
logger.debug(f"DEBUG: 已复制离线补丁文件 {source_path}{target_path}")
return True
except Exception as e:
if debug_mode:
print(f"DEBUG: 复制离线补丁文件失败: {e}")
logger.error(f"DEBUG: 复制离线补丁文件失败: {e}")
return False
def verify_patch_hash(self, game_version, file_path):
@@ -220,66 +225,65 @@ class OfflineModeManager:
expected_hash = PLUGIN_HASH.get("after", "")
if not expected_hash:
print(f"DEBUG: 未找到 {game_version} 的预期哈希值")
logger.warning(f"DEBUG: 未找到 {game_version} 的预期哈希值")
return False
debug_mode = self._is_debug_mode()
if debug_mode:
print(f"DEBUG: 开始验证离线补丁文件: {file_path}")
print(f"DEBUG: 游戏版本: {game_version}")
print(f"DEBUG: 预期哈希值: {expected_hash}")
logger.debug(f"DEBUG: 开始验证离线补丁文件: {file_path}")
logger.debug(f"DEBUG: 游戏版本: {game_version}")
logger.debug(f"DEBUG: 预期哈希值: {expected_hash}")
try:
# 检查文件是否存在
if not os.path.exists(file_path):
if debug_mode:
print(f"DEBUG: 补丁文件不存在: {file_path}")
logger.warning(f"DEBUG: 补丁文件不存在: {file_path}")
return False
# 检查文件大小
file_size = os.path.getsize(file_path)
if debug_mode:
print(f"DEBUG: 补丁文件大小: {file_size} 字节")
logger.debug(f"DEBUG: 补丁文件大小: {file_size} 字节")
if file_size == 0:
if debug_mode:
print(f"DEBUG: 补丁文件大小为0无效文件")
logger.warning(f"DEBUG: 补丁文件大小为0无效文件")
return False
# 创建临时目录用于解压文件
with tempfile.TemporaryDirectory() as temp_dir:
if debug_mode:
print(f"DEBUG: 创建临时目录: {temp_dir}")
logger.debug(f"DEBUG: 创建临时目录: {temp_dir}")
# 解压补丁文件
try:
if debug_mode:
print(f"DEBUG: 开始解压文件: {file_path}")
logger.debug(f"DEBUG: 开始解压文件: {file_path}")
with py7zr.SevenZipFile(file_path, mode="r") as archive:
# 获取压缩包内文件列表
file_list = archive.getnames()
if debug_mode:
print(f"DEBUG: 压缩包内文件列表: {file_list}")
logger.debug(f"DEBUG: 压缩包内文件列表: {file_list}")
# 解压所有文件
archive.extractall(path=temp_dir)
if debug_mode:
print(f"DEBUG: 解压完成")
logger.debug(f"DEBUG: 解压完成")
# 列出解压后的文件
extracted_files = []
for root, dirs, files in os.walk(temp_dir):
for file in files:
extracted_files.append(os.path.join(root, file))
print(f"DEBUG: 解压后的文件列表: {extracted_files}")
logger.debug(f"DEBUG: 解压后的文件列表: {extracted_files}")
except Exception as e:
if debug_mode:
print(f"DEBUG: 解压补丁文件失败: {e}")
print(f"DEBUG: 错误类型: {type(e).__name__}")
import traceback
print(f"DEBUG: 错误堆栈: {traceback.format_exc()}")
logger.error(f"DEBUG: 解压补丁文件失败: {e}")
logger.error(f"DEBUG: 错误类型: {type(e).__name__}")
logger.error(f"DEBUG: 错误堆栈: {traceback.format_exc()}")
return False
# 获取补丁文件路径
@@ -297,7 +301,7 @@ class OfflineModeManager:
if not patch_file or not os.path.exists(patch_file):
if debug_mode:
print(f"DEBUG: 未找到解压后的补丁文件: {patch_file}")
logger.warning(f"DEBUG: 未找到解压后的补丁文件: {patch_file}")
# 尝试查找可能的替代文件
alternative_files = []
for root, dirs, files in os.walk(temp_dir):
@@ -305,18 +309,18 @@ class OfflineModeManager:
if file.endswith('.xp3') or file.endswith('.int'):
alternative_files.append(os.path.join(root, file))
if alternative_files:
print(f"DEBUG: 找到可能的替代文件: {alternative_files}")
logger.debug(f"DEBUG: 找到可能的替代文件: {alternative_files}")
# 检查解压目录结构
print(f"DEBUG: 检查解压目录结构:")
logger.debug(f"DEBUG: 检查解压目录结构:")
for root, dirs, files in os.walk(temp_dir):
print(f"DEBUG: 目录: {root}")
print(f"DEBUG: 子目录: {dirs}")
print(f"DEBUG: 文件: {files}")
logger.debug(f"DEBUG: 目录: {root}")
logger.debug(f"DEBUG: 子目录: {dirs}")
logger.debug(f"DEBUG: 文件: {files}")
return False
if debug_mode:
print(f"DEBUG: 找到解压后的补丁文件: {patch_file}")
logger.debug(f"DEBUG: 找到解压后的补丁文件: {patch_file}")
# 计算补丁文件哈希值
try:
@@ -327,22 +331,21 @@ class OfflineModeManager:
result = file_hash.lower() == expected_hash.lower()
if debug_mode:
print(f"DEBUG: 补丁文件 {patch_file} 哈希值验证: {'成功' if result else '失败'}")
print(f"DEBUG: 预期哈希值: {expected_hash}")
print(f"DEBUG: 实际哈希值: {file_hash}")
logger.debug(f"DEBUG: 补丁文件 {patch_file} 哈希值验证: {'成功' if result else '失败'}")
logger.debug(f"DEBUG: 预期哈希值: {expected_hash}")
logger.debug(f"DEBUG: 实际哈希值: {file_hash}")
return result
except Exception as e:
if debug_mode:
print(f"DEBUG: 计算补丁文件哈希值失败: {e}")
print(f"DEBUG: 错误类型: {type(e).__name__}")
logger.error(f"DEBUG: 计算补丁文件哈希值失败: {e}")
logger.error(f"DEBUG: 错误类型: {type(e).__name__}")
return False
except Exception as e:
if debug_mode:
print(f"DEBUG: 验证补丁哈希值失败: {e}")
print(f"DEBUG: 错误类型: {type(e).__name__}")
import traceback
print(f"DEBUG: 错误堆栈: {traceback.format_exc()}")
logger.error(f"DEBUG: 验证补丁哈希值失败: {e}")
logger.error(f"DEBUG: 错误类型: {type(e).__name__}")
logger.error(f"DEBUG: 错误堆栈: {traceback.format_exc()}")
return False
def is_offline_mode_available(self):
@@ -378,11 +381,11 @@ class OfflineModeManager:
debug_mode = self._is_debug_mode()
if debug_mode:
print(f"DEBUG: 开始离线安装流程,选择的游戏: {selected_games}")
logger.debug(f"DEBUG: 开始离线安装流程,选择的游戏: {selected_games}")
if not self.is_in_offline_mode():
if debug_mode:
print("DEBUG: 当前不是离线模式,无法使用离线安装")
logger.warning("DEBUG: 当前不是离线模式,无法使用离线安装")
return False
# 确保已扫描过补丁文件
@@ -391,7 +394,7 @@ class OfflineModeManager:
if not self.offline_patches:
if debug_mode:
print("DEBUG: 未找到任何离线补丁文件")
logger.warning("DEBUG: 未找到任何离线补丁文件")
msgbox_frame(
f"离线安装错误 - {self.app_name}",
"\n未找到任何离线补丁文件,无法进行离线安装。\n\n请将补丁文件放置在软件所在目录后再尝试。\n",
@@ -406,7 +409,7 @@ class OfflineModeManager:
if not game_dirs:
if debug_mode:
print("DEBUG: 未识别到任何游戏目录")
logger.warning("DEBUG: 未识别到任何游戏目录")
return False
# 显示文件检验窗口
@@ -453,11 +456,11 @@ class OfflineModeManager:
if self.get_offline_patch_path(game_version):
installable_games.append(game_version)
elif debug_mode:
print(f"DEBUG: 未找到 {game_version} 的离线补丁文件,跳过")
logger.warning(f"DEBUG: 未找到 {game_version} 的离线补丁文件,跳过")
if not installable_games:
if debug_mode:
print("DEBUG: 没有需要安装的游戏或未找到对应的离线补丁")
logger.info("DEBUG: 没有需要安装的游戏或未找到对应的离线补丁")
msgbox_frame(
f"离线安装信息 - {self.app_name}",
"\n没有需要安装的游戏或未找到对应的离线补丁文件。\n",
@@ -468,7 +471,7 @@ class OfflineModeManager:
# 开始安装流程
if debug_mode:
print(f"DEBUG: 开始离线安装流程,安装游戏: {installable_games}")
logger.info(f"DEBUG: 开始离线安装流程,安装游戏: {installable_games}")
# 创建安装任务列表
install_tasks = []
@@ -522,7 +525,7 @@ class OfflineModeManager:
if not install_tasks:
# 所有任务完成,进行后检查
if debug_mode:
print("DEBUG: 所有离线安装任务完成,进行后检查")
logger.info("DEBUG: 所有离线安装任务完成,进行后检查")
self.main_window.after_hash_compare()
return
@@ -530,9 +533,9 @@ class OfflineModeManager:
patch_file, game_folder, game_version, _7z_path, plugin_path = install_tasks.pop(0)
if debug_mode:
print(f"DEBUG: 处理离线安装任务: {game_version}")
print(f"DEBUG: 补丁文件: {patch_file}")
print(f"DEBUG: 游戏目录: {game_folder}")
logger.debug(f"DEBUG: 处理离线安装任务: {game_version}")
logger.debug(f"DEBUG: 补丁文件: {patch_file}")
logger.debug(f"DEBUG: 游戏目录: {game_folder}")
# 确保目标目录存在
os.makedirs(os.path.dirname(_7z_path), exist_ok=True)
@@ -542,8 +545,8 @@ class OfflineModeManager:
shutil.copy2(patch_file, _7z_path)
if debug_mode:
print(f"DEBUG: 已复制补丁文件到缓存目录: {_7z_path}")
print(f"DEBUG: 开始验证补丁文件哈希值")
logger.debug(f"DEBUG: 已复制补丁文件到缓存目录: {_7z_path}")
logger.debug(f"DEBUG: 开始验证补丁文件哈希值")
# 获取预期的哈希值
expected_hash = None
@@ -559,7 +562,7 @@ class OfflineModeManager:
expected_hash = PLUGIN_HASH.get("after", "")
if debug_mode and expected_hash:
print(f"DEBUG: 预期哈希值: {expected_hash}")
logger.debug(f"DEBUG: 预期哈希值: {expected_hash}")
# 显示哈希验证窗口 - 使用离线特定消息
self.main_window.hash_msg_box = self.main_window.hash_manager.hash_pop_window(check_type="offline_verify", is_offline=True)
@@ -574,7 +577,7 @@ class OfflineModeManager:
if hash_valid:
if debug_mode:
print(f"DEBUG: 补丁文件哈希验证成功,开始解压")
logger.info(f"DEBUG: 补丁文件哈希验证成功,开始解压")
# 显示解压窗口 - 使用离线特定消息
self.main_window.hash_msg_box = self.main_window.hash_manager.hash_pop_window(check_type="offline_extraction", is_offline=True)
@@ -596,7 +599,7 @@ class OfflineModeManager:
extraction_thread.start()
except Exception as e:
if debug_mode:
print(f"DEBUG: 创建或启动解压线程失败: {e}")
logger.error(f"DEBUG: 创建或启动解压线程失败: {e}")
# 关闭解压窗口
if self.main_window.hash_msg_box and self.main_window.hash_msg_box.isVisible():
@@ -614,7 +617,7 @@ class OfflineModeManager:
self.process_next_offline_install_task(install_tasks)
else:
if debug_mode:
print(f"DEBUG: 补丁文件哈希验证失败")
logger.warning(f"DEBUG: 补丁文件哈希验证失败")
# 显示错误消息
msgbox_frame(
@@ -627,7 +630,7 @@ class OfflineModeManager:
self.process_next_offline_install_task(install_tasks)
except Exception as e:
if debug_mode:
print(f"DEBUG: 离线安装任务处理失败: {e}")
logger.error(f"DEBUG: 离线安装任务处理失败: {e}")
# 显示错误消息
msgbox_frame(
@@ -656,9 +659,9 @@ class OfflineModeManager:
self.main_window.hash_msg_box = None
if debug_mode:
print(f"DEBUG: 离线解压完成,状态: {'成功' if success else '失败'}")
logger.debug(f"DEBUG: 离线解压完成,状态: {'成功' if success else '失败'}")
if not success:
print(f"DEBUG: 错误信息: {error_message}")
logger.error(f"DEBUG: 错误信息: {error_message}")
if not success:
# 显示错误消息
@@ -686,7 +689,7 @@ class OfflineModeManager:
debug_mode = self._is_debug_mode()
if debug_mode:
print("DEBUG: 离线解压完成,继续处理下一个任务")
logger.debug("DEBUG: 离线解压完成,继续处理下一个任务")
# 处理下一个任务
self.process_next_offline_install_task(remaining_tasks)