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:
juancarlos.cavero 2026-07-14 14:00:02 +02:00
parent ebe876c497
commit 12d423d739
8 changed files with 269 additions and 153 deletions

View file

@ -13,9 +13,15 @@ JWT_SECRET=generate-a-long-random-string
FRONTEND_URL=https://openshorts.app
ALLOWED_ORIGINS=https://openshorts.app
# Email — magic link (Resend)
RESEND_API_KEY=re_...
EMAIL_FROM=OpenShorts <login@openshorts.app>
# Email — magic link + admin alerts, via SMTP (e.g. Namecheap Private Email).
# Quote the password if it contains $ or * so dotenv keeps it literal.
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_CLIENT_ID=

19
app.py
View file

@ -42,13 +42,14 @@ BILLING_ENABLED = os.environ.get("BILLING_ENABLED", "").lower() in ("1", "true",
if BILLING_ENABLED:
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
else:
cloud = None
managed_keys = None
_metering = None
_cloud_config = None
_alerts = None
async def get_current_user_optional(request: Request):
# 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,
# release otherwise so the minutes go back to the user.
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
concurrency_semaphore.release()
job_queue.task_done()
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):
if not BILLING_ENABLED:
return

72
cloud/alerts.py Normal file
View 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]}",
)

View file

@ -83,14 +83,36 @@ class Settings:
origins = [o.strip() for o in raw.split(",") if o.strip()]
return origins or [self.frontend_url]
# Email (Resend)
# Email (SMTP — e.g. Namecheap Private Email)
@property
def resend_api_key(self) -> str:
return os.environ.get("RESEND_API_KEY", "")
def smtp_host(self) -> str:
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
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
@property

View file

@ -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
log instead of sent, so the login flow is still testable without a real inbox.
If SMTP isn't configured (local dev), messages are printed to the server log so
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
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):
if not settings.resend_api_key:
if not settings.smtp_configured:
print(f"✉️ [DEV magic link] {email} -> {link}")
return
html = f"""
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
<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>
</div>
"""
async with httpx.AsyncClient(timeout=15) as client:
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()
await send_email(email, "Your OpenShorts sign-in link", html)

View file

