feat: 720p->360p download fallback + SMTP email alerts
- main.py / metering.py: try the HD (bgutil/720p) strategy first, fall back to the conservative (360p) clients on any failure, so a YouTube/yt-dlp change degrades gracefully instead of failing the whole job. - cloud/alerts.py: in-memory tracking of managed-job outcomes; emails the admin (ADMIN_EMAIL) when a proxy/credit error appears or when many jobs fail in a row, with a 1h per-alert cooldown. Wired into run_job_wrapper. - Email switched from Resend to SMTP (cloud/emails.py) for magic link + alerts (Namecheap Private Email). Config via SMTP_* / EMAIL_FROM / ADMIN_EMAIL in the mounted .env (kept out of compose so the password's $/* aren't mangled). SMTP send verified from host and from the backend container.
This commit is contained in:
parent
ebe876c497
commit
12d423d739
8 changed files with 269 additions and 153 deletions
|
|
@ -13,9 +13,15 @@ JWT_SECRET=generate-a-long-random-string
|
||||||
FRONTEND_URL=https://openshorts.app
|
FRONTEND_URL=https://openshorts.app
|
||||||
ALLOWED_ORIGINS=https://openshorts.app
|
ALLOWED_ORIGINS=https://openshorts.app
|
||||||
|
|
||||||
# Email — magic link (Resend)
|
# Email — magic link + admin alerts, via SMTP (e.g. Namecheap Private Email).
|
||||||
RESEND_API_KEY=re_...
|
# Quote the password if it contains $ or * so dotenv keeps it literal.
|
||||||
EMAIL_FROM=OpenShorts <login@openshorts.app>
|
SMTP_HOST=mail.privateemail.com
|
||||||
|
SMTP_PORT=465
|
||||||
|
SMTP_USER=info@yourdomain.com
|
||||||
|
SMTP_PASSWORD='your-mailbox-password'
|
||||||
|
EMAIL_FROM=OpenShorts <info@yourdomain.com>
|
||||||
|
# Operational alerts (proxy out of credits / high failure rate) are emailed here.
|
||||||
|
ADMIN_EMAIL=you@example.com
|
||||||
|
|
||||||
# Google OAuth (optional; magic link works without it)
|
# Google OAuth (optional; magic link works without it)
|
||||||
GOOGLE_CLIENT_ID=
|
GOOGLE_CLIENT_ID=
|
||||||
|
|
|
||||||
19
app.py
19
app.py
|
|
@ -42,13 +42,14 @@ BILLING_ENABLED = os.environ.get("BILLING_ENABLED", "").lower() in ("1", "true",
|
||||||
|
|
||||||
if BILLING_ENABLED:
|
if BILLING_ENABLED:
|
||||||
import cloud
|
import cloud
|
||||||
from cloud import managed_keys, metering as _metering, config as _cloud_config
|
from cloud import managed_keys, metering as _metering, config as _cloud_config, alerts as _alerts
|
||||||
from cloud.auth import get_current_user_optional
|
from cloud.auth import get_current_user_optional
|
||||||
else:
|
else:
|
||||||
cloud = None
|
cloud = None
|
||||||
managed_keys = None
|
managed_keys = None
|
||||||
_metering = None
|
_metering = None
|
||||||
_cloud_config = None
|
_cloud_config = None
|
||||||
|
_alerts = None
|
||||||
|
|
||||||
async def get_current_user_optional(request: Request):
|
async def get_current_user_optional(request: Request):
|
||||||
# No-op dependency in self-host mode: every request is anonymous / BYOK.
|
# No-op dependency in self-host mode: every request is anonymous / BYOK.
|
||||||
|
|
@ -313,12 +314,28 @@ async def run_job_wrapper(job_id):
|
||||||
# Settle the minute reservation (managed jobs only): commit on success,
|
# Settle the minute reservation (managed jobs only): commit on success,
|
||||||
# release otherwise so the minutes go back to the user.
|
# release otherwise so the minutes go back to the user.
|
||||||
await _settle_reservation(job_id)
|
await _settle_reservation(job_id)
|
||||||
|
# Operational alerting for managed jobs (proxy out of credits / failures).
|
||||||
|
await _record_job_alert(job_id)
|
||||||
# Always release semaphore and mark queue task done
|
# Always release semaphore and mark queue task done
|
||||||
concurrency_semaphore.release()
|
concurrency_semaphore.release()
|
||||||
job_queue.task_done()
|
job_queue.task_done()
|
||||||
print(f"✅ Released slot for job: {job_id}")
|
print(f"✅ Released slot for job: {job_id}")
|
||||||
|
|
||||||
|
|
||||||
|
async def _record_job_alert(job_id):
|
||||||
|
if not BILLING_ENABLED:
|
||||||
|
return
|
||||||
|
job = jobs.get(job_id) or {}
|
||||||
|
if not job.get('user_id'):
|
||||||
|
return # only track managed jobs
|
||||||
|
ok = job.get('status') == 'completed'
|
||||||
|
err = "" if ok else " ".join(job.get('logs', [])[-10:])
|
||||||
|
try:
|
||||||
|
await _alerts.record_job_outcome(ok, err)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"⚠️ Alert recording error for {job_id}: {e}")
|
||||||
|
|
||||||
|
|
||||||
async def _settle_reservation(job_id):
|
async def _settle_reservation(job_id):
|
||||||
if not BILLING_ENABLED:
|
if not BILLING_ENABLED:
|
||||||
return
|
return
|
||||||
|
|
|
||||||
72
cloud/alerts.py
Normal file
72
cloud/alerts.py
Normal file
|
|
@ -0,0 +1,72 @@
|
||||||
|
"""Operational email alerts for the admin (proxy out of credits, high failure rate).
|
||||||
|
|
||||||
|
Tracks recent managed-job outcomes in memory and emails ADMIN_EMAIL (via Resend)
|
||||||
|
when something looks broken, with a per-alert cooldown so it never spams.
|
||||||
|
"""
|
||||||
|
import time
|
||||||
|
from collections import deque
|
||||||
|
|
||||||
|
from .config import settings
|
||||||
|
from .emails import send_email
|
||||||
|
|
||||||
|
_recent = deque(maxlen=12) # rolling window of recent job outcomes (ok bool)
|
||||||
|
_last_alert = {} # alert kind -> last-sent epoch
|
||||||
|
_ALERT_COOLDOWN = 3600 # 1 hour between repeats of the same alert
|
||||||
|
_FAIL_WINDOW_MIN = 6 # need at least this many recent jobs to judge a rate
|
||||||
|
_FAIL_THRESHOLD = 5 # ...and this many failures among them
|
||||||
|
|
||||||
|
# Substrings that suggest the proxy itself failed (auth / balance / tunnel).
|
||||||
|
_PROXY_HINTS = ("proxy", "407", "proxyauthentication", "tunnel connection",
|
||||||
|
"credit", "balance", "insufficient", "payment required")
|
||||||
|
|
||||||
|
|
||||||
|
def _looks_like_proxy_error(err: str) -> bool:
|
||||||
|
e = (err or "").lower()
|
||||||
|
return any(k in e for k in _PROXY_HINTS)
|
||||||
|
|
||||||
|
|
||||||
|
def _cooldown_ok(kind: str) -> bool:
|
||||||
|
now = time.time()
|
||||||
|
if now - _last_alert.get(kind, 0) < _ALERT_COOLDOWN:
|
||||||
|
return False
|
||||||
|
_last_alert[kind] = now
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def send_admin_alert(subject: str, body: str):
|
||||||
|
to = settings.admin_email
|
||||||
|
if not to or not settings.smtp_configured:
|
||||||
|
print(f"⚠️ [ADMIN ALERT] {subject}\n{body[:500]}"
|
||||||
|
+ ("" if to else " (set ADMIN_EMAIL + SMTP_* to email these)"))
|
||||||
|
return
|
||||||
|
html = f"<pre style='font:13px/1.5 monospace;white-space:pre-wrap'>{body}</pre>"
|
||||||
|
await send_email(to, f"[OpenShorts] {subject}", html)
|
||||||
|
|
||||||
|
|
||||||
|
async def record_job_outcome(ok: bool, error_text: str = ""):
|
||||||
|
"""Record a managed job's result and fire an alert if the picture looks bad."""
|
||||||
|
_recent.append(bool(ok))
|
||||||
|
if ok:
|
||||||
|
return
|
||||||
|
|
||||||
|
# 1) Proxy / credits problem — most urgent, alert immediately.
|
||||||
|
if _looks_like_proxy_error(error_text) and _cooldown_ok("proxy"):
|
||||||
|
await send_admin_alert(
|
||||||
|
"⚠️ Proxy error — DataImpulse may be out of credits",
|
||||||
|
"A managed job failed with a proxy-related error. Check your residential "
|
||||||
|
"proxy balance (DataImpulse) — downloads will keep failing until it's topped up.\n\n"
|
||||||
|
f"Error:\n{error_text[:1200]}",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
# 2) High failure rate — the YouTube download path may be broken (arms race).
|
||||||
|
recent = list(_recent)
|
||||||
|
fails = recent.count(False)
|
||||||
|
if len(recent) >= _FAIL_WINDOW_MIN and fails >= _FAIL_THRESHOLD and _cooldown_ok("failrate"):
|
||||||
|
await send_admin_alert(
|
||||||
|
"⚠️ High download failure rate",
|
||||||
|
f"{fails} of the last {len(recent)} managed jobs failed. The YouTube "
|
||||||
|
"download path may be broken (yt-dlp / PO-token change). A backend image "
|
||||||
|
"rebuild usually pulls the yt-dlp fix.\n\n"
|
||||||
|
f"Last error:\n{error_text[:1200]}",
|
||||||
|
)
|
||||||
|
|
@ -83,14 +83,36 @@ class Settings:
|
||||||
origins = [o.strip() for o in raw.split(",") if o.strip()]
|
origins = [o.strip() for o in raw.split(",") if o.strip()]
|
||||||
return origins or [self.frontend_url]
|
return origins or [self.frontend_url]
|
||||||
|
|
||||||
# Email (Resend)
|
# Email (SMTP — e.g. Namecheap Private Email)
|
||||||
@property
|
@property
|
||||||
def resend_api_key(self) -> str:
|
def smtp_host(self) -> str:
|
||||||
return os.environ.get("RESEND_API_KEY", "")
|
return os.environ.get("SMTP_HOST", "mail.privateemail.com")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def smtp_port(self) -> int:
|
||||||
|
return int(os.environ.get("SMTP_PORT", "465"))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def smtp_user(self) -> str:
|
||||||
|
return os.environ.get("SMTP_USER", "")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def smtp_password(self) -> str:
|
||||||
|
return os.environ.get("SMTP_PASSWORD", "")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def smtp_configured(self) -> bool:
|
||||||
|
return bool(self.smtp_user and self.smtp_password)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def email_from(self) -> str:
|
def email_from(self) -> str:
|
||||||
return os.environ.get("EMAIL_FROM", "OpenShorts <login@openshorts.app>")
|
# Namecheap requires the From to be the authenticated mailbox.
|
||||||
|
return os.environ.get("EMAIL_FROM") or (f"OpenShorts <{self.smtp_user}>" if self.smtp_user else "OpenShorts")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def admin_email(self) -> str:
|
||||||
|
# Where operational alerts (proxy out of credits, high failure rate) go.
|
||||||
|
return os.environ.get("ADMIN_EMAIL", "")
|
||||||
|
|
||||||
# Google OAuth
|
# Google OAuth
|
||||||
@property
|
@property
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,51 @@
|
||||||
"""Transactional email via Resend (magic-link login).
|
"""Transactional + operational email via SMTP (e.g. Namecheap Private Email).
|
||||||
|
|
||||||
If RESEND_API_KEY is unset (e.g. local dev), the link is printed to the server
|
If SMTP isn't configured (local dev), messages are printed to the server log so
|
||||||
log instead of sent, so the login flow is still testable without a real inbox.
|
the magic-link flow and alerts still work without a real mailbox.
|
||||||
"""
|
"""
|
||||||
import httpx
|
import asyncio
|
||||||
|
import smtplib
|
||||||
|
import ssl
|
||||||
|
from email.message import EmailMessage
|
||||||
|
|
||||||
from .config import settings
|
from .config import settings
|
||||||
|
|
||||||
|
|
||||||
|
def _send_sync(to: str, subject: str, html: str):
|
||||||
|
msg = EmailMessage()
|
||||||
|
msg["From"] = settings.email_from
|
||||||
|
msg["To"] = to
|
||||||
|
msg["Subject"] = subject
|
||||||
|
msg.set_content("This message requires an HTML-capable email client.")
|
||||||
|
msg.add_alternative(html, subtype="html")
|
||||||
|
|
||||||
|
if settings.smtp_port == 465:
|
||||||
|
with smtplib.SMTP_SSL(settings.smtp_host, settings.smtp_port,
|
||||||
|
context=ssl.create_default_context(), timeout=20) as s:
|
||||||
|
s.login(settings.smtp_user, settings.smtp_password)
|
||||||
|
s.send_message(msg)
|
||||||
|
else:
|
||||||
|
with smtplib.SMTP(settings.smtp_host, settings.smtp_port, timeout=20) as s:
|
||||||
|
s.starttls(context=ssl.create_default_context())
|
||||||
|
s.login(settings.smtp_user, settings.smtp_password)
|
||||||
|
s.send_message(msg)
|
||||||
|
|
||||||
|
|
||||||
|
async def send_email(to: str, subject: str, html: str):
|
||||||
|
"""Send an email (async wrapper). Logs instead of sending if SMTP is unset."""
|
||||||
|
if not settings.smtp_configured:
|
||||||
|
print(f"✉️ [DEV email → {to}] {subject}")
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
await asyncio.to_thread(_send_sync, to, subject, html)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"⚠️ Failed to send email to {to}: {e}")
|
||||||
|
|
||||||
|
|
||||||
async def send_magic_link_email(email: str, link: str):
|
async def send_magic_link_email(email: str, link: str):
|
||||||
if not settings.resend_api_key:
|
if not settings.smtp_configured:
|
||||||
print(f"✉️ [DEV magic link] {email} -> {link}")
|
print(f"✉️ [DEV magic link] {email} -> {link}")
|
||||||
return
|
return
|
||||||
|
|
||||||
html = f"""
|
html = f"""
|
||||||
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
|
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
|
||||||
<h2>Sign in to OpenShorts</h2>
|
<h2>Sign in to OpenShorts</h2>
|
||||||
|
|
@ -22,15 +55,4 @@ async def send_magic_link_email(email: str, link: str):
|
||||||
<p style="color:#666;font-size:13px">If you didn't request this, ignore this email.</p>
|
<p style="color:#666;font-size:13px">If you didn't request this, ignore this email.</p>
|
||||||
</div>
|
</div>
|
||||||
"""
|
"""
|
||||||
async with httpx.AsyncClient(timeout=15) as client:
|
await send_email(email, "Your OpenShorts sign-in link", html)
|
||||||
resp = await client.post(
|
|
||||||
"https://api.resend.com/emails",
|
|
||||||
headers={"Authorization": f"Bearer {settings.resend_api_key}"},
|
|
||||||
json={
|
|
||||||
"from": settings.email_from,
|
|
||||||
"to": [email],
|
|
||||||
"subject": "Your OpenShorts sign-in link",
|
|
||||||
"html": html,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
resp.raise_for_status()
|
|
||||||
|
|
|
||||||
|
|
@ -73,28 +73,29 @@ def probe_url_minutes(url: str) -> float:
|
||||||
"""
|
"""
|
||||||
import yt_dlp
|
import yt_dlp
|
||||||
bgutil = os.environ.get("BGUTIL_BASE_URL", "").strip()
|
bgutil = os.environ.get("BGUTIL_BASE_URL", "").strip()
|
||||||
if bgutil:
|
|
||||||
extractor_args = {"youtubepot-bgutilhttp": {"base_url": [bgutil]}}
|
|
||||||
else:
|
|
||||||
extractor_args = {
|
|
||||||
"youtube": {
|
|
||||||
"player_client": ["tv_embed", "android", "mweb", "web"],
|
|
||||||
"player_skip": ["webpage", "configs"],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
opts = {
|
|
||||||
"skip_download": True, "quiet": True, "no_warnings": True,
|
|
||||||
"extractor_args": extractor_args,
|
|
||||||
}
|
|
||||||
proxy = os.environ.get("PROXY_URL", "").strip()
|
proxy = os.environ.get("PROXY_URL", "").strip()
|
||||||
|
conservative = {"youtube": {"player_client": ["tv_embed", "android", "mweb", "web"],
|
||||||
|
"player_skip": ["webpage", "configs"]}}
|
||||||
|
# Try the bgutil/HD extractor first, then the conservative one — mirrors the
|
||||||
|
# download's HD→fallback logic so the probe never fails alone.
|
||||||
|
strategies = ([{"youtubepot-bgutilhttp": {"base_url": [bgutil]}}] if bgutil else []) + [conservative]
|
||||||
|
|
||||||
|
last_err = None
|
||||||
|
for extractor_args in strategies:
|
||||||
|
opts = {"skip_download": True, "quiet": True, "no_warnings": True,
|
||||||
|
"extractor_args": extractor_args}
|
||||||
if proxy:
|
if proxy:
|
||||||
opts["proxy"] = proxy
|
opts["proxy"] = proxy
|
||||||
|
try:
|
||||||
with yt_dlp.YoutubeDL(opts) as ydl:
|
with yt_dlp.YoutubeDL(opts) as ydl:
|
||||||
info = ydl.extract_info(url, download=False)
|
info = ydl.extract_info(url, download=False)
|
||||||
duration = info.get("duration")
|
duration = info.get("duration")
|
||||||
if not duration:
|
if duration:
|
||||||
raise ValueError("Could not determine video duration")
|
|
||||||
return float(duration) / 60.0
|
return float(duration) / 60.0
|
||||||
|
last_err = ValueError("no duration in metadata")
|
||||||
|
except Exception as e:
|
||||||
|
last_err = e
|
||||||
|
raise ValueError(f"Could not determine video duration ({last_err})")
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- #
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
|
||||||
|
|
@ -40,9 +40,10 @@ services:
|
||||||
- JWT_SECRET=${JWT_SECRET}
|
- JWT_SECRET=${JWT_SECRET}
|
||||||
- FRONTEND_URL=${FRONTEND_URL:-https://openshorts.app}
|
- FRONTEND_URL=${FRONTEND_URL:-https://openshorts.app}
|
||||||
- ALLOWED_ORIGINS=${ALLOWED_ORIGINS:-https://openshorts.app}
|
- ALLOWED_ORIGINS=${ALLOWED_ORIGINS:-https://openshorts.app}
|
||||||
# Email (magic link) — Resend
|
# Email (magic link + admin alerts) is via SMTP and read from the mounted
|
||||||
- RESEND_API_KEY=${RESEND_API_KEY}
|
# .env (SMTP_HOST/PORT/USER/PASSWORD, EMAIL_FROM, ADMIN_EMAIL). It's kept
|
||||||
- EMAIL_FROM=${EMAIL_FROM:-OpenShorts <login@openshorts.app>}
|
# out of this list on purpose so the SMTP password's $/* aren't mangled by
|
||||||
|
# compose/shell variable substitution.
|
||||||
# Google OAuth
|
# Google OAuth
|
||||||
- GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID}
|
- GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID}
|
||||||
- GOOGLE_CLIENT_SECRET=${GOOGLE_CLIENT_SECRET}
|
- GOOGLE_CLIENT_SECRET=${GOOGLE_CLIENT_SECRET}
|
||||||
|
|
|
||||||
145
main.py
145
main.py
|
|
@ -481,124 +481,99 @@ def download_youtube_video(url, output_dir="."):
|
||||||
if _proxy:
|
if _proxy:
|
||||||
print("🌐 Using residential proxy for download.")
|
print("🌐 Using residential proxy for download.")
|
||||||
|
|
||||||
# YouTube client strategy:
|
# Two download strategies, tried in order so a break in the HD path degrades
|
||||||
# - Hosted (BGUTIL_BASE_URL set): use yt-dlp's default clients + the bgutil
|
# gracefully instead of failing the whole job:
|
||||||
# PO-token provider → unlocks 720p/1080p (needs the bgutil sidecar + a Deno
|
# 1) HD — yt-dlp default clients + the bgutil PO-token provider
|
||||||
# JS runtime + a recent yt-dlp, all baked into the cloud image).
|
# (BGUTIL_BASE_URL, needs the sidecar + Deno + recent yt-dlp) → 720p/1080p.
|
||||||
# - Self-host (no bgutil): fall back to the conservative tv_embed/android
|
# 2) Fallback — conservative tv_embed/android clients, no PO provider (~360p),
|
||||||
# clients that work without a PO-token provider (caps around 360p, but no
|
# which is also the ONLY strategy for self-host (no bgutil configured).
|
||||||
# extra infra required).
|
|
||||||
_bgutil = os.environ.get("BGUTIL_BASE_URL", "").strip()
|
_bgutil = os.environ.get("BGUTIL_BASE_URL", "").strip()
|
||||||
if _bgutil:
|
hd_args = {'youtubepot-bgutilhttp': {'base_url': [_bgutil]}} if _bgutil else None
|
||||||
_extractor_args = {'youtubepot-bgutilhttp': {'base_url': [_bgutil]}}
|
fallback_args = {
|
||||||
else:
|
|
||||||
_extractor_args = {
|
|
||||||
'youtube': {
|
'youtube': {
|
||||||
'player_client': ['tv_embed', 'android', 'mweb', 'web'],
|
'player_client': ['tv_embed', 'android', 'mweb', 'web'],
|
||||||
'player_skip': ['webpage', 'configs'],
|
'player_skip': ['webpage', 'configs'],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_COMMON_YDL_OPTS = {
|
# Cap at 720p when using a paid proxy (bandwidth cost); direct keeps best.
|
||||||
'quiet': False,
|
if _proxy:
|
||||||
'verbose': True,
|
hd_fmt = ('bestvideo[vcodec^=avc1][height<=720][ext=mp4]+bestaudio[ext=m4a]/'
|
||||||
'no_warnings': False,
|
'bestvideo[vcodec^=avc1][height<=720]+bestaudio/best[height<=720][ext=mp4]/best[height<=720]/best')
|
||||||
|
else:
|
||||||
|
hd_fmt = 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best'
|
||||||
|
fallback_fmt = 'best[ext=mp4]/best'
|
||||||
|
|
||||||
|
def _base_opts(extractor_args):
|
||||||
|
return {
|
||||||
|
'quiet': False, 'verbose': True, 'no_warnings': False,
|
||||||
'cookiefile': cookies_path if cookies_path else None,
|
'cookiefile': cookies_path if cookies_path else None,
|
||||||
'proxy': _proxy,
|
'proxy': _proxy, 'socket_timeout': 30, 'retries': 10, 'fragment_retries': 10,
|
||||||
'socket_timeout': 30,
|
'nocheckcertificate': True, 'cachedir': False,
|
||||||
'retries': 10,
|
'extractor_args': extractor_args,
|
||||||
'fragment_retries': 10,
|
|
||||||
'nocheckcertificate': True,
|
|
||||||
'cachedir': False,
|
|
||||||
'extractor_args': _extractor_args,
|
|
||||||
'http_headers': {
|
'http_headers': {
|
||||||
'User-Agent': (
|
'User-Agent': (
|
||||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
|
||||||
'AppleWebKit/537.36 (KHTML, like Gecko) '
|
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
|
||||||
'Chrome/120.0.0.0 Safari/537.36'
|
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
with yt_dlp.YoutubeDL(_COMMON_YDL_OPTS) as ydl:
|
def _attempt(extractor_args, fmt):
|
||||||
try:
|
with yt_dlp.YoutubeDL(_base_opts(extractor_args)) as ydl:
|
||||||
info = ydl.extract_info(url, download=False)
|
info = ydl.extract_info(url, download=False)
|
||||||
video_title = info.get('title', 'youtube_video')
|
sanitized = sanitize_filename(info.get('title', 'youtube_video'))
|
||||||
sanitized_title = sanitize_filename(video_title)
|
expected = os.path.join(output_dir, f'{sanitized}.mp4')
|
||||||
|
if os.path.exists(expected):
|
||||||
|
os.remove(expected)
|
||||||
|
dl_opts = {
|
||||||
|
**_base_opts(extractor_args),
|
||||||
|
'format': fmt,
|
||||||
|
'outtmpl': os.path.join(output_dir, f'{sanitized}.%(ext)s'),
|
||||||
|
'merge_output_format': 'mp4', 'overwrites': True,
|
||||||
|
}
|
||||||
|
with yt_dlp.YoutubeDL(dl_opts) as ydl:
|
||||||
|
ydl.download([url])
|
||||||
|
return sanitized
|
||||||
|
|
||||||
|
attempts = ([('HD', hd_args, hd_fmt)] if hd_args else []) + [('fallback', fallback_args, fallback_fmt)]
|
||||||
|
|
||||||
|
sanitized_title = None
|
||||||
|
last_err = None
|
||||||
|
for label, ea, fmt in attempts:
|
||||||
|
try:
|
||||||
|
print(f"📥 Download attempt: {label}")
|
||||||
|
sanitized_title = _attempt(ea, fmt)
|
||||||
|
print(f"✅ Download succeeded ({label}).")
|
||||||
|
break
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Force print to stderr/stdout immediately so it's captured before crash
|
last_err = e
|
||||||
|
print(f"⚠️ Download attempt '{label}' failed: {str(e)[:200]}")
|
||||||
|
|
||||||
|
if sanitized_title is None:
|
||||||
import sys
|
import sys
|
||||||
import traceback
|
|
||||||
|
|
||||||
# Print minimal error first to ensure something gets out
|
|
||||||
print("🚨 YOUTUBE DOWNLOAD ERROR 🚨", file=sys.stderr)
|
|
||||||
|
|
||||||
error_msg = f"""
|
error_msg = f"""
|
||||||
|
|
||||||
❌ ================================================================= ❌
|
❌ ================================================================= ❌
|
||||||
❌ FATAL ERROR: YOUTUBE DOWNLOAD FAILED
|
❌ FATAL ERROR: YOUTUBE DOWNLOAD FAILED (all strategies)
|
||||||
❌ ================================================================= ❌
|
❌ ================================================================= ❌
|
||||||
|
REASON: YouTube blocked the request or the download tooling is out of date.
|
||||||
REASON: YouTube has blocked the download request (Error 429/Unavailable).
|
👇 SOLUTION FOR USER: download the video manually and use the 'Upload Video' tab.
|
||||||
This is likely a temporary IP ban on this server.
|
Technical Details: {str(last_err)}
|
||||||
|
|
||||||
👇 SOLUTION FOR USER 👇
|
|
||||||
---------------------------------------------------------------------
|
|
||||||
1. Download the video manually to your computer.
|
|
||||||
2. Use the 'Upload Video' tab in this app to process it.
|
|
||||||
---------------------------------------------------------------------
|
|
||||||
|
|
||||||
Technical Details: {str(e)}
|
|
||||||
"""
|
"""
|
||||||
# Print to both streams to ensure capture
|
|
||||||
print(error_msg, file=sys.stdout)
|
print(error_msg, file=sys.stdout)
|
||||||
print(error_msg, file=sys.stderr)
|
print(error_msg, file=sys.stderr)
|
||||||
|
sys.stdout.flush(); sys.stderr.flush()
|
||||||
# Force flush
|
|
||||||
sys.stdout.flush()
|
|
||||||
sys.stderr.flush()
|
|
||||||
|
|
||||||
# Wait a split second to allow buffer to drain before raising
|
|
||||||
time.sleep(0.5)
|
time.sleep(0.5)
|
||||||
|
raise last_err
|
||||||
raise e
|
|
||||||
|
|
||||||
output_template = os.path.join(output_dir, f'{sanitized_title}.%(ext)s')
|
|
||||||
expected_file = os.path.join(output_dir, f'{sanitized_title}.mp4')
|
|
||||||
if os.path.exists(expected_file):
|
|
||||||
os.remove(expected_file)
|
|
||||||
print(f"🗑️ Removed existing file to re-download with H.264 codec")
|
|
||||||
|
|
||||||
# When downloading through a paid proxy, cap at 720p to control bandwidth
|
|
||||||
# cost (a 720p source is plenty for 9:16 clips). Direct downloads keep best.
|
|
||||||
if _proxy:
|
|
||||||
_fmt = ('bestvideo[vcodec^=avc1][height<=720][ext=mp4]+bestaudio[ext=m4a]/'
|
|
||||||
'bestvideo[vcodec^=avc1][height<=720]+bestaudio/best[height<=720][ext=mp4]/best[height<=720]/best')
|
|
||||||
else:
|
|
||||||
_fmt = 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best'
|
|
||||||
|
|
||||||
ydl_opts = {
|
|
||||||
**_COMMON_YDL_OPTS,
|
|
||||||
'format': _fmt,
|
|
||||||
'outtmpl': output_template,
|
|
||||||
'merge_output_format': 'mp4',
|
|
||||||
'overwrites': True,
|
|
||||||
}
|
|
||||||
|
|
||||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
|
||||||
ydl.download([url])
|
|
||||||
|
|
||||||
downloaded_file = os.path.join(output_dir, f'{sanitized_title}.mp4')
|
downloaded_file = os.path.join(output_dir, f'{sanitized_title}.mp4')
|
||||||
|
|
||||||
if not os.path.exists(downloaded_file):
|
if not os.path.exists(downloaded_file):
|
||||||
for f in os.listdir(output_dir):
|
for f in os.listdir(output_dir):
|
||||||
if f.startswith(sanitized_title) and f.endswith('.mp4'):
|
if f.startswith(sanitized_title) and f.endswith('.mp4'):
|
||||||
downloaded_file = os.path.join(output_dir, f)
|
downloaded_file = os.path.join(output_dir, f)
|
||||||
break
|
break
|
||||||
|
|
||||||
step_end_time = time.time()
|
print(f"✅ Video downloaded in {time.time() - step_start_time:.2f}s: {downloaded_file}")
|
||||||
print(f"✅ Video downloaded in {step_end_time - step_start_time:.2f}s: {downloaded_file}")
|
|
||||||
|
|
||||||
return downloaded_file, sanitized_title
|
return downloaded_file, sanitized_title
|
||||||
|
|
||||||
def process_video_to_vertical(input_video, final_output_video):
|
def process_video_to_vertical(input_video, final_output_video):
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue