The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
refactor(setting_cards): 重构代理设置组件以支持多协议代理配置
XiaoYouChR6bfde3114260
diff --git a/app/supports/utils.py b/app/supports/utils.pyindex c2b3691c..e4726296 100644--- a/app/supports/utils.py+++ b/app/supports/utils.py@@ -5,6 +5,7 @@ from functools import wrapsfrom pathlib import Pathfrom time import sleepfrom typing import Callable+from urllib.parse import urlsplit, urlunsplitfrom PySide6.QtCore import QUrl, Qt, QProcess, QStandardPathsfrom PySide6.QtGui import QDesktopServices@@ -15,6 +16,9 @@ from app.bases.models import Taskfrom app.supports.config import cfg+_PROXY_PROTOCOLS = ("http", "https", "ftp")++def openFolder(path):path = Path(path)if path.exists():@@ -38,91 +42,144 @@ def openAppLogFolder():openFolder(f"{appLocalDataLocation}/GhostDownloader/GhostDownloader.log")-def getSystemProxy():- if sys.platform == "win32":+def _getWindowsSystemProxies() -> dict[str, str]:+ import winreg++ with winreg.OpenKey(+ winreg.HKEY_CURRENT_USER,+ r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",+ ) as key:+ proxyEnable, _ = winreg.QueryValueEx(key, "ProxyEnable")+ if not proxyEnable:+ return {}++ proxyServer, _ = winreg.QueryValueEx(key, "ProxyServer")+ rawProxies: dict[str, str] = {}+ defaultProxy = ""+ for entry in str(proxyServer or "").split(";"):+ entry = entry.strip()+ if not entry:+ continue++ if "=" not in entry:+ defaultProxy = entry+ continue++ protocol, value = entry.split("=", 1)+ protocol = protocol.strip().lower()+ value = value.strip()+ if protocol in _PROXY_PROTOCOLS and value:+ rawProxies[protocol] = value++ if defaultProxy:+ for protocol in _PROXY_PROTOCOLS:+ rawProxies.setdefault(protocol, defaultProxy)++ proxies = {+ protocol: value if "://" in value else f"http://{value}"+ for protocol, value in rawProxies.items()+ if value+ }+ if not proxies:+ return {}++ username = None+ password = Nonetry:- import winreg-- key = winreg.OpenKey(- winreg.HKEY_CURRENT_USER,- r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",+ proxyUser, _ = winreg.QueryValueEx(key, "ProxyUser")+ if proxyUser:+ username = str(proxyUser)++ proxyPass, _ = winreg.QueryValueEx(key, "ProxyPass")+ if proxyPass:+ password = str(proxyPass)+ except (FileNotFoundError, OSError):+ pass++ if not username and not password:+ return proxies++ credentials = username or ""+ if password is not None:+ credentials = f"{credentials}:{password}"++ proxiesWithCredentials: dict[str, str] = {}+ for protocol, proxyUrl in proxies.items():+ parsed = urlsplit(proxyUrl)+ if parsed.username or parsed.password:+ proxiesWithCredentials[protocol] = proxyUrl+ continue++ proxiesWithCredentials[protocol] = urlunsplit(+ parsed._replace(netloc=f"{credentials}@{parsed.netloc}"))- proxyEnable, _ = winreg.QueryValueEx(key, "ProxyEnable")+ return proxiesWithCredentials- if proxyEnable:- proxyServer, _ = winreg.QueryValueEx(key, "ProxyServer")- # TODO 当 http 代理和 https 代理不同时,当前实现只能获取 http 代理,后续可以改进为分别获取 http 和 https 代理- if "http=" in proxyServer:- proxyServer = proxyServer.split(";")[0].split("=")[1]+def _getLinuxSystemProxies() -> dict[str, str]:+ proxies = {+ protocol: str(+ os.environ.get(f"{protocol}_proxy")+ or os.environ.get(f"{protocol.upper()}_PROXY")+ or ""+ ).strip()+ for protocol in _PROXY_PROTOCOLS+ }+ fallbackProxy = proxies["https"] or proxies["http"]+ if fallbackProxy:+ for protocol in _PROXY_PROTOCOLS:+ if not proxies[protocol]:+ proxies[protocol] = fallbackProxy- if not proxyServer.startswith("http://") and not proxyServer.startswith(- "https://"- ):- proxyServer = "http://" + proxyServer+ return {protocol: proxyUrl for protocol, proxyUrl in proxies.items() if proxyUrl}- # 尝试从 Windows 凭证管理器获取用户名和密码- username = None- password = None- try:- proxyUser, _ = winreg.QueryValueEx(key, "ProxyUser")- if proxyUser:- username = proxyUser- proxyPass, _ = winreg.QueryValueEx(key, "ProxyPass")- if proxyPass:- password = proxyPass- except (FileNotFoundError, OSError):- # 注册表中未找到用户名或密码- pass-- # 如果有用户名和密码,插入到代理 URL 中- if username or password:- protocol = proxyServer[: proxyServer.find("://")]- hostPort = proxyServer[proxyServer.find("://") + 3 :]- credentials = f"{username or ''}:{password or ''}"- proxyServer = f"{protocol}://{credentials}@{hostPort}"-- return proxyServer- else:- return None-- except FileNotFoundError:- return None- except Exception as e:- logger.opt(exception=e).error("无法获取 Windows 代理服务器")- return None- elif sys.platform == "linux": # 读取 Linux 系统代理- try:- proxyUrl = os.environ.get("https_proxy") or os.environ.get("http_proxy")- return proxyUrl- except Exception as e:- logger.opt(exception=e).error("无法获取 Linux 代理服务器")- return None+def _getDarwinSystemProxies() -> dict[str, str]:+ import SystemConfiguration- elif sys.platform == "darwin":- import SystemConfiguration+ proxySettings = SystemConfiguration.SCDynamicStoreCopyProxies(None) # type: ignore+ if proxySettings.get("SOCKSEnable", 0):+ proxyUrl = f"socks5://{proxySettings.get('SOCKSProxy')}:{proxySettings.get('SOCKSPort')}"+ return {protocol: proxyUrl for protocol in _PROXY_PROTOCOLS}- _ = SystemConfiguration.SCDynamicStoreCopyProxies(None) # type: ignore+ if proxySettings.get("HTTPEnable", 0):+ proxyUrl = f"http://{proxySettings.get('HTTPProxy')}:{proxySettings.get('HTTPPort')}"+ return {protocol: proxyUrl for protocol in _PROXY_PROTOCOLS}- if _.get("SOCKSEnable", 0):- return f"socks5://{_.get('SOCKSProxy')}:{_.get('SOCKSPort')}"- elif _.get("HTTPEnable", 0):- return f"http://{_.get('HTTPProxy')}:{_.get('HTTPPort')}"- else:- return None+ return {}- return None++def getSystemProxies() -> dict[str, str] | None:+ try:+ if sys.platform == "win32":+ proxies = _getWindowsSystemProxies()+ elif sys.platform == "linux":+ proxies = _getLinuxSystemProxies()+ elif sys.platform == "darwin":+ proxies = _getDarwinSystemProxies()+ else:+ proxies = {}+ except FileNotFoundError:+ return None+ except Exception as e:+ logger.opt(exception=e).error("无法获取系统代理服务器")+ return None+ return proxies or Nonedef getProxies():if cfg.proxyServer.value == "Off":return None- elif cfg.proxyServer.value == "Auto":- return {"http": getSystemProxy(), "https": getSystemProxy()}- else:- return {"http": cfg.proxyServer.value, "https": cfg.proxyServer.value}++ if cfg.proxyServer.value == "Auto":+ return getSystemProxies()++ proxyServer = str(cfg.proxyServer.value).strip()+ if not proxyServer:+ return None++ return {protocol: proxyServer for protocol in _PROXY_PROTOCOLS}def getReadableSize(size: int):diff --git a/app/view/components/setting_cards.py b/app/view/components/setting_cards.pyindex f25be3c9..3944423b 100644--- a/app/view/components/setting_cards.py+++ b/app/view/components/setting_cards.py@@ -22,9 +22,10 @@ from qfluentwidgets import (EditableComboBox,ToolButton,)+from urllib.parse import urlsplitfrom app.supports.config import cfg-from app.supports.utils import getSystemProxy+from app.supports.utils import getSystemProxiesclass SpinBoxSettingCard(SettingCard):@@ -137,32 +138,27 @@ class ProxySettingCard(ExpandGroupSettingCard):else:self.customRadioButton.setChecked(True)self.__onRadioButtonClicked(self.customRadioButton)- self.customProtocolComboBox.setCurrentText(- configValue[: configValue.find("://")]- )- # 解析代理字符串,格式可能是:- # protocol://ip:port 或 protocol://username:password@ip:port- proxyPart = configValue[configValue.find("://") + 3 :]- if "@" in proxyPart:- # 包含账号密码- credentials, hostPort = proxyPart.rsplit("@", 1)- if ":" in credentials:- username, password = credentials.split(":", 1)- self.usernameLineEdit.setText(username)- self.passwordLineEdit.setText(password)- else:- self.usernameLineEdit.setText(credentials)- else:- hostPort = proxyPart-- # 解析主机和端口- hostAndPort = hostPort.split(":")- self.customIPLineEdit.setText(hostAndPort[0])- self.customPortLineEdit.setText(hostAndPort[1])+ self._applyProxyUrl(configValue)self.choiceLabel.setText(self.buttonGroup.checkedButton().text())self.choiceLabel.adjustSize()+ def _applyProxyUrl(self, proxyUrl: str | None):+ if not proxyUrl:+ self.customProtocolComboBox.setCurrentText("")+ self.customIPLineEdit.setText(self.tr("未检测到代理"))+ self.customPortLineEdit.setText("")+ self.usernameLineEdit.setText("")+ self.passwordLineEdit.setText("")+ return++ parsed = urlsplit(proxyUrl)+ self.customProtocolComboBox.setCurrentText(parsed.scheme)+ self.customIPLineEdit.setText(parsed.hostname or "")+ self.customPortLineEdit.setText(str(parsed.port or ""))+ self.usernameLineEdit.setText(parsed.username or "")+ self.passwordLineEdit.setText(parsed.password or "")+def __initWidget(self):self.__initLayout()self.buttonGroup.buttonClicked.connect(self.__onRadioButtonClicked)@@ -242,39 +238,14 @@ class ProxySettingCard(ExpandGroupSettingCard):self.customProxyWidget.setDisabled(True)self.credentialsWidget.setDisabled(True)- systemValue = getSystemProxy()- # 分析 SystemProxy,格式可能为:- # protocol://ip:port 或 protocol://username:password@ip:port- if systemValue:- protocol = systemValue[: systemValue.find("://")]- self.customProtocolComboBox.setCurrentText(protocol)-- # 解析代理 URL,提取用户名、密码、IP、端口- proxyPart = systemValue[systemValue.find("://") + 3 :]- if "@" in proxyPart: # 包含账号密码- credentials, hostPort = proxyPart.rsplit("@", 1)- if ":" in credentials:- username, password = credentials.split(":", 1)- self.usernameLineEdit.setText(username)- self.passwordLineEdit.setText(password)- else:- self.usernameLineEdit.setText(credentials)- self.passwordLineEdit.setText("")- else: # 不包含账号密码,清空输入框- self.usernameLineEdit.setText("")- self.passwordLineEdit.setText("")- hostPort = proxyPart-- # 解析主机和端口- hostAndPort = hostPort.split(":")- self.customIPLineEdit.setText(hostAndPort[0])- self.customPortLineEdit.setText(hostAndPort[1])- else:- self.customProtocolComboBox.setCurrentText("")- self.customIPLineEdit.setText(self.tr("未检测到代理"))- self.customPortLineEdit.setText("")- self.usernameLineEdit.setText("")- self.passwordLineEdit.setText("")+ systemProxies = getSystemProxies()+ systemValue = None+ if systemProxies:+ for protocol in ("https", "http", "ftp"):+ systemValue = systemProxies.get(protocol)+ if systemValue:+ break+ self._applyProxyUrl(systemValue)cfg.set(self.configItem, "Auto")