feat: add hosted paid mode (managed keys, Stripe trial, metering)

Adds an optional cloud/paid mode behind a BILLING_ENABLED flag. With the flag
off the app is byte-identical to today's self-hosted BYOK build (regression-zero).

Backend (cloud/ package, only imported when BILLING_ENABLED):
- Auth: magic link (Resend) + Google OAuth (authlib) + JWT sessions
- Stripe: hosted Checkout with 3-day card trial, Customer Portal, idempotent
  order-safe webhooks; 3 plans (Starter/Creator/Pro) resolved by lookup_key
- Postgres + SQLAlchemy async; atomic minute metering (reserve/commit/release,
  plan->topup FIFO, restart-safe) with sweeper
- Managed keys: Gemini + Upload-Post server-side for entitled users; paid-only
  (BYOK core header ignored on hosted); Upload-Post white-label per-user profiles
- Metering wired into /api/process (probe->reserve->402, priority queue) and
  thumbnail image generation (3 min/batch)
- yt-dlp residential PROXY_URL support + 720p cap for hosted YouTube downloads

Frontend:
- AuthContext, LoginModal, PricingSection (3-day trial), AccountPage, UsageMeter,
  TopUpModal, TrialGate/AdvancedBanner
- Paid-only UI: hide BYOK core inputs, trial prompts per tool
- Included (Clip Generator, YouTube Studio) vs BYOK (AI Shorts/dubbing: fal.ai +
  ElevenLabs) clearly separated; ThumbnailStudio + SaaShortsTab managed-aware
- Landing: free-self-host vs paid-hosted messaging

Verified end-to-end against real Postgres + Stripe test mode.
This commit is contained in:
juancarlos.cavero 2026-07-14 13:04:43 +02:00
parent fe87af6dd5
commit 05578c5456
35 changed files with 2927 additions and 104 deletions

38
.env.cloud.example Normal file
View file

@ -0,0 +1,38 @@
# Cloud (paid / managed-keys) mode — env template for openshorts.app.
# Copy to .env and fill in. Only needed when running with docker-compose.cloud.yml.
# Self-hosters running plain BYOK do NOT need any of this.
BILLING_ENABLED=true
# Postgres (docker-compose.cloud.yml provisions the `db` service)
POSTGRES_PASSWORD=change-me
DATABASE_URL=postgresql+asyncpg://openshorts:change-me@db:5432/openshorts
# Auth
JWT_SECRET=generate-a-long-random-string
FRONTEND_URL=https://openshorts.app
ALLOWED_ORIGINS=https://openshorts.app
# Email — magic link (Resend)
RESEND_API_KEY=re_...
EMAIL_FROM=OpenShorts <login@openshorts.app>
# Google OAuth (optional; magic link works without it)
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
# Stripe (test keys shown; use live keys in production).
# Prices are resolved by lookup_key (starter_monthly, topup_60, ...) at runtime,
# so no price IDs are needed here. Create the prices with those lookup_keys.
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
# Managed provider keys (server-owned; only handed to entitled paid users)
MANAGED_GEMINI_API_KEY=
MANAGED_UPLOAD_POST_API_KEY=
OPENSHORTS_LOGO_URL=https://openshorts.app/logo.png
# Residential proxy for YouTube downloads (avoids datacenter-IP bans on the
# hosted server). Recommended: DataImpulse (~$1/GB PAYG). Downloads are capped
# to 720p when this is set, to control bandwidth cost. Empty = direct download.
PROXY_URL=

View file

@ -10,11 +10,14 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
# Copy and install Python dependencies # Copy and install Python dependencies
# Copy and install Python dependencies # Copy and install Python dependencies
COPY requirements.txt . COPY requirements.txt requirements-billing.txt ./
RUN python -m venv /opt/venv RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH" ENV PATH="/opt/venv/bin:$PATH"
RUN pip install --upgrade pip RUN pip install --upgrade pip
RUN pip install --no-cache-dir -r requirements.txt RUN pip install --no-cache-dir -r requirements.txt
# Cloud (paid mode) deps: installed always so one image serves both modes; they
# are only imported when BILLING_ENABLED is set. Harmless/unused in self-host.
RUN pip install --no-cache-dir -r requirements-billing.txt
# Final stage # Final stage
FROM python:3.11-slim FROM python:3.11-slim

41
alembic.ini Normal file
View file

@ -0,0 +1,41 @@
# Alembic config for cloud-mode schema migrations.
# The boot path uses create_all (see cloud/database.init_engine); Alembic is here
# for controlled migrations once the schema needs to evolve.
# Usage: DATABASE_URL=... alembic revision --autogenerate -m "msg" && alembic upgrade head
[alembic]
script_location = alembic
prepend_sys_path = .
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

60
alembic/env.py Normal file
View file

@ -0,0 +1,60 @@
"""Alembic environment (async) for cloud-mode migrations.
Reads the DB URL from the DATABASE_URL env var and targets cloud.models metadata,
so `alembic revision --autogenerate` works out of the box.
"""
import asyncio
import os
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
# Register model metadata.
from cloud.database import Base
import cloud.models # noqa: F401
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
db_url = os.environ.get("DATABASE_URL", "")
if db_url:
config.set_main_option("sqlalchemy.url", db_url)
target_metadata = Base.metadata
def run_migrations_offline():
context.configure(
url=config.get_main_option("sqlalchemy.url"),
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def _do_run(connection):
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_migrations_online():
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(_do_run)
await connectable.dispose()
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_migrations_online())

22
alembic/script.py.mako Normal file
View file

@ -0,0 +1,22 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}

331
app.py
View file

