From 9fd1cacb0c90171f3dc9b41f32ab9678fb7edf88 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Mon, 20 Jul 2026 00:26:21 +0200 Subject: [PATCH] =?UTF-8?q?feat(billing):=20free=20plan=20(20=20min/mes=20?= =?UTF-8?q?sin=20tarjeta)=20+=20retirar=20trial=20+=20opt-in=20galer=C3=AD?= =?UTF-8?q?a=20UGC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Plan free resuelto en metering (sin fila Stripe): 20 min/mes para cuentas Google, período sintético de mes natural con reset automático - TRIAL_DAYS=0 para nuevos checkouts; trials en curso grandfathered - Watermark drawtext en clips free (pasada única post-render, sobrevive subtítulos/hooks); thumbnails IA solo de pago - Anti-abuso: 3 jobs/día por cuenta, 5 por IP, rate-limit de probes, contador mensual de GB de proxy con alerta Telegram a 100 GB - Clips free caducan a 7 días (purge_free_expired); purge_expired respeta a cancelados que ahora son free - Galería UGC pública pasa a opt-in (share_to_gallery, antes publicaba producto+guion de todos los usuarios sin permiso) - Emails: clips listos (con star-ask) y sin-minutos (cooldown 24h) - Frontend: card Free en pricing, copy sin trial (landing/legal/gates), StarBanner en resultados y TopUpModal, upsell de watermark --- app.py | 236 +++++++++++++++++--- cloud/auth.py | 8 +- cloud/billing.py | 15 +- cloud/config.py | 34 ++- cloud/emails.py | 38 ++++ cloud/metering.py | 87 ++++++-- cloud/videos.py | 58 ++++- dashboard/src/App.jsx | 15 ++ dashboard/src/Landing.jsx | 14 +- dashboard/src/Legal.jsx | 31 +-- dashboard/src/components/AccountPage.jsx | 12 +- dashboard/src/components/AdvancedBanner.jsx | 2 +- dashboard/src/components/PricingPage.jsx | 12 +- dashboard/src/components/PricingSection.jsx | 34 ++- dashboard/src/components/ProfileMenu.jsx | 2 +- dashboard/src/components/SaaShortsTab.jsx | 23 ++ dashboard/src/components/StarBanner.jsx | 19 ++ dashboard/src/components/TopUpModal.jsx | 4 + dashboard/src/components/TrialGate.jsx | 11 +- dashboard/src/contexts/AuthContext.jsx | 5 +- main.py | 48 ++++ tests/test_metering_free_plan.py | 53 +++++ 22 files changed, 651 insertions(+), 110 deletions(-) create mode 100644 dashboard/src/components/StarBanner.jsx create mode 100644 tests/test_metering_free_plan.py diff --git a/app.py b/app.py index 7aff4c9..ecce018 100644 --- a/app.py +++ b/app.py @@ -12,6 +12,7 @@ import zipfile import math import itertools import asyncio +from datetime import datetime, timezone from dotenv import load_dotenv from typing import Dict, Optional, List from contextlib import asynccontextmanager @@ -123,8 +124,61 @@ def gemini_missing_error(): return HTTPException(status_code=400, detail="Missing X-Gemini-Key header") +def _client_ip(request) -> str: + """Client IP, honoring the proxy's X-Forwarded-For (Traefik in prod).""" + fwd = request.headers.get("x-forwarded-for") + if fwd: + return fwd.split(",")[0].strip() + return request.client.host if request.client else "unknown" + + +# In-memory abuse counters. Reset on restart by design — the hard monthly +# quota lives in the metering ledger; these only flatten bursts and casual +# multi-accounting, so losing them on a deploy is fine. +_daily_counters = {"date": None, "users": {}, "ips": {}} +_probe_times: dict = {} # user_id -> [monotonic timestamps] +PROBES_PER_HOUR = 15 + +# Out-of-minutes upsell email: at most one per user per day (a client may +# retry the same 402 many times). +_last_quota_email: dict = {} +_QUOTA_EMAIL_COOLDOWN = 24 * 3600 + + +def _maybe_send_quota_email(user): + if user is None or user.plan != "free" or not user.email: + return + now = time.monotonic() + last = _last_quota_email.get(str(user.id)) + if last is not None and now - last < _QUOTA_EMAIL_COOLDOWN: + return + _last_quota_email[str(user.id)] = now + from cloud.emails import send_out_of_minutes_email + upgrade_url = f"{_cloud_config.settings.frontend_url}/#/pricing" + asyncio.create_task(send_out_of_minutes_email(user.email, upgrade_url)) + + +def _daily_bucket(kind: str) -> dict: + today = datetime.now(timezone.utc).strftime("%Y-%m-%d") + if _daily_counters["date"] != today: + _daily_counters.update(date=today, users={}, ips={}) + return _daily_counters[kind] + + +def _check_probe_rate(user_id): + now = time.monotonic() + times = _probe_times.setdefault(str(user_id), []) + times[:] = [t for t in times if now - t < 3600] + if len(times) >= PROBES_PER_HOUR: + raise HTTPException(status_code=429, + detail="Too many requests this hour. Please slow down.") + times.append(now) + + async def reserve_process_minutes(request, url, input_path, job_id): - """Meter a managed /api/process request. Returns (user_id, priority, reservation_id). + """Meter a managed /api/process request. + + Returns (user_id, priority, reservation_id, plan). BYOK / self-host requests don't consume minutes (priority 2, no reservation). For a managed (entitled, no BYOK header) request this probes the input @@ -137,10 +191,10 @@ async def reserve_process_minutes(request, url, input_path, job_id): on the operator's key for free. Only skip metering when billing is off. """ if not BILLING_ENABLED: - return None, 2, None + return None, 2, None, None user = await _user_from_request(request) if not managed_keys.has_active_entitlement(user): - return None, 2, None # shouldn't happen (resolve_gemini would have 402'd) + return None, 2, None, None # shouldn't happen (resolve_gemini would have 402'd) priority = _cloud_config.PLAN_PRIORITY.get(user.plan, 1) @@ -152,6 +206,25 @@ async def reserve_process_minutes(request, url, input_path, job_id): raise HTTPException(status_code=429, detail="You already have the maximum number of jobs running. Please wait.") + # Free-plan daily burst caps, checked BEFORE the probe so URL spam never + # reaches the proxy. Per-account and per-IP (multi-account abuse). + if user.plan == "free": + user_counts = _daily_bucket("users") + if user_counts.get(str(user.id), 0) >= _cloud_config.FREE_DAILY_JOBS: + raise HTTPException(status_code=429, detail={ + "error": "daily_limit", + "message": "Free plan daily limit reached. Come back tomorrow or upgrade for more.", + }) + ip_counts = _daily_bucket("ips") + if ip_counts.get(_client_ip(request), 0) >= _cloud_config.FREE_DAILY_JOBS_PER_IP: + raise HTTPException(status_code=429, detail={ + "error": "daily_limit", + "message": "Free plan daily limit reached for this network. Come back tomorrow or upgrade.", + }) + + # Probe rate limit: probing costs a (cheap) proxied metadata call. + _check_probe_rate(user.id) + # Probe input duration (blocking → run in a thread). loop = asyncio.get_event_loop() try: @@ -167,12 +240,22 @@ async def reserve_process_minutes(request, url, input_path, job_id): try: reservation_id = await _metering.reserve_minutes(user.id, minutes, job_id) except _metering.QuotaExceeded as e: + _maybe_send_quota_email(user) raise HTTPException(status_code=402, detail={ "error": "quota_exceeded", "minutes_required": e.required, "minutes_remaining": e.remaining, }) - return user.id, priority, reservation_id + + # Count the job against the free daily caps only once it actually reserved. + if user.plan == "free": + user_counts = _daily_bucket("users") + user_counts[str(user.id)] = user_counts.get(str(user.id), 0) + 1 + ip_counts = _daily_bucket("ips") + ip = _client_ip(request) + ip_counts[ip] = ip_counts.get(ip, 0) + 1 + + return user.id, priority, reservation_id, user.plan async def reserve_managed_action(request, minutes, job_id, job_type): @@ -189,6 +272,7 @@ async def reserve_managed_action(request, minutes, job_id, job_type): try: return await _metering.reserve_minutes(user.id, minutes, job_id, job_type) except _metering.QuotaExceeded as e: + _maybe_send_quota_email(user) raise HTTPException(status_code=402, detail={ "error": "quota_exceeded", "minutes_required": e.required, @@ -412,6 +496,33 @@ async def process_queue(): print(f"❌ Queue dispatch error: {e}") await asyncio.sleep(1) +# Monthly proxy bandwidth counter (in-memory; an alert threshold, not a bill — +# losing it on a deploy just means the alert re-arms from 0 mid-month). +_proxy_month = {"month": None, "bytes": 0, "alerted": False} +PROXY_ALERT_GB = 100 + + +async def _track_proxy_usage(job_id): + nbytes = (jobs.get(job_id) or {}).get('proxy_bytes') or 0 + if not nbytes: + return + month = datetime.now(timezone.utc).strftime("%Y-%m") + if _proxy_month["month"] != month: + _proxy_month.update(month=month, bytes=0, alerted=False) + _proxy_month["bytes"] += nbytes + gb = _proxy_month["bytes"] / 1e9 + if gb >= PROXY_ALERT_GB and not _proxy_month["alerted"] and _alerts: + _proxy_month["alerted"] = True + try: + await _alerts.send_admin_alert( + "Proxy bandwidth threshold", + f"Managed downloads have used {gb:.1f} GB of proxy bandwidth in {month} " + f"(threshold {PROXY_ALERT_GB} GB). Review free-plan usage.", + ) + except Exception as e: + print(f"⚠️ Proxy alert failed: {e}") + + async def run_job_wrapper(job_id): """Wrapper to run job and release semaphore""" try: @@ -428,6 +539,10 @@ async def run_job_wrapper(job_id): await _archive_managed_job(job_id) # Operational alerting for managed jobs (proxy out of credits / failures). await _record_job_alert(job_id) + # Accumulate proxy bandwidth for the monthly cost alert. + await _track_proxy_usage(job_id) + # Tell the owner their clips are ready (managed jobs, once per job). + await _notify_clips_ready(job_id) # Always release semaphore and mark queue task done concurrency_semaphore.release() job_queue.task_done() @@ -470,6 +585,33 @@ def _archive_clip_edit_bg(job_id: str, clip_index: int, filename: str): asyncio.create_task(_run()) +async def _notify_clips_ready(job_id): + """Email the owner when their clips finish — processing takes minutes, so + this lets them close the tab. Once per job (email_sent flag).""" + if not BILLING_ENABLED: + return + job = jobs.get(job_id) or {} + if not job.get('user_id') or job.get('status') != 'completed' or job.get('email_sent'): + return + clips = (job.get('result') or {}).get('clips') or [] + if not clips: + return + job['email_sent'] = True + try: + from cloud.database import session as cloud_session + from cloud.models import User + from cloud.emails import send_clips_ready_email + async with cloud_session() as s: + user = await s.get(User, job['user_id']) + if not user or not user.email: + return + title = clips[0].get('video_title_for_youtube_short') or clips[0].get('title') or "Your video" + await send_clips_ready_email(user.email, title, len(clips), + _cloud_config.settings.frontend_url) + except Exception as e: + print(f"⚠️ Clips-ready email error for {job_id}: {e}") + + async def _record_job_alert(job_id): if not BILLING_ENABLED: return @@ -601,6 +743,14 @@ def enqueue_output(out, job_id): for line in iter(out.readline, b''): decoded_line = _scrub_secrets(line.decode('utf-8').strip()) if decoded_line: + # Internal marker from main.py's downloader, not a log line. + if decoded_line.startswith("PROXY_BYTES="): + try: + if job_id in jobs: + jobs[job_id]['proxy_bytes'] = int(decoded_line.split("=", 1)[1]) + except ValueError: + pass + continue print(f"📝 [Job Output] {decoded_line}") if job_id in jobs: jobs[job_id]['logs'].append(decoded_line) @@ -859,7 +1009,11 @@ async def process_endpoint( print(f"[attestation] job={job_id} ip={attestation['ip']} source={attestation['source']} ack=true") # Meter + reserve minutes for managed users (no-op for BYOK / self-host). - user_id, priority, reservation_id = await reserve_process_minutes(request, url, input_path, job_id) + user_id, priority, reservation_id, user_plan = await reserve_process_minutes(request, url, input_path, job_id) + if user_plan == "free": + # Free-plan clips carry a burned-in watermark (applied by the main.py + # subprocess after each clip renders). + env["WATERMARK"] = "1" # Enqueue Job jobs[job_id] = { @@ -2249,6 +2403,15 @@ async def thumbnail_generate( if not api_key: raise gemini_missing_error() + # Image generation is the one expensive managed Gemini call — paid plans only. + if BILLING_ENABLED: + user = await _user_from_request(request) + if user is not None and user.plan == "free": + raise HTTPException(status_code=403, detail={ + "error": "plan_required", + "message": "AI thumbnail generation is available on paid plans.", + }) + # Clamp count count = min(max(1, count), 6) @@ -2944,6 +3107,9 @@ class SaaSGenerateRequest(BaseModel): selected_actor_url: Optional[str] = None # Pre-selected actor image URL retry_job_id: Optional[str] = None video_mode: str = "lowcost" # "lowcost" or "premium" + # Publishing to the public /gallery is opt-in: generated videos carry the + # user's product name, URL and full script. + share_to_gallery: bool = False @app.post("/api/saasshorts/generate") @@ -3066,35 +3232,37 @@ async def saasshorts_generate( } saas_jobs[job_id]["logs"].append("Video generation completed!") - # Upload to public gallery (non-blocking) - try: - gallery_meta = { - "title": req.script.get("title", "Untitled"), - "hook_text": req.script.get("hook_text", ""), - "caption": req.script.get("caption", ""), - "hashtags": req.script.get("hashtags", []), - "full_narration": req.script.get("full_narration", ""), - "actor_description": req.script.get("actor_description", ""), - "style": req.script.get("style", "ugc"), - "language": req.script.get("language", "en"), - "duration": result.get("duration", 0), - "video_mode": req.video_mode, - "product_name": req.script.get("_product_name", ""), - "product_url": req.script.get("_product_url", ""), - "segments": req.script.get("segments", []), - "cost_estimate": result.get("cost_estimate", {}), - } - gallery_result = upload_video_to_gallery( - video_path=result["video_path"], - actor_image_path=result.get("actor_image", ""), - metadata=gallery_meta, - video_id=job_id[:8], - ) - if gallery_result: - saas_jobs[job_id]["result"]["gallery_video_id"] = gallery_result["video_id"] - log_msg("📤 Uploaded to public gallery.") - except Exception as gallery_err: - log_msg(f"⚠️ Gallery upload skipped: {gallery_err}") + # Upload to public gallery — opt-in only: the metadata carries + # the user's product name, URL and full script. + if req.share_to_gallery: + try: + gallery_meta = { + "title": req.script.get("title", "Untitled"), + "hook_text": req.script.get("hook_text", ""), + "caption": req.script.get("caption", ""), + "hashtags": req.script.get("hashtags", []), + "full_narration": req.script.get("full_narration", ""), + "actor_description": req.script.get("actor_description", ""), + "style": req.script.get("style", "ugc"), + "language": req.script.get("language", "en"), + "duration": result.get("duration", 0), + "video_mode": req.video_mode, + "product_name": req.script.get("_product_name", ""), + "product_url": req.script.get("_product_url", ""), + "segments": req.script.get("segments", []), + "cost_estimate": result.get("cost_estimate", {}), + } + gallery_result = upload_video_to_gallery( + video_path=result["video_path"], + actor_image_path=result.get("actor_image", ""), + metadata=gallery_meta, + video_id=job_id[:8], + ) + if gallery_result: + saas_jobs[job_id]["result"]["gallery_video_id"] = gallery_result["video_id"] + log_msg("📤 Uploaded to public gallery.") + except Exception as gallery_err: + log_msg(f"⚠️ Gallery upload skipped: {gallery_err}") except Exception as e: print(f"[SaaSShorts] ❌ Job {job_id} failed: {e}") diff --git a/cloud/auth.py b/cloud/auth.py index 41c072d..b8a8760 100644 --- a/cloud/auth.py +++ b/cloud/auth.py @@ -79,13 +79,15 @@ async def _load_current_user(session, user_id) -> Optional["CurrentUser"]: (float(t.minutes_total) - float(t.minutes_consumed) for t in topups), 0.0 ) profile = await session.get(UploadPostProfile, user_id) - # Entitled to managed keys if they have an active plan OR any top-up credit. - entitled = bool(sub is not None or topup_remaining > 0) + # Entitled to managed keys with an active plan, any top-up credit, or the + # free monthly allowance (Google-authenticated accounts only). + free = sub is None and metering.free_plan_eligible(user) + entitled = bool(sub is not None or topup_remaining > 0 or free) return CurrentUser( id=user.id, email=user.email, entitled=entitled, - plan=sub.plan if sub else None, + plan=sub.plan if sub else ("free" if free else None), upload_post_profile=profile.profile_username if profile else None, ) diff --git a/cloud/billing.py b/cloud/billing.py index 5e30c2a..99630d2 100644 --- a/cloud/billing.py +++ b/cloud/billing.py @@ -106,7 +106,8 @@ async def _active_sub_exists(user_id) -> bool: # unpaid / incomplete; those must still block, otherwise the user can spawn a # second subscription while the first one keeps dunning (real case: annual # trial -> end-trial -> card declined -> past_due, then a fresh monthly sub). - # Terminal states (canceled, incomplete_expired) do NOT block. + # Terminal states (canceled, incomplete_expired) do NOT block. Free-plan + # users have no Subscription row at all, so their upgrade checkout passes. return bool(sub and sub.status in ( "active", "trialing", "past_due", "unpaid", "incomplete", "paused", )) @@ -154,7 +155,8 @@ async def create_checkout(body: CheckoutRequest, request: Request): "minutes": str(entry.get("minutes", "")), }, ) - # Subscriptions start with a card-required free trial that auto-charges. + # Dead while TRIAL_DAYS == 0 (trials retired in favor of the free plan); + # kept as the documented grandfathering mechanism. if mode == "subscription" and TRIAL_DAYS > 0: kwargs["subscription_data"] = {"trial_period_days": TRIAL_DAYS} session = await asyncio.to_thread(lambda: stripe.checkout.Session.create(**kwargs)) @@ -164,7 +166,9 @@ async def create_checkout(body: CheckoutRequest, request: Request): @router.post("/api/billing/end-trial") async def end_trial(request: Request): """End the free trial immediately: charge the card now and unlock full plan - minutes. Used when a trialing user hits the trial minute cap and chooses to + minutes. Kept for grandfathered trialing subscriptions — removable once + ``SELECT count(*) FROM subscriptions WHERE status='trialing'`` reaches 0. + Used when a trialing user hits the trial minute cap and chooses to activate their plan right away. The subscription webhook flips status→active (and thus the full ``minutes_per_period`` allowance) once Stripe confirms.""" user = await get_current_user_required(request) @@ -379,8 +383,9 @@ async def _upsert_subscription(sub_obj: dict, event_created: datetime): await send_admin_alert( "🔻 Subscription canceled", f"A {plan} subscriber just canceled.\n" - f"Access continues until {end_dt:%Y-%m-%d}; their videos are then kept " - f"{VIDEO_RETENTION_GRACE_DAYS} more days before deletion.", + f"Access continues until {end_dt:%Y-%m-%d}. Google-authed users then " + f"drop to the free plan (clips expire after 7 days); others keep their " + f"videos {VIDEO_RETENTION_GRACE_DAYS} more days before deletion.", ) diff --git a/cloud/config.py b/cloud/config.py index 0e727b6..38eee4f 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -27,14 +27,32 @@ PLAN_MINUTES = { "pro": 750, } -# Free trial length (days) for new subscriptions. Card required; auto-charges at -# the end. -TRIAL_DAYS = 3 +# Free plan: monthly allowance for Google-authenticated users with no +# subscription. No Stripe object exists for it — it is resolved entirely in +# cloud/metering.py against a synthetic calendar-month period. Setting +# FREE_PLAN_MINUTES = 0 disables the free plan. +FREE_PLAN_MINUTES = 20 +# Gate the free allowance behind Google sign-in; magic-link-only accounts are +# disposable-email fodder and stay unentitled. +FREE_REQUIRES_GOOGLE = True +# Max processing jobs per free account per UTC day (abuse bound on GPU/proxy). +FREE_DAILY_JOBS = 3 +# Same bound per client IP across free accounts. Generous on purpose: much of +# the audience is behind CGNAT (India/Indonesia share IPs among thousands). +FREE_DAILY_JOBS_PER_IP = 5 +# Free users' clips expire from R2 after this many days (paid libraries are +# durable). Also an upgrade lever, mirroring OpusClip's 3-day free exports. +FREE_CLIP_RETENTION_DAYS = 7 -# Minute cap DURING the trial (across all plans). Enough to evaluate the product, -# but bounds the free managed-compute / proxy exposure per sign-up so a -# cancel-before-charge account can't burn a full plan's worth of minutes. Once the -# trial converts to an active subscription the full plan allowance applies. +# Free trial length (days) for new subscriptions. Trials are retired in favor +# of the free plan; the checkout only injects trial_period_days when > 0, and +# existing 'trialing' subscriptions are still honored until they convert or +# cancel (grandfathering). +TRIAL_DAYS = 0 + +# Minute cap DURING the trial (across all plans). Kept for grandfathered +# 'trialing' subscriptions; removable once no subscription has status +# 'trialing'. TRIAL_MINUTE_CAP = 20 # Gemini IMAGE generation (thumbnails) is the one expensive managed Gemini call @@ -75,6 +93,7 @@ PLAN_PRIORITY = { "pro": 0, "creator": 1, "starter": 1, + "free": 2, } # Max simultaneous managed jobs per user, by plan. @@ -82,6 +101,7 @@ PLAN_JOB_LIMIT = { "pro": 3, "creator": 2, "starter": 2, + "free": 1, } diff --git a/cloud/emails.py b/cloud/emails.py index 133944d..1073af0 100644 --- a/cloud/emails.py +++ b/cloud/emails.py @@ -56,3 +56,41 @@ async def send_magic_link_email(email: str, link: str): """ await send_email(email, "Your OpenShorts sign-in link", html) + + +GITHUB_REPO_URL = "https://github.com/mutonby/openshorts" + + +async def send_clips_ready_email(email: str, job_title: str, clip_count: int, + dashboard_url: str): + """Job-completion notice: lets the user close the tab during processing.""" + title = (job_title or "Your video").strip() + html = f""" +
+

