feat(billing): free plan (20 min/mes sin tarjeta) + retirar trial + opt-in galería UGC

- 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
This commit is contained in:
juancarlos.cavero 2026-07-20 00:26:21 +02:00
parent d5f2767d70
commit 9fd1cacb0c
22 changed files with 651 additions and 110 deletions

236
app.py
View file

@ -12,6 +12,7 @@ import zipfile
import math import math
import itertools import itertools
import asyncio import asyncio
from datetime import datetime, timezone
from dotenv import load_dotenv from dotenv import load_dotenv
from typing import Dict, Optional, List from typing import Dict, Optional, List
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
@ -123,8 +124,61 @@ def gemini_missing_error():
return HTTPException(status_code=400, detail="Missing X-Gemini-Key header") 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): 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). BYOK / self-host requests don't consume minutes (priority 2, no reservation).
For a managed (entitled, no BYOK header) request this probes the input 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. on the operator's key for free. Only skip metering when billing is off.
""" """
if not BILLING_ENABLED: if not BILLING_ENABLED:
return None, 2, None return None, 2, None, None
user = await _user_from_request(request) user = await _user_from_request(request)
if not managed_keys.has_active_entitlement(user): 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) 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, raise HTTPException(status_code=429,
detail="You already have the maximum number of jobs running. Please wait.") 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). # Probe input duration (blocking → run in a thread).
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
try: try:
@ -167,12 +240,22 @@ async def reserve_process_minutes(request, url, input_path, job_id):
try: try:
reservation_id = await _metering.reserve_minutes(user.id, minutes, job_id) reservation_id = await _metering.reserve_minutes(user.id, minutes, job_id)
except _metering.QuotaExceeded as e: except _metering.QuotaExceeded as e:
_maybe_send_quota_email(user)
raise HTTPException(status_code=402, detail={ raise HTTPException(status_code=402, detail={
"error": "quota_exceeded", "error": "quota_exceeded",
"minutes_required": e.required, "minutes_required": e.required,
"minutes_remaining": e.remaining, "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): 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: try:
return await _metering.reserve_minutes(user.id, minutes, job_id, job_type) return await _metering.reserve_minutes(user.id, minutes, job_id, job_type)
except _metering.QuotaExceeded as e: except _metering.QuotaExceeded as e:
_maybe_send_quota_email(user)
raise HTTPException(status_code=402, detail={ raise HTTPException(status_code=402, detail={
"error": "quota_exceeded", "error": "quota_exceeded",
"minutes_required": e.required, "minutes_required": e.required,
@ -412,6 +496,33 @@ async def process_queue():
print(f"❌ Queue dispatch error: {e}") print(f"❌ Queue dispatch error: {e}")
await asyncio.sleep(1) 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): async def run_job_wrapper(job_id):
"""Wrapper to run job and release semaphore""" """Wrapper to run job and release semaphore"""
try: try:
@ -428,6 +539,10 @@ async def run_job_wrapper(job_id):
await _archive_managed_job(job_id) await _archive_managed_job(job_id)
# Operational alerting for managed jobs (proxy out of credits / failures). # Operational alerting for managed jobs (proxy out of credits / failures).
await _record_job_alert(job_id) 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 # Always release semaphore and mark queue task done
concurrency_semaphore.release() concurrency_semaphore.release()
job_queue.task_done() 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()) 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): async def _record_job_alert(job_id):
if not BILLING_ENABLED: if not BILLING_ENABLED:
return return
@ -601,6 +743,14 @@ def enqueue_output(out, job_id):
for line in iter(out.readline, b''): for line in iter(out.readline, b''):
decoded_line = _scrub_secrets(line.decode('utf-8').strip()) decoded_line = _scrub_secrets(line.decode('utf-8').strip())
if decoded_line: 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}") print(f"📝 [Job Output] {decoded_line}")
if job_id in jobs: if job_id in jobs:
jobs[job_id]['logs'].append(decoded_line) 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") 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). # 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 # Enqueue Job
jobs[job_id] = { jobs[job_id] = {
@ -2249,6 +2403,15 @@ async def thumbnail_generate(
if not api_key: if not api_key:
raise gemini_missing_error() 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 # Clamp count
count = min(max(1, count), 6) count = min(max(1, count), 6)
@ -2944,6 +3107,9 @@ class SaaSGenerateRequest(BaseModel):
selected_actor_url: Optional[str] = None # Pre-selected actor image URL selected_actor_url: Optional[str] = None # Pre-selected actor image URL
retry_job_id: Optional[str] = None retry_job_id: Optional[str] = None
video_mode: str = "lowcost" # "lowcost" or "premium" 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") @app.post("/api/saasshorts/generate")
@ -3066,35 +3232,37 @@ async def saasshorts_generate(
} }
saas_jobs[job_id]["logs"].append("Video generation completed!") saas_jobs[job_id]["logs"].append("Video generation completed!")
# Upload to public gallery (non-blocking) # Upload to public gallery — opt-in only: the metadata carries
try: # the user's product name, URL and full script.
gallery_meta = { if req.share_to_gallery:
"title": req.script.get("title", "Untitled"), try:
"hook_text": req.script.get("hook_text", ""), gallery_meta = {
"caption": req.script.get("caption", ""), "title": req.script.get("title", "Untitled"),
"hashtags": req.script.get("hashtags", []), "hook_text": req.script.get("hook_text", ""),
"full_narration": req.script.get("full_narration", ""), "caption": req.script.get("caption", ""),
"actor_description": req.script.get("actor_description", ""), "hashtags": req.script.get("hashtags", []),
"style": req.script.get("style", "ugc"), "full_narration": req.script.get("full_narration", ""),
"language": req.script.get("language", "en"), "actor_description": req.script.get("actor_description", ""),
"duration": result.get("duration", 0), "style": req.script.get("style", "ugc"),
"video_mode": req.video_mode, "language": req.script.get("language", "en"),
"product_name": req.script.get("_product_name", ""), "duration": result.get("duration", 0),
"product_url": req.script.get("_product_url", ""), "video_mode": req.video_mode,
"segments": req.script.get("segments", []), "product_name": req.script.get("_product_name", ""),
"cost_estimate": result.get("cost_estimate", {}), "product_url": req.script.get("_product_url", ""),
} "segments": req.script.get("segments", []),
gallery_result = upload_video_to_gallery( "cost_estimate": result.get("cost_estimate", {}),
video_path=result["video_path"], }
actor_image_path=result.get("actor_image", ""), gallery_result = upload_video_to_gallery(
metadata=gallery_meta, video_path=result["video_path"],
video_id=job_id[:8], actor_image_path=result.get("actor_image", ""),
) metadata=gallery_meta,
if gallery_result: video_id=job_id[:8],
saas_jobs[job_id]["result"]["gallery_video_id"] = gallery_result["video_id"] )
log_msg("📤 Uploaded to public gallery.") if gallery_result:
except Exception as gallery_err: saas_jobs[job_id]["result"]["gallery_video_id"] = gallery_result["video_id"]
log_msg(f"⚠️ Gallery upload skipped: {gallery_err}") log_msg("📤 Uploaded to public gallery.")
except Exception as gallery_err:
log_msg(f"⚠️ Gallery upload skipped: {gallery_err}")
except Exception as e: except Exception as e:
print(f"[SaaSShorts] ❌ Job {job_id} failed: {e}") print(f"[SaaSShorts] ❌ Job {job_id} failed: {e}")

View file

@ -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 (float(t.minutes_total) - float(t.minutes_consumed) for t in topups), 0.0
) )
profile = await session.get(UploadPostProfile, user_id) profile = await session.get(UploadPostProfile, user_id)
# Entitled to managed keys if they have an active plan OR any top-up credit. # Entitled to managed keys with an active plan, any top-up credit, or the
entitled = bool(sub is not None or topup_remaining > 0) # 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( return CurrentUser(
id=user.id, id=user.id,
email=user.email, email=user.email,
entitled=entitled, 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, upload_post_profile=profile.profile_username if profile else None,
) )

View file

@ -106,7 +106,8 @@ async def _active_sub_exists(user_id) -> bool:
# unpaid / incomplete; those must still block, otherwise the user can spawn a # unpaid / incomplete; those must still block, otherwise the user can spawn a
# second subscription while the first one keeps dunning (real case: annual # second subscription while the first one keeps dunning (real case: annual
# trial -> end-trial -> card declined -> past_due, then a fresh monthly sub). # 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 ( return bool(sub and sub.status in (
"active", "trialing", "past_due", "unpaid", "incomplete", "paused", "active", "trialing", "past_due", "unpaid", "incomplete", "paused",
)) ))
@ -154,7 +155,8 @@ async def create_checkout(body: CheckoutRequest, request: Request):
"minutes": str(entry.get("minutes", "")), "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: if mode == "subscription" and TRIAL_DAYS > 0:
kwargs["subscription_data"] = {"trial_period_days": TRIAL_DAYS} kwargs["subscription_data"] = {"trial_period_days": TRIAL_DAYS}
session = await asyncio.to_thread(lambda: stripe.checkout.Session.create(**kwargs)) 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") @router.post("/api/billing/end-trial")
async def end_trial(request: Request): async def end_trial(request: Request):
"""End the free trial immediately: charge the card now and unlock full plan """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 activate their plan right away. The subscription webhook flips status→active
(and thus the full ``minutes_per_period`` allowance) once Stripe confirms.""" (and thus the full ``minutes_per_period`` allowance) once Stripe confirms."""
user = await get_current_user_required(request) 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( await send_admin_alert(
"🔻 Subscription canceled", "🔻 Subscription canceled",
f"A {plan} subscriber just canceled.\n" f"A {plan} subscriber just canceled.\n"
f"Access continues until {end_dt:%Y-%m-%d}; their videos are then kept " f"Access continues until {end_dt:%Y-%m-%d}. Google-authed users then "
f"{VIDEO_RETENTION_GRACE_DAYS} more days before deletion.", f"drop to the free plan (clips expire after 7 days); others keep their "
f"videos {VIDEO_RETENTION_GRACE_DAYS} more days before deletion.",
) )

