From 05578c545688d5067f59b746763cfc4e1edb850f Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 14 Jul 2026 13:04:43 +0200 Subject: [PATCH] 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. --- .env.cloud.example | 38 ++ Dockerfile | 5 +- alembic.ini | 41 +++ alembic/env.py | 60 ++++ alembic/script.py.mako | 22 ++ app.py | 345 ++++++++++++++++--- cloud/__init__.py | 47 +++ cloud/auth.py | 214 ++++++++++++ cloud/billing.py | 329 ++++++++++++++++++ cloud/config.py | 151 ++++++++ cloud/database.py | 49 +++ cloud/emails.py | 36 ++ cloud/managed_keys.py | 25 ++ cloud/metering.py | 271 +++++++++++++++ cloud/models.py | 105 ++++++ cloud/oauth.py | 93 +++++ cloud/social_profiles.py | 102 ++++++ dashboard/src/App.jsx | 145 +++++++- dashboard/src/Landing.jsx | 47 ++- dashboard/src/components/AccountPage.jsx | 135 ++++++++ dashboard/src/components/AdvancedBanner.jsx | 27 ++ dashboard/src/components/LoginModal.jsx | 91 +++++ dashboard/src/components/PricingSection.jsx | 171 +++++++++ dashboard/src/components/SaaShortsTab.jsx | 19 +- dashboard/src/components/ThumbnailStudio.jsx | 45 +-- dashboard/src/components/TopUpModal.jsx | 52 +++ dashboard/src/components/TrialGate.jsx | 25 ++ dashboard/src/components/UsageMeter.jsx | 28 ++ dashboard/src/contexts/AuthContext.jsx | 123 +++++++ dashboard/src/lib/api.js | 48 +++ dashboard/src/main.jsx | 51 ++- docker-compose.cloud.yml | 52 +++ docker-compose.e2e.local.yml | 10 + main.py | 18 +- requirements-billing.txt | 11 + 35 files changed, 2927 insertions(+), 104 deletions(-) create mode 100644 .env.cloud.example create mode 100644 alembic.ini create mode 100644 alembic/env.py create mode 100644 alembic/script.py.mako create mode 100644 cloud/__init__.py create mode 100644 cloud/auth.py create mode 100644 cloud/billing.py create mode 100644 cloud/config.py create mode 100644 cloud/database.py create mode 100644 cloud/emails.py create mode 100644 cloud/managed_keys.py create mode 100644 cloud/metering.py create mode 100644 cloud/models.py create mode 100644 cloud/oauth.py create mode 100644 cloud/social_profiles.py create mode 100644 dashboard/src/components/AccountPage.jsx create mode 100644 dashboard/src/components/AdvancedBanner.jsx create mode 100644 dashboard/src/components/LoginModal.jsx create mode 100644 dashboard/src/components/PricingSection.jsx create mode 100644 dashboard/src/components/TopUpModal.jsx create mode 100644 dashboard/src/components/TrialGate.jsx create mode 100644 dashboard/src/components/UsageMeter.jsx create mode 100644 dashboard/src/contexts/AuthContext.jsx create mode 100644 dashboard/src/lib/api.js create mode 100644 docker-compose.cloud.yml create mode 100644 docker-compose.e2e.local.yml create mode 100644 requirements-billing.txt diff --git a/.env.cloud.example b/.env.cloud.example new file mode 100644 index 0000000..b5f42e2 --- /dev/null +++ b/.env.cloud.example @@ -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 + +# 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= diff --git a/Dockerfile b/Dockerfile index 95bfd1f..31895e2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 requirements.txt . +COPY requirements.txt requirements-billing.txt ./ RUN python -m venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" RUN pip install --upgrade pip 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 FROM python:3.11-slim diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..6b8c0ee --- /dev/null +++ b/alembic.ini @@ -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 diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..d41af74 --- /dev/null +++ b/alembic/env.py @@ -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()) diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..9dab8a1 --- /dev/null +++ b/alembic/script.py.mako @@ -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"} diff --git a/app.py b/app.py index 0da7234..6dcde0e 100644 --- a/app.py +++ b/app.py @@ -6,6 +6,8 @@ import json import shutil import glob import time +import math +import itertools import asyncio from dotenv import load_dotenv from typing import Dict, Optional, List @@ -32,14 +34,168 @@ MAX_FILE_SIZE_MB = 2048 # 2GB limit JOB_RETENTION_SECONDS = 3600 # 1 hour retention 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 -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] = {} thumbnail_sessions: Dict[str, Dict] = {} publish_jobs: Dict[str, Dict] = {} # {publish_id: {status, result, error}} # Semester to limit concurrency to 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: """ Backward-compat rescue: @@ -131,9 +287,9 @@ async def process_queue(): print(f"🚀 Job Queue Worker started with {MAX_CONCURRENT_JOBS} concurrent slots.") while True: try: - # Wait for a job - job_id = await job_queue.get() - + # Wait for a job (priority, seq, job_id) — lowest priority first. + _priority, _seq, job_id = await job_queue.get() + # Acquire semaphore slot (waits if max jobs are running) await concurrency_semaphore.acquire() print(f"🔄 Acquired slot for job: {job_id}") @@ -154,25 +310,51 @@ async def run_job_wrapper(job_id): except Exception as e: print(f"❌ Job wrapper error {job_id}: {e}") 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 concurrency_semaphore.release() job_queue.task_done() 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 async def lifespan(app: FastAPI): # Start worker and cleanup worker_task = asyncio.create_task(process_queue()) cleanup_task = asyncio.create_task(cleanup_jobs()) + if BILLING_ENABLED: + await cloud.setup_async(app) yield # Cleanup (optional: cancel worker) 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( CORSMiddleware, - allow_origins=["*"], + allow_origins=cloud.settings.allowed_origins if BILLING_ENABLED else ["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], @@ -311,7 +493,11 @@ async def run_job(job_id, job_data): @app.get("/api/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") async def process_endpoint( @@ -320,9 +506,9 @@ async def process_endpoint( url: 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: - raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") + raise gemini_missing_error() ack_flag = str(acknowledged).lower() in ("1", "true", "yes") @@ -365,6 +551,7 @@ async def process_endpoint( env = os.environ.copy() env["GEMINI_API_KEY"] = api_key # Override with key from request + input_path = None if url: cmd.extend(["-u", url]) else: @@ -390,6 +577,9 @@ async def process_endpoint( print(f"[attestation] job={job_id} ip={attestation['ip']} source={attestation['source']} ack=true") + # Meter + reserve minutes for managed users (no-op for BYOK / self-host). + user_id, priority, reservation_id = await reserve_process_minutes(request, url, input_path, job_id) + # Enqueue Job jobs[job_id] = { 'status': 'queued', @@ -397,10 +587,12 @@ async def process_endpoint( 'cmd': cmd, 'env': env, '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"} @@ -431,13 +623,13 @@ class EditRequest(BaseModel): @app.post("/api/edit") async def edit_clip( req: EditRequest, - x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") + request: Request, ): - # Determine API Key - final_api_key = req.api_key or x_gemini_key or os.environ.get("GEMINI_API_KEY") - + # BYOK body key wins; otherwise resolve header / managed / self-host env. + final_api_key = req.api_key or await resolve_gemini(request) + 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: raise HTTPException(status_code=404, detail="Job not found") @@ -647,13 +839,13 @@ class EffectsGenerateRequest(BaseModel): @app.post("/api/effects/generate") async def generate_effects_config( 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.""" - 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: - raise HTTPException(status_code=400, detail="Missing Gemini API Key (Header)") + raise gemini_missing_error() if req.job_id not in jobs: raise HTTPException(status_code=404, detail="Job not found") @@ -1044,8 +1236,8 @@ async def translate_clip( class SocialPostRequest(BaseModel): job_id: str clip_index: int - api_key: str - user_id: str + api_key: Optional[str] = None # BYOK; ignored for managed users + user_id: Optional[str] = None # BYOK profile; ignored for managed users platforms: List[str] # ["tiktok", "instagram", "youtube"] # Optional overrides if frontend wants to edit them title: Optional[str] = None @@ -1056,14 +1248,23 @@ class SocialPostRequest(BaseModel): import httpx @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: 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] if 'result' not in job or 'clips' not in job['result']: raise HTTPException(status_code=400, detail="Job result not available") - + try: clip = job['result']['clips'][req.clip_index] # Video URL is relative /videos/..., we need absolute file path @@ -1085,12 +1286,12 @@ async def post_to_socials(req: SocialPostRequest): # Prepare form data url = "https://api.upload-post.com/api/upload" headers = { - "Authorization": f"Apikey {req.api_key}" + "Authorization": f"Apikey {upload_key}" } - + # Prepare data as dict (httpx handles lists for multiple values) data_payload = { - "user": req.user_id, + "user": post_user, "title": final_title, "platform[]": req.platforms, # Pass list directly "async_upload": "true" # Enable async upload @@ -1142,11 +1343,16 @@ async def post_to_socials(req: SocialPostRequest): raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/social/user") -async def get_social_user(api_key: str = Header(..., alias="X-Upload-Post-Key")): - """Proxy to fetch user ID from Upload-Post""" +async def get_social_user(request: Request): + """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: raise HTTPException(status_code=400, detail="Missing X-Upload-Post-Key header") - + url = "https://api.upload-post.com/api/uploadposts/users" print(f"🔍 Fetching User ID from: {url}") headers = {"Authorization": f"Apikey {api_key}"} @@ -1185,10 +1391,14 @@ async def get_social_user(api_key: str = Header(..., alias="X-Upload-Post-Key")) "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: # Fallback if no profiles found return {"profiles": [], "error": "No profiles found"} - + return {"profiles": profiles_list} @@ -1276,9 +1486,9 @@ async def thumbnail_analyze( x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") ): """Analyze a video and suggest viral YouTube titles.""" - api_key = x_gemini_key + api_key = await resolve_gemini(request) if not api_key: - raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") + raise gemini_missing_error() pre_transcript = None @@ -1357,12 +1567,12 @@ class ThumbnailTitlesRequest(BaseModel): @app.post("/api/thumbnail/titles") async def thumbnail_titles( req: ThumbnailTitlesRequest, - x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") + request: Request, ): """Refine title suggestions or accept a manual title.""" - api_key = x_gemini_key + api_key = await resolve_gemini(request) 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 if req.title: @@ -1419,16 +1629,20 @@ async def thumbnail_generate( count: int = Form(3), face: 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.""" - api_key = x_gemini_key + api_key = await resolve_gemini(request) if not api_key: - raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") + raise gemini_missing_error() # Clamp count 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 face_path = None bg_path = None @@ -1469,11 +1683,18 @@ async def thumbnail_generate( 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).") + # Success — charge the reserved minutes. + if reservation_id: + await _metering.commit_reservation(reservation_id) return {"thumbnails": thumbnails} except HTTPException: + if reservation_id: + await _metering.release_reservation(reservation_id) raise except Exception as e: + if reservation_id: + await _metering.release_reservation(reservation_id) print(f"❌ Thumbnail Generate Error: {e}") raise HTTPException(status_code=500, detail=str(e)) @@ -1485,12 +1706,12 @@ class ThumbnailDescribeRequest(BaseModel): @app.post("/api/thumbnail/describe") async def thumbnail_describe( req: ThumbnailDescribeRequest, - x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") + request: Request, ): """Generate a YouTube description with chapters from the transcript.""" - api_key = x_gemini_key + api_key = await resolve_gemini(request) 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: raise HTTPException(status_code=404, detail="Session not found") @@ -1520,18 +1741,27 @@ async def thumbnail_describe( @app.post("/api/thumbnail/publish") async def thumbnail_publish( + request: Request, background_tasks: BackgroundTasks, session_id: str = Form(...), title: str = Form(...), description: str = Form(...), thumbnail_url: str = Form(...), - api_key: str = Form(...), - user_id: str = Form(...), + api_key: Optional[str] = Form(None), # BYOK; ignored for managed users + 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.""" if session_id not in thumbnail_sessions: 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] video_path = session.get("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.""" try: upload_url = "https://api.upload-post.com/api/upload" - headers = {"Authorization": f"Apikey {api_key}"} + headers = {"Authorization": f"Apikey {upload_key}"} data_payload = { - "user": user_id, + "user": post_user, "platform[]": ["youtube"], "title": title, # required base field (fallback) "async_upload": "true", @@ -1670,12 +1900,12 @@ class SaaSAnalyzeRequest(BaseModel): @app.post("/api/saasshorts/analyze") async def saasshorts_analyze( 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.""" - gemini_key = x_gemini_key or os.environ.get("GEMINI_API_KEY") + gemini_key = await resolve_gemini(request) 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: 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): job_id: str - api_key: str - user_id: str + api_key: Optional[str] = None # BYOK; ignored for managed users + user_id: Optional[str] = None # BYOK profile; ignored for managed users platforms: List[str] title: Optional[str] = None description: Optional[str] = None @@ -1821,11 +2051,18 @@ class SaaSPostRequest(BaseModel): @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.""" if req.job_id not in saas_jobs: 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] result = job.get("result") 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!") url = "https://api.upload-post.com/api/upload" - headers = {"Authorization": f"Apikey {req.api_key}"} + headers = {"Authorization": f"Apikey {upload_key}"} data_payload = { - "user": req.user_id, + "user": post_user, "title": final_title, "platform[]": req.platforms, "async_upload": "true", diff --git a/cloud/__init__.py b/cloud/__init__.py new file mode 100644 index 0000000..13b8227 --- /dev/null +++ b/cloud/__init__.py @@ -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).") diff --git a/cloud/auth.py b/cloud/auth.py new file mode 100644 index 0000000..41c072d --- /dev/null +++ b/cloud/auth.py @@ -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, + } diff --git a/cloud/billing.py b/cloud/billing.py new file mode 100644 index 0000000..1c81aed --- /dev/null +++ b/cloud/billing.py @@ -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) diff --git a/cloud/config.py b/cloud/config.py new file mode 100644 index 0000000..fadbcdb --- /dev/null +++ b/cloud/config.py @@ -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 ") + + # 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." + ) diff --git a/cloud/database.py b/cloud/database.py new file mode 100644 index 0000000..f3f7bc2 --- /dev/null +++ b/cloud/database.py @@ -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 diff --git a/cloud/emails.py b/cloud/emails.py new file mode 100644 index 0000000..32f8c2f --- /dev/null +++ b/cloud/emails.py @@ -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""" +
+

