Skip to content

The only downloader you need. 下载器的集大成者。

优化任务创建逻辑, 提高运行速度

XiaoYouChRd4d5faf4d11d
diff --git a/app/common/download_task.py b/app/common/download_task.py
index 799cca97..9d85c097 100644
--- a/app/common/download_task.py
+++ b/app/common/download_task.py
@@ -73,7 +73,6 @@ def getRealUrl(url: str):
class DownloadTask(QThread):
"""作用相当于包工头"""
- refreshLastProgress = Signal(str) # 用于读取历史记录后刷新进度
# processChange = Signal(str) # 目前进度 且因为C++ int最大值仅支持到2^31 PyQt又没有Qint类 故只能使用str代替
workerInfoChange = Signal(list) # 目前进度 v3.2版本引进了分段式进度条
taskFinished = Signal() # 内置信号的不好用
@@ -81,87 +80,6 @@ class DownloadTask(QThread):
def __init__(self, url, maxBlockNum: int = 8, filePath=None, fileName=None, parent=None):
super().__init__(parent)
- # 获取真实URL
- url = getRealUrl(url)
-
- head = httpx.head(url, headers=Headers, proxy=getWindowsProxy()).headers
-
- # 获取文件大小, 判断是否可以分块下载
- if "content-length" not in head:
- self.fileSize = 1
- self.ableToParallelDownload = False
- else:
- self.fileSize = int(head["content-length"])
- self.ableToParallelDownload = True
-
- # 获取文件名
- if not fileName:
- try:
- # 首先,尝试处理 Content-Disposition 中的 filename* (RFC 5987 格式)
- headerValue = head["content-disposition"]
- if 'filename*' in headerValue:
- match = re.search(r'filename\*\s*=\s*([^;]+)', headerValue, re.IGNORECASE)
- if match:
- fileName = match.group(1)
- fileName = decode_rfc2231(fileName)
- fileName = urllib.parse.unquote(fileName[2]) # filename* 后的部分是编码信息
-
- # 如果 filename* 没有成功获取,尝试处理普通的 filename
- if not fileName and 'filename' in headerValue:
- match = re.search(r'filename\s*=\s*["\']?([^"\';]+)["\']?', headerValue, re.IGNORECASE)
- if match:
- fileName = match.group(1)
-
- # 移除文件名头尾可能存在的引号
- if fileName:
- fileName = fileName.strip('"\'')
- else:
- raise KeyError
-
- logger.debug(f"方法1获取文件名成功, 文件名:{fileName}")
- except (KeyError, IndexError) as e:
- try:
- logger.info(f"方法1获取文件名失败, KeyError or IndexError:{e}")
- # 解析 URL
- # 解析查询字符串
- # 获取 response-content-disposition 参数
- # 解码并分割 disposition
- # 提取文件名
- fileName = unquote(parse_qs(urlparse(url).query).get('response-content-disposition', [''])[0]).split("filename=")[-1]
- # 去掉可能存在的引号
- if fileName.startswith('"') and fileName.endswith('"'):
- fileName = fileName[1:-1]
- elif fileName.startswith("'") and fileName.endswith("'"):
- fileName = fileName[1:-1]
-
- if not fileName:
- raise KeyError
-
- logger.debug(f"方法2获取文件名成功, 文件名:{fileName}")
-
- except (KeyError, IndexError) as e:
- # 处理没有文件名的情况
- logger.info(f"方法2获取文件名失败, KeyError or IndexError:{e}")
- fileName = urlparse(url).path.split('/')[-1]
- logger.debug(f"方法3获取文件名成功, 文件名:{fileName}")
- except Exception as e:
- # 什么都 Get 不到的情况
- logger.info(f"获取文件名失败, Exception:{e}")
- content_type = head["content-type"].split('/')[-1]
- fileName = f"downloaded_file{int(time())}.{content_type}"
- logger.debug(f"方法4获取文件名成功, 文件名:{fileName}")
-
- # 获取文件路径
- if not filePath and Path(filePath).is_dir() == False:
- filePath = Path.cwd()
- else:
- filePath = Path(filePath)
- if not filePath.exists():
- filePath.mkdir()
-
- # 创建空文件
- Path(f"{filePath}/{fileName}").touch()
-
self.process = []
self.url = url
self.fileName = fileName
@@ -228,6 +146,89 @@ class DownloadTask(QThread):
return step_list
def run(self):
+
+ # 初始化信息
+ # 获取真实URL
+ self.url = getRealUrl(self.url)
+
+ head = httpx.head(self.url, headers=Headers, proxy=getWindowsProxy()).headers
+
+ # 获取文件大小, 判断是否可以分块下载
+ if "content-length" not in head:
+ self.fileSize = 1
+ self.ableToParallelDownload = False
+ else:
+ self.fileSize = int(head["content-length"])
+ self.ableToParallelDownload = True
+
+ # 获取文件名
+ if not self.fileName:
+ try:
+ # 首先,尝试处理 Content-Disposition 中的 self.fileName* (RFC 5987 格式)
+ headerValue = head["content-disposition"]
+ if 'fileName*' in headerValue:
+ match = re.search(r'fileName\*\s*=\s*([^;]+)', headerValue, re.IGNORECASE)
+ if match:
+ self.fileName = match.group(1)
+ self.fileName = decode_rfc2231(self.fileName)
+ self.fileName = urllib.parse.unquote(self.fileName[2]) # self.fileName* 后的部分是编码信息
+
+ # 如果 self.fileName* 没有成功获取,尝试处理普通的 self.fileName
+ if not self.fileName and 'fileName' in headerValue:
+ match = re.search(r'fileName\s*=\s*["\']?([^"\';]+)["\']?', headerValue, re.IGNORECASE)
+ if match:
+ self.fileName = match.group(1)
+
+ # 移除文件名头尾可能存在的引号
+ if self.fileName:
+ self.fileName = self.fileName.strip('"\'')
+ else:
+ raise KeyError
+
+ logger.debug(f"方法1获取文件名成功, 文件名:{self.fileName}")
+ except (KeyError, IndexError) as e:
+ try:
+ logger.info(f"方法1获取文件名失败, KeyError or IndexError:{e}")
+ # 解析 URL
+ # 解析查询字符串
+ # 获取 response-content-disposition 参数
+ # 解码并分割 disposition
+ # 提取文件名
+ 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]
+ elif self.fileName.startswith("'") and self.fileName.endswith("'"):
+ self.fileName = self.fileName[1:-1]
+
+ if not self.fileName:
+ raise KeyError
+
+ logger.debug(f"方法2获取文件名成功, 文件名:{self.fileName}")
+
+ except (KeyError, IndexError) as e:
+ # 处理没有文件名的情况
+ logger.info(f"方法2获取文件名失败, KeyError or IndexError:{e}")
+ self.fileName = urlparse(self.url).path.split('/')[-1]
+ logger.debug(f"方法3获取文件名成功, 文件名:{self.fileName}")
+ except Exception as e:
+ # 什么都 Get 不到的情况
+ logger.info(f"获取文件名失败, Exception:{e}")
+ content_type = head["content-type"].split('/')[-1]
+ self.fileName = f"downloaded_file{int(time())}.{content_type}"
+ logger.debug(f"方法4获取文件名成功, 文件名:{self.fileName}")
+
+ # 获取文件路径
+ 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()
+
+ # 创建空文件
+ Path(f"{self.filePath}/{self.fileName}").touch()
+
# TODO 发消息给主线程
if not self.ableToParallelDownload:
self.maxBlockNum = 1
@@ -243,7 +244,6 @@ class DownloadTask(QThread):
DownloadWorker(i["start"], i["process"], i["end"], self.url, self.filePath,
self.fileName, self.client))
- self.refreshLastProgress.emit(str(sum([i.process for i in self.workers]))) # 要不然速度会错
# TODO 错误处理
except:
for i in range(self.maxBlockNum):
diff --git a/app/common/signal_bus.py b/app/common/signal_bus.py
index 7192fc93..85d7f20c 100644
--- a/app/common/signal_bus.py
+++ b/app/common/signal_bus.py
@@ -5,7 +5,7 @@ from PySide6.QtGui import QPixmap
class SignalBus(QObject):
""" Signal bus """
- addTaskSignal = Signal(str, str, int, str, str, QPixmap, bool) # url, filePath, maxBlockNum, name, icon
+ addTaskSignal = Signal(str, str, int, str, str, QPixmap, bool) # url, filePath, maxBlockNum, status, name, icon, autoStart
Tasks = []
diff --git a/app/components/task_card.py b/app/components/task_card.py
index 83dcafb5..70b8e506 100644
--- a/app/components/task_card.py
+++ b/app/components/task_card.py
@@ -44,8 +44,7 @@ proxy = getWindowsProxy()
class TaskCard(CardWidget, Ui_TaskCard):
# removeTaskSignal = Signal(int, bool)
def __init__(self, url, path, maxBlockNum: int, pixmap: QPixmap = None, name: str = None, status: str = "working",
- parent=None,
- autoCreated=False):
+ parent=None, autoCreated=False):
super().__init__(parent=parent)
self.setupUi(self)
@@ -64,9 +63,6 @@ class TaskCard(CardWidget, Ui_TaskCard):
self.verticalLayout.addWidget(self.progressBar)
- def _(progress: str): # 用于赋值
- self.lastProcess = int(progress)
-
if name:
self.fileName = name
@@ -77,7 +73,6 @@ class TaskCard(CardWidget, Ui_TaskCard):
self.task = DownloadTask(url, maxBlockNum, path)
self.fileName = self.task.fileName
- self.task.refreshLastProgress.connect(_)
self.task.workerInfoChange.connect(self.__changeInfo)
self.task.taskFinished.connect(self.taskFinished)
@@ -228,15 +223,13 @@ class TaskCard(CardWidget, Ui_TaskCard):
# process = int(content)
_ = len(content) - self.progressBar.blockNum
if _:
- for i in range(_):
- self.progressBar.addProgressBar()
+ self.progressBar.addProgressBar(content, _)
process = 0
for e, i in enumerate(content):
process += i["process"] - i["start"]
- self.progressBar.HBoxLayout.setStretch(e, int((i["end"] - i["start"]) / 1048576)) # 除以1MB
self.progressBar.progressBarList[e].setValue( ( (i["process"] - i["start"]) / (i["end"] - i["start"]) ) * 100)
duringLastSecondProcess = process - self.lastProcess
diff --git a/app/components/task_progress_bar.py b/app/components/task_progress_bar.py
index 12bc45d8..f463d309 100644
--- a/app/components/task_progress_bar.py
+++ b/app/components/task_progress_bar.py
@@ -19,8 +19,14 @@ class TaskProgressBar(QWidget):
self.HBoxLayout.addWidget(_)
self.progressBarList.append(_)
- def addProgressBar(self):
- _ = ProgressBar(self)
- self.HBoxLayout.addWidget(_)
- self.progressBarList.append(_)
- self.blockNum += 1
\ No newline at end of file
+ def addProgressBar(self, content: list, quantity: int):
+
+ for i in range(quantity):
+ _ = ProgressBar(self)
+ self.HBoxLayout.addWidget(_)
+ self.progressBarList.append(_)
+
+ self.blockNum += quantity
+
+ for e, i in enumerate(content): # 更改 Stretch
+ self.progressBar.HBoxLayout.setStretch(e, int((i["end"] - i["start"]) / 1048576)) # 除以1MB
\ No newline at end of file
diff --git a/app/view/main_window.py b/app/view/main_window.py
index 8cbbe2be..590cc94a 100644
--- a/app/view/main_window.py
+++ b/app/view/main_window.py
@@ -74,7 +74,7 @@ class MainWindow(MSFluentWindow):
self.splashScreen.finish()
def addDownloadTaskFromWebSocket(self, url: str):
- self.taskInterface.addDownloadTask(url, cfg.downloadFolder.value, cfg.maxBlockNum.value)
+ signalBus.addTaskSignal.emit(url, cfg.downloadFolder.value, cfg.maxBlockNum.value, None, None, None, None)
self.tray.showMessage(self.windowTitle(), f"已捕获来自浏览器的下载任务: \n{url}", self.windowIcon())
def toggleTheme(self, callback: str):