Skip to content

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

让浏览器插件可以捕捉请求标头, 下载任务在接口上可以自定义 Headers, 对 Ghost Downloader 记录文件进行序列化并优化 task_card.py 的改变任务状态方式

XiaoYouChRf3b5d157cbc5
diff --git a/app/common/download_task.py b/app/common/download_task.py
index 0dbe626c..0acd7cc2 100644
--- a/app/common/download_task.py
+++ b/app/common/download_task.py
@@ -358,7 +358,7 @@ class DownloadTask(QThread):
# 任务初始化完成
self.taskInited.emit()
- # TODO 发消息给主线程
+ # TODO 发消息给 TaskCard
if not self.ableToParallelDownload:
self.preBlockNum = 1
diff --git a/app/components/task_card.py b/app/components/task_card.py
index 8e4dc412..247b7480 100644
--- a/app/components/task_card.py
+++ b/app/components/task_card.py
@@ -1,4 +1,5 @@
import hashlib
+import pickle
from pathlib import Path
from PySide6.QtCore import QThread, Signal, QFileInfo
@@ -21,14 +22,13 @@ proxy = getProxy()
class TaskCard(CardWidget, Ui_TaskCard):
taskStatusChanged = Signal()
- def __init__(self, url, path, maxBlockNum: int, headers:dict, name: str = None, status: str = "working",
+ def __init__(self, url, path, maxBlockNum: int, headers: dict, name: str = None, status: str = "working",
parent=None, autoCreated=False):
super().__init__(parent=parent)
self.setupUi(self)
# 初始化参数
-
self.url = url
self.headers = headers
self.filePath = path
@@ -37,7 +37,6 @@ class TaskCard(CardWidget, Ui_TaskCard):
self.autoCreated = autoCreated # 事实上用来记录历史文件是否已经创建
# Show Information
-
self.__showInfo("若任务初始化过久,请检查网络连接后重试.")
self.TitleLabel.setText("正在初始化任务...")
@@ -53,7 +52,6 @@ class TaskCard(CardWidget, Ui_TaskCard):
self.fileName = name
if not self.status == "finished": # 不是已完成的任务才要进行的操作
-
self.pauseButton.setDisabled(True)
if name:
@@ -95,6 +93,55 @@ class TaskCard(CardWidget, Ui_TaskCard):
elif self.status == "paused":
self.pauseButton.setIcon(FIF.PLAY)
+ def updateTaskRecord(self, newStatus: str):
+ recordPath = "{}/Ghost Downloader 记录文件".format(cfg.appPath)
+
+ # 读取所有记录
+ records = []
+ try:
+ with open(recordPath, "rb") as f:
+ while True:
+ try:
+ record = pickle.load(f)
+ records.append(record)
+ except EOFError:
+ break
+ except FileNotFoundError:
+ pass
+
+ # 检查是否已有匹配的记录
+ found = False
+ updatedRecords = []
+ for record in records:
+ if (record["url"] == self.url and
+ record["fileName"] == self.fileName and
+ record["filePath"] == str(self.filePath) and
+ record["blockNum"] == self.maxBlockNum and
+ record["headers"] == self.headers):
+ found = True
+ if newStatus != "deleted":
+ record["status"] = newStatus
+ updatedRecords.append(record)
+ else:
+ updatedRecords.append(record)
+
+ # 如果没有找到匹配的记录且 newStatus 不是 "deleted",则添加新记录
+ if not found and newStatus != "deleted":
+ updatedRecords.append({
+ "url": self.url,
+ "fileName": self.fileName,
+ "filePath": str(self.filePath),
+ "blockNum": self.maxBlockNum,
+ "status": self.status,
+ "headers": self.headers
+ })
+
+ # 写回记录文件
+ with open(recordPath, "wb") as f:
+ for record in updatedRecords:
+ pickle.dump(record, f)
+
+
def __onTaskError(self, exception: str):
self.__showInfo(f"Error: {exception}")
@@ -103,11 +150,7 @@ class TaskCard(CardWidget, Ui_TaskCard):
# 写入未完成任务记录文件,以供下次打开时继续下载
if self.fileName and not self.autoCreated:
- with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "a", encoding="utf-8") as f:
- _ = {"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),
- "blockNum": self.maxBlockNum, "status": self.status}
- f.write(str(_) + "\n")
-
+ self.updateTaskRecord(self.status)
self.autoCreated = True
# TODO 因为Windows会返回已经处理过的只有左上角一点点的图像,所以需要超分辨率触发条件
@@ -141,16 +184,7 @@ class TaskCard(CardWidget, Ui_TaskCard):
self.task.deleteLater()
# 改变记录状态
- with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "r", encoding="utf-8") as f:
- _ = f.read()
-
- _ = _.replace(str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),
- "blockNum": self.maxBlockNum, "status": self.status}) + "\n",
- str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),
- "blockNum": self.maxBlockNum, "status": "paused"}) + "\n")
-
- with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "w", encoding="utf-8") as f:
- f.write(_)
+ self.updateTaskRecord("paused")
except Exception as e:
logger.warning(f"Task:{self.fileName}, 暂停时遇到错误: {repr(e)}")
@@ -166,7 +200,7 @@ class TaskCard(CardWidget, Ui_TaskCard):
try:
self.task = DownloadTask(self.url, self.headers, self.maxBlockNum, self.filePath, self.fileName)
- except: # TODO 没有 fileName 的情况
+ except: # TODO 没有 fileName 的情况
self.task = DownloadTask(self.url, self.headers, self.maxBlockNum, self.filePath)
self.__connectSignalToSlot()
@@ -175,16 +209,7 @@ class TaskCard(CardWidget, Ui_TaskCard):
try:
# 改变记录状态
- with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "r", encoding="utf-8") as f:
- _ = f.read()
-
- _ = _.replace(str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),
- "blockNum": self.maxBlockNum, "status": self.status}) + "\n",
- str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),
- "blockNum": self.maxBlockNum, "status": "working"}) + "\n")
-
- with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "w", encoding="utf-8") as f:
- f.write(_)
+ self.updateTaskRecord("working")
finally:
self.__showInfo("任务正在开始")
@@ -229,14 +254,7 @@ class TaskCard(CardWidget, Ui_TaskCard):
finally:
try:
# 删除记录文件
- with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "r", encoding="utf-8") as f:
- _ = f.read()
-
- _ = _.replace(str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),
- "blockNum": self.maxBlockNum, "status": self.status}) + "\n", "")
-
- with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "w", encoding="utf-8") as f:
- f.write(_)
+ self.updateTaskRecord("deleted")
finally:
# Remove Widget
@@ -245,7 +263,7 @@ class TaskCard(CardWidget, Ui_TaskCard):
self.taskStatusChanged.emit()
self.deleteLater()
- def __showInfo(self, content:str):
+ def __showInfo(self, content: str):
# 隐藏 statusHorizontalLayout
self.speedLabel.hide()
self.leftTimeLabel.hide()
@@ -270,7 +288,7 @@ class TaskCard(CardWidget, Ui_TaskCard):
self.progressBar.addProgressBar(content, _)
for e, i in enumerate(content):
- self.progressBar.progressBarList[e].setValue( ( (i["process"] - i["start"]) / (i["end"] - i["start"]) ) * 100)
+ self.progressBar.progressBarList[e].setValue(((i["process"] - i["start"]) / (i["end"] - i["start"])) * 100)
# 如果还在显示消息状态,则调用 __hideInfo
if self.infoLabel.isVisible():
@@ -296,23 +314,14 @@ class TaskCard(CardWidget, Ui_TaskCard):
self.__showInfo("任务已经完成")
- try: # 程序启动时不要发
+ try: # 程序启动时不要发
self.window().tray.showMessage(self.window().windowTitle(), f"任务 {self.fileName} 已完成!", self.window().windowIcon())
except:
pass
if not self.status == "finished": # 不是自动创建的已完成任务
# 改变记录状态
- with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "r", encoding="utf-8") as f:
- _ = f.read()
-
- _ = _.replace(str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),
- "blockNum": self.maxBlockNum, "status": self.status}) + "\n",
- str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),
- "blockNum": self.maxBlockNum, "status": "finished"}) + "\n")
-
- with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "w", encoding="utf-8") as f:
- f.write(_)
+ self.updateTaskRecord("finished")
# 再获取一次图标
_ = QFileIconProvider().icon(QFileInfo(f"{self.filePath}/{self.fileName}")).pixmap(128, 128) # 自动获取图标
diff --git a/app/view/main_window.py b/app/view/main_window.py
index a3a43070..8a12a0cc 100644
--- a/app/view/main_window.py
+++ b/app/view/main_window.py
@@ -1,7 +1,7 @@
# coding: utf-8
import ctypes
+import pickle
import sys
-from ast import literal_eval
from ctypes import byref, c_int
from pathlib import Path
@@ -15,7 +15,7 @@ from qfluentwidgets import NavigationItemPosition, MSFluentWindow, SplashScreen
from .setting_interface import SettingInterface
from .task_interface import TaskInterface
-from ..common.config import cfg, Headers
+from ..common.config import cfg
from ..common.custom_socket import GhostDownloaderSocketServer
from ..common.signal_bus import signalBus
from ..components.add_task_dialog import AddTaskOptionDialog
@@ -70,15 +70,15 @@ class MainWindow(MSFluentWindow):
# 创建未完成的任务
historyFile = Path("{}/Ghost Downloader 记录文件".format(cfg.appPath))
- # 未完成任务记录文件格式示例: [{"url": "xxx", "fileName": "xxx", "filePath": "xxx", "blockNum": x, "status": "xxx"}]
if historyFile.exists():
- with open(historyFile, 'r', encoding='utf-8') as f:
- unfinishedTaskInfo = f.readlines()
- logger.debug(f"Unfinished Task is following:{unfinishedTaskInfo}")
- for i in unfinishedTaskInfo:
- if i: # 避免空行
- i = literal_eval(i)
- signalBus.addTaskSignal.emit(i['url'], i['filePath'], i['blockNum'], i['fileName'], i["status"], Headers, True)
+ with open(historyFile, 'rb') as f:
+ try:
+ while True:
+ taskRecord = pickle.load(f)
+ logger.debug(f"Unfinished Task is following: {taskRecord}")
+ signalBus.addTaskSignal.emit(taskRecord['url'], taskRecord['filePath'], taskRecord['blockNum'], taskRecord['fileName'], taskRecord['status'], taskRecord['headers'], True)
+ except EOFError:
+ pass
else:
historyFile.touch()
diff --git a/chrome_extension/background.js b/chrome_extension/background.js
index 52e703d4..c6a81eea 100644
--- a/chrome_extension/background.js
+++ b/chrome_extension/background.js
@@ -98,6 +98,13 @@ function stopHeartbeat() {
}
}
+// 提取获取 shouldDisableExtension 的逻辑到一个单独的函数
+function isExtensionDisabled(callback) {
+ chrome.storage.local.get(["shouldDisableExtension"], (result) => {
+ callback(result.shouldDisableExtension || false);
+ });
+}
+
// 监听下载开始事件并阻止下载
chrome.downloads.onCreated.addListener((downloadItem) => {
if (downloadItem.state === "in_progress") {
@@ -136,7 +143,7 @@ chrome.webRequest.onBeforeSendHeaders.addListener(
// 监听 onHeadersReceived 事件,捕获响应头并匹配下载文件类型
chrome.webRequest.onHeadersReceived.addListener(
(details) => {
- // 查找响应头中的 content-type
+ // 查找响应头中的 content-disposition
const contentDispositionHeader = details.responseHeaders.find(
(header) => header.name.toLowerCase() === "content-disposition"
);
@@ -156,8 +163,13 @@ chrome.webRequest.onHeadersReceived.addListener(
console.log("捕获到的下载请求信息:", requestInfo);
- // 将请求信息发送到 WebSocket
- sendDownloadInfo(requestInfo);
+ // 检查是否禁用扩展
+ isExtensionDisabled((shouldDisableExtension) => {
+ if (!shouldDisableExtension) {
+ // 将请求信息发送到 WebSocket
+ sendDownloadInfo(requestInfo);
+ }
+ });
}
}