Skip to content

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

refactor(pack): 移除手动可执行文件路径配置并引入通用提取功能

XiaoYouChRc7e97a44701d
diff --git a/features/extract_pack/manifest.toml b/features/extract_pack/manifest.toml
new file mode 100644
index 00000000..a6de767b
--- /dev/null
+++ b/features/extract_pack/manifest.toml
@@ -0,0 +1,2 @@
+[pack]
+entry = "pack.py"
diff --git a/features/extract_pack/pack.py b/features/extract_pack/pack.py
new file mode 100644
index 00000000..3aed5dc1
--- /dev/null
+++ b/features/extract_pack/pack.py
@@ -0,0 +1,4 @@
+from app.bases.interfaces import FeaturePack
+
+class ExtractPack(FeaturePack):
+ pass
diff --git a/features/extract_pack/task.py b/features/extract_pack/task.py
new file mode 100644
index 00000000..1f7ab916
--- /dev/null
+++ b/features/extract_pack/task.py
@@ -0,0 +1,247 @@
+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 TaskStage, TaskStatus
+
+
+def _normalizePath(path: Path | str) -> str:
+ return str(Path(path)).replace("\\", "/")
+
+
+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
+class ExtractStage(TaskStage):
+ archivePath: str
+ installFolder: str
+ executableNames: list[str]
+ extractedExecutables: dict[str, str] = field(default_factory=dict)
+ cleanupArchive: bool = field(default=True)
+
+
+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 = getattr(self.stage, "_task", None)
+ if task is None:
+ return
+
+ archiveSize = int(getattr(task, "archiveSize", 0) or 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] = _normalizePath(executablePath)
+
+ return executables
+
+ async def run(self):
+ archivePath = Path(self.stage.archivePath)
+ if not archivePath.is_file():
+ self.stage.setStatus(TaskStatus.FAILED)
+ 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)
diff --git a/features/ffmpeg_pack/config.py b/features/ffmpeg_pack/config.py
index 20409075..0b1a4666 100644
--- a/features/ffmpeg_pack/config.py
+++ b/features/ffmpeg_pack/config.py
@@ -8,7 +8,6 @@ from PySide6.QtCore import QStandardPaths, Qt, Signal
from PySide6.QtWidgets import QFileDialog
from qfluentwidgets import (
ConfigItem,
- ConfigValidator,
FluentIcon,
FolderValidator,
SettingCard,
@@ -25,16 +24,6 @@ if TYPE_CHECKING:
from app.view.windows.main_window import MainWindow
-class ExecutablePathValidator(ConfigValidator):
- def validate(self, value) -> bool:
- return isinstance(value, str)
-
- def correct(self, value) -> str:
- if not isinstance(value, str):
- return ""
- return str(Path(value)).replace("\\", "/") if value else ""
-
-
def _executableName(name: str) -> str:
return f"{name}.exe" if sys.platform == "win32" else name
@@ -46,11 +35,7 @@ def _guessInstallRoot(ffmpegPath: str) -> str:
return str(path.parent).replace("\\", "/")
-def _resolveExecutable(name: str, configuredPath: str) -> str:
- path = Path(configuredPath)
- if configuredPath and path.is_file():
- return str(path).replace("\\", "/")
-
+def _resolveExecutable(name: str) -> str:
installFolder = Path(ffmpegConfig.installFolder.value)
for candidate in (installFolder / "bin" / _executableName(name), installFolder / _executableName(name)):
if candidate.is_file():
@@ -61,14 +46,7 @@ def _resolveExecutable(name: str, configuredPath: str) -> str:
def resolveFFmpegExecutables() -> tuple[str, str]:
- ffmpegPath = _resolveExecutable("ffmpeg", ffmpegConfig.ffmpegPath.value)
- ffprobePath = _resolveExecutable("ffprobe", ffmpegConfig.ffprobePath.value)
- return ffmpegPath, ffprobePath
-
-
-def setPreferredFFmpegExecutables(ffmpegPath: str, ffprobePath: str):
- cfg.set(ffmpegConfig.ffmpegPath, ffmpegPath)
- cfg.set(ffmpegConfig.ffprobePath, ffprobePath)
+ return _resolveExecutable("ffmpeg"), _resolveExecutable("ffprobe")
async def queryFFmpegRuntime() -> dict[str, str]:
@@ -121,9 +99,6 @@ class FFmpegInstallFolderCard(SettingCard):
def _updatePath(self, path: str):
cfg.set(ffmpegConfig.installFolder, path)
- # 修改安装目录时,清空安装器写入的首选路径,重新回到目录/PATH 探测逻辑
- cfg.set(ffmpegConfig.ffmpegPath, "")
- cfg.set(ffmpegConfig.ffprobePath, "")
self.setContent(ffmpegConfig.installFolder.value)
self.pathChanged.emit(ffmpegConfig.installFolder.value)
@@ -197,8 +172,6 @@ class FFmpegRuntimeCard(SettingCard):
class FFmpegConfig(PackConfig):
installFolder = ConfigItem("FFmpeg", "InstallFolder", f"{QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppLocalDataLocation)}/GhostDownloader/FFmpeg", FolderValidator())
- ffmpegPath = ConfigItem("FFmpeg", "PreferredFFmpegPath", "", ExecutablePathValidator())
- ffprobePath = ConfigItem("FFmpeg", "PreferredFFprobePath", "", ExecutablePathValidator())
def loadSettingCards(self, settingPage: "SettingPage"):
self.ffmpegGroup = SettingCardGroup(self.tr("FFmpeg"), settingPage.container)
diff --git a/features/ffmpeg_pack/manifest.toml b/features/ffmpeg_pack/manifest.toml
index 784ec150..7b5f6ce0 100644
--- a/features/ffmpeg_pack/manifest.toml
+++ b/features/ffmpeg_pack/manifest.toml
@@ -1,3 +1,3 @@
[pack]
entry = "pack.py"
-dependencies = ["http_pack"]
+dependencies = ["http_pack", "extract_pack"]
diff --git a/features/ffmpeg_pack/task.py b/features/ffmpeg_pack/task.py
index 6746d6de..11587553 100644
--- a/features/ffmpeg_pack/task.py
+++ b/features/ffmpeg_pack/task.py
@@ -1,12 +1,9 @@
import asyncio
import platform
-import shutil
import sys
-import zipfile
from contextlib import suppress
from dataclasses import dataclass, field
from pathlib import Path
-from time import perf_counter
from typing import Any, TYPE_CHECKING
import niquests
@@ -17,18 +14,17 @@ from app.bases.models import Task, TaskStage, TaskStatus
from app.services.core_service import coreService
from app.supports.config import DEFAULT_HEADERS, cfg
from app.supports.utils import getProxies
-from .config import (
- ffmpegConfig,
- resolveFFmpegExecutables,
- setPreferredFFmpegExecutables,
-)
+from .config import ffmpegConfig, resolveFFmpegExecutables
if TYPE_CHECKING:
from features.http_pack.task import HttpTaskStage, HttpWorker
+ from features.extract_pack.task import ExtractStage, ExtractWorker
else:
try:
+ from extract_pack.task import ExtractStage, ExtractWorker
from http_pack.task import HttpTaskStage, HttpWorker
except ImportError:
+ from features.extract_pack.task import ExtractStage, ExtractWorker
from features.http_pack.task import HttpTaskStage, HttpWorker
@@ -259,165 +255,6 @@ class FFmpegWorker(Worker):
logger.opt(exception=e).error("failed to cleanup temporary file {}", path)
-@dataclass
-class FFmpegExtractStage(TaskStage):
- archivePath: str
- installFolder: str
- ffmpegPath: str
- ffprobePath: str
- cleanupArchive: bool = field(default=True)
-
-
-class FFmpegExtractWorker(Worker):
- chunkSize = 1048576
-
- def __init__(self, stage: FFmpegExtractStage):
- 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 = getattr(self.stage, "_task", None)
- if task is None:
- return
-
- archiveSize = int(getattr(task, "archiveSize", 0) or 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:
- directPath = root / "bin" / name
- if directPath.is_file():
- return directPath
-
- for candidate in root.rglob(name):
- if candidate.is_file():
- return candidate
-
- return None
-
- async def _extractArchive(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 = tempDir / info.filename
- targetPath.parent.mkdir(parents=True, exist_ok=True)
-
- with archive.open(info, "r") as source, open(targetPath, "wb") as target:
- while True:
- chunk = source.read(self.chunkSize)
- if not chunk:
- break
-
- 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)
-
- def _installExtractedFiles(self, extractedRoot: Path, installDir: Path, archiveName: str, tempDirName: str) -> tuple[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))
-
- ffmpegPath = self._findExecutable(installDir, _executableName("ffmpeg"))
- ffprobePath = self._findExecutable(installDir, _executableName("ffprobe"))
- if ffmpegPath is None or ffprobePath is None:
- raise RuntimeError("安装包解压完成,但未找到 ffmpeg 或 ffprobe 可执行文件")
-
- return _normalizePath(ffmpegPath), _normalizePath(ffprobePath)
-
- async def run(self):
- if sys.platform != "win32":
- self.stage.setStatus(TaskStatus.FAILED)
- raise RuntimeError("当前平台不支持 FFmpeg 一键安装")
-
- archivePath = Path(self.stage.archivePath)
- if not archivePath.is_file():
- self.stage.setStatus(TaskStatus.FAILED)
- raise FileNotFoundError(f"未找到 FFmpeg 安装包: {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)
-
- with zipfile.ZipFile(archivePath) as archive:
- extractSize = sum(info.file_size for info in archive.infolist() if not info.is_dir())
-
- self._updateTaskFileSize(extractSize)
- await self._extractArchive(archivePath, tempDir, extractSize)
-
- extractedRoot = self._resolveExtractedRoot(tempDir)
- ffmpegPath, ffprobePath = self._installExtractedFiles(
- extractedRoot,
- installDir,
- archivePath.name,
- tempDir.name,
- )
-
- task = getattr(self.stage, "_task", None)
- if task is not None:
- task.ffmpegPath = ffmpegPath
- task.ffprobePath = ffprobePath
-
- cfg.set(ffmpegConfig.installFolder, _normalizePath(installDir))
- setPreferredFFmpegExecutables(ffmpegPath, ffprobePath)
-
- if self.stage.cleanupArchive and archivePath.exists():
- archivePath.unlink()
-
- self.stage.ffmpegPath = ffmpegPath
- self.stage.ffprobePath = ffprobePath
- 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)
-
-
@dataclass(kw_only=True)
class FFmpegInstallTask(Task):
url: str
@@ -443,17 +280,17 @@ class FFmpegInstallTask(Task):
installDir = Path(self.installFolder)
self.path = installDir
self.archivePath = _normalizePath(installDir / self.assetName)
- self.ffmpegPath = _normalizePath(installDir / "bin" / _executableName("ffmpeg"))
- self.ffprobePath = _normalizePath(installDir / "bin" / _executableName("ffprobe"))
+ if not self.ffmpegPath:
+ self.ffmpegPath = _normalizePath(installDir / "bin" / _executableName("ffmpeg"))
+ if not self.ffprobePath:
+ self.ffprobePath = _normalizePath(installDir / "bin" / _executableName("ffprobe"))
for stage in self.stages:
if isinstance(stage, HttpTaskStage):
stage.resolvePath = self.archivePath
- elif isinstance(stage, FFmpegExtractStage):
+ elif isinstance(stage, ExtractStage):
stage.archivePath = self.archivePath
stage.installFolder = _normalizePath(installDir)
- stage.ffmpegPath = self.ffmpegPath
- stage.ffprobePath = self.ffprobePath
async def run(self):
self.stages.sort(key=lambda stage: stage.stageIndex)
@@ -470,8 +307,10 @@ class FFmpegInstallTask(Task):
await HttpWorker(stage).run()
continue
- if isinstance(stage, FFmpegExtractStage):
- await FFmpegExtractWorker(stage).run()
+ if isinstance(stage, ExtractStage):
+ await ExtractWorker(stage).run()
+ self.ffmpegPath = stage.extractedExecutables[_executableName("ffmpeg")]
+ self.ffprobePath = stage.extractedExecutables[_executableName("ffprobe")]
continue
raise TypeError(f"不支持的 FFmpegInstallTaskStage: {type(stage).__name__}")
@@ -524,16 +363,15 @@ async def createWindowsInstallTask() -> FFmpegInstallTask:
)
downloadStage.stageIndex = 1
- downloadStage.resolvePath = task.archivePath
- extractStage = FFmpegExtractStage(
- stageIndex=2,
- archivePath=task.archivePath,
- installFolder=task.installFolder,
- ffmpegPath=task.ffmpegPath,
- ffprobePath=task.ffprobePath,
- )
-
task.addStage(downloadStage)
- task.addStage(extractStage)
+ task.addStage(
+ ExtractStage(
+ stageIndex=2,
+ archivePath="",
+ installFolder="",
+ executableNames=[_executableName("ffmpeg"), _executableName("ffprobe")],
+ )
+ )
+ task.syncStagePaths()
setattr(task, "_featurePackName", "ffmpeg_pack")
return task
diff --git a/features/http_pack/task.py b/features/http_pack/task.py
index 2991c967..3aa7af49 100644
--- a/features/http_pack/task.py
+++ b/features/http_pack/task.py
@@ -378,6 +378,7 @@ class HttpWorker(Worker):
self.client = niquests.AsyncSession(happy_eyeballs=True, pool_maxsize=256)
self.client.trust_env = False
shouldCleanupRecordFile = False
+ Path(self.stage.resolvePath).parent.mkdir(parents=True, exist_ok=True)
restored = False
if self.stage.fileSize != SpecialFileSize.NOT_SUPPORTED:
diff --git a/features/m3u8_pack/config.py b/features/m3u8_pack/config.py
index e83ea063..c4cc5042 100644
--- a/features/m3u8_pack/config.py
+++ b/features/m3u8_pack/config.py
@@ -10,7 +10,6 @@ from qfluentwidgets import (
BoolValidator,
ComboBoxSettingCard,
ConfigItem,
- ConfigValidator,
FluentIcon,
FolderValidator,
InfoBar,
@@ -42,16 +41,6 @@ except ImportError:
from features.ffmpeg_pack.config import resolveFFmpegExecutables
-class ExecutablePathValidator(ConfigValidator):
- def validate(self, value) -> bool:
- return isinstance(value, str)
-
- def correct(self, value) -> str:
- if not isinstance(value, str):
- return ""
- return str(Path(value)).replace("\\", "/") if value else ""
-
-
def _normalizePath(path: Path | str) -> str:
return str(Path(path)).replace("\\", "/")
@@ -64,11 +53,7 @@ def _guessInstallRoot(downloaderPath: str) -> str:
return _normalizePath(Path(downloaderPath).parent)
-def _resolveExecutable(configuredPath: str) -> str:
- path = Path(configuredPath)
- if configuredPath and path.is_file():
- return _normalizePath(path)
-
+def _resolveExecutable() -> str:
installFolder = Path(m3u8Config.installFolder.value)
candidate = installFolder / _executableName("N_m3u8DL-RE")
if candidate.is_file():
@@ -81,11 +66,7 @@ def _resolveExecutable(configuredPath: str) -> str:
def resolveM3U8DownloaderExecutable() -> str:
- return _resolveExecutable(m3u8Config.downloaderPath.value)
-
-
-def setPreferredM3U8Downloader(path: str):
- cfg.set(m3u8Config.downloaderPath, path)
+ return _resolveExecutable()
async def queryM3U8Runtime() -> dict[str, str]:
@@ -138,7 +119,6 @@ class M3U8InstallFolderCard(SettingCard):
def _updatePath(self, path: str):
cfg.set(m3u8Config.installFolder, path)
- cfg.set(m3u8Config.downloaderPath, "")
self.setContent(m3u8Config.installFolder.value)
self.pathChanged.emit(m3u8Config.installFolder.value)
@@ -182,7 +162,7 @@ class M3U8RuntimeCard(SettingCard):
ffmpegPath = str(runtimeInfo.get("ffmpegPath") or "").strip()
if downloaderPath:
- ffmpegText = self.tr("已检测到") if ffmpegPath else self.tr("未检测到,部分流可能无法自动混流")
+ ffmpegText = ffmpegPath if ffmpegPath else self.tr("未检测到,部分流可能无法自动混流")
content = self.tr("版本: {0}\n安装路径: {1}\nFFmpeg: {2}").format(
version or self.tr("未知"),
installPath or downloaderPath,
@@ -218,7 +198,6 @@ class M3U8Config(PackConfig):
f"{QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppLocalDataLocation)}/GhostDownloader/M3U8DL",
FolderValidator(),
)
- downloaderPath = ConfigItem("M3U8", "PreferredRuntimePath", "", ExecutablePathValidator())
outputFormat = OptionsConfigItem("M3U8", "OutputFormat", "mp4", OptionsValidator(["mp4", "mkv"]))
threadCount = RangeConfigItem("M3U8", "ThreadCount", 8, RangeValidator(1, 64))
retryCount = RangeConfigItem("M3U8", "RetryCount", 3, RangeValidator(0, 20))
diff --git a/features/m3u8_pack/manifest.toml b/features/m3u8_pack/manifest.toml
index 209f7371..184517d6 100644
--- a/features/m3u8_pack/manifest.toml
+++ b/features/m3u8_pack/manifest.toml
@@ -1,3 +1,3 @@
[pack]
entry = "pack.py"
-dependencies = ["http_pack", "ffmpeg_pack"]
+dependencies = ["http_pack", "extract_pack", "ffmpeg_pack"]
diff --git a/features/m3u8_pack/task.py b/features/m3u8_pack/task.py
index 44b28033..24a73038 100644
--- a/features/m3u8_pack/task.py
+++ b/features/m3u8_pack/task.py
@@ -1,15 +1,11 @@
import asyncio
import platform
import re
-import shutil
import sys
-import tarfile
-import zipfile
from contextlib import suppress
from dataclasses import dataclass, field
from email.message import Message
from pathlib import Path
-from time import perf_counter
from typing import Any, TYPE_CHECKING
from urllib.parse import parse_qs, unquote, urlparse
@@ -21,20 +17,19 @@ from app.bases.models import Task, TaskStage, TaskStatus
from app.services.core_service import coreService
from app.supports.config import DEFAULT_HEADERS, cfg
from app.supports.utils import getProxies
-from .config import (
- m3u8Config,
- resolveM3U8DownloaderExecutable,
- setPreferredM3U8Downloader,
-)
+from .config import m3u8Config, resolveM3U8DownloaderExecutable
if TYPE_CHECKING:
from features.ffmpeg_pack.config import resolveFFmpegExecutables
from features.http_pack.task import HttpTaskStage, HttpWorker, httpConfig
+ from features.extract_pack.task import ExtractStage, ExtractWorker
else:
try:
+ from extract_pack.task import ExtractStage, ExtractWorker
from ffmpeg_pack.config import resolveFFmpegExecutables
from http_pack.task import HttpTaskStage, HttpWorker, httpConfig
except ImportError:
+ from features.extract_pack.task import ExtractStage, ExtractWorker
from features.ffmpeg_pack.config import resolveFFmpegExecutables
from features.http_pack.task import HttpTaskStage, HttpWorker, httpConfig
@@ -172,20 +167,6 @@ def _executableName(name: str) -> str:
return f"{name}.exe" if sys.platform == "win32" else name
-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
-
-
def _detectRuntimeTarget() -> tuple[str, str]:
machine = platform.machine().lower()
@@ -639,216 +620,6 @@ async def parse(payload: dict) -> M3U8Task:
return task
-@dataclass
-class M3U8ExtractStage(TaskStage):
- archivePath: str
- installFolder: str
- executablePath: str
- cleanupArchive: bool = field(default=True)
-
-
-class M3U8ExtractWorker(Worker):
- chunkSize = 1048576
-
- def __init__(self, stage: M3U8ExtractStage):
- 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 = getattr(self.stage, "_task", None)
- if task is None:
- return
-
- archiveSize = int(getattr(task, "archiveSize", 0) or 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) -> Path | None:
- directPath = root / _executableName("N_m3u8DL-RE")
- if directPath.is_file():
- return directPath
-
- for candidate in root.rglob(_executableName("N_m3u8DL-RE")):
- if candidate.is_file():
- return candidate
-
- return None
-
- 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, open(targetPath, "wb") as target:
- while True:
- chunk = source.read(self.chunkSize)
- if not chunk:
- break
-
- 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 _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, open(targetPath, "wb") as target:
- while True:
- chunk = source.read(self.chunkSize)
- if not chunk:
- break
-
- 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 _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) -> 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))
-
- executablePath = self._findExecutable(installDir)
- if executablePath is None:
- raise RuntimeError("安装包解压完成,但未找到 N_m3u8DL-RE 可执行文件")
-
- if sys.platform != "win32":
- executablePath.chmod(executablePath.stat().st_mode | 0o755)
-
- return _normalizePath(executablePath)
-
- async def run(self):
- archivePath = Path(self.stage.archivePath)
- if not archivePath.is_file():
- self.stage.setStatus(TaskStatus.FAILED)
- raise FileNotFoundError(f"未找到 N_m3u8DL-RE 安装包: {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)
- executablePath = self._installExtractedFiles(
- extractedRoot,
- installDir,
- archivePath.name,
- tempDir.name,
- )
-
- task = getattr(self.stage, "_task", None)
- if task is not None:
- task.executablePath = executablePath
-
- cfg.set(m3u8Config.installFolder, _normalizePath(installDir))
- setPreferredM3U8Downloader(executablePath)
-
- if self.stage.cleanupArchive and archivePath.exists():
- archivePath.unlink()
-
- self.stage.executablePath = executablePath
- 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)
-
-
@dataclass(kw_only=True)
class M3U8InstallTask(Task):
url: str
@@ -879,10 +650,9 @@ class M3U8InstallTask(Task):
for stage in self.stages:
if isinstance(stage, HttpTaskStage):
stage.resolvePath = self.archivePath
- elif isinstance(stage, M3U8ExtractStage):
+ elif isinstance(stage, ExtractStage):
stage.archivePath = self.archivePath
stage.installFolder = _normalizePath(installDir)
- stage.executablePath = self.executablePath
async def run(self):
self.stages.sort(key=lambda stage: stage.stageIndex)
@@ -899,8 +669,9 @@ class M3U8InstallTask(Task):
await HttpWorker(stage).run()
continue
- if isinstance(stage, M3U8ExtractStage):
- await M3U8ExtractWorker(stage).run()
+ if isinstance(stage, ExtractStage):
+ await ExtractWorker(stage).run()
+ self.executablePath = stage.extractedExecutables[_executableName("N_m3u8DL-RE")]
continue
raise TypeError(f"不支持的 M3U8InstallTaskStage: {type(stage).__name__}")
@@ -953,15 +724,15 @@ async def createInstallTask() -> M3U8InstallTask:
)
downloadStage.stageIndex = 1
- downloadStage.resolvePath = task.archivePath
- extractStage = M3U8ExtractStage(
- stageIndex=2,
- archivePath=task.archivePath,
- installFolder=task.installFolder,
- executablePath=task.executablePath,
- )
-
task.addStage(downloadStage)
- task.addStage(extractStage)
+ task.addStage(
+ ExtractStage(
+ stageIndex=2,
+ archivePath="",
+ installFolder="",
+ executableNames=[_executableName("N_m3u8DL-RE")],
+ )
+ )
+ task.syncStagePaths()
setattr(task, "_featurePackName", "m3u8_pack")
return task