View file

@ -27,14 +27,32 @@ PLAN_MINUTES = {
"pro": 750, "pro": 750,
} }
# Free trial length (days) for new subscriptions. Card required; auto-charges at # Free plan: monthly allowance for Google-authenticated users with no
# the end. # subscription. No Stripe object exists for it — it is resolved entirely in
TRIAL_DAYS = 3 # 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, # Free trial length (days) for new subscriptions. Trials are retired in favor
# but bounds the free managed-compute / proxy exposure per sign-up so a # of the free plan; the checkout only injects trial_period_days when > 0, and
# cancel-before-charge account can't burn a full plan's worth of minutes. Once the # existing 'trialing' subscriptions are still honored until they convert or
# trial converts to an active subscription the full plan allowance applies. # 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 TRIAL_MINUTE_CAP = 20
# Gemini IMAGE generation (thumbnails) is the one expensive managed Gemini call # Gemini IMAGE generation (thumbnails) is the one expensive managed Gemini call
@ -75,6 +93,7 @@ PLAN_PRIORITY = {
"pro": 0, "pro": 0,
"creator": 1, "creator": 1,
"starter": 1, "starter": 1,
"free": 2,
} }
# Max simultaneous managed jobs per user, by plan. # Max simultaneous managed jobs per user, by plan.
@ -82,6 +101,7 @@ PLAN_JOB_LIMIT = {
"pro": 3, "pro": 3,
"creator": 2, "creator": 2,
"starter": 2, "starter": 2,
"free": 1,
} }

