The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
引入分段式进度条,修改了部分变量名
XiaoYouChRfca26409202b
diff --git a/app/common/download_task.py b/app/common/download_task.pyindex 5d5dd413..318f1caf 100644--- a/app/common/download_task.py+++ b/app/common/download_task.py@@ -29,6 +29,7 @@ urlRe = re.compile(r"^" +"(?:/\\S*)?" +"$", re.IGNORECASE)+MAX_REASSIGN_SIZE = 30*1024*1024 # 30Mdef getRealUrl(url: str):try:@@ -68,8 +69,11 @@ def getRealUrl(url: str):class DownloadTask(QThread):- refreshLastProgress = Signal(str) # 用于读取历史记录后刷新进度- processChange = Signal(str) # 目前进度 且因为C++ int最大值仅支持到2^31 PyQt又没有Qint类 故只能使用str代替+ """作用相当于包工头"""++ refreshLastProgress = Signal(str) # 用于读取历史记录后刷新进度+ # processChange = Signal(str) # 目前进度 且因为C++ int最大值仅支持到2^31 PyQt又没有Qint类 故只能使用str代替+ processChange = Signal(list) # 目前进度 3.2版本引进了分段式进度条taskFinished = Signal() # 内置信号的不好用def __init__(self, url, maxBlockNum: int = 8, filePath=None, fileName=None, parent=None):@@ -122,7 +126,7 @@ class DownloadTask(QThread):# 创建空文件Path(f"{filePath}/{fileName}").touch()- self.process = 0+ self.process = []self.url = urlself.fileName = fileNameself.filePath = filePath@@ -183,24 +187,25 @@ class DownloadTask(QThread):logger.debug(f"Task {self.fileName}, starting the thread {i.id}...")i.start()-- fileResolve = Path(f"{self.filePath}/{self.fileName}")+ # fileResolve = Path(f"{self.filePath}/{self.fileName}")# 实时统计进度并写入历史记录文件- while not self.process == self.fileSize:+ while not sum(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+ f.write(str([{"id": i.id, "start": i.startPos, "process": i.process, "end": i.endPos} for i inself.workers]))f.flush()# self.process = os.path.getsize(fileResolve)- self.process = sum([i.process - i.startProcess + 1 for i in self.workers])- self.processChange.emit(str(self.process))+ # self.process = sum([i.process - i.startProcess + 1 for i in self.workers])+ # self.processChange.emit(str(self.process))++ self.process = [i.process - i.startPos + 1 for i in self.workers]+ self.processChange.emit(self.process)# print(self.process, self.fileSize)sleep(1)-# 删除历史记录文件try:Path(f"{self.filePath}/{self.fileName}.ghd").unlink()@@ -214,44 +219,57 @@ class DownloadTask(QThread):class DownloadWorker(QThread):+ """只能出卖劳动力的最底层工作者"""++ workerFinished = Signal() # 内置的信号不好用+def __init__(self, id, start, process, end, url, filePath, fileName, parent=None):super().__init__(parent)self.id = id- self.startProcess = start+ self.startPos = startself.process = process- self.end = end+ self.endPos = endself.url = urlself.filePath = filePathself.fileName = fileNamedef run(self):- finished = False- while not finished:- try:- download_headers = {"Range": f"bytes={self.process}-{self.end}",- "User-Agent": Headers["User-Agent"]}+ if self.process < self.endPos: # 因为可能会创建空线程+ finished = False+ while not finished:+ try:+ download_headers = {"Range": f"bytes={self.process}-{self.endPos}",+ "User-Agent": Headers["User-Agent"]}- res = requests.get(self.url, headers=download_headers, proxies=getWindowsProxy(), stream=True,- timeout=60)+ 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+ 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+ if self.process >= self.endPos:+ self.process = self.endPos- self.file.close()- finished = True+ try:+ self.file.close()+ except:+ pass- except Exception as e:- self.file.close()- logger.info(f"Task: {self.fileName}, Thread {self.id} is reconnecting to the server, Error: {e}")- sleep(5)+ finished = True++ except Exception as e:+ logger.info(f"Task: {self.fileName}, Thread {self.id} is reconnecting to the server, Error: {e}")+ try:+ self.file.close()+ except:+ pass- self.process = self.end+ sleep(5)+ self.process = self.endPos+ self.workerFinished.emit()diff --git a/app/components/Ui_TaskCard.py b/app/components/Ui_TaskCard.pyindex 1ab2d4d0..2e285b25 100644--- a/app/components/Ui_TaskCard.py+++ b/app/components/Ui_TaskCard.py@@ -118,11 +118,6 @@ class Ui_TaskCard(object):self.verticalLayout.addLayout(self.horizontalLayout_2)- self.ProgressBar = ProgressBar(TaskCard)- self.ProgressBar.setObjectName(u"ProgressBar")-- self.verticalLayout.addWidget(self.ProgressBar)-self.horizontalLayout_3.addLayout(self.verticalLayout)# 初始化 Icon 类diff --git a/app/components/task_card.py b/app/components/task_card.pyindex 6a2d8511..a6d90414 100644--- a/app/components/task_card.py+++ b/app/components/task_card.py@@ -11,6 +11,7 @@ from loguru import loggerfrom qfluentwidgets import CardWidgetfrom .Ui_TaskCard import Ui_TaskCard+from .task_progress_bar import TaskProgressBarfrom ..common.download_task import DownloadTaskfrom ..common.tool_hub import getWindowsProxy, getReadableSize@@ -56,6 +57,10 @@ class TaskCard(CardWidget, Ui_TaskCard):self.status = status # working paused finished canceled# self.number = number+ self.progressBar = TaskProgressBar(maxBlockNum, self)+ self.progressBar.setObjectName(u"progressBar")++ self.verticalLayout.addWidget(self.progressBar)def _(progress: str): # 用于赋值self.lastProcess = int(progress)@@ -151,6 +156,7 @@ class TaskCard(CardWidget, Ui_TaskCard):self.task = DownloadTask(self.url, self.maxBlockNum, self.filePath, self.fileName)self.task.start()self.task.processChange.connect(self.__changeInfo)+ self.task.taskFinished.connect(self.taskFinished)# 改变记录状态with open("./Ghost Downloader 记录文件", "r", encoding="utf-8") as f:@@ -213,15 +219,20 @@ class TaskCard(CardWidget, Ui_TaskCard):self.hide()- def __changeInfo(self, content: str):+ def __changeInfo(self, content: list):- process = int(content)+ # process = int(content)+ process = sum(content)duringLastSecondProcess = process - self.lastProcessself.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.ProgressBar.setValue((process / self.task.fileSize) * 100)++ for e, i in enumerate(content):+ self.progressBar.changeValue(e, (i / (self.task.workers[e].endPos - self.task.workers[e].startPos) ) * 100)+self.lastProcess = processdiff --git a/app/components/task_progress_bar.py b/app/components/task_progress_bar.pynew file mode 100644index 00000000..fcf4c569--- /dev/null+++ b/app/components/task_progress_bar.py@@ -0,0 +1,23 @@+from PySide6.QtWidgets import QWidget, QHBoxLayout+from qfluentwidgets import ProgressBar++class TaskProgressBar(QWidget):+ def __init__(self, blockNum: int, parent=None):+ super().__init__(parent)++ self.blockNum = blockNum+ self.progressBarList = []++ # Setup UI+ self.HBoxLayout = QHBoxLayout(self)+ self.HBoxLayout.setContentsMargins(0, 0, 0, 0)+ self.HBoxLayout.setSpacing(0)+ self.setLayout(self.HBoxLayout)++ for i in range(self.blockNum):+ _ = ProgressBar(self)+ self.HBoxLayout.addWidget(_)+ self.progressBarList.append(_)++ def changeValue(self, index: int, value: int):+ self.progressBarList[index].setValue(value)