@ -6,6 +6,8 @@ import json
import shutil import shutil
import glob import glob
import time import time
import math
import itertools
import asyncio import asyncio
from dotenv import load_dotenv from dotenv import load_dotenv
from typing import Dict, Optional, List from typing import Dict, Optional, List
@ -32,14 +34,168 @@ MAX_FILE_SIZE_MB = 2048 # 2GB limit
JOB_RETENTION_SECONDS = 3600 # 1 hour retention JOB_RETENTION_SECONDS = 3600 # 1 hour retention
DISABLE_YOUTUBE_URL = os.environ.get("DISABLE_YOUTUBE_URL", "false").lower() in ("1", "true", "yes") DISABLE_YOUTUBE_URL = os.environ.get("DISABLE_YOUTUBE_URL", "false").lower() in ("1", "true", "yes")
# ---- Cloud billing (paid / managed-keys) integration --------------------------
# All paid-mode code lives in the optional `cloud/` package and is imported ONLY
# when BILLING_ENABLED is set. With the flag off, the app behaves exactly as the
# self-hosted BYOK app does today (no extra dependencies required).
BILLING_ENABLED = os.environ.get("BILLING_ENABLED", "").lower() in ("1", "true", "yes")
if BILLING_ENABLED:
import cloud
from cloud import managed_keys, metering as _metering, config as _cloud_config
from cloud.auth import get_current_user_optional
else:
cloud = None
managed_keys = None
_metering = None
_cloud_config = None
async def get_current_user_optional(request: Request):
# No-op dependency in self-host mode: every request is anonymous / BYOK.
return None
async def _user_from_request(request: Request):
"""Load the authenticated cloud user (or None). Cheap indexed lookup."""
return await get_current_user_optional(request)
async def resolve_gemini(request: Request) -> Optional[str]:
"""Resolve the Gemini API key for a request.
Cloud (hosted) is PAID-ONLY: there is no BYOK for the core pipeline, so the
``X-Gemini-Key`` header is ignored — an entitled user (active plan or trial)
gets the managed server key, everyone else gets ``None`` (→ 402, start trial).
Self-host keeps BYOK: header wins, else the env fallback.
"""
if BILLING_ENABLED:
user = await _user_from_request(request)
if managed_keys.has_active_entitlement(user):
return managed_keys.gemini_key()
return None
header = request.headers.get("X-Gemini-Key")
if header:
return header
return os.environ.get("GEMINI_API_KEY")
async def resolve_upload_post(request: Request, body_key: Optional[str] = None):
"""Resolve the Upload-Post key and the profile to post as.
Returns ``(api_key, forced_profile_username_or_None)``. Cloud is paid-only:
an entitled user gets the managed key + their own forced profile (body key /
user_id ignored); a non-entitled user gets ``(None, None)``. Self-host keeps
BYOK: header, then body key, then env.
"""
if BILLING_ENABLED:
user = await _user_from_request(request)
if managed_keys.has_active_entitlement(user):
profile = await cloud.social_profiles.ensure_profile(user)
return managed_keys.upload_post_key(), profile
return None, None
header = request.headers.get("X-Upload-Post-Key")
key = header or body_key or os.environ.get("UPLOAD_POST_API_KEY")
return key, None
def gemini_missing_error():
"""The right 4xx when no Gemini key could be resolved.
402 for a signed-in-but-not-entitled cloud user (needs a plan); 400 otherwise
(BYOK header simply missing).
"""
if BILLING_ENABLED:
return HTTPException(status_code=402, detail={
"error": "no_plan",
"message": "This action needs an active plan. Choose a plan or add your own API key.",
})
return HTTPException(status_code=400, detail="Missing X-Gemini-Key header")
async def reserve_process_minutes(request, url, input_path, job_id):
"""Meter a managed /api/process request. Returns (user_id, priority, reservation_id).
BYOK / self-host requests don't consume minutes (priority 2, no reservation).
For a managed (entitled, no BYOK header) request this probes the input
duration, enforces the per-user concurrent-job limit, and reserves minutes —
raising 402 (quota) or 429 (too many jobs) as needed.
"""
if not BILLING_ENABLED or request.headers.get("X-Gemini-Key"):
return None, 2, 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)
priority = _cloud_config.PLAN_PRIORITY.get(user.plan, 1)
# Per-user simultaneous job cap.
limit = _cloud_config.PLAN_JOB_LIMIT.get(user.plan, 2)
active = sum(1 for j in jobs.values()
if j.get('user_id') == user.id and j.get('status') in ('queued', 'processing'))
if active >= limit:
raise HTTPException(status_code=429,
detail="You already have the maximum number of jobs running. Please wait.")
# Probe input duration (blocking → run in a thread).
loop = asyncio.get_event_loop()
try:
if url:
minutes = await loop.run_in_executor(None, _metering.probe_url_minutes, url)
else:
minutes = await loop.run_in_executor(None, _metering.probe_file_minutes, input_path)
except Exception:
raise HTTPException(status_code=400,
detail="Could not determine the video duration. Try a different source.")
minutes = max(1, math.ceil(minutes))
try:
reservation_id = await _metering.reserve_minutes(user.id, minutes, job_id)
except _metering.QuotaExceeded as e:
raise HTTPException(status_code=402, detail={
"error": "quota_exceeded",
"minutes_required": e.required,
"minutes_remaining": e.remaining,
})
return user.id, priority, reservation_id
async def reserve_managed_action(request, minutes, job_id, job_type):
"""Reserve quota for a synchronous managed action (e.g. thumbnail image gen).
Returns a reservation_id to commit/release around the work, or None for
BYOK / self-host. Raises 402 when the user is out of minutes.
"""
if not BILLING_ENABLED:
return None
user = await _user_from_request(request)
if not managed_keys.has_active_entitlement(user):
return None # BYOK header path (self-host) — not metered
try:
return await _metering.reserve_minutes(user.id, minutes, job_id, job_type)
except _metering.QuotaExceeded as e:
raise HTTPException(status_code=402, detail={
"error": "quota_exceeded",
"minutes_required": e.required,
"minutes_remaining": e.remaining,
})
# Application State # Application State
job_queue = asyncio.Queue() # PriorityQueue holds (priority, seq, job_id). Lower priority dispatches first:
# pro=0, starter/creator=1, BYOK/anonymous/self-host=2. The seq counter keeps
# FIFO order within a priority and makes the tuples always comparable. With
# BILLING disabled every job enqueues at priority 2 → plain FIFO as before.
job_queue = asyncio.PriorityQueue()
_job_seq = itertools.count()
jobs: Dict[str, Dict] = {} jobs: Dict[str, Dict] = {}
thumbnail_sessions: Dict[str, Dict] = {} thumbnail_sessions: Dict[str, Dict] = {}
publish_jobs: Dict[str, Dict] = {} # {publish_id: {status, result, error}} publish_jobs: Dict[str, Dict] = {} # {publish_id: {status, result, error}}
# Semester to limit concurrency to MAX_CONCURRENT_JOBS # Semester to limit concurrency to MAX_CONCURRENT_JOBS
concurrency_semaphore = asyncio.Semaphore(MAX_CONCURRENT_JOBS) concurrency_semaphore = asyncio.Semaphore(MAX_CONCURRENT_JOBS)
def _enqueue_job(job_id: str, priority: int = 2):
job_queue.put_nowait((priority, next(_job_seq), job_id))
def _relocate_root_job_artifacts(job_id: str, job_output_dir: str) -> bool: def _relocate_root_job_artifacts(job_id: str, job_output_dir: str) -> bool:
""" """
Backward-compat rescue: Backward-compat rescue:
@ -131,8 +287,8 @@ async def process_queue():
print(f"🚀 Job Queue Worker started with {MAX_CONCURRENT_JOBS} concurrent slots.") print(f"🚀 Job Queue Worker started with {MAX_CONCURRENT_JOBS} concurrent slots.")
while True: while True:
try: try:
# Wait for a job # Wait for a job (priority, seq, job_id) — lowest priority first.
job_id = await job_queue.get() _priority, _seq, job_id = await job_queue.get()
# Acquire semaphore slot (waits if max jobs are running) # Acquire semaphore slot (waits if max jobs are running)
await concurrency_semaphore.acquire() await concurrency_semaphore.acquire()
@ -154,25 +310,51 @@ async def run_job_wrapper(job_id):
except Exception as e: except Exception as e:
print(f"❌ Job wrapper error {job_id}: {e}") print(f"❌ Job wrapper error {job_id}: {e}")
finally: finally:
# Settle the minute reservation (managed jobs only): commit on success,
# release otherwise so the minutes go back to the user.
await _settle_reservation(job_id)
# 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()
print(f"✅ Released slot for job: {job_id}") print(f"✅ Released slot for job: {job_id}")
async def _settle_reservation(job_id):
if not BILLING_ENABLED:
return
job = jobs.get(job_id) or {}
reservation_id = job.get('reservation_id')
if not reservation_id:
return
try:
if job.get('status') == 'completed':
await cloud.metering.commit_reservation(reservation_id)
else:
await cloud.metering.release_reservation(reservation_id)
except Exception as e:
print(f"⚠️ Reservation settle error for {job_id}: {e}")
@asynccontextmanager @asynccontextmanager
async def lifespan(app: FastAPI): async def lifespan(app: FastAPI):
# Start worker and cleanup # Start worker and cleanup
worker_task = asyncio.create_task(process_queue()) worker_task = asyncio.create_task(process_queue())
cleanup_task = asyncio.create_task(cleanup_jobs()) cleanup_task = asyncio.create_task(cleanup_jobs())
if BILLING_ENABLED:
await cloud.setup_async(app)
yield yield
# Cleanup (optional: cancel worker) # Cleanup (optional: cancel worker)
app = FastAPI(lifespan=lifespan) app = FastAPI(lifespan=lifespan)
# Enable CORS for frontend # Cloud mode: attach middleware + routers at import time (before the app serves).
if BILLING_ENABLED:
cloud.setup_sync(app)
# Enable CORS for frontend. Cloud mode locks this down to the configured origins;
# self-host keeps the permissive wildcard it has always used.
app.add_middleware( app.add_middleware(
CORSMiddleware, CORSMiddleware,
allow_origins=["*"], allow_origins=cloud.settings.allowed_origins if BILLING_ENABLED else ["*"],
allow_credentials=True, allow_credentials=True,
allow_methods=["*"], allow_methods=["*"],
allow_headers=["*"], allow_headers=["*"],
@ -311,7 +493,11 @@ async def run_job(job_id, job_data):
@app.get("/api/config") @app.get("/api/config")
async def get_config(): async def get_config():
return {"youtubeUrlEnabled": not DISABLE_YOUTUBE_URL} return {
"youtubeUrlEnabled": not DISABLE_YOUTUBE_URL,
"billingEnabled": BILLING_ENABLED,
"googleAuthEnabled": bool(BILLING_ENABLED and cloud.settings.google_auth_enabled),
}
@app.post("/api/process") @app.post("/api/process")
async def process_endpoint( async def process_endpoint(
@ -320,9 +506,9 @@ async def process_endpoint(
url: Optional[str] = Form(None), url: Optional[str] = Form(None),
acknowledged: Optional[str] = Form(None) acknowledged: Optional[str] = Form(None)
): ):
api_key = request.headers.get("X-Gemini-Key") api_key = await resolve_gemini(request)
if not api_key: if not api_key:
raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") raise gemini_missing_error()
ack_flag = str(acknowledged).lower() in ("1", "true", "yes") ack_flag = str(acknowledged).lower() in ("1", "true", "yes")
@ -365,6 +551,7 @@ async def process_endpoint(
env = os.environ.copy() env = os.environ.copy()
env["GEMINI_API_KEY"] = api_key # Override with key from request env["GEMINI_API_KEY"] = api_key # Override with key from request
input_path = None
if url: if url:
cmd.extend(["-u", url]) cmd.extend(["-u", url])
else: else:
@ -390,6 +577,9 @@ 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).
user_id, priority, reservation_id = await reserve_process_minutes(request, url, input_path, job_id)
# Enqueue Job # Enqueue Job
jobs[job_id] = { jobs[job_id] = {
'status': 'queued', 'status': 'queued',
@ -397,10 +587,12 @@ async def process_endpoint(
'cmd': cmd, 'cmd': cmd,
'env': env, 'env': env,
'output_dir': job_output_dir, 'output_dir': job_output_dir,
'attestation': attestation 'attestation': attestation,
'user_id': user_id,
'reservation_id': reservation_id,
} }
await job_queue.put(job_id) _enqueue_job(job_id, priority)
return {"job_id": job_id, "status": "queued"} return {"job_id": job_id, "status": "queued"}
@ -431,13 +623,13 @@ class EditRequest(BaseModel):
@app.post("/api/edit") @app.post("/api/edit")
async def edit_clip( async def edit_clip(
req: EditRequest, req: EditRequest,
x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") request: Request,
): ):
# Determine API Key # BYOK body key wins; otherwise resolve header / managed / self-host env.
final_api_key = req.api_key or x_gemini_key or os.environ.get("GEMINI_API_KEY") final_api_key = req.api_key or await resolve_gemini(request)
if not final_api_key: if not final_api_key:
raise HTTPException(status_code=400, detail="Missing Gemini API Key (Header or Body)") raise gemini_missing_error()
if req.job_id not in jobs: if req.job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")
@ -647,13 +839,13 @@ class EffectsGenerateRequest(BaseModel):
@app.post("/api/effects/generate") @app.post("/api/effects/generate")
async def generate_effects_config( async def generate_effects_config(
req: EffectsGenerateRequest, req: EffectsGenerateRequest,
x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") request: Request,
): ):
"""Generate structured EffectsConfig JSON for Remotion rendering via Gemini AI.""" """Generate structured EffectsConfig JSON for Remotion rendering via Gemini AI."""
final_api_key = x_gemini_key or os.environ.get("GEMINI_API_KEY") final_api_key = await resolve_gemini(request)
if not final_api_key: if not final_api_key:
raise HTTPException(status_code=400, detail="Missing Gemini API Key (Header)") raise gemini_missing_error()
if req.job_id not in jobs: if req.job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")
@ -1044,8 +1236,8 @@ async def translate_clip(
class SocialPostRequest(BaseModel): class SocialPostRequest(BaseModel):
job_id: str job_id: str
clip_index: int clip_index: int
api_key: str api_key: Optional[str] = None # BYOK; ignored for managed users
user_id: str user_id: Optional[str] = None # BYOK profile; ignored for managed users
platforms: List[str] # ["tiktok", "instagram", "youtube"] platforms: List[str] # ["tiktok", "instagram", "youtube"]
# Optional overrides if frontend wants to edit them # Optional overrides if frontend wants to edit them
title: Optional[str] = None title: Optional[str] = None
@ -1056,10 +1248,19 @@ class SocialPostRequest(BaseModel):
import httpx import httpx
@app.post("/api/social/post") @app.post("/api/social/post")
async def post_to_socials(req: SocialPostRequest): async def post_to_socials(req: SocialPostRequest, request: Request):
if req.job_id not in jobs: if req.job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")
# Resolve the Upload-Post key + profile. For managed users the server key is
# used and their own profile is forced (body api_key / user_id are ignored).
upload_key, forced_profile = await resolve_upload_post(request, req.api_key)
if not upload_key:
raise HTTPException(status_code=400, detail="Missing Upload-Post API key")
post_user = forced_profile or req.user_id
if not post_user:
raise HTTPException(status_code=400, detail="Missing Upload-Post user profile")
job = jobs[req.job_id] job = jobs[req.job_id]
if 'result' not in job or 'clips' not in job['result']: if 'result' not in job or 'clips' not in job['result']:
raise HTTPException(status_code=400, detail="Job result not available") raise HTTPException(status_code=400, detail="Job result not available")
@ -1085,12 +1286,12 @@ async def post_to_socials(req: SocialPostRequest):
# Prepare form data # Prepare form data
url = "https://api.upload-post.com/api/upload" url = "https://api.upload-post.com/api/upload"
headers = { headers = {
"Authorization": f"Apikey {req.api_key}" "Authorization": f"Apikey {upload_key}"
} }
# Prepare data as dict (httpx handles lists for multiple values) # Prepare data as dict (httpx handles lists for multiple values)
data_payload = { data_payload = {
"user": req.user_id, "user": post_user,
"title": final_title, "title": final_title,
"platform[]": req.platforms, # Pass list directly "platform[]": req.platforms, # Pass list directly
"async_upload": "true" # Enable async upload "async_upload": "true" # Enable async upload
@ -1142,8 +1343,13 @@ async def post_to_socials(req: SocialPostRequest):
raise HTTPException(status_code=500, detail=str(e)) raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/social/user") @app.get("/api/social/user")
async def get_social_user(api_key: str = Header(..., alias="X-Upload-Post-Key")): async def get_social_user(request: Request):
"""Proxy to fetch user ID from Upload-Post""" """Proxy to fetch user profiles from Upload-Post.
BYOK: uses the caller's key and returns all profiles on that account.
Managed: uses the server key but returns ONLY the caller's own profile.
"""
api_key, forced_profile = await resolve_upload_post(request, None)
if not api_key: if not api_key:
raise HTTPException(status_code=400, detail="Missing X-Upload-Post-Key header") raise HTTPException(status_code=400, detail="Missing X-Upload-Post-Key header")
@ -1185,6 +1391,10 @@ async def get_social_user(api_key: str = Header(..., alias="X-Upload-Post-Key"))
"connected": connected "connected": connected
}) })
# Managed users must only ever see their own profile.
if forced_profile is not None:
profiles_list = [p for p in profiles_list if p.get("username") == forced_profile]
if not profiles_list: if not profiles_list:
# Fallback if no profiles found # Fallback if no profiles found
return {"profiles": [], "error": "No profiles found"} return {"profiles": [], "error": "No profiles found"}
@ -1276,9 +1486,9 @@ async def thumbnail_analyze(
x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key")
): ):
"""Analyze a video and suggest viral YouTube titles.""" """Analyze a video and suggest viral YouTube titles."""
api_key = x_gemini_key api_key = await resolve_gemini(request)
if not api_key: if not api_key:
raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") raise gemini_missing_error()
pre_transcript = None pre_transcript = None
@ -1357,12 +1567,12 @@ class ThumbnailTitlesRequest(BaseModel):
@app.post("/api/thumbnail/titles") @app.post("/api/thumbnail/titles")
async def thumbnail_titles( async def thumbnail_titles(
req: ThumbnailTitlesRequest, req: ThumbnailTitlesRequest,
x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") request: Request,
): ):
"""Refine title suggestions or accept a manual title.""" """Refine title suggestions or accept a manual title."""
api_key = x_gemini_key api_key = await resolve_gemini(request)
if not api_key: if not api_key:
raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") raise gemini_missing_error()
# Manual title mode - just create a session with the user's title # Manual title mode - just create a session with the user's title
if req.title: if req.title:
@ -1419,16 +1629,20 @@ async def thumbnail_generate(
count: int = Form(3), count: int = Form(3),
face: Optional[UploadFile] = File(None), face: Optional[UploadFile] = File(None),
background: Optional[UploadFile] = File(None), background: Optional[UploadFile] = File(None),
x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key")
): ):
"""Generate YouTube thumbnails with Gemini image generation.""" """Generate YouTube thumbnails with Gemini image generation."""
api_key = x_gemini_key api_key = await resolve_gemini(request)
if not api_key: if not api_key:
raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") raise gemini_missing_error()
# Clamp count # Clamp count
count = min(max(1, count), 6) count = min(max(1, count), 6)
# Gemini image generation is the expensive managed call — meter it against the
# plan quota (a batch ≈ THUMBNAIL_MINUTES). No-op for BYOK / self-host.
thumb_minutes = _cloud_config.THUMBNAIL_MINUTES if BILLING_ENABLED else 0
reservation_id = await reserve_managed_action(request, thumb_minutes, session_id, "thumbnail")
# Save optional uploaded images # Save optional uploaded images
face_path = None face_path = None
bg_path = None bg_path = None
@ -1469,11 +1683,18 @@ async def thumbnail_generate(
if not thumbnails: if not thumbnails:
raise HTTPException(status_code=500, detail="Thumbnail generation failed. Please check your Gemini API key has access to image generation (gemini-3.1-flash-image-preview model).") raise HTTPException(status_code=500, detail="Thumbnail generation failed. Please check your Gemini API key has access to image generation (gemini-3.1-flash-image-preview model).")
# Success — charge the reserved minutes.
if reservation_id:
await _metering.commit_reservation(reservation_id)
return {"thumbnails": thumbnails} return {"thumbnails": thumbnails}
except HTTPException: except HTTPException:
if reservation_id:
await _metering.release_reservation(reservation_id)
raise raise
except Exception as e: except Exception as e:
if reservation_id:
await _metering.release_reservation(reservation_id)
print(f"❌ Thumbnail Generate Error: {e}") print(f"❌ Thumbnail Generate Error: {e}")
raise HTTPException(status_code=500, detail=str(e)) raise HTTPException(status_code=500, detail=str(e))
@ -1485,12 +1706,12 @@ class ThumbnailDescribeRequest(BaseModel):
@app.post("/api/thumbnail/describe") @app.post("/api/thumbnail/describe")
async def thumbnail_describe( async def thumbnail_describe(
req: ThumbnailDescribeRequest, req: ThumbnailDescribeRequest,
x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") request: Request,
): ):
"""Generate a YouTube description with chapters from the transcript.""" """Generate a YouTube description with chapters from the transcript."""
api_key = x_gemini_key api_key = await resolve_gemini(request)
if not api_key: if not api_key:
raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") raise gemini_missing_error()
if req.session_id not in thumbnail_sessions: if req.session_id not in thumbnail_sessions:
raise HTTPException(status_code=404, detail="Session not found") raise HTTPException(status_code=404, detail="Session not found")
@ -1520,18 +1741,27 @@ async def thumbnail_describe(
@app.post("/api/thumbnail/publish") @app.post("/api/thumbnail/publish")
async def thumbnail_publish( async def thumbnail_publish(
request: Request,
background_tasks: BackgroundTasks, background_tasks: BackgroundTasks,
session_id: str = Form(...), session_id: str = Form(...),
title: str = Form(...), title: str = Form(...),
description: str = Form(...), description: str = Form(...),
thumbnail_url: str = Form(...), thumbnail_url: str = Form(...),
api_key: str = Form(...), api_key: Optional[str] = Form(None), # BYOK; ignored for managed users
user_id: str = Form(...), user_id: Optional[str] = Form(None), # BYOK profile; ignored for managed users
): ):
"""Kick off a background upload to YouTube via Upload-Post and return immediately.""" """Kick off a background upload to YouTube via Upload-Post and return immediately."""
if session_id not in thumbnail_sessions: if session_id not in thumbnail_sessions:
raise HTTPException(status_code=404, detail="Session not found") raise HTTPException(status_code=404, detail="Session not found")
# Managed users: server key + forced own profile; body fields ignored.
upload_key, forced_profile = await resolve_upload_post(request, api_key)
if not upload_key:
raise HTTPException(status_code=400, detail="Missing Upload-Post API key")
post_user = forced_profile or user_id
if not post_user:
raise HTTPException(status_code=400, detail="Missing Upload-Post user profile")
session = thumbnail_sessions[session_id] session = thumbnail_sessions[session_id]
video_path = session.get("video_path") video_path = session.get("video_path")
if not video_path or not os.path.exists(video_path): if not video_path or not os.path.exists(video_path):
@ -1555,9 +1785,9 @@ async def thumbnail_publish(
"""Runs in a thread via BackgroundTasks — does the actual multipart upload.""" """Runs in a thread via BackgroundTasks — does the actual multipart upload."""
try: try:
upload_url = "https://api.upload-post.com/api/upload" upload_url = "https://api.upload-post.com/api/upload"
headers = {"Authorization": f"Apikey {api_key}"} headers = {"Authorization": f"Apikey {upload_key}"}
data_payload = { data_payload = {
"user": user_id, "user": post_user,
"platform[]": ["youtube"], "platform[]": ["youtube"],
"title": title, # required base field (fallback) "title": title, # required base field (fallback)
"async_upload": "true", "async_upload": "true",
@ -1670,12 +1900,12 @@ class SaaSAnalyzeRequest(BaseModel):
@app.post("/api/saasshorts/analyze") @app.post("/api/saasshorts/analyze")
async def saasshorts_analyze( async def saasshorts_analyze(
req: SaaSAnalyzeRequest, req: SaaSAnalyzeRequest,
x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key"), request: Request,
): ):
"""Analyze a URL or manual description and generate video scripts.""" """Analyze a URL or manual description and generate video scripts."""
gemini_key = x_gemini_key or os.environ.get("GEMINI_API_KEY") gemini_key = await resolve_gemini(request)
if not gemini_key: if not gemini_key:
raise HTTPException(status_code=400, detail="Missing Gemini API Key") raise gemini_missing_error()
if not req.url and not req.description: if not req.url and not req.description:
raise HTTPException(status_code=400, detail="Provide a URL or a product description") raise HTTPException(status_code=400, detail="Provide a URL or a product description")
@ -1811,8 +2041,8 @@ async def saasshorts_video_gallery(limit: int = 50):
class SaaSPostRequest(BaseModel): class SaaSPostRequest(BaseModel):
job_id: str job_id: str
api_key: str api_key: Optional[str] = None # BYOK; ignored for managed users
user_id: str user_id: Optional[str] = None # BYOK profile; ignored for managed users
platforms: List[str] platforms: List[str]
title: Optional[str] = None title: Optional[str] = None
description: Optional[str] = None description: Optional[str] = None
@ -1821,11 +2051,18 @@ class SaaSPostRequest(BaseModel):
@app.post("/api/saasshorts/post") @app.post("/api/saasshorts/post")
async def saasshorts_post_to_socials(req: SaaSPostRequest): async def saasshorts_post_to_socials(req: SaaSPostRequest, request: Request):
"""Post an AI Shorts video to social media via Upload-Post.""" """Post an AI Shorts video to social media via Upload-Post."""
if req.job_id not in saas_jobs: if req.job_id not in saas_jobs:
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")
upload_key, forced_profile = await resolve_upload_post(request, req.api_key)
if not upload_key:
raise HTTPException(status_code=400, detail="Missing Upload-Post API key")
post_user = forced_profile or req.user_id
if not post_user:
raise HTTPException(status_code=400, detail="Missing Upload-Post user profile")
job = saas_jobs[req.job_id] job = saas_jobs[req.job_id]
result = job.get("result") result = job.get("result")
if not result or not result.get("video_url"): if not result or not result.get("video_url"):
@ -1847,10 +2084,10 @@ async def saasshorts_post_to_socials(req: SaaSPostRequest):
final_description = script.get("full_narration", "Check this out!") final_description = script.get("full_narration", "Check this out!")
url = "https://api.upload-post.com/api/upload" url = "https://api.upload-post.com/api/upload"
headers = {"Authorization": f"Apikey {req.api_key}"} headers = {"Authorization": f"Apikey {upload_key}"}
data_payload = { data_payload = {
"user": req.user_id, "user": post_user,
"title": final_title, "title": final_title,
"platform[]": req.platforms, "platform[]": req.platforms,
"async_upload": "true", "async_upload": "true",

47
cloud/__init__.py Normal file
View file

@ -0,0 +1,47 @@
"""Optional cloud (paid / managed-keys) mode for OpenShorts.
This whole package is dormant unless the ``BILLING_ENABLED`` env flag is set.
``app.py`` imports it only in that case, so self-hosters never need the extra
dependencies in ``requirements-billing.txt``.
Wiring is split in two because Starlette forbids adding middleware after the app
has started:
- ``setup_sync(app)`` -> runs at import time (middleware + routers)
- ``setup_async(app)`` -> runs in the lifespan (DB engine, sweeper, orphans)
Both are built up phase by phase; each phase appends its own wiring.
"""
from .config import is_enabled, settings, validate_required # noqa: F401
def setup_sync(app):
"""Synchronous wiring done at import time (before the app serves).
Middleware and routers must be attached here. Fails fast on missing config
so a misconfigured deploy never boots half-enabled.
"""
validate_required()
# SessionMiddleware backs the OAuth state handshake.
from starlette.middleware.sessions import SessionMiddleware
app.add_middleware(SessionMiddleware, secret_key=settings.jwt_secret)
from . import auth, oauth, billing, social_profiles
oauth.register()
billing._init_stripe()
app.include_router(auth.router)
app.include_router(oauth.router)
app.include_router(billing.router)
app.include_router(social_profiles.router)
async def setup_async(app):
"""Async initialization done inside the FastAPI lifespan.
DB engine, orphaned-reservation cleanup and the metering sweeper live here.
"""
from . import database, metering
await database.init_engine()
await metering.release_orphaned_reservations()
metering.start_sweeper()
print("☁️ Cloud billing mode ENABLED (DB ready, metering active).")

214
cloud/auth.py Normal file
View file

@ -0,0 +1,214 @@
"""Authentication for cloud mode: magic link + JWT sessions + current-user loading.
- Magic link: POST /api/auth/magic-link -> emailed single-use token (15 min).
POST /api/auth/magic-link/verify consumes it (POST, not GET, so email scanners
that prefetch links can't burn them) and returns a 30-day JWT.
- get_current_user_optional never raises: a missing/expired token degrades to the
anonymous BYOK flow rather than breaking it.
- /api/me returns the user's plan + minute balance (no Stripe call needed).
"""
import hashlib
import secrets
from datetime import datetime, timezone, timedelta
from typing import Optional
import jwt
from fastapi import APIRouter, Request, HTTPException
from pydantic import BaseModel, EmailStr
from sqlalchemy import select, func, and_
from .config import settings
from . import database, metering
from .models import User, MagicLinkToken, UploadPostProfile
router = APIRouter()
JWT_ALGO = "HS256"
JWT_TTL_DAYS = 30
MAGIC_TTL_MINUTES = 15
MAGIC_RATE_LIMIT = 3 # per email
MAGIC_RATE_WINDOW_MIN = 15
def _now():
return datetime.now(timezone.utc)
# --------------------------------------------------------------------------- #
# JWT + current user
# --------------------------------------------------------------------------- #
def issue_jwt(user_id, email) -> str:
payload = {
"sub": str(user_id),
"email": email,
"exp": _now() + timedelta(days=JWT_TTL_DAYS),
"iat": _now(),
}
return jwt.encode(payload, settings.jwt_secret, algorithm=JWT_ALGO)
def _decode_jwt(token: str) -> Optional[dict]:
try:
return jwt.decode(token, settings.jwt_secret, algorithms=[JWT_ALGO])
except Exception:
return None
class CurrentUser:
"""Lightweight per-request user snapshot carried through endpoints.
Kept small and eager (no lazy DB access) so sync helpers like
``managed_keys.has_active_entitlement`` can read it without awaiting.
"""
def __init__(self, id, email, entitled=False, plan=None, upload_post_profile=None):
self.id = id
self.email = email
self.entitled = entitled
self.plan = plan
self.upload_post_profile = upload_post_profile
async def _load_current_user(session, user_id) -> Optional["CurrentUser"]:
user = await session.get(User, user_id)
if user is None:
return None
sub = await metering._active_subscription(session, user_id)
topups = await metering._topups_fifo(session, user_id)
topup_remaining = sum(
(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)
return CurrentUser(
id=user.id,
email=user.email,
entitled=entitled,
plan=sub.plan if sub else None,
upload_post_profile=profile.profile_username if profile else None,
)
async def get_current_user_optional(request: Request) -> Optional[CurrentUser]:
"""Return the authenticated user, or None for anonymous / BYOK requests."""
auth = request.headers.get("Authorization", "")
if not auth.lower().startswith("bearer "):
return None
payload = _decode_jwt(auth[7:].strip())
if not payload:
return None
try:
import uuid
user_id = uuid.UUID(payload["sub"])
except Exception:
return None
async with database.session() as session:
return await _load_current_user(session, user_id)
async def get_current_user_required(request: Request) -> CurrentUser:
user = await get_current_user_optional(request)
if user is None:
raise HTTPException(status_code=401, detail="Authentication required")
return user
# --------------------------------------------------------------------------- #
# Magic link
# --------------------------------------------------------------------------- #
class MagicLinkRequest(BaseModel):
email: EmailStr
class MagicVerifyRequest(BaseModel):
token: str
@router.post("/api/auth/magic-link")
async def request_magic_link(payload: MagicLinkRequest, request: Request):
from .emails import send_magic_link_email
email = payload.email.lower()
async with database.session() as session:
async with session.begin():
window_start = _now() - timedelta(minutes=MAGIC_RATE_WINDOW_MIN)
recent = (await session.execute(
select(func.count(MagicLinkToken.id)).where(and_(
MagicLinkToken.email == email,
MagicLinkToken.created_at >= window_start,
))
)).scalar_one()
if recent >= MAGIC_RATE_LIMIT:
raise HTTPException(status_code=429, detail="Too many login attempts. Try again in a few minutes.")
raw_token = secrets.token_urlsafe(32)
token_hash = hashlib.sha256(raw_token.encode()).hexdigest()
session.add(MagicLinkToken(
email=email,
token_hash=token_hash,
expires_at=_now() + timedelta(minutes=MAGIC_TTL_MINUTES),
request_ip=request.client.host if request.client else None,
))
link = f"{settings.frontend_url}/#/auth/verify?ml={raw_token}"
await send_magic_link_email(email, link)
return {"ok": True}
@router.post("/api/auth/magic-link/verify")
async def verify_magic_link(payload: MagicVerifyRequest):
token_hash = hashlib.sha256(payload.token.encode()).hexdigest()
async with database.session() as session:
async with session.begin():
row = (await session.execute(
select(MagicLinkToken).where(MagicLinkToken.token_hash == token_hash)
.with_for_update()
)).scalar_one_or_none()
if row is None or row.used_at is not None or row.expires_at < _now():
raise HTTPException(status_code=400, detail="This sign-in link is invalid or expired.")
row.used_at = _now()
email = row.email.lower()
user = (await session.execute(
select(User).where(User.email == email)
)).scalar_one_or_none()
if user is None:
user = User(email=email, last_login_at=_now())
session.add(user)
await session.flush()
else:
user.last_login_at = _now()
user_id, user_email = user.id, user.email
token = issue_jwt(user_id, user_email)
cu = await _load_current_user(session, user_id)
return {"token": token, "user": {"id": str(user_id), "email": user_email, "entitled": cu.entitled}}
# --------------------------------------------------------------------------- #
# /api/me
# --------------------------------------------------------------------------- #
@router.get("/api/me")
async def get_me(request: Request):
user = await get_current_user_required(request)
async with database.session() as session:
bal = await metering._balance(session, user.id)
sub = bal["_sub"]
return {
"user": {"id": str(user.id), "email": user.email},
"entitled": user.entitled,
"plan": bal["plan"],
"status": sub.status if sub else None,
"interval": sub.interval if sub else None,
"period_end": bal["period_end"].isoformat() if bal["period_end"] else None,
"cancel_at_period_end": sub.cancel_at_period_end if sub else False,
"minutes": {
"plan_allowance": bal["plan_allowance"],
"plan_used": bal["plan_used"],
"plan_remaining": bal["plan_remaining"],
"topup_remaining": bal["topup_remaining"],
"remaining": bal["remaining"],
},
"upload_post_profile": user.upload_post_profile,
}

329
cloud/billing.py Normal file
View file

@ -0,0 +1,329 @@
"""Stripe billing: catalog, checkout, customer portal and webhooks.
Design (matches the Stripe implementation planner for this use case):
- Stripe-hosted Checkout: subscription mode for plans, payment mode for top-ups.
- Stripe-hosted Customer Portal for self-service plan management.
- Prices resolved by stable lookup_key at runtime (no price IDs in env).
- Webhooks are idempotent (stripe_events dedupe) and order-safe (last_event_at);
every handler upserts the full object rather than applying deltas.
"""
import asyncio
from datetime import datetime, timezone
import stripe
from fastapi import APIRouter, Request, HTTPException
from pydantic import BaseModel
from sqlalchemy import select
from .config import settings, PLAN_MINUTES, TRIAL_DAYS, SUBSCRIPTION_LOOKUP_KEYS, TOPUP_LOOKUP_KEYS
from . import database
from .models import User, Subscription, CreditTopup, StripeEvent
from .auth import get_current_user_required
router = APIRouter()
_catalog = None
def _init_stripe():
stripe.api_key = settings.stripe_secret_key
def _ts(unix) -> datetime:
return datetime.fromtimestamp(unix, tz=timezone.utc)
# --------------------------------------------------------------------------- #
# Catalog (resolved once by lookup_key)
# --------------------------------------------------------------------------- #
async def get_catalog(force=False):
global _catalog
if _catalog is not None and not force:
return _catalog
_init_stripe()
prices = await asyncio.to_thread(
lambda: stripe.Price.list(
lookup_keys=SUBSCRIPTION_LOOKUP_KEYS + TOPUP_LOOKUP_KEYS,
expand=["data.product"], limit=100, active=True,
)
)
plans, topups, by_id = [], [], {}
for p in prices.data:
md = p.metadata or {}
if p.recurring:
plan = md.get("plan")
interval = md.get("interval") or p.recurring.get("interval")
if plan not in PLAN_MINUTES:
continue
entry = {
"kind": "subscription", "price_id": p.id, "lookup_key": p.lookup_key,
"plan": plan, "interval": interval, "minutes": PLAN_MINUTES[plan],
"amount": p.unit_amount, "currency": p.currency,
}
plans.append(entry)
else:
minutes = int(md.get("topup_minutes", 0))
entry = {
"kind": "topup", "price_id": p.id, "lookup_key": p.lookup_key,
"minutes": minutes, "amount": p.unit_amount, "currency": p.currency,
}
topups.append(entry)
by_id[p.id] = entry
_catalog = {"plans": plans, "topups": topups, "by_id": by_id}
return _catalog
def plan_info_for_price(price_id: str):
"""Sync lookup into the cached catalog (webhook path). Returns entry or None."""
if _catalog is None:
return None
return _catalog["by_id"].get(price_id)
# --------------------------------------------------------------------------- #
# Customer helper
# --------------------------------------------------------------------------- #
async def ensure_stripe_customer(user_id, email) -> str:
async with database.session() as s:
async with s.begin():
u = await s.get(User, user_id)
if u.stripe_customer_id:
return u.stripe_customer_id
cust = await asyncio.to_thread(
lambda: stripe.Customer.create(email=email, metadata={"user_id": str(user_id)})
)
u.stripe_customer_id = cust.id
return cust.id
async def _active_sub_exists(user_id) -> bool:
async with database.session() as s:
sub = (await s.execute(
select(Subscription).where(Subscription.user_id == user_id)
)).scalar_one_or_none()
return bool(sub and sub.status in ("active", "trialing"))
# --------------------------------------------------------------------------- #
# Endpoints
# --------------------------------------------------------------------------- #
@router.get("/api/billing/plans")
async def list_plans():
cat = await get_catalog()
return {"plans": cat["plans"], "topups": cat["topups"]}
class CheckoutRequest(BaseModel):
price_id: str
@router.post("/api/billing/checkout")
async def create_checkout(body: CheckoutRequest, request: Request):
user = await get_current_user_required(request)
cat = await get_catalog()
entry = cat["by_id"].get(body.price_id)
if not entry:
raise HTTPException(status_code=400, detail="Unknown price")
mode = "subscription" if entry["kind"] == "subscription" else "payment"
if mode == "subscription" and await _active_sub_exists(user.id):
raise HTTPException(status_code=409,
detail="You already have an active plan. Manage it from your account.")
customer_id = await ensure_stripe_customer(user.id, user.email)
fe = settings.frontend_url
kwargs = dict(
mode=mode,
customer=customer_id,
line_items=[{"price": body.price_id, "quantity": 1}],
client_reference_id=str(user.id),
success_url=f"{fe}/#/account?checkout=success",
cancel_url=f"{fe}/#/pricing?checkout=cancel",
allow_promotion_codes=True,
metadata={
"user_id": str(user.id),
"kind": entry["kind"],
"minutes": str(entry.get("minutes", "")),
},
)
# Subscriptions start with a card-required free trial that auto-charges.
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))
return {"url": session.url}
@router.post("/api/billing/portal")
async def create_portal(request: Request):
user = await get_current_user_required(request)
customer_id = await ensure_stripe_customer(user.id, user.email)
session = await asyncio.to_thread(lambda: stripe.billing_portal.Session.create(
customer=customer_id, return_url=f"{settings.frontend_url}/#/account",
))
return {"url": session.url}
# --------------------------------------------------------------------------- #
# Webhook
# --------------------------------------------------------------------------- #
@router.post("/api/stripe/webhook")
async def stripe_webhook(request: Request):
payload = await request.body()
sig = request.headers.get("stripe-signature", "")
try:
event = stripe.Webhook.construct_event(payload, sig, settings.stripe_webhook_secret)
except Exception:
raise HTTPException(status_code=400, detail="Invalid signature")
# Dedupe: if we've already recorded this event, ack and skip.
async with database.session() as s:
if await s.get(StripeEvent, event["id"]):
return {"ok": True, "dedup": True}
await handle_event(event)
async with database.session() as s:
async with s.begin():
from sqlalchemy.dialects.postgresql import insert as pg_insert
await s.execute(pg_insert(StripeEvent).values(
id=event["id"], type=event["type"], created=_ts(event["created"]),
).on_conflict_do_nothing(index_elements=["id"]))
return {"ok": True}
async def handle_event(event: dict):
"""Idempotent event dispatch. Public so tests can call it directly."""
etype = event["type"]
obj = event["data"]["object"]
created = _ts(event["created"])
if etype == "checkout.session.completed" and obj.get("mode") == "payment":
await _apply_topup(obj)
elif etype in ("customer.subscription.created", "customer.subscription.updated"):
await _upsert_subscription(obj, created)
elif etype == "customer.subscription.deleted":
await _set_subscription_status(obj, "canceled", created)
elif etype == "invoice.payment_failed":
await _set_subscription_status_by_invoice(obj, "past_due", created)
elif etype == "invoice.paid":
await _set_subscription_status_by_invoice(obj, "active", created)
async def _user_id_for_customer(session, customer_id):
return (await session.execute(
select(User.id).where(User.stripe_customer_id == customer_id)
)).scalar_one_or_none()
async def _apply_topup(session_obj: dict):
"""Credit a top-up from a completed one-off Checkout (idempotent by session id)."""
session_id = session_obj["id"]
minutes = int((session_obj.get("metadata") or {}).get("minutes") or 0)
if minutes <= 0:
return
async with database.session() as s:
async with s.begin():
existing = (await s.execute(
select(CreditTopup).where(CreditTopup.stripe_session_id == session_id)
)).scalar_one_or_none()
if existing:
return
user_id = (session_obj.get("metadata") or {}).get("user_id")
if not user_id:
user_id = await _user_id_for_customer(s, session_obj.get("customer"))
if not user_id:
return
s.add(CreditTopup(
user_id=user_id, stripe_session_id=session_id,
minutes_total=minutes, minutes_consumed=0,
))
def _sub_item(sub_obj: dict):
try:
return sub_obj["items"]["data"][0]
except Exception:
return {}
def _sub_price_id(sub_obj: dict):
try:
return _sub_item(sub_obj)["price"]["id"]
except Exception:
return None
def _sub_period(sub_obj: dict):
"""Return (start, end) unix timestamps, from the subscription or its item.
Newer Stripe API versions expose current_period_* on the item, older ones on
the subscription itself — support both.
"""
item = _sub_item(sub_obj)
start = sub_obj.get("current_period_start") or item.get("current_period_start")
end = sub_obj.get("current_period_end") or item.get("current_period_end")
return start, end
async def _upsert_subscription(sub_obj: dict, event_created: datetime):
price_id = _sub_price_id(sub_obj)
info = plan_info_for_price(price_id)
if info is None:
await get_catalog(force=True)
info = plan_info_for_price(price_id)
if info is None:
return # unknown price — ignore
plan = info["plan"]
interval = info["interval"]
minutes = PLAN_MINUTES[plan]
async with database.session() as s:
async with s.begin():
user_id = await _user_id_for_customer(s, sub_obj.get("customer"))
if not user_id:
return
row = (await s.execute(
select(Subscription).where(Subscription.user_id == user_id).with_for_update()
)).scalar_one_or_none()
# Order guard: ignore events older than what we've already applied.
if row and row.last_event_at and event_created < row.last_event_at:
return
start, end = _sub_period(sub_obj)
values = dict(
stripe_subscription_id=sub_obj["id"],
stripe_price_id=price_id,
plan=plan, interval=interval, status=sub_obj["status"],
minutes_per_period=minutes,
current_period_start=_ts(start),
current_period_end=_ts(end),
cancel_at_period_end=bool(sub_obj.get("cancel_at_period_end")),
last_event_at=event_created,
)
if row is None:
s.add(Subscription(user_id=user_id, **values))
else:
for k, v in values.items():
setattr(row, k, v)
async def _set_subscription_status(sub_obj: dict, status: str, event_created: datetime):
async with database.session() as s:
async with s.begin():
row = (await s.execute(
select(Subscription).where(
Subscription.stripe_subscription_id == sub_obj["id"]
).with_for_update()
)).scalar_one_or_none()
if row is None:
return
if row.last_event_at and event_created < row.last_event_at:
return
row.status = status
row.last_event_at = event_created
async def _set_subscription_status_by_invoice(invoice_obj: dict, status: str, event_created: datetime):
sub_id = invoice_obj.get("subscription")
if not sub_id:
return
await _set_subscription_status({"id": sub_id}, status, event_created)

151
cloud/config.py Normal file
View file

@ -0,0 +1,151 @@
"""Central configuration for the optional cloud (paid / managed-keys) mode.
Everything here is read lazily from environment variables so that importing the
`cloud` package never has side effects. Nothing in this module is loaded unless
``BILLING_ENABLED`` is truthy (see ``cloud.is_enabled``).
"""
import os
from functools import lru_cache
def _flag(name: str, default: str = "") -> bool:
return os.environ.get(name, default).lower() in ("1", "true", "yes")
def is_enabled() -> bool:
"""Master switch. When False the whole cloud package stays dormant."""
return _flag("BILLING_ENABLED")
# --- Plan catalog -----------------------------------------------------------
# minutes granted per billing period, keyed by internal plan name. This is the
# AUTHORITATIVE quota source (not Stripe price metadata, which a dashboard edit
# could change). Plan name is resolved from the Stripe price; minutes from here.
PLAN_MINUTES = {
"starter": 100,
"creator": 300,
"pro": 750,
}
# Free trial length (days) for new subscriptions. Card required; auto-charges at
# the end. No minute cap during the trial — the card + Stripe Radar deter abuse.
TRIAL_DAYS = 3
# Gemini IMAGE generation (thumbnails) is the one expensive managed Gemini call
# (~$0.04/image, batch of ~3). It isn't naturally minute-metered, so each
# thumbnail generation batch consumes this many minutes from the plan quota —
# roughly matching its cost to the per-minute economics. Text (titles/desc) is free.
THUMBNAIL_MINUTES = 3
# Stripe prices are resolved at runtime by these stable lookup_keys, so no price
# IDs need to be copied into env vars (they differ between test and live anyway).
SUBSCRIPTION_LOOKUP_KEYS = [
"starter_monthly", "starter_yearly",
"creator_monthly", "creator_yearly",
"pro_monthly", "pro_yearly",
]
TOPUP_LOOKUP_KEYS = ["topup_60", "topup_200"]
# Queue priority per plan (lower dispatches first). BYOK / anonymous = 2.
PLAN_PRIORITY = {
"pro": 0,
"creator": 1,
"starter": 1,
}
# Max simultaneous managed jobs per user, by plan.
PLAN_JOB_LIMIT = {
"pro": 3,
"creator": 2,
"starter": 2,
}
class Settings:
"""Lazily-evaluated env-backed settings. Access attributes, not the class."""
# Core
@property
def database_url(self) -> str:
return os.environ.get("DATABASE_URL", "")
@property
def jwt_secret(self) -> str:
return os.environ.get("JWT_SECRET", "")
@property
def frontend_url(self) -> str:
return os.environ.get("FRONTEND_URL", "https://openshorts.app").rstrip("/")
@property
def allowed_origins(self) -> list:
raw = os.environ.get("ALLOWED_ORIGINS", "")
origins = [o.strip() for o in raw.split(",") if o.strip()]
return origins or [self.frontend_url]
# Email (Resend)
@property
def resend_api_key(self) -> str:
return os.environ.get("RESEND_API_KEY", "")
@property
def email_from(self) -> str:
return os.environ.get("EMAIL_FROM", "OpenShorts <login@openshorts.app>")
# Google OAuth
@property
def google_client_id(self) -> str:
return os.environ.get("GOOGLE_CLIENT_ID", "")
@property
def google_client_secret(self) -> str:
return os.environ.get("GOOGLE_CLIENT_SECRET", "")
@property
def google_auth_enabled(self) -> bool:
return bool(self.google_client_id and self.google_client_secret)
# Stripe
@property
def stripe_secret_key(self) -> str:
return os.environ.get("STRIPE_SECRET_KEY", "")
@property
def stripe_webhook_secret(self) -> str:
return os.environ.get("STRIPE_WEBHOOK_SECRET", "")
# Managed provider keys (server-owned, only handed to entitled users)
@property
def managed_gemini_key(self) -> str:
return os.environ.get("MANAGED_GEMINI_API_KEY", "")
@property
def managed_upload_post_key(self) -> str:
return os.environ.get("MANAGED_UPLOAD_POST_API_KEY", "")
@property
def openshorts_logo_url(self) -> str:
return os.environ.get("OPENSHORTS_LOGO_URL", "https://openshorts.app/logo.png")
settings = Settings()
def validate_required():
"""Raise a clear error if mandatory cloud settings are missing.
Called from ``cloud.setup`` at startup so a misconfigured deploy fails fast
instead of erroring on the first paid request.
"""
missing = []
if not settings.database_url:
missing.append("DATABASE_URL")
if not settings.jwt_secret:
missing.append("JWT_SECRET")
if missing:
raise RuntimeError(
"BILLING_ENABLED is set but required settings are missing: "
+ ", ".join(missing)
+ ". Set them (see docker-compose.cloud.yml) or unset BILLING_ENABLED "
"to run in self-hosted BYOK mode."
)

49
cloud/database.py Normal file
View file

@ -0,0 +1,49 @@
"""Async SQLAlchemy engine + session management for cloud mode."""
from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
from sqlalchemy.orm import declarative_base
from .config import settings
Base = declarative_base()
_engine = None
_sessionmaker = None
async def init_engine():
"""Create the async engine + sessionmaker and ensure the schema exists.
Uses ``create_all`` for zero-friction boot (additive-only schema in v1).
Alembic (see ``alembic/``) is available for controlled migrations later.
"""
global _engine, _sessionmaker
if _engine is not None:
return
# Import models so their tables register on Base.metadata before create_all.
from . import models # noqa: F401
_engine = create_async_engine(settings.database_url, pool_pre_ping=True)
_sessionmaker = async_sessionmaker(_engine, expire_on_commit=False, class_=AsyncSession)
async with _engine.begin() as conn:
# Case-insensitive email uniqueness.
await conn.execute(text("CREATE EXTENSION IF NOT EXISTS citext"))
await conn.run_sync(Base.metadata.create_all)
def get_sessionmaker():
if _sessionmaker is None:
raise RuntimeError("Cloud DB engine not initialized — call init_engine() first.")
return _sessionmaker
def session():
"""Return a new AsyncSession context manager (for use outside FastAPI deps)."""
return get_sessionmaker()()
async def get_db():
"""FastAPI dependency yielding an AsyncSession."""
async with get_sessionmaker()() as s:
yield s

36
cloud/emails.py Normal file
View file

@ -0,0 +1,36 @@
"""Transactional email via Resend (magic-link login).
If RESEND_API_KEY is unset (e.g. local dev), the link is printed to the server
log instead of sent, so the login flow is still testable without a real inbox.
"""
import httpx
from .config import settings
async def send_magic_link_email(email: str, link: str):
if not settings.resend_api_key:
print(f"✉️ [DEV magic link] {email} -> {link}")
return
html = f"""
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
<h2>Sign in to OpenShorts</h2>
<p>Click the button below to sign in. This link expires in 15 minutes.</p>
<p><a href="{link}" style="display:inline-block;background:#111;color:#fff;
padding:12px 20px;border-radius:8px;text-decoration:none">Sign in</a></p>
<p style="color:#666;font-size:13px">If you didn't request this, ignore this email.</p>
</div>
"""
async with httpx.AsyncClient(timeout=15) as client:
resp = await client.post(
"https://api.resend.com/emails",
headers={"Authorization": f"Bearer {settings.resend_api_key}"},
json={
"from": settings.email_from,
"to": [email],
"subject": "Your OpenShorts sign-in link",
"html": html,
},
)
resp.raise_for_status()

25
cloud/managed_keys.py Normal file
View file

@ -0,0 +1,25 @@
"""Resolution of server-owned (managed) provider keys for entitled users.
Only Gemini and Upload-Post are managed in v1. ElevenLabs and fal stay BYOK.
The functions here are sync and read from the ``CurrentUser`` snapshot so they
can be called inline from ``app.py``'s resolve helpers without awaiting.
"""
from typing import Optional
from .config import settings
def has_active_entitlement(user) -> bool:
"""True if this user may consume managed keys (active plan or top-up credit).
The ``entitled`` flag is computed once in Fase 2/3 when the user is loaded
(active subscription OR remaining top-up minutes).
"""
return bool(user is not None and getattr(user, "entitled", False))
def gemini_key() -> Optional[str]:
return settings.managed_gemini_key or None
def upload_post_key() -> Optional[str]:
return settings.managed_upload_post_key or None

271
cloud/metering.py Normal file
View file

@ -0,0 +1,271 @@
"""Minute metering: quota reservation, commit and release — atomic and restart-safe.
Accounting model (all serialized by a per-user ``SELECT ... FOR UPDATE`` lock):
* A subscription grants ``minutes_per_period`` for the window
``[current_period_start, current_period_end)``. Usage against the plan is the
sum of ledger rows tagged with the current ``period_end`` and status
reserved|committed. Rows from previous periods carry a different ``period_end``
and stop counting automatically → renewal needs no cron.
* Top-ups form a FIFO pool (``minutes_total - minutes_consumed``) that persists
across periods and survives cancellation.
* A reservation consumes IMMEDIATELY (not at commit): plan first, then top-ups
FIFO. Because the whole split happens while holding the user lock, concurrent
reservations can never oversell. ``commit`` just flips the row to committed;
``release`` refunds the exact top-up allocation recorded on the row.
Probing input duration (ffprobe / yt-dlp metadata) lives here too.
"""
import asyncio
import json
import math
import os
import subprocess
from datetime import datetime, timezone, timedelta
from decimal import Decimal
from sqlalchemy import select, update, func, and_
from . import database
from .models import User, Subscription, CreditTopup, UsageLedger
SWEEP_INTERVAL_SECONDS = 15 * 60
STUCK_RESERVATION_HOURS = 3
class QuotaExceeded(Exception):
def __init__(self, remaining: float, required: float):
self.remaining = remaining
self.required = required
super().__init__(f"Quota exceeded: need {required} min, {remaining} remaining")
def _now():
return datetime.now(timezone.utc)
def _D(x) -> Decimal:
return Decimal(str(x))
# --------------------------------------------------------------------------- #
# Duration probing
# --------------------------------------------------------------------------- #
def probe_file_minutes(path: str) -> float:
"""Return the media duration in minutes via ffprobe. Raises on failure."""
out = subprocess.check_output(
["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", path],
stderr=subprocess.STDOUT,
)
seconds = float(out.decode().strip())
return seconds / 60.0
def probe_url_minutes(url: str) -> float:
"""Return the video duration in minutes from yt-dlp metadata (no download).
Raises ValueError if the duration is unknown (e.g. live streams) — the caller
turns that into a 400 for managed users.
"""
import yt_dlp
with yt_dlp.YoutubeDL({"skip_download": True, "quiet": True, "no_warnings": True}) as ydl:
info = ydl.extract_info(url, download=False)
duration = info.get("duration")
if not duration:
raise ValueError("Could not determine video duration")
return float(duration) / 60.0
# --------------------------------------------------------------------------- #
# Balance computation (assumes caller holds the user lock when mutating)
# --------------------------------------------------------------------------- #
async def _active_subscription(session, user_id):
row = (await session.execute(
select(Subscription).where(Subscription.user_id == user_id)
)).scalar_one_or_none()
if row and row.status in ("active", "trialing") and row.current_period_end > _now():
return row
return None
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_(
UsageLedger.user_id == user_id,
UsageLedger.period_end == period_end,
UsageLedger.status.in_(("reserved", "committed")),
))
)).scalar_one()
return _D(total)
async def _topups_fifo(session, user_id):
return list((await session.execute(
select(CreditTopup).where(CreditTopup.user_id == user_id)
.order_by(CreditTopup.created_at.asc())
)).scalars())
async def _balance(session, user_id):
"""Return a dict of the user's current minute balance (read-only)."""
sub = await _active_subscription(session, user_id)
plan_allowance = _D(sub.minutes_per_period) if sub else _D(0)
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)
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_allowance": float(plan_allowance),
"plan_used": float(plan_used),
"plan_remaining": float(plan_remaining),
"topup_remaining": float(topup_remaining),
"remaining": float(plan_remaining + topup_remaining),
"period_end": period_end,
"_sub": sub,
"_plan_remaining_d": plan_remaining,
"_topups": topups,
}
async def get_balance(user_id) -> dict:
"""Public read-only balance for /api/me."""
async with database.session() as session:
b = await _balance(session, user_id)
return {k: v for k, v in b.items() if not k.startswith("_")}
def has_topup_credit_sync(remaining: float) -> bool:
return remaining > 0
# --------------------------------------------------------------------------- #
# Reserve / commit / release
# --------------------------------------------------------------------------- #
async def reserve_minutes(user_id, minutes: float, job_id: str, job_type: str = "process"):
"""Atomically reserve ``minutes``. Returns the ledger row id.
Raises ``QuotaExceeded`` if the user lacks the minutes. Consumes plan first,
then top-ups FIFO, all under the per-user lock.
"""
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)
plan_remaining = b["_plan_remaining_d"]
remaining_total = _D(b["remaining"])
if minutes > remaining_total:
raise QuotaExceeded(remaining=float(remaining_total), required=float(minutes))
from_plan = min(minutes, plan_remaining)
from_topup = minutes - from_plan
allocations = []
need = from_topup
if need > 0:
for t in b["_topups"]:
if need <= 0:
break
avail = _D(t.minutes_total) - _D(t.minutes_consumed)
if avail <= 0:
continue
take = min(avail, need)
t.minutes_consumed = _D(t.minutes_consumed) + take
allocations.append({"topup_id": str(t.id), "minutes": float(take)})
need -= take
row = UsageLedger(
user_id=user_id,
job_id=job_id,
job_type=job_type,
minutes=minutes,
minutes_from_plan=from_plan,
minutes_from_topup=from_topup,
topup_allocations=allocations or None,
status="reserved",
period_end=b["period_end"],
)
session.add(row)
await session.flush()
return str(row.id)
async def commit_reservation(ledger_id: str):
"""Flip a reservation to committed. Consumption already happened at reserve."""
async with database.session() as session:
async with session.begin():
row = await session.get(UsageLedger, ledger_id)
if row and row.status == "reserved":
row.status = "committed"
async def release_reservation(ledger_id: str):
"""Release a reservation and refund its exact top-up allocation."""
async with database.session() as session:
async with session.begin():
row = await session.get(UsageLedger, ledger_id)
if not row or row.status != "reserved":
return
await session.execute(
select(User.id).where(User.id == row.user_id).with_for_update()
)
for alloc in (row.topup_allocations or []):
t = await session.get(CreditTopup, alloc["topup_id"])
if t is not None:
t.minutes_consumed = max(_D(0), _D(t.minutes_consumed) - _D(alloc["minutes"]))
row.status = "released"
async def release_orphaned_reservations():
"""At startup, release every still-``reserved`` row.
Jobs live only in memory, so a restart loses all in-flight jobs; their
reservations must be refunded or they would leak quota forever.
"""
async with database.session() as session:
ids = list((await session.execute(
select(UsageLedger.id).where(UsageLedger.status == "reserved")
)).scalars())
for lid in ids:
await release_reservation(str(lid))
if ids:
print(f"☁️ Released {len(ids)} orphaned reservation(s) at startup.")
async def _sweep_once():
cutoff = _now() - timedelta(hours=STUCK_RESERVATION_HOURS)
async with database.session() as session:
ids = list((await session.execute(
select(UsageLedger.id).where(and_(
UsageLedger.status == "reserved",
UsageLedger.created_at < cutoff,
))
)).scalars())
for lid in ids:
await release_reservation(str(lid))
if ids:
print(f"☁️ Swept {len(ids)} stuck reservation(s).")
async def _sweeper_loop():
while True:
try:
await asyncio.sleep(SWEEP_INTERVAL_SECONDS)
await _sweep_once()
except asyncio.CancelledError:
break
except Exception as e: # never let the sweeper die
print(f"⚠️ Metering sweeper error: {e}")
def start_sweeper():
asyncio.create_task(_sweeper_loop())

105
cloud/models.py Normal file
View file

@ -0,0 +1,105 @@
"""SQLAlchemy models for cloud mode.
Money and quota live here, so the accounting tables (subscriptions, credit_topups,
usage_ledger) are designed for atomic, restart-safe metering — see cloud/metering.py.
"""
import uuid
from sqlalchemy import (
Column, String, Integer, Numeric, Boolean, DateTime, ForeignKey, Text, func, Index,
)
from sqlalchemy.dialects.postgresql import UUID, CITEXT, JSONB
from .database import Base
def _uuid():
return uuid.uuid4()
class User(Base):
__tablename__ = "users"
id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid)
email = Column(CITEXT, unique=True, nullable=False)
google_sub = Column(Text, unique=True, nullable=True)
stripe_customer_id = Column(Text, unique=True, nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
last_login_at = Column(DateTime(timezone=True), nullable=True)
class MagicLinkToken(Base):
__tablename__ = "magic_link_tokens"
id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid)
email = Column(CITEXT, nullable=False)
token_hash = Column(Text, unique=True, nullable=False) # sha256 of the raw token
expires_at = Column(DateTime(timezone=True), nullable=False)
used_at = Column(DateTime(timezone=True), nullable=True)
request_ip = Column(Text, nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
__table_args__ = (Index("ix_magic_email_created", "email", "created_at"),)
class Subscription(Base):
__tablename__ = "subscriptions"
id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid)
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
unique=True, nullable=False) # one active sub per user
stripe_subscription_id = Column(Text, unique=True, nullable=False)
stripe_price_id = Column(Text, nullable=True)
plan = Column(String(20), nullable=False) # starter | creator | pro
interval = Column(String(10), nullable=False) # month | year
status = Column(String(20), nullable=False) # active | trialing | past_due | canceled | incomplete
minutes_per_period = Column(Integer, nullable=False)
current_period_start = Column(DateTime(timezone=True), nullable=False)
current_period_end = Column(DateTime(timezone=True), nullable=False)
cancel_at_period_end = Column(Boolean, nullable=False, default=False)
last_event_at = Column(DateTime(timezone=True), nullable=True) # ordering guard for webhooks
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
class CreditTopup(Base):
__tablename__ = "credit_topups"
id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid)
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
nullable=False, index=True)
stripe_session_id = Column(Text, unique=True, nullable=True) # idempotency for the webhook
minutes_total = Column(Integer, nullable=False)
minutes_consumed = Column(Numeric(10, 2), nullable=False, default=0) # FIFO drain target
created_at = Column(DateTime(timezone=True), server_default=func.now())
class UsageLedger(Base):
__tablename__ = "usage_ledger"
id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid)
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
job_id = Column(Text, nullable=False)
job_type = Column(String(20), nullable=False, default="process")
minutes = Column(Numeric(10, 2), nullable=False) # total reserved
minutes_from_plan = Column(Numeric(10, 2), nullable=False, default=0)
minutes_from_topup = Column(Numeric(10, 2), nullable=False, default=0)
# [{topup_id, minutes}] — exact FIFO allocation, so release can refund precisely.
topup_allocations = Column(JSONB, nullable=True)
status = Column(String(12), nullable=False, default="reserved") # reserved | committed | released
period_end = Column(DateTime(timezone=True), nullable=True) # sub period this counts against
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
__table_args__ = (
Index("ix_usage_user_status", "user_id", "status"),
Index("ix_usage_user_period_status", "user_id", "period_end", "status"),
)
class UploadPostProfile(Base):
__tablename__ = "upload_post_profiles"
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
primary_key=True)
profile_username = Column(Text, unique=True, nullable=False)
created_at = Column(DateTime(timezone=True), server_default=func.now())
class StripeEvent(Base):
__tablename__ = "stripe_events"
id = Column(Text, primary_key=True) # Stripe event.id — dedupe key
type = Column(Text, nullable=True)
created = Column(DateTime(timezone=True), nullable=True)
processed_at = Column(DateTime(timezone=True), server_default=func.now())

