The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
Version 3.0.1 更新了好多东西啊~ 1、使用QThread对下载引擎进行重构 a)可以自动获取文件名 b)可以删除任务 c)速度显示正常 d)下载功能前所未有的稳定 2、解耦合多个组件,方便后期维护 3、隐藏调试菜单 4、新增自定义任务功能 5、更新了版本号
XiaoYouChRf0917d33d986
diff --git a/Res_rc.py b/Res_rc.pyindex dfbf1bd8..4a0e2b10 100644--- a/Res_rc.py+++ b/Res_rc.py@@ -455,10 +455,13 @@ qt_resource_struct = b"\\x00\x00\x01\x89\xcf8\x96`\"+def qInitResources():QtCore.qRegisterResourceData(0x03, qt_resource_struct, qt_resource_name, qt_resource_data)+def qCleanupResources():QtCore.qUnregisterResourceData(0x03, qt_resource_struct, qt_resource_name, qt_resource_data)+qInitResources()diff --git a/app/common/download_task.py b/app/common/download_task.pynew file mode 100644index 00000000..5e4899eb--- /dev/null+++ b/app/common/download_task.py@@ -0,0 +1,241 @@+import re+from pathlib import Path+from time import time, sleep+from urllib.parse import urlparse++import requests+from PySide6.QtCore import QThread, Signal++from app.common.tool_hub import getWindowsProxy++Headers = {+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.64"}++urlRe = re.compile(r"^" ++ "((?:https?|ftp)://)" ++ "(?:\\S+(?::\\S*)?@)?" ++ "(?:" ++ "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" ++ "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" ++ "(\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" ++ "|" ++ "((?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" ++ '(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*' ++ "(\\.([a-z\\u00a1-\\uffff]{2,}))" ++ ")" ++ "(?::\\d{2,5})?" ++ "(?:/\\S*)?" ++ "$", re.IGNORECASE)+++def getRealUrl(url: str):+ try:+ response = requests.head(url=url, headers=Headers, allow_redirects=False, verify=False,+ proxies=getWindowsProxy())++ if response.status_code == 400: # Bad Requests+ # TODO 报错处理+ print("ERROR!", "HTTP400!Bad Url!\n请尝试更换下载链接!")+ return++ while response.status_code == 302: # 当302的时候+ rs = response.headers["location"] # 获取重定向信息+ print(f'Status_Code:302, Headers["Location"] Info: {rs}')+ # 看它返回的是不是完整的URL+ t = urlRe.search(rs)+ if t: # 是的话直接跳转+ url = rs+ elif not t: # 不是在前面加上URL+ url = re.findall(r"((?:https?|ftp)://[\s\S]*?)/", url)+ url = url[0] + rs++ print(f"Status_Code:302,Redirect to {url}")++ response = requests.head(url=url, headers=Headers, allow_redirects=False, verify=False,+ proxies=getWindowsProxy()) # 再访问一次++ return url++ # TODO 报错处理+ except requests.exceptions.ConnectionError as err:+ print(f"网络连接失败!错误信息:{err}")+ return+ except ValueError as err:+ print(f"网络连接失败!错误信息: {err}")+ return+++class DownloadTask(QThread):+ processChange = Signal(str) # 目前进度 且因为C++ int最大值仅支持到2^31 PyQt又没有Qint类 故只能使用str代替+ taskFinished = Signal() # 内置信号的不好用++ def __init__(self, url, maxBlockNum: int = 8, filePath=None, fileName=None, parent=None):+ super().__init__(parent)++ # 获取真实URL+ url = getRealUrl(url)++ head = requests.head(url, headers=Headers, proxies=getWindowsProxy()).headers++ # 获取文件大小, 判断是否可以分块下载+ if "content-length" not in head:+ self.fileSize = 0+ self.ableToParallelDownload = False+ else:+ self.fileSize = int(head["content-length"])+ self.ableToParallelDownload = True++ # 获取文件名+ if not fileName:+ try:+ fileName = head["content-disposition"]+ t = re.findall(r"filename=\"([\s\S]*)\"", fileName)+ if t:+ fileName = t[0]+ else:+ t = re.findall(r"filename=([\s\S]*);", fileName)+ fileName = t[0]+ print(f"方法1获取文件名成功, 文件名:{fileName}")+ except KeyError or IndexError as e:+ # 处理没有文件名的情况+ print(f"获取文件名失败, KeyError or IndexError:{e}")+ fileName = urlparse(url).path.split('/')[-1]+ print(f"方法2获取文件名成功, 文件名:{fileName}")+ except Exception as e:+ # 什么都 Get 不到的情况+ print(f"获取文件名失败, Exception:{e}")+ content_type = head["content-type"].split('/')[-1]+ fileName = f"downloaded_file{int(time())}.{content_type}"+ print(f"方法3获取文件名成功, 文件名:{fileName}")++ # 获取文件路径+ if not filePath and Path(filePath).is_dir() == False:+ filePath = Path.cwd()+ else:+ filePath = Path(filePath)+ if not filePath.exists():+ filePath.mkdir()++ # 创建空文件+ Path(f"{filePath}/{fileName}").touch()++ self.process = 0+ self.url = url+ self.fileName = fileName+ self.filePath = filePath+ self.maxBlockNum = maxBlockNum+ self.workers: list[DownloadWorker] = []++ def clacDivisionalRange(self):+ step = self.fileSize // self.maxBlockNum # 每块大小+ arr = list(range(0, self.fileSize, step))++ # 否则线程数可能会不按预期地少一个+ if self.fileSize % self.maxBlockNum == 0:+ arr.append(self.fileSize)++ step_list = []++ for i in range(len(arr) - 1): #++ s_pos, e_pos = arr[i], arr[i + 1] - 1+ step_list.append([s_pos, e_pos])++ step_list[-1][-1] = self.fileSize - 1 # 修正++ return step_list++ def run(self):+ # 读取历史记录+ # 历史记录.ghd文件采用格式示例: [{"id": 0, "start": 0, "process": 0, "end": 100, }, {"id": 1, "start": 101, "process": 111, "end": 200}]+ if Path(f"{self.filePath}/{self.fileName}.ghd").exists():+ try:+ with open(f"{self.filePath}/{self.fileName}.ghd", "r", encoding="utf-8") as f:+ workersInfo = eval(f.read())+ print(workersInfo)+ for i in workersInfo:+ self.workers.append(+ DownloadWorker(i["id"], i["start"], i["process"], i["end"], self.url, self.filePath,+ self.fileName))+ # TODO 错误处理+ except:+ if self.ableToParallelDownload:+ for i in range(self.maxBlockNum):+ stepList = self.clacDivisionalRange()+ self.workers.append(+ DownloadWorker(i, stepList[i][0], stepList[i][0], stepList[i][1], self.url, self.filePath,+ self.fileName))+ else:+ if self.ableToParallelDownload:+ for i in range(self.maxBlockNum):+ stepList = self.clacDivisionalRange()+ self.workers.append(+ DownloadWorker(i, stepList[i][0], stepList[i][0], stepList[i][1], self.url, self.filePath,+ self.fileName))++ for i in self.workers:+ print(f"正在启动第{i.id}个线程")+ i.start()++ # 实时统计进度并写入历史记录文件+ while not self.process == self.fileSize:+ with open(f"{self.filePath}/{self.fileName}.ghd", "w", encoding="utf-8") as f:+ f.write(str([{"id": i.id, "start": i.startProcess, "process": i.process, "end": i.end} for i in+ self.workers]))+ f.flush()++ self.process = sum([i.process - i.startProcess + 1 for i in self.workers])+ self.processChange.emit(str(self.process))++ # print(self.process, self.fileSize)++ sleep(1)++ # 删除历史记录文件+ try:+ Path(f"{self.filePath}/{self.fileName}.ghd").unlink()++ except Exception as e:+ print(f"删除历史记录文件失败, 请手动删除. 错误信息: {e}")++ self.taskFinished.emit()+++class DownloadWorker(QThread):+ def __init__(self, id, start, process, end, url, filePath, fileName, parent=None):+ super().__init__(parent)+ self.id = id+ self.startProcess = start+ self.process = process+ self.end = end+ self.url = url+ self.filePath = filePath+ self.fileName = fileName++ def run(self):+ finished = False+ while not finished:+ try:+ download_headers = {"Range": f"bytes={self.process}-{self.end}",+ "User-Agent": Headers["User-Agent"]}++ res = requests.get(self.url, headers=download_headers, proxies=getWindowsProxy(), stream=True,+ timeout=60)++ self.file = open(f"{self.filePath}/{self.fileName}", "rb+")+ self.file.seek(self.process)+ for chunk in res.iter_content(chunk_size=65536): # iter_content 的单位是字节, 即每64K写一次文件+ if chunk:+ self.file.write(chunk)+ self.process += 65536++ if self.process >= self.end:+ self.process = self.end++ self.file.close()+ finished = True++ except Exception as e:+ self.file.close()+ print(f"线程{self.id}正在重连, Error: {e}")+ sleep(5)diff --git a/app/common/signal_bus.py b/app/common/signal_bus.pyindex accd9ca7..56932df2 100644--- a/app/common/signal_bus.py+++ b/app/common/signal_bus.py@@ -2,11 +2,11 @@from PySide6.QtCore import QObject, Signalfrom PySide6.QtGui import QPixmap+class SignalBus(QObject):""" Signal bus """-- addTaskSignal = Signal(str,str,int,str,QPixmap)- TaskList = []+ addTaskSignal = Signal(str, str, int, str, QPixmap, bool) # url, filePath, maxBlockNum, name, icon+ Tasks = []-signalBus = SignalBus()\ No newline at end of file+signalBus = SignalBus()diff --git a/app/common/tool_hub.py b/app/common/tool_hub.pynew file mode 100644index 00000000..37f85be0--- /dev/null+++ b/app/common/tool_hub.py@@ -0,0 +1,41 @@+import winreg+++def getWindowsProxy():+ try:+ # 打开 Windows 注册表项+ key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,+ r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')++ # 获取代理开关状态+ proxy_enable, _ = winreg.QueryValueEx(key, 'ProxyEnable')++ if proxy_enable:+ # 获取代理地址和端口号+ proxy_server, _ = winreg.QueryValueEx(key, 'ProxyServer')+ return {+ "http": proxy_server,+ "https": proxy_server,+ }+ else:+ return {+ "http": None,+ "https": None,+ }++ except Exception as e:+ print("获取 Windows 系统代理失败:", e)+ return {+ "http": None,+ "https": None,+ }+++def getReadableSize(size):+ units = ["B", "KB", "MB", "GB", "TB", "PB"]+ unit_index = 0+ K = 1024.0+ while size >= K:+ size = size / K+ unit_index += 1+ return "%.2f %s" % (size, units[unit_index])diff --git a/app/components/Ui_SystemInfoCard.py b/app/components/Ui_SystemInfoCard.pyindex 5c896da9..02c545ca 100644--- a/app/components/Ui_SystemInfoCard.py+++ b/app/components/Ui_SystemInfoCard.py@@ -8,18 +8,12 @@## WARNING! All changes made in this file will be lost when recompiling UI file!################################################################################-from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,- QMetaObject, QObject, QPoint, QRect,- QSize, QTime, QUrl, Qt)-from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,- QFont, QFontDatabase, QGradient, QIcon,- QImage, QKeySequence, QLinearGradient, QPainter,- QPalette, QPixmap, QRadialGradient, QTransform)-from PySide6.QtWidgets import (QApplication, QHBoxLayout, QSizePolicy, QVBoxLayout,- QWidget)--from qfluentwidgets import (BodyLabel, CardWidget, PixmapLabel, PrimarySplitPushButton,- SplitPushButton, TitleLabel)+from PySide6.QtCore import (QCoreApplication, QMetaObject, QSize, Qt)+from PySide6.QtWidgets import (QHBoxLayout, QSizePolicy, QVBoxLayout)++from qfluentwidgets import (BodyLabel, PixmapLabel, PrimarySplitPushButton,+ TitleLabel)+class Ui_SystemInfoCard(object):def setupUi(self, SystemInfoCard):@@ -65,7 +59,6 @@ class Ui_SystemInfoCard(object):self.BodyVBoxLayout.addWidget(self.BodyLabel)-self.horizontalLayout.addLayout(self.BodyVBoxLayout)self.PrimarySplitPushButton = PrimarySplitPushButton(SystemInfoCard)@@ -75,14 +68,15 @@ class Ui_SystemInfoCard(object):self.horizontalLayout.addWidget(self.PrimarySplitPushButton)-self.retranslateUi(SystemInfoCard)QMetaObject.connectSlotsByName(SystemInfoCard)+# setupUidef retranslateUi(self, SystemInfoCard):SystemInfoCard.setWindowTitle(QCoreApplication.translate("SystemInfoCard", u"Form", None))- self.PrimarySplitPushButton.setProperty("text_", QCoreApplication.translate("SystemInfoCard", u" \u4e0b\u8f7d ", None))+ self.PrimarySplitPushButton.setProperty("text_", QCoreApplication.translate("SystemInfoCard",+ u" \u4e0b\u8f7d ",+ None))# retranslateUi-diff --git a/app/components/Ui_TaskCard.py b/app/components/Ui_TaskCard.pyindex e4a78802..87e3ac86 100644--- a/app/components/Ui_TaskCard.py+++ b/app/components/Ui_TaskCard.py@@ -8,18 +8,16 @@## WARNING! All changes made in this file will be lost when recompiling UI file!################################################################################-from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,- QMetaObject, QObject, QPoint, QRect,- QSize, QTime, QUrl, Qt)-from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,- QFont, QFontDatabase, QGradient, QIcon,- QImage, QKeySequence, QLinearGradient, QPainter,- QPalette, QPixmap, QRadialGradient, QTransform)-from PySide6.QtWidgets import (QApplication, QHBoxLayout, QSizePolicy, QSpacerItem,- QVBoxLayout, QWidget)--from qfluentwidgets import (BodyLabel, CardWidget, PixmapLabel, ProgressBar,- PushButton, TitleLabel, ToolButton, PrimaryToolButton)+from PySide6.QtCore import (QCoreApplication, QMetaObject, QSize, Qt)+from PySide6.QtGui import (QIcon)+from PySide6.QtWidgets import (QHBoxLayout, QSizePolicy, QSpacerItem,+ QVBoxLayout)++from qfluentwidgets import (BodyLabel, PixmapLabel, ProgressBar,+ TitleLabel, ToolButton, PrimaryToolButton)++from qfluentwidgets import FluentIcon as FIF+class Ui_TaskCard(object):def setupUi(self, TaskCard):@@ -32,8 +30,8 @@ class Ui_TaskCard(object):self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")self.LogoPixmapLabel = PixmapLabel(TaskCard)self.LogoPixmapLabel.setObjectName(u"LogoPixmapLabel")- self.LogoPixmapLabel.setMinimumSize(QSize(101, 101))- self.LogoPixmapLabel.setMaximumSize(QSize(101, 101))+ self.LogoPixmapLabel.setMinimumSize(QSize(91, 91))+ self.LogoPixmapLabel.setMaximumSize(QSize(91, 91))self.LogoPixmapLabel.setScaledContents(True)self.LogoPixmapLabel.setAlignment(Qt.AlignCenter)@@ -68,12 +66,12 @@ class Ui_TaskCard(object):self.horizontalLayout.addWidget(self.pauseButton)- # self.cancelButton = ToolButton(TaskCard)- # self.cancelButton.setObjectName(u"cancelButton")- # self.cancelButton.setMinimumSize(QSize(31, 31))- # self.cancelButton.setMaximumSize(QSize(31, 31))+ self.cancelButton = ToolButton(TaskCard)+ self.cancelButton.setObjectName(u"cancelButton")+ self.cancelButton.setMinimumSize(QSize(31, 31))+ self.cancelButton.setMaximumSize(QSize(31, 31))- # self.horizontalLayout.addWidget(self.cancelButton)+ self.horizontalLayout.addWidget(self.cancelButton)self.folderButton = PrimaryToolButton(TaskCard)self.folderButton.setObjectName(u"folderButton")@@ -89,7 +87,7 @@ class Ui_TaskCard(object):self.speedLable = BodyLabel(TaskCard)self.speedLable.setObjectName(u"speedLable")self.speedLable.setMinimumSize(QSize(0, 19))- self.speedLable.setMaximumSize(QSize(151, 19))+ self.speedLable.setMaximumSize(QSize(601, 19))self.horizontalLayout_2.addWidget(self.speedLable)@@ -111,7 +109,6 @@ class Ui_TaskCard(object):self.horizontalLayout_2.addWidget(self.processLabel)-self.verticalLayout.addLayout(self.horizontalLayout_2)self.ProgressBar = ProgressBar(TaskCard)@@ -119,20 +116,28 @@ class Ui_TaskCard(object):self.verticalLayout.addWidget(self.ProgressBar)-self.horizontalLayout_3.addLayout(self.verticalLayout)+ # 初始化 Icon 类+ self.pauseIcon = QIcon()+ self.pauseIcon.addFile(u":/icon/pause.svg", QSize(), QIcon.Normal, QIcon.Off)+ self.playIcon = QIcon()+ self.playIcon.addFile(u":/icon/play.svg", QSize(), QIcon.Normal, QIcon.Off)++ self.pauseButton.setIcon(self.pauseIcon)+ self.cancelButton.setIcon(FIF.DELETE)+ self.folderButton.setIcon(FIF.FOLDER)self.retranslateUi(TaskCard)QMetaObject.connectSlotsByName(TaskCard)+# setupUidef retranslateUi(self, TaskCard):TaskCard.setWindowTitle(QCoreApplication.translate("TaskCard", u"Form", None))self.pauseButton.setText("")- # self.cancelButton.setText("")+ self.cancelButton.setText("")self.folderButton.setText("")self.processLabel.setText("")# retranslateUi-diff --git a/app/components/add_task_option_dialog.py b/app/components/add_task_option_dialog.pynew file mode 100644index 00000000..3053094a--- /dev/null+++ b/app/components/add_task_option_dialog.py@@ -0,0 +1,158 @@+import os+import re+from pathlib import Path++from PySide6.QtCore import Signal, QDir+from PySide6.QtGui import QColor+from PySide6.QtWidgets import QVBoxLayout, QFileDialog, QHBoxLayout, QSizePolicy+from qfluentwidgets import PushSettingCard, SettingCardGroup, RangeSettingCard, RangeConfigItem, RangeValidator, \+ PushButton, PrimaryPushButton, ComboBoxSettingCard, OptionsValidator, OptionsConfigItem, TextEdit, \+ MessageBox, isDarkTheme+from qfluentwidgets.common.icon import FluentIcon as FIF+from qfluentwidgets.components.dialog_box.mask_dialog_base import MaskDialogBase++from ..common.signal_bus import signalBus++urlRe = re.compile(r"^" ++ "((?:https?|ftp)://)" ++ "(?:\\S+(?::\\S*)?@)?" ++ "(?:" ++ "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" ++ "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" ++ "(\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" ++ "|" ++ "((?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" ++ '(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*' ++ "(\\.([a-z\\u00a1-\\uffff]{2,}))" ++ ")" ++ "(?::\\d{2,5})?" ++ "(?:/\\S*)?" ++ "$", re.IGNORECASE)+++class AddTaskOptionDialog(MaskDialogBase):+ startSignal = Signal()++ def __init__(self, parent=None):+ super().__init__(parent=parent)++ self.setShadowEffect(60, (0, 10), QColor(0, 0, 0, 50))+ self.setMaskColor(QColor(0, 0, 0, 76))++ self.VBoxLayout = QVBoxLayout(self.widget)+ self.VBoxLayout.setContentsMargins(18, 18, 18, 18)++ self.widget.setLayout(self.VBoxLayout)++ self.widget.setMinimumSize(510, 400)+ self.widget.setMaximumSize(680, 410)+ if isDarkTheme():+ # C = ThemeColor.DARK_3.color()+ self.widget.setStyleSheet(".QFrame{border-radius:10px;background-color:rgb(39,39,39)}")+ else:+ self.widget.setStyleSheet(".QFrame{border-radius:10px;background-color:white}")++ # 下载链接组+ self.linkGroup = SettingCardGroup(+ "新建任务", self.widget)++ self.linkTextEdit = TextEdit(self.linkGroup)+ self.linkTextEdit.setPlaceholderText("请在此键入下载链接")+ self.linkTextEdit.setMinimumHeight(100)+ sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)+ self.linkTextEdit.setSizePolicy(sizePolicy)++ self.linkGroup.addSettingCard(self.linkTextEdit)++ # 下载设置组+ self.settingGroup = SettingCardGroup(+ "下载设置", self.widget)++ # Choose Folder Card+ self.downloadFolderCard = PushSettingCard(+ "选择下载目录",+ FIF.DOWNLOAD,+ "下载目录",+ QDir.currentPath(),+ self.settingGroup+ )++ # Choose Threading Card+ self.blockNumCard = RangeSettingCard(+ RangeConfigItem("Material", "AcrylicBlurRadius", 24, RangeValidator(1, 128)),+ FIF.CHAT,+ "下载线程数",+ '下载线程越多,下载越快,同时也越吃性能',+ self.settingGroup+ )++ self.buttonLayout = QHBoxLayout()++ self.yesButton = PrimaryPushButton(self)+ self.yesButton.setObjectName("yesButton")+ self.yesButton.setDisabled(True)+ self.yesButton.setText("开始下载")+ self.noButton = PushButton(self)+ self.noButton.setObjectName("noButton")+ self.noButton.setText("取消下载")++ self.buttonLayout.addWidget(self.noButton)+ self.buttonLayout.addWidget(self.yesButton)+ self.buttonLayout.setSpacing(18)++ self.settingGroup.addSettingCards([self.downloadFolderCard, self.blockNumCard])++ self.VBoxLayout.addWidget(self.linkGroup)+ self.VBoxLayout.addWidget(self.settingGroup)+ self.VBoxLayout.addLayout(self.buttonLayout)++ self.__connectSignalToSlot()++ def __connectSignalToSlot(self):+ self.downloadFolderCard.clicked.connect(+ self.__onDownloadFolderCardClicked)+ self.noButton.clicked.connect(self.close)++ self.yesButton.clicked.connect(self.startTask)++ self.linkTextEdit.textChanged.connect(self.__onLinkTextChanged)++ def startTask(self):+ path = Path(self.downloadFolderCard.contentLabel.text())++ # 检测路径是否有权限写入+ if not path.exists():+ try:+ path.mkdir(parents=True, exist_ok=True)+ except Exception as e:+ MessageBox("错误", str(e), self)+ else:+ if not os.access(path, os.W_OK):+ MessageBox("错误", "似乎是没有权限向此目录写入文件", self)++ url = self.linkTextEdit.toPlainText()++ signalBus.addTaskSignal.emit(url,+ str(path), self.blockNumCard.configItem.value,+ "", None, False)+ self.close()++ def __onDownloadFolderCardClicked(self):+ """ download folder card clicked slot """+ folder = QFileDialog.getExistingDirectory(+ self, "选择文件夹", "./")+ if not folder or self.downloadFolderCard.contentLabel.text() == folder:+ return++ self.downloadFolderCard.setContent(folder)++ def __onLinkTextChanged(self):+ """ link text changed slot """+ text: str = self.linkTextEdit.toPlainText()++ _ = urlRe.search(text)++ if _:+ self.yesButton.setEnabled(True)+ else:+ self.yesButton.setDisabled(True)diff --git a/app/components/download_option_dialog.py b/app/components/download_option_dialog.pyindex a5880bd9..df04b9f4 100644--- a/app/components/download_option_dialog.py+++ b/app/components/download_option_dialog.py@@ -1,11 +1,12 @@+import osfrom pathlib import Path-from PySide6.QtCore import Signal+from PySide6.QtCore import Signal, QDirfrom PySide6.QtGui import QColorfrom PySide6.QtWidgets import QVBoxLayout, QFileDialog, QHBoxLayout, QSizePolicyfrom qfluentwidgets import PushSettingCard, SettingCardGroup, RangeSettingCard, RangeConfigItem, RangeValidator, \PushButton, PrimaryPushButton, ComboBoxSettingCard, OptionsValidator, OptionsConfigItem, TextEdit, \- Theme, qconfig+ MessageBox, isDarkThemefrom qfluentwidgets.common.icon import FluentIcon as FIFfrom qfluentwidgets.components.dialog_box.mask_dialog_base import MaskDialogBase@@ -30,17 +31,16 @@ class DownloadOptionDialog(MaskDialogBase):self.widget.setLayout(self.VBoxLayout)- self.widget.setMinimumSize(510, 410)- self.widget.setMaximumSize(680, 420)- print(qconfig.themeMode.value)- if qconfig.themeMode.value == Theme.DARK:+ self.widget.setMinimumSize(510, 510)+ self.widget.setMaximumSize(680, 520)+ if isDarkTheme():# C = ThemeColor.DARK_3.color()self.widget.setStyleSheet(".QFrame{border-radius:10px;background-color:rgb(39,39,39)}")else:self.widget.setStyleSheet(".QFrame{border-radius:10px;background-color:white}")- # 信息组- self.VersionGroup = SettingCardGroup(+ # 版本组+ self.versionGroup = SettingCardGroup("选择版本", self.widget)for i in self.list:@@ -55,19 +55,25 @@ class DownloadOptionDialog(MaskDialogBase):"选择版本","选择你想下载的版本",texts=self.versions,- parent=self.VersionGroup+ parent=self.versionGroup)- self.logTextEdit = TextEdit(self.VersionGroup)+ self.versionGroup.addSettingCard(self.versionCard)++ self.logGroup = SettingCardGroup(+ "更新日志", self.widget)++ self.logTextEdit = TextEdit(self.versionGroup)self.logTextEdit.setReadOnly(True)+ self.logTextEdit.setMinimumHeight(100)self.logTextEdit.setText(self.list[0]["Log"])sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)self.logTextEdit.setSizePolicy(sizePolicy)- self.VersionGroup.addSettingCards([self.versionCard, self.logTextEdit])+ self.logGroup.addSettingCard(self.logTextEdit)# 下载设置组- self.SettingGroup = SettingCardGroup(+ self.settingGroup = SettingCardGroup("下载设置", self.widget)# Choose Folder Card@@ -75,20 +81,20 @@ class DownloadOptionDialog(MaskDialogBase):"选择下载目录",FIF.DOWNLOAD,"下载目录",- str(Path.cwd()),- self.SettingGroup+ QDir.currentPath(),+ self.settingGroup)# Choose Threading Cardself.blockNumCard = RangeSettingCard(- RangeConfigItem("Material", "AcrylicBlurRadius", 8, RangeValidator(0, 10)),+ RangeConfigItem("Material", "AcrylicBlurRadius", 24, RangeValidator(1, 128)),FIF.CHAT,"下载线程数",'下载线程越多,下载越快,同时也越吃性能',- self.SettingGroup+ self.settingGroup)- self.ButtonLayout = QHBoxLayout()+ self.buttonLayout = QHBoxLayout()self.yesButton = PrimaryPushButton(self)self.yesButton.setObjectName("yesButton")@@ -97,15 +103,16 @@ class DownloadOptionDialog(MaskDialogBase):self.noButton.setObjectName("noButton")self.noButton.setText("取消下载")- self.ButtonLayout.addWidget(self.noButton)- self.ButtonLayout.addWidget(self.yesButton)- self.ButtonLayout.setSpacing(18)+ self.buttonLayout.addWidget(self.noButton)+ self.buttonLayout.addWidget(self.yesButton)+ self.buttonLayout.setSpacing(18)- self.SettingGroup.addSettingCards([self.downloadFolderCard, self.blockNumCard])+ self.settingGroup.addSettingCards([self.downloadFolderCard, self.blockNumCard])- self.VBoxLayout.addWidget(self.VersionGroup)- self.VBoxLayout.addWidget(self.SettingGroup)- self.VBoxLayout.addLayout(self.ButtonLayout)+ self.VBoxLayout.addWidget(self.versionGroup)+ self.VBoxLayout.addWidget(self.logGroup)+ self.VBoxLayout.addWidget(self.settingGroup)+ self.VBoxLayout.addLayout(self.buttonLayout)self.__connectSignalToSlot()@@ -119,9 +126,21 @@ class DownloadOptionDialog(MaskDialogBase):self.versionCard.comboBox.currentIndexChanged.connect(self._onCurrentIndexChanged)def startTask(self):+ path = Path(self.downloadFolderCard.contentLabel.text())++ # 检测路径是否有权限写入+ if not path.exists():+ try:+ path.mkdir(parents=True, exist_ok=True)+ except Exception as e:+ MessageBox("错误", str(e), self)+ else:+ if not os.access(path, os.W_OK):+ MessageBox("错误", "似乎是没有权限向此目录写入文件", self)+signalBus.addTaskSignal.emit(self.list[self.versionCard.comboBox.currentIndex()]["Url"],- self.downloadFolderCard.contentLabel.text(), self.blockNumCard.configItem.value,- self.dict["Name"], self.dict["Pixmap"])+ str(path), self.blockNumCard.configItem.value,+ "", None, False)self.close()def __onDownloadFolderCardClicked(self):diff --git a/app/components/system_info_card.py b/app/components/system_info_card.pyindex 8dbef670..36fb7455 100644--- a/app/components/system_info_card.py+++ b/app/components/system_info_card.py@@ -1,11 +1,11 @@-from .Ui_SystemInfoCard import Ui_SystemInfoCard+from PySide6.QtCore import QUrl+from PySide6.QtGui import QDesktopServices, QPixmapfrom qfluentwidgets import CardWidget, RoundMenu, Actionfrom qfluentwidgets import FluentIcon as FIF+from .Ui_SystemInfoCard import Ui_SystemInfoCardfrom ..components.download_option_dialog import DownloadOptionDialog-from PySide6.QtGui import QDesktopServices, QPixmap-from PySide6.QtCore import QUrlclass SystemInfoCard(CardWidget, Ui_SystemInfoCard):def __init__(self, parent=None):@@ -22,13 +22,11 @@ class SystemInfoCard(CardWidget, Ui_SystemInfoCard):self.Menu.addAction(self.VideoAction)self.PrimarySplitPushButton.setFlyout(self.Menu)-def connect_signal_to_slot(self):- self.VideoAction.triggered.connect(lambda:QDesktopServices.openUrl(QUrl(self.Video)))+ self.VideoAction.triggered.connect(lambda: QDesktopServices.openUrl(QUrl(self.Video)))self.PrimarySplitPushButton.clicked.connect(self.open_download_messagebox)def open_download_messagebox(self):- w = DownloadOptionDialog(self.parent().parent().parent().parent().parent().parent(), self.List, {"Pixmap": self.pixmap, "Name":self.TitleLabel.text()})+ w = DownloadOptionDialog(self.parent().parent().parent().parent().parent().parent(), self.List,+ {"Pixmap": self.pixmap, "Name": self.TitleLabel.text()})w.exec()--diff --git a/app/components/task_card.py b/app/components/task_card.pyindex 14441a00..e5b2d664 100644--- a/app/components/task_card.py+++ b/app/components/task_card.py@@ -1,382 +1,229 @@+import hashlibimport osimport re-import threading-import traceback-import winreg-from concurrent.futures import ThreadPoolExecutor, as_completedfrom pathlib import Path-from time import time, sleep+from time import sleep-import requests-from PySide6.QtCore import QSize, Signal-from PySide6.QtGui import QPixmap, QIcon+from PySide6.QtCore import QThread, Signal, QFileInfo+from PySide6.QtGui import QPixmap+from PySide6.QtWidgets import QFileIconProviderfrom qfluentwidgets import CardWidget-from qfluentwidgets import FluentIcon as FIFfrom .Ui_TaskCard import Ui_TaskCard+from ..common.download_task import DownloadTask+from ..common.tool_hub import getWindowsProxy, getReadableSizeHeaders = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.64"}urlRe = re.compile(r"^" +- "((?:https?|ftp)://)" +- "(?:\\S+(?::\\S*)?@)?" +- "(?:" +- "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +- "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +- "(\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +- "|" +- "((?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +- '(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*' +- "(\\.([a-z\\u00a1-\\uffff]{2,}))" +- ")" +- "(?::\\d{2,5})?" +- "(?:/\\S*)?" +- "$", re.IGNORECASE)--def get_windows_proxy():- try:- # 打开 Windows 注册表项- key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,- r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')-- # 获取代理开关状态- proxy_enable, _ = winreg.QueryValueEx(key, 'ProxyEnable')-- if proxy_enable:- # 获取代理地址和端口号- proxy_server, _ = winreg.QueryValueEx(key, 'ProxyServer')- return proxy_server- else:- return None-- except Exception as e:- print("获取 Windows 系统代理失败:", e)- return None-+ "((?:https?|ftp)://)" ++ "(?:\\S+(?::\\S*)?@)?" ++ "(?:" ++ "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" ++ "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" ++ "(\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" ++ "|" ++ "((?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" ++ '(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*' ++ "(\\.([a-z\\u00a1-\\uffff]{2,}))" ++ ")" ++ "(?::\\d{2,5})?" ++ "(?:/\\S*)?" ++ "$", re.IGNORECASE)# 获取系统代理-proxy = get_windows_proxy()-if proxy:- proxy = {- "http": proxy,- "https": proxy,- }-else:- proxy = {- "http": None,- "https": None,- }+proxy = getWindowsProxy()class TaskCard(CardWidget, Ui_TaskCard):- changeInfoSignal = Signal(int, str, str)-- def __init__(self, url: str, path: str, block_num: int, number:int,name: str, pixmap: QPixmap, parent=None, file_name=None):+ def __init__(self, url, path, maxBlockNum: int, pixmap: QPixmap = None, name: str = None, parent=None,+ autoCreated=False):super().__init__(parent=parent)- self.setupUi(self)- self.TitleLabel.setText(name)- self.LogoPixmapLabel.setPixmap(pixmap)- self.LogoPixmapLabel.setFixedSize(101, 101)+ self.setupUi(self)- # 初始化 Icon 类- self.pauseIcon = QIcon()- self.pauseIcon.addFile(u":/icon/pause.svg", QSize(), QIcon.Normal, QIcon.Off)- self.playIcon = QIcon()- self.playIcon.addFile(u":/icon/play.svg", QSize(), QIcon.Normal, QIcon.Off)+ # 初始化参数- self.pauseButton.setIcon(self.pauseIcon)- # self.cancelButton.setIcon(FIF.DELETE)- self.folderButton.setIcon(FIF.FOLDER)+ self.url = url+ self.filePath = path+ self.maxBlockNum = maxBlockNum- self.paused = False+ if name:+ self.task = DownloadTask(url, maxBlockNum, path, name)+ self.fileName = name+ else:+ self.task = DownloadTask(url, maxBlockNum, path)+ self.fileName = self.task.fileName- self.number = number+ if not pixmap:+ pixmap = QFileIconProvider().icon(QFileInfo(f"{self.filePath}/{self.fileName}")).pixmap(128, 128) # 自动获取图标- # 下载相关初始化+ self.paused = False- # 初始化参数- self.divisional_ranges = []- self.blockNums = block_num- self.every_process = []- self.total_process = 0-- # 处理重定向- self.url = self.__get_real_url(url)- print(self.url)-- # 获取文件大小- head = requests.head(self.url, headers=Headers, proxies=proxy).headers- self.fileSize = int(head["content-length"])- print(self.fileSize)-- # 获取文件名- if not file_name:- try:- self.fileName = head["content-disposition"]- print(self.fileName)- t = re.findall(r"filename=\"([\s\S]*)\"", self.fileName)- if t:- self.fileName = t[0]- except KeyError:- # 处理没有文件名的情况- # print(f"KeyError:{err}")- self.fileName = Path(url).name- print(self.fileName)- except Exception as e:- # 什么都 Get 不到的情况- # TODO Report- traceback.print_exc()- content_type = head["content-type"].split('/')[-1]- self.fileName = f"downloaded_file{int(time())}.{content_type}"- # print(file_name)- else:- self.fileName = file_name+ self.lastProcess = 0- # 判断路径是否存在并创建路径- if not path:- self.savePath = Path(__file__)- self.savePath = self.savePath.parent- # print(save_path)- else:- try:- self.savePath = Path(path)- if not self.savePath.exists():- self.savePath.mkdir()- except:- # TODO 路径不对就别干了- return-- # 文件绝对路径(合并file_name和save_path)- self.fileResolve = self.savePath / self.fileName- self.fileInfoResolve = Path(self.savePath / f"~${self.fileName}")- print(f"绝对路径:{self.fileResolve}")+ # 显示信息+ self.TitleLabel.setText(self.fileName)+ self.LogoPixmapLabel.setPixmap(pixmap)+ self.LogoPixmapLabel.setFixedSize(91, 91)+ self.processLabel.setText(f"0B/{getReadableSize(self.task.fileSize)}")# 连接信号到槽- self.changeInfoSignal.connect(self.__change_info)- self.pauseButton.clicked.connect(self.pause_task)- self.folderButton.clicked.connect(lambda:os.startfile(path))+ self.pauseButton.clicked.connect(self.pauseTask)+ self.cancelButton.clicked.connect(self.cancelTask)+ self.folderButton.clicked.connect(lambda: os.startfile(self.task.filePath))+ self.task.processChange.connect(self.__changeInfo)+ self.task.taskFinished.connect(self.taskFinished)++ # 写入未完成任务记录文件,以供下次打开时继续下载+ if not autoCreated:+ with open("./history", "a", encoding="utf-8") as f:+ _ = {"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),+ "blockNum": self.maxBlockNum}+ f.write(str(_) + "\n")# 开始下载- self.Thread = threading.Thread(target=self.start, daemon=True)- self.Thread.start()-- def pause_task(self):- if self.paused:- self.paused = False # 停止就开始- self.processLabel.setText("正在重启")- if not self.Thread.is_alive():- self.Thread = threading.Thread(target=self.start, daemon=True)- self.Thread.start()- self.pauseButton.setIcon(self.pauseIcon)- elif not self.paused:- self.paused = True- self.processLabel.setText("正在暂停")- while self.Thread.is_alive():- sleep(0.1)+ self.task.start()++ def pauseTask(self):+ if not self.paused: # 暂停+ self.pauseButton.setDisabled(True)self.pauseButton.setIcon(self.playIcon)- self.processLabel.setText("暂停中")-- def __change_info(self, value:int, process:str, speed:str):- self.ProgressBar.setValue(value)- self.processLabel.setText(process)- self.speedLable.setText(speed)-- def __get_real_url(self, url: str):- try:- response = requests.head(url=url, headers=Headers, allow_redirects=False, verify=False)- print(response)-- if response.status_code == 400: # Bad Requests- # TODO 报错处理- print("ERROR!", "HTTP400!Bad Url!\n请尝试更换下载链接!")- return-- while response.status_code == 302: # 当302的时候- rs = response.headers["location"] # 获取重定向信息- print(rs)- # 看它返回的是不是完整的URL- t = urlRe.search(rs)- if t: # 是的话直接跳转- url = rs- elif not t: # 不是在前面加上URL- url = re.findall(r"((?:https?|ftp)://[\s\S]*?)/", url)- url = url[0] + rs-- print(url)-- response = requests.head(url=url, headers=Headers, allow_redirects=False, verify=False) # 再访问一次-- return url-- # TODO 报错处理- except requests.exceptions.ConnectionError as err:- print("网络连接失败!", f"请检查网络连接!\n{err}")- return- except ValueError as err:- print("网络连接失败!", f"请尝试关闭代理!\n{err}")- return-- def calc_divisional_range(self):- step = self.fileSize // self.blockNums # 每块大小- # print(f"Step:{step}")-- arr = list(range(0, self.fileSize, step))-- # 否则线程数可能会不按预期地少一个- if self.fileSize % self.blockNums == 0:- arr.append(self.fileSize)-- # print(f"Arr:{arr}")- step_list = []- for i in range(len(arr) - 1):- s_pos, e_pos = arr[i], arr[i + 1] - 1- step_list.append([s_pos, e_pos])- step_list[-1][-1] = self.fileSize - 1- # print(f"StepList:{step_list}")- return step_list-- def download_worker(self, number, s_pos, e_pos):- finished = False- while not finished:+ for i in self.task.workers:+ try:+ i.file.close()+ except Exception as e:+ print(f"似乎无法关闭线程{i.id}对文件的占用, 错误信息: {e}")+ i.terminate()+ self.task.terminate()+ self.speedLable.setText("任务已经暂停")+ self.paused = True+ self.pauseButton.setEnabled(True)++ else: # 继续+ self.pauseButton.setDisabled(True)+ self.pauseButton.setIcon(self.pauseIcon)+ self.task = DownloadTask(self.url, self.maxBlockNum, self.filePath, self.fileName)+ self.task.start()+ self.task.processChange.connect(self.__changeInfo)+ self.speedLable.setText("任务正在开始")+ self.paused = False+ self.pauseButton.setEnabled(True)++ def cancelTask(self):+ self.pauseButton.setDisabled(True)+ self.cancelButton.setDisabled(True)++ for i in self.task.workers:try:- download_headers = {"Range": f"bytes={s_pos}-{e_pos}",- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.64"}- res = requests.get(self.url, headers=download_headers, proxies=proxy, stream=True, timeout=60)- with open(self.fileResolve, "rb+") as f:- f.seek(s_pos)- for chunk in res.iter_content(chunk_size=65536): # iter_content 的单位是字节, 即每64K写一次文件- if self.paused:- return- if chunk:- f.write(chunk)- s_pos += 65536- self.every_process[number] += 65536- finished = True+ i.file.close()except Exception as e:- if self.paused:- return- print("正在重连,Error", e)- sleep(5)-- self.every_process[number] = 0-- def __get_readable_size(self, size):- units = ["B", "KB", "MB", "GB", "TB", "PB"]- unit_index = 0- K = 1024.0- while size >= K:- size = size / K- unit_index += 1- return "%.2f %s" % (size, units[unit_index])-- def download_minitor(self):- p = self.calc_divisional_range()- l = 0-- while self.total_process != self.fileSize:-- if self.paused:- return-- _ = ""- t = 0- self.total_process = self.fileResolve.stat().st_size- # 写入记录文件- with open(self.fileInfoResolve, "w+") as f:- try:- # print(self.divisional_ranges, self.every_process)- for n in range(self.blockNums):- _ += f"{str(self.divisional_ranges[n][0] + self.every_process[n])}|{self.divisional_ranges[n][1]}\n"- # print(_)+ print(f"似乎无法关闭线程{i.id}对文件的占用, 错误信息: {e}")+ i.terminate()+ self.task.terminate()++ # 删除文件+ tryCount = 0+ isDeleted = False+ while not isDeleted and tryCount < 3:+ try:+ Path(f"{self.filePath}/{self.fileName}").unlink()+ Path(f"{self.filePath}/{self.fileName}.ghd").unlink()+ print("删除成功!")++ # 删除记录文件+ with open("./history", "r", encoding="utf-8") as f:+ _ = f.read()++ _ = _.replace(str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),+ "blockNum": self.maxBlockNum}) + "\n", "")++ with open("./history", "w", encoding="utf-8") as f:f.write(_)- f.flush()- # 计算速度- for i, o in enumerate(self.every_process):- k = p[i][0]- u = self.divisional_ranges[i][0]- t += (o + u) - k- # print(f"Debug,l:{l},t:{self.total_process}")- speed = self.__get_readable_size(t - l)- # 打印信息- print("\r", f"P:{round(t / self.fileSize, 2)}, {t}|{self.fileSize}", speed, end="")- # 发送信号更新界面- self.changeInfoSignal.emit(int(round(t / self.fileSize, 2) * 100), f"{self.__get_readable_size(t)}|{self.__get_readable_size(self.fileSize)}", f"{speed}/s")- f.close()- l = t- sleep(1) # 每 N 秒检测一次- except Exception as e:- print(e)+ isDeleted = True+ tryCount = 5- # 打印信息- print("\nFinished!")- # 发送信号更新界面- self.changeInfoSignal.emit(100,- "已完成",- "")+ except FileNotFoundError:+ isDeleted = True+ tryCount = 5+ except Exception as e:+ print(f"似乎无法删除文件, 错误信息: {e}")+ tryCount += 1- def start(self):- # TODO 为了适配暂停后重新开始需要重置数据- self.every_process = []- self.total_process = 0- # 开始下载- if self.fileSize:- if not self.fileInfoResolve.exists(): # 不存在记录文件的话就从头下载- # 计算每个分块- self.divisional_ranges = self.calc_divisional_range()- # 创建空文件- with open(self.fileResolve, "wb") as f:- f.close()- # # 创建记录文件- # with open(self.fileInfoResolve, "wb") as f:- # pass- # # 隐藏记录文件- #- # 创建线程池- with ThreadPoolExecutor() as p:- futures = []- for number, _ in enumerate(self.divisional_ranges, start=0):- s_pos = _[0]- e_pos = _[1]- self.every_process.append(0)- print(number, s_pos, e_pos)- futures.append(p.submit(self.download_worker, number, s_pos, e_pos))- # 增加检测线程- futures.append(p.submit(self.download_minitor))- # 设置为守护进程- for i in p._threads:- i.daemon = True- # 等待所有任务执行完毕- as_completed(futures)- # 删除记录文件- try:- Path.unlink(self.fileInfoResolve)- except:- pass-- else: # 记录文件存在,断点续传- with open(self.fileInfoResolve, "r") as f:- with ThreadPoolExecutor() as p:- futures = []- for number, i in enumerate(f.readlines()):- i = i.split("|")- s_pos = int(i[0])- e_pos = int(i[1][:-1]) # 去掉最后的\n- self.divisional_ranges.append([s_pos, e_pos])- self.every_process.append(0)- print("断点续传:", number, s_pos, e_pos)- futures.append(p.submit(self.download_worker, number, s_pos, e_pos))- # 关闭文件,以防万一- f.close()- # 增加检测线程- futures.append(p.submit(self.download_minitor))- # 等待所有任务执行完毕- as_completed(futures)- # 删除记录文件- try:- Path.unlink(self.fileInfoResolve)- except:- pass+ sleep(0.1)++ self.deleteLater()++ def __changeInfo(self, content: str):++ process = int(content)++ duringLastSecondProcess = process - self.lastProcess++ self.speedLable.setText(f"{getReadableSize(duringLastSecondProcess)}/s")+ self.processLabel.setText(f"{getReadableSize(process)}/{getReadableSize(self.task.fileSize)}")+ self.ProgressBar.setValue((process / self.task.fileSize) * 100)++ self.lastProcess = process++ def taskFinished(self):+ self.pauseButton.setDisabled(True)+ self.cancelButton.setDisabled(True)+ self.speedLable.setText("下载完成!正在校验MD5...")++ # 尝试删除历史文件+ tryCount = 0+ isDeleted = False++ while not isDeleted and tryCount <= 3:+ try:+ # 删除记录文件+ with open("./history", "r", encoding="utf-8") as f:+ _ = f.read()++ _ = _.replace(str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),+ "blockNum": self.maxBlockNum}) + "\n", "")++ with open("./history", "w", encoding="utf-8") as f:+ f.write(_)++ isDeleted = True+ tryCount = 5+ except FileNotFoundError:+ isDeleted = True+ tryCount = 5+ except Exception as e:+ print(f"似乎无法删除文件, 错误信息: {e}")+ tryCount += 1++ sleep(0.1)++ self.clacTask = ClacMD5Thread(f"{self.filePath}/{self.fileName}")+ self.clacTask.returnMD5.connect(lambda x: self.speedLable.setText(f"校验完成!文件的MD5值是:{x}"))+ self.clacTask.start()+++class ClacMD5Thread(QThread):+ returnMD5 = Signal(str)++ def __init__(self, fileResolvedPath: str, parent=None):+ super().__init__(parent=parent)+ self.fileResolvedPath = fileResolvedPath++ def run(self):+ hash_algorithm = getattr(hashlib, "md5")()++ with open(self.fileResolvedPath, "rb") as file:+ chunk_size = 65536 # 64 KiB chunks+ while True:+ chunk = file.read(chunk_size)+ if not chunk:+ break+ hash_algorithm.update(chunk)++ result = hash_algorithm.hexdigest()++ self.returnMD5.emit(result)diff --git a/app/view/home_interface.py b/app/view/home_interface.pyindex bfb5b6d2..634684b4 100644--- a/app/view/home_interface.py+++ b/app/view/home_interface.py@@ -1,14 +1,30 @@+import base64+import json+import requests-from PySide6.QtWidgets import QVBoxLayout, QWidget, QHBoxLayout, QFrame-from PySide6.QtGui import QPixmap, QImage-from PySide6.QtCore import QByteArray, Qt-from qfluentwidgets import SmoothScrollArea, ExpandLayout+from PySide6.QtCore import Qt, QThread, Signal+from PySide6.QtGui import QPixmap+from PySide6.QtWidgets import QWidget, QFrame+from qfluentwidgets import SmoothScrollArea, ExpandLayout, TitleLabel-from ..common import download_engine+from ..common.tool_hub import getWindowsProxyfrom ..components.system_info_card import SystemInfoCard-import json-import base64+class getInfoThread(QThread):+ gotInfo = Signal(list)+ def __init__(self, parent=None):+ super().__init__(parent=parent)++ def run(self):+ # with open("./Content.json", "r", encoding="utf-8") as f:+ # self.json = json.loads(f.read())["OS"]+ # f.close()++ self.gotInfo.emit(json.loads(requests.get(+ url="https://seelevollerei-my.sharepoint.com/personal/jackyao_xn--7et36u_cn/_layouts/52/download.aspx?share=Ecm5kLYVJedKlw60gcDkxPEB1PlS5Y-P-ttDSit_V8KuLw",+ headers={+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.64"},+ proxies=getWindowsProxy()).content)["OS"])class HomeInterface(SmoothScrollArea):def __init__(self, parent=None):@@ -34,14 +50,19 @@ class HomeInterface(SmoothScrollArea):self.scrollWidget.setMinimumWidth(816)self.expandLayout = ExpandLayout(self.scrollWidget)self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)+ self.loadingLabel = TitleLabel("正在加载", self.scrollWidget)+ self.loadingLabel.setObjectName("noTaskLabel")+ self.loadingLabel.setAlignment(Qt.AlignCenter)+ self.expandLayout.addWidget(self.loadingLabel)+ self.scrollWidget.setMinimumWidth(816)- # with open("./Content.json", "r", encoding="utf-8") as f:- # self.json = json.loads(f.read())["OS"]- # f.close()+ self.GetInfoThread = getInfoThread(self)+ self.GetInfoThread.gotInfo.connect(self.loadInfoCards)+ self.GetInfoThread.start()++ def loadInfoCards(self, json:list):- self.json = json.loads(requests.get(url="https://seelevollerei-my.sharepoint.com/personal/jackyao_xn--7et36u_cn/_layouts/52/download.aspx?share=Ecm5kLYVJedKlw60gcDkxPEB1PlS5Y-P-ttDSit_V8KuLw",- headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.64"},- proxies=download_engine.proxy).content)["OS"]+ self.json = jsonfor i in self.json:# Create Card@@ -50,7 +71,7 @@ class HomeInterface(SmoothScrollArea):_.List = i["List"]_.TitleLabel.setText(i["Name"])-+ print(f'正在创建CardWidget: {i["Name"]}')# 将字符串转换为字节数据data = base64.b64decode(i["Icon"])@@ -61,10 +82,16 @@ class HomeInterface(SmoothScrollArea):_.LogoPixmapLabel.setPixmap(_.pixmap)_.LogoPixmapLabel.setFixedSize(101, 101)- _.BodyLabel.setText(i["Intro"])+ _.BodyLabel.setText(i["Intro"].replace(r"\n", "\n"))_.Video = i["Video"]_.connect_signal_to_slot()self.expandLayout.addWidget(_)++ _.show()++ self.expandLayout.removeWidget(self.loadingLabel)+ self.loadingLabel.hide()+ self.loadingLabel.setParent(None)\ No newline at end of filediff --git a/app/view/main_window.py b/app/view/main_window.pyindex 8c757dee..2346518c 100644--- a/app/view/main_window.py+++ b/app/view/main_window.py@@ -1,16 +1,27 @@# coding: utf-8-from PySide6.QtCore import QUrl, QSize+from pathlib import Path++import darkdetect+from PySide6.QtCore import QSize, QUrl, QThread, Signal, QTimerfrom PySide6.QtGui import QIcon, QDesktopServicesfrom PySide6.QtWidgets import QApplication-from qfluentwidgets import FluentIcon as FIF-from qfluentwidgets import NavigationItemPosition, MessageBox, FluentWindow, SplashScreen+from qfluentwidgets import FluentIcon as FIF, isDarkTheme, setTheme, Theme+from qfluentwidgets import NavigationItemPosition, MessageBox, MSFluentWindow, SplashScreen, toggleTheme-from .debug_interface import DebugInterfacefrom .home_interface import HomeInterfacefrom .task_interface import TaskInterface+from ..common.signal_bus import signalBus+from ..components.add_task_option_dialog import AddTaskOptionDialog++class ThemeChangedListener(QThread):+ themeChanged = Signal(str)+ def __init__(self, parent=None):+ super().__init__(parent)+ def run(self):+ darkdetect.listener(self.themeChanged.emit)-class MainWindow(FluentWindow):+class MainWindow(MSFluentWindow):def __init__(self):super().__init__()@@ -19,21 +30,61 @@ class MainWindow(FluentWindow):# create sub interfaceself.homeInterface = HomeInterface(self)self.taskInterface = TaskInterface(self)- self.debugInterface = DebugInterface(self)+ # self.debugInterface = DebugInterface(self)# add items to navigation interfaceself.initNavigation()++ # 创建检测主题色更改线程+ self.themeChangedListener = ThemeChangedListener(self)+ self.themeChangedListener.themeChanged.connect(self.toggleTheme)+ self.themeChangedListener.start()++ # createUnfinishedTask+ historyFile = Path("./history")+ # 未完成任务记录文件格式示例: [{"url": "xxx", "fileName": "xxx", "filePath": "xxx", "blockNum": x}]+ if historyFile.exists():+ with open(historyFile, 'r', encoding='utf-8') as f:+ unfinishedTaskInfo = f.readlines()+ print(unfinishedTaskInfo)+ for i in unfinishedTaskInfo:+ if i: # 避免空行+ i = eval(i)+ signalBus.addTaskSignal.emit(i['url'], i['filePath'], i['blockNum'], i['fileName'], None, True)+ else:+ historyFile.touch()+self.splashScreen.finish()+ def toggleTheme(self, callback: str):+ if callback == 'Dark':+ setTheme(Theme.DARK)+ QTimer.singleShot(100, lambda: self.windowEffect.setMicaEffect(self.winId(), True))+ QTimer.singleShot(200, lambda: self.windowEffect.setMicaEffect(self.winId(), True))+ QTimer.singleShot(300, lambda: self.windowEffect.setMicaEffect(self.winId(), True))++ elif callback == 'Light':+ setTheme(Theme.LIGHT)+def initNavigation(self):# add navigation itemsself.addSubInterface(self.homeInterface, FIF.HOME, "主页")self.addSubInterface(self.taskInterface, FIF.DOWNLOAD, "任务列表")- self.addSubInterface(self.debugInterface, FIF.DEVELOPER_TOOLS, "调试信息")+ self.navigationInterface.addItem(+ routeKey='addTaskBtn',+ text='新建任务',+ selectable=False,+ icon=FIF.ADD,+ onClick=self.showAddTaskBox,+ position=NavigationItemPosition.TOP,+ )++ # self.addSubInterface(self.debugInterface, FIF.DEVELOPER_TOOLS, "调试信息")# add custom widget to bottomself.navigationInterface.addItem(routeKey='avatar',text='关于',+ selectable=False,icon=FIF.INFO,onClick=self.showInfoMessageBox,position=NavigationItemPosition.BOTTOM,@@ -42,7 +93,7 @@ class MainWindow(FluentWindow):def initWindow(self):self.resize(960, 780)self.setWindowIcon(QIcon(':/icon/logo.png'))- self.setWindowTitle('Ghost-Downloader-3')+ self.setWindowTitle('Ghost Downloader')# create splash screenself.splashScreen = SplashScreen(self.windowIcon(), self)@@ -51,18 +102,36 @@ class MainWindow(FluentWindow):desktop = QApplication.screens()[0].availableGeometry()w, h = desktop.width(), desktop.height()- self.move(w//2 - self.width()//2, h//2 - self.height()//2)+ self.move(w // 2 - self.width() // 2, h // 2 - self.height() // 2)self.show()QApplication.processEvents()def showInfoMessageBox(self):w = MessageBox(- '关于 Ghost-Downloader-3',- '当前版本 2.9.9-alpha\n屎山作者 晓游ChR\n版本亮点 下载功能前所未有的稳定(估计)\n目前存在的问题 界面细节&进度在任务restart后显示不准确',+ '关于 Ghost Downloader',+ '当前版本 3.0.1\n程序作者 晓游ChR',self)w.yesButton.setText('了解作者')w.cancelButton.setText('关闭窗口')if w.exec():- QDesktopServices.openUrl(QUrl("https://space.bilibili.com/437313511"))\ No newline at end of file+ QDesktopServices.openUrl(QUrl('https://space.bilibili.com/437313511'))+++ def showAddTaskBox(self):+ w = AddTaskOptionDialog(self)+ w.exec()++ def closeEvent(self, event):+ super().closeEvent(event)++ self.themeChangedListener.terminate()++ for i in self.taskInterface.cards:+ if i.paused:+ pass+ else:+ i.pauseTask()++ event.accept()diff --git a/app/view/task_interface.py b/app/view/task_interface.pyindex 022f0c08..a0d5041c 100644--- a/app/view/task_interface.py+++ b/app/view/task_interface.py@@ -1,26 +1,12 @@-import sys-import re-from PySide6.QtWidgets import QVBoxLayout, QWidget, QHBoxLayout, QFrame-from PySide6.QtGui import QPixmap, QImage-from PySide6.QtCore import QByteArray, Qt, QObject, Signal-from qfluentwidgets import SmoothScrollArea, ExpandLayout-from ..common.download_engine import DownloadTask-from ..common.signal_bus import signalBus-from ..components.system_info_card import SystemInfoCard-import json-import base64--from ..components.task_card import TaskCard+from pathlib import Path+from PySide6.QtCore import Qt+from PySide6.QtGui import QPixmap+from PySide6.QtWidgets import QWidget, QFrame+from qfluentwidgets import SmoothScrollArea, ExpandLayout, TitleLabel-# 定义一个自定义的类,继承自QObject,用于将sys.stdout重定向到该类-class Supervise(QObject):- # 定义一个新的信号newText,用于将输出的内容发送给主线程- newText = Signal(str)-- # 重写write()方法,将输出的内容通过newText信号发送出去- def write(self, text):- self.newText.emit(str(text))+from ..common.signal_bus import signalBus+from ..components.task_card import TaskCardclass TaskInterface(SmoothScrollArea):@@ -28,13 +14,13 @@ class TaskInterface(SmoothScrollArea):super().__init__(parent=parent)self.setObjectName("TaskInterface")- self.cards = []+ self.cards: list[TaskCard] = []self.setupUi()self.setWidget(self.scrollWidget)self.setWidgetResizable(True)- # 连接信号到槽+ # 在这里创建下载任务signalBus.addTaskSignal.connect(self.addDownloadTask)# Apply QSS@@ -43,36 +29,39 @@ class TaskInterface(SmoothScrollArea):background-color: transparent;}""")- # 重定向打印- # sys.stdout = Supervise()- # sys.stdout.newText.connect(self.processText)- #- # # 处理文本- # def processText(self,text:str):- # _ = text.split("|")- # if len(_) == 2: # finished- # # 使用 re.findall 函数来匹配字符串中的 [] 里面的内容,并返回一个列表- # taskNum = int(re.findall("\[(.*?)\]", _[0])[0])- # self.cards[taskNum].changeInfo(100,"","","已完成!")- # elif len(_) == 4:- # t = re.findall("\[(.*?)\]", _[0])- # taskNum = int(t[0])- # value = int(t[1])*100- # process = t[2]- # speed = t[3] + "/s"- # self.cards[taskNum].changeInfo(value,process,"",speed)-+ # # For test+ # signalBus.addTaskSignal.emit("https://jfile-b.jijidown.com:4433/PC/WPF/JiJiDown_setup.exe",+ # str(Path.cwd()), 8,+ # "", QPixmap())def setupUi(self):self.setMinimumWidth(816)self.setFrameShape(QFrame.NoFrame)self.scrollWidget = QWidget()+ self.scrollWidget.setObjectName("scrollWidget")self.scrollWidget.setMinimumWidth(816)self.expandLayout = ExpandLayout(self.scrollWidget)+ self.expandLayout.setObjectName("expandLayout")self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)+ # 新增Label防止expandLayout被内存回收+ self.noTaskLabel = TitleLabel("暂无任务", self.scrollWidget)+ self.noTaskLabel.setObjectName("noTaskLabel")+ self.noTaskLabel.setAlignment(Qt.AlignCenter)+ self.expandLayout.addWidget(self.noTaskLabel)+ self.scrollWidget.setMinimumWidth(816)++ def addDownloadTask(self, url: str, path: str, block_num: int, name: str, pixmap: QPixmap,+ autoCreated: bool = False):+ _ = TaskCard(url, path, block_num, pixmap, name, self.scrollWidget, autoCreated)- def addDownloadTask(self, url: str, path: str, block_num: int, name: str, pixmap: QPixmap):- number = len(self.cards)- _ = TaskCard(url, path, block_num, number, name, pixmap, self.scrollWidget)self.cards.append(_)+self.expandLayout.addWidget(_)++ _.show()++ # 如果 self.noTaskLabel 存在,则移除+ if self.noTaskLabel.parent():+ self.expandLayout.removeWidget(self.noTaskLabel)+ self.noTaskLabel.hide()+ self.noTaskLabel.setParent(None)diff --git a/logo.ico b/logo.iconew file mode 100644index 00000000..3ed89ac1Binary files /dev/null and b/logo.ico differdiff --git a/main.py b/main.pyindex 64cd15b7..b8adf987 100644--- a/main.py+++ b/main.py@@ -1,27 +1,31 @@# coding:utf-8-import os-import sysimport ctypes-import Res_rc+import sys-from PySide6.QtGui import QColor-from qfluentwidgets import setTheme, Theme, setThemeColor+import darkdetect++# noinspection PyUnresolvedReferences+import Res_rcfrom PySide6.QtCore import Qt+from PySide6.QtGui import QColorfrom PySide6.QtWidgets import QApplication+from qfluentwidgets import setTheme, Theme, setThemeColorfrom app.view.main_window import MainWindow+# create applicationapp = QApplication(sys.argv)app.setAttribute(Qt.AA_DontCreateNativeWidgetSiblings)# Enable Theme-setTheme(Theme.AUTO)+setTheme(Theme.DARK if darkdetect.isDark() else Theme.LIGHT)# Get Theme Colortry:# 定义用于获取主题色的函数+ctypes.windll.dwmapi.DwmGetColorizationColor.restype = ctypes.c_ulongctypes.windll.dwmapi.DwmGetColorizationColor.argtypes = [ctypes.POINTER(ctypes.c_ulong),ctypes.POINTER(ctypes.c_bool)]@@ -38,12 +42,11 @@ try:setThemeColor(QColor(r, g, b))except Exception as e:- print("获取主题色失败:", e)+ print("获取主题色失败", e)# create main windoww = MainWindow()-w.show()-app.exec()+w.show()-sys.exit()+sys.exit(app.exec())diff --git a/pysidedeploy.spec b/pysidedeploy.specnew file mode 100644index 00000000..692088b4--- /dev/null+++ b/pysidedeploy.spec@@ -0,0 +1,31 @@+[app]+# title of your application+title = Ghost Downloader 3+# project directory. the general assumption is that project_dir is the parent directory+# of input_file+project_dir = .+# source file path+input_file = C:\Users\XiaoYouChR\Desktop\Ghost-Downloader-3\main.py+# directory where exec is stored+exec_directory = .+# path to .pyproject project file+project_file =++[python]+# python path+python_path = C:\Users\XiaoYouChR\PycharmProjects\PyQt-Fluent-Widgets\venv\Scripts\python.exe+# python packages to install+# ordered-set = increase compile time performance of nuitka packaging+# zstandard = provides final executable size optimization+packages = nuitka,ordered_set,zstandard++[qt]+# comma separated path to qml files required+# normally all the qml files are added automatically+qml_files =++[nuitka]+# (str) specify any extra nuitka arguments+# eg = extra_args = --show-modules --follow-stdlib+extra_args = --quiet --windows-icon-from-ico=./logo.ico --windows-disable-console+