Merge pull request #52 from mutonby/feat/paid-mode

Paid hosted mode (managed keys, billing, video library) — self-host stays free
This commit is contained in:
mutonby 2026-07-16 18:03:00 +02:00 committed by GitHub
commit 3ea5973e25
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
56 changed files with 4627 additions and 336 deletions

View file

@ -38,6 +38,15 @@ videos/
# Model files (downloaded at build time)
*.pt
# Secrets — never bake real credentials into the image (repo is public,
# image may be pushed to a registry). Runtime env comes via compose env_file.
.env
.env.*
!.env.example
!.env.cloud.example
*.pem
*.key
# Docker
Dockerfile
docker-compose.yml

64
.env.cloud.example Normal file
View file

@ -0,0 +1,64 @@
# 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 + admin alerts, via SMTP (e.g. Namecheap Private Email).
# Quote the password if it contains $ or * so dotenv keeps it literal.
SMTP_HOST=mail.privateemail.com
SMTP_PORT=465
SMTP_USER=info@yourdomain.com
SMTP_PASSWORD='your-mailbox-password'
EMAIL_FROM=OpenShorts <info@yourdomain.com>
# Operational alerts (proxy out of credits / high failure rate) are emailed here.
ADMIN_EMAIL=you@example.com
# Telegram admin alerts (optional) — instant pings for purchases, cancellations,
# proxy-out-of-credits and high failure rate. Create a bot with @BotFather to get
# the token, then message your bot and read the chat id from:
# https://api.telegram.org/bot<TOKEN>/getUpdates
TELEGRAM_BOT_TOKEN=
TELEGRAM_CHAT_ID=
# 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=
# Cloudflare R2 (S3-compatible) — durable storage for users' generated videos.
# Create an R2 bucket + an "Object Read & Write" API token scoped to it.
R2_ENDPOINT=https://<account_id>.r2.cloudflarestorage.com
R2_BUCKET=openshorts-videos
R2_ACCESS_KEY_ID=
R2_SECRET_ACCESS_KEY=
# PO-token provider for 720p/1080p YouTube downloads.
# The bgutil provider is baked into the backend image in *script mode*
# (BGUTIL_SCRIPT_PATH is set inside the Dockerfile) — no sidecar, nothing to set here.
# Only if you run bgutil as an external HTTP service, point at it instead:
# BGUTIL_BASE_URL=http://bgutil:4416

View file

