Skip to content

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

feat(YouTube): 支持手动导入 Cookie,接收浏览器扩展 Cookie

XiaoYouChR6a4f37a8be36
diff --git a/features/yt_dlp_pack/config.py b/features/yt_dlp_pack/config.py
index d75d1f0f..ec880dd6 100644
--- a/features/yt_dlp_pack/config.py
+++ b/features/yt_dlp_pack/config.py
@@ -5,9 +5,13 @@ import platform
import sys
from pathlib import Path
-from PySide6.QtCore import QT_TRANSLATE_NOOP as N
+from PySide6.QtCore import QCoreApplication, QT_TRANSLATE_NOOP as N, Qt
from PySide6.QtWidgets import QWidget
-from qfluentwidgets import BoolValidator, ConfigItem, FluentIcon, FolderValidator, OptionsConfigItem, OptionsValidator
+from qfluentwidgets import (
+ BoolValidator, CaptionLabel, ConfigItem, FluentIcon, FolderValidator,
+ OptionsConfigItem, OptionsValidator, PushButton, SettingCard,
+ ToolButton, ToolTipFilter,
+)
from app.config.paths import APP_DATA_DIR
from app.models.pack import BinaryRuntime, PackConfig
@@ -16,6 +20,35 @@ from app.platform.filesystem import findExecutable
PYPI_API = "https://pypi.org/pypi/yt-dlp/json"
QJS_RELEASE_BASE = "https://github.com/quickjs-ng/quickjs/releases/latest/download"
+COOKIE_DOMAIN = ".youtube.com"
+
+
+def cookieFile() -> Path:
+ return Path(APP_DATA_DIR) / "YtDlp" / "cookies.txt"
+
+
+def hasCookieFile() -> bool:
+ path = cookieFile()
+ return path.is_file() and path.stat().st_size > 0
+
+
+def saveCookies(cookieString: str) -> None:
+ lines = ["# Netscape HTTP Cookie File"]
+ for pair in cookieString.split(";"):
+ pair = pair.strip()
+ if not pair or "=" not in pair:
+ continue
+ name, _, value = pair.partition("=")
+ lines.append(f"{COOKIE_DOMAIN}\tTRUE\t/\tTRUE\t0\t{name.strip()}\t{value.strip()}")
+ path = cookieFile()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+
+
+def clearCookies() -> None:
+ path = cookieFile()
+ if path.is_file():
+ path.unlink()
class YtDlpConfig(PackConfig):
@@ -57,6 +90,8 @@ class YtDlpConfig(PackConfig):
parent=group,
))
+ cards.append(CookieSettingCard(group))
+
cards.extend([
SwitchSettingCard(
FluentIcon.VIDEO,
@@ -261,4 +296,80 @@ def _qjsAssetName() -> str:
return f"qjs-linux-{arch}"
+class CookieSettingCard(SettingCard):
+
+ def __init__(self, parent=None):
+ super().__init__(
+ FluentIcon.CERTIFICATE,
+ QCoreApplication.translate("YtDlpConfig", "YouTube Cookie"),
+ self._statusText(),
+ parent,
+ )
+ self._importButton = PushButton(
+ QCoreApplication.translate("YtDlpConfig", "导入"),
+ self,
+ )
+ self._clearButton = ToolButton(FluentIcon.DELETE, self)
+ self._clearButton.setToolTip(
+ QCoreApplication.translate("YtDlpConfig", "清除 Cookie")
+ )
+ self._clearButton.installEventFilter(ToolTipFilter(self._clearButton))
+ self._clearButton.setVisible(hasCookieFile())
+
+ self.hBoxLayout.addWidget(self._importButton, 0, Qt.AlignmentFlag.AlignRight)
+ self.hBoxLayout.addSpacing(8)
+ self.hBoxLayout.addWidget(self._clearButton, 0, Qt.AlignmentFlag.AlignRight)
+ self.hBoxLayout.addSpacing(16)
+
+ self._importButton.clicked.connect(self._onImportClicked)
+ self._clearButton.clicked.connect(self._onClearClicked)
+
+ def _statusText(self) -> str:
+ if hasCookieFile():
+ return QCoreApplication.translate("YtDlpConfig", "已导入")
+ return QCoreApplication.translate(
+ "YtDlpConfig", "粘贴 Cookie 用于下载需要登录的内容"
+ )
+
+ def _refresh(self) -> None:
+ self.setContent(self._statusText())
+ self._clearButton.setVisible(hasCookieFile())
+
+ def _onImportClicked(self) -> None:
+ from qfluentwidgets import MessageBoxBase, SubtitleLabel, PlainTextEdit
+
+ dialog = MessageBoxBase(self.window())
+ dialog.widget.setMinimumWidth(500)
+ dialog.viewLayout.addWidget(SubtitleLabel(
+ QCoreApplication.translate("YtDlpConfig", "导入 YouTube Cookie"),
+ dialog,
+ ))
+
+ label = CaptionLabel(
+ QCoreApplication.translate(
+ "YtDlpConfig",
+ "打开 YouTube 并登录,按 F12 打开开发者工具,在 Network 标签中"
+ "找到任意请求,复制其 Cookie 请求头的值并粘贴到下方",
+ ),
+ dialog,
+ )
+ label.setWordWrap(True)
+ dialog.viewLayout.addWidget(label)
+
+ editor = PlainTextEdit(dialog)
+ editor.setPlaceholderText("SID=xxx; HSID=xxx; ...")
+ editor.setMinimumHeight(120)
+ dialog.viewLayout.addWidget(editor)
+
+ if dialog.exec():
+ text = editor.toPlainText().strip()
+ if text:
+ saveCookies(text)
+ self._refresh()
+
+ def _onClearClicked(self) -> None:
+ clearCookies()
+ self._refresh()
+
+
youTubeRuntime = YouTubeRuntime()
diff --git a/features/yt_dlp_pack/error_catalog.py b/features/yt_dlp_pack/error_catalog.py
index d6f97ecc..94f02dd2 100644
--- a/features/yt_dlp_pack/error_catalog.py
+++ b/features/yt_dlp_pack/error_catalog.py
@@ -8,6 +8,8 @@ N("TaskErrors", "年龄限制视频,需要已登录账号的 Cookie({detail}
N("TaskErrors", "YouTube 需要人机验证,请在设置中配置 Cookie({detail})")
N("TaskErrors", "请求的格式不可用,请稍后重试({detail})")
N("TaskErrors", "下载被拒绝(403),链接可能已失效({detail})")
+N("TaskErrors", "浏览器 Cookie 解密失败,请在设置中手动导入 Cookie 或使用浏览器扩展({detail})")
+N("TaskErrors", "无法读取浏览器 Cookie 数据库,请关闭浏览器后重试或手动导入 Cookie({detail})")
N("TaskErrors", "视频信息提取失败:{detail}")
N("TaskErrors", "未找到可用的视频格式")
N("TaskErrors", "{name} 未安装,请在设置中安装")
diff --git a/features/yt_dlp_pack/pack.py b/features/yt_dlp_pack/pack.py
index 81eb3a0d..523123d2 100644
--- a/features/yt_dlp_pack/pack.py
+++ b/features/yt_dlp_pack/pack.py
@@ -25,6 +25,11 @@ class YouTubeParser(TaskParser):
url = options.url.strip()
isPlaylist = bool(parse_qs(urlparse(url).query).get("list"))
+ cookieHeader = options.headers.get("cookie") or options.headers.get("Cookie")
+ if cookieHeader:
+ from .config import saveCookies
+ saveCookies(cookieHeader)
+
title = await self._fetchTitle(url)
name = toSafeFilename(title) if title else "YouTube 视频"
diff --git a/features/yt_dlp_pack/task.py b/features/yt_dlp_pack/task.py
index 579d7dd4..dd545088 100644
--- a/features/yt_dlp_pack/task.py
+++ b/features/yt_dlp_pack/task.py
@@ -27,6 +27,8 @@ ERROR_HINTS = (
("confirm you're not a bot", "YouTube 需要人机验证,请在设置中配置 Cookie({detail})"),
("requested format is not available", "请求的格式不可用,请稍后重试({detail})"),
("http error 403", "下载被拒绝(403),链接可能已失效({detail})"),
+ ("decrypt", "浏览器 Cookie 解密失败,请在设置中手动导入 Cookie 或使用浏览器扩展({detail})"),
+ ("could not copy", "无法读取浏览器 Cookie 数据库,请关闭浏览器后重试或手动导入 Cookie({detail})"),
)
STEPS_PER_VIDEO = 4
@@ -51,7 +53,7 @@ def loadYtDlpToPath() -> None:
def buildYtDlpOptions(*, noplaylist: bool = True) -> dict:
- from .config import youTubeRuntime, ytDlpConfig
+ from .config import cookieFile, hasCookieFile, youTubeRuntime, ytDlpConfig
from app.config.cfg import proxy
opts: dict = {
@@ -67,9 +69,12 @@ def buildYtDlpOptions(*, noplaylist: bool = True) -> dict:
proxyUrl = proxy()
if proxyUrl:
opts["proxy"] = proxyUrl
- browser = ytDlpConfig.loginBrowser.value
- if browser:
- opts["cookiesfrombrowser"] = (browser,)
+ if hasCookieFile():
+ opts["cookiefile"] = str(cookieFile())
+ else:
+ browser = ytDlpConfig.loginBrowser.value
+ if browser:
+ opts["cookiesfrombrowser"] = (browser,)
return opts
@@ -77,8 +82,18 @@ def probeFormats(url: str) -> dict:
loadYtDlpToPath()
yt_dlp = importlib.import_module("yt_dlp")
opts = buildYtDlpOptions()
- with yt_dlp.YoutubeDL(opts) as ydl:
- return ydl.extract_info(url, download=False)
+ hasCookie = "cookiefile" in opts or "cookiesfrombrowser" in opts
+ try:
+ with yt_dlp.YoutubeDL(opts) as ydl:
+ return ydl.extract_info(url, download=False)
+ except Exception:
+ if not hasCookie:
+ raise
+ logger.info("retrying without cookies for {}", url)
+ opts.pop("cookiefile", None)
+ opts.pop("cookiesfrombrowser", None)
+ with yt_dlp.YoutubeDL(opts) as ydl:
+ return ydl.extract_info(url, download=False)
def probePlaylist(url: str) -> list[dict]: