Skip to content

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

feat(m3u8): 添加 M3U8 流媒体下载功能支持

XiaoYouChR34d45eb88755
diff --git a/features/m3u8_pack/cards.py b/features/m3u8_pack/cards.py
new file mode 100644
index 00000000..f34708ca
--- /dev/null
+++ b/features/m3u8_pack/cards.py
@@ -0,0 +1,171 @@
+import shutil
+from pathlib import Path
+
+from PySide6.QtCore import QEvent, QFileInfo, Qt
+from PySide6.QtGui import QMouseEvent
+from PySide6.QtWidgets import QFileIconProvider, QHBoxLayout, QWidget
+from qfluentwidgets import BodyLabel, ImageLabel, LineEdit, StrongBodyLabel
+
+from app.bases.models import TaskStatus
+from app.supports.utils import getReadableSize, getReadableTime
+from app.view.components.cards import ResultCard, UniversalTaskCard
+
+from .task import M3U8InstallTask, M3U8Task
+
+
+def _removeFile(path: Path):
+ try:
+ if path.is_file() or path.is_symlink():
+ path.unlink()
+ except FileNotFoundError:
+ pass
+
+
+class M3U8TaskCard(UniversalTaskCard):
+ def _renderTaskState(self):
+ division = max(1, len(self.task.stages))
+ progress = 0.0
+ speed = 0
+ receivedBytes = 0
+
+ for stage in self.task.stages:
+ progress += stage.progress
+ speed += stage.speed
+ receivedBytes += stage.receivedBytes
+
+ progress /= division
+ self.progressBar.setValue(progress)
+
+ if self.task.fileSize > 1:
+ self.progressLabel.setText(f"{getReadableSize(receivedBytes)}/{getReadableSize(self.task.fileSize)}")
+ else:
+ self.progressLabel.setText(self.tr("{0} / {1:.2f}%").format(getReadableSize(receivedBytes), progress))
+
+ if self.task.status == TaskStatus.RUNNING:
+ self.progressBar.setError(False)
+ if self.infoLabel.isVisible():
+ self.infoLabel.hide()
+ self.speedLabel.show()
+ self.leftTimeLabel.show()
+ self.progressLabel.show()
+ self.speedLabel.setText(f"{getReadableSize(speed)}/s")
+ if self.task.fileSize > 1 and speed > 0:
+ self.leftTimeLabel.setText(getReadableTime(int((self.task.fileSize - receivedBytes) / speed)))
+ else:
+ self.leftTimeLabel.setText("--")
+ elif self.task.status == TaskStatus.COMPLETED:
+ self.progressBar.setError(False)
+ self.progressBar.hide()
+ self.showStatusInfo(self.tr("任务已经完成"))
+ elif self.task.status == TaskStatus.FAILED:
+ self.progressBar.error()
+ self.onTaskFailed()
+ elif self.task.status == TaskStatus.PAUSED:
+ self.progressBar.setError(False)
+ self.progressBar.pause()
+ self.showStatusInfo(self.tr("任务已经暂停"))
+ else:
+ self.progressBar.setError(False)
+ self.progressBar.pause()
+ self.showStatusInfo(self.tr("任务正在等待"))
+
+ self.refreshToggleButton()
+
+ def onTaskDeleted(self, completely: bool = False):
+ if not completely:
+ return
+
+ task = self.task
+ _removeFile(Path(task.resolvePath))
+ shutil.rmtree(Path(task.tempDir), ignore_errors=True)
+
+ outputDirectory = Path(task.path)
+ if outputDirectory.exists():
+ prefix = f"{task.saveName}."
+ for candidate in outputDirectory.iterdir():
+ if candidate.name == Path(task.resolvePath).name:
+ continue
+ if candidate.is_file() and candidate.name.startswith(prefix):
+ _removeFile(candidate)
+
+
+class M3U8InstallTaskCard(UniversalTaskCard):
+ def onTaskDeleted(self, completely: bool = False):
+ if not completely:
+ return
+
+ if isinstance(self.task, M3U8InstallTask):
+ shutil.rmtree(self.task.installFolder, ignore_errors=True)
+ return
+
+ super().onTaskDeleted(completely)
+
+
+class M3U8ResultCard(ResultCard):
+ def __init__(self, task: M3U8Task, parent: QWidget = None):
+ super().__init__(task, parent)
+ self.task = task
+ self.iconLabel = ImageLabel(self)
+ self.filenameLabel = StrongBodyLabel(self.task.title, self)
+ self.filenameEdit = LineEdit(self)
+ self.metaLabel = BodyLabel(self._metaText(), self)
+ self.mainLayout = QHBoxLayout(self)
+
+ self._initWidget()
+ self._initLayout()
+
+ def _initWidget(self):
+ self.setFixedHeight(35)
+ self._refreshIcon()
+ self.filenameLabel.setCursor(Qt.CursorShape.PointingHandCursor)
+ self.filenameLabel.installEventFilter(self)
+ self.filenameEdit.setText(self.task.title)
+ self.filenameEdit.editingFinished.connect(self._onEditingFinished)
+ self.filenameEdit.hide()
+
+ def _initLayout(self):
+ self.mainLayout.setContentsMargins(10, 2, 10, 2)
+ self.mainLayout.setSpacing(12)
+ self.mainLayout.addWidget(self.iconLabel)
+ self.mainLayout.addWidget(self.filenameLabel)
+ self.mainLayout.addWidget(self.filenameEdit)
+ self.mainLayout.addStretch()
+ self.mainLayout.addWidget(self.metaLabel)
+
+ def _metaText(self) -> str:
+ manifestText = "DASH" if self.task.manifestType == "mpd" else "HLS"
+ modeText = self.tr("直播") if self.task.isLive else self.tr("点播")
+ return f"{manifestText} · {modeText}"
+
+ def _refreshIcon(self):
+ icon = QFileIconProvider().icon(QFileInfo(self.task.resolvePath))
+ self.iconLabel.setImage(icon.pixmap(16, 16))
+ self.iconLabel.setFixedSize(16, 16)
+
+ def eventFilter(self, obj, event: QEvent):
+ if obj is self.filenameLabel:
+ if event.type() == QEvent.Type.MouseButtonDblClick and isinstance(event, QMouseEvent):
+ if event.button() == Qt.MouseButton.LeftButton:
+ self._enterEditMode()
+ return True
+ return super().eventFilter(obj, event)
+
+ def _enterEditMode(self):
+ self.filenameLabel.hide()
+ self.filenameEdit.show()
+ self.filenameEdit.setFocus()
+ self.filenameEdit.selectAll()
+
+ def _onEditingFinished(self):
+ newFilename = self.filenameEdit.text().strip()
+ if newFilename and newFilename != self.task.title:
+ self.task.setTitle(newFilename)
+ self.filenameLabel.setText(self.task.title)
+ self.filenameEdit.setText(self.task.title)
+ self._refreshIcon()
+
+ self.filenameEdit.hide()
+ self.filenameLabel.show()
+
+ def getTask(self) -> M3U8Task:
+ return self.task
diff --git a/features/m3u8_pack/config.py b/features/m3u8_pack/config.py
new file mode 100644
index 00000000..e83ea063
--- /dev/null
+++ b/features/m3u8_pack/config.py
@@ -0,0 +1,351 @@
+import asyncio
+import shutil
+import sys
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from PySide6.QtCore import QStandardPaths, Qt, Signal
+from PySide6.QtWidgets import QFileDialog
+from qfluentwidgets import (
+ BoolValidator,
+ ComboBoxSettingCard,
+ ConfigItem,
+ ConfigValidator,
+ FluentIcon,
+ FolderValidator,
+ InfoBar,
+ OptionsConfigItem,
+ OptionsValidator,
+ PrimaryPushButton,
+ RangeConfigItem,
+ RangeSettingCard,
+ RangeValidator,
+ SettingCard,
+ SettingCardGroup,
+ SwitchSettingCard,
+ ToolButton,
+ ToolTipFilter,
+)
+
+from app.bases.models import PackConfig
+from app.services.core_service import coreService
+from app.supports.config import cfg
+from app.view.components.setting_cards import SpinBoxSettingCard
+
+if TYPE_CHECKING:
+ from app.view.pages.setting_page import SettingPage
+ from app.view.windows.main_window import MainWindow
+
+try:
+ from ffmpeg_pack.config import resolveFFmpegExecutables
+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("\\", "/")
+
+
+def _executableName(name: str) -> str:
+ return f"{name}.exe" if sys.platform == "win32" else name
+
+
+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)
+
+ installFolder = Path(m3u8Config.installFolder.value)
+ candidate = installFolder / _executableName("N_m3u8DL-RE")
+ if candidate.is_file():
+ return _normalizePath(candidate)
+
+ found = shutil.which("N_m3u8DL-RE")
+ if not found and sys.platform == "win32":
+ found = shutil.which("N_m3u8DL-RE.exe")
+ return _normalizePath(found) if found else ""
+
+
+def resolveM3U8DownloaderExecutable() -> str:
+ return _resolveExecutable(m3u8Config.downloaderPath.value)
+
+
+def setPreferredM3U8Downloader(path: str):
+ cfg.set(m3u8Config.downloaderPath, path)
+
+
+async def queryM3U8Runtime() -> dict[str, str]:
+ downloaderPath = resolveM3U8DownloaderExecutable()
+ ffmpegPath, _ = resolveFFmpegExecutables()
+ runtimeInfo = {
+ "downloaderPath": downloaderPath,
+ "version": "",
+ "installPath": "",
+ "ffmpegPath": ffmpegPath,
+ }
+ if not downloaderPath:
+ return runtimeInfo
+
+ process = await asyncio.create_subprocess_exec(
+ downloaderPath,
+ "--version",
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ stdout, stderr = await process.communicate()
+ if process.returncode != 0:
+ return runtimeInfo
+
+ output = stdout.decode("utf-8", errors="ignore") or stderr.decode("utf-8", errors="ignore")
+ lines = [line.strip() for line in output.splitlines() if line.strip()]
+ runtimeInfo["version"] = lines[0] if lines else ""
+ runtimeInfo["installPath"] = _guessInstallRoot(downloaderPath)
+ 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)
+ cfg.set(m3u8Config.downloaderPath, "")
+ 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"{QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppLocalDataLocation)}/GhostDownloader/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.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.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)
+
+ def _onRuntimeLoaded(self, result, error: str | None):
+ self.refreshButton.setEnabled(True)
+ if error:
+ self.setContent(self.tr("检测运行时失败"))
+ return
+
+ runtimeInfo = 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()
+
+ if downloaderPath:
+ ffmpegText = self.tr("已检测到") if ffmpegPath else self.tr("未检测到,部分流可能无法自动混流")
+ content = self.tr("版本: {0}\n安装路径: {1}\nFFmpeg: {2}").format(
+ version or self.tr("未知"),
+ installPath or downloaderPath,
+ ffmpegText,
+ )
+ else:
+ content = self.tr("未检测到可用的 N_m3u8DL-RE")
+ self.setContent(content)
+
+ def _onInstallClicked(self):
+ from .task import createInstallTask
+
+ self.installButton.setEnabled(False)
+ self.installButton.setText(self.tr("准备中..."))
+ coreService.runCoroutine(createInstallTask(), self._onInstallTaskCreated)
+
+ 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("安装 N_m3u8DL-RE 失败"), error or self.tr("无法创建安装任务"), duration=-1, parent=mainWindow)
+ return
+
+ mainWindow.addTask(result)
+
+
+class M3U8Config(PackConfig):
+ installFolder = ConfigItem(
+ "M3U8",
+ "InstallFolder",
+ 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))
+ requestTimeout = RangeConfigItem("M3U8", "RequestTimeout", 100, RangeValidator(5, 600))
+ autoSelect = ConfigItem("M3U8", "AutoSelect", True, BoolValidator())
+ concurrentDownload = ConfigItem("M3U8", "ConcurrentDownload", True, BoolValidator())
+ appendUrlParams = ConfigItem("M3U8", "AppendUrlParams", False, BoolValidator())
+ binaryMerge = ConfigItem("M3U8", "BinaryMerge", False, BoolValidator())
+ checkSegmentsCount = ConfigItem("M3U8", "CheckSegmentsCount", True, BoolValidator())
+ liveRealTimeMerge = ConfigItem("M3U8", "LiveRealTimeMerge", False, BoolValidator())
+ liveKeepSegments = ConfigItem("M3U8", "LiveKeepSegments", False, BoolValidator())
+ livePipeMux = ConfigItem("M3U8", "LivePipeMux", False, BoolValidator())
+
+ def loadSettingCards(self, settingPage: "SettingPage"):
+ self.m3u8Group = SettingCardGroup(self.tr("流媒体下载"), settingPage.container)
+ self.installFolderCard = M3U8InstallFolderCard(self.m3u8Group)
+ self.runtimeCard = M3U8RuntimeCard(self.m3u8Group)
+ self.outputFormatCard = ComboBoxSettingCard(
+ self.outputFormat,
+ FluentIcon.VIDEO,
+ self.tr("输出容器"),
+ self.tr("下载完成后优先使用 ffmpeg 混流为指定容器"),
+ texts=["MP4", "MKV"],
+ parent=self.m3u8Group,
+ )
+ self.threadCountCard = RangeSettingCard(
+ self.threadCount,
+ FluentIcon.CLOUD,
+ self.tr("分片线程数"),
+ self.tr("传给 N_m3u8DL-RE 的下载线程数"),
+ self.m3u8Group,
+ )
+ self.retryCountCard = RangeSettingCard(
+ self.retryCount,
+ FluentIcon.SYNC,
+ self.tr("分片重试次数"),
+ self.tr("单个分片下载失败时的最大重试次数"),
+ self.m3u8Group,
+ )
+ self.requestTimeoutCard = SpinBoxSettingCard(
+ FluentIcon.HISTORY,
+ self.tr("请求超时"),
+ self.tr("HTTP 请求超时时间"),
+ " s",
+ self.requestTimeout,
+ self.m3u8Group,
+ 5,
+ )
+ self.autoSelectCard = SwitchSettingCard(
+ FluentIcon.ACCEPT,
+ self.tr("自动选择最佳轨道"),
+ self.tr("默认选择最佳音视频轨道,避免每个链接都手动挑选"),
+ self.autoSelect,
+ self.m3u8Group,
+ )
+ self.concurrentDownloadCard = SwitchSettingCard(
+ FluentIcon.PAUSE,
+ self.tr("并发下载音视频"),
+ self.tr("同时下载已选择的音频、视频和字幕轨道"),
+ self.concurrentDownload,
+ self.m3u8Group,
+ )
+ self.appendUrlParamsCard = SwitchSettingCard(
+ FluentIcon.LINK,
+ self.tr("追加 URL 参数"),
+ self.tr("把输入链接上的 Query 参数追加到分片请求"),
+ self.appendUrlParams,
+ self.m3u8Group,
+ )
+ self.binaryMergeCard = SwitchSettingCard(
+ FluentIcon.ALIGNMENT,
+ self.tr("二进制合并"),
+ self.tr("让 N_m3u8DL-RE 使用二进制方式合并分片"),
+ self.binaryMerge,
+ self.m3u8Group,
+ )
+ self.checkSegmentsCountCard = SwitchSettingCard(
+ FluentIcon.SEARCH,
+ self.tr("校验分片数量"),
+ self.tr("下载完成后检查实际分片数是否与预期一致"),
+ self.checkSegmentsCount,
+ self.m3u8Group,
+ )
+ self.liveRealTimeMergeCard = SwitchSettingCard(
+ FluentIcon.CAMERA,
+ self.tr("直播实时合并"),
+ self.tr("录制直播流时边下边合并"),
+ self.liveRealTimeMerge,
+ self.m3u8Group,
+ )
+ self.liveKeepSegmentsCard = SwitchSettingCard(
+ FluentIcon.SAVE,
+ self.tr("直播保留分片"),
+ self.tr("实时合并直播时仍保留原始分片"),
+ self.liveKeepSegments,
+ self.m3u8Group,
+ )
+ self.livePipeMuxCard = SwitchSettingCard(
+ FluentIcon.CODE,
+ self.tr("直播管道混流"),
+ self.tr("直播实时合并时通过管道交给 ffmpeg 混流"),
+ self.livePipeMux,
+ self.m3u8Group,
+ )
+
+ self.installFolderCard.pathChanged.connect(lambda _: self.runtimeCard.refreshStatus())
+
+ for card in (
+ self.installFolderCard,
+ self.runtimeCard,
+ self.outputFormatCard,
+ self.threadCountCard,
+ self.retryCountCard,
+ self.requestTimeoutCard,
+ self.autoSelectCard,
+ self.concurrentDownloadCard,
+ self.appendUrlParamsCard,
+ self.binaryMergeCard,
+ self.checkSegmentsCountCard,
+ self.liveRealTimeMergeCard,
+ self.liveKeepSegmentsCard,
+ self.livePipeMuxCard,
+ ):
+ self.m3u8Group.addSettingCard(card)
+
+ settingPage.vBoxLayout.addWidget(self.m3u8Group)
+ self.runtimeCard.refreshStatus()
+
+
+m3u8Config = M3U8Config()
diff --git a/features/m3u8_pack/manifest.toml b/features/m3u8_pack/manifest.toml
new file mode 100644
index 00000000..209f7371
--- /dev/null
+++ b/features/m3u8_pack/manifest.toml
@@ -0,0 +1,3 @@
+[pack]
+entry = "pack.py"
+dependencies = ["http_pack", "ffmpeg_pack"]
diff --git a/features/m3u8_pack/pack.py b/features/m3u8_pack/pack.py
new file mode 100644
index 00000000..88c1fe1b
--- /dev/null
+++ b/features/m3u8_pack/pack.py
@@ -0,0 +1,41 @@
+from urllib.parse import urlparse
+
+from app.bases.interfaces import FeaturePack
+from app.bases.models import Task
+
+from .cards import M3U8InstallTaskCard, M3U8ResultCard, M3U8TaskCard
+from .config import m3u8Config
+from .task import M3U8InstallTask, M3U8Task, parse
+
+
+def _isSupportedUrl(url: str) -> bool:
+ parsedUrl = urlparse(url)
+ if parsedUrl.scheme.lower() not in {"http", "https"}:
+ return False
+
+ loweredUrl = url.lower()
+ return any(marker in loweredUrl for marker in (".m3u8", ".m3u", ".mpd"))
+
+
+class M3U8Pack(FeaturePack):
+ priority = 80
+ taskType = (M3U8Task, M3U8InstallTask)
+ config = m3u8Config
+
+ def canHandle(self, url: str) -> bool:
+ return _isSupportedUrl(url)
+
+ async def parse(self, payload: dict) -> Task:
+ return await parse(payload)
+
+ def createTaskCard(self, task: Task, parent=None):
+ if isinstance(task, M3U8InstallTask):
+ return M3U8InstallTaskCard(task, parent)
+ if isinstance(task, M3U8Task):
+ return M3U8TaskCard(task, parent)
+ return None
+
+ def createResultCard(self, task: Task, parent=None):
+ if isinstance(task, M3U8Task):
+ return M3U8ResultCard(task, parent)
+ return None
diff --git a/features/m3u8_pack/task.py b/features/m3u8_pack/task.py
new file mode 100644
index 00000000..44b28033
--- /dev/null
+++ b/features/m3u8_pack/task.py
@@ -0,0 +1,967 @@
+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
+
+import niquests
+from loguru import logger
+
+from app.bases.interfaces import Worker
+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,
+)
+
+if TYPE_CHECKING:
+ from features.ffmpeg_pack.config import resolveFFmpegExecutables
+ from features.http_pack.task import HttpTaskStage, HttpWorker, httpConfig
+else:
+ try:
+ from ffmpeg_pack.config import resolveFFmpegExecutables
+ from http_pack.task import HttpTaskStage, HttpWorker, httpConfig
+ except ImportError:
+ from features.ffmpeg_pack.config import resolveFFmpegExecutables
+ from features.http_pack.task import HttpTaskStage, HttpWorker, httpConfig
+
+
+_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 _normalizePath(path: Path | str) -> str:
+ return str(Path(path)).replace("\\", "/")
+
+
+def _sanitizeName(name: str) -> str:
+ cleaned = re.sub(r'[\x00-\x1f\\/:*?"<>|]+', "_", str(name or "")).strip().rstrip(".")
+ return cleaned or "stream"
+
+
+def _stripKnownSuffix(name: str) -> str:
+ suffix = Path(name).suffix.lower()
+ if suffix in _KNOWN_SUFFIXES:
+ return name[:-len(suffix)]
+ return name
+
+
+def _parseContentDispositionName(headers: dict[str, str]) -> str:
+ cd = headers.get("content-disposition", "")
+ if not cd:
+ return ""
+
+ msg = Message()
+ msg["Content-Disposition"] = cd
+ params = msg.get_params(header="Content-Disposition")
+ paramDict = {key.lower(): value for key, value in params if isinstance(value, str)}
+
+ if "filename*" in paramDict and "'" in paramDict["filename*"]:
+ encoding, _, encodedText = paramDict["filename*"].split("'", 2)
+ return unquote(encodedText, encoding=encoding or "utf-8")
+ if "filename" in paramDict:
+ return paramDict["filename"].strip("\"' ")
+ return ""
+
+
+def _deriveManifestType(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 _detectLive(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 _deriveDefaultTitle(url: str, headers: dict[str, str], extension: str) -> str:
+ candidates: list[str] = []
+ if name := _parseContentDispositionName(headers):
+ candidates.append(name)
+
+ 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 = _stripKnownSuffix(_sanitizeName(Path(candidate).name))
+ if name:
+ return f"{name}.{extension}"
+
+ return f"stream.{extension}"
+
+
+def _bytesFromUnit(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,
+ }
+ return int(float(value) * scale[unit])
+
+
+def _boolText(value: bool) -> str:
+ return "true" if value else "false"
+
+
+def _pickProxy(proxies: dict | None) -> str:
+ if not isinstance(proxies, dict):
+ return ""
+ for key in ("https", "http"):
+ value = str(proxies.get(key) or "").strip()
+ if value:
+ return value
+ return ""
+
+
+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()
+
+ if sys.platform == "win32":
+ if machine in {"amd64", "x86_64"}:
+ return "win-x64", "Windows x64"
+ if machine in {"arm64", "aarch64"}:
+ return "win-arm64", "Windows ARM64"
+ return "win-NT6.0-x86", "Windows x86"
+
+ if sys.platform == "darwin":
+ if machine in {"arm64", "aarch64"}:
+ return "osx-arm64", "macOS Apple Silicon"
+ return "osx-x64", "macOS Intel"
+
+ if sys.platform == "linux":
+ libcName = platform.libc_ver()[0].lower()
+ if machine in {"arm64", "aarch64"}:
+ return ("linux-musl-arm64", "Linux musl ARM64") if libcName == "musl" else ("linux-arm64", "Linux ARM64")
+ return ("linux-musl-x64", "Linux musl x64") if libcName == "musl" else ("linux-x64", "Linux x64")
+
+ raise RuntimeError(f"当前平台暂不支持一键安装 N_m3u8DL-RE: {sys.platform}")
+
+
+def _selectReleaseAsset(assets: list[dict[str, Any]]) -> dict[str, Any]:
+ target, _ = _detectRuntimeTarget()
+ for asset in assets:
+ name = str(asset.get("name") or "")
+ if target in name:
+ return asset
+ raise RuntimeError(f"未找到适用于当前平台的 N_m3u8DL-RE 安装包: {target}")
+
+
+async def _requestReleaseAsset() -> dict[str, Any]:
+ client = niquests.AsyncSession(headers=_M3U8DL_RELEASE_HEADERS, timeout=30, happy_eyeballs=True)
+ client.trust_env = False
+
+ try:
+ response = await client.get(
+ _M3U8DL_RELEASE_API,
+ proxies=getProxies(),
+ verify=cfg.SSLVerify.value,
+ allow_redirects=True,
+ )
+ try:
+ response.raise_for_status()
+ payload = response.json()
+ finally:
+ response.close()
+ finally:
+ await client.close()
+
+ assets = payload.get("assets")
+ 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)
+ if not downloadUrl or not assetName or size <= 0:
+ raise RuntimeError("GitHub Release 返回了不完整的安装包信息")
+
+ return {
+ "name": assetName,
+ "url": downloadUrl,
+ "size": size,
+ }
+
+
+@dataclass
+class M3U8TaskStage(TaskStage):
+ resolvePath: str
+ tempDir: str
+ lastMessage: str = field(default="")
+
+
+@dataclass
+class M3U8Task(Task):
+ headers: dict = field(default_factory=DEFAULT_HEADERS.copy)
+ proxies: dict | None = field(default_factory=getProxies)
+ threadCount: int = field(default_factory=lambda: m3u8Config.threadCount.value)
+ retryCount: int = field(default_factory=lambda: m3u8Config.retryCount.value)
+ requestTimeout: int = field(default_factory=lambda: m3u8Config.requestTimeout.value)
+ autoSelect: bool = field(default_factory=lambda: m3u8Config.autoSelect.value)
+ concurrentDownload: bool = field(default_factory=lambda: m3u8Config.concurrentDownload.value)
+ appendUrlParams: bool = field(default_factory=lambda: m3u8Config.appendUrlParams.value)
+ binaryMerge: bool = field(default_factory=lambda: m3u8Config.binaryMerge.value)
+ checkSegmentsCount: bool = field(default_factory=lambda: m3u8Config.checkSegmentsCount.value)
+ outputFormat: str = field(default_factory=lambda: m3u8Config.outputFormat.value)
+ liveRealTimeMerge: bool = field(default_factory=lambda: m3u8Config.liveRealTimeMerge.value)
+ liveKeepSegments: bool = field(default_factory=lambda: m3u8Config.liveKeepSegments.value)
+ livePipeMux: bool = field(default_factory=lambda: m3u8Config.livePipeMux.value)
+ manifestType: str = field(default="m3u8")
+ isLive: bool = field(default=False)
+ actualExtension: str = field(default="")
+
+ def __post_init__(self):
+ self.title = self._normalizeTitle(self.title)
+ super().__post_init__()
+ self.syncStagePaths()
+
+ @property
+ def outputExtension(self) -> str:
+ if self.actualExtension:
+ return self.actualExtension
+ if self.liveRealTimeMerge:
+ return "ts"
+ return self.outputFormat
+
+ @property
+ def saveName(self) -> str:
+ suffix = f".{self.outputExtension.lower()}"
+ if self.title.lower().endswith(suffix):
+ return self.title[:-len(suffix)]
+ return _stripKnownSuffix(self.title)
+
+ @property
+ def tempDir(self) -> str:
+ return _normalizePath(Path(self.path) / ".gd3_m3u8" / self.taskId)
+
+ def _normalizeTitle(self, title: str) -> str:
+ name = _sanitizeName(Path(str(title).strip() or "stream").name)
+ suffix = f".{self.outputExtension.lower()}"
+ if name.lower().endswith(suffix):
+ return name
+ name = _stripKnownSuffix(name)
+ return f"{name}.{self.outputExtension}"
+
+ def setTitle(self, title: str):
+ self.title = self._normalizeTitle(title)
+ self.syncStagePaths()
+
+ def syncStagePaths(self):
+ resolvePath = _normalizePath(Path(self.path) / self.title)
+ tempDir = self.tempDir
+ for stage in self.stages:
+ if isinstance(stage, M3U8TaskStage):
+ stage.resolvePath = resolvePath
+ stage.tempDir = tempDir
+
+ def applyPayloadToTask(self, payload: dict[str, Any]):
+ super().applyPayloadToTask(payload)
+
+ headers = payload.get("headers")
+ if isinstance(headers, dict):
+ self.headers = headers.copy()
+
+ if "proxies" in payload:
+ proxies = payload.get("proxies")
+ else:
+ proxies = self.proxies
+ if isinstance(proxies, dict) or proxies is None:
+ self.proxies = proxies
+
+ self.syncStagePaths()
+
+ async def run(self):
+ self.stages.sort(key=lambda stage: stage.stageIndex)
+ currentStage = None
+ try:
+ for stage in self.stages:
+ if self.status != TaskStatus.RUNNING:
+ break
+ if stage.status == TaskStatus.COMPLETED:
+ continue
+
+ currentStage = stage
+ if isinstance(stage, M3U8TaskStage):
+ await M3U8Worker(stage).run()
+ continue
+
+ raise TypeError(f"不支持的 M3U8TaskStage: {type(stage).__name__}")
+ except asyncio.CancelledError:
+ logger.info(f"{self.title} 停止下载")
+ raise
+ except Exception as e:
+ if currentStage is not None and not currentStage.error:
+ currentStage.setError(e)
+ logger.opt(exception=e).error("{} 下载失败", self.title)
+ raise
+
+ def __hash__(self):
+ return hash(self.taskId)
+
+
+class M3U8Worker(Worker):
+ def __init__(self, stage: M3U8TaskStage):
+ super().__init__(stage)
+ self.stage = stage
+ self.task: M3U8Task = getattr(stage, "_task")
+
+ def _buildArguments(self, downloaderPath: str) -> list[str]:
+ args = [
+ self.task.url,
+ f"--save-dir={self.task.path}",
+ f"--save-name={self.task.saveName}",
+ f"--tmp-dir={self.stage.tempDir}",
+ f"--thread-count={self.task.threadCount}",
+ f"--download-retry-count={self.task.retryCount}",
+ f"--http-request-timeout={self.task.requestTimeout}",
+ f"--auto-select={_boolText(self.task.autoSelect)}",
+ f"--concurrent-download={_boolText(self.task.concurrentDownload)}",
+ f"--append-url-params={_boolText(self.task.appendUrlParams)}",
+ f"--binary-merge={_boolText(self.task.binaryMerge)}",
+ f"--check-segments-count={_boolText(self.task.checkSegmentsCount)}",
+ "--del-after-done=true",
+ "--write-meta-json=false",
+ "--no-log=true",
+ "--no-ansi-color=true",
+ "--disable-update-check=true",
+ ]
+
+ proxyUrl = _pickProxy(self.task.proxies)
+ args.append("--use-system-proxy=false")
+ if proxyUrl:
+ args.append(f"--custom-proxy={proxyUrl}")
+
+ ffmpegPath, _ = resolveFFmpegExecutables()
+ if ffmpegPath:
+ args.append(f"--ffmpeg-binary-path={ffmpegPath}")
+
+ if self.task.liveRealTimeMerge:
+ args.append("--live-real-time-merge=true")
+ args.append(f"--live-keep-segments={_boolText(self.task.liveKeepSegments)}")
+ args.append(f"--live-pipe-mux={_boolText(self.task.livePipeMux)}")
+ else:
+ muxOption = f"format={self.task.outputFormat}:muxer=ffmpeg"
+ if ffmpegPath:
+ muxOption += f":bin_path={ffmpegPath}"
+ args.append(f"--mux-after-done={muxOption}")
+
+ for name, value in self.task.headers.items():
+ if value is None:
+ continue
+ text = str(value).strip()
+ if not text:
+ continue
+ args.extend(["-H", f"{name}: {text}"])
+
+ return args
+
+ def _handleOutputLine(self, line: str):
+ text = line.strip()
+ if not text:
+ return
+
+ self.stage.lastMessage = text[:1000]
+
+ vodMatch = _VOD_PROGRESS_PATTERN.search(text)
+ if vodMatch:
+ progress = float(vodMatch.group(3))
+ currentSize = _bytesFromUnit(vodMatch.group(4), vodMatch.group(5))
+ totalSize = _bytesFromUnit(vodMatch.group(6), vodMatch.group(7))
+ speed = _bytesFromUnit(vodMatch.group(8), vodMatch.group(9))
+ self.stage.progress = progress
+ self.stage.receivedBytes = currentSize
+ self.stage.speed = speed
+ if totalSize > 0:
+ self.task.fileSize = totalSize
+ return
+
+ liveMatch = _LIVE_PROGRESS_PATTERN.search(text)
+ if liveMatch:
+ self.stage.progress = float(liveMatch.group(4))
+ self.stage.speed = 0 if liveMatch.group(5) == "-" else _bytesFromUnit(liveMatch.group(6), liveMatch.group(7))
+
+ async def _readOutput(self, stream: asyncio.StreamReader | None):
+ if stream is None:
+ return
+
+ buffer = ""
+ while True:
+ chunk = await stream.read(4096)
+ if not chunk:
+ break
+
+ buffer += chunk.decode("utf-8", errors="ignore")
+ buffer = buffer.replace("\r\n", "\n").replace("\r", "\n")
+ lines = buffer.split("\n")
+ buffer = lines.pop()
+ for line in lines:
+ self._handleOutputLine(line)
+
+ if buffer.strip():
+ self._handleOutputLine(buffer)
+
+ def _resolveFinalOutput(self) -> Path | None:
+ target = Path(self.stage.resolvePath)
+ if target.is_file():
+ return target
+
+ outputDir = Path(self.task.path)
+ if not outputDir.is_dir():
+ return None
+
+ candidates: list[Path] = []
+ expectedSuffix = f".{self.task.outputExtension.lower()}"
+ prefix = self.task.saveName.lower()
+ ignoredSuffixes = {".json", ".txt", ".log", ".tmp", ".ghd"}
+
+ 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)
+
+ if not candidates:
+ return None
+
+ candidates.sort(
+ key=lambda path: (
+ path.suffix.lower() != expectedSuffix,
+ -path.stat().st_mtime,
+ )
+ )
+ return candidates[0]
+
+ def _syncFinalOutput(self):
+ candidate = self._resolveFinalOutput()
+ if candidate is None:
+ return
+
+ self.task.actualExtension = candidate.suffix.lstrip(".")
+ self.task.fileSize = max(self.task.fileSize, candidate.stat().st_size)
+ if candidate.name != self.task.title:
+ self.task.setTitle(candidate.name)
+
+ async def _stopProcess(self, process: asyncio.subprocess.Process):
+ if process.returncode is not None:
+ return
+
+ process.terminate()
+ try:
+ await asyncio.wait_for(process.wait(), timeout=3)
+ except asyncio.TimeoutError:
+ process.kill()
+ await process.wait()
+
+ async def run(self):
+ downloaderPath = resolveM3U8DownloaderExecutable()
+ if not downloaderPath:
+ self.stage.setStatus(TaskStatus.FAILED)
+ raise RuntimeError("未找到可用的 N_m3u8DL-RE,请先在设置中安装或配置运行时")
+
+ Path(self.task.path).mkdir(parents=True, exist_ok=True)
+ Path(self.stage.tempDir).mkdir(parents=True, exist_ok=True)
+
+ process = None
+ outputTask = None
+ try:
+ args = self._buildArguments(downloaderPath)
+ process = await asyncio.create_subprocess_exec(
+ downloaderPath,
+ *args,
+ cwd=str(Path(downloaderPath).parent),
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.STDOUT,
+ )
+ outputTask = asyncio.create_task(self._readOutput(process.stdout))
+
+ await process.wait()
+ if outputTask is not None:
+ await outputTask
+
+ if process.returncode != 0:
+ message = self.stage.lastMessage or f"N_m3u8DL-RE 退出码异常: {process.returncode}"
+ raise RuntimeError(message)
+
+ self._syncFinalOutput()
+ self.stage.setStatus(TaskStatus.COMPLETED)
+ except asyncio.CancelledError:
+ self.stage.setStatus(TaskStatus.PAUSED)
+ if process is not None:
+ await self._stopProcess(process)
+ if outputTask is not None and not outputTask.done():
+ outputTask.cancel()
+ with suppress(asyncio.CancelledError):
+ await outputTask
+ raise
+ except Exception as e:
+ self.stage.setError(e)
+ raise
+
+
+async def parse(payload: dict) -> M3U8Task:
+ url = str(payload["url"]).strip()
+ headers = payload.get("headers", DEFAULT_HEADERS)
+ proxies = payload.get("proxies", getProxies())
+ path = Path(payload.get("path", cfg.downloadFolder.value))
+
+ client = niquests.AsyncSession(headers=headers, timeout=30, happy_eyeballs=True)
+ client.trust_env = False
+
+ try:
+ response = await client.get(
+ url,
+ proxies=proxies,
+ verify=cfg.SSLVerify.value,
+ allow_redirects=True,
+ )
+ try:
+ response.raise_for_status()
+ body = response.text
+ loweredHeaders = {key.lower(): value for key, value in response.headers.items()}
+ manifestType = _deriveManifestType(str(response.url), loweredHeaders, body)
+ isLive = _detectLive(manifestType, body)
+ title = _deriveDefaultTitle(
+ str(response.url),
+ loweredHeaders,
+ "ts" if m3u8Config.liveRealTimeMerge.value else m3u8Config.outputFormat.value,
+ )
+ finally:
+ response.close()
+ finally:
+ await client.close()
+
+ task = M3U8Task(
+ title=title,
+ url=url,
+ fileSize=1,
+ headers=headers.copy() if isinstance(headers, dict) else DEFAULT_HEADERS.copy(),
+ proxies=proxies,
+ path=path,
+ 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,
+ )
+ task.addStage(
+ M3U8TaskStage(
+ stageIndex=1,
+ resolvePath="",
+ tempDir="",
+ )
+ )
+ task.syncStagePaths()
+ 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
+ assetName: str
+ headers: dict = field(default_factory=DEFAULT_HEADERS.copy)
+ proxies: dict | None = field(default_factory=getProxies)
+ blockNum: int = field(default_factory=lambda: httpConfig.preBlockNum.value)
+ installFolder: str
+ archiveSize: int = field(default=0)
+ archivePath: str = field(default="")
+ executablePath: str = field(default="")
+
+ @property
+ def resolvePath(self) -> str:
+ return self.executablePath or self.archivePath or _normalizePath(Path(self.installFolder) / self.title)
+
+ def __post_init__(self):
+ super().__post_init__()
+ self.syncStagePaths()
+
+ def syncStagePaths(self):
+ installDir = Path(self.installFolder)
+ self.path = installDir
+ self.archivePath = _normalizePath(installDir / self.assetName)
+ if not self.executablePath:
+ self.executablePath = _normalizePath(installDir / _executableName("N_m3u8DL-RE"))
+
+ for stage in self.stages:
+ if isinstance(stage, HttpTaskStage):
+ stage.resolvePath = self.archivePath
+ elif isinstance(stage, M3U8ExtractStage):
+ stage.archivePath = self.archivePath
+ stage.installFolder = _normalizePath(installDir)
+ stage.executablePath = self.executablePath
+
+ async def run(self):
+ self.stages.sort(key=lambda stage: stage.stageIndex)
+ currentStage = None
+ try:
+ for stage in self.stages:
+ if self.status != TaskStatus.RUNNING:
+ break
+ if stage.status == TaskStatus.COMPLETED:
+ continue
+
+ currentStage = stage
+ if isinstance(stage, HttpTaskStage):
+ await HttpWorker(stage).run()
+ continue
+
+ if isinstance(stage, M3U8ExtractStage):
+ await M3U8ExtractWorker(stage).run()
+ continue
+
+ raise TypeError(f"不支持的 M3U8InstallTaskStage: {type(stage).__name__}")
+ except asyncio.CancelledError:
+ logger.info(f"{self.title} 停止安装")
+ raise
+ except Exception as e:
+ if currentStage is not None and not currentStage.error:
+ currentStage.setError(e)
+ logger.opt(exception=e).error("{} 安装失败", self.title)
+ raise
+
+ def __hash__(self):
+ return hash(self.taskId)
+
+
+async def createInstallTask() -> M3U8InstallTask:
+ assetInfo = await _requestReleaseAsset()
+ _, archLabel = _detectRuntimeTarget()
+ installFolder = m3u8Config.installFolder.value
+ downloadTask = await coreService._parseUrl(
+ {
+ "url": assetInfo["url"],
+ "headers": DEFAULT_HEADERS.copy(),
+ "proxies": getProxies(),
+ "path": Path(installFolder),
+ }
+ )
+
+ if not downloadTask.stages:
+ raise RuntimeError("解析 N_m3u8DL-RE 安装包链接后未获取到下载阶段")
+
+ downloadStage = downloadTask.stages[0]
+ if not isinstance(downloadStage, HttpTaskStage):
+ raise TypeError(f"解析出的下载阶段类型无效: {type(downloadStage).__name__}")
+
+ archiveSize = downloadTask.fileSize if downloadTask.fileSize > 0 else assetInfo["size"]
+ assetName = downloadTask.title or str(assetInfo["name"])
+
+ task = M3U8InstallTask(
+ title=f"N_m3u8DL-RE 安装 ({archLabel})",
+ url=downloadTask.url,
+ assetName=assetName,
+ fileSize=archiveSize,
+ headers=downloadTask.headers.copy(),
+ proxies=downloadTask.proxies,
+ blockNum=downloadTask.blockNum,
+ installFolder=installFolder,
+ archiveSize=archiveSize,
+ )
+
+ 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)
+ setattr(task, "_featurePackName", "m3u8_pack")
+ return task