Your clips are ready 🎬

+

{title} produced {clip_count} viral-ready + clip{'s' if clip_count != 1 else ''}. They're waiting in your dashboard.

+

View my clips

+

Enjoying OpenShorts? A + star on GitHub helps a lot ⭐

+
+ """ + await send_email(email, f"Your clips are ready — {title}", html) + + +async def send_out_of_minutes_email(email: str, upgrade_url: str): + """Free user hit their monthly quota — the natural upgrade moment.""" + html = f""" +
+

You've used your free minutes 🚀

+

You've hit this month's free allowance. That usually means the clips + are working for you — Starter gives you 100 minutes a month, + no watermark, and a durable clip library.

+

See plans

+

Your free minutes reset on the 1st of + every month.

+
+ """ + await send_email(email, "You've used your free OpenShorts minutes", html) diff --git a/cloud/metering.py b/cloud/metering.py index 7e9b380..62f0cd6 100644 --- a/cloud/metering.py +++ b/cloud/metering.py @@ -120,6 +120,42 @@ async def _active_subscription(session, user_id): return None +def free_plan_eligible(user) -> bool: + """True if this ``User`` row qualifies for the free monthly allowance. + + Free minutes are only for Google-authenticated accounts: magic-link-only + sign-ins accept disposable-email domains and would make the free plan a + multi-account faucet. FREE_PLAN_MINUTES = 0 disables the free plan. + """ + if user is None or config.FREE_PLAN_MINUTES <= 0: + return False + if config.FREE_REQUIRES_GOOGLE and not user.google_sub: + return False + return True + + +def free_period_end(now: datetime | None = None) -> datetime: + """First instant of the next UTC calendar month. + + Free-plan ledger rows are tagged with this synthetic ``period_end`` so the + existing period accounting resets them monthly with no cron, exactly like + Stripe periods. A real subscription's ``current_period_end`` is anchored to + the checkout instant, so it can only collide with this value if it lands on + a month start to the second — accepted as negligible. + """ + now = now or _now() + if now.month == 12: + return datetime(now.year + 1, 1, 1, tzinfo=timezone.utc) + return datetime(now.year, now.month + 1, 1, tzinfo=timezone.utc) + + +async def is_free_user(session, user_id) -> bool: + """Google-authed user currently on the free plan (no active/trialing sub).""" + if await _active_subscription(session, user_id): + return False + return free_plan_eligible(await session.get(User, user_id)) + + async def _plan_used_this_period(session, user_id, period_end) -> Decimal: total = (await session.execute( select(func.coalesce(func.sum(UsageLedger.minutes_from_plan), 0)).where(and_( @@ -138,23 +174,43 @@ async def _topups_fifo(session, user_id): )).scalars()) -async def _balance(session, user_id): - """Return a dict of the user's current minute balance (read-only).""" +async def _balance(session, user_id, user=None): + """Return a dict of the user's current minute balance (read-only). + + ``user`` may be a pre-fetched ``User`` row to save a lookup; it is only + consulted on the subscription-less path (free-plan eligibility). + """ sub = await _active_subscription(session, user_id) - plan_allowance = _D(sub.minutes_per_period) if sub else _D(0) - # During the trial, cap the allowance so a cancel-before-charge account can't - # burn a whole plan's worth of managed minutes. Full allowance once active. - if sub and sub.status == "trialing": - plan_allowance = min(plan_allowance, _D(config.TRIAL_MINUTE_CAP)) - period_end = sub.current_period_end if sub else None - plan_used = await _plan_used_this_period(session, user_id, period_end) if sub else _D(0) + if sub: + plan_name = sub.plan + plan_allowance = _D(sub.minutes_per_period) + # During the trial, cap the allowance so a cancel-before-charge account + # can't burn a whole plan's worth of managed minutes. Kept for + # grandfathered 'trialing' subscriptions. + if sub.status == "trialing": + plan_allowance = min(plan_allowance, _D(config.TRIAL_MINUTE_CAP)) + period_end = sub.current_period_end + plan_used = await _plan_used_this_period(session, user_id, period_end) + else: + if user is None: + user = await session.get(User, user_id) + if free_plan_eligible(user): + plan_name = "free" + plan_allowance = _D(config.FREE_PLAN_MINUTES) + period_end = free_period_end() + plan_used = await _plan_used_this_period(session, user_id, period_end) + else: + plan_name = None + plan_allowance = _D(0) + period_end = None + plan_used = _D(0) plan_remaining = max(_D(0), plan_allowance - plan_used) topups = await _topups_fifo(session, user_id) topup_remaining = sum((_D(t.minutes_total) - _D(t.minutes_consumed) for t in topups), _D(0)) return { - "plan": sub.plan if sub else None, + "plan": plan_name, "plan_allowance": float(plan_allowance), "plan_used": float(plan_used), "plan_remaining": float(plan_remaining), @@ -190,11 +246,12 @@ async def reserve_minutes(user_id, minutes: float, job_id: str, job_type: str = minutes = _D(minutes) async with database.session() as session: async with session.begin(): - # Serialize all of this user's reservations. - await session.execute( - select(User.id).where(User.id == user_id).with_for_update() - ) - b = await _balance(session, user_id) + # Serialize all of this user's reservations. Selecting the full row + # (same lock semantics) lets _balance skip a second User lookup. + locked_user = (await session.execute( + select(User).where(User.id == user_id).with_for_update() + )).scalar_one_or_none() + b = await _balance(session, user_id, user=locked_user) plan_remaining = b["_plan_remaining_d"] remaining_total = _D(b["remaining"]) if minutes > remaining_total: diff --git a/cloud/videos.py b/cloud/videos.py index 3686184..9ff0ef3 100644 --- a/cloud/videos.py +++ b/cloud/videos.py @@ -9,8 +9,8 @@ from datetime import timedelta from fastapi import APIRouter, HTTPException, Request from sqlalchemy import select, delete -from .config import settings, VIDEO_RETENTION_GRACE_DAYS -from . import database, storage +from .config import settings, VIDEO_RETENTION_GRACE_DAYS, FREE_CLIP_RETENTION_DAYS +from . import database, storage, metering from .models import UserVideo, Subscription, Project from .auth import get_current_user_required @@ -260,6 +260,12 @@ async def purge_expired(): continue if last_event_at + timedelta(days=VIDEO_RETENTION_GRACE_DAYS) > now: continue + # A canceled Google-authed user is now an entitled FREE user, not a + # lapsed one — their library follows the free 7-day per-clip expiry + # (purge_free_expired) instead of the full wipe. + async with database.session() as s: + if await metering.is_free_user(s, user_id): + continue # Any videos or projects left? async with database.session() as s: has = (await s.execute( @@ -280,6 +286,53 @@ async def purge_expired(): print(f"⚠️ Video purge failed for {user_id}: {e}") +async def purge_free_expired(): + """Expire free users' clips/projects after FREE_CLIP_RETENTION_DAYS. + + Paid libraries are durable; the free plan keeps R2 storage bounded (and the + limited retention is an upgrade lever). Only rows whose owner is currently + on the free plan are touched — a user who upgraded keeps everything. + """ + from datetime import datetime, timezone + cutoff = datetime.now(timezone.utc) - timedelta(days=FREE_CLIP_RETENTION_DAYS) + async with database.session() as s: + old_videos = list((await s.execute( + select(UserVideo).where(UserVideo.created_at < cutoff) + )).scalars()) + old_projects = list((await s.execute( + select(Project).where(Project.updated_at < cutoff) + )).scalars()) + + by_user = {} + for v in old_videos: + by_user.setdefault(v.user_id, {"videos": [], "projects": []})["videos"].append(v) + for p in old_projects: + by_user.setdefault(p.user_id, {"videos": [], "projects": []})["projects"].append(p) + + for user_id, items in by_user.items(): + async with database.session() as s: + if not await metering.is_free_user(s, user_id): + continue + try: + for v in items["videos"]: + await asyncio.to_thread(storage.delete_key, v.r2_key) + for p in items["projects"]: + if p.metadata_r2_key: + await asyncio.to_thread(storage.delete_key, p.metadata_r2_key) + async with database.session() as s: + async with s.begin(): + if items["videos"]: + await s.execute(delete(UserVideo).where( + UserVideo.id.in_([v.id for v in items["videos"]]))) + if items["projects"]: + await s.execute(delete(Project).where( + Project.id.in_([p.id for p in items["projects"]]))) + n = len(items["videos"]) + len(items["projects"]) + print(f"🗑️ Free retention: purged {n} expired object(s) for user {user_id}.") + except Exception as e: + print(f"⚠️ Free retention purge failed for {user_id}: {e}") + + _SWEEP_INTERVAL = 6 * 3600 # every 6 hours @@ -288,6 +341,7 @@ async def _sweeper_loop(): try: await asyncio.sleep(_SWEEP_INTERVAL) await purge_expired() + await purge_free_expired() except asyncio.CancelledError: break except Exception as e: diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index ba714a4..194b371 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -11,6 +11,7 @@ import UGCGallery from './components/UGCGallery'; import ScheduleWeekModal from './components/ScheduleWeekModal'; import UsageMeter from './components/UsageMeter'; import TopUpModal from './components/TopUpModal'; +import StarBanner from './components/StarBanner'; import TrialUpgradeModal from './components/TrialUpgradeModal'; import LoginModal from './components/LoginModal'; import TrialGate from './components/TrialGate'; @@ -1350,6 +1351,20 @@ function App() { )} + {status === 'complete' && results?.clips?.length > 0 && ( +
+ + {plan === 'free' && ( + + )} +
+ )} +
{results && results.clips && results.clips.length > 0 ? (
diff --git a/dashboard/src/Landing.jsx b/dashboard/src/Landing.jsx index a9805f0..63eef1c 100644 --- a/dashboard/src/Landing.jsx +++ b/dashboard/src/Landing.jsx @@ -151,7 +151,7 @@ export default function Landing({ onLaunchApp }) { const faqs = [ { question: "Is OpenShorts really free? What's the catch?", - answer: "There are two ways to use OpenShorts. (1) Self-hosted is 100% free and open source: you run it with Docker on your own machine, bring your own API keys, and there are no watermarks, no usage limits, and no subscription. Google Gemini API (required) powers the AI analysis — its free tier includes 1,500 requests/day. ElevenLabs (optional) enables AI dubbing in 30+ languages. Upload-Post (optional) publishes to YouTube, TikTok, and Instagram. (2) Hosted at openshorts.app is the no-setup option: we run all the AI and compute for you and you don't need any API keys — it's a paid service with a 3-day free trial, then plans from $12/mo for 100 minutes of video. So: free if you self-host, paid if you want us to host it for you. Both are far cheaper than Opus Clip ($15-228/month) or Kapwing ($24-79/month)." + answer: "There are two ways to use OpenShorts. (1) Self-hosted is 100% free and open source: you run it with Docker on your own machine, bring your own API keys, and there are no watermarks, no usage limits, and no subscription. Google Gemini API (required) powers the AI analysis — its free tier includes 1,500 requests/day. ElevenLabs (optional) enables AI dubbing in 30+ languages. Upload-Post (optional) publishes to YouTube, TikTok, and Instagram. (2) Hosted at openshorts.app is the no-setup option: we run all the AI and compute for you and you don't need any API keys — it has a free plan (20 minutes of video a month, watermark, no credit card) and paid plans from $12/mo for 100 minutes without watermark. So: free if you self-host, free to try in the cloud, paid if you want more. Both are far cheaper than Opus Clip ($15-228/month) or Kapwing ($24-79/month)." }, { question: "What is OpenShorts and how does it work?", @@ -257,7 +257,7 @@ export default function Landing({ onLaunchApp }) {
{billingEnabled ? ( - start free trial + start free ) : ( @@ -274,7 +274,7 @@ export default function Landing({ onLaunchApp }) {

- 3-day free trial · 20 free minutes · from $12/mo · no watermarks. prefer to run it yourself?{' '} + free plan · 20 min/month · no credit card · paid plans from $12/mo without watermark. prefer to run it yourself?{' '} {billingEnabled ? ( - start free trial + start free ) : (

- + {plan === 'free' ? ( + + ) : ( + + )}
diff --git a/dashboard/src/components/AdvancedBanner.jsx b/dashboard/src/components/AdvancedBanner.jsx index 007bffe..9f41c82 100644 --- a/dashboard/src/components/AdvancedBanner.jsx +++ b/dashboard/src/components/AdvancedBanner.jsx @@ -12,7 +12,7 @@ export default function AdvancedBanner({ needsPlan, onKeys }) {
Advanced tool.{' '} {needsPlan - ? <>Start your 3-day free trial to unlock. This tool also uses your own fal.ai + ElevenLabs keys (you pay those providers). + ? <>Sign in with Google to unlock free. This tool also uses your own fal.ai + ElevenLabs keys (you pay those providers). : <>AI video & voice generation use your own fal.ai + ElevenLabs keys — add them in Settings. Script & orchestration are included in your plan.}
diff --git a/dashboard/src/components/PricingPage.jsx b/dashboard/src/components/PricingPage.jsx index 5fd4a17..c6e1c15 100644 --- a/dashboard/src/components/PricingPage.jsx +++ b/dashboard/src/components/PricingPage.jsx @@ -6,7 +6,7 @@ import PricingSection from './PricingSection'; const FAQS = [ { question: "Is OpenShorts really free? What's the catch?", - answer: "There are two ways to use OpenShorts. (1) Self-hosted is 100% free and open source: you run it with Docker on your own machine, bring your own API keys, and there are no watermarks, no usage limits, and no subscription. Google Gemini API (required) powers the AI analysis — its free tier includes 1,500 requests/day. ElevenLabs (optional) enables AI dubbing in 30+ languages. Upload-Post (optional) publishes to YouTube, TikTok, and Instagram. (2) Hosted at openshorts.app is the no-setup option: we run all the AI and compute for you and you don't need any API keys — it's a paid service with a 3-day free trial, then plans from $12/mo for 100 minutes of video. So: free if you self-host, paid if you want us to host it for you. Both are far cheaper than Opus Clip ($15-228/month) or Kapwing ($24-79/month)." + answer: "There are two ways to use OpenShorts. (1) Self-hosted is 100% free and open source: you run it with Docker on your own machine, bring your own API keys, and there are no watermarks, no usage limits, and no subscription. Google Gemini API (required) powers the AI analysis — its free tier includes 1,500 requests/day. ElevenLabs (optional) enables AI dubbing in 30+ languages. Upload-Post (optional) publishes to YouTube, TikTok, and Instagram. (2) Hosted at openshorts.app is the no-setup option: we run all the AI and compute for you and you don't need any API keys — it has a free plan (20 minutes of video a month, watermark, no credit card) and paid plans from $12/mo for 100 minutes without watermark. So: free if you self-host, free to try in the cloud, paid if you want more. Both are far cheaper than Opus Clip ($15-228/month) or Kapwing ($24-79/month)." }, { question: "How does OpenShorts compare to Opus Clip?", @@ -61,8 +61,8 @@ const TRUST_CARDS = [ eyebrow: 'cancel anytime', body: ( <> - 3-day free trial with up to 20 minutes included; you are not charged during the trial. - Billing runs on Stripe — cancel anytime from your account. + Start on the free plan — 20 minutes a month, no credit card. Billing for paid + plans runs on Stripe — cancel anytime from your account. ), }, @@ -123,7 +123,7 @@ export default function PricingPage({ onRequireLogin }) {

start clipping in minutes.

-

3-day free trial · 20 free minutes · cancel anytime

+

free plan · 20 min/month · no credit card

@@ -197,11 +197,11 @@ export default function PricingPage({ onRequireLogin }) {

- three free days. twenty free minutes. no charge until you decide. + twenty free minutes. every month. no card until you decide.

new Intl.NumberFormat('en-US', { style: 'currency', currency: (currency || 'usd').toUpperCase(), maximumFractionDigits: 0 }).format((amount || 0) / 100); -// 3-tier pricing with monthly/annual toggle. Checkout requires sign-in. +// Free tier + 3 paid tiers with monthly/annual toggle. Checkout requires sign-in. export default function PricingSection({ onRequireLogin }) { const { isSignedIn } = useAuth(); const [plans, setPlans] = useState([]); @@ -66,7 +67,30 @@ export default function PricingSection({ onRequireLogin }) { />
-
+
+ {/* Free tier — no card, Google sign-in only */} +
+

free

+

Try it on your own videos

+
+ $0 + /mo +
+
    +
  • {FREE_MINUTES} min of video / month
  • +
  • YouTube URL or upload
  • +
  • No credit card — Google sign-in
  • +
  • Watermark · clips kept 7 days
  • +
+ +

free minutes reset monthly.

+
+ {PLAN_ORDER.map((plan) => { const entry = byPlan(plan); if (!entry) return null; @@ -98,9 +122,9 @@ export default function PricingSection({ onRequireLogin }) { disabled={busyPrice === entry.price_id} className={`w-full ${highlight ? 'btn-primary' : 'btn-ghost'}`} > - {busyPrice === entry.price_id ? : 'Start 3-day free trial'} + {busyPrice === entry.price_id ? : `Get ${plan}`} -

3 days free, then billed monthly. Cancel anytime.

+

billed {interval === 'month' ? 'monthly' : 'yearly'}. cancel anytime.

); })} @@ -164,7 +188,7 @@ export default function PricingSection({ onRequireLogin }) {

- Use it free on your own computer, or skip the setup and use it here — 3 days free, then a plan. + Use it free on your own computer, start free right here, or upgrade for more minutes and no watermark.

); diff --git a/dashboard/src/components/ProfileMenu.jsx b/dashboard/src/components/ProfileMenu.jsx index 6279c21..4abd05a 100644 --- a/dashboard/src/components/ProfileMenu.jsx +++ b/dashboard/src/components/ProfileMenu.jsx @@ -40,7 +40,7 @@ export default function ProfileMenu() { onClick={() => { setOpen(false); window.location.hash = '#/pricing'; }} className="w-full flex items-center gap-3 px-4 py-2.5 text-sm lowercase text-brass hover:bg-paper3 transition-colors" > - Start free trial + Start free )} ); diff --git a/dashboard/src/contexts/AuthContext.jsx b/dashboard/src/contexts/AuthContext.jsx index 376e695..40659d6 100644 --- a/dashboard/src/contexts/AuthContext.jsx +++ b/dashboard/src/contexts/AuthContext.jsx @@ -65,8 +65,9 @@ export function AuthProvider({ children }) { } } const signedInMe = await refreshMe(); - // New sign-ups (and anyone without an active plan/trial) go straight to - // pricing so they can start their free trial; entitled users land in the app. + // Google sign-ins are entitled (free plan) and land in the app; only + // magic-link-only accounts (no entitlement) are routed to pricing, where + // the free card tells them to use Google. if (signedInMe?.user && !signedInMe?.entitled) destination = '#/pricing'; } catch (e) { // fall through — user lands signed-out diff --git a/main.py b/main.py index 91fb468..8464138 100644 --- a/main.py +++ b/main.py @@ -587,6 +587,16 @@ def download_youtube_video(url, output_dir="."): }, } + # Wire bytes actually pulled through the (paid) proxy, summed across + # fragments/streams. Reported to app.py via the PROXY_BYTES= line below. + _dl_bytes = {"total": 0} + + def _progress_hook(d): + if d.get('status') == 'finished': + _dl_bytes["total"] += int(d.get('total_bytes') + or d.get('total_bytes_estimate') + or d.get('downloaded_bytes') or 0) + def _attempt(extractor_args, fmt): with yt_dlp.YoutubeDL(_base_opts(extractor_args)) as ydl: info = ydl.extract_info(url, download=False) @@ -599,6 +609,7 @@ def download_youtube_video(url, output_dir="."): 'format': fmt, 'outtmpl': os.path.join(output_dir, f'{sanitized}.%(ext)s'), 'merge_output_format': 'mp4', 'overwrites': True, + 'progress_hooks': [_progress_hook], } with yt_dlp.YoutubeDL(dl_opts) as ydl: ydl.download([url]) @@ -641,6 +652,10 @@ Technical Details: {str(last_err)} downloaded_file = os.path.join(output_dir, f) break + if _proxy and _dl_bytes["total"]: + # Machine-parseable marker consumed by app.py's log reader for the + # monthly proxy-bandwidth counter. Not shown to clients (log filter). + print(f"PROXY_BYTES={_dl_bytes['total']}") print(f"✅ Video downloaded in {time.time() - step_start_time:.2f}s: {downloaded_file}") return downloaded_file, sanitized_title @@ -672,6 +687,37 @@ def render_clip(input_video, final_output_video, output_format="auto"): return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect) +def apply_watermark(video_path): + """Burn the OpenShorts watermark into a finished clip (free plan). + + One re-encode pass on the final file so every output format (TRACK, + GENERAL, horizontal passthrough) gets the mark, and later subtitle/hook + re-encodes keep it — they re-encode the already-marked pixels. + """ + font_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), + "fonts", "NotoSerif-Bold.ttf") + font_arg = f"fontfile={font_path}:" if os.path.exists(font_path) else "" + draw = ( + f"drawtext={font_arg}text=openshorts.app:" + "fontcolor=white@0.6:borderw=2:bordercolor=black@0.4:" + "fontsize=h/30:x=(w-text_w)/2:y=h-(h/12)" + ) + tmp_path = video_path + ".wm.mp4" + cmd = ["ffmpeg", "-y", "-i", video_path, "-vf", draw, + *video_encode_args(QUALITY), "-c:a", "copy", + "-movflags", "+faststart", tmp_path] + result = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + timeout=1800) + if result.returncode == 0 and os.path.exists(tmp_path): + os.replace(tmp_path, video_path) + return True + err = (result.stderr or b"").decode(errors="ignore")[-300:] + print(f" ⚠️ Watermark pass failed (clip kept unmarked): {err}") + if os.path.exists(tmp_path): + os.remove(tmp_path) + return False + + def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO): """ Core logic to reframe a horizontal video to a target aspect ratio using @@ -1141,6 +1187,8 @@ if __name__ == '__main__': subprocess.run(cut_command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) success = render_clip(clip_temp_path, clip_final_path, output_format) + if success and os.environ.get("WATERMARK") == "1": + apply_watermark(clip_final_path) if success: print(f" ✅ Clip {i+1} ready: {clip_final_path}") return success diff --git a/tests/test_metering_free_plan.py b/tests/test_metering_free_plan.py new file mode 100644 index 0000000..f749cc5 --- /dev/null +++ b/tests/test_metering_free_plan.py @@ -0,0 +1,53 @@ +"""Free-plan eligibility and synthetic period logic (pure functions, no DB).""" +from datetime import datetime, timezone +from types import SimpleNamespace + +import pytest + +from cloud import config, metering + + +def _user(google_sub="g-123"): + return SimpleNamespace(google_sub=google_sub) + + +class TestFreePlanEligible: + def test_google_user_is_eligible(self): + assert metering.free_plan_eligible(_user()) is True + + def test_magic_link_only_user_is_not_eligible(self): + assert metering.free_plan_eligible(_user(google_sub=None)) is False + + def test_none_user_is_not_eligible(self): + assert metering.free_plan_eligible(None) is False + + def test_zero_minutes_disables_free_plan(self, monkeypatch): + monkeypatch.setattr(config, "FREE_PLAN_MINUTES", 0) + assert metering.free_plan_eligible(_user()) is False + + def test_google_gate_can_be_disabled(self, monkeypatch): + monkeypatch.setattr(config, "FREE_REQUIRES_GOOGLE", False) + assert metering.free_plan_eligible(_user(google_sub=None)) is True + + +class TestFreePeriodEnd: + @pytest.mark.parametrize("now, expected", [ + (datetime(2026, 7, 20, 12, 30, tzinfo=timezone.utc), + datetime(2026, 8, 1, tzinfo=timezone.utc)), + (datetime(2026, 12, 31, 23, 59, 59, tzinfo=timezone.utc), + datetime(2027, 1, 1, tzinfo=timezone.utc)), + (datetime(2026, 1, 1, 0, 0, 0, tzinfo=timezone.utc), + datetime(2026, 2, 1, tzinfo=timezone.utc)), + ]) + def test_first_instant_of_next_month(self, now, expected): + assert metering.free_period_end(now) == expected + + def test_stable_within_a_month(self): + a = metering.free_period_end(datetime(2026, 7, 1, tzinfo=timezone.utc)) + b = metering.free_period_end(datetime(2026, 7, 31, 23, 59, tzinfo=timezone.utc)) + assert a == b + + def test_rolls_over_at_month_boundary(self): + july = metering.free_period_end(datetime(2026, 7, 31, 23, 59, tzinfo=timezone.utc)) + august = metering.free_period_end(datetime(2026, 8, 1, 0, 0, 1, tzinfo=timezone.utc)) + assert august > july