View file

@ -56,3 +56,41 @@ async def send_magic_link_email(email: str, link: str):
</div> </div>
""" """
await send_email(email, "Your OpenShorts sign-in link", html) 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"""
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
<h2>Your clips are ready 🎬</h2>
<p><strong>{title}</strong> produced {clip_count} viral-ready
clip{'s' if clip_count != 1 else ''}. They're waiting in your dashboard.</p>
<p><a href="{dashboard_url}" style="display:inline-block;background:#111;color:#fff;
padding:12px 20px;border-radius:8px;text-decoration:none">View my clips</a></p>
<p style="color:#666;font-size:13px">Enjoying OpenShorts? A
<a href="{GITHUB_REPO_URL}" style="color:#666">star on GitHub</a> helps a lot ⭐</p>
</div>
"""
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"""
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
<h2>You've used your free minutes 🚀</h2>
<p>You've hit this month's free allowance. That usually means the clips
are working for you — Starter gives you <strong>100 minutes a month</strong>,
no watermark, and a durable clip library.</p>
<p><a href="{upgrade_url}" style="display:inline-block;background:#111;color:#fff;
padding:12px 20px;border-radius:8px;text-decoration:none">See plans</a></p>
<p style="color:#666;font-size:13px">Your free minutes reset on the 1st of
every month.</p>
</div>
"""
await send_email(email, "You've used your free OpenShorts minutes", html)

View file

