The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
refactor: 重构三个模块 (#460)
XiaoYouChRf13c5d140ca9
diff --git a/app/bases/models.py b/app/bases/models.pyindex 30d2ea55..51d8928b 100644--- a/app/bases/models.py+++ b/app/bases/models.py@@ -129,9 +129,6 @@ class TaskStage:def updateOutputFile(self, taskPath: Path, taskTitle: str):pass- def onCompleted(self, task: "Task"):- pass-@classmethoddef fromFile(cls, file: TaskFile, task: "Task") -> "TaskStage":raise NotImplementedError@@ -330,7 +327,6 @@ class Task:currentStage = stageworker = stage.workerType(stage)await worker.run()- stage.onCompleted(self)except asyncio.CancelledError:logger.info("{} stopped", self.title)raisediff --git a/app/supports/utils.py b/app/supports/utils.pyindex e0919ecf..c620c99a 100644--- a/app/supports/utils.py+++ b/app/supports/utils.py@@ -1,4 +1,5 @@import re+import shutilimport sysfrom datetime import datetimefrom functools import wraps@@ -184,6 +185,17 @@ def toExecutable(name: str) -> str:return f"{name}.exe" if sys.platform == "win32" else name+def findExecutable(installFolder: Path, name: str, *subdirs: str) -> str:+ exe = toExecutable(name)+ candidates = [installFolder / sub / exe for sub in subdirs]+ candidates.append(installFolder / exe)+ for candidate in candidates:+ if candidate.is_file():+ return toPosixPath(candidate)+ found = shutil.which(name)+ return toPosixPath(found) if found else ""++def toBytes(value: str, unit: str) -> int:_SCALE = {"B": 1, "KB": 1024, "MB": 1024 ** 2, "GB": 1024 ** 3,"Bps": 1, "KBps": 1024, "MBps": 1024 ** 2, "GBps": 1024 ** 3}diff --git a/app/view/components/setting_cards.py b/app/view/components/setting_cards.pyindex 5b9f5c27..42d4ee9a 100644--- a/app/view/components/setting_cards.py+++ b/app/view/components/setting_cards.py@@ -23,6 +23,7 @@ from qfluentwidgets import (LineEdit,EditableComboBox,ToolButton,+ ToolTipFilter,)from app.supports.config import cfg@@ -294,6 +295,52 @@ class ProxySettingCard(ExpandGroupSettingCard):self.defaultRadioButton.setChecked(True)+class InstallFolderCard(SettingCard):+ pathChanged = Signal(str)++ def __init__(self, configItem: ConfigItem, defaultPath: str,+ title: str, browseTitle: str, parent=None):+ super().__init__(FluentIcon.FOLDER, title, configItem.value, parent)+ self.configItem = configItem+ self.defaultPath = defaultPath+ self.browseTitle = browseTitle+ self.chooseFolderButton = ToolButton(FluentIcon.FOLDER, self)+ self.restoreDefaultButton = ToolButton(FluentIcon.CANCEL, self)++ self._initWidget()+ self._initLayout()+ self._bind()++ def _initWidget(self):+ self.chooseFolderButton.setToolTip(self.tr("浏览文件夹"))+ self.chooseFolderButton.installEventFilter(ToolTipFilter(self.chooseFolderButton))+ self.restoreDefaultButton.setToolTip(self.tr("恢复默认路径"))+ self.restoreDefaultButton.installEventFilter(ToolTipFilter(self.restoreDefaultButton))++ def _initLayout(self):+ self.hBoxLayout.addWidget(self.chooseFolderButton, 0, Qt.AlignmentFlag.AlignRight)+ self.hBoxLayout.addSpacing(8)+ self.hBoxLayout.addWidget(self.restoreDefaultButton, 0, Qt.AlignmentFlag.AlignRight)+ self.hBoxLayout.addSpacing(16)++ def _bind(self):+ self.chooseFolderButton.clicked.connect(self._chooseFolder)+ self.restoreDefaultButton.clicked.connect(self._restoreDefault)++ def _updatePath(self, path: str):+ cfg.set(self.configItem, path)+ self.setContent(self.configItem.value)+ self.pathChanged.emit(self.configItem.value)++ def _chooseFolder(self):+ folder = QFileDialog.getExistingDirectory(self.window(), self.browseTitle)+ if folder:+ self._updatePath(folder)++ def _restoreDefault(self):+ self._updatePath(self.defaultPath)++class SelectFolderSettingCard(SettingCard):"""下载路径设置卡片组件,集成历史路径管理"""diff --git a/features/bili_pack/pack.py b/features/bili_pack/pack.pyindex 82e96944..69b8e703 100644--- a/features/bili_pack/pack.py+++ b/features/bili_pack/pack.py@@ -323,9 +323,6 @@ class BilibiliPack(FeaturePack):))task.addStage(BilibiliMergeStage(stageIndex=stageBase + 3,- videoPath="",- audioPath="",- outputFile="",pageIndex=index,pageSuffix=pageSuffix,))diff --git a/features/bili_pack/task.py b/features/bili_pack/task.pyindex fa4c0f02..cbd1bcfb 100644--- a/features/bili_pack/task.py+++ b/features/bili_pack/task.py@@ -40,6 +40,6 @@ class BilibiliMergeStage(FFmpegStage):def updateOutputFile(self, taskPath: Path, taskTitle: str):baseTitle = taskTitle[:-4] if taskTitle.lower().endswith(".mp4") else taskTitlestem = f"{baseTitle}{self.pageSuffix}" if self.pageSuffix else baseTitle- self.outputFile = str(taskPath / f"{stem}.mp4")- self.videoPath = str(taskPath / f"{stem}.video.m4s")- self.audioPath = str(taskPath / f"{stem}.audio.m4s")+ self.outputFile = taskPath / f"{stem}.mp4"+ self.videoPath = taskPath / f"{stem}.video.m4s"+ self.audioPath = taskPath / f"{stem}.audio.m4s"diff --git a/features/extract_pack/manifest.toml b/features/disk_pack/manifest.tomlsimilarity index 100%rename from features/extract_pack/manifest.tomlrename to features/disk_pack/manifest.tomldiff --git a/features/disk_pack/pack.py b/features/disk_pack/pack.pynew file mode 100644index 00000000..62dfba1c--- /dev/null+++ b/features/disk_pack/pack.py@@ -0,0 +1,72 @@+from pathlib import Path++from app.bases.interfaces import FeaturePack+from app.bases.models import Task+from app.supports.config import DEFAULT_HEADERS+from app.supports.utils import getProxies, toPosixPath+from .task import ExtractStage, InstallStage+++class DiskPack(FeaturePack):+ packId = "disk"+++async def buildToolInstallTask(+ *,+ packId: str,+ title: str,+ downloadUrl: str,+ fallbackAssetName: str,+ fallbackSize: int,+ installFolder: Path,+ executableNames: list[str],+ headers: dict[str, str] | None = None,+) -> Task:+ from app.services.feature_service import featureService++ downloadPayload = {+ "url": downloadUrl,+ "headers": (headers or DEFAULT_HEADERS).copy(),+ "proxies": getProxies(),+ "path": installFolder,+ }+ downloadTask = await featureService.parse(downloadPayload)+ if not downloadTask.stages:+ raise RuntimeError(f"解析 {fallbackAssetName} 下载链接后未获取到下载阶段")++ downloadStage = downloadTask.stages[0]+ archiveSize = downloadTask.fileSize if downloadTask.fileSize > 0 else fallbackSize+ assetName = downloadTask.title or fallbackAssetName+ archivePath = toPosixPath(installFolder / assetName)++ downloadStage.stageIndex = 1+ downloadStage.outputFile = archivePath++ task = Task(+ title=title,+ url=downloadTask.url,+ packId=packId,+ fileSize=archiveSize,+ path=installFolder,+ usesSlot=False,+ metadata={+ "installFolder": str(installFolder),+ "assetName": assetName,+ },+ )+ extractDir = toPosixPath(installFolder / ".extracting")+ task.addStage(downloadStage)+ task.addStage(ExtractStage(+ stageIndex=2,+ archivePath=archivePath,+ outputFolder=extractDir,+ archiveSize=archiveSize,+ ))+ task.addStage(InstallStage(+ stageIndex=3,+ sourceDir=extractDir,+ installFolder=toPosixPath(installFolder),+ archivePath=archivePath,+ executableNames=executableNames,+ ))+ return taskdiff --git a/features/disk_pack/task.py b/features/disk_pack/task.pynew file mode 100644index 00000000..5a1a859d--- /dev/null+++ b/features/disk_pack/task.py@@ -0,0 +1,207 @@+import asyncio+import shutil+import sys+import tarfile+import zipfile+from dataclasses import dataclass, field+from pathlib import Path+from time import perf_counter++from app.bases.interfaces import Worker+from app.bases.models import TaskStage, TaskStatus+from app.supports.utils import toPosixPath+++_CHUNK_SIZE = 1 << 20+++@dataclass(kw_only=True)+class ExtractStage(TaskStage):+ workerType: type = field(init=False, repr=False)+ canPause: bool = field(init=False, default=False)++ archivePath: str+ outputFolder: str+ archiveSize: int = 0+++async def _extractZip(archive: Path, outputFolder: Path, stage: ExtractStage):+ with zipfile.ZipFile(archive) as zf:+ files = [info for info in zf.infolist() if not info.is_dir()]+ totalSize = sum(info.file_size for info in files)+ stage.task.fileSize = max(stage.archiveSize + totalSize, stage.archiveSize)++ safeRoot = outputFolder.resolve()+ extractedBytes = speedBytes = 0+ speedTime = perf_counter()+ for info in files:+ # 防 zip-slip:archive 里若含 "../" 路径会让文件落到 outputFolder 之外+ memberPath = (outputFolder / info.filename).resolve()+ if safeRoot not in {memberPath, *memberPath.parents}:+ raise RuntimeError(f"压缩包包含非法路径: {info.filename}")+ memberPath.parent.mkdir(parents=True, exist_ok=True)+ with zf.open(info, "r") as source, open(memberPath, "wb") as target:+ while chunk := source.read(_CHUNK_SIZE):+ target.write(chunk)+ extractedBytes += len(chunk)+ stage.receivedBytes = extractedBytes+ if totalSize > 0:+ stage.progress = min(99.5, extractedBytes / totalSize * 100)+ now = perf_counter()+ if now - speedTime >= 0.5:+ stage.speed = int((extractedBytes - speedBytes) / (now - speedTime))+ speedBytes, speedTime = extractedBytes, now+ await asyncio.sleep(0)+++async def _extractTar(archive: Path, outputFolder: Path, stage: ExtractStage):+ with tarfile.open(archive, "r:*") as tf:+ files = [m for m in tf.getmembers() if m.isfile()]+ totalSize = sum(m.size for m in files)+ stage.task.fileSize = max(stage.archiveSize + totalSize, stage.archiveSize)++ safeRoot = outputFolder.resolve()+ extractedBytes = speedBytes = 0+ speedTime = perf_counter()+ for member in files:+ # 防 tar-slip:archive 里若含 "../" 路径会让文件落到 outputFolder 之外+ memberPath = (outputFolder / member.name).resolve()+ if safeRoot not in {memberPath, *memberPath.parents}:+ raise RuntimeError(f"压缩包包含非法路径: {member.name}")+ memberPath.parent.mkdir(parents=True, exist_ok=True)+ source = tf.extractfile(member)+ if source is None:+ continue+ with source, open(memberPath, "wb") as target:+ while chunk := source.read(_CHUNK_SIZE):+ target.write(chunk)+ extractedBytes += len(chunk)+ stage.receivedBytes = extractedBytes+ if totalSize > 0:+ stage.progress = min(99.5, extractedBytes / totalSize * 100)+ now = perf_counter()+ if now - speedTime >= 0.5:+ stage.speed = int((extractedBytes - speedBytes) / (now - speedTime))+ speedBytes, speedTime = extractedBytes, now+ await asyncio.sleep(0)+++class ExtractWorker(Worker):+ def __init__(self, stage: ExtractStage):+ super().__init__(stage)+ self.stage = stage++ async def run(self):+ archive = Path(self.stage.archivePath)+ if not archive.is_file():+ raise FileNotFoundError(f"未找到安装包: {archive}")++ outputFolder = Path(self.stage.outputFolder)++ try:+ self.stage.progress = 0+ self.stage.speed = 0+ self.stage.receivedBytes = 0++ outputFolder.mkdir(parents=True, exist_ok=True)++ lowered = archive.name.lower()+ if lowered.endswith(".tar.gz"):+ await _extractTar(archive, outputFolder, self.stage)+ elif lowered.endswith(".zip"):+ await _extractZip(archive, outputFolder, self.stage)+ else:+ raise RuntimeError(f"不支持的压缩包格式: {archive.name}")++ self.stage.setStatus(TaskStatus.COMPLETED)+ except asyncio.CancelledError:+ self.stage.setStatus(TaskStatus.PAUSED)+ raise+ except Exception as e:+ self.stage.setError(e)+ raise+++ExtractStage.workerType = ExtractWorker+++@dataclass(kw_only=True)+class InstallStage(TaskStage):+ workerType: type = field(init=False, repr=False)+ canPause: bool = field(init=False, default=False)++ sourceDir: str+ installFolder: str+ archivePath: str = ""+ cleanup: bool = True+ executableNames: list[str] = field(default_factory=list)+ extractedExecutables: dict[str, str] = field(default_factory=dict)+++def _executablePath(root: Path, name: str) -> Path:+ for candidate in (root / "bin" / name, root / name):+ if candidate.is_file():+ return candidate+ found = next((c for c in root.rglob(name) if c.is_file()), None)+ if found is None:+ raise RuntimeError(f"安装包解压完成,但未找到可执行文件: {name}")+ return found+++class InstallWorker(Worker):+ def __init__(self, stage: InstallStage):+ super().__init__(stage)+ self.stage = stage++ async def run(self):+ sourceDir = Path(self.stage.sourceDir)+ installDir = Path(self.stage.installFolder)+ archive = Path(self.stage.archivePath) if self.stage.archivePath else None++ try:+ # archive 和 sourceDir 都可能位于 installDir 内,清空时必须保留+ preserve = {sourceDir.name}+ if archive is not None and archive.parent == installDir:+ preserve.add(archive.name)+ for child in installDir.iterdir():+ if child.name in preserve:+ continue+ if child.is_dir() and not child.is_symlink():+ shutil.rmtree(child, ignore_errors=True)+ else:+ child.unlink(missing_ok=True)++ # archive 常把内容包在一个顶层版本目录里(如 ffmpeg-7.0/),跳过它直接移内层+ children = list(sourceDir.iterdir())+ contentRoot = children[0] if len(children) == 1 and children[0].is_dir() else sourceDir++ for child in list(contentRoot.iterdir()):+ shutil.move(str(child), str(installDir / child.name))++ executables: dict[str, Path] = {+ name: _executablePath(installDir, name)+ for name in self.stage.executableNames+ }+ if sys.platform != "win32":+ for path in executables.values():+ path.chmod(path.stat().st_mode | 0o755)++ self.stage.extractedExecutables = {name: toPosixPath(p) for name, p in executables.items()}+ self.stage.task.metadata["extractedExecutables"] = self.stage.extractedExecutables++ if self.stage.cleanup and archive is not None and archive.exists():+ archive.unlink()++ self.stage.setStatus(TaskStatus.COMPLETED)+ except asyncio.CancelledError:+ self.stage.setStatus(TaskStatus.PAUSED)+ raise+ except Exception as e:+ self.stage.setError(e)+ raise+ finally:+ if self.stage.cleanup and sourceDir.exists():+ shutil.rmtree(sourceDir, ignore_errors=True)+++InstallStage.workerType = InstallWorkerdiff --git a/features/extract_pack/pack.py b/features/extract_pack/pack.pydeleted file mode 100644index 49392125..00000000--- a/features/extract_pack/pack.py+++ /dev/null@@ -1,5 +0,0 @@-from app.bases.interfaces import FeaturePack---class ExtractPack(FeaturePack):- packId = "extract"diff --git a/features/extract_pack/task.py b/features/extract_pack/task.pydeleted file mode 100644index 681c1608..00000000--- a/features/extract_pack/task.py+++ /dev/null@@ -1,236 +0,0 @@-import asyncio-import shutil-import sys-import tarfile-import zipfile-from contextlib import suppress-from dataclasses import dataclass, field-from pathlib import Path-from time import perf_counter--from app.bases.interfaces import Worker-from app.bases.models import Task, TaskStage, TaskStatus-from app.supports.utils import toPosixPath---def _archiveSuffix(name: str) -> str:- loweredName = name.lower()- if loweredName.endswith(".tar.gz"):- return ".tar.gz"- return Path(name).suffix.lower()---def _safeJoin(root: Path, relative: str) -> Path:- target = (root / relative).resolve()- if root.resolve() not in {target, *target.parents}:- raise RuntimeError(f"压缩包包含非法路径: {relative}")- return target---@dataclass(kw_only=True)-class ExtractStage(TaskStage):- workerType: type = field(init=False, repr=False)- canPause: bool = field(init=False, default=False)-- archivePath: str- installFolder: str- executableNames: list[str] = field(default_factory=list)- extractedExecutables: dict[str, str] = field(default_factory=dict)- cleanupArchive: bool = True-- def updateOutputFile(self, taskPath: Path, taskTitle: str):- pass-- def onCompleted(self, task: Task):- if self.extractedExecutables:- task.metadata["extractedExecutables"] = self.extractedExecutables---class ExtractWorker(Worker):- chunkSize = 1048576-- def __init__(self, stage: ExtractStage):- super().__init__(stage)- self.stage = stage-- def _removePath(self, path: Path):- if path.is_dir() and not path.is_symlink():- shutil.rmtree(path, ignore_errors=True)- else:- with suppress(FileNotFoundError):- path.unlink()-- def _updateTaskFileSize(self, extractedSize: int):- task = self.stage.task- archiveSize = int(task.metadata.get("archiveSize", 0))- task.fileSize = max(archiveSize + extractedSize, archiveSize)-- def _resolveExtractedRoot(self, tempDir: Path) -> Path:- children = list(tempDir.iterdir())- if len(children) == 1 and children[0].is_dir():- return children[0]- return tempDir-- def _findExecutable(self, root: Path, name: str) -> Path | None:- for candidate in (root / "bin" / name, root / name):- if candidate.is_file():- return candidate-- for candidate in root.rglob(name):- if candidate.is_file():- return candidate-- return None-- async def _writeExtractedFile(- self,- source,- targetPath: Path,- extractedBytes: int,- speedBytes: int,- speedTime: float,- totalSize: int,- ) -> tuple[int, int, float]:- with open(targetPath, "wb") as target:- while True:- chunk = source.read(self.chunkSize)- if not chunk:- return extractedBytes, speedBytes, speedTime-- target.write(chunk)- extractedBytes += len(chunk)- self.stage.receivedBytes = extractedBytes- if totalSize > 0:- self.stage.progress = min(99.5, max(0.0, extractedBytes / totalSize * 100))-- now = perf_counter()- if now - speedTime >= 0.5:- self.stage.speed = int((extractedBytes - speedBytes) / (now - speedTime))- speedBytes = extractedBytes- speedTime = now- await asyncio.sleep(0)-- async def _extractZip(self, archivePath: Path, tempDir: Path, totalSize: int):- extractedBytes = 0- speedBytes = 0- speedTime = perf_counter()-- with zipfile.ZipFile(archivePath) as archive:- infos = [info for info in archive.infolist() if not info.is_dir()]- for info in infos:- targetPath = _safeJoin(tempDir, info.filename)- targetPath.parent.mkdir(parents=True, exist_ok=True)-- with archive.open(info, "r") as source:- extractedBytes, speedBytes, speedTime = await self._writeExtractedFile(- source, targetPath, extractedBytes, speedBytes, speedTime, totalSize,- )-- async def _extractTar(self, archivePath: Path, tempDir: Path, totalSize: int):- extractedBytes = 0- speedBytes = 0- speedTime = perf_counter()-- with tarfile.open(archivePath, "r:*") as archive:- members = [member for member in archive.getmembers() if member.isfile()]- for member in members:- targetPath = _safeJoin(tempDir, member.name)- targetPath.parent.mkdir(parents=True, exist_ok=True)-- source = archive.extractfile(member)- if source is None:- continue-- with source:- extractedBytes, speedBytes, speedTime = await self._writeExtractedFile(- source, targetPath, extractedBytes, speedBytes, speedTime, totalSize,- )-- async def _extractArchive(self, archivePath: Path, tempDir: Path, totalSize: int):- suffix = _archiveSuffix(archivePath.name)- if suffix == ".zip":- await self._extractZip(archivePath, tempDir, totalSize)- return- if suffix == ".tar.gz":- await self._extractTar(archivePath, tempDir, totalSize)- return- raise RuntimeError(f"不支持的压缩包格式: {archivePath.name}")-- def _archiveExtractSize(self, archivePath: Path) -> int:- suffix = _archiveSuffix(archivePath.name)- if suffix == ".zip":- with zipfile.ZipFile(archivePath) as archive:- return sum(info.file_size for info in archive.infolist() if not info.is_dir())- if suffix == ".tar.gz":- with tarfile.open(archivePath, "r:*") as archive:- return sum(member.size for member in archive.getmembers() if member.isfile())- raise RuntimeError(f"不支持的压缩包格式: {archivePath.name}")-- def _installExtractedFiles(self, extractedRoot: Path, installDir: Path, archiveName: str, tempDirName: str) -> dict[str, str]:- for child in installDir.iterdir():- if child.name in {archiveName, tempDirName}:- continue- self._removePath(child)-- for child in list(extractedRoot.iterdir()):- target = installDir / child.name- if target.exists():- self._removePath(target)- shutil.move(str(child), str(target))-- executables: dict[str, str] = {}- for name in self.stage.executableNames:- executablePath = self._findExecutable(installDir, name)- if executablePath is None:- raise RuntimeError(f"安装包解压完成,但未找到可执行文件: {name}")-- if sys.platform != "win32":- executablePath.chmod(executablePath.stat().st_mode | 0o755)-- executables[name] = toPosixPath(executablePath)-- return executables-- async def run(self):- archivePath = Path(self.stage.archivePath)- if not archivePath.is_file():- raise FileNotFoundError(f"未找到安装包: {archivePath}")-- installDir = Path(self.stage.installFolder)- tempDir = installDir / ".extracting"-- try:- self.stage.progress = 0- self.stage.speed = 0- self.stage.receivedBytes = 0-- installDir.mkdir(parents=True, exist_ok=True)- if tempDir.exists():- shutil.rmtree(tempDir, ignore_errors=True)- tempDir.mkdir(parents=True, exist_ok=True)-- extractSize = self._archiveExtractSize(archivePath)- self._updateTaskFileSize(extractSize)- await self._extractArchive(archivePath, tempDir, extractSize)-- extractedRoot = self._resolveExtractedRoot(tempDir)- self.stage.extractedExecutables = self._installExtractedFiles(- extractedRoot, installDir, archivePath.name, tempDir.name,- )-- if self.stage.cleanupArchive and archivePath.exists():- archivePath.unlink()-- self.stage.setStatus(TaskStatus.COMPLETED)- except asyncio.CancelledError:- self.stage.setStatus(TaskStatus.PAUSED)- raise- except Exception as e:- self.stage.setError(e)- raise- finally:- if tempDir.exists():- shutil.rmtree(tempDir, ignore_errors=True)---ExtractStage.workerType = ExtractWorkerdiff --git a/features/ffmpeg_pack/config.py b/features/ffmpeg_pack/config.pyindex 33193e43..7c9ef792 100644--- a/features/ffmpeg_pack/config.py+++ b/features/ffmpeg_pack/config.py@@ -4,50 +4,53 @@ import sysfrom pathlib import Pathfrom typing import TYPE_CHECKING-from PySide6.QtCore import Qt, Signal-from PySide6.QtWidgets import QFileDialog+from PySide6.QtCore import Qt, QUrl+from PySide6.QtGui import QDesktopServices+from PySide6.QtWidgets import QApplicationfrom qfluentwidgets import (ConfigItem,FluentIcon,FolderValidator,+ InfoBar,+ InfoBarPosition,+ PrimaryPushButton,SettingCard,- ToolButton, PrimaryPushButton, InfoBar, ToolTipFilter+ ToolButton,)from app.bases.models import PackConfigfrom app.services.core_service import coreService-from app.supports.config import cfgfrom app.supports.paths import APP_DATA_DIR-from app.supports.utils import toExecutable, toPosixPath+from app.supports.utils import findExecutable, toPosixPathfrom app.view.components.setting_card_group import CollapsibleSettingCardGroup+from app.view.components.setting_cards import InstallFolderCardif TYPE_CHECKING:from app.view.pages.setting_page import SettingPagefrom app.view.windows.main_window import MainWindow-def _guessInstallRoot(ffmpegPath: str) -> str:- path = Path(ffmpegPath)- if path.parent.name.lower() == "bin":- return toPosixPath(path.parent.parent)- return toPosixPath(path.parent)---def _findExecutable(name: str) -> str:- installFolder = Path(ffmpegConfig.installFolder.value)- for candidate in (installFolder / "bin" / toExecutable(name), installFolder / toExecutable(name)):- if candidate.is_file():- return toPosixPath(candidate)-- found = shutil.which(name)- return toPosixPath(found) if found else ""+def _linuxInstallCommand() -> str:+ """检测可用包管理器;都没命中时 fallback 到 apt 命令文本(让用户自行替换)。"""+ candidates = (+ ("apt", "sudo apt install ffmpeg"),+ ("dnf", "sudo dnf install ffmpeg"),+ ("pacman", "sudo pacman -S ffmpeg"),+ ("zypper", "sudo zypper install ffmpeg"),+ ("apk", "sudo apk add ffmpeg"),+ )+ return next((cmd for pm, cmd in candidates if shutil.which(pm)), candidates[0][1])def ffmpegPaths() -> tuple[str, str]:- return _findExecutable("ffmpeg"), _findExecutable("ffprobe")+ installFolder = Path(ffmpegConfig.installFolder.value)+ return (+ findExecutable(installFolder, "ffmpeg", "bin"),+ findExecutable(installFolder, "ffprobe", "bin"),+ )-async def queryFFmpegRuntime() -> dict[str, str]:+async def probeFFmpegRuntime() -> dict[str, str]:ffmpegPath, ffprobePath = ffmpegPaths()runtimeInfo = {"ffmpegPath": ffmpegPath,@@ -69,64 +72,52 @@ async def queryFFmpegRuntime() -> dict[str, str]:if process.returncode != 0:return runtimeInfo- firstLine = stdout.decode("utf-8", errors="ignore").splitlines()- versionLine = firstLine[0].strip() if firstLine else ""+ lines = stdout.decode("utf-8", errors="ignore").splitlines()+ versionLine = lines[0].strip() if lines else ""version = versionLine.removeprefix("ffmpeg version ").split(" Copyright", 1)[0].strip()runtimeInfo["version"] = version or versionLine- runtimeInfo["installPath"] = _guessInstallRoot(ffmpegPath)+ binPath = Path(ffmpegPath)+ installRoot = binPath.parent.parent if binPath.parent.name.lower() == "bin" else binPath.parent+ runtimeInfo["installPath"] = toPosixPath(installRoot)return runtimeInfo-class FFmpegInstallFolderCard(SettingCard):- pathChanged = Signal(str)-- def __init__(self, parent=None):- super().__init__(FluentIcon.FOLDER, self.tr("FFmpeg 安装目录"), ffmpegConfig.installFolder.value, parent)- self.chooseFolderButton = ToolButton(FluentIcon.FOLDER, self)- self.restoreDefaultButton = ToolButton(FluentIcon.CANCEL, self)- self.hBoxLayout.addWidget(self.chooseFolderButton, 0, Qt.AlignmentFlag.AlignRight)- self.hBoxLayout.addSpacing(8)- self.hBoxLayout.addWidget(self.restoreDefaultButton, 0, Qt.AlignmentFlag.AlignRight)- self.hBoxLayout.addSpacing(16)-- self.chooseFolderButton.clicked.connect(self._chooseFolder)- self.restoreDefaultButton.clicked.connect(self._restoreDefault)- self.chooseFolderButton.setToolTip(self.tr("浏览文件夹"))- self.chooseFolderButton.installEventFilter(ToolTipFilter(self.chooseFolderButton))- self.restoreDefaultButton.setToolTip(self.tr("恢复默认路径"))- self.restoreDefaultButton.installEventFilter(ToolTipFilter(self.restoreDefaultButton))-- def _updatePath(self, path: str):- cfg.set(ffmpegConfig.installFolder, path)- self.setContent(ffmpegConfig.installFolder.value)- self.pathChanged.emit(ffmpegConfig.installFolder.value)-- def _chooseFolder(self):- folder = QFileDialog.getExistingDirectory(self.window(), self.tr("选择 FFmpeg 安装目录"))- if folder:- self._updatePath(folder)-- def _restoreDefault(self):- self._updatePath(f"{APP_DATA_DIR}/FFmpeg")--class FFmpegRuntimeCard(SettingCard):def __init__(self, parent=None):super().__init__(FluentIcon.INFO, self.tr("当前 FFmpeg"), self.tr("正在检测 FFmpeg 运行时..."), parent)- self.installButton = PrimaryPushButton(self.tr("一键安装"), self)+ self.installButton = PrimaryPushButton(self)self.refreshButton = ToolButton(FluentIcon.SYNC, self)++ self._initWidget()+ self._initLayout()+ self._bind()++ def _initWidget(self):+ if sys.platform == "win32":+ self.installButton.setText(self.tr("一键安装"))+ self._installAction = self._downloadFFmpeg+ elif sys.platform == "darwin" and not shutil.which("brew"):+ self.installButton.setText(self.tr("打开 brew.sh"))+ self._installAction = lambda: QDesktopServices.openUrl(QUrl("https://brew.sh"))+ else:+ command = "brew install ffmpeg" if sys.platform == "darwin" else _linuxInstallCommand()+ self.installButton.setText(self.tr("复制安装命令"))+ self._installAction = lambda: self._copyCommand(command)++ def _initLayout(self):self.hBoxLayout.addWidget(self.installButton, 0, Qt.AlignmentFlag.AlignRight)self.hBoxLayout.addSpacing(8)self.hBoxLayout.addWidget(self.refreshButton, 0, Qt.AlignmentFlag.AlignRight)self.hBoxLayout.addSpacing(16)- self.installButton.setVisible(sys.platform == "win32")- self.installButton.clicked.connect(self._onInstallClicked)++ def _bind(self):+ self.installButton.clicked.connect(self._installAction)self.refreshButton.clicked.connect(self.refreshStatus)def refreshStatus(self):self.refreshButton.setEnabled(False)self.setContent(self.tr("正在检测 FFmpeg 运行时..."))- coreService.runCoroutine(queryFFmpegRuntime(), self._onRuntimeLoaded)+ coreService.runCoroutine(probeFFmpegRuntime(), self._onRuntimeLoaded)def _onRuntimeLoaded(self, result, error: str | None):self.refreshButton.setEnabled(True)@@ -135,37 +126,36 @@ class FFmpegRuntimeCard(SettingCard):returnruntimeInfo = result or {}- ffmpegPath = str(runtimeInfo.get("ffmpegPath") or "").strip()- ffprobePath = str(runtimeInfo.get("ffprobePath") or "").strip()- version = str(runtimeInfo.get("version") or "").strip()- installPath = str(runtimeInfo.get("installPath") or "").strip()-+ ffmpegPath = runtimeInfo.get("ffmpegPath", "")+ ffprobePath = runtimeInfo.get("ffprobePath", "")if ffmpegPath and ffprobePath:- content = self.tr("版本: {0}\n安装路径: {1}").format(version or self.tr("未知"), installPath or ffmpegPath)+ version = runtimeInfo.get("version", "")+ installPath = runtimeInfo.get("installPath", "")+ self.setContent(self.tr("版本: {0}\n安装路径: {1}").format(version or self.tr("未知"), installPath or ffmpegPath))else:- content = self.tr("未检测到可用的 ffmpeg 和 ffprobe")- self.setContent(content)-- def _onInstallClicked(self):- if sys.platform != "win32":- return+ self.setContent(self.tr("未检测到可用的 ffmpeg 和 ffprobe"))+ def _downloadFFmpeg(self):from .pack import createInstallTask-self.installButton.setEnabled(False)self.installButton.setText(self.tr("准备中..."))coreService.runCoroutine(createInstallTask(), self._onInstallTaskCreated)+ def _copyCommand(self, command: str):+ QApplication.clipboard().setText(command)+ InfoBar.success(+ self.tr("已复制安装命令"), command,+ duration=2000, position=InfoBarPosition.BOTTOM_RIGHT, parent=self.window(),+ )+def _onInstallTaskCreated(self, result, error: str | None):self.installButton.setEnabled(True)self.installButton.setText(self.tr("一键安装"))mainWindow: "MainWindow" = self.window()-if error or result is None:InfoBar.error(self.tr("安装 FFmpeg 失败"), error or self.tr("无法创建安装任务"), duration=-1, parent=mainWindow)return-mainWindow.addTask(result)@@ -174,7 +164,13 @@ class FFmpegConfig(PackConfig):def setupSettings(self, settingPage: "SettingPage"):self.ffmpegGroup = CollapsibleSettingCardGroup(self.tr("FFmpeg"), "ffmpeg", settingPage.container)- self.installFolderCard = FFmpegInstallFolderCard(self.ffmpegGroup)+ self.installFolderCard = InstallFolderCard(+ ffmpegConfig.installFolder,+ f"{APP_DATA_DIR}/FFmpeg",+ self.tr("FFmpeg 安装目录"),+ self.tr("选择 FFmpeg 安装目录"),+ self.ffmpegGroup,+ )self.runtimeCard = FFmpegRuntimeCard(self.ffmpegGroup)self.installFolderCard.pathChanged.connect(lambda _: self.runtimeCard.refreshStatus())diff --git a/features/ffmpeg_pack/manifest.toml b/features/ffmpeg_pack/manifest.tomlindex 7b5f6ce0..eef5b6e1 100644--- a/features/ffmpeg_pack/manifest.toml+++ b/features/ffmpeg_pack/manifest.toml@@ -1,3 +1,3 @@[pack]entry = "pack.py"-dependencies = ["http_pack", "extract_pack"]+dependencies = ["http_pack", "disk_pack"]diff --git a/features/ffmpeg_pack/pack.py b/features/ffmpeg_pack/pack.pyindex 8609168a..bd7a8943 100644--- a/features/ffmpeg_pack/pack.py+++ b/features/ffmpeg_pack/pack.py@@ -1,3 +1,4 @@+import asyncioimport platformimport sysfrom pathlib import Path@@ -9,16 +10,16 @@ import niquestsfrom app.bases.interfaces import FeaturePackfrom app.bases.models import Task, SpecialFileSizefrom app.supports.config import DEFAULT_HEADERS, cfg-from app.supports.utils import getProxies, toExecutable, toPosixPath, toSafeFilename+from app.supports.utils import getProxies, toExecutable, toSafeFilenamefrom .config import ffmpegConfig, ffmpegPathsfrom .task import FFmpegStageif TYPE_CHECKING:+ from features.disk_pack.pack import buildToolInstallTaskfrom features.http_pack.task import HttpTaskStage- from features.extract_pack.task import ExtractStageelse:+ from disk_pack.pack import buildToolInstallTaskfrom http_pack.task import HttpTaskStage- from extract_pack.task import ExtractStageFFMPEG_MERGE_URL = "gd3+ffmpeg://merge"@@ -30,20 +31,12 @@ _FFMPEG_HEADERS = {}-def _resourceExtension(name: str, url: str) -> str:- fileName = Path(name).name if name else Path(urlparse(url).path).name- return Path(fileName).suffix.lstrip(".").lower()---def _mergeOutputTitle(title: str) -> str:- baseTitle = toSafeFilename(title, fallback="merged-media")- if baseTitle.lower().endswith(".mp4"):- return baseTitle- return f"{baseTitle}.mp4"+ target = name or urlparse(url).path+ return Path(target).suffix.lstrip(".").lower()-def _detectWindowsTarget() -> tuple[str, str]:+def _windowsTarget() -> tuple[str, str]:if sys.platform != "win32":raise RuntimeError("一键安装 FFmpeg 仅支持 Windows 平台")@@ -55,12 +48,10 @@ def _detectWindowsTarget() -> tuple[str, str]:raise RuntimeError(f"不支持的 Windows 架构: {platform.machine()}")-def _selectReleaseAsset(assets: list[dict[str, Any]]) -> dict[str, Any]:- target, _ = _detectWindowsTarget()+def _bestAsset(assets: list[dict[str, Any]], target: str) -> dict[str, Any]:candidates: list[tuple[int, dict[str, Any]]] = []for asset in assets:- name = str(asset.get("name") or "")- lowerName = name.lower()+ lowerName = asset["name"].lower()if target not in lowerName or not lowerName.endswith(".zip") or "shared" in lowerName:continue@@ -75,12 +66,10 @@ def _selectReleaseAsset(assets: list[dict[str, Any]]) -> dict[str, Any]:if not candidates:raise RuntimeError(f"未找到适用于当前平台的 FFmpeg 安装包: {target}")+ return max(candidates, key=lambda item: item[0])[1]- candidates.sort(key=lambda item: item[0], reverse=True)- return candidates[0][1]--async def _requestLatestReleaseAsset() -> dict[str, Any]:+async def _fetchLatestRelease(target: str) -> dict[str, Any]:async with niquests.AsyncSession(headers=_FFMPEG_HEADERS, timeout=30, happy_eyeballs=True) as client:client.trust_env = Falseresponse = await client.get(@@ -96,10 +85,10 @@ async def _requestLatestReleaseAsset() -> dict[str, Any]:if not isinstance(assets, list):raise RuntimeError("GitHub Release 返回了无效的 assets 数据")- asset = _selectReleaseAsset(assets)- downloadUrl = str(asset.get("browser_download_url") or "").strip()- assetName = str(asset.get("name") or "").strip()- size = int(asset.get("size") or 0)+ asset = _bestAsset(assets, target)+ downloadUrl = asset["browser_download_url"].strip()+ assetName = asset["name"].strip()+ size = asset["size"]if not downloadUrl or not assetName or size <= 0:raise RuntimeError("GitHub Release 返回了不完整的 FFmpeg 安装包信息")@@ -110,58 +99,59 @@ async def _requestLatestReleaseAsset() -> dict[str, Any]:}+async def _resourceDownloadTask(item: dict[str, Any], payload: dict[str, Any], path: Path) -> Task:+ from app.services.feature_service import featureService++ url = item["url"].strip()+ if not url.startswith(("http://", "https://")):+ raise RuntimeError("在线合并暂不支持 blob 或非 HTTP 资源")++ resourceTask = await featureService.parse({+ "url": url,+ "filename": (item.get("filename") or "").strip(),+ "headers": item.get("headers") or {},+ "fileSize": item.get("fileSize") or SpecialFileSize.UNKNOWN,+ "supportsRange": bool(item.get("supportsRange")),+ "proxies": payload.get("proxies", getProxies()),+ "path": path,+ "preBlockNum": payload.get("preBlockNum", cfg.preBlockNum.value),+ })+ if not resourceTask.stages:+ raise RuntimeError("解析在线合并源文件失败")+ return resourceTask++async def createMergeTask(payload: dict[str, Any]) -> Task:ffmpeg, ffprobe = ffmpegPaths()if not ffmpeg or not ffprobe:raise RuntimeError("未找到可用的 ffmpeg 和 ffprobe,请先在设置中安装或配置 FFmpeg")- from app.services.feature_service import featureService-resources = payload.get("resources") or []if len(resources) != 2:raise RuntimeError("在线合并暂时只支持 2 个 HTTP 音视频资源")- parsedResources: list[tuple[dict[str, Any], Task]] = []- for item in resources:- url = str(item.get("url") or "").strip()- if not url.startswith(("http://", "https://")):- raise RuntimeError("在线合并暂不支持 blob 或非 HTTP 资源")-- resourcePayload = {- "url": url,- "filename": str(item.get("filename") or "").strip(),- "headers": item.get("headers") or {},- "fileSize": item.get("fileSize") or SpecialFileSize.UNKNOWN,- "supportsRange": bool(item.get("supportsRange")),- "proxies": payload.get("proxies", getProxies()),- "path": Path(payload.get("path", cfg.downloadFolder.value)),- "preBlockNum": payload.get("preBlockNum", cfg.preBlockNum.value),- }-- resourceTask = await featureService.parse(resourcePayload)-- if not resourceTask.stages:- raise RuntimeError("解析在线合并源文件失败")-- parsedResources.append((item, resourceTask))-- outputTitle = _mergeOutputTitle(- str(payload.get("outputTitle") or "").strip()- or str(parsedResources[0][0].get("pageTitle") or "").strip()- or "merged-media"+ path = Path(payload.get("path", cfg.downloadFolder.value))+ videoTask, audioTask = await asyncio.gather(+ _resourceDownloadTask(resources[0], payload, path),+ _resourceDownloadTask(resources[1], payload, path),+ )++ rawTitle = (+ (payload.get("outputTitle") or "").strip()+ or (resources[0].get("pageTitle") or "").strip())+ baseTitle = toSafeFilename(rawTitle, fallback="merged-media")+ outputTitle = baseTitle if baseTitle.lower().endswith(".mp4") else f"{baseTitle}.mp4"- videoTask = parsedResources[0][1]- audioTask = parsedResources[1][1]videoStage: HttpTaskStage = videoTask.stages[0]audioStage: HttpTaskStage = audioTask.stages[0]-videoExt = _resourceExtension(videoTask.title, videoStage.url)audioExt = _resourceExtension(audioTask.title, audioStage.url)- path = Path(payload.get("path", cfg.downloadFolder.value))+finalPath = path / outputTitle- videoPath = finalPath.with_name(f"{finalPath.stem}.video{f'.{videoExt}' if videoExt else ''}")- audioPath = finalPath.with_name(f"{finalPath.stem}.audio{f'.{audioExt}' if audioExt else ''}")+ stem = finalPath.stem+ videoPath = finalPath.with_name(f"{stem}.video.{videoExt}" if videoExt else f"{stem}.video")+ audioPath = finalPath.with_name(f"{stem}.audio.{audioExt}" if audioExt else f"{stem}.audio")videoStage.stageIndex = 1videoStage.outputFile = str(videoPath)@@ -175,8 +165,6 @@ async def createMergeTask(payload: dict[str, Any]) -> Task:fileSize=max(0, videoTask.fileSize) + max(0, audioTask.fileSize),path=path,metadata={- "proxies": payload.get("proxies", getProxies()),- "blockNum": payload.get("preBlockNum", cfg.preBlockNum.value),"videoFileName": videoTask.title,"audioFileName": audioTask.title,},@@ -185,60 +173,26 @@ async def createMergeTask(payload: dict[str, Any]) -> Task:task.addStage(audioStage)task.addStage(FFmpegStage(stageIndex=3,- videoPath=str(videoPath),- audioPath=str(audioPath),- outputFile=str(finalPath),+ videoPath=videoPath,+ audioPath=audioPath,+ outputFile=finalPath,))return taskasync def createInstallTask() -> Task:- from app.services.feature_service import featureService-- assetInfo = await _requestLatestReleaseAsset()- _, archLabel = _detectWindowsTarget()- installFolder = ffmpegConfig.installFolder.value-- downloadPayload = {- "url": assetInfo["url"],- "headers": _FFMPEG_HEADERS.copy(),- "proxies": getProxies(),- "path": Path(installFolder),- }- downloadTask = await featureService.parse(downloadPayload)-- if not downloadTask.stages:- raise RuntimeError("解析 FFmpeg 下载链接后未获取到下载阶段")-- downloadStage: HttpTaskStage = downloadTask.stages[0]- archiveSize = downloadTask.fileSize if downloadTask.fileSize > 0 else assetInfo["size"]- assetName = downloadTask.title or str(assetInfo["name"])- archivePath = toPosixPath(Path(installFolder) / assetName)-- downloadStage.stageIndex = 1- downloadStage.outputFile = archivePath-- task = Task(- title=f"FFmpeg 安装 ({archLabel})",- url=downloadTask.url,+ target, archLabel = _windowsTarget()+ assetInfo = await _fetchLatestRelease(target)+ return await buildToolInstallTask(packId="ffmpeg",- fileSize=archiveSize,- path=Path(installFolder),- usesSlot=False,- metadata={- "archiveSize": archiveSize,- "installFolder": installFolder,- "assetName": assetName,- },- )- task.addStage(downloadStage)- task.addStage(ExtractStage(- stageIndex=2,- archivePath=archivePath,- installFolder=toPosixPath(Path(installFolder)),+ title=f"FFmpeg 安装 ({archLabel})",+ downloadUrl=assetInfo["url"],+ fallbackAssetName=assetInfo["name"],+ fallbackSize=assetInfo["size"],+ installFolder=Path(ffmpegConfig.installFolder.value),executableNames=[toExecutable("ffmpeg"), toExecutable("ffprobe")],- ))- return task+ headers=_FFMPEG_HEADERS,+ )class FFmpegPack(FeaturePack):@@ -246,7 +200,7 @@ class FFmpegPack(FeaturePack):config = ffmpegConfigdef matches(self, url: str) -> bool:- return str(url).strip() == FFMPEG_MERGE_URL+ return url.strip() == FFMPEG_MERGE_URLasync def parse(self, payload: dict) -> Task:return await createMergeTask(payload)diff --git a/features/ffmpeg_pack/task.py b/features/ffmpeg_pack/task.pyindex d8cdf73f..1dcd12d5 100644--- a/features/ffmpeg_pack/task.py+++ b/features/ffmpeg_pack/task.py@@ -10,57 +10,51 @@ from app.bases.models import TaskStage, TaskStatusfrom .config import ffmpegPaths+def _parseDuration(value: str) -> float:+ try:+ return max(0.0, float(value))+ except ValueError:+ return 0.0+++async def _probeDuration(ffprobe: str, path: Path) -> float:+ process = await asyncio.create_subprocess_exec(+ ffprobe,+ "-v", "error",+ "-show_entries", "format=duration",+ "-of", "default=noprint_wrappers=1:nokey=1",+ path,+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ stdout, stderr = await process.communicate()++ if process.returncode != 0:+ message = stderr.decode("utf-8", errors="ignore").strip()+ logger.warning("ffprobe 获取时长失败: {}, {}", path, message or process.returncode)+ return 0.0++ return _parseDuration(stdout.decode("utf-8", errors="ignore").strip())++@dataclass(kw_only=True)class FFmpegStage(TaskStage):workerType: type = field(init=False, repr=False)canPause: bool = field(init=False, default=False)- videoPath: str- audioPath: str- outputFile: str = ""+ videoPath: Path = field(default_factory=Path)+ audioPath: Path = field(default_factory=Path)+ outputFile: Path = field(default_factory=Path)cleanupSource: bool = True- def updateOutputFile(self, taskPath: Path, taskTitle: str):- pass-class FFmpegWorker(Worker):def __init__(self, stage: FFmpegStage):super().__init__(stage)self.stage = stage- @staticmethod- def _parseDuration(value) -> float:- try:- duration = float(value)- except (TypeError, ValueError):- return 0.0- return duration if duration > 0 else 0.0-- async def _fetchDuration(self, ffprobe: str, path: str) -> float:- process = await asyncio.create_subprocess_exec(- ffprobe,- "-v", "error",- "-show_entries", "format=duration",- "-of", "default=noprint_wrappers=1:nokey=1",- path,- stdin=asyncio.subprocess.DEVNULL,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- )- stdout, stderr = await process.communicate()-- if process.returncode != 0:- message = stderr.decode("utf-8", errors="ignore").strip()- logger.warning("ffprobe 获取时长失败: {}, {}", path, message or process.returncode)- return 0.0-- return self._parseDuration(stdout.decode("utf-8", errors="ignore").strip())-- async def _readProgress(self, stream: asyncio.StreamReader | None, totalDuration: float):- if stream is None:- return-+ async def _readProgress(self, stream: asyncio.StreamReader, totalDuration: float):while True:rawLine = await stream.readline()if not rawLine:@@ -71,7 +65,7 @@ class FFmpegWorker(Worker):continueif line.startswith("out_time_us=") and totalDuration > 0:- currentDuration = self._parseDuration(line.removeprefix("out_time_us=")) / 1_000_000+ currentDuration = _parseDuration(line.removeprefix("out_time_us=")) / 1_000_000if currentDuration <= 0:continueself.stage.progress = min(99.5, max(0.0, currentDuration / totalDuration * 100))@@ -83,16 +77,12 @@ class FFmpegWorker(Worker):if not ffmpeg or not ffprobe:raise RuntimeError("未找到可用的 ffmpeg 和 ffprobe,请先在设置中安装或配置 FFmpeg")- outputFile = Path(self.stage.outputFile)- outputFile.parent.mkdir(parents=True, exist_ok=True)+ self.stage.outputFile.parent.mkdir(parents=True, exist_ok=True)process = NoneprogressTask = Nonetry:- self.stage.progress = 0- self.stage.speed = 0- self.stage.receivedBytes = 0- totalDuration = await self._fetchDuration(ffprobe, self.stage.videoPath)+ totalDuration = await _probeDuration(ffprobe, self.stage.videoPath)process = await asyncio.create_subprocess_exec(ffmpeg,"-y", "-v", "error", "-nostats", "-progress", "pipe:1",@@ -108,17 +98,20 @@ class FFmpegWorker(Worker):await process.wait()await progressTask- stderrOutput = ""- if process.stderr is not None:- stderrOutput = (await process.stderr.read()).decode("utf-8", errors="ignore").strip()if process.returncode != 0:- if stderrOutput:- raise RuntimeError(f"ffmpeg 退出码异常: {process.returncode}, {stderrOutput}")- raise RuntimeError(f"ffmpeg 退出码异常: {process.returncode}")+ stderrOutput = (await process.stderr.read()).decode("utf-8", errors="ignore").strip()+ suffix = f", {stderrOutput}" if stderrOutput else ""+ raise RuntimeError(f"ffmpeg 退出码异常: {process.returncode}{suffix}")self.stage.setStatus(TaskStatus.COMPLETED)if self.stage.cleanupSource:- self._cleanupSourceFiles()+ # 同时清理 HttpWorker 写下的 .ghd 临时元数据文件+ for path in (self.stage.videoPath, self.stage.audioPath):+ for target in (path, path.with_name(f"{path.name}.ghd")):+ try:+ target.unlink(missing_ok=True)+ except OSError as e:+ logger.opt(exception=e).warning("failed to cleanup temporary file {}", target)except asyncio.CancelledError:self.stage.setStatus(TaskStatus.PAUSED)if process is not None and process.returncode is None:@@ -133,17 +126,5 @@ class FFmpegWorker(Worker):self.stage.setError(e)raise- def _cleanupSourceFiles(self):- for rawPath in (self.stage.videoPath, self.stage.audioPath):- target = Path(rawPath)- for path in (target, Path(rawPath + ".ghd")):- try:- if path.is_file() or path.is_symlink():- path.unlink()- except FileNotFoundError:- continue- except Exception as e:- logger.opt(exception=e).error("failed to cleanup temporary file {}", path)-FFmpegStage.workerType = FFmpegWorkerdiff --git a/features/m3u8_pack/cards.py b/features/m3u8_pack/cards.pyindex 1b629408..c5ad8cd7 100644--- a/features/m3u8_pack/cards.py+++ b/features/m3u8_pack/cards.py@@ -9,14 +9,7 @@ from qfluentwidgets import BodyLabel, ImageLabel, LineEdit, StrongBodyLabelfrom app.bases.models import Task, TaskStatusfrom app.supports.utils import toReadableSize, toReadableTimefrom app.view.components.cards import ResultCard, UniversalTaskCard---def _removeFile(path: Path):- try:- if path.is_file() or path.is_symlink():- path.unlink()- except FileNotFoundError:- pass+from .task import M3U8TaskStageclass M3U8TaskCard(UniversalTaskCard):@@ -74,8 +67,10 @@ class M3U8TaskCard(UniversalTaskCard):returntask = self.task- _removeFile(Path(task.outputFolder))- shutil.rmtree(Path(task.metadata.get('tempDir', '')), ignore_errors=True)+ Path(task.outputFolder).unlink(missing_ok=True)+ for stage in task.stages:+ if isinstance(stage, M3U8TaskStage) and stage.tempDir:+ shutil.rmtree(Path(stage.tempDir), ignore_errors=True)outputDirectory = Path(task.path)if outputDirectory.exists():@@ -84,7 +79,7 @@ class M3U8TaskCard(UniversalTaskCard):if candidate.name == Path(task.outputFolder).name:continueif candidate.is_file() and candidate.name.startswith(prefix):- _removeFile(candidate)+ candidate.unlink(missing_ok=True)class M3U8InstallTaskCard(UniversalTaskCard):diff --git a/features/m3u8_pack/config.py b/features/m3u8_pack/config.pyindex 7fc8850e..031981e5 100644--- a/features/m3u8_pack/config.py+++ b/features/m3u8_pack/config.py@@ -1,11 +1,8 @@import asyncio-import shutil-import sysfrom pathlib import Pathfrom typing import TYPE_CHECKING-from PySide6.QtCore import Qt, Signal-from PySide6.QtWidgets import QFileDialog+from PySide6.QtCore import Qtfrom qfluentwidgets import (BoolValidator,ComboBoxSettingCard,@@ -22,16 +19,14 @@ from qfluentwidgets import (SettingCard,SwitchSettingCard,ToolButton,- ToolTipFilter,)from app.bases.models import PackConfigfrom app.services.core_service import coreService-from app.supports.config import cfgfrom app.supports.paths import APP_DATA_DIR-from app.supports.utils import toExecutable, toPosixPath+from app.supports.utils import findExecutable, toPosixPathfrom app.view.components.setting_card_group import CollapsibleSettingCardGroup-from app.view.components.setting_cards import SpinBoxSettingCard+from app.view.components.setting_cards import InstallFolderCard, SpinBoxSettingCardif TYPE_CHECKING:from app.view.pages.setting_page import SettingPage@@ -44,18 +39,10 @@ except ImportError:def downloaderPath() -> str:- installFolder = Path(m3u8Config.installFolder.value)- candidate = installFolder / toExecutable("N_m3u8DL-RE")- if candidate.is_file():- return toPosixPath(candidate)+ return findExecutable(Path(m3u8Config.installFolder.value), "N_m3u8DL-RE")- found = shutil.which("N_m3u8DL-RE")- if not found and sys.platform == "win32":- found = shutil.which("N_m3u8DL-RE.exe")- return toPosixPath(found) if found else ""--async def queryM3U8Runtime() -> dict[str, str]:+async def probeM3U8Runtime() -> dict[str, str]:execPath = downloaderPath()ffmpegPath, _ = ffmpegPaths()runtimeInfo = {@@ -85,56 +72,29 @@ async def queryM3U8Runtime() -> dict[str, str]:return runtimeInfo-class M3U8InstallFolderCard(SettingCard):- pathChanged = Signal(str)-- def __init__(self, parent=None):- super().__init__(FluentIcon.FOLDER, self.tr("N_m3u8DL-RE 安装目录"), m3u8Config.installFolder.value, parent)- self.chooseFolderButton = ToolButton(FluentIcon.FOLDER, self)- self.restoreDefaultButton = ToolButton(FluentIcon.CANCEL, self)- self.hBoxLayout.addWidget(self.chooseFolderButton, 0, Qt.AlignmentFlag.AlignRight)- self.hBoxLayout.addSpacing(8)- self.hBoxLayout.addWidget(self.restoreDefaultButton, 0, Qt.AlignmentFlag.AlignRight)- self.hBoxLayout.addSpacing(16)-- self.chooseFolderButton.clicked.connect(self._chooseFolder)- self.restoreDefaultButton.clicked.connect(self._restoreDefault)- self.chooseFolderButton.setToolTip(self.tr("浏览文件夹"))- self.chooseFolderButton.installEventFilter(ToolTipFilter(self.chooseFolderButton))- self.restoreDefaultButton.setToolTip(self.tr("恢复默认路径"))- self.restoreDefaultButton.installEventFilter(ToolTipFilter(self.restoreDefaultButton))-- def _updatePath(self, path: str):- cfg.set(m3u8Config.installFolder, path)- self.setContent(m3u8Config.installFolder.value)- self.pathChanged.emit(m3u8Config.installFolder.value)-- def _chooseFolder(self):- folder = QFileDialog.getExistingDirectory(self.window(), self.tr("选择 N_m3u8DL-RE 安装目录"))- if folder:- self._updatePath(folder)-- def _restoreDefault(self):- defaultPath = f"{APP_DATA_DIR}/M3U8DL"- self._updatePath(defaultPath)--class M3U8RuntimeCard(SettingCard):def __init__(self, parent=None):super().__init__(FluentIcon.INFO, self.tr("当前 N_m3u8DL-RE"), self.tr("正在检测运行时..."), parent)self.installButton = PrimaryPushButton(self.tr("一键安装"), self)self.refreshButton = ToolButton(FluentIcon.SYNC, self)++ self._initLayout()+ self._bind()++ def _initLayout(self):self.hBoxLayout.addWidget(self.installButton, 0, Qt.AlignmentFlag.AlignRight)self.hBoxLayout.addSpacing(8)self.hBoxLayout.addWidget(self.refreshButton, 0, Qt.AlignmentFlag.AlignRight)self.hBoxLayout.addSpacing(16)++ def _bind(self):self.installButton.clicked.connect(self._onInstallClicked)self.refreshButton.clicked.connect(self.refreshStatus)def refreshStatus(self):self.refreshButton.setEnabled(False)self.setContent(self.tr("正在检测运行时..."))- coreService.runCoroutine(queryM3U8Runtime(), self._onRuntimeLoaded)+ coreService.runCoroutine(probeM3U8Runtime(), self._onRuntimeLoaded)def _onRuntimeLoaded(self, result, error: str | None):self.refreshButton.setEnabled(True)@@ -143,16 +103,16 @@ class M3U8RuntimeCard(SettingCard):returnruntimeInfo = result or {}- downloaderPath = str(runtimeInfo.get("downloaderPath") or "").strip()- version = str(runtimeInfo.get("version") or "").strip()- installPath = str(runtimeInfo.get("installPath") or "").strip()- ffmpegPath = str(runtimeInfo.get("ffmpegPath") or "").strip()+ executablePath = runtimeInfo.get("downloaderPath", "")+ version = runtimeInfo.get("version", "")+ installPath = runtimeInfo.get("installPath", "")+ ffmpegPath = runtimeInfo.get("ffmpegPath", "")- if downloaderPath:+ if executablePath:ffmpegText = ffmpegPath if ffmpegPath else self.tr("未检测到,部分流可能无法自动混流")content = self.tr("版本: {0}\n安装路径: {1}\nFFmpeg: {2}").format(version or self.tr("未知"),- installPath or downloaderPath,+ installPath or executablePath,ffmpegText,)else:@@ -160,7 +120,7 @@ class M3U8RuntimeCard(SettingCard):self.setContent(content)def _onInstallClicked(self):- from .task import createInstallTask+ from .pack import createInstallTaskself.installButton.setEnabled(False)self.installButton.setText(self.tr("准备中..."))@@ -200,7 +160,13 @@ class M3U8Config(PackConfig):def setupSettings(self, settingPage: "SettingPage"):self.m3u8Group = CollapsibleSettingCardGroup(self.tr("流媒体下载"), "m3u8", settingPage.container)- self.installFolderCard = M3U8InstallFolderCard(self.m3u8Group)+ self.installFolderCard = InstallFolderCard(+ m3u8Config.installFolder,+ f"{APP_DATA_DIR}/M3U8DL",+ self.tr("N_m3u8DL-RE 安装目录"),+ self.tr("选择 N_m3u8DL-RE 安装目录"),+ self.m3u8Group,+ )self.runtimeCard = M3U8RuntimeCard(self.m3u8Group)self.outputFormatCard = ComboBoxSettingCard(self.outputFormat,diff --git a/features/m3u8_pack/manifest.toml b/features/m3u8_pack/manifest.tomlindex 184517d6..b7043905 100644--- a/features/m3u8_pack/manifest.toml+++ b/features/m3u8_pack/manifest.toml@@ -1,3 +1,3 @@[pack]entry = "pack.py"-dependencies = ["http_pack", "extract_pack", "ffmpeg_pack"]+dependencies = ["http_pack", "disk_pack", "ffmpeg_pack"]diff --git a/features/m3u8_pack/pack.py b/features/m3u8_pack/pack.pyindex 36914b07..0ed35ef1 100644--- a/features/m3u8_pack/pack.py+++ b/features/m3u8_pack/pack.py@@ -1,14 +1,85 @@+import platform+import sys+from email.message import Message+from email.utils import collapse_rfc2231_valuefrom pathlib import Path-from urllib.parse import urlparse+from typing import TYPE_CHECKING, Literal+from urllib.parse import parse_qs, unquote, urlparseimport niquestsfrom app.bases.interfaces import FeaturePackfrom app.bases.models import Taskfrom app.supports.config import DEFAULT_HEADERS, cfg-from app.supports.utils import getProxies, splitCookies, toPosixPath+from app.supports.utils import getProxies, splitCookies, toExecutable, toSafeFilenamefrom .config import m3u8Config-from .task import M3U8TaskStage, _isLive, _manifestType, _stem, _title+from .task import M3U8TaskStage++if TYPE_CHECKING:+ from features.disk_pack.pack import buildToolInstallTask+else:+ from disk_pack.pack import buildToolInstallTask+++_M3U8DL_RELEASE_TAG = "v0.5.1-beta"+_M3U8DL_RELEASE_API = f"https://api.github.com/repos/nilaoda/N_m3u8DL-RE/releases/tags/{_M3U8DL_RELEASE_TAG}"+_M3U8DL_RELEASE_HEADERS = {+ "accept": "application/vnd.github+json",+ "user-agent": DEFAULT_HEADERS["user-agent"],+}+_KNOWN_SUFFIXES = {+ ".m3u8", ".m3u", ".mpd", ".mp4", ".mkv",+ ".ts", ".webm", ".m4a", ".m4v", ".vtt", ".srt",+}+++def _stem(name: str) -> str:+ suffix = Path(name).suffix+ if suffix.lower() in _KNOWN_SUFFIXES:+ return name[:-len(suffix)]+ return name+++def _manifestType(url: str, headers: dict[str, str], body: str) -> Literal["m3u8", "mpd"]:+ loweredUrl = url.lower()+ contentType = headers.get("content-type", "").lower()+ sample = body.lstrip()[:256].lower()+ if ".mpd" in loweredUrl or "dash+xml" in contentType or sample.startswith("<mpd"):+ return "mpd"+ return "m3u8"+++def _title(url: str, headers: dict[str, str], extension: str) -> str:+ candidates: list[str] = []++ cd = headers.get("content-disposition", "")+ if cd:+ msg = Message()+ msg["Content-Disposition"] = cd+ params = msg.get_params(header="Content-Disposition")+ 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)+ for key in ("filename", "file", "name", "title"):+ values = query.get(key)+ if values:+ candidates.append(values[0])++ if parsedUrl.path:+ candidates.append(unquote(Path(parsedUrl.path).name))++ for candidate in candidates:+ name = _stem(toSafeFilename(candidate, fallback="stream"))+ if name:+ return f"{name}.{extension}"++ return f"stream.{extension}"class M3U8Pack(FeaturePack):@@ -21,16 +92,15 @@ class M3U8Pack(FeaturePack):if parsedUrl.scheme.lower() not in {"http", "https"}:return FalseloweredUrl = url.lower()- return ".m3u8" in loweredUrl or ".m3u" in loweredUrl or ".mpd" in loweredUrl+ return ".m3u" in loweredUrl or ".mpd" in loweredUrlasync def parse(self, payload: dict) -> Task:- url = str(payload["url"]).strip()- headers = payload.get("headers", DEFAULT_HEADERS)+ url = payload["url"].strip()+ rawHeaders = payload.get("headers", DEFAULT_HEADERS)+ headers = rawHeaders.copy() if isinstance(rawHeaders, dict) else DEFAULT_HEADERS.copy()proxies = payload.get("proxies", getProxies())- path: Path = payload.get("path", Path(cfg.downloadFolder.value))- requestHeaders, requestCookies = splitCookies(- headers if isinstance(headers, dict) else DEFAULT_HEADERS- )+ path = Path(payload.get("path", cfg.downloadFolder.value))+ requestHeaders, requestCookies = splitCookies(headers)async with niquests.AsyncSession(timeout=30, happy_eyeballs=True) as client:client.trust_env = False@@ -45,38 +115,15 @@ class M3U8Pack(FeaturePack):response.raise_for_status()body = response.textloweredHeaders = {key.lower(): value for key, value in response.headers.items()}- manifestType = _manifestType(str(response.url), loweredHeaders, body)- isLive = _isLive(manifestType, body)- extension = "ts" if m3u8Config.liveRealTimeMerge.value else m3u8Config.outputFormat.value- title = _title(str(response.url), loweredHeaders, extension)- if isinstance(headers, dict):- headers = headers.copy()+ manifestType = _manifestType(response.url, loweredHeaders, body)+ loweredBody = body.lower()+ if manifestType == "mpd":+ isLive = 'type="dynamic"' in loweredBody or "type='dynamic'" in loweredBodyelse:- headers = DEFAULT_HEADERS.copy()-- saveName = _stem(title)- metadata = {- "headers": headers,- "proxies": proxies,- "threadCount": m3u8Config.threadCount.value,- "retryCount": m3u8Config.retryCount.value,- "requestTimeout": m3u8Config.requestTimeout.value,- "autoSelect": m3u8Config.autoSelect.value,- "concurrentDownload": m3u8Config.concurrentDownload.value,- "appendUrlParams": m3u8Config.appendUrlParams.value,- "binaryMerge": m3u8Config.binaryMerge.value,- "checkSegmentsCount": m3u8Config.checkSegmentsCount.value,- "outputFormat": m3u8Config.outputFormat.value,- "liveRealTimeMerge": m3u8Config.liveRealTimeMerge.value,- "liveKeepSegments": m3u8Config.liveKeepSegments.value,- "livePipeMux": m3u8Config.livePipeMux.value,- "manifestType": manifestType,- "isLive": isLive,- "actualExtension": "",- "saveName": saveName,- "outputExtension": extension,- }+ isLive = "#ext-x-endlist" not in loweredBody+ extension = "ts" if m3u8Config.liveRealTimeMerge.value else m3u8Config.outputFormat.value+ title = _title(response.url, loweredHeaders, extension)task = Task(title=title,@@ -84,16 +131,89 @@ class M3U8Pack(FeaturePack):packId=self.packId,fileSize=1,path=path,- metadata=metadata,+ metadata={+ "manifestType": manifestType,+ "isLive": isLive,+ },)- taskId = task.taskId- outputFile = toPosixPath(path / title)- tempDir = toPosixPath(path / ".gd3_m3u8" / taskId)-- task.addStage(M3U8TaskStage(+ stage = M3U8TaskStage(stageIndex=1,- outputFile=outputFile,- tempDir=tempDir,- ))+ saveName=_stem(title),+ headers=headers,+ proxies=proxies if isinstance(proxies, dict) else {},+ threadCount=m3u8Config.threadCount.value,+ retryCount=m3u8Config.retryCount.value,+ requestTimeout=m3u8Config.requestTimeout.value,+ autoSelect=m3u8Config.autoSelect.value,+ concurrentDownload=m3u8Config.concurrentDownload.value,+ appendUrlParams=m3u8Config.appendUrlParams.value,+ binaryMerge=m3u8Config.binaryMerge.value,+ checkSegmentsCount=m3u8Config.checkSegmentsCount.value,+ outputFormat=m3u8Config.outputFormat.value,+ liveRealTimeMerge=m3u8Config.liveRealTimeMerge.value,+ liveKeepSegments=m3u8Config.liveKeepSegments.value,+ livePipeMux=m3u8Config.livePipeMux.value,+ )+ task.addStage(stage)+ stage.updateOutputFile(path, title)return task+++async def createInstallTask() -> Task:+ machine = platform.machine().lower()+ if sys.platform == "win32":+ if machine in {"amd64", "x86_64"}:+ target, archLabel = "win-x64", "Windows x64"+ elif machine in {"arm64", "aarch64"}:+ target, archLabel = "win-arm64", "Windows ARM64"+ else:+ target, archLabel = "win-NT6.0-x86", "Windows x86"+ elif sys.platform == "darwin":+ if machine in {"arm64", "aarch64"}:+ target, archLabel = "osx-arm64", "macOS Apple Silicon"+ else:+ target, archLabel = "osx-x64", "macOS Intel"+ elif sys.platform == "linux":+ libcName = platform.libc_ver()[0].lower()+ if machine in {"arm64", "aarch64"}:+ target, archLabel = ("linux-musl-arm64", "Linux musl ARM64") if libcName == "musl" else ("linux-arm64", "Linux ARM64")+ else:+ target, archLabel = ("linux-musl-x64", "Linux musl x64") if libcName == "musl" else ("linux-x64", "Linux x64")+ else:+ raise RuntimeError(f"当前平台暂不支持一键安装 N_m3u8DL-RE: {sys.platform}")++ async with niquests.AsyncSession(headers=_M3U8DL_RELEASE_HEADERS, timeout=30, happy_eyeballs=True) as client:+ client.trust_env = False+ response = await client.get(+ _M3U8DL_RELEASE_API,+ proxies=getProxies(),+ verify=cfg.SSLVerify.value,+ allow_redirects=True,+ )+ response.raise_for_status()+ payload = response.json()++ assets = payload.get("assets")+ if not isinstance(assets, list):+ raise RuntimeError("GitHub Release 返回了无效的 assets 数据")++ asset = next((item for item in assets if target in item["name"]), None)+ if asset is None:+ raise RuntimeError(f"未找到适用于当前平台的 N_m3u8DL-RE 安装包: {target}")++ downloadUrl = asset["browser_download_url"].strip()+ assetName = asset["name"].strip()+ size = asset["size"]+ if not downloadUrl or not assetName or size <= 0:+ raise RuntimeError("GitHub Release 返回了不完整的安装包信息")++ return await buildToolInstallTask(+ packId="m3u8",+ title=f"N_m3u8DL-RE 安装 ({archLabel})",+ downloadUrl=downloadUrl,+ fallbackAssetName=assetName,+ fallbackSize=size,+ installFolder=Path(m3u8Config.installFolder.value),+ executableNames=[toExecutable("N_m3u8DL-RE")],+ )diff --git a/features/m3u8_pack/task.py b/features/m3u8_pack/task.pyindex 4bb1681b..37dd6b51 100644--- a/features/m3u8_pack/task.py+++ b/features/m3u8_pack/task.py@@ -1,112 +1,34 @@import asyncio-import platformimport re-import sysfrom contextlib import suppressfrom dataclasses import dataclass, field-from email.message import Message-from email.utils import collapse_rfc2231_valuefrom pathlib import Pathfrom typing import TYPE_CHECKING-from urllib.parse import parse_qs, unquote, urlparse--import niquestsfrom app.bases.interfaces import Worker-from app.bases.models import Task, TaskStage, TaskStatus-from app.supports.config import DEFAULT_HEADERS, cfg-from app.supports.utils import getProxies, toBytes, toExecutable, toPosixPath, toSafeFilename-from .config import m3u8Config, downloaderPath+from app.bases.models import TaskStage, TaskStatus+from app.supports.utils import toBytes, toPosixPath+from .config import downloaderPathif TYPE_CHECKING:from features.ffmpeg_pack.config import ffmpegPaths- from features.http_pack.task import HttpTaskStage- from features.extract_pack.task import ExtractStageelse:- from extract_pack.task import ExtractStagefrom ffmpeg_pack.config import ffmpegPaths- from http_pack.task import HttpTaskStage-_KNOWN_SUFFIXES = {- ".m3u8", ".m3u", ".mpd", ".mp4", ".mkv",- ".ts", ".webm", ".m4a", ".m4v", ".vtt", ".srt",-}_VOD_PROGRESS_PATTERN = re.compile(r"(\d+)/(\d+)\s+(\d+\.\d+)%\s+(\d+\.\d+)(KB|MB|GB|B)/(\d+\.\d+)(KB|MB|GB|B)\s+(\d+\.\d+)(GBps|MBps|KBps|Bps)\s+(.+)")_LIVE_PROGRESS_PATTERN = re.compile(r"(\d{2}m\d{2}s)/(\d{2}m\d{2}s)\s+\d+/\d+\s+(Recording|Waiting)\s+(\d+)%\s+(-|(\d+\.\d+)(GBps|MBps|KBps|Bps))")-_M3U8DL_RELEASE_TAG = "v0.5.1-beta"-_M3U8DL_RELEASE_API = f"https://api.github.com/repos/nilaoda/N_m3u8DL-RE/releases/tags/{_M3U8DL_RELEASE_TAG}"-_M3U8DL_RELEASE_HEADERS = {- "accept": "application/vnd.github+json",- "user-agent": DEFAULT_HEADERS["user-agent"],-}---def _stem(name: str) -> str:- suffix = Path(name).suffix.lower()- if suffix in _KNOWN_SUFFIXES:- return name[:-len(suffix)]- return name+_IGNORED_OUTPUT_SUFFIXES = {".json", ".txt", ".log", ".tmp", ".ghd"}def _toBool(value: bool) -> str:return "true" if value else "false"-def _manifestType(url: str, headers: dict[str, str], body: str) -> str:- loweredUrl = url.lower()- contentType = headers.get("content-type", "").lower()- sample = body.lstrip()[:256].lower()-- if ".mpd" in loweredUrl or "dash+xml" in contentType or sample.startswith("<mpd"):- return "mpd"- return "m3u8"---def _isLive(manifestType: str, body: str) -> bool:- loweredBody = body.lower()- if manifestType == "mpd":- return 'type="dynamic"' in loweredBody or "type='dynamic'" in loweredBody- return "#ext-x-endlist" not in loweredBody---def _title(url: str, headers: dict[str, str], extension: str) -> str:- candidates: list[str] = []-- cd = headers.get("content-disposition", "")- if cd:- msg = Message()- msg["Content-Disposition"] = cd- params = msg.get_params(header="Content-Disposition")- 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)- for key in ("filename", "file", "name", "title"):- values = query.get(key)- if values:- candidates.append(values[0])-- if parsedUrl.path:- candidates.append(unquote(Path(parsedUrl.path).name))-- for candidate in candidates:- name = _stem(toSafeFilename(candidate, fallback="stream"))- if name:- return f"{name}.{extension}"-- return f"stream.{extension}"--@dataclass(kw_only=True)class M3U8TaskStage(TaskStage):workerType: type = field(init=False, repr=False)@@ -114,6 +36,26 @@ class M3U8TaskStage(TaskStage):outputFile: str = ""tempDir: str = ""+ saveName: str = ""+ actualExtension: str = ""++ headers: dict[str, str] = field(default_factory=dict)+ proxies: dict[str, str] = field(default_factory=dict)++ threadCount: int = 16+ retryCount: int = 3+ requestTimeout: int = 10+ autoSelect: bool = True+ concurrentDownload: bool = True+ appendUrlParams: bool = False+ binaryMerge: bool = False+ checkSegmentsCount: bool = True++ outputFormat: str = "mp4"+ liveRealTimeMerge: bool = False+ liveKeepSegments: bool = False+ livePipeMux: bool = False+lastMessage: str = ""def updateOutputFile(self, taskPath: Path, taskTitle: str):@@ -125,25 +67,22 @@ class M3U8Worker(Worker):def __init__(self, stage: M3U8TaskStage):super().__init__(stage)self.stage = stage- self.task = stage.taskdef _buildArgs(self) -> list[str]:- meta = self.task.metadata- saveName = meta.get("saveName", _stem(self.task.title))-+ stage = self.stageargs = [- self.task.url,- f"--save-dir={self.task.path}",- f"--save-name={saveName}",- f"--tmp-dir={self.stage.tempDir}",- f"--thread-count={meta.get('threadCount', 16)}",- f"--download-retry-count={meta.get('retryCount', 3)}",- f"--http-request-timeout={meta.get('requestTimeout', 10)}",- f"--auto-select={_toBool(meta.get('autoSelect', True))}",- f"--concurrent-download={_toBool(meta.get('concurrentDownload', True))}",- f"--append-url-params={_toBool(meta.get('appendUrlParams', False))}",- f"--binary-merge={_toBool(meta.get('binaryMerge', False))}",- f"--check-segments-count={_toBool(meta.get('checkSegmentsCount', True))}",+ stage.task.url,+ f"--save-dir={toPosixPath(stage.task.path)}",+ f"--save-name={stage.saveName}",+ f"--tmp-dir={stage.tempDir}",+ f"--thread-count={stage.threadCount}",+ f"--download-retry-count={stage.retryCount}",+ f"--http-request-timeout={stage.requestTimeout}",+ f"--auto-select={_toBool(stage.autoSelect)}",+ f"--concurrent-download={_toBool(stage.concurrentDownload)}",+ f"--append-url-params={_toBool(stage.appendUrlParams)}",+ f"--binary-merge={_toBool(stage.binaryMerge)}",+ f"--check-segments-count={_toBool(stage.checkSegmentsCount)}","--del-after-done=true","--write-meta-json=false","--no-log=true",@@ -151,10 +90,10 @@ class M3U8Worker(Worker):"--disable-update-check=true",]- proxies = meta.get("proxies")- proxyUrl = ""- if isinstance(proxies, dict):- proxyUrl = next((v for v in proxies.values() if v), "")+ proxyUrl = next((v for v in stage.proxies.values() if v), "")+ # N_m3u8DL-RE 的 .NET HttpClient 不识别 socks5h scheme,等价转为 socks5+ if proxyUrl.startswith("socks5h://"):+ proxyUrl = "socks5://" + proxyUrl[len("socks5h://"):]args.append("--use-system-proxy=false")if proxyUrl:args.append(f"--custom-proxy={proxyUrl}")@@ -163,22 +102,18 @@ class M3U8Worker(Worker):if ffmpegPath:args.append(f"--ffmpeg-binary-path={ffmpegPath}")- if meta.get("liveRealTimeMerge"):+ if stage.liveRealTimeMerge:args.append("--live-real-time-merge=true")- args.append(f"--live-keep-segments={_toBool(meta.get('liveKeepSegments', False))}")- args.append(f"--live-pipe-mux={_toBool(meta.get('livePipeMux', False))}")+ args.append(f"--live-keep-segments={_toBool(stage.liveKeepSegments)}")+ args.append(f"--live-pipe-mux={_toBool(stage.livePipeMux)}")else:- outputFormat = meta.get("outputFormat", "mp4")- muxOption = f"format={outputFormat}:muxer=ffmpeg"+ muxOption = f"format={stage.outputFormat}:muxer=ffmpeg"if ffmpegPath:muxOption += f":bin_path={ffmpegPath}"args.append(f"--mux-after-done={muxOption}")- headers = meta.get("headers", {})- for name, value in headers.items():- if value is None:- continue- text = str(value).strip()+ for name, value in stage.headers.items():+ text = value.strip()if not text:continueargs.extend(["-H", f"{name}: {text}"])@@ -199,7 +134,7 @@ class M3U8Worker(Worker):self.stage.speed = toBytes(vodMatch.group(8), vodMatch.group(9))totalSize = toBytes(vodMatch.group(6), vodMatch.group(7))if totalSize > 0:- self.task.fileSize = totalSize+ self.stage.task.fileSize = totalSizereturnliveMatch = _LIVE_PROGRESS_PATTERN.search(text)@@ -207,10 +142,7 @@ class M3U8Worker(Worker):self.stage.progress = float(liveMatch.group(4))self.stage.speed = 0 if liveMatch.group(5) == "-" else toBytes(liveMatch.group(6), liveMatch.group(7))- async def supervisor(self, stream: asyncio.StreamReader | None):- if stream is None:- return-+ async def supervisor(self, stream: asyncio.StreamReader):buffer = ""while True:chunk = await stream.read(4096)@@ -230,37 +162,28 @@ class M3U8Worker(Worker):def _updateOutput(self):target = Path(self.stage.outputFile)if target.is_file():- self.task.metadata["actualExtension"] = target.suffix.lstrip(".")- self.task.fileSize = max(self.task.fileSize, target.stat().st_size)+ self.stage.actualExtension = target.suffix.lstrip(".")+ self.stage.task.fileSize = max(self.stage.task.fileSize, target.stat().st_size)return- outputDir = self.task.path+ outputDir = self.stage.task.pathif not outputDir.is_dir():return- meta = self.task.metadata- saveName = meta.get("saveName", _stem(self.task.title))- outputExtension = meta.get("actualExtension") or (- "ts" if meta.get("liveRealTimeMerge") else meta.get("outputFormat", "mp4")- )-- prefix = saveName.lower()- ignoredSuffixes = {".json", ".txt", ".log", ".tmp", ".ghd"}- candidates: list[Path] = []-- for candidate in outputDir.iterdir():- if not candidate.is_file():- continue- if candidate.suffix.lower() in ignoredSuffixes:- continue- if not candidate.name.lower().startswith(prefix):- continue- candidates.append(candidate)+ fallbackExtension = "ts" if self.stage.liveRealTimeMerge else self.stage.outputFormat+ expectedSuffix = f".{self.stage.actualExtension or fallbackExtension}"+ prefix = self.stage.saveName.lower()+ candidates = [+ candidate+ for candidate in outputDir.iterdir()+ if candidate.is_file()+ and candidate.suffix.lower() not in _IGNORED_OUTPUT_SUFFIXES+ and candidate.name.lower().startswith(prefix)+ ]if not candidates:return- expectedSuffix = f".{outputExtension}"candidates.sort(key=lambda path: (path.suffix.lower() != expectedSuffix,@@ -268,17 +191,17 @@ class M3U8Worker(Worker):))found = candidates[0]- self.task.metadata["actualExtension"] = found.suffix.lstrip(".")- self.task.fileSize = max(self.task.fileSize, found.stat().st_size)- if found.name != self.task.title:- self.task.setTitle(found.name)+ self.stage.actualExtension = found.suffix.lstrip(".")+ self.stage.task.fileSize = max(self.stage.task.fileSize, found.stat().st_size)+ if found.name != self.stage.task.title:+ self.stage.task.setTitle(found.name)async def run(self):execPath = downloaderPath()if not execPath:raise RuntimeError("未找到可用的 N_m3u8DL-RE,请先在设置中安装或配置运行时")- self.task.path.mkdir(parents=True, exist_ok=True)+ self.stage.task.path.mkdir(parents=True, exist_ok=True)Path(self.stage.tempDir).mkdir(parents=True, exist_ok=True)process = None@@ -288,7 +211,7 @@ class M3U8Worker(Worker):process = await asyncio.create_subprocess_exec(execPath,*args,- cwd=str(Path(execPath).parent),+ cwd=Path(execPath).parent,stdin=asyncio.subprocess.DEVNULL,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT,@@ -296,8 +219,7 @@ class M3U8Worker(Worker):supervisorTask = asyncio.create_task(self.supervisor(process.stdout))await process.wait()- if supervisorTask is not None:- await supervisorTask+ await supervisorTaskif process.returncode != 0:message = self.stage.lastMessage or f"N_m3u8DL-RE 退出码异常: {process.returncode}"@@ -325,99 +247,3 @@ class M3U8Worker(Worker):M3U8TaskStage.workerType = M3U8Worker---async def createInstallTask() -> Task:- from app.services.feature_service import featureService-- machine = platform.machine().lower()- if sys.platform == "win32":- if machine in {"amd64", "x86_64"}:- target, archLabel = "win-x64", "Windows x64"- elif machine in {"arm64", "aarch64"}:- target, archLabel = "win-arm64", "Windows ARM64"- else:- target, archLabel = "win-NT6.0-x86", "Windows x86"- elif sys.platform == "darwin":- if machine in {"arm64", "aarch64"}:- target, archLabel = "osx-arm64", "macOS Apple Silicon"- else:- target, archLabel = "osx-x64", "macOS Intel"- elif sys.platform == "linux":- libcName = platform.libc_ver()[0].lower()- if machine in {"arm64", "aarch64"}:- target, archLabel = ("linux-musl-arm64", "Linux musl ARM64") if libcName == "musl" else ("linux-arm64", "Linux ARM64")- else:- target, archLabel = ("linux-musl-x64", "Linux musl x64") if libcName == "musl" else ("linux-x64", "Linux x64")- else:- raise RuntimeError(f"当前平台暂不支持一键安装 N_m3u8DL-RE: {sys.platform}")-- async with niquests.AsyncSession(headers=_M3U8DL_RELEASE_HEADERS, timeout=30, happy_eyeballs=True) as client:- client.trust_env = False- response = await client.get(- _M3U8DL_RELEASE_API,- proxies=getProxies(),- verify=cfg.SSLVerify.value,- allow_redirects=True,- )- response.raise_for_status()- payload = response.json()-- assets = payload.get("assets")- if not isinstance(assets, list):- raise RuntimeError("GitHub Release 返回了无效的 assets 数据")-- asset = None- for item in assets:- if target in str(item.get("name") or ""):- asset = item- break- if asset is None:- raise RuntimeError(f"未找到适用于当前平台的 N_m3u8DL-RE 安装包: {target}")-- downloadUrl = str(asset.get("browser_download_url") or "").strip()- assetName = str(asset.get("name") or "").strip()- size = int(asset.get("size") or 0)- if not downloadUrl or not assetName or size <= 0:- raise RuntimeError("GitHub Release 返回了不完整的安装包信息")-- installFolder = m3u8Config.installFolder.value- downloadPayload = {- "url": downloadUrl,- "headers": DEFAULT_HEADERS.copy(),- "proxies": getProxies(),- "path": Path(installFolder),- }- downloadTask = await featureService.parse(downloadPayload)-- if not downloadTask.stages:- raise RuntimeError("解析 N_m3u8DL-RE 安装包链接后未获取到下载阶段")-- downloadStage: HttpTaskStage = downloadTask.stages[0]- archiveSize = downloadTask.fileSize if downloadTask.fileSize > 0 else size- archivePath = toPosixPath(Path(installFolder) / (downloadTask.title or assetName))-- downloadStage.stageIndex = 1- downloadStage.outputFile = archivePath-- task = Task(- title=f"N_m3u8DL-RE 安装 ({archLabel})",- url=downloadUrl,- packId="m3u8",- fileSize=archiveSize,- path=Path(installFolder),- usesSlot=False,- metadata={- "archiveSize": archiveSize,- "installFolder": installFolder,- "assetName": assetName,- },- )- task.addStage(downloadStage)- task.addStage(ExtractStage(- stageIndex=2,- archivePath=archivePath,- installFolder=toPosixPath(Path(installFolder)),- executableNames=[toExecutable("N_m3u8DL-RE")],- ))- return task