93
cloud/oauth.py Normal file
View file

@ -0,0 +1,93 @@
"""Google OAuth (redirect flow) for cloud mode.
GET /api/auth/google -> redirect to Google consent
GET /api/auth/google/callback -> exchange code, upsert user, redirect to the
frontend with the JWT in the URL hash (never
reaches server logs).
Registration happens in ``register()`` (called from setup_sync) only when Google
credentials are configured; otherwise the endpoints 404.
"""
from datetime import datetime, timezone
from fastapi import APIRouter, Request, HTTPException
from starlette.responses import RedirectResponse
from sqlalchemy import select
from .config import settings
from . import database
from .models import User
from .auth import issue_jwt
router = APIRouter()
oauth = None
def register():
"""Register the Google OAuth client if credentials are present."""
global oauth
if not settings.google_auth_enabled:
return
from authlib.integrations.starlette_client import OAuth
oauth = OAuth()
oauth.register(
name="google",
client_id=settings.google_client_id,
client_secret=settings.google_client_secret,
server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
client_kwargs={"scope": "openid email profile"},
)
def _now():
return datetime.now(timezone.utc)
@router.get("/api/auth/google")
async def google_login(request: Request):
if oauth is None:
raise HTTPException(status_code=404, detail="Google login not configured")
redirect_uri = str(request.url_for("google_callback"))
return await oauth.google.authorize_redirect(request, redirect_uri)
@router.get("/api/auth/google/callback", name="google_callback")
async def google_callback(request: Request):
if oauth is None:
raise HTTPException(status_code=404, detail="Google login not configured")
try:
token = await oauth.google.authorize_access_token(request)
except Exception:
return RedirectResponse(f"{settings.frontend_url}/#/auth/callback?error=oauth")
userinfo = token.get("userinfo")
if not userinfo:
userinfo = await oauth.google.userinfo(token=token)
email = (userinfo.get("email") or "").lower()
google_sub = userinfo.get("sub")
if not email:
return RedirectResponse(f"{settings.frontend_url}/#/auth/callback?error=noemail")
async with database.session() as session:
async with session.begin():
user = (await session.execute(
select(User).where(User.google_sub == google_sub)
)).scalar_one_or_none()
if user is None:
# Merge with an existing magic-link account of the same email.
user = (await session.execute(
select(User).where(User.email == email)
)).scalar_one_or_none()
if user is None:
user = User(email=email, google_sub=google_sub, last_login_at=_now())
session.add(user)
await session.flush()
else:
user.google_sub = google_sub
user.last_login_at = _now()
else:
user.last_login_at = _now()
user_id, user_email = user.id, user.email
jwt_token = issue_jwt(user_id, user_email)
return RedirectResponse(f"{settings.frontend_url}/#/auth/callback?token={jwt_token}")