@ -10,18 +10,21 @@ 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
WORKDIR /app
# Install FFmpeg, OpenCV dependencies, and Node.js (for yt-dlp JS challenges)
# Install FFmpeg, OpenCV deps, Node.js + npm + git (for yt-dlp JS + bgutil build)
RUN apt-get update && apt-get install -y --no-install-recommends \
ffmpeg \
libgl1 \
@ -30,15 +33,30 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libxext6 \
libxrender1 \
nodejs \
npm \
git \
&& rm -rf /var/lib/apt/lists/*
# Deno JS runtime — yt-dlp needs it to solve YouTube's nsig challenge for 720p+.
COPY --from=denoland/deno:bin /deno /usr/local/bin/deno
# bgutil PO-token provider, baked in as a local Node script (script mode) — no
# separate service/sidecar needed. Unlocks 720p/1080p together with Deno.
RUN git clone --depth 1 https://github.com/Brainicism/bgutil-ytdlp-pot-provider /opt/bgutil-provider \
&& cd /opt/bgutil-provider/server \
&& npm install --no-audit --no-fund \
&& npx tsc \
&& npm cache clean --force
ENV BGUTIL_SCRIPT_PATH=/opt/bgutil-provider/server/build/generate_once.js
# Copy virtual env from builder
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
ENV PYTHONUNBUFFERED=1
# Always upgrade yt-dlp to latest (YouTube bot-detection changes frequently)
RUN pip install --upgrade --no-cache-dir yt-dlp
# Latest yt-dlp (nightly, YouTube changes constantly) + the bgutil PO-token
# provider plugin. Together with Deno + the baked-in bgutil script this unlocks 720p.
RUN pip install --upgrade --pre --no-cache-dir "yt-dlp[default]" bgutil-ytdlp-pot-provider
# Copy application code
COPY . .

View file

@ -2,6 +2,10 @@ MIT License
Copyright (c) 2024 OpenShorts
EXCEPTION: All content that resides under the "cloud/" directory of this
repository is licensed under the license defined in "cloud/LICENSE"
(the OpenShorts Commercial License), not under the MIT License below.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights

View file

@ -294,4 +294,6 @@ Contributions are welcome! Whether it's adding new AI models, improving the lip-
## License
MIT License. OpenShorts is yours to use, modify, and scale.
MIT License for the core application — OpenShorts is yours to use, modify, and scale.
**Exception:** the [`cloud/`](cloud/LICENSE) directory (billing, managed keys, and the hosted-service infrastructure behind the optional `BILLING_ENABLED` flag) is source-available under the OpenShorts Commercial License. You can read it, modify it, and self-host it for personal or internal use, but you can't offer it to third parties as a paid/hosted service. Self-hosting the core app never requires this directory.

41
alembic.ini Normal file
View file

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

60
alembic/env.py Normal file
View file

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

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

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

657
app.py

File diff suppressed because it is too large Load diff

66
cloud/LICENSE Normal file
View file

@ -0,0 +1,66 @@
The OpenShorts Commercial License (the "Commercial License")
Copyright (c) 2024-present OpenShorts (openshorts.app)
All source code and associated documentation files contained in this
directory ("cloud/") and its subdirectories (the "Commercial Software")
are NOT covered by the MIT License that applies to the rest of this
repository. The Commercial Software is licensed under the following
terms instead.
Permitted use
-------------
Subject to the conditions below, you are granted a limited, non-exclusive,
non-transferable, royalty-free license to:
1. View, study, and modify the Commercial Software.
2. Copy and self-host the Commercial Software for your own PERSONAL or
INTERNAL business use (i.e., use by you or within your own
organization).
3. Contribute changes to the Commercial Software back to this
repository.
Prohibited use
--------------
You may NOT, without a separate written commercial agreement with the
copyright holder:
1. Offer the Commercial Software, or any modified version or derivative
of it, to third parties as a hosted, managed, or paid service
(including but not limited to Software-as-a-Service, resale,
white-labeling, or any offering that competes with the hosted
service at openshorts.app).
2. Sell, sublicense, or redistribute the Commercial Software, on its
own or as part of another product or service, for a fee or other
consideration.
3. Remove, alter, or circumvent any license, billing, metering,
entitlement, or usage-limit functionality contained in the
Commercial Software when providing access to third parties.
Clarifications
--------------
- Everything OUTSIDE the cloud/ directory remains licensed under the
MIT License (see the LICENSE file at the repository root). You can
self-host, modify, and use the core OpenShorts application freely
under that license, with or without this directory present. The
application runs fully without the Commercial Software when the
BILLING_ENABLED flag is not set.
- Contributions submitted to this directory are accepted under these
same terms, and the contributor grants the copyright holder the
right to license the contribution commercially.
For commercial licensing inquiries, contact: jc.caverogracia@gmail.com
Disclaimer
----------
THE COMMERCIAL SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
COMMERCIAL SOFTWARE OR THE USE OR OTHER DEALINGS IN THE COMMERCIAL
SOFTWARE.

49
cloud/__init__.py Normal file
View file

@ -0,0 +1,49 @@
"""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, videos
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)
app.include_router(videos.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, videos
await database.init_engine()
await metering.release_orphaned_reservations()
metering.start_sweeper()
videos.start_sweeper()
print("☁️ Cloud billing mode ENABLED (DB ready, metering active).")

95
cloud/alerts.py Normal file
View file

@ -0,0 +1,95 @@
"""Operational email alerts for the admin (proxy out of credits, high failure rate).
Tracks recent managed-job outcomes in memory and emails ADMIN_EMAIL (via Resend)
when something looks broken, with a per-alert cooldown so it never spams.
"""
import time
from collections import deque
from .config import settings
from .emails import send_email
_recent = deque(maxlen=12) # rolling window of recent job outcomes (ok bool)
_last_alert = {} # alert kind -> last-sent epoch
_ALERT_COOLDOWN = 3600 # 1 hour between repeats of the same alert
_FAIL_WINDOW_MIN = 6 # need at least this many recent jobs to judge a rate
_FAIL_THRESHOLD = 5 # ...and this many failures among them
# Substrings that suggest the proxy itself failed (auth / balance / tunnel).
_PROXY_HINTS = ("proxy", "407", "proxyauthentication", "tunnel connection",
"credit", "balance", "insufficient", "payment required")
def _looks_like_proxy_error(err: str) -> bool:
e = (err or "").lower()
return any(k in e for k in _PROXY_HINTS)
def _cooldown_ok(kind: str) -> bool:
now = time.time()
if now - _last_alert.get(kind, 0) < _ALERT_COOLDOWN:
return False
_last_alert[kind] = now
return True
async def send_telegram(text: str):
"""Push a plain-text message to the admin's Telegram chat. No-op if unset.
Best-effort: never raises — an alert failing must not break a webhook or job.
"""
if not settings.telegram_configured:
return
try:
import httpx
url = f"https://api.telegram.org/bot{settings.telegram_bot_token}/sendMessage"
payload = {"chat_id": settings.telegram_chat_id, "text": text,
"disable_web_page_preview": True}
async with httpx.AsyncClient(timeout=10) as client:
await client.post(url, json=payload)
except Exception as e:
print(f"⚠️ Telegram alert failed: {e}")
async def send_admin_alert(subject: str, body: str):
"""Notify the admin via every configured channel (email + Telegram)."""
# Telegram first — instant, and configured independently of email.
await send_telegram(f"{subject}\n\n{body}")
to = settings.admin_email
if not to or not settings.smtp_configured:
if not settings.telegram_configured:
print(f"⚠️ [ADMIN ALERT] {subject}\n{body[:500]}"
+ ("" if to else " (set ADMIN_EMAIL + SMTP_* or TELEGRAM_* to receive these)"))
return
html = f"<pre style='font:13px/1.5 monospace;white-space:pre-wrap'>{body}</pre>"
await send_email(to, f"[OpenShorts] {subject}", html)
async def record_job_outcome(ok: bool, error_text: str = ""):
"""Record a managed job's result and fire an alert if the picture looks bad."""
_recent.append(bool(ok))
if ok:
return
# 1) Proxy / credits problem — most urgent, alert immediately.
if _looks_like_proxy_error(error_text) and _cooldown_ok("proxy"):
await send_admin_alert(
"⚠️ Proxy error — DataImpulse may be out of credits",
"A managed job failed with a proxy-related error. Check your residential "
"proxy balance (DataImpulse) — downloads will keep failing until it's topped up.\n\n"
f"Error:\n{error_text[:1200]}",
)
return
# 2) High failure rate — the YouTube download path may be broken (arms race).
recent = list(_recent)
fails = recent.count(False)
if len(recent) >= _FAIL_WINDOW_MIN and fails >= _FAIL_THRESHOLD and _cooldown_ok("failrate"):
await send_admin_alert(
"⚠️ High download failure rate",
f"{fails} of the last {len(recent)} managed jobs failed. The YouTube "
"download path may be broken (yt-dlp / PO-token change). A backend image "
"rebuild usually pulls the yt-dlp fix.\n\n"
f"Last error:\n{error_text[:1200]}",
)

214
cloud/auth.py Normal file
View file

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

399
cloud/billing.py Normal file
View file

@ -0,0 +1,399 @@
"""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/end-trial")
async def end_trial(request: Request):
"""End the free trial immediately: charge the card now and unlock full plan
minutes. Used when a trialing user hits the trial minute cap and chooses to
activate their plan right away. The subscription webhook flips status→active
(and thus the full ``minutes_per_period`` allowance) once Stripe confirms."""
user = await get_current_user_required(request)
async with database.session() as session:
sub = (await session.execute(
select(Subscription).where(Subscription.user_id == user.id)
)).scalar_one_or_none()
if not sub or sub.status != "trialing":
raise HTTPException(status_code=409, detail="No active trial to convert.")
try:
updated = await asyncio.to_thread(lambda: stripe.Subscription.modify(
sub.stripe_subscription_id, trial_end="now",
))
except Exception:
raise HTTPException(status_code=502, detail="Could not activate your plan. Try again.")
return {"status": updated.get("status", "active")}
@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
buyer_email = None
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,
))
buyer_email = (await s.execute(
select(User.email).where(User.id == user_id)
)).scalar_one_or_none()
from .alerts import send_admin_alert
await send_admin_alert(
"💰 Top-up purchased",
f"{buyer_email or 'A user'} bought +{minutes} minutes.",
)
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)
now_canceling = bool(sub_obj.get("cancel_at_period_end"))
# Detect the moment the user hits "cancel" (False -> True).
was_canceling = bool(row.cancel_at_period_end) if row else False
just_canceled = now_canceling and not was_canceling
# Purchase signals: brand-new subscription, and trial -> paid conversion.
is_new_sub = row is None
prev_status = row.status if row else None
buyer_email = (await s.execute(
select(User.email).where(User.id == user_id)
)).scalar_one_or_none()
end_dt = _ts(end)
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=end_dt,
cancel_at_period_end=now_canceling,
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)
# Purchase alert: someone just subscribed (trial started or paid outright).
now_status = sub_obj["status"]
if is_new_sub:
from .alerts import send_admin_alert
label = "trial started — card on file" if now_status == "trialing" else now_status
await send_admin_alert(
"🎉 New subscriber",
f"{buyer_email or 'A user'} started the {plan} ({interval}) plan.\nStatus: {label}.",
)
elif prev_status == "trialing" and now_status == "active":
from .alerts import send_admin_alert
await send_admin_alert(
"💳 Trial converted to paid",
f"{buyer_email or 'A user'} is now a paying {plan} ({interval}) subscriber. 🎉",
)
# Churn alert to the admin the moment a subscription is set to cancel.
if just_canceled:
from .alerts import send_admin_alert
from .config import VIDEO_RETENTION_GRACE_DAYS
await send_admin_alert(
"🔻 Subscription canceled",
f"A {plan} subscriber just canceled.\n"
f"Access continues until {end_dt:%Y-%m-%d}; their videos are then kept "
f"{VIDEO_RETENTION_GRACE_DAYS} more days before deletion.",
)
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)

236
cloud/config.py Normal file
View file

@ -0,0 +1,236 @@
"""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.
TRIAL_DAYS = 3
# Minute cap DURING the trial (across all plans). Enough to evaluate the product,
# but bounds the free managed-compute / proxy exposure per sign-up so a
# cancel-before-charge account can't burn a full plan's worth of minutes. Once the
# trial converts to an active subscription the full plan allowance applies.
TRIAL_MINUTE_CAP = 20
# 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
# Other managed Gemini calls that upload a video for context (AI effect/filter
# generation, thumbnail analysis, SaaS-shorts analysis). Cheaper than image gen
# but not free — meter a small fixed cost so an entitled user can't loop them to
# burn the operator's managed Gemini budget. Pure-text calls (titles/desc) stay free.
MANAGED_ANALYSIS_MINUTES = 1
# Post-processing FFmpeg re-encodes (subtitle burn, hook overlay) and the
# Remotion render proxy do real server compute per call. Meter a small fixed
# cost so an entitled user can't loop them for free off-quota.
SUBTITLE_MINUTES = 2
HOOK_MINUTES = 1
RENDER_MINUTES = 3
# The thumbnail-studio upload kicks off a (possibly YouTube) download + a full
# Whisper transcription in the background — expensive and proxy-bandwidth-heavy.
# Charge a fixed guard cost up front, settled when the background job finishes.
TRANSCRIBE_MINUTES = 2
# 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 (SMTP — e.g. Namecheap Private Email)
@property
def smtp_host(self) -> str:
return os.environ.get("SMTP_HOST", "mail.privateemail.com")
@property
def smtp_port(self) -> int:
return int(os.environ.get("SMTP_PORT", "465"))
@property
def smtp_user(self) -> str:
return os.environ.get("SMTP_USER", "")
@property
def smtp_password(self) -> str:
return os.environ.get("SMTP_PASSWORD", "")
@property
def smtp_configured(self) -> bool:
return bool(self.smtp_user and self.smtp_password)
@property
def email_from(self) -> str:
# Namecheap requires the From to be the authenticated mailbox.
return os.environ.get("EMAIL_FROM") or (f"OpenShorts <{self.smtp_user}>" if self.smtp_user else "OpenShorts")
@property
def admin_email(self) -> str:
# Where operational alerts (proxy out of credits, high failure rate) go.
return os.environ.get("ADMIN_EMAIL", "")
# Telegram (optional) — real-time admin alerts (purchases, churn, outages)
@property
def telegram_bot_token(self) -> str:
return os.environ.get("TELEGRAM_BOT_TOKEN", "")
@property
def telegram_chat_id(self) -> str:
return os.environ.get("TELEGRAM_CHAT_ID", "")
@property
def telegram_configured(self) -> bool:
return bool(self.telegram_bot_token and self.telegram_chat_id)
# 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")
# Cloudflare R2 (S3-compatible) — durable video library storage
@property
def r2_endpoint(self) -> str:
return os.environ.get("R2_ENDPOINT", "")
@property
def r2_bucket(self) -> str:
return os.environ.get("R2_BUCKET", "")
@property
def r2_access_key_id(self) -> str:
return os.environ.get("R2_ACCESS_KEY_ID", "")
@property
def r2_secret_access_key(self) -> str:
return os.environ.get("R2_SECRET_ACCESS_KEY", "")
@property
def r2_configured(self) -> bool:
return bool(self.r2_endpoint and self.r2_bucket and self.r2_access_key_id
and self.r2_secret_access_key)
# Days a user's videos survive after their subscription ends (grace period).
VIDEO_RETENTION_GRACE_DAYS = 7
settings = Settings()
def validate_required():
"""Raise a clear error if mandatory cloud settings are missing.
Called from ``cloud.setup`` at startup so a misconfigured deploy fails fast
instead of erroring on the first paid request.
"""
missing = []
if not settings.database_url:
missing.append("DATABASE_URL")
if not settings.jwt_secret:
missing.append("JWT_SECRET")
if missing:
raise RuntimeError(
"BILLING_ENABLED is set but required settings are missing: "
+ ", ".join(missing)
+ ". Set them (see docker-compose.cloud.yml) or unset BILLING_ENABLED "
"to run in self-hosted BYOK mode."
)

49
cloud/database.py Normal file
View file

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

58
cloud/emails.py Normal file
View file

@ -0,0 +1,58 @@
"""Transactional + operational email via SMTP (e.g. Namecheap Private Email).
If SMTP isn't configured (local dev), messages are printed to the server log so
the magic-link flow and alerts still work without a real mailbox.
"""
import asyncio
import smtplib
import ssl
from email.message import EmailMessage
from .config import settings
def _send_sync(to: str, subject: str, html: str):
msg = EmailMessage()
msg["From"] = settings.email_from
msg["To"] = to
msg["Subject"] = subject
msg.set_content("This message requires an HTML-capable email client.")
msg.add_alternative(html, subtype="html")
if settings.smtp_port == 465:
with smtplib.SMTP_SSL(settings.smtp_host, settings.smtp_port,
context=ssl.create_default_context(), timeout=20) as s:
s.login(settings.smtp_user, settings.smtp_password)
s.send_message(msg)
else:
with smtplib.SMTP(settings.smtp_host, settings.smtp_port, timeout=20) as s:
s.starttls(context=ssl.create_default_context())
s.login(settings.smtp_user, settings.smtp_password)
s.send_message(msg)
async def send_email(to: str, subject: str, html: str):
"""Send an email (async wrapper). Logs instead of sending if SMTP is unset."""
if not settings.smtp_configured:
print(f"✉️ [DEV email → {to}] {subject}")
return
try:
await asyncio.to_thread(_send_sync, to, subject, html)
except Exception as e:
print(f"⚠️ Failed to send email to {to}: {e}")
async def send_magic_link_email(email: str, link: str):
if not settings.smtp_configured:
print(f"✉️ [DEV magic link] {email} -> {link}")
return
html = f"""
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
<h2>Sign in to OpenShorts</h2>
<p>Click the button below to sign in. This link expires in 15 minutes.</p>
<p><a href="{link}" style="display:inline-block;background:#111;color:#fff;
padding:12px 20px;border-radius:8px;text-decoration:none">Sign in</a></p>
<p style="color:#666;font-size:13px">If you didn't request this, ignore this email.</p>
</div>
"""
await send_email(email, "Your OpenShorts sign-in link", html)

25
cloud/managed_keys.py Normal file
View file

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

306
cloud/metering.py Normal file
View file

@ -0,0 +1,306 @@
"""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 config, 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).
Uses the same residential proxy + anti-bot extractor args as the actual
download (main.py), so the metadata probe doesn't get IP-blocked on the
server before we even reach the download step. Metadata only — negligible
bandwidth. Raises ValueError if the duration is unknown (e.g. live streams).
"""
import yt_dlp
# SSRF guard: reject non-http(s) / private / metadata hosts before probing.
from security_utils import assert_public_url
assert_public_url(url)
bgutil_http = os.environ.get("BGUTIL_BASE_URL", "").strip()
bgutil_script = os.environ.get("BGUTIL_SCRIPT_PATH", "").strip()
proxy = os.environ.get("PROXY_URL", "").strip()
conservative = {"youtube": {"player_client": ["tv_embed", "android", "mweb", "web"],
"player_skip": ["webpage", "configs"]}}
# Try the bgutil/HD extractor first (http or baked-in script), then the
# conservative one — mirrors the download's HD→fallback logic.
if bgutil_http:
hd = [{"youtubepot-bgutilhttp": {"base_url": [bgutil_http]}}]
elif bgutil_script:
hd = [{"youtubepot-bgutilscript": {"script_path": [bgutil_script]}}]
else:
hd = []
strategies = hd + [conservative]
last_err = None
for extractor_args in strategies:
opts = {"skip_download": True, "quiet": True, "no_warnings": True,
"extractor_args": extractor_args}
if proxy:
opts["proxy"] = proxy
try:
with yt_dlp.YoutubeDL(opts) as ydl:
info = ydl.extract_info(url, download=False)
duration = info.get("duration")
if duration:
return float(duration) / 60.0
last_err = ValueError("no duration in metadata")
except Exception as e:
last_err = e
raise ValueError(f"Could not determine video duration ({last_err})")
# --------------------------------------------------------------------------- #
# 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)
# During the trial, cap the allowance so a cancel-before-charge account can't
# burn a whole plan's worth of managed minutes. Full allowance once active.
if sub and sub.status == "trialing":
plan_allowance = min(plan_allowance, _D(config.TRIAL_MINUTE_CAP))
period_end = sub.current_period_end if sub else None
plan_used = await _plan_used_this_period(session, user_id, period_end) if sub else _D(0)
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())

118
cloud/models.py Normal file
View file

@ -0,0 +1,118 @@
"""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 UserVideo(Base):
__tablename__ = "user_videos"
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)
job_id = Column(Text, nullable=False)
clip_index = Column(Integer, nullable=True)
r2_key = Column(Text, nullable=False)
title = Column(Text, nullable=True)
size_bytes = Column(Integer, nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
class StripeEvent(Base):
__tablename__ = "stripe_events"
id = Column(Text, primary_key=True) # Stripe event.id — dedupe key
type = Column(Text, nullable=True)
created = Column(DateTime(timezone=True), nullable=True)
processed_at = Column(DateTime(timezone=True), server_default=func.now())

93
cloud/oauth.py Normal file
View file

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

102
cloud/social_profiles.py Normal file
View file

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

66
cloud/storage.py Normal file
View file

@ -0,0 +1,66 @@
"""Cloudflare R2 (S3-compatible) storage for the users' durable video library.
Layout: users/<user_id>/<job_id>/<filename>. Presigned URLs give private,
time-limited view/download links. Delete-by-prefix wipes a user's whole library
when their subscription's grace period ends.
"""
import boto3
from botocore.config import Config
from .config import settings
_client = None
def client():
global _client
if _client is None:
_client = boto3.client(
"s3",
endpoint_url=settings.r2_endpoint,
aws_access_key_id=settings.r2_access_key_id,
aws_secret_access_key=settings.r2_secret_access_key,
region_name="auto",
config=Config(signature_version="s3v4", retries={"max_attempts": 3}),
)
return _client
def user_prefix(user_id) -> str:
return f"users/{user_id}/"
def job_key(user_id, job_id, filename) -> str:
return f"users/{user_id}/{job_id}/{filename}"
def upload_file(local_path, key, content_type="video/mp4"):
client().upload_file(local_path, settings.r2_bucket, key,
ExtraArgs={"ContentType": content_type})
def presigned_get(key, expires=3600, download_name=None) -> str:
params = {"Bucket": settings.r2_bucket, "Key": key}
if download_name:
params["ResponseContentDisposition"] = f'attachment; filename="{download_name}"'
return client().generate_presigned_url("get_object", Params=params, ExpiresIn=expires)
def delete_prefix(prefix) -> int:
"""Delete every object under a prefix. Returns the count deleted."""
c = client()
deleted = 0
token = None
while True:
kw = {"Bucket": settings.r2_bucket, "Prefix": prefix, "MaxKeys": 1000}
if token:
kw["ContinuationToken"] = token
resp = c.list_objects_v2(**kw)
objs = [{"Key": o["Key"]} for o in resp.get("Contents", [])]
if objs:
c.delete_objects(Bucket=settings.r2_bucket, Delete={"Objects": objs})
deleted += len(objs)
if not resp.get("IsTruncated"):
break
token = resp.get("NextContinuationToken")
return deleted

121
cloud/videos.py Normal file
View file

@ -0,0 +1,121 @@
"""Users' durable video library on R2: archive on completion, list for history,
purge after the subscription grace period.
"""
import asyncio
import os
from datetime import timedelta
from fastapi import APIRouter, Request
from sqlalchemy import select, delete
from .config import settings, VIDEO_RETENTION_GRACE_DAYS
from . import database, storage
from .models import UserVideo, Subscription
from .auth import get_current_user_required
router = APIRouter()
async def archive_job(user_id, job_id, clips, output_dir):
"""Upload a completed managed job's clips to R2 and record them for history."""
if not settings.r2_configured or not clips:
return
rows = []
for i, clip in enumerate(clips):
video_url = clip.get("video_url") or ""
filename = video_url.split("/")[-1]
if not filename:
continue
local_path = os.path.join(output_dir, filename)
if not os.path.exists(local_path):
continue
key = storage.job_key(user_id, job_id, filename)
try:
await asyncio.to_thread(storage.upload_file, local_path, key)
except Exception as e:
print(f"⚠️ R2 upload failed for {key}: {e}")
continue
rows.append(UserVideo(
user_id=user_id, job_id=job_id, clip_index=i, r2_key=key,
title=clip.get("title") or "Short",
size_bytes=os.path.getsize(local_path),
))
if rows:
async with database.session() as s:
async with s.begin():
s.add_all(rows)
print(f"☁️ Archived {len(rows)} clip(s) to R2 for user {user_id}.")
@router.get("/api/history")
async def history(request: Request):
"""List the signed-in user's saved videos with private, time-limited links."""
user = await get_current_user_required(request)
async with database.session() as s:
vids = list((await s.execute(
select(UserVideo).where(UserVideo.user_id == user.id)
.order_by(UserVideo.created_at.desc()).limit(500)
)).scalars())
items = []
for v in vids:
safe_name = (v.title or "short").strip().replace("/", "-")[:60] + ".mp4"
items.append({
"id": str(v.id),
"job_id": v.job_id,
"title": v.title,
"created_at": v.created_at.isoformat() if v.created_at else None,
"size_bytes": v.size_bytes,
"view_url": storage.presigned_get(v.r2_key, expires=3600),
"download_url": storage.presigned_get(v.r2_key, expires=3600, download_name=safe_name),
})
return {"videos": items}
async def purge_expired():
"""Delete R2 videos for users whose subscription ended > grace-period days ago."""
async with database.session() as s:
# Users with a canceled subscription past the grace period, who still have videos.
canceled = list((await s.execute(
select(Subscription.user_id, Subscription.last_event_at)
.where(Subscription.status == "canceled")
)).all())
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
for user_id, last_event_at in canceled:
if not last_event_at:
continue
if last_event_at + timedelta(days=VIDEO_RETENTION_GRACE_DAYS) > now:
continue
# Any videos left?
async with database.session() as s:
has = (await s.execute(
select(UserVideo.id).where(UserVideo.user_id == user_id).limit(1)
)).first()
if not has:
continue
try:
n = await asyncio.to_thread(storage.delete_prefix, storage.user_prefix(user_id))
async with database.session() as s:
async with s.begin():
await s.execute(delete(UserVideo).where(UserVideo.user_id == user_id))
print(f"🗑️ Purged {n} R2 object(s) for lapsed user {user_id}.")
except Exception as e:
print(f"⚠️ Video purge failed for {user_id}: {e}")
_SWEEP_INTERVAL = 6 * 3600 # every 6 hours
async def _sweeper_loop():
while True:
try:
await asyncio.sleep(_SWEEP_INTERVAL)
await purge_expired()
except asyncio.CancelledError:
break
except Exception as e:
print(f"⚠️ Video retention sweeper error: {e}")
def start_sweeper():
asyncio.create_task(_sweeper_loop())

View file

@ -1,13 +1,31 @@
FROM node:18-alpine
# Multi-stage: `dev` for local docker-compose (HMR), `prod` for Coolify/production.
# The prod stage is last, so `docker build` (and Coolify) produce the static build
# by default. Local docker-compose targets the `dev` stage explicitly.
# ---- deps + dev server (local) ----
FROM node:18-alpine AS dev
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm install
COPY . .
EXPOSE 5173
CMD ["npm", "run", "dev", "--", "--host"]
# ---- production build ----
FROM node:18-alpine AS build
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm install
COPY . .
# Vite bakes env at BUILD time. Set VITE_API_URL to the backend's public URL
# (Coolify: add it as a build variable on the frontend service). Empty = same-origin.
ARG VITE_API_URL=""
ENV VITE_API_URL=$VITE_API_URL
RUN npm run build
# ---- static serving (nginx) ----
FROM nginx:alpine AS prod
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

22
dashboard/nginx.conf Normal file
View file

@ -0,0 +1,22 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
# Cache hashed assets aggressively; never cache index.html.
location /assets/ {
expires 1y;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
# SPA: serve index.html for any route (hash routing / deep links).
location / {
try_files $uri $uri/ /index.html;
}
# Basic security headers.
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
}

View file

@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react';
import { Upload, FileVideo, Sparkles, Youtube, Instagram, Share2, LogOut, ChevronDown, Check, Activity, LayoutDashboard, Settings, PlusCircle, History, Menu, X, Terminal, Shield, LayoutGrid, Image, Globe, RotateCcw, Calendar, AlertTriangle, KeyRound, Bot, Users, Smartphone, ExternalLink, Copy, CheckCircle2 } from 'lucide-react';
import { Upload, FileVideo, Sparkles, Youtube, Instagram, Share2, LogOut, ChevronDown, Check, Activity, LayoutDashboard, Settings, PlusCircle, History, Menu, X, Terminal, Shield, LayoutGrid, Image, Globe, RotateCcw, Calendar, AlertTriangle, KeyRound, Bot, Users, Smartphone, ExternalLink, Copy, CheckCircle2, Mail } from 'lucide-react';
import KeyInput from './components/KeyInput';
import MediaInput from './components/MediaInput';
import ResultCard from './components/ResultCard';
@ -9,6 +9,16 @@ 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 TrialUpgradeModal from './components/TrialUpgradeModal';
import LoginModal from './components/LoginModal';
import TrialGate from './components/TrialGate';
import AdvancedBanner from './components/AdvancedBanner';
import HistoryTab from './components/HistoryTab';
import ProfileMenu from './components/ProfileMenu';
import { useAuth } from './contexts/AuthContext';
import { apiFetch, apiJson, QuotaError } from './lib/api';
import { getApiUrl } from './config';
// Enhanced "Encryption" using XOR + Base64 with a Salt
@ -128,12 +138,19 @@ const SESSION_MAX_AGE = 3600000; // 1 hour (matches server job retention)
// Mock polling function
const pollJob = async (jobId) => {
const res = await fetch(getApiUrl(`/api/status/${jobId}`));
const res = await apiFetch(`/api/status/${jobId}`);
if (!res.ok) throw new Error('Status check failed');
return res.json();
};
function App() {
// Cloud auth/billing session (inert when billing is disabled).
const { billingEnabled, isManaged, isSignedIn, signingIn, me, plan, refreshMe } = useAuth();
const [showLogin, setShowLogin] = useState(false);
const [showTopUp, setShowTopUp] = useState(false);
const [showTrialUpgrade, setShowTrialUpgrade] = 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 +337,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 +375,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 +389,25 @@ 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');
// Trial users hit the trial minute cap → prompt them to activate the plan
// now (unlocks full minutes). Active users → offer a top-up.
if (me?.status === 'trialing') {
setShowTrialUpgrade(true);
} else {
setTopUpInfo({ required: e.minutesRequired, remaining: e.minutesRemaining });
setShowTopUp(true);
}
return;
}
setStatus('error');
setLogs(l => [...l, `Error starting job: ${e.message}`]);
}
@ -421,6 +474,16 @@ function App() {
<span className="font-medium hidden lg:block">YouTube Studio</span>
</button>
{billingEnabled && isSignedIn && (
<button
onClick={() => setActiveTab('history')}
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'history' ? 'bg-primary/10 text-primary' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
>
<History size={20} />
<span className="font-medium hidden lg:block">History</span>
</button>
)}
{/* <button
onClick={() => setActiveTab('gallery')}
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'gallery' ? 'bg-primary/10 text-primary' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
@ -466,6 +529,32 @@ function App() {
<p className="text-[10px] text-zinc-400 group-hover:text-zinc-300 transition-colors truncate">Free & Community Driven</p>
</div>
</a>
{billingEnabled && (
<a
href="#/pricing"
className="flex items-center gap-2 p-3 bg-white/5 hover:bg-white/10 rounded-xl transition-colors group"
>
<div className="w-8 h-8 rounded-full bg-primary/20 text-primary flex items-center justify-center shrink-0">
<Sparkles size={16} />
</div>
<div className="hidden lg:block overflow-hidden">
<p className="text-sm font-bold text-white leading-none mb-0.5">Plans &amp; Pricing</p>
<p className="text-[10px] text-zinc-400 group-hover:text-zinc-300 transition-colors truncate">View all plans</p>
</div>
</a>
)}
<a
href="mailto:info@openshorts.app"
className="flex items-center gap-2 p-3 bg-white/5 hover:bg-white/10 rounded-xl transition-colors group"
>
<div className="w-8 h-8 rounded-full bg-primary/20 text-primary flex items-center justify-center shrink-0">
<Mail size={16} />
</div>
<div className="hidden lg:block overflow-hidden">
<p className="text-sm font-bold text-white leading-none mb-0.5">Support</p>
<p className="text-[10px] text-zinc-400 group-hover:text-zinc-300 transition-colors truncate">info@openshorts.app</p>
</div>
</a>
</div>
</div>
);
@ -503,11 +592,29 @@ function App() {
/>
)}
{(!apiKey || !uploadPostKey) && (
{/* Cloud: minutes meter + account/sign-in */}
{billingEnabled && isManaged && (
<UsageMeter onClick={() => { window.location.hash = '#/account'; }} />
)}
{billingEnabled && isSignedIn && !isManaged && (
<button onClick={() => { window.location.hash = '#/pricing'; }}
className="text-xs text-primary bg-primary/10 hover:bg-primary/20 px-3 py-1 rounded-full border border-primary/30 transition-colors">
Start free trial
</button>
)}
{billingEnabled && !isSignedIn && (
<button onClick={() => setShowLogin(true)}
className="text-xs bg-white/10 hover:bg-white/20 px-3 py-1 rounded-full transition-colors">
Sign in
</button>
)}
{billingEnabled && isSignedIn && <ProfileMenu />}
{keysMissing && (
<button
onClick={() => setActiveTab('settings')}
onClick={() => (billingEnabled && !isSignedIn ? setShowLogin(true) : setActiveTab('settings'))}
className="text-xs text-amber-400 bg-amber-500/10 hover:bg-amber-500/20 px-3 py-1 rounded-full border border-amber-500/30 transition-colors flex items-center gap-1.5"
title="Click to configure your API keys"
title="Configure API keys or choose a plan"
>
<AlertTriangle size={12} />
{!apiKey && !uploadPostKey
@ -521,7 +628,7 @@ function App() {
</header>
{/* Persistent Missing Keys Banner — visible on every screen */}
{(!apiKey || !uploadPostKey) && activeTab !== 'settings' && (
{keysMissing && activeTab !== 'settings' && (
<div className="mx-6 mt-3 p-3 bg-amber-500/10 border border-amber-500/30 rounded-xl flex items-center justify-between gap-4 shrink-0 animate-[fadeIn_0.3s_ease-out]">
<div className="flex items-center gap-3 text-sm text-amber-200">
<KeyRound size={16} className="shrink-0 text-amber-400" />
@ -559,6 +666,12 @@ function App() {
</div>
)}
{/* Included tools (Clip Generator, YouTube Studio): non-blocking trial prompt. */}
{gateThisTab && <TrialGate toolName={TOOL_NAMES[activeTab] || 'this'} />}
{/* Advanced tools (AI Shorts, AI Agent): BYOK fal.ai + ElevenLabs notice. */}
{advancedThisTab && <AdvancedBanner needsPlan={needsPlan} onKeys={() => setActiveTab('settings')} />}
{/* Main Workspace */}
<div className="flex-1 overflow-hidden relative">
@ -571,6 +684,36 @@ function App() {
<Shield size={12} /> Privacy: keys only live in your browser (sent to backend just to process)
</div>
</div>
{isManaged ? (
<div className="glass-panel p-6 mb-2">
<div className="flex items-center justify-between mb-3">
<h2 className="text-lg font-semibold">Included in your plan</h2>
<span className="text-[10px] bg-green-500/10 border border-green-500/30 px-2 py-0.5 rounded text-green-400 uppercase tracking-wider">Managed</span>
</div>
<p className="text-xs text-zinc-500 mb-5 leading-relaxed">
Your plan includes the <strong>Clip Generator</strong> and <strong>YouTube Studio</strong>,
fully managed — no API keys required. AI Shorts &amp; dubbing use your own fal.ai / ElevenLabs
keys (below). Connect your social accounts to publish directly.
</p>
<button onClick={handleConnectSocials} className="btn-primary py-2 px-4 text-sm flex items-center gap-2">
<Share2 size={16} /> Connect social accounts
</button>
</div>
) : billingEnabled ? (
<div className="glass-panel p-6 mb-2 border-primary/30 ring-1 ring-primary/20">
<div className="flex items-center justify-between mb-3">
<h2 className="text-lg font-semibold">Start your free trial</h2>
<span className="text-[10px] bg-primary/10 border border-primary/30 px-2 py-0.5 rounded text-primary uppercase tracking-wider">3 days free</span>
</div>
<p className="text-xs text-zinc-500 mb-5 leading-relaxed">
Generate shorts with zero setup — no API keys needed. 3 days free, then from $12/mo. Cancel anytime.
</p>
<button onClick={() => { window.location.hash = '#/pricing'; }} className="btn-primary py-2 px-4 text-sm flex items-center gap-2">
<Sparkles size={16} /> See plans & start trial
</button>
</div>
) : (
<>
<KeyInput onKeySet={setApiKey} savedKey={apiKey} />
<div className={`glass-panel p-6 mt-8 ${!uploadPostKey ? 'border-amber-500/30 ring-1 ring-amber-500/20' : ''}`}>
@ -620,14 +763,17 @@ function App() {
</div>
</div>
</>
)}
<div className="glass-panel p-6 mt-8">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold">Video Translation</h2>
<span className="text-[10px] bg-white/5 border border-white/5 px-2 py-0.5 rounded text-zinc-500 uppercase tracking-wider">Optional</span>
<span className="text-[10px] bg-amber-500/10 border border-amber-500/30 px-2 py-0.5 rounded text-amber-400 uppercase tracking-wider">Your own key</span>
</div>
<p className="text-xs text-zinc-500 mb-6 leading-relaxed">
Translate your clips to different languages using <strong>ElevenLabs</strong> AI dubbing.
Automatically translates speech while preserving the original voice characteristics.
For <strong>AI Shorts &amp; dubbing</strong> — bring your own key. Translate your clips to different
languages using <strong>ElevenLabs</strong> AI dubbing (billed by ElevenLabs). Not covered by your plan.
</p>
<div className="space-y-4">
<label className="block text-sm text-zinc-400">ElevenLabs API Key</label>
@ -674,11 +820,12 @@ function App() {
<div className="glass-panel p-6 mt-8">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold">AI Shorts (UGC Videos)</h2>
<span className="text-[10px] bg-violet-500/10 border border-violet-500/20 px-2 py-0.5 rounded text-violet-400 uppercase tracking-wider">New</span>
<span className="text-[10px] bg-amber-500/10 border border-amber-500/30 px-2 py-0.5 rounded text-amber-400 uppercase tracking-wider">Your own key</span>
</div>
<p className="text-xs text-zinc-500 mb-6 leading-relaxed">
Generate UGC-style videos with AI actors for any product or business using <strong>fal.ai</strong>.
Just describe your product or paste a URL. Requires fal.ai + ElevenLabs API keys.
<strong> Not covered by your plan</strong> — bring your own fal.ai + ElevenLabs keys (billed by those
providers, ~$0.65-2 per video). Your plan still covers the AI script &amp; orchestration.
</p>
<div className="space-y-4">
<label className="block text-sm text-zinc-400">fal.ai API Key</label>
@ -726,7 +873,7 @@ function App() {
{/* View: SaaS Shorts */}
{activeTab === 'saasshorts' && (
<SaaShortsTab geminiApiKey={apiKey} elevenLabsKey={elevenLabsKey} falKey={falKey} uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} />
<SaaShortsTab geminiApiKey={apiKey} elevenLabsKey={elevenLabsKey} falKey={falKey} uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} managed={isManaged} />
)}
{/* View: AI Agent */}
@ -851,8 +998,10 @@ function App() {
)}
{/* View: Thumbnails */}
{activeTab === 'history' && <HistoryTab />}
{activeTab === 'thumbnails' && (
<ThumbnailStudio geminiApiKey={apiKey} uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} />
<ThumbnailStudio geminiApiKey={apiKey} uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} managed={isManaged} />
)}
{/* View: Gallery */}
@ -1106,6 +1255,22 @@ function App() {
uploadPostKey={uploadPostKey}
uploadUserId={uploadUserId}
/>
{showLogin && <LoginModal onClose={() => setShowLogin(false)} />}
{showTopUp && (
<TopUpModal
onClose={() => setShowTopUp(false)}
required={topUpInfo.required}
remaining={topUpInfo.remaining}
/>
)}
{showTrialUpgrade && (
<TrialUpgradeModal
plan={plan}
onActivated={refreshMe}
onClose={() => setShowTrialUpgrade(false)}
/>
)}
</div>
);
}

View file

@ -1,5 +1,7 @@
import React from 'react';
import { Sparkles, Zap, Globe, FileVideo, Subtitles, Youtube, Instagram, Shield, Github, ArrowRight, Play, Check, ChevronDown, Monitor, Cpu, Languages, Type, Upload, Scissors } from 'lucide-react';
import PricingSection from './components/PricingSection';
import { useAuth } from './contexts/AuthContext';
const TikTokIcon = ({ size = 16, className = "" }) => (
<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" className={className}>
@ -56,6 +58,7 @@ const FAQItem = ({ question, answer, isOpen, onClick }) => (
);
export default function Landing({ onLaunchApp }) {
const { billingEnabled } = useAuth();
const [openFaq, setOpenFaq] = React.useState(null);
const features = [
@ -136,7 +139,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?",
@ -199,6 +202,7 @@ export default function Landing({ onLaunchApp }) {
<div className="hidden md:flex items-center gap-8 text-sm text-zinc-400">
<a href="#features" className="hover:text-white transition-colors">Features</a>
<a href="#how-it-works" className="hover:text-white transition-colors">How It Works</a>
{billingEnabled && <a href="#pricing" className="hover:text-white transition-colors">Pricing</a>}
<a href="#comparison" className="hover:text-white transition-colors">Comparison</a>
<a href="#faq" className="hover:text-white transition-colors">FAQ</a>
</div>
@ -259,6 +263,11 @@ export default function Landing({ onLaunchApp }) {
</a>
</div>
<p className="text-sm text-zinc-500 mb-12">
<strong className="text-zinc-300">Free to self-host</strong> with Docker (bring your own keys) ·
or use it here with no setup — <strong className="text-zinc-300">3-day free trial, then from $12/mo</strong>
</p>
{/* Platform Icons */}
<div className="flex items-center justify-center gap-6 text-zinc-500">
<span className="text-sm">Export to:</span>
@ -302,6 +311,63 @@ export default function Landing({ onLaunchApp }) {
</div>
</section>
{/* Two ways to use it: free self-host vs paid hosted */}
<section className="py-16 px-6">
<div className="max-w-4xl mx-auto text-center mb-10">
<h2 className="text-3xl md:text-4xl font-bold mb-3">Two ways to use OpenShorts</h2>
<p className="text-zinc-400 max-w-2xl mx-auto">Run it yourself for free, or let us run everything for you.</p>
</div>
<div className="max-w-4xl mx-auto grid md:grid-cols-2 gap-6">
<div className="bg-surface/50 border border-white/10 rounded-2xl p-8 flex flex-col">
<div className="flex items-center gap-2 mb-2">
<Github size={20} className="text-zinc-300" />
<h3 className="text-xl font-bold text-white">Self-hosted</h3>
<span className="text-[10px] bg-green-500/10 border border-green-500/30 px-2 py-0.5 rounded text-green-400 uppercase tracking-wider">Free</span>
</div>
<p className="text-zinc-400 text-sm leading-relaxed mb-5 flex-1">
100% free and open source. Run it with Docker on your own machine, bring your own API keys,
no limits, no subscription. Best if you're technical and want full control.
</p>
<a href="https://github.com/mutonby/openshorts" target="_blank" rel="noopener noreferrer"
className="inline-flex items-center justify-center gap-2 bg-white/10 hover:bg-white/20 text-white px-5 py-3 rounded-xl font-medium transition-all">
<Github size={18} /> Get it on GitHub
</a>
</div>
<div className="bg-primary/5 border border-primary/30 rounded-2xl p-8 flex flex-col">
<div className="flex items-center gap-2 mb-2">
<Sparkles size={20} className="text-primary" />
<h3 className="text-xl font-bold text-white">Hosted on openshorts.app</h3>
<span className="text-[10px] bg-primary/10 border border-primary/30 px-2 py-0.5 rounded text-primary uppercase tracking-wider">From $12/mo</span>
</div>
<p className="text-zinc-400 text-sm leading-relaxed mb-5 flex-1">
Zero setup, no API keys — we run all the AI and compute for you, and every clip you make is saved
to your private library. Sign in with email or Google. <b>3-day free trial</b>, then a plan from
$12/mo (100 min). Best if you just want to make clips without any technical hassle.
</p>
<a href="#pricing"
className="inline-flex items-center justify-center gap-2 bg-primary hover:bg-blue-600 text-white px-5 py-3 rounded-xl font-medium transition-all">
See plans <ArrowRight size={18} />
</a>
</div>
</div>
</section>
{/* Pricing Section — hosted plans (self-host stays free) */}
{billingEnabled && (
<section id="pricing" className="py-20 px-6 bg-surface/20">
<div className="max-w-6xl mx-auto">
<div className="text-center mb-12">
<h2 className="text-3xl md:text-4xl font-bold mb-4">Simple, transparent pricing</h2>
<p className="text-zinc-400 max-w-2xl mx-auto">
Same features on every plan — you only pay for volume. Start with a 3-day free trial (card required,
20 free minutes), cancel anytime. Prefer to self-host? It stays free forever.
</p>
</div>
<PricingSection onRequireLogin={() => { window.location.hash = '#/pricing'; }} />
</div>
</section>
)}
{/* 3 Tools in 1 Section */}
<section className="py-20 px-6">
<div className="max-w-6xl mx-auto">

View file

@ -1,8 +1,9 @@
import React from 'react';
import { ArrowLeft } from 'lucide-react';
const LAST_UPDATED = '2026-05-06';
const LAST_UPDATED = '2026-07-15';
const ISSUES_URL = 'https://github.com/mutonby/openshorts/issues';
const SUPPORT_EMAIL = 'info@openshorts.app';
function Section({ title, children }) {
return (
@ -37,25 +38,81 @@ export default function Legal() {
<Section title="The short version">
<p>
OpenShorts is a free, open-source AI clip generator. There are no accounts, no payments, and we
do not persistently store the videos you upload or the clips we generate. By using the Service
you agree to the points below.
OpenShorts is an AI clip generator. There are two ways to use it:
</p>
<ul className="list-disc pl-6 space-y-1">
<li>
<strong className="text-white">Self-hosted (free):</strong> the open-source software, run on
your own machine with your own API keys. No account, no payment, no data held by us.
</li>
<li>
<strong className="text-white">Hosted at openshorts.app (paid):</strong> we run everything for
you. It requires an account and a paid subscription (with a free trial), and we store the
videos you generate while your subscription is active.
</li>
</ul>
<p>By using the hosted Service you agree to the terms below.</p>
</Section>
<Section title="Accounts & sign-in">
<p>
The hosted Service requires an account. You can sign in with a magic link sent to your email or
with Google. We store your email address to operate your account and authenticate you. You are
responsible for keeping access to your inbox / Google account secure.
</p>
</Section>
<Section title="Service is provided as-is">
<Section title="Free trial, plans & billing">
<p>
The Service is offered for free, on a best-effort basis, with no warranties of any kind and no
guarantee of uptime, accuracy, or fitness for any particular purpose. To the maximum extent
permitted by law, we are not liable for any damages arising from your use of the Service.
Paid plans are <strong className="text-white">Starter ($12/mo · 100 min)</strong>,{' '}
<strong className="text-white">Creator ($29/mo · 300 min)</strong> and{' '}
<strong className="text-white">Pro ($59/mo · 750 min)</strong>, each also available annually (two
months free). "Minutes" are minutes of input video processed per billing period; additional
minutes can be bought as one-off top-ups.
</p>
<p>
<strong className="text-white">Free trial:</strong> new subscriptions start with a{' '}
<strong className="text-white">3-day free trial</strong> that includes up to{' '}
<strong className="text-white">20 minutes</strong> of video processing. You provide a payment
method up front but are <strong className="text-white">not charged during the trial</strong>. If
you do not cancel before the trial ends, your subscription automatically begins, your full plan
minutes unlock, and your payment method is charged the plan price. You can cancel at any time from
your account.
</p>
<p>
<strong className="text-white">Auto-renewal:</strong> subscriptions renew automatically each
period (monthly or yearly) at the then-current price until you cancel. We'll email a reminder
before the trial converts to a paid subscription.
</p>
<p>
Payments are processed by <strong className="text-white">Stripe</strong>. We never see or store
your full card details. Prices are in USD and exclude any applicable taxes/VAT, which are added
at checkout where required.
</p>
</Section>
<Section title="Cancellation & refunds">
<p>
You can cancel anytime from your account (or Stripe's billing portal). On cancellation your plan
stays active until the end of the current paid period; we do not charge you again after that.
</p>
<p>
Except where required by law, payments are <strong className="text-white">non-refundable</strong>{' '}
and we do not prorate partial periods. To avoid being charged for a period you don't want, cancel
before it renews (and, for the trial, before it ends).
</p>
<p>
<strong className="text-white">EU/EEA consumers:</strong> the Service is digital content/services
supplied immediately. By starting to use it (including during the trial) you request immediate
performance and acknowledge that you lose the 14-day right of withdrawal once performance has
begun, to the extent permitted by law.
</p>
</Section>
<Section title="You are responsible for what you upload">
<p>
Before processing a video, you must affirmatively confirm — via the checkbox in the upload
interface — that you own the content or have the rights to process it. By doing so you
represent and warrant that:
Before processing a video you must confirm — via the checkbox in the upload interface — that you
own the content or have the rights to process it. By doing so you represent and warrant that:
</p>
<ul className="list-disc pl-6 space-y-1">
<li>You own all rights to the content, or have a valid license or permission to process it;</li>
@ -63,56 +120,74 @@ export default function Legal() {
<li>The content is not unlawful, defamatory, or otherwise prohibited.</li>
</ul>
<p>
If you submit content you do not have rights to, that is your responsibility, not ours. You
agree to indemnify OpenShorts and its contributors against any third-party claim arising from
content you submitted.
If you submit content you do not have rights to, that is your responsibility. You agree to
indemnify OpenShorts and its contributors against any third-party claim arising from content you
submitted. We may suspend or terminate accounts that abuse the Service or infringe others' rights.
</p>
</Section>
<Section title="What we keep, and for how long">
<Section title="What we store, and for how long">
<ul className="list-disc pl-6 space-y-1">
<li>
<strong className="text-white">Uploaded videos and generated clips:</strong> deleted with
their job, typically within 1 hour. Not backed up off-server in our hosted deployment.
<strong className="text-white">Account data:</strong> your email address and your subscription
status and usage (minutes used). Kept while your account exists.
</li>
<li>
<strong className="text-white">Attestation record (IP, user-agent, timestamp, source):</strong>{' '}
kept in memory with the job and discarded when the job is purged (≈1 hour). Used only to
evidence the ownership confirmation in case of a takedown or dispute.
<strong className="text-white">Generated videos:</strong> the clips you create are stored on
Cloudflare R2 and available in your library <strong className="text-white">while your
subscription is active, plus 7 days after it ends</strong>, then permanently deleted.
</li>
<li>
<strong className="text-white">Standard server access logs:</strong> retained up to 30 days
for debugging and abuse prevention.
<strong className="text-white">Uploaded/source files &amp; working data:</strong> deleted from
our processing servers shortly after the job finishes (typically within 1 hour).
</li>
<li>
<strong className="text-white">API keys (Gemini, ElevenLabs, Upload-Post):</strong> stored
encrypted in your browser's <code className="text-zinc-200">localStorage</code>. They are
sent as request headers when a feature needs them, used to call the relevant third party,
and never written to our database or disk.
<strong className="text-white">Billing data:</strong> handled by Stripe; we keep a reference
to your Stripe customer/subscription, not your card.
</li>
<li>
<strong className="text-white">Optional add-on keys (ElevenLabs, fal.ai):</strong> for BYOK
features, stored encrypted in your browser and sent as request headers only when needed —
never written to our database.
</li>
<li>
<strong className="text-white">Server access logs:</strong> retained up to 30 days for
debugging and abuse prevention.
</li>
</ul>
<p>We do not sell, rent, or share your data with third parties for advertising or any unrelated purpose.</p>
</Section>
<Section title="Third-party APIs">
<Section title="Subprocessors">
<p>To provide the hosted Service we share the minimum necessary data with:</p>
<ul className="list-disc pl-6 space-y-1">
<li><strong className="text-white">Stripe</strong> — payments &amp; subscriptions.</li>
<li><strong className="text-white">Cloudflare (R2)</strong> — storage of your generated videos.</li>
<li><strong className="text-white">Google (Gemini)</strong> — AI analysis, titles and thumbnails.</li>
<li><strong className="text-white">Upload-Post</strong> — publishing to TikTok, Instagram &amp; YouTube (when you connect them).</li>
<li><strong className="text-white">A residential-proxy provider</strong> — retrieving videos you submit by link.</li>
<li><strong className="text-white">Namecheap Private Email</strong> — transactional email (sign-in links, notices).</li>
</ul>
<p>Each has its own terms and privacy policy, which apply in addition to this notice.</p>
</Section>
<Section title="Service is provided as-is">
<p>
When you use a feature that requires it, OpenShorts forwards relevant data to the third-party
API for which you provided a key — Google Gemini (AI analysis), ElevenLabs (optional dubbing),
Upload-Post (optional social posting). Those services have their own terms and privacy policies
which apply in addition to this notice.
The Service is provided on a best-effort basis with no warranties of any kind and no guarantee of
uptime, accuracy, or fitness for a particular purpose. To the maximum extent permitted by law, our
aggregate liability is limited to the amount you paid us in the 3 months before the claim, and we
are not liable for indirect or consequential damages. Some third-party sources (e.g. video
platforms) may change how they work and temporarily affect ingestion.
</p>
</Section>
<Section title="Your rights (EU / EEA / UK)">
<p>
Under the GDPR / UK GDPR you have the right to access, rectify, erase, restrict, object to, or
port your personal data. Because we do not hold accounts and job data is purged within an hour,
most requests are auto-satisfied by the retention schedule. For anything else, file a request
via{' '}
<a className="text-primary underline" href={ISSUES_URL} target="_blank" rel="noopener noreferrer">
GitHub Issues
</a>
. You may also lodge a complaint with your local supervisory authority (in Spain: AEPD,{' '}
Under the GDPR / UK GDPR you may access, rectify, erase, restrict, object to, or port your
personal data. You can delete your account and its data — including your video library — by
emailing{' '}
<a className="text-primary underline" href={`mailto:${SUPPORT_EMAIL}`}>{SUPPORT_EMAIL}</a>. You may
also lodge a complaint with your local supervisory authority (in Spain: AEPD,{' '}
<a className="text-primary underline" href="https://www.aepd.es" target="_blank" rel="noopener noreferrer">
aepd.es
</a>
@ -122,36 +197,34 @@ export default function Legal() {
<Section title="Copyright takedowns">
<p>
If you believe content processed through the Service infringes your copyright, open an issue at{' '}
<a className="text-primary underline" href={ISSUES_URL} target="_blank" rel="noopener noreferrer">
{ISSUES_URL}
</a>{' '}
with: identification of the work, identification of the allegedly infringing material (job ID,
URL, or sufficient detail to locate it), your contact information, and a statement that you are
authorized to act on behalf of the rights holder. Note that uploaded content is typically
deleted within 1 hour, so most takedowns are auto-resolved by retention.
If you believe content processed through the Service infringes your copyright, email{' '}
<a className="text-primary underline" href={`mailto:${SUPPORT_EMAIL}`}>{SUPPORT_EMAIL}</a> with:
identification of the work, identification of the allegedly infringing material (enough detail to
locate it), your contact information, and a statement that you are authorized to act for the
rights holder.
</p>
</Section>
<Section title="Self-hosted instances">
<p>
OpenShorts is open source and may be self-hosted. This notice applies only to the hosted
version we operate. Self-hosted instances are operated by their respective administrators, and
their data handling, retention, and policies are their responsibility, not ours.
OpenShorts is open source and may be self-hosted. This notice applies to the hosted version we
operate at openshorts.app. Self-hosted instances are run by their administrators, whose data
handling and policies are their own responsibility, not ours.
</p>
</Section>
<Section title="Changes & contact">
<p>
We may update this notice from time to time; the "Last updated" date above reflects the most
recent revision. Continued use after a change constitutes acceptance. For any other question,
please use{' '}
We may update this notice; the "Last updated" date reflects the latest revision. For material
changes affecting paid subscribers we'll give reasonable notice. Continued use after a change
constitutes acceptance. Questions:{' '}
<a className="text-primary underline" href={`mailto:${SUPPORT_EMAIL}`}>{SUPPORT_EMAIL}</a> or{' '}
<a className="text-primary underline" href={ISSUES_URL} target="_blank" rel="noopener noreferrer">
GitHub Issues
</a>
.
</p>
<p>This notice is governed by the laws of Spain.</p>
<p>These terms are governed by the laws of Spain.</p>
</Section>
</main>
</div>

View file

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

View file

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

View file

@ -0,0 +1,61 @@
import React, { useState, useEffect } from 'react';
import { Loader2, Download, History as HistoryIcon, Film } from 'lucide-react';
import { apiJson } from '../lib/api';
// The signed-in user's saved video library (stored in R2). Private, signed links.
export default function HistoryTab() {
const [videos, setVideos] = useState(null);
const [error, setError] = useState('');
useEffect(() => {
apiJson('/api/history')
.then((d) => setVideos(d.videos || []))
.catch(() => setError('Could not load your library.'));
}, []);
const fmtDate = (iso) => (iso ? new Date(iso).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }) : '');
if (videos === null && !error) {
return <div className="flex justify-center py-20"><Loader2 className="animate-spin text-primary" /></div>;
}
return (
<div className="h-full overflow-y-auto p-8 max-w-5xl mx-auto animate-[fadeIn_0.3s_ease-out]">
<div className="flex items-center gap-3 mb-2">
<HistoryIcon className="text-primary" />
<h1 className="text-2xl font-bold">Your library</h1>
</div>
<p className="text-zinc-400 text-sm mb-8">
All the shorts you've generated, saved while your plan is active. Kept for 7 days after your plan ends.
</p>
{error && <p className="text-red-400 text-sm">{error}</p>}
{videos && videos.length === 0 && (
<div className="text-center py-20 text-zinc-500">
<Film size={40} className="mx-auto mb-4 opacity-50" />
<p>No videos yet. Generate your first short from the Clip Generator.</p>
</div>
)}
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-5">
{(videos || []).map((v) => (
<div key={v.id} className="bg-surface border border-white/10 rounded-xl overflow-hidden group">
<div className="aspect-[9/16] bg-black">
<video src={v.view_url} controls preload="metadata" className="w-full h-full object-contain" />
</div>
<div className="p-3">
<p className="text-sm font-medium line-clamp-2 mb-1" title={v.title}>{v.title || 'Short'}</p>
<div className="flex items-center justify-between">
<span className="text-[11px] text-zinc-500">{fmtDate(v.created_at)}</span>
<a href={v.download_url} className="text-primary hover:text-blue-400 flex items-center gap-1 text-xs" title="Download">
<Download size={14} /> Download
</a>
</div>
</div>
</div>
))}
</div>
</div>
);
}

View file

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

View file

@ -1,13 +1,30 @@
import React, { useState, useEffect } from 'react';
import { Youtube, Upload, FileVideo, X } from 'lucide-react';
import React, { useState, useEffect, useRef } from 'react';
import { Link2, Upload, FileVideo, X, Info } from 'lucide-react';
import { getApiUrl } from '../config';
const SUPPORTED_PLATFORMS = [
'YouTube', 'Vimeo', 'TikTok', 'X / Twitter', 'Twitch',
'Facebook', 'Instagram', 'Dailymotion', 'Reddit', 'Streamable',
];
export default function MediaInput({ onProcess, isProcessing }) {
const [youtubeUrlEnabled, setYoutubeUrlEnabled] = useState(true);
const [mode, setMode] = useState('url'); // 'url' | 'file'
const [url, setUrl] = useState('');
const [file, setFile] = useState(null);
const [acknowledged, setAcknowledged] = useState(false);
const [showInfo, setShowInfo] = useState(false);
const infoRef = useRef(null);
// Close the compatibility popover on any outside click.
useEffect(() => {
if (!showInfo) return;
const onClick = (e) => {
if (infoRef.current && !infoRef.current.contains(e.target)) setShowInfo(false);
};
document.addEventListener('mousedown', onClick);
return () => document.removeEventListener('mousedown', onClick);
}, [showInfo]);
useEffect(() => {
fetch(getApiUrl('/api/config'))
@ -50,8 +67,8 @@ export default function MediaInput({ onProcess, isProcessing }) {
: 'text-zinc-400 hover:text-white'
}`}
>
<Youtube size={18} />
YouTube URL
<Link2 size={18} />
Video URL
</button>
)}
<button
@ -69,14 +86,41 @@ export default function MediaInput({ onProcess, isProcessing }) {
<form onSubmit={handleSubmit}>
{mode === 'url' ? (
<div className="space-y-4">
<input
type="url"
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="https://www.youtube.com/watch?v=..."
className="input-field"
required
/>
<div className="relative">
<input
type="url"
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="https://... paste a video link"
className="input-field pr-11"
required
/>
<div className="absolute inset-y-0 right-2 flex items-center" ref={infoRef}>
<button
type="button"
onClick={() => setShowInfo((v) => !v)}
aria-label="Supported platforms"
className="p-1.5 text-zinc-500 hover:text-primary transition-colors"
>
<Info size={18} />
</button>
{showInfo && (
<div className="absolute right-0 top-full mt-2 w-64 z-20 bg-surface border border-white/10 rounded-xl shadow-xl p-4 text-left animate-[fadeIn_0.15s_ease-out]">
<p className="text-xs font-semibold text-white mb-2">Paste a link from</p>
<div className="flex flex-wrap gap-1.5">
{SUPPORTED_PLATFORMS.map((p) => (
<span key={p} className="text-[11px] px-2 py-0.5 rounded-full bg-white/5 text-zinc-300 border border-white/5">
{p}
</span>
))}
</div>
<p className="text-[11px] text-zinc-500 mt-2.5 leading-relaxed">
…and 1,000+ more sites. If a link has a public video, we can usually fetch it.
</p>
</div>
)}
</div>
</div>
</div>
) : (
<div

View file

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

View file

@ -0,0 +1,62 @@
import React, { useState, useRef, useEffect } from 'react';
import { User, CreditCard, LogOut, Sparkles } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
// Header avatar + dropdown for signed-in cloud users: shows the email and gives
// access to Account & billing (manage subscription, top-ups) and Sign out.
export default function ProfileMenu() {
const { user, isManaged, logout } = useAuth();
const [open, setOpen] = useState(false);
const ref = useRef(null);
useEffect(() => {
if (!open) return;
const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
document.addEventListener('mousedown', onClick);
return () => document.removeEventListener('mousedown', onClick);
}, [open]);
if (!user) return null;
const initial = (user.email || '?').trim().charAt(0).toUpperCase();
return (
<div className="relative" ref={ref}>
<button
onClick={() => setOpen((v) => !v)}
aria-label="Account menu"
className="w-8 h-8 rounded-full bg-primary/20 border border-primary/30 text-primary flex items-center justify-center text-sm font-semibold hover:bg-primary/30 transition-colors"
>
{initial}
</button>
{open && (
<div className="absolute right-0 top-full mt-2 w-60 z-30 bg-surface border border-white/10 rounded-xl shadow-xl overflow-hidden animate-[fadeIn_0.15s_ease-out]">
<div className="px-4 py-3 border-b border-white/5">
<p className="text-xs text-zinc-500">Signed in as</p>
<p className="text-sm text-white truncate" title={user.email}>{user.email}</p>
</div>
{!isManaged && (
<button
onClick={() => { setOpen(false); window.location.hash = '#/pricing'; }}
className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-primary hover:bg-white/5 transition-colors"
>
<Sparkles size={16} /> Start free trial
</button>
)}
<button
onClick={() => { setOpen(false); window.location.hash = '#/account'; }}
className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-zinc-200 hover:bg-white/5 transition-colors"
>
<CreditCard size={16} /> Account &amp; billing
</button>
<button
onClick={() => { setOpen(false); logout(); }}
className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-zinc-200 hover:bg-white/5 transition-colors border-t border-white/5"
>
<LogOut size={16} /> Sign out
</button>
</div>
)}
</div>
);
}

View file

@ -1,6 +1,7 @@
import React, { useState, useEffect } from 'react';
import { Download, Share2, Instagram, Youtube, Video, CheckCircle, AlertCircle, X, Loader2, Copy, Wand2, Type, Calendar, Clock, Languages } from 'lucide-react';
import { getApiUrl } from '../config';
import { apiFetch } from '../lib/api';
import SubtitleModal from './SubtitleModal';
import HookModal from './HookModal';
import TranslateModal from './TranslateModal';
@ -42,7 +43,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
// Fetch clip duration from transcript endpoint
useEffect(() => {
if (!jobId || index === undefined) return;
fetch(getApiUrl(`/api/clip/${jobId}/${index}/transcript`))
apiFetch(`/api/clip/${jobId}/${index}/transcript`)
.then(res => res.ok ? res.json() : null)
.then(data => {
if (data && data.durationSec) setClipDuration(data.durationSec);
@ -72,7 +73,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
}
// Try Remotion effects endpoint first
const effectsRes = await fetch(getApiUrl('/api/effects/generate'), {
const effectsRes = await apiFetch('/api/effects/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@ -104,7 +105,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
}
// Fallback: legacy FFmpeg edit endpoint
const res = await fetch(getApiUrl('/api/edit'), {
const res = await apiFetch('/api/edit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@ -165,7 +166,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
}
// Fallback: legacy FFmpeg
const res = await fetch(getApiUrl('/api/subtitle'), {
const res = await apiFetch('/api/subtitle', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@ -224,7 +225,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
? { text: hookData, position: 'top', size: 'M' }
: hookData;
const res = await fetch(getApiUrl('/api/hook'), {
const res = await apiFetch('/api/hook', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@ -273,7 +274,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
console.log('[Translate] Request body:', requestBody);
console.log('[Translate] Sending request to /api/translate');
const res = await fetch(getApiUrl('/api/translate'), {
const res = await apiFetch('/api/translate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@ -353,7 +354,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
}
const res = await fetch(getApiUrl('/api/social/post'), {
const res = await apiFetch('/api/social/post', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)

View file

@ -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();
@ -139,7 +144,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
if (jobId && genStatus === 'processing') {
interval = setInterval(async () => {
try {
const res = await fetch(getApiUrl(`/api/saasshorts/status/${jobId}`));
const res = await apiFetch(`/api/saasshorts/status/${jobId}`);
if (res.status === 404) {
// Job lost (server restart) — treat as failed so Retry appears
setGenStatus('failed');
@ -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',
@ -1010,7 +1015,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
const formData = new FormData();
formData.append('file', file);
try {
const res = await fetch(getApiUrl('/api/saasshorts/actor-upload'), {
const res = await apiFetch('/api/saasshorts/actor-upload', {
method: 'POST',
body: formData,
});
@ -1073,7 +1078,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
setActorOptions([]);
setSelectedActor(null);
try {
const res = await fetch(getApiUrl('/api/saasshorts/actor-options'), {
const res = await apiFetch('/api/saasshorts/actor-options', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Fal-Key': falKey },
body: JSON.stringify({ actor_description: actorDescription, num_options: 3 }),
@ -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),

View file

@ -1,6 +1,7 @@
import React, { useState, useMemo } from 'react';
import { X, Loader2, Calendar, Clock, CheckCircle, AlertCircle, Video, Instagram, Youtube, ChevronLeft, ChevronRight, Globe, ExternalLink } from 'lucide-react';
import { getApiUrl } from '../config';
import { apiFetch } from '../lib/api';
const DAYS = ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'];
const MONTHS = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];
@ -134,7 +135,7 @@ export default function ScheduleWeekModal({ isOpen, onClose, clips, jobId, uploa
};
try {
const res = await fetch(getApiUrl('/api/social/post'), {
const res = await apiFetch('/api/social/post', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)

View file

@ -1,6 +1,7 @@
import React, { useState, useEffect } from 'react';
import { X, Type, Loader2 } from 'lucide-react';
import { getApiUrl } from '../config';
import { apiFetch } from '../lib/api';
import RemotionPreview from './RemotionPreview';
const FONT_OPTIONS = [
@ -54,7 +55,7 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
if (!isOpen || !jobId || clipIndex === undefined) return;
setCaptionsLoading(true);
fetch(getApiUrl(`/api/clip/${jobId}/${clipIndex}/transcript`))
apiFetch(`/api/clip/${jobId}/${clipIndex}/transcript`)
.then((res) => res.ok ? res.json() : null)
.then((data) => {
if (data && data.captions && data.captions.length > 0) {

View file

@ -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'
@ -146,7 +151,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
const formData = new FormData();
formData.append('file', file);
const res = await fetch(getApiUrl('/api/thumbnail/upload'), {
const res = await apiFetch('/api/thumbnail/upload', {
method: 'POST',
body: formData
});
@ -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
<StepIndicator currentStep={step} />
{/* Gemini API Key Warning */}
{!geminiApiKey && (
{/* Gemini API Key Warning (self-host BYOK only; managed uses server key) */}
{needsKey && (
<div className="mb-6 p-5 bg-amber-500/10 border border-amber-500/30 rounded-xl flex items-start gap-3">
<AlertCircle size={20} className="text-amber-400 shrink-0 mt-0.5" />
<div>
@ -485,7 +490,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
{/* ===== STEP 0: Input Mode Selection ===== */}
{step === 0 && (
<div className={`grid md:grid-cols-2 gap-6 ${!geminiApiKey ? 'opacity-50 pointer-events-none select-none' : ''}`}>
<div className={`grid md:grid-cols-2 gap-6 ${needsKey ? 'opacity-50 pointer-events-none select-none' : ''}`}>
{/* Mode A: Video Analysis */}
<div className="glass-panel p-6 space-y-4">
<div className="flex items-center gap-3 mb-2">
@ -1058,7 +1063,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
</div>
{/* Publish Button */}
{(!uploadPostKey || !uploadUserId) ? (
{(!managed && (!uploadPostKey || !uploadUserId)) ? (
<div className="glass-panel p-6 space-y-3">
<div className="flex items-center gap-2 text-amber-400">
<AlertCircle size={16} />

View file

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

View file

@ -0,0 +1,25 @@
import React from 'react';
import { Sparkles, ArrowRight } from 'lucide-react';
// Slim, non-blocking banner shown above a tool when a hosted user has no active
// plan/trial. The tool stays visible below; actions still route to pricing.
export default function TrialGate({ toolName = 'this' }) {
return (
<div className="mx-6 mt-3 p-3 bg-primary/10 border border-primary/30 rounded-xl flex items-center justify-between gap-4 shrink-0 animate-[fadeIn_0.3s_ease-out]">
<div className="flex items-center gap-3 text-sm">
<Sparkles size={16} className="shrink-0 text-primary" />
<div className="text-primary/90">
<span className="font-semibold text-white">Preview mode.</span>{' '}
Start your <span className="font-semibold text-white">3-day free trial</span> to generate with {toolName} —
no API keys, from $12/mo. <span className="text-zinc-400">Or run it free by self-hosting.</span>
</div>
</div>
<button
onClick={() => { window.location.hash = '#/pricing'; }}
className="shrink-0 inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-lg bg-primary hover:bg-blue-600 text-white transition-colors"
>
See plans <ArrowRight size={14} />
</button>
</div>
);
}

View file

@ -0,0 +1,93 @@
import React, { useState, useEffect } from 'react';
import { X, Loader2, Rocket, CheckCircle2 } from 'lucide-react';
import { apiJson } from '../lib/api';
// Shown when a TRIALING user hits the trial minute cap. Lets them end the trial
// and activate the paid plan right away (charges the card now, unlocks the full
// monthly minutes). The subscription webhook flips status→active server-side.
export default function TrialUpgradeModal({ plan, onActivated, onClose }) {
const [busy, setBusy] = useState(false);
const [done, setDone] = useState(false);
const [error, setError] = useState('');
const [planMinutes, setPlanMinutes] = useState(null);
// Look up the full monthly minutes for the current plan (to show what unlocks).
useEffect(() => {
apiJson('/api/billing/plans')
.then((d) => {
const match = (d.plans || []).find((p) => p.plan === plan && p.interval === 'month');
if (match) setPlanMinutes(match.minutes);
})
.catch(() => {});
}, [plan]);
const activate = async () => {
setBusy(true);
setError('');
try {
const res = await apiJson('/api/billing/end-trial', { method: 'POST' });
// Poll /api/me until the webhook flips the subscription to active.
let ok = res?.status === 'active';
for (let i = 0; i < 10 && !ok; i++) {
await new Promise((r) => setTimeout(r, 1500));
const me = await onActivated();
ok = me?.status === 'active';
}
if (ok) {
setDone(true);
setTimeout(onClose, 1800);
} else {
// Charge is processing (or card needs attention) — let them proceed anyway.
await onActivated();
setError('Almost there — your plan is activating. If it doesn\'t unlock in a minute, check your billing details.');
}
} catch (e) {
setError('Could not activate your plan. Please try again or manage billing from your account.');
} finally {
setBusy(false);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4">
<div className="bg-surface border border-white/10 rounded-2xl p-8 w-full max-w-md relative">
<button onClick={onClose} className="absolute right-4 top-4 text-zinc-400 hover:text-white"><X size={20} /></button>
{done ? (
<div className="text-center py-4">
<div className="inline-flex p-3 bg-green-500/20 rounded-full text-green-400 mb-4"><CheckCircle2 size={24} /></div>
<h2 className="text-xl font-bold mb-1">You're all set 🎉</h2>
<p className="text-zinc-400 text-sm">Your plan is active{planMinutes ? ` with ${planMinutes} minutes` : ''}. Go ahead and generate your clips.</p>
</div>
) : (
<>
<div className="inline-flex p-3 bg-primary/20 rounded-full text-primary mb-4"><Rocket size={24} /></div>
<h2 className="text-xl font-bold mb-1">You've used your free trial minutes</h2>
<p className="text-zinc-400 text-sm mb-6">
Activate your{plan ? <> <span className="capitalize font-semibold text-white">{plan}</span></> : ''} plan now to unlock{' '}
{planMinutes ? <><b className="text-white">{planMinutes} minutes</b> every month</> : 'your full monthly minutes'} and keep creating.
Your card is charged today and your 3-day trial ends now.
</p>
{error && <p className="text-amber-400 text-xs mb-4">{error}</p>}
<button
onClick={activate}
disabled={busy}
className="w-full btn-primary py-3 flex items-center justify-center gap-2 disabled:opacity-60"
>
{busy ? <><Loader2 size={18} className="animate-spin" /> Activating…</> : <>Activate my plan now</>}
</button>
<button
onClick={onClose}
disabled={busy}
className="w-full mt-2 text-zinc-400 hover:text-white text-sm py-2 disabled:opacity-60"
>
Maybe later
</button>
</>
)}
</div>
</div>
);
}

View file

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

View file

@ -0,0 +1,135 @@
// 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);
let destination = '#app';
try {
if (kind === 'callback') {
const token = params.get('token');
if (token) {
setToken(token);
// Scrub the token from the URL immediately (replaceState, no new
// history entry) so the bearer token isn't left reachable via Back.
try {
window.history.replaceState(null, document.title,
window.location.pathname + window.location.search);
} catch (_) { /* ignore */ }
}
} 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);
}
}
const signedInMe = await refreshMe();
// New sign-ups (and anyone without an active plan/trial) go straight to
// pricing so they can start their free trial; entitled users land in the app.
if (signedInMe?.user && !signedInMe?.entitled) destination = '#/pricing';
} catch (e) {
// fall through — user lands signed-out
} finally {
setSigningIn(false);
// Clear the sensitive hash, land wherever we resolved above.
window.location.hash = destination;
}
return true;
}, [refreshMe]);
useEffect(() => {
(async () => {
try {
const cfg = await (await fetch(getApiUrl('/api/config'))).json();
setConfig(cfg);
if (cfg.billingEnabled) {
const handled = await handleAuthHash();
if (!handled) await refreshMe();
}
} catch (_) { /* config fetch failed — stay in BYOK */ }
setLoading(false);
})();
}, [handleAuthHash, refreshMe]);
const requestMagicLink = useCallback(async (email) => {
const res = await apiFetch('/api/auth/magic-link', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email }),
});
if (res.status === 429) throw new Error('Too many attempts. Try again in a few minutes.');
if (!res.ok) throw new Error('Could not send sign-in link.');
return true;
}, []);
const loginWithGoogle = useCallback(() => {
window.location.href = getApiUrl('/api/auth/google');
}, []);
const logout = useCallback(() => {
clearToken();
setMe(null);
}, []);
const value = {
billingEnabled: config.billingEnabled,
googleAuthEnabled: config.googleAuthEnabled,
loading,
signingIn,
user: me?.user || null,
me,
plan: me?.plan || null,
entitled: !!me?.entitled,
minutes: me?.minutes || null,
isSignedIn: !!me?.user,
// Managed = signed-in AND entitled (active plan or top-up credit).
isManaged: !!(config.billingEnabled && me?.entitled),
refreshMe,
requestMagicLink,
loginWithGoogle,
logout,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

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

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

View file

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

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

@ -0,0 +1,56 @@
# 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
# Fail the deploy loudly if unset, rather than silently using a weak default.
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set for cloud mode}
- 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:?POSTGRES_PASSWORD must be set for cloud mode}@db:5432/openshorts
- JWT_SECRET=${JWT_SECRET}
- FRONTEND_URL=${FRONTEND_URL:-https://openshorts.app}
- ALLOWED_ORIGINS=${ALLOWED_ORIGINS:-https://openshorts.app}
# Email (magic link + admin alerts) is via SMTP and read from the mounted
# .env (SMTP_HOST/PORT/USER/PASSWORD, EMAIL_FROM, ADMIN_EMAIL). It's kept
# out of this list on purpose so the SMTP password's $/* aren't mangled by
# compose/shell variable substitution.
# 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:-}
# 720p/1080p: the bgutil PO-token provider is baked into the backend image
# (script mode, BGUTIL_SCRIPT_PATH). No sidecar or BGUTIL_BASE_URL needed.
volumes:
pgdata:

View file

@ -0,0 +1,19 @@
# 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"
environment:
# Point auth/magic-link/CORS at the local frontend instead of openshorts.app.
- FRONTEND_URL=http://localhost:5176
- ALLOWED_ORIGINS=http://localhost:5176,http://localhost:5175,http://localhost:8001
frontend:
ports: !override
- "5176:5173"
environment:
# Call the backend directly (not via the Vite proxy) so Google OAuth builds
# a redirect_uri of http://localhost:8001/... which matches the registered
# client. Cross-origin API calls are allowed by ALLOWED_ORIGINS above.
- VITE_API_URL=http://localhost:8001

View file

@ -11,7 +11,9 @@ services:
restart: unless-stopped
frontend:
build: ./dashboard
build:
context: ./dashboard
target: dev
container_name: openshorts-frontend
ports:
- "5175:5173"

182
main.py
View file

@ -451,6 +451,11 @@ def download_youtube_video(url, output_dir="."):
Downloads a YouTube video using yt-dlp.
Returns the path to the downloaded video and the video title.
"""
# SSRF guard: block non-http(s) schemes and private/loopback/metadata hosts
# before handing the URL to yt-dlp.
from security_utils import assert_public_url
assert_public_url(url)
print(f"🔍 Debug: yt-dlp version: {yt_dlp.version.__version__}")
print("📥 Downloading video from YouTube...")
step_start_time = time.time()
@ -474,105 +479,114 @@ def download_youtube_video(url, output_dir="."):
cookies_path = None
print("⚠️ YOUTUBE_COOKIES env var not found.")
# 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.
_COMMON_YDL_OPTS = {
'quiet': False,
'verbose': True,
'no_warnings': False,
'cookiefile': cookies_path if cookies_path else None,
'socket_timeout': 30,
'retries': 10,
'fragment_retries': 10,
'nocheckcertificate': True,
'cachedir': False,
'extractor_args': {
'youtube': {
'player_client': ['tv_embed', 'android', 'mweb', 'web'],
'player_skip': ['webpage', 'configs'],
}
},
'http_headers': {
'User-Agent': (
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/120.0.0.0 Safari/537.36'
),
},
# 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.")
# Two download strategies, tried in order so a break in the HD path degrades
# gracefully instead of failing the whole job:
# 1) HD — yt-dlp default clients + the bgutil PO-token provider
# (BGUTIL_BASE_URL, needs the sidecar + Deno + recent yt-dlp) → 720p/1080p.
# 2) Fallback — conservative tv_embed/android clients, no PO provider (~360p),
# which is also the ONLY strategy for self-host (no bgutil configured).
# PO-token provider: HTTP mode (external BGUTIL_BASE_URL) or the baked-in
# local Node script (BGUTIL_SCRIPT_PATH, set in the image). Either enables HD.
_bgutil_http = os.environ.get("BGUTIL_BASE_URL", "").strip()
_bgutil_script = os.environ.get("BGUTIL_SCRIPT_PATH", "").strip()
if _bgutil_http:
hd_args = {'youtubepot-bgutilhttp': {'base_url': [_bgutil_http]}}
elif _bgutil_script:
hd_args = {'youtubepot-bgutilscript': {'script_path': [_bgutil_script]}}
else:
hd_args = None
fallback_args = {
'youtube': {
'player_client': ['tv_embed', 'android', 'mweb', 'web'],
'player_skip': ['webpage', 'configs'],
}
}
with yt_dlp.YoutubeDL(_COMMON_YDL_OPTS) as ydl:
try:
# Cap at 720p when using a paid proxy (bandwidth cost); direct keeps best.
if _proxy:
hd_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:
hd_fmt = 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best'
fallback_fmt = 'best[ext=mp4]/best'
def _base_opts(extractor_args):
return {
'quiet': False, 'verbose': True, 'no_warnings': False,
'cookiefile': cookies_path if cookies_path else None,
'proxy': _proxy, 'socket_timeout': 30, 'retries': 10, 'fragment_retries': 10,
'nocheckcertificate': True, 'cachedir': False,
'extractor_args': extractor_args,
'http_headers': {
'User-Agent': (
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
),
},
}
def _attempt(extractor_args, fmt):
with yt_dlp.YoutubeDL(_base_opts(extractor_args)) as ydl:
info = ydl.extract_info(url, download=False)
video_title = info.get('title', 'youtube_video')
sanitized_title = sanitize_filename(video_title)
sanitized = sanitize_filename(info.get('title', 'youtube_video'))
expected = os.path.join(output_dir, f'{sanitized}.mp4')
if os.path.exists(expected):
os.remove(expected)
dl_opts = {
**_base_opts(extractor_args),
'format': fmt,
'outtmpl': os.path.join(output_dir, f'{sanitized}.%(ext)s'),
'merge_output_format': 'mp4', 'overwrites': True,
}
with yt_dlp.YoutubeDL(dl_opts) as ydl:
ydl.download([url])
return sanitized
attempts = ([('HD', hd_args, hd_fmt)] if hd_args else []) + [('fallback', fallback_args, fallback_fmt)]
sanitized_title = None
last_err = None
for label, ea, fmt in attempts:
try:
print(f"📥 Download attempt: {label}")
sanitized_title = _attempt(ea, fmt)
print(f"✅ Download succeeded ({label}).")
break
except Exception as e:
# Force print to stderr/stdout immediately so it's captured before crash
import sys
import traceback
# Print minimal error first to ensure something gets out
print("🚨 YOUTUBE DOWNLOAD ERROR 🚨", file=sys.stderr)
error_msg = f"""
last_err = e
print(f"⚠️ Download attempt '{label}' failed: {str(e)[:200]}")
if sanitized_title is None:
import sys
error_msg = f"""
❌ ================================================================= ❌
❌ FATAL ERROR: YOUTUBE DOWNLOAD FAILED
❌ FATAL ERROR: YOUTUBE DOWNLOAD FAILED (all strategies)
❌ ================================================================= ❌
REASON: YouTube has blocked the download request (Error 429/Unavailable).
This is likely a temporary IP ban on this server.
👇 SOLUTION FOR USER 👇
---------------------------------------------------------------------
1. Download the video manually to your computer.
2. Use the 'Upload Video' tab in this app to process it.
---------------------------------------------------------------------
Technical Details: {str(e)}
"""
# Print to both streams to ensure capture
print(error_msg, file=sys.stdout)
print(error_msg, file=sys.stderr)
# Force flush
sys.stdout.flush()
sys.stderr.flush()
# Wait a split second to allow buffer to drain before raising
time.sleep(0.5)
raise e
output_template = os.path.join(output_dir, f'{sanitized_title}.%(ext)s')
expected_file = os.path.join(output_dir, f'{sanitized_title}.mp4')
if os.path.exists(expected_file):
os.remove(expected_file)
print(f"🗑️ Removed existing file to re-download with H.264 codec")
ydl_opts = {
**_COMMON_YDL_OPTS,
'format': 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best',
'outtmpl': output_template,
'merge_output_format': 'mp4',
'overwrites': True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
REASON: YouTube blocked the request or the download tooling is out of date.
👇 SOLUTION FOR USER: download the video manually and use the 'Upload Video' tab.
Technical Details: {str(last_err)}
"""
print(error_msg, file=sys.stdout)
print(error_msg, file=sys.stderr)
sys.stdout.flush(); sys.stderr.flush()
time.sleep(0.5)
raise last_err
downloaded_file = os.path.join(output_dir, f'{sanitized_title}.mp4')
if not os.path.exists(downloaded_file):
for f in os.listdir(output_dir):
if f.startswith(sanitized_title) and f.endswith('.mp4'):
downloaded_file = os.path.join(output_dir, f)
break
step_end_time = time.time()
print(f"✅ Video downloaded in {step_end_time - step_start_time:.2f}s: {downloaded_file}")
print(f"✅ Video downloaded in {time.time() - step_start_time:.2f}s: {downloaded_file}")
return downloaded_file, sanitized_title
def process_video_to_vertical(input_video, final_output_video):

11
requirements-billing.txt Normal file
View file

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

View file

@ -150,15 +150,25 @@ Be thorough. Use REAL data from your search results, not made-up information."""
def scrape_website(url: str) -> dict:
"""Scrape a SaaS website to extract key content for analysis."""
from bs4 import BeautifulSoup
from security_utils import assert_public_url
# SSRF guard: reject non-http(s) / private / metadata hosts, and re-validate
# every redirect hop so a public URL can't 30x-bounce us to an internal host.
current = assert_public_url(url)
print(f"[SaaSShorts] 🌐 Scraping {url}...")
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
with httpx.Client(timeout=30.0, follow_redirects=True) as client:
response = client.get(url, headers=headers)
with httpx.Client(timeout=30.0, follow_redirects=False) as client:
response = None
for _ in range(5):
response = client.get(current, headers=headers)
if response.has_redirect_location:
current = assert_public_url(str(response.next_request.url))
continue
break
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
@ -211,9 +221,19 @@ def scrape_website(url: str) -> dict:
for sub_url in list(subpages)[:3]:
try:
print(f"[SaaSShorts] → Subpage: {sub_url}")
with httpx.Client(timeout=20.0, follow_redirects=True) as client:
resp = client.get(sub_url, headers=headers)
if resp.status_code == 200:
# Same SSRF guard as the main page: no auto-redirects and re-validate
# every hop, so a same-host page can't 30x-bounce us onto an internal
# host (e.g. 169.254.169.254 cloud metadata).
sub_current = assert_public_url(sub_url)
with httpx.Client(timeout=20.0, follow_redirects=False) as client:
resp = None
for _ in range(5):
resp = client.get(sub_current, headers=headers)
if resp.has_redirect_location:
sub_current = assert_public_url(str(resp.next_request.url))
continue
break
if resp is not None and resp.status_code == 200:
sub_soup = BeautifulSoup(resp.text, "html.parser")
for tag in sub_soup(["script", "style", "nav", "footer", "header", "noscript"]):
tag.decompose()

76
security_utils.py Normal file
View file

@ -0,0 +1,76 @@
"""Small, dependency-free SSRF guards shared by the download / scrape paths.
The app fetches user-supplied URLs server-side (yt-dlp downloads, SaaS landing
page scraping, actor-image download). Without a guard, a caller can point those
at internal services or the cloud metadata endpoint (169.254.169.254) to read
instance credentials. ``assert_public_url`` rejects non-HTTP(S) schemes and any
host that resolves to a private / loopback / link-local / reserved address.
"""
from __future__ import annotations
import ipaddress
import socket
from urllib.parse import urlparse
class UnsafeURLError(ValueError):
"""Raised when a URL is not safe to fetch server-side."""
def _ip_is_public(ip: str) -> bool:
try:
addr = ipaddress.ip_address(ip)
except ValueError:
return False
return not (
addr.is_private
or addr.is_loopback
or addr.is_link_local
or addr.is_reserved
or addr.is_multicast
or addr.is_unspecified
)
def assert_public_url(url: str) -> str:
"""Return ``url`` if it is safe to fetch, else raise ``UnsafeURLError``.
Blocks non-http(s) schemes and hosts that resolve to any non-public IP.
Resolves every A/AAAA record so a hostname that maps to a private range
(or to 169.254.169.254) is rejected rather than silently fetched.
"""
if not url or not isinstance(url, str):
raise UnsafeURLError("Empty URL")
parsed = urlparse(url.strip())
if parsed.scheme.lower() not in ("http", "https"):
raise UnsafeURLError(f"Unsupported URL scheme: {parsed.scheme!r}")
host = parsed.hostname
if not host:
raise UnsafeURLError("URL has no host")
# If the host is a literal IP, validate it directly (no DNS).
try:
ipaddress.ip_address(host)
is_ip_literal = True
except ValueError:
is_ip_literal = False
if is_ip_literal:
if not _ip_is_public(host):
raise UnsafeURLError(f"URL host is not a public address: {host}")
return url
try:
infos = socket.getaddrinfo(host, parsed.port or None, proto=socket.IPPROTO_TCP)
except socket.gaierror as e:
raise UnsafeURLError(f"Could not resolve host {host!r}: {e}")
resolved = {info[4][0] for info in infos}
if not resolved:
raise UnsafeURLError(f"Host {host!r} did not resolve")
for ip in resolved:
if not _ip_is_public(ip):
raise UnsafeURLError(f"Host {host!r} resolves to a non-public address: {ip}")
return url

View file

@ -155,6 +155,13 @@ def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16,
- Outline mode (bg_opacity=0): Text with colored outline/border
- Box mode (bg_opacity>0): Text with semi-transparent background box
"""
# Sanitize the client-supplied font name before it goes into the FFmpeg
# force_style string. A quote/comma/colon/backslash would break out of the
# quoted style and inject extra libavfilter directives (filtergraph
# injection / DoS). Keep only safe font-name characters.
import re as _re
font_name = _re.sub(r"[^A-Za-z0-9 _\-]", "", str(font_name))[:64].strip() or "Verdana"
# Position mapping
ass_alignment = 2
align_lower = str(alignment).lower()