Skip to content

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

fix(yt_dlp): 修复部分机器提取报格式不可用的问题

XiaoYouChR79cccbdbf338
diff --git a/dist/packs/yt_dlp_pack.zip b/dist/packs/yt_dlp_pack.zip
index 1ac971d0..4fc1e53a 100644
Binary files a/dist/packs/yt_dlp_pack.zip and b/dist/packs/yt_dlp_pack.zip differ
diff --git a/docs/adr/0007-yt-dlp-library-mode-with-wreq.md b/docs/adr/0007-yt-dlp-library-mode-with-wreq.md
index 325897b5..4a1fe4c9 100644
--- a/docs/adr/0007-yt-dlp-library-mode-with-wreq.md
+++ b/docs/adr/0007-yt-dlp-library-mode-with-wreq.md
@@ -12,9 +12,11 @@ progress — it never touches YouTube's API directly.
Switch yt_dlp_pack from subprocess mode to **library mode, extract-only**:
-- **Install:** download the `yt_dlp` wheel (~3–5 MB) and a QuickJS-NG `qjs`
- binary (~2 MB) at runtime into the pack's vendor directory. One "一键安装"
- button, one Task with three steps (download whl, download qjs, extract/chmod).
+- **Install:** download the `yt_dlp` wheel (~3–5 MB), the matching `yt-dlp-ejs`
+ challenge-solver wheel (~55 KB, pinned to `yt_dlp`'s `vendor.VERSION`), and a
+ QuickJS-NG `qjs` binary (~2 MB) at runtime into the pack's vendor directory.
+ All three are installed via `YouTubeRuntime.install()` using PyPI/GitCode
+ mirrors so extraction does not depend on reaching GitHub at runtime.
Total: ~7 MB vs ~130 MB.
- **Isolation:** all yt-dlp imports are lazy (`importlib.import_module`), so
Nuitka's AST scanner in `deploy.py` never sees them. The main binary size is
diff --git a/features/yt_dlp_pack/config.py b/features/yt_dlp_pack/config.py
index 84249f46..1cf098ce 100644
--- a/features/yt_dlp_pack/config.py
+++ b/features/yt_dlp_pack/config.py
@@ -173,17 +173,7 @@ class YouTubeRuntime(BinaryRuntime):
if not versionFile.is_file():
return VersionInfo("")
- ytDlpVersion = ""
- try:
- text = versionFile.read_text(encoding="utf-8")
- for node in ast.walk(ast.parse(text)):
- if isinstance(node, ast.Assign):
- for target in node.targets:
- if isinstance(target, ast.Name) and target.id == "__version__":
- if isinstance(node.value, ast.Constant):
- ytDlpVersion = str(node.value.value)
- except Exception:
- pass
+ ytDlpVersion = parseConstant(versionFile, "__version__")
qjsPath = self.qjsPath()
if qjsPath:
@@ -210,9 +200,10 @@ class YouTubeRuntime(BinaryRuntime):
def installedPaths(self) -> list[Path]:
folder = self.installFolder()
- if IS_ANDROID:
- return [folder / "yt_dlp"]
- return [folder / "yt_dlp", folder / ("qjs.exe" if sys.platform == "win32" else "qjs")]
+ paths = [folder / "yt_dlp", folder / "yt_dlp_ejs"]
+ if not IS_ANDROID:
+ paths.append(folder / ("qjs.exe" if sys.platform == "win32" else "qjs"))
+ return paths
async def install(self, version: str, onProgress: Callable[[float], None]) -> None:
folder = self.installFolder()
@@ -233,6 +224,51 @@ class YouTubeRuntime(BinaryRuntime):
await fetchPypiFile(wheelUrl, archive, onProgress)
await installArchive(archive, folder, subtree="yt_dlp/")
+ ejsInfoFile = folder / "yt_dlp" / "extractor" / "youtube" / "jsc" / "_builtin" / "vendor" / "_info.py"
+ ejsVersion = parseConstant(ejsInfoFile, "VERSION")
+ if ejsVersion:
+ ejsUrl = await fetchEjsWheel(ejsVersion)
+ ejsArchive = folder / "yt_dlp_ejs.whl"
+ await fetchPypiFile(ejsUrl, ejsArchive)
+ await installArchive(ejsArchive, folder, subtree="yt_dlp_ejs/")
+
+
+def parseConstant(path: Path, name: str) -> str:
+ if not path.is_file():
+ return ""
+ try:
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Assign):
+ for target in node.targets:
+ if isinstance(target, ast.Name) and target.id == name:
+ if isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):
+ return node.value.value
+ except Exception:
+ pass
+ return ""
+
+
+async def fetchEjsWheel(version: str) -> str:
+ target = parseVersion(version)
+ exact: str = ""
+ compatible: dict[tuple[int, ...], str] = {}
+ for releaseVersion, files in (await fetchPypiReleases("yt-dlp-ejs")).items():
+ wheel = next((f for f in files if f["filename"].endswith("-py3-none-any.whl") and not f.get("yanked")), None)
+ if not wheel:
+ continue
+ parsed = parseVersion(releaseVersion)
+ if parsed == target:
+ exact = wheel["url"]
+ break
+ if parsed[:2] == target[:2] and "dev" not in releaseVersion:
+ compatible[parsed] = wheel["url"]
+ if exact:
+ return exact
+ if compatible:
+ return compatible[max(compatible)]
+ raise TaskError("未找到 yt-dlp-ejs {version}", version=version)
+
async def fetchNightlyWheel() -> tuple[str, str]:
nightlies = {}
diff --git a/features/yt_dlp_pack/i18n.py b/features/yt_dlp_pack/i18n.py
index a5521de8..626bc285 100644
--- a/features/yt_dlp_pack/i18n.py
+++ b/features/yt_dlp_pack/i18n.py
@@ -6,9 +6,12 @@ N("TaskErrors", "私密视频,需要已授权账号的 Cookie。请通过浏
N("TaskErrors", "会员专属视频,需要会员账号的 Cookie。请通过浏览器扩展下载或在设置中手动导入 Cookie({detail})")
N("TaskErrors", "年龄限制视频,需要登录。请通过浏览器扩展下载或在设置中手动导入 Cookie({detail})")
N("TaskErrors", "YouTube 需要人机验证。请通过浏览器扩展下载或在设置中手动导入 Cookie({detail})")
-N("TaskErrors", "请求的格式不可用,请稍后重试({detail})")
+N("TaskErrors", "QuickJS 运行环境异常,请在设置中重新安装 yt-dlp({detail})")
+N("TaskErrors", "YouTube 解密组件缺失或不可用,请在设置中更新或重新安装 yt-dlp({detail})")
+N("TaskErrors", "YouTube Cookie 已失效或受限,请在设置中清除或重新导入 Cookie({detail})")
+N("TaskErrors", "请求的格式不可用,请在设置中更新 yt-dlp 后重试({detail})")
N("TaskErrors", "下载被拒绝(403),链接可能已失效({detail})")
N("TaskErrors", "视频信息提取失败:{detail}")
N("TaskErrors", "未找到可用的视频格式")
-N("TaskErrors", "未找到 yt-dlp nightly tarball")
-N("TaskErrors", "FFmpeg 写入元数据失败({code}):{detail}")
+N("TaskErrors", "未找到 yt-dlp nightly")
+N("TaskErrors", "未找到 yt-dlp-ejs {version}")
diff --git a/features/yt_dlp_pack/manifest.toml b/features/yt_dlp_pack/manifest.toml
index ec4436c9..a96b63f2 100644
--- a/features/yt_dlp_pack/manifest.toml
+++ b/features/yt_dlp_pack/manifest.toml
@@ -2,5 +2,5 @@
entry = "pack.py"
class = "YouTubePack"
dependencies = ["http_pack", "ffmpeg_pack"]
-version = "1.4.1"
+version = "1.4.2"
gdMinVersion = "4.5.0"
diff --git a/features/yt_dlp_pack/task.py b/features/yt_dlp_pack/task.py
index 58f7a70c..4d44c984 100644
--- a/features/yt_dlp_pack/task.py
+++ b/features/yt_dlp_pack/task.py
@@ -5,7 +5,7 @@ import importlib
import io
import tempfile
import threading
-from collections.abc import Awaitable, Callable, Iterable, Iterator
+from collections.abc import Awaitable, Callable, Iterable, Iterator, Sequence
from dataclasses import dataclass, field
from itertools import count
from pathlib import Path
@@ -26,10 +26,59 @@ ERROR_HINTS = (
("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})"),
)
+FORMAT_UNAVAILABLE_NEEDLE = "requested format is not available"
+
+FORMAT_WARNING_HINTS = (
+ (
+ ("no supported javascript runtime", "error running quickjs"),
+ "QuickJS 运行环境异常,请在设置中重新安装 yt-dlp({detail})",
+ ),
+ (
+ ("failed to download challenge solver", "remote component", "n challenge solving failed"),
+ "YouTube 解密组件缺失或不可用,请在设置中更新或重新安装 yt-dlp({detail})",
+ ),
+ (
+ ("cookies are no longer valid", "forcing sabr"),
+ "YouTube Cookie 已失效或受限,请在设置中清除或重新导入 Cookie({detail})",
+ ),
+)
+
+
+class YtDlpLogger:
+ def __init__(self) -> None:
+ self.warnings: list[str] = []
+
+ def debug(self, msg: str) -> None:
+ if msg:
+ logger.debug("[yt-dlp] {}", msg)
+
+ def warning(self, msg: str) -> None:
+ if msg:
+ self.warnings.append(msg)
+ logger.warning("[yt-dlp] {}", msg)
+
+ def error(self, msg: str) -> None:
+ if msg:
+ logger.warning("[yt-dlp] {}", msg)
+
+
+def buildExtractError(detail: str, warnings: Sequence[str] = ()) -> TaskError:
+ lowered = detail.lower()
+ hint = next((h for needle, h in ERROR_HINTS if needle in lowered), "")
+ if hint:
+ return TaskError(hint, detail=detail)
+ if FORMAT_UNAVAILABLE_NEEDLE in lowered:
+ joinedWarnings = "\n".join(warnings).lower()
+ for needles, warningHint in FORMAT_WARNING_HINTS:
+ if any(needle in joinedWarnings for needle in needles):
+ return TaskError(warningHint, detail=detail)
+ return TaskError("请求的格式不可用,请在设置中更新 yt-dlp 后重试({detail})", detail=detail)
+ return TaskError("视频信息提取失败:{detail}", detail=detail or "unknown")
+
+
_pathLock = threading.Lock()
_pathInserted = False
@@ -49,17 +98,23 @@ def loadYtDlpToPath() -> None:
_pathInserted = True
-def buildYtDlpOptions(*, noplaylist: bool = True) -> dict:
+def buildYtDlpOptions(
+ *,
+ noplaylist: bool = True,
+ useCookies: bool = True,
+ ytLogger: YtDlpLogger | None = None,
+) -> dict:
from .config import cookieFile, hasCookieFile, youTubeRuntime
from app.config.cfg import cfg, proxy
opts: dict = {
"quiet": True,
- "no_warnings": True,
"allowed_extractors": ["youtube.*"],
"remote_components": {"ejs:github"},
"nocheckcertificate": not cfg.shouldVerifySsl.value,
}
+ if ytLogger is not None:
+ opts["logger"] = ytLogger
if noplaylist:
opts["noplaylist"] = True
qjsPath = youTubeRuntime.qjsPath()
@@ -68,26 +123,52 @@ def buildYtDlpOptions(*, noplaylist: bool = True) -> dict:
proxyUrl = proxy()
if proxyUrl:
opts["proxy"] = proxyUrl
- if hasCookieFile():
+ if useCookies and hasCookieFile():
opts["cookiefile"] = io.StringIO(cookieFile().read_text(encoding="utf-8"))
return opts
-def probeFormats(url: str) -> dict:
+def extractInfo(url: str, opts: dict) -> 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)
+def probeFormats(
+ url: str,
+ *,
+ extract: Callable[[str, dict], dict] = extractInfo,
+) -> dict:
+ ytLogger = YtDlpLogger()
+ opts = buildYtDlpOptions(ytLogger=ytLogger)
+ try:
+ return extract(url, opts)
+ except Exception as firstError:
+ detail = str(firstError)
+ shouldRetryWithoutCookies = (
+ "cookiefile" in opts
+ and FORMAT_UNAVAILABLE_NEEDLE in detail.lower()
+ and not any(needle in detail.lower() for needle, _ in ERROR_HINTS)
+ )
+ if shouldRetryWithoutCookies:
+ logger.info("retrying extract_info without cookies for {}", url)
+ retryLogger = YtDlpLogger()
+ retryOpts = buildYtDlpOptions(useCookies=False, ytLogger=retryLogger)
+ try:
+ return extract(url, retryOpts)
+ except Exception as retryError:
+ logger.opt(exception=retryError).warning("extract_info retry without cookies failed for {}", url)
+ raise buildExtractError(str(retryError), [*ytLogger.warnings, *retryLogger.warnings]) from retryError
+ logger.opt(exception=firstError).warning("extract_info failed for {}", url)
+ raise buildExtractError(detail, ytLogger.warnings) from firstError
+
+
def probePlaylist(url: str) -> list[dict]:
- loadYtDlpToPath()
- yt_dlp = importlib.import_module("yt_dlp")
- opts = buildYtDlpOptions(noplaylist=False)
+ ytLogger = YtDlpLogger()
+ opts = buildYtDlpOptions(noplaylist=False, ytLogger=ytLogger)
opts["extract_flat"] = True
- with yt_dlp.YoutubeDL(opts) as ydl:
- info = ydl.extract_info(url, download=False)
+ info = extractInfo(url, opts)
entries = info.get("entries") or []
return [
{"id": e.get("id") or "", "title": e.get("title") or "", "duration": e.get("duration") or 0}
@@ -355,16 +436,7 @@ class YouTubeExtractStep(TaskStep):
raise TaskError("{name} 未安装,请在设置中安装", name=youTubeRuntime.name)
url = self.videoUrl or self.task.url
- try:
- info = await asyncio.to_thread(probeFormats, url)
- except Exception as e:
- logger.opt(exception=e).warning("extract_info failed for {}", url)
- detail = str(e)
- lowered = detail.lower()
- hint = next((h for needle, h in ERROR_HINTS if needle in lowered), "")
- if hint:
- raise TaskError(hint, detail=detail)
- raise TaskError("视频信息提取失败:{detail}", detail=detail or "unknown")
+ info = await asyncio.to_thread(probeFormats, url)
videoFmt, audioFmt = buildFormatPair(info, self.task)
if not videoFmt and not audioFmt:
diff --git a/tests/yt_dlp_pack/test_binary_runtime.py b/tests/yt_dlp_pack/test_binary_runtime.py
index 89bfc2e6..73b302c3 100644
--- a/tests/yt_dlp_pack/test_binary_runtime.py
+++ b/tests/yt_dlp_pack/test_binary_runtime.py
@@ -1,13 +1,15 @@
from __future__ import annotations
+import pytest
from aiohttp import web
from app import sources
-from yt_dlp_pack.config import fetchNightlyWheel
+from app.models.task import TaskError
+from yt_dlp_pack.config import fetchEjsWheel, fetchNightlyWheel
-def buildWheel(version: str, yanked: bool = False) -> dict:
- return {"filename": f"yt_dlp-{version}-py3-none-any.whl", "url": version, "yanked": yanked}
+def buildWheel(version: str, yanked: bool = False, package: str = "yt_dlp") -> dict:
+ return {"filename": f"{package}-{version}-py3-none-any.whl", "url": version, "yanked": yanked}
async def test_probe_nightly_is_latest_dev_build(startServer, monkeypatch):
@@ -27,3 +29,25 @@ async def test_probe_nightly_is_latest_dev_build(startServer, monkeypatch):
monkeypatch.setitem(sources.PYPI_MIRRORS, source, url)
assert await fetchNightlyWheel() == ("2026.08.27.003630", "2026.8.27.3630.dev0")
+
+
+async def test_fetch_ejs_wheel_matches_version_or_same_minor(startServer, monkeypatch):
+ releases = {
+ "0.7.0": [buildWheel("0.7.0", package="yt_dlp_ejs")],
+ "0.8.0": [buildWheel("0.8.0", package="yt_dlp_ejs")],
+ "0.8.1": [buildWheel("0.8.1", package="yt_dlp_ejs")],
+ "0.8.2": [buildWheel("0.8.2", yanked=True, package="yt_dlp_ejs")],
+ "0.8.3.dev0": [buildWheel("0.8.3.dev0", package="yt_dlp_ejs")],
+ }
+
+ async def handler(request):
+ return web.json_response({"releases": releases})
+
+ url = await startServer(handler)
+ for source in sources.PYPI_MIRRORS:
+ monkeypatch.setitem(sources.PYPI_MIRRORS, source, url)
+
+ assert await fetchEjsWheel("0.8.0") == "0.8.0"
+ assert await fetchEjsWheel("0.8.9") == "0.8.1"
+ with pytest.raises(TaskError, match="yt-dlp-ejs"):
+ await fetchEjsWheel("0.9.0")
diff --git a/tests/yt_dlp_pack/test_task.py b/tests/yt_dlp_pack/test_task.py
index c12e786a..36749a4a 100644
--- a/tests/yt_dlp_pack/test_task.py
+++ b/tests/yt_dlp_pack/test_task.py
@@ -85,3 +85,72 @@ def test_merge_step_builds_per_source_trim_args(tmp_path):
assert mergeStep._buildTrimArgs(mergeStep._videoPath) == (["-ss", "3.0"], ["-t", "30"])
assert mergeStep._buildTrimArgs(mergeStep._audioPath) == (["-ss", "0.5"], ["-t", "30"])
+
+def test_probe_formats_retries_without_cookies():
+ from yt_dlp_pack.config import clearCookies, saveCookies
+ from yt_dlp_pack.task import probeFormats
+
+ calls: list[bool] = []
+
+ def fakeExtract(url: str, opts: dict) -> dict:
+ hasCookies = "cookiefile" in opts
+ calls.append(hasCookies)
+ if hasCookies:
+ opts["logger"].warning("The provided YouTube account cookies are no longer valid.")
+ raise RuntimeError("ERROR: [youtube] wYSncx9zLIU: Requested format is not available.")
+ return {"id": "wYSncx9zLIU", "formats": [{"format_id": "18"}]}
+
+ saveCookies("SID=1")
+ try:
+ info = probeFormats("https://www.youtube.com/watch?v=wYSncx9zLIU", extract=fakeExtract)
+ finally:
+ clearCookies()
+
+ assert calls == [True, False]
+ assert info["id"] == "wYSncx9zLIU"
+
+
+def test_probe_formats_keeps_auth_error_with_cookies():
+ from yt_dlp_pack.config import clearCookies, saveCookies
+ from yt_dlp_pack.task import probeFormats
+
+ calls: list[bool] = []
+
+ def fakeExtract(url: str, opts: dict) -> dict:
+ calls.append("cookiefile" in opts)
+ raise RuntimeError("ERROR: [youtube] abc: Private video. Sign in if you've been granted access")
+
+ saveCookies("SID=1")
+ try:
+ with pytest.raises(TaskError, match="私密视频"):
+ probeFormats("https://www.youtube.com/watch?v=abc", extract=fakeExtract)
+ finally:
+ clearCookies()
+
+ assert calls == [True]
+
+
+ ("warning", "expectedMatch"),
+ [
+ ("No supported JavaScript runtime could be found.", "QuickJS"),
+ ("Remote component challenge solver script (quickjs) was skipped.", "解密组件"),
+ ("n challenge solving failed: Some formats may be missing.", "解密组件"),
+ ("The provided YouTube account cookies are no longer valid.", "Cookie"),
+ ("", "更新 yt-dlp"),
+ ],
+)
+def test_probe_formats_reports_root_cause_from_warnings(warning, expectedMatch):
+ from yt_dlp_pack.config import clearCookies
+ from yt_dlp_pack.task import probeFormats
+
+ clearCookies()
+
+ def fakeExtract(url: str, opts: dict) -> dict:
+ if warning:
+ opts["logger"].warning(warning)
+ raise RuntimeError("ERROR: [youtube] wYSncx9zLIU: Requested format is not available.")
+
+ with pytest.raises(TaskError, match=expectedMatch):
+ probeFormats("https://www.youtube.com/watch?v=wYSncx9zLIU", extract=fakeExtract)
+
diff --git a/versions.json b/versions.json
index 3d7dadd6..7f8d2ec4 100644
--- a/versions.json
+++ b/versions.json
@@ -116,9 +116,9 @@
"gdMinVersion": "4.5.0"
},
"yt_dlp_pack": {
- "version": "1.4.1",
+ "version": "1.4.2",
"file": "yt_dlp_pack.zip",
- "sha256": "61c04cdef4a75d0dc4c897938e6110a0c97062b565c048877fdc15aef26809a7",
+ "sha256": "0b702cafa0c3cae1d69c7de7169af1c3abed6688eefb2b3ae5c3ad3e92cc7423",
"gdMinVersion": "4.5.0"
},
"arxiv_pack": {