@ -73,28 +73,29 @@ def probe_url_minutes(url: str) -> float:
"""
import yt_dlp
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()
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:
opts["proxy"] = proxy
try:
with yt_dlp.YoutubeDL(opts) as ydl:
info = ydl.extract_info(url, download=False)
duration = info.get("duration")
if not duration:
raise ValueError("Could not determine video duration")
if duration:
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})")
# --------------------------------------------------------------------------- #

View file

@ -40,9 +40,10 @@ services:
- JWT_SECRET=${JWT_SECRET}
- FRONTEND_URL=${FRONTEND_URL:-https://openshorts.app}
- ALLOWED_ORIGINS=${ALLOWED_ORIGINS:-https://openshorts.app}
# Email (magic link) — Resend
- RESEND_API_KEY=${RESEND_API_KEY}
- EMAIL_FROM=${EMAIL_FROM:-OpenShorts <login@openshorts.app>}
# Email (magic link + admin alerts) is via SMTP and read from the mounted
# .env (SMTP_HOST/PORT/USER/PASSWORD, EMAIL_FROM, ADMIN_EMAIL). It's kept
# out of this list on purpose so the SMTP password's $/* aren't mangled by
# compose/shell variable substitution.
# Google OAuth
- GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID}
- GOOGLE_CLIENT_SECRET=${GOOGLE_CLIENT_SECRET}

147
main.py
View file

@ -481,124 +481,99 @@ def download_youtube_video(url, output_dir="."):
if _proxy:
print("🌐 Using residential proxy for download.")
# YouTube client strategy:
# - Hosted (BGUTIL_BASE_URL set): use yt-dlp's default clients + the bgutil
# PO-token provider → unlocks 720p/1080p (needs the bgutil sidecar + a Deno
# JS runtime + a recent yt-dlp, all baked into the cloud image).
# - Self-host (no bgutil): fall back to the conservative tv_embed/android
# clients that work without a PO-token provider (caps around 360p, but no
# extra infra required).
# Two download strategies, tried in order so a break in the HD path degrades
# gracefully instead of failing the whole job:
# 1) HD — yt-dlp default clients + the bgutil PO-token provider
# (BGUTIL_BASE_URL, needs the sidecar + Deno + recent yt-dlp) → 720p/1080p.
# 2) Fallback — conservative tv_embed/android clients, no PO provider (~360p),
# which is also the ONLY strategy for self-host (no bgutil configured).
_bgutil = os.environ.get("BGUTIL_BASE_URL", "").strip()
if _bgutil:
_extractor_args = {'youtubepot-bgutilhttp': {'base_url': [_bgutil]}}
else:
_extractor_args = {
hd_args = {'youtubepot-bgutilhttp': {'base_url': [_bgutil]}} if _bgutil else None
fallback_args = {
'youtube': {
'player_client': ['tv_embed', 'android', 'mweb', 'web'],
'player_skip': ['webpage', 'configs'],
}
}
_COMMON_YDL_OPTS = {
'quiet': False,
'verbose': True,
'no_warnings': False,
# Cap at 720p when using a paid proxy (bandwidth cost); direct keeps best.
if _proxy:
hd_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:
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,
'proxy': _proxy,
'socket_timeout': 30,
'retries': 10,
'fragment_retries': 10,
'nocheckcertificate': True,
'cachedir': False,
'extractor_args': _extractor_args,
'proxy': _proxy, 'socket_timeout': 30, 'retries': 10, 'fragment_retries': 10,
'nocheckcertificate': True, 'cachedir': False,
'extractor_args': extractor_args,
'http_headers': {
'User-Agent': (
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/120.0.0.0 Safari/537.36'
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
),
},
}
with yt_dlp.YoutubeDL(_COMMON_YDL_OPTS) as ydl:
try:
def _attempt(extractor_args, fmt):
with yt_dlp.YoutubeDL(_base_opts(extractor_args)) as ydl:
info = ydl.extract_info(url, download=False)
video_title = info.get('title', 'youtube_video')
sanitized_title = sanitize_filename(video_title)
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),
'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:
# 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 traceback
# Print minimal error first to ensure something gets out
print("🚨 YOUTUBE DOWNLOAD ERROR 🚨", file=sys.stderr)
error_msg = f"""
❌ ================================================================= ❌
❌ FATAL ERROR: YOUTUBE DOWNLOAD FAILED
❌ FATAL ERROR: YOUTUBE DOWNLOAD FAILED (all strategies)
❌ ================================================================= ❌
REASON: YouTube has blocked the download request (Error 429/Unavailable).
This is likely a temporary IP ban on this server.
👇 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
REASON: YouTube blocked the request or the download tooling is out of date.
👇 SOLUTION FOR USER: download the video manually and use the 'Upload Video' tab.
Technical Details: {str(last_err)}
"""
print(error_msg, file=sys.stdout)
print(error_msg, file=sys.stderr)
# Force flush
sys.stdout.flush()
sys.stderr.flush()
# Wait a split second to allow buffer to drain before raising
sys.stdout.flush(); sys.stderr.flush()
time.sleep(0.5)
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])
raise last_err
downloaded_file = os.path.join(output_dir, f'{sanitized_title}.mp4')
if not os.path.exists(downloaded_file):
for f in os.listdir(output_dir):
if f.startswith(sanitized_title) and f.endswith('.mp4'):
downloaded_file = os.path.join(output_dir, f)
break
step_end_time = time.time()
print(f"✅ Video downloaded in {step_end_time - step_start_time:.2f}s: {downloaded_file}")
print(f"✅ Video downloaded in {time.time() - step_start_time:.2f}s: {downloaded_file}")
return downloaded_file, sanitized_title
def process_video_to_vertical(input_video, final_output_video):