优化: 1. 修复SSL警告问题 2. 优化加载对话框显示逻辑 3. 添加API测试工具

This commit is contained in:
huangzhenpc
2025-02-13 10:13:22 +08:00
parent 207c3c604e
commit 30aab5f9b2
3 changed files with 171 additions and 79 deletions

View File

@@ -165,14 +165,41 @@ class AccountSwitcher:
"code": code
}
response = requests.post(
self.config.get_api_url("activate"),
json=data,
headers={"Content-Type": "application/json"},
timeout=10
)
# 禁用SSL警告
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# 设置请求参数
request_kwargs = {
"json": data,
"headers": {"Content-Type": "application/json"},
"timeout": 5, # 减少超时时间从10秒到5秒
"verify": False # 禁用SSL验证
}
# 尝试发送请求
try:
response = requests.post(
self.config.get_api_url("activate"),
**request_kwargs
)
except requests.exceptions.SSLError:
# 如果发生SSL错误创建自定义SSL上下文
import ssl
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
# 使用自定义SSL上下文重试请求
session = requests.Session()
session.verify = False
response = session.post(
self.config.get_api_url("activate"),
**request_kwargs
)
result = response.json()
# 激活成功
if result["code"] == 200:
api_data = result["data"]
# 构造标准的返回数据结构
@@ -184,22 +211,18 @@ class AccountSwitcher:
"device_info": self.get_device_info()
}
return True, result["msg"], account_info
return False, result["msg"], {
"status": "inactive",
"expire_time": "",
"total_days": 0,
"days_left": 0,
"device_info": self.get_device_info()
}
# 激活码无效或已被使用
elif result["code"] == 400:
logging.warning(f"激活码无效或已被使用: {result.get('msg', '未知错误')}")
return False, result.get("msg", "激活码无效或已被使用"), None
# 其他错误情况
else:
logging.error(f"激活失败: {result.get('msg', '未知错误')}")
return False, result["msg"], None # 返回 None 而不是空的账号信息
except Exception as e:
return False, f"激活失败: {str(e)}", {
"status": "inactive",
"expire_time": "",
"total_days": 0,
"days_left": 0,
"device_info": self.get_device_info()
}
logging.error(f"激活失败: {str(e)}")
return False, f"激活失败: {str(e)}", None # 返回 None 而不是空的账号信息
def reset_machine_id(self) -> bool:
"""重置机器码"""
@@ -310,28 +333,38 @@ class AccountSwitcher:
api_url = self.config.get_api_url("status")
logging.info(f"正在检查会员状态...")
logging.info(f"API URL: {api_url}")
logging.info(f"请求数据: {data}")
response = requests.post(
api_url,
json=data,
headers={"Content-Type": "application/json"},
timeout=10
)
# 设置请求参数
request_kwargs = {
"json": data,
"headers": {"Content-Type": "application/json"},
"timeout": 2, # 减少超时时间到2秒
"verify": False
}
# 使用session来复用连接
session = requests.Session()
session.verify = False
# 尝试发送请求
try:
response = session.post(api_url, **request_kwargs)
except requests.exceptions.Timeout:
# 超时后快速重试一次
logging.warning("首次请求超时,正在重试...")
response = session.post(api_url, **request_kwargs)
result = response.json()
logging.info(f"状态检查响应: {result}")
if result.get("code") in [1, 200]: # 兼容两种响应码
if result.get("code") in [1, 200]:
api_data = result.get("data", {})
# 构造标准的返回数据结构
return {
"status": api_data.get("status", "inactive"),
"expire_time": api_data.get("expire_time", ""),
"total_days": api_data.get("total_days", 0),
"days_left": api_data.get("days_left", 0),
"device_info": self.get_device_info() # 添加设备信息
"device_info": self.get_device_info()
}
else:
error_msg = result.get("msg", "未知错误")
@@ -428,17 +461,33 @@ class AccountSwitcher:
"Content-Type": "application/json"
}
# 禁用SSL警告
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# 设置请求参数
request_kwargs = {
"json": data,
"headers": headers,
"timeout": 30, # 增加超时时间
"verify": False # 禁用SSL验证
}
try:
# 添加SSL验证选项和超时设置
response = requests.post(
endpoint,
json=data,
headers=headers,
timeout=30, # 增加超时时间
verify=False, # 禁用SSL验证
)
# 禁用SSL警告
requests.packages.urllib3.disable_warnings()
# 尝试发送请求
try:
response = requests.post(endpoint, **request_kwargs)
except requests.exceptions.SSLError:
# 如果发生SSL错误创建自定义SSL上下文
import ssl
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
# 使用自定义SSL上下文重试请求
session = requests.Session()
session.verify = False
response = session.post(endpoint, **request_kwargs)
response_data = response.json()

View File

