fix(download): explicit default,mweb clients so account cookies stop yielding "Video unavailable"
With account cookies yt-dlp's authed defaults are tv_downgraded + web, and on a share of videos both come back UNPLAYABLE / SABR-only, reported as "Video unavailable" with no formats. That happened on every static IP too, so it was mistaken for an IP ban and fed ~26 downloads a week to the per-GB proxy, which then fetched 360p through the same dead client list. Measured in the prod container on 6-sep-2026, same static proxy, same video: cookies + defaults -> unavailable; cookies + default,mweb (+ PO token) -> 1080p; no cookies -> 1080p. - yt_clients.py: one client list (default,mweb + bgutil provider) shared by the download and the duration probe. Never player_skip=webpage: it drops the Data Sync ID and mweb loses its PO token (360p only). - main.py: the fallback list (tv_embed, android) is gone from yt-dlp; the fallback now runs anonymously when the cookie attempt already failed on that route, and every attempt asks for the 1080p spec (the fallback's best[ext=mp4] was itself the 360p progressive file). - metering: an uploader's country block is a content error; the residential pool failed identically in 5 of 6 paid probes (3-5 sep). The probe alert now says when the paid proxy failed too. Claude-Session: https://claude.ai/code/session_013ubPhpBw8kAUcLXCCfH4C5
This commit is contained in:
parent
3c9cc989f2
commit
959407c30e
7 changed files with 184 additions and 44 deletions
24
CLAUDE.md
24
CLAUDE.md
|
|
@ -336,13 +336,27 @@ Async job queue with semaphore-based concurrency control. Configure via `MAX_CON
|
|||
|
||||
Downloads go direct → static ISP proxies (flat rate) → DataImpulse (per GB),
|
||||
and the duration probe (`cloud/metering.probe_url_minutes`) follows the same
|
||||
order, with one extra free step before any per-GB attempt: the conservative
|
||||
clients (tv_embed/android) through a static (`fallback-static`), because
|
||||
YouTube serves the HD/web client a fake "Video unavailable" from
|
||||
datacenter-ISP IPs on some videos while those clients pass on the same IPs. Two rules keep the per-GB proxy at zero on a normal day: the probe
|
||||
order, with one extra free step before any per-GB attempt: the fallback
|
||||
clients through a static (`fallback-static`). **The client list is explicit
|
||||
and shared** (`yt_clients.py`: `default,mweb` + the bgutil PO token
|
||||
provider): with account cookies yt-dlp's own defaults are `tv_downgraded` +
|
||||
`web`, and on a share of videos both come back UNPLAYABLE / SABR-only, which
|
||||
yt-dlp reports as "Video unavailable". That was mistaken for an IP ban for a
|
||||
week (it happened on every static IP too) and fed ~26 downloads a week to
|
||||
the per-GB proxy, which then fetched 360p through the same dead list.
|
||||
Measured in the prod container on 6-sep-2026, same static, same video:
|
||||
cookies + defaults → unavailable; cookies + `default,mweb` → 1080p; no
|
||||
cookies → 1080p. `mweb` needs the PO token, and the token needs the
|
||||
webpage: never put `player_skip: webpage` back. A fallback attempt runs
|
||||
anonymously when an HD attempt already failed with the cookies on that
|
||||
route, and every attempt asks for the 1080p format spec (the old
|
||||
`best[ext=mp4]` fallback spec was itself the 360p progressive file).
|
||||
Two rules keep the per-GB proxy at zero on a normal day: the probe
|
||||
reaches it **only** when a static route failed for a reason another IP can
|
||||
fix (`static_failure_warrants_paid`: bot-check, 403/429, proxy/network
|
||||
errors), never for a private/removed/members-only video or a live stream
|
||||
errors), never for a private/removed/members-only video, an uploader's
|
||||
country block (the residential pool failed identically in 5 of 6 paid
|
||||
probes, 3-5 sep) or a live stream
|
||||
with no duration (those failed the same on every IP and used to cost ~1.7 MB
|
||||
× 2 extractors each), and **never for a non-YouTube URL** (the download
|
||||
plan already excluded those; Twitch, Kick, Rumble and product pages were
|
||||
|
|
|
|||
|
|
@ -83,8 +83,6 @@ _IP_SPECIFIC_HINTS = (
|
|||
# — the same symptom as the 19-aug server-IP ban. A truly dead link costs
|
||||
# ~3 MB to re-check; a real video wrongly refused costs the job.
|
||||
"video unavailable",
|
||||
"available in your country", "in your country", "geo-restricted", "geoblock",
|
||||
"blocked it in your country",
|
||||
"remote end closed", "connection refused", "network is unreachable",
|
||||
"name or service not known", "eof occurred",
|
||||
)
|
||||
|
|
@ -94,6 +92,12 @@ _CONTENT_HINTS = (
|
|||
"unsupported url", "no video formats found", "premieres in", "will begin in",
|
||||
"this live event", "no duration in metadata", "requested format is not available",
|
||||
"account has been terminated", "video is age", "confirm your age",
|
||||
# An uploader's country block: the residential pool exits from the same
|
||||
# blocked countries, so the paid probe failed with the identical error in
|
||||
# 5 of the 6 cases between 3-sep and 5-sep-2026 (3.6 MB each, and the
|
||||
# Telegram alert claimed the paid proxy "answered").
|
||||
"available in your country", "in your country", "geo-restricted", "geoblock",
|
||||
"blocked it in your country",
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -161,17 +165,13 @@ def probe_url_minutes(url: str, allow_paid: bool = True) -> float:
|
|||
|
||||
bgutil_http = os.environ.get("BGUTIL_BASE_URL", "").strip()
|
||||
bgutil_script = os.environ.get("BGUTIL_SCRIPT_PATH", "").strip()
|
||||
conservative = {"youtube": {"player_client": ["tv_embed", "android", "mweb", "web"],
|
||||
"player_skip": ["webpage", "configs"]}}
|
||||
# Try the bgutil/HD extractor first (http or baked-in script), then the
|
||||
# conservative one — mirrors the download's HD→fallback logic.
|
||||
if bgutil_http:
|
||||
hd = [{"youtubepot-bgutilhttp": {"base_url": [bgutil_http]}}]
|
||||
elif bgutil_script:
|
||||
hd = [{"youtubepot-bgutilscript": {"script_path": [bgutil_script]}}]
|
||||
else:
|
||||
hd = []
|
||||
strategies = hd + [conservative]
|
||||
# Same client lists as the download (yt_clients.py): the authed defaults
|
||||
# alone answer "Video unavailable" for a share of videos on every IP, and
|
||||
# each of those probes then paid the per-GB proxy for nothing.
|
||||
from yt_clients import hd_extractor_args, fallback_extractor_args
|
||||
hd_args = hd_extractor_args(bgutil_http, bgutil_script)
|
||||
strategies = ([hd_args] if hd_args else []) + [
|
||||
fallback_extractor_args(bgutil_http, bgutil_script)]
|
||||
|
||||
# Rotated per probe to spread load across the pool, like the download does.
|
||||
statics = [p.strip() for p in
|
||||
|
|
|
|||
|
|
@ -218,7 +218,10 @@ async def record_probe(event: dict):
|
|||
await _persist("probe", event.get("job_id"), url_host, "paid-probe",
|
||||
int(event.get("bytes_estimate") or 0), event)
|
||||
fails = "\n".join(f" {k}: {str(v)[:140]}" for k, v in (event.get("static_errors") or {}).items())
|
||||
await _alert(f"probe {url_host or '?'}: statics failed, paid proxy answered"
|
||||
paid_failed = event.get("paid_failed")
|
||||
outcome = (f"paid proxy failed too: {str(paid_failed)[:140]}" if paid_failed
|
||||
else "paid proxy answered")
|
||||
await _alert(f"probe {url_host or '?'}: statics failed, {outcome}"
|
||||
+ (f"\n{fails}" if fails else ""), int(event.get("bytes_estimate") or 0))
|
||||
|
||||
|
||||
|
|
|
|||
48
main.py
48
main.py
|
|
@ -783,18 +783,13 @@ def download_youtube_video(url, output_dir="."):
|
|||
# conservative fallback (also the only strategy for self-host).
|
||||
_bgutil_http = os.environ.get("BGUTIL_BASE_URL", "").strip()
|
||||
_bgutil_script = os.environ.get("BGUTIL_SCRIPT_PATH", "").strip()
|
||||
if _bgutil_http:
|
||||
hd_args = {'youtubepot-bgutilhttp': {'base_url': [_bgutil_http]}}
|
||||
elif _bgutil_script:
|
||||
hd_args = {'youtubepot-bgutilscript': {'script_path': [_bgutil_script]}}
|
||||
else:
|
||||
hd_args = None
|
||||
fallback_args = {
|
||||
'youtube': {
|
||||
'player_client': ['tv_embed', 'android', 'mweb', 'web'],
|
||||
'player_skip': ['webpage', 'configs'],
|
||||
}
|
||||
}
|
||||
# Client lists live in yt_clients.py (shared with the duration probe):
|
||||
# explicit `default,mweb` because the authed defaults alone return
|
||||
# "Video unavailable" on a share of videos, from every IP, and that was
|
||||
# what fed the per-GB proxy (6-sep-2026, verified in the prod container).
|
||||
from yt_clients import hd_extractor_args, fallback_extractor_args
|
||||
hd_args = hd_extractor_args(_bgutil_http, _bgutil_script)
|
||||
fallback_args = fallback_extractor_args(_bgutil_http, _bgutil_script)
|
||||
|
||||
# Cap at 720p ONLY when the bytes actually go through the PER-GB paid proxy
|
||||
# — that cap exists to control bandwidth cost, and the direct attempt and
|
||||
|
|
@ -812,12 +807,11 @@ def download_youtube_video(url, output_dir="."):
|
|||
return ('bestvideo[vcodec^=avc1][height<=1080][ext=mp4]+bestaudio[ext=m4a]/'
|
||||
'bestvideo[vcodec^=avc1][height<=1080]+bestaudio/'
|
||||
'best[height<=1080][ext=mp4]/best[ext=mp4]/best')
|
||||
fallback_fmt = 'best[ext=mp4]/best'
|
||||
|
||||
def _base_opts(extractor_args, proxy):
|
||||
def _base_opts(extractor_args, proxy, cookies=True):
|
||||
return {
|
||||
'quiet': False, 'verbose': True, 'no_warnings': False,
|
||||
'cookiefile': cookies_path if cookies_path else None,
|
||||
'cookiefile': cookies_path if (cookies and cookies_path) else None,
|
||||
'proxy': proxy, 'socket_timeout': 30, 'retries': 10, 'fragment_retries': 10,
|
||||
'nocheckcertificate': True, 'cachedir': False,
|
||||
'extractor_args': extractor_args,
|
||||
|
|
@ -844,17 +838,17 @@ def download_youtube_video(url, output_dir="."):
|
|||
or d.get('total_bytes_estimate')
|
||||
or d.get('downloaded_bytes') or 0)
|
||||
|
||||
def _attempt(extractor_args, fmt, proxy):
|
||||
def _attempt(extractor_args, fmt, proxy, cookies=True):
|
||||
_dl_bytes["total"] = 0
|
||||
_dl_bytes["partial"] = 0
|
||||
with yt_dlp.YoutubeDL(_base_opts(extractor_args, proxy)) as ydl:
|
||||
with yt_dlp.YoutubeDL(_base_opts(extractor_args, proxy, cookies)) as ydl:
|
||||
info = ydl.extract_info(url, download=False)
|
||||
sanitized = sanitize_filename(info.get('title', 'youtube_video'))
|
||||
expected = os.path.join(output_dir, f'{sanitized}.mp4')
|
||||
if os.path.exists(expected):
|
||||
os.remove(expected)
|
||||
dl_opts = {
|
||||
**_base_opts(extractor_args, proxy),
|
||||
**_base_opts(extractor_args, proxy, cookies),
|
||||
'format': fmt,
|
||||
'outtmpl': os.path.join(output_dir, f'{sanitized}.%(ext)s'),
|
||||
'merge_output_format': 'mp4', 'overwrites': True,
|
||||
|
|
@ -870,11 +864,21 @@ def download_youtube_video(url, output_dir="."):
|
|||
_direct_first = (os.environ.get("DIRECT_FIRST", "").strip() == "1"
|
||||
and (_proxy or _statics) and hd_args and cookies_path)
|
||||
|
||||
# A fallback attempt runs anonymously when an HD attempt (with cookies)
|
||||
# already failed on the same route: the account cookies are what narrows
|
||||
# yt-dlp to the clients that die with "Video unavailable", and the
|
||||
# anonymous defaults were measured at 1080p on the same static IP. With
|
||||
# no HD path at all (self-host without a PO token provider) the fallback
|
||||
# is the only attempt, so it keeps the cookies the operator configured.
|
||||
# Every attempt asks for the same 1080p spec: the fallback used to ask
|
||||
# for `best[ext=mp4]/best`, the best single-file format, which on
|
||||
# YouTube is the 360p progressive one even with 1080p streams listed.
|
||||
attempts = [
|
||||
(label,
|
||||
fallback_args if label.startswith('fallback') else hd_args,
|
||||
fallback_fmt if label.startswith('fallback') else _hd_fmt_for(capped),
|
||||
proxy)
|
||||
_hd_fmt_for(capped),
|
||||
proxy,
|
||||
not (label.startswith('fallback') and hd_args))
|
||||
for label, capped, proxy in plan_download_attempts(
|
||||
_direct_first, _statics, _proxy, bool(hd_args), youtube=is_youtube_url(url))
|
||||
]
|
||||
|
|
@ -888,7 +892,7 @@ def download_youtube_video(url, output_dir="."):
|
|||
# below so app.py can keep a durable trail of WHY a job reached the paid
|
||||
# proxy (the container log rotates within the hour; see cloud/proxy_ledger).
|
||||
attempt_log = []
|
||||
for label, ea, fmt, proxy in attempts:
|
||||
for label, ea, fmt, proxy, cookies in attempts:
|
||||
# A 403 on the media fetch is usually transient: the googlevideo URL is
|
||||
# bound to the IP that extracted it, and the residential proxy rotates
|
||||
# its exit IP between requests. Retrying re-extracts and usually lands
|
||||
|
|
@ -896,7 +900,7 @@ def download_youtube_video(url, output_dir="."):
|
|||
for retry in range(2):
|
||||
try:
|
||||
print(f"📥 Download attempt: {label}" + (f" (retry {retry})" if retry else ""))
|
||||
sanitized_title = _attempt(ea, fmt, proxy)
|
||||
sanitized_title = _attempt(ea, fmt, proxy, cookies)
|
||||
# Only bytes through the PER-GB proxy cost money; direct and
|
||||
# the flat-rate static proxies are free bandwidth for the
|
||||
# monthly counter's purposes.
|
||||
|
|
|
|||
|
|
@ -30,8 +30,7 @@ class TestStaticFailureWarrantsPaid:
|
|||
"ERROR: [youtube] BJW5gAgk4bg: Video unavailable",
|
||||
"HTTP Error 403: Forbidden", "HTTP Error 429: Too Many Requests",
|
||||
"ProxyError: Tunnel connection failed: 407",
|
||||
"Unable to download webpage: The read operation timed out",
|
||||
"The uploader has not made this video available in your country"):
|
||||
"Unable to download webpage: The read operation timed out"):
|
||||
assert metering.static_failure_warrants_paid(err), err
|
||||
|
||||
def test_content_failures_do_not(self):
|
||||
|
|
@ -39,7 +38,10 @@ class TestStaticFailureWarrantsPaid:
|
|||
"This video has been removed by the uploader",
|
||||
"Join this channel to get access to members-only content",
|
||||
"no duration in metadata", "Premieres in 3 hours",
|
||||
"Unsupported URL: https://shopee.vn/product", "Sign in to confirm your age"):
|
||||
"Unsupported URL: https://shopee.vn/product", "Sign in to confirm your age",
|
||||
# the paid pool exits from the same blocked countries: 5 of 6
|
||||
# paid probes 3-5 sep 2026 failed with the identical error
|
||||
"The uploader has not made this video available in your country"):
|
||||
assert not metering.static_failure_warrants_paid(err), err
|
||||
|
||||
def test_unknown_errors_stay_free(self):
|
||||
|
|
|
|||
66
tests/test_yt_clients.py
Normal file
66
tests/test_yt_clients.py
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
"""YouTube client selection shared by the download and the duration probe.
|
||||
|
||||
Measured 6-sep-2026 in the prod container, same static proxy, same video:
|
||||
cookies + yt-dlp's authed defaults -> "Video unavailable" (no formats);
|
||||
cookies + mweb with a PO token, or no cookies at all -> 1080p. The explicit
|
||||
`default,mweb` list is what keeps those videos off the per-GB proxy.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
yt_clients = pytest.importorskip("yt_clients")
|
||||
|
||||
|
||||
def test_hd_needs_a_pot_provider():
|
||||
assert yt_clients.hd_extractor_args("", "") is None
|
||||
|
||||
|
||||
def test_hd_lists_default_and_mweb_with_the_provider():
|
||||
got = yt_clients.hd_extractor_args("", "/opt/gen.js")
|
||||
assert got["youtube"]["player_client"] == ["default", "mweb"]
|
||||
assert got["youtubepot-bgutilscript"] == {"script_path": ["/opt/gen.js"]}
|
||||
http = yt_clients.hd_extractor_args("http://pot:4416", "/opt/gen.js")
|
||||
assert http["youtubepot-bgutilhttp"] == {"base_url": ["http://pot:4416"]}
|
||||
assert "youtubepot-bgutilscript" not in http
|
||||
|
||||
|
||||
def test_fallback_never_skips_the_webpage():
|
||||
# player_skip=webpage drops the account's Data Sync ID and mweb then
|
||||
# cannot get its PO token: only the 360p progressive format survives.
|
||||
for args in (yt_clients.fallback_extractor_args("", ""),
|
||||
yt_clients.fallback_extractor_args("", "/opt/gen.js")):
|
||||
assert "player_skip" not in args["youtube"]
|
||||
assert "mweb" in args["youtube"]["player_client"]
|
||||
for dead in ("tv_embed", "android"):
|
||||
assert dead not in args["youtube"]["player_client"]
|
||||
|
||||
|
||||
def test_fallback_keeps_the_provider_when_configured():
|
||||
assert "youtubepot-bgutilscript" in yt_clients.fallback_extractor_args("", "/x.js")
|
||||
assert "youtubepot-bgutilscript" not in yt_clients.fallback_extractor_args("", "")
|
||||
|
||||
|
||||
def test_lists_are_copies():
|
||||
a = yt_clients.hd_extractor_args("", "/x.js")["youtube"]["player_client"]
|
||||
a.append("web_safari")
|
||||
assert yt_clients.hd_extractor_args("", "/x.js")["youtube"]["player_client"] == ["default", "mweb"]
|
||||
|
||||
|
||||
def test_probe_uses_the_same_lists(monkeypatch):
|
||||
metering = pytest.importorskip("cloud.metering")
|
||||
monkeypatch.setenv("BGUTIL_SCRIPT_PATH", "/opt/gen.js")
|
||||
monkeypatch.delenv("BGUTIL_BASE_URL", raising=False)
|
||||
monkeypatch.setenv("STATIC_PROXY_URLS", "")
|
||||
monkeypatch.setenv("PROXY_URL", "")
|
||||
monkeypatch.delenv("YOUTUBE_COOKIES", raising=False)
|
||||
seen = {}
|
||||
|
||||
def fake(url, proxies, strategies, static_errors, paid, ck_path):
|
||||
seen["strategies"] = strategies
|
||||
return 1.0
|
||||
|
||||
monkeypatch.setattr(metering, "_probe_with_proxies", fake)
|
||||
metering.probe_url_minutes("https://www.youtube.com/watch?v=abc")
|
||||
assert seen["strategies"] == [
|
||||
yt_clients.hd_extractor_args("", "/opt/gen.js"),
|
||||
yt_clients.fallback_extractor_args("", "/opt/gen.js"),
|
||||
]
|
||||
51
yt_clients.py
Normal file
51
yt_clients.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
"""yt-dlp client selection for YouTube, shared by the download (``main.py``)
|
||||
and the duration probe (``cloud/metering.py``) so the two cannot drift.
|
||||
|
||||
Why the client list is explicit. With account cookies yt-dlp's defaults are
|
||||
``tv_downgraded`` + ``web``, and for a share of videos both come back
|
||||
UNPLAYABLE / SABR-only, which surfaces as "Video unavailable" with no
|
||||
formats. That looked like an IP ban (it also happened on every static ISP IP)
|
||||
and for a week sent ~26 downloads a week to the per-GB proxy, which then
|
||||
downloaded 360p through the same dead client list. Measured on 6-sep-2026
|
||||
inside the prod container, same static proxy, same video:
|
||||
|
||||
cookies + default clients -> Video unavailable
|
||||
cookies + mweb (+ PO token) -> 1080p
|
||||
no cookies + default clients -> 1080p
|
||||
cookies + default,mweb (+ PO token) -> 1080p (also on a video that worked)
|
||||
|
||||
``mweb`` needs a GVS PO token for its https formats, which the bgutil
|
||||
provider mints as long as the webpage is NOT skipped (``player_skip:
|
||||
webpage`` drops the account's Data Sync ID and the token request fails).
|
||||
The old fallback list (``tv_embed``, ``android``) is gone from yt-dlp: the
|
||||
first is "unsupported", the second is skipped whenever cookies are present.
|
||||
"""
|
||||
|
||||
HD_CLIENTS = ["default", "mweb"]
|
||||
|
||||
|
||||
def pot_provider_args(bgutil_http, bgutil_script):
|
||||
"""Extractor args selecting the PO token provider (bgutil http or script)."""
|
||||
if bgutil_http:
|
||||
return {"youtubepot-bgutilhttp": {"base_url": [bgutil_http]}}
|
||||
if bgutil_script:
|
||||
return {"youtubepot-bgutilscript": {"script_path": [bgutil_script]}}
|
||||
return {}
|
||||
|
||||
|
||||
def hd_extractor_args(bgutil_http, bgutil_script):
|
||||
"""Extractor args for the HD attempt, or None when no PO token provider
|
||||
is configured (the HD path needs one; the plan then skips it)."""
|
||||
provider = pot_provider_args(bgutil_http, bgutil_script)
|
||||
if not provider:
|
||||
return None
|
||||
return {**provider, "youtube": {"player_client": list(HD_CLIENTS)}}
|
||||
|
||||
|
||||
def fallback_extractor_args(bgutil_http, bgutil_script):
|
||||
"""Extractor args for the conservative attempt: same live client list,
|
||||
the provider when there is one, and never ``player_skip`` (see module
|
||||
docstring). Without a provider mweb still serves the progressive 360p
|
||||
format, which is enough for a probe and better than no download."""
|
||||
return {**pot_provider_args(bgutil_http, bgutil_script),
|
||||
"youtube": {"player_client": list(HD_CLIENTS)}}
|
||||
Loading…
Reference in a new issue