102
cloud/social_profiles.py Normal file
View file

@ -0,0 +1,102 @@
"""Upload-Post white-label profiles for managed users.
Each OpenShorts user maps to one Upload-Post profile (a container for their
connected socials). We create it lazily and generate branded connection links so
the user connects TikTok/IG/YouTube on a page that looks like OpenShorts.
Docs: https://docs.upload-post.com/guides/user-profile-integration
"""
import httpx
from fastapi import APIRouter, Request, HTTPException
from .config import settings
from . import database
from .models import UploadPostProfile
router = APIRouter()
API_BASE = "https://api.upload-post.com/api"
CONNECT_PLATFORMS = ["tiktok", "instagram", "youtube"]
def _auth_headers():
return {"Authorization": f"Apikey {settings.managed_upload_post_key}"}
def profile_username_for(user_id) -> str:
return f"os_{user_id.hex[:12]}"
async def _create_remote_profile(username: str):
"""Create the profile in Upload-Post. Treat 'already exists' as success."""
async with httpx.AsyncClient(timeout=20) as client:
resp = await client.post(
f"{API_BASE}/uploadposts/users",
headers=_auth_headers(),
json={"username": username},
)
if resp.status_code in (200, 201):
return
text = resp.text.lower()
# Idempotency: if it already exists, that's fine.
if resp.status_code == 400 and ("exist" in text or "already" in text):
return
# Upload-Post plan cap reached — surface a clean, actionable error, not a 500.
if "profile_limit_reached" in text or "limit of" in text:
raise HTTPException(
status_code=503,
detail="Social posting is temporarily unavailable (provider profile limit). "
"Please try again later.",
)
resp.raise_for_status()
async def ensure_profile(user) -> str:
"""Return the user's Upload-Post profile username, creating it if needed."""
async with database.session() as s:
prof = await s.get(UploadPostProfile, user.id)
if prof:
return prof.profile_username
username = profile_username_for(user.id)
await _create_remote_profile(username)
async with database.session() as s:
async with s.begin():
prof = await s.get(UploadPostProfile, user.id) # re-check under txn
if prof:
return prof.profile_username
s.add(UploadPostProfile(user_id=user.id, profile_username=username))
return username
async def get_connect_url(username: str) -> str:
"""Generate a branded, single-use connection URL (~1h) for the user's socials."""
payload = {
"username": username,
"logoImage": settings.openshorts_logo_url,
"connectTitle": "Connect your social accounts",
"connectDescription": "Link TikTok, Instagram and YouTube to post your shorts directly from OpenShorts.",
"redirectUrl": f"{settings.frontend_url}/#/account?connected=1",
"redirectButtonText": "Back to OpenShorts",
"platforms": CONNECT_PLATFORMS,
}
async with httpx.AsyncClient(timeout=20) as client:
resp = await client.post(
f"{API_BASE}/uploadposts/users/generate-jwt",
headers=_auth_headers(),
json=payload,
)
resp.raise_for_status()
data = resp.json()
return data.get("access_url") or data.get("url")
@router.post("/api/social/connect")
async def social_connect(request: Request):
"""Return a branded Upload-Post connection URL for the signed-in managed user."""
from .auth import get_current_user_required
user = await get_current_user_required(request)
username = await ensure_profile(user)
access_url = await get_connect_url(username)
return {"access_url": access_url}