@@ -44,6 +44,7 @@ class LoadingDialog(QDialog):
self.progress_bar = QProgressBar()
self.progress_bar.setTextVisible(False)
self.progress_bar.setRange(0, 0) # 设置为循环模式
self.progress_bar.setMinimumWidth(250) # 设置最小宽度
layout.addWidget(self.progress_bar)
self.setLayout(layout)
@@ -63,13 +64,54 @@ class LoadingDialog(QDialog):
border: 2px solid #e9ecef;
border-radius: 5px;
text-align: center;
min-height: 12px;
}
QProgressBar::chunk {
background-color: #0d6efd;
width: 10px;
width: 15px;
margin: 0.5px;
}
""")
# 添加定时器以自动更新进度条动画
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_progress)
self.progress_value = 0
def update_progress(self):
"""更新进度条动画"""
self.progress_value = (self.progress_value + 1) % 100
self.progress_bar.setValue(self.progress_value)
def showEvent(self, event):
"""显示时启动定时器"""
super().showEvent(event)
self.timer.start(50) # 每50毫秒更新一次
def hideEvent(self, event):
"""隐藏时停止定时器"""
self.timer.stop()
super().hideEvent(event)
def check_status(self):
"""检查会员状态从API获取"""
try:
# 只在首次检查时显示加载对话框,并设置更明确的提示
if self._activation_status is None:
self.show_loading_dialog("正在连接服务器,请稍候...")
# 创建工作线程
self.worker = ApiWorker(self.switcher.get_member_status)
self.worker.finished.connect(self.on_status_check_complete)
self.worker.start()
except Exception as e:
if self._activation_status is None:
self.hide_loading_dialog()
QMessageBox.critical(self, "错误", f"检查状态失败: {str(e)}")
self._activation_status = False
logging.error(f"检查状态时发生错误: {str(e)}")
return False
class ApiWorker(QThread):
"""API请求工作线程"""
@@ -313,35 +355,41 @@ class MainWindow(QMainWindow):
def show_loading_dialog(self, message="请稍候..."):
"""显示加载对话框"""
self.loading_dialog = LoadingDialog(self, message)
self.loading_dialog.setStyleSheet("""
QDialog {
background-color: #f8f9fa;
}
QLabel {
color: #0d6efd;
font-size: 14px;
font-weight: bold;
padding: 10px;
}
QProgressBar {
border: 2px solid #e9ecef;
border-radius: 5px;
text-align: center;
}
QProgressBar::chunk {
background-color: #0d6efd;
width: 10px;
margin: 0.5px;
}
""")
if not hasattr(self, 'loading_dialog') or not self.loading_dialog:
self.loading_dialog = LoadingDialog(self, message)
self.loading_dialog.setStyleSheet("""
QDialog {
background-color: #f8f9fa;
}
QLabel {
color: #0d6efd;
font-size: 14px;
font-weight: bold;
padding: 10px;
}
QProgressBar {
border: 2px solid #e9ecef;
border-radius: 5px;
text-align: center;
}
QProgressBar::chunk {
background-color: #0d6efd;
width: 10px;
margin: 0.5px;
}
""")
else:
self.loading_dialog.message_label.setText(message)
self.loading_dialog.show()
QApplication.processEvents() # 确保对话框立即显示
def hide_loading_dialog(self):
"""隐藏加载对话框"""
if hasattr(self, 'loading_dialog'):
if hasattr(self, 'loading_dialog') and self.loading_dialog:
self.loading_dialog.hide()
self.loading_dialog.deleteLater()
self.loading_dialog = None
QApplication.processEvents() # 确保对话框立即隐藏
def activate_account(self):
"""激活账号"""
@@ -512,7 +560,7 @@ class MainWindow(QMainWindow):
if isinstance(data, tuple):
success, message, account_info = data
if success:
if success and account_info is not None:
# 更新会员信息显示
self.update_status_display(account_info)
# 更新激活状态缓存
@@ -603,20 +651,10 @@ class MainWindow(QMainWindow):
}
""")
msg.exec_()
# 更新显示为未激活状态
self.update_status_display(account_info)
# 所有失败情况都不更新状态显示
else:
QMessageBox.critical(self, "错误", f"激活失败: {data}")
# 更新为未激活状态
device_info = self.switcher.get_device_info()
inactive_status = {
"status": "inactive",
"expire_time": "",
"total_days": 0,
"days_left": 0,
"device_info": device_info
}
self.update_status_display(inactive_status)
# 更新状态显示
def update_status_display(self, status_info: dict):
"""更新状态显示"""
@@ -660,7 +698,7 @@ class MainWindow(QMainWindow):
try:
# 只在首次检查时显示加载对话框
if self._activation_status is None:
self.show_loading_dialog("正在检查会员状态,请稍候...")
self.show_loading_dialog("正在连接服务器...")
# 创建工作线程
self.worker = ApiWorker(self.switcher.get_member_status)

View File

@@ -5,12 +5,17 @@ import os
import atexit
import shutil
import tempfile
import urllib3
from pathlib import Path
from PyQt5.QtWidgets import QApplication, QMessageBox, QSystemTrayIcon, QMenu
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
from gui.main_window import MainWindow
# 禁用所有 SSL 相关警告
urllib3.disable_warnings()
logging.getLogger('urllib3').setLevel(logging.ERROR)
def cleanup_temp():
"""清理临时文件"""
try: