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.
+ """
+ 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.
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 && (
+
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 }) {
- 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
) : (
- 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.
@@ -1257,6 +1276,10 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
Your Short is Ready
+
+
+
+
{/* Video Player */}
diff --git a/dashboard/src/components/StarBanner.jsx b/dashboard/src/components/StarBanner.jsx
new file mode 100644
index 0000000..295eb22
--- /dev/null
+++ b/dashboard/src/components/StarBanner.jsx
@@ -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 (
+
+
+ {message} Star us on GitHub ⭐
+
+ );
+}
diff --git a/dashboard/src/components/TopUpModal.jsx b/dashboard/src/components/TopUpModal.jsx
index b975db2..599a94e 100644
--- a/dashboard/src/components/TopUpModal.jsx
+++ b/dashboard/src/components/TopUpModal.jsx
@@ -2,6 +2,7 @@ import React, { useState, useEffect } from 'react';
import { Loader2, Zap } from 'lucide-react';
import { apiJson } from '../lib/api';
import Modal from './ui/Modal';
+import StarBanner from './StarBanner';
// Opens when a job hits a 402 (quota exceeded). Lets the user buy more minutes.
export default function TopUpModal({ onClose, required, remaining }) {
@@ -46,6 +47,9 @@ export default function TopUpModal({ onClose, required, remaining }) {
{topups.length === 0 &&
}
Or upgrade your plan for more monthly minutes.
+
+
+
);
}
diff --git a/dashboard/src/components/TrialGate.jsx b/dashboard/src/components/TrialGate.jsx
index 8318bd2..b8e1d30 100644
--- a/dashboard/src/components/TrialGate.jsx
+++ b/dashboard/src/components/TrialGate.jsx
@@ -1,8 +1,9 @@
import React from 'react';
import { Sparkles, ArrowRight } from 'lucide-react';
-// Slim, non-blocking banner shown above a tool when a hosted user has no active
-// plan/trial. The tool stays visible below; actions still route to pricing.
+// Slim, non-blocking banner shown above a tool when a hosted user has no
+// 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' }) {
return (
Preview mode.{' '}
- Start your 3-day free trial to generate with {toolName} —
- no API keys, from $12/mo. Or run it free by self-hosting.
+ Sign in with Google to use {toolName} free —
+ 20 min/month, no credit card. Or run it free by self-hosting.