The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
现在对话框支持自动跟随系统主题了 使用协程更新下载引擎 解决了无法正常删除文件的问题
XiaoYouChRc1e0036416c2
diff --git a/app/common/download_task.py b/app/common/download_task.pyindex d199eebe..13d730da 100644--- a/app/common/download_task.py+++ b/app/common/download_task.py@@ -1,10 +1,12 @@+import asyncioimport reimport structimport urllibfrom email.utils import decode_rfc2231from pathlib import Pathfrom threading import Thread-from time import sleep, time+from time import time+from types import coroutinefrom urllib.parse import urlparse, parse_qs, unquoteimport httpx@@ -12,7 +14,7 @@ from PySide6.QtCore import QThread, Signalfrom loguru import loggerfrom app.common.config import cfg-from app.common.methods import getProxy, getReadableSize, retry+from app.common.methods import getProxy, 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"}@@ -34,47 +36,45 @@ urlRe = re.compile(r"^" +"$", re.IGNORECASE)-def getRealUrl(url: str):- # try:- response = httpx.head(url=url, headers=Headers, follow_redirects=False, verify=False,- proxy=getProxy())-- if response.status_code == 400: # Bad Requests- # TODO 报错处理- logger.error("HTTP status code 400, it seems that the url is unavailable")- return-- while response.status_code == 302: # 当302的时候- rs = response.headers["location"] # 获取重定向信息- logger.info(f'HTTP status code:302, Headers["Location"] is: {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-- logger.info(f"HTTP status code:302, Redirect to {url}")-- response = httpx.head(url=url, headers=Headers, follow_redirects=False, verify=False,- proxy=getProxy()) # 再访问一次-- return url-- # TODO 报错处理- # except httpx.ConnectError as err:- # logger.error(f"Cannot connect to the Internet! Error: {err}")- # return- # except ValueError as err:- # logger.error(f"Cannot connect to the Internet! Error: {err}")- # return- # except httpx.ConnectTimeout as err:- # logger.error(f"Cannot connect to the Internet! Error: {err}")- # return+# def getRealUrl(url: str):+# response = httpx.head(url=url, headers=Headers, follow_redirects=False, verify=False,+# proxy=getProxy())+#+# if response.status_code == 400: # Bad Requests+# # TODO 报错处理+# logger.error("HTTP status code 400, it seems that the url is unavailable")+# return+#+# while response.status_code == 302: # 当302的时候+# rs = response.headers["location"] # 获取重定向信息+# logger.info(f'HTTP status code:302, Headers["Location"] is: {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+#+# logger.info(f"HTTP status code:302, Redirect to {url}")+#+# response = httpx.head(url=url, headers=Headers, follow_redirects=False, verify=False,+# proxy=getProxy()) # 再访问一次+#+# return url+class DownloadWorker:+ """只能出卖劳动力的最底层工作者"""++ def __init__(self, start, process, end, client: httpx.AsyncClient):+ self.startPos = start+ self.process = process+ self.endPos = end++ self.client = client+class DownloadTask(QThread):- """作用相当于包工头"""+ """TaskManager"""taskInited = Signal() # 线程初始化成功# processChange = Signal(str) # 目前进度 且因为C++ int最大值仅支持到2^31 PyQt又没有Qint类 故只能使用str代替@@ -91,17 +91,21 @@ class DownloadTask(QThread):self.filePath = filePathself.maxBlockNum = maxBlockNumself.workers: list[DownloadWorker] = []+ self.tasks: list[coroutine] = []- self.client = httpx.Client(headers=Headers, verify=False,- proxy=getProxy())+ self.client = httpx.AsyncClient(headers=Headers, verify=False,+ proxy=getProxy(), limits=httpx.Limits(max_connections=256))+ self.fileLock = asyncio.Lock()- self.__tempThread = Thread(target=self.__getLinkInfo, daemon=True)+ self.__tempThread = Thread(target=self.__getLinkInfo, daemon=True) # TODO 获取文件名和文件大小的线程等信息, 暂时使用线程方式self.__tempThread.start()- def __reassignWorker(self):+ def __reassignWorker(self, task: coroutine):# 找到剩余进度最多的线程maxRemainder = 0+ maxRemainderWorkerProcess = 0+ maxRemainderWorkerEnd = 0maxRemainderWorker: DownloadWorker = Nonefor i in self.workers:@@ -111,7 +115,7 @@ class DownloadTask(QThread):maxRemainder = (maxRemainderWorkerEnd - maxRemainderWorkerProcess)maxRemainderWorker = i- if maxRemainderWorker and maxRemainder > cfg.maxReassignSize.value * 1048576:+ if maxRemainderWorker and maxRemainder > cfg.maxReassignSize.value * 1048576: # 转换成 MB# 平均分配工作量baseShare = maxRemainder // 2remainder = maxRemainder % 2@@ -121,14 +125,15 @@ class DownloadTask(QThread):# 安配新的工人s_pos = maxRemainderWorkerProcess + baseShare + remainder + 1- _ = DownloadWorker(s_pos, s_pos, maxRemainderWorkerEnd, self.url, self.filePath,- self.fileName, self.client)- _.workerFinished.connect(self.__reassignWorker)- _.start()- self.workers.insert(self.workers.index(maxRemainderWorker) + 1, _)+ newWorker = DownloadWorker(s_pos, s_pos, maxRemainderWorkerEnd, self.client)+ newTask = asyncio.create_task(self.__handleWorker(newWorker))+ newTask.add_done_callback(self.__reassignWorker)++ self.workers.insert(self.workers.index(maxRemainderWorker) + 1, newWorker)+ self.tasks.append(newTask)logger.info(- f"Task{self.fileName} 分配新线程成功, 剩余量:{getReadableSize(maxRemainder)},修改后的EndPos:{maxRemainderWorker.endPos},新线程:{_},新线程的StartPos:{s_pos}")+ f"Task{self.fileName} 分配新线程成功, 剩余量:{getReadableSize(maxRemainder)},修改后的EndPos:{maxRemainderWorker.endPos},新线程:{newWorker},新线程的StartPos:{s_pos}")else:logger.info(@@ -155,8 +160,8 @@ class DownloadTask(QThread):def __getLinkInfo(self):try:- response = self.client.head(self.url, follow_redirects=True)- response.raise_for_status() # 如果状态码不是 2xx,抛出异常+ response = httpx.head(self.url, follow_redirects=True)+ response.raise_for_status() # 如果状态码不是 2xx,抛出异常head = response.headers@@ -203,7 +208,9 @@ class DownloadTask(QThread):# 获取 response-content-disposition 参数# 解码并分割 disposition# 提取文件名- self.fileName = unquote(parse_qs(urlparse(self.url).query).get('response-content-disposition', [''])[0]).split("filename=")[-1]+ self.fileName = \+ unquote(parse_qs(urlparse(self.url).query).get('response-content-disposition', [''])[0]).split(+ "filename=")[-1]# 去掉可能存在的引号if self.fileName.startswith('"') and self.fileName.endswith('"'):self.fileName = self.fileName[1:-1]@@ -238,7 +245,7 @@ class DownloadTask(QThread):self.taskInited.emit()- except Exception as e: # 重试也没用+ except Exception as e: # 重试也没用self.gotWrong.emit(str(e))def __loadWorkers(self):@@ -255,133 +262,143 @@ class DownloadTask(QThread):start, process, end = struct.unpack("<QQQ", data)self.workers.append(- DownloadWorker(start, process, end, self.url, self.filePath,- self.fileName, self.client))+ DownloadWorker(start, process, end, self.client))except Exception as e:logger.error(f"Failed to load workers: {e}")+ stepList = self.__clacDivisionalRange()+for i in range(self.maxBlockNum):- stepList = self.__clacDivisionalRange()self.workers.append(- DownloadWorker(stepList[i][0], stepList[i][0], stepList[i][1], self.url, self.filePath,- self.fileName, self.client))+ DownloadWorker(stepList[i][0], stepList[i][0], stepList[i][1], self.client))else:+ stepList = self.__clacDivisionalRange()+for i in range(self.maxBlockNum):- stepList = self.__clacDivisionalRange()self.workers.append(- DownloadWorker(stepList[i][0], stepList[i][0], stepList[i][1], self.url, self.filePath,- self.fileName, self.client))+ DownloadWorker(stepList[i][0], stepList[i][0], stepList[i][1], self.client))- @retry(3, 0.1)- def run(self):- self.__tempThread.join()+ async def __handleWorker(self, worker: DownloadWorker):+ if worker.process < worker.endPos: # 因为可能会创建空线程+ finished = False+ while not finished:+ try:+ download_headers = {"Range": f"bytes={worker.process}-{worker.endPos}",+ "User-Agent": Headers["User-Agent"]}- # 创建空文件- Path(f"{self.filePath}/{self.fileName}").touch()-- # TODO 发消息给主线程- if not self.ableToParallelDownload:- self.maxBlockNum = 1+ async with worker.client.stream(url=self.url, headers=download_headers, timeout=30,+ method="GET") as res:+ async for chunk in res.aiter_raw(chunk_size=65536): # aiter_content 的单位是字节, 即每64K写一次文件+ if worker.endPos <= worker.process:+ break+ if chunk:+ async with self.fileLock: # 必须加锁!+ self.file.seek(worker.process)+ self.file.write(chunk)+ worker.process += 65536- # 加载分块- self.__loadWorkers()+ if worker.process >= worker.endPos:+ worker.process = worker.endPos- for i in self.workers:- logger.debug(f"Task {self.fileName}, starting the thread {i}...")- i.workerFinished.connect(self.__reassignWorker)- i.start()+ finished = True- # fileResolve = Path(f"{self.filePath}/{self.fileName}")- # 实时统计进度并写入历史记录文件- with open(f"{self.filePath}/{self.fileName}.ghd", "wb") as f:- while not self.process == self.fileSize:+ except Exception as e:+ logger.info(+ f"Task: {self.fileName}, Thread {worker} is reconnecting to the server, Error: {repr(e)}")- f.seek(0)- info = []- self.process = 0+ self.gotWrong.emit(repr(e))- for i in self.workers:+ await asyncio.sleep(5)- info.append({"start": i.startPos, "process": i.process, "end": i.endPos})+ worker.process = worker.endPos- self.process += (i.process - i.startPos + 1)+ async def __supervisor(self):+ """实时统计进度并写入历史记录文件"""- # 保存 workers 信息为二进制格式- data = struct.pack("<QQQ", i.startPos, i.process, i.endPos)- f.write(data)+ while not self.process == self.fileSize:- f.flush()- f.truncate()+ self.ghdFile.seek(0)+ info = []+ self.process = 0- self.workerInfoChange.emit(info)+ for i in self.workers:+ info.append({"start": i.startPos, "process": i.process, "end": i.endPos})- sleep(1)+ self.process += (i.process - i.startPos + 1)- # 删除历史记录文件+ # 保存 workers 信息为二进制格式+ data = struct.pack("<QQQ", i.startPos, i.process, i.endPos)+ self.ghdFile.write(data)++ self.ghdFile.flush()+ self.ghdFile.truncate()++ self.workerInfoChange.emit(info)++ await asyncio.sleep(1)++ async def __main(self):try:- Path(f"{self.filePath}/{self.fileName}.ghd").unlink()+ # 打开下载文件+ self.file = open(f"{self.filePath}/{self.fileName}", "rb+")- except Exception as e:- logger.error(f"Failed to delete the history file, please delete it manually. Err: {e}")+ # 启动 Worker+ for i in self.workers:+ logger.debug(f"Task {self.fileName}, starting the thread {i}...")- logger.info(f"Task {self.fileName} finished!")+ _ = asyncio.create_task(self.__handleWorker(i))+ _.add_done_callback(self.__reassignWorker)- self.taskFinished.emit()+ self.tasks.append(_)+ self.ghdFile = open(f"{self.filePath}/{self.fileName}.ghd", "wb")+ supervisorTask = asyncio.create_task(self.__supervisor())-class DownloadWorker(QThread):- """只能出卖劳动力的最底层工作者"""+ # 仅仅需要等待 supervisorTask+ await supervisorTask- workerFinished = Signal() # 内置的信号不好用+ # 关闭+ await self.client.aclose()- def __init__(self, start, process, end, url, filePath, fileName, client: httpx.Client, parent=None):- super().__init__(parent)- self.startPos = start- self.process = process- self.endPos = end- self.url = url- self.filePath = filePath- self.fileName = fileName- self.client = client+ except Exception as e:+ self.gotWrong.emit(repr(e))+ # @retry(3, 0.1)def run(self):- 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"]}+ self.__tempThread.join()- self.file = open(f"{self.filePath}/{self.fileName}", "rb+")- self.file.seek(self.process)+ # 创建空文件+ Path(f"{self.filePath}/{self.fileName}").touch()- with self.client.stream(url=self.url, headers=download_headers, timeout=30, method="GET") as res:- for chunk in res.iter_raw(chunk_size=65536): # iter_content 的单位是字节, 即每64K写一次文件- if self.endPos <= self.process:- break- if chunk:- self.file.write(chunk)- self.process += 65536+ # TODO 发消息给主线程+ if not self.ableToParallelDownload:+ self.maxBlockNum = 1- if self.process >= self.endPos:- self.process = self.endPos+ # 加载分块+ self.__loadWorkers()- try:- self.file.close()- except:- pass+ # 主逻辑, 使用事件循环启动异步任务+ loop = asyncio.new_event_loop()+ asyncio.set_event_loop(loop)- finished = True+ try:+ loop.run_until_complete(self.__main())+ except asyncio.CancelledError:+ pass+ finally:+ loop.run_until_complete(loop.shutdown_asyncgens())+ loop.close()- except Exception as e:- logger.info(f"Task: {self.fileName}, Thread {self} is reconnecting to the server, Error: {e}")+ self.file.close()+ self.ghdFile.close()- try:- self.file.close()- except:- pass+ # 删除历史记录文件+ try:+ Path(f"{self.filePath}/{self.fileName}.ghd").unlink()- sleep(5)+ except Exception as e:+ logger.error(f"Failed to delete the history file, please delete it manually. Err: {e}")++ logger.info(f"Task {self.fileName} finished!")- self.process = self.endPos- self.workerFinished.emit()+ self.taskFinished.emit()diff --git a/app/components/add_task_dialog.py b/app/components/add_task_dialog.pyindex 6c61501b..c27847e4 100644--- a/app/components/add_task_dialog.py+++ b/app/components/add_task_dialog.py@@ -6,7 +6,7 @@ from PySide6.QtCore import Signal, Qt, QTimerfrom PySide6.QtGui import QColorfrom PySide6.QtWidgets import QVBoxLayout, QFileDialog, QHBoxLayout, QSizePolicyfrom qfluentwidgets import PushSettingCard, SettingCardGroup, RangeSettingCard, PushButton, PrimaryPushButton, TextEdit, \- MessageBox, isDarkTheme, InfoBar, InfoBarPosition+ MessageBox, InfoBar, InfoBarPosition, FluentStyleSheetfrom qfluentwidgets.common.icon import FluentIcon as FIFfrom qfluentwidgets.components.dialog_box.mask_dialog_base import MaskDialogBase@@ -36,6 +36,8 @@ class AddTaskOptionDialog(MaskDialogBase):def __init__(self, parent=None):super().__init__(parent=parent)+ FluentStyleSheet.DIALOG.apply(self.widget)+self.setShadowEffect(60, (0, 10), QColor(0, 0, 0, 50))self.setMaskColor(QColor(0, 0, 0, 76))@@ -46,11 +48,6 @@ class AddTaskOptionDialog(MaskDialogBase):self.widget.setMinimumSize(510, 420)self.widget.setMaximumSize(680, 430)- 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(diff --git a/app/components/custom_tray.py b/app/components/custom_tray.pyindex 06aeaa56..73a59031 100644--- a/app/components/custom_tray.py+++ b/app/components/custom_tray.py@@ -4,6 +4,7 @@ from PySide6.QtWidgets import QSystemTrayIcon, QApplicationfrom qfluentwidgets import Actionfrom qfluentwidgets import FluentIcon as FIFfrom qfluentwidgets.components.material import AcrylicMenu+from shiboken6.Shiboken import deleteclass FixedAcrylicSystemTrayMenu(AcrylicMenu):@@ -60,19 +61,17 @@ class CustomSystemTrayIcon(QSystemTrayIcon):def __onQuitActionTriggered(self):self.parent().themeChangedListener.terminate()- for i in self.parent().taskInterface.cards:+ for i in self.parent().taskInterface.cards: # 是为了不写入历史记录安全的退出if i.status == 'working':- for j in i.task.workers:- # try:- # j.file.close()- # except AttributeError as e:- # logger.info(f"Task:{i.task.fileName}, users operate too quickly!, thread {i} error: {e}")- # except Exception as e:- # logger.warning(- # f"Task:{i.task.fileName}, it seems that cannot cancel thread {i} occupancy of the file, error: {e}")- j.terminate()+ for j in i.task.tasks:+ j.cancel()+ i.task.file.close()+ i.task.ghdFile.close()i.task.terminate()+ i.task.deleteLater()++ delete(i.task)QApplication.quit()diff --git a/app/components/task_card.py b/app/components/task_card.pyindex df7122d9..824cc1f4 100644--- a/app/components/task_card.py+++ b/app/components/task_card.py@@ -8,6 +8,7 @@ from PySide6.QtWidgets import QFileIconProviderfrom loguru import loggerfrom qfluentwidgets import CardWidgetfrom qfluentwidgets import FluentIcon as FIF+from shiboken6.Shiboken import deletefrom .Ui_TaskCard import Ui_TaskCardfrom .task_progress_bar import TaskProgressBar@@ -147,15 +148,15 @@ class TaskCard(CardWidget, Ui_TaskCard):self.pauseButton.setIcon(FIF.PLAY)try:- for i in self.task.workers:- # try:- # i.file.close()- # except Exception as e:- # logger.warning(- # f"Task:{self.fileName}, it seems that cannot cancel thread {i} occupancy of the file, error: {e}")- i.terminate()+ for i in self.task.tasks:+ i.cancel()+ self.task.file.close()+ self.task.ghdFile.close()self.task.terminate()+ self.task.deleteLater()++ delete(self.task)# 改变记录状态with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "r", encoding="utf-8") as f:diff --git a/app/components/update_dialog.py b/app/components/update_dialog.pyindex 9dad54c8..5c220ace 100644--- a/app/components/update_dialog.py+++ b/app/components/update_dialog.py@@ -1,10 +1,9 @@import httpxfrom PySide6.QtCore import QThread, Signalfrom PySide6.QtGui import QColor-from PySide6.QtWidgets import QVBoxLayout, QSizePolicy, QHBoxLayout, QListWidgetItem, QTableWidgetItem+from PySide6.QtWidgets import QTableWidgetItemfrom loguru import logger-from qfluentwidgets import isDarkTheme, TextEdit, ListWidget, BodyLabel, PrimaryPushButton, \- PushButton, SubtitleLabel, InfoBar, InfoBarPosition+from qfluentwidgets import InfoBar, InfoBarPosition, FluentStyleSheetfrom qfluentwidgets.components.dialog_box.mask_dialog_base import MaskDialogBasefrom app.common.config import VERSION, cfg@@ -43,6 +42,8 @@ class UpdateDialog(MaskDialogBase, Ui_UpdateDialog):def __init__(self, parent, content: dict):super().__init__(parent=parent)+ FluentStyleSheet.DIALOG.apply(self.widget)+self.content = contentself.tabelViewInfos = []self.urls: list[str] = []@@ -57,12 +58,6 @@ class UpdateDialog(MaskDialogBase, Ui_UpdateDialog):self.widget.setMinimumSize(520, 650)self.widget.setMaximumSize(680, 720)- 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.__analyzeContent()# connect signal to slotdiff --git a/plugins/jy_os_page.py b/plugins/jy_os_page.pyindex bc73b26c..a5692533 100644--- a/plugins/jy_os_page.py+++ b/plugins/jy_os_page.py@@ -8,10 +8,10 @@ from PySide6.QtCore import Qt, QThread, Signal, QDir, QUrl, QSize, QMetaObject,from PySide6.QtGui import QPixmap, QColor, QDesktopServicesfrom PySide6.QtWidgets import QWidget, QFrame, QVBoxLayout, QSizePolicy, QHBoxLayout, QFileDialogfrom loguru import logger-from qfluentwidgets import ScrollArea, TitleLabel, isDarkTheme, SettingCardGroup, OptionsConfigItem, OptionsValidator, \+from qfluentwidgets import ScrollArea, TitleLabel, SettingCardGroup, OptionsConfigItem, OptionsValidator, \ComboBoxSettingCard, FluentIcon as FIF, TextEdit, PushSettingCard, RangeSettingCard, RangeConfigItem, \RangeValidator, PrimaryPushButton, PushButton, MessageBox, CardWidget, RoundMenu, Action, PixmapLabel, BodyLabel, \- PrimarySplitPushButton, NavigationItemPosition+ PrimarySplitPushButton, NavigationItemPosition, FluentStyleSheetfrom qfluentwidgets.components.dialog_box.mask_dialog_base import MaskDialogBasefrom app.common.methods import getProxy@@ -129,6 +129,8 @@ class DownloadOptionDialog(MaskDialogBase):def __init__(self, parent=None, list=None, dict=None):super().__init__(parent=parent)+ FluentStyleSheet.DIALOG.apply(self.widget)+self.dict = dictself.list = listself.versions = []@@ -143,11 +145,6 @@ class DownloadOptionDialog(MaskDialogBase):self.widget.setMinimumSize(510, 530)self.widget.setMaximumSize(680, 540)- 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(diff --git a/requirements.txt b/requirements.txtindex 8ef74299..68e94d45 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,4 +1,5 @@PySide6-Fluent-Widgets>=1.6.3PySide6==6.7.2-loguru==0.7.2-httpx==0.27.0+loguru~=0.7.2+httpx~=0.27.0+darkdetect~=0.8.0