The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
refactor(download_task): 重构下载任务处理逻辑
XiaoYouChR01c4aa322663
diff --git a/app/common/download_task.py b/app/common/download_task.pyindex d466f02f..5d207ff8 100644--- a/app/common/download_task.py+++ b/app/common/download_task.py@@ -2,9 +2,11 @@ import asyncioimport structimport sysimport time+from abc import ABC, abstractmethodfrom asyncio import Taskfrom pathlib import Pathfrom threading import Thread+from typing import Listimport httpxfrom PySide6.QtCore import QThread, Signal@@ -15,26 +17,152 @@ from app.common.methods import getProxy, getReadableSize, getLinkInfo, createSpaclass DownloadWorker:- """只能出卖劳动力的最底层工作者"""+ """Worker responsible for downloading a specific range of a file"""def __init__(self, start, progress, end, client: httpx.AsyncClient):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++class WorkerStrategy(ABC):+ """Base strategy for handling download workers"""++ def __init__(self, file, client: httpx.AsyncClient, 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++ finished = False+ while not finished:+ try:+ workingRangeHeaders = self.client.headers.copy()+ workingRangeHeaders["range"] = f"bytes={worker.progress}-{worker.endPos - 1}"++ async with self.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"Server rejected range request, status code: {res.status_code}")++ async for chunk in res.aiter_bytes(chunk_size=65536):+ if worker.isCompleted:+ break++ if chunk:+ self.file.seek(worker.progress)+ self.file.write(chunk)+ worker.progress += 65536+ cfg.globalSpeed += 65536++ if cfg.speedLimitation.value and cfg.globalSpeed >= cfg.speedLimitation.value:+ time.sleep(1)++ worker.progress = worker.endPos+ finished = True++ except Exception as e:+ logger.info(f"Thread {worker.startPos}-{worker.endPos} is reconnecting, Error: {repr(e)}")+ await asyncio.sleep(5)++ worker.progress = worker.endPos+++class SingleDownloadStrategy(WorkerStrategy):+ """Strategy for non-parallel downloading"""++ def __init__(self, file, client: httpx.AsyncClient, 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++ finished = False+ while not finished:+ try:+ workingHeaders = self.client.headers.copy()+ async with self.client.stream(url=self.url, headers=workingHeaders,+ timeout=30, method="GET") as res:+ res.raise_for_status()++ async for chunk in res.aiter_bytes():+ 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:+ time.sleep(1)++ if self.onComplete:+ self.onComplete()++ finished = True++ 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- self.fileSize == -1 表示自动获取; == 0 表示不能并行下载; else 表示正常"""+ """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) # 线程初始化成功, 并传递是否支持并行下载的信息- # 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) # 😭 我出问题了+ 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 = 1def __init__(self, url, headers, preTaskNum: int = 8,@@ -42,6 +170,7 @@ class DownloadTask(QThread):):super().__init__(parent)+ # Basic task propertiesself.progress = 0self.url = urlself.headers = headers@@ -50,431 +179,539 @@ class DownloadTask(QThread):self.preBlockNum = preTaskNumself.autoSpeedUp = autoSpeedUpself.fileSize = fileSize- self.ableToParallelDownload: bool-- self.ghdFile = None # 提前初始化,避免因为不能并行下载时访问属性报错-- self.workers: list[DownloadWorker] = []- self.tasks: list[Task] = []- self.historySpeed = [0] * 10 # 历史速度 10 秒内的平均速度-- _ = getProxy()-- self.client = httpx.AsyncClient(headers=headers, verify=cfg.SSLVerify.value,- proxy=_, limits=httpx.Limits(max_connections=256), trust_env=False, follow_redirects=True)-- self.__initThread = Thread(target=self.__initTask, daemon=True) # TODO 获取文件名和文件大小的线程等信息, 暂时使用线程方式- self.__initThread.start()+ 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++ # Worker and task management+ self.workers: List[DownloadWorker] = []+ self.tasks: List[Task] = []+ self.supervisorTask = None+ self.downloadStrategy = None++ # Speed tracking+ self.historySpeed = [0] * 10 # Rolling window of 10 seconds for speed calculation++ # HTTP client setup+ proxy = getProxy()+ self.client = httpx.AsyncClient(+ headers=headers,+ verify=cfg.SSLVerify.value,+ proxy=proxy,+ limits=httpx.Limits(max_connections=256),+ trust_env=False,+ follow_redirects=True+ )++ # Initialize task in a separate thread+ self.initThread = Thread(target=self.__initTask, daemon=True)+ self.initThread.start()def __reassignWorker(self):-- # 找到剩余进度最多的线程- 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-- newWorker = DownloadWorker(startPos, startPos, maxRemainderWorkerEnd, self.client)-- newTask = self.loop.create_task(self.__handleWorker(newWorker))-- self.workers.insert(self.workers.index(maxRemainderWorker) + 1, newWorker)+ """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:+ remainingBytes = worker.remainingBytes+ if remainingBytes > maxRemainingBytes:+ maxRemainingBytes = remainingBytes+ workerWithMaxRemaining = worker++ # 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+ newTask = self.loop.create_task(self.downloadStrategy.handleWorker(newWorker))++ # Add new worker and task to their respective lists+ insertIndex = self.workers.index(workerWithMaxRemaining) + 1+ self.workers.insert(insertIndex, newWorker)self.tasks.append(newTask)logger.info(- f"Task{self.fileName} 分配新线程成功, 剩余量:{getReadableSize(maxRemainder)},修改后的EndPos:{maxRemainderWorker.endPos},新线程:{newWorker},新线程的StartPos:{startPos}")-+ f"Task {self.fileName}: Split workload successfully. " ++ f"Remaining: {getReadableSize(maxRemainingBytes)}, " ++ f"Original worker now ends at: {newEndPos}, " ++ f"New worker starts at: {newStartPos}"+ )else:logger.info(- f"Task{self.fileName} 欲分配新线程失败, 剩余量小于最小分块大小, 剩余量:{getReadableSize(maxRemainder)}")-- def __calcDivisionalRange(self):- step = self.fileSize // self.preBlockNum # 每块大小- arr = list(range(0, self.fileSize, step))-- # 否则线程数可能会不按预期地少一个+ f"Task {self.fileName}: Cannot split workload. " ++ f"Remaining bytes ({getReadableSize(maxRemainingBytes)}) " ++ f"less than minimum split size ({getReadableSize(minReassignSize)})"+ )++ 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))++ # Ensure we have the correct number of blocksif self.fileSize % self.preBlockNum == 0:- arr.append(self.fileSize)-- stepList = []+ rangePoints.append(self.fileSize)- 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]- 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 # 修正-- return stepList+ return workRangesdef __initTask(self):- """获取链接信息并初始化线程"""+ """Initialize the download task by getting file information and preparing the file"""try:- 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.__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:self.preBlockNum = 1- except Exception as e: # 重试也没用+ except Exception as e:self.gotWrong.emit(repr(e))- def __loadWorkers(self):- if not self.ableToParallelDownload:- # 如果无法并行下载,创建一个单线程的 worker- self.workers.append(DownloadWorker(0, 0, 1, self.client))- return+ 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)- # 如果 .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 字节+ def __determineDownloadMode(self):+ """Determine download mode based on file size"""+ if self.fileSize > 0:+ self.downloadMode = self.MODE_PARALLEL+ else:+ self.downloadMode = self.MODE_SINGLE- if not data:- break+ 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- start, process, end = struct.unpack("<QQQ", data)- self.workers.append(- DownloadWorker(start, process, end, self.client))+ self.filePath = Path(self.filePath)+ if not self.filePath.exists():+ self.filePath.mkdir()- except Exception as e:- logger.error(f"Failed to load workers: {e}")- stepList = self.__calcDivisionalRange()+ 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'\/:*?"<>|'])- for i in range(self.preBlockNum):- self.workers.append(- DownloadWorker(stepList[i][0], stepList[i][0], stepList[i][1], self.client))- else:- 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 - 1}" # 添加范围-- 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_bytes(chunk_size=65536):- if worker.endPos <= worker.progress:- break- if chunk:- self.file.seek(worker.progress)- self.file.write(chunk)- worker.progress += 65536- cfg.globalSpeed += 65536- 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)+ # Truncate filename if too long+ if len(self.fileName) > 255:+ self.fileName = self.fileName[:255]- worker.progress = worker.endPos+ def __createFileIfNeeded(self):+ """Create the file if it doesn't exist"""+ filePath = Path(f"{self.filePath}/{self.fileName}")+ if filePath.exists():+ return- 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_bytes():- 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:- await asyncio.sleep(1) # 在锁里面睡,只阻塞 worker, 不阻塞 supervisor-- 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)+ filePath.touch()+ try:+ createSparseFile(filePath)+ except Exception as e:+ logger.warning(f"Failed to create sparse file: {repr(e)}")- worker.progress = worker.endPos+ 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- async def __supervisor(self):- """实时统计进度并写入历史记录文件"""- LastProgress = 0 # 可能会出现unbound error,所以将LastProgress提取为函数全局变量+ # 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()- for i in self.workers:- self.progress += i.progress - i.startPos- LastProgress = self.progress+ 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- if self.ableToParallelDownload:- if self.autoSpeedUp:- # 初始化变量- maxSpeedPerConnect = 1 # 防止除以0- additionalTaskNum = len(self.tasks) # 最初为计算每个线程的平均速度- formerAvgSpeed = 0 # 提速之前的平均速度- duringTime = 0 # 计算平均速度的时间间隔, 为 10 秒- _ = 0+ start, progress, end = struct.unpack("<QQQ", data)+ self.workers.append(DownloadWorker(start, progress, end, self.client))- while not self.progress == self.fileSize:+ except Exception as e:+ logger.error(f"Failed to load workers from history: {e}")+ # Fall back to creating new workers+ self.__createNewWorkers()- info = []- # 记录每块信息- self.ghdFile.seek(0)- self.progress = 0+ def __createNewWorkers(self):+ """Create new workers for a fresh download"""+ workRanges = self.__calculateWorkRanges()- for i in self.workers:- info.append({"start": i.startPos, "progress": i.progress, "end": i.endPos})+ for i in range(self.preBlockNum):+ startPos, endPos = workRanges[i][0], workRanges[i][1]+ self.workers.append(DownloadWorker(startPos, startPos, endPos, self.client))- self.progress += i.progress - i.startPos+ 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")- # 保存 workers 信息为二进制格式- data = struct.pack("<QQQ", i.startPos, i.progress, i.endPos)- self.ghdFile.write(data)+ # Create the appropriate download strategy based on download mode+ if self.downloadMode == self.MODE_PARALLEL:+ self.downloadStrategy = ParallelDownloadStrategy(self.file, self.client, self.url)- self.ghdFile.flush()- self.ghdFile.truncate()+ # Create tasks for all workers+ for worker in self.workers:+ task = asyncio.create_task(self.downloadStrategy.handleWorker(worker))+ self.tasks.append(task)- self.workerInfoChanged.emit(info)+ # 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- # 计算速度- 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+ self.downloadStrategy = SingleDownloadStrategy(self.file, self.client, self.url, markCompleted)- self.speedChanged.emit(avgSpeed)+ # Create a single task for the worker+ logger.debug(f"Task {self.fileName}: Starting single thread download")+ task = asyncio.create_task(self.downloadStrategy.handleWorker(self.workers[0]))+ self.tasks.append(task)- # print(f"avgSpeed: {avgSpeed}, historySpeed: {self.historySpeed}")+ async def __supervisor(self):+ """Monitor download progress, update history file, and manage speed optimization"""+ lastProgress = 0- if self.autoSpeedUp:- if duringTime < 10:- duringTime += 1- else:- duringTime = 0+ # Initialize total progress+ for worker in self.workers:+ self.progress += worker.progress - worker.startPos+ lastProgress = self.progress- speedPerConnect = avgSpeed / len(self.tasks)- if speedPerConnect > maxSpeedPerConnect:- maxSpeedPerConnect = speedPerConnect- _ = (0.85 * maxSpeedPerConnect * additionalTaskNum) + formerAvgSpeed+ 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 auto speed-up variables if enabled+ speedUpVars = None+ if self.autoSpeedUp:+ speedUpVars = {+ 'maxSpeedPerConnect': 1, # Prevent division by zero+ 'additionalTaskNum': len(self.tasks), # For calculating average speed per thread+ 'formerAvgSpeed': 0, # Speed before optimization+ 'duringTime': 0, # Time interval for speed calculation (10 seconds)+ 'targetSpeed': 0 # Target speed for optimization+ }++ # Monitor until download is complete+ while self.progress != self.fileSize:+ # Update progress and history file+ workerInfo = self.__updateProgressAndHistory()++ # Calculate and emit current speed+ currentSpeed = self.progress - lastProgress+ lastProgress = self.progress+ avgSpeed = self.__updateSpeedHistory(currentSpeed)++ # Handle auto speed-up if enabled+ if self.autoSpeedUp:+ self.__handleAutoSpeedUp(avgSpeed, speedUpVars)++ # Wait before next update+ await asyncio.sleep(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- # if maxSpeedPerConnect <= 1:- # await asyncio.sleep(1)- # continue+ # 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)++ # Update total progress+ self.progress += worker.progress - worker.startPos++ # Save worker state to history file+ data = struct.pack("<QQQ", worker.startPos, worker.progress, worker.endPos)+ self.ghdFile.write(data)++ # Ensure history file is updated+ self.ghdFile.flush()+ self.ghdFile.truncate()++ # Emit updated worker info for UI+ self.workerInfoChanged.emit(workerInfo)++ return workerInfo++ 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++ def __handleAutoSpeedUp(self, avgSpeed, vars):+ """Handle auto speed-up logic to optimize download speed"""+ # Update time counter and return if not ready for optimization+ if vars['duringTime'] < 10:+ vars['duringTime'] += 1+ return- # logger.debug(f"当前效率: {(avgSpeed - formerAvgSpeed) / additionalTaskNum / maxSpeedPerConnect}, speed: {speed}, formerAvgSpeed: {formerAvgSpeed}, additionalTaskNum: {additionalTaskNum}, maxSpeedPerConnect: {maxSpeedPerConnect}")+ # Reset counter for next interval+ vars['duringTime'] = 0- # 原公式:(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+ # Calculate speed per connection+ speedPerConnect = avgSpeed / len(self.tasks) if self.tasks else 1- if len(self.tasks) < 253:- for i in range(4):- self.__reassignWorker() # 新增线程+ # Update max speed per connection if current is higher+ self.__updateMaxSpeedPerConnect(speedPerConnect, vars)- await asyncio.sleep(1)- else:- while not self.ableToParallelDownload: # 实际上此时 self.ableToParallelDownload 用于记录任务是否完成- self.progress = 0+ # Check if we should add more workers based on efficiency+ if avgSpeed < vars['targetSpeed']:+ return # Current efficiency is not good enough- for i in self.workers:- self.progress += i.progress - i.startPos+ # Current efficiency is good, prepare for adding more workers+ self.__prepareForMoreWorkers(avgSpeed, vars)- self.workerInfoChanged.emit([])+ # Add more workers if we haven't reached the limit+ if len(self.tasks) < 253:+ self.__addMoreWorkers(4)- # 计算速度- speed = (self.progress - LastProgress)- LastProgress = self.progress- self.historySpeed.pop(0)- self.historySpeed.append(speed)- avgSpeed = sum(self.historySpeed) / 10+ def __updateMaxSpeedPerConnect(self, speedPerConnect, vars):+ """Update maximum speed per connection if current is higher"""+ if speedPerConnect <= vars['maxSpeedPerConnect']:+ return++ vars['maxSpeedPerConnect'] = speedPerConnect+ vars['targetSpeed'] = (0.85 * vars['maxSpeedPerConnect'] * vars['additionalTaskNum']) + vars['formerAvgSpeed']- self.speedChanged.emit(avgSpeed)+ def __prepareForMoreWorkers(self, avgSpeed, vars):+ """Prepare variables for adding more workers"""+ vars['formerAvgSpeed'] = avgSpeed+ vars['additionalTaskNum'] = 4+ vars['targetSpeed'] = (0.85 * vars['maxSpeedPerConnect'] * vars['additionalTaskNum']) + vars['formerAvgSpeed']- await asyncio.sleep(1)+ def __addMoreWorkers(self, count):+ """Add more workers to improve download speed"""+ for _ in range(count):+ self.__reassignWorker()async def __main(self):+ """Main download execution flow"""try:- # 打开下载文件+ # Open the download fileself.file = open(f"{self.filePath}/{self.fileName}", "rb+")- if self.ableToParallelDownload:- for i in self.workers: # 启动 Worker- _ = asyncio.create_task(self.__handleWorker(i))-- 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(_)-- print(self.tasks)+ # Create download tasks using the appropriate strategy+ await self.__createDownloadTasks()+ # Start the supervisor to monitor progressself.supervisorTask = asyncio.create_task(self.__supervisor())- # 仅仅需要等待 supervisorTask++ # Wait for the supervisor to completetry:await self.supervisorTaskexcept asyncio.CancelledError:await self.client.aclose()- # 关闭- await self.client.aclose()+ # Clean up resources+ await self.__cleanupResources()- self.file.close()+ # Handle task completion+ await self.__handleTaskCompletion()- if self.fileSize: # 事实上表示 ableToParallelDownload 为 False- self.ghdFile.close()- else:- logger.info(f"Task {self.fileName} finished!")- self.taskFinished.emit()+ except Exception as e:+ self.gotWrong.emit(repr(e))- if self.progress == self.fileSize:- # 下载完成时删除历史记录文件, 防止没下载完时误删- try:- Path(f"{self.filePath}/{self.fileName}.ghd").unlink()+ async def __cleanupResources(self):+ """Clean up resources after download completes or is cancelled"""+ # Close HTTP client+ await self.client.aclose()- except Exception as e:- logger.error(f"Failed to delete the history file, please delete it manually. Err: {e}")+ # Close the download file+ if self.file:+ self.file.close()- logger.info(f"Task {self.fileName} finished!")+ # Close history file if it exists+ if self.ghdFile:+ self.ghdFile.close()- self.taskFinished.emit()+ 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- except Exception as e:- self.gotWrong.emit(repr(e))+ # 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}")++ logger.info(f"Task {self.fileName} finished!")+ self.taskFinished.emit()def stop(self):- for task in self.tasks:- task.cancel()+ """Stop all download tasks and clean up resources"""+ # Cancel all worker tasks+ self.__cancelAllTasks()- # 关闭+ # Cancel supervisor tasktry:- self.supervisorTask.cancel()+ if self.supervisorTask:+ 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():+ task.cancel()++ def __closeFiles(self):+ """Close all open files"""+ if hasattr(self, 'file') and self.file:self.file.close()- if self.ghdFile:- self.ghdFile.close()- 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+ 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- time.sleep(0.05)+ 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++ 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}")- # @retry(3, 0.1)def run(self):- self.__initThread.join()+ """Main thread entry point for the download task"""+ # Wait for initialization to complete+ self.initThread.join()- # 加载分块+ # Load or create workersself.__loadWorkers()-- print(self.tasks, self.workers)-- # 主逻辑, 使用事件循环启动异步任务++ # Create and configure event loopself.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:- print(e)+ logger.debug(f"Download task cancelled: {e}")+ except Exception as e:+ logger.error(f"Error in download task: {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}")