From 12d423d739a0751d950da23222b5ce35d1ff0367 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 14 Jul 2026 14:00:02 +0200 Subject: [PATCH] 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. --- .env.cloud.example | 12 ++- app.py | 19 +++- cloud/alerts.py | 72 ++++++++++++++++ cloud/config.py | 30 ++++++- cloud/emails.py | 58 +++++++++---- cloud/metering.py | 43 +++++----- docker-compose.cloud.yml | 7 +- main.py | 181 +++++++++++++++++---------------------- 8 files changed, 269 insertions(+), 153 deletions(-) create mode 100644 cloud/alerts.py diff --git a/.env.cloud.example b/.env.cloud.example index a065a57..ae5c54c 100644 --- a/.env.cloud.example +++ b/.env.cloud.example @@ -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 +# 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 +# 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= diff --git a/app.py b/app.py index 6dcde0e..3a62e1d 100644 --- a/app.py +++ b/app.py @@ -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 diff --git a/cloud/alerts.py b/cloud/alerts.py new file mode 100644 index 0000000..7d40cfb --- /dev/null +++ b/cloud/alerts.py @@ -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"
{body}
" + 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]}", + ) diff --git a/cloud/config.py b/cloud/config.py index fadbcdb..23e6112 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -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 ") + # 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 diff --git a/cloud/emails.py b/cloud/emails.py index 32f8c2f..133944d 100644 --- a/cloud/emails.py +++ b/cloud/emails.py @@ -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"""

Sign in to OpenShorts

@@ -22,15 +55,4 @@ async def send_magic_link_email(email: str, link: str):

If you didn't request this, ignore this email.

""" - 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) diff --git a/cloud/metering.py b/cloud/metering.py index 43e4465..6e71779 100644 --- a/cloud/metering.py +++ b/cloud/metering.py @@ -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() - if proxy: - opts["proxy"] = proxy - 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") - return float(duration) / 60.0 + 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 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})") # --------------------------------------------------------------------------- # diff --git a/docker-compose.cloud.yml b/docker-compose.cloud.yml index 1659913..ff1a4af 100644 --- a/docker-compose.cloud.yml +++ b/docker-compose.cloud.yml @@ -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 } + # 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} diff --git a/main.py b/main.py index b0a1824..17919a4 100644 --- a/main.py +++ b/main.py @@ -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]}} + 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'], + } + } + + # 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: - _extractor_args = { - 'youtube': { - 'player_client': ['tv_embed', 'android', 'mweb', 'web'], - 'player_skip': ['webpage', 'configs'], - } + 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, + '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' + ), + }, } - _COMMON_YDL_OPTS = { - '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, - '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' - ), - }, - } - - 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 - import sys - import traceback - - # Print minimal error first to ensure something gets out - print("🚨 YOUTUBE DOWNLOAD ERROR 🚨", file=sys.stderr) - - error_msg = f""" - + last_err = e + print(f"⚠️ Download attempt '{label}' failed: {str(e)[:200]}") + + if sanitized_title is None: + import sys + 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. +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) + sys.stdout.flush(); sys.stderr.flush() + time.sleep(0.5) + raise 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.stderr) - - # Force flush - sys.stdout.flush() - sys.stderr.flush() - - # Wait a split second to allow buffer to drain before raising - 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]) - 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):