The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
revert(download_task): 恢复对下载引擎的更改
XiaoYouChR4dfbf4e79039
diff --git a/app/common/download_task.py b/app/common/download_task.pyindex 14286b87..9996ad3a 100644--- a/app/common/download_task.py+++ b/app/common/download_task.py@@ -2,203 +2,55 @@ import asyncioimport structimport sysimport time-from abc import ABC, abstractmethodfrom asyncio import Taskfrom pathlib import Pathfrom threading import Thread-from typing import Listimport curl_cffifrom PySide6.QtCore import QThread, Signalfrom loguru import logger-from app.common.config import cfg, BASE_EFFICIENCY_THRESHOLD-from app.common.dto import SpeedInfo, SpeedRecorder+from app.common.config import cfgfrom app.common.methods import getProxy, getReadableSize, getLinkInfo, createSparseFileclass DownloadWorker:- """Worker responsible for downloading a specific range of a file"""+ """只能出卖劳动力的最底层工作者"""def __init__(self, start, progress, end, client: curl_cffi.AsyncSession):self.startPos = startself.progress = progressself.endPos = end- self.client = client-- @property- def remainingBytes(self) -> int:- """Calculate remaining bytes to download"""- return self.endPos - self.progress-- @property- def isCompleted(self) -> bool:- """Check if worker has completed its task"""- return self.progress >= self.endPos-- @property- def task(self):- if hasattr(self, '_task'):- return self._task- else:- logger.error("Task not set yet")- @task.setter- def task(self, task: asyncio.Task):- if not self.running:- self._task = task- else:- self._task.cancel()- self._task = task- logger.warning("Task is running, cancel old task before setting new one")-- @property- def running(self) -> bool:- if hasattr(self, '_task'):- return not self._task.done()- else:- return False-- def cancel(self):- if hasattr(self, '_task'):- self._task.cancel()--class WorkerStrategy(ABC):- """Base strategy for handling download workers"""-- def __init__(self, file, client: curl_cffi.AsyncSession, url: str):- self.file = fileself.client = client- self.url = url-- @abstractmethod- async def handleWorker(self, worker: DownloadWorker) -> None:- """Handle the download process for a worker"""- pass---class ParallelDownloadStrategy(WorkerStrategy):- """Strategy for parallel downloading with range requests"""-- async def handleWorker(self, worker: DownloadWorker) -> None:- """Handle parallel download for a specific worker"""- if worker.isCompleted:- worker.progress = worker.endPos- logger.warning(f"Worker {worker.startPos}-{worker.endPos} is already completed, skipping download.")- return-- while worker.progress < worker.endPos:- try:- workingRangeHeaders = self.client.headers.copy()- workingRangeHeaders["range"] = f"bytes={worker.progress}-{worker.endPos - 1}"-- async with self.client.stream("GET", self.url, headers=workingRangeHeaders,- timeout=30) as res:- res: curl_cffi.Response- res.raise_for_status()- if res.status_code != 206:- raise Exception(f"Server rejected range request, status code: {res.status_code}")-- async for chunk in res.aiter_content():- if worker.isCompleted:- break-- if chunk:- self.file.seek(worker.progress)- self.file.write(chunk)- chunkSize = len(chunk)- worker.progress += chunkSize- cfg.globalSpeed += chunkSize-- if cfg.speedLimitation.value and cfg.globalSpeed >= cfg.speedLimitation.value:- await asyncio.sleep(2)-- worker.progress = worker.endPos-- except Exception as e:- logger.info(f"Thread {worker.startPos}-{worker.endPos} is reconnecting, progress: {worker.progress}, Error: {repr(e)}")- await asyncio.sleep(5)-- worker.progress = worker.endPos---class SingleDownloadStrategy(WorkerStrategy):- """Strategy for non-parallel downloading"""-- def __init__(self, file, client: curl_cffi.AsyncSession, url: str, onComplete: callable = None):- super().__init__(file, client, url)- self.onComplete = onComplete-- async def handleWorker(self, worker: DownloadWorker) -> None:- """Handle non-parallel download for a worker"""- if worker.isCompleted:- worker.progress = worker.endPos- logger.warning(f"Worker {worker.startPos}-{worker.endPos} is already completed, skipping download.")- return-- while worker.progress < worker.endPos:- try:- workingHeaders = self.client.headers.copy()- async with self.client.stream("GET", self.url, headers=workingHeaders,- timeout=30) as res:- res.raise_for_status()-- async for chunk in res.aiter_content():- if chunk:- self.file.seek(worker.progress)- self.file.write(chunk)- chunkSize = len(chunk)- worker.progress += chunkSize- cfg.globalSpeed += chunkSize-- if cfg.speedLimitation.value and cfg.globalSpeed >= cfg.speedLimitation.value:- await asyncio.sleep(2)-- if self.onComplete:- self.onComplete()-- except Exception as e:- logger.info(f"Thread {worker.startPos}-{worker.endPos} is reconnecting, Error: {repr(e)}")- await asyncio.sleep(5)-- worker.progress = worker.endPosclass DownloadTask(QThread):- """Task Manager for downloading files with support for parallel and non-parallel downloads-- This class handles the download process, supporting both parallel downloads with resume- capability and single-threaded downloads without resume capability.-- Download modes:- - DETECT: Auto-detect file size and determine download mode (fileSize = -1)- - SINGLE: Non-parallel download, no resume capability (fileSize = 0)- - PARALLEL: Parallel download with resume capability (fileSize > 0)-- The download mode is determined based on the file size:- - If fileSize > 0, the download is performed in parallel with multiple workers- - If fileSize = 0, the download is performed with a single worker without resume capability- - If fileSize = -1, the file size is auto-detected and the mode is determined accordingly- """-- taskInited = Signal(bool) # Emitted when task is initialized, with parallel download capability flag- workerInfoChanged = Signal(list) # Emitted when worker progress changes, for segmented progress bars- speedChanged = Signal(int) # Emitted when download speed changes- taskFinished = Signal() # Emitted when task is finished- gotWrong = Signal(str) # Emitted when an error occurs-- # Download modes- MODE_DETECT = -1- MODE_SINGLE = 0- MODE_PARALLEL = 1+ """Task Manager+ self.fileSize == -1 表示自动获取; == 0 表示不能并行下载; else 表示正常"""++ taskInited = Signal(bool) # 线程初始化成功, 并传递是否支持并行下载的信息+ # processChange = Signal(str) # 目前进度 且因为C++ int最大值仅支持到2^31 PyQt又没有Qint类 故只能使用str代替+ workerInfoChanged = Signal(list) # 目前进度 v3.2版本引进了分段式进度条+ speedChanged = Signal(+ int+ ) # 平均速度 因为 autoSpeedUp 功能需要实时计算平均速度 v3.4.4 起移入后端计算速度, 每秒速度可能超过 2^31 Bytes 吗?+ taskFinished = Signal() # 内置信号的不好用+ gotWrong = Signal(str) # 😭 我出问题了def __init__(- self, url, headers, preTaskNum: int = 8,- filePath: str = None, fileName: str = None, autoSpeedUp: bool = False, fileSize: int = -1, parent=None+ self,+ url,+ headers,+ preTaskNum: int = 8,+ filePath: str = None,+ fileName: str = None,+ autoSpeedUp: bool = False,+ fileSize: int = -1,+ parent=None,):super().__init__(parent)- # Basic task propertiesself.progress = 0self.url = urlself.headers = headers@@ -207,550 +59,488 @@ class DownloadTask(QThread):self.preBlockNum = preTaskNumself.autoSpeedUp = autoSpeedUpself.fileSize = fileSize- self.downloadMode = self.MODE_DETECT # Initial mode is detect- self.isCompleted = False # Flag to track completion status-- # File handling- self.file = None- self.ghdFile = None+ self.ableToParallelDownload: bool- # Worker and task management- self.workers: List[DownloadWorker] = []- self.tasks: List[Task] = []- self.doneTask: int = 0 # Count of completed tasks- self.supervisorTask = None- self.downloadStrategy = None+ self.workers: list[DownloadWorker] = []+ self.tasks: list[Task] = []+ self.historySpeed = [0] * 10 # 历史速度 10 秒内的平均速度- # Speed tracking- self.historySpeed = [0] * 10 # Rolling window of 10 seconds for speed calculation-- # HTTP client setupproxy = getProxy()+self.client = curl_cffi.AsyncSession(- headers=headers,+ headers=headers,verify=cfg.SSLVerify.value,- proxy=proxy,+ proxy=proxy,max_clients=256,- trust_env=False,+ trust_env=False,allow_redirects=True,impersonate="chrome",- http_version="v3"+ http_version="v3",)- # Initialize task in a separate thread- self.initThread = Thread(target=self.__initTask, daemon=True)- self.initThread.start()-+ self.__initThread = Thread(+ target=self.__initTask, daemon=True+ ) # TODO 获取文件名和文件大小的线程等信息, 暂时使用线程方式+ self.__initThread.start()def __reassignWorker(self):- """Find the worker with the most remaining work and split its workload"""- # Find worker with maximum remaining bytes- workerWithMaxRemaining = None- maxRemainingBytes = 0-- for worker in self.workers:- if worker.running:- remainingBytes = worker.remainingBytes- if remainingBytes > maxRemainingBytes:- maxRemainingBytes = remainingBytes- workerWithMaxRemaining = worker- elif not worker.isCompleted:- # 总是优先运行未运行的worker- self.startWorker(worker)- return--- # Check if we should split the workload- minReassignSize = cfg.maxReassignSize.value * 1048576 # Convert to bytes- if workerWithMaxRemaining and maxRemainingBytes > minReassignSize:- # Split the workload evenly- currentProgress = workerWithMaxRemaining.progress- originalEndPos = workerWithMaxRemaining.endPos-- # Calculate split point- baseShare = maxRemainingBytes // 2- remainder = maxRemainingBytes % 2- newEndPos = currentProgress + baseShare + remainder-- # Update existing worker's endpoint- workerWithMaxRemaining.endPos = newEndPos-- # Create new worker for the second half- newStartPos = newEndPos- newWorker = DownloadWorker(newStartPos, newStartPos, originalEndPos, self.client)-- # Create task for the new worker- self.startWorker(newWorker)-- # Add new worker and task to their respective lists- insertIndex = self.workers.index(workerWithMaxRemaining) + 1- self.workers.insert(insertIndex, newWorker)++ # 找到剩余进度最多的线程+ maxRemainder = 0+ maxRemainderWorkerProcess = 0+ maxRemainderWorkerEnd = 0+ maxRemainderWorker: DownloadWorker = None++ for i in self.workers:+ if (+ i.endPos - i.progress+ ) > maxRemainder: # 其实逻辑有一点问题, 但是影响不大+ maxRemainderWorkerProcess = i.progress+ maxRemainderWorkerEnd = i.endPos+ maxRemainder = maxRemainderWorkerEnd - maxRemainderWorkerProcess+ maxRemainderWorker = i++ if (+ maxRemainderWorker and maxRemainder > cfg.maxReassignSize.value * 1048576+ ): # 转换成 MB+ # 平均分配工作量+ baseShare = maxRemainder // 2+ remainder = maxRemainder % 2++ maxRemainderWorker.endPos = (+ maxRemainderWorkerProcess + baseShare + remainder+ ) # 直接修改好像也不会怎么样++ # 安配新的工人+ startPos = maxRemainderWorkerProcess + baseShare + remainder + 1++ newWorker = DownloadWorker(+ startPos, startPos, maxRemainderWorkerEnd, self.client+ )++ newTask = self.loop.create_task(self.__handleWorker(newWorker))++ self.workers.insert(self.workers.index(maxRemainderWorker) + 1, newWorker)+ self.tasks.append(newTask)logger.info(- f"Task {self.fileName}: Split workload successfully. " +- f"Remaining: {getReadableSize(maxRemainingBytes)}, " +- f"Original worker now ends at: {newEndPos}, " +- f"New worker starts at: {newStartPos}"+ f"Task{self.fileName} 分配新线程成功, 剩余量:{getReadableSize(maxRemainder)},修改后的EndPos:{maxRemainderWorker.endPos},新线程:{newWorker},新线程的StartPos:{startPos}")+else:logger.info(- f"Task {self.fileName}: Cannot split workload. " +- f"Remaining bytes ({getReadableSize(maxRemainingBytes)}) " +- f"less than minimum split size ({getReadableSize(minReassignSize)})"+ f"Task{self.fileName} 欲分配新线程失败, 剩余量小于最小分块大小, 剩余量:{getReadableSize(maxRemainder)}")- def __calculateWorkRanges(self):- """Calculate work ranges for parallel download workers"""- # Calculate size of each block- blockSize = self.fileSize // self.preBlockNum- rangePoints = list(range(0, self.fileSize, blockSize))+ def __calcDivisionalRange(self):+ step = self.fileSize // self.preBlockNum # 每块大小+ arr = list(range(0, self.fileSize, step))- # Ensure we have the correct number of blocks+ # 否则线程数可能会不按预期地少一个if self.fileSize % self.preBlockNum == 0:- rangePoints.append(self.fileSize)+ arr.append(self.fileSize)++ stepList = []++ for i in range(len(arr) - 1): #- # Create list of start/end positions for each worker- workRanges = []- for i in range(len(rangePoints) - 1):- startPos, endPos = rangePoints[i], rangePoints[i + 1]- workRanges.append([startPos, endPos])+ startPos, endPos = arr[i], arr[i + 1] - 1+ stepList.append([startPos, endPos])- # Ensure the last range ends at the file size- if workRanges:- workRanges[-1][-1] = self.fileSize+ stepList[-1][-1] = self.fileSize - 1 # 修正- return workRanges+ return stepListdef __initTask(self):- """Initialize the download task by getting file information and preparing the file"""+ """获取链接信息并初始化线程"""try:- self.__getFileInfo()- self.__determineDownloadMode()- self.__setupFilePath()- self.__sanitizeFileName()- self.__createFileIfNeeded()-- # Signal task initialization completion- # True if parallel download is possible- self.taskInited.emit(self.downloadMode == self.MODE_PARALLEL)-- # For non-parallel downloads, use only one worker- if self.downloadMode == self.MODE_SINGLE:+ if self.fileSize == -1 or not self.fileName:+ self.url, self.fileName, self.fileSize = getLinkInfo(+ self.url, self.headers, self.fileName+ )++ if self.fileSize:+ self.ableToParallelDownload = True+ else:+ self.ableToParallelDownload = False # 处理无法并行下载的情况++ # 获取文件路径+ if not self.filePath and Path(self.filePath).is_dir() == False:+ self.filePath = Path.cwd()++ else:+ self.filePath = Path(self.filePath)+ if not self.filePath.exists():+ self.filePath.mkdir()++ # 检验文件合法性并自动重命名+ if sys.platform == "win32":+ self.fileName = "".join(+ [i for i in self.fileName if i not in r'\/:*?"<>|']+ ) # 去除Windows系统不允许的字符+ if len(self.fileName) > 255:+ self.fileName = self.fileName[:255]++ filePath = Path(f"{self.filePath}/{self.fileName}")++ if not filePath.exists():+ filePath.touch()+ try:+ createSparseFile(filePath)+ except Exception as e:+ logger.warning("创建稀疏文件失败", repr(e))++ # 任务初始化完成+ if self.ableToParallelDownload:+ self.taskInited.emit(True)+ else:+ self.taskInited.emit(False)self.preBlockNum = 1- except Exception as e:+ except Exception as e: # 重试也没用self.gotWrong.emit(repr(e))- def __getFileInfo(self):- """Get file information if needed"""- if self.fileSize == self.MODE_DETECT or not self.fileName:- self.url, self.fileName, self.fileSize = getLinkInfo(self.url, self.headers, self.fileName)+ def __loadWorkers(self):+ if not self.ableToParallelDownload:+ # 如果无法并行下载,创建一个单线程的 worker+ self.workers.append(DownloadWorker(0, 0, 1, self.client))+ return++ # 如果 .ghd 文件存在,读取并解析二进制数据+ filePath = Path(f"{self.filePath}/{self.fileName}.ghd")+ if filePath.exists():+ try:+ with open(filePath, "rb") as f:+ while True:+ data = f.read(+ 24+ ) # 每个 worker 有 3 个 64 位的无符号整数,共 24 字节++ if not data:+ break++ start, process, end = struct.unpack("<QQQ", data)+ self.workers.append(+ DownloadWorker(start, process, end, self.client)+ )- def __determineDownloadMode(self):- """Determine download mode based on file size"""- if self.fileSize > 0:- self.downloadMode = self.MODE_PARALLEL+ except Exception as e:+ logger.error(f"Failed to load workers: {e}")+ stepList = self.__calcDivisionalRange()++ for i in range(self.preBlockNum):+ self.workers.append(+ DownloadWorker(+ stepList[i][0], stepList[i][0], stepList[i][1], self.client+ )+ )else:- self.downloadMode = self.MODE_SINGLE+ stepList = self.__calcDivisionalRange()++ for i in range(self.preBlockNum):+ self.workers.append(+ DownloadWorker(+ stepList[i][0], stepList[i][0], stepList[i][1], self.client+ )+ )++ # 主下载逻辑+ async def __handleWorker(self, worker: DownloadWorker):+ logger.debug(+ f"{self.fileName} task is launching the worker {worker.startPos}-{worker.endPos}..."+ )+ if worker.progress < worker.endPos: # 因为可能会创建空线程+ finished = False+ while not finished:+ try:+ workingRangeHeaders = self.headers.copy()++ workingRangeHeaders["range"] = (+ f"bytes={worker.progress}-{worker.endPos}" # 添加范围+ )++ async with worker.client.stream(+ url=self.url,+ headers=workingRangeHeaders,+ timeout=30,+ method="GET",+ ) as res:+ res.raise_for_status()+ if res.status_code != 206:+ raise Exception(+ f"服务器拒绝了范围请求,状态码:{res.status_code}"+ )+ async for chunk in res.aiter_content():+ if worker.endPos <= worker.progress:+ break+ if chunk:+ self.file.seek(worker.progress)+ self.file.write(chunk)+ chunkSize = len(chunk)+ worker.progress += chunkSize+ cfg.globalSpeed += chunkSize+ if cfg.speedLimitation.value:+ if cfg.globalSpeed >= cfg.speedLimitation.value:+ time.sleep(1)++ if worker.progress >= worker.endPos:+ worker.progress = worker.endPos++ finished = True++ except Exception as e:+ logger.info(+ f"Task: {self.fileName}, Thread {worker} is reconnecting to the server, Error: {repr(e)}"+ )++ self.gotWrong.emit(repr(e))++ await asyncio.sleep(5)- def __setupFilePath(self):- """Setup and ensure file path exists"""- if not self.filePath or not Path(self.filePath).is_dir():- self.filePath = Path.cwd()- return+ worker.progress = worker.endPos- self.filePath = Path(self.filePath)- if not self.filePath.exists():- self.filePath.mkdir()+ async def __handleWorkerWhenUnableToParallelDownload(self, worker: DownloadWorker):+ if worker.progress < worker.endPos: # 因为可能会创建空线程+ finished = False+ while not finished:+ try:+ WorkingRangeHeaders = self.headers.copy()+ async with worker.client.stream(+ url=self.url,+ headers=WorkingRangeHeaders,+ timeout=30,+ method="GET",+ ) as res:+ res.raise_for_status()+ async for chunk in res.aiter_content():+ if chunk:+ self.file.seek(worker.progress)+ self.file.write(chunk)+ _ = len(chunk)+ worker.progress += _+ cfg.globalSpeed += _+ if cfg.speedLimitation.value:+ if cfg.globalSpeed >= cfg.speedLimitation.value:+ time.sleep(1)++ self.ableToParallelDownload = True # 事实上用来表示任务已经完成++ finished = True++ except Exception as e:+ logger.info(+ f"Task: {self.fileName}, Thread {worker} is reconnecting to the server, Error: {repr(e)}"+ )++ self.gotWrong.emit(repr(e))++ await asyncio.sleep(5)- def __sanitizeFileName(self):- """Sanitize and truncate filename if needed"""- # Sanitize filename for Windows- if sys.platform == "win32":- self.fileName = ''.join([c for c in self.fileName if c not in r'\/:*?"<>|'])+ worker.progress = worker.endPos- # Truncate filename if too long- if len(self.fileName) > 255:- self.fileName = self.fileName[:255]+ async def __supervisor(self):+ """实时统计进度并写入历史记录文件"""+ LastProgress = (+ 0 # 可能会出现unbound error,所以将LastProgress提取为函数全局变量+ )- def __createFileIfNeeded(self):- """Create the file if it doesn't exist"""- filePath = Path(f"{self.filePath}/{self.fileName}")- if filePath.exists():- return+ for i in self.workers:+ self.progress += i.progress - i.startPos + 1+ LastProgress = self.progress- filePath.touch()- try:- createSparseFile(filePath)- except Exception as e:- logger.warning(f"Failed to create sparse file: {repr(e)}")+ if self.ableToParallelDownload:+ if self.autoSpeedUp:+ # 初始化变量+ maxSpeedPerConnect = 1 # 防止除以 0+ additionalTaskNum = len(self.tasks) # 最初为计算每个线程的平均速度+ formerAvgSpeed = 0 # 提速之前的平均速度+ duringTime = 0 # 计算平均速度的时间间隔, 为 10 秒+ _ = 0- def __loadWorkers(self):- """Load or create workers for the download task"""- if self.downloadMode == self.MODE_SINGLE:- # For non-parallel downloads, create a single worker- self.workers.append(DownloadWorker(0, 0, 1, self.client))- return+ while not self.progress == self.fileSize:- # For parallel downloads, check if we have a history file (.ghd) to resume download- historyFilePath = Path(f"{self.filePath}/{self.fileName}.ghd")- if historyFilePath.exists():- self.__loadWorkersFromHistory(historyFilePath)- else:- self.__createNewWorkers()+ info = []+ # 记录每块信息+ self.ghdFile.seek(0)+ self.progress = 0- def __loadWorkersFromHistory(self, historyFilePath: Path):- """Load workers from a history file"""- try:- with open(historyFilePath, "rb") as historyFile:- while True:- # Each worker has 3 uint64 values (start, progress, end) = 24 bytes- data = historyFile.read(24)- if not data:- break+ for i in self.workers:+ info.append(+ {"start": i.startPos, "progress": i.progress, "end": i.endPos}+ )- start, progress, end = struct.unpack("<QQQ", data)- self.workers.append(DownloadWorker(start, progress, end, self.client))+ self.progress += i.progress - i.startPos + 1- except Exception as e:- logger.error(f"Failed to load workers from history: {e}")- # Fall back to creating new workers- self.__createNewWorkers()-- def __createNewWorkers(self):- """Create new workers for a fresh download"""- workRanges = self.__calculateWorkRanges()-- for i in range(self.preBlockNum):- startPos, endPos = workRanges[i][0], workRanges[i][1]- self.workers.append(DownloadWorker(startPos, startPos, endPos, self.client))-- async def __createDownloadTasks(self):- """Create download tasks for all workers using the appropriate strategy"""- logger.debug(f"Task {self.fileName}: Creating download tasks for {len(self.workers)} workers")-- # Create the appropriate download strategy based on download mode- if self.downloadMode == self.MODE_PARALLEL:- self.downloadStrategy = ParallelDownloadStrategy(self.file, self.client, self.url)-- # Create tasks for all workers- created = 0- for worker in self.workers:- if not worker.isCompleted:- self.startWorker(worker)- created += 1- if created >= self.preBlockNum:- break-- # Open history file for parallel downloads- self.ghdFile = open(f"{self.filePath}/{self.fileName}.ghd", "wb")- else:- # For non-parallel downloads, mark completion when done- def markCompleted():- self.isCompleted = True # Mark task as completed+ # 保存 workers 信息为二进制格式+ data = struct.pack("<QQQ", i.startPos, i.progress, i.endPos)+ self.ghdFile.write(data)- self.downloadStrategy = SingleDownloadStrategy(self.file, self.client, self.url, markCompleted)+ self.ghdFile.flush()+ self.ghdFile.truncate()- # Create a single task for the worker- logger.debug(f"Task {self.fileName}: Starting single thread download")- self.startWorker(self.workers[0])+ self.workerInfoChanged.emit(info)- async def __supervisor(self):- """Monitor download progress, update history file, and manage speed optimization"""- lastProgress = 0+ # 计算速度+ speed = self.progress - LastProgress+ # print(f"speed: {speed}, progress: {self.progress}, LastProgress: {LastProgress}")+ LastProgress = self.progress+ self.historySpeed.pop(0)+ self.historySpeed.append(speed)+ avgSpeed = sum(self.historySpeed) / 10- # Initialize total progress- for worker in self.workers:- self.progress += worker.progress - worker.startPos- lastProgress = self.progress+ self.speedChanged.emit(avgSpeed)- if self.downloadMode == self.MODE_PARALLEL:- await self.__runParallelSupervisor(lastProgress)- else:- await self.__runSingleSupervisor(lastProgress)-- async def __runParallelSupervisor(self, lastProgress):- """Supervisor for parallel downloads with history tracking and speed optimization"""- # Initialize smart-boost variables if enabled- if self.autoSpeedUp:-- recorder = SpeedRecorder(self.progress)- info = SpeedInfo()- formerInfo = SpeedInfo()- formerTaskNum = taskNum = 0- maxSpeedPerConnect = 1-- # Monitor until download is complete- while self.progress != self.fileSize:- # Update progress and history file- workerInfo = self.__updateProgressAndHistory() #用不到的 workerInfo-- # Calculate and emit current speed- currentSpeed = self.progress - lastProgress- lastProgress = self.progress- avgSpeed = self.__updateSpeedHistory(currentSpeed) #用不到 avgSpeed-- # Handle auto speed-up if enabled- if self.autoSpeedUp:- if taskNum != self.taskNum: #如果线程数发生变化:- formerTaskNum = taskNum- taskNum = self.taskNum- formerInfo: SpeedInfo = info- recorder.reset(self.progress)- logger.info(f'taskNum changed:{self.taskNum}')-- elif recorder.update(self.progress).time > 60: # 每60秒强制重置- recorder.reset(self.progress)-- else: # 主逻辑- info: SpeedInfo = recorder.update(self.progress)- if self.taskNum > 0:- speedPerConnect = info.speed / self.taskNum- if speedPerConnect > maxSpeedPerConnect:- maxSpeedPerConnect = speedPerConnect-- speedPerAdditionalThread = (info.speed - formerInfo.speed) / (taskNum - formerTaskNum)- threadEfficiency = speedPerAdditionalThread / maxSpeedPerConnect- # timeCompensation = 0.8 ** info.time- timeCompensation = 1/(1 + 3 ** (2 * info.time / 3 - 3)) # \frac{1}{1+3^{\left(\frac{2}{3}x-3\right)}}- adjustedEfficiencyThreshold = BASE_EFFICIENCY_THRESHOLD + timeCompensation-- if threadEfficiency >= adjustedEfficiencyThreshold and self.taskNum < 256:- logger.debug(f'自动提速增加新线程 {threadEfficiency}, {adjustedEfficiencyThreshold}')- self.__reassignWorker()- # Wait before next update- await asyncio.sleep(1)-- async def handleWorker(self, worker: DownloadWorker):- await self.downloadStrategy.handleWorker(worker)- if not self.autoSpeedUp or self.taskNum <= self.preBlockNum:# 如果开启了自动提速且添加了额外线程,则重新分配工作线程由自动提速控制- self.__reassignWorker()- self.doneTask += 1-- async def __runSingleSupervisor(self, lastProgress):- """Supervisor for non-parallel downloads"""- # Monitor until download is complete (marked by isCompleted flag)- while not self.isCompleted:- # Update total progress- self.progress = 0- for worker in self.workers:- self.progress += worker.progress - worker.startPos-- # Emit empty worker info (no segments for non-parallel downloads)- self.workerInfoChanged.emit([])-- # Calculate and emit current speed- currentSpeed = self.progress - lastProgress- lastProgress = self.progress- avgSpeed = self.__updateSpeedHistory(currentSpeed)-- # Wait before next update- await asyncio.sleep(1)-- def __updateProgressAndHistory(self):- """Update progress from all workers and write to history file"""- workerInfo = []- self.ghdFile.seek(0)- self.progress = 0+ # print(f"avgSpeed: {avgSpeed}, historySpeed: {self.historySpeed}")- # Process each worker- for worker in self.workers:- # Create info dict for UI- info = {- "start": worker.startPos,- "progress": worker.progress,- "end": worker.endPos- }- workerInfo.append(info)+ if self.autoSpeedUp:+ if duringTime < 10:+ duringTime += 1+ else:+ duringTime = 0- # Update total progress- self.progress += worker.progress - worker.startPos+ speedPerConnect = avgSpeed / len(self.tasks)+ if speedPerConnect > maxSpeedPerConnect:+ maxSpeedPerConnect = speedPerConnect+ _ = (+ 0.9 * maxSpeedPerConnect * additionalTaskNum+ ) + formerAvgSpeed++ # if maxSpeedPerConnect <= 1:+ # await asyncio.sleep(1)+ # continue++ # logger.debug(f"当前效率: {(avgSpeed - formerAvgSpeed) / additionalTaskNum / maxSpeedPerConnect}, speed: {speed}, formerAvgSpeed: {formerAvgSpeed}, additionalTaskNum: {additionalTaskNum}, maxSpeedPerConnect: {maxSpeedPerConnect}")++ # 原公式:(avgSpeed - formerAvgSpeed) / additionalTaskNum / maxSpeedPerConnect >= 0.85+ # 然后将不等号左边的计算全部移到右边+ if avgSpeed >= _:+ # 新增加线程的效率 >= 0.85 时,新增线程+ # logger.debug(f'自动提速增加新线程, 当前效率: {(avgSpeed - formerAvgSpeed) / additionalTaskNum / maxSpeedPerConnect}')+ formerAvgSpeed = avgSpeed+ additionalTaskNum = 4+ _ = (+ 0.85 * maxSpeedPerConnect * additionalTaskNum+ ) + formerAvgSpeed++ if len(self.tasks) < 253:+ for i in range(4):+ self.__reassignWorker() # 新增线程++ await asyncio.sleep(1)+ else:+ while (+ not self.ableToParallelDownload+ ): # 实际上此时 self.ableToParallelDownload 用于记录任务是否完成+ self.progress = 0- # Save worker state to history file- data = struct.pack("<QQQ", worker.startPos, worker.progress, worker.endPos)- self.ghdFile.write(data)+ for i in self.workers:+ self.progress += i.progress - i.startPos + 1- # Ensure history file is updated- self.ghdFile.flush()- self.ghdFile.truncate()+ self.workerInfoChanged.emit([])- # Emit updated worker info for UI- self.workerInfoChanged.emit(workerInfo)+ # 计算速度+ speed = self.progress - LastProgress+ LastProgress = self.progress+ self.historySpeed.pop(0)+ self.historySpeed.append(speed)+ avgSpeed = sum(self.historySpeed) / 10- return workerInfo+ self.speedChanged.emit(avgSpeed)- def __updateSpeedHistory(self, currentSpeed):- """Update speed history and calculate average speed"""- self.historySpeed.pop(0)- self.historySpeed.append(currentSpeed)- avgSpeed = sum(self.historySpeed) / 10- self.speedChanged.emit(avgSpeed)- return avgSpeed+ await asyncio.sleep(1)async def __main(self):- """Main download execution flow"""try:- # Open the download file+ # 打开下载文件self.file = open(f"{self.filePath}/{self.fileName}", "rb+")- # Create download tasks using the appropriate strategy- await self.__createDownloadTasks()+ if self.ableToParallelDownload:+ for i in self.workers: # 启动 Worker+ _ = asyncio.create_task(self.__handleWorker(i))- # Start the supervisor to monitor progress- self.supervisorTask = asyncio.create_task(self.__supervisor())+ self.tasks.append(_)++ self.ghdFile = open(f"{self.filePath}/{self.fileName}.ghd", "wb")++ else:+ logger.debug(f"Task {self.fileName}, starting single thread...")+ _ = asyncio.create_task(+ self.__handleWorkerWhenUnableToParallelDownload(self.workers[0])+ )+ self.tasks.append(_)- # Wait for the supervisor to complete+ self.supervisorTask = asyncio.create_task(self.__supervisor())+ # 仅仅需要等待 supervisorTasktry:await self.supervisorTaskexcept asyncio.CancelledError:await self.client.close()- # Clean up resources- await self.__cleanupResources()-- # Handle task completion- await self.__handleTaskCompletion()+ # 关闭+ await self.client.close()- except Exception as e:- self.gotWrong.emit(repr(e))+ self.file.close()- async def __cleanupResources(self):- """Clean up resources after download completes or is cancelled"""- # Close HTTP client- await self.client.close()+ if self.fileSize: # 事实上表示 ableToParallelDownload 为 False+ self.ghdFile.close()+ else:+ logger.info(f"Task {self.fileName} finished!")+ self.taskFinished.emit()- # Close the download file- if self.file:- self.file.close()+ if self.progress == self.fileSize:+ # 下载完成时删除历史记录文件, 防止没下载完时误删+ try:+ Path(f"{self.filePath}/{self.fileName}.ghd").unlink()- # Close history file if it exists- if self.ghdFile:- self.ghdFile.close()+ except Exception as e:+ logger.error(+ f"Failed to delete the history file, please delete it manually. Err: {e}"+ )- async def __handleTaskCompletion(self):- """Handle task completion and cleanup"""- # For non-parallel downloads that completed successfully- if self.downloadMode == self.MODE_SINGLE and self.isCompleted:- logger.info(f"Task {self.fileName} finished!")- self.taskFinished.emit()- return+ logger.info(f"Task {self.fileName} finished!")- # For parallel downloads that completed successfully- if self.downloadMode == self.MODE_PARALLEL and self.progress == self.fileSize:- # Delete history file when download is complete- try:- historyFile = Path(f"{self.filePath}/{self.fileName}.ghd")- if historyFile.exists():- historyFile.unlink()- except Exception as e:- logger.error(f"Failed to delete history file: {e}")+ self.taskFinished.emit()- logger.info(f"Task {self.fileName} finished!")- self.taskFinished.emit()+ except Exception as e:+ self.gotWrong.emit(repr(e))def stop(self):- """Stop all download tasks and clean up resources"""- # Cancel all worker tasks- self.__cancelAllTasks()+ for task in self.tasks:+ task.cancel()- # Cancel supervisor task+ # 关闭try:- if self.supervisorTask:- self.supervisorTask.cancel()+ self.supervisorTask.cancel()finally:- # Close files- self.__closeFiles()-- # Ensure all tasks are properly cancelled- self.__waitForTasksToComplete()-- def __cancelAllTasks(self):- """Cancel all worker tasks"""- for task in self.tasks:- if task and not task.done():- try:- task.cancel()- finally:- pass-- def __closeFiles(self):- """Close all open files"""- if hasattr(self, 'file') and self.file:self.file.close()-- if self.ghdFile:self.ghdFile.close()- def __waitForTasksToComplete(self):- """Wait for all tasks to complete after cancellation"""- timeout = 0- maxTimeout = 100 # 5 seconds max wait-- while not all(task.done() for task in self.tasks) and timeout < maxTimeout:- # Try to cancel any remaining tasks- self.__cancelRemainingTasks()-- # Wait a bit before checking again- time.sleep(0.05)- timeout += 1-- def __cancelRemainingTasks(self):- """Attempt to cancel any tasks that are not yet done"""- for task in self.tasks:- if task.done():- continue+ while not all(task.done() for task in self.tasks): # 等待所有任务完成+ for task in self.tasks:+ try:+ task.cancel()+ except RuntimeError:+ pass+ except Exception as e:+ raise e- try:- task.cancel()- except RuntimeError:- # RuntimeError can occur if the task is in an invalid state- pass- except Exception as e:- logger.error(f"Error cancelling task: {e}")+ time.sleep(0.05)+ # @retry(3, 0.1)def run(self):- """Main thread entry point for the download task"""- # Wait for initialization to complete- self.initThread.join()+ self.__initThread.join()- # Load or create workers+ # 加载分块self.__loadWorkers()- # Create and configure event loop- if sys.platform == "win32":- asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())-+ # 主逻辑, 使用事件循环启动异步任务self.loop = asyncio.new_event_loop()asyncio.set_event_loop(self.loop)- # Run the main download processtry:self.loop.run_until_complete(self.__main())except asyncio.CancelledError as e:- logger.debug(f"Download task cancelled: {e}")- except Exception as e:- logger.error(f"Error in download task: {e}")+ print(e)finally:- # Clean up the event loop- self.__cleanupEventLoop()-- def __cleanupEventLoop(self):- """Clean up the event loop resources"""- try:- # Close any remaining async generatorsself.loop.run_until_complete(self.loop.shutdown_asyncgens())- # Close the event loopself.loop.close()- except Exception as e:- logger.error(f"Error cleaning up event loop: {e}")-- @property- def taskNum(self) -> int:- """Get the number of active tasks"""- return len(self.tasks) - self.doneTask-- def startWorker(self, worker: DownloadWorker):- task = self.loop.create_task(self.handleWorker(worker))- worker.task = task- self.tasks.append(task)-