The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
修复新增任务时不写入记录文件的bug;将平均速度的计算位置从 task_card.py 移动到 download_task.py;用平均速度作为自动提速的计算标准并把自动提速的增加线程数提高到4, 提高自动提速的精准性。
XiaoYouChRda65e00490bb
diff --git a/app/common/download_task.py b/app/common/download_task.pyindex f34f1524..4dd0319c 100644--- a/app/common/download_task.py+++ b/app/common/download_task.py@@ -40,7 +40,8 @@ class DownloadTask(QThread):taskInited = Signal() # 线程初始化成功# processChange = Signal(str) # 目前进度 且因为C++ int最大值仅支持到2^31 PyQt又没有Qint类 故只能使用str代替- workerInfoChange = Signal(list) # 目前进度 v3.2版本引进了分段式进度条+ workerInfoChanged = Signal(list) # 目前进度 v3.2版本引进了分段式进度条+ speedChanged = Signal(int) # 平均速度 因为 autoSpeedUp 功能需要实时计算平均速度 v3.4.4 起移入后端计算速度, 每秒速度可能超过 2^31 Bytes 吗?taskFinished = Signal() # 内置信号的不好用gotWrong = Signal(str) # 😭 我出问题了@@ -53,8 +54,10 @@ class DownloadTask(QThread):self.filePath = filePathself.preBlockNum = preTaskNumself.autoSpeedUp = autoSpeedUp+self.workers: list[DownloadWorker] = []self.tasks: list[Task] = []+ self.historySpeed = [0] * 10 # 历史速度 10 秒内的平均速度self.client = httpx.AsyncClient(headers=Headers, verify=False,proxy=getProxy(), limits=httpx.Limits(max_connections=256))@@ -208,17 +211,20 @@ class DownloadTask(QThread):async def __supervisor(self):"""实时统计进度并写入历史记录文件"""+ for i in self.workers:+ self.process += (i.process - i.startPos + 1)+ LastProcess = self.process+if self.autoSpeedUp:# 初始化变量- for i in self.workers:- self.process += (i.process - i.startPos + 1) # 最初为计算每个线程的平均速度- LastProcess = self.process- maxSpeedPerConnect = 1 # 防止除以0- newTaskNum = len(self.tasks)- formerSpeed = 0+ maxSpeedPerConnect = 1 # 防止除以0+ additionalTaskNum = len(self.tasks) # 最初为计算每个线程的平均速度+ formerAvgSpeed = 0 # 提速之前的平均速度+ duringTime = 0 # 计算平均速度的时间间隔, 为 10 秒while not self.process == self.fileSize:+ # 记录每块信息self.ghdFile.seek(0)info = []self.process = 0@@ -235,35 +241,47 @@ class DownloadTask(QThread):self.ghdFile.flush()self.ghdFile.truncate()- self.workerInfoChange.emit(info)+ self.workerInfoChanged.emit(info)++ # 计算速度+ speed = (self.process - LastProcess)+ print(f"speed: {speed}, process: {self.process}, LastProcess: {LastProcess}")+ LastProcess = self.process+ self.historySpeed.pop(0)+ self.historySpeed.append(speed)+ avgSpeed = sum(self.historySpeed) / 10++ self.speedChanged.emit(avgSpeed)++ # print(f"avgSpeed: {avgSpeed}, historySpeed: {self.historySpeed}")if self.autoSpeedUp:- speed = (self.process - LastProcess) / 1- LastProcess = self.process- speedPerConnect = formerSpeed / len(self.tasks)-- if speedPerConnect > maxSpeedPerConnect:- maxSpeedPerConnect = speedPerConnect+ if duringTime < 10:+ duringTime += 1+ else:+ duringTime = 0++ speedPerConnect = avgSpeed / len(self.tasks)+ # print(f"taskNum: {len(self.tasks)}, speedPerConnect: {speedPerConnect}, maxSpeedPerConnect: {maxSpeedPerConnect}")- if maxSpeedPerConnect <= 1:- await asyncio.sleep(1)- continue+ if speedPerConnect > maxSpeedPerConnect:+ maxSpeedPerConnect = speedPerConnect- if formerSpeed == 0:- formerSpeed = speed- await asyncio.sleep(1)- continue+ # if maxSpeedPerConnect <= 1:+ # await asyncio.sleep(1)+ # continue- #print(f'{self.taskNum}\t{(speed - formerSpeed) / newTaskNum}\t{maxSpeedPerConnect}\t{(speed - formerSpeed) / newTaskNum / maxSpeedPerConnect}')+ # logger.debug(f"当前效率: {(avgSpeed - formerAvgSpeed) / additionalTaskNum / maxSpeedPerConnect}, speed: {speed}, formerAvgSpeed: {formerAvgSpeed}, additionalTaskNum: {additionalTaskNum}, maxSpeedPerConnect: {maxSpeedPerConnect}")- if (speed - formerSpeed) / newTaskNum / maxSpeedPerConnect >= 0.85:- # 新增加线程的效率 >= 0.9 时,新增线程- logger.debug(f'自动提速增加新线程 {(speed - formerSpeed) / newTaskNum / maxSpeedPerConnect}')- formerSpeed = speed- newTaskNum = 1+ if (avgSpeed - formerAvgSpeed) / additionalTaskNum / maxSpeedPerConnect >= 0.85:+ # 新增加线程的效率 >= 0.85 时,新增线程+ # logger.debug(f'自动提速增加新线程, 当前效率: {(avgSpeed - formerAvgSpeed) / additionalTaskNum / maxSpeedPerConnect}')+ formerAvgSpeed = avgSpeed+ additionalTaskNum = 4- if len(self.tasks) < 256:- self.__reassignWorker() # 新增线程+ if len(self.tasks) < 253:+ for i in range(4):+ self.__reassignWorker() # 新增线程await asyncio.sleep(1)@@ -286,7 +304,7 @@ class DownloadTask(QThread):# 仅仅需要等待 supervisorTasktry:- await self.supervisorTask # supervisorTask 被 cancel 后,会抛出 CancelledError, 所以之后的代码不会执行+ await self.supervisorTaskexcept asyncio.CancelledError:await self.client.aclose()@@ -297,7 +315,7 @@ class DownloadTask(QThread):self.ghdFile.close()if self.process == self.fileSize:- # 删除历史记录文件+ # 下载完成时删除历史记录文件, 防止没下载完时误删try:Path(f"{self.filePath}/{self.fileName}.ghd").unlink()diff --git a/app/components/task_card.py b/app/components/task_card.pyindex 2c413cfd..316661be 100644--- a/app/components/task_card.py+++ b/app/components/task_card.py@@ -33,8 +33,7 @@ class TaskCard(CardWidget, Ui_TaskCard):self.filePath = pathself.maxBlockNum = maxBlockNumself.status = status # working paused finished canceled- self.lastProcess = 0- self.autoCreated = autoCreated+ self.autoCreated = autoCreated # 事实上用来记录历史文件是否已经创建# Show Information@@ -48,7 +47,6 @@ class TaskCard(CardWidget, Ui_TaskCard):self.progressBar.setObjectName(u"progressBar")self.verticalLayout.addWidget(self.progressBar)- self.historySpeed = [0] * 10if name:self.fileName = name@@ -62,13 +60,6 @@ class TaskCard(CardWidget, Ui_TaskCard):self.__onTaskInited()- # 写入未完成任务记录文件,以供下次打开时继续下载- if not self.autoCreated:- with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "a", encoding="utf-8") as f:- _ = {"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),- "blockNum": self.maxBlockNum, "status": self.status}- f.write(str(_) + "\n")-if self.status == "paused":self.__showInfo("任务已经暂停")@@ -109,6 +100,15 @@ class TaskCard(CardWidget, Ui_TaskCard):def __onTaskInited(self):self.fileName = self.task.fileName+ # 写入未完成任务记录文件,以供下次打开时继续下载+ if self.fileName and not self.autoCreated:+ with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "a", encoding="utf-8") as f:+ _ = {"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),+ "blockNum": self.maxBlockNum, "status": self.status}+ f.write(str(_) + "\n")++ self.autoCreated = True+# TODO 因为Windows会返回已经处理过的只有左上角一点点的图像,所以需要超分辨率触发条件# _ = QFileIconProvider().icon(QFileInfo(f"{self.filePath}/{self.fileName}")).pixmap(48, 48).scaled(91, 91, aspectMode=Qt.AspectRatioMode.KeepAspectRatio,# mode=Qt.TransformationMode.SmoothTransformation) # 自动获取图标@@ -259,42 +259,32 @@ class TaskCard(CardWidget, Ui_TaskCard):self.leftTimeLabel.show()self.processLabel.show()- def __changeStatus(self, content: list):+ def __updateProcess(self, content: list):# 理论来说 worker 直增不减 所以ProgressBar不用考虑线程减少的问题_ = len(content) - self.progressBar.blockNumif _:self.progressBar.addProgressBar(content, _)- process = 0-for e, i in enumerate(content):- process += i["process"] - i["start"]self.progressBar.progressBarList[e].setValue( ( (i["process"] - i["start"]) / (i["end"] - i["start"]) ) * 100)- duringLastSecondProcess = process - self.lastProcess-- self.historySpeed.pop(0)- self.historySpeed.append(duringLastSecondProcess)- avgSpeed = sum(self.historySpeed) / len(self.historySpeed)-# 如果还在显示消息状态,则调用 __hideInfoif self.infoLabel.isVisible():self.__hideInfo()- self.speedLabel.setText(f"{getReadableSize(avgSpeed)}/s")- self.processLabel.setText(f"{getReadableSize(process)}/{getReadableSize(self.task.fileSize)}")+ self.processLabel.setText(f"{getReadableSize(self.task.process)}/{getReadableSize(self.task.fileSize)}")++ def __UpdateSpeed(self, avgSpeed: int):-+ self.speedLabel.setText(f"{getReadableSize(avgSpeed)}/s")# 计算剩余时间,并转换为 MM:SStry:- leftTime = (self.task.fileSize - process) / avgSpeed+ leftTime = (self.task.fileSize - self.task.process) / avgSpeedself.leftTimeLabel.setText(f"{int(leftTime // 60):02d}:{int(leftTime % 60):02d}")except ZeroDivisionError:self.leftTimeLabel.setText("Infinity")- self.lastProcess = process-def __onTaskFinished(self):self.pauseButton.setDisabled(True)self.cancelButton.setDisabled(True)@@ -346,7 +336,8 @@ class TaskCard(CardWidget, Ui_TaskCard):def __connectSignalToSlot(self):self.task.taskInited.connect(self.__onTaskInited)- self.task.workerInfoChange.connect(self.__changeStatus)+ self.task.workerInfoChanged.connect(self.__updateProcess)+ self.task.speedChanged.connect(self.__UpdateSpeed)self.task.taskFinished.connect(self.__onTaskFinished)self.task.taskFinished.connect(self.taskFinished)