Skip to content

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

feat(desktop): YouTube 下载支持(yt-dlp pack)

XiaoYouChR80eff7cc4c1b
diff --git a/features/yt_dlp_pack/config.py b/features/yt_dlp_pack/config.py
new file mode 100644
index 00000000..31a3cb75
--- /dev/null
+++ b/features/yt_dlp_pack/config.py
@@ -0,0 +1,148 @@
+import asyncio
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from PySide6.QtCore import Qt
+from qfluentwidgets import (
+ ConfigItem,
+ FluentIcon,
+ FolderValidator,
+ InfoBar,
+ PrimaryPushButton,
+ SettingCard,
+ ToolButton,
+)
+
+from app.bases.models import PackConfig
+from app.services.core_service import coreService
+from app.supports.paths import APP_DATA_DIR
+from app.supports.utils import findExecutable, toPosixPath
+from app.view.components.setting_card_group import CollapsibleSettingCardGroup
+from app.view.components.setting_cards import InstallFolderCard, LineEditSettingCard
+
+if TYPE_CHECKING:
+ from app.view.pages.setting_page import SettingPage
+ from app.view.windows.main_window import MainWindow
+
+
+def downloaderPath() -> str:
+ return findExecutable(Path(ytDlpConfig.installFolder.value), "yt-dlp")
+
+
+async def probeYtDlpRuntime() -> dict[str, str]:
+ execPath = downloaderPath()
+ info = {"downloaderPath": execPath, "version": "", "installPath": ""}
+ if not execPath:
+ return info
+
+ process = await asyncio.create_subprocess_exec(
+ execPath,
+ "--version",
+ stdin=asyncio.subprocess.DEVNULL,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ stdout, stderr = await process.communicate()
+ if process.returncode != 0:
+ return info
+
+ 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()]
+ info["version"] = lines[0] if lines else ""
+ info["installPath"] = toPosixPath(Path(execPath).parent)
+ return info
+
+
+class YtDlpRuntimeCard(SettingCard):
+ def __init__(self, parent=None):
+ super().__init__(FluentIcon.INFO, self.tr("当前 yt-dlp"), 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(probeYtDlpRuntime(), self._onRuntimeLoaded)
+
+ def _onRuntimeLoaded(self, result, error: str | None):
+ self.refreshButton.setEnabled(True)
+ if error:
+ self.setContent(self.tr("检测运行时失败"))
+ return
+
+ info = result or {}
+ executablePath = info.get("downloaderPath", "")
+ if executablePath:
+ content = self.tr("版本: {0}\n安装路径: {1}").format(
+ info.get("version") or self.tr("未知"),
+ info.get("installPath") or executablePath,
+ )
+ else:
+ content = self.tr("未检测到可用的 yt-dlp")
+ self.setContent(content)
+
+ def _onInstallClicked(self):
+ from .pack 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("安装 yt-dlp 失败"), error or self.tr("无法创建安装任务"), duration=-1, parent=mainWindow)
+ return
+
+ mainWindow.addTask(result)
+
+
+class YtDlpConfig(PackConfig):
+ installFolder = ConfigItem("YtDlp", "InstallFolder", f"{APP_DATA_DIR}/YtDlp", FolderValidator())
+ videoFormat = ConfigItem("YtDlp", "VideoFormat", "bv*+ba/b")
+
+ def setupSettings(self, settingPage: "SettingPage"):
+ self.group = CollapsibleSettingCardGroup(self.tr("YouTube 下载"), "ytdlp", settingPage.container)
+ self.installFolderCard = InstallFolderCard(
+ self.installFolder,
+ f"{APP_DATA_DIR}/YtDlp",
+ self.tr("yt-dlp 安装目录"),
+ self.tr("选择 yt-dlp 安装目录"),
+ self.group,
+ )
+ self.runtimeCard = YtDlpRuntimeCard(self.group)
+ self.group.addSettingCards([
+ self.installFolderCard,
+ self.runtimeCard,
+ LineEditSettingCard(
+ FluentIcon.VIDEO,
+ self.tr("下载格式"),
+ self.tr("传给 yt-dlp 的 -f 选择表达式,默认最佳画质并自动合并"),
+ self.videoFormat,
+ self.group,
+ placeholder="bv*+ba/b",
+ ),
+ ])
+
+ self.installFolderCard.pathChanged.connect(lambda _: self.runtimeCard.refreshStatus())
+ settingPage.addSettingGroup(self.group)
+ self.runtimeCard.refreshStatus()
+
+
+ytDlpConfig = YtDlpConfig()
diff --git a/features/yt_dlp_pack/manifest.toml b/features/yt_dlp_pack/manifest.toml
new file mode 100644
index 00000000..b7043905
--- /dev/null
+++ b/features/yt_dlp_pack/manifest.toml
@@ -0,0 +1,3 @@
+[pack]
+entry = "pack.py"
+dependencies = ["http_pack", "disk_pack", "ffmpeg_pack"]
diff --git a/features/yt_dlp_pack/pack.py b/features/yt_dlp_pack/pack.py
new file mode 100644
index 00000000..0aa8faa6
--- /dev/null
+++ b/features/yt_dlp_pack/pack.py
@@ -0,0 +1,120 @@
+import platform
+import sys
+from pathlib import Path
+from urllib.parse import urlparse
+
+import niquests
+
+from app.bases.interfaces import FeaturePack
+from app.bases.models import Task
+from app.supports.config import activeUserAgent, cfg, defaultHeaders
+from app.supports.utils import getProxies, toExecutable, toPosixPath
+from .config import ytDlpConfig
+from .task import YtDlpInstallStage, YtDlpTask, YtDlpTaskStage
+
+_YTDLP_RELEASE_API = "https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest"
+_YTDLP_RELEASE_HEADERS = {
+ "accept": "application/vnd.github+json",
+ "user-agent": activeUserAgent(),
+}
+_YOUTUBE_HOSTS = ("youtube.com", "youtu.be")
+
+
+def _assetName() -> str:
+ # yt-dlp serves a self-contained executable per platform — pick the one yt-dlp itself names.
+ machine = platform.machine().lower()
+ if sys.platform == "win32":
+ return "yt-dlp.exe"
+ if sys.platform == "darwin":
+ return "yt-dlp_macos"
+ if machine in {"arm64", "aarch64"}:
+ return "yt-dlp_linux_aarch64"
+ return "yt-dlp_linux"
+
+
+class YtDlpPack(FeaturePack):
+ packId = "ytdlp"
+ # Below http (100) so YouTube watch pages route here instead of being grabbed as HTML.
+ priority = 70
+ config = ytDlpConfig
+
+ def matches(self, url: str) -> bool:
+ host = (urlparse(url).hostname or "").lower()
+ return any(host == h or host.endswith(f".{h}") for h in _YOUTUBE_HOSTS)
+
+ async def parse(self, payload: dict) -> Task:
+ url = payload["url"].strip()
+ proxies = payload.get("proxies", getProxies())
+ path = Path(payload.get("path", cfg.downloadFolder.value))
+ rawHeaders = payload.get("headers")
+ headers = rawHeaders.copy() if isinstance(rawHeaders, dict) and rawHeaders else {}
+
+ # Stay offline: the binary isn't needed just to enqueue. The real title and size
+ # come back from yt-dlp at download time (-o %(title)s + after_move filepath).
+ task = YtDlpTask(title="YouTube 视频.mp4", url=url, fileSize=1, path=path)
+ task.addStage(YtDlpTaskStage(
+ stageIndex=1,
+ videoFormat=ytDlpConfig.videoFormat.value,
+ headers=headers,
+ proxies=proxies if isinstance(proxies, dict) else {},
+ ))
+ return task
+
+
+async def createInstallTask() -> Task:
+ from app.services.feature_service import featureService
+ from disk_pack.task import InstallTask
+
+ assetName = _assetName()
+ installFolder = Path(ytDlpConfig.installFolder.value)
+ binaryPath = installFolder / toExecutable("yt-dlp")
+
+ async with niquests.AsyncSession(headers=_YTDLP_RELEASE_HEADERS, timeout=30, happy_eyeballs=True) as client:
+ client.trust_env = False
+ response = await client.get(
+ _YTDLP_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 item.get("name") == assetName), None)
+ if asset is None:
+ raise RuntimeError(f"未找到适用于当前平台的 yt-dlp 安装包: {assetName}")
+
+ downloadUrl = asset["browser_download_url"].strip()
+ size = asset["size"]
+ if not downloadUrl or size <= 0:
+ raise RuntimeError("GitHub Release 返回了不完整的安装包信息")
+
+ # Reuse http_pack to download the single binary straight to its final path, then chmod.
+ downloadTask = await featureService.parse({
+ "url": downloadUrl,
+ "headers": defaultHeaders(),
+ "proxies": getProxies(),
+ "path": installFolder,
+ })
+ if not downloadTask.stages:
+ raise RuntimeError("解析 yt-dlp 下载链接后未获取到下载阶段")
+ downloadStage = downloadTask.stages[0]
+ downloadStage.stageIndex = 1
+ downloadStage.outputFile = toPosixPath(binaryPath)
+
+ task = InstallTask(
+ title=f"yt-dlp 安装 ({assetName})",
+ url=downloadUrl,
+ packId="ytdlp",
+ fileSize=size,
+ path=installFolder,
+ usesSlot=False,
+ installFolder=str(installFolder),
+ )
+ task.addStage(downloadStage)
+ task.addStage(YtDlpInstallStage(stageIndex=2, binaryPath=toPosixPath(binaryPath)))
+ return task
diff --git a/features/yt_dlp_pack/task.py b/features/yt_dlp_pack/task.py
new file mode 100644
index 00000000..80a595bf
--- /dev/null
+++ b/features/yt_dlp_pack/task.py
@@ -0,0 +1,241 @@
+import asyncio
+import sys
+from contextlib import suppress
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from app.bases.interfaces import Worker
+from app.bases.models import Task, TaskStage, TaskStatus
+from app.supports.utils import toPosixPath
+from .config import downloaderPath
+
+if TYPE_CHECKING:
+ from features.ffmpeg_pack.config import ffmpegPaths
+else:
+ from ffmpeg_pack.config import ffmpegPaths
+
+
+# yt-dlp prints one line per update via --progress-template; the sentinel keeps our parser
+# clear of yt-dlp's own [download]/[youtube] chatter on the same (merged) stream.
+_PROGRESS_SENTINEL = "#GD3PROG#"
+_FINAL_SENTINEL = "#GD3FILE#"
+_PROGRESS_TEMPLATE = (
+ f"download:{_PROGRESS_SENTINEL}"
+ "%(progress.downloaded_bytes)s|%(progress.total_bytes)s|"
+ "%(progress.total_bytes_estimate)s|%(progress.speed)s"
+)
+_FINAL_TEMPLATE = f"after_move:{_FINAL_SENTINEL}%(filepath)s"
+
+
+def _toInt(value: str) -> int:
+ try:
+ return int(float(value))
+ except (TypeError, ValueError):
+ return 0
+
+
+# yt-dlp's ERROR lines are terse and English; map the common ones to actionable Chinese.
+_ERROR_HINTS = (
+ ("is not available in your country", "该视频在当前地区不可用,可在设置里配置代理后重试"),
+ ("video unavailable", "视频不可用(可能已被删除或设为私有)"),
+ ("private video", "私有视频,需要有权限账号的 cookies"),
+ ("members-only", "会员专享视频,需要对应会员账号的 cookies"),
+ ("confirm your age", "年龄限制视频,需要登录账号的 cookies"),
+ ("confirm you're not a bot", "YouTube 要求人机验证,请在设置里配置 cookies"),
+ ("requested format is not available", "请求的画质不可用,请改用其它格式"),
+ ("http error 403", "下载被拒绝(403),链接可能已过期,请重试"),
+)
+
+
+def _friendlyError(message: str) -> str:
+ lowered = message.lower()
+ for needle, hint in _ERROR_HINTS:
+ if needle in lowered:
+ return hint
+ return message
+
+
+@dataclass(kw_only=True)
+class YtDlpTaskStage(TaskStage):
+ workerType: type = field(init=False, repr=False)
+
+ videoFormat: str = "bv*+ba/b"
+ headers: dict[str, str] = field(default_factory=dict)
+ proxies: dict[str, str] = field(default_factory=dict)
+ lastMessage: str = ""
+
+ @property
+ def outputTemplate(self) -> str:
+ # yt-dlp names the file itself; the real title/size land back via after_move filepath.
+ return toPosixPath(Path(self.task.path) / "%(title)s.%(ext)s")
+
+
+@dataclass(kw_only=True, eq=False)
+class YtDlpTask(Task):
+ packId: str = "ytdlp"
+
+ @property
+ def stage(self) -> "YtDlpTaskStage":
+ return self.stages[0]
+
+
+class YtDlpWorker(Worker):
+ def __init__(self, stage: YtDlpTaskStage):
+ super().__init__(stage)
+ self.stage = stage
+ self._finalPath = ""
+
+ def _buildArgs(self) -> list[str]:
+ stage = self.stage
+ args = [
+ stage.task.url,
+ "-f", stage.videoFormat,
+ "-o", stage.outputTemplate,
+ "--no-playlist",
+ "--newline",
+ "--no-color",
+ "--no-simulate",
+ # --print silently turns on quiet mode, which suppresses --progress-template;
+ # --progress forces the progress lines back on so the card updates live.
+ "--progress",
+ "--progress-template", _PROGRESS_TEMPLATE,
+ "--print", _FINAL_TEMPLATE,
+ ]
+ ffmpegPath, _ = ffmpegPaths()
+ if ffmpegPath:
+ args.extend(["--ffmpeg-location", ffmpegPath])
+ proxyUrl = next((v for v in stage.proxies.values() if v), "")
+ if proxyUrl:
+ args.extend(["--proxy", proxyUrl])
+ for name, value in stage.headers.items():
+ text = value.strip()
+ if text:
+ args.extend(["--add-header", f"{name}:{text}"])
+ return args
+
+ def _parseOutputLine(self, line: str):
+ text = line.strip()
+ if not text:
+ return
+ if text.startswith(_FINAL_SENTINEL):
+ self._finalPath = text[len(_FINAL_SENTINEL):].strip()
+ return
+ if text.startswith(_PROGRESS_SENTINEL):
+ parts = text[len(_PROGRESS_SENTINEL):].split("|")
+ if len(parts) >= 4:
+ downloaded = _toInt(parts[0])
+ total = _toInt(parts[1]) or _toInt(parts[2])
+ self.stage.receivedBytes = downloaded
+ self.stage.speed = _toInt(parts[3])
+ if total > 0:
+ self.stage.task.fileSize = max(self.stage.task.fileSize, total)
+ self.stage.progress = min(99.5, downloaded / total * 100)
+ return
+ # yt-dlp's ERROR:/[youtube] lines — keep the latest as the failure message.
+ self.stage.lastMessage = text[:1000]
+
+ async def supervisor(self, stream: asyncio.StreamReader):
+ 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._parseOutputLine(line)
+ if buffer.strip():
+ self._parseOutputLine(buffer)
+
+ def _applyFinalFile(self):
+ if not self._finalPath:
+ return
+ path = Path(self._finalPath)
+ if path.is_file() and path.stat().st_size > 0:
+ self.stage.task.fileSize = max(self.stage.task.fileSize, path.stat().st_size)
+ if path.name != self.stage.task.title:
+ self.stage.task.setTitle(path.name)
+
+ async def run(self):
+ execPath = downloaderPath()
+ if not execPath:
+ raise RuntimeError("未找到可用的 yt-dlp,请先在设置中安装或配置运行时")
+
+ self.stage.task.path.mkdir(parents=True, exist_ok=True)
+ process = None
+ supervisorTask = None
+ try:
+ process = await asyncio.create_subprocess_exec(
+ execPath,
+ *self._buildArgs(),
+ cwd=Path(execPath).parent,
+ stdin=asyncio.subprocess.DEVNULL,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.STDOUT,
+ )
+ supervisorTask = asyncio.create_task(self.supervisor(process.stdout))
+
+ await process.wait()
+ await supervisorTask
+
+ if process.returncode != 0:
+ raise RuntimeError(_friendlyError(self.stage.lastMessage) or f"yt-dlp 退出码异常: {process.returncode}")
+
+ self._applyFinalFile()
+ self.stage.speed = 0
+ self.stage.setStatus(TaskStatus.COMPLETED)
+ except asyncio.CancelledError:
+ if process is not None and process.returncode is None:
+ process.terminate()
+ try:
+ await asyncio.wait_for(process.wait(), timeout=3)
+ except asyncio.TimeoutError:
+ process.kill()
+ await process.wait()
+ if supervisorTask is not None and not supervisorTask.done():
+ supervisorTask.cancel()
+ with suppress(asyncio.CancelledError):
+ await supervisorTask
+ self.stage.setStatus(TaskStatus.PAUSED)
+ raise
+ except Exception as e:
+ self.stage.setError(e)
+ raise
+
+
+# yt-dlp ships as a single executable (not an archive), so install is just "place + chmod"
+# rather than disk_pack's download→extract→install. This stage runs after the download stage.
+@dataclass(kw_only=True)
+class YtDlpInstallStage(TaskStage):
+ workerType: type = field(init=False, repr=False)
+ canPause: bool = field(init=False, default=False)
+
+ binaryPath: str
+
+
+class YtDlpInstallWorker(Worker):
+ def __init__(self, stage: YtDlpInstallStage):
+ super().__init__(stage)
+ self.stage = stage
+
+ async def run(self):
+ path = Path(self.stage.binaryPath)
+ try:
+ if not path.is_file():
+ raise FileNotFoundError(f"未找到已下载的 yt-dlp: {path}")
+ if sys.platform != "win32":
+ path.chmod(path.stat().st_mode | 0o755)
+ self.stage.setStatus(TaskStatus.COMPLETED)
+ except asyncio.CancelledError:
+ self.stage.setStatus(TaskStatus.PAUSED)
+ raise
+ except Exception as e:
+ self.stage.setError(e)
+ raise
+
+
+YtDlpTaskStage.workerType = YtDlpWorker
+YtDlpInstallStage.workerType = YtDlpInstallWorker