Sign in to OpenShorts

+

Click the button below to sign in. This link expires in 15 minutes.

+

Sign in

+

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

+
+ """ + async with httpx.AsyncClient(timeout=15) as client: + resp = await client.post( + "https://api.resend.com/emails", + headers={"Authorization": f"Bearer {settings.resend_api_key}"}, + json={ + "from": settings.email_from, + "to": [email], + "subject": "Your OpenShorts sign-in link", + "html": html, + }, + ) + resp.raise_for_status() diff --git a/cloud/managed_keys.py b/cloud/managed_keys.py new file mode 100644 index 0000000..f61bf86 --- /dev/null +++ b/cloud/managed_keys.py @@ -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 diff --git a/cloud/metering.py b/cloud/metering.py new file mode 100644 index 0000000..6238b40 --- /dev/null +++ b/cloud/metering.py @@ -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()) diff --git a/cloud/models.py b/cloud/models.py new file mode 100644 index 0000000..d265243 --- /dev/null +++ b/cloud/models.py @@ -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()) diff --git a/cloud/oauth.py b/cloud/oauth.py new file mode 100644 index 0000000..0b30f06 --- /dev/null +++ b/cloud/oauth.py @@ -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}") diff --git a/cloud/social_profiles.py b/cloud/social_profiles.py new file mode 100644 index 0000000..e7fe0c9 --- /dev/null +++ b/cloud/social_profiles.py @@ -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} diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index fb0e912..d992ffc 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -9,6 +9,13 @@ import ThumbnailStudio from './components/ThumbnailStudio'; import SaaShortsTab from './components/SaaShortsTab'; import UGCGallery from './components/UGCGallery'; 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'; // Enhanced "Encryption" using XOR + Base64 with a Salt @@ -134,6 +141,12 @@ const pollJob = async (jobId) => { }; 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') || ''); // Social API State - Load encrypted or plain 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) => { - 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); return; } @@ -332,7 +371,9 @@ function App() { try { 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') { headers['Content-Type'] = 'application/json'; @@ -344,17 +385,19 @@ function App() { body = formData; } - const res = await fetch(getApiUrl('/api/process'), { - method: 'POST', - headers: data.type === 'url' ? headers : { 'X-Gemini-Key': apiKey }, - body - }); + const res = await apiFetch('/api/process', { method: 'POST', headers, body }); if (!res.ok) throw new Error(await res.text()); const resData = await res.json(); setJobId(resData.job_id); } catch (e) { + if (e instanceof QuotaError) { + setStatus('idle'); + setTopUpInfo({ required: e.minutesRequired, remaining: e.minutesRemaining }); + setShowTopUp(true); + return; + } setStatus('error'); setLogs(l => [...l, `Error starting job: ${e.message}`]); } @@ -503,11 +546,28 @@ function App() { /> )} - {(!apiKey || !uploadPostKey) && ( + {/* Cloud: minutes meter + account/sign-in */} + {billingEnabled && isManaged && ( + { window.location.hash = '#/account'; }} /> + )} + {billingEnabled && isSignedIn && !isManaged && ( + + )} + {billingEnabled && !isSignedIn && ( + + )} + + {keysMissing && ( + + ) : billingEnabled ? ( +
+
+

Start your free trial

+ 3 days free +
+

+ Generate shorts with zero setup — no API keys needed. 3 days free, then from $12/mo. Cancel anytime. +

+ +
+ ) : ( + <>
@@ -620,14 +716,17 @@ function App() {
+ + )} +

Video Translation

- Optional + Your own key

- Translate your clips to different languages using ElevenLabs AI dubbing. - Automatically translates speech while preserving the original voice characteristics. + For AI Shorts & dubbing — bring your own key. Translate your clips to different + languages using ElevenLabs AI dubbing (billed by ElevenLabs). Not covered by your plan.

@@ -674,11 +773,12 @@ function App() {

AI Shorts (UGC Videos)

- New + Your own key

Generate UGC-style videos with AI actors for any product or business using fal.ai. - Just describe your product or paste a URL. Requires fal.ai + ElevenLabs API keys. + Not covered by your plan — bring your own fal.ai + ElevenLabs keys (billed by those + providers, ~$0.65-2 per video). Your plan still covers the AI script & orchestration.

@@ -726,7 +826,7 @@ function App() { {/* View: SaaS Shorts */} {activeTab === 'saasshorts' && ( - + )} {/* View: AI Agent */} @@ -852,7 +952,7 @@ function App() { {/* View: Thumbnails */} {activeTab === 'thumbnails' && ( - + )} {/* View: Gallery */} @@ -1106,6 +1206,15 @@ function App() { uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} /> + + {showLogin && setShowLogin(false)} />} + {showTopUp && ( + setShowTopUp(false)} + required={topUpInfo.required} + remaining={topUpInfo.remaining} + /> + )}
); } diff --git a/dashboard/src/Landing.jsx b/dashboard/src/Landing.jsx index 5f3e124..0789c94 100644 --- a/dashboard/src/Landing.jsx +++ b/dashboard/src/Landing.jsx @@ -136,7 +136,7 @@ export default function Landing({ onLaunchApp }) { }, { 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?", @@ -259,6 +259,11 @@ export default function Landing({ onLaunchApp }) {
+

+ Free to self-host with Docker (bring your own keys) · + or use it here with no setup — 3-day free trial, then from $12/mo +

+ {/* Platform Icons */}
Export to: @@ -302,6 +307,46 @@ export default function Landing({ onLaunchApp }) {
+ {/* Two ways to use it: free self-host vs paid hosted */} +
+
+

Two ways to use OpenShorts

+

Run it yourself for free, or let us run everything for you.

+
+
+
+
+ +

Self-hosted

+ Free +
+

+ 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. +

+ + Get it on GitHub + +
+
+
+ +

Hosted on openshorts.app

+ From $12/mo +
+

+ Zero setup, no API keys, we run all the AI and compute for you. 3-day free trial, then a plan + from $12/mo (100 min). Best if you just want to make clips without any technical hassle. +

+ +
+
+
+ {/* 3 Tools in 1 Section */}
diff --git a/dashboard/src/components/AccountPage.jsx b/dashboard/src/components/AccountPage.jsx new file mode 100644 index 0000000..cae7fef --- /dev/null +++ b/dashboard/src/components/AccountPage.jsx @@ -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
; + + 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 ( +
+
+
+

Your account

+

{me.user?.email}

+
+ +
+ + {activating && ( +
+ Activating your plan… +
+ )} + +
+
+
+ {plan ? `${plan} plan` : 'No active plan'} + {me.status && me.status !== 'active' && ( + {me.status} + )} + {me.cancel_at_period_end && ( + cancels at period end + )} +
+ +
+ +
+
+ Plan minutes + {fmt1(m.plan_used)} / {fmt1(m.plan_allowance)} used +
+
+
+
+
+ Top-up minutes + {fmt1(m.topup_remaining)} remaining +
+
+ Total remaining + {fmt1(m.remaining)} min +
+
+
+ + {topups.length > 0 && ( +
+

Buy more minutes

+

Top-ups never expire while your plan is active.

+
+ {topups.map((t) => ( + + ))} +
+
+ )} +
+ ); +} diff --git a/dashboard/src/components/AdvancedBanner.jsx b/dashboard/src/components/AdvancedBanner.jsx new file mode 100644 index 0000000..5887271 --- /dev/null +++ b/dashboard/src/components/AdvancedBanner.jsx @@ -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 ( +
+
+ +
+ Advanced tool.{' '} + {needsPlan + ? <>Start your 3-day free trial to unlock. This tool also uses your own fal.ai + ElevenLabs keys (you pay those providers). + : <>AI video & voice generation use your own fal.ai + ElevenLabs keys — add them in Settings. Script & orchestration are included in your plan.} +
+
+ +
+ ); +} diff --git a/dashboard/src/components/LoginModal.jsx b/dashboard/src/components/LoginModal.jsx new file mode 100644 index 0000000..83cbd86 --- /dev/null +++ b/dashboard/src/components/LoginModal.jsx @@ -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 ( +
+
+ + +

Sign in to OpenShorts

+

Access your plan and generate shorts with no API keys.

+ + {sent ? ( +
+
+ +
+

Check your inbox

+

We sent a sign-in link to {email}. It expires in 15 minutes.

+
+ ) : ( + <> +
+
+ + setEmail(e.target.value)} + placeholder="you@email.com" + className="input-field pl-10" + autoFocus + /> +
+ {error &&

{error}

} + +
+ + {googleAuthEnabled && ( + <> +
+
+ or +
+
+ + + )} + + )} +
+
+ ); +} diff --git a/dashboard/src/components/PricingSection.jsx b/dashboard/src/components/PricingSection.jsx new file mode 100644 index 0000000..529b612 --- /dev/null +++ b/dashboard/src/components/PricingSection.jsx @@ -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
; + } + + const byPlan = (plan) => plans.find((p) => p.plan === plan && p.interval === interval); + + return ( +
+
+ Monthly + + + Yearly · 2 months free + +
+ +
+ {PLAN_ORDER.map((plan) => { + const entry = byPlan(plan); + if (!entry) return null; + const highlight = plan === HIGHLIGHT; + return ( +
+ {highlight && ( + + Most popular + + )} +

{plan}

+

{PLAN_BLURB[plan]}

+
+ {fmt(entry.amount, entry.currency)} + /{interval === 'month' ? 'mo' : 'yr'} +
+
    +
  • {entry.minutes} min of video / month
  • +
  • No API keys needed
  • +
  • Gemini + auto-posting included
  • + {plan === 'pro' &&
  • Priority processing queue
  • } +
+ +

3 days free, then billed monthly. Cancel anytime.

+
+ ); + })} +
+ + {/* What every plan includes vs what's bring-your-own-key */} +
+
+

+ Included in every plan +

+
    +
  • Clip Generator — fully managed, no API keys
  • +
  • YouTube Studio — titles, thumbnails, descriptions
  • +
  • Auto-posting to TikTok, Reels & Shorts
  • +
  • All the AI & compute run on our servers
  • +
+

+ Your monthly minutes cover video processing. Titles & descriptions are free; + AI thumbnail image generation uses ~3 min of your quota per batch. +

+
+
+

+ Bring your own key +

+

+ AI Shorts (AI-actor UGC videos) and voice dubbing use premium generation from + fal.ai and ElevenLabs. 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 & orchestration. +

+

Managed credits for these are coming later — no keys needed.

+
+
+ + {/* Free self-hosted path — the honest "free" option */} +
+
+
+
+
+

+ Free forever — self-hosted + $0 +

+

+ OpenShorts is open source. Run it on your own machine with Docker and use it completely free — + you just bring your own API keys and your own hardware. The plans above are for the + hosted version on this site: zero setup, no keys, we run everything for you. +

+
+
+ + Self-host free + +
+
+ +

+ Use it free on your own computer, or skip the setup and use it here — 3 days free, then a plan. +

+
+ ); +} diff --git a/dashboard/src/components/SaaShortsTab.jsx b/dashboard/src/components/SaaShortsTab.jsx index 6ffadbb..e905c19 100644 --- a/dashboard/src/components/SaaShortsTab.jsx +++ b/dashboard/src/components/SaaShortsTab.jsx @@ -1,6 +1,7 @@ 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 { getApiUrl } from '../config'; +import { apiFetch } from '../lib/api'; const STYLE_OPTIONS = [ { id: 'ugc', label: 'UGC Natural', desc: 'Authentic, talking to camera' }, @@ -34,7 +35,11 @@ function saveCache(url, analysis, webResearch, scripts) { } 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 const [step, setStep] = useState(() => { const cache = loadCache(); @@ -186,7 +191,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo const handleAnalyze = async () => { if (!url.trim() && !description.trim()) return; - if (!geminiApiKey) { + if (needsGeminiKey) { setAnalyzeError('Gemini API key required. Set it in Settings.'); return; } @@ -195,11 +200,11 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo setAnalyzeError(''); try { - const res = await fetch(getApiUrl('/api/saasshorts/analyze'), { + const res = await apiFetch('/api/saasshorts/analyze', { method: 'POST', headers: { 'Content-Type': 'application/json', - 'X-Gemini-Key': geminiApiKey, + ...geminiHeader, }, body: JSON.stringify({ url: url.trim() || undefined, @@ -274,7 +279,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo scriptToSend.full_narration = editedNarration; } - const res = await fetch(getApiUrl('/api/saasshorts/generate'), { + const res = await apiFetch('/api/saasshorts/generate', { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -320,7 +325,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo scriptToSend.full_narration = editedNarration; } - const res = await fetch(getApiUrl('/api/saasshorts/generate'), { + const res = await apiFetch('/api/saasshorts/generate', { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -1467,7 +1472,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo payload.scheduled_date = new Date(scheduleDate).toISOString(); payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; } - const res = await fetch(getApiUrl('/api/saasshorts/post'), { + const res = await apiFetch('/api/saasshorts/post', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), diff --git a/dashboard/src/components/ThumbnailStudio.jsx b/dashboard/src/components/ThumbnailStudio.jsx index 5663972..3b4b7b3 100644 --- a/dashboard/src/components/ThumbnailStudio.jsx +++ b/dashboard/src/components/ThumbnailStudio.jsx @@ -1,6 +1,7 @@ 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 { getApiUrl } from '../config'; +import { apiFetch } from '../lib/api'; 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 const [step, setStep] = useState(0); const [mode, setMode] = useState(null); // 'video' or 'manual' @@ -165,7 +170,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse // --- Step 1: Analyze Video --- 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); try { @@ -180,9 +185,9 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse return alert('Please upload a video file.'); } - const res = await fetch(getApiUrl('/api/thumbnail/analyze'), { + const res = await apiFetch('/api/thumbnail/analyze', { method: 'POST', - headers: { 'X-Gemini-Key': geminiApiKey }, + headers: keyHeader, body: formData }); @@ -223,11 +228,11 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse // Create session for manual mode const newSessionId = sessionId || crypto.randomUUID(); setSessionId(newSessionId); - fetch(getApiUrl('/api/thumbnail/titles'), { + apiFetch('/api/thumbnail/titles', { method: 'POST', headers: { 'Content-Type': 'application/json', - 'X-Gemini-Key': geminiApiKey + ...keyHeader }, body: JSON.stringify({ title: manualTitle, session_id: newSessionId }) }).catch(() => { }); @@ -246,11 +251,11 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse setChatHistory(prev => [...prev, { role: 'user', content: userMsg }]); try { - const res = await fetch(getApiUrl('/api/thumbnail/titles'), { + const res = await apiFetch('/api/thumbnail/titles', { method: 'POST', headers: { 'Content-Type': 'application/json', - 'X-Gemini-Key': geminiApiKey + ...keyHeader }, body: JSON.stringify({ session_id: sessionId, message: userMsg }) }); @@ -275,7 +280,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse // --- Step 3: Generate Thumbnails --- 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; 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 (bgImage) formData.append('background', bgImage); - const res = await fetch(getApiUrl('/api/thumbnail/generate'), { + const res = await apiFetch('/api/thumbnail/generate', { method: 'POST', - headers: { 'X-Gemini-Key': geminiApiKey }, + headers: keyHeader, body: formData }); @@ -334,18 +339,18 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse // --- Description Generation --- 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; if (!finalTitle) return alert('Please select a title first.'); if (!sessionId) return alert('No session available.'); setIsDescribing(true); try { - const res = await fetch(getApiUrl('/api/thumbnail/describe'), { + const res = await apiFetch('/api/thumbnail/describe', { method: 'POST', headers: { 'Content-Type': 'application/json', - 'X-Gemini-Key': geminiApiKey + ...keyHeader }, body: JSON.stringify({ session_id: sessionId, title: finalTitle }) }); @@ -366,7 +371,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse // --- Publish to YouTube --- 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; if (!finalTitle) return alert('No title selected.'); 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); // 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', body: formData }); @@ -472,8 +477,8 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse - {/* Gemini API Key Warning */} - {!geminiApiKey && ( + {/* Gemini API Key Warning (self-host BYOK only; managed uses server key) */} + {needsKey && (
@@ -485,7 +490,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse {/* ===== STEP 0: Input Mode Selection ===== */} {step === 0 && ( -
+
{/* Mode A: Video Analysis */}
@@ -1058,7 +1063,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
{/* Publish Button */} - {(!uploadPostKey || !uploadUserId) ? ( + {(!managed && (!uploadPostKey || !uploadUserId)) ? (
diff --git a/dashboard/src/components/TopUpModal.jsx b/dashboard/src/components/TopUpModal.jsx new file mode 100644 index 0000000..b863911 --- /dev/null +++ b/dashboard/src/components/TopUpModal.jsx @@ -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 ( +
+
+ +
+

You're out of minutes

+

+ {typeof required === 'number' + ? <>This video needs {required} min but you have {Math.round((remaining || 0) * 10) / 10} min left. + : 'Add more minutes to keep generating.'} +

+
+ {topups.map((t) => ( + + ))} + {topups.length === 0 &&
} +
+

Or upgrade your plan for more monthly minutes.

+
+
+ ); +} diff --git a/dashboard/src/components/TrialGate.jsx b/dashboard/src/components/TrialGate.jsx new file mode 100644 index 0000000..774abd0 --- /dev/null +++ b/dashboard/src/components/TrialGate.jsx @@ -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 ( +
+
+ +
+ Preview mode.{' '} + Start your 3-day free trial to generate with {toolName} — + no API keys, from $12/mo. Or run it free by self-hosting. +
+
+ +
+ ); +} diff --git a/dashboard/src/components/UsageMeter.jsx b/dashboard/src/components/UsageMeter.jsx new file mode 100644 index 0000000..6f417a0 --- /dev/null +++ b/dashboard/src/components/UsageMeter.jsx @@ -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 ( + + ); +} diff --git a/dashboard/src/contexts/AuthContext.jsx b/dashboard/src/contexts/AuthContext.jsx new file mode 100644 index 0000000..db95819 --- /dev/null +++ b/dashboard/src/contexts/AuthContext.jsx @@ -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 {children}; +} diff --git a/dashboard/src/lib/api.js b/dashboard/src/lib/api.js new file mode 100644 index 0000000..0819d45 --- /dev/null +++ b/dashboard/src/lib/api.js @@ -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(); +} diff --git a/dashboard/src/main.jsx b/dashboard/src/main.jsx index 7bd9579..5c51ae6 100644 --- a/dashboard/src/main.jsx +++ b/dashboard/src/main.jsx @@ -4,10 +4,50 @@ import './index.css' import App from './App.jsx' import Landing from './Landing.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 ( +
+
+ OpenShorts + ← Back to app +
+
+ {title &&

{title}

} + {children} +
+
+ ); +} + +function PricingView() { + const [showLogin, setShowLogin] = useState(false); + return ( + + setShowLogin(true)} /> + {showLogin && setShowLogin(false)} />} + + ); +} + +function AccountView() { + const { isSignedIn, loading } = useAuth(); + useEffect(() => { + if (!loading && !isSignedIn) window.location.hash = '#/pricing'; + }, [loading, isSignedIn]); + return ; +} function Root() { 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 === '#app' || localStorage.getItem('openshorts_skip_landing') === '1') return 'app'; return 'landing'; @@ -28,12 +68,19 @@ function Root() { }; if (view === 'legal') return ; + if (view === 'pricing') return ; + if (view === 'account') return ; + if (view === 'auth') { + return
Signing you in…
; + } if (view === 'app') return ; return ; } createRoot(document.getElementById('root')).render( - + + + , ) diff --git a/docker-compose.cloud.yml b/docker-compose.cloud.yml new file mode 100644 index 0000000..662c547 --- /dev/null +++ b/docker-compose.cloud.yml @@ -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 } + # 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: diff --git a/docker-compose.e2e.local.yml b/docker-compose.e2e.local.yml new file mode 100644 index 0000000..4dd4570 --- /dev/null +++ b/docker-compose.e2e.local.yml @@ -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" diff --git a/main.py b/main.py index 0e26f8c..f8fa0f9 100644 --- a/main.py +++ b/main.py @@ -474,6 +474,13 @@ def download_youtube_video(url, output_dir="."): cookies_path = None 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. # extractor_args tries multiple player clients in order; tv_embed / android # avoid the OAuth/PO-token checks that block server IPs. @@ -482,6 +489,7 @@ def download_youtube_video(url, output_dir="."): 'verbose': True, 'no_warnings': False, 'cookiefile': cookies_path if cookies_path else None, + 'proxy': _proxy, 'socket_timeout': 30, 'retries': 10, 'fragment_retries': 10, @@ -551,9 +559,17 @@ Technical Details: {str(e)} os.remove(expected_file) print(f"🗑️ Removed existing file to re-download with H.264 codec") + # When downloading through a paid proxy, cap at 720p to control bandwidth + # cost (a 720p source is plenty for 9:16 clips). Direct downloads keep best. + if _proxy: + _fmt = ('bestvideo[vcodec^=avc1][height<=720][ext=mp4]+bestaudio[ext=m4a]/' + 'bestvideo[vcodec^=avc1][height<=720]+bestaudio/best[height<=720][ext=mp4]/best[height<=720]/best') + else: + _fmt = 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best' + ydl_opts = { **_COMMON_YDL_OPTS, - 'format': 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best', + 'format': _fmt, 'outtmpl': output_template, 'merge_output_format': 'mp4', 'overwrites': True, diff --git a/requirements-billing.txt b/requirements-billing.txt new file mode 100644 index 0000000..cfd8b08 --- /dev/null +++ b/requirements-billing.txt @@ -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