@ -120,6 +120,42 @@ async def _active_subscription(session, user_id):
return None 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: async def _plan_used_this_period(session, user_id, period_end) -> Decimal:
total = (await session.execute( total = (await session.execute(
select(func.coalesce(func.sum(UsageLedger.minutes_from_plan), 0)).where(and_( select(func.coalesce(func.sum(UsageLedger.minutes_from_plan), 0)).where(and_(
@ -138,23 +174,43 @@ async def _topups_fifo(session, user_id):
)).scalars()) )).scalars())
async def _balance(session, user_id): async def _balance(session, user_id, user=None):
"""Return a dict of the user's current minute balance (read-only).""" """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) sub = await _active_subscription(session, user_id)
plan_allowance = _D(sub.minutes_per_period) if sub else _D(0) if sub:
# During the trial, cap the allowance so a cancel-before-charge account can't plan_name = sub.plan
# burn a whole plan's worth of managed minutes. Full allowance once active. plan_allowance = _D(sub.minutes_per_period)
if sub and sub.status == "trialing": # During the trial, cap the allowance so a cancel-before-charge account
plan_allowance = min(plan_allowance, _D(config.TRIAL_MINUTE_CAP)) # can't burn a whole plan's worth of managed minutes. Kept for
period_end = sub.current_period_end if sub else None # grandfathered 'trialing' subscriptions.
plan_used = await _plan_used_this_period(session, user_id, period_end) if sub else _D(0) 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) plan_remaining = max(_D(0), plan_allowance - plan_used)
topups = await _topups_fifo(session, user_id) topups = await _topups_fifo(session, user_id)
topup_remaining = sum((_D(t.minutes_total) - _D(t.minutes_consumed) for t in topups), _D(0)) topup_remaining = sum((_D(t.minutes_total) - _D(t.minutes_consumed) for t in topups), _D(0))
return { return {
"plan": sub.plan if sub else None, "plan": plan_name,
"plan_allowance": float(plan_allowance), "plan_allowance": float(plan_allowance),
"plan_used": float(plan_used), "plan_used": float(plan_used),
"plan_remaining": float(plan_remaining), "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) minutes = _D(minutes)
async with database.session() as session: async with database.session() as session:
async with session.begin(): async with session.begin():
# Serialize all of this user's reservations. # Serialize all of this user's reservations. Selecting the full row
await session.execute( # (same lock semantics) lets _balance skip a second User lookup.
select(User.id).where(User.id == user_id).with_for_update() locked_user = (await session.execute(
) select(User).where(User.id == user_id).with_for_update()
b = await _balance(session, user_id) )).scalar_one_or_none()
b = await _balance(session, user_id, user=locked_user)
plan_remaining = b["_plan_remaining_d"] plan_remaining = b["_plan_remaining_d"]
remaining_total = _D(b["remaining"]) remaining_total = _D(b["remaining"])
if minutes > remaining_total: if minutes > remaining_total:

View file

@ -9,8 +9,8 @@ from datetime import timedelta
from fastapi import APIRouter, HTTPException, Request from fastapi import APIRouter, HTTPException, Request
from sqlalchemy import select, delete from sqlalchemy import select, delete
from .config import settings, VIDEO_RETENTION_GRACE_DAYS from .config import settings, VIDEO_RETENTION_GRACE_DAYS, FREE_CLIP_RETENTION_DAYS
from . import database, storage from . import database, storage, metering
from .models import UserVideo, Subscription, Project from .models import UserVideo, Subscription, Project
from .auth import get_current_user_required from .auth import get_current_user_required
@ -260,6 +260,12 @@ async def purge_expired():
continue continue
if last_event_at + timedelta(days=VIDEO_RETENTION_GRACE_DAYS) > now: if last_event_at + timedelta(days=VIDEO_RETENTION_GRACE_DAYS) > now:
continue 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? # Any videos or projects left?
async with database.session() as s: async with database.session() as s:
has = (await s.execute( has = (await s.execute(
@ -280,6 +286,53 @@ async def purge_expired():
print(f"⚠️ Video purge failed for {user_id}: {e}") 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 _SWEEP_INTERVAL = 6 * 3600 # every 6 hours
@ -288,6 +341,7 @@ async def _sweeper_loop():
try: try:
await asyncio.sleep(_SWEEP_INTERVAL) await asyncio.sleep(_SWEEP_INTERVAL)
await purge_expired() await purge_expired()
await purge_free_expired()
except asyncio.CancelledError: except asyncio.CancelledError:
break break
except Exception as e: except Exception as e:

View file

@ -11,6 +11,7 @@ import UGCGallery from './components/UGCGallery';
import ScheduleWeekModal from './components/ScheduleWeekModal'; import ScheduleWeekModal from './components/ScheduleWeekModal';
import UsageMeter from './components/UsageMeter'; import UsageMeter from './components/UsageMeter';
import TopUpModal from './components/TopUpModal'; import TopUpModal from './components/TopUpModal';
import StarBanner from './components/StarBanner';
import TrialUpgradeModal from './components/TrialUpgradeModal'; import TrialUpgradeModal from './components/TrialUpgradeModal';
import LoginModal from './components/LoginModal'; import LoginModal from './components/LoginModal';
import TrialGate from './components/TrialGate'; import TrialGate from './components/TrialGate';
@ -1350,6 +1351,20 @@ function App() {
)} )}
</h2> </h2>
{status === 'complete' && results?.clips?.length > 0 && (
<div className="mb-2 space-y-2">
<StarBanner message="Happy with your clips?" />
{plan === 'free' && (
<button
onClick={() => { window.location.hash = '#/pricing'; }}
className="w-full text-left px-3 py-2 rounded-input bg-paper3 border border-rule text-sm text-muted hover:text-ink transition-colors"
>
Free clips carry a watermark and expire in 7 days — <span className="text-brass">upgrade to remove both</span>.
</button>
)}
</div>
)}
<div className="flex-1 overflow-y-auto custom-scrollbar p-1"> <div className="flex-1 overflow-y-auto custom-scrollbar p-1">
{results && results.clips && results.clips.length > 0 ? ( {results && results.clips && results.clips.length > 0 ? (
<div className={`grid gap-4 pb-10 ${status === 'complete' ? 'grid-cols-1 xl:grid-cols-2' : 'grid-cols-1'}`}> <div className={`grid gap-4 pb-10 ${status === 'complete' ? 'grid-cols-1 xl:grid-cols-2' : 'grid-cols-1'}`}>

View file

@ -151,7 +151,7 @@ export default function Landing({ onLaunchApp }) {
const faqs = [ const faqs = [
{ {
question: "Is OpenShorts really free? What's the catch?", 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?", question: "What is OpenShorts and how does it work?",
@ -257,7 +257,7 @@ export default function Landing({ onLaunchApp }) {
<div className="flex flex-wrap items-center gap-4 mb-5"> <div className="flex flex-wrap items-center gap-4 mb-5">
{billingEnabled ? ( {billingEnabled ? (
<a href="#pricing" className="btn-primary whitespace-nowrap"> <a href="#pricing" className="btn-primary whitespace-nowrap">
start free trial start free
<ArrowRight size={16} /> <ArrowRight size={16} />
</a> </a>
) : ( ) : (
@ -274,7 +274,7 @@ export default function Landing({ onLaunchApp }) {
</div> </div>
<p className="text-sm text-muted lowercase"> <p className="text-sm text-muted lowercase">
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?{' '}
<a <a
href="https://github.com/mutonby/openshorts" href="https://github.com/mutonby/openshorts"
target="_blank" target="_blank"
@ -398,7 +398,7 @@ export default function Landing({ onLaunchApp }) {
</ul> </ul>
{billingEnabled ? ( {billingEnabled ? (
<a href="#pricing" className="btn-primary whitespace-nowrap"> <a href="#pricing" className="btn-primary whitespace-nowrap">
start free trial <ArrowRight size={16} /> start free <ArrowRight size={16} />
</a> </a>
) : ( ) : (
<button onClick={onLaunchApp} className="btn-primary whitespace-nowrap"> <button onClick={onLaunchApp} className="btn-primary whitespace-nowrap">
@ -431,7 +431,7 @@ export default function Landing({ onLaunchApp }) {
<section id="pricing" className="py-20 px-6 border-t border-rule"> <section id="pricing" className="py-20 px-6 border-t border-rule">
<div className="max-w-6xl mx-auto"> <div className="max-w-6xl mx-auto">
<SectionHeader eyebrow="03 · Pricing" title="Simple, transparent pricing"> <SectionHeader eyebrow="03 · Pricing" title="Simple, transparent pricing">
3-day free trial with 20 free minutes. Cancel anytime. Free plan with 20 minutes a month — no credit card. Cancel anytime.
</SectionHeader> </SectionHeader>
<PricingSection onRequireLogin={() => { window.location.hash = '#/pricing'; }} /> <PricingSection onRequireLogin={() => { window.location.hash = '#/pricing'; }} />
</div> </div>
@ -698,11 +698,11 @@ export default function Landing({ onLaunchApp }) {
<section className="py-24 px-6 border-t border-rule"> <section className="py-24 px-6 border-t border-rule">
<div className="max-w-3xl mx-auto text-center"> <div className="max-w-3xl mx-auto text-center">
<h2 className="font-display text-4xl md:text-5xl lowercase text-ink tracking-tight mb-5">start creating viral videos today.</h2> <h2 className="font-display text-4xl md:text-5xl lowercase text-ink tracking-tight mb-5">start creating viral videos today.</h2>
<p className="text-muted mb-10 max-w-xl mx-auto leading-relaxed lowercase">3-day free trial · 20 free minutes · no watermarks — or self-host free with docker.</p> <p className="text-muted mb-10 max-w-xl mx-auto leading-relaxed lowercase">free plan · 20 min/month · no credit card — or self-host free with docker.</p>
<div className="flex flex-wrap items-center justify-center gap-4"> <div className="flex flex-wrap items-center justify-center gap-4">
{billingEnabled ? ( {billingEnabled ? (
<a href="#pricing" className="btn-primary whitespace-nowrap"> <a href="#pricing" className="btn-primary whitespace-nowrap">
start free trial start free
<ArrowRight size={16} /> <ArrowRight size={16} />
</a> </a>
) : ( ) : (

View file

@ -55,9 +55,9 @@ export default function Legal() {
your own machine with your own API keys. No account, no payment, no data held by us. your own machine with your own API keys. No account, no payment, no data held by us.
</li> </li>
<li> <li>
<strong className="text-ink">Hosted at openshorts.app (paid):</strong> we run everything for <strong className="text-ink">Hosted at openshorts.app:</strong> we run everything for
you. It requires an account and a paid subscription (with a free trial), and we store the you. It requires an account and offers a free plan and paid subscriptions; we store the
videos you generate while your subscription is active. videos you generate subject to the retention rules below.
</li> </li>
</ul> </ul>
<p>By using the hosted Service you agree to the terms below.</p> <p>By using the hosted Service you agree to the terms below.</p>
@ -71,7 +71,7 @@ export default function Legal() {
</p> </p>
</Section> </Section>
<Section title="Free trial, plans & billing"> <Section title="Free plan, paid plans & billing">
<p> <p>
Paid plans are <strong className="text-ink">Starter ($12/mo · 100 min)</strong>,{' '} Paid plans are <strong className="text-ink">Starter ($12/mo · 100 min)</strong>,{' '}
<strong className="text-ink">Creator ($29/mo · 300 min)</strong> and{' '} <strong className="text-ink">Creator ($29/mo · 300 min)</strong> and{' '}
@ -80,18 +80,21 @@ export default function Legal() {
minutes can be bought as one-off top-ups. minutes can be bought as one-off top-ups.
</p> </p>
<p> <p>
<strong className="text-ink">Free trial:</strong> new subscriptions start with a{' '} <strong className="text-ink">Free plan:</strong> accounts signed in with Google get{' '}
<strong className="text-ink">3-day free trial</strong> that includes up to{' '} <strong className="text-ink">20 minutes</strong> of video processing per calendar month at no
<strong className="text-ink">20 minutes</strong> of video processing. You provide a payment cost and with no payment method required. Free clips carry a watermark and are stored for{' '}
method up front but are <strong className="text-ink">not charged during the trial</strong>. If <strong className="text-ink">7 days</strong>, after which they are deleted. Free allowances,
you do not cancel before the trial ends, your subscription automatically begins, your full plan limits and features may change; the free plan may not be available to accounts we reasonably
minutes unlock, and your payment method is charged the plan price. You can cancel at any time from believe are abusing it (e.g. duplicate accounts).
your account.
</p> </p>
<p> <p>
<strong className="text-ink">Auto-renewal:</strong> subscriptions renew automatically each <strong className="text-ink">Auto-renewal:</strong> paid subscriptions renew automatically each
period (monthly or yearly) at the then-current price until you cancel. We'll email a reminder period (monthly or yearly) at the then-current price until you cancel.
before the trial converts to a paid subscription. </p>
<p>
<strong className="text-ink">Legacy trials:</strong> subscriptions started before the free plan
existed may include a 3-day free trial under the terms shown at their sign-up; those trials
convert or cancel per Stripe's standard flow.
</p> </p>
<p> <p>
Payments are processed by <strong className="text-ink">Stripe</strong>. We never see or store Payments are processed by <strong className="text-ink">Stripe</strong>. We never see or store

View file

@ -99,9 +99,15 @@ export default function AccountPage() {
<span className="badge-warn">cancels at period end</span> <span className="badge-warn">cancels at period end</span>
)} )}
</div> </div>
<button onClick={openPortal} disabled={busy} className="btn-ghost px-4 py-2 shrink-0"> {plan === 'free' ? (
<CreditCard size={16} /> Manage billing <button onClick={() => { window.location.hash = '#/pricing'; }} className="btn-primary px-4 py-2 shrink-0 text-xs">
</button> Upgrade
</button>
) : (
<button onClick={openPortal} disabled={busy} className="btn-ghost px-4 py-2 shrink-0">
<CreditCard size={16} /> Manage billing
</button>
)}
</div> </div>
<div className="space-y-2"> <div className="space-y-2">

View file

@ -12,7 +12,7 @@ export default function AdvancedBanner({ needsPlan, onKeys }) {
<div className="text-ink2 lowercase"> <div className="text-ink2 lowercase">
<span className="font-medium text-ink">Advanced tool.</span>{' '} <span className="font-medium text-ink">Advanced tool.</span>{' '}
{needsPlan {needsPlan
? <>Start your <span className="font-medium text-ink">3-day free trial</span> to unlock. This tool also uses your own <span className="font-medium text-ink normal-case">fal.ai + ElevenLabs</span> keys (you pay those providers).</> ? <>Sign in with <span className="font-medium text-ink">Google</span> to unlock free. This tool also uses your own <span className="font-medium text-ink normal-case">fal.ai + ElevenLabs</span> keys (you pay those providers).</>
: <>AI video &amp; voice generation use your own <span className="font-medium text-ink normal-case">fal.ai + ElevenLabs</span> keys — add them in Settings. Script &amp; orchestration are included in your plan.</>} : <>AI video &amp; voice generation use your own <span className="font-medium text-ink normal-case">fal.ai + ElevenLabs</span> keys — add them in Settings. Script &amp; orchestration are included in your plan.</>}
</div> </div>
</div> </div>

View file

@ -6,7 +6,7 @@ import PricingSection from './PricingSection';
const FAQS = [ const FAQS = [
{ {
question: "Is OpenShorts really free? What's the catch?", 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?", question: "How does OpenShorts compare to Opus Clip?",
@ -61,8 +61,8 @@ const TRUST_CARDS = [
eyebrow: 'cancel anytime', eyebrow: 'cancel anytime',
body: ( body: (
<> <>
3-day free trial with up to 20 minutes included; you are not charged during the trial. Start on the free plan — 20 minutes a month, no credit card. Billing for paid
Billing runs on Stripe — cancel anytime from your account. plans runs on Stripe — cancel anytime from your account.
</> </>
), ),
}, },
@ -123,7 +123,7 @@ export default function PricingPage({ onRequireLogin }) {
<h1 className="font-display lowercase text-ink tracking-tight text-4xl md:text-6xl leading-[1.02] mb-5"> <h1 className="font-display lowercase text-ink tracking-tight text-4xl md:text-6xl leading-[1.02] mb-5">
start clipping in minutes. start clipping in minutes.
</h1> </h1>
<p className="readout">3-day free trial · 20 free minutes · cancel anytime</p> <p className="readout">free plan · 20 min/month · no credit card</p>
</div> </div>
</header> </header>
@ -197,11 +197,11 @@ export default function PricingPage({ onRequireLogin }) {
<section className="px-6 py-24 border-t border-rule"> <section className="px-6 py-24 border-t border-rule">
<div className="max-w-3xl mx-auto text-center"> <div className="max-w-3xl mx-auto text-center">
<h2 className="font-display text-4xl md:text-5xl lowercase text-ink tracking-tight mb-10"> <h2 className="font-display text-4xl md:text-5xl lowercase text-ink tracking-tight mb-10">
three free days. twenty free minutes. no charge until you decide. twenty free minutes. every month. no card until you decide.
</h2> </h2>
<div className="flex flex-wrap items-center justify-center gap-4"> <div className="flex flex-wrap items-center justify-center gap-4">
<button onClick={scrollToPlans} className="btn-primary whitespace-nowrap"> <button onClick={scrollToPlans} className="btn-primary whitespace-nowrap">
start free trial start free
<ArrowRight size={16} /> <ArrowRight size={16} />
</button> </button>
<a <a

View file

@ -11,11 +11,12 @@ const PLAN_BLURB = {
pro: 'For power users & teams', pro: 'For power users & teams',
}; };
const HIGHLIGHT = 'creator'; const HIGHLIGHT = 'creator';
const FREE_MINUTES = 20;
const fmt = (amount, currency) => const fmt = (amount, currency) =>
new Intl.NumberFormat('en-US', { style: 'currency', currency: (currency || 'usd').toUpperCase(), maximumFractionDigits: 0 }).format((amount || 0) / 100); 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 }) { export default function PricingSection({ onRequireLogin }) {
const { isSignedIn } = useAuth(); const { isSignedIn } = useAuth();
const [plans, setPlans] = useState([]); const [plans, setPlans] = useState([]);
@ -66,7 +67,30 @@ export default function PricingSection({ onRequireLogin }) {
/> />
</div> </div>
<div className="grid md:grid-cols-3 gap-6"> <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6">
{/* Free tier — no card, Google sign-in only */}
<div className="relative card p-6 flex flex-col">
<h3 className="font-display lowercase text-xl text-ink">free</h3>
<p className="text-muted text-sm mb-4 lowercase">Try it on your own videos</p>
<div className="mb-4 flex items-baseline gap-1.5">
<span className="font-display text-4xl text-ink tabular-nums">$0</span>
<span className="readout">/mo</span>
</div>
<ul className="space-y-2 text-sm text-ink2 mb-6 flex-1">
<li className="flex items-start gap-2"><Check size={16} className="text-ok shrink-0 mt-0.5" /> <span><b>{FREE_MINUTES} min</b> of video / month</span></li>
<li className="flex items-start gap-2"><Check size={16} className="text-ok shrink-0 mt-0.5" /> <span>YouTube URL or upload</span></li>
<li className="flex items-start gap-2"><Check size={16} className="text-ok shrink-0 mt-0.5" /> <span>No credit card — Google sign-in</span></li>
<li className="flex items-start gap-2"><Check size={16} className="text-muted shrink-0 mt-0.5" /> <span className="text-muted">Watermark · clips kept 7 days</span></li>
</ul>
<button
onClick={() => { if (!isSignedIn) { onRequireLogin?.(null); } else { window.location.hash = ''; } }}
className="w-full btn-ghost"
>
Start free
</button>
<p className="text-center text-xs text-muted mt-2 lowercase">free minutes reset monthly.</p>
</div>
{PLAN_ORDER.map((plan) => { {PLAN_ORDER.map((plan) => {
const entry = byPlan(plan); const entry = byPlan(plan);
if (!entry) return null; if (!entry) return null;
@ -98,9 +122,9 @@ export default function PricingSection({ onRequireLogin }) {
disabled={busyPrice === entry.price_id} disabled={busyPrice === entry.price_id}
className={`w-full ${highlight ? 'btn-primary' : 'btn-ghost'}`} className={`w-full ${highlight ? 'btn-primary' : 'btn-ghost'}`}
> >
{busyPrice === entry.price_id ? <Loader2 size={18} className="animate-spin" /> : 'Start 3-day free trial'} {busyPrice === entry.price_id ? <Loader2 size={18} className="animate-spin" /> : `Get ${plan}`}
</button> </button>
<p className="text-center text-xs text-muted mt-2 lowercase">3 days free, then billed monthly. Cancel anytime.</p> <p className="text-center text-xs text-muted mt-2 lowercase">billed {interval === 'month' ? 'monthly' : 'yearly'}. cancel anytime.</p>
</div> </div>
); );
})} })}
@ -164,7 +188,7 @@ export default function PricingSection({ onRequireLogin }) {
</div> </div>
<p className="text-center text-muted text-xs mt-6 lowercase"> <p className="text-center text-muted text-xs mt-6 lowercase">
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.
</p> </p>
</div> </div>
); );

View file

@ -40,7 +40,7 @@ export default function ProfileMenu() {
onClick={() => { setOpen(false); window.location.hash = '#/pricing'; }} 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" className="w-full flex items-center gap-3 px-4 py-2.5 text-sm lowercase text-brass hover:bg-paper3 transition-colors"
> >
<Sparkles size={16} /> Start free trial <Sparkles size={16} /> Start free
</button> </button>
)} )}
<button <button

View file

@ -4,6 +4,7 @@ import { getApiUrl } from '../config';
import { apiFetch } from '../lib/api'; import { apiFetch } from '../lib/api';
import StepIndicator from './ui/StepIndicator'; import StepIndicator from './ui/StepIndicator';
import SegmentedControl from './ui/SegmentedControl'; import SegmentedControl from './ui/SegmentedControl';
import StarBanner from './StarBanner';
const STYLE_OPTIONS = [ const STYLE_OPTIONS = [
{ id: 'ugc', label: 'UGC Natural', desc: 'Authentic, talking to camera' }, { id: 'ugc', label: 'UGC Natural', desc: 'Authentic, talking to camera' },
@ -69,6 +70,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
const [selectedScript, setSelectedScript] = useState(0); const [selectedScript, setSelectedScript] = useState(0);
// Step 2: Configure // Step 2: Configure
const [shareToGallery, setShareToGallery] = useState(false);
const [voices, setVoices] = useState([]); const [voices, setVoices] = useState([]);
const [selectedVoice, setSelectedVoice] = useState('21m00Tcm4TlvDq8ikWAM'); const [selectedVoice, setSelectedVoice] = useState('21m00Tcm4TlvDq8ikWAM');
const [actorDescription, setActorDescription] = useState(''); const [actorDescription, setActorDescription] = useState('');
@ -296,6 +298,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
actor_description: actorDescription || undefined, actor_description: actorDescription || undefined,
selected_actor_url: selectedActor || undefined, selected_actor_url: selectedActor || undefined,
video_mode: videoMode, video_mode: videoMode,
share_to_gallery: shareToGallery,
}), }),
}); });
@ -342,6 +345,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
actor_description: actorDescription || undefined, actor_description: actorDescription || undefined,
retry_job_id: jobId, retry_job_id: jobId,
video_mode: videoMode, video_mode: videoMode,
share_to_gallery: shareToGallery,
}), }),
}); });
@ -1121,6 +1125,21 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
Set them in Settings. Set them in Settings.
</div> </div>
)} )}
<label className="flex items-start gap-2 text-sm text-ink cursor-pointer">
<input
type="checkbox"
checked={shareToGallery}
onChange={(e) => setShareToGallery(e.target.checked)}
className="mt-0.5 accent-brass"
/>
<span>
Share this video in the public gallery
<span className="block text-xs text-muted">
Your video, product name and script will be visible at openshorts.app/gallery
</span>
</span>
</label>
</div> </div>
<div className="flex justify-between"> <div className="flex justify-between">
@ -1257,6 +1276,10 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
Your Short is Ready Your Short is Ready
</h2> </h2>
<div className="mb-4">
<StarBanner message="Happy with your short?" />
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6"> <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Video Player */} {/* Video Player */}
<div className="card aspect-[9/16] max-h-[500px] bg-black overflow-hidden relative"> <div className="card aspect-[9/16] max-h-[500px] bg-black overflow-hidden relative">

View file

@ -0,0 +1,19 @@
import { Github } from 'lucide-react';
export const REPO_URL = 'https://github.com/mutonby/openshorts';
// Small "star us" ask, placed at high-delight moments (clips just rendered)
// and at the free-plan ceiling (out-of-minutes modal). No incentive attached.
export default function StarBanner({ message = 'Enjoying OpenShorts?' }) {
return (
<a
href={REPO_URL}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-2 px-3 py-2 rounded-input bg-paper3 border border-rule text-sm text-muted hover:text-ink transition-colors"
>
<Github size={14} className="shrink-0" />
<span>{message} <span className="text-brass">Star us on GitHub ⭐</span></span>
</a>
);
}

View file

@ -2,6 +2,7 @@ import React, { useState, useEffect } from 'react';
import { Loader2, Zap } from 'lucide-react'; import { Loader2, Zap } from 'lucide-react';
import { apiJson } from '../lib/api'; import { apiJson } from '../lib/api';
import Modal from './ui/Modal'; import Modal from './ui/Modal';
import StarBanner from './StarBanner';
// Opens when a job hits a 402 (quota exceeded). Lets the user buy more minutes. // Opens when a job hits a 402 (quota exceeded). Lets the user buy more minutes.
export default function TopUpModal({ onClose, required, remaining }) { export default function TopUpModal({ onClose, required, remaining }) {
@ -46,6 +47,9 @@ export default function TopUpModal({ onClose, required, remaining }) {
{topups.length === 0 && <div className="col-span-2 flex justify-center py-4"><Loader2 className="animate-spin text-brass" /></div>} {topups.length === 0 && <div className="col-span-2 flex justify-center py-4"><Loader2 className="animate-spin text-brass" /></div>}
</div> </div>
<p className="text-muted text-xs mt-4 text-center lowercase">Or upgrade your plan for more monthly minutes.</p> <p className="text-muted text-xs mt-4 text-center lowercase">Or upgrade your plan for more monthly minutes.</p>
<div className="mt-4">
<StarBanner message="Not ready to buy?" />
</div>
</Modal> </Modal>
); );
} }

View file

@ -1,8 +1,9 @@
import React from 'react'; import React from 'react';
import { Sparkles, ArrowRight } from 'lucide-react'; import { Sparkles, ArrowRight } from 'lucide-react';
// Slim, non-blocking banner shown above a tool when a hosted user has no active // Slim, non-blocking banner shown above a tool when a hosted user has no
// plan/trial. The tool stays visible below; actions still route to pricing. // entitlement. Google-authed users get the free plan automatically, so this
// only fires for signed-out or magic-link-only accounts.
export default function TrialGate({ toolName = 'this' }) { export default function TrialGate({ toolName = 'this' }) {
return ( return (
<div className="card mx-6 mt-3 px-4 py-3 flex items-center justify-between gap-4 shrink-0 animate-fade"> <div className="card mx-6 mt-3 px-4 py-3 flex items-center justify-between gap-4 shrink-0 animate-fade">
@ -10,15 +11,15 @@ export default function TrialGate({ toolName = 'this' }) {
<Sparkles size={16} className="shrink-0 text-brass" /> <Sparkles size={16} className="shrink-0 text-brass" />
<div className="text-ink2 lowercase"> <div className="text-ink2 lowercase">
<span className="font-medium text-ink">Preview mode.</span>{' '} <span className="font-medium text-ink">Preview mode.</span>{' '}
Start your <span className="font-medium text-ink">3-day free trial</span> to generate with {toolName} — Sign in with <span className="font-medium text-ink">Google</span> to use {toolName} free —
no API keys, from $12/mo. <span className="text-muted">Or run it free by self-hosting.</span> 20 min/month, no credit card. <span className="text-muted">Or run it free by self-hosting.</span>
</div> </div>
</div> </div>
<button <button
onClick={() => { window.location.hash = '#/pricing'; }} onClick={() => { window.location.hash = '#/pricing'; }}
className="btn-primary shrink-0 text-xs px-4 py-2" className="btn-primary shrink-0 text-xs px-4 py-2"
> >
See plans <ArrowRight size={14} /> Start free <ArrowRight size={14} />
</button> </button>
</div> </div>
); );

View file

@ -65,8 +65,9 @@ export function AuthProvider({ children }) {
} }
} }
const signedInMe = await refreshMe(); const signedInMe = await refreshMe();
// New sign-ups (and anyone without an active plan/trial) go straight to // Google sign-ins are entitled (free plan) and land in the app; only
// pricing so they can start their free trial; entitled users land in the app. // 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'; if (signedInMe?.user && !signedInMe?.entitled) destination = '#/pricing';
} catch (e) { } catch (e) {
// fall through — user lands signed-out // fall through — user lands signed-out

48
main.py
View file

@ -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): def _attempt(extractor_args, fmt):
with yt_dlp.YoutubeDL(_base_opts(extractor_args)) as ydl: with yt_dlp.YoutubeDL(_base_opts(extractor_args)) as ydl:
info = ydl.extract_info(url, download=False) info = ydl.extract_info(url, download=False)
@ -599,6 +609,7 @@ def download_youtube_video(url, output_dir="."):
'format': fmt, 'format': fmt,
'outtmpl': os.path.join(output_dir, f'{sanitized}.%(ext)s'), 'outtmpl': os.path.join(output_dir, f'{sanitized}.%(ext)s'),
'merge_output_format': 'mp4', 'overwrites': True, 'merge_output_format': 'mp4', 'overwrites': True,
'progress_hooks': [_progress_hook],
} }
with yt_dlp.YoutubeDL(dl_opts) as ydl: with yt_dlp.YoutubeDL(dl_opts) as ydl:
ydl.download([url]) ydl.download([url])
@ -641,6 +652,10 @@ Technical Details: {str(last_err)}
downloaded_file = os.path.join(output_dir, f) downloaded_file = os.path.join(output_dir, f)
break 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}") print(f"✅ Video downloaded in {time.time() - step_start_time:.2f}s: {downloaded_file}")
return downloaded_file, sanitized_title 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) 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): 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 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) subprocess.run(cut_command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
success = render_clip(clip_temp_path, clip_final_path, output_format) 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: if success:
print(f" ✅ Clip {i+1} ready: {clip_final_path}") print(f" ✅ Clip {i+1} ready: {clip_final_path}")
return success return success

View file

@ -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