The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
refactor: 统一输出文件处理逻辑,简化代码结构
XiaoYouChR55f284485b94
diff --git a/app/bases/models.py b/app/bases/models.pyindex cd011785..dddb8f6e 100644--- a/app/bases/models.py+++ b/app/bases/models.py@@ -70,6 +70,10 @@ class TaskFile:@dataclass(kw_only=True)class TaskStage:_registry: ClassVar[Dict[str, Type["TaskStage"]]] = {}+ _TYPE_ALIASES: ClassVar[Dict[str, str]] = {+ "FtpTaskStage": "FtpStage",+ "BitTorrentTaskStage": "TaskStage",+ }workerType: ClassVar[Type["Worker"]]canPause: ClassVar[bool] = True@@ -146,7 +150,8 @@ class TaskStage:obj = dataif "type" in obj and isinstance(obj["type"], str):- stageCls = TaskStage._registry.get(obj["type"], cls)+ typeName = TaskStage._TYPE_ALIASES.get(obj["type"], obj["type"])+ stageCls = TaskStage._registry.get(typeName, cls)obj.pop("type", None)else:stageCls = cls@@ -386,8 +391,10 @@ class Task:obj["stages"] = stagesrawFiles = obj.pop("files", None)- if rawFiles is not None:+ if rawFiles is not None and targetCls is cls:obj["files"] = [TaskFile(**_filterDataclassKwargs(TaskFile, f)) for f in rawFiles]+ elif rawFiles is not None:+ obj["files"] = rawFilesreturn targetCls(**_filterDataclassKwargs(targetCls, obj))diff --git a/app/services/browser_service.py b/app/services/browser_service.pyindex da874d89..fafb4c5a 100644--- a/app/services/browser_service.py+++ b/app/services/browser_service.py@@ -243,8 +243,8 @@ class BrowserService(QObject):})def _serialize(self, task: Task) -> dict[str, Any]:- resolvePath = Path(task.outputFolder)- parentPath = resolvePath.parent+ outputFolder = Path(task.outputFolder)+ parentPath = outputFolder.parentstages = task.stagesprogress = (100.0 if task.status == TaskStatus.COMPLETED else 0.0@@ -259,12 +259,12 @@ class BrowserService(QObject):"fileSize": int(task.fileSize),"speed": sum(stage.speed for stage in stages),"createdAt": task.createdAt,- "resolvePath": str(resolvePath),+ "resolvePath": str(outputFolder),"parentPath": str(parentPath),"canPause": bool(task.canPause),- "canOpenFile": resolvePath.exists(),+ "canOpenFile": outputFolder.exists(),"canOpenFolder": parentPath.exists(),- "fileExt": resolvePath.suffix.lstrip(".").lower(),+ "fileExt": outputFolder.suffix.lstrip(".").lower(),"packName": packName,}diff --git a/app/services/core_service.py b/app/services/core_service.pyindex 02c8daad..eaa3f01e 100644--- a/app/services/core_service.py+++ b/app/services/core_service.py@@ -84,12 +84,15 @@ class CoreService(QThread):async def _runCoroutine(self, coroutine: Coroutine, callbackId):try:result = await coroutine- callback = self._pendingCallbacks.pop(callbackId)- self._executeCallback(callback, result, None)+ error = Noneexcept Exception as e:logger.opt(exception=e).error("异步任务执行失败 {}", callbackId)- callback = self._pendingCallbacks.pop(callbackId)- self._executeCallback(callback, None, repr(e))+ result = None+ error = repr(e)++ callback = self._pendingCallbacks.pop(callbackId, None)+ if callback is not None:+ self._executeCallback(callback, result, error)def _executeCallback(self, callback: Callable, result: Any, error: str = None):"""线程安全地执行回调函数diff --git a/app/view/components/cards.py b/app/view/components/cards.pyindex 52f1f621..1fce7b2d 100644--- a/app/view/components/cards.py+++ b/app/view/components/cards.py@@ -401,9 +401,9 @@ class UniversalTaskCard(TaskCard):if self.task.outputFolder:candidates.add(Path(self.task.outputFolder))for stage in self.task.stages:- resolvePath = getattr(stage, "resolvePath", None)- if resolvePath:- candidates.add(Path(resolvePath))+ outputFile = getattr(stage, "outputFile", None)+ if outputFile:+ candidates.add(Path(outputFile))for target in candidates:if not target:diff --git a/features/bittorrent_pack/task.py b/features/bittorrent_pack/task.pyindex eea1a05c..8815cea4 100644--- a/features/bittorrent_pack/task.py+++ b/features/bittorrent_pack/task.py@@ -183,6 +183,7 @@ class BTTask(Task):self.title = toSafeFilename(self.title, fallback="torrent")super().__post_init__()self.fileSize = sum(file.size for file in self.files if file.selected)+ self._updateSlot()@propertydef stage(self) -> TaskStage:diff --git a/features/ffmpeg_pack/task.py b/features/ffmpeg_pack/task.pyindex b6437d55..d8cdf73f 100644--- a/features/ffmpeg_pack/task.py+++ b/features/ffmpeg_pack/task.py@@ -83,8 +83,8 @@ class FFmpegWorker(Worker):if not ffmpeg or not ffprobe:raise RuntimeError("未找到可用的 ffmpeg 和 ffprobe,请先在设置中安装或配置 FFmpeg")- outputPath = Path(self.stage.outputFile)- outputPath.parent.mkdir(parents=True, exist_ok=True)+ outputFile = Path(self.stage.outputFile)+ outputFile.parent.mkdir(parents=True, exist_ok=True)process = NoneprogressTask = Nonediff --git a/features/ftp_pack/cards.py b/features/ftp_pack/cards.pyindex b6f22304..569f318a 100644--- a/features/ftp_pack/cards.py+++ b/features/ftp_pack/cards.py@@ -277,9 +277,9 @@ class FtpTaskCard(UniversalTaskCard):returnfor stage in self.task.stages:- resolvePath = stage.outputFile.strip()- if not resolvePath:+ outputFile = stage.outputFile.strip()+ if not outputFile:continue- target = Path(resolvePath)+ target = Path(outputFile)_removePath(target)_removePath(Path(str(target) + ".ghd"))diff --git a/features/ftp_pack/task.py b/features/ftp_pack/task.pyindex 97b72f0b..98ecb3e3 100644--- a/features/ftp_pack/task.py+++ b/features/ftp_pack/task.py@@ -271,21 +271,23 @@ class FtpTask(Task):super().applySettings(payload)if "proxies" in payload:self.proxies = payload["proxies"]- if "preBlockNum" in payload:- self.blockNum = payload["preBlockNum"]self.updateStagePaths()+ @propertydef canPause(self) -> bool:selectedStages = self.selectedStagesreturn bool(selectedStages) and all(stage.supportsRange for stage in selectedStages)def pendingStages(self):+ from app.supports.recorder import taskRecorder+self.stages.sort(key=lambda stage: stage.stageIndex)for stage in self.selectedStages:if self.status != TaskStatus.RUNNING:breakif stage.status == TaskStatus.COMPLETED:continue+ taskRecorder.flush()yield stageasync def run(self):diff --git a/features/http_pack/pack.py b/features/http_pack/pack.pyindex 31cb075f..f182eccd 100644--- a/features/http_pack/pack.py+++ b/features/http_pack/pack.py@@ -1,5 +1,6 @@import refrom email.message import Message+from email.utils import collapse_rfc2231_valuefrom mimetypes import guess_extensionfrom pathlib import Pathfrom time import time_ns@@ -123,20 +124,12 @@ def _fileName(url: str, headers: dict) -> str: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*"]- if "'" in val: # charset'lang'encoded_text- parts = val.split("'", 2)- if len(parts) == 3:- encoding, _, encodedText = parts- fileName = unquote(encodedText, encoding=encoding or "utf-8")-- if not fileName and "filename" in paramDict:- fileName = paramDict["filename"].strip("\"' ")+ msg["Content-Disposition"] = cd+ params = msg.get_params(header="Content-Disposition")+ paramDict = {k.lower(): v for k, v in params}+ fileName = collapse_rfc2231_value(+ paramDict.get("filename") or paramDict.get("filename*") or ""+ ).strip("\"' ")if not fileName and "content-location" in headers:cl = headers["content-location"]@@ -157,16 +150,14 @@ def _fileName(url: str, headers: dict) -> str:cleanPath = path.split(";")[0]fileName = unquote(cleanPath.split("/")[-1])+ contentType = headers.get("content-type", "").split(";", 1)[0].lower().strip()+ standardExt = guess_extension(contentType) if contentType else ""+ standardExt = standardExt or ""+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}"- else:- if "." not in fileName:- contentType = headers.get("content-type", "").split(";")[0].lower().strip()- standardExt = guess_extension(contentType) or ""- fileName = f"{fileName}.{standardExt}"+ fileName = f"file_{int(time_ns())}{standardExt}"+ elif "." not in fileName and standardExt:+ fileName = f"{fileName}{standardExt}"return toSafeFilename(fileName, fallback=f"file_{int(time_ns())}")@@ -185,13 +176,15 @@ class HttpPack(FeaturePack):blockNum: int = payload.get("preBlockNum", cfg.preBlockNum.value)path: Path = payload.get("path", Path(cfg.downloadFolder.value))- fileName = payload.get("filename") or ""+ fileName = str(payload.get("filename") or "").strip()fileSize = payload.get("fileSize") or SpecialFileSize.UNKNOWNsupportsRange = payload.get("supportsRange", False)if not fileName:fileSize, supportsRange, finalUrl, head = await _probe(url, headers, proxies)fileName = _fileName(finalUrl, head)+ else:+ fileName = toSafeFilename(fileName, fallback=f"file_{int(time_ns())}")task = Task(title=fileName,diff --git a/features/http_pack/task.py b/features/http_pack/task.pyindex 0e634bc8..290c900a 100644--- a/features/http_pack/task.py+++ b/features/http_pack/task.py@@ -299,9 +299,10 @@ class HttpWorker(Worker):self.subworkers.append(HttpSubworker(0, 0, SpecialFileSize.UNKNOWN))return- step = self.stage.fileSize // self.stage.blockNum+ blockNum = min(self.stage.blockNum, self.stage.fileSize)+ step = self.stage.fileSize // blockNumstart = 0- for i in range(self.stage.blockNum - 1):+ for _ in range(blockNum - 1):end = start + step - 1self.subworkers.append(HttpSubworker(start, start, end))start = end + 1diff --git a/features/m3u8_pack/task.py b/features/m3u8_pack/task.pyindex 2c0656d3..4bb1681b 100644--- a/features/m3u8_pack/task.py+++ b/features/m3u8_pack/task.py@@ -5,6 +5,7 @@ import sysfrom contextlib import suppressfrom dataclasses import dataclass, fieldfrom email.message import Message+from email.utils import collapse_rfc2231_valuefrom pathlib import Pathfrom typing import TYPE_CHECKINGfrom urllib.parse import parse_qs, unquote, urlparse@@ -81,12 +82,12 @@ def _title(url: str, headers: dict[str, str], extension: str) -> str:msg = Message()msg["Content-Disposition"] = cdparams = msg.get_params(header="Content-Disposition")- paramDict = {key.lower(): value for key, value in params if isinstance(value, str)}- if "filename*" in paramDict and "'" in paramDict["filename*"]:- encoding, _, encodedText = paramDict["filename*"].split("'", 2)- candidates.append(unquote(encodedText, encoding=encoding or "utf-8"))- elif "filename" in paramDict:- candidates.append(paramDict["filename"].strip("\"' "))+ paramDict = {key.lower(): value for key, value in params}+ fileName = collapse_rfc2231_value(+ paramDict.get("filename") or paramDict.get("filename*") or ""+ ).strip("\"' ")+ if fileName:+ candidates.append(fileName)parsedUrl = urlparse(url)query = parse_qs(parsedUrl.query)