The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(core): 实现HTTP下载功能包和任务系统重构
XiaoYouChR4626e609627e
diff --git a/.gitignore b/.gitignorenew file mode 100644index 00000000..61d3a0bd--- /dev/null+++ b/.gitignore@@ -0,0 +1,31 @@+# 忽略.vscode文件夹+.vscode/+.VSCodeCounter++# 忽略工作区文件+*.code-workspace+.DS_Store++# 忽略 .idea+.idea/++# 忽略python缓存文件+*/__pycache__+*.py[cod]++# 忽略日志文件+log/+*.log++# 忽略 ui 文件+*.ui++# 忽略 Ghost Downloader 文件+Ghost Downloader 记录文件+Ghost Downloader 配置文件.json++# 忽略构建文件+build/+dist/+output/+*.spec\ No newline at end of filediff --git a/app/bases/interfaces.py b/app/bases/interfaces.pyindex 23d16b4d..1a547cc8 100644--- a/app/bases/interfaces.py+++ b/app/bases/interfaces.py@@ -1,15 +1,21 @@from typing import TYPE_CHECKING-from app.view.components.cards import TaskCardBase+from app.bases.models import TaskStage+from app.view.components.cards import TaskCardif TYPE_CHECKING:from app.view.windows.main_window import MainWindow-class FeaturePackBase:+class Worker:+ def __init__(self, stage: TaskStage):+ pass- def parse(self, payload: dict) -> TaskCardBase:++class FeaturePack:++ async def parse(self, payload: dict) -> TaskCard:raise NotImplementedErrordef load(self, mainWindow: "MainWindow"):- raise NotImplementedError\ No newline at end of file+ passdiff --git a/app/bases/models.py b/app/bases/models.pyindex 9a5e508e..4bae2824 100644--- a/app/bases/models.py+++ b/app/bases/models.py@@ -1,6 +1,7 @@from enum import Enum, autofrom dataclasses import dataclass, field-from typing import Any, Optional+from time import time_ns+from typing import Any, Optional, Selffrom uuid import uuid4import time@@ -17,16 +18,15 @@ class TaskStatus(Enum):FAILED = auto()-@dataclass+@dataclass(kw_only=True)class TaskStage:"""Represents a single, executable stage within a parent Task."""- taskId: strstageIndex: intdisplayIntent: strworkerType: strstageId: str = field(default_factory=lambda: f"stg_{uuid4().hex}")- instructionPayload: dict[str, Any] = field(default_factory=dict)+ # metadata: dict[str, Any] = field(default_factory=dict)status: TaskStatus = TaskStatus.WAITINGprogress: float = 0.0@@ -35,14 +35,26 @@ class TaskStage:if not (0 <= self.progress <= 1):raise ValueError(f"progress must be between 0 and 1, got {self.progress}")+ def serialize(self) -> dict[str, Any]:+ raise NotImplementedError-@dataclass+ def deserialize(self, dict: dict[str, Any]) -> Self:+ raise NotImplementedError+++@dataclass(kw_only=True)class Task:"""Represents a logical, user-facing task, which is a collection of stages."""title: strtaskId: str = field(default_factory=lambda: f"tsk_{uuid4().hex}")status: TaskStatus = TaskStatus.RUNNING- currentStageId: Optional[str] = None- createdAt: int = field(default_factory=lambda: int(time.time()))- metadata: dict[str, Any] = field(default_factory=dict)+ stages: list[TaskStage] = field(default_factory=list)+ createdAt: int = field(default_factory=lambda: int(time_ns()))+ # metadata: dict[str, Any] = field(default_factory=dict)++ def serialize(self) -> dict[str, Any]:+ raise NotImplementedError++ def deserialize(self, dict: dict[str, Any]) -> Self:+ raise NotImplementedErrordiff --git a/app/services/core_service.py b/app/services/core_service.pyindex 8635634c..88a60abe 100644--- a/app/services/core_service.py+++ b/app/services/core_service.py@@ -10,6 +10,7 @@ from loguru import loggerfrom app.bases.models import Taskfrom app.services.feature_service import featureService+from features.http_pack.pack import parseclass CoreService(QThread):@@ -29,97 +30,99 @@ class CoreService(QThread):asyncio.set_event_loop(self.loop)self.mainLoop = self.loop.create_task(self.main())self.tasks: set[Task] = set()- self._pending_callbacks: Dict[str, Callable] = {} # 存储待执行的回调函数+ self._pendingCallbacks: Dict[str, Callable[[dict, str | None], Coroutine | None]] = {}- def runCoroutine(self, coroutine: Coroutine, callback):- # 生成回调标识符- callback_id = f"custom_{id(callback)}_{hash(str(coroutine))}"+ def runCoroutine(self, coroutine: Coroutine, callback: Callable[[dict, str | None], Coroutine | None] | None = None):+ if callback is not None:+ callbackId = f"custom_{id(callback)}_{hash(coroutine)}"- # 存储回调函数- self._pending_callbacks[callback_id] = callback+ self._pendingCallbacks[callbackId] = callback- self.loop.create_task(self._runCoroutine(coroutine, callback_id))+ self.loop.create_task(self._runCoroutine(coroutine, callbackId))- return callback_id+ return callbackId- async def _runCoroutine(self, coroutine: Coroutine, callback_id):+ return ""++ async def _runCoroutine(self, coroutine: Coroutine, callbackId):try:result = await coroutine- callback = self._pending_callbacks.pop(callback_id)+ callback = self._pendingCallbacks.pop(callbackId)self._executeCallback(callback, result, None)except Exception as e:- callback = self._pending_callbacks.pop(callback_id)+ callback = self._pendingCallbacks.pop(callbackId)self._executeCallback(callback, None, repr(e))- async def _parseUrl(self, payload: dict, callback_id: str = None):+ def _executeCallback(self, callback: Callable, result: Any, error: str = None):+ """线程安全地执行回调函数++ 通过 Qt 的事件循环机制确保回调在主线程中执行,+ 避免子线程直接操作 UI 导致的崩溃问题。++ Args:+ callback: 回调函数+ result: 成功结果+ error: 错误信息+ """++ def wrapper():+ try:+ if asyncio.iscoroutinefunction(callback):+ self.loop.create_task(callback(result, error))+ else:+ callback(result, error)+ except Exception as e:+ errorMsg = f"回调函数执行失败: {str(e)}\n{traceback.format_exc()}"+ logger.exception(errorMsg)++ application = QApplication.instance()+ if application:+ QTimer.singleShot(0, application, wrapper)+ else:+ wrapper()++ async def _parseUrl(self, payload: dict, callbackId: str = None):"""内部异步方法:解析 URL 并通过线程安全方式调用回调Args:payload: 包含 url, headers, proxies 等信息的字典- callback_id: 回调函数标识符+ callbackId: 回调函数标识符"""try:url = payload.get('url', '')if not url:raise ValueError("URL 不能为空")-- # 从 FeatureService 获取对应的解析函数- parse_function = featureService.getParseFunction(url)- if parse_function is None:- raise ValueError(f"不支持的 URL 类型: {url}")-- # 执行解析- result = await parse_function(payload)-- # 通过线程安全方式调用回调- if callback_id and callback_id in self._pending_callbacks:- callback = self._pending_callbacks.pop(callback_id)++ parseFunction = parse++ result = await parseFunction(payload)++ if callbackId and callbackId in self._pendingCallbacks:+ callback = self._pendingCallbacks.pop(callbackId)self._executeCallback(callback, result, None)-+except Exception as e:- error_msg = f"解析 URL 失败: {str(e)}\n{traceback.format_exc()}"- # 在子线程中打印错误信息到终端- logger.exception(error_msg)-- if callback_id and callback_id in self._pending_callbacks:- callback = self._pending_callbacks.pop(callback_id)- self._executeCallback(callback, None, error_msg)+ errorMsg = f"解析 URL 失败: {str(e)}\n{traceback.format_exc()}"+ logger.exception(errorMsg)- def parseUrl(self, payload: dict, callback: Callable = None) -> str:- """线程安全的 URL 解析接口,仅使用回调函数-- Args:- payload: 包含解析所需信息的字典- 必须包含: url (str)- 可选包含: headers (dict), proxies (dict)- callback: 回调函数,签名应为 callback(result: dict, error: str = None)-- Returns:- str: 操作标识符,可用于追踪该解析请求- """- if not self.loop or not self.loop.is_running():- raise RuntimeError("CoreService 事件循环未运行")-- if callback is None:- raise ValueError("必须提供回调函数")-- # 生成回调标识符- callback_id = f"parse_{id(callback)}_{hash(str(payload))}"-- # 存储回调函数- self._pending_callbacks[callback_id] = callback-- # 在事件循环中调度解析任务- self.loop.create_task(self._parseUrl(payload, callback_id))-- return callback_id+ if callbackId and callbackId in self._pendingCallbacks:+ callback = self._pendingCallbacks.pop(callbackId)+ self._executeCallback(callback, None, errorMsg)++ def parseUrl(self, payload: dict, callback: Callable) -> str:+ callbackId = f"parse_{id(callback)}_{hash(payload)}"+ self._pendingCallbacks[callbackId] = callback++ self.loop.create_task(self._parseUrl(payload, callbackId))++ return callbackIdasync def _createTask(self, payload: dict) -> Task:"""内部异步方法:创建下载任务-+Args:payload: 包含任务创建信息的字典-+Returns:Task: 创建的任务对象"""@@ -127,7 +130,7 @@ class CoreService(QThread):# TODO: 实现具体的任务创建逻辑# 这里应该调用 FeatureService 获取相应的任务创建函数# 然后执行任务创建流程-+# 示例实现task_data = {'title': payload.get('filename', '未知文件'),@@ -137,15 +140,30 @@ class CoreService(QThread):'download_path': payload.get('downloadPath', '')}}-+task = Task(**task_data)self.tasks.add(task)-+return task-++ except Exception as e:+ error_msg = f"创建任务失败: {str(e)}\n{traceback.format_exc()}"+ raise e++ async def _createTaskWithCallback(self, payload: dict, callbackId: str):+ """带回调的任务创建包装方法"""+ try:+ task = await self._createTask(payload)+ if callbackId in self._pendingCallbacks:+ callback = self._pendingCallbacks.pop(callbackId)+ self._executeCallback(callback, task, None)except Exception as e:error_msg = f"创建任务失败: {str(e)}\n{traceback.format_exc()}"- raise+ logger.exception(error_msg)++ if callbackId in self._pendingCallbacks:+ callback = self._pendingCallbacks.pop(callbackId)+ self._executeCallback(callback, None, str(e))def createTask(self, payload: dict, callback: Callable = None) -> str:"""线程安全的任务创建接口,使用回调函数@@ -164,31 +182,15 @@ class CoreService(QThread):raise ValueError("必须提供回调函数")# 生成回调标识符- callback_id = f"create_{id(callback)}_{hash(str(payload))}"+ callbackId = f"create_{id(callback)}_{hash(str(payload))}"# 存储回调函数- self._pending_callbacks[callback_id] = callback+ self._pendingCallbacks[callbackId] = callback# 在事件循环中调度任务创建- self.loop.create_task(self._createTaskWithCallback(payload, callback_id))+ self.loop.create_task(self._createTaskWithCallback(payload, callbackId))- return callback_id-- async def _createTaskWithCallback(self, payload: dict, callback_id: str):- """带回调的任务创建包装方法"""- try:- task = await self._createTask(payload)- if callback_id in self._pending_callbacks:- callback = self._pending_callbacks.pop(callback_id)- self._executeCallback(callback, task, None)- except Exception as e:- error_msg = f"创建任务失败: {str(e)}\n{traceback.format_exc()}"- # 在子线程中打印错误信息到终端- logger.exception(error_msg)-- if callback_id in self._pending_callbacks:- callback = self._pending_callbacks.pop(callback_id)- self._executeCallback(callback, None, str(e))+ return callbackIddef getAllTaskInfo(self) -> set:"""获取所有任务信息@@ -198,62 +200,34 @@ class CoreService(QThread):"""return self.tasks.copy()- def getTaskById(self, task_id: str) -> Task:- """根据任务ID获取任务对象+ def getTaskById(self, taskId: str) -> Task | None:+ """根据任务Id获取任务对象Args:- task_id: 任务ID+ taskId: 任务IdReturns:Task: 对应的任务对象,如果不存在则返回None"""for task in self.tasks:- if task.taskId == task_id:+ if task.taskId == taskId:return taskreturn None- def removeCallback(self, callback_id: str) -> bool:+ def removeCallback(self, callbackId: str) -> bool:"""移除待执行的回调函数Args:- callback_id: 回调函数标识符+ callbackId: 回调函数标识符Returns:bool: 是否成功移除"""- if callback_id in self._pending_callbacks:- del self._pending_callbacks[callback_id]+ if callbackId in self._pendingCallbacks:+ del self._pendingCallbacks[callbackId]return Truereturn False- def _executeCallback(self, callback: Callable, result: Any, error: str = None):- """线程安全地执行回调函数-- 通过 Qt 的事件循环机制确保回调在主线程中执行,- 避免子线程直接操作 UI 导致的崩溃问题。-- Args:- callback: 回调函数- result: 成功结果- error: 错误信息- """- def wrapper():- try:- if asyncio.iscoroutinefunction(callback):- # 如果是协程函数,在事件循环中执行- self.loop.create_task(callback(result, error))- else:- # 普通函数直接调用- callback(result, error)- except Exception as e:- errorMsg = f"回调函数执行失败: {str(e)}\n{traceback.format_exc()}"- logger.exception(errorMsg)-- if QApplication.instance():- QTimer.singleShot(0, QApplication.instance(), wrapper)- else:- wrapper()-async def main(self):"""主事件循环@@ -270,7 +244,6 @@ class CoreService(QThread):await asyncio.sleep(1)except asyncio.CancelledError:- # 优雅退出breakexcept Exception as e:print(f"主循环发生错误: {e}")@@ -289,19 +262,12 @@ class CoreService(QThread):def stop(self):"""停止服务"""if self.loop and self.loop.is_running():- # 取消主循环任务if hasattr(self, 'mainLoop') and not self.mainLoop.done():self.mainLoop.cancel()-- # 关闭事件循环+self.loop.call_soon_threadsafe(self.loop.stop)- # def isRunning(self) -> bool:- # """检查服务是否正在运行- #- # Returns:- # bool: 服务运行状态- # """- # return self.loop is not None and self.loop.is_running()+ self._pendingCallbacks.clear()+ self.tasks.clear()coreService = CoreService()diff --git a/app/services/feature_service.py b/app/services/feature_service.pyindex 12c949d8..1eba5c02 100644--- a/app/services/feature_service.py+++ b/app/services/feature_service.py@@ -4,6 +4,8 @@ import importlib.utilfrom typing import TYPE_CHECKING, Dict, Any, Callablefrom pathlib import Path+from app.bases.interfaces import FeaturePack+if TYPE_CHECKING:from app.view.windows.main_window import MainWindow@@ -12,120 +14,125 @@ class FeatureService:"""从 features 文件夹加载 features pack, 当 CoreService 询问时, 返回对应动态加载的函数"""def __init__(self):- self.parseFunction: Dict[str, Callable] = {}- self.availableTask: Dict[str, Any] = {}+ # self.parseFunction: Dict[str, Callable] = {}+ # self.availableTask: Dict[str, Any] = {}self.loadedPacks: Dict[str, Any] = {}self.featuresPath = Path(__file__).parent.parent.parent / "features"- def getParseFunction(self, url: str):- """返回对应 url 的解析函数"""- # TODO: 实现 URL 匹配逻辑,返回对应的解析函数- return None-- def getAvailableTask(self):- # TODO: 实现获取可用任务类型的逻辑- return self.availableTask+ # def getParseFunction(self, url: str):+ # """返回对应 url 的解析函数"""+ # # TODO: 实现 URL 匹配逻辑,返回对应的解析函数+ # return None+ #+ # def getAvailableTask(self):+ # # TODO: 实现获取可用任务类型的逻辑+ # return self.availableTaskdef discoverFeaturePacks(self) -> list:"""发现 features 文件夹中的所有 feature packs"""featurePacks = []-+if not self.featuresPath.exists():print(f"警告: features 文件夹不存在: {self.featuresPath}")return featurePacks-- # 遍历 features 目录下的所有子目录+for item in self.featuresPath.iterdir():- if item.is_dir() and not item.name.startswith('.'):+ if item.is_dir() and not item.name.startswith("."):packPath = item / "pack.py"if packPath.exists():- featurePacks.append({- 'name': item.name,- 'path': str(packPath),- 'directory': str(item)- })-+ featurePacks.append(+ {+ "name": item.name,+ "path": str(packPath),+ "directory": str(item),+ }+ )+return featurePacksdef loadFeaturePack(self, packInfo: dict, mainWindow: "MainWindow"):"""加载单个 feature pack"""try:- # 动态导入 pack.py 模块+ packageName = packInfo["name"]+ moduleName = f"{packageName}.pack"+spec = importlib.util.spec_from_file_location(- f"feature_pack_{packInfo['name']}",- packInfo['path']+ moduleName,+ packInfo["path"],+ submodule_search_locations=[packInfo["directory"]],)-+if spec is None or spec.loader is None:print(f"错误: 无法加载 feature pack: {packInfo['name']}")return False-+module = importlib.util.module_from_spec(spec)-- # 添加模块到 sys.path 以便相对导入- sys.path.insert(0, packInfo['directory'])+try:+ sys.modules[moduleName] = modulespec.loader.exec_module(module)- finally:- # 移除临时添加的路径- if packInfo['directory'] in sys.path:- sys.path.remove(packInfo['directory'])-- # 查找 FeaturePackBase 的子类- from app.bases.interfaces import FeaturePackBase-+ except Exception as e:+ if moduleName in sys.modules:+ del sys.modules[moduleName]+ raise e+featurePackClass = Nonefor attrName in dir(module):attr = getattr(module, attrName)- if (isinstance(attr, type) and- issubclass(attr, FeaturePackBase) and- attr != FeaturePackBase):+ if (+ isinstance(attr, type)+ and issubclass(attr, FeaturePack)+ and attr != FeaturePack+ ):featurePackClass = attrbreak-+if featurePackClass is None:- print(f"警告: 在 {packInfo['name']} 中未找到 FeaturePackBase 的子类")+ print(f"警告: 在 {packInfo['name']} 中未找到 FeaturePack 的子类")return False-- # 实例化并加载 feature pack+packInstance = featurePackClass()packInstance.load(mainWindow)-- # 保存加载的 pack 信息- self.loadedPacks[packInfo['name']] = {- 'instance': packInstance,- 'module': module,- 'class': featurePackClass++ self.loadedPacks[packInfo["name"]] = {+ "instance": packInstance,+ "module": module,+ "class": featurePackClass,}-+print(f"✓ 成功加载 feature pack: {packInfo['name']}")return True-+except Exception as e:+ moduleName = f"{packInfo['name']}.pack"+ if moduleName in sys.modules:+ del sys.modules[moduleName]print(f"✗ 加载 feature pack 失败 {packInfo['name']}: {str(e)}")import traceback+traceback.print_exc()return Falsedef loadFeatures(self, mainWindow: "MainWindow"):"""从 ./features 文件夹自动发现并加载所有 feature packs"""print("开始加载 feature packs...")-- # 发现所有 feature packs+featurePacks = self.discoverFeaturePacks()-+if not featurePacks:print("未发现任何 feature packs")return-- print(f"发现 {len(featurePacks)} 个 feature packs: {[pack['name'] for pack in featurePacks]}")-- # 加载每个 feature pack++ print(+ f"发现 {len(featurePacks)} 个 feature packs: {[pack['name'] for pack in featurePacks]}"+ )+loadedCount = 0for packInfo in featurePacks:if self.loadFeaturePack(packInfo, mainWindow):loadedCount += 1-+print(f"feature packs 加载完成: {loadedCount}/{len(featurePacks)} 个成功加载")+featureService = FeatureService()diff --git a/app/supports/utils.py b/app/supports/utils.pyindex b938ab3d..a1f8f9c7 100644--- a/app/supports/utils.py+++ b/app/supports/utils.py@@ -71,6 +71,7 @@ def getSystemProxy():if proxyEnable:proxyServer, _ = winreg.QueryValueEx(key, "ProxyServer")+ # TODO http=10.1.1.1:8080;https=10.1.1.1:8080if "http=" in proxyServer:proxyServer = proxyServer.split(";")[0].split("=")[1]diff --git a/app/view/components/add_task_dialog.py b/app/view/components/add_task_dialog.pyindex aa6fa8ed..595fcc4b 100644--- a/app/view/components/add_task_dialog.py+++ b/app/view/components/add_task_dialog.py@@ -9,7 +9,9 @@ from app.services.core_service import coreServicefrom app.supports.config import cfg, DEFAULT_HEADERSfrom app.supports.utils import getProxiesfrom app.view.components.card_widgets import ParseResultHeaderCardWidget, SettingHeaderCardWidget-from app.view.components.cards import ResultCardBase+from app.view.components.cards import ResultCard+from features.http_pack.cards import HttpResultCard+from features.http_pack.task import HttpTaskclass AddTaskDialog(MessageBoxBase):@@ -35,7 +37,7 @@ class AddTaskDialog(MessageBoxBase):# self.parseResultGroup.hide()for i in range(5):self.parseResultGroup.addWidget(- ResultCardBase(f"DingTalk-{i}.avi", 123456789, "https://example.com/DingTalk.exe", self.parseResultGroup))+ HttpResultCard(HttpTask(title="DingTalk-{i}.avi", fileSize=123456789, url="https://example.com/DingTalk.exe"), self.parseResultGroup))def initWidget(self):self.setObjectName("AddTaskDialog")@@ -62,8 +64,7 @@ class AddTaskDialog(MessageBoxBase):urls = self.urlEdit.toPlainText().strip().split("\n")headers = DEFAULT_HEADERSproxies = getProxies()-- # 清空之前的解析结果+self.parseResultGroup.clearResults()for url in urls:@@ -79,7 +80,7 @@ class AddTaskDialog(MessageBoxBase):coreService.parseUrl(payload, self._handleParseResult)except Exception as e:print(f"提交解析请求失败: {e}")-+def _handleParseResult(self, result: dict, error: str = None):"""处理 URL 解析结果的回调函数@@ -94,15 +95,16 @@ class AddTaskDialog(MessageBoxBase):returnif result:+ # TODO 直接改成 Task# 提取解析结果filename = result.get('filename', '未知文件')file_size = result.get('fileSize', 0)url = result.get('url', '')# 添加到界面- self.addParseResult(filename, file_size, url)+ self.addHttpParseResult(filename, file_size, url)- def addParseResult(self, filename: str, fileSize: int, url: str):+ def addHttpParseResult(self, filename: str, fileSize: int, url: str) -> ResultCard | None:"""添加解析结果卡片到滚动区域Args:@@ -111,10 +113,10 @@ class AddTaskDialog(MessageBoxBase):url: 下载链接Returns:- ResultCardBase: 创建的结果卡片对象+ ResultCard: 创建的结果卡片对象"""try:- resultCard = ResultCardBase(filename, fileSize, url, self.parseResultGroup)+ resultCard = ResultCard(filename, fileSize, url, self.parseResultGroup)self.parseResultGroup.addWidget(resultCard)return resultCardexcept Exception as e:@@ -133,6 +135,7 @@ class AddTaskDialog(MessageBoxBase):cls._instance.exec()def closeEvent(self, e):+ print(1111)self.urlEdit.clear()self.parseResultGroup.clearResults()return super().closeEvent(e)diff --git a/app/view/components/card_widgets.py b/app/view/components/card_widgets.pyindex 05103eef..ae1881f7 100644--- a/app/view/components/card_widgets.py+++ b/app/view/components/card_widgets.py@@ -3,7 +3,7 @@ from PySide6.QtGui import QFont, QColor, QPainterfrom PySide6.QtWidgets import QWidget, QVBoxLayout, QLabelfrom qfluentwidgets import ScrollArea, setFont, isDarkTheme, CardGroupWidget-from app.view.components.cards import ResultCardBase, GroupSettingCard+from app.view.components.cards import ResultCard, GroupSettingCardclass HeaderCardWidgetBase(QWidget):@@ -82,7 +82,7 @@ class ParseResultHeaderCardWidget(HeaderCardWidgetBase):results = []for i in range(self.scrollLayout.count()):widget = self.scrollLayout.itemAt(i).widget()- if isinstance(widget, ResultCardBase):+ if isinstance(widget, ResultCard):results.append(widget.getData())return resultsdiff --git a/app/view/components/cards.py b/app/view/components/cards.pyindex b88febee..9dd9421e 100644--- a/app/view/components/cards.py+++ b/app/view/components/cards.py@@ -1,103 +1,22 @@from PySide6.QtCore import Qt, QEvent, QFileInfo, Signalfrom PySide6.QtGui import QMouseEvent, QColor, QPainter, QPen-from PySide6.QtWidgets import QWidget, QHBoxLayout, QFileIconProvider, QVBoxLayout+from PySide6.QtWidgets import QWidget, QHBoxLayout, QFileIconProviderfrom qfluentwidgets import ImageLabel, StrongBodyLabel, LineEdit, BodyLabel, isDarkTheme, CardWidget, CheckBox, \- themeColor, FluentIcon, PrimaryToolButton, ToolButton, TransparentToolButton, ProgressBar, IconWidget, CaptionLabel+ themeColor, IconWidgetfrom app.bases.models import Taskfrom app.supports.utils import getReadableSizefrom app.view.components.dialogs import DeleteTaskDialog-from app.view.components.labels import IconBodyLabel-class ResultCardBase(QWidget):+class ResultCard(QWidget):"""显示下载链接解析结果的卡片组件"""- def __init__(self, filename: str, fileSize: int, url: str, parent: QWidget = None):+ def __init__(self, task: Task, parent: QWidget = None):super().__init__(parent)- self.filename = filename- self.fileSize = fileSize- self.url = url+ self.task = taskself.borderRadius = 5- self.iconLabel = ImageLabel(self)- self.filenameLabel = StrongBodyLabel(filename, self)- self.filenameEdit = LineEdit(self)- self.sizeLabel = BodyLabel(getReadableSize(fileSize), self)- self.mainLayout = QHBoxLayout(self)-- self.initWidget()- self.initLayout()-- def initWidget(self):- """初始化组件属性"""- self.setFixedHeight(35)- self.resetFileIcon()- # 设置文件名标签- self.filenameLabel.setCursor(Qt.CursorShape.PointingHandCursor)- self.filenameLabel.installEventFilter(self)- # 设置编辑框- self.filenameEdit.setText(self.filename)- self.filenameEdit.editingFinished.connect(self._onEditingFinished)- self.filenameEdit.hide()-- def initLayout(self):- """初始化布局"""- self.mainLayout.setContentsMargins(10, 2, 10, 2)- self.mainLayout.setSpacing(12)- self.mainLayout.addWidget(self.iconLabel)- self.mainLayout.addWidget(self.filenameLabel)- self.mainLayout.addWidget(self.filenameEdit)- self.mainLayout.addStretch()- self.mainLayout.addWidget(self.sizeLabel)-- def eventFilter(self, obj, event: QEvent):- """事件过滤器,处理双击事件"""- if obj is self.filenameLabel:- if event.type() == QEvent.Type.MouseButtonDblClick and isinstance(event, QMouseEvent):- if event.button() == Qt.MouseButton.LeftButton:- self._enterEditMode()- return True- return super().eventFilter(obj, event)-- def resetFileIcon(self):- icon = QFileIconProvider().icon(QFileInfo(self.filename))- self.iconLabel.setImage(icon.pixmap(16, 16))- self.iconLabel.setFixedSize(16, 16)-- def _enterEditMode(self):- """进入编辑模式"""- self.filenameLabel.hide()- self.filenameEdit.show()- self.filenameEdit.setFocus()- self.filenameEdit.selectAll()-- def _onEditingFinished(self):- """编辑完成回调"""- newFilename = self.filenameEdit.text().strip()- if newFilename and newFilename != self.filename:- self.filename = newFilename- self.filenameLabel.setText(newFilename)- self.resetFileIcon()-- self.filenameEdit.hide()- self.filenameLabel.show()- self.filenameLabel.setFocus()-- def getData(self) -> dict:- """获取卡片数据"""- return {- "filename": self.filename,- "file_size": self.fileSize,- "url": self.url- }-- def setFilename(self, filename: str):- """设置文件名"""- self.filename = filename- self.filenameLabel.setText(filename)- self.filenameEdit.setText(filename)-@propertydef backgroundColor(self):return QColor(255, 255, 255, 13 if isDarkTheme() else 200)@@ -154,7 +73,7 @@ class GroupSettingCard(QWidget):painter.drawLine(self.rect().topLeft(), self.rect().topRight())-class TaskCardBase(CardWidget):+class TaskCard(CardWidget):""" Task card base class """deleted = Signal(str) # Send Task ID@@ -226,55 +145,3 @@ class TaskCardBase(CardWidget):return super().paintEvent(e)--class TaskCard(TaskCardBase):- """ Task card """- def __init__(self, task: Task, parent=None):- super().__init__(parent)- self.task = task- self.setFixedHeight(60)-- self.hBoxLayout = QHBoxLayout(self)- self.iconLabel = ImageLabel(QFileIconProvider().icon(QFileInfo("C:/Users/XiaoYouChR/Videos/Captures/反恐精英:全球攻势 2025-11-09 12-51-21.mp4")).pixmap(48, 48), self)- # TODO macOS- self.iconLabel.setFixedSize(48, 48)-- self.infoVBoxLayout = QVBoxLayout(self)- self.filenameLabel = StrongBodyLabel(self.task.title, self)- self.infoLayout = QHBoxLayout(self)- self.speedLabel = IconBodyLabel("0.00MB/s", FluentIcon.SPEED_HIGH, self)- self.leftTimeLabel = IconBodyLabel("00:00:00", FluentIcon.STOP_WATCH, self)- self.progressLabel = IconBodyLabel("2.22MB/342.12MB", FluentIcon.LIBRARY, self)- self.pauseButton = PrimaryToolButton(FluentIcon.PAUSE, self)- self.openFileButton = ToolButton(FluentIcon.LINK, self)- self.openFolderButton = ToolButton(FluentIcon.FOLDER, self)- self.cancelButton = TransparentToolButton(FluentIcon.CLOSE, self)- self.progressBar = ProgressBar(self)- self.progressBar.setCustomBackgroundColor(QColor(0, 0, 0, 0), QColor(0, 0, 0, 0))- # init- self.initLayout()- # TODO For Test- self.progressBar.setValue(24)-- def initLayout(self):- self.hBoxLayout.addWidget(self.checkBox)- self.hBoxLayout.addWidget(self.iconLabel)-- self.infoVBoxLayout.addWidget(self.filenameLabel)- self.infoLayout.addWidget(self.speedLabel)- self.infoLayout.addWidget(self.leftTimeLabel)- self.infoLayout.addWidget(self.progressLabel)- self.infoVBoxLayout.addLayout(self.infoLayout)- self.infoVBoxLayout.setContentsMargins(2, 8, 2, 8)- self.hBoxLayout.addLayout(self.infoVBoxLayout)- self.hBoxLayout.addStretch()- self.hBoxLayout.addWidget(self.pauseButton)- self.hBoxLayout.addWidget(self.openFileButton)- self.hBoxLayout.addWidget(self.openFolderButton)- self.hBoxLayout.addWidget(self.cancelButton)-- self.hBoxLayout.setContentsMargins(12, 0, 12, 0)-- def resizeEvent(self, e):- self.progressBar.setGeometry(4, self.height() - 4, self.width() - 8, 4)- return super().resizeEvent(e)diff --git a/app/view/pages/task_page.py b/app/view/pages/task_page.pyindex 2891cc17..f284336c 100644--- a/app/view/pages/task_page.py+++ b/app/view/pages/task_page.py@@ -8,7 +8,8 @@ from qfluentwidgets import ScrollArea, FlowLayout, setFont, TitleLabel, PrimaryPDropDownToolButtonfrom app.view.components.labels import IconBodyLabel-from app.view.components.cards import TaskCardBase, TaskCard+from app.view.components.cards import TaskCard+from features.http_pack.cards import HttpTaskCardfrom app.bases.models import Task@@ -124,7 +125,7 @@ class TaskPage(ScrollArea):# TODO create for testself.cards = []for i in range(10):- self.cards.append(TaskCard(Task(title=f"DingTalk-{i}.avi"), self))+ self.cards.append(HttpTaskCard(Task(title=f"DingTalk-{i}.avi"), self))self.cards[-1].setObjectName(f"testCard{i}")self.viewLayout.addWidget(self.cards[-1], alignment=Qt.AlignmentFlag.AlignTop)diff --git a/features/http_pack/cards.py b/features/http_pack/cards.pynew file mode 100644index 00000000..e7dc9228--- /dev/null+++ b/features/http_pack/cards.py@@ -0,0 +1,150 @@+from PySide6.QtCore import QFileInfo, Qt, QEvent+from PySide6.QtGui import QColor, QMouseEvent+from PySide6.QtWidgets import QHBoxLayout, QFileIconProvider, QVBoxLayout, QWidget+from qfluentwidgets import ImageLabel, StrongBodyLabel, FluentIcon, PrimaryToolButton, ToolButton, \+ TransparentToolButton, ProgressBar, LineEdit, BodyLabel++from app.bases.models import Task+from app.supports.utils import getReadableSize+from app.view.components.cards import TaskCard, ResultCard+from app.view.components.labels import IconBodyLabel+from features.http_pack.task import HttpTask+++class HttpTaskCard(TaskCard):+ """ Task card """+ def __init__(self, task: Task, parent=None):+ super().__init__(parent)+ self.task = task+ self.setFixedHeight(60)++ self.hBoxLayout = QHBoxLayout(self)+ self.iconLabel = ImageLabel(QFileIconProvider().icon(QFileInfo("C:/Users/XiaoYouChR/Videos/Captures/反恐精英:全球攻势 2025-11-09 12-51-21.mp4")).pixmap(48, 48), self)+ # TODO macOS+ self.iconLabel.setFixedSize(48, 48)++ self.infoVBoxLayout = QVBoxLayout(self)+ self.filenameLabel = StrongBodyLabel(self.task.title, self)+ self.infoLayout = QHBoxLayout(self)+ self.speedLabel = IconBodyLabel("0.00MB/s", FluentIcon.SPEED_HIGH, self)+ self.leftTimeLabel = IconBodyLabel("00:00:00", FluentIcon.STOP_WATCH, self)+ self.progressLabel = IconBodyLabel("2.22MB/342.12MB", FluentIcon.LIBRARY, self)+ self.pauseButton = PrimaryToolButton(FluentIcon.PAUSE, self)+ self.openFileButton = ToolButton(FluentIcon.LINK, self)+ self.openFolderButton = ToolButton(FluentIcon.FOLDER, self)+ self.cancelButton = TransparentToolButton(FluentIcon.CLOSE, self)+ self.progressBar = ProgressBar(self)+ self.progressBar.setCustomBackgroundColor(QColor(0, 0, 0, 0), QColor(0, 0, 0, 0))+ # init+ self.initLayout()+ # TODO For Test+ self.progressBar.setValue(24)++ def initLayout(self):+ self.hBoxLayout.addWidget(self.checkBox)+ self.hBoxLayout.addWidget(self.iconLabel)++ self.infoVBoxLayout.addWidget(self.filenameLabel)+ self.infoLayout.addWidget(self.speedLabel)+ self.infoLayout.addWidget(self.leftTimeLabel)+ self.infoLayout.addWidget(self.progressLabel)+ self.infoVBoxLayout.addLayout(self.infoLayout)+ self.infoVBoxLayout.setContentsMargins(2, 8, 2, 8)+ self.hBoxLayout.addLayout(self.infoVBoxLayout)+ self.hBoxLayout.addStretch()+ self.hBoxLayout.addWidget(self.pauseButton)+ self.hBoxLayout.addWidget(self.openFileButton)+ self.hBoxLayout.addWidget(self.openFolderButton)+ self.hBoxLayout.addWidget(self.cancelButton)++ self.hBoxLayout.setContentsMargins(12, 0, 12, 0)++ def resizeEvent(self, e):+ self.progressBar.setGeometry(4, self.height() - 4, self.width() - 8, 4)+ return super().resizeEvent(e)+++class HttpResultCard(ResultCard):+ def __init__(self, task: HttpTask, parent: QWidget = None):+ super().__init__(task, parent)+ self.filename = task.title+ self.fileSize = task.fileSize+ self.url = task.url++ self.iconLabel = ImageLabel(self)+ self.filenameLabel = StrongBodyLabel(self.filename, self)+ self.filenameEdit = LineEdit(self)+ self.sizeLabel = BodyLabel(getReadableSize(self.fileSize), self)+ self.mainLayout = QHBoxLayout(self)++ self.initWidget()+ self.initLayout()++ def initWidget(self):+ """初始化组件属性"""+ self.setFixedHeight(35)+ self.resetFileIcon()+ # 设置文件名标签+ self.filenameLabel.setCursor(Qt.CursorShape.PointingHandCursor)+ self.filenameLabel.installEventFilter(self)+ # 设置编辑框+ self.filenameEdit.setText(self.filename)+ self.filenameEdit.editingFinished.connect(self._onEditingFinished)+ self.filenameEdit.hide()++ def initLayout(self):+ """初始化布局"""+ self.mainLayout.setContentsMargins(10, 2, 10, 2)+ self.mainLayout.setSpacing(12)+ self.mainLayout.addWidget(self.iconLabel)+ self.mainLayout.addWidget(self.filenameLabel)+ self.mainLayout.addWidget(self.filenameEdit)+ self.mainLayout.addStretch()+ self.mainLayout.addWidget(self.sizeLabel)++ def eventFilter(self, obj, event: QEvent):+ """事件过滤器,处理双击事件"""+ if obj is self.filenameLabel:+ if event.type() == QEvent.Type.MouseButtonDblClick and isinstance(event, QMouseEvent):+ if event.button() == Qt.MouseButton.LeftButton:+ self._enterEditMode()+ return True+ return super().eventFilter(obj, event)++ def resetFileIcon(self):+ icon = QFileIconProvider().icon(QFileInfo(self.filename))+ self.iconLabel.setImage(icon.pixmap(16, 16))+ self.iconLabel.setFixedSize(16, 16)++ def _enterEditMode(self):+ """进入编辑模式"""+ self.filenameLabel.hide()+ self.filenameEdit.show()+ self.filenameEdit.setFocus()+ self.filenameEdit.selectAll()++ def _onEditingFinished(self):+ """编辑完成回调"""+ newFilename = self.filenameEdit.text().strip()+ if newFilename and newFilename != self.filename:+ self.filename = newFilename+ self.filenameLabel.setText(newFilename)+ self.resetFileIcon()++ self.filenameEdit.hide()+ self.filenameLabel.show()+ self.filenameLabel.setFocus()++ def getData(self) -> dict:+ """获取卡片数据"""+ return {+ "filename": self.filename,+ "file_size": self.fileSize,+ "url": self.url+ }++ def setFilename(self, filename: str):+ """设置文件名"""+ self.filename = filename+ self.filenameLabel.setText(filename)+ self.filenameEdit.setText(filename)diff --git a/features/http_pack/const.py b/features/http_pack/const.pynew file mode 100644index 00000000..40cb8e74--- /dev/null+++ b/features/http_pack/const.py@@ -0,0 +1,6 @@+from enum import IntEnum+++class SpecialFileSize(IntEnum):+ NOT_SUPPORTED = -1+ UNKNOWN = 0diff --git a/features/http_pack/pack.py b/features/http_pack/pack.pyindex 063e940d..da4f11a0 100644--- a/features/http_pack/pack.py+++ b/features/http_pack/pack.py@@ -1,15 +1,133 @@-from app.bases.interfaces import FeaturePackBase-from typing import TYPE_CHECKING+import re+from email.message import Message+from enum import Enum+from mimetypes import guess_extension+from time import time_ns+from urllib.parse import unquote, urlparse, parse_qs-if TYPE_CHECKING:- from app.view.windows.main_window import MainWindow+from loguru import logger+from app.bases.interfaces import FeaturePack+from .cards import HttpTaskCard, HttpResultCard-class HttpPack(FeaturePackBase):- """HTTP 下载功能包"""-- def load(self, mainWindow: "MainWindow"):- """加载 HTTP 下载功能"""- # 这里可以添加 HTTP 下载相关的界面或功能- print("HTTP Pack 已加载 - 提供 HTTP/HTTPS 链接解析和下载功能")- # TODO: 实现具体的 HTTP 下载界面和功能\ No newline at end of file+import niquests++from .const import SpecialFileSize+from .task import HttpTask+++def _extractFileName(url: str, headers: dict) -> str:++ fileName = ""++ # Content-Disposition (RFC 6266/5987)+ cd = headers.get("content-disposition", "")+ if cd:+ msg = Message()+ msg['Content-Disposition'] = cd+ params = msg.get_params(header='Content-Disposition')+ paramDict = {k.lower(): v for k, v in params if isinstance(v, str)}++ if "filename*" in paramDict:+ val = paramDict["filename*"] # charset'lang'encoded_text+ if "'" in val:+ parts = val.split("'", 2)+ if len(parts) == 3:+ encoding, _, encodedText = parts+ fileName = unquote(encodedText, encoding=encoding or "utf-8")+ logger.info(f"方案 A 获取文件名: {fileName}")++ if not fileName and "filename" in paramDict:+ fileName = paramDict["filename"].strip("\"' ")+ logger.info(f"方案 B 获取文件名: {fileName}")++ # Content-Location (RFC 7231)+ if not fileName and "content-location" in headers:+ cl = headers["content-location"]+ fileName = unquote(urlparse(cl).path.split("/")[-1])+ logger.info(f"方案 C 获取文件名: {fileName}")++ # OSS/S3 覆盖响应头+ if not fileName:+ parsedUrl = urlparse(url)+ queryParams = parse_qs(parsedUrl.query)+ rcd = queryParams.get("response-content-disposition", [""])[0]+ if "filename=" in rcd.lower():+ match = re.search(r'filename\s*=\s*["\']?([^"\';]+)["\']?', rcd, re.IGNORECASE)+ if match:+ fileName = unquote(match.group(1)).strip("\"' ")+ logger.info(f"方案 D 获取文件名: {fileName}")++ # URL 路径解析+ if not fileName:+ path = urlparse(url).path+ if path and "/" in path:+ # 移除路径中的参数 (如 ;jsessionid=...)+ cleanPath = path.split(";")[0]+ fileName = unquote(cleanPath.split("/")[-1])+ logger.info(f"方案 E 获取文件名: {fileName}")++ # 兜底处理+ if not fileName:+ contentType = headers.get("content-type", "").split(";")[0].lower().strip()+ standardExt = guess_extension(contentType) or ""+ timestamp = int(time_ns())+ fileName = f"file_{timestamp}.{standardExt}"+ logger.info(f"方案 F 获取文件名: {fileName}")+ else:+ if "." not in fileName:+ contentType = headers.get("content-type", "").split(";")[0].lower().strip()+ standardExt = guess_extension(contentType) or ""+ fileName = f"{fileName}.{standardExt}"++ fileName = re.sub(r'[\x00-\x1f\\/:*?"<>|]', "_", fileName)+ if len(fileName) > 200:+ base, ext = (fileName.rsplit(".", 1) if "." in fileName else (fileName, ""))+ fileName = base[:190] + ("." + ext)++ return fileName.strip()++async def parse(payload: dict) -> HttpResultCard:+ url: str = payload['url']+ headers: dict = payload['payload']+ proxies: dict = payload['proxies']++ requestHeaders = headers.copy()+ requestHeaders["Range"] = "bytes=0-"++ # TODO verify config+ response = await niquests.aget(url, headers=requestHeaders, proxies=proxies, verify=False, allow_redirects=True, stream=True)+ response.raise_for_status()++ head = response.headers+ head = {k.lower(): v for k, v in head.items()}++ # 获取文件大小, 判断是否可以分块下载+ # 状态码为206才是范围请求,200表示服务器拒绝了范围请求同时将发送整个文件+ if response.status_code == 206 and "content-range" in head:+ # https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Reference/Headers/Content-Range+ _left, _char, right = head["content-range"].rpartition("/")++ if right != "*":+ fileSize = int(right)+ logger.info(+ f"content-range: {head['content-range']}, fileSize: {fileSize}, content-length: {head['content-length']}"+ )++ elif "content-length" in head:+ fileSize = int(head["content-length"])++ else:+ fileSize = SpecialFileSize.UNKNOWN+ logger.info("文件似乎支持续传,但无法获取文件大小")+ else:+ fileSize = SpecialFileSize.NOT_SUPPORTED+ logger.info("文件不支持续传")++ await response.aclose()++ # 获取文件名+ fileName = _extractFileName(response.url, head) # 这里取重定向之前的 URL 目的是更好的获取++ task = HttpTask(title=fileName, url=url, fileSize=fileSize, headers=headers)+ return HttpResultCard(task)diff --git a/features/http_pack/task.py b/features/http_pack/task.pynew file mode 100644index 00000000..2340a2d3--- /dev/null+++ b/features/http_pack/task.py@@ -0,0 +1,19 @@+from dataclasses import field, dataclass++from app.bases.interfaces import Worker+from app.bases.models import Task, TaskStage+from app.supports.config import DEFAULT_HEADERS+++class HttpTaskStage(TaskStage):+ ...++@dataclass+class HttpTask(Task):++ url: str+ fileSize: int+ headers: dict = field(default_factory=DEFAULT_HEADERS.copy)++class HttpWorker(Worker):+ ...diff --git a/features/jack_yao/pack.py b/features/jack_yao/pack.pyindex a955a6b3..4ea953e5 100644--- a/features/jack_yao/pack.py+++ b/features/jack_yao/pack.py@@ -8,7 +8,7 @@ from PySide6.QtGui import QPixmap, QColor, QDesktopServices, QPainterfrom PySide6.QtWidgets import QWidget, QVBoxLayout, QSizePolicy, QHBoxLayout, QFileDialogfrom loguru import logger-from app.bases.interfaces import FeaturePackBase+from app.bases.interfaces import FeaturePackfrom typing import TYPE_CHECKINGfrom app.services.core_service import coreService@@ -30,7 +30,7 @@ if TYPE_CHECKING:from app.view.windows.main_window import MainWindow-class JackYaoPack(FeaturePackBase):+class JackYaoPack(FeaturePack):def load(self, mainWindow:"MainWindow"):mainWindow.resourceInterface = ResourceInterface()