Skip to content

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

feat(desktop): yt-dlp 任务真实标题 + per-task 画质选择

XiaoYouChR8d008682d8b2
diff --git a/features/yt_dlp_pack/cards.py b/features/yt_dlp_pack/cards.py
new file mode 100644
index 00000000..7b8b3686
--- /dev/null
+++ b/features/yt_dlp_pack/cards.py
@@ -0,0 +1,46 @@
+from typing import Any
+
+from qfluentwidgets import ComboBox
+
+from app.view.components.cards import ParseSettingCard
+
+# label → yt-dlp -f selector. Fixed tiers keep parse offline (no per-video format probe).
+_QUALITY_TIERS = (
+ ("最佳画质", "bv*+ba/b"),
+ ("1080p", "bv*[height<=1080]+ba/b[height<=1080]"),
+ ("720p", "bv*[height<=720]+ba/b[height<=720]"),
+ ("480p", "bv*[height<=480]+ba/b[height<=480]"),
+ ("仅音频", "ba/b"),
+)
+
+
+class YtDlpQualityEditCard(ParseSettingCard):
+ def __init__(self, icon, title: str, parent=None, *, initial: str = "") -> None:
+ self._initialFormat = initial
+ super().__init__(icon, title, parent)
+
+ def initCustomWidget(self) -> None:
+ self.qualityCombo = ComboBox(self)
+ self._initWidget()
+ self._initLayout()
+ self._bind()
+
+ def _initWidget(self) -> None:
+ self.qualityCombo.setMinimumWidth(220)
+ selectedIndex = 0
+ for index, (label, expr) in enumerate(_QUALITY_TIERS):
+ self.qualityCombo.addItem(label, userData=expr)
+ if self._initialFormat and expr == self._initialFormat:
+ selectedIndex = index
+ self.qualityCombo.setCurrentIndex(selectedIndex)
+
+ def _initLayout(self) -> None:
+ self.hBoxLayout.addWidget(self.qualityCombo)
+ self.hBoxLayout.addSpacing(16)
+
+ def _bind(self) -> None:
+ self.qualityCombo.currentIndexChanged.connect(lambda _: self.payloadChanged.emit())
+
+ @property
+ def payload(self) -> dict[str, Any]:
+ return {"videoFormat": self.qualityCombo.currentData() or _QUALITY_TIERS[0][1]}
diff --git a/features/yt_dlp_pack/pack.py b/features/yt_dlp_pack/pack.py
index 0aa8faa6..83d3ca9b 100644
--- a/features/yt_dlp_pack/pack.py
+++ b/features/yt_dlp_pack/pack.py
@@ -1,3 +1,4 @@
+import asyncio
import platform
import sys
from pathlib import Path
@@ -8,8 +9,8 @@ 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 app.supports.utils import getProxies, toExecutable, toPosixPath, toSafeFilename
+from .config import downloaderPath, ytDlpConfig
from .task import YtDlpInstallStage, YtDlpTask, YtDlpTaskStage
_YTDLP_RELEASE_API = "https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest"
@@ -32,6 +33,33 @@ def _assetName() -> str:
return "yt-dlp_linux"
+async def _probeTitle(url: str, proxies: dict) -> str:
+ execPath = downloaderPath()
+ if not execPath:
+ return ""
+ args = [url, "--no-playlist", "--skip-download", "--no-warnings", "--print", "%(title)s"]
+ proxyUrl = next((v for v in proxies.values() if v), "")
+ if proxyUrl:
+ args.extend(["--proxy", proxyUrl])
+ try:
+ process = await asyncio.create_subprocess_exec(
+ execPath, *args,
+ stdin=asyncio.subprocess.DEVNULL,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.DEVNULL,
+ )
+ stdout, _ = await asyncio.wait_for(process.communicate(), timeout=20)
+ except asyncio.TimeoutError:
+ process.kill()
+ return ""
+ except OSError:
+ return ""
+ if process.returncode != 0:
+ return ""
+ lines = stdout.decode("utf-8", errors="ignore").strip().splitlines()
+ return lines[0].strip() if lines else ""
+
+
class YtDlpPack(FeaturePack):
packId = "ytdlp"
# Below http (100) so YouTube watch pages route here instead of being grabbed as HTML.
@@ -45,18 +73,24 @@ class YtDlpPack(FeaturePack):
async def parse(self, payload: dict) -> Task:
url = payload["url"].strip()
proxies = payload.get("proxies", getProxies())
+ if not isinstance(proxies, dict):
+ proxies = {}
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)
+ # Best-effort title for the dialog/card. The real filename + size land back from
+ # yt-dlp at download time (-o %(title)s + after_move filepath), so a blocked probe
+ # just falls back to the placeholder and the task still enqueues.
+ probedTitle = await _probeTitle(url, proxies)
+ title = toSafeFilename(probedTitle, fallback="youtube_video") if probedTitle else "YouTube 视频"
+
+ task = YtDlpTask(title=f"{title}.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 {},
+ proxies=proxies,
))
return task
diff --git a/features/yt_dlp_pack/task.py b/features/yt_dlp_pack/task.py
index 80a595bf..7d269a8d 100644
--- a/features/yt_dlp_pack/task.py
+++ b/features/yt_dlp_pack/task.py
@@ -3,7 +3,7 @@ import sys
from contextlib import suppress
from dataclasses import dataclass, field
from pathlib import Path
-from typing import TYPE_CHECKING
+from typing import ClassVar, TYPE_CHECKING
from app.bases.interfaces import Worker
from app.bases.models import Task, TaskStage, TaskStatus
@@ -74,11 +74,28 @@ class YtDlpTaskStage(TaskStage):
@dataclass(kw_only=True, eq=False)
class YtDlpTask(Task):
packId: str = "ytdlp"
+ supportsEdit: ClassVar[bool] = True
@property
def stage(self) -> "YtDlpTaskStage":
return self.stages[0]
+ def editorCards(self, parent):
+ from qfluentwidgets import FluentIcon
+
+ from app.view.components.add_task_dialog import SelectFolderCard
+ from .cards import YtDlpQualityEditCard
+
+ return [
+ YtDlpQualityEditCard(FluentIcon.VIDEO, parent.tr("画质"), parent, initial=self.stage.videoFormat),
+ SelectFolderCard(FluentIcon.DOWNLOAD, parent.tr("下载到"), parent, initial=self.path),
+ ]
+
+ def applySettings(self, payload: dict):
+ super().applySettings(payload)
+ if "videoFormat" in payload:
+ self.stage.videoFormat = payload["videoFormat"]
+
class YtDlpWorker(Worker):
def __init__(self, stage: YtDlpTaskStage):
@@ -185,7 +202,6 @@ class YtDlpWorker(Worker):
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: