The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(desktop): yt-dlp 画质即选与下载前预估大小
XiaoYouChRd4681ffe8e50
diff --git a/features/yt_dlp_pack/cards.py b/features/yt_dlp_pack/cards.pyindex 7b8b3686..a7d580c0 100644--- a/features/yt_dlp_pack/cards.py+++ b/features/yt_dlp_pack/cards.py@@ -1,12 +1,14 @@-from typing import Any-+from PySide6.QtWidgets import QWidgetfrom qfluentwidgets import ComboBox-from app.view.components.cards import ParseSettingCard+from app.bases.models import SpecialFileSize, Task+from app.services.core_service import coreService+from app.supports.utils import getProxies, toReadableSize+from app.view.components.cards import UniversalResultCard+from .task import DEFAULT_VIDEO_FORMAT, probeMediaInfo-# label → yt-dlp -f selector. Fixed tiers keep parse offline (no per-video format probe)._QUALITY_TIERS = (- ("最佳画质", "bv*+ba/b"),+ ("最佳画质", DEFAULT_VIDEO_FORMAT),("1080p", "bv*[height<=1080]+ba/b[height<=1080]"),("720p", "bv*[height<=720]+ba/b[height<=720]"),("480p", "bv*[height<=480]+ba/b[height<=480]"),@@ -14,33 +16,47 @@ _QUALITY_TIERS = ()-class YtDlpQualityEditCard(ParseSettingCard):- def __init__(self, icon, title: str, parent=None, *, initial: str = "") -> None:- self._initialFormat = initial- super().__init__(icon, title, parent)+class YtDlpResultCard(UniversalResultCard):+ def __init__(self, task: Task, parent: QWidget = None):+ super().__init__(task, parent)+ self._pendingFormat = self.task.stage.videoFormat+ self._renderSize(self.task.fileSize)+ self.qualityCombo.currentIndexChanged.connect(lambda _: self._onQualityChanged())- def initCustomWidget(self) -> None:+ def initWidget(self):+ super().initWidget()self.qualityCombo = ComboBox(self)- self._initWidget()- self._initLayout()- self._bind()-- def _initWidget(self) -> None:- self.qualityCombo.setMinimumWidth(220)+ self.qualityCombo.setMinimumWidth(140)selectedIndex = 0for index, (label, expr) in enumerate(_QUALITY_TIERS):self.qualityCombo.addItem(label, userData=expr)- if self._initialFormat and expr == self._initialFormat:+ if expr == self.task.stage.videoFormat:selectedIndex = indexself.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]}+ def initLayout(self):+ super().initLayout()+ self.mainLayout.insertWidget(self.mainLayout.indexOf(self.sizeLabel), self.qualityCombo)++ def _onQualityChanged(self):+ videoFormat = self.qualityCombo.currentData() or _QUALITY_TIERS[0][1]+ self.task.applySettings({"videoFormat": videoFormat})+ self._pendingFormat = videoFormat+ self.sizeLabel.setText(self.tr("计算中…"))+ coreService.runCoroutine(+ probeMediaInfo(self.task.url, getProxies(), videoFormat, self.task.stage.headers),+ lambda result, error, fmt=videoFormat: self._onSizeProbed(fmt, result, error),+ )++ def _onSizeProbed(self, videoFormat: str, result, error):+ if videoFormat != self._pendingFormat:+ return # 用户又改了档,丢弃过期结果+ size = result[1] if (not error and result) else SpecialFileSize.UNKNOWN+ self.task.fileSize = size+ self._renderSize(size)++ def _renderSize(self, size: int):+ if size in {SpecialFileSize.UNKNOWN, SpecialFileSize.NOT_SUPPORTED}:+ self.sizeLabel.setText(self.tr("未知"))+ else:+ self.sizeLabel.setText(self.tr("约 {0}").format(toReadableSize(size)))diff --git a/features/yt_dlp_pack/config.py b/features/yt_dlp_pack/config.pyindex 31a3cb75..052e8f9f 100644--- a/features/yt_dlp_pack/config.py+++ b/features/yt_dlp_pack/config.py@@ -18,7 +18,7 @@ from app.services.core_service import coreServicefrom app.supports.paths import APP_DATA_DIRfrom app.supports.utils import findExecutable, toPosixPathfrom app.view.components.setting_card_group import CollapsibleSettingCardGroup-from app.view.components.setting_cards import InstallFolderCard, LineEditSettingCard+from app.view.components.setting_cards import InstallFolderCardif TYPE_CHECKING:from app.view.pages.setting_page import SettingPage@@ -115,7 +115,6 @@ class YtDlpRuntimeCard(SettingCard):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)@@ -130,14 +129,6 @@ class YtDlpConfig(PackConfig):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())diff --git a/features/yt_dlp_pack/pack.py b/features/yt_dlp_pack/pack.pyindex 3a2e6c8a..391b9da8 100644--- a/features/yt_dlp_pack/pack.py+++ b/features/yt_dlp_pack/pack.py@@ -1,4 +1,3 @@-import asyncioimport platformimport sysfrom pathlib import Path@@ -10,8 +9,8 @@ from app.bases.interfaces import FeaturePackfrom app.bases.models import Taskfrom app.supports.config import activeUserAgent, cfg, defaultHeadersfrom app.supports.utils import getProxies, toExecutable, toPosixPath, toSafeFilename-from .config import downloaderPath, ytDlpConfig-from .task import YtDlpInstallStage, YtDlpTask, YtDlpTaskStage+from .config import ytDlpConfig+from .task import DEFAULT_VIDEO_FORMAT, YtDlpInstallStage, YtDlpTask, YtDlpTaskStage, probeMediaInfo_YTDLP_RELEASE_API = "https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest"_YTDLP_RELEASE_HEADERS = {@@ -33,33 +32,6 @@ 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.@@ -70,25 +42,28 @@ class YtDlpPack(FeaturePack):host = (urlparse(url).hostname or "").lower()return any(host == h or host.endswith(f".{h}") for h in _YOUTUBE_HOSTS)+ def resultCard(self, task, parent=None):+ from .cards import YtDlpResultCard+ return YtDlpResultCard(task, parent)+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 {}-- # 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)+ videoFormat = DEFAULT_VIDEO_FORMAT+ probedTitle, probedSize = await probeMediaInfo(url, proxies, videoFormat, headers)title = toSafeFilename(probedTitle) if probedTitle else "YouTube 视频"- task = YtDlpTask(title=f"{title}.mp4", url=url, fileSize=1, path=path)+ task = YtDlpTask(title=f"{title}.mp4", url=url, fileSize=probedSize, path=path)task.addStage(YtDlpTaskStage(stageIndex=1,- videoFormat=ytDlpConfig.videoFormat.value,+ videoFormat=videoFormat,headers=headers,- proxies=proxies if isinstance(proxies, dict) else {},+ proxies=proxies,))return taskdiff --git a/features/yt_dlp_pack/task.py b/features/yt_dlp_pack/task.pyindex 7d269a8d..55bd12fd 100644--- a/features/yt_dlp_pack/task.py+++ b/features/yt_dlp_pack/task.py@@ -6,7 +6,7 @@ from pathlib import Pathfrom typing import ClassVar, TYPE_CHECKINGfrom app.bases.interfaces import Worker-from app.bases.models import Task, TaskStage, TaskStatus+from app.bases.models import SpecialFileSize, Task, TaskStage, TaskStatusfrom app.supports.utils import toPosixPathfrom .config import downloaderPath@@ -27,6 +27,8 @@ _PROGRESS_TEMPLATE = ()_FINAL_TEMPLATE = f"after_move:{_FINAL_SENTINEL}%(filepath)s"+DEFAULT_VIDEO_FORMAT = "bv*+ba/b"+def _toInt(value: str) -> int:try:@@ -56,11 +58,52 @@ def _friendlyError(message: str) -> str:return message+async def probeMediaInfo(url: str, proxies: dict, videoFormat: str, headers: dict | None = None) -> tuple[str, int]:+ """探测真实标题与选定画质的预估总大小;受限/超时回落 ("", UNKNOWN)。"""+ execPath = downloaderPath()+ if not execPath:+ return "", SpecialFileSize.UNKNOWN++ args = [+ url, "-f", videoFormat, "--no-playlist", "--skip-download", "--no-warnings",+ "--print", "%(title)s", "--print", "%(filesize_approx)s",+ ]+ proxyUrl = next((v for v in proxies.values() if v), "")+ if proxyUrl:+ args.extend(["--proxy", proxyUrl])+ for name, value in (headers or {}).items():+ text = str(value).strip()+ if text:+ args.extend(["--add-header", f"{name}:{text}"])++ 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 "", SpecialFileSize.UNKNOWN+ except OSError:+ return "", SpecialFileSize.UNKNOWN++ if process.returncode != 0:+ return "", SpecialFileSize.UNKNOWN++ lines = stdout.decode("utf-8", errors="ignore").strip().splitlines()+ title = lines[0].strip() if lines else ""+ size = _toInt(lines[1]) if len(lines) > 1 else SpecialFileSize.UNKNOWN+ return title, size++@dataclass(kw_only=True)class YtDlpTaskStage(TaskStage):workerType: type = field(init=False, repr=False)- videoFormat: str = "bv*+ba/b"+ videoFormat: str = DEFAULT_VIDEO_FORMATheaders: dict[str, str] = field(default_factory=dict)proxies: dict[str, str] = field(default_factory=dict)lastMessage: str = ""@@ -84,10 +127,8 @@ class YtDlpTask(Task):from qfluentwidgets import FluentIconfrom app.view.components.add_task_dialog import SelectFolderCard- from .cards import YtDlpQualityEditCardreturn [- YtDlpQualityEditCard(FluentIcon.VIDEO, parent.tr("画质"), parent, initial=self.stage.videoFormat),SelectFolderCard(FluentIcon.DOWNLOAD, parent.tr("下载到"), parent, initial=self.path),]