Skip to content

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

fix(yt-dlp): 修复 Cookie 认证失效和格式提取失败

XiaoYouChRd1f0e5d7f991
diff --git a/features/yt_dlp_pack/config.py b/features/yt_dlp_pack/config.py
index 6a3d6f63..aa04ac60 100644
--- a/features/yt_dlp_pack/config.py
+++ b/features/yt_dlp_pack/config.py
@@ -9,8 +9,7 @@ from PySide6.QtCore import QCoreApplication, QT_TRANSLATE_NOOP as N, Qt
from PySide6.QtWidgets import QWidget
from qfluentwidgets import (
BoolValidator, CaptionLabel, ConfigItem, FluentIcon, FolderValidator,
- OptionsConfigItem, OptionsValidator, PushButton, SettingCard,
- ToolButton, ToolTipFilter,
+ PushButton, SettingCard, ToolButton, ToolTipFilter,
)
from app.config.paths import APP_DATA_DIR
@@ -21,6 +20,7 @@ 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"
+AUTH_COOKIE_NAMES = ("LOGIN_INFO", "SAPISID", "__Secure-1PAPISID", "__Secure-3PAPISID")
def cookieFile() -> Path:
@@ -45,6 +45,11 @@ def saveCookies(cookieString: str) -> None:
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+def saveCookiesIfBetter(cookieString: str) -> None:
+ if any(name in cookieString for name in AUTH_COOKIE_NAMES):
+ saveCookies(cookieString)
+
+
def clearCookies() -> None:
path = cookieFile()
if path.is_file():
@@ -53,17 +58,13 @@ def clearCookies() -> None:
class YtDlpConfig(PackConfig):
installFolder = ConfigItem("YtDlp", "InstallFolder", f"{APP_DATA_DIR}/YtDlp", FolderValidator())
- loginBrowser = OptionsConfigItem(
- "YtDlp", "LoginBrowser", "",
- OptionsValidator(["", "chrome", "firefox", "edge", "safari"]),
- )
subtitleLanguages = ConfigItem("YtDlp", "SubtitleLanguages", "en")
shouldPreferMp4 = ConfigItem("YtDlp", "PreferMp4", True, BoolValidator())
shouldEmbedMetadata = ConfigItem("YtDlp", "EmbedMetadata", True, BoolValidator())
shouldEmbedChapters = ConfigItem("YtDlp", "EmbedChapters", True, BoolValidator())
def settingGroups(self, parent: QWidget) -> list:
- from qfluentwidgets import ComboBoxSettingCard, FluentIcon, SwitchSettingCard
+ from qfluentwidgets import FluentIcon, SwitchSettingCard
from app.view.components.setting_card_group import CollapsibleSettingCardGroup
from app.view.components.setting_cards import SelectFolderSettingCard
@@ -81,15 +82,6 @@ class YtDlpConfig(PackConfig):
installFolderCard.pathChanged.connect(runtimeCard._onInstallFolderChanged)
cards.insert(0, installFolderCard)
- cards.append(ComboBoxSettingCard(
- self.loginBrowser,
- FluentIcon.PEOPLE,
- self.tr("登录浏览器"),
- self.tr("从指定浏览器读取 YouTube 登录状态,用于下载需要登录的内容"),
- texts=[self.tr("不使用"), "Chrome", "Firefox", "Edge", "Safari"],
- parent=group,
- ))
-
cards.append(CookieSettingCard(group))
cards.extend([
@@ -330,6 +322,10 @@ class CookieSettingCard(SettingCard):
"YtDlpConfig", "粘贴 Cookie 用于下载需要登录的内容"
)
+ def showEvent(self, event) -> None:
+ super().showEvent(event)
+ self._refresh()
+
def _refresh(self) -> None:
self.setContent(self._statusText())
self._clearButton.setVisible(hasCookieFile())
diff --git a/features/yt_dlp_pack/error_catalog.py b/features/yt_dlp_pack/error_catalog.py
index 94f02dd2..d764afe0 100644
--- a/features/yt_dlp_pack/error_catalog.py
+++ b/features/yt_dlp_pack/error_catalog.py
@@ -2,14 +2,12 @@ from PySide6.QtCore import QT_TRANSLATE_NOOP as N
N("TaskErrors", "该视频在您所在地区不可用,请尝试配置代理({detail})")
N("TaskErrors", "视频不可用,可能已被删除或设为私密({detail})")
-N("TaskErrors", "私密视频,需要已授权账号的 Cookie({detail})")
-N("TaskErrors", "会员专属视频,需要会员账号的 Cookie({detail})")
-N("TaskErrors", "年龄限制视频,需要已登录账号的 Cookie({detail})")
-N("TaskErrors", "YouTube 需要人机验证,请在设置中配置 Cookie({detail})")
+N("TaskErrors", "私密视频,需要已授权账号的 Cookie。请通过浏览器扩展下载或在设置中手动导入 Cookie({detail})")
+N("TaskErrors", "会员专属视频,需要会员账号的 Cookie。请通过浏览器扩展下载或在设置中手动导入 Cookie({detail})")
+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 38ae05f5..b7ad4ec6 100644
--- a/features/yt_dlp_pack/pack.py
+++ b/features/yt_dlp_pack/pack.py
@@ -28,8 +28,8 @@ class YouTubeParser(TaskParser):
cookieHeader = options.headers.get("cookie") or options.headers.get("Cookie")
if cookieHeader:
- from .config import saveCookies
- saveCookies(cookieHeader)
+ from .config import saveCookiesIfBetter
+ saveCookiesIfBetter(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 5908292c..29d6d830 100644
--- a/features/yt_dlp_pack/task.py
+++ b/features/yt_dlp_pack/task.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import importlib
+import io
import re
import shutil
import tempfile
@@ -21,14 +22,12 @@ from ffmpeg_pack.task import FFmpegResourceStep, FFmpegStep, mediaStem
ERROR_HINTS = (
("is not available in your country", "该视频在您所在地区不可用,请尝试配置代理({detail})"),
("video unavailable", "视频不可用,可能已被删除或设为私密({detail})"),
- ("private video", "私密视频,需要已授权账号的 Cookie({detail})"),
- ("members-only", "会员专属视频,需要会员账号的 Cookie({detail})"),
- ("confirm your age", "年龄限制视频,需要已登录账号的 Cookie({detail})"),
- ("confirm you're not a bot", "YouTube 需要人机验证,请在设置中配置 Cookie({detail})"),
+ ("private video", "私密视频,需要已授权账号的 Cookie。请通过浏览器扩展下载或在设置中手动导入 Cookie({detail})"),
+ ("members-only", "会员专属视频,需要会员账号的 Cookie。请通过浏览器扩展下载或在设置中手动导入 Cookie({detail})"),
+ ("confirm your age", "年龄限制视频,需要登录。请通过浏览器扩展下载或在设置中手动导入 Cookie({detail})"),
+ ("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
@@ -53,13 +52,14 @@ def loadYtDlpToPath() -> None:
def buildYtDlpOptions(*, noplaylist: bool = True) -> dict:
- from .config import cookieFile, hasCookieFile, youTubeRuntime, ytDlpConfig
+ from .config import cookieFile, hasCookieFile, youTubeRuntime
from app.config.cfg import proxy
opts: dict = {
"quiet": True,
"no_warnings": True,
"allowed_extractors": ["youtube.*"],
+ "remote_components": {"ejs:github"},
}
if noplaylist:
opts["noplaylist"] = True
@@ -70,11 +70,7 @@ def buildYtDlpOptions(*, noplaylist: bool = True) -> dict:
if proxyUrl:
opts["proxy"] = proxyUrl
if hasCookieFile():
- opts["cookiefile"] = str(cookieFile())
- else:
- browser = ytDlpConfig.loginBrowser.value
- if browser:
- opts["cookiesfrombrowser"] = (browser,)
+ opts["cookiefile"] = io.StringIO(cookieFile().read_text(encoding="utf-8"))
return opts
@@ -82,18 +78,8 @@ def probeFormats(url: str) -> dict:
loadYtDlpToPath()
yt_dlp = importlib.import_module("yt_dlp")
opts = buildYtDlpOptions()
- 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)
+ with yt_dlp.YoutubeDL(opts) as ydl:
+ return ydl.extract_info(url, download=False)
def probePlaylist(url: str) -> list[dict]:
@@ -364,7 +350,7 @@ class YouTubeResourceStep(FFmpegResourceStep):
if not self.url:
self.setStatus(TaskStatus.COMPLETED)
return
- await super().run()
+ await super().run(reportSpeed, waitForSpeedLimit)
@dataclass(kw_only=True)
@@ -401,7 +387,7 @@ class YouTubeMergeStep(FFmpegStep):
if self.metadataTitle or self.chapters:
await self._runWithMetadata()
else:
- await super().run()
+ await super().run(reportSpeed, waitForSpeedLimit)
return
singleInput = self._videoPath if hasVideo else self._audioPath if hasAudio else None