View file

@ -9,6 +9,13 @@ import ThumbnailStudio from './components/ThumbnailStudio';
import SaaShortsTab from './components/SaaShortsTab'; import SaaShortsTab from './components/SaaShortsTab';
import UGCGallery from './components/UGCGallery'; import UGCGallery from './components/UGCGallery';
import ScheduleWeekModal from './components/ScheduleWeekModal'; import ScheduleWeekModal from './components/ScheduleWeekModal';
import UsageMeter from './components/UsageMeter';
import TopUpModal from './components/TopUpModal';
import LoginModal from './components/LoginModal';
import TrialGate from './components/TrialGate';
import AdvancedBanner from './components/AdvancedBanner';
import { useAuth } from './contexts/AuthContext';
import { apiFetch, apiJson, QuotaError } from './lib/api';
import { getApiUrl } from './config'; import { getApiUrl } from './config';
// Enhanced "Encryption" using XOR + Base64 with a Salt // Enhanced "Encryption" using XOR + Base64 with a Salt
@ -134,6 +141,12 @@ const pollJob = async (jobId) => {
}; };
function App() { function App() {
// Cloud auth/billing session (inert when billing is disabled).
const { billingEnabled, isManaged, isSignedIn, signingIn } = useAuth();
const [showLogin, setShowLogin] = useState(false);
const [showTopUp, setShowTopUp] = useState(false);
const [topUpInfo, setTopUpInfo] = useState({});
const [apiKey, setApiKey] = useState(localStorage.getItem('gemini_key') || ''); const [apiKey, setApiKey] = useState(localStorage.getItem('gemini_key') || '');
// Social API State - Load encrypted or plain // Social API State - Load encrypted or plain
const [uploadPostKey, setUploadPostKey] = useState(() => { const [uploadPostKey, setUploadPostKey] = useState(() => {
@ -320,8 +333,34 @@ function App() {
} }
}; };
// Hosted is paid-only (no BYOK core). Self-host uses BYOK keys.
// `keysMissing` now means "self-host BYOK keys missing" — it never fires on hosted.
const keysMissing = !billingEnabled && (!apiKey || !uploadPostKey);
const needsPlan = billingEnabled && !isManaged; // hosted, signed-out or no active plan/trial
// Included in the plan (fully managed, no keys): Clip Generator + YouTube Studio.
// Advanced (bring your own fal.ai + ElevenLabs keys): AI Shorts + AI Agent.
const INCLUDED_TOOL_TABS = ['dashboard', 'thumbnails'];
const ADVANCED_TOOL_TABS = ['saasshorts', 'ai-agent'];
const TOOL_NAMES = { dashboard: 'the Clip Generator', thumbnails: 'the YouTube Studio' };
const gateThisTab = needsPlan && INCLUDED_TOOL_TABS.includes(activeTab); // included tool, no plan yet
const advancedThisTab = billingEnabled && ADVANCED_TOOL_TABS.includes(activeTab); // BYOK-notice tools
// Managed users connect their socials via Upload-Post's branded hosted page.
const handleConnectSocials = async () => {
try {
const { access_url } = await apiJson('/api/social/connect', { method: 'POST' });
if (access_url) window.open(access_url, '_blank', 'noopener');
} catch (e) {
alert('Could not open the connection page. Please try again.');
}
};
const handleProcess = async (data) => { const handleProcess = async (data) => {
if (!apiKey || !uploadPostKey) { // Hosted: must be signed in AND on an active plan/trial. Self-host: BYOK keys.
if (billingEnabled) {
if (!isSignedIn) { setShowLogin(true); return; }
if (!isManaged) { window.location.hash = '#/pricing'; return; }
} else if (keysMissing) {
setShowKeyModal(true); setShowKeyModal(true);
return; return;
} }
@ -332,7 +371,9 @@ function App() {
try { try {
let body; let body;
const headers = { 'X-Gemini-Key': apiKey }; // BYOK sends the Gemini header; managed users rely on the bearer token
// that apiFetch attaches automatically.
const headers = apiKey ? { 'X-Gemini-Key': apiKey } : {};
if (data.type === 'url') { if (data.type === 'url') {
headers['Content-Type'] = 'application/json'; headers['Content-Type'] = 'application/json';
@ -344,17 +385,19 @@ function App() {
body = formData; body = formData;
} }
const res = await fetch(getApiUrl('/api/process'), { const res = await apiFetch('/api/process', { method: 'POST', headers, body });
method: 'POST',
headers: data.type === 'url' ? headers : { 'X-Gemini-Key': apiKey },
body
});
if (!res.ok) throw new Error(await res.text()); if (!res.ok) throw new Error(await res.text());
const resData = await res.json(); const resData = await res.json();
setJobId(resData.job_id); setJobId(resData.job_id);
} catch (e) { } catch (e) {
if (e instanceof QuotaError) {
setStatus('idle');
setTopUpInfo({ required: e.minutesRequired, remaining: e.minutesRemaining });
setShowTopUp(true);
return;
}
setStatus('error'); setStatus('error');
setLogs(l => [...l, `Error starting job: ${e.message}`]); setLogs(l => [...l, `Error starting job: ${e.message}`]);
} }
@ -503,11 +546,28 @@ function App() {
/> />
)} )}
{(!apiKey || !uploadPostKey) && ( {/* Cloud: minutes meter + account/sign-in */}
{billingEnabled && isManaged && (
<UsageMeter onClick={() => { window.location.hash = '#/account'; }} />
)}
{billingEnabled && isSignedIn && !isManaged && (
<button onClick={() => { window.location.hash = '#/pricing'; }}
className="text-xs text-primary bg-primary/10 hover:bg-primary/20 px-3 py-1 rounded-full border border-primary/30 transition-colors">
Start free trial
</button>
)}
{billingEnabled && !isSignedIn && (
<button onClick={() => setShowLogin(true)}
className="text-xs bg-white/10 hover:bg-white/20 px-3 py-1 rounded-full transition-colors">
Sign in
</button>
)}
{keysMissing && (
<button <button
onClick={() => setActiveTab('settings')} onClick={() => (billingEnabled && !isSignedIn ? setShowLogin(true) : setActiveTab('settings'))}
className="text-xs text-amber-400 bg-amber-500/10 hover:bg-amber-500/20 px-3 py-1 rounded-full border border-amber-500/30 transition-colors flex items-center gap-1.5" className="text-xs text-amber-400 bg-amber-500/10 hover:bg-amber-500/20 px-3 py-1 rounded-full border border-amber-500/30 transition-colors flex items-center gap-1.5"
title="Click to configure your API keys" title="Configure API keys or choose a plan"
> >
<AlertTriangle size={12} /> <AlertTriangle size={12} />
{!apiKey && !uploadPostKey {!apiKey && !uploadPostKey
@ -521,7 +581,7 @@ function App() {
</header> </header>
{/* Persistent Missing Keys Banner — visible on every screen */} {/* Persistent Missing Keys Banner — visible on every screen */}
{(!apiKey || !uploadPostKey) && activeTab !== 'settings' && ( {keysMissing && activeTab !== 'settings' && (
<div className="mx-6 mt-3 p-3 bg-amber-500/10 border border-amber-500/30 rounded-xl flex items-center justify-between gap-4 shrink-0 animate-[fadeIn_0.3s_ease-out]"> <div className="mx-6 mt-3 p-3 bg-amber-500/10 border border-amber-500/30 rounded-xl flex items-center justify-between gap-4 shrink-0 animate-[fadeIn_0.3s_ease-out]">
<div className="flex items-center gap-3 text-sm text-amber-200"> <div className="flex items-center gap-3 text-sm text-amber-200">
<KeyRound size={16} className="shrink-0 text-amber-400" /> <KeyRound size={16} className="shrink-0 text-amber-400" />
@ -559,6 +619,12 @@ function App() {
</div> </div>
)} )}
{/* Included tools (Clip Generator, YouTube Studio): non-blocking trial prompt. */}
{gateThisTab && <TrialGate toolName={TOOL_NAMES[activeTab] || 'this'} />}
{/* Advanced tools (AI Shorts, AI Agent): BYOK fal.ai + ElevenLabs notice. */}
{advancedThisTab && <AdvancedBanner needsPlan={needsPlan} onKeys={() => setActiveTab('settings')} />}
{/* Main Workspace */} {/* Main Workspace */}
<div className="flex-1 overflow-hidden relative"> <div className="flex-1 overflow-hidden relative">
@ -571,6 +637,36 @@ function App() {
<Shield size={12} /> Privacy: keys only live in your browser (sent to backend just to process) <Shield size={12} /> Privacy: keys only live in your browser (sent to backend just to process)
</div> </div>
</div> </div>
{isManaged ? (
<div className="glass-panel p-6 mb-2">
<div className="flex items-center justify-between mb-3">
<h2 className="text-lg font-semibold">Included in your plan</h2>
<span className="text-[10px] bg-green-500/10 border border-green-500/30 px-2 py-0.5 rounded text-green-400 uppercase tracking-wider">Managed</span>
</div>
<p className="text-xs text-zinc-500 mb-5 leading-relaxed">
Your plan includes the <strong>Clip Generator</strong> and <strong>YouTube Studio</strong>,
fully managed — no API keys required. AI Shorts &amp; dubbing use your own fal.ai / ElevenLabs
keys (below). Connect your social accounts to publish directly.
</p>
<button onClick={handleConnectSocials} className="btn-primary py-2 px-4 text-sm flex items-center gap-2">
<Share2 size={16} /> Connect social accounts
</button>
</div>
) : billingEnabled ? (
<div className="glass-panel p-6 mb-2 border-primary/30 ring-1 ring-primary/20">
<div className="flex items-center justify-between mb-3">
<h2 className="text-lg font-semibold">Start your free trial</h2>
<span className="text-[10px] bg-primary/10 border border-primary/30 px-2 py-0.5 rounded text-primary uppercase tracking-wider">3 days free</span>
</div>
<p className="text-xs text-zinc-500 mb-5 leading-relaxed">
Generate shorts with zero setup — no API keys needed. 3 days free, then from $12/mo. Cancel anytime.
</p>
<button onClick={() => { window.location.hash = '#/pricing'; }} className="btn-primary py-2 px-4 text-sm flex items-center gap-2">
<Sparkles size={16} /> See plans & start trial
</button>
</div>
) : (
<>
<KeyInput onKeySet={setApiKey} savedKey={apiKey} /> <KeyInput onKeySet={setApiKey} savedKey={apiKey} />
<div className={`glass-panel p-6 mt-8 ${!uploadPostKey ? 'border-amber-500/30 ring-1 ring-amber-500/20' : ''}`}> <div className={`glass-panel p-6 mt-8 ${!uploadPostKey ? 'border-amber-500/30 ring-1 ring-amber-500/20' : ''}`}>
@ -620,14 +716,17 @@ function App() {
</div> </div>
</div> </div>
</>
)}
<div className="glass-panel p-6 mt-8"> <div className="glass-panel p-6 mt-8">
<div className="flex items-center justify-between mb-4"> <div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold">Video Translation</h2> <h2 className="text-lg font-semibold">Video Translation</h2>
<span className="text-[10px] bg-white/5 border border-white/5 px-2 py-0.5 rounded text-zinc-500 uppercase tracking-wider">Optional</span> <span className="text-[10px] bg-amber-500/10 border border-amber-500/30 px-2 py-0.5 rounded text-amber-400 uppercase tracking-wider">Your own key</span>
</div> </div>
<p className="text-xs text-zinc-500 mb-6 leading-relaxed"> <p className="text-xs text-zinc-500 mb-6 leading-relaxed">
Translate your clips to different languages using <strong>ElevenLabs</strong> AI dubbing. For <strong>AI Shorts &amp; dubbing</strong> — bring your own key. Translate your clips to different
Automatically translates speech while preserving the original voice characteristics. languages using <strong>ElevenLabs</strong> AI dubbing (billed by ElevenLabs). Not covered by your plan.
</p> </p>
<div className="space-y-4"> <div className="space-y-4">
<label className="block text-sm text-zinc-400">ElevenLabs API Key</label> <label className="block text-sm text-zinc-400">ElevenLabs API Key</label>
@ -674,11 +773,12 @@ function App() {
<div className="glass-panel p-6 mt-8"> <div className="glass-panel p-6 mt-8">
<div className="flex items-center justify-between mb-4"> <div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold">AI Shorts (UGC Videos)</h2> <h2 className="text-lg font-semibold">AI Shorts (UGC Videos)</h2>
<span className="text-[10px] bg-violet-500/10 border border-violet-500/20 px-2 py-0.5 rounded text-violet-400 uppercase tracking-wider">New</span> <span className="text-[10px] bg-amber-500/10 border border-amber-500/30 px-2 py-0.5 rounded text-amber-400 uppercase tracking-wider">Your own key</span>
</div> </div>
<p className="text-xs text-zinc-500 mb-6 leading-relaxed"> <p className="text-xs text-zinc-500 mb-6 leading-relaxed">
Generate UGC-style videos with AI actors for any product or business using <strong>fal.ai</strong>. Generate UGC-style videos with AI actors for any product or business using <strong>fal.ai</strong>.
Just describe your product or paste a URL. Requires fal.ai + ElevenLabs API keys. <strong> Not covered by your plan</strong> — bring your own fal.ai + ElevenLabs keys (billed by those
providers, ~$0.65-2 per video). Your plan still covers the AI script &amp; orchestration.
</p> </p>
<div className="space-y-4"> <div className="space-y-4">
<label className="block text-sm text-zinc-400">fal.ai API Key</label> <label className="block text-sm text-zinc-400">fal.ai API Key</label>
@ -726,7 +826,7 @@ function App() {
{/* View: SaaS Shorts */} {/* View: SaaS Shorts */}
{activeTab === 'saasshorts' && ( {activeTab === 'saasshorts' && (
<SaaShortsTab geminiApiKey={apiKey} elevenLabsKey={elevenLabsKey} falKey={falKey} uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} /> <SaaShortsTab geminiApiKey={apiKey} elevenLabsKey={elevenLabsKey} falKey={falKey} uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} managed={isManaged} />
)} )}
{/* View: AI Agent */} {/* View: AI Agent */}
@ -852,7 +952,7 @@ function App() {
{/* View: Thumbnails */} {/* View: Thumbnails */}
{activeTab === 'thumbnails' && ( {activeTab === 'thumbnails' && (
<ThumbnailStudio geminiApiKey={apiKey} uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} /> <ThumbnailStudio geminiApiKey={apiKey} uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} managed={isManaged} />
)} )}
{/* View: Gallery */} {/* View: Gallery */}
@ -1106,6 +1206,15 @@ function App() {
uploadPostKey={uploadPostKey} uploadPostKey={uploadPostKey}
uploadUserId={uploadUserId} uploadUserId={uploadUserId}
/> />
{showLogin && <LoginModal onClose={() => setShowLogin(false)} />}
{showTopUp && (
<TopUpModal
onClose={() => setShowTopUp(false)}
required={topUpInfo.required}
remaining={topUpInfo.remaining}
/>
)}
</div> </div>
); );
} }

View file

@ -136,7 +136,7 @@ export default function Landing({ onLaunchApp }) {
}, },
{ {
question: "Is OpenShorts really free? What's the catch?", question: "Is OpenShorts really free? What's the catch?",
answer: "OpenShorts is 100% free and open source. You self-host it using Docker on your own machine or server. It uses three external APIs — all with free tiers. Google Gemini API (required) powers the AI analysis, viral moment detection, and thumbnail generation — its free tier includes 1,500 requests per day. ElevenLabs API (optional) enables AI voice dubbing in 30+ languages — free tier included. Upload-Post API (optional) is a social media API that allows direct publishing to YouTube, TikTok, and Instagram — 10 free uploads/month, no credit card required. There are no watermarks, no usage limits, no monthly subscriptions, and no per-video fees — unlike 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'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)."
}, },
{ {
question: "How does OpenShorts compare to Opus Clip?", question: "How does OpenShorts compare to Opus Clip?",
@ -259,6 +259,11 @@ export default function Landing({ onLaunchApp }) {
</a> </a>
</div> </div>
<p className="text-sm text-zinc-500 mb-12">
<strong className="text-zinc-300">Free to self-host</strong> with Docker (bring your own keys) ·
or use it here with no setup — <strong className="text-zinc-300">3-day free trial, then from $12/mo</strong>
</p>
{/* Platform Icons */} {/* Platform Icons */}
<div className="flex items-center justify-center gap-6 text-zinc-500"> <div className="flex items-center justify-center gap-6 text-zinc-500">
<span className="text-sm">Export to:</span> <span className="text-sm">Export to:</span>
@ -302,6 +307,46 @@ export default function Landing({ onLaunchApp }) {
</div> </div>
</section> </section>
{/* Two ways to use it: free self-host vs paid hosted */}
<section className="py-16 px-6">
<div className="max-w-4xl mx-auto text-center mb-10">
<h2 className="text-3xl md:text-4xl font-bold mb-3">Two ways to use OpenShorts</h2>
<p className="text-zinc-400 max-w-2xl mx-auto">Run it yourself for free, or let us run everything for you.</p>
</div>
<div className="max-w-4xl mx-auto grid md:grid-cols-2 gap-6">
<div className="bg-surface/50 border border-white/10 rounded-2xl p-8 flex flex-col">
<div className="flex items-center gap-2 mb-2">
<Github size={20} className="text-zinc-300" />
<h3 className="text-xl font-bold text-white">Self-hosted</h3>
<span className="text-[10px] bg-green-500/10 border border-green-500/30 px-2 py-0.5 rounded text-green-400 uppercase tracking-wider">Free</span>
</div>
<p className="text-zinc-400 text-sm leading-relaxed mb-5 flex-1">
100% free and open source. Run it with Docker on your own machine, bring your own API keys,
no limits, no subscription. Best if you're technical and want full control.
</p>
<a href="https://github.com/mutonby/openshorts" target="_blank" rel="noopener noreferrer"
className="inline-flex items-center justify-center gap-2 bg-white/10 hover:bg-white/20 text-white px-5 py-3 rounded-xl font-medium transition-all">
<Github size={18} /> Get it on GitHub
</a>
</div>
<div className="bg-primary/5 border border-primary/30 rounded-2xl p-8 flex flex-col">
<div className="flex items-center gap-2 mb-2">
<Sparkles size={20} className="text-primary" />
<h3 className="text-xl font-bold text-white">Hosted on openshorts.app</h3>
<span className="text-[10px] bg-primary/10 border border-primary/30 px-2 py-0.5 rounded text-primary uppercase tracking-wider">From $12/mo</span>
</div>
<p className="text-zinc-400 text-sm leading-relaxed mb-5 flex-1">
Zero setup, no API keys, we run all the AI and compute for you. <b>3-day free trial</b>, then a plan
from $12/mo (100 min). Best if you just want to make clips without any technical hassle.
</p>
<button onClick={() => { window.location.hash = '#/pricing'; }}
className="inline-flex items-center justify-center gap-2 bg-primary hover:bg-blue-600 text-white px-5 py-3 rounded-xl font-medium transition-all">
See plans <ArrowRight size={18} />
</button>
</div>
</div>
</section>
{/* 3 Tools in 1 Section */} {/* 3 Tools in 1 Section */}
<section className="py-20 px-6"> <section className="py-20 px-6">
<div className="max-w-6xl mx-auto"> <div className="max-w-6xl mx-auto">

View file

@ -0,0 +1,135 @@
import React, { useState, useEffect, useCallback } from 'react';
import { Loader2, CreditCard, LogOut, Zap, Plus } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api';
const fmt1 = (n) => Math.round((n || 0) * 10) / 10;
// Account/billing page: plan, usage meter, top-ups, manage billing, logout.
export default function AccountPage() {
const { me, refreshMe, logout, plan, minutes } = useAuth();
const [busy, setBusy] = useState(false);
const [topups, setTopups] = useState([]);
const [activating, setActivating] = useState(false);
// After returning from Checkout the webhook may lag — poll /api/me briefly.
useEffect(() => {
const hash = window.location.hash || '';
if (!hash.includes('checkout=success')) return;
setActivating(true);
let tries = 0;
const t = setInterval(async () => {
tries += 1;
const data = await refreshMe();
if ((data && data.plan) || tries > 15) {
clearInterval(t);
setActivating(false);
window.location.hash = '#/account';
}
}, 2000);
return () => clearInterval(t);
}, [refreshMe]);
useEffect(() => {
apiJson('/api/billing/plans').then((d) => setTopups(d.topups || [])).catch(() => {});
}, []);
const openPortal = useCallback(async () => {
setBusy(true);
try {
const { url } = await apiJson('/api/billing/portal', { method: 'POST' });
window.location.href = url;
} catch (e) { setBusy(false); alert('Could not open billing portal.'); }
}, []);
const buyTopup = useCallback(async (price_id) => {
setBusy(true);
try {
const { url } = await apiJson('/api/billing/checkout', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ price_id }),
});
window.location.href = url;
} catch (e) { setBusy(false); alert('Could not start checkout.'); }
}, []);
if (!me) return <div className="flex justify-center py-16"><Loader2 className="animate-spin text-primary" /></div>;
const m = minutes || {};
const total = (m.plan_allowance || 0) + (m.topup_remaining || 0) + (m.plan_used || 0);
const usedPct = total > 0 ? Math.min(100, ((m.plan_used || 0) / (m.plan_allowance || 1)) * 100) : 0;
return (
<div className="max-w-2xl mx-auto space-y-6">
<div className="flex items-center justify-between">
<div>
<h2 className="text-2xl font-bold">Your account</h2>
<p className="text-zinc-400 text-sm">{me.user?.email}</p>
</div>
<button onClick={logout} className="text-zinc-400 hover:text-white flex items-center gap-2 text-sm">
<LogOut size={16} /> Sign out
</button>
</div>
{activating && (
<div className="bg-primary/10 border border-primary/30 rounded-xl p-4 text-sm flex items-center gap-2">
<Loader2 size={16} className="animate-spin" /> Activating your plan…
</div>
)}
<div className="bg-surface border border-white/10 rounded-2xl p-6">
<div className="flex items-center justify-between mb-4">
<div>
<span className="text-lg font-semibold capitalize">{plan ? `${plan} plan` : 'No active plan'}</span>
{me.status && me.status !== 'active' && (
<span className="ml-2 text-xs px-2 py-0.5 rounded-full bg-yellow-500/20 text-yellow-400">{me.status}</span>
)}
{me.cancel_at_period_end && (
<span className="ml-2 text-xs px-2 py-0.5 rounded-full bg-zinc-500/20 text-zinc-300">cancels at period end</span>
)}
</div>
<button onClick={openPortal} disabled={busy}
className="text-sm bg-white/10 hover:bg-white/20 px-4 py-2 rounded-lg flex items-center gap-2">
<CreditCard size={16} /> Manage billing
</button>
</div>
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-zinc-400">Plan minutes</span>
<span>{fmt1(m.plan_used)} / {fmt1(m.plan_allowance)} used</span>
</div>
<div className="h-2 bg-white/10 rounded-full overflow-hidden">
<div className="h-full bg-primary transition-all" style={{ width: `${usedPct}%` }} />
</div>
<div className="flex justify-between text-sm pt-1">
<span className="text-zinc-400">Top-up minutes</span>
<span>{fmt1(m.topup_remaining)} remaining</span>
</div>
<div className="flex justify-between text-base font-semibold pt-2 border-t border-white/5">
<span>Total remaining</span>
<span className="text-primary">{fmt1(m.remaining)} min</span>
</div>
</div>
</div>
{topups.length > 0 && (
<div className="bg-surface border border-white/10 rounded-2xl p-6">
<h3 className="font-semibold mb-1 flex items-center gap-2"><Plus size={16} /> Buy more minutes</h3>
<p className="text-zinc-400 text-sm mb-4">Top-ups never expire while your plan is active.</p>
<div className="grid grid-cols-2 gap-3">
{topups.map((t) => (
<button key={t.price_id} onClick={() => buyTopup(t.price_id)} disabled={busy}
className="border border-white/10 hover:border-primary rounded-xl p-4 text-left transition-all">
<div className="text-lg font-bold">+{t.minutes} min</div>
<div className="text-zinc-400 text-sm">
{new Intl.NumberFormat('en-US', { style: 'currency', currency: (t.currency || 'usd').toUpperCase(), maximumFractionDigits: 0 }).format((t.amount || 0) / 100)}
</div>
</button>
))}
</div>
</div>
)}
</div>
);
}

View file

@ -0,0 +1,27 @@
import React from 'react';
import { KeyRound, ArrowRight } from 'lucide-react';
// Banner for advanced tools (AI Shorts, AI Agent) that use fal.ai + ElevenLabs.
// These are BYOK: the plan covers the script/orchestration, the user brings their
// own keys for the premium generation. If they have no plan yet, also nudge trial.
export default function AdvancedBanner({ needsPlan, onKeys }) {
return (
<div className="mx-6 mt-3 p-3 bg-amber-500/10 border border-amber-500/30 rounded-xl flex items-center justify-between gap-4 shrink-0 animate-[fadeIn_0.3s_ease-out]">
<div className="flex items-center gap-3 text-sm">
<KeyRound size={16} className="shrink-0 text-amber-400" />
<div className="text-amber-100/90">
<span className="font-semibold text-white">Advanced tool.</span>{' '}
{needsPlan
? <>Start your <span className="font-semibold text-white">3-day free trial</span> to unlock. This tool also uses your own <span className="font-semibold text-white">fal.ai + ElevenLabs</span> keys (you pay those providers).</>
: <>AI video &amp; voice generation use your own <span className="font-semibold text-white">fal.ai + ElevenLabs</span> keys — add them in Settings. Script &amp; orchestration are included in your plan.</>}
</div>
</div>
<button
onClick={needsPlan ? () => { window.location.hash = '#/pricing'; } : onKeys}
className="shrink-0 inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-lg bg-amber-500 hover:bg-amber-400 text-black transition-colors"
>
{needsPlan ? <>See plans <ArrowRight size={14} /></> : 'Add keys'}
</button>
</div>
);
}

View file

@ -0,0 +1,91 @@
import React, { useState } from 'react';
import { X, Mail, Check, Loader2 } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
// Sign-in modal: magic link (email) + Google OAuth.
export default function LoginModal({ onClose }) {
const { requestMagicLink, loginWithGoogle, googleAuthEnabled } = useAuth();
const [email, setEmail] = useState('');
const [sent, setSent] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const submit = async (e) => {
e.preventDefault();
if (!email.trim()) return;
setBusy(true);
setError('');
try {
await requestMagicLink(email.trim());
setSent(true);
} catch (err) {
setError(err.message || 'Something went wrong.');
} finally {
setBusy(false);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4">
<div className="bg-surface border border-white/10 rounded-2xl p-8 w-full max-w-md relative animate-[fadeIn_0.3s_ease-out]">
<button onClick={onClose} className="absolute right-4 top-4 text-zinc-400 hover:text-white transition-colors">
<X size={20} />
</button>
<h2 className="text-2xl font-bold mb-1">Sign in to OpenShorts</h2>
<p className="text-zinc-400 text-sm mb-6">Access your plan and generate shorts with no API keys.</p>
{sent ? (
<div className="text-center py-6">
<div className="inline-flex p-3 bg-green-500/20 rounded-full text-green-400 mb-4">
<Check size={28} />
</div>
<p className="font-medium">Check your inbox</p>
<p className="text-zinc-400 text-sm mt-1">We sent a sign-in link to <b>{email}</b>. It expires in 15 minutes.</p>
</div>
) : (
<>
<form onSubmit={submit} className="space-y-3">
<div className="relative">
<Mail size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500" />
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="you@email.com"
className="input-field pl-10"
autoFocus
/>
</div>
{error && <p className="text-red-400 text-sm">{error}</p>}
<button
type="submit"
disabled={busy || !email.trim()}
className="w-full bg-primary hover:bg-blue-600 disabled:opacity-50 text-white font-medium py-3 rounded-xl transition-all flex items-center justify-center gap-2"
>
{busy ? <Loader2 size={18} className="animate-spin" /> : 'Email me a sign-in link'}
</button>
</form>
{googleAuthEnabled && (
<>
<div className="flex items-center gap-3 my-5">
<div className="flex-1 h-px bg-white/10" />
<span className="text-xs text-zinc-500">or</span>
<div className="flex-1 h-px bg-white/10" />
</div>
<button
onClick={loginWithGoogle}
className="w-full bg-white text-zinc-900 font-medium py-3 rounded-xl hover:bg-zinc-100 transition-all flex items-center justify-center gap-2"
>
<svg width="18" height="18" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>
Continue with Google
</button>
</>
)}
</>
)}
</div>
</div>
);
}

View file

@ -0,0 +1,171 @@
import React, { useState, useEffect } from 'react';
import { Check, Loader2, Zap, Github, Server } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api';
const PLAN_ORDER = ['starter', 'creator', 'pro'];
const PLAN_BLURB = {
starter: 'For getting started',
creator: 'For regular creators',
pro: 'For power users & teams',
};
const HIGHLIGHT = 'creator';
const fmt = (amount, currency) =>
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.
export default function PricingSection({ onRequireLogin }) {
const { isSignedIn } = useAuth();
const [plans, setPlans] = useState([]);
const [interval, setInterval] = useState('month');
const [loading, setLoading] = useState(true);
const [busyPrice, setBusyPrice] = useState(null);
useEffect(() => {
apiJson('/api/billing/plans')
.then((d) => setPlans(d.plans || []))
.catch(() => setPlans([]))
.finally(() => setLoading(false));
}, []);
const checkout = async (price_id) => {
if (!isSignedIn) { onRequireLogin?.(price_id); return; }
setBusyPrice(price_id);
try {
const { url } = await apiJson('/api/billing/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ price_id }),
});
window.location.href = url;
} catch (e) {
setBusyPrice(null);
alert('Could not start checkout. Please try again.');
}
};
if (loading) {
return <div className="flex justify-center py-16"><Loader2 className="animate-spin text-primary" /></div>;
}
const byPlan = (plan) => plans.find((p) => p.plan === plan && p.interval === interval);
return (
<div className="max-w-5xl mx-auto">
<div className="flex items-center justify-center gap-3 mb-10">
<span className={interval === 'month' ? 'text-white' : 'text-zinc-500'}>Monthly</span>
<button
onClick={() => setInterval(interval === 'month' ? 'year' : 'month')}
className="relative w-14 h-7 rounded-full bg-white/10 transition-colors"
>
<span className={`absolute top-1 w-5 h-5 rounded-full bg-primary transition-all ${interval === 'year' ? 'left-8' : 'left-1'}`} />
</button>
<span className={interval === 'year' ? 'text-white' : 'text-zinc-500'}>
Yearly <span className="text-green-400 text-sm">· 2 months free</span>
</span>
</div>
<div className="grid md:grid-cols-3 gap-6">
{PLAN_ORDER.map((plan) => {
const entry = byPlan(plan);
if (!entry) return null;
const highlight = plan === HIGHLIGHT;
return (
<div
key={plan}
className={`relative rounded-2xl p-6 border flex flex-col ${highlight ? 'border-primary bg-primary/5 shadow-xl shadow-primary/10' : 'border-white/10 bg-surface'}`}
>
{highlight && (
<span className="absolute -top-3 left-1/2 -translate-x-1/2 bg-primary text-white text-xs font-semibold px-3 py-1 rounded-full">
Most popular
</span>
)}
<h3 className="text-xl font-bold capitalize">{plan}</h3>
<p className="text-zinc-400 text-sm mb-4">{PLAN_BLURB[plan]}</p>
<div className="mb-4">
<span className="text-4xl font-bold">{fmt(entry.amount, entry.currency)}</span>
<span className="text-zinc-400">/{interval === 'month' ? 'mo' : 'yr'}</span>
</div>
<ul className="space-y-2 text-sm mb-6 flex-1">
<li className="flex items-center gap-2"><Check size={16} className="text-green-400" /> <b>{entry.minutes} min</b> of video / month</li>
<li className="flex items-center gap-2"><Check size={16} className="text-green-400" /> No API keys needed</li>
<li className="flex items-center gap-2"><Check size={16} className="text-green-400" /> Gemini + auto-posting included</li>
{plan === 'pro' && <li className="flex items-center gap-2"><Zap size={16} className="text-yellow-400" /> Priority processing queue</li>}
</ul>
<button
onClick={() => checkout(entry.price_id)}
disabled={busyPrice === entry.price_id}
className={`w-full py-3 rounded-xl font-medium transition-all flex items-center justify-center gap-2 ${highlight ? 'bg-primary hover:bg-blue-600 text-white' : 'bg-white/10 hover:bg-white/20 text-white'}`}
>
{busyPrice === entry.price_id ? <Loader2 size={18} className="animate-spin" /> : 'Start 3-day free trial'}
</button>
<p className="text-center text-[11px] text-zinc-500 mt-2">3 days free, then billed monthly. Cancel anytime.</p>
</div>
);
})}
</div>
{/* What every plan includes vs what's bring-your-own-key */}
<div className="mt-10 grid md:grid-cols-2 gap-4">
<div className="rounded-2xl border border-green-500/20 bg-green-500/5 p-6">
<h3 className="font-semibold mb-3 flex items-center gap-2">
<Check size={18} className="text-green-400" /> Included in every plan
</h3>
<ul className="space-y-2 text-sm text-zinc-300">
<li className="flex items-center gap-2"><Check size={15} className="text-green-400 shrink-0" /> <b>Clip Generator</b> — fully managed, no API keys</li>
<li className="flex items-center gap-2"><Check size={15} className="text-green-400 shrink-0" /> <b>YouTube Studio</b> — titles, thumbnails, descriptions</li>
<li className="flex items-center gap-2"><Check size={15} className="text-green-400 shrink-0" /> Auto-posting to TikTok, Reels &amp; Shorts</li>
<li className="flex items-center gap-2"><Check size={15} className="text-green-400 shrink-0" /> All the AI &amp; compute run on our servers</li>
</ul>
<p className="text-[11px] text-zinc-500 mt-3 pt-3 border-t border-white/5">
Your monthly minutes cover video processing. Titles &amp; descriptions are free;
AI <b>thumbnail image generation</b> uses ~3 min of your quota per batch.
</p>
</div>
<div className="rounded-2xl border border-amber-500/20 bg-amber-500/5 p-6">
<h3 className="font-semibold mb-3 flex items-center gap-2">
<Zap size={18} className="text-amber-400" /> Bring your own key
</h3>
<p className="text-sm text-zinc-400 mb-3 leading-relaxed">
<b>AI Shorts</b> (AI-actor UGC videos) and <b>voice dubbing</b> use premium generation from
<b> fal.ai</b> and <b>ElevenLabs</b>. Connect your own keys for those — you're billed by those
providers directly (typically ~$0.65-2 per video). Your plan still covers the script &amp; orchestration.
</p>
<p className="text-[11px] text-zinc-500">Managed credits for these are coming later — no keys needed.</p>
</div>
</div>
{/* Free self-hosted path — the honest "free" option */}
<div className="mt-10 rounded-2xl border border-white/10 bg-surface/60 p-6 md:p-8">
<div className="flex flex-col md:flex-row md:items-center gap-6 justify-between">
<div className="flex items-start gap-4">
<div className="p-3 rounded-xl bg-white/5 text-zinc-300"><Server size={22} /></div>
<div>
<h3 className="text-lg font-bold flex items-center gap-2">
Free forever — self-hosted
<span className="text-[10px] bg-green-500/10 border border-green-500/30 px-2 py-0.5 rounded text-green-400 uppercase tracking-wider">$0</span>
</h3>
<p className="text-zinc-400 text-sm mt-1 max-w-xl leading-relaxed">
OpenShorts is open source. Run it on your own machine with Docker and use it <b>completely free</b> —
you just bring your own API keys and your own hardware. The plans above are for the
<b> hosted version on this site</b>: zero setup, no keys, we run everything for you.
</p>
</div>
</div>
<a
href="https://github.com/mutonby/openshorts"
target="_blank" rel="noopener noreferrer"
className="shrink-0 inline-flex items-center gap-2 bg-white/10 hover:bg-white/20 text-white px-5 py-3 rounded-xl font-medium transition-all"
>
<Github size={18} /> Self-host free
</a>
</div>
</div>
<p className="text-center text-zinc-500 text-xs mt-6">
Use it free on your own computer, or skip the setup and use it here — 3 days free, then a plan.
</p>
</div>
);
}

View file

@ -1,6 +1,7 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { Globe, Sparkles, Download, Copy, Check, ChevronRight, ChevronLeft, Loader2, AlertCircle, Volume2, User, Film, Terminal, ChevronDown, RefreshCw, Zap, Target, TrendingUp, MessageSquare, Eye, Share2, Calendar, Upload } from 'lucide-react'; import { Globe, Sparkles, Download, Copy, Check, ChevronRight, ChevronLeft, Loader2, AlertCircle, Volume2, User, Film, Terminal, ChevronDown, RefreshCw, Zap, Target, TrendingUp, MessageSquare, Eye, Share2, Calendar, Upload } from 'lucide-react';
import { getApiUrl } from '../config'; import { getApiUrl } from '../config';
import { apiFetch } from '../lib/api';
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' },
@ -34,7 +35,11 @@ function saveCache(url, analysis, webResearch, scripts) {
} catch { /* localStorage full */ } } catch { /* localStorage full */ }
} }
export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uploadPostKey, uploadUserId }) { export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uploadPostKey, uploadUserId, managed = false }) {
// Managed (hosted plan): Gemini (script) + Upload-Post run server-side via the
// bearer token — no BYOK Gemini key needed. fal.ai + ElevenLabs stay BYOK.
const geminiHeader = geminiApiKey ? { 'X-Gemini-Key': geminiApiKey } : {};
const needsGeminiKey = !geminiApiKey && !managed;
// Wizard state // Wizard state
const [step, setStep] = useState(() => { const [step, setStep] = useState(() => {
const cache = loadCache(); const cache = loadCache();
@ -186,7 +191,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
const handleAnalyze = async () => { const handleAnalyze = async () => {
if (!url.trim() && !description.trim()) return; if (!url.trim() && !description.trim()) return;
if (!geminiApiKey) { if (needsGeminiKey) {
setAnalyzeError('Gemini API key required. Set it in Settings.'); setAnalyzeError('Gemini API key required. Set it in Settings.');
return; return;
} }
@ -195,11 +200,11 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
setAnalyzeError(''); setAnalyzeError('');
try { try {
const res = await fetch(getApiUrl('/api/saasshorts/analyze'), { const res = await apiFetch('/api/saasshorts/analyze', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-Gemini-Key': geminiApiKey, ...geminiHeader,
}, },
body: JSON.stringify({ body: JSON.stringify({
url: url.trim() || undefined, url: url.trim() || undefined,
@ -274,7 +279,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
scriptToSend.full_narration = editedNarration; scriptToSend.full_narration = editedNarration;
} }
const res = await fetch(getApiUrl('/api/saasshorts/generate'), { const res = await apiFetch('/api/saasshorts/generate', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -320,7 +325,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
scriptToSend.full_narration = editedNarration; scriptToSend.full_narration = editedNarration;
} }
const res = await fetch(getApiUrl('/api/saasshorts/generate'), { const res = await apiFetch('/api/saasshorts/generate', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -1467,7 +1472,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
payload.scheduled_date = new Date(scheduleDate).toISOString(); payload.scheduled_date = new Date(scheduleDate).toISOString();
payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
} }
const res = await fetch(getApiUrl('/api/saasshorts/post'), { const res = await apiFetch('/api/saasshorts/post', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload), body: JSON.stringify(payload),

View file

@ -1,6 +1,7 @@
import React, { useState, useRef, useCallback } from 'react'; import React, { useState, useRef, useCallback } from 'react';
import { Upload, Image, Loader2, Send, Check, Download, ArrowRight, ArrowLeft, Sparkles, Video, Type, X, Plus, MessageSquare, FileText, Youtube, AlertCircle, CheckCircle2, Settings } from 'lucide-react'; import { Upload, Image, Loader2, Send, Check, Download, ArrowRight, ArrowLeft, Sparkles, Video, Type, X, Plus, MessageSquare, FileText, Youtube, AlertCircle, CheckCircle2, Settings } from 'lucide-react';
import { getApiUrl } from '../config'; import { getApiUrl } from '../config';
import { apiFetch } from '../lib/api';
const STEPS = ['Input', 'Titles', 'Generate', 'Description', 'Publish']; const STEPS = ['Input', 'Titles', 'Generate', 'Description', 'Publish'];
@ -92,7 +93,11 @@ function DragDropZone({ label, accept, onFile, file, onClear, icon: Icon }) {
); );
} }
export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUserId }) { export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUserId, managed = false }) {
// Managed (hosted plan): Gemini runs server-side via the bearer token, no BYOK key.
// Only send X-Gemini-Key for self-host BYOK. apiFetch attaches the bearer token.
const keyHeader = geminiApiKey ? { 'X-Gemini-Key': geminiApiKey } : {};
const needsKey = !geminiApiKey && !managed;
// Step management // Step management
const [step, setStep] = useState(0); const [step, setStep] = useState(0);
const [mode, setMode] = useState(null); // 'video' or 'manual' const [mode, setMode] = useState(null); // 'video' or 'manual'
@ -165,7 +170,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
// --- Step 1: Analyze Video --- // --- Step 1: Analyze Video ---
const handleAnalyze = async () => { const handleAnalyze = async () => {
if (!geminiApiKey) return alert('Please set your Gemini API key in Settings first.'); if (needsKey) return alert('Please set your Gemini API key in Settings first.');
setIsAnalyzing(true); setIsAnalyzing(true);
try { try {
@ -180,9 +185,9 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
return alert('Please upload a video file.'); return alert('Please upload a video file.');
} }
const res = await fetch(getApiUrl('/api/thumbnail/analyze'), { const res = await apiFetch('/api/thumbnail/analyze', {
method: 'POST', method: 'POST',
headers: { 'X-Gemini-Key': geminiApiKey }, headers: keyHeader,
body: formData body: formData
}); });
@ -223,11 +228,11 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
// Create session for manual mode // Create session for manual mode
const newSessionId = sessionId || crypto.randomUUID(); const newSessionId = sessionId || crypto.randomUUID();
setSessionId(newSessionId); setSessionId(newSessionId);
fetch(getApiUrl('/api/thumbnail/titles'), { apiFetch('/api/thumbnail/titles', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-Gemini-Key': geminiApiKey ...keyHeader
}, },
body: JSON.stringify({ title: manualTitle, session_id: newSessionId }) body: JSON.stringify({ title: manualTitle, session_id: newSessionId })
}).catch(() => { }); }).catch(() => { });
@ -246,11 +251,11 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
setChatHistory(prev => [...prev, { role: 'user', content: userMsg }]); setChatHistory(prev => [...prev, { role: 'user', content: userMsg }]);
try { try {
const res = await fetch(getApiUrl('/api/thumbnail/titles'), { const res = await apiFetch('/api/thumbnail/titles', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-Gemini-Key': geminiApiKey ...keyHeader
}, },
body: JSON.stringify({ session_id: sessionId, message: userMsg }) body: JSON.stringify({ session_id: sessionId, message: userMsg })
}); });
@ -275,7 +280,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
// --- Step 3: Generate Thumbnails --- // --- Step 3: Generate Thumbnails ---
const handleGenerate = async () => { const handleGenerate = async () => {
if (!geminiApiKey) return alert('Please set your Gemini API key in Settings first.'); if (needsKey) return alert('Please set your Gemini API key in Settings first.');
const finalTitle = selectedTitle || manualTitle; const finalTitle = selectedTitle || manualTitle;
if (!finalTitle) return alert('Please select or enter a title first.'); if (!finalTitle) return alert('Please select or enter a title first.');
@ -291,9 +296,9 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
if (faceImage) formData.append('face', faceImage); if (faceImage) formData.append('face', faceImage);
if (bgImage) formData.append('background', bgImage); if (bgImage) formData.append('background', bgImage);
const res = await fetch(getApiUrl('/api/thumbnail/generate'), { const res = await apiFetch('/api/thumbnail/generate', {
method: 'POST', method: 'POST',
headers: { 'X-Gemini-Key': geminiApiKey }, headers: keyHeader,
body: formData body: formData
}); });
@ -334,18 +339,18 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
// --- Description Generation --- // --- Description Generation ---
const handleGenerateDescription = async () => { const handleGenerateDescription = async () => {
if (!geminiApiKey) return alert('Please set your Gemini API key in Settings first.'); if (needsKey) return alert('Please set your Gemini API key in Settings first.');
const finalTitle = selectedTitle || manualTitle; const finalTitle = selectedTitle || manualTitle;
if (!finalTitle) return alert('Please select a title first.'); if (!finalTitle) return alert('Please select a title first.');
if (!sessionId) return alert('No session available.'); if (!sessionId) return alert('No session available.');
setIsDescribing(true); setIsDescribing(true);
try { try {
const res = await fetch(getApiUrl('/api/thumbnail/describe'), { const res = await apiFetch('/api/thumbnail/describe', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-Gemini-Key': geminiApiKey ...keyHeader
}, },
body: JSON.stringify({ session_id: sessionId, title: finalTitle }) body: JSON.stringify({ session_id: sessionId, title: finalTitle })
}); });
@ -366,7 +371,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
// --- Publish to YouTube --- // --- Publish to YouTube ---
const handlePublish = async () => { const handlePublish = async () => {
if (!uploadPostKey || !uploadUserId) return alert('Please configure your Upload-Post API key and user in Settings first.'); if (!managed && (!uploadPostKey || !uploadUserId)) return alert('Please configure your Upload-Post API key and user in Settings first.');
const finalTitle = selectedTitle || manualTitle; const finalTitle = selectedTitle || manualTitle;
if (!finalTitle) return alert('No title selected.'); if (!finalTitle) return alert('No title selected.');
if (!selectedThumbnail) return alert('Please select a thumbnail first.'); if (!selectedThumbnail) return alert('Please select a thumbnail first.');
@ -384,7 +389,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
formData.append('user_id', uploadUserId); formData.append('user_id', uploadUserId);
// Submit the publish job — returns immediately with a publish_id // Submit the publish job — returns immediately with a publish_id
const res = await fetch(getApiUrl('/api/thumbnail/publish'), { const res = await apiFetch('/api/thumbnail/publish', {
method: 'POST', method: 'POST',
body: formData body: formData
}); });
@ -472,8 +477,8 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
<StepIndicator currentStep={step} /> <StepIndicator currentStep={step} />
{/* Gemini API Key Warning */} {/* Gemini API Key Warning (self-host BYOK only; managed uses server key) */}
{!geminiApiKey && ( {needsKey && (
<div className="mb-6 p-5 bg-amber-500/10 border border-amber-500/30 rounded-xl flex items-start gap-3"> <div className="mb-6 p-5 bg-amber-500/10 border border-amber-500/30 rounded-xl flex items-start gap-3">
<AlertCircle size={20} className="text-amber-400 shrink-0 mt-0.5" /> <AlertCircle size={20} className="text-amber-400 shrink-0 mt-0.5" />
<div> <div>
@ -485,7 +490,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
{/* ===== STEP 0: Input Mode Selection ===== */} {/* ===== STEP 0: Input Mode Selection ===== */}
{step === 0 && ( {step === 0 && (
<div className={`grid md:grid-cols-2 gap-6 ${!geminiApiKey ? 'opacity-50 pointer-events-none select-none' : ''}`}> <div className={`grid md:grid-cols-2 gap-6 ${needsKey ? 'opacity-50 pointer-events-none select-none' : ''}`}>
{/* Mode A: Video Analysis */} {/* Mode A: Video Analysis */}
<div className="glass-panel p-6 space-y-4"> <div className="glass-panel p-6 space-y-4">
<div className="flex items-center gap-3 mb-2"> <div className="flex items-center gap-3 mb-2">
@ -1058,7 +1063,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
</div> </div>
{/* Publish Button */} {/* Publish Button */}
{(!uploadPostKey || !uploadUserId) ? ( {(!managed && (!uploadPostKey || !uploadUserId)) ? (
<div className="glass-panel p-6 space-y-3"> <div className="glass-panel p-6 space-y-3">
<div className="flex items-center gap-2 text-amber-400"> <div className="flex items-center gap-2 text-amber-400">
<AlertCircle size={16} /> <AlertCircle size={16} />

View file

@ -0,0 +1,52 @@
import React, { useState, useEffect } from 'react';
import { X, Loader2, Zap } from 'lucide-react';
import { apiJson } from '../lib/api';
// Opens when a job hits a 402 (quota exceeded). Lets the user buy more minutes.
export default function TopUpModal({ onClose, required, remaining }) {
const [topups, setTopups] = useState([]);
const [busy, setBusy] = useState(false);
useEffect(() => {
apiJson('/api/billing/plans').then((d) => setTopups(d.topups || [])).catch(() => {});
}, []);
const buy = async (price_id) => {
setBusy(true);
try {
const { url } = await apiJson('/api/billing/checkout', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ price_id }),
});
window.location.href = url;
} catch (e) { setBusy(false); alert('Could not start checkout.'); }
};
const fmt = (a, c) => new Intl.NumberFormat('en-US', { style: 'currency', currency: (c || 'usd').toUpperCase(), maximumFractionDigits: 0 }).format((a || 0) / 100);
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4">
<div className="bg-surface border border-white/10 rounded-2xl p-8 w-full max-w-md relative">
<button onClick={onClose} className="absolute right-4 top-4 text-zinc-400 hover:text-white"><X size={20} /></button>
<div className="inline-flex p-3 bg-amber-500/20 rounded-full text-amber-400 mb-4"><Zap size={24} /></div>
<h2 className="text-xl font-bold mb-1">You're out of minutes</h2>
<p className="text-zinc-400 text-sm mb-6">
{typeof required === 'number'
? <>This video needs <b>{required} min</b> but you have <b>{Math.round((remaining || 0) * 10) / 10} min</b> left.</>
: 'Add more minutes to keep generating.'}
</p>
<div className="grid grid-cols-2 gap-3">
{topups.map((t) => (
<button key={t.price_id} onClick={() => buy(t.price_id)} disabled={busy}
className="border border-white/10 hover:border-primary rounded-xl p-4 text-left transition-all disabled:opacity-50">
<div className="text-lg font-bold">+{t.minutes} min</div>
<div className="text-zinc-400 text-sm">{fmt(t.amount, t.currency)}</div>
</button>
))}
{topups.length === 0 && <div className="col-span-2 flex justify-center py-4"><Loader2 className="animate-spin text-primary" /></div>}
</div>
<p className="text-zinc-500 text-xs mt-4 text-center">Or upgrade your plan for more monthly minutes.</p>
</div>
</div>
);
}

View file

@ -0,0 +1,25 @@
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.
export default function TrialGate({ toolName = 'this' }) {
return (
<div className="mx-6 mt-3 p-3 bg-primary/10 border border-primary/30 rounded-xl flex items-center justify-between gap-4 shrink-0 animate-[fadeIn_0.3s_ease-out]">
<div className="flex items-center gap-3 text-sm">
<Sparkles size={16} className="shrink-0 text-primary" />
<div className="text-primary/90">
<span className="font-semibold text-white">Preview mode.</span>{' '}
Start your <span className="font-semibold text-white">3-day free trial</span> to generate with {toolName} —
no API keys, from $12/mo. <span className="text-zinc-400">Or run it free by self-hosting.</span>
</div>
</div>
<button
onClick={() => { window.location.hash = '#/pricing'; }}
className="shrink-0 inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-lg bg-primary hover:bg-blue-600 text-white transition-colors"
>
See plans <ArrowRight size={14} />
</button>
</div>
);
}

View file

@ -0,0 +1,28 @@
import React from 'react';
import { Zap } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
// Compact minutes-remaining pill for the header (managed users only).
export default function UsageMeter({ onClick }) {
const { isManaged, minutes } = useAuth();
if (!isManaged || !minutes) return null;
const remaining = Math.round((minutes.remaining || 0) * 10) / 10;
const allowance = (minutes.plan_allowance || 0) + (minutes.topup_remaining || 0) + (minutes.plan_used || 0);
const pct = allowance > 0 ? Math.max(4, Math.min(100, (remaining / allowance) * 100)) : 0;
const low = remaining <= (allowance * 0.2);
return (
<button
onClick={onClick}
title="Manage your plan"
className={`flex items-center gap-2 px-3 py-1.5 rounded-full border text-xs transition-colors ${low ? 'border-amber-500/40 bg-amber-500/10 text-amber-300 hover:bg-amber-500/20' : 'border-white/10 bg-white/5 text-zinc-300 hover:bg-white/10'}`}
>
<Zap size={13} className={low ? 'text-amber-400' : 'text-primary'} />
<span className="font-medium">{remaining} min</span>
<span className="w-12 h-1.5 rounded-full bg-white/10 overflow-hidden hidden sm:inline-block">
<span className={`block h-full ${low ? 'bg-amber-400' : 'bg-primary'}`} style={{ width: `${pct}%` }} />
</span>
</button>
);
}

View file

@ -0,0 +1,123 @@
// Auth + billing session state for cloud mode.
// - Reads /api/config to learn whether billing is enabled at all.
// - Handles the magic-link and Google OAuth redirect hashes.
// - Exposes the current user, plan and minute balance to the app.
// When billingEnabled is false the provider is inert and the app behaves as the
// classic BYOK dashboard.
import { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { getApiUrl } from '../config';
import { apiFetch, apiJson, getToken, setToken, clearToken } from '../lib/api';
const AuthContext = createContext(null);
export const useAuth = () => useContext(AuthContext);
export function AuthProvider({ children }) {
const [config, setConfig] = useState({ billingEnabled: false, googleAuthEnabled: false });
const [me, setMe] = useState(null); // /api/me payload, or null when signed out
const [loading, setLoading] = useState(true);
const [signingIn, setSigningIn] = useState(false);
const refreshMe = useCallback(async () => {
if (!getToken()) { setMe(null); return null; }
try {
const data = await apiJson('/api/me');
setMe(data);
return data;
} catch (e) {
// Stale/invalid token: drop it and fall back to anonymous BYOK.
clearToken();
setMe(null);
return null;
}
}, []);
// Handle auth redirect hashes: #/auth/verify?ml=... and #/auth/callback?token=...
const handleAuthHash = useCallback(async () => {
const hash = window.location.hash || '';
const match = hash.match(/^#\/auth\/(verify|callback)\??(.*)$/);
if (!match) return false;
const [, kind, query] = match;
const params = new URLSearchParams(query);
setSigningIn(true);
try {
if (kind === 'callback') {
const token = params.get('token');
if (token) setToken(token);
} else if (kind === 'verify') {
const ml = params.get('ml');
if (ml) {
const data = await apiJson('/api/auth/magic-link/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: ml }),
});
if (data.token) setToken(data.token);
}
}
await refreshMe();
} catch (e) {
// fall through — user lands signed-out
} finally {
setSigningIn(false);
// Clear the sensitive hash, land in the app.
window.location.hash = '#app';
}
return true;
}, [refreshMe]);
useEffect(() => {
(async () => {
try {
const cfg = await (await fetch(getApiUrl('/api/config'))).json();
setConfig(cfg);
if (cfg.billingEnabled) {
const handled = await handleAuthHash();
if (!handled) await refreshMe();
}
} catch (_) { /* config fetch failed — stay in BYOK */ }
setLoading(false);
})();
}, [handleAuthHash, refreshMe]);
const requestMagicLink = useCallback(async (email) => {
const res = await apiFetch('/api/auth/magic-link', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email }),
});
if (res.status === 429) throw new Error('Too many attempts. Try again in a few minutes.');
if (!res.ok) throw new Error('Could not send sign-in link.');
return true;
}, []);
const loginWithGoogle = useCallback(() => {
window.location.href = getApiUrl('/api/auth/google');
}, []);
const logout = useCallback(() => {
clearToken();
setMe(null);
}, []);
const value = {
billingEnabled: config.billingEnabled,
googleAuthEnabled: config.googleAuthEnabled,
loading,
signingIn,
user: me?.user || null,
me,
plan: me?.plan || null,
entitled: !!me?.entitled,
minutes: me?.minutes || null,
isSignedIn: !!me?.user,
// Managed = signed-in AND entitled (active plan or top-up credit).
isManaged: !!(config.billingEnabled && me?.entitled),
refreshMe,
requestMagicLink,
loginWithGoogle,
logout,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

48
dashboard/src/lib/api.js Normal file
View file

@ -0,0 +1,48 @@
// Centralized API client for cloud mode.
// Adds the Authorization: Bearer header from the stored session token, and turns
// a 402 (quota exceeded) into a typed QuotaError the UI can catch to prompt a top-up.
import { getApiUrl } from '../config';
export const AUTH_TOKEN_KEY = 'openshorts_auth';
export const getToken = () => localStorage.getItem(AUTH_TOKEN_KEY) || '';
export const setToken = (t) => localStorage.setItem(AUTH_TOKEN_KEY, t);
export const clearToken = () => localStorage.removeItem(AUTH_TOKEN_KEY);
export class QuotaError extends Error {
constructor(detail) {
super('quota_exceeded');
this.name = 'QuotaError';
this.minutesRequired = detail?.minutes_required;
this.minutesRemaining = detail?.minutes_remaining;
}
}
// Drop-in fetch wrapper. Always attaches the bearer token when present.
export async function apiFetch(path, options = {}) {
const headers = new Headers(options.headers || {});
const token = getToken();
if (token) headers.set('Authorization', `Bearer ${token}`);
const res = await fetch(getApiUrl(path), { ...options, headers });
if (res.status === 402) {
let detail = {};
try {
const body = await res.clone().json();
detail = body.detail || body;
} catch (_) { /* ignore */ }
throw new QuotaError(detail);
}
return res;
}
// Convenience JSON helper.
export async function apiJson(path, options = {}) {
const res = await apiFetch(path, options);
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new Error(`${res.status}: ${text}`);
}
return res.json();
}

View file

@ -4,10 +4,50 @@ import './index.css'
import App from './App.jsx' import App from './App.jsx'
import Landing from './Landing.jsx' import Landing from './Landing.jsx'
import Legal from './Legal.jsx' import Legal from './Legal.jsx'
import { AuthProvider, useAuth } from './contexts/AuthContext'
import PricingSection from './components/PricingSection'
import AccountPage from './components/AccountPage'
import LoginModal from './components/LoginModal'
function PageShell({ title, children }) {
return (
<div className="min-h-screen bg-background text-white">
<header className="h-16 border-b border-white/5 flex items-center justify-between px-6">
<a href="#app" className="font-bold text-lg">OpenShorts</a>
<a href="#app" className="text-sm text-zinc-400 hover:text-white">← Back to app</a>
</header>
<main className="p-8">
{title && <h1 className="text-3xl font-bold text-center mb-10">{title}</h1>}
{children}
</main>
</div>
);
}
function PricingView() {
const [showLogin, setShowLogin] = useState(false);
return (
<PageShell title="Choose your plan">
<PricingSection onRequireLogin={() => setShowLogin(true)} />
{showLogin && <LoginModal onClose={() => setShowLogin(false)} />}
</PageShell>
);
}
function AccountView() {
const { isSignedIn, loading } = useAuth();
useEffect(() => {
if (!loading && !isSignedIn) window.location.hash = '#/pricing';
}, [loading, isSignedIn]);
return <PageShell><AccountPage /></PageShell>;
}
function Root() { function Root() {
const resolveView = () => { const resolveView = () => {
const hash = window.location.hash; const hash = window.location.hash || '';
if (hash.startsWith('#/auth/')) return 'auth'; // AuthContext consumes then redirects
if (hash.startsWith('#/account')) return 'account';
if (hash.startsWith('#/pricing')) return 'pricing';
if (hash === '#legal') return 'legal'; if (hash === '#legal') return 'legal';
if (hash === '#app' || localStorage.getItem('openshorts_skip_landing') === '1') return 'app'; if (hash === '#app' || localStorage.getItem('openshorts_skip_landing') === '1') return 'app';
return 'landing'; return 'landing';
@ -28,12 +68,19 @@ function Root() {
}; };
if (view === 'legal') return <Legal />; if (view === 'legal') return <Legal />;
if (view === 'pricing') return <PricingView />;
if (view === 'account') return <AccountView />;
if (view === 'auth') {
return <div className="min-h-screen flex items-center justify-center bg-background text-zinc-400">Signing you in…</div>;
}
if (view === 'app') return <App />; if (view === 'app') return <App />;
return <Landing onLaunchApp={handleLaunchApp} />; return <Landing onLaunchApp={handleLaunchApp} />;
} }
createRoot(document.getElementById('root')).render( createRoot(document.getElementById('root')).render(
<StrictMode> <StrictMode>
<Root /> <AuthProvider>
<Root />
</AuthProvider>
</StrictMode>, </StrictMode>,
) )

52
docker-compose.cloud.yml Normal file
View file

@ -0,0 +1,52 @@
# Cloud (paid / managed-keys) mode override for openshorts.app.
# Usage:
# docker compose -f docker-compose.yml -f docker-compose.cloud.yml up --build
#
# The base docker-compose.yml is untouched and keeps working as pure BYOK for
# self-hosters. This file only adds the Postgres service and the cloud env.
services:
db:
image: postgres:16-alpine
container_name: openshorts-db
environment:
- POSTGRES_USER=openshorts
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-openshorts}
- POSTGRES_DB=openshorts
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U openshorts"]
interval: 5s
timeout: 3s
retries: 10
restart: unless-stopped
backend:
depends_on:
db:
condition: service_healthy
environment:
- BILLING_ENABLED=true
- DATABASE_URL=postgresql+asyncpg://openshorts:${POSTGRES_PASSWORD:-openshorts}@db:5432/openshorts
- JWT_SECRET=${JWT_SECRET}
- FRONTEND_URL=${FRONTEND_URL:-https://openshorts.app}
- ALLOWED_ORIGINS=${ALLOWED_ORIGINS:-https://openshorts.app}
# Email (magic link) — Resend
- RESEND_API_KEY=${RESEND_API_KEY}
- EMAIL_FROM=${EMAIL_FROM:-OpenShorts <login@openshorts.app>}
# Google OAuth
- GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID}
- GOOGLE_CLIENT_SECRET=${GOOGLE_CLIENT_SECRET}
# Stripe (prices are resolved by lookup_key at runtime — no price IDs needed)
- STRIPE_SECRET_KEY=${STRIPE_SECRET_KEY}
- STRIPE_WEBHOOK_SECRET=${STRIPE_WEBHOOK_SECRET}
# Managed provider keys (server-owned)
- MANAGED_GEMINI_API_KEY=${MANAGED_GEMINI_API_KEY}
- MANAGED_UPLOAD_POST_API_KEY=${MANAGED_UPLOAD_POST_API_KEY}
- OPENSHORTS_LOGO_URL=${OPENSHORTS_LOGO_URL:-https://openshorts.app/logo.png}
# Residential proxy for YouTube downloads (avoids datacenter-IP bans).
# e.g. http://user:pass@gate.dataimpulse.com:823 — leave empty to go direct.
- PROXY_URL=${PROXY_URL:-}
volumes:
pgdata:

View file

@ -0,0 +1,10 @@
# Local-only override: remap host ports to avoid clashes with other running
# projects (e.g. another backend on :8000). Not for production.
# `!override` REPLACES the base ports list instead of appending to it.
services:
backend:
ports: !override
- "8001:8000"
frontend:
ports: !override
- "5176:5173"

18
main.py
View file

@ -474,6 +474,13 @@ def download_youtube_video(url, output_dir="."):
cookies_path = None cookies_path = None
print("⚠️ YOUTUBE_COOKIES env var not found.") print("⚠️ YOUTUBE_COOKIES env var not found.")
# Optional residential proxy for YouTube (avoids datacenter-IP bans on hosted
# servers). Set PROXY_URL (e.g. http://user:pass@gate.provider.com:port).
# When unset (self-host), downloads go direct as before.
_proxy = os.environ.get("PROXY_URL", "").strip() or None
if _proxy:
print("🌐 Using residential proxy for download.")
# Common yt-dlp options to work around YouTube bot detection. # Common yt-dlp options to work around YouTube bot detection.
# extractor_args tries multiple player clients in order; tv_embed / android # extractor_args tries multiple player clients in order; tv_embed / android
# avoid the OAuth/PO-token checks that block server IPs. # avoid the OAuth/PO-token checks that block server IPs.
@ -482,6 +489,7 @@ def download_youtube_video(url, output_dir="."):
'verbose': True, 'verbose': True,
'no_warnings': False, 'no_warnings': False,
'cookiefile': cookies_path if cookies_path else None, 'cookiefile': cookies_path if cookies_path else None,
'proxy': _proxy,
'socket_timeout': 30, 'socket_timeout': 30,
'retries': 10, 'retries': 10,
'fragment_retries': 10, 'fragment_retries': 10,
@ -551,9 +559,17 @@ Technical Details: {str(e)}
os.remove(expected_file) os.remove(expected_file)
print(f"🗑️ Removed existing file to re-download with H.264 codec") print(f"🗑️ Removed existing file to re-download with H.264 codec")
# When downloading through a paid proxy, cap at 720p to control bandwidth
# cost (a 720p source is plenty for 9:16 clips). Direct downloads keep best.
if _proxy:
_fmt = ('bestvideo[vcodec^=avc1][height<=720][ext=mp4]+bestaudio[ext=m4a]/'
'bestvideo[vcodec^=avc1][height<=720]+bestaudio/best[height<=720][ext=mp4]/best[height<=720]/best')
else:
_fmt = 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best'
ydl_opts = { ydl_opts = {
**_COMMON_YDL_OPTS, **_COMMON_YDL_OPTS,
'format': 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best', 'format': _fmt,
'outtmpl': output_template, 'outtmpl': output_template,
'merge_output_format': 'mp4', 'merge_output_format': 'mp4',
'overwrites': True, 'overwrites': True,

11
requirements-billing.txt Normal file
View file

@ -0,0 +1,11 @@
# Extra dependencies for cloud (paid / managed-keys) mode ONLY.
# Self-hosters running BYOK do NOT need these — see requirements.txt.
# Installed on top of requirements.txt when BILLING_ENABLED is used.
sqlalchemy[asyncio]==2.0.36
asyncpg==0.30.0
alembic==1.14.0
stripe==11.3.0
authlib==1.3.2
itsdangerous==2.2.0
PyJWT==2.10.1
email-validator==2.2.0